langchain 1.0.0-alpha.3 → 1.0.0-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (201) hide show
  1. package/dist/agents/ReactAgent.cjs +1 -1
  2. package/dist/agents/ReactAgent.cjs.map +1 -1
  3. package/dist/agents/ReactAgent.d.cts +3 -3
  4. package/dist/agents/ReactAgent.d.cts.map +1 -1
  5. package/dist/agents/ReactAgent.d.ts +3 -3
  6. package/dist/agents/ReactAgent.d.ts.map +1 -1
  7. package/dist/agents/ReactAgent.js +2 -2
  8. package/dist/agents/ReactAgent.js.map +1 -1
  9. package/dist/agents/RunnableCallable.cjs +5 -0
  10. package/dist/agents/RunnableCallable.cjs.map +1 -1
  11. package/dist/agents/RunnableCallable.d.cts +2 -0
  12. package/dist/agents/RunnableCallable.d.cts.map +1 -1
  13. package/dist/agents/RunnableCallable.d.ts +2 -0
  14. package/dist/agents/RunnableCallable.d.ts.map +1 -1
  15. package/dist/agents/RunnableCallable.js +5 -0
  16. package/dist/agents/RunnableCallable.js.map +1 -1
  17. package/dist/agents/annotation.cjs +2 -2
  18. package/dist/agents/annotation.cjs.map +1 -1
  19. package/dist/agents/annotation.d.cts +4 -4
  20. package/dist/agents/annotation.d.cts.map +1 -1
  21. package/dist/agents/annotation.d.ts +3 -3
  22. package/dist/agents/annotation.d.ts.map +1 -1
  23. package/dist/agents/annotation.js +2 -2
  24. package/dist/agents/annotation.js.map +1 -1
  25. package/dist/agents/createAgent.cjs +10 -0
  26. package/dist/agents/createAgent.cjs.map +1 -0
  27. package/dist/agents/createAgent.js +10 -0
  28. package/dist/agents/createAgent.js.map +1 -0
  29. package/dist/agents/errors.cjs +1 -1
  30. package/dist/agents/errors.cjs.map +1 -1
  31. package/dist/agents/errors.js +1 -1
  32. package/dist/agents/errors.js.map +1 -1
  33. package/dist/agents/index.cjs +23 -4
  34. package/dist/agents/index.cjs.map +1 -1
  35. package/dist/agents/index.d.cts +96 -33
  36. package/dist/agents/index.d.cts.map +1 -1
  37. package/dist/agents/index.d.ts +96 -33
  38. package/dist/agents/index.d.ts.map +1 -1
  39. package/dist/agents/index.js +23 -4
  40. package/dist/agents/index.js.map +1 -1
  41. package/dist/agents/middlewareAgent/ReactAgent.cjs +255 -0
  42. package/dist/agents/middlewareAgent/ReactAgent.cjs.map +1 -0
  43. package/dist/agents/middlewareAgent/ReactAgent.d.cts +68 -0
  44. package/dist/agents/middlewareAgent/ReactAgent.d.cts.map +1 -0
  45. package/dist/agents/middlewareAgent/ReactAgent.d.ts +68 -0
  46. package/dist/agents/middlewareAgent/ReactAgent.d.ts.map +1 -0
  47. package/dist/agents/middlewareAgent/ReactAgent.js +254 -0
  48. package/dist/agents/middlewareAgent/ReactAgent.js.map +1 -0
  49. package/dist/agents/middlewareAgent/annotation.cjs +39 -0
  50. package/dist/agents/middlewareAgent/annotation.cjs.map +1 -0
  51. package/dist/agents/middlewareAgent/annotation.js +38 -0
  52. package/dist/agents/middlewareAgent/annotation.js.map +1 -0
  53. package/dist/agents/middlewareAgent/index.cjs +11 -0
  54. package/dist/agents/middlewareAgent/index.cjs.map +1 -0
  55. package/dist/agents/middlewareAgent/index.js +11 -0
  56. package/dist/agents/middlewareAgent/index.js.map +1 -0
  57. package/dist/agents/middlewareAgent/middleware.cjs +47 -0
  58. package/dist/agents/middlewareAgent/middleware.cjs.map +1 -0
  59. package/dist/agents/middlewareAgent/middleware.d.cts +46 -0
  60. package/dist/agents/middlewareAgent/middleware.d.cts.map +1 -0
  61. package/dist/agents/middlewareAgent/middleware.d.ts +46 -0
  62. package/dist/agents/middlewareAgent/middleware.d.ts.map +1 -0
  63. package/dist/agents/middlewareAgent/middleware.js +46 -0
  64. package/dist/agents/middlewareAgent/middleware.js.map +1 -0
  65. package/dist/agents/middlewareAgent/middlewares/hitl.cjs +235 -0
  66. package/dist/agents/middlewareAgent/middlewares/hitl.cjs.map +1 -0
  67. package/dist/agents/middlewareAgent/middlewares/hitl.d.cts +199 -0
  68. package/dist/agents/middlewareAgent/middlewares/hitl.d.cts.map +1 -0
  69. package/dist/agents/middlewareAgent/middlewares/hitl.d.ts +199 -0
  70. package/dist/agents/middlewareAgent/middlewares/hitl.d.ts.map +1 -0
  71. package/dist/agents/middlewareAgent/middlewares/hitl.js +234 -0
  72. package/dist/agents/middlewareAgent/middlewares/hitl.js.map +1 -0
  73. package/dist/agents/middlewareAgent/middlewares/index.cjs +8 -0
  74. package/dist/agents/middlewareAgent/middlewares/index.d.cts +4 -0
  75. package/dist/agents/middlewareAgent/middlewares/index.d.ts +4 -0
  76. package/dist/agents/middlewareAgent/middlewares/index.js +5 -0
  77. package/dist/agents/middlewareAgent/middlewares/promptCaching.cjs +153 -0
  78. package/dist/agents/middlewareAgent/middlewares/promptCaching.cjs.map +1 -0
  79. package/dist/agents/middlewareAgent/middlewares/promptCaching.d.cts +152 -0
  80. package/dist/agents/middlewareAgent/middlewares/promptCaching.d.cts.map +1 -0
  81. package/dist/agents/middlewareAgent/middlewares/promptCaching.d.ts +152 -0
  82. package/dist/agents/middlewareAgent/middlewares/promptCaching.d.ts.map +1 -0
  83. package/dist/agents/middlewareAgent/middlewares/promptCaching.js +152 -0
  84. package/dist/agents/middlewareAgent/middlewares/promptCaching.js.map +1 -0
  85. package/dist/agents/middlewareAgent/middlewares/summarization.cjs +262 -0
  86. package/dist/agents/middlewareAgent/middlewares/summarization.cjs.map +1 -0
  87. package/dist/agents/middlewareAgent/middlewares/summarization.d.cts +89 -0
  88. package/dist/agents/middlewareAgent/middlewares/summarization.d.cts.map +1 -0
  89. package/dist/agents/middlewareAgent/middlewares/summarization.d.ts +89 -0
  90. package/dist/agents/middlewareAgent/middlewares/summarization.d.ts.map +1 -0
  91. package/dist/agents/middlewareAgent/middlewares/summarization.js +260 -0
  92. package/dist/agents/middlewareAgent/middlewares/summarization.js.map +1 -0
  93. package/dist/agents/middlewareAgent/nodes/AfterModalNode.cjs +29 -0
  94. package/dist/agents/middlewareAgent/nodes/AfterModalNode.cjs.map +1 -0
  95. package/dist/agents/middlewareAgent/nodes/AfterModalNode.js +29 -0
  96. package/dist/agents/middlewareAgent/nodes/AfterModalNode.js.map +1 -0
  97. package/dist/agents/middlewareAgent/nodes/AgentNode.cjs +332 -0
  98. package/dist/agents/middlewareAgent/nodes/AgentNode.cjs.map +1 -0
  99. package/dist/agents/middlewareAgent/nodes/AgentNode.js +331 -0
  100. package/dist/agents/middlewareAgent/nodes/AgentNode.js.map +1 -0
  101. package/dist/agents/middlewareAgent/nodes/BeforeModalNode.cjs +27 -0
  102. package/dist/agents/middlewareAgent/nodes/BeforeModalNode.cjs.map +1 -0
  103. package/dist/agents/middlewareAgent/nodes/BeforeModalNode.js +27 -0
  104. package/dist/agents/middlewareAgent/nodes/BeforeModalNode.js.map +1 -0
  105. package/dist/agents/middlewareAgent/nodes/middleware.cjs +73 -0
  106. package/dist/agents/middlewareAgent/nodes/middleware.cjs.map +1 -0
  107. package/dist/agents/middlewareAgent/nodes/middleware.js +73 -0
  108. package/dist/agents/middlewareAgent/nodes/middleware.js.map +1 -0
  109. package/dist/agents/middlewareAgent/nodes/utils.cjs +74 -0
  110. package/dist/agents/middlewareAgent/nodes/utils.cjs.map +1 -0
  111. package/dist/agents/middlewareAgent/nodes/utils.js +70 -0
  112. package/dist/agents/middlewareAgent/nodes/utils.js.map +1 -0
  113. package/dist/agents/middlewareAgent/types.d.cts +393 -0
  114. package/dist/agents/middlewareAgent/types.d.cts.map +1 -0
  115. package/dist/agents/middlewareAgent/types.d.ts +393 -0
  116. package/dist/agents/middlewareAgent/types.d.ts.map +1 -0
  117. package/dist/agents/nodes/AgentNode.cjs.map +1 -1
  118. package/dist/agents/nodes/AgentNode.js.map +1 -1
  119. package/dist/agents/nodes/ToolNode.cjs +1 -1
  120. package/dist/agents/nodes/ToolNode.cjs.map +1 -1
  121. package/dist/agents/nodes/ToolNode.d.cts +4 -4
  122. package/dist/agents/nodes/ToolNode.d.cts.map +1 -1
  123. package/dist/agents/nodes/ToolNode.d.ts +1 -1
  124. package/dist/agents/nodes/ToolNode.d.ts.map +1 -1
  125. package/dist/agents/nodes/ToolNode.js +1 -1
  126. package/dist/agents/nodes/ToolNode.js.map +1 -1
  127. package/dist/agents/responses.cjs +1 -1
  128. package/dist/agents/responses.cjs.map +1 -1
  129. package/dist/agents/responses.d.cts +1 -1
  130. package/dist/agents/responses.d.cts.map +1 -1
  131. package/dist/agents/responses.d.ts +1 -1
  132. package/dist/agents/responses.d.ts.map +1 -1
  133. package/dist/agents/responses.js +1 -1
  134. package/dist/agents/responses.js.map +1 -1
  135. package/dist/agents/types.d.cts +12 -12
  136. package/dist/agents/types.d.cts.map +1 -1
  137. package/dist/agents/types.d.ts +8 -8
  138. package/dist/agents/types.d.ts.map +1 -1
  139. package/dist/agents/utils.cjs +1 -1
  140. package/dist/agents/utils.cjs.map +1 -1
  141. package/dist/agents/utils.js +1 -1
  142. package/dist/agents/utils.js.map +1 -1
  143. package/dist/agents/withAgentName.cjs +1 -1
  144. package/dist/agents/withAgentName.cjs.map +1 -1
  145. package/dist/agents/withAgentName.js +1 -1
  146. package/dist/agents/withAgentName.js.map +1 -1
  147. package/dist/chains/api/api_chain.d.cts +1 -1
  148. package/dist/chains/base.d.cts +1 -1
  149. package/dist/chains/combine_docs_chain.d.cts +1 -1
  150. package/dist/chains/combine_documents/stuff.d.cts +1 -1
  151. package/dist/chains/conversational_retrieval_chain.d.cts +1 -1
  152. package/dist/chains/graph_qa/cypher.d.cts +1 -1
  153. package/dist/chains/history_aware_retriever.d.cts +2 -2
  154. package/dist/chains/llm_chain.d.cts +3 -3
  155. package/dist/chains/openai_functions/base.d.cts +3 -3
  156. package/dist/chains/openai_functions/openapi.d.cts +1 -1
  157. package/dist/chains/openai_functions/structured_output.d.cts +3 -3
  158. package/dist/chains/openai_functions/tagging.d.cts +1 -1
  159. package/dist/chains/query_constructor/index.cjs +1 -1
  160. package/dist/chains/query_constructor/index.d.cts +2 -2
  161. package/dist/chains/query_constructor/index.d.ts +1 -1
  162. package/dist/chains/query_constructor/index.js +1 -1
  163. package/dist/chains/question_answering/load.d.ts +2 -2
  164. package/dist/chains/question_answering/load.d.ts.map +1 -1
  165. package/dist/chains/retrieval.d.cts +1 -1
  166. package/dist/chains/router/llm_router.d.cts +1 -1
  167. package/dist/chains/router/multi_prompt.cjs +1 -1
  168. package/dist/chains/router/multi_prompt.js +1 -1
  169. package/dist/chains/router/multi_retrieval_qa.cjs +1 -1
  170. package/dist/chains/router/multi_retrieval_qa.js +1 -1
  171. package/dist/chains/sql_db/sql_db_chain.d.cts +2 -2
  172. package/dist/chains/summarization/load.d.ts +2 -2
  173. package/dist/chains/summarization/load.d.ts.map +1 -1
  174. package/dist/chat_models/universal.d.cts +3 -3
  175. package/dist/evaluation/agents/trajectory.d.cts +3 -3
  176. package/dist/evaluation/agents/trajectory.d.ts.map +1 -1
  177. package/dist/evaluation/comparison/pairwise.d.cts +1 -1
  178. package/dist/evaluation/comparison/pairwise.d.ts.map +1 -1
  179. package/dist/evaluation/criteria/criteria.d.cts +1 -1
  180. package/dist/evaluation/qa/eval_chain.d.cts +1 -1
  181. package/dist/index.cjs +5 -2
  182. package/dist/index.cjs.map +1 -1
  183. package/dist/index.d.cts +6 -5
  184. package/dist/index.d.ts +4 -3
  185. package/dist/index.js +5 -3
  186. package/dist/index.js.map +1 -1
  187. package/dist/load/import_map.cjs +1 -1
  188. package/dist/load/import_map.js +1 -1
  189. package/dist/memory/summary.d.cts +1 -1
  190. package/dist/output_parsers/fix.d.cts +1 -1
  191. package/dist/output_parsers/http_response.d.cts +1 -1
  192. package/dist/output_parsers/structured.cjs +1 -1
  193. package/dist/output_parsers/structured.d.cts +2 -2
  194. package/dist/output_parsers/structured.d.ts +1 -1
  195. package/dist/output_parsers/structured.js +1 -1
  196. package/dist/tools/fs.d.cts +1 -1
  197. package/dist/tools/json.d.cts +1 -1
  198. package/dist/tools/retriever.d.cts +1 -1
  199. package/dist/tools/vectorstore.d.cts +1 -1
  200. package/dist/tools/webbrowser.d.cts +1 -1
  201. package/package.json +14 -3
@@ -0,0 +1,332 @@
1
+ const require_rolldown_runtime = require('../../../_virtual/rolldown_runtime.cjs');
2
+ const require_chat_models_universal = require('../../../chat_models/universal.cjs');
3
+ const require_errors = require('../../errors.cjs');
4
+ const require_utils = require('../../utils.cjs');
5
+ const require_RunnableCallable = require('../../RunnableCallable.cjs');
6
+ const require_utils$1 = require('../../nodes/utils.cjs');
7
+ const require_withAgentName = require('../../withAgentName.cjs');
8
+ const require_responses = require('../../responses.cjs');
9
+ const require_utils$2 = require('./utils.cjs');
10
+ const __langchain_core_messages = require_rolldown_runtime.__toESM(require("@langchain/core/messages"));
11
+ const __langchain_langgraph = require_rolldown_runtime.__toESM(require("@langchain/langgraph"));
12
+ const __langchain_core_utils_types = require_rolldown_runtime.__toESM(require("@langchain/core/utils/types"));
13
+ const zod = require_rolldown_runtime.__toESM(require("zod"));
14
+
15
+ //#region src/agents/middlewareAgent/nodes/AgentNode.ts
16
+ var AgentNode = class extends require_RunnableCallable.RunnableCallable {
17
+ #options;
18
+ #structuredToolInfo = {};
19
+ constructor(options) {
20
+ super({
21
+ name: options.name ?? "model",
22
+ func: (input, config) => this.#run(input, config)
23
+ });
24
+ this.#options = options;
25
+ /**
26
+ * Populate a list of structured tool info.
27
+ */
28
+ this.#structuredToolInfo = require_responses.transformResponseFormat(this.#options.responseFormat).filter((format) => format instanceof require_responses.ToolStrategy).reduce((acc, format) => {
29
+ acc[format.name] = format;
30
+ return acc;
31
+ }, {});
32
+ }
33
+ async #run(state, config) {
34
+ /**
35
+ * Check if we just executed a returnDirect tool
36
+ * If so, we should generate structured response (if needed) and stop
37
+ */
38
+ const lastMessage = state.messages.at(-1);
39
+ if (lastMessage && (0, __langchain_core_messages.isToolMessage)(lastMessage) && lastMessage.name && this.#options.shouldReturnDirect.has(lastMessage.name))
40
+ /**
41
+ * return directly without invoking the model again
42
+ */
43
+ return { messages: [] };
44
+ const response = await this.#invokeModel(state, config);
45
+ /**
46
+ * if we were able to generate a structured response, return it
47
+ */
48
+ if ("structuredResponse" in response) return {
49
+ messages: [...state.messages, ...response.messages || []],
50
+ structuredResponse: response.structuredResponse
51
+ };
52
+ /**
53
+ * if we need to direct the agent to the model, return the update
54
+ */
55
+ if (response instanceof __langchain_langgraph.Command) return response;
56
+ response.name = this.name;
57
+ response.lc_kwargs.name = this.name;
58
+ if (this.#areMoreStepsNeeded(state, response)) return { messages: [new __langchain_core_messages.AIMessage("Sorry, need more steps to process this request.", {
59
+ name: this.name,
60
+ lc_kwargs: { name: this.name },
61
+ id: response.id
62
+ })] };
63
+ return { messages: [response] };
64
+ }
65
+ /**
66
+ * Derive the model from the options.
67
+ * @param state - The state of the agent.
68
+ * @param config - The config of the agent.
69
+ * @returns The model.
70
+ */
71
+ #deriveModel(state, config) {
72
+ if (this.#options.model) {
73
+ if (typeof this.#options.model === "string") return require_chat_models_universal.initChatModel(this.#options.model);
74
+ throw new Error("`model` option must be a string.");
75
+ }
76
+ const model = this.#options.llm;
77
+ /**
78
+ * If the model is a function, call it to get the model.
79
+ */
80
+ if (typeof model === "function") return model(state, config);
81
+ if (model) return model;
82
+ throw new Error("No model option was provided, either via `model` or via `llm` option.");
83
+ }
84
+ async #invokeModel(state, config, options = {}) {
85
+ const model = await this.#deriveModel(state, config);
86
+ /**
87
+ * Execute prepareModelRequest hooks from beforeModelNodes
88
+ */
89
+ const preparedOptions = await this.#executePrepareModelRequestHooks(model, state, config);
90
+ /**
91
+ * If user provides a model in the preparedOptions, use it,
92
+ * otherwise use the model from the options
93
+ */
94
+ const finalModel = preparedOptions?.model ?? model;
95
+ /**
96
+ * Check if the LLM already has bound tools and throw if it does.
97
+ */
98
+ require_utils.validateLLMHasNoBoundTools(finalModel);
99
+ const modelWithTools = await this.#bindTools(finalModel, preparedOptions);
100
+ let modelInput = this.#getModelInputState(state);
101
+ if (preparedOptions?.messages) modelInput = {
102
+ ...modelInput,
103
+ messages: preparedOptions.messages
104
+ };
105
+ if (preparedOptions?.systemMessage) {
106
+ const systemMsg = new __langchain_core_messages.SystemMessage(preparedOptions.systemMessage);
107
+ modelInput = {
108
+ ...modelInput,
109
+ messages: [systemMsg, ...modelInput.messages]
110
+ };
111
+ }
112
+ const signal = require_utils$1.mergeAbortSignals(this.#options.signal, config.signal);
113
+ const invokeConfig = {
114
+ ...config,
115
+ signal
116
+ };
117
+ const response = await modelWithTools.invoke(modelInput, invokeConfig);
118
+ /**
119
+ * if the user requests a native schema output, try to parse the response
120
+ * and return the structured response if it is valid
121
+ */
122
+ if (this.#options.responseFormat instanceof require_responses.ProviderStrategy) {
123
+ const structuredResponse = this.#options.responseFormat.parse(response);
124
+ if (structuredResponse) return {
125
+ structuredResponse,
126
+ messages: [response]
127
+ };
128
+ }
129
+ if (!response.tool_calls) return response;
130
+ const toolCalls = response.tool_calls.filter((call) => call.name in this.#structuredToolInfo);
131
+ /**
132
+ * if there were not structured tool calls, we can return the response
133
+ */
134
+ if (toolCalls.length === 0) return response;
135
+ /**
136
+ * if there were multiple structured tool calls, we should throw an error as this
137
+ * scenario is not defined/supported.
138
+ */
139
+ if (toolCalls.length > 1) return this.#handleMultipleStructuredOutputs(response, toolCalls);
140
+ const toolStrategy = this.#structuredToolInfo[toolCalls[0].name];
141
+ const toolMessageContent = toolStrategy?.options?.toolMessageContent;
142
+ return this.#handleSingleStructuredOutput(response, toolCalls[0], toolMessageContent ?? options.lastMessage);
143
+ }
144
+ /**
145
+ * If the model returns multiple structured outputs, we need to handle it.
146
+ * @param response - The response from the model
147
+ * @param toolCalls - The tool calls that were made
148
+ * @returns The response from the model
149
+ */
150
+ #handleMultipleStructuredOutputs(response, toolCalls) {
151
+ /**
152
+ * the following should never happen, let's throw an error if it does
153
+ */
154
+ if (this.#options.responseFormat instanceof require_responses.ProviderStrategy) throw new Error("Multiple structured outputs should not apply to native structured output responses");
155
+ const multipleStructuredOutputsError = new require_errors.MultipleStructuredOutputsError(toolCalls.map((call) => call.name));
156
+ return this.#handleToolStrategyError(multipleStructuredOutputsError, response, toolCalls[0]);
157
+ }
158
+ /**
159
+ * If the model returns a single structured output, we need to handle it.
160
+ * @param toolCall - The tool call that was made
161
+ * @returns The structured response and a message to the LLM if needed
162
+ */
163
+ #handleSingleStructuredOutput(response, toolCall, lastMessage) {
164
+ const tool = this.#structuredToolInfo[toolCall.name];
165
+ try {
166
+ const structuredResponse = tool.parse(toolCall.args);
167
+ return {
168
+ structuredResponse,
169
+ messages: [response, new __langchain_core_messages.AIMessage(lastMessage ?? `Returning structured response: ${JSON.stringify(structuredResponse)}`)]
170
+ };
171
+ } catch (error) {
172
+ return this.#handleToolStrategyError(error, response, toolCall);
173
+ }
174
+ }
175
+ async #handleToolStrategyError(error, response, toolCall) {
176
+ /**
177
+ * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.
178
+ * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user
179
+ * uses `toolStrategy` to define the response format. If the user applies a list of json
180
+ * schema objects, these will be transformed into multiple `ToolStrategy` entries but all
181
+ * with the same `handleError` option.
182
+ */
183
+ const errorHandler = Object.values(this.#structuredToolInfo).at(0)?.options?.handleError;
184
+ const toolCallId = toolCall.id;
185
+ if (!toolCallId) throw new Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");
186
+ /**
187
+ * retry if:
188
+ */
189
+ if (typeof errorHandler === "boolean" && errorHandler || Array.isArray(errorHandler) && errorHandler.some((h) => h instanceof require_errors.MultipleStructuredOutputsError)) return new __langchain_langgraph.Command({
190
+ update: { messages: [response, new __langchain_core_messages.ToolMessage({
191
+ content: error.message,
192
+ tool_call_id: toolCallId
193
+ })] },
194
+ goto: "model"
195
+ });
196
+ /**
197
+ * if `errorHandler` is a string, retry the tool call with given string
198
+ */
199
+ if (typeof errorHandler === "string") return new __langchain_langgraph.Command({
200
+ update: { messages: [response, new __langchain_core_messages.ToolMessage({
201
+ content: errorHandler,
202
+ tool_call_id: toolCallId
203
+ })] },
204
+ goto: "model"
205
+ });
206
+ /**
207
+ * if `errorHandler` is a function, retry the tool call with the function
208
+ */
209
+ if (typeof errorHandler === "function") {
210
+ const content = await errorHandler(error);
211
+ if (typeof content !== "string") throw new Error("Error handler must return a string.");
212
+ return new __langchain_langgraph.Command({
213
+ update: { messages: [response, new __langchain_core_messages.ToolMessage({
214
+ content,
215
+ tool_call_id: toolCallId
216
+ })] },
217
+ goto: "model"
218
+ });
219
+ }
220
+ /**
221
+ * throw otherwise, e.g. if `errorHandler` is not defined or set to `false`
222
+ */
223
+ throw error;
224
+ }
225
+ #areMoreStepsNeeded(state, response) {
226
+ const allToolsReturnDirect = response instanceof __langchain_core_messages.AIMessage && response.tool_calls?.every((call) => this.#options.shouldReturnDirect.has(call.name));
227
+ const remainingSteps = "remainingSteps" in state ? state.remainingSteps : void 0;
228
+ return Boolean(remainingSteps && (remainingSteps < 1 && allToolsReturnDirect || remainingSteps < 2 && require_utils.hasToolCalls(state.messages)));
229
+ }
230
+ #getModelInputState(state) {
231
+ const { messages, llmInputMessages,...rest } = state;
232
+ if (llmInputMessages && llmInputMessages.length > 0) return {
233
+ messages: llmInputMessages,
234
+ ...rest
235
+ };
236
+ return {
237
+ messages,
238
+ ...rest
239
+ };
240
+ }
241
+ async #executePrepareModelRequestHooks(model, state, config) {
242
+ if (!this.#options.prepareModelRequestHookMiddlewares || this.#options.prepareModelRequestHookMiddlewares.length === 0) return void 0;
243
+ let systemMessage;
244
+ if (typeof this.#options.prompt === "string") systemMessage = new __langchain_core_messages.SystemMessage(this.#options.prompt);
245
+ else if ((0, __langchain_core_messages.isBaseMessage)(this.#options.prompt)) systemMessage = this.#options.prompt;
246
+ let currentOptions = {
247
+ model,
248
+ systemMessage,
249
+ messages: state.messages,
250
+ tools: []
251
+ };
252
+ const middlewares = this.#options.prepareModelRequestHookMiddlewares;
253
+ for (const [middleware, getMiddlewareState] of middlewares) {
254
+ const context = {
255
+ ...middleware.contextSchema?.parse({}) || {},
256
+ ...config?.context || {}
257
+ };
258
+ const runtime = {
259
+ toolCalls: require_utils$2.parseToolCalls(state.messages),
260
+ toolResults: require_utils$2.parseToolResults(state.messages),
261
+ context
262
+ };
263
+ const result = await middleware.prepareModelRequest(currentOptions, {
264
+ messages: state.messages,
265
+ ...getMiddlewareState()
266
+ }, {
267
+ ...runtime,
268
+ context
269
+ });
270
+ if (result) currentOptions = {
271
+ ...currentOptions,
272
+ ...result
273
+ };
274
+ }
275
+ return currentOptions;
276
+ }
277
+ async #bindTools(model, preparedOptions) {
278
+ const options = { ...preparedOptions?.modelSettings };
279
+ const structuredTools = Object.values(this.#structuredToolInfo);
280
+ const allTools = this.#options.toolClasses.concat(...structuredTools.map((toolStrategy) => toolStrategy.tool), ...preparedOptions?.tools || []);
281
+ /**
282
+ * If there are structured tools, we need to set the tool choice to "any"
283
+ * so that the model can choose to use a structured tool or not.
284
+ */
285
+ const toolChoice = preparedOptions?.toolChoice || (structuredTools.length > 0 ? "any" : void 0);
286
+ /**
287
+ * check if the user requests a native schema output
288
+ */
289
+ if (this.#options.responseFormat instanceof require_responses.ProviderStrategy) {
290
+ /**
291
+ * if the model does not support JSON schema output, throw an error
292
+ */
293
+ if (!require_utils.hasSupportForJsonSchemaOutput(model)) throw new Error("Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.");
294
+ const jsonSchemaParams = {
295
+ name: this.#options.responseFormat.schema?.name ?? "extract",
296
+ description: (0, __langchain_core_utils_types.getSchemaDescription)(this.#options.responseFormat.schema),
297
+ schema: this.#options.responseFormat.schema,
298
+ strict: true
299
+ };
300
+ Object.assign(options, {
301
+ response_format: {
302
+ type: "json_schema",
303
+ json_schema: jsonSchemaParams
304
+ },
305
+ ls_structured_output_format: {
306
+ kwargs: { method: "json_schema" },
307
+ schema: this.#options.responseFormat.schema
308
+ },
309
+ strict: true
310
+ });
311
+ }
312
+ /**
313
+ * Bind tools to the model if they are not already bound.
314
+ */
315
+ const modelWithTools = await require_utils.bindTools(model, allTools, {
316
+ ...options,
317
+ tool_choice: toolChoice
318
+ });
319
+ /**
320
+ * Create a model runnable with the prompt and agent name
321
+ */
322
+ const modelRunnable = require_utils.getPromptRunnable(this.#options.prompt).pipe(this.#options.includeAgentName === "inline" ? require_withAgentName.withAgentName(modelWithTools, this.#options.includeAgentName) : modelWithTools);
323
+ return modelRunnable;
324
+ }
325
+ static get nodeOptions() {
326
+ return { input: zod.z.object({ messages: zod.z.array(zod.z.custom()) }) };
327
+ }
328
+ };
329
+
330
+ //#endregion
331
+ exports.AgentNode = AgentNode;
332
+ //# sourceMappingURL=AgentNode.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AgentNode.cjs","names":["RunnableCallable","options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>","#run","#options","#structuredToolInfo","transformResponseFormat","ToolStrategy","state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]","config: RunnableConfig","#invokeModel","Command","#areMoreStepsNeeded","AIMessage","initChatModel","options: {\n lastMessage?: string;\n }","#deriveModel","#executePrepareModelRequestHooks","validateLLMHasNoBoundTools","#bindTools","#getModelInputState","SystemMessage","mergeAbortSignals","ProviderStrategy","#handleMultipleStructuredOutputs","#handleSingleStructuredOutput","response: AIMessage","toolCalls: ToolCall[]","MultipleStructuredOutputsError","#handleToolStrategyError","toolCall: ToolCall","lastMessage?: string","error: ToolStrategyError","ToolMessage","response: BaseMessage","hasToolCalls","model: LanguageModelLike","config: LangGraphRunnableConfig","systemMessage: BaseMessage | undefined","currentOptions: ModelRequest","runtime: Runtime<any>","parseToolCalls","parseToolResults","preparedOptions?: ModelRequest","options: Partial<BaseChatModelCallOptions & AnthropicModelSettings>","hasSupportForJsonSchemaOutput","bindTools","getPromptRunnable","withAgentName","z"],"sources":["../../../../src/agents/middlewareAgent/nodes/AgentNode.ts"],"sourcesContent":["/* eslint-disable no-instanceof/no-instanceof */\nimport { Runnable, RunnableConfig } from \"@langchain/core/runnables\";\nimport {\n BaseMessage,\n AIMessage,\n ToolMessage,\n SystemMessage,\n isBaseMessage,\n isToolMessage,\n} from \"@langchain/core/messages\";\nimport { z } from \"zod\";\nimport { Command, type LangGraphRunnableConfig } from \"@langchain/langgraph\";\nimport { type LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { type BaseChatModelCallOptions } from \"@langchain/core/language_models/chat_models\";\nimport {\n InteropZodObject,\n getSchemaDescription,\n} from \"@langchain/core/utils/types\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\n\nimport { initChatModel } from \"../../../chat_models/universal.js\";\nimport { MultipleStructuredOutputsError } from \"../../errors.js\";\nimport { RunnableCallable } from \"../../RunnableCallable.js\";\nimport { PreHookAnnotation, AnyAnnotationRoot } from \"../../annotation.js\";\nimport {\n bindTools,\n getPromptRunnable,\n validateLLMHasNoBoundTools,\n hasToolCalls,\n hasSupportForJsonSchemaOutput,\n} from \"../../utils.js\";\nimport { mergeAbortSignals } from \"../../nodes/utils.js\";\nimport {\n ModelRequest,\n CreateAgentParams,\n InternalAgentState,\n AnthropicModelSettings,\n Runtime,\n AgentMiddleware,\n} from \"../types.js\";\nimport type { ClientTool, ServerTool } from \"../../types.js\";\nimport { withAgentName } from \"../../withAgentName.js\";\nimport {\n ToolStrategy,\n ProviderStrategy,\n transformResponseFormat,\n ToolStrategyError,\n} from \"../../responses.js\";\nimport { parseToolCalls, parseToolResults } from \"./utils.js\";\n\ntype ResponseHandlerResult<StructuredResponseFormat> =\n | {\n structuredResponse: StructuredResponseFormat;\n messages: BaseMessage[];\n }\n | Promise<Command>;\n\nexport interface AgentNodeOptions<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends Pick<\n CreateAgentParams<StructuredResponseFormat, ContextSchema>,\n | \"llm\"\n | \"model\"\n | \"prompt\"\n | \"includeAgentName\"\n | \"name\"\n | \"responseFormat\"\n | \"middlewares\"\n > {\n toolClasses: (ClientTool | ServerTool)[];\n shouldReturnDirect: Set<string>;\n signal?: AbortSignal;\n prepareModelRequestHookMiddlewares?: [\n AgentMiddleware<any, any, any>,\n () => any\n ][];\n}\n\nexport class AgentNode<\n StructuredResponseFormat extends Record<string, unknown> = Record<\n string,\n unknown\n >,\n ContextSchema extends AnyAnnotationRoot | InteropZodObject = AnyAnnotationRoot\n> extends RunnableCallable<\n InternalAgentState<StructuredResponseFormat> & PreHookAnnotation[\"State\"],\n { messages: BaseMessage[] } | { structuredResponse: StructuredResponseFormat }\n> {\n #options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>;\n\n #structuredToolInfo: Record<string, ToolStrategy> = {};\n\n constructor(\n options: AgentNodeOptions<StructuredResponseFormat, ContextSchema>\n ) {\n super({\n name: options.name ?? \"model\",\n func: (input, config) =>\n this.#run(input, config as RunnableConfig) as any,\n });\n\n this.#options = options;\n\n /**\n * Populate a list of structured tool info.\n */\n this.#structuredToolInfo = (\n transformResponseFormat(this.#options.responseFormat).filter(\n (format) => format instanceof ToolStrategy\n ) as ToolStrategy[]\n ).reduce((acc, format) => {\n acc[format.name] = format;\n return acc;\n }, {} as Record<string, ToolStrategy>);\n }\n\n async #run(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n /**\n * Check if we just executed a returnDirect tool\n * If so, we should generate structured response (if needed) and stop\n */\n const lastMessage = state.messages.at(-1);\n if (\n lastMessage &&\n isToolMessage(lastMessage) &&\n lastMessage.name &&\n this.#options.shouldReturnDirect.has(lastMessage.name)\n ) {\n /**\n * return directly without invoking the model again\n */\n return { messages: [] };\n }\n\n const response = await this.#invokeModel(state, config);\n\n /**\n * if we were able to generate a structured response, return it\n */\n if (\"structuredResponse\" in response) {\n return {\n messages: [...state.messages, ...(response.messages || [])],\n structuredResponse: response.structuredResponse,\n };\n }\n\n /**\n * if we need to direct the agent to the model, return the update\n */\n if (response instanceof Command) {\n return response;\n }\n\n response.name = this.name;\n response.lc_kwargs.name = this.name;\n\n if (this.#areMoreStepsNeeded(state, response)) {\n return {\n messages: [\n new AIMessage(\"Sorry, need more steps to process this request.\", {\n name: this.name,\n lc_kwargs: { name: this.name },\n id: response.id,\n }),\n ],\n };\n }\n\n return { messages: [response] };\n }\n\n /**\n * Derive the model from the options.\n * @param state - The state of the agent.\n * @param config - The config of the agent.\n * @returns The model.\n */\n #deriveModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig\n ) {\n if (this.#options.model) {\n if (typeof this.#options.model === \"string\") {\n return initChatModel(this.#options.model);\n }\n\n throw new Error(\"`model` option must be a string.\");\n }\n\n const model = this.#options.llm;\n\n /**\n * If the model is a function, call it to get the model.\n */\n if (typeof model === \"function\") {\n return model(state, config);\n }\n\n if (model) {\n return model;\n }\n\n throw new Error(\n \"No model option was provided, either via `model` or via `llm` option.\"\n );\n }\n\n async #invokeModel(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: RunnableConfig,\n options: {\n lastMessage?: string;\n } = {}\n ): Promise<AIMessage | ResponseHandlerResult<StructuredResponseFormat>> {\n const model = await this.#deriveModel(state, config);\n\n /**\n * Execute prepareModelRequest hooks from beforeModelNodes\n */\n const preparedOptions = await this.#executePrepareModelRequestHooks(\n model,\n state,\n config\n );\n\n /**\n * If user provides a model in the preparedOptions, use it,\n * otherwise use the model from the options\n */\n const finalModel = preparedOptions?.model ?? model;\n\n /**\n * Check if the LLM already has bound tools and throw if it does.\n */\n validateLLMHasNoBoundTools(finalModel);\n\n const modelWithTools = await this.#bindTools(finalModel, preparedOptions);\n let modelInput = this.#getModelInputState(state);\n\n // Use messages from preparedOptions if provided\n if (preparedOptions?.messages) {\n modelInput = { ...modelInput, messages: preparedOptions.messages };\n }\n\n // Add system message if provided\n if (preparedOptions?.systemMessage) {\n // Prepend a system message if needed\n const systemMsg = new SystemMessage(preparedOptions.systemMessage);\n modelInput = {\n ...modelInput,\n messages: [systemMsg, ...modelInput.messages],\n };\n }\n\n const signal = mergeAbortSignals(this.#options.signal, config.signal);\n const invokeConfig = {\n ...config,\n signal,\n };\n\n const response = (await modelWithTools.invoke(\n modelInput,\n invokeConfig\n )) as AIMessage;\n\n /**\n * if the user requests a native schema output, try to parse the response\n * and return the structured response if it is valid\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n const structuredResponse = this.#options.responseFormat.parse(response);\n if (structuredResponse) {\n return { structuredResponse, messages: [response] };\n }\n }\n\n if (!response.tool_calls) {\n return response;\n }\n\n const toolCalls = response.tool_calls.filter(\n (call) => call.name in this.#structuredToolInfo\n );\n\n /**\n * if there were not structured tool calls, we can return the response\n */\n if (toolCalls.length === 0) {\n return response;\n }\n\n /**\n * if there were multiple structured tool calls, we should throw an error as this\n * scenario is not defined/supported.\n */\n if (toolCalls.length > 1) {\n return this.#handleMultipleStructuredOutputs(response, toolCalls);\n }\n\n const toolStrategy = this.#structuredToolInfo[toolCalls[0].name];\n const toolMessageContent = toolStrategy?.options?.toolMessageContent;\n return this.#handleSingleStructuredOutput(\n response,\n toolCalls[0],\n toolMessageContent ?? options.lastMessage\n );\n }\n\n /**\n * If the model returns multiple structured outputs, we need to handle it.\n * @param response - The response from the model\n * @param toolCalls - The tool calls that were made\n * @returns The response from the model\n */\n #handleMultipleStructuredOutputs(\n response: AIMessage,\n toolCalls: ToolCall[]\n ): Promise<Command> {\n /**\n * the following should never happen, let's throw an error if it does\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n throw new Error(\n \"Multiple structured outputs should not apply to native structured output responses\"\n );\n }\n\n const multipleStructuredOutputsError = new MultipleStructuredOutputsError(\n toolCalls.map((call) => call.name)\n );\n\n return this.#handleToolStrategyError(\n multipleStructuredOutputsError,\n response,\n toolCalls[0]\n );\n }\n\n /**\n * If the model returns a single structured output, we need to handle it.\n * @param toolCall - The tool call that was made\n * @returns The structured response and a message to the LLM if needed\n */\n #handleSingleStructuredOutput(\n response: AIMessage,\n toolCall: ToolCall,\n lastMessage?: string\n ): ResponseHandlerResult<StructuredResponseFormat> {\n const tool = this.#structuredToolInfo[toolCall.name];\n\n try {\n const structuredResponse = tool.parse(\n toolCall.args\n ) as StructuredResponseFormat;\n\n return {\n structuredResponse,\n messages: [\n response,\n new AIMessage(\n lastMessage ??\n `Returning structured response: ${JSON.stringify(\n structuredResponse\n )}`\n ),\n ],\n };\n } catch (error) {\n return this.#handleToolStrategyError(\n error as ToolStrategyError,\n response,\n toolCall\n );\n }\n }\n\n async #handleToolStrategyError(\n error: ToolStrategyError,\n response: AIMessage,\n toolCall: ToolCall\n ): Promise<Command> {\n /**\n * Using the `errorHandler` option of the first `ToolStrategy` entry is sufficient here.\n * There is technically only one `ToolStrategy` entry in `structuredToolInfo` if the user\n * uses `toolStrategy` to define the response format. If the user applies a list of json\n * schema objects, these will be transformed into multiple `ToolStrategy` entries but all\n * with the same `handleError` option.\n */\n const errorHandler = Object.values(this.#structuredToolInfo).at(0)?.options\n ?.handleError;\n\n const toolCallId = toolCall.id;\n if (!toolCallId) {\n throw new Error(\n \"Tool call ID is required to handle tool output errors. Please provide a tool call ID.\"\n );\n }\n\n /**\n * retry if:\n */\n if (\n /**\n * if the user has provided `true` as the `errorHandler` option, return a new AIMessage\n * with the error message and retry the tool call.\n */\n (typeof errorHandler === \"boolean\" && errorHandler) ||\n /**\n * if `errorHandler` is an array and contains MultipleStructuredOutputsError\n */\n (Array.isArray(errorHandler) &&\n errorHandler.some((h) => h instanceof MultipleStructuredOutputsError))\n ) {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: error.message,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a string, retry the tool call with given string\n */\n if (typeof errorHandler === \"string\") {\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content: errorHandler,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * if `errorHandler` is a function, retry the tool call with the function\n */\n if (typeof errorHandler === \"function\") {\n const content = await errorHandler(error);\n if (typeof content !== \"string\") {\n throw new Error(\"Error handler must return a string.\");\n }\n\n return new Command({\n update: {\n messages: [\n response,\n new ToolMessage({\n content,\n tool_call_id: toolCallId,\n }),\n ],\n },\n goto: \"model\",\n });\n }\n\n /**\n * throw otherwise, e.g. if `errorHandler` is not defined or set to `false`\n */\n throw error;\n }\n\n #areMoreStepsNeeded(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n response: BaseMessage\n ): boolean {\n const allToolsReturnDirect =\n response instanceof AIMessage &&\n response.tool_calls?.every((call) =>\n this.#options.shouldReturnDirect.has(call.name)\n );\n const remainingSteps =\n \"remainingSteps\" in state ? (state.remainingSteps as number) : undefined;\n return Boolean(\n remainingSteps &&\n ((remainingSteps < 1 && allToolsReturnDirect) ||\n (remainingSteps < 2 && hasToolCalls(state.messages)))\n );\n }\n\n #getModelInputState(\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"]\n ): Omit<InternalAgentState<StructuredResponseFormat>, \"llmInputMessages\"> {\n const { messages, llmInputMessages, ...rest } = state;\n if (llmInputMessages && llmInputMessages.length > 0) {\n return { messages: llmInputMessages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n return { messages, ...rest } as Omit<\n InternalAgentState<StructuredResponseFormat>,\n \"llmInputMessages\"\n >;\n }\n\n async #executePrepareModelRequestHooks(\n model: LanguageModelLike,\n state: InternalAgentState<StructuredResponseFormat> &\n PreHookAnnotation[\"State\"],\n config: LangGraphRunnableConfig\n ): Promise<ModelRequest | undefined> {\n if (\n !this.#options.prepareModelRequestHookMiddlewares ||\n this.#options.prepareModelRequestHookMiddlewares.length === 0\n ) {\n return undefined;\n }\n\n // Get the prompt for system message\n let systemMessage: BaseMessage | undefined;\n if (typeof this.#options.prompt === \"string\") {\n systemMessage = new SystemMessage(this.#options.prompt);\n } else if (isBaseMessage(this.#options.prompt)) {\n systemMessage = this.#options.prompt;\n }\n\n // Prepare the initial call options\n let currentOptions: ModelRequest = {\n model,\n systemMessage,\n messages: state.messages,\n tools: [],\n };\n\n // Execute prepareModelRequest hooks from all middlewares\n const middlewares = this.#options.prepareModelRequestHookMiddlewares;\n for (const [middleware, getMiddlewareState] of middlewares) {\n // Merge context with default context of middleware\n const context = {\n ...(middleware.contextSchema?.parse({}) || {}),\n ...(config?.context || {}),\n };\n\n // Create runtime\n const runtime: Runtime<any> = {\n toolCalls: parseToolCalls(state.messages),\n toolResults: parseToolResults(state.messages),\n context,\n };\n\n const result = await middleware.prepareModelRequest!(\n currentOptions,\n {\n messages: state.messages,\n ...getMiddlewareState(),\n },\n {\n ...runtime,\n context,\n }\n );\n\n if (result) {\n currentOptions = { ...currentOptions, ...result };\n }\n }\n\n return currentOptions;\n }\n\n async #bindTools(\n model: LanguageModelLike,\n preparedOptions?: ModelRequest\n ): Promise<Runnable> {\n const options: Partial<BaseChatModelCallOptions & AnthropicModelSettings> =\n {\n ...preparedOptions?.modelSettings,\n };\n const structuredTools = Object.values(this.#structuredToolInfo);\n\n // Use tools from preparedOptions if provided, otherwise use default tools\n const allTools = this.#options.toolClasses.concat(\n ...structuredTools.map((toolStrategy) => toolStrategy.tool),\n ...(preparedOptions?.tools || [])\n );\n\n /**\n * If there are structured tools, we need to set the tool choice to \"any\"\n * so that the model can choose to use a structured tool or not.\n */\n const toolChoice =\n preparedOptions?.toolChoice ||\n (structuredTools.length > 0 ? \"any\" : undefined);\n\n /**\n * check if the user requests a native schema output\n */\n if (this.#options.responseFormat instanceof ProviderStrategy) {\n /**\n * if the model does not support JSON schema output, throw an error\n */\n if (!hasSupportForJsonSchemaOutput(model)) {\n throw new Error(\n \"Model does not support native structured output responses. Please use a model that supports native structured output responses or use a tool output.\"\n );\n }\n\n const jsonSchemaParams = {\n name: this.#options.responseFormat.schema?.name ?? \"extract\",\n description: getSchemaDescription(this.#options.responseFormat.schema),\n schema: this.#options.responseFormat.schema,\n strict: true,\n };\n\n Object.assign(options, {\n response_format: {\n type: \"json_schema\",\n json_schema: jsonSchemaParams,\n },\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: this.#options.responseFormat.schema,\n },\n strict: true,\n });\n }\n\n /**\n * Bind tools to the model if they are not already bound.\n */\n const modelWithTools = await bindTools(model, allTools, {\n ...options,\n tool_choice: toolChoice,\n });\n\n /**\n * Create a model runnable with the prompt and agent name\n */\n const modelRunnable = getPromptRunnable(this.#options.prompt).pipe(\n this.#options.includeAgentName === \"inline\"\n ? withAgentName(modelWithTools, this.#options.includeAgentName)\n : modelWithTools\n );\n\n return modelRunnable;\n }\n\n static get nodeOptions() {\n return {\n input: z.object({\n messages: z.array(z.custom<BaseMessage>()),\n }),\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkFA,IAAa,YAAb,cAMUA,0CAGR;CACA;CAEA,sBAAoD,CAAE;CAEtD,YACEC,SACA;EACA,MAAM;GACJ,MAAM,QAAQ,QAAQ;GACtB,MAAM,CAAC,OAAO,WACZ,KAAKC,KAAK,OAAO,OAAyB;EAC7C,EAAC;EAEF,KAAKC,WAAW;;;;EAKhB,KAAKC,sBACHC,0CAAwB,KAAKF,SAAS,eAAe,CAAC,OACpD,CAAC,WAAW,kBAAkBG,+BAC/B,CACD,OAAO,CAAC,KAAK,WAAW;GACxB,IAAI,OAAO,QAAQ;AACnB,UAAO;EACR,GAAE,CAAE,EAAiC;CACvC;CAED,MAAMJ,KACJK,OAEAC,QACA;;;;;EAKA,MAAM,cAAc,MAAM,SAAS,GAAG,GAAG;AACzC,MACE,4DACc,YAAY,IAC1B,YAAY,QACZ,KAAKL,SAAS,mBAAmB,IAAI,YAAY,KAAK;;;;AAKtD,SAAO,EAAE,UAAU,CAAE,EAAE;EAGzB,MAAM,WAAW,MAAM,KAAKM,aAAa,OAAO,OAAO;;;;AAKvD,MAAI,wBAAwB,SAC1B,QAAO;GACL,UAAU,CAAC,GAAG,MAAM,UAAU,G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