dan92 commited on
Commit
7de2611
·
verified ·
1 Parent(s): 7cde6d0

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +608 -673
index.js CHANGED
@@ -1,674 +1,609 @@
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
- // 处理图片响应
407
- const processContent = (content) => {
408
- if (content?.image_url?.url) {
409
- return [{
410
- type: "image_url",
411
- image_url: {
412
- url: content.image_url.url
413
- }
414
- }];
415
- }
416
- return content;
417
- };
418
-
419
- return {
420
- ...baseResponse,
421
- object: 'chat.completion',
422
- choices: [{
423
- index: 0,
424
- message: {
425
- role: 'assistant',
426
- content: processContent(message)
427
- },
428
- finish_reason: 'stop'
429
- }],
430
- usage: null
431
- };
432
- }
433
- }
434
-
435
- // 中间件配置
436
- const app = express();
437
- app.use(express.json({ limit: '5mb' }));
438
- app.use(express.urlencoded({ extended: true, limit: '5mb' }));
439
- app.use(cors({
440
- origin: '*',
441
- methods: ['GET', 'POST', 'OPTIONS'],
442
- allowedHeaders: ['Content-Type', 'Authorization']
443
- }));
444
-
445
- // 添加请求日志中间件
446
- app.use((req, res, next) => {
447
- console.log(`[${new Date().toISOString()}] 收到请求:`, {
448
- method: req.method,
449
- path: req.path,
450
- headers: req.headers,
451
- body: req.body
452
- });
453
- next();
454
- });
455
-
456
- // 添加响应日志中间件
457
- app.use((req, res, next) => {
458
- const oldSend = res.send;
459
- res.send = function (data) {
460
- console.log(`[${new Date().toISOString()}] 发送响应:`, {
461
- status: res.statusCode,
462
- headers: res.getHeaders(),
463
- body: data
464
- });
465
- oldSend.apply(res, arguments);
466
- }
467
- next();
468
- });
469
-
470
- // API路由
471
- app.get('/hf/v1/models', (req, res) => {
472
- res.json({
473
- object: "list",
474
- data: Object.keys(CONFIG.MODELS).map((model, index) => ({
475
- id: model,
476
- object: "model",
477
- created: Math.floor(Date.now() / 1000),
478
- owned_by: "xai",
479
- }))
480
- });
481
- });
482
-
483
- app.post('/hf/v1/chat/completions', async (req, res) => {
484
- const authToken = req.headers.authorization?.replace('Bearer ', '');
485
- if (authToken !== CONFIG.API.API_KEY) {
486
- return res.status(401).json({ error: 'Unauthorized' });
487
- }
488
- if (req.body.model === 'grok-latest-image' && req.body.stream) {
489
- return res.status(400).json({ error: '该模型不支持流式' });
490
- }
491
-
492
- try {
493
- await Utils.makeRequest(req, res);
494
- } catch (error) {
495
- await Utils.handleError(error, res);
496
- }
497
- });
498
-
499
- async function handleStreamResponse(response, model, res) {
500
- res.setHeader('Content-Type', 'text/event-stream');
501
- res.setHeader('Cache-Control', 'no-cache');
502
- res.setHeader('Connection', 'keep-alive');
503
-
504
- try {
505
- // 获取响应文本
506
- const responseText = await response.text();
507
- const lines = responseText.split('\n');
508
-
509
- for (const line of lines) {
510
- if (!line.startsWith('data: ')) continue;
511
-
512
- const data = line.slice(6);
513
- if (data === '[DONE]') {
514
- res.write('data: [DONE]\n\n');
515
- continue;
516
- }
517
- console.log("data", data);
518
- let linejosn = JSON.parse(data);
519
- const token = linejosn.token;
520
- if (token && token.length > 0) {
521
- const responseData = MessageProcessor.createChatResponse(token, model, true);
522
- res.write(`data: ${JSON.stringify(responseData)}\n\n`);
523
- }
524
- }
525
-
526
- res.end();
527
- } catch (error) {
528
- Utils.handleError(error, res);
529
- }
530
- }
531
-
532
- async function handleNormalResponse(response, model, res) {
533
- let fullResponse = '';
534
- let imageUrl = '';
535
-
536
- try {
537
- const responseText = await response.text();
538
- console.log('原始响应文本:', responseText);
539
- const lines = responseText.split('\n');
540
-
541
- for (const line of lines) {
542
- if (!line.startsWith('data: ')) continue;
543
-
544
- const data = line.slice(6);
545
- if (data === '[DONE]') continue;
546
- let linejosn = JSON.parse(data);
547
- console.log('解析的JSON数据:', linejosn);
548
-
549
- if (linejosn.response === "token") {
550
- const token = linejosn.token;
551
- if (token && token.length > 0) {
552
- fullResponse += token;
553
- }
554
- } else if (linejosn.response === "modelResponse" && model === 'grok-latest-image') {
555
- console.log('检测到图片响应:', linejosn.modelResponse);
556
- if (linejosn?.modelResponse?.generatedImageUrls?.length > 0) {
557
- imageUrl = linejosn.modelResponse.generatedImageUrls[0]; // 获取第一个URL
558
- console.log('获取到图片URL:', imageUrl);
559
- }
560
- }
561
- }
562
-
563
- if (imageUrl) {
564
- console.log('开始处理图片URL:', imageUrl);
565
- const dataImage = await handleImageResponse(imageUrl);
566
- console.log('处理后的图片数据:', JSON.stringify(dataImage, null, 2));
567
-
568
- const responseData = MessageProcessor.createChatResponse(dataImage, model);
569
- console.log('最终的响应对象:', JSON.stringify(responseData, null, 2));
570
- res.json(responseData);
571
- } else {
572
- console.log('没有图片URL,返回文本响应:', fullResponse);
573
- const responseData = MessageProcessor.createChatResponse(fullResponse, model);
574
- res.json(responseData);
575
- }
576
- } catch (error) {
577
- console.error('处理响应时发生错误:', error);
578
- Utils.handleError(error, res);
579
- }
580
- }
581
-
582
- async function handleImageResponse(imageUrl) {
583
- try {
584
- //对服务器发送图片请求
585
- const MAX_RETRIES = 3;
586
- let retryCount = 0;
587
- let imageBase64Response;
588
-
589
- while (retryCount < MAX_RETRIES) {
590
- try {
591
- //发送图片请求获取图片
592
- imageBase64Response = await fetch(`https://assets.grok.com/${imageUrl}`, {
593
- method: 'GET',
594
- headers: {
595
- ...DEFAULT_HEADERS,
596
- ...CONFIG.API.SIGNATURE_COOKIE
597
- }
598
- });
599
-
600
- if (imageBase64Response.ok) {
601
- break; // 如果请求成功,跳出重试循环
602
- }
603
-
604
- retryCount++;
605
- if (retryCount === MAX_RETRIES) {
606
- throw new Error(`上游服务请求失败! status: ${imageBase64Response.status}`);
607
- }
608
-
609
- // 等待一段时间后重试(可以使用指数退避)
610
- await new Promise(resolve => setTimeout(resolve, 500 * retryCount));
611
-
612
- } catch (error) {
613
- retryCount++;
614
- if (retryCount === MAX_RETRIES) {
615
- throw error;
616
- }
617
- // 等待一段时间后重试
618
- await new Promise(resolve => setTimeout(resolve, 500 * retryCount));
619
- }
620
- }
621
-
622
- const arrayBuffer = await imageBase64Response.arrayBuffer();
623
- const imagebuffer = Buffer.from(arrayBuffer);
624
-
625
- const base64String = imagebuffer.toString('base64');
626
-
627
- // 获取图片类型(例如:image/jpeg, image/png)
628
- const imageContentType = imageBase64Response.headers.get('content-type');
629
-
630
- // 修改返回结构,确保返回Markdown格式的图片标签
631
- return {
632
- image_url: {
633
- url: `data:image/jpg;base64,${base64String}`
634
- }
635
- };
636
- } catch (error) {
637
- console.error('图片处理失败:', error);
638
- return '图片生成失败';
639
- }
640
- }
641
-
642
- // 添加测试端点
643
- app.post('/hf/v1/test', (req, res) => {
644
- // 返回OpenAI标准格式示例
645
- res.json({
646
- "id": "chatcmpl-123",
647
- "object": "chat.completion",
648
- "created": 1677652288,
649
- "model": "grok-latest-image",
650
- "choices": [{
651
- "index": 0,
652
- "message": {
653
- "role": "assistant",
654
- "content": [{
655
- "type": "image_url",
656
- "image_url": {
657
- "url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="
658
- }
659
- }]
660
- },
661
- "finish_reason": "stop"
662
- }]
663
- });
664
- });
665
-
666
- // 404处理
667
- app.use((req, res) => {
668
- res.status(404).send('请求路径不存在');
669
- });
670
-
671
- // 启动服务器
672
- app.listen(CONFIG.SERVER.PORT, () => {
673
- console.log(`服务器已启动,监听端口: ${CONFIG.SERVER.PORT}`);
674
  });
 
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
+ return {
420
+ ...baseResponse,
421
+ object: 'chat.completion',
422
+ choices: [{
423
+ index: 0,
424
+ message: {
425
+ role: 'assistant',
426
+ content: message
427
+ },
428
+ finish_reason: 'stop'
429
+ }],
430
+ usage: null
431
+ };
432
+ }
433
+ }
434
+
435
+ // 中间件配置
436
+ const app = express();
437
+ app.use(express.json({ limit: '5mb' }));
438
+ app.use(express.urlencoded({ extended: true, limit: '5mb' }));
439
+ app.use(cors({
440
+ origin: '*',
441
+ methods: ['GET', 'POST', 'OPTIONS'],
442
+ allowedHeaders: ['Content-Type', 'Authorization']
443
+ }));
444
+ // API路由
445
+ app.get('/hf/v1/models', (req, res) => {
446
+ res.json({
447
+ object: "list",
448
+ data: Object.keys(CONFIG.MODELS).map((model, index) => ({
449
+ id: model,
450
+ object: "model",
451
+ created: Math.floor(Date.now() / 1000),
452
+ owned_by: "xai",
453
+ }))
454
+ });
455
+ });
456
+
457
+ app.post('/hf/v1/chat/completions', async (req, res) => {
458
+ const authToken = req.headers.authorization?.replace('Bearer ', '');
459
+ if (authToken !== CONFIG.API.API_KEY) {
460
+ return res.status(401).json({ error: 'Unauthorized' });
461
+ }
462
+ if (req.body.model === 'grok-latest-image' && req.body.stream) {
463
+ return res.status(400).json({ error: '该模型不支持流式' });
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
+ const token = linejosn.token;
494
+ if (token && token.length > 0) {
495
+ const responseData = MessageProcessor.createChatResponse(token, model, true);
496
+ res.write(`data: ${JSON.stringify(responseData)}\n\n`);
497
+ }
498
+ }
499
+
500
+ res.end();
501
+ } catch (error) {
502
+ Utils.handleError(error, res);
503
+ }
504
+ }
505
+
506
+ async function handleNormalResponse(response, model, res) {
507
+ let fullResponse = '';
508
+ let imageUrl = '';
509
+
510
+ try {
511
+ const responseText = await response.text();
512
+ const lines = responseText.split('\n');
513
+
514
+ for (const line of lines) {
515
+ if (!line.startsWith('data: ')) continue;
516
+
517
+ const data = line.slice(6);
518
+ if (data === '[DONE]') continue;
519
+ let linejosn = JSON.parse(data);
520
+ if (linejosn.response === "token") {
521
+ const token = linejosn.token;
522
+ if (token && token.length > 0) {
523
+ fullResponse += token;
524
+ }
525
+ } else if (linejosn.response === "modelResponse" && model === 'grok-latest-image') {
526
+ if (linejosn?.modelResponse?.generatedImageUrls) {
527
+ imageUrl = linejosn.modelResponse.generatedImageUrls;
528
+ }
529
+ }
530
+ }
531
+
532
+ if (imageUrl) {
533
+ const dataImage = await handleImageResponse(imageUrl);
534
+ fullResponse = [{
535
+ type: "image_url",
536
+ image_url: {
537
+ url: dataImage
538
+ }
539
+ }]
540
+ const responseData = MessageProcessor.createChatResponse(fullResponse, model);
541
+ res.json(responseData);
542
+ } else {
543
+ const responseData = MessageProcessor.createChatResponse(fullResponse, model);
544
+ res.json(responseData);
545
+ }
546
+ } catch (error) {
547
+ Utils.handleError(error, res);
548
+ }
549
+ }
550
+ async function handleImageResponse(imageUrl) {
551
+ //对服务器发送图片请求
552
+ const MAX_RETRIES = 3;
553
+ let retryCount = 0;
554
+ let imageBase64Response;
555
+
556
+ while (retryCount < MAX_RETRIES) {
557
+ try {
558
+ //发送图片请求获取图片
559
+ imageBase64Response = await fetch(`https://assets.grok.com/${imageUrl}`, {
560
+ method: 'GET',
561
+ headers: {
562
+ ...DEFAULT_HEADERS,
563
+ ...CONFIG.API.SIGNATURE_COOKIE
564
+ }
565
+ });
566
+
567
+ if (imageBase64Response.ok) {
568
+ break; // 如果请求成功,跳出重试循环
569
+ }
570
+
571
+ retryCount++;
572
+ if (retryCount === MAX_RETRIES) {
573
+ throw new Error(`上游服务请求失败! status: ${imageBase64Response.status}`);
574
+ }
575
+
576
+ // 等待一段时间后重试(可以使用指数退避)
577
+ await new Promise(resolve => setTimeout(resolve, 500 * retryCount));
578
+
579
+ } catch (error) {
580
+ retryCount++;
581
+ if (retryCount === MAX_RETRIES) {
582
+ throw error;
583
+ }
584
+ // 等待一段时间后重试
585
+ await new Promise(resolve => setTimeout(resolve, 500 * retryCount));
586
+ }
587
+ }
588
+
589
+ const arrayBuffer = await imageBase64Response.arrayBuffer();
590
+ const imagebuffer = Buffer.from(arrayBuffer);
591
+
592
+ const base64String = imagebuffer.toString('base64');
593
+
594
+ // 获取图片类型(例如:image/jpeg, image/png)
595
+ const imageContentType = imageBase64Response.headers.get('content-type');
596
+
597
+ // 构建 Data URL返回
598
+ return `data:${imageContentType};base64,${base64String}`;
599
+ }
600
+
601
+ // 404处理
602
+ app.use((req, res) => {
603
+ res.status(404).send('请求路径不存在');
604
+ });
605
+
606
+ // 启动服务器
607
+ app.listen(CONFIG.SERVER.PORT, () => {
608
+ console.log(`服务器已启动,监听端口: ${CONFIG.SERVER.PORT}`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
609
  });