forked from fatwang2/coze2openai
-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
255 lines (241 loc) · 7.71 KB
/
app.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
import express from "express";
import bodyParser from "body-parser";
import dotenv from "dotenv";
import fetch from "node-fetch";
dotenv.config();
const app = express();
app.use(bodyParser.json());
const coze_api_base = process.env.COZE_API_BASE || "api.coze.com";
const default_bot_id = process.env.BOT_ID || "";
const botConfig = process.env.BOT_CONFIG ? JSON.parse(process.env.BOT_CONFIG) : {};
var corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers":
"DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization",
"Access-Control-Max-Age": "86400",
};
app.use((req, res, next) => {
res.set(corsHeaders);
if (req.method === 'OPTIONS') {
return res.status(204).end();
}
console.log('Request Method:', req.method);
console.log('Request Path:', req.path);
next();
});
app.get("/", (req, res) => {
res.send(`
<html>
<head>
<title>COZE2OPENAI</title>
</head>
<body>
<h1>Coze2OpenAI</h1>
<p>Congratulations! Your project has been successfully deployed.</p>
</body>
</html>
`);
});
app.post("/v1/chat/completions", async (req, res) => {
const authHeader =
req.headers["authorization"] || req.headers["Authorization"];
if (!authHeader) {
return res.status(401).json({
code: 401,
errmsg: "Unauthorized.",
});
} else {
const token = authHeader.split(" ")[1];
if (!token) {
return res.status(401).json({
code: 401,
errmsg: "Unauthorized.",
});
}
}
try {
const data = req.body;
const messages = data.messages;
const model = data.model;
const chatHistory = [];
for (let i = 0; i < messages.length - 1; i++) {
const message = messages[i];
const role = message.role;
const content = message.content;
chatHistory.push({
role: role,
content: content,
content_type: "text"
});
}
const lastMessage = messages[messages.length - 1];
const queryString = lastMessage.content;
const stream = data.stream !== undefined ? data.stream : false;
let requestBody;
const bot_id = model && botConfig[model] ? botConfig[model] : default_bot_id;
requestBody = {
query: queryString,
stream: stream,
conversation_id: "",
user: "apiuser",
bot_id: bot_id,
chat_history: chatHistory
};
const coze_api_url = `https://${coze_api_base}/open_api/v2/chat`;
const resp = await fetch(coze_api_url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${authHeader.split(" ")[1]}`,
},
body: JSON.stringify(requestBody),
});
if (stream) {
res.setHeader("Content-Type", "text/event-stream");
const stream = resp.body;
let buffer = "";
stream.on("data", (chunk) => {
buffer += chunk.toString();
let lines = buffer.split("\n");
for (let i = 0; i < lines.length - 1; i++) {
let line = lines[i].trim();
if (!line.startsWith("data:")) continue;
line = line.slice(5).trim();
let chunkObj;
try {
if (line.startsWith("{")) {
chunkObj = JSON.parse(line);
} else {
continue;
}
} catch (error) {
console.error("Error parsing chunk:", error);
continue;
}
if (chunkObj.event === "message") {
if (
chunkObj.message.role === "assistant" &&
chunkObj.message.type === "answer"
) {
let chunkContent = chunkObj.message.content;
if (chunkContent !== "") {
const chunkId = `chatcmpl-${Date.now()}`;
const chunkCreated = Math.floor(Date.now() / 1000);
res.write(
"data: " +
JSON.stringify({
id: chunkId,
object: "chat.completion.chunk",
created: chunkCreated,
model: data.model,
choices: [
{
index: 0,
delta: {
content: chunkContent,
},
finish_reason: null,
},
],
}) +
"\n\n"
);
}
}
} else if (chunkObj.event === "done") {
const chunkId = `chatcmpl-${Date.now()}`;
const chunkCreated = Math.floor(Date.now() / 1000);
res.write(
"data: " +
JSON.stringify({
id: chunkId,
object: "chat.completion.chunk",
created: chunkCreated,
model: data.model,
choices: [
{
index: 0,
delta: {},
finish_reason: "stop",
},
],
}) +
"\n\n"
);
res.write("data: [DONE]\n\n");
res.end();
} else if (chunkObj.event === "ping") {
} else if (chunkObj.event === "error") {
console.error(`Error: ${chunkObj.code}, ${chunkObj.message}`);
res
.status(500)
.write(
`data: ${JSON.stringify({ error: chunkObj.message })}\n\n`
);
res.write("data: [DONE]\n\n");
res.end();
}
}
buffer = lines[lines.length - 1];
});
} else {
resp
.json()
.then((data) => {
if (data.code === 0 && data.msg === "success") {
const messages = data.messages;
const answerMessage = messages.find(
(message) =>
message.role === "assistant" && message.type === "answer"
);
if (answerMessage) {
const result = answerMessage.content.trim();
const usageData = {
prompt_tokens: 100,
completion_tokens: 10,
total_tokens: 110,
};
const chunkId = `chatcmpl-${Date.now()}`;
const chunkCreated = Math.floor(Date.now() / 1000);
const formattedResponse = {
id: chunkId,
object: "chat.completion",
created: chunkCreated,
model: req.body.model,
choices: [
{
index: 0,
message: {
role: "assistant",
content: result,
},
logprobs: null,
finish_reason: "stop",
},
],
usage: usageData,
system_fingerprint: "fp_2f57f81c11",
};
const jsonResponse = JSON.stringify(formattedResponse, null, 2);
res.set("Content-Type", "application/json");
res.send(jsonResponse);
} else {
res.status(500).json({ error: "No answer message found." });
}
} else {
res
.status(500)
.json({ error: "Unexpected response from Coze API." });
}
})
.catch((error) => {
console.error("Error parsing JSON:", error);
res.status(500).json({ error: "Error parsing JSON response." });
});
}
} catch (error) {
console.error("Error:", error);
}
});
app.listen(process.env.PORT || 3000);