Spaces:
Paused
Paused
File size: 5,056 Bytes
93be000 3a88836 93be000 3a88836 93be000 db08733 93be000 db08733 93be000 db08733 93be000 db08733 93be000 db08733 93be000 db08733 93be000 3a88836 93be000 e8b4f0c 3a88836 db08733 93be000 a0eb55b 93be000 db08733 93be000 db08733 93be000 3a88836 93be000 3a88836 93be000 3a88836 93be000 3a88836 93be000 3a88836 93be000 3a88836 93be000 3a88836 93be000 3a88836 93be000 3a88836 93be000 3a88836 93be000 3a88836 93be000 314abaa |
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 |
const express = require('express');
const fetch = require('node-fetch');
const { v4: uuidv4 } = require('uuid');
const app = express();
require('dotenv').config();
const modelMapping = {
"gpt-4o-mini": "GPT-4o mini",
"claude-haiku": "Claude Haiku",
"llama-3": "Llama 3",
"gemini-1.5": "Gemini 1.5",
"gemini-flash": "Gemini Flash",
"command-r": "Command R"
};
app.use(express.json());
const getCurrentTimestamp = () => Math.floor(Date.now() / 1000);
const splitIntoChunks = (text, chunkSize) => {
const chunks = [];
for (let i = 0; i < text.length; i += chunkSize) {
chunks.push(text.slice(i, i + chunkSize));
}
return chunks;
};
const getTempUserID = async () => {
try {
const response = await fetch('https://playground.julius.ai/api/temp_user_id');
const data = await response.json();
return data.temp_user_id;
} catch (error) {
throw new Error('Failed to get temp user ID');
}
};
const sendToJulius = async (tempUserID, message, model) => {
const conversationID = uuidv4();
const juliusReq = {
message: {
content: message,
role: "user"
},
provider: "default",
chat_mode: "auto",
client_version: "20240130",
theme: "dark",
selectedModels: [model]
};
try {
const response = await fetch('https://playground.julius.ai/api/chat/message', {
method: 'POST',
headers: {
'is-demo': tempUserID,
'Content-Type': 'application/json',
'Platform': 'web',
'conversation-id': conversationID,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36'
},
body: JSON.stringify(juliusReq)
});
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let fullResponse = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
const lines = value.split('\n');
for (const line of lines) {
try {
const jsonResp = JSON.parse(line);
if (jsonResp.content) {
fullResponse += jsonResp.content;
}
} catch (e) {
// 忽略解析错误
}
}
}
return fullResponse;
} catch (error) {
throw new Error('Failed to send to Julius');
}
};
app.all('*', async (req, res) => {
// 身份验证
const authToken = process.env.AUTH_TOKEN;
if (authToken) {
const requestToken = req.headers.authorization?.replace('Bearer ', '');
if (!requestToken || requestToken !== authToken) {
return res.status(401).send('Access Denied');
}
}
// 健康检查
if (req.path !== '/v1/chat/completions') {
return res.json({
status: "Julius2Api Service Running...",
message: "MoLoveSze..."
});
}
if (req.method !== 'POST') {
return res.status(405).send('Method not allowed');
}
try {
const openAIReq = req.body;
const isStream = openAIReq.stream || false;
// 模型映射
const mappedModel = modelMapping[openAIReq.model] || 'GPT-4o mini';
openAIReq.model = mappedModel;
const tempUserID = await getTempUserID();
const juliusResp = await sendToJulius(tempUserID,
openAIReq.messages[openAIReq.messages.length - 1].content,
mappedModel
);
const respId = `chatcmpl-${tempUserID}`;
const created = getCurrentTimestamp();
if (isStream) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
// 发送初始响应
const firstResponse = {
id: respId,
object: "chat.completion.chunk",
created: created,
model: mappedModel,
choices: [{
delta: { role: "assistant" },
index: 0
}]
};
res.write(`data: ${JSON.stringify(firstResponse)}\n\n`);
// 分块发送内容
const chunks = splitIntoChunks(juliusResp, 50);
chunks.forEach((chunk, index) => {
const response = {
id: respId,
object: "chat.completion.chunk",
created: created,
model: mappedModel,
choices: [{
delta: { content: chunk },
index: 0,
finish_reason: index === chunks.length - 1 ? 'stop' : null
}]
};
res.write(`data: ${JSON.stringify(response)}\n\n`);
});
res.write('data: [DONE]\n\n');
res.end();
} else {
const response = {
id: respId,
object: "chat.completion",
created: created,
model: mappedModel,
choices: [{
message: {
role: "assistant",
content: juliusResp
},
finish_reason: "stop"
}]
};
res.json(response);
}
} catch (error) {
console.error(error);
res.status(500).send(error.message);
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
}); |