@librechat/agents 2.0.4 → 2.1.0
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/common/enum.cjs +1 -0
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/events.cjs +10 -0
- package/dist/cjs/events.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +38 -2
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/llm.cjs +1 -3
- package/dist/cjs/llm/anthropic/llm.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -1
- package/dist/cjs/llm/fake.cjs +55 -0
- package/dist/cjs/llm/fake.cjs.map +1 -0
- package/dist/cjs/llm/providers.cjs +7 -5
- package/dist/cjs/llm/providers.cjs.map +1 -1
- package/dist/cjs/llm/text.cjs.map +1 -1
- package/dist/cjs/messages.cjs.map +1 -1
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/splitStream.cjs.map +1 -1
- package/dist/cjs/stream.cjs +97 -20
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +8 -2
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/utils/graph.cjs.map +1 -1
- package/dist/cjs/utils/llm.cjs.map +1 -1
- package/dist/cjs/utils/misc.cjs.map +1 -1
- package/dist/cjs/utils/run.cjs.map +1 -1
- package/dist/cjs/utils/title.cjs.map +1 -1
- package/dist/esm/common/enum.mjs +1 -0
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/events.mjs +10 -0
- package/dist/esm/events.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +39 -3
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/llm/anthropic/llm.mjs +1 -3
- package/dist/esm/llm/anthropic/llm.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -1
- package/dist/esm/llm/fake.mjs +52 -0
- package/dist/esm/llm/fake.mjs.map +1 -0
- package/dist/esm/llm/providers.mjs +8 -6
- package/dist/esm/llm/providers.mjs.map +1 -1
- package/dist/esm/llm/text.mjs.map +1 -1
- package/dist/esm/messages.mjs.map +1 -1
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/splitStream.mjs.map +1 -1
- package/dist/esm/stream.mjs +98 -21
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +9 -3
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/utils/graph.mjs.map +1 -1
- package/dist/esm/utils/llm.mjs.map +1 -1
- package/dist/esm/utils/misc.mjs.map +1 -1
- package/dist/esm/utils/run.mjs.map +1 -1
- package/dist/esm/utils/title.mjs.map +1 -1
- package/dist/types/common/enum.d.ts +2 -1
- package/dist/types/events.d.ts +4 -1
- package/dist/types/graphs/Graph.d.ts +9 -1
- package/dist/types/llm/fake.d.ts +21 -0
- package/dist/types/specs/spec.utils.d.ts +1 -0
- package/dist/types/stream.d.ts +9 -13
- package/dist/types/types/llm.d.ts +10 -5
- package/dist/types/types/stream.d.ts +12 -0
- package/package.json +15 -26
- package/src/common/enum.ts +1 -0
- package/src/events.ts +13 -1
- package/src/graphs/Graph.ts +43 -4
- package/src/llm/fake.ts +83 -0
- package/src/llm/providers.ts +7 -5
- package/src/scripts/simple.ts +28 -14
- package/src/specs/anthropic.simple.test.ts +204 -0
- package/src/specs/openai.simple.test.ts +204 -0
- package/src/specs/reasoning.test.ts +165 -0
- package/src/specs/spec.utils.ts +3 -0
- package/src/stream.ts +104 -36
- package/src/tools/CodeExecutor.ts +8 -2
- package/src/types/llm.ts +10 -5
- package/src/types/stream.ts +14 -1
- package/src/utils/llmConfig.ts +17 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.mjs","sources":["../../src/messages.ts"],"sourcesContent":["// src/messages.ts\nimport { AIMessageChunk, HumanMessage, ToolMessage, AIMessage, BaseMessage } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\n\nexport function getConverseOverrideMessage({\n userMessage,\n lastMessageX,\n lastMessageY\n}: {\n userMessage: string[];\n lastMessageX: AIMessageChunk | null;\n lastMessageY: ToolMessage;\n}): HumanMessage {\n const content = `\nUser: ${userMessage[1]}\n\n---\n# YOU HAVE ALREADY RESPONDED TO THE LATEST USER MESSAGE:\n\n# Observations:\n- ${lastMessageX?.content}\n\n# Tool Calls:\n- ${lastMessageX?.tool_calls?.join('\\n- ')}\n\n# Tool Responses:\n- ${lastMessageY.content}\n`;\n\n return new HumanMessage(content);\n}\n\nconst modifyContent = (messageType: string, content: t.ExtendedMessageContent[]): t.ExtendedMessageContent[] => {\n return content.map(item => {\n if (item && typeof item === 'object' && 'type' in item && item.type != null && item.type) {\n let newType = item.type;\n if (newType.endsWith('_delta')) {\n newType = newType.replace('_delta', '');\n }\n const allowedTypes = ['image_url', 'text', 'tool_use', 'tool_result'];\n if (!allowedTypes.includes(newType)) {\n newType = 'text';\n }\n\n /* Handle the edge case for empty object 'tool_use' input in AI messages */\n if (messageType === 'ai' && newType === 'tool_use' && 'input' in item && item.input === '') {\n return { ...item, type: newType, input: '{}' };\n }\n\n return { ...item, type: newType };\n }\n return item;\n });\n};\n\nexport function modifyDeltaProperties(obj?: AIMessageChunk): AIMessageChunk | undefined {\n if (!obj || typeof obj !== 'object') return obj;\n\n const messageType = obj._getType ? obj._getType() : '';\n\n if (Array.isArray(obj.content)) {\n obj.content = modifyContent(messageType, obj.content);\n }\n if (obj.lc_kwargs && Array.isArray(obj.lc_kwargs.content)) {\n obj.lc_kwargs.content = modifyContent(messageType, obj.lc_kwargs.content);\n }\n return obj;\n}\n\nexport function formatAnthropicMessage(message: AIMessageChunk): AIMessage {\n if (!message.tool_calls || message.tool_calls.length === 0) {\n return new AIMessage({ content: message.content });\n }\n\n const toolCallMap = new Map(message.tool_calls.map(tc => [tc.id, tc]));\n let formattedContent: string | t.ExtendedMessageContent[];\n\n if (Array.isArray(message.content)) {\n formattedContent = message.content.reduce<t.ExtendedMessageContent[]>((acc, item) => {\n if (typeof item === 'object' && item !== null) {\n const extendedItem = item as t.ExtendedMessageContent;\n if (extendedItem.type === 'text' && extendedItem.text != null && extendedItem.text) {\n acc.push({ type: 'text', text: extendedItem.text });\n } else if (extendedItem.type === 'tool_use' && extendedItem.id != null && extendedItem.id) {\n const toolCall = toolCallMap.get(extendedItem.id);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: extendedItem.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string\n });\n }\n } else if ('input' in extendedItem && extendedItem.input != null && extendedItem.input) {\n try {\n const parsedInput = JSON.parse(extendedItem.input);\n const toolCall = message.tool_calls?.find(tc => tc.args.input === parsedInput.input);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string\n });\n }\n } catch (e) {\n if (extendedItem.input) {\n acc.push({ type: 'text', text: extendedItem.input });\n }\n }\n }\n } else if (typeof item === 'string') {\n acc.push({ type: 'text', text: item });\n }\n return acc;\n }, []);\n } else if (typeof message.content === 'string') {\n formattedContent = message.content;\n } else {\n formattedContent = [];\n }\n\n // const formattedToolCalls: ToolCall[] = message.tool_calls.map(toolCall => ({\n // id: toolCall.id ?? '',\n // name: toolCall.name,\n // args: toolCall.args,\n // type: 'tool_call',\n // }));\n\n const formattedToolCalls: t.AgentToolCall[] = message.tool_calls.map(toolCall => ({\n id: toolCall.id ?? '',\n type: 'function',\n function: {\n name: toolCall.name,\n arguments: toolCall.args\n }\n }));\n\n return new AIMessage({\n content: formattedContent,\n tool_calls: formattedToolCalls as ToolCall[],\n additional_kwargs: {\n ...message.additional_kwargs,\n }\n });\n}\n\nexport function convertMessagesToContent(messages: BaseMessage[]): t.MessageContentComplex[] {\n const processedContent: t.MessageContentComplex[] = [];\n\n const addContentPart = (message: BaseMessage | null): void => {\n const content = message?.lc_kwargs.content != null ? message.lc_kwargs.content : message?.content;\n if (content === undefined) {\n return;\n }\n if (typeof content === 'string') {\n processedContent.push({\n type: 'text',\n text: content\n });\n } else if (Array.isArray(content)) {\n const filteredContent = content.filter(item => item && item.type !== 'tool_use');\n processedContent.push(...filteredContent);\n }\n };\n\n let currentAIMessageIndex = -1;\n const toolCallMap = new Map<string, t.CustomToolCall>();\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i] as BaseMessage | null;\n const messageType = message?._getType();\n\n if (messageType === 'ai' && (message as AIMessage).tool_calls?.length) {\n const tool_calls = (message as AIMessage).tool_calls || [];\n for (const tool_call of tool_calls) {\n if (!tool_call.id) {\n continue;\n }\n\n toolCallMap.set(tool_call.id, tool_call);\n }\n\n addContentPart(message);\n currentAIMessageIndex = processedContent.length - 1;\n continue;\n } else if (messageType === 'tool' && (message as ToolMessage).tool_call_id) {\n const id = (message as ToolMessage).tool_call_id;\n const output = (message as ToolMessage).content;\n const tool_call = toolCallMap.get(id);\n\n processedContent.push({\n type: 'tool_call',\n tool_call: Object.assign({}, tool_call, { output }),\n });\n const contentPart = processedContent[currentAIMessageIndex];\n const tool_call_ids = contentPart.tool_call_ids || [];\n tool_call_ids.push(id);\n contentPart.tool_call_ids = tool_call_ids;\n continue;\n } else if (messageType !== 'ai') {\n continue;\n }\n\n addContentPart(message);\n }\n\n return processedContent;\n}\n\nexport function formatAnthropicArtifactContent(messages: BaseMessage[]): void {\n const lastMessage = messages[messages.length - 1];\n if (!(lastMessage instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(messages,\n msg => (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some(tc => tc.id === lastMessage.tool_call_id)) ?? false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n const hasArtifactContent = messages.some(\n (msg, i) => i > latestAIParentIndex\n && msg instanceof ToolMessage\n && msg.artifact != null\n && msg.artifact?.content != null\n && Array.isArray(msg.artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n const message = messages[latestAIParentIndex] as AIMessageChunk;\n const toolCallIds = message.tool_calls?.map(tc => tc.id) ?? [];\n\n for (let j = latestAIParentIndex + 1; j < messages.length; j++) {\n const msg = messages[j];\n if (msg instanceof ToolMessage &&\n toolCallIds.includes(msg.tool_call_id) &&\n msg.artifact != null &&\n Array.isArray(msg.artifact?.content) &&\n Array.isArray(msg.content)) {\n msg.content = msg.content.concat(msg.artifact.content);\n }\n }\n}\n\nexport function formatArtifactPayload(messages: BaseMessage[]): void {\n const lastMessageY = messages[messages.length - 1];\n if (!(lastMessageY instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(messages,\n msg => (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some(tc => tc.id === lastMessageY.tool_call_id)) ?? false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n const hasArtifactContent = messages.some(\n (msg, i) => i > latestAIParentIndex\n && msg instanceof ToolMessage\n && msg.artifact != null\n && msg.artifact?.content != null\n && Array.isArray(msg.artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n // Collect all relevant tool messages and their artifacts\n const relevantMessages = messages\n .slice(latestAIParentIndex + 1)\n .filter(msg => msg instanceof ToolMessage) as ToolMessage[];\n\n // Aggregate all content and artifacts\n const aggregatedContent: t.MessageContentComplex[] = [];\n\n relevantMessages.forEach(msg => {\n if (!Array.isArray(msg.artifact?.content)) {\n return;\n }\n if (!Array.isArray(msg.content)) {\n return;\n }\n aggregatedContent.push(...msg.content);\n msg.content = 'Tool response is included in the next message as a Human message';\n aggregatedContent.push(...msg.artifact.content);\n });\n\n // Add single HumanMessage with all aggregated content\n if (aggregatedContent.length > 0) {\n messages.push(new HumanMessage({ content: aggregatedContent }));\n }\n}\n\nexport function findLastIndex<T>(array: T[], predicate: (value: T) => boolean): number {\n for (let i = array.length - 1; i >= 0; i--) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return -1;\n}"],"names":[],"mappings":";;AAAA;AAKM,SAAU,0BAA0B,CAAC,EACzC,WAAW,EACX,YAAY,EACZ,YAAY,EAKb,EAAA;AACC,IAAA,MAAM,OAAO,GAAG,CAAA;QACV,WAAW,CAAC,CAAC,CAAC,CAAA;;;;;;AAMlB,EAAA,EAAA,YAAY,EAAE,OAAO,CAAA;;;AAGrB,EAAA,EAAA,YAAY,EAAE,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC,CAAA;;;AAGtC,EAAA,EAAA,YAAY,CAAC,OAAO,CAAA;CACvB,CAAC;AAEA,IAAA,OAAO,IAAI,YAAY,CAAC,OAAO,CAAC,CAAC;AACnC,CAAC;AAED,MAAM,aAAa,GAAG,CAAC,WAAmB,EAAE,OAAmC,KAAgC;AAC7G,IAAA,OAAO,OAAO,CAAC,GAAG,CAAC,IAAI,IAAG;QACxB,IAAI,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,MAAM,IAAI,IAAI,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,IAAI,IAAI,CAAC,IAAI,EAAE;AACxF,YAAA,IAAI,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC;AACxB,YAAA,IAAI,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE;gBAC9B,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;aACzC;YACD,MAAM,YAAY,GAAG,CAAC,WAAW,EAAE,MAAM,EAAE,UAAU,EA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IAAI,CAAC,IAAI,YAAY,CAAC,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC,CAAC;KACjE;AACH,CAAC;AAEe,SAAA,aAAa,CAAI,KAAU,EAAE,SAAgC,EAAA;AAC3E,IAAA,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE;QAC1C,IAAI,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE;AACvB,YAAA,OAAO,CAAC,CAAC;SACV;KACF;IACD,OAAO,CAAC,CAAC,CAAC;AACZ;;;;"}
|
|
1
|
+
{"version":3,"file":"messages.mjs","sources":["../../src/messages.ts"],"sourcesContent":["// src/messages.ts\nimport { AIMessageChunk, HumanMessage, ToolMessage, AIMessage, BaseMessage } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\n\nexport function getConverseOverrideMessage({\n userMessage,\n lastMessageX,\n lastMessageY\n}: {\n userMessage: string[];\n lastMessageX: AIMessageChunk | null;\n lastMessageY: ToolMessage;\n}): HumanMessage {\n const content = `\nUser: ${userMessage[1]}\n\n---\n# YOU HAVE ALREADY RESPONDED TO THE LATEST USER MESSAGE:\n\n# Observations:\n- ${lastMessageX?.content}\n\n# Tool Calls:\n- ${lastMessageX?.tool_calls?.join('\\n- ')}\n\n# Tool Responses:\n- ${lastMessageY.content}\n`;\n\n return new HumanMessage(content);\n}\n\nconst modifyContent = (messageType: string, content: t.ExtendedMessageContent[]): t.ExtendedMessageContent[] => {\n return content.map(item => {\n if (item && typeof item === 'object' && 'type' in item && item.type != null && item.type) {\n let newType = item.type;\n if (newType.endsWith('_delta')) {\n newType = newType.replace('_delta', '');\n }\n const allowedTypes = ['image_url', 'text', 'tool_use', 'tool_result'];\n if (!allowedTypes.includes(newType)) {\n newType = 'text';\n }\n\n /* Handle the edge case for empty object 'tool_use' input in AI messages */\n if (messageType === 'ai' && newType === 'tool_use' && 'input' in item && item.input === '') {\n return { ...item, type: newType, input: '{}' };\n }\n\n return { ...item, type: newType };\n }\n return item;\n });\n};\n\nexport function modifyDeltaProperties(obj?: AIMessageChunk): AIMessageChunk | undefined {\n if (!obj || typeof obj !== 'object') return obj;\n\n const messageType = obj._getType ? obj._getType() : '';\n\n if (Array.isArray(obj.content)) {\n obj.content = modifyContent(messageType, obj.content);\n }\n if (obj.lc_kwargs && Array.isArray(obj.lc_kwargs.content)) {\n obj.lc_kwargs.content = modifyContent(messageType, obj.lc_kwargs.content);\n }\n return obj;\n}\n\nexport function formatAnthropicMessage(message: AIMessageChunk): AIMessage {\n if (!message.tool_calls || message.tool_calls.length === 0) {\n return new AIMessage({ content: message.content });\n }\n\n const toolCallMap = new Map(message.tool_calls.map(tc => [tc.id, tc]));\n let formattedContent: string | t.ExtendedMessageContent[];\n\n if (Array.isArray(message.content)) {\n formattedContent = message.content.reduce<t.ExtendedMessageContent[]>((acc, item) => {\n if (typeof item === 'object' && item !== null) {\n const extendedItem = item as t.ExtendedMessageContent;\n if (extendedItem.type === 'text' && extendedItem.text != null && extendedItem.text) {\n acc.push({ type: 'text', text: extendedItem.text });\n } else if (extendedItem.type === 'tool_use' && extendedItem.id != null && extendedItem.id) {\n const toolCall = toolCallMap.get(extendedItem.id);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: extendedItem.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string\n });\n }\n } else if ('input' in extendedItem && extendedItem.input != null && extendedItem.input) {\n try {\n const parsedInput = JSON.parse(extendedItem.input);\n const toolCall = message.tool_calls?.find(tc => tc.args.input === parsedInput.input);\n if (toolCall) {\n acc.push({\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args as unknown as string\n });\n }\n } catch (e) {\n if (extendedItem.input) {\n acc.push({ type: 'text', text: extendedItem.input });\n }\n }\n }\n } else if (typeof item === 'string') {\n acc.push({ type: 'text', text: item });\n }\n return acc;\n }, []);\n } else if (typeof message.content === 'string') {\n formattedContent = message.content;\n } else {\n formattedContent = [];\n }\n\n // const formattedToolCalls: ToolCall[] = message.tool_calls.map(toolCall => ({\n // id: toolCall.id ?? '',\n // name: toolCall.name,\n // args: toolCall.args,\n // type: 'tool_call',\n // }));\n\n const formattedToolCalls: t.AgentToolCall[] = message.tool_calls.map(toolCall => ({\n id: toolCall.id ?? '',\n type: 'function',\n function: {\n name: toolCall.name,\n arguments: toolCall.args\n }\n }));\n\n return new AIMessage({\n content: formattedContent,\n tool_calls: formattedToolCalls as ToolCall[],\n additional_kwargs: {\n ...message.additional_kwargs,\n }\n });\n}\n\nexport function convertMessagesToContent(messages: BaseMessage[]): t.MessageContentComplex[] {\n const processedContent: t.MessageContentComplex[] = [];\n\n const addContentPart = (message: BaseMessage | null): void => {\n const content = message?.lc_kwargs.content != null ? message.lc_kwargs.content : message?.content;\n if (content === undefined) {\n return;\n }\n if (typeof content === 'string') {\n processedContent.push({\n type: 'text',\n text: content\n });\n } else if (Array.isArray(content)) {\n const filteredContent = content.filter(item => item && item.type !== 'tool_use');\n processedContent.push(...filteredContent);\n }\n };\n\n let currentAIMessageIndex = -1;\n const toolCallMap = new Map<string, t.CustomToolCall>();\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i] as BaseMessage | null;\n const messageType = message?._getType();\n\n if (messageType === 'ai' && (message as AIMessage).tool_calls?.length) {\n const tool_calls = (message as AIMessage).tool_calls || [];\n for (const tool_call of tool_calls) {\n if (!tool_call.id) {\n continue;\n }\n\n toolCallMap.set(tool_call.id, tool_call);\n }\n\n addContentPart(message);\n currentAIMessageIndex = processedContent.length - 1;\n continue;\n } else if (messageType === 'tool' && (message as ToolMessage).tool_call_id) {\n const id = (message as ToolMessage).tool_call_id;\n const output = (message as ToolMessage).content;\n const tool_call = toolCallMap.get(id);\n\n processedContent.push({\n type: 'tool_call',\n tool_call: Object.assign({}, tool_call, { output }),\n });\n const contentPart = processedContent[currentAIMessageIndex];\n const tool_call_ids = contentPart.tool_call_ids || [];\n tool_call_ids.push(id);\n contentPart.tool_call_ids = tool_call_ids;\n continue;\n } else if (messageType !== 'ai') {\n continue;\n }\n\n addContentPart(message);\n }\n\n return processedContent;\n}\n\nexport function formatAnthropicArtifactContent(messages: BaseMessage[]): void {\n const lastMessage = messages[messages.length - 1];\n if (!(lastMessage instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(messages,\n msg => (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some(tc => tc.id === lastMessage.tool_call_id)) ?? false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n const hasArtifactContent = messages.some(\n (msg, i) => i > latestAIParentIndex\n && msg instanceof ToolMessage\n && msg.artifact != null\n && msg.artifact?.content != null\n && Array.isArray(msg.artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n const message = messages[latestAIParentIndex] as AIMessageChunk;\n const toolCallIds = message.tool_calls?.map(tc => tc.id) ?? [];\n\n for (let j = latestAIParentIndex + 1; j < messages.length; j++) {\n const msg = messages[j];\n if (msg instanceof ToolMessage &&\n toolCallIds.includes(msg.tool_call_id) &&\n msg.artifact != null &&\n Array.isArray(msg.artifact?.content) &&\n Array.isArray(msg.content)) {\n msg.content = msg.content.concat(msg.artifact.content);\n }\n }\n}\n\nexport function formatArtifactPayload(messages: BaseMessage[]): void {\n const lastMessageY = messages[messages.length - 1];\n if (!(lastMessageY instanceof ToolMessage)) return;\n\n // Find the latest AIMessage with tool_calls that this tool message belongs to\n const latestAIParentIndex = findLastIndex(messages,\n msg => (msg instanceof AIMessageChunk &&\n (msg.tool_calls?.length ?? 0) > 0 &&\n msg.tool_calls?.some(tc => tc.id === lastMessageY.tool_call_id)) ?? false\n );\n\n if (latestAIParentIndex === -1) return;\n\n // Check if any tool message after the AI message has array artifact content\n const hasArtifactContent = messages.some(\n (msg, i) => i > latestAIParentIndex\n && msg instanceof ToolMessage\n && msg.artifact != null\n && msg.artifact?.content != null\n && Array.isArray(msg.artifact.content)\n );\n\n if (!hasArtifactContent) return;\n\n // Collect all relevant tool messages and their artifacts\n const relevantMessages = messages\n .slice(latestAIParentIndex + 1)\n .filter(msg => msg instanceof ToolMessage) as ToolMessage[];\n\n // Aggregate all content and artifacts\n const aggregatedContent: t.MessageContentComplex[] = [];\n\n relevantMessages.forEach(msg => {\n if (!Array.isArray(msg.artifact?.content)) {\n return;\n }\n if (!Array.isArray(msg.content)) {\n return;\n }\n aggregatedContent.push(...msg.content);\n msg.content = 'Tool response is included in the next message as a Human message';\n aggregatedContent.push(...msg.artifact.content);\n });\n\n // Add single HumanMessage with all aggregated content\n if (aggregatedContent.length > 0) {\n messages.push(new HumanMessage({ content: aggregatedContent }));\n }\n}\n\nexport function findLastIndex<T>(array: T[], predicate: (value: T) => boolean): number {\n for (let i = array.length - 1; i >= 0; i--) {\n if (predicate(array[i])) {\n return i;\n }\n }\n return -1;\n}"],"names":[],"mappings":";;AAAA;AAKM,SAAU,0BAA0B,CAAC,EACzC,WAAW,EACX,YAAY,EACZ,YAAY,EAKb,EAAA;AACC,IAAA,MAAM,OAAO,GAAG;QACV,WAAW,CAAC,CAAC,CAAC;;;;;;AAMlB,EAAA,EAAA,YAAY,EAAE,OAAO;;;AAGrB,EAAA,EAAA,YAAY,EAAE,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC;;;AAGtC,EAAA,EAAA,YAAY,CAAC,OAAO;CACvB;AAEC,IAAA,OAAO,IAAI,YAAY,CAAC,OAAO,CAAC;AAClC;AAEA,MAAM,aAAa,GAAG,CAAC,WAAmB,EAAE,OAAmC,KAAgC;AAC7G,IAAA,OAAO,OAAO,CAAC,GAAG,CAAC,IAAI,IAAG;QACxB,IAAI,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,MAAM,IAAI,IAAI,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,IA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prompts';\nimport { AzureChatOpenAI, ChatOpenAI } from '@langchain/openai';\nimport type { BaseMessage, MessageContentComplex } from '@langchain/core/messages';\nimport type { ClientCallbacks, SystemCallbacks } from '@/graphs/Graph';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport type * as t from '@/types';\nimport { GraphEvents, Providers, Callback } from '@/common';\nimport { manualToolStreamProviders } from '@/llm/providers';\nimport { createTitleRunnable } from '@/utils/title';\nimport { StandardGraph } from '@/graphs/Graph';\nimport { HandlerRegistry } from '@/events';\nimport { isOpenAILike } from '@/utils/llm';\n\nexport class Run<T extends t.BaseGraphState> {\n graphRunnable?: t.CompiledWorkflow<T, Partial<T>, string>;\n // private collab!: CollabGraph;\n // private taskManager!: TaskManager;\n private handlerRegistry: HandlerRegistry;\n id: string;\n Graph: StandardGraph | undefined;\n provider: Providers | undefined;\n returnContent: boolean = false;\n\n private constructor(config: Partial<t.RunConfig>) {\n const runId = config.runId ?? '';\n if (!runId) {\n throw new Error('Run ID not provided');\n }\n\n this.id = runId;\n\n const handlerRegistry = new HandlerRegistry();\n\n if (config.customHandlers) {\n for (const [eventType, handler] of Object.entries(config.customHandlers)) {\n handlerRegistry.register(eventType, handler);\n }\n }\n\n this.handlerRegistry = handlerRegistry;\n\n if (!config.graphConfig) {\n throw new Error('Graph config not provided');\n }\n\n if (config.graphConfig.type === 'standard' || !config.graphConfig.type) {\n this.provider = config.graphConfig.llmConfig.provider;\n this.graphRunnable = this.createStandardGraph(config.graphConfig) as unknown as t.CompiledWorkflow<T, Partial<T>, string>;\n if (this.Graph) {\n this.Graph.handlerRegistry = handlerRegistry;\n }\n }\n\n this.returnContent = config.returnContent ?? false;\n }\n\n private createStandardGraph(config: t.StandardGraphConfig): t.CompiledWorkflow<t.IState, Partial<t.IState>, string> {\n const { llmConfig, instructions, additional_instructions, signal, streamBuffer, toolEnd, tools = [] } = config;\n const { provider, ...clientOptions } = llmConfig;\n\n const standardGraph = new StandardGraph({\n runId: this.id,\n tools,\n provider,\n signal,\n instructions,\n clientOptions,\n additional_instructions,\n streamBuffer,\n toolEnd,\n });\n this.Graph = standardGraph;\n return standardGraph.createWorkflow();\n }\n\n static async create<T extends t.BaseGraphState>(config: t.RunConfig): Promise<Run<T>> {\n return new Run<T>(config);\n }\n\n getRunMessages(): BaseMessage[] | undefined {\n if (!this.Graph) {\n throw new Error('Graph not initialized. Make sure to use Run.create() to instantiate the Run.');\n }\n return this.Graph.getRunMessages();\n }\n\n async processStream(\n inputs: t.IState,\n config: Partial<RunnableConfig> & { version: 'v1' | 'v2'; run_id?: string },\n streamOptions?: t.EventStreamOptions,\n ): Promise<MessageContentComplex[] | undefined> {\n if (!this.graphRunnable) {\n throw new Error('Run not initialized. Make sure to use Run.create() to instantiate the Run.');\n }\n if (!this.Graph) {\n throw new Error('Graph not initialized. Make sure to use Run.create() to instantiate the Run.');\n }\n\n this.Graph.resetValues(streamOptions?.keepContent);\n const provider = this.Graph.provider;\n const hasTools = this.Graph.tools ? this.Graph.tools.length > 0 : false;\n if (streamOptions?.callbacks) {\n /* TODO: conflicts with callback manager */\n const callbacks = config.callbacks as t.ProvidedCallbacks ?? [];\n config.callbacks = callbacks.concat(this.getCallbacks(streamOptions.callbacks));\n }\n\n if (!this.id) {\n throw new Error('Run ID not provided');\n }\n\n config.run_id = this.id;\n config.configurable = Object.assign(config.configurable ?? {}, { run_id: this.id, provider: this.provider });\n\n const stream = this.graphRunnable.streamEvents(inputs, config);\n\n for await (const event of stream) {\n const { data, name, metadata, ...info } = event;\n\n let eventName: t.EventName = info.event;\n if (hasTools && manualToolStreamProviders.has(provider) && eventName === GraphEvents.CHAT_MODEL_STREAM) {\n /* Skipping CHAT_MODEL_STREAM event due to double-call edge case */\n continue;\n }\n\n if (eventName && eventName === GraphEvents.ON_CUSTOM_EVENT) {\n eventName = name;\n }\n\n const handler = this.handlerRegistry.getHandler(eventName);\n if (handler) {\n handler.handle(eventName, data, metadata, this.Graph);\n }\n }\n\n if (this.returnContent) {\n return this.Graph.getContentParts();\n }\n }\n\n private createSystemCallback<K extends keyof ClientCallbacks>(\n clientCallbacks: ClientCallbacks,\n key: K\n ): SystemCallbacks[K] {\n return ((...args: unknown[]) => {\n const clientCallback = clientCallbacks[key];\n if (clientCallback && this.Graph) {\n (clientCallback as (...args: unknown[]) => void)(this.Graph, ...args);\n }\n }) as SystemCallbacks[K];\n }\n\n getCallbacks(clientCallbacks: ClientCallbacks): SystemCallbacks {\n return {\n [Callback.TOOL_ERROR]: this.createSystemCallback(clientCallbacks, Callback.TOOL_ERROR),\n [Callback.TOOL_START]: this.createSystemCallback(clientCallbacks, Callback.TOOL_START),\n [Callback.TOOL_END]: this.createSystemCallback(clientCallbacks, Callback.TOOL_END),\n };\n }\n\n async generateTitle({\n inputText,\n contentParts,\n titlePrompt,\n clientOptions,\n chainOptions,\n skipLanguage,\n } : {\n inputText: string;\n contentParts: (t.MessageContentComplex | undefined)[];\n titlePrompt?: string;\n skipLanguage?: boolean;\n clientOptions?: t.ClientOptions;\n chainOptions?: Partial<RunnableConfig> | undefined;\n }): Promise<{ language: string; title: string }> {\n const convoTemplate = PromptTemplate.fromTemplate('User: {input}\\nAI: {output}');\n const response = contentParts.map((part) => {\n if (part?.type === 'text') return part.text;\n return '';\n }).join('\\n');\n const convo = (await convoTemplate.invoke({ input: inputText, output: response })).value;\n const model = this.Graph?.getNewModel({\n clientOptions,\n omitOriginalOptions: ['streaming'],\n });\n if (!model) {\n return { language: '', title: '' };\n }\n if (isOpenAILike(this.provider) && (model instanceof ChatOpenAI || model instanceof AzureChatOpenAI)) {\n model.temperature = (clientOptions as t.OpenAIClientOptions | undefined)?.temperature as number;\n model.topP = (clientOptions as t.OpenAIClientOptions | undefined)?.topP as number;\n model.frequencyPenalty = (clientOptions as t.OpenAIClientOptions | undefined)?.frequencyPenalty as number;\n model.presencePenalty = (clientOptions as t.OpenAIClientOptions | undefined)?.presencePenalty as number;\n model.n = (clientOptions as t.OpenAIClientOptions | undefined)?.n as number;\n }\n const chain = await createTitleRunnable(model, titlePrompt);\n return await chain.invoke({ convo, inputText, skipLanguage }, chainOptions) as { language: string; title: string };\n }\n}\n"],"names":[],"mappings":";;;;;;;;;AAAA;MAca,GAAG,CAAA;AACd,IAAA,aAAa,CAA6C;;;AAGlD,IAAA,eAAe,CAAkB;AACzC,IAAA,EAAE,CAAS;AACX,IAAA,KAAK,CAA4B;AACjC,IAAA,QAAQ,CAAwB;IAChC,aAAa,GAAY,KAAK,CAAC;AAE/B,IAAA,WAAA,CAAoB,MAA4B,EAAA;AAC9C,QAAA,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,IAAI,EAAE,CAAC;QACjC,IAAI,CAAC,KAAK,EAAE;AACV,YAAA,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;SACxC;AAED,QAAA,IAAI,CAAC,EAAE,GAAG,KAAK,CAAC;AAEhB,QAAA,MAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC;AAE9C,QAAA,IAAI,MAAM,CAAC,cAAc,EAAE;AACzB,YAAA,KAAK,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,cAAc,CAAC,EAAE;AACxE,gBAAA,eAAe,CAAC,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;aAC9C;SACF;AAED,QAAA,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;AAEvC,QAAA,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE;AACvB,YAAA,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;SAC9C;AAED,QAAA,IAAI,MAAM,CAAC,WAAW,CAAC,IAAI,KAAK,UAAU,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,EAAE;YACtE,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,WAAW,CAAC,SAAS,CAAC,QAAQ,CAAC;YACtD,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,mBAAmB,CAAC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D,EAAE,eAAyB,CAAC;AACxG,YAAA,KAAK,CAAC,CAAC,GAAI,aAAmD,EAAE,CAAW,CAAC;SAC7E;QACD,MAAM,KAAK,GAAG,MAAM,mBAAmB,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;AAC5D,QAAA,OAAO,MAAM,KAAK,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,EAAE,YAAY,CAAwC,CAAC;KACpH;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"run.mjs","sources":["../../src/run.ts"],"sourcesContent":["// src/run.ts\nimport { PromptTemplate } from '@langchain/core/prompts';\nimport { AzureChatOpenAI, ChatOpenAI } from '@langchain/openai';\nimport type { BaseMessage, MessageContentComplex } from '@langchain/core/messages';\nimport type { ClientCallbacks, SystemCallbacks } from '@/graphs/Graph';\nimport type { RunnableConfig } from '@langchain/core/runnables';\nimport type * as t from '@/types';\nimport { GraphEvents, Providers, Callback } from '@/common';\nimport { manualToolStreamProviders } from '@/llm/providers';\nimport { createTitleRunnable } from '@/utils/title';\nimport { StandardGraph } from '@/graphs/Graph';\nimport { HandlerRegistry } from '@/events';\nimport { isOpenAILike } from '@/utils/llm';\n\nexport class Run<T extends t.BaseGraphState> {\n graphRunnable?: t.CompiledWorkflow<T, Partial<T>, string>;\n // private collab!: CollabGraph;\n // private taskManager!: TaskManager;\n private handlerRegistry: HandlerRegistry;\n id: string;\n Graph: StandardGraph | undefined;\n provider: Providers | undefined;\n returnContent: boolean = false;\n\n private constructor(config: Partial<t.RunConfig>) {\n const runId = config.runId ?? '';\n if (!runId) {\n throw new Error('Run ID not provided');\n }\n\n this.id = runId;\n\n const handlerRegistry = new HandlerRegistry();\n\n if (config.customHandlers) {\n for (const [eventType, handler] of Object.entries(config.customHandlers)) {\n handlerRegistry.register(eventType, handler);\n }\n }\n\n this.handlerRegistry = handlerRegistry;\n\n if (!config.graphConfig) {\n throw new Error('Graph config not provided');\n }\n\n if (config.graphConfig.type === 'standard' || !config.graphConfig.type) {\n this.provider = config.graphConfig.llmConfig.provider;\n this.graphRunnable = this.createStandardGraph(config.graphConfig) as unknown as t.CompiledWorkflow<T, Partial<T>, string>;\n if (this.Graph) {\n this.Graph.handlerRegistry = handlerRegistry;\n }\n }\n\n this.returnContent = config.returnContent ?? false;\n }\n\n private createStandardGraph(config: t.StandardGraphConfig): t.CompiledWorkflow<t.IState, Partial<t.IState>, string> {\n const { llmConfig, instructions, additional_instructions, signal, streamBuffer, toolEnd, tools = [] } = config;\n const { provider, ...clientOptions } = llmConfig;\n\n const standardGraph = new StandardGraph({\n runId: this.id,\n tools,\n provider,\n signal,\n instructions,\n clientOptions,\n additional_instructions,\n streamBuffer,\n toolEnd,\n });\n this.Graph = standardGraph;\n return standardGraph.createWorkflow();\n }\n\n static async create<T extends t.BaseGraphState>(config: t.RunConfig): Promise<Run<T>> {\n return new Run<T>(config);\n }\n\n getRunMessages(): BaseMessage[] | undefined {\n if (!this.Graph) {\n throw new Error('Graph not initialized. Make sure to use Run.create() to instantiate the Run.');\n }\n return this.Graph.getRunMessages();\n }\n\n async processStream(\n inputs: t.IState,\n config: Partial<RunnableConfig> & { version: 'v1' | 'v2'; run_id?: string },\n streamOptions?: t.EventStreamOptions,\n ): Promise<MessageContentComplex[] | undefined> {\n if (!this.graphRunnable) {\n throw new Error('Run not initialized. Make sure to use Run.create() to instantiate the Run.');\n }\n if (!this.Graph) {\n throw new Error('Graph not initialized. Make sure to use Run.create() to instantiate the Run.');\n }\n\n this.Graph.resetValues(streamOptions?.keepContent);\n const provider = this.Graph.provider;\n const hasTools = this.Graph.tools ? this.Graph.tools.length > 0 : false;\n if (streamOptions?.callbacks) {\n /* TODO: conflicts with callback manager */\n const callbacks = config.callbacks as t.ProvidedCallbacks ?? [];\n config.callbacks = callbacks.concat(this.getCallbacks(streamOptions.callbacks));\n }\n\n if (!this.id) {\n throw new Error('Run ID not provided');\n }\n\n config.run_id = this.id;\n config.configurable = Object.assign(config.configurable ?? {}, { run_id: this.id, provider: this.provider });\n\n const stream = this.graphRunnable.streamEvents(inputs, config);\n\n for await (const event of stream) {\n const { data, name, metadata, ...info } = event;\n\n let eventName: t.EventName = info.event;\n if (hasTools && manualToolStreamProviders.has(provider) && eventName === GraphEvents.CHAT_MODEL_STREAM) {\n /* Skipping CHAT_MODEL_STREAM event due to double-call edge case */\n continue;\n }\n\n if (eventName && eventName === GraphEvents.ON_CUSTOM_EVENT) {\n eventName = name;\n }\n\n const handler = this.handlerRegistry.getHandler(eventName);\n if (handler) {\n handler.handle(eventName, data, metadata, this.Graph);\n }\n }\n\n if (this.returnContent) {\n return this.Graph.getContentParts();\n }\n }\n\n private createSystemCallback<K extends keyof ClientCallbacks>(\n clientCallbacks: ClientCallbacks,\n key: K\n ): SystemCallbacks[K] {\n return ((...args: unknown[]) => {\n const clientCallback = clientCallbacks[key];\n if (clientCallback && this.Graph) {\n (clientCallback as (...args: unknown[]) => void)(this.Graph, ...args);\n }\n }) as SystemCallbacks[K];\n }\n\n getCallbacks(clientCallbacks: ClientCallbacks): SystemCallbacks {\n return {\n [Callback.TOOL_ERROR]: this.createSystemCallback(clientCallbacks, Callback.TOOL_ERROR),\n [Callback.TOOL_START]: this.createSystemCallback(clientCallbacks, Callback.TOOL_START),\n [Callback.TOOL_END]: this.createSystemCallback(clientCallbacks, Callback.TOOL_END),\n };\n }\n\n async generateTitle({\n inputText,\n contentParts,\n titlePrompt,\n clientOptions,\n chainOptions,\n skipLanguage,\n } : {\n inputText: string;\n contentParts: (t.MessageContentComplex | undefined)[];\n titlePrompt?: string;\n skipLanguage?: boolean;\n clientOptions?: t.ClientOptions;\n chainOptions?: Partial<RunnableConfig> | undefined;\n }): Promise<{ language: string; title: string }> {\n const convoTemplate = PromptTemplate.fromTemplate('User: {input}\\nAI: {output}');\n const response = contentParts.map((part) => {\n if (part?.type === 'text') return part.text;\n return '';\n }).join('\\n');\n const convo = (await convoTemplate.invoke({ input: inputText, output: response })).value;\n const model = this.Graph?.getNewModel({\n clientOptions,\n omitOriginalOptions: ['streaming'],\n });\n if (!model) {\n return { language: '', title: '' };\n }\n if (isOpenAILike(this.provider) && (model instanceof ChatOpenAI || model instanceof AzureChatOpenAI)) {\n model.temperature = (clientOptions as t.OpenAIClientOptions | undefined)?.temperature as number;\n model.topP = (clientOptions as t.OpenAIClientOptions | undefined)?.topP as number;\n model.frequencyPenalty = (clientOptions as t.OpenAIClientOptions | undefined)?.frequencyPenalty as number;\n model.presencePenalty = (clientOptions as t.OpenAIClientOptions | undefined)?.presencePenalty as number;\n model.n = (clientOptions as t.OpenAIClientOptions | undefined)?.n as number;\n }\n const chain = await createTitleRunnable(model, titlePrompt);\n return await chain.invoke({ convo, inputText, skipLanguage }, chainOptions) as { language: string; title: string };\n }\n}\n"],"names":[],"mappings":";;;;;;;;;AAAA;MAca,GAAG,CAAA;AACd,IAAA,aAAa;;;AAGL,IAAA,eAAe;AACvB,IAAA,EAAE;AACF,IAAA,KAAK;AACL,IAAA,QAAQ;IACR,aAAa,GAAY,KAAK;AAE9B,IAAA,WAAA,CAAoB,MAA4B,EAAA;AAC9C,QAAA,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,IAAI,EAAE;QAChC,IAAI,CAAC,KAAK,EAAE;AACV,YAAA,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC;;AAGxC,QAAA,IAAI,CAAC,EAAE,GAAG,KAAK;AAEf,QAAA,MAAM,eAAe,GAAG,IAAI,eAAe,EAAE;AAE7C,QAAA,IAAI,MAAM,CAAC,cAAc,EAAE;AACzB,YAAA,KAAK,MAAM,CAAC,SAAS,EAAE,OAAO,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,cAAc,CAAC,EAAE;AACxE,gBAAA,eAAe,CAAC,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;;;AAIhD,QAAA,IAAI,CAAC,eAAe,GAAG,eAAe;AAEtC,QAAA,IAAI,CAAC,MAAM,CAAC,WAAW,EAAE;AACvB,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,CAAC,GAAI,aAAmD,EAAE,CAAW;;QAE7E,MAAM,KAAK,GAAG,MAAM,mBAAmB,CAAC,KAAK,EAAE,WAAW,CAAC;AAC3D,QAAA,OAAO,MAAM,KAAK,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,EAAE,YAAY,CAAwC;;AAErH;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"splitStream.mjs","sources":["../../src/splitStream.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport type * as t from '@/types';\nimport { ContentTypes, GraphEvents, StepTypes } from '@/common';\n\nexport const SEPARATORS = ['.', '?', '!', '۔', '。', '‥', ';', '¡', '¿', '\\n', '```'];\n\nexport class SplitStreamHandler {\n private inCodeBlock = false;\n private inThinkBlock = false;\n private accumulate: boolean;\n tokens: string[] = [];\n lastToken = '';\n reasoningTokens: string[] = [];\n currentStepId?: string;\n currentMessageId?: string;\n currentType?: ContentTypes.TEXT | ContentTypes.THINK;\n currentLength = 0;\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n currentIndex = -1;\n blockThreshold = 4500;\n /** The run ID AKA the Message ID associated with the complete generation */\n runId: string;\n handlers?: t.SplitStreamHandlers;\n constructor({\n runId,\n handlers,\n accumulate,\n reasoningKey,\n blockThreshold,\n }: {\n runId: string,\n accumulate?: boolean,\n handlers: t.SplitStreamHandlers\n blockThreshold?: number,\n reasoningKey?: 'reasoning_content' | 'reasoning',\n }) {\n this.runId = runId;\n this.handlers = handlers;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (blockThreshold != null) {\n this.blockThreshold = blockThreshold;\n }\n this.accumulate = accumulate ?? false;\n }\n getMessageId = (): string | undefined => {\n const messageId = this.currentMessageId;\n if (messageId != null && messageId) {\n return messageId;\n }\n return undefined;\n };\n createMessageStep = (type?: ContentTypes.TEXT | ContentTypes.THINK): [string, string] => {\n if (type != null && this.currentType !== type) {\n this.currentType = type;\n }\n this.currentLength = 0;\n this.currentIndex += 1;\n this.currentStepId = `step_${nanoid()}`;\n this.currentMessageId = `msg_${nanoid()}`;\n return [this.currentStepId, this.currentMessageId];\n };\n dispatchRunStep = (stepId: string, stepDetails: t.StepDetails): void => {\n const runStep: t.RunStep = {\n id: stepId,\n runId: this.runId,\n type: stepDetails.type,\n index: this.currentIndex,\n stepDetails,\n // usage: null,\n };\n this.handlers?.[GraphEvents.ON_RUN_STEP]?.({ event: GraphEvents.ON_RUN_STEP, data: runStep });\n };\n dispatchMessageDelta = (stepId: string, delta: t.MessageDelta): void => {\n const messageDelta: t.MessageDeltaEvent = {\n id: stepId,\n delta,\n };\n this.handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.({ event: GraphEvents.ON_MESSAGE_DELTA, data: messageDelta });\n };\n dispatchReasoningDelta = (stepId: string, delta: t.ReasoningDelta): void => {\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n this.handlers?.[GraphEvents.ON_REASONING_DELTA]?.({ event: GraphEvents.ON_REASONING_DELTA, data: reasoningDelta });\n };\n handleContent = (content: string, _type: ContentTypes.TEXT | ContentTypes.THINK): void => {\n let type = _type;\n if (this.inThinkBlock && type === ContentTypes.TEXT) {\n type = ContentTypes.THINK;\n }\n if (this.accumulate) {\n if (type === ContentTypes.THINK) {\n this.reasoningTokens.push(content);\n } else {\n this.tokens.push(content);\n }\n }\n\n if (this.currentType !== type) {\n const [newStepId, newMessageId] = this.createMessageStep(type);\n this.dispatchRunStep(newStepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: newMessageId,\n },\n });\n }\n\n const stepId = this.currentStepId ?? '';\n if (type === ContentTypes.THINK) {\n this.dispatchReasoningDelta(stepId, {\n content: [{\n type: ContentTypes.THINK,\n think: content,\n }],\n });\n } else {\n this.dispatchMessageDelta(stepId, {\n content: [{\n type: ContentTypes.TEXT,\n text: content,\n }],\n });\n }\n\n this.currentLength += content.length;\n if (this.inCodeBlock) {\n return;\n }\n\n if (this.currentLength > this.blockThreshold && SEPARATORS.some(sep => content.includes(sep))) {\n const [newStepId, newMessageId] = this.createMessageStep(type);\n this.dispatchRunStep(newStepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: newMessageId,\n },\n });\n }\n };\n handle(chunk?: t.CustomChunk): void {\n if (!chunk) {\n return;\n }\n\n const content = chunk.choices?.[0]?.delta.content ?? '';\n const reasoning_content = chunk.choices?.[0]?.delta[this.reasoningKey] ?? '';\n\n if (!content.length && !reasoning_content.length) {\n return;\n }\n\n if (content.includes('```')) {\n this.inCodeBlock = !this.inCodeBlock;\n }\n\n if (content.includes('<think>') && !this.inCodeBlock) {\n this.inThinkBlock = true;\n } else if (this.lastToken.includes('</think>') && !this.inCodeBlock) {\n this.inThinkBlock = false;\n }\n\n this.lastToken = content;\n\n const message_id = this.getMessageId() ?? '';\n\n if (!message_id) {\n const initialContentType = this.inThinkBlock ? ContentTypes.THINK : ContentTypes.TEXT;\n const initialType = reasoning_content ? ContentTypes.THINK : initialContentType;\n const [stepId, message_id] = this.createMessageStep(initialType);\n this.dispatchRunStep(stepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n if (reasoning_content) {\n this.handleContent(reasoning_content, ContentTypes.THINK);\n } else {\n this.handleContent(content, ContentTypes.TEXT);\n }\n }\n}"],"names":[],"mappings":";;;AAIa,MAAA,UAAU,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE;MAExE,kBAAkB,CAAA;IACrB,WAAW,GAAG,KAAK,CAAC;IACpB,YAAY,GAAG,KAAK,CAAC;AACrB,IAAA,UAAU,CAAU;IAC5B,MAAM,GAAa,EAAE,CAAC;IACtB,SAAS,GAAG,EAAE,CAAC;IACf,eAAe,GAAa,EAAE,C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WAAW,EAAE;AACpD,YAAA,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;SAC1B;AAAM,aAAA,IAAI,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE;AACnE,YAAA,IAAI,CAAC,YAAY,GAAG,KAAK,CAAC;SAC3B;AAED,QAAA,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC;QAEzB,MAAM,UAAU,GAAG,IAAI,CAAC,YAAY,EAAE,IAAI,EAAE,CAAC;QAE7C,IAAI,CAAC,UAAU,EAAE;AACf,YAAA,MAAM,kBAAkB,GAAG,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC,KAAK,GAAG,YAAY,CAAC,IAAI,CAAC;AACtF,YAAA,MAAM,WAAW,GAAG,iBAAiB,GAAG,YAAY,CAAC,KAAK,GAAG,kBAAkB,CAAC;AAChF,YAAA,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,GAAG,IAAI,CAAC,iBAAiB,CAAC,WAAW,CAAC,CAAC;AACjE,YAAA,IAAI,CAAC,eAAe,CAAC,MAAM,EAAE;gBAC3B,IAAI,EAAE,SAAS,CAAC,gBAAgB;AAChC,gBAAA,gBAAgB,EAAE;oBAChB,UAAU;AACX,iBAAA;AACF,aAAA,CAAC,CAAC;SACJ;QAED,IAAI,iBAAiB,EAAE;YACrB,IAAI,CAAC,aAAa,CAAC,iBAAiB,EAAE,YAAY,CAAC,KAAK,CAAC,CAAC;SAC3D;aAAM;YACL,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,YAAY,CAAC,IAAI,CAAC,CAAC;SAChD;KACF;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"splitStream.mjs","sources":["../../src/splitStream.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport type * as t from '@/types';\nimport { ContentTypes, GraphEvents, StepTypes } from '@/common';\n\nexport const SEPARATORS = ['.', '?', '!', '۔', '。', '‥', ';', '¡', '¿', '\\n', '```'];\n\nexport class SplitStreamHandler {\n private inCodeBlock = false;\n private inThinkBlock = false;\n private accumulate: boolean;\n tokens: string[] = [];\n lastToken = '';\n reasoningTokens: string[] = [];\n currentStepId?: string;\n currentMessageId?: string;\n currentType?: ContentTypes.TEXT | ContentTypes.THINK;\n currentLength = 0;\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n currentIndex = -1;\n blockThreshold = 4500;\n /** The run ID AKA the Message ID associated with the complete generation */\n runId: string;\n handlers?: t.SplitStreamHandlers;\n constructor({\n runId,\n handlers,\n accumulate,\n reasoningKey,\n blockThreshold,\n }: {\n runId: string,\n accumulate?: boolean,\n handlers: t.SplitStreamHandlers\n blockThreshold?: number,\n reasoningKey?: 'reasoning_content' | 'reasoning',\n }) {\n this.runId = runId;\n this.handlers = handlers;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (blockThreshold != null) {\n this.blockThreshold = blockThreshold;\n }\n this.accumulate = accumulate ?? false;\n }\n getMessageId = (): string | undefined => {\n const messageId = this.currentMessageId;\n if (messageId != null && messageId) {\n return messageId;\n }\n return undefined;\n };\n createMessageStep = (type?: ContentTypes.TEXT | ContentTypes.THINK): [string, string] => {\n if (type != null && this.currentType !== type) {\n this.currentType = type;\n }\n this.currentLength = 0;\n this.currentIndex += 1;\n this.currentStepId = `step_${nanoid()}`;\n this.currentMessageId = `msg_${nanoid()}`;\n return [this.currentStepId, this.currentMessageId];\n };\n dispatchRunStep = (stepId: string, stepDetails: t.StepDetails): void => {\n const runStep: t.RunStep = {\n id: stepId,\n runId: this.runId,\n type: stepDetails.type,\n index: this.currentIndex,\n stepDetails,\n // usage: null,\n };\n this.handlers?.[GraphEvents.ON_RUN_STEP]?.({ event: GraphEvents.ON_RUN_STEP, data: runStep });\n };\n dispatchMessageDelta = (stepId: string, delta: t.MessageDelta): void => {\n const messageDelta: t.MessageDeltaEvent = {\n id: stepId,\n delta,\n };\n this.handlers?.[GraphEvents.ON_MESSAGE_DELTA]?.({ event: GraphEvents.ON_MESSAGE_DELTA, data: messageDelta });\n };\n dispatchReasoningDelta = (stepId: string, delta: t.ReasoningDelta): void => {\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n this.handlers?.[GraphEvents.ON_REASONING_DELTA]?.({ event: GraphEvents.ON_REASONING_DELTA, data: reasoningDelta });\n };\n handleContent = (content: string, _type: ContentTypes.TEXT | ContentTypes.THINK): void => {\n let type = _type;\n if (this.inThinkBlock && type === ContentTypes.TEXT) {\n type = ContentTypes.THINK;\n }\n if (this.accumulate) {\n if (type === ContentTypes.THINK) {\n this.reasoningTokens.push(content);\n } else {\n this.tokens.push(content);\n }\n }\n\n if (this.currentType !== type) {\n const [newStepId, newMessageId] = this.createMessageStep(type);\n this.dispatchRunStep(newStepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: newMessageId,\n },\n });\n }\n\n const stepId = this.currentStepId ?? '';\n if (type === ContentTypes.THINK) {\n this.dispatchReasoningDelta(stepId, {\n content: [{\n type: ContentTypes.THINK,\n think: content,\n }],\n });\n } else {\n this.dispatchMessageDelta(stepId, {\n content: [{\n type: ContentTypes.TEXT,\n text: content,\n }],\n });\n }\n\n this.currentLength += content.length;\n if (this.inCodeBlock) {\n return;\n }\n\n if (this.currentLength > this.blockThreshold && SEPARATORS.some(sep => content.includes(sep))) {\n const [newStepId, newMessageId] = this.createMessageStep(type);\n this.dispatchRunStep(newStepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: newMessageId,\n },\n });\n }\n };\n handle(chunk?: t.CustomChunk): void {\n if (!chunk) {\n return;\n }\n\n const content = chunk.choices?.[0]?.delta.content ?? '';\n const reasoning_content = chunk.choices?.[0]?.delta[this.reasoningKey] ?? '';\n\n if (!content.length && !reasoning_content.length) {\n return;\n }\n\n if (content.includes('```')) {\n this.inCodeBlock = !this.inCodeBlock;\n }\n\n if (content.includes('<think>') && !this.inCodeBlock) {\n this.inThinkBlock = true;\n } else if (this.lastToken.includes('</think>') && !this.inCodeBlock) {\n this.inThinkBlock = false;\n }\n\n this.lastToken = content;\n\n const message_id = this.getMessageId() ?? '';\n\n if (!message_id) {\n const initialContentType = this.inThinkBlock ? ContentTypes.THINK : ContentTypes.TEXT;\n const initialType = reasoning_content ? ContentTypes.THINK : initialContentType;\n const [stepId, message_id] = this.createMessageStep(initialType);\n this.dispatchRunStep(stepId, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n if (reasoning_content) {\n this.handleContent(reasoning_content, ContentTypes.THINK);\n } else {\n this.handleContent(content, ContentTypes.TEXT);\n }\n }\n}"],"names":[],"mappings":";;;AAIa,MAAA,UAAU,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,KAAK;MAEtE,kBAAkB,CAAA;IACrB,WAAW,GAAG,KAAK;IACnB,YAAY,GAAG,KAAK;AACpB,IAAA,UAAU;IAClB,MAAM,GAAa,EAAE;IACrB,SAAS,GAAG,EAAE;IACd,eAAe,GAAa,EAAE;AAC9B,IAAA,aAAa;AACb,IAAA,gBAAgB;AAChB,IAAA,WAAW;IACX,aAAa,GAAG,CAAC;IACjB,YAAY,GAAsC,mBAAmB;IACrE,YAAY,GAAG,EAAE;IACjB,cAAc,GAAG,IAAI;;AAErB,IAAA,KAAK;AACL,IAAA,QAAQ;IACR,WAAY,CAAA,EACV,KAAK,EACL,QAAQ,EACR,UAAU,EACV,YAAY,EACZ,cAAc,GAOb,EAAA;AACD,QAAA,IAAI,CAAC,KAAK,GAAG,KAAK;AAClB,QAAA,IAAI,CAAC,QAAQ,GAAG,QAAQ;QACxB,IAAI,YAAY,EAAE;AAChB,YAAA,IAAI,CAAC,YAAY,GAAG,YAAY;;AAElC,QAAA,IAAI,cAAc,IAAI,IAAI,EAAE;AAC1B,YAAA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AI,CAAC,aAAa,CAAC,OAAO,EAAE,YAAY,CAAC,IAAI,CAAC;;;AAGnD;;;;"}
|
package/dist/esm/stream.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { nanoid } from 'nanoid';
|
|
2
|
-
import { StepTypes,
|
|
2
|
+
import { StepTypes, ContentTypes, ToolCallTypes, GraphEvents } from './common/enum.mjs';
|
|
3
3
|
|
|
4
4
|
// src/stream.ts
|
|
5
5
|
function getNonEmptyValue(possibleValues) {
|
|
@@ -69,6 +69,7 @@ const handleToolCalls = (toolCalls, metadata, graph) => {
|
|
|
69
69
|
/* If the previous step exists and is a message creation */
|
|
70
70
|
if (prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION) {
|
|
71
71
|
dispatchToolCallIds(prevStepId);
|
|
72
|
+
graph.messageStepHasToolCalls.set(prevStepId, true);
|
|
72
73
|
/* If the previous step doesn't exist or is not a message creation */
|
|
73
74
|
}
|
|
74
75
|
else if (!prevRunStep || prevRunStep.type !== StepTypes.MESSAGE_CREATION) {
|
|
@@ -80,6 +81,7 @@ const handleToolCalls = (toolCalls, metadata, graph) => {
|
|
|
80
81
|
},
|
|
81
82
|
});
|
|
82
83
|
dispatchToolCallIds(stepId);
|
|
84
|
+
graph.messageStepHasToolCalls.set(prevStepId, true);
|
|
83
85
|
}
|
|
84
86
|
graph.dispatchRunStep(stepKey, {
|
|
85
87
|
type: StepTypes.TOOL_CALLS,
|
|
@@ -91,21 +93,22 @@ class ChatModelStreamHandler {
|
|
|
91
93
|
if (!graph) {
|
|
92
94
|
throw new Error('Graph not found');
|
|
93
95
|
}
|
|
94
|
-
const chunk = data.chunk;
|
|
95
|
-
const content = chunk?.content;
|
|
96
96
|
if (!graph.config) {
|
|
97
97
|
throw new Error('Config not found in graph');
|
|
98
98
|
}
|
|
99
|
-
if (!chunk) {
|
|
99
|
+
if (!data.chunk) {
|
|
100
100
|
console.warn(`No chunk found in ${event} event`);
|
|
101
101
|
return;
|
|
102
102
|
}
|
|
103
|
+
const chunk = data.chunk;
|
|
104
|
+
const content = chunk.additional_kwargs?.[graph.reasoningKey] ?? chunk.content;
|
|
105
|
+
this.handleReasoning(chunk, graph);
|
|
103
106
|
let hasToolCalls = false;
|
|
104
|
-
const hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;
|
|
105
107
|
if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id)) {
|
|
106
108
|
hasToolCalls = true;
|
|
107
109
|
handleToolCalls(chunk.tool_calls, metadata, graph);
|
|
108
110
|
}
|
|
111
|
+
const hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;
|
|
109
112
|
const isEmptyContent = typeof content === 'undefined' || !content.length || typeof content === 'string' && !content;
|
|
110
113
|
const isEmptyChunk = isEmptyContent && !hasToolCallChunks;
|
|
111
114
|
const chunkId = chunk.id ?? '';
|
|
@@ -128,13 +131,7 @@ class ChatModelStreamHandler {
|
|
|
128
131
|
&& chunk.tool_call_chunks
|
|
129
132
|
&& chunk.tool_call_chunks.length
|
|
130
133
|
&& typeof chunk.tool_call_chunks[0]?.index === 'number') {
|
|
131
|
-
|
|
132
|
-
const prevRunStep = graph.getRunStep(prevStepId);
|
|
133
|
-
const stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);
|
|
134
|
-
graph.dispatchRunStepDelta(stepId, {
|
|
135
|
-
type: StepTypes.TOOL_CALLS,
|
|
136
|
-
tool_calls: chunk.tool_call_chunks,
|
|
137
|
-
});
|
|
134
|
+
this.handleToolCallChunks({ graph, stepKey, toolCallChunks: chunk.tool_call_chunks });
|
|
138
135
|
}
|
|
139
136
|
if (isEmptyContent) {
|
|
140
137
|
return;
|
|
@@ -177,18 +174,98 @@ hasToolCallChunks: ${hasToolCallChunks}
|
|
|
177
174
|
return;
|
|
178
175
|
}
|
|
179
176
|
else if (typeof content === 'string') {
|
|
177
|
+
if (graph.currentTokenType === ContentTypes.TEXT) {
|
|
178
|
+
graph.dispatchMessageDelta(stepId, {
|
|
179
|
+
content: [{
|
|
180
|
+
type: ContentTypes.TEXT,
|
|
181
|
+
text: content,
|
|
182
|
+
}],
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
else {
|
|
186
|
+
graph.dispatchReasoningDelta(stepId, {
|
|
187
|
+
content: [{
|
|
188
|
+
type: ContentTypes.THINK,
|
|
189
|
+
think: content,
|
|
190
|
+
}],
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
else if (content.every((c) => c.type?.startsWith(ContentTypes.TEXT))) {
|
|
180
195
|
graph.dispatchMessageDelta(stepId, {
|
|
196
|
+
content,
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
handleToolCallChunks = ({ graph, stepKey, toolCallChunks, }) => {
|
|
201
|
+
const prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);
|
|
202
|
+
const prevRunStep = graph.getRunStep(prevStepId);
|
|
203
|
+
const _stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);
|
|
204
|
+
/** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */
|
|
205
|
+
const tool_calls = prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION
|
|
206
|
+
? []
|
|
207
|
+
: undefined;
|
|
208
|
+
/** Edge Case: `id` and `name` fields cannot be empty strings */
|
|
209
|
+
for (const toolCallChunk of toolCallChunks) {
|
|
210
|
+
if (toolCallChunk.name === '') {
|
|
211
|
+
toolCallChunk.name = undefined;
|
|
212
|
+
}
|
|
213
|
+
if (toolCallChunk.id === '') {
|
|
214
|
+
toolCallChunk.id = undefined;
|
|
215
|
+
}
|
|
216
|
+
else if (tool_calls != null && toolCallChunk.id != null && toolCallChunk.name != null) {
|
|
217
|
+
tool_calls.push({
|
|
218
|
+
args: {},
|
|
219
|
+
id: toolCallChunk.id,
|
|
220
|
+
name: toolCallChunk.name,
|
|
221
|
+
type: ToolCallTypes.TOOL_CALL,
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
let stepId = _stepId;
|
|
226
|
+
const alreadyDispatched = prevRunStep?.type === StepTypes.MESSAGE_CREATION && graph.messageStepHasToolCalls.has(prevStepId);
|
|
227
|
+
if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {
|
|
228
|
+
graph.dispatchMessageDelta(prevStepId, {
|
|
181
229
|
content: [{
|
|
182
|
-
type:
|
|
183
|
-
text:
|
|
230
|
+
type: ContentTypes.TEXT,
|
|
231
|
+
text: '',
|
|
232
|
+
tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),
|
|
184
233
|
}],
|
|
185
234
|
});
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
235
|
+
graph.messageStepHasToolCalls.set(prevStepId, true);
|
|
236
|
+
stepId = graph.dispatchRunStep(stepKey, {
|
|
237
|
+
type: StepTypes.TOOL_CALLS,
|
|
238
|
+
tool_calls,
|
|
190
239
|
});
|
|
191
240
|
}
|
|
241
|
+
graph.dispatchRunStepDelta(stepId, {
|
|
242
|
+
type: StepTypes.TOOL_CALLS,
|
|
243
|
+
tool_calls: toolCallChunks,
|
|
244
|
+
});
|
|
245
|
+
};
|
|
246
|
+
handleReasoning(chunk, graph) {
|
|
247
|
+
const reasoning_content = chunk.additional_kwargs?.[graph.reasoningKey];
|
|
248
|
+
if (reasoning_content != null && reasoning_content && (chunk.content == null || chunk.content === '')) {
|
|
249
|
+
graph.currentTokenType = ContentTypes.THINK;
|
|
250
|
+
graph.tokenTypeSwitch = 'reasoning';
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
else if (graph.tokenTypeSwitch === 'reasoning' && graph.currentTokenType !== ContentTypes.TEXT && chunk.content != null && chunk.content !== '') {
|
|
254
|
+
graph.currentTokenType = ContentTypes.TEXT;
|
|
255
|
+
graph.tokenTypeSwitch = 'content';
|
|
256
|
+
}
|
|
257
|
+
else if (chunk.content != null && typeof chunk.content === 'string' && chunk.content.includes('<think>')) {
|
|
258
|
+
graph.currentTokenType = ContentTypes.THINK;
|
|
259
|
+
graph.tokenTypeSwitch = 'content';
|
|
260
|
+
}
|
|
261
|
+
else if (graph.lastToken != null && graph.lastToken.includes('</think>')) {
|
|
262
|
+
graph.currentTokenType = ContentTypes.TEXT;
|
|
263
|
+
graph.tokenTypeSwitch = 'content';
|
|
264
|
+
}
|
|
265
|
+
if (typeof chunk.content !== 'string') {
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
graph.lastToken = chunk.content;
|
|
192
269
|
}
|
|
193
270
|
}
|
|
194
271
|
function createContentAggregator() {
|
|
@@ -293,7 +370,7 @@ function createContentAggregator() {
|
|
|
293
370
|
const reasoningDelta = data;
|
|
294
371
|
const runStep = stepMap.get(reasoningDelta.id);
|
|
295
372
|
if (!runStep) {
|
|
296
|
-
console.warn('No run step or runId found for
|
|
373
|
+
console.warn('No run step or runId found for reasoning delta event');
|
|
297
374
|
return;
|
|
298
375
|
}
|
|
299
376
|
if (reasoningDelta.delta.content) {
|
|
@@ -313,12 +390,12 @@ function createContentAggregator() {
|
|
|
313
390
|
if (runStepDelta.delta.type === StepTypes.TOOL_CALLS &&
|
|
314
391
|
runStepDelta.delta.tool_calls) {
|
|
315
392
|
runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {
|
|
316
|
-
const toolCallId = toolCallIdMap.get(runStepDelta.id)
|
|
393
|
+
const toolCallId = toolCallIdMap.get(runStepDelta.id);
|
|
317
394
|
const contentPart = {
|
|
318
395
|
type: ContentTypes.TOOL_CALL,
|
|
319
396
|
tool_call: {
|
|
320
|
-
name: toolCallDelta.name ?? '',
|
|
321
397
|
args: toolCallDelta.args ?? '',
|
|
398
|
+
name: toolCallDelta.name,
|
|
322
399
|
id: toolCallId,
|
|
323
400
|
},
|
|
324
401
|
};
|
package/dist/esm/stream.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.mjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport { nanoid } from 'nanoid';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\nimport { StepTypes, ContentTypes, GraphEvents, ToolCallTypes } from '@/common';\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\nexport const getMessageId = (stepKey: string, graph: Graph<t.BaseGraphState>, returnExistingId = false): string | undefined => {\n const messageId = graph.messageIdsByStepKey.get(stepKey);\n if (messageId != null && messageId) {\n return returnExistingId ? messageId : undefined;\n }\n\n const prelimMessageId = graph.prelimMessageIdsByStepKey.get(stepKey);\n if (prelimMessageId != null && prelimMessageId) {\n graph.prelimMessageIdsByStepKey.delete(stepKey);\n graph.messageIdsByStepKey.set(stepKey, prelimMessageId);\n return prelimMessageId;\n }\n\n const message_id = `msg_${nanoid()}`;\n graph.messageIdsByStepKey.set(stepKey, message_id);\n return message_id;\n};\n\nexport const handleToolCalls = (toolCalls?: ToolCall[], metadata?: Record<string, unknown>, graph?: Graph): 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 tool_calls: ToolCall[] = [];\n const tool_call_ids: string[] = [];\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 tool_calls.push(tool_call);\n tool_call_ids.push(toolCallId);\n }\n\n const stepKey = graph.getStepKey(metadata);\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 (e) {\n // no previous step\n }\n\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\n graph.dispatchMessageDelta(lastMessageStepId, {\n content: [{\n type: 'text',\n text: '',\n tool_call_ids,\n }],\n });\n };\n /* If the previous step exists and is a message creation */\n if (prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION) {\n dispatchToolCallIds(prevStepId);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (!prevRunStep || prevRunStep.type !== StepTypes.MESSAGE_CREATION) {\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 }\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n};\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData, metadata?: Record<string, unknown>, graph?: Graph): void {\n if (!graph) {\n throw new Error('Graph not found');\n }\n\n const chunk = data.chunk as AIMessageChunk | undefined;\n const content = chunk?.content;\n\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n\n if (!chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n let hasToolCalls = false;\n const hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n\n if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id)) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const isEmptyContent = typeof content === 'undefined' || !content.length || 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 (hasToolCallChunks\n && chunk.tool_call_chunks\n && chunk.tool_call_chunks.length\n && typeof chunk.tool_call_chunks[0]?.index === 'number') {\n const prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n const prevRunStep = graph.getRunStep(prevStepId);\n const stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\n graph.dispatchRunStepDelta(stepId, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: 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 // eslint-disable-next-line no-console\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 (hasToolCallChunks && (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)) {\n return;\n } else if (typeof content === 'string') {\n graph.dispatchMessageDelta(stepId, {\n content: [{\n type: 'text',\n text: content,\n }],\n });\n } else if (content.every((c) => c.type?.startsWith('text'))) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n }\n }\n}\n\nexport type ContentAggregatorResult = {\n stepMap: Map<string, t.RunStep | undefined>;\n contentParts: Array<t.MessageContentComplex | undefined>;\n aggregateContent: ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | {\n result: t.ToolEndEvent;\n };\n}) => void\n};\n\nexport function createContentAggregator(): 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 (partType === ContentTypes.IMAGE_URL && 'image_url' in contentPart) {\n const currentContent = contentParts[index] as { type: 'image_url'; image_url: string };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (partType === ContentTypes.TOOL_CALL && 'tool_call' in contentPart) {\n const existingContent = contentParts[index] as Omit<t.ToolCallContent, 'tool_call'> & { tool_call?: ToolCall } | undefined;\n\n const args = finalUpdate\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args || '') + (contentPart.tool_call.args ?? '');\n\n const id = getNonEmptyValue([contentPart.tool_call.id, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([contentPart.tool_call.name, existingContent?.tool_call?.name]) ?? '';\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 = ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | { result: t.ToolEndEvent };\n }): void => {\n\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 (runStep.stepDetails.type === StepTypes.TOOL_CALLS && runStep.stepDetails.tool_calls) {\n runStep.stepDetails.tool_calls.forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\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 (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 message 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\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 name: toolCallDelta.name ?? '',\n args: toolCallDelta.args ?? '',\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('No run step or runId found for completed tool call event');\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\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":[],"mappings":";;;AAAA;AAQA,SAAS,gBAAgB,CAAC,cAAwB,EAAA;AAChD,IAAA,KAAK,MAAM,KAAK,IAAI,cAAc,EAAE;QAClC,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;AAChC,YAAA,OAAO,KAAK,CAAC;SACd;KACF;AACD,IAAA,OAAO,SAAS,CAAC;AACnB,CAAC;AAEM,MAAM,YAAY,GAAG,CAAC,OAAe,EAAE,KAA8B,EAAE,gBAAgB,GAAG,KAAK,KAAwB;IAC5H,MAAM,SAAS,GAAG,KAAK,CAAC,mBAAmB,CAAC,GAAG,CAAC,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AAW,CAAC,CAAC;AAC5C,iBAAC,CAAC,CAAC;aACJ;SACF;AAAM,aAAA,IAAI,KAAK,KAAK,WAAW,CAAC,qBAAqB,EAAE;AACtD,YAAA,MAAM,EAAE,MAAM,EAAE,GAAG,IAA6C,CAAC;AAEjE,YAAA,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;YAE9B,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YACpC,IAAI,CAAC,OAAO,EAAE;AACZ,gBAAA,OAAO,CAAC,IAAI,CAAC,0DAA0D,CAAC,CAAC;gBACzE,OAAO;aACR;AAED,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAE,YAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B,CAAC;YAEF,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;SACjD;AAEH,KAAC,CAAC;AAEF,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE,CAAC;AACrD;;;;"}
|
|
1
|
+
{"version":3,"file":"stream.mjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport { nanoid } from 'nanoid';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\nimport { StepTypes, ContentTypes, GraphEvents, ToolCallTypes } from '@/common';\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\nexport const getMessageId = (stepKey: string, graph: Graph<t.BaseGraphState>, returnExistingId = false): string | undefined => {\n const messageId = graph.messageIdsByStepKey.get(stepKey);\n if (messageId != null && messageId) {\n return returnExistingId ? messageId : undefined;\n }\n\n const prelimMessageId = graph.prelimMessageIdsByStepKey.get(stepKey);\n if (prelimMessageId != null && prelimMessageId) {\n graph.prelimMessageIdsByStepKey.delete(stepKey);\n graph.messageIdsByStepKey.set(stepKey, prelimMessageId);\n return prelimMessageId;\n }\n\n const message_id = `msg_${nanoid()}`;\n graph.messageIdsByStepKey.set(stepKey, message_id);\n return message_id;\n};\n\nexport const handleToolCalls = (toolCalls?: ToolCall[], metadata?: Record<string, unknown>, graph?: Graph): 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 tool_calls: ToolCall[] = [];\n const tool_call_ids: string[] = [];\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 tool_calls.push(tool_call);\n tool_call_ids.push(toolCallId);\n }\n\n const stepKey = graph.getStepKey(metadata);\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 (e) {\n // no previous step\n }\n\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\n graph.dispatchMessageDelta(lastMessageStepId, {\n content: [{\n type: 'text',\n text: '',\n tool_call_ids,\n }],\n });\n };\n /* If the previous step exists and is a message creation */\n if (prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION) {\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 (!prevRunStep || prevRunStep.type !== StepTypes.MESSAGE_CREATION) {\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 graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n};\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData, metadata?: Record<string, unknown>, graph?: Graph): 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 = (chunk.additional_kwargs?.[graph.reasoningKey] as string | undefined) ?? chunk.content;\n this.handleReasoning(chunk, graph);\n\n let hasToolCalls = false;\n if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id)) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent = typeof content === 'undefined' || !content.length || 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 (hasToolCallChunks\n && chunk.tool_call_chunks\n && chunk.tool_call_chunks.length\n && typeof chunk.tool_call_chunks[0]?.index === 'number') {\n this.handleToolCallChunks({ graph, stepKey, toolCallChunks: chunk.tool_call_chunks });\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 // eslint-disable-next-line no-console\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 (hasToolCallChunks && (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)) {\n return;\n } else if (typeof content === 'string') {\n if (graph.currentTokenType === ContentTypes.TEXT) {\n graph.dispatchMessageDelta(stepId, {\n content: [{\n type: ContentTypes.TEXT,\n text: content,\n }],\n });\n } else {\n graph.dispatchReasoningDelta(stepId, {\n content: [{\n type: ContentTypes.THINK,\n think: content,\n }],\n });\n }\n } else if (content.every((c) => c.type?.startsWith(ContentTypes.TEXT))) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n }\n }\n handleToolCallChunks = ({\n graph,\n stepKey,\n toolCallChunks,\n }: {\n graph: Graph;\n stepKey: string;\n toolCallChunks: ToolCallChunk[],\n }): void => {\n const prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n const prevRunStep = graph.getRunStep(prevStepId);\n const _stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\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 /** 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 (tool_calls != null && toolCallChunk.id != null && toolCallChunk.name != null) {\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 = prevRunStep?.type === StepTypes.MESSAGE_CREATION && graph.messageStepHasToolCalls.has(prevStepId);\n if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {\n graph.dispatchMessageDelta(prevStepId, {\n content: [{\n type: ContentTypes.TEXT,\n text: '',\n tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),\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 handleReasoning(chunk: Partial<AIMessageChunk>, graph: Graph): void {\n const reasoning_content = chunk.additional_kwargs?.[graph.reasoningKey] as string | undefined;\n if (reasoning_content != null && reasoning_content && (chunk.content == null || chunk.content === '')) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'reasoning';\n return;\n } else if (graph.tokenTypeSwitch === 'reasoning' && graph.currentTokenType !== ContentTypes.TEXT && chunk.content != null && chunk.content !== '') {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n } else if (chunk.content != null && typeof chunk.content === 'string' && chunk.content.includes('<think>')) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'content';\n } else if (graph.lastToken != null && graph.lastToken.includes('</think>')) {\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 (partType === ContentTypes.IMAGE_URL && 'image_url' in contentPart) {\n const currentContent = contentParts[index] as { type: 'image_url'; image_url: string };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (partType === ContentTypes.TOOL_CALL && 'tool_call' in contentPart) {\n const existingContent = contentParts[index] as Omit<t.ToolCallContent, 'tool_call'> & { tool_call?: ToolCall } | undefined;\n\n const args = finalUpdate\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args || '') + (contentPart.tool_call.args ?? '');\n\n const id = getNonEmptyValue([contentPart.tool_call.id, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([contentPart.tool_call.name, existingContent?.tool_call?.name]) ?? '';\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 = ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | { result: t.ToolEndEvent };\n }): void => {\n\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 (runStep.stepDetails.type === StepTypes.TOOL_CALLS && runStep.stepDetails.tool_calls) {\n runStep.stepDetails.tool_calls.forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\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 (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\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('No run step or runId found for completed tool call event');\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\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":[],"mappings":";;;AAAA;AAQA,SAAS,gBAAgB,CAAC,cAAwB,EAAA;AAChD,IAAA,KAAK,MAAM,KAAK,IAAI,cAAc,EAAE;QAClC,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;AAChC,YAAA,OAAO,KAAK;;;AAGhB,IAAA,OAAO,SAAS;AAClB;AAEO,MAAM,YAAY,GAAG,CAAC,OAAe,EAAE,KAA8B,EAAE,gBAAgB,GAAG,KAAK,KAAwB;IAC5H,MAAM,SAAS,GAAG,KAAK,CAAC,mBAAmB,CAAC,GAAG,CAAC,OAAO,CAAC;AACxD,IAAA,IAAI,SAAS,IAAI,IAAI,IAAI,SAAS,EAAE;QAClC,OAAO,gBAAgB,GAAG,SAAS,GAAG,SAAS;;IAGjD,MAAM,eAAe,GAAG,KAAK,CAAC,yBAAyB,CAAC,GAAG,CAAC,OAAO,CAAC;AACpE,IAAA,IAAI,eAAe,IAAI,IAAI,IAAI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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;;AAGnD,KAAC;AAED,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE;AACpD;;;;"}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { config } from 'dotenv';
|
|
3
|
+
import fetch from 'node-fetch';
|
|
4
|
+
import { HttpsProxyAgent } from 'https-proxy-agent';
|
|
3
5
|
import { tool } from '@langchain/core/tools';
|
|
4
6
|
import { getEnvironmentVariable } from '@langchain/core/utils/env';
|
|
5
|
-
import {
|
|
7
|
+
import { Constants, EnvVar } from '../common/enum.mjs';
|
|
6
8
|
|
|
7
9
|
config();
|
|
8
10
|
const imageExtRegex = /\.(jpg|jpeg|png|gif|webp)$/i;
|
|
@@ -61,7 +63,7 @@ Usage:
|
|
|
61
63
|
...params,
|
|
62
64
|
};
|
|
63
65
|
try {
|
|
64
|
-
const
|
|
66
|
+
const fetchOptions = {
|
|
65
67
|
method: 'POST',
|
|
66
68
|
headers: {
|
|
67
69
|
'Content-Type': 'application/json',
|
|
@@ -69,7 +71,11 @@ Usage:
|
|
|
69
71
|
'X-API-Key': apiKey,
|
|
70
72
|
},
|
|
71
73
|
body: JSON.stringify(postData),
|
|
72
|
-
}
|
|
74
|
+
};
|
|
75
|
+
if (process.env.PROXY != null && process.env.PROXY !== '') {
|
|
76
|
+
fetchOptions.agent = new HttpsProxyAgent(process.env.PROXY);
|
|
77
|
+
}
|
|
78
|
+
const response = await fetch(EXEC_ENDPOINT, fetchOptions);
|
|
73
79
|
if (!response.ok) {
|
|
74
80
|
throw new Error(`HTTP error! status: ${response.status}`);
|
|
75
81
|
}
|