@copilotkit/aimock 1.14.9 → 1.15.1
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/CHANGELOG.md +29 -0
- package/dist/bedrock-converse.cjs +129 -21
- 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 +131 -23
- package/dist/bedrock-converse.js.map +1 -1
- package/dist/bedrock.cjs +258 -44
- 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 +259 -46
- package/dist/bedrock.js.map +1 -1
- package/dist/cohere.cjs +287 -31
- package/dist/cohere.cjs.map +1 -1
- package/dist/cohere.d.cts +9 -0
- package/dist/cohere.d.cts.map +1 -1
- package/dist/cohere.d.ts +9 -0
- package/dist/cohere.d.ts.map +1 -1
- package/dist/cohere.js +288 -32
- package/dist/cohere.js.map +1 -1
- package/dist/config-loader.d.ts.map +1 -1
- package/dist/embeddings.cjs +21 -3
- package/dist/embeddings.cjs.map +1 -1
- package/dist/embeddings.d.cts +2 -2
- package/dist/embeddings.d.cts.map +1 -1
- package/dist/embeddings.d.ts +2 -2
- package/dist/embeddings.d.ts.map +1 -1
- package/dist/embeddings.js +21 -3
- package/dist/embeddings.js.map +1 -1
- package/dist/gemini.cjs +46 -43
- 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 +46 -43
- package/dist/gemini.js.map +1 -1
- package/dist/helpers.cjs +9 -0
- 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 +9 -0
- package/dist/helpers.js.map +1 -1
- package/dist/images.cjs +19 -1
- package/dist/images.cjs.map +1 -1
- package/dist/images.js +19 -1
- package/dist/images.js.map +1 -1
- package/dist/index.cjs +2 -0
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +3 -3
- package/dist/jest.cjs +10 -3
- package/dist/jest.cjs.map +1 -1
- package/dist/jest.js +10 -3
- package/dist/jest.js.map +1 -1
- package/dist/journal.cjs +1 -1
- package/dist/journal.cjs.map +1 -1
- package/dist/journal.d.cts.map +1 -1
- package/dist/journal.d.ts.map +1 -1
- package/dist/journal.js +1 -1
- package/dist/journal.js.map +1 -1
- package/dist/messages.cjs +3 -2
- package/dist/messages.cjs.map +1 -1
- package/dist/messages.js +3 -2
- package/dist/messages.js.map +1 -1
- package/dist/ollama.cjs +125 -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 +126 -5
- package/dist/ollama.js.map +1 -1
- package/dist/recorder.cjs +224 -53
- package/dist/recorder.cjs.map +1 -1
- package/dist/recorder.js +224 -53
- package/dist/recorder.js.map +1 -1
- package/dist/responses.cjs +10 -1
- package/dist/responses.cjs.map +1 -1
- package/dist/responses.d.cts +2 -1
- package/dist/responses.d.cts.map +1 -1
- package/dist/responses.d.ts +2 -1
- package/dist/responses.d.ts.map +1 -1
- package/dist/responses.js +10 -2
- package/dist/responses.js.map +1 -1
- package/dist/router.cjs +13 -6
- package/dist/router.cjs.map +1 -1
- package/dist/router.js +13 -6
- package/dist/router.js.map +1 -1
- package/dist/server.cjs +144 -62
- 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 +145 -63
- package/dist/server.js.map +1 -1
- package/dist/speech.cjs +19 -1
- package/dist/speech.cjs.map +1 -1
- package/dist/speech.js +19 -1
- package/dist/speech.js.map +1 -1
- package/dist/transcription.cjs +8 -4
- package/dist/transcription.cjs.map +1 -1
- package/dist/transcription.d.cts.map +1 -1
- package/dist/transcription.d.ts.map +1 -1
- package/dist/transcription.js +8 -4
- package/dist/transcription.js.map +1 -1
- package/dist/types.d.cts +1 -0
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.ts +1 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/video.cjs +63 -1
- package/dist/video.cjs.map +1 -1
- package/dist/video.d.cts +15 -2
- package/dist/video.d.cts.map +1 -1
- package/dist/video.d.ts +15 -2
- package/dist/video.d.ts.map +1 -1
- package/dist/video.js +63 -2
- package/dist/video.js.map +1 -1
- package/dist/vitest.cjs +10 -3
- package/dist/vitest.cjs.map +1 -1
- package/dist/vitest.js +10 -3
- package/dist/vitest.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 {\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 completionReq._endpointType = \"chat\";\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 completionReq._endpointType = \"chat\";\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;EAC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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 isContentWithToolCallsResponse,\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 ?? true,\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 ?? true,\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/chat — content + tool calls ────────────────────\n\nfunction buildOllamaChatContentWithToolCallsChunks(\n content: string,\n toolCalls: ToolCall[],\n model: string,\n chunkSize: number,\n logger: Logger,\n): object[] {\n const chunks: object[] = [];\n\n // Content chunks first\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 // Tool calls in a single chunk (same as tool-call-only path)\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 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 buildOllamaChatContentWithToolCallsResponse(\n content: string,\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 completionReq._endpointType = \"chat\";\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, source: \"proxy\" },\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 // Content + tool calls response (must be checked before text/tool-only branches)\n if (isContentWithToolCallsResponse(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 = buildOllamaChatContentWithToolCallsResponse(\n response.content,\n response.toolCalls,\n completionReq.model,\n logger,\n );\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const chunks = buildOllamaChatContentWithToolCallsChunks(\n response.content,\n response.toolCalls,\n completionReq.model,\n chunkSize,\n logger,\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 // 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 completionReq._endpointType = \"chat\";\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, source: \"proxy\" },\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 fixtures matched but not supported on /api/generate\n if (isToolCallResponse(response) || isContentWithToolCallsResponse(response)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: urlPath,\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 400, fixture },\n });\n writeErrorResponse(\n res,\n 400,\n JSON.stringify({\n error: {\n message: \"Tool call fixtures are not supported on /api/generate — use /api/chat instead\",\n type: \"invalid_request_error\",\n },\n }),\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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AI,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/recorder.cjs
CHANGED
|
@@ -67,6 +67,7 @@ async function proxyAndRecord(req, res, request, providerKey, pathname, fixtures
|
|
|
67
67
|
let upstreamBody;
|
|
68
68
|
let rawBuffer;
|
|
69
69
|
let streamedToClient = false;
|
|
70
|
+
let clientDisconnected = false;
|
|
70
71
|
try {
|
|
71
72
|
const result = await makeUpstreamRequest(target, forwardHeaders, requestBody, res);
|
|
72
73
|
upstreamStatus = result.status;
|
|
@@ -74,14 +75,17 @@ async function proxyAndRecord(req, res, request, providerKey, pathname, fixtures
|
|
|
74
75
|
upstreamBody = result.body;
|
|
75
76
|
rawBuffer = result.rawBuffer;
|
|
76
77
|
streamedToClient = result.streamedToClient;
|
|
78
|
+
clientDisconnected = result.clientDisconnected;
|
|
77
79
|
} catch (err) {
|
|
78
80
|
const msg = err instanceof Error ? err.message : "Unknown proxy error";
|
|
79
81
|
defaults.logger.error(`Proxy request failed: ${msg}`);
|
|
80
|
-
res.
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
82
|
+
if (!res.headersSent) {
|
|
83
|
+
res.writeHead(502, { "Content-Type": "application/json" });
|
|
84
|
+
res.end(JSON.stringify({ error: {
|
|
85
|
+
message: `Proxy to upstream failed: ${msg}`,
|
|
86
|
+
type: "proxy_error"
|
|
87
|
+
} }));
|
|
88
|
+
} else res.end();
|
|
85
89
|
return true;
|
|
86
90
|
}
|
|
87
91
|
const contentType = upstreamHeaders["content-type"];
|
|
@@ -100,10 +104,20 @@ async function proxyAndRecord(req, res, request, providerKey, pathname, fixtures
|
|
|
100
104
|
if (collapsed.truncated) defaults.logger.warn("Bedrock EventStream: CRC mismatch — response may be truncated");
|
|
101
105
|
if (collapsed.droppedChunks && collapsed.droppedChunks > 0) defaults.logger.warn(`${collapsed.droppedChunks} chunk(s) dropped during stream collapse`);
|
|
102
106
|
if (collapsed.content === "" && (!collapsed.toolCalls || collapsed.toolCalls.length === 0)) defaults.logger.warn("Stream collapse produced empty content — fixture may be incomplete");
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
+
const reasoningSpread = collapsed.reasoning ? { reasoning: collapsed.reasoning } : {};
|
|
108
|
+
if (collapsed.toolCalls && collapsed.toolCalls.length > 0) if (collapsed.content) fixtureResponse = {
|
|
109
|
+
content: collapsed.content,
|
|
110
|
+
toolCalls: collapsed.toolCalls,
|
|
111
|
+
...reasoningSpread
|
|
112
|
+
};
|
|
113
|
+
else fixtureResponse = {
|
|
114
|
+
toolCalls: collapsed.toolCalls,
|
|
115
|
+
...reasoningSpread
|
|
116
|
+
};
|
|
117
|
+
else fixtureResponse = {
|
|
118
|
+
content: collapsed.content ?? "",
|
|
119
|
+
...reasoningSpread
|
|
120
|
+
};
|
|
107
121
|
} else {
|
|
108
122
|
let parsedResponse = null;
|
|
109
123
|
try {
|
|
@@ -114,9 +128,15 @@ async function proxyAndRecord(req, res, request, providerKey, pathname, fixtures
|
|
|
114
128
|
let encodingFormat;
|
|
115
129
|
try {
|
|
116
130
|
encodingFormat = rawBody ? JSON.parse(rawBody).encoding_format : void 0;
|
|
117
|
-
} catch {
|
|
131
|
+
} catch (err) {
|
|
132
|
+
defaults.logger.debug(`Could not parse encoding_format from raw body: ${err instanceof Error ? err.message : "unknown error"}`);
|
|
133
|
+
}
|
|
118
134
|
fixtureResponse = buildFixtureResponse(parsedResponse, upstreamStatus, encodingFormat);
|
|
119
135
|
}
|
|
136
|
+
if (clientDisconnected) {
|
|
137
|
+
defaults.logger.warn("Client disconnected mid-stream — skipping fixture save to avoid truncated data");
|
|
138
|
+
return true;
|
|
139
|
+
}
|
|
120
140
|
const fixtureMatch = buildFixtureMatch(defaults.requestTransform ? defaults.requestTransform(request) : request);
|
|
121
141
|
const fixture = {
|
|
122
142
|
match: fixtureMatch,
|
|
@@ -141,7 +161,8 @@ async function proxyAndRecord(req, res, request, providerKey, pathname, fixtures
|
|
|
141
161
|
} catch (err) {
|
|
142
162
|
const msg = err instanceof Error ? err.message : "Unknown filesystem error";
|
|
143
163
|
defaults.logger.error(`Failed to save fixture to disk: ${msg}`);
|
|
144
|
-
res.setHeader("X-LLMock-Record-Error", msg);
|
|
164
|
+
if (!res.headersSent) res.setHeader("X-LLMock-Record-Error", msg);
|
|
165
|
+
else defaults.logger.warn(`Cannot set X-LLMock-Record-Error header — headers already sent`);
|
|
145
166
|
}
|
|
146
167
|
if (writtenToDisk) {
|
|
147
168
|
if (!isEmptyMatch) fixtures.push(fixture);
|
|
@@ -152,7 +173,8 @@ async function proxyAndRecord(req, res, request, providerKey, pathname, fixtures
|
|
|
152
173
|
const relayHeaders = {};
|
|
153
174
|
if (ctString) relayHeaders["Content-Type"] = ctString;
|
|
154
175
|
res.writeHead(upstreamStatus, relayHeaders);
|
|
155
|
-
|
|
176
|
+
const isAudioRelay = ctString.toLowerCase().startsWith("audio/");
|
|
177
|
+
res.end(isBinaryStream || isAudioRelay ? rawBuffer : upstreamBody);
|
|
156
178
|
}
|
|
157
179
|
return true;
|
|
158
180
|
}
|
|
@@ -176,28 +198,34 @@ function makeUpstreamRequest(target, headers, body, clientRes) {
|
|
|
176
198
|
const ctStr = Array.isArray(ct) ? ct.join(", ") : ct ?? "";
|
|
177
199
|
const isSSE = ctStr.toLowerCase().includes("text/event-stream");
|
|
178
200
|
let streamedToClient = false;
|
|
201
|
+
let clientDisconnected = false;
|
|
179
202
|
if (isSSE && clientRes && !clientRes.headersSent) {
|
|
180
203
|
const relayHeaders = {};
|
|
181
204
|
if (ctStr) relayHeaders["Content-Type"] = ctStr;
|
|
182
205
|
clientRes.writeHead(res.statusCode ?? 200, relayHeaders);
|
|
183
206
|
if (typeof clientRes.flushHeaders === "function") clientRes.flushHeaders();
|
|
184
207
|
streamedToClient = true;
|
|
208
|
+
clientRes.on("close", () => {
|
|
209
|
+
clientDisconnected = true;
|
|
210
|
+
req.destroy();
|
|
211
|
+
});
|
|
185
212
|
}
|
|
186
213
|
const chunks = [];
|
|
187
214
|
res.on("data", (chunk) => {
|
|
188
215
|
chunks.push(chunk);
|
|
189
|
-
if (streamedToClient) clientRes.write(chunk);
|
|
216
|
+
if (streamedToClient && clientRes && !clientDisconnected && !clientRes.destroyed && !clientRes.writableEnded) clientRes.write(chunk);
|
|
190
217
|
});
|
|
191
218
|
res.on("error", reject);
|
|
192
219
|
res.on("end", () => {
|
|
193
220
|
const rawBuffer = Buffer.concat(chunks);
|
|
194
|
-
if (streamedToClient) clientRes.end();
|
|
221
|
+
if (streamedToClient && clientRes && !clientDisconnected && !clientRes.destroyed && !clientRes.writableEnded) clientRes.end();
|
|
195
222
|
resolve({
|
|
196
223
|
status: res.statusCode ?? 500,
|
|
197
224
|
headers: res.headers,
|
|
198
225
|
body: rawBuffer.toString(),
|
|
199
226
|
rawBuffer,
|
|
200
|
-
streamedToClient
|
|
227
|
+
streamedToClient,
|
|
228
|
+
clientDisconnected
|
|
201
229
|
});
|
|
202
230
|
});
|
|
203
231
|
});
|
|
@@ -222,7 +250,7 @@ function buildFixtureResponse(parsed, status, encodingFormat) {
|
|
|
222
250
|
status
|
|
223
251
|
};
|
|
224
252
|
const obj = parsed;
|
|
225
|
-
if (obj.error) {
|
|
253
|
+
if (typeof obj.error === "object" && obj.error !== null && typeof obj.error.message === "string") {
|
|
226
254
|
const err = obj.error;
|
|
227
255
|
return {
|
|
228
256
|
error: {
|
|
@@ -236,11 +264,12 @@ function buildFixtureResponse(parsed, status, encodingFormat) {
|
|
|
236
264
|
if (Array.isArray(obj.data) && obj.data.length > 0) {
|
|
237
265
|
const first = obj.data[0];
|
|
238
266
|
if (Array.isArray(first.embedding)) return { embedding: first.embedding };
|
|
239
|
-
if (typeof first.embedding === "string" && encodingFormat === "base64")
|
|
267
|
+
if (typeof first.embedding === "string" && encodingFormat === "base64") {
|
|
240
268
|
const buf = Buffer.from(first.embedding, "base64");
|
|
241
|
-
const
|
|
269
|
+
const aligned = new Uint8Array(buf).buffer;
|
|
270
|
+
const floats = new Float32Array(aligned, 0, buf.byteLength / 4);
|
|
242
271
|
return { embedding: Array.from(floats) };
|
|
243
|
-
}
|
|
272
|
+
}
|
|
244
273
|
if (first.url || first.b64_json) {
|
|
245
274
|
const images = obj.data.map((item) => ({
|
|
246
275
|
...item.url ? { url: String(item.url) } : {},
|
|
@@ -266,7 +295,7 @@ function buildFixtureResponse(parsed, status, encodingFormat) {
|
|
|
266
295
|
...Array.isArray(obj.words) ? { words: obj.words } : {},
|
|
267
296
|
...Array.isArray(obj.segments) ? { segments: obj.segments } : {}
|
|
268
297
|
} };
|
|
269
|
-
if (typeof obj.id === "string" && typeof obj.status === "string" && (obj.status === "completed" || obj.status === "in_progress" || obj.status === "failed")) {
|
|
298
|
+
if (typeof obj.id === "string" && typeof obj.status === "string" && (obj.status === "completed" || obj.status === "in_progress" || obj.status === "failed") && !("choices" in obj) && !("content" in obj) && !("candidates" in obj) && !("message" in obj) && !("data" in obj) && !("object" in obj)) {
|
|
270
299
|
if (obj.status === "completed" && obj.url) return { video: {
|
|
271
300
|
id: String(obj.id),
|
|
272
301
|
status: "completed",
|
|
@@ -281,40 +310,109 @@ function buildFixtureResponse(parsed, status, encodingFormat) {
|
|
|
281
310
|
if (Array.isArray(obj.choices) && obj.choices.length > 0) {
|
|
282
311
|
const message = obj.choices[0].message;
|
|
283
312
|
if (message) {
|
|
284
|
-
|
|
285
|
-
|
|
313
|
+
const hasToolCalls = Array.isArray(message.tool_calls) && message.tool_calls.length > 0;
|
|
314
|
+
const hasContent = typeof message.content === "string" && message.content.length > 0;
|
|
315
|
+
const openaiReasoning = typeof message.reasoning_content === "string" && message.reasoning_content.length > 0 ? message.reasoning_content : void 0;
|
|
316
|
+
if (hasToolCalls) {
|
|
317
|
+
const toolCalls = message.tool_calls.map((tc) => {
|
|
318
|
+
const fn = tc.function;
|
|
319
|
+
return {
|
|
320
|
+
name: String(fn.name),
|
|
321
|
+
arguments: String(fn.arguments),
|
|
322
|
+
...tc.id ? { id: String(tc.id) } : {}
|
|
323
|
+
};
|
|
324
|
+
});
|
|
325
|
+
if (hasContent) return {
|
|
326
|
+
content: message.content,
|
|
327
|
+
toolCalls,
|
|
328
|
+
...openaiReasoning ? { reasoning: openaiReasoning } : {}
|
|
329
|
+
};
|
|
286
330
|
return {
|
|
287
|
-
|
|
288
|
-
|
|
331
|
+
toolCalls,
|
|
332
|
+
...openaiReasoning ? { reasoning: openaiReasoning } : {}
|
|
289
333
|
};
|
|
290
|
-
}
|
|
291
|
-
if (
|
|
334
|
+
}
|
|
335
|
+
if (hasContent) return {
|
|
336
|
+
content: message.content,
|
|
337
|
+
...openaiReasoning ? { reasoning: openaiReasoning } : {}
|
|
338
|
+
};
|
|
339
|
+
return {
|
|
340
|
+
content: "",
|
|
341
|
+
...openaiReasoning ? { reasoning: openaiReasoning } : {}
|
|
342
|
+
};
|
|
292
343
|
}
|
|
293
344
|
}
|
|
294
345
|
if (Array.isArray(obj.content) && obj.content.length > 0) {
|
|
295
346
|
const blocks = obj.content;
|
|
296
347
|
const toolUseBlocks = blocks.filter((b) => b.type === "tool_use");
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
const
|
|
302
|
-
|
|
348
|
+
const textBlocks = blocks.filter((b) => b.type === "text" && typeof b.text === "string");
|
|
349
|
+
const thinkingBlocks = blocks.filter((b) => b.type === "thinking");
|
|
350
|
+
const hasToolCalls = toolUseBlocks.length > 0;
|
|
351
|
+
const joinedText = textBlocks.map((b) => String(b.text ?? "")).join("");
|
|
352
|
+
const hasContent = joinedText.length > 0;
|
|
353
|
+
const anthropicReasoning = thinkingBlocks.length > 0 ? thinkingBlocks.map((b) => String(b.thinking ?? "")).join("") : void 0;
|
|
354
|
+
if (hasToolCalls) {
|
|
355
|
+
const toolCalls = toolUseBlocks.map((b) => ({
|
|
356
|
+
name: String(b.name),
|
|
357
|
+
arguments: typeof b.input === "string" ? b.input : JSON.stringify(b.input),
|
|
358
|
+
...b.id ? { id: String(b.id) } : {}
|
|
359
|
+
}));
|
|
360
|
+
if (hasContent) return {
|
|
361
|
+
content: joinedText,
|
|
362
|
+
toolCalls,
|
|
363
|
+
...anthropicReasoning ? { reasoning: anthropicReasoning } : {}
|
|
364
|
+
};
|
|
365
|
+
return {
|
|
366
|
+
toolCalls,
|
|
367
|
+
...anthropicReasoning ? { reasoning: anthropicReasoning } : {}
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
if (hasContent) return {
|
|
371
|
+
content: joinedText,
|
|
372
|
+
...anthropicReasoning ? { reasoning: anthropicReasoning } : {}
|
|
373
|
+
};
|
|
374
|
+
if (anthropicReasoning) return {
|
|
375
|
+
content: "",
|
|
376
|
+
reasoning: anthropicReasoning
|
|
377
|
+
};
|
|
303
378
|
}
|
|
304
379
|
if (Array.isArray(obj.candidates) && obj.candidates.length > 0) {
|
|
305
380
|
const content = obj.candidates[0].content;
|
|
306
381
|
if (content && Array.isArray(content.parts)) {
|
|
307
382
|
const parts = content.parts;
|
|
308
383
|
const fnCallParts = parts.filter((p) => p.functionCall);
|
|
309
|
-
|
|
310
|
-
|
|
384
|
+
const textParts = parts.filter((p) => typeof p.text === "string" && !p.thought);
|
|
385
|
+
const thoughtParts = parts.filter((p) => p.thought === true && typeof p.text === "string");
|
|
386
|
+
const hasToolCalls = fnCallParts.length > 0;
|
|
387
|
+
const joinedText = textParts.map((p) => String(p.text ?? "")).join("");
|
|
388
|
+
const hasContent = joinedText.length > 0;
|
|
389
|
+
const geminiReasoning = thoughtParts.length > 0 ? thoughtParts.map((p) => String(p.text ?? "")).join("") : void 0;
|
|
390
|
+
if (hasToolCalls) {
|
|
391
|
+
const toolCalls = fnCallParts.map((p) => {
|
|
392
|
+
const fc = p.functionCall;
|
|
393
|
+
return {
|
|
394
|
+
name: String(fc.name),
|
|
395
|
+
arguments: typeof fc.args === "string" ? fc.args : JSON.stringify(fc.args)
|
|
396
|
+
};
|
|
397
|
+
});
|
|
398
|
+
if (hasContent) return {
|
|
399
|
+
content: joinedText,
|
|
400
|
+
toolCalls,
|
|
401
|
+
...geminiReasoning ? { reasoning: geminiReasoning } : {}
|
|
402
|
+
};
|
|
311
403
|
return {
|
|
312
|
-
|
|
313
|
-
|
|
404
|
+
toolCalls,
|
|
405
|
+
...geminiReasoning ? { reasoning: geminiReasoning } : {}
|
|
314
406
|
};
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
|
|
407
|
+
}
|
|
408
|
+
if (hasContent) return {
|
|
409
|
+
content: joinedText,
|
|
410
|
+
...geminiReasoning ? { reasoning: geminiReasoning } : {}
|
|
411
|
+
};
|
|
412
|
+
return {
|
|
413
|
+
content: "",
|
|
414
|
+
...geminiReasoning ? { reasoning: geminiReasoning } : {}
|
|
415
|
+
};
|
|
318
416
|
}
|
|
319
417
|
}
|
|
320
418
|
if (obj.output && typeof obj.output === "object") {
|
|
@@ -322,32 +420,105 @@ function buildFixtureResponse(parsed, status, encodingFormat) {
|
|
|
322
420
|
if (msg && Array.isArray(msg.content)) {
|
|
323
421
|
const blocks = msg.content;
|
|
324
422
|
const toolUseBlocks = blocks.filter((b) => b.toolUse);
|
|
325
|
-
|
|
326
|
-
|
|
423
|
+
const textBlocks = blocks.filter((b) => typeof b.text === "string");
|
|
424
|
+
const reasoningBlocks = blocks.filter((b) => b.reasoningContent);
|
|
425
|
+
const hasToolCalls = toolUseBlocks.length > 0;
|
|
426
|
+
const joinedText = textBlocks.map((b) => String(b.text ?? "")).join("");
|
|
427
|
+
const hasContent = joinedText.length > 0;
|
|
428
|
+
const bedrockReasoning = reasoningBlocks.length > 0 ? reasoningBlocks.map((b) => {
|
|
429
|
+
const rt = b.reasoningContent?.reasoningText;
|
|
430
|
+
return String(rt?.text ?? "");
|
|
431
|
+
}).join("") : void 0;
|
|
432
|
+
if (hasToolCalls) {
|
|
433
|
+
const toolCalls = toolUseBlocks.map((b) => {
|
|
434
|
+
const tu = b.toolUse;
|
|
435
|
+
return {
|
|
436
|
+
name: String(tu.name ?? ""),
|
|
437
|
+
arguments: typeof tu.input === "string" ? tu.input : JSON.stringify(tu.input),
|
|
438
|
+
...tu.toolUseId ? { id: String(tu.toolUseId) } : {}
|
|
439
|
+
};
|
|
440
|
+
});
|
|
441
|
+
if (hasContent) return {
|
|
442
|
+
content: joinedText,
|
|
443
|
+
toolCalls,
|
|
444
|
+
...bedrockReasoning ? { reasoning: bedrockReasoning } : {}
|
|
445
|
+
};
|
|
327
446
|
return {
|
|
328
|
-
|
|
329
|
-
|
|
447
|
+
toolCalls,
|
|
448
|
+
...bedrockReasoning ? { reasoning: bedrockReasoning } : {}
|
|
330
449
|
};
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
|
|
450
|
+
}
|
|
451
|
+
if (hasContent) return {
|
|
452
|
+
content: joinedText,
|
|
453
|
+
...bedrockReasoning ? { reasoning: bedrockReasoning } : {}
|
|
454
|
+
};
|
|
455
|
+
return {
|
|
456
|
+
content: "",
|
|
457
|
+
...bedrockReasoning ? { reasoning: bedrockReasoning } : {}
|
|
458
|
+
};
|
|
334
459
|
}
|
|
335
460
|
}
|
|
461
|
+
if (typeof obj.finish_reason === "string" && obj.message && typeof obj.message === "object" && Array.isArray(obj.message.content)) {
|
|
462
|
+
const msg = obj.message;
|
|
463
|
+
const contentBlocks = msg.content;
|
|
464
|
+
const textBlock = contentBlocks.find((b) => b.type === "text" && typeof b.text === "string");
|
|
465
|
+
const hasContent = textBlock && typeof textBlock.text === "string" && textBlock.text.length > 0;
|
|
466
|
+
const toolCallBlocks = contentBlocks.filter((b) => b.type === "tool_call");
|
|
467
|
+
const msgToolCalls = Array.isArray(msg.tool_calls) ? msg.tool_calls : [];
|
|
468
|
+
if (toolCallBlocks.length > 0) {
|
|
469
|
+
const toolCalls = toolCallBlocks.map((b) => ({
|
|
470
|
+
name: String(b.name ?? b.function?.name ?? ""),
|
|
471
|
+
arguments: typeof b.parameters === "string" ? b.parameters : typeof b.parameters === "object" ? JSON.stringify(b.parameters) : typeof b.function?.arguments === "string" ? String(b.function.arguments) : JSON.stringify(b.function?.arguments),
|
|
472
|
+
...b.id ? { id: String(b.id) } : {}
|
|
473
|
+
}));
|
|
474
|
+
if (hasContent) return {
|
|
475
|
+
content: textBlock.text,
|
|
476
|
+
toolCalls
|
|
477
|
+
};
|
|
478
|
+
return { toolCalls };
|
|
479
|
+
}
|
|
480
|
+
if (msgToolCalls.length > 0) {
|
|
481
|
+
const toolCalls = msgToolCalls.map((tc) => {
|
|
482
|
+
const fn = tc.function;
|
|
483
|
+
return {
|
|
484
|
+
name: String(tc.name ?? fn?.name ?? ""),
|
|
485
|
+
arguments: typeof tc.parameters === "string" ? tc.parameters : typeof tc.parameters === "object" ? JSON.stringify(tc.parameters) : typeof fn?.arguments === "string" ? String(fn.arguments) : JSON.stringify(fn?.arguments),
|
|
486
|
+
...tc.id ? { id: String(tc.id) } : {}
|
|
487
|
+
};
|
|
488
|
+
});
|
|
489
|
+
if (hasContent) return {
|
|
490
|
+
content: textBlock.text,
|
|
491
|
+
toolCalls
|
|
492
|
+
};
|
|
493
|
+
return { toolCalls };
|
|
494
|
+
}
|
|
495
|
+
if (hasContent) return { content: textBlock.text };
|
|
496
|
+
}
|
|
336
497
|
if (obj.message && typeof obj.message === "object") {
|
|
337
498
|
const msg = obj.message;
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
499
|
+
const hasOllamaToolCalls = Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0;
|
|
500
|
+
const hasOllamaContent = typeof msg.content === "string" && msg.content.length > 0;
|
|
501
|
+
if (hasOllamaToolCalls) {
|
|
502
|
+
const toolCalls = msg.tool_calls.filter((tc) => tc.function != null).map((tc) => {
|
|
503
|
+
const fn = tc.function;
|
|
504
|
+
return {
|
|
505
|
+
name: String(fn.name ?? ""),
|
|
506
|
+
arguments: typeof fn.arguments === "string" ? fn.arguments : JSON.stringify(fn.arguments)
|
|
507
|
+
};
|
|
508
|
+
});
|
|
509
|
+
if (hasOllamaContent) return {
|
|
510
|
+
content: msg.content,
|
|
511
|
+
toolCalls
|
|
343
512
|
};
|
|
344
|
-
|
|
345
|
-
|
|
513
|
+
return { toolCalls };
|
|
514
|
+
}
|
|
515
|
+
if (hasOllamaContent) return { content: msg.content };
|
|
346
516
|
if (Array.isArray(msg.content) && msg.content.length > 0) {
|
|
347
517
|
const first = msg.content[0];
|
|
348
518
|
if (typeof first.text === "string") return { content: first.text };
|
|
349
519
|
}
|
|
350
520
|
}
|
|
521
|
+
if (typeof obj.response === "string" && "done" in obj) return { content: obj.response };
|
|
351
522
|
return {
|
|
352
523
|
error: {
|
|
353
524
|
message: "Could not detect response format from upstream",
|