langchain 1.0.0-alpha.1 → 1.0.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/agents/ReactAgent.cjs +1 -1
  2. package/dist/agents/ReactAgent.cjs.map +1 -1
  3. package/dist/agents/ReactAgent.d.cts.map +1 -1
  4. package/dist/agents/ReactAgent.d.ts.map +1 -1
  5. package/dist/agents/ReactAgent.js +2 -2
  6. package/dist/agents/ReactAgent.js.map +1 -1
  7. package/dist/agents/annotation.cjs +120 -0
  8. package/dist/agents/annotation.cjs.map +1 -1
  9. package/dist/agents/annotation.d.cts +15 -11
  10. package/dist/agents/annotation.d.cts.map +1 -1
  11. package/dist/agents/annotation.d.ts +15 -11
  12. package/dist/agents/annotation.d.ts.map +1 -1
  13. package/dist/agents/annotation.js +120 -1
  14. package/dist/agents/annotation.js.map +1 -1
  15. package/dist/agents/index.d.cts +1 -1
  16. package/dist/agents/index.d.ts +1 -1
  17. package/dist/agents/nodes/AgentNode.cjs +8 -3
  18. package/dist/agents/nodes/AgentNode.cjs.map +1 -1
  19. package/dist/agents/nodes/AgentNode.js +8 -3
  20. package/dist/agents/nodes/AgentNode.js.map +1 -1
  21. package/dist/agents/nodes/ToolNode.cjs +1 -1
  22. package/dist/agents/nodes/ToolNode.cjs.map +1 -1
  23. package/dist/agents/nodes/ToolNode.js +1 -1
  24. package/dist/agents/nodes/ToolNode.js.map +1 -1
  25. package/dist/agents/responses.cjs +1 -2
  26. package/dist/agents/responses.cjs.map +1 -1
  27. package/dist/agents/responses.d.cts +5 -0
  28. package/dist/agents/responses.d.cts.map +1 -1
  29. package/dist/agents/responses.d.ts +5 -0
  30. package/dist/agents/responses.d.ts.map +1 -1
  31. package/dist/agents/responses.js +1 -2
  32. package/dist/agents/responses.js.map +1 -1
  33. package/dist/agents/types.d.cts +21 -3
  34. package/dist/agents/types.d.cts.map +1 -1
  35. package/dist/agents/types.d.ts +21 -3
  36. package/dist/agents/types.d.ts.map +1 -1
  37. package/dist/evaluation/comparison/pairwise.d.ts.map +1 -1
  38. package/dist/evaluation/criteria/criteria.d.ts.map +1 -1
  39. package/dist/hub/base.cjs.map +1 -1
  40. package/dist/hub/base.js.map +1 -1
  41. package/dist/index.cjs +50 -1
  42. package/dist/index.cjs.map +1 -1
  43. package/dist/index.d.cts +3 -3
  44. package/dist/index.d.ts +3 -3
  45. package/dist/index.js +10 -3
  46. package/dist/index.js.map +1 -1
  47. package/package.json +26 -25
@@ -32,7 +32,7 @@ var ReactAgent = class {
32
32
  * our graph needs to check if these were called
33
33
  */
34
34
  const shouldReturnDirect = new Set(toolClasses.filter(require_utils.isClientTool).filter((tool) => "returnDirect" in tool && tool.returnDirect).map((tool) => tool.name));
35
- const schema = this.options.stateSchema ?? require_annotation.createReactAgentAnnotationConditional(this.options.responseFormat !== void 0);
35
+ const schema = this.options.stateSchema ? require_annotation.enhanceStateSchemaWithMessageReducer(this.options.stateSchema) : require_annotation.createReactAgentAnnotationConditional(this.options.responseFormat !== void 0);
36
36
  const workflow = new __langchain_langgraph.StateGraph(schema, this.options.contextSchema);
37
37
  const allNodeWorkflows = workflow;
38
38
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"ReactAgent.cjs","names":["options: CreateReactAgentParams<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >","#toolBehaviorVersion","validateLLMHasNoBoundTools","isClientTool","createReactAgentAnnotationConditional","StateGraph","AgentNode","#inputSchema","ToolNode","START","#getEntryPoint","#getPostModelHookPaths","#createPostModelHookRouter","#getModelPaths","#createModelRouter","#createToolsRouter","END","#graph","toolClasses: (ClientTool | ServerTool)[]","paths: (typeof END | \"agent\" | \"pre_model_hook\" | \"tools\")[]","state: InternalAgentState<StructuredResponseFormat>","isToolMessage","isAIMessage","Send","ToolMessage","paths: (\"tools\" | typeof END)[]","AIMessage","shouldReturnDirect: Set<string>","params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }"],"sources":["../../src/agents/ReactAgent.ts"],"sourcesContent":["/* eslint-disable prefer-destructuring, no-instanceof/no-instanceof */\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\nimport {\n AnnotationRoot,\n StateGraph,\n END,\n START,\n Send,\n CompiledStateGraph,\n MessagesAnnotation,\n} from \"@langchain/langgraph\";\nimport {\n isToolMessage,\n isAIMessage,\n ToolMessage,\n AIMessage,\n} from \"@langchain/core/messages\";\n\nimport {\n createReactAgentAnnotationConditional,\n ReactAgentAnnotation,\n} from \"./annotation.js\";\nimport { isClientTool, validateLLMHasNoBoundTools } from \"./utils.js\";\nimport { AgentNode } from \"./nodes/AgentNode.js\";\nimport { ToolNode } from \"./nodes/ToolNode.js\";\nimport type {\n CreateReactAgentParams,\n ClientTool,\n ServerTool,\n InternalAgentState,\n WithStateGraphNodes,\n} from \"./types.js\";\nimport type { AnyAnnotationRoot, ToAnnotationRoot } from \"./annotation.js\";\nimport type { ResponseFormatUndefined } from \"./responses.js\";\n\ntype AgentGraph<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> = CompiledStateGraph<\n ToAnnotationRoot<StateSchema>[\"State\"],\n ToAnnotationRoot<StateSchema>[\"Update\"],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n typeof MessagesAnnotation.spec & ToAnnotationRoot<StateSchema>[\"spec\"],\n ReactAgentAnnotation<StructuredResponseFormat>[\"spec\"] &\n ToAnnotationRoot<StateSchema>[\"spec\"],\n ToAnnotationRoot<ContextSchema>[\"spec\"],\n unknown\n>;\n\nexport class ReactAgent<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> {\n #graph: AgentGraph<StateSchema, StructuredResponseFormat, ContextSchema>;\n\n #inputSchema?: AnnotationRoot<ToAnnotationRoot<StateSchema>[\"spec\"]>;\n\n #toolBehaviorVersion: \"v1\" | \"v2\" = \"v2\";\n\n constructor(\n public options: CreateReactAgentParams<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >\n ) {\n this.#toolBehaviorVersion = options.version ?? this.#toolBehaviorVersion;\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n if (options.llm && typeof options.llm !== \"function\") {\n validateLLMHasNoBoundTools(options.llm);\n }\n\n /**\n * validate that model and llm options are not provided together\n */\n if (options.llm && options.model) {\n throw new Error(\"Cannot provide both `model` and `llm` options.\");\n }\n\n /**\n * validate that either model or llm option is provided\n */\n if (!options.llm && !options.model) {\n throw new Error(\n \"Either `model` or `llm` option must be provided to create an agent.\"\n );\n }\n\n const toolClasses = Array.isArray(options.tools)\n ? options.tools\n : options.tools.tools;\n\n /**\n * If any of the tools are configured to return_directly after running,\n * our graph needs to check if these were called\n */\n const shouldReturnDirect = new Set(\n toolClasses\n .filter(isClientTool)\n .filter((tool) => \"returnDirect\" in tool && tool.returnDirect)\n .map((tool) => tool.name)\n );\n\n const schema = (this.options.stateSchema ??\n createReactAgentAnnotationConditional<StructuredResponseFormat>(\n this.options.responseFormat !== undefined\n )) as AnyAnnotationRoot;\n\n const workflow = new StateGraph(schema, this.options.contextSchema);\n\n const allNodeWorkflows = workflow as WithStateGraphNodes<\n \"pre_model_hook\" | \"post_model_hook\" | \"tools\" | \"agent\",\n typeof workflow\n >;\n\n /**\n * Add Nodes\n */\n allNodeWorkflows.addNode(\n \"agent\",\n new AgentNode({\n llm: this.options.llm,\n model: this.options.model,\n prompt: this.options.prompt,\n includeAgentName: this.options.includeAgentName,\n name: this.options.name,\n responseFormat: this.options.responseFormat,\n toolClasses,\n shouldReturnDirect,\n signal: this.options.signal,\n }),\n {\n input: this.#inputSchema,\n }\n );\n\n /**\n * add single tool node for all tools\n */\n if (toolClasses.length > 0) {\n const toolNode = new ToolNode(toolClasses.filter(isClientTool), {\n signal: this.options.signal,\n });\n allNodeWorkflows.addNode(\"tools\", toolNode);\n }\n\n /**\n * setup preModelHook\n */\n if (options.preModelHook) {\n allNodeWorkflows.addNode(\"pre_model_hook\", options.preModelHook);\n }\n\n /**\n * setup postModelHook\n */\n if (options.postModelHook) {\n allNodeWorkflows.addNode(\"post_model_hook\", options.postModelHook);\n }\n\n /**\n * Add Edges\n */\n allNodeWorkflows.addEdge(START, this.#getEntryPoint());\n\n if (this.options.preModelHook) {\n allNodeWorkflows.addEdge(\"pre_model_hook\", \"agent\");\n }\n\n if (this.options.postModelHook) {\n allNodeWorkflows.addEdge(\"agent\", \"post_model_hook\");\n const postHookPaths = this.#getPostModelHookPaths(\n toolClasses.filter(isClientTool)\n );\n if (postHookPaths.length === 1) {\n allNodeWorkflows.addEdge(\"post_model_hook\", postHookPaths[0]);\n } else {\n allNodeWorkflows.addConditionalEdges(\n \"post_model_hook\",\n this.#createPostModelHookRouter(),\n postHookPaths\n );\n }\n } else {\n const modelPaths = this.#getModelPaths(toolClasses.filter(isClientTool));\n if (modelPaths.length === 1) {\n allNodeWorkflows.addEdge(\"agent\", modelPaths[0]);\n } else {\n allNodeWorkflows.addConditionalEdges(\n \"agent\",\n this.#createModelRouter(),\n modelPaths\n );\n }\n }\n\n /**\n * add edges for tools node\n */\n if (toolClasses.length > 0) {\n if (shouldReturnDirect.size > 0) {\n allNodeWorkflows.addConditionalEdges(\n \"tools\",\n this.#createToolsRouter(shouldReturnDirect),\n [this.#getEntryPoint(), END]\n );\n } else {\n allNodeWorkflows.addEdge(\"tools\", this.#getEntryPoint());\n }\n }\n\n /**\n * compile the graph\n */\n this.#graph = allNodeWorkflows.compile({\n checkpointer: this.options.checkpointer ?? this.options.checkpointSaver,\n interruptBefore: this.options.interruptBefore,\n interruptAfter: this.options.interruptAfter,\n store: this.options.store,\n name: this.options.name,\n description: this.options.description,\n });\n }\n\n /**\n * Get the compiled graph.\n */\n get graph(): AgentGraph<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n > {\n return this.#graph;\n }\n\n #getEntryPoint() {\n const entryPoint = this.options.preModelHook ? \"pre_model_hook\" : \"agent\";\n return entryPoint;\n }\n\n /**\n * Get possible edge destinations from post_model_hook node.\n */\n #getPostModelHookPaths(toolClasses: (ClientTool | ServerTool)[]) {\n const paths: (typeof END | \"agent\" | \"pre_model_hook\" | \"tools\")[] = [];\n if (toolClasses.length > 0) {\n paths.push(this.#getEntryPoint(), \"tools\");\n }\n paths.push(END);\n return paths;\n }\n\n #createPostModelHookRouter() {\n return (state: InternalAgentState<StructuredResponseFormat>) => {\n const messages = state.messages;\n const toolMessages = messages.filter(isToolMessage);\n const lastAiMessage = messages.filter(isAIMessage).at(-1);\n const pendingToolCalls = lastAiMessage?.tool_calls?.filter(\n (call) => !toolMessages.some((m) => m.tool_call_id === call.id)\n );\n\n if (pendingToolCalls && pendingToolCalls.length > 0) {\n /**\n * The tool node processes a single message.\n * All tool calls in the message are executed in parallel within the tool node.\n * @deprecated likely to be removed in the next version of the agent\n */\n if (this.#toolBehaviorVersion === \"v1\") {\n return \"tools\";\n }\n\n /**\n * The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n */\n return pendingToolCalls.map(\n (toolCall) => new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n }\n\n if (messages.at(-1) instanceof ToolMessage) {\n return this.#getEntryPoint();\n }\n\n return END;\n };\n }\n\n /**\n * Get possible edge destinations from model node.\n * @param toolClasses names of tools to call\n * @returns list of possible edge destinations\n */\n #getModelPaths(\n toolClasses: (ClientTool | ServerTool)[]\n ): (\"tools\" | typeof END)[] {\n const paths: (\"tools\" | typeof END)[] = [];\n if (toolClasses.length > 0) {\n paths.push(\"tools\");\n }\n\n paths.push(END);\n\n return paths;\n }\n\n /**\n * Create routing function for model node conditional edges.\n */\n #createModelRouter() {\n /**\n * determine if the agent should continue or not\n */\n return (state: InternalAgentState<StructuredResponseFormat>) => {\n const messages = state.messages;\n const lastMessage = messages.at(-1);\n\n if (\n !(lastMessage instanceof AIMessage) ||\n !lastMessage.tool_calls ||\n lastMessage.tool_calls.length === 0\n ) {\n if (this.options.postModelHook) {\n return \"post_model_hook\";\n }\n\n return END;\n }\n\n if (this.options.postModelHook) {\n return \"post_model_hook\";\n }\n\n /**\n * The tool node processes a single message.\n */\n if (this.#toolBehaviorVersion === \"v1\") {\n return \"tools\";\n }\n\n /**\n * Route to tools node\n */\n return lastMessage.tool_calls.map(\n (toolCall) => new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n };\n }\n\n /**\n * Create routing function for tools node conditional edges.\n */\n #createToolsRouter(shouldReturnDirect: Set<string>) {\n return (state: InternalAgentState<StructuredResponseFormat>) => {\n const messages = state.messages;\n const lastMessage = messages[messages.length - 1];\n\n // Check if we just executed a returnDirect tool\n if (\n lastMessage instanceof ToolMessage &&\n lastMessage.name &&\n shouldReturnDirect.has(lastMessage.name)\n ) {\n // If we have a response format, route to agent to generate structured response\n // Otherwise, return directly\n return this.options.responseFormat ? this.#getEntryPoint() : END;\n }\n\n // For non-returnDirect tools, always route back to agent\n return this.#getEntryPoint();\n };\n }\n\n /**\n * @inheritdoc\n */\n get invoke(): AgentGraph<StateSchema, StructuredResponseFormat>[\"invoke\"] {\n return this.#graph.invoke.bind(this.#graph);\n }\n\n /**\n * @inheritdoc\n */\n get stream(): AgentGraph<StateSchema, StructuredResponseFormat>[\"stream\"] {\n return this.#graph.stream.bind(this.#graph);\n }\n\n /**\n * @inheritdoc\n */\n get streamEvents(): AgentGraph<\n StateSchema,\n StructuredResponseFormat\n >[\"streamEvents\"] {\n return this.#graph.streamEvents.bind(this.#graph);\n }\n\n /**\n * Visualize the graph as a PNG image.\n * @param params - Parameters for the drawMermaidPng method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns PNG image as a buffer\n */\n async drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n const image = await representation.drawMermaidPng(params);\n const arrayBuffer = await image.arrayBuffer();\n const buffer = new Uint8Array(arrayBuffer);\n return buffer;\n }\n\n /**\n * Draw the graph as a Mermaid string.\n * @param params - Parameters for the drawMermaid method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns Mermaid string\n */\n async drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n return representation.drawMermaid(params);\n }\n}\n"],"mappings":";;;;;;;;;AAqDA,IAAa,aAAb,MAME;CACA;CAEA;CAEA,uBAAoC;CAEpC,YACSA,SAKP;EALO;EAMP,KAAKC,uBAAuB,QAAQ,WAAW,KAAKA;;;;AAKpD,MAAI,QAAQ,OAAO,OAAO,QAAQ,QAAQ,YACxCC,yCAA2B,QAAQ,IAAI;;;;AAMzC,MAAI,QAAQ,OAAO,QAAQ,MACzB,OAAM,IAAI,MAAM;;;;AAMlB,MAAI,CAAC,QAAQ,OAAO,CAAC,QAAQ,MAC3B,OAAM,IAAI,MACR;EAIJ,MAAM,cAAc,MAAM,QAAQ,QAAQ,MAAM,GAC5C,QAAQ,QACR,QAAQ,MAAM;;;;;EAMlB,MAAM,qBAAqB,IAAI,IAC7B,YACG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5C;;;;CAKD,IAAI,eAGc;AAChB,SAAO,KAAKA,OAAO,aAAa,KAAK,KAAKA,OAAO;CAClD;;;;;;;;;;;CAYD,MAAM,eAAeW,QAMlB;EACD,MAAM,iBAAiB,MAAM,KAAKX,OAAO,eAAe;EACxD,MAAM,QAAQ,MAAM,eAAe,eAAe,OAAO;EACzD,MAAM,cAAc,MAAM,MAAM,aAAa;EAC7C,MAAM,SAAS,IAAI,WAAW;AAC9B,SAAO;CACR;;;;;;;;;;;CAYD,MAAM,YAAYW,QAMf;EACD,MAAM,iBAAiB,MAAM,KAAKX,OAAO,eAAe;AACxD,SAAO,eAAe,YAAY,OAAO;CAC1C;AACF"}
1
+ {"version":3,"file":"ReactAgent.cjs","names":["options: CreateReactAgentParams<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >","#toolBehaviorVersion","validateLLMHasNoBoundTools","isClientTool","enhanceStateSchemaWithMessageReducer","createReactAgentAnnotationConditional","StateGraph","AgentNode","#inputSchema","ToolNode","START","#getEntryPoint","#getPostModelHookPaths","#createPostModelHookRouter","#getModelPaths","#createModelRouter","#createToolsRouter","END","#graph","toolClasses: (ClientTool | ServerTool)[]","paths: (typeof END | \"agent\" | \"pre_model_hook\" | \"tools\")[]","state: InternalAgentState<StructuredResponseFormat>","isToolMessage","isAIMessage","Send","ToolMessage","paths: (\"tools\" | typeof END)[]","AIMessage","shouldReturnDirect: Set<string>","params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }"],"sources":["../../src/agents/ReactAgent.ts"],"sourcesContent":["/* eslint-disable prefer-destructuring, no-instanceof/no-instanceof */\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\nimport {\n AnnotationRoot,\n StateGraph,\n END,\n START,\n Send,\n CompiledStateGraph,\n MessagesAnnotation,\n} from \"@langchain/langgraph\";\nimport {\n isToolMessage,\n isAIMessage,\n ToolMessage,\n AIMessage,\n} from \"@langchain/core/messages\";\n\nimport {\n createReactAgentAnnotationConditional,\n ReactAgentAnnotation,\n} from \"./annotation.js\";\nimport { isClientTool, validateLLMHasNoBoundTools } from \"./utils.js\";\nimport { AgentNode } from \"./nodes/AgentNode.js\";\nimport { ToolNode } from \"./nodes/ToolNode.js\";\nimport type {\n CreateReactAgentParams,\n ClientTool,\n ServerTool,\n InternalAgentState,\n WithStateGraphNodes,\n} from \"./types.js\";\nimport {\n enhanceStateSchemaWithMessageReducer,\n type AnyAnnotationRoot,\n type ToAnnotationRoot,\n} from \"./annotation.js\";\nimport type { ResponseFormatUndefined } from \"./responses.js\";\n\ntype AgentGraph<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> = CompiledStateGraph<\n ToAnnotationRoot<StateSchema>[\"State\"],\n ToAnnotationRoot<StateSchema>[\"Update\"],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n typeof MessagesAnnotation.spec & ToAnnotationRoot<StateSchema>[\"spec\"],\n ReactAgentAnnotation<StructuredResponseFormat>[\"spec\"] &\n ToAnnotationRoot<StateSchema>[\"spec\"],\n ToAnnotationRoot<ContextSchema>[\"spec\"],\n unknown\n>;\n\nexport class ReactAgent<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> {\n #graph: AgentGraph<StateSchema, StructuredResponseFormat, ContextSchema>;\n\n #inputSchema?: AnnotationRoot<ToAnnotationRoot<StateSchema>[\"spec\"]>;\n\n #toolBehaviorVersion: \"v1\" | \"v2\" = \"v2\";\n\n constructor(\n public options: CreateReactAgentParams<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >\n ) {\n this.#toolBehaviorVersion = options.version ?? this.#toolBehaviorVersion;\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n if (options.llm && typeof options.llm !== \"function\") {\n validateLLMHasNoBoundTools(options.llm);\n }\n\n /**\n * validate that model and llm options are not provided together\n */\n if (options.llm && options.model) {\n throw new Error(\"Cannot provide both `model` and `llm` options.\");\n }\n\n /**\n * validate that either model or llm option is provided\n */\n if (!options.llm && !options.model) {\n throw new Error(\n \"Either `model` or `llm` option must be provided to create an agent.\"\n );\n }\n\n const toolClasses = Array.isArray(options.tools)\n ? options.tools\n : options.tools.tools;\n\n /**\n * If any of the tools are configured to return_directly after running,\n * our graph needs to check if these were called\n */\n const shouldReturnDirect = new Set(\n toolClasses\n .filter(isClientTool)\n .filter((tool) => \"returnDirect\" in tool && tool.returnDirect)\n .map((tool) => tool.name)\n );\n\n const schema = this.options.stateSchema\n ? enhanceStateSchemaWithMessageReducer(this.options.stateSchema)\n : createReactAgentAnnotationConditional<StructuredResponseFormat>(\n this.options.responseFormat !== undefined\n );\n\n const workflow = new StateGraph(schema, this.options.contextSchema);\n\n const allNodeWorkflows = workflow as WithStateGraphNodes<\n \"pre_model_hook\" | \"post_model_hook\" | \"tools\" | \"agent\",\n typeof workflow\n >;\n\n /**\n * Add Nodes\n */\n allNodeWorkflows.addNode(\n \"agent\",\n new AgentNode({\n llm: this.options.llm,\n model: this.options.model,\n prompt: this.options.prompt,\n includeAgentName: this.options.includeAgentName,\n name: this.options.name,\n responseFormat: this.options.responseFormat,\n toolClasses,\n shouldReturnDirect,\n signal: this.options.signal,\n }),\n {\n input: this.#inputSchema,\n }\n );\n\n /**\n * add single tool node for all tools\n */\n if (toolClasses.length > 0) {\n const toolNode = new ToolNode(toolClasses.filter(isClientTool), {\n signal: this.options.signal,\n });\n allNodeWorkflows.addNode(\"tools\", toolNode);\n }\n\n /**\n * setup preModelHook\n */\n if (options.preModelHook) {\n allNodeWorkflows.addNode(\"pre_model_hook\", options.preModelHook);\n }\n\n /**\n * setup postModelHook\n */\n if (options.postModelHook) {\n allNodeWorkflows.addNode(\"post_model_hook\", options.postModelHook);\n }\n\n /**\n * Add Edges\n */\n allNodeWorkflows.addEdge(START, this.#getEntryPoint());\n\n if (this.options.preModelHook) {\n allNodeWorkflows.addEdge(\"pre_model_hook\", \"agent\");\n }\n\n if (this.options.postModelHook) {\n allNodeWorkflows.addEdge(\"agent\", \"post_model_hook\");\n const postHookPaths = this.#getPostModelHookPaths(\n toolClasses.filter(isClientTool)\n );\n if (postHookPaths.length === 1) {\n allNodeWorkflows.addEdge(\"post_model_hook\", postHookPaths[0]);\n } else {\n allNodeWorkflows.addConditionalEdges(\n \"post_model_hook\",\n this.#createPostModelHookRouter(),\n postHookPaths\n );\n }\n } else {\n const modelPaths = this.#getModelPaths(toolClasses.filter(isClientTool));\n if (modelPaths.length === 1) {\n allNodeWorkflows.addEdge(\"agent\", modelPaths[0]);\n } else {\n allNodeWorkflows.addConditionalEdges(\n \"agent\",\n this.#createModelRouter(),\n modelPaths\n );\n }\n }\n\n /**\n * add edges for tools node\n */\n if (toolClasses.length > 0) {\n if (shouldReturnDirect.size > 0) {\n allNodeWorkflows.addConditionalEdges(\n \"tools\",\n this.#createToolsRouter(shouldReturnDirect),\n [this.#getEntryPoint(), END]\n );\n } else {\n allNodeWorkflows.addEdge(\"tools\", this.#getEntryPoint());\n }\n }\n\n /**\n * compile the graph\n */\n this.#graph = allNodeWorkflows.compile({\n checkpointer: this.options.checkpointer ?? this.options.checkpointSaver,\n interruptBefore: this.options.interruptBefore,\n interruptAfter: this.options.interruptAfter,\n store: this.options.store,\n name: this.options.name,\n description: this.options.description,\n });\n }\n\n /**\n * Get the compiled graph.\n */\n get graph(): AgentGraph<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n > {\n return this.#graph;\n }\n\n #getEntryPoint() {\n const entryPoint = this.options.preModelHook ? \"pre_model_hook\" : \"agent\";\n return entryPoint;\n }\n\n /**\n * Get possible edge destinations from post_model_hook node.\n */\n #getPostModelHookPaths(toolClasses: (ClientTool | ServerTool)[]) {\n const paths: (typeof END | \"agent\" | \"pre_model_hook\" | \"tools\")[] = [];\n if (toolClasses.length > 0) {\n paths.push(this.#getEntryPoint(), \"tools\");\n }\n paths.push(END);\n return paths;\n }\n\n #createPostModelHookRouter() {\n return (state: InternalAgentState<StructuredResponseFormat>) => {\n const messages = state.messages;\n const toolMessages = messages.filter(isToolMessage);\n const lastAiMessage = messages.filter(isAIMessage).at(-1);\n const pendingToolCalls = lastAiMessage?.tool_calls?.filter(\n (call) => !toolMessages.some((m) => m.tool_call_id === call.id)\n );\n\n if (pendingToolCalls && pendingToolCalls.length > 0) {\n /**\n * The tool node processes a single message.\n * All tool calls in the message are executed in parallel within the tool node.\n * @deprecated likely to be removed in the next version of the agent\n */\n if (this.#toolBehaviorVersion === \"v1\") {\n return \"tools\";\n }\n\n /**\n * The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n */\n return pendingToolCalls.map(\n (toolCall) => new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n }\n\n if (messages.at(-1) instanceof ToolMessage) {\n return this.#getEntryPoint();\n }\n\n return END;\n };\n }\n\n /**\n * Get possible edge destinations from model node.\n * @param toolClasses names of tools to call\n * @returns list of possible edge destinations\n */\n #getModelPaths(\n toolClasses: (ClientTool | ServerTool)[]\n ): (\"tools\" | typeof END)[] {\n const paths: (\"tools\" | typeof END)[] = [];\n if (toolClasses.length > 0) {\n paths.push(\"tools\");\n }\n\n paths.push(END);\n\n return paths;\n }\n\n /**\n * Create routing function for model node conditional edges.\n */\n #createModelRouter() {\n /**\n * determine if the agent should continue or not\n */\n return (state: InternalAgentState<StructuredResponseFormat>) => {\n const messages = state.messages;\n const lastMessage = messages.at(-1);\n\n if (\n !(lastMessage instanceof AIMessage) ||\n !lastMessage.tool_calls ||\n lastMessage.tool_calls.length === 0\n ) {\n if (this.options.postModelHook) {\n return \"post_model_hook\";\n }\n\n return END;\n }\n\n if (this.options.postModelHook) {\n return \"post_model_hook\";\n }\n\n /**\n * The tool node processes a single message.\n */\n if (this.#toolBehaviorVersion === \"v1\") {\n return \"tools\";\n }\n\n /**\n * Route to tools node\n */\n return lastMessage.tool_calls.map(\n (toolCall) => new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n };\n }\n\n /**\n * Create routing function for tools node conditional edges.\n */\n #createToolsRouter(shouldReturnDirect: Set<string>) {\n return (state: InternalAgentState<StructuredResponseFormat>) => {\n const messages = state.messages;\n const lastMessage = messages[messages.length - 1];\n\n // Check if we just executed a returnDirect tool\n if (\n lastMessage instanceof ToolMessage &&\n lastMessage.name &&\n shouldReturnDirect.has(lastMessage.name)\n ) {\n // If we have a response format, route to agent to generate structured response\n // Otherwise, return directly\n return this.options.responseFormat ? this.#getEntryPoint() : END;\n }\n\n // For non-returnDirect tools, always route back to agent\n return this.#getEntryPoint();\n };\n }\n\n /**\n * @inheritdoc\n */\n get invoke(): AgentGraph<StateSchema, StructuredResponseFormat>[\"invoke\"] {\n return this.#graph.invoke.bind(this.#graph);\n }\n\n /**\n * @inheritdoc\n */\n get stream(): AgentGraph<StateSchema, StructuredResponseFormat>[\"stream\"] {\n return this.#graph.stream.bind(this.#graph);\n }\n\n /**\n * @inheritdoc\n */\n get streamEvents(): AgentGraph<\n StateSchema,\n StructuredResponseFormat\n >[\"streamEvents\"] {\n return this.#graph.streamEvents.bind(this.#graph);\n }\n\n /**\n * Visualize the graph as a PNG image.\n * @param params - Parameters for the drawMermaidPng method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns PNG image as a buffer\n */\n async drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n const image = await representation.drawMermaidPng(params);\n const arrayBuffer = await image.arrayBuffer();\n const buffer = new Uint8Array(arrayBuffer);\n return buffer;\n }\n\n /**\n * Draw the graph as a Mermaid string.\n * @param params - Parameters for the drawMermaid method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns Mermaid string\n */\n async drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n return representation.drawMermaid(params);\n }\n}\n"],"mappings":";;;;;;;;;AAyDA,IAAa,aAAb,MAME;CACA;CAEA;CAEA,uBAAoC;CAEpC,YACSA,SAKP;EALO;EAMP,KAAKC,uBAAuB,QAAQ,WAAW,KAAKA;;;;AAKpD,MAAI,QAAQ,OAAO,OAAO,QAAQ,QAAQ,YACxCC,yCAA2B,QAAQ,IAAI;;;;AAMzC,MAAI,QAAQ,OAAO,QAAQ,MACzB,OAAM,IAAI,MAAM;;;;AAMlB,MAAI,CAAC,QAAQ,OAAO,CAAC,QAAQ,MAC3B,OAAM,IAAI,MACR;EAIJ,MAAM,cAAc,MAAM,QAAQ,QAAQ,MAAM,GAC5C,QAAQ,QACR,QAAQ,MAAM;;;;;EAMlB,MAAM,qBAAqB,IAAI,IAC7B,YACG,OAAOC,2BAAa,CACpB,OAAO,CAAC,SAAS,kBAAkB,QAAQ,KAAK,aAAa,CAC7D,IAAI,CAAC,SAAS,KAAK,KAAK;EAG7B,MAAM,SAAS,KAAK,QAAQ,cACxBC,wDAAqC,KAAK,QAAQ,YAAY,GAC9DC,yDACE,KAAK,QAAQ,mBAAmB,OACjC;EAEL,MAAM,WAAW,IAAIC,iCAAW,QAAQ,KAAK,Q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MAAM,MAAM,aAAa;EAC7C,MAAM,SAAS,IAAI,WAAW;AAC9B,SAAO;CACR;;;;;;;;;;;CAYD,MAAM,YAAYW,QAMf;EACD,MAAM,iBAAiB,MAAM,KAAKX,OAAO,eAAe;AACxD,SAAO,eAAe,YAAY,OAAO;CAC1C;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"ReactAgent.d.cts","names":["InteropZodObject","CompiledStateGraph","MessagesAnnotation","ReactAgentAnnotation","CreateReactAgentParams","AnyAnnotationRoot","ToAnnotationRoot","ResponseFormatUndefined","AgentGraph","Record","StateSchema","spec","StructuredResponseFormat","ContextSchema","ReactAgent","ArrayBuffer","Uint8Array","Promise"],"sources":["../../src/agents/ReactAgent.d.ts"],"sourcesContent":["/* eslint-disable prefer-destructuring, no-instanceof/no-instanceof */\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\nimport { CompiledStateGraph, MessagesAnnotation } from \"@langchain/langgraph\";\nimport { ReactAgentAnnotation } from \"./annotation.js\";\nimport type { CreateReactAgentParams } from \"./types.js\";\nimport type { AnyAnnotationRoot, ToAnnotationRoot } from \"./annotation.js\";\nimport type { ResponseFormatUndefined } from \"./responses.js\";\ntype AgentGraph<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, StructuredResponseFormat extends Record<string, any> | ResponseFormatUndefined = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = CompiledStateGraph<ToAnnotationRoot<StateSchema>[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"], \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nany, typeof MessagesAnnotation.spec & ToAnnotationRoot<StateSchema>[\"spec\"], ReactAgentAnnotation<StructuredResponseFormat>[\"spec\"] & ToAnnotationRoot<StateSchema>[\"spec\"], ToAnnotationRoot<ContextSchema>[\"spec\"], unknown>;\nexport declare class ReactAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, StructuredResponseFormat extends Record<string, any> | ResponseFormatUndefined = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> {\n #private;\n options: CreateReactAgentParams<StateSchema, StructuredResponseFormat, ContextSchema>;\n constructor(options: CreateReactAgentParams<StateSchema, StructuredResponseFormat, ContextSchema>);\n /**\n * Get the compiled graph.\n */\n get graph(): AgentGraph<StateSchema, StructuredResponseFormat, ContextSchema>;\n /**\n * @inheritdoc\n */\n get invoke(): AgentGraph<StateSchema, StructuredResponseFormat>[\"invoke\"];\n /**\n * @inheritdoc\n */\n get stream(): AgentGraph<StateSchema, StructuredResponseFormat>[\"stream\"];\n /**\n * @inheritdoc\n */\n get streamEvents(): AgentGraph<StateSchema, StructuredResponseFormat>[\"streamEvents\"];\n /**\n * Visualize the graph as a PNG image.\n * @param params - Parameters for the drawMermaidPng method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns PNG image as a buffer\n */\n drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }): Promise<Uint8Array<ArrayBuffer>>;\n /**\n * Draw the graph as a Mermaid string.\n * @param params - Parameters for the drawMermaid method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns Mermaid string\n */\n drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }): Promise<string>;\n}\nexport {};\n"],"mappings":";;;;;;;AAM8D,KACzDQ,UAAAA,CAAAA,oBAA+BH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gent.d.cts","names":["InteropZodObject","CompiledStateGraph","MessagesAnnotation","ReactAgentAnnotation","CreateReactAgentParams","AnyAnnotationRoot","ToAnnotationRoot","ResponseFormatUndefined","AgentGraph","Record","StateSchema","spec","StructuredResponseFormat","ContextSchema","ReactAgent","ArrayBuffer","Uint8Array","Promise"],"sources":["../../src/agents/ReactAgent.d.ts"],"sourcesContent":["/* eslint-disable prefer-destructuring, no-instanceof/no-instanceof */\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\nimport { CompiledStateGraph, MessagesAnnotation } from \"@langchain/langgraph\";\nimport { ReactAgentAnnotation } from \"./annotation.js\";\nimport type { CreateReactAgentParams } from \"./types.js\";\nimport { type AnyAnnotationRoot, type ToAnnotationRoot } from \"./annotation.js\";\nimport type { ResponseFormatUndefined } from \"./responses.js\";\ntype AgentGraph<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, StructuredResponseFormat extends Record<string, any> | ResponseFormatUndefined = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = CompiledStateGraph<ToAnnotationRoot<StateSchema>[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"], \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nany, typeof MessagesAnnotation.spec & ToAnnotationRoot<StateSchema>[\"spec\"], ReactAgentAnnotation<StructuredResponseFormat>[\"spec\"] & ToAnnotationRoot<StateSchema>[\"spec\"], ToAnnotationRoot<ContextSchema>[\"spec\"], unknown>;\nexport declare class ReactAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, StructuredResponseFormat extends Record<string, any> | ResponseFormatUndefined = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> {\n #private;\n options: CreateReactAgentParams<StateSchema, StructuredResponseFormat, ContextSchema>;\n constructor(options: CreateReactAgentParams<StateSchema, StructuredResponseFormat, ContextSchema>);\n /**\n * Get the compiled graph.\n */\n get graph(): AgentGraph<StateSchema, StructuredResponseFormat, ContextSchema>;\n /**\n * @inheritdoc\n */\n get invoke(): AgentGraph<StateSchema, StructuredResponseFormat>[\"invoke\"];\n /**\n * @inheritdoc\n */\n get stream(): AgentGraph<StateSchema, StructuredResponseFormat>[\"stream\"];\n /**\n * @inheritdoc\n */\n get streamEvents(): AgentGraph<StateSchema, StructuredResponseFormat>[\"streamEvents\"];\n /**\n * Visualize the graph as a PNG image.\n * @param params - Parameters for the drawMermaidPng method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns PNG image as a buffer\n */\n drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }): Promise<Uint8Array<ArrayBuffer>>;\n /**\n * Draw the graph as a Mermaid string.\n * @param params - Parameters for the drawMermaid method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns Mermaid string\n */\n drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }): Promise<string>;\n}\nexport {};\n"],"mappings":";;;;;;;AAM8D,KACzDQ,UAAAA,CAAAA,oBAA+BH,iBAArB,GAAyCL,gBAAzC,GAA4DK,iBAA5D,EAAA,iCAAgHI,MAAhH,CAAA,MAAA,EAAA,GAAA,CAAA,GAAsIF,uBAAtI,GAAgKE,MAAhK,CAAA,MAAA,EAAA,GAAA,CAAA,EAAA,sBAA2MJ,iBAA3M,GAA+NL,gBAA/N,GAAkPK,iBAAlP,CAAA,GAAu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M,MAAAA,CAAAA,CAAAA,EAgBhFJ,UAhBgFI,CAgBrEF,WAhBqEE,EAgBxDA,wBAhBwDA,CAAAA,CAAAA,QAAAA,CAAAA;EAAwB;;;EAA4B,IAAwCC,YAAAA,CAAAA,CAAAA,EAoBtKL,UApBsKK,CAoB3JH,WApB2JG,EAoB9ID,wBApB8IC,CAAAA,CAAAA,cAAAA,CAAAA;EAAa;;AAF6F;AAGxS;;;;;;;EAA4L,cAAGJ,CAAAA,MAEtH,CAFsHA,EAAAA;IAA2CJ,UAAAA,CAAAA,EAAAA,OAAAA;IAAoBL,UAAAA,CAAAA,EAAAA,MAAAA;IAAmBK,UAAAA,CAAAA,EAiC5PI,MAjC4PJ,CAAAA,MAAAA,EAAAA,MAAAA,CAAAA;IAE7OK,eAAAA,CAAAA,EAAAA,MAAAA;IAAaE,eAAAA,CAAAA,EAAAA,MAAAA;EAAwB,CAAA,CAAA,EAkCjEK,OAlCmEJ,CAkC3DG,UAlC2DH,CAkChDE,WAlCgDF,CAAAA,CAAAA;EAAa;;;;;;;;;;EAShD,WAAED,CAAAA,MAQI,CARJA,EAAAA;IAAxBJ,UAAAA,CAAAA,EAAAA,OAAAA;IAIWE,UAAAA,CAAAA,EAAAA,MAAAA;IAAaE,UAAAA,CAAAA,EAmCrBH,MAnCqBG,CAAAA,MAAAA,EAAAA,MAAAA,CAAAA;IAAxBJ,eAAAA,CAAAA,EAAAA,MAAAA;IAIiBE,eAAAA,CAAAA,EAAAA,MAAAA;EAAW,CAAA,CAAA,EAkCtCO,OAlCwCL,CAAAA,MAAAA,CAAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"ReactAgent.d.ts","names":["InteropZodObject","CompiledStateGraph","MessagesAnnotation","ReactAgentAnnotation","CreateReactAgentParams","AnyAnnotationRoot","ToAnnotationRoot","ResponseFormatUndefined","AgentGraph","Record","StateSchema","spec","StructuredResponseFormat","ContextSchema","ReactAgent","ArrayBuffer","Uint8Array","Promise"],"sources":["../../src/agents/ReactAgent.d.ts"],"sourcesContent":["/* eslint-disable prefer-destructuring, no-instanceof/no-instanceof */\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\nimport { CompiledStateGraph, MessagesAnnotation } from \"@langchain/langgraph\";\nimport { ReactAgentAnnotation } from \"./annotation.js\";\nimport type { CreateReactAgentParams } from \"./types.js\";\nimport type { AnyAnnotationRoot, ToAnnotationRoot } from \"./annotation.js\";\nimport type { ResponseFormatUndefined } from \"./responses.js\";\ntype AgentGraph<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, StructuredResponseFormat extends Record<string, any> | ResponseFormatUndefined = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = CompiledStateGraph<ToAnnotationRoot<StateSchema>[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"], \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nany, typeof MessagesAnnotation.spec & ToAnnotationRoot<StateSchema>[\"spec\"], ReactAgentAnnotation<StructuredResponseFormat>[\"spec\"] & ToAnnotationRoot<StateSchema>[\"spec\"], ToAnnotationRoot<ContextSchema>[\"spec\"], unknown>;\nexport declare class ReactAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, StructuredResponseFormat extends Record<string, any> | ResponseFormatUndefined = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> {\n #private;\n options: CreateReactAgentParams<StateSchema, StructuredResponseFormat, ContextSchema>;\n constructor(options: CreateReactAgentParams<StateSchema, StructuredResponseFormat, ContextSchema>);\n /**\n * Get the compiled graph.\n */\n get graph(): AgentGraph<StateSchema, StructuredResponseFormat, ContextSchema>;\n /**\n * @inheritdoc\n */\n get invoke(): AgentGraph<StateSchema, StructuredResponseFormat>[\"invoke\"];\n /**\n * @inheritdoc\n */\n get stream(): AgentGraph<StateSchema, StructuredResponseFormat>[\"stream\"];\n /**\n * @inheritdoc\n */\n get streamEvents(): AgentGraph<StateSchema, StructuredResponseFormat>[\"streamEvents\"];\n /**\n * Visualize the graph as a PNG image.\n * @param params - Parameters for the drawMermaidPng method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns PNG image as a buffer\n */\n drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }): Promise<Uint8Array<ArrayBuffer>>;\n /**\n * Draw the graph as a Mermaid string.\n * @param params - Parameters for the drawMermaid method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns Mermaid string\n */\n drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }): Promise<string>;\n}\nexport {};\n"],"mappings":";;;;;;;AAM8D,KACzDQ,UAAAA,CAAAA,oBAA+BH,iBAArB,GAAyCL,gBAAzC,GAA4DK,iBAA5D,EAAA,iCAAgHI,MAAhH,CAAA,MAAA,EAAA,GAAA,CAAA,GAAsIF,uBAAtI,GAAgKE,MAAhK,CAAA,MAAA,EAAA,GAAA,CAAA,EAAA,sBAA2MJ,iBAA3M,GAA+NL,gBAA/N,GAAkPK,iBAAlP,CAAA,GAAuQJ,kBAAvQ,CAA0RK,gBAA1R,CAA2SI,WAA3S,CAAA,CAAA,OAAA,CAAA,EAAkUJ,gBAAlU,CAAmVI,WAAnV,CAAA,CAAA,QAAA,CAAA;;GAAA,EAAA,OAEHR,kBAAAA,CAAmBS,IAFKN,GAEEC,gBAFFD,CAEmBK,WAFnBL,CAAAA,CA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CAAAA,CAAAA,cAAAA,CAAAA;EAAa;;AAF6F;AAGxS;;;;;;;EAA4L,cAAGJ,CAAAA,MAEtH,CAFsHA,EAAAA;IAA2CJ,UAAAA,CAAAA,EAAAA,OAAAA;IAAoBL,UAAAA,CAAAA,EAAAA,MAAAA;IAAmBK,UAAAA,CAAAA,EAiC5PI,MAjC4PJ,CAAAA,MAAAA,EAAAA,MAAAA,CAAAA;IAE7OK,eAAAA,CAAAA,EAAAA,MAAAA;IAAaE,eAAAA,CAAAA,EAAAA,MAAAA;EAAwB,CAAA,CAAA,EAkCjEK,OAlCmEJ,CAkC3DG,UAlC2DH,CAkChDE,WAlCgDF,CAAAA,CAAAA;EAAa;;;;;;;;;;EAShD,WAAED,CAAAA,MAQI,CARJA,EAAAA;IAAxBJ,UAAAA,CAAAA,EAAAA,OAAAA;IAIWE,UAAAA,CAAAA,EAAAA,MAAAA;IAAaE,UAAAA,CAAAA,EAmCrBH,MAnCqBG,CAAAA,MAAAA,EAAAA,MAAAA,CAAAA;IAAxBJ,eAAAA,CAAAA,EAAAA,MAAAA;IAIiBE,eAAAA,CAAAA,EAAAA,MAAAA;EAAW,CAAA,CAAA,EAkCtCO,OAlCwCL,CAAAA,MAAAA,CAAAA"}
1
+ {"version":3,"file":"ReactAgent.d.ts","names":["InteropZodObject","CompiledStateGraph","MessagesAnnotation","ReactAgentAnnotation","CreateReactAgentParams","AnyAnnotationRoot","ToAnnotationRoot","ResponseFormatUndefined","AgentGraph","Record","StateSchema","spec","StructuredResponseFormat","ContextSchema","ReactAgent","ArrayBuffer","Uint8Array","Promise"],"sources":["../../src/agents/ReactAgent.d.ts"],"sourcesContent":["/* eslint-disable prefer-destructuring, no-instanceof/no-instanceof */\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\nimport { CompiledStateGraph, MessagesAnnotation } from \"@langchain/langgraph\";\nimport { ReactAgentAnnotation } from \"./annotation.js\";\nimport type { CreateReactAgentParams } from \"./types.js\";\nimport { type AnyAnnotationRoot, type ToAnnotationRoot } from \"./annotation.js\";\nimport type { ResponseFormatUndefined } from \"./responses.js\";\ntype AgentGraph<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, StructuredResponseFormat extends Record<string, any> | ResponseFormatUndefined = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> = CompiledStateGraph<ToAnnotationRoot<StateSchema>[\"State\"], ToAnnotationRoot<StateSchema>[\"Update\"], \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nany, typeof MessagesAnnotation.spec & ToAnnotationRoot<StateSchema>[\"spec\"], ReactAgentAnnotation<StructuredResponseFormat>[\"spec\"] & ToAnnotationRoot<StateSchema>[\"spec\"], ToAnnotationRoot<ContextSchema>[\"spec\"], unknown>;\nexport declare class ReactAgent<StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot, StructuredResponseFormat extends Record<string, any> | ResponseFormatUndefined = Record<string, any>, ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot> {\n #private;\n options: CreateReactAgentParams<StateSchema, StructuredResponseFormat, ContextSchema>;\n constructor(options: CreateReactAgentParams<StateSchema, StructuredResponseFormat, ContextSchema>);\n /**\n * Get the compiled graph.\n */\n get graph(): AgentGraph<StateSchema, StructuredResponseFormat, ContextSchema>;\n /**\n * @inheritdoc\n */\n get invoke(): AgentGraph<StateSchema, StructuredResponseFormat>[\"invoke\"];\n /**\n * @inheritdoc\n */\n get stream(): AgentGraph<StateSchema, StructuredResponseFormat>[\"stream\"];\n /**\n * @inheritdoc\n */\n get streamEvents(): AgentGraph<StateSchema, StructuredResponseFormat>[\"streamEvents\"];\n /**\n * Visualize the graph as a PNG image.\n * @param params - Parameters for the drawMermaidPng method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns PNG image as a buffer\n */\n drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }): Promise<Uint8Array<ArrayBuffer>>;\n /**\n * Draw the graph as a Mermaid string.\n * @param params - Parameters for the drawMermaid method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns Mermaid string\n */\n drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }): Promise<string>;\n}\nexport {};\n"],"mappings":";;;;;;;AAM8D,KACzDQ,UAAAA,CAAAA,oBAA+BH,iBAArB,GAAyCL,gBAAzC,GAA4DK,iBAA5D,EAAA,iCAAgHI,MAAhH,CAAA,MAAA,EAAA,GAAA,CAAA,GAAsIF,uBAAtI,GAAgKE,MAAhK,CAAA,MAAA,EAAA,GAAA,CAAA,EAAA,sBAA2MJ,iBAA3M,GAA+NL,gBAA/N,GAAkPK,iBAAlP,CAAA,GAAuQJ,kBAAvQ,CAA0RK,gBAA1R,CAA2SI,WAA3S,CAAA,CAAA,OAAA,CAAA,EAAkUJ,gBAAlU,CAAmVI,WAAnV,CAAA,CAAA,QAAA,CAAA;;GAAA,EAAA,OAEHR,kBAAAA,CAAmBS,IAFKN,GAEEC,gBAFFD,CAEmBK,WAFnBL,CAAAA,CAAAA,MAAAA,CAAAA,EAEyCF,oBAFzCE,CAE8DO,wBAF9DP,CAAAA,CAAAA,MAAAA,CAAAA,GAEkGC,gBAFlGD,CAEmHK,WAFnHL,CAAAA,CAAAA,MAAAA,CAAAA,EAEyIC,gBAFzID,CAE0JQ,aAF1JR,CAAAA,CAAAA,MAAAA,CAAAA,EAAAA,OAAAA,C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A,MAAAA,EAAAA,MAAAA,CAAAA;IAE7OK,eAAAA,CAAAA,EAAAA,MAAAA;IAAaE,eAAAA,CAAAA,EAAAA,MAAAA;EAAwB,CAAA,CAAA,EAkCjEK,OAlCmEJ,CAkC3DG,UAlC2DH,CAkChDE,WAlCgDF,CAAAA,CAAAA;EAAa;;;;;;;;;;EAShD,WAAED,CAAAA,MAQI,CARJA,EAAAA;IAAxBJ,UAAAA,CAAAA,EAAAA,OAAAA;IAIWE,UAAAA,CAAAA,EAAAA,MAAAA;IAAaE,UAAAA,CAAAA,EAmCrBH,MAnCqBG,CAAAA,MAAAA,EAAAA,MAAAA,CAAAA;IAAxBJ,eAAAA,CAAAA,EAAAA,MAAAA;IAIiBE,eAAAA,CAAAA,EAAAA,MAAAA;EAAW,CAAA,CAAA,EAkCtCO,OAlCwCL,CAAAA,MAAAA,CAAAA"}
@@ -1,4 +1,4 @@
1
- import { createReactAgentAnnotationConditional } from "./annotation.js";
1
+ import { createReactAgentAnnotationConditional, enhanceStateSchemaWithMessageReducer } from "./annotation.js";
2
2
  import { isClientTool, validateLLMHasNoBoundTools } from "./utils.js";
3
3
  import { AgentNode } from "./nodes/AgentNode.js";
4
4
  import { ToolNode } from "./nodes/ToolNode.js";
@@ -31,7 +31,7 @@ var ReactAgent = class {
31
31
  * our graph needs to check if these were called
32
32
  */
33
33
  const shouldReturnDirect = new Set(toolClasses.filter(isClientTool).filter((tool) => "returnDirect" in tool && tool.returnDirect).map((tool) => tool.name));
34
- const schema = this.options.stateSchema ?? createReactAgentAnnotationConditional(this.options.responseFormat !== void 0);
34
+ const schema = this.options.stateSchema ? enhanceStateSchemaWithMessageReducer(this.options.stateSchema) : createReactAgentAnnotationConditional(this.options.responseFormat !== void 0);
35
35
  const workflow = new StateGraph(schema, this.options.contextSchema);
36
36
  const allNodeWorkflows = workflow;
37
37
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"ReactAgent.js","names":["options: CreateReactAgentParams<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >","#toolBehaviorVersion","#inputSchema","#getEntryPoint","#getPostModelHookPaths","#createPostModelHookRouter","#getModelPaths","#createModelRouter","#createToolsRouter","#graph","toolClasses: (ClientTool | ServerTool)[]","paths: (typeof END | \"agent\" | \"pre_model_hook\" | \"tools\")[]","state: InternalAgentState<StructuredResponseFormat>","paths: (\"tools\" | typeof END)[]","shouldReturnDirect: Set<string>","params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }"],"sources":["../../src/agents/ReactAgent.ts"],"sourcesContent":["/* eslint-disable prefer-destructuring, no-instanceof/no-instanceof */\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\nimport {\n AnnotationRoot,\n StateGraph,\n END,\n START,\n Send,\n CompiledStateGraph,\n MessagesAnnotation,\n} from \"@langchain/langgraph\";\nimport {\n isToolMessage,\n isAIMessage,\n ToolMessage,\n AIMessage,\n} from \"@langchain/core/messages\";\n\nimport {\n createReactAgentAnnotationConditional,\n ReactAgentAnnotation,\n} from \"./annotation.js\";\nimport { isClientTool, validateLLMHasNoBoundTools } from \"./utils.js\";\nimport { AgentNode } from \"./nodes/AgentNode.js\";\nimport { ToolNode } from \"./nodes/ToolNode.js\";\nimport type {\n CreateReactAgentParams,\n ClientTool,\n ServerTool,\n InternalAgentState,\n WithStateGraphNodes,\n} from \"./types.js\";\nimport type { AnyAnnotationRoot, ToAnnotationRoot } from \"./annotation.js\";\nimport type { ResponseFormatUndefined } from \"./responses.js\";\n\ntype AgentGraph<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> = CompiledStateGraph<\n ToAnnotationRoot<StateSchema>[\"State\"],\n ToAnnotationRoot<StateSchema>[\"Update\"],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n typeof MessagesAnnotation.spec & ToAnnotationRoot<StateSchema>[\"spec\"],\n ReactAgentAnnotation<StructuredResponseFormat>[\"spec\"] &\n ToAnnotationRoot<StateSchema>[\"spec\"],\n ToAnnotationRoot<ContextSchema>[\"spec\"],\n unknown\n>;\n\nexport class ReactAgent<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> {\n #graph: AgentGraph<StateSchema, StructuredResponseFormat, ContextSchema>;\n\n #inputSchema?: AnnotationRoot<ToAnnotationRoot<StateSchema>[\"spec\"]>;\n\n #toolBehaviorVersion: \"v1\" | \"v2\" = \"v2\";\n\n constructor(\n public options: CreateReactAgentParams<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >\n ) {\n this.#toolBehaviorVersion = options.version ?? this.#toolBehaviorVersion;\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n if (options.llm && typeof options.llm !== \"function\") {\n validateLLMHasNoBoundTools(options.llm);\n }\n\n /**\n * validate that model and llm options are not provided together\n */\n if (options.llm && options.model) {\n throw new Error(\"Cannot provide both `model` and `llm` options.\");\n }\n\n /**\n * validate that either model or llm option is provided\n */\n if (!options.llm && !options.model) {\n throw new Error(\n \"Either `model` or `llm` option must be provided to create an agent.\"\n );\n }\n\n const toolClasses = Array.isArray(options.tools)\n ? options.tools\n : options.tools.tools;\n\n /**\n * If any of the tools are configured to return_directly after running,\n * our graph needs to check if these were called\n */\n const shouldReturnDirect = new Set(\n toolClasses\n .filter(isClientTool)\n .filter((tool) => \"returnDirect\" in tool && tool.returnDirect)\n .map((tool) => tool.name)\n );\n\n const schema = (this.options.stateSchema ??\n createReactAgentAnnotationConditional<StructuredResponseFormat>(\n this.options.responseFormat !== undefined\n )) as AnyAnnotationRoot;\n\n const workflow = new StateGraph(schema, this.options.contextSchema);\n\n const allNodeWorkflows = workflow as WithStateGraphNodes<\n \"pre_model_hook\" | \"post_model_hook\" | \"tools\" | \"agent\",\n typeof workflow\n >;\n\n /**\n * Add Nodes\n */\n allNodeWorkflows.addNode(\n \"agent\",\n new AgentNode({\n llm: this.options.llm,\n model: this.options.model,\n prompt: this.options.prompt,\n includeAgentName: this.options.includeAgentName,\n name: this.options.name,\n responseFormat: this.options.responseFormat,\n toolClasses,\n shouldReturnDirect,\n signal: this.options.signal,\n }),\n {\n input: this.#inputSchema,\n }\n );\n\n /**\n * add single tool node for all tools\n */\n if (toolClasses.length > 0) {\n const toolNode = new ToolNode(toolClasses.filter(isClientTool), {\n signal: this.options.signal,\n });\n allNodeWorkflows.addNode(\"tools\", toolNode);\n }\n\n /**\n * setup preModelHook\n */\n if (options.preModelHook) {\n allNodeWorkflows.addNode(\"pre_model_hook\", options.preModelHook);\n }\n\n /**\n * setup postModelHook\n */\n if (options.postModelHook) {\n allNodeWorkflows.addNode(\"post_model_hook\", options.postModelHook);\n }\n\n /**\n * Add Edges\n */\n allNodeWorkflows.addEdge(START, this.#getEntryPoint());\n\n if (this.options.preModelHook) {\n allNodeWorkflows.addEdge(\"pre_model_hook\", \"agent\");\n }\n\n if (this.options.postModelHook) {\n allNodeWorkflows.addEdge(\"agent\", \"post_model_hook\");\n const postHookPaths = this.#getPostModelHookPaths(\n toolClasses.filter(isClientTool)\n );\n if (postHookPaths.length === 1) {\n allNodeWorkflows.addEdge(\"post_model_hook\", postHookPaths[0]);\n } else {\n allNodeWorkflows.addConditionalEdges(\n \"post_model_hook\",\n this.#createPostModelHookRouter(),\n postHookPaths\n );\n }\n } else {\n const modelPaths = this.#getModelPaths(toolClasses.filter(isClientTool));\n if (modelPaths.length === 1) {\n allNodeWorkflows.addEdge(\"agent\", modelPaths[0]);\n } else {\n allNodeWorkflows.addConditionalEdges(\n \"agent\",\n this.#createModelRouter(),\n modelPaths\n );\n }\n }\n\n /**\n * add edges for tools node\n */\n if (toolClasses.length > 0) {\n if (shouldReturnDirect.size > 0) {\n allNodeWorkflows.addConditionalEdges(\n \"tools\",\n this.#createToolsRouter(shouldReturnDirect),\n [this.#getEntryPoint(), END]\n );\n } else {\n allNodeWorkflows.addEdge(\"tools\", this.#getEntryPoint());\n }\n }\n\n /**\n * compile the graph\n */\n this.#graph = allNodeWorkflows.compile({\n checkpointer: this.options.checkpointer ?? this.options.checkpointSaver,\n interruptBefore: this.options.interruptBefore,\n interruptAfter: this.options.interruptAfter,\n store: this.options.store,\n name: this.options.name,\n description: this.options.description,\n });\n }\n\n /**\n * Get the compiled graph.\n */\n get graph(): AgentGraph<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n > {\n return this.#graph;\n }\n\n #getEntryPoint() {\n const entryPoint = this.options.preModelHook ? \"pre_model_hook\" : \"agent\";\n return entryPoint;\n }\n\n /**\n * Get possible edge destinations from post_model_hook node.\n */\n #getPostModelHookPaths(toolClasses: (ClientTool | ServerTool)[]) {\n const paths: (typeof END | \"agent\" | \"pre_model_hook\" | \"tools\")[] = [];\n if (toolClasses.length > 0) {\n paths.push(this.#getEntryPoint(), \"tools\");\n }\n paths.push(END);\n return paths;\n }\n\n #createPostModelHookRouter() {\n return (state: InternalAgentState<StructuredResponseFormat>) => {\n const messages = state.messages;\n const toolMessages = messages.filter(isToolMessage);\n const lastAiMessage = messages.filter(isAIMessage).at(-1);\n const pendingToolCalls = lastAiMessage?.tool_calls?.filter(\n (call) => !toolMessages.some((m) => m.tool_call_id === call.id)\n );\n\n if (pendingToolCalls && pendingToolCalls.length > 0) {\n /**\n * The tool node processes a single message.\n * All tool calls in the message are executed in parallel within the tool node.\n * @deprecated likely to be removed in the next version of the agent\n */\n if (this.#toolBehaviorVersion === \"v1\") {\n return \"tools\";\n }\n\n /**\n * The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n */\n return pendingToolCalls.map(\n (toolCall) => new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n }\n\n if (messages.at(-1) instanceof ToolMessage) {\n return this.#getEntryPoint();\n }\n\n return END;\n };\n }\n\n /**\n * Get possible edge destinations from model node.\n * @param toolClasses names of tools to call\n * @returns list of possible edge destinations\n */\n #getModelPaths(\n toolClasses: (ClientTool | ServerTool)[]\n ): (\"tools\" | typeof END)[] {\n const paths: (\"tools\" | typeof END)[] = [];\n if (toolClasses.length > 0) {\n paths.push(\"tools\");\n }\n\n paths.push(END);\n\n return paths;\n }\n\n /**\n * Create routing function for model node conditional edges.\n */\n #createModelRouter() {\n /**\n * determine if the agent should continue or not\n */\n return (state: InternalAgentState<StructuredResponseFormat>) => {\n const messages = state.messages;\n const lastMessage = messages.at(-1);\n\n if (\n !(lastMessage instanceof AIMessage) ||\n !lastMessage.tool_calls ||\n lastMessage.tool_calls.length === 0\n ) {\n if (this.options.postModelHook) {\n return \"post_model_hook\";\n }\n\n return END;\n }\n\n if (this.options.postModelHook) {\n return \"post_model_hook\";\n }\n\n /**\n * The tool node processes a single message.\n */\n if (this.#toolBehaviorVersion === \"v1\") {\n return \"tools\";\n }\n\n /**\n * Route to tools node\n */\n return lastMessage.tool_calls.map(\n (toolCall) => new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n };\n }\n\n /**\n * Create routing function for tools node conditional edges.\n */\n #createToolsRouter(shouldReturnDirect: Set<string>) {\n return (state: InternalAgentState<StructuredResponseFormat>) => {\n const messages = state.messages;\n const lastMessage = messages[messages.length - 1];\n\n // Check if we just executed a returnDirect tool\n if (\n lastMessage instanceof ToolMessage &&\n lastMessage.name &&\n shouldReturnDirect.has(lastMessage.name)\n ) {\n // If we have a response format, route to agent to generate structured response\n // Otherwise, return directly\n return this.options.responseFormat ? this.#getEntryPoint() : END;\n }\n\n // For non-returnDirect tools, always route back to agent\n return this.#getEntryPoint();\n };\n }\n\n /**\n * @inheritdoc\n */\n get invoke(): AgentGraph<StateSchema, StructuredResponseFormat>[\"invoke\"] {\n return this.#graph.invoke.bind(this.#graph);\n }\n\n /**\n * @inheritdoc\n */\n get stream(): AgentGraph<StateSchema, StructuredResponseFormat>[\"stream\"] {\n return this.#graph.stream.bind(this.#graph);\n }\n\n /**\n * @inheritdoc\n */\n get streamEvents(): AgentGraph<\n StateSchema,\n StructuredResponseFormat\n >[\"streamEvents\"] {\n return this.#graph.streamEvents.bind(this.#graph);\n }\n\n /**\n * Visualize the graph as a PNG image.\n * @param params - Parameters for the drawMermaidPng method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns PNG image as a buffer\n */\n async drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n const image = await representation.drawMermaidPng(params);\n const arrayBuffer = await image.arrayBuffer();\n const buffer = new Uint8Array(arrayBuffer);\n return buffer;\n }\n\n /**\n * Draw the graph as a Mermaid string.\n * @param params - Parameters for the drawMermaid method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns Mermaid string\n */\n async drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n return representation.drawMermaid(params);\n }\n}\n"],"mappings":";;;;;;;;AAqDA,IAAa,aAAb,MAME;CACA;CAEA;CAEA,uBAAoC;CAEpC,YACSA,SAKP;EALO;EAMP,KAAKC,uBAAuB,QAAQ,WAAW,KAAKA;;;;AAKpD,MAAI,QAAQ,OAAO,OAAO,QAAQ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,KAAK,QAAQ,iBAAiB,KAAKT,gBAAgB,GAAG;AAI/D,UAAO,KAAKA,gBAAgB;EAC7B;CACF;;;;CAKD,IAAI,SAAsE;AACxE,SAAO,KAAKM,OAAO,OAAO,KAAK,KAAKA,OAAO;CAC5C;;;;CAKD,IAAI,SAAsE;AACxE,SAAO,KAAKA,OAAO,OAAO,KAAK,KAAKA,OAAO;CAC5C;;;;CAKD,IAAI,eAGc;AAChB,SAAO,KAAKA,OAAO,aAAa,KAAK,KAAKA,OAAO;CAClD;;;;;;;;;;;CAYD,MAAM,eAAeM,QAMlB;EACD,MAAM,iBAAiB,MAAM,KAAKN,OAAO,eAAe;EACxD,MAAM,QAAQ,MAAM,eAAe,eAAe,OAAO;EACzD,MAAM,cAAc,MAAM,MAAM,aAAa;EAC7C,MAAM,SAAS,IAAI,WAAW;AAC9B,SAAO;CACR;;;;;;;;;;;CAYD,MAAM,YAAYM,QAMf;EACD,MAAM,iBAAiB,MAAM,KAAKN,OAAO,eAAe;AACxD,SAAO,eAAe,YAAY,OAAO;CAC1C;AACF"}
1
+ {"version":3,"file":"ReactAgent.js","names":["options: CreateReactAgentParams<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >","#toolBehaviorVersion","#inputSchema","#getEntryPoint","#getPostModelHookPaths","#createPostModelHookRouter","#getModelPaths","#createModelRouter","#createToolsRouter","#graph","toolClasses: (ClientTool | ServerTool)[]","paths: (typeof END | \"agent\" | \"pre_model_hook\" | \"tools\")[]","state: InternalAgentState<StructuredResponseFormat>","paths: (\"tools\" | typeof END)[]","shouldReturnDirect: Set<string>","params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }"],"sources":["../../src/agents/ReactAgent.ts"],"sourcesContent":["/* eslint-disable prefer-destructuring, no-instanceof/no-instanceof */\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\nimport {\n AnnotationRoot,\n StateGraph,\n END,\n START,\n Send,\n CompiledStateGraph,\n MessagesAnnotation,\n} from \"@langchain/langgraph\";\nimport {\n isToolMessage,\n isAIMessage,\n ToolMessage,\n AIMessage,\n} from \"@langchain/core/messages\";\n\nimport {\n createReactAgentAnnotationConditional,\n ReactAgentAnnotation,\n} from \"./annotation.js\";\nimport { isClientTool, validateLLMHasNoBoundTools } from \"./utils.js\";\nimport { AgentNode } from \"./nodes/AgentNode.js\";\nimport { ToolNode } from \"./nodes/ToolNode.js\";\nimport type {\n CreateReactAgentParams,\n ClientTool,\n ServerTool,\n InternalAgentState,\n WithStateGraphNodes,\n} from \"./types.js\";\nimport {\n enhanceStateSchemaWithMessageReducer,\n type AnyAnnotationRoot,\n type ToAnnotationRoot,\n} from \"./annotation.js\";\nimport type { ResponseFormatUndefined } from \"./responses.js\";\n\ntype AgentGraph<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> = CompiledStateGraph<\n ToAnnotationRoot<StateSchema>[\"State\"],\n ToAnnotationRoot<StateSchema>[\"Update\"],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n typeof MessagesAnnotation.spec & ToAnnotationRoot<StateSchema>[\"spec\"],\n ReactAgentAnnotation<StructuredResponseFormat>[\"spec\"] &\n ToAnnotationRoot<StateSchema>[\"spec\"],\n ToAnnotationRoot<ContextSchema>[\"spec\"],\n unknown\n>;\n\nexport class ReactAgent<\n StateSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot,\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> {\n #graph: AgentGraph<StateSchema, StructuredResponseFormat, ContextSchema>;\n\n #inputSchema?: AnnotationRoot<ToAnnotationRoot<StateSchema>[\"spec\"]>;\n\n #toolBehaviorVersion: \"v1\" | \"v2\" = \"v2\";\n\n constructor(\n public options: CreateReactAgentParams<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n >\n ) {\n this.#toolBehaviorVersion = options.version ?? this.#toolBehaviorVersion;\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n if (options.llm && typeof options.llm !== \"function\") {\n validateLLMHasNoBoundTools(options.llm);\n }\n\n /**\n * validate that model and llm options are not provided together\n */\n if (options.llm && options.model) {\n throw new Error(\"Cannot provide both `model` and `llm` options.\");\n }\n\n /**\n * validate that either model or llm option is provided\n */\n if (!options.llm && !options.model) {\n throw new Error(\n \"Either `model` or `llm` option must be provided to create an agent.\"\n );\n }\n\n const toolClasses = Array.isArray(options.tools)\n ? options.tools\n : options.tools.tools;\n\n /**\n * If any of the tools are configured to return_directly after running,\n * our graph needs to check if these were called\n */\n const shouldReturnDirect = new Set(\n toolClasses\n .filter(isClientTool)\n .filter((tool) => \"returnDirect\" in tool && tool.returnDirect)\n .map((tool) => tool.name)\n );\n\n const schema = this.options.stateSchema\n ? enhanceStateSchemaWithMessageReducer(this.options.stateSchema)\n : createReactAgentAnnotationConditional<StructuredResponseFormat>(\n this.options.responseFormat !== undefined\n );\n\n const workflow = new StateGraph(schema, this.options.contextSchema);\n\n const allNodeWorkflows = workflow as WithStateGraphNodes<\n \"pre_model_hook\" | \"post_model_hook\" | \"tools\" | \"agent\",\n typeof workflow\n >;\n\n /**\n * Add Nodes\n */\n allNodeWorkflows.addNode(\n \"agent\",\n new AgentNode({\n llm: this.options.llm,\n model: this.options.model,\n prompt: this.options.prompt,\n includeAgentName: this.options.includeAgentName,\n name: this.options.name,\n responseFormat: this.options.responseFormat,\n toolClasses,\n shouldReturnDirect,\n signal: this.options.signal,\n }),\n {\n input: this.#inputSchema,\n }\n );\n\n /**\n * add single tool node for all tools\n */\n if (toolClasses.length > 0) {\n const toolNode = new ToolNode(toolClasses.filter(isClientTool), {\n signal: this.options.signal,\n });\n allNodeWorkflows.addNode(\"tools\", toolNode);\n }\n\n /**\n * setup preModelHook\n */\n if (options.preModelHook) {\n allNodeWorkflows.addNode(\"pre_model_hook\", options.preModelHook);\n }\n\n /**\n * setup postModelHook\n */\n if (options.postModelHook) {\n allNodeWorkflows.addNode(\"post_model_hook\", options.postModelHook);\n }\n\n /**\n * Add Edges\n */\n allNodeWorkflows.addEdge(START, this.#getEntryPoint());\n\n if (this.options.preModelHook) {\n allNodeWorkflows.addEdge(\"pre_model_hook\", \"agent\");\n }\n\n if (this.options.postModelHook) {\n allNodeWorkflows.addEdge(\"agent\", \"post_model_hook\");\n const postHookPaths = this.#getPostModelHookPaths(\n toolClasses.filter(isClientTool)\n );\n if (postHookPaths.length === 1) {\n allNodeWorkflows.addEdge(\"post_model_hook\", postHookPaths[0]);\n } else {\n allNodeWorkflows.addConditionalEdges(\n \"post_model_hook\",\n this.#createPostModelHookRouter(),\n postHookPaths\n );\n }\n } else {\n const modelPaths = this.#getModelPaths(toolClasses.filter(isClientTool));\n if (modelPaths.length === 1) {\n allNodeWorkflows.addEdge(\"agent\", modelPaths[0]);\n } else {\n allNodeWorkflows.addConditionalEdges(\n \"agent\",\n this.#createModelRouter(),\n modelPaths\n );\n }\n }\n\n /**\n * add edges for tools node\n */\n if (toolClasses.length > 0) {\n if (shouldReturnDirect.size > 0) {\n allNodeWorkflows.addConditionalEdges(\n \"tools\",\n this.#createToolsRouter(shouldReturnDirect),\n [this.#getEntryPoint(), END]\n );\n } else {\n allNodeWorkflows.addEdge(\"tools\", this.#getEntryPoint());\n }\n }\n\n /**\n * compile the graph\n */\n this.#graph = allNodeWorkflows.compile({\n checkpointer: this.options.checkpointer ?? this.options.checkpointSaver,\n interruptBefore: this.options.interruptBefore,\n interruptAfter: this.options.interruptAfter,\n store: this.options.store,\n name: this.options.name,\n description: this.options.description,\n });\n }\n\n /**\n * Get the compiled graph.\n */\n get graph(): AgentGraph<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema\n > {\n return this.#graph;\n }\n\n #getEntryPoint() {\n const entryPoint = this.options.preModelHook ? \"pre_model_hook\" : \"agent\";\n return entryPoint;\n }\n\n /**\n * Get possible edge destinations from post_model_hook node.\n */\n #getPostModelHookPaths(toolClasses: (ClientTool | ServerTool)[]) {\n const paths: (typeof END | \"agent\" | \"pre_model_hook\" | \"tools\")[] = [];\n if (toolClasses.length > 0) {\n paths.push(this.#getEntryPoint(), \"tools\");\n }\n paths.push(END);\n return paths;\n }\n\n #createPostModelHookRouter() {\n return (state: InternalAgentState<StructuredResponseFormat>) => {\n const messages = state.messages;\n const toolMessages = messages.filter(isToolMessage);\n const lastAiMessage = messages.filter(isAIMessage).at(-1);\n const pendingToolCalls = lastAiMessage?.tool_calls?.filter(\n (call) => !toolMessages.some((m) => m.tool_call_id === call.id)\n );\n\n if (pendingToolCalls && pendingToolCalls.length > 0) {\n /**\n * The tool node processes a single message.\n * All tool calls in the message are executed in parallel within the tool node.\n * @deprecated likely to be removed in the next version of the agent\n */\n if (this.#toolBehaviorVersion === \"v1\") {\n return \"tools\";\n }\n\n /**\n * The tool node processes a single tool call. Tool calls are distributed across\n * multiple instances of the tool node using the Send API.\n */\n return pendingToolCalls.map(\n (toolCall) => new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n }\n\n if (messages.at(-1) instanceof ToolMessage) {\n return this.#getEntryPoint();\n }\n\n return END;\n };\n }\n\n /**\n * Get possible edge destinations from model node.\n * @param toolClasses names of tools to call\n * @returns list of possible edge destinations\n */\n #getModelPaths(\n toolClasses: (ClientTool | ServerTool)[]\n ): (\"tools\" | typeof END)[] {\n const paths: (\"tools\" | typeof END)[] = [];\n if (toolClasses.length > 0) {\n paths.push(\"tools\");\n }\n\n paths.push(END);\n\n return paths;\n }\n\n /**\n * Create routing function for model node conditional edges.\n */\n #createModelRouter() {\n /**\n * determine if the agent should continue or not\n */\n return (state: InternalAgentState<StructuredResponseFormat>) => {\n const messages = state.messages;\n const lastMessage = messages.at(-1);\n\n if (\n !(lastMessage instanceof AIMessage) ||\n !lastMessage.tool_calls ||\n lastMessage.tool_calls.length === 0\n ) {\n if (this.options.postModelHook) {\n return \"post_model_hook\";\n }\n\n return END;\n }\n\n if (this.options.postModelHook) {\n return \"post_model_hook\";\n }\n\n /**\n * The tool node processes a single message.\n */\n if (this.#toolBehaviorVersion === \"v1\") {\n return \"tools\";\n }\n\n /**\n * Route to tools node\n */\n return lastMessage.tool_calls.map(\n (toolCall) => new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n };\n }\n\n /**\n * Create routing function for tools node conditional edges.\n */\n #createToolsRouter(shouldReturnDirect: Set<string>) {\n return (state: InternalAgentState<StructuredResponseFormat>) => {\n const messages = state.messages;\n const lastMessage = messages[messages.length - 1];\n\n // Check if we just executed a returnDirect tool\n if (\n lastMessage instanceof ToolMessage &&\n lastMessage.name &&\n shouldReturnDirect.has(lastMessage.name)\n ) {\n // If we have a response format, route to agent to generate structured response\n // Otherwise, return directly\n return this.options.responseFormat ? this.#getEntryPoint() : END;\n }\n\n // For non-returnDirect tools, always route back to agent\n return this.#getEntryPoint();\n };\n }\n\n /**\n * @inheritdoc\n */\n get invoke(): AgentGraph<StateSchema, StructuredResponseFormat>[\"invoke\"] {\n return this.#graph.invoke.bind(this.#graph);\n }\n\n /**\n * @inheritdoc\n */\n get stream(): AgentGraph<StateSchema, StructuredResponseFormat>[\"stream\"] {\n return this.#graph.stream.bind(this.#graph);\n }\n\n /**\n * @inheritdoc\n */\n get streamEvents(): AgentGraph<\n StateSchema,\n StructuredResponseFormat\n >[\"streamEvents\"] {\n return this.#graph.streamEvents.bind(this.#graph);\n }\n\n /**\n * Visualize the graph as a PNG image.\n * @param params - Parameters for the drawMermaidPng method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns PNG image as a buffer\n */\n async drawMermaidPng(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n const image = await representation.drawMermaidPng(params);\n const arrayBuffer = await image.arrayBuffer();\n const buffer = new Uint8Array(arrayBuffer);\n return buffer;\n }\n\n /**\n * Draw the graph as a Mermaid string.\n * @param params - Parameters for the drawMermaid method.\n * @param params.withStyles - Whether to include styles in the graph.\n * @param params.curveStyle - The style of the graph's curves.\n * @param params.nodeColors - The colors of the graph's nodes.\n * @param params.wrapLabelNWords - The maximum number of words to wrap in a node's label.\n * @param params.backgroundColor - The background color of the graph.\n * @returns Mermaid string\n */\n async drawMermaid(params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }) {\n const representation = await this.#graph.getGraphAsync();\n return representation.drawMermaid(params);\n }\n}\n"],"mappings":";;;;;;;;AAyDA,IAAa,aAAb,MAME;CACA;CAEA;CAEA,uBAAoC;CAEpC,YACSA,SAKP;EALO;EAMP,KAAKC,uBAAuB,QAAQ,WAAW,KAAKA;;;;AAKpD,MAAI,QAAQ,OAAO,OAAO,QAAQ,QAAQ,YACxC,2BAA2B,QAAQ,IAAI;;;;AAMzC,MAAI,QAAQ,OAAO,QAAQ,MACzB,OAAM,IAAI,MAAM;;;;AAMlB,MAAI,CAAC,QAAQ,OAAO,CAAC,QAAQ,MAC3B,OAAM,IAAI,MACR;EAIJ,MAAM,cAAc,MAAM,QAAQ,QAAQ,MAAM,GAC5C,QAAQ,QACR,QAAQ,MAAM;;;;;EAMlB,MAAM,qBAAqB,IAAI,IAC7B,YACG,OAAO,aAAa,CACpB,OAAO,CAAC,SAAS,kBAAkB,QAAQ,KAAK,aAAa,CAC7D,IAAI,CAAC,SAAS,KAAK,KAAK;EAG7B,MAAM,SAAS,KAAK,QAAQ,cACxB,qCAAqC,KA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D,MAAM,QAAQ,MAAM,eAAe,eAAe,OAAO;EACzD,MAAM,cAAc,MAAM,MAAM,aAAa;EAC7C,MAAM,SAAS,IAAI,WAAW;AAC9B,SAAO;CACR;;;;;;;;;;;CAYD,MAAM,YAAYM,QAMf;EACD,MAAM,iBAAiB,MAAM,KAAKN,OAAO,eAAe;AACxD,SAAO,eAAe,YAAY,OAAO;CAC1C;AACF"}
@@ -1,5 +1,6 @@
1
1
  const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
2
  const __langchain_langgraph = require_rolldown_runtime.__toESM(require("@langchain/langgraph"));
3
+ const __langchain_core_utils_types = require_rolldown_runtime.__toESM(require("@langchain/core/utils/types"));
3
4
 
4
5
  //#region src/agents/annotation.ts
5
6
  const PreHookAnnotation = __langchain_langgraph.Annotation.Root({
@@ -23,7 +24,126 @@ function createReactAgentAnnotationConditional(hasStructuredResponse = true) {
23
24
  structuredResponse: (0, __langchain_langgraph.Annotation)()
24
25
  });
25
26
  }
27
+ /**
28
+ * Enhances a state schema to ensure proper message handling.
29
+ * If a Zod schema is provided, it creates an annotation that includes the messagesStateReducer
30
+ * and infers appropriate reducers for all other fields.
31
+ *
32
+ * @param stateSchema - The state schema to enhance.
33
+ * @returns The enhanced state schema.
34
+ */
35
+ function enhanceStateSchemaWithMessageReducer(stateSchema) {
36
+ /**
37
+ * If it's already an annotation, return as-is
38
+ */
39
+ if (typeof stateSchema === "object" && "State" in stateSchema) return stateSchema;
40
+ /**
41
+ * If it's a Zod schema, create annotations for all fields
42
+ */
43
+ if ((0, __langchain_core_utils_types.isInteropZodSchema)(stateSchema)) {
44
+ const shape = (0, __langchain_core_utils_types.getInteropZodObjectShape)(stateSchema);
45
+ const annotationFields = {};
46
+ /**
47
+ * Process each field in the Zod schema
48
+ */
49
+ for (const [key, zodType] of Object.entries(shape)) annotationFields[key] = key === "messages" ? (0, __langchain_langgraph.Annotation)({
50
+ reducer: __langchain_langgraph.messagesStateReducer,
51
+ default: () => []
52
+ }) : createAnnotationForZodType(zodType);
53
+ /**
54
+ * Ensure messages field exists even if not in the Zod schema
55
+ */
56
+ if (!annotationFields.messages) annotationFields.messages = (0, __langchain_langgraph.Annotation)({
57
+ reducer: __langchain_langgraph.messagesStateReducer,
58
+ default: () => []
59
+ });
60
+ return __langchain_langgraph.Annotation.Root(annotationFields);
61
+ }
62
+ /**
63
+ * Fallback: create a base annotation with message reducer only
64
+ */
65
+ return __langchain_langgraph.Annotation.Root({ messages: (0, __langchain_langgraph.Annotation)({
66
+ reducer: __langchain_langgraph.messagesStateReducer,
67
+ default: () => []
68
+ }) });
69
+ }
70
+ /**
71
+ * Type configuration for different Zod types
72
+ */
73
+ const ZOD_TYPE_CONFIGS = {
74
+ ZodString: {
75
+ reducer: (_, update) => update,
76
+ fallbackDefault: ""
77
+ },
78
+ ZodNumber: {
79
+ reducer: (_, update) => update,
80
+ fallbackDefault: 0
81
+ },
82
+ ZodBoolean: {
83
+ reducer: (_, update) => update,
84
+ fallbackDefault: false
85
+ },
86
+ ZodArray: {
87
+ reducer: (_, update) => update,
88
+ fallbackDefault: []
89
+ },
90
+ ZodRecord: {
91
+ reducer: (current, update) => ({
92
+ ...current,
93
+ ...update
94
+ }),
95
+ fallbackDefault: {}
96
+ },
97
+ ZodObject: {
98
+ reducer: (current, update) => ({
99
+ ...current,
100
+ ...update
101
+ }),
102
+ fallbackDefault: {}
103
+ }
104
+ };
105
+ /**
106
+ * Creates an annotation based on type configuration and default value
107
+ */
108
+ function createAnnotationFromConfig(config, defaultValueFn) {
109
+ return (0, __langchain_langgraph.Annotation)({
110
+ reducer: config.reducer,
111
+ default: defaultValueFn
112
+ });
113
+ }
114
+ /**
115
+ * Creates an appropriate annotation for a given Zod type.
116
+ */
117
+ function createAnnotationForZodType(zodType) {
118
+ const typeName = zodType._def?.typeName;
119
+ const defaultGetter = (0, __langchain_core_utils_types.getInteropZodDefaultGetter)(zodType);
120
+ const isOptional = typeName === "ZodOptional";
121
+ /**
122
+ * Handle Zod wrapper first
123
+ */
124
+ if (typeName === "ZodDefault" || typeName === "ZodOptional" || typeName === "ZodNullable") {
125
+ const innerTypeName = zodType._def.innerType._def?.typeName;
126
+ const config$1 = ZOD_TYPE_CONFIGS[innerTypeName];
127
+ return config$1 ? createAnnotationFromConfig(config$1, () => defaultGetter?.() || (isOptional ? void 0 : config$1?.fallbackDefault)) : (0, __langchain_langgraph.Annotation)({
128
+ reducer: (_, update) => update,
129
+ default: () => defaultGetter?.()
130
+ });
131
+ }
132
+ /**
133
+ * Handle regular types
134
+ */
135
+ const config = ZOD_TYPE_CONFIGS[typeName];
136
+ if (config) return createAnnotationFromConfig(config, () => defaultGetter?.() || config?.fallbackDefault);
137
+ /**
138
+ * Fallback for unknown types
139
+ */
140
+ return (0, __langchain_langgraph.Annotation)({
141
+ reducer: (_, update) => update,
142
+ default: () => defaultGetter?.()
143
+ });
144
+ }
26
145
 
27
146
  //#endregion
28
147
  exports.createReactAgentAnnotationConditional = createReactAgentAnnotationConditional;
148
+ exports.enhanceStateSchemaWithMessageReducer = enhanceStateSchemaWithMessageReducer;
29
149
  //# sourceMappingURL=annotation.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"annotation.cjs","names":["Annotation","messagesStateReducer"],"sources":["../../src/agents/annotation.ts"],"sourcesContent":["import { BaseMessage } from \"@langchain/core/messages\";\nimport {\n Annotation,\n Messages,\n AnnotationRoot,\n messagesStateReducer,\n} from \"@langchain/langgraph\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport type { InteropZodObject } from \"@langchain/core/utils/types\";\nimport type { ResponseFormatUndefined } from \"./responses.js\";\n\nexport const PreHookAnnotation = Annotation.Root({\n llmInputMessages: Annotation<BaseMessage[], Messages>({\n reducer: (_, update) => messagesStateReducer([], update),\n default: () => [],\n }),\n messages: Annotation<BaseMessage[], Messages>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n});\nexport type PreHookAnnotation = typeof PreHookAnnotation;\n\n// Base annotation without structuredResponse (for ResponseFormatUndefined)\nexport const createReactAgentBaseAnnotation = () =>\n Annotation.Root({\n messages: Annotation<BaseMessage[], Messages>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n });\n\n// Full annotation with structuredResponse (for regular cases)\nconst createReactAgentAnnotation = <\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>\n>() =>\n Annotation.Root({\n messages: Annotation<BaseMessage[], Messages>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n structuredResponse: Annotation<T>,\n });\n\n// Create annotation conditionally - for ResponseFormatUndefined, don't include structuredResponse\nexport function createReactAgentAnnotationConditional<\n T extends Record<string, any> | ResponseFormatUndefined\n>(hasStructuredResponse = true) {\n const baseAnnotation = {\n messages: Annotation<BaseMessage[], Messages>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n };\n\n if (!hasStructuredResponse) {\n return Annotation.Root(baseAnnotation);\n }\n\n return Annotation.Root({\n ...baseAnnotation,\n structuredResponse:\n Annotation<T extends ResponseFormatUndefined ? never : T>(),\n });\n}\n\n// Helper type to select the right annotation based on the response format type\nexport type ReactAgentAnnotation<\n T extends Record<string, any> | ResponseFormatUndefined\n> = T extends ResponseFormatUndefined\n ? ReturnType<typeof createReactAgentBaseAnnotation>\n : T extends Record<string, any>\n ? ReturnType<typeof createReactAgentAnnotation<T>>\n : never;\n\nexport type ToAnnotationRoot<A extends AnyAnnotationRoot | InteropZodObject> =\n A extends AnyAnnotationRoot\n ? A\n : A extends InteropZodObject\n ? AnnotationRoot<InteropZodToStateDefinition<A>>\n : never;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyAnnotationRoot = AnnotationRoot<any>;\n"],"mappings":";;;;AAWA,MAAa,oBAAoBA,iCAAW,KAAK;CAC/C,wDAAsD;EACpD,SAAS,CAAC,GAAG,2DAAgC,CAAE,GAAE,OAAO;EACxD,SAAS,MAAM,CAAE;CAClB,EAAC;CACF,gDAA8C;EAC5C,SAASC;EACT,SAAS,MAAM,CAAE;CAClB,EAAC;AACH,EAAC;AA0BF,SAAgB,sCAEd,wBAAwB,MAAM;CAC9B,MAAM,iBAAiB,EACrB,gDAA8C;EAC5C,SAASA;EACT,SAAS,MAAM,CAAE;CAClB,EAAC,CACH;AAED,KAAI,CAAC,sBACH,QAAOD,iCAAW,KAAK,eAAe;AAGxC,QAAOA,iCAAW,KAAK;EACrB,GAAG;EACH,2DAC6D;CAC9D,EAAC;AACH"}
1
+ {"version":3,"file":"annotation.cjs","names":["PreHookAnnotation: AnnotationRoot<{\n llmInputMessages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}>","Annotation","messagesStateReducer","stateSchema: AnyAnnotationRoot | InteropZodObject","annotationFields: Record<string, any>","_: unknown","update: unknown","current: unknown[]","update: unknown[]","config: (typeof ZOD_TYPE_CONFIGS)[keyof typeof ZOD_TYPE_CONFIGS]","defaultValueFn: () => unknown","zodType: any","config"],"sources":["../../src/agents/annotation.ts"],"sourcesContent":["import { BaseMessage } from \"@langchain/core/messages\";\nimport {\n Annotation,\n Messages,\n AnnotationRoot,\n messagesStateReducer,\n type BinaryOperatorAggregate,\n type LastValue,\n} from \"@langchain/langgraph\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport {\n isInteropZodSchema,\n getInteropZodObjectShape,\n getInteropZodDefaultGetter,\n type InteropZodObject,\n} from \"@langchain/core/utils/types\";\nimport type { ResponseFormatUndefined } from \"./responses.js\";\n\nexport const PreHookAnnotation: AnnotationRoot<{\n llmInputMessages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}> = Annotation.Root({\n llmInputMessages: Annotation<BaseMessage[], Messages>({\n reducer: (_, update) => messagesStateReducer([], update),\n default: () => [],\n }),\n messages: Annotation<BaseMessage[], Messages>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n});\nexport type PreHookAnnotation = typeof PreHookAnnotation;\n\n// Base annotation without structuredResponse (for ResponseFormatUndefined)\nexport const createReactAgentBaseAnnotation = () =>\n Annotation.Root({\n messages: Annotation<BaseMessage[], Messages>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n });\n\n// Full annotation with structuredResponse (for regular cases)\nconst createReactAgentAnnotation = <\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>\n>(): AnnotationRoot<{\n structuredResponse: LastValue<T>;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}> =>\n Annotation.Root({\n messages: Annotation<BaseMessage[], Messages>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n structuredResponse: Annotation<T>(),\n });\n\n// Create annotation conditionally - for ResponseFormatUndefined, don't include structuredResponse\nexport function createReactAgentAnnotationConditional<\n T extends Record<string, any> | ResponseFormatUndefined\n>(\n hasStructuredResponse = true\n): AnnotationRoot<{\n structuredResponse: LastValue<T extends ResponseFormatUndefined ? never : T>;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}> {\n const baseAnnotation = {\n messages: Annotation<BaseMessage[], Messages>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n };\n\n if (!hasStructuredResponse) {\n return Annotation.Root(baseAnnotation) as AnnotationRoot<{\n structuredResponse: LastValue<\n T extends ResponseFormatUndefined ? never : T\n >;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n }>;\n }\n\n return Annotation.Root({\n ...baseAnnotation,\n structuredResponse:\n Annotation<T extends ResponseFormatUndefined ? never : T>(),\n });\n}\n\n// Helper type to select the right annotation based on the response format type\nexport type ReactAgentAnnotation<\n T extends Record<string, any> | ResponseFormatUndefined\n> = T extends ResponseFormatUndefined\n ? ReturnType<typeof createReactAgentBaseAnnotation>\n : T extends Record<string, any>\n ? ReturnType<typeof createReactAgentAnnotation<T>>\n : never;\n\nexport type ToAnnotationRoot<A extends AnyAnnotationRoot | InteropZodObject> =\n A extends AnyAnnotationRoot\n ? A\n : A extends InteropZodObject\n ? AnnotationRoot<InteropZodToStateDefinition<A>>\n : never;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyAnnotationRoot = AnnotationRoot<any>;\n\n/**\n * Enhances a state schema to ensure proper message handling.\n * If a Zod schema is provided, it creates an annotation that includes the messagesStateReducer\n * and infers appropriate reducers for all other fields.\n *\n * @param stateSchema - The state schema to enhance.\n * @returns The enhanced state schema.\n */\nexport function enhanceStateSchemaWithMessageReducer(\n stateSchema: AnyAnnotationRoot | InteropZodObject\n) {\n /**\n * If it's already an annotation, return as-is\n */\n if (typeof stateSchema === \"object\" && \"State\" in stateSchema) {\n return stateSchema;\n }\n\n /**\n * If it's a Zod schema, create annotations for all fields\n */\n if (isInteropZodSchema(stateSchema)) {\n const shape = getInteropZodObjectShape(stateSchema);\n const annotationFields: Record<string, any> = {};\n\n /**\n * Process each field in the Zod schema\n */\n for (const [key, zodType] of Object.entries(shape)) {\n annotationFields[key] =\n key === \"messages\"\n ? /**\n * Special handling for messages field - always use messagesStateReducer\n */\n Annotation<BaseMessage[]>({\n reducer: messagesStateReducer,\n default: () => [],\n })\n : /**\n * For other fields, create appropriate annotations based on type\n */\n createAnnotationForZodType(zodType);\n }\n\n /**\n * Ensure messages field exists even if not in the Zod schema\n */\n if (!annotationFields.messages) {\n annotationFields.messages = Annotation<BaseMessage[]>({\n reducer: messagesStateReducer,\n default: () => [],\n });\n }\n\n return Annotation.Root(annotationFields);\n }\n\n /**\n * Fallback: create a base annotation with message reducer only\n */\n return Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n });\n}\n\n/**\n * Type configuration for different Zod types\n */\nconst ZOD_TYPE_CONFIGS = {\n ZodString: {\n reducer: (_: unknown, update: unknown) => update,\n fallbackDefault: \"\",\n },\n ZodNumber: {\n reducer: (_: unknown, update: unknown) => update,\n fallbackDefault: 0,\n },\n ZodBoolean: {\n reducer: (_: unknown, update: unknown) => update,\n fallbackDefault: false,\n },\n ZodArray: {\n reducer: (_: unknown, update: unknown) => update,\n fallbackDefault: [] as unknown[],\n },\n ZodRecord: {\n reducer: (current: unknown[], update: unknown[]) => ({\n ...current,\n ...update,\n }),\n fallbackDefault: {} as Record<string, unknown>,\n },\n ZodObject: {\n reducer: (current: unknown[], update: unknown[]) => ({\n ...current,\n ...update,\n }),\n fallbackDefault: {} as Record<string, unknown>,\n },\n} as const;\n\n/**\n * Creates an annotation based on type configuration and default value\n */\nfunction createAnnotationFromConfig(\n config: (typeof ZOD_TYPE_CONFIGS)[keyof typeof ZOD_TYPE_CONFIGS],\n defaultValueFn: () => unknown\n) {\n return Annotation<any>({\n reducer: config.reducer,\n default: defaultValueFn,\n });\n}\n\n/**\n * Creates an appropriate annotation for a given Zod type.\n */\nfunction createAnnotationForZodType(zodType: any): any {\n const typeName = zodType._def?.typeName;\n const defaultGetter = getInteropZodDefaultGetter(zodType);\n const isOptional = typeName === \"ZodOptional\";\n\n /**\n * Handle Zod wrapper first\n */\n if (\n typeName === \"ZodDefault\" ||\n typeName === \"ZodOptional\" ||\n typeName === \"ZodNullable\"\n ) {\n const innerTypeName = zodType._def.innerType._def?.typeName;\n const config =\n ZOD_TYPE_CONFIGS[innerTypeName as keyof typeof ZOD_TYPE_CONFIGS];\n return config\n ? createAnnotationFromConfig(\n config,\n () =>\n defaultGetter?.() ||\n (isOptional ? undefined : config?.fallbackDefault)\n )\n : Annotation<unknown>({\n reducer: (_: unknown, update: unknown) => update,\n default: () => defaultGetter?.(),\n });\n }\n\n /**\n * Handle regular types\n */\n const config = ZOD_TYPE_CONFIGS[typeName as keyof typeof ZOD_TYPE_CONFIGS];\n if (config) {\n return createAnnotationFromConfig(\n config,\n () => defaultGetter?.() || config?.fallbackDefault\n );\n }\n\n /**\n * Fallback for unknown types\n */\n return Annotation<unknown>({\n reducer: (_: unknown, update: unknown) => update,\n default: () => defaultGetter?.(),\n });\n}\n"],"mappings":";;;;;AAkBA,M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oB;EAC1C,iBAAiB;CAClB;CACD,UAAU;EACR,SAAS,CAACD,GAAYC,WAAoB;EAC1C,iBAAiB,CAAE;CACpB;CACD,WAAW;EACT,SAAS,CAACC,SAAoBC,YAAuB;GACnD,GAAG;GACH,GAAG;EACJ;EACD,iBAAiB,CAAE;CACpB;CACD,WAAW;EACT,SAAS,CAACD,SAAoBC,YAAuB;GACnD,GAAG;GACH,GAAG;EACJ;EACD,iBAAiB,CAAE;CACpB;AACF;;;;AAKD,SAAS,2BACPC,QACAC,gBACA;AACA,8CAAuB;EACrB,SAAS,OAAO;EAChB,SAAS;CACV,EAAC;AACH;;;;AAKD,SAAS,2BAA2BC,SAAmB;CACrD,MAAM,WAAW,QAAQ,MAAM;CAC/B,MAAM,6EAA2C,QAAQ;CACzD,MAAM,aAAa,aAAa;;;;AAKhC,KACE,aAAa,gBACb,aAAa,iBACb,aAAa,eACb;EACA,MAAM,gBAAgB,QAAQ,KAAK,UAAU,MAAM;EACnD,MAAMC,WACJ,iBAAiB;AACnB,SAAOA,WACH,2BACEA,UACA,MACE,iBAAiB,KAChB,aAAa,SAAYA,UAAQ,iBACrC,yCACmB;GAClB,SAAS,CAACP,GAAYC,WAAoB;GAC1C,SAAS,MAAM,iBAAiB;EACjC,EAAC;CACP;;;;CAKD,MAAM,SAAS,iBAAiB;AAChC,KAAI,OACF,QAAO,2BACL,QACA,MAAM,iBAAiB,IAAI,QAAQ,gBACpC;;;;AAMH,8CAA2B;EACzB,SAAS,CAACD,GAAYC,WAAoB;EAC1C,SAAS,MAAM,iBAAiB;CACjC,EAAC;AACH"}
@@ -1,30 +1,25 @@
1
1
  import { ResponseFormatUndefined } from "./responses.cjs";
2
2
  import { InteropZodObject } from "@langchain/core/utils/types";
3
3
  import { BaseMessage } from "@langchain/core/messages";
4
- import * as _langchain_langgraph0 from "@langchain/langgraph";
5
- import { AnnotationRoot, Messages } from "@langchain/langgraph";
4
+ import { AnnotationRoot, BinaryOperatorAggregate, LastValue, Messages } from "@langchain/langgraph";
6
5
  import { InteropZodToStateDefinition } from "@langchain/langgraph/zod";
7
6
 
8
7
  //#region src/agents/annotation.d.ts
9
8
  declare const PreHookAnnotation: AnnotationRoot<{
10
- llmInputMessages: _langchain_langgraph0.BinaryOperatorAggregate<BaseMessage[], Messages>;
11
- messages: _langchain_langgraph0.BinaryOperatorAggregate<BaseMessage[], Messages>;
9
+ llmInputMessages: BinaryOperatorAggregate<BaseMessage[], Messages>;
10
+ messages: BinaryOperatorAggregate<BaseMessage[], Messages>;
12
11
  }>;
13
12
  type PreHookAnnotation = typeof PreHookAnnotation;
14
13
  // Base annotation without structuredResponse (for ResponseFormatUndefined)
15
14
  declare const createReactAgentBaseAnnotation: () => AnnotationRoot<{
16
- messages: _langchain_langgraph0.BinaryOperatorAggregate<BaseMessage[], Messages>;
15
+ messages: BinaryOperatorAggregate<BaseMessage[], Messages>;
17
16
  }>;
18
17
  // Full annotation with structuredResponse (for regular cases)
19
18
  declare const createReactAgentAnnotation: <
20
19
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
21
20
  T extends Record<string, any> = Record<string, any>>() => AnnotationRoot<{
22
- messages: _langchain_langgraph0.BinaryOperatorAggregate<BaseMessage[], Messages>;
23
- structuredResponse: {
24
- (): _langchain_langgraph0.LastValue<T>;
25
- (annotation: _langchain_langgraph0.SingleReducer<T, T>): _langchain_langgraph0.BinaryOperatorAggregate<T, T>;
26
- Root: <S extends _langchain_langgraph0.StateDefinition>(sd: S) => AnnotationRoot<S>;
27
- };
21
+ structuredResponse: LastValue<T>;
22
+ messages: BinaryOperatorAggregate<BaseMessage[], Messages>;
28
23
  }>;
29
24
  // Create annotation conditionally - for ResponseFormatUndefined, don't include structuredResponse
30
25
 
@@ -33,6 +28,15 @@ type ReactAgentAnnotation<T extends Record<string, any> | ResponseFormatUndefine
33
28
  type ToAnnotationRoot<A extends AnyAnnotationRoot | InteropZodObject> = A extends AnyAnnotationRoot ? A : A extends InteropZodObject ? AnnotationRoot<InteropZodToStateDefinition<A>> : never;
34
29
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
35
30
  type AnyAnnotationRoot = AnnotationRoot<any>;
31
+ /**
32
+ * Enhances a state schema to ensure proper message handling.
33
+ * If a Zod schema is provided, it creates an annotation that includes the messagesStateReducer
34
+ * and infers appropriate reducers for all other fields.
35
+ *
36
+ * @param stateSchema - The state schema to enhance.
37
+ * @returns The enhanced state schema.
38
+ */
39
+
36
40
  //#endregion
37
41
  export { AnyAnnotationRoot, PreHookAnnotation, ReactAgentAnnotation, ToAnnotationRoot };
38
42
  //# sourceMappingURL=annotation.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"annotation.d.cts","names":["BaseMessage","Messages","AnnotationRoot","InteropZodToStateDefinition","InteropZodObject","ResponseFormatUndefined","PreHookAnnotation","_langchain_langgraph0","BinaryOperatorAggregate","createReactAgentBaseAnnotation","createReactAgentAnnotation","Record","T","LastValue","SingleReducer","StateDefinition","S","createReactAgentAnnotationConditional","ReactAgentAnnotation","ReturnType","ToAnnotationRoot","AnyAnnotationRoot","A"],"sources":["../../src/agents/annotation.d.ts"],"sourcesContent":["import { BaseMessage } from \"@langchain/core/messages\";\nimport { Messages, AnnotationRoot } from \"@langchain/langgraph\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport type { InteropZodObject } from \"@langchain/core/utils/types\";\nimport type { ResponseFormatUndefined } from \"./responses.js\";\nexport declare const PreHookAnnotation: AnnotationRoot<{\n llmInputMessages: import(\"@langchain/langgraph\").BinaryOperatorAggregate<BaseMessage[], Messages>;\n messages: import(\"@langchain/langgraph\").BinaryOperatorAggregate<BaseMessage[], Messages>;\n}>;\nexport type PreHookAnnotation = typeof PreHookAnnotation;\n// Base annotation without structuredResponse (for ResponseFormatUndefined)\nexport declare const createReactAgentBaseAnnotation: () => AnnotationRoot<{\n messages: import(\"@langchain/langgraph\").BinaryOperatorAggregate<BaseMessage[], Messages>;\n}>;\n// Full annotation with structuredResponse (for regular cases)\ndeclare const createReactAgentAnnotation: <\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nT extends Record<string, any> = Record<string, any>>() => AnnotationRoot<{\n messages: import(\"@langchain/langgraph\").BinaryOperatorAggregate<BaseMessage[], Messages>;\n structuredResponse: {\n (): import(\"@langchain/langgraph\").LastValue<T>;\n (annotation: import(\"@langchain/langgraph\").SingleReducer<T, T>): import(\"@langchain/langgraph\").BinaryOperatorAggregate<T, T>;\n Root: <S extends import(\"@langchain/langgraph\").StateDefinition>(sd: S) => AnnotationRoot<S>;\n };\n}>;\n// Create annotation conditionally - for ResponseFormatUndefined, don't include structuredResponse\nexport declare function createReactAgentAnnotationConditional<T extends Record<string, any> | ResponseFormatUndefined>(hasStructuredResponse?: boolean): AnnotationRoot<{\n messages: import(\"@langchain/langgraph\").BinaryOperatorAggregate<BaseMessage[], Messages>;\n}> | AnnotationRoot<{\n messages: import(\"@langchain/langgraph\").BinaryOperatorAggregate<BaseMessage[], Messages>;\n structuredResponse: import(\"@langchain/langgraph\").LastValue<T extends ResponseFormatUndefined ? never : T>;\n}>;\n// Helper type to select the right annotation based on the response format type\nexport type ReactAgentAnnotation<T extends Record<string, any> | ResponseFormatUndefined> = T extends ResponseFormatUndefined ? ReturnType<typeof createReactAgentBaseAnnotation> : T extends Record<string, any> ? ReturnType<typeof createReactAgentAnnotation<T>> : never;\nexport type ToAnnotationRoot<A extends AnyAnnotationRoot | InteropZodObject> = A extends AnyAnnotationRoot ? A : A extends InteropZodObject ? AnnotationRoot<InteropZodToStateDefinition<A>> : never;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyAnnotationRoot = AnnotationRoot<any>;\nexport {};\n"],"mappings":";;;;;;;;cAKqBM,mBAAmBJ;oBAC4DK,qBAAAA,CAA/CC,wBAAwBR,eAAeC;YACAM,qBAAAA,CAA/CC,wBAAwBR,eAAeC;AAFpF,CAAA,CAAA;AAGE,KACUK,iBAAAA,GADV,OACqCA,iBADrC;;AAF0FL,cAKvEQ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BT,gBAdhBS,CAAAA,GAcoCS,CAdpCT,SAc8CQ,iBAd9CR,GAckES,CAdlET,GAcsES,CAdtET,SAcgFT,gBAdhFS,GAcmGX,cAdnGW,CAckHV,2BAdlHU,CAc8IS,CAd9IT,CAAAA,CAAAA,GAAAA,KAAAA;;AAC0BD,KAezDS,iBAAAA,GAAoBnB,cAfqCU,CAAAA,GAAAA,CAAAA"}
1
+ {"version":3,"file":"annotation.d.cts","names":["BaseMessage","Messages","AnnotationRoot","BinaryOperatorAggregate","LastValue","InteropZodToStateDefinition","InteropZodObject","ResponseFormatUndefined","PreHookAnnotation","createReactAgentBaseAnnotation","createReactAgentAnnotation","Record","T","createReactAgentAnnotationConditional","ReactAgentAnnotation","ReturnType","ToAnnotationRoot","AnyAnnotationRoot","A","enhanceStateSchemaWithMessageReducer"],"sources":["../../src/agents/annotation.d.ts"],"sourcesContent":["import { BaseMessage } from \"@langchain/core/messages\";\nimport { Messages, AnnotationRoot, type BinaryOperatorAggregate, type LastValue } from \"@langchain/langgraph\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport { type InteropZodObject } from \"@langchain/core/utils/types\";\nimport type { ResponseFormatUndefined } from \"./responses.js\";\nexport declare const PreHookAnnotation: AnnotationRoot<{\n llmInputMessages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}>;\nexport type PreHookAnnotation = typeof PreHookAnnotation;\n// Base annotation without structuredResponse (for ResponseFormatUndefined)\nexport declare const createReactAgentBaseAnnotation: () => AnnotationRoot<{\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}>;\n// Full annotation with structuredResponse (for regular cases)\ndeclare const createReactAgentAnnotation: <\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nT extends Record<string, any> = Record<string, any>>() => AnnotationRoot<{\n structuredResponse: LastValue<T>;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}>;\n// Create annotation conditionally - for ResponseFormatUndefined, don't include structuredResponse\nexport declare function createReactAgentAnnotationConditional<T extends Record<string, any> | ResponseFormatUndefined>(hasStructuredResponse?: boolean): AnnotationRoot<{\n structuredResponse: LastValue<T extends ResponseFormatUndefined ? never : T>;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}>;\n// Helper type to select the right annotation based on the response format type\nexport type ReactAgentAnnotation<T extends Record<string, any> | ResponseFormatUndefined> = T extends ResponseFormatUndefined ? ReturnType<typeof createReactAgentBaseAnnotation> : T extends Record<string, any> ? ReturnType<typeof createReactAgentAnnotation<T>> : never;\nexport type ToAnnotationRoot<A extends AnyAnnotationRoot | InteropZodObject> = A extends AnyAnnotationRoot ? A : A extends InteropZodObject ? AnnotationRoot<InteropZodToStateDefinition<A>> : never;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyAnnotationRoot = AnnotationRoot<any>;\n/**\n * Enhances a state schema to ensure proper message handling.\n * If a Zod schema is provided, it creates an annotation that includes the messagesStateReducer\n * and infers appropriate reducers for all other fields.\n *\n * @param stateSchema - The state schema to enhance.\n * @returns The enhanced state schema.\n */\nexport declare function enhanceStateSchemaWithMessageReducer(stateSchema: AnyAnnotationRoot | InteropZodObject): AnnotationRoot<{\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n}> | AnyAnnotationRoot;\nexport {};\n"],"mappings":";;;;;;;cAKqBQ,mBAAmBN;oBAClBC,wBAAwBH,eAAeC;EADxCO,QAAAA,EAEPL,uBACZ,CADoCH,WACpC,EAAA,EADmDC,QACnD,CAAA;CAAA,CAAA;AAF4CD,KAGlCQ,iBAAAA,GAHkCR,OAGPQ,iBAHOR;;AAAxBG,cAKDM,8BALCN,EAAAA,GAAAA,GAKqCD,cALrCC,CAAAA;EAAuB,QACPH,EAKxBG,uBALwBH,CAKAA,WALAA,EAAAA,EAKeC,QALfD,CAAAA;CAAW,CAAA;;cAQnCU,0BAV0BR,EAAAA;AAAc;AAItD,UAQUS,MAREH,CAAAA,MAAAA,EAAiB,GAAA,CAAA,GAQGG,MAROH,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA,CAAAA,GAAiB,GAQEN,cARF,CAAA;EAEnCO,kBAAAA,EAOGL,SAPHK,CAOaG,CAPbH,CAAAA;EAEnB,QAAA,EAMYN,uBANZ,CAMoCH,WANpC,EAAA,EAMmDC,QANnD,CAAA;CAAA,CAAA;;;;AAIQU,KAUEG,oBAVFH,CAAAA,UAUiCA,MAVjCA,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA,GAUuDJ,uBAVvDI,CAAAA,GAUkFC,CAVlFD,SAU4FJ,uBAV5FI,GAUsHI,UAVtHJ,CAAAA,OAUwIF,8BAVxIE,CAAAA,GAU0KC,CAV1KD,SAUoLA,MAVpLA,CAAAA,MAAAA,EAAAA,GAAAA,CAAAA,GAU0MI,UAV1MJ,CAAAA,OAU4ND,0BAV5NC,CAUuPC,CAVvPD,CAAAA,CAAAA,GAAAA,KAAAA;AAAsBA,KAWpBK,gBAXoBL,CAAAA,UAWOM,iBAXPN,GAW2BL,gBAX3BK,CAAAA,GAW+CO,CAX/CP,SAWyDM,iBAXzDN,GAW6EO,CAX7EP,GAWiFO,CAXjFP,SAW2FL,gBAX3FK,GAW8GT,cAX9GS,CAW6HN,2BAX7HM,CAWyJO,CAXzJP,CAAAA,CAAAA,GAAAA,KAAAA;;AACRP,KAYZa,iBAAAA,GAAoBf,cAZRE,CAAAA,GAAAA,CAAAA;;;;;AADgD;AAUxE"}
@@ -1,30 +1,25 @@
1
1
  import { ResponseFormatUndefined } from "./responses.js";
2
2
  import { BaseMessage } from "@langchain/core/messages";
3
- import * as _langchain_langgraph0 from "@langchain/langgraph";
4
- import { AnnotationRoot, Messages } from "@langchain/langgraph";
3
+ import { AnnotationRoot, BinaryOperatorAggregate, LastValue, Messages } from "@langchain/langgraph";
5
4
  import { InteropZodObject } from "@langchain/core/utils/types";
6
5
  import { InteropZodToStateDefinition } from "@langchain/langgraph/zod";
7
6
 
8
7
  //#region src/agents/annotation.d.ts
9
8
  declare const PreHookAnnotation: AnnotationRoot<{
10
- llmInputMessages: _langchain_langgraph0.BinaryOperatorAggregate<BaseMessage[], Messages>;
11
- messages: _langchain_langgraph0.BinaryOperatorAggregate<BaseMessage[], Messages>;
9
+ llmInputMessages: BinaryOperatorAggregate<BaseMessage[], Messages>;
10
+ messages: BinaryOperatorAggregate<BaseMessage[], Messages>;
12
11
  }>;
13
12
  type PreHookAnnotation = typeof PreHookAnnotation;
14
13
  // Base annotation without structuredResponse (for ResponseFormatUndefined)
15
14
  declare const createReactAgentBaseAnnotation: () => AnnotationRoot<{
16
- messages: _langchain_langgraph0.BinaryOperatorAggregate<BaseMessage[], Messages>;
15
+ messages: BinaryOperatorAggregate<BaseMessage[], Messages>;
17
16
  }>;
18
17
  // Full annotation with structuredResponse (for regular cases)
19
18
  declare const createReactAgentAnnotation: <
20
19
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
21
20
  T extends Record<string, any> = Record<string, any>>() => AnnotationRoot<{
22
- messages: _langchain_langgraph0.BinaryOperatorAggregate<BaseMessage[], Messages>;
23
- structuredResponse: {
24
- (): _langchain_langgraph0.LastValue<T>;
25
- (annotation: _langchain_langgraph0.SingleReducer<T, T>): _langchain_langgraph0.BinaryOperatorAggregate<T, T>;
26
- Root: <S extends _langchain_langgraph0.StateDefinition>(sd: S) => AnnotationRoot<S>;
27
- };
21
+ structuredResponse: LastValue<T>;
22
+ messages: BinaryOperatorAggregate<BaseMessage[], Messages>;
28
23
  }>;
29
24
  // Create annotation conditionally - for ResponseFormatUndefined, don't include structuredResponse
30
25
 
@@ -33,6 +28,15 @@ type ReactAgentAnnotation<T extends Record<string, any> | ResponseFormatUndefine
33
28
  type ToAnnotationRoot<A extends AnyAnnotationRoot | InteropZodObject> = A extends AnyAnnotationRoot ? A : A extends InteropZodObject ? AnnotationRoot<InteropZodToStateDefinition<A>> : never;
34
29
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
35
30
  type AnyAnnotationRoot = AnnotationRoot<any>;
31
+ /**
32
+ * Enhances a state schema to ensure proper message handling.
33
+ * If a Zod schema is provided, it creates an annotation that includes the messagesStateReducer
34
+ * and infers appropriate reducers for all other fields.
35
+ *
36
+ * @param stateSchema - The state schema to enhance.
37
+ * @returns The enhanced state schema.
38
+ */
39
+
36
40
  //#endregion
37
41
  export { AnyAnnotationRoot, PreHookAnnotation, ReactAgentAnnotation, ToAnnotationRoot };
38
42
  //# sourceMappingURL=annotation.d.ts.map