@langchain/anthropic 1.0.0-alpha.1 → 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.
@@ -22,7 +22,7 @@ function _toolsInParams(params) {
22
22
  function _documentsInParams(params) {
23
23
  for (const message of params.messages ?? []) {
24
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;
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
26
  }
27
27
  return false;
28
28
  }
@@ -33,15 +33,18 @@ function isAnthropicTool(tool) {
33
33
  return "input_schema" in tool;
34
34
  }
35
35
  function isBuiltinTool(tool) {
36
- const builtinTools = [
37
- "web_search",
38
- "bash",
39
- "code_execution",
40
- "computer",
41
- "str_replace_editor",
42
- "str_replace_based_edit_tool"
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_"
43
46
  ];
44
- return typeof tool === "object" && tool !== null && "type" in tool && "name" in tool && typeof tool.type === "string" && typeof tool.name === "string" && builtinTools.includes(tool.name);
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));
45
48
  }
46
49
  function extractToken(chunk) {
47
50
  if (typeof chunk.content === "string") return chunk.content;
@@ -453,6 +456,7 @@ var ChatAnthropicMessages = class extends __langchain_core_language_models_chat_
453
456
  streaming = false;
454
457
  clientOptions;
455
458
  thinking = { type: "disabled" };
459
+ contextManagement;
456
460
  batchClient;
457
461
  streamingClient;
458
462
  streamUsage = true;
@@ -474,15 +478,16 @@ var ChatAnthropicMessages = class extends __langchain_core_language_models_chat_
474
478
  this.modelName = fields?.model ?? fields?.modelName ?? this.model;
475
479
  this.model = this.modelName;
476
480
  this.invocationKwargs = fields?.invocationKwargs ?? {};
477
- if (this.model.includes("opus-4-1")) this.topP = fields?.topP === null ? void 0 : fields?.topP;
481
+ if (this.model.includes("opus-4-1") || this.model.includes("sonnet-4-5")) this.topP = fields?.topP === null ? void 0 : fields?.topP;
478
482
  else this.topP = fields?.topP ?? this.topP;
479
483
  this.temperature = fields?.temperature === null ? void 0 : fields?.temperature ?? this.temperature;
480
484
  this.topK = fields?.topK ?? this.topK;
481
- this.maxTokens = fields?.maxTokensToSample ?? fields?.maxTokens ?? this.maxTokens;
485
+ this.maxTokens = fields?.maxTokens ?? this.maxTokens;
482
486
  this.stopSequences = fields?.stopSequences ?? this.stopSequences;
483
487
  this.streaming = fields?.streaming ?? false;
484
488
  this.streamUsage = fields?.streamUsage ?? this.streamUsage;
485
489
  this.thinking = fields?.thinking ?? this.thinking;
490
+ this.contextManagement = fields?.contextManagement ?? this.contextManagement;
486
491
  this.createClient = fields?.createClient ?? ((options) => new __anthropic_ai_sdk.Anthropic(options));
487
492
  }
488
493
  getLsParams(options) {
@@ -533,7 +538,7 @@ var ChatAnthropicMessages = class extends __langchain_core_language_models_chat_
533
538
  const tool_choice = require_tools.handleToolChoice(options?.tool_choice);
534
539
  if (this.thinking.type === "enabled") {
535
540
  if (this.topK !== -1) throw new Error("topK is not supported when thinking is enabled");
536
- if (this.topP !== -1) throw new Error("topP 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");
537
542
  if (this.temperature !== 1) throw new Error("temperature is not supported when thinking is enabled");
538
543
  return {
539
544
  model: this.model,
@@ -543,7 +548,9 @@ var ChatAnthropicMessages = class extends __langchain_core_language_models_chat_
543
548
  tools: this.formatStructuredToolToAnthropic(options?.tools),
544
549
  tool_choice,
545
550
  thinking: this.thinking,
546
- ...this.invocationKwargs
551
+ context_management: this.contextManagement,
552
+ ...this.invocationKwargs,
553
+ container: options?.container
547
554
  };
548
555
  }
549
556
  return {
@@ -557,7 +564,9 @@ var ChatAnthropicMessages = class extends __langchain_core_language_models_chat_
557
564
  tools: this.formatStructuredToolToAnthropic(options?.tools),
558
565
  tool_choice,
559
566
  thinking: this.thinking,
560
- ...this.invocationKwargs
567
+ context_management: this.contextManagement,
568
+ ...this.invocationKwargs,
569
+ container: options?.container
561
570
  };
562
571
  }
563
572
  /** @ignore */
@@ -1 +1 @@
1
- {"version":3,"file":"chat_models.cjs","names":["params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams","tool: any","tool: unknown","chunk: AIMessageChunk","BaseChatModel","fields?: AnthropicInput & BaseChatModelParams","options: ClientOptions","Anthropic","options: this[\"ParsedCallOptions\"]","tools: ChatAnthropicCallOptions[\"tools\"]","tools: ChatAnthropicToolType[]","kwargs?: Partial<CallOptions>","options?: this[\"ParsedCallOptions\"]","tool_choice:\n | Anthropic.Messages.ToolChoiceAuto\n | Anthropic.Messages.ToolChoiceAny\n | Anthropic.Messages.ToolChoiceTool\n | undefined","handleToolChoice","messages: BaseMessage[]","runManager?: CallbackManagerForLLMRun","_convertMessagesToAnthropicPayload","_makeMessageChunkFromAnthropicEvent","ChatGenerationChunk","AIMessageChunk","params: Omit<\n | Anthropic.Messages.MessageCreateParamsNonStreaming\n | Anthropic.Messages.MessageCreateParamsStreaming,\n \"messages\"\n > &\n Kwargs","requestOptions: AnthropicRequestOptions","anthropicResponseToChatMessages","finalChunk: ChatGenerationChunk | undefined","request: AnthropicStreamingMessageCreateParams & Kwargs","options?: AnthropicRequestOptions","wrapAnthropicClientError","request: AnthropicMessageCreateParams & Kwargs","options: AnthropicRequestOptions","options","outputSchema:\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>","config?: StructuredOutputMethodOptions<boolean>","schema: InteropZodType<RunOutput> | Record<string, any>","outputParser: BaseLLMOutputParser<RunOutput>","tools: Anthropic.Messages.Tool[]","AnthropicToolsOutputParser","anthropicTools: Anthropic.Messages.Tool","message: AIMessageChunk","RunnablePassthrough","input: any","config","RunnableSequence"],"sources":["../src/chat_models.ts"],"sourcesContent":["import { Anthropic, type ClientOptions } from \"@anthropic-ai/sdk\";\nimport type { Stream } from \"@anthropic-ai/sdk/streaming\";\n\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport { AIMessageChunk, type BaseMessage } from \"@langchain/core/messages\";\nimport { ChatGenerationChunk, type ChatResult } from \"@langchain/core/outputs\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport {\n BaseChatModel,\n BaseChatModelCallOptions,\n LangSmithParams,\n type BaseChatModelParams,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n type StructuredOutputMethodOptions,\n type BaseLanguageModelInput,\n isOpenAITool,\n} from \"@langchain/core/language_models/base\";\nimport { toJsonSchema } from \"@langchain/core/utils/json_schema\";\nimport { BaseLLMOutputParser } from \"@langchain/core/output_parsers\";\nimport {\n Runnable,\n RunnablePassthrough,\n RunnableSequence,\n} from \"@langchain/core/runnables\";\nimport {\n InteropZodType,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\n\nimport { isLangChainTool } from \"@langchain/core/utils/function_calling\";\nimport { AnthropicToolsOutputParser } from \"./output_parsers.js\";\nimport { handleToolChoice } from \"./utils/tools.js\";\nimport { _convertMessagesToAnthropicPayload } from \"./utils/message_inputs.js\";\nimport {\n _makeMessageChunkFromAnthropicEvent,\n anthropicResponseToChatMessages,\n} from \"./utils/message_outputs.js\";\nimport {\n AnthropicBuiltInToolUnion,\n AnthropicMessageCreateParams,\n AnthropicMessageStreamEvent,\n AnthropicRequestOptions,\n AnthropicStreamingMessageCreateParams,\n AnthropicThinkingConfigParam,\n AnthropicToolChoice,\n ChatAnthropicToolType,\n} from \"./types.js\";\nimport { wrapAnthropicClientError } from \"./utils/errors.js\";\n\nexport interface ChatAnthropicCallOptions\n extends BaseChatModelCallOptions,\n Pick<AnthropicInput, \"streamUsage\"> {\n tools?: ChatAnthropicToolType[];\n /**\n * Whether or not to specify what tool the model should use\n * @default \"auto\"\n */\n tool_choice?: AnthropicToolChoice;\n /**\n * Custom headers to pass to the Anthropic API\n * when making a request.\n */\n headers?: Record<string, string>;\n}\n\nfunction _toolsInParams(\n params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams\n): boolean {\n return !!(params.tools && params.tools.length > 0);\n}\n\nfunction _documentsInParams(\n params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams\n): boolean {\n for (const message of params.messages ?? []) {\n if (typeof message.content === \"string\") {\n continue;\n }\n for (const block of message.content ?? []) {\n if (\n typeof block === \"object\" &&\n block != null &&\n block.type === \"document\" &&\n typeof block.citations === \"object\" &&\n block.citations.enabled\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\nfunction _thinkingInParams(\n params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams\n): boolean {\n return !!(params.thinking && params.thinking.type === \"enabled\");\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction isAnthropicTool(tool: any): tool is Anthropic.Messages.Tool {\n return \"input_schema\" in tool;\n}\n\nfunction isBuiltinTool(tool: unknown): tool is AnthropicBuiltInToolUnion {\n const builtinTools = [\n \"web_search\",\n \"bash\",\n \"code_execution\",\n \"computer\",\n \"str_replace_editor\",\n \"str_replace_based_edit_tool\",\n ];\n return (\n typeof tool === \"object\" &&\n tool !== null &&\n \"type\" in tool &&\n \"name\" in tool &&\n typeof tool.type === \"string\" &&\n typeof tool.name === \"string\" &&\n builtinTools.includes(tool.name)\n );\n}\n\n/**\n * @see https://docs.anthropic.com/claude/docs/models-overview\n */\nexport type AnthropicMessagesModelId =\n | Anthropic.Model\n | (string & NonNullable<unknown>);\n\n/**\n * Input to AnthropicChat class.\n */\nexport interface AnthropicInput {\n /** Amount of randomness injected into the response. Ranges\n * from 0 to 1. Use temp closer to 0 for analytical /\n * multiple choice, and temp closer to 1 for creative\n * and generative tasks.\n * To not set this field, pass `null`. If `undefined` is passed,\n * the default (1) will be used.\n */\n temperature?: number | null;\n\n /** Only sample from the top K options for each subsequent\n * token. Used to remove \"long tail\" low probability\n * responses. Defaults to -1, which disables it.\n */\n topK?: number;\n\n /** Does nucleus sampling, in which we compute the\n * cumulative distribution over all the options for each\n * subsequent token in decreasing probability order and\n * cut it off once it reaches a particular probability\n * specified by top_p. Defaults to -1, which disables it.\n * Note that you should either alter temperature or top_p,\n * but not both.\n *\n * To not set this field, pass `null`. If `undefined` is passed,\n * the default (-1) will be used.\n *\n * For Opus 4.1, this defaults to `null`.\n */\n topP?: number | null;\n\n /** A maximum number of tokens to generate before stopping. */\n maxTokens?: number;\n\n /**\n * A maximum number of tokens to generate before stopping.\n * @deprecated Use \"maxTokens\" instead.\n */\n maxTokensToSample?: number;\n\n /** A list of strings upon which to stop generating.\n * You probably want `[\"\\n\\nHuman:\"]`, as that's the cue for\n * the next turn in the dialog agent.\n */\n stopSequences?: string[];\n\n /** Whether to stream the results or not */\n streaming?: boolean;\n\n /** Anthropic API key */\n anthropicApiKey?: string;\n /** Anthropic API key */\n apiKey?: string;\n\n /** Anthropic API URL */\n anthropicApiUrl?: string;\n\n /** @deprecated Use \"model\" instead */\n modelName?: AnthropicMessagesModelId;\n /** Model name to use */\n model?: AnthropicMessagesModelId;\n\n /** Overridable Anthropic ClientOptions */\n clientOptions?: ClientOptions;\n\n /** Holds any additional parameters that are valid to pass to {@link\n * https://console.anthropic.com/docs/api/reference |\n * `anthropic.messages`} that are not explicitly specified on this class.\n */\n invocationKwargs?: Kwargs;\n\n /**\n * Whether or not to include token usage data in streamed chunks.\n * @default true\n */\n streamUsage?: boolean;\n\n /**\n * Optional method that returns an initialized underlying Anthropic client.\n * Useful for accessing Anthropic models hosted on other cloud services\n * such as Google Vertex.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n createClient?: (options: ClientOptions) => any;\n\n /**\n * Options for extended thinking.\n */\n thinking?: AnthropicThinkingConfigParam;\n}\n\n/**\n * A type representing additional parameters that can be passed to the\n * Anthropic API.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Kwargs = Record<string, any>;\n\nfunction extractToken(chunk: AIMessageChunk): string | undefined {\n if (typeof chunk.content === \"string\") {\n return chunk.content;\n } else if (\n Array.isArray(chunk.content) &&\n chunk.content.length >= 1 &&\n \"input\" in chunk.content[0]\n ) {\n return typeof chunk.content[0].input === \"string\"\n ? chunk.content[0].input\n : JSON.stringify(chunk.content[0].input);\n } else if (\n Array.isArray(chunk.content) &&\n chunk.content.length >= 1 &&\n \"text\" in chunk.content[0] &&\n typeof chunk.content[0].text === \"string\"\n ) {\n return chunk.content[0].text;\n }\n return undefined;\n}\n\n/**\n * Anthropic chat model integration.\n *\n * Setup:\n * Install `@langchain/anthropic` and set an environment variable named `ANTHROPIC_API_KEY`.\n *\n * ```bash\n * npm install @langchain/anthropic\n * export ANTHROPIC_API_KEY=\"your-api-key\"\n * ```\n *\n * ## [Constructor args](https://api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html#constructor)\n *\n * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_anthropic.ChatAnthropicCallOptions.html)\n *\n * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.\n * They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below:\n *\n * ```typescript\n * // When calling `.bind`, call options should be passed via the first argument\n * const llmWithArgsBound = llm.bindTools([...]).withConfig({\n * stop: [\"\\n\"],\n * });\n *\n * // When calling `.bindTools`, call options should be passed via the second argument\n * const llmWithTools = llm.bindTools(\n * [...],\n * {\n * tool_choice: \"auto\",\n * }\n * );\n * ```\n *\n * ## Examples\n *\n * <details open>\n * <summary><strong>Instantiate</strong></summary>\n *\n * ```typescript\n * import { ChatAnthropic } from '@langchain/anthropic';\n *\n * const llm = new ChatAnthropic({\n * model: \"claude-3-5-sonnet-20240620\",\n * temperature: 0,\n * maxTokens: undefined,\n * maxRetries: 2,\n * // apiKey: \"...\",\n * // baseUrl: \"...\",\n * // other params...\n * });\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Invoking</strong></summary>\n *\n * ```typescript\n * const input = `Translate \"I love programming\" into French.`;\n *\n * // Models also accept a list of chat messages or a formatted prompt\n * const result = await llm.invoke(input);\n * console.log(result);\n * ```\n *\n * ```txt\n * AIMessage {\n * \"id\": \"msg_01QDpd78JUHpRP6bRRNyzbW3\",\n * \"content\": \"Here's the translation to French:\\n\\nJ'adore la programmation.\",\n * \"response_metadata\": {\n * \"id\": \"msg_01QDpd78JUHpRP6bRRNyzbW3\",\n * \"model\": \"claude-3-5-sonnet-20240620\",\n * \"stop_reason\": \"end_turn\",\n * \"stop_sequence\": null,\n * \"usage\": {\n * \"input_tokens\": 25,\n * \"output_tokens\": 19\n * },\n * \"type\": \"message\",\n * \"role\": \"assistant\"\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 25,\n * \"output_tokens\": 19,\n * \"total_tokens\": 44\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Streaming Chunks</strong></summary>\n *\n * ```typescript\n * for await (const chunk of await llm.stream(input)) {\n * console.log(chunk);\n * }\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"id\": \"msg_01N8MwoYxiKo9w4chE4gXUs4\",\n * \"content\": \"\",\n * \"additional_kwargs\": {\n * \"id\": \"msg_01N8MwoYxiKo9w4chE4gXUs4\",\n * \"type\": \"message\",\n * \"role\": \"assistant\",\n * \"model\": \"claude-3-5-sonnet-20240620\"\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 25,\n * \"output_tokens\": 1,\n * \"total_tokens\": 26\n * }\n * }\n * AIMessageChunk {\n * \"content\": \"\",\n * }\n * AIMessageChunk {\n * \"content\": \"Here\",\n * }\n * AIMessageChunk {\n * \"content\": \"'s\",\n * }\n * AIMessageChunk {\n * \"content\": \" the translation to\",\n * }\n * AIMessageChunk {\n * \"content\": \" French:\\n\\nJ\",\n * }\n * AIMessageChunk {\n * \"content\": \"'adore la programmation\",\n * }\n * AIMessageChunk {\n * \"content\": \".\",\n * }\n * AIMessageChunk {\n * \"content\": \"\",\n * \"additional_kwargs\": {\n * \"stop_reason\": \"end_turn\",\n * \"stop_sequence\": null\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 0,\n * \"output_tokens\": 19,\n * \"total_tokens\": 19\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Aggregate Streamed Chunks</strong></summary>\n *\n * ```typescript\n * import { AIMessageChunk } from '@langchain/core/messages';\n * import { concat } from '@langchain/core/utils/stream';\n *\n * const stream = await llm.stream(input);\n * let full: AIMessageChunk | undefined;\n * for await (const chunk of stream) {\n * full = !full ? chunk : concat(full, chunk);\n * }\n * console.log(full);\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"id\": \"msg_01SBTb5zSGXfjUc7yQ8EKEEA\",\n * \"content\": \"Here's the translation to French:\\n\\nJ'adore la programmation.\",\n * \"additional_kwargs\": {\n * \"id\": \"msg_01SBTb5zSGXfjUc7yQ8EKEEA\",\n * \"type\": \"message\",\n * \"role\": \"assistant\",\n * \"model\": \"claude-3-5-sonnet-20240620\",\n * \"stop_reason\": \"end_turn\",\n * \"stop_sequence\": null\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 25,\n * \"output_tokens\": 20,\n * \"total_tokens\": 45\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Bind tools</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const GetWeather = {\n * name: \"GetWeather\",\n * description: \"Get the current weather in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const GetPopulation = {\n * name: \"GetPopulation\",\n * description: \"Get the current population in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);\n * const aiMsg = await llmWithTools.invoke(\n * \"Which city is hotter today and which is bigger: LA or NY?\"\n * );\n * console.log(aiMsg.tool_calls);\n * ```\n *\n * ```txt\n * [\n * {\n * name: 'GetWeather',\n * args: { location: 'Los Angeles, CA' },\n * id: 'toolu_01WjW3Dann6BPJVtLhovdBD5',\n * type: 'tool_call'\n * },\n * {\n * name: 'GetWeather',\n * args: { location: 'New York, NY' },\n * id: 'toolu_01G6wfJgqi5zRmJomsmkyZXe',\n * type: 'tool_call'\n * },\n * {\n * name: 'GetPopulation',\n * args: { location: 'Los Angeles, CA' },\n * id: 'toolu_0165qYWBA2VFyUst5RA18zew',\n * type: 'tool_call'\n * },\n * {\n * name: 'GetPopulation',\n * args: { location: 'New York, NY' },\n * id: 'toolu_01PGNyP33vxr13tGqr7i3rDo',\n * type: 'tool_call'\n * }\n * ]\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Structured Output</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const Joke = z.object({\n * setup: z.string().describe(\"The setup of the joke\"),\n * punchline: z.string().describe(\"The punchline to the joke\"),\n * rating: z.number().optional().describe(\"How funny the joke is, from 1 to 10\")\n * }).describe('Joke to tell user.');\n *\n * const structuredLlm = llm.withStructuredOutput(Joke, { name: \"Joke\" });\n * const jokeResult = await structuredLlm.invoke(\"Tell me a joke about cats\");\n * console.log(jokeResult);\n * ```\n *\n * ```txt\n * {\n * setup: \"Why don't cats play poker in the jungle?\",\n * punchline: 'Too many cheetahs!',\n * rating: 7\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Multimodal</strong></summary>\n *\n * ```typescript\n * import { HumanMessage } from '@langchain/core/messages';\n *\n * const imageUrl = \"https://example.com/image.jpg\";\n * const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());\n * const base64Image = Buffer.from(imageData).toString('base64');\n *\n * const message = new HumanMessage({\n * content: [\n * { type: \"text\", text: \"describe the weather in this image\" },\n * {\n * type: \"image_url\",\n * image_url: { url: `data:image/jpeg;base64,${base64Image}` },\n * },\n * ]\n * });\n *\n * const imageDescriptionAiMsg = await llm.invoke([message]);\n * console.log(imageDescriptionAiMsg.content);\n * ```\n *\n * ```txt\n * 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.\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Usage Metadata</strong></summary>\n *\n * ```typescript\n * const aiMsgForMetadata = await llm.invoke(input);\n * console.log(aiMsgForMetadata.usage_metadata);\n * ```\n *\n * ```txt\n * { input_tokens: 25, output_tokens: 19, total_tokens: 44 }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Stream Usage Metadata</strong></summary>\n *\n * ```typescript\n * const streamForMetadata = await llm.stream(\n * input,\n * {\n * streamUsage: true\n * }\n * );\n * let fullForMetadata: AIMessageChunk | undefined;\n * for await (const chunk of streamForMetadata) {\n * fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk);\n * }\n * console.log(fullForMetadata?.usage_metadata);\n * ```\n *\n * ```txt\n * { input_tokens: 25, output_tokens: 20, total_tokens: 45 }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Response Metadata</strong></summary>\n *\n * ```typescript\n * const aiMsgForResponseMetadata = await llm.invoke(input);\n * console.log(aiMsgForResponseMetadata.response_metadata);\n * ```\n *\n * ```txt\n * {\n * id: 'msg_01STxeQxJmp4sCSpioD6vK3L',\n * model: 'claude-3-5-sonnet-20240620',\n * stop_reason: 'end_turn',\n * stop_sequence: null,\n * usage: { input_tokens: 25, output_tokens: 19 },\n * type: 'message',\n * role: 'assistant'\n * }\n * ```\n * </details>\n *\n * <br />\n */\nexport class ChatAnthropicMessages<\n CallOptions extends ChatAnthropicCallOptions = ChatAnthropicCallOptions\n >\n extends BaseChatModel<CallOptions, AIMessageChunk>\n implements AnthropicInput\n{\n static lc_name() {\n return \"ChatAnthropic\";\n }\n\n get lc_secrets(): { [key: string]: string } | undefined {\n return {\n anthropicApiKey: \"ANTHROPIC_API_KEY\",\n apiKey: \"ANTHROPIC_API_KEY\",\n };\n }\n\n get lc_aliases(): Record<string, string> {\n return {\n modelName: \"model\",\n };\n }\n\n lc_serializable = true;\n\n anthropicApiKey?: string;\n\n apiKey?: string;\n\n apiUrl?: string;\n\n temperature: number | undefined = 1;\n\n topK = -1;\n\n topP: number | undefined = -1;\n\n maxTokens = 2048;\n\n modelName = \"claude-2.1\";\n\n model = \"claude-2.1\";\n\n invocationKwargs?: Kwargs;\n\n stopSequences?: string[];\n\n streaming = false;\n\n clientOptions: ClientOptions;\n\n thinking: AnthropicThinkingConfigParam = { type: \"disabled\" };\n\n // Used for non-streaming requests\n protected batchClient: Anthropic;\n\n // Used for streaming requests\n protected streamingClient: Anthropic;\n\n streamUsage = true;\n\n /**\n * Optional method that returns an initialized underlying Anthropic client.\n * Useful for accessing Anthropic models hosted on other cloud services\n * such as Google Vertex.\n */\n createClient: (options: ClientOptions) => Anthropic;\n\n constructor(fields?: AnthropicInput & BaseChatModelParams) {\n super(fields ?? {});\n\n this.anthropicApiKey =\n fields?.apiKey ??\n fields?.anthropicApiKey ??\n getEnvironmentVariable(\"ANTHROPIC_API_KEY\");\n\n if (!this.anthropicApiKey && !fields?.createClient) {\n throw new Error(\"Anthropic API key not found\");\n }\n this.clientOptions = fields?.clientOptions ?? {};\n /** Keep anthropicApiKey for backwards compatibility */\n this.apiKey = this.anthropicApiKey;\n\n // Support overriding the default API URL (i.e., https://api.anthropic.com)\n this.apiUrl = fields?.anthropicApiUrl;\n\n /** Keep modelName for backwards compatibility */\n this.modelName = fields?.model ?? fields?.modelName ?? this.model;\n this.model = this.modelName;\n\n this.invocationKwargs = fields?.invocationKwargs ?? {};\n\n if (this.model.includes(\"opus-4-1\")) {\n // Default to `undefined` for `topP` for Opus 4.1 models\n this.topP = fields?.topP === null ? undefined : fields?.topP;\n } else {\n this.topP = fields?.topP ?? this.topP;\n }\n\n // If the user passes `null`, set it to `undefined`. Otherwise, use their value or the default. We have to check for null, because\n // there's no way for us to know if they explicitly set it to `undefined`, or never passed a value\n this.temperature =\n fields?.temperature === null\n ? undefined\n : fields?.temperature ?? this.temperature;\n this.topK = fields?.topK ?? this.topK;\n this.maxTokens =\n fields?.maxTokensToSample ?? fields?.maxTokens ?? this.maxTokens;\n this.stopSequences = fields?.stopSequences ?? this.stopSequences;\n\n this.streaming = fields?.streaming ?? false;\n this.streamUsage = fields?.streamUsage ?? this.streamUsage;\n\n this.thinking = fields?.thinking ?? this.thinking;\n\n this.createClient =\n fields?.createClient ??\n ((options: ClientOptions) => new Anthropic(options));\n }\n\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams {\n const params = this.invocationParams(options);\n return {\n ls_provider: \"anthropic\",\n ls_model_name: this.model,\n ls_model_type: \"chat\",\n ls_temperature: params.temperature ?? undefined,\n ls_max_tokens: params.max_tokens ?? undefined,\n ls_stop: options.stop,\n };\n }\n\n /**\n * Formats LangChain StructuredTools to AnthropicTools.\n *\n * @param {ChatAnthropicCallOptions[\"tools\"]} tools The tools to format\n * @returns {AnthropicTool[] | undefined} The formatted tools, or undefined if none are passed.\n */\n formatStructuredToolToAnthropic(\n tools: ChatAnthropicCallOptions[\"tools\"]\n ): Anthropic.Messages.ToolUnion[] | undefined {\n if (!tools || !tools.length) {\n return undefined;\n }\n return tools.map((tool) => {\n if (isBuiltinTool(tool)) {\n return tool;\n }\n if (isAnthropicTool(tool)) {\n return tool;\n }\n if (isOpenAITool(tool)) {\n return {\n name: tool.function.name,\n description: tool.function.description,\n input_schema: tool.function\n .parameters as Anthropic.Messages.Tool.InputSchema,\n };\n }\n if (isLangChainTool(tool)) {\n return {\n name: tool.name,\n description: tool.description,\n input_schema: (isInteropZodSchema(tool.schema)\n ? toJsonSchema(tool.schema)\n : tool.schema) as Anthropic.Messages.Tool.InputSchema,\n };\n }\n throw new Error(\n `Unknown tool type passed to ChatAnthropic: ${JSON.stringify(\n tool,\n null,\n 2\n )}`\n );\n });\n }\n\n override bindTools(\n tools: ChatAnthropicToolType[],\n kwargs?: Partial<CallOptions>\n ): Runnable<BaseLanguageModelInput, AIMessageChunk, CallOptions> {\n return this.withConfig({\n tools: this.formatStructuredToolToAnthropic(tools),\n ...kwargs,\n } as Partial<CallOptions>);\n }\n\n /**\n * Get the parameters used to invoke the model\n */\n override invocationParams(\n options?: this[\"ParsedCallOptions\"]\n ): Omit<\n AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams,\n \"messages\"\n > &\n Kwargs {\n const tool_choice:\n | Anthropic.Messages.ToolChoiceAuto\n | Anthropic.Messages.ToolChoiceAny\n | Anthropic.Messages.ToolChoiceTool\n | undefined = handleToolChoice(options?.tool_choice);\n\n if (this.thinking.type === \"enabled\") {\n if (this.topK !== -1) {\n throw new Error(\"topK is not supported when thinking is enabled\");\n }\n if (this.topP !== -1) {\n throw new Error(\"topP is not supported when thinking is enabled\");\n }\n if (this.temperature !== 1) {\n throw new Error(\n \"temperature is not supported when thinking is enabled\"\n );\n }\n\n return {\n model: this.model,\n stop_sequences: options?.stop ?? this.stopSequences,\n stream: this.streaming,\n max_tokens: this.maxTokens,\n tools: this.formatStructuredToolToAnthropic(options?.tools),\n tool_choice,\n thinking: this.thinking,\n ...this.invocationKwargs,\n };\n }\n return {\n model: this.model,\n temperature: this.temperature,\n top_k: this.topK,\n top_p: this.topP,\n stop_sequences: options?.stop ?? this.stopSequences,\n stream: this.streaming,\n max_tokens: this.maxTokens,\n tools: this.formatStructuredToolToAnthropic(options?.tools),\n tool_choice,\n thinking: this.thinking,\n ...this.invocationKwargs,\n };\n }\n\n /** @ignore */\n _identifyingParams() {\n return {\n model_name: this.model,\n ...this.invocationParams(),\n };\n }\n\n /**\n * Get the identifying parameters for the model\n */\n identifyingParams() {\n return {\n model_name: this.model,\n ...this.invocationParams(),\n };\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const params = this.invocationParams(options);\n const formattedMessages = _convertMessagesToAnthropicPayload(messages);\n const payload = {\n ...params,\n ...formattedMessages,\n stream: true,\n } as const;\n const coerceContentToString =\n !_toolsInParams(payload) &&\n !_documentsInParams(payload) &&\n !_thinkingInParams(payload);\n\n const stream = await this.createStreamWithRetry(payload, {\n headers: options.headers,\n });\n\n for await (const data of stream) {\n if (options.signal?.aborted) {\n stream.controller.abort();\n throw new Error(\"AbortError: User aborted the request.\");\n }\n const shouldStreamUsage = this.streamUsage ?? options.streamUsage;\n const result = _makeMessageChunkFromAnthropicEvent(data, {\n streamUsage: shouldStreamUsage,\n coerceContentToString,\n });\n if (!result) continue;\n\n const { chunk } = result;\n\n // Extract the text content token for text field and runManager.\n const token = extractToken(chunk);\n const generationChunk = new ChatGenerationChunk({\n message: new AIMessageChunk({\n // Just yield chunk as it is and tool_use will be concat by BaseChatModel._generateUncached().\n content: chunk.content,\n additional_kwargs: chunk.additional_kwargs,\n tool_call_chunks: chunk.tool_call_chunks,\n usage_metadata: shouldStreamUsage ? chunk.usage_metadata : undefined,\n response_metadata: chunk.response_metadata,\n id: chunk.id,\n }),\n text: token ?? \"\",\n });\n yield generationChunk;\n\n await runManager?.handleLLMNewToken(\n token ?? \"\",\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk: generationChunk }\n );\n }\n }\n\n /** @ignore */\n async _generateNonStreaming(\n messages: BaseMessage[],\n params: Omit<\n | Anthropic.Messages.MessageCreateParamsNonStreaming\n | Anthropic.Messages.MessageCreateParamsStreaming,\n \"messages\"\n > &\n Kwargs,\n requestOptions: AnthropicRequestOptions\n ) {\n const response = await this.completionWithRetry(\n {\n ...params,\n stream: false,\n ..._convertMessagesToAnthropicPayload(messages),\n },\n requestOptions\n );\n\n const { content, ...additionalKwargs } = response;\n\n const generations = anthropicResponseToChatMessages(\n content,\n additionalKwargs\n );\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { role: _role, type: _type, ...rest } = additionalKwargs;\n return { generations, llmOutput: rest };\n }\n\n /** @ignore */\n async _generate(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n if (this.stopSequences && options.stop) {\n throw new Error(\n `\"stopSequence\" parameter found in input and default params`\n );\n }\n\n const params = this.invocationParams(options);\n if (params.stream) {\n let finalChunk: ChatGenerationChunk | undefined;\n const stream = this._streamResponseChunks(messages, options, runManager);\n for await (const chunk of stream) {\n if (finalChunk === undefined) {\n finalChunk = chunk;\n } else {\n finalChunk = finalChunk.concat(chunk);\n }\n }\n if (finalChunk === undefined) {\n throw new Error(\"No chunks returned from Anthropic API.\");\n }\n return {\n generations: [\n {\n text: finalChunk.text,\n message: finalChunk.message,\n },\n ],\n };\n } else {\n return this._generateNonStreaming(messages, params, {\n signal: options.signal,\n headers: options.headers,\n });\n }\n }\n\n /**\n * Creates a streaming request with retry.\n * @param request The parameters for creating a completion.\n * @param options\n * @returns A streaming request.\n */\n protected async createStreamWithRetry(\n request: AnthropicStreamingMessageCreateParams & Kwargs,\n options?: AnthropicRequestOptions\n ): Promise<Stream<AnthropicMessageStreamEvent>> {\n if (!this.streamingClient) {\n const options_ = this.apiUrl ? { baseURL: this.apiUrl } : undefined;\n this.streamingClient = this.createClient({\n dangerouslyAllowBrowser: true,\n ...this.clientOptions,\n ...options_,\n apiKey: this.apiKey,\n // Prefer LangChain built-in retries\n maxRetries: 0,\n });\n }\n const makeCompletionRequest = async () => {\n try {\n return await this.streamingClient.messages.create(\n {\n ...request,\n ...this.invocationKwargs,\n stream: true,\n } as AnthropicStreamingMessageCreateParams,\n options\n );\n } catch (e) {\n const error = wrapAnthropicClientError(e);\n throw error;\n }\n };\n return this.caller.call(makeCompletionRequest);\n }\n\n /** @ignore */\n protected async completionWithRetry(\n request: AnthropicMessageCreateParams & Kwargs,\n options: AnthropicRequestOptions\n ): Promise<Anthropic.Message> {\n if (!this.batchClient) {\n const options = this.apiUrl ? { baseURL: this.apiUrl } : undefined;\n this.batchClient = this.createClient({\n dangerouslyAllowBrowser: true,\n ...this.clientOptions,\n ...options,\n apiKey: this.apiKey,\n maxRetries: 0,\n });\n }\n const makeCompletionRequest = async () => {\n try {\n return await this.batchClient.messages.create(\n {\n ...request,\n ...this.invocationKwargs,\n } as AnthropicMessageCreateParams,\n options\n );\n } catch (e) {\n const error = wrapAnthropicClientError(e);\n throw error;\n }\n };\n return this.caller.callWithOptions(\n { signal: options.signal ?? undefined },\n makeCompletionRequest\n );\n }\n\n _llmType() {\n return \"anthropic\";\n }\n\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n > {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const schema: InteropZodType<RunOutput> | Record<string, any> =\n outputSchema;\n const name = config?.name;\n const method = config?.method;\n const includeRaw = config?.includeRaw;\n if (method === \"jsonMode\") {\n throw new Error(`Anthropic only supports \"functionCalling\" as a method.`);\n }\n\n let functionName = name ?? \"extract\";\n let outputParser: BaseLLMOutputParser<RunOutput>;\n let tools: Anthropic.Messages.Tool[];\n if (isInteropZodSchema(schema)) {\n const jsonSchema = toJsonSchema(schema);\n tools = [\n {\n name: functionName,\n description:\n jsonSchema.description ?? \"A function available to call.\",\n input_schema: jsonSchema as Anthropic.Messages.Tool.InputSchema,\n },\n ];\n outputParser = new AnthropicToolsOutputParser({\n returnSingle: true,\n keyName: functionName,\n zodSchema: schema,\n });\n } else {\n let anthropicTools: Anthropic.Messages.Tool;\n if (\n typeof schema.name === \"string\" &&\n typeof schema.description === \"string\" &&\n typeof schema.input_schema === \"object\" &&\n schema.input_schema != null\n ) {\n anthropicTools = schema as Anthropic.Messages.Tool;\n functionName = schema.name;\n } else {\n anthropicTools = {\n name: functionName,\n description: schema.description ?? \"\",\n input_schema: schema as Anthropic.Messages.Tool.InputSchema,\n };\n }\n tools = [anthropicTools];\n outputParser = new AnthropicToolsOutputParser<RunOutput>({\n returnSingle: true,\n keyName: functionName,\n });\n }\n let llm;\n if (this.thinking?.type === \"enabled\") {\n const thinkingAdmonition =\n \"Anthropic structured output relies on forced tool calling, \" +\n \"which is not supported when `thinking` is enabled. This method will raise \" +\n \"OutputParserException if tool calls are not \" +\n \"generated. Consider disabling `thinking` or adjust your prompt to ensure \" +\n \"the tool is called.\";\n\n console.warn(thinkingAdmonition);\n\n llm = this.withConfig({\n tools,\n ls_structured_output_format: {\n kwargs: { method: \"functionCalling\" },\n schema: toJsonSchema(schema),\n },\n } as Partial<CallOptions>);\n\n const raiseIfNoToolCalls = (message: AIMessageChunk) => {\n if (!message.tool_calls || message.tool_calls.length === 0) {\n throw new Error(thinkingAdmonition);\n }\n return message;\n };\n\n llm = llm.pipe(raiseIfNoToolCalls);\n } else {\n llm = this.withConfig({\n tools,\n tool_choice: {\n type: \"tool\",\n name: functionName,\n },\n ls_structured_output_format: {\n kwargs: { method: \"functionCalling\" },\n schema: toJsonSchema(schema),\n },\n } as Partial<CallOptions>);\n }\n\n if (!includeRaw) {\n return llm.pipe(outputParser).withConfig({\n runName: \"ChatAnthropicStructuredOutput\",\n }) as Runnable<BaseLanguageModelInput, RunOutput>;\n }\n\n const parserAssign = RunnablePassthrough.assign({\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parsed: (input: any, config) => outputParser.invoke(input.raw, config),\n });\n const parserNone = RunnablePassthrough.assign({\n parsed: () => null,\n });\n const parsedWithFallback = parserAssign.withFallbacks({\n fallbacks: [parserNone],\n });\n return RunnableSequence.from<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n >([\n {\n raw: llm,\n },\n parsedWithFallback,\n ]).withConfig({\n runName: \"StructuredOutputRunnable\",\n });\n }\n}\n\nexport class ChatAnthropic extends ChatAnthropicMessages {}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkEA,SAAS,eACPA,QACS;AACT,QAAO,CAAC,EAAE,OAAO,SAAS,OAAO,MAAM,SAAS;AACjD;AAED,SAAS,mBACPA,QACS;AACT,MAAK,MAAM,WAAW,OAAO,YAAY,CAAE,GAAE;AAC3C,MAAI,OAAO,QAAQ,YAAY,SAC7B;AAEF,OAAK,MAAM,SAAS,QAAQ,WAAW,CAAE,EACvC,KACE,OAAO,UAAU,YACjB,SAAS,QACT,MAAM,SAAS,cACf,OAAO,MAAM,cAAc,YAC3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C,OAAYC,aAAW,aAAa,OAAO,MAAM,KAAKA,SAAO,CACvE,EAAC;EACF,MAAM,aAAaF,+CAAoB,OAAO,EAC5C,QAAQ,MAAM,KACf,EAAC;EACF,MAAM,qBAAqB,aAAa,cAAc,EACpD,WAAW,CAAC,UAAW,EACxB,EAAC;AACF,SAAOG,4CAAiB,KAGtB,CACA,EACE,KAAK,IACN,GACD,kBACD,EAAC,CAAC,WAAW,EACZ,SAAS,2BACV,EAAC;CACH;AACF;AAED,IAAa,gBAAb,cAAmC,sBAAsB,CAAE"}
1
+ {"version":3,"file":"chat_models.cjs","names":["params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams","tool: any","tool: unknown","chunk: AIMessageChunk","BaseChatModel","fields?: AnthropicInput & BaseChatModelParams","options: ClientOptions","Anthropic","options: this[\"ParsedCallOptions\"]","tools: ChatAnthropicCallOptions[\"tools\"]","tools: ChatAnthropicToolType[]","kwargs?: Partial<CallOptions>","options?: this[\"ParsedCallOptions\"]","tool_choice:\n | Anthropic.Messages.ToolChoiceAuto\n | Anthropic.Messages.ToolChoiceAny\n | Anthropic.Messages.ToolChoiceTool\n | Anthropic.Messages.ToolChoiceNone\n | undefined","handleToolChoice","messages: BaseMessage[]","runManager?: CallbackManagerForLLMRun","_convertMessagesToAnthropicPayload","_makeMessageChunkFromAnthropicEvent","ChatGenerationChunk","AIMessageChunk","params: Omit<\n | Anthropic.Messages.MessageCreateParamsNonStreaming\n | Anthropic.Messages.MessageCreateParamsStreaming,\n \"messages\"\n > &\n Kwargs","requestOptions: AnthropicRequestOptions","anthropicResponseToChatMessages","finalChunk: ChatGenerationChunk | undefined","request: AnthropicStreamingMessageCreateParams & Kwargs","options?: AnthropicRequestOptions","wrapAnthropicClientError","request: AnthropicMessageCreateParams & Kwargs","options: AnthropicRequestOptions","options","outputSchema:\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>","config?: StructuredOutputMethodOptions<boolean>","schema: InteropZodType<RunOutput> | Record<string, any>","outputParser: BaseLLMOutputParser<RunOutput>","tools: Anthropic.Messages.Tool[]","AnthropicToolsOutputParser","anthropicTools: Anthropic.Messages.Tool","message: AIMessageChunk","RunnablePassthrough","input: any","config","RunnableSequence"],"sources":["../src/chat_models.ts"],"sourcesContent":["import { Anthropic, type ClientOptions } from \"@anthropic-ai/sdk\";\nimport type { Stream } from \"@anthropic-ai/sdk/streaming\";\n\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport { AIMessageChunk, type BaseMessage } from \"@langchain/core/messages\";\nimport { ChatGenerationChunk, type ChatResult } from \"@langchain/core/outputs\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport {\n BaseChatModel,\n BaseChatModelCallOptions,\n LangSmithParams,\n type BaseChatModelParams,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n type StructuredOutputMethodOptions,\n type BaseLanguageModelInput,\n isOpenAITool,\n} from \"@langchain/core/language_models/base\";\nimport { toJsonSchema } from \"@langchain/core/utils/json_schema\";\nimport { BaseLLMOutputParser } from \"@langchain/core/output_parsers\";\nimport {\n Runnable,\n RunnablePassthrough,\n RunnableSequence,\n} from \"@langchain/core/runnables\";\nimport {\n InteropZodType,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\n\nimport { isLangChainTool } from \"@langchain/core/utils/function_calling\";\nimport { AnthropicToolsOutputParser } from \"./output_parsers.js\";\nimport { handleToolChoice } from \"./utils/tools.js\";\nimport { _convertMessagesToAnthropicPayload } from \"./utils/message_inputs.js\";\nimport {\n _makeMessageChunkFromAnthropicEvent,\n anthropicResponseToChatMessages,\n} from \"./utils/message_outputs.js\";\nimport {\n AnthropicBuiltInToolUnion,\n AnthropicContextManagementConfigParam,\n AnthropicMessageCreateParams,\n AnthropicMessageStreamEvent,\n AnthropicRequestOptions,\n AnthropicStreamingMessageCreateParams,\n AnthropicThinkingConfigParam,\n AnthropicToolChoice,\n ChatAnthropicToolType,\n} from \"./types.js\";\nimport { wrapAnthropicClientError } from \"./utils/errors.js\";\n\nexport interface ChatAnthropicCallOptions\n extends BaseChatModelCallOptions,\n Pick<AnthropicInput, \"streamUsage\"> {\n tools?: ChatAnthropicToolType[];\n /**\n * Whether or not to specify what tool the model should use\n * @default \"auto\"\n */\n tool_choice?: AnthropicToolChoice;\n /**\n * Custom headers to pass to the Anthropic API\n * when making a request.\n */\n headers?: Record<string, string>;\n /**\n * Container ID for file persistence across turns with code execution.\n * Used with the code_execution_20250825 tool.\n */\n container?: string;\n}\n\nfunction _toolsInParams(\n params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams\n): boolean {\n return !!(params.tools && params.tools.length > 0);\n}\n\nfunction _documentsInParams(\n params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams\n): boolean {\n for (const message of params.messages ?? []) {\n if (typeof message.content === \"string\") {\n continue;\n }\n for (const block of message.content ?? []) {\n if (\n typeof block === \"object\" &&\n block != null &&\n block.type === \"document\" &&\n typeof block.citations === \"object\" &&\n block.citations?.enabled\n ) {\n return true;\n }\n }\n }\n return false;\n}\n\nfunction _thinkingInParams(\n params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams\n): boolean {\n return !!(params.thinking && params.thinking.type === \"enabled\");\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction isAnthropicTool(tool: any): tool is Anthropic.Messages.Tool {\n return \"input_schema\" in tool;\n}\n\nfunction isBuiltinTool(tool: unknown): tool is AnthropicBuiltInToolUnion {\n const builtInToolPrefixes = [\n \"text_editor_\",\n \"computer_\",\n \"bash_\",\n \"web_search_\",\n \"web_fetch_\",\n \"str_replace_editor_\",\n \"str_replace_based_edit_tool_\",\n \"code_execution_\",\n \"memory_\",\n ];\n return (\n typeof tool === \"object\" &&\n tool !== null &&\n \"type\" in tool &&\n \"name\" in tool &&\n typeof tool.type === \"string\" &&\n builtInToolPrefixes.some(\n (prefix) => typeof tool.type === \"string\" && tool.type.startsWith(prefix)\n )\n );\n}\n\n/**\n * @see https://docs.anthropic.com/claude/docs/models-overview\n */\nexport type AnthropicMessagesModelId =\n | Anthropic.Model\n | (string & NonNullable<unknown>);\n\n/**\n * Input to AnthropicChat class.\n */\nexport interface AnthropicInput {\n /** Amount of randomness injected into the response. Ranges\n * from 0 to 1. Use temp closer to 0 for analytical /\n * multiple choice, and temp closer to 1 for creative\n * and generative tasks.\n * To not set this field, pass `null`. If `undefined` is passed,\n * the default (1) will be used.\n */\n temperature?: number | null;\n\n /** Only sample from the top K options for each subsequent\n * token. Used to remove \"long tail\" low probability\n * responses. Defaults to -1, which disables it.\n */\n topK?: number;\n\n /** Does nucleus sampling, in which we compute the\n * cumulative distribution over all the options for each\n * subsequent token in decreasing probability order and\n * cut it off once it reaches a particular probability\n * specified by top_p. Defaults to -1, which disables it.\n * Note that you should either alter temperature or top_p,\n * but not both.\n *\n * To not set this field, pass `null`. If `undefined` is passed,\n * the default (-1) will be used.\n *\n * For Opus 4.1 and Sonnet 4.5, this defaults to `null`.\n */\n topP?: number | null;\n\n /** A maximum number of tokens to generate before stopping. */\n maxTokens?: number;\n\n /** A list of strings upon which to stop generating.\n * You probably want `[\"\\n\\nHuman:\"]`, as that's the cue for\n * the next turn in the dialog agent.\n */\n stopSequences?: string[];\n\n /** Whether to stream the results or not */\n streaming?: boolean;\n\n /** Anthropic API key */\n anthropicApiKey?: string;\n /** Anthropic API key */\n apiKey?: string;\n\n /** Anthropic API URL */\n anthropicApiUrl?: string;\n\n /** @deprecated Use \"model\" instead */\n modelName?: AnthropicMessagesModelId;\n /** Model name to use */\n model?: AnthropicMessagesModelId;\n\n /** Overridable Anthropic ClientOptions */\n clientOptions?: ClientOptions;\n\n /** Holds any additional parameters that are valid to pass to {@link\n * https://console.anthropic.com/docs/api/reference |\n * `anthropic.messages`} that are not explicitly specified on this class.\n */\n invocationKwargs?: Kwargs;\n\n /**\n * Whether or not to include token usage data in streamed chunks.\n * @default true\n */\n streamUsage?: boolean;\n\n /**\n * Optional method that returns an initialized underlying Anthropic client.\n * Useful for accessing Anthropic models hosted on other cloud services\n * such as Google Vertex.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n createClient?: (options: ClientOptions) => any;\n\n /**\n * Options for extended thinking.\n */\n thinking?: AnthropicThinkingConfigParam;\n\n /**\n * Configuration for context management. See https://docs.claude.com/en/docs/build-with-claude/context-editing\n */\n contextManagement?: AnthropicContextManagementConfigParam;\n}\n\n/**\n * A type representing additional parameters that can be passed to the\n * Anthropic API.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Kwargs = Record<string, any>;\n\nfunction extractToken(chunk: AIMessageChunk): string | undefined {\n if (typeof chunk.content === \"string\") {\n return chunk.content;\n } else if (\n Array.isArray(chunk.content) &&\n chunk.content.length >= 1 &&\n \"input\" in chunk.content[0]\n ) {\n return typeof chunk.content[0].input === \"string\"\n ? chunk.content[0].input\n : JSON.stringify(chunk.content[0].input);\n } else if (\n Array.isArray(chunk.content) &&\n chunk.content.length >= 1 &&\n \"text\" in chunk.content[0] &&\n typeof chunk.content[0].text === \"string\"\n ) {\n return chunk.content[0].text;\n }\n return undefined;\n}\n\n/**\n * Anthropic chat model integration.\n *\n * Setup:\n * Install `@langchain/anthropic` and set an environment variable named `ANTHROPIC_API_KEY`.\n *\n * ```bash\n * npm install @langchain/anthropic\n * export ANTHROPIC_API_KEY=\"your-api-key\"\n * ```\n *\n * ## [Constructor args](https://api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html#constructor)\n *\n * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_anthropic.ChatAnthropicCallOptions.html)\n *\n * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.\n * They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below:\n *\n * ```typescript\n * // When calling `.bind`, call options should be passed via the first argument\n * const llmWithArgsBound = llm.bindTools([...]).withConfig({\n * stop: [\"\\n\"],\n * });\n *\n * // When calling `.bindTools`, call options should be passed via the second argument\n * const llmWithTools = llm.bindTools(\n * [...],\n * {\n * tool_choice: \"auto\",\n * }\n * );\n * ```\n *\n * ## Examples\n *\n * <details open>\n * <summary><strong>Instantiate</strong></summary>\n *\n * ```typescript\n * import { ChatAnthropic } from '@langchain/anthropic';\n *\n * const llm = new ChatAnthropic({\n * model: \"claude-3-5-sonnet-20240620\",\n * temperature: 0,\n * maxTokens: undefined,\n * maxRetries: 2,\n * // apiKey: \"...\",\n * // baseUrl: \"...\",\n * // other params...\n * });\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Invoking</strong></summary>\n *\n * ```typescript\n * const input = `Translate \"I love programming\" into French.`;\n *\n * // Models also accept a list of chat messages or a formatted prompt\n * const result = await llm.invoke(input);\n * console.log(result);\n * ```\n *\n * ```txt\n * AIMessage {\n * \"id\": \"msg_01QDpd78JUHpRP6bRRNyzbW3\",\n * \"content\": \"Here's the translation to French:\\n\\nJ'adore la programmation.\",\n * \"response_metadata\": {\n * \"id\": \"msg_01QDpd78JUHpRP6bRRNyzbW3\",\n * \"model\": \"claude-3-5-sonnet-20240620\",\n * \"stop_reason\": \"end_turn\",\n * \"stop_sequence\": null,\n * \"usage\": {\n * \"input_tokens\": 25,\n * \"output_tokens\": 19\n * },\n * \"type\": \"message\",\n * \"role\": \"assistant\"\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 25,\n * \"output_tokens\": 19,\n * \"total_tokens\": 44\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Streaming Chunks</strong></summary>\n *\n * ```typescript\n * for await (const chunk of await llm.stream(input)) {\n * console.log(chunk);\n * }\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"id\": \"msg_01N8MwoYxiKo9w4chE4gXUs4\",\n * \"content\": \"\",\n * \"additional_kwargs\": {\n * \"id\": \"msg_01N8MwoYxiKo9w4chE4gXUs4\",\n * \"type\": \"message\",\n * \"role\": \"assistant\",\n * \"model\": \"claude-3-5-sonnet-20240620\"\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 25,\n * \"output_tokens\": 1,\n * \"total_tokens\": 26\n * }\n * }\n * AIMessageChunk {\n * \"content\": \"\",\n * }\n * AIMessageChunk {\n * \"content\": \"Here\",\n * }\n * AIMessageChunk {\n * \"content\": \"'s\",\n * }\n * AIMessageChunk {\n * \"content\": \" the translation to\",\n * }\n * AIMessageChunk {\n * \"content\": \" French:\\n\\nJ\",\n * }\n * AIMessageChunk {\n * \"content\": \"'adore la programmation\",\n * }\n * AIMessageChunk {\n * \"content\": \".\",\n * }\n * AIMessageChunk {\n * \"content\": \"\",\n * \"additional_kwargs\": {\n * \"stop_reason\": \"end_turn\",\n * \"stop_sequence\": null\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 0,\n * \"output_tokens\": 19,\n * \"total_tokens\": 19\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Aggregate Streamed Chunks</strong></summary>\n *\n * ```typescript\n * import { AIMessageChunk } from '@langchain/core/messages';\n * import { concat } from '@langchain/core/utils/stream';\n *\n * const stream = await llm.stream(input);\n * let full: AIMessageChunk | undefined;\n * for await (const chunk of stream) {\n * full = !full ? chunk : concat(full, chunk);\n * }\n * console.log(full);\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"id\": \"msg_01SBTb5zSGXfjUc7yQ8EKEEA\",\n * \"content\": \"Here's the translation to French:\\n\\nJ'adore la programmation.\",\n * \"additional_kwargs\": {\n * \"id\": \"msg_01SBTb5zSGXfjUc7yQ8EKEEA\",\n * \"type\": \"message\",\n * \"role\": \"assistant\",\n * \"model\": \"claude-3-5-sonnet-20240620\",\n * \"stop_reason\": \"end_turn\",\n * \"stop_sequence\": null\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 25,\n * \"output_tokens\": 20,\n * \"total_tokens\": 45\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Bind tools</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const GetWeather = {\n * name: \"GetWeather\",\n * description: \"Get the current weather in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const GetPopulation = {\n * name: \"GetPopulation\",\n * description: \"Get the current population in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);\n * const aiMsg = await llmWithTools.invoke(\n * \"Which city is hotter today and which is bigger: LA or NY?\"\n * );\n * console.log(aiMsg.tool_calls);\n * ```\n *\n * ```txt\n * [\n * {\n * name: 'GetWeather',\n * args: { location: 'Los Angeles, CA' },\n * id: 'toolu_01WjW3Dann6BPJVtLhovdBD5',\n * type: 'tool_call'\n * },\n * {\n * name: 'GetWeather',\n * args: { location: 'New York, NY' },\n * id: 'toolu_01G6wfJgqi5zRmJomsmkyZXe',\n * type: 'tool_call'\n * },\n * {\n * name: 'GetPopulation',\n * args: { location: 'Los Angeles, CA' },\n * id: 'toolu_0165qYWBA2VFyUst5RA18zew',\n * type: 'tool_call'\n * },\n * {\n * name: 'GetPopulation',\n * args: { location: 'New York, NY' },\n * id: 'toolu_01PGNyP33vxr13tGqr7i3rDo',\n * type: 'tool_call'\n * }\n * ]\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Structured Output</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const Joke = z.object({\n * setup: z.string().describe(\"The setup of the joke\"),\n * punchline: z.string().describe(\"The punchline to the joke\"),\n * rating: z.number().optional().describe(\"How funny the joke is, from 1 to 10\")\n * }).describe('Joke to tell user.');\n *\n * const structuredLlm = llm.withStructuredOutput(Joke, { name: \"Joke\" });\n * const jokeResult = await structuredLlm.invoke(\"Tell me a joke about cats\");\n * console.log(jokeResult);\n * ```\n *\n * ```txt\n * {\n * setup: \"Why don't cats play poker in the jungle?\",\n * punchline: 'Too many cheetahs!',\n * rating: 7\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Multimodal</strong></summary>\n *\n * ```typescript\n * import { HumanMessage } from '@langchain/core/messages';\n *\n * const imageUrl = \"https://example.com/image.jpg\";\n * const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());\n * const base64Image = Buffer.from(imageData).toString('base64');\n *\n * const message = new HumanMessage({\n * content: [\n * { type: \"text\", text: \"describe the weather in this image\" },\n * {\n * type: \"image_url\",\n * image_url: { url: `data:image/jpeg;base64,${base64Image}` },\n * },\n * ]\n * });\n *\n * const imageDescriptionAiMsg = await llm.invoke([message]);\n * console.log(imageDescriptionAiMsg.content);\n * ```\n *\n * ```txt\n * 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.\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Usage Metadata</strong></summary>\n *\n * ```typescript\n * const aiMsgForMetadata = await llm.invoke(input);\n * console.log(aiMsgForMetadata.usage_metadata);\n * ```\n *\n * ```txt\n * { input_tokens: 25, output_tokens: 19, total_tokens: 44 }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Stream Usage Metadata</strong></summary>\n *\n * ```typescript\n * const streamForMetadata = await llm.stream(\n * input,\n * {\n * streamUsage: true\n * }\n * );\n * let fullForMetadata: AIMessageChunk | undefined;\n * for await (const chunk of streamForMetadata) {\n * fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk);\n * }\n * console.log(fullForMetadata?.usage_metadata);\n * ```\n *\n * ```txt\n * { input_tokens: 25, output_tokens: 20, total_tokens: 45 }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Response Metadata</strong></summary>\n *\n * ```typescript\n * const aiMsgForResponseMetadata = await llm.invoke(input);\n * console.log(aiMsgForResponseMetadata.response_metadata);\n * ```\n *\n * ```txt\n * {\n * id: 'msg_01STxeQxJmp4sCSpioD6vK3L',\n * model: 'claude-3-5-sonnet-20240620',\n * stop_reason: 'end_turn',\n * stop_sequence: null,\n * usage: { input_tokens: 25, output_tokens: 19 },\n * type: 'message',\n * role: 'assistant'\n * }\n * ```\n * </details>\n *\n * <br />\n */\nexport class ChatAnthropicMessages<\n CallOptions extends ChatAnthropicCallOptions = ChatAnthropicCallOptions\n >\n extends BaseChatModel<CallOptions, AIMessageChunk>\n implements AnthropicInput\n{\n static lc_name() {\n return \"ChatAnthropic\";\n }\n\n get lc_secrets(): { [key: string]: string } | undefined {\n return {\n anthropicApiKey: \"ANTHROPIC_API_KEY\",\n apiKey: \"ANTHROPIC_API_KEY\",\n };\n }\n\n get lc_aliases(): Record<string, string> {\n return {\n modelName: \"model\",\n };\n }\n\n lc_serializable = true;\n\n anthropicApiKey?: string;\n\n apiKey?: string;\n\n apiUrl?: string;\n\n temperature: number | undefined = 1;\n\n topK = -1;\n\n topP: number | undefined = -1;\n\n maxTokens = 2048;\n\n modelName = \"claude-2.1\";\n\n model = \"claude-2.1\";\n\n invocationKwargs?: Kwargs;\n\n stopSequences?: string[];\n\n streaming = false;\n\n clientOptions: ClientOptions;\n\n thinking: AnthropicThinkingConfigParam = { type: \"disabled\" };\n\n contextManagement?: AnthropicContextManagementConfigParam;\n\n // Used for non-streaming requests\n protected batchClient: Anthropic;\n\n // Used for streaming requests\n protected streamingClient: Anthropic;\n\n streamUsage = true;\n\n /**\n * Optional method that returns an initialized underlying Anthropic client.\n * Useful for accessing Anthropic models hosted on other cloud services\n * such as Google Vertex.\n */\n createClient: (options: ClientOptions) => Anthropic;\n\n constructor(fields?: AnthropicInput & BaseChatModelParams) {\n super(fields ?? {});\n\n this.anthropicApiKey =\n fields?.apiKey ??\n fields?.anthropicApiKey ??\n getEnvironmentVariable(\"ANTHROPIC_API_KEY\");\n\n if (!this.anthropicApiKey && !fields?.createClient) {\n throw new Error(\"Anthropic API key not found\");\n }\n this.clientOptions = fields?.clientOptions ?? {};\n /** Keep anthropicApiKey for backwards compatibility */\n this.apiKey = this.anthropicApiKey;\n\n // Support overriding the default API URL (i.e., https://api.anthropic.com)\n this.apiUrl = fields?.anthropicApiUrl;\n\n /** Keep modelName for backwards compatibility */\n this.modelName = fields?.model ?? fields?.modelName ?? this.model;\n this.model = this.modelName;\n\n this.invocationKwargs = fields?.invocationKwargs ?? {};\n\n if (this.model.includes(\"opus-4-1\") || this.model.includes(\"sonnet-4-5\")) {\n // Default to `undefined` for `topP` for Opus 4.1 models\n this.topP = fields?.topP === null ? undefined : fields?.topP;\n } else {\n this.topP = fields?.topP ?? this.topP;\n }\n\n // If the user passes `null`, set it to `undefined`. Otherwise, use their value or the default. We have to check for null, because\n // there's no way for us to know if they explicitly set it to `undefined`, or never passed a value\n this.temperature =\n fields?.temperature === null\n ? undefined\n : fields?.temperature ?? this.temperature;\n this.topK = fields?.topK ?? this.topK;\n this.maxTokens = fields?.maxTokens ?? this.maxTokens;\n this.stopSequences = fields?.stopSequences ?? this.stopSequences;\n\n this.streaming = fields?.streaming ?? false;\n this.streamUsage = fields?.streamUsage ?? this.streamUsage;\n\n this.thinking = fields?.thinking ?? this.thinking;\n this.contextManagement =\n fields?.contextManagement ?? this.contextManagement;\n\n this.createClient =\n fields?.createClient ??\n ((options: ClientOptions) => new Anthropic(options));\n }\n\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams {\n const params = this.invocationParams(options);\n return {\n ls_provider: \"anthropic\",\n ls_model_name: this.model,\n ls_model_type: \"chat\",\n ls_temperature: params.temperature ?? undefined,\n ls_max_tokens: params.max_tokens ?? undefined,\n ls_stop: options.stop,\n };\n }\n\n /**\n * Formats LangChain StructuredTools to AnthropicTools.\n *\n * @param {ChatAnthropicCallOptions[\"tools\"]} tools The tools to format\n * @returns {AnthropicTool[] | undefined} The formatted tools, or undefined if none are passed.\n */\n formatStructuredToolToAnthropic(\n tools: ChatAnthropicCallOptions[\"tools\"]\n ): Anthropic.Messages.ToolUnion[] | undefined {\n if (!tools || !tools.length) {\n return undefined;\n }\n return tools.map((tool) => {\n if (isBuiltinTool(tool)) {\n return tool;\n }\n if (isAnthropicTool(tool)) {\n return tool;\n }\n if (isOpenAITool(tool)) {\n return {\n name: tool.function.name,\n description: tool.function.description,\n input_schema: tool.function\n .parameters as Anthropic.Messages.Tool.InputSchema,\n };\n }\n if (isLangChainTool(tool)) {\n return {\n name: tool.name,\n description: tool.description,\n input_schema: (isInteropZodSchema(tool.schema)\n ? toJsonSchema(tool.schema)\n : tool.schema) as Anthropic.Messages.Tool.InputSchema,\n };\n }\n throw new Error(\n `Unknown tool type passed to ChatAnthropic: ${JSON.stringify(\n tool,\n null,\n 2\n )}`\n );\n });\n }\n\n override bindTools(\n tools: ChatAnthropicToolType[],\n kwargs?: Partial<CallOptions>\n ): Runnable<BaseLanguageModelInput, AIMessageChunk, CallOptions> {\n return this.withConfig({\n tools: this.formatStructuredToolToAnthropic(tools),\n ...kwargs,\n } as Partial<CallOptions>);\n }\n\n /**\n * Get the parameters used to invoke the model\n */\n override invocationParams(\n options?: this[\"ParsedCallOptions\"]\n ): Omit<\n AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams,\n \"messages\"\n > &\n Kwargs {\n const tool_choice:\n | Anthropic.Messages.ToolChoiceAuto\n | Anthropic.Messages.ToolChoiceAny\n | Anthropic.Messages.ToolChoiceTool\n | Anthropic.Messages.ToolChoiceNone\n | undefined = handleToolChoice(options?.tool_choice);\n\n if (this.thinking.type === \"enabled\") {\n if (this.topK !== -1) {\n throw new Error(\"topK is not supported when thinking is enabled\");\n }\n if (\n this.model.includes(\"opus-4-1\") || this.model.includes(\"sonnet-4-5\")\n ? this.topP !== undefined\n : this.topP !== -1\n ) {\n throw new Error(\"topP is not supported when thinking is enabled\");\n }\n if (this.temperature !== 1) {\n throw new Error(\n \"temperature is not supported when thinking is enabled\"\n );\n }\n\n return {\n model: this.model,\n stop_sequences: options?.stop ?? this.stopSequences,\n stream: this.streaming,\n max_tokens: this.maxTokens,\n tools: this.formatStructuredToolToAnthropic(options?.tools),\n tool_choice,\n thinking: this.thinking,\n context_management: this.contextManagement,\n ...this.invocationKwargs,\n container: options?.container,\n };\n }\n return {\n model: this.model,\n temperature: this.temperature,\n top_k: this.topK,\n top_p: this.topP,\n stop_sequences: options?.stop ?? this.stopSequences,\n stream: this.streaming,\n max_tokens: this.maxTokens,\n tools: this.formatStructuredToolToAnthropic(options?.tools),\n tool_choice,\n thinking: this.thinking,\n context_management: this.contextManagement,\n ...this.invocationKwargs,\n container: options?.container,\n };\n }\n\n /** @ignore */\n _identifyingParams() {\n return {\n model_name: this.model,\n ...this.invocationParams(),\n };\n }\n\n /**\n * Get the identifying parameters for the model\n */\n identifyingParams() {\n return {\n model_name: this.model,\n ...this.invocationParams(),\n };\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const params = this.invocationParams(options);\n const formattedMessages = _convertMessagesToAnthropicPayload(messages);\n const payload = {\n ...params,\n ...formattedMessages,\n stream: true,\n } as const;\n const coerceContentToString =\n !_toolsInParams(payload) &&\n !_documentsInParams(payload) &&\n !_thinkingInParams(payload);\n\n const stream = await this.createStreamWithRetry(payload, {\n headers: options.headers,\n });\n\n for await (const data of stream) {\n if (options.signal?.aborted) {\n stream.controller.abort();\n throw new Error(\"AbortError: User aborted the request.\");\n }\n const shouldStreamUsage = this.streamUsage ?? options.streamUsage;\n const result = _makeMessageChunkFromAnthropicEvent(data, {\n streamUsage: shouldStreamUsage,\n coerceContentToString,\n });\n if (!result) continue;\n\n const { chunk } = result;\n\n // Extract the text content token for text field and runManager.\n const token = extractToken(chunk);\n const generationChunk = new ChatGenerationChunk({\n message: new AIMessageChunk({\n // Just yield chunk as it is and tool_use will be concat by BaseChatModel._generateUncached().\n content: chunk.content,\n additional_kwargs: chunk.additional_kwargs,\n tool_call_chunks: chunk.tool_call_chunks,\n usage_metadata: shouldStreamUsage ? chunk.usage_metadata : undefined,\n response_metadata: chunk.response_metadata,\n id: chunk.id,\n }),\n text: token ?? \"\",\n });\n yield generationChunk;\n\n await runManager?.handleLLMNewToken(\n token ?? \"\",\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk: generationChunk }\n );\n }\n }\n\n /** @ignore */\n async _generateNonStreaming(\n messages: BaseMessage[],\n params: Omit<\n | Anthropic.Messages.MessageCreateParamsNonStreaming\n | Anthropic.Messages.MessageCreateParamsStreaming,\n \"messages\"\n > &\n Kwargs,\n requestOptions: AnthropicRequestOptions\n ) {\n const response = await this.completionWithRetry(\n {\n ...params,\n stream: false,\n ..._convertMessagesToAnthropicPayload(messages),\n },\n requestOptions\n );\n\n const { content, ...additionalKwargs } = response;\n\n const generations = anthropicResponseToChatMessages(\n content,\n additionalKwargs\n );\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { role: _role, type: _type, ...rest } = additionalKwargs;\n return { generations, llmOutput: rest };\n }\n\n /** @ignore */\n async _generate(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n if (this.stopSequences && options.stop) {\n throw new Error(\n `\"stopSequence\" parameter found in input and default params`\n );\n }\n\n const params = this.invocationParams(options);\n if (params.stream) {\n let finalChunk: ChatGenerationChunk | undefined;\n const stream = this._streamResponseChunks(messages, options, runManager);\n for await (const chunk of stream) {\n if (finalChunk === undefined) {\n finalChunk = chunk;\n } else {\n finalChunk = finalChunk.concat(chunk);\n }\n }\n if (finalChunk === undefined) {\n throw new Error(\"No chunks returned from Anthropic API.\");\n }\n return {\n generations: [\n {\n text: finalChunk.text,\n message: finalChunk.message,\n },\n ],\n };\n } else {\n return this._generateNonStreaming(messages, params, {\n signal: options.signal,\n headers: options.headers,\n });\n }\n }\n\n /**\n * Creates a streaming request with retry.\n * @param request The parameters for creating a completion.\n * @param options\n * @returns A streaming request.\n */\n protected async createStreamWithRetry(\n request: AnthropicStreamingMessageCreateParams & Kwargs,\n options?: AnthropicRequestOptions\n ): Promise<Stream<AnthropicMessageStreamEvent>> {\n if (!this.streamingClient) {\n const options_ = this.apiUrl ? { baseURL: this.apiUrl } : undefined;\n this.streamingClient = this.createClient({\n dangerouslyAllowBrowser: true,\n ...this.clientOptions,\n ...options_,\n apiKey: this.apiKey,\n // Prefer LangChain built-in retries\n maxRetries: 0,\n });\n }\n const makeCompletionRequest = async () => {\n try {\n return await this.streamingClient.messages.create(\n {\n ...request,\n ...this.invocationKwargs,\n stream: true,\n } as AnthropicStreamingMessageCreateParams,\n options\n );\n } catch (e) {\n const error = wrapAnthropicClientError(e);\n throw error;\n }\n };\n return this.caller.call(makeCompletionRequest);\n }\n\n /** @ignore */\n protected async completionWithRetry(\n request: AnthropicMessageCreateParams & Kwargs,\n options: AnthropicRequestOptions\n ): Promise<Anthropic.Message> {\n if (!this.batchClient) {\n const options = this.apiUrl ? { baseURL: this.apiUrl } : undefined;\n this.batchClient = this.createClient({\n dangerouslyAllowBrowser: true,\n ...this.clientOptions,\n ...options,\n apiKey: this.apiKey,\n maxRetries: 0,\n });\n }\n const makeCompletionRequest = async () => {\n try {\n return await this.batchClient.messages.create(\n {\n ...request,\n ...this.invocationKwargs,\n } as AnthropicMessageCreateParams,\n options\n );\n } catch (e) {\n const error = wrapAnthropicClientError(e);\n throw error;\n }\n };\n return this.caller.callWithOptions(\n { signal: options.signal ?? undefined },\n makeCompletionRequest\n );\n }\n\n _llmType() {\n return \"anthropic\";\n }\n\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n > {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const schema: InteropZodType<RunOutput> | Record<string, any> =\n outputSchema;\n const name = config?.name;\n const method = config?.method;\n const includeRaw = config?.includeRaw;\n if (method === \"jsonMode\") {\n throw new Error(`Anthropic only supports \"functionCalling\" as a method.`);\n }\n\n let functionName = name ?? \"extract\";\n let outputParser: BaseLLMOutputParser<RunOutput>;\n let tools: Anthropic.Messages.Tool[];\n if (isInteropZodSchema(schema)) {\n const jsonSchema = toJsonSchema(schema);\n tools = [\n {\n name: functionName,\n description:\n jsonSchema.description ?? \"A function available to call.\",\n input_schema: jsonSchema as Anthropic.Messages.Tool.InputSchema,\n },\n ];\n outputParser = new AnthropicToolsOutputParser({\n returnSingle: true,\n keyName: functionName,\n zodSchema: schema,\n });\n } else {\n let anthropicTools: Anthropic.Messages.Tool;\n if (\n typeof schema.name === \"string\" &&\n typeof schema.description === \"string\" &&\n typeof schema.input_schema === \"object\" &&\n schema.input_schema != null\n ) {\n anthropicTools = schema as Anthropic.Messages.Tool;\n functionName = schema.name;\n } else {\n anthropicTools = {\n name: functionName,\n description: schema.description ?? \"\",\n input_schema: schema as Anthropic.Messages.Tool.InputSchema,\n };\n }\n tools = [anthropicTools];\n outputParser = new AnthropicToolsOutputParser<RunOutput>({\n returnSingle: true,\n keyName: functionName,\n });\n }\n let llm;\n if (this.thinking?.type === \"enabled\") {\n const thinkingAdmonition =\n \"Anthropic structured output relies on forced tool calling, \" +\n \"which is not supported when `thinking` is enabled. This method will raise \" +\n \"OutputParserException if tool calls are not \" +\n \"generated. Consider disabling `thinking` or adjust your prompt to ensure \" +\n \"the tool is called.\";\n\n console.warn(thinkingAdmonition);\n\n llm = this.withConfig({\n tools,\n ls_structured_output_format: {\n kwargs: { method: \"functionCalling\" },\n schema: toJsonSchema(schema),\n },\n } as Partial<CallOptions>);\n\n const raiseIfNoToolCalls = (message: AIMessageChunk) => {\n if (!message.tool_calls || message.tool_calls.length === 0) {\n throw new Error(thinkingAdmonition);\n }\n return message;\n };\n\n llm = llm.pipe(raiseIfNoToolCalls);\n } else {\n llm = this.withConfig({\n tools,\n tool_choice: {\n type: \"tool\",\n name: functionName,\n },\n ls_structured_output_format: {\n kwargs: { method: \"functionCalling\" },\n schema: toJsonSchema(schema),\n },\n } as Partial<CallOptions>);\n }\n\n if (!includeRaw) {\n return llm.pipe(outputParser).withConfig({\n runName: \"ChatAnthropicStructuredOutput\",\n }) as Runnable<BaseLanguageModelInput, RunOutput>;\n }\n\n const parserAssign = RunnablePassthrough.assign({\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parsed: (input: any, config) => outputParser.invoke(input.raw, config),\n });\n const parserNone = RunnablePassthrough.assign({\n parsed: () => null,\n });\n const parsedWithFallback = parserAssign.withFallbacks({\n fallbacks: [parserNone],\n });\n return RunnableSequence.from<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n >([\n {\n raw: llm,\n },\n parsedWithFallback,\n ]).withConfig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,SAAS;GACV;EACF;EACD,IAAI;AACJ,MAAI,KAAK,UAAU,SAAS,WAAW;GACrC,MAAM,qBACJ;GAMF,QAAQ,KAAK,mBAAmB;GAEhC,MAAM,KAAK,WAAW;IACpB;IACA,6BAA6B;KAC3B,QAAQ,EAAE,QAAQ,kBAAmB;KACrC,6DAAqB,OAAO;IAC7B;GACF,EAAyB;GAE1B,MAAM,qBAAqB,CAACE,YAA4B;AACtD,QAAI,CAAC,QAAQ,cAAc,QAAQ,WAAW,WAAW,EACvD,OAAM,IAAI,MAAM;AAElB,WAAO;GACR;GAED,MAAM,IAAI,KAAK,mBAAmB;EACnC,OACC,MAAM,KAAK,WAAW;GACpB;GACA,aAAa;IACX,MAAM;IACN,MAAM;GACP;GACD,6BAA6B;IAC3B,QAAQ,EAAE,QAAQ,kBAAmB;IACrC,6DAAqB,OAAO;GAC7B;EACF,EAAyB;AAG5B,MAAI,CAAC,WACH,QAAO,IAAI,KAAK,aAAa,CAAC,WAAW,EACvC,SAAS,gCACV,EAAC;EAGJ,MAAM,eAAeC,+CAAoB,OAAO,EAE9C,QAAQ,CAACC,OAAYC,aAAW,aAAa,OAAO,MAAM,KAAKA,SAAO,CACvE,EAAC;EACF,MAAM,aAAaF,+CAAoB,OAAO,EAC5C,QAAQ,MAAM,KACf,EAAC;EACF,MAAM,qBAAqB,aAAa,cAAc,EACpD,WAAW,CAAC,UAAW,EACxB,EAAC;AACF,SAAOG,4CAAiB,KAGtB,CACA,EACE,KAAK,IACN,GACD,kBACD,EAAC,CAAC,WAAW,EACZ,SAAS,2BACV,EAAC;CACH;AACF;AAED,IAAa,gBAAb,cAAmC,sBAAsB,CAAE"}
@@ -1,4 +1,4 @@
1
- import { AnthropicMessageCreateParams, AnthropicMessageStreamEvent, AnthropicRequestOptions, AnthropicStreamingMessageCreateParams, AnthropicThinkingConfigParam, AnthropicToolChoice, ChatAnthropicToolType } from "./types.cjs";
1
+ import { AnthropicContextManagementConfigParam, AnthropicMessageCreateParams, AnthropicMessageStreamEvent, AnthropicRequestOptions, AnthropicStreamingMessageCreateParams, AnthropicThinkingConfigParam, AnthropicToolChoice, ChatAnthropicToolType } from "./types.cjs";
2
2
  import * as _langchain_core_outputs0 from "@langchain/core/outputs";
3
3
  import { ChatGenerationChunk, ChatResult } from "@langchain/core/outputs";
4
4
  import { Anthropic as Anthropic$1, ClientOptions } from "@anthropic-ai/sdk";
@@ -23,6 +23,11 @@ interface ChatAnthropicCallOptions extends BaseChatModelCallOptions, Pick<Anthro
23
23
  * when making a request.
24
24
  */
25
25
  headers?: Record<string, string>;
26
+ /**
27
+ * Container ID for file persistence across turns with code execution.
28
+ * Used with the code_execution_20250825 tool.
29
+ */
30
+ container?: string;
26
31
  }
27
32
  /**
28
33
  * @see https://docs.anthropic.com/claude/docs/models-overview
@@ -56,16 +61,11 @@ interface AnthropicInput {
56
61
  * To not set this field, pass `null`. If `undefined` is passed,
57
62
  * the default (-1) will be used.
58
63
  *
59
- * For Opus 4.1, this defaults to `null`.
64
+ * For Opus 4.1 and Sonnet 4.5, this defaults to `null`.
60
65
  */
61
66
  topP?: number | null;
62
67
  /** A maximum number of tokens to generate before stopping. */
63
68
  maxTokens?: number;
64
- /**
65
- * A maximum number of tokens to generate before stopping.
66
- * @deprecated Use "maxTokens" instead.
67
- */
68
- maxTokensToSample?: number;
69
69
  /** A list of strings upon which to stop generating.
70
70
  * You probably want `["\n\nHuman:"]`, as that's the cue for
71
71
  * the next turn in the dialog agent.
@@ -106,6 +106,10 @@ interface AnthropicInput {
106
106
  * Options for extended thinking.
107
107
  */
108
108
  thinking?: AnthropicThinkingConfigParam;
109
+ /**
110
+ * Configuration for context management. See https://docs.claude.com/en/docs/build-with-claude/context-editing
111
+ */
112
+ contextManagement?: AnthropicContextManagementConfigParam;
109
113
  }
110
114
  /**
111
115
  * A type representing additional parameters that can be passed to the
@@ -510,6 +514,7 @@ declare class ChatAnthropicMessages<CallOptions extends ChatAnthropicCallOptions
510
514
  streaming: boolean;
511
515
  clientOptions: ClientOptions;
512
516
  thinking: AnthropicThinkingConfigParam;
517
+ contextManagement?: AnthropicContextManagementConfigParam;
513
518
  // Used for non-streaming requests
514
519
  protected batchClient: Anthropic$1;
515
520
  // Used for streaming requests
@@ -1 +1 @@
1
- {"version":3,"file":"chat_models.d.cts","names":["Anthropic","ClientOptions","Stream","CallbackManagerForLLMRun","AIMessageChunk","BaseMessage","ChatGenerationChunk","ChatResult","BaseChatModel","BaseChatModelCallOptions","LangSmithParams","BaseChatModelParams","StructuredOutputMethodOptions","BaseLanguageModelInput","Runnable","InteropZodType","AnthropicMessageCreateParams","AnthropicMessageStreamEvent","AnthropicRequestOptions","AnthropicStreamingMessageCreateParams","AnthropicThinkingConfigParam","AnthropicToolChoice","ChatAnthropicToolType","ChatAnthropicCallOptions","AnthropicInput","Record","Pick","AnthropicMessagesModelId","Model","NonNullable","Kwargs","ChatAnthropicMessages","CallOptions","Messages","ToolUnion","Partial","Omit","Metadata","TextBlockParam","ThinkingConfigParam","ToolChoice","AsyncGenerator","MessageCreateParamsNonStreaming","MessageCreateParamsStreaming","_langchain_core_outputs0","ChatGeneration","StopReason","Usage","Promise","Message","RunOutput","ChatAnthropic"],"sources":["../src/chat_models.d.ts"],"sourcesContent":["import { Anthropic, type ClientOptions } from \"@anthropic-ai/sdk\";\nimport type { Stream } from \"@anthropic-ai/sdk/streaming\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport { AIMessageChunk, type BaseMessage } from \"@langchain/core/messages\";\nimport { ChatGenerationChunk, type ChatResult } from \"@langchain/core/outputs\";\nimport { BaseChatModel, BaseChatModelCallOptions, LangSmithParams, type BaseChatModelParams } from \"@langchain/core/language_models/chat_models\";\nimport { type StructuredOutputMethodOptions, type BaseLanguageModelInput } from \"@langchain/core/language_models/base\";\nimport { Runnable } from \"@langchain/core/runnables\";\nimport { InteropZodType } from \"@langchain/core/utils/types\";\nimport { AnthropicMessageCreateParams, AnthropicMessageStreamEvent, AnthropicRequestOptions, AnthropicStreamingMessageCreateParams, AnthropicThinkingConfigParam, AnthropicToolChoice, ChatAnthropicToolType } from \"./types.js\";\nexport interface ChatAnthropicCallOptions extends BaseChatModelCallOptions, Pick<AnthropicInput, \"streamUsage\"> {\n tools?: ChatAnthropicToolType[];\n /**\n * Whether or not to specify what tool the model should use\n * @default \"auto\"\n */\n tool_choice?: AnthropicToolChoice;\n /**\n * Custom headers to pass to the Anthropic API\n * when making a request.\n */\n headers?: Record<string, string>;\n}\n/**\n * @see https://docs.anthropic.com/claude/docs/models-overview\n */\nexport type AnthropicMessagesModelId = Anthropic.Model | (string & NonNullable<unknown>);\n/**\n * Input to AnthropicChat class.\n */\nexport interface AnthropicInput {\n /** Amount of randomness injected into the response. Ranges\n * from 0 to 1. Use temp closer to 0 for analytical /\n * multiple choice, and temp closer to 1 for creative\n * and generative tasks.\n * To not set this field, pass `null`. If `undefined` is passed,\n * the default (1) will be used.\n */\n temperature?: number | null;\n /** Only sample from the top K options for each subsequent\n * token. Used to remove \"long tail\" low probability\n * responses. Defaults to -1, which disables it.\n */\n topK?: number;\n /** Does nucleus sampling, in which we compute the\n * cumulative distribution over all the options for each\n * subsequent token in decreasing probability order and\n * cut it off once it reaches a particular probability\n * specified by top_p. Defaults to -1, which disables it.\n * Note that you should either alter temperature or top_p,\n * but not both.\n *\n * To not set this field, pass `null`. If `undefined` is passed,\n * the default (-1) will be used.\n *\n * For Opus 4.1, this defaults to `null`.\n */\n topP?: number | null;\n /** A maximum number of tokens to generate before stopping. */\n maxTokens?: number;\n /**\n * A maximum number of tokens to generate before stopping.\n * @deprecated Use \"maxTokens\" instead.\n */\n maxTokensToSample?: number;\n /** A list of strings upon which to stop generating.\n * You probably want `[\"\\n\\nHuman:\"]`, as that's the cue for\n * the next turn in the dialog agent.\n */\n stopSequences?: string[];\n /** Whether to stream the results or not */\n streaming?: boolean;\n /** Anthropic API key */\n anthropicApiKey?: string;\n /** Anthropic API key */\n apiKey?: string;\n /** Anthropic API URL */\n anthropicApiUrl?: string;\n /** @deprecated Use \"model\" instead */\n modelName?: AnthropicMessagesModelId;\n /** Model name to use */\n model?: AnthropicMessagesModelId;\n /** Overridable Anthropic ClientOptions */\n clientOptions?: ClientOptions;\n /** Holds any additional parameters that are valid to pass to {@link\n * https://console.anthropic.com/docs/api/reference |\n * `anthropic.messages`} that are not explicitly specified on this class.\n */\n invocationKwargs?: Kwargs;\n /**\n * Whether or not to include token usage data in streamed chunks.\n * @default true\n */\n streamUsage?: boolean;\n /**\n * Optional method that returns an initialized underlying Anthropic client.\n * Useful for accessing Anthropic models hosted on other cloud services\n * such as Google Vertex.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n createClient?: (options: ClientOptions) => any;\n /**\n * Options for extended thinking.\n */\n thinking?: AnthropicThinkingConfigParam;\n}\n/**\n * A type representing additional parameters that can be passed to the\n * Anthropic API.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Kwargs = Record<string, any>;\n/**\n * Anthropic chat model integration.\n *\n * Setup:\n * Install `@langchain/anthropic` and set an environment variable named `ANTHROPIC_API_KEY`.\n *\n * ```bash\n * npm install @langchain/anthropic\n * export ANTHROPIC_API_KEY=\"your-api-key\"\n * ```\n *\n * ## [Constructor args](https://api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html#constructor)\n *\n * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_anthropic.ChatAnthropicCallOptions.html)\n *\n * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.\n * They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below:\n *\n * ```typescript\n * // When calling `.bind`, call options should be passed via the first argument\n * const llmWithArgsBound = llm.bindTools([...]).withConfig({\n * stop: [\"\\n\"],\n * });\n *\n * // When calling `.bindTools`, call options should be passed via the second argument\n * const llmWithTools = llm.bindTools(\n * [...],\n * {\n * tool_choice: \"auto\",\n * }\n * );\n * ```\n *\n * ## Examples\n *\n * <details open>\n * <summary><strong>Instantiate</strong></summary>\n *\n * ```typescript\n * import { ChatAnthropic } from '@langchain/anthropic';\n *\n * const llm = new ChatAnthropic({\n * model: \"claude-3-5-sonnet-20240620\",\n * temperature: 0,\n * maxTokens: undefined,\n * maxRetries: 2,\n * // apiKey: \"...\",\n * // baseUrl: \"...\",\n * // other params...\n * });\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Invoking</strong></summary>\n *\n * ```typescript\n * const input = `Translate \"I love programming\" into French.`;\n *\n * // Models also accept a list of chat messages or a formatted prompt\n * const result = await llm.invoke(input);\n * console.log(result);\n * ```\n *\n * ```txt\n * AIMessage {\n * \"id\": \"msg_01QDpd78JUHpRP6bRRNyzbW3\",\n * \"content\": \"Here's the translation to French:\\n\\nJ'adore la programmation.\",\n * \"response_metadata\": {\n * \"id\": \"msg_01QDpd78JUHpRP6bRRNyzbW3\",\n * \"model\": \"claude-3-5-sonnet-20240620\",\n * \"stop_reason\": \"end_turn\",\n * \"stop_sequence\": null,\n * \"usage\": {\n * \"input_tokens\": 25,\n * \"output_tokens\": 19\n * },\n * \"type\": \"message\",\n * \"role\": \"assistant\"\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 25,\n * \"output_tokens\": 19,\n * \"total_tokens\": 44\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Streaming Chunks</strong></summary>\n *\n * ```typescript\n * for await (const chunk of await llm.stream(input)) {\n * console.log(chunk);\n * }\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"id\": \"msg_01N8MwoYxiKo9w4chE4gXUs4\",\n * \"content\": \"\",\n * \"additional_kwargs\": {\n * \"id\": \"msg_01N8MwoYxiKo9w4chE4gXUs4\",\n * \"type\": \"message\",\n * \"role\": \"assistant\",\n * \"model\": \"claude-3-5-sonnet-20240620\"\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 25,\n * \"output_tokens\": 1,\n * \"total_tokens\": 26\n * }\n * }\n * AIMessageChunk {\n * \"content\": \"\",\n * }\n * AIMessageChunk {\n * \"content\": \"Here\",\n * }\n * AIMessageChunk {\n * \"content\": \"'s\",\n * }\n * AIMessageChunk {\n * \"content\": \" the translation to\",\n * }\n * AIMessageChunk {\n * \"content\": \" French:\\n\\nJ\",\n * }\n * AIMessageChunk {\n * \"content\": \"'adore la programmation\",\n * }\n * AIMessageChunk {\n * \"content\": \".\",\n * }\n * AIMessageChunk {\n * \"content\": \"\",\n * \"additional_kwargs\": {\n * \"stop_reason\": \"end_turn\",\n * \"stop_sequence\": null\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 0,\n * \"output_tokens\": 19,\n * \"total_tokens\": 19\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Aggregate Streamed Chunks</strong></summary>\n *\n * ```typescript\n * import { AIMessageChunk } from '@langchain/core/messages';\n * import { concat } from '@langchain/core/utils/stream';\n *\n * const stream = await llm.stream(input);\n * let full: AIMessageChunk | undefined;\n * for await (const chunk of stream) {\n * full = !full ? chunk : concat(full, chunk);\n * }\n * console.log(full);\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"id\": \"msg_01SBTb5zSGXfjUc7yQ8EKEEA\",\n * \"content\": \"Here's the translation to French:\\n\\nJ'adore la programmation.\",\n * \"additional_kwargs\": {\n * \"id\": \"msg_01SBTb5zSGXfjUc7yQ8EKEEA\",\n * \"type\": \"message\",\n * \"role\": \"assistant\",\n * \"model\": \"claude-3-5-sonnet-20240620\",\n * \"stop_reason\": \"end_turn\",\n * \"stop_sequence\": null\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 25,\n * \"output_tokens\": 20,\n * \"total_tokens\": 45\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Bind tools</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const GetWeather = {\n * name: \"GetWeather\",\n * description: \"Get the current weather in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const GetPopulation = {\n * name: \"GetPopulation\",\n * description: \"Get the current population in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);\n * const aiMsg = await llmWithTools.invoke(\n * \"Which city is hotter today and which is bigger: LA or NY?\"\n * );\n * console.log(aiMsg.tool_calls);\n * ```\n *\n * ```txt\n * [\n * {\n * name: 'GetWeather',\n * args: { location: 'Los Angeles, CA' },\n * id: 'toolu_01WjW3Dann6BPJVtLhovdBD5',\n * type: 'tool_call'\n * },\n * {\n * name: 'GetWeather',\n * args: { location: 'New York, NY' },\n * id: 'toolu_01G6wfJgqi5zRmJomsmkyZXe',\n * type: 'tool_call'\n * },\n * {\n * name: 'GetPopulation',\n * args: { location: 'Los Angeles, CA' },\n * id: 'toolu_0165qYWBA2VFyUst5RA18zew',\n * type: 'tool_call'\n * },\n * {\n * name: 'GetPopulation',\n * args: { location: 'New York, NY' },\n * id: 'toolu_01PGNyP33vxr13tGqr7i3rDo',\n * type: 'tool_call'\n * }\n * ]\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Structured Output</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const Joke = z.object({\n * setup: z.string().describe(\"The setup of the joke\"),\n * punchline: z.string().describe(\"The punchline to the joke\"),\n * rating: z.number().optional().describe(\"How funny the joke is, from 1 to 10\")\n * }).describe('Joke to tell user.');\n *\n * const structuredLlm = llm.withStructuredOutput(Joke, { name: \"Joke\" });\n * const jokeResult = await structuredLlm.invoke(\"Tell me a joke about cats\");\n * console.log(jokeResult);\n * ```\n *\n * ```txt\n * {\n * setup: \"Why don't cats play poker in the jungle?\",\n * punchline: 'Too many cheetahs!',\n * rating: 7\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Multimodal</strong></summary>\n *\n * ```typescript\n * import { HumanMessage } from '@langchain/core/messages';\n *\n * const imageUrl = \"https://example.com/image.jpg\";\n * const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());\n * const base64Image = Buffer.from(imageData).toString('base64');\n *\n * const message = new HumanMessage({\n * content: [\n * { type: \"text\", text: \"describe the weather in this image\" },\n * {\n * type: \"image_url\",\n * image_url: { url: `data:image/jpeg;base64,${base64Image}` },\n * },\n * ]\n * });\n *\n * const imageDescriptionAiMsg = await llm.invoke([message]);\n * console.log(imageDescriptionAiMsg.content);\n * ```\n *\n * ```txt\n * 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.\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Usage Metadata</strong></summary>\n *\n * ```typescript\n * const aiMsgForMetadata = await llm.invoke(input);\n * console.log(aiMsgForMetadata.usage_metadata);\n * ```\n *\n * ```txt\n * { input_tokens: 25, output_tokens: 19, total_tokens: 44 }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Stream Usage Metadata</strong></summary>\n *\n * ```typescript\n * const streamForMetadata = await llm.stream(\n * input,\n * {\n * streamUsage: true\n * }\n * );\n * let fullForMetadata: AIMessageChunk | undefined;\n * for await (const chunk of streamForMetadata) {\n * fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk);\n * }\n * console.log(fullForMetadata?.usage_metadata);\n * ```\n *\n * ```txt\n * { input_tokens: 25, output_tokens: 20, total_tokens: 45 }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Response Metadata</strong></summary>\n *\n * ```typescript\n * const aiMsgForResponseMetadata = await llm.invoke(input);\n * console.log(aiMsgForResponseMetadata.response_metadata);\n * ```\n *\n * ```txt\n * {\n * id: 'msg_01STxeQxJmp4sCSpioD6vK3L',\n * model: 'claude-3-5-sonnet-20240620',\n * stop_reason: 'end_turn',\n * stop_sequence: null,\n * usage: { input_tokens: 25, output_tokens: 19 },\n * type: 'message',\n * role: 'assistant'\n * }\n * ```\n * </details>\n *\n * <br />\n */\nexport declare class ChatAnthropicMessages<CallOptions extends ChatAnthropicCallOptions = ChatAnthropicCallOptions> extends BaseChatModel<CallOptions, AIMessageChunk> implements AnthropicInput {\n static lc_name(): string;\n get lc_secrets(): {\n [key: string]: string;\n } | undefined;\n get lc_aliases(): Record<string, string>;\n lc_serializable: boolean;\n anthropicApiKey?: string;\n apiKey?: string;\n apiUrl?: string;\n temperature: number | undefined;\n topK: number;\n topP: number | undefined;\n maxTokens: number;\n modelName: string;\n model: string;\n invocationKwargs?: Kwargs;\n stopSequences?: string[];\n streaming: boolean;\n clientOptions: ClientOptions;\n thinking: AnthropicThinkingConfigParam;\n // Used for non-streaming requests\n protected batchClient: Anthropic;\n // Used for streaming requests\n protected streamingClient: Anthropic;\n streamUsage: boolean;\n /**\n * Optional method that returns an initialized underlying Anthropic client.\n * Useful for accessing Anthropic models hosted on other cloud services\n * such as Google Vertex.\n */\n createClient: (options: ClientOptions) => Anthropic;\n constructor(fields?: AnthropicInput & BaseChatModelParams);\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams;\n /**\n * Formats LangChain StructuredTools to AnthropicTools.\n *\n * @param {ChatAnthropicCallOptions[\"tools\"]} tools The tools to format\n * @returns {AnthropicTool[] | undefined} The formatted tools, or undefined if none are passed.\n */\n formatStructuredToolToAnthropic(tools: ChatAnthropicCallOptions[\"tools\"]): Anthropic.Messages.ToolUnion[] | undefined;\n bindTools(tools: ChatAnthropicToolType[], kwargs?: Partial<CallOptions>): Runnable<BaseLanguageModelInput, AIMessageChunk, CallOptions>;\n /**\n * Get the parameters used to invoke the model\n */\n invocationParams(options?: this[\"ParsedCallOptions\"]): Omit<AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams, \"messages\"> & Kwargs;\n /** @ignore */\n _identifyingParams(): {\n max_tokens: number;\n model: Anthropic.Model;\n metadata?: Anthropic.Metadata | undefined;\n service_tier?: \"auto\" | \"standard_only\" | undefined;\n stop_sequences?: string[] | undefined;\n system?: string | Anthropic.TextBlockParam[] | undefined;\n temperature?: number | undefined;\n thinking?: Anthropic.ThinkingConfigParam | undefined;\n tool_choice?: Anthropic.ToolChoice | undefined;\n tools?: Anthropic.ToolUnion[] | undefined;\n top_k?: number | undefined;\n top_p?: number | undefined;\n stream?: boolean | undefined;\n model_name: string;\n };\n /**\n * Get the identifying parameters for the model\n */\n identifyingParams(): {\n max_tokens: number;\n model: Anthropic.Model;\n metadata?: Anthropic.Metadata | undefined;\n service_tier?: \"auto\" | \"standard_only\" | undefined;\n stop_sequences?: string[] | undefined;\n system?: string | Anthropic.TextBlockParam[] | undefined;\n temperature?: number | undefined;\n thinking?: Anthropic.ThinkingConfigParam | undefined;\n tool_choice?: Anthropic.ToolChoice | undefined;\n tools?: Anthropic.ToolUnion[] | undefined;\n top_k?: number | undefined;\n top_p?: number | undefined;\n stream?: boolean | undefined;\n model_name: string;\n };\n _streamResponseChunks(messages: BaseMessage[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;\n /** @ignore */\n _generateNonStreaming(messages: BaseMessage[], params: Omit<Anthropic.Messages.MessageCreateParamsNonStreaming | Anthropic.Messages.MessageCreateParamsStreaming, \"messages\"> & Kwargs, requestOptions: AnthropicRequestOptions): Promise<{\n generations: import(\"@langchain/core/outputs\").ChatGeneration[];\n llmOutput: {\n id: string;\n model: Anthropic.Model;\n stop_reason: Anthropic.StopReason | null;\n stop_sequence: string | null;\n usage: Anthropic.Usage;\n };\n }>;\n /** @ignore */\n _generate(messages: BaseMessage[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;\n /**\n * Creates a streaming request with retry.\n * @param request The parameters for creating a completion.\n * @param options\n * @returns A streaming request.\n */\n protected createStreamWithRetry(request: AnthropicStreamingMessageCreateParams & Kwargs, options?: AnthropicRequestOptions): Promise<Stream<AnthropicMessageStreamEvent>>;\n /** @ignore */\n protected completionWithRetry(request: AnthropicMessageCreateParams & Kwargs, options: AnthropicRequestOptions): Promise<Anthropic.Message>;\n _llmType(): string;\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {\n raw: BaseMessage;\n parsed: RunOutput;\n }>;\n}\nexport declare class ChatAnthropic extends ChatAnthropicMessages {\n}\nexport {};\n"],"mappings":";;;;;;;;;;;;;UAUiBuB,wBAAAA,SAAiCd,0BAA0BiB,KAAKF;UACrEF;;AADZ;;;EAA+F,WACnFA,CAAAA,EAKMD,mBALNC;EAAqB;;;;EAD+C,OAAA,CAAA,EAWlEG,MAXkE,CAAA,MAAA,EAAA,MAAA,CAAA;AAgBhF;;;;AAA8E,KAAlEE,wBAAAA,GAA2B3B,WAAAA,CAAU4B,KAA6B,GAAA,CAAA,MAAA,GAAXC,WAAW,CAAA,OAAA,CAAA,CAAA;AAI9E;;;AAmDYF,UAnDKH,cAAAA,CAmDLG;EAAwB;;;;AAuBO;AAC1C;AA+XD;EAA0C,WAAA,CAAA,EAAA,MAAA,GAAA,IAAA;EAAA;;;;EAA2H,IAK/IF,CAAAA,EAAAA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AAUiD;;;;oBAIjHxB,sBAAsBA,mCAAmCV,eAAemC;;IAEvFzB,8BAA8Bb,uCAAuCE,SAASD,wBAAwBqC;;;oBAGvFzB,sBAAsBA,mCAAmCV,eAAemC;;IAEvFzB,8BAA8Bb,sCAAsCE,SAASD;SACvER;YACG6C;;;cAGKC,aAAAA,SAAsBpB,qBAAqB"}
1
+ {"version":3,"file":"chat_models.d.cts","names":["Anthropic","ClientOptions","Stream","CallbackManagerForLLMRun","AIMessageChunk","BaseMessage","ChatGenerationChunk","ChatResult","BaseChatModel","BaseChatModelCallOptions","LangSmithParams","BaseChatModelParams","StructuredOutputMethodOptions","BaseLanguageModelInput","Runnable","InteropZodType","AnthropicContextManagementConfigParam","AnthropicMessageCreateParams","AnthropicMessageStreamEvent","AnthropicRequestOptions","AnthropicStreamingMessageCreateParams","AnthropicThinkingConfigParam","AnthropicToolChoice","ChatAnthropicToolType","ChatAnthropicCallOptions","AnthropicInput","Record","Pick","AnthropicMessagesModelId","Model","NonNullable","Kwargs","ChatAnthropicMessages","CallOptions","Messages","ToolUnion","Partial","Omit","Metadata","TextBlockParam","ThinkingConfigParam","ToolChoice","AsyncGenerator","MessageCreateParamsNonStreaming","MessageCreateParamsStreaming","_langchain_core_outputs0","ChatGeneration","StopReason","Usage","Promise","Message","RunOutput","ChatAnthropic"],"sources":["../src/chat_models.d.ts"],"sourcesContent":["import { Anthropic, type ClientOptions } from \"@anthropic-ai/sdk\";\nimport type { Stream } from \"@anthropic-ai/sdk/streaming\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport { AIMessageChunk, type BaseMessage } from \"@langchain/core/messages\";\nimport { ChatGenerationChunk, type ChatResult } from \"@langchain/core/outputs\";\nimport { BaseChatModel, BaseChatModelCallOptions, LangSmithParams, type BaseChatModelParams } from \"@langchain/core/language_models/chat_models\";\nimport { type StructuredOutputMethodOptions, type BaseLanguageModelInput } from \"@langchain/core/language_models/base\";\nimport { Runnable } from \"@langchain/core/runnables\";\nimport { InteropZodType } from \"@langchain/core/utils/types\";\nimport { AnthropicContextManagementConfigParam, AnthropicMessageCreateParams, AnthropicMessageStreamEvent, AnthropicRequestOptions, AnthropicStreamingMessageCreateParams, AnthropicThinkingConfigParam, AnthropicToolChoice, ChatAnthropicToolType } from \"./types.js\";\nexport interface ChatAnthropicCallOptions extends BaseChatModelCallOptions, Pick<AnthropicInput, \"streamUsage\"> {\n tools?: ChatAnthropicToolType[];\n /**\n * Whether or not to specify what tool the model should use\n * @default \"auto\"\n */\n tool_choice?: AnthropicToolChoice;\n /**\n * Custom headers to pass to the Anthropic API\n * when making a request.\n */\n headers?: Record<string, string>;\n /**\n * Container ID for file persistence across turns with code execution.\n * Used with the code_execution_20250825 tool.\n */\n container?: string;\n}\n/**\n * @see https://docs.anthropic.com/claude/docs/models-overview\n */\nexport type AnthropicMessagesModelId = Anthropic.Model | (string & NonNullable<unknown>);\n/**\n * Input to AnthropicChat class.\n */\nexport interface AnthropicInput {\n /** Amount of randomness injected into the response. Ranges\n * from 0 to 1. Use temp closer to 0 for analytical /\n * multiple choice, and temp closer to 1 for creative\n * and generative tasks.\n * To not set this field, pass `null`. If `undefined` is passed,\n * the default (1) will be used.\n */\n temperature?: number | null;\n /** Only sample from the top K options for each subsequent\n * token. Used to remove \"long tail\" low probability\n * responses. Defaults to -1, which disables it.\n */\n topK?: number;\n /** Does nucleus sampling, in which we compute the\n * cumulative distribution over all the options for each\n * subsequent token in decreasing probability order and\n * cut it off once it reaches a particular probability\n * specified by top_p. Defaults to -1, which disables it.\n * Note that you should either alter temperature or top_p,\n * but not both.\n *\n * To not set this field, pass `null`. If `undefined` is passed,\n * the default (-1) will be used.\n *\n * For Opus 4.1 and Sonnet 4.5, this defaults to `null`.\n */\n topP?: number | null;\n /** A maximum number of tokens to generate before stopping. */\n maxTokens?: number;\n /** A list of strings upon which to stop generating.\n * You probably want `[\"\\n\\nHuman:\"]`, as that's the cue for\n * the next turn in the dialog agent.\n */\n stopSequences?: string[];\n /** Whether to stream the results or not */\n streaming?: boolean;\n /** Anthropic API key */\n anthropicApiKey?: string;\n /** Anthropic API key */\n apiKey?: string;\n /** Anthropic API URL */\n anthropicApiUrl?: string;\n /** @deprecated Use \"model\" instead */\n modelName?: AnthropicMessagesModelId;\n /** Model name to use */\n model?: AnthropicMessagesModelId;\n /** Overridable Anthropic ClientOptions */\n clientOptions?: ClientOptions;\n /** Holds any additional parameters that are valid to pass to {@link\n * https://console.anthropic.com/docs/api/reference |\n * `anthropic.messages`} that are not explicitly specified on this class.\n */\n invocationKwargs?: Kwargs;\n /**\n * Whether or not to include token usage data in streamed chunks.\n * @default true\n */\n streamUsage?: boolean;\n /**\n * Optional method that returns an initialized underlying Anthropic client.\n * Useful for accessing Anthropic models hosted on other cloud services\n * such as Google Vertex.\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n createClient?: (options: ClientOptions) => any;\n /**\n * Options for extended thinking.\n */\n thinking?: AnthropicThinkingConfigParam;\n /**\n * Configuration for context management. See https://docs.claude.com/en/docs/build-with-claude/context-editing\n */\n contextManagement?: AnthropicContextManagementConfigParam;\n}\n/**\n * A type representing additional parameters that can be passed to the\n * Anthropic API.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Kwargs = Record<string, any>;\n/**\n * Anthropic chat model integration.\n *\n * Setup:\n * Install `@langchain/anthropic` and set an environment variable named `ANTHROPIC_API_KEY`.\n *\n * ```bash\n * npm install @langchain/anthropic\n * export ANTHROPIC_API_KEY=\"your-api-key\"\n * ```\n *\n * ## [Constructor args](https://api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html#constructor)\n *\n * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_anthropic.ChatAnthropicCallOptions.html)\n *\n * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.\n * They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below:\n *\n * ```typescript\n * // When calling `.bind`, call options should be passed via the first argument\n * const llmWithArgsBound = llm.bindTools([...]).withConfig({\n * stop: [\"\\n\"],\n * });\n *\n * // When calling `.bindTools`, call options should be passed via the second argument\n * const llmWithTools = llm.bindTools(\n * [...],\n * {\n * tool_choice: \"auto\",\n * }\n * );\n * ```\n *\n * ## Examples\n *\n * <details open>\n * <summary><strong>Instantiate</strong></summary>\n *\n * ```typescript\n * import { ChatAnthropic } from '@langchain/anthropic';\n *\n * const llm = new ChatAnthropic({\n * model: \"claude-3-5-sonnet-20240620\",\n * temperature: 0,\n * maxTokens: undefined,\n * maxRetries: 2,\n * // apiKey: \"...\",\n * // baseUrl: \"...\",\n * // other params...\n * });\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Invoking</strong></summary>\n *\n * ```typescript\n * const input = `Translate \"I love programming\" into French.`;\n *\n * // Models also accept a list of chat messages or a formatted prompt\n * const result = await llm.invoke(input);\n * console.log(result);\n * ```\n *\n * ```txt\n * AIMessage {\n * \"id\": \"msg_01QDpd78JUHpRP6bRRNyzbW3\",\n * \"content\": \"Here's the translation to French:\\n\\nJ'adore la programmation.\",\n * \"response_metadata\": {\n * \"id\": \"msg_01QDpd78JUHpRP6bRRNyzbW3\",\n * \"model\": \"claude-3-5-sonnet-20240620\",\n * \"stop_reason\": \"end_turn\",\n * \"stop_sequence\": null,\n * \"usage\": {\n * \"input_tokens\": 25,\n * \"output_tokens\": 19\n * },\n * \"type\": \"message\",\n * \"role\": \"assistant\"\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 25,\n * \"output_tokens\": 19,\n * \"total_tokens\": 44\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Streaming Chunks</strong></summary>\n *\n * ```typescript\n * for await (const chunk of await llm.stream(input)) {\n * console.log(chunk);\n * }\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"id\": \"msg_01N8MwoYxiKo9w4chE4gXUs4\",\n * \"content\": \"\",\n * \"additional_kwargs\": {\n * \"id\": \"msg_01N8MwoYxiKo9w4chE4gXUs4\",\n * \"type\": \"message\",\n * \"role\": \"assistant\",\n * \"model\": \"claude-3-5-sonnet-20240620\"\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 25,\n * \"output_tokens\": 1,\n * \"total_tokens\": 26\n * }\n * }\n * AIMessageChunk {\n * \"content\": \"\",\n * }\n * AIMessageChunk {\n * \"content\": \"Here\",\n * }\n * AIMessageChunk {\n * \"content\": \"'s\",\n * }\n * AIMessageChunk {\n * \"content\": \" the translation to\",\n * }\n * AIMessageChunk {\n * \"content\": \" French:\\n\\nJ\",\n * }\n * AIMessageChunk {\n * \"content\": \"'adore la programmation\",\n * }\n * AIMessageChunk {\n * \"content\": \".\",\n * }\n * AIMessageChunk {\n * \"content\": \"\",\n * \"additional_kwargs\": {\n * \"stop_reason\": \"end_turn\",\n * \"stop_sequence\": null\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 0,\n * \"output_tokens\": 19,\n * \"total_tokens\": 19\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Aggregate Streamed Chunks</strong></summary>\n *\n * ```typescript\n * import { AIMessageChunk } from '@langchain/core/messages';\n * import { concat } from '@langchain/core/utils/stream';\n *\n * const stream = await llm.stream(input);\n * let full: AIMessageChunk | undefined;\n * for await (const chunk of stream) {\n * full = !full ? chunk : concat(full, chunk);\n * }\n * console.log(full);\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"id\": \"msg_01SBTb5zSGXfjUc7yQ8EKEEA\",\n * \"content\": \"Here's the translation to French:\\n\\nJ'adore la programmation.\",\n * \"additional_kwargs\": {\n * \"id\": \"msg_01SBTb5zSGXfjUc7yQ8EKEEA\",\n * \"type\": \"message\",\n * \"role\": \"assistant\",\n * \"model\": \"claude-3-5-sonnet-20240620\",\n * \"stop_reason\": \"end_turn\",\n * \"stop_sequence\": null\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 25,\n * \"output_tokens\": 20,\n * \"total_tokens\": 45\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Bind tools</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const GetWeather = {\n * name: \"GetWeather\",\n * description: \"Get the current weather in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const GetPopulation = {\n * name: \"GetPopulation\",\n * description: \"Get the current population in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);\n * const aiMsg = await llmWithTools.invoke(\n * \"Which city is hotter today and which is bigger: LA or NY?\"\n * );\n * console.log(aiMsg.tool_calls);\n * ```\n *\n * ```txt\n * [\n * {\n * name: 'GetWeather',\n * args: { location: 'Los Angeles, CA' },\n * id: 'toolu_01WjW3Dann6BPJVtLhovdBD5',\n * type: 'tool_call'\n * },\n * {\n * name: 'GetWeather',\n * args: { location: 'New York, NY' },\n * id: 'toolu_01G6wfJgqi5zRmJomsmkyZXe',\n * type: 'tool_call'\n * },\n * {\n * name: 'GetPopulation',\n * args: { location: 'Los Angeles, CA' },\n * id: 'toolu_0165qYWBA2VFyUst5RA18zew',\n * type: 'tool_call'\n * },\n * {\n * name: 'GetPopulation',\n * args: { location: 'New York, NY' },\n * id: 'toolu_01PGNyP33vxr13tGqr7i3rDo',\n * type: 'tool_call'\n * }\n * ]\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Structured Output</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const Joke = z.object({\n * setup: z.string().describe(\"The setup of the joke\"),\n * punchline: z.string().describe(\"The punchline to the joke\"),\n * rating: z.number().optional().describe(\"How funny the joke is, from 1 to 10\")\n * }).describe('Joke to tell user.');\n *\n * const structuredLlm = llm.withStructuredOutput(Joke, { name: \"Joke\" });\n * const jokeResult = await structuredLlm.invoke(\"Tell me a joke about cats\");\n * console.log(jokeResult);\n * ```\n *\n * ```txt\n * {\n * setup: \"Why don't cats play poker in the jungle?\",\n * punchline: 'Too many cheetahs!',\n * rating: 7\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Multimodal</strong></summary>\n *\n * ```typescript\n * import { HumanMessage } from '@langchain/core/messages';\n *\n * const imageUrl = \"https://example.com/image.jpg\";\n * const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());\n * const base64Image = Buffer.from(imageData).toString('base64');\n *\n * const message = new HumanMessage({\n * content: [\n * { type: \"text\", text: \"describe the weather in this image\" },\n * {\n * type: \"image_url\",\n * image_url: { url: `data:image/jpeg;base64,${base64Image}` },\n * },\n * ]\n * });\n *\n * const imageDescriptionAiMsg = await llm.invoke([message]);\n * console.log(imageDescriptionAiMsg.content);\n * ```\n *\n * ```txt\n * 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.\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Usage Metadata</strong></summary>\n *\n * ```typescript\n * const aiMsgForMetadata = await llm.invoke(input);\n * console.log(aiMsgForMetadata.usage_metadata);\n * ```\n *\n * ```txt\n * { input_tokens: 25, output_tokens: 19, total_tokens: 44 }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Stream Usage Metadata</strong></summary>\n *\n * ```typescript\n * const streamForMetadata = await llm.stream(\n * input,\n * {\n * streamUsage: true\n * }\n * );\n * let fullForMetadata: AIMessageChunk | undefined;\n * for await (const chunk of streamForMetadata) {\n * fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk);\n * }\n * console.log(fullForMetadata?.usage_metadata);\n * ```\n *\n * ```txt\n * { input_tokens: 25, output_tokens: 20, total_tokens: 45 }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Response Metadata</strong></summary>\n *\n * ```typescript\n * const aiMsgForResponseMetadata = await llm.invoke(input);\n * console.log(aiMsgForResponseMetadata.response_metadata);\n * ```\n *\n * ```txt\n * {\n * id: 'msg_01STxeQxJmp4sCSpioD6vK3L',\n * model: 'claude-3-5-sonnet-20240620',\n * stop_reason: 'end_turn',\n * stop_sequence: null,\n * usage: { input_tokens: 25, output_tokens: 19 },\n * type: 'message',\n * role: 'assistant'\n * }\n * ```\n * </details>\n *\n * <br />\n */\nexport declare class ChatAnthropicMessages<CallOptions extends ChatAnthropicCallOptions = ChatAnthropicCallOptions> extends BaseChatModel<CallOptions, AIMessageChunk> implements AnthropicInput {\n static lc_name(): string;\n get lc_secrets(): {\n [key: string]: string;\n } | undefined;\n get lc_aliases(): Record<string, string>;\n lc_serializable: boolean;\n anthropicApiKey?: string;\n apiKey?: string;\n apiUrl?: string;\n temperature: number | undefined;\n topK: number;\n topP: number | undefined;\n maxTokens: number;\n modelName: string;\n model: string;\n invocationKwargs?: Kwargs;\n stopSequences?: string[];\n streaming: boolean;\n clientOptions: ClientOptions;\n thinking: AnthropicThinkingConfigParam;\n contextManagement?: AnthropicContextManagementConfigParam;\n // Used for non-streaming requests\n protected batchClient: Anthropic;\n // Used for streaming requests\n protected streamingClient: Anthropic;\n streamUsage: boolean;\n /**\n * Optional method that returns an initialized underlying Anthropic client.\n * Useful for accessing Anthropic models hosted on other cloud services\n * such as Google Vertex.\n */\n createClient: (options: ClientOptions) => Anthropic;\n constructor(fields?: AnthropicInput & BaseChatModelParams);\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams;\n /**\n * Formats LangChain StructuredTools to AnthropicTools.\n *\n * @param {ChatAnthropicCallOptions[\"tools\"]} tools The tools to format\n * @returns {AnthropicTool[] | undefined} The formatted tools, or undefined if none are passed.\n */\n formatStructuredToolToAnthropic(tools: ChatAnthropicCallOptions[\"tools\"]): Anthropic.Messages.ToolUnion[] | undefined;\n bindTools(tools: ChatAnthropicToolType[], kwargs?: Partial<CallOptions>): Runnable<BaseLanguageModelInput, AIMessageChunk, CallOptions>;\n /**\n * Get the parameters used to invoke the model\n */\n invocationParams(options?: this[\"ParsedCallOptions\"]): Omit<AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams, \"messages\"> & Kwargs;\n /** @ignore */\n _identifyingParams(): {\n max_tokens: number;\n model: Anthropic.Model;\n metadata?: Anthropic.Metadata | undefined;\n service_tier?: \"auto\" | \"standard_only\" | undefined;\n stop_sequences?: string[] | undefined;\n system?: string | Anthropic.TextBlockParam[] | undefined;\n temperature?: number | undefined;\n thinking?: Anthropic.ThinkingConfigParam | undefined;\n tool_choice?: Anthropic.ToolChoice | undefined;\n tools?: Anthropic.ToolUnion[] | undefined;\n top_k?: number | undefined;\n top_p?: number | undefined;\n stream?: boolean | undefined;\n model_name: string;\n };\n /**\n * Get the identifying parameters for the model\n */\n identifyingParams(): {\n max_tokens: number;\n model: Anthropic.Model;\n metadata?: Anthropic.Metadata | undefined;\n service_tier?: \"auto\" | \"standard_only\" | undefined;\n stop_sequences?: string[] | undefined;\n system?: string | Anthropic.TextBlockParam[] | undefined;\n temperature?: number | undefined;\n thinking?: Anthropic.ThinkingConfigParam | undefined;\n tool_choice?: Anthropic.ToolChoice | undefined;\n tools?: Anthropic.ToolUnion[] | undefined;\n top_k?: number | undefined;\n top_p?: number | undefined;\n stream?: boolean | undefined;\n model_name: string;\n };\n _streamResponseChunks(messages: BaseMessage[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;\n /** @ignore */\n _generateNonStreaming(messages: BaseMessage[], params: Omit<Anthropic.Messages.MessageCreateParamsNonStreaming | Anthropic.Messages.MessageCreateParamsStreaming, \"messages\"> & Kwargs, requestOptions: AnthropicRequestOptions): Promise<{\n generations: import(\"@langchain/core/outputs\").ChatGeneration[];\n llmOutput: {\n id: string;\n model: Anthropic.Model;\n stop_reason: Anthropic.StopReason | null;\n stop_sequence: string | null;\n usage: Anthropic.Usage;\n };\n }>;\n /** @ignore */\n _generate(messages: BaseMessage[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;\n /**\n * Creates a streaming request with retry.\n * @param request The parameters for creating a completion.\n * @param options\n * @returns A streaming request.\n */\n protected createStreamWithRetry(request: AnthropicStreamingMessageCreateParams & Kwargs, options?: AnthropicRequestOptions): Promise<Stream<AnthropicMessageStreamEvent>>;\n /** @ignore */\n protected completionWithRetry(request: AnthropicMessageCreateParams & Kwargs, options: AnthropicRequestOptions): Promise<Anthropic.Message>;\n _llmType(): string;\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {\n raw: BaseMessage;\n parsed: RunOutput;\n }>;\n}\nexport declare class ChatAnthropic extends ChatAnthropicMessages {\n}\nexport {};\n"],"mappings":";;;;;;;;;;;;;UAUiBwB,wBAAAA,SAAiCf,0BAA0BkB,KAAKF;UACrEF;;AADZ;;;EAA+F,WACnFA,CAAAA,EAKMD,mBALNC;EAAqB;;;;EAD+C,OAAA,CAAA,EAWlEG,MAXkE,CAAA,MAAA,EAAA,MAAA,CAAA;EAqBpEE;;;;EAAkE,SAAA,CAAA,EAAA,MAAA;AAI9E;;;;AA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BAA0B8B;iBAAHJ,wBAAAA,CAC5KC,cAAAA;;;aAGpC9C,WAAAA,CAAU6B;mBACJ7B,WAAAA,CAAU+C;;aAEhB/C,WAAAA,CAAUgD;;;;sBAIL3C,gEAAgEF,2BAA2B8C,QAAQ1C;;;;;;;2CAO9Ea,wCAAwCW,kBAAkBZ,0BAA0B8B,QAAQ/C,OAAOgB;;yCAErGD,+BAA+Bc,iBAAiBZ,0BAA0B8B,QAAQjD,WAAAA,CAAUkD;;;;oBAIjHxB,sBAAsBA,mCAAmCX,eAAeoC;;IAEvFzB,8BAA8Bd,uCAAuCE,SAASD,wBAAwBsC;;;oBAGvFzB,sBAAsBA,mCAAmCX,eAAeoC;;IAEvFzB,8BAA8Bd,sCAAsCE,SAASD;SACvER;YACG8C;;;cAGKC,aAAAA,SAAsBpB,qBAAqB"}
@@ -1,4 +1,4 @@
1
- import { AnthropicMessageCreateParams, AnthropicMessageStreamEvent, AnthropicRequestOptions, AnthropicStreamingMessageCreateParams, AnthropicThinkingConfigParam, AnthropicToolChoice, ChatAnthropicToolType } from "./types.js";
1
+ import { AnthropicContextManagementConfigParam, AnthropicMessageCreateParams, AnthropicMessageStreamEvent, AnthropicRequestOptions, AnthropicStreamingMessageCreateParams, AnthropicThinkingConfigParam, AnthropicToolChoice, ChatAnthropicToolType } from "./types.js";
2
2
  import { Anthropic as Anthropic$1, ClientOptions } from "@anthropic-ai/sdk";
3
3
  import { AIMessageChunk, BaseMessage } from "@langchain/core/messages";
4
4
  import * as _langchain_core_outputs0 from "@langchain/core/outputs";
@@ -23,6 +23,11 @@ interface ChatAnthropicCallOptions extends BaseChatModelCallOptions, Pick<Anthro
23
23
  * when making a request.
24
24
  */
25
25
  headers?: Record<string, string>;
26
+ /**
27
+ * Container ID for file persistence across turns with code execution.
28
+ * Used with the code_execution_20250825 tool.
29
+ */
30
+ container?: string;
26
31
  }
27
32
  /**
28
33
  * @see https://docs.anthropic.com/claude/docs/models-overview
@@ -56,16 +61,11 @@ interface AnthropicInput {
56
61
  * To not set this field, pass `null`. If `undefined` is passed,
57
62
  * the default (-1) will be used.
58
63
  *
59
- * For Opus 4.1, this defaults to `null`.
64
+ * For Opus 4.1 and Sonnet 4.5, this defaults to `null`.
60
65
  */
61
66
  topP?: number | null;
62
67
  /** A maximum number of tokens to generate before stopping. */
63
68
  maxTokens?: number;
64
- /**
65
- * A maximum number of tokens to generate before stopping.
66
- * @deprecated Use "maxTokens" instead.
67
- */
68
- maxTokensToSample?: number;
69
69
  /** A list of strings upon which to stop generating.
70
70
  * You probably want `["\n\nHuman:"]`, as that's the cue for
71
71
  * the next turn in the dialog agent.
@@ -106,6 +106,10 @@ interface AnthropicInput {
106
106
  * Options for extended thinking.
107
107
  */
108
108
  thinking?: AnthropicThinkingConfigParam;
109
+ /**
110
+ * Configuration for context management. See https://docs.claude.com/en/docs/build-with-claude/context-editing
111
+ */
112
+ contextManagement?: AnthropicContextManagementConfigParam;
109
113
  }
110
114
  /**
111
115
  * A type representing additional parameters that can be passed to the
@@ -510,6 +514,7 @@ declare class ChatAnthropicMessages<CallOptions extends ChatAnthropicCallOptions
510
514
  streaming: boolean;
511
515
  clientOptions: ClientOptions;
512
516
  thinking: AnthropicThinkingConfigParam;
517
+ contextManagement?: AnthropicContextManagementConfigParam;
513
518
  // Used for non-streaming requests
514
519
  protected batchClient: Anthropic$1;
515
520
  // Used for streaming requests