@langchain/openai 1.5.5 → 1.5.6
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 +6 -0
- package/dist/azure/chat_models/common.cjs.map +1 -1
- package/dist/azure/chat_models/common.d.cts +1 -1
- package/dist/azure/chat_models/common.d.cts.map +1 -1
- package/dist/azure/chat_models/common.d.ts +1 -1
- package/dist/azure/chat_models/common.d.ts.map +1 -1
- package/dist/azure/chat_models/common.js.map +1 -1
- package/dist/azure/chat_models/completions.cjs.map +1 -1
- package/dist/azure/chat_models/completions.d.cts +0 -1
- package/dist/azure/chat_models/completions.d.cts.map +1 -1
- package/dist/azure/chat_models/completions.d.ts +0 -1
- package/dist/azure/chat_models/completions.d.ts.map +1 -1
- package/dist/azure/chat_models/completions.js.map +1 -1
- package/dist/azure/chat_models/index.cjs.map +1 -1
- package/dist/azure/chat_models/index.d.cts +1 -2
- package/dist/azure/chat_models/index.d.cts.map +1 -1
- package/dist/azure/chat_models/index.d.ts +0 -1
- package/dist/azure/chat_models/index.d.ts.map +1 -1
- package/dist/azure/chat_models/index.js.map +1 -1
- package/dist/azure/chat_models/responses.cjs.map +1 -1
- package/dist/azure/chat_models/responses.d.cts +0 -1
- package/dist/azure/chat_models/responses.d.cts.map +1 -1
- package/dist/azure/chat_models/responses.d.ts +0 -1
- package/dist/azure/chat_models/responses.d.ts.map +1 -1
- package/dist/azure/chat_models/responses.js.map +1 -1
- package/dist/azure/embeddings.cjs.map +1 -1
- package/dist/azure/embeddings.d.cts +2 -2
- package/dist/azure/embeddings.d.cts.map +1 -1
- package/dist/azure/embeddings.d.ts +2 -2
- package/dist/azure/embeddings.d.ts.map +1 -1
- package/dist/azure/embeddings.js.map +1 -1
- package/dist/azure/llms.cjs.map +1 -1
- package/dist/azure/llms.d.cts +0 -1
- package/dist/azure/llms.d.cts.map +1 -1
- package/dist/azure/llms.d.ts +0 -1
- package/dist/azure/llms.d.ts.map +1 -1
- package/dist/azure/llms.js.map +1 -1
- package/dist/chat_models/base.cjs +37 -3
- package/dist/chat_models/base.cjs.map +1 -1
- package/dist/chat_models/base.d.cts +6 -7
- package/dist/chat_models/base.d.cts.map +1 -1
- package/dist/chat_models/base.d.ts +5 -6
- package/dist/chat_models/base.d.ts.map +1 -1
- package/dist/chat_models/base.js +37 -3
- package/dist/chat_models/base.js.map +1 -1
- package/dist/chat_models/completions.cjs.map +1 -1
- package/dist/chat_models/completions.d.cts +0 -1
- package/dist/chat_models/completions.d.cts.map +1 -1
- package/dist/chat_models/completions.d.ts +0 -1
- package/dist/chat_models/completions.d.ts.map +1 -1
- package/dist/chat_models/completions.js.map +1 -1
- package/dist/chat_models/index.cjs.map +1 -1
- package/dist/chat_models/index.d.cts +14 -17
- package/dist/chat_models/index.d.cts.map +1 -1
- package/dist/chat_models/index.d.ts +14 -17
- package/dist/chat_models/index.d.ts.map +1 -1
- package/dist/chat_models/index.js.map +1 -1
- package/dist/chat_models/profiles.cjs.map +1 -1
- package/dist/chat_models/profiles.js.map +1 -1
- package/dist/chat_models/responses.cjs.map +1 -1
- package/dist/chat_models/responses.d.cts +0 -1
- package/dist/chat_models/responses.d.cts.map +1 -1
- package/dist/chat_models/responses.d.ts +0 -1
- package/dist/chat_models/responses.d.ts.map +1 -1
- package/dist/chat_models/responses.js.map +1 -1
- package/dist/converters/completions.cjs.map +1 -1
- package/dist/converters/completions.d.cts +0 -1
- package/dist/converters/completions.d.cts.map +1 -1
- package/dist/converters/completions.d.ts +0 -1
- package/dist/converters/completions.d.ts.map +1 -1
- package/dist/converters/completions.js.map +1 -1
- package/dist/converters/index.cjs +14 -2
- package/dist/converters/index.d.cts +2 -1
- package/dist/converters/index.d.ts +2 -1
- package/dist/converters/index.js +3 -3
- package/dist/converters/responses.cjs.map +1 -1
- package/dist/converters/responses.d.cts +0 -1
- package/dist/converters/responses.d.cts.map +1 -1
- package/dist/converters/responses.d.ts +0 -1
- package/dist/converters/responses.d.ts.map +1 -1
- package/dist/converters/responses.js.map +1 -1
- package/dist/embeddings.cjs.map +1 -1
- package/dist/embeddings.d.cts +2 -2
- package/dist/embeddings.d.cts.map +1 -1
- package/dist/embeddings.d.ts +2 -2
- package/dist/embeddings.d.ts.map +1 -1
- package/dist/embeddings.js.map +1 -1
- package/dist/index.d.cts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/llms.cjs +1 -1
- package/dist/llms.cjs.map +1 -1
- package/dist/llms.d.cts +1 -2
- package/dist/llms.d.cts.map +1 -1
- package/dist/llms.d.ts +1 -2
- package/dist/llms.d.ts.map +1 -1
- package/dist/llms.js +1 -1
- package/dist/llms.js.map +1 -1
- package/dist/tools/applyPatch.cjs +4 -0
- package/dist/tools/applyPatch.cjs.map +1 -1
- package/dist/tools/applyPatch.d.cts +1 -2
- package/dist/tools/applyPatch.d.cts.map +1 -1
- package/dist/tools/applyPatch.d.ts +1 -2
- package/dist/tools/applyPatch.d.ts.map +1 -1
- package/dist/tools/applyPatch.js +1 -1
- package/dist/tools/applyPatch.js.map +1 -1
- package/dist/tools/codeInterpreter.cjs.map +1 -1
- package/dist/tools/codeInterpreter.d.cts +0 -1
- package/dist/tools/codeInterpreter.d.cts.map +1 -1
- package/dist/tools/codeInterpreter.d.ts +0 -1
- package/dist/tools/codeInterpreter.d.ts.map +1 -1
- package/dist/tools/codeInterpreter.js.map +1 -1
- package/dist/tools/computerUse.cjs +1 -0
- package/dist/tools/computerUse.cjs.map +1 -1
- package/dist/tools/computerUse.d.cts +1 -2
- package/dist/tools/computerUse.d.cts.map +1 -1
- package/dist/tools/computerUse.d.ts +1 -2
- package/dist/tools/computerUse.d.ts.map +1 -1
- package/dist/tools/computerUse.js +1 -1
- package/dist/tools/computerUse.js.map +1 -1
- package/dist/tools/custom.cjs.map +1 -1
- package/dist/tools/custom.d.cts +1 -2
- package/dist/tools/custom.d.cts.map +1 -1
- package/dist/tools/custom.d.ts +1 -2
- package/dist/tools/custom.d.ts.map +1 -1
- package/dist/tools/custom.js.map +1 -1
- package/dist/tools/dalle.cjs.map +1 -1
- package/dist/tools/dalle.d.cts +0 -1
- package/dist/tools/dalle.d.cts.map +1 -1
- package/dist/tools/dalle.d.ts +0 -1
- package/dist/tools/dalle.d.ts.map +1 -1
- package/dist/tools/dalle.js.map +1 -1
- package/dist/tools/fileSearch.cjs.map +1 -1
- package/dist/tools/fileSearch.d.cts +0 -1
- package/dist/tools/fileSearch.d.cts.map +1 -1
- package/dist/tools/fileSearch.d.ts +0 -1
- package/dist/tools/fileSearch.d.ts.map +1 -1
- package/dist/tools/fileSearch.js.map +1 -1
- package/dist/tools/imageGeneration.cjs.map +1 -1
- package/dist/tools/imageGeneration.d.cts +0 -1
- package/dist/tools/imageGeneration.d.cts.map +1 -1
- package/dist/tools/imageGeneration.d.ts +0 -1
- package/dist/tools/imageGeneration.d.ts.map +1 -1
- package/dist/tools/imageGeneration.js.map +1 -1
- package/dist/tools/index.cjs +2 -1
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.d.cts +1 -2
- package/dist/tools/index.d.cts.map +1 -1
- package/dist/tools/index.d.ts +1 -2
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js +2 -2
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/localShell.cjs +2 -0
- package/dist/tools/localShell.cjs.map +1 -1
- package/dist/tools/localShell.d.cts +1 -2
- package/dist/tools/localShell.d.cts.map +1 -1
- package/dist/tools/localShell.d.ts +1 -2
- package/dist/tools/localShell.d.ts.map +1 -1
- package/dist/tools/localShell.js +1 -1
- package/dist/tools/localShell.js.map +1 -1
- package/dist/tools/mcp.cjs.map +1 -1
- package/dist/tools/mcp.d.cts +0 -1
- package/dist/tools/mcp.d.cts.map +1 -1
- package/dist/tools/mcp.d.ts +0 -1
- package/dist/tools/mcp.d.ts.map +1 -1
- package/dist/tools/mcp.js.map +1 -1
- package/dist/tools/shell.cjs +1 -0
- package/dist/tools/shell.cjs.map +1 -1
- package/dist/tools/shell.d.cts +1 -2
- package/dist/tools/shell.d.cts.map +1 -1
- package/dist/tools/shell.d.ts +1 -2
- package/dist/tools/shell.d.ts.map +1 -1
- package/dist/tools/shell.js +1 -1
- package/dist/tools/shell.js.map +1 -1
- package/dist/tools/toolSearch.cjs.map +1 -1
- package/dist/tools/toolSearch.d.cts +0 -1
- package/dist/tools/toolSearch.d.cts.map +1 -1
- package/dist/tools/toolSearch.d.ts +0 -1
- package/dist/tools/toolSearch.d.ts.map +1 -1
- package/dist/tools/toolSearch.js.map +1 -1
- package/dist/tools/webSearch.cjs.map +1 -1
- package/dist/tools/webSearch.d.cts +1 -2
- package/dist/tools/webSearch.d.cts.map +1 -1
- package/dist/tools/webSearch.d.ts +1 -2
- package/dist/tools/webSearch.d.ts.map +1 -1
- package/dist/tools/webSearch.js.map +1 -1
- package/dist/types.d.cts +0 -1
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.ts +0 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/azure.cjs.map +1 -1
- package/dist/utils/azure.d.cts.map +1 -1
- package/dist/utils/azure.d.ts.map +1 -1
- package/dist/utils/azure.js.map +1 -1
- package/dist/utils/client.cjs.map +1 -1
- package/dist/utils/client.d.cts.map +1 -1
- package/dist/utils/client.d.ts.map +1 -1
- package/dist/utils/client.js.map +1 -1
- package/dist/utils/errors.cjs.map +1 -1
- package/dist/utils/errors.js.map +1 -1
- package/dist/utils/misc.cjs +2 -0
- package/dist/utils/misc.cjs.map +1 -1
- package/dist/utils/misc.d.cts +0 -1
- package/dist/utils/misc.d.cts.map +1 -1
- package/dist/utils/misc.d.ts +0 -1
- package/dist/utils/misc.d.ts.map +1 -1
- package/dist/utils/misc.js +1 -1
- package/dist/utils/misc.js.map +1 -1
- package/dist/utils/output.cjs.map +1 -1
- package/dist/utils/output.js.map +1 -1
- package/dist/utils/prompts.cjs.map +1 -1
- package/dist/utils/prompts.d.cts +0 -1
- package/dist/utils/prompts.d.cts.map +1 -1
- package/dist/utils/prompts.d.ts +0 -1
- package/dist/utils/prompts.d.ts.map +1 -1
- package/dist/utils/prompts.js.map +1 -1
- package/dist/utils/responses_stream_events.cjs.map +1 -1
- package/dist/utils/responses_stream_events.d.cts +0 -1
- package/dist/utils/responses_stream_events.d.cts.map +1 -1
- package/dist/utils/responses_stream_events.d.ts +0 -1
- package/dist/utils/responses_stream_events.d.ts.map +1 -1
- package/dist/utils/responses_stream_events.js.map +1 -1
- package/dist/utils/tools.cjs.map +1 -1
- package/dist/utils/tools.d.cts +2 -0
- package/dist/utils/tools.d.cts.map +1 -1
- package/dist/utils/tools.d.ts +2 -0
- package/dist/utils/tools.d.ts.map +1 -1
- package/dist/utils/tools.js.map +1 -1
- package/package.json +6 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"responses.js","names":["iife","castToolOutputs"],"sources":["../../src/converters/responses.ts"],"sourcesContent":["import { OpenAI as OpenAIClient } from \"openai\";\nimport {\n AIMessage,\n AIMessageChunk,\n type BaseMessage,\n type UsageMetadata,\n type BaseMessageFields,\n type MessageContent,\n type InvalidToolCall,\n MessageContentImageUrl,\n isDataContentBlock,\n convertToProviderContentBlock,\n ContentBlock,\n} from \"@langchain/core/messages\";\nimport { ChatGenerationChunk } from \"@langchain/core/outputs\";\nimport {\n makeInvalidToolCall,\n parseToolCall,\n} from \"@langchain/core/output_parsers/openai_tools\";\nimport type {\n ToolCall,\n ToolCallChunk,\n ToolMessage,\n} from \"@langchain/core/messages/tool\";\nimport { ResponseInputMessageContentList } from \"openai/resources/responses/responses.js\";\nimport { ChatOpenAIReasoningSummary } from \"../types.js\";\nimport {\n isComputerToolCall,\n isCustomToolCall,\n parseComputerCall,\n parseCustomToolCall,\n} from \"../utils/tools.js\";\nimport {\n getFilenameFromMetadata,\n getRequiredFilenameFromMetadata,\n iife,\n isReasoningModel,\n messageToOpenAIRole,\n} from \"../utils/misc.js\";\nimport { Converter } from \"@langchain/core/utils/format\";\nimport { completionsApiContentBlockConverter } from \"./completions.js\";\n\nconst _FUNCTION_CALL_IDS_MAP_KEY = \"__openai_function_call_ids__\";\nconst _CUSTOM_TOOL_CALL_IDS_MAP_KEY = \"__openai_custom_tool_call_ids__\";\n\n/** Streaming-only marker; not part of @langchain/core ToolCallChunk. */\ntype OpenAICustomToolCallChunk = ToolCallChunk & { isCustomTool?: true };\n\ntype OpenAIAnnotation =\n OpenAIClient.Responses.ResponseOutputText[\"annotations\"][number];\n\n/**\n * Converts an OpenAI annotation to a LangChain Citation or BaseContentBlock.\n *\n * OpenAI has several annotation types:\n * - `url_citation`: Web citations with url, title, start_index, end_index\n * - `file_citation`: File citations with file_id, filename, index\n * - `container_file_citation`: Container file citations with container_id, file_id, filename, start_index, end_index\n * - `file_path`: File paths with file_id, index\n *\n * This function maps them to LangChain's Citation format or preserves them as non-standard blocks.\n */\nfunction convertOpenAIAnnotationToLangChain(\n annotation: OpenAIAnnotation\n): ContentBlock.Citation | ContentBlock.NonStandard {\n if (annotation.type === \"url_citation\") {\n return {\n type: \"citation\",\n source: \"url_citation\",\n url: annotation.url,\n title: annotation.title,\n startIndex: annotation.start_index,\n endIndex: annotation.end_index,\n } satisfies ContentBlock.Citation;\n }\n\n if (annotation.type === \"file_citation\") {\n return {\n type: \"citation\",\n source: \"file_citation\",\n title: annotation.filename,\n startIndex: annotation.index,\n // Store file_id in a way that can be retrieved\n file_id: annotation.file_id,\n } as ContentBlock.Citation;\n }\n\n if (annotation.type === \"container_file_citation\") {\n return {\n type: \"citation\",\n source: \"container_file_citation\",\n title: annotation.filename,\n startIndex: annotation.start_index,\n endIndex: annotation.end_index,\n // Store additional IDs\n file_id: annotation.file_id,\n container_id: annotation.container_id,\n } as ContentBlock.Citation;\n }\n\n if (annotation.type === \"file_path\") {\n return {\n type: \"citation\",\n source: \"file_path\",\n startIndex: annotation.index,\n file_id: annotation.file_id,\n } as ContentBlock.Citation;\n }\n\n // For unknown annotation types, preserve them as non-standard blocks\n return {\n type: \"non_standard\",\n value: annotation as unknown as Record<string, unknown>,\n } satisfies ContentBlock.NonStandard;\n}\n\n/**\n * Converts a LangChain Citation or BaseContentBlock back to an OpenAI annotation.\n *\n * This is the inverse of `convertOpenAIAnnotationToLangChain`. It handles all four\n * annotation types (url_citation, file_citation, container_file_citation, file_path)\n * and also passes through annotations that are already in OpenAI format.\n */\nfunction convertLangChainAnnotationToOpenAI(\n annotation:\n | ContentBlock.Citation\n | ContentBlock.NonStandard\n | Record<string, unknown>\n): OpenAIAnnotation {\n // If it's already in OpenAI format, pass through unchanged\n if (\n annotation.type === \"url_citation\" ||\n annotation.type === \"file_citation\" ||\n annotation.type === \"container_file_citation\" ||\n annotation.type === \"file_path\"\n ) {\n return annotation as unknown as OpenAIAnnotation;\n }\n\n // Convert from LangChain citation format back to OpenAI format\n if (annotation.type === \"citation\") {\n const citation = annotation as ContentBlock.Citation & {\n file_id?: string;\n container_id?: string;\n };\n\n if (citation.source === \"url_citation\") {\n return {\n type: \"url_citation\",\n url: citation.url ?? \"\",\n title: citation.title ?? \"\",\n start_index: citation.startIndex ?? 0,\n end_index: citation.endIndex ?? 0,\n } as OpenAIAnnotation;\n }\n\n if (citation.source === \"file_citation\") {\n return {\n type: \"file_citation\",\n file_id: citation.file_id ?? \"\",\n filename: citation.title ?? \"\",\n index: citation.startIndex ?? 0,\n } as OpenAIAnnotation;\n }\n\n if (citation.source === \"container_file_citation\") {\n return {\n type: \"container_file_citation\",\n file_id: citation.file_id ?? \"\",\n filename: citation.title ?? \"\",\n container_id: citation.container_id ?? \"\",\n start_index: citation.startIndex ?? 0,\n end_index: citation.endIndex ?? 0,\n } as OpenAIAnnotation;\n }\n\n if (citation.source === \"file_path\") {\n return {\n type: \"file_path\",\n file_id: citation.file_id ?? \"\",\n index: citation.startIndex ?? 0,\n } as OpenAIAnnotation;\n }\n }\n\n // For non_standard blocks, unwrap the value\n if (annotation.type === \"non_standard\") {\n return (annotation as ContentBlock.NonStandard)\n .value as unknown as OpenAIAnnotation;\n }\n\n // Unknown format, pass through as-is\n return annotation as unknown as OpenAIAnnotation;\n}\n\ntype ExcludeController<T> = T extends { controller: unknown } ? never : T;\n\nexport type ResponsesCreate = OpenAIClient.Responses[\"create\"];\nexport type ResponsesParse = OpenAIClient.Responses[\"parse\"];\n\nexport type ResponsesCreateInvoke = ExcludeController<\n Awaited<ReturnType<ResponsesCreate>>\n>;\nexport type ResponsesParseInvoke = ExcludeController<\n Awaited<ReturnType<ResponsesParse>>\n>;\n\nexport type ResponsesInputItem = OpenAIClient.Responses.ResponseInputItem;\n\n/**\n * Converts OpenAI Responses API usage statistics to LangChain's UsageMetadata format.\n *\n * This converter transforms token usage information from OpenAI's Responses API into\n * the standardized UsageMetadata format used throughout LangChain. It handles both\n * basic token counts and detailed token breakdowns including cached tokens and\n * reasoning tokens.\n *\n * @param usage - The usage statistics object from OpenAI's Responses API containing\n * token counts and optional detailed breakdowns.\n *\n * @returns A UsageMetadata object containing:\n * - `input_tokens`: Total number of tokens in the input/prompt (defaults to 0 if not provided)\n * - `output_tokens`: Total number of tokens in the model's output (defaults to 0 if not provided)\n * - `total_tokens`: Combined total of input and output tokens (defaults to 0 if not provided)\n * - `input_token_details`: Object containing detailed input token information:\n * - `cache_read`: Number of tokens read from cache (only included if available)\n * - `output_token_details`: Object containing detailed output token information:\n * - `reasoning`: Number of tokens used for reasoning (only included if available)\n *\n * @example\n * ```typescript\n * const usage = {\n * input_tokens: 100,\n * output_tokens: 50,\n * total_tokens: 150,\n * input_tokens_details: { cached_tokens: 20 },\n * output_tokens_details: { reasoning_tokens: 10 }\n * };\n *\n * const metadata = convertResponsesUsageToUsageMetadata(usage);\n * // Returns:\n * // {\n * // input_tokens: 100,\n * // output_tokens: 50,\n * // total_tokens: 150,\n * // input_token_details: { cache_read: 20 },\n * // output_token_details: { reasoning: 10 }\n * // }\n * ```\n *\n * @remarks\n * - The function safely handles undefined or null values by using optional chaining\n * and nullish coalescing operators\n * - Detailed token information (cache_read, reasoning) is only included in the result\n * if the corresponding values are present in the input\n * - Token counts default to 0 if not provided in the usage object\n * - This converter is specifically designed for OpenAI's Responses API format and\n * may differ from other OpenAI API endpoints\n */\nexport const convertResponsesUsageToUsageMetadata: Converter<\n OpenAIClient.Responses.ResponseUsage | undefined,\n UsageMetadata\n> = (usage) => {\n const inputTokenDetails = {\n ...(usage?.input_tokens_details?.cached_tokens != null && {\n cache_read: usage?.input_tokens_details?.cached_tokens,\n }),\n };\n const outputTokenDetails = {\n ...(usage?.output_tokens_details?.reasoning_tokens != null && {\n reasoning: usage?.output_tokens_details?.reasoning_tokens,\n }),\n };\n return {\n input_tokens: usage?.input_tokens ?? 0,\n output_tokens: usage?.output_tokens ?? 0,\n total_tokens: usage?.total_tokens ?? 0,\n input_token_details: inputTokenDetails,\n output_token_details: outputTokenDetails,\n };\n};\n\n/**\n * Converts an OpenAI Responses API response to a LangChain AIMessage.\n *\n * This converter processes the output from OpenAI's Responses API (both `create` and `parse` methods)\n * and transforms it into a LangChain AIMessage object with all relevant metadata, tool calls, and content.\n *\n * @param response - The response object from OpenAI's Responses API. Can be either:\n * - ResponsesCreateInvoke: Result from `responses.create()`\n * - ResponsesParseInvoke: Result from `responses.parse()`\n *\n * @returns An AIMessage containing:\n * - `id`: The message ID from the response output\n * - `content`: Array of message content blocks (text, images, etc.)\n * - `tool_calls`: Array of successfully parsed tool calls\n * - `invalid_tool_calls`: Array of tool calls that failed to parse\n * - `usage_metadata`: Token usage information converted to LangChain format\n * - `additional_kwargs`: Extra data including:\n * - `refusal`: Refusal text if the model refused to respond\n * - `reasoning`: Reasoning output for reasoning models\n * - `tool_outputs`: Results from built-in tools (web search, file search, etc.)\n * - `parsed`: Parsed structured output when using json_schema format\n * - Function call ID mappings for tracking\n * - `response_metadata`: Metadata about the response including model, timestamps, status, etc.\n *\n * @throws Error if the response contains an error object. The error message and code are extracted\n * from the response.error field.\n *\n * @example\n * ```typescript\n * const response = await client.responses.create({\n * model: \"gpt-4\",\n * input: [{ type: \"message\", content: \"Hello\" }]\n * });\n * const message = convertResponsesMessageToAIMessage(response);\n * console.log(message.content); // Message content\n * console.log(message.tool_calls); // Any tool calls made\n * ```\n *\n * @remarks\n * The converter handles multiple output item types:\n * - `message`: Text and structured content from the model\n * - `function_call`: Tool/function calls that need to be executed\n * - `reasoning`: Reasoning traces from reasoning models (o1, o3, etc.)\n * - `custom_tool_call`: Custom tool invocations\n * - Built-in tool outputs: web_search, file_search, code_interpreter, etc.\n *\n * Tool calls are parsed and validated. Invalid tool calls (malformed JSON, etc.) are captured\n * in the `invalid_tool_calls` array rather than throwing errors.\n */\nexport const convertResponsesMessageToAIMessage: Converter<\n ResponsesCreateInvoke | ResponsesParseInvoke,\n AIMessage\n> = (response) => {\n if (response.error) {\n // TODO: add support for `addLangChainErrorFields`\n const error = new Error(response.error.message);\n error.name = response.error.code;\n throw error;\n }\n\n const content: MessageContent = [];\n const tool_calls: ToolCall[] = [];\n const invalid_tool_calls: InvalidToolCall[] = [];\n // Preserve the raw output items so that convertMessagesToResponsesInput can\n // return them verbatim on the fast path. We strip `parsed_arguments` from\n // function_call items because the OpenAI SDK injects it when using\n // responses.parse(), but the API rejects it when sent back as input.\n const cleanedOutput = response.output.map((item) => {\n if (item.type === \"function_call\" && \"parsed_arguments\" in item) {\n const cleaned = { ...item };\n delete (cleaned as Record<string, unknown>).parsed_arguments;\n return cleaned;\n }\n return item;\n });\n\n const response_metadata: Record<string, unknown> = {\n model_provider: \"openai\",\n model: response.model,\n created_at: response.created_at,\n id: response.id,\n incomplete_details: response.incomplete_details,\n metadata: response.metadata,\n object: response.object,\n output: cleanedOutput,\n status: response.status,\n user: response.user,\n service_tier: response.service_tier,\n // for compatibility with chat completion calls.\n model_name: response.model,\n };\n\n const additional_kwargs: {\n [key: string]: unknown;\n refusal?: string;\n reasoning?: OpenAIClient.Responses.ResponseReasoningItem;\n tool_outputs?: unknown[];\n parsed?: unknown;\n [_FUNCTION_CALL_IDS_MAP_KEY]?: Record<string, string>;\n [_CUSTOM_TOOL_CALL_IDS_MAP_KEY]?: Record<string, string>;\n } = {};\n\n for (const item of response.output) {\n if (item.type === \"message\") {\n content.push(\n ...item.content.flatMap((part) => {\n if (part.type === \"output_text\") {\n if (\"parsed\" in part && part.parsed != null) {\n additional_kwargs.parsed = part.parsed;\n }\n const block: ContentBlock = {\n type: \"text\",\n text: part.text,\n annotations: part.annotations.map(\n convertOpenAIAnnotationToLangChain\n ),\n ...(item.phase !== null ? { phase: item.phase } : {}),\n };\n return block;\n }\n\n if (part.type === \"refusal\") {\n additional_kwargs.refusal = part.refusal;\n return [];\n }\n\n return part;\n })\n );\n } else if (item.type === \"function_call\") {\n const fnAdapter = {\n function: { name: item.name, arguments: item.arguments },\n id: item.call_id,\n };\n\n try {\n tool_calls.push(parseToolCall(fnAdapter, { returnId: true }));\n } catch (e: unknown) {\n let errMessage: string | undefined;\n if (\n typeof e === \"object\" &&\n e != null &&\n \"message\" in e &&\n typeof e.message === \"string\"\n ) {\n errMessage = e.message;\n }\n invalid_tool_calls.push(makeInvalidToolCall(fnAdapter, errMessage));\n }\n\n additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] ??= {};\n if (item.id) {\n additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY][item.call_id] = item.id;\n }\n } else if (item.type === \"reasoning\") {\n additional_kwargs.reasoning = item;\n // Also elevate reasoning to content for UI rendering\n const reasoningText = item.summary\n ?.map((s) => s.text)\n .filter(Boolean)\n .join(\"\");\n if (reasoningText) {\n content.push({\n type: \"reasoning\",\n reasoning: reasoningText,\n });\n }\n } else if (item.type === \"custom_tool_call\") {\n const parsed = parseCustomToolCall(item);\n if (parsed) {\n tool_calls.push(parsed);\n additional_kwargs[_CUSTOM_TOOL_CALL_IDS_MAP_KEY] ??= {};\n if (item.id && item.call_id) {\n additional_kwargs[_CUSTOM_TOOL_CALL_IDS_MAP_KEY][item.call_id] =\n item.id;\n }\n } else {\n invalid_tool_calls.push(\n makeInvalidToolCall(item, \"Malformed custom tool call\")\n );\n }\n } else if (item.type === \"computer_call\") {\n const parsed = parseComputerCall(item);\n if (parsed) {\n tool_calls.push(parsed);\n } else {\n invalid_tool_calls.push(\n makeInvalidToolCall(item, \"Malformed computer call\")\n );\n }\n } else if (item.type === \"image_generation_call\") {\n // Add image as proper content block if result is available\n if (item.result) {\n content.push({\n type: \"image\",\n mimeType: \"image/png\",\n data: item.result,\n id: item.id,\n metadata: {\n status: item.status,\n },\n } satisfies ContentBlock.Multimodal.Image);\n }\n // Also store in tool_outputs for backwards compatibility and multi-turn editing (needs id)\n additional_kwargs.tool_outputs ??= [];\n additional_kwargs.tool_outputs.push(item);\n } else {\n additional_kwargs.tool_outputs ??= [];\n additional_kwargs.tool_outputs.push(item);\n }\n }\n\n return new AIMessage({\n id: response.id,\n content,\n tool_calls,\n invalid_tool_calls,\n usage_metadata: convertResponsesUsageToUsageMetadata(response.usage),\n additional_kwargs,\n response_metadata,\n });\n};\n\n/**\n * Converts a LangChain ChatOpenAI reasoning summary to an OpenAI Responses API reasoning item.\n *\n * This converter transforms reasoning summaries that have been accumulated during streaming\n * (where summary parts may arrive in multiple chunks with the same index) into the final\n * consolidated format expected by OpenAI's Responses API. It combines summary parts that\n * share the same index and removes the index field from the final output.\n *\n * @param reasoning - A ChatOpenAI reasoning summary object containing:\n * - `id`: The reasoning item ID\n * - `type`: The type of reasoning (typically \"reasoning\")\n * - `summary`: Array of summary parts, each with:\n * - `text`: The summary text content\n * - `type`: The summary type (e.g., \"summary_text\")\n * - `index`: The index used to group related summary parts during streaming\n *\n * @returns An OpenAI Responses API ResponseReasoningItem with:\n * - All properties from the input reasoning object\n * - `summary`: Consolidated array of summary objects with:\n * - `text`: Combined text from all parts with the same index\n * - `type`: The summary type\n * - No `index` field (removed after consolidation)\n *\n * @example\n * ```typescript\n * // Input: Reasoning summary with multiple parts at the same index\n * const reasoning = {\n * id: \"reasoning_123\",\n * type: \"reasoning\",\n * summary: [\n * { text: \"First \", type: \"summary_text\", index: 0 },\n * { text: \"part\", type: \"summary_text\", index: 0 },\n * { text: \"Second part\", type: \"summary_text\", index: 1 }\n * ]\n * };\n *\n * const result = convertReasoningSummaryToResponsesReasoningItem(reasoning);\n * // Returns:\n * // {\n * // id: \"reasoning_123\",\n * // type: \"reasoning\",\n * // summary: [\n * // { text: \"First part\", type: \"summary_text\" },\n * // { text: \"Second part\", type: \"summary_text\" }\n * // ]\n * // }\n * ```\n *\n * @remarks\n * - This converter is primarily used when reconstructing complete reasoning items from\n * streaming chunks, where summary parts may arrive incrementally with index markers\n * - Summary parts with the same index are concatenated in the order they appear\n * - If the reasoning summary contains only one part, no reduction is performed\n * - The index field is used internally during streaming to track which summary parts\n * belong together, but is removed from the final output as it's not part of the\n * OpenAI Responses API schema\n * - This is the inverse operation of the streaming accumulation that happens in\n * `convertResponsesDeltaToChatGenerationChunk`\n */\nexport const convertReasoningSummaryToResponsesReasoningItem: Converter<\n ChatOpenAIReasoningSummary,\n OpenAIClient.Responses.ResponseReasoningItem\n> = (reasoning) => {\n // combine summary parts that have the same index and then remove the indexes\n const summary = (\n reasoning.summary.length > 1\n ? reasoning.summary.reduce(\n (acc, curr) => {\n const last = acc[acc.length - 1];\n\n if (last!.index === curr.index) {\n last!.text += curr.text;\n } else {\n acc.push(curr);\n }\n return acc;\n },\n [{ ...reasoning.summary[0] }]\n )\n : reasoning.summary\n ).map((s) =>\n Object.fromEntries(Object.entries(s).filter(([k]) => k !== \"index\"))\n ) as OpenAIClient.Responses.ResponseReasoningItem.Summary[];\n\n return {\n ...reasoning,\n summary,\n } as OpenAIClient.Responses.ResponseReasoningItem;\n};\n\n/**\n * Converts OpenAI Responses API stream events to LangChain ChatGenerationChunk objects.\n *\n * This converter processes streaming events from OpenAI's Responses API and transforms them\n * into LangChain ChatGenerationChunk objects that can be used in streaming chat applications.\n * It handles various event types including text deltas, tool calls, reasoning, and metadata updates.\n *\n * @param event - A streaming event from OpenAI's Responses API\n *\n * @returns A ChatGenerationChunk containing:\n * - `text`: Concatenated text content from all text parts in the event\n * - `message`: An AIMessageChunk with:\n * - `id`: Response ID (set on `response.created` / `response.completed`)\n * - `content`: Array of content blocks (text with optional annotations)\n * - `tool_call_chunks`: Incremental tool call data (name, args, id)\n * - `usage_metadata`: Token usage information (only in completion events)\n * - `additional_kwargs`: Extra data including:\n * - `refusal`: Refusal text if the model refused to respond\n * - `reasoning`: Reasoning output for reasoning models (id, type, summary)\n * - `tool_outputs`: Results from built-in tools (web search, file search, etc.)\n * - `parsed`: Parsed structured output when using json_schema format\n * - Function call ID mappings for tracking\n * - `response_metadata`: Metadata about the response (model, id, etc.)\n * - `generationInfo`: Additional generation information (e.g., tool output status)\n *\n * Returns `null` for events that don't produce meaningful chunks:\n * - Partial image generation events (to avoid storing all partial images in history)\n * - Unrecognized event types\n *\n * @example\n * ```typescript\n * const stream = await client.responses.create({\n * model: \"gpt-4\",\n * input: [{ type: \"message\", content: \"Hello\" }],\n * stream: true\n * });\n *\n * for await (const event of stream) {\n * const chunk = convertResponsesDeltaToChatGenerationChunk(event);\n * if (chunk) {\n * console.log(chunk.text); // Incremental text\n * console.log(chunk.message.tool_call_chunks); // Tool call updates\n * }\n * }\n * ```\n *\n * @remarks\n * - Text content is accumulated in an array with index tracking for proper ordering\n * - Tool call chunks include incremental arguments that need to be concatenated by the consumer\n * - Reasoning summaries are built incrementally across multiple events\n * - Function call IDs are tracked in `additional_kwargs` to map call_id to item id\n * - The `text` field is provided for legacy compatibility with `onLLMNewToken` callbacks\n * - Usage metadata is only available in `response.completed` events\n * - Partial images are intentionally ignored to prevent memory bloat in conversation history\n */\nexport const convertResponsesDeltaToChatGenerationChunk: Converter<\n OpenAIClient.Responses.ResponseStreamEvent,\n ChatGenerationChunk | null\n> = (event) => {\n const content: ContentBlock[] = [];\n let generationInfo: Record<string, unknown> = {};\n let usage_metadata: UsageMetadata | undefined;\n const tool_call_chunks: ToolCallChunk[] = [];\n const response_metadata: Record<string, unknown> = {\n model_provider: \"openai\",\n };\n const additional_kwargs: {\n [key: string]: unknown;\n reasoning?: Partial<ChatOpenAIReasoningSummary>;\n tool_outputs?: unknown[];\n } = {};\n let id: string | undefined;\n if (event.type === \"response.output_text.delta\") {\n content.push({\n type: \"text\",\n text: event.delta,\n index: event.content_index,\n } satisfies ContentBlock.Text);\n } else if (event.type === \"response.output_text.annotation.added\") {\n content.push({\n type: \"text\",\n text: \"\",\n annotations: [\n convertOpenAIAnnotationToLangChain(\n event.annotation as OpenAIAnnotation\n ),\n ],\n index: event.content_index,\n } satisfies ContentBlock.Text);\n } else if (\n event.type === \"response.output_item.added\" &&\n event.item.type === \"message\"\n ) {\n const phase = \"phase\" in event.item ? event.item.phase : undefined;\n if (phase) {\n content.push({\n type: \"text\",\n text: \"\",\n phase,\n index: 0,\n } as ContentBlock.Text);\n }\n } else if (\n event.type === \"response.output_item.added\" &&\n event.item.type === \"function_call\"\n ) {\n tool_call_chunks.push({\n type: \"tool_call_chunk\",\n name: event.item.name,\n args: event.item.arguments,\n id: event.item.call_id,\n index: event.output_index,\n });\n\n additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] = {\n [event.item.call_id]: event.item.id,\n };\n } else if (\n event.type === \"response.output_item.added\" &&\n event.item.type === \"custom_tool_call\"\n ) {\n tool_call_chunks.push({\n type: \"tool_call_chunk\",\n isCustomTool: true,\n name: event.item.name,\n args: event.item.input,\n id: event.item.call_id,\n index: event.output_index,\n } satisfies OpenAICustomToolCallChunk);\n\n additional_kwargs[_CUSTOM_TOOL_CALL_IDS_MAP_KEY] = {\n [event.item.call_id]: event.item.id,\n };\n } else if (\n event.type === \"response.output_item.done\" &&\n event.item.type === \"computer_call\"\n ) {\n // Handle computer_call as a tool call so ToolNode can process it\n tool_call_chunks.push({\n type: \"tool_call_chunk\",\n name: \"computer_use\",\n args: JSON.stringify({ action: event.item.action }),\n id: event.item.call_id,\n index: event.output_index,\n });\n // Also store the raw item for additional context (pending_safety_checks, etc.)\n additional_kwargs.tool_outputs = [event.item];\n } else if (\n event.type === \"response.output_item.done\" &&\n event.item.type === \"image_generation_call\"\n ) {\n // Add image as proper content block if result is available\n if (event.item.result) {\n content.push({\n type: \"image\",\n mimeType: \"image/png\",\n data: event.item.result,\n id: event.item.id,\n metadata: {\n status: event.item.status,\n },\n } satisfies ContentBlock.Multimodal.Image);\n }\n // Also store in tool_outputs for backwards compatibility and multi-turn editing (needs id)\n additional_kwargs.tool_outputs = [event.item];\n } else if (\n event.type === \"response.output_item.done\" &&\n [\n \"web_search_call\",\n \"file_search_call\",\n \"code_interpreter_call\",\n \"shell_call\",\n \"local_shell_call\",\n \"mcp_call\",\n \"mcp_list_tools\",\n \"mcp_approval_request\",\n \"custom_tool_call\",\n \"tool_search_call\",\n \"tool_search_output\",\n ].includes(event.item.type)\n ) {\n additional_kwargs.tool_outputs = [event.item];\n } else if (event.type === \"response.created\") {\n id = event.response.id;\n response_metadata.id = event.response.id;\n response_metadata.model_name = event.response.model;\n response_metadata.model = event.response.model;\n } else if (\n event.type === \"response.completed\" ||\n event.type === \"response.incomplete\"\n ) {\n id = event.response.id;\n const msg = convertResponsesMessageToAIMessage(event.response);\n\n usage_metadata = convertResponsesUsageToUsageMetadata(event.response.usage);\n\n if (event.response.text?.format?.type === \"json_schema\" && msg.text) {\n try {\n additional_kwargs.parsed ??= JSON.parse(msg.text);\n } catch {\n // Some models (observed with gpt-5-mini on service_tier: \"auto\")\n // intermittently emit trailing characters after a valid JSON object\n // in the Responses API path. Throw-on-parse kills the entire stream\n // even though msg.text is otherwise usable. Leave parsed undefined\n // and let the caller fall back to msg.text or retry. See #10894.\n }\n }\n for (const [key, value] of Object.entries(event.response)) {\n if (key === \"id\") continue;\n // Use the cleaned output from the converted message so that\n // SDK-only fields like parsed_arguments are not persisted.\n if (key === \"output\") {\n response_metadata[key] = msg.response_metadata.output;\n } else {\n response_metadata[key] = value;\n }\n }\n } else if (\n event.type === \"response.function_call_arguments.delta\" ||\n event.type === \"response.custom_tool_call_input.delta\"\n ) {\n tool_call_chunks.push({\n type: \"tool_call_chunk\",\n args: event.delta,\n index: event.output_index,\n ...(event.type === \"response.custom_tool_call_input.delta\"\n ? { isCustomTool: true }\n : {}),\n });\n } else if (\n event.type === \"response.web_search_call.in_progress\" ||\n event.type === \"response.web_search_call.searching\" ||\n event.type === \"response.web_search_call.completed\" ||\n event.type === \"response.file_search_call.in_progress\" ||\n event.type === \"response.file_search_call.searching\" ||\n event.type === \"response.file_search_call.completed\" ||\n event.type === \"response.image_generation_call.in_progress\" ||\n event.type === \"response.image_generation_call.generating\" ||\n event.type === \"response.image_generation_call.completed\"\n ) {\n const [, type, status] = event.type.match(/^response\\.(.*)\\.([^.]+)$/) ?? [\n \"\",\n \"\",\n \"\",\n ];\n generationInfo = {\n tool_outputs: {\n id: event.item_id,\n type,\n status,\n },\n };\n } else if (event.type === \"response.refusal.done\") {\n additional_kwargs.refusal = event.refusal;\n } else if (\n event.type === \"response.output_item.added\" &&\n \"item\" in event &&\n event.item.type === \"reasoning\"\n ) {\n const summary: ChatOpenAIReasoningSummary[\"summary\"] | undefined = event\n .item.summary\n ? event.item.summary.map((s, index) => ({\n ...s,\n index,\n }))\n : undefined;\n\n additional_kwargs.reasoning = {\n // We only capture ID in the first event or else the concatenated result of all chunks will\n // have an ID field that is repeated once per event. There is special handling for the `type`\n // field that prevents this, however.\n id: event.item.id,\n type: event.item.type,\n ...(summary ? { summary } : {}),\n };\n\n // Also elevate reasoning to content for UI rendering\n const reasoningText = event.item.summary\n ?.map((s) => s.text)\n .filter(Boolean)\n .join(\"\");\n if (reasoningText) {\n content.push({\n type: \"reasoning\",\n reasoning: reasoningText,\n });\n }\n } else if (event.type === \"response.reasoning_summary_part.added\") {\n additional_kwargs.reasoning = {\n type: \"reasoning\",\n summary: [{ ...event.part, index: event.summary_index }],\n };\n\n // Also elevate reasoning to content for UI rendering\n if (event.part.text) {\n content.push({\n type: \"reasoning\",\n reasoning: event.part.text,\n index: event.summary_index,\n });\n }\n } else if (event.type === \"response.reasoning_summary_text.delta\") {\n additional_kwargs.reasoning = {\n type: \"reasoning\",\n summary: [\n {\n text: event.delta,\n type: \"summary_text\",\n index: event.summary_index,\n },\n ],\n };\n\n // Also elevate reasoning to content for UI rendering\n if (event.delta) {\n content.push({\n type: \"reasoning\",\n reasoning: event.delta,\n index: event.summary_index,\n });\n }\n } else if (event.type === \"response.image_generation_call.partial_image\") {\n // noop/fixme: retaining partial images in a message chunk means that _all_\n // partial images get kept in history, so we don't do anything here.\n return null;\n } else {\n return null;\n }\n\n return new ChatGenerationChunk({\n // Legacy reasons, `onLLMNewToken` should pulls this out\n text: content.map((part) => part.text).join(\"\"),\n message: new AIMessageChunk({\n id,\n content,\n tool_call_chunks,\n usage_metadata,\n additional_kwargs,\n response_metadata,\n }),\n generationInfo,\n });\n};\n\n/**\n * Converts a single LangChain BaseMessage to OpenAI Responses API input format.\n *\n * This converter transforms a LangChain message into one or more ResponseInputItem objects\n * that can be used with OpenAI's Responses API. It handles complex message structures including\n * tool calls, reasoning blocks, multimodal content, and various content block types.\n *\n * @param message - The LangChain BaseMessage to convert. Can be any message type including\n * HumanMessage, AIMessage, SystemMessage, ToolMessage, etc.\n *\n * @returns An array of ResponseInputItem objects.\n *\n * @example\n * Basic text message conversion:\n * ```typescript\n * const message = new HumanMessage(\"Hello, how are you?\");\n * const items = convertStandardContentMessageToResponsesInput(message);\n * // Returns: [{ type: \"message\", role: \"user\", content: [{ type: \"input_text\", text: \"Hello, how are you?\" }] }]\n * ```\n *\n * @example\n * AI message with tool calls:\n * ```typescript\n * const message = new AIMessage({\n * content: \"I'll check the weather for you.\",\n * tool_calls: [{\n * id: \"call_123\",\n * name: \"get_weather\",\n * args: { location: \"San Francisco\" }\n * }]\n * });\n * const items = convertStandardContentMessageToResponsesInput(message);\n * // Returns:\n * // [\n * // { type: \"message\", role: \"assistant\", content: [{ type: \"input_text\", text: \"I'll check the weather for you.\" }] },\n * // { type: \"function_call\", call_id: \"call_123\", name: \"get_weather\", arguments: '{\"location\":\"San Francisco\"}' }\n * // ]\n * ```\n */\nexport const convertStandardContentMessageToResponsesInput: Converter<\n BaseMessage,\n OpenAIClient.Responses.ResponseInputItem[]\n> = (message) => {\n const isResponsesMessage =\n AIMessage.isInstance(message) &&\n message.response_metadata?.model_provider === \"openai\";\n\n function* iterateItems(): Generator<OpenAIClient.Responses.ResponseInputItem> {\n const messageRole = iife(() => {\n try {\n const role = messageToOpenAIRole(message);\n if (\n role === \"system\" ||\n role === \"developer\" ||\n role === \"assistant\" ||\n role === \"user\"\n ) {\n return role;\n }\n return \"assistant\";\n } catch {\n return \"assistant\";\n }\n });\n\n // Text parts must match the message role: assistant content uses\n // `output_text` (the Responses API rejects `input_text` for assistant\n // messages), every other role uses `input_text`.\n const makeTextPart = (\n text: string\n ): ResponseInputMessageContentList[number] =>\n (messageRole === \"assistant\"\n ? { type: \"output_text\", text, annotations: [] }\n : {\n type: \"input_text\",\n text,\n }) as unknown as ResponseInputMessageContentList[number];\n\n let currentMessage: OpenAIClient.Responses.EasyInputMessage | undefined =\n undefined;\n\n const functionCallIdsWithBlocks = new Set<string>();\n const serverFunctionCallIdsWithBlocks = new Set<string>();\n\n const pendingFunctionChunks = new Map<\n string,\n { name?: string; args: string[] }\n >();\n const pendingServerFunctionChunks = new Map<\n string,\n { name?: string; args: string[] }\n >();\n\n function* flushMessage() {\n if (!currentMessage) return;\n const content = currentMessage.content;\n if (\n (typeof content === \"string\" && content.length > 0) ||\n (Array.isArray(content) && content.length > 0)\n ) {\n yield currentMessage;\n }\n currentMessage = undefined;\n }\n\n const pushMessageContent = (\n content: OpenAIClient.Responses.ResponseInputMessageContentList,\n phase?: OpenAIClient.Responses.EasyInputMessage[\"phase\"]\n ) => {\n if (!currentMessage) {\n currentMessage = {\n type: \"message\",\n role: messageRole,\n content: [],\n ...(phase ? { phase } : {}),\n };\n }\n if (typeof currentMessage.content === \"string\") {\n currentMessage.content =\n currentMessage.content.length > 0\n ? [makeTextPart(currentMessage.content), ...content]\n : [...content];\n } else {\n currentMessage.content.push(...content);\n }\n };\n\n const toJsonString = (value: unknown) => {\n if (typeof value === \"string\") {\n return value;\n }\n try {\n return JSON.stringify(value ?? {});\n } catch {\n return \"{}\";\n }\n };\n\n const resolveImageItem = (\n block: ContentBlock.Multimodal.Image\n ): OpenAIClient.Responses.ResponseInputImage | undefined => {\n const detail = iife(() => {\n const raw = block.metadata?.detail;\n if (raw === \"low\" || raw === \"high\" || raw === \"auto\") {\n return raw;\n }\n return \"auto\";\n });\n if (block.fileId) {\n return {\n type: \"input_image\",\n detail,\n file_id: block.fileId,\n };\n }\n if (block.url) {\n return {\n type: \"input_image\",\n detail,\n image_url: block.url,\n };\n }\n if (block.data) {\n const base64Data =\n typeof block.data === \"string\"\n ? block.data\n : Buffer.from(block.data).toString(\"base64\");\n const mimeType = block.mimeType ?? \"image/png\";\n return {\n type: \"input_image\",\n detail,\n image_url: `data:${mimeType};base64,${base64Data}`,\n };\n }\n return undefined;\n };\n\n const resolveFileItem = (\n block: ContentBlock.Multimodal.File | ContentBlock.Multimodal.Video\n ): OpenAIClient.Responses.ResponseInputFile | undefined => {\n if (block.fileId) {\n const filename = getFilenameFromMetadata(block);\n return {\n type: \"input_file\",\n file_id: block.fileId,\n ...(filename ? { filename } : {}),\n };\n }\n if (block.url) {\n const filename = getFilenameFromMetadata(block);\n return {\n ...(filename ? { filename } : {}),\n type: \"input_file\",\n file_url: block.url,\n };\n }\n if (block.data) {\n const filename = getRequiredFilenameFromMetadata(block);\n const encoded =\n typeof block.data === \"string\"\n ? block.data\n : Buffer.from(block.data).toString(\"base64\");\n const mimeType = block.mimeType ?? \"application/octet-stream\";\n return {\n type: \"input_file\",\n file_data: `data:${mimeType};base64,${encoded}`,\n filename,\n };\n }\n return undefined;\n };\n\n const convertReasoningBlock = (\n block: ContentBlock.Reasoning\n ): OpenAIClient.Responses.ResponseReasoningItem => {\n const summaryEntries = iife(() => {\n if (Array.isArray(block.summary)) {\n const candidate = block.summary;\n const mapped =\n candidate\n ?.map((item) => item?.text)\n .filter((text): text is string => typeof text === \"string\") ?? [];\n if (mapped.length > 0) {\n return mapped;\n }\n }\n return block.reasoning ? [block.reasoning] : [];\n });\n\n const summary =\n summaryEntries.length > 0\n ? summaryEntries.map((text) => ({\n type: \"summary_text\" as const,\n text,\n }))\n : [{ type: \"summary_text\" as const, text: \"\" }];\n\n // Only include `id` when we actually have one. Reasoning blocks\n // reassembled from streaming chunks (e.g. via `streamEvents`) never\n // carry an id, since OpenAI's streaming protocol omits it. Emitting\n // `id: \"\"` makes the Responses API reject the turn with\n // `400 Invalid 'input[n].id': ''`, so we omit the field instead — the\n // same way the legacy reconstruction path leaves a missing id off.\n // Reasoning input items only carry `summary` — the Responses API rejects\n // a populated `content` array on input (`400 Invalid 'input[n].content':\n // array too long. Expected an array with maximum length 0`). The reasoning\n // text is already represented in `summary`, so we do not forward `content`.\n return {\n type: \"reasoning\",\n ...(block.id ? { id: block.id } : {}),\n summary,\n } as OpenAIClient.Responses.ResponseReasoningItem;\n };\n\n const convertFunctionCall = (\n block: ContentBlock.Tools.ToolCall | ContentBlock.Tools.ServerToolCall\n ): OpenAIClient.Responses.ResponseFunctionToolCall => ({\n type: \"function_call\",\n name: block.name ?? \"\",\n call_id: block.id ?? \"\",\n arguments: toJsonString(block.args),\n });\n\n const convertFunctionCallOutput = (\n block: ContentBlock.Tools.ServerToolCallResult\n ): OpenAIClient.Responses.ResponseInputItem.FunctionCallOutput => {\n const output = toJsonString(block.output);\n const status =\n block.status === \"success\"\n ? \"completed\"\n : block.status === \"error\"\n ? \"incomplete\"\n : undefined;\n return {\n type: \"function_call_output\",\n call_id: block.toolCallId ?? \"\",\n output,\n ...(status ? { status } : {}),\n };\n };\n\n for (const block of message.contentBlocks) {\n if (block.type === \"text\") {\n const phase = iife(() => {\n if (\n !(\n \"extras\" in block &&\n typeof block.extras === \"object\" &&\n block.extras !== null &&\n \"phase\" in block.extras\n )\n )\n return undefined;\n return block.extras\n .phase as OpenAIClient.Responses.EasyInputMessage[\"phase\"];\n });\n pushMessageContent([makeTextPart(block.text)], phase);\n } else if (block.type === \"invalid_tool_call\") {\n // no-op\n } else if (block.type === \"reasoning\") {\n yield* flushMessage();\n yield convertReasoningBlock(\n block as ContentBlock.Standard & { type: \"reasoning\" }\n );\n } else if (block.type === \"tool_call\") {\n yield* flushMessage();\n const id = block.id ?? \"\";\n if (id) {\n functionCallIdsWithBlocks.add(id);\n pendingFunctionChunks.delete(id);\n }\n yield convertFunctionCall(\n block as ContentBlock.Standard & { type: \"tool_call\" }\n );\n } else if (block.type === \"tool_call_chunk\") {\n if (block.id) {\n const existing = pendingFunctionChunks.get(block.id) ?? {\n name: block.name,\n args: [],\n };\n if (block.name) existing.name = block.name;\n if (block.args) existing.args.push(block.args);\n pendingFunctionChunks.set(block.id, existing);\n }\n } else if (block.type === \"server_tool_call\") {\n yield* flushMessage();\n const id = block.id ?? \"\";\n if (id) {\n serverFunctionCallIdsWithBlocks.add(id);\n pendingServerFunctionChunks.delete(id);\n }\n yield convertFunctionCall(block);\n } else if (block.type === \"server_tool_call_chunk\") {\n if (block.id) {\n const existing = pendingServerFunctionChunks.get(block.id) ?? {\n name: block.name,\n args: [],\n };\n if (block.name) existing.name = block.name;\n if (block.args) existing.args.push(block.args);\n pendingServerFunctionChunks.set(block.id, existing);\n }\n } else if (block.type === \"server_tool_call_result\") {\n yield* flushMessage();\n yield convertFunctionCallOutput(block);\n } else if (block.type === \"audio\") {\n // no-op\n } else if (block.type === \"file\") {\n const fileItem = resolveFileItem(block);\n if (fileItem) {\n pushMessageContent([fileItem]);\n }\n } else if (block.type === \"image\") {\n const imageItem = resolveImageItem(block);\n if (imageItem) {\n pushMessageContent([imageItem]);\n }\n } else if (block.type === \"video\") {\n const videoItem = resolveFileItem(block);\n if (videoItem) {\n pushMessageContent([videoItem]);\n }\n } else if (block.type === \"text-plain\") {\n if (block.text) {\n pushMessageContent([makeTextPart(block.text)]);\n }\n } else if (block.type === \"non_standard\" && isResponsesMessage) {\n yield* flushMessage();\n yield block.value as ResponsesInputItem;\n }\n }\n yield* flushMessage();\n\n for (const [id, chunk] of pendingFunctionChunks) {\n if (!id || functionCallIdsWithBlocks.has(id)) continue;\n const args = chunk.args.join(\"\");\n if (!chunk.name && !args) continue;\n yield {\n type: \"function_call\",\n call_id: id,\n name: chunk.name ?? \"\",\n arguments: args,\n };\n }\n\n for (const [id, chunk] of pendingServerFunctionChunks) {\n if (!id || serverFunctionCallIdsWithBlocks.has(id)) continue;\n const args = chunk.args.join(\"\");\n if (!chunk.name && !args) continue;\n yield {\n type: \"function_call\",\n call_id: id,\n name: chunk.name ?? \"\",\n arguments: args,\n };\n }\n }\n return Array.from(iterateItems());\n};\n\n/**\n * - MCP (Model Context Protocol) approval responses\n * - Zero Data Retention (ZDR) mode handling\n *\n * @param params - Conversion parameters\n * @param params.messages - Array of LangChain BaseMessages to convert\n * @param params.zdrEnabled - Whether Zero Data Retention mode is enabled. When true, certain\n * metadata like message IDs and function call IDs are omitted from the output\n * @param params.model - The model name being used. Used to determine if special role mapping\n * is needed (e.g., \"system\" -> \"developer\" for reasoning models)\n *\n * @returns Array of ResponsesInputItem objects formatted for the OpenAI Responses API\n *\n * @throws {Error} When a function message is encountered (not supported)\n * @throws {Error} When computer call output format is invalid\n *\n * @example\n * ```typescript\n * const messages = [\n * new HumanMessage(\"Hello\"),\n * new AIMessage({ content: \"Hi there!\", tool_calls: [...] })\n * ];\n *\n * const input = convertMessagesToResponsesInput({\n * messages,\n * zdrEnabled: false,\n * model: \"gpt-4\"\n * });\n * ```\n */\nexport const convertMessagesToResponsesInput: Converter<\n { messages: BaseMessage[]; zdrEnabled: boolean; model: string },\n ResponsesInputItem[]\n> = ({ messages, zdrEnabled, model }) => {\n return messages.flatMap(\n (lcMsg): ResponsesInputItem | ResponsesInputItem[] => {\n const responseMetadata = lcMsg.response_metadata as\n | Record<string, unknown>\n | undefined;\n if (responseMetadata?.output_version === \"v1\") {\n return convertStandardContentMessageToResponsesInput(lcMsg);\n }\n\n const additional_kwargs =\n lcMsg.additional_kwargs as BaseMessageFields[\"additional_kwargs\"] & {\n [_FUNCTION_CALL_IDS_MAP_KEY]?: Record<string, string>;\n reasoning?: OpenAIClient.Responses.ResponseReasoningItem;\n type?: string;\n refusal?: string;\n };\n\n let role = messageToOpenAIRole(lcMsg);\n if (role === \"system\" && isReasoningModel(model)) role = \"developer\";\n\n if (role === \"function\") {\n throw new Error(\"Function messages are not supported in Responses API\");\n }\n\n if (role === \"tool\") {\n const toolMessage = lcMsg as ToolMessage;\n\n // Handle computer call output\n if (additional_kwargs?.type === \"computer_call_output\") {\n const output = (() => {\n if (typeof toolMessage.content === \"string\") {\n return {\n type: \"input_image\" as const,\n image_url: toolMessage.content,\n };\n }\n\n if (Array.isArray(toolMessage.content)) {\n /**\n * Check for input_image type first (computer-use-preview format)\n */\n const inputImage = toolMessage.content.find(\n (i) => i.type === \"input_image\"\n ) as { type: \"input_image\"; image_url: string } | undefined;\n\n if (inputImage) return inputImage;\n\n /**\n * Check for computer_screenshot type (legacy format)\n */\n const oaiScreenshot = toolMessage.content.find(\n (i) => i.type === \"computer_screenshot\"\n ) as\n | { type: \"computer_screenshot\"; image_url: string }\n | undefined;\n\n if (oaiScreenshot) return oaiScreenshot;\n\n /**\n * Convert image_url content block to input_image format\n */\n const lcImage = toolMessage.content.find(\n (i) => i.type === \"image_url\"\n ) as MessageContentImageUrl;\n\n if (lcImage) {\n return {\n type: \"input_image\" as const,\n image_url:\n typeof lcImage.image_url === \"string\"\n ? lcImage.image_url\n : lcImage.image_url.url,\n };\n }\n }\n\n throw new Error(\"Invalid computer call output\");\n })();\n\n /**\n * Cast needed because OpenAI SDK types don't yet include input_image\n * for computer-use-preview model output format\n */\n return {\n type: \"computer_call_output\",\n output,\n call_id: toolMessage.tool_call_id,\n } as ResponsesInputItem;\n }\n\n // Handle custom tool output\n if (toolMessage.additional_kwargs?.customTool) {\n return {\n type: \"custom_tool_call_output\",\n call_id: toolMessage.tool_call_id,\n output: toolMessage.content as string,\n };\n }\n\n // Check if content contains provider-native OpenAI content blocks\n // that should be passed through without stringification\n const isProviderNativeContent =\n Array.isArray(toolMessage.content) &&\n toolMessage.content.every(\n (item) =>\n typeof item === \"object\" &&\n item !== null &&\n \"type\" in item &&\n (item.type === \"input_file\" ||\n item.type === \"input_image\" ||\n item.type === \"input_text\")\n );\n\n return {\n type: \"function_call_output\",\n call_id: toolMessage.tool_call_id,\n id: toolMessage.id?.startsWith(\"fc_\") ? toolMessage.id : undefined,\n output: isProviderNativeContent\n ? (toolMessage.content as OpenAIClient.Responses.ResponseFunctionCallOutputItemList)\n : typeof toolMessage.content !== \"string\"\n ? JSON.stringify(toolMessage.content)\n : toolMessage.content,\n };\n }\n\n if (role === \"assistant\") {\n // if we have the original response items, just reuse them\n if (\n !zdrEnabled &&\n responseMetadata?.output != null &&\n Array.isArray(responseMetadata?.output) &&\n responseMetadata?.output.length > 0 &&\n responseMetadata?.output.every((item) => \"type\" in item)\n ) {\n return responseMetadata?.output;\n }\n\n // otherwise, try to reconstruct the response from what we have\n\n const input: ResponsesInputItem[] = [];\n\n // reasoning items\n const reasoning = additional_kwargs?.reasoning;\n const hasEncryptedContent = !!reasoning?.encrypted_content;\n /**\n * With ZDR enabled, OpenAI does not retain reasoning items, so we only send\n * them when encrypted content is available (via include: [\"reasoning.encrypted_content\"]).\n * With ZDR disabled, we include reasoning item ids so OpenAI can reference them, as it's storing them.\n */\n if (reasoning && (!zdrEnabled || hasEncryptedContent)) {\n const reasoningItem =\n convertReasoningSummaryToResponsesReasoningItem(reasoning);\n input.push(reasoningItem);\n }\n\n // ai content\n let { content } = lcMsg;\n if (additional_kwargs?.refusal) {\n if (typeof content === \"string\") {\n content = [{ type: \"output_text\", text: content, annotations: [] }];\n }\n content = [\n ...(content as ContentBlock[]),\n { type: \"refusal\", refusal: additional_kwargs.refusal },\n ];\n }\n\n if (typeof content === \"string\" || content.length > 0) {\n const messageItem: ResponsesInputItem = {\n type: \"message\",\n role: \"assistant\",\n ...(lcMsg.id && !zdrEnabled && lcMsg.id.startsWith(\"msg_\")\n ? { id: lcMsg.id }\n : {}),\n content: iife(() => {\n if (typeof content === \"string\") {\n return content;\n }\n return content.flatMap((item) => {\n if (item.type === \"text\") {\n const textItem = item as ContentBlock.Text;\n return {\n type: \"output_text\",\n text: textItem.text,\n annotations: (textItem.annotations ?? []).map(\n convertLangChainAnnotationToOpenAI\n ),\n };\n }\n\n if (item.type === \"output_text\" || item.type === \"refusal\") {\n return item;\n }\n\n return [];\n });\n }) as ResponseInputMessageContentList,\n phase: iife(() => {\n if (!Array.isArray(content)) {\n return undefined;\n }\n\n const phasedContent = content.find(\n (item): item is ContentBlock & { phase: string } =>\n \"phase\" in item && typeof item.phase === \"string\"\n );\n return phasedContent?.phase as\n | OpenAIClient.Responses.EasyInputMessage[\"phase\"]\n | undefined;\n }),\n };\n input.push(messageItem);\n }\n\n const functionCallIds = additional_kwargs?.[_FUNCTION_CALL_IDS_MAP_KEY];\n const customToolCallIds =\n additional_kwargs?.[_CUSTOM_TOOL_CALL_IDS_MAP_KEY];\n\n if (AIMessage.isInstance(lcMsg) && !!lcMsg.tool_calls?.length) {\n input.push(\n ...lcMsg.tool_calls.map((toolCall): ResponsesInputItem => {\n if (isCustomToolCall(toolCall, customToolCallIds)) {\n return {\n type: \"custom_tool_call\",\n id:\n \"call_id\" in toolCall &&\n typeof toolCall.call_id === \"string\"\n ? toolCall.call_id\n : (customToolCallIds?.[toolCall.id ?? \"\"] ?? \"\"),\n call_id: toolCall.id ?? \"\",\n input: toolCall.args.input,\n name: toolCall.name,\n };\n }\n if (isComputerToolCall(toolCall)) {\n return {\n type: \"computer_call\",\n id: toolCall.call_id,\n call_id: toolCall.id ?? \"\",\n action: toolCall.args.action,\n } as ResponsesInputItem;\n }\n return {\n type: \"function_call\",\n name: toolCall.name,\n arguments: JSON.stringify(toolCall.args),\n call_id: toolCall.id!,\n ...(!zdrEnabled ? { id: functionCallIds?.[toolCall.id!] } : {}),\n };\n })\n );\n } else if (additional_kwargs?.tool_calls) {\n input.push(\n ...additional_kwargs.tool_calls.map(\n (toolCall): ResponsesInputItem => ({\n type: \"function_call\",\n name: toolCall.function.name,\n call_id: toolCall.id,\n arguments: toolCall.function.arguments,\n ...(!zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {}),\n })\n )\n );\n }\n\n const toolOutputs = (\n responseMetadata?.output as Array<ResponsesInputItem>\n )?.length\n ? responseMetadata?.output\n : additional_kwargs.tool_outputs;\n\n const fallthroughCallTypes: ResponsesInputItem[\"type\"][] = [\n \"computer_call\",\n \"mcp_call\",\n \"code_interpreter_call\",\n \"image_generation_call\",\n \"shell_call\",\n \"local_shell_call\",\n ];\n\n if (toolOutputs != null) {\n const castToolOutputs = toolOutputs as Array<ResponsesInputItem>;\n const fallthroughCalls = castToolOutputs?.filter((item) =>\n fallthroughCallTypes.includes(item.type)\n );\n if (fallthroughCalls.length > 0) input.push(...fallthroughCalls);\n }\n\n return input;\n }\n\n if (role === \"user\" || role === \"system\" || role === \"developer\") {\n if (typeof lcMsg.content === \"string\") {\n return { type: \"message\", role, content: lcMsg.content };\n }\n\n const messages: ResponsesInputItem[] = [];\n const content = (lcMsg.content as ContentBlock[]).flatMap((item) => {\n if (item.type === \"mcp_approval_response\") {\n messages.push({\n type: \"mcp_approval_response\",\n approval_request_id: item.approval_request_id as string,\n approve: item.approve as boolean,\n });\n }\n if (isDataContentBlock(item)) {\n // The Responses API supports file URLs natively, but the Chat\n // Completions converter rejects URL file blocks. Convert standard\n // file blocks to the native `input_file` shape instead of routing\n // them through the completions converter.\n if (item.type === \"file\") {\n const filename = getFilenameFromMetadata(item);\n if (item.source_type === \"url\") {\n return {\n type: \"input_file\",\n file_url: item.url,\n ...(filename ? { filename } : {}),\n };\n }\n if (item.source_type === \"id\") {\n return {\n type: \"input_file\",\n file_id: item.id,\n ...(filename ? { filename } : {}),\n };\n }\n if (item.source_type === \"base64\") {\n const mimeType = item.mime_type ?? \"\";\n return {\n type: \"input_file\",\n file_data: `data:${mimeType};base64,${item.data}`,\n filename: getRequiredFilenameFromMetadata(item),\n };\n }\n }\n return convertToProviderContentBlock(\n item,\n completionsApiContentBlockConverter\n );\n }\n if (item.type === \"text\") {\n return {\n type: \"input_text\",\n text: item.text,\n };\n }\n if (item.type === \"image_url\") {\n const imageUrl = iife(() => {\n if (typeof item.image_url === \"string\") {\n return item.image_url;\n } else if (\n typeof item.image_url === \"object\" &&\n item.image_url !== null &&\n \"url\" in item.image_url\n ) {\n return item.image_url.url;\n }\n return undefined;\n });\n const detail = iife(() => {\n if (typeof item.image_url === \"string\") {\n return \"auto\";\n } else if (\n typeof item.image_url === \"object\" &&\n item.image_url !== null &&\n \"detail\" in item.image_url\n ) {\n return item.image_url.detail;\n }\n return undefined;\n });\n return {\n type: \"input_image\",\n image_url: imageUrl,\n detail,\n };\n }\n if (\n item.type === \"input_text\" ||\n item.type === \"input_image\" ||\n item.type === \"input_file\"\n ) {\n return item;\n }\n return [];\n });\n\n if (content.length > 0) {\n messages.push({\n type: \"message\",\n role,\n content: content as ResponseInputMessageContentList,\n });\n }\n return messages;\n }\n\n console.warn(\n `Unsupported role found when converting to OpenAI Responses API: ${role}`\n );\n return [];\n }\n );\n};\n"],"mappings":";;;;;;;AA0CA,MAAM,6BAA6B;AACnC,MAAM,gCAAgC;;;;;;;;;;;;AAmBtC,SAAS,mCACP,YACkD;AAClD,KAAI,WAAW,SAAS,eACtB,QAAO;EACL,MAAM;EACN,QAAQ;EACR,KAAK,WAAW;EAChB,OAAO,WAAW;EAClB,YAAY,WAAW;EACvB,UAAU,WAAW;EACtB;AAGH,KAAI,WAAW,SAAS,gBACtB,QAAO;EACL,MAAM;EACN,QAAQ;EACR,OAAO,WAAW;EAClB,YAAY,WAAW;EAEvB,SAAS,WAAW;EACrB;AAGH,KAAI,WAAW,SAAS,0BACtB,QAAO;EACL,MAAM;EACN,QAAQ;EACR,OAAO,WAAW;EAClB,YAAY,WAAW;EACvB,UAAU,WAAW;EAErB,SAAS,WAAW;EACpB,cAAc,WAAW;EAC1B;A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B,QAAO;OACL,MAAM;OACN,UAAU,KAAK;OACf,GAAI,WAAW,EAAE,UAAU,GAAG,EAAE;OACjC;AAEH,UAAI,KAAK,gBAAgB,KACvB,QAAO;OACL,MAAM;OACN,SAAS,KAAK;OACd,GAAI,WAAW,EAAE,UAAU,GAAG,EAAE;OACjC;AAEH,UAAI,KAAK,gBAAgB,SAEvB,QAAO;OACL,MAAM;OACN,WAAW,QAHI,KAAK,aAAa,GAGL,UAAU,KAAK;OAC3C,UAAU,gCAAgC,KAAK;OAChD;;AAGL,YAAO,8BACL,MACA,oCACD;;AAEH,QAAI,KAAK,SAAS,OAChB,QAAO;KACL,MAAM;KACN,MAAM,KAAK;KACZ;AAEH,QAAI,KAAK,SAAS,YAyBhB,QAAO;KACL,MAAM;KACN,WA1BeD,aAAW;AAC1B,UAAI,OAAO,KAAK,cAAc,SAC5B,QAAO,KAAK;eAEZ,OAAO,KAAK,cAAc,YAC1B,KAAK,cAAc,QACnB,SAAS,KAAK,UAEd,QAAO,KAAK,UAAU;OAkBL;KACnB,QAfaA,aAAW;AACxB,UAAI,OAAO,KAAK,cAAc,SAC5B,QAAO;eAEP,OAAO,KAAK,cAAc,YAC1B,KAAK,cAAc,QACnB,YAAY,KAAK,UAEjB,QAAO,KAAK,UAAU;OAOlB;KACP;AAEH,QACE,KAAK,SAAS,gBACd,KAAK,SAAS,iBACd,KAAK,SAAS,aAEd,QAAO;AAET,WAAO,EAAE;KACT;AAEF,OAAI,QAAQ,SAAS,EACnB,UAAS,KAAK;IACZ,MAAM;IACN;IACS;IACV,CAAC;AAEJ,UAAO;;AAGT,UAAQ,KACN,mEAAmE,OACpE;AACD,SAAO,EAAE;GAEZ"}
|
|
1
|
+
{"version":3,"file":"responses.js","names":["iife","castToolOutputs"],"sources":["../../src/converters/responses.ts"],"sourcesContent":["import { OpenAI as OpenAIClient } from \"openai\";\nimport {\n AIMessage,\n AIMessageChunk,\n type BaseMessage,\n type UsageMetadata,\n type BaseMessageFields,\n type MessageContent,\n type InvalidToolCall,\n MessageContentImageUrl,\n isDataContentBlock,\n convertToProviderContentBlock,\n ContentBlock,\n} from \"@langchain/core/messages\";\nimport { ChatGenerationChunk } from \"@langchain/core/outputs\";\nimport {\n makeInvalidToolCall,\n parseToolCall,\n} from \"@langchain/core/output_parsers/openai_tools\";\nimport type {\n ToolCall,\n ToolCallChunk,\n ToolMessage,\n} from \"@langchain/core/messages/tool\";\nimport { ResponseInputMessageContentList } from \"openai/resources/responses/responses.js\";\nimport { ChatOpenAIReasoningSummary } from \"../types.js\";\nimport {\n isComputerToolCall,\n isCustomToolCall,\n parseComputerCall,\n parseCustomToolCall,\n} from \"../utils/tools.js\";\nimport {\n getFilenameFromMetadata,\n getRequiredFilenameFromMetadata,\n iife,\n isReasoningModel,\n messageToOpenAIRole,\n} from \"../utils/misc.js\";\nimport { Converter } from \"@langchain/core/utils/format\";\nimport { completionsApiContentBlockConverter } from \"./completions.js\";\n\nconst _FUNCTION_CALL_IDS_MAP_KEY = \"__openai_function_call_ids__\";\nconst _CUSTOM_TOOL_CALL_IDS_MAP_KEY = \"__openai_custom_tool_call_ids__\";\n\n/** Streaming-only marker; not part of @langchain/core ToolCallChunk. */\ntype OpenAICustomToolCallChunk = ToolCallChunk & { isCustomTool?: true };\n\ntype OpenAIAnnotation =\n OpenAIClient.Responses.ResponseOutputText[\"annotations\"][number];\n\n/**\n * Converts an OpenAI annotation to a LangChain Citation or BaseContentBlock.\n *\n * OpenAI has several annotation types:\n * - `url_citation`: Web citations with url, title, start_index, end_index\n * - `file_citation`: File citations with file_id, filename, index\n * - `container_file_citation`: Container file citations with container_id, file_id, filename, start_index, end_index\n * - `file_path`: File paths with file_id, index\n *\n * This function maps them to LangChain's Citation format or preserves them as non-standard blocks.\n */\nfunction convertOpenAIAnnotationToLangChain(\n annotation: OpenAIAnnotation\n): ContentBlock.Citation | ContentBlock.NonStandard {\n if (annotation.type === \"url_citation\") {\n return {\n type: \"citation\",\n source: \"url_citation\",\n url: annotation.url,\n title: annotation.title,\n startIndex: annotation.start_index,\n endIndex: annotation.end_index,\n } satisfies ContentBlock.Citation;\n }\n\n if (annotation.type === \"file_citation\") {\n return {\n type: \"citation\",\n source: \"file_citation\",\n title: annotation.filename,\n startIndex: annotation.index,\n // Store file_id in a way that can be retrieved\n file_id: annotation.file_id,\n } as ContentBlock.Citation;\n }\n\n if (annotation.type === \"container_file_citation\") {\n return {\n type: \"citation\",\n source: \"container_file_citation\",\n title: annotation.filename,\n startIndex: annotation.start_index,\n endIndex: annotation.end_index,\n // Store additional IDs\n file_id: annotation.file_id,\n container_id: annotation.container_id,\n } as ContentBlock.Citation;\n }\n\n if (annotation.type === \"file_path\") {\n return {\n type: \"citation\",\n source: \"file_path\",\n startIndex: annotation.index,\n file_id: annotation.file_id,\n } as ContentBlock.Citation;\n }\n\n // For unknown annotation types, preserve them as non-standard blocks\n return {\n type: \"non_standard\",\n value: annotation as unknown as Record<string, unknown>,\n } satisfies ContentBlock.NonStandard;\n}\n\n/**\n * Converts a LangChain Citation or BaseContentBlock back to an OpenAI annotation.\n *\n * This is the inverse of `convertOpenAIAnnotationToLangChain`. It handles all four\n * annotation types (url_citation, file_citation, container_file_citation, file_path)\n * and also passes through annotations that are already in OpenAI format.\n */\nfunction convertLangChainAnnotationToOpenAI(\n annotation:\n | ContentBlock.Citation\n | ContentBlock.NonStandard\n | Record<string, unknown>\n): OpenAIAnnotation {\n // If it's already in OpenAI format, pass through unchanged\n if (\n annotation.type === \"url_citation\" ||\n annotation.type === \"file_citation\" ||\n annotation.type === \"container_file_citation\" ||\n annotation.type === \"file_path\"\n ) {\n return annotation as unknown as OpenAIAnnotation;\n }\n\n // Convert from LangChain citation format back to OpenAI format\n if (annotation.type === \"citation\") {\n const citation = annotation as ContentBlock.Citation & {\n file_id?: string;\n container_id?: string;\n };\n\n if (citation.source === \"url_citation\") {\n return {\n type: \"url_citation\",\n url: citation.url ?? \"\",\n title: citation.title ?? \"\",\n start_index: citation.startIndex ?? 0,\n end_index: citation.endIndex ?? 0,\n } as OpenAIAnnotation;\n }\n\n if (citation.source === \"file_citation\") {\n return {\n type: \"file_citation\",\n file_id: citation.file_id ?? \"\",\n filename: citation.title ?? \"\",\n index: citation.startIndex ?? 0,\n } as OpenAIAnnotation;\n }\n\n if (citation.source === \"container_file_citation\") {\n return {\n type: \"container_file_citation\",\n file_id: citation.file_id ?? \"\",\n filename: citation.title ?? \"\",\n container_id: citation.container_id ?? \"\",\n start_index: citation.startIndex ?? 0,\n end_index: citation.endIndex ?? 0,\n } as OpenAIAnnotation;\n }\n\n if (citation.source === \"file_path\") {\n return {\n type: \"file_path\",\n file_id: citation.file_id ?? \"\",\n index: citation.startIndex ?? 0,\n } as OpenAIAnnotation;\n }\n }\n\n // For non_standard blocks, unwrap the value\n if (annotation.type === \"non_standard\") {\n return (annotation as ContentBlock.NonStandard)\n .value as unknown as OpenAIAnnotation;\n }\n\n // Unknown format, pass through as-is\n return annotation as unknown as OpenAIAnnotation;\n}\n\ntype ExcludeController<T> = T extends { controller: unknown } ? never : T;\n\nexport type ResponsesCreate = OpenAIClient.Responses[\"create\"];\nexport type ResponsesParse = OpenAIClient.Responses[\"parse\"];\n\nexport type ResponsesCreateInvoke = ExcludeController<\n Awaited<ReturnType<ResponsesCreate>>\n>;\nexport type ResponsesParseInvoke = ExcludeController<\n Awaited<ReturnType<ResponsesParse>>\n>;\n\nexport type ResponsesInputItem = OpenAIClient.Responses.ResponseInputItem;\n\n/**\n * Converts OpenAI Responses API usage statistics to LangChain's UsageMetadata format.\n *\n * This converter transforms token usage information from OpenAI's Responses API into\n * the standardized UsageMetadata format used throughout LangChain. It handles both\n * basic token counts and detailed token breakdowns including cached tokens and\n * reasoning tokens.\n *\n * @param usage - The usage statistics object from OpenAI's Responses API containing\n * token counts and optional detailed breakdowns.\n *\n * @returns A UsageMetadata object containing:\n * - `input_tokens`: Total number of tokens in the input/prompt (defaults to 0 if not provided)\n * - `output_tokens`: Total number of tokens in the model's output (defaults to 0 if not provided)\n * - `total_tokens`: Combined total of input and output tokens (defaults to 0 if not provided)\n * - `input_token_details`: Object containing detailed input token information:\n * - `cache_read`: Number of tokens read from cache (only included if available)\n * - `output_token_details`: Object containing detailed output token information:\n * - `reasoning`: Number of tokens used for reasoning (only included if available)\n *\n * @example\n * ```typescript\n * const usage = {\n * input_tokens: 100,\n * output_tokens: 50,\n * total_tokens: 150,\n * input_tokens_details: { cached_tokens: 20 },\n * output_tokens_details: { reasoning_tokens: 10 }\n * };\n *\n * const metadata = convertResponsesUsageToUsageMetadata(usage);\n * // Returns:\n * // {\n * // input_tokens: 100,\n * // output_tokens: 50,\n * // total_tokens: 150,\n * // input_token_details: { cache_read: 20 },\n * // output_token_details: { reasoning: 10 }\n * // }\n * ```\n *\n * @remarks\n * - The function safely handles undefined or null values by using optional chaining\n * and nullish coalescing operators\n * - Detailed token information (cache_read, reasoning) is only included in the result\n * if the corresponding values are present in the input\n * - Token counts default to 0 if not provided in the usage object\n * - This converter is specifically designed for OpenAI's Responses API format and\n * may differ from other OpenAI API endpoints\n */\nexport const convertResponsesUsageToUsageMetadata: Converter<\n OpenAIClient.Responses.ResponseUsage | undefined,\n UsageMetadata\n> = (usage) => {\n const inputTokenDetails = {\n ...(usage?.input_tokens_details?.cached_tokens != null && {\n cache_read: usage?.input_tokens_details?.cached_tokens,\n }),\n };\n const outputTokenDetails = {\n ...(usage?.output_tokens_details?.reasoning_tokens != null && {\n reasoning: usage?.output_tokens_details?.reasoning_tokens,\n }),\n };\n return {\n input_tokens: usage?.input_tokens ?? 0,\n output_tokens: usage?.output_tokens ?? 0,\n total_tokens: usage?.total_tokens ?? 0,\n input_token_details: inputTokenDetails,\n output_token_details: outputTokenDetails,\n };\n};\n\n/**\n * Converts an OpenAI Responses API response to a LangChain AIMessage.\n *\n * This converter processes the output from OpenAI's Responses API (both `create` and `parse` methods)\n * and transforms it into a LangChain AIMessage object with all relevant metadata, tool calls, and content.\n *\n * @param response - The response object from OpenAI's Responses API. Can be either:\n * - ResponsesCreateInvoke: Result from `responses.create()`\n * - ResponsesParseInvoke: Result from `responses.parse()`\n *\n * @returns An AIMessage containing:\n * - `id`: The message ID from the response output\n * - `content`: Array of message content blocks (text, images, etc.)\n * - `tool_calls`: Array of successfully parsed tool calls\n * - `invalid_tool_calls`: Array of tool calls that failed to parse\n * - `usage_metadata`: Token usage information converted to LangChain format\n * - `additional_kwargs`: Extra data including:\n * - `refusal`: Refusal text if the model refused to respond\n * - `reasoning`: Reasoning output for reasoning models\n * - `tool_outputs`: Results from built-in tools (web search, file search, etc.)\n * - `parsed`: Parsed structured output when using json_schema format\n * - Function call ID mappings for tracking\n * - `response_metadata`: Metadata about the response including model, timestamps, status, etc.\n *\n * @throws Error if the response contains an error object. The error message and code are extracted\n * from the response.error field.\n *\n * @example\n * ```typescript\n * const response = await client.responses.create({\n * model: \"gpt-4\",\n * input: [{ type: \"message\", content: \"Hello\" }]\n * });\n * const message = convertResponsesMessageToAIMessage(response);\n * console.log(message.content); // Message content\n * console.log(message.tool_calls); // Any tool calls made\n * ```\n *\n * @remarks\n * The converter handles multiple output item types:\n * - `message`: Text and structured content from the model\n * - `function_call`: Tool/function calls that need to be executed\n * - `reasoning`: Reasoning traces from reasoning models (o1, o3, etc.)\n * - `custom_tool_call`: Custom tool invocations\n * - Built-in tool outputs: web_search, file_search, code_interpreter, etc.\n *\n * Tool calls are parsed and validated. Invalid tool calls (malformed JSON, etc.) are captured\n * in the `invalid_tool_calls` array rather than throwing errors.\n */\nexport const convertResponsesMessageToAIMessage: Converter<\n ResponsesCreateInvoke | ResponsesParseInvoke,\n AIMessage\n> = (response) => {\n if (response.error) {\n // TODO: add support for `addLangChainErrorFields`\n const error = new Error(response.error.message);\n error.name = response.error.code;\n throw error;\n }\n\n const content: MessageContent = [];\n const tool_calls: ToolCall[] = [];\n const invalid_tool_calls: InvalidToolCall[] = [];\n // Preserve the raw output items so that convertMessagesToResponsesInput can\n // return them verbatim on the fast path. We strip `parsed_arguments` from\n // function_call items because the OpenAI SDK injects it when using\n // responses.parse(), but the API rejects it when sent back as input.\n const cleanedOutput = response.output.map((item) => {\n if (item.type === \"function_call\" && \"parsed_arguments\" in item) {\n const cleaned = { ...item };\n delete (cleaned as Record<string, unknown>).parsed_arguments;\n return cleaned;\n }\n return item;\n });\n\n const response_metadata: Record<string, unknown> = {\n model_provider: \"openai\",\n model: response.model,\n created_at: response.created_at,\n id: response.id,\n incomplete_details: response.incomplete_details,\n metadata: response.metadata,\n object: response.object,\n output: cleanedOutput,\n status: response.status,\n user: response.user,\n service_tier: response.service_tier,\n // for compatibility with chat completion calls.\n model_name: response.model,\n };\n\n const additional_kwargs: {\n [key: string]: unknown;\n refusal?: string;\n reasoning?: OpenAIClient.Responses.ResponseReasoningItem;\n tool_outputs?: unknown[];\n parsed?: unknown;\n [_FUNCTION_CALL_IDS_MAP_KEY]?: Record<string, string>;\n [_CUSTOM_TOOL_CALL_IDS_MAP_KEY]?: Record<string, string>;\n } = {};\n\n for (const item of response.output) {\n if (item.type === \"message\") {\n content.push(\n ...item.content.flatMap((part) => {\n if (part.type === \"output_text\") {\n if (\"parsed\" in part && part.parsed != null) {\n additional_kwargs.parsed = part.parsed;\n }\n const block: ContentBlock = {\n type: \"text\",\n text: part.text,\n annotations: part.annotations.map(\n convertOpenAIAnnotationToLangChain\n ),\n ...(item.phase !== null ? { phase: item.phase } : {}),\n };\n return block;\n }\n\n if (part.type === \"refusal\") {\n additional_kwargs.refusal = part.refusal;\n return [];\n }\n\n return part;\n })\n );\n } else if (item.type === \"function_call\") {\n const fnAdapter = {\n function: { name: item.name, arguments: item.arguments },\n id: item.call_id,\n };\n\n try {\n tool_calls.push(parseToolCall(fnAdapter, { returnId: true }));\n } catch (e: unknown) {\n let errMessage: string | undefined;\n if (\n typeof e === \"object\" &&\n e != null &&\n \"message\" in e &&\n typeof e.message === \"string\"\n ) {\n errMessage = e.message;\n }\n invalid_tool_calls.push(makeInvalidToolCall(fnAdapter, errMessage));\n }\n\n additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] ??= {};\n if (item.id) {\n additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY][item.call_id] = item.id;\n }\n } else if (item.type === \"reasoning\") {\n additional_kwargs.reasoning = item;\n // Also elevate reasoning to content for UI rendering\n const reasoningText = item.summary\n ?.map((s) => s.text)\n .filter(Boolean)\n .join(\"\");\n if (reasoningText) {\n content.push({\n type: \"reasoning\",\n reasoning: reasoningText,\n });\n }\n } else if (item.type === \"custom_tool_call\") {\n const parsed = parseCustomToolCall(item);\n if (parsed) {\n tool_calls.push(parsed);\n additional_kwargs[_CUSTOM_TOOL_CALL_IDS_MAP_KEY] ??= {};\n if (item.id && item.call_id) {\n additional_kwargs[_CUSTOM_TOOL_CALL_IDS_MAP_KEY][item.call_id] =\n item.id;\n }\n } else {\n invalid_tool_calls.push(\n makeInvalidToolCall(item, \"Malformed custom tool call\")\n );\n }\n } else if (item.type === \"computer_call\") {\n const parsed = parseComputerCall(item);\n if (parsed) {\n tool_calls.push(parsed);\n } else {\n invalid_tool_calls.push(\n makeInvalidToolCall(item, \"Malformed computer call\")\n );\n }\n } else if (item.type === \"image_generation_call\") {\n // Add image as proper content block if result is available\n if (item.result) {\n content.push({\n type: \"image\",\n mimeType: \"image/png\",\n data: item.result,\n id: item.id,\n metadata: {\n status: item.status,\n },\n } satisfies ContentBlock.Multimodal.Image);\n }\n // Also store in tool_outputs for backwards compatibility and multi-turn editing (needs id)\n additional_kwargs.tool_outputs ??= [];\n additional_kwargs.tool_outputs.push(item);\n } else {\n additional_kwargs.tool_outputs ??= [];\n additional_kwargs.tool_outputs.push(item);\n }\n }\n\n return new AIMessage({\n id: response.id,\n content,\n tool_calls,\n invalid_tool_calls,\n usage_metadata: convertResponsesUsageToUsageMetadata(response.usage),\n additional_kwargs,\n response_metadata,\n });\n};\n\n/**\n * Converts a LangChain ChatOpenAI reasoning summary to an OpenAI Responses API reasoning item.\n *\n * This converter transforms reasoning summaries that have been accumulated during streaming\n * (where summary parts may arrive in multiple chunks with the same index) into the final\n * consolidated format expected by OpenAI's Responses API. It combines summary parts that\n * share the same index and removes the index field from the final output.\n *\n * @param reasoning - A ChatOpenAI reasoning summary object containing:\n * - `id`: The reasoning item ID\n * - `type`: The type of reasoning (typically \"reasoning\")\n * - `summary`: Array of summary parts, each with:\n * - `text`: The summary text content\n * - `type`: The summary type (e.g., \"summary_text\")\n * - `index`: The index used to group related summary parts during streaming\n *\n * @returns An OpenAI Responses API ResponseReasoningItem with:\n * - All properties from the input reasoning object\n * - `summary`: Consolidated array of summary objects with:\n * - `text`: Combined text from all parts with the same index\n * - `type`: The summary type\n * - No `index` field (removed after consolidation)\n *\n * @example\n * ```typescript\n * // Input: Reasoning summary with multiple parts at the same index\n * const reasoning = {\n * id: \"reasoning_123\",\n * type: \"reasoning\",\n * summary: [\n * { text: \"First \", type: \"summary_text\", index: 0 },\n * { text: \"part\", type: \"summary_text\", index: 0 },\n * { text: \"Second part\", type: \"summary_text\", index: 1 }\n * ]\n * };\n *\n * const result = convertReasoningSummaryToResponsesReasoningItem(reasoning);\n * // Returns:\n * // {\n * // id: \"reasoning_123\",\n * // type: \"reasoning\",\n * // summary: [\n * // { text: \"First part\", type: \"summary_text\" },\n * // { text: \"Second part\", type: \"summary_text\" }\n * // ]\n * // }\n * ```\n *\n * @remarks\n * - This converter is primarily used when reconstructing complete reasoning items from\n * streaming chunks, where summary parts may arrive incrementally with index markers\n * - Summary parts with the same index are concatenated in the order they appear\n * - If the reasoning summary contains only one part, no reduction is performed\n * - The index field is used internally during streaming to track which summary parts\n * belong together, but is removed from the final output as it's not part of the\n * OpenAI Responses API schema\n * - This is the inverse operation of the streaming accumulation that happens in\n * `convertResponsesDeltaToChatGenerationChunk`\n */\nexport const convertReasoningSummaryToResponsesReasoningItem: Converter<\n ChatOpenAIReasoningSummary,\n OpenAIClient.Responses.ResponseReasoningItem\n> = (reasoning) => {\n // combine summary parts that have the same index and then remove the indexes\n const summary = (\n reasoning.summary.length > 1\n ? reasoning.summary.reduce(\n (acc, curr) => {\n const last = acc[acc.length - 1];\n\n if (last!.index === curr.index) {\n last!.text += curr.text;\n } else {\n acc.push(curr);\n }\n return acc;\n },\n [{ ...reasoning.summary[0] }]\n )\n : reasoning.summary\n ).map((s) =>\n Object.fromEntries(Object.entries(s).filter(([k]) => k !== \"index\"))\n ) as OpenAIClient.Responses.ResponseReasoningItem.Summary[];\n\n return {\n ...reasoning,\n summary,\n } as OpenAIClient.Responses.ResponseReasoningItem;\n};\n\n/**\n * Converts OpenAI Responses API stream events to LangChain ChatGenerationChunk objects.\n *\n * This converter processes streaming events from OpenAI's Responses API and transforms them\n * into LangChain ChatGenerationChunk objects that can be used in streaming chat applications.\n * It handles various event types including text deltas, tool calls, reasoning, and metadata updates.\n *\n * @param event - A streaming event from OpenAI's Responses API\n *\n * @returns A ChatGenerationChunk containing:\n * - `text`: Concatenated text content from all text parts in the event\n * - `message`: An AIMessageChunk with:\n * - `id`: Response ID (set on `response.created` / `response.completed`)\n * - `content`: Array of content blocks (text with optional annotations)\n * - `tool_call_chunks`: Incremental tool call data (name, args, id)\n * - `usage_metadata`: Token usage information (only in completion events)\n * - `additional_kwargs`: Extra data including:\n * - `refusal`: Refusal text if the model refused to respond\n * - `reasoning`: Reasoning output for reasoning models (id, type, summary)\n * - `tool_outputs`: Results from built-in tools (web search, file search, etc.)\n * - `parsed`: Parsed structured output when using json_schema format\n * - Function call ID mappings for tracking\n * - `response_metadata`: Metadata about the response (model, id, etc.)\n * - `generationInfo`: Additional generation information (e.g., tool output status)\n *\n * Returns `null` for events that don't produce meaningful chunks:\n * - Partial image generation events (to avoid storing all partial images in history)\n * - Unrecognized event types\n *\n * @example\n * ```typescript\n * const stream = await client.responses.create({\n * model: \"gpt-4\",\n * input: [{ type: \"message\", content: \"Hello\" }],\n * stream: true\n * });\n *\n * for await (const event of stream) {\n * const chunk = convertResponsesDeltaToChatGenerationChunk(event);\n * if (chunk) {\n * console.log(chunk.text); // Incremental text\n * console.log(chunk.message.tool_call_chunks); // Tool call updates\n * }\n * }\n * ```\n *\n * @remarks\n * - Text content is accumulated in an array with index tracking for proper ordering\n * - Tool call chunks include incremental arguments that need to be concatenated by the consumer\n * - Reasoning summaries are built incrementally across multiple events\n * - Function call IDs are tracked in `additional_kwargs` to map call_id to item id\n * - The `text` field is provided for legacy compatibility with `onLLMNewToken` callbacks\n * - Usage metadata is only available in `response.completed` events\n * - Partial images are intentionally ignored to prevent memory bloat in conversation history\n */\nexport const convertResponsesDeltaToChatGenerationChunk: Converter<\n OpenAIClient.Responses.ResponseStreamEvent,\n ChatGenerationChunk | null\n> = (event) => {\n const content: ContentBlock[] = [];\n let generationInfo: Record<string, unknown> = {};\n let usage_metadata: UsageMetadata | undefined;\n const tool_call_chunks: ToolCallChunk[] = [];\n const response_metadata: Record<string, unknown> = {\n model_provider: \"openai\",\n };\n const additional_kwargs: {\n [key: string]: unknown;\n reasoning?: Partial<ChatOpenAIReasoningSummary>;\n tool_outputs?: unknown[];\n } = {};\n let id: string | undefined;\n if (event.type === \"response.output_text.delta\") {\n content.push({\n type: \"text\",\n text: event.delta,\n index: event.content_index,\n } satisfies ContentBlock.Text);\n } else if (event.type === \"response.output_text.annotation.added\") {\n content.push({\n type: \"text\",\n text: \"\",\n annotations: [\n convertOpenAIAnnotationToLangChain(\n event.annotation as OpenAIAnnotation\n ),\n ],\n index: event.content_index,\n } satisfies ContentBlock.Text);\n } else if (\n event.type === \"response.output_item.added\" &&\n event.item.type === \"message\"\n ) {\n const phase = \"phase\" in event.item ? event.item.phase : undefined;\n if (phase) {\n content.push({\n type: \"text\",\n text: \"\",\n phase,\n index: 0,\n } as ContentBlock.Text);\n }\n } else if (\n event.type === \"response.output_item.added\" &&\n event.item.type === \"function_call\"\n ) {\n tool_call_chunks.push({\n type: \"tool_call_chunk\",\n name: event.item.name,\n args: event.item.arguments,\n id: event.item.call_id,\n index: event.output_index,\n });\n\n additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] = {\n [event.item.call_id]: event.item.id,\n };\n } else if (\n event.type === \"response.output_item.added\" &&\n event.item.type === \"custom_tool_call\"\n ) {\n tool_call_chunks.push({\n type: \"tool_call_chunk\",\n isCustomTool: true,\n name: event.item.name,\n args: event.item.input,\n id: event.item.call_id,\n index: event.output_index,\n } satisfies OpenAICustomToolCallChunk);\n\n additional_kwargs[_CUSTOM_TOOL_CALL_IDS_MAP_KEY] = {\n [event.item.call_id]: event.item.id,\n };\n } else if (\n event.type === \"response.output_item.done\" &&\n event.item.type === \"computer_call\"\n ) {\n // Handle computer_call as a tool call so ToolNode can process it\n tool_call_chunks.push({\n type: \"tool_call_chunk\",\n name: \"computer_use\",\n args: JSON.stringify({ action: event.item.action }),\n id: event.item.call_id,\n index: event.output_index,\n });\n // Also store the raw item for additional context (pending_safety_checks, etc.)\n additional_kwargs.tool_outputs = [event.item];\n } else if (\n event.type === \"response.output_item.done\" &&\n event.item.type === \"image_generation_call\"\n ) {\n // Add image as proper content block if result is available\n if (event.item.result) {\n content.push({\n type: \"image\",\n mimeType: \"image/png\",\n data: event.item.result,\n id: event.item.id,\n metadata: {\n status: event.item.status,\n },\n } satisfies ContentBlock.Multimodal.Image);\n }\n // Also store in tool_outputs for backwards compatibility and multi-turn editing (needs id)\n additional_kwargs.tool_outputs = [event.item];\n } else if (\n event.type === \"response.output_item.done\" &&\n [\n \"web_search_call\",\n \"file_search_call\",\n \"code_interpreter_call\",\n \"shell_call\",\n \"local_shell_call\",\n \"mcp_call\",\n \"mcp_list_tools\",\n \"mcp_approval_request\",\n \"custom_tool_call\",\n \"tool_search_call\",\n \"tool_search_output\",\n ].includes(event.item.type)\n ) {\n additional_kwargs.tool_outputs = [event.item];\n } else if (event.type === \"response.created\") {\n id = event.response.id;\n response_metadata.id = event.response.id;\n response_metadata.model_name = event.response.model;\n response_metadata.model = event.response.model;\n } else if (\n event.type === \"response.completed\" ||\n event.type === \"response.incomplete\"\n ) {\n id = event.response.id;\n const msg = convertResponsesMessageToAIMessage(event.response);\n\n usage_metadata = convertResponsesUsageToUsageMetadata(event.response.usage);\n\n if (event.response.text?.format?.type === \"json_schema\" && msg.text) {\n try {\n additional_kwargs.parsed ??= JSON.parse(msg.text);\n } catch {\n // Some models (observed with gpt-5-mini on service_tier: \"auto\")\n // intermittently emit trailing characters after a valid JSON object\n // in the Responses API path. Throw-on-parse kills the entire stream\n // even though msg.text is otherwise usable. Leave parsed undefined\n // and let the caller fall back to msg.text or retry. See #10894.\n }\n }\n for (const [key, value] of Object.entries(event.response)) {\n if (key === \"id\") continue;\n // Use the cleaned output from the converted message so that\n // SDK-only fields like parsed_arguments are not persisted.\n if (key === \"output\") {\n response_metadata[key] = msg.response_metadata.output;\n } else {\n response_metadata[key] = value;\n }\n }\n } else if (\n event.type === \"response.function_call_arguments.delta\" ||\n event.type === \"response.custom_tool_call_input.delta\"\n ) {\n tool_call_chunks.push({\n type: \"tool_call_chunk\",\n args: event.delta,\n index: event.output_index,\n ...(event.type === \"response.custom_tool_call_input.delta\"\n ? { isCustomTool: true }\n : {}),\n });\n } else if (\n event.type === \"response.web_search_call.in_progress\" ||\n event.type === \"response.web_search_call.searching\" ||\n event.type === \"response.web_search_call.completed\" ||\n event.type === \"response.file_search_call.in_progress\" ||\n event.type === \"response.file_search_call.searching\" ||\n event.type === \"response.file_search_call.completed\" ||\n event.type === \"response.image_generation_call.in_progress\" ||\n event.type === \"response.image_generation_call.generating\" ||\n event.type === \"response.image_generation_call.completed\"\n ) {\n const [, type, status] = event.type.match(/^response\\.(.*)\\.([^.]+)$/) ?? [\n \"\",\n \"\",\n \"\",\n ];\n generationInfo = {\n tool_outputs: {\n id: event.item_id,\n type,\n status,\n },\n };\n } else if (event.type === \"response.refusal.done\") {\n additional_kwargs.refusal = event.refusal;\n } else if (\n event.type === \"response.output_item.added\" &&\n \"item\" in event &&\n event.item.type === \"reasoning\"\n ) {\n const summary: ChatOpenAIReasoningSummary[\"summary\"] | undefined = event\n .item.summary\n ? event.item.summary.map((s, index) => ({\n ...s,\n index,\n }))\n : undefined;\n\n additional_kwargs.reasoning = {\n // We only capture ID in the first event or else the concatenated result of all chunks will\n // have an ID field that is repeated once per event. There is special handling for the `type`\n // field that prevents this, however.\n id: event.item.id,\n type: event.item.type,\n ...(summary ? { summary } : {}),\n };\n\n // Also elevate reasoning to content for UI rendering\n const reasoningText = event.item.summary\n ?.map((s) => s.text)\n .filter(Boolean)\n .join(\"\");\n if (reasoningText) {\n content.push({\n type: \"reasoning\",\n reasoning: reasoningText,\n });\n }\n } else if (event.type === \"response.reasoning_summary_part.added\") {\n additional_kwargs.reasoning = {\n type: \"reasoning\",\n summary: [{ ...event.part, index: event.summary_index }],\n };\n\n // Also elevate reasoning to content for UI rendering\n if (event.part.text) {\n content.push({\n type: \"reasoning\",\n reasoning: event.part.text,\n index: event.summary_index,\n });\n }\n } else if (event.type === \"response.reasoning_summary_text.delta\") {\n additional_kwargs.reasoning = {\n type: \"reasoning\",\n summary: [\n {\n text: event.delta,\n type: \"summary_text\",\n index: event.summary_index,\n },\n ],\n };\n\n // Also elevate reasoning to content for UI rendering\n if (event.delta) {\n content.push({\n type: \"reasoning\",\n reasoning: event.delta,\n index: event.summary_index,\n });\n }\n } else if (event.type === \"response.image_generation_call.partial_image\") {\n // noop/fixme: retaining partial images in a message chunk means that _all_\n // partial images get kept in history, so we don't do anything here.\n return null;\n } else {\n return null;\n }\n\n return new ChatGenerationChunk({\n // Legacy reasons, `onLLMNewToken` should pulls this out\n text: content.map((part) => part.text).join(\"\"),\n message: new AIMessageChunk({\n id,\n content,\n tool_call_chunks,\n usage_metadata,\n additional_kwargs,\n response_metadata,\n }),\n generationInfo,\n });\n};\n\n/**\n * Converts a single LangChain BaseMessage to OpenAI Responses API input format.\n *\n * This converter transforms a LangChain message into one or more ResponseInputItem objects\n * that can be used with OpenAI's Responses API. It handles complex message structures including\n * tool calls, reasoning blocks, multimodal content, and various content block types.\n *\n * @param message - The LangChain BaseMessage to convert. Can be any message type including\n * HumanMessage, AIMessage, SystemMessage, ToolMessage, etc.\n *\n * @returns An array of ResponseInputItem objects.\n *\n * @example\n * Basic text message conversion:\n * ```typescript\n * const message = new HumanMessage(\"Hello, how are you?\");\n * const items = convertStandardContentMessageToResponsesInput(message);\n * // Returns: [{ type: \"message\", role: \"user\", content: [{ type: \"input_text\", text: \"Hello, how are you?\" }] }]\n * ```\n *\n * @example\n * AI message with tool calls:\n * ```typescript\n * const message = new AIMessage({\n * content: \"I'll check the weather for you.\",\n * tool_calls: [{\n * id: \"call_123\",\n * name: \"get_weather\",\n * args: { location: \"San Francisco\" }\n * }]\n * });\n * const items = convertStandardContentMessageToResponsesInput(message);\n * // Returns:\n * // [\n * // { type: \"message\", role: \"assistant\", content: [{ type: \"input_text\", text: \"I'll check the weather for you.\" }] },\n * // { type: \"function_call\", call_id: \"call_123\", name: \"get_weather\", arguments: '{\"location\":\"San Francisco\"}' }\n * // ]\n * ```\n */\nexport const convertStandardContentMessageToResponsesInput: Converter<\n BaseMessage,\n OpenAIClient.Responses.ResponseInputItem[]\n> = (message) => {\n const isResponsesMessage =\n AIMessage.isInstance(message) &&\n message.response_metadata?.model_provider === \"openai\";\n\n function* iterateItems(): Generator<OpenAIClient.Responses.ResponseInputItem> {\n const messageRole = iife(() => {\n try {\n const role = messageToOpenAIRole(message);\n if (\n role === \"system\" ||\n role === \"developer\" ||\n role === \"assistant\" ||\n role === \"user\"\n ) {\n return role;\n }\n return \"assistant\";\n } catch {\n return \"assistant\";\n }\n });\n\n // Text parts must match the message role: assistant content uses\n // `output_text` (the Responses API rejects `input_text` for assistant\n // messages), every other role uses `input_text`.\n const makeTextPart = (\n text: string\n ): ResponseInputMessageContentList[number] =>\n (messageRole === \"assistant\"\n ? { type: \"output_text\", text, annotations: [] }\n : {\n type: \"input_text\",\n text,\n }) as unknown as ResponseInputMessageContentList[number];\n\n let currentMessage: OpenAIClient.Responses.EasyInputMessage | undefined =\n undefined;\n\n const functionCallIdsWithBlocks = new Set<string>();\n const serverFunctionCallIdsWithBlocks = new Set<string>();\n\n const pendingFunctionChunks = new Map<\n string,\n { name?: string; args: string[] }\n >();\n const pendingServerFunctionChunks = new Map<\n string,\n { name?: string; args: string[] }\n >();\n\n function* flushMessage() {\n if (!currentMessage) return;\n const content = currentMessage.content;\n if (\n (typeof content === \"string\" && content.length > 0) ||\n (Array.isArray(content) && content.length > 0)\n ) {\n yield currentMessage;\n }\n currentMessage = undefined;\n }\n\n const pushMessageContent = (\n content: OpenAIClient.Responses.ResponseInputMessageContentList,\n phase?: OpenAIClient.Responses.EasyInputMessage[\"phase\"]\n ) => {\n if (!currentMessage) {\n currentMessage = {\n type: \"message\",\n role: messageRole,\n content: [],\n ...(phase ? { phase } : {}),\n };\n }\n if (typeof currentMessage.content === \"string\") {\n currentMessage.content =\n currentMessage.content.length > 0\n ? [makeTextPart(currentMessage.content), ...content]\n : [...content];\n } else {\n currentMessage.content.push(...content);\n }\n };\n\n const toJsonString = (value: unknown) => {\n if (typeof value === \"string\") {\n return value;\n }\n try {\n return JSON.stringify(value ?? {});\n } catch {\n return \"{}\";\n }\n };\n\n const resolveImageItem = (\n block: ContentBlock.Multimodal.Image\n ): OpenAIClient.Responses.ResponseInputImage | undefined => {\n const detail = iife(() => {\n const raw = block.metadata?.detail;\n if (raw === \"low\" || raw === \"high\" || raw === \"auto\") {\n return raw;\n }\n return \"auto\";\n });\n if (block.fileId) {\n return {\n type: \"input_image\",\n detail,\n file_id: block.fileId,\n };\n }\n if (block.url) {\n return {\n type: \"input_image\",\n detail,\n image_url: block.url,\n };\n }\n if (block.data) {\n const base64Data =\n typeof block.data === \"string\"\n ? block.data\n : Buffer.from(block.data).toString(\"base64\");\n const mimeType = block.mimeType ?? \"image/png\";\n return {\n type: \"input_image\",\n detail,\n image_url: `data:${mimeType};base64,${base64Data}`,\n };\n }\n return undefined;\n };\n\n const resolveFileItem = (\n block: ContentBlock.Multimodal.File | ContentBlock.Multimodal.Video\n ): OpenAIClient.Responses.ResponseInputFile | undefined => {\n if (block.fileId) {\n const filename = getFilenameFromMetadata(block);\n return {\n type: \"input_file\",\n file_id: block.fileId,\n ...(filename ? { filename } : {}),\n };\n }\n if (block.url) {\n const filename = getFilenameFromMetadata(block);\n return {\n ...(filename ? { filename } : {}),\n type: \"input_file\",\n file_url: block.url,\n };\n }\n if (block.data) {\n const filename = getRequiredFilenameFromMetadata(block);\n const encoded =\n typeof block.data === \"string\"\n ? block.data\n : Buffer.from(block.data).toString(\"base64\");\n const mimeType = block.mimeType ?? \"application/octet-stream\";\n return {\n type: \"input_file\",\n file_data: `data:${mimeType};base64,${encoded}`,\n filename,\n };\n }\n return undefined;\n };\n\n const convertReasoningBlock = (\n block: ContentBlock.Reasoning\n ): OpenAIClient.Responses.ResponseReasoningItem => {\n const summaryEntries = iife(() => {\n if (Array.isArray(block.summary)) {\n const candidate = block.summary;\n const mapped =\n candidate\n ?.map((item) => item?.text)\n .filter((text): text is string => typeof text === \"string\") ?? [];\n if (mapped.length > 0) {\n return mapped;\n }\n }\n return block.reasoning ? [block.reasoning] : [];\n });\n\n const summary =\n summaryEntries.length > 0\n ? summaryEntries.map((text) => ({\n type: \"summary_text\" as const,\n text,\n }))\n : [{ type: \"summary_text\" as const, text: \"\" }];\n\n // Only include `id` when we actually have one. Reasoning blocks\n // reassembled from streaming chunks (e.g. via `streamEvents`) never\n // carry an id, since OpenAI's streaming protocol omits it. Emitting\n // `id: \"\"` makes the Responses API reject the turn with\n // `400 Invalid 'input[n].id': ''`, so we omit the field instead — the\n // same way the legacy reconstruction path leaves a missing id off.\n // Reasoning input items only carry `summary` — the Responses API rejects\n // a populated `content` array on input (`400 Invalid 'input[n].content':\n // array too long. Expected an array with maximum length 0`). The reasoning\n // text is already represented in `summary`, so we do not forward `content`.\n return {\n type: \"reasoning\",\n ...(block.id ? { id: block.id } : {}),\n summary,\n } as OpenAIClient.Responses.ResponseReasoningItem;\n };\n\n const convertFunctionCall = (\n block: ContentBlock.Tools.ToolCall | ContentBlock.Tools.ServerToolCall\n ): OpenAIClient.Responses.ResponseFunctionToolCall => ({\n type: \"function_call\",\n name: block.name ?? \"\",\n call_id: block.id ?? \"\",\n arguments: toJsonString(block.args),\n });\n\n const convertFunctionCallOutput = (\n block: ContentBlock.Tools.ServerToolCallResult\n ): OpenAIClient.Responses.ResponseInputItem.FunctionCallOutput => {\n const output = toJsonString(block.output);\n const status =\n block.status === \"success\"\n ? \"completed\"\n : block.status === \"error\"\n ? \"incomplete\"\n : undefined;\n return {\n type: \"function_call_output\",\n call_id: block.toolCallId ?? \"\",\n output,\n ...(status ? { status } : {}),\n };\n };\n\n for (const block of message.contentBlocks) {\n if (block.type === \"text\") {\n const phase = iife(() => {\n if (\n !(\n \"extras\" in block &&\n typeof block.extras === \"object\" &&\n block.extras !== null &&\n \"phase\" in block.extras\n )\n )\n return undefined;\n return block.extras\n .phase as OpenAIClient.Responses.EasyInputMessage[\"phase\"];\n });\n pushMessageContent([makeTextPart(block.text)], phase);\n } else if (block.type === \"invalid_tool_call\") {\n // no-op\n } else if (block.type === \"reasoning\") {\n yield* flushMessage();\n yield convertReasoningBlock(\n block as ContentBlock.Standard & { type: \"reasoning\" }\n );\n } else if (block.type === \"tool_call\") {\n yield* flushMessage();\n const id = block.id ?? \"\";\n if (id) {\n functionCallIdsWithBlocks.add(id);\n pendingFunctionChunks.delete(id);\n }\n yield convertFunctionCall(\n block as ContentBlock.Standard & { type: \"tool_call\" }\n );\n } else if (block.type === \"tool_call_chunk\") {\n if (block.id) {\n const existing = pendingFunctionChunks.get(block.id) ?? {\n name: block.name,\n args: [],\n };\n if (block.name) existing.name = block.name;\n if (block.args) existing.args.push(block.args);\n pendingFunctionChunks.set(block.id, existing);\n }\n } else if (block.type === \"server_tool_call\") {\n yield* flushMessage();\n const id = block.id ?? \"\";\n if (id) {\n serverFunctionCallIdsWithBlocks.add(id);\n pendingServerFunctionChunks.delete(id);\n }\n yield convertFunctionCall(block);\n } else if (block.type === \"server_tool_call_chunk\") {\n if (block.id) {\n const existing = pendingServerFunctionChunks.get(block.id) ?? {\n name: block.name,\n args: [],\n };\n if (block.name) existing.name = block.name;\n if (block.args) existing.args.push(block.args);\n pendingServerFunctionChunks.set(block.id, existing);\n }\n } else if (block.type === \"server_tool_call_result\") {\n yield* flushMessage();\n yield convertFunctionCallOutput(block);\n } else if (block.type === \"audio\") {\n // no-op\n } else if (block.type === \"file\") {\n const fileItem = resolveFileItem(block);\n if (fileItem) {\n pushMessageContent([fileItem]);\n }\n } else if (block.type === \"image\") {\n const imageItem = resolveImageItem(block);\n if (imageItem) {\n pushMessageContent([imageItem]);\n }\n } else if (block.type === \"video\") {\n const videoItem = resolveFileItem(block);\n if (videoItem) {\n pushMessageContent([videoItem]);\n }\n } else if (block.type === \"text-plain\") {\n if (block.text) {\n pushMessageContent([makeTextPart(block.text)]);\n }\n } else if (block.type === \"non_standard\" && isResponsesMessage) {\n yield* flushMessage();\n yield block.value as ResponsesInputItem;\n }\n }\n yield* flushMessage();\n\n for (const [id, chunk] of pendingFunctionChunks) {\n if (!id || functionCallIdsWithBlocks.has(id)) continue;\n const args = chunk.args.join(\"\");\n if (!chunk.name && !args) continue;\n yield {\n type: \"function_call\",\n call_id: id,\n name: chunk.name ?? \"\",\n arguments: args,\n };\n }\n\n for (const [id, chunk] of pendingServerFunctionChunks) {\n if (!id || serverFunctionCallIdsWithBlocks.has(id)) continue;\n const args = chunk.args.join(\"\");\n if (!chunk.name && !args) continue;\n yield {\n type: \"function_call\",\n call_id: id,\n name: chunk.name ?? \"\",\n arguments: args,\n };\n }\n }\n return Array.from(iterateItems());\n};\n\n/**\n * - MCP (Model Context Protocol) approval responses\n * - Zero Data Retention (ZDR) mode handling\n *\n * @param params - Conversion parameters\n * @param params.messages - Array of LangChain BaseMessages to convert\n * @param params.zdrEnabled - Whether Zero Data Retention mode is enabled. When true, certain\n * metadata like message IDs and function call IDs are omitted from the output\n * @param params.model - The model name being used. Used to determine if special role mapping\n * is needed (e.g., \"system\" -> \"developer\" for reasoning models)\n *\n * @returns Array of ResponsesInputItem objects formatted for the OpenAI Responses API\n *\n * @throws {Error} When a function message is encountered (not supported)\n * @throws {Error} When computer call output format is invalid\n *\n * @example\n * ```typescript\n * const messages = [\n * new HumanMessage(\"Hello\"),\n * new AIMessage({ content: \"Hi there!\", tool_calls: [...] })\n * ];\n *\n * const input = convertMessagesToResponsesInput({\n * messages,\n * zdrEnabled: false,\n * model: \"gpt-4\"\n * });\n * ```\n */\nexport const convertMessagesToResponsesInput: Converter<\n { messages: BaseMessage[]; zdrEnabled: boolean; model: string },\n ResponsesInputItem[]\n> = ({ messages, zdrEnabled, model }) => {\n return messages.flatMap(\n (lcMsg): ResponsesInputItem | ResponsesInputItem[] => {\n const responseMetadata = lcMsg.response_metadata as\n | Record<string, unknown>\n | undefined;\n if (responseMetadata?.output_version === \"v1\") {\n return convertStandardContentMessageToResponsesInput(lcMsg);\n }\n\n const additional_kwargs =\n lcMsg.additional_kwargs as BaseMessageFields[\"additional_kwargs\"] & {\n [_FUNCTION_CALL_IDS_MAP_KEY]?: Record<string, string>;\n reasoning?: OpenAIClient.Responses.ResponseReasoningItem;\n type?: string;\n refusal?: string;\n };\n\n let role = messageToOpenAIRole(lcMsg);\n if (role === \"system\" && isReasoningModel(model)) role = \"developer\";\n\n if (role === \"function\") {\n throw new Error(\"Function messages are not supported in Responses API\");\n }\n\n if (role === \"tool\") {\n const toolMessage = lcMsg as ToolMessage;\n\n // Handle computer call output\n if (additional_kwargs?.type === \"computer_call_output\") {\n const output = (() => {\n if (typeof toolMessage.content === \"string\") {\n return {\n type: \"input_image\" as const,\n image_url: toolMessage.content,\n };\n }\n\n if (Array.isArray(toolMessage.content)) {\n /**\n * Check for input_image type first (computer-use-preview format)\n */\n const inputImage = toolMessage.content.find(\n (i) => i.type === \"input_image\"\n ) as { type: \"input_image\"; image_url: string } | undefined;\n\n if (inputImage) return inputImage;\n\n /**\n * Check for computer_screenshot type (legacy format)\n */\n const oaiScreenshot = toolMessage.content.find(\n (i) => i.type === \"computer_screenshot\"\n ) as\n | { type: \"computer_screenshot\"; image_url: string }\n | undefined;\n\n if (oaiScreenshot) return oaiScreenshot;\n\n /**\n * Convert image_url content block to input_image format\n */\n const lcImage = toolMessage.content.find(\n (i) => i.type === \"image_url\"\n ) as MessageContentImageUrl;\n\n if (lcImage) {\n return {\n type: \"input_image\" as const,\n image_url:\n typeof lcImage.image_url === \"string\"\n ? lcImage.image_url\n : lcImage.image_url.url,\n };\n }\n }\n\n throw new Error(\"Invalid computer call output\");\n })();\n\n /**\n * Cast needed because OpenAI SDK types don't yet include input_image\n * for computer-use-preview model output format\n */\n return {\n type: \"computer_call_output\",\n output,\n call_id: toolMessage.tool_call_id,\n } as ResponsesInputItem;\n }\n\n // Handle custom tool output\n if (toolMessage.additional_kwargs?.customTool) {\n return {\n type: \"custom_tool_call_output\",\n call_id: toolMessage.tool_call_id,\n output: toolMessage.content as string,\n };\n }\n\n // Check if content contains provider-native OpenAI content blocks\n // that should be passed through without stringification\n const isProviderNativeContent =\n Array.isArray(toolMessage.content) &&\n toolMessage.content.every(\n (item) =>\n typeof item === \"object\" &&\n item !== null &&\n \"type\" in item &&\n (item.type === \"input_file\" ||\n item.type === \"input_image\" ||\n item.type === \"input_text\")\n );\n\n return {\n type: \"function_call_output\",\n call_id: toolMessage.tool_call_id,\n id: toolMessage.id?.startsWith(\"fc_\") ? toolMessage.id : undefined,\n output: isProviderNativeContent\n ? (toolMessage.content as OpenAIClient.Responses.ResponseFunctionCallOutputItemList)\n : typeof toolMessage.content !== \"string\"\n ? JSON.stringify(toolMessage.content)\n : toolMessage.content,\n };\n }\n\n if (role === \"assistant\") {\n // if we have the original response items, just reuse them\n if (\n !zdrEnabled &&\n responseMetadata?.output != null &&\n Array.isArray(responseMetadata?.output) &&\n responseMetadata?.output.length > 0 &&\n responseMetadata?.output.every((item) => \"type\" in item)\n ) {\n return responseMetadata?.output;\n }\n\n // otherwise, try to reconstruct the response from what we have\n\n const input: ResponsesInputItem[] = [];\n\n // reasoning items\n const reasoning = additional_kwargs?.reasoning;\n const hasEncryptedContent = !!reasoning?.encrypted_content;\n /**\n * With ZDR enabled, OpenAI does not retain reasoning items, so we only send\n * them when encrypted content is available (via include: [\"reasoning.encrypted_content\"]).\n * With ZDR disabled, we include reasoning item ids so OpenAI can reference them, as it's storing them.\n */\n if (reasoning && (!zdrEnabled || hasEncryptedContent)) {\n const reasoningItem =\n convertReasoningSummaryToResponsesReasoningItem(reasoning);\n input.push(reasoningItem);\n }\n\n // ai content\n let { content } = lcMsg;\n if (additional_kwargs?.refusal) {\n if (typeof content === \"string\") {\n content = [{ type: \"output_text\", text: content, annotations: [] }];\n }\n content = [\n ...(content as ContentBlock[]),\n { type: \"refusal\", refusal: additional_kwargs.refusal },\n ];\n }\n\n if (typeof content === \"string\" || content.length > 0) {\n const messageItem: ResponsesInputItem = {\n type: \"message\",\n role: \"assistant\",\n ...(lcMsg.id && !zdrEnabled && lcMsg.id.startsWith(\"msg_\")\n ? { id: lcMsg.id }\n : {}),\n content: iife(() => {\n if (typeof content === \"string\") {\n return content;\n }\n return content.flatMap((item) => {\n if (item.type === \"text\") {\n const textItem = item as ContentBlock.Text;\n return {\n type: \"output_text\",\n text: textItem.text,\n annotations: (textItem.annotations ?? []).map(\n convertLangChainAnnotationToOpenAI\n ),\n };\n }\n\n if (item.type === \"output_text\" || item.type === \"refusal\") {\n return item;\n }\n\n return [];\n });\n }) as ResponseInputMessageContentList,\n phase: iife(() => {\n if (!Array.isArray(content)) {\n return undefined;\n }\n\n const phasedContent = content.find(\n (item): item is ContentBlock & { phase: string } =>\n \"phase\" in item && typeof item.phase === \"string\"\n );\n return phasedContent?.phase as\n | OpenAIClient.Responses.EasyInputMessage[\"phase\"]\n | undefined;\n }),\n };\n input.push(messageItem);\n }\n\n const functionCallIds = additional_kwargs?.[_FUNCTION_CALL_IDS_MAP_KEY];\n const customToolCallIds =\n additional_kwargs?.[_CUSTOM_TOOL_CALL_IDS_MAP_KEY];\n\n if (AIMessage.isInstance(lcMsg) && !!lcMsg.tool_calls?.length) {\n input.push(\n ...lcMsg.tool_calls.map((toolCall): ResponsesInputItem => {\n if (isCustomToolCall(toolCall, customToolCallIds)) {\n return {\n type: \"custom_tool_call\",\n id:\n \"call_id\" in toolCall &&\n typeof toolCall.call_id === \"string\"\n ? toolCall.call_id\n : (customToolCallIds?.[toolCall.id ?? \"\"] ?? \"\"),\n call_id: toolCall.id ?? \"\",\n input: toolCall.args.input,\n name: toolCall.name,\n };\n }\n if (isComputerToolCall(toolCall)) {\n return {\n type: \"computer_call\",\n id: toolCall.call_id,\n call_id: toolCall.id ?? \"\",\n action: toolCall.args.action,\n } as ResponsesInputItem;\n }\n return {\n type: \"function_call\",\n name: toolCall.name,\n arguments: JSON.stringify(toolCall.args),\n call_id: toolCall.id!,\n ...(!zdrEnabled ? { id: functionCallIds?.[toolCall.id!] } : {}),\n };\n })\n );\n } else if (additional_kwargs?.tool_calls) {\n input.push(\n ...additional_kwargs.tool_calls.map(\n (toolCall): ResponsesInputItem => ({\n type: \"function_call\",\n name: toolCall.function.name,\n call_id: toolCall.id,\n arguments: toolCall.function.arguments,\n ...(!zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {}),\n })\n )\n );\n }\n\n const toolOutputs = (\n responseMetadata?.output as Array<ResponsesInputItem>\n )?.length\n ? responseMetadata?.output\n : additional_kwargs.tool_outputs;\n\n const fallthroughCallTypes: ResponsesInputItem[\"type\"][] = [\n \"computer_call\",\n \"mcp_call\",\n \"code_interpreter_call\",\n \"image_generation_call\",\n \"shell_call\",\n \"local_shell_call\",\n ];\n\n if (toolOutputs != null) {\n const castToolOutputs = toolOutputs as Array<ResponsesInputItem>;\n const fallthroughCalls = castToolOutputs?.filter((item) =>\n fallthroughCallTypes.includes(item.type)\n );\n if (fallthroughCalls.length > 0) input.push(...fallthroughCalls);\n }\n\n return input;\n }\n\n if (role === \"user\" || role === \"system\" || role === \"developer\") {\n if (typeof lcMsg.content === \"string\") {\n return { type: \"message\", role, content: lcMsg.content };\n }\n\n const messages: ResponsesInputItem[] = [];\n const content = (lcMsg.content as ContentBlock[]).flatMap((item) => {\n if (item.type === \"mcp_approval_response\") {\n messages.push({\n type: \"mcp_approval_response\",\n approval_request_id: item.approval_request_id as string,\n approve: item.approve as boolean,\n });\n }\n if (isDataContentBlock(item)) {\n // The Responses API supports file URLs natively, but the Chat\n // Completions converter rejects URL file blocks. Convert standard\n // file blocks to the native `input_file` shape instead of routing\n // them through the completions converter.\n if (item.type === \"file\") {\n const filename = getFilenameFromMetadata(item);\n if (item.source_type === \"url\") {\n return {\n type: \"input_file\",\n file_url: item.url,\n ...(filename ? { filename } : {}),\n };\n }\n if (item.source_type === \"id\") {\n return {\n type: \"input_file\",\n file_id: item.id,\n ...(filename ? { filename } : {}),\n };\n }\n if (item.source_type === \"base64\") {\n const mimeType = item.mime_type ?? \"\";\n return {\n type: \"input_file\",\n file_data: `data:${mimeType};base64,${item.data}`,\n filename: getRequiredFilenameFromMetadata(item),\n };\n }\n }\n return convertToProviderContentBlock(\n item,\n completionsApiContentBlockConverter\n );\n }\n if (item.type === \"text\") {\n return {\n type: \"input_text\",\n text: item.text,\n };\n }\n if (item.type === \"image_url\") {\n const imageUrl = iife(() => {\n if (typeof item.image_url === \"string\") {\n return item.image_url;\n } else if (\n typeof item.image_url === \"object\" &&\n item.image_url !== null &&\n \"url\" in item.image_url\n ) {\n return item.image_url.url;\n }\n return undefined;\n });\n const detail = iife(() => {\n if (typeof item.image_url === \"string\") {\n return \"auto\";\n } else if (\n typeof item.image_url === \"object\" &&\n item.image_url !== null &&\n \"detail\" in item.image_url\n ) {\n return item.image_url.detail;\n }\n return undefined;\n });\n return {\n type: \"input_image\",\n image_url: imageUrl,\n detail,\n };\n }\n if (\n item.type === \"input_text\" ||\n item.type === \"input_image\" ||\n item.type === \"input_file\"\n ) {\n return item;\n }\n return [];\n });\n\n if (content.length > 0) {\n messages.push({\n type: \"message\",\n role,\n content: content as ResponseInputMessageContentList,\n });\n }\n return messages;\n }\n\n console.warn(\n `Unsupported role found when converting to OpenAI Responses API: ${role}`\n );\n return [];\n }\n );\n};\n"],"mappings":";;;;;;;AA0CA,MAAM,6BAA6B;AACnC,MAAM,gCAAgC;;;;;;;;;;;;AAmBtC,SAAS,mCACP,YACkD;CAClD,IAAI,WAAW,SAAS,gBACtB,OAAO;EACL,MAAM;EACN,QAAQ;EACR,KAAK,WAAW;EAChB,OAAO,WAAW;EAClB,YAAY,WAAW;EACvB,UAAU,WAAW;CACvB;CAGF,IAAI,WAAW,SAAS,iBACtB,OAAO;EACL,MAAM;EACN,QAAQ;EACR,OAAO,WAAW;EAClB,YAAY,WAAW;EAEvB,SAAS,WAAW;CACtB;CAGF,IAAI,WAAW,SAAS,2BACtB,OAAO;EACL,MAAM;EACN,QAAQ;EACR,OAAO,WAAW;EAClB,YAAY,WAAW;EACvB,UAAU,WAAW;EAErB,SAAS,WAAW;EACpB,cAAc,WAAW;CAC3B;CAGF,IAAI,WAAW,SAAS,aACtB,OAAO;EACL,MAAM;EACN,QAAQ;EACR,YAAY,WAAW;EACvB,SAAS,WAAW;CACtB;CAIF,OAAO;EACL,MAAM;EACN,OAAO;CACT;AACF;;;;;;;;AASA,SAAS,mCACP,YAIkB;CAElB,IACE,WAAW,SAAS,kBACpB,WAAW,SAAS,mBACpB,WAAW,SAAS,6BACpB,WAAW,SAAS,aAEpB,OAAO;CAIT,IAAI,WAAW,SAAS,YAAY;EAClC,MAAM,WAAW;EAKjB,IAAI,SAAS,WAAW,gBACtB,OAAO;GACL,MAAM;GACN,KAAK,SAAS,OAAO;GACrB,OAAO,SAAS,SAAS;GACzB,aAAa,SAAS,cAAc;GACpC,WAAW,SAAS,YAAY;EAClC;EAGF,IAAI,SAAS,WAAW,iBACtB,OAAO;GACL,MAAM;GACN,SAAS,SAAS,WAAW;GAC7B,UAAU,SAAS,SAAS;GAC5B,OAAO,SAAS,cAAc;EAChC;EAGF,IAAI,SAAS,WAAW,2BACtB,OAAO;GACL,MAAM;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 @@
|
|
|
1
|
-
{"version":3,"file":"embeddings.cjs","names":["Embeddings","getEndpoint","getHeadersWithUserAgent","OpenAIClient","wrapOpenAIClientError"],"sources":["../src/embeddings.ts"],"sourcesContent":["import { type ClientOptions, OpenAI as OpenAIClient } from \"openai\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { Embeddings, type EmbeddingsParams } from \"@langchain/core/embeddings\";\nimport { chunkArray } from \"@langchain/core/utils/chunk_array\";\nimport type { OpenAIApiKey } from \"./types.js\";\nimport {\n getEndpoint,\n OpenAIEndpointConfig,\n getHeadersWithUserAgent,\n} from \"./utils/azure.js\";\nimport { wrapOpenAIClientError } from \"./utils/client.js\";\n\n/**\n * @see https://platform.openai.com/docs/guides/embeddings#embedding-models\n */\nexport type OpenAIEmbeddingModelId =\n | OpenAIClient.EmbeddingModel\n | (string & NonNullable<unknown>);\n\n/**\n * Interface for OpenAIEmbeddings parameters. Extends EmbeddingsParams and\n * defines additional parameters specific to the OpenAIEmbeddings class.\n */\nexport interface OpenAIEmbeddingsParams extends EmbeddingsParams {\n /**\n * Model name to use\n * Alias for `model`\n * @deprecated Use \"model\" instead.\n */\n modelName: OpenAIEmbeddingModelId;\n /** Model name to use */\n model: OpenAIEmbeddingModelId;\n\n /**\n * The number of dimensions the resulting output embeddings should have.\n * Only supported in `text-embedding-3` and later models.\n */\n dimensions?: number;\n\n /**\n * Timeout to use when making requests to OpenAI.\n */\n timeout?: number;\n\n /**\n * The maximum number of documents to embed in a single request. This is\n * limited by the OpenAI API to a maximum of 2048.\n */\n batchSize?: number;\n\n /**\n * Whether to strip new lines from the input text. This is recommended by\n * OpenAI for older models, but may not be suitable for all use cases.\n * See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500\n */\n stripNewLines?: boolean;\n\n /**\n * The format to return the embeddings in. Can be either 'float' or 'base64'.\n */\n encodingFormat?: \"float\" | \"base64\";\n}\n\n/**\n * Class for generating embeddings using the OpenAI API.\n *\n * To use with Azure, import the `AzureOpenAIEmbeddings` class.\n *\n * @example\n * ```typescript\n * // Embed a query using OpenAIEmbeddings to generate embeddings for a given text\n * const model = new OpenAIEmbeddings();\n * const res = await model.embedQuery(\n * \"What would be a good company name for a company that makes colorful socks?\",\n * );\n * console.log({ res });\n *\n * ```\n */\nexport class OpenAIEmbeddings<TOutput = number[]>\n extends Embeddings<TOutput>\n implements Partial<OpenAIEmbeddingsParams>\n{\n model = \"text-embedding-ada-002\";\n\n /** @deprecated Use \"model\" instead */\n modelName: string;\n\n batchSize = 512;\n\n // TODO: Update to `false` on next minor release (see: https://github.com/langchain-ai/langchainjs/pull/3612)\n stripNewLines = true;\n\n /**\n * The number of dimensions the resulting output embeddings should have.\n * Only supported in `text-embedding-3` and later models.\n */\n dimensions?: number;\n\n timeout?: number;\n\n organization?: string;\n\n encodingFormat?: \"float\" | \"base64\";\n\n protected client: OpenAIClient;\n\n protected clientConfig: ClientOptions;\n\n protected apiKey?: OpenAIApiKey;\n\n constructor(\n fields?: Partial<OpenAIEmbeddingsParams> & {\n verbose?: boolean;\n /**\n * The OpenAI API key to use.\n * Alias for `apiKey`.\n */\n openAIApiKey?: OpenAIApiKey;\n /** The OpenAI API key to use. */\n apiKey?: OpenAIApiKey;\n configuration?: ClientOptions;\n }\n ) {\n const fieldsWithDefaults = { maxConcurrency: 2, ...fields };\n\n super(fieldsWithDefaults);\n\n const apiKey =\n fieldsWithDefaults?.apiKey ??\n fieldsWithDefaults?.openAIApiKey ??\n getEnvironmentVariable(\"OPENAI_API_KEY\");\n\n this.organization =\n fieldsWithDefaults?.configuration?.organization ??\n getEnvironmentVariable(\"OPENAI_ORGANIZATION\");\n\n this.model =\n fieldsWithDefaults?.model ?? fieldsWithDefaults?.modelName ?? this.model;\n this.modelName = this.model;\n this.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize;\n this.stripNewLines =\n fieldsWithDefaults?.stripNewLines ?? this.stripNewLines;\n this.timeout = fieldsWithDefaults?.timeout;\n this.dimensions = fieldsWithDefaults?.dimensions;\n this.encodingFormat = fieldsWithDefaults?.encodingFormat;\n\n this.clientConfig = {\n apiKey,\n organization: this.organization,\n dangerouslyAllowBrowser: true,\n ...fields?.configuration,\n };\n }\n\n /**\n * Method to generate embeddings for an array of documents. Splits the\n * documents into batches and makes requests to the OpenAI API to generate\n * embeddings.\n * @param texts Array of documents to generate embeddings for.\n * @returns Promise that resolves to a 2D array of embeddings for each document.\n */\n async embedDocuments(texts: string[]): Promise<TOutput[]> {\n const batches = chunkArray(\n this.stripNewLines ? texts.map((t) => t.replace(/\\n/g, \" \")) : texts,\n this.batchSize\n );\n\n const batchRequests = batches.map((batch) => {\n const params: OpenAIClient.EmbeddingCreateParams = {\n model: this.model,\n input: batch,\n };\n if (this.dimensions) {\n params.dimensions = this.dimensions;\n }\n if (this.encodingFormat) {\n params.encoding_format = this.encodingFormat;\n }\n return this.embeddingWithRetry(params);\n });\n const batchResponses = await Promise.all(batchRequests);\n\n const embeddings: TOutput[] = [];\n for (let i = 0; i < batchResponses.length; i += 1) {\n const batch = batches[i];\n const { data: batchResponse } = batchResponses[i];\n for (let j = 0; j < batch.length; j += 1) {\n embeddings.push(batchResponse[j].embedding as TOutput);\n }\n }\n return embeddings;\n }\n\n /**\n * Method to generate an embedding for a single document. Calls the\n * embeddingWithRetry method with the document as the input.\n * @param text Document to generate an embedding for.\n * @returns Promise that resolves to an embedding for the document.\n */\n async embedQuery(text: string): Promise<TOutput> {\n const params: OpenAIClient.EmbeddingCreateParams = {\n model: this.model,\n input: this.stripNewLines ? text.replace(/\\n/g, \" \") : text,\n };\n if (this.dimensions) {\n params.dimensions = this.dimensions;\n }\n if (this.encodingFormat) {\n params.encoding_format = this.encodingFormat;\n }\n const { data } = await this.embeddingWithRetry(params);\n return data[0].embedding as TOutput;\n }\n\n /**\n * Private method to make a request to the OpenAI API to generate\n * embeddings. Handles the retry logic and returns the response from the\n * API.\n * @param request Request to send to the OpenAI API.\n * @returns Promise that resolves to the response from the API.\n */\n protected async embeddingWithRetry(\n request: OpenAIClient.EmbeddingCreateParams\n ) {\n if (!this.client) {\n const openAIEndpointConfig: OpenAIEndpointConfig = {\n baseURL: this.clientConfig.baseURL,\n };\n\n const endpoint = getEndpoint(openAIEndpointConfig);\n\n const params = {\n ...this.clientConfig,\n baseURL: endpoint,\n timeout: this.timeout,\n maxRetries: 0,\n };\n\n if (!params.baseURL) {\n delete params.baseURL;\n }\n\n params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders);\n\n this.client = new OpenAIClient(params);\n }\n const requestOptions = {};\n\n return this.caller.call(async () => {\n try {\n const res = await this.client.embeddings.create(\n request,\n requestOptions\n );\n return res;\n } catch (e) {\n const error = wrapOpenAIClientError(e);\n throw error;\n }\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+EA,IAAa,mBAAb,cACUA,2BAAAA,WAEV;CACE,QAAQ;;CAGR;CAEA,YAAY;CAGZ,gBAAgB;;;;;CAMhB;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,YACE,QAWA;EACA,MAAM,qBAAqB;GAAE,gBAAgB;GAAG,GAAG;GAAQ;AAE3D,QAAM,mBAAmB;EAEzB,MAAM,SACJ,oBAAoB,UACpB,oBAAoB,iBAAA,GAAA,0BAAA,wBACG,iBAAiB;AAE1C,OAAK,eACH,oBAAoB,eAAe,iBAAA,GAAA,0BAAA,wBACZ,sBAAsB;AAE/C,OAAK,QACH,oBAAoB,SAAS,oBAAoB,aAAa,KAAK;AACrE,OAAK,YAAY,KAAK;AACtB,OAAK,YAAY,oBAAoB,aAAa,KAAK;AACvD,OAAK,gBACH,oBAAoB,iBAAiB,KAAK;AAC5C,OAAK,UAAU,oBAAoB;AACnC,OAAK,aAAa,oBAAoB;AACtC,OAAK,iBAAiB,oBAAoB;AAE1C,OAAK,eAAe;GAClB;GACA,cAAc,KAAK;GACnB,yBAAyB;GACzB,GAAG,QAAQ;GACZ;;;;;;;;;CAUH,MAAM,eAAe,OAAqC;E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wB,OAAO,eAAe;AAEtE,QAAK,SAAS,IAAIC,OAAAA,OAAa,OAAO;;EAExC,MAAM,iBAAiB,EAAE;AAEzB,SAAO,KAAK,OAAO,KAAK,YAAY;AAClC,OAAI;AAKF,WAAO,MAJW,KAAK,OAAO,WAAW,OACvC,SACA,eACD;YAEM,GAAG;AAEV,UADcC,eAAAA,sBAAsB,EACzB;;IAEb"}
|
|
1
|
+
{"version":3,"file":"embeddings.cjs","names":["Embeddings","getEndpoint","getHeadersWithUserAgent","OpenAIClient","wrapOpenAIClientError"],"sources":["../src/embeddings.ts"],"sourcesContent":["import { type ClientOptions, OpenAI as OpenAIClient } from \"openai\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { Embeddings, type EmbeddingsParams } from \"@langchain/core/embeddings\";\nimport { chunkArray } from \"@langchain/core/utils/chunk_array\";\nimport type { OpenAIApiKey } from \"./types.js\";\nimport {\n getEndpoint,\n OpenAIEndpointConfig,\n getHeadersWithUserAgent,\n} from \"./utils/azure.js\";\nimport { wrapOpenAIClientError } from \"./utils/client.js\";\n\n/**\n * @see https://platform.openai.com/docs/guides/embeddings#embedding-models\n */\nexport type OpenAIEmbeddingModelId =\n | OpenAIClient.EmbeddingModel\n | (string & NonNullable<unknown>);\n\n/**\n * Interface for OpenAIEmbeddings parameters. Extends EmbeddingsParams and\n * defines additional parameters specific to the OpenAIEmbeddings class.\n */\nexport interface OpenAIEmbeddingsParams extends EmbeddingsParams {\n /**\n * Model name to use\n * Alias for `model`\n * @deprecated Use \"model\" instead.\n */\n modelName: OpenAIEmbeddingModelId;\n /** Model name to use */\n model: OpenAIEmbeddingModelId;\n\n /**\n * The number of dimensions the resulting output embeddings should have.\n * Only supported in `text-embedding-3` and later models.\n */\n dimensions?: number;\n\n /**\n * Timeout to use when making requests to OpenAI.\n */\n timeout?: number;\n\n /**\n * The maximum number of documents to embed in a single request. This is\n * limited by the OpenAI API to a maximum of 2048.\n */\n batchSize?: number;\n\n /**\n * Whether to strip new lines from the input text. This is recommended by\n * OpenAI for older models, but may not be suitable for all use cases.\n * See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500\n */\n stripNewLines?: boolean;\n\n /**\n * The format to return the embeddings in. Can be either 'float' or 'base64'.\n */\n encodingFormat?: \"float\" | \"base64\";\n}\n\n/**\n * Class for generating embeddings using the OpenAI API.\n *\n * To use with Azure, import the `AzureOpenAIEmbeddings` class.\n *\n * @example\n * ```typescript\n * // Embed a query using OpenAIEmbeddings to generate embeddings for a given text\n * const model = new OpenAIEmbeddings();\n * const res = await model.embedQuery(\n * \"What would be a good company name for a company that makes colorful socks?\",\n * );\n * console.log({ res });\n *\n * ```\n */\nexport class OpenAIEmbeddings<TOutput = number[]>\n extends Embeddings<TOutput>\n implements Partial<OpenAIEmbeddingsParams>\n{\n model = \"text-embedding-ada-002\";\n\n /** @deprecated Use \"model\" instead */\n modelName: string;\n\n batchSize = 512;\n\n // TODO: Update to `false` on next minor release (see: https://github.com/langchain-ai/langchainjs/pull/3612)\n stripNewLines = true;\n\n /**\n * The number of dimensions the resulting output embeddings should have.\n * Only supported in `text-embedding-3` and later models.\n */\n dimensions?: number;\n\n timeout?: number;\n\n organization?: string;\n\n encodingFormat?: \"float\" | \"base64\";\n\n protected client: OpenAIClient;\n\n protected clientConfig: ClientOptions;\n\n protected apiKey?: OpenAIApiKey;\n\n constructor(\n fields?: Partial<OpenAIEmbeddingsParams> & {\n verbose?: boolean;\n /**\n * The OpenAI API key to use.\n * Alias for `apiKey`.\n */\n openAIApiKey?: OpenAIApiKey;\n /** The OpenAI API key to use. */\n apiKey?: OpenAIApiKey;\n configuration?: ClientOptions;\n }\n ) {\n const fieldsWithDefaults = { maxConcurrency: 2, ...fields };\n\n super(fieldsWithDefaults);\n\n const apiKey =\n fieldsWithDefaults?.apiKey ??\n fieldsWithDefaults?.openAIApiKey ??\n getEnvironmentVariable(\"OPENAI_API_KEY\");\n\n this.organization =\n fieldsWithDefaults?.configuration?.organization ??\n getEnvironmentVariable(\"OPENAI_ORGANIZATION\");\n\n this.model =\n fieldsWithDefaults?.model ?? fieldsWithDefaults?.modelName ?? this.model;\n this.modelName = this.model;\n this.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize;\n this.stripNewLines =\n fieldsWithDefaults?.stripNewLines ?? this.stripNewLines;\n this.timeout = fieldsWithDefaults?.timeout;\n this.dimensions = fieldsWithDefaults?.dimensions;\n this.encodingFormat = fieldsWithDefaults?.encodingFormat;\n\n this.clientConfig = {\n apiKey,\n organization: this.organization,\n dangerouslyAllowBrowser: true,\n ...fields?.configuration,\n };\n }\n\n /**\n * Method to generate embeddings for an array of documents. Splits the\n * documents into batches and makes requests to the OpenAI API to generate\n * embeddings.\n * @param texts Array of documents to generate embeddings for.\n * @returns Promise that resolves to a 2D array of embeddings for each document.\n */\n async embedDocuments(texts: string[]): Promise<TOutput[]> {\n const batches = chunkArray(\n this.stripNewLines ? texts.map((t) => t.replace(/\\n/g, \" \")) : texts,\n this.batchSize\n );\n\n const batchRequests = batches.map((batch) => {\n const params: OpenAIClient.EmbeddingCreateParams = {\n model: this.model,\n input: batch,\n };\n if (this.dimensions) {\n params.dimensions = this.dimensions;\n }\n if (this.encodingFormat) {\n params.encoding_format = this.encodingFormat;\n }\n return this.embeddingWithRetry(params);\n });\n const batchResponses = await Promise.all(batchRequests);\n\n const embeddings: TOutput[] = [];\n for (let i = 0; i < batchResponses.length; i += 1) {\n const batch = batches[i];\n const { data: batchResponse } = batchResponses[i];\n for (let j = 0; j < batch.length; j += 1) {\n embeddings.push(batchResponse[j].embedding as TOutput);\n }\n }\n return embeddings;\n }\n\n /**\n * Method to generate an embedding for a single document. Calls the\n * embeddingWithRetry method with the document as the input.\n * @param text Document to generate an embedding for.\n * @returns Promise that resolves to an embedding for the document.\n */\n async embedQuery(text: string): Promise<TOutput> {\n const params: OpenAIClient.EmbeddingCreateParams = {\n model: this.model,\n input: this.stripNewLines ? text.replace(/\\n/g, \" \") : text,\n };\n if (this.dimensions) {\n params.dimensions = this.dimensions;\n }\n if (this.encodingFormat) {\n params.encoding_format = this.encodingFormat;\n }\n const { data } = await this.embeddingWithRetry(params);\n return data[0].embedding as TOutput;\n }\n\n /**\n * Private method to make a request to the OpenAI API to generate\n * embeddings. Handles the retry logic and returns the response from the\n * API.\n * @param request Request to send to the OpenAI API.\n * @returns Promise that resolves to the response from the API.\n */\n protected async embeddingWithRetry(\n request: OpenAIClient.EmbeddingCreateParams\n ) {\n if (!this.client) {\n const openAIEndpointConfig: OpenAIEndpointConfig = {\n baseURL: this.clientConfig.baseURL,\n };\n\n const endpoint = getEndpoint(openAIEndpointConfig);\n\n const params = {\n ...this.clientConfig,\n baseURL: endpoint,\n timeout: this.timeout,\n maxRetries: 0,\n };\n\n if (!params.baseURL) {\n delete params.baseURL;\n }\n\n params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders);\n\n this.client = new OpenAIClient(params);\n }\n const requestOptions = {};\n\n return this.caller.call(async () => {\n try {\n const res = await this.client.embeddings.create(\n request,\n requestOptions\n );\n return res;\n } catch (e) {\n const error = wrapOpenAIClientError(e);\n throw error;\n }\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+EA,IAAa,mBAAb,cACUA,2BAAAA,WAEV;CACE,QAAQ;;CAGR;CAEA,YAAY;CAGZ,gBAAgB;;;;;CAMhB;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,YACE,QAWA;EACA,MAAM,qBAAqB;GAAE,gBAAgB;GAAG,GAAG;EAAO;EAE1D,MAAM,kBAAkB;EAExB,MAAM,SACJ,oBAAoB,UACpB,oBAAoB,iBAAA,GAAA,0BAAA,uBAAA,CACG,gBAAgB;EAEzC,KAAK,eACH,oBAAoB,eAAe,iBAAA,GAAA,0BAAA,uBAAA,CACZ,qBAAqB;EAE9C,KAAK,QACH,oBAAoB,SAAS,oBAAoB,aAAa,KAAK;EACrE,KAAK,YAAY,KAAK;EACtB,KAAK,YAAY,oBAAoB,aAAa,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B;;;;;;;;CASA,MAAgB,mBACd,SACA;EACA,IAAI,CAAC,KAAK,QAAQ;GAKhB,MAAM,WAAWC,cAAAA,YAAY,EAH3B,SAAS,KAAK,aAAa,QAGmB,CAAC;GAEjD,MAAM,SAAS;IACb,GAAG,KAAK;IACR,SAAS;IACT,SAAS,KAAK;IACd,YAAY;GACd;GAEA,IAAI,CAAC,OAAO,SACV,OAAO,OAAO;GAGhB,OAAO,iBAAiBC,cAAAA,wBAAwB,OAAO,cAAc;GAErE,KAAK,SAAS,IAAIC,OAAAA,OAAa,MAAM;EACvC;EACA,MAAM,iBAAiB,CAAC;EAExB,OAAO,KAAK,OAAO,KAAK,YAAY;GAClC,IAAI;IAKF,OAAO,MAJW,KAAK,OAAO,WAAW,OACvC,SACA,cACF;GAEF,SAAS,GAAG;IAEV,MADcC,eAAAA,sBAAsB,CAC1B;GACZ;EACF,CAAC;CACH;AACF"}
|
package/dist/embeddings.d.cts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { OpenAIApiKey } from "./types.cjs";
|
|
2
2
|
import { ClientOptions, OpenAI } from "openai";
|
|
3
3
|
import { Embeddings, EmbeddingsParams } from "@langchain/core/embeddings";
|
|
4
|
-
|
|
5
4
|
//#region src/embeddings.d.ts
|
|
6
5
|
/**
|
|
7
6
|
* @see https://platform.openai.com/docs/guides/embeddings#embedding-models
|
|
@@ -84,7 +83,8 @@ declare class OpenAIEmbeddings<TOutput = number[]> extends Embeddings<TOutput> i
|
|
|
84
83
|
* The OpenAI API key to use.
|
|
85
84
|
* Alias for `apiKey`.
|
|
86
85
|
*/
|
|
87
|
-
openAIApiKey?: OpenAIApiKey;
|
|
86
|
+
openAIApiKey?: OpenAIApiKey;
|
|
87
|
+
/** The OpenAI API key to use. */
|
|
88
88
|
apiKey?: OpenAIApiKey;
|
|
89
89
|
configuration?: ClientOptions;
|
|
90
90
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"embeddings.d.cts","names":[],"sources":["../src/embeddings.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"embeddings.d.cts","names":[],"sources":["../src/embeddings.ts"],"mappings":";;;;;;;KAeY,yBACR,OAAa,2BACH;;;;;UAMG,+BAA+B;;;;;;EAM9C,WAAW;;EAEX,OAAO;;;;;EAMP;;;;EAKA;;;;;EAMA;;;;;;EAOA;;;;EAKA;;;;;;;;;;;;;;;;;;cAmBW,iBAAiB,4BACpB,WAAW,oBACR,QAAQ;EAEnB;;EAGA;EAEA;EAGA;;;;;EAMA;EAEA;EAEA;EAEA;YAEU,QAAQ;YAER,cAAc;YAEd,SAAS;EAEnB,YACE,SAAS,QAAQ;IACf;;;;;IAKA,eAAe;;IAEf,SAAS;IACT,gBAAgB;;;;;;;;;EAyCd,eAAe,kBAAkB,QAAQ;;;;;;;EAsCzC,WAAW,eAAe,QAAQ;;;;;;;;YAsBxB,mBACd,SAAS,OAAa,wBAAqB,QAAA,OAAA"}
|
package/dist/embeddings.d.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { OpenAIApiKey } from "./types.js";
|
|
2
2
|
import { ClientOptions, OpenAI } from "openai";
|
|
3
3
|
import { Embeddings, EmbeddingsParams } from "@langchain/core/embeddings";
|
|
4
|
-
|
|
5
4
|
//#region src/embeddings.d.ts
|
|
6
5
|
/**
|
|
7
6
|
* @see https://platform.openai.com/docs/guides/embeddings#embedding-models
|
|
@@ -84,7 +83,8 @@ declare class OpenAIEmbeddings<TOutput = number[]> extends Embeddings<TOutput> i
|
|
|
84
83
|
* The OpenAI API key to use.
|
|
85
84
|
* Alias for `apiKey`.
|
|
86
85
|
*/
|
|
87
|
-
openAIApiKey?: OpenAIApiKey;
|
|
86
|
+
openAIApiKey?: OpenAIApiKey;
|
|
87
|
+
/** The OpenAI API key to use. */
|
|
88
88
|
apiKey?: OpenAIApiKey;
|
|
89
89
|
configuration?: ClientOptions;
|
|
90
90
|
});
|
package/dist/embeddings.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"embeddings.d.ts","names":[],"sources":["../src/embeddings.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"embeddings.d.ts","names":[],"sources":["../src/embeddings.ts"],"mappings":";;;;;;;KAeY,yBACR,OAAa,2BACH;;;;;UAMG,+BAA+B;;;;;;EAM9C,WAAW;;EAEX,OAAO;;;;;EAMP;;;;EAKA;;;;;EAMA;;;;;;EAOA;;;;EAKA;;;;;;;;;;;;;;;;;;cAmBW,iBAAiB,4BACpB,WAAW,oBACR,QAAQ;EAEnB;;EAGA;EAEA;EAGA;;;;;EAMA;EAEA;EAEA;EAEA;YAEU,QAAQ;YAER,cAAc;YAEd,SAAS;EAEnB,YACE,SAAS,QAAQ;IACf;;;;;IAKA,eAAe;;IAEf,SAAS;IACT,gBAAgB;;;;;;;;;EAyCd,eAAe,kBAAkB,QAAQ;;;;;;;EAsCzC,WAAW,eAAe,QAAQ;;;;;;;;YAsBxB,mBACd,SAAS,OAAa,wBAAqB,QAAA,OAAA"}
|
package/dist/embeddings.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"embeddings.js","names":["OpenAIClient"],"sources":["../src/embeddings.ts"],"sourcesContent":["import { type ClientOptions, OpenAI as OpenAIClient } from \"openai\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { Embeddings, type EmbeddingsParams } from \"@langchain/core/embeddings\";\nimport { chunkArray } from \"@langchain/core/utils/chunk_array\";\nimport type { OpenAIApiKey } from \"./types.js\";\nimport {\n getEndpoint,\n OpenAIEndpointConfig,\n getHeadersWithUserAgent,\n} from \"./utils/azure.js\";\nimport { wrapOpenAIClientError } from \"./utils/client.js\";\n\n/**\n * @see https://platform.openai.com/docs/guides/embeddings#embedding-models\n */\nexport type OpenAIEmbeddingModelId =\n | OpenAIClient.EmbeddingModel\n | (string & NonNullable<unknown>);\n\n/**\n * Interface for OpenAIEmbeddings parameters. Extends EmbeddingsParams and\n * defines additional parameters specific to the OpenAIEmbeddings class.\n */\nexport interface OpenAIEmbeddingsParams extends EmbeddingsParams {\n /**\n * Model name to use\n * Alias for `model`\n * @deprecated Use \"model\" instead.\n */\n modelName: OpenAIEmbeddingModelId;\n /** Model name to use */\n model: OpenAIEmbeddingModelId;\n\n /**\n * The number of dimensions the resulting output embeddings should have.\n * Only supported in `text-embedding-3` and later models.\n */\n dimensions?: number;\n\n /**\n * Timeout to use when making requests to OpenAI.\n */\n timeout?: number;\n\n /**\n * The maximum number of documents to embed in a single request. This is\n * limited by the OpenAI API to a maximum of 2048.\n */\n batchSize?: number;\n\n /**\n * Whether to strip new lines from the input text. This is recommended by\n * OpenAI for older models, but may not be suitable for all use cases.\n * See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500\n */\n stripNewLines?: boolean;\n\n /**\n * The format to return the embeddings in. Can be either 'float' or 'base64'.\n */\n encodingFormat?: \"float\" | \"base64\";\n}\n\n/**\n * Class for generating embeddings using the OpenAI API.\n *\n * To use with Azure, import the `AzureOpenAIEmbeddings` class.\n *\n * @example\n * ```typescript\n * // Embed a query using OpenAIEmbeddings to generate embeddings for a given text\n * const model = new OpenAIEmbeddings();\n * const res = await model.embedQuery(\n * \"What would be a good company name for a company that makes colorful socks?\",\n * );\n * console.log({ res });\n *\n * ```\n */\nexport class OpenAIEmbeddings<TOutput = number[]>\n extends Embeddings<TOutput>\n implements Partial<OpenAIEmbeddingsParams>\n{\n model = \"text-embedding-ada-002\";\n\n /** @deprecated Use \"model\" instead */\n modelName: string;\n\n batchSize = 512;\n\n // TODO: Update to `false` on next minor release (see: https://github.com/langchain-ai/langchainjs/pull/3612)\n stripNewLines = true;\n\n /**\n * The number of dimensions the resulting output embeddings should have.\n * Only supported in `text-embedding-3` and later models.\n */\n dimensions?: number;\n\n timeout?: number;\n\n organization?: string;\n\n encodingFormat?: \"float\" | \"base64\";\n\n protected client: OpenAIClient;\n\n protected clientConfig: ClientOptions;\n\n protected apiKey?: OpenAIApiKey;\n\n constructor(\n fields?: Partial<OpenAIEmbeddingsParams> & {\n verbose?: boolean;\n /**\n * The OpenAI API key to use.\n * Alias for `apiKey`.\n */\n openAIApiKey?: OpenAIApiKey;\n /** The OpenAI API key to use. */\n apiKey?: OpenAIApiKey;\n configuration?: ClientOptions;\n }\n ) {\n const fieldsWithDefaults = { maxConcurrency: 2, ...fields };\n\n super(fieldsWithDefaults);\n\n const apiKey =\n fieldsWithDefaults?.apiKey ??\n fieldsWithDefaults?.openAIApiKey ??\n getEnvironmentVariable(\"OPENAI_API_KEY\");\n\n this.organization =\n fieldsWithDefaults?.configuration?.organization ??\n getEnvironmentVariable(\"OPENAI_ORGANIZATION\");\n\n this.model =\n fieldsWithDefaults?.model ?? fieldsWithDefaults?.modelName ?? this.model;\n this.modelName = this.model;\n this.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize;\n this.stripNewLines =\n fieldsWithDefaults?.stripNewLines ?? this.stripNewLines;\n this.timeout = fieldsWithDefaults?.timeout;\n this.dimensions = fieldsWithDefaults?.dimensions;\n this.encodingFormat = fieldsWithDefaults?.encodingFormat;\n\n this.clientConfig = {\n apiKey,\n organization: this.organization,\n dangerouslyAllowBrowser: true,\n ...fields?.configuration,\n };\n }\n\n /**\n * Method to generate embeddings for an array of documents. Splits the\n * documents into batches and makes requests to the OpenAI API to generate\n * embeddings.\n * @param texts Array of documents to generate embeddings for.\n * @returns Promise that resolves to a 2D array of embeddings for each document.\n */\n async embedDocuments(texts: string[]): Promise<TOutput[]> {\n const batches = chunkArray(\n this.stripNewLines ? texts.map((t) => t.replace(/\\n/g, \" \")) : texts,\n this.batchSize\n );\n\n const batchRequests = batches.map((batch) => {\n const params: OpenAIClient.EmbeddingCreateParams = {\n model: this.model,\n input: batch,\n };\n if (this.dimensions) {\n params.dimensions = this.dimensions;\n }\n if (this.encodingFormat) {\n params.encoding_format = this.encodingFormat;\n }\n return this.embeddingWithRetry(params);\n });\n const batchResponses = await Promise.all(batchRequests);\n\n const embeddings: TOutput[] = [];\n for (let i = 0; i < batchResponses.length; i += 1) {\n const batch = batches[i];\n const { data: batchResponse } = batchResponses[i];\n for (let j = 0; j < batch.length; j += 1) {\n embeddings.push(batchResponse[j].embedding as TOutput);\n }\n }\n return embeddings;\n }\n\n /**\n * Method to generate an embedding for a single document. Calls the\n * embeddingWithRetry method with the document as the input.\n * @param text Document to generate an embedding for.\n * @returns Promise that resolves to an embedding for the document.\n */\n async embedQuery(text: string): Promise<TOutput> {\n const params: OpenAIClient.EmbeddingCreateParams = {\n model: this.model,\n input: this.stripNewLines ? text.replace(/\\n/g, \" \") : text,\n };\n if (this.dimensions) {\n params.dimensions = this.dimensions;\n }\n if (this.encodingFormat) {\n params.encoding_format = this.encodingFormat;\n }\n const { data } = await this.embeddingWithRetry(params);\n return data[0].embedding as TOutput;\n }\n\n /**\n * Private method to make a request to the OpenAI API to generate\n * embeddings. Handles the retry logic and returns the response from the\n * API.\n * @param request Request to send to the OpenAI API.\n * @returns Promise that resolves to the response from the API.\n */\n protected async embeddingWithRetry(\n request: OpenAIClient.EmbeddingCreateParams\n ) {\n if (!this.client) {\n const openAIEndpointConfig: OpenAIEndpointConfig = {\n baseURL: this.clientConfig.baseURL,\n };\n\n const endpoint = getEndpoint(openAIEndpointConfig);\n\n const params = {\n ...this.clientConfig,\n baseURL: endpoint,\n timeout: this.timeout,\n maxRetries: 0,\n };\n\n if (!params.baseURL) {\n delete params.baseURL;\n }\n\n params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders);\n\n this.client = new OpenAIClient(params);\n }\n const requestOptions = {};\n\n return this.caller.call(async () => {\n try {\n const res = await this.client.embeddings.create(\n request,\n requestOptions\n );\n return res;\n } catch (e) {\n const error = wrapOpenAIClientError(e);\n throw error;\n }\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA+EA,IAAa,mBAAb,cACU,WAEV;CACE,QAAQ;;CAGR;CAEA,YAAY;CAGZ,gBAAgB;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AAqB;;AAG1D,SAAO;;;;;;;;CAST,MAAM,WAAW,MAAgC;EAC/C,MAAM,SAA6C;GACjD,OAAO,KAAK;GACZ,OAAO,KAAK,gBAAgB,KAAK,QAAQ,OAAO,IAAI,GAAG;GACxD;AACD,MAAI,KAAK,WACP,QAAO,aAAa,KAAK;AAE3B,MAAI,KAAK,eACP,QAAO,kBAAkB,KAAK;EAEhC,MAAM,EAAE,SAAS,MAAM,KAAK,mBAAmB,OAAO;AACtD,SAAO,KAAK,GAAG;;;;;;;;;CAUjB,MAAgB,mBACd,SACA;AACA,MAAI,CAAC,KAAK,QAAQ;GAKhB,MAAM,WAAW,YAAY,EAH3B,SAAS,KAAK,aAAa,SAGoB,CAAC;GAElD,MAAM,SAAS;IACb,GAAG,KAAK;IACR,SAAS;IACT,SAAS,KAAK;IACd,YAAY;IACb;AAED,OAAI,CAAC,OAAO,QACV,QAAO,OAAO;AAGhB,UAAO,iBAAiB,wBAAwB,OAAO,eAAe;AAEtE,QAAK,SAAS,IAAIA,OAAa,OAAO;;EAExC,MAAM,iBAAiB,EAAE;AAEzB,SAAO,KAAK,OAAO,KAAK,YAAY;AAClC,OAAI;AAKF,WAAO,MAJW,KAAK,OAAO,WAAW,OACvC,SACA,eACD;YAEM,GAAG;AAEV,UADc,sBAAsB,EACzB;;IAEb"}
|
|
1
|
+
{"version":3,"file":"embeddings.js","names":["OpenAIClient"],"sources":["../src/embeddings.ts"],"sourcesContent":["import { type ClientOptions, OpenAI as OpenAIClient } from \"openai\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { Embeddings, type EmbeddingsParams } from \"@langchain/core/embeddings\";\nimport { chunkArray } from \"@langchain/core/utils/chunk_array\";\nimport type { OpenAIApiKey } from \"./types.js\";\nimport {\n getEndpoint,\n OpenAIEndpointConfig,\n getHeadersWithUserAgent,\n} from \"./utils/azure.js\";\nimport { wrapOpenAIClientError } from \"./utils/client.js\";\n\n/**\n * @see https://platform.openai.com/docs/guides/embeddings#embedding-models\n */\nexport type OpenAIEmbeddingModelId =\n | OpenAIClient.EmbeddingModel\n | (string & NonNullable<unknown>);\n\n/**\n * Interface for OpenAIEmbeddings parameters. Extends EmbeddingsParams and\n * defines additional parameters specific to the OpenAIEmbeddings class.\n */\nexport interface OpenAIEmbeddingsParams extends EmbeddingsParams {\n /**\n * Model name to use\n * Alias for `model`\n * @deprecated Use \"model\" instead.\n */\n modelName: OpenAIEmbeddingModelId;\n /** Model name to use */\n model: OpenAIEmbeddingModelId;\n\n /**\n * The number of dimensions the resulting output embeddings should have.\n * Only supported in `text-embedding-3` and later models.\n */\n dimensions?: number;\n\n /**\n * Timeout to use when making requests to OpenAI.\n */\n timeout?: number;\n\n /**\n * The maximum number of documents to embed in a single request. This is\n * limited by the OpenAI API to a maximum of 2048.\n */\n batchSize?: number;\n\n /**\n * Whether to strip new lines from the input text. This is recommended by\n * OpenAI for older models, but may not be suitable for all use cases.\n * See: https://github.com/openai/openai-python/issues/418#issuecomment-1525939500\n */\n stripNewLines?: boolean;\n\n /**\n * The format to return the embeddings in. Can be either 'float' or 'base64'.\n */\n encodingFormat?: \"float\" | \"base64\";\n}\n\n/**\n * Class for generating embeddings using the OpenAI API.\n *\n * To use with Azure, import the `AzureOpenAIEmbeddings` class.\n *\n * @example\n * ```typescript\n * // Embed a query using OpenAIEmbeddings to generate embeddings for a given text\n * const model = new OpenAIEmbeddings();\n * const res = await model.embedQuery(\n * \"What would be a good company name for a company that makes colorful socks?\",\n * );\n * console.log({ res });\n *\n * ```\n */\nexport class OpenAIEmbeddings<TOutput = number[]>\n extends Embeddings<TOutput>\n implements Partial<OpenAIEmbeddingsParams>\n{\n model = \"text-embedding-ada-002\";\n\n /** @deprecated Use \"model\" instead */\n modelName: string;\n\n batchSize = 512;\n\n // TODO: Update to `false` on next minor release (see: https://github.com/langchain-ai/langchainjs/pull/3612)\n stripNewLines = true;\n\n /**\n * The number of dimensions the resulting output embeddings should have.\n * Only supported in `text-embedding-3` and later models.\n */\n dimensions?: number;\n\n timeout?: number;\n\n organization?: string;\n\n encodingFormat?: \"float\" | \"base64\";\n\n protected client: OpenAIClient;\n\n protected clientConfig: ClientOptions;\n\n protected apiKey?: OpenAIApiKey;\n\n constructor(\n fields?: Partial<OpenAIEmbeddingsParams> & {\n verbose?: boolean;\n /**\n * The OpenAI API key to use.\n * Alias for `apiKey`.\n */\n openAIApiKey?: OpenAIApiKey;\n /** The OpenAI API key to use. */\n apiKey?: OpenAIApiKey;\n configuration?: ClientOptions;\n }\n ) {\n const fieldsWithDefaults = { maxConcurrency: 2, ...fields };\n\n super(fieldsWithDefaults);\n\n const apiKey =\n fieldsWithDefaults?.apiKey ??\n fieldsWithDefaults?.openAIApiKey ??\n getEnvironmentVariable(\"OPENAI_API_KEY\");\n\n this.organization =\n fieldsWithDefaults?.configuration?.organization ??\n getEnvironmentVariable(\"OPENAI_ORGANIZATION\");\n\n this.model =\n fieldsWithDefaults?.model ?? fieldsWithDefaults?.modelName ?? this.model;\n this.modelName = this.model;\n this.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize;\n this.stripNewLines =\n fieldsWithDefaults?.stripNewLines ?? this.stripNewLines;\n this.timeout = fieldsWithDefaults?.timeout;\n this.dimensions = fieldsWithDefaults?.dimensions;\n this.encodingFormat = fieldsWithDefaults?.encodingFormat;\n\n this.clientConfig = {\n apiKey,\n organization: this.organization,\n dangerouslyAllowBrowser: true,\n ...fields?.configuration,\n };\n }\n\n /**\n * Method to generate embeddings for an array of documents. Splits the\n * documents into batches and makes requests to the OpenAI API to generate\n * embeddings.\n * @param texts Array of documents to generate embeddings for.\n * @returns Promise that resolves to a 2D array of embeddings for each document.\n */\n async embedDocuments(texts: string[]): Promise<TOutput[]> {\n const batches = chunkArray(\n this.stripNewLines ? texts.map((t) => t.replace(/\\n/g, \" \")) : texts,\n this.batchSize\n );\n\n const batchRequests = batches.map((batch) => {\n const params: OpenAIClient.EmbeddingCreateParams = {\n model: this.model,\n input: batch,\n };\n if (this.dimensions) {\n params.dimensions = this.dimensions;\n }\n if (this.encodingFormat) {\n params.encoding_format = this.encodingFormat;\n }\n return this.embeddingWithRetry(params);\n });\n const batchResponses = await Promise.all(batchRequests);\n\n const embeddings: TOutput[] = [];\n for (let i = 0; i < batchResponses.length; i += 1) {\n const batch = batches[i];\n const { data: batchResponse } = batchResponses[i];\n for (let j = 0; j < batch.length; j += 1) {\n embeddings.push(batchResponse[j].embedding as TOutput);\n }\n }\n return embeddings;\n }\n\n /**\n * Method to generate an embedding for a single document. Calls the\n * embeddingWithRetry method with the document as the input.\n * @param text Document to generate an embedding for.\n * @returns Promise that resolves to an embedding for the document.\n */\n async embedQuery(text: string): Promise<TOutput> {\n const params: OpenAIClient.EmbeddingCreateParams = {\n model: this.model,\n input: this.stripNewLines ? text.replace(/\\n/g, \" \") : text,\n };\n if (this.dimensions) {\n params.dimensions = this.dimensions;\n }\n if (this.encodingFormat) {\n params.encoding_format = this.encodingFormat;\n }\n const { data } = await this.embeddingWithRetry(params);\n return data[0].embedding as TOutput;\n }\n\n /**\n * Private method to make a request to the OpenAI API to generate\n * embeddings. Handles the retry logic and returns the response from the\n * API.\n * @param request Request to send to the OpenAI API.\n * @returns Promise that resolves to the response from the API.\n */\n protected async embeddingWithRetry(\n request: OpenAIClient.EmbeddingCreateParams\n ) {\n if (!this.client) {\n const openAIEndpointConfig: OpenAIEndpointConfig = {\n baseURL: this.clientConfig.baseURL,\n };\n\n const endpoint = getEndpoint(openAIEndpointConfig);\n\n const params = {\n ...this.clientConfig,\n baseURL: endpoint,\n timeout: this.timeout,\n maxRetries: 0,\n };\n\n if (!params.baseURL) {\n delete params.baseURL;\n }\n\n params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders);\n\n this.client = new OpenAIClient(params);\n }\n const requestOptions = {};\n\n return this.caller.call(async () => {\n try {\n const res = await this.client.embeddings.create(\n request,\n requestOptions\n );\n return res;\n } catch (e) {\n const error = wrapOpenAIClientError(e);\n throw error;\n }\n });\n }\n}\n"],"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AAM,EAAE,MAAM,kBAAkB,eAAe;GAC/C,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,GACrC,WAAW,KAAK,cAAc,EAAE,CAAC,SAAoB;EAEzD;EACA,OAAO;CACT;;;;;;;CAQA,MAAM,WAAW,MAAgC;EAC/C,MAAM,SAA6C;GACjD,OAAO,KAAK;GACZ,OAAO,KAAK,gBAAgB,KAAK,QAAQ,OAAO,GAAG,IAAI;EACzD;EACA,IAAI,KAAK,YACP,OAAO,aAAa,KAAK;EAE3B,IAAI,KAAK,gBACP,OAAO,kBAAkB,KAAK;EAEhC,MAAM,EAAE,SAAS,MAAM,KAAK,mBAAmB,MAAM;EACrD,OAAO,KAAK,EAAE,CAAC;CACjB;;;;;;;;CASA,MAAgB,mBACd,SACA;EACA,IAAI,CAAC,KAAK,QAAQ;GAKhB,MAAM,WAAW,YAAY,EAH3B,SAAS,KAAK,aAAa,QAGmB,CAAC;GAEjD,MAAM,SAAS;IACb,GAAG,KAAK;IACR,SAAS;IACT,SAAS,KAAK;IACd,YAAY;GACd;GAEA,IAAI,CAAC,OAAO,SACV,OAAO,OAAO;GAGhB,OAAO,iBAAiB,wBAAwB,OAAO,cAAc;GAErE,KAAK,SAAS,IAAIA,OAAa,MAAM;EACvC;EACA,MAAM,iBAAiB,CAAC;EAExB,OAAO,KAAK,OAAO,KAAK,YAAY;GAClC,IAAI;IAKF,OAAO,MAJW,KAAK,OAAO,WAAW,OACvC,SACA,cACF;GAEF,SAAS,GAAG;IAEV,MADc,sBAAsB,CAC1B;GACZ;EACF,CAAC;CACH;AACF"}
|
package/dist/index.d.cts
CHANGED
|
@@ -32,5 +32,6 @@ import { ConvertOpenAICompletionsStreamOptions, convertOpenAICompletionsStream }
|
|
|
32
32
|
import { ConvertOpenAIResponsesStreamOptions, convertOpenAIResponsesStream } from "./utils/responses_stream_events.cjs";
|
|
33
33
|
import { completionsApiContentBlockConverter, convertCompletionsDeltaToBaseMessageChunk, convertCompletionsMessageToBaseMessage, convertMessagesToCompletionsMessageParams, convertStandardContentBlockToCompletionsContentPart, convertStandardContentMessageToCompletionsMessage } from "./converters/completions.cjs";
|
|
34
34
|
import { ResponsesCreate, ResponsesCreateInvoke, ResponsesInputItem, ResponsesParse, ResponsesParseInvoke, convertMessagesToResponsesInput, convertReasoningSummaryToResponsesReasoningItem, convertResponsesDeltaToChatGenerationChunk, convertResponsesMessageToAIMessage, convertResponsesUsageToUsageMetadata, convertStandardContentMessageToResponsesInput } from "./converters/responses.cjs";
|
|
35
|
+
import "./converters/index.cjs";
|
|
35
36
|
import { ClientOptions, OpenAI as OpenAIClient, toFile } from "openai";
|
|
36
|
-
export { ApplyPatchCreateFileOperation, ApplyPatchDeleteFileOperation, ApplyPatchOperation, ApplyPatchOptions, ApplyPatchTool, ApplyPatchUpdateFileOperation, AzureChatOpenAI, AzureChatOpenAICompletions, type AzureChatOpenAIFields, AzureChatOpenAIResponses, AzureOpenAI, AzureOpenAIChatInput, AzureOpenAIEmbeddings, AzureOpenAIInput, BaseChatOpenAI, type BaseChatOpenAICallOptions, type BaseChatOpenAIFields, ChatOpenAI, type ChatOpenAICallOptions, ChatOpenAICompletions, type ChatOpenAICompletionsCallOptions, type ChatOpenAIFields, ChatOpenAIReasoningSummary, ChatOpenAIResponseFormat, ChatOpenAIResponses, type ChatOpenAIResponsesCallOptions, type ClientOptions, CodeInterpreterAutoContainer, CodeInterpreterMemoryLimit, CodeInterpreterOptions, CodeInterpreterTool, ComputerUseAction, ComputerUseClickAction, ComputerUseDoubleClickAction, ComputerUseDragAction, ComputerUseEnvironment, ComputerUseInput, ComputerUseKeypressAction, ComputerUseMoveAction, ComputerUseOptions, ComputerUseScreenshotAction, ComputerUseScrollAction, ComputerUseTool, ComputerUseTypeAction, ComputerUseWaitAction, type ConvertOpenAICompletionsStreamOptions, type ConvertOpenAIResponsesStreamOptions, DallEAPIWrapper, DallEAPIWrapperParams, FileSearchComparisonFilter, FileSearchComparisonType, FileSearchCompoundFilter, FileSearchFilter, FileSearchHybridSearchWeights, FileSearchOptions, FileSearchRankingOptions, FileSearchTool, HeadersLike, ImageGenerationInputMask, ImageGenerationOptions, ImageGenerationTool, LocalShellAction, LocalShellOptions, LocalShellTool, McpApprovalFilter, McpConnectorId, McpConnectorOptions, McpRemoteServerOptions, McpTool, McpToolFilter, OpenAI, OpenAIApiKey, OpenAIBaseInput, OpenAICacheRetentionParam,
|
|
37
|
+
export { type ApplyPatchCreateFileOperation, type ApplyPatchDeleteFileOperation, type ApplyPatchOperation, type ApplyPatchOptions, type ApplyPatchTool, type ApplyPatchUpdateFileOperation, AzureChatOpenAI, AzureChatOpenAICompletions, type AzureChatOpenAIFields, AzureChatOpenAIResponses, AzureOpenAI, AzureOpenAIChatInput, AzureOpenAIEmbeddings, AzureOpenAIInput, BaseChatOpenAI, type BaseChatOpenAICallOptions, type BaseChatOpenAIFields, ChatOpenAI, type ChatOpenAICallOptions, ChatOpenAICompletions, type ChatOpenAICompletionsCallOptions, type ChatOpenAIFields, ChatOpenAIReasoningSummary, ChatOpenAIResponseFormat, ChatOpenAIResponses, type ChatOpenAIResponsesCallOptions, type ClientOptions, type CodeInterpreterAutoContainer, type CodeInterpreterMemoryLimit, type CodeInterpreterOptions, type CodeInterpreterTool, type ComputerUseAction, type ComputerUseClickAction, type ComputerUseDoubleClickAction, type ComputerUseDragAction, type ComputerUseEnvironment, type ComputerUseInput, type ComputerUseKeypressAction, type ComputerUseMoveAction, type ComputerUseOptions, type ComputerUseScreenshotAction, type ComputerUseScrollAction, type ComputerUseTool, type ComputerUseTypeAction, type ComputerUseWaitAction, type ConvertOpenAICompletionsStreamOptions, type ConvertOpenAIResponsesStreamOptions, DallEAPIWrapper, DallEAPIWrapperParams, type FileSearchComparisonFilter, type FileSearchComparisonType, type FileSearchCompoundFilter, type FileSearchFilter, type FileSearchHybridSearchWeights, type FileSearchOptions, type FileSearchRankingOptions, type FileSearchTool, HeadersLike, type ImageGenerationInputMask, type ImageGenerationOptions, type ImageGenerationTool, type LocalShellAction, type LocalShellOptions, type LocalShellTool, type McpApprovalFilter, type McpConnectorId, type McpConnectorOptions, type McpRemoteServerOptions, type McpTool, type McpToolFilter, OpenAI, OpenAIApiKey, OpenAIBaseInput, OpenAICacheRetentionParam, OpenAICallOptions, OpenAIChatInput, OpenAIChatModelId, OpenAIClient, OpenAICoreRequestOptions, OpenAIEmbeddingModelId, OpenAIEmbeddings, OpenAIEmbeddingsParams, OpenAIEndpointConfig, OpenAIImageModelId, OpenAIInput, OpenAIVerbosityParam, ResponseFormatConfiguration, ResponsesCreate, ResponsesCreateInvoke, ResponsesInputItem, ResponsesParse, ResponsesParseInvoke, type ShellAction, type ShellCallOutcome, type ShellCommandOutput, type ShellOptions, type ShellResult, type ShellTool, type TiktokenModel, type ToolSearchOptions, type ToolSearchTool, type WebSearchFilters, type WebSearchOptions, type WebSearchTool, completionsApiContentBlockConverter, convertCompletionsDeltaToBaseMessageChunk, convertCompletionsMessageToBaseMessage, convertMessagesToCompletionsMessageParams, convertMessagesToResponsesInput, convertOpenAICompletionsStream, convertOpenAIResponsesStream, convertPromptToOpenAI, convertReasoningSummaryToResponsesReasoningItem, convertResponsesDeltaToChatGenerationChunk, convertResponsesMessageToAIMessage, convertResponsesUsageToUsageMetadata, convertStandardContentBlockToCompletionsContentPart, convertStandardContentMessageToCompletionsMessage, convertStandardContentMessageToResponsesInput, customTool, getEndpoint, getFormattedEnv, getHeadersWithUserAgent, isHeaders, messageToOpenAIRole, normalizeHeaders, toFile, tools, wrapOpenAIClientError };
|