yxmiler commited on
Commit
2c66a64
·
verified ·
1 Parent(s): 983f39b

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +635 -630
index.js CHANGED
@@ -1,631 +1,636 @@
1
- import express from 'express';
2
- import fetch from 'node-fetch';
3
- import dotenv from 'dotenv';
4
- import cors from 'cors';
5
- import { launch } from 'puppeteer';
6
- import { v4 as uuidv4 } from 'uuid';
7
- import path from 'path';
8
- import fs from 'fs';
9
-
10
- dotenv.config();
11
- // 配置常量
12
- const CONFIG = {
13
- MODELS: {
14
- 'grok-latest': 'grok-latest',
15
- 'grok-latest-image': 'grok-latest'
16
- },
17
- API: {
18
- BASE_URL: "https://grok.com",
19
- API_KEY: process.env.API_KEY || "sk-123456",
20
- SSO_TOKEN: null,//登录时才有的认证cookie,这里暂时用不到,之后可能需要
21
- SIGNATURE_COOKIE: null
22
- },
23
- SERVER: {
24
- PORT: process.env.PORT || 3000,
25
- BODY_LIMIT: '5mb'
26
- },
27
- RETRY: {
28
- MAX_ATTEMPTS: 3,//重试次数
29
- DELAY_BASE: 1000 // 基础延迟时间(毫秒)
30
- },
31
- CHROME_PATH: process.env.CHROME_PATH || 'C:/Program Files/Google/Chrome/Application/chrome.exe'// 替换为你的 Chrome 实际路径
32
- };
33
-
34
-
35
- // 请求头配置
36
- const DEFAULT_HEADERS = {
37
- 'accept': '*/*',
38
- 'accept-language': 'zh-CN,zh;q=0.9',
39
- 'accept-encoding': 'gzip, deflate, br, zstd',
40
- 'content-type': 'text/plain;charset=UTF-8',
41
- 'Connection': 'keep-alive',
42
- 'origin': 'https://grok.com',
43
- 'priority': 'u=1, i',
44
- 'sec-ch-ua': '"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"',
45
- 'sec-ch-ua-mobile': '?0',
46
- 'sec-ch-ua-platform': '"Windows"',
47
- 'sec-fetch-dest': 'empty',
48
- 'sec-fetch-mode': 'cors',
49
- 'sec-fetch-site': 'same-origin',
50
- 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36',
51
- 'baggage': 'sentry-public_key=b311e0f2690c81f25e2c4cf6d4f7ce1c'
52
- };
53
-
54
- // 定义签名文件路径为 /tmp 目录
55
- const SIGNATURE_FILE_PATH = '/tmp/signature.json';
56
-
57
- class Utils {
58
- static async extractGrokHeaders() {
59
- try {
60
- // 启动浏览器
61
- const browser = await launch({
62
- executablePath: CONFIG.CHROME_PATH,
63
- headless: true
64
- });
65
-
66
- const page = await browser.newPage();
67
- await page.goto(`${CONFIG.API.BASE_URL}`, { waitUntil: 'networkidle0' });
68
-
69
- // 获取所有 Cookies
70
- const cookies = await page.cookies();
71
- const targetHeaders = ['x-anonuserid', 'x-challenge', 'x-signature'];
72
- const extractedHeaders = {};
73
- // 遍历 Cookies
74
- for (const cookie of cookies) {
75
- // 检查是否为目标头信息
76
- if (targetHeaders.includes(cookie.name.toLowerCase())) {
77
- extractedHeaders[cookie.name.toLowerCase()] = cookie.value;
78
- }
79
- }
80
- // 关闭浏览器
81
- await browser.close();
82
- // 打印并返回提取的头信息
83
- console.log('提取的头信息:', JSON.stringify(extractedHeaders, null, 2));
84
- return extractedHeaders;
85
-
86
- } catch (error) {
87
- console.error('获取头信息出错:', error);
88
- return null;
89
- }
90
- }
91
- static async get_signature() {
92
- console.log("刷新认证信息");
93
- let retryCount = 0;
94
- while (retryCount < CONFIG.RETRY.MAX_ATTEMPTS) {
95
- let headers = await Utils.extractGrokHeaders();
96
- if (headers) {
97
- console.log("获取认证信息成功");
98
- CONFIG.API.SIGNATURE_COOKIE = { cookie: `x-anonuserid=${headers["x-anonuserid"]}; x-challenge=${headers["x-challenge"]}; x-signature=${headers["x-signature"]}` };
99
- try {
100
- fs.writeFileSync(SIGNATURE_FILE_PATH, JSON.stringify(CONFIG.API.SIGNATURE_COOKIE));//保存认证信息
101
- return CONFIG.API.SIGNATURE_COOKIE;
102
- } catch (error) {
103
- console.error('写入签名文件失败:', error);
104
- return CONFIG.API.SIGNATURE_COOKIE;
105
- }
106
- }
107
- retryCount++;
108
- if (retryCount >= CONFIG.RETRY.MAX_ATTEMPTS) {
109
- throw new Error(`获取认证信息失败!`);
110
- }
111
- await new Promise(resolve => setTimeout(resolve, CONFIG.RETRY.DELAY_BASE * retryCount));
112
- }
113
- }
114
- static async retryRequestWithNewSignature(originalRequest) {
115
- console.log("认证信息已过期,尝试刷新认证信息并重新请求~");
116
- try {
117
- // 刷新认证信息
118
- await Utils.get_signature();
119
-
120
- // 重新执行原始请求
121
- return await originalRequest();
122
- } catch (error) {
123
- // 第二次失败直接抛出错误
124
- throw new Error(`重试请求失败: ${error.message}`);
125
- }
126
- }
127
- static async handleError(error, res, originalRequest = null) {
128
- console.error('Error:', error);
129
-
130
- // 如果是500错误且提供了原始请求函数,尝试重新获取签名并重试
131
- if (error.status === 500 && originalRequest) {
132
- try {
133
- const result = await Utils.retryRequestWithNewSignature(originalRequest);
134
- return result;
135
- } catch (retryError) {
136
- console.error('重试失败:', retryError);
137
- return res.status(500).json({
138
- error: {
139
- message: retryError.message,
140
- type: 'server_error',
141
- param: null,
142
- code: retryError.code || null
143
- }
144
- });
145
- }
146
- }
147
-
148
- // 其他错误直接返回
149
- res.status(500).json({
150
- error: {
151
- message: error.message,
152
- type: 'server_error',
153
- param: null,
154
- code: error.code || null
155
- }
156
- });
157
- }
158
-
159
- static async makeRequest(req, res) {
160
- try {
161
- if (!CONFIG.API.SIGNATURE_COOKIE) {
162
- await Utils.get_signature();
163
- try {
164
- CONFIG.API.SIGNATURE_COOKIE = JSON.parse(fs.readFileSync(SIGNATURE_FILE_PATH));
165
- } catch (error) {
166
- console.error('读取签名文件失败:', error);
167
- await Utils.get_signature(); // 如果读取失败,重新获取签名
168
- }
169
- }
170
- const grokClient = new GrokApiClient(req.body.model);
171
- const requestPayload = await grokClient.prepareChatRequest(req.body);
172
- //创建新对话
173
- const newMessageReq = await fetch(`${CONFIG.API.BASE_URL}/api/rpc`, {
174
- method: 'POST',
175
- headers: {
176
- ...DEFAULT_HEADERS,
177
- ...CONFIG.API.SIGNATURE_COOKIE
178
- },
179
- body: JSON.stringify({
180
- rpc: "createConversation",
181
- req: {
182
- temporary: false
183
- }
184
- })
185
- });
186
-
187
- if (!newMessageReq.ok) {
188
- throw new Error(`上游服务请求失败! status: ${newMessageReq.status}`);
189
- }
190
-
191
- // 获取响应文本
192
- const responseText = await newMessageReq.json();
193
- const conversationId = responseText.conversationId;
194
- console.log("会话ID:conversationId", conversationId);
195
- if (!conversationId) {
196
- throw new Error(`创建会话失败! status: ${newMessageReq.status}`);
197
- }
198
- //发送对话
199
- const response = await fetch(`${CONFIG.API.BASE_URL}/api/conversations/${conversationId}/responses`, {
200
- method: 'POST',
201
- headers: {
202
- "accept": "text/event-stream",
203
- "baggage": "sentry-public_key=b311e0f2690c81f25e2c4cf6d4f7ce1c",
204
- "content-type": "text/plain;charset=UTF-8",
205
- "Connection": "keep-alive",
206
- ...CONFIG.API.SIGNATURE_COOKIE
207
- },
208
- body: JSON.stringify(requestPayload)
209
- });
210
-
211
- if (!response.ok) {
212
- throw new Error(`上游服务请求失败! status: ${response.status}`);
213
- }
214
-
215
- if (req.body.stream) {
216
- await handleStreamResponse(response, req.body.model, res);
217
- } else {
218
- await handleNormalResponse(response, req.body.model, res);
219
- }
220
- } catch (error) {
221
- throw error;
222
- }
223
- }
224
- }
225
-
226
-
227
- class GrokApiClient {
228
- constructor(modelId) {
229
- if (!CONFIG.MODELS[modelId]) {
230
- throw new Error(`不支持的模型: ${modelId}`);
231
- }
232
- this.modelId = CONFIG.MODELS[modelId];
233
- }
234
-
235
- processMessageContent(content) {
236
- if (typeof content === 'string') return content;
237
- return null;
238
- }
239
- // 获取图片类型
240
- getImageType(base64String) {
241
- let mimeType = 'image/jpeg';
242
- if (base64String.includes('data:image')) {
243
- const matches = base64String.match(/data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+);base64,/);
244
- if (matches) {
245
- mimeType = matches[1];
246
- }
247
- }
248
- const extension = mimeType.split('/')[1];
249
- const fileName = `image.${extension}`;
250
-
251
- return {
252
- mimeType: mimeType,
253
- fileName: fileName
254
- };
255
- }
256
-
257
- async uploadBase64Image(base64Data, url) {
258
- try {
259
- // 处理 base64 数据
260
- let imageBuffer;
261
- if (base64Data.includes('data:image')) {
262
- imageBuffer = base64Data.split(',')[1];
263
- } else {
264
- imageBuffer = base64Data
265
- }
266
- const { mimeType, fileName } = this.getImageType(base64Data);
267
- let uploadData = {
268
- rpc: "uploadFile",
269
- req: {
270
- fileName: fileName,
271
- fileMimeType: mimeType,
272
- content: imageBuffer
273
- }
274
- };
275
- console.log("发送图片请求");
276
- // 发送请求
277
- const response = await fetch(url, {
278
- method: 'POST',
279
- headers: {
280
- ...CONFIG.DEFAULT_HEADERS,
281
- ...CONFIG.API.SIGNATURE_COOKIE
282
- },
283
- body: JSON.stringify(uploadData)
284
- });
285
-
286
- if (!response.ok) {
287
- console.error(`上传图片失败,状态码:${response.status},原因:${response.error}`);
288
- return '';
289
- }
290
-
291
- const result = await response.json();
292
- console.log('上传图片成功:', result);
293
- return result.fileMetadataId;
294
-
295
- } catch (error) {
296
- console.error('上传图片失败:', error);
297
- return '';
298
- }
299
- }
300
-
301
- async prepareChatRequest(request) {
302
- const processImageUrl = async (content) => {
303
- if (content.type === 'image_url' && content.image_url.url.includes('data:image')) {
304
- const imageResponse = await this.uploadBase64Image(
305
- content.image_url.url,
306
- `${CONFIG.API.BASE_URL}/api/rpc`
307
- );
308
- return imageResponse;
309
- }
310
- return null;
311
- };
312
- let fileAttachments = [];
313
- let messages = '';
314
- let lastRole = null;
315
- let lastContent = '';
316
-
317
- for (const current of request.messages) {
318
- const role = current.role === 'assistant' ? 'assistant' : 'user';
319
- let textContent = '';
320
- // 处理消息内容
321
- if (Array.isArray(current.content)) {
322
- // 处理数组内的所有内容
323
- for (const item of current.content) {
324
- if (item.type === 'image_url') {
325
- // 如果是图片且是最后一条消息,则处理图片
326
- if (current === request.messages[request.messages.length - 1]) {
327
- const processedImage = await processImageUrl(item);
328
- if (processedImage) fileAttachments.push(processedImage);
329
- }
330
- textContent += (textContent ? '\n' : '') + "[图片]";//图片占位符
331
- } else if (item.type === 'text') {
332
- textContent += (textContent ? '\n' : '') + item.text;
333
- }
334
- }
335
- } else if (typeof current.content === 'object' && current.content !== null) {
336
- // 处理单个对象内容
337
- if (current.content.type === 'image_url') {
338
- // 如果是图片且是最后一条消息,则处理图片
339
- if (current === request.messages[request.messages.length - 1]) {
340
- const processedImage = await processImageUrl(current.content);
341
- if (processedImage) fileAttachments.push(processedImage);
342
- }
343
- textContent += (textContent ? '\n' : '') + "[图片]";//图片占位符
344
- } else if (current.content.type === 'text') {
345
- textContent = current.content.text;
346
- }
347
- } else {
348
- // 处理普通文本内容
349
- textContent = this.processMessageContent(current.content);
350
- }
351
- // 添加文本内容到消息字符串
352
- if (textContent) {
353
- if (role === lastRole) {
354
- // 如果角色相同,合并消息内容
355
- lastContent += '\n' + textContent;
356
- messages = messages.substring(0, messages.lastIndexOf(`${role.toUpperCase()}: `)) +
357
- `${role.toUpperCase()}: ${lastContent}\n`;
358
- } else {
359
- // 如果角色不同,添加新的消息
360
- messages += `${role.toUpperCase()}: ${textContent}\n`;
361
- lastContent = textContent;
362
- lastRole = role;
363
- }
364
- } else if (current === request.messages[request.messages.length - 1] && fileAttachments.length > 0) {
365
- // 如果是最后一条消息且有图片附件,添加空消息占位
366
- messages += `${role.toUpperCase()}: [图片]\n`;
367
- }
368
- }
369
-
370
- if (fileAttachments.length > 4) {
371
- fileAttachments = fileAttachments.slice(0, 4); // 最多上传4张
372
- }
373
-
374
- messages = messages.trim();
375
-
376
- return {
377
- message: messages,
378
- modelName: this.modelId,
379
- disableSearch: false,
380
- imageAttachments: [],
381
- returnImageBytes: false,
382
- returnRawGrokInXaiRequest: false,
383
- fileAttachments: fileAttachments,
384
- enableImageStreaming: false,
385
- imageGenerationCount: 1,
386
- toolOverrides: {
387
- imageGen: request.model === 'grok-latest-image',
388
- webSearch: false,
389
- xSearch: false,
390
- xMediaSearch: false,
391
- trendsSearch: false,
392
- xPostAnalyze: false
393
- }
394
- };
395
- }
396
- }
397
-
398
- class MessageProcessor {
399
- static createChatResponse(message, model, isStream = false) {
400
- const baseResponse = {
401
- id: `chatcmpl-${uuidv4()}`,
402
- created: Math.floor(Date.now() / 1000),
403
- model: model
404
- };
405
-
406
- if (isStream) {
407
- return {
408
- ...baseResponse,
409
- object: 'chat.completion.chunk',
410
- choices: [{
411
- index: 0,
412
- delta: {
413
- content: message
414
- }
415
- }]
416
- };
417
- }
418
-
419
- // 如果是数组(图片响应),直接使用整个数组作为content
420
- const messageContent = Array.isArray(message) ? message : message;
421
-
422
- return {
423
- ...baseResponse,
424
- object: 'chat.completion',
425
- choices: [{
426
- index: 0,
427
- message: {
428
- role: 'assistant',
429
- content: messageContent
430
- },
431
- finish_reason: 'stop'
432
- }],
433
- usage: null
434
- };
435
- }
436
- }
437
-
438
- // 中间件配置
439
- const app = express();
440
- app.use(express.json({ limit: '5mb' }));
441
- app.use(express.urlencoded({ extended: true, limit: '5mb' }));
442
- app.use(cors({
443
- origin: '*',
444
- methods: ['GET', 'POST', 'OPTIONS'],
445
- allowedHeaders: ['Content-Type', 'Authorization']
446
- }));
447
- // API路由
448
- app.get('/hf/v1/models', (req, res) => {
449
- res.json({
450
- object: "list",
451
- data: Object.keys(CONFIG.MODELS).map((model, index) => ({
452
- id: model,
453
- object: "model",
454
- created: Math.floor(Date.now() / 1000),
455
- owned_by: "xai",
456
- }))
457
- });
458
- });
459
-
460
- app.post('/hf/v1/chat/completions', async (req, res) => {
461
- const authToken = req.headers.authorization?.replace('Bearer ', '');
462
- if (authToken !== CONFIG.API.API_KEY) {
463
- return res.status(401).json({ error: 'Unauthorized' });
464
- }
465
- if (req.body.model === 'grok-latest-image' && req.body.stream) {
466
- return res.status(400).json({ error: '该模型不支持流式' });
467
- }
468
-
469
- try {
470
- await Utils.makeRequest(req, res);
471
- } catch (error) {
472
- await Utils.handleError(error, res);
473
- }
474
- });
475
-
476
- async function handleStreamResponse(response, model, res) {
477
- res.setHeader('Content-Type', 'text/event-stream');
478
- res.setHeader('Cache-Control', 'no-cache');
479
- res.setHeader('Connection', 'keep-alive');
480
-
481
- try {
482
- // 获取响应文本
483
- const responseText = await response.text();
484
- const lines = responseText.split('\n');
485
-
486
- for (const line of lines) {
487
- if (!line.startsWith('data: ')) continue;
488
-
489
- const data = line.slice(6);
490
- if (data === '[DONE]') {
491
- res.write('data: [DONE]\n\n');
492
- continue;
493
- }
494
- console.log("data", data);
495
- let linejosn = JSON.parse(data);
496
- const token = linejosn.token;
497
- if (token && token.length > 0) {
498
- const responseData = MessageProcessor.createChatResponse(token, model, true);
499
- res.write(`data: ${JSON.stringify(responseData)}\n\n`);
500
- }
501
- }
502
-
503
- res.end();
504
- } catch (error) {
505
- Utils.handleError(error, res);
506
- }
507
- }
508
-
509
- async function handleNormalResponse(response, model, res) {
510
- let fullResponse = '';
511
- let imageUrl = '';
512
-
513
- try {
514
- const responseText = await response.text();
515
- console.log('原始响应文本:', responseText);
516
- const lines = responseText.split('\n');
517
-
518
- for (const line of lines) {
519
- if (!line.startsWith('data: ')) continue;
520
-
521
- const data = line.slice(6);
522
- if (data === '[DONE]') continue;
523
- let linejosn = JSON.parse(data);
524
- console.log('解析的JSON数据:', linejosn);
525
-
526
- if (linejosn.response === "token") {
527
- const token = linejosn.token;
528
- if (token && token.length > 0) {
529
- fullResponse += token;
530
- }
531
- } else if (linejosn.response === "modelResponse" && model === 'grok-latest-image') {
532
- console.log('检测到图片响应:', linejosn.modelResponse);
533
- if (linejosn?.modelResponse?.generatedImageUrls?.length > 0) {
534
- imageUrl = linejosn.modelResponse.generatedImageUrls[0]; // 获取第一个URL
535
- console.log('获取到图片URL:', imageUrl);
536
- }
537
- }
538
- }
539
-
540
- if (imageUrl) {
541
- console.log('开始处理图片URL:', imageUrl);
542
- const dataImage = await handleImageResponse(imageUrl);
543
- console.log('处理后的图片数据:', JSON.stringify(dataImage, null, 2));
544
-
545
- const responseData = MessageProcessor.createChatResponse([dataImage], model);
546
- console.log('最终的响应对象:', JSON.stringify(responseData, null, 2));
547
- res.json(responseData);
548
- } else {
549
- console.log('没有图片URL,返回文本响应:', fullResponse);
550
- const responseData = MessageProcessor.createChatResponse(fullResponse, model);
551
- res.json(responseData);
552
- }
553
- } catch (error) {
554
- console.error('处理响应时发生错误:', error);
555
- Utils.handleError(error, res);
556
- }
557
- }
558
-
559
- async function handleImageResponse(imageUrl) {
560
- try {
561
- //对服务器发送图片请求
562
- const MAX_RETRIES = 3;
563
- let retryCount = 0;
564
- let imageBase64Response;
565
-
566
- while (retryCount < MAX_RETRIES) {
567
- try {
568
- //发送图片请求获取图片
569
- imageBase64Response = await fetch(`https://assets.grok.com/${imageUrl}`, {
570
- method: 'GET',
571
- headers: {
572
- ...DEFAULT_HEADERS,
573
- ...CONFIG.API.SIGNATURE_COOKIE
574
- }
575
- });
576
-
577
- if (imageBase64Response.ok) {
578
- break; // 如果请求成功,跳出重试循环
579
- }
580
-
581
- retryCount++;
582
- if (retryCount === MAX_RETRIES) {
583
- throw new Error(`上游服务请求失败! status: ${imageBase64Response.status}`);
584
- }
585
-
586
- // 等待一段时间后重试(可以使用指数退避)
587
- await new Promise(resolve => setTimeout(resolve, 500 * retryCount));
588
-
589
- } catch (error) {
590
- retryCount++;
591
- if (retryCount === MAX_RETRIES) {
592
- throw error;
593
- }
594
- // 等待一段时间后重试
595
- await new Promise(resolve => setTimeout(resolve, 500 * retryCount));
596
- }
597
- }
598
-
599
- const arrayBuffer = await imageBase64Response.arrayBuffer();
600
- const imagebuffer = Buffer.from(arrayBuffer);
601
-
602
- const base64String = imagebuffer.toString('base64');
603
-
604
- // 获取图片类型(例如:image/jpeg, image/png)
605
- const imageContentType = imageBase64Response.headers.get('content-type');
606
-
607
- // 修改返回结构,确保返回Markdown格式的图片标签
608
- return {
609
- type: "image_url",
610
- image_url: {
611
- url: `data:image/jpg;base64,${base64String}`
612
- }
613
- };
614
-
615
- // 或者如果需要直接返回可显示的字符串
616
- // return `![generated image](data:image/jpg;base64,${base64String})`;
617
- } catch (error) {
618
- console.error('图片处理失败:', error);
619
- return '图片生成失败';
620
- }
621
- }
622
-
623
- // 404处理
624
- app.use((req, res) => {
625
- res.status(404).send('请求路径不存在');
626
- });
627
-
628
- // 启动服务器
629
- app.listen(CONFIG.SERVER.PORT, () => {
630
- console.log(`服务器已启动,监听端口: ${CONFIG.SERVER.PORT}`);
 
 
 
 
 
631
  });
 
1
+ import express from 'express';
2
+ import fetch from 'node-fetch';
3
+ import dotenv from 'dotenv';
4
+ import cors from 'cors';
5
+ import { launch } from 'puppeteer';
6
+ import { v4 as uuidv4 } from 'uuid';
7
+ import path from 'path';
8
+ import fs from 'fs';
9
+
10
+ dotenv.config();
11
+ // 配置常量
12
+ const CONFIG = {
13
+ MODELS: {
14
+ 'grok-latest': 'grok-latest',
15
+ 'grok-latest-image': 'grok-latest'
16
+ },
17
+ API: {
18
+ BASE_URL: "https://grok.com",
19
+ API_KEY: process.env.API_KEY || "sk-123456",
20
+ SSO_TOKEN: null,//登录时才有的认证cookie,这里暂时用不到,之后可能需要
21
+ SIGNATURE_COOKIE: null
22
+ },
23
+ SERVER: {
24
+ PORT: process.env.PORT || 3000,
25
+ BODY_LIMIT: '5mb'
26
+ },
27
+ RETRY: {
28
+ MAX_ATTEMPTS: 3,//重试次数
29
+ DELAY_BASE: 1000 // 基础延迟时间(毫秒)
30
+ },
31
+ CHROME_PATH: process.env.CHROME_PATH || 'C:/Program Files/Google/Chrome/Application/chrome.exe'// 替换为你的 Chrome 实际路径
32
+ };
33
+
34
+
35
+ // 请求头配置
36
+ const DEFAULT_HEADERS = {
37
+ 'accept': '*/*',
38
+ 'accept-language': 'zh-CN,zh;q=0.9',
39
+ 'accept-encoding': 'gzip, deflate, br, zstd',
40
+ 'content-type': 'text/plain;charset=UTF-8',
41
+ 'Connection': 'keep-alive',
42
+ 'origin': 'https://grok.com',
43
+ 'priority': 'u=1, i',
44
+ 'sec-ch-ua': '"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"',
45
+ 'sec-ch-ua-mobile': '?0',
46
+ 'sec-ch-ua-platform': '"Windows"',
47
+ 'sec-fetch-dest': 'empty',
48
+ 'sec-fetch-mode': 'cors',
49
+ 'sec-fetch-site': 'same-origin',
50
+ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36',
51
+ 'baggage': 'sentry-public_key=b311e0f2690c81f25e2c4cf6d4f7ce1c'
52
+ };
53
+
54
+ // 定义签名文件路径为 /tmp 目录
55
+ const SIGNATURE_FILE_PATH = '/tmp/signature.json';
56
+
57
+ class Utils {
58
+ static async extractGrokHeaders() {
59
+ try {
60
+ // 启动浏览器
61
+ const browser = await launch({
62
+ executablePath: CONFIG.CHROME_PATH,
63
+ headless: true
64
+ });
65
+
66
+ const page = await browser.newPage();
67
+ await page.goto(`${CONFIG.API.BASE_URL}`, { waitUntil: 'networkidle0' });
68
+
69
+ // 获取所有 Cookies
70
+ const cookies = await page.cookies();
71
+ const targetHeaders = ['x-anonuserid', 'x-challenge', 'x-signature'];
72
+ const extractedHeaders = {};
73
+ // 遍历 Cookies
74
+ for (const cookie of cookies) {
75
+ // 检查是否为目标头信息
76
+ if (targetHeaders.includes(cookie.name.toLowerCase())) {
77
+ extractedHeaders[cookie.name.toLowerCase()] = cookie.value;
78
+ }
79
+ }
80
+ // 关闭浏览器
81
+ await browser.close();
82
+ // 打印并返回提取的头信息
83
+ console.log('提取的头信息:', JSON.stringify(extractedHeaders, null, 2));
84
+ return extractedHeaders;
85
+
86
+ } catch (error) {
87
+ console.error('获取头信息出错:', error);
88
+ return null;
89
+ }
90
+ }
91
+ static async get_signature() {
92
+ console.log("刷新认证信息");
93
+ let retryCount = 0;
94
+ while (retryCount < CONFIG.RETRY.MAX_ATTEMPTS) {
95
+ let headers = await Utils.extractGrokHeaders();
96
+ if (headers) {
97
+ console.log("获取认证信息成功");
98
+ CONFIG.API.SIGNATURE_COOKIE = { cookie: `x-anonuserid=${headers["x-anonuserid"]}; x-challenge=${headers["x-challenge"]}; x-signature=${headers["x-signature"]}` };
99
+ try {
100
+ fs.writeFileSync(SIGNATURE_FILE_PATH, JSON.stringify(CONFIG.API.SIGNATURE_COOKIE));//保存认证信息
101
+ return CONFIG.API.SIGNATURE_COOKIE;
102
+ } catch (error) {
103
+ console.error('写入签名文件失败:', error);
104
+ return CONFIG.API.SIGNATURE_COOKIE;
105
+ }
106
+ }
107
+ retryCount++;
108
+ if (retryCount >= CONFIG.RETRY.MAX_ATTEMPTS) {
109
+ throw new Error(`获取认证信息失败!`);
110
+ }
111
+ await new Promise(resolve => setTimeout(resolve, CONFIG.RETRY.DELAY_BASE * retryCount));
112
+ }
113
+ }
114
+ static async retryRequestWithNewSignature(originalRequest) {
115
+ console.log("认证信息已过期,尝试刷新认证信息并重新请求~");
116
+ try {
117
+ // 刷新认证信息
118
+ await Utils.get_signature();
119
+
120
+ // 重新执行原始请求
121
+ return await originalRequest();
122
+ } catch (error) {
123
+ // 第二次失败直接抛出错误
124
+ throw new Error(`重试请求失败: ${error.message}`);
125
+ }
126
+ }
127
+ static async handleError(error, res, originalRequest = null) {
128
+ console.error('Error:', error);
129
+
130
+ // 如果是500错误且提供了原始请求函数,尝试重新获取签名并重试
131
+ if (error.status === 500 && originalRequest) {
132
+ try {
133
+ const result = await Utils.retryRequestWithNewSignature(originalRequest);
134
+ return result;
135
+ } catch (retryError) {
136
+ console.error('重试失败:', retryError);
137
+ return res.status(500).json({
138
+ error: {
139
+ message: retryError.message,
140
+ type: 'server_error',
141
+ param: null,
142
+ code: retryError.code || null
143
+ }
144
+ });
145
+ }
146
+ }
147
+
148
+ // 其他错误直接返回
149
+ res.status(500).json({
150
+ error: {
151
+ message: error.message,
152
+ type: 'server_error',
153
+ param: null,
154
+ code: error.code || null
155
+ }
156
+ });
157
+ }
158
+
159
+ static async makeRequest(req, res) {
160
+ try {
161
+ if (!CONFIG.API.SIGNATURE_COOKIE) {
162
+ await Utils.get_signature();
163
+ try {
164
+ CONFIG.API.SIGNATURE_COOKIE = JSON.parse(fs.readFileSync(SIGNATURE_FILE_PATH));
165
+ } catch (error) {
166
+ console.error('读取签名文件失败:', error);
167
+ await Utils.get_signature(); // 如果读取失败,���新获取签名
168
+ }
169
+ }
170
+ const grokClient = new GrokApiClient(req.body.model);
171
+ const requestPayload = await grokClient.prepareChatRequest(req.body);
172
+ //创建新对话
173
+ const newMessageReq = await fetch(`${CONFIG.API.BASE_URL}/api/rpc`, {
174
+ method: 'POST',
175
+ headers: {
176
+ ...DEFAULT_HEADERS,
177
+ ...CONFIG.API.SIGNATURE_COOKIE
178
+ },
179
+ body: JSON.stringify({
180
+ rpc: "createConversation",
181
+ req: {
182
+ temporary: false
183
+ }
184
+ })
185
+ });
186
+
187
+ if (!newMessageReq.ok) {
188
+ throw new Error(`上游服务请求失败! status: ${newMessageReq.status}`);
189
+ }
190
+
191
+ // 获取响应文本
192
+ const responseText = await newMessageReq.json();
193
+ const conversationId = responseText.conversationId;
194
+ console.log("会话ID:conversationId", conversationId);
195
+ if (!conversationId) {
196
+ throw new Error(`创建会话失败! status: ${newMessageReq.status}`);
197
+ }
198
+ //发送对话
199
+ const response = await fetch(`${CONFIG.API.BASE_URL}/api/conversations/${conversationId}/responses`, {
200
+ method: 'POST',
201
+ headers: {
202
+ "accept": "text/event-stream",
203
+ "baggage": "sentry-public_key=b311e0f2690c81f25e2c4cf6d4f7ce1c",
204
+ "content-type": "text/plain;charset=UTF-8",
205
+ "Connection": "keep-alive",
206
+ ...CONFIG.API.SIGNATURE_COOKIE
207
+ },
208
+ body: JSON.stringify(requestPayload)
209
+ });
210
+
211
+ if (!response.ok) {
212
+ throw new Error(`上游服务请求失败! status: ${response.status}`);
213
+ }
214
+
215
+ if (req.body.stream) {
216
+ await handleStreamResponse(response, req.body.model, res);
217
+ } else {
218
+ await handleNormalResponse(response, req.body.model, res);
219
+ }
220
+ } catch (error) {
221
+ throw error;
222
+ }
223
+ }
224
+ }
225
+
226
+
227
+ class GrokApiClient {
228
+ constructor(modelId) {
229
+ if (!CONFIG.MODELS[modelId]) {
230
+ throw new Error(`不支持的模型: ${modelId}`);
231
+ }
232
+ this.modelId = CONFIG.MODELS[modelId];
233
+ }
234
+
235
+ processMessageContent(content) {
236
+ if (typeof content === 'string') return content;
237
+ return null;
238
+ }
239
+ // 获取图片类型
240
+ getImageType(base64String) {
241
+ let mimeType = 'image/jpeg';
242
+ if (base64String.includes('data:image')) {
243
+ const matches = base64String.match(/data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+);base64,/);
244
+ if (matches) {
245
+ mimeType = matches[1];
246
+ }
247
+ }
248
+ const extension = mimeType.split('/')[1];
249
+ const fileName = `image.${extension}`;
250
+
251
+ return {
252
+ mimeType: mimeType,
253
+ fileName: fileName
254
+ };
255
+ }
256
+
257
+ async uploadBase64Image(base64Data, url) {
258
+ try {
259
+ // 处理 base64 数据
260
+ let imageBuffer;
261
+ if (base64Data.includes('data:image')) {
262
+ imageBuffer = base64Data.split(',')[1];
263
+ } else {
264
+ imageBuffer = base64Data
265
+ }
266
+ const { mimeType, fileName } = this.getImageType(base64Data);
267
+ let uploadData = {
268
+ rpc: "uploadFile",
269
+ req: {
270
+ fileName: fileName,
271
+ fileMimeType: mimeType,
272
+ content: imageBuffer
273
+ }
274
+ };
275
+ console.log("发送图片请求");
276
+ // 发送请求
277
+ const response = await fetch(url, {
278
+ method: 'POST',
279
+ headers: {
280
+ ...CONFIG.DEFAULT_HEADERS,
281
+ ...CONFIG.API.SIGNATURE_COOKIE
282
+ },
283
+ body: JSON.stringify(uploadData)
284
+ });
285
+
286
+ if (!response.ok) {
287
+ console.error(`上传图片失败,状态码:${response.status},原因:${response.error}`);
288
+ return '';
289
+ }
290
+
291
+ const result = await response.json();
292
+ console.log('上传图片成功:', result);
293
+ return result.fileMetadataId;
294
+
295
+ } catch (error) {
296
+ console.error('上传图片失败:', error);
297
+ return '';
298
+ }
299
+ }
300
+
301
+ async prepareChatRequest(request) {
302
+ const processImageUrl = async (content) => {
303
+ if (content.type === 'image_url' && content.image_url.url.includes('data:image')) {
304
+ const imageResponse = await this.uploadBase64Image(
305
+ content.image_url.url,
306
+ `${CONFIG.API.BASE_URL}/api/rpc`
307
+ );
308
+ return imageResponse;
309
+ }
310
+ return null;
311
+ };
312
+ let fileAttachments = [];
313
+ let messages = '';
314
+ let lastRole = null;
315
+ let lastContent = '';
316
+
317
+ for (const current of request.messages) {
318
+ const role = current.role === 'assistant' ? 'assistant' : 'user';
319
+ let textContent = '';
320
+ // 处理消息内容
321
+ if (Array.isArray(current.content)) {
322
+ // 处理数组内的所有内容
323
+ for (const item of current.content) {
324
+ if (item.type === 'image_url') {
325
+ // 如果是图片且是最后一条消息,则处理图片
326
+ if (current === request.messages[request.messages.length - 1]) {
327
+ const processedImage = await processImageUrl(item);
328
+ if (processedImage) fileAttachments.push(processedImage);
329
+ }
330
+ textContent += (textContent ? '\n' : '') + "[图片]";//图片占位符
331
+ } else if (item.type === 'text') {
332
+ textContent += (textContent ? '\n' : '') + item.text;
333
+ }
334
+ }
335
+ } else if (typeof current.content === 'object' && current.content !== null) {
336
+ // 处理单个对象内容
337
+ if (current.content.type === 'image_url') {
338
+ // 如果是图片且是最后一条消息,则处理图片
339
+ if (current === request.messages[request.messages.length - 1]) {
340
+ const processedImage = await processImageUrl(current.content);
341
+ if (processedImage) fileAttachments.push(processedImage);
342
+ }
343
+ textContent += (textContent ? '\n' : '') + "[图片]";//图片占位符
344
+ } else if (current.content.type === 'text') {
345
+ textContent = current.content.text;
346
+ }
347
+ } else {
348
+ // 处理普通文本内容
349
+ textContent = this.processMessageContent(current.content);
350
+ }
351
+ // 添加文本内容到消息字符串
352
+ if (textContent) {
353
+ if (role === lastRole) {
354
+ // 如果角色相同,合并消息内容
355
+ lastContent += '\n' + textContent;
356
+ messages = messages.substring(0, messages.lastIndexOf(`${role.toUpperCase()}: `)) +
357
+ `${role.toUpperCase()}: ${lastContent}\n`;
358
+ } else {
359
+ // 如果角色不同,添加新的消息
360
+ messages += `${role.toUpperCase()}: ${textContent}\n`;
361
+ lastContent = textContent;
362
+ lastRole = role;
363
+ }
364
+ } else if (current === request.messages[request.messages.length - 1] && fileAttachments.length > 0) {
365
+ // 如果是最后一条消息且有图片附件,添加空消息占位
366
+ messages += `${role.toUpperCase()}: [图片]\n`;
367
+ }
368
+ }
369
+
370
+ if (fileAttachments.length > 4) {
371
+ fileAttachments = fileAttachments.slice(0, 4); // 最多上传4张
372
+ }
373
+
374
+ messages = messages.trim();
375
+
376
+ return {
377
+ message: messages,
378
+ modelName: this.modelId,
379
+ disableSearch: false,
380
+ imageAttachments: [],
381
+ returnImageBytes: false,
382
+ returnRawGrokInXaiRequest: false,
383
+ fileAttachments: fileAttachments,
384
+ enableImageStreaming: false,
385
+ imageGenerationCount: 1,
386
+ toolOverrides: {
387
+ imageGen: request.model === 'grok-latest-image',
388
+ webSearch: false,
389
+ xSearch: false,
390
+ xMediaSearch: false,
391
+ trendsSearch: false,
392
+ xPostAnalyze: false
393
+ }
394
+ };
395
+ }
396
+ }
397
+
398
+ class MessageProcessor {
399
+ static createChatResponse(message, model, isStream = false) {
400
+ const baseResponse = {
401
+ id: `chatcmpl-${uuidv4()}`,
402
+ created: Math.floor(Date.now() / 1000),
403
+ model: model
404
+ };
405
+
406
+ if (isStream) {
407
+ return {
408
+ ...baseResponse,
409
+ object: 'chat.completion.chunk',
410
+ choices: [{
411
+ index: 0,
412
+ delta: {
413
+ content: message
414
+ }
415
+ }]
416
+ };
417
+ }
418
+
419
+ // 如果是数组(图片响应),直接使用整个数组作为content
420
+ const messageContent = Array.isArray(message) ? message : message;
421
+
422
+ return {
423
+ ...baseResponse,
424
+ object: 'chat.completion',
425
+ choices: [{
426
+ index: 0,
427
+ message: {
428
+ role: 'assistant',
429
+ content: messageContent
430
+ },
431
+ finish_reason: 'stop'
432
+ }],
433
+ usage: null
434
+ };
435
+ }
436
+ }
437
+
438
+ // 中间件配置
439
+ const app = express();
440
+ app.use(express.json({ limit: '5mb' }));
441
+ app.use(express.urlencoded({ extended: true, limit: '5mb' }));
442
+ app.use(cors({
443
+ origin: '*',
444
+ methods: ['GET', 'POST', 'OPTIONS'],
445
+ allowedHeaders: ['Content-Type', 'Authorization']
446
+ }));
447
+ // API路由
448
+ app.get('/hf/v1/models', (req, res) => {
449
+ res.json({
450
+ object: "list",
451
+ data: Object.keys(CONFIG.MODELS).map((model, index) => ({
452
+ id: model,
453
+ object: "model",
454
+ created: Math.floor(Date.now() / 1000),
455
+ owned_by: "xai",
456
+ }))
457
+ });
458
+ });
459
+
460
+ app.post('/hf/v1/chat/completions', async (req, res) => {
461
+ const authToken = req.headers.authorization?.replace('Bearer ', '');
462
+ if (authToken !== CONFIG.API.API_KEY) {
463
+ return res.status(401).json({ error: 'Unauthorized' });
464
+ }
465
+
466
+ try {
467
+ await Utils.makeRequest(req, res);
468
+ } catch (error) {
469
+ await Utils.handleError(error, res);
470
+ }
471
+ });
472
+
473
+ async function handleStreamResponse(response, model, res) {
474
+ res.setHeader('Content-Type', 'text/event-stream');
475
+ res.setHeader('Cache-Control', 'no-cache');
476
+ res.setHeader('Connection', 'keep-alive');
477
+
478
+ try {
479
+ // 获取响应文本
480
+ const responseText = await response.text();
481
+ const lines = responseText.split('\n');
482
+
483
+ for (const line of lines) {
484
+ if (!line.startsWith('data: ')) continue;
485
+
486
+ const data = line.slice(6);
487
+ if (data === '[DONE]') {
488
+ res.write('data: [DONE]\n\n');
489
+ continue;
490
+ }
491
+ console.log("data", data);
492
+ let linejosn = JSON.parse(data);
493
+ if (linejosn.response === "token" && model == "grok-latest") {
494
+ const token = linejosn.token;
495
+ if (token && token.length > 0) {
496
+ const responseData = MessageProcessor.createChatResponse(token, model, true);
497
+ res.write(`data: ${JSON.stringify(responseData)}\n\n`);
498
+ }
499
+ } else if (linejosn.response === "modelResponse" && model === 'grok-latest-image') {
500
+ if (linejosn?.modelResponse?.generatedImageUrls?.length > 0) {
501
+ imageUrl = linejosn.modelResponse.generatedImageUrls[0]; // 获取第一个URL
502
+ const dataImage = await handleImageResponse(imageUrl);
503
+ const responseData = MessageProcessor.createChatResponse(dataImage, model, true);
504
+ res.write(`data: ${JSON.stringify(responseData)}\n\n`);
505
+ }
506
+ }
507
+ }
508
+
509
+ res.end();
510
+ } catch (error) {
511
+ Utils.handleError(error, res);
512
+ }
513
+ }
514
+
515
+ async function handleNormalResponse(response, model, res) {
516
+ let fullResponse = '';
517
+ let imageUrl = '';
518
+
519
+ try {
520
+ const responseText = await response.text();
521
+ console.log('原始响应文本:', responseText);
522
+ const lines = responseText.split('\n');
523
+
524
+ for (const line of lines) {
525
+ if (!line.startsWith('data: ')) continue;
526
+
527
+ const data = line.slice(6);
528
+ if (data === '[DONE]') continue;
529
+ let linejosn = JSON.parse(data);
530
+ console.log('解析的JSON数据:', linejosn);
531
+
532
+ if (linejosn.response === "token") {
533
+ const token = linejosn.token;
534
+ if (token && token.length > 0) {
535
+ fullResponse += token;
536
+ }
537
+ } else if (linejosn.response === "modelResponse" && model === 'grok-latest-image') {
538
+ console.log('检测到图片响应:', linejosn.modelResponse);
539
+ if (linejosn?.modelResponse?.generatedImageUrls?.length > 0) {
540
+ imageUrl = linejosn.modelResponse.generatedImageUrls[0]; // 获取第一个URL
541
+ console.log('获取到图片URL:', imageUrl);
542
+ }
543
+ }
544
+ }
545
+
546
+ if (imageUrl) {
547
+ console.log('开始处理图片URL:', imageUrl);
548
+ const dataImage = await handleImageResponse(imageUrl);
549
+
550
+ const responseData = MessageProcessor.createChatResponse([dataImage], model);
551
+ console.log('最终的响应对象:', JSON.stringify(responseData, null, 2));
552
+ res.json(responseData);
553
+ } else {
554
+ console.log('没有图片URL,返回文本响应:', fullResponse);
555
+ const responseData = MessageProcessor.createChatResponse(fullResponse, model);
556
+ res.json(responseData);
557
+ }
558
+ } catch (error) {
559
+ console.error('处理响应时发生错误:', error);
560
+ Utils.handleError(error, res);
561
+ }
562
+ }
563
+
564
+ async function handleImageResponse(imageUrl) {
565
+ try {
566
+ //对服务器发送图片请求
567
+ const MAX_RETRIES = 3;
568
+ let retryCount = 0;
569
+ let imageBase64Response;
570
+
571
+ while (retryCount < MAX_RETRIES) {
572
+ try {
573
+ //发送图片请求获取��片
574
+ imageBase64Response = await fetch(`https://assets.grok.com/${imageUrl}`, {
575
+ method: 'GET',
576
+ headers: {
577
+ ...DEFAULT_HEADERS,
578
+ ...CONFIG.API.SIGNATURE_COOKIE
579
+ }
580
+ });
581
+
582
+ if (imageBase64Response.ok) {
583
+ break; // 如果请求成功,跳出重试循环
584
+ }
585
+
586
+ retryCount++;
587
+ if (retryCount === MAX_RETRIES) {
588
+ throw new Error(`上游服务请求失败! status: ${imageBase64Response.status}`);
589
+ }
590
+
591
+ // 等待一段时间后重试(可以使用指数退避)
592
+ await new Promise(resolve => setTimeout(resolve, 500 * retryCount));
593
+
594
+ } catch (error) {
595
+ retryCount++;
596
+ if (retryCount === MAX_RETRIES) {
597
+ throw error;
598
+ }
599
+ // 等待一段时间后重试
600
+ await new Promise(resolve => setTimeout(resolve, 500 * retryCount));
601
+ }
602
+ }
603
+
604
+ const arrayBuffer = await imageBase64Response.arrayBuffer();
605
+ const imagebuffer = Buffer.from(arrayBuffer);
606
+
607
+ const base64String = imagebuffer.toString('base64');
608
+
609
+ // 获取图片类型(例如:image/jpeg, image/png)
610
+ const imageContentType = imageBase64Response.headers.get('content-type');
611
+
612
+ // 修改返回结构,确保返回Markdown格式的图片标签
613
+ return {
614
+ type: "image_url",
615
+ image_url: {
616
+ url: `data:image/jpg;base64,${base64String}`
617
+ }
618
+ };
619
+
620
+ // 或者如果需要直接返回可显示的字符串
621
+ // return `![generated image](data:image/jpg;base64,${base64String})`;
622
+ } catch (error) {
623
+ console.error('图片处理失败:', error);
624
+ return '图片生成失败';
625
+ }
626
+ }
627
+
628
+ // 404处理
629
+ app.use((req, res) => {
630
+ res.status(404).send('请求路径不存在');
631
+ });
632
+
633
+ // 启动服务器
634
+ app.listen(CONFIG.SERVER.PORT, () => {
635
+ console.log(`服务器已启动,监听端口: ${CONFIG.SERVER.PORT}`);
636
  });