@librechat/agents 2.4.54 → 2.4.56
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/llm/openai/index.cjs +106 -2
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/utils/index.cjs +55 -0
- package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
- package/dist/cjs/stream.cjs +6 -1
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/handlers.cjs +1 -1
- package/dist/cjs/tools/handlers.cjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +107 -3
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/llm/openai/utils/index.mjs +56 -2
- package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
- package/dist/esm/stream.mjs +6 -1
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/handlers.mjs +1 -1
- package/dist/esm/tools/handlers.mjs.map +1 -1
- package/dist/types/llm/openai/index.d.ts +3 -2
- package/package.json +1 -1
- package/src/llm/openai/index.ts +145 -5
- package/src/stream.ts +8 -1
- package/src/tools/handlers.ts +2 -2
|
@@ -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 ((\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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C,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,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AI,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;;;;"}
|
package/dist/esm/stream.mjs
CHANGED
|
@@ -357,11 +357,16 @@ function createContentAggregator() {
|
|
|
357
357
|
const existingContent = contentParts[index];
|
|
358
358
|
const toolCallArgs = contentPart.tool_call.args;
|
|
359
359
|
/** When args are a valid object, they are likely already invoked */
|
|
360
|
-
|
|
360
|
+
let args = finalUpdate ||
|
|
361
361
|
typeof existingContent?.tool_call?.args === 'object' ||
|
|
362
362
|
typeof toolCallArgs === 'object'
|
|
363
363
|
? contentPart.tool_call.args
|
|
364
364
|
: (existingContent?.tool_call?.args ?? '') + (toolCallArgs ?? '');
|
|
365
|
+
if (finalUpdate &&
|
|
366
|
+
args == null &&
|
|
367
|
+
existingContent?.tool_call?.args != null) {
|
|
368
|
+
args = existingContent.tool_call.args;
|
|
369
|
+
}
|
|
365
370
|
const id = getNonEmptyValue([
|
|
366
371
|
contentPart.tool_call.id,
|
|
367
372
|
existingContent?.tool_call?.id,
|
package/dist/esm/stream.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.mjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { ChatOpenAIReasoningSummary } from '@langchain/openai';\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 {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n} from '@/common';\nimport {\n handleServerToolResult,\n handleToolCallChunks,\n handleToolCalls,\n} 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 const skipHandling = handleServerToolResult({\n content,\n metadata,\n graph,\n });\n if (skipHandling) {\n return;\n }\n this.handleReasoning(chunk, graph, metadata?.provider as Providers);\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":";;;;;;AAoBA;;;;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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ChatOpenAIReasoningSummary } from '@langchain/openai';\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 {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n} from '@/common';\nimport {\n handleServerToolResult,\n handleToolCallChunks,\n handleToolCalls,\n} 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 const skipHandling = handleServerToolResult({\n content,\n metadata,\n graph,\n });\n if (skipHandling) {\n return;\n }\n this.handleReasoning(chunk, graph, metadata?.provider as Providers);\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 let 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 if (\n finalUpdate &&\n args == null &&\n existingContent?.tool_call?.args != null\n ) {\n args = existingContent.tool_call.args;\n }\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":";;;;;;AAoBA;;;;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;QACh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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,EAAE,YAAY,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;;;;"}
|
|
@@ -217,7 +217,7 @@ function handleAnthropicSearchResults({ contentPart, toolCall, metadata, graph,
|
|
|
217
217
|
results: contentPart.content,
|
|
218
218
|
});
|
|
219
219
|
const name = toolCall.name;
|
|
220
|
-
const input = toolCall.args;
|
|
220
|
+
const input = toolCall.args ?? {};
|
|
221
221
|
const artifact = {
|
|
222
222
|
[Constants.WEB_SEARCH]: searchResultData,
|
|
223
223
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handlers.mjs","sources":["../../../src/tools/handlers.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/tools/handlers.ts\nimport { nanoid } from 'nanoid';\nimport { ToolMessage } from '@langchain/core/messages';\nimport type { AnthropicWebSearchResultBlockParam } from '@/llm/anthropic/types';\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n Constants,\n} from '@/common';\nimport {\n coerceAnthropicSearchResults,\n isAnthropicWebSearchResult,\n} from '@/tools/search/anthropic';\nimport { formatResultsForLLM } from '@/tools/search/format';\nimport { getMessageId } from '@/messages';\n\nexport function handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks,\n}: {\n graph: Graph;\n stepKey: string;\n toolCallChunks: ToolCallChunk[];\n}): void {\n let prevStepId: string;\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n /** Edge Case: If no previous step exists, create a new message creation step */\n const message_id = getMessageId(stepKey, graph, true) ?? '';\n prevStepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n prevRunStep = graph.getRunStep(prevStepId);\n }\n\n const _stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\n\n /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */\n const tool_calls: ToolCall[] | undefined =\n prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION\n ? []\n : undefined;\n\n /** Edge Case: `id` and `name` fields cannot be empty strings */\n for (const toolCallChunk of toolCallChunks) {\n if (toolCallChunk.name === '') {\n toolCallChunk.name = undefined;\n }\n if (toolCallChunk.id === '') {\n toolCallChunk.id = undefined;\n } else if (\n tool_calls != null &&\n toolCallChunk.id != null &&\n toolCallChunk.name != null\n ) {\n tool_calls.push({\n args: {},\n id: toolCallChunk.id,\n name: toolCallChunk.name,\n type: ToolCallTypes.TOOL_CALL,\n });\n }\n }\n\n let stepId: string = _stepId;\n const alreadyDispatched =\n prevRunStep?.type === StepTypes.MESSAGE_CREATION &&\n graph.messageStepHasToolCalls.has(prevStepId);\n if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {\n graph.dispatchMessageDelta(prevStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: '',\n tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),\n },\n ],\n });\n graph.messageStepHasToolCalls.set(prevStepId, true);\n stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n }\n graph.dispatchRunStepDelta(stepId, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: toolCallChunks,\n });\n}\n\nexport const handleToolCalls = (\n toolCalls?: ToolCall[],\n metadata?: Record<string, unknown>,\n graph?: Graph\n): void => {\n if (!graph || !metadata) {\n console.warn(`Graph or metadata not found in ${event} event`);\n return;\n }\n\n if (!toolCalls) {\n return;\n }\n\n if (toolCalls.length === 0) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n for (const tool_call of toolCalls) {\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\n tool_call.id = toolCallId;\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n\n let prevStepId = '';\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n // no previous step\n }\n\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\n graph.dispatchMessageDelta(lastMessageStepId, {\n content: [\n {\n type: 'text',\n text: '',\n tool_call_ids: [toolCallId],\n },\n ],\n });\n };\n /* If the previous step exists and is a message creation */\n if (\n prevStepId &&\n prevRunStep &&\n prevRunStep.type === StepTypes.MESSAGE_CREATION\n ) {\n dispatchToolCallIds(prevStepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (\n !prevRunStep ||\n prevRunStep.type !== StepTypes.MESSAGE_CREATION\n ) {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n const stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n });\n dispatchToolCallIds(stepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n }\n\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: [tool_call],\n });\n }\n};\n\nexport const toolResultTypes = new Set([\n // 'tool_use',\n // 'server_tool_use',\n // 'input_json_delta',\n 'tool_result',\n 'web_search_result',\n 'web_search_tool_result',\n]);\n\n/**\n * Handles the result of a server tool call; in other words, a provider's built-in tool.\n * As of 2025-07-06, only Anthropic handles server tool calls with this pattern.\n */\nexport function handleServerToolResult({\n content,\n metadata,\n graph,\n}: {\n content?: string | t.MessageContentComplex[];\n metadata?: Record<string, unknown>;\n graph: Graph;\n}): boolean {\n let skipHandling = false;\n if (metadata?.provider !== Providers.ANTHROPIC) {\n return skipHandling;\n }\n if (\n typeof content === 'string' ||\n content == null ||\n content.length === 0 ||\n (content.length === 1 &&\n (content[0] as t.ToolResultContent).tool_use_id == null)\n ) {\n return skipHandling;\n }\n\n for (const contentPart of content) {\n const toolUseId = (contentPart as t.ToolResultContent).tool_use_id;\n if (toolUseId == null || toolUseId === '') {\n continue;\n }\n const stepId = graph.toolCallStepIds.get(toolUseId);\n if (stepId == null || stepId === '') {\n console.warn(\n `Tool use ID ${toolUseId} not found in graph, cannot dispatch tool result.`\n );\n continue;\n }\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(\n `Run step for ${stepId} does not exist, cannot dispatch tool result.`\n );\n continue;\n } else if (runStep.type !== StepTypes.TOOL_CALLS) {\n console.warn(\n `Run step for ${stepId} is not a tool call step, cannot dispatch tool result.`\n );\n continue;\n }\n\n const toolCall =\n runStep.stepDetails.type === StepTypes.TOOL_CALLS\n ? (runStep.stepDetails.tool_calls?.find(\n (toolCall) => toolCall.id === toolUseId\n ) as ToolCall)\n : undefined;\n\n if (!toolCall) {\n continue;\n }\n\n if (\n contentPart.type === 'web_search_result' ||\n contentPart.type === 'web_search_tool_result'\n ) {\n handleAnthropicSearchResults({\n contentPart: contentPart as t.ToolResultContent,\n toolCall,\n metadata,\n graph,\n });\n }\n\n if (!skipHandling) {\n skipHandling = true;\n }\n }\n\n return skipHandling;\n}\n\nfunction handleAnthropicSearchResults({\n contentPart,\n toolCall,\n metadata,\n graph,\n}: {\n contentPart: t.ToolResultContent;\n toolCall: ToolCall;\n metadata?: Record<string, unknown>;\n graph: Graph;\n}): void {\n if (!Array.isArray(contentPart.content)) {\n console.warn(\n `Expected content to be an array, got ${typeof contentPart.content}`\n );\n return;\n }\n\n if (!isAnthropicWebSearchResult(contentPart.content[0])) {\n console.warn(\n `Expected content to be an Anthropic web search result, got ${JSON.stringify(\n contentPart.content\n )}`\n );\n return;\n }\n\n const turn = graph.invokedToolIds?.size ?? 0;\n const searchResultData = coerceAnthropicSearchResults({\n turn,\n results: contentPart.content as AnthropicWebSearchResultBlockParam[],\n });\n\n const name = toolCall.name;\n const input = toolCall.args;\n const artifact = {\n [Constants.WEB_SEARCH]: searchResultData,\n };\n const { output: formattedOutput } = formatResultsForLLM(\n turn,\n searchResultData\n );\n const output = new ToolMessage({\n name,\n artifact,\n content: formattedOutput,\n tool_call_id: toolCall.id!,\n });\n const toolEndData: t.ToolEndData = {\n input,\n output,\n };\n graph.handlerRegistry\n ?.getHandler(GraphEvents.TOOL_END)\n ?.handle(GraphEvents.TOOL_END, toolEndData, metadata, graph);\n\n if (graph.invokedToolIds == null) {\n graph.invokedToolIds = new Set<string>();\n }\n\n graph.invokedToolIds.add(toolCall.id!);\n}\n"],"names":[],"mappings":";;;;;;;;AAAA;AACA;AAsBM,SAAU,oBAAoB,CAAC,EACnC,KAAK,EACL,OAAO,EACP,cAAc,GAKf,EAAA;AACC,IAAA,IAAI,UAAkB;AACtB,IAAA,IAAI,WAAkC;AACtC,IAAA,IAAI;AACF,QAAA,UAAU,GAAG,KAAK,CAAC,cAAc,CAAC,OAAO,EAAE,KAAK,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC,CAAC;AACxE,QAAA,WAAW,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC;;AAC1C,IAAA,MAAM;;AAEN,QAAA,MAAM,UAAU,GAAG,YAAY,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,EAAE;AAC3D,QAAA,UAAU,GAAG,KAAK,CAAC,eAAe,CA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AAI,CAAC;IAC5C,MAAM,gBAAgB,GAAG,4BAA4B,CAAC;QACpD,IAAI;QACJ,OAAO,EAAE,WAAW,CAAC,OAA+C;AACrE,KAAA,CAAC;AAEF,IAAA,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI;AAC1B,IAAA,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI;AAC3B,IAAA,MAAM,QAAQ,GAAG;AACf,QAAA,CAAC,SAAS,CAAC,UAAU,GAAG,gBAAgB;KACzC;AACD,IAAA,MAAM,EAAE,MAAM,EAAE,eAAe,EAAE,GAAG,mBAAmB,CACrD,IAAI,EACJ,gBAAgB,CACjB;AACD,IAAA,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC;QAC7B,IAAI;QACJ,QAAQ;AACR,QAAA,OAAO,EAAE,eAAe;QACxB,YAAY,EAAE,QAAQ,CAAC,EAAG;AAC3B,KAAA,CAAC;AACF,IAAA,MAAM,WAAW,GAAkB;QACjC,KAAK;QACL,MAAM;KACP;AACD,IAAA,KAAK,CAAC;AACJ,UAAE,UAAU,CAAC,WAAW,CAAC,QAAQ;AACjC,UAAE,MAAM,CAAC,WAAW,CAAC,QAAQ,EAAE,WAAW,EAAE,QAAQ,EAAE,KAAK,CAAC;AAE9D,IAAA,IAAI,KAAK,CAAC,cAAc,IAAI,IAAI,EAAE;AAChC,QAAA,KAAK,CAAC,cAAc,GAAG,IAAI,GAAG,EAAU;;IAG1C,KAAK,CAAC,cAAc,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAG,CAAC;AACxC;;;;"}
|
|
1
|
+
{"version":3,"file":"handlers.mjs","sources":["../../../src/tools/handlers.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/tools/handlers.ts\nimport { nanoid } from 'nanoid';\nimport { ToolMessage } from '@langchain/core/messages';\nimport type { AnthropicWebSearchResultBlockParam } from '@/llm/anthropic/types';\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\nimport {\n ToolCallTypes,\n ContentTypes,\n GraphEvents,\n StepTypes,\n Providers,\n Constants,\n} from '@/common';\nimport {\n coerceAnthropicSearchResults,\n isAnthropicWebSearchResult,\n} from '@/tools/search/anthropic';\nimport { formatResultsForLLM } from '@/tools/search/format';\nimport { getMessageId } from '@/messages';\n\nexport function handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks,\n}: {\n graph: Graph;\n stepKey: string;\n toolCallChunks: ToolCallChunk[];\n}): void {\n let prevStepId: string;\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n /** Edge Case: If no previous step exists, create a new message creation step */\n const message_id = getMessageId(stepKey, graph, true) ?? '';\n prevStepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n prevRunStep = graph.getRunStep(prevStepId);\n }\n\n const _stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\n\n /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */\n const tool_calls: ToolCall[] | undefined =\n prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION\n ? []\n : undefined;\n\n /** Edge Case: `id` and `name` fields cannot be empty strings */\n for (const toolCallChunk of toolCallChunks) {\n if (toolCallChunk.name === '') {\n toolCallChunk.name = undefined;\n }\n if (toolCallChunk.id === '') {\n toolCallChunk.id = undefined;\n } else if (\n tool_calls != null &&\n toolCallChunk.id != null &&\n toolCallChunk.name != null\n ) {\n tool_calls.push({\n args: {},\n id: toolCallChunk.id,\n name: toolCallChunk.name,\n type: ToolCallTypes.TOOL_CALL,\n });\n }\n }\n\n let stepId: string = _stepId;\n const alreadyDispatched =\n prevRunStep?.type === StepTypes.MESSAGE_CREATION &&\n graph.messageStepHasToolCalls.has(prevStepId);\n if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {\n graph.dispatchMessageDelta(prevStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: '',\n tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),\n },\n ],\n });\n graph.messageStepHasToolCalls.set(prevStepId, true);\n stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n }\n graph.dispatchRunStepDelta(stepId, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: toolCallChunks,\n });\n}\n\nexport const handleToolCalls = (\n toolCalls?: ToolCall[],\n metadata?: Record<string, unknown>,\n graph?: Graph\n): void => {\n if (!graph || !metadata) {\n console.warn(`Graph or metadata not found in ${event} event`);\n return;\n }\n\n if (!toolCalls) {\n return;\n }\n\n if (toolCalls.length === 0) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n for (const tool_call of toolCalls) {\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\n tool_call.id = toolCallId;\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n\n let prevStepId = '';\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n // no previous step\n }\n\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\n graph.dispatchMessageDelta(lastMessageStepId, {\n content: [\n {\n type: 'text',\n text: '',\n tool_call_ids: [toolCallId],\n },\n ],\n });\n };\n /* If the previous step exists and is a message creation */\n if (\n prevStepId &&\n prevRunStep &&\n prevRunStep.type === StepTypes.MESSAGE_CREATION\n ) {\n dispatchToolCallIds(prevStepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (\n !prevRunStep ||\n prevRunStep.type !== StepTypes.MESSAGE_CREATION\n ) {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n const stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n });\n dispatchToolCallIds(stepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n }\n\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: [tool_call],\n });\n }\n};\n\nexport const toolResultTypes = new Set([\n // 'tool_use',\n // 'server_tool_use',\n // 'input_json_delta',\n 'tool_result',\n 'web_search_result',\n 'web_search_tool_result',\n]);\n\n/**\n * Handles the result of a server tool call; in other words, a provider's built-in tool.\n * As of 2025-07-06, only Anthropic handles server tool calls with this pattern.\n */\nexport function handleServerToolResult({\n content,\n metadata,\n graph,\n}: {\n content?: string | t.MessageContentComplex[];\n metadata?: Record<string, unknown>;\n graph: Graph;\n}): boolean {\n let skipHandling = false;\n if (metadata?.provider !== Providers.ANTHROPIC) {\n return skipHandling;\n }\n if (\n typeof content === 'string' ||\n content == null ||\n content.length === 0 ||\n (content.length === 1 &&\n (content[0] as t.ToolResultContent).tool_use_id == null)\n ) {\n return skipHandling;\n }\n\n for (const contentPart of content) {\n const toolUseId = (contentPart as t.ToolResultContent).tool_use_id;\n if (toolUseId == null || toolUseId === '') {\n continue;\n }\n const stepId = graph.toolCallStepIds.get(toolUseId);\n if (stepId == null || stepId === '') {\n console.warn(\n `Tool use ID ${toolUseId} not found in graph, cannot dispatch tool result.`\n );\n continue;\n }\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(\n `Run step for ${stepId} does not exist, cannot dispatch tool result.`\n );\n continue;\n } else if (runStep.type !== StepTypes.TOOL_CALLS) {\n console.warn(\n `Run step for ${stepId} is not a tool call step, cannot dispatch tool result.`\n );\n continue;\n }\n\n const toolCall =\n runStep.stepDetails.type === StepTypes.TOOL_CALLS\n ? (runStep.stepDetails.tool_calls?.find(\n (toolCall) => toolCall.id === toolUseId\n ) as ToolCall)\n : undefined;\n\n if (!toolCall) {\n continue;\n }\n\n if (\n contentPart.type === 'web_search_result' ||\n contentPart.type === 'web_search_tool_result'\n ) {\n handleAnthropicSearchResults({\n contentPart: contentPart as t.ToolResultContent,\n toolCall,\n metadata,\n graph,\n });\n }\n\n if (!skipHandling) {\n skipHandling = true;\n }\n }\n\n return skipHandling;\n}\n\nfunction handleAnthropicSearchResults({\n contentPart,\n toolCall,\n metadata,\n graph,\n}: {\n contentPart: t.ToolResultContent;\n toolCall: Partial<ToolCall>;\n metadata?: Record<string, unknown>;\n graph: Graph;\n}): void {\n if (!Array.isArray(contentPart.content)) {\n console.warn(\n `Expected content to be an array, got ${typeof contentPart.content}`\n );\n return;\n }\n\n if (!isAnthropicWebSearchResult(contentPart.content[0])) {\n console.warn(\n `Expected content to be an Anthropic web search result, got ${JSON.stringify(\n contentPart.content\n )}`\n );\n return;\n }\n\n const turn = graph.invokedToolIds?.size ?? 0;\n const searchResultData = coerceAnthropicSearchResults({\n turn,\n results: contentPart.content as AnthropicWebSearchResultBlockParam[],\n });\n\n const name = toolCall.name;\n const input = toolCall.args ?? {};\n const artifact = {\n [Constants.WEB_SEARCH]: searchResultData,\n };\n const { output: formattedOutput } = formatResultsForLLM(\n turn,\n searchResultData\n );\n const output = new ToolMessage({\n name,\n artifact,\n content: formattedOutput,\n tool_call_id: toolCall.id!,\n });\n const toolEndData: t.ToolEndData = {\n input,\n output,\n };\n graph.handlerRegistry\n ?.getHandler(GraphEvents.TOOL_END)\n ?.handle(GraphEvents.TOOL_END, toolEndData, metadata, graph);\n\n if (graph.invokedToolIds == null) {\n graph.invokedToolIds = new Set<string>();\n }\n\n graph.invokedToolIds.add(toolCall.id!);\n}\n"],"names":[],"mappings":";;;;;;;;AAAA;AACA;AAsBM,SAAU,oBAAoB,CAAC,EACnC,KAAK,EACL,OAAO,EACP,cAAc,GAKf,EAAA;AACC,IAAA,IAAI,UAAkB;AACtB,IAAA,IAAI,WAAkC;AACtC,IAAA,IAAI;AACF,QAAA,UAAU,GAAG,KAAK,CAAC,cAAc,CAAC,OAAO,EAAE,KAAK,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC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
1
|
import { AzureOpenAI as AzureOpenAIClient } from 'openai';
|
|
2
2
|
import { ChatXAI as OriginalChatXAI } from '@langchain/xai';
|
|
3
|
+
import { ChatGenerationChunk } from '@langchain/core/outputs';
|
|
3
4
|
import { ChatDeepSeek as OriginalChatDeepSeek } from '@langchain/deepseek';
|
|
4
|
-
import { OpenAIClient, ChatOpenAI as OriginalChatOpenAI, AzureChatOpenAI as OriginalAzureChatOpenAI } from '@langchain/openai';
|
|
5
|
-
import type { ChatGenerationChunk } from '@langchain/core/outputs';
|
|
6
5
|
import { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';
|
|
6
|
+
import { OpenAIClient, ChatOpenAI as OriginalChatOpenAI, AzureChatOpenAI as OriginalAzureChatOpenAI } from '@langchain/openai';
|
|
7
7
|
import type { BindToolsInput } from '@langchain/core/language_models/chat_models';
|
|
8
8
|
import type { BaseMessage } from '@langchain/core/messages';
|
|
9
9
|
import type * as t from '@langchain/openai';
|
|
@@ -45,6 +45,7 @@ export declare class ChatOpenAI extends OriginalChatOpenAI<t.ChatOpenAICallOptio
|
|
|
45
45
|
get exposedClient(): CustomOpenAIClient;
|
|
46
46
|
protected _getClientOptions(options?: OpenAICoreRequestOptions): OpenAICoreRequestOptions;
|
|
47
47
|
_streamResponseChunks(messages: BaseMessage[], options: this['ParsedCallOptions'], runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;
|
|
48
|
+
_streamResponseChunks2(messages: BaseMessage[], options: this['ParsedCallOptions'], runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;
|
|
48
49
|
}
|
|
49
50
|
export declare class AzureChatOpenAI extends OriginalAzureChatOpenAI {
|
|
50
51
|
get exposedClient(): CustomOpenAIClient;
|