@copilotkit/aimock 1.8.0 → 1.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +2 -0
- package/dist/a2a-types.d.ts.map +1 -1
- package/dist/bedrock-converse.cjs +6 -4
- package/dist/bedrock-converse.cjs.map +1 -1
- package/dist/bedrock-converse.d.cts.map +1 -1
- package/dist/bedrock-converse.d.ts.map +1 -1
- package/dist/bedrock-converse.js +7 -5
- package/dist/bedrock-converse.js.map +1 -1
- package/dist/bedrock.cjs +6 -4
- package/dist/bedrock.cjs.map +1 -1
- package/dist/bedrock.d.cts.map +1 -1
- package/dist/bedrock.d.ts.map +1 -1
- package/dist/bedrock.js +7 -5
- package/dist/bedrock.js.map +1 -1
- package/dist/cohere.cjs +3 -2
- package/dist/cohere.cjs.map +1 -1
- package/dist/cohere.d.cts.map +1 -1
- package/dist/cohere.d.ts.map +1 -1
- package/dist/cohere.js +4 -3
- package/dist/cohere.js.map +1 -1
- package/dist/embeddings.cjs +3 -2
- package/dist/embeddings.cjs.map +1 -1
- package/dist/embeddings.d.cts.map +1 -1
- package/dist/embeddings.d.ts.map +1 -1
- package/dist/embeddings.js +4 -3
- package/dist/embeddings.js.map +1 -1
- package/dist/gemini.cjs +105 -30
- package/dist/gemini.cjs.map +1 -1
- package/dist/gemini.d.cts.map +1 -1
- package/dist/gemini.d.ts.map +1 -1
- package/dist/gemini.js +106 -31
- package/dist/gemini.js.map +1 -1
- package/dist/helpers.cjs +150 -14
- package/dist/helpers.cjs.map +1 -1
- package/dist/helpers.d.cts.map +1 -1
- package/dist/helpers.d.ts.map +1 -1
- package/dist/helpers.js +147 -15
- package/dist/helpers.js.map +1 -1
- package/dist/index.cjs +1 -0
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/journal.cjs +26 -9
- package/dist/journal.cjs.map +1 -1
- package/dist/journal.d.cts +10 -5
- package/dist/journal.d.cts.map +1 -1
- package/dist/journal.d.ts +10 -5
- package/dist/journal.d.ts.map +1 -1
- package/dist/journal.js +26 -10
- package/dist/journal.js.map +1 -1
- package/dist/llmock.cjs +2 -2
- package/dist/llmock.cjs.map +1 -1
- package/dist/llmock.d.cts +1 -1
- package/dist/llmock.d.ts +1 -1
- package/dist/llmock.js +2 -2
- package/dist/llmock.js.map +1 -1
- package/dist/messages.cjs +192 -2
- package/dist/messages.cjs.map +1 -1
- package/dist/messages.d.cts.map +1 -1
- package/dist/messages.d.ts.map +1 -1
- package/dist/messages.js +193 -3
- package/dist/messages.js.map +1 -1
- package/dist/ollama.cjs +6 -4
- package/dist/ollama.cjs.map +1 -1
- package/dist/ollama.d.cts.map +1 -1
- package/dist/ollama.d.ts.map +1 -1
- package/dist/ollama.js +7 -5
- package/dist/ollama.js.map +1 -1
- package/dist/responses.cjs +250 -126
- package/dist/responses.cjs.map +1 -1
- package/dist/responses.d.cts.map +1 -1
- package/dist/responses.d.ts.map +1 -1
- package/dist/responses.js +251 -127
- package/dist/responses.js.map +1 -1
- package/dist/server.cjs +42 -5
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts.map +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +43 -6
- package/dist/server.js.map +1 -1
- package/dist/stream-collapse.cjs +48 -40
- package/dist/stream-collapse.cjs.map +1 -1
- package/dist/stream-collapse.d.cts.map +1 -1
- package/dist/stream-collapse.d.ts.map +1 -1
- package/dist/stream-collapse.js +48 -40
- package/dist/stream-collapse.js.map +1 -1
- package/dist/types.d.cts +9 -1
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.ts +9 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/ws-gemini-live.cjs +4 -2
- package/dist/ws-gemini-live.cjs.map +1 -1
- package/dist/ws-gemini-live.d.cts +1 -0
- package/dist/ws-gemini-live.d.ts +1 -0
- package/dist/ws-gemini-live.js +4 -2
- package/dist/ws-gemini-live.js.map +1 -1
- package/dist/ws-realtime.cjs +4 -2
- package/dist/ws-realtime.cjs.map +1 -1
- package/dist/ws-realtime.d.cts +1 -0
- package/dist/ws-realtime.d.ts +1 -0
- package/dist/ws-realtime.js +4 -2
- package/dist/ws-realtime.js.map +1 -1
- package/dist/ws-responses.cjs +4 -2
- package/dist/ws-responses.cjs.map +1 -1
- package/dist/ws-responses.d.cts +1 -0
- package/dist/ws-responses.d.ts +1 -0
- package/dist/ws-responses.js +4 -2
- package/dist/ws-responses.js.map +1 -1
- package/package.json +1 -1
package/dist/ollama.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ollama.js","names":[],"sources":["../src/ollama.ts"],"sourcesContent":["/**\n * Ollama API endpoint support.\n *\n * Translates incoming /api/chat and /api/generate requests into the\n * ChatCompletionRequest format used by the fixture router, and converts\n * fixture responses back into Ollama's NDJSON streaming or non-streaming format.\n *\n * Key differences from OpenAI:\n * - Ollama defaults to stream: true (opposite of OpenAI)\n * - Streaming uses NDJSON, not SSE\n * - Tool call arguments are objects, not JSON strings\n * - Tool calls have no id field\n */\n\nimport type * as http from \"node:http\";\nimport type {\n ChatCompletionRequest,\n ChatMessage,\n Fixture,\n HandlerDefaults,\n ToolCall,\n ToolDefinition,\n} from \"./types.js\";\nimport { isTextResponse, isToolCallResponse, isErrorResponse, flattenHeaders } from \"./helpers.js\";\nimport { matchFixture } from \"./router.js\";\nimport { writeErrorResponse } from \"./sse-writer.js\";\nimport { writeNDJSONStream } from \"./ndjson-writer.js\";\nimport { createInterruptionSignal } from \"./interruption.js\";\nimport type { Journal } from \"./journal.js\";\nimport type { Logger } from \"./logger.js\";\nimport { applyChaos } from \"./chaos.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\n\n// ─── Ollama request types ────────────────────────────────────────────────────\n\ninterface OllamaMessage {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string;\n}\n\ninterface OllamaToolDef {\n type: string;\n function: {\n name: string;\n description?: string;\n parameters?: object;\n };\n}\n\ninterface OllamaRequest {\n model: string;\n messages: OllamaMessage[];\n stream?: boolean; // default true!\n options?: { temperature?: number; num_predict?: number };\n tools?: OllamaToolDef[];\n}\n\ninterface OllamaGenerateRequest {\n model: string;\n prompt: string;\n stream?: boolean; // default true!\n options?: { temperature?: number; num_predict?: number };\n}\n\n// ─── Duration fields (zeroed, required on final/non-streaming responses) ────\n\nconst DURATION_FIELDS = {\n done_reason: \"stop\" as const,\n total_duration: 0,\n load_duration: 0,\n prompt_eval_count: 0,\n prompt_eval_duration: 0,\n eval_count: 0,\n eval_duration: 0,\n};\n\n// ─── Input conversion: Ollama → ChatCompletionRequest ────────────────────────\n\nexport function ollamaToCompletionRequest(req: OllamaRequest): ChatCompletionRequest {\n const messages: ChatMessage[] = [];\n\n for (const msg of req.messages) {\n messages.push({\n role: msg.role as ChatMessage[\"role\"],\n content: msg.content,\n });\n }\n\n // Convert tools\n let tools: ToolDefinition[] | undefined;\n if (req.tools && req.tools.length > 0) {\n tools = req.tools.map((t) => ({\n type: \"function\" as const,\n function: {\n name: t.function.name,\n description: t.function.description,\n parameters: t.function.parameters,\n },\n }));\n }\n\n return {\n model: req.model,\n messages,\n stream: req.stream,\n temperature: req.options?.temperature,\n max_tokens: req.options?.num_predict,\n tools,\n };\n}\n\nfunction ollamaGenerateToCompletionRequest(req: OllamaGenerateRequest): ChatCompletionRequest {\n return {\n model: req.model,\n messages: [{ role: \"user\", content: req.prompt }],\n stream: req.stream,\n temperature: req.options?.temperature,\n max_tokens: req.options?.num_predict,\n };\n}\n\n// ─── Response builders: /api/chat ────────────────────────────────────────────\n\nfunction buildOllamaChatTextChunks(\n content: string,\n model: string,\n chunkSize: number,\n reasoning?: string,\n): object[] {\n const chunks: object[] = [];\n\n // Reasoning chunks (before content)\n if (reasoning) {\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n chunks.push({\n model,\n message: { role: \"assistant\", content: \"\", reasoning_content: slice },\n done: false,\n });\n }\n }\n\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n chunks.push({\n model,\n message: { role: \"assistant\", content: slice },\n done: false,\n });\n }\n\n // Final chunk with done: true and all duration fields\n chunks.push({\n model,\n message: { role: \"assistant\", content: \"\" },\n done: true,\n ...DURATION_FIELDS,\n });\n\n return chunks;\n}\n\nfunction buildOllamaChatTextResponse(content: string, model: string, reasoning?: string): object {\n return {\n model,\n message: {\n role: \"assistant\",\n content,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n },\n done: true,\n ...DURATION_FIELDS,\n };\n}\n\nfunction buildOllamaChatToolCallChunks(\n toolCalls: ToolCall[],\n model: string,\n logger: Logger,\n): object[] {\n const ollamaToolCalls = toolCalls.map((tc) => {\n let argsObj: unknown;\n try {\n argsObj = JSON.parse(tc.arguments || \"{}\");\n } catch {\n logger.warn(\n `Malformed JSON in fixture tool call arguments for \"${tc.name}\": ${tc.arguments}`,\n );\n argsObj = {};\n }\n return {\n function: {\n name: tc.name,\n arguments: argsObj,\n },\n };\n });\n\n // Tool calls are sent in a single chunk (no streaming of individual args)\n const chunks: object[] = [];\n chunks.push({\n model,\n message: {\n role: \"assistant\",\n content: \"\",\n tool_calls: ollamaToolCalls,\n },\n done: false,\n });\n\n // Final chunk\n chunks.push({\n model,\n message: { role: \"assistant\", content: \"\" },\n done: true,\n ...DURATION_FIELDS,\n });\n\n return chunks;\n}\n\nfunction buildOllamaChatToolCallResponse(\n toolCalls: ToolCall[],\n model: string,\n logger: Logger,\n): object {\n const ollamaToolCalls = toolCalls.map((tc) => {\n let argsObj: unknown;\n try {\n argsObj = JSON.parse(tc.arguments || \"{}\");\n } catch {\n logger.warn(\n `Malformed JSON in fixture tool call arguments for \"${tc.name}\": ${tc.arguments}`,\n );\n argsObj = {};\n }\n return {\n function: {\n name: tc.name,\n arguments: argsObj,\n },\n };\n });\n\n return {\n model,\n message: {\n role: \"assistant\",\n content: \"\",\n tool_calls: ollamaToolCalls,\n },\n done: true,\n ...DURATION_FIELDS,\n };\n}\n\n// ─── Response builders: /api/generate ────────────────────────────────────────\n\nfunction buildOllamaGenerateTextChunks(\n content: string,\n model: string,\n chunkSize: number,\n reasoning?: string,\n): object[] {\n const chunks: object[] = [];\n const createdAt = new Date().toISOString();\n\n // Reasoning chunks (before content)\n if (reasoning) {\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n chunks.push({\n model,\n created_at: createdAt,\n response: \"\",\n reasoning_content: slice,\n done: false,\n });\n }\n }\n\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n chunks.push({\n model,\n created_at: createdAt,\n response: slice,\n done: false,\n });\n }\n\n // Final chunk\n chunks.push({\n model,\n created_at: createdAt,\n response: \"\",\n done: true,\n ...DURATION_FIELDS,\n context: [],\n });\n\n return chunks;\n}\n\nfunction buildOllamaGenerateTextResponse(\n content: string,\n model: string,\n reasoning?: string,\n): object {\n return {\n model,\n created_at: new Date().toISOString(),\n response: content,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n done: true,\n ...DURATION_FIELDS,\n context: [],\n };\n}\n\n// ─── Request handler: /api/chat ──────────────────────────────────────────────\n\nexport async function handleOllama(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n): Promise<void> {\n const { logger } = defaults;\n setCorsHeaders(res);\n\n const urlPath = req.url ?? \"/api/chat\";\n\n let ollamaReq: OllamaRequest;\n try {\n ollamaReq = JSON.parse(raw) as OllamaRequest;\n } catch {\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Malformed JSON\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n if (!ollamaReq.messages || !Array.isArray(ollamaReq.messages)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Invalid request: messages array is required\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Convert to ChatCompletionRequest for fixture matching\n const completionReq = ollamaToCompletionRequest(ollamaReq);\n\n const fixture = matchFixture(\n fixtures,\n completionReq,\n journal.fixtureMatchCounts,\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures);\n }\n\n if (\n applyChaos(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n journal,\n {\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n },\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n if (defaults.record) {\n const proxied = await proxyAndRecord(\n req,\n res,\n completionReq,\n \"ollama\",\n urlPath,\n fixtures,\n defaults,\n raw,\n );\n if (proxied) {\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: res.statusCode ?? 200, fixture: null },\n });\n return;\n }\n }\n const strictStatus = defaults.strict ? 503 : 404;\n const strictMessage = defaults.strict\n ? \"Strict mode: no fixture matched\"\n : \"No fixture matched\";\n if (defaults.strict) {\n logger.error(`STRICT: No fixture matched for ${req.method ?? \"POST\"} ${urlPath}`);\n }\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: strictStatus, fixture: null },\n });\n writeErrorResponse(\n res,\n strictStatus,\n JSON.stringify({\n error: {\n message: strictMessage,\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n const response = fixture.response;\n const latency = fixture.latency ?? defaults.latency;\n const chunkSize = Math.max(1, fixture.chunkSize ?? defaults.chunkSize);\n\n // Ollama defaults to streaming when stream is absent or true\n const streaming = ollamaReq.stream !== false;\n\n // Error response\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, JSON.stringify(response));\n return;\n }\n\n // Text response\n if (isTextResponse(response)) {\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n if (!streaming) {\n const body = buildOllamaChatTextResponse(\n response.content,\n completionReq.model,\n response.reasoning,\n );\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const chunks = buildOllamaChatTextChunks(\n response.content,\n completionReq.model,\n chunkSize,\n response.reasoning,\n );\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeNDJSONStream(res, chunks, {\n latency,\n streamingProfile: fixture.streamingProfile,\n signal: interruption?.signal,\n onChunkSent: interruption?.tick,\n });\n if (!completed) {\n if (!res.writableEnded) res.destroy();\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption?.reason();\n }\n interruption?.cleanup();\n }\n return;\n }\n\n // Tool call response\n if (isToolCallResponse(response)) {\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n if (!streaming) {\n const body = buildOllamaChatToolCallResponse(response.toolCalls, completionReq.model, logger);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const chunks = buildOllamaChatToolCallChunks(response.toolCalls, completionReq.model, logger);\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeNDJSONStream(res, chunks, {\n latency,\n streamingProfile: fixture.streamingProfile,\n signal: interruption?.signal,\n onChunkSent: interruption?.tick,\n });\n if (!completed) {\n if (!res.writableEnded) res.destroy();\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption?.reason();\n }\n interruption?.cleanup();\n }\n return;\n }\n\n // Unknown response type\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: {\n message: \"Fixture response did not match any known type\",\n type: \"server_error\",\n },\n }),\n );\n}\n\n// ─── Request handler: /api/generate ──────────────────────────────────────────\n\nexport async function handleOllamaGenerate(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n): Promise<void> {\n setCorsHeaders(res);\n\n const urlPath = req.url ?? \"/api/generate\";\n\n let generateReq: OllamaGenerateRequest;\n try {\n generateReq = JSON.parse(raw) as OllamaGenerateRequest;\n } catch {\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Malformed JSON\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n if (!generateReq.prompt || typeof generateReq.prompt !== \"string\") {\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Invalid request: prompt field is required\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Convert to ChatCompletionRequest for fixture matching\n const completionReq = ollamaGenerateToCompletionRequest(generateReq);\n\n const fixture = matchFixture(\n fixtures,\n completionReq,\n journal.fixtureMatchCounts,\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures);\n }\n\n if (\n applyChaos(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n journal,\n {\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n },\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n if (defaults.record) {\n const proxied = await proxyAndRecord(\n req,\n res,\n completionReq,\n \"ollama\",\n urlPath,\n fixtures,\n defaults,\n raw,\n );\n if (proxied) {\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: res.statusCode ?? 200, fixture: null },\n });\n return;\n }\n }\n const strictStatus = defaults.strict ? 503 : 404;\n const strictMessage = defaults.strict\n ? \"Strict mode: no fixture matched\"\n : \"No fixture matched\";\n if (defaults.strict) {\n defaults.logger.error(`STRICT: No fixture matched for ${req.method ?? \"POST\"} ${urlPath}`);\n }\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: strictStatus, fixture: null },\n });\n writeErrorResponse(\n res,\n strictStatus,\n JSON.stringify({\n error: {\n message: strictMessage,\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n const response = fixture.response;\n const latency = fixture.latency ?? defaults.latency;\n const chunkSize = Math.max(1, fixture.chunkSize ?? defaults.chunkSize);\n\n // Ollama defaults to streaming when stream is absent or true\n const streaming = generateReq.stream !== false;\n\n // Error response\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, JSON.stringify(response));\n return;\n }\n\n // Text response (only type supported for /api/generate)\n if (isTextResponse(response)) {\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n if (!streaming) {\n const body = buildOllamaGenerateTextResponse(\n response.content,\n completionReq.model,\n response.reasoning,\n );\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const chunks = buildOllamaGenerateTextChunks(\n response.content,\n completionReq.model,\n chunkSize,\n response.reasoning,\n );\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeNDJSONStream(res, chunks, {\n latency,\n streamingProfile: fixture.streamingProfile,\n signal: interruption?.signal,\n onChunkSent: interruption?.tick,\n });\n if (!completed) {\n if (!res.writableEnded) res.destroy();\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption?.reason();\n }\n interruption?.cleanup();\n }\n return;\n }\n\n // Tool call responses not supported for /api/generate — fall through to error\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: {\n message: \"Fixture response did not match any known type\",\n type: \"server_error\",\n },\n }),\n );\n}\n"],"mappings":";;;;;;;;;AAkEA,MAAM,kBAAkB;CACtB,aAAa;CACb,gBAAgB;CAChB,eAAe;CACf,mBAAmB;CACnB,sBAAsB;CACtB,YAAY;CACZ,eAAe;CAChB;AAID,SAAgB,0BAA0B,KAA2C;CACnF,MAAM,WAA0B,EAAE;AAElC,MAAK,MAAM,OAAO,IAAI,SACpB,UAAS,KAAK;EACZ,MAAM,IAAI;EACV,SAAS,IAAI;EACd,CAAC;CAIJ,IAAI;AACJ,KAAI,IAAI,SAAS,IAAI,MAAM,SAAS,EAClC,SAAQ,IAAI,MAAM,KAAK,OAAO;EAC5B,MAAM;EACN,UAAU;GACR,MAAM,EAAE,SAAS;GACjB,aAAa,EAAE,SAAS;GACxB,YAAY,EAAE,SAAS;GACxB;EACF,EAAE;AAGL,QAAO;EACL,OAAO,IAAI;EACX;EACA,QAAQ,IAAI;EACZ,aAAa,I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,SAAS,CAAC;AACzD;;AAIF,KAAI,eAAe,SAAS,EAAE;EAC5B,MAAM,eAAe,QAAQ,IAAI;GAC/B,QAAQ,IAAI,UAAU;GACtB,MAAM;GACN,SAAS,eAAe,IAAI,QAAQ;GACpC,MAAM;GACN,UAAU;IAAE,QAAQ;IAAK;IAAS;GACnC,CAAC;AACF,MAAI,CAAC,WAAW;GACd,MAAM,OAAO,gCACX,SAAS,SACT,cAAc,OACd,SAAS,UACV;AACD,OAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,OAAI,IAAI,KAAK,UAAU,KAAK,CAAC;SACxB;GACL,MAAM,SAAS,8BACb,SAAS,SACT,cAAc,OACd,WACA,SAAS,UACV;GACD,MAAM,eAAe,yBAAyB,QAAQ;AAOtD,OAAI,CANc,MAAM,kBAAkB,KAAK,QAAQ;IACrD;IACA,kBAAkB,QAAQ;IAC1B,QAAQ,cAAc;IACtB,aAAa,cAAc;IAC5B,CAAC,EACc;AACd,QAAI,CAAC,IAAI,cAAe,KAAI,SAAS;AACrC,iBAAa,SAAS,cAAc;AACpC,iBAAa,SAAS,kBAAkB,cAAc,QAAQ;;AAEhE,iBAAc,SAAS;;AAEzB;;AAIF,SAAQ,IAAI;EACV,QAAQ,IAAI,UAAU;EACtB,MAAM;EACN,SAAS,eAAe,IAAI,QAAQ;EACpC,MAAM;EACN,UAAU;GAAE,QAAQ;GAAK;GAAS;EACnC,CAAC;AACF,oBACE,KACA,KACA,KAAK,UAAU,EACb,OAAO;EACL,SAAS;EACT,MAAM;EACP,EACF,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"ollama.js","names":[],"sources":["../src/ollama.ts"],"sourcesContent":["/**\n * Ollama API endpoint support.\n *\n * Translates incoming /api/chat and /api/generate requests into the\n * ChatCompletionRequest format used by the fixture router, and converts\n * fixture responses back into Ollama's NDJSON streaming or non-streaming format.\n *\n * Key differences from OpenAI:\n * - Ollama defaults to stream: true (opposite of OpenAI)\n * - Streaming uses NDJSON, not SSE\n * - Tool call arguments are objects, not JSON strings\n * - Tool calls have no id field\n */\n\nimport type * as http from \"node:http\";\nimport type {\n ChatCompletionRequest,\n ChatMessage,\n Fixture,\n HandlerDefaults,\n ToolCall,\n ToolDefinition,\n} from \"./types.js\";\nimport {\n isTextResponse,\n isToolCallResponse,\n isErrorResponse,\n flattenHeaders,\n getTestId,\n} from \"./helpers.js\";\nimport { matchFixture } from \"./router.js\";\nimport { writeErrorResponse } from \"./sse-writer.js\";\nimport { writeNDJSONStream } from \"./ndjson-writer.js\";\nimport { createInterruptionSignal } from \"./interruption.js\";\nimport type { Journal } from \"./journal.js\";\nimport type { Logger } from \"./logger.js\";\nimport { applyChaos } from \"./chaos.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\n\n// ─── Ollama request types ────────────────────────────────────────────────────\n\ninterface OllamaMessage {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string;\n}\n\ninterface OllamaToolDef {\n type: string;\n function: {\n name: string;\n description?: string;\n parameters?: object;\n };\n}\n\ninterface OllamaRequest {\n model: string;\n messages: OllamaMessage[];\n stream?: boolean; // default true!\n options?: { temperature?: number; num_predict?: number };\n tools?: OllamaToolDef[];\n}\n\ninterface OllamaGenerateRequest {\n model: string;\n prompt: string;\n stream?: boolean; // default true!\n options?: { temperature?: number; num_predict?: number };\n}\n\n// ─── Duration fields (zeroed, required on final/non-streaming responses) ────\n\nconst DURATION_FIELDS = {\n done_reason: \"stop\" as const,\n total_duration: 0,\n load_duration: 0,\n prompt_eval_count: 0,\n prompt_eval_duration: 0,\n eval_count: 0,\n eval_duration: 0,\n};\n\n// ─── Input conversion: Ollama → ChatCompletionRequest ────────────────────────\n\nexport function ollamaToCompletionRequest(req: OllamaRequest): ChatCompletionRequest {\n const messages: ChatMessage[] = [];\n\n for (const msg of req.messages) {\n messages.push({\n role: msg.role as ChatMessage[\"role\"],\n content: msg.content,\n });\n }\n\n // Convert tools\n let tools: ToolDefinition[] | undefined;\n if (req.tools && req.tools.length > 0) {\n tools = req.tools.map((t) => ({\n type: \"function\" as const,\n function: {\n name: t.function.name,\n description: t.function.description,\n parameters: t.function.parameters,\n },\n }));\n }\n\n return {\n model: req.model,\n messages,\n stream: req.stream,\n temperature: req.options?.temperature,\n max_tokens: req.options?.num_predict,\n tools,\n };\n}\n\nfunction ollamaGenerateToCompletionRequest(req: OllamaGenerateRequest): ChatCompletionRequest {\n return {\n model: req.model,\n messages: [{ role: \"user\", content: req.prompt }],\n stream: req.stream,\n temperature: req.options?.temperature,\n max_tokens: req.options?.num_predict,\n };\n}\n\n// ─── Response builders: /api/chat ────────────────────────────────────────────\n\nfunction buildOllamaChatTextChunks(\n content: string,\n model: string,\n chunkSize: number,\n reasoning?: string,\n): object[] {\n const chunks: object[] = [];\n\n // Reasoning chunks (before content)\n if (reasoning) {\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n chunks.push({\n model,\n message: { role: \"assistant\", content: \"\", reasoning_content: slice },\n done: false,\n });\n }\n }\n\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n chunks.push({\n model,\n message: { role: \"assistant\", content: slice },\n done: false,\n });\n }\n\n // Final chunk with done: true and all duration fields\n chunks.push({\n model,\n message: { role: \"assistant\", content: \"\" },\n done: true,\n ...DURATION_FIELDS,\n });\n\n return chunks;\n}\n\nfunction buildOllamaChatTextResponse(content: string, model: string, reasoning?: string): object {\n return {\n model,\n message: {\n role: \"assistant\",\n content,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n },\n done: true,\n ...DURATION_FIELDS,\n };\n}\n\nfunction buildOllamaChatToolCallChunks(\n toolCalls: ToolCall[],\n model: string,\n logger: Logger,\n): object[] {\n const ollamaToolCalls = toolCalls.map((tc) => {\n let argsObj: unknown;\n try {\n argsObj = JSON.parse(tc.arguments || \"{}\");\n } catch {\n logger.warn(\n `Malformed JSON in fixture tool call arguments for \"${tc.name}\": ${tc.arguments}`,\n );\n argsObj = {};\n }\n return {\n function: {\n name: tc.name,\n arguments: argsObj,\n },\n };\n });\n\n // Tool calls are sent in a single chunk (no streaming of individual args)\n const chunks: object[] = [];\n chunks.push({\n model,\n message: {\n role: \"assistant\",\n content: \"\",\n tool_calls: ollamaToolCalls,\n },\n done: false,\n });\n\n // Final chunk\n chunks.push({\n model,\n message: { role: \"assistant\", content: \"\" },\n done: true,\n ...DURATION_FIELDS,\n });\n\n return chunks;\n}\n\nfunction buildOllamaChatToolCallResponse(\n toolCalls: ToolCall[],\n model: string,\n logger: Logger,\n): object {\n const ollamaToolCalls = toolCalls.map((tc) => {\n let argsObj: unknown;\n try {\n argsObj = JSON.parse(tc.arguments || \"{}\");\n } catch {\n logger.warn(\n `Malformed JSON in fixture tool call arguments for \"${tc.name}\": ${tc.arguments}`,\n );\n argsObj = {};\n }\n return {\n function: {\n name: tc.name,\n arguments: argsObj,\n },\n };\n });\n\n return {\n model,\n message: {\n role: \"assistant\",\n content: \"\",\n tool_calls: ollamaToolCalls,\n },\n done: true,\n ...DURATION_FIELDS,\n };\n}\n\n// ─── Response builders: /api/generate ────────────────────────────────────────\n\nfunction buildOllamaGenerateTextChunks(\n content: string,\n model: string,\n chunkSize: number,\n reasoning?: string,\n): object[] {\n const chunks: object[] = [];\n const createdAt = new Date().toISOString();\n\n // Reasoning chunks (before content)\n if (reasoning) {\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n chunks.push({\n model,\n created_at: createdAt,\n response: \"\",\n reasoning_content: slice,\n done: false,\n });\n }\n }\n\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n chunks.push({\n model,\n created_at: createdAt,\n response: slice,\n done: false,\n });\n }\n\n // Final chunk\n chunks.push({\n model,\n created_at: createdAt,\n response: \"\",\n done: true,\n ...DURATION_FIELDS,\n context: [],\n });\n\n return chunks;\n}\n\nfunction buildOllamaGenerateTextResponse(\n content: string,\n model: string,\n reasoning?: string,\n): object {\n return {\n model,\n created_at: new Date().toISOString(),\n response: content,\n ...(reasoning ? { reasoning_content: reasoning } : {}),\n done: true,\n ...DURATION_FIELDS,\n context: [],\n };\n}\n\n// ─── Request handler: /api/chat ──────────────────────────────────────────────\n\nexport async function handleOllama(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n): Promise<void> {\n const { logger } = defaults;\n setCorsHeaders(res);\n\n const urlPath = req.url ?? \"/api/chat\";\n\n let ollamaReq: OllamaRequest;\n try {\n ollamaReq = JSON.parse(raw) as OllamaRequest;\n } catch {\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Malformed JSON\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n if (!ollamaReq.messages || !Array.isArray(ollamaReq.messages)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Invalid request: messages array is required\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Convert to ChatCompletionRequest for fixture matching\n const completionReq = ollamaToCompletionRequest(ollamaReq);\n\n const testId = getTestId(req);\n const fixture = matchFixture(\n fixtures,\n completionReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n }\n\n if (\n applyChaos(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n journal,\n {\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n },\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n if (defaults.record) {\n const proxied = await proxyAndRecord(\n req,\n res,\n completionReq,\n \"ollama\",\n urlPath,\n fixtures,\n defaults,\n raw,\n );\n if (proxied) {\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: res.statusCode ?? 200, fixture: null },\n });\n return;\n }\n }\n const strictStatus = defaults.strict ? 503 : 404;\n const strictMessage = defaults.strict\n ? \"Strict mode: no fixture matched\"\n : \"No fixture matched\";\n if (defaults.strict) {\n logger.error(`STRICT: No fixture matched for ${req.method ?? \"POST\"} ${urlPath}`);\n }\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: strictStatus, fixture: null },\n });\n writeErrorResponse(\n res,\n strictStatus,\n JSON.stringify({\n error: {\n message: strictMessage,\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n const response = fixture.response;\n const latency = fixture.latency ?? defaults.latency;\n const chunkSize = Math.max(1, fixture.chunkSize ?? defaults.chunkSize);\n\n // Ollama defaults to streaming when stream is absent or true\n const streaming = ollamaReq.stream !== false;\n\n // Error response\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, JSON.stringify(response));\n return;\n }\n\n // Text response\n if (isTextResponse(response)) {\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n if (!streaming) {\n const body = buildOllamaChatTextResponse(\n response.content,\n completionReq.model,\n response.reasoning,\n );\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const chunks = buildOllamaChatTextChunks(\n response.content,\n completionReq.model,\n chunkSize,\n response.reasoning,\n );\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeNDJSONStream(res, chunks, {\n latency,\n streamingProfile: fixture.streamingProfile,\n signal: interruption?.signal,\n onChunkSent: interruption?.tick,\n });\n if (!completed) {\n if (!res.writableEnded) res.destroy();\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption?.reason();\n }\n interruption?.cleanup();\n }\n return;\n }\n\n // Tool call response\n if (isToolCallResponse(response)) {\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n if (!streaming) {\n const body = buildOllamaChatToolCallResponse(response.toolCalls, completionReq.model, logger);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const chunks = buildOllamaChatToolCallChunks(response.toolCalls, completionReq.model, logger);\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeNDJSONStream(res, chunks, {\n latency,\n streamingProfile: fixture.streamingProfile,\n signal: interruption?.signal,\n onChunkSent: interruption?.tick,\n });\n if (!completed) {\n if (!res.writableEnded) res.destroy();\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption?.reason();\n }\n interruption?.cleanup();\n }\n return;\n }\n\n // Unknown response type\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: {\n message: \"Fixture response did not match any known type\",\n type: \"server_error\",\n },\n }),\n );\n}\n\n// ─── Request handler: /api/generate ──────────────────────────────────────────\n\nexport async function handleOllamaGenerate(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n): Promise<void> {\n setCorsHeaders(res);\n\n const urlPath = req.url ?? \"/api/generate\";\n\n let generateReq: OllamaGenerateRequest;\n try {\n generateReq = JSON.parse(raw) as OllamaGenerateRequest;\n } catch {\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Malformed JSON\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n if (!generateReq.prompt || typeof generateReq.prompt !== \"string\") {\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Invalid request: prompt field is required\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Convert to ChatCompletionRequest for fixture matching\n const completionReq = ollamaGenerateToCompletionRequest(generateReq);\n\n const testId = getTestId(req);\n const fixture = matchFixture(\n fixtures,\n completionReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n }\n\n if (\n applyChaos(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n journal,\n {\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n },\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n if (defaults.record) {\n const proxied = await proxyAndRecord(\n req,\n res,\n completionReq,\n \"ollama\",\n urlPath,\n fixtures,\n defaults,\n raw,\n );\n if (proxied) {\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: res.statusCode ?? 200, fixture: null },\n });\n return;\n }\n }\n const strictStatus = defaults.strict ? 503 : 404;\n const strictMessage = defaults.strict\n ? \"Strict mode: no fixture matched\"\n : \"No fixture matched\";\n if (defaults.strict) {\n defaults.logger.error(`STRICT: No fixture matched for ${req.method ?? \"POST\"} ${urlPath}`);\n }\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: strictStatus, fixture: null },\n });\n writeErrorResponse(\n res,\n strictStatus,\n JSON.stringify({\n error: {\n message: strictMessage,\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n const response = fixture.response;\n const latency = fixture.latency ?? defaults.latency;\n const chunkSize = Math.max(1, fixture.chunkSize ?? defaults.chunkSize);\n\n // Ollama defaults to streaming when stream is absent or true\n const streaming = generateReq.stream !== false;\n\n // Error response\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, JSON.stringify(response));\n return;\n }\n\n // Text response (only type supported for /api/generate)\n if (isTextResponse(response)) {\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n if (!streaming) {\n const body = buildOllamaGenerateTextResponse(\n response.content,\n completionReq.model,\n response.reasoning,\n );\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const chunks = buildOllamaGenerateTextChunks(\n response.content,\n completionReq.model,\n chunkSize,\n response.reasoning,\n );\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeNDJSONStream(res, chunks, {\n latency,\n streamingProfile: fixture.streamingProfile,\n signal: interruption?.signal,\n onChunkSent: interruption?.tick,\n });\n if (!completed) {\n if (!res.writableEnded) res.destroy();\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption?.reason();\n }\n interruption?.cleanup();\n }\n return;\n }\n\n // Tool call responses not supported for /api/generate — fall through to error\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: {\n message: \"Fixture response did not match any known type\",\n type: \"server_error\",\n },\n }),\n );\n}\n"],"mappings":";;;;;;;;;AAwEA,MAAM,kBAAkB;CACtB,aAAa;CACb,gBAAgB;CAChB,eAAe;CACf,mBAAmB;CACnB,sBAAsB;CACtB,YAAY;CACZ,eAAe;CAChB;AAID,SAAgB,0BAA0B,KAA2C;CACnF,MAAM,WAA0B,EAAE;AAElC,MAAK,MAAM,OAAO,IAAI,SACpB,UAAS,KAAK;EACZ,MAAM,IAAI;EACV,SAAS,IAAI;EACd,CAAC;CAIJ,IAAI;AACJ,KAAI,IAAI,SAAS,IAAI,MAAM,SAAS,EAClC,SAAQ,IAAI,MAAM,KAAK,OAAO;EAC5B,MAAM;EACN,UAAU;GACR,MAAM,EAAE,SAAS;GACjB,aAAa,EAAE,SAAS;GACxB,YAAY,EAAE,SAAS;GACxB;EACF,EAAE;AAGL,QAAO;EACL,OAAO,IAAI;EACX;EACA,QAAQ,IAAI;EACZ,aAAa,IAAI,SAAS;EAC1B,YAAY,IAAI,SAAS;EACzB;EACD;;AAGH,SAAS,kCAAkC,KAAmD;AAC5F,QAAO;EACL,OAAO,IAAI;EACX,UAAU,CAAC;GAAE,MAAM;GAAQ,SAAS,IAAI;GAAQ,CAAC;EACjD,QAAQ,IAAI;EACZ,aAAa,IAAI,SAAS;EAC1B,YAAY,IAAI,SAAS;EAC1B;;AAKH,SAAS,0BACP,SACA,OACA,WACA,WACU;CACV,MAAM,SAAmB,EAAE;AAG3B,KAAI,UACF,MAAK,IAAI,IAAI,GAAG,IAAI,UAAU,QAAQ,KAAK,WAAW;EACpD,MAAM,QAAQ,UAAU,MAAM,GAAG,IAAI,UAAU;AAC/C,SAAO,KAAK;GACV;GACA,SAAS;IAAE,MAAM;IAAa,SAAS;IAAI,mBAAmB;IAAO;GACrE,MAAM;GACP,CAAC;;AAIN,MAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KA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AQ;AAOtD,OAAI,CANc,MAAM,kBAAkB,KAAK,QAAQ;IACrD;IACA,kBAAkB,QAAQ;IAC1B,QAAQ,cAAc;IACtB,aAAa,cAAc;IAC5B,CAAC,EACc;AACd,QAAI,CAAC,IAAI,cAAe,KAAI,SAAS;AACrC,iBAAa,SAAS,cAAc;AACpC,iBAAa,SAAS,kBAAkB,cAAc,QAAQ;;AAEhE,iBAAc,SAAS;;AAEzB;;AAIF,SAAQ,IAAI;EACV,QAAQ,IAAI,UAAU;EACtB,MAAM;EACN,SAAS,eAAe,IAAI,QAAQ;EACpC,MAAM;EACN,UAAU;GAAE,QAAQ;GAAK;GAAS;EACnC,CAAC;AACF,oBACE,KACA,KACA,KAAK,UAAU,EACb,OAAO;EACL,SAAS;EACT,MAAM;EACP,EACF,CAAC,CACH"}
|
package/dist/responses.cjs
CHANGED
|
@@ -76,108 +76,9 @@ function itemId() {
|
|
|
76
76
|
return require_helpers.generateId("msg");
|
|
77
77
|
}
|
|
78
78
|
function buildTextStreamEvents(content, model, chunkSize, reasoning, webSearches) {
|
|
79
|
-
const respId =
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
const events = [];
|
|
83
|
-
let msgOutputIndex = 0;
|
|
84
|
-
const prefixOutputItems = [];
|
|
85
|
-
events.push({
|
|
86
|
-
type: "response.created",
|
|
87
|
-
response: {
|
|
88
|
-
id: respId,
|
|
89
|
-
object: "response",
|
|
90
|
-
created_at: created,
|
|
91
|
-
model,
|
|
92
|
-
status: "in_progress",
|
|
93
|
-
output: []
|
|
94
|
-
}
|
|
95
|
-
});
|
|
96
|
-
events.push({
|
|
97
|
-
type: "response.in_progress",
|
|
98
|
-
response: {
|
|
99
|
-
id: respId,
|
|
100
|
-
object: "response",
|
|
101
|
-
created_at: created,
|
|
102
|
-
model,
|
|
103
|
-
status: "in_progress",
|
|
104
|
-
output: []
|
|
105
|
-
}
|
|
106
|
-
});
|
|
107
|
-
if (reasoning) {
|
|
108
|
-
const reasoningEvents = buildReasoningStreamEvents(reasoning, model, chunkSize);
|
|
109
|
-
events.push(...reasoningEvents);
|
|
110
|
-
const doneEvent = reasoningEvents.find((e) => e.type === "response.output_item.done" && e.item?.type === "reasoning");
|
|
111
|
-
if (doneEvent) prefixOutputItems.push(doneEvent.item);
|
|
112
|
-
msgOutputIndex++;
|
|
113
|
-
}
|
|
114
|
-
if (webSearches && webSearches.length > 0) {
|
|
115
|
-
const searchEvents = buildWebSearchStreamEvents(webSearches, msgOutputIndex);
|
|
116
|
-
events.push(...searchEvents);
|
|
117
|
-
const doneEvents = searchEvents.filter((e) => e.type === "response.output_item.done" && e.item?.type === "web_search_call");
|
|
118
|
-
for (const de of doneEvents) prefixOutputItems.push(de.item);
|
|
119
|
-
msgOutputIndex += webSearches.length;
|
|
120
|
-
}
|
|
121
|
-
events.push({
|
|
122
|
-
type: "response.output_item.added",
|
|
123
|
-
output_index: msgOutputIndex,
|
|
124
|
-
item: {
|
|
125
|
-
type: "message",
|
|
126
|
-
id: msgId,
|
|
127
|
-
status: "in_progress",
|
|
128
|
-
role: "assistant",
|
|
129
|
-
content: []
|
|
130
|
-
}
|
|
131
|
-
});
|
|
132
|
-
events.push({
|
|
133
|
-
type: "response.content_part.added",
|
|
134
|
-
output_index: msgOutputIndex,
|
|
135
|
-
content_index: 0,
|
|
136
|
-
part: {
|
|
137
|
-
type: "output_text",
|
|
138
|
-
text: ""
|
|
139
|
-
}
|
|
140
|
-
});
|
|
141
|
-
for (let i = 0; i < content.length; i += chunkSize) {
|
|
142
|
-
const slice = content.slice(i, i + chunkSize);
|
|
143
|
-
events.push({
|
|
144
|
-
type: "response.output_text.delta",
|
|
145
|
-
item_id: msgId,
|
|
146
|
-
output_index: msgOutputIndex,
|
|
147
|
-
content_index: 0,
|
|
148
|
-
delta: slice
|
|
149
|
-
});
|
|
150
|
-
}
|
|
151
|
-
events.push({
|
|
152
|
-
type: "response.output_text.done",
|
|
153
|
-
output_index: msgOutputIndex,
|
|
154
|
-
content_index: 0,
|
|
155
|
-
text: content
|
|
156
|
-
});
|
|
157
|
-
events.push({
|
|
158
|
-
type: "response.content_part.done",
|
|
159
|
-
output_index: msgOutputIndex,
|
|
160
|
-
content_index: 0,
|
|
161
|
-
part: {
|
|
162
|
-
type: "output_text",
|
|
163
|
-
text: content
|
|
164
|
-
}
|
|
165
|
-
});
|
|
166
|
-
const msgItem = {
|
|
167
|
-
type: "message",
|
|
168
|
-
id: msgId,
|
|
169
|
-
status: "completed",
|
|
170
|
-
role: "assistant",
|
|
171
|
-
content: [{
|
|
172
|
-
type: "output_text",
|
|
173
|
-
text: content
|
|
174
|
-
}]
|
|
175
|
-
};
|
|
176
|
-
events.push({
|
|
177
|
-
type: "response.output_item.done",
|
|
178
|
-
output_index: msgOutputIndex,
|
|
179
|
-
item: msgItem
|
|
180
|
-
});
|
|
79
|
+
const { respId, created, events, prefixOutputItems, nextOutputIndex } = buildResponsePreamble(model, chunkSize, reasoning, webSearches);
|
|
80
|
+
const { events: msgEvents, msgItem } = buildMessageOutputEvents(content, chunkSize, nextOutputIndex);
|
|
81
|
+
events.push(...msgEvents);
|
|
181
82
|
events.push({
|
|
182
83
|
type: "response.completed",
|
|
183
84
|
response: {
|
|
@@ -359,7 +260,7 @@ function buildWebSearchStreamEvents(queries, startOutputIndex) {
|
|
|
359
260
|
type: "web_search_call",
|
|
360
261
|
id: searchId,
|
|
361
262
|
status: "in_progress",
|
|
362
|
-
query: queries[i]
|
|
263
|
+
action: { query: queries[i] }
|
|
363
264
|
}
|
|
364
265
|
});
|
|
365
266
|
events.push({
|
|
@@ -369,15 +270,128 @@ function buildWebSearchStreamEvents(queries, startOutputIndex) {
|
|
|
369
270
|
type: "web_search_call",
|
|
370
271
|
id: searchId,
|
|
371
272
|
status: "completed",
|
|
372
|
-
query: queries[i]
|
|
273
|
+
action: { query: queries[i] }
|
|
373
274
|
}
|
|
374
275
|
});
|
|
375
276
|
}
|
|
376
277
|
return events;
|
|
377
278
|
}
|
|
378
|
-
function
|
|
279
|
+
function buildResponsePreamble(model, chunkSize, reasoning, webSearches) {
|
|
379
280
|
const respId = responseId();
|
|
281
|
+
const created = Math.floor(Date.now() / 1e3);
|
|
282
|
+
const events = [];
|
|
283
|
+
const prefixOutputItems = [];
|
|
284
|
+
let nextOutputIndex = 0;
|
|
285
|
+
events.push({
|
|
286
|
+
type: "response.created",
|
|
287
|
+
response: {
|
|
288
|
+
id: respId,
|
|
289
|
+
object: "response",
|
|
290
|
+
created_at: created,
|
|
291
|
+
model,
|
|
292
|
+
status: "in_progress",
|
|
293
|
+
output: []
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
events.push({
|
|
297
|
+
type: "response.in_progress",
|
|
298
|
+
response: {
|
|
299
|
+
id: respId,
|
|
300
|
+
object: "response",
|
|
301
|
+
created_at: created,
|
|
302
|
+
model,
|
|
303
|
+
status: "in_progress",
|
|
304
|
+
output: []
|
|
305
|
+
}
|
|
306
|
+
});
|
|
307
|
+
if (reasoning) {
|
|
308
|
+
const reasoningEvents = buildReasoningStreamEvents(reasoning, model, chunkSize);
|
|
309
|
+
events.push(...reasoningEvents);
|
|
310
|
+
const doneEvent = reasoningEvents.find((e) => e.type === "response.output_item.done" && e.item?.type === "reasoning");
|
|
311
|
+
if (doneEvent) prefixOutputItems.push(doneEvent.item);
|
|
312
|
+
nextOutputIndex++;
|
|
313
|
+
}
|
|
314
|
+
if (webSearches && webSearches.length > 0) {
|
|
315
|
+
const searchEvents = buildWebSearchStreamEvents(webSearches, nextOutputIndex);
|
|
316
|
+
events.push(...searchEvents);
|
|
317
|
+
const doneEvents = searchEvents.filter((e) => e.type === "response.output_item.done" && e.item?.type === "web_search_call");
|
|
318
|
+
for (const de of doneEvents) prefixOutputItems.push(de.item);
|
|
319
|
+
nextOutputIndex += webSearches.length;
|
|
320
|
+
}
|
|
321
|
+
return {
|
|
322
|
+
respId,
|
|
323
|
+
created,
|
|
324
|
+
events,
|
|
325
|
+
prefixOutputItems,
|
|
326
|
+
nextOutputIndex
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
function buildMessageOutputEvents(content, chunkSize, outputIndex) {
|
|
380
330
|
const msgId = itemId();
|
|
331
|
+
const events = [];
|
|
332
|
+
events.push({
|
|
333
|
+
type: "response.output_item.added",
|
|
334
|
+
output_index: outputIndex,
|
|
335
|
+
item: {
|
|
336
|
+
type: "message",
|
|
337
|
+
id: msgId,
|
|
338
|
+
status: "in_progress",
|
|
339
|
+
role: "assistant",
|
|
340
|
+
content: []
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
events.push({
|
|
344
|
+
type: "response.content_part.added",
|
|
345
|
+
output_index: outputIndex,
|
|
346
|
+
content_index: 0,
|
|
347
|
+
part: {
|
|
348
|
+
type: "output_text",
|
|
349
|
+
text: ""
|
|
350
|
+
}
|
|
351
|
+
});
|
|
352
|
+
for (let i = 0; i < content.length; i += chunkSize) events.push({
|
|
353
|
+
type: "response.output_text.delta",
|
|
354
|
+
item_id: msgId,
|
|
355
|
+
output_index: outputIndex,
|
|
356
|
+
content_index: 0,
|
|
357
|
+
delta: content.slice(i, i + chunkSize)
|
|
358
|
+
});
|
|
359
|
+
events.push({
|
|
360
|
+
type: "response.output_text.done",
|
|
361
|
+
output_index: outputIndex,
|
|
362
|
+
content_index: 0,
|
|
363
|
+
text: content
|
|
364
|
+
});
|
|
365
|
+
events.push({
|
|
366
|
+
type: "response.content_part.done",
|
|
367
|
+
output_index: outputIndex,
|
|
368
|
+
content_index: 0,
|
|
369
|
+
part: {
|
|
370
|
+
type: "output_text",
|
|
371
|
+
text: content
|
|
372
|
+
}
|
|
373
|
+
});
|
|
374
|
+
const msgItem = {
|
|
375
|
+
type: "message",
|
|
376
|
+
id: msgId,
|
|
377
|
+
status: "completed",
|
|
378
|
+
role: "assistant",
|
|
379
|
+
content: [{
|
|
380
|
+
type: "output_text",
|
|
381
|
+
text: content
|
|
382
|
+
}]
|
|
383
|
+
};
|
|
384
|
+
events.push({
|
|
385
|
+
type: "response.output_item.done",
|
|
386
|
+
output_index: outputIndex,
|
|
387
|
+
item: msgItem
|
|
388
|
+
});
|
|
389
|
+
return {
|
|
390
|
+
events,
|
|
391
|
+
msgItem
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
function buildOutputPrefix(content, reasoning, webSearches) {
|
|
381
395
|
const output = [];
|
|
382
396
|
if (reasoning) output.push({
|
|
383
397
|
type: "reasoning",
|
|
@@ -391,11 +405,11 @@ function buildTextResponse(content, model, reasoning, webSearches) {
|
|
|
391
405
|
type: "web_search_call",
|
|
392
406
|
id: require_helpers.generateId("ws"),
|
|
393
407
|
status: "completed",
|
|
394
|
-
query
|
|
408
|
+
action: { query }
|
|
395
409
|
});
|
|
396
410
|
output.push({
|
|
397
411
|
type: "message",
|
|
398
|
-
id:
|
|
412
|
+
id: itemId(),
|
|
399
413
|
status: "completed",
|
|
400
414
|
role: "assistant",
|
|
401
415
|
content: [{
|
|
@@ -403,8 +417,11 @@ function buildTextResponse(content, model, reasoning, webSearches) {
|
|
|
403
417
|
text: content
|
|
404
418
|
}]
|
|
405
419
|
});
|
|
420
|
+
return output;
|
|
421
|
+
}
|
|
422
|
+
function buildResponseEnvelope(model, output) {
|
|
406
423
|
return {
|
|
407
|
-
id:
|
|
424
|
+
id: responseId(),
|
|
408
425
|
object: "response",
|
|
409
426
|
created_at: Math.floor(Date.now() / 1e3),
|
|
410
427
|
model,
|
|
@@ -417,27 +434,101 @@ function buildTextResponse(content, model, reasoning, webSearches) {
|
|
|
417
434
|
}
|
|
418
435
|
};
|
|
419
436
|
}
|
|
437
|
+
function buildTextResponse(content, model, reasoning, webSearches) {
|
|
438
|
+
return buildResponseEnvelope(model, buildOutputPrefix(content, reasoning, webSearches));
|
|
439
|
+
}
|
|
420
440
|
function buildToolCallResponse(toolCalls, model) {
|
|
421
|
-
return {
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
441
|
+
return buildResponseEnvelope(model, toolCalls.map((tc) => ({
|
|
442
|
+
type: "function_call",
|
|
443
|
+
id: require_helpers.generateId("fc"),
|
|
444
|
+
call_id: tc.id || require_helpers.generateToolCallId(),
|
|
445
|
+
name: tc.name,
|
|
446
|
+
arguments: tc.arguments,
|
|
447
|
+
status: "completed"
|
|
448
|
+
})));
|
|
449
|
+
}
|
|
450
|
+
function buildContentWithToolCallsStreamEvents(content, toolCalls, model, chunkSize, reasoning, webSearches) {
|
|
451
|
+
const { respId, created, events, prefixOutputItems, nextOutputIndex } = buildResponsePreamble(model, chunkSize, reasoning, webSearches);
|
|
452
|
+
const { events: msgEvents, msgItem } = buildMessageOutputEvents(content, chunkSize, nextOutputIndex);
|
|
453
|
+
events.push(...msgEvents);
|
|
454
|
+
const fcOutputItems = [];
|
|
455
|
+
for (let idx = 0; idx < toolCalls.length; idx++) {
|
|
456
|
+
const tc = toolCalls[idx];
|
|
457
|
+
const callId = tc.id || require_helpers.generateToolCallId();
|
|
458
|
+
const fcId = require_helpers.generateId("fc");
|
|
459
|
+
const fcOutputIndex = nextOutputIndex + 1 + idx;
|
|
460
|
+
const args = tc.arguments;
|
|
461
|
+
events.push({
|
|
462
|
+
type: "response.output_item.added",
|
|
463
|
+
output_index: fcOutputIndex,
|
|
464
|
+
item: {
|
|
465
|
+
type: "function_call",
|
|
466
|
+
id: fcId,
|
|
467
|
+
call_id: callId,
|
|
468
|
+
name: tc.name,
|
|
469
|
+
arguments: "",
|
|
470
|
+
status: "in_progress"
|
|
471
|
+
}
|
|
472
|
+
});
|
|
473
|
+
for (let i = 0; i < args.length; i += chunkSize) events.push({
|
|
474
|
+
type: "response.function_call_arguments.delta",
|
|
475
|
+
item_id: fcId,
|
|
476
|
+
output_index: fcOutputIndex,
|
|
477
|
+
delta: args.slice(i, i + chunkSize)
|
|
478
|
+
});
|
|
479
|
+
events.push({
|
|
480
|
+
type: "response.function_call_arguments.done",
|
|
481
|
+
output_index: fcOutputIndex,
|
|
482
|
+
arguments: args
|
|
483
|
+
});
|
|
484
|
+
const doneItem = {
|
|
428
485
|
type: "function_call",
|
|
429
|
-
id:
|
|
430
|
-
call_id:
|
|
486
|
+
id: fcId,
|
|
487
|
+
call_id: callId,
|
|
431
488
|
name: tc.name,
|
|
432
|
-
arguments:
|
|
489
|
+
arguments: args,
|
|
433
490
|
status: "completed"
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
491
|
+
};
|
|
492
|
+
events.push({
|
|
493
|
+
type: "response.output_item.done",
|
|
494
|
+
output_index: fcOutputIndex,
|
|
495
|
+
item: doneItem
|
|
496
|
+
});
|
|
497
|
+
fcOutputItems.push(doneItem);
|
|
498
|
+
}
|
|
499
|
+
events.push({
|
|
500
|
+
type: "response.completed",
|
|
501
|
+
response: {
|
|
502
|
+
id: respId,
|
|
503
|
+
object: "response",
|
|
504
|
+
created_at: created,
|
|
505
|
+
model,
|
|
506
|
+
status: "completed",
|
|
507
|
+
output: [
|
|
508
|
+
...prefixOutputItems,
|
|
509
|
+
msgItem,
|
|
510
|
+
...fcOutputItems
|
|
511
|
+
],
|
|
512
|
+
usage: {
|
|
513
|
+
input_tokens: 0,
|
|
514
|
+
output_tokens: 0,
|
|
515
|
+
total_tokens: 0
|
|
516
|
+
}
|
|
439
517
|
}
|
|
440
|
-
};
|
|
518
|
+
});
|
|
519
|
+
return events;
|
|
520
|
+
}
|
|
521
|
+
function buildContentWithToolCallsResponse(content, toolCalls, model, reasoning, webSearches) {
|
|
522
|
+
const output = buildOutputPrefix(content, reasoning, webSearches);
|
|
523
|
+
for (const tc of toolCalls) output.push({
|
|
524
|
+
type: "function_call",
|
|
525
|
+
id: require_helpers.generateId("fc"),
|
|
526
|
+
call_id: tc.id || require_helpers.generateToolCallId(),
|
|
527
|
+
name: tc.name,
|
|
528
|
+
arguments: tc.arguments,
|
|
529
|
+
status: "completed"
|
|
530
|
+
});
|
|
531
|
+
return buildResponseEnvelope(model, output);
|
|
441
532
|
}
|
|
442
533
|
async function writeResponsesSSEStream(res, events, optionsOrLatency) {
|
|
443
534
|
const opts = typeof optionsOrLatency === "number" ? { latency: optionsOrLatency } : optionsOrLatency ?? {};
|
|
@@ -487,8 +578,9 @@ async function handleResponses(req, res, raw, fixtures, journal, defaults, setCo
|
|
|
487
578
|
return;
|
|
488
579
|
}
|
|
489
580
|
const completionReq = responsesToCompletionRequest(responsesReq);
|
|
490
|
-
const
|
|
491
|
-
|
|
581
|
+
const testId = require_helpers.getTestId(req);
|
|
582
|
+
const fixture = require_router.matchFixture(fixtures, completionReq, journal.getFixtureMatchCountsForTest(testId), defaults.requestTransform);
|
|
583
|
+
if (fixture) journal.incrementFixtureMatchCount(fixture, fixtures, testId);
|
|
492
584
|
if (require_chaos.applyChaos(res, fixture, defaults.chaos, req.headers, journal, {
|
|
493
585
|
method: req.method ?? "POST",
|
|
494
586
|
path: req.url ?? "/v1/responses",
|
|
@@ -549,6 +641,38 @@ async function handleResponses(req, res, raw, fixtures, journal, defaults, setCo
|
|
|
549
641
|
require_sse_writer.writeErrorResponse(res, status, JSON.stringify(response));
|
|
550
642
|
return;
|
|
551
643
|
}
|
|
644
|
+
if (require_helpers.isContentWithToolCallsResponse(response)) {
|
|
645
|
+
const journalEntry = journal.add({
|
|
646
|
+
method: req.method ?? "POST",
|
|
647
|
+
path: req.url ?? "/v1/responses",
|
|
648
|
+
headers: require_helpers.flattenHeaders(req.headers),
|
|
649
|
+
body: completionReq,
|
|
650
|
+
response: {
|
|
651
|
+
status: 200,
|
|
652
|
+
fixture
|
|
653
|
+
}
|
|
654
|
+
});
|
|
655
|
+
if (responsesReq.stream !== true) {
|
|
656
|
+
const body = buildContentWithToolCallsResponse(response.content, response.toolCalls, completionReq.model, response.reasoning, response.webSearches);
|
|
657
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
658
|
+
res.end(JSON.stringify(body));
|
|
659
|
+
} else {
|
|
660
|
+
const events = buildContentWithToolCallsStreamEvents(response.content, response.toolCalls, completionReq.model, chunkSize, response.reasoning, response.webSearches);
|
|
661
|
+
const interruption = require_interruption.createInterruptionSignal(fixture);
|
|
662
|
+
if (!await writeResponsesSSEStream(res, events, {
|
|
663
|
+
latency,
|
|
664
|
+
streamingProfile: fixture.streamingProfile,
|
|
665
|
+
signal: interruption?.signal,
|
|
666
|
+
onChunkSent: interruption?.tick
|
|
667
|
+
})) {
|
|
668
|
+
if (!res.writableEnded) res.destroy();
|
|
669
|
+
journalEntry.response.interrupted = true;
|
|
670
|
+
journalEntry.response.interruptReason = interruption?.reason();
|
|
671
|
+
}
|
|
672
|
+
interruption?.cleanup();
|
|
673
|
+
}
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
552
676
|
if (require_helpers.isTextResponse(response)) {
|
|
553
677
|
const journalEntry = journal.add({
|
|
554
678
|
method: req.method ?? "POST",
|