-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
394 lines (340 loc) · 11.8 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import axios from 'axios';
dotenv.config();
const app = express();
const port = process.env.PORT || 3000;
// Configure logging
const LOG_LEVELS = {
error: 0,
warn: 1,
info: 2,
debug: 3
};
const currentLogLevel = LOG_LEVELS[process.env.LOG_LEVEL?.toLowerCase()] ?? LOG_LEVELS.info;
function log(level, ...args) {
if (LOG_LEVELS[level] <= currentLogLevel) {
const timestamp = new Date().toISOString();
console[level === 'debug' ? 'log' : level](`[${timestamp}] [${level.toUpperCase()}]`, ...args);
}
}
// Store conversation IDs in memory
const conversationStore = new Map();
app.use(cors());
app.use(express.json());
// Validate required environment variables
if (!process.env.DIFY_API_URL || !process.env.DIFY_API_KEY) {
log('error', 'DIFY_API_URL and DIFY_API_KEY environment variables are required');
process.exit(1);
}
// Configure Dify API client
const difyClient = axios.create({
baseURL: process.env.DIFY_API_URL,
headers: {
'Authorization': `Bearer ${process.env.DIFY_API_KEY}`,
'Content-Type': 'application/json',
},
timeout: 30000, // 30 second timeout
});
// Helper function to convert OpenAI messages to Dify query
function convertOpenAIToDifyFormat(messages, conversationKey, user = 'default-user') {
// Create a copy of messages to avoid modifying the original array
const messagesCopy = [...messages];
// Get the last user message without modifying the array
const lastUserMessage = messagesCopy.reverse().find(msg => msg.role === 'user');
if (!lastUserMessage) {
throw new Error('No user message found');
}
// Try to get existing conversation ID from store
let conversationId = conversationStore.get(conversationKey) || '';
// Debug log conversation ID extraction
log('debug', 'Conversation ID Extraction:', {
found: !!conversationId,
value: conversationId,
messageCount: messages.length,
messageFormats: messages.map(msg => ({
hasDirectId: !!msg.conversation_id,
hasChoices: !!msg.choices,
hasMessage: !!msg.message,
hasDelta: !!msg.delta
}))
});
// Debug log conversion
log('debug', 'OpenAI -> Dify Conversion:', {
messageCount: messages.length,
conversationId,
lastUserMessage: lastUserMessage.content,
allMessages: messages.map(m => ({
role: m.role,
content: m.content,
id: m.message_id || m.id
}))
});
// Format messages for conversation history
const history = [];
// Filter out system messages and process the rest chronologically
const nonSystemMessages = messages.filter(msg => msg.role !== 'system');
for (const msg of nonSystemMessages) {
// Extract content and IDs, handling various message formats
const content = msg.content ||
msg.message?.content ||
msg.delta?.content ||
'';
const messageId = msg.message_id ||
msg.id ||
msg.message?.id ||
msg.message?.message_id;
// If this is an assistant message, try to get conversation ID from various locations
let msgConversationId = '';
if (msg.role === 'assistant') {
msgConversationId = msg.conversation_id ||
msg.message?.conversation_id ||
msg.delta?.conversation_id ||
(msg.choices && msg.choices[0]?.message?.conversation_id) ||
(msg.choices && msg.choices[0]?.delta?.conversation_id) ||
'';
// If we found a conversation ID in an assistant message, use it
if (msgConversationId) {
conversationId = msgConversationId;
}
}
history.push({
role: msg.role,
content: content,
message_id: messageId,
...(msgConversationId ? { conversation_id: msgConversationId } : {})
});
}
// Format request for Dify
const request = {
query: lastUserMessage.content,
conversation_id: conversationId,
user,
inputs: {},
response_mode: 'streaming',
conversation_history: history
};
// Add conversation ID to history items if we have one
if (conversationId) {
request.conversation_history = history.map(msg => ({
...msg,
conversation_id: msg.conversation_id || conversationId
}));
}
// Debug log conversation history
log('debug', 'Conversation History:', {
history: history.map(msg => ({
role: msg.role,
content: msg.content,
message_id: msg.message_id
})),
request: {
query: request.query,
conversation_id: request.conversation_id,
user: request.user,
history_length: request.conversation_history.length
}
});
return request;
}
// Helper function to convert Dify streaming response to OpenAI format
function convertDifyToOpenAIStreamFormat(difyChunk, conversationKey) {
// Clean up the chunk by removing 'data: ' prefix and handling any newlines
const cleanChunk = difyChunk.replace('data: ', '').trim();
if (!cleanChunk) return null;
try {
// Fix JSON format by adding missing commas between properties
const fixedJson = cleanChunk.replace(/"\s+"(?!\})/g, '", "');
const data = JSON.parse(fixedJson);
if (data.event === 'message') {
// Debug log message event
log('debug', 'Dify -> OpenAI Message:', {
messageId: data.message_id,
conversationId: data.conversation_id,
answer: data.answer,
event: data.event,
metadata: data.metadata
});
const response = {
id: data.message_id || data.id,
object: 'chat.completion.chunk',
created: Math.floor(Date.now() / 1000),
model: 'gpt-3.5-turbo',
choices: [{
index: 0,
delta: {
role: 'assistant',
content: data.answer
},
finish_reason: null
}]
};
// Store conversation ID when we get it from Dify
if (data.conversation_id) {
conversationStore.set(conversationKey, data.conversation_id);
response.conversation_id = data.conversation_id;
response.choices[0].delta.conversation_id = data.conversation_id;
}
return response;
} else if (data.event === 'message_end') {
// Debug log message end event
log('debug', 'Dify -> OpenAI End:', {
messageId: data.id,
conversationId: data.conversation_id,
metadata: data.metadata,
usage: data.metadata?.usage
});
const response = {
id: data.message_id || data.id,
object: 'chat.completion.chunk',
created: Math.floor(Date.now() / 1000),
model: 'gpt-3.5-turbo',
choices: [{
index: 0,
delta: {
role: 'assistant'
},
finish_reason: 'stop'
}]
};
// Store conversation ID when we get it from Dify
if (data.conversation_id) {
conversationStore.set(conversationKey, data.conversation_id);
response.conversation_id = data.conversation_id;
response.choices[0].delta.conversation_id = data.conversation_id;
}
return response;
}
return null;
} catch (error) {
log('error', 'Error parsing Dify chunk:', error);
return null;
}
}
// Health check endpoint
app.get('/health', (req, res) => {
log('debug', 'Health check requested');
res.json({ status: 'ok' });
});
// OpenAI-compatible chat completions endpoint
app.post('/v1/chat/completions', async (req, res) => {
try {
const { messages, stream = false, user } = req.body;
if (!messages || !Array.isArray(messages)) {
log('warn', 'Invalid request format: messages must be an array');
return res.status(400).json({ error: 'Invalid messages format' });
}
// Use first message content as conversation key since it's stable across requests
const conversationKey = messages[0]?.content || '';
log('info', `Processing ${stream ? 'streaming' : 'non-streaming'} request`, {
messageCount: messages.length,
user: user || 'default-user'
});
const difyRequest = convertOpenAIToDifyFormat(messages, conversationKey, user);
if (stream) {
// Set up SSE headers
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
// Make streaming request to Dify
const response = await difyClient.post('/chat-messages', difyRequest, {
responseType: 'stream'
});
// Process the Dify stream
response.data.on('data', chunk => {
try {
const chunkStr = chunk.toString();
// Split multiple chunks that might be received together
const chunks = chunkStr.split('\n').filter(line => line.startsWith('data:'));
for (const chunk of chunks) {
const openAIFormat = convertDifyToOpenAIStreamFormat(chunk, conversationKey);
if (openAIFormat) {
const formattedResponse = `data: ${JSON.stringify(openAIFormat)}\n\n`;
res.write(formattedResponse);
}
}
} catch (error) {
log('error', 'Error processing chunk:', error);
// Continue processing next chunks even if one fails
}
});
response.data.on('error', error => {
log('error', 'Stream error:', error);
res.write('data: [DONE]\n\n');
res.end();
});
response.data.on('end', () => {
log('debug', 'Stream ended');
res.write('data: [DONE]\n\n');
res.end();
});
// Handle client disconnect
req.on('close', () => {
log('debug', 'Client disconnected');
response.data.destroy();
});
} else {
// Non-streaming request
difyRequest.response_mode = 'blocking';
const response = await difyClient.post('/chat-messages', difyRequest);
const openAIResponse = {
id: response.data.message_id || response.data.id,
object: 'chat.completion',
created: Math.floor(Date.now() / 1000),
model: 'gpt-3.5-turbo',
choices: [{
index: 0,
message: {
role: 'assistant',
content: response.data.answer
},
finish_reason: 'stop'
}],
usage: response.data.metadata?.usage || {
prompt_tokens: 0,
completion_tokens: 0,
total_tokens: 0
}
};
// Store and add conversation ID
if (response.data.conversation_id) {
conversationStore.set(conversationKey, response.data.conversation_id);
openAIResponse.conversation_id = response.data.conversation_id;
openAIResponse.choices[0].message.conversation_id = response.data.conversation_id;
}
log('debug', 'Non-streaming response:', {
messageId: openAIResponse.id,
conversationId: openAIResponse.conversation_id
});
res.json(openAIResponse);
}
} catch (error) {
log('error', 'Server error:', error);
if (axios.isAxiosError(error)) {
// Handle Dify API errors
const status = error.response?.status || 500;
const message = error.response?.data?.message || error.message;
res.status(status).json({
error: {
message: `Dify API error: ${message}`,
type: 'dify_api_error',
status
}
});
} else {
// Handle other errors
res.status(500).json({
error: {
message: 'An internal server error occurred.',
type: 'internal_server_error'
}
});
}
}
});
// Start the server
app.listen(port, () => {
log('info', `Dify2OpenAI middleware running on port ${port}`);
log('info', `Log level: ${process.env.LOG_LEVEL?.toLowerCase() || 'info'}`);
});