@langchain/core 1.3.5 → 1.3.7
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 +14 -0
- package/dist/errors/index.cjs +56 -0
- package/dist/errors/index.cjs.map +1 -1
- package/dist/errors/index.d.cts +48 -0
- package/dist/errors/index.d.cts.map +1 -1
- package/dist/errors/index.d.ts +48 -0
- package/dist/errors/index.d.ts.map +1 -1
- package/dist/errors/index.js +56 -1
- package/dist/errors/index.js.map +1 -1
- package/dist/language_models/base.cjs +1 -1
- package/dist/language_models/base.js +1 -1
- package/dist/messages/block_translators/anthropic.cjs +18 -0
- package/dist/messages/block_translators/anthropic.cjs.map +1 -1
- package/dist/messages/block_translators/anthropic.js +18 -0
- package/dist/messages/block_translators/anthropic.js.map +1 -1
- package/dist/messages/block_translators/google.cjs +27 -1
- package/dist/messages/block_translators/google.cjs.map +1 -1
- package/dist/messages/block_translators/google.js +27 -1
- package/dist/messages/block_translators/google.js.map +1 -1
- package/dist/messages/block_translators/openai.cjs +25 -0
- package/dist/messages/block_translators/openai.cjs.map +1 -1
- package/dist/messages/block_translators/openai.js +25 -0
- package/dist/messages/block_translators/openai.js.map +1 -1
- package/dist/messages/content/index.cjs +1 -0
- package/dist/messages/content/index.cjs.map +1 -1
- package/dist/messages/content/index.d.cts +23 -1
- package/dist/messages/content/index.d.cts.map +1 -1
- package/dist/messages/content/index.d.ts +23 -1
- package/dist/messages/content/index.d.ts.map +1 -1
- package/dist/messages/content/index.js +1 -0
- package/dist/messages/content/index.js.map +1 -1
- package/dist/output_parsers/json.cjs +8 -0
- package/dist/output_parsers/json.cjs.map +1 -1
- package/dist/output_parsers/json.d.cts +5 -0
- package/dist/output_parsers/json.d.cts.map +1 -1
- package/dist/output_parsers/json.d.ts +5 -0
- package/dist/output_parsers/json.d.ts.map +1 -1
- package/dist/output_parsers/json.js +8 -0
- package/dist/output_parsers/json.js.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs +3 -0
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.cjs.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.d.cts.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.d.ts.map +1 -1
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.js +3 -0
- package/dist/output_parsers/openai_tools/json_output_tools_parsers.js.map +1 -1
- package/dist/output_parsers/refusal.cjs +23 -0
- package/dist/output_parsers/refusal.cjs.map +1 -0
- package/dist/output_parsers/refusal.js +23 -0
- package/dist/output_parsers/refusal.js.map +1 -0
- package/dist/output_parsers/standard_schema.cjs +8 -0
- package/dist/output_parsers/standard_schema.cjs.map +1 -1
- package/dist/output_parsers/standard_schema.d.cts +6 -0
- package/dist/output_parsers/standard_schema.d.cts.map +1 -1
- package/dist/output_parsers/standard_schema.d.ts +6 -0
- package/dist/output_parsers/standard_schema.d.ts.map +1 -1
- package/dist/output_parsers/standard_schema.js +8 -0
- package/dist/output_parsers/standard_schema.js.map +1 -1
- package/dist/output_parsers/structured.cjs +8 -0
- package/dist/output_parsers/structured.cjs.map +1 -1
- package/dist/output_parsers/structured.d.cts +6 -0
- package/dist/output_parsers/structured.d.cts.map +1 -1
- package/dist/output_parsers/structured.d.ts +6 -0
- package/dist/output_parsers/structured.d.ts.map +1 -1
- package/dist/output_parsers/structured.js +8 -0
- package/dist/output_parsers/structured.js.map +1 -1
- package/dist/runnables/base.cjs +7 -1
- package/dist/runnables/base.cjs.map +1 -1
- package/dist/runnables/base.d.cts.map +1 -1
- package/dist/runnables/base.d.ts.map +1 -1
- package/dist/runnables/base.js +7 -1
- package/dist/runnables/base.js.map +1 -1
- package/dist/tracers/event_stream.cjs +8 -3
- package/dist/tracers/event_stream.cjs.map +1 -1
- package/dist/tracers/event_stream.js +8 -3
- package/dist/tracers/event_stream.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai.js","names":[],"sources":["../../../src/messages/block_translators/openai.ts"],"sourcesContent":["import type { ContentBlock } from \"../content/index.js\";\nimport type { AIMessageChunk, AIMessage } from \"../ai.js\";\nimport type { StandardContentBlockTranslator } from \"./index.js\";\nimport { convertToV1FromOpenAIDataBlock, isOpenAIDataBlock } from \"./data.js\";\nimport {\n _isArray,\n _isContentBlock,\n _isObject,\n _isString,\n iife,\n} from \"./utils.js\";\n\n/**\n * Converts a ChatOpenAICompletions message to an array of v1 standard content blocks.\n *\n * This function processes an AI message from ChatOpenAICompletions API format\n * and converts it to the standardized v1 content block format. It handles both\n * string content and structured content blocks, as well as tool calls.\n *\n * @param message - The AI message containing ChatOpenAICompletions formatted content\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const message = new AIMessage(\"Hello world\");\n * const standardBlocks = convertToV1FromChatCompletions(message);\n * // Returns: [{ type: \"text\", text: \"Hello world\" }]\n * ```\n *\n * @example\n * ```typescript\n * const message = new AIMessage([\n * { type: \"text\", text: \"Hello\" },\n * { type: \"image_url\", image_url: { url: \"https://example.com/image.png\" } }\n * ]);\n * message.tool_calls = [\n * { id: \"call_123\", name: \"calculator\", args: { a: 1, b: 2 } }\n * ];\n *\n * const standardBlocks = convertToV1FromChatCompletions(message);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello\" },\n * // { type: \"image\", url: \"https://example.com/image.png\" },\n * // { type: \"tool_call\", id: \"call_123\", name: \"calculator\", args: { a: 1, b: 2 } }\n * // ]\n * ```\n */\nexport function convertToV1FromChatCompletions(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock.Standard> = [];\n if (typeof message.content === \"string\") {\n // Only add text block if content is non-empty\n if (message.content.length > 0) {\n blocks.push({\n type: \"text\",\n text: message.content,\n });\n }\n } else {\n blocks.push(...convertToV1FromChatCompletionsInput(message.content));\n }\n for (const toolCall of message.tool_calls ?? []) {\n blocks.push({\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n });\n }\n return blocks;\n}\n\n/**\n * Converts a ChatOpenAICompletions message chunk to an array of v1 standard content blocks.\n *\n * This function processes an AI message chunk from OpenAI's chat completions API and converts\n * it to the standardized v1 content block format. It handles both string and array content,\n * as well as tool calls that may be present in the chunk.\n *\n * @param message - The AI message chunk containing OpenAI-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const chunk = new AIMessage(\"Hello\");\n * const standardBlocks = convertToV1FromChatCompletionsChunk(chunk);\n * // Returns: [{ type: \"text\", text: \"Hello\" }]\n * ```\n *\n * @example\n * ```typescript\n * const chunk = new AIMessage([\n * { type: \"text\", text: \"Processing...\" }\n * ]);\n * chunk.tool_calls = [\n * { id: \"call_456\", name: \"search\", args: { query: \"test\" } }\n * ];\n *\n * const standardBlocks = convertToV1FromChatCompletionsChunk(chunk);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Processing...\" },\n * // { type: \"tool_call\", id: \"call_456\", name: \"search\", args: { query: \"test\" } }\n * // ]\n * ```\n */\nexport function convertToV1FromChatCompletionsChunk(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock.Standard> = [];\n if (typeof message.content === \"string\") {\n // Only add text block if content is non-empty\n if (message.content.length > 0) {\n blocks.push({\n type: \"text\",\n text: message.content,\n });\n }\n } else {\n blocks.push(...convertToV1FromChatCompletionsInput(message.content));\n }\n\n // TODO: parse chunk position information\n for (const toolCall of message.tool_calls ?? []) {\n blocks.push({\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n });\n }\n return blocks;\n}\n\n/**\n * Converts an array of ChatOpenAICompletions content blocks to v1 standard content blocks.\n *\n * This function processes content blocks from OpenAI's Chat Completions API format\n * and converts them to the standardized v1 content block format. It handles both\n * OpenAI-specific data blocks (which require conversion) and standard blocks\n * (which are passed through with type assertion).\n *\n * @param blocks - Array of content blocks in ChatOpenAICompletions format\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const openaiBlocks = [\n * { type: \"text\", text: \"Hello world\" },\n * { type: \"image_url\", image_url: { url: \"https://example.com/image.png\" } }\n * ];\n *\n * const standardBlocks = convertToV1FromChatCompletionsInput(openaiBlocks);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello world\" },\n * // { type: \"image\", url: \"https://example.com/image.png\" }\n * // ]\n * ```\n */\nexport function convertToV1FromChatCompletionsInput(\n blocks: Array<ContentBlock>\n): Array<ContentBlock.Standard> {\n const convertedBlocks: Array<ContentBlock.Standard> = [];\n for (const block of blocks) {\n if (isOpenAIDataBlock(block)) {\n convertedBlocks.push(convertToV1FromOpenAIDataBlock(block));\n } else {\n convertedBlocks.push(block as ContentBlock.Standard);\n }\n }\n return convertedBlocks;\n}\n\nfunction convertResponsesAnnotation(\n annotation: ContentBlock\n): ContentBlock | ContentBlock.Citation {\n if (annotation.type === \"url_citation\") {\n const { url, title, start_index, end_index } = annotation;\n return {\n type: \"citation\",\n url,\n title,\n startIndex: start_index,\n endIndex: end_index,\n };\n }\n if (annotation.type === \"file_citation\") {\n const { file_id, filename, index } = annotation;\n return {\n type: \"citation\",\n title: filename,\n startIndex: index,\n endIndex: index,\n fileId: file_id,\n };\n }\n return annotation;\n}\n\n/** Builds a reasoning content block, including id/encrypted_content when present. */\nfunction mapReasoningItemToV1(\n item: Record<string, unknown>\n): ContentBlock.Standard | undefined {\n if (!_isArray(item.summary)) return undefined;\n const summary = item.summary.reduce<string>((acc, part) => {\n if (_isObject(part) && _isString(part.text)) {\n return `${acc}${part.text}`;\n }\n return acc;\n }, \"\");\n return {\n type: \"reasoning\",\n reasoning: summary,\n ...(_isString(item.id) ? { id: item.id } : {}),\n ...(_isString(item.encrypted_content)\n ? { encrypted_content: item.encrypted_content }\n : {}),\n } as ContentBlock.Standard;\n}\n\n// Converts a single built-in tool call/result entry into v1 content blocks.\nfunction* mapToolOutputToV1Blocks(\n toolOutput: unknown\n): Iterable<ContentBlock.Standard> {\n if (_isContentBlock(toolOutput, \"web_search_call\")) {\n const webSearchArgs: Record<string, unknown> = {};\n if (_isObject(toolOutput.action) && _isString(toolOutput.action.query)) {\n webSearchArgs.query = toolOutput.action.query;\n }\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"web_search\",\n args: webSearchArgs,\n };\n // Emit a server_tool_call_result when the search has completed or failed\n if (toolOutput.status === \"completed\" || toolOutput.status === \"failed\") {\n const output: Record<string, unknown> = {};\n if (_isObject(toolOutput.action)) {\n output.action = toolOutput.action;\n }\n yield {\n type: \"server_tool_call_result\",\n toolCallId: _isString(toolOutput.id) ? toolOutput.id : \"\",\n status: toolOutput.status === \"completed\" ? \"success\" : \"error\",\n output,\n };\n }\n return;\n }\n if (_isContentBlock(toolOutput, \"file_search_call\")) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"file_search\",\n args: {\n queries: _isArray(toolOutput.queries) ? toolOutput.queries : [],\n },\n };\n // Emit a server_tool_call_result when results are available\n if (toolOutput.status === \"completed\" || toolOutput.status === \"failed\") {\n yield {\n type: \"server_tool_call_result\",\n toolCallId: _isString(toolOutput.id) ? toolOutput.id : \"\",\n status: toolOutput.status === \"completed\" ? \"success\" : \"error\",\n output: _isArray(toolOutput.results)\n ? { results: toolOutput.results }\n : {},\n };\n }\n return;\n }\n if (_isContentBlock(toolOutput, \"computer_call\")) {\n yield { type: \"non_standard\", value: toolOutput };\n return;\n }\n if (_isContentBlock(toolOutput, \"code_interpreter_call\")) {\n if (_isString(toolOutput.code)) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"code_interpreter\",\n args: { code: toolOutput.code },\n };\n }\n if (_isArray(toolOutput.outputs)) {\n const returnCode = iife(() => {\n if (toolOutput.status === \"in_progress\") return undefined;\n if (toolOutput.status === \"completed\") return 0;\n if (toolOutput.status === \"incomplete\") return 127;\n if (toolOutput.status === \"interpreting\") return undefined;\n if (toolOutput.status === \"failed\") return 1;\n return undefined;\n });\n for (const output of toolOutput.outputs) {\n if (_isContentBlock(output, \"logs\")) {\n yield {\n type: \"server_tool_call_result\",\n toolCallId: toolOutput.id ?? \"\",\n status: \"success\",\n output: {\n type: \"code_interpreter_output\",\n returnCode: returnCode ?? 0,\n stderr: [0, undefined].includes(returnCode)\n ? undefined\n : String(output.logs),\n stdout: [0, undefined].includes(returnCode)\n ? String(output.logs)\n : undefined,\n },\n };\n }\n }\n }\n return;\n }\n if (_isContentBlock(toolOutput, \"mcp_call\")) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"mcp_call\",\n args: toolOutput.input,\n };\n return;\n }\n if (_isContentBlock(toolOutput, \"mcp_list_tools\")) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"mcp_list_tools\",\n args: toolOutput.input,\n };\n return;\n }\n if (_isContentBlock(toolOutput, \"mcp_approval_request\")) {\n yield { type: \"non_standard\", value: toolOutput };\n return;\n }\n if (_isContentBlock(toolOutput, \"tool_search_call\")) {\n const toolSearchArgs: Record<string, unknown> = {};\n if (_isObject(toolOutput.arguments)) {\n Object.assign(toolSearchArgs, toolOutput.arguments);\n }\n const toolSearchCallExtras: Record<string, unknown> = {};\n if (_isString(toolOutput.execution)) {\n toolSearchCallExtras.execution = toolOutput.execution;\n }\n if (_isString(toolOutput.status)) {\n toolSearchCallExtras.status = toolOutput.status;\n }\n if (_isString(toolOutput.call_id)) {\n toolSearchCallExtras.call_id = toolOutput.call_id;\n }\n yield {\n id: _isString(toolOutput.id) ? toolOutput.id : \"\",\n type: \"server_tool_call\",\n name: \"tool_search\",\n args: toolSearchArgs,\n ...(Object.keys(toolSearchCallExtras).length > 0\n ? { extras: toolSearchCallExtras }\n : {}),\n };\n return;\n }\n if (_isContentBlock(toolOutput, \"tool_search_output\")) {\n const toolSearchOutputExtras: Record<string, unknown> = {\n name: \"tool_search\",\n };\n if (_isString(toolOutput.execution)) {\n toolSearchOutputExtras.execution = toolOutput.execution;\n }\n yield {\n type: \"server_tool_call_result\",\n toolCallId: _isString(toolOutput.id) ? toolOutput.id : \"\",\n status:\n toolOutput.status === \"completed\"\n ? \"success\"\n : toolOutput.status === \"failed\"\n ? \"error\"\n : \"success\",\n output: {\n tools: _isArray(toolOutput.tools) ? toolOutput.tools : [],\n },\n extras: toolSearchOutputExtras,\n };\n return;\n }\n if (_isContentBlock(toolOutput, \"image_generation_call\")) {\n // Convert image_generation_call to proper image content block if result is available\n if (_isString(toolOutput.result)) {\n yield {\n type: \"image\",\n mimeType: \"image/png\",\n data: toolOutput.result,\n id: _isString(toolOutput.id) ? toolOutput.id : undefined,\n metadata: {\n status: _isString(toolOutput.status) ? toolOutput.status : undefined,\n },\n };\n }\n // Also yield as non_standard for backwards compatibility\n yield { type: \"non_standard\", value: toolOutput };\n return;\n }\n if (_isObject(toolOutput)) {\n yield { type: \"non_standard\", value: toolOutput };\n }\n}\n\n/**\n * Converts a ChatOpenAIResponses message to an array of v1 standard content blocks.\n *\n * This function processes an AI message containing OpenAI Responses-specific content blocks\n * and converts them to the standardized v1 content block format. It handles reasoning summaries,\n * text content with annotations, tool calls, and various tool outputs including code interpreter,\n * web search, file search, computer calls, and MCP-related blocks.\n *\n * A response can hold more than one reasoning item (e.g. multiple tool calls\n * in one turn, common on GPT-5.6-class models). When `response_metadata.output`\n * is available, each item's own `id`/`encrypted_content` is preserved and\n * blocks are sorted back into original order, so replay under Zero Data\n * Retention interleaves reasoning and tool calls correctly. Without it (e.g.\n * a hand-built message), falls back to a single reasoning block from\n * `additional_kwargs.reasoning`, as before.\n *\n * @param message - The AI message containing OpenAI Responses-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const message = new AIMessage({\n * content: [{ type: \"text\", text: \"Hello world\", annotations: [] }],\n * tool_calls: [{ id: \"123\", name: \"calculator\", args: { a: 1, b: 2 } }],\n * additional_kwargs: {\n * reasoning: { summary: [{ text: \"Let me calculate this...\" }] },\n * tool_outputs: [\n * {\n * type: \"code_interpreter_call\",\n * code: \"print('hello')\",\n * outputs: [{ type: \"logs\", logs: \"hello\" }]\n * }\n * ]\n * }\n * });\n *\n * const standardBlocks = convertToV1FromResponses(message);\n * // Returns:\n * // [\n * // { type: \"reasoning\", reasoning: \"Let me calculate this...\" },\n * // { type: \"text\", text: \"Hello world\", annotations: [] },\n * // { type: \"tool_call\", id: \"123\", name: \"calculator\", args: { a: 1, b: 2 } },\n * // { type: \"server_tool_call\", name: \"code_interpreter\", args: { code: \"print('hello')\" } },\n * // { type: \"server_tool_call_result\", toolCallId: \"\", status: \"success\", output: { type: \"code_interpreter_output\", returnCode: 0, stdout: \"hello\" } }\n * // ]\n * ```\n */\nexport function convertToV1FromResponses(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n const rawOutput = message.response_metadata?.output;\n const hasRawOutput = _isArray(rawOutput) && rawOutput.length > 0;\n\n // Maps a per-item key (namespaced by type, since ids aren't globally unique) to its original response.output position.\n const positionByKey = new Map<string, number>();\n let messageItemCount = 0;\n let onlyMessageItemIndex: number | undefined;\n if (hasRawOutput) {\n (rawOutput as unknown[]).forEach((rawItem, index) => {\n if (!_isObject(rawItem) || !_isString(rawItem.type)) return;\n if (rawItem.type === \"reasoning\" && _isString(rawItem.id)) {\n positionByKey.set(`reasoning:${rawItem.id}`, index);\n } else if (\n // These three types all become tool_call blocks keyed by call_id.\n (rawItem.type === \"function_call\" ||\n rawItem.type === \"custom_tool_call\" ||\n rawItem.type === \"computer_call\") &&\n _isString(rawItem.call_id)\n ) {\n positionByKey.set(`tool_call:${rawItem.call_id}`, index);\n } else if (rawItem.type === \"message\") {\n messageItemCount += 1;\n onlyMessageItemIndex = index;\n } else if (_isString(rawItem.id)) {\n positionByKey.set(`other:${rawItem.type}:${rawItem.id}`, index);\n }\n });\n }\n // Text isn't keyed to a specific \"message\" item, so only position it when exactly one exists (an unambiguous match).\n const textBlockKey =\n messageItemCount === 1 && onlyMessageItemIndex != null\n ? `message:${onlyMessageItemIndex}`\n : undefined;\n if (textBlockKey != null) {\n positionByKey.set(textBlockKey, onlyMessageItemIndex as number);\n }\n\n function* iterateContent(): Iterable<\n [block: ContentBlock.Standard, key: string | undefined]\n > {\n if (hasRawOutput) {\n for (const rawItem of rawOutput as unknown[]) {\n if (_isObject(rawItem) && rawItem.type === \"reasoning\") {\n const block = mapReasoningItemToV1(rawItem);\n if (block) {\n yield [\n block,\n _isString(rawItem.id) ? `reasoning:${rawItem.id}` : undefined,\n ];\n }\n }\n }\n } else if (\n _isObject(message.additional_kwargs?.reasoning) &&\n _isArray(message.additional_kwargs.reasoning.summary)\n ) {\n const block = mapReasoningItemToV1(message.additional_kwargs.reasoning);\n if (block) yield [block, undefined];\n }\n\n const content =\n typeof message.content === \"string\"\n ? [{ type: \"text\", text: message.content }]\n : message.content;\n for (const block of content) {\n if (_isContentBlock(block, \"text\")) {\n const {\n text,\n annotations,\n phase,\n extras: existingExtras,\n ...rest\n } = block;\n const extras: Record<string, unknown> = _isObject(existingExtras)\n ? { ...(existingExtras as Record<string, unknown>) }\n : {};\n if (_isString(phase)) {\n extras.phase = phase;\n }\n const extrasSpread = Object.keys(extras).length > 0 ? { extras } : {};\n yield [\n {\n ...rest,\n ...extrasSpread,\n type: \"text\",\n text: String(text),\n ...(Array.isArray(annotations)\n ? { annotations: annotations.map(convertResponsesAnnotation) }\n : {}),\n },\n textBlockKey,\n ];\n }\n }\n for (const toolCall of message.tool_calls ?? []) {\n yield [\n {\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n },\n toolCall.id ? `tool_call:${toolCall.id}` : undefined,\n ];\n }\n if (\n _isObject(message.additional_kwargs) &&\n _isArray(message.additional_kwargs.tool_outputs)\n ) {\n for (const toolOutput of message.additional_kwargs.tool_outputs) {\n // All blocks from one tool output share this key -- fine since the API returns a call and its result as one item.\n const key =\n _isObject(toolOutput) &&\n _isString(toolOutput.type) &&\n _isString(toolOutput.id)\n ? `other:${toolOutput.type}:${toolOutput.id}`\n : undefined;\n for (const block of mapToolOutputToV1Blocks(toolOutput)) {\n yield [block, key];\n }\n }\n }\n }\n\n const withKeys = Array.from(iterateContent());\n if (!hasRawOutput) {\n return withKeys.map(([block]) => block);\n }\n // Stable sort by original position; unkeyed blocks sort last, in push order.\n return withKeys\n .map(([block, key], pushIndex) => ({\n block,\n pushIndex,\n position: key != null ? positionByKey.get(key) : undefined,\n }))\n .sort((a, b) => {\n const aPos = a.position ?? Number.POSITIVE_INFINITY;\n const bPos = b.position ?? Number.POSITIVE_INFINITY;\n if (aPos !== bPos) return aPos - bPos;\n return a.pushIndex - b.pushIndex;\n })\n .map((entry) => entry.block);\n}\n\n/**\n * Converts a ChatOpenAIResponses message chunk to an array of v1 standard content blocks.\n *\n * This function processes an AI message chunk containing OpenAI-specific content blocks\n * and converts them to the standardized v1 content block format. It handles both the\n * regular message content and tool call chunks that are specific to streaming responses.\n *\n * @param message - The AI message chunk containing OpenAI-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const messageChunk = new AIMessageChunk({\n * content: [{ type: \"text\", text: \"Hello\" }],\n * tool_call_chunks: [\n * { id: \"call_123\", name: \"calculator\", args: '{\"a\": 1' }\n * ]\n * });\n *\n * const standardBlocks = convertToV1FromResponsesChunk(messageChunk);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello\" },\n * // { type: \"tool_call_chunk\", id: \"call_123\", name: \"calculator\", args: '{\"a\": 1' }\n * // ]\n * ```\n */\nexport function convertToV1FromResponsesChunk(\n message: AIMessageChunk\n): Array<ContentBlock.Standard> {\n function* iterateContent(): Iterable<ContentBlock.Standard> {\n yield* convertToV1FromResponses(message);\n for (const toolCallChunk of message.tool_call_chunks ?? []) {\n yield {\n type: \"tool_call_chunk\",\n id: toolCallChunk.id,\n name: toolCallChunk.name,\n args: toolCallChunk.args,\n };\n }\n }\n return Array.from(iterateContent());\n}\n\nexport const ChatOpenAITranslator: StandardContentBlockTranslator = {\n translateContent: (message) => {\n if (typeof message.content === \"string\") {\n return convertToV1FromChatCompletions(message);\n }\n return convertToV1FromResponses(message);\n },\n translateContentChunk: (message) => {\n if (typeof message.content === \"string\") {\n return convertToV1FromChatCompletionsChunk(message);\n }\n return convertToV1FromResponsesChunk(message);\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,+BACd,SAC8B;CAC9B,MAAM,SAAuC,CAAC;CAC9C,IAAI,OAAO,QAAQ,YAAY,UAEzB;MAAA,QAAQ,QAAQ,SAAS,GAC3B,OAAO,KAAK;GACV,MAAM;GACN,MAAM,QAAQ;EAChB,CAAC;CAAA,OAGH,OAAO,KAAK,GAAG,oCAAoC,QAAQ,OAAO,CAAC;CAErE,KAAK,MAAM,YAAY,QAAQ,cAAc,CAAC,GAC5C,OAAO,KAAK;EACV,MAAM;EACN,IAAI,SAAS;EACb,MAAM,SAAS;EACf,MAAM,SAAS;CACjB,CAAC;CAEH,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAgB,oCACd,SAC8B;CAC9B,MAAM,SAAuC,CAAC;CAC9C,IAAI,OAAO,QAAQ,YAAY,UAEzB;MAAA,QAAQ,QAAQ,SAAS,GAC3B,OAAO,KAAK;GACV,MAAM;GACN,MAAM,QAAQ;EAChB,CAAC;CAAA,OAGH,OAAO,KAAK,GAAG,oCAAoC,QAAQ,OAAO,CAAC;CAIrE,KAAK,MAAM,YAAY,QAAQ,cAAc,CAAC,GAC5C,OAAO,KAAK;EACV,MAAM;EACN,IAAI,SAAS;EACb,MAAM,SAAS;EACf,MAAM,SAAS;CACjB,CAAC;CAEH,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,oCACd,QAC8B;CAC9B,MAAM,kBAAgD,CAAC;CACvD,KAAK,MAAM,SAAS,QAClB,IAAI,kBAAkB,KAAK,GACzB,gBAAgB,KAAK,+BAA+B,KAAK,CAAC;MAE1D,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a,uBAAuD;CAClE,mBAAmB,YAAY;EAC7B,IAAI,OAAO,QAAQ,YAAY,UAC7B,OAAO,+BAA+B,OAAO;EAE/C,OAAO,yBAAyB,OAAO;CACzC;CACA,wBAAwB,YAAY;EAClC,IAAI,OAAO,QAAQ,YAAY,UAC7B,OAAO,oCAAoC,OAAO;EAEpD,OAAO,8BAA8B,OAAO;CAC9C;AACF"}
|
|
1
|
+
{"version":3,"file":"openai.js","names":[],"sources":["../../../src/messages/block_translators/openai.ts"],"sourcesContent":["import type { ContentBlock } from \"../content/index.js\";\nimport type { AIMessageChunk, AIMessage } from \"../ai.js\";\nimport type { StandardContentBlockTranslator } from \"./index.js\";\nimport { convertToV1FromOpenAIDataBlock, isOpenAIDataBlock } from \"./data.js\";\nimport {\n _isArray,\n _isContentBlock,\n _isObject,\n _isString,\n iife,\n} from \"./utils.js\";\n\n/** The refusal Chat Completions and Responses keep in `additional_kwargs`. */\nfunction refusalFromAdditionalKwargs(\n message: AIMessage\n): ContentBlock.Refusal | undefined {\n const refusal = message.additional_kwargs.refusal;\n return _isString(refusal) && refusal.length > 0\n ? { type: \"refusal\", refusal }\n : undefined;\n}\n\n/**\n * Converts a ChatOpenAICompletions message to an array of v1 standard content blocks.\n *\n * This function processes an AI message from ChatOpenAICompletions API format\n * and converts it to the standardized v1 content block format. It handles both\n * string content and structured content blocks, as well as tool calls.\n *\n * @param message - The AI message containing ChatOpenAICompletions formatted content\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const message = new AIMessage(\"Hello world\");\n * const standardBlocks = convertToV1FromChatCompletions(message);\n * // Returns: [{ type: \"text\", text: \"Hello world\" }]\n * ```\n *\n * @example\n * ```typescript\n * const message = new AIMessage([\n * { type: \"text\", text: \"Hello\" },\n * { type: \"image_url\", image_url: { url: \"https://example.com/image.png\" } }\n * ]);\n * message.tool_calls = [\n * { id: \"call_123\", name: \"calculator\", args: { a: 1, b: 2 } }\n * ];\n *\n * const standardBlocks = convertToV1FromChatCompletions(message);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello\" },\n * // { type: \"image\", url: \"https://example.com/image.png\" },\n * // { type: \"tool_call\", id: \"call_123\", name: \"calculator\", args: { a: 1, b: 2 } }\n * // ]\n * ```\n */\nexport function convertToV1FromChatCompletions(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock.Standard> = [];\n if (typeof message.content === \"string\") {\n // Only add text block if content is non-empty\n if (message.content.length > 0) {\n blocks.push({\n type: \"text\",\n text: message.content,\n });\n }\n } else {\n blocks.push(...convertToV1FromChatCompletionsInput(message.content));\n }\n for (const toolCall of message.tool_calls ?? []) {\n blocks.push({\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n });\n }\n const refusal = refusalFromAdditionalKwargs(message);\n if (refusal) blocks.push(refusal);\n return blocks;\n}\n\n/**\n * Converts a ChatOpenAICompletions message chunk to an array of v1 standard content blocks.\n *\n * This function processes an AI message chunk from OpenAI's chat completions API and converts\n * it to the standardized v1 content block format. It handles both string and array content,\n * as well as tool calls that may be present in the chunk.\n *\n * @param message - The AI message chunk containing OpenAI-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const chunk = new AIMessage(\"Hello\");\n * const standardBlocks = convertToV1FromChatCompletionsChunk(chunk);\n * // Returns: [{ type: \"text\", text: \"Hello\" }]\n * ```\n *\n * @example\n * ```typescript\n * const chunk = new AIMessage([\n * { type: \"text\", text: \"Processing...\" }\n * ]);\n * chunk.tool_calls = [\n * { id: \"call_456\", name: \"search\", args: { query: \"test\" } }\n * ];\n *\n * const standardBlocks = convertToV1FromChatCompletionsChunk(chunk);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Processing...\" },\n * // { type: \"tool_call\", id: \"call_456\", name: \"search\", args: { query: \"test\" } }\n * // ]\n * ```\n */\nexport function convertToV1FromChatCompletionsChunk(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n const blocks: Array<ContentBlock.Standard> = [];\n if (typeof message.content === \"string\") {\n // Only add text block if content is non-empty\n if (message.content.length > 0) {\n blocks.push({\n type: \"text\",\n text: message.content,\n });\n }\n } else {\n blocks.push(...convertToV1FromChatCompletionsInput(message.content));\n }\n\n // TODO: parse chunk position information\n for (const toolCall of message.tool_calls ?? []) {\n blocks.push({\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n });\n }\n const refusal = refusalFromAdditionalKwargs(message);\n if (refusal) blocks.push(refusal);\n return blocks;\n}\n\n/**\n * Converts an array of ChatOpenAICompletions content blocks to v1 standard content blocks.\n *\n * This function processes content blocks from OpenAI's Chat Completions API format\n * and converts them to the standardized v1 content block format. It handles both\n * OpenAI-specific data blocks (which require conversion) and standard blocks\n * (which are passed through with type assertion).\n *\n * @param blocks - Array of content blocks in ChatOpenAICompletions format\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const openaiBlocks = [\n * { type: \"text\", text: \"Hello world\" },\n * { type: \"image_url\", image_url: { url: \"https://example.com/image.png\" } }\n * ];\n *\n * const standardBlocks = convertToV1FromChatCompletionsInput(openaiBlocks);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello world\" },\n * // { type: \"image\", url: \"https://example.com/image.png\" }\n * // ]\n * ```\n */\nexport function convertToV1FromChatCompletionsInput(\n blocks: Array<ContentBlock>\n): Array<ContentBlock.Standard> {\n const convertedBlocks: Array<ContentBlock.Standard> = [];\n for (const block of blocks) {\n if (isOpenAIDataBlock(block)) {\n convertedBlocks.push(convertToV1FromOpenAIDataBlock(block));\n } else {\n convertedBlocks.push(block as ContentBlock.Standard);\n }\n }\n return convertedBlocks;\n}\n\nfunction convertResponsesAnnotation(\n annotation: ContentBlock\n): ContentBlock | ContentBlock.Citation {\n if (annotation.type === \"url_citation\") {\n const { url, title, start_index, end_index } = annotation;\n return {\n type: \"citation\",\n url,\n title,\n startIndex: start_index,\n endIndex: end_index,\n };\n }\n if (annotation.type === \"file_citation\") {\n const { file_id, filename, index } = annotation;\n return {\n type: \"citation\",\n title: filename,\n startIndex: index,\n endIndex: index,\n fileId: file_id,\n };\n }\n return annotation;\n}\n\n/** Builds a reasoning content block, including id/encrypted_content when present. */\nfunction mapReasoningItemToV1(\n item: Record<string, unknown>\n): ContentBlock.Standard | undefined {\n if (!_isArray(item.summary)) return undefined;\n const summary = item.summary.reduce<string>((acc, part) => {\n if (_isObject(part) && _isString(part.text)) {\n return `${acc}${part.text}`;\n }\n return acc;\n }, \"\");\n return {\n type: \"reasoning\",\n reasoning: summary,\n ...(_isString(item.id) ? { id: item.id } : {}),\n ...(_isString(item.encrypted_content)\n ? { encrypted_content: item.encrypted_content }\n : {}),\n } as ContentBlock.Standard;\n}\n\n// Converts a single built-in tool call/result entry into v1 content blocks.\nfunction* mapToolOutputToV1Blocks(\n toolOutput: unknown\n): Iterable<ContentBlock.Standard> {\n if (_isContentBlock(toolOutput, \"web_search_call\")) {\n const webSearchArgs: Record<string, unknown> = {};\n if (_isObject(toolOutput.action) && _isString(toolOutput.action.query)) {\n webSearchArgs.query = toolOutput.action.query;\n }\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"web_search\",\n args: webSearchArgs,\n };\n // Emit a server_tool_call_result when the search has completed or failed\n if (toolOutput.status === \"completed\" || toolOutput.status === \"failed\") {\n const output: Record<string, unknown> = {};\n if (_isObject(toolOutput.action)) {\n output.action = toolOutput.action;\n }\n yield {\n type: \"server_tool_call_result\",\n toolCallId: _isString(toolOutput.id) ? toolOutput.id : \"\",\n status: toolOutput.status === \"completed\" ? \"success\" : \"error\",\n output,\n };\n }\n return;\n }\n if (_isContentBlock(toolOutput, \"file_search_call\")) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"file_search\",\n args: {\n queries: _isArray(toolOutput.queries) ? toolOutput.queries : [],\n },\n };\n // Emit a server_tool_call_result when results are available\n if (toolOutput.status === \"completed\" || toolOutput.status === \"failed\") {\n yield {\n type: \"server_tool_call_result\",\n toolCallId: _isString(toolOutput.id) ? toolOutput.id : \"\",\n status: toolOutput.status === \"completed\" ? \"success\" : \"error\",\n output: _isArray(toolOutput.results)\n ? { results: toolOutput.results }\n : {},\n };\n }\n return;\n }\n if (_isContentBlock(toolOutput, \"computer_call\")) {\n yield { type: \"non_standard\", value: toolOutput };\n return;\n }\n if (_isContentBlock(toolOutput, \"code_interpreter_call\")) {\n if (_isString(toolOutput.code)) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"code_interpreter\",\n args: { code: toolOutput.code },\n };\n }\n if (_isArray(toolOutput.outputs)) {\n const returnCode = iife(() => {\n if (toolOutput.status === \"in_progress\") return undefined;\n if (toolOutput.status === \"completed\") return 0;\n if (toolOutput.status === \"incomplete\") return 127;\n if (toolOutput.status === \"interpreting\") return undefined;\n if (toolOutput.status === \"failed\") return 1;\n return undefined;\n });\n for (const output of toolOutput.outputs) {\n if (_isContentBlock(output, \"logs\")) {\n yield {\n type: \"server_tool_call_result\",\n toolCallId: toolOutput.id ?? \"\",\n status: \"success\",\n output: {\n type: \"code_interpreter_output\",\n returnCode: returnCode ?? 0,\n stderr: [0, undefined].includes(returnCode)\n ? undefined\n : String(output.logs),\n stdout: [0, undefined].includes(returnCode)\n ? String(output.logs)\n : undefined,\n },\n };\n }\n }\n }\n return;\n }\n if (_isContentBlock(toolOutput, \"mcp_call\")) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"mcp_call\",\n args: toolOutput.input,\n };\n return;\n }\n if (_isContentBlock(toolOutput, \"mcp_list_tools\")) {\n yield {\n id: toolOutput.id,\n type: \"server_tool_call\",\n name: \"mcp_list_tools\",\n args: toolOutput.input,\n };\n return;\n }\n if (_isContentBlock(toolOutput, \"mcp_approval_request\")) {\n yield { type: \"non_standard\", value: toolOutput };\n return;\n }\n if (_isContentBlock(toolOutput, \"tool_search_call\")) {\n const toolSearchArgs: Record<string, unknown> = {};\n if (_isObject(toolOutput.arguments)) {\n Object.assign(toolSearchArgs, toolOutput.arguments);\n }\n const toolSearchCallExtras: Record<string, unknown> = {};\n if (_isString(toolOutput.execution)) {\n toolSearchCallExtras.execution = toolOutput.execution;\n }\n if (_isString(toolOutput.status)) {\n toolSearchCallExtras.status = toolOutput.status;\n }\n if (_isString(toolOutput.call_id)) {\n toolSearchCallExtras.call_id = toolOutput.call_id;\n }\n yield {\n id: _isString(toolOutput.id) ? toolOutput.id : \"\",\n type: \"server_tool_call\",\n name: \"tool_search\",\n args: toolSearchArgs,\n ...(Object.keys(toolSearchCallExtras).length > 0\n ? { extras: toolSearchCallExtras }\n : {}),\n };\n return;\n }\n if (_isContentBlock(toolOutput, \"tool_search_output\")) {\n const toolSearchOutputExtras: Record<string, unknown> = {\n name: \"tool_search\",\n };\n if (_isString(toolOutput.execution)) {\n toolSearchOutputExtras.execution = toolOutput.execution;\n }\n yield {\n type: \"server_tool_call_result\",\n toolCallId: _isString(toolOutput.id) ? toolOutput.id : \"\",\n status:\n toolOutput.status === \"completed\"\n ? \"success\"\n : toolOutput.status === \"failed\"\n ? \"error\"\n : \"success\",\n output: {\n tools: _isArray(toolOutput.tools) ? toolOutput.tools : [],\n },\n extras: toolSearchOutputExtras,\n };\n return;\n }\n if (_isContentBlock(toolOutput, \"image_generation_call\")) {\n // Convert image_generation_call to proper image content block if result is available\n if (_isString(toolOutput.result)) {\n yield {\n type: \"image\",\n mimeType: \"image/png\",\n data: toolOutput.result,\n id: _isString(toolOutput.id) ? toolOutput.id : undefined,\n metadata: {\n status: _isString(toolOutput.status) ? toolOutput.status : undefined,\n },\n };\n }\n // Also yield as non_standard for backwards compatibility\n yield { type: \"non_standard\", value: toolOutput };\n return;\n }\n if (_isObject(toolOutput)) {\n yield { type: \"non_standard\", value: toolOutput };\n }\n}\n\n/**\n * Converts a ChatOpenAIResponses message to an array of v1 standard content blocks.\n *\n * This function processes an AI message containing OpenAI Responses-specific content blocks\n * and converts them to the standardized v1 content block format. It handles reasoning summaries,\n * text content with annotations, tool calls, and various tool outputs including code interpreter,\n * web search, file search, computer calls, and MCP-related blocks.\n *\n * A response can hold more than one reasoning item (e.g. multiple tool calls\n * in one turn, common on GPT-5.6-class models). When `response_metadata.output`\n * is available, each item's own `id`/`encrypted_content` is preserved and\n * blocks are sorted back into original order, so replay under Zero Data\n * Retention interleaves reasoning and tool calls correctly. Without it (e.g.\n * a hand-built message), falls back to a single reasoning block from\n * `additional_kwargs.reasoning`, as before.\n *\n * @param message - The AI message containing OpenAI Responses-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const message = new AIMessage({\n * content: [{ type: \"text\", text: \"Hello world\", annotations: [] }],\n * tool_calls: [{ id: \"123\", name: \"calculator\", args: { a: 1, b: 2 } }],\n * additional_kwargs: {\n * reasoning: { summary: [{ text: \"Let me calculate this...\" }] },\n * tool_outputs: [\n * {\n * type: \"code_interpreter_call\",\n * code: \"print('hello')\",\n * outputs: [{ type: \"logs\", logs: \"hello\" }]\n * }\n * ]\n * }\n * });\n *\n * const standardBlocks = convertToV1FromResponses(message);\n * // Returns:\n * // [\n * // { type: \"reasoning\", reasoning: \"Let me calculate this...\" },\n * // { type: \"text\", text: \"Hello world\", annotations: [] },\n * // { type: \"tool_call\", id: \"123\", name: \"calculator\", args: { a: 1, b: 2 } },\n * // { type: \"server_tool_call\", name: \"code_interpreter\", args: { code: \"print('hello')\" } },\n * // { type: \"server_tool_call_result\", toolCallId: \"\", status: \"success\", output: { type: \"code_interpreter_output\", returnCode: 0, stdout: \"hello\" } }\n * // ]\n * ```\n */\nexport function convertToV1FromResponses(\n message: AIMessage\n): Array<ContentBlock.Standard> {\n const rawOutput = message.response_metadata?.output;\n const hasRawOutput = _isArray(rawOutput) && rawOutput.length > 0;\n\n // Maps a per-item key (namespaced by type, since ids aren't globally unique) to its original response.output position.\n const positionByKey = new Map<string, number>();\n let messageItemCount = 0;\n let onlyMessageItemIndex: number | undefined;\n if (hasRawOutput) {\n (rawOutput as unknown[]).forEach((rawItem, index) => {\n if (!_isObject(rawItem) || !_isString(rawItem.type)) return;\n if (rawItem.type === \"reasoning\" && _isString(rawItem.id)) {\n positionByKey.set(`reasoning:${rawItem.id}`, index);\n } else if (\n // These three types all become tool_call blocks keyed by call_id.\n (rawItem.type === \"function_call\" ||\n rawItem.type === \"custom_tool_call\" ||\n rawItem.type === \"computer_call\") &&\n _isString(rawItem.call_id)\n ) {\n positionByKey.set(`tool_call:${rawItem.call_id}`, index);\n } else if (rawItem.type === \"message\") {\n messageItemCount += 1;\n onlyMessageItemIndex = index;\n } else if (_isString(rawItem.id)) {\n positionByKey.set(`other:${rawItem.type}:${rawItem.id}`, index);\n }\n });\n }\n // Text isn't keyed to a specific \"message\" item, so only position it when exactly one exists (an unambiguous match).\n const textBlockKey =\n messageItemCount === 1 && onlyMessageItemIndex != null\n ? `message:${onlyMessageItemIndex}`\n : undefined;\n if (textBlockKey != null) {\n positionByKey.set(textBlockKey, onlyMessageItemIndex as number);\n }\n\n function* iterateContent(): Iterable<\n [block: ContentBlock.Standard, key: string | undefined]\n > {\n if (hasRawOutput) {\n for (const rawItem of rawOutput as unknown[]) {\n if (_isObject(rawItem) && rawItem.type === \"reasoning\") {\n const block = mapReasoningItemToV1(rawItem);\n if (block) {\n yield [\n block,\n _isString(rawItem.id) ? `reasoning:${rawItem.id}` : undefined,\n ];\n }\n }\n }\n } else if (\n _isObject(message.additional_kwargs?.reasoning) &&\n _isArray(message.additional_kwargs.reasoning.summary)\n ) {\n const block = mapReasoningItemToV1(message.additional_kwargs.reasoning);\n if (block) yield [block, undefined];\n }\n\n const content =\n typeof message.content === \"string\"\n ? [{ type: \"text\", text: message.content }]\n : message.content;\n for (const block of content) {\n if (_isContentBlock(block, \"text\")) {\n const {\n text,\n annotations,\n phase,\n extras: existingExtras,\n ...rest\n } = block;\n const extras: Record<string, unknown> = _isObject(existingExtras)\n ? { ...(existingExtras as Record<string, unknown>) }\n : {};\n if (_isString(phase)) {\n extras.phase = phase;\n }\n const extrasSpread = Object.keys(extras).length > 0 ? { extras } : {};\n yield [\n {\n ...rest,\n ...extrasSpread,\n type: \"text\",\n text: String(text),\n ...(Array.isArray(annotations)\n ? { annotations: annotations.map(convertResponsesAnnotation) }\n : {}),\n },\n textBlockKey,\n ];\n }\n }\n let hasRefusalPart = false;\n for (const block of content) {\n if (_isContentBlock(block, \"refusal\") && _isString(block.refusal)) {\n hasRefusalPart = true;\n yield [\n {\n type: \"refusal\",\n refusal: block.refusal,\n ...(_isString(block.id) ? { id: block.id } : {}),\n },\n textBlockKey,\n ];\n }\n }\n if (!hasRefusalPart) {\n const refusal = refusalFromAdditionalKwargs(message);\n if (refusal) yield [refusal, textBlockKey];\n }\n for (const toolCall of message.tool_calls ?? []) {\n yield [\n {\n type: \"tool_call\",\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n },\n toolCall.id ? `tool_call:${toolCall.id}` : undefined,\n ];\n }\n if (\n _isObject(message.additional_kwargs) &&\n _isArray(message.additional_kwargs.tool_outputs)\n ) {\n for (const toolOutput of message.additional_kwargs.tool_outputs) {\n // All blocks from one tool output share this key -- fine since the API returns a call and its result as one item.\n const key =\n _isObject(toolOutput) &&\n _isString(toolOutput.type) &&\n _isString(toolOutput.id)\n ? `other:${toolOutput.type}:${toolOutput.id}`\n : undefined;\n for (const block of mapToolOutputToV1Blocks(toolOutput)) {\n yield [block, key];\n }\n }\n }\n }\n\n const withKeys = Array.from(iterateContent());\n if (!hasRawOutput) {\n return withKeys.map(([block]) => block);\n }\n // Stable sort by original position; unkeyed blocks sort last, in push order.\n return withKeys\n .map(([block, key], pushIndex) => ({\n block,\n pushIndex,\n position: key != null ? positionByKey.get(key) : undefined,\n }))\n .sort((a, b) => {\n const aPos = a.position ?? Number.POSITIVE_INFINITY;\n const bPos = b.position ?? Number.POSITIVE_INFINITY;\n if (aPos !== bPos) return aPos - bPos;\n return a.pushIndex - b.pushIndex;\n })\n .map((entry) => entry.block);\n}\n\n/**\n * Converts a ChatOpenAIResponses message chunk to an array of v1 standard content blocks.\n *\n * This function processes an AI message chunk containing OpenAI-specific content blocks\n * and converts them to the standardized v1 content block format. It handles both the\n * regular message content and tool call chunks that are specific to streaming responses.\n *\n * @param message - The AI message chunk containing OpenAI-formatted content blocks\n * @returns Array of content blocks in v1 standard format\n *\n * @example\n * ```typescript\n * const messageChunk = new AIMessageChunk({\n * content: [{ type: \"text\", text: \"Hello\" }],\n * tool_call_chunks: [\n * { id: \"call_123\", name: \"calculator\", args: '{\"a\": 1' }\n * ]\n * });\n *\n * const standardBlocks = convertToV1FromResponsesChunk(messageChunk);\n * // Returns:\n * // [\n * // { type: \"text\", text: \"Hello\" },\n * // { type: \"tool_call_chunk\", id: \"call_123\", name: \"calculator\", args: '{\"a\": 1' }\n * // ]\n * ```\n */\nexport function convertToV1FromResponsesChunk(\n message: AIMessageChunk\n): Array<ContentBlock.Standard> {\n function* iterateContent(): Iterable<ContentBlock.Standard> {\n yield* convertToV1FromResponses(message);\n for (const toolCallChunk of message.tool_call_chunks ?? []) {\n yield {\n type: \"tool_call_chunk\",\n id: toolCallChunk.id,\n name: toolCallChunk.name,\n args: toolCallChunk.args,\n };\n }\n }\n return Array.from(iterateContent());\n}\n\nexport const ChatOpenAITranslator: StandardContentBlockTranslator = {\n translateContent: (message) => {\n if (typeof message.content === \"string\") {\n return convertToV1FromChatCompletions(message);\n }\n return convertToV1FromResponses(message);\n },\n translateContentChunk: (message) => {\n if (typeof message.content === \"string\") {\n return convertToV1FromChatCompletionsChunk(message);\n }\n return convertToV1FromResponsesChunk(message);\n },\n};\n"],"mappings":";;;;AAaA,SAAS,4BACP,SACkC;CAClC,MAAM,UAAU,QAAQ,kBAAkB;CAC1C,OAAO,UAAU,OAAO,KAAK,QAAQ,SAAS,IAC1C;EAAE,MAAM;EAAW;CAAQ,IAC3B,KAAA;AACN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,+BACd,SAC8B;CAC9B,MAA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8B;CAC9B,UAAU,iBAAkD;EAC1D,OAAO,yBAAyB,OAAO;EACvC,KAAK,MAAM,iBAAiB,QAAQ,oBAAoB,CAAC,GACvD,MAAM;GACJ,MAAM;GACN,IAAI,cAAc;GAClB,MAAM,cAAc;GACpB,MAAM,cAAc;EACtB;CAEJ;CACA,OAAO,MAAM,KAAK,eAAe,CAAC;AACpC;AAEA,MAAa,uBAAuD;CAClE,mBAAmB,YAAY;EAC7B,IAAI,OAAO,QAAQ,YAAY,UAC7B,OAAO,+BAA+B,OAAO;EAE/C,OAAO,yBAAyB,OAAO;CACzC;CACA,wBAAwB,YAAY;EAClC,IAAI,OAAO,QAAQ,YAAY,UAC7B,OAAO,oCAAoC,OAAO;EAEpD,OAAO,8BAA8B,OAAO;CAC9C;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["KNOWN_TOOL_BLOCK_TYPES","KNOWN_MULTIMODAL_BLOCK_TYPES"],"sources":["../../../src/messages/content/index.ts"],"sourcesContent":["import type { BaseContentBlock } from \"./base.js\";\nimport {\n KNOWN_BLOCK_TYPES as KNOWN_TOOL_BLOCK_TYPES,\n type Tools,\n} from \"./tools.js\";\nimport {\n KNOWN_BLOCK_TYPES as KNOWN_MULTIMODAL_BLOCK_TYPES,\n type Multimodal,\n} from \"./multimodal.js\";\nimport { type Data } from \"./data.js\";\nimport { type DeepPartial } from \"../../types/type-utils.js\";\n\nexport interface ContentBlock extends BaseContentBlock {}\n\nexport type PartialContentBlock<T extends ContentBlock = ContentBlock> = {\n readonly type: T[\"type\"];\n} & DeepPartial<Exclude<T, \"type\">>;\n\nexport const KNOWN_BLOCK_TYPES = [\n \"text\",\n \"reasoning\",\n ...KNOWN_TOOL_BLOCK_TYPES,\n ...KNOWN_MULTIMODAL_BLOCK_TYPES,\n];\n\n// oxlint-disable-next-line @typescript-eslint/no-namespace\nexport declare namespace ContentBlock {\n /**\n * Annotation for citing data from a document.\n */\n export interface Citation {\n /**\n * Type of the content block\n */\n readonly type: \"citation\";\n /**\n * Source type for the citation.\n */\n source?: string;\n /**\n * URL of the document source\n */\n url?: string;\n /**\n * Source document title.\n *\n * For example, the page title for a web page or the title of a paper.\n */\n title?: string;\n /**\n * Start index of the **response text** for which the annotation applies.\n *\n * @see {Text}\n */\n startIndex?: number;\n /**\n * End index of the **response text** for which the annotation applies.\n *\n * @see {Text}\n */\n endIndex?: number;\n /**\n * Excerpt of source text being cited.\n */\n citedText?: string;\n }\n\n /**\n * Text output from a LLM.\n *\n * This typically represents the main text content of a message, such as the response\n * from a language model or the text of a user message.\n */\n export interface Text extends ContentBlock {\n /**\n * Type of the content block\n */\n readonly type: \"text\";\n /**\n * Block text.\n */\n text: string;\n /**\n * Index of block in aggregate response. Used during streaming.\n */\n index?: string | number;\n /**\n * Citations and other annotations.\n */\n annotations?: Array<Citation | BaseContentBlock>;\n }\n\n /**\n * Reasoning output from a LLM.\n */\n export interface Reasoning extends ContentBlock {\n /**\n * Type of the content block\n */\n readonly type: \"reasoning\";\n /**\n * Reasoning text.\n *\n * Either the thought summary or the raw reasoning text itself.\n * This is often parsed from `<think>` tags in the model's response.\n */\n reasoning: string;\n /**\n * Index of block in aggregate response. Used during streaming.\n */\n index?: string | number;\n }\n\n /**\n * Provider-specific content block.\n *\n * This is used to represent content blocks that are not part of the standard LangChain content model.\n * If a provider's non-standard output includes reasoning and tool calls, it should be\n * the adapter's job to parse that payload and emit the corresponding standard reasoning and tool call blocks.\n */\n export interface NonStandard<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n TValue extends Record<string, any> = Record<string, any>,\n > extends ContentBlock {\n /**\n * Type of the content block\n */\n type: \"non_standard\";\n /**\n * Provider-specific data\n */\n value: TValue;\n }\n\n export { Tools };\n export { Multimodal };\n export { Data };\n\n export type Standard =\n | Text\n | Reasoning\n | NonStandard\n | Tools.Standard\n | Multimodal.Standard;\n}\n"],"mappings":";;;AAkBA,MAAa,oBAAoB;CAC/B;CACA;CACA,GAAGA,cAAAA;CACH,GAAGC,mBAAAA;AACL"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["KNOWN_TOOL_BLOCK_TYPES","KNOWN_MULTIMODAL_BLOCK_TYPES"],"sources":["../../../src/messages/content/index.ts"],"sourcesContent":["import type { BaseContentBlock } from \"./base.js\";\nimport {\n KNOWN_BLOCK_TYPES as KNOWN_TOOL_BLOCK_TYPES,\n type Tools,\n} from \"./tools.js\";\nimport {\n KNOWN_BLOCK_TYPES as KNOWN_MULTIMODAL_BLOCK_TYPES,\n type Multimodal,\n} from \"./multimodal.js\";\nimport { type Data } from \"./data.js\";\nimport { type DeepPartial } from \"../../types/type-utils.js\";\n\nexport interface ContentBlock extends BaseContentBlock {}\n\nexport type PartialContentBlock<T extends ContentBlock = ContentBlock> = {\n readonly type: T[\"type\"];\n} & DeepPartial<Exclude<T, \"type\">>;\n\nexport const KNOWN_BLOCK_TYPES = [\n \"text\",\n \"reasoning\",\n \"refusal\",\n ...KNOWN_TOOL_BLOCK_TYPES,\n ...KNOWN_MULTIMODAL_BLOCK_TYPES,\n];\n\n// oxlint-disable-next-line @typescript-eslint/no-namespace\nexport declare namespace ContentBlock {\n /**\n * Annotation for citing data from a document.\n */\n export interface Citation {\n /**\n * Type of the content block\n */\n readonly type: \"citation\";\n /**\n * Source type for the citation.\n */\n source?: string;\n /**\n * URL of the document source\n */\n url?: string;\n /**\n * Source document title.\n *\n * For example, the page title for a web page or the title of a paper.\n */\n title?: string;\n /**\n * Start index of the **response text** for which the annotation applies.\n *\n * @see {Text}\n */\n startIndex?: number;\n /**\n * End index of the **response text** for which the annotation applies.\n *\n * @see {Text}\n */\n endIndex?: number;\n /**\n * Excerpt of source text being cited.\n */\n citedText?: string;\n }\n\n /**\n * Text output from a LLM.\n *\n * This typically represents the main text content of a message, such as the response\n * from a language model or the text of a user message.\n */\n export interface Text extends ContentBlock {\n /**\n * Type of the content block\n */\n readonly type: \"text\";\n /**\n * Block text.\n */\n text: string;\n /**\n * Index of block in aggregate response. Used during streaming.\n */\n index?: string | number;\n /**\n * Citations and other annotations.\n */\n annotations?: Array<Citation | BaseContentBlock>;\n }\n\n /**\n * Reasoning output from a LLM.\n */\n export interface Reasoning extends ContentBlock {\n /**\n * Type of the content block\n */\n readonly type: \"reasoning\";\n /**\n * Reasoning text.\n *\n * Either the thought summary or the raw reasoning text itself.\n * This is often parsed from `<think>` tags in the model's response.\n */\n reasoning: string;\n /**\n * Index of block in aggregate response. Used during streaming.\n */\n index?: string | number;\n }\n\n /**\n * An explicit refusal reported by the model provider.\n *\n * Providers report refusals, such as safety-policy refusals, as successful\n * responses. This block marks them so callers can tell a refusal apart from\n * an empty or unparsable answer. Refusals the model writes as ordinary text\n * are not detected.\n */\n export interface Refusal extends ContentBlock {\n /**\n * Type of the content block\n */\n readonly type: \"refusal\";\n /**\n * The refusal message, or an empty string if the provider sent none.\n */\n refusal: string;\n /**\n * Additional provider-specific data, such as Anthropic's refusal `category`.\n */\n extras?: Record<string, unknown>;\n }\n\n /**\n * Provider-specific content block.\n *\n * This is used to represent content blocks that are not part of the standard LangChain content model.\n * If a provider's non-standard output includes reasoning and tool calls, it should be\n * the adapter's job to parse that payload and emit the corresponding standard reasoning and tool call blocks.\n */\n export interface NonStandard<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n TValue extends Record<string, any> = Record<string, any>,\n > extends ContentBlock {\n /**\n * Type of the content block\n */\n type: \"non_standard\";\n /**\n * Provider-specific data\n */\n value: TValue;\n }\n\n export { Tools };\n export { Multimodal };\n export { Data };\n\n export type Standard =\n | Text\n | Reasoning\n | Refusal\n | NonStandard\n | Tools.Standard\n | Multimodal.Standard;\n}\n"],"mappings":";;;AAkBA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA,GAAGA,cAAAA;CACH,GAAGC,mBAAAA;AACL"}
|
|
@@ -92,6 +92,28 @@ export declare namespace ContentBlock {
|
|
|
92
92
|
*/
|
|
93
93
|
index?: string | number;
|
|
94
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* An explicit refusal reported by the model provider.
|
|
97
|
+
*
|
|
98
|
+
* Providers report refusals, such as safety-policy refusals, as successful
|
|
99
|
+
* responses. This block marks them so callers can tell a refusal apart from
|
|
100
|
+
* an empty or unparsable answer. Refusals the model writes as ordinary text
|
|
101
|
+
* are not detected.
|
|
102
|
+
*/
|
|
103
|
+
export interface Refusal extends ContentBlock {
|
|
104
|
+
/**
|
|
105
|
+
* Type of the content block
|
|
106
|
+
*/
|
|
107
|
+
readonly type: "refusal";
|
|
108
|
+
/**
|
|
109
|
+
* The refusal message, or an empty string if the provider sent none.
|
|
110
|
+
*/
|
|
111
|
+
refusal: string;
|
|
112
|
+
/**
|
|
113
|
+
* Additional provider-specific data, such as Anthropic's refusal `category`.
|
|
114
|
+
*/
|
|
115
|
+
extras?: Record<string, unknown>;
|
|
116
|
+
}
|
|
95
117
|
/**
|
|
96
118
|
* Provider-specific content block.
|
|
97
119
|
*
|
|
@@ -112,6 +134,6 @@ export declare namespace ContentBlock {
|
|
|
112
134
|
export { Tools };
|
|
113
135
|
export { Multimodal };
|
|
114
136
|
export { Data };
|
|
115
|
-
export type Standard = Text | Reasoning | NonStandard | Tools.Standard | Multimodal.Standard;
|
|
137
|
+
export type Standard = Text | Reasoning | Refusal | NonStandard | Tools.Standard | Multimodal.Standard;
|
|
116
138
|
}
|
|
117
139
|
//# sourceMappingURL=index.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../../src/messages/content/index.ts"],"mappings":";;;;;iBAYiB,qBAAqB;YAE1B,oBAAoB,UAAU,eAAe;WAC9C,MAAM;IACb,YAAY,QAAQ;qBAEX;
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../../../src/messages/content/index.ts"],"mappings":";;;;;iBAYiB,qBAAqB;YAE1B,oBAAoB,UAAU,eAAe;WAC9C,MAAM;IACb,YAAY,QAAQ;qBAEX;yBASY;;;;mBAIN;;;;aAIN;;;;IAIT;;;;IAIA;;;;;;IAMA;;;;;;IAMA;;;;;;IAMA;;;;IAIA;;;;;;;;mBASe,aAAa;;;;aAInB;;;;IAIT;;;;IAIA;;;;IAIA,cAAc,MAAM,WAAW;;;;;mBAMhB,kBAAkB;;;;aAIxB;;;;;;;IAOT;;;;IAIA;;;;;;;;;;mBAWe,gBAAgB;;;;aAItB;;;;IAIT;;;;IAIA,SAAS;;;;;;;;;mBAUM,YAEf,eAAe,sBAAsB,6BAC7B;;;;IAIR;;;;IAIA,OAAO;;WAGA;WACA;WACA;cAEG,WACR,OACA,YACA,UACA,cACA,MAAM,WACN,WAAW"}
|
|
@@ -92,6 +92,28 @@ export declare namespace ContentBlock {
|
|
|
92
92
|
*/
|
|
93
93
|
index?: string | number;
|
|
94
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* An explicit refusal reported by the model provider.
|
|
97
|
+
*
|
|
98
|
+
* Providers report refusals, such as safety-policy refusals, as successful
|
|
99
|
+
* responses. This block marks them so callers can tell a refusal apart from
|
|
100
|
+
* an empty or unparsable answer. Refusals the model writes as ordinary text
|
|
101
|
+
* are not detected.
|
|
102
|
+
*/
|
|
103
|
+
export interface Refusal extends ContentBlock {
|
|
104
|
+
/**
|
|
105
|
+
* Type of the content block
|
|
106
|
+
*/
|
|
107
|
+
readonly type: "refusal";
|
|
108
|
+
/**
|
|
109
|
+
* The refusal message, or an empty string if the provider sent none.
|
|
110
|
+
*/
|
|
111
|
+
refusal: string;
|
|
112
|
+
/**
|
|
113
|
+
* Additional provider-specific data, such as Anthropic's refusal `category`.
|
|
114
|
+
*/
|
|
115
|
+
extras?: Record<string, unknown>;
|
|
116
|
+
}
|
|
95
117
|
/**
|
|
96
118
|
* Provider-specific content block.
|
|
97
119
|
*
|
|
@@ -112,6 +134,6 @@ export declare namespace ContentBlock {
|
|
|
112
134
|
export { Tools };
|
|
113
135
|
export { Multimodal };
|
|
114
136
|
export { Data };
|
|
115
|
-
export type Standard = Text | Reasoning | NonStandard | Tools.Standard | Multimodal.Standard;
|
|
137
|
+
export type Standard = Text | Reasoning | Refusal | NonStandard | Tools.Standard | Multimodal.Standard;
|
|
116
138
|
}
|
|
117
139
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/messages/content/index.ts"],"mappings":";;;;;iBAYiB,qBAAqB;YAE1B,oBAAoB,UAAU,eAAe;WAC9C,MAAM;IACb,YAAY,QAAQ;qBAEX;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../../src/messages/content/index.ts"],"mappings":";;;;;iBAYiB,qBAAqB;YAE1B,oBAAoB,UAAU,eAAe;WAC9C,MAAM;IACb,YAAY,QAAQ;qBAEX;yBASY;;;;mBAIN;;;;aAIN;;;;IAIT;;;;IAIA;;;;;;IAMA;;;;;;IAMA;;;;;;IAMA;;;;IAIA;;;;;;;;mBASe,aAAa;;;;aAInB;;;;IAIT;;;;IAIA;;;;IAIA,cAAc,MAAM,WAAW;;;;;mBAMhB,kBAAkB;;;;aAIxB;;;;;;;IAOT;;;;IAIA;;;;;;;;;;mBAWe,gBAAgB;;;;aAItB;;;;IAIT;;;;IAIA,SAAS;;;;;;;;;mBAUM,YAEf,eAAe,sBAAsB,6BAC7B;;;;IAIR;;;;IAIA,OAAO;;WAGA;WACA;WACA;cAEG,WACR,OACA,YACA,UACA,cACA,MAAM,WACN,WAAW"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["KNOWN_TOOL_BLOCK_TYPES","KNOWN_MULTIMODAL_BLOCK_TYPES"],"sources":["../../../src/messages/content/index.ts"],"sourcesContent":["import type { BaseContentBlock } from \"./base.js\";\nimport {\n KNOWN_BLOCK_TYPES as KNOWN_TOOL_BLOCK_TYPES,\n type Tools,\n} from \"./tools.js\";\nimport {\n KNOWN_BLOCK_TYPES as KNOWN_MULTIMODAL_BLOCK_TYPES,\n type Multimodal,\n} from \"./multimodal.js\";\nimport { type Data } from \"./data.js\";\nimport { type DeepPartial } from \"../../types/type-utils.js\";\n\nexport interface ContentBlock extends BaseContentBlock {}\n\nexport type PartialContentBlock<T extends ContentBlock = ContentBlock> = {\n readonly type: T[\"type\"];\n} & DeepPartial<Exclude<T, \"type\">>;\n\nexport const KNOWN_BLOCK_TYPES = [\n \"text\",\n \"reasoning\",\n ...KNOWN_TOOL_BLOCK_TYPES,\n ...KNOWN_MULTIMODAL_BLOCK_TYPES,\n];\n\n// oxlint-disable-next-line @typescript-eslint/no-namespace\nexport declare namespace ContentBlock {\n /**\n * Annotation for citing data from a document.\n */\n export interface Citation {\n /**\n * Type of the content block\n */\n readonly type: \"citation\";\n /**\n * Source type for the citation.\n */\n source?: string;\n /**\n * URL of the document source\n */\n url?: string;\n /**\n * Source document title.\n *\n * For example, the page title for a web page or the title of a paper.\n */\n title?: string;\n /**\n * Start index of the **response text** for which the annotation applies.\n *\n * @see {Text}\n */\n startIndex?: number;\n /**\n * End index of the **response text** for which the annotation applies.\n *\n * @see {Text}\n */\n endIndex?: number;\n /**\n * Excerpt of source text being cited.\n */\n citedText?: string;\n }\n\n /**\n * Text output from a LLM.\n *\n * This typically represents the main text content of a message, such as the response\n * from a language model or the text of a user message.\n */\n export interface Text extends ContentBlock {\n /**\n * Type of the content block\n */\n readonly type: \"text\";\n /**\n * Block text.\n */\n text: string;\n /**\n * Index of block in aggregate response. Used during streaming.\n */\n index?: string | number;\n /**\n * Citations and other annotations.\n */\n annotations?: Array<Citation | BaseContentBlock>;\n }\n\n /**\n * Reasoning output from a LLM.\n */\n export interface Reasoning extends ContentBlock {\n /**\n * Type of the content block\n */\n readonly type: \"reasoning\";\n /**\n * Reasoning text.\n *\n * Either the thought summary or the raw reasoning text itself.\n * This is often parsed from `<think>` tags in the model's response.\n */\n reasoning: string;\n /**\n * Index of block in aggregate response. Used during streaming.\n */\n index?: string | number;\n }\n\n /**\n * Provider-specific content block.\n *\n * This is used to represent content blocks that are not part of the standard LangChain content model.\n * If a provider's non-standard output includes reasoning and tool calls, it should be\n * the adapter's job to parse that payload and emit the corresponding standard reasoning and tool call blocks.\n */\n export interface NonStandard<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n TValue extends Record<string, any> = Record<string, any>,\n > extends ContentBlock {\n /**\n * Type of the content block\n */\n type: \"non_standard\";\n /**\n * Provider-specific data\n */\n value: TValue;\n }\n\n export { Tools };\n export { Multimodal };\n export { Data };\n\n export type Standard =\n | Text\n | Reasoning\n | NonStandard\n | Tools.Standard\n | Multimodal.Standard;\n}\n"],"mappings":";;;AAkBA,MAAa,oBAAoB;CAC/B;CACA;CACA,GAAGA;CACH,GAAGC;AACL"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["KNOWN_TOOL_BLOCK_TYPES","KNOWN_MULTIMODAL_BLOCK_TYPES"],"sources":["../../../src/messages/content/index.ts"],"sourcesContent":["import type { BaseContentBlock } from \"./base.js\";\nimport {\n KNOWN_BLOCK_TYPES as KNOWN_TOOL_BLOCK_TYPES,\n type Tools,\n} from \"./tools.js\";\nimport {\n KNOWN_BLOCK_TYPES as KNOWN_MULTIMODAL_BLOCK_TYPES,\n type Multimodal,\n} from \"./multimodal.js\";\nimport { type Data } from \"./data.js\";\nimport { type DeepPartial } from \"../../types/type-utils.js\";\n\nexport interface ContentBlock extends BaseContentBlock {}\n\nexport type PartialContentBlock<T extends ContentBlock = ContentBlock> = {\n readonly type: T[\"type\"];\n} & DeepPartial<Exclude<T, \"type\">>;\n\nexport const KNOWN_BLOCK_TYPES = [\n \"text\",\n \"reasoning\",\n \"refusal\",\n ...KNOWN_TOOL_BLOCK_TYPES,\n ...KNOWN_MULTIMODAL_BLOCK_TYPES,\n];\n\n// oxlint-disable-next-line @typescript-eslint/no-namespace\nexport declare namespace ContentBlock {\n /**\n * Annotation for citing data from a document.\n */\n export interface Citation {\n /**\n * Type of the content block\n */\n readonly type: \"citation\";\n /**\n * Source type for the citation.\n */\n source?: string;\n /**\n * URL of the document source\n */\n url?: string;\n /**\n * Source document title.\n *\n * For example, the page title for a web page or the title of a paper.\n */\n title?: string;\n /**\n * Start index of the **response text** for which the annotation applies.\n *\n * @see {Text}\n */\n startIndex?: number;\n /**\n * End index of the **response text** for which the annotation applies.\n *\n * @see {Text}\n */\n endIndex?: number;\n /**\n * Excerpt of source text being cited.\n */\n citedText?: string;\n }\n\n /**\n * Text output from a LLM.\n *\n * This typically represents the main text content of a message, such as the response\n * from a language model or the text of a user message.\n */\n export interface Text extends ContentBlock {\n /**\n * Type of the content block\n */\n readonly type: \"text\";\n /**\n * Block text.\n */\n text: string;\n /**\n * Index of block in aggregate response. Used during streaming.\n */\n index?: string | number;\n /**\n * Citations and other annotations.\n */\n annotations?: Array<Citation | BaseContentBlock>;\n }\n\n /**\n * Reasoning output from a LLM.\n */\n export interface Reasoning extends ContentBlock {\n /**\n * Type of the content block\n */\n readonly type: \"reasoning\";\n /**\n * Reasoning text.\n *\n * Either the thought summary or the raw reasoning text itself.\n * This is often parsed from `<think>` tags in the model's response.\n */\n reasoning: string;\n /**\n * Index of block in aggregate response. Used during streaming.\n */\n index?: string | number;\n }\n\n /**\n * An explicit refusal reported by the model provider.\n *\n * Providers report refusals, such as safety-policy refusals, as successful\n * responses. This block marks them so callers can tell a refusal apart from\n * an empty or unparsable answer. Refusals the model writes as ordinary text\n * are not detected.\n */\n export interface Refusal extends ContentBlock {\n /**\n * Type of the content block\n */\n readonly type: \"refusal\";\n /**\n * The refusal message, or an empty string if the provider sent none.\n */\n refusal: string;\n /**\n * Additional provider-specific data, such as Anthropic's refusal `category`.\n */\n extras?: Record<string, unknown>;\n }\n\n /**\n * Provider-specific content block.\n *\n * This is used to represent content blocks that are not part of the standard LangChain content model.\n * If a provider's non-standard output includes reasoning and tool calls, it should be\n * the adapter's job to parse that payload and emit the corresponding standard reasoning and tool call blocks.\n */\n export interface NonStandard<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n TValue extends Record<string, any> = Record<string, any>,\n > extends ContentBlock {\n /**\n * Type of the content block\n */\n type: \"non_standard\";\n /**\n * Provider-specific data\n */\n value: TValue;\n }\n\n export { Tools };\n export { Multimodal };\n export { Data };\n\n export type Standard =\n | Text\n | Reasoning\n | Refusal\n | NonStandard\n | Tools.Standard\n | Multimodal.Standard;\n}\n"],"mappings":";;;AAkBA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA,GAAGA;CACH,GAAGC;AACL"}
|
|
@@ -2,6 +2,7 @@ const require_transform = require("./transform.cjs");
|
|
|
2
2
|
const require_duplex = require("../utils/fast-json-patch/src/duplex.cjs");
|
|
3
3
|
require("../utils/json_patch.cjs");
|
|
4
4
|
const require_json = require("../utils/json.cjs");
|
|
5
|
+
const require_refusal = require("./refusal.cjs");
|
|
5
6
|
// src/output_parsers/json.ts
|
|
6
7
|
/**
|
|
7
8
|
* Class for parsing the output of an LLM into a JSON object.
|
|
@@ -29,6 +30,13 @@ var JsonOutputParser = class extends require_transform.BaseCumulativeTransformOu
|
|
|
29
30
|
async parsePartialResult(generations) {
|
|
30
31
|
return require_json.parseJsonMarkdown(generations[0].text);
|
|
31
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* @throws {ModelRefusalError} If the model refused instead of answering.
|
|
35
|
+
*/
|
|
36
|
+
async parseResult(generations, callbacks) {
|
|
37
|
+
require_refusal.throwIfRefused(generations[0]);
|
|
38
|
+
return super.parseResult(generations, callbacks);
|
|
39
|
+
}
|
|
32
40
|
async parse(text) {
|
|
33
41
|
return require_json.parseJsonMarkdown(text, JSON.parse);
|
|
34
42
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.cjs","names":["BaseCumulativeTransformOutputParser","compare","parseJsonMarkdown"],"sources":["../../src/output_parsers/json.ts"],"sourcesContent":["import { BaseCumulativeTransformOutputParser } from \"./transform.js\";\nimport { Operation, compare } from \"../utils/json_patch.js\";\nimport { ChatGeneration, Generation } from \"../outputs.js\";\nimport { parseJsonMarkdown, parsePartialJson } from \"../utils/json.js\";\nimport type { BaseMessage } from \"../messages/index.js\";\n\n/**\n * Class for parsing the output of an LLM into a JSON object.\n */\nexport class JsonOutputParser<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> extends BaseCumulativeTransformOutputParser<T> {\n static lc_name() {\n return \"JsonOutputParser\";\n }\n\n lc_namespace = [\"langchain_core\", \"output_parsers\"];\n\n lc_serializable = true;\n\n /** @internal */\n override _concatOutputChunks<T>(first: T, second: T): T {\n if (this.diff) {\n return super._concatOutputChunks(first, second);\n }\n return second;\n }\n\n protected _diff(\n prev: unknown | undefined,\n next: unknown\n ): Operation[] | undefined {\n if (!next) {\n return undefined;\n }\n if (!prev) {\n return [{ op: \"replace\", path: \"\", value: next }];\n }\n return compare(prev, next);\n }\n\n // This should actually return Partial<T>, but there's no way\n // to specify emitted chunks as instances separate from the main output type.\n async parsePartialResult(\n generations: ChatGeneration[] | Generation[]\n ): Promise<T | undefined> {\n return parseJsonMarkdown(generations[0].text) as T | undefined;\n }\n\n async parse(text: string): Promise<T> {\n return parseJsonMarkdown(text, JSON.parse) as T;\n }\n\n getFormatInstructions(): string {\n return \"\";\n }\n\n /**\n * Extracts text content from a message for JSON parsing.\n * Uses the message's `.text` accessor which properly handles both\n * string content and ContentBlock[] arrays (extracting text from text blocks).\n * @param message The message to extract text from\n * @returns The text content of the message\n */\n protected _baseMessageToString(message: BaseMessage): string {\n return message.text;\n }\n}\n\nexport { parsePartialJson, parseJsonMarkdown };\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"json.cjs","names":["BaseCumulativeTransformOutputParser","compare","parseJsonMarkdown"],"sources":["../../src/output_parsers/json.ts"],"sourcesContent":["import { BaseCumulativeTransformOutputParser } from \"./transform.js\";\nimport { Operation, compare } from \"../utils/json_patch.js\";\nimport { ChatGeneration, Generation } from \"../outputs.js\";\nimport { parseJsonMarkdown, parsePartialJson } from \"../utils/json.js\";\nimport type { BaseMessage } from \"../messages/index.js\";\nimport type { Callbacks } from \"../callbacks/manager.js\";\nimport { throwIfRefused } from \"./refusal.js\";\n\n/**\n * Class for parsing the output of an LLM into a JSON object.\n */\nexport class JsonOutputParser<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> extends BaseCumulativeTransformOutputParser<T> {\n static lc_name() {\n return \"JsonOutputParser\";\n }\n\n lc_namespace = [\"langchain_core\", \"output_parsers\"];\n\n lc_serializable = true;\n\n /** @internal */\n override _concatOutputChunks<T>(first: T, second: T): T {\n if (this.diff) {\n return super._concatOutputChunks(first, second);\n }\n return second;\n }\n\n protected _diff(\n prev: unknown | undefined,\n next: unknown\n ): Operation[] | undefined {\n if (!next) {\n return undefined;\n }\n if (!prev) {\n return [{ op: \"replace\", path: \"\", value: next }];\n }\n return compare(prev, next);\n }\n\n // This should actually return Partial<T>, but there's no way\n // to specify emitted chunks as instances separate from the main output type.\n async parsePartialResult(\n generations: ChatGeneration[] | Generation[]\n ): Promise<T | undefined> {\n return parseJsonMarkdown(generations[0].text) as T | undefined;\n }\n\n /**\n * @throws {ModelRefusalError} If the model refused instead of answering.\n */\n override async parseResult(\n generations: Generation[] | ChatGeneration[],\n callbacks?: Callbacks\n ): Promise<T> {\n throwIfRefused(generations[0]);\n return super.parseResult(generations, callbacks);\n }\n\n async parse(text: string): Promise<T> {\n return parseJsonMarkdown(text, JSON.parse) as T;\n }\n\n getFormatInstructions(): string {\n return \"\";\n }\n\n /**\n * Extracts text content from a message for JSON parsing.\n * Uses the message's `.text` accessor which properly handles both\n * string content and ContentBlock[] arrays (extracting text from text blocks).\n * @param message The message to extract text from\n * @returns The text content of the message\n */\n protected _baseMessageToString(message: BaseMessage): string {\n return message.text;\n }\n}\n\nexport { parsePartialJson, parseJsonMarkdown };\n"],"mappings":";;;;;;;;;AAWA,IAAa,mBAAb,cAGUA,kBAAAA,oCAAuC;CAC/C,OAAO,UAAU;EACf,OAAO;CACT;CAEA,eAAe,CAAC,kBAAkB,gBAAgB;CAElD,kBAAkB;;CAGlB,oBAAgC,OAAU,QAAc;EACtD,IAAI,KAAK,MACP,OAAO,MAAM,oBAAoB,OAAO,MAAM;EAEhD,OAAO;CACT;CAEA,MACE,MACA,MACyB;EACzB,IAAI,CAAC,MACH;EAEF,IAAI,CAAC,MACH,OAAO,CAAC;GAAE,IAAI;GAAW,MAAM;GAAI,OAAO;EAAK,CAAC;EAElD,OAAOC,eAAAA,QAAQ,MAAM,IAAI;CAC3B;CAIA,MAAM,mBACJ,aACwB;EACxB,OAAOC,aAAAA,kBAAkB,YAAY,EAAE,CAAC,IAAI;CAC9C;;;;CAKA,MAAe,YACb,aACA,WACY;EACZ,gBAAA,eAAe,YAAY,EAAE;EAC7B,OAAO,MAAM,YAAY,aAAa,SAAS;CACjD;CAEA,MAAM,MAAM,MAA0B;EACpC,OAAOA,aAAAA,kBAAkB,MAAM,KAAK,KAAK;CAC3C;CAEA,wBAAgC;EAC9B,OAAO;CACT;;;;;;;;CASA,qBAA+B,SAA8B;EAC3D,OAAO,QAAQ;CACjB;AACF"}
|
|
@@ -3,6 +3,7 @@ import { BaseCumulativeTransformOutputParser } from "./transform.cjs";
|
|
|
3
3
|
import { Operation } from "../utils/fast-json-patch/src/core.cjs";
|
|
4
4
|
import { ChatGeneration, Generation } from "../outputs.cjs";
|
|
5
5
|
import "../messages/index.cjs";
|
|
6
|
+
import { Callbacks } from "../callbacks/manager.cjs";
|
|
6
7
|
import { parseJsonMarkdown, parsePartialJson } from "../utils/json.cjs";
|
|
7
8
|
/**
|
|
8
9
|
* Class for parsing the output of an LLM into a JSON object.
|
|
@@ -15,6 +16,10 @@ export declare class JsonOutputParser<T extends Record<string, any> = Record<str
|
|
|
15
16
|
_concatOutputChunks<T>(first: T, second: T): T;
|
|
16
17
|
protected _diff(prev: unknown | undefined, next: unknown): Operation[] | undefined;
|
|
17
18
|
parsePartialResult(generations: ChatGeneration[] | Generation[]): Promise<T | undefined>;
|
|
19
|
+
/**
|
|
20
|
+
* @throws {ModelRefusalError} If the model refused instead of answering.
|
|
21
|
+
*/
|
|
22
|
+
parseResult(generations: Generation[] | ChatGeneration[], callbacks?: Callbacks): Promise<T>;
|
|
18
23
|
parse(text: string): Promise<T>;
|
|
19
24
|
getFormatInstructions(): string;
|
|
20
25
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.d.cts","names":[],"sources":["../../src/output_parsers/json.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"json.d.cts","names":[],"sources":["../../src/output_parsers/json.ts"],"mappings":";;;;;;;;;;qBAWa,iBAEX,UAAU,sBAAsB,6BACxB,oCAAoC;SACrC;EAIP;EAEA;;EAGS,oBAAoB,GAAG,OAAO,GAAG,QAAQ,IAAI;YAO5C,MACR,2BACA,gBACC;EAYG,mBACJ,aAAa,mBAAmB,eAC/B,QAAQ;;;;EAOI,YACb,aAAa,eAAe,kBAC5B,YAAY,YACX,QAAQ;EAKL,MAAM,eAAe,QAAQ;EAInC;;;;;;;;YAWU,qBAAqB,SAAS"}
|
|
@@ -3,6 +3,7 @@ import { BaseCumulativeTransformOutputParser } from "./transform.js";
|
|
|
3
3
|
import { Operation } from "../utils/fast-json-patch/src/core.js";
|
|
4
4
|
import { ChatGeneration, Generation } from "../outputs.js";
|
|
5
5
|
import "../messages/index.js";
|
|
6
|
+
import { Callbacks } from "../callbacks/manager.js";
|
|
6
7
|
import { parseJsonMarkdown, parsePartialJson } from "../utils/json.js";
|
|
7
8
|
/**
|
|
8
9
|
* Class for parsing the output of an LLM into a JSON object.
|
|
@@ -15,6 +16,10 @@ export declare class JsonOutputParser<T extends Record<string, any> = Record<str
|
|
|
15
16
|
_concatOutputChunks<T>(first: T, second: T): T;
|
|
16
17
|
protected _diff(prev: unknown | undefined, next: unknown): Operation[] | undefined;
|
|
17
18
|
parsePartialResult(generations: ChatGeneration[] | Generation[]): Promise<T | undefined>;
|
|
19
|
+
/**
|
|
20
|
+
* @throws {ModelRefusalError} If the model refused instead of answering.
|
|
21
|
+
*/
|
|
22
|
+
parseResult(generations: Generation[] | ChatGeneration[], callbacks?: Callbacks): Promise<T>;
|
|
18
23
|
parse(text: string): Promise<T>;
|
|
19
24
|
getFormatInstructions(): string;
|
|
20
25
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.d.ts","names":[],"sources":["../../src/output_parsers/json.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"json.d.ts","names":[],"sources":["../../src/output_parsers/json.ts"],"mappings":";;;;;;;;;;qBAWa,iBAEX,UAAU,sBAAsB,6BACxB,oCAAoC;SACrC;EAIP;EAEA;;EAGS,oBAAoB,GAAG,OAAO,GAAG,QAAQ,IAAI;YAO5C,MACR,2BACA,gBACC;EAYG,mBACJ,aAAa,mBAAmB,eAC/B,QAAQ;;;;EAOI,YACb,aAAa,eAAe,kBAC5B,YAAY,YACX,QAAQ;EAKL,MAAM,eAAe,QAAQ;EAInC;;;;;;;;YAWU,qBAAqB,SAAS"}
|
|
@@ -2,6 +2,7 @@ import { BaseCumulativeTransformOutputParser } from "./transform.js";
|
|
|
2
2
|
import { compare } from "../utils/fast-json-patch/src/duplex.js";
|
|
3
3
|
import "../utils/json_patch.js";
|
|
4
4
|
import { parseJsonMarkdown, parsePartialJson } from "../utils/json.js";
|
|
5
|
+
import { throwIfRefused } from "./refusal.js";
|
|
5
6
|
// src/output_parsers/json.ts
|
|
6
7
|
/**
|
|
7
8
|
* Class for parsing the output of an LLM into a JSON object.
|
|
@@ -29,6 +30,13 @@ var JsonOutputParser = class extends BaseCumulativeTransformOutputParser {
|
|
|
29
30
|
async parsePartialResult(generations) {
|
|
30
31
|
return parseJsonMarkdown(generations[0].text);
|
|
31
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* @throws {ModelRefusalError} If the model refused instead of answering.
|
|
35
|
+
*/
|
|
36
|
+
async parseResult(generations, callbacks) {
|
|
37
|
+
throwIfRefused(generations[0]);
|
|
38
|
+
return super.parseResult(generations, callbacks);
|
|
39
|
+
}
|
|
32
40
|
async parse(text) {
|
|
33
41
|
return parseJsonMarkdown(text, JSON.parse);
|
|
34
42
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json.js","names":[],"sources":["../../src/output_parsers/json.ts"],"sourcesContent":["import { BaseCumulativeTransformOutputParser } from \"./transform.js\";\nimport { Operation, compare } from \"../utils/json_patch.js\";\nimport { ChatGeneration, Generation } from \"../outputs.js\";\nimport { parseJsonMarkdown, parsePartialJson } from \"../utils/json.js\";\nimport type { BaseMessage } from \"../messages/index.js\";\n\n/**\n * Class for parsing the output of an LLM into a JSON object.\n */\nexport class JsonOutputParser<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> extends BaseCumulativeTransformOutputParser<T> {\n static lc_name() {\n return \"JsonOutputParser\";\n }\n\n lc_namespace = [\"langchain_core\", \"output_parsers\"];\n\n lc_serializable = true;\n\n /** @internal */\n override _concatOutputChunks<T>(first: T, second: T): T {\n if (this.diff) {\n return super._concatOutputChunks(first, second);\n }\n return second;\n }\n\n protected _diff(\n prev: unknown | undefined,\n next: unknown\n ): Operation[] | undefined {\n if (!next) {\n return undefined;\n }\n if (!prev) {\n return [{ op: \"replace\", path: \"\", value: next }];\n }\n return compare(prev, next);\n }\n\n // This should actually return Partial<T>, but there's no way\n // to specify emitted chunks as instances separate from the main output type.\n async parsePartialResult(\n generations: ChatGeneration[] | Generation[]\n ): Promise<T | undefined> {\n return parseJsonMarkdown(generations[0].text) as T | undefined;\n }\n\n async parse(text: string): Promise<T> {\n return parseJsonMarkdown(text, JSON.parse) as T;\n }\n\n getFormatInstructions(): string {\n return \"\";\n }\n\n /**\n * Extracts text content from a message for JSON parsing.\n * Uses the message's `.text` accessor which properly handles both\n * string content and ContentBlock[] arrays (extracting text from text blocks).\n * @param message The message to extract text from\n * @returns The text content of the message\n */\n protected _baseMessageToString(message: BaseMessage): string {\n return message.text;\n }\n}\n\nexport { parsePartialJson, parseJsonMarkdown };\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"json.js","names":[],"sources":["../../src/output_parsers/json.ts"],"sourcesContent":["import { BaseCumulativeTransformOutputParser } from \"./transform.js\";\nimport { Operation, compare } from \"../utils/json_patch.js\";\nimport { ChatGeneration, Generation } from \"../outputs.js\";\nimport { parseJsonMarkdown, parsePartialJson } from \"../utils/json.js\";\nimport type { BaseMessage } from \"../messages/index.js\";\nimport type { Callbacks } from \"../callbacks/manager.js\";\nimport { throwIfRefused } from \"./refusal.js\";\n\n/**\n * Class for parsing the output of an LLM into a JSON object.\n */\nexport class JsonOutputParser<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> extends BaseCumulativeTransformOutputParser<T> {\n static lc_name() {\n return \"JsonOutputParser\";\n }\n\n lc_namespace = [\"langchain_core\", \"output_parsers\"];\n\n lc_serializable = true;\n\n /** @internal */\n override _concatOutputChunks<T>(first: T, second: T): T {\n if (this.diff) {\n return super._concatOutputChunks(first, second);\n }\n return second;\n }\n\n protected _diff(\n prev: unknown | undefined,\n next: unknown\n ): Operation[] | undefined {\n if (!next) {\n return undefined;\n }\n if (!prev) {\n return [{ op: \"replace\", path: \"\", value: next }];\n }\n return compare(prev, next);\n }\n\n // This should actually return Partial<T>, but there's no way\n // to specify emitted chunks as instances separate from the main output type.\n async parsePartialResult(\n generations: ChatGeneration[] | Generation[]\n ): Promise<T | undefined> {\n return parseJsonMarkdown(generations[0].text) as T | undefined;\n }\n\n /**\n * @throws {ModelRefusalError} If the model refused instead of answering.\n */\n override async parseResult(\n generations: Generation[] | ChatGeneration[],\n callbacks?: Callbacks\n ): Promise<T> {\n throwIfRefused(generations[0]);\n return super.parseResult(generations, callbacks);\n }\n\n async parse(text: string): Promise<T> {\n return parseJsonMarkdown(text, JSON.parse) as T;\n }\n\n getFormatInstructions(): string {\n return \"\";\n }\n\n /**\n * Extracts text content from a message for JSON parsing.\n * Uses the message's `.text` accessor which properly handles both\n * string content and ContentBlock[] arrays (extracting text from text blocks).\n * @param message The message to extract text from\n * @returns The text content of the message\n */\n protected _baseMessageToString(message: BaseMessage): string {\n return message.text;\n }\n}\n\nexport { parsePartialJson, parseJsonMarkdown };\n"],"mappings":";;;;;;;;;AAWA,IAAa,mBAAb,cAGU,oCAAuC;CAC/C,OAAO,UAAU;EACf,OAAO;CACT;CAEA,eAAe,CAAC,kBAAkB,gBAAgB;CAElD,kBAAkB;;CAGlB,oBAAgC,OAAU,QAAc;EACtD,IAAI,KAAK,MACP,OAAO,MAAM,oBAAoB,OAAO,MAAM;EAEhD,OAAO;CACT;CAEA,MACE,MACA,MACyB;EACzB,IAAI,CAAC,MACH;EAEF,IAAI,CAAC,MACH,OAAO,CAAC;GAAE,IAAI;GAAW,MAAM;GAAI,OAAO;EAAK,CAAC;EAElD,OAAO,QAAQ,MAAM,IAAI;CAC3B;CAIA,MAAM,mBACJ,aACwB;EACxB,OAAO,kBAAkB,YAAY,EAAE,CAAC,IAAI;CAC9C;;;;CAKA,MAAe,YACb,aACA,WACY;EACZ,eAAe,YAAY,EAAE;EAC7B,OAAO,MAAM,YAAY,aAAa,SAAS;CACjD;CAEA,MAAM,MAAM,MAA0B;EACpC,OAAO,kBAAkB,MAAM,KAAK,KAAK;CAC3C;CAEA,wBAAgC;EAC9B,OAAO;CACT;;;;;;;;CASA,qBAA+B,SAA8B;EAC3D,OAAO,QAAQ;CACjB;AACF"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
const require_json = require("../../utils/json.cjs");
|
|
2
2
|
const require_base = require("../base.cjs");
|
|
3
|
+
const require_refusal = require("../refusal.cjs");
|
|
3
4
|
require("../json.cjs");
|
|
4
5
|
const require_transform = require("../transform.cjs");
|
|
5
6
|
const require_ai = require("../../messages/ai.cjs");
|
|
@@ -78,6 +79,7 @@ var JsonOutputToolsParser = class extends require_transform.BaseCumulativeTransf
|
|
|
78
79
|
throw new Error("Not implemented.");
|
|
79
80
|
}
|
|
80
81
|
async parseResult(generations) {
|
|
82
|
+
require_refusal.throwIfRefused(generations[0]);
|
|
81
83
|
return await this.parsePartialResult(generations, false);
|
|
82
84
|
}
|
|
83
85
|
/**
|
|
@@ -164,6 +166,7 @@ var JsonOutputKeyToolsParser = class extends JsonOutputToolsParser {
|
|
|
164
166
|
return returnedValues;
|
|
165
167
|
}
|
|
166
168
|
async parseResult(generations) {
|
|
169
|
+
require_refusal.throwIfRefused(generations[0]);
|
|
167
170
|
const matchingResults = (await super.parsePartialResult(generations, false)).filter((result) => result.type === this.keyName);
|
|
168
171
|
let returnedValues = matchingResults;
|
|
169
172
|
if (!matchingResults.length) return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json_output_tools_parsers.cjs","names":["parsePartialJson","OutputParserException","BaseCumulativeTransformOutputParser","isAIMessage","interopSafeParseAsync"],"sources":["../../../src/output_parsers/openai_tools/json_output_tools_parsers.ts"],"sourcesContent":["import type { ZodV3Like, ZodV4Like } from \"../../utils/types/zod.js\";\nimport { ChatGeneration, ChatGenerationChunk } from \"../../outputs.js\";\nimport { OutputParserException } from \"../base.js\";\nimport { parsePartialJson } from \"../json.js\";\nimport { InvalidToolCall, ToolCall } from \"../../messages/tool.js\";\nimport {\n BaseCumulativeTransformOutputParser,\n BaseCumulativeTransformOutputParserInput,\n} from \"../transform.js\";\nimport { isAIMessage } from \"../../messages/ai.js\";\nimport {\n type InteropZodType,\n interopSafeParseAsync,\n} from \"../../utils/types/zod.js\";\nimport { SerializableSchema } from \"../../utils/standard_schema.js\";\n\nexport type ParsedToolCall = {\n id?: string;\n\n type: string;\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n args: Record<string, any>;\n};\n\nexport type JsonOutputToolsParserParams = {\n /** Whether to return the tool call id. */\n returnId?: boolean;\n} & BaseCumulativeTransformOutputParserInput;\n\nexport function parseToolCall(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n options: { returnId?: boolean; partial: true }\n): ToolCall | undefined;\nexport function parseToolCall(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n options?: { returnId?: boolean; partial?: false }\n): ToolCall;\nexport function parseToolCall(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n options?: { returnId?: boolean; partial?: boolean }\n): ToolCall | undefined;\nexport function parseToolCall(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n options?: { returnId?: boolean; partial?: boolean }\n): ToolCall | undefined {\n if (rawToolCall.function === undefined) {\n return undefined;\n }\n let functionArgs;\n if (options?.partial) {\n try {\n functionArgs = parsePartialJson(rawToolCall.function.arguments ?? \"{}\");\n } catch {\n return undefined;\n }\n } else {\n try {\n functionArgs = JSON.parse(rawToolCall.function.arguments);\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n throw new OutputParserException(\n [\n `Function \"${rawToolCall.function.name}\" arguments:`,\n ``,\n rawToolCall.function.arguments,\n ``,\n `are not valid JSON.`,\n `Error: ${e.message}`,\n ].join(\"\\n\")\n );\n }\n }\n\n const parsedToolCall: ToolCall = {\n name: rawToolCall.function.name,\n args: functionArgs,\n type: \"tool_call\",\n };\n\n if (options?.returnId) {\n parsedToolCall.id = rawToolCall.id;\n }\n\n return parsedToolCall;\n}\n\nexport function convertLangChainToolCallToOpenAI(toolCall: ToolCall) {\n if (toolCall.id === undefined) {\n throw new Error(`All OpenAI tool calls must have an \"id\" field.`);\n }\n return {\n id: toolCall.id,\n type: \"function\",\n function: {\n name: toolCall.name,\n arguments: JSON.stringify(toolCall.args),\n },\n };\n}\n\nexport function makeInvalidToolCall(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n errorMsg?: string\n): InvalidToolCall {\n return {\n name: rawToolCall.function?.name,\n args: rawToolCall.function?.arguments,\n id: rawToolCall.id,\n error: errorMsg,\n type: \"invalid_tool_call\",\n };\n}\n\n/**\n * Class for parsing the output of a tool-calling LLM into a JSON object.\n */\nexport class JsonOutputToolsParser<\n T,\n> extends BaseCumulativeTransformOutputParser<T> {\n static lc_name() {\n return \"JsonOutputToolsParser\";\n }\n\n returnId = false;\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"openai_tools\"];\n\n lc_serializable = true;\n\n constructor(fields?: JsonOutputToolsParserParams) {\n super(fields);\n this.returnId = fields?.returnId ?? this.returnId;\n }\n\n protected _diff() {\n throw new Error(\"Not supported.\");\n }\n\n async parse(): Promise<T> {\n throw new Error(\"Not implemented.\");\n }\n\n async parseResult(generations: ChatGeneration[]): Promise<T> {\n const result = await this.parsePartialResult(generations, false);\n return result;\n }\n\n /**\n * Parses the output and returns a JSON object. If `argsOnly` is true,\n * only the arguments of the function call are returned.\n * @param generations The output of the LLM to parse.\n * @returns A JSON object representation of the function call or its arguments.\n */\n async parsePartialResult(\n generations: ChatGenerationChunk[] | ChatGeneration[],\n partial = true\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any> {\n const message = generations[0].message;\n let toolCalls;\n if (isAIMessage(message) && message.tool_calls?.length) {\n toolCalls = message.tool_calls.map((toolCall) => {\n const { id, ...rest } = toolCall;\n if (!this.returnId) {\n return rest;\n }\n return {\n id,\n ...rest,\n };\n });\n } else if (message.additional_kwargs.tool_calls !== undefined) {\n const rawToolCalls = JSON.parse(\n JSON.stringify(message.additional_kwargs.tool_calls)\n );\n toolCalls = rawToolCalls.map((rawToolCall: Record<string, unknown>) => {\n return parseToolCall(rawToolCall, { returnId: this.returnId, partial });\n });\n }\n if (!toolCalls) {\n return [];\n }\n const parsedToolCalls = [];\n for (const toolCall of toolCalls) {\n if (toolCall !== undefined) {\n const backwardsCompatibleToolCall: ParsedToolCall = {\n type: toolCall.name,\n args: toolCall.args,\n id: toolCall.id,\n };\n parsedToolCalls.push(backwardsCompatibleToolCall);\n }\n }\n return parsedToolCalls;\n }\n}\n\ntype JsonOutputKeyToolsParserParamsBase = {\n keyName: string;\n returnSingle?: boolean;\n} & JsonOutputToolsParserParams;\n\ntype JsonOutputKeyToolsParserParamsV3<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> = { zodSchema?: ZodV3Like<T> } & JsonOutputKeyToolsParserParamsBase;\n\ntype JsonOutputKeyToolsParserParamsV4<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> = { zodSchema?: ZodV4Like<T, T> } & JsonOutputKeyToolsParserParamsBase;\n\nexport type JsonOutputKeyToolsParserParamsInterop<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> = { zodSchema?: InteropZodType<T> } & JsonOutputKeyToolsParserParamsBase;\n\nexport type JsonOutputKeyToolsParserParamsSerializable<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> = {\n serializableSchema?: SerializableSchema<T>;\n} & JsonOutputKeyToolsParserParamsBase;\n\n// Use Zod 3 for backwards compatibility\nexport type JsonOutputKeyToolsParserParams<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> = JsonOutputKeyToolsParserParamsV3<T>;\n\n/**\n * Class for parsing the output of a tool-calling LLM into a JSON object if you are\n * expecting only a single tool to be called.\n */\nexport class JsonOutputKeyToolsParser<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> extends JsonOutputToolsParser<T> {\n static lc_name() {\n return \"JsonOutputKeyToolsParser\";\n }\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"openai_tools\"];\n\n lc_serializable = true;\n\n returnId = false;\n\n /** The type of tool calls to return. */\n keyName: string;\n\n /** Whether to return only the first tool call. */\n returnSingle = false;\n\n zodSchema?: InteropZodType<T>;\n\n serializableSchema?: SerializableSchema<T>;\n\n constructor(params: JsonOutputKeyToolsParserParamsV3<T>);\n\n constructor(params: JsonOutputKeyToolsParserParamsV4<T>);\n\n constructor(params: JsonOutputKeyToolsParserParamsInterop<T>);\n\n constructor(\n params:\n | JsonOutputKeyToolsParserParamsV3<T>\n | JsonOutputKeyToolsParserParamsV4<T>\n | JsonOutputKeyToolsParserParamsInterop<T>\n | JsonOutputKeyToolsParserParamsSerializable<T>\n ) {\n super(params);\n this.keyName = params.keyName;\n this.returnSingle = params.returnSingle ?? this.returnSingle;\n if (\"zodSchema\" in params) {\n this.zodSchema = params.zodSchema;\n }\n if (\"serializableSchema\" in params) {\n this.serializableSchema = params.serializableSchema;\n }\n }\n\n protected async _validateResult(result: unknown): Promise<T> {\n if (this.serializableSchema !== undefined) {\n const validated =\n await this.serializableSchema[\"~standard\"].validate(result);\n if (validated.issues) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${JSON.stringify(\n result,\n null,\n 2\n )}\". Error: ${JSON.stringify(validated.issues)}`,\n JSON.stringify(result, null, 2)\n );\n }\n return validated.value as T;\n }\n if (this.zodSchema === undefined) {\n return result as T;\n }\n const zodParsedResult = await interopSafeParseAsync(this.zodSchema, result);\n if (zodParsedResult.success) {\n return zodParsedResult.data;\n } else {\n throw new OutputParserException(\n `Failed to parse. Text: \"${JSON.stringify(\n result,\n null,\n 2\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n )}\". Error: ${JSON.stringify((zodParsedResult.error as any)?.issues)}`,\n JSON.stringify(result, null, 2)\n );\n }\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n async parsePartialResult(generations: ChatGeneration[]): Promise<any> {\n const results = await super.parsePartialResult(generations);\n const matchingResults = results.filter(\n (result: ParsedToolCall) => result.type === this.keyName\n );\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n let returnedValues: ParsedToolCall[] | Record<string, any>[] =\n matchingResults;\n if (!matchingResults.length) {\n return undefined;\n }\n if (!this.returnId) {\n returnedValues = matchingResults.map(\n (result: ParsedToolCall) => result.args\n );\n }\n if (this.returnSingle) {\n return returnedValues[0];\n }\n return returnedValues;\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n async parseResult(generations: ChatGeneration[]): Promise<any> {\n const results = await super.parsePartialResult(generations, false);\n const matchingResults = results.filter(\n (result: ParsedToolCall) => result.type === this.keyName\n );\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n let returnedValues: ParsedToolCall[] | Record<string, any>[] =\n matchingResults;\n if (!matchingResults.length) {\n return undefined;\n }\n if (!this.returnId) {\n returnedValues = matchingResults.map(\n (result: ParsedToolCall) => result.args\n );\n }\n if (this.returnSingle) {\n return this._validateResult(returnedValues[0]);\n }\n const toolCallResults = await Promise.all(\n returnedValues.map((value) => this._validateResult(value))\n );\n return toolCallResults;\n }\n}\n"],"mappings":";;;;;;;AA6CA,SAAgB,cAEd,aACA,SACsB;CACtB,IAAI,YAAY,aAAa,KAAA,GAC3B;CAEF,IAAI;CACJ,IAAI,SAAS,SACX,IAAI;EACF,eAAeA,aAAAA,iBAAiB,YAAY,SAAS,aAAa,IAAI;CACxE,QAAQ;EACN;CACF;MAEA,IAAI;EACF,eAAe,KAAK,MAAM,YAAY,SAAS,SAAS;CAE1D,SAAS,GAAQ;EACf,MAAM,IAAIC,aAAAA,sBACR;GACE,aAAa,YAAY,SAAS,KAAK;GACvC;GACA,YAAY,SAAS;GACrB;GACA;GACA,UAAU,EAAE;EACd,CAAC,CAAC,KAAK,IAAI,CACb;CACF;CAGF,MAAM,iBAA2B;EAC/B,MAAM,YAAY,SAAS;EAC3B,MAAM;EACN,MAAM;CACR;CAEA,IAAI,SAAS,UACX,eAAe,KAAK,YAAY;CAGlC,OAAO;AACT;AAEA,SAAgB,iCAAiC,UAAoB;CACnE,IAAI,SAAS,OAAO,KAAA,GAClB,MAAM,IAAI,MAAM,gDAAgD;CAElE,OAAO;EACL,IAAI,SAAS;EACb,MAAM;EACN,UAAU;GACR,MAAM,S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OAAO,SAAS,KAAK,OACnD;EAEA,IAAI,iBACF;EACF,IAAI,CAAC,gBAAgB,QACnB;EAEF,IAAI,CAAC,KAAK,UACR,iBAAiB,gBAAgB,KAC9B,WAA2B,OAAO,IACrC;EAEF,IAAI,KAAK,cACP,OAAO,eAAe;EAExB,OAAO;CACT;CAGA,MAAM,YAAY,aAA6C;EAE7D,MAAM,mBAAkB,MADF,MAAM,mBAAmB,aAAa,KAAK,EAAA,CACjC,QAC7B,WAA2B,OAAO,SAAS,KAAK,OACnD;EAEA,IAAI,iBACF;EACF,IAAI,CAAC,gBAAgB,QACnB;EAEF,IAAI,CAAC,KAAK,UACR,iBAAiB,gBAAgB,KAC9B,WAA2B,OAAO,IACrC;EAEF,IAAI,KAAK,cACP,OAAO,KAAK,gBAAgB,eAAe,EAAE;EAK/C,OAAO,MAHuB,QAAQ,IACpC,eAAe,KAAK,UAAU,KAAK,gBAAgB,KAAK,CAAC,CAC3D;CAEF;AACF"}
|
|
1
|
+
{"version":3,"file":"json_output_tools_parsers.cjs","names":["parsePartialJson","OutputParserException","BaseCumulativeTransformOutputParser","isAIMessage","interopSafeParseAsync"],"sources":["../../../src/output_parsers/openai_tools/json_output_tools_parsers.ts"],"sourcesContent":["import type { ZodV3Like, ZodV4Like } from \"../../utils/types/zod.js\";\nimport { ChatGeneration, ChatGenerationChunk } from \"../../outputs.js\";\nimport { OutputParserException } from \"../base.js\";\nimport { throwIfRefused } from \"../refusal.js\";\nimport { parsePartialJson } from \"../json.js\";\nimport { InvalidToolCall, ToolCall } from \"../../messages/tool.js\";\nimport {\n BaseCumulativeTransformOutputParser,\n BaseCumulativeTransformOutputParserInput,\n} from \"../transform.js\";\nimport { isAIMessage } from \"../../messages/ai.js\";\nimport {\n type InteropZodType,\n interopSafeParseAsync,\n} from \"../../utils/types/zod.js\";\nimport { SerializableSchema } from \"../../utils/standard_schema.js\";\n\nexport type ParsedToolCall = {\n id?: string;\n\n type: string;\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n args: Record<string, any>;\n};\n\nexport type JsonOutputToolsParserParams = {\n /** Whether to return the tool call id. */\n returnId?: boolean;\n} & BaseCumulativeTransformOutputParserInput;\n\nexport function parseToolCall(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n options: { returnId?: boolean; partial: true }\n): ToolCall | undefined;\nexport function parseToolCall(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n options?: { returnId?: boolean; partial?: false }\n): ToolCall;\nexport function parseToolCall(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n options?: { returnId?: boolean; partial?: boolean }\n): ToolCall | undefined;\nexport function parseToolCall(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n options?: { returnId?: boolean; partial?: boolean }\n): ToolCall | undefined {\n if (rawToolCall.function === undefined) {\n return undefined;\n }\n let functionArgs;\n if (options?.partial) {\n try {\n functionArgs = parsePartialJson(rawToolCall.function.arguments ?? \"{}\");\n } catch {\n return undefined;\n }\n } else {\n try {\n functionArgs = JSON.parse(rawToolCall.function.arguments);\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n throw new OutputParserException(\n [\n `Function \"${rawToolCall.function.name}\" arguments:`,\n ``,\n rawToolCall.function.arguments,\n ``,\n `are not valid JSON.`,\n `Error: ${e.message}`,\n ].join(\"\\n\")\n );\n }\n }\n\n const parsedToolCall: ToolCall = {\n name: rawToolCall.function.name,\n args: functionArgs,\n type: \"tool_call\",\n };\n\n if (options?.returnId) {\n parsedToolCall.id = rawToolCall.id;\n }\n\n return parsedToolCall;\n}\n\nexport function convertLangChainToolCallToOpenAI(toolCall: ToolCall) {\n if (toolCall.id === undefined) {\n throw new Error(`All OpenAI tool calls must have an \"id\" field.`);\n }\n return {\n id: toolCall.id,\n type: \"function\",\n function: {\n name: toolCall.name,\n arguments: JSON.stringify(toolCall.args),\n },\n };\n}\n\nexport function makeInvalidToolCall(\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n rawToolCall: Record<string, any>,\n errorMsg?: string\n): InvalidToolCall {\n return {\n name: rawToolCall.function?.name,\n args: rawToolCall.function?.arguments,\n id: rawToolCall.id,\n error: errorMsg,\n type: \"invalid_tool_call\",\n };\n}\n\n/**\n * Class for parsing the output of a tool-calling LLM into a JSON object.\n */\nexport class JsonOutputToolsParser<\n T,\n> extends BaseCumulativeTransformOutputParser<T> {\n static lc_name() {\n return \"JsonOutputToolsParser\";\n }\n\n returnId = false;\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"openai_tools\"];\n\n lc_serializable = true;\n\n constructor(fields?: JsonOutputToolsParserParams) {\n super(fields);\n this.returnId = fields?.returnId ?? this.returnId;\n }\n\n protected _diff() {\n throw new Error(\"Not supported.\");\n }\n\n async parse(): Promise<T> {\n throw new Error(\"Not implemented.\");\n }\n\n async parseResult(generations: ChatGeneration[]): Promise<T> {\n throwIfRefused(generations[0]);\n const result = await this.parsePartialResult(generations, false);\n return result;\n }\n\n /**\n * Parses the output and returns a JSON object. If `argsOnly` is true,\n * only the arguments of the function call are returned.\n * @param generations The output of the LLM to parse.\n * @returns A JSON object representation of the function call or its arguments.\n */\n async parsePartialResult(\n generations: ChatGenerationChunk[] | ChatGeneration[],\n partial = true\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n ): Promise<any> {\n const message = generations[0].message;\n let toolCalls;\n if (isAIMessage(message) && message.tool_calls?.length) {\n toolCalls = message.tool_calls.map((toolCall) => {\n const { id, ...rest } = toolCall;\n if (!this.returnId) {\n return rest;\n }\n return {\n id,\n ...rest,\n };\n });\n } else if (message.additional_kwargs.tool_calls !== undefined) {\n const rawToolCalls = JSON.parse(\n JSON.stringify(message.additional_kwargs.tool_calls)\n );\n toolCalls = rawToolCalls.map((rawToolCall: Record<string, unknown>) => {\n return parseToolCall(rawToolCall, { returnId: this.returnId, partial });\n });\n }\n if (!toolCalls) {\n return [];\n }\n const parsedToolCalls = [];\n for (const toolCall of toolCalls) {\n if (toolCall !== undefined) {\n const backwardsCompatibleToolCall: ParsedToolCall = {\n type: toolCall.name,\n args: toolCall.args,\n id: toolCall.id,\n };\n parsedToolCalls.push(backwardsCompatibleToolCall);\n }\n }\n return parsedToolCalls;\n }\n}\n\ntype JsonOutputKeyToolsParserParamsBase = {\n keyName: string;\n returnSingle?: boolean;\n} & JsonOutputToolsParserParams;\n\ntype JsonOutputKeyToolsParserParamsV3<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> = { zodSchema?: ZodV3Like<T> } & JsonOutputKeyToolsParserParamsBase;\n\ntype JsonOutputKeyToolsParserParamsV4<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> = { zodSchema?: ZodV4Like<T, T> } & JsonOutputKeyToolsParserParamsBase;\n\nexport type JsonOutputKeyToolsParserParamsInterop<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> = { zodSchema?: InteropZodType<T> } & JsonOutputKeyToolsParserParamsBase;\n\nexport type JsonOutputKeyToolsParserParamsSerializable<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> = {\n serializableSchema?: SerializableSchema<T>;\n} & JsonOutputKeyToolsParserParamsBase;\n\n// Use Zod 3 for backwards compatibility\nexport type JsonOutputKeyToolsParserParams<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> = JsonOutputKeyToolsParserParamsV3<T>;\n\n/**\n * Class for parsing the output of a tool-calling LLM into a JSON object if you are\n * expecting only a single tool to be called.\n */\nexport class JsonOutputKeyToolsParser<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> extends JsonOutputToolsParser<T> {\n static lc_name() {\n return \"JsonOutputKeyToolsParser\";\n }\n\n lc_namespace = [\"langchain\", \"output_parsers\", \"openai_tools\"];\n\n lc_serializable = true;\n\n returnId = false;\n\n /** The type of tool calls to return. */\n keyName: string;\n\n /** Whether to return only the first tool call. */\n returnSingle = false;\n\n zodSchema?: InteropZodType<T>;\n\n serializableSchema?: SerializableSchema<T>;\n\n constructor(params: JsonOutputKeyToolsParserParamsV3<T>);\n\n constructor(params: JsonOutputKeyToolsParserParamsV4<T>);\n\n constructor(params: JsonOutputKeyToolsParserParamsInterop<T>);\n\n constructor(\n params:\n | JsonOutputKeyToolsParserParamsV3<T>\n | JsonOutputKeyToolsParserParamsV4<T>\n | JsonOutputKeyToolsParserParamsInterop<T>\n | JsonOutputKeyToolsParserParamsSerializable<T>\n ) {\n super(params);\n this.keyName = params.keyName;\n this.returnSingle = params.returnSingle ?? this.returnSingle;\n if (\"zodSchema\" in params) {\n this.zodSchema = params.zodSchema;\n }\n if (\"serializableSchema\" in params) {\n this.serializableSchema = params.serializableSchema;\n }\n }\n\n protected async _validateResult(result: unknown): Promise<T> {\n if (this.serializableSchema !== undefined) {\n const validated =\n await this.serializableSchema[\"~standard\"].validate(result);\n if (validated.issues) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${JSON.stringify(\n result,\n null,\n 2\n )}\". Error: ${JSON.stringify(validated.issues)}`,\n JSON.stringify(result, null, 2)\n );\n }\n return validated.value as T;\n }\n if (this.zodSchema === undefined) {\n return result as T;\n }\n const zodParsedResult = await interopSafeParseAsync(this.zodSchema, result);\n if (zodParsedResult.success) {\n return zodParsedResult.data;\n } else {\n throw new OutputParserException(\n `Failed to parse. Text: \"${JSON.stringify(\n result,\n null,\n 2\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n )}\". Error: ${JSON.stringify((zodParsedResult.error as any)?.issues)}`,\n JSON.stringify(result, null, 2)\n );\n }\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n async parsePartialResult(generations: ChatGeneration[]): Promise<any> {\n const results = await super.parsePartialResult(generations);\n const matchingResults = results.filter(\n (result: ParsedToolCall) => result.type === this.keyName\n );\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n let returnedValues: ParsedToolCall[] | Record<string, any>[] =\n matchingResults;\n if (!matchingResults.length) {\n return undefined;\n }\n if (!this.returnId) {\n returnedValues = matchingResults.map(\n (result: ParsedToolCall) => result.args\n );\n }\n if (this.returnSingle) {\n return returnedValues[0];\n }\n return returnedValues;\n }\n\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n async parseResult(generations: ChatGeneration[]): Promise<any> {\n throwIfRefused(generations[0]);\n const results = await super.parsePartialResult(generations, false);\n const matchingResults = results.filter(\n (result: ParsedToolCall) => result.type === this.keyName\n );\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n let returnedValues: ParsedToolCall[] | Record<string, any>[] =\n matchingResults;\n if (!matchingResults.length) {\n return undefined;\n }\n if (!this.returnId) {\n returnedValues = matchingResults.map(\n (result: ParsedToolCall) => result.args\n );\n }\n if (this.returnSingle) {\n return this._validateResult(returnedValues[0]);\n }\n const toolCallResults = await Promise.all(\n returnedValues.map((value) => this._validateResult(value))\n );\n return toolCallResults;\n }\n}\n"],"mappings":";;;;;;;;AA8CA,SAAgB,cAEd,aACA,SACsB;CACtB,IAAI,YAAY,aAAa,KAAA,GAC3B;CAEF,IAAI;CACJ,IAAI,SAAS,SACX,IAAI;EACF,eAAeA,aAAAA,iBAAiB,YAAY,SAAS,aAAa,IAAI;CACxE,QAAQ;EACN;CACF;MAEA,IAAI;EACF,eAAe,KAAK,MAAM,YAAY,SAAS,SAAS;CAE1D,SAAS,GAAQ;EACf,MAAM,IAAIC,aAAAA,sBACR;GACE,aAAa,YAAY,SAAS,KAAK;GACvC;GACA,YAAY,SAAS;GACrB;GACA;GACA,UAAU,EAAE;EACd,CAAC,CAAC,KAAK,IAAI,CACb;CACF;CAGF,MAAM,iBAA2B;EAC/B,MAAM,YAAY,SAAS;EAC3B,MAAM;EACN,MAA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AIH,aAAAA,sBACR,2BAA2B,KAAK,UAC9B,QACA,MACA,CAEF,EAAE,YAAY,KAAK,UAAW,gBAAgB,OAAe,MAAM,KACnE,KAAK,UAAU,QAAQ,MAAM,CAAC,CAChC;CAEJ;CAGA,MAAM,mBAAmB,aAA6C;EAEpE,MAAM,mBAAkB,MADF,MAAM,mBAAmB,WAAW,EAAA,CAC1B,QAC7B,WAA2B,OAAO,SAAS,KAAK,OACnD;EAEA,IAAI,iBACF;EACF,IAAI,CAAC,gBAAgB,QACnB;EAEF,IAAI,CAAC,KAAK,UACR,iBAAiB,gBAAgB,KAC9B,WAA2B,OAAO,IACrC;EAEF,IAAI,KAAK,cACP,OAAO,eAAe;EAExB,OAAO;CACT;CAGA,MAAM,YAAY,aAA6C;EAC7D,gBAAA,eAAe,YAAY,EAAE;EAE7B,MAAM,mBAAkB,MADF,MAAM,mBAAmB,aAAa,KAAK,EAAA,CACjC,QAC7B,WAA2B,OAAO,SAAS,KAAK,OACnD;EAEA,IAAI,iBACF;EACF,IAAI,CAAC,gBAAgB,QACnB;EAEF,IAAI,CAAC,KAAK,UACR,iBAAiB,gBAAgB,KAC9B,WAA2B,OAAO,IACrC;EAEF,IAAI,KAAK,cACP,OAAO,KAAK,gBAAgB,eAAe,EAAE;EAK/C,OAAO,MAHuB,QAAQ,IACpC,eAAe,KAAK,UAAU,KAAK,gBAAgB,KAAK,CAAC,CAC3D;CAEF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json_output_tools_parsers.d.cts","names":[],"sources":["../../../src/output_parsers/openai_tools/json_output_tools_parsers.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"json_output_tools_parsers.d.cts","names":[],"sources":["../../../src/output_parsers/openai_tools/json_output_tools_parsers.ts"],"mappings":";;;;;YAiBY;EACV;EAEA;EAGA,MAAM;;YAGI;;EAEV;IACE;wBAEY,cAEd,aAAa,qBACb;EAAW;EAAoB;IAC9B;wBACa,cAEd,aAAa,qBACb;EAAY;EAAoB;IAC/B;wBACa,cAEd,aAAa,qBACb;EAAY;EAAoB;IAC/B;wBA+Ca,iCAAiC,UAAU;EAKvD;EACA;EACA;IACE;IACA;;;wBAKU,oBAEd,aAAa,qBACb,oBACC;;;;qBAaU,sBACX,WACQ,oCAAoC;SACrC;EAIP;EAEA;EAEA;EAEA,YAAY,SAAS;YAKX;EAIJ,SAAS,QAAQ;EAIjB,YAAY,aAAa,mBAAmB,QAAQ;;;;;;;EAYpD,mBACJ,aAAa,wBAAwB,kBACrC,oBAEC;;KAwCA;EACH;EACA;IACE;KAEC,iCAEH,UAAU,sBAAsB;EAC5B,YAAY,UAAU;IAAO;KAE9B,iCAEH,UAAU,sBAAsB;EAC5B,YAAY,UAAU,GAAG;IAAO;YAE1B,sCAEV,UAAU,sBAAsB;EAC5B,YAAY,eAAe;IAAO;YAE5B,2CAEV,UAAU,sBAAsB;EAEhC,qBAAqB,mBAAmB;IACtC;YAGQ,+BAEV,UAAU,sBAAsB,uBAC9B,iCAAiC;;;;;qBAMxB,yBAEX,UAAU,sBAAsB,6BACxB,sBAAsB;SACvB;EAIP;EAEA;EAEA;;EAGA;;EAGA;EAEA,YAAY,eAAe;EAE3B,qBAAqB,mBAAmB;EAExC,YAAY,QAAQ,iCAAiC;EAErD,YAAY,QAAQ,iCAAiC;EAErD,YAAY,QAAQ,sCAAsC;YAoB1C,gBAAgB,kBAAkB,QAAQ;EAoCpD,mBAAmB,aAAa,mBAAmB;EAuBnD,YAAY,aAAa,mBAAmB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json_output_tools_parsers.d.ts","names":[],"sources":["../../../src/output_parsers/openai_tools/json_output_tools_parsers.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"json_output_tools_parsers.d.ts","names":[],"sources":["../../../src/output_parsers/openai_tools/json_output_tools_parsers.ts"],"mappings":";;;;;YAiBY;EACV;EAEA;EAGA,MAAM;;YAGI;;EAEV;IACE;wBAEY,cAEd,aAAa,qBACb;EAAW;EAAoB;IAC9B;wBACa,cAEd,aAAa,qBACb;EAAY;EAAoB;IAC/B;wBACa,cAEd,aAAa,qBACb;EAAY;EAAoB;IAC/B;wBA+Ca,iCAAiC,UAAU;EAKvD;EACA;EACA;IACE;IACA;;;wBAKU,oBAEd,aAAa,qBACb,oBACC;;;;qBAaU,sBACX,WACQ,oCAAoC;SACrC;EAIP;EAEA;EAEA;EAEA,YAAY,SAAS;YAKX;EAIJ,SAAS,QAAQ;EAIjB,YAAY,aAAa,mBAAmB,QAAQ;;;;;;;EAYpD,mBACJ,aAAa,wBAAwB,kBACrC,oBAEC;;KAwCA;EACH;EACA;IACE;KAEC,iCAEH,UAAU,sBAAsB;EAC5B,YAAY,UAAU;IAAO;KAE9B,iCAEH,UAAU,sBAAsB;EAC5B,YAAY,UAAU,GAAG;IAAO;YAE1B,sCAEV,UAAU,sBAAsB;EAC5B,YAAY,eAAe;IAAO;YAE5B,2CAEV,UAAU,sBAAsB;EAEhC,qBAAqB,mBAAmB;IACtC;YAGQ,+BAEV,UAAU,sBAAsB,uBAC9B,iCAAiC;;;;;qBAMxB,yBAEX,UAAU,sBAAsB,6BACxB,sBAAsB;SACvB;EAIP;EAEA;EAEA;;EAGA;;EAGA;EAEA,YAAY,eAAe;EAE3B,qBAAqB,mBAAmB;EAExC,YAAY,QAAQ,iCAAiC;EAErD,YAAY,QAAQ,iCAAiC;EAErD,YAAY,QAAQ,sCAAsC;YAoB1C,gBAAgB,kBAAkB,QAAQ;EAoCpD,mBAAmB,aAAa,mBAAmB;EAuBnD,YAAY,aAAa,mBAAmB"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { parsePartialJson } from "../../utils/json.js";
|
|
2
2
|
import { OutputParserException } from "../base.js";
|
|
3
|
+
import { throwIfRefused } from "../refusal.js";
|
|
3
4
|
import "../json.js";
|
|
4
5
|
import { BaseCumulativeTransformOutputParser } from "../transform.js";
|
|
5
6
|
import { isAIMessage } from "../../messages/ai.js";
|
|
@@ -78,6 +79,7 @@ var JsonOutputToolsParser = class extends BaseCumulativeTransformOutputParser {
|
|
|
78
79
|
throw new Error("Not implemented.");
|
|
79
80
|
}
|
|
80
81
|
async parseResult(generations) {
|
|
82
|
+
throwIfRefused(generations[0]);
|
|
81
83
|
return await this.parsePartialResult(generations, false);
|
|
82
84
|
}
|
|
83
85
|
/**
|
|
@@ -164,6 +166,7 @@ var JsonOutputKeyToolsParser = class extends JsonOutputToolsParser {
|
|
|
164
166
|
return returnedValues;
|
|
165
167
|
}
|
|
166
168
|
async parseResult(generations) {
|
|
169
|
+
throwIfRefused(generations[0]);
|
|
167
170
|
const matchingResults = (await super.parsePartialResult(generations, false)).filter((result) => result.type === this.keyName);
|
|
168
171
|
let returnedValues = matchingResults;
|
|
169
172
|
if (!matchingResults.length) return;
|