@librechat/agents 1.5.9 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/events.cjs +1 -1
- package/dist/cjs/events.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +9 -9
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/esm/events.mjs +1 -1
- package/dist/esm/events.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +9 -9
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/types/graphs/Graph.d.ts +1 -1
- package/package.json +1 -1
- package/src/events.ts +1 -1
- package/src/graphs/Graph.ts +10 -10
package/dist/cjs/events.cjs
CHANGED
|
@@ -38,7 +38,7 @@ class ToolEndHandler {
|
|
|
38
38
|
return;
|
|
39
39
|
}
|
|
40
40
|
this.callback?.(toolEndData);
|
|
41
|
-
graph.handleToolCallCompleted({ input: toolEndData.input, output: toolEndData.output });
|
|
41
|
+
graph.handleToolCallCompleted({ input: toolEndData.input, output: toolEndData.output }, metadata);
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
44
|
class TestLLMStreamHandler {
|
package/dist/cjs/events.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.cjs","sources":["../../src/events.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/events.ts\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\n\nexport class HandlerRegistry {\n private handlers: Map<string, t.EventHandler> = new Map();\n\n register(eventType: string, handler: t.EventHandler): void {\n this.handlers.set(eventType, handler);\n }\n\n getHandler(eventType: string): t.EventHandler | undefined {\n return this.handlers.get(eventType);\n }\n}\n\nexport class ModelEndHandler implements t.EventHandler {\n handle(event: string, data: t.ModelEndData, 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 const usage = data?.output?.usage_metadata;\n\n console.log(`====== ${event.toUpperCase()} ======`);\n console.dir({\n usage,\n }, { depth: null });\n }\n}\n\nexport class ToolEndHandler implements t.EventHandler {\n private callback?: t.ToolEndCallback;\n constructor(callback?: t.ToolEndCallback) {\n this.callback = callback;\n }\n handle(event: string, data: t.StreamEventData | undefined, 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 const toolEndData = data as t.ToolEndData | undefined;\n if (!toolEndData?.output) {\n console.warn('No output found in tool_end event');\n return;\n }\n\n this.callback?.(toolEndData);\n\n graph.handleToolCallCompleted({ input: toolEndData.input, output: toolEndData.output });\n }\n}\n\nexport class TestLLMStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData | undefined): void {\n const chunk = data?.chunk;\n const isMessageChunk = !!(chunk && 'message' in chunk);\n const msg = isMessageChunk && chunk.message;\n if (msg && msg.tool_call_chunks && msg.tool_call_chunks.length > 0) {\n console.log(msg.tool_call_chunks);\n } else if (msg && msg.content) {\n if (typeof msg.content === 'string') {\n process.stdout.write(msg.content);\n }\n }\n }\n}\n\nexport class TestChatStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData | undefined): void {\n const chunk = data?.chunk;\n const isContentChunk = !!(chunk && 'content' in chunk);\n const content = isContentChunk && chunk.content;\n\n if (!content || !isContentChunk) {\n return;\n }\n\n if (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) {\n console.dir(chunk.tool_call_chunks, { depth: null });\n }\n\n if (typeof content === 'string') {\n process.stdout.write(content);\n } else {\n console.dir(content, { depth: null });\n }\n }\n}\n\nexport class LLMStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData | undefined, metadata?: Record<string, unknown>): void {\n const chunk = data?.chunk;\n const isMessageChunk = !!(chunk && 'message' in chunk);\n const msg = isMessageChunk && chunk.message;\n if (metadata) { console.log(metadata); }\n if (msg && msg.tool_call_chunks && msg.tool_call_chunks.length > 0) {\n console.log(msg.tool_call_chunks);\n } else if (msg && msg.content) {\n if (typeof msg.content === 'string') {\n // const text_delta = msg.content;\n // dispatchCustomEvent(GraphEvents.CHAT_MODEL_STREAM, { chunk }, config);\n process.stdout.write(msg.content);\n }\n }\n }\n}\n\nexport const createMetadataAggregator = (_collected?: Record<string, unknown>[]): t.MetadataAggregatorResult => {\n const collected = _collected || [];\n\n const handleLLMEnd: t.HandleLLMEnd = (output) => {\n const { generations } = output;\n const lastMessageOutput = (generations[generations.length - 1] as (t.StreamGeneration | undefined)[] | undefined)?.[0];\n if (!lastMessageOutput) {\n return;\n }\n const { message } = lastMessageOutput;\n if (message?.response_metadata) {\n collected.push(message.response_metadata);\n }\n };\n\n return { handleLLMEnd, collected };\n};"],"names":[],"mappings":";;MAKa,eAAe,CAAA;AAClB,IAAA,QAAQ,GAAgC,IAAI,GAAG,EAAE,CAAC;IAE1D,QAAQ,CAAC,SAAiB,EAAE,OAAuB,EAAA;QACjD,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;KACvC;AAED,IAAA,UAAU,CAAC,SAAiB,EAAA;QAC1B,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;KACrC;AACF,CAAA;MAEY,eAAe,CAAA;AAC1B,IAAA,MAAM,CAAC,KAAa,EAAE,IAAoB,EAAE,QAAkC,EAAE,KAAa,EAAA;AAC3F,QAAA,IAAI,CAAC,KAAK,IAAI,CAAC,QAAQ,EAAE;AACvB,YAAA,OAAO,CAAC,IAAI,CAAC,kCAAkC,KAAK,CAAA,MAAA,CAAQ,CAAC,CAAC;YAC9D,OAAO;SACR;AAED,QAAA,MAAM,KAAK,GAAG,IAAI,EAAE,MAAM,EAAE,cAAc,CAAC;QAE3C,OAAO,CAAC,GAAG,CAAC,CAAU,OAAA,EAAA,KAAK,CAAC,WAAW,EAAE,CAAS,OAAA,CAAA,CAAC,CAAC;QACpD,OAAO,CAAC,GAAG,CAAC;YACV,KAAK;AACN,SAAA,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;KACrB;AACF,CAAA;MAEY,cAAc,CAAA;AACjB,IAAA,QAAQ,CAAqB;AACrC,IAAA,WAAA,CAAY,QAA4B,EAAA;AACtC,QAAA,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;KAC1B;AACD,IAAA,MAAM,CAAC,KAAa,EAAE,IAAmC,EAAE,QAAkC,EAAE,KAAa,EAAA;AAC1G,QAAA,IAAI,CAAC,KAAK,IAAI,CAAC,QAAQ,EAAE;AACvB,YAAA,OAAO,CAAC,IAAI,CAAC,kCAAkC,KAAK,CAAA,MAAA,CAAQ,CAAC,CAAC;YAC9D,OAAO;SACR;QAED,MAAM,WAAW,GAAG,IAAiC,CAAC;AACtD,QAAA,IAAI,CAAC,WAAW,EAAE,MAAM,EAAE;AACxB,YAAA,OAAO,CAAC,IAAI,CAAC,mCAAmC,CAAC,CAAC;YAClD,OAAO;SACR;AAED,QAAA,IAAI,CAAC,QAAQ,GAAG,WAAW,CAAC,CAAC;AAE7B,QAAA,KAAK,CAAC,uBAAuB,CAAC,EAAE,KAAK,EAAE,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,WAAW,CAAC,MAAM,EAAE,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"events.cjs","sources":["../../src/events.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/events.ts\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\n\nexport class HandlerRegistry {\n private handlers: Map<string, t.EventHandler> = new Map();\n\n register(eventType: string, handler: t.EventHandler): void {\n this.handlers.set(eventType, handler);\n }\n\n getHandler(eventType: string): t.EventHandler | undefined {\n return this.handlers.get(eventType);\n }\n}\n\nexport class ModelEndHandler implements t.EventHandler {\n handle(event: string, data: t.ModelEndData, 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 const usage = data?.output?.usage_metadata;\n\n console.log(`====== ${event.toUpperCase()} ======`);\n console.dir({\n usage,\n }, { depth: null });\n }\n}\n\nexport class ToolEndHandler implements t.EventHandler {\n private callback?: t.ToolEndCallback;\n constructor(callback?: t.ToolEndCallback) {\n this.callback = callback;\n }\n handle(event: string, data: t.StreamEventData | undefined, 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 const toolEndData = data as t.ToolEndData | undefined;\n if (!toolEndData?.output) {\n console.warn('No output found in tool_end event');\n return;\n }\n\n this.callback?.(toolEndData);\n\n graph.handleToolCallCompleted({ input: toolEndData.input, output: toolEndData.output }, metadata);\n }\n}\n\nexport class TestLLMStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData | undefined): void {\n const chunk = data?.chunk;\n const isMessageChunk = !!(chunk && 'message' in chunk);\n const msg = isMessageChunk && chunk.message;\n if (msg && msg.tool_call_chunks && msg.tool_call_chunks.length > 0) {\n console.log(msg.tool_call_chunks);\n } else if (msg && msg.content) {\n if (typeof msg.content === 'string') {\n process.stdout.write(msg.content);\n }\n }\n }\n}\n\nexport class TestChatStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData | undefined): void {\n const chunk = data?.chunk;\n const isContentChunk = !!(chunk && 'content' in chunk);\n const content = isContentChunk && chunk.content;\n\n if (!content || !isContentChunk) {\n return;\n }\n\n if (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) {\n console.dir(chunk.tool_call_chunks, { depth: null });\n }\n\n if (typeof content === 'string') {\n process.stdout.write(content);\n } else {\n console.dir(content, { depth: null });\n }\n }\n}\n\nexport class LLMStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData | undefined, metadata?: Record<string, unknown>): void {\n const chunk = data?.chunk;\n const isMessageChunk = !!(chunk && 'message' in chunk);\n const msg = isMessageChunk && chunk.message;\n if (metadata) { console.log(metadata); }\n if (msg && msg.tool_call_chunks && msg.tool_call_chunks.length > 0) {\n console.log(msg.tool_call_chunks);\n } else if (msg && msg.content) {\n if (typeof msg.content === 'string') {\n // const text_delta = msg.content;\n // dispatchCustomEvent(GraphEvents.CHAT_MODEL_STREAM, { chunk }, config);\n process.stdout.write(msg.content);\n }\n }\n }\n}\n\nexport const createMetadataAggregator = (_collected?: Record<string, unknown>[]): t.MetadataAggregatorResult => {\n const collected = _collected || [];\n\n const handleLLMEnd: t.HandleLLMEnd = (output) => {\n const { generations } = output;\n const lastMessageOutput = (generations[generations.length - 1] as (t.StreamGeneration | undefined)[] | undefined)?.[0];\n if (!lastMessageOutput) {\n return;\n }\n const { message } = lastMessageOutput;\n if (message?.response_metadata) {\n collected.push(message.response_metadata);\n }\n };\n\n return { handleLLMEnd, collected };\n};"],"names":[],"mappings":";;MAKa,eAAe,CAAA;AAClB,IAAA,QAAQ,GAAgC,IAAI,GAAG,EAAE,CAAC;IAE1D,QAAQ,CAAC,SAAiB,EAAE,OAAuB,EAAA;QACjD,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;KACvC;AAED,IAAA,UAAU,CAAC,SAAiB,EAAA;QAC1B,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;KACrC;AACF,CAAA;MAEY,eAAe,CAAA;AAC1B,IAAA,MAAM,CAAC,KAAa,EAAE,IAAoB,EAAE,QAAkC,EAAE,KAAa,EAAA;AAC3F,QAAA,IAAI,CAAC,KAAK,IAAI,CAAC,QAAQ,EAAE;AACvB,YAAA,OAAO,CAAC,IAAI,CAAC,kCAAkC,KAAK,CAAA,MAAA,CAAQ,CAAC,CAAC;YAC9D,OAAO;SACR;AAED,QAAA,MAAM,KAAK,GAAG,IAAI,EAAE,MAAM,EAAE,cAAc,CAAC;QAE3C,OAAO,CAAC,GAAG,CAAC,CAAU,OAAA,EAAA,KAAK,CAAC,WAAW,EAAE,CAAS,OAAA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E,CAAC;AACrC;;;;;;;;;;"}
|
|
@@ -173,7 +173,7 @@ class StandardGraph extends Graph {
|
|
|
173
173
|
}
|
|
174
174
|
createCallModel() {
|
|
175
175
|
return async (state, config) => {
|
|
176
|
-
const { provider } = config?.configurable ?? {};
|
|
176
|
+
const { provider = '' } = config?.configurable ?? {};
|
|
177
177
|
if (!config || !provider) {
|
|
178
178
|
throw new Error(`No ${config ? 'provider' : 'config'} provided`);
|
|
179
179
|
}
|
|
@@ -196,7 +196,7 @@ class StandardGraph extends Graph {
|
|
|
196
196
|
}
|
|
197
197
|
}
|
|
198
198
|
this.lastStreamCall = Date.now();
|
|
199
|
-
if (this.tools?.length && (provider === _enum.Providers.ANTHROPIC || provider === _enum.Providers.BEDROCK)) {
|
|
199
|
+
if ((this.tools?.length ?? 0) > 0 && (provider === _enum.Providers.ANTHROPIC || provider === _enum.Providers.BEDROCK)) {
|
|
200
200
|
const stream$1 = await this.boundModel.stream(finalMessages, config);
|
|
201
201
|
let finalChunk;
|
|
202
202
|
for await (const chunk of stream$1) {
|
|
@@ -246,10 +246,11 @@ class StandardGraph extends Graph {
|
|
|
246
246
|
const [stepId, stepIndex] = this.generateStepId(stepKey);
|
|
247
247
|
if (stepDetails.type === _enum.StepTypes.TOOL_CALLS && stepDetails.tool_calls) {
|
|
248
248
|
for (const tool_call of stepDetails.tool_calls) {
|
|
249
|
-
|
|
249
|
+
const toolCallId = tool_call.id ?? '';
|
|
250
|
+
if (!toolCallId || this.toolCallStepIds.has(toolCallId)) {
|
|
250
251
|
continue;
|
|
251
252
|
}
|
|
252
|
-
this.toolCallStepIds.set(
|
|
253
|
+
this.toolCallStepIds.set(toolCallId, stepId);
|
|
253
254
|
}
|
|
254
255
|
}
|
|
255
256
|
const runStep = {
|
|
@@ -260,8 +261,9 @@ class StandardGraph extends Graph {
|
|
|
260
261
|
stepDetails,
|
|
261
262
|
usage: null,
|
|
262
263
|
};
|
|
263
|
-
|
|
264
|
-
|
|
264
|
+
const runId = this.runId ?? '';
|
|
265
|
+
if (runId) {
|
|
266
|
+
runStep.runId = runId;
|
|
265
267
|
}
|
|
266
268
|
this.contentData.push(runStep);
|
|
267
269
|
this.contentIndexMap.set(stepId, runStep.index);
|
|
@@ -274,7 +276,7 @@ class StandardGraph extends Graph {
|
|
|
274
276
|
}
|
|
275
277
|
const { input, output } = data;
|
|
276
278
|
const { tool_call_id } = output;
|
|
277
|
-
const stepId = this.toolCallStepIds.get(tool_call_id);
|
|
279
|
+
const stepId = this.toolCallStepIds.get(tool_call_id) ?? '';
|
|
278
280
|
if (!stepId) {
|
|
279
281
|
throw new Error(`No stepId found for tool_call_id ${tool_call_id}`);
|
|
280
282
|
}
|
|
@@ -283,8 +285,6 @@ class StandardGraph extends Graph {
|
|
|
283
285
|
throw new Error(`No run step found for stepId ${stepId}`);
|
|
284
286
|
}
|
|
285
287
|
if (!data.output) {
|
|
286
|
-
// console.warn('No output found in tool_end event');
|
|
287
|
-
// console.dir(data, { depth: null });
|
|
288
288
|
return;
|
|
289
289
|
}
|
|
290
290
|
const args = typeof input === 'string' ? input : input.input;
|
|
@@ -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 { START, StateGraph } from '@langchain/langgraph';\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 { StructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { Providers, GraphEvents, GraphNodeKeys, StepTypes, Callback } from '@/common';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport { modifyDeltaProperties, convertMessagesToContent } from '@/messages';\nimport { resetIfNotEmpty, joinKeys, sleep } from '@/utils';\nimport { getChatModelClass } from '@/llm/providers';\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 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): void;\n\n abstract createCallModel(): (state: T, config?: RunnableConfig) => Promise<Partial<T>>;\n abstract createWorkflow(): t.CompiledWorkflow<T, Partial<T>, TNodeName>;\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}\n\nexport class StandardGraph extends Graph<\n t.BaseGraphState,\n GraphNode\n> {\n private graphState: t.GraphStateChannels<t.BaseGraphState>;\n private clientOptions: Record<string, unknown>;\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\n constructor({\n runId,\n tools,\n toolMap,\n provider,\n clientOptions,\n instructions,\n additional_instructions = '',\n streamBuffer,\n } : {\n runId?: string;\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 }) {\n super();\n this.runId = runId;\n this.tools = tools;\n this.toolMap = toolMap;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.streamBuffer = streamBuffer;\n this.graphState = this.createGraphState();\n this.boundModel = this.initializeModel();\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(): void {\n this.messages = [];\n this.config = resetIfNotEmpty(this.config, undefined);\n this.contentData = resetIfNotEmpty(this.contentData, []);\n this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n this.toolCallStepIds = resetIfNotEmpty(this.toolCallStepIds, new Map());\n this.contentIndexMap = resetIfNotEmpty(this.contentIndexMap, 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.thread_id as string,\n metadata.langgraph_node as string,\n metadata.langgraph_step as number,\n metadata.langgraph_task_idx as number,\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 });\n }\n\n initializeModel(): Runnable {\n const ChatModelClass = getChatModelClass(this.provider);\n const model = new ChatModelClass(this.clientOptions);\n if (!this.tools || this.tools.length === 0) {\n return model;\n }\n return model.bindTools(this.tools as StructuredTool[]);\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 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 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 && (provider === Providers.ANTHROPIC || provider === Providers.BEDROCK)) {\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, Partial<t.BaseGraphState>, GraphNode> {\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, Partial<t.BaseGraphState>, GraphNode>({\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, 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 if (!tool_call.id || this.toolCallStepIds.has(tool_call.id)) {\n continue;\n }\n this.toolCallStepIds.set(tool_call.id, 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 if (this.runId) {\n runStep.runId = this.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 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 const runStep = this.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n if (!data.output) {\n // console.warn('No output found in tool_end event');\n // console.dir(data, { depth: null });\n return;\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","messages","Providers","AIMessageChunk","ToolMessage","sleep","stream","dispatchCustomEvent","GraphEvents","concat","modifyDeltaProperties","toolsCondition","StateGraph","START","StepTypes"],"mappings":";;;;;;;;;;;;;;AAAA;AAkBA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAGA,mBAAa,CAAC;MAcjB,KAAK,CAAA;AAuBzB,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;AAClC,CAAA;AAEK,MAAO,aAAc,SAAQ,KAGlC,CAAA;AACS,IAAA,UAAU,CAAyC;AACnD,IAAA,aAAa,CAA0B;AAC/C,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;AAEpB,IAAA,WAAA,CAAY,EACV,KAAK,EACL,KAAK,EACL,OAAO,EACP,QAAQ,EACR,aAAa,EACb,YAAY,EACZ,uBAAuB,G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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;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;;;;;"}
|
|
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 { START, StateGraph } from '@langchain/langgraph';\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 { StructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { Providers, GraphEvents, GraphNodeKeys, StepTypes, Callback } from '@/common';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport { modifyDeltaProperties, convertMessagesToContent } from '@/messages';\nimport { resetIfNotEmpty, joinKeys, sleep } from '@/utils';\nimport { getChatModelClass } from '@/llm/providers';\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 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, Partial<T>, TNodeName>;\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}\n\nexport class StandardGraph extends Graph<\n t.BaseGraphState,\n GraphNode\n> {\n private graphState: t.GraphStateChannels<t.BaseGraphState>;\n private clientOptions: Record<string, unknown>;\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\n constructor({\n runId,\n tools,\n toolMap,\n provider,\n clientOptions,\n instructions,\n additional_instructions = '',\n streamBuffer,\n } : {\n runId?: string;\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 }) {\n super();\n this.runId = runId;\n this.tools = tools;\n this.toolMap = toolMap;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.streamBuffer = streamBuffer;\n this.graphState = this.createGraphState();\n this.boundModel = this.initializeModel();\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(): void {\n this.messages = [];\n this.config = resetIfNotEmpty(this.config, undefined);\n this.contentData = resetIfNotEmpty(this.contentData, []);\n this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n this.toolCallStepIds = resetIfNotEmpty(this.toolCallStepIds, new Map());\n this.contentIndexMap = resetIfNotEmpty(this.contentIndexMap, 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.thread_id as string,\n metadata.langgraph_node as string,\n metadata.langgraph_step as number,\n metadata.langgraph_task_idx as number,\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 });\n }\n\n initializeModel(): Runnable {\n const ChatModelClass = getChatModelClass(this.provider);\n const model = new ChatModelClass(this.clientOptions);\n if (!this.tools || this.tools.length === 0) {\n return model;\n }\n return model.bindTools(this.tools as StructuredTool[]);\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 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 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 && (provider === Providers.ANTHROPIC || provider === Providers.BEDROCK)) {\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, Partial<t.BaseGraphState>, GraphNode> {\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, Partial<t.BaseGraphState>, GraphNode>({\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, 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 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 const runStep = this.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n if (!data.output) {\n return;\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","messages","Providers","AIMessageChunk","ToolMessage","sleep","stream","dispatchCustomEvent","GraphEvents","concat","modifyDeltaProperties","toolsCondition","StateGraph","START","StepTypes"],"mappings":";;;;;;;;;;;;;;AAAA;AAkBA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAGA,mBAAa,CAAC;MAcjB,KAAK,CAAA;AAuBzB,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;AAClC,CAAA;AAEK,MAAO,aAAc,SAAQ,KAGlC,CAAA;AACS,IAAA,UAAU,CAAyC;AACnD,IAAA,aAAa,CAA0B;AAC/C,IAAA,UAAU,CAAW;;AAErB,IAAA,cAAc,CAAqB;AACnC,IAAA,eAAe,CAA8B;AAC7C,IAAA,aAAa,CAA4B;IACzC,QAAQ,GAAkB,EAAE,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I,CAAC,MAAM,CAAC,CAAC;KAC9E;AACF;;;;;"}
|
package/dist/esm/events.mjs
CHANGED
|
@@ -36,7 +36,7 @@ class ToolEndHandler {
|
|
|
36
36
|
return;
|
|
37
37
|
}
|
|
38
38
|
this.callback?.(toolEndData);
|
|
39
|
-
graph.handleToolCallCompleted({ input: toolEndData.input, output: toolEndData.output });
|
|
39
|
+
graph.handleToolCallCompleted({ input: toolEndData.input, output: toolEndData.output }, metadata);
|
|
40
40
|
}
|
|
41
41
|
}
|
|
42
42
|
class TestLLMStreamHandler {
|
package/dist/esm/events.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.mjs","sources":["../../src/events.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/events.ts\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\n\nexport class HandlerRegistry {\n private handlers: Map<string, t.EventHandler> = new Map();\n\n register(eventType: string, handler: t.EventHandler): void {\n this.handlers.set(eventType, handler);\n }\n\n getHandler(eventType: string): t.EventHandler | undefined {\n return this.handlers.get(eventType);\n }\n}\n\nexport class ModelEndHandler implements t.EventHandler {\n handle(event: string, data: t.ModelEndData, 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 const usage = data?.output?.usage_metadata;\n\n console.log(`====== ${event.toUpperCase()} ======`);\n console.dir({\n usage,\n }, { depth: null });\n }\n}\n\nexport class ToolEndHandler implements t.EventHandler {\n private callback?: t.ToolEndCallback;\n constructor(callback?: t.ToolEndCallback) {\n this.callback = callback;\n }\n handle(event: string, data: t.StreamEventData | undefined, 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 const toolEndData = data as t.ToolEndData | undefined;\n if (!toolEndData?.output) {\n console.warn('No output found in tool_end event');\n return;\n }\n\n this.callback?.(toolEndData);\n\n graph.handleToolCallCompleted({ input: toolEndData.input, output: toolEndData.output });\n }\n}\n\nexport class TestLLMStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData | undefined): void {\n const chunk = data?.chunk;\n const isMessageChunk = !!(chunk && 'message' in chunk);\n const msg = isMessageChunk && chunk.message;\n if (msg && msg.tool_call_chunks && msg.tool_call_chunks.length > 0) {\n console.log(msg.tool_call_chunks);\n } else if (msg && msg.content) {\n if (typeof msg.content === 'string') {\n process.stdout.write(msg.content);\n }\n }\n }\n}\n\nexport class TestChatStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData | undefined): void {\n const chunk = data?.chunk;\n const isContentChunk = !!(chunk && 'content' in chunk);\n const content = isContentChunk && chunk.content;\n\n if (!content || !isContentChunk) {\n return;\n }\n\n if (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) {\n console.dir(chunk.tool_call_chunks, { depth: null });\n }\n\n if (typeof content === 'string') {\n process.stdout.write(content);\n } else {\n console.dir(content, { depth: null });\n }\n }\n}\n\nexport class LLMStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData | undefined, metadata?: Record<string, unknown>): void {\n const chunk = data?.chunk;\n const isMessageChunk = !!(chunk && 'message' in chunk);\n const msg = isMessageChunk && chunk.message;\n if (metadata) { console.log(metadata); }\n if (msg && msg.tool_call_chunks && msg.tool_call_chunks.length > 0) {\n console.log(msg.tool_call_chunks);\n } else if (msg && msg.content) {\n if (typeof msg.content === 'string') {\n // const text_delta = msg.content;\n // dispatchCustomEvent(GraphEvents.CHAT_MODEL_STREAM, { chunk }, config);\n process.stdout.write(msg.content);\n }\n }\n }\n}\n\nexport const createMetadataAggregator = (_collected?: Record<string, unknown>[]): t.MetadataAggregatorResult => {\n const collected = _collected || [];\n\n const handleLLMEnd: t.HandleLLMEnd = (output) => {\n const { generations } = output;\n const lastMessageOutput = (generations[generations.length - 1] as (t.StreamGeneration | undefined)[] | undefined)?.[0];\n if (!lastMessageOutput) {\n return;\n }\n const { message } = lastMessageOutput;\n if (message?.response_metadata) {\n collected.push(message.response_metadata);\n }\n };\n\n return { handleLLMEnd, collected };\n};"],"names":[],"mappings":"MAKa,eAAe,CAAA;AAClB,IAAA,QAAQ,GAAgC,IAAI,GAAG,EAAE,CAAC;IAE1D,QAAQ,CAAC,SAAiB,EAAE,OAAuB,EAAA;QACjD,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;KACvC;AAED,IAAA,UAAU,CAAC,SAAiB,EAAA;QAC1B,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;KACrC;AACF,CAAA;MAEY,eAAe,CAAA;AAC1B,IAAA,MAAM,CAAC,KAAa,EAAE,IAAoB,EAAE,QAAkC,EAAE,KAAa,EAAA;AAC3F,QAAA,IAAI,CAAC,KAAK,IAAI,CAAC,QAAQ,EAAE;AACvB,YAAA,OAAO,CAAC,IAAI,CAAC,kCAAkC,KAAK,CAAA,MAAA,CAAQ,CAAC,CAAC;YAC9D,OAAO;SACR;AAED,QAAA,MAAM,KAAK,GAAG,IAAI,EAAE,MAAM,EAAE,cAAc,CAAC;QAE3C,OAAO,CAAC,GAAG,CAAC,CAAU,OAAA,EAAA,KAAK,CAAC,WAAW,EAAE,CAAS,OAAA,CAAA,CAAC,CAAC;QACpD,OAAO,CAAC,GAAG,CAAC;YACV,KAAK;AACN,SAAA,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;KACrB;AACF,CAAA;MAEY,cAAc,CAAA;AACjB,IAAA,QAAQ,CAAqB;AACrC,IAAA,WAAA,CAAY,QAA4B,EAAA;AACtC,QAAA,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;KAC1B;AACD,IAAA,MAAM,CAAC,KAAa,EAAE,IAAmC,EAAE,QAAkC,EAAE,KAAa,EAAA;AAC1G,QAAA,IAAI,CAAC,KAAK,IAAI,CAAC,QAAQ,EAAE;AACvB,YAAA,OAAO,CAAC,IAAI,CAAC,kCAAkC,KAAK,CAAA,MAAA,CAAQ,CAAC,CAAC;YAC9D,OAAO;SACR;QAED,MAAM,WAAW,GAAG,IAAiC,CAAC;AACtD,QAAA,IAAI,CAAC,WAAW,EAAE,MAAM,EAAE;AACxB,YAAA,OAAO,CAAC,IAAI,CAAC,mCAAmC,CAAC,CAAC;YAClD,OAAO;SACR;AAED,QAAA,IAAI,CAAC,QAAQ,GAAG,WAAW,CAAC,CAAC;AAE7B,QAAA,KAAK,CAAC,uBAAuB,CAAC,EAAE,KAAK,EAAE,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,WAAW,CAAC,MAAM,EAAE,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"events.mjs","sources":["../../src/events.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/events.ts\nimport type { Graph } from '@/graphs';\nimport type * as t from '@/types';\n\nexport class HandlerRegistry {\n private handlers: Map<string, t.EventHandler> = new Map();\n\n register(eventType: string, handler: t.EventHandler): void {\n this.handlers.set(eventType, handler);\n }\n\n getHandler(eventType: string): t.EventHandler | undefined {\n return this.handlers.get(eventType);\n }\n}\n\nexport class ModelEndHandler implements t.EventHandler {\n handle(event: string, data: t.ModelEndData, 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 const usage = data?.output?.usage_metadata;\n\n console.log(`====== ${event.toUpperCase()} ======`);\n console.dir({\n usage,\n }, { depth: null });\n }\n}\n\nexport class ToolEndHandler implements t.EventHandler {\n private callback?: t.ToolEndCallback;\n constructor(callback?: t.ToolEndCallback) {\n this.callback = callback;\n }\n handle(event: string, data: t.StreamEventData | undefined, 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 const toolEndData = data as t.ToolEndData | undefined;\n if (!toolEndData?.output) {\n console.warn('No output found in tool_end event');\n return;\n }\n\n this.callback?.(toolEndData);\n\n graph.handleToolCallCompleted({ input: toolEndData.input, output: toolEndData.output }, metadata);\n }\n}\n\nexport class TestLLMStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData | undefined): void {\n const chunk = data?.chunk;\n const isMessageChunk = !!(chunk && 'message' in chunk);\n const msg = isMessageChunk && chunk.message;\n if (msg && msg.tool_call_chunks && msg.tool_call_chunks.length > 0) {\n console.log(msg.tool_call_chunks);\n } else if (msg && msg.content) {\n if (typeof msg.content === 'string') {\n process.stdout.write(msg.content);\n }\n }\n }\n}\n\nexport class TestChatStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData | undefined): void {\n const chunk = data?.chunk;\n const isContentChunk = !!(chunk && 'content' in chunk);\n const content = isContentChunk && chunk.content;\n\n if (!content || !isContentChunk) {\n return;\n }\n\n if (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) {\n console.dir(chunk.tool_call_chunks, { depth: null });\n }\n\n if (typeof content === 'string') {\n process.stdout.write(content);\n } else {\n console.dir(content, { depth: null });\n }\n }\n}\n\nexport class LLMStreamHandler implements t.EventHandler {\n handle(event: string, data: t.StreamEventData | undefined, metadata?: Record<string, unknown>): void {\n const chunk = data?.chunk;\n const isMessageChunk = !!(chunk && 'message' in chunk);\n const msg = isMessageChunk && chunk.message;\n if (metadata) { console.log(metadata); }\n if (msg && msg.tool_call_chunks && msg.tool_call_chunks.length > 0) {\n console.log(msg.tool_call_chunks);\n } else if (msg && msg.content) {\n if (typeof msg.content === 'string') {\n // const text_delta = msg.content;\n // dispatchCustomEvent(GraphEvents.CHAT_MODEL_STREAM, { chunk }, config);\n process.stdout.write(msg.content);\n }\n }\n }\n}\n\nexport const createMetadataAggregator = (_collected?: Record<string, unknown>[]): t.MetadataAggregatorResult => {\n const collected = _collected || [];\n\n const handleLLMEnd: t.HandleLLMEnd = (output) => {\n const { generations } = output;\n const lastMessageOutput = (generations[generations.length - 1] as (t.StreamGeneration | undefined)[] | undefined)?.[0];\n if (!lastMessageOutput) {\n return;\n }\n const { message } = lastMessageOutput;\n if (message?.response_metadata) {\n collected.push(message.response_metadata);\n }\n };\n\n return { handleLLMEnd, collected };\n};"],"names":[],"mappings":"MAKa,eAAe,CAAA;AAClB,IAAA,QAAQ,GAAgC,IAAI,GAAG,EAAE,CAAC;IAE1D,QAAQ,CAAC,SAAiB,EAAE,OAAuB,EAAA;QACjD,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;KACvC;AAED,IAAA,UAAU,CAAC,SAAiB,EAAA;QAC1B,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;KACrC;AACF,CAAA;MAEY,eAAe,CAAA;AAC1B,IAAA,MAAM,CAAC,KAAa,EAAE,IAAoB,EAAE,QAAkC,EAAE,KAAa,EAAA;AAC3F,QAAA,IAAI,CAAC,KAAK,IAAI,CAAC,QAAQ,EAAE;AACvB,YAAA,OAAO,CAAC,IAAI,CAAC,kCAAkC,KAAK,CAAA,MAAA,CAAQ,CAAC,CAAC;YAC9D,OAAO;SACR;AAED,QAAA,MAAM,KAAK,GAAG,IAAI,EAAE,MAAM,EAAE,cAAc,CAAC;QAE3C,OAAO,CAAC,GAAG,CAAC,CAAU,OAAA,EAAA,KAAK,CAAC,WAAW,EAAE,CAAS,OAAA,CAAA,CAAC,CAAC;QACpD,OAAO,CAAC,GAAG,CAAC;YACV,KAAK;AACN,SAAA,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;KACrB;AACF,CAAA;MAEY,cAAc,CAAA;AACjB,IAAA,QAAQ,CAAqB;AACrC,IAAA,WAAA,CAAY,QAA4B,EAAA;AACtC,QAAA,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;KAC1B;AACD,IAAA,MAAM,CAAC,KAAa,EAAE,IAAmC,EAAE,QAAkC,EAAE,KAAa,EAAA;AAC1G,QAAA,IAAI,CAAC,KAAK,IAAI,CAA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CAAC,CAAC;SACnC;AAAM,aAAA,IAAI,GAAG,IAAI,GAAG,CAAC,OAAO,EAAE;AAC7B,YAAA,IAAI,OAAO,GAAG,CAAC,OAAO,KAAK,QAAQ,EAAE;;;gBAGnC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;aACnC;SACF;KACF;AACF,CAAA;AAEY,MAAA,wBAAwB,GAAG,CAAC,UAAsC,KAAgC;AAC7G,IAAA,MAAM,SAAS,GAAG,UAAU,IAAI,EAAE,CAAC;AAEnC,IAAA,MAAM,YAAY,GAAmB,CAAC,MAAM,KAAI;AAC9C,QAAA,MAAM,EAAE,WAAW,EAAE,GAAG,MAAM,CAAC;AAC/B,QAAA,MAAM,iBAAiB,GAAI,WAAW,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC,CAAoD,GAAG,CAAC,CAAC,CAAC;QACvH,IAAI,CAAC,iBAAiB,EAAE;YACtB,OAAO;SACR;AACD,QAAA,MAAM,EAAE,OAAO,EAAE,GAAG,iBAAiB,CAAC;AACtC,QAAA,IAAI,OAAO,EAAE,iBAAiB,EAAE;AAC9B,YAAA,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC;SAC3C;AACH,KAAC,CAAC;AAEF,IAAA,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,CAAC;AACrC;;;;"}
|
|
@@ -171,7 +171,7 @@ class StandardGraph extends Graph {
|
|
|
171
171
|
}
|
|
172
172
|
createCallModel() {
|
|
173
173
|
return async (state, config) => {
|
|
174
|
-
const { provider } = config?.configurable ?? {};
|
|
174
|
+
const { provider = '' } = config?.configurable ?? {};
|
|
175
175
|
if (!config || !provider) {
|
|
176
176
|
throw new Error(`No ${config ? 'provider' : 'config'} provided`);
|
|
177
177
|
}
|
|
@@ -194,7 +194,7 @@ class StandardGraph extends Graph {
|
|
|
194
194
|
}
|
|
195
195
|
}
|
|
196
196
|
this.lastStreamCall = Date.now();
|
|
197
|
-
if (this.tools?.length && (provider === Providers.ANTHROPIC || provider === Providers.BEDROCK)) {
|
|
197
|
+
if ((this.tools?.length ?? 0) > 0 && (provider === Providers.ANTHROPIC || provider === Providers.BEDROCK)) {
|
|
198
198
|
const stream = await this.boundModel.stream(finalMessages, config);
|
|
199
199
|
let finalChunk;
|
|
200
200
|
for await (const chunk of stream) {
|
|
@@ -244,10 +244,11 @@ class StandardGraph extends Graph {
|
|
|
244
244
|
const [stepId, stepIndex] = this.generateStepId(stepKey);
|
|
245
245
|
if (stepDetails.type === StepTypes.TOOL_CALLS && stepDetails.tool_calls) {
|
|
246
246
|
for (const tool_call of stepDetails.tool_calls) {
|
|
247
|
-
|
|
247
|
+
const toolCallId = tool_call.id ?? '';
|
|
248
|
+
if (!toolCallId || this.toolCallStepIds.has(toolCallId)) {
|
|
248
249
|
continue;
|
|
249
250
|
}
|
|
250
|
-
this.toolCallStepIds.set(
|
|
251
|
+
this.toolCallStepIds.set(toolCallId, stepId);
|
|
251
252
|
}
|
|
252
253
|
}
|
|
253
254
|
const runStep = {
|
|
@@ -258,8 +259,9 @@ class StandardGraph extends Graph {
|
|
|
258
259
|
stepDetails,
|
|
259
260
|
usage: null,
|
|
260
261
|
};
|
|
261
|
-
|
|
262
|
-
|
|
262
|
+
const runId = this.runId ?? '';
|
|
263
|
+
if (runId) {
|
|
264
|
+
runStep.runId = runId;
|
|
263
265
|
}
|
|
264
266
|
this.contentData.push(runStep);
|
|
265
267
|
this.contentIndexMap.set(stepId, runStep.index);
|
|
@@ -272,7 +274,7 @@ class StandardGraph extends Graph {
|
|
|
272
274
|
}
|
|
273
275
|
const { input, output } = data;
|
|
274
276
|
const { tool_call_id } = output;
|
|
275
|
-
const stepId = this.toolCallStepIds.get(tool_call_id);
|
|
277
|
+
const stepId = this.toolCallStepIds.get(tool_call_id) ?? '';
|
|
276
278
|
if (!stepId) {
|
|
277
279
|
throw new Error(`No stepId found for tool_call_id ${tool_call_id}`);
|
|
278
280
|
}
|
|
@@ -281,8 +283,6 @@ class StandardGraph extends Graph {
|
|
|
281
283
|
throw new Error(`No run step found for stepId ${stepId}`);
|
|
282
284
|
}
|
|
283
285
|
if (!data.output) {
|
|
284
|
-
// console.warn('No output found in tool_end event');
|
|
285
|
-
// console.dir(data, { depth: null });
|
|
286
286
|
return;
|
|
287
287
|
}
|
|
288
288
|
const args = typeof input === 'string' ? input : input.input;
|
|
@@ -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 { START, StateGraph } from '@langchain/langgraph';\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 { StructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { Providers, GraphEvents, GraphNodeKeys, StepTypes, Callback } from '@/common';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport { modifyDeltaProperties, convertMessagesToContent } from '@/messages';\nimport { resetIfNotEmpty, joinKeys, sleep } from '@/utils';\nimport { getChatModelClass } from '@/llm/providers';\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 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): void;\n\n abstract createCallModel(): (state: T, config?: RunnableConfig) => Promise<Partial<T>>;\n abstract createWorkflow(): t.CompiledWorkflow<T, Partial<T>, TNodeName>;\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}\n\nexport class StandardGraph extends Graph<\n t.BaseGraphState,\n GraphNode\n> {\n private graphState: t.GraphStateChannels<t.BaseGraphState>;\n private clientOptions: Record<string, unknown>;\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\n constructor({\n runId,\n tools,\n toolMap,\n provider,\n clientOptions,\n instructions,\n additional_instructions = '',\n streamBuffer,\n } : {\n runId?: string;\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 }) {\n super();\n this.runId = runId;\n this.tools = tools;\n this.toolMap = toolMap;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.streamBuffer = streamBuffer;\n this.graphState = this.createGraphState();\n this.boundModel = this.initializeModel();\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(): void {\n this.messages = [];\n this.config = resetIfNotEmpty(this.config, undefined);\n this.contentData = resetIfNotEmpty(this.contentData, []);\n this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n this.toolCallStepIds = resetIfNotEmpty(this.toolCallStepIds, new Map());\n this.contentIndexMap = resetIfNotEmpty(this.contentIndexMap, 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.thread_id as string,\n metadata.langgraph_node as string,\n metadata.langgraph_step as number,\n metadata.langgraph_task_idx as number,\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 });\n }\n\n initializeModel(): Runnable {\n const ChatModelClass = getChatModelClass(this.provider);\n const model = new ChatModelClass(this.clientOptions);\n if (!this.tools || this.tools.length === 0) {\n return model;\n }\n return model.bindTools(this.tools as StructuredTool[]);\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 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 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 && (provider === Providers.ANTHROPIC || provider === Providers.BEDROCK)) {\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, Partial<t.BaseGraphState>, GraphNode> {\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, Partial<t.BaseGraphState>, GraphNode>({\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, 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 if (!tool_call.id || this.toolCallStepIds.has(tool_call.id)) {\n continue;\n }\n this.toolCallStepIds.set(tool_call.id, 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 if (this.runId) {\n runStep.runId = this.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 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 const runStep = this.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n if (!data.output) {\n // console.warn('No output found in tool_end event');\n // console.dir(data, { depth: null });\n return;\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;AAkBA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,aAAa,CAAC;MAcjB,KAAK,CAAA;AAuBzB,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,GA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,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 { START, StateGraph } from '@langchain/langgraph';\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 { StructuredTool } from '@langchain/core/tools';\nimport type * as t from '@/types';\nimport { Providers, GraphEvents, GraphNodeKeys, StepTypes, Callback } from '@/common';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport { modifyDeltaProperties, convertMessagesToContent } from '@/messages';\nimport { resetIfNotEmpty, joinKeys, sleep } from '@/utils';\nimport { getChatModelClass } from '@/llm/providers';\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 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, Partial<T>, TNodeName>;\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}\n\nexport class StandardGraph extends Graph<\n t.BaseGraphState,\n GraphNode\n> {\n private graphState: t.GraphStateChannels<t.BaseGraphState>;\n private clientOptions: Record<string, unknown>;\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\n constructor({\n runId,\n tools,\n toolMap,\n provider,\n clientOptions,\n instructions,\n additional_instructions = '',\n streamBuffer,\n } : {\n runId?: string;\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 }) {\n super();\n this.runId = runId;\n this.tools = tools;\n this.toolMap = toolMap;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.streamBuffer = streamBuffer;\n this.graphState = this.createGraphState();\n this.boundModel = this.initializeModel();\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(): void {\n this.messages = [];\n this.config = resetIfNotEmpty(this.config, undefined);\n this.contentData = resetIfNotEmpty(this.contentData, []);\n this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n this.toolCallStepIds = resetIfNotEmpty(this.toolCallStepIds, new Map());\n this.contentIndexMap = resetIfNotEmpty(this.contentIndexMap, 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.thread_id as string,\n metadata.langgraph_node as string,\n metadata.langgraph_step as number,\n metadata.langgraph_task_idx as number,\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 });\n }\n\n initializeModel(): Runnable {\n const ChatModelClass = getChatModelClass(this.provider);\n const model = new ChatModelClass(this.clientOptions);\n if (!this.tools || this.tools.length === 0) {\n return model;\n }\n return model.bindTools(this.tools as StructuredTool[]);\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 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 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 && (provider === Providers.ANTHROPIC || provider === Providers.BEDROCK)) {\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, Partial<t.BaseGraphState>, GraphNode> {\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, Partial<t.BaseGraphState>, GraphNode>({\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, 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 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 const runStep = this.getRunStep(stepId);\n if (!runStep) {\n throw new Error(`No run step found for stepId ${stepId}`);\n }\n\n if (!data.output) {\n return;\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;AAkBA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,aAAa,CAAC;MAcjB,KAAK,CAAA;AAuBzB,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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AAE,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;;;;"}
|
|
@@ -33,7 +33,7 @@ export declare abstract class Graph<T extends t.BaseGraphState = t.BaseGraphStat
|
|
|
33
33
|
abstract dispatchRunStep(stepKey: string, stepDetails: t.StepDetails): string;
|
|
34
34
|
abstract dispatchRunStepDelta(id: string, delta: t.ToolCallDelta): void;
|
|
35
35
|
abstract dispatchMessageDelta(id: string, delta: t.MessageDelta): void;
|
|
36
|
-
abstract handleToolCallCompleted(data: t.ToolEndData): void;
|
|
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, Partial<T>, TNodeName>;
|
|
39
39
|
messageIdsByStepKey: Map<string, string>;
|
package/package.json
CHANGED
package/src/events.ts
CHANGED
|
@@ -50,7 +50,7 @@ export class ToolEndHandler implements t.EventHandler {
|
|
|
50
50
|
|
|
51
51
|
this.callback?.(toolEndData);
|
|
52
52
|
|
|
53
|
-
graph.handleToolCallCompleted({ input: toolEndData.input, output: toolEndData.output });
|
|
53
|
+
graph.handleToolCallCompleted({ input: toolEndData.input, output: toolEndData.output }, metadata);
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
56
|
|
package/src/graphs/Graph.ts
CHANGED
|
@@ -49,7 +49,7 @@ export abstract class Graph<
|
|
|
49
49
|
abstract dispatchRunStep(stepKey: string, stepDetails: t.StepDetails): string;
|
|
50
50
|
abstract dispatchRunStepDelta(id: string, delta: t.ToolCallDelta): void;
|
|
51
51
|
abstract dispatchMessageDelta(id: string, delta: t.MessageDelta): void;
|
|
52
|
-
abstract handleToolCallCompleted(data: t.ToolEndData): void;
|
|
52
|
+
abstract handleToolCallCompleted(data: t.ToolEndData, metadata?: Record<string, unknown>): void;
|
|
53
53
|
|
|
54
54
|
abstract createCallModel(): (state: T, config?: RunnableConfig) => Promise<Partial<T>>;
|
|
55
55
|
abstract createWorkflow(): t.CompiledWorkflow<T, Partial<T>, TNodeName>;
|
|
@@ -266,7 +266,7 @@ export class StandardGraph extends Graph<
|
|
|
266
266
|
|
|
267
267
|
createCallModel() {
|
|
268
268
|
return async (state: t.BaseGraphState, config?: RunnableConfig): Promise<Partial<t.BaseGraphState>> => {
|
|
269
|
-
const { provider } = (config?.configurable as t.GraphConfig | undefined) ?? {} ;
|
|
269
|
+
const { provider = '' } = (config?.configurable as t.GraphConfig | undefined) ?? {} ;
|
|
270
270
|
if (!config || !provider) {
|
|
271
271
|
throw new Error(`No ${config ? 'provider' : 'config'} provided`);
|
|
272
272
|
}
|
|
@@ -296,7 +296,7 @@ export class StandardGraph extends Graph<
|
|
|
296
296
|
|
|
297
297
|
this.lastStreamCall = Date.now();
|
|
298
298
|
|
|
299
|
-
if (this.tools?.length && (provider === Providers.ANTHROPIC || provider === Providers.BEDROCK)) {
|
|
299
|
+
if ((this.tools?.length ?? 0) > 0 && (provider === Providers.ANTHROPIC || provider === Providers.BEDROCK)) {
|
|
300
300
|
const stream = await this.boundModel.stream(finalMessages, config);
|
|
301
301
|
let finalChunk: AIMessageChunk | undefined;
|
|
302
302
|
for await (const chunk of stream) {
|
|
@@ -353,10 +353,11 @@ export class StandardGraph extends Graph<
|
|
|
353
353
|
const [stepId, stepIndex] = this.generateStepId(stepKey);
|
|
354
354
|
if (stepDetails.type === StepTypes.TOOL_CALLS && stepDetails.tool_calls) {
|
|
355
355
|
for (const tool_call of stepDetails.tool_calls) {
|
|
356
|
-
|
|
356
|
+
const toolCallId = tool_call.id ?? '';
|
|
357
|
+
if (!toolCallId || this.toolCallStepIds.has(toolCallId)) {
|
|
357
358
|
continue;
|
|
358
359
|
}
|
|
359
|
-
this.toolCallStepIds.set(
|
|
360
|
+
this.toolCallStepIds.set(toolCallId, stepId);
|
|
360
361
|
}
|
|
361
362
|
}
|
|
362
363
|
|
|
@@ -369,8 +370,9 @@ export class StandardGraph extends Graph<
|
|
|
369
370
|
usage: null,
|
|
370
371
|
};
|
|
371
372
|
|
|
372
|
-
|
|
373
|
-
|
|
373
|
+
const runId = this.runId ?? '';
|
|
374
|
+
if (runId) {
|
|
375
|
+
runStep.runId = runId;
|
|
374
376
|
}
|
|
375
377
|
|
|
376
378
|
this.contentData.push(runStep);
|
|
@@ -386,7 +388,7 @@ export class StandardGraph extends Graph<
|
|
|
386
388
|
|
|
387
389
|
const { input, output } = data;
|
|
388
390
|
const { tool_call_id } = output;
|
|
389
|
-
const stepId = this.toolCallStepIds.get(tool_call_id);
|
|
391
|
+
const stepId = this.toolCallStepIds.get(tool_call_id) ?? '';
|
|
390
392
|
if (!stepId) {
|
|
391
393
|
throw new Error(`No stepId found for tool_call_id ${tool_call_id}`);
|
|
392
394
|
}
|
|
@@ -396,8 +398,6 @@ export class StandardGraph extends Graph<
|
|
|
396
398
|
}
|
|
397
399
|
|
|
398
400
|
if (!data.output) {
|
|
399
|
-
// console.warn('No output found in tool_end event');
|
|
400
|
-
// console.dir(data, { depth: null });
|
|
401
401
|
return;
|
|
402
402
|
}
|
|
403
403
|
|