@librechat/agents 2.3.1 → 2.3.3
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/graphs/Graph.cjs +6 -6
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/llm.cjs +7 -7
- package/dist/cjs/llm/anthropic/llm.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +6 -6
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +24 -24
- package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -1
- package/dist/cjs/llm/fake.cjs.map +1 -1
- package/dist/cjs/llm/text.cjs.map +1 -1
- package/dist/cjs/main.cjs +3 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/core.cjs +6 -6
- package/dist/cjs/messages/core.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +11 -9
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/messages/prune.cjs +155 -205
- package/dist/cjs/messages/prune.cjs.map +1 -1
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/stream.cjs +7 -7
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +1 -1
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/utils/tokens.cjs +3 -3
- package/dist/cjs/utils/tokens.cjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +6 -6
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/llm/anthropic/llm.mjs +7 -7
- package/dist/esm/llm/anthropic/llm.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +6 -6
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_outputs.mjs +24 -24
- package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -1
- package/dist/esm/llm/fake.mjs.map +1 -1
- package/dist/esm/llm/text.mjs.map +1 -1
- package/dist/esm/main.mjs +1 -1
- package/dist/esm/messages/core.mjs +6 -6
- package/dist/esm/messages/core.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +11 -9
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/messages/prune.mjs +153 -206
- package/dist/esm/messages/prune.mjs.map +1 -1
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/stream.mjs +7 -7
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +1 -1
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/utils/tokens.mjs +3 -3
- package/dist/esm/utils/tokens.mjs.map +1 -1
- package/dist/types/messages/format.d.ts +1 -2
- package/dist/types/messages/prune.d.ts +31 -2
- package/dist/types/types/stream.d.ts +2 -2
- package/dist/types/utils/tokens.d.ts +1 -1
- package/package.json +4 -3
- package/src/graphs/Graph.ts +8 -8
- package/src/llm/anthropic/llm.ts +7 -8
- package/src/llm/anthropic/types.ts +4 -4
- package/src/llm/anthropic/utils/message_inputs.ts +6 -6
- package/src/llm/anthropic/utils/message_outputs.ts +39 -39
- package/src/llm/fake.ts +2 -2
- package/src/llm/text.ts +1 -1
- package/src/messages/core.ts +9 -9
- package/src/messages/format.ts +43 -42
- package/src/messages/formatAgentMessages.test.ts +35 -35
- package/src/messages/formatAgentMessages.tools.test.ts +30 -30
- package/src/messages/prune.ts +182 -255
- package/src/messages/shiftIndexTokenCountMap.test.ts +18 -18
- package/src/mockStream.ts +1 -1
- package/src/run.ts +2 -2
- package/src/specs/prune.test.ts +89 -89
- package/src/specs/reasoning.test.ts +1 -1
- package/src/specs/thinking-prune.test.ts +265 -261
- package/src/specs/tool-error.test.ts +16 -17
- package/src/stream.ts +21 -18
- package/src/tools/ToolNode.ts +1 -1
- package/src/types/stream.ts +4 -3
- package/src/utils/tokens.ts +12 -12
package/dist/cjs/stream.cjs
CHANGED
|
@@ -51,7 +51,7 @@ const handleToolCalls = (toolCalls, metadata, graph) => {
|
|
|
51
51
|
prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);
|
|
52
52
|
prevRunStep = graph.getRunStep(prevStepId);
|
|
53
53
|
}
|
|
54
|
-
catch
|
|
54
|
+
catch {
|
|
55
55
|
// no previous step
|
|
56
56
|
}
|
|
57
57
|
const dispatchToolCallIds = (lastMessageStepId) => {
|
|
@@ -102,7 +102,7 @@ class ChatModelStreamHandler {
|
|
|
102
102
|
const content = chunk.additional_kwargs?.[graph.reasoningKey] ?? chunk.content;
|
|
103
103
|
this.handleReasoning(chunk, graph);
|
|
104
104
|
let hasToolCalls = false;
|
|
105
|
-
if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id)) {
|
|
105
|
+
if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id != null && tc.id !== '')) {
|
|
106
106
|
hasToolCalls = true;
|
|
107
107
|
handleToolCalls(chunk.tool_calls, metadata, graph);
|
|
108
108
|
}
|
|
@@ -146,7 +146,6 @@ class ChatModelStreamHandler {
|
|
|
146
146
|
const stepId = graph.getStepIdByKey(stepKey);
|
|
147
147
|
const runStep = graph.getRunStep(stepId);
|
|
148
148
|
if (!runStep) {
|
|
149
|
-
// eslint-disable-next-line no-console
|
|
150
149
|
console.warn(`\n
|
|
151
150
|
==============================================================
|
|
152
151
|
|
|
@@ -189,12 +188,13 @@ hasToolCallChunks: ${hasToolCallChunks}
|
|
|
189
188
|
});
|
|
190
189
|
}
|
|
191
190
|
}
|
|
192
|
-
else if (content.every((c) => c.type?.startsWith(_enum.ContentTypes.TEXT))) {
|
|
191
|
+
else if (content.every((c) => c.type?.startsWith(_enum.ContentTypes.TEXT) ?? false)) {
|
|
193
192
|
graph.dispatchMessageDelta(stepId, {
|
|
194
193
|
content,
|
|
195
194
|
});
|
|
196
195
|
}
|
|
197
|
-
else if (content.every((c) => c.type?.startsWith(_enum.ContentTypes.THINKING)
|
|
196
|
+
else if (content.every((c) => (c.type?.startsWith(_enum.ContentTypes.THINKING) ?? false) ||
|
|
197
|
+
(c.type?.startsWith(_enum.ContentTypes.REASONING_CONTENT) ?? false))) {
|
|
198
198
|
graph.dispatchReasoningDelta(stepId, {
|
|
199
199
|
content: content.map((c) => ({
|
|
200
200
|
type: _enum.ContentTypes.THINK,
|
|
@@ -210,7 +210,7 @@ hasToolCallChunks: ${hasToolCallChunks}
|
|
|
210
210
|
prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);
|
|
211
211
|
prevRunStep = graph.getRunStep(prevStepId);
|
|
212
212
|
}
|
|
213
|
-
catch
|
|
213
|
+
catch {
|
|
214
214
|
/** Edge Case: If no previous step exists, create a new message creation step */
|
|
215
215
|
const message_id = getMessageId(stepKey, graph, true) ?? '';
|
|
216
216
|
prevStepId = graph.dispatchRunStep(stepKey, {
|
|
@@ -335,7 +335,7 @@ function createContentAggregator() {
|
|
|
335
335
|
}
|
|
336
336
|
else if (partType.startsWith(_enum.ContentTypes.AGENT_UPDATE) &&
|
|
337
337
|
_enum.ContentTypes.AGENT_UPDATE in contentPart &&
|
|
338
|
-
contentPart.agent_update) {
|
|
338
|
+
contentPart.agent_update != null) {
|
|
339
339
|
const update = {
|
|
340
340
|
type: _enum.ContentTypes.AGENT_UPDATE,
|
|
341
341
|
agent_update: contentPart.agent_update,
|
package/dist/cjs/stream.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.cjs","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\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 (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: [toolCallId],\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\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(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 } else if (content.every((c) => c.type?.startsWith(ContentTypes.THINKING) || c.type?.startsWith(ContentTypes.REASONING_CONTENT))) {\n graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think: (c as t.ThinkingContentText).thinking ?? (c as t.BedrockReasoningContentText).reasoningText?.text ?? '',\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 (e) {\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 (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 let reasoning_content = chunk.additional_kwargs?.[graph.reasoningKey] as string | undefined;\n if (Array.isArray(chunk.content) && (chunk.content[0]?.type === 'thinking' || chunk.content[0]?.type === 'reasoning_content')) {\n reasoning_content = 'valid';\n }\n if (reasoning_content != null && reasoning_content && (chunk.content == null || chunk.content === '' || reasoning_content === 'valid')) {\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 (\n partType.startsWith(ContentTypes.AGENT_UPDATE) &&\n ContentTypes.AGENT_UPDATE in contentPart &&\n contentPart.agent_update\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 (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.AgentUpdate | 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_AGENT_UPDATE && (data as t.AgentUpdate | undefined)?.agent_update) {\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\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":["nanoid","StepTypes","ContentTypes","ToolCallTypes","GraphEvents"],"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,eAAe,EAAE;AAC9C,QAAA,KAAK,CAAC,yBAAyB,CAAC,MAAM,CAAC,OAAO,CAAC;QAC/C,KAAK,CAAC,mBAAmB,CAAC,GAAG,CAAC,OAA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AM,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,CAAC,0DAA0D,CAAC;gBACxE;;AAGF,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAEF,kBAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B;YAED,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC;;AAGnD,KAAC;AAED,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE;AACpD;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"stream.cjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport { 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 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 type: 'text',\n text: '',\n tool_call_ids: [toolCallId],\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\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(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 != null && 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\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) ?? false)) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n } else if (content.every(\n (c) =>\n (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||\n (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false)\n )) {\n graph.dispatchReasoningDelta(stepId, {\n content: content.map((c) => ({\n type: ContentTypes.THINK,\n think: (c as t.ThinkingContentText).thinking ?? (c as Partial<t.BedrockReasoningContentText>).reasoningText?.text ?? '',\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 && 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 (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 let reasoning_content = chunk.additional_kwargs?.[graph.reasoningKey] as string | undefined;\n if (Array.isArray(chunk.content) && (chunk.content[0]?.type === 'thinking' || chunk.content[0]?.type === 'reasoning_content')) {\n reasoning_content = 'valid';\n }\n if (reasoning_content != null && reasoning_content && (chunk.content == null || chunk.content === '' || reasoning_content === 'valid')) {\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 (\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 (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.AgentUpdate | 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_AGENT_UPDATE && (data as t.AgentUpdate | undefined)?.agent_update) {\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\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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AAE,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;;;;;;;"}
|
|
@@ -70,7 +70,7 @@ class ToolNode extends run.RunnableCallable {
|
|
|
70
70
|
id: call.id,
|
|
71
71
|
name: call.name,
|
|
72
72
|
input: call.args,
|
|
73
|
-
}, config
|
|
73
|
+
}, config.metadata);
|
|
74
74
|
return new messages.ToolMessage({
|
|
75
75
|
content: `Error: ${e.message}\n Please fix your mistakes.`,
|
|
76
76
|
name: call.name,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolNode.cjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import { END, MessagesAnnotation, isCommand, isGraphInterrupt } from '@langchain/langgraph';\nimport { ToolMessage, isBaseMessage } from '@langchain/core/messages';\nimport type { RunnableConfig, RunnableToolLike } from '@langchain/core/runnables';\nimport type { BaseMessage, AIMessage } from '@langchain/core/messages';\nimport type { StructuredToolInterface } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport{ RunnableCallable } from '@/utils';\nimport { GraphNodeKeys } from '@/common';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\n tools: t.GenericTool[];\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\n private loadRuntimeTools?: t.ToolRefGenerator;\n handleToolErrors = true;\n toolCallStepIds?: Map<string, string>;\n errorHandler?: t.ToolNodeConstructorParams['errorHandler'];\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n errorHandler,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n }: t.ToolNodeConstructorParams) {\n super({ name, tags, func: (input, config) => this.run(input, config) });\n this.tools = tools;\n this.toolMap = toolMap ?? new Map(tools.map(tool => [tool.name, tool]));\n this.toolCallStepIds = toolCallStepIds;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.loadRuntimeTools = loadRuntimeTools;\n this.errorHandler = errorHandler;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n const message = Array.isArray(input)\n ? input[input.length - 1]\n : input.messages[input.messages.length - 1];\n\n if (message._getType() !== 'ai') {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n (message as AIMessage).tool_calls ?? []\n );\n this.tools = tools;\n this.toolMap = toolMap ?? new Map(tools.map(tool => [tool.name, tool]));\n }\n const outputs = await Promise.all(\n (message as AIMessage).tool_calls?.map(async (call) => {\n const tool = this.toolMap.get(call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n const args = call.args;\n const stepId = this.toolCallStepIds?.get(call.id!);\n const output = await tool.invoke(\n { ...call, args, type: 'tool_call', stepId },\n config,\n );\n if (\n (isBaseMessage(output) && output._getType() === 'tool') ||\n isCommand(output)\n ) {\n return output;\n } else {\n return new ToolMessage({\n name: tool.name,\n content:\n typeof output === 'string' ? output : JSON.stringify(output),\n tool_call_id: call.id!,\n });\n }\n } catch (_e: unknown) {\n const e = _e as Error;\n if (!this.handleToolErrors) {\n throw e;\n }\n if (isGraphInterrupt(e)) {\n throw e;\n }\n this.errorHandler?.({\n error: e,\n id: call.id!,\n name: call.name,\n input: call.args,\n }, config
|
|
1
|
+
{"version":3,"file":"ToolNode.cjs","sources":["../../../src/tools/ToolNode.ts"],"sourcesContent":["import { END, MessagesAnnotation, isCommand, isGraphInterrupt } from '@langchain/langgraph';\nimport { ToolMessage, isBaseMessage } from '@langchain/core/messages';\nimport type { RunnableConfig, RunnableToolLike } from '@langchain/core/runnables';\nimport type { BaseMessage, AIMessage } from '@langchain/core/messages';\nimport type { StructuredToolInterface } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport{ RunnableCallable } from '@/utils';\nimport { GraphNodeKeys } from '@/common';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class ToolNode<T = any> extends RunnableCallable<T, T> {\n tools: t.GenericTool[];\n private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;\n private loadRuntimeTools?: t.ToolRefGenerator;\n handleToolErrors = true;\n toolCallStepIds?: Map<string, string>;\n errorHandler?: t.ToolNodeConstructorParams['errorHandler'];\n\n constructor({\n tools,\n toolMap,\n name,\n tags,\n errorHandler,\n toolCallStepIds,\n handleToolErrors,\n loadRuntimeTools,\n }: t.ToolNodeConstructorParams) {\n super({ name, tags, func: (input, config) => this.run(input, config) });\n this.tools = tools;\n this.toolMap = toolMap ?? new Map(tools.map(tool => [tool.name, tool]));\n this.toolCallStepIds = toolCallStepIds;\n this.handleToolErrors = handleToolErrors ?? this.handleToolErrors;\n this.loadRuntimeTools = loadRuntimeTools;\n this.errorHandler = errorHandler;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n protected async run(input: any, config: RunnableConfig): Promise<T> {\n const message = Array.isArray(input)\n ? input[input.length - 1]\n : input.messages[input.messages.length - 1];\n\n if (message._getType() !== 'ai') {\n throw new Error('ToolNode only accepts AIMessages as input.');\n }\n\n if (this.loadRuntimeTools) {\n const { tools, toolMap } = this.loadRuntimeTools(\n (message as AIMessage).tool_calls ?? []\n );\n this.tools = tools;\n this.toolMap = toolMap ?? new Map(tools.map(tool => [tool.name, tool]));\n }\n const outputs = await Promise.all(\n (message as AIMessage).tool_calls?.map(async (call) => {\n const tool = this.toolMap.get(call.name);\n try {\n if (tool === undefined) {\n throw new Error(`Tool \"${call.name}\" not found.`);\n }\n const args = call.args;\n const stepId = this.toolCallStepIds?.get(call.id!);\n const output = await tool.invoke(\n { ...call, args, type: 'tool_call', stepId },\n config,\n );\n if (\n (isBaseMessage(output) && output._getType() === 'tool') ||\n isCommand(output)\n ) {\n return output;\n } else {\n return new ToolMessage({\n name: tool.name,\n content:\n typeof output === 'string' ? output : JSON.stringify(output),\n tool_call_id: call.id!,\n });\n }\n } catch (_e: unknown) {\n const e = _e as Error;\n if (!this.handleToolErrors) {\n throw e;\n }\n if (isGraphInterrupt(e)) {\n throw e;\n }\n this.errorHandler?.({\n error: e,\n id: call.id!,\n name: call.name,\n input: call.args,\n }, config.metadata);\n return new ToolMessage({\n content: `Error: ${e.message}\\n Please fix your mistakes.`,\n name: call.name,\n tool_call_id: call.id ?? '',\n });\n }\n }) ?? []\n );\n\n if (!outputs.some(isCommand)) {\n return (Array.isArray(input) ? outputs : { messages: outputs }) as T;\n }\n\n const combinedOutputs = outputs.map((output) => {\n if (isCommand(output)) {\n return output;\n }\n return Array.isArray(input) ? [output] : { messages: [output] };\n });\n return combinedOutputs as T;\n }\n}\n\nexport function toolsCondition(\n state: BaseMessage[] | typeof MessagesAnnotation.State\n): 'tools' | typeof END {\n const message = Array.isArray(state)\n ? state[state.length - 1]\n : state.messages[state.messages.length - 1];\n\n if (\n 'tool_calls' in message &&\n ((message as AIMessage).tool_calls?.length ?? 0) > 0\n ) {\n return GraphNodeKeys.TOOLS;\n } else {\n return END;\n }\n}"],"names":["RunnableCallable","isBaseMessage","isCommand","ToolMessage","isGraphInterrupt","GraphNodeKeys","END"],"mappings":";;;;;;;;AASA;AACM,MAAO,QAAkB,SAAQA,oBAAsB,CAAA;AAC3D,IAAA,KAAK;AACG,IAAA,OAAO;AACP,IAAA,gBAAgB;IACxB,gBAAgB,GAAG,IAAI;AACvB,IAAA,eAAe;AACf,IAAA,YAAY;AAEZ,IAAA,WAAA,CAAY,EACV,KAAK,EACL,OAAO,EACP,IAAI,EACJ,IAAI,EACJ,YAAY,EACZ,eAAe,EACf,gBAAgB,EAChB,gBAAgB,GACY,EAAA;QAC5B,KAAK,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC,GAAG,CAAC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AC,IAAI,CAAC,EACpD;QACA,OAAOG,mBAAa,CAAC,KAAK;;SACrB;AACL,QAAA,OAAOC,aAAG;;AAEd;;;;;"}
|
|
@@ -4,10 +4,10 @@ var lite = require('js-tiktoken/lite');
|
|
|
4
4
|
var _enum = require('../common/enum.cjs');
|
|
5
5
|
|
|
6
6
|
function getTokenCountForMessage(message, getTokenCount) {
|
|
7
|
-
|
|
7
|
+
const tokensPerMessage = 3;
|
|
8
8
|
const processValue = (value) => {
|
|
9
9
|
if (Array.isArray(value)) {
|
|
10
|
-
for (
|
|
10
|
+
for (const item of value) {
|
|
11
11
|
if (!item ||
|
|
12
12
|
!item.type ||
|
|
13
13
|
item.type === _enum.ContentTypes.ERROR ||
|
|
@@ -51,7 +51,7 @@ function getTokenCountForMessage(message, getTokenCount) {
|
|
|
51
51
|
return numTokens;
|
|
52
52
|
}
|
|
53
53
|
const createTokenCounter = async () => {
|
|
54
|
-
const res = await fetch(
|
|
54
|
+
const res = await fetch('https://tiktoken.pages.dev/js/o200k_base.json');
|
|
55
55
|
const o200k_base = await res.json();
|
|
56
56
|
const countTokens = (text) => {
|
|
57
57
|
const enc = new lite.Tiktoken(o200k_base);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tokens.cjs","sources":["../../../src/utils/tokens.ts"],"sourcesContent":["import { Tiktoken } from
|
|
1
|
+
{"version":3,"file":"tokens.cjs","sources":["../../../src/utils/tokens.ts"],"sourcesContent":["import { Tiktoken } from 'js-tiktoken/lite';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport { ContentTypes } from '@/common/enum';\n\nexport function getTokenCountForMessage(message: BaseMessage, getTokenCount: (text: string) => number): number {\n const tokensPerMessage = 3;\n\n const processValue = (value: unknown): void => {\n if (Array.isArray(value)) {\n for (const item of value) {\n if (\n !item ||\n !item.type ||\n item.type === ContentTypes.ERROR ||\n item.type === ContentTypes.IMAGE_URL\n ) {\n continue;\n }\n\n if (item.type === ContentTypes.TOOL_CALL && item.tool_call != null) {\n const toolName = item.tool_call?.name || '';\n if (toolName != null && toolName && typeof toolName === 'string') {\n numTokens += getTokenCount(toolName);\n }\n\n const args = item.tool_call?.args || '';\n if (args != null && args && typeof args === 'string') {\n numTokens += getTokenCount(args);\n }\n\n const output = item.tool_call?.output || '';\n if (output != null && output && typeof output === 'string') {\n numTokens += getTokenCount(output);\n }\n continue;\n }\n\n const nestedValue = item[item.type];\n\n if (!nestedValue) {\n continue;\n }\n\n processValue(nestedValue);\n }\n } else if (typeof value === 'string') {\n numTokens += getTokenCount(value);\n } else if (typeof value === 'number') {\n numTokens += getTokenCount(value.toString());\n } else if (typeof value === 'boolean') {\n numTokens += getTokenCount(value.toString());\n }\n };\n\n let numTokens = tokensPerMessage;\n processValue(message.content);\n return numTokens;\n}\n\nexport const createTokenCounter = async () => {\n const res = await fetch('https://tiktoken.pages.dev/js/o200k_base.json');\n const o200k_base = await res.json();\n\n const countTokens = (text: string): number => {\n const enc = new Tiktoken(o200k_base);\n return enc.encode(text).length;\n };\n\n return (message: BaseMessage): number => getTokenCountForMessage(message, countTokens);\n};"],"names":["ContentTypes","Tiktoken"],"mappings":";;;;;AAIgB,SAAA,uBAAuB,CAAC,OAAoB,EAAE,aAAuC,EAAA;IACnG,MAAM,gBAAgB,GAAG,CAAC;AAE1B,IAAA,MAAM,YAAY,GAAG,CAAC,KAAc,KAAU;AAC5C,QAAA,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;AACxB,YAAA,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;AACxB,gBAAA,IACE,CAAC,IAAI;oBACL,CAAC,IAAI,CAAC,IAAI;AACV,oBAAA,IAAI,CAAC,IAAI,KAAKA,kBAAY,CAAC,KAAK;AAChC,oBAAA,IAAI,CAAC,IAAI,KAAKA,kBAAY,CAAC,SAAS,EACpC;oBACA;;AAGF,gBAAA,IAAI,IAAI,CAAC,IAAI,KAAKA,kBAAY,CAAC,SAAS,IAAI,IAAI,CAAC,SAAS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kBAAkB,GAAG,YAAW;AAC3C,IAAA,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,+CAA+C,CAAC;AACxE,IAAA,MAAM,UAAU,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE;AAEnC,IAAA,MAAM,WAAW,GAAG,CAAC,IAAY,KAAY;AAC3C,QAAA,MAAM,GAAG,GAAG,IAAIC,aAAQ,CAAC,UAAU,CAAC;QACpC,OAAO,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM;AAChC,KAAC;IAED,OAAO,CAAC,OAAoB,KAAa,uBAAuB,CAAC,OAAO,EAAE,WAAW,CAAC;AACxF;;;;;"}
|
|
@@ -75,13 +75,13 @@ class StandardGraph extends Graph {
|
|
|
75
75
|
if (additional_instructions) {
|
|
76
76
|
finalInstructions = finalInstructions ? `${finalInstructions}\n\n${additional_instructions}` : additional_instructions;
|
|
77
77
|
}
|
|
78
|
-
if (finalInstructions && provider === Providers.ANTHROPIC && clientOptions
|
|
78
|
+
if (finalInstructions && provider === Providers.ANTHROPIC && clientOptions.clientOptions?.defaultHeaders?.['anthropic-beta']?.includes('prompt-caching')) {
|
|
79
79
|
finalInstructions = {
|
|
80
80
|
content: [
|
|
81
81
|
{
|
|
82
|
-
type:
|
|
82
|
+
type: 'text',
|
|
83
83
|
text: instructions,
|
|
84
|
-
cache_control: { type:
|
|
84
|
+
cache_control: { type: 'ephemeral' },
|
|
85
85
|
},
|
|
86
86
|
],
|
|
87
87
|
};
|
|
@@ -263,8 +263,8 @@ class StandardGraph extends Graph {
|
|
|
263
263
|
let messagesToUse = messages;
|
|
264
264
|
if (!this.pruneMessages && this.tokenCounter && this.maxContextTokens && this.indexTokenCountMap[0] != null) {
|
|
265
265
|
const isAnthropicWithThinking = ((this.provider === Providers.ANTHROPIC
|
|
266
|
-
|| (this.provider === Providers.BEDROCK && this.clientOptions
|
|
267
|
-
&& this.clientOptions
|
|
266
|
+
|| (this.provider === Providers.BEDROCK && this.clientOptions.model?.includes('anthropic')))
|
|
267
|
+
&& this.clientOptions.thinking != null);
|
|
268
268
|
this.pruneMessages = createPruneMessages({
|
|
269
269
|
indexTokenCountMap: this.indexTokenCountMap,
|
|
270
270
|
maxTokens: this.maxContextTokens,
|
|
@@ -335,7 +335,7 @@ class StandardGraph extends Graph {
|
|
|
335
335
|
}
|
|
336
336
|
result = { messages: [finalMessage] };
|
|
337
337
|
}
|
|
338
|
-
this.storeUsageMetadata(result
|
|
338
|
+
this.storeUsageMetadata(result.messages?.[0]);
|
|
339
339
|
return result;
|
|
340
340
|
};
|
|
341
341
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Graph.mjs","sources":["../../../src/graphs/Graph.ts"],"sourcesContent":["// src/graphs/Graph.ts\nimport { nanoid } from 'nanoid';\nimport { concat } from '@langchain/core/utils/stream';\nimport { ToolNode } from '@langchain/langgraph/prebuilt';\nimport { ChatVertexAI } from '@langchain/google-vertexai';\nimport { START, END, StateGraph } from '@langchain/langgraph';\nimport { ChatOpenAI, AzureChatOpenAI } from '@langchain/openai';\nimport { Runnable, RunnableConfig } from '@langchain/core/runnables';\nimport { dispatchCustomEvent } from '@langchain/core/callbacks/dispatch';\nimport { AIMessageChunk, ToolMessage, SystemMessage } from '@langchain/core/messages';\nimport type { BaseMessage, BaseMessageFields, UsageMetadata } from '@langchain/core/messages';\nimport type * as t from '@/types';\nimport { Providers, GraphEvents, GraphNodeKeys, StepTypes, Callback, ContentTypes } from '@/common';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport { getChatModelClass, manualToolStreamProviders } from '@/llm/providers';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport {\n createPruneMessages,\n modifyDeltaProperties,\n formatArtifactPayload,\n convertMessagesToContent,\n formatAnthropicArtifactContent,\n} from '@/messages';\nimport { resetIfNotEmpty, isOpenAILike, isGoogleLike, joinKeys, sleep } from '@/utils';\nimport { createFakeStreamingLLM } from '@/llm/fake';\nimport { HandlerRegistry } from '@/events';\n\nconst { AGENT, TOOLS } = GraphNodeKeys;\nexport type GraphNode = GraphNodeKeys | typeof START;\nexport type ClientCallback<T extends unknown[]> = (graph: StandardGraph, ...args: T) => void;\nexport type ClientCallbacks = {\n [Callback.TOOL_ERROR]?: ClientCallback<[Error, string]>;\n [Callback.TOOL_START]?: ClientCallback<unknown[]>;\n [Callback.TOOL_END]?: ClientCallback<unknown[]>;\n}\nexport type SystemCallbacks = {\n [K in keyof ClientCallbacks]: ClientCallbacks[K] extends ClientCallback<infer Args>\n ? (...args: Args) => void\n : never;\n};\n\nexport abstract class Graph<\n T extends t.BaseGraphState = t.BaseGraphState,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n TNodeName extends string = string,\n> {\n abstract resetValues(): void;\n abstract createGraphState(): t.GraphStateChannels<T>;\n abstract initializeTools(): CustomToolNode<T> | ToolNode<T>;\n abstract initializeModel(): Runnable;\n abstract getRunMessages(): BaseMessage[] | undefined;\n abstract getContentParts(): t.MessageContentComplex[] | undefined;\n abstract generateStepId(stepKey: string): [string, number];\n abstract getKeyList(metadata: Record<string, unknown> | undefined): (string | number | undefined)[];\n abstract getStepKey(metadata: Record<string, unknown> | undefined): string;\n abstract checkKeyList(keyList: (string | number | undefined)[]): boolean;\n abstract getStepIdByKey(stepKey: string, index?: number): string\n abstract getRunStep(stepId: string): t.RunStep | undefined;\n abstract dispatchRunStep(stepKey: string, stepDetails: t.StepDetails): string;\n abstract dispatchRunStepDelta(id: string, delta: t.ToolCallDelta): void;\n abstract dispatchMessageDelta(id: string, delta: t.MessageDelta): void;\n abstract dispatchReasoningDelta(stepId: string, delta: t.ReasoningDelta): void;\n abstract handleToolCallCompleted(data: t.ToolEndData, metadata?: Record<string, unknown>): void;\n\n abstract createCallModel(): (state: T, config?: RunnableConfig) => Promise<Partial<T>>;\n abstract createWorkflow(): t.CompiledWorkflow<T>;\n lastToken?: string;\n tokenTypeSwitch?: 'reasoning' | 'content';\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n currentTokenType: ContentTypes.TEXT | ContentTypes.THINK = ContentTypes.TEXT;\n messageStepHasToolCalls: Map<string, boolean> = new Map();\n messageIdsByStepKey: Map<string, string> = new Map();\n prelimMessageIdsByStepKey: Map<string, string> = new Map();\n config: RunnableConfig | undefined;\n contentData: t.RunStep[] = [];\n stepKeyIds: Map<string, string[]> = new Map<string, string[]>();\n contentIndexMap: Map<string, number> = new Map();\n toolCallStepIds: Map<string, string> = new Map();\n currentUsage: Partial<UsageMetadata> | undefined;\n indexTokenCountMap: Record<string, number> = {};\n maxContextTokens: number | undefined;\n pruneMessages?: ReturnType<typeof createPruneMessages>;\n /** The amount of time that should pass before another consecutive API call */\n streamBuffer: number | undefined;\n tokenCounter?: t.TokenCounter;\n signal?: AbortSignal;\n}\n\nexport class StandardGraph extends Graph<\n t.BaseGraphState,\n GraphNode\n> {\n private graphState: t.GraphStateChannels<t.BaseGraphState>;\n clientOptions: t.ClientOptions;\n boundModel: Runnable;\n /** The last recorded timestamp that a stream API call was invoked */\n lastStreamCall: number | undefined;\n handlerRegistry: HandlerRegistry | undefined;\n systemMessage: SystemMessage | undefined;\n messages: BaseMessage[] = [];\n runId: string | undefined;\n tools?: t.GenericTool[];\n toolMap?: t.ToolMap;\n startIndex: number = 0;\n provider: Providers;\n toolEnd: boolean;\n signal: AbortSignal | undefined;\n\n constructor({\n runId,\n tools,\n signal,\n toolMap,\n provider,\n streamBuffer,\n instructions,\n reasoningKey,\n clientOptions,\n toolEnd = false,\n additional_instructions = '',\n } : t.StandardGraphInput) {\n super();\n this.runId = runId;\n this.tools = tools;\n this.signal = signal;\n this.toolEnd = toolEnd;\n this.toolMap = toolMap;\n this.provider = provider;\n this.streamBuffer = streamBuffer;\n this.clientOptions = clientOptions;\n this.graphState = this.createGraphState();\n this.boundModel = this.initializeModel();\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n\n let finalInstructions: string | BaseMessageFields = instructions ?? '';\n if (additional_instructions) {\n finalInstructions = finalInstructions ? `${finalInstructions}\\n\\n${additional_instructions}` : additional_instructions;\n }\n\n if (finalInstructions && provider === Providers.ANTHROPIC && (clientOptions as t.AnthropicClientOptions)?.clientOptions?.defaultHeaders?.['anthropic-beta']?.includes('prompt-caching')) {\n finalInstructions = {\n content: [\n {\n type: \"text\",\n text: instructions,\n cache_control: { type: \"ephemeral\" },\n },\n ],\n };\n }\n\n if (finalInstructions) {\n this.systemMessage = new SystemMessage(finalInstructions);\n }\n }\n\n /* Init */\n\n resetValues(keepContent?: boolean): void {\n this.messages = [];\n this.config = resetIfNotEmpty(this.config, undefined);\n if (keepContent !== true) {\n this.contentData = resetIfNotEmpty(this.contentData, []);\n this.contentIndexMap = resetIfNotEmpty(this.contentIndexMap, new Map());\n }\n this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n this.toolCallStepIds = resetIfNotEmpty(this.toolCallStepIds, new Map());\n this.messageIdsByStepKey = resetIfNotEmpty(this.messageIdsByStepKey, new Map());\n this.messageStepHasToolCalls = resetIfNotEmpty(this.prelimMessageIdsByStepKey, new Map());\n this.prelimMessageIdsByStepKey = resetIfNotEmpty(this.prelimMessageIdsByStepKey, new Map());\n this.currentTokenType = resetIfNotEmpty(this.currentTokenType, ContentTypes.TEXT);\n this.lastToken = resetIfNotEmpty(this.lastToken, undefined);\n this.tokenTypeSwitch = resetIfNotEmpty(this.tokenTypeSwitch, undefined);\n this.indexTokenCountMap = resetIfNotEmpty(this.indexTokenCountMap, {});\n this.currentUsage = resetIfNotEmpty(this.currentUsage, undefined);\n this.tokenCounter = resetIfNotEmpty(this.tokenCounter, undefined);\n this.maxContextTokens = resetIfNotEmpty(this.maxContextTokens, undefined);\n }\n\n /* Run Step Processing */\n\n getRunStep(stepId: string): t.RunStep | undefined {\n const index = this.contentIndexMap.get(stepId);\n if (index !== undefined) {\n return this.contentData[index];\n }\n return undefined;\n }\n\n getStepKey(metadata: Record<string, unknown> | undefined): string {\n if (!metadata) return '';\n\n const keyList = this.getKeyList(metadata);\n if (this.checkKeyList(keyList)) {\n throw new Error('Missing metadata');\n }\n\n return joinKeys(keyList);\n }\n\n getStepIdByKey(stepKey: string, index?: number): string {\n const stepIds = this.stepKeyIds.get(stepKey);\n if (!stepIds) {\n throw new Error(`No step IDs found for stepKey ${stepKey}`);\n }\n\n if (index === undefined) {\n return stepIds[stepIds.length - 1];\n }\n\n return stepIds[index];\n }\n\n generateStepId(stepKey: string): [string, number] {\n const stepIds = this.stepKeyIds.get(stepKey);\n let newStepId: string | undefined;\n let stepIndex = 0;\n if (stepIds) {\n stepIndex = stepIds.length;\n newStepId = `step_${nanoid()}`;\n stepIds.push(newStepId);\n this.stepKeyIds.set(stepKey, stepIds);\n } else {\n newStepId = `step_${nanoid()}`;\n this.stepKeyIds.set(stepKey, [newStepId]);\n }\n\n return [newStepId, stepIndex];\n }\n\n getKeyList(metadata: Record<string, unknown> | undefined): (string | number | undefined)[] {\n if (!metadata) return [];\n\n const keyList = [\n metadata.run_id as string,\n metadata.thread_id as string,\n metadata.langgraph_node as string,\n metadata.langgraph_step as number,\n metadata.checkpoint_ns as string,\n ];\n if (this.currentTokenType === ContentTypes.THINK) {\n keyList.push('reasoning');\n }\n\n return keyList;\n }\n\n checkKeyList(keyList: (string | number | undefined)[]): boolean {\n return keyList.some((key) => key === undefined);\n }\n\n /* Misc.*/\n\n getRunMessages(): BaseMessage[] | undefined {\n return this.messages.slice(this.startIndex);\n }\n\n getContentParts(): t.MessageContentComplex[] | undefined {\n return convertMessagesToContent(this.messages.slice(this.startIndex));\n }\n\n /* Graph */\n\n createGraphState(): t.GraphStateChannels<t.BaseGraphState> {\n return {\n messages: {\n value: (x: BaseMessage[], y: BaseMessage[]): BaseMessage[] => {\n if (!x.length) {\n if (this.systemMessage) {\n x.push(this.systemMessage);\n }\n\n this.startIndex = x.length + y.length;\n }\n const current = x.concat(y);\n this.messages = current;\n return current;\n },\n default: () => [],\n },\n };\n }\n\n initializeTools(): CustomToolNode<t.BaseGraphState> | ToolNode<t.BaseGraphState> {\n // return new ToolNode<t.BaseGraphState>(this.tools);\n return new CustomToolNode<t.BaseGraphState>({\n tools: this.tools || [],\n toolMap: this.toolMap,\n toolCallStepIds: this.toolCallStepIds,\n errorHandler: this.handleToolCallError.bind(this),\n });\n }\n\n initializeModel(): Runnable {\n const ChatModelClass = getChatModelClass(this.provider);\n const model = new ChatModelClass(this.clientOptions);\n\n if (isOpenAILike(this.provider) && (model instanceof ChatOpenAI || model instanceof AzureChatOpenAI)) {\n model.temperature = (this.clientOptions as t.OpenAIClientOptions).temperature as number;\n model.topP = (this.clientOptions as t.OpenAIClientOptions).topP as number;\n model.frequencyPenalty = (this.clientOptions as t.OpenAIClientOptions).frequencyPenalty as number;\n model.presencePenalty = (this.clientOptions as t.OpenAIClientOptions).presencePenalty as number;\n model.n = (this.clientOptions as t.OpenAIClientOptions).n as number;\n } else if (this.provider === Providers.VERTEXAI && model instanceof ChatVertexAI) {\n model.temperature = (this.clientOptions as t.VertexAIClientOptions).temperature as number;\n model.topP = (this.clientOptions as t.VertexAIClientOptions).topP as number;\n model.topK = (this.clientOptions as t.VertexAIClientOptions).topK as number;\n model.topLogprobs = (this.clientOptions as t.VertexAIClientOptions).topLogprobs as number;\n model.frequencyPenalty = (this.clientOptions as t.VertexAIClientOptions).frequencyPenalty as number;\n model.presencePenalty = (this.clientOptions as t.VertexAIClientOptions).presencePenalty as number;\n model.maxOutputTokens = (this.clientOptions as t.VertexAIClientOptions).maxOutputTokens as number;\n }\n\n if (!this.tools || this.tools.length === 0) {\n return model as unknown as Runnable;\n }\n\n return (model as t.ModelWithTools).bindTools(this.tools);\n }\n overrideTestModel(responses: string[], sleep?: number, toolCalls?: ToolCall[]): void {\n this.boundModel = createFakeStreamingLLM({\n responses,\n sleep,\n toolCalls,\n });\n }\n\n getNewModel({\n clientOptions = {},\n omitOriginalOptions,\n } : {\n clientOptions?: t.ClientOptions;\n omitOriginalOptions?: string[]\n }): t.ChatModelInstance {\n const ChatModelClass = getChatModelClass(this.provider);\n const _options = omitOriginalOptions ? Object.fromEntries(\n Object.entries(this.clientOptions).filter(([key]) => !omitOriginalOptions.includes(key)),\n ) : this.clientOptions;\n const options = Object.assign(_options, clientOptions);\n return new ChatModelClass(options);\n }\n\n storeUsageMetadata(finalMessage?: BaseMessage): void {\n if (finalMessage && 'usage_metadata' in finalMessage && finalMessage.usage_metadata) {\n this.currentUsage = finalMessage.usage_metadata as Partial<UsageMetadata>;\n }\n }\n\n createCallModel() {\n return async (state: t.BaseGraphState, config?: RunnableConfig): Promise<Partial<t.BaseGraphState>> => {\n const { provider = '' } = (config?.configurable as t.GraphConfig | undefined) ?? {} ;\n if (!config || !provider) {\n throw new Error(`No ${config ? 'provider' : 'config'} provided`);\n }\n if (!config.signal) {\n config.signal = this.signal;\n }\n this.config = config;\n const { messages } = state;\n\n let messagesToUse = messages;\n if (!this.pruneMessages && this.tokenCounter && this.maxContextTokens && this.indexTokenCountMap[0] != null) {\n const isAnthropicWithThinking = (\n (this.provider === Providers.ANTHROPIC\n || (this.provider === Providers.BEDROCK && (this.clientOptions as t.BedrockClientOptions)?.model?.includes('anthropic')))\n && (this.clientOptions as t.AnthropicClientOptions)?.thinking != null);\n \n this.pruneMessages = createPruneMessages({\n indexTokenCountMap: this.indexTokenCountMap,\n maxTokens: this.maxContextTokens,\n tokenCounter: this.tokenCounter,\n startIndex: this.startIndex,\n thinkingEnabled: isAnthropicWithThinking,\n });\n }\n if (this.pruneMessages) {\n const { context, indexTokenCountMap } = this.pruneMessages({\n messages,\n usageMetadata: this.currentUsage,\n // startOnMessageType: 'human',\n });\n this.indexTokenCountMap = indexTokenCountMap;\n messagesToUse = context;\n }\n\n const finalMessages = messagesToUse;\n const lastMessageX = finalMessages.length >= 2 ? finalMessages[finalMessages.length - 2] : null;\n const lastMessageY = finalMessages.length >= 1 ? finalMessages[finalMessages.length - 1] : null;\n\n if (\n provider === Providers.BEDROCK\n && lastMessageX instanceof AIMessageChunk\n && lastMessageY instanceof ToolMessage\n && typeof lastMessageX.content === 'string'\n ) {\n finalMessages[finalMessages.length - 2].content = '';\n }\n\n const isLatestToolMessage = lastMessageY instanceof ToolMessage;\n\n if (isLatestToolMessage && provider === Providers.ANTHROPIC) {\n formatAnthropicArtifactContent(finalMessages);\n } else if (\n isLatestToolMessage &&\n (isOpenAILike(provider) || isGoogleLike(provider))\n ) {\n formatArtifactPayload(finalMessages);\n }\n\n if (this.lastStreamCall != null && this.streamBuffer != null) {\n const timeSinceLastCall = Date.now() - this.lastStreamCall;\n if (timeSinceLastCall < this.streamBuffer) {\n const timeToWait = Math.ceil((this.streamBuffer - timeSinceLastCall) / 1000) * 1000;\n await sleep(timeToWait);\n }\n }\n\n this.lastStreamCall = Date.now();\n\n let result: Partial<t.BaseGraphState>;\n if ((this.tools?.length ?? 0) > 0 && manualToolStreamProviders.has(provider)) {\n const stream = await this.boundModel.stream(finalMessages, config);\n let finalChunk: AIMessageChunk | undefined;\n for await (const chunk of stream) {\n dispatchCustomEvent(GraphEvents.CHAT_MODEL_STREAM, { chunk }, config);\n if (!finalChunk) {\n finalChunk = chunk;\n } else {\n finalChunk = concat(finalChunk, chunk);\n }\n }\n\n finalChunk = modifyDeltaProperties(this.provider, finalChunk);\n result = { messages: [finalChunk as AIMessageChunk] };\n } else {\n const finalMessage = (await this.boundModel.invoke(finalMessages, config)) as AIMessageChunk;\n if ((finalMessage.tool_calls?.length ?? 0) > 0) {\n finalMessage.tool_calls = finalMessage.tool_calls?.filter((tool_call) => {\n if (!tool_call.name) {\n return false;\n }\n return true;\n });\n }\n result = { messages: [finalMessage] };\n }\n \n this.storeUsageMetadata(result?.messages?.[0]);\n return result;\n };\n }\n\n createWorkflow(): t.CompiledWorkflow<t.BaseGraphState> {\n const routeMessage = (state: t.BaseGraphState, config?: RunnableConfig): string => {\n this.config = config;\n // const lastMessage = state.messages[state.messages.length - 1] as AIMessage;\n // if (!lastMessage?.tool_calls?.length) {\n // return END;\n // }\n // return TOOLS;\n return toolsCondition(state);\n };\n\n const workflow = new StateGraph<t.BaseGraphState>({\n channels: this.graphState,\n })\n .addNode(AGENT, this.createCallModel())\n .addNode(TOOLS, this.initializeTools())\n .addEdge(START, AGENT)\n .addConditionalEdges(AGENT, routeMessage)\n .addEdge(TOOLS, this.toolEnd ? END : AGENT);\n\n return workflow.compile();\n }\n\n /* Dispatchers */\n\n /**\n * Dispatches a run step to the client, returns the step ID\n */\n dispatchRunStep(stepKey: string, stepDetails: t.StepDetails): string {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n const [stepId, stepIndex] = this.generateStepId(stepKey);\n if (stepDetails.type === StepTypes.TOOL_CALLS && stepDetails.tool_calls) {\n for (const tool_call of stepDetails.tool_calls) {\n const toolCallId = tool_call.id ?? '';\n if (!toolCallId || this.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n this.toolCallStepIds.set(toolCallId, stepId);\n }\n }\n\n const runStep: t.RunStep = {\n stepIndex,\n id: stepId,\n type: stepDetails.type,\n index: this.contentData.length,\n stepDetails,\n usage: null,\n };\n\n const runId = this.runId ?? '';\n if (runId) {\n runStep.runId = runId;\n }\n\n this.contentData.push(runStep);\n this.contentIndexMap.set(stepId, runStep.index);\n dispatchCustomEvent(GraphEvents.ON_RUN_STEP, runStep, this.config);\n return stepId;\n }\n\n handleToolCallCompleted(data: t.ToolEndData, metadata?: Record<string, unknown>): void {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n if (!data.output) {\n return;\n }\n\n const { input, output } = data;\n const { tool_call_id } = output;\n const stepId = this.toolCallStepIds.get(tool_call_id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${tool_call_id}`);\n }\n\n const runStep = this.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n const args = typeof input === 'string' ? input : input.input;\n const tool_call = {\n args: typeof args === 'string' ? args : JSON.stringify(args),\n name: output.name ?? '',\n id: output.tool_call_id,\n output: typeof output.content === 'string'\n ? output.content\n : JSON.stringify(output.content),\n progress: 1,\n };\n\n this.handlerRegistry?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n { result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call\n } as t.ToolCompleteEvent,\n },\n metadata,\n this,\n );\n }\n handleToolCallError(data: t.ToolErrorData, metadata?: Record<string, unknown>): void {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n if (!data.id) {\n console.warn('No Tool ID provided for Tool Error');\n return;\n }\n\n const stepId = this.toolCallStepIds.get(data.id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${data.id}`);\n }\n\n const { name, input: args, error } = data;\n\n const runStep = this.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n const tool_call: t.ProcessedToolCall = {\n id: data.id,\n name: name ?? '',\n args: typeof args === 'string' ? args : JSON.stringify(args),\n output: `Error processing tool${error?.message ? `: ${error.message}` : ''}`,\n progress: 1,\n };\n\n this.handlerRegistry?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n { result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call\n } as t.ToolCompleteEvent,\n },\n metadata,\n this,\n );\n }\n\n dispatchRunStepDelta(id: string, delta: t.ToolCallDelta): void {\n if (!this.config) {\n throw new Error('No config provided');\n } else if (!id) {\n throw new Error('No step ID found');\n }\n const runStepDelta: t.RunStepDeltaEvent = {\n id,\n delta,\n };\n dispatchCustomEvent(GraphEvents.ON_RUN_STEP_DELTA, runStepDelta, this.config);\n }\n\n dispatchMessageDelta(id: string, delta: t.MessageDelta): void {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const messageDelta: t.MessageDeltaEvent = {\n id,\n delta,\n };\n dispatchCustomEvent(GraphEvents.ON_MESSAGE_DELTA, messageDelta, this.config);\n }\n\n dispatchReasoningDelta = (stepId: string, delta: t.ReasoningDelta): void => {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n dispatchCustomEvent(GraphEvents.ON_REASONING_DELTA, reasoningDelta, this.config);\n };\n}\n"],"names":["CustomToolNode"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AA2BA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,aAAa;MAchB,KAAK,CAAA;AAyBzB,IAAA,SAAS;AACT,IAAA,eAAe;IACf,YAAY,GAAsC,mBAAmB;AACrE,IAAA,gBAAgB,GAA2C,YAAY,CAAC,IAAI;AAC5E,IAAA,uBAAuB,GAAyB,IAAI,GAAG,EAAE;AACzD,IAAA,mBAAmB,GAAwB,IAAI,GAAG,EAAE;AACpD,IAAA,yBAAyB,GAAwB,IAAI,GAAG,EAAE;AAC1D,IAAA,MAAM;IACN,WAAW,GAAgB,EAAE;AAC7B,IAAA,UAAU,GAA0B,IAAI,GAAG,EAAoB;AAC/D,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;AAChD,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;AAChD,IAAA,YAAY;IACZ,kBAAkB,GAA2B,EAAE;AAC/C,IAAA,gBAAgB;AAChB,IAAA,aAAa;;AAEb,IAAA,YAAY;AACZ,IAAA,YAAY;AACZ,IAAA,MAAM;AACP;AAEK,MAAO,aAAc,SAAQ,KAGlC,CAAA;AACS,IAAA,UAAU;AAClB,IAAA,aAAa;AACb,IAAA,UAAU;;AAEV,IAAA,cAAc;AACd,IAAA,eAAe;AACf,IAAA,aAAa;IACb,QAAQ,GAAkB,EAAE;AAC5B,IAAA,KAAK;AACL,IAAA,KAAK;AACL,IAAA,OAAO;IACP,UAAU,GAAW,CAAC;AACtB,IAAA,QAAQ;AACR,IAAA,OAAO;AACP,IAAA,MAAM;IAEN,WAAY,CAAA,EACV,KAAK,EACL,KAAK,E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KAAK,CAAC,oBAAoB,CAAC;;AAEvC,QAAA,MAAM,YAAY,GAAwB;YACxC,EAAE;YACF,KAAK;SACN;QACD,mBAAmB,CAAC,WAAW,CAAC,gBAAgB,EAAE,YAAY,EAAE,IAAI,CAAC,MAAM,CAAC;;AAG9E,IAAA,sBAAsB,GAAG,CAAC,MAAc,EAAE,KAAuB,KAAU;AACzE,QAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC;;AAEvC,QAAA,MAAM,cAAc,GAA0B;AAC5C,YAAA,EAAE,EAAE,MAAM;YACV,KAAK;SACN;QACD,mBAAmB,CAAC,WAAW,CAAC,kBAAkB,EAAE,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC;AAClF,KAAC;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"Graph.mjs","sources":["../../../src/graphs/Graph.ts"],"sourcesContent":["// src/graphs/Graph.ts\nimport { nanoid } from 'nanoid';\nimport { concat } from '@langchain/core/utils/stream';\nimport { ToolNode } from '@langchain/langgraph/prebuilt';\nimport { ChatVertexAI } from '@langchain/google-vertexai';\nimport { START, END, StateGraph } from '@langchain/langgraph';\nimport { ChatOpenAI, AzureChatOpenAI } from '@langchain/openai';\nimport { Runnable, RunnableConfig } from '@langchain/core/runnables';\nimport { dispatchCustomEvent } from '@langchain/core/callbacks/dispatch';\nimport { AIMessageChunk, ToolMessage, SystemMessage } from '@langchain/core/messages';\nimport type { BaseMessage, BaseMessageFields, UsageMetadata } from '@langchain/core/messages';\nimport type * as t from '@/types';\nimport { Providers, GraphEvents, GraphNodeKeys, StepTypes, Callback, ContentTypes } from '@/common';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport { getChatModelClass, manualToolStreamProviders } from '@/llm/providers';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport {\n createPruneMessages,\n modifyDeltaProperties,\n formatArtifactPayload,\n convertMessagesToContent,\n formatAnthropicArtifactContent,\n} from '@/messages';\nimport { resetIfNotEmpty, isOpenAILike, isGoogleLike, joinKeys, sleep } from '@/utils';\nimport { createFakeStreamingLLM } from '@/llm/fake';\nimport { HandlerRegistry } from '@/events';\n\nconst { AGENT, TOOLS } = GraphNodeKeys;\nexport type GraphNode = GraphNodeKeys | typeof START;\nexport type ClientCallback<T extends unknown[]> = (graph: StandardGraph, ...args: T) => void;\nexport type ClientCallbacks = {\n [Callback.TOOL_ERROR]?: ClientCallback<[Error, string]>;\n [Callback.TOOL_START]?: ClientCallback<unknown[]>;\n [Callback.TOOL_END]?: ClientCallback<unknown[]>;\n}\nexport type SystemCallbacks = {\n [K in keyof ClientCallbacks]: ClientCallbacks[K] extends ClientCallback<infer Args>\n ? (...args: Args) => void\n : never;\n};\n\nexport abstract class Graph<\n T extends t.BaseGraphState = t.BaseGraphState,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n TNodeName extends string = string,\n> {\n abstract resetValues(): void;\n abstract createGraphState(): t.GraphStateChannels<T>;\n abstract initializeTools(): CustomToolNode<T> | ToolNode<T>;\n abstract initializeModel(): Runnable;\n abstract getRunMessages(): BaseMessage[] | undefined;\n abstract getContentParts(): t.MessageContentComplex[] | undefined;\n abstract generateStepId(stepKey: string): [string, number];\n abstract getKeyList(metadata: Record<string, unknown> | undefined): (string | number | undefined)[];\n abstract getStepKey(metadata: Record<string, unknown> | undefined): string;\n abstract checkKeyList(keyList: (string | number | undefined)[]): boolean;\n abstract getStepIdByKey(stepKey: string, index?: number): string\n abstract getRunStep(stepId: string): t.RunStep | undefined;\n abstract dispatchRunStep(stepKey: string, stepDetails: t.StepDetails): string;\n abstract dispatchRunStepDelta(id: string, delta: t.ToolCallDelta): void;\n abstract dispatchMessageDelta(id: string, delta: t.MessageDelta): void;\n abstract dispatchReasoningDelta(stepId: string, delta: t.ReasoningDelta): void;\n abstract handleToolCallCompleted(data: t.ToolEndData, metadata?: Record<string, unknown>): void;\n\n abstract createCallModel(): (state: T, config?: RunnableConfig) => Promise<Partial<T>>;\n abstract createWorkflow(): t.CompiledWorkflow<T>;\n lastToken?: string;\n tokenTypeSwitch?: 'reasoning' | 'content';\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n currentTokenType: ContentTypes.TEXT | ContentTypes.THINK = ContentTypes.TEXT;\n messageStepHasToolCalls: Map<string, boolean> = new Map();\n messageIdsByStepKey: Map<string, string> = new Map();\n prelimMessageIdsByStepKey: Map<string, string> = new Map();\n config: RunnableConfig | undefined;\n contentData: t.RunStep[] = [];\n stepKeyIds: Map<string, string[]> = new Map<string, string[]>();\n contentIndexMap: Map<string, number> = new Map();\n toolCallStepIds: Map<string, string> = new Map();\n currentUsage: Partial<UsageMetadata> | undefined;\n indexTokenCountMap: Record<string, number> = {};\n maxContextTokens: number | undefined;\n pruneMessages?: ReturnType<typeof createPruneMessages>;\n /** The amount of time that should pass before another consecutive API call */\n streamBuffer: number | undefined;\n tokenCounter?: t.TokenCounter;\n signal?: AbortSignal;\n}\n\nexport class StandardGraph extends Graph<\n t.BaseGraphState,\n GraphNode\n> {\n private graphState: t.GraphStateChannels<t.BaseGraphState>;\n clientOptions: t.ClientOptions;\n boundModel: Runnable;\n /** The last recorded timestamp that a stream API call was invoked */\n lastStreamCall: number | undefined;\n handlerRegistry: HandlerRegistry | undefined;\n systemMessage: SystemMessage | undefined;\n messages: BaseMessage[] = [];\n runId: string | undefined;\n tools?: t.GenericTool[];\n toolMap?: t.ToolMap;\n startIndex: number = 0;\n provider: Providers;\n toolEnd: boolean;\n signal: AbortSignal | undefined;\n\n constructor({\n runId,\n tools,\n signal,\n toolMap,\n provider,\n streamBuffer,\n instructions,\n reasoningKey,\n clientOptions,\n toolEnd = false,\n additional_instructions = '',\n } : t.StandardGraphInput) {\n super();\n this.runId = runId;\n this.tools = tools;\n this.signal = signal;\n this.toolEnd = toolEnd;\n this.toolMap = toolMap;\n this.provider = provider;\n this.streamBuffer = streamBuffer;\n this.clientOptions = clientOptions;\n this.graphState = this.createGraphState();\n this.boundModel = this.initializeModel();\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n\n let finalInstructions: string | BaseMessageFields = instructions ?? '';\n if (additional_instructions) {\n finalInstructions = finalInstructions ? `${finalInstructions}\\n\\n${additional_instructions}` : additional_instructions;\n }\n\n if (finalInstructions && provider === Providers.ANTHROPIC && (clientOptions as t.AnthropicClientOptions).clientOptions?.defaultHeaders?.['anthropic-beta']?.includes('prompt-caching')) {\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructions,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n\n if (finalInstructions) {\n this.systemMessage = new SystemMessage(finalInstructions);\n }\n }\n\n /* Init */\n\n resetValues(keepContent?: boolean): void {\n this.messages = [];\n this.config = resetIfNotEmpty(this.config, undefined);\n if (keepContent !== true) {\n this.contentData = resetIfNotEmpty(this.contentData, []);\n this.contentIndexMap = resetIfNotEmpty(this.contentIndexMap, new Map());\n }\n this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n this.toolCallStepIds = resetIfNotEmpty(this.toolCallStepIds, new Map());\n this.messageIdsByStepKey = resetIfNotEmpty(this.messageIdsByStepKey, new Map());\n this.messageStepHasToolCalls = resetIfNotEmpty(this.prelimMessageIdsByStepKey, new Map());\n this.prelimMessageIdsByStepKey = resetIfNotEmpty(this.prelimMessageIdsByStepKey, new Map());\n this.currentTokenType = resetIfNotEmpty(this.currentTokenType, ContentTypes.TEXT);\n this.lastToken = resetIfNotEmpty(this.lastToken, undefined);\n this.tokenTypeSwitch = resetIfNotEmpty(this.tokenTypeSwitch, undefined);\n this.indexTokenCountMap = resetIfNotEmpty(this.indexTokenCountMap, {});\n this.currentUsage = resetIfNotEmpty(this.currentUsage, undefined);\n this.tokenCounter = resetIfNotEmpty(this.tokenCounter, undefined);\n this.maxContextTokens = resetIfNotEmpty(this.maxContextTokens, undefined);\n }\n\n /* Run Step Processing */\n\n getRunStep(stepId: string): t.RunStep | undefined {\n const index = this.contentIndexMap.get(stepId);\n if (index !== undefined) {\n return this.contentData[index];\n }\n return undefined;\n }\n\n getStepKey(metadata: Record<string, unknown> | undefined): string {\n if (!metadata) return '';\n\n const keyList = this.getKeyList(metadata);\n if (this.checkKeyList(keyList)) {\n throw new Error('Missing metadata');\n }\n\n return joinKeys(keyList);\n }\n\n getStepIdByKey(stepKey: string, index?: number): string {\n const stepIds = this.stepKeyIds.get(stepKey);\n if (!stepIds) {\n throw new Error(`No step IDs found for stepKey ${stepKey}`);\n }\n\n if (index === undefined) {\n return stepIds[stepIds.length - 1];\n }\n\n return stepIds[index];\n }\n\n generateStepId(stepKey: string): [string, number] {\n const stepIds = this.stepKeyIds.get(stepKey);\n let newStepId: string | undefined;\n let stepIndex = 0;\n if (stepIds) {\n stepIndex = stepIds.length;\n newStepId = `step_${nanoid()}`;\n stepIds.push(newStepId);\n this.stepKeyIds.set(stepKey, stepIds);\n } else {\n newStepId = `step_${nanoid()}`;\n this.stepKeyIds.set(stepKey, [newStepId]);\n }\n\n return [newStepId, stepIndex];\n }\n\n getKeyList(metadata: Record<string, unknown> | undefined): (string | number | undefined)[] {\n if (!metadata) return [];\n\n const keyList = [\n metadata.run_id as string,\n metadata.thread_id as string,\n metadata.langgraph_node as string,\n metadata.langgraph_step as number,\n metadata.checkpoint_ns as string,\n ];\n if (this.currentTokenType === ContentTypes.THINK) {\n keyList.push('reasoning');\n }\n\n return keyList;\n }\n\n checkKeyList(keyList: (string | number | undefined)[]): boolean {\n return keyList.some((key) => key === undefined);\n }\n\n /* Misc.*/\n\n getRunMessages(): BaseMessage[] | undefined {\n return this.messages.slice(this.startIndex);\n }\n\n getContentParts(): t.MessageContentComplex[] | undefined {\n return convertMessagesToContent(this.messages.slice(this.startIndex));\n }\n\n /* Graph */\n\n createGraphState(): t.GraphStateChannels<t.BaseGraphState> {\n return {\n messages: {\n value: (x: BaseMessage[], y: BaseMessage[]): BaseMessage[] => {\n if (!x.length) {\n if (this.systemMessage) {\n x.push(this.systemMessage);\n }\n\n this.startIndex = x.length + y.length;\n }\n const current = x.concat(y);\n this.messages = current;\n return current;\n },\n default: () => [],\n },\n };\n }\n\n initializeTools(): CustomToolNode<t.BaseGraphState> | ToolNode<t.BaseGraphState> {\n // return new ToolNode<t.BaseGraphState>(this.tools);\n return new CustomToolNode<t.BaseGraphState>({\n tools: this.tools || [],\n toolMap: this.toolMap,\n toolCallStepIds: this.toolCallStepIds,\n errorHandler: this.handleToolCallError.bind(this),\n });\n }\n\n initializeModel(): Runnable {\n const ChatModelClass = getChatModelClass(this.provider);\n const model = new ChatModelClass(this.clientOptions);\n\n if (isOpenAILike(this.provider) && (model instanceof ChatOpenAI || model instanceof AzureChatOpenAI)) {\n model.temperature = (this.clientOptions as t.OpenAIClientOptions).temperature as number;\n model.topP = (this.clientOptions as t.OpenAIClientOptions).topP as number;\n model.frequencyPenalty = (this.clientOptions as t.OpenAIClientOptions).frequencyPenalty as number;\n model.presencePenalty = (this.clientOptions as t.OpenAIClientOptions).presencePenalty as number;\n model.n = (this.clientOptions as t.OpenAIClientOptions).n as number;\n } else if (this.provider === Providers.VERTEXAI && model instanceof ChatVertexAI) {\n model.temperature = (this.clientOptions as t.VertexAIClientOptions).temperature as number;\n model.topP = (this.clientOptions as t.VertexAIClientOptions).topP as number;\n model.topK = (this.clientOptions as t.VertexAIClientOptions).topK as number;\n model.topLogprobs = (this.clientOptions as t.VertexAIClientOptions).topLogprobs as number;\n model.frequencyPenalty = (this.clientOptions as t.VertexAIClientOptions).frequencyPenalty as number;\n model.presencePenalty = (this.clientOptions as t.VertexAIClientOptions).presencePenalty as number;\n model.maxOutputTokens = (this.clientOptions as t.VertexAIClientOptions).maxOutputTokens as number;\n }\n\n if (!this.tools || this.tools.length === 0) {\n return model as unknown as Runnable;\n }\n\n return (model as t.ModelWithTools).bindTools(this.tools);\n }\n overrideTestModel(responses: string[], sleep?: number, toolCalls?: ToolCall[]): void {\n this.boundModel = createFakeStreamingLLM({\n responses,\n sleep,\n toolCalls,\n });\n }\n\n getNewModel({\n clientOptions = {},\n omitOriginalOptions,\n } : {\n clientOptions?: t.ClientOptions;\n omitOriginalOptions?: string[]\n }): t.ChatModelInstance {\n const ChatModelClass = getChatModelClass(this.provider);\n const _options = omitOriginalOptions ? Object.fromEntries(\n Object.entries(this.clientOptions).filter(([key]) => !omitOriginalOptions.includes(key)),\n ) : this.clientOptions;\n const options = Object.assign(_options, clientOptions);\n return new ChatModelClass(options);\n }\n\n storeUsageMetadata(finalMessage?: BaseMessage): void {\n if (finalMessage && 'usage_metadata' in finalMessage && finalMessage.usage_metadata) {\n this.currentUsage = finalMessage.usage_metadata as Partial<UsageMetadata>;\n }\n }\n\n createCallModel() {\n return async (state: t.BaseGraphState, config?: RunnableConfig): Promise<Partial<t.BaseGraphState>> => {\n const { provider = '' } = (config?.configurable as t.GraphConfig | undefined) ?? {} ;\n if (!config || !provider) {\n throw new Error(`No ${config ? 'provider' : 'config'} provided`);\n }\n if (!config.signal) {\n config.signal = this.signal;\n }\n this.config = config;\n const { messages } = state;\n\n let messagesToUse = messages;\n if (!this.pruneMessages && this.tokenCounter && this.maxContextTokens && this.indexTokenCountMap[0] != null) {\n const isAnthropicWithThinking = (\n (this.provider === Providers.ANTHROPIC\n || (this.provider === Providers.BEDROCK && (this.clientOptions as t.BedrockClientOptions).model?.includes('anthropic')))\n && (this.clientOptions as t.AnthropicClientOptions).thinking != null);\n\n this.pruneMessages = createPruneMessages({\n indexTokenCountMap: this.indexTokenCountMap,\n maxTokens: this.maxContextTokens,\n tokenCounter: this.tokenCounter,\n startIndex: this.startIndex,\n thinkingEnabled: isAnthropicWithThinking,\n });\n }\n if (this.pruneMessages) {\n const { context, indexTokenCountMap } = this.pruneMessages({\n messages,\n usageMetadata: this.currentUsage,\n // startOnMessageType: 'human',\n });\n this.indexTokenCountMap = indexTokenCountMap;\n messagesToUse = context;\n }\n\n const finalMessages = messagesToUse;\n const lastMessageX = finalMessages.length >= 2 ? finalMessages[finalMessages.length - 2] : null;\n const lastMessageY = finalMessages.length >= 1 ? finalMessages[finalMessages.length - 1] : null;\n\n if (\n provider === Providers.BEDROCK\n && lastMessageX instanceof AIMessageChunk\n && lastMessageY instanceof ToolMessage\n && typeof lastMessageX.content === 'string'\n ) {\n finalMessages[finalMessages.length - 2].content = '';\n }\n\n const isLatestToolMessage = lastMessageY instanceof ToolMessage;\n\n if (isLatestToolMessage && provider === Providers.ANTHROPIC) {\n formatAnthropicArtifactContent(finalMessages);\n } else if (\n isLatestToolMessage &&\n (isOpenAILike(provider) || isGoogleLike(provider))\n ) {\n formatArtifactPayload(finalMessages);\n }\n\n if (this.lastStreamCall != null && this.streamBuffer != null) {\n const timeSinceLastCall = Date.now() - this.lastStreamCall;\n if (timeSinceLastCall < this.streamBuffer) {\n const timeToWait = Math.ceil((this.streamBuffer - timeSinceLastCall) / 1000) * 1000;\n await sleep(timeToWait);\n }\n }\n\n this.lastStreamCall = Date.now();\n\n let result: Partial<t.BaseGraphState>;\n if ((this.tools?.length ?? 0) > 0 && manualToolStreamProviders.has(provider)) {\n const stream = await this.boundModel.stream(finalMessages, config);\n let finalChunk: AIMessageChunk | undefined;\n for await (const chunk of stream) {\n dispatchCustomEvent(GraphEvents.CHAT_MODEL_STREAM, { chunk }, config);\n if (!finalChunk) {\n finalChunk = chunk;\n } else {\n finalChunk = concat(finalChunk, chunk);\n }\n }\n\n finalChunk = modifyDeltaProperties(this.provider, finalChunk);\n result = { messages: [finalChunk as AIMessageChunk] };\n } else {\n const finalMessage = (await this.boundModel.invoke(finalMessages, config)) as AIMessageChunk;\n if ((finalMessage.tool_calls?.length ?? 0) > 0) {\n finalMessage.tool_calls = finalMessage.tool_calls?.filter((tool_call) => {\n if (!tool_call.name) {\n return false;\n }\n return true;\n });\n }\n result = { messages: [finalMessage] };\n }\n\n this.storeUsageMetadata(result.messages?.[0]);\n return result;\n };\n }\n\n createWorkflow(): t.CompiledWorkflow<t.BaseGraphState> {\n const routeMessage = (state: t.BaseGraphState, config?: RunnableConfig): string => {\n this.config = config;\n // const lastMessage = state.messages[state.messages.length - 1] as AIMessage;\n // if (!lastMessage?.tool_calls?.length) {\n // return END;\n // }\n // return TOOLS;\n return toolsCondition(state);\n };\n\n const workflow = new StateGraph<t.BaseGraphState>({\n channels: this.graphState,\n })\n .addNode(AGENT, this.createCallModel())\n .addNode(TOOLS, this.initializeTools())\n .addEdge(START, AGENT)\n .addConditionalEdges(AGENT, routeMessage)\n .addEdge(TOOLS, this.toolEnd ? END : AGENT);\n\n return workflow.compile();\n }\n\n /* Dispatchers */\n\n /**\n * Dispatches a run step to the client, returns the step ID\n */\n dispatchRunStep(stepKey: string, stepDetails: t.StepDetails): string {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n const [stepId, stepIndex] = this.generateStepId(stepKey);\n if (stepDetails.type === StepTypes.TOOL_CALLS && stepDetails.tool_calls) {\n for (const tool_call of stepDetails.tool_calls) {\n const toolCallId = tool_call.id ?? '';\n if (!toolCallId || this.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n this.toolCallStepIds.set(toolCallId, stepId);\n }\n }\n\n const runStep: t.RunStep = {\n stepIndex,\n id: stepId,\n type: stepDetails.type,\n index: this.contentData.length,\n stepDetails,\n usage: null,\n };\n\n const runId = this.runId ?? '';\n if (runId) {\n runStep.runId = runId;\n }\n\n this.contentData.push(runStep);\n this.contentIndexMap.set(stepId, runStep.index);\n dispatchCustomEvent(GraphEvents.ON_RUN_STEP, runStep, this.config);\n return stepId;\n }\n\n handleToolCallCompleted(data: t.ToolEndData, metadata?: Record<string, unknown>): void {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n if (!data.output) {\n return;\n }\n\n const { input, output } = data;\n const { tool_call_id } = output;\n const stepId = this.toolCallStepIds.get(tool_call_id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${tool_call_id}`);\n }\n\n const runStep = this.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n const args = typeof input === 'string' ? input : input.input;\n const tool_call = {\n args: typeof args === 'string' ? args : JSON.stringify(args),\n name: output.name ?? '',\n id: output.tool_call_id,\n output: typeof output.content === 'string'\n ? output.content\n : JSON.stringify(output.content),\n progress: 1,\n };\n\n this.handlerRegistry?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n { result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call\n } as t.ToolCompleteEvent,\n },\n metadata,\n this,\n );\n }\n handleToolCallError(data: t.ToolErrorData, metadata?: Record<string, unknown>): void {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n if (!data.id) {\n console.warn('No Tool ID provided for Tool Error');\n return;\n }\n\n const stepId = this.toolCallStepIds.get(data.id) ?? '';\n if (!stepId) {\n throw new Error(`No stepId found for tool_call_id ${data.id}`);\n }\n\n const { name, input: args, error } = data;\n\n const runStep = this.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n const tool_call: t.ProcessedToolCall = {\n id: data.id,\n name: name ?? '',\n args: typeof args === 'string' ? args : JSON.stringify(args),\n output: `Error processing tool${error?.message ? `: ${error.message}` : ''}`,\n progress: 1,\n };\n\n this.handlerRegistry?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)?.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n { result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call\n } as t.ToolCompleteEvent,\n },\n metadata,\n this,\n );\n }\n\n dispatchRunStepDelta(id: string, delta: t.ToolCallDelta): void {\n if (!this.config) {\n throw new Error('No config provided');\n } else if (!id) {\n throw new Error('No step ID found');\n }\n const runStepDelta: t.RunStepDeltaEvent = {\n id,\n delta,\n };\n dispatchCustomEvent(GraphEvents.ON_RUN_STEP_DELTA, runStepDelta, this.config);\n }\n\n dispatchMessageDelta(id: string, delta: t.MessageDelta): void {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const messageDelta: t.MessageDeltaEvent = {\n id,\n delta,\n };\n dispatchCustomEvent(GraphEvents.ON_MESSAGE_DELTA, messageDelta, this.config);\n }\n\n dispatchReasoningDelta = (stepId: string, delta: t.ReasoningDelta): void => {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n dispatchCustomEvent(GraphEvents.ON_REASONING_DELTA, reasoningDelta, this.config);\n };\n}\n"],"names":["CustomToolNode"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AA2BA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,aAAa;MAchB,KAAK,CAAA;AAyBzB,IAAA,SAAS;AACT,IAAA,eAAe;IACf,YAAY,GAAsC,mBAAmB;AACrE,IAAA,gBAAgB,GAA2C,YAAY,CAAC,IAAI;AAC5E,IAAA,uBAAuB,GAAyB,IAAI,GAAG,EAAE;AACzD,IAAA,mBAAmB,GAAwB,IAAI,GAAG,EAAE;AACpD,IAAA,yBAAyB,GAAwB,IAAI,GAAG,EAAE;AAC1D,IAAA,MAAM;IACN,WAAW,GAAgB,EAAE;AAC7B,IAAA,UAAU,GAA0B,IAAI,GAAG,EAAoB;AAC/D,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;AAChD,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;AAChD,IAAA,YAAY;IACZ,kBAAkB,GAA2B,EAAE;AAC/C,IAAA,gBAAgB;AAChB,IAAA,aAAa;;AAEb,IAAA,YAAY;AACZ,IAAA,YAAY;AACZ,IAAA,MAAM;AACP;AAEK,MAAO,aAAc,SAAQ,KAGlC,CAAA;AACS,IAAA,UAAU;AAClB,IAAA,aAAa;AACb,IAAA,UAAU;;AAEV,IAAA,cAAc;AACd,IAAA,eAAe;AACf,IAAA,aAAa;IACb,QAAQ,GAAkB,EAAE;AAC5B,IAAA,KAAK;AACL,IAAA,KAAK;AACL,IAAA,OAAO;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AG/E,oBAAoB,CAAC,EAAU,EAAE,KAAqB,EAAA;AACpD,QAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC;;AAEvC,QAAA,MAAM,YAAY,GAAwB;YACxC,EAAE;YACF,KAAK;SACN;QACD,mBAAmB,CAAC,WAAW,CAAC,gBAAgB,EAAE,YAAY,EAAE,IAAI,CAAC,MAAM,CAAC;;AAG9E,IAAA,sBAAsB,GAAG,CAAC,MAAc,EAAE,KAAuB,KAAU;AACzE,QAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC;;AAEvC,QAAA,MAAM,cAAc,GAA0B;AAC5C,YAAA,EAAE,EAAE,MAAM;YACV,KAAK;SACN;QACD,mBAAmB,CAAC,WAAW,CAAC,kBAAkB,EAAE,cAAc,EAAE,IAAI,CAAC,MAAM,CAAC;AAClF,KAAC;AACF;;;;"}
|
|
@@ -10,14 +10,14 @@ function _toolsInParams(params) {
|
|
|
10
10
|
}
|
|
11
11
|
function _documentsInParams(params) {
|
|
12
12
|
for (const message of params.messages ?? []) {
|
|
13
|
-
if (typeof message.content ===
|
|
13
|
+
if (typeof message.content === 'string') {
|
|
14
14
|
continue;
|
|
15
15
|
}
|
|
16
16
|
for (const block of message.content ?? []) {
|
|
17
|
-
if (typeof block ===
|
|
17
|
+
if (typeof block === 'object' &&
|
|
18
18
|
block != null &&
|
|
19
|
-
block.type ===
|
|
20
|
-
typeof block.citations ===
|
|
19
|
+
block.type === 'document' &&
|
|
20
|
+
typeof block.citations === 'object' &&
|
|
21
21
|
block.citations.enabled) {
|
|
22
22
|
return true;
|
|
23
23
|
}
|
|
@@ -26,7 +26,7 @@ function _documentsInParams(params) {
|
|
|
26
26
|
return false;
|
|
27
27
|
}
|
|
28
28
|
function _thinkingInParams(params) {
|
|
29
|
-
return !!(params.thinking && params.thinking.type ===
|
|
29
|
+
return !!(params.thinking && params.thinking.type === 'enabled');
|
|
30
30
|
}
|
|
31
31
|
function extractToken(chunk) {
|
|
32
32
|
if (typeof chunk.content === 'string') {
|
|
@@ -95,8 +95,8 @@ class CustomAnthropic extends ChatAnthropicMessages {
|
|
|
95
95
|
}
|
|
96
96
|
const totalUsage = {
|
|
97
97
|
input_tokens: inputUsage?.input_tokens ?? 0,
|
|
98
|
-
output_tokens: outputUsage
|
|
99
|
-
total_tokens: (inputUsage?.input_tokens ?? 0) + (outputUsage
|
|
98
|
+
output_tokens: outputUsage.output_tokens ?? 0,
|
|
99
|
+
total_tokens: (inputUsage?.input_tokens ?? 0) + (outputUsage.output_tokens ?? 0),
|
|
100
100
|
};
|
|
101
101
|
if (inputUsage?.cache_creation_input_tokens != null || inputUsage?.cache_read_input_tokens != null) {
|
|
102
102
|
totalUsage.input_token_details = {
|