@librechat/agents 2.4.318 → 2.4.319
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/events.cjs +3 -3
- package/dist/cjs/events.cjs.map +1 -1
- package/dist/cjs/main.cjs +5 -2
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/ids.cjs +23 -0
- package/dist/cjs/messages/ids.cjs.map +1 -0
- package/dist/cjs/stream.cjs +8 -155
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/handlers.cjs +144 -0
- package/dist/cjs/tools/handlers.cjs.map +1 -0
- package/dist/cjs/tools/search/tool.cjs +2 -4
- package/dist/cjs/tools/search/tool.cjs.map +1 -1
- package/dist/esm/events.mjs +1 -1
- package/dist/esm/events.mjs.map +1 -1
- package/dist/esm/main.mjs +3 -1
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/ids.mjs +21 -0
- package/dist/esm/messages/ids.mjs.map +1 -0
- package/dist/esm/stream.mjs +7 -152
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/handlers.mjs +141 -0
- package/dist/esm/tools/handlers.mjs.map +1 -0
- package/dist/esm/tools/search/tool.mjs +2 -4
- package/dist/esm/tools/search/tool.mjs.map +1 -1
- package/dist/types/index.d.ts +1 -0
- package/dist/types/messages/ids.d.ts +3 -0
- package/dist/types/messages/index.d.ts +1 -0
- package/dist/types/stream.d.ts +0 -8
- package/dist/types/tools/handlers.d.ts +8 -0
- package/dist/types/tools/search/types.d.ts +8 -7
- package/package.json +1 -1
- package/src/events.ts +49 -15
- package/src/index.ts +1 -0
- package/src/messages/ids.ts +26 -0
- package/src/messages/index.ts +1 -0
- package/src/stream.ts +4 -186
- package/src/tools/handlers.ts +167 -0
- package/src/tools/search/tool.ts +2 -4
- package/src/tools/search/types.ts +9 -9
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, 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\n/**\n * Parses content to extract thinking sections enclosed in <think> tags using string operations\n * @param content The content to parse\n * @returns An object with separated text and thinking content\n */\nfunction parseThinkingContent(content: string): {\n text: string;\n thinking: string;\n} {\n // If no think tags, return the original content as text\n if (!content.includes('<think>')) {\n return { text: content, thinking: '' };\n }\n\n let textResult = '';\n const thinkingResult: string[] = [];\n let position = 0;\n\n while (position < content.length) {\n const thinkStart = content.indexOf('<think>', position);\n\n if (thinkStart === -1) {\n // No more think tags, add the rest and break\n textResult += content.slice(position);\n break;\n }\n\n // Add text before the think tag\n textResult += content.slice(position, thinkStart);\n\n const thinkEnd = content.indexOf('</think>', thinkStart);\n if (thinkEnd === -1) {\n // Malformed input, no closing tag\n textResult += content.slice(thinkStart);\n break;\n }\n\n // Add the thinking content\n const thinkContent = content.slice(thinkStart + 7, thinkEnd);\n thinkingResult.push(thinkContent);\n\n // Move position to after the think tag\n position = thinkEnd + 8; // 8 is the length of '</think>'\n }\n\n return {\n text: textResult.trim(),\n thinking: thinkingResult.join('\\n').trim(),\n };\n}\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nexport const getMessageId = (\n stepKey: string,\n graph: Graph<t.BaseGraphState>,\n returnExistingId = false\n): 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 = (\n toolCalls?: ToolCall[],\n metadata?: Record<string, unknown>,\n graph?: Graph\n): void => {\n if (!graph || !metadata) {\n console.warn(`Graph or metadata not found in ${event} event`);\n return;\n }\n\n if (!toolCalls) {\n return;\n }\n\n if (toolCalls.length === 0) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n for (const tool_call of toolCalls) {\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\n tool_call.id = toolCallId;\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n\n let prevStepId = '';\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n // no previous step\n }\n\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\n graph.dispatchMessageDelta(lastMessageStepId, {\n content: [\n {\n type: 'text',\n text: '',\n tool_call_ids: [toolCallId],\n },\n ],\n });\n };\n /* If the previous step exists and is a message creation */\n if (\n prevStepId &&\n prevRunStep &&\n prevRunStep.type === StepTypes.MESSAGE_CREATION\n ) {\n dispatchToolCallIds(prevStepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (\n !prevRunStep ||\n prevRunStep.type !== StepTypes.MESSAGE_CREATION\n ) {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n const stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n });\n dispatchToolCallIds(stepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n }\n\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: [tool_call],\n });\n }\n};\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: Graph\n ): void {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content =\n (chunk.additional_kwargs?.[graph.reasoningKey] as string | undefined) ??\n chunk.content;\n this.handleReasoning(chunk, graph);\n\n let hasToolCalls = false;\n if (\n chunk.tool_calls &&\n chunk.tool_calls.length > 0 &&\n chunk.tool_calls.every((tc) => tc.id != null && tc.id !== '')\n ) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent =\n typeof content === 'undefined' ||\n !content.length ||\n (typeof content === 'string' && !content);\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n const chunkId = chunk.id ?? '';\n if (isEmptyChunk && chunkId && chunkId.startsWith('msg')) {\n if (graph.messageIdsByStepKey.has(chunkId)) {\n return;\n } else if (graph.prelimMessageIdsByStepKey.has(chunkId)) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunkId);\n return;\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (\n hasToolCallChunks &&\n chunk.tool_call_chunks &&\n chunk.tool_call_chunks.length &&\n typeof chunk.tool_call_chunks[0]?.index === 'number'\n ) {\n this.handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (graph.currentTokenType === ContentTypes.TEXT) {\n graph.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n } else if (graph.currentTokenType === 'think_and_text') {\n const { text, thinking } = parseThinkingContent(content);\n if (thinking) {\n graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: thinking,\n },\n ],\n });\n }\n if (text) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n const newStepKey = graph.getStepKey(metadata);\n const message_id = getMessageId(newStepKey, graph) ?? '';\n graph.dispatchRunStep(newStepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n\n const newStepId = graph.getStepIdByKey(newStepKey);\n graph.dispatchMessageDelta(newStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: text,\n },\n ],\n });\n }\n } else {\n graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n }\n } else if (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false)\n )\n ) {\n graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think:\n (c as t.ThinkingContentText).thinking ??\n (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ??\n '',\n })),\n });\n }\n }\n handleToolCallChunks = ({\n graph,\n stepKey,\n toolCallChunks,\n }: {\n graph: Graph;\n stepKey: string;\n toolCallChunks: ToolCallChunk[];\n }): void => {\n let prevStepId: string;\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n /** Edge Case: If no previous step exists, create a new message creation step */\n const message_id = getMessageId(stepKey, graph, true) ?? '';\n prevStepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n prevRunStep = graph.getRunStep(prevStepId);\n }\n\n const _stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\n\n /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */\n const tool_calls: ToolCall[] | undefined =\n prevStepId &&\n prevRunStep &&\n prevRunStep.type === StepTypes.MESSAGE_CREATION\n ? []\n : undefined;\n\n /** Edge Case: `id` and `name` fields cannot be empty strings */\n for (const toolCallChunk of toolCallChunks) {\n if (toolCallChunk.name === '') {\n toolCallChunk.name = undefined;\n }\n if (toolCallChunk.id === '') {\n toolCallChunk.id = undefined;\n } else if (\n tool_calls != null &&\n toolCallChunk.id != null &&\n toolCallChunk.name != null\n ) {\n tool_calls.push({\n args: {},\n id: toolCallChunk.id,\n name: toolCallChunk.name,\n type: ToolCallTypes.TOOL_CALL,\n });\n }\n }\n\n let stepId: string = _stepId;\n const alreadyDispatched =\n prevRunStep?.type === StepTypes.MESSAGE_CREATION &&\n graph.messageStepHasToolCalls.has(prevStepId);\n if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {\n graph.dispatchMessageDelta(prevStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: '',\n tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),\n },\n ],\n });\n graph.messageStepHasToolCalls.set(prevStepId, true);\n stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n }\n graph.dispatchRunStepDelta(stepId, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: toolCallChunks,\n });\n };\n handleReasoning(chunk: Partial<AIMessageChunk>, graph: Graph): void {\n let reasoning_content = chunk.additional_kwargs?.[graph.reasoningKey] as\n | string\n | undefined;\n if (\n Array.isArray(chunk.content) &&\n (chunk.content[0]?.type === 'thinking' ||\n chunk.content[0]?.type === 'reasoning_content')\n ) {\n reasoning_content = 'valid';\n }\n if (\n reasoning_content != null &&\n reasoning_content &&\n (chunk.content == null ||\n chunk.content === '' ||\n reasoning_content === 'valid')\n ) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'reasoning';\n return;\n } else if (\n graph.tokenTypeSwitch === 'reasoning' &&\n graph.currentTokenType !== ContentTypes.TEXT &&\n chunk.content != null &&\n chunk.content !== ''\n ) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>') &&\n chunk.content.includes('</think>')\n ) {\n graph.currentTokenType = 'think_and_text';\n graph.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>')\n ) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'content';\n } else if (\n graph.lastToken != null &&\n graph.lastToken.includes('</think>')\n ) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n graph.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart: t.MessageContentComplex,\n finalUpdate = false\n ): void => {\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (\n partType === ContentTypes.IMAGE_URL &&\n 'image_url' in contentPart\n ) {\n const currentContent = contentParts[index] as {\n type: 'image_url';\n image_url: string;\n };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (\n partType === ContentTypes.TOOL_CALL &&\n 'tool_call' in contentPart\n ) {\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart;\n })\n | undefined;\n\n const toolCallArgs = (contentPart.tool_call as t.ToolCallPart).args;\n /** When args are a valid object, they are likely already invoked */\n const args =\n finalUpdate ||\n typeof existingContent?.tool_call?.args === 'object' ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args ?? '') + (toolCallArgs ?? '');\n\n const id =\n getNonEmptyValue([\n contentPart.tool_call.id,\n existingContent?.tool_call?.id,\n ]) ?? '';\n const name =\n getNonEmptyValue([\n contentPart.tool_call.name,\n existingContent?.tool_call?.name,\n ]) ?? '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.RunStepDeltaEvent\n | { result: t.ToolEndEvent };\n }): void => {\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n (runStep.stepDetails.tool_calls as ToolCall[]).forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate;\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn(\n 'No run step or runId found for completed tool call event'\n );\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":[],"mappings":";;;AAAA;AAQA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAe,EAAA;;IAK3C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAChC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE;;IAGxC,IAAI,UAAU,GAAG,EAAE;IACnB,MAAM,cAAc,GAAa,EAAE;IACnC,IAAI,QAAQ,GAAG,CAAC;AAEhB,IAAA,OAAO,QAAQ,GAAG,OAAO,CAAC,MAAM,EAAE;QAChC,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC;AAEvD,QAAA,IAAI,UAAU,KAAK,EAAE,EAAE;;AAErB,YAAA,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC;YACrC;;;QAIF,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,UAAU,CAAC;QAEjD,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,UAAU,EAAE,UAAU,CAAC;AACxD,QAAA,IAAI,QAAQ,KAAK,EAAE,EAAE;;AAEnB,YAAA,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC;YACvC;;;AAIF,QAAA,MAAM,YAAY,GAAG,OAAO,CAAC,KAAK,CAAC,UAAU,GAAG,CAAC,EAAE,QAAQ,CAAC;AAC5D,QAAA,cAAc,CAAC,IAAI,CAAC,YAAY,CAAC;;AAGjC,QAAA,QAAQ,GAAG,QAAQ,GAAG,CAAC,CAAC;;IAG1B,OAAO;AACL,QAAA,IAAI,EAAE,UAAU,CAAC,IAAI,EAAE;QACvB,QAAQ,EAAE,cAAc,CAAC,IAAI,CAAC,IAAI,CAA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B,4BAAA,EAAE,EAAE,UAAU;AACf,yBAAA;qBACF;AAED,oBAAA,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,CAAC;AAC3C,iBAAC,CAAC;;;AAEC,aAAA,IAAI,KAAK,KAAK,WAAW,CAAC,qBAAqB,EAAE;AACtD,YAAA,MAAM,EAAE,MAAM,EAAE,GAAG,IAA6C;AAEhE,YAAA,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,MAAM;YAE7B,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC;YACnC,IAAI,CAAC,OAAO,EAAE;AACZ,gBAAA,OAAO,CAAC,IAAI,CACV,0DAA0D,CAC3D;gBACD;;AAGF,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAE,YAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B;YAED,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC;;AAEnD,KAAC;AAED,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE;AACpD;;;;"}
|
|
1
|
+
{"version":3,"file":"stream.mjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\nimport { StepTypes, ContentTypes, GraphEvents, ToolCallTypes } from '@/common';\nimport { handleToolCalls, handleToolCallChunks } from '@/tools/handlers';\nimport { getMessageId } from '@/messages';\n\n/**\n * Parses content to extract thinking sections enclosed in <think> tags using string operations\n * @param content The content to parse\n * @returns An object with separated text and thinking content\n */\nfunction parseThinkingContent(content: string): {\n text: string;\n thinking: string;\n} {\n // If no think tags, return the original content as text\n if (!content.includes('<think>')) {\n return { text: content, thinking: '' };\n }\n\n let textResult = '';\n const thinkingResult: string[] = [];\n let position = 0;\n\n while (position < content.length) {\n const thinkStart = content.indexOf('<think>', position);\n\n if (thinkStart === -1) {\n // No more think tags, add the rest and break\n textResult += content.slice(position);\n break;\n }\n\n // Add text before the think tag\n textResult += content.slice(position, thinkStart);\n\n const thinkEnd = content.indexOf('</think>', thinkStart);\n if (thinkEnd === -1) {\n // Malformed input, no closing tag\n textResult += content.slice(thinkStart);\n break;\n }\n\n // Add the thinking content\n const thinkContent = content.slice(thinkStart + 7, thinkEnd);\n thinkingResult.push(thinkContent);\n\n // Move position to after the think tag\n position = thinkEnd + 8; // 8 is the length of '</think>'\n }\n\n return {\n text: textResult.trim(),\n thinking: thinkingResult.join('\\n').trim(),\n };\n}\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(\n event: string,\n data: t.StreamEventData,\n metadata?: Record<string, unknown>,\n graph?: Graph\n ): void {\n if (!graph) {\n throw new Error('Graph not found');\n }\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n if (!data.chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n const chunk = data.chunk as Partial<AIMessageChunk>;\n const content =\n (chunk.additional_kwargs?.[graph.reasoningKey] as string | undefined) ??\n chunk.content;\n this.handleReasoning(chunk, graph);\n\n let hasToolCalls = false;\n if (\n chunk.tool_calls &&\n chunk.tool_calls.length > 0 &&\n chunk.tool_calls.every((tc) => tc.id != null && tc.id !== '')\n ) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const hasToolCallChunks =\n (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n const isEmptyContent =\n typeof content === 'undefined' ||\n !content.length ||\n (typeof content === 'string' && !content);\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n const chunkId = chunk.id ?? '';\n if (isEmptyChunk && chunkId && chunkId.startsWith('msg')) {\n if (graph.messageIdsByStepKey.has(chunkId)) {\n return;\n } else if (graph.prelimMessageIdsByStepKey.has(chunkId)) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunkId);\n return;\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (\n hasToolCallChunks &&\n chunk.tool_call_chunks &&\n chunk.tool_call_chunks.length &&\n typeof chunk.tool_call_chunks[0]?.index === 'number'\n ) {\n handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks: chunk.tool_call_chunks,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (\n hasToolCallChunks &&\n (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)\n ) {\n return;\n } else if (typeof content === 'string') {\n if (graph.currentTokenType === ContentTypes.TEXT) {\n graph.dispatchMessageDelta(stepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: content,\n },\n ],\n });\n } else if (graph.currentTokenType === 'think_and_text') {\n const { text, thinking } = parseThinkingContent(content);\n if (thinking) {\n graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: thinking,\n },\n ],\n });\n }\n if (text) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n const newStepKey = graph.getStepKey(metadata);\n const message_id = getMessageId(newStepKey, graph) ?? '';\n graph.dispatchRunStep(newStepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n\n const newStepId = graph.getStepIdByKey(newStepKey);\n graph.dispatchMessageDelta(newStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: text,\n },\n ],\n });\n }\n } else {\n graph.dispatchReasoningDelta(stepId, {\n content: [\n {\n type: ContentTypes.THINK,\n think: content,\n },\n ],\n });\n }\n } else if (\n content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)\n ) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (\n content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false)\n )\n ) {\n graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think:\n (c as t.ThinkingContentText).thinking ??\n (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ??\n '',\n })),\n });\n }\n }\n handleReasoning(chunk: Partial<AIMessageChunk>, graph: Graph): void {\n let reasoning_content = chunk.additional_kwargs?.[graph.reasoningKey] as\n | string\n | undefined;\n if (\n Array.isArray(chunk.content) &&\n (chunk.content[0]?.type === 'thinking' ||\n chunk.content[0]?.type === 'reasoning_content')\n ) {\n reasoning_content = 'valid';\n }\n if (\n reasoning_content != null &&\n reasoning_content &&\n (chunk.content == null ||\n chunk.content === '' ||\n reasoning_content === 'valid')\n ) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'reasoning';\n return;\n } else if (\n graph.tokenTypeSwitch === 'reasoning' &&\n graph.currentTokenType !== ContentTypes.TEXT &&\n chunk.content != null &&\n chunk.content !== ''\n ) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>') &&\n chunk.content.includes('</think>')\n ) {\n graph.currentTokenType = 'think_and_text';\n graph.tokenTypeSwitch = 'content';\n } else if (\n chunk.content != null &&\n typeof chunk.content === 'string' &&\n chunk.content.includes('<think>')\n ) {\n graph.currentTokenType = ContentTypes.THINK;\n graph.tokenTypeSwitch = 'content';\n } else if (\n graph.lastToken != null &&\n graph.lastToken.includes('</think>')\n ) {\n graph.currentTokenType = ContentTypes.TEXT;\n graph.tokenTypeSwitch = 'content';\n }\n if (typeof chunk.content !== 'string') {\n return;\n }\n graph.lastToken = chunk.content;\n }\n}\n\nexport function createContentAggregator(): t.ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart: t.MessageContentComplex,\n finalUpdate = false\n ): void => {\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update != null\n ) {\n const update: t.AgentUpdate = {\n type: ContentTypes.AGENT_UPDATE,\n agent_update: contentPart.agent_update,\n };\n\n contentParts[index] = update;\n } else if (\n partType === ContentTypes.IMAGE_URL &&\n 'image_url' in contentPart\n ) {\n const currentContent = contentParts[index] as {\n type: 'image_url';\n image_url: string;\n };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (\n partType === ContentTypes.TOOL_CALL &&\n 'tool_call' in contentPart\n ) {\n const existingContent = contentParts[index] as\n | (Omit<t.ToolCallContent, 'tool_call'> & {\n tool_call?: t.ToolCallPart;\n })\n | undefined;\n\n const toolCallArgs = (contentPart.tool_call as t.ToolCallPart).args;\n /** When args are a valid object, they are likely already invoked */\n const args =\n finalUpdate ||\n typeof existingContent?.tool_call?.args === 'object' ||\n typeof toolCallArgs === 'object'\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args ?? '') + (toolCallArgs ?? '');\n\n const id =\n getNonEmptyValue([\n contentPart.tool_call.id,\n existingContent?.tool_call?.id,\n ]) ?? '';\n const name =\n getNonEmptyValue([\n contentPart.tool_call.name,\n existingContent?.tool_call?.name,\n ]) ?? '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({\n event,\n data,\n }: {\n event: GraphEvents;\n data:\n | t.RunStep\n | t.AgentUpdate\n | t.MessageDeltaEvent\n | t.RunStepDeltaEvent\n | { result: t.ToolEndEvent };\n }): void => {\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (\n runStep.stepDetails.type === StepTypes.TOOL_CALLS &&\n runStep.stepDetails.tool_calls\n ) {\n (runStep.stepDetails.tool_calls as ToolCall[]).forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCall.args,\n name: toolCall.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (\n event === GraphEvents.ON_AGENT_UPDATE &&\n (data as t.AgentUpdate | undefined)?.agent_update\n ) {\n const contentPart = data as t.AgentUpdate;\n updateContent(contentPart.agent_update.index, contentPart);\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for reasoning delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n args: toolCallDelta.args ?? '',\n name: toolCallDelta.name,\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn(\n 'No run step or runId found for completed tool call event'\n );\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":[],"mappings":";;;;;;AASA;;;;AAIG;AACH,SAAS,oBAAoB,CAAC,OAAe,EAAA;;IAK3C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;QAChC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE;;IAGxC,IAAI,UAAU,GAAG,EAAE;IACnB,MAAM,cAAc,GAAa,EAAE;IACnC,IAAI,QAAQ,GAAG,CAAC;AAEhB,IAAA,OAAO,QAAQ,GAAG,OAAO,CAAC,MAAM,EAAE;QAChC,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC;AAEvD,QAAA,IAAI,UAAU,KAAK,EAAE,EAAE;;AAErB,YAAA,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC;YACrC;;;QAIF,UAAU,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,UAAU,CAAC;QAEjD,MAAM,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,UAAU,EAAE,UAAU,CAAC;AACxD,Q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,KAAI;oBACtD,MAAM,UAAU,GAAG,aAAa,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,CAAC;AAErD,oBAAA,MAAM,WAAW,GAA4B;wBAC3C,IAAI,EAAE,YAAY,CAAC,SAAS;AAC5B,wBAAA,SAAS,EAAE;AACT,4BAAA,IAAI,EAAE,aAAa,CAAC,IAAI,IAAI,EAAE;4BAC9B,IAAI,EAAE,aAAa,CAAC,IAAI;AACxB,4BAAA,EAAE,EAAE,UAAU;AACf,yBAAA;qBACF;AAED,oBAAA,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,CAAC;AAC3C,iBAAC,CAAC;;;AAEC,aAAA,IAAI,KAAK,KAAK,WAAW,CAAC,qBAAqB,EAAE;AACtD,YAAA,MAAM,EAAE,MAAM,EAAE,GAAG,IAA6C;AAEhE,YAAA,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,MAAM;YAE7B,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC;YACnC,IAAI,CAAC,OAAO,EAAE;AACZ,gBAAA,OAAO,CAAC,IAAI,CACV,0DAA0D,CAC3D;gBACD;;AAGF,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAE,YAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B;YAED,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC;;AAEnD,KAAC;AAED,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE;AACpD;;;;"}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { nanoid } from 'nanoid';
|
|
2
|
+
import { StepTypes, ToolCallTypes, ContentTypes } from '../common/enum.mjs';
|
|
3
|
+
import '../messages/core.mjs';
|
|
4
|
+
import { getMessageId } from '../messages/ids.mjs';
|
|
5
|
+
import '@langchain/core/messages';
|
|
6
|
+
|
|
7
|
+
/* eslint-disable no-console */
|
|
8
|
+
// src/tools/handlers.ts
|
|
9
|
+
function handleToolCallChunks({ graph, stepKey, toolCallChunks, }) {
|
|
10
|
+
let prevStepId;
|
|
11
|
+
let prevRunStep;
|
|
12
|
+
try {
|
|
13
|
+
prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);
|
|
14
|
+
prevRunStep = graph.getRunStep(prevStepId);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
/** Edge Case: If no previous step exists, create a new message creation step */
|
|
18
|
+
const message_id = getMessageId(stepKey, graph, true) ?? '';
|
|
19
|
+
prevStepId = graph.dispatchRunStep(stepKey, {
|
|
20
|
+
type: StepTypes.MESSAGE_CREATION,
|
|
21
|
+
message_creation: {
|
|
22
|
+
message_id,
|
|
23
|
+
},
|
|
24
|
+
});
|
|
25
|
+
prevRunStep = graph.getRunStep(prevStepId);
|
|
26
|
+
}
|
|
27
|
+
const _stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);
|
|
28
|
+
/** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */
|
|
29
|
+
const tool_calls = prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION
|
|
30
|
+
? []
|
|
31
|
+
: undefined;
|
|
32
|
+
/** Edge Case: `id` and `name` fields cannot be empty strings */
|
|
33
|
+
for (const toolCallChunk of toolCallChunks) {
|
|
34
|
+
if (toolCallChunk.name === '') {
|
|
35
|
+
toolCallChunk.name = undefined;
|
|
36
|
+
}
|
|
37
|
+
if (toolCallChunk.id === '') {
|
|
38
|
+
toolCallChunk.id = undefined;
|
|
39
|
+
}
|
|
40
|
+
else if (tool_calls != null &&
|
|
41
|
+
toolCallChunk.id != null &&
|
|
42
|
+
toolCallChunk.name != null) {
|
|
43
|
+
tool_calls.push({
|
|
44
|
+
args: {},
|
|
45
|
+
id: toolCallChunk.id,
|
|
46
|
+
name: toolCallChunk.name,
|
|
47
|
+
type: ToolCallTypes.TOOL_CALL,
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
let stepId = _stepId;
|
|
52
|
+
const alreadyDispatched = prevRunStep?.type === StepTypes.MESSAGE_CREATION &&
|
|
53
|
+
graph.messageStepHasToolCalls.has(prevStepId);
|
|
54
|
+
if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {
|
|
55
|
+
graph.dispatchMessageDelta(prevStepId, {
|
|
56
|
+
content: [
|
|
57
|
+
{
|
|
58
|
+
type: ContentTypes.TEXT,
|
|
59
|
+
text: '',
|
|
60
|
+
tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),
|
|
61
|
+
},
|
|
62
|
+
],
|
|
63
|
+
});
|
|
64
|
+
graph.messageStepHasToolCalls.set(prevStepId, true);
|
|
65
|
+
stepId = graph.dispatchRunStep(stepKey, {
|
|
66
|
+
type: StepTypes.TOOL_CALLS,
|
|
67
|
+
tool_calls,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
graph.dispatchRunStepDelta(stepId, {
|
|
71
|
+
type: StepTypes.TOOL_CALLS,
|
|
72
|
+
tool_calls: toolCallChunks,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
const handleToolCalls = (toolCalls, metadata, graph) => {
|
|
76
|
+
if (!graph || !metadata) {
|
|
77
|
+
console.warn(`Graph or metadata not found in ${event} event`);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (!toolCalls) {
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
if (toolCalls.length === 0) {
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const stepKey = graph.getStepKey(metadata);
|
|
87
|
+
for (const tool_call of toolCalls) {
|
|
88
|
+
const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;
|
|
89
|
+
tool_call.id = toolCallId;
|
|
90
|
+
if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
let prevStepId = '';
|
|
94
|
+
let prevRunStep;
|
|
95
|
+
try {
|
|
96
|
+
prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);
|
|
97
|
+
prevRunStep = graph.getRunStep(prevStepId);
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
// no previous step
|
|
101
|
+
}
|
|
102
|
+
const dispatchToolCallIds = (lastMessageStepId) => {
|
|
103
|
+
graph.dispatchMessageDelta(lastMessageStepId, {
|
|
104
|
+
content: [
|
|
105
|
+
{
|
|
106
|
+
type: 'text',
|
|
107
|
+
text: '',
|
|
108
|
+
tool_call_ids: [toolCallId],
|
|
109
|
+
},
|
|
110
|
+
],
|
|
111
|
+
});
|
|
112
|
+
};
|
|
113
|
+
/* If the previous step exists and is a message creation */
|
|
114
|
+
if (prevStepId &&
|
|
115
|
+
prevRunStep &&
|
|
116
|
+
prevRunStep.type === StepTypes.MESSAGE_CREATION) {
|
|
117
|
+
dispatchToolCallIds(prevStepId);
|
|
118
|
+
graph.messageStepHasToolCalls.set(prevStepId, true);
|
|
119
|
+
/* If the previous step doesn't exist or is not a message creation */
|
|
120
|
+
}
|
|
121
|
+
else if (!prevRunStep ||
|
|
122
|
+
prevRunStep.type !== StepTypes.MESSAGE_CREATION) {
|
|
123
|
+
const messageId = getMessageId(stepKey, graph, true) ?? '';
|
|
124
|
+
const stepId = graph.dispatchRunStep(stepKey, {
|
|
125
|
+
type: StepTypes.MESSAGE_CREATION,
|
|
126
|
+
message_creation: {
|
|
127
|
+
message_id: messageId,
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
dispatchToolCallIds(stepId);
|
|
131
|
+
graph.messageStepHasToolCalls.set(prevStepId, true);
|
|
132
|
+
}
|
|
133
|
+
graph.dispatchRunStep(stepKey, {
|
|
134
|
+
type: StepTypes.TOOL_CALLS,
|
|
135
|
+
tool_calls: [tool_call],
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
export { handleToolCallChunks, handleToolCalls };
|
|
141
|
+
//# sourceMappingURL=handlers.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"handlers.mjs","sources":["../../../src/tools/handlers.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/tools/handlers.ts\nimport { nanoid } from 'nanoid';\nimport type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\nimport { StepTypes, ContentTypes, ToolCallTypes } from '@/common';\nimport { getMessageId } from '@/messages';\n\nexport function handleToolCallChunks({\n graph,\n stepKey,\n toolCallChunks,\n}: {\n graph: Graph;\n stepKey: string;\n toolCallChunks: ToolCallChunk[];\n}): void {\n let prevStepId: string;\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n /** Edge Case: If no previous step exists, create a new message creation step */\n const message_id = getMessageId(stepKey, graph, true) ?? '';\n prevStepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n prevRunStep = graph.getRunStep(prevStepId);\n }\n\n const _stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\n\n /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */\n const tool_calls: ToolCall[] | undefined =\n prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION\n ? []\n : undefined;\n\n /** Edge Case: `id` and `name` fields cannot be empty strings */\n for (const toolCallChunk of toolCallChunks) {\n if (toolCallChunk.name === '') {\n toolCallChunk.name = undefined;\n }\n if (toolCallChunk.id === '') {\n toolCallChunk.id = undefined;\n } else if (\n tool_calls != null &&\n toolCallChunk.id != null &&\n toolCallChunk.name != null\n ) {\n tool_calls.push({\n args: {},\n id: toolCallChunk.id,\n name: toolCallChunk.name,\n type: ToolCallTypes.TOOL_CALL,\n });\n }\n }\n\n let stepId: string = _stepId;\n const alreadyDispatched =\n prevRunStep?.type === StepTypes.MESSAGE_CREATION &&\n graph.messageStepHasToolCalls.has(prevStepId);\n if (!alreadyDispatched && tool_calls?.length === toolCallChunks.length) {\n graph.dispatchMessageDelta(prevStepId, {\n content: [\n {\n type: ContentTypes.TEXT,\n text: '',\n tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),\n },\n ],\n });\n graph.messageStepHasToolCalls.set(prevStepId, true);\n stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n }\n graph.dispatchRunStepDelta(stepId, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: toolCallChunks,\n });\n}\n\nexport const handleToolCalls = (\n toolCalls?: ToolCall[],\n metadata?: Record<string, unknown>,\n graph?: Graph\n): void => {\n if (!graph || !metadata) {\n console.warn(`Graph or metadata not found in ${event} event`);\n return;\n }\n\n if (!toolCalls) {\n return;\n }\n\n if (toolCalls.length === 0) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n for (const tool_call of toolCalls) {\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\n tool_call.id = toolCallId;\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n\n let prevStepId = '';\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch {\n // no previous step\n }\n\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\n graph.dispatchMessageDelta(lastMessageStepId, {\n content: [\n {\n type: 'text',\n text: '',\n tool_call_ids: [toolCallId],\n },\n ],\n });\n };\n /* If the previous step exists and is a message creation */\n if (\n prevStepId &&\n prevRunStep &&\n prevRunStep.type === StepTypes.MESSAGE_CREATION\n ) {\n dispatchToolCallIds(prevStepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (\n !prevRunStep ||\n prevRunStep.type !== StepTypes.MESSAGE_CREATION\n ) {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n const stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n });\n dispatchToolCallIds(stepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n }\n\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: [tool_call],\n });\n }\n};\n"],"names":[],"mappings":";;;;;;AAAA;AACA;AAQM,SAAU,oBAAoB,CAAC,EACnC,KAAK,EACL,OAAO,EACP,cAAc,GAKf,EAAA;AACC,IAAA,IAAI,UAAkB;AACtB,IAAA,IAAI,WAAkC;AACtC,IAAA,IAAI;AACF,QAAA,UAAU,GAAG,KAAK,CAAC,cAAc,CAAC,OAAO,EAAE,KAAK,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC,CAAC;AACxE,QAAA,WAAW,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC;;AAC1C,IAAA,MAAM;;AAEN,QAAA,MAAM,UAAU,GAAG,YAAY,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,EAAE;AAC3D,QAAA,UAAU,GAAG,KAAK,CAAC,eAAe,CAAC,OAAO,EAAE;YAC1C,IAAI,EAAE,SAAS,CAAC,gBAAgB;AAChC,YAAA,gBAAgB,EAAE;gBAChB,UAAU;AACX,aAAA;AACF,SAAA,CAAC;AACF,QAAA,WAAW,GAAG,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC;;AAG5C,IAAA,MAAM,OAAO,GAAG,KAAK,CAAC,cAAc,CAAC,OAAO,EAAE,WAAW,EAAE,KAAK,CAAC;;AAGjE,IAAA,MAAM,UAAU,GACd,UAAU,IAAI,WAAW,IAAI,WAAW,CAAC,IAAI,KAAK,SAAS,CAAC;AAC1D,UAAE;UACA,SAAS;;AAGf,IAAA,KAAK,MAAM,aAAa,IAAI,cAAc,EAAE;A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E,MAAM;AACZ,wBAAA,IAAI,EAAE,EAAE;wBACR,aAAa,EAAE,CAAC,UAAU,CAAC;AAC5B,qBAAA;AACF,iBAAA;AACF,aAAA,CAAC;AACJ,SAAC;;AAED,QAAA,IACE,UAAU;YACV,WAAW;AACX,YAAA,WAAW,CAAC,IAAI,KAAK,SAAS,CAAC,gBAAgB,EAC/C;YACA,mBAAmB,CAAC,UAAU,CAAC;YAC/B,KAAK,CAAC,uBAAuB,CAAC,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC;;;AAE9C,aAAA,IACL,CAAC,WAAW;AACZ,YAAA,WAAW,CAAC,IAAI,KAAK,SAAS,CAAC,gBAAgB,EAC/C;AACA,YAAA,MAAM,SAAS,GAAG,YAAY,CAAC,OAAO,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,EAAE;AAC1D,YAAA,MAAM,MAAM,GAAG,KAAK,CAAC,eAAe,CAAC,OAAO,EAAE;gBAC5C,IAAI,EAAE,SAAS,CAAC,gBAAgB;AAChC,gBAAA,gBAAgB,EAAE;AAChB,oBAAA,UAAU,EAAE,SAAS;AACtB,iBAAA;AACF,aAAA,CAAC;YACF,mBAAmB,CAAC,MAAM,CAAC;YAC3B,KAAK,CAAC,uBAAuB,CAAC,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC;;AAGrD,QAAA,KAAK,CAAC,eAAe,CAAC,OAAO,EAAE;YAC7B,IAAI,EAAE,SAAS,CAAC,UAAU;YAC1B,UAAU,EAAE,CAAC,SAAS,CAAC;AACxB,SAAA,CAAC;;AAEN;;;;"}
|
|
@@ -112,10 +112,8 @@ const createSearchTool = (config = {}) => {
|
|
|
112
112
|
});
|
|
113
113
|
const turn = runnableConfig.toolCall?.turn ?? 0;
|
|
114
114
|
const { output, references } = formatResultsForLLM(turn, searchResult);
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
{ [Constants.WEB_SEARCH]: { turn, ...searchResult, references } },
|
|
118
|
-
];
|
|
115
|
+
const data = { turn, ...searchResult, references };
|
|
116
|
+
return [output, { [Constants.WEB_SEARCH]: data }];
|
|
119
117
|
}, {
|
|
120
118
|
name: Constants.WEB_SEARCH,
|
|
121
119
|
description: `
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool.mjs","sources":["../../../../src/tools/search/tool.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport { z } from 'zod';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from './types';\nimport { createSearchAPI, createSourceProcessor } from './search';\nimport { createFirecrawlScraper } from './firecrawl';\nimport { expandHighlights } from './highlights';\nimport { formatResultsForLLM } from './format';\nimport { createReranker } from './rerankers';\nimport { Constants } from '@/common';\n\nconst DEFAULT_QUERY_DESCRIPTION = `\nGUIDELINES:\n- Start broad, then narrow: Begin with key concepts, then refine with specifics\n- Think like sources: Use terminology experts would use in the field\n- Consider perspective: Frame queries from different viewpoints for better results\n- Quality over quantity: A precise 3-4 word query often beats lengthy sentences\n\nTECHNIQUES (combine for power searches):\n- EXACT PHRASES: Use quotes (\"climate change report\")\n- EXCLUDE TERMS: Use minus to remove unwanted results (-wikipedia)\n- SITE-SPECIFIC: Restrict to websites (site:edu research)\n- FILETYPE: Find specific documents (filetype:pdf study)\n- OR OPERATOR: Find alternatives (electric OR hybrid cars)\n- DATE RANGE: Recent information (data after:2020)\n- WILDCARDS: Use * for unknown terms (how to * bread)\n- SPECIFIC QUESTIONS: Use who/what/when/where/why/how\n- DOMAIN TERMS: Include technical terminology for specialized topics\n- CONCISE TERMS: Prioritize keywords over sentences\n`.trim();\n\nconst DEFAULT_COUNTRY_DESCRIPTION = `Country code to localize search results.\nUse standard 2-letter country codes: \"us\", \"uk\", \"ca\", \"de\", \"fr\", \"jp\", \"br\", etc.\nProvide this when the search should return results specific to a particular country.\nExamples:\n- \"us\" for United States (default)\n- \"de\" for Germany\n- \"in\" for India\n`.trim();\n\n/**\n * Creates a search tool with a schema that dynamically includes the country field\n * only when the searchProvider is 'serper'.\n *\n * @param config - The search tool configuration\n * @returns A DynamicStructuredTool with a schema that depends on the searchProvider\n */\nexport const createSearchTool = (\n config: t.SearchToolConfig = {}\n): DynamicStructuredTool<typeof SearchToolSchema> => {\n const {\n searchProvider = 'serper',\n serperApiKey,\n searxngInstanceUrl,\n searxngApiKey,\n rerankerType = 'cohere',\n topResults = 5,\n strategies = ['no_extraction'],\n filterContent = true,\n firecrawlApiKey,\n firecrawlApiUrl,\n firecrawlFormats = ['markdown', 'html'],\n jinaApiKey,\n cohereApiKey,\n onSearchResults: _onSearchResults,\n } = config;\n\n const querySchema = z.string().describe(DEFAULT_QUERY_DESCRIPTION);\n const schemaObject: {\n query: z.ZodString;\n country?: z.ZodOptional<z.ZodString>;\n } = {\n query: querySchema,\n };\n\n if (searchProvider === 'serper') {\n schemaObject.country = z\n .string()\n .optional()\n .describe(DEFAULT_COUNTRY_DESCRIPTION);\n }\n\n const SearchToolSchema = z.object(schemaObject);\n\n const searchAPI = createSearchAPI({\n searchProvider,\n serperApiKey,\n searxngInstanceUrl,\n searxngApiKey,\n });\n\n const firecrawlScraper = createFirecrawlScraper({\n apiKey: firecrawlApiKey ?? process.env.FIRECRAWL_API_KEY,\n apiUrl: firecrawlApiUrl,\n formats: firecrawlFormats,\n });\n\n const selectedReranker = createReranker({\n rerankerType,\n jinaApiKey,\n cohereApiKey,\n });\n\n if (!selectedReranker) {\n console.warn('No reranker selected. Using default ranking.');\n }\n\n const sourceProcessor = createSourceProcessor(\n {\n reranker: selectedReranker,\n topResults,\n strategies,\n filterContent,\n },\n firecrawlScraper\n );\n\n const search = async ({\n query,\n country,\n proMode = true,\n maxSources = 5,\n onSearchResults,\n }: {\n query: string;\n country?: string;\n maxSources?: number;\n proMode?: boolean;\n onSearchResults?: (sources: t.SearchResult) => void;\n }): Promise<t.SearchResultData> => {\n try {\n const sources = await searchAPI.getSources({ query, country });\n onSearchResults?.(sources);\n\n if (!sources.success) {\n throw new Error(sources.error ?? 'Search failed');\n }\n\n const processedSources = await sourceProcessor.processSources(\n sources,\n maxSources,\n query,\n proMode\n );\n return expandHighlights(processedSources);\n } catch (error) {\n console.error('Error in search:', error);\n return {\n organic: [],\n topStories: [],\n images: [],\n relatedSearches: [],\n error: error instanceof Error ? error.message : String(error),\n };\n }\n };\n\n return tool<typeof SearchToolSchema>(\n async (params, runnableConfig) => {\n const { query, country: _c } = params;\n const country = typeof _c === 'string' && _c ? _c : undefined;\n const searchResult = await search({\n query,\n country,\n onSearchResults: _onSearchResults\n ? (result): void => {\n _onSearchResults(result, runnableConfig);\n }\n : undefined,\n });\n const turn = runnableConfig.toolCall?.turn ?? 0;\n const { output, references } = formatResultsForLLM(turn, searchResult);\n
|
|
1
|
+
{"version":3,"file":"tool.mjs","sources":["../../../../src/tools/search/tool.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport { z } from 'zod';\nimport { tool, DynamicStructuredTool } from '@langchain/core/tools';\nimport type * as t from './types';\nimport { createSearchAPI, createSourceProcessor } from './search';\nimport { createFirecrawlScraper } from './firecrawl';\nimport { expandHighlights } from './highlights';\nimport { formatResultsForLLM } from './format';\nimport { createReranker } from './rerankers';\nimport { Constants } from '@/common';\n\nconst DEFAULT_QUERY_DESCRIPTION = `\nGUIDELINES:\n- Start broad, then narrow: Begin with key concepts, then refine with specifics\n- Think like sources: Use terminology experts would use in the field\n- Consider perspective: Frame queries from different viewpoints for better results\n- Quality over quantity: A precise 3-4 word query often beats lengthy sentences\n\nTECHNIQUES (combine for power searches):\n- EXACT PHRASES: Use quotes (\"climate change report\")\n- EXCLUDE TERMS: Use minus to remove unwanted results (-wikipedia)\n- SITE-SPECIFIC: Restrict to websites (site:edu research)\n- FILETYPE: Find specific documents (filetype:pdf study)\n- OR OPERATOR: Find alternatives (electric OR hybrid cars)\n- DATE RANGE: Recent information (data after:2020)\n- WILDCARDS: Use * for unknown terms (how to * bread)\n- SPECIFIC QUESTIONS: Use who/what/when/where/why/how\n- DOMAIN TERMS: Include technical terminology for specialized topics\n- CONCISE TERMS: Prioritize keywords over sentences\n`.trim();\n\nconst DEFAULT_COUNTRY_DESCRIPTION = `Country code to localize search results.\nUse standard 2-letter country codes: \"us\", \"uk\", \"ca\", \"de\", \"fr\", \"jp\", \"br\", etc.\nProvide this when the search should return results specific to a particular country.\nExamples:\n- \"us\" for United States (default)\n- \"de\" for Germany\n- \"in\" for India\n`.trim();\n\n/**\n * Creates a search tool with a schema that dynamically includes the country field\n * only when the searchProvider is 'serper'.\n *\n * @param config - The search tool configuration\n * @returns A DynamicStructuredTool with a schema that depends on the searchProvider\n */\nexport const createSearchTool = (\n config: t.SearchToolConfig = {}\n): DynamicStructuredTool<typeof SearchToolSchema> => {\n const {\n searchProvider = 'serper',\n serperApiKey,\n searxngInstanceUrl,\n searxngApiKey,\n rerankerType = 'cohere',\n topResults = 5,\n strategies = ['no_extraction'],\n filterContent = true,\n firecrawlApiKey,\n firecrawlApiUrl,\n firecrawlFormats = ['markdown', 'html'],\n jinaApiKey,\n cohereApiKey,\n onSearchResults: _onSearchResults,\n } = config;\n\n const querySchema = z.string().describe(DEFAULT_QUERY_DESCRIPTION);\n const schemaObject: {\n query: z.ZodString;\n country?: z.ZodOptional<z.ZodString>;\n } = {\n query: querySchema,\n };\n\n if (searchProvider === 'serper') {\n schemaObject.country = z\n .string()\n .optional()\n .describe(DEFAULT_COUNTRY_DESCRIPTION);\n }\n\n const SearchToolSchema = z.object(schemaObject);\n\n const searchAPI = createSearchAPI({\n searchProvider,\n serperApiKey,\n searxngInstanceUrl,\n searxngApiKey,\n });\n\n const firecrawlScraper = createFirecrawlScraper({\n apiKey: firecrawlApiKey ?? process.env.FIRECRAWL_API_KEY,\n apiUrl: firecrawlApiUrl,\n formats: firecrawlFormats,\n });\n\n const selectedReranker = createReranker({\n rerankerType,\n jinaApiKey,\n cohereApiKey,\n });\n\n if (!selectedReranker) {\n console.warn('No reranker selected. Using default ranking.');\n }\n\n const sourceProcessor = createSourceProcessor(\n {\n reranker: selectedReranker,\n topResults,\n strategies,\n filterContent,\n },\n firecrawlScraper\n );\n\n const search = async ({\n query,\n country,\n proMode = true,\n maxSources = 5,\n onSearchResults,\n }: {\n query: string;\n country?: string;\n maxSources?: number;\n proMode?: boolean;\n onSearchResults?: (sources: t.SearchResult) => void;\n }): Promise<t.SearchResultData> => {\n try {\n const sources = await searchAPI.getSources({ query, country });\n onSearchResults?.(sources);\n\n if (!sources.success) {\n throw new Error(sources.error ?? 'Search failed');\n }\n\n const processedSources = await sourceProcessor.processSources(\n sources,\n maxSources,\n query,\n proMode\n );\n return expandHighlights(processedSources);\n } catch (error) {\n console.error('Error in search:', error);\n return {\n organic: [],\n topStories: [],\n images: [],\n relatedSearches: [],\n error: error instanceof Error ? error.message : String(error),\n };\n }\n };\n\n return tool<typeof SearchToolSchema>(\n async (params, runnableConfig) => {\n const { query, country: _c } = params;\n const country = typeof _c === 'string' && _c ? _c : undefined;\n const searchResult = await search({\n query,\n country,\n onSearchResults: _onSearchResults\n ? (result): void => {\n _onSearchResults(result, runnableConfig);\n }\n : undefined,\n });\n const turn = runnableConfig.toolCall?.turn ?? 0;\n const { output, references } = formatResultsForLLM(turn, searchResult);\n const data: t.SearchResultData = { turn, ...searchResult, references };\n return [output, { [Constants.WEB_SEARCH]: data }];\n },\n {\n name: Constants.WEB_SEARCH,\n description: `\nReal-time search. Results have required citation anchors.\n\nNote: Use ONCE per reply unless instructed otherwise.\n\nAnchors:\n- \\\\ue202turnXtypeY\n- X = turn idx, type = 'search' | 'news' | 'image' | 'ref', Y = item idx\n\nSpecial Markers:\n- \\\\ue203...\\\\ue204 — highlight start/end of cited text (for Standalone or Group citations)\n- \\\\ue200...\\\\ue201 — group block (e.g. \\\\ue200\\\\ue202turn0search1\\\\ue202turn0news2\\\\ue201)\n\n**CITE EVERY NON-OBVIOUS FACT/QUOTE:**\nUse anchor marker(s) immediately after the statement:\n- Standalone: \"Pure functions produce same output. \\\\ue202turn0search0\"\n- Standalone (multiple): \"Today's News \\\\ue202turn0search0\\\\ue202turn0news0\"\n- Highlight: \"\\\\ue203Highlight text.\\\\ue204\\\\ue202turn0news1\"\n- Group: \"Sources. \\\\ue200\\\\ue202turn0search0\\\\ue202turn0news1\\\\ue201\"\n- Group Highlight: \"\\\\ue203Highlight for group.\\\\ue204 \\\\ue200\\\\ue202turn0search0\\\\ue202turn0news1\\\\ue201\"\n- Image: \"See photo \\\\ue202turn0image0.\"\n\n**NEVER use markdown links, [1], or footnotes. CITE ONLY with anchors provided.**\n`.trim(),\n schema: SearchToolSchema,\n responseFormat: Constants.CONTENT_AND_ARTIFACT,\n }\n );\n};\n"],"names":[],"mappings":";;;;;;;;;AAAA;AAWA,MAAM,yBAAyB,GAAG;;;;;;;;;;;;;;;;;;CAkBjC,CAAC,IAAI,EAAE;AAER,MAAM,2BAA2B,GAAG,CAAA;;;;;;;CAOnC,CAAC,IAAI,EAAE;AAER;;;;;;AAMG;MACU,gBAAgB,GAAG,CAC9B,MAA6B,GAAA,EAAE,KACmB;IAClD,MAAM,EACJ,cAAc,GAAG,QAAQ,EACzB,YAAY,EACZ,kBAAkB,EAClB,aAAa,EACb,YAAY,GAAG,QAAQ,EACvB,UAAU,GAAG,CAAC,EACd,UAAU,GAAG,CAAC,eAAe,CAAC,EAC9B,aAAa,GAAG,IAAI,EACpB,eAAe,EACf,eAAe,EACf,gBAAgB,GAAG,CAAC,UAAU,EAAE,MAAM,CAAC,EACvC,UAAU,EACV,YAAY,EACZ,eAAe,EAAE,gBAAgB,GAClC,GAAG,MAAM;IAEV,MAAM,WAAW,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,yBAAyB,CAAC;AAClE,IAAA,MAAM,YAAY,GAGd;AACF,QAAA,KAAK,EAAE,WAAW;KACnB;AAED,IAAA,IAAI,cAAc,KAAK,QAAQ,EAAE;QAC/B,YAAY,CAAC,OAAO,GAAG;AACpB,aAAA,MAAM;AACN,aAAA,QAAQ;aACR,QAAQ,CAAC,2BAA2B,CAAC;;IAG1C,MAAM,gB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C/C,KAAA,CACF;AACH;;;;"}
|
package/dist/types/index.d.ts
CHANGED
package/dist/types/stream.d.ts
CHANGED
|
@@ -1,16 +1,8 @@
|
|
|
1
1
|
import type { AIMessageChunk } from '@langchain/core/messages';
|
|
2
|
-
import type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';
|
|
3
2
|
import type { Graph } from '@/graphs';
|
|
4
3
|
import type * as t from '@/types';
|
|
5
|
-
export declare const getMessageId: (stepKey: string, graph: Graph<t.BaseGraphState>, returnExistingId?: boolean) => string | undefined;
|
|
6
|
-
export declare const handleToolCalls: (toolCalls?: ToolCall[], metadata?: Record<string, unknown>, graph?: Graph) => void;
|
|
7
4
|
export declare class ChatModelStreamHandler implements t.EventHandler {
|
|
8
5
|
handle(event: string, data: t.StreamEventData, metadata?: Record<string, unknown>, graph?: Graph): void;
|
|
9
|
-
handleToolCallChunks: ({ graph, stepKey, toolCallChunks, }: {
|
|
10
|
-
graph: Graph;
|
|
11
|
-
stepKey: string;
|
|
12
|
-
toolCallChunks: ToolCallChunk[];
|
|
13
|
-
}) => void;
|
|
14
6
|
handleReasoning(chunk: Partial<AIMessageChunk>, graph: Graph): void;
|
|
15
7
|
}
|
|
16
8
|
export declare function createContentAggregator(): t.ContentAggregatorResult;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';
|
|
2
|
+
import type { Graph } from '@/graphs';
|
|
3
|
+
export declare function handleToolCallChunks({ graph, stepKey, toolCallChunks, }: {
|
|
4
|
+
graph: Graph;
|
|
5
|
+
stepKey: string;
|
|
6
|
+
toolCallChunks: ToolCallChunk[];
|
|
7
|
+
}): void;
|
|
8
|
+
export declare const handleToolCalls: (toolCalls?: ToolCall[], metadata?: Record<string, unknown>, graph?: Graph) => void;
|
|
@@ -22,6 +22,7 @@ export type ResultReference = {
|
|
|
22
22
|
attribution?: string;
|
|
23
23
|
};
|
|
24
24
|
export interface SearchResultData {
|
|
25
|
+
turn?: number;
|
|
25
26
|
organic?: ProcessedOrganic[];
|
|
26
27
|
topStories?: ProcessedTopStory[];
|
|
27
28
|
images?: ImageResult[];
|
|
@@ -86,13 +87,6 @@ export interface ScraperContentResult {
|
|
|
86
87
|
export interface ScraperExtractionResult {
|
|
87
88
|
no_extraction: ScraperContentResult;
|
|
88
89
|
}
|
|
89
|
-
export interface SearXNGResult {
|
|
90
|
-
title?: string;
|
|
91
|
-
url?: string;
|
|
92
|
-
content?: string;
|
|
93
|
-
publishedDate?: string;
|
|
94
|
-
img_src?: string;
|
|
95
|
-
}
|
|
96
90
|
export interface JinaRerankerResult {
|
|
97
91
|
index: number;
|
|
98
92
|
relevance_score: number;
|
|
@@ -482,3 +476,10 @@ export interface SearxNGSearchPayload {
|
|
|
482
476
|
*/
|
|
483
477
|
disabled_engines?: string;
|
|
484
478
|
}
|
|
479
|
+
export interface SearXNGResult {
|
|
480
|
+
title?: string;
|
|
481
|
+
url?: string;
|
|
482
|
+
content?: string;
|
|
483
|
+
publishedDate?: string;
|
|
484
|
+
img_src?: string;
|
|
485
|
+
}
|
package/package.json
CHANGED
package/src/events.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
/* eslint-disable no-console */
|
|
2
2
|
// src/events.ts
|
|
3
|
-
import type {
|
|
3
|
+
import type {
|
|
4
|
+
UsageMetadata,
|
|
5
|
+
BaseMessageFields,
|
|
6
|
+
} from '@langchain/core/messages';
|
|
4
7
|
import type { Graph } from '@/graphs';
|
|
5
8
|
import type * as t from '@/types';
|
|
6
|
-
import { handleToolCalls } from '@/
|
|
9
|
+
import { handleToolCalls } from '@/tools/handlers';
|
|
7
10
|
import { Providers } from '@/common';
|
|
8
11
|
|
|
9
12
|
export class HandlerRegistry {
|
|
@@ -27,7 +30,12 @@ export class ModelEndHandler implements t.EventHandler {
|
|
|
27
30
|
this.collectedUsage = collectedUsage;
|
|
28
31
|
}
|
|
29
32
|
|
|
30
|
-
handle(
|
|
33
|
+
handle(
|
|
34
|
+
event: string,
|
|
35
|
+
data: t.ModelEndData,
|
|
36
|
+
metadata?: Record<string, unknown>,
|
|
37
|
+
graph?: Graph
|
|
38
|
+
): void {
|
|
31
39
|
if (!graph || !metadata) {
|
|
32
40
|
console.warn(`Graph or metadata not found in ${event} event`);
|
|
33
41
|
return;
|
|
@@ -43,9 +51,12 @@ export class ModelEndHandler implements t.EventHandler {
|
|
|
43
51
|
}
|
|
44
52
|
|
|
45
53
|
console.log(`====== ${event.toUpperCase()} ======`);
|
|
46
|
-
console.dir(
|
|
47
|
-
|
|
48
|
-
|
|
54
|
+
console.dir(
|
|
55
|
+
{
|
|
56
|
+
usage,
|
|
57
|
+
},
|
|
58
|
+
{ depth: null }
|
|
59
|
+
);
|
|
49
60
|
|
|
50
61
|
if (metadata.provider !== Providers.GOOGLE) {
|
|
51
62
|
return;
|
|
@@ -60,7 +71,12 @@ export class ToolEndHandler implements t.EventHandler {
|
|
|
60
71
|
constructor(callback?: t.ToolEndCallback) {
|
|
61
72
|
this.callback = callback;
|
|
62
73
|
}
|
|
63
|
-
handle(
|
|
74
|
+
handle(
|
|
75
|
+
event: string,
|
|
76
|
+
data: t.StreamEventData | undefined,
|
|
77
|
+
metadata?: Record<string, unknown>,
|
|
78
|
+
graph?: Graph
|
|
79
|
+
): void {
|
|
64
80
|
if (!graph || !metadata) {
|
|
65
81
|
console.warn(`Graph or metadata not found in ${event} event`);
|
|
66
82
|
return;
|
|
@@ -74,14 +90,17 @@ export class ToolEndHandler implements t.EventHandler {
|
|
|
74
90
|
|
|
75
91
|
this.callback?.(toolEndData, metadata);
|
|
76
92
|
|
|
77
|
-
graph.handleToolCallCompleted(
|
|
93
|
+
graph.handleToolCallCompleted(
|
|
94
|
+
{ input: toolEndData.input, output: toolEndData.output },
|
|
95
|
+
metadata
|
|
96
|
+
);
|
|
78
97
|
}
|
|
79
98
|
}
|
|
80
99
|
|
|
81
100
|
export class TestLLMStreamHandler implements t.EventHandler {
|
|
82
101
|
handle(event: string, data: t.StreamEventData | undefined): void {
|
|
83
102
|
const chunk = data?.chunk;
|
|
84
|
-
const
|
|
103
|
+
const isMessageChunk = !!(chunk && 'message' in chunk);
|
|
85
104
|
const msg = isMessageChunk ? chunk.message : undefined;
|
|
86
105
|
if (msg && msg.tool_call_chunks && msg.tool_call_chunks.length > 0) {
|
|
87
106
|
console.log(msg.tool_call_chunks);
|
|
@@ -116,11 +135,17 @@ export class TestChatStreamHandler implements t.EventHandler {
|
|
|
116
135
|
}
|
|
117
136
|
|
|
118
137
|
export class LLMStreamHandler implements t.EventHandler {
|
|
119
|
-
handle(
|
|
138
|
+
handle(
|
|
139
|
+
event: string,
|
|
140
|
+
data: t.StreamEventData | undefined,
|
|
141
|
+
metadata?: Record<string, unknown>
|
|
142
|
+
): void {
|
|
120
143
|
const chunk = data?.chunk;
|
|
121
|
-
const
|
|
144
|
+
const isMessageChunk = !!(chunk && 'message' in chunk);
|
|
122
145
|
const msg = isMessageChunk && chunk.message;
|
|
123
|
-
if (metadata) {
|
|
146
|
+
if (metadata) {
|
|
147
|
+
console.log(metadata);
|
|
148
|
+
}
|
|
124
149
|
if (msg && msg.tool_call_chunks && msg.tool_call_chunks.length > 0) {
|
|
125
150
|
console.log(msg.tool_call_chunks);
|
|
126
151
|
} else if (msg && msg.content) {
|
|
@@ -133,12 +158,21 @@ export class LLMStreamHandler implements t.EventHandler {
|
|
|
133
158
|
}
|
|
134
159
|
}
|
|
135
160
|
|
|
136
|
-
export const createMetadataAggregator = (
|
|
161
|
+
export const createMetadataAggregator = (
|
|
162
|
+
_collected?: Record<
|
|
163
|
+
string,
|
|
164
|
+
NonNullable<BaseMessageFields['response_metadata']>
|
|
165
|
+
>[]
|
|
166
|
+
): t.MetadataAggregatorResult => {
|
|
137
167
|
const collected = _collected || [];
|
|
138
168
|
|
|
139
169
|
const handleLLMEnd: t.HandleLLMEnd = (output) => {
|
|
140
170
|
const { generations } = output;
|
|
141
|
-
const lastMessageOutput = (
|
|
171
|
+
const lastMessageOutput = (
|
|
172
|
+
generations[generations.length - 1] as
|
|
173
|
+
| (t.StreamGeneration | undefined)[]
|
|
174
|
+
| undefined
|
|
175
|
+
)?.[0];
|
|
142
176
|
if (!lastMessageOutput) {
|
|
143
177
|
return;
|
|
144
178
|
}
|
|
@@ -149,4 +183,4 @@ export const createMetadataAggregator = (_collected?: Record<string, NonNullable
|
|
|
149
183
|
};
|
|
150
184
|
|
|
151
185
|
return { handleLLMEnd, collected };
|
|
152
|
-
};
|
|
186
|
+
};
|