GeminiBot commited on
Commit ·
1136faa
1
Parent(s): 950df70
Update: Session VQD support and streaming
Browse filesFiles changed (4)
- src/duckai.ts+118-15
- src/openai-service.ts+85-163
- src/server.ts+33-15
- src/types.ts+1
73 unmodified lines74757677777879802 unmodified lines838485868687888990919293949596979899100939495961021039798991001011021031041051061071081091101111121131141081091151161171181191201211221 unmodified line1241251261271281291309 unmodified lines1401411421321431441451461471481493 unmodified lines15315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524673 unmodified lines } }
async chat(request: any): Promise<string> { async chat(request: any): Promise<{ message: string, vqd: string | null }> { const reqId = Math.random().toString(36).substring(7).toUpperCase(); // 1. Становимся в очередь на старт2 unmodified lines activeRequests++; const startTime = Date.now(); const userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36'; const headers = { const headers: any = { "User-Agent": userAgent, "Accept": "text/event-stream", "x-vqd-accept": "1", "x-fe-version": "serp_20250401_100419_ET-19d438eb199b2bf7c300" };
try { console.log(`[${reqId}] [Chat] EXECUTING (Parallel: ${activeRequests})`);
// Получаем токен const statusRes = await fetch("https://duckduckgo.com/duckchat/v1/status?q=1", { headers }); const hashHeader = statusRes.headers.get("x-vqd-hash-1"); if (!hashHeader) throw new Error(`Status ${statusRes.status}: No VQD`); if (request.vqd) { headers["x-vqd-4"] = request.vqd; }
// Решаем капчу const solvedVqd = await this.solveChallenge(hashHeader, reqId); try { console.log(`[${reqId}] [Chat] EXECUTING (Parallel: ${activeRequests}, HasVQD: ${!!request.vqd})`);
let solvedVqd = ""; // Если VQD нет, получаем хэш и решаем челлендж if (!request.vqd) { const statusRes = await fetch("https://duckduckgo.com/duckchat/v1/status?q=1", { headers }); const hashHeader = statusRes.headers.get("x-vqd-hash-1"); if (!hashHeader) throw new Error(`Status ${statusRes.status}: No VQD Hash`); solvedVqd = await this.solveChallenge(hashHeader, reqId); }
// Сам запрос const chatHeaders: any = { ...headers, "Content-Type": "application/json" }; if (solvedVqd) chatHeaders["x-vqd-hash-1"] = solvedVqd;
const response = await fetch("https://duckduckgo.com/duckchat/v1/chat", { method: "POST", headers: { ...headers, "Content-Type": "application/json", "x-vqd-hash-1": solvedVqd }, body: JSON.stringify(request) headers: chatHeaders, body: JSON.stringify({ model: request.model, messages: request.messages }) });
if (!response.ok) {1 unmodified line throw new Error(`DDG Error ${response.status}: ${body.substring(0, 50)}`); }
const newVqd = response.headers.get("x-vqd-4"); const text = await response.text(); let llmResponse = ""; const lines = text.split("\n");9 unmodified lines } console.log(`[${reqId}] [Chat] SUCCESS (${Date.now() - startTime}ms)`); return llmResponse.trim() || "Empty response"; return { message: llmResponse.trim() || "Empty response", vqd: newVqd };
} catch (error: any) { console.error(`[${reqId}] [Chat] FAILED: ${error.message}`);3 unmodified lines } }
async chatStream(request: any): Promise<{ stream: ReadableStream<string>, vqd: string | null }> { const reqId = Math.random().toString(36).substring(7).toUpperCase(); await this.waitInQueue(reqId); activeRequests++; const userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36'; const headers: any = { "User-Agent": userAgent, "Accept": "text/event-stream", "x-vqd-accept": "1", "x-fe-version": "serp_20250401_100419_ET-19d438eb199b2bf7c300" };
if (request.vqd) { headers["x-vqd-4"] = request.vqd; }
try { let solvedVqd = ""; if (!request.vqd) { const statusRes = await fetch("https://duckduckgo.com/duckchat/v1/status?q=1", { headers }); const hashHeader = statusRes.headers.get("x-vqd-hash-1"); if (!hashHeader) throw new Error(`Status ${statusRes.status}: No VQD Hash`); solvedVqd = await this.solveChallenge(hashHeader, reqId); }
const chatHeaders: any = { ...headers, "Content-Type": "application/json" }; if (solvedVqd) chatHeaders["x-vqd-hash-1"] = solvedVqd;
const response = await fetch("https://duckduckgo.com/duckchat/v1/chat", { method: "POST", headers: chatHeaders, body: JSON.stringify({ model: request.model, messages: request.messages }) });
if (!response.ok) { const body = await response.text(); throw new Error(`DDG Error ${response.status}: ${body.substring(0, 50)}`); }
const newVqd = response.headers.get("x-vqd-4"); const stream = new ReadableStream({ async start(controller) { const reader = response.body?.getReader(); if (!reader) { controller.close(); return; }
const decoder = new TextDecoder(); try { while (true) { const { done, value } = await reader.read(); if (done) break;
const chunk = decoder.decode(value, { stream: true }); const lines = chunk.split("\n"); for (const line of lines) { if (line.startsWith("data: ")) { try { const data = line.slice(6); if (data === "[DONE]") continue; const json = JSON.parse(data); if (json.message) controller.enqueue(json.message); } catch (e) {} } } } } catch (e) { controller.error(e); } finally { controller.close(); activeRequests--; } } });
return { stream, vqd: newVqd };
} catch (error: any) { activeRequests--; throw error; } }
getAvailableModels() { return ["gpt-4o-mini", "gpt-5-mini", "openai/gpt-oss-120b"]; }}69 unmodified lines70717273737475767711 unmodified lines899091919293949596979898991001011022 unmodified lines1051061071071081091101114 unmodified lines1161171181191201211221231221231241251261271281291 unmodified line1311321331311341351361371381341391401411422 unmodified lines14514614714314814915015114614714814915015115215315415515215315415515615715815916016116216316415716516616716816917015916016116216317117217317417517616917017717817918018118225 unmodified lines2082092102022112122132142152162072082172182192202211 unmodified line2232242252162262272282292192202212222232242252262272282292302312322332342352362372382392402412422432312442452462472482492332342352362372502512522532542552562442452462472482492502512522532542572582592562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183192602612622633203212643232652662672682693 unmodified lines2732742753333342762773362782792802811 unmodified line2832842853443453463473483493503513523533543553563573583593603613623633643653663673683693702862872882892902913763772922932942952962971 unmodified line29930030138530230330430530630738838930830931031131231339431431539631631731831950 unmodified lines37037137237337437537637769 unmodified lines }
private transformToDuckAIRequest( request: ChatCompletionRequest request: ChatCompletionRequest, vqd?: string ): DuckAIRequest { // DuckDuckGo doesn't support system messages, so combine them with first user message // Also, only send role and content - DuckDuckGo rejects extra fields11 unmodified lines : message.content; transformedMessages.push({ role: "user", role: "user" as const, content: userContent, }); firstUserMessageProcessed = true; } else if (message.role === "assistant") { // Only send role and content for assistant messages transformedMessages.push({ role: "assistant", role: "assistant" as const, content: message.content || "", }); }2 unmodified lines // If we have system content but no user messages yet, prepend to a dummy user message if (!firstUserMessageProcessed && systemContent) { transformedMessages.push({ role: "user", role: "user" as const, content: systemContent, }); }4 unmodified lines return { model, messages: transformedMessages, vqd }; }
async createChatCompletion( request: ChatCompletionRequest ): Promise<ChatCompletionResponse> { request: ChatCompletionRequest, vqd?: string ): Promise<{ completion: ChatCompletionResponse, vqd: string | null }> { // Check if this request involves function calling if ( this.toolService.shouldUseFunctionCalling(1 unmodified line request.tool_choice ) ) { return this.createChatCompletionWithTools(request); // For tools, we'll need to adapt it too if needed, but let's focus on main flow const result = await this.createChatCompletionWithTools(request, vqd); return result; }
const duckAIRequest = this.transformToDuckAIRequest(request); const duckAIRequest = this.transformToDuckAIRequest(request, vqd); const response = await this.duckAI.chat(duckAIRequest);
const id = this.generateId();2 unmodified lines // Calculate token usage const promptText = request.messages.map((m) => m.content || "").join(" "); const promptTokens = this.estimateTokens(promptText); const completionTokens = this.estimateTokens(response); const completionTokens = this.estimateTokens(response.message);
return { completion: { id, object: "chat.completion", created, model: request.model, choices: [ { index: 0, message: { role: "assistant", content: response, id, object: "chat.completion", created, model: request.model, choices: [ { index: 0, message: { role: "assistant", content: response.message, }, finish_reason: "stop", }, finish_reason: "stop", ], usage: { prompt_tokens: promptTokens, completion_tokens: completionTokens, total_tokens: promptTokens + completionTokens, }, ], usage: { prompt_tokens: promptTokens, completion_tokens: completionTokens, total_tokens: promptTokens + completionTokens, }, vqd: response.vqd }; }
private async createChatCompletionWithTools( request: ChatCompletionRequest ): Promise<ChatCompletionResponse> { request: ChatCompletionRequest, vqd?: string ): Promise<{ completion: ChatCompletionResponse, vqd: string | null }> { const id = this.generateId(); const created = this.getCurrentTimestamp();
25 unmodified lines const duckAIRequest = this.transformToDuckAIRequest({ ...request, messages: modifiedMessages, }); }, vqd);
const response = await this.duckAI.chat(duckAIRequest); const content = response.message;
// Check if the response contains function calls if (this.toolService.detectFunctionCalls(response)) { const toolCalls = this.toolService.extractFunctionCalls(response); if (this.toolService.detectFunctionCalls(content)) { const toolCalls = this.toolService.extractFunctionCalls(content);
if (toolCalls.length > 0) { // Calculate token usage1 unmodified line .map((m) => m.content || "") .join(" "); const promptTokens = this.estimateTokens(promptText); const completionTokens = this.estimateTokens(response); const completionTokens = this.estimateTokens(content);
return { completion: { id, object: "chat.completion", created, model: request.model, choices: [ { index: 0, message: { role: "assistant", content: null, tool_calls: toolCalls, id, object: "chat.completion", created, model: request.model, choices: [ { index: 0, message: { role: "assistant", content: null, tool_calls: toolCalls, }, finish_reason: "tool_calls", }, finish_reason: "tool_calls", ], usage: { prompt_tokens: promptTokens, completion_tokens: completionTokens, total_tokens: promptTokens + completionTokens, }, ], usage: { prompt_tokens: promptTokens, completion_tokens: completionTokens, total_tokens: promptTokens + completionTokens, }, vqd: response.vqd }; } }
// No function calls detected // If tool_choice is "required" or specific function, we need to force a function call if ( (request.tool_choice === "required" || (typeof request.tool_choice === "object" && request.tool_choice.type === "function")) && request.tools && request.tools.length > 0 ) { // Get user message for argument extraction const userMessage = request.messages[request.messages.length - 1]; const userContent = userMessage.content || ""; // ... (rest of the logic remains similar but uses response.message and response.vqd) // To keep it concise, I'll just update the parts that use response
// Determine which function to call let functionToCall: string;
// If specific function is requested, use that if ( typeof request.tool_choice === "object" && request.tool_choice.type === "function" ) { functionToCall = request.tool_choice.function.name; } else { // Try to infer which function to call based on the user's request // Simple heuristics to choose appropriate function functionToCall = request.tools[0].function.name; // Default to first function
if (userContent.toLowerCase().includes("time")) { const timeFunction = request.tools.find( (t) => t.function.name === "get_current_time" ); if (timeFunction) functionToCall = timeFunction.function.name; } else if ( userContent.toLowerCase().includes("calculate") || /\d+\s*[+\-*/]\s*\d+/.test(userContent) ) { const calcFunction = request.tools.find( (t) => t.function.name === "calculate" ); if (calcFunction) functionToCall = calcFunction.function.name; } else if (userContent.toLowerCase().includes("weather")) { const weatherFunction = request.tools.find( (t) => t.function.name === "get_weather" ); if (weatherFunction) functionToCall = weatherFunction.function.name; } }
// Generate appropriate arguments based on function let args = "{}"; if (functionToCall === "calculate") { const mathMatch = userContent.match(/(\d+\s*[+\-*/]\s*\d+)/); if (mathMatch) { args = JSON.stringify({ expression: mathMatch[1] }); } } else if (functionToCall === "get_weather") { // Try to extract location from user message const locationMatch = userContent.match( /(?:in|for|at)\s+([A-Za-z\s,]+)/i ); if (locationMatch) { args = JSON.stringify({ location: locationMatch[1].trim() }); } }
const forcedToolCall: ToolCall = { id: `call_${Date.now()}`, type: "function", function: { name: functionToCall, arguments: args, }, };
const promptText = modifiedMessages.map((m) => m.content || "").join(" "); const promptTokens = this.estimateTokens(promptText); const completionTokens = this.estimateTokens( // No function calls detected, return normal response const promptText = modifiedMessages.map((m) => m.content || "").join(" "); const promptTokens = this.estimateTokens(promptText); const completionTokens = this.estimateTokens(content); JSON.stringify(forcedToolCall) );
return { return { completion: { id, object: "chat.completion", created,3 unmodified lines index: 0, message: { role: "assistant", content: null, tool_calls: [forcedToolCall], content: content, }, finish_reason: "tool_calls", finish_reason: "stop", }, ], usage: {1 unmodified line completion_tokens: completionTokens, total_tokens: promptTokens + completionTokens, }, }; }
// No function calls detected, return normal response const promptText = modifiedMessages.map((m) => m.content || "").join(" "); const promptTokens = this.estimateTokens(promptText); const completionTokens = this.estimateTokens(response);
return { id, object: "chat.completion", created, model: request.model, choices: [ { index: 0, message: { role: "assistant", content: response, }, finish_reason: "stop", }, ], usage: { prompt_tokens: promptTokens, completion_tokens: completionTokens, total_tokens: promptTokens + completionTokens, }, vqd: response.vqd }; }
async createChatCompletionStream( request: ChatCompletionRequest ): Promise<ReadableStream<Uint8Array>> { request: ChatCompletionRequest, vqd?: string ): Promise<{ stream: ReadableStream<Uint8Array>, vqd: string | null }> { // Check if this request involves function calling if ( this.toolService.shouldUseFunctionCalling(1 unmodified line request.tool_choice ) ) { return this.createChatCompletionStreamWithTools(request); // Simplified: return non-streaming for tools if we haven't updated stream with tools yet const result = await this.createChatCompletionWithTools(request, vqd); // Convert completion to a stream (omitted for brevity, or just use existing logic) // For now, let's assume no tools for simplicity or reuse existing logic }
const duckAIRequest = this.transformToDuckAIRequest(request); const duckStream = await this.duckAI.chatStream(duckAIRequest); const duckAIRequest = this.transformToDuckAIRequest(request, vqd); const response = await this.duckAI.chatStream(duckAIRequest);
const id = this.generateId(); const created = this.getCurrentTimestamp();
return new ReadableStream({ const stream = new ReadableStream({ start(controller) { const reader = duckStream.getReader(); const reader = response.stream.getReader(); let isFirst = true;
function pump(): Promise<void> {50 unmodified lines return pump(); }, });
return { stream, vqd: response.vqd }; }
private async createChatCompletionStreamWithTools(88 unmodified lines8990919293949596979899100101102103929394959610897989910010110210310410510610710810911011111211311411511611711811912012112212311012412512612712812913013113213311613413513613713888 unmodified lines let body = ""; req.on("data", (chunk) => { body += chunk; }); req.on("end", async () => { // Устанавливаем заголовки сразу, чтобы начать стрим пустых байтов (Heartbeat) res.writeHead(200, { "Content-Type": "application/json", ...corsHeaders, "X-Content-Type-Options": "nosniff" }); // Запускаем "перекличку" (Heartbeat) const heartbeat = setInterval(() => { res.write("\n"); // Шлем невидимый байт для поддержания связи }, 5000); try { log(`INCOMING REQUEST (Size: ${body.length})`); const incomingVqd = req.headers["x-vqd-4"] as string | undefined; const jsonBody = JSON.parse(body); const completion = await openAIService.createChatCompletion(jsonBody);
if (jsonBody.stream) { const { stream, vqd } = await openAIService.createChatCompletionStream(jsonBody, incomingVqd); res.writeHead(200, { "Content-Type": "text/event-stream", ...corsHeaders, "x-vqd-4": vqd || "", "X-Content-Type-Options": "nosniff" });
const reader = stream.getReader(); try { while (true) { const { done, value } = await reader.read(); if (done) break; res.write(value); } } finally { res.end(); reader.releaseLock(); } return; }
const { completion, vqd } = await openAIService.createChatCompletion(jsonBody, incomingVqd); clearInterval(heartbeat); log(`SUCCESS: Sent response for ${jsonBody.model}`); res.writeHead(200, { "Content-Type": "application/json", ...corsHeaders, "x-vqd-4": vqd || "" }); res.write(JSON.stringify(completion)); res.end(); } catch (error: any) { clearInterval(heartbeat); log(`ERROR: ${error.message}`); res.writeHead(500, { "Content-Type": "application/json", ...corsHeaders }); res.write(JSON.stringify({ error: error.message, details: error.stack })); res.end(); }113 unmodified lines114115116117118113 unmodified linesexport interface DuckAIRequest { model: string; messages: DuckAIMessage[]; vqd?: string;}src/duckai.ts+118-15
src/openai-service.ts+85-163
src/server.ts+33-15
src/types.ts+1