@langchain/openai 1.2.6 → 1.2.8-dev-1771365493298
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 +8 -0
- package/dist/azure/chat_models/common.cjs +9 -10
- package/dist/azure/chat_models/common.cjs.map +1 -1
- package/dist/azure/chat_models/common.d.cts +0 -1
- package/dist/azure/chat_models/common.d.cts.map +1 -1
- package/dist/azure/chat_models/common.d.ts +0 -1
- package/dist/azure/chat_models/common.d.ts.map +1 -1
- package/dist/azure/chat_models/common.js +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.map +1 -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 +0 -1
- 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.map +1 -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 +10 -13
- package/dist/azure/embeddings.cjs.map +1 -1
- package/dist/azure/embeddings.d.cts +1 -2
- package/dist/azure/embeddings.d.cts.map +1 -1
- package/dist/azure/embeddings.d.ts +1 -2
- package/dist/azure/embeddings.d.ts.map +1 -1
- package/dist/azure/embeddings.js +3 -5
- package/dist/azure/embeddings.js.map +1 -1
- package/dist/azure/llms.cjs +9 -10
- package/dist/azure/llms.cjs.map +1 -1
- package/dist/azure/llms.d.cts +2 -2
- package/dist/azure/llms.d.cts.map +1 -1
- package/dist/azure/llms.d.ts +2 -2
- package/dist/azure/llms.d.ts.map +1 -1
- package/dist/azure/llms.js +3 -3
- package/dist/azure/llms.js.map +1 -1
- package/dist/chat_models/base.cjs +38 -45
- package/dist/chat_models/base.cjs.map +1 -1
- package/dist/chat_models/base.d.cts.map +1 -1
- package/dist/chat_models/base.d.ts.map +1 -1
- package/dist/chat_models/base.js +10 -16
- package/dist/chat_models/base.js.map +1 -1
- package/dist/chat_models/completions.cjs +9 -13
- package/dist/chat_models/completions.cjs.map +1 -1
- package/dist/chat_models/completions.d.cts.map +1 -1
- package/dist/chat_models/completions.d.ts.map +1 -1
- package/dist/chat_models/completions.js +3 -6
- 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.map +1 -1
- 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 +1 -2
- package/dist/chat_models/profiles.cjs.map +1 -1
- package/dist/chat_models/profiles.js +1 -2
- package/dist/chat_models/profiles.js.map +1 -1
- package/dist/chat_models/responses.cjs +5 -7
- package/dist/chat_models/responses.cjs.map +1 -1
- package/dist/chat_models/responses.d.cts.map +1 -1
- package/dist/chat_models/responses.d.ts.map +1 -1
- package/dist/chat_models/responses.js +3 -4
- package/dist/chat_models/responses.js.map +1 -1
- package/dist/converters/completions.cjs +36 -45
- 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 +14 -22
- package/dist/converters/completions.js.map +1 -1
- package/dist/converters/index.js +2 -0
- package/dist/converters/responses.cjs +53 -55
- package/dist/converters/responses.cjs.map +1 -1
- package/dist/converters/responses.d.cts.map +1 -1
- package/dist/converters/responses.d.ts.map +1 -1
- package/dist/converters/responses.js +45 -46
- package/dist/converters/responses.js.map +1 -1
- package/dist/embeddings.cjs +11 -15
- package/dist/embeddings.cjs.map +1 -1
- package/dist/embeddings.d.cts +1 -3
- package/dist/embeddings.d.cts.map +1 -1
- package/dist/embeddings.d.ts +1 -3
- package/dist/embeddings.d.ts.map +1 -1
- package/dist/embeddings.js +3 -6
- package/dist/embeddings.js.map +1 -1
- package/dist/index.cjs +2 -2
- package/dist/llms.cjs +27 -33
- package/dist/llms.cjs.map +1 -1
- package/dist/llms.d.cts +0 -1
- package/dist/llms.d.cts.map +1 -1
- package/dist/llms.d.ts +0 -1
- package/dist/llms.d.ts.map +1 -1
- package/dist/llms.js +15 -20
- package/dist/llms.js.map +1 -1
- package/dist/tools/applyPatch.cjs +3 -4
- package/dist/tools/applyPatch.cjs.map +1 -1
- package/dist/tools/applyPatch.d.cts +0 -1
- package/dist/tools/applyPatch.d.cts.map +1 -1
- package/dist/tools/applyPatch.d.ts +0 -1
- package/dist/tools/applyPatch.d.ts.map +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 +7 -13
- package/dist/tools/computerUse.cjs.map +1 -1
- package/dist/tools/computerUse.d.cts +0 -1
- package/dist/tools/computerUse.d.cts.map +1 -1
- package/dist/tools/computerUse.d.ts +0 -1
- package/dist/tools/computerUse.d.ts.map +1 -1
- package/dist/tools/computerUse.js +1 -6
- package/dist/tools/computerUse.js.map +1 -1
- package/dist/tools/custom.cjs +6 -7
- package/dist/tools/custom.cjs.map +1 -1
- package/dist/tools/custom.d.cts.map +1 -1
- package/dist/tools/custom.d.ts.map +1 -1
- package/dist/tools/custom.js.map +1 -1
- package/dist/tools/dalle.cjs +10 -16
- 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 +6 -11
- 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.map +1 -1
- package/dist/tools/index.d.cts +0 -1
- package/dist/tools/index.d.cts.map +1 -1
- package/dist/tools/index.d.ts +0 -1
- package/dist/tools/index.d.ts.map +1 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/localShell.cjs +3 -4
- package/dist/tools/localShell.cjs.map +1 -1
- package/dist/tools/localShell.d.cts +0 -1
- package/dist/tools/localShell.d.cts.map +1 -1
- package/dist/tools/localShell.d.ts +0 -1
- package/dist/tools/localShell.d.ts.map +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 +3 -4
- package/dist/tools/shell.cjs.map +1 -1
- package/dist/tools/shell.d.cts +0 -1
- package/dist/tools/shell.d.cts.map +1 -1
- package/dist/tools/shell.d.ts +0 -1
- package/dist/tools/shell.d.ts.map +1 -1
- package/dist/tools/shell.js.map +1 -1
- package/dist/tools/webSearch.cjs.map +1 -1
- package/dist/tools/webSearch.d.cts +0 -1
- package/dist/tools/webSearch.d.cts.map +1 -1
- package/dist/tools/webSearch.d.ts +0 -1
- 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 +2 -3
- 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 +9 -3
- 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 +8 -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 -3
- 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.map +1 -1
- package/dist/utils/output.cjs +7 -8
- package/dist/utils/output.cjs.map +1 -1
- package/dist/utils/output.js.map +1 -1
- package/dist/utils/prompts.cjs +1 -2
- 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 +1 -2
- package/dist/utils/prompts.js.map +1 -1
- package/dist/utils/tools.cjs +9 -12
- package/dist/utils/tools.cjs.map +1 -1
- package/dist/utils/tools.d.cts +0 -1
- package/dist/utils/tools.d.cts.map +1 -1
- package/dist/utils/tools.d.ts +0 -1
- package/dist/utils/tools.d.ts.map +1 -1
- package/dist/utils/tools.js +5 -7
- package/dist/utils/tools.js.map +1 -1
- package/package.json +5 -5
- package/dist/_virtual/rolldown_runtime.cjs +0 -25
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"completions.js","names":["completionsApiContentBlockConverter: StandardContentBlockConverter<{\n text: ChatCompletionContentPartText;\n image: ChatCompletionContentPartImage;\n audio: ChatCompletionContentPartInputAudio;\n file: ChatCompletionContentPart.File;\n}>","mimeType: { type: string; subtype: string }","convertCompletionsMessageToBaseMessage: Converter<\n {\n message: OpenAIClient.Chat.Completions.ChatCompletionMessage;\n rawResponse: OpenAIClient.Chat.Completions.ChatCompletion;\n includeRawResponse?: boolean;\n },\n BaseMessage\n>","rawToolCalls: OpenAIToolCall[] | undefined","e: any","additional_kwargs: Record<string, unknown>","response_metadata: Record<string, unknown> | undefined","convertCompletionsDeltaToBaseMessageChunk: Converter<\n {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n delta: Record<string, any>;\n rawResponse: OpenAIClient.Chat.Completions.ChatCompletionChunk;\n includeRawResponse?: boolean;\n defaultRole?: OpenAIClient.Chat.ChatCompletionRole;\n },\n BaseMessageChunk\n>","toolCallChunks: ToolCallChunk[]","convertStandardContentBlockToCompletionsContentPart: Converter<\n ContentBlock.Standard,\n | OpenAIClient.Chat.Completions.ChatCompletionContentPartImage\n | OpenAIClient.Chat.Completions.ChatCompletionContentPartInputAudio\n | OpenAIClient.Chat.Completions.ChatCompletionContentPart.File\n | undefined\n>","format","convertStandardContentMessageToCompletionsMessage: Converter<\n { message: BaseMessage; model?: string },\n OpenAIClient.Chat.Completions.ChatCompletionMessageParam\n>","blocks: ContentBlock.Standard[]","convertMessagesToCompletionsMessageParams: Converter<\n { messages: BaseMessage[]; model?: string },\n OpenAIClient.Chat.Completions.ChatCompletionMessageParam[]\n>","completionParam: Record<string, any>"],"sources":["../../src/converters/completions.ts"],"sourcesContent":["import {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageChunk,\n ChatMessage,\n ChatMessageChunk,\n FunctionMessageChunk,\n HumanMessageChunk,\n OpenAIToolCall,\n SystemMessageChunk,\n ToolCallChunk,\n ToolMessage,\n ToolMessageChunk,\n parseBase64DataUrl,\n parseMimeType,\n StandardContentBlockConverter,\n isDataContentBlock,\n ContentBlock,\n iife,\n convertToProviderContentBlock,\n} from \"@langchain/core/messages\";\nimport {\n convertLangChainToolCallToOpenAI,\n makeInvalidToolCall,\n parseToolCall,\n} from \"@langchain/core/output_parsers/openai_tools\";\nimport { Converter } from \"@langchain/core/utils/format\";\nimport type {\n ChatCompletionContentPartText,\n ChatCompletionContentPartImage,\n ChatCompletionContentPartInputAudio,\n ChatCompletionContentPart,\n} from \"openai/resources/chat/completions\";\nimport { OpenAI as OpenAIClient } from \"openai\";\nimport { handleMultiModalOutput } from \"../utils/output.js\";\nimport {\n getRequiredFilenameFromMetadata,\n isReasoningModel,\n messageToOpenAIRole,\n} from \"../utils/misc.js\";\n\n/**\n * @deprecated This converter is an internal detail of the OpenAI provider. Do not use it directly. This will be revisited in a future release.\n */\nexport const completionsApiContentBlockConverter: StandardContentBlockConverter<{\n text: ChatCompletionContentPartText;\n image: ChatCompletionContentPartImage;\n audio: ChatCompletionContentPartInputAudio;\n file: ChatCompletionContentPart.File;\n}> = {\n providerName: \"ChatOpenAI\",\n\n fromStandardTextBlock(block): ChatCompletionContentPartText {\n return { type: \"text\", text: block.text };\n },\n\n fromStandardImageBlock(block): ChatCompletionContentPartImage {\n if (block.source_type === \"url\") {\n return {\n type: \"image_url\",\n image_url: {\n url: block.url,\n ...(block.metadata?.detail\n ? { detail: block.metadata.detail as \"auto\" | \"low\" | \"high\" }\n : {}),\n },\n };\n }\n\n if (block.source_type === \"base64\") {\n const url = `data:${block.mime_type ?? \"\"};base64,${block.data}`;\n return {\n type: \"image_url\",\n image_url: {\n url,\n ...(block.metadata?.detail\n ? { detail: block.metadata.detail as \"auto\" | \"low\" | \"high\" }\n : {}),\n },\n };\n }\n\n throw new Error(\n `Image content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`\n );\n },\n\n fromStandardAudioBlock(block): ChatCompletionContentPartInputAudio {\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (!data) {\n throw new Error(\n `URL audio blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`\n );\n }\n\n const rawMimeType = data.mime_type || block.mime_type || \"\";\n let mimeType: { type: string; subtype: string };\n\n try {\n mimeType = parseMimeType(rawMimeType);\n } catch {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n if (\n mimeType.type !== \"audio\" ||\n (mimeType.subtype !== \"wav\" && mimeType.subtype !== \"mp3\")\n ) {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n return {\n type: \"input_audio\",\n input_audio: {\n format: mimeType.subtype,\n data: data.data,\n },\n };\n }\n\n if (block.source_type === \"base64\") {\n let mimeType: { type: string; subtype: string };\n\n try {\n mimeType = parseMimeType(block.mime_type ?? \"\");\n } catch {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n if (\n mimeType.type !== \"audio\" ||\n (mimeType.subtype !== \"wav\" && mimeType.subtype !== \"mp3\")\n ) {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n return {\n type: \"input_audio\",\n input_audio: {\n format: mimeType.subtype,\n data: block.data,\n },\n };\n }\n\n throw new Error(\n `Audio content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`\n );\n },\n\n fromStandardFileBlock(block): ChatCompletionContentPart.File {\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n\n const filename = getRequiredFilenameFromMetadata(block);\n\n if (!data) {\n throw new Error(\n `URL file blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`\n );\n }\n\n return {\n type: \"file\",\n file: {\n file_data: block.url, // formatted as base64 data URL\n ...(block.metadata?.filename || block.metadata?.name\n ? {\n filename,\n }\n : {}),\n },\n };\n }\n\n if (block.source_type === \"base64\") {\n const filename = getRequiredFilenameFromMetadata(block);\n\n return {\n type: \"file\",\n file: {\n file_data: `data:${block.mime_type ?? \"\"};base64,${block.data}`,\n ...(block.metadata?.filename ||\n block.metadata?.name ||\n block.metadata?.title\n ? {\n filename,\n }\n : {}),\n },\n };\n }\n\n if (block.source_type === \"id\") {\n return {\n type: \"file\",\n file: {\n file_id: block.id,\n },\n };\n }\n\n throw new Error(\n `File content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`\n );\n },\n};\n\n/**\n * Converts an OpenAI Chat Completions API message to a LangChain BaseMessage.\n *\n * This converter transforms messages from OpenAI's Chat Completions API format into\n * LangChain's internal message representation, handling various message types and\n * preserving metadata, tool calls, and other relevant information.\n *\n * @remarks\n * The converter handles the following message roles:\n * - `assistant`: Converted to {@link AIMessage} with support for tool calls, function calls,\n * audio content, and multi-modal outputs\n * - Other roles: Converted to generic {@link ChatMessage}\n *\n * For assistant messages, the converter:\n * - Parses and validates tool calls, separating valid and invalid calls\n * - Preserves function call information in additional_kwargs\n * - Includes usage statistics and system fingerprint in response_metadata\n * - Handles multi-modal content (text, images, audio)\n * - Optionally includes the raw API response for debugging\n *\n * @param params - Conversion parameters\n * @param params.message - The OpenAI chat completion message to convert\n * @param params.rawResponse - The complete raw response from OpenAI's API, used to extract\n * metadata like model name, usage statistics, and system fingerprint\n * @param params.includeRawResponse - If true, includes the raw OpenAI response in the\n * message's additional_kwargs under the `__raw_response` key. Useful for debugging\n * or accessing provider-specific fields. Defaults to false.\n *\n * @returns A LangChain BaseMessage instance:\n * - {@link AIMessage} for assistant messages with tool calls, metadata, and content\n * - {@link ChatMessage} for all other message types\n *\n * @example\n * ```typescript\n * const baseMessage = convertCompletionsMessageToBaseMessage({\n * message: {\n * role: \"assistant\",\n * content: \"Hello! How can I help you?\",\n * tool_calls: [\n * {\n * id: \"call_123\",\n * type: \"function\",\n * function: { name: \"get_weather\", arguments: '{\"location\":\"NYC\"}' }\n * }\n * ]\n * },\n * rawResponse: completionResponse,\n * includeRawResponse: true\n * });\n * // Returns an AIMessage with parsed tool calls and metadata\n * ```\n *\n * @throws {Error} If tool call parsing fails, the invalid tool call is captured in\n * the `invalid_tool_calls` array rather than throwing an error\n *\n */\nexport const convertCompletionsMessageToBaseMessage: Converter<\n {\n message: OpenAIClient.Chat.Completions.ChatCompletionMessage;\n rawResponse: OpenAIClient.Chat.Completions.ChatCompletion;\n includeRawResponse?: boolean;\n },\n BaseMessage\n> = ({ message, rawResponse, includeRawResponse }) => {\n const rawToolCalls: OpenAIToolCall[] | undefined = message.tool_calls as\n | OpenAIToolCall[]\n | undefined;\n switch (message.role) {\n case \"assistant\": {\n const toolCalls = [];\n const invalidToolCalls = [];\n for (const rawToolCall of rawToolCalls ?? []) {\n try {\n toolCalls.push(parseToolCall(rawToolCall, { returnId: true }));\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n invalidToolCalls.push(makeInvalidToolCall(rawToolCall, e.message));\n }\n }\n const additional_kwargs: Record<string, unknown> = {\n function_call: message.function_call,\n tool_calls: rawToolCalls,\n };\n if (includeRawResponse !== undefined) {\n additional_kwargs.__raw_response = rawResponse;\n }\n const response_metadata: Record<string, unknown> | undefined = {\n model_provider: \"openai\",\n model_name: rawResponse.model,\n ...(rawResponse.system_fingerprint\n ? {\n usage: { ...rawResponse.usage },\n system_fingerprint: rawResponse.system_fingerprint,\n }\n : {}),\n };\n\n if (message.audio) {\n additional_kwargs.audio = message.audio;\n }\n\n const content = handleMultiModalOutput(\n message.content || \"\",\n rawResponse.choices?.[0]?.message\n );\n return new AIMessage({\n content,\n tool_calls: toolCalls,\n invalid_tool_calls: invalidToolCalls,\n additional_kwargs,\n response_metadata,\n id: rawResponse.id,\n });\n }\n default:\n return new ChatMessage(message.content || \"\", message.role ?? \"unknown\");\n }\n};\n\n/**\n * Converts an OpenAI Chat Completions API delta (streaming chunk) to a LangChain BaseMessageChunk.\n *\n * This converter is used during streaming responses to transform incremental updates from OpenAI's\n * Chat Completions API into LangChain message chunks. It handles various message types, tool calls,\n * function calls, audio content, and role-specific message chunk creation.\n *\n * @param params - Conversion parameters\n * @param params.delta - The delta object from an OpenAI streaming chunk containing incremental\n * message updates. May include content, role, tool_calls, function_call, audio, etc.\n * @param params.rawResponse - The complete raw ChatCompletionChunk response from OpenAI,\n * containing metadata like model info, usage stats, and the delta\n * @param params.includeRawResponse - Optional flag to include the raw OpenAI response in the\n * message chunk's additional_kwargs. Useful for debugging or accessing provider-specific data\n * @param params.defaultRole - Optional default role to use if the delta doesn't specify one.\n * Typically used to maintain role consistency across chunks in a streaming response\n *\n * @returns A BaseMessageChunk subclass appropriate for the message role:\n * - HumanMessageChunk for \"user\" role\n * - AIMessageChunk for \"assistant\" role (includes tool call chunks)\n * - SystemMessageChunk for \"system\" or \"developer\" roles\n * - FunctionMessageChunk for \"function\" role\n * - ToolMessageChunk for \"tool\" role\n * - ChatMessageChunk for any other role\n *\n * @example\n * Basic streaming text chunk:\n * ```typescript\n * const chunk = convertCompletionsDeltaToBaseMessageChunk({\n * delta: { role: \"assistant\", content: \"Hello\" },\n * rawResponse: { id: \"chatcmpl-123\", model: \"gpt-4\", ... }\n * });\n * // Returns: AIMessageChunk with content \"Hello\"\n * ```\n *\n * @example\n * Streaming chunk with tool call:\n * ```typescript\n * const chunk = convertCompletionsDeltaToBaseMessageChunk({\n * delta: {\n * role: \"assistant\",\n * tool_calls: [{\n * index: 0,\n * id: \"call_123\",\n * function: { name: \"get_weather\", arguments: '{\"location\":' }\n * }]\n * },\n * rawResponse: { id: \"chatcmpl-123\", ... }\n * });\n * // Returns: AIMessageChunk with tool_call_chunks containing partial tool call data\n * ```\n *\n * @remarks\n * - Tool calls are converted to ToolCallChunk objects with incremental data\n * - Audio content includes the chunk index from the raw response\n * - The \"developer\" role is mapped to SystemMessageChunk with a special marker\n * - Response metadata includes model provider info and usage statistics\n * - Function calls and tool calls are stored in additional_kwargs for compatibility\n */\nexport const convertCompletionsDeltaToBaseMessageChunk: Converter<\n {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n delta: Record<string, any>;\n rawResponse: OpenAIClient.Chat.Completions.ChatCompletionChunk;\n includeRawResponse?: boolean;\n defaultRole?: OpenAIClient.Chat.ChatCompletionRole;\n },\n BaseMessageChunk\n> = ({ delta, rawResponse, includeRawResponse, defaultRole }) => {\n const role = delta.role ?? defaultRole;\n const content = delta.content ?? \"\";\n let additional_kwargs: Record<string, unknown>;\n if (delta.function_call) {\n additional_kwargs = {\n function_call: delta.function_call,\n };\n } else if (delta.tool_calls) {\n additional_kwargs = {\n tool_calls: delta.tool_calls,\n };\n } else {\n additional_kwargs = {};\n }\n if (includeRawResponse) {\n additional_kwargs.__raw_response = rawResponse;\n }\n\n if (delta.audio) {\n additional_kwargs.audio = {\n ...delta.audio,\n index: rawResponse.choices[0].index,\n };\n }\n\n const response_metadata = {\n model_provider: \"openai\",\n usage: { ...rawResponse.usage },\n };\n if (role === \"user\") {\n return new HumanMessageChunk({ content, response_metadata });\n } else if (role === \"assistant\") {\n const toolCallChunks: ToolCallChunk[] = [];\n if (Array.isArray(delta.tool_calls)) {\n for (const rawToolCall of delta.tool_calls) {\n toolCallChunks.push({\n name: rawToolCall.function?.name,\n args: rawToolCall.function?.arguments,\n id: rawToolCall.id,\n index: rawToolCall.index,\n type: \"tool_call_chunk\",\n });\n }\n }\n return new AIMessageChunk({\n content,\n tool_call_chunks: toolCallChunks,\n additional_kwargs,\n id: rawResponse.id,\n response_metadata,\n });\n } else if (role === \"system\") {\n return new SystemMessageChunk({ content, response_metadata });\n } else if (role === \"developer\") {\n return new SystemMessageChunk({\n content,\n response_metadata,\n additional_kwargs: {\n __openai_role__: \"developer\",\n },\n });\n } else if (role === \"function\") {\n return new FunctionMessageChunk({\n content,\n additional_kwargs,\n name: delta.name,\n response_metadata,\n });\n } else if (role === \"tool\") {\n return new ToolMessageChunk({\n content,\n additional_kwargs,\n tool_call_id: delta.tool_call_id,\n response_metadata,\n });\n } else {\n return new ChatMessageChunk({ content, role, response_metadata });\n }\n};\n\n/**\n * Converts a standard LangChain content block to an OpenAI Completions API content part.\n *\n * This converter transforms LangChain's standardized content blocks (image, audio, file)\n * into the format expected by OpenAI's Chat Completions API. It handles various content\n * types including images (URL or base64), audio (base64), and files (data or file ID).\n *\n * @param block - The standard content block to convert. Can be an image, audio, or file block.\n *\n * @returns An OpenAI Chat Completions content part object, or undefined if the block\n * cannot be converted (e.g., missing required data).\n *\n * @example\n * Image with URL:\n * ```typescript\n * const block = { type: \"image\", url: \"https://example.com/image.jpg\" };\n * const part = convertStandardContentBlockToCompletionsContentPart(block);\n * // Returns: { type: \"image_url\", image_url: { url: \"https://example.com/image.jpg\" } }\n * ```\n *\n * @example\n * Image with base64 data:\n * ```typescript\n * const block = { type: \"image\", data: \"iVBORw0KGgo...\", mimeType: \"image/png\" };\n * const part = convertStandardContentBlockToCompletionsContentPart(block);\n * // Returns: { type: \"image_url\", image_url: { url: \"data:image/png;base64,iVBORw0KGgo...\" } }\n * ```\n */\nexport const convertStandardContentBlockToCompletionsContentPart: Converter<\n ContentBlock.Standard,\n | OpenAIClient.Chat.Completions.ChatCompletionContentPartImage\n | OpenAIClient.Chat.Completions.ChatCompletionContentPartInputAudio\n | OpenAIClient.Chat.Completions.ChatCompletionContentPart.File\n | undefined\n> = (block) => {\n if (block.type === \"image\") {\n if (block.url) {\n return {\n type: \"image_url\",\n image_url: {\n url: block.url,\n },\n };\n } else if (block.data) {\n return {\n type: \"image_url\",\n image_url: {\n url: `data:${block.mimeType};base64,${block.data}`,\n },\n };\n }\n }\n if (block.type === \"audio\") {\n if (block.data) {\n const format = iife(() => {\n const [, format] = block.mimeType.split(\"/\");\n if (format === \"wav\" || format === \"mp3\") {\n return format;\n }\n return \"wav\";\n });\n return {\n type: \"input_audio\",\n input_audio: {\n data: block.data.toString(),\n format,\n },\n };\n }\n }\n if (block.type === \"file\") {\n if (block.data) {\n const filename = getRequiredFilenameFromMetadata(block);\n\n return {\n type: \"file\",\n file: {\n file_data: `data:${block.mimeType};base64,${block.data}`,\n filename: filename,\n },\n };\n }\n if (block.fileId) {\n return {\n type: \"file\",\n file: {\n file_id: block.fileId,\n },\n };\n }\n }\n return undefined;\n};\n\n/**\n * Converts a LangChain BaseMessage with standard content blocks to an OpenAI Chat Completions API message parameter.\n *\n * This converter transforms LangChain's standardized message format (using contentBlocks) into the format\n * expected by OpenAI's Chat Completions API. It handles role mapping, content filtering, and multi-modal\n * content conversion for various message types.\n *\n * @remarks\n * The converter performs the following transformations:\n * - Maps LangChain message roles to OpenAI API roles (user, assistant, system, developer, tool, function)\n * - For reasoning models, automatically converts \"system\" role to \"developer\" role\n * - Filters content blocks based on message role (most roles only include text blocks)\n * - For user messages, converts multi-modal content blocks (images, audio, files) to OpenAI format\n * - Preserves tool call IDs for tool messages and function names for function messages\n *\n * Role-specific behavior:\n * - **developer**: Returns only text content blocks (used for reasoning models)\n * - **system**: Returns only text content blocks\n * - **assistant**: Returns only text content blocks\n * - **tool**: Returns only text content blocks with tool_call_id preserved\n * - **function**: Returns text content blocks joined as a single string with function name\n * - **user** (default): Returns multi-modal content including text, images, audio, and files\n *\n * @param params - Conversion parameters\n * @param params.message - The LangChain BaseMessage to convert. Must have contentBlocks property\n * containing an array of standard content blocks (text, image, audio, file, etc.)\n * @param params.model - Optional model name. Used to determine if special role mapping is needed\n * (e.g., \"system\" -> \"developer\" for reasoning models like o1)\n *\n * @returns An OpenAI ChatCompletionMessageParam object formatted for the Chat Completions API.\n * The structure varies by role:\n * - Developer/System/Assistant: `{ role, content: TextBlock[] }`\n * - Tool: `{ role: \"tool\", tool_call_id, content: TextBlock[] }`\n * - Function: `{ role: \"function\", name, content: string }`\n * - User: `{ role: \"user\", content: Array<TextPart | ImagePart | AudioPart | FilePart> }`\n *\n * @example\n * Simple text message:\n * ```typescript\n * const message = new HumanMessage({\n * content: [{ type: \"text\", text: \"Hello!\" }]\n * });\n * const param = convertStandardContentMessageToCompletionsMessage({ message });\n * // Returns: { role: \"user\", content: [{ type: \"text\", text: \"Hello!\" }] }\n * ```\n *\n * @example\n * Multi-modal user message with image:\n * ```typescript\n * const message = new HumanMessage({\n * content: [\n * { type: \"text\", text: \"What's in this image?\" },\n * { type: \"image\", url: \"https://example.com/image.jpg\" }\n * ]\n * });\n * const param = convertStandardContentMessageToCompletionsMessage({ message });\n * // Returns: {\n * // role: \"user\",\n * // content: [\n * // { type: \"text\", text: \"What's in this image?\" },\n * // { type: \"image_url\", image_url: { url: \"https://example.com/image.jpg\" } }\n * // ]\n * // }\n * ```\n */\nexport const convertStandardContentMessageToCompletionsMessage: Converter<\n { message: BaseMessage; model?: string },\n OpenAIClient.Chat.Completions.ChatCompletionMessageParam\n> = ({ message, model }) => {\n let role = messageToOpenAIRole(message);\n if (role === \"system\" && isReasoningModel(model)) {\n role = \"developer\";\n }\n if (role === \"developer\") {\n return {\n role: \"developer\",\n content: message.contentBlocks.filter((block) => block.type === \"text\"),\n };\n } else if (role === \"system\") {\n return {\n role: \"system\",\n content: message.contentBlocks.filter((block) => block.type === \"text\"),\n };\n } else if (role === \"assistant\") {\n return {\n role: \"assistant\",\n content: message.contentBlocks.filter((block) => block.type === \"text\"),\n };\n } else if (role === \"tool\" && ToolMessage.isInstance(message)) {\n return {\n role: \"tool\",\n tool_call_id: message.tool_call_id,\n content: message.contentBlocks.filter((block) => block.type === \"text\"),\n };\n } else if (role === \"function\") {\n return {\n role: \"function\",\n name: message.name ?? \"\",\n content: message.contentBlocks\n .filter((block) => block.type === \"text\")\n .join(\"\"),\n };\n }\n // Default to user message handling\n function* iterateUserContent(blocks: ContentBlock.Standard[]) {\n for (const block of blocks) {\n if (block.type === \"text\") {\n yield {\n type: \"text\" as const,\n text: block.text,\n };\n }\n const data = convertStandardContentBlockToCompletionsContentPart(block);\n if (data) {\n yield data;\n }\n }\n }\n return {\n role: \"user\",\n content: Array.from(iterateUserContent(message.contentBlocks)),\n };\n};\n\n/**\n * Converts an array of LangChain BaseMessages to OpenAI Chat Completions API message parameters.\n *\n * This converter transforms LangChain's internal message representation into the format required\n * by OpenAI's Chat Completions API. It handles various message types, roles, content formats,\n * tool calls, function calls, audio messages, and special model-specific requirements.\n *\n * @remarks\n * The converter performs several key transformations:\n * - Maps LangChain message types to OpenAI roles (user, assistant, system, tool, function, developer)\n * - Converts standard content blocks (v1 format) using a specialized converter\n * - Handles multimodal content including text, images, audio, and data blocks\n * - Preserves tool calls and function calls with proper formatting\n * - Applies model-specific role mappings (e.g., \"system\" → \"developer\" for reasoning models)\n * - Splits audio messages into separate message parameters when needed\n *\n * @param params - Conversion parameters\n * @param params.messages - Array of LangChain BaseMessages to convert. Can include any message\n * type: HumanMessage, AIMessage, SystemMessage, ToolMessage, FunctionMessage, etc.\n * @param params.model - Optional model name used to determine if special role mapping is needed.\n * For reasoning models (o1, o3, etc.), \"system\" role is converted to \"developer\" role.\n *\n * @returns Array of ChatCompletionMessageParam objects formatted for OpenAI's Chat Completions API.\n * Some messages may be split into multiple parameters (e.g., audio messages).\n *\n * @example\n * Basic message conversion:\n * ```typescript\n * const messages = [\n * new HumanMessage(\"What's the weather like?\"),\n * new AIMessage(\"Let me check that for you.\")\n * ];\n *\n * const params = convertMessagesToCompletionsMessageParams({\n * messages,\n * model: \"gpt-4\"\n * });\n * // Returns:\n * // [\n * // { role: \"user\", content: \"What's the weather like?\" },\n * // { role: \"assistant\", content: \"Let me check that for you.\" }\n * // ]\n * ```\n *\n * @example\n * Message with tool calls:\n * ```typescript\n * const messages = [\n * new AIMessage({\n * content: \"\",\n * tool_calls: [{\n * id: \"call_123\",\n * name: \"get_weather\",\n * args: { location: \"San Francisco\" }\n * }]\n * })\n * ];\n *\n * const params = convertMessagesToCompletionsMessageParams({ messages });\n * // Returns:\n * // [{\n * // role: \"assistant\",\n * // content: \"\",\n * // tool_calls: [{\n * // id: \"call_123\",\n * // type: \"function\",\n * // function: { name: \"get_weather\", arguments: '{\"location\":\"San Francisco\"}' }\n * // }]\n * // }]\n * ```\n */\nexport const convertMessagesToCompletionsMessageParams: Converter<\n { messages: BaseMessage[]; model?: string },\n OpenAIClient.Chat.Completions.ChatCompletionMessageParam[]\n> = ({ messages, model }) => {\n return messages.flatMap((message) => {\n if (\n \"output_version\" in message.response_metadata &&\n message.response_metadata?.output_version === \"v1\"\n ) {\n return convertStandardContentMessageToCompletionsMessage({ message });\n }\n let role = messageToOpenAIRole(message);\n if (role === \"system\" && isReasoningModel(model)) {\n role = \"developer\";\n }\n\n const content =\n typeof message.content === \"string\"\n ? message.content\n : message.content.flatMap((m) => {\n if (isDataContentBlock(m)) {\n return convertToProviderContentBlock(\n m,\n completionsApiContentBlockConverter\n );\n }\n // Drop Anthropic tool_use blocks from content — these are\n // already represented in message.tool_calls and would cause\n // an API error if passed through to OpenAI.\n if (\n typeof m === \"object\" &&\n m !== null &&\n \"type\" in m &&\n m.type === \"tool_use\"\n ) {\n return [];\n }\n return m;\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const completionParam: Record<string, any> = {\n role,\n content,\n };\n if (message.name != null) {\n completionParam.name = message.name;\n }\n if (message.additional_kwargs.function_call != null) {\n completionParam.function_call = message.additional_kwargs.function_call;\n }\n if (AIMessage.isInstance(message) && !!message.tool_calls?.length) {\n completionParam.tool_calls = message.tool_calls.map(\n convertLangChainToolCallToOpenAI\n );\n } else {\n if (message.additional_kwargs.tool_calls != null) {\n completionParam.tool_calls = message.additional_kwargs.tool_calls;\n }\n if (ToolMessage.isInstance(message) && message.tool_call_id != null) {\n completionParam.tool_call_id = message.tool_call_id;\n }\n }\n\n if (\n message.additional_kwargs.audio &&\n typeof message.additional_kwargs.audio === \"object\" &&\n \"id\" in message.additional_kwargs.audio\n ) {\n const audioMessage = {\n role: \"assistant\",\n audio: {\n id: message.additional_kwargs.audio.id,\n },\n };\n return [\n completionParam,\n audioMessage,\n ] as OpenAIClient.Chat.Completions.ChatCompletionMessageParam[];\n }\n\n return completionParam as OpenAIClient.Chat.Completions.ChatCompletionMessageParam;\n });\n};\n"],"mappings":";;;;;;;;;AA6CA,MAAaA,sCAKR;CACH,cAAc;CAEd,sBAAsB,OAAsC;AAC1D,SAAO;GAAE,MAAM;GAAQ,MAAM,MAAM;EAAM;CAC1C;CAED,uBAAuB,OAAuC;AAC5D,MAAI,MAAM,gBAAgB,MACxB,QAAO;GACL,MAAM;GACN,WAAW;IACT,KAAK,MAAM;IACX,GAAI,MAAM,UAAU,SAChB,EAAE,QAAQ,MAAM,SAAS,OAAmC,IAC5D,CAAE;GACP;EACF;AAGH,MAAI,MAAM,gBAAgB,UAAU;GAClC,MAAM,MAAM,CAAC,KAAK,EAAE,MAAM,aAAa,GAAG,QAAQ,EAAE,MAAM,MAAM;AAChE,UAAO;IACL,MAAM;IACN,WAAW;KACT;KACA,GAAI,MAAM,UAAU,SAChB,EAAE,QAAQ,MAAM,SAAS,OAAmC,IAC5D,CAAE;IACP;GACF;EACF;AAED,QAAM,IAAI,MACR,CAAC,sCAAsC,EAAE,MAAM,YAAY,iCAAiC,CAAC;CAEhG;CAED,uBAAuB,OAA4C;AACjE,MAAI,MAAM,gBAAgB,OAAO;GAC/B,MAAM,OAAO,mBAAmB,EAAE,SAAS,MAAM,IAAK,EAAC;AACvD,OAAI,CAAC,KACH,OAAM,IAAI,MACR,CAAC,kCAAkC,EAAE,MAAM,YAAY,+CAA+C,CAAC;GAI3G,MAAM,cAAc,KAAK,aAAa,MAAM,aAAa;GACzD,IAAIC;AAEJ,OAAI;IACF,WAAW,cAAc,YAAY;GACtC,QAAO;AACN,UAAM,IAAI,MACR,CAAC,8BAA8B,EAAE,MAAM,YAAY,8CAA8C,CAAC;GAErG;AAED,OACE,SAAS,SAAS,WACjB,SAAS,YAAY,SAAS,SAAS,YAAY,MAEpD,OAAM,IAAI,MAC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QAAO,8BACL,GACA,oCACD;AAKH,OACE,OAAO,MAAM,YACb,MAAM,QACN,UAAU,KACV,EAAE,SAAS,WAEX,QAAO,CAAE;AAEX,UAAO;EACR,EAAC;EAER,MAAMC,kBAAuC;GAC3C;GACA;EACD;AACD,MAAI,QAAQ,QAAQ,MAClB,gBAAgB,OAAO,QAAQ;AAEjC,MAAI,QAAQ,kBAAkB,iBAAiB,MAC7C,gBAAgB,gBAAgB,QAAQ,kBAAkB;AAE5D,MAAI,UAAU,WAAW,QAAQ,IAAI,CAAC,CAAC,QAAQ,YAAY,QACzD,gBAAgB,aAAa,QAAQ,WAAW,IAC9C,iCACD;OACI;AACL,OAAI,QAAQ,kBAAkB,cAAc,MAC1C,gBAAgB,aAAa,QAAQ,kBAAkB;AAEzD,OAAI,YAAY,WAAW,QAAQ,IAAI,QAAQ,gBAAgB,MAC7D,gBAAgB,eAAe,QAAQ;EAE1C;AAED,MACE,QAAQ,kBAAkB,SAC1B,OAAO,QAAQ,kBAAkB,UAAU,YAC3C,QAAQ,QAAQ,kBAAkB,OAClC;GACA,MAAM,eAAe;IACnB,MAAM;IACN,OAAO,EACL,IAAI,QAAQ,kBAAkB,MAAM,GACrC;GACF;AACD,UAAO,CACL,iBACA,YACD;EACF;AAED,SAAO;CACR,EAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"completions.js","names":[],"sources":["../../src/converters/completions.ts"],"sourcesContent":["import {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n BaseMessageChunk,\n ChatMessage,\n ChatMessageChunk,\n FunctionMessageChunk,\n HumanMessageChunk,\n OpenAIToolCall,\n SystemMessageChunk,\n ToolCallChunk,\n ToolMessage,\n ToolMessageChunk,\n parseBase64DataUrl,\n parseMimeType,\n StandardContentBlockConverter,\n isDataContentBlock,\n ContentBlock,\n iife,\n convertToProviderContentBlock,\n} from \"@langchain/core/messages\";\nimport {\n convertLangChainToolCallToOpenAI,\n makeInvalidToolCall,\n parseToolCall,\n} from \"@langchain/core/output_parsers/openai_tools\";\nimport { Converter } from \"@langchain/core/utils/format\";\nimport type {\n ChatCompletionContentPartText,\n ChatCompletionContentPartImage,\n ChatCompletionContentPartInputAudio,\n ChatCompletionContentPart,\n} from \"openai/resources/chat/completions\";\nimport { OpenAI as OpenAIClient } from \"openai\";\nimport { handleMultiModalOutput } from \"../utils/output.js\";\nimport {\n getRequiredFilenameFromMetadata,\n isReasoningModel,\n messageToOpenAIRole,\n} from \"../utils/misc.js\";\n\n/**\n * @deprecated This converter is an internal detail of the OpenAI provider. Do not use it directly. This will be revisited in a future release.\n */\nexport const completionsApiContentBlockConverter: StandardContentBlockConverter<{\n text: ChatCompletionContentPartText;\n image: ChatCompletionContentPartImage;\n audio: ChatCompletionContentPartInputAudio;\n file: ChatCompletionContentPart.File;\n}> = {\n providerName: \"ChatOpenAI\",\n\n fromStandardTextBlock(block): ChatCompletionContentPartText {\n return { type: \"text\", text: block.text };\n },\n\n fromStandardImageBlock(block): ChatCompletionContentPartImage {\n if (block.source_type === \"url\") {\n return {\n type: \"image_url\",\n image_url: {\n url: block.url,\n ...(block.metadata?.detail\n ? { detail: block.metadata.detail as \"auto\" | \"low\" | \"high\" }\n : {}),\n },\n };\n }\n\n if (block.source_type === \"base64\") {\n const url = `data:${block.mime_type ?? \"\"};base64,${block.data}`;\n return {\n type: \"image_url\",\n image_url: {\n url,\n ...(block.metadata?.detail\n ? { detail: block.metadata.detail as \"auto\" | \"low\" | \"high\" }\n : {}),\n },\n };\n }\n\n throw new Error(\n `Image content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`\n );\n },\n\n fromStandardAudioBlock(block): ChatCompletionContentPartInputAudio {\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (!data) {\n throw new Error(\n `URL audio blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`\n );\n }\n\n const rawMimeType = data.mime_type || block.mime_type || \"\";\n let mimeType: { type: string; subtype: string };\n\n try {\n mimeType = parseMimeType(rawMimeType);\n } catch {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n if (\n mimeType.type !== \"audio\" ||\n (mimeType.subtype !== \"wav\" && mimeType.subtype !== \"mp3\")\n ) {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n return {\n type: \"input_audio\",\n input_audio: {\n format: mimeType.subtype,\n data: data.data,\n },\n };\n }\n\n if (block.source_type === \"base64\") {\n let mimeType: { type: string; subtype: string };\n\n try {\n mimeType = parseMimeType(block.mime_type ?? \"\");\n } catch {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n if (\n mimeType.type !== \"audio\" ||\n (mimeType.subtype !== \"wav\" && mimeType.subtype !== \"mp3\")\n ) {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n return {\n type: \"input_audio\",\n input_audio: {\n format: mimeType.subtype,\n data: block.data,\n },\n };\n }\n\n throw new Error(\n `Audio content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`\n );\n },\n\n fromStandardFileBlock(block): ChatCompletionContentPart.File {\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n\n const filename = getRequiredFilenameFromMetadata(block);\n\n if (!data) {\n throw new Error(\n `URL file blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`\n );\n }\n\n return {\n type: \"file\",\n file: {\n file_data: block.url, // formatted as base64 data URL\n ...(block.metadata?.filename || block.metadata?.name\n ? {\n filename,\n }\n : {}),\n },\n };\n }\n\n if (block.source_type === \"base64\") {\n const filename = getRequiredFilenameFromMetadata(block);\n\n return {\n type: \"file\",\n file: {\n file_data: `data:${block.mime_type ?? \"\"};base64,${block.data}`,\n ...(block.metadata?.filename ||\n block.metadata?.name ||\n block.metadata?.title\n ? {\n filename,\n }\n : {}),\n },\n };\n }\n\n if (block.source_type === \"id\") {\n return {\n type: \"file\",\n file: {\n file_id: block.id,\n },\n };\n }\n\n throw new Error(\n `File content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`\n );\n },\n};\n\n/**\n * Converts an OpenAI Chat Completions API message to a LangChain BaseMessage.\n *\n * This converter transforms messages from OpenAI's Chat Completions API format into\n * LangChain's internal message representation, handling various message types and\n * preserving metadata, tool calls, and other relevant information.\n *\n * @remarks\n * The converter handles the following message roles:\n * - `assistant`: Converted to {@link AIMessage} with support for tool calls, function calls,\n * audio content, and multi-modal outputs\n * - Other roles: Converted to generic {@link ChatMessage}\n *\n * For assistant messages, the converter:\n * - Parses and validates tool calls, separating valid and invalid calls\n * - Preserves function call information in additional_kwargs\n * - Includes usage statistics and system fingerprint in response_metadata\n * - Handles multi-modal content (text, images, audio)\n * - Optionally includes the raw API response for debugging\n *\n * @param params - Conversion parameters\n * @param params.message - The OpenAI chat completion message to convert\n * @param params.rawResponse - The complete raw response from OpenAI's API, used to extract\n * metadata like model name, usage statistics, and system fingerprint\n * @param params.includeRawResponse - If true, includes the raw OpenAI response in the\n * message's additional_kwargs under the `__raw_response` key. Useful for debugging\n * or accessing provider-specific fields. Defaults to false.\n *\n * @returns A LangChain BaseMessage instance:\n * - {@link AIMessage} for assistant messages with tool calls, metadata, and content\n * - {@link ChatMessage} for all other message types\n *\n * @example\n * ```typescript\n * const baseMessage = convertCompletionsMessageToBaseMessage({\n * message: {\n * role: \"assistant\",\n * content: \"Hello! How can I help you?\",\n * tool_calls: [\n * {\n * id: \"call_123\",\n * type: \"function\",\n * function: { name: \"get_weather\", arguments: '{\"location\":\"NYC\"}' }\n * }\n * ]\n * },\n * rawResponse: completionResponse,\n * includeRawResponse: true\n * });\n * // Returns an AIMessage with parsed tool calls and metadata\n * ```\n *\n * @throws {Error} If tool call parsing fails, the invalid tool call is captured in\n * the `invalid_tool_calls` array rather than throwing an error\n *\n */\nexport const convertCompletionsMessageToBaseMessage: Converter<\n {\n message: OpenAIClient.Chat.Completions.ChatCompletionMessage;\n rawResponse: OpenAIClient.Chat.Completions.ChatCompletion;\n includeRawResponse?: boolean;\n },\n BaseMessage\n> = ({ message, rawResponse, includeRawResponse }) => {\n const rawToolCalls: OpenAIToolCall[] | undefined = message.tool_calls as\n | OpenAIToolCall[]\n | undefined;\n switch (message.role) {\n case \"assistant\": {\n const toolCalls = [];\n const invalidToolCalls = [];\n for (const rawToolCall of rawToolCalls ?? []) {\n try {\n toolCalls.push(parseToolCall(rawToolCall, { returnId: true }));\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n invalidToolCalls.push(makeInvalidToolCall(rawToolCall, e.message));\n }\n }\n const additional_kwargs: Record<string, unknown> = {\n function_call: message.function_call,\n tool_calls: rawToolCalls,\n };\n if (includeRawResponse !== undefined) {\n additional_kwargs.__raw_response = rawResponse;\n }\n const response_metadata: Record<string, unknown> | undefined = {\n model_provider: \"openai\",\n model_name: rawResponse.model,\n ...(rawResponse.system_fingerprint\n ? {\n usage: { ...rawResponse.usage },\n system_fingerprint: rawResponse.system_fingerprint,\n }\n : {}),\n };\n\n if (message.audio) {\n additional_kwargs.audio = message.audio;\n }\n\n const content = handleMultiModalOutput(\n message.content || \"\",\n rawResponse.choices?.[0]?.message\n );\n return new AIMessage({\n content,\n tool_calls: toolCalls,\n invalid_tool_calls: invalidToolCalls,\n additional_kwargs,\n response_metadata,\n id: rawResponse.id,\n });\n }\n default:\n return new ChatMessage(message.content || \"\", message.role ?? \"unknown\");\n }\n};\n\n/**\n * Converts an OpenAI Chat Completions API delta (streaming chunk) to a LangChain BaseMessageChunk.\n *\n * This converter is used during streaming responses to transform incremental updates from OpenAI's\n * Chat Completions API into LangChain message chunks. It handles various message types, tool calls,\n * function calls, audio content, and role-specific message chunk creation.\n *\n * @param params - Conversion parameters\n * @param params.delta - The delta object from an OpenAI streaming chunk containing incremental\n * message updates. May include content, role, tool_calls, function_call, audio, etc.\n * @param params.rawResponse - The complete raw ChatCompletionChunk response from OpenAI,\n * containing metadata like model info, usage stats, and the delta\n * @param params.includeRawResponse - Optional flag to include the raw OpenAI response in the\n * message chunk's additional_kwargs. Useful for debugging or accessing provider-specific data\n * @param params.defaultRole - Optional default role to use if the delta doesn't specify one.\n * Typically used to maintain role consistency across chunks in a streaming response\n *\n * @returns A BaseMessageChunk subclass appropriate for the message role:\n * - HumanMessageChunk for \"user\" role\n * - AIMessageChunk for \"assistant\" role (includes tool call chunks)\n * - SystemMessageChunk for \"system\" or \"developer\" roles\n * - FunctionMessageChunk for \"function\" role\n * - ToolMessageChunk for \"tool\" role\n * - ChatMessageChunk for any other role\n *\n * @example\n * Basic streaming text chunk:\n * ```typescript\n * const chunk = convertCompletionsDeltaToBaseMessageChunk({\n * delta: { role: \"assistant\", content: \"Hello\" },\n * rawResponse: { id: \"chatcmpl-123\", model: \"gpt-4\", ... }\n * });\n * // Returns: AIMessageChunk with content \"Hello\"\n * ```\n *\n * @example\n * Streaming chunk with tool call:\n * ```typescript\n * const chunk = convertCompletionsDeltaToBaseMessageChunk({\n * delta: {\n * role: \"assistant\",\n * tool_calls: [{\n * index: 0,\n * id: \"call_123\",\n * function: { name: \"get_weather\", arguments: '{\"location\":' }\n * }]\n * },\n * rawResponse: { id: \"chatcmpl-123\", ... }\n * });\n * // Returns: AIMessageChunk with tool_call_chunks containing partial tool call data\n * ```\n *\n * @remarks\n * - Tool calls are converted to ToolCallChunk objects with incremental data\n * - Audio content includes the chunk index from the raw response\n * - The \"developer\" role is mapped to SystemMessageChunk with a special marker\n * - Response metadata includes model provider info and usage statistics\n * - Function calls and tool calls are stored in additional_kwargs for compatibility\n */\nexport const convertCompletionsDeltaToBaseMessageChunk: Converter<\n {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n delta: Record<string, any>;\n rawResponse: OpenAIClient.Chat.Completions.ChatCompletionChunk;\n includeRawResponse?: boolean;\n defaultRole?: OpenAIClient.Chat.ChatCompletionRole;\n },\n BaseMessageChunk\n> = ({ delta, rawResponse, includeRawResponse, defaultRole }) => {\n const role = delta.role ?? defaultRole;\n const content = delta.content ?? \"\";\n let additional_kwargs: Record<string, unknown>;\n if (delta.function_call) {\n additional_kwargs = {\n function_call: delta.function_call,\n };\n } else if (delta.tool_calls) {\n additional_kwargs = {\n tool_calls: delta.tool_calls,\n };\n } else {\n additional_kwargs = {};\n }\n if (includeRawResponse) {\n additional_kwargs.__raw_response = rawResponse;\n }\n\n if (delta.audio) {\n additional_kwargs.audio = {\n ...delta.audio,\n index: rawResponse.choices[0].index,\n };\n }\n\n const response_metadata = {\n model_provider: \"openai\",\n usage: { ...rawResponse.usage },\n };\n if (role === \"user\") {\n return new HumanMessageChunk({ content, response_metadata });\n } else if (role === \"assistant\") {\n const toolCallChunks: ToolCallChunk[] = [];\n if (Array.isArray(delta.tool_calls)) {\n for (const rawToolCall of delta.tool_calls) {\n toolCallChunks.push({\n name: rawToolCall.function?.name,\n args: rawToolCall.function?.arguments,\n id: rawToolCall.id,\n index: rawToolCall.index,\n type: \"tool_call_chunk\",\n });\n }\n }\n return new AIMessageChunk({\n content,\n tool_call_chunks: toolCallChunks,\n additional_kwargs,\n id: rawResponse.id,\n response_metadata,\n });\n } else if (role === \"system\") {\n return new SystemMessageChunk({ content, response_metadata });\n } else if (role === \"developer\") {\n return new SystemMessageChunk({\n content,\n response_metadata,\n additional_kwargs: {\n __openai_role__: \"developer\",\n },\n });\n } else if (role === \"function\") {\n return new FunctionMessageChunk({\n content,\n additional_kwargs,\n name: delta.name,\n response_metadata,\n });\n } else if (role === \"tool\") {\n return new ToolMessageChunk({\n content,\n additional_kwargs,\n tool_call_id: delta.tool_call_id,\n response_metadata,\n });\n } else {\n return new ChatMessageChunk({ content, role, response_metadata });\n }\n};\n\n/**\n * Converts a standard LangChain content block to an OpenAI Completions API content part.\n *\n * This converter transforms LangChain's standardized content blocks (image, audio, file)\n * into the format expected by OpenAI's Chat Completions API. It handles various content\n * types including images (URL or base64), audio (base64), and files (data or file ID).\n *\n * @param block - The standard content block to convert. Can be an image, audio, or file block.\n *\n * @returns An OpenAI Chat Completions content part object, or undefined if the block\n * cannot be converted (e.g., missing required data).\n *\n * @example\n * Image with URL:\n * ```typescript\n * const block = { type: \"image\", url: \"https://example.com/image.jpg\" };\n * const part = convertStandardContentBlockToCompletionsContentPart(block);\n * // Returns: { type: \"image_url\", image_url: { url: \"https://example.com/image.jpg\" } }\n * ```\n *\n * @example\n * Image with base64 data:\n * ```typescript\n * const block = { type: \"image\", data: \"iVBORw0KGgo...\", mimeType: \"image/png\" };\n * const part = convertStandardContentBlockToCompletionsContentPart(block);\n * // Returns: { type: \"image_url\", image_url: { url: \"data:image/png;base64,iVBORw0KGgo...\" } }\n * ```\n */\nexport const convertStandardContentBlockToCompletionsContentPart: Converter<\n ContentBlock.Standard,\n | OpenAIClient.Chat.Completions.ChatCompletionContentPartImage\n | OpenAIClient.Chat.Completions.ChatCompletionContentPartInputAudio\n | OpenAIClient.Chat.Completions.ChatCompletionContentPart.File\n | undefined\n> = (block) => {\n if (block.type === \"image\") {\n if (block.url) {\n return {\n type: \"image_url\",\n image_url: {\n url: block.url,\n },\n };\n } else if (block.data) {\n return {\n type: \"image_url\",\n image_url: {\n url: `data:${block.mimeType};base64,${block.data}`,\n },\n };\n }\n }\n if (block.type === \"audio\") {\n if (block.data) {\n const format = iife(() => {\n const [, format] = block.mimeType.split(\"/\");\n if (format === \"wav\" || format === \"mp3\") {\n return format;\n }\n return \"wav\";\n });\n return {\n type: \"input_audio\",\n input_audio: {\n data: block.data.toString(),\n format,\n },\n };\n }\n }\n if (block.type === \"file\") {\n if (block.data) {\n const filename = getRequiredFilenameFromMetadata(block);\n\n return {\n type: \"file\",\n file: {\n file_data: `data:${block.mimeType};base64,${block.data}`,\n filename: filename,\n },\n };\n }\n if (block.fileId) {\n return {\n type: \"file\",\n file: {\n file_id: block.fileId,\n },\n };\n }\n }\n return undefined;\n};\n\n/**\n * Converts a LangChain BaseMessage with standard content blocks to an OpenAI Chat Completions API message parameter.\n *\n * This converter transforms LangChain's standardized message format (using contentBlocks) into the format\n * expected by OpenAI's Chat Completions API. It handles role mapping, content filtering, and multi-modal\n * content conversion for various message types.\n *\n * @remarks\n * The converter performs the following transformations:\n * - Maps LangChain message roles to OpenAI API roles (user, assistant, system, developer, tool, function)\n * - For reasoning models, automatically converts \"system\" role to \"developer\" role\n * - Filters content blocks based on message role (most roles only include text blocks)\n * - For user messages, converts multi-modal content blocks (images, audio, files) to OpenAI format\n * - Preserves tool call IDs for tool messages and function names for function messages\n *\n * Role-specific behavior:\n * - **developer**: Returns only text content blocks (used for reasoning models)\n * - **system**: Returns only text content blocks\n * - **assistant**: Returns only text content blocks\n * - **tool**: Returns only text content blocks with tool_call_id preserved\n * - **function**: Returns text content blocks joined as a single string with function name\n * - **user** (default): Returns multi-modal content including text, images, audio, and files\n *\n * @param params - Conversion parameters\n * @param params.message - The LangChain BaseMessage to convert. Must have contentBlocks property\n * containing an array of standard content blocks (text, image, audio, file, etc.)\n * @param params.model - Optional model name. Used to determine if special role mapping is needed\n * (e.g., \"system\" -> \"developer\" for reasoning models like o1)\n *\n * @returns An OpenAI ChatCompletionMessageParam object formatted for the Chat Completions API.\n * The structure varies by role:\n * - Developer/System/Assistant: `{ role, content: TextBlock[] }`\n * - Tool: `{ role: \"tool\", tool_call_id, content: TextBlock[] }`\n * - Function: `{ role: \"function\", name, content: string }`\n * - User: `{ role: \"user\", content: Array<TextPart | ImagePart | AudioPart | FilePart> }`\n *\n * @example\n * Simple text message:\n * ```typescript\n * const message = new HumanMessage({\n * content: [{ type: \"text\", text: \"Hello!\" }]\n * });\n * const param = convertStandardContentMessageToCompletionsMessage({ message });\n * // Returns: { role: \"user\", content: [{ type: \"text\", text: \"Hello!\" }] }\n * ```\n *\n * @example\n * Multi-modal user message with image:\n * ```typescript\n * const message = new HumanMessage({\n * content: [\n * { type: \"text\", text: \"What's in this image?\" },\n * { type: \"image\", url: \"https://example.com/image.jpg\" }\n * ]\n * });\n * const param = convertStandardContentMessageToCompletionsMessage({ message });\n * // Returns: {\n * // role: \"user\",\n * // content: [\n * // { type: \"text\", text: \"What's in this image?\" },\n * // { type: \"image_url\", image_url: { url: \"https://example.com/image.jpg\" } }\n * // ]\n * // }\n * ```\n */\nexport const convertStandardContentMessageToCompletionsMessage: Converter<\n { message: BaseMessage; model?: string },\n OpenAIClient.Chat.Completions.ChatCompletionMessageParam\n> = ({ message, model }) => {\n let role = messageToOpenAIRole(message);\n if (role === \"system\" && isReasoningModel(model)) {\n role = \"developer\";\n }\n if (role === \"developer\") {\n return {\n role: \"developer\",\n content: message.contentBlocks.filter((block) => block.type === \"text\"),\n };\n } else if (role === \"system\") {\n return {\n role: \"system\",\n content: message.contentBlocks.filter((block) => block.type === \"text\"),\n };\n } else if (role === \"assistant\") {\n return {\n role: \"assistant\",\n content: message.contentBlocks.filter((block) => block.type === \"text\"),\n };\n } else if (role === \"tool\" && ToolMessage.isInstance(message)) {\n return {\n role: \"tool\",\n tool_call_id: message.tool_call_id,\n content: message.contentBlocks.filter((block) => block.type === \"text\"),\n };\n } else if (role === \"function\") {\n return {\n role: \"function\",\n name: message.name ?? \"\",\n content: message.contentBlocks\n .filter((block) => block.type === \"text\")\n .join(\"\"),\n };\n }\n // Default to user message handling\n function* iterateUserContent(blocks: ContentBlock.Standard[]) {\n for (const block of blocks) {\n if (block.type === \"text\") {\n yield {\n type: \"text\" as const,\n text: block.text,\n };\n }\n const data = convertStandardContentBlockToCompletionsContentPart(block);\n if (data) {\n yield data;\n }\n }\n }\n return {\n role: \"user\",\n content: Array.from(iterateUserContent(message.contentBlocks)),\n };\n};\n\n/**\n * Converts an array of LangChain BaseMessages to OpenAI Chat Completions API message parameters.\n *\n * This converter transforms LangChain's internal message representation into the format required\n * by OpenAI's Chat Completions API. It handles various message types, roles, content formats,\n * tool calls, function calls, audio messages, and special model-specific requirements.\n *\n * @remarks\n * The converter performs several key transformations:\n * - Maps LangChain message types to OpenAI roles (user, assistant, system, tool, function, developer)\n * - Converts standard content blocks (v1 format) using a specialized converter\n * - Handles multimodal content including text, images, audio, and data blocks\n * - Preserves tool calls and function calls with proper formatting\n * - Applies model-specific role mappings (e.g., \"system\" → \"developer\" for reasoning models)\n * - Splits audio messages into separate message parameters when needed\n *\n * @param params - Conversion parameters\n * @param params.messages - Array of LangChain BaseMessages to convert. Can include any message\n * type: HumanMessage, AIMessage, SystemMessage, ToolMessage, FunctionMessage, etc.\n * @param params.model - Optional model name used to determine if special role mapping is needed.\n * For reasoning models (o1, o3, etc.), \"system\" role is converted to \"developer\" role.\n *\n * @returns Array of ChatCompletionMessageParam objects formatted for OpenAI's Chat Completions API.\n * Some messages may be split into multiple parameters (e.g., audio messages).\n *\n * @example\n * Basic message conversion:\n * ```typescript\n * const messages = [\n * new HumanMessage(\"What's the weather like?\"),\n * new AIMessage(\"Let me check that for you.\")\n * ];\n *\n * const params = convertMessagesToCompletionsMessageParams({\n * messages,\n * model: \"gpt-4\"\n * });\n * // Returns:\n * // [\n * // { role: \"user\", content: \"What's the weather like?\" },\n * // { role: \"assistant\", content: \"Let me check that for you.\" }\n * // ]\n * ```\n *\n * @example\n * Message with tool calls:\n * ```typescript\n * const messages = [\n * new AIMessage({\n * content: \"\",\n * tool_calls: [{\n * id: \"call_123\",\n * name: \"get_weather\",\n * args: { location: \"San Francisco\" }\n * }]\n * })\n * ];\n *\n * const params = convertMessagesToCompletionsMessageParams({ messages });\n * // Returns:\n * // [{\n * // role: \"assistant\",\n * // content: \"\",\n * // tool_calls: [{\n * // id: \"call_123\",\n * // type: \"function\",\n * // function: { name: \"get_weather\", arguments: '{\"location\":\"San Francisco\"}' }\n * // }]\n * // }]\n * ```\n */\nexport const convertMessagesToCompletionsMessageParams: Converter<\n { messages: BaseMessage[]; model?: string },\n OpenAIClient.Chat.Completions.ChatCompletionMessageParam[]\n> = ({ messages, model }) => {\n return messages.flatMap((message) => {\n if (\n \"output_version\" in message.response_metadata &&\n message.response_metadata?.output_version === \"v1\"\n ) {\n return convertStandardContentMessageToCompletionsMessage({ message });\n }\n let role = messageToOpenAIRole(message);\n if (role === \"system\" && isReasoningModel(model)) {\n role = \"developer\";\n }\n\n const content =\n typeof message.content === \"string\"\n ? message.content\n : message.content.flatMap((m) => {\n if (isDataContentBlock(m)) {\n return convertToProviderContentBlock(\n m,\n completionsApiContentBlockConverter\n );\n }\n // Drop Anthropic tool_use blocks from content — these are\n // already represented in message.tool_calls and would cause\n // an API error if passed through to OpenAI.\n if (\n typeof m === \"object\" &&\n m !== null &&\n \"type\" in m &&\n m.type === \"tool_use\"\n ) {\n return [];\n }\n return m;\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const completionParam: Record<string, any> = {\n role,\n content,\n };\n if (message.name != null) {\n completionParam.name = message.name;\n }\n if (message.additional_kwargs.function_call != null) {\n completionParam.function_call = message.additional_kwargs.function_call;\n }\n if (AIMessage.isInstance(message) && !!message.tool_calls?.length) {\n completionParam.tool_calls = message.tool_calls.map(\n convertLangChainToolCallToOpenAI\n );\n } else {\n if (message.additional_kwargs.tool_calls != null) {\n completionParam.tool_calls = message.additional_kwargs.tool_calls;\n }\n if (ToolMessage.isInstance(message) && message.tool_call_id != null) {\n completionParam.tool_call_id = message.tool_call_id;\n }\n }\n\n if (\n message.additional_kwargs.audio &&\n typeof message.additional_kwargs.audio === \"object\" &&\n \"id\" in message.additional_kwargs.audio\n ) {\n const audioMessage = {\n role: \"assistant\",\n audio: {\n id: message.additional_kwargs.audio.id,\n },\n };\n return [\n completionParam,\n audioMessage,\n ] as OpenAIClient.Chat.Completions.ChatCompletionMessageParam[];\n }\n\n return completionParam as OpenAIClient.Chat.Completions.ChatCompletionMessageParam;\n });\n};\n"],"mappings":";;;;;;;;;AA6CA,MAAa,sCAKR;CACH,cAAc;CAEd,sBAAsB,OAAsC;AAC1D,SAAO;GAAE,MAAM;GAAQ,MAAM,MAAM;GAAM;;CAG3C,uBAAuB,OAAuC;AAC5D,MAAI,MAAM,gBAAgB,MACxB,QAAO;GACL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1
|
import { completionsApiContentBlockConverter, convertCompletionsDeltaToBaseMessageChunk, convertCompletionsMessageToBaseMessage, convertMessagesToCompletionsMessageParams, convertStandardContentBlockToCompletionsContentPart, convertStandardContentMessageToCompletionsMessage } from "./completions.js";
|
|
2
2
|
import { convertMessagesToResponsesInput, convertReasoningSummaryToResponsesReasoningItem, convertResponsesDeltaToChatGenerationChunk, convertResponsesMessageToAIMessage, convertResponsesUsageToUsageMetadata, convertStandardContentMessageToResponsesInput } from "./responses.js";
|
|
3
|
+
|
|
4
|
+
export { };
|
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
1
|
const require_tools = require('../utils/tools.cjs');
|
|
3
2
|
const require_misc = require('../utils/misc.cjs');
|
|
4
3
|
const require_completions = require('./completions.cjs');
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
4
|
+
let _langchain_core_messages = require("@langchain/core/messages");
|
|
5
|
+
let _langchain_core_outputs = require("@langchain/core/outputs");
|
|
6
|
+
let _langchain_core_output_parsers_openai_tools = require("@langchain/core/output_parsers/openai_tools");
|
|
8
7
|
|
|
9
8
|
//#region src/converters/responses.ts
|
|
10
9
|
const _FUNCTION_CALL_IDS_MAP_KEY = "__openai_function_call_ids__";
|
|
@@ -216,6 +215,14 @@ const convertResponsesMessageToAIMessage = (response) => {
|
|
|
216
215
|
const content = [];
|
|
217
216
|
const tool_calls = [];
|
|
218
217
|
const invalid_tool_calls = [];
|
|
218
|
+
const cleanedOutput = response.output.map((item) => {
|
|
219
|
+
if (item.type === "function_call" && "parsed_arguments" in item) {
|
|
220
|
+
const cleaned = { ...item };
|
|
221
|
+
delete cleaned.parsed_arguments;
|
|
222
|
+
return cleaned;
|
|
223
|
+
}
|
|
224
|
+
return item;
|
|
225
|
+
});
|
|
219
226
|
const response_metadata = {
|
|
220
227
|
model_provider: "openai",
|
|
221
228
|
model: response.model,
|
|
@@ -224,6 +231,7 @@ const convertResponsesMessageToAIMessage = (response) => {
|
|
|
224
231
|
incomplete_details: response.incomplete_details,
|
|
225
232
|
metadata: response.metadata,
|
|
226
233
|
object: response.object,
|
|
234
|
+
output: cleanedOutput,
|
|
227
235
|
status: response.status,
|
|
228
236
|
user: response.user,
|
|
229
237
|
service_tier: response.service_tier,
|
|
@@ -256,11 +264,11 @@ const convertResponsesMessageToAIMessage = (response) => {
|
|
|
256
264
|
id: item.call_id
|
|
257
265
|
};
|
|
258
266
|
try {
|
|
259
|
-
tool_calls.push((0,
|
|
267
|
+
tool_calls.push((0, _langchain_core_output_parsers_openai_tools.parseToolCall)(fnAdapter, { returnId: true }));
|
|
260
268
|
} catch (e) {
|
|
261
269
|
let errMessage;
|
|
262
270
|
if (typeof e === "object" && e != null && "message" in e && typeof e.message === "string") errMessage = e.message;
|
|
263
|
-
invalid_tool_calls.push((0,
|
|
271
|
+
invalid_tool_calls.push((0, _langchain_core_output_parsers_openai_tools.makeInvalidToolCall)(fnAdapter, errMessage));
|
|
264
272
|
}
|
|
265
273
|
additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] ??= {};
|
|
266
274
|
if (item.id) additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY][item.call_id] = item.id;
|
|
@@ -274,11 +282,11 @@ const convertResponsesMessageToAIMessage = (response) => {
|
|
|
274
282
|
} else if (item.type === "custom_tool_call") {
|
|
275
283
|
const parsed = require_tools.parseCustomToolCall(item);
|
|
276
284
|
if (parsed) tool_calls.push(parsed);
|
|
277
|
-
else invalid_tool_calls.push((0,
|
|
285
|
+
else invalid_tool_calls.push((0, _langchain_core_output_parsers_openai_tools.makeInvalidToolCall)(item, "Malformed custom tool call"));
|
|
278
286
|
} else if (item.type === "computer_call") {
|
|
279
287
|
const parsed = require_tools.parseComputerCall(item);
|
|
280
288
|
if (parsed) tool_calls.push(parsed);
|
|
281
|
-
else invalid_tool_calls.push((0,
|
|
289
|
+
else invalid_tool_calls.push((0, _langchain_core_output_parsers_openai_tools.makeInvalidToolCall)(item, "Malformed computer call"));
|
|
282
290
|
} else if (item.type === "image_generation_call") {
|
|
283
291
|
if (item.result) content.push({
|
|
284
292
|
type: "image",
|
|
@@ -293,7 +301,7 @@ const convertResponsesMessageToAIMessage = (response) => {
|
|
|
293
301
|
additional_kwargs.tool_outputs ??= [];
|
|
294
302
|
additional_kwargs.tool_outputs.push(item);
|
|
295
303
|
}
|
|
296
|
-
return new
|
|
304
|
+
return new _langchain_core_messages.AIMessage({
|
|
297
305
|
id: messageId,
|
|
298
306
|
content,
|
|
299
307
|
tool_calls,
|
|
@@ -495,7 +503,11 @@ const convertResponsesDeltaToChatGenerationChunk = (event) => {
|
|
|
495
503
|
const msg = convertResponsesMessageToAIMessage(event.response);
|
|
496
504
|
usage_metadata = convertResponsesUsageToUsageMetadata(event.response.usage);
|
|
497
505
|
if (event.response.text?.format?.type === "json_schema") additional_kwargs.parsed ??= JSON.parse(msg.text);
|
|
498
|
-
for (const [key, value] of Object.entries(event.response))
|
|
506
|
+
for (const [key, value] of Object.entries(event.response)) {
|
|
507
|
+
if (key === "id") continue;
|
|
508
|
+
if (key === "output") response_metadata[key] = msg.response_metadata.output;
|
|
509
|
+
else response_metadata[key] = value;
|
|
510
|
+
}
|
|
499
511
|
} else if (event.type === "response.function_call_arguments.delta" || event.type === "response.custom_tool_call_input.delta") tool_call_chunks.push({
|
|
500
512
|
type: "tool_call_chunk",
|
|
501
513
|
args: event.delta,
|
|
@@ -549,9 +561,9 @@ const convertResponsesDeltaToChatGenerationChunk = (event) => {
|
|
|
549
561
|
});
|
|
550
562
|
} else if (event.type === "response.image_generation_call.partial_image") return null;
|
|
551
563
|
else return null;
|
|
552
|
-
return new
|
|
564
|
+
return new _langchain_core_outputs.ChatGenerationChunk({
|
|
553
565
|
text: content.map((part) => part.text).join(""),
|
|
554
|
-
message: new
|
|
566
|
+
message: new _langchain_core_messages.AIMessageChunk({
|
|
555
567
|
id,
|
|
556
568
|
content,
|
|
557
569
|
tool_call_chunks,
|
|
@@ -602,7 +614,7 @@ const convertResponsesDeltaToChatGenerationChunk = (event) => {
|
|
|
602
614
|
* ```
|
|
603
615
|
*/
|
|
604
616
|
const convertStandardContentMessageToResponsesInput = (message) => {
|
|
605
|
-
const isResponsesMessage =
|
|
617
|
+
const isResponsesMessage = _langchain_core_messages.AIMessage.isInstance(message) && message.response_metadata?.model_provider === "openai";
|
|
606
618
|
function* iterateItems() {
|
|
607
619
|
const messageRole = require_misc.iife(() => {
|
|
608
620
|
try {
|
|
@@ -662,14 +674,12 @@ const convertStandardContentMessageToResponsesInput = (message) => {
|
|
|
662
674
|
};
|
|
663
675
|
if (block.data) {
|
|
664
676
|
const base64Data = typeof block.data === "string" ? block.data : Buffer.from(block.data).toString("base64");
|
|
665
|
-
const mimeType = block.mimeType ?? "image/png";
|
|
666
677
|
return {
|
|
667
678
|
type: "input_image",
|
|
668
679
|
detail,
|
|
669
|
-
image_url: `data:${mimeType};base64,${base64Data}`
|
|
680
|
+
image_url: `data:${block.mimeType ?? "image/png"};base64,${base64Data}`
|
|
670
681
|
};
|
|
671
682
|
}
|
|
672
|
-
return void 0;
|
|
673
683
|
};
|
|
674
684
|
const resolveFileItem = (block) => {
|
|
675
685
|
if (block.fileId) {
|
|
@@ -691,20 +701,17 @@ const convertStandardContentMessageToResponsesInput = (message) => {
|
|
|
691
701
|
if (block.data) {
|
|
692
702
|
const filename = require_misc.getRequiredFilenameFromMetadata(block);
|
|
693
703
|
const encoded = typeof block.data === "string" ? block.data : Buffer.from(block.data).toString("base64");
|
|
694
|
-
const mimeType = block.mimeType ?? "application/octet-stream";
|
|
695
704
|
return {
|
|
696
705
|
type: "input_file",
|
|
697
|
-
file_data: `data:${mimeType};base64,${encoded}`,
|
|
706
|
+
file_data: `data:${block.mimeType ?? "application/octet-stream"};base64,${encoded}`,
|
|
698
707
|
...filename ? { filename } : {}
|
|
699
708
|
};
|
|
700
709
|
}
|
|
701
|
-
return void 0;
|
|
702
710
|
};
|
|
703
711
|
const convertReasoningBlock = (block) => {
|
|
704
712
|
const summaryEntries = require_misc.iife(() => {
|
|
705
713
|
if (Array.isArray(block.summary)) {
|
|
706
|
-
const
|
|
707
|
-
const mapped = candidate?.map((item) => item?.text).filter((text) => typeof text === "string") ?? [];
|
|
714
|
+
const mapped = block.summary?.map((item) => item?.text).filter((text) => typeof text === "string") ?? [];
|
|
708
715
|
if (mapped.length > 0) return mapped;
|
|
709
716
|
}
|
|
710
717
|
return block.reasoning ? [block.reasoning] : [];
|
|
@@ -873,8 +880,14 @@ const convertMessagesToResponsesInput = ({ messages, zdrEnabled, model }) => {
|
|
|
873
880
|
if (role === "function") throw new Error("Function messages are not supported in Responses API");
|
|
874
881
|
if (role === "tool") {
|
|
875
882
|
const toolMessage = lcMsg;
|
|
876
|
-
if (additional_kwargs?.type === "computer_call_output")
|
|
877
|
-
|
|
883
|
+
if (additional_kwargs?.type === "computer_call_output")
|
|
884
|
+
/**
|
|
885
|
+
* Cast needed because OpenAI SDK types don't yet include input_image
|
|
886
|
+
* for computer-use-preview model output format
|
|
887
|
+
*/
|
|
888
|
+
return {
|
|
889
|
+
type: "computer_call_output",
|
|
890
|
+
output: (() => {
|
|
878
891
|
if (typeof toolMessage.content === "string") return {
|
|
879
892
|
type: "input_image",
|
|
880
893
|
image_url: toolMessage.content
|
|
@@ -900,17 +913,9 @@ const convertMessagesToResponsesInput = ({ messages, zdrEnabled, model }) => {
|
|
|
900
913
|
};
|
|
901
914
|
}
|
|
902
915
|
throw new Error("Invalid computer call output");
|
|
903
|
-
})()
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
* for computer-use-preview model output format
|
|
907
|
-
*/
|
|
908
|
-
return {
|
|
909
|
-
type: "computer_call_output",
|
|
910
|
-
output,
|
|
911
|
-
call_id: toolMessage.tool_call_id
|
|
912
|
-
};
|
|
913
|
-
}
|
|
916
|
+
})(),
|
|
917
|
+
call_id: toolMessage.tool_call_id
|
|
918
|
+
};
|
|
914
919
|
if (toolMessage.additional_kwargs?.customTool) return {
|
|
915
920
|
type: "custom_tool_call_output",
|
|
916
921
|
call_id: toolMessage.tool_call_id,
|
|
@@ -968,7 +973,7 @@ const convertMessagesToResponsesInput = ({ messages, zdrEnabled, model }) => {
|
|
|
968
973
|
})
|
|
969
974
|
});
|
|
970
975
|
const functionCallIds = additional_kwargs?.[_FUNCTION_CALL_IDS_MAP_KEY];
|
|
971
|
-
if (
|
|
976
|
+
if (_langchain_core_messages.AIMessage.isInstance(lcMsg) && !!lcMsg.tool_calls?.length) input.push(...lcMsg.tool_calls.map((toolCall) => {
|
|
972
977
|
if (require_tools.isCustomToolCall(toolCall)) return {
|
|
973
978
|
type: "custom_tool_call",
|
|
974
979
|
id: toolCall.call_id,
|
|
@@ -1007,8 +1012,7 @@ const convertMessagesToResponsesInput = ({ messages, zdrEnabled, model }) => {
|
|
|
1007
1012
|
"local_shell_call"
|
|
1008
1013
|
];
|
|
1009
1014
|
if (toolOutputs != null) {
|
|
1010
|
-
const
|
|
1011
|
-
const fallthroughCalls = castToolOutputs?.filter((item) => fallthroughCallTypes.includes(item.type));
|
|
1015
|
+
const fallthroughCalls = toolOutputs?.filter((item) => fallthroughCallTypes.includes(item.type));
|
|
1012
1016
|
if (fallthroughCalls.length > 0) input.push(...fallthroughCalls);
|
|
1013
1017
|
}
|
|
1014
1018
|
return input;
|
|
@@ -1019,44 +1023,38 @@ const convertMessagesToResponsesInput = ({ messages, zdrEnabled, model }) => {
|
|
|
1019
1023
|
role,
|
|
1020
1024
|
content: lcMsg.content
|
|
1021
1025
|
};
|
|
1022
|
-
const messages
|
|
1026
|
+
const messages = [];
|
|
1023
1027
|
const content = lcMsg.content.flatMap((item) => {
|
|
1024
|
-
if (item.type === "mcp_approval_response") messages
|
|
1028
|
+
if (item.type === "mcp_approval_response") messages.push({
|
|
1025
1029
|
type: "mcp_approval_response",
|
|
1026
1030
|
approval_request_id: item.approval_request_id,
|
|
1027
1031
|
approve: item.approve
|
|
1028
1032
|
});
|
|
1029
|
-
if ((0,
|
|
1033
|
+
if ((0, _langchain_core_messages.isDataContentBlock)(item)) return (0, _langchain_core_messages.convertToProviderContentBlock)(item, require_completions.completionsApiContentBlockConverter);
|
|
1030
1034
|
if (item.type === "text") return {
|
|
1031
1035
|
type: "input_text",
|
|
1032
1036
|
text: item.text
|
|
1033
1037
|
};
|
|
1034
|
-
if (item.type === "image_url") {
|
|
1035
|
-
|
|
1038
|
+
if (item.type === "image_url") return {
|
|
1039
|
+
type: "input_image",
|
|
1040
|
+
image_url: require_misc.iife(() => {
|
|
1036
1041
|
if (typeof item.image_url === "string") return item.image_url;
|
|
1037
1042
|
else if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url) return item.image_url.url;
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
const detail = require_misc.iife(() => {
|
|
1043
|
+
}),
|
|
1044
|
+
detail: require_misc.iife(() => {
|
|
1041
1045
|
if (typeof item.image_url === "string") return "auto";
|
|
1042
1046
|
else if (typeof item.image_url === "object" && item.image_url !== null && "detail" in item.image_url) return item.image_url.detail;
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
return {
|
|
1046
|
-
type: "input_image",
|
|
1047
|
-
image_url: imageUrl,
|
|
1048
|
-
detail
|
|
1049
|
-
};
|
|
1050
|
-
}
|
|
1047
|
+
})
|
|
1048
|
+
};
|
|
1051
1049
|
if (item.type === "input_text" || item.type === "input_image" || item.type === "input_file") return item;
|
|
1052
1050
|
return [];
|
|
1053
1051
|
});
|
|
1054
|
-
if (content.length > 0) messages
|
|
1052
|
+
if (content.length > 0) messages.push({
|
|
1055
1053
|
type: "message",
|
|
1056
1054
|
role,
|
|
1057
1055
|
content
|
|
1058
1056
|
});
|
|
1059
|
-
return messages
|
|
1057
|
+
return messages;
|
|
1060
1058
|
}
|
|
1061
1059
|
console.warn(`Unsupported role found when converting to OpenAI Responses API: ${role}`);
|
|
1062
1060
|
return [];
|