@langchain/openai 1.2.6 → 1.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @langchain/openai
2
2
 
3
+ ## 1.2.7
4
+
5
+ ### Patch Changes
6
+
7
+ - [#9954](https://github.com/langchain-ai/langchainjs/pull/9954) [`6939dab`](https://github.com/langchain-ai/langchainjs/commit/6939dabc8dc6481942e7e2c19e3dc61bc374d65a) Thanks [@akintunero](https://github.com/akintunero)! - fix(openai): store response.output in response_metadata for reasoning model round-trips
8
+
9
+ - [#9898](https://github.com/langchain-ai/langchainjs/pull/9898) [`ad581c7`](https://github.com/langchain-ai/langchainjs/commit/ad581c76138ea12ebdaee444c0dcdc4f6a280624) Thanks [@Muhammad-Kamran-Khan](https://github.com/Muhammad-Kamran-Khan)! - fix(openai): pass service_tier to API when using Responses API
10
+
3
11
  ## 1.2.6
4
12
 
5
13
  ### Patch Changes
@@ -23,6 +23,7 @@ var ChatOpenAIResponses = class extends require_base.BaseChatOpenAI {
23
23
  temperature: this.temperature,
24
24
  top_p: this.topP,
25
25
  user: this.user,
26
+ service_tier: this.service_tier,
26
27
  stream: this.streaming,
27
28
  previous_response_id: options?.previous_response_id,
28
29
  truncation: options?.truncation,
@@ -1 +1 @@
1
- {"version":3,"file":"responses.cjs","names":["BaseChatOpenAI","options?: this[\"ParsedCallOptions\"]","strict: boolean | undefined","params: ChatResponsesInvocationParams","isBuiltInToolChoice","formatToOpenAIToolChoice","messages: BaseMessage[]","options: this[\"ParsedCallOptions\"]","runManager?: CallbackManagerForLLMRun","finalChunk: ChatGenerationChunk | undefined","convertMessagesToResponsesInput","convertResponsesMessageToAIMessage","convertResponsesDeltaToChatGenerationChunk","request: OpenAIClient.Responses.ResponseCreateParams","requestOptions?: OpenAIClient.RequestOptions","wrapOpenAIClientError","tools: ChatOpenAIToolType[]","fields: { stream?: boolean; strict?: boolean }","reducedTools: ResponsesTool[]","isBuiltInTool","isCustomTool","isOpenAICustomTool","convertCompletionsCustomTool"],"sources":["../../src/chat_models/responses.ts"],"sourcesContent":["import { OpenAI as OpenAIClient } from \"openai\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport { AIMessage, type BaseMessage } from \"@langchain/core/messages\";\nimport { ChatGenerationChunk, type ChatResult } from \"@langchain/core/outputs\";\nimport { isOpenAITool as isOpenAIFunctionTool } from \"@langchain/core/language_models/base\";\nimport { wrapOpenAIClientError } from \"../utils/client.js\";\nimport {\n ChatOpenAIToolType,\n convertCompletionsCustomTool,\n formatToOpenAIToolChoice,\n isBuiltInTool,\n isBuiltInToolChoice,\n isCustomTool,\n isOpenAICustomTool,\n ResponsesTool,\n} from \"../utils/tools.js\";\nimport { BaseChatOpenAI, BaseChatOpenAICallOptions } from \"./base.js\";\nimport {\n convertMessagesToResponsesInput,\n convertResponsesDeltaToChatGenerationChunk,\n convertResponsesMessageToAIMessage,\n} from \"../converters/responses.js\";\nimport { OpenAIVerbosityParam } from \"../types.js\";\n\nexport interface ChatOpenAIResponsesCallOptions extends BaseChatOpenAICallOptions {\n /**\n * Configuration options for a text response from the model. Can be plain text or\n * structured JSON data.\n */\n text?: OpenAIClient.Responses.ResponseCreateParams[\"text\"];\n\n /**\n * The truncation strategy to use for the model response.\n */\n truncation?: OpenAIClient.Responses.ResponseCreateParams[\"truncation\"];\n\n /**\n * Specify additional output data to include in the model response.\n */\n include?: OpenAIClient.Responses.ResponseCreateParams[\"include\"];\n\n /**\n * The unique ID of the previous response to the model. Use this to create multi-turn\n * conversations.\n */\n previous_response_id?: OpenAIClient.Responses.ResponseCreateParams[\"previous_response_id\"];\n\n /**\n * The verbosity of the model's response.\n */\n verbosity?: OpenAIVerbosityParam;\n}\n\nexport type ChatResponsesInvocationParams = Omit<\n OpenAIClient.Responses.ResponseCreateParams,\n \"input\"\n>;\n\n/**\n * OpenAI Responses API implementation.\n *\n * Will be exported in a later version of @langchain/openai.\n *\n * @internal\n */\nexport class ChatOpenAIResponses<\n CallOptions extends ChatOpenAIResponsesCallOptions =\n ChatOpenAIResponsesCallOptions,\n> extends BaseChatOpenAI<CallOptions> {\n override invocationParams(\n options?: this[\"ParsedCallOptions\"]\n ): ChatResponsesInvocationParams {\n let strict: boolean | undefined;\n if (options?.strict !== undefined) {\n strict = options.strict;\n }\n if (strict === undefined && this.supportsStrictToolCalling !== undefined) {\n strict = this.supportsStrictToolCalling;\n }\n\n const params: ChatResponsesInvocationParams = {\n model: this.model,\n temperature: this.temperature,\n top_p: this.topP,\n user: this.user,\n\n // if include_usage is set or streamUsage then stream must be set to true.\n stream: this.streaming,\n previous_response_id: options?.previous_response_id,\n truncation: options?.truncation,\n include: options?.include,\n tools: options?.tools?.length\n ? this._reduceChatOpenAITools(options.tools, {\n stream: this.streaming,\n strict,\n })\n : undefined,\n tool_choice: isBuiltInToolChoice(options?.tool_choice)\n ? options?.tool_choice\n : (() => {\n const formatted = formatToOpenAIToolChoice(options?.tool_choice);\n if (typeof formatted === \"object\" && \"type\" in formatted) {\n if (formatted.type === \"function\") {\n return { type: \"function\", name: formatted.function.name };\n } else if (formatted.type === \"allowed_tools\") {\n return {\n type: \"allowed_tools\",\n mode: formatted.allowed_tools.mode,\n tools: formatted.allowed_tools.tools,\n };\n } else if (formatted.type === \"custom\") {\n return {\n type: \"custom\",\n name: formatted.custom.name,\n };\n }\n }\n return undefined;\n })(),\n text: (() => {\n if (options?.text) return options.text;\n const format = this._getResponseFormat(options?.response_format);\n if (format?.type === \"json_schema\") {\n if (format.json_schema.schema != null) {\n return {\n format: {\n type: \"json_schema\",\n schema: format.json_schema.schema,\n description: format.json_schema.description,\n name: format.json_schema.name,\n strict: format.json_schema.strict,\n },\n verbosity: options?.verbosity,\n };\n }\n return undefined;\n }\n return { format, verbosity: options?.verbosity };\n })(),\n parallel_tool_calls: options?.parallel_tool_calls,\n max_output_tokens: this.maxTokens === -1 ? undefined : this.maxTokens,\n prompt_cache_key: options?.promptCacheKey ?? this.promptCacheKey,\n prompt_cache_retention:\n options?.promptCacheRetention ?? this.promptCacheRetention,\n ...(this.zdrEnabled ? { store: false } : {}),\n ...this.modelKwargs,\n };\n\n const reasoning = this._getReasoningParams(options);\n\n if (reasoning !== undefined) {\n params.reasoning = reasoning;\n }\n\n return params;\n }\n\n async _generate(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n options.signal?.throwIfAborted();\n const invocationParams = this.invocationParams(options);\n if (invocationParams.stream) {\n const stream = this._streamResponseChunks(messages, options, runManager);\n let finalChunk: ChatGenerationChunk | undefined;\n for await (const chunk of stream) {\n chunk.message.response_metadata = {\n ...chunk.generationInfo,\n ...chunk.message.response_metadata,\n };\n finalChunk = finalChunk?.concat(chunk) ?? chunk;\n }\n\n return {\n generations: finalChunk ? [finalChunk] : [],\n llmOutput: {\n estimatedTokenUsage: (finalChunk?.message as AIMessage | undefined)\n ?.usage_metadata,\n },\n };\n } else {\n const data = await this.completionWithRetry(\n {\n input: convertMessagesToResponsesInput({\n messages,\n zdrEnabled: this.zdrEnabled ?? false,\n model: this.model,\n }),\n ...invocationParams,\n stream: false,\n },\n { signal: options?.signal, ...options?.options }\n );\n\n return {\n generations: [\n {\n text: data.output_text,\n message: convertResponsesMessageToAIMessage(data),\n },\n ],\n llmOutput: {\n id: data.id,\n estimatedTokenUsage: data.usage\n ? {\n promptTokens: data.usage.input_tokens,\n completionTokens: data.usage.output_tokens,\n totalTokens: data.usage.total_tokens,\n }\n : undefined,\n },\n };\n }\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const streamIterable = await this.completionWithRetry(\n {\n ...this.invocationParams(options),\n input: convertMessagesToResponsesInput({\n messages,\n zdrEnabled: this.zdrEnabled ?? false,\n model: this.model,\n }),\n stream: true,\n },\n options\n );\n\n for await (const data of streamIterable) {\n if (options.signal?.aborted) {\n return;\n }\n const chunk = convertResponsesDeltaToChatGenerationChunk(data);\n if (chunk == null) continue;\n yield chunk;\n await runManager?.handleLLMNewToken(\n chunk.text || \"\",\n {\n prompt: options.promptIndex ?? 0,\n completion: 0,\n },\n undefined,\n undefined,\n undefined,\n { chunk }\n );\n }\n }\n\n /**\n * Calls the Responses API with retry logic in case of failures.\n * @param request The request to send to the OpenAI API.\n * @param options Optional configuration for the API call.\n * @returns The response from the OpenAI API.\n */\n async completionWithRetry(\n request: OpenAIClient.Responses.ResponseCreateParamsStreaming,\n requestOptions?: OpenAIClient.RequestOptions\n ): Promise<AsyncIterable<OpenAIClient.Responses.ResponseStreamEvent>>;\n\n async completionWithRetry(\n request: OpenAIClient.Responses.ResponseCreateParamsNonStreaming,\n requestOptions?: OpenAIClient.RequestOptions\n ): Promise<OpenAIClient.Responses.Response>;\n\n async completionWithRetry(\n request: OpenAIClient.Responses.ResponseCreateParams,\n requestOptions?: OpenAIClient.RequestOptions\n ): Promise<\n | AsyncIterable<OpenAIClient.Responses.ResponseStreamEvent>\n | OpenAIClient.Responses.Response\n > {\n return this.caller.call(async () => {\n const clientOptions = this._getClientOptions(requestOptions);\n try {\n // use parse if dealing with json_schema\n if (request.text?.format?.type === \"json_schema\" && !request.stream) {\n return await this.client.responses.parse(request, clientOptions);\n }\n return await this.client.responses.create(request, clientOptions);\n } catch (e) {\n const error = wrapOpenAIClientError(e);\n throw error;\n }\n });\n }\n\n /** @internal */\n protected _reduceChatOpenAITools(\n tools: ChatOpenAIToolType[],\n fields: { stream?: boolean; strict?: boolean }\n ): ResponsesTool[] {\n const reducedTools: ResponsesTool[] = [];\n for (const tool of tools) {\n if (isBuiltInTool(tool)) {\n if (tool.type === \"image_generation\" && fields?.stream) {\n // OpenAI sends a 400 error if partial_images is not set and we want to stream.\n // We also set it to 1 since we don't support partial images yet.\n tool.partial_images = 1;\n }\n reducedTools.push(tool);\n } else if (isCustomTool(tool)) {\n const customToolData = tool.metadata.customTool;\n reducedTools.push({\n type: \"custom\",\n name: customToolData.name,\n description: customToolData.description,\n format: customToolData.format,\n } as ResponsesTool);\n } else if (isOpenAIFunctionTool(tool)) {\n reducedTools.push({\n type: \"function\",\n name: tool.function.name,\n parameters: tool.function.parameters,\n description: tool.function.description,\n strict: fields?.strict ?? null,\n });\n } else if (isOpenAICustomTool(tool)) {\n reducedTools.push(convertCompletionsCustomTool(tool));\n }\n }\n return reducedTools;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiEA,IAAa,sBAAb,cAGUA,4BAA4B;CACpC,AAAS,iBACPC,SAC+B;EAC/B,IAAIC;AACJ,MAAI,SAAS,WAAW,QACtB,SAAS,QAAQ;AAEnB,MAAI,WAAW,UAAa,KAAK,8BAA8B,QAC7D,SAAS,KAAK;EAGhB,MAAMC,SAAwC;GAC5C,OAAO,KAAK;GACZ,aAAa,KAAK;GAClB,OAAO,KAAK;GACZ,MAAM,KAAK;GAGX,QAAQ,KAAK;GACb,sBAAsB,SAAS;GAC/B,YAAY,SAAS;GACrB,SAAS,SAAS;GAClB,OAAO,SAAS,OAAO,SACnB,KAAK,uBAAuB,QAAQ,OAAO;IACzC,QAAQ,KAAK;IACb;GACD,EAAC,GACF;GACJ,aAAaC,kCAAoB,SAAS,YAAY,GAClD,SAAS,eACR,MAAM;IACL,MAAM,YAAYC,uCAAyB,SAAS,YAAY;AAChE,QAAI,OAAO,cAAc,YAAY,UAAU,WAC7C;SAAI,UAAU,SAAS,WACrB,QAAO;MAAE,MAAM;MAAY,MAAM,UAAU,SAAS;KAAM;cACjD,UAAU,SAAS,gBAC5B,QAAO;MACL,MAAM;MACN,MAAM,UAAU,cAAc;MAC9B,OAAO,UAAU,cAAc;KAChC;cACQ,UAAU,SAAS,SAC5B,QAAO;MACL,MAAM;MACN,MAAM,UAAU,OAAO;KACxB;IACF;AAEH,WAAO;GACR,IAAG;GACR,OAAO,MAAM;AACX,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ACiB;EACjB,MAAMC,eAAgC,CAAE;AACxC,OAAK,MAAM,QAAQ,MACjB,KAAIC,4BAAc,KAAK,EAAE;AACvB,OAAI,KAAK,SAAS,sBAAsB,QAAQ,QAG9C,KAAK,iBAAiB;GAExB,aAAa,KAAK,KAAK;EACxB,WAAUC,2BAAa,KAAK,EAAE;GAC7B,MAAM,iBAAiB,KAAK,SAAS;GACrC,aAAa,KAAK;IAChB,MAAM;IACN,MAAM,eAAe;IACrB,aAAa,eAAe;IAC5B,QAAQ,eAAe;GACxB,EAAkB;EACpB,mEAA+B,KAAK,EACnC,aAAa,KAAK;GAChB,MAAM;GACN,MAAM,KAAK,SAAS;GACpB,YAAY,KAAK,SAAS;GAC1B,aAAa,KAAK,SAAS;GAC3B,QAAQ,QAAQ,UAAU;EAC3B,EAAC;WACOC,iCAAmB,KAAK,EACjC,aAAa,KAAKC,2CAA6B,KAAK,CAAC;AAGzD,SAAO;CACR;AACF"}
1
+ {"version":3,"file":"responses.cjs","names":["BaseChatOpenAI","options?: this[\"ParsedCallOptions\"]","strict: boolean | undefined","params: ChatResponsesInvocationParams","isBuiltInToolChoice","formatToOpenAIToolChoice","messages: BaseMessage[]","options: this[\"ParsedCallOptions\"]","runManager?: CallbackManagerForLLMRun","finalChunk: ChatGenerationChunk | undefined","convertMessagesToResponsesInput","convertResponsesMessageToAIMessage","convertResponsesDeltaToChatGenerationChunk","request: OpenAIClient.Responses.ResponseCreateParams","requestOptions?: OpenAIClient.RequestOptions","wrapOpenAIClientError","tools: ChatOpenAIToolType[]","fields: { stream?: boolean; strict?: boolean }","reducedTools: ResponsesTool[]","isBuiltInTool","isCustomTool","isOpenAICustomTool","convertCompletionsCustomTool"],"sources":["../../src/chat_models/responses.ts"],"sourcesContent":["import { OpenAI as OpenAIClient } from \"openai\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport { AIMessage, type BaseMessage } from \"@langchain/core/messages\";\nimport { ChatGenerationChunk, type ChatResult } from \"@langchain/core/outputs\";\nimport { isOpenAITool as isOpenAIFunctionTool } from \"@langchain/core/language_models/base\";\nimport { wrapOpenAIClientError } from \"../utils/client.js\";\nimport {\n ChatOpenAIToolType,\n convertCompletionsCustomTool,\n formatToOpenAIToolChoice,\n isBuiltInTool,\n isBuiltInToolChoice,\n isCustomTool,\n isOpenAICustomTool,\n ResponsesTool,\n} from \"../utils/tools.js\";\nimport { BaseChatOpenAI, BaseChatOpenAICallOptions } from \"./base.js\";\nimport {\n convertMessagesToResponsesInput,\n convertResponsesDeltaToChatGenerationChunk,\n convertResponsesMessageToAIMessage,\n} from \"../converters/responses.js\";\nimport { OpenAIVerbosityParam } from \"../types.js\";\n\nexport interface ChatOpenAIResponsesCallOptions extends BaseChatOpenAICallOptions {\n /**\n * Configuration options for a text response from the model. Can be plain text or\n * structured JSON data.\n */\n text?: OpenAIClient.Responses.ResponseCreateParams[\"text\"];\n\n /**\n * The truncation strategy to use for the model response.\n */\n truncation?: OpenAIClient.Responses.ResponseCreateParams[\"truncation\"];\n\n /**\n * Specify additional output data to include in the model response.\n */\n include?: OpenAIClient.Responses.ResponseCreateParams[\"include\"];\n\n /**\n * The unique ID of the previous response to the model. Use this to create multi-turn\n * conversations.\n */\n previous_response_id?: OpenAIClient.Responses.ResponseCreateParams[\"previous_response_id\"];\n\n /**\n * The verbosity of the model's response.\n */\n verbosity?: OpenAIVerbosityParam;\n}\n\nexport type ChatResponsesInvocationParams = Omit<\n OpenAIClient.Responses.ResponseCreateParams,\n \"input\"\n>;\n\n/**\n * OpenAI Responses API implementation.\n *\n * Will be exported in a later version of @langchain/openai.\n *\n * @internal\n */\nexport class ChatOpenAIResponses<\n CallOptions extends ChatOpenAIResponsesCallOptions =\n ChatOpenAIResponsesCallOptions,\n> extends BaseChatOpenAI<CallOptions> {\n override invocationParams(\n options?: this[\"ParsedCallOptions\"]\n ): ChatResponsesInvocationParams {\n let strict: boolean | undefined;\n if (options?.strict !== undefined) {\n strict = options.strict;\n }\n if (strict === undefined && this.supportsStrictToolCalling !== undefined) {\n strict = this.supportsStrictToolCalling;\n }\n\n const params: ChatResponsesInvocationParams = {\n model: this.model,\n temperature: this.temperature,\n top_p: this.topP,\n user: this.user,\n service_tier: this.service_tier,\n\n // if include_usage is set or streamUsage then stream must be set to true.\n stream: this.streaming,\n previous_response_id: options?.previous_response_id,\n truncation: options?.truncation,\n include: options?.include,\n tools: options?.tools?.length\n ? this._reduceChatOpenAITools(options.tools, {\n stream: this.streaming,\n strict,\n })\n : undefined,\n tool_choice: isBuiltInToolChoice(options?.tool_choice)\n ? options?.tool_choice\n : (() => {\n const formatted = formatToOpenAIToolChoice(options?.tool_choice);\n if (typeof formatted === \"object\" && \"type\" in formatted) {\n if (formatted.type === \"function\") {\n return { type: \"function\", name: formatted.function.name };\n } else if (formatted.type === \"allowed_tools\") {\n return {\n type: \"allowed_tools\",\n mode: formatted.allowed_tools.mode,\n tools: formatted.allowed_tools.tools,\n };\n } else if (formatted.type === \"custom\") {\n return {\n type: \"custom\",\n name: formatted.custom.name,\n };\n }\n }\n return undefined;\n })(),\n text: (() => {\n if (options?.text) return options.text;\n const format = this._getResponseFormat(options?.response_format);\n if (format?.type === \"json_schema\") {\n if (format.json_schema.schema != null) {\n return {\n format: {\n type: \"json_schema\",\n schema: format.json_schema.schema,\n description: format.json_schema.description,\n name: format.json_schema.name,\n strict: format.json_schema.strict,\n },\n verbosity: options?.verbosity,\n };\n }\n return undefined;\n }\n return { format, verbosity: options?.verbosity };\n })(),\n parallel_tool_calls: options?.parallel_tool_calls,\n max_output_tokens: this.maxTokens === -1 ? undefined : this.maxTokens,\n prompt_cache_key: options?.promptCacheKey ?? this.promptCacheKey,\n prompt_cache_retention:\n options?.promptCacheRetention ?? this.promptCacheRetention,\n ...(this.zdrEnabled ? { store: false } : {}),\n ...this.modelKwargs,\n };\n\n const reasoning = this._getReasoningParams(options);\n\n if (reasoning !== undefined) {\n params.reasoning = reasoning;\n }\n\n return params;\n }\n\n async _generate(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n options.signal?.throwIfAborted();\n const invocationParams = this.invocationParams(options);\n if (invocationParams.stream) {\n const stream = this._streamResponseChunks(messages, options, runManager);\n let finalChunk: ChatGenerationChunk | undefined;\n for await (const chunk of stream) {\n chunk.message.response_metadata = {\n ...chunk.generationInfo,\n ...chunk.message.response_metadata,\n };\n finalChunk = finalChunk?.concat(chunk) ?? chunk;\n }\n\n return {\n generations: finalChunk ? [finalChunk] : [],\n llmOutput: {\n estimatedTokenUsage: (finalChunk?.message as AIMessage | undefined)\n ?.usage_metadata,\n },\n };\n } else {\n const data = await this.completionWithRetry(\n {\n input: convertMessagesToResponsesInput({\n messages,\n zdrEnabled: this.zdrEnabled ?? false,\n model: this.model,\n }),\n ...invocationParams,\n stream: false,\n },\n { signal: options?.signal, ...options?.options }\n );\n\n return {\n generations: [\n {\n text: data.output_text,\n message: convertResponsesMessageToAIMessage(data),\n },\n ],\n llmOutput: {\n id: data.id,\n estimatedTokenUsage: data.usage\n ? {\n promptTokens: data.usage.input_tokens,\n completionTokens: data.usage.output_tokens,\n totalTokens: data.usage.total_tokens,\n }\n : undefined,\n },\n };\n }\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const streamIterable = await this.completionWithRetry(\n {\n ...this.invocationParams(options),\n input: convertMessagesToResponsesInput({\n messages,\n zdrEnabled: this.zdrEnabled ?? false,\n model: this.model,\n }),\n stream: true,\n },\n options\n );\n\n for await (const data of streamIterable) {\n if (options.signal?.aborted) {\n return;\n }\n const chunk = convertResponsesDeltaToChatGenerationChunk(data);\n if (chunk == null) continue;\n yield chunk;\n await runManager?.handleLLMNewToken(\n chunk.text || \"\",\n {\n prompt: options.promptIndex ?? 0,\n completion: 0,\n },\n undefined,\n undefined,\n undefined,\n { chunk }\n );\n }\n }\n\n /**\n * Calls the Responses API with retry logic in case of failures.\n * @param request The request to send to the OpenAI API.\n * @param options Optional configuration for the API call.\n * @returns The response from the OpenAI API.\n */\n async completionWithRetry(\n request: OpenAIClient.Responses.ResponseCreateParamsStreaming,\n requestOptions?: OpenAIClient.RequestOptions\n ): Promise<AsyncIterable<OpenAIClient.Responses.ResponseStreamEvent>>;\n\n async completionWithRetry(\n request: OpenAIClient.Responses.ResponseCreateParamsNonStreaming,\n requestOptions?: OpenAIClient.RequestOptions\n ): Promise<OpenAIClient.Responses.Response>;\n\n async completionWithRetry(\n request: OpenAIClient.Responses.ResponseCreateParams,\n requestOptions?: OpenAIClient.RequestOptions\n ): Promise<\n | AsyncIterable<OpenAIClient.Responses.ResponseStreamEvent>\n | OpenAIClient.Responses.Response\n > {\n return this.caller.call(async () => {\n const clientOptions = this._getClientOptions(requestOptions);\n try {\n // use parse if dealing with json_schema\n if (request.text?.format?.type === \"json_schema\" && !request.stream) {\n return await this.client.responses.parse(request, clientOptions);\n }\n return await this.client.responses.create(request, clientOptions);\n } catch (e) {\n const error = wrapOpenAIClientError(e);\n throw error;\n }\n });\n }\n\n /** @internal */\n protected _reduceChatOpenAITools(\n tools: ChatOpenAIToolType[],\n fields: { stream?: boolean; strict?: boolean }\n ): ResponsesTool[] {\n const reducedTools: ResponsesTool[] = [];\n for (const tool of tools) {\n if (isBuiltInTool(tool)) {\n if (tool.type === \"image_generation\" && fields?.stream) {\n // OpenAI sends a 400 error if partial_images is not set and we want to stream.\n // We also set it to 1 since we don't support partial images yet.\n tool.partial_images = 1;\n }\n reducedTools.push(tool);\n } else if (isCustomTool(tool)) {\n const customToolData = tool.metadata.customTool;\n reducedTools.push({\n type: \"custom\",\n name: customToolData.name,\n description: customToolData.description,\n format: customToolData.format,\n } as ResponsesTool);\n } else if (isOpenAIFunctionTool(tool)) {\n reducedTools.push({\n type: \"function\",\n name: tool.function.name,\n parameters: tool.function.parameters,\n description: tool.function.description,\n strict: fields?.strict ?? null,\n });\n } else if (isOpenAICustomTool(tool)) {\n reducedTools.push(convertCompletionsCustomTool(tool));\n }\n }\n return reducedTools;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiEA,IAAa,sBAAb,cAGUA,4BAA4B;CACpC,AAAS,iBACPC,SAC+B;EAC/B,IAAIC;AACJ,MAAI,SAAS,WAAW,QACtB,SAAS,QAAQ;AAEnB,MAAI,WAAW,UAAa,KAAK,8BAA8B,QAC7D,SAAS,KAAK;EAGhB,MAAMC,SAAwC;GAC5C,OAAO,KAAK;GACZ,aAAa,KAAK;GAClB,OAAO,KAAK;GACZ,MAAM,KAAK;GACX,cAAc,KAAK;GAGnB,QAAQ,KAAK;GACb,sBAAsB,SAAS;GAC/B,YAAY,SAAS;GACrB,SAAS,SAAS;GAClB,OAAO,SAAS,OAAO,SACnB,KAAK,uBAAuB,QAAQ,OAAO;IACzC,QAAQ,KAAK;IACb;GACD,EAAC,GACF;GACJ,aAAaC,kCAAoB,SAAS,YAAY,GAClD,SAAS,eACR,MAAM;IACL,MAAM,YAAYC,uCAAyB,SAAS,YAAY;AAChE,QAAI,OAAO,cAAc,YAAY,UAAU,WAC7C;SAAI,UAAU,SAAS,WACrB,QAAO;MAAE,MAAM;MAAY,MAAM,UAAU,SAAS;KAAM;cACjD,UAAU,SAAS,gBAC5B,QAAO;MACL,MAAM;MACN,MAAM,UAAU,cAAc;MAC9B,OAAO,UAAU,cAAc;KAChC;cACQ,UAAU,SAAS,SAC5B,QAAO;MACL,MAAM;MACN,MAAM,UAAU,OAAO;KACxB;IACF;AAEH,WAAO;GACR,IAAG;GACR,OAAO,MAAM;AACX,QAAI,SAAS,KAAM,QAAO,QAAQ;IAClC,MAAM,SAAS,KAAK,mBAAmB,SAAS,gBAAgB;AAChE,QAAI,QAAQ,SAAS,eAAe;AAClC,SAAI,OAAO,YAAY,UAAU,KAC/B,QAAO;MACL,QAAQ;OACN,MAAM;OACN,QAAQ,OAAO,YAAY;OAC3B,aAAa,OAA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AM,iBAAiB,KAAK,SAAS;GACrC,aAAa,KAAK;IAChB,MAAM;IACN,MAAM,eAAe;IACrB,aAAa,eAAe;IAC5B,QAAQ,eAAe;GACxB,EAAkB;EACpB,mEAA+B,KAAK,EACnC,aAAa,KAAK;GAChB,MAAM;GACN,MAAM,KAAK,SAAS;GACpB,YAAY,KAAK,SAAS;GAC1B,aAAa,KAAK,SAAS;GAC3B,QAAQ,QAAQ,UAAU;EAC3B,EAAC;WACOC,iCAAmB,KAAK,EACjC,aAAa,KAAKC,2CAA6B,KAAK,CAAC;AAGzD,SAAO;CACR;AACF"}
@@ -22,6 +22,7 @@ var ChatOpenAIResponses = class extends BaseChatOpenAI {
22
22
  temperature: this.temperature,
23
23
  top_p: this.topP,
24
24
  user: this.user,
25
+ service_tier: this.service_tier,
25
26
  stream: this.streaming,
26
27
  previous_response_id: options?.previous_response_id,
27
28
  truncation: options?.truncation,
@@ -1 +1 @@
1
- {"version":3,"file":"responses.js","names":["options?: this[\"ParsedCallOptions\"]","strict: boolean | undefined","params: ChatResponsesInvocationParams","messages: BaseMessage[]","options: this[\"ParsedCallOptions\"]","runManager?: CallbackManagerForLLMRun","finalChunk: ChatGenerationChunk | undefined","request: OpenAIClient.Responses.ResponseCreateParams","requestOptions?: OpenAIClient.RequestOptions","tools: ChatOpenAIToolType[]","fields: { stream?: boolean; strict?: boolean }","reducedTools: ResponsesTool[]","isOpenAIFunctionTool"],"sources":["../../src/chat_models/responses.ts"],"sourcesContent":["import { OpenAI as OpenAIClient } from \"openai\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport { AIMessage, type BaseMessage } from \"@langchain/core/messages\";\nimport { ChatGenerationChunk, type ChatResult } from \"@langchain/core/outputs\";\nimport { isOpenAITool as isOpenAIFunctionTool } from \"@langchain/core/language_models/base\";\nimport { wrapOpenAIClientError } from \"../utils/client.js\";\nimport {\n ChatOpenAIToolType,\n convertCompletionsCustomTool,\n formatToOpenAIToolChoice,\n isBuiltInTool,\n isBuiltInToolChoice,\n isCustomTool,\n isOpenAICustomTool,\n ResponsesTool,\n} from \"../utils/tools.js\";\nimport { BaseChatOpenAI, BaseChatOpenAICallOptions } from \"./base.js\";\nimport {\n convertMessagesToResponsesInput,\n convertResponsesDeltaToChatGenerationChunk,\n convertResponsesMessageToAIMessage,\n} from \"../converters/responses.js\";\nimport { OpenAIVerbosityParam } from \"../types.js\";\n\nexport interface ChatOpenAIResponsesCallOptions extends BaseChatOpenAICallOptions {\n /**\n * Configuration options for a text response from the model. Can be plain text or\n * structured JSON data.\n */\n text?: OpenAIClient.Responses.ResponseCreateParams[\"text\"];\n\n /**\n * The truncation strategy to use for the model response.\n */\n truncation?: OpenAIClient.Responses.ResponseCreateParams[\"truncation\"];\n\n /**\n * Specify additional output data to include in the model response.\n */\n include?: OpenAIClient.Responses.ResponseCreateParams[\"include\"];\n\n /**\n * The unique ID of the previous response to the model. Use this to create multi-turn\n * conversations.\n */\n previous_response_id?: OpenAIClient.Responses.ResponseCreateParams[\"previous_response_id\"];\n\n /**\n * The verbosity of the model's response.\n */\n verbosity?: OpenAIVerbosityParam;\n}\n\nexport type ChatResponsesInvocationParams = Omit<\n OpenAIClient.Responses.ResponseCreateParams,\n \"input\"\n>;\n\n/**\n * OpenAI Responses API implementation.\n *\n * Will be exported in a later version of @langchain/openai.\n *\n * @internal\n */\nexport class ChatOpenAIResponses<\n CallOptions extends ChatOpenAIResponsesCallOptions =\n ChatOpenAIResponsesCallOptions,\n> extends BaseChatOpenAI<CallOptions> {\n override invocationParams(\n options?: this[\"ParsedCallOptions\"]\n ): ChatResponsesInvocationParams {\n let strict: boolean | undefined;\n if (options?.strict !== undefined) {\n strict = options.strict;\n }\n if (strict === undefined && this.supportsStrictToolCalling !== undefined) {\n strict = this.supportsStrictToolCalling;\n }\n\n const params: ChatResponsesInvocationParams = {\n model: this.model,\n temperature: this.temperature,\n top_p: this.topP,\n user: this.user,\n\n // if include_usage is set or streamUsage then stream must be set to true.\n stream: this.streaming,\n previous_response_id: options?.previous_response_id,\n truncation: options?.truncation,\n include: options?.include,\n tools: options?.tools?.length\n ? this._reduceChatOpenAITools(options.tools, {\n stream: this.streaming,\n strict,\n })\n : undefined,\n tool_choice: isBuiltInToolChoice(options?.tool_choice)\n ? options?.tool_choice\n : (() => {\n const formatted = formatToOpenAIToolChoice(options?.tool_choice);\n if (typeof formatted === \"object\" && \"type\" in formatted) {\n if (formatted.type === \"function\") {\n return { type: \"function\", name: formatted.function.name };\n } else if (formatted.type === \"allowed_tools\") {\n return {\n type: \"allowed_tools\",\n mode: formatted.allowed_tools.mode,\n tools: formatted.allowed_tools.tools,\n };\n } else if (formatted.type === \"custom\") {\n return {\n type: \"custom\",\n name: formatted.custom.name,\n };\n }\n }\n return undefined;\n })(),\n text: (() => {\n if (options?.text) return options.text;\n const format = this._getResponseFormat(options?.response_format);\n if (format?.type === \"json_schema\") {\n if (format.json_schema.schema != null) {\n return {\n format: {\n type: \"json_schema\",\n schema: format.json_schema.schema,\n description: format.json_schema.description,\n name: format.json_schema.name,\n strict: format.json_schema.strict,\n },\n verbosity: options?.verbosity,\n };\n }\n return undefined;\n }\n return { format, verbosity: options?.verbosity };\n })(),\n parallel_tool_calls: options?.parallel_tool_calls,\n max_output_tokens: this.maxTokens === -1 ? undefined : this.maxTokens,\n prompt_cache_key: options?.promptCacheKey ?? this.promptCacheKey,\n prompt_cache_retention:\n options?.promptCacheRetention ?? this.promptCacheRetention,\n ...(this.zdrEnabled ? { store: false } : {}),\n ...this.modelKwargs,\n };\n\n const reasoning = this._getReasoningParams(options);\n\n if (reasoning !== undefined) {\n params.reasoning = reasoning;\n }\n\n return params;\n }\n\n async _generate(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n options.signal?.throwIfAborted();\n const invocationParams = this.invocationParams(options);\n if (invocationParams.stream) {\n const stream = this._streamResponseChunks(messages, options, runManager);\n let finalChunk: ChatGenerationChunk | undefined;\n for await (const chunk of stream) {\n chunk.message.response_metadata = {\n ...chunk.generationInfo,\n ...chunk.message.response_metadata,\n };\n finalChunk = finalChunk?.concat(chunk) ?? chunk;\n }\n\n return {\n generations: finalChunk ? [finalChunk] : [],\n llmOutput: {\n estimatedTokenUsage: (finalChunk?.message as AIMessage | undefined)\n ?.usage_metadata,\n },\n };\n } else {\n const data = await this.completionWithRetry(\n {\n input: convertMessagesToResponsesInput({\n messages,\n zdrEnabled: this.zdrEnabled ?? false,\n model: this.model,\n }),\n ...invocationParams,\n stream: false,\n },\n { signal: options?.signal, ...options?.options }\n );\n\n return {\n generations: [\n {\n text: data.output_text,\n message: convertResponsesMessageToAIMessage(data),\n },\n ],\n llmOutput: {\n id: data.id,\n estimatedTokenUsage: data.usage\n ? {\n promptTokens: data.usage.input_tokens,\n completionTokens: data.usage.output_tokens,\n totalTokens: data.usage.total_tokens,\n }\n : undefined,\n },\n };\n }\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const streamIterable = await this.completionWithRetry(\n {\n ...this.invocationParams(options),\n input: convertMessagesToResponsesInput({\n messages,\n zdrEnabled: this.zdrEnabled ?? false,\n model: this.model,\n }),\n stream: true,\n },\n options\n );\n\n for await (const data of streamIterable) {\n if (options.signal?.aborted) {\n return;\n }\n const chunk = convertResponsesDeltaToChatGenerationChunk(data);\n if (chunk == null) continue;\n yield chunk;\n await runManager?.handleLLMNewToken(\n chunk.text || \"\",\n {\n prompt: options.promptIndex ?? 0,\n completion: 0,\n },\n undefined,\n undefined,\n undefined,\n { chunk }\n );\n }\n }\n\n /**\n * Calls the Responses API with retry logic in case of failures.\n * @param request The request to send to the OpenAI API.\n * @param options Optional configuration for the API call.\n * @returns The response from the OpenAI API.\n */\n async completionWithRetry(\n request: OpenAIClient.Responses.ResponseCreateParamsStreaming,\n requestOptions?: OpenAIClient.RequestOptions\n ): Promise<AsyncIterable<OpenAIClient.Responses.ResponseStreamEvent>>;\n\n async completionWithRetry(\n request: OpenAIClient.Responses.ResponseCreateParamsNonStreaming,\n requestOptions?: OpenAIClient.RequestOptions\n ): Promise<OpenAIClient.Responses.Response>;\n\n async completionWithRetry(\n request: OpenAIClient.Responses.ResponseCreateParams,\n requestOptions?: OpenAIClient.RequestOptions\n ): Promise<\n | AsyncIterable<OpenAIClient.Responses.ResponseStreamEvent>\n | OpenAIClient.Responses.Response\n > {\n return this.caller.call(async () => {\n const clientOptions = this._getClientOptions(requestOptions);\n try {\n // use parse if dealing with json_schema\n if (request.text?.format?.type === \"json_schema\" && !request.stream) {\n return await this.client.responses.parse(request, clientOptions);\n }\n return await this.client.responses.create(request, clientOptions);\n } catch (e) {\n const error = wrapOpenAIClientError(e);\n throw error;\n }\n });\n }\n\n /** @internal */\n protected _reduceChatOpenAITools(\n tools: ChatOpenAIToolType[],\n fields: { stream?: boolean; strict?: boolean }\n ): ResponsesTool[] {\n const reducedTools: ResponsesTool[] = [];\n for (const tool of tools) {\n if (isBuiltInTool(tool)) {\n if (tool.type === \"image_generation\" && fields?.stream) {\n // OpenAI sends a 400 error if partial_images is not set and we want to stream.\n // We also set it to 1 since we don't support partial images yet.\n tool.partial_images = 1;\n }\n reducedTools.push(tool);\n } else if (isCustomTool(tool)) {\n const customToolData = tool.metadata.customTool;\n reducedTools.push({\n type: \"custom\",\n name: customToolData.name,\n description: customToolData.description,\n format: customToolData.format,\n } as ResponsesTool);\n } else if (isOpenAIFunctionTool(tool)) {\n reducedTools.push({\n type: \"function\",\n name: tool.function.name,\n parameters: tool.function.parameters,\n description: tool.function.description,\n strict: fields?.strict ?? null,\n });\n } else if (isOpenAICustomTool(tool)) {\n reducedTools.push(convertCompletionsCustomTool(tool));\n }\n }\n return reducedTools;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAiEA,IAAa,sBAAb,cAGU,eAA4B;CACpC,AAAS,iBACPA,SAC+B;EAC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AAK,SAAS;GAC1B,aAAa,KAAK,SAAS;GAC3B,QAAQ,QAAQ,UAAU;EAC3B,EAAC;WACO,mBAAmB,KAAK,EACjC,aAAa,KAAK,6BAA6B,KAAK,CAAC;AAGzD,SAAO;CACR;AACF"}
1
+ {"version":3,"file":"responses.js","names":["options?: this[\"ParsedCallOptions\"]","strict: boolean | undefined","params: ChatResponsesInvocationParams","messages: BaseMessage[]","options: this[\"ParsedCallOptions\"]","runManager?: CallbackManagerForLLMRun","finalChunk: ChatGenerationChunk | undefined","request: OpenAIClient.Responses.ResponseCreateParams","requestOptions?: OpenAIClient.RequestOptions","tools: ChatOpenAIToolType[]","fields: { stream?: boolean; strict?: boolean }","reducedTools: ResponsesTool[]","isOpenAIFunctionTool"],"sources":["../../src/chat_models/responses.ts"],"sourcesContent":["import { OpenAI as OpenAIClient } from \"openai\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport { AIMessage, type BaseMessage } from \"@langchain/core/messages\";\nimport { ChatGenerationChunk, type ChatResult } from \"@langchain/core/outputs\";\nimport { isOpenAITool as isOpenAIFunctionTool } from \"@langchain/core/language_models/base\";\nimport { wrapOpenAIClientError } from \"../utils/client.js\";\nimport {\n ChatOpenAIToolType,\n convertCompletionsCustomTool,\n formatToOpenAIToolChoice,\n isBuiltInTool,\n isBuiltInToolChoice,\n isCustomTool,\n isOpenAICustomTool,\n ResponsesTool,\n} from \"../utils/tools.js\";\nimport { BaseChatOpenAI, BaseChatOpenAICallOptions } from \"./base.js\";\nimport {\n convertMessagesToResponsesInput,\n convertResponsesDeltaToChatGenerationChunk,\n convertResponsesMessageToAIMessage,\n} from \"../converters/responses.js\";\nimport { OpenAIVerbosityParam } from \"../types.js\";\n\nexport interface ChatOpenAIResponsesCallOptions extends BaseChatOpenAICallOptions {\n /**\n * Configuration options for a text response from the model. Can be plain text or\n * structured JSON data.\n */\n text?: OpenAIClient.Responses.ResponseCreateParams[\"text\"];\n\n /**\n * The truncation strategy to use for the model response.\n */\n truncation?: OpenAIClient.Responses.ResponseCreateParams[\"truncation\"];\n\n /**\n * Specify additional output data to include in the model response.\n */\n include?: OpenAIClient.Responses.ResponseCreateParams[\"include\"];\n\n /**\n * The unique ID of the previous response to the model. Use this to create multi-turn\n * conversations.\n */\n previous_response_id?: OpenAIClient.Responses.ResponseCreateParams[\"previous_response_id\"];\n\n /**\n * The verbosity of the model's response.\n */\n verbosity?: OpenAIVerbosityParam;\n}\n\nexport type ChatResponsesInvocationParams = Omit<\n OpenAIClient.Responses.ResponseCreateParams,\n \"input\"\n>;\n\n/**\n * OpenAI Responses API implementation.\n *\n * Will be exported in a later version of @langchain/openai.\n *\n * @internal\n */\nexport class ChatOpenAIResponses<\n CallOptions extends ChatOpenAIResponsesCallOptions =\n ChatOpenAIResponsesCallOptions,\n> extends BaseChatOpenAI<CallOptions> {\n override invocationParams(\n options?: this[\"ParsedCallOptions\"]\n ): ChatResponsesInvocationParams {\n let strict: boolean | undefined;\n if (options?.strict !== undefined) {\n strict = options.strict;\n }\n if (strict === undefined && this.supportsStrictToolCalling !== undefined) {\n strict = this.supportsStrictToolCalling;\n }\n\n const params: ChatResponsesInvocationParams = {\n model: this.model,\n temperature: this.temperature,\n top_p: this.topP,\n user: this.user,\n service_tier: this.service_tier,\n\n // if include_usage is set or streamUsage then stream must be set to true.\n stream: this.streaming,\n previous_response_id: options?.previous_response_id,\n truncation: options?.truncation,\n include: options?.include,\n tools: options?.tools?.length\n ? this._reduceChatOpenAITools(options.tools, {\n stream: this.streaming,\n strict,\n })\n : undefined,\n tool_choice: isBuiltInToolChoice(options?.tool_choice)\n ? options?.tool_choice\n : (() => {\n const formatted = formatToOpenAIToolChoice(options?.tool_choice);\n if (typeof formatted === \"object\" && \"type\" in formatted) {\n if (formatted.type === \"function\") {\n return { type: \"function\", name: formatted.function.name };\n } else if (formatted.type === \"allowed_tools\") {\n return {\n type: \"allowed_tools\",\n mode: formatted.allowed_tools.mode,\n tools: formatted.allowed_tools.tools,\n };\n } else if (formatted.type === \"custom\") {\n return {\n type: \"custom\",\n name: formatted.custom.name,\n };\n }\n }\n return undefined;\n })(),\n text: (() => {\n if (options?.text) return options.text;\n const format = this._getResponseFormat(options?.response_format);\n if (format?.type === \"json_schema\") {\n if (format.json_schema.schema != null) {\n return {\n format: {\n type: \"json_schema\",\n schema: format.json_schema.schema,\n description: format.json_schema.description,\n name: format.json_schema.name,\n strict: format.json_schema.strict,\n },\n verbosity: options?.verbosity,\n };\n }\n return undefined;\n }\n return { format, verbosity: options?.verbosity };\n })(),\n parallel_tool_calls: options?.parallel_tool_calls,\n max_output_tokens: this.maxTokens === -1 ? undefined : this.maxTokens,\n prompt_cache_key: options?.promptCacheKey ?? this.promptCacheKey,\n prompt_cache_retention:\n options?.promptCacheRetention ?? this.promptCacheRetention,\n ...(this.zdrEnabled ? { store: false } : {}),\n ...this.modelKwargs,\n };\n\n const reasoning = this._getReasoningParams(options);\n\n if (reasoning !== undefined) {\n params.reasoning = reasoning;\n }\n\n return params;\n }\n\n async _generate(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n options.signal?.throwIfAborted();\n const invocationParams = this.invocationParams(options);\n if (invocationParams.stream) {\n const stream = this._streamResponseChunks(messages, options, runManager);\n let finalChunk: ChatGenerationChunk | undefined;\n for await (const chunk of stream) {\n chunk.message.response_metadata = {\n ...chunk.generationInfo,\n ...chunk.message.response_metadata,\n };\n finalChunk = finalChunk?.concat(chunk) ?? chunk;\n }\n\n return {\n generations: finalChunk ? [finalChunk] : [],\n llmOutput: {\n estimatedTokenUsage: (finalChunk?.message as AIMessage | undefined)\n ?.usage_metadata,\n },\n };\n } else {\n const data = await this.completionWithRetry(\n {\n input: convertMessagesToResponsesInput({\n messages,\n zdrEnabled: this.zdrEnabled ?? false,\n model: this.model,\n }),\n ...invocationParams,\n stream: false,\n },\n { signal: options?.signal, ...options?.options }\n );\n\n return {\n generations: [\n {\n text: data.output_text,\n message: convertResponsesMessageToAIMessage(data),\n },\n ],\n llmOutput: {\n id: data.id,\n estimatedTokenUsage: data.usage\n ? {\n promptTokens: data.usage.input_tokens,\n completionTokens: data.usage.output_tokens,\n totalTokens: data.usage.total_tokens,\n }\n : undefined,\n },\n };\n }\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const streamIterable = await this.completionWithRetry(\n {\n ...this.invocationParams(options),\n input: convertMessagesToResponsesInput({\n messages,\n zdrEnabled: this.zdrEnabled ?? false,\n model: this.model,\n }),\n stream: true,\n },\n options\n );\n\n for await (const data of streamIterable) {\n if (options.signal?.aborted) {\n return;\n }\n const chunk = convertResponsesDeltaToChatGenerationChunk(data);\n if (chunk == null) continue;\n yield chunk;\n await runManager?.handleLLMNewToken(\n chunk.text || \"\",\n {\n prompt: options.promptIndex ?? 0,\n completion: 0,\n },\n undefined,\n undefined,\n undefined,\n { chunk }\n );\n }\n }\n\n /**\n * Calls the Responses API with retry logic in case of failures.\n * @param request The request to send to the OpenAI API.\n * @param options Optional configuration for the API call.\n * @returns The response from the OpenAI API.\n */\n async completionWithRetry(\n request: OpenAIClient.Responses.ResponseCreateParamsStreaming,\n requestOptions?: OpenAIClient.RequestOptions\n ): Promise<AsyncIterable<OpenAIClient.Responses.ResponseStreamEvent>>;\n\n async completionWithRetry(\n request: OpenAIClient.Responses.ResponseCreateParamsNonStreaming,\n requestOptions?: OpenAIClient.RequestOptions\n ): Promise<OpenAIClient.Responses.Response>;\n\n async completionWithRetry(\n request: OpenAIClient.Responses.ResponseCreateParams,\n requestOptions?: OpenAIClient.RequestOptions\n ): Promise<\n | AsyncIterable<OpenAIClient.Responses.ResponseStreamEvent>\n | OpenAIClient.Responses.Response\n > {\n return this.caller.call(async () => {\n const clientOptions = this._getClientOptions(requestOptions);\n try {\n // use parse if dealing with json_schema\n if (request.text?.format?.type === \"json_schema\" && !request.stream) {\n return await this.client.responses.parse(request, clientOptions);\n }\n return await this.client.responses.create(request, clientOptions);\n } catch (e) {\n const error = wrapOpenAIClientError(e);\n throw error;\n }\n });\n }\n\n /** @internal */\n protected _reduceChatOpenAITools(\n tools: ChatOpenAIToolType[],\n fields: { stream?: boolean; strict?: boolean }\n ): ResponsesTool[] {\n const reducedTools: ResponsesTool[] = [];\n for (const tool of tools) {\n if (isBuiltInTool(tool)) {\n if (tool.type === \"image_generation\" && fields?.stream) {\n // OpenAI sends a 400 error if partial_images is not set and we want to stream.\n // We also set it to 1 since we don't support partial images yet.\n tool.partial_images = 1;\n }\n reducedTools.push(tool);\n } else if (isCustomTool(tool)) {\n const customToolData = tool.metadata.customTool;\n reducedTools.push({\n type: \"custom\",\n name: customToolData.name,\n description: customToolData.description,\n format: customToolData.format,\n } as ResponsesTool);\n } else if (isOpenAIFunctionTool(tool)) {\n reducedTools.push({\n type: \"function\",\n name: tool.function.name,\n parameters: tool.function.parameters,\n description: tool.function.description,\n strict: fields?.strict ?? null,\n });\n } else if (isOpenAICustomTool(tool)) {\n reducedTools.push(convertCompletionsCustomTool(tool));\n }\n }\n return reducedTools;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAiEA,IAAa,sBAAb,cAGU,eAA4B;CACpC,AAAS,iBACPA,SAC+B;EAC/B,IAAIC;AACJ,MAAI,SAAS,WAAW,QACtB,SAAS,QAAQ;AAEnB,MAAI,WAAW,UAAa,KAAK,8BAA8B,QAC7D,SAAS,KAAK;EAGhB,MAAMC,SAAwC;GAC5C,OAAO,KAAK;GACZ,aAAa,KAAK;GAClB,OAAO,KAAK;GACZ,MAAM,KAAK;GACX,cAAc,KAAK;GAGnB,QAAQ,KAAK;GACb,sBAAsB,SAAS;GAC/B,YAAY,SAAS;GACrB,SAAS,SAAS;GAClB,OAAO,SAAS,OAAO,SACnB,KAAK,uBAAuB,QAAQ,OAAO;IACzC,QAAQ,KAAK;IACb;GACD,EAAC,GACF;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AAO,EACV;EACF;CACF;CAkBD,MAAM,oBACJE,SACAC,gBAIA;AACA,SAAO,KAAK,OAAO,KAAK,YAAY;GAClC,MAAM,gBAAgB,KAAK,kBAAkB,eAAe;AAC5D,OAAI;AAEF,QAAI,QAAQ,MAAM,QAAQ,SAAS,iBAAiB,CAAC,QAAQ,OAC3D,QAAO,MAAM,KAAK,OAAO,UAAU,MAAM,SAAS,cAAc;AAElE,WAAO,MAAM,KAAK,OAAO,UAAU,OAAO,SAAS,cAAc;GAClE,SAAQ,GAAG;IACV,MAAM,QAAQ,sBAAsB,EAAE;AACtC,UAAM;GACP;EACF,EAAC;CACH;;CAGD,AAAU,uBACRC,OACAC,QACiB;EACjB,MAAMC,eAAgC,CAAE;AACxC,OAAK,MAAM,QAAQ,MACjB,KAAI,cAAc,KAAK,EAAE;AACvB,OAAI,KAAK,SAAS,sBAAsB,QAAQ,QAG9C,KAAK,iBAAiB;GAExB,aAAa,KAAK,KAAK;EACxB,WAAU,aAAa,KAAK,EAAE;GAC7B,MAAM,iBAAiB,KAAK,SAAS;GACrC,aAAa,KAAK;IAChB,MAAM;IACN,MAAM,eAAe;IACrB,aAAa,eAAe;IAC5B,QAAQ,eAAe;GACxB,EAAkB;EACpB,WAAUC,aAAqB,KAAK,EACnC,aAAa,KAAK;GAChB,MAAM;GACN,MAAM,KAAK,SAAS;GACpB,YAAY,KAAK,SAAS;GAC1B,aAAa,KAAK,SAAS;GAC3B,QAAQ,QAAQ,UAAU;EAC3B,EAAC;WACO,mBAAmB,KAAK,EACjC,aAAa,KAAK,6BAA6B,KAAK,CAAC;AAGzD,SAAO;CACR;AACF"}
@@ -216,6 +216,14 @@ const convertResponsesMessageToAIMessage = (response) => {
216
216
  const content = [];
217
217
  const tool_calls = [];
218
218
  const invalid_tool_calls = [];
219
+ const cleanedOutput = response.output.map((item) => {
220
+ if (item.type === "function_call" && "parsed_arguments" in item) {
221
+ const cleaned = { ...item };
222
+ delete cleaned.parsed_arguments;
223
+ return cleaned;
224
+ }
225
+ return item;
226
+ });
219
227
  const response_metadata = {
220
228
  model_provider: "openai",
221
229
  model: response.model,
@@ -224,6 +232,7 @@ const convertResponsesMessageToAIMessage = (response) => {
224
232
  incomplete_details: response.incomplete_details,
225
233
  metadata: response.metadata,
226
234
  object: response.object,
235
+ output: cleanedOutput,
227
236
  status: response.status,
228
237
  user: response.user,
229
238
  service_tier: response.service_tier,
@@ -495,7 +504,11 @@ const convertResponsesDeltaToChatGenerationChunk = (event) => {
495
504
  const msg = convertResponsesMessageToAIMessage(event.response);
496
505
  usage_metadata = convertResponsesUsageToUsageMetadata(event.response.usage);
497
506
  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)) if (key !== "id") response_metadata[key] = value;
507
+ for (const [key, value] of Object.entries(event.response)) {
508
+ if (key === "id") continue;
509
+ if (key === "output") response_metadata[key] = msg.response_metadata.output;
510
+ else response_metadata[key] = value;
511
+ }
499
512
  } else if (event.type === "response.function_call_arguments.delta" || event.type === "response.custom_tool_call_input.delta") tool_call_chunks.push({
500
513
  type: "tool_call_chunk",
501
514
  args: event.delta,
@@ -1 +1 @@
1
- {"version":3,"file":"responses.cjs","names":["annotation: OpenAIAnnotation","annotation:\n | ContentBlock.Citation\n | ContentBlock.NonStandard\n | Record<string, unknown>","convertResponsesUsageToUsageMetadata: Converter<\n OpenAIClient.Responses.ResponseUsage | undefined,\n UsageMetadata\n>","convertResponsesMessageToAIMessage: Converter<\n ResponsesCreateInvoke | ResponsesParseInvoke,\n AIMessage\n>","messageId: string | undefined","content: MessageContent","tool_calls: ToolCall[]","invalid_tool_calls: InvalidToolCall[]","response_metadata: Record<string, unknown>","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 }","e: unknown","errMessage: string | undefined","parseCustomToolCall","parseComputerCall","AIMessage","convertReasoningSummaryToResponsesReasoningItem: Converter<\n ChatOpenAIReasoningSummary,\n OpenAIClient.Responses.ResponseReasoningItem\n>","convertResponsesDeltaToChatGenerationChunk: Converter<\n OpenAIClient.Responses.ResponseStreamEvent,\n ChatGenerationChunk | null\n>","content: ContentBlock[]","generationInfo: Record<string, unknown>","usage_metadata: UsageMetadata | undefined","tool_call_chunks: ToolCallChunk[]","additional_kwargs: {\n [key: string]: unknown;\n reasoning?: Partial<ChatOpenAIReasoningSummary>;\n tool_outputs?: unknown[];\n }","id: string | undefined","summary: ChatOpenAIReasoningSummary[\"summary\"] | undefined","ChatGenerationChunk","AIMessageChunk","convertStandardContentMessageToResponsesInput: Converter<\n BaseMessage,\n OpenAIClient.Responses.ResponseInputItem[]\n>","iife","messageToOpenAIRole","currentMessage: OpenAIClient.Responses.EasyInputMessage | undefined","pushMessageContent: (\n content: OpenAIClient.Responses.ResponseInputMessageContentList\n ) => void","value: unknown","block: ContentBlock.Multimodal.Image","block: ContentBlock.Multimodal.File | ContentBlock.Multimodal.Video","getFilenameFromMetadata","getRequiredFilenameFromMetadata","block: ContentBlock.Reasoning","reasoningItem: OpenAIClient.Responses.ResponseReasoningItem","block: ContentBlock.Tools.ToolCall | ContentBlock.Tools.ServerToolCall","block: ContentBlock.Tools.ServerToolCallResult","convertMessagesToResponsesInput: Converter<\n { messages: BaseMessage[]; zdrEnabled: boolean; model: string },\n ResponsesInputItem[]\n>","isReasoningModel","input: ResponsesInputItem[]","isCustomToolCall","isComputerToolCall","fallthroughCallTypes: ResponsesInputItem[\"type\"][]","messages: ResponsesInputItem[]","messages","completionsApiContentBlockConverter"],"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__\";\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 let messageId: string | undefined;\n const content: MessageContent = [];\n const tool_calls: ToolCall[] = [];\n const invalid_tool_calls: InvalidToolCall[] = [];\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 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 } = {};\n\n for (const item of response.output) {\n if (item.type === \"message\") {\n messageId = item.id;\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 return {\n type: \"text\",\n text: part.text,\n annotations: part.annotations.map(\n convertOpenAIAnnotationToLangChain\n ),\n } satisfies ContentBlock.Text;\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 } 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: messageId,\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 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`: Message ID (set when a message output item is added)\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 id = event.item.id;\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.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 ].includes(event.item.type)\n ) {\n additional_kwargs.tool_outputs = [event.item];\n } else if (event.type === \"response.created\") {\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 (event.type === \"response.completed\") {\n const msg = convertResponsesMessageToAIMessage(event.response);\n\n usage_metadata = convertResponsesUsageToUsageMetadata(event.response.usage);\n\n if (event.response.text?.format?.type === \"json_schema\") {\n additional_kwargs.parsed ??= JSON.parse(msg.text);\n }\n for (const [key, value] of Object.entries(event.response)) {\n if (key !== \"id\") response_metadata[key] = value;\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 });\n } else if (\n event.type === \"response.web_search_call.completed\" ||\n event.type === \"response.file_search_call.completed\"\n ) {\n generationInfo = {\n tool_outputs: {\n id: event.item_id,\n type: event.type.replace(\"response.\", \"\").replace(\".completed\", \"\"),\n status: \"completed\",\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 });\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 });\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 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 ) => void = (content) => {\n if (!currentMessage) {\n currentMessage = {\n type: \"message\",\n role: messageRole,\n content: [],\n };\n }\n if (typeof currentMessage.content === \"string\") {\n currentMessage.content =\n currentMessage.content.length > 0\n ? [{ type: \"input_text\", text: 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 ? { 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 const reasoningItem: OpenAIClient.Responses.ResponseReasoningItem = {\n type: \"reasoning\",\n id: block.id ?? \"\",\n summary,\n };\n\n if (block.reasoning) {\n reasoningItem.content = [\n {\n type: \"reasoning_text\" as const,\n text: block.reasoning,\n },\n ];\n }\n return reasoningItem;\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 pushMessageContent([{ type: \"input_text\", text: block.text }]);\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([\n {\n type: \"input_text\",\n text: block.text,\n },\n ]);\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 as { content: ContentBlock[] };\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 input.push({\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 return {\n type: \"output_text\",\n text: item.text,\n annotations: (item.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 });\n }\n\n const functionCallIds = additional_kwargs?.[_FUNCTION_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)) {\n return {\n type: \"custom_tool_call\",\n id: toolCall.call_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 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;;;;;;;;;;;;AAgBnC,SAAS,mCACPA,YACkD;AAClD,KAAI,WAAW,SAAS,eACtB,QAAO;EACL,MAAM;EACN,QAAQ;EACR,KAAK,WAAW;EAChB,OAAO,WAAW;EAClB,YAAY,WAAW;EACvB,UAAU,WAAW;CACtB;AAGH,KAAI,WAAW,SAAS,gBACtB,QAAO;EACL,MAAM;EACN,QAAQ;EACR,OAAO,WAAW;EAClB,YAAY,WAAW;EAEvB,SAAS,WAAW;CACrB;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;CAC1B;AAGH,KAAI,WAAW,SAAS,YACtB,QAAO;EACL,MAAM;EACN,QAAQ;EACR,YAAY,WAAW;EACvB,SAAS,WA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C,CAAE;GACzC,MAAM,UAAW,MAAM,QAA2B,QAAQ,CAAC,SAAS;AAClE,QAAI,KAAK,SAAS,yBAChBC,WAAS,KAAK;KACZ,MAAM;KACN,qBAAqB,KAAK;KAC1B,SAAS,KAAK;IACf,EAAC;AAEJ,0DAAuB,KAAK,CAC1B,qEACE,MACAC,wDACD;AAEH,QAAI,KAAK,SAAS,OAChB,QAAO;KACL,MAAM;KACN,MAAM,KAAK;IACZ;AAEH,QAAI,KAAK,SAAS,aAAa;KAC7B,MAAM,WAAWrB,kBAAK,MAAM;AAC1B,UAAI,OAAO,KAAK,cAAc,SAC5B,QAAO,KAAK;eAEZ,OAAO,KAAK,cAAc,YAC1B,KAAK,cAAc,QACnB,SAAS,KAAK,UAEd,QAAO,KAAK,UAAU;AAExB,aAAO;KACR,EAAC;KACF,MAAM,SAASA,kBAAK,MAAM;AACxB,UAAI,OAAO,KAAK,cAAc,SAC5B,QAAO;eAEP,OAAO,KAAK,cAAc,YAC1B,KAAK,cAAc,QACnB,YAAY,KAAK,UAEjB,QAAO,KAAK,UAAU;AAExB,aAAO;KACR,EAAC;AACF,YAAO;MACL,MAAM;MACN,WAAW;MACX;KACD;IACF;AACD,QACE,KAAK,SAAS,gBACd,KAAK,SAAS,iBACd,KAAK,SAAS,aAEd,QAAO;AAET,WAAO,CAAE;GACV,EAAC;AAEF,OAAI,QAAQ,SAAS,GACnBoB,WAAS,KAAK;IACZ,MAAM;IACN;IACS;GACV,EAAC;AAEJ,UAAOA;EACR;EAED,QAAQ,KACN,CAAC,gEAAgE,EAAE,MAAM,CAC1E;AACD,SAAO,CAAE;CACV,EACF;AACF"}
1
+ {"version":3,"file":"responses.cjs","names":["annotation: OpenAIAnnotation","annotation:\n | ContentBlock.Citation\n | ContentBlock.NonStandard\n | Record<string, unknown>","convertResponsesUsageToUsageMetadata: Converter<\n OpenAIClient.Responses.ResponseUsage | undefined,\n UsageMetadata\n>","convertResponsesMessageToAIMessage: Converter<\n ResponsesCreateInvoke | ResponsesParseInvoke,\n AIMessage\n>","messageId: string | undefined","content: MessageContent","tool_calls: ToolCall[]","invalid_tool_calls: InvalidToolCall[]","response_metadata: Record<string, unknown>","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 }","e: unknown","errMessage: string | undefined","parseCustomToolCall","parseComputerCall","AIMessage","convertReasoningSummaryToResponsesReasoningItem: Converter<\n ChatOpenAIReasoningSummary,\n OpenAIClient.Responses.ResponseReasoningItem\n>","convertResponsesDeltaToChatGenerationChunk: Converter<\n OpenAIClient.Responses.ResponseStreamEvent,\n ChatGenerationChunk | null\n>","content: ContentBlock[]","generationInfo: Record<string, unknown>","usage_metadata: UsageMetadata | undefined","tool_call_chunks: ToolCallChunk[]","additional_kwargs: {\n [key: string]: unknown;\n reasoning?: Partial<ChatOpenAIReasoningSummary>;\n tool_outputs?: unknown[];\n }","id: string | undefined","summary: ChatOpenAIReasoningSummary[\"summary\"] | undefined","ChatGenerationChunk","AIMessageChunk","convertStandardContentMessageToResponsesInput: Converter<\n BaseMessage,\n OpenAIClient.Responses.ResponseInputItem[]\n>","iife","messageToOpenAIRole","currentMessage: OpenAIClient.Responses.EasyInputMessage | undefined","pushMessageContent: (\n content: OpenAIClient.Responses.ResponseInputMessageContentList\n ) => void","value: unknown","block: ContentBlock.Multimodal.Image","block: ContentBlock.Multimodal.File | ContentBlock.Multimodal.Video","getFilenameFromMetadata","getRequiredFilenameFromMetadata","block: ContentBlock.Reasoning","reasoningItem: OpenAIClient.Responses.ResponseReasoningItem","block: ContentBlock.Tools.ToolCall | ContentBlock.Tools.ServerToolCall","block: ContentBlock.Tools.ServerToolCallResult","convertMessagesToResponsesInput: Converter<\n { messages: BaseMessage[]; zdrEnabled: boolean; model: string },\n ResponsesInputItem[]\n>","isReasoningModel","input: ResponsesInputItem[]","isCustomToolCall","isComputerToolCall","fallthroughCallTypes: ResponsesInputItem[\"type\"][]","messages: ResponsesInputItem[]","messages","completionsApiContentBlockConverter"],"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__\";\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 let messageId: string | undefined;\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 } = {};\n\n for (const item of response.output) {\n if (item.type === \"message\") {\n messageId = item.id;\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 return {\n type: \"text\",\n text: part.text,\n annotations: part.annotations.map(\n convertOpenAIAnnotationToLangChain\n ),\n } satisfies ContentBlock.Text;\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 } 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: messageId,\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 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`: Message ID (set when a message output item is added)\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 id = event.item.id;\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.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 ].includes(event.item.type)\n ) {\n additional_kwargs.tool_outputs = [event.item];\n } else if (event.type === \"response.created\") {\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 (event.type === \"response.completed\") {\n const msg = convertResponsesMessageToAIMessage(event.response);\n\n usage_metadata = convertResponsesUsageToUsageMetadata(event.response.usage);\n\n if (event.response.text?.format?.type === \"json_schema\") {\n additional_kwargs.parsed ??= JSON.parse(msg.text);\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 });\n } else if (\n event.type === \"response.web_search_call.completed\" ||\n event.type === \"response.file_search_call.completed\"\n ) {\n generationInfo = {\n tool_outputs: {\n id: event.item_id,\n type: event.type.replace(\"response.\", \"\").replace(\".completed\", \"\"),\n status: \"completed\",\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 });\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 });\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 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 ) => void = (content) => {\n if (!currentMessage) {\n currentMessage = {\n type: \"message\",\n role: messageRole,\n content: [],\n };\n }\n if (typeof currentMessage.content === \"string\") {\n currentMessage.content =\n currentMessage.content.length > 0\n ? [{ type: \"input_text\", text: 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 ? { 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 const reasoningItem: OpenAIClient.Responses.ResponseReasoningItem = {\n type: \"reasoning\",\n id: block.id ?? \"\",\n summary,\n };\n\n if (block.reasoning) {\n reasoningItem.content = [\n {\n type: \"reasoning_text\" as const,\n text: block.reasoning,\n },\n ];\n }\n return reasoningItem;\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 pushMessageContent([{ type: \"input_text\", text: block.text }]);\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([\n {\n type: \"input_text\",\n text: block.text,\n },\n ]);\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 as { content: ContentBlock[] };\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 input.push({\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 return {\n type: \"output_text\",\n text: item.text,\n annotations: (item.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 });\n }\n\n const functionCallIds = additional_kwargs?.[_FUNCTION_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)) {\n return {\n type: \"custom_tool_call\",\n id: toolCall.call_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 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;;;;;;;;;;;;AAgBnC,SAAS,mCACPA,YACkD;AAClD,KAAI,WAAW,SAAS,eACtB,QAAO;EACL,MAAM;EACN,QAAQ;EACR,KAAK,WAAW;EAChB,OAAO,WAAW;EAClB,YAAY,WAAW;EACvB,UAAU,WAAW;CACtB;AAGH,KAAI,WAAW,SAAS,gBACtB,QAAO;EACL,MAAM;EACN,QAAQ;EACR,OAAO,WAAW;EAClB,YAAY,WAAW;EAEvB,SAAS,WAAW;CACrB;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;CAC1B;AAGH,KAAI,WAAW,SAAS,YACtB,QAAO;EACL,MAAM;EACN,QAAQ;EACR,YAAY,WAAW;EACvB,SAAS,WAAW;CACrB;AAIH,QAAO;EACL,MAAM;EACN,OAAO;CACR;AACF;;;;;;;;AASD,SAAS,mCACPC,YAIkB;AAElB,KACE,WAAW,SAAS,kBACpB,WAAW,SAAS,mBACpB,WAAW,SAAS,6BACpB,WAAW,SAAS,YAEpB,QAAO;AAIT,KAAI,WAAW,SAAS,YAAY;EAClC,MAAM,WAAW;AAKjB,MAAI,SAAS,WAAW,eACtB,QAAO;GACL,MAAM;GACN,KAAK,SAAS,OAAO;GACrB,OAAO,SAAS,SAAS;GACzB,aAAa,SAAS,cAAc;GACpC,WAAW,SAAS,YAAY;EACjC;AAGH,MAAI,SAAS,WAAW,gBACtB,QAAO;GACL,MAAM;GACN,SAAS,SAAS,WAAW;GAC7B,UAAU,SAAS,SAAS;GAC5B,OAAO,SAAS,cAAc;EAC/B;AAGH,MAAI,SAAS,WAAW,0BACtB,QAAO;GACL,MAAM;GACN,SAAS,SAAS,WA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,KAAK,SAAS,aAAa;KAC7B,MAAM,WAAWrB,kBAAK,MAAM;AAC1B,UAAI,OAAO,KAAK,cAAc,SAC5B,QAAO,KAAK;eAEZ,OAAO,KAAK,cAAc,YAC1B,KAAK,cAAc,QACnB,SAAS,KAAK,UAEd,QAAO,KAAK,UAAU;AAExB,aAAO;KACR,EAAC;KACF,MAAM,SAASA,kBAAK,MAAM;AACxB,UAAI,OAAO,KAAK,cAAc,SAC5B,QAAO;eAEP,OAAO,KAAK,cAAc,YAC1B,KAAK,cAAc,QACnB,YAAY,KAAK,UAEjB,QAAO,KAAK,UAAU;AAExB,aAAO;KACR,EAAC;AACF,YAAO;MACL,MAAM;MACN,WAAW;MACX;KACD;IACF;AACD,QACE,KAAK,SAAS,gBACd,KAAK,SAAS,iBACd,KAAK,SAAS,aAEd,QAAO;AAET,WAAO,CAAE;GACV,EAAC;AAEF,OAAI,QAAQ,SAAS,GACnBoB,WAAS,KAAK;IACZ,MAAM;IACN;IACS;GACV,EAAC;AAEJ,UAAOA;EACR;EAED,QAAQ,KACN,CAAC,gEAAgE,EAAE,MAAM,CAC1E;AACD,SAAO,CAAE;CACV,EACF;AACF"}
@@ -215,6 +215,14 @@ const convertResponsesMessageToAIMessage = (response) => {
215
215
  const content = [];
216
216
  const tool_calls = [];
217
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
+ });
218
226
  const response_metadata = {
219
227
  model_provider: "openai",
220
228
  model: response.model,
@@ -223,6 +231,7 @@ const convertResponsesMessageToAIMessage = (response) => {
223
231
  incomplete_details: response.incomplete_details,
224
232
  metadata: response.metadata,
225
233
  object: response.object,
234
+ output: cleanedOutput,
226
235
  status: response.status,
227
236
  user: response.user,
228
237
  service_tier: response.service_tier,
@@ -494,7 +503,11 @@ const convertResponsesDeltaToChatGenerationChunk = (event) => {
494
503
  const msg = convertResponsesMessageToAIMessage(event.response);
495
504
  usage_metadata = convertResponsesUsageToUsageMetadata(event.response.usage);
496
505
  if (event.response.text?.format?.type === "json_schema") additional_kwargs.parsed ??= JSON.parse(msg.text);
497
- for (const [key, value] of Object.entries(event.response)) if (key !== "id") response_metadata[key] = value;
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
+ }
498
511
  } else if (event.type === "response.function_call_arguments.delta" || event.type === "response.custom_tool_call_input.delta") tool_call_chunks.push({
499
512
  type: "tool_call_chunk",
500
513
  args: event.delta,
@@ -1 +1 @@
1
- {"version":3,"file":"responses.js","names":["annotation: OpenAIAnnotation","annotation:\n | ContentBlock.Citation\n | ContentBlock.NonStandard\n | Record<string, unknown>","convertResponsesUsageToUsageMetadata: Converter<\n OpenAIClient.Responses.ResponseUsage | undefined,\n UsageMetadata\n>","convertResponsesMessageToAIMessage: Converter<\n ResponsesCreateInvoke | ResponsesParseInvoke,\n AIMessage\n>","messageId: string | undefined","content: MessageContent","tool_calls: ToolCall[]","invalid_tool_calls: InvalidToolCall[]","response_metadata: Record<string, unknown>","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 }","e: unknown","errMessage: string | undefined","convertReasoningSummaryToResponsesReasoningItem: Converter<\n ChatOpenAIReasoningSummary,\n OpenAIClient.Responses.ResponseReasoningItem\n>","convertResponsesDeltaToChatGenerationChunk: Converter<\n OpenAIClient.Responses.ResponseStreamEvent,\n ChatGenerationChunk | null\n>","content: ContentBlock[]","generationInfo: Record<string, unknown>","usage_metadata: UsageMetadata | undefined","tool_call_chunks: ToolCallChunk[]","additional_kwargs: {\n [key: string]: unknown;\n reasoning?: Partial<ChatOpenAIReasoningSummary>;\n tool_outputs?: unknown[];\n }","id: string | undefined","summary: ChatOpenAIReasoningSummary[\"summary\"] | undefined","convertStandardContentMessageToResponsesInput: Converter<\n BaseMessage,\n OpenAIClient.Responses.ResponseInputItem[]\n>","currentMessage: OpenAIClient.Responses.EasyInputMessage | undefined","pushMessageContent: (\n content: OpenAIClient.Responses.ResponseInputMessageContentList\n ) => void","value: unknown","block: ContentBlock.Multimodal.Image","block: ContentBlock.Multimodal.File | ContentBlock.Multimodal.Video","block: ContentBlock.Reasoning","reasoningItem: OpenAIClient.Responses.ResponseReasoningItem","block: ContentBlock.Tools.ToolCall | ContentBlock.Tools.ServerToolCall","block: ContentBlock.Tools.ServerToolCallResult","convertMessagesToResponsesInput: Converter<\n { messages: BaseMessage[]; zdrEnabled: boolean; model: string },\n ResponsesInputItem[]\n>","input: ResponsesInputItem[]","fallthroughCallTypes: ResponsesInputItem[\"type\"][]","messages: ResponsesInputItem[]","messages"],"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__\";\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 let messageId: string | undefined;\n const content: MessageContent = [];\n const tool_calls: ToolCall[] = [];\n const invalid_tool_calls: InvalidToolCall[] = [];\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 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 } = {};\n\n for (const item of response.output) {\n if (item.type === \"message\") {\n messageId = item.id;\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 return {\n type: \"text\",\n text: part.text,\n annotations: part.annotations.map(\n convertOpenAIAnnotationToLangChain\n ),\n } satisfies ContentBlock.Text;\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 } 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: messageId,\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 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`: Message ID (set when a message output item is added)\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 id = event.item.id;\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.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 ].includes(event.item.type)\n ) {\n additional_kwargs.tool_outputs = [event.item];\n } else if (event.type === \"response.created\") {\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 (event.type === \"response.completed\") {\n const msg = convertResponsesMessageToAIMessage(event.response);\n\n usage_metadata = convertResponsesUsageToUsageMetadata(event.response.usage);\n\n if (event.response.text?.format?.type === \"json_schema\") {\n additional_kwargs.parsed ??= JSON.parse(msg.text);\n }\n for (const [key, value] of Object.entries(event.response)) {\n if (key !== \"id\") response_metadata[key] = value;\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 });\n } else if (\n event.type === \"response.web_search_call.completed\" ||\n event.type === \"response.file_search_call.completed\"\n ) {\n generationInfo = {\n tool_outputs: {\n id: event.item_id,\n type: event.type.replace(\"response.\", \"\").replace(\".completed\", \"\"),\n status: \"completed\",\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 });\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 });\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 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 ) => void = (content) => {\n if (!currentMessage) {\n currentMessage = {\n type: \"message\",\n role: messageRole,\n content: [],\n };\n }\n if (typeof currentMessage.content === \"string\") {\n currentMessage.content =\n currentMessage.content.length > 0\n ? [{ type: \"input_text\", text: 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 ? { 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 const reasoningItem: OpenAIClient.Responses.ResponseReasoningItem = {\n type: \"reasoning\",\n id: block.id ?? \"\",\n summary,\n };\n\n if (block.reasoning) {\n reasoningItem.content = [\n {\n type: \"reasoning_text\" as const,\n text: block.reasoning,\n },\n ];\n }\n return reasoningItem;\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 pushMessageContent([{ type: \"input_text\", text: block.text }]);\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([\n {\n type: \"input_text\",\n text: block.text,\n },\n ]);\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 as { content: ContentBlock[] };\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 input.push({\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 return {\n type: \"output_text\",\n text: item.text,\n annotations: (item.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 });\n }\n\n const functionCallIds = additional_kwargs?.[_FUNCTION_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)) {\n return {\n type: \"custom_tool_call\",\n id: toolCall.call_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 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;;;;;;;;;;;;AAgBnC,SAAS,mCACPA,YACkD;AAClD,KAAI,WAAW,SAAS,eACtB,QAAO;EACL,MAAM;EACN,QAAQ;EACR,KAAK,WAAW;EAChB,OAAO,WAAW;EAClB,YAAY,WAAW;EACvB,UAAU,WAAW;CACtB;AAGH,KAAI,WAAW,SAAS,gBACtB,QAAO;EACL,MAAM;EACN,QAAQ;EACR,OAAO,WAAW;EAClB,YAAY,WAAW;EAEvB,SAAS,WAAW;CACrB;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;CAC1B;AAGH,KAAI,WAAW,SAAS,YACtB,QAAO;EACL,MAAM;EACN,QAAQ;EACR,YAAY,WAAW;EACvB,SAAS,WAAW;CACrB;AAIH,QAAO;EACL,MAAM;EACN,OAAO;CACR;AACF;;;;;;;;AASD,SAAS,mCACPC,YAIkB;AAElB,KACE,WAAW,SAAS,kBACpB,WAAW,SAAS,mBACpB,WAAW,SAAS,6BACpB,WAAW,SAAS,YAEpB,QAAO;AAIT,KAAI,WAAW,SAAS,YAAY;EAClC,MAAM,WAAW;AAKjB,MAAI,SAAS,WAAW,eACtB,QAAO;GACL,MAAM;GACN,KAAK,SAAS,OAAO;GACrB,OAAO,SAAS,SAAS;GACzB,aAAa,SAAS,cAAc;GACpC,WAAW,SAAS,YAAY;EACjC;AAGH,MAAI,SAAS,WAAW,gBACtB,QAAO;GACL,MAAM;GACN,SAAS,SAAS,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c,QACnB,SAAS,KAAK,UAEd,QAAO,KAAK,UAAU;AAExB,aAAO;KACR,EAAC;KACF,MAAM,SAAS,KAAK,MAAM;AACxB,UAAI,OAAO,KAAK,cAAc,SAC5B,QAAO;eAEP,OAAO,KAAK,cAAc,YAC1B,KAAK,cAAc,QACnB,YAAY,KAAK,UAEjB,QAAO,KAAK,UAAU;AAExB,aAAO;KACR,EAAC;AACF,YAAO;MACL,MAAM;MACN,WAAW;MACX;KACD;IACF;AACD,QACE,KAAK,SAAS,gBACd,KAAK,SAAS,iBACd,KAAK,SAAS,aAEd,QAAO;AAET,WAAO,CAAE;GACV,EAAC;AAEF,OAAI,QAAQ,SAAS,GACnBA,WAAS,KAAK;IACZ,MAAM;IACN;IACS;GACV,EAAC;AAEJ,UAAOA;EACR;EAED,QAAQ,KACN,CAAC,gEAAgE,EAAE,MAAM,CAC1E;AACD,SAAO,CAAE;CACV,EACF;AACF"}
1
+ {"version":3,"file":"responses.js","names":["annotation: OpenAIAnnotation","annotation:\n | ContentBlock.Citation\n | ContentBlock.NonStandard\n | Record<string, unknown>","convertResponsesUsageToUsageMetadata: Converter<\n OpenAIClient.Responses.ResponseUsage | undefined,\n UsageMetadata\n>","convertResponsesMessageToAIMessage: Converter<\n ResponsesCreateInvoke | ResponsesParseInvoke,\n AIMessage\n>","messageId: string | undefined","content: MessageContent","tool_calls: ToolCall[]","invalid_tool_calls: InvalidToolCall[]","response_metadata: Record<string, unknown>","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 }","e: unknown","errMessage: string | undefined","convertReasoningSummaryToResponsesReasoningItem: Converter<\n ChatOpenAIReasoningSummary,\n OpenAIClient.Responses.ResponseReasoningItem\n>","convertResponsesDeltaToChatGenerationChunk: Converter<\n OpenAIClient.Responses.ResponseStreamEvent,\n ChatGenerationChunk | null\n>","content: ContentBlock[]","generationInfo: Record<string, unknown>","usage_metadata: UsageMetadata | undefined","tool_call_chunks: ToolCallChunk[]","additional_kwargs: {\n [key: string]: unknown;\n reasoning?: Partial<ChatOpenAIReasoningSummary>;\n tool_outputs?: unknown[];\n }","id: string | undefined","summary: ChatOpenAIReasoningSummary[\"summary\"] | undefined","convertStandardContentMessageToResponsesInput: Converter<\n BaseMessage,\n OpenAIClient.Responses.ResponseInputItem[]\n>","currentMessage: OpenAIClient.Responses.EasyInputMessage | undefined","pushMessageContent: (\n content: OpenAIClient.Responses.ResponseInputMessageContentList\n ) => void","value: unknown","block: ContentBlock.Multimodal.Image","block: ContentBlock.Multimodal.File | ContentBlock.Multimodal.Video","block: ContentBlock.Reasoning","reasoningItem: OpenAIClient.Responses.ResponseReasoningItem","block: ContentBlock.Tools.ToolCall | ContentBlock.Tools.ServerToolCall","block: ContentBlock.Tools.ServerToolCallResult","convertMessagesToResponsesInput: Converter<\n { messages: BaseMessage[]; zdrEnabled: boolean; model: string },\n ResponsesInputItem[]\n>","input: ResponsesInputItem[]","fallthroughCallTypes: ResponsesInputItem[\"type\"][]","messages: ResponsesInputItem[]","messages"],"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__\";\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 let messageId: string | undefined;\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 } = {};\n\n for (const item of response.output) {\n if (item.type === \"message\") {\n messageId = item.id;\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 return {\n type: \"text\",\n text: part.text,\n annotations: part.annotations.map(\n convertOpenAIAnnotationToLangChain\n ),\n } satisfies ContentBlock.Text;\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 } 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: messageId,\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 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`: Message ID (set when a message output item is added)\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 id = event.item.id;\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.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 ].includes(event.item.type)\n ) {\n additional_kwargs.tool_outputs = [event.item];\n } else if (event.type === \"response.created\") {\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 (event.type === \"response.completed\") {\n const msg = convertResponsesMessageToAIMessage(event.response);\n\n usage_metadata = convertResponsesUsageToUsageMetadata(event.response.usage);\n\n if (event.response.text?.format?.type === \"json_schema\") {\n additional_kwargs.parsed ??= JSON.parse(msg.text);\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 });\n } else if (\n event.type === \"response.web_search_call.completed\" ||\n event.type === \"response.file_search_call.completed\"\n ) {\n generationInfo = {\n tool_outputs: {\n id: event.item_id,\n type: event.type.replace(\"response.\", \"\").replace(\".completed\", \"\"),\n status: \"completed\",\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 });\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 });\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 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 ) => void = (content) => {\n if (!currentMessage) {\n currentMessage = {\n type: \"message\",\n role: messageRole,\n content: [],\n };\n }\n if (typeof currentMessage.content === \"string\") {\n currentMessage.content =\n currentMessage.content.length > 0\n ? [{ type: \"input_text\", text: 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 ? { 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 const reasoningItem: OpenAIClient.Responses.ResponseReasoningItem = {\n type: \"reasoning\",\n id: block.id ?? \"\",\n summary,\n };\n\n if (block.reasoning) {\n reasoningItem.content = [\n {\n type: \"reasoning_text\" as const,\n text: block.reasoning,\n },\n ];\n }\n return reasoningItem;\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 pushMessageContent([{ type: \"input_text\", text: block.text }]);\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([\n {\n type: \"input_text\",\n text: block.text,\n },\n ]);\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 as { content: ContentBlock[] };\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 input.push({\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 return {\n type: \"output_text\",\n text: item.text,\n annotations: (item.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 });\n }\n\n const functionCallIds = additional_kwargs?.[_FUNCTION_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)) {\n return {\n type: \"custom_tool_call\",\n id: toolCall.call_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 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;;;;;;;;;;;;AAgBnC,SAAS,mCACPA,YACkD;AAClD,KAAI,WAAW,SAAS,eACtB,QAAO;EACL,MAAM;EACN,QAAQ;EACR,KAAK,WAAW;EAChB,OAAO,WAAW;EAClB,YAAY,WAAW;EACvB,UAAU,WAAW;CACtB;AAGH,KAAI,WAAW,SAAS,gBACtB,QAAO;EACL,MAAM;EACN,QAAQ;EACR,OAAO,WAAW;EAClB,YAAY,WAAW;EAEvB,SAAS,WAAW;CACrB;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;CAC1B;AAGH,KAAI,WAAW,SAAS,YACtB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AM;IACN;IACS;GACV,EAAC;AAEJ,UAAOA;EACR;EAED,QAAQ,KACN,CAAC,gEAAgE,EAAE,MAAM,CAC1E;AACD,SAAO,CAAE;CACV,EACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"codeInterpreter.d.cts","names":["OpenAI","OpenAIClient","ServerTool","CodeInterpreterMemoryLimit","CodeInterpreterAutoContainer","CodeInterpreterOptions","CodeInterpreterTool","Responses","Tool","CodeInterpreter","codeInterpreter"],"sources":["../../src/tools/codeInterpreter.d.ts"],"sourcesContent":["import { OpenAI as OpenAIClient } from \"openai\";\nimport type { ServerTool } from \"@langchain/core/tools\";\n/**\n * Memory limit options for the Code Interpreter container.\n * Higher tiers offer more RAM and are billed at different rates.\n */\nexport type CodeInterpreterMemoryLimit = \"1g\" | \"4g\" | \"16g\" | \"64g\";\n/**\n * Auto container configuration for Code Interpreter.\n * Creates a new container automatically or reuses an active one.\n */\nexport interface CodeInterpreterAutoContainer {\n /**\n * Memory limit for the container.\n * - `\"1g\"` (default): 1 GB RAM\n * - `\"4g\"`: 4 GB RAM\n * - `\"16g\"`: 16 GB RAM\n * - `\"64g\"`: 64 GB RAM\n */\n memoryLimit?: CodeInterpreterMemoryLimit;\n /**\n * Optional list of uploaded file IDs to make available to the code.\n * Files in the model input are automatically uploaded, so this is only\n * needed for additional files.\n */\n fileIds?: string[];\n}\n/**\n * Options for the Code Interpreter tool.\n */\nexport interface CodeInterpreterOptions {\n /**\n * The container configuration for the Code Interpreter.\n *\n * Can be either:\n * - A string container ID for explicit mode (created via `/v1/containers` endpoint)\n * - An auto configuration object that creates/reuses containers automatically\n *\n * If not provided, defaults to auto mode with default settings.\n */\n container?: string | CodeInterpreterAutoContainer;\n}\n/**\n * OpenAI Code Interpreter tool type for the Responses API.\n */\nexport type CodeInterpreterTool = OpenAIClient.Responses.Tool.CodeInterpreter;\n/**\n * Creates a Code Interpreter tool that allows models to write and run Python code\n * in a sandboxed environment to solve complex problems.\n *\n * Use Code Interpreter for:\n * - **Data analysis**: Processing files with diverse data and formatting\n * - **File generation**: Creating files with data and images of graphs\n * - **Iterative coding**: Writing and running code iteratively to solve problems\n * - **Visual intelligence**: Cropping, zooming, rotating, and transforming images\n *\n * The tool runs in a container, which is a fully sandboxed virtual machine.\n * Containers can be created automatically (auto mode) or explicitly via the\n * `/v1/containers` endpoint.\n *\n * @see {@link https://platform.openai.com/docs/guides/tools-code-interpreter | OpenAI Code Interpreter Documentation}\n *\n * @param options - Configuration options for the Code Interpreter tool\n * @returns A Code Interpreter tool definition to be passed to the OpenAI Responses API\n *\n * @example\n * ```typescript\n * import { ChatOpenAI, tools } from \"@langchain/openai\";\n *\n * const model = new ChatOpenAI({ model: \"gpt-4.1\" });\n *\n * // Basic usage with auto container (default 1GB memory)\n * const response = await model.invoke(\n * \"Solve the equation 3x + 11 = 14\",\n * { tools: [tools.codeInterpreter()] }\n * );\n *\n * // With increased memory limit for larger computations\n * const response = await model.invoke(\n * \"Analyze this large dataset and create visualizations\",\n * {\n * tools: [tools.codeInterpreter({\n * container: { memoryLimit: \"4g\" }\n * })]\n * }\n * );\n *\n * // With specific files available to the code\n * const response = await model.invoke(\n * \"Process the uploaded CSV file\",\n * {\n * tools: [tools.codeInterpreter({\n * container: {\n * memoryLimit: \"4g\",\n * fileIds: [\"file-abc123\", \"file-def456\"]\n * }\n * })]\n * }\n * );\n *\n * // Using an explicit container ID (created via /v1/containers)\n * const response = await model.invoke(\n * \"Continue working with the data\",\n * {\n * tools: [tools.codeInterpreter({\n * container: \"cntr_abc123\"\n * })]\n * }\n * );\n * ```\n *\n * @remarks\n * - Containers expire after 20 minutes of inactivity\n * - While called \"Code Interpreter\", the model knows it as the \"python tool\"\n * - For explicit prompting, ask for \"the python tool\" in your prompts\n * - Files in model input are automatically uploaded to the container\n * - Generated files are returned as `container_file_citation` annotations\n */\nexport declare function codeInterpreter(options?: CodeInterpreterOptions): ServerTool;\n//# sourceMappingURL=codeInterpreter.d.ts.map"],"mappings":";;;;;;;AAMA;AAKA;AAmBiBK,KAxBLF,0BAAAA,GAwB2B,IAUdC,GAAAA,IAAAA,GAAAA,KAAAA,GAAAA,KAAAA;AAKzB;AAyEA;;;UA3GiBA,4BAAAA;;;;;;;;gBAQCD;;;;;;;;;;;UAWDE,sBAAAA;;;;;;;;;;uBAUQD;;;;;KAKbE,mBAAAA,GAAsBL,QAAAA,CAAaM,SAAAA,CAAUC,IAAAA,CAAKC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyEtCC,eAAAA,WAA0BL,yBAAyBH"}
1
+ {"version":3,"file":"codeInterpreter.d.cts","names":["OpenAI","OpenAIClient","ServerTool","CodeInterpreterMemoryLimit","CodeInterpreterAutoContainer","CodeInterpreterOptions","CodeInterpreterTool","Responses","Tool","CodeInterpreter","codeInterpreter"],"sources":["../../src/tools/codeInterpreter.d.ts"],"sourcesContent":["import { OpenAI as OpenAIClient } from \"openai\";\nimport type { ServerTool } from \"@langchain/core/tools\";\n/**\n * Memory limit options for the Code Interpreter container.\n * Higher tiers offer more RAM and are billed at different rates.\n */\nexport type CodeInterpreterMemoryLimit = \"1g\" | \"4g\" | \"16g\" | \"64g\";\n/**\n * Auto container configuration for Code Interpreter.\n * Creates a new container automatically or reuses an active one.\n */\nexport interface CodeInterpreterAutoContainer {\n /**\n * Memory limit for the container.\n * - `\"1g\"` (default): 1 GB RAM\n * - `\"4g\"`: 4 GB RAM\n * - `\"16g\"`: 16 GB RAM\n * - `\"64g\"`: 64 GB RAM\n */\n memoryLimit?: CodeInterpreterMemoryLimit;\n /**\n * Optional list of uploaded file IDs to make available to the code.\n * Files in the model input are automatically uploaded, so this is only\n * needed for additional files.\n */\n fileIds?: string[];\n}\n/**\n * Options for the Code Interpreter tool.\n */\nexport interface CodeInterpreterOptions {\n /**\n * The container configuration for the Code Interpreter.\n *\n * Can be either:\n * - A string container ID for explicit mode (created via `/v1/containers` endpoint)\n * - An auto configuration object that creates/reuses containers automatically\n *\n * If not provided, defaults to auto mode with default settings.\n */\n container?: string | CodeInterpreterAutoContainer;\n}\n/**\n * OpenAI Code Interpreter tool type for the Responses API.\n */\nexport type CodeInterpreterTool = OpenAIClient.Responses.Tool.CodeInterpreter;\n/**\n * Creates a Code Interpreter tool that allows models to write and run Python code\n * in a sandboxed environment to solve complex problems.\n *\n * Use Code Interpreter for:\n * - **Data analysis**: Processing files with diverse data and formatting\n * - **File generation**: Creating files with data and images of graphs\n * - **Iterative coding**: Writing and running code iteratively to solve problems\n * - **Visual intelligence**: Cropping, zooming, rotating, and transforming images\n *\n * The tool runs in a container, which is a fully sandboxed virtual machine.\n * Containers can be created automatically (auto mode) or explicitly via the\n * `/v1/containers` endpoint.\n *\n * @see {@link https://platform.openai.com/docs/guides/tools-code-interpreter | OpenAI Code Interpreter Documentation}\n *\n * @param options - Configuration options for the Code Interpreter tool\n * @returns A Code Interpreter tool definition to be passed to the OpenAI Responses API\n *\n * @example\n * ```typescript\n * import { ChatOpenAI, tools } from \"@langchain/openai\";\n *\n * const model = new ChatOpenAI({ model: \"gpt-4.1\" });\n *\n * // Basic usage with auto container (default 1GB memory)\n * const response = await model.invoke(\n * \"Solve the equation 3x + 11 = 14\",\n * { tools: [tools.codeInterpreter()] }\n * );\n *\n * // With increased memory limit for larger computations\n * const response = await model.invoke(\n * \"Analyze this large dataset and create visualizations\",\n * {\n * tools: [tools.codeInterpreter({\n * container: { memoryLimit: \"4g\" }\n * })]\n * }\n * );\n *\n * // With specific files available to the code\n * const response = await model.invoke(\n * \"Process the uploaded CSV file\",\n * {\n * tools: [tools.codeInterpreter({\n * container: {\n * memoryLimit: \"4g\",\n * fileIds: [\"file-abc123\", \"file-def456\"]\n * }\n * })]\n * }\n * );\n *\n * // Using an explicit container ID (created via /v1/containers)\n * const response = await model.invoke(\n * \"Continue working with the data\",\n * {\n * tools: [tools.codeInterpreter({\n * container: \"cntr_abc123\"\n * })]\n * }\n * );\n * ```\n *\n * @remarks\n * - Containers expire after 20 minutes of inactivity\n * - While called \"Code Interpreter\", the model knows it as the \"python tool\"\n * - For explicit prompting, ask for \"the python tool\" in your prompts\n * - Files in model input are automatically uploaded to the container\n * - Generated files are returned as `container_file_citation` annotations\n */\nexport declare function codeInterpreter(options?: CodeInterpreterOptions): ServerTool;\n//# sourceMappingURL=codeInterpreter.d.ts.map"],"mappings":";;;;;;;AAMA;AAKA;AAmBiBK,KAxBLF,0BAAAA,GAkCaC,IAAAA,GAAAA,IAAAA,GAAAA,KAAAA,GAAAA,KAAAA;AAKzB;AAyEA;;;UA3GiBA,4BAAAA;;;;;;;;gBAQCD;;;;;;;;;;;UAWDE,sBAAAA;;;;;;;;;;uBAUQD;;;;;KAKbE,mBAAAA,GAAsBL,QAAAA,CAAaM,SAAAA,CAAUC,IAAAA,CAAKC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyEtCC,eAAAA,WAA0BL,yBAAyBH"}
@@ -1 +1 @@
1
- {"version":3,"file":"mcp.d.cts","names":["OpenAI","OpenAIClient","ServerTool","McpConnectorId","McpToolFilter","McpApprovalFilter","McpBaseOptions","Record","McpRemoteServerOptions","McpConnectorOptions","McpTool","Responses","Tool","Mcp","mcp"],"sources":["../../src/tools/mcp.d.ts"],"sourcesContent":["import { OpenAI as OpenAIClient } from \"openai\";\nimport type { ServerTool } from \"@langchain/core/tools\";\n/**\n * Available connector IDs for OpenAI's built-in service connectors.\n * These are OpenAI-maintained MCP wrappers for popular services.\n */\nexport type McpConnectorId = \"connector_dropbox\" | \"connector_gmail\" | \"connector_googlecalendar\" | \"connector_googledrive\" | \"connector_microsoftteams\" | \"connector_outlookcalendar\" | \"connector_outlookemail\" | \"connector_sharepoint\";\n/**\n * Filter object to specify which tools are allowed.\n */\nexport interface McpToolFilter {\n /**\n * List of allowed tool names.\n */\n toolNames?: string[];\n /**\n * Indicates whether or not a tool modifies data or is read-only.\n * If an MCP server is annotated with `readOnlyHint`, it will match this filter.\n */\n readOnly?: boolean;\n}\n/**\n * Filter object for approval requirements.\n */\nexport interface McpApprovalFilter {\n /**\n * Tools that always require approval before execution.\n */\n always?: McpToolFilter;\n /**\n * Tools that never require approval.\n */\n never?: McpToolFilter;\n}\n/**\n * Base options shared between remote MCP servers and connectors.\n */\ninterface McpBaseOptions {\n /**\n * A label for this MCP server, used to identify it in tool calls.\n */\n serverLabel: string;\n /**\n * List of allowed tool names or a filter object.\n * Use this to limit which tools from the MCP server are available to the model.\n */\n allowedTools?: string[] | McpToolFilter;\n /**\n * An OAuth access token for authentication with the MCP server.\n * Your application must handle the OAuth authorization flow and provide the token here.\n */\n authorization?: string;\n /**\n * Optional HTTP headers to send to the MCP server.\n * Use for authentication or other purposes.\n */\n headers?: Record<string, string>;\n /**\n * Specify which of the MCP server's tools require approval before execution.\n * - `\"always\"`: All tools require approval\n * - `\"never\"`: No tools require approval\n * - `McpApprovalFilter`: Fine-grained control over which tools require approval\n *\n * @default \"always\" (approval required for all tools)\n */\n requireApproval?: \"always\" | \"never\" | McpApprovalFilter;\n /**\n * Optional description of the MCP server, used to provide more context to the model.\n */\n serverDescription?: string;\n}\n/**\n * Options for connecting to a remote MCP server via URL.\n */\nexport interface McpRemoteServerOptions extends McpBaseOptions {\n /**\n * The URL for the MCP server.\n * The server must implement the Streamable HTTP or HTTP/SSE transport protocol.\n */\n serverUrl: string;\n}\n/**\n * Options for connecting to an OpenAI-maintained service connector.\n */\nexport interface McpConnectorOptions extends McpBaseOptions {\n /**\n * Identifier for the service connector.\n * These are OpenAI-maintained MCP wrappers for popular services.\n *\n * Available connectors:\n * - `connector_dropbox`: Dropbox file access\n * - `connector_gmail`: Gmail email access\n * - `connector_googlecalendar`: Google Calendar access\n * - `connector_googledrive`: Google Drive file access\n * - `connector_microsoftteams`: Microsoft Teams access\n * - `connector_outlookcalendar`: Outlook Calendar access\n * - `connector_outlookemail`: Outlook Email access\n * - `connector_sharepoint`: SharePoint file access\n */\n connectorId: McpConnectorId;\n}\n/**\n * OpenAI MCP tool type for the Responses API.\n */\nexport type McpTool = OpenAIClient.Responses.Tool.Mcp;\n/**\n * Creates an MCP tool that connects to a remote MCP server or OpenAI service connector.\n * This allows OpenAI models to access external tools and services via the Model Context Protocol.\n *\n * There are two ways to use MCP tools:\n * 1. **Remote MCP servers**: Connect to any server on the public Internet that implements\n * the MCP protocol using `serverUrl`.\n * 2. **Connectors**: Use OpenAI-maintained MCP wrappers for popular services like\n * Google Workspace or Dropbox using `connectorId`.\n *\n * @see {@link https://platform.openai.com/docs/guides/tools-remote-mcp | OpenAI MCP Documentation}\n *\n * @param options - Configuration options for the MCP tool\n * @returns An MCP tool definition to be passed to the OpenAI Responses API\n *\n * @example\n * ```typescript\n * import { ChatOpenAI, tools } from \"@langchain/openai\";\n *\n * const model = new ChatOpenAI({ model: \"gpt-4o\" });\n *\n * // Using a remote MCP server\n * const response = await model.invoke(\"Roll 2d4+1\", {\n * tools: [tools.mcp({\n * serverLabel: \"dmcp\",\n * serverDescription: \"A D&D MCP server for dice rolling\",\n * serverUrl: \"https://dmcp-server.deno.dev/sse\",\n * requireApproval: \"never\",\n * })],\n * });\n *\n * // Using a connector (e.g., Google Calendar)\n * const calendarResponse = await model.invoke(\"What's on my calendar today?\", {\n * tools: [tools.mcp({\n * serverLabel: \"google_calendar\",\n * connectorId: \"connector_googlecalendar\",\n * authorization: \"<oauth-access-token>\",\n * requireApproval: \"never\",\n * })],\n * });\n *\n * // With tool filtering - only allow specific tools\n * const filteredResponse = await model.invoke(\"Roll some dice\", {\n * tools: [tools.mcp({\n * serverLabel: \"dmcp\",\n * serverUrl: \"https://dmcp-server.deno.dev/sse\",\n * allowedTools: [\"roll\"], // Only allow the \"roll\" tool\n * requireApproval: \"never\",\n * })],\n * });\n *\n * // With fine-grained approval control\n * const controlledResponse = await model.invoke(\"Search and modify files\", {\n * tools: [tools.mcp({\n * serverLabel: \"deepwiki\",\n * serverUrl: \"https://mcp.deepwiki.com/mcp\",\n * requireApproval: {\n * never: { toolNames: [\"ask_question\", \"read_wiki_structure\"] },\n * // All other tools will require approval\n * },\n * })],\n * });\n * ```\n */\nexport declare function mcp(options: McpRemoteServerOptions): ServerTool;\nexport declare function mcp(options: McpConnectorOptions): ServerTool;\nexport {};\n//# sourceMappingURL=mcp.d.ts.map"],"mappings":";;;;;;;AAMA;AAIA;AAciBK,KAlBLF,cAAAA,GAkBsB,mBAIrBC,GAAAA,iBAIY,GAAA,0BAAA,GAAA,uBAAA,GAAA,0BAAA,GAAA,2BAAA,GAAA,wBAAA,GAAA,sBAAA;AACxB;;;AAgC0CC,UAvD1BD,aAAAA,CAuD0BC;EAAiB;AAS5D;AAUA;EAoBYK,SAAAA,CAAO,EAAA,MAAA,EAAA;EAiEKI;AACxB;;;;;;;;UAlJiBT,iBAAAA;;;;WAIJD;;;;UAIDA;;;;;UAKFE,cAAAA;;;;;;;;;4BASoBF;;;;;;;;;;YAUhBG;;;;;;;;;yCAS6BF;;;;;;;;;UAS1BG,sBAAAA,SAA+BF;;;;;;;;;;UAU/BG,mBAAAA,SAA4BH;;;;;;;;;;;;;;;eAe5BH;;;;;KAKLO,OAAAA,GAAUT,QAAAA,CAAaU,SAAAA,CAAUC,IAAAA,CAAKC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiE1BC,GAAAA,UAAaN,yBAAyBN;iBACtCY,GAAAA,UAAaL,sBAAsBP"}
1
+ {"version":3,"file":"mcp.d.cts","names":["OpenAI","OpenAIClient","ServerTool","McpConnectorId","McpToolFilter","McpApprovalFilter","McpBaseOptions","Record","McpRemoteServerOptions","McpConnectorOptions","McpTool","Responses","Tool","Mcp","mcp"],"sources":["../../src/tools/mcp.d.ts"],"sourcesContent":["import { OpenAI as OpenAIClient } from \"openai\";\nimport type { ServerTool } from \"@langchain/core/tools\";\n/**\n * Available connector IDs for OpenAI's built-in service connectors.\n * These are OpenAI-maintained MCP wrappers for popular services.\n */\nexport type McpConnectorId = \"connector_dropbox\" | \"connector_gmail\" | \"connector_googlecalendar\" | \"connector_googledrive\" | \"connector_microsoftteams\" | \"connector_outlookcalendar\" | \"connector_outlookemail\" | \"connector_sharepoint\";\n/**\n * Filter object to specify which tools are allowed.\n */\nexport interface McpToolFilter {\n /**\n * List of allowed tool names.\n */\n toolNames?: string[];\n /**\n * Indicates whether or not a tool modifies data or is read-only.\n * If an MCP server is annotated with `readOnlyHint`, it will match this filter.\n */\n readOnly?: boolean;\n}\n/**\n * Filter object for approval requirements.\n */\nexport interface McpApprovalFilter {\n /**\n * Tools that always require approval before execution.\n */\n always?: McpToolFilter;\n /**\n * Tools that never require approval.\n */\n never?: McpToolFilter;\n}\n/**\n * Base options shared between remote MCP servers and connectors.\n */\ninterface McpBaseOptions {\n /**\n * A label for this MCP server, used to identify it in tool calls.\n */\n serverLabel: string;\n /**\n * List of allowed tool names or a filter object.\n * Use this to limit which tools from the MCP server are available to the model.\n */\n allowedTools?: string[] | McpToolFilter;\n /**\n * An OAuth access token for authentication with the MCP server.\n * Your application must handle the OAuth authorization flow and provide the token here.\n */\n authorization?: string;\n /**\n * Optional HTTP headers to send to the MCP server.\n * Use for authentication or other purposes.\n */\n headers?: Record<string, string>;\n /**\n * Specify which of the MCP server's tools require approval before execution.\n * - `\"always\"`: All tools require approval\n * - `\"never\"`: No tools require approval\n * - `McpApprovalFilter`: Fine-grained control over which tools require approval\n *\n * @default \"always\" (approval required for all tools)\n */\n requireApproval?: \"always\" | \"never\" | McpApprovalFilter;\n /**\n * Optional description of the MCP server, used to provide more context to the model.\n */\n serverDescription?: string;\n}\n/**\n * Options for connecting to a remote MCP server via URL.\n */\nexport interface McpRemoteServerOptions extends McpBaseOptions {\n /**\n * The URL for the MCP server.\n * The server must implement the Streamable HTTP or HTTP/SSE transport protocol.\n */\n serverUrl: string;\n}\n/**\n * Options for connecting to an OpenAI-maintained service connector.\n */\nexport interface McpConnectorOptions extends McpBaseOptions {\n /**\n * Identifier for the service connector.\n * These are OpenAI-maintained MCP wrappers for popular services.\n *\n * Available connectors:\n * - `connector_dropbox`: Dropbox file access\n * - `connector_gmail`: Gmail email access\n * - `connector_googlecalendar`: Google Calendar access\n * - `connector_googledrive`: Google Drive file access\n * - `connector_microsoftteams`: Microsoft Teams access\n * - `connector_outlookcalendar`: Outlook Calendar access\n * - `connector_outlookemail`: Outlook Email access\n * - `connector_sharepoint`: SharePoint file access\n */\n connectorId: McpConnectorId;\n}\n/**\n * OpenAI MCP tool type for the Responses API.\n */\nexport type McpTool = OpenAIClient.Responses.Tool.Mcp;\n/**\n * Creates an MCP tool that connects to a remote MCP server or OpenAI service connector.\n * This allows OpenAI models to access external tools and services via the Model Context Protocol.\n *\n * There are two ways to use MCP tools:\n * 1. **Remote MCP servers**: Connect to any server on the public Internet that implements\n * the MCP protocol using `serverUrl`.\n * 2. **Connectors**: Use OpenAI-maintained MCP wrappers for popular services like\n * Google Workspace or Dropbox using `connectorId`.\n *\n * @see {@link https://platform.openai.com/docs/guides/tools-remote-mcp | OpenAI MCP Documentation}\n *\n * @param options - Configuration options for the MCP tool\n * @returns An MCP tool definition to be passed to the OpenAI Responses API\n *\n * @example\n * ```typescript\n * import { ChatOpenAI, tools } from \"@langchain/openai\";\n *\n * const model = new ChatOpenAI({ model: \"gpt-4o\" });\n *\n * // Using a remote MCP server\n * const response = await model.invoke(\"Roll 2d4+1\", {\n * tools: [tools.mcp({\n * serverLabel: \"dmcp\",\n * serverDescription: \"A D&D MCP server for dice rolling\",\n * serverUrl: \"https://dmcp-server.deno.dev/sse\",\n * requireApproval: \"never\",\n * })],\n * });\n *\n * // Using a connector (e.g., Google Calendar)\n * const calendarResponse = await model.invoke(\"What's on my calendar today?\", {\n * tools: [tools.mcp({\n * serverLabel: \"google_calendar\",\n * connectorId: \"connector_googlecalendar\",\n * authorization: \"<oauth-access-token>\",\n * requireApproval: \"never\",\n * })],\n * });\n *\n * // With tool filtering - only allow specific tools\n * const filteredResponse = await model.invoke(\"Roll some dice\", {\n * tools: [tools.mcp({\n * serverLabel: \"dmcp\",\n * serverUrl: \"https://dmcp-server.deno.dev/sse\",\n * allowedTools: [\"roll\"], // Only allow the \"roll\" tool\n * requireApproval: \"never\",\n * })],\n * });\n *\n * // With fine-grained approval control\n * const controlledResponse = await model.invoke(\"Search and modify files\", {\n * tools: [tools.mcp({\n * serverLabel: \"deepwiki\",\n * serverUrl: \"https://mcp.deepwiki.com/mcp\",\n * requireApproval: {\n * never: { toolNames: [\"ask_question\", \"read_wiki_structure\"] },\n * // All other tools will require approval\n * },\n * })],\n * });\n * ```\n */\nexport declare function mcp(options: McpRemoteServerOptions): ServerTool;\nexport declare function mcp(options: McpConnectorOptions): ServerTool;\nexport {};\n//# sourceMappingURL=mcp.d.ts.map"],"mappings":";;;;;;;AAMA;AAIA;AAciBK,KAlBLF,cAAAA,GAkBsB,mBAIrBC,GAIDA,iBAAa,GAAA,0BAAA,GAAA,uBAAA,GAAA,0BAAA,GAAA,2BAAA,GAAA,wBAAA,GAAA,sBAAA;AACxB;;;AAgC0CC,UAvD1BD,aAAAA,CAuD0BC;EAAiB;AAS5D;AAUA;EAoBYK,SAAAA,CAAO,EAAA,MAAA,EAAA;EAiEKI;AACxB;;;;;;;;UAlJiBT,iBAAAA;;;;WAIJD;;;;UAIDA;;;;;UAKFE,cAAAA;;;;;;;;;4BASoBF;;;;;;;;;;YAUhBG;;;;;;;;;yCAS6BF;;;;;;;;;UAS1BG,sBAAAA,SAA+BF;;;;;;;;;;UAU/BG,mBAAAA,SAA4BH;;;;;;;;;;;;;;;eAe5BH;;;;;KAKLO,OAAAA,GAAUT,QAAAA,CAAaU,SAAAA,CAAUC,IAAAA,CAAKC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiE1BC,GAAAA,UAAaN,yBAAyBN;iBACtCY,GAAAA,UAAaL,sBAAsBP"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langchain/openai",
3
- "version": "1.2.6",
3
+ "version": "1.2.7",
4
4
  "description": "OpenAI integrations for LangChain.js",
5
5
  "author": "LangChain",
6
6
  "license": "MIT",
@@ -36,7 +36,7 @@
36
36
  "uuid": "^11.1.0",
37
37
  "vitest": "^3.2.4",
38
38
  "zod-to-json-schema": "^3.24.6",
39
- "@langchain/core": "1.1.20",
39
+ "@langchain/core": "^1.1.21",
40
40
  "@langchain/eslint": "0.1.1",
41
41
  "@langchain/standard-tests": "0.0.23",
42
42
  "@langchain/tsconfig": "0.0.1"