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
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
const WebSocket = require('ws');
const express = require('express');
const request = require('request');
const axios = require('axios');
const qs = require('qs');


// 创建一个 Express 应用实例
const app = express();

// 解析请求体
app.use(express.json({ limit: "50mb" }));
app.use(express.urlencoded({ limit: "50mb", extended: true }));

const PORT = 9877;
app.get("/", (req, res) => {
    res.send("欢迎来到Node.js Express应用!");
});


function uuidv4() {
    // 生成16个随机字节(128位)
    const bytes = new Uint8Array(16);
    for (let i = 0; i < 16; i++) {
        bytes[i] = Math.floor(Math.random() * 256);
    }

    // 按照 UUID v4 标准格式设置特定位
    bytes[6] = (bytes[6] & 0x0f) | 0x40; // 0100xxxx: version 4
    bytes[8] = (bytes[8] & 0x3f) | 0x80; // 10xxxxxx: variant

    // 转换成 8-4-4-4-12 的 hex 格式
    const hex = [...bytes].map(b => b.toString(16).padStart(2, '0'));

    return (
        hex.slice(0, 4).join('') + '-' +
        hex.slice(4, 6).join('') + '-' +
        hex.slice(6, 8).join('') + '-' +
        hex.slice(8, 10).join('') + '-' +
        hex.slice(10, 16).join('')
    );
}
async function fetchTokenDetails(authHeader) {
    const url = 'https://api.promptlayer.com/ws-token-request';
    const headers = { Authorization: "Bearer " + authHeader };

    const response = await axios.post(url, null, { headers });
    if (response.data.success) {
        const access_token = response.data.token_details.token;
        const clientId = response.data.token_details.clientId;
        return { access_token, clientId };
    } else {
        throw new Error('Failed to get token details');
    }
}

/**
 * 获取 workspace id
 */
async function fetchWorkspaceId(authHeader) {
    const url = 'https://api.promptlayer.com/workspaces';
    const headers = { Authorization: "Bearer " + authHeader };

    const response = await axios.get(url, { headers });
    if (response.data.success && response.data.workspaces.length > 0) {
        const workspaceId = response.data.workspaces[0].id;
        return { workspaceId };
    } else {
        throw new Error('Failed to get workspace id');
    }
}


function transformMessagesArray(messages) {
    if (!Array.isArray(messages)) {
        throw new Error("输入必须是一个数组");
    }

    return messages.map(msg => ({
        role: msg.role,
        content: [
            {
                type: "text",
                text: msg.content
            }
        ],
        tool_calls: [],
        template_format: "f-string"
    }));
}


// 刷新playseesion
async function pysession(authHeader, workspaceId, databody) {
    const url = 'https://api.promptlayer.com/api/dashboard/v2/workspaces/' + workspaceId + '/playground_sessions';
    const headers = { Authorization: "Bearer " + authHeader };
    let provider = "openai"
    let model = "gpt-4o"
    let parameters = {
        "temperature": 1,
        "seed": 0,
        "response_format": null,
        "top_p": 1,
        "frequency_penalty": 0,
        "presence_penalty": 0
    }
    if (databody.model.includes("claude") && (databody.model.includes("3.7") || databody.model.includes("3-7"))) {
        provider = "anthropic"
        model = "claude-3-7-sonnet-latest"
        parameters = {
            "max_tokens": 64000,
            "temperature": 1
        }
    }
    if (databody.model.includes("claude") && (databody.model.includes("3.5") || databody.model.includes("3-5"))) {
        provider = "anthropic"
        model = "claude-3-5-sonnet-latest"
        parameters = {
            "max_tokens": 256,
            "temperature": 1,
            "top_k": 0,
            "top_p": 0
        }
    }
    if (databody.model.includes("4.1")) {
        model = "gpt-4.1"
    }

    if (databody.model.includes("4.5") || databody.model.includes("4-5")) {
        model = "gpt-4.5-preview"
    }
    if (databody.model == "gpt-4o-search-preview") {
        model = "gpt-4o-search-preview"
        parameters = {
            "response_format": null,
            "web_search_options": {
                "search_context_size": "medium",
                "user_location": {
                    "approximate": {
                        "city": "New York",
                        "country": "US",
                        "region": "New York",
                        "timezone": "America/New_York"
                    },
                    "type": "approximate"
                }
            }
        }
    }
    let data = {
        "id": uuidv4(),
        "name": "Not implemented",
        "prompt_blueprint": {
            "inference_client_name": null,
            "metadata": {
                "model": {
                    "name": model,
                    "provider": provider,
                    "parameters": parameters
                }
            },
            "prompt_template": {
                "type": "chat",
                "messages": transformMessagesArray(databody.messages),
                "tools": null,
                "input_variables": [],
                "functions": []
            },
            "provider_base_url_name": null
        },
        "input_variables": []
    }
    const response = await axios.put(url, data, { headers});
    if (response.data.success) {
        return response.data.playground_session.id;
    } else {
        return -1
    }
}


async function postmessage(authHeader, workspaceId, playground_sessions, databody) {
    const url = 'https://api.promptlayer.com/api/dashboard/v2/workspaces/' + workspaceId + '/run_groups';
    const headers = { Authorization: "Bearer " + authHeader };
    let provider = "openai"
    let model = "gpt-4o"
    let parameters = {
        "temperature": 1,
        "seed": 0,
        "response_format": null,
        "top_p": 1,
        "frequency_penalty": 0,
        "presence_penalty": 0
    }
    if (databody.model.includes("claude") && (databody.model.includes("3.7") || databody.model.includes("3-7"))) {
        provider = "anthropic"
        model = "claude-3-7-sonnet-latest"
        parameters = {
            "max_tokens": 64000,
            "temperature": 1
        }
    }
    if (databody.model.includes("claude") && (databody.model.includes("3.5") || databody.model.includes("3-5"))) {
        provider = "anthropic"
        model = "claude-3-5-sonnet-latest"
        parameters = {
            "max_tokens": 256,
            "temperature": 1,
            "top_k": 0,
            "top_p": 0
        }
    }
    if (databody.model.includes("4.1")) {
        model = "gpt-4.1"
    }

    if (databody.model.includes("4.5") || databody.model.includes("4-5")) {
        model = "gpt-4.5-preview"
    }
    if (databody.model == "gpt-4o-search-preview") {
        model = "gpt-4o-search-preview"
        parameters = {
            "response_format": null,
            "web_search_options": {
                "search_context_size": "medium",
                "user_location": {
                    "approximate": {
                        "city": "New York",
                        "country": "US",
                        "region": "New York",
                        "timezone": "America/New_York"
                    },
                    "type": "approximate"
                }
            }
        }
    }
    let data = {
        "id": uuidv4(),
        "playground_session_id": playground_sessions,
        "shared_prompt_blueprint": {
            "inference_client_name": null,
            "metadata": {
                "model": {
                    "name": model,
                    "provider": provider,
                    "parameters": parameters
                }
            },
            "prompt_template": {
                "type": "chat",
                "messages": transformMessagesArray(databody.messages),
                "tools": null,
                "input_variables": [],
                "functions": []
            },
            "provider_base_url_name": null
        },
        "individual_run_requests": [
            {
                "input_variables": {},
                "run_group_position": 1
            }
        ]
    }
    const response = await axios.post(url, data, { headers });
    if (response.data.success) {
        return 1
    } else {
        return -1
    }
}
function isJsonString(str) {
    try {
        const parsed = JSON.parse(str);
        return typeof parsed === 'object' && parsed !== null;
    } catch (e) {
        return false;
    }
}
// postmessage("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTc0NzczOTk1MCwianRpIjoiMjc0YTlmNDUtYTRhZC00MDAxLWFkN2MtMzc5MmNkYTI2NDk4IiwidHlwZSI6ImFjY2VzcyIsInN1YiI6MjIyMzksIm5iZiI6MTc0NzczOTk1MCwiZXhwIjoxNzQ4MzQ0NzUwfQ.ZSqkwGlZIW8OmCo0JfHK4BUW2kdnIJ_p-CNJ9FN2pIQ",22553,"499e14da-4977-4d69-8b3e-566041c151e2" )
function findDifference(str1, str2) {
    // 检查第一个字符串是否是第二个字符串的一部分
    if (str2.startsWith(str1)) {
        // 如果是,返回第二个字符串的不同部分
        return str2.slice(str1.length);
    } else {
        // 如果不是,返回一个提示信息或者处理其他逻辑
        return "";
    }
}
function normalizeMessages(messages) {
    if (!Array.isArray(messages)) {
        return [{
            "role": "user",
            "content": "error"
        }]; // 或者根据你的需求返回其他内容
    }
    // 遍历每个 message 对象
    return messages.map((message) => {
        if (Array.isArray(message.content)) {
            // 如果 content 是数组,则提取 type="text" 的 text 内容
            const textContent = message.content
                .filter((item) => item.type === "text")
                .map((item) => item.text)
                .join(" ");

            // 将 message.content 替换为 textContent
            return {
                ...message,
                content: textContent
            };
        }
        // 如果 content 不是数组,直接返回 message 对象
        return message;
    });
}

app.get('/v1/models', async (req, res) => {
  const models = [
    "claude-3-5-sonnet-20240620",
    "claude-3-7-sonnet-20250219",
    "claude-3-5-sonnet-20241022",
    "gpt-4o",
    "gpt-4.1",
    "gpt-4.1-2025-04-14",
    "gpt-4.5-preview-2025-02-27",
    "gpt-4o-search-preview"
  ];

  const result = models.map((id) => {
    return {
      id,
      object: "model",
      created: 1626777600,
      owned_by: "custom",
      root: id.startsWith("claude") ? "anthropic" : "openai"
    };
  });

  res.json({
    data: result,
    success: true
  });
});


app.post('/v1/chat/completions', async (req, res) => {
    let databody = req.body
    databody.messages = normalizeMessages(databody.messages)
    let access = ""
    let authHeader = req.headers['authorization'];
    if (authHeader && authHeader.startsWith("Bearer")) {
        access = authHeader.split("Bearer ")[1];
    }
    if(access == "") {
        return
    }
    const [tokenResult, workspaceResult] = await Promise.all([
        fetchTokenDetails(access),
        fetchWorkspaceId(access)
    ]);

    const { access_token, clientId } = tokenResult;
    const { workspaceId } = workspaceResult;

    //刷新sessionid
    let playground_sessions = await pysession(access, workspaceId, databody)

    // 发送的数据
    const sendAction = `{"action":10,"channel":"user:${clientId}","params":{"agent":"react-hooks/2.0.2"}}`
    // 构建 wss url
    const wsUrl = `wss://realtime.ably.io/?access_token=${encodeURIComponent(access_token)}&clientId=${clientId}&format=json&heartbeats=true&v=3&agent=ably-js%2F2.0.2%20browser`;
    // 创建 WebSocket 连接
    const ws = new WebSocket(wsUrl);

    let closedByServer = false;
    let last = ""
    let linshi = ""
    let send = ""
    let nonstr = ""
    postmessage(access, workspaceId, playground_sessions, databody)
    ws.onopen = () => {
        ws.send(sendAction);
    };

    ws.onmessage = async (event) => {
        try {
            const data = event.data;
            linshi = ""
            send = ""
            const msg = JSON.parse(data);
            let firstMsg = msg?.messages?.[0];
            if (
                    firstMsg?.name === "UPDATE_LAST_MESSAGE" &&
                    typeof firstMsg.data === "string" &&
                    isJsonString(firstMsg.data)
                ) {
                linshi = JSON.parse(msg.messages[0].data).payload.message.content[0].text
                send = findDifference(last, linshi)
                last = linshi
                nonstr += send
                if (databody.stream == true) {
                    res.write(`data: {"id":"chatcmpl-9709rQdvMSIASrvcWGVsJMQouP2UV","object":"chat.completion.chunk","created":${Math.floor(Date.now() / 1000)},"model":"${databody.model}","system_fingerprint":"fp_3bc1b5746c","choices":[{"index":0,"delta":{"content":${JSON.stringify(send)}},"logprobs":null,"finish_reason":null}]} \n\n`)
                }
            }
             
        if (
            firstMsg?.name === "INDIVIDUAL_RUN_COMPLETE" &&
            typeof firstMsg.data === "string" &&
            isJsonString(firstMsg.data)
            ){
                if (!databody.stream || databody.stream != true) {
                    res.json({
                        id: "chatcmpl-8Tos2WZQfPdBaccpgMkasGxtQfJtq",
                        object: "chat.completion",
                        created: Math.floor(Date.now() / 1000),
                        model: databody.model,
                        choices: [
                            {
                                index: 0,
                                message: {
                                    role: "assistant",
                                    content: nonstr,
                                },
                                finish_reason: "stop",
                            },
                        ],
                        usage: {
                            prompt_tokens: 0,
                            completion_tokens: 0,
                            total_tokens: 0,
                        },
                        system_fingerprint: null,
                    });
                    return;
                }
                res.write(
                    `data: {"id":"chatcmpl-89CvUKf0C36wUexKrTrmhf5tTEnEw","object":"chat.completion.chunk","model":"${databody.model}","created":${Math.floor(
                        Date.now() / 1000,
                    )},"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}\n\n`,
                );
                res.write(`data: [DONE]\n`);
                res.end(); 
                ws.close();
            }
            // 收到 {"action":0} 时断开
            if (msg.action === 0) {
                closedByServer = true;
                ws.close();
            }
            // 你可以在这里做一些转发或处理,也可以直接返回到前端
        } catch (err) {
            // 不是 JSON,直接忽略
        }
    }

    ws.onclose = () => {
        return
    }

    ws.onerror = (err) => {
        res.status(500).json({ code: 2, msg: 'Socket error', error: err.message });
    }

    
});

app.listen(7860, () => {
    console.log('Server running at http://localhost:3000');
});