@langchain/anthropic 0.3.25 → 1.0.0-alpha.1

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