@librechat/agents 2.4.47 → 2.4.49

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.
@@ -301,7 +301,7 @@ function _convertMessagesToOpenAIResponsesParams(messages$1, model, zdrEnabled)
301
301
  ...(zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {}),
302
302
  })));
303
303
  }
304
- const toolOutputs = lcMsg.response_metadata.output.length
304
+ const toolOutputs = (lcMsg.response_metadata.output?.length ?? 0) > 0
305
305
  ? lcMsg.response_metadata.output
306
306
  : additional_kwargs.tool_outputs;
307
307
  const fallthroughCallTypes = [
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../../../../../src/llm/openai/utils/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/ban-ts-comment */\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\nimport { type OpenAI as OpenAIClient } from 'openai';\nimport type {\n ChatCompletionContentPartText,\n ChatCompletionContentPartImage,\n ChatCompletionContentPartInputAudio,\n ChatCompletionContentPart,\n} from 'openai/resources/chat/completions';\nimport {\n AIMessage,\n AIMessageChunk,\n type BaseMessage,\n ChatMessage,\n ToolMessage,\n isAIMessage,\n type UsageMetadata,\n type BaseMessageFields,\n type MessageContent,\n type InvalidToolCall,\n type MessageContentImageUrl,\n StandardContentBlockConverter,\n parseBase64DataUrl,\n parseMimeType,\n convertToProviderContentBlock,\n isDataContentBlock,\n} from '@langchain/core/messages';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport {\n convertLangChainToolCallToOpenAI,\n makeInvalidToolCall,\n parseToolCall,\n} from '@langchain/core/output_parsers/openai_tools';\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type {\n OpenAICallOptions,\n OpenAIChatInput,\n ChatOpenAIReasoningSummary,\n} from '@langchain/openai';\n\nexport type { OpenAICallOptions, OpenAIChatInput };\n\n// Utility types to get hidden OpenAI response types\ntype ExtractAsyncIterableType<T> = T extends AsyncIterable<infer U> ? U : never;\ntype ExcludeController<T> = T extends { controller: unknown } ? never : T;\ntype ExcludeNonController<T> = T extends { controller: unknown } ? T : never;\n\ntype ResponsesCreate = OpenAIClient.Responses['create'];\ntype ResponsesParse = OpenAIClient.Responses['parse'];\n\ntype ResponsesInputItem = OpenAIClient.Responses.ResponseInputItem;\n\ntype ResponsesCreateInvoke = ExcludeController<\n Awaited<ReturnType<ResponsesCreate>>\n>;\n\ntype ResponsesParseInvoke = ExcludeController<\n Awaited<ReturnType<ResponsesParse>>\n>;\n\ntype ResponsesCreateStream = ExcludeNonController<\n Awaited<ReturnType<ResponsesCreate>>\n>;\n\nexport type ResponseReturnStreamEvents =\n ExtractAsyncIterableType<ResponsesCreateStream>;\n\n// TODO import from SDK when available\ntype OpenAIRoleEnum =\n | 'system'\n | 'developer'\n | 'assistant'\n | 'user'\n | 'function'\n | 'tool';\n\ntype OpenAICompletionParam =\n OpenAIClient.Chat.Completions.ChatCompletionMessageParam;\n\nfunction extractGenericMessageCustomRole(message: ChatMessage) {\n if (\n message.role !== 'system' &&\n message.role !== 'developer' &&\n message.role !== 'assistant' &&\n message.role !== 'user' &&\n message.role !== 'function' &&\n message.role !== 'tool'\n ) {\n console.warn(`Unknown message role: ${message.role}`);\n }\n\n return message.role as OpenAIRoleEnum;\n}\n\nexport function messageToOpenAIRole(message: BaseMessage): OpenAIRoleEnum {\n const type = message._getType();\n switch (type) {\n case 'system':\n return 'system';\n case 'ai':\n return 'assistant';\n case 'human':\n return 'user';\n case 'function':\n return 'function';\n case 'tool':\n return 'tool';\n case 'generic': {\n if (!ChatMessage.isInstance(message))\n throw new Error('Invalid generic chat message');\n return extractGenericMessageCustomRole(message);\n }\n default:\n throw new Error(`Unknown message type: ${type}`);\n }\n}\n\nconst completionsApiContentBlockConverter: StandardContentBlockConverter<{\n text: ChatCompletionContentPartText;\n image: ChatCompletionContentPartImage;\n audio: ChatCompletionContentPartInputAudio;\n file: ChatCompletionContentPart.File;\n}> = {\n providerName: 'ChatOpenAI',\n\n fromStandardTextBlock(block): ChatCompletionContentPartText {\n return { type: 'text', text: block.text };\n },\n\n fromStandardImageBlock(block): ChatCompletionContentPartImage {\n if (block.source_type === 'url') {\n return {\n type: 'image_url',\n image_url: {\n url: block.url,\n ...(block.metadata?.detail\n ? { detail: block.metadata.detail as 'auto' | 'low' | 'high' }\n : {}),\n },\n };\n }\n\n if (block.source_type === 'base64') {\n const url = `data:${block.mime_type ?? ''};base64,${block.data}`;\n return {\n type: 'image_url',\n image_url: {\n url,\n ...(block.metadata?.detail\n ? { detail: block.metadata.detail as 'auto' | 'low' | 'high' }\n : {}),\n },\n };\n }\n\n throw new Error(\n `Image content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`\n );\n },\n\n fromStandardAudioBlock(block): ChatCompletionContentPartInputAudio {\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (!data) {\n throw new Error(\n `URL audio blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`\n );\n }\n\n const rawMimeType = data.mime_type || block.mime_type || '';\n let mimeType: { type: string; subtype: string };\n\n try {\n mimeType = parseMimeType(rawMimeType);\n } catch {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n if (\n mimeType.type !== 'audio' ||\n (mimeType.subtype !== 'wav' && mimeType.subtype !== 'mp3')\n ) {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n return {\n type: 'input_audio',\n input_audio: {\n format: mimeType.subtype,\n data: data.data,\n },\n };\n }\n\n if (block.source_type === 'base64') {\n let mimeType: { type: string; subtype: string };\n\n try {\n mimeType = parseMimeType(block.mime_type ?? '');\n } catch {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n if (\n mimeType.type !== 'audio' ||\n (mimeType.subtype !== 'wav' && mimeType.subtype !== 'mp3')\n ) {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n return {\n type: 'input_audio',\n input_audio: {\n format: mimeType.subtype,\n data: block.data,\n },\n };\n }\n\n throw new Error(\n `Audio content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`\n );\n },\n\n fromStandardFileBlock(block): ChatCompletionContentPart.File {\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (!data) {\n throw new Error(\n `URL file blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`\n );\n }\n\n return {\n type: 'file',\n file: {\n file_data: block.url, // formatted as base64 data URL\n ...(block.metadata?.filename || block.metadata?.name\n ? {\n filename: (block.metadata.filename ||\n block.metadata.name) as string,\n }\n : {}),\n },\n };\n }\n\n if (block.source_type === 'base64') {\n return {\n type: 'file',\n file: {\n file_data: `data:${block.mime_type ?? ''};base64,${block.data}`,\n ...(block.metadata?.filename ||\n block.metadata?.name ||\n block.metadata?.title\n ? {\n filename: (block.metadata.filename ||\n block.metadata.name ||\n block.metadata.title) as string,\n }\n : {}),\n },\n };\n }\n\n if (block.source_type === 'id') {\n return {\n type: 'file',\n file: {\n file_id: block.id,\n },\n };\n }\n\n throw new Error(\n `File content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`\n );\n },\n};\n\n// Used in LangSmith, export is important here\nexport function _convertMessagesToOpenAIParams(\n messages: BaseMessage[],\n model?: string\n): OpenAICompletionParam[] {\n // TODO: Function messages do not support array content, fix cast\n return messages.flatMap((message) => {\n let role = messageToOpenAIRole(message);\n if (role === 'system' && isReasoningModel(model)) {\n role = 'developer';\n }\n\n const content =\n typeof message.content === 'string'\n ? message.content\n : message.content.map((m) => {\n if (isDataContentBlock(m)) {\n return convertToProviderContentBlock(\n m,\n completionsApiContentBlockConverter\n );\n }\n return m;\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const completionParam: Record<string, any> = {\n role,\n content,\n };\n if (message.name != null) {\n completionParam.name = message.name;\n }\n if (message.additional_kwargs.function_call != null) {\n completionParam.function_call = message.additional_kwargs.function_call;\n completionParam.content = '';\n }\n if (isAIMessage(message) && !!message.tool_calls?.length) {\n completionParam.tool_calls = message.tool_calls.map(\n convertLangChainToolCallToOpenAI\n );\n completionParam.content = '';\n } else {\n if (message.additional_kwargs.tool_calls != null) {\n completionParam.tool_calls = message.additional_kwargs.tool_calls;\n }\n if ((message as ToolMessage).tool_call_id != null) {\n completionParam.tool_call_id = (message as ToolMessage).tool_call_id;\n }\n }\n\n if (\n message.additional_kwargs.audio &&\n typeof message.additional_kwargs.audio === 'object' &&\n 'id' in message.additional_kwargs.audio\n ) {\n const audioMessage = {\n role: 'assistant',\n audio: {\n id: message.additional_kwargs.audio.id,\n },\n };\n return [completionParam, audioMessage] as OpenAICompletionParam[];\n }\n\n return completionParam as OpenAICompletionParam;\n });\n}\n\nconst _FUNCTION_CALL_IDS_MAP_KEY = '__openai_function_call_ids__';\n\nfunction _convertReasoningSummaryToOpenAIResponsesParams(\n reasoning: ChatOpenAIReasoningSummary\n): OpenAIClient.Responses.ResponseReasoningItem {\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.at(-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\nexport function _convertMessagesToOpenAIResponsesParams(\n messages: BaseMessage[],\n model?: string,\n zdrEnabled?: boolean\n): ResponsesInputItem[] {\n return messages.flatMap(\n (lcMsg): ResponsesInputItem | ResponsesInputItem[] => {\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: 'computer_screenshot' as const,\n image_url: toolMessage.content,\n };\n }\n\n if (Array.isArray(toolMessage.content)) {\n const oaiScreenshot = toolMessage.content.find(\n (i) => i.type === 'computer_screenshot'\n ) as { type: 'computer_screenshot'; image_url: string };\n\n if (oaiScreenshot) return oaiScreenshot;\n\n const lcImage = toolMessage.content.find(\n (i) => i.type === 'image_url'\n ) as MessageContentImageUrl;\n\n if (lcImage) {\n return {\n type: 'computer_screenshot' 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 return {\n type: 'computer_call_output',\n output,\n call_id: toolMessage.tool_call_id,\n };\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:\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 lcMsg.response_metadata.output != null &&\n Array.isArray(lcMsg.response_metadata.output) &&\n lcMsg.response_metadata.output.length > 0 &&\n lcMsg.response_metadata.output.every((item) => 'type' in item)\n ) {\n return lcMsg.response_metadata.output;\n }\n\n // otherwise, try to reconstruct the response from what we have\n\n const input: ResponsesInputItem[] = [];\n\n // reasoning items\n if (additional_kwargs.reasoning && !zdrEnabled) {\n const reasoningItem = _convertReasoningSummaryToOpenAIResponsesParams(\n additional_kwargs.reasoning\n );\n input.push(reasoningItem);\n }\n\n // ai content\n let { content } = lcMsg;\n if (additional_kwargs.refusal) {\n if (typeof content === 'string') {\n content = [{ type: 'output_text', text: content, annotations: [] }];\n }\n content = [\n ...content,\n { type: 'refusal', refusal: additional_kwargs.refusal },\n ];\n }\n\n input.push({\n type: 'message',\n role: 'assistant',\n ...(lcMsg.id && !zdrEnabled ? { id: lcMsg.id } : {}),\n content:\n typeof content === 'string'\n ? content\n : content.flatMap((item) => {\n if (item.type === 'text') {\n return {\n type: 'output_text',\n text: item.text,\n // @ts-expect-error TODO: add types for `annotations`\n annotations: item.annotations ?? [],\n };\n }\n\n if (item.type === 'output_text' || item.type === 'refusal') {\n return item;\n }\n\n return [];\n }),\n });\n\n const functionCallIds = additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY];\n\n if (isAIMessage(lcMsg) && !!lcMsg.tool_calls?.length) {\n input.push(\n ...lcMsg.tool_calls.map(\n (toolCall): ResponsesInputItem => ({\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 lcMsg.response_metadata.output as Array<ResponsesInputItem>\n ).length\n ? lcMsg.response_metadata.output\n : additional_kwargs.tool_outputs;\n\n const fallthroughCallTypes: ResponsesInputItem['type'][] = [\n 'computer_call',\n /** @ts-ignore */\n 'mcp_call',\n /** @ts-ignore */\n 'code_interpreter_call',\n /** @ts-ignore */\n 'image_generation_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.flatMap((item) => {\n if (item.type === 'mcp_approval_response') {\n messages.push({\n // @ts-ignore\n type: 'mcp_approval_response',\n approval_request_id: item.approval_request_id,\n approve: item.approve,\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 return {\n type: 'input_image',\n image_url:\n typeof item.image_url === 'string'\n ? item.image_url\n : item.image_url.url,\n detail:\n typeof item.image_url === 'string'\n ? 'auto'\n : item.image_url.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({ type: 'message', role, content });\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\nexport function isReasoningModel(model?: string) {\n return model != null && model && /^o\\d/.test(model);\n}\n\nfunction _convertOpenAIResponsesMessageToBaseMessage(\n response: ResponsesCreateInvoke | ResponsesParseInvoke\n): BaseMessage {\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: 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\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,\n };\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 } 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: response.usage,\n additional_kwargs,\n response_metadata,\n });\n}\n\nexport function _convertOpenAIResponsesDeltaToBaseMessageChunk(\n chunk: ResponseReturnStreamEvents\n) {\n const content: Record<string, unknown>[] = [];\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 const additional_kwargs: {\n [key: string]: unknown;\n reasoning?: Partial<ChatOpenAIReasoningSummary>;\n tool_outputs?: unknown[];\n } = {};\n let id: string | undefined;\n if (chunk.type === 'response.output_text.delta') {\n content.push({\n type: 'text',\n text: chunk.delta,\n index: chunk.content_index,\n });\n /** @ts-ignore */\n } else if (chunk.type === 'response.output_text_annotation.added') {\n content.push({\n type: 'text',\n text: '',\n /** @ts-ignore */\n annotations: [chunk.annotation],\n /** @ts-ignore */\n index: chunk.content_index,\n });\n } else if (\n chunk.type === 'response.output_item.added' &&\n chunk.item.type === 'message'\n ) {\n id = chunk.item.id;\n } else if (\n chunk.type === 'response.output_item.added' &&\n chunk.item.type === 'function_call'\n ) {\n tool_call_chunks.push({\n type: 'tool_call_chunk',\n name: chunk.item.name,\n args: chunk.item.arguments,\n id: chunk.item.call_id,\n index: chunk.output_index,\n });\n\n additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] = {\n [chunk.item.call_id]: chunk.item.id,\n };\n } else if (\n chunk.type === 'response.output_item.done' &&\n [\n 'web_search_call',\n 'file_search_call',\n 'computer_call',\n 'code_interpreter_call',\n 'mcp_call',\n 'mcp_list_tools',\n 'mcp_approval_request',\n 'image_generation_call',\n ].includes(chunk.item.type)\n ) {\n additional_kwargs.tool_outputs = [chunk.item];\n } else if (chunk.type === 'response.created') {\n response_metadata.id = chunk.response.id;\n response_metadata.model_name = chunk.response.model;\n response_metadata.model = chunk.response.model;\n } else if (chunk.type === 'response.completed') {\n const msg = _convertOpenAIResponsesMessageToBaseMessage(chunk.response);\n\n usage_metadata = chunk.response.usage;\n if (chunk.response.text?.format?.type === 'json_schema') {\n additional_kwargs.parsed ??= JSON.parse(msg.text);\n }\n for (const [key, value] of Object.entries(chunk.response)) {\n if (key !== 'id') response_metadata[key] = value;\n }\n } else if (chunk.type === 'response.function_call_arguments.delta') {\n tool_call_chunks.push({\n type: 'tool_call_chunk',\n args: chunk.delta,\n index: chunk.output_index,\n });\n } else if (\n chunk.type === 'response.web_search_call.completed' ||\n chunk.type === 'response.file_search_call.completed'\n ) {\n generationInfo = {\n tool_outputs: {\n id: chunk.item_id,\n type: chunk.type.replace('response.', '').replace('.completed', ''),\n status: 'completed',\n },\n };\n } else if (chunk.type === 'response.refusal.done') {\n additional_kwargs.refusal = chunk.refusal;\n } else if (\n chunk.type === 'response.output_item.added' &&\n 'item' in chunk &&\n chunk.item.type === 'reasoning'\n ) {\n const summary: ChatOpenAIReasoningSummary['summary'] | undefined = chunk\n .item.summary\n ? chunk.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 chunk or else the concatenated result of all chunks will\n // have an ID field that is repeated once per chunk. There is special handling for the `type`\n // field that prevents this, however.\n id: chunk.item.id,\n type: chunk.item.type,\n ...(summary ? { summary } : {}),\n };\n } else if (chunk.type === 'response.reasoning_summary_part.added') {\n additional_kwargs.reasoning = {\n type: 'reasoning',\n summary: [{ ...chunk.part, index: chunk.summary_index }],\n };\n } else if (chunk.type === 'response.reasoning_summary_text.delta') {\n additional_kwargs.reasoning = {\n type: 'reasoning',\n summary: [\n { text: chunk.delta, type: 'summary_text', index: chunk.summary_index },\n ],\n };\n /** @ts-ignore */\n } else if (chunk.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"],"names":["ChatMessage","parseBase64DataUrl","parseMimeType","messages","isAIMessage","isDataContentBlock","convertToProviderContentBlock","parseToolCall","makeInvalidToolCall","AIMessage","ChatGenerationChunk","AIMessageChunk"],"mappings":";;;;;;AA+EA,SAAS,+BAA+B,CAAC,OAAoB,EAAA;AAC3D,IAAA,IACE,OAAO,CAAC,IAAI,KAAK,QAAQ;QACzB,OAAO,CAAC,IAAI,KAAK,WAAW;QAC5B,OAAO,CAAC,IAAI,KAAK,WAAW;QAC5B,OAAO,CAAC,IAAI,KAAK,MAAM;QACvB,OAAO,CAAC,IAAI,KAAK,UAAU;AAC3B,QAAA,OAAO,CAAC,IAAI,KAAK,MAAM,EACvB;QACA,OAAO,CAAC,IAAI,CAAC,CAAA,sBAAA,EAAyB,OAAO,CAAC,IAAI,CAAE,CAAA,CAAC;;IAGvD,OAAO,OAAO,CAAC,IAAsB;AACvC;AAEM,SAAU,mBAAmB,CAAC,OAAoB,EAAA;AACtD,IAAA,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,EAAE;IAC/B,QAAQ,IAAI;AACZ,QAAA,KAAK,QAAQ;AACX,YAAA,OAAO,QAAQ;AACjB,QAAA,KAAK,IAAI;AACP,YAAA,OAAO,WAAW;AACpB,QAAA,KAAK,OAAO;AACV,YAAA,OAAO,MAAM;AACf,QAAA,KAAK,UAAU;AACb,YAAA,OAAO,UAAU;AACnB,QAAA,KAAK,MAAM;AACT,YAAA,OAAO,MAAM;QACf,KAAK,SAAS,EAAE;AACd,YAAA,IAAI,CAACA,oBAAW,CAAC,UAAU,CAAC,OAAO,CAAC;AAClC,gBAAA,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC;AACjD,YAAA,OAAO,+BAA+B,CAAC,OAAO,CAAC;;AAEjD,QAAA;AACE,YAAA,MAAM,IAAI,KAAK,CAAC,yBAAyB,IAAI,CAAA,CAAE,CAAC;;AAEpD;AAEA,MAAM,mCAAmC,GAKpC;AACH,IAAA,YAAY,EAAE,YAAY;AAE1B,IAAA,qBAAqB,CAAC,KAAK,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* eslint-disable @typescript-eslint/ban-ts-comment */\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\nimport { type OpenAI as OpenAIClient } from 'openai';\nimport type {\n ChatCompletionContentPartText,\n ChatCompletionContentPartImage,\n ChatCompletionContentPartInputAudio,\n ChatCompletionContentPart,\n} from 'openai/resources/chat/completions';\nimport {\n AIMessage,\n AIMessageChunk,\n type BaseMessage,\n ChatMessage,\n ToolMessage,\n isAIMessage,\n type UsageMetadata,\n type BaseMessageFields,\n type MessageContent,\n type InvalidToolCall,\n type MessageContentImageUrl,\n StandardContentBlockConverter,\n parseBase64DataUrl,\n parseMimeType,\n convertToProviderContentBlock,\n isDataContentBlock,\n} from '@langchain/core/messages';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport {\n convertLangChainToolCallToOpenAI,\n makeInvalidToolCall,\n parseToolCall,\n} from '@langchain/core/output_parsers/openai_tools';\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type {\n OpenAICallOptions,\n OpenAIChatInput,\n ChatOpenAIReasoningSummary,\n} from '@langchain/openai';\n\nexport type { OpenAICallOptions, OpenAIChatInput };\n\n// Utility types to get hidden OpenAI response types\ntype ExtractAsyncIterableType<T> = T extends AsyncIterable<infer U> ? U : never;\ntype ExcludeController<T> = T extends { controller: unknown } ? never : T;\ntype ExcludeNonController<T> = T extends { controller: unknown } ? T : never;\n\ntype ResponsesCreate = OpenAIClient.Responses['create'];\ntype ResponsesParse = OpenAIClient.Responses['parse'];\n\ntype ResponsesInputItem = OpenAIClient.Responses.ResponseInputItem;\n\ntype ResponsesCreateInvoke = ExcludeController<\n Awaited<ReturnType<ResponsesCreate>>\n>;\n\ntype ResponsesParseInvoke = ExcludeController<\n Awaited<ReturnType<ResponsesParse>>\n>;\n\ntype ResponsesCreateStream = ExcludeNonController<\n Awaited<ReturnType<ResponsesCreate>>\n>;\n\nexport type ResponseReturnStreamEvents =\n ExtractAsyncIterableType<ResponsesCreateStream>;\n\n// TODO import from SDK when available\ntype OpenAIRoleEnum =\n | 'system'\n | 'developer'\n | 'assistant'\n | 'user'\n | 'function'\n | 'tool';\n\ntype OpenAICompletionParam =\n OpenAIClient.Chat.Completions.ChatCompletionMessageParam;\n\nfunction extractGenericMessageCustomRole(message: ChatMessage) {\n if (\n message.role !== 'system' &&\n message.role !== 'developer' &&\n message.role !== 'assistant' &&\n message.role !== 'user' &&\n message.role !== 'function' &&\n message.role !== 'tool'\n ) {\n console.warn(`Unknown message role: ${message.role}`);\n }\n\n return message.role as OpenAIRoleEnum;\n}\n\nexport function messageToOpenAIRole(message: BaseMessage): OpenAIRoleEnum {\n const type = message._getType();\n switch (type) {\n case 'system':\n return 'system';\n case 'ai':\n return 'assistant';\n case 'human':\n return 'user';\n case 'function':\n return 'function';\n case 'tool':\n return 'tool';\n case 'generic': {\n if (!ChatMessage.isInstance(message))\n throw new Error('Invalid generic chat message');\n return extractGenericMessageCustomRole(message);\n }\n default:\n throw new Error(`Unknown message type: ${type}`);\n }\n}\n\nconst completionsApiContentBlockConverter: StandardContentBlockConverter<{\n text: ChatCompletionContentPartText;\n image: ChatCompletionContentPartImage;\n audio: ChatCompletionContentPartInputAudio;\n file: ChatCompletionContentPart.File;\n}> = {\n providerName: 'ChatOpenAI',\n\n fromStandardTextBlock(block): ChatCompletionContentPartText {\n return { type: 'text', text: block.text };\n },\n\n fromStandardImageBlock(block): ChatCompletionContentPartImage {\n if (block.source_type === 'url') {\n return {\n type: 'image_url',\n image_url: {\n url: block.url,\n ...(block.metadata?.detail\n ? { detail: block.metadata.detail as 'auto' | 'low' | 'high' }\n : {}),\n },\n };\n }\n\n if (block.source_type === 'base64') {\n const url = `data:${block.mime_type ?? ''};base64,${block.data}`;\n return {\n type: 'image_url',\n image_url: {\n url,\n ...(block.metadata?.detail\n ? { detail: block.metadata.detail as 'auto' | 'low' | 'high' }\n : {}),\n },\n };\n }\n\n throw new Error(\n `Image content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`\n );\n },\n\n fromStandardAudioBlock(block): ChatCompletionContentPartInputAudio {\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (!data) {\n throw new Error(\n `URL audio blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`\n );\n }\n\n const rawMimeType = data.mime_type || block.mime_type || '';\n let mimeType: { type: string; subtype: string };\n\n try {\n mimeType = parseMimeType(rawMimeType);\n } catch {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n if (\n mimeType.type !== 'audio' ||\n (mimeType.subtype !== 'wav' && mimeType.subtype !== 'mp3')\n ) {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n return {\n type: 'input_audio',\n input_audio: {\n format: mimeType.subtype,\n data: data.data,\n },\n };\n }\n\n if (block.source_type === 'base64') {\n let mimeType: { type: string; subtype: string };\n\n try {\n mimeType = parseMimeType(block.mime_type ?? '');\n } catch {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n if (\n mimeType.type !== 'audio' ||\n (mimeType.subtype !== 'wav' && mimeType.subtype !== 'mp3')\n ) {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n return {\n type: 'input_audio',\n input_audio: {\n format: mimeType.subtype,\n data: block.data,\n },\n };\n }\n\n throw new Error(\n `Audio content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`\n );\n },\n\n fromStandardFileBlock(block): ChatCompletionContentPart.File {\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (!data) {\n throw new Error(\n `URL file blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`\n );\n }\n\n return {\n type: 'file',\n file: {\n file_data: block.url, // formatted as base64 data URL\n ...(block.metadata?.filename || block.metadata?.name\n ? {\n filename: (block.metadata.filename ||\n block.metadata.name) as string,\n }\n : {}),\n },\n };\n }\n\n if (block.source_type === 'base64') {\n return {\n type: 'file',\n file: {\n file_data: `data:${block.mime_type ?? ''};base64,${block.data}`,\n ...(block.metadata?.filename ||\n block.metadata?.name ||\n block.metadata?.title\n ? {\n filename: (block.metadata.filename ||\n block.metadata.name ||\n block.metadata.title) as string,\n }\n : {}),\n },\n };\n }\n\n if (block.source_type === 'id') {\n return {\n type: 'file',\n file: {\n file_id: block.id,\n },\n };\n }\n\n throw new Error(\n `File content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`\n );\n },\n};\n\n// Used in LangSmith, export is important here\nexport function _convertMessagesToOpenAIParams(\n messages: BaseMessage[],\n model?: string\n): OpenAICompletionParam[] {\n // TODO: Function messages do not support array content, fix cast\n return messages.flatMap((message) => {\n let role = messageToOpenAIRole(message);\n if (role === 'system' && isReasoningModel(model)) {\n role = 'developer';\n }\n\n const content =\n typeof message.content === 'string'\n ? message.content\n : message.content.map((m) => {\n if (isDataContentBlock(m)) {\n return convertToProviderContentBlock(\n m,\n completionsApiContentBlockConverter\n );\n }\n return m;\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const completionParam: Record<string, any> = {\n role,\n content,\n };\n if (message.name != null) {\n completionParam.name = message.name;\n }\n if (message.additional_kwargs.function_call != null) {\n completionParam.function_call = message.additional_kwargs.function_call;\n completionParam.content = '';\n }\n if (isAIMessage(message) && !!message.tool_calls?.length) {\n completionParam.tool_calls = message.tool_calls.map(\n convertLangChainToolCallToOpenAI\n );\n completionParam.content = '';\n } else {\n if (message.additional_kwargs.tool_calls != null) {\n completionParam.tool_calls = message.additional_kwargs.tool_calls;\n }\n if ((message as ToolMessage).tool_call_id != null) {\n completionParam.tool_call_id = (message as ToolMessage).tool_call_id;\n }\n }\n\n if (\n message.additional_kwargs.audio &&\n typeof message.additional_kwargs.audio === 'object' &&\n 'id' in message.additional_kwargs.audio\n ) {\n const audioMessage = {\n role: 'assistant',\n audio: {\n id: message.additional_kwargs.audio.id,\n },\n };\n return [completionParam, audioMessage] as OpenAICompletionParam[];\n }\n\n return completionParam as OpenAICompletionParam;\n });\n}\n\nconst _FUNCTION_CALL_IDS_MAP_KEY = '__openai_function_call_ids__';\n\nfunction _convertReasoningSummaryToOpenAIResponsesParams(\n reasoning: ChatOpenAIReasoningSummary\n): OpenAIClient.Responses.ResponseReasoningItem {\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.at(-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\nexport function _convertMessagesToOpenAIResponsesParams(\n messages: BaseMessage[],\n model?: string,\n zdrEnabled?: boolean\n): ResponsesInputItem[] {\n return messages.flatMap(\n (lcMsg): ResponsesInputItem | ResponsesInputItem[] => {\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: 'computer_screenshot' as const,\n image_url: toolMessage.content,\n };\n }\n\n if (Array.isArray(toolMessage.content)) {\n const oaiScreenshot = toolMessage.content.find(\n (i) => i.type === 'computer_screenshot'\n ) as { type: 'computer_screenshot'; image_url: string };\n\n if (oaiScreenshot) return oaiScreenshot;\n\n const lcImage = toolMessage.content.find(\n (i) => i.type === 'image_url'\n ) as MessageContentImageUrl;\n\n if (lcImage) {\n return {\n type: 'computer_screenshot' 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 return {\n type: 'computer_call_output',\n output,\n call_id: toolMessage.tool_call_id,\n };\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:\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 lcMsg.response_metadata.output != null &&\n Array.isArray(lcMsg.response_metadata.output) &&\n lcMsg.response_metadata.output.length > 0 &&\n lcMsg.response_metadata.output.every((item) => 'type' in item)\n ) {\n return lcMsg.response_metadata.output;\n }\n\n // otherwise, try to reconstruct the response from what we have\n\n const input: ResponsesInputItem[] = [];\n\n // reasoning items\n if (additional_kwargs.reasoning && !zdrEnabled) {\n const reasoningItem = _convertReasoningSummaryToOpenAIResponsesParams(\n additional_kwargs.reasoning\n );\n input.push(reasoningItem);\n }\n\n // ai content\n let { content } = lcMsg;\n if (additional_kwargs.refusal) {\n if (typeof content === 'string') {\n content = [{ type: 'output_text', text: content, annotations: [] }];\n }\n content = [\n ...content,\n { type: 'refusal', refusal: additional_kwargs.refusal },\n ];\n }\n\n input.push({\n type: 'message',\n role: 'assistant',\n ...(lcMsg.id && !zdrEnabled ? { id: lcMsg.id } : {}),\n content:\n typeof content === 'string'\n ? content\n : content.flatMap((item) => {\n if (item.type === 'text') {\n return {\n type: 'output_text',\n text: item.text,\n // @ts-expect-error TODO: add types for `annotations`\n annotations: item.annotations ?? [],\n };\n }\n\n if (item.type === 'output_text' || item.type === 'refusal') {\n return item;\n }\n\n return [];\n }),\n });\n\n const functionCallIds = additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY];\n\n if (isAIMessage(lcMsg) && !!lcMsg.tool_calls?.length) {\n input.push(\n ...lcMsg.tool_calls.map(\n (toolCall): ResponsesInputItem => ({\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 ((\n lcMsg.response_metadata.output as\n | Array<ResponsesInputItem>\n | undefined\n )?.length ?? 0) > 0\n ? lcMsg.response_metadata.output\n : additional_kwargs.tool_outputs;\n\n const fallthroughCallTypes: ResponsesInputItem['type'][] = [\n 'computer_call',\n /** @ts-ignore */\n 'mcp_call',\n /** @ts-ignore */\n 'code_interpreter_call',\n /** @ts-ignore */\n 'image_generation_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.flatMap((item) => {\n if (item.type === 'mcp_approval_response') {\n messages.push({\n // @ts-ignore\n type: 'mcp_approval_response',\n approval_request_id: item.approval_request_id,\n approve: item.approve,\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 return {\n type: 'input_image',\n image_url:\n typeof item.image_url === 'string'\n ? item.image_url\n : item.image_url.url,\n detail:\n typeof item.image_url === 'string'\n ? 'auto'\n : item.image_url.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({ type: 'message', role, content });\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\nexport function isReasoningModel(model?: string) {\n return model != null && model && /^o\\d/.test(model);\n}\n\nfunction _convertOpenAIResponsesMessageToBaseMessage(\n response: ResponsesCreateInvoke | ResponsesParseInvoke\n): BaseMessage {\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: 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\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,\n };\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 } 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: response.usage,\n additional_kwargs,\n response_metadata,\n });\n}\n\nexport function _convertOpenAIResponsesDeltaToBaseMessageChunk(\n chunk: ResponseReturnStreamEvents\n) {\n const content: Record<string, unknown>[] = [];\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 const additional_kwargs: {\n [key: string]: unknown;\n reasoning?: Partial<ChatOpenAIReasoningSummary>;\n tool_outputs?: unknown[];\n } = {};\n let id: string | undefined;\n if (chunk.type === 'response.output_text.delta') {\n content.push({\n type: 'text',\n text: chunk.delta,\n index: chunk.content_index,\n });\n /** @ts-ignore */\n } else if (chunk.type === 'response.output_text_annotation.added') {\n content.push({\n type: 'text',\n text: '',\n /** @ts-ignore */\n annotations: [chunk.annotation],\n /** @ts-ignore */\n index: chunk.content_index,\n });\n } else if (\n chunk.type === 'response.output_item.added' &&\n chunk.item.type === 'message'\n ) {\n id = chunk.item.id;\n } else if (\n chunk.type === 'response.output_item.added' &&\n chunk.item.type === 'function_call'\n ) {\n tool_call_chunks.push({\n type: 'tool_call_chunk',\n name: chunk.item.name,\n args: chunk.item.arguments,\n id: chunk.item.call_id,\n index: chunk.output_index,\n });\n\n additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] = {\n [chunk.item.call_id]: chunk.item.id,\n };\n } else if (\n chunk.type === 'response.output_item.done' &&\n [\n 'web_search_call',\n 'file_search_call',\n 'computer_call',\n 'code_interpreter_call',\n 'mcp_call',\n 'mcp_list_tools',\n 'mcp_approval_request',\n 'image_generation_call',\n ].includes(chunk.item.type)\n ) {\n additional_kwargs.tool_outputs = [chunk.item];\n } else if (chunk.type === 'response.created') {\n response_metadata.id = chunk.response.id;\n response_metadata.model_name = chunk.response.model;\n response_metadata.model = chunk.response.model;\n } else if (chunk.type === 'response.completed') {\n const msg = _convertOpenAIResponsesMessageToBaseMessage(chunk.response);\n\n usage_metadata = chunk.response.usage;\n if (chunk.response.text?.format?.type === 'json_schema') {\n additional_kwargs.parsed ??= JSON.parse(msg.text);\n }\n for (const [key, value] of Object.entries(chunk.response)) {\n if (key !== 'id') response_metadata[key] = value;\n }\n } else if (chunk.type === 'response.function_call_arguments.delta') {\n tool_call_chunks.push({\n type: 'tool_call_chunk',\n args: chunk.delta,\n index: chunk.output_index,\n });\n } else if (\n chunk.type === 'response.web_search_call.completed' ||\n chunk.type === 'response.file_search_call.completed'\n ) {\n generationInfo = {\n tool_outputs: {\n id: chunk.item_id,\n type: chunk.type.replace('response.', '').replace('.completed', ''),\n status: 'completed',\n },\n };\n } else if (chunk.type === 'response.refusal.done') {\n additional_kwargs.refusal = chunk.refusal;\n } else if (\n chunk.type === 'response.output_item.added' &&\n 'item' in chunk &&\n chunk.item.type === 'reasoning'\n ) {\n const summary: ChatOpenAIReasoningSummary['summary'] | undefined = chunk\n .item.summary\n ? chunk.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 chunk or else the concatenated result of all chunks will\n // have an ID field that is repeated once per chunk. There is special handling for the `type`\n // field that prevents this, however.\n id: chunk.item.id,\n type: chunk.item.type,\n ...(summary ? { summary } : {}),\n };\n } else if (chunk.type === 'response.reasoning_summary_part.added') {\n additional_kwargs.reasoning = {\n type: 'reasoning',\n summary: [{ ...chunk.part, index: chunk.summary_index }],\n };\n } else if (chunk.type === 'response.reasoning_summary_text.delta') {\n additional_kwargs.reasoning = {\n type: 'reasoning',\n summary: [\n { text: chunk.delta, type: 'summary_text', index: chunk.summary_index },\n ],\n };\n /** @ts-ignore */\n } else if (chunk.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"],"names":["ChatMessage","parseBase64DataUrl","parseMimeType","messages","isAIMessage","isDataContentBlock","convertToProviderContentBlock","parseToolCall","makeInvalidToolCall","AIMessage","ChatGenerationChunk","AIMessageChunk"],"mappings":";;;;;;AA+EA,SAAS,+BAA+B,CAAC,OAAoB,EAAA;AAC3D,IAAA,IACE,OAAO,CAAC,IAAI,KAAK,QAAQ;QACzB,OAAO,CAAC,IAAI,KAAK,WAAW;QAC5B,OAAO,CAAC,IAAI,KAAK,WAAW;QAC5B,OAAO,CAAC,IAAI,KAAK,MAAM;QACvB,OAAO,CAAC,IAAI,KAAK,UAAU;AAC3B,QAAA,OAAO,CAAC,IAAI,KAAK,MAAM,EACvB;QACA,OAAO,CAAC,IAAI,CAAC,CAAA,sBAAA,EAAyB,OAAO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,CAAC,aAAa,EAAE,CAAC;SACzD;;AACI,SAAA,IAAI,KAAK,CAAC,IAAI,KAAK,uCAAuC,EAAE;QACjE,iBAAiB,CAAC,SAAS,GAAG;AAC5B,YAAA,IAAI,EAAE,WAAW;AACjB,YAAA,OAAO,EAAE;AACP,gBAAA,EAAE,IAAI,EAAE,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE,cAAc,EAAE,KAAK,EAAE,KAAK,CAAC,aAAa,EAAE;AACxE,aAAA;SACF;;;AAEI,SAAA,IAAI,KAAK,CAAC,IAAI,KAAK,8CAA8C,EAAE;;;AAGxE,QAAA,OAAO,IAAI;;SACN;AACL,QAAA,OAAO,IAAI;;IAGb,OAAO,IAAIC,2BAAmB,CAAC;;AAE7B,QAAA,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC;QAC/C,OAAO,EAAE,IAAIC,uBAAc,CAAC;YAC1B,EAAE;YACF,OAAO;YACP,gBAAgB;YAChB,cAAc;YACd,iBAAiB;YACjB,iBAAiB;SAClB,CAAC;QACF,cAAc;AACf,KAAA,CAAC;AACJ;;;;;;;"}
@@ -53,6 +53,15 @@ function getNonEmptyValue(possibleValues) {
53
53
  }
54
54
  return undefined;
55
55
  }
56
+ function getChunkContent({ chunk, provider, reasoningKey, }) {
57
+ if ((provider === _enum.Providers.OPENAI || provider === _enum.Providers.AZURE) &&
58
+ chunk?.additional_kwargs?.reasoning?.summary?.[0]?.text != null &&
59
+ (chunk?.additional_kwargs?.reasoning?.summary?.[0]?.text?.length ?? 0) > 0) {
60
+ return chunk?.additional_kwargs?.reasoning?.summary?.[0]?.text;
61
+ }
62
+ return (chunk?.additional_kwargs?.[reasoningKey] ??
63
+ chunk?.content);
64
+ }
56
65
  class ChatModelStreamHandler {
57
66
  handle(event, data, metadata, graph) {
58
67
  if (!graph) {
@@ -66,9 +75,12 @@ class ChatModelStreamHandler {
66
75
  return;
67
76
  }
68
77
  const chunk = data.chunk;
69
- const content = chunk.additional_kwargs?.[graph.reasoningKey] ??
70
- chunk.content;
71
- this.handleReasoning(chunk, graph);
78
+ const content = getChunkContent({
79
+ chunk,
80
+ reasoningKey: graph.reasoningKey,
81
+ provider: metadata?.provider,
82
+ });
83
+ this.handleReasoning(chunk, graph, metadata?.provider);
72
84
  let hasToolCalls = false;
73
85
  if (chunk.tool_calls &&
74
86
  chunk.tool_calls.length > 0 &&
@@ -222,7 +234,7 @@ hasToolCallChunks: ${hasToolCallChunks}
222
234
  });
223
235
  }
224
236
  }
225
- handleReasoning(chunk, graph) {
237
+ handleReasoning(chunk, graph, provider) {
226
238
  let reasoning_content = chunk.additional_kwargs?.[graph.reasoningKey];
227
239
  if (Array.isArray(chunk.content) &&
228
240
  (chunk.content[0]?.type === _enum.ContentTypes.THINKING ||
@@ -230,8 +242,15 @@ hasToolCallChunks: ${hasToolCallChunks}
230
242
  chunk.content[0]?.type === _enum.ContentTypes.REASONING_CONTENT)) {
231
243
  reasoning_content = 'valid';
232
244
  }
245
+ else if ((provider === _enum.Providers.OPENAI || provider === _enum.Providers.AZURE) &&
246
+ reasoning_content != null &&
247
+ typeof reasoning_content !== 'string' &&
248
+ reasoning_content.summary?.[0]?.text != null &&
249
+ reasoning_content.summary[0].text) {
250
+ reasoning_content = 'valid';
251
+ }
233
252
  if (reasoning_content != null &&
234
- reasoning_content &&
253
+ reasoning_content !== '' &&
235
254
  (chunk.content == null ||
236
255
  chunk.content === '' ||
237
256
  reasoning_content === 'valid')) {
@@ -1 +1 @@
1
- {"version":3,"file":"stream.cjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\nimport { StepTypes, ContentTypes, GraphEvents, ToolCallTypes } from '@/common';\nimport { handleToolCalls, handleToolCallChunks } from '@/tools/handlers';\nimport { getMessageId } from '@/messages';\n\n/**\n * Parses content to extract thinking sections enclosed in <think> tags using string operations\n * @param content The content to parse\n * @returns An object with separated text and thinking content\n */\nfunction parseThinkingContent(content: string): {\n text: string;\n thinking: string;\n} {\n // If no think tags, return the original content as text\n if (!content.includes('<think>')) {\n return { text: content, thinking: '' };\n }\n\n let textResult = '';\n const thinkingResult: string[] = [];\n let position = 0;\n\n while (position < content.length) {\n const thinkStart = content.indexOf('<think>', position);\n\n if (thinkStart === -1) {\n // No more think tags, add the rest and break\n textResult += content.slice(position);\n break;\n }\n\n // Add text before the think tag\n textResult += content.slice(position, thinkStart);\n\n const thinkEnd = content.indexOf('</think>', thinkStart);\n if (thinkEnd === -1) {\n // Malformed input, no closing tag\n textResult += content.slice(thinkStart);\n break;\n }\n\n // Add the thinking content\n const thinkContent = content.slice(thinkStart + 7, thinkEnd);\n thinkingResult.push(thinkContent);\n\n // Move position to after the think tag\n position = thinkEnd + 8; // 8 is the length of '</think>'\n }\n\n return {\n text: textResult.trim(),\n thinking: thinkingResult.join('\\n').trim(),\n };\n}\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: Graph\n ): void {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content =\n (chunk.additional_kwargs?.[graph.reasoningKey] as string | undefined) ??\n chunk.content;\n this.handleReasoning(chunk, graph);\n\n let hasToolCalls = false;\n if (\n chunk.tool_calls &&\n chunk.tool_calls.length > 0 &&\n chunk.tool_calls.every((tc) => tc.id != null && tc.id !== '')\n ) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent =\n typeof content === 'undefined' ||\n !content.length ||\n (typeof content === 'string' && !content);\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n const chunkId = chunk.id ?? '';\n if (isEmptyChunk && chunkId && chunkId.startsWith('msg')) {\n if (graph.messageIdsByStepKey.has(chunkId)) {\n return;\n } else if (graph.prelimMessageIdsByStepKey.has(chunkId)) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunkId);\n return;\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (\n hasToolCallChunks &&\n chunk.tool_call_chunks &&\n chunk.tool_call_chunks.length &&\n typeof chunk.tool_call_chunks[0]?.index === 'number'\n ) {\n handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (graph.currentTokenType === ContentTypes.TEXT) {\n graph.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n } else if (graph.currentTokenType === 'think_and_text') {\n const { text, thinking } = parseThinkingContent(content);\n if (thinking) {\n graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: thinking,\n },\n ],\n });\n }\n if (text) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n const newStepKey = graph.getStepKey(metadata);\n const message_id = getMessageId(newStepKey, graph) ?? '';\n graph.dispatchRunStep(newStepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n\n const newStepId = graph.getStepIdByKey(newStepKey);\n graph.dispatchMessageDelta(newStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: text,\n },\n ],\n });\n }\n } else {\n graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n }\n } else if (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false)\n )\n ) {\n graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think:\n (c as t.ThinkingContentText).thinking ??\n (c as Partial<t.GoogleReasoningContentText>).reasoning ??\n (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ??\n '',\n })),\n });\n }\n }\n handleReasoning(chunk: Partial<AIMessageChunk>, graph: Graph): void {\n let reasoning_content = chunk.additional_kwargs?.[graph.reasoningKey] as\n | string\n | undefined;\n if (\n Array.isArray(chunk.content) &&\n (chunk.content[0]?.type === ContentTypes.THINKING ||\n chunk.content[0]?.type === ContentTypes.REASONING ||\n chunk.content[0]?.type === ContentTypes.REASONING_CONTENT)\n ) {\n reasoning_content = 'valid';\n }\n if (\n reasoning_content != null &&\n reasoning_content &&\n (chunk.content == null ||\n chunk.content === '' ||\n reasoning_content === 'valid')\n ) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'reasoning';\n return;\n } else if (\n graph.tokenTypeSwitch === 'reasoning' &&\n graph.currentTokenType !== ContentTypes.TEXT &&\n ((chunk.content != null && chunk.content !== '') ||\n (chunk.tool_calls?.length ?? 0) > 0)\n ) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>') &&\n chunk.content.includes('</think>')\n ) {\n graph.currentTokenType = 'think_and_text';\n graph.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>')\n ) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'content';\n } else if (\n graph.lastToken != null &&\n graph.lastToken.includes('</think>')\n ) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n graph.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart: t.MessageContentComplex,\n finalUpdate = false\n ): void => {\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (\n partType === ContentTypes.IMAGE_URL &&\n 'image_url' in contentPart\n ) {\n const currentContent = contentParts[index] as {\n type: 'image_url';\n image_url: string;\n };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (\n partType === ContentTypes.TOOL_CALL &&\n 'tool_call' in contentPart\n ) {\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart;\n })\n | undefined;\n\n const toolCallArgs = (contentPart.tool_call as t.ToolCallPart).args;\n /** When args are a valid object, they are likely already invoked */\n const args =\n finalUpdate ||\n typeof existingContent?.tool_call?.args === 'object' ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args ?? '') + (toolCallArgs ?? '');\n\n const id =\n getNonEmptyValue([\n contentPart.tool_call.id,\n existingContent?.tool_call?.id,\n ]) ?? '';\n const name =\n getNonEmptyValue([\n contentPart.tool_call.name,\n existingContent?.tool_call?.name,\n ]) ?? '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.RunStepDeltaEvent\n | { result: t.ToolEndEvent };\n }): void => {\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n (runStep.stepDetails.tool_calls as ToolCall[]).forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate;\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn(\n 'No run step or runId found for completed tool call event'\n );\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":["handleToolCalls","handleToolCallChunks","getMessageId","StepTypes","ContentTypes","ToolCallTypes","GraphEvents"],"mappings":";;;;;;;;AASA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAe,EAAA;;IAK3C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAChC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE;;IAGxC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,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,CAAC;AAC3C,iBAAC,CAAC;;;AAEC,aAAA,IAAI,KAAK,KAAKE,iBAAW,CAAC,qBAAqB,EAAE;AACtD,YAAA,MAAM,EAAE,MAAM,EAAE,GAAG,IAA6C;AAEhE,YAAA,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,MAAM;YAE7B,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC;YACnC,IAAI,CAAC,OAAO,EAAE;AACZ,gBAAA,OAAO,CAAC,IAAI,CACV,0DAA0D,CAC3D;gBACD;;AAGF,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAEF,kBAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B;YAED,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC;;AAEnD,KAAC;AAED,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE;AACpD;;;;;"}
1
+ {"version":3,"file":"stream.cjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type { ChatOpenAIReasoningSummary } from '@langchain/openai';\nimport type * as t from '@/types';\nimport {\n StepTypes,\n ContentTypes,\n GraphEvents,\n ToolCallTypes,\n Providers,\n} from '@/common';\nimport { handleToolCalls, handleToolCallChunks } from '@/tools/handlers';\nimport { getMessageId } from '@/messages';\n\n/**\n * Parses content to extract thinking sections enclosed in <think> tags using string operations\n * @param content The content to parse\n * @returns An object with separated text and thinking content\n */\nfunction parseThinkingContent(content: string): {\n text: string;\n thinking: string;\n} {\n // If no think tags, return the original content as text\n if (!content.includes('<think>')) {\n return { text: content, thinking: '' };\n }\n\n let textResult = '';\n const thinkingResult: string[] = [];\n let position = 0;\n\n while (position < content.length) {\n const thinkStart = content.indexOf('<think>', position);\n\n if (thinkStart === -1) {\n // No more think tags, add the rest and break\n textResult += content.slice(position);\n break;\n }\n\n // Add text before the think tag\n textResult += content.slice(position, thinkStart);\n\n const thinkEnd = content.indexOf('</think>', thinkStart);\n if (thinkEnd === -1) {\n // Malformed input, no closing tag\n textResult += content.slice(thinkStart);\n break;\n }\n\n // Add the thinking content\n const thinkContent = content.slice(thinkStart + 7, thinkEnd);\n thinkingResult.push(thinkContent);\n\n // Move position to after the think tag\n position = thinkEnd + 8; // 8 is the length of '</think>'\n }\n\n return {\n text: textResult.trim(),\n thinking: thinkingResult.join('\\n').trim(),\n };\n}\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nfunction getChunkContent({\n chunk,\n provider,\n reasoningKey,\n}: {\n chunk?: Partial<AIMessageChunk>;\n provider?: Providers;\n reasoningKey: 'reasoning_content' | 'reasoning';\n}): string | t.MessageContentComplex[] | undefined {\n if (\n (provider === Providers.OPENAI || provider === Providers.AZURE) &&\n (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text != null &&\n ((\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text?.length ?? 0) > 0\n ) {\n return (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text;\n }\n return (\n (chunk?.additional_kwargs?.[reasoningKey] as string | undefined) ??\n chunk?.content\n );\n}\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: Graph\n ): void {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content = getChunkContent({\n chunk,\n reasoningKey: graph.reasoningKey,\n provider: metadata?.provider as Providers,\n });\n this.handleReasoning(chunk, graph, metadata?.provider as Providers);\n\n let hasToolCalls = false;\n if (\n chunk.tool_calls &&\n chunk.tool_calls.length > 0 &&\n chunk.tool_calls.every((tc) => tc.id != null && tc.id !== '')\n ) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent =\n typeof content === 'undefined' ||\n !content.length ||\n (typeof content === 'string' && !content);\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n const chunkId = chunk.id ?? '';\n if (isEmptyChunk && chunkId && chunkId.startsWith('msg')) {\n if (graph.messageIdsByStepKey.has(chunkId)) {\n return;\n } else if (graph.prelimMessageIdsByStepKey.has(chunkId)) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunkId);\n return;\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (\n hasToolCallChunks &&\n chunk.tool_call_chunks &&\n chunk.tool_call_chunks.length &&\n typeof chunk.tool_call_chunks[0]?.index === 'number'\n ) {\n handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (graph.currentTokenType === ContentTypes.TEXT) {\n graph.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n } else if (graph.currentTokenType === 'think_and_text') {\n const { text, thinking } = parseThinkingContent(content);\n if (thinking) {\n graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: thinking,\n },\n ],\n });\n }\n if (text) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n const newStepKey = graph.getStepKey(metadata);\n const message_id = getMessageId(newStepKey, graph) ?? '';\n graph.dispatchRunStep(newStepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n\n const newStepId = graph.getStepIdByKey(newStepKey);\n graph.dispatchMessageDelta(newStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: text,\n },\n ],\n });\n }\n } else {\n graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n }\n } else if (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false)\n )\n ) {\n graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think:\n (c as t.ThinkingContentText).thinking ??\n (c as Partial<t.GoogleReasoningContentText>).reasoning ??\n (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ??\n '',\n })),\n });\n }\n }\n handleReasoning(\n chunk: Partial<AIMessageChunk>,\n graph: Graph,\n provider?: Providers\n ): void {\n let reasoning_content = chunk.additional_kwargs?.[graph.reasoningKey] as\n | string\n | Partial<ChatOpenAIReasoningSummary>\n | undefined;\n if (\n Array.isArray(chunk.content) &&\n (chunk.content[0]?.type === ContentTypes.THINKING ||\n chunk.content[0]?.type === ContentTypes.REASONING ||\n chunk.content[0]?.type === ContentTypes.REASONING_CONTENT)\n ) {\n reasoning_content = 'valid';\n } else if (\n (provider === Providers.OPENAI || provider === Providers.AZURE) &&\n reasoning_content != null &&\n typeof reasoning_content !== 'string' &&\n reasoning_content.summary?.[0]?.text != null &&\n reasoning_content.summary[0].text\n ) {\n reasoning_content = 'valid';\n }\n if (\n reasoning_content != null &&\n reasoning_content !== '' &&\n (chunk.content == null ||\n chunk.content === '' ||\n reasoning_content === 'valid')\n ) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'reasoning';\n return;\n } else if (\n graph.tokenTypeSwitch === 'reasoning' &&\n graph.currentTokenType !== ContentTypes.TEXT &&\n ((chunk.content != null && chunk.content !== '') ||\n (chunk.tool_calls?.length ?? 0) > 0)\n ) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>') &&\n chunk.content.includes('</think>')\n ) {\n graph.currentTokenType = 'think_and_text';\n graph.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>')\n ) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'content';\n } else if (\n graph.lastToken != null &&\n graph.lastToken.includes('</think>')\n ) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n graph.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart: t.MessageContentComplex,\n finalUpdate = false\n ): void => {\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (\n partType === ContentTypes.IMAGE_URL &&\n 'image_url' in contentPart\n ) {\n const currentContent = contentParts[index] as {\n type: 'image_url';\n image_url: string;\n };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (\n partType === ContentTypes.TOOL_CALL &&\n 'tool_call' in contentPart\n ) {\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart;\n })\n | undefined;\n\n const toolCallArgs = (contentPart.tool_call as t.ToolCallPart).args;\n /** When args are a valid object, they are likely already invoked */\n const args =\n finalUpdate ||\n typeof existingContent?.tool_call?.args === 'object' ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args ?? '') + (toolCallArgs ?? '');\n\n const id =\n getNonEmptyValue([\n contentPart.tool_call.id,\n existingContent?.tool_call?.id,\n ]) ?? '';\n const name =\n getNonEmptyValue([\n contentPart.tool_call.name,\n existingContent?.tool_call?.name,\n ]) ?? '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.RunStepDeltaEvent\n | { result: t.ToolEndEvent };\n }): void => {\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n (runStep.stepDetails.tool_calls as ToolCall[]).forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate;\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn(\n 'No run step or runId found for completed tool call event'\n );\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":["Providers","handleToolCalls","handleToolCallChunks","getMessageId","StepTypes","ContentTypes","ToolCallTypes","GraphEvents"],"mappings":";;;;;;;;AAgBA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAe,EAAA;;IAK3C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAChC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE;;IAGxC,IAAI,UAAU,GAAG,EAAE;IACnB,MAAM,cAAc,GAAa,EAAE;IACnC,IAAI,QAAQ,GAAG,CAAC;AAEhB,IAAA,OAAO,QAAQ,GAAG,OAAO,CAAC,MAAM,EAAE;QAChC,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC;AAEvD,QAAA,IAAI,UAAU,KAAK,EAAE,EAAE;;AAErB,YAAA,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC;YACrC;;;QAIF,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,UAAU,CAAC;QAEjD,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,UAAU,EAAE,UAAU,CAAC;AACxD,QAAA,IAAI,QAAQ,KAAK,EAAE,EAAE;;AAEnB,YAAA,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC;YACvC;;;AAIF,QAAA,MAAM,YAAY,GAAG,OAAO,CAAC,KAAK,CAAC,UAAU,GAAG,CAAC,EAAE,QAAQ,CAAC;AAC5D,QAAA,cAAc,CAAC,IAAI,CAAC,YAAY,CAAC;;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CAAC,EAAE,CAAC;AAErD,oBAAA,MAAM,WAAW,GAA4B;wBAC3C,IAAI,EAAEC,kBAAY,CAAC,SAAS;AAC5B,wBAAA,SAAS,EAAE;AACT,4BAAA,IAAI,EAAE,aAAa,CAAC,IAAI,IAAI,EAAE;4BAC9B,IAAI,EAAE,aAAa,CAAC,IAAI;AACxB,4BAAA,EAAE,EAAE,UAAU;AACf,yBAAA;qBACF;AAED,oBAAA,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,CAAC;AAC3C,iBAAC,CAAC;;;AAEC,aAAA,IAAI,KAAK,KAAKE,iBAAW,CAAC,qBAAqB,EAAE;AACtD,YAAA,MAAM,EAAE,MAAM,EAAE,GAAG,IAA6C;AAEhE,YAAA,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,MAAM;YAE7B,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC;YACnC,IAAI,CAAC,OAAO,EAAE;AACZ,gBAAA,OAAO,CAAC,IAAI,CACV,0DAA0D,CAC3D;gBACD;;AAGF,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAEF,kBAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B;YAED,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC;;AAEnD,KAAC;AAED,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE;AACpD;;;;;"}
@@ -299,7 +299,7 @@ function _convertMessagesToOpenAIResponsesParams(messages, model, zdrEnabled) {
299
299
  ...(zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {}),
300
300
  })));
301
301
  }
302
- const toolOutputs = lcMsg.response_metadata.output.length
302
+ const toolOutputs = (lcMsg.response_metadata.output?.length ?? 0) > 0
303
303
  ? lcMsg.response_metadata.output
304
304
  : additional_kwargs.tool_outputs;
305
305
  const fallthroughCallTypes = [
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../../../../../src/llm/openai/utils/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/ban-ts-comment */\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\nimport { type OpenAI as OpenAIClient } from 'openai';\nimport type {\n ChatCompletionContentPartText,\n ChatCompletionContentPartImage,\n ChatCompletionContentPartInputAudio,\n ChatCompletionContentPart,\n} from 'openai/resources/chat/completions';\nimport {\n AIMessage,\n AIMessageChunk,\n type BaseMessage,\n ChatMessage,\n ToolMessage,\n isAIMessage,\n type UsageMetadata,\n type BaseMessageFields,\n type MessageContent,\n type InvalidToolCall,\n type MessageContentImageUrl,\n StandardContentBlockConverter,\n parseBase64DataUrl,\n parseMimeType,\n convertToProviderContentBlock,\n isDataContentBlock,\n} from '@langchain/core/messages';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport {\n convertLangChainToolCallToOpenAI,\n makeInvalidToolCall,\n parseToolCall,\n} from '@langchain/core/output_parsers/openai_tools';\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type {\n OpenAICallOptions,\n OpenAIChatInput,\n ChatOpenAIReasoningSummary,\n} from '@langchain/openai';\n\nexport type { OpenAICallOptions, OpenAIChatInput };\n\n// Utility types to get hidden OpenAI response types\ntype ExtractAsyncIterableType<T> = T extends AsyncIterable<infer U> ? U : never;\ntype ExcludeController<T> = T extends { controller: unknown } ? never : T;\ntype ExcludeNonController<T> = T extends { controller: unknown } ? T : never;\n\ntype ResponsesCreate = OpenAIClient.Responses['create'];\ntype ResponsesParse = OpenAIClient.Responses['parse'];\n\ntype ResponsesInputItem = OpenAIClient.Responses.ResponseInputItem;\n\ntype ResponsesCreateInvoke = ExcludeController<\n Awaited<ReturnType<ResponsesCreate>>\n>;\n\ntype ResponsesParseInvoke = ExcludeController<\n Awaited<ReturnType<ResponsesParse>>\n>;\n\ntype ResponsesCreateStream = ExcludeNonController<\n Awaited<ReturnType<ResponsesCreate>>\n>;\n\nexport type ResponseReturnStreamEvents =\n ExtractAsyncIterableType<ResponsesCreateStream>;\n\n// TODO import from SDK when available\ntype OpenAIRoleEnum =\n | 'system'\n | 'developer'\n | 'assistant'\n | 'user'\n | 'function'\n | 'tool';\n\ntype OpenAICompletionParam =\n OpenAIClient.Chat.Completions.ChatCompletionMessageParam;\n\nfunction extractGenericMessageCustomRole(message: ChatMessage) {\n if (\n message.role !== 'system' &&\n message.role !== 'developer' &&\n message.role !== 'assistant' &&\n message.role !== 'user' &&\n message.role !== 'function' &&\n message.role !== 'tool'\n ) {\n console.warn(`Unknown message role: ${message.role}`);\n }\n\n return message.role as OpenAIRoleEnum;\n}\n\nexport function messageToOpenAIRole(message: BaseMessage): OpenAIRoleEnum {\n const type = message._getType();\n switch (type) {\n case 'system':\n return 'system';\n case 'ai':\n return 'assistant';\n case 'human':\n return 'user';\n case 'function':\n return 'function';\n case 'tool':\n return 'tool';\n case 'generic': {\n if (!ChatMessage.isInstance(message))\n throw new Error('Invalid generic chat message');\n return extractGenericMessageCustomRole(message);\n }\n default:\n throw new Error(`Unknown message type: ${type}`);\n }\n}\n\nconst completionsApiContentBlockConverter: StandardContentBlockConverter<{\n text: ChatCompletionContentPartText;\n image: ChatCompletionContentPartImage;\n audio: ChatCompletionContentPartInputAudio;\n file: ChatCompletionContentPart.File;\n}> = {\n providerName: 'ChatOpenAI',\n\n fromStandardTextBlock(block): ChatCompletionContentPartText {\n return { type: 'text', text: block.text };\n },\n\n fromStandardImageBlock(block): ChatCompletionContentPartImage {\n if (block.source_type === 'url') {\n return {\n type: 'image_url',\n image_url: {\n url: block.url,\n ...(block.metadata?.detail\n ? { detail: block.metadata.detail as 'auto' | 'low' | 'high' }\n : {}),\n },\n };\n }\n\n if (block.source_type === 'base64') {\n const url = `data:${block.mime_type ?? ''};base64,${block.data}`;\n return {\n type: 'image_url',\n image_url: {\n url,\n ...(block.metadata?.detail\n ? { detail: block.metadata.detail as 'auto' | 'low' | 'high' }\n : {}),\n },\n };\n }\n\n throw new Error(\n `Image content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`\n );\n },\n\n fromStandardAudioBlock(block): ChatCompletionContentPartInputAudio {\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (!data) {\n throw new Error(\n `URL audio blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`\n );\n }\n\n const rawMimeType = data.mime_type || block.mime_type || '';\n let mimeType: { type: string; subtype: string };\n\n try {\n mimeType = parseMimeType(rawMimeType);\n } catch {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n if (\n mimeType.type !== 'audio' ||\n (mimeType.subtype !== 'wav' && mimeType.subtype !== 'mp3')\n ) {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n return {\n type: 'input_audio',\n input_audio: {\n format: mimeType.subtype,\n data: data.data,\n },\n };\n }\n\n if (block.source_type === 'base64') {\n let mimeType: { type: string; subtype: string };\n\n try {\n mimeType = parseMimeType(block.mime_type ?? '');\n } catch {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n if (\n mimeType.type !== 'audio' ||\n (mimeType.subtype !== 'wav' && mimeType.subtype !== 'mp3')\n ) {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n return {\n type: 'input_audio',\n input_audio: {\n format: mimeType.subtype,\n data: block.data,\n },\n };\n }\n\n throw new Error(\n `Audio content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`\n );\n },\n\n fromStandardFileBlock(block): ChatCompletionContentPart.File {\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (!data) {\n throw new Error(\n `URL file blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`\n );\n }\n\n return {\n type: 'file',\n file: {\n file_data: block.url, // formatted as base64 data URL\n ...(block.metadata?.filename || block.metadata?.name\n ? {\n filename: (block.metadata.filename ||\n block.metadata.name) as string,\n }\n : {}),\n },\n };\n }\n\n if (block.source_type === 'base64') {\n return {\n type: 'file',\n file: {\n file_data: `data:${block.mime_type ?? ''};base64,${block.data}`,\n ...(block.metadata?.filename ||\n block.metadata?.name ||\n block.metadata?.title\n ? {\n filename: (block.metadata.filename ||\n block.metadata.name ||\n block.metadata.title) as string,\n }\n : {}),\n },\n };\n }\n\n if (block.source_type === 'id') {\n return {\n type: 'file',\n file: {\n file_id: block.id,\n },\n };\n }\n\n throw new Error(\n `File content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`\n );\n },\n};\n\n// Used in LangSmith, export is important here\nexport function _convertMessagesToOpenAIParams(\n messages: BaseMessage[],\n model?: string\n): OpenAICompletionParam[] {\n // TODO: Function messages do not support array content, fix cast\n return messages.flatMap((message) => {\n let role = messageToOpenAIRole(message);\n if (role === 'system' && isReasoningModel(model)) {\n role = 'developer';\n }\n\n const content =\n typeof message.content === 'string'\n ? message.content\n : message.content.map((m) => {\n if (isDataContentBlock(m)) {\n return convertToProviderContentBlock(\n m,\n completionsApiContentBlockConverter\n );\n }\n return m;\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const completionParam: Record<string, any> = {\n role,\n content,\n };\n if (message.name != null) {\n completionParam.name = message.name;\n }\n if (message.additional_kwargs.function_call != null) {\n completionParam.function_call = message.additional_kwargs.function_call;\n completionParam.content = '';\n }\n if (isAIMessage(message) && !!message.tool_calls?.length) {\n completionParam.tool_calls = message.tool_calls.map(\n convertLangChainToolCallToOpenAI\n );\n completionParam.content = '';\n } else {\n if (message.additional_kwargs.tool_calls != null) {\n completionParam.tool_calls = message.additional_kwargs.tool_calls;\n }\n if ((message as ToolMessage).tool_call_id != null) {\n completionParam.tool_call_id = (message as ToolMessage).tool_call_id;\n }\n }\n\n if (\n message.additional_kwargs.audio &&\n typeof message.additional_kwargs.audio === 'object' &&\n 'id' in message.additional_kwargs.audio\n ) {\n const audioMessage = {\n role: 'assistant',\n audio: {\n id: message.additional_kwargs.audio.id,\n },\n };\n return [completionParam, audioMessage] as OpenAICompletionParam[];\n }\n\n return completionParam as OpenAICompletionParam;\n });\n}\n\nconst _FUNCTION_CALL_IDS_MAP_KEY = '__openai_function_call_ids__';\n\nfunction _convertReasoningSummaryToOpenAIResponsesParams(\n reasoning: ChatOpenAIReasoningSummary\n): OpenAIClient.Responses.ResponseReasoningItem {\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.at(-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\nexport function _convertMessagesToOpenAIResponsesParams(\n messages: BaseMessage[],\n model?: string,\n zdrEnabled?: boolean\n): ResponsesInputItem[] {\n return messages.flatMap(\n (lcMsg): ResponsesInputItem | ResponsesInputItem[] => {\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: 'computer_screenshot' as const,\n image_url: toolMessage.content,\n };\n }\n\n if (Array.isArray(toolMessage.content)) {\n const oaiScreenshot = toolMessage.content.find(\n (i) => i.type === 'computer_screenshot'\n ) as { type: 'computer_screenshot'; image_url: string };\n\n if (oaiScreenshot) return oaiScreenshot;\n\n const lcImage = toolMessage.content.find(\n (i) => i.type === 'image_url'\n ) as MessageContentImageUrl;\n\n if (lcImage) {\n return {\n type: 'computer_screenshot' 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 return {\n type: 'computer_call_output',\n output,\n call_id: toolMessage.tool_call_id,\n };\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:\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 lcMsg.response_metadata.output != null &&\n Array.isArray(lcMsg.response_metadata.output) &&\n lcMsg.response_metadata.output.length > 0 &&\n lcMsg.response_metadata.output.every((item) => 'type' in item)\n ) {\n return lcMsg.response_metadata.output;\n }\n\n // otherwise, try to reconstruct the response from what we have\n\n const input: ResponsesInputItem[] = [];\n\n // reasoning items\n if (additional_kwargs.reasoning && !zdrEnabled) {\n const reasoningItem = _convertReasoningSummaryToOpenAIResponsesParams(\n additional_kwargs.reasoning\n );\n input.push(reasoningItem);\n }\n\n // ai content\n let { content } = lcMsg;\n if (additional_kwargs.refusal) {\n if (typeof content === 'string') {\n content = [{ type: 'output_text', text: content, annotations: [] }];\n }\n content = [\n ...content,\n { type: 'refusal', refusal: additional_kwargs.refusal },\n ];\n }\n\n input.push({\n type: 'message',\n role: 'assistant',\n ...(lcMsg.id && !zdrEnabled ? { id: lcMsg.id } : {}),\n content:\n typeof content === 'string'\n ? content\n : content.flatMap((item) => {\n if (item.type === 'text') {\n return {\n type: 'output_text',\n text: item.text,\n // @ts-expect-error TODO: add types for `annotations`\n annotations: item.annotations ?? [],\n };\n }\n\n if (item.type === 'output_text' || item.type === 'refusal') {\n return item;\n }\n\n return [];\n }),\n });\n\n const functionCallIds = additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY];\n\n if (isAIMessage(lcMsg) && !!lcMsg.tool_calls?.length) {\n input.push(\n ...lcMsg.tool_calls.map(\n (toolCall): ResponsesInputItem => ({\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 lcMsg.response_metadata.output as Array<ResponsesInputItem>\n ).length\n ? lcMsg.response_metadata.output\n : additional_kwargs.tool_outputs;\n\n const fallthroughCallTypes: ResponsesInputItem['type'][] = [\n 'computer_call',\n /** @ts-ignore */\n 'mcp_call',\n /** @ts-ignore */\n 'code_interpreter_call',\n /** @ts-ignore */\n 'image_generation_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.flatMap((item) => {\n if (item.type === 'mcp_approval_response') {\n messages.push({\n // @ts-ignore\n type: 'mcp_approval_response',\n approval_request_id: item.approval_request_id,\n approve: item.approve,\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 return {\n type: 'input_image',\n image_url:\n typeof item.image_url === 'string'\n ? item.image_url\n : item.image_url.url,\n detail:\n typeof item.image_url === 'string'\n ? 'auto'\n : item.image_url.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({ type: 'message', role, content });\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\nexport function isReasoningModel(model?: string) {\n return model != null && model && /^o\\d/.test(model);\n}\n\nfunction _convertOpenAIResponsesMessageToBaseMessage(\n response: ResponsesCreateInvoke | ResponsesParseInvoke\n): BaseMessage {\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: 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\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,\n };\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 } 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: response.usage,\n additional_kwargs,\n response_metadata,\n });\n}\n\nexport function _convertOpenAIResponsesDeltaToBaseMessageChunk(\n chunk: ResponseReturnStreamEvents\n) {\n const content: Record<string, unknown>[] = [];\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 const additional_kwargs: {\n [key: string]: unknown;\n reasoning?: Partial<ChatOpenAIReasoningSummary>;\n tool_outputs?: unknown[];\n } = {};\n let id: string | undefined;\n if (chunk.type === 'response.output_text.delta') {\n content.push({\n type: 'text',\n text: chunk.delta,\n index: chunk.content_index,\n });\n /** @ts-ignore */\n } else if (chunk.type === 'response.output_text_annotation.added') {\n content.push({\n type: 'text',\n text: '',\n /** @ts-ignore */\n annotations: [chunk.annotation],\n /** @ts-ignore */\n index: chunk.content_index,\n });\n } else if (\n chunk.type === 'response.output_item.added' &&\n chunk.item.type === 'message'\n ) {\n id = chunk.item.id;\n } else if (\n chunk.type === 'response.output_item.added' &&\n chunk.item.type === 'function_call'\n ) {\n tool_call_chunks.push({\n type: 'tool_call_chunk',\n name: chunk.item.name,\n args: chunk.item.arguments,\n id: chunk.item.call_id,\n index: chunk.output_index,\n });\n\n additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] = {\n [chunk.item.call_id]: chunk.item.id,\n };\n } else if (\n chunk.type === 'response.output_item.done' &&\n [\n 'web_search_call',\n 'file_search_call',\n 'computer_call',\n 'code_interpreter_call',\n 'mcp_call',\n 'mcp_list_tools',\n 'mcp_approval_request',\n 'image_generation_call',\n ].includes(chunk.item.type)\n ) {\n additional_kwargs.tool_outputs = [chunk.item];\n } else if (chunk.type === 'response.created') {\n response_metadata.id = chunk.response.id;\n response_metadata.model_name = chunk.response.model;\n response_metadata.model = chunk.response.model;\n } else if (chunk.type === 'response.completed') {\n const msg = _convertOpenAIResponsesMessageToBaseMessage(chunk.response);\n\n usage_metadata = chunk.response.usage;\n if (chunk.response.text?.format?.type === 'json_schema') {\n additional_kwargs.parsed ??= JSON.parse(msg.text);\n }\n for (const [key, value] of Object.entries(chunk.response)) {\n if (key !== 'id') response_metadata[key] = value;\n }\n } else if (chunk.type === 'response.function_call_arguments.delta') {\n tool_call_chunks.push({\n type: 'tool_call_chunk',\n args: chunk.delta,\n index: chunk.output_index,\n });\n } else if (\n chunk.type === 'response.web_search_call.completed' ||\n chunk.type === 'response.file_search_call.completed'\n ) {\n generationInfo = {\n tool_outputs: {\n id: chunk.item_id,\n type: chunk.type.replace('response.', '').replace('.completed', ''),\n status: 'completed',\n },\n };\n } else if (chunk.type === 'response.refusal.done') {\n additional_kwargs.refusal = chunk.refusal;\n } else if (\n chunk.type === 'response.output_item.added' &&\n 'item' in chunk &&\n chunk.item.type === 'reasoning'\n ) {\n const summary: ChatOpenAIReasoningSummary['summary'] | undefined = chunk\n .item.summary\n ? chunk.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 chunk or else the concatenated result of all chunks will\n // have an ID field that is repeated once per chunk. There is special handling for the `type`\n // field that prevents this, however.\n id: chunk.item.id,\n type: chunk.item.type,\n ...(summary ? { summary } : {}),\n };\n } else if (chunk.type === 'response.reasoning_summary_part.added') {\n additional_kwargs.reasoning = {\n type: 'reasoning',\n summary: [{ ...chunk.part, index: chunk.summary_index }],\n };\n } else if (chunk.type === 'response.reasoning_summary_text.delta') {\n additional_kwargs.reasoning = {\n type: 'reasoning',\n summary: [\n { text: chunk.delta, type: 'summary_text', index: chunk.summary_index },\n ],\n };\n /** @ts-ignore */\n } else if (chunk.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"],"names":[],"mappings":";;;;AA+EA,SAAS,+BAA+B,CAAC,OAAoB,EAAA;AAC3D,IAAA,IACE,OAAO,CAAC,IAAI,KAAK,QAAQ;QACzB,OAAO,CAAC,IAAI,KAAK,WAAW;QAC5B,OAAO,CAAC,IAAI,KAAK,WAAW;QAC5B,OAAO,CAAC,IAAI,KAAK,MAAM;QACvB,OAAO,CAAC,IAAI,KAAK,UAAU;AAC3B,QAAA,OAAO,CAAC,IAAI,KAAK,MAAM,EACvB;QACA,OAAO,CAAC,IAAI,CAAC,CAAA,sBAAA,EAAyB,OAAO,CAAC,IAAI,CAAE,CAAA,CAAC;;IAGvD,OAAO,OAAO,CAAC,IAAsB;AACvC;AAEM,SA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AE,WAAW;AACjB,YAAA,OAAO,EAAE;AACP,gBAAA,EAAE,IAAI,EAAE,KAAK,CAAC,KAAK,EAAE,IAAI,EAAE,cAAc,EAAE,KAAK,EAAE,KAAK,CAAC,aAAa,EAAE;AACxE,aAAA;SACF;;;AAEI,SAAA,IAAI,KAAK,CAAC,IAAI,KAAK,8CAA8C,EAAE;;;AAGxE,QAAA,OAAO,IAAI;;SACN;AACL,QAAA,OAAO,IAAI;;IAGb,OAAO,IAAI,mBAAmB,CAAC;;AAE7B,QAAA,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC;QAC/C,OAAO,EAAE,IAAI,cAAc,CAAC;YAC1B,EAAE;YACF,OAAO;YACP,gBAAgB;YAChB,cAAc;YACd,iBAAiB;YACjB,iBAAiB;SAClB,CAAC;QACF,cAAc;AACf,KAAA,CAAC;AACJ;;;;"}
1
+ {"version":3,"file":"index.mjs","sources":["../../../../../src/llm/openai/utils/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/ban-ts-comment */\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\nimport { type OpenAI as OpenAIClient } from 'openai';\nimport type {\n ChatCompletionContentPartText,\n ChatCompletionContentPartImage,\n ChatCompletionContentPartInputAudio,\n ChatCompletionContentPart,\n} from 'openai/resources/chat/completions';\nimport {\n AIMessage,\n AIMessageChunk,\n type BaseMessage,\n ChatMessage,\n ToolMessage,\n isAIMessage,\n type UsageMetadata,\n type BaseMessageFields,\n type MessageContent,\n type InvalidToolCall,\n type MessageContentImageUrl,\n StandardContentBlockConverter,\n parseBase64DataUrl,\n parseMimeType,\n convertToProviderContentBlock,\n isDataContentBlock,\n} from '@langchain/core/messages';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport {\n convertLangChainToolCallToOpenAI,\n makeInvalidToolCall,\n parseToolCall,\n} from '@langchain/core/output_parsers/openai_tools';\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type {\n OpenAICallOptions,\n OpenAIChatInput,\n ChatOpenAIReasoningSummary,\n} from '@langchain/openai';\n\nexport type { OpenAICallOptions, OpenAIChatInput };\n\n// Utility types to get hidden OpenAI response types\ntype ExtractAsyncIterableType<T> = T extends AsyncIterable<infer U> ? U : never;\ntype ExcludeController<T> = T extends { controller: unknown } ? never : T;\ntype ExcludeNonController<T> = T extends { controller: unknown } ? T : never;\n\ntype ResponsesCreate = OpenAIClient.Responses['create'];\ntype ResponsesParse = OpenAIClient.Responses['parse'];\n\ntype ResponsesInputItem = OpenAIClient.Responses.ResponseInputItem;\n\ntype ResponsesCreateInvoke = ExcludeController<\n Awaited<ReturnType<ResponsesCreate>>\n>;\n\ntype ResponsesParseInvoke = ExcludeController<\n Awaited<ReturnType<ResponsesParse>>\n>;\n\ntype ResponsesCreateStream = ExcludeNonController<\n Awaited<ReturnType<ResponsesCreate>>\n>;\n\nexport type ResponseReturnStreamEvents =\n ExtractAsyncIterableType<ResponsesCreateStream>;\n\n// TODO import from SDK when available\ntype OpenAIRoleEnum =\n | 'system'\n | 'developer'\n | 'assistant'\n | 'user'\n | 'function'\n | 'tool';\n\ntype OpenAICompletionParam =\n OpenAIClient.Chat.Completions.ChatCompletionMessageParam;\n\nfunction extractGenericMessageCustomRole(message: ChatMessage) {\n if (\n message.role !== 'system' &&\n message.role !== 'developer' &&\n message.role !== 'assistant' &&\n message.role !== 'user' &&\n message.role !== 'function' &&\n message.role !== 'tool'\n ) {\n console.warn(`Unknown message role: ${message.role}`);\n }\n\n return message.role as OpenAIRoleEnum;\n}\n\nexport function messageToOpenAIRole(message: BaseMessage): OpenAIRoleEnum {\n const type = message._getType();\n switch (type) {\n case 'system':\n return 'system';\n case 'ai':\n return 'assistant';\n case 'human':\n return 'user';\n case 'function':\n return 'function';\n case 'tool':\n return 'tool';\n case 'generic': {\n if (!ChatMessage.isInstance(message))\n throw new Error('Invalid generic chat message');\n return extractGenericMessageCustomRole(message);\n }\n default:\n throw new Error(`Unknown message type: ${type}`);\n }\n}\n\nconst completionsApiContentBlockConverter: StandardContentBlockConverter<{\n text: ChatCompletionContentPartText;\n image: ChatCompletionContentPartImage;\n audio: ChatCompletionContentPartInputAudio;\n file: ChatCompletionContentPart.File;\n}> = {\n providerName: 'ChatOpenAI',\n\n fromStandardTextBlock(block): ChatCompletionContentPartText {\n return { type: 'text', text: block.text };\n },\n\n fromStandardImageBlock(block): ChatCompletionContentPartImage {\n if (block.source_type === 'url') {\n return {\n type: 'image_url',\n image_url: {\n url: block.url,\n ...(block.metadata?.detail\n ? { detail: block.metadata.detail as 'auto' | 'low' | 'high' }\n : {}),\n },\n };\n }\n\n if (block.source_type === 'base64') {\n const url = `data:${block.mime_type ?? ''};base64,${block.data}`;\n return {\n type: 'image_url',\n image_url: {\n url,\n ...(block.metadata?.detail\n ? { detail: block.metadata.detail as 'auto' | 'low' | 'high' }\n : {}),\n },\n };\n }\n\n throw new Error(\n `Image content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`\n );\n },\n\n fromStandardAudioBlock(block): ChatCompletionContentPartInputAudio {\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (!data) {\n throw new Error(\n `URL audio blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`\n );\n }\n\n const rawMimeType = data.mime_type || block.mime_type || '';\n let mimeType: { type: string; subtype: string };\n\n try {\n mimeType = parseMimeType(rawMimeType);\n } catch {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n if (\n mimeType.type !== 'audio' ||\n (mimeType.subtype !== 'wav' && mimeType.subtype !== 'mp3')\n ) {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n return {\n type: 'input_audio',\n input_audio: {\n format: mimeType.subtype,\n data: data.data,\n },\n };\n }\n\n if (block.source_type === 'base64') {\n let mimeType: { type: string; subtype: string };\n\n try {\n mimeType = parseMimeType(block.mime_type ?? '');\n } catch {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n if (\n mimeType.type !== 'audio' ||\n (mimeType.subtype !== 'wav' && mimeType.subtype !== 'mp3')\n ) {\n throw new Error(\n `Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`\n );\n }\n\n return {\n type: 'input_audio',\n input_audio: {\n format: mimeType.subtype,\n data: block.data,\n },\n };\n }\n\n throw new Error(\n `Audio content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`\n );\n },\n\n fromStandardFileBlock(block): ChatCompletionContentPart.File {\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (!data) {\n throw new Error(\n `URL file blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`\n );\n }\n\n return {\n type: 'file',\n file: {\n file_data: block.url, // formatted as base64 data URL\n ...(block.metadata?.filename || block.metadata?.name\n ? {\n filename: (block.metadata.filename ||\n block.metadata.name) as string,\n }\n : {}),\n },\n };\n }\n\n if (block.source_type === 'base64') {\n return {\n type: 'file',\n file: {\n file_data: `data:${block.mime_type ?? ''};base64,${block.data}`,\n ...(block.metadata?.filename ||\n block.metadata?.name ||\n block.metadata?.title\n ? {\n filename: (block.metadata.filename ||\n block.metadata.name ||\n block.metadata.title) as string,\n }\n : {}),\n },\n };\n }\n\n if (block.source_type === 'id') {\n return {\n type: 'file',\n file: {\n file_id: block.id,\n },\n };\n }\n\n throw new Error(\n `File content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`\n );\n },\n};\n\n// Used in LangSmith, export is important here\nexport function _convertMessagesToOpenAIParams(\n messages: BaseMessage[],\n model?: string\n): OpenAICompletionParam[] {\n // TODO: Function messages do not support array content, fix cast\n return messages.flatMap((message) => {\n let role = messageToOpenAIRole(message);\n if (role === 'system' && isReasoningModel(model)) {\n role = 'developer';\n }\n\n const content =\n typeof message.content === 'string'\n ? message.content\n : message.content.map((m) => {\n if (isDataContentBlock(m)) {\n return convertToProviderContentBlock(\n m,\n completionsApiContentBlockConverter\n );\n }\n return m;\n });\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const completionParam: Record<string, any> = {\n role,\n content,\n };\n if (message.name != null) {\n completionParam.name = message.name;\n }\n if (message.additional_kwargs.function_call != null) {\n completionParam.function_call = message.additional_kwargs.function_call;\n completionParam.content = '';\n }\n if (isAIMessage(message) && !!message.tool_calls?.length) {\n completionParam.tool_calls = message.tool_calls.map(\n convertLangChainToolCallToOpenAI\n );\n completionParam.content = '';\n } else {\n if (message.additional_kwargs.tool_calls != null) {\n completionParam.tool_calls = message.additional_kwargs.tool_calls;\n }\n if ((message as ToolMessage).tool_call_id != null) {\n completionParam.tool_call_id = (message as ToolMessage).tool_call_id;\n }\n }\n\n if (\n message.additional_kwargs.audio &&\n typeof message.additional_kwargs.audio === 'object' &&\n 'id' in message.additional_kwargs.audio\n ) {\n const audioMessage = {\n role: 'assistant',\n audio: {\n id: message.additional_kwargs.audio.id,\n },\n };\n return [completionParam, audioMessage] as OpenAICompletionParam[];\n }\n\n return completionParam as OpenAICompletionParam;\n });\n}\n\nconst _FUNCTION_CALL_IDS_MAP_KEY = '__openai_function_call_ids__';\n\nfunction _convertReasoningSummaryToOpenAIResponsesParams(\n reasoning: ChatOpenAIReasoningSummary\n): OpenAIClient.Responses.ResponseReasoningItem {\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.at(-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\nexport function _convertMessagesToOpenAIResponsesParams(\n messages: BaseMessage[],\n model?: string,\n zdrEnabled?: boolean\n): ResponsesInputItem[] {\n return messages.flatMap(\n (lcMsg): ResponsesInputItem | ResponsesInputItem[] => {\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: 'computer_screenshot' as const,\n image_url: toolMessage.content,\n };\n }\n\n if (Array.isArray(toolMessage.content)) {\n const oaiScreenshot = toolMessage.content.find(\n (i) => i.type === 'computer_screenshot'\n ) as { type: 'computer_screenshot'; image_url: string };\n\n if (oaiScreenshot) return oaiScreenshot;\n\n const lcImage = toolMessage.content.find(\n (i) => i.type === 'image_url'\n ) as MessageContentImageUrl;\n\n if (lcImage) {\n return {\n type: 'computer_screenshot' 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 return {\n type: 'computer_call_output',\n output,\n call_id: toolMessage.tool_call_id,\n };\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:\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 lcMsg.response_metadata.output != null &&\n Array.isArray(lcMsg.response_metadata.output) &&\n lcMsg.response_metadata.output.length > 0 &&\n lcMsg.response_metadata.output.every((item) => 'type' in item)\n ) {\n return lcMsg.response_metadata.output;\n }\n\n // otherwise, try to reconstruct the response from what we have\n\n const input: ResponsesInputItem[] = [];\n\n // reasoning items\n if (additional_kwargs.reasoning && !zdrEnabled) {\n const reasoningItem = _convertReasoningSummaryToOpenAIResponsesParams(\n additional_kwargs.reasoning\n );\n input.push(reasoningItem);\n }\n\n // ai content\n let { content } = lcMsg;\n if (additional_kwargs.refusal) {\n if (typeof content === 'string') {\n content = [{ type: 'output_text', text: content, annotations: [] }];\n }\n content = [\n ...content,\n { type: 'refusal', refusal: additional_kwargs.refusal },\n ];\n }\n\n input.push({\n type: 'message',\n role: 'assistant',\n ...(lcMsg.id && !zdrEnabled ? { id: lcMsg.id } : {}),\n content:\n typeof content === 'string'\n ? content\n : content.flatMap((item) => {\n if (item.type === 'text') {\n return {\n type: 'output_text',\n text: item.text,\n // @ts-expect-error TODO: add types for `annotations`\n annotations: item.annotations ?? [],\n };\n }\n\n if (item.type === 'output_text' || item.type === 'refusal') {\n return item;\n }\n\n return [];\n }),\n });\n\n const functionCallIds = additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY];\n\n if (isAIMessage(lcMsg) && !!lcMsg.tool_calls?.length) {\n input.push(\n ...lcMsg.tool_calls.map(\n (toolCall): ResponsesInputItem => ({\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 ((\n lcMsg.response_metadata.output as\n | Array<ResponsesInputItem>\n | undefined\n )?.length ?? 0) > 0\n ? lcMsg.response_metadata.output\n : additional_kwargs.tool_outputs;\n\n const fallthroughCallTypes: ResponsesInputItem['type'][] = [\n 'computer_call',\n /** @ts-ignore */\n 'mcp_call',\n /** @ts-ignore */\n 'code_interpreter_call',\n /** @ts-ignore */\n 'image_generation_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.flatMap((item) => {\n if (item.type === 'mcp_approval_response') {\n messages.push({\n // @ts-ignore\n type: 'mcp_approval_response',\n approval_request_id: item.approval_request_id,\n approve: item.approve,\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 return {\n type: 'input_image',\n image_url:\n typeof item.image_url === 'string'\n ? item.image_url\n : item.image_url.url,\n detail:\n typeof item.image_url === 'string'\n ? 'auto'\n : item.image_url.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({ type: 'message', role, content });\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\nexport function isReasoningModel(model?: string) {\n return model != null && model && /^o\\d/.test(model);\n}\n\nfunction _convertOpenAIResponsesMessageToBaseMessage(\n response: ResponsesCreateInvoke | ResponsesParseInvoke\n): BaseMessage {\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: 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\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,\n };\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 } 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: response.usage,\n additional_kwargs,\n response_metadata,\n });\n}\n\nexport function _convertOpenAIResponsesDeltaToBaseMessageChunk(\n chunk: ResponseReturnStreamEvents\n) {\n const content: Record<string, unknown>[] = [];\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 const additional_kwargs: {\n [key: string]: unknown;\n reasoning?: Partial<ChatOpenAIReasoningSummary>;\n tool_outputs?: unknown[];\n } = {};\n let id: string | undefined;\n if (chunk.type === 'response.output_text.delta') {\n content.push({\n type: 'text',\n text: chunk.delta,\n index: chunk.content_index,\n });\n /** @ts-ignore */\n } else if (chunk.type === 'response.output_text_annotation.added') {\n content.push({\n type: 'text',\n text: '',\n /** @ts-ignore */\n annotations: [chunk.annotation],\n /** @ts-ignore */\n index: chunk.content_index,\n });\n } else if (\n chunk.type === 'response.output_item.added' &&\n chunk.item.type === 'message'\n ) {\n id = chunk.item.id;\n } else if (\n chunk.type === 'response.output_item.added' &&\n chunk.item.type === 'function_call'\n ) {\n tool_call_chunks.push({\n type: 'tool_call_chunk',\n name: chunk.item.name,\n args: chunk.item.arguments,\n id: chunk.item.call_id,\n index: chunk.output_index,\n });\n\n additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] = {\n [chunk.item.call_id]: chunk.item.id,\n };\n } else if (\n chunk.type === 'response.output_item.done' &&\n [\n 'web_search_call',\n 'file_search_call',\n 'computer_call',\n 'code_interpreter_call',\n 'mcp_call',\n 'mcp_list_tools',\n 'mcp_approval_request',\n 'image_generation_call',\n ].includes(chunk.item.type)\n ) {\n additional_kwargs.tool_outputs = [chunk.item];\n } else if (chunk.type === 'response.created') {\n response_metadata.id = chunk.response.id;\n response_metadata.model_name = chunk.response.model;\n response_metadata.model = chunk.response.model;\n } else if (chunk.type === 'response.completed') {\n const msg = _convertOpenAIResponsesMessageToBaseMessage(chunk.response);\n\n usage_metadata = chunk.response.usage;\n if (chunk.response.text?.format?.type === 'json_schema') {\n additional_kwargs.parsed ??= JSON.parse(msg.text);\n }\n for (const [key, value] of Object.entries(chunk.response)) {\n if (key !== 'id') response_metadata[key] = value;\n }\n } else if (chunk.type === 'response.function_call_arguments.delta') {\n tool_call_chunks.push({\n type: 'tool_call_chunk',\n args: chunk.delta,\n index: chunk.output_index,\n });\n } else if (\n chunk.type === 'response.web_search_call.completed' ||\n chunk.type === 'response.file_search_call.completed'\n ) {\n generationInfo = {\n tool_outputs: {\n id: chunk.item_id,\n type: chunk.type.replace('response.', '').replace('.completed', ''),\n status: 'completed',\n },\n };\n } else if (chunk.type === 'response.refusal.done') {\n additional_kwargs.refusal = chunk.refusal;\n } else if (\n chunk.type === 'response.output_item.added' &&\n 'item' in chunk &&\n chunk.item.type === 'reasoning'\n ) {\n const summary: ChatOpenAIReasoningSummary['summary'] | undefined = chunk\n .item.summary\n ? chunk.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 chunk or else the concatenated result of all chunks will\n // have an ID field that is repeated once per chunk. There is special handling for the `type`\n // field that prevents this, however.\n id: chunk.item.id,\n type: chunk.item.type,\n ...(summary ? { summary } : {}),\n };\n } else if (chunk.type === 'response.reasoning_summary_part.added') {\n additional_kwargs.reasoning = {\n type: 'reasoning',\n summary: [{ ...chunk.part, index: chunk.summary_index }],\n };\n } else if (chunk.type === 'response.reasoning_summary_text.delta') {\n additional_kwargs.reasoning = {\n type: 'reasoning',\n summary: [\n { text: chunk.delta, type: 'summary_text', index: chunk.summary_index },\n ],\n };\n /** @ts-ignore */\n } else if (chunk.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"],"names":[],"mappings":";;;;AA+EA,SAAS,+BAA+B,CAAC,OAAoB,EAAA;AAC3D,IAAA,IACE,OAAO,CAAC,IAAI,KAAK,QAAQ;QACzB,OAAO,CAAC,IAAI,KAAK,WAAW;QAC5B,OAAO,CAAC,IAAI,KAAK,WAAW;QAC5B,OAAO,CAAC,IAAI,KAAK,MAAM;QACvB,OAAO,CAAC,IAAI,KAAK,UAAU;AAC3B,QAAA,OAAO,CAAC,IAAI,KAAK,MAAM,EACvB;QACA,OAAO,CAAC,IAAI,CAAC,CAAA,sBAAA,EAAyB,OAAO,CAAC,IAAI,CAAE,CAAA,CAAC;;IAGvD,OAAO,OAAO,CAAC,IAAsB;AACvC;AAEM,SAAU,mBAAmB,CAAC,OAAoB,EAAA;AACtD,IAAA,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,EAAE;IAC/B,QAAQ,IAAI;AACZ,QAAA,KAAK,QAAQ;AACX,YAAA,OAAO,QAAQ;AACjB,QAAA,KAAK,IAAI;AACP,YAAA,OAAO,WAAW;AACpB,QAAA,KAAK,OAAO;AACV,YAAA,OAAO,MAAM;AACf,QAAA,KAAK,UAAU;AACb,YAAA,OAAO,UAAU;AACnB,QAAA,KAAK,MAAM;AACT,YAAA,OAAO,MAAM;QACf,KAAK,SAAS,EAAE;AACd,YAAA,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,OAAO,CAAC;AAClC,gBAAA,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC;AACjD,YAAA,OAAO,+BAA+B,CAAC,OAAO,CAAC;;AAEjD,QAAA;AACE,YAAA,MAAM,IAAI,KAAK,CAAC,yBAAyB,IAAI,CAAA,CAAE,CAAC;;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F,cAAc;AACf,KAAA,CAAC;AACJ;;;;"}
@@ -1,4 +1,4 @@
1
- import { StepTypes, ContentTypes, GraphEvents, ToolCallTypes } from './common/enum.mjs';
1
+ import { StepTypes, ContentTypes, Providers, GraphEvents, ToolCallTypes } from './common/enum.mjs';
2
2
  import { handleToolCalls, handleToolCallChunks } from './tools/handlers.mjs';
3
3
  import './messages/core.mjs';
4
4
  import { getMessageId } from './messages/ids.mjs';
@@ -51,6 +51,15 @@ function getNonEmptyValue(possibleValues) {
51
51
  }
52
52
  return undefined;
53
53
  }
54
+ function getChunkContent({ chunk, provider, reasoningKey, }) {
55
+ if ((provider === Providers.OPENAI || provider === Providers.AZURE) &&
56
+ chunk?.additional_kwargs?.reasoning?.summary?.[0]?.text != null &&
57
+ (chunk?.additional_kwargs?.reasoning?.summary?.[0]?.text?.length ?? 0) > 0) {
58
+ return chunk?.additional_kwargs?.reasoning?.summary?.[0]?.text;
59
+ }
60
+ return (chunk?.additional_kwargs?.[reasoningKey] ??
61
+ chunk?.content);
62
+ }
54
63
  class ChatModelStreamHandler {
55
64
  handle(event, data, metadata, graph) {
56
65
  if (!graph) {
@@ -64,9 +73,12 @@ class ChatModelStreamHandler {
64
73
  return;
65
74
  }
66
75
  const chunk = data.chunk;
67
- const content = chunk.additional_kwargs?.[graph.reasoningKey] ??
68
- chunk.content;
69
- this.handleReasoning(chunk, graph);
76
+ const content = getChunkContent({
77
+ chunk,
78
+ reasoningKey: graph.reasoningKey,
79
+ provider: metadata?.provider,
80
+ });
81
+ this.handleReasoning(chunk, graph, metadata?.provider);
70
82
  let hasToolCalls = false;
71
83
  if (chunk.tool_calls &&
72
84
  chunk.tool_calls.length > 0 &&
@@ -220,7 +232,7 @@ hasToolCallChunks: ${hasToolCallChunks}
220
232
  });
221
233
  }
222
234
  }
223
- handleReasoning(chunk, graph) {
235
+ handleReasoning(chunk, graph, provider) {
224
236
  let reasoning_content = chunk.additional_kwargs?.[graph.reasoningKey];
225
237
  if (Array.isArray(chunk.content) &&
226
238
  (chunk.content[0]?.type === ContentTypes.THINKING ||
@@ -228,8 +240,15 @@ hasToolCallChunks: ${hasToolCallChunks}
228
240
  chunk.content[0]?.type === ContentTypes.REASONING_CONTENT)) {
229
241
  reasoning_content = 'valid';
230
242
  }
243
+ else if ((provider === Providers.OPENAI || provider === Providers.AZURE) &&
244
+ reasoning_content != null &&
245
+ typeof reasoning_content !== 'string' &&
246
+ reasoning_content.summary?.[0]?.text != null &&
247
+ reasoning_content.summary[0].text) {
248
+ reasoning_content = 'valid';
249
+ }
231
250
  if (reasoning_content != null &&
232
- reasoning_content &&
251
+ reasoning_content !== '' &&
233
252
  (chunk.content == null ||
234
253
  chunk.content === '' ||
235
254
  reasoning_content === 'valid')) {
@@ -1 +1 @@
1
- {"version":3,"file":"stream.mjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\nimport { StepTypes, ContentTypes, GraphEvents, ToolCallTypes } from '@/common';\nimport { handleToolCalls, handleToolCallChunks } from '@/tools/handlers';\nimport { getMessageId } from '@/messages';\n\n/**\n * Parses content to extract thinking sections enclosed in <think> tags using string operations\n * @param content The content to parse\n * @returns An object with separated text and thinking content\n */\nfunction parseThinkingContent(content: string): {\n text: string;\n thinking: string;\n} {\n // If no think tags, return the original content as text\n if (!content.includes('<think>')) {\n return { text: content, thinking: '' };\n }\n\n let textResult = '';\n const thinkingResult: string[] = [];\n let position = 0;\n\n while (position < content.length) {\n const thinkStart = content.indexOf('<think>', position);\n\n if (thinkStart === -1) {\n // No more think tags, add the rest and break\n textResult += content.slice(position);\n break;\n }\n\n // Add text before the think tag\n textResult += content.slice(position, thinkStart);\n\n const thinkEnd = content.indexOf('</think>', thinkStart);\n if (thinkEnd === -1) {\n // Malformed input, no closing tag\n textResult += content.slice(thinkStart);\n break;\n }\n\n // Add the thinking content\n const thinkContent = content.slice(thinkStart + 7, thinkEnd);\n thinkingResult.push(thinkContent);\n\n // Move position to after the think tag\n position = thinkEnd + 8; // 8 is the length of '</think>'\n }\n\n return {\n text: textResult.trim(),\n thinking: thinkingResult.join('\\n').trim(),\n };\n}\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: Graph\n ): void {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content =\n (chunk.additional_kwargs?.[graph.reasoningKey] as string | undefined) ??\n chunk.content;\n this.handleReasoning(chunk, graph);\n\n let hasToolCalls = false;\n if (\n chunk.tool_calls &&\n chunk.tool_calls.length > 0 &&\n chunk.tool_calls.every((tc) => tc.id != null && tc.id !== '')\n ) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent =\n typeof content === 'undefined' ||\n !content.length ||\n (typeof content === 'string' && !content);\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n const chunkId = chunk.id ?? '';\n if (isEmptyChunk && chunkId && chunkId.startsWith('msg')) {\n if (graph.messageIdsByStepKey.has(chunkId)) {\n return;\n } else if (graph.prelimMessageIdsByStepKey.has(chunkId)) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunkId);\n return;\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (\n hasToolCallChunks &&\n chunk.tool_call_chunks &&\n chunk.tool_call_chunks.length &&\n typeof chunk.tool_call_chunks[0]?.index === 'number'\n ) {\n handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (graph.currentTokenType === ContentTypes.TEXT) {\n graph.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n } else if (graph.currentTokenType === 'think_and_text') {\n const { text, thinking } = parseThinkingContent(content);\n if (thinking) {\n graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: thinking,\n },\n ],\n });\n }\n if (text) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n const newStepKey = graph.getStepKey(metadata);\n const message_id = getMessageId(newStepKey, graph) ?? '';\n graph.dispatchRunStep(newStepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n\n const newStepId = graph.getStepIdByKey(newStepKey);\n graph.dispatchMessageDelta(newStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: text,\n },\n ],\n });\n }\n } else {\n graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n }\n } else if (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false)\n )\n ) {\n graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think:\n (c as t.ThinkingContentText).thinking ??\n (c as Partial<t.GoogleReasoningContentText>).reasoning ??\n (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ??\n '',\n })),\n });\n }\n }\n handleReasoning(chunk: Partial<AIMessageChunk>, graph: Graph): void {\n let reasoning_content = chunk.additional_kwargs?.[graph.reasoningKey] as\n | string\n | undefined;\n if (\n Array.isArray(chunk.content) &&\n (chunk.content[0]?.type === ContentTypes.THINKING ||\n chunk.content[0]?.type === ContentTypes.REASONING ||\n chunk.content[0]?.type === ContentTypes.REASONING_CONTENT)\n ) {\n reasoning_content = 'valid';\n }\n if (\n reasoning_content != null &&\n reasoning_content &&\n (chunk.content == null ||\n chunk.content === '' ||\n reasoning_content === 'valid')\n ) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'reasoning';\n return;\n } else if (\n graph.tokenTypeSwitch === 'reasoning' &&\n graph.currentTokenType !== ContentTypes.TEXT &&\n ((chunk.content != null && chunk.content !== '') ||\n (chunk.tool_calls?.length ?? 0) > 0)\n ) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>') &&\n chunk.content.includes('</think>')\n ) {\n graph.currentTokenType = 'think_and_text';\n graph.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>')\n ) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'content';\n } else if (\n graph.lastToken != null &&\n graph.lastToken.includes('</think>')\n ) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n graph.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart: t.MessageContentComplex,\n finalUpdate = false\n ): void => {\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (\n partType === ContentTypes.IMAGE_URL &&\n 'image_url' in contentPart\n ) {\n const currentContent = contentParts[index] as {\n type: 'image_url';\n image_url: string;\n };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (\n partType === ContentTypes.TOOL_CALL &&\n 'tool_call' in contentPart\n ) {\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart;\n })\n | undefined;\n\n const toolCallArgs = (contentPart.tool_call as t.ToolCallPart).args;\n /** When args are a valid object, they are likely already invoked */\n const args =\n finalUpdate ||\n typeof existingContent?.tool_call?.args === 'object' ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args ?? '') + (toolCallArgs ?? '');\n\n const id =\n getNonEmptyValue([\n contentPart.tool_call.id,\n existingContent?.tool_call?.id,\n ]) ?? '';\n const name =\n getNonEmptyValue([\n contentPart.tool_call.name,\n existingContent?.tool_call?.name,\n ]) ?? '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.RunStepDeltaEvent\n | { result: t.ToolEndEvent };\n }): void => {\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n (runStep.stepDetails.tool_calls as ToolCall[]).forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate;\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn(\n 'No run step or runId found for completed tool call event'\n );\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":[],"mappings":";;;;;;AASA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAe,EAAA;;IAK3C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAChC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE;;IAGxC,IAAI,UAAU,GAAG,EAAE;IACnB,MAAM,cAAc,GAAa,EAAE;IACnC,IAAI,QAAQ,GAAG,CAAC;AAEhB,IAAA,OAAO,QAAQ,GAAG,OAAO,CAAC,MAAM,EAAE;QAChC,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC;AAEvD,QAAA,IAAI,UAAU,KAAK,EAAE,EAAE;;AAErB,YAAA,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC;YACrC;;;QAIF,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,UAAU,CAAC;QAEjD,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,UAAU,EAAE,UAAU,CAAC;AACxD,QAAA,IAAI,QAAQ,KAAK,EAAE,EAAE;;AAEnB,YAAA,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,UAAU,CA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":"stream.mjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type { ChatOpenAIReasoningSummary } from '@langchain/openai';\nimport type * as t from '@/types';\nimport {\n StepTypes,\n ContentTypes,\n GraphEvents,\n ToolCallTypes,\n Providers,\n} from '@/common';\nimport { handleToolCalls, handleToolCallChunks } from '@/tools/handlers';\nimport { getMessageId } from '@/messages';\n\n/**\n * Parses content to extract thinking sections enclosed in <think> tags using string operations\n * @param content The content to parse\n * @returns An object with separated text and thinking content\n */\nfunction parseThinkingContent(content: string): {\n text: string;\n thinking: string;\n} {\n // If no think tags, return the original content as text\n if (!content.includes('<think>')) {\n return { text: content, thinking: '' };\n }\n\n let textResult = '';\n const thinkingResult: string[] = [];\n let position = 0;\n\n while (position < content.length) {\n const thinkStart = content.indexOf('<think>', position);\n\n if (thinkStart === -1) {\n // No more think tags, add the rest and break\n textResult += content.slice(position);\n break;\n }\n\n // Add text before the think tag\n textResult += content.slice(position, thinkStart);\n\n const thinkEnd = content.indexOf('</think>', thinkStart);\n if (thinkEnd === -1) {\n // Malformed input, no closing tag\n textResult += content.slice(thinkStart);\n break;\n }\n\n // Add the thinking content\n const thinkContent = content.slice(thinkStart + 7, thinkEnd);\n thinkingResult.push(thinkContent);\n\n // Move position to after the think tag\n position = thinkEnd + 8; // 8 is the length of '</think>'\n }\n\n return {\n text: textResult.trim(),\n thinking: thinkingResult.join('\\n').trim(),\n };\n}\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nfunction getChunkContent({\n chunk,\n provider,\n reasoningKey,\n}: {\n chunk?: Partial<AIMessageChunk>;\n provider?: Providers;\n reasoningKey: 'reasoning_content' | 'reasoning';\n}): string | t.MessageContentComplex[] | undefined {\n if (\n (provider === Providers.OPENAI || provider === Providers.AZURE) &&\n (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text != null &&\n ((\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text?.length ?? 0) > 0\n ) {\n return (\n chunk?.additional_kwargs?.reasoning as\n | Partial<ChatOpenAIReasoningSummary>\n | undefined\n )?.summary?.[0]?.text;\n }\n return (\n (chunk?.additional_kwargs?.[reasoningKey] as string | undefined) ??\n chunk?.content\n );\n}\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: Graph\n ): void {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content = getChunkContent({\n chunk,\n reasoningKey: graph.reasoningKey,\n provider: metadata?.provider as Providers,\n });\n this.handleReasoning(chunk, graph, metadata?.provider as Providers);\n\n let hasToolCalls = false;\n if (\n chunk.tool_calls &&\n chunk.tool_calls.length > 0 &&\n chunk.tool_calls.every((tc) => tc.id != null && tc.id !== '')\n ) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent =\n typeof content === 'undefined' ||\n !content.length ||\n (typeof content === 'string' && !content);\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n const chunkId = chunk.id ?? '';\n if (isEmptyChunk && chunkId && chunkId.startsWith('msg')) {\n if (graph.messageIdsByStepKey.has(chunkId)) {\n return;\n } else if (graph.prelimMessageIdsByStepKey.has(chunkId)) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunkId);\n return;\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (\n hasToolCallChunks &&\n chunk.tool_call_chunks &&\n chunk.tool_call_chunks.length &&\n typeof chunk.tool_call_chunks[0]?.index === 'number'\n ) {\n handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (graph.currentTokenType === ContentTypes.TEXT) {\n graph.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n } else if (graph.currentTokenType === 'think_and_text') {\n const { text, thinking } = parseThinkingContent(content);\n if (thinking) {\n graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: thinking,\n },\n ],\n });\n }\n if (text) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n const newStepKey = graph.getStepKey(metadata);\n const message_id = getMessageId(newStepKey, graph) ?? '';\n graph.dispatchRunStep(newStepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n\n const newStepId = graph.getStepIdByKey(newStepKey);\n graph.dispatchMessageDelta(newStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: text,\n },\n ],\n });\n }\n } else {\n graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n }\n } else if (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false)\n )\n ) {\n graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think:\n (c as t.ThinkingContentText).thinking ??\n (c as Partial<t.GoogleReasoningContentText>).reasoning ??\n (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ??\n '',\n })),\n });\n }\n }\n handleReasoning(\n chunk: Partial<AIMessageChunk>,\n graph: Graph,\n provider?: Providers\n ): void {\n let reasoning_content = chunk.additional_kwargs?.[graph.reasoningKey] as\n | string\n | Partial<ChatOpenAIReasoningSummary>\n | undefined;\n if (\n Array.isArray(chunk.content) &&\n (chunk.content[0]?.type === ContentTypes.THINKING ||\n chunk.content[0]?.type === ContentTypes.REASONING ||\n chunk.content[0]?.type === ContentTypes.REASONING_CONTENT)\n ) {\n reasoning_content = 'valid';\n } else if (\n (provider === Providers.OPENAI || provider === Providers.AZURE) &&\n reasoning_content != null &&\n typeof reasoning_content !== 'string' &&\n reasoning_content.summary?.[0]?.text != null &&\n reasoning_content.summary[0].text\n ) {\n reasoning_content = 'valid';\n }\n if (\n reasoning_content != null &&\n reasoning_content !== '' &&\n (chunk.content == null ||\n chunk.content === '' ||\n reasoning_content === 'valid')\n ) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'reasoning';\n return;\n } else if (\n graph.tokenTypeSwitch === 'reasoning' &&\n graph.currentTokenType !== ContentTypes.TEXT &&\n ((chunk.content != null && chunk.content !== '') ||\n (chunk.tool_calls?.length ?? 0) > 0)\n ) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>') &&\n chunk.content.includes('</think>')\n ) {\n graph.currentTokenType = 'think_and_text';\n graph.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>')\n ) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'content';\n } else if (\n graph.lastToken != null &&\n graph.lastToken.includes('</think>')\n ) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n graph.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart: t.MessageContentComplex,\n finalUpdate = false\n ): void => {\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (\n partType === ContentTypes.IMAGE_URL &&\n 'image_url' in contentPart\n ) {\n const currentContent = contentParts[index] as {\n type: 'image_url';\n image_url: string;\n };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (\n partType === ContentTypes.TOOL_CALL &&\n 'tool_call' in contentPart\n ) {\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart;\n })\n | undefined;\n\n const toolCallArgs = (contentPart.tool_call as t.ToolCallPart).args;\n /** When args are a valid object, they are likely already invoked */\n const args =\n finalUpdate ||\n typeof existingContent?.tool_call?.args === 'object' ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args ?? '') + (toolCallArgs ?? '');\n\n const id =\n getNonEmptyValue([\n contentPart.tool_call.id,\n existingContent?.tool_call?.id,\n ]) ?? '';\n const name =\n getNonEmptyValue([\n contentPart.tool_call.name,\n existingContent?.tool_call?.name,\n ]) ?? '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.RunStepDeltaEvent\n | { result: t.ToolEndEvent };\n }): void => {\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n (runStep.stepDetails.tool_calls as ToolCall[]).forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate;\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn(\n 'No run step or runId found for completed tool call event'\n );\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":[],"mappings":";;;;;;AAgBA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAe,EAAA;;IAK3C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAChC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE;;IAGxC,IAAI,UAAU,GAAG,EAAE;IACnB,MAAM,cAAc,GAAa,EAAE;IACnC,IAAI,QAAQ,GAAG,CAAC;AAEhB,IAAA,OAAO,QAAQ,GAAG,OAAO,CAAC,MAAM,EAAE;QAChC,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC;AAEvD,QAAA,IAAI,UAAU,KAAK,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;AAED,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE;AACpD;;;;"}
@@ -1,8 +1,9 @@
1
1
  import type { AIMessageChunk } from '@langchain/core/messages';
2
2
  import type { Graph } from '@/graphs';
3
3
  import type * as t from '@/types';
4
+ import { Providers } from '@/common';
4
5
  export declare class ChatModelStreamHandler implements t.EventHandler {
5
6
  handle(event: string, data: t.StreamEventData, metadata?: Record<string, unknown>, graph?: Graph): void;
6
- handleReasoning(chunk: Partial<AIMessageChunk>, graph: Graph): void;
7
+ handleReasoning(chunk: Partial<AIMessageChunk>, graph: Graph, provider?: Providers): void;
7
8
  }
8
9
  export declare function createContentAggregator(): t.ContentAggregatorResult;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@librechat/agents",
3
- "version": "2.4.47",
3
+ "version": "2.4.49",
4
4
  "main": "./dist/cjs/main.cjs",
5
5
  "module": "./dist/esm/main.mjs",
6
6
  "types": "./dist/types/index.d.ts",
@@ -47,7 +47,7 @@
47
47
  "image": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/image.ts --provider 'google' --name 'Jo' --location 'New York, NY'",
48
48
  "code_exec_files": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/code_exec_files.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
49
49
  "code_exec_simple": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/code_exec_simple.ts --provider 'google' --name 'Jo' --location 'New York, NY'",
50
- "simple": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/simple.ts --provider 'google' --name 'Jo' --location 'New York, NY'",
50
+ "simple": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/simple.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
51
51
  "caching": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/caching.ts --name 'Jo' --location 'New York, NY'",
52
52
  "thinking": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/thinking.ts --name 'Jo' --location 'New York, NY'",
53
53
  "memory": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/memory.ts --provider 'openAI' --name 'Jo' --location 'New York, NY'",
@@ -553,11 +553,14 @@ export function _convertMessagesToOpenAIResponsesParams(
553
553
  );
554
554
  }
555
555
 
556
- const toolOutputs = (
557
- lcMsg.response_metadata.output as Array<ResponsesInputItem>
558
- ).length
559
- ? lcMsg.response_metadata.output
560
- : additional_kwargs.tool_outputs;
556
+ const toolOutputs =
557
+ ((
558
+ lcMsg.response_metadata.output as
559
+ | Array<ResponsesInputItem>
560
+ | undefined
561
+ )?.length ?? 0) > 0
562
+ ? lcMsg.response_metadata.output
563
+ : additional_kwargs.tool_outputs;
561
564
 
562
565
  const fallthroughCallTypes: ResponsesInputItem['type'][] = [
563
566
  'computer_call',
package/src/stream.ts CHANGED
@@ -2,8 +2,15 @@
2
2
  import type { AIMessageChunk } from '@langchain/core/messages';
3
3
  import type { ToolCall } from '@langchain/core/messages/tool';
4
4
  import type { Graph } from '@/graphs';
5
+ import type { ChatOpenAIReasoningSummary } from '@langchain/openai';
5
6
  import type * as t from '@/types';
6
- import { StepTypes, ContentTypes, GraphEvents, ToolCallTypes } from '@/common';
7
+ import {
8
+ StepTypes,
9
+ ContentTypes,
10
+ GraphEvents,
11
+ ToolCallTypes,
12
+ Providers,
13
+ } from '@/common';
7
14
  import { handleToolCalls, handleToolCallChunks } from '@/tools/handlers';
8
15
  import { getMessageId } from '@/messages';
9
16
 
@@ -66,6 +73,41 @@ function getNonEmptyValue(possibleValues: string[]): string | undefined {
66
73
  }
67
74
  return undefined;
68
75
  }
76
+
77
+ function getChunkContent({
78
+ chunk,
79
+ provider,
80
+ reasoningKey,
81
+ }: {
82
+ chunk?: Partial<AIMessageChunk>;
83
+ provider?: Providers;
84
+ reasoningKey: 'reasoning_content' | 'reasoning';
85
+ }): string | t.MessageContentComplex[] | undefined {
86
+ if (
87
+ (provider === Providers.OPENAI || provider === Providers.AZURE) &&
88
+ (
89
+ chunk?.additional_kwargs?.reasoning as
90
+ | Partial<ChatOpenAIReasoningSummary>
91
+ | undefined
92
+ )?.summary?.[0]?.text != null &&
93
+ ((
94
+ chunk?.additional_kwargs?.reasoning as
95
+ | Partial<ChatOpenAIReasoningSummary>
96
+ | undefined
97
+ )?.summary?.[0]?.text?.length ?? 0) > 0
98
+ ) {
99
+ return (
100
+ chunk?.additional_kwargs?.reasoning as
101
+ | Partial<ChatOpenAIReasoningSummary>
102
+ | undefined
103
+ )?.summary?.[0]?.text;
104
+ }
105
+ return (
106
+ (chunk?.additional_kwargs?.[reasoningKey] as string | undefined) ??
107
+ chunk?.content
108
+ );
109
+ }
110
+
69
111
  export class ChatModelStreamHandler implements t.EventHandler {
70
112
  handle(
71
113
  event: string,
@@ -85,10 +127,12 @@ export class ChatModelStreamHandler implements t.EventHandler {
85
127
  }
86
128
 
87
129
  const chunk = data.chunk as Partial<AIMessageChunk>;
88
- const content =
89
- (chunk.additional_kwargs?.[graph.reasoningKey] as string | undefined) ??
90
- chunk.content;
91
- this.handleReasoning(chunk, graph);
130
+ const content = getChunkContent({
131
+ chunk,
132
+ reasoningKey: graph.reasoningKey,
133
+ provider: metadata?.provider as Providers,
134
+ });
135
+ this.handleReasoning(chunk, graph, metadata?.provider as Providers);
92
136
 
93
137
  let hasToolCalls = false;
94
138
  if (
@@ -260,9 +304,14 @@ hasToolCallChunks: ${hasToolCallChunks}
260
304
  });
261
305
  }
262
306
  }
263
- handleReasoning(chunk: Partial<AIMessageChunk>, graph: Graph): void {
307
+ handleReasoning(
308
+ chunk: Partial<AIMessageChunk>,
309
+ graph: Graph,
310
+ provider?: Providers
311
+ ): void {
264
312
  let reasoning_content = chunk.additional_kwargs?.[graph.reasoningKey] as
265
313
  | string
314
+ | Partial<ChatOpenAIReasoningSummary>
266
315
  | undefined;
267
316
  if (
268
317
  Array.isArray(chunk.content) &&
@@ -271,10 +320,18 @@ hasToolCallChunks: ${hasToolCallChunks}
271
320
  chunk.content[0]?.type === ContentTypes.REASONING_CONTENT)
272
321
  ) {
273
322
  reasoning_content = 'valid';
323
+ } else if (
324
+ (provider === Providers.OPENAI || provider === Providers.AZURE) &&
325
+ reasoning_content != null &&
326
+ typeof reasoning_content !== 'string' &&
327
+ reasoning_content.summary?.[0]?.text != null &&
328
+ reasoning_content.summary[0].text
329
+ ) {
330
+ reasoning_content = 'valid';
274
331
  }
275
332
  if (
276
333
  reasoning_content != null &&
277
- reasoning_content &&
334
+ reasoning_content !== '' &&
278
335
  (chunk.content == null ||
279
336
  chunk.content === '' ||
280
337
  reasoning_content === 'valid')