Update index.js
Browse files6 unmodified lines78910111011124 unmodified lines171819202122233 unmodified lines2728293130313233343536383937383940414243454445464753 unmodified lines1011021031051041051063 unmodified lines1101111121131141151161171181192 unmodified lines12212312412512612712812913013113213313413513613713837 unmodified lines17617717817117918018116 unmodified lines19819920019420120220320412 unmodified lines2172182192132202212228 unmodified lines2312322332282342352362372322382392402411 unmodified line2432442452402462472482492502452512522532543 unmodified lines25825926025525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030126126226311 unmodified lines27527627731927827932128028128228347 unmodified lines3313323333753343353363375 unmodified lines34334434538734634734834935039235135235335439635535635735835936040240336136236336436536636736836937037137237337440637537637737841137938041338138241538338438538638738866 unmodified lines45545645748845845946046164 unmodified lines5265275285595605295305315325645335345355365375385395705405415425435745445455465475785485495505515525535545835555565575865585595605895615625635645 unmodified lines5705715726016025735745755765772 unmodified lines58058158261158358458558661658758858959059161959259359459520 unmodified lines61661761864661962062113 unmodified lines6356366376666386396686406416426436446726736456466476482 unmodified lines6516526536826546556566866876576586596606616626936636646652 unmodified lines6686696707027037047056716726736746757107116766776781 unmodified line68068168271968368468568668768868969069169269369469569669769869913 unmodified lines7137147157457167177187191 unmodified line7217227237247257267274 unmodified lines7327337347637647357367377387396 unmodified lines7467477487777497507517521 unmodified line75475575675775875976076178878979079176276376479576576676776876980077077177277312 unmodified lines78678778881978979079179212 unmodified lines80580680783880880981081110 unmodified lines82282382485582582682736 unmodified lines8648658668988678688698709038718729058738746 unmodified linesimport StealthPlugin from 'puppeteer-extra-plugin-stealth'import { v4 as uuidv4 } from 'uuid';import Logger from './logger.js';import fs from 'fs';import path from 'path';
dotenv.config();
4 unmodified lines 'grok-2-imageGen': 'grok-latest', 'grok-2-search': 'grok-latest', "grok-3": "grok-3", "grok-3-search": "grok-3", "grok-3-imageGen": "grok-3", "grok-3-deepsearch": "grok-3", "grok-3-reasoning": "grok-3"3 unmodified lines API_KEY: process.env.API_KEY || "sk-123456", SIGNATURE_COOKIE: null, TEMP_COOKIE: null, PICGO_KEY: process.env.PICGO_KEY || null //想要生图的话需要填入这个PICGO图床的key PICGO_KEY: process.env.PICGO_KEY || null //想要流式生图的话需要填入这个PICGO图床的key }, SERVER: { PORT: process.env.PORT || 3000, BODY_LIMIT: '5mb' }, RETRY: { MAX_ATTEMPTS: 2,//重试次数 DELAY_BASE: 1000 // 基础延迟时间(毫秒) MAX_ATTEMPTS: 2//重试次数 }, SHOW_THINKING:process.env.SHOW_THINKING === 'true', IS_THINKING: false, IS_IMG_GEN: false, IS_IMG_GEN2: false, SSO_INDEX: 0,//sso的索引 ISSHOW_SEARCH_RESULTS: process.env.ISSHOW_SEARCH_RESULTS === 'true',//是否显示搜索结果,默认关闭 ISSHOW_SEARCH_RESULTS: process.env.ISSHOW_SEARCH_RESULTS === 'true',//是否显示搜索结果 CHROME_PATH: process.env.CHROME_PATH || "/usr/bin/chromium"//chrome路径};puppeteer.use(StealthPlugin())53 unmodified lines }
getTokenByIndex(index, model) { if (!this.modelRateLimit[model]) return; if(this.activeTokens.length === 0){ return null; }3 unmodified lines }
recordModelRequest(token, model) { if(model === 'grok-3-search' || model === 'grok-3-imageGen'){ model = 'grok-3'; }
if (!this.modelRateLimit[model]) return; const tokenFrequency = this.tokenModelFrequency.get(token); if (tokenFrequency && tokenFrequency[model] !== undefined) {2 unmodified lines this.checkAndRemoveTokenIfLimitReached(token); } setModelLimit(index, model) { if(model === 'grok-3-search' || model === 'grok-3-imageGen'){ model = 'grok-3'; } if (!this.modelRateLimit[model]) return; const tokenFrequency = this.tokenModelFrequency.get(this.activeTokens[index]); tokenFrequency[model] = 9999; } isTokenModelLimitReached(index, model) { if(model === 'grok-3-search' || model === 'grok-3-imageGen'){ model = 'grok-3'; } if (!this.modelRateLimit[model]) return; const token = this.activeTokens[index]; const tokenFrequency = this.tokenModelFrequency.get(token);37 unmodified lines if (now - expiredTime >= 2 * 60 * 60 * 1000) { this.tokenModelUsage.set(token, { "grok-3": 0, "grok-3-imageGen": 0, "grok-3-deepsearch": 0, "grok-3-reasoning": 0 });16 unmodified lines
class Utils { static async extractGrokHeaders() { console.log("开始提取头信息"); Logger.info("开始提取头信息", 'Server'); try { // 启动浏览器 const browser = await puppeteer.launch({12 unmodified lines await page.evaluate(() => { return new Promise(resolve => setTimeout(resolve, 5000)) }) console.log('等待5秒完成') // 获取所有 Cookies const cookies = await page.cookies(); const targetHeaders = ['x-anonuserid', 'x-challenge', 'x-signature'];8 unmodified lines // 关闭浏览器 await browser.close(); // 打印并返回提取的头信息 console.log('提取的头信息:', JSON.stringify(extractedHeaders, null, 2)); Logger.info('提取的头信息:', JSON.stringify(extractedHeaders, null, 2), 'Server'); return extractedHeaders;
} catch (error) { console.error('获取头信息出错:', error); Logger.error('获取头信息出错:', error, 'Server'); return null; } }1 unmodified line if (CONFIG.API.TEMP_COOKIE) { return CONFIG.API.TEMP_COOKIE; } console.log("刷新认证信息"); Logger.info("刷新认证信息", 'Server'); let retryCount = 0; while (!CONFIG.API.TEMP_COOKIE || retryCount < CONFIG.RETRY.MAX_ATTEMPTS) { let headers = await Utils.extractGrokHeaders(); if (headers) { console.log("获取认证信息成功"); Logger.info("获取认证信息成功", 'Server'); CONFIG.API.TEMP_COOKIE = { cookie: `x-anonuserid=${headers["x-anonuserid"]}; x-challenge=${headers["x-challenge"]}; x-signature=${headers["x-signature"]}` }; return; }3 unmodified lines } } } static async handleError(error, res) { // 如果是500错误且提供了原始请求函数,尝试重新获取签名并重试 if (String(error).includes("status: 500")) { try { await Utils.get_signature(); if (CONFIG.API.SIGNATURE_COOKIE) { return res.status(500).json({ error: { message: `${error.message}已重新刷新认证信息,请重新对话`, type: 'server_error', param: null, code: retryError.code || null } }); } else { return res.status(500).json({ error: { message: "认证信息获取失败", type: 'server_error', param: null, code: null } }); } } catch (error) { console.error('重试失败:', error); return res.status(500).json({ error: { message: `${error.message},认证信息获取失败`, type: 'server_error', param: null, code: error.code || null } }); } }
// 其他错误直接返回 res.status(500).json({ error: { message: error.message, type: 'server_error', param: null, code: error.code || null } }); } static async organizeSearchResults(searchResults) { // 确保传入的是有效的搜索结果对象 if (!searchResults || !searchResults.results) {11 unmodified lines }); return formattedResults.join('\n\n'); } static createAuthHeaders(model) { static async createAuthHeaders(model) { return { 'cookie': `${tokenManager.getTokenByIndex(CONFIG.SSO_INDEX, model)}` 'cookie': `${await tokenManager.getTokenByIndex(CONFIG.SSO_INDEX, model)}` }; }}47 unmodified lines content: imageBuffer } }; console.log("发送图片请求"); Logger.info("发送图片请求", 'Server'); // 发送请求 const response = await fetch(url, { method: 'POST',5 unmodified lines });
if (!response.ok) { console.error(`上传图片失败,状态码:${response.status},原因:${response.error}`); Logger.error(`上传图片失败,状态码:${response.status},原因:${response.error}`, 'Server'); return ''; }
const result = await response.json(); console.log('上传图片成功:', result); Logger.info('上传图片成功:', result, 'Server'); return result.fileMetadataId;
} catch (error) { console.error('上传图片失败:', error); Logger.error(error, 'Server'); return ''; } }
async prepareChatRequest(request) { if ((request.model === 'grok-2-imageGen' || request.model === 'grok-3-imageGen') && !CONFIG.API.PICGO_KEY) { throw new Error(`该模型需要配置PICGO图床密钥!`); if ((request.model === 'grok-2-imageGen' || request.model === 'grok-3-imageGen') && !CONFIG.API.PICGO_KEY && request.stream) { throw new Error(`该模型流式输出需要配置PICGO图床密钥!`); } // 处理画图模型的消息限制 let todoMessages = request.messages; if (request.model === 'grok-2-imageGen' || request.model === 'grok-3-imageGen') { const lastMessage = todoMessages[todoMessages.length - 1]; if (lastMessage.role !== 'user') { throw new Error('画图模型的最后一条消息必须是用户消息!'); } todoMessages = [lastMessage]; } const todoMessages = request.messages; const fileAttachments = []; let messages = ''; let lastRole = null; let lastContent = ''; const search = request.model === 'grok-2-search'; const search = request.model === 'grok-2-search' || request.model === 'grok-3-search'; // 移除<think>标签及其内容 // 移除<think>标签及其内容和base64图片 const removeThinkTags = (text) => { return text.replace(/<think>[\s\S]*?<\/think>/g, '').trim(); text = text.replace(/<think>[\s\S]*?<\/think>/g, '').trim(); text = text.replace(/!\[image\]\(data:.*?base64,.*?\)/g, '[图片]'); return text; }; const processImageUrl = async (content) => {66 unmodified lines return { modelName: this.modelId, message: messages.trim(), fileAttachments: fileAttachments.slice(0, 4), // 最多保留4张图片 fileAttachments: fileAttachments.slice(0, 4), imageAttachments: [], disableSearch: false, enableImageGeneration: true,64 unmodified lines } return result; } var token = linejosn?.token if (!token) return result;
//非生图模型的处理 switch (model) { case 'grok-2': result.token = token; result.token = linejosn?.token; return result; case 'grok-2-search': case 'grok-3-search': if (linejosn?.webSearchResults && CONFIG.ISSHOW_SEARCH_RESULTS) { result.token = `\r\n<think>${await Utils.organizeSearchResults(linejosn.webSearchResults)}</think>\r\n`; } else { result.token = token; result.token = linejosn?.token; } return result; case 'grok-3': result.token = token; result.token = linejosn?.token; return result; case 'grok-3-deepsearch': if (linejosn.messageTag === "final") { result.token = token; result.token = linejosn?.token; } return result; case 'grok-3-reasoning': if(linejosn?.isThinking && !CONFIG.SHOW_THINKING)return result;
if (linejosn?.isThinking && !CONFIG.IS_THINKING) { result.token = "<think>" + token; result.token = "<think>" + linejosn?.token; CONFIG.IS_THINKING = true; } else if (CONFIG.IS_THINKING && !linejosn.isThinking) { result.token = "</think>" + token; result.token = "</think>" + linejosn?.token; CONFIG.IS_THINKING = false; } else { result.token = token; result.token = linejosn?.token; } return result; }5 unmodified lines let buffer = ''; let fullResponse = ''; const dataPromises = [];
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => { stream.on('data', async (chunk) => { buffer += chunk.toString(); const lines = buffer.split('\n');2 unmodified lines for (const line of lines) { if (!line.trim()) continue; const trimmedLine = line.trim(); fs.appendFileSync(path.resolve(process.cwd(), 'response4.txt'), trimmedLine + '\n'); if (trimmedLine.startsWith('data: ')) { const data = trimmedLine.substring(6); try { if (!data.trim()) continue; if(data === "[DONE]")continue; if(data === "[DONE]") continue; const linejosn = JSON.parse(data); if (linejosn?.error) { Logger.error(JSON.stringify(linejosn,null,2), 'Server'); stream.destroy(); reject(new Error(linejosn)); reject(new Error("RateLimitError")); return; } if (linejosn?.doImgGen || linejosn?.imageAttachmentInfo) {20 unmodified lines })(); dataPromises.push(processPromise); } catch (error) { console.log(error); continue; } }13 unmodified lines } CONFIG.IS_IMG_GEN = false; CONFIG.IS_IMG_GEN2 = false; resolve(); resolve(); } catch (error) { reject(error); reject(error); } });
stream.on('error', (error) => { Logger.error(error, 'Server'); reject(error); reject(error); }); }); } catch (error) {2 unmodified lines CONFIG.IS_IMG_GEN2 = false; throw error; }
}
async function handleImageResponse(imageUrl) { //对服务器发送图片请求 const MAX_RETRIES = 3; const MAX_RETRIES = 2; let retryCount = 0; let imageBase64Response;
while (retryCount < MAX_RETRIES) { try { //发送图片请求获取图片 imageBase64Response = await fetch(`https://assets.grok.com/${imageUrl}`, { method: 'GET', headers: {2 unmodified lines } });
if (imageBase64Response.ok) { break; // 如果请求成功,跳出重试循环 }
if (imageBase64Response.ok) break; retryCount++; if (retryCount === MAX_RETRIES) { throw new Error(`上游服务请求失败! status: ${imageBase64Response.status}`); }
// 等待一段时间后重试(可以使用指数退避) await new Promise(resolve => setTimeout(resolve, CONFIG.API.RETRY_TIME * retryCount));
} catch (error) {1 unmodified line if (retryCount === MAX_RETRIES) { throw error; } // 等待一段时间后重试 await new Promise(resolve => setTimeout(resolve, CONFIG.API.RETRY_TIME * retryCount)); } }
const arrayBuffer = await imageBase64Response.arrayBuffer(); const imageBuffer = Buffer.from(arrayBuffer);
if(!CONFIG.API.PICGO_KEY){ const base64Image = imageBuffer.toString('base64'); const imageContentType = imageBase64Response.headers.get('content-type'); return `` }
const formData = new FormData();
formData.append('source', imageBuffer, {13 unmodified lines if (!responseURL.ok) { return "生图失败,请查看图床密钥是否设置正确" } else { console.log("生图成功"); Logger.info("生图成功", 'Server'); const result = await responseURL.json(); return `` }1 unmodified line
const tokenManager = new AuthTokenManager();await initialization();
// 中间件配置const app = express();app.use(Logger.requestLogger);4 unmodified lines methods: ['GET', 'POST', 'OPTIONS'], allowedHeaders: ['Content-Type', 'Authorization']}));// API路由app.get('/hf/v1/models', (req, res) => {
app.get('/v1/models', (req, res) => { res.json({ object: "list", data: Object.keys(CONFIG.MODELS).map((model, index) => ({6 unmodified lines});
app.post('/hf/v1/chat/completions', async (req, res) => {app.post('/v1/chat/completions', async (req, res) => { try { const authToken = req.headers.authorization?.replace('Bearer ', ''); if (authToken !== CONFIG.API.API_KEY) {1 unmodified line } let isTempCookie = req.body.model.includes("grok-2"); let retryCount = 0; const grokClient = new GrokApiClient(req.body.model); const requestPayload = await grokClient.prepareChatRequest(req.body); while (retryCount < CONFIG.RETRY.MAX_ATTEMPTS) { retryCount++; const grokClient = new GrokApiClient(req.body.model); const requestPayload = await grokClient.prepareChatRequest(req.body); console.log(JSON.stringify(requestPayload,null,2));
if (!CONFIG.API.TEMP_COOKIE) { await Utils.get_signature(); } //获取验证cookie
if (isTempCookie) { CONFIG.API.SIGNATURE_COOKIE = CONFIG.API.TEMP_COOKIE; Logger.info(`已切换为临时令牌`, 'Server'); } else { CONFIG.API.SIGNATURE_COOKIE = Utils.createAuthHeaders(req.body.model); CONFIG.API.SIGNATURE_COOKIE = await Utils.createAuthHeaders(req.body.model); } Logger.info(`当前令牌索引: ${CONFIG.SSO_INDEX}`, 'Server'); const newMessageReq = await fetch(`${CONFIG.API.BASE_URL}/api/rpc`, {12 unmodified lines
const responseText = await newMessageReq.json(); const conversationId = responseText.conversationId; //发送对话
const response = await fetch(`${CONFIG.API.BASE_URL}/api/conversations/${conversationId}/responses`, { method: 'POST', headers: {12 unmodified lines Logger.info(`当前剩余可用令牌数: ${tokenManager.getTokenCount()}`, 'Server'); try { await handleResponse(response, req.body.model, res, req.body.stream); return; // 成功后直接返回 return; } catch (error) { if(isTempCookie){ await Utils.get_signature();10 unmodified lines } } } else { // 处理429错误 if (response.status === 429) { if (isTempCookie) { await Utils.get_signature();36 unmodified lines});
// 404处理app.use((req, res) => { res.status(200).send('api运行正常');});
// 启动服务器
app.listen(CONFIG.SERVER.PORT, () => { console.log(`服务器已启动,监听端口: ${CONFIG.SERVER.PORT}`); Logger.info(`服务器已启动,监听端口: ${CONFIG.SERVER.PORT}`, 'Server');});index.js+88-120