Skip to main content
You can find information about Anthropic’s latest models, their costs, context windows, and supported input types in the Claude docs.
API ReferenceFor detailed documentation of all features and configuration options, head to the ChatAnthropic API reference.
AWS Bedrock and Google VertexAINote that certain Anthropic models can also be accessed via AWS Bedrock and Google VertexAI. See the ChatBedrock and ChatVertexAI integrations to use Anthropic models via these services.For Anthropic models on AWS Bedrock with the same API as ChatAnthropic, use ChatAnthropicBedrock from langchain-aws.

Overview

Integration details

Model features

Setup

To access Anthropic (Claude) models you’ll need to install the langchain-anthropic integration package and acquire a Claude API key.

Installation

Credentials

Head to the Claude console to sign up and generate a Claude API key. Once you’ve done this set the ANTHROPIC_API_KEY environment variable:
To enable automated tracing of your model calls, set your LangSmith API key:

Instantiation

Now we can instantiate our model object and generate chat completions:
See the ChatAnthropic API reference for details on all available instantiation parameters.
Inference geographyTo control where model inference runs for data residency, pass inference_geo when you create ChatAnthropic. See Anthropic documentation for supported values.

Invocation

To aggregate the full message from the stream:
Learn more about supported invocation methods in our models guide.

Content blocks

When using tools, extended thinking, and other features, content from a single Anthropic AIMessage can either be a single string or a list of Anthropic content blocks. For example, when an Anthropic model invokes a tool, the tool invocation is part of the message content (as well as being exposed in the standardized AIMessage.tool_calls):
Using content_blocks will render the content in LangChain’s standard format that is consistent across other model providers. Read more about content blocks.
You can also access tool calls specifically in a standard format using the tool_calls attribute:

Tools

Anthropic’s tool use features allow you to define external functions that Claude can call during a conversation. This enables dynamic information retrieval, computations, and interactions with external systems. See ChatAnthropic.bind_tools for details on how to bind tools to your model instance.
For information about Claude’s built-in tools (code execution, web browsing, files API, etc), see the Built-in tools.

Strict tool use

Strict tool use requires langchain-anthropic>=1.1.0. See the Claude docs for supported models.
Anthropic supports opt-in strict schema adherence to tool calls. This guarantees that tool names and arguments are validated and correctly typed through constrained decoding. Without strict mode, Claude can occasionally generate invalid tool inputs that break your applications:
  • Type mismatches: passengers: "2" instead of passengers: 2
  • Missing required fields: Omitting fields your function expects
  • Invalid enum values: Values outside the allowed set
  • Schema violations: Nested objects not matching expected structure
Strict tool use guarantees schema-compliant tool calls:
  • Tool inputs strictly follow your input_schema
  • Guaranteed field types and required fields
  • Eliminate error handling for malformed inputs
  • Tool name used is always from provided tools
To enable strict tool use, specify strict=True when calling bind_tools.
Consider a booking system where passengers must be an integer:
Strict tool use has some JSON schema limitations to be aware of. See the Claude docs for more details. If your tool schema uses unsupported features, you’ll receive a 400 error. In these cases, simplify the schema or use standard (non-strict) tool calling.

Input examples

For complex tools, you can provide usage examples to help Claude understand how to use them correctly. This is done by setting input_examples in the tool’s extras parameter.
The extras parameter also supports:

Fine-grained tool streaming

Anthropic supports fine-grained tool streaming, which reduces latency when streaming tool calls with large parameters. Rather than buffering entire parameter values before transmission, fine-grained streaming sends parameter data as it becomes available. This can reduce the initial delay from 15 seconds to around 3 seconds for large tool parameters.
Fine-grained streaming may return invalid or partial JSON inputs, especially if the response reaches max_tokens before completing. Implement appropriate error handling for incomplete JSON data.
To enable fine-grained tool streaming for a tool that should stream tool parameters incrementally, set extras={"eager_input_streaming": True} on the tool. That value is passed through to the Anthropic API on the tool definition.
The streaming data arrives as input_json_delta blocks in chunk.content. You can accumulate these to build the complete tool arguments:

Programmatic tool calling

Programmatic tool calling requires langchain-anthropic>=1.3.0. See the Claude docs for supported models.
Tools can be configured to be callable from Claude’s code execution environment, reducing latency and token consumption in contexts involving large data processing or multi-tool workflows. Refer to Claude’s programmatic tool calling guide for details. To use this feature:
  • Include the code execution built-in tool in your set of tools
  • Specify extras={"allowed_callers": ["code_execution_20250825"]} on tools you wish to call programmatically
See below for a full example with create_agent.
You can specify reuse_last_container on initialization to automatically reuse code execution containers from previous model responses.

Multimodal

Claude supports image and PDF inputs as content blocks, both in Anthropic’s native format (see docs for vision and PDF support) as well as LangChain’s standard format.

Supported input methods

The Files API can also be used to upload files to a container for use with Claude’s built-in code-execution tools. See the code execution section for details.

Image input

Provide image inputs along with text using a HumanMessage with list content format.

PDF input

Provide PDF file inputs along with text.

Extended thinking

Some Claude models support an extended thinking feature, which will output the step-by-step reasoning process that led to its final answer. See compatible models in the Claude documentation. To use extended thinking, specify the thinking parameter when initializing ChatAnthropic. If needed, it can also be passed in as a parameter during invocation. For Claude Sonnet and earlier models, you will need to specify a token budget. For Claude Opus 4.6+, you can use adaptive thinking which automatically determines the budget.
The Claude Messages API handles thinking differently across Claude Sonnet 3.7 and Claude 4 models.Refer to the Claude docs for more info.

Effort

Certain Claude models support an effort feature, which controls how many tokens Claude uses when responding. This is useful for balancing response quality against latency and cost.
Model supportEffort is generally available on Claude Opus 4.6 and Claude Opus 4.5. The max effort level is only supported on Claude Opus 4.6. The xhigh effort level is supported on Claude Opus 4.7. Anthropic may add or adjust model support over time—use the Claude effort documentation as the source of truth.
Setting effort to "high" produces exactly the same behavior as omitting the parameter altogether.
See the Claude documentation for detail on when to use different effort levels and to see supported models.

Task budgets

Claude Opus 4.7 and later support task budgets, an advisory token target for an agentic loop (thinking, tool calls, tool results, and final output). The model sees a running countdown and uses it to prioritize work and finish gracefully. Unlike max_tokens, task budgets are not a hard cap.
Task budgets require langchain-anthropic>=1.4.1 and are currently in beta.

Citations

Anthropic supports a citations feature that lets Claude attach context to its answers based on source documents supplied by the user. When document or search_result content blocks with "citations": {"enabled": True} are included in a query, Claude may generate citations in its response.

Simple example

In this example we pass a plain text document. In the background, Claude automatically chunks the input text into sentences, which are used when generating citations.

In tool results (agentic RAG)

Claude supports a search_result content block representing citable results from queries against a knowledge base or other custom source. These content blocks can be passed to claude both top-line (as in the above example) and within a tool result. This allows Claude to cite elements of its response using the result of a tool call. To pass search results in response to tool calls, define a tool that returns a list of search_result content blocks in Anthropic’s native format. For example:
Here we demonstrate an end-to-end example in which we populate a LangChain vector store with sample documents and equip Claude with a tool that queries those documents.The tool here takes a search query and a category string literal, but any valid tool signature can be used.This example requires langchain-openai and numpy to be installed:

Using with text splitters

Anthropic also lets you specify your own splits using custom document types. LangChain text splitters can be used to generate meaningful splits for this purpose. See the below example, where we split the LangChain README.md (a markdown document) and pass it to Claude as context: This example requires langchain-text-splitters to be installed:

Prompt caching

Anthropic supports caching of elements of your prompts, including messages, tool definitions, tool results, images and documents. This allows you to reuse large documents, instructions, few-shot documents, and other data to reduce latency and costs. There are two ways to enable prompt caching on direct model calls:
  • Automatic caching: Pass cache_control at invocation time (model.invoke(..., cache_control=...)). This is provider/API-level caching: the Anthropic API applies the cache breakpoint to the last cacheable block and moves it forward as conversations grow.
  • Explicit cache breakpoints: Place cache_control directly on individual content blocks for fine-grained, direct breakpoint control over exactly what gets cached.
Only certain Claude models support prompt caching. See the Claude documentation for details.
For LangChain agents, prefer AnthropicPromptCachingMiddleware when you want LangChain to optimize stable system prompt and tool content. The middleware is a LangChain agent/harness optimization and is not the same as the invocation-level cache_control shown below, which mirrors the Anthropic API behavior.

Automatic caching

Automatic caching requires langchain-anthropic>=1.4.0.
Pass cache_control as an invocation parameter to automatically cache all content up to and including the last cacheable block. On subsequent requests with the same prefix, cached content is reused automatically. The cache breakpoint moves forward as conversations grow, so you don’t need to manage individual cache_control markers.
For 1-hour caching, specify the ttl field:

Explicit cache breakpoints

For fine-grained control, mark individual content blocks with cache_control. This is useful when you need to cache different sections that change at different frequencies.

Messages

1-hour cachingThe cache lifetime is 5 minutes by default. For longer caching, specify "ttl": "1h" in the cache_control field. 1-hour cache writes cost 2x the base input token price (vs 1.25x for 5-minute).
Details of cached token counts will be included on the InputTokenDetails of response’s usage_metadata:

Caching tools

Incremental caching in conversational applications

Prompt caching can be used in multi-turn conversations to maintain context from earlier messages without redundant processing. We can enable incremental caching by marking the final message with cache_control. Claude will automatically use the longest previously-cached prefix for follow-up messages. Below, we implement a simple chatbot that incorporates this feature. We follow the LangChain chatbot tutorial, but add a custom reducer that automatically marks the last content block in each user message with cache_control:
In the LangSmith trace, toggling “raw output” will show exactly what messages are sent to the chat model, including cache_control keys.

Token counting

You can count tokens in messages before sending them to the model using get_num_tokens_from_messages(). This uses Anthropic’s official token counting API.
You can also count tokens when using tools:

Context management

Anthropic supports context management features that automatically manage the model’s context window to optimize performance and cost. See the Claude documentation for more details and configuration options.

Clearing tool uses

Clear tool results from the context to reduce token usage while preserving the conversation flow.
Context management is supported since langchain-anthropic>=0.3.21You must specify the context-management-2025-06-27 beta header to apply context management to your model calls.

Automatic compaction

Claude Opus 4.6 and later support automatic server-side compaction, which intelligently condenses conversation history when the context window approaches its limit. This allows for longer conversations without manual context management.
Automatic compaction requirements:
  • Claude Opus 4.6 or later
  • langchain-anthropic>=1.3.0
  • compact-2026-01-12 beta header
See Anthropic’s docs for details on trigger configuration. When a compaction event is triggered, ChatAnthropic will return compaction blocks representing the state of the prompt. These should be retained in the message history that is passed back to the model in multi-turn applications.

Structured output

Structured output requires langchain-anthropic>=1.1.0. See the Claude docs for supported models.
Anthropic supports a native structured output feature, which guarantees that its responses adhere to a given schema. You can access this feature in individual model calls, or by specifying the response format of a LangChain agent. See below for examples.
Use the with_structured_output method to generate a structured model response. Specify method="json_schema" to enable Anthropic’s native structured output feature; otherwise the method defaults to using function calling.
Specify response_format with ProviderStrategy to engage Anthropic’s structured output feature when generating its final response.

Built-in tools

Anthropic supports a variety of built-in client and server-side tools. Server-side tools (e.g., web search) are passed to the model and executed by Anthropic. Client-side tools (e.g., bash tool) require you to implement the callback execution logic in your application and return results to the model. In either case, you make tools accessible to your chat model by using bind_tools on the model instance. Importantly, client-side tools require you to implement the execution logic. See the relevant sections below for examples.
Middleware vs toolsFor client-side tools (e.g. bash, text editor, memory), you may opt to use middleware, which provide production-ready implementations that contain built-in execution, state management, and security policies.Use middleware when you want a turnkey solution; use tools (documented below) when you need custom execution logic or want to use bind_tools directly.
Beta toolsIf binding a beta tool to your chat model, LangChain will automatically add the required beta header for you.

Bash tool

Claude supports a client-side bash tool that allows it to execute shell commands in a persistent bash session. This enables system operations, script execution, and command-line automation.
Important: You must provide the execution environmentLangChain handles the API integration (sending/receiving tool calls), but you are responsible for:
  • Setting up a sandboxed computing environment (Docker, VM, etc.)
  • Implementing command execution and output capture
  • Passing results back to Claude in an agent loop
See the Claude bash tool docs for implementation guidance.
Requirements:
  • Claude 4 models or Claude Sonnet 3.7
The bash tool supports two parameters:
  • command (required): The bash command to execute
  • restart (optional): Set to true to restart the bash session
For a “batteries-included” implementation, consider using ClaudeBashToolMiddleware which provides persistent sessions, Docker isolation, output redaction, and startup/shutdown commands out of the box.

Code execution

Claude can use a server-side code execution tool to execute code in a sandboxed environment.
Anthropic’s 2025-08-25 code execution tools are supported since langchain-anthropic>=1.0.3.The legacy 2025-05-22 tool is supported since langchain-anthropic>=0.3.14.
The code sandbox does not have internet access, thus you may only use packages that are pre-installed in the environment. See the Claude docs for more info.
Using the Files API, Claude can write code to access files for data analysis and other purposes. See example below:
Note that Claude may generate files as part of its code execution. You can access these files using the Files API:
Available tool versions:
  • code_execution_20250522 (legacy)
  • code_execution_20250825 (recommended)

Computer use

Claude supports client-side computer use capabilities, allowing it to interact with desktop environments through screenshots, mouse control, and keyboard input.
Important: You must provide the execution environmentLangChain handles the API integration (sending/receiving tool calls), but you are responsible for:
  • Setting up a sandboxed computing environment (Linux VM, Docker container, etc.)
  • Implementing a virtual display (e.g., Xvfb)
  • Executing Claude’s tool calls (screenshot, mouse clicks, keyboard input)
  • Passing results back to Claude in an agent loop
Anthropic provides a reference implementation to help you get started.
Requirements:
  • Claude Opus 4.5, Claude 4, or Claude Sonnet 3.7
Available tool versions:
  • computer_20250124 (for Claude 4 and Claude Sonnet 3.7)
  • computer_20251124 (for Claude Opus 4.5)

Remote MCP

Claude can use a server-side MCP connector tool for model-generated calls to remote MCP servers.
Remote MCP is supported since langchain-anthropic>=0.3.14

Text editor

Claude supports a client-side text editor tool can be used to view and modify text local files. See the text editor tool documentation for details.
Available tool versions:
  • text_editor_20250124 (legacy)
  • text_editor_20250728 (recommended)
For a “batteries-included” implementation, consider using StateClaudeTextEditorMiddleware or FilesystemClaudeTextEditorMiddleware which provide LangGraph state integration or filesystem persistence, path validation, and other features.

Web fetching

Claude can use a server-side web fetching tool to retrieve full content from specified web pages and PDF documents and ground its responses with citations.
Claude can use a server-side web search tool to run searches and ground its responses with citations.
Web search tool is supported since langchain-anthropic>=0.3.13

Memory tool

Claude supports a memory tool for client-side storage and retrieval of context across conversational threads. See the memory tool documentation for details.
Anthropic’s built-in memory tool is supported since langchain-anthropic>=0.3.21
For a “batteries-included” implementation, consider using StateClaudeMemoryMiddleware or FilesystemClaudeMemoryMiddleware which provide LangGraph state integration or filesystem persistence, automatic system prompt injection, and other features.
Claude supports a server-side tool search feature that enables dynamic tool discovery and loading. Instead of loading all tool definitions into the context window upfront, Claude can search your tool catalog and load only the tools it needs. This is useful when:
  • You have 10+ tools available in your system
  • Tool definitions are consuming significant tokens
  • You’re experiencing tool selection accuracy issues with large tool sets
There are two tool search variants:
  • Regex (tool_search_tool_regex_20251119): Claude constructs regex patterns to search for tools
  • BM25 (tool_search_tool_bm25_20251119): Claude uses natural language queries to search for tools
Use the extras parameter to specify defer_loading on LangChain tools:
Key points:
  • Tools with defer_loading: True are only loaded when Claude discovers them via search
  • Keep your 3-5 most frequently used tools as non-deferred for optimal performance
  • Both variants search tool names, descriptions, argument names, and argument descriptions
See the Claude documentation for more details on tool search, including usage with MCP servers and client-side implementations.

Response metadata

Token usage metadata

Message chunks containing token usage will be included during streaming by default:
These can be disabled by setting stream_usage=False in the stream method or when initializing ChatAnthropic.

API reference

For detailed documentation of all features and configuration options, head to the ChatAnthropic API reference.