langchain 1.0.1 → 1.0.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 (148) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/_virtual/rolldown_runtime.cjs +0 -4
  3. package/dist/_virtual/rolldown_runtime.js +1 -10
  4. package/dist/agents/ReactAgent.cjs +21 -41
  5. package/dist/agents/ReactAgent.cjs.map +1 -1
  6. package/dist/agents/ReactAgent.js +21 -41
  7. package/dist/agents/ReactAgent.js.map +1 -1
  8. package/dist/agents/annotation.cjs +1 -0
  9. package/dist/agents/annotation.cjs.map +1 -1
  10. package/dist/agents/annotation.js +1 -0
  11. package/dist/agents/annotation.js.map +1 -1
  12. package/dist/agents/index.cjs.map +1 -1
  13. package/dist/agents/index.d.cts +11 -11
  14. package/dist/agents/index.d.cts.map +1 -1
  15. package/dist/agents/index.d.ts +11 -11
  16. package/dist/agents/index.d.ts.map +1 -1
  17. package/dist/agents/index.js.map +1 -1
  18. package/dist/agents/middleware/callLimit.d.cts.map +1 -1
  19. package/dist/agents/middleware/callLimit.d.ts.map +1 -1
  20. package/dist/agents/middleware/contextEditing.d.cts.map +1 -1
  21. package/dist/agents/middleware/contextEditing.d.ts.map +1 -1
  22. package/dist/agents/middleware/dynamicSystemPrompt.d.cts.map +1 -1
  23. package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +1 -1
  24. package/dist/agents/middleware/hitl.cjs +7 -2
  25. package/dist/agents/middleware/hitl.cjs.map +1 -1
  26. package/dist/agents/middleware/hitl.d.cts.map +1 -1
  27. package/dist/agents/middleware/hitl.d.ts.map +1 -1
  28. package/dist/agents/middleware/hitl.js +7 -2
  29. package/dist/agents/middleware/hitl.js.map +1 -1
  30. package/dist/agents/middleware/index.cjs +2 -1
  31. package/dist/agents/middleware/index.d.cts +15 -0
  32. package/dist/agents/middleware/index.d.ts +14 -0
  33. package/dist/agents/middleware/index.js +2 -1
  34. package/dist/agents/middleware/modelCallLimit.cjs +145 -0
  35. package/dist/agents/middleware/modelCallLimit.cjs.map +1 -0
  36. package/dist/agents/middleware/modelCallLimit.d.cts +128 -0
  37. package/dist/agents/middleware/modelCallLimit.d.cts.map +1 -0
  38. package/dist/agents/middleware/modelCallLimit.d.ts +128 -0
  39. package/dist/agents/middleware/modelCallLimit.d.ts.map +1 -0
  40. package/dist/agents/middleware/modelCallLimit.js +144 -0
  41. package/dist/agents/middleware/modelCallLimit.js.map +1 -0
  42. package/dist/agents/middleware/promptCaching.d.cts.map +1 -1
  43. package/dist/agents/middleware/summarization.cjs +4 -2
  44. package/dist/agents/middleware/summarization.cjs.map +1 -1
  45. package/dist/agents/middleware/summarization.d.cts +7 -6
  46. package/dist/agents/middleware/summarization.d.cts.map +1 -1
  47. package/dist/agents/middleware/summarization.d.ts +7 -6
  48. package/dist/agents/middleware/summarization.d.ts.map +1 -1
  49. package/dist/agents/middleware/summarization.js +4 -2
  50. package/dist/agents/middleware/summarization.js.map +1 -1
  51. package/dist/agents/middleware/todoListMiddleware.d.cts.map +1 -1
  52. package/dist/agents/middleware/toolCallLimit.cjs +205 -92
  53. package/dist/agents/middleware/toolCallLimit.cjs.map +1 -1
  54. package/dist/agents/middleware/toolCallLimit.d.cts +46 -37
  55. package/dist/agents/middleware/toolCallLimit.d.cts.map +1 -1
  56. package/dist/agents/middleware/toolCallLimit.d.ts +46 -37
  57. package/dist/agents/middleware/toolCallLimit.d.ts.map +1 -1
  58. package/dist/agents/middleware/toolCallLimit.js +206 -93
  59. package/dist/agents/middleware/toolCallLimit.js.map +1 -1
  60. package/dist/agents/middleware/toolRetry.cjs +224 -0
  61. package/dist/agents/middleware/toolRetry.cjs.map +1 -0
  62. package/dist/agents/middleware/toolRetry.d.cts +179 -0
  63. package/dist/agents/middleware/toolRetry.d.cts.map +1 -0
  64. package/dist/agents/middleware/toolRetry.d.ts +179 -0
  65. package/dist/agents/middleware/toolRetry.d.ts.map +1 -0
  66. package/dist/agents/middleware/toolRetry.js +223 -0
  67. package/dist/agents/middleware/toolRetry.js.map +1 -0
  68. package/dist/agents/middleware/types.d.cts +21 -19
  69. package/dist/agents/middleware/types.d.cts.map +1 -1
  70. package/dist/agents/middleware/types.d.ts +21 -19
  71. package/dist/agents/middleware/types.d.ts.map +1 -1
  72. package/dist/agents/middleware/utils.cjs +7 -0
  73. package/dist/agents/middleware/utils.cjs.map +1 -1
  74. package/dist/agents/middleware/utils.d.cts.map +1 -1
  75. package/dist/agents/middleware/utils.d.ts.map +1 -1
  76. package/dist/agents/middleware/utils.js +7 -1
  77. package/dist/agents/middleware/utils.js.map +1 -1
  78. package/dist/agents/middleware.cjs.map +1 -1
  79. package/dist/agents/middleware.d.cts +4 -4
  80. package/dist/agents/middleware.d.cts.map +1 -1
  81. package/dist/agents/middleware.d.ts +4 -4
  82. package/dist/agents/middleware.d.ts.map +1 -1
  83. package/dist/agents/middleware.js.map +1 -1
  84. package/dist/agents/nodes/AgentNode.cjs +21 -47
  85. package/dist/agents/nodes/AgentNode.cjs.map +1 -1
  86. package/dist/agents/nodes/AgentNode.js +22 -48
  87. package/dist/agents/nodes/AgentNode.js.map +1 -1
  88. package/dist/agents/nodes/ToolNode.cjs +12 -18
  89. package/dist/agents/nodes/ToolNode.cjs.map +1 -1
  90. package/dist/agents/nodes/ToolNode.js +12 -18
  91. package/dist/agents/nodes/ToolNode.js.map +1 -1
  92. package/dist/agents/nodes/middleware.cjs +9 -7
  93. package/dist/agents/nodes/middleware.cjs.map +1 -1
  94. package/dist/agents/nodes/middleware.js +10 -8
  95. package/dist/agents/nodes/middleware.js.map +1 -1
  96. package/dist/agents/nodes/types.d.cts +1 -1
  97. package/dist/agents/nodes/types.d.cts.map +1 -1
  98. package/dist/agents/nodes/types.d.ts +1 -1
  99. package/dist/agents/nodes/types.d.ts.map +1 -1
  100. package/dist/agents/nodes/utils.cjs +5 -1
  101. package/dist/agents/nodes/utils.cjs.map +1 -1
  102. package/dist/agents/nodes/utils.js +5 -1
  103. package/dist/agents/nodes/utils.js.map +1 -1
  104. package/dist/agents/runtime.d.cts +11 -27
  105. package/dist/agents/runtime.d.cts.map +1 -1
  106. package/dist/agents/runtime.d.ts +11 -27
  107. package/dist/agents/runtime.d.ts.map +1 -1
  108. package/dist/agents/state.cjs +45 -0
  109. package/dist/agents/state.cjs.map +1 -0
  110. package/dist/agents/state.js +44 -0
  111. package/dist/agents/state.js.map +1 -0
  112. package/dist/agents/types.d.cts +1 -1
  113. package/dist/agents/types.d.cts.map +1 -1
  114. package/dist/agents/types.d.ts +1 -1
  115. package/dist/agents/types.d.ts.map +1 -1
  116. package/dist/agents/utils.cjs +10 -2
  117. package/dist/agents/utils.cjs.map +1 -1
  118. package/dist/agents/utils.js +10 -2
  119. package/dist/agents/utils.js.map +1 -1
  120. package/dist/chat_models/universal.cjs +4 -3
  121. package/dist/chat_models/universal.cjs.map +1 -1
  122. package/dist/chat_models/universal.js +4 -3
  123. package/dist/chat_models/universal.js.map +1 -1
  124. package/dist/embeddings/cache_backed.cjs +140 -0
  125. package/dist/embeddings/cache_backed.cjs.map +1 -0
  126. package/dist/embeddings/cache_backed.d.cts +107 -0
  127. package/dist/embeddings/cache_backed.d.cts.map +1 -0
  128. package/dist/embeddings/cache_backed.d.ts +107 -0
  129. package/dist/embeddings/cache_backed.d.ts.map +1 -0
  130. package/dist/embeddings/cache_backed.js +134 -0
  131. package/dist/embeddings/cache_backed.js.map +1 -0
  132. package/dist/embeddings/fake.cjs +22 -0
  133. package/dist/embeddings/fake.cjs.map +1 -0
  134. package/dist/embeddings/fake.d.cts +1 -0
  135. package/dist/embeddings/fake.d.ts +1 -0
  136. package/dist/embeddings/fake.js +12 -0
  137. package/dist/embeddings/fake.js.map +1 -0
  138. package/dist/hub/base.cjs +4 -17
  139. package/dist/hub/base.cjs.map +1 -1
  140. package/dist/hub/base.js +2 -15
  141. package/dist/hub/base.js.map +1 -1
  142. package/dist/index.cjs +6 -18
  143. package/dist/index.cjs.map +1 -1
  144. package/dist/index.d.cts +3 -3
  145. package/dist/index.d.ts +3 -3
  146. package/dist/index.js +4 -5
  147. package/dist/index.js.map +1 -1
  148. package/package.json +6 -9
@@ -8,6 +8,7 @@ import { BeforeAgentNode } from "./nodes/BeforeAgentNode.js";
8
8
  import { BeforeModelNode } from "./nodes/BeforeModelNode.js";
9
9
  import { AfterModelNode } from "./nodes/AfterModelNode.js";
10
10
  import { AfterAgentNode } from "./nodes/AfterAgentNode.js";
11
+ import { StateManager } from "./state.js";
11
12
  import { AIMessage, ToolMessage } from "@langchain/core/messages";
12
13
  import { Command, END, START, Send, StateGraph } from "@langchain/langgraph";
13
14
 
@@ -16,6 +17,7 @@ var ReactAgent = class {
16
17
  #graph;
17
18
  #toolBehaviorVersion = "v2";
18
19
  #agentNode;
20
+ #stateManager = new StateManager();
19
21
  constructor(options) {
20
22
  this.options = options;
21
23
  this.#toolBehaviorVersion = options.version ?? this.#toolBehaviorVersion;
@@ -72,7 +74,8 @@ var ReactAgent = class {
72
74
  if (middlewareNames.has(m.name)) throw new Error(`Middleware ${m.name} is defined multiple times`);
73
75
  middlewareNames.add(m.name);
74
76
  if (m.beforeAgent) {
75
- beforeAgentNode = new BeforeAgentNode(m, { getPrivateState: () => this.#agentNode.getState()._privateState });
77
+ beforeAgentNode = new BeforeAgentNode(m, { getState: () => this.#stateManager.getState(m.name) });
78
+ this.#stateManager.addNode(m, beforeAgentNode);
76
79
  const name = `${m.name}.before_agent`;
77
80
  beforeAgentNodes.push({
78
81
  index: i,
@@ -82,7 +85,8 @@ var ReactAgent = class {
82
85
  allNodeWorkflows.addNode(name, beforeAgentNode, beforeAgentNode.nodeOptions);
83
86
  }
84
87
  if (m.beforeModel) {
85
- beforeModelNode = new BeforeModelNode(m, { getPrivateState: () => this.#agentNode.getState()._privateState });
88
+ beforeModelNode = new BeforeModelNode(m, { getState: () => this.#stateManager.getState(m.name) });
89
+ this.#stateManager.addNode(m, beforeModelNode);
86
90
  const name = `${m.name}.before_model`;
87
91
  beforeModelNodes.push({
88
92
  index: i,
@@ -92,7 +96,8 @@ var ReactAgent = class {
92
96
  allNodeWorkflows.addNode(name, beforeModelNode, beforeModelNode.nodeOptions);
93
97
  }
94
98
  if (m.afterModel) {
95
- afterModelNode = new AfterModelNode(m, { getPrivateState: () => this.#agentNode.getState()._privateState });
99
+ afterModelNode = new AfterModelNode(m, { getState: () => this.#stateManager.getState(m.name) });
100
+ this.#stateManager.addNode(m, afterModelNode);
96
101
  const name = `${m.name}.after_model`;
97
102
  afterModelNodes.push({
98
103
  index: i,
@@ -102,7 +107,8 @@ var ReactAgent = class {
102
107
  allNodeWorkflows.addNode(name, afterModelNode, afterModelNode.nodeOptions);
103
108
  }
104
109
  if (m.afterAgent) {
105
- afterAgentNode = new AfterAgentNode(m, { getPrivateState: () => this.#agentNode.getState()._privateState });
110
+ afterAgentNode = new AfterAgentNode(m, { getState: () => this.#stateManager.getState(m.name) });
111
+ this.#stateManager.addNode(m, afterAgentNode);
106
112
  const name = `${m.name}.after_agent`;
107
113
  afterAgentNodes.push({
108
114
  index: i,
@@ -111,30 +117,19 @@ var ReactAgent = class {
111
117
  });
112
118
  allNodeWorkflows.addNode(name, afterAgentNode, afterAgentNode.nodeOptions);
113
119
  }
114
- if (m.wrapModelCall) wrapModelCallHookMiddleware.push([m, () => ({
115
- ...beforeAgentNode?.getState(),
116
- ...beforeModelNode?.getState(),
117
- ...afterModelNode?.getState(),
118
- ...afterAgentNode?.getState()
119
- })]);
120
+ if (m.wrapModelCall) wrapModelCallHookMiddleware.push([m, () => this.#stateManager.getState(m.name)]);
120
121
  }
121
122
  /**
122
123
  * Add Nodes
123
124
  */
124
- allNodeWorkflows.addNode("model_request", this.#agentNode, AgentNode.nodeOptions);
125
- /**
126
- * Collect and compose wrapToolCall handlers from middleware
127
- * Wrap each handler with error handling and validation
128
- */
129
- const wrapToolCallHandler = wrapToolCall(middleware);
125
+ allNodeWorkflows.addNode("model_request", this.#agentNode);
130
126
  /**
131
127
  * add single tool node for all tools
132
128
  */
133
129
  if (toolClasses.filter(isClientTool).length > 0) {
134
130
  const toolNode = new ToolNode(toolClasses.filter(isClientTool), {
135
131
  signal: this.options.signal,
136
- wrapToolCall: wrapToolCallHandler,
137
- getPrivateState: () => this.#agentNode.getState()._privateState
132
+ wrapToolCall: wrapToolCall(middleware)
138
133
  });
139
134
  allNodeWorkflows.addNode("tools", toolNode);
140
135
  }
@@ -431,33 +426,19 @@ var ReactAgent = class {
431
426
  /**
432
427
  * Initialize middleware states if not already present in the input state.
433
428
  */
434
- async #initializeMiddlewareStates(state) {
429
+ async #initializeMiddlewareStates(state, config) {
435
430
  if (!this.options.middleware || this.options.middleware.length === 0 || state instanceof Command || !state) return state;
436
431
  const defaultStates = await initializeMiddlewareStates(this.options.middleware, state);
437
- const updatedState = { ...state };
432
+ const threadState = await this.#graph.getState(config).catch(() => ({ values: {} }));
433
+ const updatedState = {
434
+ ...threadState.values,
435
+ ...state
436
+ };
438
437
  if (!updatedState) return updatedState;
439
438
  for (const [key, value] of Object.entries(defaultStates)) if (!(key in updatedState)) updatedState[key] = value;
440
439
  return updatedState;
441
440
  }
442
441
  /**
443
- * Populate the private state of the agent node from the previous state.
444
- */
445
- async #populatePrivateState(config) {
446
- /**
447
- * not needed if thread_id is not provided
448
- */
449
- if (!config?.configurable?.thread_id) return;
450
- const prevState = await this.#graph.getState(config);
451
- /**
452
- * not need if state is empty
453
- */
454
- if (!prevState.values._privateState) return;
455
- this.#agentNode.setState({
456
- structuredResponse: void 0,
457
- _privateState: prevState.values._privateState
458
- });
459
- }
460
- /**
461
442
  * Executes the agent with the given state and returns the final state after all processing.
462
443
  *
463
444
  * This method runs the agent's entire workflow synchronously, including:
@@ -501,8 +482,7 @@ var ReactAgent = class {
501
482
  * ```
502
483
  */
503
484
  async invoke(state, config) {
504
- const initializedState = await this.#initializeMiddlewareStates(state);
505
- await this.#populatePrivateState(config);
485
+ const initializedState = await this.#initializeMiddlewareStates(state, config);
506
486
  return this.#graph.invoke(initializedState, config);
507
487
  }
508
488
  /**
@@ -548,7 +528,7 @@ var ReactAgent = class {
548
528
  * ```
549
529
  */
550
530
  async stream(state, config) {
551
- const initializedState = await this.#initializeMiddlewareStates(state);
531
+ const initializedState = await this.#initializeMiddlewareStates(state, config);
552
532
  return this.#graph.stream(initializedState, config);
553
533
  }
554
534
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"ReactAgent.js","names":["options: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema\n >","#toolBehaviorVersion","beforeAgentNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[]","beforeModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[]","afterModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[]","afterAgentNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[]","wrapModelCallHookMiddleware: [\n AgentMiddleware,\n /**\n * ToDo: better type to get the state of middleware\n */\n () => any\n ][]","#agentNode","beforeAgentNode: BeforeAgentNode | undefined","beforeModelNode: BeforeModelNode | undefined","afterModelNode: AfterModelNode | undefined","afterAgentNode: AfterAgentNode | undefined","entryNode: string","#createBeforeAgentRouter","#createBeforeModelRouter","#getModelPaths","#createModelRouter","#createAfterModelSequenceRouter","#createAfterModelRouter","#createToolsRouter","#graph","toolClasses: (ClientTool | ServerTool)[]","includeModelRequest: boolean","paths: (\"tools\" | \"model_request\" | typeof END)[]","shouldReturnDirect: Set<string>","exitNode: string | typeof END","state: any","state: BuiltInState","allowJump: boolean","state: Omit<BuiltInState, \"jumpTo\"> & { jumpTo?: JumpTo }","allowed: string[]","nextDefault: string","#initializeMiddlewareStates","state: InvokeStateParameter<StateSchema, TMiddleware>","#populatePrivateState","config?: RunnableConfig","config?: InvokeConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n >","config?: StreamConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n >","params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }","config?: StreamConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n > & { version?: \"v1\" | \"v2\" }","streamOptions?: Parameters<Runnable[\"streamEvents\"]>[2]","config: RunnableConfig","options?: GetStateOptions","options?: CheckpointListOptions","namespace?: string","recurse?: boolean","inputConfig: LangGraphRunnableConfig","values: Record<string, unknown> | unknown","asNode?: string"],"sources":["../../src/agents/ReactAgent.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\n\nimport {\n AnnotationRoot,\n StateGraph,\n END,\n START,\n Send,\n Command,\n CompiledStateGraph,\n type GetStateOptions,\n type LangGraphRunnableConfig,\n} from \"@langchain/langgraph\";\nimport type { CheckpointListOptions } from \"@langchain/langgraph-checkpoint\";\nimport { ToolMessage, AIMessage } from \"@langchain/core/messages\";\nimport { IterableReadableStream } from \"@langchain/core/utils/stream\";\nimport type { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport type { StreamEvent } from \"@langchain/core/tracers/log_stream\";\n\nimport { createAgentAnnotationConditional } from \"./annotation.js\";\nimport {\n isClientTool,\n validateLLMHasNoBoundTools,\n wrapToolCall,\n} from \"./utils.js\";\n\nimport { AgentNode } from \"./nodes/AgentNode.js\";\nimport { ToolNode } from \"./nodes/ToolNode.js\";\nimport { BeforeAgentNode } from \"./nodes/BeforeAgentNode.js\";\nimport { BeforeModelNode } from \"./nodes/BeforeModelNode.js\";\nimport { AfterModelNode } from \"./nodes/AfterModelNode.js\";\nimport { AfterAgentNode } from \"./nodes/AfterAgentNode.js\";\nimport {\n initializeMiddlewareStates,\n parseJumpToTarget,\n} from \"./nodes/utils.js\";\n\nimport type { WithStateGraphNodes } from \"./types.js\";\nimport type { ClientTool, ServerTool } from \"./tools.js\";\n\nimport type {\n CreateAgentParams,\n BuiltInState,\n JumpTo,\n UserInput,\n} from \"./types.js\";\nimport type {\n PrivateState,\n InvokeConfiguration,\n StreamConfiguration,\n} from \"./runtime.js\";\nimport type {\n AgentMiddleware,\n InferMiddlewareContextInputs,\n InferMiddlewareStates,\n InferMiddlewareInputStates,\n InferContextInput,\n AnyAnnotationRoot,\n InferSchemaInput,\n ToAnnotationRoot,\n} from \"./middleware/types.js\";\nimport { type ResponseFormatUndefined } from \"./responses.js\";\nimport { getHookConstraint } from \"./middleware/utils.js\";\n\n// Helper type to get the state definition with middleware states\ntype MergedAgentState<\n StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined,\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined,\n TMiddleware extends readonly AgentMiddleware[]\n> = InferSchemaInput<StateSchema> &\n (StructuredResponseFormat extends ResponseFormatUndefined\n ? Omit<BuiltInState, \"jumpTo\">\n : Omit<BuiltInState, \"jumpTo\"> & {\n structuredResponse: StructuredResponseFormat;\n }) &\n InferMiddlewareStates<TMiddleware>;\n\ntype InvokeStateParameter<\n StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined,\n TMiddleware extends readonly AgentMiddleware[]\n> =\n | (UserInput<StateSchema> & InferMiddlewareInputStates<TMiddleware>)\n | Command<any, any, any>\n | null;\n\ntype AgentGraph<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware[] = []\n> = CompiledStateGraph<\n any,\n any,\n any,\n any,\n MergedAgentState<StateSchema, StructuredResponseFormat, TMiddleware>,\n ToAnnotationRoot<ContextSchema>[\"spec\"],\n unknown\n>;\n\nexport class ReactAgent<\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n> {\n #graph: AgentGraph<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema,\n TMiddleware\n >;\n\n #toolBehaviorVersion: \"v1\" | \"v2\" = \"v2\";\n\n #agentNode: AgentNode<any, AnyAnnotationRoot>;\n\n constructor(\n public options: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema\n >\n ) {\n this.#toolBehaviorVersion = options.version ?? this.#toolBehaviorVersion;\n\n /**\n * validate that model option is provided\n */\n if (!options.model) {\n throw new Error(\"`model` option is required to create an agent.\");\n }\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n if (typeof options.model !== \"string\") {\n validateLLMHasNoBoundTools(options.model);\n }\n\n /**\n * define complete list of tools based on options and middleware\n */\n const middlewareTools = (this.options.middleware\n ?.filter((m) => m.tools)\n .flatMap((m) => m.tools) ?? []) as (ClientTool | ServerTool)[];\n const toolClasses = [...(options.tools ?? []), ...middlewareTools];\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 /**\n * Create a schema that merges agent base schema with middleware state schemas\n * Using Zod with withLangGraph ensures LangGraph Studio gets proper metadata\n */\n const schema = createAgentAnnotationConditional<StateSchema, TMiddleware>(\n this.options.responseFormat !== undefined,\n this.options.stateSchema as StateSchema,\n this.options.middleware as TMiddleware\n );\n\n const workflow = new StateGraph(\n schema as unknown as AnnotationRoot<any>,\n this.options.contextSchema\n );\n\n const allNodeWorkflows = workflow as WithStateGraphNodes<\n \"tools\" | \"model_request\" | string,\n typeof workflow\n >;\n\n // Generate node names for middleware nodes that have hooks\n const beforeAgentNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const beforeModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const afterModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const afterAgentNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const wrapModelCallHookMiddleware: [\n AgentMiddleware,\n /**\n * ToDo: better type to get the state of middleware\n */\n () => any\n ][] = [];\n\n this.#agentNode = new AgentNode({\n model: this.options.model,\n systemPrompt: this.options.systemPrompt,\n includeAgentName: this.options.includeAgentName,\n name: this.options.name,\n responseFormat: this.options.responseFormat,\n middleware: this.options.middleware,\n toolClasses,\n shouldReturnDirect,\n signal: this.options.signal,\n wrapModelCallHookMiddleware,\n });\n\n const middlewareNames = new Set<string>();\n const middleware = this.options.middleware ?? [];\n for (let i = 0; i < middleware.length; i++) {\n let beforeAgentNode: BeforeAgentNode | undefined;\n let beforeModelNode: BeforeModelNode | undefined;\n let afterModelNode: AfterModelNode | undefined;\n let afterAgentNode: AfterAgentNode | undefined;\n const m = middleware[i];\n if (middlewareNames.has(m.name)) {\n throw new Error(`Middleware ${m.name} is defined multiple times`);\n }\n\n middlewareNames.add(m.name);\n if (m.beforeAgent) {\n beforeAgentNode = new BeforeAgentNode(m, {\n getPrivateState: () => this.#agentNode.getState()._privateState,\n });\n const name = `${m.name}.before_agent`;\n beforeAgentNodes.push({\n index: i,\n name,\n allowed: getHookConstraint(m.beforeAgent),\n });\n allNodeWorkflows.addNode(\n name,\n beforeAgentNode,\n beforeAgentNode.nodeOptions\n );\n }\n if (m.beforeModel) {\n beforeModelNode = new BeforeModelNode(m, {\n getPrivateState: () => this.#agentNode.getState()._privateState,\n });\n const name = `${m.name}.before_model`;\n beforeModelNodes.push({\n index: i,\n name,\n allowed: getHookConstraint(m.beforeModel),\n });\n allNodeWorkflows.addNode(\n name,\n beforeModelNode,\n beforeModelNode.nodeOptions\n );\n }\n if (m.afterModel) {\n afterModelNode = new AfterModelNode(m, {\n getPrivateState: () => this.#agentNode.getState()._privateState,\n });\n const name = `${m.name}.after_model`;\n afterModelNodes.push({\n index: i,\n name,\n allowed: getHookConstraint(m.afterModel),\n });\n allNodeWorkflows.addNode(\n name,\n afterModelNode,\n afterModelNode.nodeOptions\n );\n }\n if (m.afterAgent) {\n afterAgentNode = new AfterAgentNode(m, {\n getPrivateState: () => this.#agentNode.getState()._privateState,\n });\n const name = `${m.name}.after_agent`;\n afterAgentNodes.push({\n index: i,\n name,\n allowed: getHookConstraint(m.afterAgent),\n });\n allNodeWorkflows.addNode(\n name,\n afterAgentNode,\n afterAgentNode.nodeOptions\n );\n }\n\n if (m.wrapModelCall) {\n wrapModelCallHookMiddleware.push([\n m,\n () => ({\n ...beforeAgentNode?.getState(),\n ...beforeModelNode?.getState(),\n ...afterModelNode?.getState(),\n ...afterAgentNode?.getState(),\n }),\n ]);\n }\n }\n\n /**\n * Add Nodes\n */\n allNodeWorkflows.addNode(\n \"model_request\",\n this.#agentNode,\n AgentNode.nodeOptions\n );\n\n /**\n * Collect and compose wrapToolCall handlers from middleware\n * Wrap each handler with error handling and validation\n */\n const wrapToolCallHandler = wrapToolCall(middleware);\n\n /**\n * add single tool node for all tools\n */\n if (toolClasses.filter(isClientTool).length > 0) {\n const toolNode = new ToolNode(toolClasses.filter(isClientTool), {\n signal: this.options.signal,\n wrapToolCall: wrapToolCallHandler,\n getPrivateState: () => this.#agentNode.getState()._privateState,\n });\n allNodeWorkflows.addNode(\"tools\", toolNode);\n }\n\n /**\n * Add Edges\n */\n // Determine the entry node (runs once at start): before_agent -> before_model -> model_request\n let entryNode: string;\n if (beforeAgentNodes.length > 0) {\n entryNode = beforeAgentNodes[0].name;\n } else if (beforeModelNodes.length > 0) {\n entryNode = beforeModelNodes[0].name;\n } else {\n entryNode = \"model_request\";\n }\n\n // Determine the loop entry node (beginning of agent loop, excludes before_agent)\n // This is where tools will loop back to for the next iteration\n const loopEntryNode =\n beforeModelNodes.length > 0 ? beforeModelNodes[0].name : \"model_request\";\n\n // Determine the exit node (runs once at end): after_agent or END\n const exitNode =\n afterAgentNodes.length > 0\n ? afterAgentNodes[afterAgentNodes.length - 1].name\n : END;\n\n allNodeWorkflows.addEdge(START, entryNode);\n\n // Connect beforeAgent nodes (run once at start)\n for (let i = 0; i < beforeAgentNodes.length; i++) {\n const node = beforeAgentNodes[i];\n const current = node.name;\n const isLast = i === beforeAgentNodes.length - 1;\n const nextDefault = isLast ? loopEntryNode : beforeAgentNodes[i + 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const hasTools = toolClasses.filter(isClientTool).length > 0;\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== \"tools\" || hasTools);\n // Replace END with exitNode (which could be an afterAgent node)\n const destinations = Array.from(\n new Set([\n nextDefault,\n ...allowedMapped.map((dest) => (dest === END ? exitNode : dest)),\n ])\n ) as (\"tools\" | \"model_request\" | typeof END)[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createBeforeAgentRouter(\n toolClasses.filter(isClientTool),\n nextDefault,\n exitNode\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect beforeModel nodes; add conditional routing ONLY if allowed jumps are specified\n for (let i = 0; i < beforeModelNodes.length; i++) {\n const node = beforeModelNodes[i];\n const current = node.name;\n const isLast = i === beforeModelNodes.length - 1;\n const nextDefault = isLast\n ? \"model_request\"\n : beforeModelNodes[i + 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const hasTools = toolClasses.filter(isClientTool).length > 0;\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== \"tools\" || hasTools);\n const destinations = Array.from(\n new Set([nextDefault, ...allowedMapped])\n ) as (\"tools\" | \"model_request\" | typeof END)[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createBeforeModelRouter(\n toolClasses.filter(isClientTool),\n nextDefault\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect agent to last afterModel node (for reverse order execution)\n const lastAfterModelNode = afterModelNodes.at(-1);\n if (afterModelNodes.length > 0 && lastAfterModelNode) {\n allNodeWorkflows.addEdge(\"model_request\", lastAfterModelNode.name);\n } else {\n // If no afterModel nodes, connect model_request directly to model paths\n const modelPaths = this.#getModelPaths(toolClasses.filter(isClientTool));\n // Replace END with exitNode in destinations, since exitNode might be an afterAgent node\n const destinations = modelPaths.map((p) =>\n p === END ? exitNode : p\n ) as (\"tools\" | \"model_request\" | typeof END)[];\n if (destinations.length === 1) {\n allNodeWorkflows.addEdge(\"model_request\", destinations[0]);\n } else {\n allNodeWorkflows.addConditionalEdges(\n \"model_request\",\n this.#createModelRouter(exitNode),\n destinations\n );\n }\n }\n\n // Connect afterModel nodes in reverse sequence; add conditional routing ONLY if allowed jumps are specified per node\n for (let i = afterModelNodes.length - 1; i > 0; i--) {\n const node = afterModelNodes[i];\n const current = node.name;\n const nextDefault = afterModelNodes[i - 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const hasTools = toolClasses.filter(isClientTool).length > 0;\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== \"tools\" || hasTools);\n const destinations = Array.from(\n new Set([nextDefault, ...allowedMapped])\n ) as (\"tools\" | \"model_request\" | typeof END)[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createAfterModelSequenceRouter(\n toolClasses.filter(isClientTool),\n node.allowed,\n nextDefault\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect first afterModel node (last to execute) to model paths with jumpTo support\n if (afterModelNodes.length > 0) {\n const firstAfterModel = afterModelNodes[0];\n const firstAfterModelNode = firstAfterModel.name;\n\n // Include exitNode in the paths since afterModel should be able to route to after_agent or END\n const modelPaths = this.#getModelPaths(\n toolClasses.filter(isClientTool),\n true\n ).filter(\n (p) => p !== \"tools\" || toolClasses.filter(isClientTool).length > 0\n );\n\n const allowJump = Boolean(\n firstAfterModel.allowed && firstAfterModel.allowed.length > 0\n );\n\n // Replace END with exitNode in destinations, since exitNode might be an afterAgent node\n const destinations = modelPaths.map((p) =>\n p === END ? exitNode : p\n ) as (\"tools\" | \"model_request\" | typeof END)[];\n\n allNodeWorkflows.addConditionalEdges(\n firstAfterModelNode,\n this.#createAfterModelRouter(\n toolClasses.filter(isClientTool),\n allowJump,\n exitNode\n ),\n destinations\n );\n }\n\n // Connect afterAgent nodes (run once at end, in reverse order like afterModel)\n for (let i = afterAgentNodes.length - 1; i > 0; i--) {\n const node = afterAgentNodes[i];\n const current = node.name;\n const nextDefault = afterAgentNodes[i - 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const hasTools = toolClasses.filter(isClientTool).length > 0;\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== \"tools\" || hasTools);\n const destinations = Array.from(\n new Set([nextDefault, ...allowedMapped])\n ) as (\"tools\" | \"model_request\" | typeof END)[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createAfterModelSequenceRouter(\n toolClasses.filter(isClientTool),\n node.allowed,\n nextDefault\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect the first afterAgent node (last to execute) to END\n if (afterAgentNodes.length > 0) {\n const firstAfterAgent = afterAgentNodes[0];\n const firstAfterAgentNode = firstAfterAgent.name;\n\n if (firstAfterAgent.allowed && firstAfterAgent.allowed.length > 0) {\n const hasTools = toolClasses.filter(isClientTool).length > 0;\n const allowedMapped = firstAfterAgent.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== \"tools\" || hasTools);\n\n /**\n * For after_agent, only use explicitly allowed destinations (don't add loopEntryNode)\n * The default destination (when no jump occurs) should be END\n */\n const destinations = Array.from(new Set([END, ...allowedMapped])) as (\n | \"tools\"\n | \"model_request\"\n | typeof END\n )[];\n\n allNodeWorkflows.addConditionalEdges(\n firstAfterAgentNode,\n this.#createAfterModelSequenceRouter(\n toolClasses.filter(isClientTool),\n firstAfterAgent.allowed,\n END as string\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(firstAfterAgentNode, END);\n }\n }\n\n /**\n * add edges for tools node\n */\n if (toolClasses.filter(isClientTool).length > 0) {\n // Tools should return to loop entry node (not including before_agent)\n const toolReturnTarget = loopEntryNode;\n\n if (shouldReturnDirect.size > 0) {\n allNodeWorkflows.addConditionalEdges(\n \"tools\",\n this.#createToolsRouter(shouldReturnDirect, exitNode),\n [toolReturnTarget, exitNode as string]\n );\n } else {\n allNodeWorkflows.addEdge(\"tools\", toolReturnTarget);\n }\n }\n\n /**\n * compile the graph\n */\n this.#graph = allNodeWorkflows.compile({\n checkpointer: this.options.checkpointer,\n store: this.options.store,\n name: this.options.name,\n description: this.options.description,\n }) as AgentGraph<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema,\n TMiddleware\n >;\n }\n\n /**\n * Get the compiled {@link https://docs.langchain.com/oss/javascript/langgraph/use-graph-api | StateGraph}.\n */\n get graph(): AgentGraph<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema,\n TMiddleware\n > {\n return this.#graph;\n }\n\n /**\n * Get possible edge destinations from model node.\n * @param toolClasses names of tools to call\n * @param includeModelRequest whether to include \"model_request\" as a valid path (for jumpTo routing)\n * @returns list of possible edge destinations\n */\n #getModelPaths(\n toolClasses: (ClientTool | ServerTool)[],\n includeModelRequest: boolean = false\n ): (\"tools\" | \"model_request\" | typeof END)[] {\n const paths: (\"tools\" | \"model_request\" | typeof END)[] = [];\n if (toolClasses.length > 0) {\n paths.push(\"tools\");\n }\n\n if (includeModelRequest) {\n paths.push(\"model_request\");\n }\n\n paths.push(END);\n\n return paths;\n }\n\n /**\n * Create routing function for tools node conditional edges.\n */\n #createToolsRouter(\n shouldReturnDirect: Set<string>,\n exitNode: string | typeof END\n ) {\n /**\n * ToDo: fix type\n */\n return (state: any) => {\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 ToolMessage.isInstance(lastMessage) &&\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 to exit node (could be after_agent or END)\n return this.options.responseFormat ? \"model_request\" : exitNode;\n }\n\n // For non-returnDirect tools, always route back to agent\n return \"model_request\";\n };\n }\n\n /**\n * Create routing function for model node conditional edges.\n * @param exitNode - The exit node to route to (could be after_agent or END)\n */\n #createModelRouter(exitNode: string | typeof END = END) {\n /**\n * determine if the agent should continue or not\n */\n return (state: BuiltInState) => {\n const messages = state.messages;\n const lastMessage = messages.at(-1);\n\n if (\n !AIMessage.isInstance(lastMessage) ||\n !lastMessage.tool_calls ||\n lastMessage.tool_calls.length === 0\n ) {\n return exitNode;\n }\n\n // Check if all tool calls are for structured response extraction\n const hasOnlyStructuredResponseCalls = lastMessage.tool_calls.every(\n (toolCall) => toolCall.name.startsWith(\"extract-\")\n );\n\n if (hasOnlyStructuredResponseCalls) {\n // If all tool calls are for structured response extraction, go to exit node\n // The AgentNode will handle these internally and return the structured response\n return exitNode;\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 (filter out any structured response tool calls)\n */\n const regularToolCalls = lastMessage.tool_calls.filter(\n (toolCall) => !toolCall.name.startsWith(\"extract-\")\n );\n\n if (regularToolCalls.length === 0) {\n return exitNode;\n }\n\n return regularToolCalls.map(\n (toolCall) => new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n };\n }\n\n /**\n * Create routing function for jumpTo functionality after afterModel hooks.\n *\n * This router checks if the `jumpTo` property is set in the state after afterModel middleware\n * execution. If set, it routes to the specified target (\"model_request\" or \"tools\").\n * If not set, it falls back to the normal model routing logic for afterModel context.\n *\n * The jumpTo property is automatically cleared after use to prevent infinite loops.\n *\n * @param toolClasses - Available tool classes for validation\n * @param allowJump - Whether jumping is allowed\n * @param exitNode - The exit node to route to (could be after_agent or END)\n * @returns Router function that handles jumpTo logic and normal routing\n */\n #createAfterModelRouter(\n toolClasses: (ClientTool | ServerTool)[],\n allowJump: boolean,\n exitNode: string | typeof END\n ) {\n const hasStructuredResponse = Boolean(this.options.responseFormat);\n\n return (state: Omit<BuiltInState, \"jumpTo\"> & { jumpTo?: JumpTo }) => {\n // First, check if we just processed a structured response\n // If so, ignore any existing jumpTo and go to exitNode\n const messages = state.messages;\n const lastMessage = messages.at(-1);\n if (\n AIMessage.isInstance(lastMessage) &&\n (!lastMessage.tool_calls || lastMessage.tool_calls.length === 0)\n ) {\n return exitNode;\n }\n\n // Check if jumpTo is set in the state and allowed\n if (allowJump && state.jumpTo) {\n if (state.jumpTo === END) {\n return exitNode;\n }\n if (state.jumpTo === \"tools\") {\n // If trying to jump to tools but no tools are available, go to exitNode\n if (toolClasses.length === 0) {\n return exitNode;\n }\n return new Send(\"tools\", { ...state, jumpTo: undefined });\n }\n // destination === \"model_request\"\n return new Send(\"model_request\", { ...state, jumpTo: undefined });\n }\n\n // check if there are pending tool calls\n const toolMessages = messages.filter(ToolMessage.isInstance);\n const lastAiMessage = messages.filter(AIMessage.isInstance).at(-1);\n const pendingToolCalls = lastAiMessage?.tool_calls?.filter(\n (call) => !toolMessages.some((m) => m.tool_call_id === call.id)\n );\n if (pendingToolCalls && pendingToolCalls.length > 0) {\n return pendingToolCalls.map(\n (toolCall) => new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n }\n\n // if we exhausted all tool calls, but still have no structured response tool calls,\n // go back to model_request\n const hasStructuredResponseCalls = lastAiMessage?.tool_calls?.some(\n (toolCall) => toolCall.name.startsWith(\"extract-\")\n );\n\n if (\n pendingToolCalls &&\n pendingToolCalls.length === 0 &&\n !hasStructuredResponseCalls &&\n hasStructuredResponse\n ) {\n return \"model_request\";\n }\n\n if (\n !AIMessage.isInstance(lastMessage) ||\n !lastMessage.tool_calls ||\n lastMessage.tool_calls.length === 0\n ) {\n return exitNode;\n }\n\n // Check if all tool calls are for structured response extraction\n const hasOnlyStructuredResponseCalls = lastMessage.tool_calls.every(\n (toolCall) => toolCall.name.startsWith(\"extract-\")\n );\n\n // Check if there are any regular tool calls (non-structured response)\n const hasRegularToolCalls = lastMessage.tool_calls.some(\n (toolCall) => !toolCall.name.startsWith(\"extract-\")\n );\n\n if (hasOnlyStructuredResponseCalls || !hasRegularToolCalls) {\n return exitNode;\n }\n\n /**\n * For routing from afterModel nodes, always use simple string paths\n * The Send API is handled at the model_request node level\n */\n return \"tools\";\n };\n }\n\n /**\n * Router for afterModel sequence nodes (connecting later middlewares to earlier ones),\n * honoring allowed jump targets and defaulting to the next node.\n */\n #createAfterModelSequenceRouter(\n toolClasses: (ClientTool | ServerTool)[],\n allowed: string[],\n nextDefault: string\n ) {\n const allowedSet = new Set(allowed.map((t) => parseJumpToTarget(t)));\n return (state: BuiltInState) => {\n if (state.jumpTo) {\n const dest = parseJumpToTarget(state.jumpTo);\n if (dest === END && allowedSet.has(END)) {\n return END;\n }\n if (dest === \"tools\" && allowedSet.has(\"tools\")) {\n if (toolClasses.length === 0) return END;\n return new Send(\"tools\", { ...state, jumpTo: undefined });\n }\n if (dest === \"model_request\" && allowedSet.has(\"model_request\")) {\n return new Send(\"model_request\", { ...state, jumpTo: undefined });\n }\n }\n return nextDefault as any;\n };\n }\n\n /**\n * Create routing function for jumpTo functionality after beforeAgent hooks.\n * Falls back to the default next node if no jumpTo is present.\n * When jumping to END, routes to exitNode (which could be an afterAgent node).\n */\n #createBeforeAgentRouter(\n toolClasses: (ClientTool | ServerTool)[],\n nextDefault: string,\n exitNode: string | typeof END\n ) {\n return (state: BuiltInState) => {\n if (!state.jumpTo) {\n return nextDefault;\n }\n const destination = parseJumpToTarget(state.jumpTo);\n if (destination === END) {\n // When beforeAgent jumps to END, route to exitNode (first afterAgent node)\n return exitNode;\n }\n if (destination === \"tools\") {\n if (toolClasses.length === 0) {\n return exitNode;\n }\n return new Send(\"tools\", { ...state, jumpTo: undefined });\n }\n // destination === \"model_request\"\n return new Send(\"model_request\", { ...state, jumpTo: undefined });\n };\n }\n\n /**\n * Create routing function for jumpTo functionality after beforeModel hooks.\n * Falls back to the default next node if no jumpTo is present.\n */\n #createBeforeModelRouter(\n toolClasses: (ClientTool | ServerTool)[],\n nextDefault: string\n ) {\n return (state: BuiltInState) => {\n if (!state.jumpTo) {\n return nextDefault;\n }\n const destination = parseJumpToTarget(state.jumpTo);\n if (destination === END) {\n return END;\n }\n if (destination === \"tools\") {\n if (toolClasses.length === 0) {\n return END;\n }\n return new Send(\"tools\", { ...state, jumpTo: undefined });\n }\n // destination === \"model_request\"\n return new Send(\"model_request\", { ...state, jumpTo: undefined });\n };\n }\n\n /**\n * Initialize middleware states if not already present in the input state.\n */\n async #initializeMiddlewareStates(\n state: InvokeStateParameter<StateSchema, TMiddleware>\n ): Promise<InvokeStateParameter<StateSchema, TMiddleware>> {\n if (\n !this.options.middleware ||\n this.options.middleware.length === 0 ||\n state instanceof Command ||\n !state\n ) {\n return state;\n }\n\n const defaultStates = await initializeMiddlewareStates(\n this.options.middleware,\n state\n );\n const updatedState = { ...state } as InvokeStateParameter<\n StateSchema,\n TMiddleware\n >;\n if (!updatedState) {\n return updatedState;\n }\n\n // Only add defaults for keys that don't exist in current state\n for (const [key, value] of Object.entries(defaultStates)) {\n if (!(key in updatedState)) {\n updatedState[key as keyof typeof updatedState] = value;\n }\n }\n\n return updatedState;\n }\n\n /**\n * Populate the private state of the agent node from the previous state.\n */\n async #populatePrivateState(config?: RunnableConfig) {\n /**\n * not needed if thread_id is not provided\n */\n if (!config?.configurable?.thread_id) {\n return;\n }\n const prevState = (await this.#graph.getState(config as any)) as {\n values: {\n _privateState: PrivateState;\n };\n };\n\n /**\n * not need if state is empty\n */\n if (!prevState.values._privateState) {\n return;\n }\n\n this.#agentNode.setState({\n structuredResponse: undefined,\n _privateState: prevState.values._privateState,\n });\n }\n\n /**\n * Executes the agent with the given state and returns the final state after all processing.\n *\n * This method runs the agent's entire workflow synchronously, including:\n * - Processing the input messages through any configured middleware\n * - Calling the language model to generate responses\n * - Executing any tool calls made by the model\n * - Running all middleware hooks (beforeModel, afterModel, etc.)\n *\n * @param state - The initial state for the agent execution. Can be:\n * - An object containing `messages` array and any middleware-specific state properties\n * - A Command object for more advanced control flow\n *\n * @param config - Optional runtime configuration including:\n * @param config.context - The context for the agent execution.\n * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc.\n * @param config.store - The store for the agent execution for persisting state, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Memory storage}.\n * @param config.signal - An optional {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} for the agent execution.\n * @param config.recursionLimit - The recursion limit for the agent execution.\n *\n * @returns A Promise that resolves to the final agent state after execution completes.\n * The returned state includes:\n * - a `messages` property containing an array with all messages (input, AI responses, tool calls/results)\n * - a `structuredResponse` property containing the structured response (if configured)\n * - all state values defined in the middleware\n *\n * @example\n * ```typescript\n * const agent = new ReactAgent({\n * llm: myModel,\n * tools: [calculator, webSearch],\n * responseFormat: z.object({\n * weather: z.string(),\n * }),\n * });\n *\n * const result = await agent.invoke({\n * messages: [{ role: \"human\", content: \"What's the weather in Paris?\" }]\n * });\n *\n * console.log(result.structuredResponse.weather); // outputs: \"It's sunny and 75°F.\"\n * ```\n */\n async invoke(\n state: InvokeStateParameter<StateSchema, TMiddleware>,\n config?: InvokeConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n >\n ) {\n type FullState = MergedAgentState<\n StateSchema,\n StructuredResponseFormat,\n TMiddleware\n >;\n const initializedState = await this.#initializeMiddlewareStates(state);\n await this.#populatePrivateState(config);\n\n return this.#graph.invoke(\n initializedState,\n config as unknown as InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n ) as Promise<FullState>;\n }\n\n /**\n * Executes the agent with streaming, returning an async iterable of state updates as they occur.\n *\n * This method runs the agent's workflow similar to `invoke`, but instead of waiting for\n * completion, it streams high-level state updates in real-time. This allows you to:\n * - Display intermediate results to users as they're generated\n * - Monitor the agent's progress through each step\n * - React to state changes as nodes complete\n *\n * For more granular event-level streaming (like individual LLM tokens), use `streamEvents` instead.\n *\n * @param state - The initial state for the agent execution. Can be:\n * - An object containing `messages` array and any middleware-specific state properties\n * - A Command object for more advanced control flow\n *\n * @param config - Optional runtime configuration including:\n * @param config.context - The context for the agent execution.\n * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc.\n * @param config.store - The store for the agent execution for persisting state, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Memory storage}.\n * @param config.signal - An optional {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} for the agent execution.\n * @param config.streamMode - The streaming mode for the agent execution, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/streaming#supported-stream-modes | Supported stream modes}.\n * @param config.recursionLimit - The recursion limit for the agent execution.\n *\n * @returns A Promise that resolves to an IterableReadableStream of state updates.\n * Each update contains the current state after a node completes.\n *\n * @example\n * ```typescript\n * const agent = new ReactAgent({\n * llm: myModel,\n * tools: [calculator, webSearch]\n * });\n *\n * const stream = await agent.stream({\n * messages: [{ role: \"human\", content: \"What's 2+2 and the weather in NYC?\" }]\n * });\n *\n * for await (const chunk of stream) {\n * console.log(chunk); // State update from each node\n * }\n * ```\n */\n async stream(\n state: InvokeStateParameter<StateSchema, TMiddleware>,\n config?: StreamConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n >\n ): Promise<IterableReadableStream<any>> {\n const initializedState = await this.#initializeMiddlewareStates(state);\n return this.#graph.stream(initializedState, config as Record<string, any>);\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 /**\n * The following are internal methods to enable support for LangGraph Platform.\n * They are not part of the createAgent public API.\n *\n * Note: we intentionally return as `never` to avoid type errors due to type inference.\n */\n\n /**\n * @internal\n */\n streamEvents(\n state: InvokeStateParameter<StateSchema, TMiddleware>,\n config?: StreamConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n > & { version?: \"v1\" | \"v2\" },\n streamOptions?: Parameters<Runnable[\"streamEvents\"]>[2]\n ): IterableReadableStream<StreamEvent> {\n return this.#graph.streamEvents(\n state,\n {\n ...(config as any),\n version: config?.version ?? \"v2\",\n },\n streamOptions\n );\n }\n /**\n * @internal\n */\n getGraphAsync(config?: RunnableConfig) {\n return this.#graph.getGraphAsync(config) as never;\n }\n /**\n * @internal\n */\n getState(config: RunnableConfig, options?: GetStateOptions) {\n return this.#graph.getState(config, options) as never;\n }\n /**\n * @internal\n */\n getStateHistory(config: RunnableConfig, options?: CheckpointListOptions) {\n return this.#graph.getStateHistory(config, options) as never;\n }\n /**\n * @internal\n */\n getSubgraphs(namespace?: string, recurse?: boolean) {\n return this.#graph.getSubgraphs(namespace, recurse) as never;\n }\n /**\n * @internal\n */\n getSubgraphAsync(namespace?: string, recurse?: boolean) {\n return this.#graph.getSubgraphsAsync(namespace, recurse) as never;\n }\n /**\n * @internal\n */\n updateState(\n inputConfig: LangGraphRunnableConfig,\n values: Record<string, unknown> | unknown,\n asNode?: string\n ) {\n return this.#graph.updateState(inputConfig, values, asNode) as never;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA+GA,IAAa,aAAb,MAYE;CACA;CAOA,uBAAoC;CAEpC;CAEA,YACSA,SAKP;EALO;EAMP,KAAKC,uBAAuB,QAAQ,WAAW,KAAKA;;;;AAKpD,MAAI,CAAC,QAAQ,MACX,OAAM,IAAI,MAAM;;;;AAMlB,MAAI,OAAO,QAAQ,UAAU,UAC3B,2BAA2B,QAAQ,MAAM;;;;EAM3C,MAAM,kBAAmB,KAAK,QAAQ,YAClC,OAAO,CAAC,MAAM,EAAE,MAAM,CACvB,QAAQ,CAAC,MAAM,EAAE,MAAM,IAAI,CAAE;EAChC,MAAM,cAAc,CAAC,GAAI,QAAQ,SAAS,CAAE,GAAG,GAAG,eAAgB;;;;;EAMlE,MAAM,qBAAqB,IAAI,IAC7B,YACG,OAAO,aAAa,CACpB,OAAO,CAAC,SAAS,kBAAkB,QAAQ,KAAK,aAAa,CAC7D,IAAI,CAAC,SAAS,KAAK,KAAK;;;;;EAO7B,MAAM,SAAS,iCACb,KAAK,QAAQ,mBAAmB,QAChC,KAAK,QAAQ,aACb,KAAK,QAAQ,WACd;EAED,MAAM,WAAW,IAAI,WACnB,QACA,KAAK,QAAQ;EAGf,MAAM,mBAAmB;EAMzB,MAAMC,mBAIA,CAAE;EACR,MAAMC,mBAIA,CAAE;EACR,MAAMC,kB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AACtD,SAAO,KAAKzB,OAAO,kBAAkB,WAAW,QAAQ;CACzD;;;;CAID,YACE0B,aACAC,QACAC,QACA;AACA,SAAO,KAAK5B,OAAO,YAAY,aAAa,QAAQ,OAAO;CAC5D;AACF"}
1
+ {"version":3,"file":"ReactAgent.js","names":["options: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema\n >","#toolBehaviorVersion","beforeAgentNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[]","beforeModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[]","afterModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[]","afterAgentNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[]","wrapModelCallHookMiddleware: [\n AgentMiddleware,\n /**\n * ToDo: better type to get the state of middleware\n */\n () => any\n ][]","#agentNode","beforeAgentNode: BeforeAgentNode | undefined","beforeModelNode: BeforeModelNode | undefined","afterModelNode: AfterModelNode | undefined","afterAgentNode: AfterAgentNode | undefined","#stateManager","entryNode: string","#createBeforeAgentRouter","#createBeforeModelRouter","#getModelPaths","#createModelRouter","#createAfterModelSequenceRouter","#createAfterModelRouter","#createToolsRouter","#graph","toolClasses: (ClientTool | ServerTool)[]","includeModelRequest: boolean","paths: (\"tools\" | \"model_request\" | typeof END)[]","shouldReturnDirect: Set<string>","exitNode: string | typeof END","state: any","state: BuiltInState","allowJump: boolean","state: Omit<BuiltInState, \"jumpTo\"> & { jumpTo?: JumpTo }","allowed: string[]","nextDefault: string","#initializeMiddlewareStates","state: InvokeStateParameter<StateSchema, TMiddleware>","config: RunnableConfig","config?: InvokeConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n >","config?: StreamConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n >","params?: {\n withStyles?: boolean;\n curveStyle?: string;\n nodeColors?: Record<string, string>;\n wrapLabelNWords?: number;\n backgroundColor?: string;\n }","config?: StreamConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n > & { version?: \"v1\" | \"v2\" }","streamOptions?: Parameters<Runnable[\"streamEvents\"]>[2]","config?: RunnableConfig","options?: GetStateOptions","options?: CheckpointListOptions","namespace?: string","recurse?: boolean","inputConfig: LangGraphRunnableConfig","values: Record<string, unknown> | unknown","asNode?: string"],"sources":["../../src/agents/ReactAgent.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\n\nimport {\n AnnotationRoot,\n StateGraph,\n END,\n START,\n Send,\n Command,\n CompiledStateGraph,\n type GetStateOptions,\n type LangGraphRunnableConfig,\n} from \"@langchain/langgraph\";\nimport type { CheckpointListOptions } from \"@langchain/langgraph-checkpoint\";\nimport { ToolMessage, AIMessage } from \"@langchain/core/messages\";\nimport { IterableReadableStream } from \"@langchain/core/utils/stream\";\nimport type { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport type { StreamEvent } from \"@langchain/core/tracers/log_stream\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { createAgentAnnotationConditional } from \"./annotation.js\";\nimport {\n isClientTool,\n validateLLMHasNoBoundTools,\n wrapToolCall,\n} from \"./utils.js\";\n\nimport { AgentNode } from \"./nodes/AgentNode.js\";\nimport { ToolNode } from \"./nodes/ToolNode.js\";\nimport { BeforeAgentNode } from \"./nodes/BeforeAgentNode.js\";\nimport { BeforeModelNode } from \"./nodes/BeforeModelNode.js\";\nimport { AfterModelNode } from \"./nodes/AfterModelNode.js\";\nimport { AfterAgentNode } from \"./nodes/AfterAgentNode.js\";\nimport {\n initializeMiddlewareStates,\n parseJumpToTarget,\n} from \"./nodes/utils.js\";\nimport { StateManager } from \"./state.js\";\n\nimport type { WithStateGraphNodes } from \"./types.js\";\n\nimport type {\n CreateAgentParams,\n BuiltInState,\n JumpTo,\n UserInput,\n} from \"./types.js\";\nimport type { InvokeConfiguration, StreamConfiguration } from \"./runtime.js\";\nimport type {\n AgentMiddleware,\n InferMiddlewareContextInputs,\n InferMiddlewareStates,\n InferMiddlewareInputStates,\n InferContextInput,\n AnyAnnotationRoot,\n InferSchemaInput,\n ToAnnotationRoot,\n} from \"./middleware/types.js\";\nimport { type ResponseFormatUndefined } from \"./responses.js\";\nimport { getHookConstraint } from \"./middleware/utils.js\";\n\n// Helper type to get the state definition with middleware states\ntype MergedAgentState<\n StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined,\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined,\n TMiddleware extends readonly AgentMiddleware[]\n> = InferSchemaInput<StateSchema> &\n (StructuredResponseFormat extends ResponseFormatUndefined\n ? Omit<BuiltInState, \"jumpTo\">\n : Omit<BuiltInState, \"jumpTo\"> & {\n structuredResponse: StructuredResponseFormat;\n }) &\n InferMiddlewareStates<TMiddleware>;\n\ntype InvokeStateParameter<\n StateSchema extends AnyAnnotationRoot | InteropZodObject | undefined,\n TMiddleware extends readonly AgentMiddleware[]\n> =\n | (UserInput<StateSchema> & InferMiddlewareInputStates<TMiddleware>)\n | Command<any, any, any>\n | null;\n\ntype AgentGraph<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware[] = []\n> = CompiledStateGraph<\n any,\n any,\n any,\n any,\n MergedAgentState<StateSchema, StructuredResponseFormat, TMiddleware>,\n ToAnnotationRoot<ContextSchema>[\"spec\"],\n unknown\n>;\n\nexport class ReactAgent<\n StructuredResponseFormat extends\n | Record<string, any>\n | ResponseFormatUndefined = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n> {\n #graph: AgentGraph<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema,\n TMiddleware\n >;\n\n #toolBehaviorVersion: \"v1\" | \"v2\" = \"v2\";\n\n #agentNode: AgentNode<any, AnyAnnotationRoot>;\n\n #stateManager = new StateManager();\n\n constructor(\n public options: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema\n >\n ) {\n this.#toolBehaviorVersion = options.version ?? this.#toolBehaviorVersion;\n\n /**\n * validate that model option is provided\n */\n if (!options.model) {\n throw new Error(\"`model` option is required to create an agent.\");\n }\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n if (typeof options.model !== \"string\") {\n validateLLMHasNoBoundTools(options.model);\n }\n\n /**\n * define complete list of tools based on options and middleware\n */\n const middlewareTools = (this.options.middleware\n ?.filter((m) => m.tools)\n .flatMap((m) => m.tools) ?? []) as (ClientTool | ServerTool)[];\n const toolClasses = [...(options.tools ?? []), ...middlewareTools];\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 /**\n * Create a schema that merges agent base schema with middleware state schemas\n * Using Zod with withLangGraph ensures LangGraph Studio gets proper metadata\n */\n const schema = createAgentAnnotationConditional<StateSchema, TMiddleware>(\n this.options.responseFormat !== undefined,\n this.options.stateSchema as StateSchema,\n this.options.middleware as TMiddleware\n );\n\n const workflow = new StateGraph(\n schema as unknown as AnnotationRoot<any>,\n this.options.contextSchema\n );\n\n const allNodeWorkflows = workflow as WithStateGraphNodes<\n \"tools\" | \"model_request\" | string,\n typeof workflow\n >;\n\n // Generate node names for middleware nodes that have hooks\n const beforeAgentNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const beforeModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const afterModelNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const afterAgentNodes: {\n index: number;\n name: string;\n allowed?: string[];\n }[] = [];\n const wrapModelCallHookMiddleware: [\n AgentMiddleware,\n /**\n * ToDo: better type to get the state of middleware\n */\n () => any\n ][] = [];\n\n this.#agentNode = new AgentNode({\n model: this.options.model,\n systemPrompt: this.options.systemPrompt,\n includeAgentName: this.options.includeAgentName,\n name: this.options.name,\n responseFormat: this.options.responseFormat,\n middleware: this.options.middleware,\n toolClasses,\n shouldReturnDirect,\n signal: this.options.signal,\n wrapModelCallHookMiddleware,\n });\n\n const middlewareNames = new Set<string>();\n const middleware = this.options.middleware ?? [];\n for (let i = 0; i < middleware.length; i++) {\n let beforeAgentNode: BeforeAgentNode | undefined;\n let beforeModelNode: BeforeModelNode | undefined;\n let afterModelNode: AfterModelNode | undefined;\n let afterAgentNode: AfterAgentNode | undefined;\n const m = middleware[i];\n if (middlewareNames.has(m.name)) {\n throw new Error(`Middleware ${m.name} is defined multiple times`);\n }\n\n middlewareNames.add(m.name);\n if (m.beforeAgent) {\n beforeAgentNode = new BeforeAgentNode(m, {\n getState: () => this.#stateManager.getState(m.name),\n });\n this.#stateManager.addNode(m, beforeAgentNode);\n const name = `${m.name}.before_agent`;\n beforeAgentNodes.push({\n index: i,\n name,\n allowed: getHookConstraint(m.beforeAgent),\n });\n allNodeWorkflows.addNode(\n name,\n beforeAgentNode,\n beforeAgentNode.nodeOptions\n );\n }\n if (m.beforeModel) {\n beforeModelNode = new BeforeModelNode(m, {\n getState: () => this.#stateManager.getState(m.name),\n });\n this.#stateManager.addNode(m, beforeModelNode);\n const name = `${m.name}.before_model`;\n beforeModelNodes.push({\n index: i,\n name,\n allowed: getHookConstraint(m.beforeModel),\n });\n allNodeWorkflows.addNode(\n name,\n beforeModelNode,\n beforeModelNode.nodeOptions\n );\n }\n if (m.afterModel) {\n afterModelNode = new AfterModelNode(m, {\n getState: () => this.#stateManager.getState(m.name),\n });\n this.#stateManager.addNode(m, afterModelNode);\n const name = `${m.name}.after_model`;\n afterModelNodes.push({\n index: i,\n name,\n allowed: getHookConstraint(m.afterModel),\n });\n allNodeWorkflows.addNode(\n name,\n afterModelNode,\n afterModelNode.nodeOptions\n );\n }\n if (m.afterAgent) {\n afterAgentNode = new AfterAgentNode(m, {\n getState: () => this.#stateManager.getState(m.name),\n });\n this.#stateManager.addNode(m, afterAgentNode);\n const name = `${m.name}.after_agent`;\n afterAgentNodes.push({\n index: i,\n name,\n allowed: getHookConstraint(m.afterAgent),\n });\n allNodeWorkflows.addNode(\n name,\n afterAgentNode,\n afterAgentNode.nodeOptions\n );\n }\n\n if (m.wrapModelCall) {\n wrapModelCallHookMiddleware.push([\n m,\n () => this.#stateManager.getState(m.name),\n ]);\n }\n }\n\n /**\n * Add Nodes\n */\n allNodeWorkflows.addNode(\"model_request\", this.#agentNode);\n\n /**\n * add single tool node for all tools\n */\n if (toolClasses.filter(isClientTool).length > 0) {\n const toolNode = new ToolNode(toolClasses.filter(isClientTool), {\n signal: this.options.signal,\n wrapToolCall: wrapToolCall(middleware),\n });\n allNodeWorkflows.addNode(\"tools\", toolNode);\n }\n\n /**\n * Add Edges\n */\n // Determine the entry node (runs once at start): before_agent -> before_model -> model_request\n let entryNode: string;\n if (beforeAgentNodes.length > 0) {\n entryNode = beforeAgentNodes[0].name;\n } else if (beforeModelNodes.length > 0) {\n entryNode = beforeModelNodes[0].name;\n } else {\n entryNode = \"model_request\";\n }\n\n // Determine the loop entry node (beginning of agent loop, excludes before_agent)\n // This is where tools will loop back to for the next iteration\n const loopEntryNode =\n beforeModelNodes.length > 0 ? beforeModelNodes[0].name : \"model_request\";\n\n // Determine the exit node (runs once at end): after_agent or END\n const exitNode =\n afterAgentNodes.length > 0\n ? afterAgentNodes[afterAgentNodes.length - 1].name\n : END;\n\n allNodeWorkflows.addEdge(START, entryNode);\n\n // Connect beforeAgent nodes (run once at start)\n for (let i = 0; i < beforeAgentNodes.length; i++) {\n const node = beforeAgentNodes[i];\n const current = node.name;\n const isLast = i === beforeAgentNodes.length - 1;\n const nextDefault = isLast ? loopEntryNode : beforeAgentNodes[i + 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const hasTools = toolClasses.filter(isClientTool).length > 0;\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== \"tools\" || hasTools);\n // Replace END with exitNode (which could be an afterAgent node)\n const destinations = Array.from(\n new Set([\n nextDefault,\n ...allowedMapped.map((dest) => (dest === END ? exitNode : dest)),\n ])\n ) as (\"tools\" | \"model_request\" | typeof END)[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createBeforeAgentRouter(\n toolClasses.filter(isClientTool),\n nextDefault,\n exitNode\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect beforeModel nodes; add conditional routing ONLY if allowed jumps are specified\n for (let i = 0; i < beforeModelNodes.length; i++) {\n const node = beforeModelNodes[i];\n const current = node.name;\n const isLast = i === beforeModelNodes.length - 1;\n const nextDefault = isLast\n ? \"model_request\"\n : beforeModelNodes[i + 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const hasTools = toolClasses.filter(isClientTool).length > 0;\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== \"tools\" || hasTools);\n const destinations = Array.from(\n new Set([nextDefault, ...allowedMapped])\n ) as (\"tools\" | \"model_request\" | typeof END)[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createBeforeModelRouter(\n toolClasses.filter(isClientTool),\n nextDefault\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect agent to last afterModel node (for reverse order execution)\n const lastAfterModelNode = afterModelNodes.at(-1);\n if (afterModelNodes.length > 0 && lastAfterModelNode) {\n allNodeWorkflows.addEdge(\"model_request\", lastAfterModelNode.name);\n } else {\n // If no afterModel nodes, connect model_request directly to model paths\n const modelPaths = this.#getModelPaths(toolClasses.filter(isClientTool));\n // Replace END with exitNode in destinations, since exitNode might be an afterAgent node\n const destinations = modelPaths.map((p) =>\n p === END ? exitNode : p\n ) as (\"tools\" | \"model_request\" | typeof END)[];\n if (destinations.length === 1) {\n allNodeWorkflows.addEdge(\"model_request\", destinations[0]);\n } else {\n allNodeWorkflows.addConditionalEdges(\n \"model_request\",\n this.#createModelRouter(exitNode),\n destinations\n );\n }\n }\n\n // Connect afterModel nodes in reverse sequence; add conditional routing ONLY if allowed jumps are specified per node\n for (let i = afterModelNodes.length - 1; i > 0; i--) {\n const node = afterModelNodes[i];\n const current = node.name;\n const nextDefault = afterModelNodes[i - 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const hasTools = toolClasses.filter(isClientTool).length > 0;\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== \"tools\" || hasTools);\n const destinations = Array.from(\n new Set([nextDefault, ...allowedMapped])\n ) as (\"tools\" | \"model_request\" | typeof END)[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createAfterModelSequenceRouter(\n toolClasses.filter(isClientTool),\n node.allowed,\n nextDefault\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect first afterModel node (last to execute) to model paths with jumpTo support\n if (afterModelNodes.length > 0) {\n const firstAfterModel = afterModelNodes[0];\n const firstAfterModelNode = firstAfterModel.name;\n\n // Include exitNode in the paths since afterModel should be able to route to after_agent or END\n const modelPaths = this.#getModelPaths(\n toolClasses.filter(isClientTool),\n true\n ).filter(\n (p) => p !== \"tools\" || toolClasses.filter(isClientTool).length > 0\n );\n\n const allowJump = Boolean(\n firstAfterModel.allowed && firstAfterModel.allowed.length > 0\n );\n\n // Replace END with exitNode in destinations, since exitNode might be an afterAgent node\n const destinations = modelPaths.map((p) =>\n p === END ? exitNode : p\n ) as (\"tools\" | \"model_request\" | typeof END)[];\n\n allNodeWorkflows.addConditionalEdges(\n firstAfterModelNode,\n this.#createAfterModelRouter(\n toolClasses.filter(isClientTool),\n allowJump,\n exitNode\n ),\n destinations\n );\n }\n\n // Connect afterAgent nodes (run once at end, in reverse order like afterModel)\n for (let i = afterAgentNodes.length - 1; i > 0; i--) {\n const node = afterAgentNodes[i];\n const current = node.name;\n const nextDefault = afterAgentNodes[i - 1].name;\n\n if (node.allowed && node.allowed.length > 0) {\n const hasTools = toolClasses.filter(isClientTool).length > 0;\n const allowedMapped = node.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== \"tools\" || hasTools);\n const destinations = Array.from(\n new Set([nextDefault, ...allowedMapped])\n ) as (\"tools\" | \"model_request\" | typeof END)[];\n\n allNodeWorkflows.addConditionalEdges(\n current,\n this.#createAfterModelSequenceRouter(\n toolClasses.filter(isClientTool),\n node.allowed,\n nextDefault\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(current, nextDefault);\n }\n }\n\n // Connect the first afterAgent node (last to execute) to END\n if (afterAgentNodes.length > 0) {\n const firstAfterAgent = afterAgentNodes[0];\n const firstAfterAgentNode = firstAfterAgent.name;\n\n if (firstAfterAgent.allowed && firstAfterAgent.allowed.length > 0) {\n const hasTools = toolClasses.filter(isClientTool).length > 0;\n const allowedMapped = firstAfterAgent.allowed\n .map((t) => parseJumpToTarget(t))\n .filter((dest) => dest !== \"tools\" || hasTools);\n\n /**\n * For after_agent, only use explicitly allowed destinations (don't add loopEntryNode)\n * The default destination (when no jump occurs) should be END\n */\n const destinations = Array.from(new Set([END, ...allowedMapped])) as (\n | \"tools\"\n | \"model_request\"\n | typeof END\n )[];\n\n allNodeWorkflows.addConditionalEdges(\n firstAfterAgentNode,\n this.#createAfterModelSequenceRouter(\n toolClasses.filter(isClientTool),\n firstAfterAgent.allowed,\n END as string\n ),\n destinations\n );\n } else {\n allNodeWorkflows.addEdge(firstAfterAgentNode, END);\n }\n }\n\n /**\n * add edges for tools node\n */\n if (toolClasses.filter(isClientTool).length > 0) {\n // Tools should return to loop entry node (not including before_agent)\n const toolReturnTarget = loopEntryNode;\n\n if (shouldReturnDirect.size > 0) {\n allNodeWorkflows.addConditionalEdges(\n \"tools\",\n this.#createToolsRouter(shouldReturnDirect, exitNode),\n [toolReturnTarget, exitNode as string]\n );\n } else {\n allNodeWorkflows.addEdge(\"tools\", toolReturnTarget);\n }\n }\n\n /**\n * compile the graph\n */\n this.#graph = allNodeWorkflows.compile({\n checkpointer: this.options.checkpointer,\n store: this.options.store,\n name: this.options.name,\n description: this.options.description,\n }) as AgentGraph<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema,\n TMiddleware\n >;\n }\n\n /**\n * Get the compiled {@link https://docs.langchain.com/oss/javascript/langgraph/use-graph-api | StateGraph}.\n */\n get graph(): AgentGraph<\n StateSchema,\n StructuredResponseFormat,\n ContextSchema,\n TMiddleware\n > {\n return this.#graph;\n }\n\n /**\n * Get possible edge destinations from model node.\n * @param toolClasses names of tools to call\n * @param includeModelRequest whether to include \"model_request\" as a valid path (for jumpTo routing)\n * @returns list of possible edge destinations\n */\n #getModelPaths(\n toolClasses: (ClientTool | ServerTool)[],\n includeModelRequest: boolean = false\n ): (\"tools\" | \"model_request\" | typeof END)[] {\n const paths: (\"tools\" | \"model_request\" | typeof END)[] = [];\n if (toolClasses.length > 0) {\n paths.push(\"tools\");\n }\n\n if (includeModelRequest) {\n paths.push(\"model_request\");\n }\n\n paths.push(END);\n\n return paths;\n }\n\n /**\n * Create routing function for tools node conditional edges.\n */\n #createToolsRouter(\n shouldReturnDirect: Set<string>,\n exitNode: string | typeof END\n ) {\n /**\n * ToDo: fix type\n */\n return (state: any) => {\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 ToolMessage.isInstance(lastMessage) &&\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 to exit node (could be after_agent or END)\n return this.options.responseFormat ? \"model_request\" : exitNode;\n }\n\n // For non-returnDirect tools, always route back to agent\n return \"model_request\";\n };\n }\n\n /**\n * Create routing function for model node conditional edges.\n * @param exitNode - The exit node to route to (could be after_agent or END)\n */\n #createModelRouter(exitNode: string | typeof END = END) {\n /**\n * determine if the agent should continue or not\n */\n return (state: BuiltInState) => {\n const messages = state.messages;\n const lastMessage = messages.at(-1);\n\n if (\n !AIMessage.isInstance(lastMessage) ||\n !lastMessage.tool_calls ||\n lastMessage.tool_calls.length === 0\n ) {\n return exitNode;\n }\n\n // Check if all tool calls are for structured response extraction\n const hasOnlyStructuredResponseCalls = lastMessage.tool_calls.every(\n (toolCall) => toolCall.name.startsWith(\"extract-\")\n );\n\n if (hasOnlyStructuredResponseCalls) {\n // If all tool calls are for structured response extraction, go to exit node\n // The AgentNode will handle these internally and return the structured response\n return exitNode;\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 (filter out any structured response tool calls)\n */\n const regularToolCalls = lastMessage.tool_calls.filter(\n (toolCall) => !toolCall.name.startsWith(\"extract-\")\n );\n\n if (regularToolCalls.length === 0) {\n return exitNode;\n }\n\n return regularToolCalls.map(\n (toolCall) => new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n };\n }\n\n /**\n * Create routing function for jumpTo functionality after afterModel hooks.\n *\n * This router checks if the `jumpTo` property is set in the state after afterModel middleware\n * execution. If set, it routes to the specified target (\"model_request\" or \"tools\").\n * If not set, it falls back to the normal model routing logic for afterModel context.\n *\n * The jumpTo property is automatically cleared after use to prevent infinite loops.\n *\n * @param toolClasses - Available tool classes for validation\n * @param allowJump - Whether jumping is allowed\n * @param exitNode - The exit node to route to (could be after_agent or END)\n * @returns Router function that handles jumpTo logic and normal routing\n */\n #createAfterModelRouter(\n toolClasses: (ClientTool | ServerTool)[],\n allowJump: boolean,\n exitNode: string | typeof END\n ) {\n const hasStructuredResponse = Boolean(this.options.responseFormat);\n\n return (state: Omit<BuiltInState, \"jumpTo\"> & { jumpTo?: JumpTo }) => {\n // First, check if we just processed a structured response\n // If so, ignore any existing jumpTo and go to exitNode\n const messages = state.messages;\n const lastMessage = messages.at(-1);\n if (\n AIMessage.isInstance(lastMessage) &&\n (!lastMessage.tool_calls || lastMessage.tool_calls.length === 0)\n ) {\n return exitNode;\n }\n\n // Check if jumpTo is set in the state and allowed\n if (allowJump && state.jumpTo) {\n if (state.jumpTo === END) {\n return exitNode;\n }\n if (state.jumpTo === \"tools\") {\n // If trying to jump to tools but no tools are available, go to exitNode\n if (toolClasses.length === 0) {\n return exitNode;\n }\n return new Send(\"tools\", { ...state, jumpTo: undefined });\n }\n // destination === \"model_request\"\n return new Send(\"model_request\", { ...state, jumpTo: undefined });\n }\n\n // check if there are pending tool calls\n const toolMessages = messages.filter(ToolMessage.isInstance);\n const lastAiMessage = messages.filter(AIMessage.isInstance).at(-1);\n const pendingToolCalls = lastAiMessage?.tool_calls?.filter(\n (call) => !toolMessages.some((m) => m.tool_call_id === call.id)\n );\n if (pendingToolCalls && pendingToolCalls.length > 0) {\n return pendingToolCalls.map(\n (toolCall) => new Send(\"tools\", { ...state, lg_tool_call: toolCall })\n );\n }\n\n // if we exhausted all tool calls, but still have no structured response tool calls,\n // go back to model_request\n const hasStructuredResponseCalls = lastAiMessage?.tool_calls?.some(\n (toolCall) => toolCall.name.startsWith(\"extract-\")\n );\n\n if (\n pendingToolCalls &&\n pendingToolCalls.length === 0 &&\n !hasStructuredResponseCalls &&\n hasStructuredResponse\n ) {\n return \"model_request\";\n }\n\n if (\n !AIMessage.isInstance(lastMessage) ||\n !lastMessage.tool_calls ||\n lastMessage.tool_calls.length === 0\n ) {\n return exitNode;\n }\n\n // Check if all tool calls are for structured response extraction\n const hasOnlyStructuredResponseCalls = lastMessage.tool_calls.every(\n (toolCall) => toolCall.name.startsWith(\"extract-\")\n );\n\n // Check if there are any regular tool calls (non-structured response)\n const hasRegularToolCalls = lastMessage.tool_calls.some(\n (toolCall) => !toolCall.name.startsWith(\"extract-\")\n );\n\n if (hasOnlyStructuredResponseCalls || !hasRegularToolCalls) {\n return exitNode;\n }\n\n /**\n * For routing from afterModel nodes, always use simple string paths\n * The Send API is handled at the model_request node level\n */\n return \"tools\";\n };\n }\n\n /**\n * Router for afterModel sequence nodes (connecting later middlewares to earlier ones),\n * honoring allowed jump targets and defaulting to the next node.\n */\n #createAfterModelSequenceRouter(\n toolClasses: (ClientTool | ServerTool)[],\n allowed: string[],\n nextDefault: string\n ) {\n const allowedSet = new Set(allowed.map((t) => parseJumpToTarget(t)));\n return (state: BuiltInState) => {\n if (state.jumpTo) {\n const dest = parseJumpToTarget(state.jumpTo);\n if (dest === END && allowedSet.has(END)) {\n return END;\n }\n if (dest === \"tools\" && allowedSet.has(\"tools\")) {\n if (toolClasses.length === 0) return END;\n return new Send(\"tools\", { ...state, jumpTo: undefined });\n }\n if (dest === \"model_request\" && allowedSet.has(\"model_request\")) {\n return new Send(\"model_request\", { ...state, jumpTo: undefined });\n }\n }\n return nextDefault as any;\n };\n }\n\n /**\n * Create routing function for jumpTo functionality after beforeAgent hooks.\n * Falls back to the default next node if no jumpTo is present.\n * When jumping to END, routes to exitNode (which could be an afterAgent node).\n */\n #createBeforeAgentRouter(\n toolClasses: (ClientTool | ServerTool)[],\n nextDefault: string,\n exitNode: string | typeof END\n ) {\n return (state: BuiltInState) => {\n if (!state.jumpTo) {\n return nextDefault;\n }\n const destination = parseJumpToTarget(state.jumpTo);\n if (destination === END) {\n // When beforeAgent jumps to END, route to exitNode (first afterAgent node)\n return exitNode;\n }\n if (destination === \"tools\") {\n if (toolClasses.length === 0) {\n return exitNode;\n }\n return new Send(\"tools\", { ...state, jumpTo: undefined });\n }\n // destination === \"model_request\"\n return new Send(\"model_request\", { ...state, jumpTo: undefined });\n };\n }\n\n /**\n * Create routing function for jumpTo functionality after beforeModel hooks.\n * Falls back to the default next node if no jumpTo is present.\n */\n #createBeforeModelRouter(\n toolClasses: (ClientTool | ServerTool)[],\n nextDefault: string\n ) {\n return (state: BuiltInState) => {\n if (!state.jumpTo) {\n return nextDefault;\n }\n const destination = parseJumpToTarget(state.jumpTo);\n if (destination === END) {\n return END;\n }\n if (destination === \"tools\") {\n if (toolClasses.length === 0) {\n return END;\n }\n return new Send(\"tools\", { ...state, jumpTo: undefined });\n }\n // destination === \"model_request\"\n return new Send(\"model_request\", { ...state, jumpTo: undefined });\n };\n }\n\n /**\n * Initialize middleware states if not already present in the input state.\n */\n async #initializeMiddlewareStates(\n state: InvokeStateParameter<StateSchema, TMiddleware>,\n config: RunnableConfig\n ): Promise<InvokeStateParameter<StateSchema, TMiddleware>> {\n if (\n !this.options.middleware ||\n this.options.middleware.length === 0 ||\n state instanceof Command ||\n !state\n ) {\n return state;\n }\n\n const defaultStates = await initializeMiddlewareStates(\n this.options.middleware,\n state\n );\n const threadState = await this.#graph\n .getState(config)\n .catch(() => ({ values: {} }));\n const updatedState = {\n ...threadState.values,\n ...state,\n } as InvokeStateParameter<StateSchema, TMiddleware>;\n if (!updatedState) {\n return updatedState;\n }\n\n // Only add defaults for keys that don't exist in current state\n for (const [key, value] of Object.entries(defaultStates)) {\n if (!(key in updatedState)) {\n updatedState[key as keyof typeof updatedState] = value;\n }\n }\n\n return updatedState;\n }\n\n /**\n * Executes the agent with the given state and returns the final state after all processing.\n *\n * This method runs the agent's entire workflow synchronously, including:\n * - Processing the input messages through any configured middleware\n * - Calling the language model to generate responses\n * - Executing any tool calls made by the model\n * - Running all middleware hooks (beforeModel, afterModel, etc.)\n *\n * @param state - The initial state for the agent execution. Can be:\n * - An object containing `messages` array and any middleware-specific state properties\n * - A Command object for more advanced control flow\n *\n * @param config - Optional runtime configuration including:\n * @param config.context - The context for the agent execution.\n * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc.\n * @param config.store - The store for the agent execution for persisting state, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Memory storage}.\n * @param config.signal - An optional {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} for the agent execution.\n * @param config.recursionLimit - The recursion limit for the agent execution.\n *\n * @returns A Promise that resolves to the final agent state after execution completes.\n * The returned state includes:\n * - a `messages` property containing an array with all messages (input, AI responses, tool calls/results)\n * - a `structuredResponse` property containing the structured response (if configured)\n * - all state values defined in the middleware\n *\n * @example\n * ```typescript\n * const agent = new ReactAgent({\n * llm: myModel,\n * tools: [calculator, webSearch],\n * responseFormat: z.object({\n * weather: z.string(),\n * }),\n * });\n *\n * const result = await agent.invoke({\n * messages: [{ role: \"human\", content: \"What's the weather in Paris?\" }]\n * });\n *\n * console.log(result.structuredResponse.weather); // outputs: \"It's sunny and 75°F.\"\n * ```\n */\n async invoke(\n state: InvokeStateParameter<StateSchema, TMiddleware>,\n config?: InvokeConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n >\n ) {\n type FullState = MergedAgentState<\n StateSchema,\n StructuredResponseFormat,\n TMiddleware\n >;\n const initializedState = await this.#initializeMiddlewareStates(\n state,\n config as RunnableConfig\n );\n\n return this.#graph.invoke(\n initializedState,\n config as unknown as InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n ) as Promise<FullState>;\n }\n\n /**\n * Executes the agent with streaming, returning an async iterable of state updates as they occur.\n *\n * This method runs the agent's workflow similar to `invoke`, but instead of waiting for\n * completion, it streams high-level state updates in real-time. This allows you to:\n * - Display intermediate results to users as they're generated\n * - Monitor the agent's progress through each step\n * - React to state changes as nodes complete\n *\n * For more granular event-level streaming (like individual LLM tokens), use `streamEvents` instead.\n *\n * @param state - The initial state for the agent execution. Can be:\n * - An object containing `messages` array and any middleware-specific state properties\n * - A Command object for more advanced control flow\n *\n * @param config - Optional runtime configuration including:\n * @param config.context - The context for the agent execution.\n * @param config.configurable - LangGraph configuration options like `thread_id`, `run_id`, etc.\n * @param config.store - The store for the agent execution for persisting state, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/memory#memory-storage | Memory storage}.\n * @param config.signal - An optional {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal | `AbortSignal`} for the agent execution.\n * @param config.streamMode - The streaming mode for the agent execution, see more in {@link https://docs.langchain.com/oss/javascript/langgraph/streaming#supported-stream-modes | Supported stream modes}.\n * @param config.recursionLimit - The recursion limit for the agent execution.\n *\n * @returns A Promise that resolves to an IterableReadableStream of state updates.\n * Each update contains the current state after a node completes.\n *\n * @example\n * ```typescript\n * const agent = new ReactAgent({\n * llm: myModel,\n * tools: [calculator, webSearch]\n * });\n *\n * const stream = await agent.stream({\n * messages: [{ role: \"human\", content: \"What's 2+2 and the weather in NYC?\" }]\n * });\n *\n * for await (const chunk of stream) {\n * console.log(chunk); // State update from each node\n * }\n * ```\n */\n async stream(\n state: InvokeStateParameter<StateSchema, TMiddleware>,\n config?: StreamConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n >\n ): Promise<IterableReadableStream<any>> {\n const initializedState = await this.#initializeMiddlewareStates(\n state,\n config as RunnableConfig\n );\n return this.#graph.stream(initializedState, config as Record<string, any>);\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 /**\n * The following are internal methods to enable support for LangGraph Platform.\n * They are not part of the createAgent public API.\n *\n * Note: we intentionally return as `never` to avoid type errors due to type inference.\n */\n\n /**\n * @internal\n */\n streamEvents(\n state: InvokeStateParameter<StateSchema, TMiddleware>,\n config?: StreamConfiguration<\n InferContextInput<ContextSchema> &\n InferMiddlewareContextInputs<TMiddleware>\n > & { version?: \"v1\" | \"v2\" },\n streamOptions?: Parameters<Runnable[\"streamEvents\"]>[2]\n ): IterableReadableStream<StreamEvent> {\n return this.#graph.streamEvents(\n state,\n {\n ...(config as any),\n version: config?.version ?? \"v2\",\n },\n streamOptions\n );\n }\n /**\n * @internal\n */\n getGraphAsync(config?: RunnableConfig) {\n return this.#graph.getGraphAsync(config) as never;\n }\n /**\n * @internal\n */\n getState(config: RunnableConfig, options?: GetStateOptions) {\n return this.#graph.getState(config, options) as never;\n }\n /**\n * @internal\n */\n getStateHistory(config: RunnableConfig, options?: CheckpointListOptions) {\n return this.#graph.getStateHistory(config, options) as never;\n }\n /**\n * @internal\n */\n getSubgraphs(namespace?: string, recurse?: boolean) {\n return this.#graph.getSubgraphs(namespace, recurse) as never;\n }\n /**\n * @internal\n */\n getSubgraphAsync(namespace?: string, recurse?: boolean) {\n return this.#graph.getSubgraphsAsync(namespace, recurse) as never;\n }\n /**\n * @internal\n */\n updateState(\n inputConfig: LangGraphRunnableConfig,\n values: Record<string, unknown> | unknown,\n asNode?: string\n ) {\n return this.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Ae;EACxD,MAAM,QAAQ,MAAM,eAAe,eAAe,OAAO;EACzD,MAAM,cAAc,MAAM,MAAM,aAAa;EAC7C,MAAM,SAAS,IAAI,WAAW;AAC9B,SAAO;CACR;;;;;;;;;;;CAYD,MAAM,YAAYiB,QAMf;EACD,MAAM,iBAAiB,MAAM,KAAKjB,OAAO,eAAe;AACxD,SAAO,eAAe,YAAY,OAAO;CAC1C;;;;;;;;;;CAYD,aACEa,OACAK,QAIAC,eACqC;AACrC,SAAO,KAAKnB,OAAO,aACjB,OACA;GACE,GAAI;GACJ,SAAS,QAAQ,WAAW;EAC7B,GACD,cACD;CACF;;;;CAID,cAAcoB,QAAyB;AACrC,SAAO,KAAKpB,OAAO,cAAc,OAAO;CACzC;;;;CAID,SAASc,QAAwBO,SAA2B;AAC1D,SAAO,KAAKrB,OAAO,SAAS,QAAQ,QAAQ;CAC7C;;;;CAID,gBAAgBc,QAAwBQ,SAAiC;AACvE,SAAO,KAAKtB,OAAO,gBAAgB,QAAQ,QAAQ;CACpD;;;;CAID,aAAauB,WAAoBC,SAAmB;AAClD,SAAO,KAAKxB,OAAO,aAAa,WAAW,QAAQ;CACpD;;;;CAID,iBAAiBuB,WAAoBC,SAAmB;AACtD,SAAO,KAAKxB,OAAO,kBAAkB,WAAW,QAAQ;CACzD;;;;CAID,YACEyB,aACAC,QACAC,QACA;AACA,SAAO,KAAK3B,OAAO,YAAY,aAAa,QAAQ,OAAO;CAC5D;AACF"}
@@ -14,6 +14,7 @@ function createAgentAnnotationConditional(hasStructuredResponse = true, stateSch
14
14
  jumpTo: zod_v3.z.union([
15
15
  zod_v3.z.literal("model_request"),
16
16
  zod_v3.z.literal("tools"),
17
+ zod_v3.z.literal("end"),
17
18
  zod_v3.z.undefined()
18
19
  ]).optional()
19
20
  };
@@ -1 +1 @@
1
- {"version":3,"file":"annotation.cjs","names":["stateSchema: TStateSchema","middlewareList: TMiddleware","zodSchema: Record<string, any>","z","MessagesZodMeta","schema: { shape: Record<string, any> }","schema","PreHookAnnotation: AnnotationRoot<{\n llmInputMessages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}>","_x: Messages","update: Messages"],"sources":["../../src/agents/annotation.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { BaseMessage } from \"@langchain/core/messages\";\nimport { z } from \"zod/v3\";\nimport {\n Messages,\n AnnotationRoot,\n MessagesZodMeta,\n type BinaryOperatorAggregate,\n} from \"@langchain/langgraph\";\nimport { withLangGraph } from \"@langchain/langgraph/zod\";\n\nimport type { AgentMiddleware, AnyAnnotationRoot } from \"./middleware/types.js\";\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\n\nexport function createAgentAnnotationConditional<\n TStateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n TMiddleware extends readonly AgentMiddleware<any, any, any>[] = []\n>(\n hasStructuredResponse = true,\n stateSchema: TStateSchema,\n middlewareList: TMiddleware = [] as unknown as TMiddleware\n) {\n /**\n * Create Zod schema object to preserve jsonSchemaExtra\n * metadata for LangGraph Studio using v3-compatible withLangGraph\n */\n const zodSchema: Record<string, any> = {\n messages: withLangGraph(z.custom<BaseMessage[]>(), MessagesZodMeta),\n jumpTo: z\n .union([z.literal(\"model_request\"), z.literal(\"tools\"), z.undefined()])\n .optional(),\n };\n\n const applySchema = (schema: { shape: Record<string, any> }) => {\n const { shape } = schema;\n for (const [key, schema] of Object.entries(shape)) {\n /**\n * Skip private state properties\n */\n if (key.startsWith(\"_\")) {\n continue;\n }\n\n if (!(key in zodSchema)) {\n zodSchema[key] = schema;\n }\n }\n };\n\n // Add state schema properties to the Zod schema\n if (stateSchema && \"shape\" in stateSchema) {\n applySchema(stateSchema);\n }\n\n for (const middleware of middlewareList) {\n if (middleware.stateSchema) {\n applySchema(middleware.stateSchema);\n }\n }\n\n // Only include structuredResponse when responseFormat is defined\n if (hasStructuredResponse) {\n zodSchema.structuredResponse = z.any().optional();\n }\n\n return z.object(zodSchema);\n}\n\nexport const PreHookAnnotation: AnnotationRoot<{\n llmInputMessages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}> = z.object({\n llmInputMessages: withLangGraph(z.custom<BaseMessage[]>(), {\n reducer: {\n fn: (_x: Messages, update: Messages) =>\n MessagesZodMeta.reducer!.fn([], update),\n },\n default: () => [],\n }),\n /**\n * Use MessagesZodMeta to preserve jsonSchemaExtra metadata\n * for LangGraph Studio UI to render proper messages input field\n */\n messages: withLangGraph(z.custom<BaseMessage[]>(), MessagesZodMeta),\n}) as unknown as AnnotationRoot<{\n llmInputMessages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}>;\n\nexport type PreHookAnnotation = typeof PreHookAnnotation;\n"],"mappings":";;;;;;AAcA,SAAgB,iCAOd,wBAAwB,MACxBA,aACAC,iBAA8B,CAAE,GAChC;;;;;CAKA,MAAMC,YAAiC;EACrC,uDAAwBC,SAAE,QAAuB,EAAEC,sCAAgB;EACnE,QAAQD,SACL,MAAM;GAACA,SAAE,QAAQ,gBAAgB;GAAEA,SAAE,QAAQ,QAAQ;GAAEA,SAAE,WAAW;EAAC,EAAC,CACtE,UAAU;CACd;CAED,MAAM,cAAc,CAACE,WAA2C;EAC9D,MAAM,EAAE,OAAO,GAAG;AAClB,OAAK,MAAM,CAAC,KAAKC,SAAO,IAAI,OAAO,QAAQ,MAAM,EAAE;;;;AAIjD,OAAI,IAAI,WAAW,IAAI,CACrB;AAGF,OAAI,EAAE,OAAO,YACX,UAAU,OAAOA;EAEpB;CACF;AAGD,KAAI,eAAe,WAAW,aAC5B,YAAY,YAAY;AAG1B,MAAK,MAAM,cAAc,eACvB,KAAI,WAAW,aACb,YAAY,WAAW,YAAY;AAKvC,KAAI,uBACF,UAAU,qBAAqBH,SAAE,KAAK,CAAC,UAAU;AAGnD,QAAOA,SAAE,OAAO,UAAU;AAC3B;AAED,MAAaI,oBAGRJ,SAAE,OAAO;CACZ,+DAAgCA,SAAE,QAAuB,EAAE;EACzD,SAAS,EACP,IAAI,CAACK,IAAcC,WACjBL,sCAAgB,QAAS,GAAG,CAAE,GAAE,OAAO,CAC1C;EACD,SAAS,MAAM,CAAE;CAClB,EAAC;CAKF,uDAAwBD,SAAE,QAAuB,EAAEC,sCAAgB;AACpE,EAAC"}
1
+ {"version":3,"file":"annotation.cjs","names":["stateSchema: TStateSchema","middlewareList: TMiddleware","zodSchema: Record<string, any>","z","MessagesZodMeta","schema: { shape: Record<string, any> }","schema","PreHookAnnotation: AnnotationRoot<{\n llmInputMessages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}>","_x: Messages","update: Messages"],"sources":["../../src/agents/annotation.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { BaseMessage } from \"@langchain/core/messages\";\nimport { z } from \"zod/v3\";\nimport {\n Messages,\n AnnotationRoot,\n MessagesZodMeta,\n type BinaryOperatorAggregate,\n} from \"@langchain/langgraph\";\nimport { withLangGraph } from \"@langchain/langgraph/zod\";\n\nimport type { AgentMiddleware, AnyAnnotationRoot } from \"./middleware/types.js\";\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\n\nexport function createAgentAnnotationConditional<\n TStateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n TMiddleware extends readonly AgentMiddleware<any, any, any>[] = []\n>(\n hasStructuredResponse = true,\n stateSchema: TStateSchema,\n middlewareList: TMiddleware = [] as unknown as TMiddleware\n) {\n /**\n * Create Zod schema object to preserve jsonSchemaExtra\n * metadata for LangGraph Studio using v3-compatible withLangGraph\n */\n const zodSchema: Record<string, any> = {\n messages: withLangGraph(z.custom<BaseMessage[]>(), MessagesZodMeta),\n jumpTo: z\n .union([\n z.literal(\"model_request\"),\n z.literal(\"tools\"),\n z.literal(\"end\"),\n z.undefined(),\n ])\n .optional(),\n };\n\n const applySchema = (schema: { shape: Record<string, any> }) => {\n const { shape } = schema;\n for (const [key, schema] of Object.entries(shape)) {\n /**\n * Skip private state properties\n */\n if (key.startsWith(\"_\")) {\n continue;\n }\n\n if (!(key in zodSchema)) {\n zodSchema[key] = schema;\n }\n }\n };\n\n // Add state schema properties to the Zod schema\n if (stateSchema && \"shape\" in stateSchema) {\n applySchema(stateSchema);\n }\n\n for (const middleware of middlewareList) {\n if (middleware.stateSchema) {\n applySchema(middleware.stateSchema);\n }\n }\n\n // Only include structuredResponse when responseFormat is defined\n if (hasStructuredResponse) {\n zodSchema.structuredResponse = z.any().optional();\n }\n\n return z.object(zodSchema);\n}\n\nexport const PreHookAnnotation: AnnotationRoot<{\n llmInputMessages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}> = z.object({\n llmInputMessages: withLangGraph(z.custom<BaseMessage[]>(), {\n reducer: {\n fn: (_x: Messages, update: Messages) =>\n MessagesZodMeta.reducer!.fn([], update),\n },\n default: () => [],\n }),\n /**\n * Use MessagesZodMeta to preserve jsonSchemaExtra metadata\n * for LangGraph Studio UI to render proper messages input field\n */\n messages: withLangGraph(z.custom<BaseMessage[]>(), MessagesZodMeta),\n}) as unknown as AnnotationRoot<{\n llmInputMessages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}>;\n\nexport type PreHookAnnotation = typeof PreHookAnnotation;\n"],"mappings":";;;;;;AAcA,SAAgB,iCAOd,wBAAwB,MACxBA,aACAC,iBAA8B,CAAE,GAChC;;;;;CAKA,MAAMC,YAAiC;EACrC,uDAAwBC,SAAE,QAAuB,EAAEC,sCAAgB;EACnE,QAAQD,SACL,MAAM;GACLA,SAAE,QAAQ,gBAAgB;GAC1BA,SAAE,QAAQ,QAAQ;GAClBA,SAAE,QAAQ,MAAM;GAChBA,SAAE,WAAW;EACd,EAAC,CACD,UAAU;CACd;CAED,MAAM,cAAc,CAACE,WAA2C;EAC9D,MAAM,EAAE,OAAO,GAAG;AAClB,OAAK,MAAM,CAAC,KAAKC,SAAO,IAAI,OAAO,QAAQ,MAAM,EAAE;;;;AAIjD,OAAI,IAAI,WAAW,IAAI,CACrB;AAGF,OAAI,EAAE,OAAO,YACX,UAAU,OAAOA;EAEpB;CACF;AAGD,KAAI,eAAe,WAAW,aAC5B,YAAY,YAAY;AAG1B,MAAK,MAAM,cAAc,eACvB,KAAI,WAAW,aACb,YAAY,WAAW,YAAY;AAKvC,KAAI,uBACF,UAAU,qBAAqBH,SAAE,KAAK,CAAC,UAAU;AAGnD,QAAOA,SAAE,OAAO,UAAU;AAC3B;AAED,MAAaI,oBAGRJ,SAAE,OAAO;CACZ,+DAAgCA,SAAE,QAAuB,EAAE;EACzD,SAAS,EACP,IAAI,CAACK,IAAcC,WACjBL,sCAAgB,QAAS,GAAG,CAAE,GAAE,OAAO,CAC1C;EACD,SAAS,MAAM,CAAE;CAClB,EAAC;CAKF,uDAAwBD,SAAE,QAAuB,EAAEC,sCAAgB;AACpE,EAAC"}
@@ -13,6 +13,7 @@ function createAgentAnnotationConditional(hasStructuredResponse = true, stateSch
13
13
  jumpTo: z.union([
14
14
  z.literal("model_request"),
15
15
  z.literal("tools"),
16
+ z.literal("end"),
16
17
  z.undefined()
17
18
  ]).optional()
18
19
  };
@@ -1 +1 @@
1
- {"version":3,"file":"annotation.js","names":["stateSchema: TStateSchema","middlewareList: TMiddleware","zodSchema: Record<string, any>","schema: { shape: Record<string, any> }","schema","PreHookAnnotation: AnnotationRoot<{\n llmInputMessages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}>","_x: Messages","update: Messages"],"sources":["../../src/agents/annotation.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { BaseMessage } from \"@langchain/core/messages\";\nimport { z } from \"zod/v3\";\nimport {\n Messages,\n AnnotationRoot,\n MessagesZodMeta,\n type BinaryOperatorAggregate,\n} from \"@langchain/langgraph\";\nimport { withLangGraph } from \"@langchain/langgraph/zod\";\n\nimport type { AgentMiddleware, AnyAnnotationRoot } from \"./middleware/types.js\";\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\n\nexport function createAgentAnnotationConditional<\n TStateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n TMiddleware extends readonly AgentMiddleware<any, any, any>[] = []\n>(\n hasStructuredResponse = true,\n stateSchema: TStateSchema,\n middlewareList: TMiddleware = [] as unknown as TMiddleware\n) {\n /**\n * Create Zod schema object to preserve jsonSchemaExtra\n * metadata for LangGraph Studio using v3-compatible withLangGraph\n */\n const zodSchema: Record<string, any> = {\n messages: withLangGraph(z.custom<BaseMessage[]>(), MessagesZodMeta),\n jumpTo: z\n .union([z.literal(\"model_request\"), z.literal(\"tools\"), z.undefined()])\n .optional(),\n };\n\n const applySchema = (schema: { shape: Record<string, any> }) => {\n const { shape } = schema;\n for (const [key, schema] of Object.entries(shape)) {\n /**\n * Skip private state properties\n */\n if (key.startsWith(\"_\")) {\n continue;\n }\n\n if (!(key in zodSchema)) {\n zodSchema[key] = schema;\n }\n }\n };\n\n // Add state schema properties to the Zod schema\n if (stateSchema && \"shape\" in stateSchema) {\n applySchema(stateSchema);\n }\n\n for (const middleware of middlewareList) {\n if (middleware.stateSchema) {\n applySchema(middleware.stateSchema);\n }\n }\n\n // Only include structuredResponse when responseFormat is defined\n if (hasStructuredResponse) {\n zodSchema.structuredResponse = z.any().optional();\n }\n\n return z.object(zodSchema);\n}\n\nexport const PreHookAnnotation: AnnotationRoot<{\n llmInputMessages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}> = z.object({\n llmInputMessages: withLangGraph(z.custom<BaseMessage[]>(), {\n reducer: {\n fn: (_x: Messages, update: Messages) =>\n MessagesZodMeta.reducer!.fn([], update),\n },\n default: () => [],\n }),\n /**\n * Use MessagesZodMeta to preserve jsonSchemaExtra metadata\n * for LangGraph Studio UI to render proper messages input field\n */\n messages: withLangGraph(z.custom<BaseMessage[]>(), MessagesZodMeta),\n}) as unknown as AnnotationRoot<{\n llmInputMessages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}>;\n\nexport type PreHookAnnotation = typeof PreHookAnnotation;\n"],"mappings":";;;;;AAcA,SAAgB,iCAOd,wBAAwB,MACxBA,aACAC,iBAA8B,CAAE,GAChC;;;;;CAKA,MAAMC,YAAiC;EACrC,UAAU,cAAc,EAAE,QAAuB,EAAE,gBAAgB;EACnE,QAAQ,EACL,MAAM;GAAC,EAAE,QAAQ,gBAAgB;GAAE,EAAE,QAAQ,QAAQ;GAAE,EAAE,WAAW;EAAC,EAAC,CACtE,UAAU;CACd;CAED,MAAM,cAAc,CAACC,WAA2C;EAC9D,MAAM,EAAE,OAAO,GAAG;AAClB,OAAK,MAAM,CAAC,KAAKC,SAAO,IAAI,OAAO,QAAQ,MAAM,EAAE;;;;AAIjD,OAAI,IAAI,WAAW,IAAI,CACrB;AAGF,OAAI,EAAE,OAAO,YACX,UAAU,OAAOA;EAEpB;CACF;AAGD,KAAI,eAAe,WAAW,aAC5B,YAAY,YAAY;AAG1B,MAAK,MAAM,cAAc,eACvB,KAAI,WAAW,aACb,YAAY,WAAW,YAAY;AAKvC,KAAI,uBACF,UAAU,qBAAqB,EAAE,KAAK,CAAC,UAAU;AAGnD,QAAO,EAAE,OAAO,UAAU;AAC3B;AAED,MAAaC,oBAGR,EAAE,OAAO;CACZ,kBAAkB,cAAc,EAAE,QAAuB,EAAE;EACzD,SAAS,EACP,IAAI,CAACC,IAAcC,WACjB,gBAAgB,QAAS,GAAG,CAAE,GAAE,OAAO,CAC1C;EACD,SAAS,MAAM,CAAE;CAClB,EAAC;CAKF,UAAU,cAAc,EAAE,QAAuB,EAAE,gBAAgB;AACpE,EAAC"}
1
+ {"version":3,"file":"annotation.js","names":["stateSchema: TStateSchema","middlewareList: TMiddleware","zodSchema: Record<string, any>","schema: { shape: Record<string, any> }","schema","PreHookAnnotation: AnnotationRoot<{\n llmInputMessages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}>","_x: Messages","update: Messages"],"sources":["../../src/agents/annotation.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { BaseMessage } from \"@langchain/core/messages\";\nimport { z } from \"zod/v3\";\nimport {\n Messages,\n AnnotationRoot,\n MessagesZodMeta,\n type BinaryOperatorAggregate,\n} from \"@langchain/langgraph\";\nimport { withLangGraph } from \"@langchain/langgraph/zod\";\n\nimport type { AgentMiddleware, AnyAnnotationRoot } from \"./middleware/types.js\";\nimport { InteropZodObject } from \"@langchain/core/utils/types\";\n\nexport function createAgentAnnotationConditional<\n TStateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n TMiddleware extends readonly AgentMiddleware<any, any, any>[] = []\n>(\n hasStructuredResponse = true,\n stateSchema: TStateSchema,\n middlewareList: TMiddleware = [] as unknown as TMiddleware\n) {\n /**\n * Create Zod schema object to preserve jsonSchemaExtra\n * metadata for LangGraph Studio using v3-compatible withLangGraph\n */\n const zodSchema: Record<string, any> = {\n messages: withLangGraph(z.custom<BaseMessage[]>(), MessagesZodMeta),\n jumpTo: z\n .union([\n z.literal(\"model_request\"),\n z.literal(\"tools\"),\n z.literal(\"end\"),\n z.undefined(),\n ])\n .optional(),\n };\n\n const applySchema = (schema: { shape: Record<string, any> }) => {\n const { shape } = schema;\n for (const [key, schema] of Object.entries(shape)) {\n /**\n * Skip private state properties\n */\n if (key.startsWith(\"_\")) {\n continue;\n }\n\n if (!(key in zodSchema)) {\n zodSchema[key] = schema;\n }\n }\n };\n\n // Add state schema properties to the Zod schema\n if (stateSchema && \"shape\" in stateSchema) {\n applySchema(stateSchema);\n }\n\n for (const middleware of middlewareList) {\n if (middleware.stateSchema) {\n applySchema(middleware.stateSchema);\n }\n }\n\n // Only include structuredResponse when responseFormat is defined\n if (hasStructuredResponse) {\n zodSchema.structuredResponse = z.any().optional();\n }\n\n return z.object(zodSchema);\n}\n\nexport const PreHookAnnotation: AnnotationRoot<{\n llmInputMessages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}> = z.object({\n llmInputMessages: withLangGraph(z.custom<BaseMessage[]>(), {\n reducer: {\n fn: (_x: Messages, update: Messages) =>\n MessagesZodMeta.reducer!.fn([], update),\n },\n default: () => [],\n }),\n /**\n * Use MessagesZodMeta to preserve jsonSchemaExtra metadata\n * for LangGraph Studio UI to render proper messages input field\n */\n messages: withLangGraph(z.custom<BaseMessage[]>(), MessagesZodMeta),\n}) as unknown as AnnotationRoot<{\n llmInputMessages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n messages: BinaryOperatorAggregate<BaseMessage[], Messages>;\n}>;\n\nexport type PreHookAnnotation = typeof PreHookAnnotation;\n"],"mappings":";;;;;AAcA,SAAgB,iCAOd,wBAAwB,MACxBA,aACAC,iBAA8B,CAAE,GAChC;;;;;CAKA,MAAMC,YAAiC;EACrC,UAAU,cAAc,EAAE,QAAuB,EAAE,gBAAgB;EACnE,QAAQ,EACL,MAAM;GACL,EAAE,QAAQ,gBAAgB;GAC1B,EAAE,QAAQ,QAAQ;GAClB,EAAE,QAAQ,MAAM;GAChB,EAAE,WAAW;EACd,EAAC,CACD,UAAU;CACd;CAED,MAAM,cAAc,CAACC,WAA2C;EAC9D,MAAM,EAAE,OAAO,GAAG;AAClB,OAAK,MAAM,CAAC,KAAKC,SAAO,IAAI,OAAO,QAAQ,MAAM,EAAE;;;;AAIjD,OAAI,IAAI,WAAW,IAAI,CACrB;AAGF,OAAI,EAAE,OAAO,YACX,UAAU,OAAOA;EAEpB;CACF;AAGD,KAAI,eAAe,WAAW,aAC5B,YAAY,YAAY;AAG1B,MAAK,MAAM,cAAc,eACvB,KAAI,WAAW,aACb,YAAY,WAAW,YAAY;AAKvC,KAAI,uBACF,UAAU,qBAAqB,EAAE,KAAK,CAAC,UAAU;AAGnD,QAAO,EAAE,OAAO,UAAU;AAC3B;AAED,MAAaC,oBAGR,EAAE,OAAO;CACZ,kBAAkB,cAAc,EAAE,QAAuB,EAAE;EACzD,SAAS,EACP,IAAI,CAACC,IAAcC,WACjB,gBAAgB,QAAS,GAAG,CAAE,GAAE,OAAO,CAC1C;EACD,SAAS,MAAM,CAAE;CAClB,EAAC;CAKF,UAAU,cAAc,EAAE,QAAuB,EAAE,gBAAgB;AACpE,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n any\n >","ReactAgent"],"sources":["../../src/agents/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodType,\n} from \"@langchain/core/utils/types\";\n\nimport type { ResponseFormatUndefined } from \"./responses.js\";\nimport type { CreateAgentParams } from \"./types.js\";\nimport type { AgentMiddleware, AnyAnnotationRoot } from \"./middleware/types.js\";\nimport type { ExtractZodArrayTypes } from \"./types.js\";\nimport type {\n ToolStrategy,\n TypedToolStrategy,\n ProviderStrategy,\n ResponseFormat,\n JsonSchemaFormat,\n} from \"./responses.js\";\nimport { ReactAgent } from \"./ReactAgent.js\";\n\n/**\n * Creates a production-ready ReAct (Reasoning + Acting) agent that combines language models with tools\n * and middleware to create systems that can reason about tasks, decide which tools to use, and iteratively\n * work towards solutions.\n *\n * The agent follows the ReAct pattern, interleaving reasoning steps with tool calls to iteratively\n * work towards solutions. It can handle multiple tool calls in sequence or parallel, maintain state\n * across interactions, and provide auditable decision processes.\n *\n * ## Core Components\n *\n * ### Model\n * The reasoning engine can be specified as:\n * - **String identifier**: `\"openai:gpt-4o\"` for simple setup\n * - **Model instance**: Configured model object for full control\n * - **Dynamic function**: Select models at runtime based on state\n *\n * ### Tools\n * Tools give agents the ability to take actions:\n * - Pass an array of tools created with the `tool` function\n * - Or provide a configured `ToolNode` for custom error handling\n *\n * ### Prompt\n * Shape how your agent approaches tasks:\n * - String for simple instructions\n * - SystemMessage for structured prompts\n * - Function for dynamic prompts based on state\n *\n * ### Middleware\n * Middleware allows you to extend the agent's behavior:\n * - Add pre/post-model processing for context injection or validation\n * - Add dynamic control flows, e.g. terminate invocation or retries\n * - Add human-in-the-loop capabilities\n * - Add tool calls to the agent\n * - Add tool results to the agent\n *\n * ## Advanced Features\n *\n * - **Structured Output**: Use `responseFormat` with a Zod schema to get typed responses\n * - **Memory**: Extend the state schema to remember information across interactions\n * - **Streaming**: Get real-time updates as the agent processes\n *\n * @param options - Configuration options for the agent\n * @param options.llm - The language model as an instance of a chat model\n * @param options.model - The language model as a string identifier, see more in {@link https://docs.langchain.com/oss/javascript/langchain/models#basic-usage | Models}.\n * @param options.tools - Array of tools or configured ToolNode\n * @param options.prompt - System instructions (string, SystemMessage, or function)\n * @param options.responseFormat - Zod schema for structured output\n * @param options.stateSchema - Custom state schema for memory\n * @param options.middleware - Array of middleware for extending agent behavior, see more in {@link https://docs.langchain.com/oss/javascript/langchain/middleware | Middleware}.\n *\n * @returns A ReactAgent instance with `invoke` and `stream` methods\n *\n * @example Basic agent with tools\n * ```ts\n * import { createAgent, tool } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const search = tool(\n * ({ query }) => `Results for: ${query}`,\n * {\n * name: \"search\",\n * description: \"Search for information\",\n * schema: z.object({\n * query: z.string().describe(\"The search query\"),\n * })\n * }\n * );\n *\n * const agent = createAgent({\n * llm: \"openai:gpt-4o\",\n * tools: [search],\n * });\n *\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Search for ReAct agents\" }],\n * });\n * ```\n *\n * @example Structured output\n * ```ts\n * import { createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const ContactInfo = z.object({\n * name: z.string(),\n * email: z.string(),\n * phone: z.string(),\n * });\n *\n * const agent = createAgent({\n * llm: \"openai:gpt-4o\",\n * tools: [],\n * responseFormat: ContactInfo,\n * });\n *\n * const result = await agent.invoke({\n * messages: [{\n * role: \"user\",\n * content: \"Extract: John Doe, john@example.com, (555) 123-4567\"\n * }],\n * });\n *\n * console.log(result.structuredResponse);\n * // { name: 'John Doe', email: 'john@example.com', phone: '(555) 123-4567' }\n * ```\n *\n * @example Streaming responses\n * ```ts\n * const stream = await agent.stream(\n * { messages: [{ role: \"user\", content: \"What's the weather?\" }] },\n * { streamMode: \"values\" }\n * );\n *\n * for await (const chunk of stream) {\n * // ...\n * }\n * ```\n */\n// Overload 1: With responseFormat as single InteropZodType\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n T,\n StateSchema,\n ContextSchema,\n InteropZodType<T>\n > & {\n responseFormat: InteropZodType<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 2: With responseFormat as array of InteropZodTypes (infers union type)\nexport function createAgent<\n T extends readonly InteropZodType<any>[],\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n StateSchema,\n ContextSchema,\n T\n > & {\n responseFormat: T;\n middleware?: TMiddleware;\n }\n): ReactAgent<\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n StateSchema,\n ContextSchema,\n TMiddleware\n>;\n\n// Overload 3: With responseFormat as JsonSchemaFormat (JSON schema object)\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n JsonSchemaFormat\n > & {\n responseFormat: JsonSchemaFormat;\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 4: With responseFormat as array of JsonSchemaFormat (JSON schema objects)\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat[];\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 4.5: With responseFormat as union of JsonSchemaFormat | JsonSchemaFormat[]\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n JsonSchemaFormat | JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat | JsonSchemaFormat[];\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 5: With responseFormat as TypedToolStrategy (for union types from toolStrategy)\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n T,\n StateSchema,\n ContextSchema,\n TypedToolStrategy<T>\n > & {\n responseFormat: TypedToolStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 6: With responseFormat as single ToolStrategy instance\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<T, StateSchema, ContextSchema, ToolStrategy<T>> & {\n responseFormat: ToolStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 7: With responseFormat as ProviderStrategy\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n T,\n StateSchema,\n ContextSchema,\n ProviderStrategy<T>\n > & {\n responseFormat: ProviderStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 8: Without responseFormat property at all - with proper middleware state typing\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: Omit<\n CreateAgentParams<\n ResponseFormatUndefined,\n StateSchema,\n ContextSchema,\n never\n >,\n \"responseFormat\"\n > & { middleware?: TMiddleware }\n): ReactAgent<ResponseFormatUndefined, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 9: With responseFormat explicitly undefined\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: Omit<\n CreateAgentParams<\n ResponseFormatUndefined,\n StateSchema,\n ContextSchema,\n never\n >,\n \"responseFormat\"\n > & {\n responseFormat?: undefined;\n middleware?: TMiddleware;\n }\n): ReactAgent<ResponseFormatUndefined, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 10: For other ResponseFormat values (failsafe)\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n ResponseFormat\n > & {\n responseFormat: ResponseFormat;\n middleware?: TMiddleware;\n }\n): ReactAgent<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n TMiddleware\n>;\n\n// Implementation\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any>,\n StateSchema extends AnyAnnotationRoot | InteropZodObject,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject,\n TMiddleware extends readonly AgentMiddleware[] = []\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n any\n >\n): ReactAgent<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n TMiddleware\n> {\n return new ReactAgent(params);\n}\n\n// Re-export types and utilities\nexport * from \"./types.js\";\nexport * from \"./errors.js\";\nexport type { JumpToTarget } from \"./constants.js\";\nexport type { Runtime } from \"./runtime.js\";\nexport {\n toolStrategy,\n providerStrategy,\n ToolStrategy,\n ProviderStrategy,\n type ResponseFormat,\n type ResponseFormatUndefined,\n} from \"./responses.js\";\nexport { createMiddleware } from \"./middleware.js\";\nexport type {\n ToolCallRequest,\n ToolCallHandler,\n WrapToolCallHook,\n} from \"./middleware/types.js\";\nexport { FakeToolCallingModel } from \"./tests/utils.js\";\nexport type { ReactAgent } from \"./ReactAgent.js\";\n"],"mappings":";;;;;;;AA+YA,SAAgB,YAMdA,QAWA;AACA,QAAO,IAAIC,8BAAW;AACvB"}
1
+ {"version":3,"file":"index.cjs","names":["params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n any\n >","ReactAgent"],"sources":["../../src/agents/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodType,\n} from \"@langchain/core/utils/types\";\n\nimport type { ResponseFormatUndefined } from \"./responses.js\";\nimport type { CreateAgentParams } from \"./types.js\";\nimport type { AgentMiddleware, AnyAnnotationRoot } from \"./middleware/types.js\";\nimport type { ExtractZodArrayTypes } from \"./types.js\";\nimport type {\n ToolStrategy,\n TypedToolStrategy,\n ProviderStrategy,\n ResponseFormat,\n JsonSchemaFormat,\n} from \"./responses.js\";\nimport { ReactAgent } from \"./ReactAgent.js\";\n\n/**\n * Creates a production-ready ReAct (Reasoning + Acting) agent that combines language models with tools\n * and middleware to create systems that can reason about tasks, decide which tools to use, and iteratively\n * work towards solutions.\n *\n * The agent follows the ReAct pattern, interleaving reasoning steps with tool calls to iteratively\n * work towards solutions. It can handle multiple tool calls in sequence or parallel, maintain state\n * across interactions, and provide auditable decision processes.\n *\n * ## Core Components\n *\n * ### Model\n * The reasoning engine can be specified as:\n * - **String identifier**: `\"openai:gpt-4o\"` for simple setup\n * - **Model instance**: Configured model object for full control\n * - **Dynamic function**: Select models at runtime based on state\n *\n * ### Tools\n * Tools give agents the ability to take actions:\n * - Pass an array of tools created with the `tool` function\n * - Or provide a configured `ToolNode` for custom error handling\n *\n * ### Prompt\n * Shape how your agent approaches tasks:\n * - String for simple instructions\n * - SystemMessage for structured prompts\n * - Function for dynamic prompts based on state\n *\n * ### Middleware\n * Middleware allows you to extend the agent's behavior:\n * - Add pre/post-model processing for context injection or validation\n * - Add dynamic control flows, e.g. terminate invocation or retries\n * - Add human-in-the-loop capabilities\n * - Add tool calls to the agent\n * - Add tool results to the agent\n *\n * ## Advanced Features\n *\n * - **Structured Output**: Use `responseFormat` with a Zod schema to get typed responses\n * - **Memory**: Extend the state schema to remember information across interactions\n * - **Streaming**: Get real-time updates as the agent processes\n *\n * @param options - Configuration options for the agent\n * @param options.llm - The language model as an instance of a chat model\n * @param options.model - The language model as a string identifier, see more in {@link https://docs.langchain.com/oss/javascript/langchain/models#basic-usage | Models}.\n * @param options.tools - Array of tools or configured ToolNode\n * @param options.prompt - System instructions (string, SystemMessage, or function)\n * @param options.responseFormat - Zod schema for structured output\n * @param options.stateSchema - Custom state schema for memory\n * @param options.middleware - Array of middleware for extending agent behavior, see more in {@link https://docs.langchain.com/oss/javascript/langchain/middleware | Middleware}.\n *\n * @returns A ReactAgent instance with `invoke` and `stream` methods\n *\n * @example Basic agent with tools\n * ```ts\n * import { createAgent, tool } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const search = tool(\n * ({ query }) => `Results for: ${query}`,\n * {\n * name: \"search\",\n * description: \"Search for information\",\n * schema: z.object({\n * query: z.string().describe(\"The search query\"),\n * })\n * }\n * );\n *\n * const agent = createAgent({\n * llm: \"openai:gpt-4o\",\n * tools: [search],\n * });\n *\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Search for ReAct agents\" }],\n * });\n * ```\n *\n * @example Structured output\n * ```ts\n * import { createAgent } from \"langchain\";\n * import { z } from \"zod\";\n *\n * const ContactInfo = z.object({\n * name: z.string(),\n * email: z.string(),\n * phone: z.string(),\n * });\n *\n * const agent = createAgent({\n * llm: \"openai:gpt-4o\",\n * tools: [],\n * responseFormat: ContactInfo,\n * });\n *\n * const result = await agent.invoke({\n * messages: [{\n * role: \"user\",\n * content: \"Extract: John Doe, john@example.com, (555) 123-4567\"\n * }],\n * });\n *\n * console.log(result.structuredResponse);\n * // { name: 'John Doe', email: 'john@example.com', phone: '(555) 123-4567' }\n * ```\n *\n * @example Streaming responses\n * ```ts\n * const stream = await agent.stream(\n * { messages: [{ role: \"user\", content: \"What's the weather?\" }] },\n * { streamMode: \"values\" }\n * );\n *\n * for await (const chunk of stream) {\n * // ...\n * }\n * ```\n */\n// Overload 1: With responseFormat as single InteropZodType\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n T,\n StateSchema,\n ContextSchema,\n InteropZodType<T>\n > & {\n responseFormat: InteropZodType<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 2: With responseFormat as array of InteropZodTypes (infers union type)\nexport function createAgent<\n T extends readonly InteropZodType<any>[],\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n StateSchema,\n ContextSchema,\n T\n > & {\n responseFormat: T;\n middleware?: TMiddleware;\n }\n): ReactAgent<\n ExtractZodArrayTypes<T> extends Record<string, any>\n ? ExtractZodArrayTypes<T>\n : Record<string, any>,\n StateSchema,\n ContextSchema,\n TMiddleware\n>;\n\n// Overload 3: With responseFormat as JsonSchemaFormat (JSON schema object)\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n JsonSchemaFormat\n > & {\n responseFormat: JsonSchemaFormat;\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 4: With responseFormat as array of JsonSchemaFormat (JSON schema objects)\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat[];\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 4.5: With responseFormat as union of JsonSchemaFormat | JsonSchemaFormat[]\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n Record<string, unknown>,\n StateSchema,\n ContextSchema,\n JsonSchemaFormat | JsonSchemaFormat[]\n > & {\n responseFormat: JsonSchemaFormat | JsonSchemaFormat[];\n middleware?: TMiddleware;\n }\n): ReactAgent<Record<string, unknown>, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 5: With responseFormat as TypedToolStrategy (for union types from toolStrategy)\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n T,\n StateSchema,\n ContextSchema,\n TypedToolStrategy<T>\n > & {\n responseFormat: TypedToolStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 6: With responseFormat as single ToolStrategy instance\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<T, StateSchema, ContextSchema, ToolStrategy<T>> & {\n responseFormat: ToolStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 7: With responseFormat as ProviderStrategy\nexport function createAgent<\n T extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n T,\n StateSchema,\n ContextSchema,\n ProviderStrategy<T>\n > & {\n responseFormat: ProviderStrategy<T>;\n middleware?: TMiddleware;\n }\n): ReactAgent<T, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 8: Without responseFormat property at all - with proper middleware state typing\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: Omit<\n CreateAgentParams<\n ResponseFormatUndefined,\n StateSchema,\n ContextSchema,\n never\n >,\n \"responseFormat\"\n > & { middleware?: TMiddleware }\n): ReactAgent<ResponseFormatUndefined, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 9: With responseFormat explicitly undefined\nexport function createAgent<\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: Omit<\n CreateAgentParams<\n ResponseFormatUndefined,\n StateSchema,\n ContextSchema,\n never\n >,\n \"responseFormat\"\n > & {\n responseFormat?: undefined;\n middleware?: TMiddleware;\n }\n): ReactAgent<ResponseFormatUndefined, StateSchema, ContextSchema, TMiddleware>;\n\n// Overload 10: For other ResponseFormat values (failsafe)\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any> = Record<string, any>,\n StateSchema extends\n | AnyAnnotationRoot\n | InteropZodObject\n | undefined = undefined,\n ContextSchema extends\n | AnyAnnotationRoot\n | InteropZodObject = AnyAnnotationRoot,\n const TMiddleware extends readonly AgentMiddleware[] = readonly AgentMiddleware[]\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n ResponseFormat\n > & {\n responseFormat: ResponseFormat;\n middleware?: TMiddleware;\n }\n): ReactAgent<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n TMiddleware\n>;\n\n// Implementation\nexport function createAgent<\n StructuredResponseFormat extends Record<string, any>,\n StateSchema extends AnyAnnotationRoot | InteropZodObject,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject,\n TMiddleware extends readonly AgentMiddleware[] = []\n>(\n params: CreateAgentParams<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n any\n >\n): ReactAgent<\n StructuredResponseFormat,\n StateSchema,\n ContextSchema,\n TMiddleware\n> {\n return new ReactAgent(params);\n}\n\n// Re-export types and utilities\nexport * from \"./types.js\";\nexport * from \"./errors.js\";\nexport type { JumpToTarget } from \"./constants.js\";\nexport type { Runtime } from \"./runtime.js\";\nexport {\n toolStrategy,\n providerStrategy,\n ToolStrategy,\n ProviderStrategy,\n type ResponseFormat,\n type ResponseFormatUndefined,\n} from \"./responses.js\";\nexport { createMiddleware } from \"./middleware.js\";\nexport type {\n ToolCallRequest,\n ToolCallHandler,\n WrapToolCallHook,\n} from \"./middleware/types.js\";\nexport { FakeToolCallingModel } from \"./tests/utils.js\";\nexport type { ReactAgent } from \"./ReactAgent.js\";\n"],"mappings":";;;;;;;AA+YA,SAAgB,YAMdA,QAWA;AACA,QAAO,IAAIC,8BAAW;AACvB"}