dan92 commited on
Commit
0c0fa0b
·
verified ·
1 Parent(s): 99b97d0

Upload 4 files

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