Files
OmniRoute/open-sse/executors/chatgptWebTools.ts
Diego Rodrigues de Sa e Souza 98c9f5b136 fix(chatgpt-web): wire tool/function calling via shared webTools shim (#5240) (#5349)
Integrated into release/v3.8.41 — wire tool/function calling into chatgpt-web via shared webTools shim (#5240). Test: chatgpt-web-tools-5240 green (4/4).
2026-06-29 11:21:47 -03:00

120 lines
4.1 KiB
TypeScript

// Tool-call emulation helpers for the ChatGPT Web executor (#5240).
//
// chatgpt.com has no native function calling. When the OpenAI request carries
// `tools`, the prompt-side shim (`prepareToolMessages` in
// ../translator/webTools.ts) injects a `<tool>` contract; on the response side
// we parse `<tool>{...}</tool>` blocks back into OpenAI `tool_calls` —
// mirroring the sibling web-session executors (qwen-web, perplexity-web, ...).
//
// The whole tool-mode orchestration lives here so the (frozen) chatgpt-web.ts
// only gains an import + a single delegating call.
import { buildToolAwareResult } from "../translator/webTools.ts";
const SSE_HEADERS: Record<string, string> = {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
};
function sseChunk(data: unknown): string {
return `data: ${JSON.stringify(data)}\n\n`;
}
/**
* Parse any `<tool>` blocks in a buffered JSON completion's assistant content
* into OpenAI tool_calls and rewrite the choice. On parse failure the original
* body passes through untouched.
*/
async function applyToolCallsToJsonResponse(
response: Response,
requestedTools: unknown
): Promise<Response> {
const bodyText = await response.text();
try {
const json = JSON.parse(bodyText);
const rawContent = json?.choices?.[0]?.message?.content || "";
const { content, toolCalls, finishReason } = buildToolAwareResult(
rawContent,
requestedTools,
"cgpt"
);
if (toolCalls) {
json.choices[0].message = { role: "assistant", content: null, tool_calls: toolCalls };
json.choices[0].finish_reason = finishReason;
} else {
json.choices[0].message.content = content;
}
return new Response(JSON.stringify(json), {
status: response.status,
headers: { "Content-Type": "application/json" },
});
} catch {
return new Response(bodyText, {
status: response.status,
headers: { "Content-Type": "application/json" },
});
}
}
/**
* Replay an already-built OpenAI `chat.completion` object as a buffered SSE
* stream: a role chunk, then a single terminal chunk carrying either
* `delta.tool_calls` + `finish_reason: "tool_calls"` or plain content +
* `finish_reason: "stop"`. No token-by-token streaming while tools are active.
*/
function toolCompletionToSseStream(
completion: Record<string, unknown>,
cid: string,
created: number,
model: string
): ReadableStream<Uint8Array> {
const encoder = new TextEncoder();
const choice = (completion?.choices as Array<Record<string, unknown>> | undefined)?.[0] ?? {};
const message = (choice.message as Record<string, unknown>) ?? {};
const finishReason = (choice.finish_reason as string) ?? "stop";
const chunk = (delta: Record<string, unknown>, fr: string | null): Uint8Array =>
encoder.encode(
sseChunk({
id: cid,
object: "chat.completion.chunk",
created,
model,
system_fingerprint: null,
choices: [{ index: 0, delta, finish_reason: fr, logprobs: null }],
})
);
return new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(chunk({ role: "assistant" }, null));
const delta = message.tool_calls
? { tool_calls: message.tool_calls }
: { content: (message.content as string) ?? "" };
controller.enqueue(chunk(delta, finishReason));
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
controller.close();
},
});
}
/**
* Tool mode: parse `<tool>` blocks in an already-buffered JSON completion into
* tool_calls, then return either the JSON completion (non-streaming) or a
* terminal SSE replay of it (streaming).
*/
export async function buildToolModeResponse(
bufferedJson: Response,
requestedTools: unknown,
stream: boolean,
meta: { cid: string; created: number; model: string }
): Promise<Response> {
const jsonResponse = await applyToolCallsToJsonResponse(bufferedJson, requestedTools);
if (!stream) return jsonResponse;
const completion = await jsonResponse.json();
return new Response(toolCompletionToSseStream(completion, meta.cid, meta.created, meta.model), {
status: 200,
headers: SSE_HEADERS,
});
}