207 lines
6.0 KiB
TypeScript
207 lines
6.0 KiB
TypeScript
import { CHAT_CONFIG } from '../config/chat';
|
|
|
|
// 获取环境变量的服务端函数
|
|
const getServerEnvVar = (name: string, defaultValue: string = '') => {
|
|
return process.env[name] || defaultValue;
|
|
};
|
|
|
|
// Dify API 客户端配置
|
|
const DIFY_CONFIG = {
|
|
API_URL: getServerEnvVar('NEXT_PUBLIC_API_URL', 'https://api.dify.ai/v1'),
|
|
API_KEY: getServerEnvVar('NEXT_PUBLIC_APP_KEY', ''),
|
|
APP_ID: (() => {
|
|
const rawAppId = getServerEnvVar('NEXT_PUBLIC_APP_ID', '');
|
|
// 从完整URL中提取APP ID
|
|
const match = rawAppId.match(/\/app\/([a-f0-9-]{36})/);
|
|
return match ? match[1] : rawAppId;
|
|
})(),
|
|
};
|
|
|
|
// console.log('🔧 Dify Client Config:', {
|
|
// apiUrl: DIFY_CONFIG.API_URL,
|
|
// appId: DIFY_CONFIG.APP_ID,
|
|
// hasApiKey: !!DIFY_CONFIG.API_KEY
|
|
// });
|
|
|
|
// 基础请求函数
|
|
const difyFetch = async (endpoint: string, options: RequestInit = {}) => {
|
|
const url = `${DIFY_CONFIG.API_URL}/${endpoint.replace(/^\//, '')}`;
|
|
|
|
const headers = {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': `Bearer ${DIFY_CONFIG.API_KEY}`,
|
|
...options.headers,
|
|
};
|
|
|
|
// console.log('🌐 Dify API Request:', {
|
|
// url,
|
|
// method: options.method || 'GET',
|
|
// hasAuth: !!DIFY_CONFIG.API_KEY
|
|
// });
|
|
|
|
const response = await fetch(url, {
|
|
...options,
|
|
headers,
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
console.error('❌ Dify API Error:', {
|
|
status: response.status,
|
|
statusText: response.statusText,
|
|
error: errorText
|
|
});
|
|
throw new Error(`Dify API Error: ${response.status} ${response.statusText}`);
|
|
}
|
|
|
|
return response;
|
|
};
|
|
|
|
// 生成用户ID
|
|
const generateUserId = (sessionId: string) => {
|
|
return `user_${DIFY_CONFIG.APP_ID}:${sessionId}`;
|
|
};
|
|
|
|
// Dify API 客户端
|
|
export const difyClient = {
|
|
// 获取应用参数
|
|
async getApplicationParameters(user: string) {
|
|
const response = await difyFetch('parameters', {
|
|
method: 'GET',
|
|
headers: {
|
|
'Authorization': `Bearer ${DIFY_CONFIG.API_KEY}`,
|
|
},
|
|
});
|
|
return response.json();
|
|
},
|
|
|
|
// 获取会话列表
|
|
async getConversations(user: string) {
|
|
const params = new URLSearchParams({
|
|
user,
|
|
limit: '100',
|
|
first_id: '',
|
|
});
|
|
|
|
const response = await difyFetch(`conversations?${params}`, {
|
|
method: 'GET',
|
|
});
|
|
return response.json();
|
|
},
|
|
|
|
// 获取会话消息
|
|
async getConversationMessages(user: string, conversationId: string) {
|
|
const params = new URLSearchParams({
|
|
user,
|
|
conversation_id: conversationId,
|
|
limit: '20',
|
|
last_id: '',
|
|
});
|
|
|
|
const response = await difyFetch(`messages?${params}`, {
|
|
method: 'GET',
|
|
});
|
|
return response.json();
|
|
},
|
|
|
|
// 发送聊天消息
|
|
async createChatMessage(
|
|
inputs: Record<string, any>,
|
|
query: string,
|
|
user: string,
|
|
responseMode: string = 'streaming',
|
|
conversationId?: string,
|
|
files?: any[]
|
|
) {
|
|
const body = {
|
|
inputs,
|
|
query,
|
|
user,
|
|
response_mode: responseMode,
|
|
conversation_id: conversationId,
|
|
files: files || [],
|
|
};
|
|
|
|
console.log('🌐 [DifyClient] 发送聊天消息:', {
|
|
queryLength: query.length,
|
|
queryPreview: query.substring(0, 100) + (query.length > 100 ? '...' : ''),
|
|
user,
|
|
responseMode,
|
|
conversationId,
|
|
hasInputs: !!inputs && Object.keys(inputs).length > 0,
|
|
inputsKeys: inputs ? Object.keys(inputs) : [],
|
|
hasFiles: !!files && files.length > 0,
|
|
filesCount: files?.length || 0
|
|
});
|
|
|
|
const response = await difyFetch('chat-messages', {
|
|
method: 'POST',
|
|
body: JSON.stringify(body),
|
|
});
|
|
|
|
console.log('📡 [DifyClient] Dify API响应:', {
|
|
status: response.status,
|
|
statusText: response.statusText,
|
|
hasBody: !!response.body,
|
|
contentType: response.headers.get('Content-Type'),
|
|
responseMode
|
|
});
|
|
|
|
// 对于流式响应,直接返回Response对象
|
|
if (responseMode === 'streaming') {
|
|
console.log('🌊 [DifyClient] 返回流式响应对象');
|
|
return response;
|
|
}
|
|
|
|
console.log('📄 [DifyClient] 解析JSON响应');
|
|
return response.json();
|
|
},
|
|
|
|
// 重命名会话
|
|
async renameConversation(conversationId: string, name: string, user: string, autoGenerate: boolean = false) {
|
|
const body = {
|
|
name,
|
|
auto_generate: autoGenerate,
|
|
user,
|
|
};
|
|
|
|
const response = await difyFetch(`conversations/${conversationId}/name`, {
|
|
method: 'POST',
|
|
body: JSON.stringify(body),
|
|
});
|
|
return response.json();
|
|
},
|
|
|
|
// 删除会话
|
|
async deleteConversation(conversationId: string, user: string) {
|
|
const body = {
|
|
user,
|
|
};
|
|
|
|
const response = await difyFetch(`conversations/${conversationId}`, {
|
|
method: 'DELETE',
|
|
body: JSON.stringify(body),
|
|
});
|
|
return response.json();
|
|
},
|
|
|
|
// 更新消息反馈
|
|
async updateMessageFeedback(messageId: string, rating: 'like' | 'dislike' | null, user: string) {
|
|
const body = {
|
|
rating,
|
|
user,
|
|
};
|
|
|
|
const response = await difyFetch(`messages/${messageId}/feedbacks`, {
|
|
method: 'POST',
|
|
body: JSON.stringify(body),
|
|
});
|
|
return response.json();
|
|
},
|
|
};
|
|
|
|
// 工具函数
|
|
export const difyUtils = {
|
|
generateUserId,
|
|
getConfig: () => DIFY_CONFIG,
|
|
};
|