@langchain/anthropic 0.3.31 → 1.0.0-alpha.2

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 (101) hide show
  1. package/README.md +8 -8
  2. package/dist/_virtual/rolldown_runtime.cjs +25 -0
  3. package/dist/chat_models.cjs +781 -1012
  4. package/dist/chat_models.cjs.map +1 -0
  5. package/dist/chat_models.d.cts +620 -0
  6. package/dist/chat_models.d.cts.map +1 -0
  7. package/dist/chat_models.d.ts +227 -211
  8. package/dist/chat_models.d.ts.map +1 -0
  9. package/dist/chat_models.js +775 -1003
  10. package/dist/chat_models.js.map +1 -0
  11. package/dist/index.cjs +6 -20
  12. package/dist/index.d.cts +4 -0
  13. package/dist/index.d.ts +4 -3
  14. package/dist/index.js +4 -2
  15. package/dist/output_parsers.cjs +65 -104
  16. package/dist/output_parsers.cjs.map +1 -0
  17. package/dist/output_parsers.js +64 -100
  18. package/dist/output_parsers.js.map +1 -0
  19. package/dist/types.d.cts +33 -0
  20. package/dist/types.d.cts.map +1 -0
  21. package/dist/types.d.ts +30 -32
  22. package/dist/types.d.ts.map +1 -0
  23. package/dist/utils/content.cjs +151 -0
  24. package/dist/utils/content.cjs.map +1 -0
  25. package/dist/utils/content.js +146 -0
  26. package/dist/utils/content.js.map +1 -0
  27. package/dist/utils/errors.cjs +16 -27
  28. package/dist/utils/errors.cjs.map +1 -0
  29. package/dist/utils/errors.js +17 -25
  30. package/dist/utils/errors.js.map +1 -0
  31. package/dist/utils/index.cjs +7 -0
  32. package/dist/utils/index.cjs.map +1 -0
  33. package/dist/utils/index.js +6 -0
  34. package/dist/utils/index.js.map +1 -0
  35. package/dist/utils/message_inputs.cjs +223 -534
  36. package/dist/utils/message_inputs.cjs.map +1 -0
  37. package/dist/utils/message_inputs.js +224 -532
  38. package/dist/utils/message_inputs.js.map +1 -0
  39. package/dist/utils/message_outputs.cjs +186 -250
  40. package/dist/utils/message_outputs.cjs.map +1 -0
  41. package/dist/utils/message_outputs.js +185 -247
  42. package/dist/utils/message_outputs.js.map +1 -0
  43. package/dist/utils/prompts.cjs +46 -45
  44. package/dist/utils/prompts.cjs.map +1 -0
  45. package/dist/utils/prompts.d.cts +45 -0
  46. package/dist/utils/prompts.d.cts.map +1 -0
  47. package/dist/utils/prompts.d.ts +8 -2
  48. package/dist/utils/prompts.d.ts.map +1 -0
  49. package/dist/utils/prompts.js +46 -42
  50. package/dist/utils/prompts.js.map +1 -0
  51. package/dist/utils/standard.cjs +285 -0
  52. package/dist/utils/standard.cjs.map +1 -0
  53. package/dist/utils/standard.js +285 -0
  54. package/dist/utils/standard.js.map +1 -0
  55. package/dist/utils/tools.cjs +15 -30
  56. package/dist/utils/tools.cjs.map +1 -0
  57. package/dist/utils/tools.js +15 -28
  58. package/dist/utils/tools.js.map +1 -0
  59. package/package.json +45 -71
  60. package/dist/experimental/index.cjs +0 -17
  61. package/dist/experimental/index.d.ts +0 -1
  62. package/dist/experimental/index.js +0 -1
  63. package/dist/experimental/tool_calling.cjs +0 -318
  64. package/dist/experimental/tool_calling.d.ts +0 -57
  65. package/dist/experimental/tool_calling.js +0 -314
  66. package/dist/experimental/utils/tool_calling.cjs +0 -106
  67. package/dist/experimental/utils/tool_calling.d.ts +0 -10
  68. package/dist/experimental/utils/tool_calling.js +0 -101
  69. package/dist/load/import_constants.cjs +0 -5
  70. package/dist/load/import_constants.d.ts +0 -1
  71. package/dist/load/import_constants.js +0 -2
  72. package/dist/load/import_map.cjs +0 -39
  73. package/dist/load/import_map.d.ts +0 -2
  74. package/dist/load/import_map.js +0 -3
  75. package/dist/load/import_type.cjs +0 -3
  76. package/dist/load/import_type.d.ts +0 -5
  77. package/dist/load/import_type.js +0 -2
  78. package/dist/load/index.cjs +0 -63
  79. package/dist/load/index.d.ts +0 -14
  80. package/dist/load/index.js +0 -25
  81. package/dist/load/map_keys.cjs +0 -2
  82. package/dist/load/map_keys.d.ts +0 -3
  83. package/dist/load/map_keys.js +0 -1
  84. package/dist/load/serializable.cjs +0 -17
  85. package/dist/load/serializable.d.ts +0 -1
  86. package/dist/load/serializable.js +0 -1
  87. package/dist/output_parsers.d.ts +0 -22
  88. package/dist/types.cjs +0 -48
  89. package/dist/types.js +0 -45
  90. package/dist/utils/errors.d.ts +0 -3
  91. package/dist/utils/message_inputs.d.ts +0 -14
  92. package/dist/utils/message_outputs.d.ts +0 -14
  93. package/dist/utils/tools.d.ts +0 -3
  94. package/experimental.cjs +0 -1
  95. package/experimental.d.cts +0 -1
  96. package/experimental.d.ts +0 -1
  97. package/experimental.js +0 -1
  98. package/index.cjs +0 -1
  99. package/index.d.cts +0 -1
  100. package/index.d.ts +0 -1
  101. package/index.js +0 -1
@@ -1,1026 +1,795 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ChatAnthropic = exports.ChatAnthropicMessages = void 0;
4
- const sdk_1 = require("@anthropic-ai/sdk");
5
- const messages_1 = require("@langchain/core/messages");
6
- const outputs_1 = require("@langchain/core/outputs");
7
- const env_1 = require("@langchain/core/utils/env");
8
- const chat_models_1 = require("@langchain/core/language_models/chat_models");
9
- const base_1 = require("@langchain/core/language_models/base");
10
- const json_schema_1 = require("@langchain/core/utils/json_schema");
11
- const runnables_1 = require("@langchain/core/runnables");
12
- const types_1 = require("@langchain/core/utils/types");
13
- const function_calling_1 = require("@langchain/core/utils/function_calling");
14
- const output_parsers_js_1 = require("./output_parsers.cjs");
15
- const tools_js_1 = require("./utils/tools.cjs");
16
- const message_inputs_js_1 = require("./utils/message_inputs.cjs");
17
- const message_outputs_js_1 = require("./utils/message_outputs.cjs");
18
- const errors_js_1 = require("./utils/errors.cjs");
1
+ const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
2
+ const require_output_parsers = require('./output_parsers.cjs');
3
+ const require_tools = require('./utils/tools.cjs');
4
+ const require_message_inputs = require('./utils/message_inputs.cjs');
5
+ const require_message_outputs = require('./utils/message_outputs.cjs');
6
+ const require_errors = require('./utils/errors.cjs');
7
+ const __anthropic_ai_sdk = require_rolldown_runtime.__toESM(require("@anthropic-ai/sdk"));
8
+ const __langchain_core_messages = require_rolldown_runtime.__toESM(require("@langchain/core/messages"));
9
+ const __langchain_core_outputs = require_rolldown_runtime.__toESM(require("@langchain/core/outputs"));
10
+ const __langchain_core_utils_env = require_rolldown_runtime.__toESM(require("@langchain/core/utils/env"));
11
+ const __langchain_core_language_models_chat_models = require_rolldown_runtime.__toESM(require("@langchain/core/language_models/chat_models"));
12
+ const __langchain_core_language_models_base = require_rolldown_runtime.__toESM(require("@langchain/core/language_models/base"));
13
+ const __langchain_core_utils_json_schema = require_rolldown_runtime.__toESM(require("@langchain/core/utils/json_schema"));
14
+ const __langchain_core_runnables = require_rolldown_runtime.__toESM(require("@langchain/core/runnables"));
15
+ const __langchain_core_utils_types = require_rolldown_runtime.__toESM(require("@langchain/core/utils/types"));
16
+ const __langchain_core_utils_function_calling = require_rolldown_runtime.__toESM(require("@langchain/core/utils/function_calling"));
17
+
18
+ //#region src/chat_models.ts
19
19
  function _toolsInParams(params) {
20
- return !!(params.tools && params.tools.length > 0);
20
+ return !!(params.tools && params.tools.length > 0);
21
21
  }
22
22
  function _documentsInParams(params) {
23
- for (const message of params.messages ?? []) {
24
- if (typeof message.content === "string") {
25
- continue;
26
- }
27
- for (const block of message.content ?? []) {
28
- if (typeof block === "object" &&
29
- block != null &&
30
- block.type === "document" &&
31
- typeof block.citations === "object" &&
32
- block.citations?.enabled) {
33
- return true;
34
- }
35
- }
36
- }
37
- return false;
23
+ for (const message of params.messages ?? []) {
24
+ if (typeof message.content === "string") continue;
25
+ for (const block of message.content ?? []) if (typeof block === "object" && block != null && block.type === "document" && typeof block.citations === "object" && block.citations?.enabled) return true;
26
+ }
27
+ return false;
38
28
  }
39
29
  function _thinkingInParams(params) {
40
- return !!(params.thinking && params.thinking.type === "enabled");
30
+ return !!(params.thinking && params.thinking.type === "enabled");
41
31
  }
42
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
43
32
  function isAnthropicTool(tool) {
44
- return "input_schema" in tool;
33
+ return "input_schema" in tool;
45
34
  }
46
35
  function isBuiltinTool(tool) {
47
- const builtInToolPrefixes = [
48
- "text_editor_",
49
- "computer_",
50
- "bash_",
51
- "web_search_",
52
- "web_fetch_",
53
- "str_replace_editor_",
54
- "str_replace_based_edit_tool_",
55
- "code_execution_",
56
- "memory_",
57
- ];
58
- return (typeof tool === "object" &&
59
- tool !== null &&
60
- "type" in tool &&
61
- "name" in tool &&
62
- builtInToolPrefixes.some((prefix) => typeof tool.type === "string" && tool.type.startsWith(prefix)));
36
+ const builtInToolPrefixes = [
37
+ "text_editor_",
38
+ "computer_",
39
+ "bash_",
40
+ "web_search_",
41
+ "web_fetch_",
42
+ "str_replace_editor_",
43
+ "str_replace_based_edit_tool_",
44
+ "code_execution_",
45
+ "memory_"
46
+ ];
47
+ return typeof tool === "object" && tool !== null && "type" in tool && "name" in tool && typeof tool.type === "string" && builtInToolPrefixes.some((prefix) => typeof tool.type === "string" && tool.type.startsWith(prefix));
63
48
  }
64
49
  function extractToken(chunk) {
65
- if (typeof chunk.content === "string") {
66
- return chunk.content;
67
- }
68
- else if (Array.isArray(chunk.content) &&
69
- chunk.content.length >= 1 &&
70
- "input" in chunk.content[0]) {
71
- return typeof chunk.content[0].input === "string"
72
- ? chunk.content[0].input
73
- : JSON.stringify(chunk.content[0].input);
74
- }
75
- else if (Array.isArray(chunk.content) &&
76
- chunk.content.length >= 1 &&
77
- "text" in chunk.content[0]) {
78
- return chunk.content[0].text;
79
- }
80
- return undefined;
50
+ if (typeof chunk.content === "string") return chunk.content;
51
+ else if (Array.isArray(chunk.content) && chunk.content.length >= 1 && "input" in chunk.content[0]) return typeof chunk.content[0].input === "string" ? chunk.content[0].input : JSON.stringify(chunk.content[0].input);
52
+ else if (Array.isArray(chunk.content) && chunk.content.length >= 1 && "text" in chunk.content[0] && typeof chunk.content[0].text === "string") return chunk.content[0].text;
53
+ return void 0;
81
54
  }
82
55
  /**
83
- * Anthropic chat model integration.
84
- *
85
- * Setup:
86
- * Install `@langchain/anthropic` and set an environment variable named `ANTHROPIC_API_KEY`.
87
- *
88
- * ```bash
89
- * npm install @langchain/anthropic
90
- * export ANTHROPIC_API_KEY="your-api-key"
91
- * ```
92
- *
93
- * ## [Constructor args](https://api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html#constructor)
94
- *
95
- * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_anthropic.ChatAnthropicCallOptions.html)
96
- *
97
- * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.
98
- * They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below:
99
- *
100
- * ```typescript
101
- * // When calling `.bind`, call options should be passed via the first argument
102
- * const llmWithArgsBound = llm.bindTools([...]).withConfig({
103
- * stop: ["\n"],
104
- * });
105
- *
106
- * // When calling `.bindTools`, call options should be passed via the second argument
107
- * const llmWithTools = llm.bindTools(
108
- * [...],
109
- * {
110
- * tool_choice: "auto",
111
- * }
112
- * );
113
- * ```
114
- *
115
- * ## Examples
116
- *
117
- * <details open>
118
- * <summary><strong>Instantiate</strong></summary>
119
- *
120
- * ```typescript
121
- * import { ChatAnthropic } from '@langchain/anthropic';
122
- *
123
- * const llm = new ChatAnthropic({
124
- * model: "claude-3-5-sonnet-20240620",
125
- * temperature: 0,
126
- * maxTokens: undefined,
127
- * maxRetries: 2,
128
- * // apiKey: "...",
129
- * // baseUrl: "...",
130
- * // other params...
131
- * });
132
- * ```
133
- * </details>
134
- *
135
- * <br />
136
- *
137
- * <details>
138
- * <summary><strong>Invoking</strong></summary>
139
- *
140
- * ```typescript
141
- * const input = `Translate "I love programming" into French.`;
142
- *
143
- * // Models also accept a list of chat messages or a formatted prompt
144
- * const result = await llm.invoke(input);
145
- * console.log(result);
146
- * ```
147
- *
148
- * ```txt
149
- * AIMessage {
150
- * "id": "msg_01QDpd78JUHpRP6bRRNyzbW3",
151
- * "content": "Here's the translation to French:\n\nJ'adore la programmation.",
152
- * "response_metadata": {
153
- * "id": "msg_01QDpd78JUHpRP6bRRNyzbW3",
154
- * "model": "claude-3-5-sonnet-20240620",
155
- * "stop_reason": "end_turn",
156
- * "stop_sequence": null,
157
- * "usage": {
158
- * "input_tokens": 25,
159
- * "output_tokens": 19
160
- * },
161
- * "type": "message",
162
- * "role": "assistant"
163
- * },
164
- * "usage_metadata": {
165
- * "input_tokens": 25,
166
- * "output_tokens": 19,
167
- * "total_tokens": 44
168
- * }
169
- * }
170
- * ```
171
- * </details>
172
- *
173
- * <br />
174
- *
175
- * <details>
176
- * <summary><strong>Streaming Chunks</strong></summary>
177
- *
178
- * ```typescript
179
- * for await (const chunk of await llm.stream(input)) {
180
- * console.log(chunk);
181
- * }
182
- * ```
183
- *
184
- * ```txt
185
- * AIMessageChunk {
186
- * "id": "msg_01N8MwoYxiKo9w4chE4gXUs4",
187
- * "content": "",
188
- * "additional_kwargs": {
189
- * "id": "msg_01N8MwoYxiKo9w4chE4gXUs4",
190
- * "type": "message",
191
- * "role": "assistant",
192
- * "model": "claude-3-5-sonnet-20240620"
193
- * },
194
- * "usage_metadata": {
195
- * "input_tokens": 25,
196
- * "output_tokens": 1,
197
- * "total_tokens": 26
198
- * }
199
- * }
200
- * AIMessageChunk {
201
- * "content": "",
202
- * }
203
- * AIMessageChunk {
204
- * "content": "Here",
205
- * }
206
- * AIMessageChunk {
207
- * "content": "'s",
208
- * }
209
- * AIMessageChunk {
210
- * "content": " the translation to",
211
- * }
212
- * AIMessageChunk {
213
- * "content": " French:\n\nJ",
214
- * }
215
- * AIMessageChunk {
216
- * "content": "'adore la programmation",
217
- * }
218
- * AIMessageChunk {
219
- * "content": ".",
220
- * }
221
- * AIMessageChunk {
222
- * "content": "",
223
- * "additional_kwargs": {
224
- * "stop_reason": "end_turn",
225
- * "stop_sequence": null
226
- * },
227
- * "usage_metadata": {
228
- * "input_tokens": 0,
229
- * "output_tokens": 19,
230
- * "total_tokens": 19
231
- * }
232
- * }
233
- * ```
234
- * </details>
235
- *
236
- * <br />
237
- *
238
- * <details>
239
- * <summary><strong>Aggregate Streamed Chunks</strong></summary>
240
- *
241
- * ```typescript
242
- * import { AIMessageChunk } from '@langchain/core/messages';
243
- * import { concat } from '@langchain/core/utils/stream';
244
- *
245
- * const stream = await llm.stream(input);
246
- * let full: AIMessageChunk | undefined;
247
- * for await (const chunk of stream) {
248
- * full = !full ? chunk : concat(full, chunk);
249
- * }
250
- * console.log(full);
251
- * ```
252
- *
253
- * ```txt
254
- * AIMessageChunk {
255
- * "id": "msg_01SBTb5zSGXfjUc7yQ8EKEEA",
256
- * "content": "Here's the translation to French:\n\nJ'adore la programmation.",
257
- * "additional_kwargs": {
258
- * "id": "msg_01SBTb5zSGXfjUc7yQ8EKEEA",
259
- * "type": "message",
260
- * "role": "assistant",
261
- * "model": "claude-3-5-sonnet-20240620",
262
- * "stop_reason": "end_turn",
263
- * "stop_sequence": null
264
- * },
265
- * "usage_metadata": {
266
- * "input_tokens": 25,
267
- * "output_tokens": 20,
268
- * "total_tokens": 45
269
- * }
270
- * }
271
- * ```
272
- * </details>
273
- *
274
- * <br />
275
- *
276
- * <details>
277
- * <summary><strong>Bind tools</strong></summary>
278
- *
279
- * ```typescript
280
- * import { z } from 'zod';
281
- *
282
- * const GetWeather = {
283
- * name: "GetWeather",
284
- * description: "Get the current weather in a given location",
285
- * schema: z.object({
286
- * location: z.string().describe("The city and state, e.g. San Francisco, CA")
287
- * }),
288
- * }
289
- *
290
- * const GetPopulation = {
291
- * name: "GetPopulation",
292
- * description: "Get the current population in a given location",
293
- * schema: z.object({
294
- * location: z.string().describe("The city and state, e.g. San Francisco, CA")
295
- * }),
296
- * }
297
- *
298
- * const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);
299
- * const aiMsg = await llmWithTools.invoke(
300
- * "Which city is hotter today and which is bigger: LA or NY?"
301
- * );
302
- * console.log(aiMsg.tool_calls);
303
- * ```
304
- *
305
- * ```txt
306
- * [
307
- * {
308
- * name: 'GetWeather',
309
- * args: { location: 'Los Angeles, CA' },
310
- * id: 'toolu_01WjW3Dann6BPJVtLhovdBD5',
311
- * type: 'tool_call'
312
- * },
313
- * {
314
- * name: 'GetWeather',
315
- * args: { location: 'New York, NY' },
316
- * id: 'toolu_01G6wfJgqi5zRmJomsmkyZXe',
317
- * type: 'tool_call'
318
- * },
319
- * {
320
- * name: 'GetPopulation',
321
- * args: { location: 'Los Angeles, CA' },
322
- * id: 'toolu_0165qYWBA2VFyUst5RA18zew',
323
- * type: 'tool_call'
324
- * },
325
- * {
326
- * name: 'GetPopulation',
327
- * args: { location: 'New York, NY' },
328
- * id: 'toolu_01PGNyP33vxr13tGqr7i3rDo',
329
- * type: 'tool_call'
330
- * }
331
- * ]
332
- * ```
333
- * </details>
334
- *
335
- * <br />
336
- *
337
- * <details>
338
- * <summary><strong>Structured Output</strong></summary>
339
- *
340
- * ```typescript
341
- * import { z } from 'zod';
342
- *
343
- * const Joke = z.object({
344
- * setup: z.string().describe("The setup of the joke"),
345
- * punchline: z.string().describe("The punchline to the joke"),
346
- * rating: z.number().optional().describe("How funny the joke is, from 1 to 10")
347
- * }).describe('Joke to tell user.');
348
- *
349
- * const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" });
350
- * const jokeResult = await structuredLlm.invoke("Tell me a joke about cats");
351
- * console.log(jokeResult);
352
- * ```
353
- *
354
- * ```txt
355
- * {
356
- * setup: "Why don't cats play poker in the jungle?",
357
- * punchline: 'Too many cheetahs!',
358
- * rating: 7
359
- * }
360
- * ```
361
- * </details>
362
- *
363
- * <br />
364
- *
365
- * <details>
366
- * <summary><strong>Multimodal</strong></summary>
367
- *
368
- * ```typescript
369
- * import { HumanMessage } from '@langchain/core/messages';
370
- *
371
- * const imageUrl = "https://example.com/image.jpg";
372
- * const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());
373
- * const base64Image = Buffer.from(imageData).toString('base64');
374
- *
375
- * const message = new HumanMessage({
376
- * content: [
377
- * { type: "text", text: "describe the weather in this image" },
378
- * {
379
- * type: "image_url",
380
- * image_url: { url: `data:image/jpeg;base64,${base64Image}` },
381
- * },
382
- * ]
383
- * });
384
- *
385
- * const imageDescriptionAiMsg = await llm.invoke([message]);
386
- * console.log(imageDescriptionAiMsg.content);
387
- * ```
388
- *
389
- * ```txt
390
- * The weather in this image appears to be beautiful and clear. The sky is a vibrant blue with scattered white clouds, suggesting a sunny and pleasant day. The clouds are wispy and light, indicating calm conditions without any signs of storms or heavy weather. The bright green grass on the rolling hills looks lush and well-watered, which could mean recent rainfall or good growing conditions. Overall, the scene depicts a perfect spring or early summer day with mild temperatures, plenty of sunshine, and gentle breezes - ideal weather for enjoying the outdoors or for plant growth.
391
- * ```
392
- * </details>
393
- *
394
- * <br />
395
- *
396
- * <details>
397
- * <summary><strong>Usage Metadata</strong></summary>
398
- *
399
- * ```typescript
400
- * const aiMsgForMetadata = await llm.invoke(input);
401
- * console.log(aiMsgForMetadata.usage_metadata);
402
- * ```
403
- *
404
- * ```txt
405
- * { input_tokens: 25, output_tokens: 19, total_tokens: 44 }
406
- * ```
407
- * </details>
408
- *
409
- * <br />
410
- *
411
- * <details>
412
- * <summary><strong>Stream Usage Metadata</strong></summary>
413
- *
414
- * ```typescript
415
- * const streamForMetadata = await llm.stream(
416
- * input,
417
- * {
418
- * streamUsage: true
419
- * }
420
- * );
421
- * let fullForMetadata: AIMessageChunk | undefined;
422
- * for await (const chunk of streamForMetadata) {
423
- * fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk);
424
- * }
425
- * console.log(fullForMetadata?.usage_metadata);
426
- * ```
427
- *
428
- * ```txt
429
- * { input_tokens: 25, output_tokens: 20, total_tokens: 45 }
430
- * ```
431
- * </details>
432
- *
433
- * <br />
434
- *
435
- * <details>
436
- * <summary><strong>Response Metadata</strong></summary>
437
- *
438
- * ```typescript
439
- * const aiMsgForResponseMetadata = await llm.invoke(input);
440
- * console.log(aiMsgForResponseMetadata.response_metadata);
441
- * ```
442
- *
443
- * ```txt
444
- * {
445
- * id: 'msg_01STxeQxJmp4sCSpioD6vK3L',
446
- * model: 'claude-3-5-sonnet-20240620',
447
- * stop_reason: 'end_turn',
448
- * stop_sequence: null,
449
- * usage: { input_tokens: 25, output_tokens: 19 },
450
- * type: 'message',
451
- * role: 'assistant'
452
- * }
453
- * ```
454
- * </details>
455
- *
456
- * <br />
457
- */
458
- class ChatAnthropicMessages extends chat_models_1.BaseChatModel {
459
- static lc_name() {
460
- return "ChatAnthropic";
461
- }
462
- get lc_secrets() {
463
- return {
464
- anthropicApiKey: "ANTHROPIC_API_KEY",
465
- apiKey: "ANTHROPIC_API_KEY",
466
- };
467
- }
468
- get lc_aliases() {
469
- return {
470
- modelName: "model",
471
- };
472
- }
473
- constructor(fields) {
474
- super(fields ?? {});
475
- Object.defineProperty(this, "lc_serializable", {
476
- enumerable: true,
477
- configurable: true,
478
- writable: true,
479
- value: true
480
- });
481
- Object.defineProperty(this, "anthropicApiKey", {
482
- enumerable: true,
483
- configurable: true,
484
- writable: true,
485
- value: void 0
486
- });
487
- Object.defineProperty(this, "apiKey", {
488
- enumerable: true,
489
- configurable: true,
490
- writable: true,
491
- value: void 0
492
- });
493
- Object.defineProperty(this, "apiUrl", {
494
- enumerable: true,
495
- configurable: true,
496
- writable: true,
497
- value: void 0
498
- });
499
- Object.defineProperty(this, "temperature", {
500
- enumerable: true,
501
- configurable: true,
502
- writable: true,
503
- value: 1
504
- });
505
- Object.defineProperty(this, "topK", {
506
- enumerable: true,
507
- configurable: true,
508
- writable: true,
509
- value: -1
510
- });
511
- Object.defineProperty(this, "topP", {
512
- enumerable: true,
513
- configurable: true,
514
- writable: true,
515
- value: -1
516
- });
517
- Object.defineProperty(this, "maxTokens", {
518
- enumerable: true,
519
- configurable: true,
520
- writable: true,
521
- value: 2048
522
- });
523
- Object.defineProperty(this, "modelName", {
524
- enumerable: true,
525
- configurable: true,
526
- writable: true,
527
- value: "claude-2.1"
528
- });
529
- Object.defineProperty(this, "model", {
530
- enumerable: true,
531
- configurable: true,
532
- writable: true,
533
- value: "claude-2.1"
534
- });
535
- Object.defineProperty(this, "invocationKwargs", {
536
- enumerable: true,
537
- configurable: true,
538
- writable: true,
539
- value: void 0
540
- });
541
- Object.defineProperty(this, "stopSequences", {
542
- enumerable: true,
543
- configurable: true,
544
- writable: true,
545
- value: void 0
546
- });
547
- Object.defineProperty(this, "streaming", {
548
- enumerable: true,
549
- configurable: true,
550
- writable: true,
551
- value: false
552
- });
553
- Object.defineProperty(this, "clientOptions", {
554
- enumerable: true,
555
- configurable: true,
556
- writable: true,
557
- value: void 0
558
- });
559
- Object.defineProperty(this, "thinking", {
560
- enumerable: true,
561
- configurable: true,
562
- writable: true,
563
- value: { type: "disabled" }
564
- });
565
- Object.defineProperty(this, "contextManagement", {
566
- enumerable: true,
567
- configurable: true,
568
- writable: true,
569
- value: void 0
570
- });
571
- // Used for non-streaming requests
572
- Object.defineProperty(this, "batchClient", {
573
- enumerable: true,
574
- configurable: true,
575
- writable: true,
576
- value: void 0
577
- });
578
- // Used for streaming requests
579
- Object.defineProperty(this, "streamingClient", {
580
- enumerable: true,
581
- configurable: true,
582
- writable: true,
583
- value: void 0
584
- });
585
- Object.defineProperty(this, "streamUsage", {
586
- enumerable: true,
587
- configurable: true,
588
- writable: true,
589
- value: true
590
- });
591
- /**
592
- * Optional method that returns an initialized underlying Anthropic client.
593
- * Useful for accessing Anthropic models hosted on other cloud services
594
- * such as Google Vertex.
595
- */
596
- Object.defineProperty(this, "createClient", {
597
- enumerable: true,
598
- configurable: true,
599
- writable: true,
600
- value: void 0
601
- });
602
- this.anthropicApiKey =
603
- fields?.apiKey ??
604
- fields?.anthropicApiKey ??
605
- (0, env_1.getEnvironmentVariable)("ANTHROPIC_API_KEY");
606
- if (!this.anthropicApiKey && !fields?.createClient) {
607
- throw new Error("Anthropic API key not found");
608
- }
609
- this.clientOptions = fields?.clientOptions ?? {};
610
- /** Keep anthropicApiKey for backwards compatibility */
611
- this.apiKey = this.anthropicApiKey;
612
- // Support overriding the default API URL (i.e., https://api.anthropic.com)
613
- this.apiUrl = fields?.anthropicApiUrl;
614
- /** Keep modelName for backwards compatibility */
615
- this.modelName = fields?.model ?? fields?.modelName ?? this.model;
616
- this.model = this.modelName;
617
- this.invocationKwargs = fields?.invocationKwargs ?? {};
618
- // Default to `undefined` for `topP` for Opus 4.1 and Sonnet 4.5 models
619
- if (this.model.includes("opus-4-1") || this.model.includes("sonnet-4-5")) {
620
- this.topP = fields?.topP === null ? undefined : fields?.topP;
621
- }
622
- else {
623
- this.topP = fields?.topP ?? this.topP;
624
- }
625
- // If the user passes `null`, set it to `undefined`. Otherwise, use their value or the default. We have to check for null, because
626
- // there's no way for us to know if they explicitly set it to `undefined`, or never passed a value
627
- this.temperature =
628
- fields?.temperature === null
629
- ? undefined
630
- : fields?.temperature ?? this.temperature;
631
- this.topK = fields?.topK ?? this.topK;
632
- this.maxTokens =
633
- fields?.maxTokensToSample ?? fields?.maxTokens ?? this.maxTokens;
634
- this.stopSequences = fields?.stopSequences ?? this.stopSequences;
635
- this.streaming = fields?.streaming ?? false;
636
- this.streamUsage = fields?.streamUsage ?? this.streamUsage;
637
- this.thinking = fields?.thinking ?? this.thinking;
638
- this.contextManagement =
639
- fields?.contextManagement ?? this.contextManagement;
640
- this.createClient =
641
- fields?.createClient ??
642
- ((options) => new sdk_1.Anthropic(options));
643
- }
644
- getLsParams(options) {
645
- const params = this.invocationParams(options);
646
- return {
647
- ls_provider: "anthropic",
648
- ls_model_name: this.model,
649
- ls_model_type: "chat",
650
- ls_temperature: params.temperature ?? undefined,
651
- ls_max_tokens: params.max_tokens ?? undefined,
652
- ls_stop: options.stop,
653
- };
654
- }
655
- /**
656
- * Formats LangChain StructuredTools to AnthropicTools.
657
- *
658
- * @param {ChatAnthropicCallOptions["tools"]} tools The tools to format
659
- * @returns {AnthropicTool[] | undefined} The formatted tools, or undefined if none are passed.
660
- */
661
- formatStructuredToolToAnthropic(tools) {
662
- if (!tools || !tools.length) {
663
- return undefined;
664
- }
665
- return tools.map((tool) => {
666
- if (isBuiltinTool(tool)) {
667
- return tool;
668
- }
669
- if (isAnthropicTool(tool)) {
670
- return tool;
671
- }
672
- if ((0, base_1.isOpenAITool)(tool)) {
673
- return {
674
- name: tool.function.name,
675
- description: tool.function.description,
676
- input_schema: tool.function
677
- .parameters,
678
- };
679
- }
680
- if ((0, function_calling_1.isLangChainTool)(tool)) {
681
- return {
682
- name: tool.name,
683
- description: tool.description,
684
- input_schema: ((0, types_1.isInteropZodSchema)(tool.schema)
685
- ? (0, json_schema_1.toJsonSchema)(tool.schema)
686
- : tool.schema),
687
- };
688
- }
689
- throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(tool, null, 2)}`);
690
- });
691
- }
692
- bindTools(tools, kwargs) {
693
- return this.withConfig({
694
- tools: this.formatStructuredToolToAnthropic(tools),
695
- ...kwargs,
696
- });
697
- }
698
- /**
699
- * Get the parameters used to invoke the model
700
- */
701
- invocationParams(options) {
702
- const tool_choice = (0, tools_js_1.handleToolChoice)(options?.tool_choice);
703
- if (this.thinking.type === "enabled") {
704
- if (this.topK !== -1) {
705
- throw new Error("topK is not supported when thinking is enabled");
706
- }
707
- if (this.model.includes("opus-4-1") || this.model.includes("sonnet-4-5")
708
- ? this.topP !== undefined
709
- : this.topP !== -1) {
710
- throw new Error("topP is not supported when thinking is enabled");
711
- }
712
- if (this.temperature !== 1) {
713
- throw new Error("temperature is not supported when thinking is enabled");
714
- }
715
- return {
716
- model: this.model,
717
- stop_sequences: options?.stop ?? this.stopSequences,
718
- stream: this.streaming,
719
- max_tokens: this.maxTokens,
720
- tools: this.formatStructuredToolToAnthropic(options?.tools),
721
- tool_choice,
722
- thinking: this.thinking,
723
- ...this.invocationKwargs,
724
- };
725
- }
726
- return {
727
- model: this.model,
728
- temperature: this.temperature,
729
- top_k: this.topK,
730
- top_p: this.topP,
731
- stop_sequences: options?.stop ?? this.stopSequences,
732
- stream: this.streaming,
733
- max_tokens: this.maxTokens,
734
- tools: this.formatStructuredToolToAnthropic(options?.tools),
735
- tool_choice,
736
- thinking: this.thinking,
737
- context_management: this.contextManagement,
738
- ...this.invocationKwargs,
739
- };
740
- }
741
- /** @ignore */
742
- _identifyingParams() {
743
- return {
744
- model_name: this.model,
745
- ...this.invocationParams(),
746
- };
747
- }
748
- /**
749
- * Get the identifying parameters for the model
750
- */
751
- identifyingParams() {
752
- return {
753
- model_name: this.model,
754
- ...this.invocationParams(),
755
- };
756
- }
757
- async *_streamResponseChunks(messages, options, runManager) {
758
- const params = this.invocationParams(options);
759
- const formattedMessages = (0, message_inputs_js_1._convertMessagesToAnthropicPayload)(messages);
760
- const payload = {
761
- ...params,
762
- ...formattedMessages,
763
- stream: true,
764
- };
765
- const coerceContentToString = !_toolsInParams(payload) &&
766
- !_documentsInParams(payload) &&
767
- !_thinkingInParams(payload);
768
- const stream = await this.createStreamWithRetry(payload, {
769
- headers: options.headers,
770
- });
771
- for await (const data of stream) {
772
- if (options.signal?.aborted) {
773
- stream.controller.abort();
774
- throw new Error("AbortError: User aborted the request.");
775
- }
776
- const shouldStreamUsage = this.streamUsage ?? options.streamUsage;
777
- const result = (0, message_outputs_js_1._makeMessageChunkFromAnthropicEvent)(data, {
778
- streamUsage: shouldStreamUsage,
779
- coerceContentToString,
780
- });
781
- if (!result)
782
- continue;
783
- const { chunk } = result;
784
- // Extract the text content token for text field and runManager.
785
- const token = extractToken(chunk);
786
- const generationChunk = new outputs_1.ChatGenerationChunk({
787
- message: new messages_1.AIMessageChunk({
788
- // Just yield chunk as it is and tool_use will be concat by BaseChatModel._generateUncached().
789
- content: chunk.content,
790
- additional_kwargs: chunk.additional_kwargs,
791
- tool_call_chunks: chunk.tool_call_chunks,
792
- usage_metadata: shouldStreamUsage ? chunk.usage_metadata : undefined,
793
- response_metadata: chunk.response_metadata,
794
- id: chunk.id,
795
- }),
796
- text: token ?? "",
797
- });
798
- yield generationChunk;
799
- await runManager?.handleLLMNewToken(token ?? "", undefined, undefined, undefined, undefined, { chunk: generationChunk });
800
- }
801
- }
802
- /** @ignore */
803
- async _generateNonStreaming(messages, params, requestOptions) {
804
- const response = await this.completionWithRetry({
805
- ...params,
806
- stream: false,
807
- ...(0, message_inputs_js_1._convertMessagesToAnthropicPayload)(messages),
808
- }, requestOptions);
809
- const { content, ...additionalKwargs } = response;
810
- const generations = (0, message_outputs_js_1.anthropicResponseToChatMessages)(content, additionalKwargs);
811
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
812
- const { role: _role, type: _type, ...rest } = additionalKwargs;
813
- return { generations, llmOutput: rest };
814
- }
815
- /** @ignore */
816
- async _generate(messages, options, runManager) {
817
- if (this.stopSequences && options.stop) {
818
- throw new Error(`"stopSequence" parameter found in input and default params`);
819
- }
820
- const params = this.invocationParams(options);
821
- if (params.stream) {
822
- let finalChunk;
823
- const stream = this._streamResponseChunks(messages, options, runManager);
824
- for await (const chunk of stream) {
825
- if (finalChunk === undefined) {
826
- finalChunk = chunk;
827
- }
828
- else {
829
- finalChunk = finalChunk.concat(chunk);
830
- }
831
- }
832
- if (finalChunk === undefined) {
833
- throw new Error("No chunks returned from Anthropic API.");
834
- }
835
- return {
836
- generations: [
837
- {
838
- text: finalChunk.text,
839
- message: finalChunk.message,
840
- },
841
- ],
842
- };
843
- }
844
- else {
845
- return this._generateNonStreaming(messages, params, {
846
- signal: options.signal,
847
- headers: options.headers,
848
- });
849
- }
850
- }
851
- /**
852
- * Creates a streaming request with retry.
853
- * @param request The parameters for creating a completion.
854
- * @param options
855
- * @returns A streaming request.
856
- */
857
- async createStreamWithRetry(request, options) {
858
- if (!this.streamingClient) {
859
- const options_ = this.apiUrl ? { baseURL: this.apiUrl } : undefined;
860
- this.streamingClient = this.createClient({
861
- dangerouslyAllowBrowser: true,
862
- ...this.clientOptions,
863
- ...options_,
864
- apiKey: this.apiKey,
865
- // Prefer LangChain built-in retries
866
- maxRetries: 0,
867
- });
868
- }
869
- const makeCompletionRequest = async () => {
870
- try {
871
- return await this.streamingClient.messages.create({
872
- ...request,
873
- ...this.invocationKwargs,
874
- stream: true,
875
- }, options);
876
- }
877
- catch (e) {
878
- const error = (0, errors_js_1.wrapAnthropicClientError)(e);
879
- throw error;
880
- }
881
- };
882
- return this.caller.call(makeCompletionRequest);
883
- }
884
- /** @ignore */
885
- async completionWithRetry(request, options) {
886
- if (!this.batchClient) {
887
- const options = this.apiUrl ? { baseURL: this.apiUrl } : undefined;
888
- this.batchClient = this.createClient({
889
- dangerouslyAllowBrowser: true,
890
- ...this.clientOptions,
891
- ...options,
892
- apiKey: this.apiKey,
893
- maxRetries: 0,
894
- });
895
- }
896
- const makeCompletionRequest = async () => {
897
- try {
898
- return await this.batchClient.messages.create({
899
- ...request,
900
- ...this.invocationKwargs,
901
- }, options);
902
- }
903
- catch (e) {
904
- const error = (0, errors_js_1.wrapAnthropicClientError)(e);
905
- throw error;
906
- }
907
- };
908
- return this.caller.callWithOptions({ signal: options.signal ?? undefined }, makeCompletionRequest);
909
- }
910
- _llmType() {
911
- return "anthropic";
912
- }
913
- withStructuredOutput(outputSchema, config) {
914
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
915
- const schema = outputSchema;
916
- const name = config?.name;
917
- const method = config?.method;
918
- const includeRaw = config?.includeRaw;
919
- if (method === "jsonMode") {
920
- throw new Error(`Anthropic only supports "functionCalling" as a method.`);
921
- }
922
- let functionName = name ?? "extract";
923
- let outputParser;
924
- let tools;
925
- if ((0, types_1.isInteropZodSchema)(schema)) {
926
- const jsonSchema = (0, json_schema_1.toJsonSchema)(schema);
927
- tools = [
928
- {
929
- name: functionName,
930
- description: jsonSchema.description ?? "A function available to call.",
931
- input_schema: jsonSchema,
932
- },
933
- ];
934
- outputParser = new output_parsers_js_1.AnthropicToolsOutputParser({
935
- returnSingle: true,
936
- keyName: functionName,
937
- zodSchema: schema,
938
- });
939
- }
940
- else {
941
- let anthropicTools;
942
- if (typeof schema.name === "string" &&
943
- typeof schema.description === "string" &&
944
- typeof schema.input_schema === "object" &&
945
- schema.input_schema != null) {
946
- anthropicTools = schema;
947
- functionName = schema.name;
948
- }
949
- else {
950
- anthropicTools = {
951
- name: functionName,
952
- description: schema.description ?? "",
953
- input_schema: schema,
954
- };
955
- }
956
- tools = [anthropicTools];
957
- outputParser = new output_parsers_js_1.AnthropicToolsOutputParser({
958
- returnSingle: true,
959
- keyName: functionName,
960
- });
961
- }
962
- let llm;
963
- if (this.thinking?.type === "enabled") {
964
- const thinkingAdmonition = "Anthropic structured output relies on forced tool calling, " +
965
- "which is not supported when `thinking` is enabled. This method will raise " +
966
- "OutputParserException if tool calls are not " +
967
- "generated. Consider disabling `thinking` or adjust your prompt to ensure " +
968
- "the tool is called.";
969
- console.warn(thinkingAdmonition);
970
- llm = this.withConfig({
971
- tools,
972
- ls_structured_output_format: {
973
- kwargs: { method: "functionCalling" },
974
- schema: (0, json_schema_1.toJsonSchema)(schema),
975
- },
976
- });
977
- const raiseIfNoToolCalls = (message) => {
978
- if (!message.tool_calls || message.tool_calls.length === 0) {
979
- throw new Error(thinkingAdmonition);
980
- }
981
- return message;
982
- };
983
- llm = llm.pipe(raiseIfNoToolCalls);
984
- }
985
- else {
986
- llm = this.withConfig({
987
- tools,
988
- tool_choice: {
989
- type: "tool",
990
- name: functionName,
991
- },
992
- ls_structured_output_format: {
993
- kwargs: { method: "functionCalling" },
994
- schema: (0, json_schema_1.toJsonSchema)(schema),
995
- },
996
- });
997
- }
998
- if (!includeRaw) {
999
- return llm.pipe(outputParser).withConfig({
1000
- runName: "ChatAnthropicStructuredOutput",
1001
- });
1002
- }
1003
- const parserAssign = runnables_1.RunnablePassthrough.assign({
1004
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1005
- parsed: (input, config) => outputParser.invoke(input.raw, config),
1006
- });
1007
- const parserNone = runnables_1.RunnablePassthrough.assign({
1008
- parsed: () => null,
1009
- });
1010
- const parsedWithFallback = parserAssign.withFallbacks({
1011
- fallbacks: [parserNone],
1012
- });
1013
- return runnables_1.RunnableSequence.from([
1014
- {
1015
- raw: llm,
1016
- },
1017
- parsedWithFallback,
1018
- ]).withConfig({
1019
- runName: "StructuredOutputRunnable",
1020
- });
1021
- }
1022
- }
1023
- exports.ChatAnthropicMessages = ChatAnthropicMessages;
1024
- class ChatAnthropic extends ChatAnthropicMessages {
1025
- }
56
+ * Anthropic chat model integration.
57
+ *
58
+ * Setup:
59
+ * Install `@langchain/anthropic` and set an environment variable named `ANTHROPIC_API_KEY`.
60
+ *
61
+ * ```bash
62
+ * npm install @langchain/anthropic
63
+ * export ANTHROPIC_API_KEY="your-api-key"
64
+ * ```
65
+ *
66
+ * ## [Constructor args](https://api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html#constructor)
67
+ *
68
+ * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_anthropic.ChatAnthropicCallOptions.html)
69
+ *
70
+ * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.
71
+ * They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below:
72
+ *
73
+ * ```typescript
74
+ * // When calling `.bind`, call options should be passed via the first argument
75
+ * const llmWithArgsBound = llm.bindTools([...]).withConfig({
76
+ * stop: ["\n"],
77
+ * });
78
+ *
79
+ * // When calling `.bindTools`, call options should be passed via the second argument
80
+ * const llmWithTools = llm.bindTools(
81
+ * [...],
82
+ * {
83
+ * tool_choice: "auto",
84
+ * }
85
+ * );
86
+ * ```
87
+ *
88
+ * ## Examples
89
+ *
90
+ * <details open>
91
+ * <summary><strong>Instantiate</strong></summary>
92
+ *
93
+ * ```typescript
94
+ * import { ChatAnthropic } from '@langchain/anthropic';
95
+ *
96
+ * const llm = new ChatAnthropic({
97
+ * model: "claude-3-5-sonnet-20240620",
98
+ * temperature: 0,
99
+ * maxTokens: undefined,
100
+ * maxRetries: 2,
101
+ * // apiKey: "...",
102
+ * // baseUrl: "...",
103
+ * // other params...
104
+ * });
105
+ * ```
106
+ * </details>
107
+ *
108
+ * <br />
109
+ *
110
+ * <details>
111
+ * <summary><strong>Invoking</strong></summary>
112
+ *
113
+ * ```typescript
114
+ * const input = `Translate "I love programming" into French.`;
115
+ *
116
+ * // Models also accept a list of chat messages or a formatted prompt
117
+ * const result = await llm.invoke(input);
118
+ * console.log(result);
119
+ * ```
120
+ *
121
+ * ```txt
122
+ * AIMessage {
123
+ * "id": "msg_01QDpd78JUHpRP6bRRNyzbW3",
124
+ * "content": "Here's the translation to French:\n\nJ'adore la programmation.",
125
+ * "response_metadata": {
126
+ * "id": "msg_01QDpd78JUHpRP6bRRNyzbW3",
127
+ * "model": "claude-3-5-sonnet-20240620",
128
+ * "stop_reason": "end_turn",
129
+ * "stop_sequence": null,
130
+ * "usage": {
131
+ * "input_tokens": 25,
132
+ * "output_tokens": 19
133
+ * },
134
+ * "type": "message",
135
+ * "role": "assistant"
136
+ * },
137
+ * "usage_metadata": {
138
+ * "input_tokens": 25,
139
+ * "output_tokens": 19,
140
+ * "total_tokens": 44
141
+ * }
142
+ * }
143
+ * ```
144
+ * </details>
145
+ *
146
+ * <br />
147
+ *
148
+ * <details>
149
+ * <summary><strong>Streaming Chunks</strong></summary>
150
+ *
151
+ * ```typescript
152
+ * for await (const chunk of await llm.stream(input)) {
153
+ * console.log(chunk);
154
+ * }
155
+ * ```
156
+ *
157
+ * ```txt
158
+ * AIMessageChunk {
159
+ * "id": "msg_01N8MwoYxiKo9w4chE4gXUs4",
160
+ * "content": "",
161
+ * "additional_kwargs": {
162
+ * "id": "msg_01N8MwoYxiKo9w4chE4gXUs4",
163
+ * "type": "message",
164
+ * "role": "assistant",
165
+ * "model": "claude-3-5-sonnet-20240620"
166
+ * },
167
+ * "usage_metadata": {
168
+ * "input_tokens": 25,
169
+ * "output_tokens": 1,
170
+ * "total_tokens": 26
171
+ * }
172
+ * }
173
+ * AIMessageChunk {
174
+ * "content": "",
175
+ * }
176
+ * AIMessageChunk {
177
+ * "content": "Here",
178
+ * }
179
+ * AIMessageChunk {
180
+ * "content": "'s",
181
+ * }
182
+ * AIMessageChunk {
183
+ * "content": " the translation to",
184
+ * }
185
+ * AIMessageChunk {
186
+ * "content": " French:\n\nJ",
187
+ * }
188
+ * AIMessageChunk {
189
+ * "content": "'adore la programmation",
190
+ * }
191
+ * AIMessageChunk {
192
+ * "content": ".",
193
+ * }
194
+ * AIMessageChunk {
195
+ * "content": "",
196
+ * "additional_kwargs": {
197
+ * "stop_reason": "end_turn",
198
+ * "stop_sequence": null
199
+ * },
200
+ * "usage_metadata": {
201
+ * "input_tokens": 0,
202
+ * "output_tokens": 19,
203
+ * "total_tokens": 19
204
+ * }
205
+ * }
206
+ * ```
207
+ * </details>
208
+ *
209
+ * <br />
210
+ *
211
+ * <details>
212
+ * <summary><strong>Aggregate Streamed Chunks</strong></summary>
213
+ *
214
+ * ```typescript
215
+ * import { AIMessageChunk } from '@langchain/core/messages';
216
+ * import { concat } from '@langchain/core/utils/stream';
217
+ *
218
+ * const stream = await llm.stream(input);
219
+ * let full: AIMessageChunk | undefined;
220
+ * for await (const chunk of stream) {
221
+ * full = !full ? chunk : concat(full, chunk);
222
+ * }
223
+ * console.log(full);
224
+ * ```
225
+ *
226
+ * ```txt
227
+ * AIMessageChunk {
228
+ * "id": "msg_01SBTb5zSGXfjUc7yQ8EKEEA",
229
+ * "content": "Here's the translation to French:\n\nJ'adore la programmation.",
230
+ * "additional_kwargs": {
231
+ * "id": "msg_01SBTb5zSGXfjUc7yQ8EKEEA",
232
+ * "type": "message",
233
+ * "role": "assistant",
234
+ * "model": "claude-3-5-sonnet-20240620",
235
+ * "stop_reason": "end_turn",
236
+ * "stop_sequence": null
237
+ * },
238
+ * "usage_metadata": {
239
+ * "input_tokens": 25,
240
+ * "output_tokens": 20,
241
+ * "total_tokens": 45
242
+ * }
243
+ * }
244
+ * ```
245
+ * </details>
246
+ *
247
+ * <br />
248
+ *
249
+ * <details>
250
+ * <summary><strong>Bind tools</strong></summary>
251
+ *
252
+ * ```typescript
253
+ * import { z } from 'zod';
254
+ *
255
+ * const GetWeather = {
256
+ * name: "GetWeather",
257
+ * description: "Get the current weather in a given location",
258
+ * schema: z.object({
259
+ * location: z.string().describe("The city and state, e.g. San Francisco, CA")
260
+ * }),
261
+ * }
262
+ *
263
+ * const GetPopulation = {
264
+ * name: "GetPopulation",
265
+ * description: "Get the current population in a given location",
266
+ * schema: z.object({
267
+ * location: z.string().describe("The city and state, e.g. San Francisco, CA")
268
+ * }),
269
+ * }
270
+ *
271
+ * const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);
272
+ * const aiMsg = await llmWithTools.invoke(
273
+ * "Which city is hotter today and which is bigger: LA or NY?"
274
+ * );
275
+ * console.log(aiMsg.tool_calls);
276
+ * ```
277
+ *
278
+ * ```txt
279
+ * [
280
+ * {
281
+ * name: 'GetWeather',
282
+ * args: { location: 'Los Angeles, CA' },
283
+ * id: 'toolu_01WjW3Dann6BPJVtLhovdBD5',
284
+ * type: 'tool_call'
285
+ * },
286
+ * {
287
+ * name: 'GetWeather',
288
+ * args: { location: 'New York, NY' },
289
+ * id: 'toolu_01G6wfJgqi5zRmJomsmkyZXe',
290
+ * type: 'tool_call'
291
+ * },
292
+ * {
293
+ * name: 'GetPopulation',
294
+ * args: { location: 'Los Angeles, CA' },
295
+ * id: 'toolu_0165qYWBA2VFyUst5RA18zew',
296
+ * type: 'tool_call'
297
+ * },
298
+ * {
299
+ * name: 'GetPopulation',
300
+ * args: { location: 'New York, NY' },
301
+ * id: 'toolu_01PGNyP33vxr13tGqr7i3rDo',
302
+ * type: 'tool_call'
303
+ * }
304
+ * ]
305
+ * ```
306
+ * </details>
307
+ *
308
+ * <br />
309
+ *
310
+ * <details>
311
+ * <summary><strong>Structured Output</strong></summary>
312
+ *
313
+ * ```typescript
314
+ * import { z } from 'zod';
315
+ *
316
+ * const Joke = z.object({
317
+ * setup: z.string().describe("The setup of the joke"),
318
+ * punchline: z.string().describe("The punchline to the joke"),
319
+ * rating: z.number().optional().describe("How funny the joke is, from 1 to 10")
320
+ * }).describe('Joke to tell user.');
321
+ *
322
+ * const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" });
323
+ * const jokeResult = await structuredLlm.invoke("Tell me a joke about cats");
324
+ * console.log(jokeResult);
325
+ * ```
326
+ *
327
+ * ```txt
328
+ * {
329
+ * setup: "Why don't cats play poker in the jungle?",
330
+ * punchline: 'Too many cheetahs!',
331
+ * rating: 7
332
+ * }
333
+ * ```
334
+ * </details>
335
+ *
336
+ * <br />
337
+ *
338
+ * <details>
339
+ * <summary><strong>Multimodal</strong></summary>
340
+ *
341
+ * ```typescript
342
+ * import { HumanMessage } from '@langchain/core/messages';
343
+ *
344
+ * const imageUrl = "https://example.com/image.jpg";
345
+ * const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());
346
+ * const base64Image = Buffer.from(imageData).toString('base64');
347
+ *
348
+ * const message = new HumanMessage({
349
+ * content: [
350
+ * { type: "text", text: "describe the weather in this image" },
351
+ * {
352
+ * type: "image_url",
353
+ * image_url: { url: `data:image/jpeg;base64,${base64Image}` },
354
+ * },
355
+ * ]
356
+ * });
357
+ *
358
+ * const imageDescriptionAiMsg = await llm.invoke([message]);
359
+ * console.log(imageDescriptionAiMsg.content);
360
+ * ```
361
+ *
362
+ * ```txt
363
+ * The weather in this image appears to be beautiful and clear. The sky is a vibrant blue with scattered white clouds, suggesting a sunny and pleasant day. The clouds are wispy and light, indicating calm conditions without any signs of storms or heavy weather. The bright green grass on the rolling hills looks lush and well-watered, which could mean recent rainfall or good growing conditions. Overall, the scene depicts a perfect spring or early summer day with mild temperatures, plenty of sunshine, and gentle breezes - ideal weather for enjoying the outdoors or for plant growth.
364
+ * ```
365
+ * </details>
366
+ *
367
+ * <br />
368
+ *
369
+ * <details>
370
+ * <summary><strong>Usage Metadata</strong></summary>
371
+ *
372
+ * ```typescript
373
+ * const aiMsgForMetadata = await llm.invoke(input);
374
+ * console.log(aiMsgForMetadata.usage_metadata);
375
+ * ```
376
+ *
377
+ * ```txt
378
+ * { input_tokens: 25, output_tokens: 19, total_tokens: 44 }
379
+ * ```
380
+ * </details>
381
+ *
382
+ * <br />
383
+ *
384
+ * <details>
385
+ * <summary><strong>Stream Usage Metadata</strong></summary>
386
+ *
387
+ * ```typescript
388
+ * const streamForMetadata = await llm.stream(
389
+ * input,
390
+ * {
391
+ * streamUsage: true
392
+ * }
393
+ * );
394
+ * let fullForMetadata: AIMessageChunk | undefined;
395
+ * for await (const chunk of streamForMetadata) {
396
+ * fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk);
397
+ * }
398
+ * console.log(fullForMetadata?.usage_metadata);
399
+ * ```
400
+ *
401
+ * ```txt
402
+ * { input_tokens: 25, output_tokens: 20, total_tokens: 45 }
403
+ * ```
404
+ * </details>
405
+ *
406
+ * <br />
407
+ *
408
+ * <details>
409
+ * <summary><strong>Response Metadata</strong></summary>
410
+ *
411
+ * ```typescript
412
+ * const aiMsgForResponseMetadata = await llm.invoke(input);
413
+ * console.log(aiMsgForResponseMetadata.response_metadata);
414
+ * ```
415
+ *
416
+ * ```txt
417
+ * {
418
+ * id: 'msg_01STxeQxJmp4sCSpioD6vK3L',
419
+ * model: 'claude-3-5-sonnet-20240620',
420
+ * stop_reason: 'end_turn',
421
+ * stop_sequence: null,
422
+ * usage: { input_tokens: 25, output_tokens: 19 },
423
+ * type: 'message',
424
+ * role: 'assistant'
425
+ * }
426
+ * ```
427
+ * </details>
428
+ *
429
+ * <br />
430
+ */
431
+ var ChatAnthropicMessages = class extends __langchain_core_language_models_chat_models.BaseChatModel {
432
+ static lc_name() {
433
+ return "ChatAnthropic";
434
+ }
435
+ get lc_secrets() {
436
+ return {
437
+ anthropicApiKey: "ANTHROPIC_API_KEY",
438
+ apiKey: "ANTHROPIC_API_KEY"
439
+ };
440
+ }
441
+ get lc_aliases() {
442
+ return { modelName: "model" };
443
+ }
444
+ lc_serializable = true;
445
+ anthropicApiKey;
446
+ apiKey;
447
+ apiUrl;
448
+ temperature = 1;
449
+ topK = -1;
450
+ topP = -1;
451
+ maxTokens = 2048;
452
+ modelName = "claude-2.1";
453
+ model = "claude-2.1";
454
+ invocationKwargs;
455
+ stopSequences;
456
+ streaming = false;
457
+ clientOptions;
458
+ thinking = { type: "disabled" };
459
+ contextManagement;
460
+ batchClient;
461
+ streamingClient;
462
+ streamUsage = true;
463
+ /**
464
+ * Optional method that returns an initialized underlying Anthropic client.
465
+ * Useful for accessing Anthropic models hosted on other cloud services
466
+ * such as Google Vertex.
467
+ */
468
+ createClient;
469
+ constructor(fields) {
470
+ super(fields ?? {});
471
+ this.anthropicApiKey = fields?.apiKey ?? fields?.anthropicApiKey ?? (0, __langchain_core_utils_env.getEnvironmentVariable)("ANTHROPIC_API_KEY");
472
+ if (!this.anthropicApiKey && !fields?.createClient) throw new Error("Anthropic API key not found");
473
+ this.clientOptions = fields?.clientOptions ?? {};
474
+ /** Keep anthropicApiKey for backwards compatibility */
475
+ this.apiKey = this.anthropicApiKey;
476
+ this.apiUrl = fields?.anthropicApiUrl;
477
+ /** Keep modelName for backwards compatibility */
478
+ this.modelName = fields?.model ?? fields?.modelName ?? this.model;
479
+ this.model = this.modelName;
480
+ this.invocationKwargs = fields?.invocationKwargs ?? {};
481
+ if (this.model.includes("opus-4-1") || this.model.includes("sonnet-4-5")) this.topP = fields?.topP === null ? void 0 : fields?.topP;
482
+ else this.topP = fields?.topP ?? this.topP;
483
+ this.temperature = fields?.temperature === null ? void 0 : fields?.temperature ?? this.temperature;
484
+ this.topK = fields?.topK ?? this.topK;
485
+ this.maxTokens = fields?.maxTokens ?? this.maxTokens;
486
+ this.stopSequences = fields?.stopSequences ?? this.stopSequences;
487
+ this.streaming = fields?.streaming ?? false;
488
+ this.streamUsage = fields?.streamUsage ?? this.streamUsage;
489
+ this.thinking = fields?.thinking ?? this.thinking;
490
+ this.contextManagement = fields?.contextManagement ?? this.contextManagement;
491
+ this.createClient = fields?.createClient ?? ((options) => new __anthropic_ai_sdk.Anthropic(options));
492
+ }
493
+ getLsParams(options) {
494
+ const params = this.invocationParams(options);
495
+ return {
496
+ ls_provider: "anthropic",
497
+ ls_model_name: this.model,
498
+ ls_model_type: "chat",
499
+ ls_temperature: params.temperature ?? void 0,
500
+ ls_max_tokens: params.max_tokens ?? void 0,
501
+ ls_stop: options.stop
502
+ };
503
+ }
504
+ /**
505
+ * Formats LangChain StructuredTools to AnthropicTools.
506
+ *
507
+ * @param {ChatAnthropicCallOptions["tools"]} tools The tools to format
508
+ * @returns {AnthropicTool[] | undefined} The formatted tools, or undefined if none are passed.
509
+ */
510
+ formatStructuredToolToAnthropic(tools) {
511
+ if (!tools || !tools.length) return void 0;
512
+ return tools.map((tool) => {
513
+ if (isBuiltinTool(tool)) return tool;
514
+ if (isAnthropicTool(tool)) return tool;
515
+ if ((0, __langchain_core_language_models_base.isOpenAITool)(tool)) return {
516
+ name: tool.function.name,
517
+ description: tool.function.description,
518
+ input_schema: tool.function.parameters
519
+ };
520
+ if ((0, __langchain_core_utils_function_calling.isLangChainTool)(tool)) return {
521
+ name: tool.name,
522
+ description: tool.description,
523
+ input_schema: (0, __langchain_core_utils_types.isInteropZodSchema)(tool.schema) ? (0, __langchain_core_utils_json_schema.toJsonSchema)(tool.schema) : tool.schema
524
+ };
525
+ throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(tool, null, 2)}`);
526
+ });
527
+ }
528
+ bindTools(tools, kwargs) {
529
+ return this.withConfig({
530
+ tools: this.formatStructuredToolToAnthropic(tools),
531
+ ...kwargs
532
+ });
533
+ }
534
+ /**
535
+ * Get the parameters used to invoke the model
536
+ */
537
+ invocationParams(options) {
538
+ const tool_choice = require_tools.handleToolChoice(options?.tool_choice);
539
+ if (this.thinking.type === "enabled") {
540
+ if (this.topK !== -1) throw new Error("topK is not supported when thinking is enabled");
541
+ if (this.model.includes("opus-4-1") || this.model.includes("sonnet-4-5") ? this.topP !== void 0 : this.topP !== -1) throw new Error("topP is not supported when thinking is enabled");
542
+ if (this.temperature !== 1) throw new Error("temperature is not supported when thinking is enabled");
543
+ return {
544
+ model: this.model,
545
+ stop_sequences: options?.stop ?? this.stopSequences,
546
+ stream: this.streaming,
547
+ max_tokens: this.maxTokens,
548
+ tools: this.formatStructuredToolToAnthropic(options?.tools),
549
+ tool_choice,
550
+ thinking: this.thinking,
551
+ context_management: this.contextManagement,
552
+ ...this.invocationKwargs,
553
+ container: options?.container
554
+ };
555
+ }
556
+ return {
557
+ model: this.model,
558
+ temperature: this.temperature,
559
+ top_k: this.topK,
560
+ top_p: this.topP,
561
+ stop_sequences: options?.stop ?? this.stopSequences,
562
+ stream: this.streaming,
563
+ max_tokens: this.maxTokens,
564
+ tools: this.formatStructuredToolToAnthropic(options?.tools),
565
+ tool_choice,
566
+ thinking: this.thinking,
567
+ context_management: this.contextManagement,
568
+ ...this.invocationKwargs,
569
+ container: options?.container
570
+ };
571
+ }
572
+ /** @ignore */
573
+ _identifyingParams() {
574
+ return {
575
+ model_name: this.model,
576
+ ...this.invocationParams()
577
+ };
578
+ }
579
+ /**
580
+ * Get the identifying parameters for the model
581
+ */
582
+ identifyingParams() {
583
+ return {
584
+ model_name: this.model,
585
+ ...this.invocationParams()
586
+ };
587
+ }
588
+ async *_streamResponseChunks(messages, options, runManager) {
589
+ const params = this.invocationParams(options);
590
+ const formattedMessages = require_message_inputs._convertMessagesToAnthropicPayload(messages);
591
+ const payload = {
592
+ ...params,
593
+ ...formattedMessages,
594
+ stream: true
595
+ };
596
+ const coerceContentToString = !_toolsInParams(payload) && !_documentsInParams(payload) && !_thinkingInParams(payload);
597
+ const stream = await this.createStreamWithRetry(payload, { headers: options.headers });
598
+ for await (const data of stream) {
599
+ if (options.signal?.aborted) {
600
+ stream.controller.abort();
601
+ throw new Error("AbortError: User aborted the request.");
602
+ }
603
+ const shouldStreamUsage = this.streamUsage ?? options.streamUsage;
604
+ const result = require_message_outputs._makeMessageChunkFromAnthropicEvent(data, {
605
+ streamUsage: shouldStreamUsage,
606
+ coerceContentToString
607
+ });
608
+ if (!result) continue;
609
+ const { chunk } = result;
610
+ const token = extractToken(chunk);
611
+ const generationChunk = new __langchain_core_outputs.ChatGenerationChunk({
612
+ message: new __langchain_core_messages.AIMessageChunk({
613
+ content: chunk.content,
614
+ additional_kwargs: chunk.additional_kwargs,
615
+ tool_call_chunks: chunk.tool_call_chunks,
616
+ usage_metadata: shouldStreamUsage ? chunk.usage_metadata : void 0,
617
+ response_metadata: chunk.response_metadata,
618
+ id: chunk.id
619
+ }),
620
+ text: token ?? ""
621
+ });
622
+ yield generationChunk;
623
+ await runManager?.handleLLMNewToken(token ?? "", void 0, void 0, void 0, void 0, { chunk: generationChunk });
624
+ }
625
+ }
626
+ /** @ignore */
627
+ async _generateNonStreaming(messages, params, requestOptions) {
628
+ const response = await this.completionWithRetry({
629
+ ...params,
630
+ stream: false,
631
+ ...require_message_inputs._convertMessagesToAnthropicPayload(messages)
632
+ }, requestOptions);
633
+ const { content,...additionalKwargs } = response;
634
+ const generations = require_message_outputs.anthropicResponseToChatMessages(content, additionalKwargs);
635
+ const { role: _role, type: _type,...rest } = additionalKwargs;
636
+ return {
637
+ generations,
638
+ llmOutput: rest
639
+ };
640
+ }
641
+ /** @ignore */
642
+ async _generate(messages, options, runManager) {
643
+ if (this.stopSequences && options.stop) throw new Error(`"stopSequence" parameter found in input and default params`);
644
+ const params = this.invocationParams(options);
645
+ if (params.stream) {
646
+ let finalChunk;
647
+ const stream = this._streamResponseChunks(messages, options, runManager);
648
+ for await (const chunk of stream) if (finalChunk === void 0) finalChunk = chunk;
649
+ else finalChunk = finalChunk.concat(chunk);
650
+ if (finalChunk === void 0) throw new Error("No chunks returned from Anthropic API.");
651
+ return { generations: [{
652
+ text: finalChunk.text,
653
+ message: finalChunk.message
654
+ }] };
655
+ } else return this._generateNonStreaming(messages, params, {
656
+ signal: options.signal,
657
+ headers: options.headers
658
+ });
659
+ }
660
+ /**
661
+ * Creates a streaming request with retry.
662
+ * @param request The parameters for creating a completion.
663
+ * @param options
664
+ * @returns A streaming request.
665
+ */
666
+ async createStreamWithRetry(request, options) {
667
+ if (!this.streamingClient) {
668
+ const options_ = this.apiUrl ? { baseURL: this.apiUrl } : void 0;
669
+ this.streamingClient = this.createClient({
670
+ dangerouslyAllowBrowser: true,
671
+ ...this.clientOptions,
672
+ ...options_,
673
+ apiKey: this.apiKey,
674
+ maxRetries: 0
675
+ });
676
+ }
677
+ const makeCompletionRequest = async () => {
678
+ try {
679
+ return await this.streamingClient.messages.create({
680
+ ...request,
681
+ ...this.invocationKwargs,
682
+ stream: true
683
+ }, options);
684
+ } catch (e) {
685
+ const error = require_errors.wrapAnthropicClientError(e);
686
+ throw error;
687
+ }
688
+ };
689
+ return this.caller.call(makeCompletionRequest);
690
+ }
691
+ /** @ignore */
692
+ async completionWithRetry(request, options) {
693
+ if (!this.batchClient) {
694
+ const options$1 = this.apiUrl ? { baseURL: this.apiUrl } : void 0;
695
+ this.batchClient = this.createClient({
696
+ dangerouslyAllowBrowser: true,
697
+ ...this.clientOptions,
698
+ ...options$1,
699
+ apiKey: this.apiKey,
700
+ maxRetries: 0
701
+ });
702
+ }
703
+ const makeCompletionRequest = async () => {
704
+ try {
705
+ return await this.batchClient.messages.create({
706
+ ...request,
707
+ ...this.invocationKwargs
708
+ }, options);
709
+ } catch (e) {
710
+ const error = require_errors.wrapAnthropicClientError(e);
711
+ throw error;
712
+ }
713
+ };
714
+ return this.caller.callWithOptions({ signal: options.signal ?? void 0 }, makeCompletionRequest);
715
+ }
716
+ _llmType() {
717
+ return "anthropic";
718
+ }
719
+ withStructuredOutput(outputSchema, config) {
720
+ const schema = outputSchema;
721
+ const name = config?.name;
722
+ const method = config?.method;
723
+ const includeRaw = config?.includeRaw;
724
+ if (method === "jsonMode") throw new Error(`Anthropic only supports "functionCalling" as a method.`);
725
+ let functionName = name ?? "extract";
726
+ let outputParser;
727
+ let tools;
728
+ if ((0, __langchain_core_utils_types.isInteropZodSchema)(schema)) {
729
+ const jsonSchema = (0, __langchain_core_utils_json_schema.toJsonSchema)(schema);
730
+ tools = [{
731
+ name: functionName,
732
+ description: jsonSchema.description ?? "A function available to call.",
733
+ input_schema: jsonSchema
734
+ }];
735
+ outputParser = new require_output_parsers.AnthropicToolsOutputParser({
736
+ returnSingle: true,
737
+ keyName: functionName,
738
+ zodSchema: schema
739
+ });
740
+ } else {
741
+ let anthropicTools;
742
+ if (typeof schema.name === "string" && typeof schema.description === "string" && typeof schema.input_schema === "object" && schema.input_schema != null) {
743
+ anthropicTools = schema;
744
+ functionName = schema.name;
745
+ } else anthropicTools = {
746
+ name: functionName,
747
+ description: schema.description ?? "",
748
+ input_schema: schema
749
+ };
750
+ tools = [anthropicTools];
751
+ outputParser = new require_output_parsers.AnthropicToolsOutputParser({
752
+ returnSingle: true,
753
+ keyName: functionName
754
+ });
755
+ }
756
+ let llm;
757
+ if (this.thinking?.type === "enabled") {
758
+ const thinkingAdmonition = "Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";
759
+ console.warn(thinkingAdmonition);
760
+ llm = this.withConfig({
761
+ tools,
762
+ ls_structured_output_format: {
763
+ kwargs: { method: "functionCalling" },
764
+ schema: (0, __langchain_core_utils_json_schema.toJsonSchema)(schema)
765
+ }
766
+ });
767
+ const raiseIfNoToolCalls = (message) => {
768
+ if (!message.tool_calls || message.tool_calls.length === 0) throw new Error(thinkingAdmonition);
769
+ return message;
770
+ };
771
+ llm = llm.pipe(raiseIfNoToolCalls);
772
+ } else llm = this.withConfig({
773
+ tools,
774
+ tool_choice: {
775
+ type: "tool",
776
+ name: functionName
777
+ },
778
+ ls_structured_output_format: {
779
+ kwargs: { method: "functionCalling" },
780
+ schema: (0, __langchain_core_utils_json_schema.toJsonSchema)(schema)
781
+ }
782
+ });
783
+ if (!includeRaw) return llm.pipe(outputParser).withConfig({ runName: "ChatAnthropicStructuredOutput" });
784
+ const parserAssign = __langchain_core_runnables.RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) });
785
+ const parserNone = __langchain_core_runnables.RunnablePassthrough.assign({ parsed: () => null });
786
+ const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] });
787
+ return __langchain_core_runnables.RunnableSequence.from([{ raw: llm }, parsedWithFallback]).withConfig({ runName: "StructuredOutputRunnable" });
788
+ }
789
+ };
790
+ var ChatAnthropic = class extends ChatAnthropicMessages {};
791
+
792
+ //#endregion
1026
793
  exports.ChatAnthropic = ChatAnthropic;
794
+ exports.ChatAnthropicMessages = ChatAnthropicMessages;
795
+ //# sourceMappingURL=chat_models.cjs.map