@librechat/agents 2.0.4 → 2.0.5
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 +11 -1
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/stream.cjs +42 -3
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +11 -1
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/stream.mjs +43 -4
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/types/graphs/Graph.d.ts +1 -0
- package/package.json +1 -1
- package/src/graphs/Graph.ts +12 -2
- package/src/stream.ts +43 -3
- package/src/utils/llmConfig.ts +10 -0
|
@@ -18,6 +18,7 @@ var run = require('../utils/run.cjs');
|
|
|
18
18
|
// src/graphs/Graph.ts
|
|
19
19
|
const { AGENT, TOOLS } = _enum.GraphNodeKeys;
|
|
20
20
|
class Graph {
|
|
21
|
+
messageStepHasToolCalls = new Map();
|
|
21
22
|
messageIdsByStepKey = new Map();
|
|
22
23
|
prelimMessageIdsByStepKey = new Map();
|
|
23
24
|
config;
|
|
@@ -76,6 +77,7 @@ class StandardGraph extends Graph {
|
|
|
76
77
|
this.stepKeyIds = graph.resetIfNotEmpty(this.stepKeyIds, new Map());
|
|
77
78
|
this.toolCallStepIds = graph.resetIfNotEmpty(this.toolCallStepIds, new Map());
|
|
78
79
|
this.messageIdsByStepKey = graph.resetIfNotEmpty(this.messageIdsByStepKey, new Map());
|
|
80
|
+
this.messageStepHasToolCalls = graph.resetIfNotEmpty(this.prelimMessageIdsByStepKey, new Map());
|
|
79
81
|
this.prelimMessageIdsByStepKey = graph.resetIfNotEmpty(this.prelimMessageIdsByStepKey, new Map());
|
|
80
82
|
}
|
|
81
83
|
/* Run Step Processing */
|
|
@@ -250,7 +252,15 @@ class StandardGraph extends Graph {
|
|
|
250
252
|
finalChunk = messages$1.modifyDeltaProperties(finalChunk);
|
|
251
253
|
return { messages: [finalChunk] };
|
|
252
254
|
}
|
|
253
|
-
const finalMessage = await this.boundModel.invoke(finalMessages, config);
|
|
255
|
+
const finalMessage = (await this.boundModel.invoke(finalMessages, config));
|
|
256
|
+
if ((finalMessage.tool_calls?.length ?? 0) > 0) {
|
|
257
|
+
finalMessage.tool_calls = finalMessage.tool_calls?.filter((tool_call) => {
|
|
258
|
+
if (!tool_call.name) {
|
|
259
|
+
return false;
|
|
260
|
+
}
|
|
261
|
+
return true;
|
|
262
|
+
});
|
|
263
|
+
}
|
|
254
264
|
return { messages: [finalMessage] };
|
|
255
265
|
};
|
|
256
266
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Graph.cjs","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 } from '@langchain/core/messages';\nimport type * as t from '@/types';\nimport { Providers, GraphEvents, GraphNodeKeys, StepTypes, Callback } from '@/common';\nimport { getChatModelClass, manualToolStreamProviders } from '@/llm/providers';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport {\n modifyDeltaProperties,\n formatArtifactPayload,\n convertMessagesToContent,\n formatAnthropicArtifactContent,\n} from '@/messages';\nimport { resetIfNotEmpty, isOpenAILike, isGoogleLike, joinKeys, sleep } from '@/utils';\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 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 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 /** The amount of time that should pass before another consecutive API call */\n streamBuffer: number | undefined;\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 toolMap,\n provider,\n clientOptions,\n instructions,\n signal,\n additional_instructions = '',\n streamBuffer,\n toolEnd = false,\n } : {\n runId?: string;\n signal?: AbortSignal;\n provider: Providers;\n tools?: t.GenericTool[];\n toolMap?: t.ToolMap;\n clientOptions: Record<string, unknown>;\n instructions?: string;\n additional_instructions?: string;\n streamBuffer?: number;\n toolEnd?: boolean;\n }) {\n super();\n this.runId = runId;\n this.tools = tools;\n this.toolMap = toolMap;\n this.provider = provider;\n this.signal = signal;\n this.clientOptions = clientOptions;\n this.streamBuffer = streamBuffer;\n this.graphState = this.createGraphState();\n this.boundModel = this.initializeModel();\n this.toolEnd = toolEnd;\n\n let finalInstructions = instructions ?? '';\n if (additional_instructions) {\n finalInstructions = finalInstructions ? `${finalInstructions}\\n\\n${additional_instructions}` : additional_instructions;\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.prelimMessageIdsByStepKey = resetIfNotEmpty(this.prelimMessageIdsByStepKey, new Map());\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 return [\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 }\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 });\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\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 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 const finalMessages = messages;\n const lastMessageX = finalMessages[finalMessages.length - 2];\n const lastMessageY = finalMessages[finalMessages.length - 1];\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 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(finalChunk);\n return { messages: [finalChunk as AIMessageChunk] };\n }\n\n const finalMessage = await this.boundModel.invoke(finalMessages, config);\n return { messages: [finalMessage as AIMessageChunk] };\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\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"],"names":["GraphNodeKeys","SystemMessage","resetIfNotEmpty","joinKeys","nanoid","convertMessagesToContent","CustomToolNode","getChatModelClass","isOpenAILike","ChatOpenAI","AzureChatOpenAI","Providers","ChatVertexAI","messages","AIMessageChunk","ToolMessage","formatAnthropicArtifactContent","isGoogleLike","formatArtifactPayload","sleep","manualToolStreamProviders","stream","dispatchCustomEvent","GraphEvents","concat","modifyDeltaProperties","toolsCondition","StateGraph","START","END","StepTypes"],"mappings":";;;;;;;;;;;;;;;;;AAAA;AAwBA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAGA,mBAAa,CAAC;MAcjB,KAAK,CAAA;AAwBzB,IAAA,mBAAmB,GAAwB,IAAI,GAAG,EAAE,CAAC;AACrD,IAAA,yBAAyB,GAAwB,IAAI,GAAG,EAAE,CAAC;AAC3D,IAAA,MAAM,CAA6B;IACnC,WAAW,GAAgB,EAAE,CAAC;AAC9B,IAAA,UAAU,GAA0B,IAAI,GAAG,EAAoB,CAAC;AAChE,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE,CAAC;AACjD,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE,CAAC;;AAEjD,IAAA,YAAY,CAAqB;AACjC,IAAA,MAAM,CAAe;AACtB,CAAA;AAEK,MAAO,aAAc,SAAQ,KAGlC,CAAA;AACS,IAAA,UAAU,CAAyC;AAC3D,IAAA,aAAa,CAAkB;AAC/B,IAAA,UAAU,CAAW;;AAErB,IAAA,cAAc,CAAqB;AACnC,IAAA,eAAe,CAA8B;AAC7C,IAAA,aAAa,CAA4B;IACzC,QAAQ,GAAkB,EAAE,CAAC;AAC7B,IAAA,KAAK,CAAqB;AAC1B,IAAA,KAAK,CAAmB;AACxB,IAAA,OAAO,CAAa;IACpB,UAAU,GAAW,CAAC,CAAC;AACvB,IAAA,QAAQ,CAAY;AACpB,IAAA,OAAO,CAAU;AACjB,IAAA,MAAM,CAA0B;IAEhC,WAAY,CAAA,EACV,KAAK,EACL,KAAK,EACL,OAAO,EACP,QAAQ,EACR,aAAa,EACb,YAAY,EACZ,MAAM,EACN,uBAAuB,GAAG,EAAE,EAC5B,YAAY,EACZ,OAAO,GAAG,KAAK,GAYhB,EAAA;AACC,QAAA,KAAK,EAAE,CAAC;AAC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C,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;SACvC;AACD,QAAA,MAAM,YAAY,GAAwB;YACxC,EAAE;YACF,KAAK;SACN,CAAC;QACFD,4BAAmB,CAACC,iBAAW,CAAC,gBAAgB,EAAE,YAAY,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;KAC9E;AACF;;;;;"}
|
|
1
|
+
{"version":3,"file":"Graph.cjs","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 } from '@langchain/core/messages';\nimport type * as t from '@/types';\nimport { Providers, GraphEvents, GraphNodeKeys, StepTypes, Callback } from '@/common';\nimport { getChatModelClass, manualToolStreamProviders } from '@/llm/providers';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport {\n modifyDeltaProperties,\n formatArtifactPayload,\n convertMessagesToContent,\n formatAnthropicArtifactContent,\n} from '@/messages';\nimport { resetIfNotEmpty, isOpenAILike, isGoogleLike, joinKeys, sleep } from '@/utils';\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 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 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 /** The amount of time that should pass before another consecutive API call */\n streamBuffer: number | undefined;\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 toolMap,\n provider,\n clientOptions,\n instructions,\n signal,\n additional_instructions = '',\n streamBuffer,\n toolEnd = false,\n } : {\n runId?: string;\n signal?: AbortSignal;\n provider: Providers;\n tools?: t.GenericTool[];\n toolMap?: t.ToolMap;\n clientOptions: Record<string, unknown>;\n instructions?: string;\n additional_instructions?: string;\n streamBuffer?: number;\n toolEnd?: boolean;\n }) {\n super();\n this.runId = runId;\n this.tools = tools;\n this.toolMap = toolMap;\n this.provider = provider;\n this.signal = signal;\n this.clientOptions = clientOptions;\n this.streamBuffer = streamBuffer;\n this.graphState = this.createGraphState();\n this.boundModel = this.initializeModel();\n this.toolEnd = toolEnd;\n\n let finalInstructions = instructions ?? '';\n if (additional_instructions) {\n finalInstructions = finalInstructions ? `${finalInstructions}\\n\\n${additional_instructions}` : additional_instructions;\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 }\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 return [\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 }\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 });\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\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 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 const finalMessages = messages;\n const lastMessageX = finalMessages[finalMessages.length - 2];\n const lastMessageY = finalMessages[finalMessages.length - 1];\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 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(finalChunk);\n return { messages: [finalChunk as AIMessageChunk] };\n }\n\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 return { messages: [finalMessage] };\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\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"],"names":["GraphNodeKeys","SystemMessage","resetIfNotEmpty","joinKeys","nanoid","convertMessagesToContent","CustomToolNode","getChatModelClass","isOpenAILike","ChatOpenAI","AzureChatOpenAI","Providers","ChatVertexAI","messages","AIMessageChunk","ToolMessage","formatAnthropicArtifactContent","isGoogleLike","formatArtifactPayload","sleep","manualToolStreamProviders","stream","dispatchCustomEvent","GraphEvents","concat","modifyDeltaProperties","toolsCondition","StateGraph","START","END","StepTypes"],"mappings":";;;;;;;;;;;;;;;;;AAAA;AAwBA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAGA,mBAAa,CAAC;MAcjB,KAAK,CAAA;AAwBzB,IAAA,uBAAuB,GAAyB,IAAI,GAAG,EAAE,CAAC;AAC1D,IAAA,mBAAmB,GAAwB,IAAI,GAAG,EAAE,CAAC;AACrD,IAAA,yBAAyB,GAAwB,IAAI,GAAG,EAAE,CAAC;AAC3D,IAAA,MAAM,CAA6B;IACnC,WAAW,GAAgB,EAAE,CAAC;AAC9B,IAAA,UAAU,GAA0B,IAAI,GAAG,EAAoB,CAAC;AAChE,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE,CAAC;AACjD,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE,CAAC;;AAEjD,IAAA,YAAY,CAAqB;AACjC,IAAA,MAAM,CAAe;AACtB,CAAA;AAEK,MAAO,aAAc,SAAQ,KAGlC,CAAA;AACS,IAAA,UAAU,CAAyC;AAC3D,IAAA,aAAa,CAAkB;AAC/B,IAAA,UAAU,CAAW;;AAErB,IAAA,cAAc,CAAqB;AACnC,IAAA,eAAe,CAA8B;AAC7C,IAAA,aAAa,CAA4B;IACzC,QAAQ,GAAkB,EAAE,CAAC;AAC7B,IAAA,KAAK,CAAqB;AAC1B,IAAA,KAAK,CAAmB;AACxB,IAAA,OAAO,CAAa;IACpB,UAAU,GAAW,CAAC,CAAC;AACvB,IAAA,QAAQ,CAAY;AACpB,IAAA,OAAO,CAAU;AACjB,IAAA,MAAM,CAA0B;IAEhC,WAAY,CAAA,EACV,KAAK,EACL,KAAK,EACL,OAAO,EACP,QAAQ,EACR,aAAa,EACb,YAAY,EACZ,MAAM,EACN,u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AAA;AACvB,SAAA,EACD,QAAQ,EACR,IAAI,CACL,CAAC;KACH;IAED,oBAAoB,CAAC,EAAU,EAAE,KAAsB,EAAA;AACrD,QAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;SACvC;aAAM,IAAI,CAAC,EAAE,EAAE;AACd,YAAA,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;SACrC;AACD,QAAA,MAAM,YAAY,GAAwB;YACxC,EAAE;YACF,KAAK;SACN,CAAC;QACFD,4BAAmB,CAACC,iBAAW,CAAC,iBAAiB,EAAE,YAAY,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;KAC/E;IAED,oBAAoB,CAAC,EAAU,EAAE,KAAqB,EAAA;AACpD,QAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;SACvC;AACD,QAAA,MAAM,YAAY,GAAwB;YACxC,EAAE;YACF,KAAK;SACN,CAAC;QACFD,4BAAmB,CAACC,iBAAW,CAAC,gBAAgB,EAAE,YAAY,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;KAC9E;AACF;;;;;"}
|
package/dist/cjs/stream.cjs
CHANGED
|
@@ -71,6 +71,7 @@ const handleToolCalls = (toolCalls, metadata, graph) => {
|
|
|
71
71
|
/* If the previous step exists and is a message creation */
|
|
72
72
|
if (prevStepId && prevRunStep && prevRunStep.type === _enum.StepTypes.MESSAGE_CREATION) {
|
|
73
73
|
dispatchToolCallIds(prevStepId);
|
|
74
|
+
graph.messageStepHasToolCalls.set(prevStepId, true);
|
|
74
75
|
/* If the previous step doesn't exist or is not a message creation */
|
|
75
76
|
}
|
|
76
77
|
else if (!prevRunStep || prevRunStep.type !== _enum.StepTypes.MESSAGE_CREATION) {
|
|
@@ -82,6 +83,7 @@ const handleToolCalls = (toolCalls, metadata, graph) => {
|
|
|
82
83
|
},
|
|
83
84
|
});
|
|
84
85
|
dispatchToolCallIds(stepId);
|
|
86
|
+
graph.messageStepHasToolCalls.set(prevStepId, true);
|
|
85
87
|
}
|
|
86
88
|
graph.dispatchRunStep(stepKey, {
|
|
87
89
|
type: _enum.StepTypes.TOOL_CALLS,
|
|
@@ -132,7 +134,44 @@ class ChatModelStreamHandler {
|
|
|
132
134
|
&& typeof chunk.tool_call_chunks[0]?.index === 'number') {
|
|
133
135
|
const prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);
|
|
134
136
|
const prevRunStep = graph.getRunStep(prevStepId);
|
|
135
|
-
const
|
|
137
|
+
const _stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);
|
|
138
|
+
/** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */
|
|
139
|
+
const tool_calls = prevStepId && prevRunStep && prevRunStep.type === _enum.StepTypes.MESSAGE_CREATION
|
|
140
|
+
? []
|
|
141
|
+
: undefined;
|
|
142
|
+
/** Edge Case: `id` and `name` fields cannot be empty strings */
|
|
143
|
+
for (const toolCallChunk of chunk.tool_call_chunks) {
|
|
144
|
+
if (toolCallChunk.name === '') {
|
|
145
|
+
toolCallChunk.name = undefined;
|
|
146
|
+
}
|
|
147
|
+
if (toolCallChunk.id === '') {
|
|
148
|
+
toolCallChunk.id = undefined;
|
|
149
|
+
}
|
|
150
|
+
else if (tool_calls != null && toolCallChunk.id != null && toolCallChunk.name != null) {
|
|
151
|
+
tool_calls.push({
|
|
152
|
+
args: {},
|
|
153
|
+
id: toolCallChunk.id,
|
|
154
|
+
name: toolCallChunk.name,
|
|
155
|
+
type: _enum.ToolCallTypes.TOOL_CALL,
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
let stepId = _stepId;
|
|
160
|
+
const alreadyDispatched = prevRunStep?.type === _enum.StepTypes.MESSAGE_CREATION && graph.messageStepHasToolCalls.has(prevStepId);
|
|
161
|
+
if (!alreadyDispatched && tool_calls?.length === chunk.tool_call_chunks.length) {
|
|
162
|
+
graph.dispatchMessageDelta(prevStepId, {
|
|
163
|
+
content: [{
|
|
164
|
+
type: 'text',
|
|
165
|
+
text: '',
|
|
166
|
+
tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),
|
|
167
|
+
}],
|
|
168
|
+
});
|
|
169
|
+
graph.messageStepHasToolCalls.set(prevStepId, true);
|
|
170
|
+
stepId = graph.dispatchRunStep(stepKey, {
|
|
171
|
+
type: _enum.StepTypes.TOOL_CALLS,
|
|
172
|
+
tool_calls,
|
|
173
|
+
});
|
|
174
|
+
}
|
|
136
175
|
graph.dispatchRunStepDelta(stepId, {
|
|
137
176
|
type: _enum.StepTypes.TOOL_CALLS,
|
|
138
177
|
tool_calls: chunk.tool_call_chunks,
|
|
@@ -315,12 +354,12 @@ function createContentAggregator() {
|
|
|
315
354
|
if (runStepDelta.delta.type === _enum.StepTypes.TOOL_CALLS &&
|
|
316
355
|
runStepDelta.delta.tool_calls) {
|
|
317
356
|
runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {
|
|
318
|
-
const toolCallId = toolCallIdMap.get(runStepDelta.id)
|
|
357
|
+
const toolCallId = toolCallIdMap.get(runStepDelta.id);
|
|
319
358
|
const contentPart = {
|
|
320
359
|
type: _enum.ContentTypes.TOOL_CALL,
|
|
321
360
|
tool_call: {
|
|
322
|
-
name: toolCallDelta.name ?? '',
|
|
323
361
|
args: toolCallDelta.args ?? '',
|
|
362
|
+
name: toolCallDelta.name,
|
|
324
363
|
id: toolCallId,
|
|
325
364
|
},
|
|
326
365
|
};
|
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 } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\nimport { StepTypes, ContentTypes, GraphEvents, ToolCallTypes } from '@/common';\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nexport const getMessageId = (stepKey: string, graph: Graph<t.BaseGraphState>, returnExistingId = false): string | undefined => {\n const messageId = graph.messageIdsByStepKey.get(stepKey);\n if (messageId != null && messageId) {\n return returnExistingId ? messageId : undefined;\n }\n\n const prelimMessageId = graph.prelimMessageIdsByStepKey.get(stepKey);\n if (prelimMessageId != null && prelimMessageId) {\n graph.prelimMessageIdsByStepKey.delete(stepKey);\n graph.messageIdsByStepKey.set(stepKey, prelimMessageId);\n return prelimMessageId;\n }\n\n const message_id = `msg_${nanoid()}`;\n graph.messageIdsByStepKey.set(stepKey, message_id);\n return message_id;\n};\n\nexport const handleToolCalls = (toolCalls?: ToolCall[], metadata?: Record<string, unknown>, graph?: Graph): void => {\n if (!graph || !metadata) {\n console.warn(`Graph or metadata not found in ${event} event`);\n return;\n }\n\n if (!toolCalls) {\n return;\n }\n\n if (toolCalls.length === 0) {\n return;\n }\n\n const tool_calls: ToolCall[] = [];\n const tool_call_ids: string[] = [];\n for (const tool_call of toolCalls) {\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\n tool_call.id = toolCallId;\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n\n tool_calls.push(tool_call);\n tool_call_ids.push(toolCallId);\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n let prevStepId = '';\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch (e) {\n // no previous step\n }\n\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\n graph.dispatchMessageDelta(lastMessageStepId, {\n content: [{\n type: 'text',\n text: '',\n tool_call_ids,\n }],\n });\n };\n /* If the previous step exists and is a message creation */\n if (prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION) {\n dispatchToolCallIds(prevStepId);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (!prevRunStep || prevRunStep.type !== StepTypes.MESSAGE_CREATION) {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n const stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n });\n dispatchToolCallIds(stepId);\n }\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n};\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData, metadata?: Record<string, unknown>, graph?: Graph): void {\n if (!graph) {\n throw new Error('Graph not found');\n }\n\n const chunk = data.chunk as AIMessageChunk | undefined;\n const content = chunk?.content;\n\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n\n if (!chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n let hasToolCalls = false;\n const hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n\n if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id)) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const isEmptyContent = typeof content === 'undefined' || !content.length || typeof content === 'string' && !content;\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n const chunkId = chunk.id ?? '';\n if (isEmptyChunk && chunkId && chunkId.startsWith('msg')) {\n if (graph.messageIdsByStepKey.has(chunkId)) {\n return;\n } else if (graph.prelimMessageIdsByStepKey.has(chunkId)) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunkId);\n return;\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (hasToolCallChunks\n && chunk.tool_call_chunks\n && chunk.tool_call_chunks.length\n && typeof chunk.tool_call_chunks[0]?.index === 'number') {\n const prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n const prevRunStep = graph.getRunStep(prevStepId);\n const stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\n graph.dispatchRunStepDelta(stepId, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: chunk.tool_call_chunks,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n // eslint-disable-next-line no-console\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (hasToolCallChunks && (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)) {\n return;\n } else if (typeof content === 'string') {\n graph.dispatchMessageDelta(stepId, {\n content: [{\n type: 'text',\n text: content,\n }],\n });\n } else if (content.every((c) => c.type?.startsWith('text'))) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n }\n }\n}\n\nexport type ContentAggregatorResult = {\n stepMap: Map<string, t.RunStep | undefined>;\n contentParts: Array<t.MessageContentComplex | undefined>;\n aggregateContent: ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | {\n result: t.ToolEndEvent;\n };\n}) => void\n};\n\nexport function createContentAggregator(): ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart: t.MessageContentComplex,\n finalUpdate = false,\n ): void => {\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (partType === ContentTypes.IMAGE_URL && 'image_url' in contentPart) {\n const currentContent = contentParts[index] as { type: 'image_url'; image_url: string };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (partType === ContentTypes.TOOL_CALL && 'tool_call' in contentPart) {\n const existingContent = contentParts[index] as Omit<t.ToolCallContent, 'tool_call'> & { tool_call?: ToolCall } | undefined;\n\n const args = finalUpdate\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args || '') + (contentPart.tool_call.args ?? '');\n\n const id = getNonEmptyValue([contentPart.tool_call.id, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([contentPart.tool_call.name, existingContent?.tool_call?.name]) ?? '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | { result: t.ToolEndEvent };\n }): void => {\n\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (runStep.stepDetails.type === StepTypes.TOOL_CALLS && runStep.stepDetails.tool_calls) {\n runStep.stepDetails.tool_calls.forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id) ?? '';\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n name: toolCallDelta.name ?? '',\n args: toolCallDelta.args ?? '',\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn('No run step or runId found for completed tool call event');\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":["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,CAAC;SACd;KACF;AACD,IAAA,OAAO,SAAS,CAAC;AACnB,CAAC;AAEM,MAAM,YAAY,GAAG,CAAC,OAAe,EAAE,KAA8B,EAAE,gBAAgB,GAAG,KAAK,KAAwB;IAC5H,MAAM,SAAS,GAAG,KAAK,CAAC,mBAAmB,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AACzD,IAAA,IAAI,SAAS,IAAI,IAAI,IAAI,SAAS,EAAE;QAClC,OAAO,gBAAgB,GAAG,SAAS,GAAG,SAAS,CAAC;KACjD;IAED,MAAM,eAAe,GAAG,KAAK,CAAC,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,YAAA,MAAM,EAAE,MAAM,EAAE,GAAG,IAA6C,CAAC;AAEjE,YAAA,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;YAE9B,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YACpC,IAAI,CAAC,OAAO,EAAE;AACZ,gBAAA,OAAO,CAAC,IAAI,CAAC,0DAA0D,CAAC,CAAC;gBACzE,OAAO;aACR;AAED,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAEF,kBAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B,CAAC;YAEF,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;SACjD;AAEH,KAAC,CAAC;AAEF,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE,CAAC;AACrD;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"stream.cjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport { nanoid } from 'nanoid';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\nimport { StepTypes, ContentTypes, GraphEvents, ToolCallTypes } from '@/common';\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nexport const getMessageId = (stepKey: string, graph: Graph<t.BaseGraphState>, returnExistingId = false): string | undefined => {\n const messageId = graph.messageIdsByStepKey.get(stepKey);\n if (messageId != null && messageId) {\n return returnExistingId ? messageId : undefined;\n }\n\n const prelimMessageId = graph.prelimMessageIdsByStepKey.get(stepKey);\n if (prelimMessageId != null && prelimMessageId) {\n graph.prelimMessageIdsByStepKey.delete(stepKey);\n graph.messageIdsByStepKey.set(stepKey, prelimMessageId);\n return prelimMessageId;\n }\n\n const message_id = `msg_${nanoid()}`;\n graph.messageIdsByStepKey.set(stepKey, message_id);\n return message_id;\n};\n\nexport const handleToolCalls = (toolCalls?: ToolCall[], metadata?: Record<string, unknown>, graph?: Graph): void => {\n if (!graph || !metadata) {\n console.warn(`Graph or metadata not found in ${event} event`);\n return;\n }\n\n if (!toolCalls) {\n return;\n }\n\n if (toolCalls.length === 0) {\n return;\n }\n\n const tool_calls: ToolCall[] = [];\n const tool_call_ids: string[] = [];\n for (const tool_call of toolCalls) {\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\n tool_call.id = toolCallId;\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n\n tool_calls.push(tool_call);\n tool_call_ids.push(toolCallId);\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n let prevStepId = '';\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch (e) {\n // no previous step\n }\n\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\n graph.dispatchMessageDelta(lastMessageStepId, {\n content: [{\n type: 'text',\n text: '',\n tool_call_ids,\n }],\n });\n };\n /* If the previous step exists and is a message creation */\n if (prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION) {\n dispatchToolCallIds(prevStepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (!prevRunStep || prevRunStep.type !== StepTypes.MESSAGE_CREATION) {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n const stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n });\n dispatchToolCallIds(stepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n }\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n};\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData, metadata?: Record<string, unknown>, graph?: Graph): void {\n if (!graph) {\n throw new Error('Graph not found');\n }\n\n const chunk = data.chunk as AIMessageChunk | undefined;\n const content = chunk?.content;\n\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n\n if (!chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n let hasToolCalls = false;\n const hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n\n if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id)) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const isEmptyContent = typeof content === 'undefined' || !content.length || typeof content === 'string' && !content;\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n const chunkId = chunk.id ?? '';\n if (isEmptyChunk && chunkId && chunkId.startsWith('msg')) {\n if (graph.messageIdsByStepKey.has(chunkId)) {\n return;\n } else if (graph.prelimMessageIdsByStepKey.has(chunkId)) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunkId);\n return;\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (hasToolCallChunks\n && chunk.tool_call_chunks\n && chunk.tool_call_chunks.length\n && typeof chunk.tool_call_chunks[0]?.index === 'number') {\n const prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n const prevRunStep = graph.getRunStep(prevStepId);\n const _stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\n /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */\n const tool_calls: ToolCall[] | undefined =\n prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION\n ? []\n : undefined;\n /** Edge Case: `id` and `name` fields cannot be empty strings */\n for (const toolCallChunk of chunk.tool_call_chunks) {\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 === chunk.tool_call_chunks.length) {\n graph.dispatchMessageDelta(prevStepId, {\n content: [{\n type: '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: chunk.tool_call_chunks,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n // eslint-disable-next-line no-console\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (hasToolCallChunks && (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)) {\n return;\n } else if (typeof content === 'string') {\n graph.dispatchMessageDelta(stepId, {\n content: [{\n type: 'text',\n text: content,\n }],\n });\n } else if (content.every((c) => c.type?.startsWith('text'))) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n }\n }\n}\n\nexport type ContentAggregatorResult = {\n stepMap: Map<string, t.RunStep | undefined>;\n contentParts: Array<t.MessageContentComplex | undefined>;\n aggregateContent: ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | {\n result: t.ToolEndEvent;\n };\n}) => void\n};\n\nexport function createContentAggregator(): ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart: t.MessageContentComplex,\n finalUpdate = false,\n ): void => {\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (partType === ContentTypes.IMAGE_URL && 'image_url' in contentPart) {\n const currentContent = contentParts[index] as { type: 'image_url'; image_url: string };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (partType === ContentTypes.TOOL_CALL && 'tool_call' in contentPart) {\n const existingContent = contentParts[index] as Omit<t.ToolCallContent, 'tool_call'> & { tool_call?: ToolCall } | undefined;\n\n const args = finalUpdate\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args || '') + (contentPart.tool_call.args ?? '');\n\n const id = getNonEmptyValue([contentPart.tool_call.id, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([contentPart.tool_call.name, existingContent?.tool_call?.name]) ?? '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | { result: t.ToolEndEvent };\n }): void => {\n\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (runStep.stepDetails.type === StepTypes.TOOL_CALLS && runStep.stepDetails.tool_calls) {\n runStep.stepDetails.tool_calls.forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n 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","ToolCallTypes","ContentTypes","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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AC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;SACjD;AAEH,KAAC,CAAC;AAEF,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE,CAAC;AACrD;;;;;;;"}
|
|
@@ -16,6 +16,7 @@ import { sleep } from '../utils/run.mjs';
|
|
|
16
16
|
// src/graphs/Graph.ts
|
|
17
17
|
const { AGENT, TOOLS } = GraphNodeKeys;
|
|
18
18
|
class Graph {
|
|
19
|
+
messageStepHasToolCalls = new Map();
|
|
19
20
|
messageIdsByStepKey = new Map();
|
|
20
21
|
prelimMessageIdsByStepKey = new Map();
|
|
21
22
|
config;
|
|
@@ -74,6 +75,7 @@ class StandardGraph extends Graph {
|
|
|
74
75
|
this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());
|
|
75
76
|
this.toolCallStepIds = resetIfNotEmpty(this.toolCallStepIds, new Map());
|
|
76
77
|
this.messageIdsByStepKey = resetIfNotEmpty(this.messageIdsByStepKey, new Map());
|
|
78
|
+
this.messageStepHasToolCalls = resetIfNotEmpty(this.prelimMessageIdsByStepKey, new Map());
|
|
77
79
|
this.prelimMessageIdsByStepKey = resetIfNotEmpty(this.prelimMessageIdsByStepKey, new Map());
|
|
78
80
|
}
|
|
79
81
|
/* Run Step Processing */
|
|
@@ -248,7 +250,15 @@ class StandardGraph extends Graph {
|
|
|
248
250
|
finalChunk = modifyDeltaProperties(finalChunk);
|
|
249
251
|
return { messages: [finalChunk] };
|
|
250
252
|
}
|
|
251
|
-
const finalMessage = await this.boundModel.invoke(finalMessages, config);
|
|
253
|
+
const finalMessage = (await this.boundModel.invoke(finalMessages, config));
|
|
254
|
+
if ((finalMessage.tool_calls?.length ?? 0) > 0) {
|
|
255
|
+
finalMessage.tool_calls = finalMessage.tool_calls?.filter((tool_call) => {
|
|
256
|
+
if (!tool_call.name) {
|
|
257
|
+
return false;
|
|
258
|
+
}
|
|
259
|
+
return true;
|
|
260
|
+
});
|
|
261
|
+
}
|
|
252
262
|
return { messages: [finalMessage] };
|
|
253
263
|
};
|
|
254
264
|
}
|
|
@@ -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 } from '@langchain/core/messages';\nimport type * as t from '@/types';\nimport { Providers, GraphEvents, GraphNodeKeys, StepTypes, Callback } from '@/common';\nimport { getChatModelClass, manualToolStreamProviders } from '@/llm/providers';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport {\n modifyDeltaProperties,\n formatArtifactPayload,\n convertMessagesToContent,\n formatAnthropicArtifactContent,\n} from '@/messages';\nimport { resetIfNotEmpty, isOpenAILike, isGoogleLike, joinKeys, sleep } from '@/utils';\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 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 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 /** The amount of time that should pass before another consecutive API call */\n streamBuffer: number | undefined;\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 toolMap,\n provider,\n clientOptions,\n instructions,\n signal,\n additional_instructions = '',\n streamBuffer,\n toolEnd = false,\n } : {\n runId?: string;\n signal?: AbortSignal;\n provider: Providers;\n tools?: t.GenericTool[];\n toolMap?: t.ToolMap;\n clientOptions: Record<string, unknown>;\n instructions?: string;\n additional_instructions?: string;\n streamBuffer?: number;\n toolEnd?: boolean;\n }) {\n super();\n this.runId = runId;\n this.tools = tools;\n this.toolMap = toolMap;\n this.provider = provider;\n this.signal = signal;\n this.clientOptions = clientOptions;\n this.streamBuffer = streamBuffer;\n this.graphState = this.createGraphState();\n this.boundModel = this.initializeModel();\n this.toolEnd = toolEnd;\n\n let finalInstructions = instructions ?? '';\n if (additional_instructions) {\n finalInstructions = finalInstructions ? `${finalInstructions}\\n\\n${additional_instructions}` : additional_instructions;\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.prelimMessageIdsByStepKey = resetIfNotEmpty(this.prelimMessageIdsByStepKey, new Map());\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 return [\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 }\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 });\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\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 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 const finalMessages = messages;\n const lastMessageX = finalMessages[finalMessages.length - 2];\n const lastMessageY = finalMessages[finalMessages.length - 1];\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 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(finalChunk);\n return { messages: [finalChunk as AIMessageChunk] };\n }\n\n const finalMessage = await this.boundModel.invoke(finalMessages, config);\n return { messages: [finalMessage as AIMessageChunk] };\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\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"],"names":["CustomToolNode"],"mappings":";;;;;;;;;;;;;;;AAAA;AAwBA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,aAAa,CAAC;MAcjB,KAAK,CAAA;AAwBzB,IAAA,mBAAmB,GAAwB,IAAI,GAAG,EAAE,CAAC;AACrD,IAAA,yBAAyB,GAAwB,IAAI,GAAG,EAAE,CAAC;AAC3D,IAAA,MAAM,CAA6B;IACnC,WAAW,GAAgB,EAAE,CAAC;AAC9B,IAAA,UAAU,GAA0B,IAAI,GAAG,EAAoB,CAAC;AAChE,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE,CAAC;AACjD,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE,CAAC;;AAEjD,IAAA,YAAY,CAAqB;AACjC,IAAA,MAAM,CAA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ACa,aAAA;AACvB,SAAA,EACD,QAAQ,EACR,IAAI,CACL,CAAC;KACH;IAED,oBAAoB,CAAC,EAAU,EAAE,KAAsB,EAAA;AACrD,QAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;SACvC;aAAM,IAAI,CAAC,EAAE,EAAE;AACd,YAAA,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;SACrC;AACD,QAAA,MAAM,YAAY,GAAwB;YACxC,EAAE;YACF,KAAK;SACN,CAAC;QACF,mBAAmB,CAAC,WAAW,CAAC,iBAAiB,EAAE,YAAY,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;KAC/E;IAED,oBAAoB,CAAC,EAAU,EAAE,KAAqB,EAAA;AACpD,QAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;SACvC;AACD,QAAA,MAAM,YAAY,GAAwB;YACxC,EAAE;YACF,KAAK;SACN,CAAC;QACF,mBAAmB,CAAC,WAAW,CAAC,gBAAgB,EAAE,YAAY,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;KAC9E;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 } from '@langchain/core/messages';\nimport type * as t from '@/types';\nimport { Providers, GraphEvents, GraphNodeKeys, StepTypes, Callback } from '@/common';\nimport { getChatModelClass, manualToolStreamProviders } from '@/llm/providers';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport {\n modifyDeltaProperties,\n formatArtifactPayload,\n convertMessagesToContent,\n formatAnthropicArtifactContent,\n} from '@/messages';\nimport { resetIfNotEmpty, isOpenAILike, isGoogleLike, joinKeys, sleep } from '@/utils';\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 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 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 /** The amount of time that should pass before another consecutive API call */\n streamBuffer: number | undefined;\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 toolMap,\n provider,\n clientOptions,\n instructions,\n signal,\n additional_instructions = '',\n streamBuffer,\n toolEnd = false,\n } : {\n runId?: string;\n signal?: AbortSignal;\n provider: Providers;\n tools?: t.GenericTool[];\n toolMap?: t.ToolMap;\n clientOptions: Record<string, unknown>;\n instructions?: string;\n additional_instructions?: string;\n streamBuffer?: number;\n toolEnd?: boolean;\n }) {\n super();\n this.runId = runId;\n this.tools = tools;\n this.toolMap = toolMap;\n this.provider = provider;\n this.signal = signal;\n this.clientOptions = clientOptions;\n this.streamBuffer = streamBuffer;\n this.graphState = this.createGraphState();\n this.boundModel = this.initializeModel();\n this.toolEnd = toolEnd;\n\n let finalInstructions = instructions ?? '';\n if (additional_instructions) {\n finalInstructions = finalInstructions ? `${finalInstructions}\\n\\n${additional_instructions}` : additional_instructions;\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 }\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 return [\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 }\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 });\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\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 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 const finalMessages = messages;\n const lastMessageX = finalMessages[finalMessages.length - 2];\n const lastMessageY = finalMessages[finalMessages.length - 1];\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 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(finalChunk);\n return { messages: [finalChunk as AIMessageChunk] };\n }\n\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 return { messages: [finalMessage] };\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\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"],"names":["CustomToolNode"],"mappings":";;;;;;;;;;;;;;;AAAA;AAwBA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,aAAa,CAAC;MAcjB,KAAK,CAAA;AAwBzB,IAAA,uBAAuB,GAAyB,IAAI,GAAG,EAAE,CAAC;AAC1D,IAAA,mBAAmB,GAAwB,IAAI,GAAG,EAAE,CAAC;AACrD,IAAA,yBAAyB,GAAwB,IAAI,GAAG,EAAE,CAAC;AAC3D,IAAA,MAAM,CAA6B;IACnC,WAAW,GAAgB,EAAE,CAAC;AAC9B,IAAA,UAAU,GAA0B,IAAI,GAAG,EAAoB,CAAC;AAChE,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE,CAAC;AACjD,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE,CAAC;;AAEjD,IAAA,YAAY,CAAqB;AACjC,IAAA,MAAM,CAAe;AACtB,CAAA;AAEK,MAAO,aAAc,SAAQ,KAGlC,CAAA;AACS,IAAA,UAAU,CAAyC;AAC3D,IAAA,aAAa,CAAkB;AAC/B,IAAA,UAAU,CAAW;;AAErB,IAAA,cAAc,CAAqB;AACnC,IAAA,eAAe,CAA8B;AAC7C,IAAA,aAAa,CAA4B;IACzC,QAAQ,GAAkB,EAAE,CAAC;AAC7B,IAAA,KAA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,CAAC,EAAE,MAAM,CACzE,WAAW,CAAC,qBAAqB,EACjC,EAAE,MAAM,EAAE;AACR,gBAAA,EAAE,EAAE,MAAM;gBACV,KAAK,EAAE,OAAO,CAAC,KAAK;AACpB,gBAAA,IAAI,EAAE,WAAW;gBACjB,SAAS;AACa,aAAA;AACvB,SAAA,EACD,QAAQ,EACR,IAAI,CACL,CAAC;KACH;IAED,oBAAoB,CAAC,EAAU,EAAE,KAAsB,EAAA;AACrD,QAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;SACvC;aAAM,IAAI,CAAC,EAAE,EAAE;AACd,YAAA,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;SACrC;AACD,QAAA,MAAM,YAAY,GAAwB;YACxC,EAAE;YACF,KAAK;SACN,CAAC;QACF,mBAAmB,CAAC,WAAW,CAAC,iBAAiB,EAAE,YAAY,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;KAC/E;IAED,oBAAoB,CAAC,EAAU,EAAE,KAAqB,EAAA;AACpD,QAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;SACvC;AACD,QAAA,MAAM,YAAY,GAAwB;YACxC,EAAE;YACF,KAAK;SACN,CAAC;QACF,mBAAmB,CAAC,WAAW,CAAC,gBAAgB,EAAE,YAAY,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;KAC9E;AACF;;;;"}
|
package/dist/esm/stream.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { nanoid } from 'nanoid';
|
|
2
|
-
import { StepTypes, GraphEvents, ContentTypes
|
|
2
|
+
import { StepTypes, ToolCallTypes, GraphEvents, ContentTypes } from './common/enum.mjs';
|
|
3
3
|
|
|
4
4
|
// src/stream.ts
|
|
5
5
|
function getNonEmptyValue(possibleValues) {
|
|
@@ -69,6 +69,7 @@ const handleToolCalls = (toolCalls, metadata, graph) => {
|
|
|
69
69
|
/* If the previous step exists and is a message creation */
|
|
70
70
|
if (prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION) {
|
|
71
71
|
dispatchToolCallIds(prevStepId);
|
|
72
|
+
graph.messageStepHasToolCalls.set(prevStepId, true);
|
|
72
73
|
/* If the previous step doesn't exist or is not a message creation */
|
|
73
74
|
}
|
|
74
75
|
else if (!prevRunStep || prevRunStep.type !== StepTypes.MESSAGE_CREATION) {
|
|
@@ -80,6 +81,7 @@ const handleToolCalls = (toolCalls, metadata, graph) => {
|
|
|
80
81
|
},
|
|
81
82
|
});
|
|
82
83
|
dispatchToolCallIds(stepId);
|
|
84
|
+
graph.messageStepHasToolCalls.set(prevStepId, true);
|
|
83
85
|
}
|
|
84
86
|
graph.dispatchRunStep(stepKey, {
|
|
85
87
|
type: StepTypes.TOOL_CALLS,
|
|
@@ -130,7 +132,44 @@ class ChatModelStreamHandler {
|
|
|
130
132
|
&& typeof chunk.tool_call_chunks[0]?.index === 'number') {
|
|
131
133
|
const prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);
|
|
132
134
|
const prevRunStep = graph.getRunStep(prevStepId);
|
|
133
|
-
const
|
|
135
|
+
const _stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);
|
|
136
|
+
/** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */
|
|
137
|
+
const tool_calls = prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION
|
|
138
|
+
? []
|
|
139
|
+
: undefined;
|
|
140
|
+
/** Edge Case: `id` and `name` fields cannot be empty strings */
|
|
141
|
+
for (const toolCallChunk of chunk.tool_call_chunks) {
|
|
142
|
+
if (toolCallChunk.name === '') {
|
|
143
|
+
toolCallChunk.name = undefined;
|
|
144
|
+
}
|
|
145
|
+
if (toolCallChunk.id === '') {
|
|
146
|
+
toolCallChunk.id = undefined;
|
|
147
|
+
}
|
|
148
|
+
else if (tool_calls != null && toolCallChunk.id != null && toolCallChunk.name != null) {
|
|
149
|
+
tool_calls.push({
|
|
150
|
+
args: {},
|
|
151
|
+
id: toolCallChunk.id,
|
|
152
|
+
name: toolCallChunk.name,
|
|
153
|
+
type: ToolCallTypes.TOOL_CALL,
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
let stepId = _stepId;
|
|
158
|
+
const alreadyDispatched = prevRunStep?.type === StepTypes.MESSAGE_CREATION && graph.messageStepHasToolCalls.has(prevStepId);
|
|
159
|
+
if (!alreadyDispatched && tool_calls?.length === chunk.tool_call_chunks.length) {
|
|
160
|
+
graph.dispatchMessageDelta(prevStepId, {
|
|
161
|
+
content: [{
|
|
162
|
+
type: 'text',
|
|
163
|
+
text: '',
|
|
164
|
+
tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),
|
|
165
|
+
}],
|
|
166
|
+
});
|
|
167
|
+
graph.messageStepHasToolCalls.set(prevStepId, true);
|
|
168
|
+
stepId = graph.dispatchRunStep(stepKey, {
|
|
169
|
+
type: StepTypes.TOOL_CALLS,
|
|
170
|
+
tool_calls,
|
|
171
|
+
});
|
|
172
|
+
}
|
|
134
173
|
graph.dispatchRunStepDelta(stepId, {
|
|
135
174
|
type: StepTypes.TOOL_CALLS,
|
|
136
175
|
tool_calls: chunk.tool_call_chunks,
|
|
@@ -313,12 +352,12 @@ function createContentAggregator() {
|
|
|
313
352
|
if (runStepDelta.delta.type === StepTypes.TOOL_CALLS &&
|
|
314
353
|
runStepDelta.delta.tool_calls) {
|
|
315
354
|
runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {
|
|
316
|
-
const toolCallId = toolCallIdMap.get(runStepDelta.id)
|
|
355
|
+
const toolCallId = toolCallIdMap.get(runStepDelta.id);
|
|
317
356
|
const contentPart = {
|
|
318
357
|
type: ContentTypes.TOOL_CALL,
|
|
319
358
|
tool_call: {
|
|
320
|
-
name: toolCallDelta.name ?? '',
|
|
321
359
|
args: toolCallDelta.args ?? '',
|
|
360
|
+
name: toolCallDelta.name,
|
|
322
361
|
id: toolCallId,
|
|
323
362
|
},
|
|
324
363
|
};
|
package/dist/esm/stream.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.mjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport { nanoid } from 'nanoid';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\nimport { StepTypes, ContentTypes, GraphEvents, ToolCallTypes } from '@/common';\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nexport const getMessageId = (stepKey: string, graph: Graph<t.BaseGraphState>, returnExistingId = false): string | undefined => {\n const messageId = graph.messageIdsByStepKey.get(stepKey);\n if (messageId != null && messageId) {\n return returnExistingId ? messageId : undefined;\n }\n\n const prelimMessageId = graph.prelimMessageIdsByStepKey.get(stepKey);\n if (prelimMessageId != null && prelimMessageId) {\n graph.prelimMessageIdsByStepKey.delete(stepKey);\n graph.messageIdsByStepKey.set(stepKey, prelimMessageId);\n return prelimMessageId;\n }\n\n const message_id = `msg_${nanoid()}`;\n graph.messageIdsByStepKey.set(stepKey, message_id);\n return message_id;\n};\n\nexport const handleToolCalls = (toolCalls?: ToolCall[], metadata?: Record<string, unknown>, graph?: Graph): void => {\n if (!graph || !metadata) {\n console.warn(`Graph or metadata not found in ${event} event`);\n return;\n }\n\n if (!toolCalls) {\n return;\n }\n\n if (toolCalls.length === 0) {\n return;\n }\n\n const tool_calls: ToolCall[] = [];\n const tool_call_ids: string[] = [];\n for (const tool_call of toolCalls) {\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\n tool_call.id = toolCallId;\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n\n tool_calls.push(tool_call);\n tool_call_ids.push(toolCallId);\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n let prevStepId = '';\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch (e) {\n // no previous step\n }\n\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\n graph.dispatchMessageDelta(lastMessageStepId, {\n content: [{\n type: 'text',\n text: '',\n tool_call_ids,\n }],\n });\n };\n /* If the previous step exists and is a message creation */\n if (prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION) {\n dispatchToolCallIds(prevStepId);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (!prevRunStep || prevRunStep.type !== StepTypes.MESSAGE_CREATION) {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n const stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n });\n dispatchToolCallIds(stepId);\n }\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n};\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData, metadata?: Record<string, unknown>, graph?: Graph): void {\n if (!graph) {\n throw new Error('Graph not found');\n }\n\n const chunk = data.chunk as AIMessageChunk | undefined;\n const content = chunk?.content;\n\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n\n if (!chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n let hasToolCalls = false;\n const hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n\n if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id)) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const isEmptyContent = typeof content === 'undefined' || !content.length || typeof content === 'string' && !content;\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n const chunkId = chunk.id ?? '';\n if (isEmptyChunk && chunkId && chunkId.startsWith('msg')) {\n if (graph.messageIdsByStepKey.has(chunkId)) {\n return;\n } else if (graph.prelimMessageIdsByStepKey.has(chunkId)) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunkId);\n return;\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (hasToolCallChunks\n && chunk.tool_call_chunks\n && chunk.tool_call_chunks.length\n && typeof chunk.tool_call_chunks[0]?.index === 'number') {\n const prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n const prevRunStep = graph.getRunStep(prevStepId);\n const stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\n graph.dispatchRunStepDelta(stepId, {\n type: StepTypes.TOOL_CALLS,\n tool_calls: chunk.tool_call_chunks,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n // eslint-disable-next-line no-console\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (hasToolCallChunks && (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)) {\n return;\n } else if (typeof content === 'string') {\n graph.dispatchMessageDelta(stepId, {\n content: [{\n type: 'text',\n text: content,\n }],\n });\n } else if (content.every((c) => c.type?.startsWith('text'))) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n }\n }\n}\n\nexport type ContentAggregatorResult = {\n stepMap: Map<string, t.RunStep | undefined>;\n contentParts: Array<t.MessageContentComplex | undefined>;\n aggregateContent: ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | {\n result: t.ToolEndEvent;\n };\n}) => void\n};\n\nexport function createContentAggregator(): ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart: t.MessageContentComplex,\n finalUpdate = false,\n ): void => {\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (partType === ContentTypes.IMAGE_URL && 'image_url' in contentPart) {\n const currentContent = contentParts[index] as { type: 'image_url'; image_url: string };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (partType === ContentTypes.TOOL_CALL && 'tool_call' in contentPart) {\n const existingContent = contentParts[index] as Omit<t.ToolCallContent, 'tool_call'> & { tool_call?: ToolCall } | undefined;\n\n const args = finalUpdate\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args || '') + (contentPart.tool_call.args ?? '');\n\n const id = getNonEmptyValue([contentPart.tool_call.id, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([contentPart.tool_call.name, existingContent?.tool_call?.name]) ?? '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | { result: t.ToolEndEvent };\n }): void => {\n\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (runStep.stepDetails.type === StepTypes.TOOL_CALLS && runStep.stepDetails.tool_calls) {\n runStep.stepDetails.tool_calls.forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id) ?? '';\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n name: toolCallDelta.name ?? '',\n args: toolCallDelta.args ?? '',\n id: toolCallId,\n },\n };\n\n updateContent(runStep.index, contentPart);\n });\n }\n } else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const { result } = data as unknown as { result: t.ToolEndEvent };\n\n const { id: stepId } = result;\n\n const runStep = stepMap.get(stepId);\n if (!runStep) {\n console.warn('No run step or runId found for completed tool call event');\n return;\n }\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: result.tool_call,\n };\n\n updateContent(runStep.index, contentPart, true);\n }\n\n };\n\n return { contentParts, aggregateContent, stepMap };\n}\n"],"names":[],"mappings":";;;AAAA;AAQA,SAAS,gBAAgB,CAAC,cAAwB,EAAA;AAChD,IAAA,KAAK,MAAM,KAAK,IAAI,cAAc,EAAE;QAClC,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;AAChC,YAAA,OAAO,KAAK,CAAC;SACd;KACF;AACD,IAAA,OAAO,SAAS,CAAC;AACnB,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AA,IAAI,EAAE,aAAa,CAAC,IAAI,IAAI,EAAE;AAC9B,4BAAA,EAAE,EAAE,UAAU;AACf,yBAAA;qBACF,CAAC;AAEF,oBAAA,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;AAC5C,iBAAC,CAAC,CAAC;aACJ;SACF;AAAM,aAAA,IAAI,KAAK,KAAK,WAAW,CAAC,qBAAqB,EAAE;AACtD,YAAA,MAAM,EAAE,MAAM,EAAE,GAAG,IAA6C,CAAC;AAEjE,YAAA,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;YAE9B,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YACpC,IAAI,CAAC,OAAO,EAAE;AACZ,gBAAA,OAAO,CAAC,IAAI,CAAC,0DAA0D,CAAC,CAAC;gBACzE,OAAO;aACR;AAED,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAE,YAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B,CAAC;YAEF,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;SACjD;AAEH,KAAC,CAAC;AAEF,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE,CAAC;AACrD;;;;"}
|
|
1
|
+
{"version":3,"file":"stream.mjs","sources":["../../src/stream.ts"],"sourcesContent":["// src/stream.ts\nimport { nanoid } from 'nanoid';\nimport type { AIMessageChunk } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\nimport { StepTypes, ContentTypes, GraphEvents, ToolCallTypes } from '@/common';\n\nfunction getNonEmptyValue(possibleValues: string[]): string | undefined {\n for (const value of possibleValues) {\n if (value && value.trim() !== '') {\n return value;\n }\n }\n return undefined;\n}\n\nexport const getMessageId = (stepKey: string, graph: Graph<t.BaseGraphState>, returnExistingId = false): string | undefined => {\n const messageId = graph.messageIdsByStepKey.get(stepKey);\n if (messageId != null && messageId) {\n return returnExistingId ? messageId : undefined;\n }\n\n const prelimMessageId = graph.prelimMessageIdsByStepKey.get(stepKey);\n if (prelimMessageId != null && prelimMessageId) {\n graph.prelimMessageIdsByStepKey.delete(stepKey);\n graph.messageIdsByStepKey.set(stepKey, prelimMessageId);\n return prelimMessageId;\n }\n\n const message_id = `msg_${nanoid()}`;\n graph.messageIdsByStepKey.set(stepKey, message_id);\n return message_id;\n};\n\nexport const handleToolCalls = (toolCalls?: ToolCall[], metadata?: Record<string, unknown>, graph?: Graph): void => {\n if (!graph || !metadata) {\n console.warn(`Graph or metadata not found in ${event} event`);\n return;\n }\n\n if (!toolCalls) {\n return;\n }\n\n if (toolCalls.length === 0) {\n return;\n }\n\n const tool_calls: ToolCall[] = [];\n const tool_call_ids: string[] = [];\n for (const tool_call of toolCalls) {\n const toolCallId = tool_call.id ?? `toolu_${nanoid()}`;\n tool_call.id = toolCallId;\n if (!toolCallId || graph.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n\n tool_calls.push(tool_call);\n tool_call_ids.push(toolCallId);\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n let prevStepId = '';\n let prevRunStep: t.RunStep | undefined;\n try {\n prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n prevRunStep = graph.getRunStep(prevStepId);\n } catch (e) {\n // no previous step\n }\n\n const dispatchToolCallIds = (lastMessageStepId: string): void => {\n graph.dispatchMessageDelta(lastMessageStepId, {\n content: [{\n type: 'text',\n text: '',\n tool_call_ids,\n }],\n });\n };\n /* If the previous step exists and is a message creation */\n if (prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION) {\n dispatchToolCallIds(prevStepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n /* If the previous step doesn't exist or is not a message creation */\n } else if (!prevRunStep || prevRunStep.type !== StepTypes.MESSAGE_CREATION) {\n const messageId = getMessageId(stepKey, graph, true) ?? '';\n const stepId = graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n },\n });\n dispatchToolCallIds(stepId);\n graph.messageStepHasToolCalls.set(prevStepId, true);\n }\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.TOOL_CALLS,\n tool_calls,\n });\n};\n\nexport class ChatModelStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData, metadata?: Record<string, unknown>, graph?: Graph): void {\n if (!graph) {\n throw new Error('Graph not found');\n }\n\n const chunk = data.chunk as AIMessageChunk | undefined;\n const content = chunk?.content;\n\n if (!graph.config) {\n throw new Error('Config not found in graph');\n }\n\n if (!chunk) {\n console.warn(`No chunk found in ${event} event`);\n return;\n }\n\n let hasToolCalls = false;\n const hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;\n\n if (chunk.tool_calls && chunk.tool_calls.length > 0 && chunk.tool_calls.every((tc) => tc.id)) {\n hasToolCalls = true;\n handleToolCalls(chunk.tool_calls, metadata, graph);\n }\n\n const isEmptyContent = typeof content === 'undefined' || !content.length || typeof content === 'string' && !content;\n const isEmptyChunk = isEmptyContent && !hasToolCallChunks;\n const chunkId = chunk.id ?? '';\n if (isEmptyChunk && chunkId && chunkId.startsWith('msg')) {\n if (graph.messageIdsByStepKey.has(chunkId)) {\n return;\n } else if (graph.prelimMessageIdsByStepKey.has(chunkId)) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n graph.prelimMessageIdsByStepKey.set(stepKey, chunkId);\n return;\n } else if (isEmptyChunk) {\n return;\n }\n\n const stepKey = graph.getStepKey(metadata);\n\n if (hasToolCallChunks\n && chunk.tool_call_chunks\n && chunk.tool_call_chunks.length\n && typeof chunk.tool_call_chunks[0]?.index === 'number') {\n const prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);\n const prevRunStep = graph.getRunStep(prevStepId);\n const _stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);\n /** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */\n const tool_calls: ToolCall[] | undefined =\n prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION\n ? []\n : undefined;\n /** Edge Case: `id` and `name` fields cannot be empty strings */\n for (const toolCallChunk of chunk.tool_call_chunks) {\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 === chunk.tool_call_chunks.length) {\n graph.dispatchMessageDelta(prevStepId, {\n content: [{\n type: '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: chunk.tool_call_chunks,\n });\n }\n\n if (isEmptyContent) {\n return;\n }\n\n const message_id = getMessageId(stepKey, graph) ?? '';\n if (message_id) {\n graph.dispatchRunStep(stepKey, {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id,\n },\n });\n }\n\n const stepId = graph.getStepIdByKey(stepKey);\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n // eslint-disable-next-line no-console\n console.warn(`\\n\n==============================================================\n\n\nRun step for ${stepId} does not exist, cannot dispatch delta event.\n\nevent: ${event}\nstepId: ${stepId}\nstepKey: ${stepKey}\nmessage_id: ${message_id}\nhasToolCalls: ${hasToolCalls}\nhasToolCallChunks: ${hasToolCallChunks}\n\n==============================================================\n\\n`);\n return;\n }\n\n /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */\n if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {\n return;\n } else if (hasToolCallChunks && (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)) {\n return;\n } else if (typeof content === 'string') {\n graph.dispatchMessageDelta(stepId, {\n content: [{\n type: 'text',\n text: content,\n }],\n });\n } else if (content.every((c) => c.type?.startsWith('text'))) {\n graph.dispatchMessageDelta(stepId, {\n content,\n });\n }\n }\n}\n\nexport type ContentAggregatorResult = {\n stepMap: Map<string, t.RunStep | undefined>;\n contentParts: Array<t.MessageContentComplex | undefined>;\n aggregateContent: ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | {\n result: t.ToolEndEvent;\n };\n}) => void\n};\n\nexport function createContentAggregator(): ContentAggregatorResult {\n const contentParts: Array<t.MessageContentComplex | undefined> = [];\n const stepMap = new Map<string, t.RunStep>();\n const toolCallIdMap = new Map<string, string>();\n\n const updateContent = (\n index: number,\n contentPart: t.MessageContentComplex,\n finalUpdate = false,\n ): void => {\n const partType = contentPart.type ?? '';\n if (!partType) {\n console.warn('No content type found in content part');\n return;\n }\n\n if (!contentParts[index]) {\n contentParts[index] = { type: partType };\n }\n\n if (!partType.startsWith(contentParts[index]?.type ?? '')) {\n console.warn('Content type mismatch');\n return;\n }\n\n if (\n partType.startsWith(ContentTypes.TEXT) &&\n ContentTypes.TEXT in contentPart &&\n typeof contentPart.text === 'string'\n ) {\n // TODO: update this!!\n const currentContent = contentParts[index] as t.MessageDeltaUpdate;\n const update: t.MessageDeltaUpdate = {\n type: ContentTypes.TEXT,\n text: (currentContent.text || '') + contentPart.text,\n };\n\n if (contentPart.tool_call_ids) {\n update.tool_call_ids = contentPart.tool_call_ids;\n }\n contentParts[index] = update;\n } else if (\n partType.startsWith(ContentTypes.THINK) &&\n ContentTypes.THINK in contentPart &&\n typeof contentPart.think === 'string'\n ) {\n const currentContent = contentParts[index] as t.ReasoningDeltaUpdate;\n const update: t.ReasoningDeltaUpdate = {\n type: ContentTypes.THINK,\n think: (currentContent.think || '') + contentPart.think,\n };\n contentParts[index] = update;\n } else if (partType === ContentTypes.IMAGE_URL && 'image_url' in contentPart) {\n const currentContent = contentParts[index] as { type: 'image_url'; image_url: string };\n contentParts[index] = {\n ...currentContent,\n };\n } else if (partType === ContentTypes.TOOL_CALL && 'tool_call' in contentPart) {\n const existingContent = contentParts[index] as Omit<t.ToolCallContent, 'tool_call'> & { tool_call?: ToolCall } | undefined;\n\n const args = finalUpdate\n ? contentPart.tool_call.args\n : (existingContent?.tool_call?.args || '') + (contentPart.tool_call.args ?? '');\n\n const id = getNonEmptyValue([contentPart.tool_call.id, existingContent?.tool_call?.id]) ?? '';\n const name =\n getNonEmptyValue([contentPart.tool_call.name, existingContent?.tool_call?.name]) ?? '';\n\n const newToolCall: ToolCall & t.PartMetadata = {\n id,\n name,\n args,\n type: ToolCallTypes.TOOL_CALL,\n };\n\n if (finalUpdate) {\n newToolCall.progress = 1;\n newToolCall.output = contentPart.tool_call.output;\n }\n\n contentParts[index] = {\n type: ContentTypes.TOOL_CALL,\n tool_call: newToolCall,\n };\n }\n };\n\n const aggregateContent = ({ event, data }: {\n event: GraphEvents;\n data: t.RunStep | t.MessageDeltaEvent | t.RunStepDeltaEvent | { result: t.ToolEndEvent };\n }): void => {\n\n if (event === GraphEvents.ON_RUN_STEP) {\n const runStep = data as t.RunStep;\n stepMap.set(runStep.id, runStep);\n\n // Store tool call IDs if present\n if (runStep.stepDetails.type === StepTypes.TOOL_CALLS && runStep.stepDetails.tool_calls) {\n runStep.stepDetails.tool_calls.forEach((toolCall) => {\n const toolCallId = toolCall.id ?? '';\n if ('id' in toolCall && toolCallId) {\n toolCallIdMap.set(runStep.id, toolCallId);\n }\n });\n }\n } else if (event === GraphEvents.ON_MESSAGE_DELTA) {\n const messageDelta = data as t.MessageDeltaEvent;\n const runStep = stepMap.get(messageDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (messageDelta.delta.content) {\n const contentPart = Array.isArray(messageDelta.delta.content)\n ? messageDelta.delta.content[0]\n : messageDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_REASONING_DELTA) {\n const reasoningDelta = data as t.ReasoningDeltaEvent;\n const runStep = stepMap.get(reasoningDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for message delta event');\n return;\n }\n\n if (reasoningDelta.delta.content) {\n const contentPart = Array.isArray(reasoningDelta.delta.content)\n ? reasoningDelta.delta.content[0]\n : reasoningDelta.delta.content;\n\n updateContent(runStep.index, contentPart);\n }\n } else if (event === GraphEvents.ON_RUN_STEP_DELTA) {\n const runStepDelta = data as t.RunStepDeltaEvent;\n const runStep = stepMap.get(runStepDelta.id);\n if (!runStep) {\n console.warn('No run step or runId found for run step delta event');\n return;\n }\n\n if (\n runStepDelta.delta.type === StepTypes.TOOL_CALLS &&\n runStepDelta.delta.tool_calls\n ) {\n\n runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {\n const toolCallId = toolCallIdMap.get(runStepDelta.id);\n\n const contentPart: t.MessageContentComplex = {\n type: ContentTypes.TOOL_CALL,\n tool_call: {\n 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 { content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BACzE,OAAO;aACR;AAED,YAAA,MAAM,WAAW,GAA4B;gBAC3C,IAAI,EAAE,YAAY,CAAC,SAAS;gBAC5B,SAAS,EAAE,MAAM,CAAC,SAAS;aAC5B,CAAC;YAEF,aAAa,CAAC,OAAO,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;SACjD;AAEH,KAAC,CAAC;AAEF,IAAA,OAAO,EAAE,YAAY,EAAE,gBAAgB,EAAE,OAAO,EAAE,CAAC;AACrD;;;;"}
|
|
@@ -36,6 +36,7 @@ export declare abstract class Graph<T extends t.BaseGraphState = t.BaseGraphStat
|
|
|
36
36
|
abstract handleToolCallCompleted(data: t.ToolEndData, metadata?: Record<string, unknown>): void;
|
|
37
37
|
abstract createCallModel(): (state: T, config?: RunnableConfig) => Promise<Partial<T>>;
|
|
38
38
|
abstract createWorkflow(): t.CompiledWorkflow<T>;
|
|
39
|
+
messageStepHasToolCalls: Map<string, boolean>;
|
|
39
40
|
messageIdsByStepKey: Map<string, string>;
|
|
40
41
|
prelimMessageIdsByStepKey: Map<string, string>;
|
|
41
42
|
config: RunnableConfig | undefined;
|
package/package.json
CHANGED
package/src/graphs/Graph.ts
CHANGED
|
@@ -60,6 +60,7 @@ export abstract class Graph<
|
|
|
60
60
|
|
|
61
61
|
abstract createCallModel(): (state: T, config?: RunnableConfig) => Promise<Partial<T>>;
|
|
62
62
|
abstract createWorkflow(): t.CompiledWorkflow<T>;
|
|
63
|
+
messageStepHasToolCalls: Map<string, boolean> = new Map();
|
|
63
64
|
messageIdsByStepKey: Map<string, string> = new Map();
|
|
64
65
|
prelimMessageIdsByStepKey: Map<string, string> = new Map();
|
|
65
66
|
config: RunnableConfig | undefined;
|
|
@@ -149,6 +150,7 @@ export class StandardGraph extends Graph<
|
|
|
149
150
|
this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());
|
|
150
151
|
this.toolCallStepIds = resetIfNotEmpty(this.toolCallStepIds, new Map());
|
|
151
152
|
this.messageIdsByStepKey = resetIfNotEmpty(this.messageIdsByStepKey, new Map());
|
|
153
|
+
this.messageStepHasToolCalls = resetIfNotEmpty(this.prelimMessageIdsByStepKey, new Map());
|
|
152
154
|
this.prelimMessageIdsByStepKey = resetIfNotEmpty(this.prelimMessageIdsByStepKey, new Map());
|
|
153
155
|
}
|
|
154
156
|
|
|
@@ -364,8 +366,16 @@ export class StandardGraph extends Graph<
|
|
|
364
366
|
return { messages: [finalChunk as AIMessageChunk] };
|
|
365
367
|
}
|
|
366
368
|
|
|
367
|
-
const finalMessage = await this.boundModel.invoke(finalMessages, config);
|
|
368
|
-
|
|
369
|
+
const finalMessage = (await this.boundModel.invoke(finalMessages, config)) as AIMessageChunk;
|
|
370
|
+
if ((finalMessage.tool_calls?.length ?? 0) > 0) {
|
|
371
|
+
finalMessage.tool_calls = finalMessage.tool_calls?.filter((tool_call) => {
|
|
372
|
+
if (!tool_call.name) {
|
|
373
|
+
return false;
|
|
374
|
+
}
|
|
375
|
+
return true;
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
return { messages: [finalMessage] };
|
|
369
379
|
};
|
|
370
380
|
}
|
|
371
381
|
|
package/src/stream.ts
CHANGED
|
@@ -83,6 +83,7 @@ export const handleToolCalls = (toolCalls?: ToolCall[], metadata?: Record<string
|
|
|
83
83
|
/* If the previous step exists and is a message creation */
|
|
84
84
|
if (prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION) {
|
|
85
85
|
dispatchToolCallIds(prevStepId);
|
|
86
|
+
graph.messageStepHasToolCalls.set(prevStepId, true);
|
|
86
87
|
/* If the previous step doesn't exist or is not a message creation */
|
|
87
88
|
} else if (!prevRunStep || prevRunStep.type !== StepTypes.MESSAGE_CREATION) {
|
|
88
89
|
const messageId = getMessageId(stepKey, graph, true) ?? '';
|
|
@@ -93,6 +94,7 @@ export const handleToolCalls = (toolCalls?: ToolCall[], metadata?: Record<string
|
|
|
93
94
|
},
|
|
94
95
|
});
|
|
95
96
|
dispatchToolCallIds(stepId);
|
|
97
|
+
graph.messageStepHasToolCalls.set(prevStepId, true);
|
|
96
98
|
}
|
|
97
99
|
graph.dispatchRunStep(stepKey, {
|
|
98
100
|
type: StepTypes.TOOL_CALLS,
|
|
@@ -151,7 +153,45 @@ export class ChatModelStreamHandler implements t.EventHandler {
|
|
|
151
153
|
&& typeof chunk.tool_call_chunks[0]?.index === 'number') {
|
|
152
154
|
const prevStepId = graph.getStepIdByKey(stepKey, graph.contentData.length - 1);
|
|
153
155
|
const prevRunStep = graph.getRunStep(prevStepId);
|
|
154
|
-
const
|
|
156
|
+
const _stepId = graph.getStepIdByKey(stepKey, prevRunStep?.index);
|
|
157
|
+
/** Edge Case: Tool Call Run Step or `tool_call_ids` never dispatched */
|
|
158
|
+
const tool_calls: ToolCall[] | undefined =
|
|
159
|
+
prevStepId && prevRunStep && prevRunStep.type === StepTypes.MESSAGE_CREATION
|
|
160
|
+
? []
|
|
161
|
+
: undefined;
|
|
162
|
+
/** Edge Case: `id` and `name` fields cannot be empty strings */
|
|
163
|
+
for (const toolCallChunk of chunk.tool_call_chunks) {
|
|
164
|
+
if (toolCallChunk.name === '') {
|
|
165
|
+
toolCallChunk.name = undefined;
|
|
166
|
+
}
|
|
167
|
+
if (toolCallChunk.id === '') {
|
|
168
|
+
toolCallChunk.id = undefined;
|
|
169
|
+
} else if (tool_calls != null && toolCallChunk.id != null && toolCallChunk.name != null) {
|
|
170
|
+
tool_calls.push({
|
|
171
|
+
args: {},
|
|
172
|
+
id: toolCallChunk.id,
|
|
173
|
+
name: toolCallChunk.name,
|
|
174
|
+
type: ToolCallTypes.TOOL_CALL,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
let stepId: string = _stepId;
|
|
180
|
+
const alreadyDispatched = prevRunStep?.type === StepTypes.MESSAGE_CREATION && graph.messageStepHasToolCalls.has(prevStepId);
|
|
181
|
+
if (!alreadyDispatched && tool_calls?.length === chunk.tool_call_chunks.length) {
|
|
182
|
+
graph.dispatchMessageDelta(prevStepId, {
|
|
183
|
+
content: [{
|
|
184
|
+
type: 'text',
|
|
185
|
+
text: '',
|
|
186
|
+
tool_call_ids: tool_calls.map((tc) => tc.id ?? ''),
|
|
187
|
+
}],
|
|
188
|
+
});
|
|
189
|
+
graph.messageStepHasToolCalls.set(prevStepId, true);
|
|
190
|
+
stepId = graph.dispatchRunStep(stepKey, {
|
|
191
|
+
type: StepTypes.TOOL_CALLS,
|
|
192
|
+
tool_calls,
|
|
193
|
+
});
|
|
194
|
+
}
|
|
155
195
|
graph.dispatchRunStepDelta(stepId, {
|
|
156
196
|
type: StepTypes.TOOL_CALLS,
|
|
157
197
|
tool_calls: chunk.tool_call_chunks,
|
|
@@ -374,13 +414,13 @@ export function createContentAggregator(): ContentAggregatorResult {
|
|
|
374
414
|
) {
|
|
375
415
|
|
|
376
416
|
runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {
|
|
377
|
-
const toolCallId = toolCallIdMap.get(runStepDelta.id)
|
|
417
|
+
const toolCallId = toolCallIdMap.get(runStepDelta.id);
|
|
378
418
|
|
|
379
419
|
const contentPart: t.MessageContentComplex = {
|
|
380
420
|
type: ContentTypes.TOOL_CALL,
|
|
381
421
|
tool_call: {
|
|
382
|
-
name: toolCallDelta.name ?? '',
|
|
383
422
|
args: toolCallDelta.args ?? '',
|
|
423
|
+
name: toolCallDelta.name,
|
|
384
424
|
id: toolCallId,
|
|
385
425
|
},
|
|
386
426
|
};
|
package/src/utils/llmConfig.ts
CHANGED
|
@@ -11,6 +11,16 @@ export const llmConfigs: Record<string, t.LLMConfig | undefined> = {
|
|
|
11
11
|
streamUsage: true,
|
|
12
12
|
// disableStreaming: true,
|
|
13
13
|
},
|
|
14
|
+
alibaba: {
|
|
15
|
+
provider: Providers.OPENAI,
|
|
16
|
+
streaming: true,
|
|
17
|
+
streamUsage: true,
|
|
18
|
+
model: 'qwen-max',
|
|
19
|
+
openAIApiKey: process.env.ALIBABA_API_KEY,
|
|
20
|
+
configuration: {
|
|
21
|
+
baseURL: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1',
|
|
22
|
+
},
|
|
23
|
+
},
|
|
14
24
|
[Providers.AZURE]: {
|
|
15
25
|
provider: Providers.AZURE,
|
|
16
26
|
temperature: 0.7,
|