@langchain/anthropic 1.3.12 → 1.3.14
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 +31 -0
- package/dist/chat_models.cjs +6 -2
- package/dist/chat_models.cjs.map +1 -1
- package/dist/chat_models.js +6 -2
- package/dist/chat_models.js.map +1 -1
- package/dist/utils/message_inputs.cjs +23 -0
- package/dist/utils/message_inputs.cjs.map +1 -1
- package/dist/utils/message_inputs.js +23 -0
- package/dist/utils/message_inputs.js.map +1 -1
- package/package.json +4 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,36 @@
|
|
|
1
1
|
# @langchain/anthropic
|
|
2
2
|
|
|
3
|
+
## 1.3.14
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies [[`41bfea5`](https://github.com/langchain-ai/langchainjs/commit/41bfea51cf119573a3b956ee782d2731fe71c681)]:
|
|
8
|
+
- @langchain/core@1.1.19
|
|
9
|
+
|
|
10
|
+
## 1.3.13
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- [#9881](https://github.com/langchain-ai/langchainjs/pull/9881) [`0c64698`](https://github.com/langchain-ai/langchainjs/commit/0c646989761d11eaa66a3290392ddb94ad54d5bd) Thanks [@marvikomo](https://github.com/marvikomo)! - handle standard file content blocks
|
|
15
|
+
|
|
16
|
+
- [#9900](https://github.com/langchain-ai/langchainjs/pull/9900) [`a9b5059`](https://github.com/langchain-ai/langchainjs/commit/a9b50597186002221aaa4585246e569fa44c27c8) Thanks [@hntrl](https://github.com/hntrl)! - Improved abort signal handling for chat models:
|
|
17
|
+
- Added `ModelAbortError` class in `@langchain/core/errors` that contains partial output when a model invocation is aborted mid-stream
|
|
18
|
+
- `invoke()` now throws `ModelAbortError` with accumulated `partialOutput` when aborted during streaming (when using streaming callback handlers)
|
|
19
|
+
- `stream()` throws a regular `AbortError` when aborted (since chunks are already yielded to the caller)
|
|
20
|
+
- All provider implementations now properly check and propagate abort signals in both `_generate()` and `_streamResponseChunks()` methods
|
|
21
|
+
- Added standard tests for abort signal behavior
|
|
22
|
+
|
|
23
|
+
- [#9900](https://github.com/langchain-ai/langchainjs/pull/9900) [`a9b5059`](https://github.com/langchain-ai/langchainjs/commit/a9b50597186002221aaa4585246e569fa44c27c8) Thanks [@hntrl](https://github.com/hntrl)! - fix(providers): add proper abort signal handling for invoke and stream operations
|
|
24
|
+
- Added early abort check (`signal.throwIfAborted()`) at the start of `_generate` methods to immediately throw when signal is already aborted
|
|
25
|
+
- Added abort signal checks inside streaming loops in `_streamResponseChunks` to return early when signal is aborted
|
|
26
|
+
- Propagated abort signals to underlying SDK calls where applicable (Google GenAI, Google Common/VertexAI, Cohere)
|
|
27
|
+
- Added standard tests for abort signal behavior in `@langchain/standard-tests`
|
|
28
|
+
|
|
29
|
+
This enables proper cancellation behavior for both invoke and streaming operations, and allows fallback chains to correctly proceed to the next runnable when the previous one is aborted.
|
|
30
|
+
|
|
31
|
+
- Updated dependencies [[`a9b5059`](https://github.com/langchain-ai/langchainjs/commit/a9b50597186002221aaa4585246e569fa44c27c8), [`a9b5059`](https://github.com/langchain-ai/langchainjs/commit/a9b50597186002221aaa4585246e569fa44c27c8)]:
|
|
32
|
+
- @langchain/core@1.1.18
|
|
33
|
+
|
|
3
34
|
## 1.3.12
|
|
4
35
|
|
|
5
36
|
### Patch Changes
|
package/dist/chat_models.cjs
CHANGED
|
@@ -764,11 +764,14 @@ var ChatAnthropicMessages = class extends __langchain_core_language_models_chat_
|
|
|
764
764
|
stream: true
|
|
765
765
|
};
|
|
766
766
|
const coerceContentToString = !_toolsInParams(payload) && !_documentsInParams(payload) && !_thinkingInParams(payload);
|
|
767
|
-
const stream = await this.createStreamWithRetry(payload, {
|
|
767
|
+
const stream = await this.createStreamWithRetry(payload, {
|
|
768
|
+
headers: options.headers,
|
|
769
|
+
signal: options.signal
|
|
770
|
+
});
|
|
768
771
|
for await (const data of stream) {
|
|
769
772
|
if (options.signal?.aborted) {
|
|
770
773
|
stream.controller.abort();
|
|
771
|
-
|
|
774
|
+
return;
|
|
772
775
|
}
|
|
773
776
|
const shouldStreamUsage = this.streamUsage ?? options.streamUsage;
|
|
774
777
|
const result = require_message_outputs._makeMessageChunkFromAnthropicEvent(data, {
|
|
@@ -812,6 +815,7 @@ var ChatAnthropicMessages = class extends __langchain_core_language_models_chat_
|
|
|
812
815
|
}
|
|
813
816
|
/** @ignore */
|
|
814
817
|
async _generate(messages, options, runManager) {
|
|
818
|
+
options.signal?.throwIfAborted();
|
|
815
819
|
if (this.stopSequences && options.stop) throw new Error(`"stopSequence" parameter found in input and default params`);
|
|
816
820
|
const params = this.invocationParams(options);
|
|
817
821
|
if (params.stream) {
|
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","applyCacheControlToPayload","_makeMessageChunkFromAnthropicEvent","ChatGenerationChunk","AIMessageChunk","params: Omit<\n | Anthropic.Messages.MessageCreateParamsNonStreaming\n | Anthropic.Messages.MessageCreateParamsStreaming,\n \"messages\"\n > &\n Kwargs","requestOptions: AnthropicRequestOptions","cacheControl?: { type: \"ephemeral\"; ttl?: \"5m\" | \"1h\" }","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 {\n _convertMessagesToAnthropicPayload,\n applyCacheControlToPayload,\n} 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\n/**\n * Cache control configuration for Anthropic prompt caching.\n * @see https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching\n */\nexport interface AnthropicCacheControl {\n type: \"ephemeral\";\n ttl?: \"5m\" | \"1h\";\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 * Cache control configuration for prompt caching.\n * When provided, applies cache_control to the last content block of the\n * last message, enabling Anthropic's prompt caching feature.\n *\n * This is the recommended way to enable prompt caching as it applies\n * cache_control at the final message formatting layer, avoiding issues\n * with message content block manipulation during earlier processing stages.\n *\n * @see https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching\n */\n cache_control?: AnthropicCacheControl;\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 let formattedMessages = _convertMessagesToAnthropicPayload(messages);\n\n // Apply cache_control to the last message's last content block if specified\n // This is the recommended approach for prompt caching - applying at the final\n // formatting layer rather than modifying message content blocks earlier\n if (options.cache_control) {\n formattedMessages = applyCacheControlToPayload(\n formattedMessages,\n options.cache_control\n );\n }\n\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 cacheControl?: { type: \"ephemeral\"; ttl?: \"5m\" | \"1h\" }\n ) {\n let formattedMessages = _convertMessagesToAnthropicPayload(messages);\n\n // Apply cache_control to the last message's last content block if specified\n // This is the recommended approach for prompt caching - applying at the final\n // formatting layer rather than modifying message content blocks earlier\n if (cacheControl) {\n formattedMessages = applyCacheControlToPayload(\n formattedMessages,\n cacheControl\n );\n }\n\n const response = await this.completionWithRetry(\n {\n ...params,\n stream: false,\n ...formattedMessages,\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(\n messages,\n params,\n {\n signal: options.signal,\n headers: options.headers,\n },\n options.cache_control\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":";;;;;;;;;;;;;;;;;;;;;AAqEA,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;AA0DD,SAAS,eACPC,QACS;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|
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","applyCacheControlToPayload","_makeMessageChunkFromAnthropicEvent","ChatGenerationChunk","AIMessageChunk","params: Omit<\n | Anthropic.Messages.MessageCreateParamsNonStreaming\n | Anthropic.Messages.MessageCreateParamsStreaming,\n \"messages\"\n > &\n Kwargs","requestOptions: AnthropicRequestOptions","cacheControl?: { type: \"ephemeral\"; ttl?: \"5m\" | \"1h\" }","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 {\n _convertMessagesToAnthropicPayload,\n applyCacheControlToPayload,\n} 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\n/**\n * Cache control configuration for Anthropic prompt caching.\n * @see https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching\n */\nexport interface AnthropicCacheControl {\n type: \"ephemeral\";\n ttl?: \"5m\" | \"1h\";\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 * Cache control configuration for prompt caching.\n * When provided, applies cache_control to the last content block of the\n * last message, enabling Anthropic's prompt caching feature.\n *\n * This is the recommended way to enable prompt caching as it applies\n * cache_control at the final message formatting layer, avoiding issues\n * with message content block manipulation during earlier processing stages.\n *\n * @see https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching\n */\n cache_control?: AnthropicCacheControl;\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 let formattedMessages = _convertMessagesToAnthropicPayload(messages);\n\n // Apply cache_control to the last message's last content block if specified\n // This is the recommended approach for prompt caching - applying at the final\n // formatting layer rather than modifying message content blocks earlier\n if (options.cache_control) {\n formattedMessages = applyCacheControlToPayload(\n formattedMessages,\n options.cache_control\n );\n }\n\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 signal: options.signal,\n });\n\n for await (const data of stream) {\n if (options.signal?.aborted) {\n stream.controller.abort();\n return;\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 cacheControl?: { type: \"ephemeral\"; ttl?: \"5m\" | \"1h\" }\n ) {\n let formattedMessages = _convertMessagesToAnthropicPayload(messages);\n\n // Apply cache_control to the last message's last content block if specified\n // This is the recommended approach for prompt caching - applying at the final\n // formatting layer rather than modifying message content blocks earlier\n if (cacheControl) {\n formattedMessages = applyCacheControlToPayload(\n formattedMessages,\n cacheControl\n );\n }\n\n const response = await this.completionWithRetry(\n {\n ...params,\n stream: false,\n ...formattedMessages,\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 options.signal?.throwIfAborted();\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(\n messages,\n params,\n {\n signal: options.signal,\n headers: options.headers,\n },\n options.cache_control\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":";;;;;;;;;;;;;;;;;;;;;AAqEA,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;AA0DD,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;E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AmB;GACnC,OACC,MAAM,KAAK,WAAW;IACpB,eAAe;IACf;IACA,aAAa;KACX,MAAM;KACN,MAAM;IACP;IACD,6BAA6B;KAC3B,QAAQ,EAAE,QAAQ,kBAAmB;KACrC,6DAAqB,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,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"}
|
package/dist/chat_models.js
CHANGED
|
@@ -763,11 +763,14 @@ var ChatAnthropicMessages = class extends BaseChatModel {
|
|
|
763
763
|
stream: true
|
|
764
764
|
};
|
|
765
765
|
const coerceContentToString = !_toolsInParams(payload) && !_documentsInParams(payload) && !_thinkingInParams(payload);
|
|
766
|
-
const stream = await this.createStreamWithRetry(payload, {
|
|
766
|
+
const stream = await this.createStreamWithRetry(payload, {
|
|
767
|
+
headers: options.headers,
|
|
768
|
+
signal: options.signal
|
|
769
|
+
});
|
|
767
770
|
for await (const data of stream) {
|
|
768
771
|
if (options.signal?.aborted) {
|
|
769
772
|
stream.controller.abort();
|
|
770
|
-
|
|
773
|
+
return;
|
|
771
774
|
}
|
|
772
775
|
const shouldStreamUsage = this.streamUsage ?? options.streamUsage;
|
|
773
776
|
const result = _makeMessageChunkFromAnthropicEvent(data, {
|
|
@@ -811,6 +814,7 @@ var ChatAnthropicMessages = class extends BaseChatModel {
|
|
|
811
814
|
}
|
|
812
815
|
/** @ignore */
|
|
813
816
|
async _generate(messages, options, runManager) {
|
|
817
|
+
options.signal?.throwIfAborted();
|
|
814
818
|
if (this.stopSequences && options.stop) throw new Error(`"stopSequence" parameter found in input and default params`);
|
|
815
819
|
const params = this.invocationParams(options);
|
|
816
820
|
if (params.stream) {
|
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","cacheControl?: { type: \"ephemeral\"; ttl?: \"5m\" | \"1h\" }","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 {\n _convertMessagesToAnthropicPayload,\n applyCacheControlToPayload,\n} 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\n/**\n * Cache control configuration for Anthropic prompt caching.\n * @see https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching\n */\nexport interface AnthropicCacheControl {\n type: \"ephemeral\";\n ttl?: \"5m\" | \"1h\";\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 * Cache control configuration for prompt caching.\n * When provided, applies cache_control to the last content block of the\n * last message, enabling Anthropic's prompt caching feature.\n *\n * This is the recommended way to enable prompt caching as it applies\n * cache_control at the final message formatting layer, avoiding issues\n * with message content block manipulation during earlier processing stages.\n *\n * @see https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching\n */\n cache_control?: AnthropicCacheControl;\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 let formattedMessages = _convertMessagesToAnthropicPayload(messages);\n\n // Apply cache_control to the last message's last content block if specified\n // This is the recommended approach for prompt caching - applying at the final\n // formatting layer rather than modifying message content blocks earlier\n if (options.cache_control) {\n formattedMessages = applyCacheControlToPayload(\n formattedMessages,\n options.cache_control\n );\n }\n\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 cacheControl?: { type: \"ephemeral\"; ttl?: \"5m\" | \"1h\" }\n ) {\n let formattedMessages = _convertMessagesToAnthropicPayload(messages);\n\n // Apply cache_control to the last message's last content block if specified\n // This is the recommended approach for prompt caching - applying at the final\n // formatting layer rather than modifying message content blocks earlier\n if (cacheControl) {\n formattedMessages = applyCacheControlToPayload(\n formattedMessages,\n cacheControl\n );\n }\n\n const response = await this.completionWithRetry(\n {\n ...params,\n stream: false,\n ...formattedMessages,\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(\n messages,\n params,\n {\n signal: options.signal,\n headers: options.headers,\n },\n options.cache_control\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":";;;;;;;;;;;;;;;;;;;;AAqEA,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;AA0DD,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,gBAAg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,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","cacheControl?: { type: \"ephemeral\"; ttl?: \"5m\" | \"1h\" }","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 {\n _convertMessagesToAnthropicPayload,\n applyCacheControlToPayload,\n} 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\n/**\n * Cache control configuration for Anthropic prompt caching.\n * @see https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching\n */\nexport interface AnthropicCacheControl {\n type: \"ephemeral\";\n ttl?: \"5m\" | \"1h\";\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 * Cache control configuration for prompt caching.\n * When provided, applies cache_control to the last content block of the\n * last message, enabling Anthropic's prompt caching feature.\n *\n * This is the recommended way to enable prompt caching as it applies\n * cache_control at the final message formatting layer, avoiding issues\n * with message content block manipulation during earlier processing stages.\n *\n * @see https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching\n */\n cache_control?: AnthropicCacheControl;\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 let formattedMessages = _convertMessagesToAnthropicPayload(messages);\n\n // Apply cache_control to the last message's last content block if specified\n // This is the recommended approach for prompt caching - applying at the final\n // formatting layer rather than modifying message content blocks earlier\n if (options.cache_control) {\n formattedMessages = applyCacheControlToPayload(\n formattedMessages,\n options.cache_control\n );\n }\n\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 signal: options.signal,\n });\n\n for await (const data of stream) {\n if (options.signal?.aborted) {\n stream.controller.abort();\n return;\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 cacheControl?: { type: \"ephemeral\"; ttl?: \"5m\" | \"1h\" }\n ) {\n let formattedMessages = _convertMessagesToAnthropicPayload(messages);\n\n // Apply cache_control to the last message's last content block if specified\n // This is the recommended approach for prompt caching - applying at the final\n // formatting layer rather than modifying message content blocks earlier\n if (cacheControl) {\n formattedMessages = applyCacheControlToPayload(\n formattedMessages,\n cacheControl\n );\n }\n\n const response = await this.completionWithRetry(\n {\n ...params,\n stream: false,\n ...formattedMessages,\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 options.signal?.throwIfAborted();\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(\n messages,\n params,\n {\n signal: options.signal,\n headers: options.headers,\n },\n options.cache_control\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":";;;;;;;;;;;;;;;;;;;;AAqEA,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,WAA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,SAAO,iBAAiB,KAGtB,CACA,EACE,KAAK,IACN,GACD,kBACD,EAAC,CAAC,WAAW,EACZ,SAAS,2BACV,EAAC;CACH;AACF;AAED,IAAa,gBAAb,cAAmC,sBAAsB,CAAE"}
|
|
@@ -107,6 +107,29 @@ function* _formatContentBlocks(content, toolCalls) {
|
|
|
107
107
|
source,
|
|
108
108
|
...cacheControl ? { cache_control: cacheControl } : {}
|
|
109
109
|
};
|
|
110
|
+
} else if (contentPart.type === "file") {
|
|
111
|
+
let source;
|
|
112
|
+
if ("url" in contentPart && typeof contentPart.url === "string") source = {
|
|
113
|
+
type: "url",
|
|
114
|
+
url: contentPart.url
|
|
115
|
+
};
|
|
116
|
+
else if ("data" in contentPart && (typeof contentPart.data === "string" || contentPart.data instanceof Uint8Array)) {
|
|
117
|
+
const media_type = "mimeType" in contentPart && typeof contentPart.mimeType === "string" ? contentPart.mimeType : "application/pdf";
|
|
118
|
+
const data = typeof contentPart.data === "string" ? contentPart.data : Buffer.from(contentPart.data).toString("base64");
|
|
119
|
+
source = {
|
|
120
|
+
type: "base64",
|
|
121
|
+
media_type,
|
|
122
|
+
data
|
|
123
|
+
};
|
|
124
|
+
} else if ("fileId" in contentPart && typeof contentPart.fileId === "string") source = {
|
|
125
|
+
type: "file",
|
|
126
|
+
file_id: contentPart.fileId
|
|
127
|
+
};
|
|
128
|
+
if (source) yield {
|
|
129
|
+
type: "document",
|
|
130
|
+
source,
|
|
131
|
+
...cacheControl ? { cache_control: cacheControl } : {}
|
|
132
|
+
};
|
|
110
133
|
} else if (contentPart.type === "document") yield {
|
|
111
134
|
...contentPart,
|
|
112
135
|
...cacheControl ? { cache_control: cacheControl } : {}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message_inputs.cjs","names":["imageUrl: string","parsedUrl: URL","messages: BaseMessage[]","HumanMessage","toolCall: ToolCall","content: ContentBlock[]","toolCalls?: ToolCall[]","standardContentBlockConverter","_isAnthropicImageBlockParam","_isAnthropicThinkingBlock","block: AnthropicThinkingBlockParam","_isAnthropicRedactedThinkingBlock","block: AnthropicRedactedThinkingBlockParam","_isAnthropicSearchResultBlock","block: AnthropicSearchResultBlockParam","message: BaseMessage","AIMessage","_formatStandardContent","payload: AnthropicMessageCreateParams","cacheControl: CacheControl","messages: AnthropicMessageCreateParams[\"messages\"]","result: AnthropicMessageCreateParams[\"messages\"]","content:\n | string\n | Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\n | AnthropicSearchResultBlockParam\n >","msg: (typeof messages)[0]"],"sources":["../../src/utils/message_inputs.ts"],"sourcesContent":["/**\n * This util file contains functions for converting LangChain messages to Anthropic messages.\n */\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport {\n type BaseMessage,\n HumanMessage,\n ToolMessage,\n MessageContentComplex,\n isDataContentBlock,\n convertToProviderContentBlock,\n parseBase64DataUrl,\n ContentBlock,\n AIMessage,\n} from \"@langchain/core/messages\";\nimport { ToolCall } from \"@langchain/core/messages/tool\";\nimport {\n AnthropicImageBlockParam,\n AnthropicMessageCreateParams,\n AnthropicTextBlockParam,\n AnthropicToolResultBlockParam,\n AnthropicToolUseBlockParam,\n AnthropicDocumentBlockParam,\n AnthropicThinkingBlockParam,\n AnthropicRedactedThinkingBlockParam,\n AnthropicServerToolUseBlockParam,\n AnthropicWebSearchToolResultBlockParam,\n AnthropicSearchResultBlockParam,\n AnthropicToolResponse,\n AnthropicContainerUploadBlockParam,\n} from \"../types.js\";\nimport {\n _isAnthropicImageBlockParam,\n _isAnthropicRedactedThinkingBlock,\n _isAnthropicSearchResultBlock,\n _isAnthropicThinkingBlock,\n standardContentBlockConverter,\n} from \"./content.js\";\nimport { _formatStandardContent } from \"./standard.js\";\n\nfunction _formatImage(imageUrl: string) {\n const parsed = parseBase64DataUrl({ dataUrl: imageUrl });\n if (parsed) {\n return {\n type: \"base64\",\n media_type: parsed.mime_type,\n data: parsed.data,\n };\n }\n let parsedUrl: URL;\n\n try {\n parsedUrl = new URL(imageUrl);\n } catch {\n throw new Error(\n [\n `Malformed image URL: ${JSON.stringify(\n imageUrl\n )}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,\n \"Example: data:image/png;base64,/9j/4AAQSk...\",\n \"Example: https://example.com/image.jpg\",\n ].join(\"\\n\\n\")\n );\n }\n\n if (parsedUrl.protocol === \"http:\" || parsedUrl.protocol === \"https:\") {\n return {\n type: \"url\",\n url: imageUrl,\n };\n }\n\n throw new Error(\n [\n `Invalid image URL protocol: ${JSON.stringify(\n parsedUrl.protocol\n )}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,\n \"Example: data:image/png;base64,/9j/4AAQSk...\",\n \"Example: https://example.com/image.jpg\",\n ].join(\"\\n\\n\")\n );\n}\n\nfunction _ensureMessageContents(messages: BaseMessage[]): BaseMessage[] {\n // Merge runs of human/tool messages into single human messages with content blocks.\n const updatedMsgs = [];\n for (const message of messages) {\n if (message._getType() === \"tool\") {\n if (typeof message.content === \"string\") {\n const previousMessage = updatedMsgs[updatedMsgs.length - 1];\n if (\n previousMessage?._getType() === \"human\" &&\n Array.isArray(previousMessage.content) &&\n \"type\" in previousMessage.content[0] &&\n previousMessage.content[0].type === \"tool_result\"\n ) {\n // If the previous message was a tool result, we merge this tool message into it.\n (previousMessage.content as MessageContentComplex[]).push({\n type: \"tool_result\",\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n });\n } else {\n // If not, we create a new human message with the tool result.\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: \"tool_result\",\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: \"tool_result\",\n // rare case: message.content could be undefined\n ...(message.content != null\n ? { content: _formatContent(message) }\n : {}),\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(message);\n }\n }\n return updatedMsgs;\n}\n\nexport function _convertLangChainToolCallToAnthropic(\n toolCall: ToolCall\n): AnthropicToolResponse {\n if (toolCall.id === undefined) {\n throw new Error(`Anthropic requires all tool calls to have an \"id\".`);\n }\n return {\n type: \"tool_use\",\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args,\n };\n}\n\nfunction* _formatContentBlocks(\n content: ContentBlock[],\n toolCalls?: ToolCall[]\n): Generator<Anthropic.Beta.BetaContentBlockParam> {\n const toolTypes = [\n \"bash_code_execution_tool_result\",\n \"input_json_delta\",\n \"server_tool_use\",\n \"text_editor_code_execution_tool_result\",\n \"tool_result\",\n \"tool_use\",\n \"web_search_result\",\n \"web_search_tool_result\",\n ];\n const textTypes = [\"text\", \"text_delta\"];\n for (const contentPart of content) {\n if (isDataContentBlock(contentPart)) {\n yield convertToProviderContentBlock(\n contentPart,\n standardContentBlockConverter\n );\n }\n\n const cacheControl =\n \"cache_control\" in contentPart ? contentPart.cache_control : undefined;\n\n if (contentPart.type === \"image_url\") {\n let source;\n if (typeof contentPart.image_url === \"string\") {\n source = _formatImage(contentPart.image_url);\n } else if (\n typeof contentPart.image_url === \"object\" &&\n contentPart.image_url !== null &&\n \"url\" in contentPart.image_url &&\n typeof contentPart.image_url.url === \"string\"\n ) {\n source = _formatImage(contentPart.image_url.url);\n }\n if (source) {\n yield {\n type: \"image\" as const, // Explicitly setting the type as \"image\"\n source,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n } as Anthropic.Messages.ImageBlockParam;\n }\n } else if (_isAnthropicImageBlockParam(contentPart)) {\n yield contentPart;\n } else if (contentPart.type === \"image\") {\n // Handle new ContentBlock.Multimodal.Image format\n let source;\n\n if (\"url\" in contentPart && typeof contentPart.url === \"string\") {\n // URL-based image\n source = _formatImage(contentPart.url);\n } else if (\n \"data\" in contentPart &&\n (typeof contentPart.data === \"string\" ||\n // eslint-disable-next-line no-instanceof/no-instanceof\n contentPart.data instanceof Uint8Array)\n ) {\n // Base64-based image\n const mimeType =\n \"mimeType\" in contentPart && typeof contentPart.mimeType === \"string\"\n ? contentPart.mimeType\n : \"image/jpeg\";\n const data =\n typeof contentPart.data === \"string\"\n ? contentPart.data\n : Buffer.from(contentPart.data).toString(\"base64\");\n source = {\n type: \"base64\" as const,\n media_type: mimeType as\n | \"image/jpeg\"\n | \"image/png\"\n | \"image/gif\"\n | \"image/webp\",\n data,\n };\n } else if (\n \"fileId\" in contentPart &&\n typeof contentPart.fileId === \"string\"\n ) {\n // File ID-based image\n // Note: Anthropic supports file IDs for images that have been uploaded\n // to their servers via the Files API\n source = {\n type: \"file\" as const,\n file_id: contentPart.fileId,\n };\n }\n\n if (source) {\n yield {\n type: \"image\" as const,\n source,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n } as Anthropic.Messages.ImageBlockParam;\n }\n } else if (contentPart.type === \"document\") {\n // PDF\n yield {\n ...contentPart,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n } as Anthropic.Messages.DocumentBlockParam;\n } else if (_isAnthropicThinkingBlock(contentPart)) {\n const block: AnthropicThinkingBlockParam = {\n type: \"thinking\" as const, // Explicitly setting the type as \"thinking\"\n thinking: contentPart.thinking,\n signature: contentPart.signature,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n yield block;\n } else if (_isAnthropicRedactedThinkingBlock(contentPart)) {\n const block: AnthropicRedactedThinkingBlockParam = {\n type: \"redacted_thinking\" as const, // Explicitly setting the type as \"redacted_thinking\"\n data: contentPart.data,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n yield block;\n } else if (_isAnthropicSearchResultBlock(contentPart)) {\n const block: AnthropicSearchResultBlockParam = {\n type: \"search_result\" as const, // Explicitly setting the type as \"search_result\"\n title: contentPart.title,\n source: contentPart.source,\n ...(\"cache_control\" in contentPart && contentPart.cache_control\n ? { cache_control: contentPart.cache_control }\n : {}),\n ...(\"citations\" in contentPart && contentPart.citations\n ? { citations: contentPart.citations }\n : {}),\n content: contentPart.content,\n };\n yield block as Anthropic.Beta.BetaSearchResultBlockParam;\n } else if (\n textTypes.find((t) => t === contentPart.type) &&\n \"text\" in contentPart\n ) {\n // Assuming contentPart is of type MessageContentText here\n yield {\n type: \"text\" as const, // Explicitly setting the type as \"text\"\n text: contentPart.text,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n ...(\"citations\" in contentPart && contentPart.citations\n ? { citations: contentPart.citations }\n : {}),\n } as Anthropic.Messages.TextBlockParam;\n } else if (toolTypes.find((t) => t === contentPart.type)) {\n const contentPartCopy = { ...contentPart };\n\n if (contentPartCopy.type === \"input_json_delta\") {\n // `input_json_delta` type only represents yielding partial tool inputs\n // and is not a valid type for Anthropic messages.\n // These blocks appear in streaming responses and should be skipped\n // as their input data is already captured in tool_calls.\n continue;\n }\n\n if (\n contentPartCopy.type === \"tool_use\" &&\n typeof contentPartCopy.input === \"string\"\n ) {\n // First, try to get the input from the corresponding tool_call.\n // This is the most reliable source since tool_calls are properly\n // consolidated from tool_call_chunks during streaming.\n const matchingToolCall = toolCalls?.find(\n (tc) => tc.id === contentPartCopy.id\n );\n if (matchingToolCall) {\n contentPartCopy.input = matchingToolCall.args;\n } else {\n // Fallback: `tool_use` content part may be followed by `input_json_delta`\n // content parts which are chunks of a stringified JSON input,\n // so we need to collect them and merge their inputs.\n const inputDeltas = content.filter(\n (nestedContentPart) =>\n nestedContentPart.index === contentPartCopy.index &&\n nestedContentPart.type === \"input_json_delta\" &&\n typeof nestedContentPart.input === \"string\"\n );\n // If no `input_json_delta` parts are found, this line will just\n // return `contentPartCopy.input`, so no additional check is needed\n contentPartCopy.input = inputDeltas.reduce(\n (accumulator, nestedContentPart) =>\n accumulator + nestedContentPart.input,\n contentPartCopy.input\n );\n }\n }\n\n if (\"index\" in contentPartCopy) {\n // Anthropic does not support passing the index field here, so we remove it.\n delete contentPartCopy.index;\n }\n\n if (\"input\" in contentPartCopy) {\n // Anthropic tool use inputs should be valid objects, when applicable.\n if (typeof contentPartCopy.input === \"string\") {\n try {\n contentPartCopy.input = JSON.parse(contentPartCopy.input);\n } catch {\n contentPartCopy.input = {};\n }\n }\n }\n // TODO: Fix when SDK types are fixed\n yield {\n ...contentPartCopy,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n } else if (contentPart.type === \"container_upload\") {\n yield {\n ...contentPart,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n } as AnthropicContainerUploadBlockParam;\n }\n\n // Note that we are intentionally dropping any blocks that we don't\n // recognize. This is to allow for cross-compatibility between different\n // providers that may have different block types. Ie if we take a message\n // output from OpenAI and send it to Anthropic, we want to drop any blocks\n // that Anthropic doesn't understand.\n }\n}\n\nfunction _formatContent(message: BaseMessage, toolCalls?: ToolCall[]) {\n const { content } = message;\n\n if (typeof content === \"string\") {\n return content;\n } else {\n return Array.from(_formatContentBlocks(content, toolCalls));\n }\n}\n\n/**\n * Formats messages as a prompt for the model.\n * Used in LangSmith, export is important here.\n * @param messages The base messages to format as a prompt.\n * @returns The formatted prompt.\n */\nexport function _convertMessagesToAnthropicPayload(\n messages: BaseMessage[]\n): AnthropicMessageCreateParams {\n const mergedMessages = _ensureMessageContents(messages);\n let system;\n if (mergedMessages.length > 0 && mergedMessages[0]._getType() === \"system\") {\n system = messages[0].content;\n }\n const conversationMessages =\n system !== undefined ? mergedMessages.slice(1) : mergedMessages;\n const formattedMessages = conversationMessages.map((message) => {\n let role;\n if (message._getType() === \"human\") {\n role = \"user\" as const;\n } else if (message._getType() === \"ai\") {\n role = \"assistant\" as const;\n } else if (message._getType() === \"tool\") {\n role = \"user\" as const;\n } else if (message._getType() === \"system\") {\n throw new Error(\n \"System messages are only permitted as the first passed message.\"\n );\n } else {\n throw new Error(`Message type \"${message.type}\" is not supported.`);\n }\n if (\n AIMessage.isInstance(message) &&\n message.response_metadata?.output_version === \"v1\"\n ) {\n return {\n role,\n content: _formatStandardContent(message),\n };\n }\n if (AIMessage.isInstance(message) && !!message.tool_calls?.length) {\n if (typeof message.content === \"string\") {\n if (message.content === \"\") {\n return {\n role,\n content: message.tool_calls.map(\n _convertLangChainToolCallToAnthropic\n ),\n };\n } else {\n return {\n role,\n content: [\n { type: \"text\", text: message.content },\n ...message.tool_calls.map(_convertLangChainToolCallToAnthropic),\n ],\n };\n }\n } else {\n const { content } = message;\n const hasMismatchedToolCalls = !message.tool_calls.every((toolCall) =>\n content.find(\n (contentPart) =>\n (contentPart.type === \"tool_use\" ||\n contentPart.type === \"input_json_delta\" ||\n contentPart.type === \"server_tool_use\") &&\n contentPart.id === toolCall.id\n )\n );\n if (hasMismatchedToolCalls) {\n console.warn(\n `The \"tool_calls\" field on a message is only respected if content is a string.`\n );\n }\n return {\n role,\n content: _formatContent(message, message.tool_calls),\n };\n }\n } else {\n return {\n role,\n content: _formatContent(\n message,\n AIMessage.isInstance(message) ? message.tool_calls : undefined\n ),\n };\n }\n });\n return {\n messages: mergeMessages(\n formattedMessages as AnthropicMessageCreateParams[\"messages\"]\n ),\n system,\n } as AnthropicMessageCreateParams;\n}\n\n/**\n * Cache control configuration for Anthropic prompt caching.\n */\ninterface CacheControl {\n type: \"ephemeral\";\n ttl?: \"5m\" | \"1h\";\n}\n\n/**\n * Applies cache_control to the last content block of the last message in the payload.\n * This is the recommended approach for prompt caching as it applies the cache_control\n * at the final formatting layer, after all message processing is complete.\n *\n * This matches the Python langchain-anthropic implementation where cache_control\n * is applied via model_settings rather than modifying message content blocks directly.\n *\n * @param payload - The formatted Anthropic message payload\n * @param cacheControl - The cache control configuration to apply\n * @returns The payload with cache_control applied to the last content block\n */\nexport function applyCacheControlToPayload(\n payload: AnthropicMessageCreateParams,\n cacheControl: CacheControl\n): AnthropicMessageCreateParams {\n if (!payload.messages || payload.messages.length === 0) {\n return payload;\n }\n\n const messages = [...payload.messages];\n const lastMessageIndex = messages.length - 1;\n const lastMessage = messages[lastMessageIndex];\n\n if (!lastMessage) {\n return payload;\n }\n\n // Handle string content - convert to text block with cache_control\n if (typeof lastMessage.content === \"string\") {\n messages[lastMessageIndex] = {\n ...lastMessage,\n content: [\n {\n type: \"text\",\n text: lastMessage.content,\n cache_control: cacheControl,\n },\n ],\n };\n return { ...payload, messages };\n }\n\n // Handle array content - add cache_control to the last block\n if (Array.isArray(lastMessage.content) && lastMessage.content.length > 0) {\n const content = [...lastMessage.content];\n const lastBlockIndex = content.length - 1;\n const lastBlock = content[lastBlockIndex];\n\n // Add cache_control to the last block\n content[lastBlockIndex] = {\n ...lastBlock,\n cache_control: cacheControl,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n\n messages[lastMessageIndex] = {\n ...lastMessage,\n content,\n };\n return { ...payload, messages };\n }\n\n return payload;\n}\n\nfunction mergeMessages(messages: AnthropicMessageCreateParams[\"messages\"]) {\n if (!messages || messages.length <= 1) {\n return messages;\n }\n\n const result: AnthropicMessageCreateParams[\"messages\"] = [];\n let currentMessage = messages[0];\n\n const normalizeContent = (\n content:\n | string\n | Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\n | AnthropicSearchResultBlockParam\n >\n ): Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\n | AnthropicSearchResultBlockParam\n > => {\n if (typeof content === \"string\") {\n return [\n {\n type: \"text\",\n text: content,\n },\n ];\n }\n return content;\n };\n\n const isToolResultMessage = (msg: (typeof messages)[0]) => {\n if (msg.role !== \"user\") return false;\n\n if (typeof msg.content === \"string\") {\n return false;\n }\n\n return (\n Array.isArray(msg.content) &&\n msg.content.every((item) => item.type === \"tool_result\")\n );\n };\n\n for (let i = 1; i < messages.length; i += 1) {\n const nextMessage = messages[i];\n\n if (\n isToolResultMessage(currentMessage) &&\n isToolResultMessage(nextMessage)\n ) {\n // Merge the messages by combining their content arrays\n currentMessage = {\n ...currentMessage,\n content: [\n ...normalizeContent(currentMessage.content),\n ...normalizeContent(nextMessage.content),\n ],\n };\n } else {\n result.push(currentMessage);\n currentMessage = nextMessage;\n }\n }\n\n result.push(currentMessage);\n return result;\n}\n"],"mappings":";;;;;;AAwCA,SAAS,aAAaA,UAAkB;CACtC,MAAM,2DAA4B,EAAE,SAAS,SAAU,EAAC;AACxD,KAAI,OACF,QAAO;EACL,MAAM;EACN,YAAY,OAAO;EACnB,MAAM,OAAO;CACd;CAEH,IAAIC;AAEJ,KAAI;EACF,YAAY,IAAI,IAAI;CACrB,QAAO;AACN,QAAM,IAAI,MACR;GACE,CAAC,qBAAqB,EAAE,KAAK,UAC3B,SACD,CAAC,6FAA6F,CAAC;GAChG;GACA;EACD,EAAC,KAAK,OAAO;CAEjB;AAED,KAAI,UAAU,aAAa,WAAW,UAAU,aAAa,SAC3D,QAAO;EACL,MAAM;EACN,KAAK;CACN;AAGH,OAAM,IAAI,MACR;EACE,CAAC,4BAA4B,EAAE,KAAK,UAClC,UAAU,SACX,CAAC,2GAA2G,CAAC;EAC9G;EACA;CACD,EAAC,KAAK,OAAO;AAEjB;AAED,SAAS,uBAAuBC,UAAwC;CAEtE,MAAM,cAAc,CAAE;AACtB,MAAK,MAAM,WAAW,SACpB,KAAI,QAAQ,UAAU,KAAK,OACzB,KAAI,OAAO,QAAQ,YAAY,UAAU;EACvC,MAAM,kBAAkB,YAAY,YAAY,SAAS;AACzD,MACE,iBAAiB,UAAU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AiB,SAAS;CAE9B,MAAM,mBAAmB,CACvBC,YAyBG;AACH,MAAI,OAAO,YAAY,SACrB,QAAO,CACL;GACE,MAAM;GACN,MAAM;EACP,CACF;AAEH,SAAO;CACR;CAED,MAAM,sBAAsB,CAACC,QAA8B;AACzD,MAAI,IAAI,SAAS,OAAQ,QAAO;AAEhC,MAAI,OAAO,IAAI,YAAY,SACzB,QAAO;AAGT,SACE,MAAM,QAAQ,IAAI,QAAQ,IAC1B,IAAI,QAAQ,MAAM,CAAC,SAAS,KAAK,SAAS,cAAc;CAE3D;AAED,MAAK,IAAI,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK,GAAG;EAC3C,MAAM,cAAc,SAAS;AAE7B,MACE,oBAAoB,eAAe,IACnC,oBAAoB,YAAY,EAGhC,iBAAiB;GACf,GAAG;GACH,SAAS,CACP,GAAG,iBAAiB,eAAe,QAAQ,EAC3C,GAAG,iBAAiB,YAAY,QAAQ,AACzC;EACF;OACI;GACL,OAAO,KAAK,eAAe;GAC3B,iBAAiB;EAClB;CACF;CAED,OAAO,KAAK,eAAe;AAC3B,QAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"message_inputs.cjs","names":["imageUrl: string","parsedUrl: URL","messages: BaseMessage[]","HumanMessage","toolCall: ToolCall","content: ContentBlock[]","toolCalls?: ToolCall[]","standardContentBlockConverter","_isAnthropicImageBlockParam","source:\n | { type: \"url\"; url: string }\n | { type: \"base64\"; media_type: string; data: string }\n | { type: \"file\"; file_id: string }\n | undefined","_isAnthropicThinkingBlock","block: AnthropicThinkingBlockParam","_isAnthropicRedactedThinkingBlock","block: AnthropicRedactedThinkingBlockParam","_isAnthropicSearchResultBlock","block: AnthropicSearchResultBlockParam","message: BaseMessage","AIMessage","_formatStandardContent","payload: AnthropicMessageCreateParams","cacheControl: CacheControl","messages: AnthropicMessageCreateParams[\"messages\"]","result: AnthropicMessageCreateParams[\"messages\"]","content:\n | string\n | Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\n | AnthropicSearchResultBlockParam\n >","msg: (typeof messages)[0]"],"sources":["../../src/utils/message_inputs.ts"],"sourcesContent":["/**\n * This util file contains functions for converting LangChain messages to Anthropic messages.\n */\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport {\n type BaseMessage,\n HumanMessage,\n ToolMessage,\n MessageContentComplex,\n isDataContentBlock,\n convertToProviderContentBlock,\n parseBase64DataUrl,\n ContentBlock,\n AIMessage,\n} from \"@langchain/core/messages\";\nimport { ToolCall } from \"@langchain/core/messages/tool\";\nimport {\n AnthropicImageBlockParam,\n AnthropicMessageCreateParams,\n AnthropicTextBlockParam,\n AnthropicToolResultBlockParam,\n AnthropicToolUseBlockParam,\n AnthropicDocumentBlockParam,\n AnthropicThinkingBlockParam,\n AnthropicRedactedThinkingBlockParam,\n AnthropicServerToolUseBlockParam,\n AnthropicWebSearchToolResultBlockParam,\n AnthropicSearchResultBlockParam,\n AnthropicToolResponse,\n AnthropicContainerUploadBlockParam,\n} from \"../types.js\";\nimport {\n _isAnthropicImageBlockParam,\n _isAnthropicRedactedThinkingBlock,\n _isAnthropicSearchResultBlock,\n _isAnthropicThinkingBlock,\n standardContentBlockConverter,\n} from \"./content.js\";\nimport { _formatStandardContent } from \"./standard.js\";\n\nfunction _formatImage(imageUrl: string) {\n const parsed = parseBase64DataUrl({ dataUrl: imageUrl });\n if (parsed) {\n return {\n type: \"base64\",\n media_type: parsed.mime_type,\n data: parsed.data,\n };\n }\n let parsedUrl: URL;\n\n try {\n parsedUrl = new URL(imageUrl);\n } catch {\n throw new Error(\n [\n `Malformed image URL: ${JSON.stringify(\n imageUrl\n )}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,\n \"Example: data:image/png;base64,/9j/4AAQSk...\",\n \"Example: https://example.com/image.jpg\",\n ].join(\"\\n\\n\")\n );\n }\n\n if (parsedUrl.protocol === \"http:\" || parsedUrl.protocol === \"https:\") {\n return {\n type: \"url\",\n url: imageUrl,\n };\n }\n\n throw new Error(\n [\n `Invalid image URL protocol: ${JSON.stringify(\n parsedUrl.protocol\n )}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,\n \"Example: data:image/png;base64,/9j/4AAQSk...\",\n \"Example: https://example.com/image.jpg\",\n ].join(\"\\n\\n\")\n );\n}\n\nfunction _ensureMessageContents(messages: BaseMessage[]): BaseMessage[] {\n // Merge runs of human/tool messages into single human messages with content blocks.\n const updatedMsgs = [];\n for (const message of messages) {\n if (message._getType() === \"tool\") {\n if (typeof message.content === \"string\") {\n const previousMessage = updatedMsgs[updatedMsgs.length - 1];\n if (\n previousMessage?._getType() === \"human\" &&\n Array.isArray(previousMessage.content) &&\n \"type\" in previousMessage.content[0] &&\n previousMessage.content[0].type === \"tool_result\"\n ) {\n // If the previous message was a tool result, we merge this tool message into it.\n (previousMessage.content as MessageContentComplex[]).push({\n type: \"tool_result\",\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n });\n } else {\n // If not, we create a new human message with the tool result.\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: \"tool_result\",\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: \"tool_result\",\n // rare case: message.content could be undefined\n ...(message.content != null\n ? { content: _formatContent(message) }\n : {}),\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(message);\n }\n }\n return updatedMsgs;\n}\n\nexport function _convertLangChainToolCallToAnthropic(\n toolCall: ToolCall\n): AnthropicToolResponse {\n if (toolCall.id === undefined) {\n throw new Error(`Anthropic requires all tool calls to have an \"id\".`);\n }\n return {\n type: \"tool_use\",\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args,\n };\n}\n\nfunction* _formatContentBlocks(\n content: ContentBlock[],\n toolCalls?: ToolCall[]\n): Generator<Anthropic.Beta.BetaContentBlockParam> {\n const toolTypes = [\n \"bash_code_execution_tool_result\",\n \"input_json_delta\",\n \"server_tool_use\",\n \"text_editor_code_execution_tool_result\",\n \"tool_result\",\n \"tool_use\",\n \"web_search_result\",\n \"web_search_tool_result\",\n ];\n const textTypes = [\"text\", \"text_delta\"];\n for (const contentPart of content) {\n if (isDataContentBlock(contentPart)) {\n yield convertToProviderContentBlock(\n contentPart,\n standardContentBlockConverter\n );\n }\n\n const cacheControl =\n \"cache_control\" in contentPart ? contentPart.cache_control : undefined;\n\n if (contentPart.type === \"image_url\") {\n let source;\n if (typeof contentPart.image_url === \"string\") {\n source = _formatImage(contentPart.image_url);\n } else if (\n typeof contentPart.image_url === \"object\" &&\n contentPart.image_url !== null &&\n \"url\" in contentPart.image_url &&\n typeof contentPart.image_url.url === \"string\"\n ) {\n source = _formatImage(contentPart.image_url.url);\n }\n if (source) {\n yield {\n type: \"image\" as const, // Explicitly setting the type as \"image\"\n source,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n } as Anthropic.Messages.ImageBlockParam;\n }\n } else if (_isAnthropicImageBlockParam(contentPart)) {\n yield contentPart;\n } else if (contentPart.type === \"image\") {\n // Handle new ContentBlock.Multimodal.Image format\n let source;\n\n if (\"url\" in contentPart && typeof contentPart.url === \"string\") {\n // URL-based image\n source = _formatImage(contentPart.url);\n } else if (\n \"data\" in contentPart &&\n (typeof contentPart.data === \"string\" ||\n // eslint-disable-next-line no-instanceof/no-instanceof\n contentPart.data instanceof Uint8Array)\n ) {\n // Base64-based image\n const mimeType =\n \"mimeType\" in contentPart && typeof contentPart.mimeType === \"string\"\n ? contentPart.mimeType\n : \"image/jpeg\";\n const data =\n typeof contentPart.data === \"string\"\n ? contentPart.data\n : Buffer.from(contentPart.data).toString(\"base64\");\n source = {\n type: \"base64\" as const,\n media_type: mimeType as\n | \"image/jpeg\"\n | \"image/png\"\n | \"image/gif\"\n | \"image/webp\",\n data,\n };\n } else if (\n \"fileId\" in contentPart &&\n typeof contentPart.fileId === \"string\"\n ) {\n // File ID-based image\n // Note: Anthropic supports file IDs for images that have been uploaded\n // to their servers via the Files API\n source = {\n type: \"file\" as const,\n file_id: contentPart.fileId,\n };\n }\n\n if (source) {\n yield {\n type: \"image\" as const,\n source,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n } as Anthropic.Messages.ImageBlockParam;\n }\n } else if (contentPart.type === \"file\") {\n // Handle new ContentBlock.Multimodal.File format\n let source:\n | { type: \"url\"; url: string }\n | { type: \"base64\"; media_type: string; data: string }\n | { type: \"file\"; file_id: string }\n | undefined;\n\n if (\"url\" in contentPart && typeof contentPart.url === \"string\") {\n // File with URL\n source = {\n type: \"url\" as const,\n url: contentPart.url,\n };\n } else if (\n \"data\" in contentPart &&\n (typeof contentPart.data === \"string\" ||\n // eslint-disable-next-line no-instanceof/no-instanceof\n contentPart.data instanceof Uint8Array)\n ) {\n // File with base64 data (string or Uint8Array)\n const media_type =\n \"mimeType\" in contentPart && typeof contentPart.mimeType === \"string\"\n ? contentPart.mimeType\n : \"application/pdf\";\n const data =\n typeof contentPart.data === \"string\"\n ? contentPart.data\n : Buffer.from(contentPart.data).toString(\"base64\");\n\n source = {\n type: \"base64\" as const,\n media_type,\n data,\n };\n } else if (\n \"fileId\" in contentPart &&\n typeof contentPart.fileId === \"string\"\n ) {\n // File ID from Anthropic Files API\n // https://platform.claude.com/docs/en/build-with-claude/pdf-support#option-3-files-api\n source = {\n type: \"file\" as const,\n file_id: contentPart.fileId,\n };\n }\n\n if (source) {\n yield {\n type: \"document\" as const,\n source,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n } as Anthropic.Messages.DocumentBlockParam;\n }\n } else if (contentPart.type === \"document\") {\n // PDF\n yield {\n ...contentPart,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n } as Anthropic.Messages.DocumentBlockParam;\n } else if (_isAnthropicThinkingBlock(contentPart)) {\n const block: AnthropicThinkingBlockParam = {\n type: \"thinking\" as const, // Explicitly setting the type as \"thinking\"\n thinking: contentPart.thinking,\n signature: contentPart.signature,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n yield block;\n } else if (_isAnthropicRedactedThinkingBlock(contentPart)) {\n const block: AnthropicRedactedThinkingBlockParam = {\n type: \"redacted_thinking\" as const, // Explicitly setting the type as \"redacted_thinking\"\n data: contentPart.data,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n yield block;\n } else if (_isAnthropicSearchResultBlock(contentPart)) {\n const block: AnthropicSearchResultBlockParam = {\n type: \"search_result\" as const, // Explicitly setting the type as \"search_result\"\n title: contentPart.title,\n source: contentPart.source,\n ...(\"cache_control\" in contentPart && contentPart.cache_control\n ? { cache_control: contentPart.cache_control }\n : {}),\n ...(\"citations\" in contentPart && contentPart.citations\n ? { citations: contentPart.citations }\n : {}),\n content: contentPart.content,\n };\n yield block as Anthropic.Beta.BetaSearchResultBlockParam;\n } else if (\n textTypes.find((t) => t === contentPart.type) &&\n \"text\" in contentPart\n ) {\n // Assuming contentPart is of type MessageContentText here\n yield {\n type: \"text\" as const, // Explicitly setting the type as \"text\"\n text: contentPart.text,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n ...(\"citations\" in contentPart && contentPart.citations\n ? { citations: contentPart.citations }\n : {}),\n } as Anthropic.Messages.TextBlockParam;\n } else if (toolTypes.find((t) => t === contentPart.type)) {\n const contentPartCopy = { ...contentPart };\n\n if (contentPartCopy.type === \"input_json_delta\") {\n // `input_json_delta` type only represents yielding partial tool inputs\n // and is not a valid type for Anthropic messages.\n // These blocks appear in streaming responses and should be skipped\n // as their input data is already captured in tool_calls.\n continue;\n }\n\n if (\n contentPartCopy.type === \"tool_use\" &&\n typeof contentPartCopy.input === \"string\"\n ) {\n // First, try to get the input from the corresponding tool_call.\n // This is the most reliable source since tool_calls are properly\n // consolidated from tool_call_chunks during streaming.\n const matchingToolCall = toolCalls?.find(\n (tc) => tc.id === contentPartCopy.id\n );\n if (matchingToolCall) {\n contentPartCopy.input = matchingToolCall.args;\n } else {\n // Fallback: `tool_use` content part may be followed by `input_json_delta`\n // content parts which are chunks of a stringified JSON input,\n // so we need to collect them and merge their inputs.\n const inputDeltas = content.filter(\n (nestedContentPart) =>\n nestedContentPart.index === contentPartCopy.index &&\n nestedContentPart.type === \"input_json_delta\" &&\n typeof nestedContentPart.input === \"string\"\n );\n // If no `input_json_delta` parts are found, this line will just\n // return `contentPartCopy.input`, so no additional check is needed\n contentPartCopy.input = inputDeltas.reduce(\n (accumulator, nestedContentPart) =>\n accumulator + nestedContentPart.input,\n contentPartCopy.input\n );\n }\n }\n\n if (\"index\" in contentPartCopy) {\n // Anthropic does not support passing the index field here, so we remove it.\n delete contentPartCopy.index;\n }\n\n if (\"input\" in contentPartCopy) {\n // Anthropic tool use inputs should be valid objects, when applicable.\n if (typeof contentPartCopy.input === \"string\") {\n try {\n contentPartCopy.input = JSON.parse(contentPartCopy.input);\n } catch {\n contentPartCopy.input = {};\n }\n }\n }\n // TODO: Fix when SDK types are fixed\n yield {\n ...contentPartCopy,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n } else if (contentPart.type === \"container_upload\") {\n yield {\n ...contentPart,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n } as AnthropicContainerUploadBlockParam;\n }\n\n // Note that we are intentionally dropping any blocks that we don't\n // recognize. This is to allow for cross-compatibility between different\n // providers that may have different block types. Ie if we take a message\n // output from OpenAI and send it to Anthropic, we want to drop any blocks\n // that Anthropic doesn't understand.\n }\n}\n\nfunction _formatContent(message: BaseMessage, toolCalls?: ToolCall[]) {\n const { content } = message;\n\n if (typeof content === \"string\") {\n return content;\n } else {\n return Array.from(_formatContentBlocks(content, toolCalls));\n }\n}\n\n/**\n * Formats messages as a prompt for the model.\n * Used in LangSmith, export is important here.\n * @param messages The base messages to format as a prompt.\n * @returns The formatted prompt.\n */\nexport function _convertMessagesToAnthropicPayload(\n messages: BaseMessage[]\n): AnthropicMessageCreateParams {\n const mergedMessages = _ensureMessageContents(messages);\n let system;\n if (mergedMessages.length > 0 && mergedMessages[0]._getType() === \"system\") {\n system = messages[0].content;\n }\n const conversationMessages =\n system !== undefined ? mergedMessages.slice(1) : mergedMessages;\n const formattedMessages = conversationMessages.map((message) => {\n let role;\n if (message._getType() === \"human\") {\n role = \"user\" as const;\n } else if (message._getType() === \"ai\") {\n role = \"assistant\" as const;\n } else if (message._getType() === \"tool\") {\n role = \"user\" as const;\n } else if (message._getType() === \"system\") {\n throw new Error(\n \"System messages are only permitted as the first passed message.\"\n );\n } else {\n throw new Error(`Message type \"${message.type}\" is not supported.`);\n }\n if (\n AIMessage.isInstance(message) &&\n message.response_metadata?.output_version === \"v1\"\n ) {\n return {\n role,\n content: _formatStandardContent(message),\n };\n }\n if (AIMessage.isInstance(message) && !!message.tool_calls?.length) {\n if (typeof message.content === \"string\") {\n if (message.content === \"\") {\n return {\n role,\n content: message.tool_calls.map(\n _convertLangChainToolCallToAnthropic\n ),\n };\n } else {\n return {\n role,\n content: [\n { type: \"text\", text: message.content },\n ...message.tool_calls.map(_convertLangChainToolCallToAnthropic),\n ],\n };\n }\n } else {\n const { content } = message;\n const hasMismatchedToolCalls = !message.tool_calls.every((toolCall) =>\n content.find(\n (contentPart) =>\n (contentPart.type === \"tool_use\" ||\n contentPart.type === \"input_json_delta\" ||\n contentPart.type === \"server_tool_use\") &&\n contentPart.id === toolCall.id\n )\n );\n if (hasMismatchedToolCalls) {\n console.warn(\n `The \"tool_calls\" field on a message is only respected if content is a string.`\n );\n }\n return {\n role,\n content: _formatContent(message, message.tool_calls),\n };\n }\n } else {\n return {\n role,\n content: _formatContent(\n message,\n AIMessage.isInstance(message) ? message.tool_calls : undefined\n ),\n };\n }\n });\n return {\n messages: mergeMessages(\n formattedMessages as AnthropicMessageCreateParams[\"messages\"]\n ),\n system,\n } as AnthropicMessageCreateParams;\n}\n\n/**\n * Cache control configuration for Anthropic prompt caching.\n */\ninterface CacheControl {\n type: \"ephemeral\";\n ttl?: \"5m\" | \"1h\";\n}\n\n/**\n * Applies cache_control to the last content block of the last message in the payload.\n * This is the recommended approach for prompt caching as it applies the cache_control\n * at the final formatting layer, after all message processing is complete.\n *\n * This matches the Python langchain-anthropic implementation where cache_control\n * is applied via model_settings rather than modifying message content blocks directly.\n *\n * @param payload - The formatted Anthropic message payload\n * @param cacheControl - The cache control configuration to apply\n * @returns The payload with cache_control applied to the last content block\n */\nexport function applyCacheControlToPayload(\n payload: AnthropicMessageCreateParams,\n cacheControl: CacheControl\n): AnthropicMessageCreateParams {\n if (!payload.messages || payload.messages.length === 0) {\n return payload;\n }\n\n const messages = [...payload.messages];\n const lastMessageIndex = messages.length - 1;\n const lastMessage = messages[lastMessageIndex];\n\n if (!lastMessage) {\n return payload;\n }\n\n // Handle string content - convert to text block with cache_control\n if (typeof lastMessage.content === \"string\") {\n messages[lastMessageIndex] = {\n ...lastMessage,\n content: [\n {\n type: \"text\",\n text: lastMessage.content,\n cache_control: cacheControl,\n },\n ],\n };\n return { ...payload, messages };\n }\n\n // Handle array content - add cache_control to the last block\n if (Array.isArray(lastMessage.content) && lastMessage.content.length > 0) {\n const content = [...lastMessage.content];\n const lastBlockIndex = content.length - 1;\n const lastBlock = content[lastBlockIndex];\n\n // Add cache_control to the last block\n content[lastBlockIndex] = {\n ...lastBlock,\n cache_control: cacheControl,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n\n messages[lastMessageIndex] = {\n ...lastMessage,\n content,\n };\n return { ...payload, messages };\n }\n\n return payload;\n}\n\nfunction mergeMessages(messages: AnthropicMessageCreateParams[\"messages\"]) {\n if (!messages || messages.length <= 1) {\n return messages;\n }\n\n const result: AnthropicMessageCreateParams[\"messages\"] = [];\n let currentMessage = messages[0];\n\n const normalizeContent = (\n content:\n | string\n | Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\n | AnthropicSearchResultBlockParam\n >\n ): Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\n | AnthropicSearchResultBlockParam\n > => {\n if (typeof content === \"string\") {\n return [\n {\n type: \"text\",\n text: content,\n },\n ];\n }\n return content;\n };\n\n const isToolResultMessage = (msg: (typeof messages)[0]) => {\n if (msg.role !== \"user\") return false;\n\n if (typeof msg.content === \"string\") {\n return false;\n }\n\n return (\n Array.isArray(msg.content) &&\n msg.content.every((item) => item.type === \"tool_result\")\n );\n };\n\n for (let i = 1; i < messages.length; i += 1) {\n const nextMessage = messages[i];\n\n if (\n isToolResultMessage(currentMessage) &&\n isToolResultMessage(nextMessage)\n ) {\n // Merge the messages by combining their content arrays\n currentMessage = {\n ...currentMessage,\n content: [\n ...normalizeContent(currentMessage.content),\n ...normalizeContent(nextMessage.content),\n ],\n };\n } else {\n result.push(currentMessage);\n currentMessage = nextMessage;\n }\n }\n\n result.push(currentMessage);\n return result;\n}\n"],"mappings":";;;;;;AAwCA,SAAS,aAAaA,UAAkB;CACtC,MAAM,2DAA4B,EAAE,SAAS,SAAU,EAAC;AACxD,KAAI,OACF,QAAO;EACL,MAAM;EACN,YAAY,OAAO;EACnB,MAAM,OAAO;CACd;CAEH,IAAIC;AAEJ,KAAI;EACF,YAAY,IAAI,IAAI;CACrB,QAAO;AACN,QAAM,IAAI,MACR;GACE,CAAC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CAED,MAAM,sBAAsB,CAACC,QAA8B;AACzD,MAAI,IAAI,SAAS,OAAQ,QAAO;AAEhC,MAAI,OAAO,IAAI,YAAY,SACzB,QAAO;AAGT,SACE,MAAM,QAAQ,IAAI,QAAQ,IAC1B,IAAI,QAAQ,MAAM,CAAC,SAAS,KAAK,SAAS,cAAc;CAE3D;AAED,MAAK,IAAI,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK,GAAG;EAC3C,MAAM,cAAc,SAAS;AAE7B,MACE,oBAAoB,eAAe,IACnC,oBAAoB,YAAY,EAGhC,iBAAiB;GACf,GAAG;GACH,SAAS,CACP,GAAG,iBAAiB,eAAe,QAAQ,EAC3C,GAAG,iBAAiB,YAAY,QAAQ,AACzC;EACF;OACI;GACL,OAAO,KAAK,eAAe;GAC3B,iBAAiB;EAClB;CACF;CAED,OAAO,KAAK,eAAe;AAC3B,QAAO;AACR"}
|
|
@@ -106,6 +106,29 @@ function* _formatContentBlocks(content, toolCalls) {
|
|
|
106
106
|
source,
|
|
107
107
|
...cacheControl ? { cache_control: cacheControl } : {}
|
|
108
108
|
};
|
|
109
|
+
} else if (contentPart.type === "file") {
|
|
110
|
+
let source;
|
|
111
|
+
if ("url" in contentPart && typeof contentPart.url === "string") source = {
|
|
112
|
+
type: "url",
|
|
113
|
+
url: contentPart.url
|
|
114
|
+
};
|
|
115
|
+
else if ("data" in contentPart && (typeof contentPart.data === "string" || contentPart.data instanceof Uint8Array)) {
|
|
116
|
+
const media_type = "mimeType" in contentPart && typeof contentPart.mimeType === "string" ? contentPart.mimeType : "application/pdf";
|
|
117
|
+
const data = typeof contentPart.data === "string" ? contentPart.data : Buffer.from(contentPart.data).toString("base64");
|
|
118
|
+
source = {
|
|
119
|
+
type: "base64",
|
|
120
|
+
media_type,
|
|
121
|
+
data
|
|
122
|
+
};
|
|
123
|
+
} else if ("fileId" in contentPart && typeof contentPart.fileId === "string") source = {
|
|
124
|
+
type: "file",
|
|
125
|
+
file_id: contentPart.fileId
|
|
126
|
+
};
|
|
127
|
+
if (source) yield {
|
|
128
|
+
type: "document",
|
|
129
|
+
source,
|
|
130
|
+
...cacheControl ? { cache_control: cacheControl } : {}
|
|
131
|
+
};
|
|
109
132
|
} else if (contentPart.type === "document") yield {
|
|
110
133
|
...contentPart,
|
|
111
134
|
...cacheControl ? { cache_control: cacheControl } : {}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"message_inputs.js","names":["imageUrl: string","parsedUrl: URL","messages: BaseMessage[]","toolCall: ToolCall","content: ContentBlock[]","toolCalls?: ToolCall[]","block: AnthropicThinkingBlockParam","block: AnthropicRedactedThinkingBlockParam","block: AnthropicSearchResultBlockParam","message: BaseMessage","payload: AnthropicMessageCreateParams","cacheControl: CacheControl","messages: AnthropicMessageCreateParams[\"messages\"]","result: AnthropicMessageCreateParams[\"messages\"]","content:\n | string\n | Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\n | AnthropicSearchResultBlockParam\n >","msg: (typeof messages)[0]"],"sources":["../../src/utils/message_inputs.ts"],"sourcesContent":["/**\n * This util file contains functions for converting LangChain messages to Anthropic messages.\n */\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport {\n type BaseMessage,\n HumanMessage,\n ToolMessage,\n MessageContentComplex,\n isDataContentBlock,\n convertToProviderContentBlock,\n parseBase64DataUrl,\n ContentBlock,\n AIMessage,\n} from \"@langchain/core/messages\";\nimport { ToolCall } from \"@langchain/core/messages/tool\";\nimport {\n AnthropicImageBlockParam,\n AnthropicMessageCreateParams,\n AnthropicTextBlockParam,\n AnthropicToolResultBlockParam,\n AnthropicToolUseBlockParam,\n AnthropicDocumentBlockParam,\n AnthropicThinkingBlockParam,\n AnthropicRedactedThinkingBlockParam,\n AnthropicServerToolUseBlockParam,\n AnthropicWebSearchToolResultBlockParam,\n AnthropicSearchResultBlockParam,\n AnthropicToolResponse,\n AnthropicContainerUploadBlockParam,\n} from \"../types.js\";\nimport {\n _isAnthropicImageBlockParam,\n _isAnthropicRedactedThinkingBlock,\n _isAnthropicSearchResultBlock,\n _isAnthropicThinkingBlock,\n standardContentBlockConverter,\n} from \"./content.js\";\nimport { _formatStandardContent } from \"./standard.js\";\n\nfunction _formatImage(imageUrl: string) {\n const parsed = parseBase64DataUrl({ dataUrl: imageUrl });\n if (parsed) {\n return {\n type: \"base64\",\n media_type: parsed.mime_type,\n data: parsed.data,\n };\n }\n let parsedUrl: URL;\n\n try {\n parsedUrl = new URL(imageUrl);\n } catch {\n throw new Error(\n [\n `Malformed image URL: ${JSON.stringify(\n imageUrl\n )}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,\n \"Example: data:image/png;base64,/9j/4AAQSk...\",\n \"Example: https://example.com/image.jpg\",\n ].join(\"\\n\\n\")\n );\n }\n\n if (parsedUrl.protocol === \"http:\" || parsedUrl.protocol === \"https:\") {\n return {\n type: \"url\",\n url: imageUrl,\n };\n }\n\n throw new Error(\n [\n `Invalid image URL protocol: ${JSON.stringify(\n parsedUrl.protocol\n )}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,\n \"Example: data:image/png;base64,/9j/4AAQSk...\",\n \"Example: https://example.com/image.jpg\",\n ].join(\"\\n\\n\")\n );\n}\n\nfunction _ensureMessageContents(messages: BaseMessage[]): BaseMessage[] {\n // Merge runs of human/tool messages into single human messages with content blocks.\n const updatedMsgs = [];\n for (const message of messages) {\n if (message._getType() === \"tool\") {\n if (typeof message.content === \"string\") {\n const previousMessage = updatedMsgs[updatedMsgs.length - 1];\n if (\n previousMessage?._getType() === \"human\" &&\n Array.isArray(previousMessage.content) &&\n \"type\" in previousMessage.content[0] &&\n previousMessage.content[0].type === \"tool_result\"\n ) {\n // If the previous message was a tool result, we merge this tool message into it.\n (previousMessage.content as MessageContentComplex[]).push({\n type: \"tool_result\",\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n });\n } else {\n // If not, we create a new human message with the tool result.\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: \"tool_result\",\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: \"tool_result\",\n // rare case: message.content could be undefined\n ...(message.content != null\n ? { content: _formatContent(message) }\n : {}),\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(message);\n }\n }\n return updatedMsgs;\n}\n\nexport function _convertLangChainToolCallToAnthropic(\n toolCall: ToolCall\n): AnthropicToolResponse {\n if (toolCall.id === undefined) {\n throw new Error(`Anthropic requires all tool calls to have an \"id\".`);\n }\n return {\n type: \"tool_use\",\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args,\n };\n}\n\nfunction* _formatContentBlocks(\n content: ContentBlock[],\n toolCalls?: ToolCall[]\n): Generator<Anthropic.Beta.BetaContentBlockParam> {\n const toolTypes = [\n \"bash_code_execution_tool_result\",\n \"input_json_delta\",\n \"server_tool_use\",\n \"text_editor_code_execution_tool_result\",\n \"tool_result\",\n \"tool_use\",\n \"web_search_result\",\n \"web_search_tool_result\",\n ];\n const textTypes = [\"text\", \"text_delta\"];\n for (const contentPart of content) {\n if (isDataContentBlock(contentPart)) {\n yield convertToProviderContentBlock(\n contentPart,\n standardContentBlockConverter\n );\n }\n\n const cacheControl =\n \"cache_control\" in contentPart ? contentPart.cache_control : undefined;\n\n if (contentPart.type === \"image_url\") {\n let source;\n if (typeof contentPart.image_url === \"string\") {\n source = _formatImage(contentPart.image_url);\n } else if (\n typeof contentPart.image_url === \"object\" &&\n contentPart.image_url !== null &&\n \"url\" in contentPart.image_url &&\n typeof contentPart.image_url.url === \"string\"\n ) {\n source = _formatImage(contentPart.image_url.url);\n }\n if (source) {\n yield {\n type: \"image\" as const, // Explicitly setting the type as \"image\"\n source,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n } as Anthropic.Messages.ImageBlockParam;\n }\n } else if (_isAnthropicImageBlockParam(contentPart)) {\n yield contentPart;\n } else if (contentPart.type === \"image\") {\n // Handle new ContentBlock.Multimodal.Image format\n let source;\n\n if (\"url\" in contentPart && typeof contentPart.url === \"string\") {\n // URL-based image\n source = _formatImage(contentPart.url);\n } else if (\n \"data\" in contentPart &&\n (typeof contentPart.data === \"string\" ||\n // eslint-disable-next-line no-instanceof/no-instanceof\n contentPart.data instanceof Uint8Array)\n ) {\n // Base64-based image\n const mimeType =\n \"mimeType\" in contentPart && typeof contentPart.mimeType === \"string\"\n ? contentPart.mimeType\n : \"image/jpeg\";\n const data =\n typeof contentPart.data === \"string\"\n ? contentPart.data\n : Buffer.from(contentPart.data).toString(\"base64\");\n source = {\n type: \"base64\" as const,\n media_type: mimeType as\n | \"image/jpeg\"\n | \"image/png\"\n | \"image/gif\"\n | \"image/webp\",\n data,\n };\n } else if (\n \"fileId\" in contentPart &&\n typeof contentPart.fileId === \"string\"\n ) {\n // File ID-based image\n // Note: Anthropic supports file IDs for images that have been uploaded\n // to their servers via the Files API\n source = {\n type: \"file\" as const,\n file_id: contentPart.fileId,\n };\n }\n\n if (source) {\n yield {\n type: \"image\" as const,\n source,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n } as Anthropic.Messages.ImageBlockParam;\n }\n } else if (contentPart.type === \"document\") {\n // PDF\n yield {\n ...contentPart,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n } as Anthropic.Messages.DocumentBlockParam;\n } else if (_isAnthropicThinkingBlock(contentPart)) {\n const block: AnthropicThinkingBlockParam = {\n type: \"thinking\" as const, // Explicitly setting the type as \"thinking\"\n thinking: contentPart.thinking,\n signature: contentPart.signature,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n yield block;\n } else if (_isAnthropicRedactedThinkingBlock(contentPart)) {\n const block: AnthropicRedactedThinkingBlockParam = {\n type: \"redacted_thinking\" as const, // Explicitly setting the type as \"redacted_thinking\"\n data: contentPart.data,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n yield block;\n } else if (_isAnthropicSearchResultBlock(contentPart)) {\n const block: AnthropicSearchResultBlockParam = {\n type: \"search_result\" as const, // Explicitly setting the type as \"search_result\"\n title: contentPart.title,\n source: contentPart.source,\n ...(\"cache_control\" in contentPart && contentPart.cache_control\n ? { cache_control: contentPart.cache_control }\n : {}),\n ...(\"citations\" in contentPart && contentPart.citations\n ? { citations: contentPart.citations }\n : {}),\n content: contentPart.content,\n };\n yield block as Anthropic.Beta.BetaSearchResultBlockParam;\n } else if (\n textTypes.find((t) => t === contentPart.type) &&\n \"text\" in contentPart\n ) {\n // Assuming contentPart is of type MessageContentText here\n yield {\n type: \"text\" as const, // Explicitly setting the type as \"text\"\n text: contentPart.text,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n ...(\"citations\" in contentPart && contentPart.citations\n ? { citations: contentPart.citations }\n : {}),\n } as Anthropic.Messages.TextBlockParam;\n } else if (toolTypes.find((t) => t === contentPart.type)) {\n const contentPartCopy = { ...contentPart };\n\n if (contentPartCopy.type === \"input_json_delta\") {\n // `input_json_delta` type only represents yielding partial tool inputs\n // and is not a valid type for Anthropic messages.\n // These blocks appear in streaming responses and should be skipped\n // as their input data is already captured in tool_calls.\n continue;\n }\n\n if (\n contentPartCopy.type === \"tool_use\" &&\n typeof contentPartCopy.input === \"string\"\n ) {\n // First, try to get the input from the corresponding tool_call.\n // This is the most reliable source since tool_calls are properly\n // consolidated from tool_call_chunks during streaming.\n const matchingToolCall = toolCalls?.find(\n (tc) => tc.id === contentPartCopy.id\n );\n if (matchingToolCall) {\n contentPartCopy.input = matchingToolCall.args;\n } else {\n // Fallback: `tool_use` content part may be followed by `input_json_delta`\n // content parts which are chunks of a stringified JSON input,\n // so we need to collect them and merge their inputs.\n const inputDeltas = content.filter(\n (nestedContentPart) =>\n nestedContentPart.index === contentPartCopy.index &&\n nestedContentPart.type === \"input_json_delta\" &&\n typeof nestedContentPart.input === \"string\"\n );\n // If no `input_json_delta` parts are found, this line will just\n // return `contentPartCopy.input`, so no additional check is needed\n contentPartCopy.input = inputDeltas.reduce(\n (accumulator, nestedContentPart) =>\n accumulator + nestedContentPart.input,\n contentPartCopy.input\n );\n }\n }\n\n if (\"index\" in contentPartCopy) {\n // Anthropic does not support passing the index field here, so we remove it.\n delete contentPartCopy.index;\n }\n\n if (\"input\" in contentPartCopy) {\n // Anthropic tool use inputs should be valid objects, when applicable.\n if (typeof contentPartCopy.input === \"string\") {\n try {\n contentPartCopy.input = JSON.parse(contentPartCopy.input);\n } catch {\n contentPartCopy.input = {};\n }\n }\n }\n // TODO: Fix when SDK types are fixed\n yield {\n ...contentPartCopy,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n } else if (contentPart.type === \"container_upload\") {\n yield {\n ...contentPart,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n } as AnthropicContainerUploadBlockParam;\n }\n\n // Note that we are intentionally dropping any blocks that we don't\n // recognize. This is to allow for cross-compatibility between different\n // providers that may have different block types. Ie if we take a message\n // output from OpenAI and send it to Anthropic, we want to drop any blocks\n // that Anthropic doesn't understand.\n }\n}\n\nfunction _formatContent(message: BaseMessage, toolCalls?: ToolCall[]) {\n const { content } = message;\n\n if (typeof content === \"string\") {\n return content;\n } else {\n return Array.from(_formatContentBlocks(content, toolCalls));\n }\n}\n\n/**\n * Formats messages as a prompt for the model.\n * Used in LangSmith, export is important here.\n * @param messages The base messages to format as a prompt.\n * @returns The formatted prompt.\n */\nexport function _convertMessagesToAnthropicPayload(\n messages: BaseMessage[]\n): AnthropicMessageCreateParams {\n const mergedMessages = _ensureMessageContents(messages);\n let system;\n if (mergedMessages.length > 0 && mergedMessages[0]._getType() === \"system\") {\n system = messages[0].content;\n }\n const conversationMessages =\n system !== undefined ? mergedMessages.slice(1) : mergedMessages;\n const formattedMessages = conversationMessages.map((message) => {\n let role;\n if (message._getType() === \"human\") {\n role = \"user\" as const;\n } else if (message._getType() === \"ai\") {\n role = \"assistant\" as const;\n } else if (message._getType() === \"tool\") {\n role = \"user\" as const;\n } else if (message._getType() === \"system\") {\n throw new Error(\n \"System messages are only permitted as the first passed message.\"\n );\n } else {\n throw new Error(`Message type \"${message.type}\" is not supported.`);\n }\n if (\n AIMessage.isInstance(message) &&\n message.response_metadata?.output_version === \"v1\"\n ) {\n return {\n role,\n content: _formatStandardContent(message),\n };\n }\n if (AIMessage.isInstance(message) && !!message.tool_calls?.length) {\n if (typeof message.content === \"string\") {\n if (message.content === \"\") {\n return {\n role,\n content: message.tool_calls.map(\n _convertLangChainToolCallToAnthropic\n ),\n };\n } else {\n return {\n role,\n content: [\n { type: \"text\", text: message.content },\n ...message.tool_calls.map(_convertLangChainToolCallToAnthropic),\n ],\n };\n }\n } else {\n const { content } = message;\n const hasMismatchedToolCalls = !message.tool_calls.every((toolCall) =>\n content.find(\n (contentPart) =>\n (contentPart.type === \"tool_use\" ||\n contentPart.type === \"input_json_delta\" ||\n contentPart.type === \"server_tool_use\") &&\n contentPart.id === toolCall.id\n )\n );\n if (hasMismatchedToolCalls) {\n console.warn(\n `The \"tool_calls\" field on a message is only respected if content is a string.`\n );\n }\n return {\n role,\n content: _formatContent(message, message.tool_calls),\n };\n }\n } else {\n return {\n role,\n content: _formatContent(\n message,\n AIMessage.isInstance(message) ? message.tool_calls : undefined\n ),\n };\n }\n });\n return {\n messages: mergeMessages(\n formattedMessages as AnthropicMessageCreateParams[\"messages\"]\n ),\n system,\n } as AnthropicMessageCreateParams;\n}\n\n/**\n * Cache control configuration for Anthropic prompt caching.\n */\ninterface CacheControl {\n type: \"ephemeral\";\n ttl?: \"5m\" | \"1h\";\n}\n\n/**\n * Applies cache_control to the last content block of the last message in the payload.\n * This is the recommended approach for prompt caching as it applies the cache_control\n * at the final formatting layer, after all message processing is complete.\n *\n * This matches the Python langchain-anthropic implementation where cache_control\n * is applied via model_settings rather than modifying message content blocks directly.\n *\n * @param payload - The formatted Anthropic message payload\n * @param cacheControl - The cache control configuration to apply\n * @returns The payload with cache_control applied to the last content block\n */\nexport function applyCacheControlToPayload(\n payload: AnthropicMessageCreateParams,\n cacheControl: CacheControl\n): AnthropicMessageCreateParams {\n if (!payload.messages || payload.messages.length === 0) {\n return payload;\n }\n\n const messages = [...payload.messages];\n const lastMessageIndex = messages.length - 1;\n const lastMessage = messages[lastMessageIndex];\n\n if (!lastMessage) {\n return payload;\n }\n\n // Handle string content - convert to text block with cache_control\n if (typeof lastMessage.content === \"string\") {\n messages[lastMessageIndex] = {\n ...lastMessage,\n content: [\n {\n type: \"text\",\n text: lastMessage.content,\n cache_control: cacheControl,\n },\n ],\n };\n return { ...payload, messages };\n }\n\n // Handle array content - add cache_control to the last block\n if (Array.isArray(lastMessage.content) && lastMessage.content.length > 0) {\n const content = [...lastMessage.content];\n const lastBlockIndex = content.length - 1;\n const lastBlock = content[lastBlockIndex];\n\n // Add cache_control to the last block\n content[lastBlockIndex] = {\n ...lastBlock,\n cache_control: cacheControl,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n\n messages[lastMessageIndex] = {\n ...lastMessage,\n content,\n };\n return { ...payload, messages };\n }\n\n return payload;\n}\n\nfunction mergeMessages(messages: AnthropicMessageCreateParams[\"messages\"]) {\n if (!messages || messages.length <= 1) {\n return messages;\n }\n\n const result: AnthropicMessageCreateParams[\"messages\"] = [];\n let currentMessage = messages[0];\n\n const normalizeContent = (\n content:\n | string\n | Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\n | AnthropicSearchResultBlockParam\n >\n ): Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\n | AnthropicSearchResultBlockParam\n > => {\n if (typeof content === \"string\") {\n return [\n {\n type: \"text\",\n text: content,\n },\n ];\n }\n return content;\n };\n\n const isToolResultMessage = (msg: (typeof messages)[0]) => {\n if (msg.role !== \"user\") return false;\n\n if (typeof msg.content === \"string\") {\n return false;\n }\n\n return (\n Array.isArray(msg.content) &&\n msg.content.every((item) => item.type === \"tool_result\")\n );\n };\n\n for (let i = 1; i < messages.length; i += 1) {\n const nextMessage = messages[i];\n\n if (\n isToolResultMessage(currentMessage) &&\n isToolResultMessage(nextMessage)\n ) {\n // Merge the messages by combining their content arrays\n currentMessage = {\n ...currentMessage,\n content: [\n ...normalizeContent(currentMessage.content),\n ...normalizeContent(nextMessage.content),\n ],\n };\n } else {\n result.push(currentMessage);\n currentMessage = nextMessage;\n }\n }\n\n result.push(currentMessage);\n return result;\n}\n"],"mappings":";;;;;AAwCA,SAAS,aAAaA,UAAkB;CACtC,MAAM,SAAS,mBAAmB,EAAE,SAAS,SAAU,EAAC;AACxD,KAAI,OACF,QAAO;EACL,MAAM;EACN,YAAY,OAAO;EACnB,MAAM,OAAO;CACd;CAEH,IAAIC;AAEJ,KAAI;EACF,YAAY,IAAI,IAAI;CACrB,QAAO;AACN,QAAM,IAAI,MACR;GACE,CAAC,qBAAqB,EAAE,KAAK,UAC3B,SACD,CAAC,6FAA6F,CAAC;GAChG;GACA;EACD,EAAC,KAAK,OAAO;CAEjB;AAED,KAAI,UAAU,aAAa,WAAW,UAAU,aAAa,SAC3D,QAAO;EACL,MAAM;EACN,KAAK;CACN;AAGH,OAAM,IAAI,MACR;EACE,CAAC,4BAA4B,EAA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;EACxC,MAAM,YAAY,QAAQ;EAG1B,QAAQ,kBAAkB;GACxB,GAAG;GACH,eAAe;EAEhB;EAED,SAAS,oBAAoB;GAC3B,GAAG;GACH;EACD;AACD,SAAO;GAAE,GAAG;GAAS;EAAU;CAChC;AAED,QAAO;AACR;AAED,SAAS,cAAcC,UAAoD;AACzE,KAAI,CAAC,YAAY,SAAS,UAAU,EAClC,QAAO;CAGT,MAAMC,SAAmD,CAAE;CAC3D,IAAI,iBAAiB,SAAS;CAE9B,MAAM,mBAAmB,CACvBC,YAyBG;AACH,MAAI,OAAO,YAAY,SACrB,QAAO,CACL;GACE,MAAM;GACN,MAAM;EACP,CACF;AAEH,SAAO;CACR;CAED,MAAM,sBAAsB,CAACC,QAA8B;AACzD,MAAI,IAAI,SAAS,OAAQ,QAAO;AAEhC,MAAI,OAAO,IAAI,YAAY,SACzB,QAAO;AAGT,SACE,MAAM,QAAQ,IAAI,QAAQ,IAC1B,IAAI,QAAQ,MAAM,CAAC,SAAS,KAAK,SAAS,cAAc;CAE3D;AAED,MAAK,IAAI,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK,GAAG;EAC3C,MAAM,cAAc,SAAS;AAE7B,MACE,oBAAoB,eAAe,IACnC,oBAAoB,YAAY,EAGhC,iBAAiB;GACf,GAAG;GACH,SAAS,CACP,GAAG,iBAAiB,eAAe,QAAQ,EAC3C,GAAG,iBAAiB,YAAY,QAAQ,AACzC;EACF;OACI;GACL,OAAO,KAAK,eAAe;GAC3B,iBAAiB;EAClB;CACF;CAED,OAAO,KAAK,eAAe;AAC3B,QAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"message_inputs.js","names":["imageUrl: string","parsedUrl: URL","messages: BaseMessage[]","toolCall: ToolCall","content: ContentBlock[]","toolCalls?: ToolCall[]","source:\n | { type: \"url\"; url: string }\n | { type: \"base64\"; media_type: string; data: string }\n | { type: \"file\"; file_id: string }\n | undefined","block: AnthropicThinkingBlockParam","block: AnthropicRedactedThinkingBlockParam","block: AnthropicSearchResultBlockParam","message: BaseMessage","payload: AnthropicMessageCreateParams","cacheControl: CacheControl","messages: AnthropicMessageCreateParams[\"messages\"]","result: AnthropicMessageCreateParams[\"messages\"]","content:\n | string\n | Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\n | AnthropicSearchResultBlockParam\n >","msg: (typeof messages)[0]"],"sources":["../../src/utils/message_inputs.ts"],"sourcesContent":["/**\n * This util file contains functions for converting LangChain messages to Anthropic messages.\n */\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport {\n type BaseMessage,\n HumanMessage,\n ToolMessage,\n MessageContentComplex,\n isDataContentBlock,\n convertToProviderContentBlock,\n parseBase64DataUrl,\n ContentBlock,\n AIMessage,\n} from \"@langchain/core/messages\";\nimport { ToolCall } from \"@langchain/core/messages/tool\";\nimport {\n AnthropicImageBlockParam,\n AnthropicMessageCreateParams,\n AnthropicTextBlockParam,\n AnthropicToolResultBlockParam,\n AnthropicToolUseBlockParam,\n AnthropicDocumentBlockParam,\n AnthropicThinkingBlockParam,\n AnthropicRedactedThinkingBlockParam,\n AnthropicServerToolUseBlockParam,\n AnthropicWebSearchToolResultBlockParam,\n AnthropicSearchResultBlockParam,\n AnthropicToolResponse,\n AnthropicContainerUploadBlockParam,\n} from \"../types.js\";\nimport {\n _isAnthropicImageBlockParam,\n _isAnthropicRedactedThinkingBlock,\n _isAnthropicSearchResultBlock,\n _isAnthropicThinkingBlock,\n standardContentBlockConverter,\n} from \"./content.js\";\nimport { _formatStandardContent } from \"./standard.js\";\n\nfunction _formatImage(imageUrl: string) {\n const parsed = parseBase64DataUrl({ dataUrl: imageUrl });\n if (parsed) {\n return {\n type: \"base64\",\n media_type: parsed.mime_type,\n data: parsed.data,\n };\n }\n let parsedUrl: URL;\n\n try {\n parsedUrl = new URL(imageUrl);\n } catch {\n throw new Error(\n [\n `Malformed image URL: ${JSON.stringify(\n imageUrl\n )}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,\n \"Example: data:image/png;base64,/9j/4AAQSk...\",\n \"Example: https://example.com/image.jpg\",\n ].join(\"\\n\\n\")\n );\n }\n\n if (parsedUrl.protocol === \"http:\" || parsedUrl.protocol === \"https:\") {\n return {\n type: \"url\",\n url: imageUrl,\n };\n }\n\n throw new Error(\n [\n `Invalid image URL protocol: ${JSON.stringify(\n parsedUrl.protocol\n )}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,\n \"Example: data:image/png;base64,/9j/4AAQSk...\",\n \"Example: https://example.com/image.jpg\",\n ].join(\"\\n\\n\")\n );\n}\n\nfunction _ensureMessageContents(messages: BaseMessage[]): BaseMessage[] {\n // Merge runs of human/tool messages into single human messages with content blocks.\n const updatedMsgs = [];\n for (const message of messages) {\n if (message._getType() === \"tool\") {\n if (typeof message.content === \"string\") {\n const previousMessage = updatedMsgs[updatedMsgs.length - 1];\n if (\n previousMessage?._getType() === \"human\" &&\n Array.isArray(previousMessage.content) &&\n \"type\" in previousMessage.content[0] &&\n previousMessage.content[0].type === \"tool_result\"\n ) {\n // If the previous message was a tool result, we merge this tool message into it.\n (previousMessage.content as MessageContentComplex[]).push({\n type: \"tool_result\",\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n });\n } else {\n // If not, we create a new human message with the tool result.\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: \"tool_result\",\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: \"tool_result\",\n // rare case: message.content could be undefined\n ...(message.content != null\n ? { content: _formatContent(message) }\n : {}),\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(message);\n }\n }\n return updatedMsgs;\n}\n\nexport function _convertLangChainToolCallToAnthropic(\n toolCall: ToolCall\n): AnthropicToolResponse {\n if (toolCall.id === undefined) {\n throw new Error(`Anthropic requires all tool calls to have an \"id\".`);\n }\n return {\n type: \"tool_use\",\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args,\n };\n}\n\nfunction* _formatContentBlocks(\n content: ContentBlock[],\n toolCalls?: ToolCall[]\n): Generator<Anthropic.Beta.BetaContentBlockParam> {\n const toolTypes = [\n \"bash_code_execution_tool_result\",\n \"input_json_delta\",\n \"server_tool_use\",\n \"text_editor_code_execution_tool_result\",\n \"tool_result\",\n \"tool_use\",\n \"web_search_result\",\n \"web_search_tool_result\",\n ];\n const textTypes = [\"text\", \"text_delta\"];\n for (const contentPart of content) {\n if (isDataContentBlock(contentPart)) {\n yield convertToProviderContentBlock(\n contentPart,\n standardContentBlockConverter\n );\n }\n\n const cacheControl =\n \"cache_control\" in contentPart ? contentPart.cache_control : undefined;\n\n if (contentPart.type === \"image_url\") {\n let source;\n if (typeof contentPart.image_url === \"string\") {\n source = _formatImage(contentPart.image_url);\n } else if (\n typeof contentPart.image_url === \"object\" &&\n contentPart.image_url !== null &&\n \"url\" in contentPart.image_url &&\n typeof contentPart.image_url.url === \"string\"\n ) {\n source = _formatImage(contentPart.image_url.url);\n }\n if (source) {\n yield {\n type: \"image\" as const, // Explicitly setting the type as \"image\"\n source,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n } as Anthropic.Messages.ImageBlockParam;\n }\n } else if (_isAnthropicImageBlockParam(contentPart)) {\n yield contentPart;\n } else if (contentPart.type === \"image\") {\n // Handle new ContentBlock.Multimodal.Image format\n let source;\n\n if (\"url\" in contentPart && typeof contentPart.url === \"string\") {\n // URL-based image\n source = _formatImage(contentPart.url);\n } else if (\n \"data\" in contentPart &&\n (typeof contentPart.data === \"string\" ||\n // eslint-disable-next-line no-instanceof/no-instanceof\n contentPart.data instanceof Uint8Array)\n ) {\n // Base64-based image\n const mimeType =\n \"mimeType\" in contentPart && typeof contentPart.mimeType === \"string\"\n ? contentPart.mimeType\n : \"image/jpeg\";\n const data =\n typeof contentPart.data === \"string\"\n ? contentPart.data\n : Buffer.from(contentPart.data).toString(\"base64\");\n source = {\n type: \"base64\" as const,\n media_type: mimeType as\n | \"image/jpeg\"\n | \"image/png\"\n | \"image/gif\"\n | \"image/webp\",\n data,\n };\n } else if (\n \"fileId\" in contentPart &&\n typeof contentPart.fileId === \"string\"\n ) {\n // File ID-based image\n // Note: Anthropic supports file IDs for images that have been uploaded\n // to their servers via the Files API\n source = {\n type: \"file\" as const,\n file_id: contentPart.fileId,\n };\n }\n\n if (source) {\n yield {\n type: \"image\" as const,\n source,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n } as Anthropic.Messages.ImageBlockParam;\n }\n } else if (contentPart.type === \"file\") {\n // Handle new ContentBlock.Multimodal.File format\n let source:\n | { type: \"url\"; url: string }\n | { type: \"base64\"; media_type: string; data: string }\n | { type: \"file\"; file_id: string }\n | undefined;\n\n if (\"url\" in contentPart && typeof contentPart.url === \"string\") {\n // File with URL\n source = {\n type: \"url\" as const,\n url: contentPart.url,\n };\n } else if (\n \"data\" in contentPart &&\n (typeof contentPart.data === \"string\" ||\n // eslint-disable-next-line no-instanceof/no-instanceof\n contentPart.data instanceof Uint8Array)\n ) {\n // File with base64 data (string or Uint8Array)\n const media_type =\n \"mimeType\" in contentPart && typeof contentPart.mimeType === \"string\"\n ? contentPart.mimeType\n : \"application/pdf\";\n const data =\n typeof contentPart.data === \"string\"\n ? contentPart.data\n : Buffer.from(contentPart.data).toString(\"base64\");\n\n source = {\n type: \"base64\" as const,\n media_type,\n data,\n };\n } else if (\n \"fileId\" in contentPart &&\n typeof contentPart.fileId === \"string\"\n ) {\n // File ID from Anthropic Files API\n // https://platform.claude.com/docs/en/build-with-claude/pdf-support#option-3-files-api\n source = {\n type: \"file\" as const,\n file_id: contentPart.fileId,\n };\n }\n\n if (source) {\n yield {\n type: \"document\" as const,\n source,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n } as Anthropic.Messages.DocumentBlockParam;\n }\n } else if (contentPart.type === \"document\") {\n // PDF\n yield {\n ...contentPart,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n } as Anthropic.Messages.DocumentBlockParam;\n } else if (_isAnthropicThinkingBlock(contentPart)) {\n const block: AnthropicThinkingBlockParam = {\n type: \"thinking\" as const, // Explicitly setting the type as \"thinking\"\n thinking: contentPart.thinking,\n signature: contentPart.signature,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n yield block;\n } else if (_isAnthropicRedactedThinkingBlock(contentPart)) {\n const block: AnthropicRedactedThinkingBlockParam = {\n type: \"redacted_thinking\" as const, // Explicitly setting the type as \"redacted_thinking\"\n data: contentPart.data,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n yield block;\n } else if (_isAnthropicSearchResultBlock(contentPart)) {\n const block: AnthropicSearchResultBlockParam = {\n type: \"search_result\" as const, // Explicitly setting the type as \"search_result\"\n title: contentPart.title,\n source: contentPart.source,\n ...(\"cache_control\" in contentPart && contentPart.cache_control\n ? { cache_control: contentPart.cache_control }\n : {}),\n ...(\"citations\" in contentPart && contentPart.citations\n ? { citations: contentPart.citations }\n : {}),\n content: contentPart.content,\n };\n yield block as Anthropic.Beta.BetaSearchResultBlockParam;\n } else if (\n textTypes.find((t) => t === contentPart.type) &&\n \"text\" in contentPart\n ) {\n // Assuming contentPart is of type MessageContentText here\n yield {\n type: \"text\" as const, // Explicitly setting the type as \"text\"\n text: contentPart.text,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n ...(\"citations\" in contentPart && contentPart.citations\n ? { citations: contentPart.citations }\n : {}),\n } as Anthropic.Messages.TextBlockParam;\n } else if (toolTypes.find((t) => t === contentPart.type)) {\n const contentPartCopy = { ...contentPart };\n\n if (contentPartCopy.type === \"input_json_delta\") {\n // `input_json_delta` type only represents yielding partial tool inputs\n // and is not a valid type for Anthropic messages.\n // These blocks appear in streaming responses and should be skipped\n // as their input data is already captured in tool_calls.\n continue;\n }\n\n if (\n contentPartCopy.type === \"tool_use\" &&\n typeof contentPartCopy.input === \"string\"\n ) {\n // First, try to get the input from the corresponding tool_call.\n // This is the most reliable source since tool_calls are properly\n // consolidated from tool_call_chunks during streaming.\n const matchingToolCall = toolCalls?.find(\n (tc) => tc.id === contentPartCopy.id\n );\n if (matchingToolCall) {\n contentPartCopy.input = matchingToolCall.args;\n } else {\n // Fallback: `tool_use` content part may be followed by `input_json_delta`\n // content parts which are chunks of a stringified JSON input,\n // so we need to collect them and merge their inputs.\n const inputDeltas = content.filter(\n (nestedContentPart) =>\n nestedContentPart.index === contentPartCopy.index &&\n nestedContentPart.type === \"input_json_delta\" &&\n typeof nestedContentPart.input === \"string\"\n );\n // If no `input_json_delta` parts are found, this line will just\n // return `contentPartCopy.input`, so no additional check is needed\n contentPartCopy.input = inputDeltas.reduce(\n (accumulator, nestedContentPart) =>\n accumulator + nestedContentPart.input,\n contentPartCopy.input\n );\n }\n }\n\n if (\"index\" in contentPartCopy) {\n // Anthropic does not support passing the index field here, so we remove it.\n delete contentPartCopy.index;\n }\n\n if (\"input\" in contentPartCopy) {\n // Anthropic tool use inputs should be valid objects, when applicable.\n if (typeof contentPartCopy.input === \"string\") {\n try {\n contentPartCopy.input = JSON.parse(contentPartCopy.input);\n } catch {\n contentPartCopy.input = {};\n }\n }\n }\n // TODO: Fix when SDK types are fixed\n yield {\n ...contentPartCopy,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n } else if (contentPart.type === \"container_upload\") {\n yield {\n ...contentPart,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n } as AnthropicContainerUploadBlockParam;\n }\n\n // Note that we are intentionally dropping any blocks that we don't\n // recognize. This is to allow for cross-compatibility between different\n // providers that may have different block types. Ie if we take a message\n // output from OpenAI and send it to Anthropic, we want to drop any blocks\n // that Anthropic doesn't understand.\n }\n}\n\nfunction _formatContent(message: BaseMessage, toolCalls?: ToolCall[]) {\n const { content } = message;\n\n if (typeof content === \"string\") {\n return content;\n } else {\n return Array.from(_formatContentBlocks(content, toolCalls));\n }\n}\n\n/**\n * Formats messages as a prompt for the model.\n * Used in LangSmith, export is important here.\n * @param messages The base messages to format as a prompt.\n * @returns The formatted prompt.\n */\nexport function _convertMessagesToAnthropicPayload(\n messages: BaseMessage[]\n): AnthropicMessageCreateParams {\n const mergedMessages = _ensureMessageContents(messages);\n let system;\n if (mergedMessages.length > 0 && mergedMessages[0]._getType() === \"system\") {\n system = messages[0].content;\n }\n const conversationMessages =\n system !== undefined ? mergedMessages.slice(1) : mergedMessages;\n const formattedMessages = conversationMessages.map((message) => {\n let role;\n if (message._getType() === \"human\") {\n role = \"user\" as const;\n } else if (message._getType() === \"ai\") {\n role = \"assistant\" as const;\n } else if (message._getType() === \"tool\") {\n role = \"user\" as const;\n } else if (message._getType() === \"system\") {\n throw new Error(\n \"System messages are only permitted as the first passed message.\"\n );\n } else {\n throw new Error(`Message type \"${message.type}\" is not supported.`);\n }\n if (\n AIMessage.isInstance(message) &&\n message.response_metadata?.output_version === \"v1\"\n ) {\n return {\n role,\n content: _formatStandardContent(message),\n };\n }\n if (AIMessage.isInstance(message) && !!message.tool_calls?.length) {\n if (typeof message.content === \"string\") {\n if (message.content === \"\") {\n return {\n role,\n content: message.tool_calls.map(\n _convertLangChainToolCallToAnthropic\n ),\n };\n } else {\n return {\n role,\n content: [\n { type: \"text\", text: message.content },\n ...message.tool_calls.map(_convertLangChainToolCallToAnthropic),\n ],\n };\n }\n } else {\n const { content } = message;\n const hasMismatchedToolCalls = !message.tool_calls.every((toolCall) =>\n content.find(\n (contentPart) =>\n (contentPart.type === \"tool_use\" ||\n contentPart.type === \"input_json_delta\" ||\n contentPart.type === \"server_tool_use\") &&\n contentPart.id === toolCall.id\n )\n );\n if (hasMismatchedToolCalls) {\n console.warn(\n `The \"tool_calls\" field on a message is only respected if content is a string.`\n );\n }\n return {\n role,\n content: _formatContent(message, message.tool_calls),\n };\n }\n } else {\n return {\n role,\n content: _formatContent(\n message,\n AIMessage.isInstance(message) ? message.tool_calls : undefined\n ),\n };\n }\n });\n return {\n messages: mergeMessages(\n formattedMessages as AnthropicMessageCreateParams[\"messages\"]\n ),\n system,\n } as AnthropicMessageCreateParams;\n}\n\n/**\n * Cache control configuration for Anthropic prompt caching.\n */\ninterface CacheControl {\n type: \"ephemeral\";\n ttl?: \"5m\" | \"1h\";\n}\n\n/**\n * Applies cache_control to the last content block of the last message in the payload.\n * This is the recommended approach for prompt caching as it applies the cache_control\n * at the final formatting layer, after all message processing is complete.\n *\n * This matches the Python langchain-anthropic implementation where cache_control\n * is applied via model_settings rather than modifying message content blocks directly.\n *\n * @param payload - The formatted Anthropic message payload\n * @param cacheControl - The cache control configuration to apply\n * @returns The payload with cache_control applied to the last content block\n */\nexport function applyCacheControlToPayload(\n payload: AnthropicMessageCreateParams,\n cacheControl: CacheControl\n): AnthropicMessageCreateParams {\n if (!payload.messages || payload.messages.length === 0) {\n return payload;\n }\n\n const messages = [...payload.messages];\n const lastMessageIndex = messages.length - 1;\n const lastMessage = messages[lastMessageIndex];\n\n if (!lastMessage) {\n return payload;\n }\n\n // Handle string content - convert to text block with cache_control\n if (typeof lastMessage.content === \"string\") {\n messages[lastMessageIndex] = {\n ...lastMessage,\n content: [\n {\n type: \"text\",\n text: lastMessage.content,\n cache_control: cacheControl,\n },\n ],\n };\n return { ...payload, messages };\n }\n\n // Handle array content - add cache_control to the last block\n if (Array.isArray(lastMessage.content) && lastMessage.content.length > 0) {\n const content = [...lastMessage.content];\n const lastBlockIndex = content.length - 1;\n const lastBlock = content[lastBlockIndex];\n\n // Add cache_control to the last block\n content[lastBlockIndex] = {\n ...lastBlock,\n cache_control: cacheControl,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n\n messages[lastMessageIndex] = {\n ...lastMessage,\n content,\n };\n return { ...payload, messages };\n }\n\n return payload;\n}\n\nfunction mergeMessages(messages: AnthropicMessageCreateParams[\"messages\"]) {\n if (!messages || messages.length <= 1) {\n return messages;\n }\n\n const result: AnthropicMessageCreateParams[\"messages\"] = [];\n let currentMessage = messages[0];\n\n const normalizeContent = (\n content:\n | string\n | Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\n | AnthropicSearchResultBlockParam\n >\n ): Array<\n | AnthropicTextBlockParam\n | AnthropicImageBlockParam\n | AnthropicToolUseBlockParam\n | AnthropicToolResultBlockParam\n | AnthropicDocumentBlockParam\n | AnthropicThinkingBlockParam\n | AnthropicRedactedThinkingBlockParam\n | AnthropicServerToolUseBlockParam\n | AnthropicWebSearchToolResultBlockParam\n | AnthropicSearchResultBlockParam\n > => {\n if (typeof content === \"string\") {\n return [\n {\n type: \"text\",\n text: content,\n },\n ];\n }\n return content;\n };\n\n const isToolResultMessage = (msg: (typeof messages)[0]) => {\n if (msg.role !== \"user\") return false;\n\n if (typeof msg.content === \"string\") {\n return false;\n }\n\n return (\n Array.isArray(msg.content) &&\n msg.content.every((item) => item.type === \"tool_result\")\n );\n };\n\n for (let i = 1; i < messages.length; i += 1) {\n const nextMessage = messages[i];\n\n if (\n isToolResultMessage(currentMessage) &&\n isToolResultMessage(nextMessage)\n ) {\n // Merge the messages by combining their content arrays\n currentMessage = {\n ...currentMessage,\n content: [\n ...normalizeContent(currentMessage.content),\n ...normalizeContent(nextMessage.content),\n ],\n };\n } else {\n result.push(currentMessage);\n currentMessage = nextMessage;\n }\n }\n\n result.push(currentMessage);\n return result;\n}\n"],"mappings":";;;;;AAwCA,SAAS,aAAaA,UAAkB;CACtC,MAAM,SAAS,mBAAmB,EAAE,SAAS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GT,MAAMC,SAAmD,CAAE;CAC3D,IAAI,iBAAiB,SAAS;CAE9B,MAAM,mBAAmB,CACvBC,YAyBG;AACH,MAAI,OAAO,YAAY,SACrB,QAAO,CACL;GACE,MAAM;GACN,MAAM;EACP,CACF;AAEH,SAAO;CACR;CAED,MAAM,sBAAsB,CAACC,QAA8B;AACzD,MAAI,IAAI,SAAS,OAAQ,QAAO;AAEhC,MAAI,OAAO,IAAI,YAAY,SACzB,QAAO;AAGT,SACE,MAAM,QAAQ,IAAI,QAAQ,IAC1B,IAAI,QAAQ,MAAM,CAAC,SAAS,KAAK,SAAS,cAAc;CAE3D;AAED,MAAK,IAAI,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK,GAAG;EAC3C,MAAM,cAAc,SAAS;AAE7B,MACE,oBAAoB,eAAe,IACnC,oBAAoB,YAAY,EAGhC,iBAAiB;GACf,GAAG;GACH,SAAS,CACP,GAAG,iBAAiB,eAAe,QAAQ,EAC3C,GAAG,iBAAiB,YAAY,QAAQ,AACzC;EACF;OACI;GACL,OAAO,KAAK,eAAe;GAC3B,iBAAiB;EAClB;CACF;CAED,OAAO,KAAK,eAAe;AAC3B,QAAO;AACR"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@langchain/anthropic",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.14",
|
|
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.19"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
24
|
"@anthropic-ai/vertex-sdk": "^0.11.5",
|
|
@@ -33,9 +33,9 @@
|
|
|
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.19",
|
|
37
37
|
"@langchain/eslint": "0.1.1",
|
|
38
|
-
"@langchain/standard-tests": "0.0.
|
|
38
|
+
"@langchain/standard-tests": "0.0.22",
|
|
39
39
|
"@langchain/tsconfig": "0.0.1"
|
|
40
40
|
},
|
|
41
41
|
"publishConfig": {
|