class ChatAnthropicMessagesBaseChatModel<CallOptions, AIMessageChunk>Anthropic chat model integration.
Setup:
Install @langchain/anthropic and set an environment variable named ANTHROPIC_API_KEY.
npm install @langchain/anthropic
export ANTHROPIC_API_KEY="your-api-key"
Runtime args can be passed as the second argument to any of the base runnable methods .invoke. .stream, .batch, etc.
They can also be passed via .bind, or the second arg in .bindTools, like shown in the examples below:
// When calling `.bind`, call options should be passed via the first argument
const llmWithArgsBound = llm.bindTools([...]).withConfig({
stop: ["\n"],
});
// When calling `.bindTools`, call options should be passed via the second argument
const llmWithTools = llm.bindTools(
[...],
{
tool_choice: "auto",
}
);
import { ChatAnthropic } from '@langchain/anthropic';
const llm = new ChatAnthropic({
model: "claude-sonnet-4-5-20250929",
temperature: 0,
maxTokens: undefined,
maxRetries: 2,
// apiKey: "...",
// baseUrl: "...",
// other params...
});
const input = `Translate "I love programming" into French.`;
// Models also accept a list of chat messages or a formatted prompt
const result = await llm.invoke(input);
console.log(result);
AIMessage {
"id": "msg_01QDpd78JUHpRP6bRRNyzbW3",
"content": "Here's the translation to French:\n\nJ'adore la programmation.",
"response_metadata": {
"id": "msg_01QDpd78JUHpRP6bRRNyzbW3",
"model": "claude-sonnet-4-5-20250929",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 25,
"output_tokens": 19
},
"type": "message",
"role": "assistant"
},
"usage_metadata": {
"input_tokens": 25,
"output_tokens": 19,
"total_tokens": 44
}
}
for await (const chunk of await llm.stream(input)) {
console.log(chunk);
}
AIMessageChunk {
"id": "msg_01N8MwoYxiKo9w4chE4gXUs4",
"content": "",
"additional_kwargs": {
"id": "msg_01N8MwoYxiKo9w4chE4gXUs4",
"type": "message",
"role": "assistant",
"model": "claude-sonnet-4-5-20250929"
},
"usage_metadata": {
"input_tokens": 25,
"output_tokens": 1,
"total_tokens": 26
}
}
AIMessageChunk {
"content": "",
}
AIMessageChunk {
"content": "Here",
}
AIMessageChunk {
"content": "'s",
}
AIMessageChunk {
"content": " the translation to",
}
AIMessageChunk {
"content": " French:\n\nJ",
}
AIMessageChunk {
"content": "'adore la programmation",
}
AIMessageChunk {
"content": ".",
}
AIMessageChunk {
"content": "",
"additional_kwargs": {
"stop_reason": "end_turn",
"stop_sequence": null
},
"usage_metadata": {
"input_tokens": 0,
"output_tokens": 19,
"total_tokens": 19
}
}
import { AIMessageChunk } from '@langchain/core/messages';
import { concat } from '@langchain/core/utils/stream';
const stream = await llm.stream(input);
let full: AIMessageChunk | undefined;
for await (const chunk of stream) {
full = !full ? chunk : concat(full, chunk);
}
console.log(full);
AIMessageChunk {
"id": "msg_01SBTb5zSGXfjUc7yQ8EKEEA",
"content": "Here's the translation to French:\n\nJ'adore la programmation.",
"additional_kwargs": {
"id": "msg_01SBTb5zSGXfjUc7yQ8EKEEA",
"type": "message",
"role": "assistant",
"model": "claude-sonnet-4-5-20250929",
"stop_reason": "end_turn",
"stop_sequence": null
},
"usage_metadata": {
"input_tokens": 25,
"output_tokens": 20,
"total_tokens": 45
}
}
import { z } from 'zod';
const GetWeather = {
name: "GetWeather",
description: "Get the current weather in a given location",
schema: z.object({
location: z.string().describe("The city and state, e.g. San Francisco, CA")
}),
}
const GetPopulation = {
name: "GetPopulation",
description: "Get the current population in a given location",
schema: z.object({
location: z.string().describe("The city and state, e.g. San Francisco, CA")
}),
}
const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);
const aiMsg = await llmWithTools.invoke(
"Which city is hotter today and which is bigger: LA or NY?"
);
console.log(aiMsg.tool_calls);
[
{
name: 'GetWeather',
args: { location: 'Los Angeles, CA' },
id: 'toolu_01WjW3Dann6BPJVtLhovdBD5',
type: 'tool_call'
},
{
name: 'GetWeather',
args: { location: 'New York, NY' },
id: 'toolu_01G6wfJgqi5zRmJomsmkyZXe',
type: 'tool_call'
},
{
name: 'GetPopulation',
args: { location: 'Los Angeles, CA' },
id: 'toolu_0165qYWBA2VFyUst5RA18zew',
type: 'tool_call'
},
{
name: 'GetPopulation',
args: { location: 'New York, NY' },
id: 'toolu_01PGNyP33vxr13tGqr7i3rDo',
type: 'tool_call'
}
]
Tool search enables Claude to dynamically discover and load tools on-demand instead of loading all tool definitions upfront. This is useful when you have many tools but want to avoid the overhead of sending all definitions with every request.
import { ChatAnthropic } from "@langchain/anthropic";
const model = new ChatAnthropic({
model: "claude-sonnet-4-5-20250929",
});
const tools = [
// Tool search server tool
{
type: "tool_search_tool_regex_20251119",
name: "tool_search_tool_regex",
},
// Tools with defer_loading are loaded on-demand
{
name: "get_weather",
description: "Get the current weather for a location",
input_schema: {
type: "object",
properties: {
location: { type: "string", description: "City name" },
unit: {
type: "string",
enum: ["celsius", "fahrenheit"],
},
},
required: ["location"],
},
defer_loading: true, // Tool is loaded on-demand
},
{
name: "search_files",
description: "Search through files in the workspace",
input_schema: {
type: "object",
properties: {
query: { type: "string" },
},
required: ["query"],
},
defer_loading: true, // Tool is loaded on-demand
},
];
const modelWithTools = model.bindTools(tools);
const response = await modelWithTools.invoke("What's the weather in San Francisco?");
You can also use the tool() helper with the extras field:
import { tool } from "@langchain/core/tools";
import { z } from "zod";
const getWeather = tool(
async (input) => `Weather in ${input.location}`,
{
name: "get_weather",
description: "Get weather for a location",
schema: z.object({ location: z.string() }),
extras: { defer_loading: true },
}
);
Note: The required advanced-tool-use-2025-11-20 beta header is automatically
appended to the request when using tool search tools.
Best practices:
defer_loading: true are only loaded when Claude discovers them via searchSee the Claude docs for more information.
ChatAnthropic supports structured output through two main approaches:
withStructuredOutput(): Uses Anthropic's tool calling
under the hood to constrain outputs to a specific schema.Using withStructuredOutput (Function Calling)
This method leverages Anthropic's tool calling capabilities to ensure the model returns data matching your schema:
import { z } from 'zod';
const Joke = z.object({
setup: z.string().describe("The setup of the joke"),
punchline: z.string().describe("The punchline to the joke"),
rating: z.number().optional().describe("How funny the joke is, from 1 to 10")
}).describe('Joke to tell user.');
const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" });
const jokeResult = await structuredLlm.invoke("Tell me a joke about cats");
console.log(jokeResult);
{
setup: "Why don't cats play poker in the jungle?",
punchline: 'Too many cheetahs!',
rating: 7
}
Using JSON Schema Mode
For more direct control, you can use Anthropic's native JSON schema support by
passing method: "jsonSchema":
import { z } from 'zod';
const RecipeSchema = z.object({
recipeName: z.string().describe("Name of the recipe"),
ingredients: z.array(z.string()).describe("List of ingredients needed"),
steps: z.array(z.string()).describe("Cooking steps in order"),
prepTime: z.number().describe("Preparation time in minutes")
});
const structuredLlm = llm.withStructuredOutput(RecipeSchema, {
method: "jsonSchema"
});
const recipe = await structuredLlm.invoke(
"Give me a simple recipe for chocolate chip cookies"
);
console.log(recipe);
{
recipeName: 'Classic Chocolate Chip Cookies',
ingredients: [
'2 1/4 cups all-purpose flour',
'1 cup butter, softened',
...
],
steps: [
'Preheat oven to 375°F',
'Mix butter and sugars until creamy',
...
],
prepTime: 15
}
import { HumanMessage } from '@langchain/core/messages';
const imageUrl = "https://example.com/image.jpg";
const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());
const base64Image = Buffer.from(imageData).toString('base64');
const message = new HumanMessage({
content: [
{ type: "text", text: "describe the weather in this image" },
{
type: "image_url",
image_url: { url: `data:image/jpeg;base64,${base64Image}` },
},
]
});
const imageDescriptionAiMsg = await llm.invoke([message]);
console.log(imageDescriptionAiMsg.content);
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.
const aiMsgForMetadata = await llm.invoke(input);
console.log(aiMsgForMetadata.usage_metadata);
{ input_tokens: 25, output_tokens: 19, total_tokens: 44 }
const streamForMetadata = await llm.stream(
input,
{
streamUsage: true
}
);
let fullForMetadata: AIMessageChunk | undefined;
for await (const chunk of streamForMetadata) {
fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk);
}
console.log(fullForMetadata?.usage_metadata);
{ input_tokens: 25, output_tokens: 20, total_tokens: 45 }
const aiMsgForResponseMetadata = await llm.invoke(input);
console.log(aiMsgForResponseMetadata.response_metadata);
{
id: 'msg_01STxeQxJmp4sCSpioD6vK3L',
model: 'claude-sonnet-4-5-20250929',
stop_reason: 'end_turn',
stop_sequence: null,
usage: { input_tokens: 25, output_tokens: 19 },
type: 'message',
role: 'assistant'
}
Anthropic API key
Anthropic API key
Optional array of beta features to enable for the Anthropic API. Beta features are experimental capabilities that may change or be removed. See https://docs.claude.com/en/api/beta-headers for available beta features.
The async caller should be used by subclasses to make any async calls, which will thus benefit from the concurrency and retry logic.
Overridable Anthropic ClientOptions
Configuration for context management. See https://docs.claude.com/en/docs/build-with-claude/context-editing
Optional method that returns an initialized underlying Anthropic client. Useful for accessing Anthropic models hosted on other cloud services such as Google Vertex.
Specifies the geographic region for inference processing. US-only inference is available at 1.1x pricing for models released after February 1, 2026.
Holds any additional parameters that are valid to pass to anthropic.messages that are not explicitly specified on this class.
A path to the module that contains the class, eg. ["langchain", "llms"] Usually should be the same as the entrypoint the class is exported from.
A maximum number of tokens to generate before stopping.
Model name to use
Configuration options for the model's output, such as effort level and output format. The effort parameter controls how many tokens Claude uses when responding, trading off between response thoroughness and token efficiency.
Effort levels: "low", "medium", "high" (default), "max" (Opus 4.6 only).
A list of strings upon which to stop generating.
You probably want ["\n\nHuman:"], as that's the cue for
the next turn in the dialog agent.
Whether to stream the results or not
Whether or not to include token usage data in streamed chunks.
Amount of randomness injected into the response. Ranges from 0 to 1. Use temperature closer to 0 for analytical / multiple choice, and temperature closer to 1 for creative and generative tasks.
Options for extended thinking.
Only sample from the top K options for each subsequent token. Used to remove "long tail" low probability responses.
Does nucleus sampling, in which we compute the cumulative distribution over all the options for each subsequent token in decreasing probability order and cut it off once it reaches a particular probability specified by top_p. Note that you should either alter temperature or top_p, but not both.
Whether to print out response text.
Internal method that handles batching and configuration for a runnable It takes a function, input values, and optional configuration, and returns a promise that resolves to the output values.
Create a unique cache key for a specific call to a specific language model.
Default streaming implementation. Subclasses should override this method if they support streaming output.
Helper method to transform an Iterator of Input values into an Iterator of
Output values, with callbacks.
Use this to implement stream() or transform() in Runnable subclasses.
Assigns new fields to the dict output of this runnable. Returns a new runnable.
Convert a runnable to a tool. Return a new instance of RunnableToolLike
which contains the runnable, name, description and schema.
Default implementation of batch, which calls invoke N times. Subclasses should override this method if they can batch more efficiently.
Bind tool-like objects to this chat model.
Creates a streaming request with retry.
Formats LangChain StructuredTools to AnthropicTools.
Generates chat based on the input messages.
Generates a prompt based on the input prompt values.
Get the number of tokens in the content.
Get the identifying parameters for the model
Get the parameters used to invoke the model
Invokes the chat model with a single input.
Pick keys from the dict output of this runnable. Returns a new runnable.
Create a new runnable sequence that runs each individual runnable in series, piping the output of one runnable into another runnable or runnable-like.
Stream output in chunks.
Stream all output from a runnable, as reported to the callback system. This includes all inner runs of LLMs, Retrievers, Tools, etc. Output is streamed as Log objects, which include a list of jsonpatch ops that describe how the state of the run has changed in each step, and the final state of the run. The jsonpatch ops can be applied in order to construct state.
Default implementation of transform, which buffers input and then calls stream. Subclasses should override this method if they can start producing output while input is still being generated.
Bind config to a Runnable, returning a new Runnable.
Create a new runnable from the current one that will try invoking other passed fallback runnables if the initial invocation fails.
Bind lifecycle listeners to a Runnable, returning a new Runnable. The Run object contains information about the run, including its id, type, input, output, error, startTime, endTime, and any tags or metadata added to the run.
Add retry logic to an existing runnable.
The name of the serializable. Override to provide an alias or to preserve the serialized module name in minified environments.
Implemented as a static method to support loading logic.
Generate a stream of events emitted by the internal steps of the runnable.
Use to create an iterator over StreamEvents that provide real-time information about the progress of the runnable, including StreamEvents from intermediate results.
A StreamEvent is a dictionary with the following schema:
event: string - Event names are of the format: on_[runnable_type]_(start|stream|end).name: string - The name of the runnable that generated the event.run_id: string - Randomly generated ID associated with the given execution of
the runnable that emitted the event. A child runnable that gets invoked as part of the execution of a
parent runnable is assigned its own unique ID.tags: string[] - The tags of the runnable that generated the event.metadata: Record<string, any> - The metadata of the runnable that generated the event.data: Record<string, any>Below is a table that illustrates some events that might be emitted by various chains. Metadata fields have been omitted from the table for brevity. Chain definitions have been included after the table.
ATTENTION This reference table is for the V2 version of the schema.
+----------------------+-----------------------------+------------------------------------------+
| event | input | output/chunk |
+======================+=============================+==========================================+
| on_chat_model_start | {"messages": BaseMessage[]} | |
+----------------------+-----------------------------+------------------------------------------+
| on_chat_model_stream | | AIMessageChunk("hello") |
+----------------------+-----------------------------+------------------------------------------+
| on_chat_model_end | {"messages": BaseMessage[]} | AIMessageChunk("hello world") |
+----------------------+-----------------------------+------------------------------------------+
| on_llm_start | {'input': 'hello'} | |
+----------------------+-----------------------------+------------------------------------------+
| on_llm_stream | | 'Hello' |
+----------------------+-----------------------------+------------------------------------------+
| on_llm_end | 'Hello human!' | |
+----------------------+-----------------------------+------------------------------------------+
| on_chain_start | | |
+----------------------+-----------------------------+------------------------------------------+
| on_chain_stream | | "hello world!" |
+----------------------+-----------------------------+------------------------------------------+
| on_chain_end | [Document(...)] | "hello world!, goodbye world!" |
+----------------------+-----------------------------+------------------------------------------+
| on_tool_start | {"x": 1, "y": "2"} | |
+----------------------+-----------------------------+------------------------------------------+
| on_tool_end | | {"x": 1, "y": "2"} |
+----------------------+-----------------------------+------------------------------------------+
| on_retriever_start | {"query": "hello"} | |
+----------------------+-----------------------------+------------------------------------------+
| on_retriever_end | {"query": "hello"} | [Document(...), ..] |
+----------------------+-----------------------------+------------------------------------------+
| on_prompt_start | {"question": "hello"} | |
+----------------------+-----------------------------+------------------------------------------+
| on_prompt_end | {"question": "hello"} | ChatPromptValue(messages: BaseMessage[]) |
+----------------------+-----------------------------+------------------------------------------+
The "on_chain_*" events are the default for Runnables that don't fit one of the above categories.
In addition to the standard events above, users can also dispatch custom events.
Custom events will be only be surfaced with in the v2 version of the API!
A custom event has following format:
+-----------+------+------------------------------------------------------------+
| Attribute | Type | Description |
+===========+======+============================================================+
| name | str | A user defined name for the event. |
+-----------+------+------------------------------------------------------------+
| data | Any | The data associated with the event. This can be anything. |
+-----------+------+------------------------------------------------------------+
Here's an example:
import { RunnableLambda } from "@langchain/core/runnables";
import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch";
// Use this import for web environments that don't support "async_hooks"
// and manually pass config to child runs.
// import { dispatchCustomEvent } from "@langchain/core/callbacks/dispatch/web";
const slowThing = RunnableLambda.from(async (someInput: string) => {
// Placeholder for some slow operation
await new Promise((resolve) => setTimeout(resolve, 100));
await dispatchCustomEvent("progress_event", {
message: "Finished step 1 of 2",
});
await new Promise((resolve) => setTimeout(resolve, 100));
return "Done";
});
const eventStream = await slowThing.streamEvents("hello world", {
version: "v2",
});
for await (const event of eventStream) {
if (event.event === "on_custom_event") {
console.log(event);
}
}const model = new ChatAnthropic({
model: "claude-opus-4-6",
thinking: { type: "adaptive" },
outputConfig: { effort: "medium" },
});