@langchain/anthropic 1.3.4 → 1.3.6-dev-1767748783694
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.
- package/CHANGELOG.md +7 -0
- package/dist/chat_models.cjs.map +1 -1
- package/dist/chat_models.js.map +1 -1
- package/dist/output_parsers.cjs.map +1 -1
- package/dist/output_parsers.js.map +1 -1
- package/dist/tools/computer.d.ts +101 -101
- package/dist/tools/computer.d.ts.map +1 -1
- package/dist/tools/textEditor.d.ts +21 -21
- package/dist/tools/textEditor.d.ts.map +1 -1
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# @langchain/anthropic
|
|
2
2
|
|
|
3
|
+
## 1.3.5
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies [[`817fc9a`](https://github.com/langchain-ai/langchainjs/commit/817fc9a56d4699f3563a6e153b13eadf7bcc661b)]:
|
|
8
|
+
- @langchain/core@1.1.10
|
|
9
|
+
|
|
3
10
|
## 1.3.4
|
|
4
11
|
|
|
5
12
|
### Patch Changes
|
package/dist/chat_models.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat_models.cjs","names":["MODEL_DEFAULT_MAX_OUTPUT_TOKENS: Partial<\n Record<Anthropic.Model, number>\n>","model?: Anthropic.Model","params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams","tool: any","tool: unknown","a?: Iterable<AnthropicBeta>","b?: Iterable<AnthropicBeta>","chunk: AIMessageChunk","BaseChatModel","fields?: ChatAnthropicInput","options: ClientOptions","Anthropic","options: this[\"ParsedCallOptions\"]","tools: ChatAnthropicCallOptions[\"tools\"]","AnthropicToolExtrasSchema","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","ANTHROPIC_TOOL_BETAS","output: AnthropicInvocationParams","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","PROFILES","outputSchema:\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>","config?: StructuredOutputMethodOptions<boolean>","llm: Runnable<BaseLanguageModelInput>","outputParser: Runnable<AIMessageChunk, RunOutput>","StructuredOutputParser","JsonOutputParser","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\";\nimport { transformJSONSchema } from \"@anthropic-ai/sdk/lib/transform-json-schema\";\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 { ModelProfile } from \"@langchain/core/language_models/profile\";\nimport { toJsonSchema } from \"@langchain/core/utils/json_schema\";\nimport {\n JsonOutputParser,\n StructuredOutputParser,\n} 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 {\n ANTHROPIC_TOOL_BETAS,\n AnthropicToolExtrasSchema,\n handleToolChoice,\n} 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 AnthropicInvocationParams,\n AnthropicMessageCreateParams,\n AnthropicMessageStreamEvent,\n AnthropicRequestOptions,\n AnthropicStreamingMessageCreateParams,\n AnthropicThinkingConfigParam,\n AnthropicToolChoice,\n ChatAnthropicOutputFormat,\n ChatAnthropicToolType,\n AnthropicMCPServerURLDefinition,\n Kwargs,\n} from \"./types.js\";\nimport { wrapAnthropicClientError } from \"./utils/errors.js\";\nimport PROFILES from \"./profiles.js\";\nimport { AnthropicBeta } from \"@anthropic-ai/sdk/resources\";\n\nconst MODEL_DEFAULT_MAX_OUTPUT_TOKENS: Partial<\n Record<Anthropic.Model, number>\n> = {\n \"claude-opus-4-1\": 8192,\n \"claude-opus-4\": 8192,\n \"claude-sonnet-4\": 8192,\n \"claude-sonnet-3-7-sonnet\": 8192,\n \"claude-3-5-sonnet\": 4096,\n \"claude-3-5-haiku\": 4096,\n \"claude-3-haiku\": 2048,\n};\nconst FALLBACK_MAX_OUTPUT_TOKENS = 2048;\n\nfunction defaultMaxOutputTokensForModel(model?: Anthropic.Model): number {\n if (!model) {\n return FALLBACK_MAX_OUTPUT_TOKENS;\n }\n const maxTokens = Object.entries(MODEL_DEFAULT_MAX_OUTPUT_TOKENS).find(\n ([key]) => model.startsWith(key)\n )?.[1];\n return maxTokens ?? FALLBACK_MAX_OUTPUT_TOKENS;\n}\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 * Output format to use for the response.\n */\n output_format?: ChatAnthropicOutputFormat;\n /**\n * Optional array of beta features to enable for the Anthropic API.\n * Beta features are experimental capabilities that may change or be removed.\n * See https://docs.anthropic.com/en/api/versioning for available beta features.\n */\n betas?: AnthropicBeta[];\n /**\n * Array of MCP server URLs to use for the request.\n */\n mcp_servers?: AnthropicMCPServerURLDefinition[];\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 \"tool_search_\",\n \"mcp_toolset\",\n ];\n return (\n typeof tool === \"object\" &&\n tool !== null &&\n \"type\" in tool &&\n (\"name\" in tool || \"mcp_server_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\nfunction _combineBetas(\n a?: Iterable<AnthropicBeta>,\n b?: Iterable<AnthropicBeta>,\n ...rest: Iterable<AnthropicBeta>[]\n): AnthropicBeta[] {\n return Array.from(\n new Set([...(a ?? []), ...(b ?? []), ...rest.flatMap((x) => Array.from(x))])\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 /**\n * Amount of randomness injected into the response. Ranges\n * from 0 to 1. Use temperature closer to 0 for analytical /\n * multiple choice, and temperature closer to 1 for creative\n * and generative tasks.\n */\n temperature?: number;\n\n /**\n * Only sample from the top K options for each subsequent\n * token. Used to remove \"long tail\" low probability\n * responses.\n */\n topK?: number;\n\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. Note that you should either alter\n * temperature or top_p, but not both.\n */\n topP?: number | null;\n\n /** A maximum number of tokens to generate before stopping. */\n maxTokens?: number;\n\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 * Optional array of beta features to enable for the Anthropic API.\n * Beta features are experimental capabilities that may change or be removed.\n * See https://docs.claude.com/en/api/beta-headers for available beta features.\n */\n betas?: AnthropicBeta[];\n}\n\n/**\n * Input to ChatAnthropic class.\n */\nexport type ChatAnthropicInput = AnthropicInput & BaseChatModelParams;\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-sonnet-4-5-20250929\",\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-sonnet-4-5-20250929\",\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-sonnet-4-5-20250929\"\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-sonnet-4-5-20250929\",\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>Tool Search</strong></summary>\n *\n * Tool search enables Claude to dynamically discover and load tools on-demand\n * instead of loading all tool definitions upfront. This is useful when you have\n * many tools but want to avoid the overhead of sending all definitions with every request.\n *\n * ```typescript\n * import { ChatAnthropic } from \"@langchain/anthropic\";\n *\n * const model = new ChatAnthropic({\n * model: \"claude-sonnet-4-5-20250929\",\n * });\n *\n * const tools = [\n * // Tool search server tool\n * {\n * type: \"tool_search_tool_regex_20251119\",\n * name: \"tool_search_tool_regex\",\n * },\n * // Tools with defer_loading are loaded on-demand\n * {\n * name: \"get_weather\",\n * description: \"Get the current weather for a location\",\n * input_schema: {\n * type: \"object\",\n * properties: {\n * location: { type: \"string\", description: \"City name\" },\n * unit: {\n * type: \"string\",\n * enum: [\"celsius\", \"fahrenheit\"],\n * },\n * },\n * required: [\"location\"],\n * },\n * defer_loading: true, // Tool is loaded on-demand\n * },\n * {\n * name: \"search_files\",\n * description: \"Search through files in the workspace\",\n * input_schema: {\n * type: \"object\",\n * properties: {\n * query: { type: \"string\" },\n * },\n * required: [\"query\"],\n * },\n * defer_loading: true, // Tool is loaded on-demand\n * },\n * ];\n *\n * const modelWithTools = model.bindTools(tools);\n * const response = await modelWithTools.invoke(\"What's the weather in San Francisco?\");\n * ```\n *\n * You can also use the `tool()` helper with the `extras` field:\n *\n * ```typescript\n * import { tool } from \"@langchain/core/tools\";\n * import { z } from \"zod\";\n *\n * const getWeather = tool(\n * async (input) => `Weather in ${input.location}`,\n * {\n * name: \"get_weather\",\n * description: \"Get weather for a location\",\n * schema: z.object({ location: z.string() }),\n * extras: { defer_loading: true },\n * }\n * );\n * ```\n *\n * **Note:** The required `advanced-tool-use-2025-11-20` beta header is automatically\n * appended to the request when using tool search tools.\n *\n * **Best practices:**\n * - Tools with `defer_loading: true` are only loaded when Claude discovers them via search\n * - Keep your 3-5 most frequently used tools as non-deferred for optimal performance\n * - Both regex and bm25 variants search tool names, descriptions, and argument info\n *\n * See the {@link https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool | Claude docs}\n * for more information.\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Structured Output</strong></summary>\n *\n * ChatAnthropic supports structured output through two main approaches:\n *\n * 1. **Function Calling with `withStructuredOutput()`**: Uses Anthropic's tool calling\n * under the hood to constrain outputs to a specific schema.\n * 2. **JSON Schema Mode**: Uses Anthropic's native JSON schema support for direct\n * structured output without tool calling overhead.\n *\n * **Using withStructuredOutput (Function Calling)**\n *\n * This method leverages Anthropic's tool calling capabilities to ensure the model\n * returns data matching your schema:\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 *\n * **Using JSON Schema Mode**\n *\n * For more direct control, you can use Anthropic's native JSON schema support by\n * passing `method: \"jsonSchema\"`:\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const RecipeSchema = z.object({\n * recipeName: z.string().describe(\"Name of the recipe\"),\n * ingredients: z.array(z.string()).describe(\"List of ingredients needed\"),\n * steps: z.array(z.string()).describe(\"Cooking steps in order\"),\n * prepTime: z.number().describe(\"Preparation time in minutes\")\n * });\n *\n * const structuredLlm = llm.withStructuredOutput(RecipeSchema, {\n * method: \"jsonSchema\"\n * });\n *\n * const recipe = await structuredLlm.invoke(\n * \"Give me a simple recipe for chocolate chip cookies\"\n * );\n * console.log(recipe);\n * ```\n *\n * ```txt\n * {\n * recipeName: 'Classic Chocolate Chip Cookies',\n * ingredients: [\n * '2 1/4 cups all-purpose flour',\n * '1 cup butter, softened',\n * ...\n * ],\n * steps: [\n * 'Preheat oven to 375°F',\n * 'Mix butter and sugars until creamy',\n * ...\n * ],\n * prepTime: 15\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-sonnet-4-5-20250929',\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;\n\n topK?: number;\n\n topP?: number;\n\n maxTokens: number;\n\n modelName = \"claude-3-5-sonnet-latest\";\n\n model = \"claude-3-5-sonnet-latest\";\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 betas?: AnthropicBeta[];\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?: ChatAnthropicInput) {\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 this.topP = fields?.topP ?? this.topP;\n\n this.temperature = fields?.temperature ?? this.temperature;\n this.topK = fields?.topK ?? this.topK;\n this.maxTokens =\n fields?.maxTokens ?? defaultMaxOutputTokensForModel(this.model);\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 this.betas = fields?.betas ?? this.betas;\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) {\n return undefined;\n }\n return tools.map((tool) => {\n if (isLangChainTool(tool) && tool.extras?.providerToolDefinition) {\n return tool.extras\n .providerToolDefinition as Anthropic.Messages.ToolUnion;\n }\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 ...(tool.extras ? AnthropicToolExtrasSchema.parse(tool.extras) : {}),\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 ): AnthropicInvocationParams {\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 const toolBetas = options?.tools?.reduce<AnthropicBeta[]>((acc, tool) => {\n if (\n typeof tool === \"object\" &&\n \"type\" in tool &&\n tool.type in ANTHROPIC_TOOL_BETAS\n ) {\n const beta = ANTHROPIC_TOOL_BETAS[tool.type];\n if (!acc.includes(beta)) {\n return [...acc, beta];\n }\n }\n return acc;\n }, []);\n\n const output: AnthropicInvocationParams = {\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 betas: _combineBetas(this.betas, options?.betas, toolBetas ?? []),\n output_format: options?.output_format,\n mcp_servers: options?.mcp_servers,\n };\n\n if (this.thinking.type === \"enabled\") {\n if (this.topP !== undefined && this.topK !== -1) {\n throw new Error(\"topK is not supported when thinking is enabled\");\n }\n if (this.temperature !== undefined && this.temperature !== 1) {\n throw new Error(\n \"temperature is not supported when thinking is enabled\"\n );\n }\n } else {\n // Only set temperature, top_k, and top_p if thinking is disabled\n output.temperature = this.temperature;\n output.top_k = this.topK;\n output.top_p = this.topP;\n }\n\n return output;\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 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 { betas, ...rest } = request;\n\n const makeCompletionRequest = async () => {\n try {\n if (request?.betas?.length) {\n const stream = await this.streamingClient.beta.messages.create(\n {\n ...rest,\n betas,\n ...this.invocationKwargs,\n stream: true,\n } as AnthropicStreamingMessageCreateParams,\n options\n );\n return stream as Stream<Anthropic.Messages.RawMessageStreamEvent>;\n }\n return await this.streamingClient.messages.create(\n {\n ...rest,\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 { betas, ...rest } = request;\n\n const makeCompletionRequest = async () => {\n try {\n if (request?.betas?.length) {\n const response = await this.batchClient.beta.messages.create(\n {\n ...rest,\n ...this.invocationKwargs,\n betas,\n } as AnthropicMessageCreateParams,\n options\n );\n return response as Anthropic.Messages.Message;\n }\n return await this.batchClient.messages.create(\n {\n ...rest,\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 /**\n * Return profiling information for the model.\n *\n * Provides information about the model's capabilities and constraints,\n * including token limits, multimodal support, and advanced features like\n * tool calling and structured output.\n *\n * @returns {ModelProfile} An object describing the model's capabilities and constraints\n *\n * @example\n * ```typescript\n * const model = new ChatAnthropic({ model: \"claude-opus-4-0\" });\n * const profile = model.profile;\n * console.log(profile.maxInputTokens); // 200000\n * console.log(profile.imageInputs); // true\n * ```\n */\n get profile(): ModelProfile {\n return PROFILES[this.model] ?? {};\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 let llm: Runnable<BaseLanguageModelInput>;\n let outputParser: Runnable<AIMessageChunk, RunOutput>;\n\n const { schema, name, includeRaw } = {\n ...config,\n schema: outputSchema,\n };\n let method = config?.method ?? \"functionCalling\";\n\n if (method === \"jsonMode\") {\n console.warn(\n `\"jsonMode\" is not supported for Anthropic models. Falling back to \"jsonSchema\".`\n );\n method = \"jsonSchema\";\n }\n if (method === \"jsonSchema\") {\n // https://docs.claude.com/en/docs/build-with-claude/structured-outputs\n outputParser = isInteropZodSchema(schema)\n ? StructuredOutputParser.fromZodSchema(schema)\n : new JsonOutputParser<RunOutput>();\n const jsonSchema = transformJSONSchema(toJsonSchema(schema));\n llm = this.withConfig({\n outputVersion: \"v0\",\n output_format: {\n type: \"json_schema\",\n schema: jsonSchema,\n },\n betas: [\"structured-outputs-2025-11-13\"],\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: jsonSchema,\n },\n } as Partial<CallOptions>);\n } else if (method === \"functionCalling\") {\n let functionName = name ?? \"extract\";\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 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 outputVersion: \"v0\",\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 outputVersion: \"v0\",\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 } else {\n throw new TypeError(\n `Unrecognized structured output method '${method}'. Expected 'functionCalling' or 'jsonSchema'`\n );\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,MAAMA,kCAEF;CACF,mBAAmB;CACnB,iBAAiB;CACjB,mBAAmB;CACnB,4BAA4B;CAC5B,qBAAqB;CACrB,oBAAoB;CACpB,kBAAkB;AACnB;AACD,MAAM,6BAA6B;AAEnC,SAAS,+BAA+BC,OAAiC;AACvE,KAAI,CAAC,MACH,QAAO;CAET,MAAM,YAAY,OAAO,QAAQ,gCAAgC,CAAC,KAChE,CAAC,CAAC,IAAI,KAAK,MAAM,WAAW,IAAI,CACjC,GAAG;AACJ,QAAO,aAAa;AACrB;AAqCD,SAAS,eACPC,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,YAC3B,MAAM,WAAW,QAEjB,QAAO;CAGZ;AACD,QAAO;AACR;AAED,SAAS,kBACPA,QACS;AACT,QAAO,CAAC,EAAE,OAAO,YAAY,OAAO,SAAS,SAAS;AACvD;AAGD,SAAS,gBAAgBC,MAA4C;AACnE,QAAO,kBAAkB;AAC1B;AAED,SAAS,cAAcC,MAAkD;CACvE,MAAM,sBAAsB;EAC1B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD;AACD,QACE,OAAO,SAAS,YAChB,SAAS,QACT,U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,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
|
+
{"version":3,"file":"chat_models.cjs","names":["MODEL_DEFAULT_MAX_OUTPUT_TOKENS: Partial<\n Record<Anthropic.Model, number>\n>","model?: Anthropic.Model","params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams","tool: any","tool: unknown","a?: Iterable<AnthropicBeta>","b?: Iterable<AnthropicBeta>","chunk: AIMessageChunk","BaseChatModel","fields?: ChatAnthropicInput","options: ClientOptions","Anthropic","options: this[\"ParsedCallOptions\"]","tools: ChatAnthropicCallOptions[\"tools\"]","AnthropicToolExtrasSchema","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","ANTHROPIC_TOOL_BETAS","output: AnthropicInvocationParams","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","PROFILES","outputSchema:\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>","config?: StructuredOutputMethodOptions<boolean>","llm: Runnable<BaseLanguageModelInput>","outputParser: Runnable<AIMessageChunk, RunOutput>","StructuredOutputParser","JsonOutputParser","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\";\nimport { transformJSONSchema } from \"@anthropic-ai/sdk/lib/transform-json-schema\";\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 { ModelProfile } from \"@langchain/core/language_models/profile\";\nimport { toJsonSchema } from \"@langchain/core/utils/json_schema\";\nimport {\n JsonOutputParser,\n StructuredOutputParser,\n} 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 {\n ANTHROPIC_TOOL_BETAS,\n AnthropicToolExtrasSchema,\n handleToolChoice,\n} 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 AnthropicInvocationParams,\n AnthropicMessageCreateParams,\n AnthropicMessageStreamEvent,\n AnthropicRequestOptions,\n AnthropicStreamingMessageCreateParams,\n AnthropicThinkingConfigParam,\n AnthropicToolChoice,\n ChatAnthropicOutputFormat,\n ChatAnthropicToolType,\n AnthropicMCPServerURLDefinition,\n Kwargs,\n} from \"./types.js\";\nimport { wrapAnthropicClientError } from \"./utils/errors.js\";\nimport PROFILES from \"./profiles.js\";\nimport { AnthropicBeta } from \"@anthropic-ai/sdk/resources\";\n\nconst MODEL_DEFAULT_MAX_OUTPUT_TOKENS: Partial<\n Record<Anthropic.Model, number>\n> = {\n \"claude-opus-4-1\": 8192,\n \"claude-opus-4\": 8192,\n \"claude-sonnet-4\": 8192,\n \"claude-sonnet-3-7-sonnet\": 8192,\n \"claude-3-5-sonnet\": 4096,\n \"claude-3-5-haiku\": 4096,\n \"claude-3-haiku\": 2048,\n};\nconst FALLBACK_MAX_OUTPUT_TOKENS = 2048;\n\nfunction defaultMaxOutputTokensForModel(model?: Anthropic.Model): number {\n if (!model) {\n return FALLBACK_MAX_OUTPUT_TOKENS;\n }\n const maxTokens = Object.entries(MODEL_DEFAULT_MAX_OUTPUT_TOKENS).find(\n ([key]) => model.startsWith(key)\n )?.[1];\n return maxTokens ?? FALLBACK_MAX_OUTPUT_TOKENS;\n}\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 * Output format to use for the response.\n */\n output_format?: ChatAnthropicOutputFormat;\n /**\n * Optional array of beta features to enable for the Anthropic API.\n * Beta features are experimental capabilities that may change or be removed.\n * See https://docs.anthropic.com/en/api/versioning for available beta features.\n */\n betas?: AnthropicBeta[];\n /**\n * Array of MCP server URLs to use for the request.\n */\n mcp_servers?: AnthropicMCPServerURLDefinition[];\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 \"tool_search_\",\n \"mcp_toolset\",\n ];\n return (\n typeof tool === \"object\" &&\n tool !== null &&\n \"type\" in tool &&\n (\"name\" in tool || \"mcp_server_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\nfunction _combineBetas(\n a?: Iterable<AnthropicBeta>,\n b?: Iterable<AnthropicBeta>,\n ...rest: Iterable<AnthropicBeta>[]\n): AnthropicBeta[] {\n return Array.from(\n new Set([...(a ?? []), ...(b ?? []), ...rest.flatMap((x) => Array.from(x))])\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 /**\n * Amount of randomness injected into the response. Ranges\n * from 0 to 1. Use temperature closer to 0 for analytical /\n * multiple choice, and temperature closer to 1 for creative\n * and generative tasks.\n */\n temperature?: number;\n\n /**\n * Only sample from the top K options for each subsequent\n * token. Used to remove \"long tail\" low probability\n * responses.\n */\n topK?: number;\n\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. Note that you should either alter\n * temperature or top_p, but not both.\n */\n topP?: number | null;\n\n /** A maximum number of tokens to generate before stopping. */\n maxTokens?: number;\n\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 * Optional array of beta features to enable for the Anthropic API.\n * Beta features are experimental capabilities that may change or be removed.\n * See https://docs.claude.com/en/api/beta-headers for available beta features.\n */\n betas?: AnthropicBeta[];\n}\n\n/**\n * Input to ChatAnthropic class.\n */\nexport type ChatAnthropicInput = AnthropicInput & BaseChatModelParams;\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-sonnet-4-5-20250929\",\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-sonnet-4-5-20250929\",\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-sonnet-4-5-20250929\"\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-sonnet-4-5-20250929\",\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>Tool Search</strong></summary>\n *\n * Tool search enables Claude to dynamically discover and load tools on-demand\n * instead of loading all tool definitions upfront. This is useful when you have\n * many tools but want to avoid the overhead of sending all definitions with every request.\n *\n * ```typescript\n * import { ChatAnthropic } from \"@langchain/anthropic\";\n *\n * const model = new ChatAnthropic({\n * model: \"claude-sonnet-4-5-20250929\",\n * });\n *\n * const tools = [\n * // Tool search server tool\n * {\n * type: \"tool_search_tool_regex_20251119\",\n * name: \"tool_search_tool_regex\",\n * },\n * // Tools with defer_loading are loaded on-demand\n * {\n * name: \"get_weather\",\n * description: \"Get the current weather for a location\",\n * input_schema: {\n * type: \"object\",\n * properties: {\n * location: { type: \"string\", description: \"City name\" },\n * unit: {\n * type: \"string\",\n * enum: [\"celsius\", \"fahrenheit\"],\n * },\n * },\n * required: [\"location\"],\n * },\n * defer_loading: true, // Tool is loaded on-demand\n * },\n * {\n * name: \"search_files\",\n * description: \"Search through files in the workspace\",\n * input_schema: {\n * type: \"object\",\n * properties: {\n * query: { type: \"string\" },\n * },\n * required: [\"query\"],\n * },\n * defer_loading: true, // Tool is loaded on-demand\n * },\n * ];\n *\n * const modelWithTools = model.bindTools(tools);\n * const response = await modelWithTools.invoke(\"What's the weather in San Francisco?\");\n * ```\n *\n * You can also use the `tool()` helper with the `extras` field:\n *\n * ```typescript\n * import { tool } from \"@langchain/core/tools\";\n * import { z } from \"zod\";\n *\n * const getWeather = tool(\n * async (input) => `Weather in ${input.location}`,\n * {\n * name: \"get_weather\",\n * description: \"Get weather for a location\",\n * schema: z.object({ location: z.string() }),\n * extras: { defer_loading: true },\n * }\n * );\n * ```\n *\n * **Note:** The required `advanced-tool-use-2025-11-20` beta header is automatically\n * appended to the request when using tool search tools.\n *\n * **Best practices:**\n * - Tools with `defer_loading: true` are only loaded when Claude discovers them via search\n * - Keep your 3-5 most frequently used tools as non-deferred for optimal performance\n * - Both regex and bm25 variants search tool names, descriptions, and argument info\n *\n * See the {@link https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool | Claude docs}\n * for more information.\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Structured Output</strong></summary>\n *\n * ChatAnthropic supports structured output through two main approaches:\n *\n * 1. **Function Calling with `withStructuredOutput()`**: Uses Anthropic's tool calling\n * under the hood to constrain outputs to a specific schema.\n * 2. **JSON Schema Mode**: Uses Anthropic's native JSON schema support for direct\n * structured output without tool calling overhead.\n *\n * **Using withStructuredOutput (Function Calling)**\n *\n * This method leverages Anthropic's tool calling capabilities to ensure the model\n * returns data matching your schema:\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 *\n * **Using JSON Schema Mode**\n *\n * For more direct control, you can use Anthropic's native JSON schema support by\n * passing `method: \"jsonSchema\"`:\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const RecipeSchema = z.object({\n * recipeName: z.string().describe(\"Name of the recipe\"),\n * ingredients: z.array(z.string()).describe(\"List of ingredients needed\"),\n * steps: z.array(z.string()).describe(\"Cooking steps in order\"),\n * prepTime: z.number().describe(\"Preparation time in minutes\")\n * });\n *\n * const structuredLlm = llm.withStructuredOutput(RecipeSchema, {\n * method: \"jsonSchema\"\n * });\n *\n * const recipe = await structuredLlm.invoke(\n * \"Give me a simple recipe for chocolate chip cookies\"\n * );\n * console.log(recipe);\n * ```\n *\n * ```txt\n * {\n * recipeName: 'Classic Chocolate Chip Cookies',\n * ingredients: [\n * '2 1/4 cups all-purpose flour',\n * '1 cup butter, softened',\n * ...\n * ],\n * steps: [\n * 'Preheat oven to 375°F',\n * 'Mix butter and sugars until creamy',\n * ...\n * ],\n * prepTime: 15\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-sonnet-4-5-20250929',\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;\n\n topK?: number;\n\n topP?: number;\n\n maxTokens: number;\n\n modelName = \"claude-3-5-sonnet-latest\";\n\n model = \"claude-3-5-sonnet-latest\";\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 betas?: AnthropicBeta[];\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?: ChatAnthropicInput) {\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 this.topP = fields?.topP ?? this.topP;\n\n this.temperature = fields?.temperature ?? this.temperature;\n this.topK = fields?.topK ?? this.topK;\n this.maxTokens =\n fields?.maxTokens ?? defaultMaxOutputTokensForModel(this.model);\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 this.betas = fields?.betas ?? this.betas;\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) {\n return undefined;\n }\n return tools.map((tool) => {\n if (isLangChainTool(tool) && tool.extras?.providerToolDefinition) {\n return tool.extras\n .providerToolDefinition as Anthropic.Messages.ToolUnion;\n }\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 ...(tool.extras ? AnthropicToolExtrasSchema.parse(tool.extras) : {}),\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 ): AnthropicInvocationParams {\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 const toolBetas = options?.tools?.reduce<AnthropicBeta[]>((acc, tool) => {\n if (\n typeof tool === \"object\" &&\n \"type\" in tool &&\n tool.type in ANTHROPIC_TOOL_BETAS\n ) {\n const beta = ANTHROPIC_TOOL_BETAS[tool.type];\n if (!acc.includes(beta)) {\n return [...acc, beta];\n }\n }\n return acc;\n }, []);\n\n const output: AnthropicInvocationParams = {\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 betas: _combineBetas(this.betas, options?.betas, toolBetas ?? []),\n output_format: options?.output_format,\n mcp_servers: options?.mcp_servers,\n };\n\n if (this.thinking.type === \"enabled\") {\n if (this.topP !== undefined && this.topK !== -1) {\n throw new Error(\"topK is not supported when thinking is enabled\");\n }\n if (this.temperature !== undefined && this.temperature !== 1) {\n throw new Error(\n \"temperature is not supported when thinking is enabled\"\n );\n }\n } else {\n // Only set temperature, top_k, and top_p if thinking is disabled\n output.temperature = this.temperature;\n output.top_k = this.topK;\n output.top_p = this.topP;\n }\n\n return output;\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 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 { betas, ...rest } = request;\n\n const makeCompletionRequest = async () => {\n try {\n if (request?.betas?.length) {\n const stream = await this.streamingClient.beta.messages.create(\n {\n ...rest,\n betas,\n ...this.invocationKwargs,\n stream: true,\n } as AnthropicStreamingMessageCreateParams,\n options\n );\n return stream as Stream<Anthropic.Messages.RawMessageStreamEvent>;\n }\n return await this.streamingClient.messages.create(\n {\n ...rest,\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 { betas, ...rest } = request;\n\n const makeCompletionRequest = async () => {\n try {\n if (request?.betas?.length) {\n const response = await this.batchClient.beta.messages.create(\n {\n ...rest,\n ...this.invocationKwargs,\n betas,\n } as AnthropicMessageCreateParams,\n options\n );\n return response as Anthropic.Messages.Message;\n }\n return await this.batchClient.messages.create(\n {\n ...rest,\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 /**\n * Return profiling information for the model.\n *\n * Provides information about the model's capabilities and constraints,\n * including token limits, multimodal support, and advanced features like\n * tool calling and structured output.\n *\n * @returns {ModelProfile} An object describing the model's capabilities and constraints\n *\n * @example\n * ```typescript\n * const model = new ChatAnthropic({ model: \"claude-opus-4-0\" });\n * const profile = model.profile;\n * console.log(profile.maxInputTokens); // 200000\n * console.log(profile.imageInputs); // true\n * ```\n */\n get profile(): ModelProfile {\n return PROFILES[this.model] ?? {};\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 let llm: Runnable<BaseLanguageModelInput>;\n let outputParser: Runnable<AIMessageChunk, RunOutput>;\n\n const { schema, name, includeRaw } = {\n ...config,\n schema: outputSchema,\n };\n let method = config?.method ?? \"functionCalling\";\n\n if (method === \"jsonMode\") {\n console.warn(\n `\"jsonMode\" is not supported for Anthropic models. Falling back to \"jsonSchema\".`\n );\n method = \"jsonSchema\";\n }\n if (method === \"jsonSchema\") {\n // https://docs.claude.com/en/docs/build-with-claude/structured-outputs\n outputParser = isInteropZodSchema(schema)\n ? StructuredOutputParser.fromZodSchema(schema)\n : new JsonOutputParser<RunOutput>();\n const jsonSchema = transformJSONSchema(toJsonSchema(schema));\n llm = this.withConfig({\n outputVersion: \"v0\",\n output_format: {\n type: \"json_schema\",\n schema: jsonSchema,\n },\n betas: [\"structured-outputs-2025-11-13\"],\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: jsonSchema,\n },\n } as Partial<CallOptions>);\n } else if (method === \"functionCalling\") {\n let functionName = name ?? \"extract\";\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 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 outputVersion: \"v0\",\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 outputVersion: \"v0\",\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 } else {\n throw new TypeError(\n `Unrecognized structured output method '${method}'. Expected 'functionCalling' or 'jsonSchema'`\n );\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,MAAMA,kCAEF;CACF,mBAAmB;CACnB,iBAAiB;C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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"}
|
package/dist/chat_models.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat_models.js","names":["MODEL_DEFAULT_MAX_OUTPUT_TOKENS: Partial<\n Record<Anthropic.Model, number>\n>","model?: Anthropic.Model","params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams","tool: any","tool: unknown","a?: Iterable<AnthropicBeta>","b?: Iterable<AnthropicBeta>","chunk: AIMessageChunk","fields?: ChatAnthropicInput","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","output: AnthropicInvocationParams","messages: BaseMessage[]","runManager?: CallbackManagerForLLMRun","params: Omit<\n | Anthropic.Messages.MessageCreateParamsNonStreaming\n | Anthropic.Messages.MessageCreateParamsStreaming,\n \"messages\"\n > &\n Kwargs","requestOptions: AnthropicRequestOptions","finalChunk: ChatGenerationChunk | undefined","request: AnthropicStreamingMessageCreateParams & Kwargs","options?: AnthropicRequestOptions","request: AnthropicMessageCreateParams & Kwargs","options: AnthropicRequestOptions","options","PROFILES","outputSchema:\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>","config?: StructuredOutputMethodOptions<boolean>","llm: Runnable<BaseLanguageModelInput>","outputParser: Runnable<AIMessageChunk, RunOutput>","tools: Anthropic.Messages.Tool[]","anthropicTools: Anthropic.Messages.Tool","message: AIMessageChunk","input: any","config"],"sources":["../src/chat_models.ts"],"sourcesContent":["import { Anthropic, type ClientOptions } from \"@anthropic-ai/sdk\";\nimport type { Stream } from \"@anthropic-ai/sdk/streaming\";\nimport { transformJSONSchema } from \"@anthropic-ai/sdk/lib/transform-json-schema\";\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 { ModelProfile } from \"@langchain/core/language_models/profile\";\nimport { toJsonSchema } from \"@langchain/core/utils/json_schema\";\nimport {\n JsonOutputParser,\n StructuredOutputParser,\n} 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 {\n ANTHROPIC_TOOL_BETAS,\n AnthropicToolExtrasSchema,\n handleToolChoice,\n} 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 AnthropicInvocationParams,\n AnthropicMessageCreateParams,\n AnthropicMessageStreamEvent,\n AnthropicRequestOptions,\n AnthropicStreamingMessageCreateParams,\n AnthropicThinkingConfigParam,\n AnthropicToolChoice,\n ChatAnthropicOutputFormat,\n ChatAnthropicToolType,\n AnthropicMCPServerURLDefinition,\n Kwargs,\n} from \"./types.js\";\nimport { wrapAnthropicClientError } from \"./utils/errors.js\";\nimport PROFILES from \"./profiles.js\";\nimport { AnthropicBeta } from \"@anthropic-ai/sdk/resources\";\n\nconst MODEL_DEFAULT_MAX_OUTPUT_TOKENS: Partial<\n Record<Anthropic.Model, number>\n> = {\n \"claude-opus-4-1\": 8192,\n \"claude-opus-4\": 8192,\n \"claude-sonnet-4\": 8192,\n \"claude-sonnet-3-7-sonnet\": 8192,\n \"claude-3-5-sonnet\": 4096,\n \"claude-3-5-haiku\": 4096,\n \"claude-3-haiku\": 2048,\n};\nconst FALLBACK_MAX_OUTPUT_TOKENS = 2048;\n\nfunction defaultMaxOutputTokensForModel(model?: Anthropic.Model): number {\n if (!model) {\n return FALLBACK_MAX_OUTPUT_TOKENS;\n }\n const maxTokens = Object.entries(MODEL_DEFAULT_MAX_OUTPUT_TOKENS).find(\n ([key]) => model.startsWith(key)\n )?.[1];\n return maxTokens ?? FALLBACK_MAX_OUTPUT_TOKENS;\n}\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 * Output format to use for the response.\n */\n output_format?: ChatAnthropicOutputFormat;\n /**\n * Optional array of beta features to enable for the Anthropic API.\n * Beta features are experimental capabilities that may change or be removed.\n * See https://docs.anthropic.com/en/api/versioning for available beta features.\n */\n betas?: AnthropicBeta[];\n /**\n * Array of MCP server URLs to use for the request.\n */\n mcp_servers?: AnthropicMCPServerURLDefinition[];\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 \"tool_search_\",\n \"mcp_toolset\",\n ];\n return (\n typeof tool === \"object\" &&\n tool !== null &&\n \"type\" in tool &&\n (\"name\" in tool || \"mcp_server_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\nfunction _combineBetas(\n a?: Iterable<AnthropicBeta>,\n b?: Iterable<AnthropicBeta>,\n ...rest: Iterable<AnthropicBeta>[]\n): AnthropicBeta[] {\n return Array.from(\n new Set([...(a ?? []), ...(b ?? []), ...rest.flatMap((x) => Array.from(x))])\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 /**\n * Amount of randomness injected into the response. Ranges\n * from 0 to 1. Use temperature closer to 0 for analytical /\n * multiple choice, and temperature closer to 1 for creative\n * and generative tasks.\n */\n temperature?: number;\n\n /**\n * Only sample from the top K options for each subsequent\n * token. Used to remove \"long tail\" low probability\n * responses.\n */\n topK?: number;\n\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. Note that you should either alter\n * temperature or top_p, but not both.\n */\n topP?: number | null;\n\n /** A maximum number of tokens to generate before stopping. */\n maxTokens?: number;\n\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 * Optional array of beta features to enable for the Anthropic API.\n * Beta features are experimental capabilities that may change or be removed.\n * See https://docs.claude.com/en/api/beta-headers for available beta features.\n */\n betas?: AnthropicBeta[];\n}\n\n/**\n * Input to ChatAnthropic class.\n */\nexport type ChatAnthropicInput = AnthropicInput & BaseChatModelParams;\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-sonnet-4-5-20250929\",\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-sonnet-4-5-20250929\",\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-sonnet-4-5-20250929\"\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-sonnet-4-5-20250929\",\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>Tool Search</strong></summary>\n *\n * Tool search enables Claude to dynamically discover and load tools on-demand\n * instead of loading all tool definitions upfront. This is useful when you have\n * many tools but want to avoid the overhead of sending all definitions with every request.\n *\n * ```typescript\n * import { ChatAnthropic } from \"@langchain/anthropic\";\n *\n * const model = new ChatAnthropic({\n * model: \"claude-sonnet-4-5-20250929\",\n * });\n *\n * const tools = [\n * // Tool search server tool\n * {\n * type: \"tool_search_tool_regex_20251119\",\n * name: \"tool_search_tool_regex\",\n * },\n * // Tools with defer_loading are loaded on-demand\n * {\n * name: \"get_weather\",\n * description: \"Get the current weather for a location\",\n * input_schema: {\n * type: \"object\",\n * properties: {\n * location: { type: \"string\", description: \"City name\" },\n * unit: {\n * type: \"string\",\n * enum: [\"celsius\", \"fahrenheit\"],\n * },\n * },\n * required: [\"location\"],\n * },\n * defer_loading: true, // Tool is loaded on-demand\n * },\n * {\n * name: \"search_files\",\n * description: \"Search through files in the workspace\",\n * input_schema: {\n * type: \"object\",\n * properties: {\n * query: { type: \"string\" },\n * },\n * required: [\"query\"],\n * },\n * defer_loading: true, // Tool is loaded on-demand\n * },\n * ];\n *\n * const modelWithTools = model.bindTools(tools);\n * const response = await modelWithTools.invoke(\"What's the weather in San Francisco?\");\n * ```\n *\n * You can also use the `tool()` helper with the `extras` field:\n *\n * ```typescript\n * import { tool } from \"@langchain/core/tools\";\n * import { z } from \"zod\";\n *\n * const getWeather = tool(\n * async (input) => `Weather in ${input.location}`,\n * {\n * name: \"get_weather\",\n * description: \"Get weather for a location\",\n * schema: z.object({ location: z.string() }),\n * extras: { defer_loading: true },\n * }\n * );\n * ```\n *\n * **Note:** The required `advanced-tool-use-2025-11-20` beta header is automatically\n * appended to the request when using tool search tools.\n *\n * **Best practices:**\n * - Tools with `defer_loading: true` are only loaded when Claude discovers them via search\n * - Keep your 3-5 most frequently used tools as non-deferred for optimal performance\n * - Both regex and bm25 variants search tool names, descriptions, and argument info\n *\n * See the {@link https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool | Claude docs}\n * for more information.\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Structured Output</strong></summary>\n *\n * ChatAnthropic supports structured output through two main approaches:\n *\n * 1. **Function Calling with `withStructuredOutput()`**: Uses Anthropic's tool calling\n * under the hood to constrain outputs to a specific schema.\n * 2. **JSON Schema Mode**: Uses Anthropic's native JSON schema support for direct\n * structured output without tool calling overhead.\n *\n * **Using withStructuredOutput (Function Calling)**\n *\n * This method leverages Anthropic's tool calling capabilities to ensure the model\n * returns data matching your schema:\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 *\n * **Using JSON Schema Mode**\n *\n * For more direct control, you can use Anthropic's native JSON schema support by\n * passing `method: \"jsonSchema\"`:\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const RecipeSchema = z.object({\n * recipeName: z.string().describe(\"Name of the recipe\"),\n * ingredients: z.array(z.string()).describe(\"List of ingredients needed\"),\n * steps: z.array(z.string()).describe(\"Cooking steps in order\"),\n * prepTime: z.number().describe(\"Preparation time in minutes\")\n * });\n *\n * const structuredLlm = llm.withStructuredOutput(RecipeSchema, {\n * method: \"jsonSchema\"\n * });\n *\n * const recipe = await structuredLlm.invoke(\n * \"Give me a simple recipe for chocolate chip cookies\"\n * );\n * console.log(recipe);\n * ```\n *\n * ```txt\n * {\n * recipeName: 'Classic Chocolate Chip Cookies',\n * ingredients: [\n * '2 1/4 cups all-purpose flour',\n * '1 cup butter, softened',\n * ...\n * ],\n * steps: [\n * 'Preheat oven to 375°F',\n * 'Mix butter and sugars until creamy',\n * ...\n * ],\n * prepTime: 15\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-sonnet-4-5-20250929',\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;\n\n topK?: number;\n\n topP?: number;\n\n maxTokens: number;\n\n modelName = \"claude-3-5-sonnet-latest\";\n\n model = \"claude-3-5-sonnet-latest\";\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 betas?: AnthropicBeta[];\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?: ChatAnthropicInput) {\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 this.topP = fields?.topP ?? this.topP;\n\n this.temperature = fields?.temperature ?? this.temperature;\n this.topK = fields?.topK ?? this.topK;\n this.maxTokens =\n fields?.maxTokens ?? defaultMaxOutputTokensForModel(this.model);\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 this.betas = fields?.betas ?? this.betas;\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) {\n return undefined;\n }\n return tools.map((tool) => {\n if (isLangChainTool(tool) && tool.extras?.providerToolDefinition) {\n return tool.extras\n .providerToolDefinition as Anthropic.Messages.ToolUnion;\n }\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 ...(tool.extras ? AnthropicToolExtrasSchema.parse(tool.extras) : {}),\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 ): AnthropicInvocationParams {\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 const toolBetas = options?.tools?.reduce<AnthropicBeta[]>((acc, tool) => {\n if (\n typeof tool === \"object\" &&\n \"type\" in tool &&\n tool.type in ANTHROPIC_TOOL_BETAS\n ) {\n const beta = ANTHROPIC_TOOL_BETAS[tool.type];\n if (!acc.includes(beta)) {\n return [...acc, beta];\n }\n }\n return acc;\n }, []);\n\n const output: AnthropicInvocationParams = {\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 betas: _combineBetas(this.betas, options?.betas, toolBetas ?? []),\n output_format: options?.output_format,\n mcp_servers: options?.mcp_servers,\n };\n\n if (this.thinking.type === \"enabled\") {\n if (this.topP !== undefined && this.topK !== -1) {\n throw new Error(\"topK is not supported when thinking is enabled\");\n }\n if (this.temperature !== undefined && this.temperature !== 1) {\n throw new Error(\n \"temperature is not supported when thinking is enabled\"\n );\n }\n } else {\n // Only set temperature, top_k, and top_p if thinking is disabled\n output.temperature = this.temperature;\n output.top_k = this.topK;\n output.top_p = this.topP;\n }\n\n return output;\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 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 { betas, ...rest } = request;\n\n const makeCompletionRequest = async () => {\n try {\n if (request?.betas?.length) {\n const stream = await this.streamingClient.beta.messages.create(\n {\n ...rest,\n betas,\n ...this.invocationKwargs,\n stream: true,\n } as AnthropicStreamingMessageCreateParams,\n options\n );\n return stream as Stream<Anthropic.Messages.RawMessageStreamEvent>;\n }\n return await this.streamingClient.messages.create(\n {\n ...rest,\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 { betas, ...rest } = request;\n\n const makeCompletionRequest = async () => {\n try {\n if (request?.betas?.length) {\n const response = await this.batchClient.beta.messages.create(\n {\n ...rest,\n ...this.invocationKwargs,\n betas,\n } as AnthropicMessageCreateParams,\n options\n );\n return response as Anthropic.Messages.Message;\n }\n return await this.batchClient.messages.create(\n {\n ...rest,\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 /**\n * Return profiling information for the model.\n *\n * Provides information about the model's capabilities and constraints,\n * including token limits, multimodal support, and advanced features like\n * tool calling and structured output.\n *\n * @returns {ModelProfile} An object describing the model's capabilities and constraints\n *\n * @example\n * ```typescript\n * const model = new ChatAnthropic({ model: \"claude-opus-4-0\" });\n * const profile = model.profile;\n * console.log(profile.maxInputTokens); // 200000\n * console.log(profile.imageInputs); // true\n * ```\n */\n get profile(): ModelProfile {\n return PROFILES[this.model] ?? {};\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 let llm: Runnable<BaseLanguageModelInput>;\n let outputParser: Runnable<AIMessageChunk, RunOutput>;\n\n const { schema, name, includeRaw } = {\n ...config,\n schema: outputSchema,\n };\n let method = config?.method ?? \"functionCalling\";\n\n if (method === \"jsonMode\") {\n console.warn(\n `\"jsonMode\" is not supported for Anthropic models. Falling back to \"jsonSchema\".`\n );\n method = \"jsonSchema\";\n }\n if (method === \"jsonSchema\") {\n // https://docs.claude.com/en/docs/build-with-claude/structured-outputs\n outputParser = isInteropZodSchema(schema)\n ? StructuredOutputParser.fromZodSchema(schema)\n : new JsonOutputParser<RunOutput>();\n const jsonSchema = transformJSONSchema(toJsonSchema(schema));\n llm = this.withConfig({\n outputVersion: \"v0\",\n output_format: {\n type: \"json_schema\",\n schema: jsonSchema,\n },\n betas: [\"structured-outputs-2025-11-13\"],\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: jsonSchema,\n },\n } as Partial<CallOptions>);\n } else if (method === \"functionCalling\") {\n let functionName = name ?? \"extract\";\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 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 outputVersion: \"v0\",\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 outputVersion: \"v0\",\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 } else {\n throw new TypeError(\n `Unrecognized structured output method '${method}'. Expected 'functionCalling' or 'jsonSchema'`\n );\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,MAAMA,kCAEF;CACF,mBAAmB;CACnB,iBAAiB;CACjB,mBAAmB;CACnB,4BAA4B;CAC5B,qBAAqB;CACrB,oBAAoB;CACpB,kBAAkB;AACnB;AACD,MAAM,6BAA6B;AAEnC,SAAS,+BAA+BC,OAAiC;AACvE,KAAI,CAAC,MACH,QAAO;CAET,MAAM,YAAY,OAAO,QAAQ,gCAAgC,CAAC,KAChE,CAAC,CAAC,IAAI,KAAK,MAAM,WAAW,IAAI,CACjC,GAAG;AACJ,QAAO,aAAa;AACrB;AAqCD,SAAS,eACPC,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;AAE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;KACA,6BAA6B;MAC3B,QAAQ,EAAE,QAAQ,kBAAmB;MACrC,QAAQ,aAAa,OAAO;KAC7B;IACF,EAAyB;IAE1B,MAAM,qBAAqB,CAACC,YAA4B;AACtD,SAAI,CAAC,QAAQ,cAAc,QAAQ,WAAW,WAAW,EACvD,OAAM,IAAI,MAAM;AAElB,YAAO;IACR;IAED,MAAM,IAAI,KAAK,mBAAmB;GACnC,OACC,MAAM,KAAK,WAAW;IACpB,eAAe;IACf;IACA,aAAa;KACX,MAAM;KACN,MAAM;IACP;IACD,6BAA6B;KAC3B,QAAQ,EAAE,QAAQ,kBAAmB;KACrC,QAAQ,aAAa,OAAO;IAC7B;GACF,EAAyB;EAE7B,MACC,OAAM,IAAI,UACR,CAAC,uCAAuC,EAAE,OAAO,6CAA6C,CAAC;AAInG,MAAI,CAAC,WACH,QAAO,IAAI,KAAK,aAAa,CAAC,WAAW,EACvC,SAAS,gCACV,EAAC;EAGJ,MAAM,eAAe,oBAAoB,OAAO,EAE9C,QAAQ,CAACC,OAAYC,aAAW,aAAa,OAAO,MAAM,KAAKA,SAAO,CACvE,EAAC;EACF,MAAM,aAAa,oBAAoB,OAAO,EAC5C,QAAQ,MAAM,KACf,EAAC;EACF,MAAM,qBAAqB,aAAa,cAAc,EACpD,WAAW,CAAC,UAAW,EACxB,EAAC;AACF,SAAO,iBAAiB,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.js","names":["MODEL_DEFAULT_MAX_OUTPUT_TOKENS: Partial<\n Record<Anthropic.Model, number>\n>","model?: Anthropic.Model","params: AnthropicMessageCreateParams | AnthropicStreamingMessageCreateParams","tool: any","tool: unknown","a?: Iterable<AnthropicBeta>","b?: Iterable<AnthropicBeta>","chunk: AIMessageChunk","fields?: ChatAnthropicInput","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","output: AnthropicInvocationParams","messages: BaseMessage[]","runManager?: CallbackManagerForLLMRun","params: Omit<\n | Anthropic.Messages.MessageCreateParamsNonStreaming\n | Anthropic.Messages.MessageCreateParamsStreaming,\n \"messages\"\n > &\n Kwargs","requestOptions: AnthropicRequestOptions","finalChunk: ChatGenerationChunk | undefined","request: AnthropicStreamingMessageCreateParams & Kwargs","options?: AnthropicRequestOptions","request: AnthropicMessageCreateParams & Kwargs","options: AnthropicRequestOptions","options","PROFILES","outputSchema:\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>","config?: StructuredOutputMethodOptions<boolean>","llm: Runnable<BaseLanguageModelInput>","outputParser: Runnable<AIMessageChunk, RunOutput>","tools: Anthropic.Messages.Tool[]","anthropicTools: Anthropic.Messages.Tool","message: AIMessageChunk","input: any","config"],"sources":["../src/chat_models.ts"],"sourcesContent":["import { Anthropic, type ClientOptions } from \"@anthropic-ai/sdk\";\nimport type { Stream } from \"@anthropic-ai/sdk/streaming\";\nimport { transformJSONSchema } from \"@anthropic-ai/sdk/lib/transform-json-schema\";\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 { ModelProfile } from \"@langchain/core/language_models/profile\";\nimport { toJsonSchema } from \"@langchain/core/utils/json_schema\";\nimport {\n JsonOutputParser,\n StructuredOutputParser,\n} 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 {\n ANTHROPIC_TOOL_BETAS,\n AnthropicToolExtrasSchema,\n handleToolChoice,\n} 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 AnthropicInvocationParams,\n AnthropicMessageCreateParams,\n AnthropicMessageStreamEvent,\n AnthropicRequestOptions,\n AnthropicStreamingMessageCreateParams,\n AnthropicThinkingConfigParam,\n AnthropicToolChoice,\n ChatAnthropicOutputFormat,\n ChatAnthropicToolType,\n AnthropicMCPServerURLDefinition,\n Kwargs,\n} from \"./types.js\";\nimport { wrapAnthropicClientError } from \"./utils/errors.js\";\nimport PROFILES from \"./profiles.js\";\nimport { AnthropicBeta } from \"@anthropic-ai/sdk/resources\";\n\nconst MODEL_DEFAULT_MAX_OUTPUT_TOKENS: Partial<\n Record<Anthropic.Model, number>\n> = {\n \"claude-opus-4-1\": 8192,\n \"claude-opus-4\": 8192,\n \"claude-sonnet-4\": 8192,\n \"claude-sonnet-3-7-sonnet\": 8192,\n \"claude-3-5-sonnet\": 4096,\n \"claude-3-5-haiku\": 4096,\n \"claude-3-haiku\": 2048,\n};\nconst FALLBACK_MAX_OUTPUT_TOKENS = 2048;\n\nfunction defaultMaxOutputTokensForModel(model?: Anthropic.Model): number {\n if (!model) {\n return FALLBACK_MAX_OUTPUT_TOKENS;\n }\n const maxTokens = Object.entries(MODEL_DEFAULT_MAX_OUTPUT_TOKENS).find(\n ([key]) => model.startsWith(key)\n )?.[1];\n return maxTokens ?? FALLBACK_MAX_OUTPUT_TOKENS;\n}\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 * Output format to use for the response.\n */\n output_format?: ChatAnthropicOutputFormat;\n /**\n * Optional array of beta features to enable for the Anthropic API.\n * Beta features are experimental capabilities that may change or be removed.\n * See https://docs.anthropic.com/en/api/versioning for available beta features.\n */\n betas?: AnthropicBeta[];\n /**\n * Array of MCP server URLs to use for the request.\n */\n mcp_servers?: AnthropicMCPServerURLDefinition[];\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 \"tool_search_\",\n \"mcp_toolset\",\n ];\n return (\n typeof tool === \"object\" &&\n tool !== null &&\n \"type\" in tool &&\n (\"name\" in tool || \"mcp_server_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\nfunction _combineBetas(\n a?: Iterable<AnthropicBeta>,\n b?: Iterable<AnthropicBeta>,\n ...rest: Iterable<AnthropicBeta>[]\n): AnthropicBeta[] {\n return Array.from(\n new Set([...(a ?? []), ...(b ?? []), ...rest.flatMap((x) => Array.from(x))])\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 /**\n * Amount of randomness injected into the response. Ranges\n * from 0 to 1. Use temperature closer to 0 for analytical /\n * multiple choice, and temperature closer to 1 for creative\n * and generative tasks.\n */\n temperature?: number;\n\n /**\n * Only sample from the top K options for each subsequent\n * token. Used to remove \"long tail\" low probability\n * responses.\n */\n topK?: number;\n\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. Note that you should either alter\n * temperature or top_p, but not both.\n */\n topP?: number | null;\n\n /** A maximum number of tokens to generate before stopping. */\n maxTokens?: number;\n\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 * Optional array of beta features to enable for the Anthropic API.\n * Beta features are experimental capabilities that may change or be removed.\n * See https://docs.claude.com/en/api/beta-headers for available beta features.\n */\n betas?: AnthropicBeta[];\n}\n\n/**\n * Input to ChatAnthropic class.\n */\nexport type ChatAnthropicInput = AnthropicInput & BaseChatModelParams;\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-sonnet-4-5-20250929\",\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-sonnet-4-5-20250929\",\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-sonnet-4-5-20250929\"\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-sonnet-4-5-20250929\",\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>Tool Search</strong></summary>\n *\n * Tool search enables Claude to dynamically discover and load tools on-demand\n * instead of loading all tool definitions upfront. This is useful when you have\n * many tools but want to avoid the overhead of sending all definitions with every request.\n *\n * ```typescript\n * import { ChatAnthropic } from \"@langchain/anthropic\";\n *\n * const model = new ChatAnthropic({\n * model: \"claude-sonnet-4-5-20250929\",\n * });\n *\n * const tools = [\n * // Tool search server tool\n * {\n * type: \"tool_search_tool_regex_20251119\",\n * name: \"tool_search_tool_regex\",\n * },\n * // Tools with defer_loading are loaded on-demand\n * {\n * name: \"get_weather\",\n * description: \"Get the current weather for a location\",\n * input_schema: {\n * type: \"object\",\n * properties: {\n * location: { type: \"string\", description: \"City name\" },\n * unit: {\n * type: \"string\",\n * enum: [\"celsius\", \"fahrenheit\"],\n * },\n * },\n * required: [\"location\"],\n * },\n * defer_loading: true, // Tool is loaded on-demand\n * },\n * {\n * name: \"search_files\",\n * description: \"Search through files in the workspace\",\n * input_schema: {\n * type: \"object\",\n * properties: {\n * query: { type: \"string\" },\n * },\n * required: [\"query\"],\n * },\n * defer_loading: true, // Tool is loaded on-demand\n * },\n * ];\n *\n * const modelWithTools = model.bindTools(tools);\n * const response = await modelWithTools.invoke(\"What's the weather in San Francisco?\");\n * ```\n *\n * You can also use the `tool()` helper with the `extras` field:\n *\n * ```typescript\n * import { tool } from \"@langchain/core/tools\";\n * import { z } from \"zod\";\n *\n * const getWeather = tool(\n * async (input) => `Weather in ${input.location}`,\n * {\n * name: \"get_weather\",\n * description: \"Get weather for a location\",\n * schema: z.object({ location: z.string() }),\n * extras: { defer_loading: true },\n * }\n * );\n * ```\n *\n * **Note:** The required `advanced-tool-use-2025-11-20` beta header is automatically\n * appended to the request when using tool search tools.\n *\n * **Best practices:**\n * - Tools with `defer_loading: true` are only loaded when Claude discovers them via search\n * - Keep your 3-5 most frequently used tools as non-deferred for optimal performance\n * - Both regex and bm25 variants search tool names, descriptions, and argument info\n *\n * See the {@link https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool | Claude docs}\n * for more information.\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Structured Output</strong></summary>\n *\n * ChatAnthropic supports structured output through two main approaches:\n *\n * 1. **Function Calling with `withStructuredOutput()`**: Uses Anthropic's tool calling\n * under the hood to constrain outputs to a specific schema.\n * 2. **JSON Schema Mode**: Uses Anthropic's native JSON schema support for direct\n * structured output without tool calling overhead.\n *\n * **Using withStructuredOutput (Function Calling)**\n *\n * This method leverages Anthropic's tool calling capabilities to ensure the model\n * returns data matching your schema:\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 *\n * **Using JSON Schema Mode**\n *\n * For more direct control, you can use Anthropic's native JSON schema support by\n * passing `method: \"jsonSchema\"`:\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const RecipeSchema = z.object({\n * recipeName: z.string().describe(\"Name of the recipe\"),\n * ingredients: z.array(z.string()).describe(\"List of ingredients needed\"),\n * steps: z.array(z.string()).describe(\"Cooking steps in order\"),\n * prepTime: z.number().describe(\"Preparation time in minutes\")\n * });\n *\n * const structuredLlm = llm.withStructuredOutput(RecipeSchema, {\n * method: \"jsonSchema\"\n * });\n *\n * const recipe = await structuredLlm.invoke(\n * \"Give me a simple recipe for chocolate chip cookies\"\n * );\n * console.log(recipe);\n * ```\n *\n * ```txt\n * {\n * recipeName: 'Classic Chocolate Chip Cookies',\n * ingredients: [\n * '2 1/4 cups all-purpose flour',\n * '1 cup butter, softened',\n * ...\n * ],\n * steps: [\n * 'Preheat oven to 375°F',\n * 'Mix butter and sugars until creamy',\n * ...\n * ],\n * prepTime: 15\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-sonnet-4-5-20250929',\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;\n\n topK?: number;\n\n topP?: number;\n\n maxTokens: number;\n\n modelName = \"claude-3-5-sonnet-latest\";\n\n model = \"claude-3-5-sonnet-latest\";\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 betas?: AnthropicBeta[];\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?: ChatAnthropicInput) {\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 this.topP = fields?.topP ?? this.topP;\n\n this.temperature = fields?.temperature ?? this.temperature;\n this.topK = fields?.topK ?? this.topK;\n this.maxTokens =\n fields?.maxTokens ?? defaultMaxOutputTokensForModel(this.model);\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 this.betas = fields?.betas ?? this.betas;\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) {\n return undefined;\n }\n return tools.map((tool) => {\n if (isLangChainTool(tool) && tool.extras?.providerToolDefinition) {\n return tool.extras\n .providerToolDefinition as Anthropic.Messages.ToolUnion;\n }\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 ...(tool.extras ? AnthropicToolExtrasSchema.parse(tool.extras) : {}),\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 ): AnthropicInvocationParams {\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 const toolBetas = options?.tools?.reduce<AnthropicBeta[]>((acc, tool) => {\n if (\n typeof tool === \"object\" &&\n \"type\" in tool &&\n tool.type in ANTHROPIC_TOOL_BETAS\n ) {\n const beta = ANTHROPIC_TOOL_BETAS[tool.type];\n if (!acc.includes(beta)) {\n return [...acc, beta];\n }\n }\n return acc;\n }, []);\n\n const output: AnthropicInvocationParams = {\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 betas: _combineBetas(this.betas, options?.betas, toolBetas ?? []),\n output_format: options?.output_format,\n mcp_servers: options?.mcp_servers,\n };\n\n if (this.thinking.type === \"enabled\") {\n if (this.topP !== undefined && this.topK !== -1) {\n throw new Error(\"topK is not supported when thinking is enabled\");\n }\n if (this.temperature !== undefined && this.temperature !== 1) {\n throw new Error(\n \"temperature is not supported when thinking is enabled\"\n );\n }\n } else {\n // Only set temperature, top_k, and top_p if thinking is disabled\n output.temperature = this.temperature;\n output.top_k = this.topK;\n output.top_p = this.topP;\n }\n\n return output;\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 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 { betas, ...rest } = request;\n\n const makeCompletionRequest = async () => {\n try {\n if (request?.betas?.length) {\n const stream = await this.streamingClient.beta.messages.create(\n {\n ...rest,\n betas,\n ...this.invocationKwargs,\n stream: true,\n } as AnthropicStreamingMessageCreateParams,\n options\n );\n return stream as Stream<Anthropic.Messages.RawMessageStreamEvent>;\n }\n return await this.streamingClient.messages.create(\n {\n ...rest,\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 { betas, ...rest } = request;\n\n const makeCompletionRequest = async () => {\n try {\n if (request?.betas?.length) {\n const response = await this.batchClient.beta.messages.create(\n {\n ...rest,\n ...this.invocationKwargs,\n betas,\n } as AnthropicMessageCreateParams,\n options\n );\n return response as Anthropic.Messages.Message;\n }\n return await this.batchClient.messages.create(\n {\n ...rest,\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 /**\n * Return profiling information for the model.\n *\n * Provides information about the model's capabilities and constraints,\n * including token limits, multimodal support, and advanced features like\n * tool calling and structured output.\n *\n * @returns {ModelProfile} An object describing the model's capabilities and constraints\n *\n * @example\n * ```typescript\n * const model = new ChatAnthropic({ model: \"claude-opus-4-0\" });\n * const profile = model.profile;\n * console.log(profile.maxInputTokens); // 200000\n * console.log(profile.imageInputs); // true\n * ```\n */\n get profile(): ModelProfile {\n return PROFILES[this.model] ?? {};\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 let llm: Runnable<BaseLanguageModelInput>;\n let outputParser: Runnable<AIMessageChunk, RunOutput>;\n\n const { schema, name, includeRaw } = {\n ...config,\n schema: outputSchema,\n };\n let method = config?.method ?? \"functionCalling\";\n\n if (method === \"jsonMode\") {\n console.warn(\n `\"jsonMode\" is not supported for Anthropic models. Falling back to \"jsonSchema\".`\n );\n method = \"jsonSchema\";\n }\n if (method === \"jsonSchema\") {\n // https://docs.claude.com/en/docs/build-with-claude/structured-outputs\n outputParser = isInteropZodSchema(schema)\n ? StructuredOutputParser.fromZodSchema(schema)\n : new JsonOutputParser<RunOutput>();\n const jsonSchema = transformJSONSchema(toJsonSchema(schema));\n llm = this.withConfig({\n outputVersion: \"v0\",\n output_format: {\n type: \"json_schema\",\n schema: jsonSchema,\n },\n betas: [\"structured-outputs-2025-11-13\"],\n ls_structured_output_format: {\n kwargs: { method: \"json_schema\" },\n schema: jsonSchema,\n },\n } as Partial<CallOptions>);\n } else if (method === \"functionCalling\") {\n let functionName = name ?? \"extract\";\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 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 outputVersion: \"v0\",\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 outputVersion: \"v0\",\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 } else {\n throw new TypeError(\n `Unrecognized structured output method '${method}'. Expected 'functionCalling' or 'jsonSchema'`\n );\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,MAAMA,kCAEF;CACF,mBAAmB;CACnB,iBAAiB;CACjB,mBAAmB;CACnB,4BAA4B;CAC5B,qBAAqB;CACrB,oBAAoB;CACpB,kBAAkB;AACnB;AACD,MAAM,6BAA6B;AAEnC,SAAS,+BAA+BC,OAAiC;AACvE,KAAI,CAAC,MACH,QAAO;CAET,MAAM,YAAY,OAAO,QAAQ,gCAAgC,CAAC,KAChE,CAAC,CAAC,IAAI,KAAK,MAAM,WAAW,IAAI,CACjC,GAAG;AACJ,QAAO,aAAa;AACrB;AAqCD,SAAS,eACPC,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,YAC3B,MAAM,WAAW,QAEjB,QAAO;CAGZ;AACD,QAAO;AACR;AAED,SAAS,kBACPA,QACS;AACT,QAAO,CAAC,EAAE,OAAO,YAAY,OAAO,SAAS,SAAS;AACvD;AAGD,SAAS,gBAAgBC,MAA4C;AACnE,QAAO,kBAAkB;AAC1B;AAED,SAAS,cAAcC,MAAkD;CACvE,MAAM,sBAAsB;EAC1B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD;AACD,QACE,OAAO,SAAS,YAChB,SAAS,QACT,UAAU,SACT,UAAU,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uC,EAAE,OAAO,6CAA6C,CAAC;AAInG,MAAI,CAAC,WACH,QAAO,IAAI,KAAK,aAAa,CAAC,WAAW,EACvC,SAAS,gCACV,EAAC;EAGJ,MAAM,eAAe,oBAAoB,OAAO,EAE9C,QAAQ,CAACC,OAAYC,aAAW,aAAa,OAAO,MAAM,KAAKA,SAAO,CACvE,EAAC;EACF,MAAM,aAAa,oBAAoB,OAAO,EAC5C,QAAQ,MAAM,KACf,EAAC;EACF,MAAM,qBAAqB,aAAa,cAAc,EACpD,WAAW,CAAC,UAAW,EACxB,EAAC;AACF,SAAO,iBAAiB,KAGtB,CACA,EACE,KAAK,IACN,GACD,kBACD,EAAC,CAAC,WAAW,EACZ,SAAS,2BACV,EAAC;CACH;AACF;AAED,IAAa,gBAAb,cAAmC,sBAAsB,CAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"output_parsers.cjs","names":["BaseLLMOutputParser","params: AnthropicToolsOutputParserParams<T>","result: unknown","e: any","OutputParserException","generations: ChatGeneration[]","tool","content: Record<string, any>[]","toolCalls: ToolCall[]"],"sources":["../src/output_parsers.ts"],"sourcesContent":["import {\n BaseLLMOutputParser,\n OutputParserException,\n} from \"@langchain/core/output_parsers\";\nimport { JsonOutputKeyToolsParserParamsInterop } from \"@langchain/core/output_parsers/openai_tools\";\nimport { ChatGeneration } from \"@langchain/core/outputs\";\nimport { ToolCall } from \"@langchain/core/messages/tool\";\nimport {\n interopSafeParseAsync,\n InteropZodType,\n} from \"@langchain/core/utils/types\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ninterface AnthropicToolsOutputParserParams<T extends Record<string, any>>\n extends JsonOutputKeyToolsParserParamsInterop<T> {}\n\nexport class AnthropicToolsOutputParser<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any
|
|
1
|
+
{"version":3,"file":"output_parsers.cjs","names":["BaseLLMOutputParser","params: AnthropicToolsOutputParserParams<T>","result: unknown","e: any","OutputParserException","generations: ChatGeneration[]","tool","content: Record<string, any>[]","toolCalls: ToolCall[]"],"sources":["../src/output_parsers.ts"],"sourcesContent":["import {\n BaseLLMOutputParser,\n OutputParserException,\n} from \"@langchain/core/output_parsers\";\nimport { JsonOutputKeyToolsParserParamsInterop } from \"@langchain/core/output_parsers/openai_tools\";\nimport { ChatGeneration } from \"@langchain/core/outputs\";\nimport { ToolCall } from \"@langchain/core/messages/tool\";\nimport {\n interopSafeParseAsync,\n InteropZodType,\n} from \"@langchain/core/utils/types\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ninterface AnthropicToolsOutputParserParams<T extends Record<string, any>>\n extends JsonOutputKeyToolsParserParamsInterop<T> {}\n\nexport class AnthropicToolsOutputParser<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> extends BaseLLMOutputParser<T> {\n static lc_name() {\n return \"AnthropicToolsOutputParser\";\n }\n\n lc_namespace = [\"langchain\", \"anthropic\", \"output_parsers\"];\n\n returnId = false;\n\n /** The type of tool calls to return. */\n keyName: string;\n\n /** Whether to return only the first tool call. */\n returnSingle = false;\n\n zodSchema?: InteropZodType<T>;\n\n constructor(params: AnthropicToolsOutputParserParams<T>) {\n super(params);\n this.keyName = params.keyName;\n this.returnSingle = params.returnSingle ?? this.returnSingle;\n this.zodSchema = params.zodSchema;\n }\n\n protected async _validateResult(result: unknown): Promise<T> {\n let parsedResult = result;\n if (typeof result === \"string\") {\n try {\n parsedResult = JSON.parse(result);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${JSON.stringify(\n result,\n null,\n 2\n )}\". Error: ${JSON.stringify(e.message)}`,\n result\n );\n }\n } else {\n parsedResult = result;\n }\n if (this.zodSchema === undefined) {\n return parsedResult as T;\n }\n const zodParsedResult = await interopSafeParseAsync(\n this.zodSchema,\n parsedResult\n );\n if (zodParsedResult.success) {\n return zodParsedResult.data;\n } else {\n throw new OutputParserException(\n `Failed to parse. Text: \"${JSON.stringify(\n result,\n null,\n 2\n )}\". Error: ${JSON.stringify(zodParsedResult.error.issues)}`,\n JSON.stringify(parsedResult, null, 2)\n );\n }\n }\n\n async parseResult(generations: ChatGeneration[]): Promise<T> {\n const tools = generations.flatMap((generation) => {\n const { message } = generation;\n if (!Array.isArray(message.content)) {\n return [];\n }\n const tool = extractToolCalls(message.content)[0];\n return tool;\n });\n if (tools[0] === undefined) {\n throw new Error(\n \"No parseable tool calls provided to AnthropicToolsOutputParser.\"\n );\n }\n const [tool] = tools;\n const validatedResult = await this._validateResult(tool.args);\n return validatedResult;\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function extractToolCalls(content: Record<string, any>[]) {\n const toolCalls: ToolCall[] = [];\n\n for (const block of content) {\n if (block.type === \"tool_use\") {\n toolCalls.push({\n name: block.name,\n args: block.input,\n id: block.id,\n type: \"tool_call\",\n });\n }\n }\n\n return toolCalls;\n}\n"],"mappings":";;;;;AAgBA,IAAa,6BAAb,cAGUA,oDAAuB;CAC/B,OAAO,UAAU;AACf,SAAO;CACR;CAED,eAAe;EAAC;EAAa;EAAa;CAAiB;CAE3D,WAAW;;CAGX;;CAGA,eAAe;CAEf;CAEA,YAAYC,QAA6C;EACvD,MAAM,OAAO;EACb,KAAK,UAAU,OAAO;EACtB,KAAK,eAAe,OAAO,gBAAgB,KAAK;EAChD,KAAK,YAAY,OAAO;CACzB;CAED,MAAgB,gBAAgBC,QAA6B;EAC3D,IAAI,eAAe;AACnB,MAAI,OAAO,WAAW,SACpB,KAAI;GACF,eAAe,KAAK,MAAM,OAAO;EAElC,SAAQC,GAAQ;AACf,SAAM,IAAIC,sDACR,CAAC,wBAAwB,EAAE,KAAK,UAC9B,QACA,MACA,EACD,CAAC,UAAU,EAAE,KAAK,UAAU,EAAE,QAAQ,EAAE,EACzC;EAEH;OAED,eAAe;AAEjB,MAAI,KAAK,cAAc,OACrB,QAAO;EAET,MAAM,kBAAkB,8DACtB,KAAK,WACL,aACD;AACD,MAAI,gBAAgB,QAClB,QAAO,gBAAgB;MAEvB,OAAM,IAAIA,sDACR,CAAC,wBAAwB,EAAE,KAAK,UAC9B,QACA,MACA,EACD,CAAC,UAAU,EAAE,KAAK,UAAU,gBAAgB,MAAM,OAAO,EAAE,EAC5D,KAAK,UAAU,cAAc,MAAM,EAAE;CAG1C;CAED,MAAM,YAAYC,aAA2C;EAC3D,MAAM,QAAQ,YAAY,QAAQ,CAAC,eAAe;GAChD,MAAM,EAAE,SAAS,GAAG;AACpB,OAAI,CAAC,MAAM,QAAQ,QAAQ,QAAQ,CACjC,QAAO,CAAE;GAEX,MAAMC,SAAO,iBAAiB,QAAQ,QAAQ,CAAC;AAC/C,UAAOA;EACR,EAAC;AACF,MAAI,MAAM,OAAO,OACf,OAAM,IAAI,MACR;EAGJ,MAAM,CAAC,KAAK,GAAG;EACf,MAAM,kBAAkB,MAAM,KAAK,gBAAgB,KAAK,KAAK;AAC7D,SAAO;CACR;AACF;AAGD,SAAgB,iBAAiBC,SAAgC;CAC/D,MAAMC,YAAwB,CAAE;AAEhC,MAAK,MAAM,SAAS,QAClB,KAAI,MAAM,SAAS,YACjB,UAAU,KAAK;EACb,MAAM,MAAM;EACZ,MAAM,MAAM;EACZ,IAAI,MAAM;EACV,MAAM;CACP,EAAC;AAIN,QAAO;AACR"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"output_parsers.js","names":["params: AnthropicToolsOutputParserParams<T>","result: unknown","e: any","generations: ChatGeneration[]","tool","content: Record<string, any>[]","toolCalls: ToolCall[]"],"sources":["../src/output_parsers.ts"],"sourcesContent":["import {\n BaseLLMOutputParser,\n OutputParserException,\n} from \"@langchain/core/output_parsers\";\nimport { JsonOutputKeyToolsParserParamsInterop } from \"@langchain/core/output_parsers/openai_tools\";\nimport { ChatGeneration } from \"@langchain/core/outputs\";\nimport { ToolCall } from \"@langchain/core/messages/tool\";\nimport {\n interopSafeParseAsync,\n InteropZodType,\n} from \"@langchain/core/utils/types\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ninterface AnthropicToolsOutputParserParams<T extends Record<string, any>>\n extends JsonOutputKeyToolsParserParamsInterop<T> {}\n\nexport class AnthropicToolsOutputParser<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any
|
|
1
|
+
{"version":3,"file":"output_parsers.js","names":["params: AnthropicToolsOutputParserParams<T>","result: unknown","e: any","generations: ChatGeneration[]","tool","content: Record<string, any>[]","toolCalls: ToolCall[]"],"sources":["../src/output_parsers.ts"],"sourcesContent":["import {\n BaseLLMOutputParser,\n OutputParserException,\n} from \"@langchain/core/output_parsers\";\nimport { JsonOutputKeyToolsParserParamsInterop } from \"@langchain/core/output_parsers/openai_tools\";\nimport { ChatGeneration } from \"@langchain/core/outputs\";\nimport { ToolCall } from \"@langchain/core/messages/tool\";\nimport {\n interopSafeParseAsync,\n InteropZodType,\n} from \"@langchain/core/utils/types\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ninterface AnthropicToolsOutputParserParams<T extends Record<string, any>>\n extends JsonOutputKeyToolsParserParamsInterop<T> {}\n\nexport class AnthropicToolsOutputParser<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T extends Record<string, any> = Record<string, any>,\n> extends BaseLLMOutputParser<T> {\n static lc_name() {\n return \"AnthropicToolsOutputParser\";\n }\n\n lc_namespace = [\"langchain\", \"anthropic\", \"output_parsers\"];\n\n returnId = false;\n\n /** The type of tool calls to return. */\n keyName: string;\n\n /** Whether to return only the first tool call. */\n returnSingle = false;\n\n zodSchema?: InteropZodType<T>;\n\n constructor(params: AnthropicToolsOutputParserParams<T>) {\n super(params);\n this.keyName = params.keyName;\n this.returnSingle = params.returnSingle ?? this.returnSingle;\n this.zodSchema = params.zodSchema;\n }\n\n protected async _validateResult(result: unknown): Promise<T> {\n let parsedResult = result;\n if (typeof result === \"string\") {\n try {\n parsedResult = JSON.parse(result);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (e: any) {\n throw new OutputParserException(\n `Failed to parse. Text: \"${JSON.stringify(\n result,\n null,\n 2\n )}\". Error: ${JSON.stringify(e.message)}`,\n result\n );\n }\n } else {\n parsedResult = result;\n }\n if (this.zodSchema === undefined) {\n return parsedResult as T;\n }\n const zodParsedResult = await interopSafeParseAsync(\n this.zodSchema,\n parsedResult\n );\n if (zodParsedResult.success) {\n return zodParsedResult.data;\n } else {\n throw new OutputParserException(\n `Failed to parse. Text: \"${JSON.stringify(\n result,\n null,\n 2\n )}\". Error: ${JSON.stringify(zodParsedResult.error.issues)}`,\n JSON.stringify(parsedResult, null, 2)\n );\n }\n }\n\n async parseResult(generations: ChatGeneration[]): Promise<T> {\n const tools = generations.flatMap((generation) => {\n const { message } = generation;\n if (!Array.isArray(message.content)) {\n return [];\n }\n const tool = extractToolCalls(message.content)[0];\n return tool;\n });\n if (tools[0] === undefined) {\n throw new Error(\n \"No parseable tool calls provided to AnthropicToolsOutputParser.\"\n );\n }\n const [tool] = tools;\n const validatedResult = await this._validateResult(tool.args);\n return validatedResult;\n }\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function extractToolCalls(content: Record<string, any>[]) {\n const toolCalls: ToolCall[] = [];\n\n for (const block of content) {\n if (block.type === \"tool_use\") {\n toolCalls.push({\n name: block.name,\n args: block.input,\n id: block.id,\n type: \"tool_call\",\n });\n }\n }\n\n return toolCalls;\n}\n"],"mappings":";;;;AAgBA,IAAa,6BAAb,cAGU,oBAAuB;CAC/B,OAAO,UAAU;AACf,SAAO;CACR;CAED,eAAe;EAAC;EAAa;EAAa;CAAiB;CAE3D,WAAW;;CAGX;;CAGA,eAAe;CAEf;CAEA,YAAYA,QAA6C;EACvD,MAAM,OAAO;EACb,KAAK,UAAU,OAAO;EACtB,KAAK,eAAe,OAAO,gBAAgB,KAAK;EAChD,KAAK,YAAY,OAAO;CACzB;CAED,MAAgB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1
1
|
import { Computer20250124Action, Computer20251124Action } from "./types.js";
|
|
2
2
|
import { ToolMessage } from "@langchain/core/messages";
|
|
3
3
|
import { DynamicStructuredTool, ToolRuntime } from "@langchain/core/tools";
|
|
4
|
-
import * as
|
|
5
|
-
import * as
|
|
4
|
+
import * as zod24 from "zod";
|
|
5
|
+
import * as zod_v4_core5 from "zod/v4/core";
|
|
6
6
|
|
|
7
7
|
//#region src/tools/computer.d.ts
|
|
8
8
|
type ComputerUseReturnType = string | Promise<string> | ToolMessage<any> | Promise<ToolMessage<any>>;
|
|
@@ -94,62 +94,62 @@ interface Computer20251124Options<TState = any, TContext = any> {
|
|
|
94
94
|
* @param options - Configuration options for the computer use tool
|
|
95
95
|
* @returns The computer use tool object that can be passed to `bindTools`
|
|
96
96
|
*/
|
|
97
|
-
declare function computer_20251124(options: Computer20251124Options): DynamicStructuredTool<
|
|
98
|
-
action:
|
|
99
|
-
},
|
|
100
|
-
action:
|
|
101
|
-
coordinate:
|
|
102
|
-
},
|
|
103
|
-
action:
|
|
104
|
-
coordinate:
|
|
105
|
-
},
|
|
106
|
-
action:
|
|
107
|
-
coordinate:
|
|
108
|
-
},
|
|
109
|
-
action:
|
|
110
|
-
coordinate:
|
|
111
|
-
},
|
|
112
|
-
action:
|
|
113
|
-
coordinate:
|
|
114
|
-
},
|
|
115
|
-
action:
|
|
116
|
-
start_coordinate:
|
|
117
|
-
end_coordinate:
|
|
118
|
-
},
|
|
119
|
-
action:
|
|
120
|
-
coordinate:
|
|
121
|
-
},
|
|
122
|
-
action:
|
|
123
|
-
coordinate:
|
|
124
|
-
},
|
|
125
|
-
action:
|
|
126
|
-
coordinate:
|
|
127
|
-
scroll_direction:
|
|
97
|
+
declare function computer_20251124(options: Computer20251124Options): DynamicStructuredTool<zod24.ZodDiscriminatedUnion<[zod24.ZodObject<{
|
|
98
|
+
action: zod24.ZodLiteral<"screenshot">;
|
|
99
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
100
|
+
action: zod24.ZodLiteral<"left_click">;
|
|
101
|
+
coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
102
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
103
|
+
action: zod24.ZodLiteral<"right_click">;
|
|
104
|
+
coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
105
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
106
|
+
action: zod24.ZodLiteral<"middle_click">;
|
|
107
|
+
coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
108
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
109
|
+
action: zod24.ZodLiteral<"double_click">;
|
|
110
|
+
coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
111
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
112
|
+
action: zod24.ZodLiteral<"triple_click">;
|
|
113
|
+
coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
114
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
115
|
+
action: zod24.ZodLiteral<"left_click_drag">;
|
|
116
|
+
start_coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
117
|
+
end_coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
118
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
119
|
+
action: zod24.ZodLiteral<"left_mouse_down">;
|
|
120
|
+
coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
121
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
122
|
+
action: zod24.ZodLiteral<"left_mouse_up">;
|
|
123
|
+
coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
124
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
125
|
+
action: zod24.ZodLiteral<"scroll">;
|
|
126
|
+
coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
127
|
+
scroll_direction: zod24.ZodEnum<{
|
|
128
128
|
down: "down";
|
|
129
129
|
left: "left";
|
|
130
130
|
right: "right";
|
|
131
131
|
up: "up";
|
|
132
132
|
}>;
|
|
133
|
-
scroll_amount:
|
|
134
|
-
},
|
|
135
|
-
action:
|
|
136
|
-
text:
|
|
137
|
-
},
|
|
138
|
-
action:
|
|
139
|
-
key:
|
|
140
|
-
},
|
|
141
|
-
action:
|
|
142
|
-
coordinate:
|
|
143
|
-
},
|
|
144
|
-
action:
|
|
145
|
-
key:
|
|
146
|
-
},
|
|
147
|
-
action:
|
|
148
|
-
duration:
|
|
149
|
-
},
|
|
150
|
-
action:
|
|
151
|
-
region:
|
|
152
|
-
},
|
|
133
|
+
scroll_amount: zod24.ZodNumber;
|
|
134
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
135
|
+
action: zod24.ZodLiteral<"type">;
|
|
136
|
+
text: zod24.ZodString;
|
|
137
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
138
|
+
action: zod24.ZodLiteral<"key">;
|
|
139
|
+
key: zod24.ZodString;
|
|
140
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
141
|
+
action: zod24.ZodLiteral<"mouse_move">;
|
|
142
|
+
coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
143
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
144
|
+
action: zod24.ZodLiteral<"hold_key">;
|
|
145
|
+
key: zod24.ZodString;
|
|
146
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
147
|
+
action: zod24.ZodLiteral<"wait">;
|
|
148
|
+
duration: zod24.ZodOptional<zod24.ZodNumber>;
|
|
149
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
150
|
+
action: zod24.ZodLiteral<"zoom">;
|
|
151
|
+
region: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber, zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
152
|
+
}, zod_v4_core5.$strip>], "action">, Computer20251124Action, any, ToolMessage<any>>;
|
|
153
153
|
/**
|
|
154
154
|
* Options for the computer use tool.
|
|
155
155
|
*
|
|
@@ -231,59 +231,59 @@ interface Computer20250124Options<TState = any, TContext = any> {
|
|
|
231
231
|
* @param options - Configuration options for the computer use tool
|
|
232
232
|
* @returns The computer use tool object that can be passed to `bindTools`
|
|
233
233
|
*/
|
|
234
|
-
declare function computer_20250124(options: Computer20250124Options): DynamicStructuredTool<
|
|
235
|
-
action:
|
|
236
|
-
},
|
|
237
|
-
action:
|
|
238
|
-
coordinate:
|
|
239
|
-
},
|
|
240
|
-
action:
|
|
241
|
-
coordinate:
|
|
242
|
-
},
|
|
243
|
-
action:
|
|
244
|
-
coordinate:
|
|
245
|
-
},
|
|
246
|
-
action:
|
|
247
|
-
coordinate:
|
|
248
|
-
},
|
|
249
|
-
action:
|
|
250
|
-
coordinate:
|
|
251
|
-
},
|
|
252
|
-
action:
|
|
253
|
-
start_coordinate:
|
|
254
|
-
end_coordinate:
|
|
255
|
-
},
|
|
256
|
-
action:
|
|
257
|
-
coordinate:
|
|
258
|
-
},
|
|
259
|
-
action:
|
|
260
|
-
coordinate:
|
|
261
|
-
},
|
|
262
|
-
action:
|
|
263
|
-
coordinate:
|
|
264
|
-
scroll_direction:
|
|
234
|
+
declare function computer_20250124(options: Computer20250124Options): DynamicStructuredTool<zod24.ZodDiscriminatedUnion<[zod24.ZodObject<{
|
|
235
|
+
action: zod24.ZodLiteral<"screenshot">;
|
|
236
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
237
|
+
action: zod24.ZodLiteral<"left_click">;
|
|
238
|
+
coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
239
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
240
|
+
action: zod24.ZodLiteral<"right_click">;
|
|
241
|
+
coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
242
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
243
|
+
action: zod24.ZodLiteral<"middle_click">;
|
|
244
|
+
coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
245
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
246
|
+
action: zod24.ZodLiteral<"double_click">;
|
|
247
|
+
coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
248
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
249
|
+
action: zod24.ZodLiteral<"triple_click">;
|
|
250
|
+
coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
251
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
252
|
+
action: zod24.ZodLiteral<"left_click_drag">;
|
|
253
|
+
start_coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
254
|
+
end_coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
255
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
256
|
+
action: zod24.ZodLiteral<"left_mouse_down">;
|
|
257
|
+
coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
258
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
259
|
+
action: zod24.ZodLiteral<"left_mouse_up">;
|
|
260
|
+
coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
261
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
262
|
+
action: zod24.ZodLiteral<"scroll">;
|
|
263
|
+
coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
264
|
+
scroll_direction: zod24.ZodEnum<{
|
|
265
265
|
down: "down";
|
|
266
266
|
left: "left";
|
|
267
267
|
right: "right";
|
|
268
268
|
up: "up";
|
|
269
269
|
}>;
|
|
270
|
-
scroll_amount:
|
|
271
|
-
},
|
|
272
|
-
action:
|
|
273
|
-
text:
|
|
274
|
-
},
|
|
275
|
-
action:
|
|
276
|
-
key:
|
|
277
|
-
},
|
|
278
|
-
action:
|
|
279
|
-
coordinate:
|
|
280
|
-
},
|
|
281
|
-
action:
|
|
282
|
-
key:
|
|
283
|
-
},
|
|
284
|
-
action:
|
|
285
|
-
duration:
|
|
286
|
-
},
|
|
270
|
+
scroll_amount: zod24.ZodNumber;
|
|
271
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
272
|
+
action: zod24.ZodLiteral<"type">;
|
|
273
|
+
text: zod24.ZodString;
|
|
274
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
275
|
+
action: zod24.ZodLiteral<"key">;
|
|
276
|
+
key: zod24.ZodString;
|
|
277
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
278
|
+
action: zod24.ZodLiteral<"mouse_move">;
|
|
279
|
+
coordinate: zod24.ZodTuple<[zod24.ZodNumber, zod24.ZodNumber], null>;
|
|
280
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
281
|
+
action: zod24.ZodLiteral<"hold_key">;
|
|
282
|
+
key: zod24.ZodString;
|
|
283
|
+
}, zod_v4_core5.$strip>, zod24.ZodObject<{
|
|
284
|
+
action: zod24.ZodLiteral<"wait">;
|
|
285
|
+
duration: zod24.ZodOptional<zod24.ZodNumber>;
|
|
286
|
+
}, zod_v4_core5.$strip>], "action">, Computer20250124Action, any, ComputerUseReturnType>;
|
|
287
287
|
//#endregion
|
|
288
288
|
export { Computer20250124Options, Computer20251124Options, ComputerUseReturnType, computer_20250124, computer_20251124 };
|
|
289
289
|
//# sourceMappingURL=computer.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"computer.d.ts","names":["zod_v4_core9","ToolMessage","DynamicStructuredTool","ToolRuntime","Computer20251124Action","Computer20250124Action","ComputerUseReturnType","Promise","Computer20251124Options","TState","TContext","computer_20251124","zod46","ZodLiteral","$strip","ZodObject","ZodNumber","ZodTuple","ZodEnum","ZodString","ZodOptional","ZodDiscriminatedUnion","Computer20250124Options","computer_20250124"],"sources":["../../src/tools/computer.d.ts"],"sourcesContent":["import { ToolMessage } from \"@langchain/core/messages\";\nimport type { DynamicStructuredTool, ToolRuntime } from \"@langchain/core/tools\";\nimport type { Computer20251124Action, Computer20250124Action } from \"./types.js\";\nexport type ComputerUseReturnType = string | Promise<string> | ToolMessage<any> | Promise<ToolMessage<any>>;\n/**\n * Options for the computer use tool (Claude Opus 4.5 only version).\n *\n * @template TState - The type of the state schema (when used with `ReactAgent`)\n * @template TContext - The type of the context schema (when used with `ReactAgent`)\n */\nexport interface Computer20251124Options<TState = any, TContext = any> {\n /**\n * The width of the display in pixels.\n */\n displayWidthPx: number;\n /**\n * The height of the display in pixels.\n */\n displayHeightPx: number;\n /**\n * Optional display number for X11 environments.\n */\n displayNumber?: number;\n /**\n * Enable zoom action for detailed screen region inspection.\n * When enabled, Claude can zoom into specific screen regions.\n * @default false\n */\n enableZoom?: boolean;\n /**\n * Optional execute function that handles computer action execution.\n * This function receives the action input and should return the result\n * (typically a base64-encoded screenshot or action confirmation).\n */\n execute?: (args: Computer20251124Action, runtime: ToolRuntime<TState, TContext>) => ComputerUseReturnType;\n}\n/**\n * Creates an Anthropic computer use tool for Claude Opus 4.5 that provides\n * screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.\n *\n * The computer use tool enables Claude to interact with desktop environments through:\n * - **Screenshot capture**: See what's currently displayed on screen\n * - **Mouse control**: Click, drag, and move the cursor\n * - **Keyboard input**: Type text and use keyboard shortcuts\n * - **Zoom**: View specific screen regions at full resolution (when enabled)\n *\n * @warning Computer use is a beta feature with unique risks. Use a dedicated virtual machine\n * or container with minimal privileges. Avoid giving access to sensitive data.\n *\n * @see {@link https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool | Anthropic Computer Use Documentation}\n *\n * @example\n * ```typescript\n * import { ChatAnthropic, tools } from \"@langchain/anthropic\";\n *\n * const llm = new ChatAnthropic({\n * model: \"claude-opus-4-5-20251101\",\n * clientOptions: {\n * defaultHeaders: {\n * \"anthropic-beta\": \"computer-use-2025-11-24\",\n * },\n * },\n * });\n *\n * const computer = tools.computer_20251124({\n * displayWidthPx: 1024,\n * displayHeightPx: 768,\n * displayNumber: 1,\n * enableZoom: true,\n * execute: async (action) => {\n * if (action.action === \"screenshot\") {\n * // Capture and return base64-encoded screenshot\n * return captureScreenshot();\n * }\n * if (action.action === \"left_click\") {\n * // Click at the specified coordinates\n * await click(action.coordinate[0], action.coordinate[1]);\n * return captureScreenshot();\n * }\n * // Handle other actions...\n * },\n * });\n *\n * const llmWithComputer = llm.bindTools([computer]);\n * const response = await llmWithComputer.invoke(\n * \"Save a picture of a cat to my desktop.\"\n * );\n * ```\n *\n * @param options - Configuration options for the computer use tool\n * @returns The computer use tool object that can be passed to `bindTools`\n */\nexport declare function computer_20251124(options: Computer20251124Options): DynamicStructuredTool<import(\"zod\").ZodDiscriminatedUnion<[import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"screenshot\">;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"left_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"right_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"middle_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"double_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"triple_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"left_click_drag\">;\n start_coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n end_coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"left_mouse_down\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"left_mouse_up\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"scroll\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n scroll_direction: import(\"zod\").ZodEnum<{\n down: \"down\";\n left: \"left\";\n right: \"right\";\n up: \"up\";\n }>;\n scroll_amount: import(\"zod\").ZodNumber;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"type\">;\n text: import(\"zod\").ZodString;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"key\">;\n key: import(\"zod\").ZodString;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"mouse_move\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"hold_key\">;\n key: import(\"zod\").ZodString;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"wait\">;\n duration: import(\"zod\").ZodOptional<import(\"zod\").ZodNumber>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"zoom\">;\n region: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber, import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>], \"action\">, Computer20251124Action, any, ToolMessage<any>>;\n/**\n * Options for the computer use tool.\n *\n * Supported models: Claude Sonnet 4.5, Haiku 4.5, Opus 4.1, Sonnet 4, Opus 4, and Sonnet 3.7 versions.\n */\nexport interface Computer20250124Options<TState = any, TContext = any> {\n /**\n * The width of the display in pixels.\n */\n displayWidthPx: number;\n /**\n * The height of the display in pixels.\n */\n displayHeightPx: number;\n /**\n * Optional display number for X11 environments.\n */\n displayNumber?: number;\n /**\n * Optional execute function that handles computer action execution.\n * This function receives the action input and should return the result\n * (typically a base64-encoded screenshot or action confirmation).\n */\n execute?: (args: Computer20250124Action, runtime: ToolRuntime<TState, TContext>) => ComputerUseReturnType;\n}\n/**\n * Creates an Anthropic computer use tool that provides screenshot capabilities and mouse/keyboard control\n * for autonomous desktop interaction.\n *\n * Supported models: Claude Sonnet 4.5, Haiku 4.5, Opus 4.1, Sonnet 4, Opus 4, and Sonnet 3.7 versions.\n *\n * The computer use tool enables Claude to interact with desktop environments through:\n * - **Screenshot capture**: See what's currently displayed on screen\n * - **Mouse control**: Click, drag, and move the cursor\n * - **Keyboard input**: Type text and use keyboard shortcuts\n *\n * @warning Computer use is a beta feature with unique risks. Use a dedicated virtual machine\n * or container with minimal privileges. Avoid giving access to sensitive data.\n *\n * @see {@link https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool | Anthropic Computer Use Documentation}\n *\n * @example\n * ```typescript\n * import { ChatAnthropic, tools } from \"@langchain/anthropic\";\n *\n * const llm = new ChatAnthropic({\n * model: \"claude-sonnet-4-5-20250929\",\n * clientOptions: {\n * defaultHeaders: {\n * \"anthropic-beta\": \"computer-use-2025-01-24\",\n * },\n * },\n * });\n *\n * const computer = tools.computer_20250124({\n * displayWidthPx: 1024,\n * displayHeightPx: 768,\n * displayNumber: 1,\n * execute: async (action) => {\n * if (action.action === \"screenshot\") {\n * // Capture and return base64-encoded screenshot\n * return captureScreenshot();\n * }\n * if (action.action === \"left_click\") {\n * // Click at the specified coordinates\n * await click(action.coordinate[0], action.coordinate[1]);\n * return captureScreenshot();\n * }\n * // Handle other actions...\n * },\n * });\n *\n * const llmWithComputer = llm.bindTools([computer]);\n * const response = await llmWithComputer.invoke(\n * \"Save a picture of a cat to my desktop.\"\n * );\n * ```\n *\n * @param options - Configuration options for the computer use tool\n * @returns The computer use tool object that can be passed to `bindTools`\n */\nexport declare function computer_20250124(options: Computer20250124Options): DynamicStructuredTool<import(\"zod\").ZodDiscriminatedUnion<[import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"screenshot\">;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"left_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"right_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"middle_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"double_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"triple_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"left_click_drag\">;\n start_coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n end_coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"left_mouse_down\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"left_mouse_up\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"scroll\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n scroll_direction: import(\"zod\").ZodEnum<{\n down: \"down\";\n left: \"left\";\n right: \"right\";\n up: \"up\";\n }>;\n scroll_amount: import(\"zod\").ZodNumber;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"type\">;\n text: import(\"zod\").ZodString;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"key\">;\n key: import(\"zod\").ZodString;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"mouse_move\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"hold_key\">;\n key: import(\"zod\").ZodString;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"wait\">;\n duration: import(\"zod\").ZodOptional<import(\"zod\").ZodNumber>;\n}, import(\"zod/v4/core\").$strip>], \"action\">, Computer20250124Action, any, ComputerUseReturnType>;\n//# sourceMappingURL=computer.d.ts.map"],"mappings":";;;;;;;KAGYM,qBAAAA,YAAiCC,kBAAkBN,mBAAmBM,QAAQN;;;;AAA1F;;;AAA0FA,UAOzEO,uBAPyEP,CAAAA,SAAAA,GAAAA,EAAAA,WAAAA,GAAAA,CAAAA,CAAAA;EAARM;AAAO;AAOzF;EAwBqBH,cAAAA,EAAAA,MAAAA;EAA6CK;;;EAAsBH,eAAAA,EAAAA,MAAAA;EAAqB;AA0D7G;;EAA0EM,aAChDC,CAAAA,EAAAA,MAAAA;EAAUb;;;;;EAGoDY,UAA1DK,CAAAA,EAAAA,OAAAA;EAAQjB;;;;;EAGkDY,OAA1DK,CAAAA,EAAAA,CAAAA,IAAAA,EAjETb,sBAiESa,EAAAA,OAAAA,EAjEwBd,WAiExBc,CAjEoCR,MAiEpCQ,EAjE4CP,QA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AHiBG;UAVSH,KAAAA,CAW/BC;QAAUD,KAAAA,CACZO;GAASnB,YAAAA,CACRc,MAAAA,GAGMF,KAAAA,CAHiBG;UAHSH,KAAAA,CAI/BC;OAAUD,KAAAA,CACbO;GAASnB,YAAAA,CACPc,MAAAA,GAGMF,KAAAA,CAHiBG;UAHSH,KAAAA,CAI/BC;cAC8DD,KAAAA,CAA1DK,UADML,KAAAA,CACkBI,SAAAA,EAASJ,KAAAA,CAAgBI,SAAAA;GAAzChB,YAAAA,CACbc,MAAAA,GAGMF,KAAAA,CAHiBG;UAHSH,KAAAA,CAI/BC;OAAUD,KAAAA,CACbO;GAASnB,YAAAA,CACPc,MAAAA,GAGMF,KAAAA,CAHiBG;UAHSH,KAAAA,CAI/BC;YACqCD,KAAAA,CAAnCQ,YADQR,KAAAA,CACkBI,SAAAA;GAAfhB,YAAAA,CACdc,MAAAA,eAAqBT,6BAA6BC"}
|
|
1
|
+
{"version":3,"file":"computer.d.ts","names":["zod_v4_core5","ToolMessage","DynamicStructuredTool","ToolRuntime","Computer20251124Action","Computer20250124Action","ComputerUseReturnType","Promise","Computer20251124Options","TState","TContext","computer_20251124","zod24","ZodLiteral","$strip","ZodObject","ZodNumber","ZodTuple","ZodEnum","ZodString","ZodOptional","ZodDiscriminatedUnion","Computer20250124Options","computer_20250124"],"sources":["../../src/tools/computer.d.ts"],"sourcesContent":["import { ToolMessage } from \"@langchain/core/messages\";\nimport type { DynamicStructuredTool, ToolRuntime } from \"@langchain/core/tools\";\nimport type { Computer20251124Action, Computer20250124Action } from \"./types.js\";\nexport type ComputerUseReturnType = string | Promise<string> | ToolMessage<any> | Promise<ToolMessage<any>>;\n/**\n * Options for the computer use tool (Claude Opus 4.5 only version).\n *\n * @template TState - The type of the state schema (when used with `ReactAgent`)\n * @template TContext - The type of the context schema (when used with `ReactAgent`)\n */\nexport interface Computer20251124Options<TState = any, TContext = any> {\n /**\n * The width of the display in pixels.\n */\n displayWidthPx: number;\n /**\n * The height of the display in pixels.\n */\n displayHeightPx: number;\n /**\n * Optional display number for X11 environments.\n */\n displayNumber?: number;\n /**\n * Enable zoom action for detailed screen region inspection.\n * When enabled, Claude can zoom into specific screen regions.\n * @default false\n */\n enableZoom?: boolean;\n /**\n * Optional execute function that handles computer action execution.\n * This function receives the action input and should return the result\n * (typically a base64-encoded screenshot or action confirmation).\n */\n execute?: (args: Computer20251124Action, runtime: ToolRuntime<TState, TContext>) => ComputerUseReturnType;\n}\n/**\n * Creates an Anthropic computer use tool for Claude Opus 4.5 that provides\n * screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.\n *\n * The computer use tool enables Claude to interact with desktop environments through:\n * - **Screenshot capture**: See what's currently displayed on screen\n * - **Mouse control**: Click, drag, and move the cursor\n * - **Keyboard input**: Type text and use keyboard shortcuts\n * - **Zoom**: View specific screen regions at full resolution (when enabled)\n *\n * @warning Computer use is a beta feature with unique risks. Use a dedicated virtual machine\n * or container with minimal privileges. Avoid giving access to sensitive data.\n *\n * @see {@link https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool | Anthropic Computer Use Documentation}\n *\n * @example\n * ```typescript\n * import { ChatAnthropic, tools } from \"@langchain/anthropic\";\n *\n * const llm = new ChatAnthropic({\n * model: \"claude-opus-4-5-20251101\",\n * clientOptions: {\n * defaultHeaders: {\n * \"anthropic-beta\": \"computer-use-2025-11-24\",\n * },\n * },\n * });\n *\n * const computer = tools.computer_20251124({\n * displayWidthPx: 1024,\n * displayHeightPx: 768,\n * displayNumber: 1,\n * enableZoom: true,\n * execute: async (action) => {\n * if (action.action === \"screenshot\") {\n * // Capture and return base64-encoded screenshot\n * return captureScreenshot();\n * }\n * if (action.action === \"left_click\") {\n * // Click at the specified coordinates\n * await click(action.coordinate[0], action.coordinate[1]);\n * return captureScreenshot();\n * }\n * // Handle other actions...\n * },\n * });\n *\n * const llmWithComputer = llm.bindTools([computer]);\n * const response = await llmWithComputer.invoke(\n * \"Save a picture of a cat to my desktop.\"\n * );\n * ```\n *\n * @param options - Configuration options for the computer use tool\n * @returns The computer use tool object that can be passed to `bindTools`\n */\nexport declare function computer_20251124(options: Computer20251124Options): DynamicStructuredTool<import(\"zod\").ZodDiscriminatedUnion<[import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"screenshot\">;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"left_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"right_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"middle_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"double_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"triple_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"left_click_drag\">;\n start_coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n end_coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"left_mouse_down\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"left_mouse_up\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"scroll\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n scroll_direction: import(\"zod\").ZodEnum<{\n down: \"down\";\n left: \"left\";\n right: \"right\";\n up: \"up\";\n }>;\n scroll_amount: import(\"zod\").ZodNumber;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"type\">;\n text: import(\"zod\").ZodString;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"key\">;\n key: import(\"zod\").ZodString;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"mouse_move\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"hold_key\">;\n key: import(\"zod\").ZodString;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"wait\">;\n duration: import(\"zod\").ZodOptional<import(\"zod\").ZodNumber>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"zoom\">;\n region: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber, import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>], \"action\">, Computer20251124Action, any, ToolMessage<any>>;\n/**\n * Options for the computer use tool.\n *\n * Supported models: Claude Sonnet 4.5, Haiku 4.5, Opus 4.1, Sonnet 4, Opus 4, and Sonnet 3.7 versions.\n */\nexport interface Computer20250124Options<TState = any, TContext = any> {\n /**\n * The width of the display in pixels.\n */\n displayWidthPx: number;\n /**\n * The height of the display in pixels.\n */\n displayHeightPx: number;\n /**\n * Optional display number for X11 environments.\n */\n displayNumber?: number;\n /**\n * Optional execute function that handles computer action execution.\n * This function receives the action input and should return the result\n * (typically a base64-encoded screenshot or action confirmation).\n */\n execute?: (args: Computer20250124Action, runtime: ToolRuntime<TState, TContext>) => ComputerUseReturnType;\n}\n/**\n * Creates an Anthropic computer use tool that provides screenshot capabilities and mouse/keyboard control\n * for autonomous desktop interaction.\n *\n * Supported models: Claude Sonnet 4.5, Haiku 4.5, Opus 4.1, Sonnet 4, Opus 4, and Sonnet 3.7 versions.\n *\n * The computer use tool enables Claude to interact with desktop environments through:\n * - **Screenshot capture**: See what's currently displayed on screen\n * - **Mouse control**: Click, drag, and move the cursor\n * - **Keyboard input**: Type text and use keyboard shortcuts\n *\n * @warning Computer use is a beta feature with unique risks. Use a dedicated virtual machine\n * or container with minimal privileges. Avoid giving access to sensitive data.\n *\n * @see {@link https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool | Anthropic Computer Use Documentation}\n *\n * @example\n * ```typescript\n * import { ChatAnthropic, tools } from \"@langchain/anthropic\";\n *\n * const llm = new ChatAnthropic({\n * model: \"claude-sonnet-4-5-20250929\",\n * clientOptions: {\n * defaultHeaders: {\n * \"anthropic-beta\": \"computer-use-2025-01-24\",\n * },\n * },\n * });\n *\n * const computer = tools.computer_20250124({\n * displayWidthPx: 1024,\n * displayHeightPx: 768,\n * displayNumber: 1,\n * execute: async (action) => {\n * if (action.action === \"screenshot\") {\n * // Capture and return base64-encoded screenshot\n * return captureScreenshot();\n * }\n * if (action.action === \"left_click\") {\n * // Click at the specified coordinates\n * await click(action.coordinate[0], action.coordinate[1]);\n * return captureScreenshot();\n * }\n * // Handle other actions...\n * },\n * });\n *\n * const llmWithComputer = llm.bindTools([computer]);\n * const response = await llmWithComputer.invoke(\n * \"Save a picture of a cat to my desktop.\"\n * );\n * ```\n *\n * @param options - Configuration options for the computer use tool\n * @returns The computer use tool object that can be passed to `bindTools`\n */\nexport declare function computer_20250124(options: Computer20250124Options): DynamicStructuredTool<import(\"zod\").ZodDiscriminatedUnion<[import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"screenshot\">;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"left_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"right_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"middle_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"double_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"triple_click\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"left_click_drag\">;\n start_coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n end_coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"left_mouse_down\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"left_mouse_up\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"scroll\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n scroll_direction: import(\"zod\").ZodEnum<{\n down: \"down\";\n left: \"left\";\n right: \"right\";\n up: \"up\";\n }>;\n scroll_amount: import(\"zod\").ZodNumber;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"type\">;\n text: import(\"zod\").ZodString;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"key\">;\n key: import(\"zod\").ZodString;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"mouse_move\">;\n coordinate: import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"hold_key\">;\n key: import(\"zod\").ZodString;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n action: import(\"zod\").ZodLiteral<\"wait\">;\n duration: import(\"zod\").ZodOptional<import(\"zod\").ZodNumber>;\n}, import(\"zod/v4/core\").$strip>], \"action\">, Computer20250124Action, any, ComputerUseReturnType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GMF,KAAAA,CAHiBG;UAJSH,KAAAA,CAK/BC;cAC8DD,KAAAA,CAA1DK,UADML,KAAAA,CACkBI,SAAAA,EAASJ,KAAAA,CAAgBI,SAAAA;GAAzChB,YAAAA,CACbc,MAAAA,GAGMF,KAAAA,CAHiBG;UAHSH,KAAAA,CAI/BC;cAC8DD,KAAAA,CAA1DK,UADML,KAAAA,CACkBI,SAAAA,EAASJ,KAAAA,CAAgBI,SAAAA;GAAzChB,YAAAA,CACbc,MAAAA,GAUMF,KAAAA,CAViBG;UAHSH,KAAAA,CAI/BC;cAC8DD,KAAAA,CAA1DK,UADML,KAAAA,CACkBI,SAAAA,EAASJ,KAAAA,CAAgBI,SAAAA;oBAAzCJ,KAAAA,CACFM;;;;;;iBAAON,KAAAA,CAMVI;GAAShB,YAAAA,CACjBc,MAAAA,GAGMF,KAAAA,CAHiBG;UAVSH,KAAAA,CAW/BC;QAAUD,KAAAA,CACZO;GAASnB,YAAAA,CACRc,MAAAA,GAGMF,KAAAA,CAHiBG;UAHSH,KAAAA,CAI/BC;OAAUD,KAAAA,CACbO;GAASnB,YAAAA,CACPc,MAAAA,GAGMF,KAAAA,CAHiBG;UAHSH,KAAAA,CAI/BC;cAC8DD,KAAAA,CAA1DK,UADML,KAAAA,CACkBI,SAAAA,EAASJ,KAAAA,CAAgBI,SAAAA;GAAzChB,YAAAA,CACbc,MAAAA,GAGMF,KAAAA,CAHiBG;UAHSH,KAAAA,CAI/BC;OAAUD,KAAAA,CACbO;GAASnB,YAAAA,CACPc,MAAAA,GAGMF,KAAAA,CAHiBG;UAHSH,KAAAA,CAI/BC;YACqCD,KAAAA,CAAnCQ,YADQR,KAAAA,CACkBI,SAAAA;GAAfhB,YAAAA,CACdc,MAAAA,eAAqBT,6BAA6BC"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { TextEditor20250728Command } from "./types.js";
|
|
2
2
|
import { DynamicStructuredTool } from "@langchain/core/tools";
|
|
3
|
-
import * as
|
|
4
|
-
import * as
|
|
3
|
+
import * as zod173 from "zod";
|
|
4
|
+
import * as zod_v4_core36 from "zod/v4/core";
|
|
5
5
|
|
|
6
6
|
//#region src/tools/textEditor.d.ts
|
|
7
7
|
/**
|
|
@@ -72,25 +72,25 @@ interface TextEditor20250728Options {
|
|
|
72
72
|
*
|
|
73
73
|
* @see https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/text-editor-tool
|
|
74
74
|
*/
|
|
75
|
-
declare function textEditor_20250728(options?: TextEditor20250728Options): DynamicStructuredTool<
|
|
76
|
-
command:
|
|
77
|
-
path:
|
|
78
|
-
view_range:
|
|
79
|
-
},
|
|
80
|
-
command:
|
|
81
|
-
path:
|
|
82
|
-
old_str:
|
|
83
|
-
new_str:
|
|
84
|
-
},
|
|
85
|
-
command:
|
|
86
|
-
path:
|
|
87
|
-
file_text:
|
|
88
|
-
},
|
|
89
|
-
command:
|
|
90
|
-
path:
|
|
91
|
-
insert_line:
|
|
92
|
-
new_str:
|
|
93
|
-
},
|
|
75
|
+
declare function textEditor_20250728(options?: TextEditor20250728Options): DynamicStructuredTool<zod173.ZodDiscriminatedUnion<[zod173.ZodObject<{
|
|
76
|
+
command: zod173.ZodLiteral<"view">;
|
|
77
|
+
path: zod173.ZodString;
|
|
78
|
+
view_range: zod173.ZodOptional<zod173.ZodTuple<[zod173.ZodNumber, zod173.ZodNumber], null>>;
|
|
79
|
+
}, zod_v4_core36.$strip>, zod173.ZodObject<{
|
|
80
|
+
command: zod173.ZodLiteral<"str_replace">;
|
|
81
|
+
path: zod173.ZodString;
|
|
82
|
+
old_str: zod173.ZodString;
|
|
83
|
+
new_str: zod173.ZodString;
|
|
84
|
+
}, zod_v4_core36.$strip>, zod173.ZodObject<{
|
|
85
|
+
command: zod173.ZodLiteral<"create">;
|
|
86
|
+
path: zod173.ZodString;
|
|
87
|
+
file_text: zod173.ZodString;
|
|
88
|
+
}, zod_v4_core36.$strip>, zod173.ZodObject<{
|
|
89
|
+
command: zod173.ZodLiteral<"insert">;
|
|
90
|
+
path: zod173.ZodString;
|
|
91
|
+
insert_line: zod173.ZodNumber;
|
|
92
|
+
new_str: zod173.ZodString;
|
|
93
|
+
}, zod_v4_core36.$strip>], "command">, {
|
|
94
94
|
command: "view";
|
|
95
95
|
path: string;
|
|
96
96
|
view_range?: [number, number] | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"textEditor.d.ts","names":["
|
|
1
|
+
{"version":3,"file":"textEditor.d.ts","names":["zod_v4_core36","DynamicStructuredTool","TextEditor20250728Command","TextEditor20250728Options","Promise","textEditor_20250728","zod173","ZodLiteral","ZodString","ZodNumber","ZodTuple","ZodOptional","$strip","ZodObject","ZodDiscriminatedUnion"],"sources":["../../src/tools/textEditor.d.ts"],"sourcesContent":["import type { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport { type TextEditor20250728Command } from \"./types.js\";\n/**\n * Options for the text editor tool (Claude 4.x version).\n */\nexport interface TextEditor20250728Options {\n /**\n * Optional execute function that handles text editor command execution.\n * This function receives the command input and should return the result.\n */\n execute?: (args: TextEditor20250728Command) => string | Promise<string>;\n /**\n * Optional maximum characters to return when viewing files.\n * If the file content exceeds this limit, it will be truncated.\n */\n maxCharacters?: number;\n}\n/**\n * Creates an Anthropic text editor tool for Claude 4.x models that can view and modify text files.\n *\n * The text editor tool enables Claude to view and modify text files, helping debug, fix,\n * and improve code or other text documents. Claude can directly interact with files,\n * providing hands-on assistance rather than just suggesting changes.\n *\n * Available commands:\n * - `view`: Examine file contents or list directory contents\n * - `str_replace`: Replace specific text in a file\n * - `create`: Create a new file with specified content\n * - `insert`: Insert text at a specific line number\n *\n * @example\n * ```typescript\n * import { ChatAnthropic, tools } from \"@langchain/anthropic\";\n * import * as fs from \"fs\";\n *\n * const llm = new ChatAnthropic({\n * model: \"claude-sonnet-4-5-20250929\",\n * });\n *\n * const textEditor = tools.textEditor_20250728({\n * execute: async (args) => {\n * if (args.command === \"view\") {\n * const content = fs.readFileSync(args.path, \"utf-8\");\n * return content.split(\"\\n\").map((line, i) => `${i + 1}: ${line}`).join(\"\\n\");\n * }\n * if (args.command === \"str_replace\") {\n * let content = fs.readFileSync(args.path, \"utf-8\");\n * content = content.replace(args.old_str!, args.new_str!);\n * fs.writeFileSync(args.path, content);\n * return \"Successfully replaced text.\";\n * }\n * // Handle other commands...\n * return \"Command executed\";\n * },\n * maxCharacters: 10000,\n * });\n *\n * const llmWithEditor = llm.bindTools([textEditor]);\n * const response = await llmWithEditor.invoke(\n * \"There's a syntax error in my primes.py file. Can you help me fix it?\"\n * );\n * ```\n *\n * @param options - Configuration options for the text editor tool\n * @param options.execute - Function that handles text editor command execution\n * @param options.maxCharacters - Maximum characters to return when viewing files\n * @returns The text editor tool object that can be passed to `bindTools`\n *\n * @see https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/text-editor-tool\n */\nexport declare function textEditor_20250728(options?: TextEditor20250728Options): DynamicStructuredTool<import(\"zod\").ZodDiscriminatedUnion<[import(\"zod\").ZodObject<{\n command: import(\"zod\").ZodLiteral<\"view\">;\n path: import(\"zod\").ZodString;\n view_range: import(\"zod\").ZodOptional<import(\"zod\").ZodTuple<[import(\"zod\").ZodNumber, import(\"zod\").ZodNumber], null>>;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n command: import(\"zod\").ZodLiteral<\"str_replace\">;\n path: import(\"zod\").ZodString;\n old_str: import(\"zod\").ZodString;\n new_str: import(\"zod\").ZodString;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n command: import(\"zod\").ZodLiteral<\"create\">;\n path: import(\"zod\").ZodString;\n file_text: import(\"zod\").ZodString;\n}, import(\"zod/v4/core\").$strip>, import(\"zod\").ZodObject<{\n command: import(\"zod\").ZodLiteral<\"insert\">;\n path: import(\"zod\").ZodString;\n insert_line: import(\"zod\").ZodNumber;\n new_str: import(\"zod\").ZodString;\n}, import(\"zod/v4/core\").$strip>], \"command\">, {\n command: \"view\";\n path: string;\n view_range?: [number, number] | undefined;\n} | {\n command: \"str_replace\";\n path: string;\n old_str: string;\n new_str: string;\n} | {\n command: \"create\";\n path: string;\n file_text: string;\n} | {\n command: \"insert\";\n path: string;\n insert_line: number;\n new_str: string;\n}, unknown, string | Promise<string>>;\n//# sourceMappingURL=textEditor.d.ts.map"],"mappings":";;;;;;;;;UAKiBG,yBAAAA;EAAAA;AAiEjB;;;EACqCG,OACbE,CAAAA,EAAAA,CAAAA,IAAAA,EA9DHN,yBA8DGM,EAAAA,GAAAA,MAAAA,GA9DoCJ,OA8DpCI,CAAAA,MAAAA,CAAAA;EAASF;;;;EACQN,aAChBY,CAAAA,EAAAA,MAAAA;;;;;;;;;;;;;;;;;;;;;;AAJ8E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAA/EP,mBAAAA,WAA8BF,4BAA4BF,sBAazBK,MAAAA,CAb6DQ,uBAIvFR,MAAAA,CAJ4HO;WAA5EP,MAAAA,CACpDC;QAAUD,MAAAA,CACbE;cACwCF,MAAAA,CAAlCK,YAAoFL,MAAAA,CAA1DI,UADvBJ,MAAAA,CAC+CG,SAAAA,EAASH,MAAAA,CAAgBG,SAAAA;GAAhET,aAAAA,CAChBY,MAAAA,GAKMN,MAAAA,CALiBO;WAJoHP,MAAAA,CAKzIC;QAAUD,MAAAA,CACbE;WAASF,MAAAA,CACNE;WAASF,MAAAA,CACTE;GAASR,aAAAA,CACXY,MAAAA,GAIMN,MAAAA,CAJiBO;WALSP,MAAAA,CAM9BC;QAAUD,MAAAA,CACbE;aAASF,MAAAA,CACJE;GAASR,aAAAA,CACbY,MAAAA,GAKMN,MAAAA,CALiBO;WAJSP,MAAAA,CAK9BC;QAAUD,MAAAA,CACbE;eAASF,MAAAA,CACFG;WAASH,MAAAA,CACbE;GAASR,aAAAA,CACXY,MAAAA;;;;;;;;;;;;;;;;;;qBAkBJR"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@langchain/anthropic",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.6-dev-1767748783694",
|
|
4
4
|
"description": "Anthropic integrations for LangChain.js",
|
|
5
5
|
"author": "LangChain",
|
|
6
6
|
"license": "MIT",
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"zod": "^3.25.76 || ^4"
|
|
19
19
|
},
|
|
20
20
|
"peerDependencies": {
|
|
21
|
-
"@langchain/core": "1.1.
|
|
21
|
+
"@langchain/core": "1.1.11-dev-1767748783694"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
24
|
"@anthropic-ai/vertex-sdk": "^0.11.5",
|
|
@@ -28,14 +28,14 @@
|
|
|
28
28
|
"dotenv": "^17.2.1",
|
|
29
29
|
"dpdm": "^3.14.0",
|
|
30
30
|
"eslint": "^9.34.0",
|
|
31
|
-
"prettier": "^
|
|
31
|
+
"prettier": "^3.5.0",
|
|
32
32
|
"rimraf": "^5.0.1",
|
|
33
33
|
"typescript": "~5.8.3",
|
|
34
34
|
"uuid": "^13.0.0",
|
|
35
35
|
"vitest": "^3.2.4",
|
|
36
|
-
"@langchain/core": "1.1.
|
|
36
|
+
"@langchain/core": "1.1.11-dev-1767748783694",
|
|
37
37
|
"@langchain/eslint": "0.1.1",
|
|
38
|
-
"@langchain/standard-tests": "0.0.
|
|
38
|
+
"@langchain/standard-tests": "0.0.14-dev-1767748783694",
|
|
39
39
|
"@langchain/tsconfig": "0.0.1"
|
|
40
40
|
},
|
|
41
41
|
"publishConfig": {
|