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.Overview
Integration details
Model features
Setup
To access Anthropic (Claude) models you’ll need to install thelangchain-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 theANTHROPIC_API_KEY environment variable:
Instantiation
Now we can instantiate our model object and generate chat completions:ChatAnthropic API reference for details on all available parameters.
Invocation
Token counting
You can count tokens in messages before sending them to the model usingget_num_tokens_from_messages(). This uses Anthropic’s official token counting API.
Content blocks
When using tools, extended thinking, and other features, content from a single AnthropicAIMessage 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):
content_blocks will render the content in LangChain’s standard format that is consistent across other model providers. Read more about content blocks.
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. SeeChatAnthropic.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:
- Claude Sonnet 4.5 or Opus 4.1.
langchain-anthropic>=1.1.0
- Type mismatches:
passengers: "2"instead ofpassengers: 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
- Tool inputs strictly follow your
input_schema - Guaranteed field types and required fields
- Eliminate error handling for malformed inputs
- Tool
nameused is always from provided tools
To enable strict tool use, specify
strict=True when calling bind_tools.
Example: Type-safe booking system
Example: Type-safe booking system
Consider a booking system where
passengers must be an integer:Input examples
For complex tools, you can provide usage examples to help Claude understand how to use them correctly. This is done by settinginput_examples in the tool’s extras parameter.
extras parameter also supports:
defer_loading(bool): Load tool on-demand for tool searchcache_control(dict): Enable prompt caching for the tool
Token-efficient tool use
Anthropic supports a token-efficient tool use feature. It is supported by default on all Claude 4 models and above.Enabling token-efficient tool use with Claude 3.7
Enabling token-efficient tool use with Claude 3.7
To use token-efficient tool use with Claude 3.7, specify the
token-efficient-tools-2025-02-19 beta-header when instantiating the model:Fine-grained tool streaming
Anthropic supports fine-grained tool streaming, a beta feature that 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. To enable fine-grained tool streaming, specify thefine-grained-tool-streaming-2025-05-14 beta header when initializing the model:
input_json_delta blocks in chunk.content. You can accumulate these to build the complete tool arguments:
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
Image input
Provide image inputs along with text using aHumanMessage 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 thethinking parameter when initializing ChatAnthropic. If needed, it can also be passed in as a parameter during invocation.
You will need to specify a token budget to use this feature. See usage example below:
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.Setting
effort to "high" produces exactly the same behavior as omitting the parameter altogether.Prompt caching
Anthropic supports caching of elements of your prompts, including messages, tool definitions, tool results, images and documents. This allows you to re-use large documents, instructions, few-shot documents, and other data to reduce latency and costs. To enable caching on an element of a prompt, mark its associated content block using thecache_control key. See examples below:
Messages
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 withcache_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:
Chatbot with incremental prompt caching
Chatbot with incremental prompt caching
cache_control keys.Citations
Anthropic supports a citations feature that lets Claude attach context to its answers based on source documents supplied by the user. When document orsearch_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 ofsearch_result content blocks in Anthropic’s native format. For example:
End to end example with LangGraph
End to end example with LangGraph
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 LangChainREADME.md (a markdown document) and pass it to Claude as context:
This example requires langchain-text-splitters to be installed:
Context management
Anthropic supports a context editing feature that will automatically manage the model’s context window (e.g., by clearing tool results). See the Claude documentation for more details and configuration options.Context management is supported since
langchain-anthropic>=0.3.21You must speficy the context-management-2025-06-27 beta header to apply context management to your model calls.Extended context window
Claude Sonnet 4 and 4.5 support a 1-million token context window, available in beta for organizations in usage tier 4 and organizations with custom rate limits. To enable the extended context window, specify thecontext-1m-2025-08-07 beta header:
Structured output
Structured output requires:
- Claude Sonnet 4.5 or Opus 4.1.
langchain-anthropic>=1.1.0
Individual model calls
Individual model calls
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.Agent response format
Agent response format
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 tools, which can be bound to the model in the usual way. Claude will generate tool calls adhering to its internal schema for the tool.Bash tool
Claude supports a 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
Requirements:
- Claude 4 models or Claude Sonnet 3.7
response.tool_calls will contain the bash command Claude wants to execute. You must run this command in your environment and pass the result back.
command(required): The bash command to executerestart(optional): Set totrueto restart the bash session
Code execution
Claude can use a 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.
Use with Files API
Use with Files API
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 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
Requirements:
- Claude Opus 4.5, Claude 4, or Claude Sonnet 3.7
response.tool_calls will contain the computer action Claude wants to perform. You must execute this action in your environment and pass the result back.
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 MCP connector tool for model-generated calls to remote MCP servers.Remote MCP is supported since
langchain-anthropic>=0.3.14Text editor
The text editor tool can be used to view and modify text files. See docs here for details.Available tool versions:
text_editor_20250124(legacy)text_editor_20250728(recommended)
Web fetching
Claude can use a web fetching tool to retrieve full content from specified web pages and PDF documents and ground its responses with citations.Web search
Claude can use a web search tool to run searches and ground its responses with citations.Web search tool is supported since
langchain-anthropic>=0.3.13Memory tool
Claude supports a memory tool for client-side storage and retrieval of context across conversational threads. See docs here for details.Anthropic’s built-in memory tool is supported since
langchain-anthropic>=0.3.21Tool search
Claude supports a 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
- 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
extras parameter to specify defer_loading on LangChain tools:
- Tools with
defer_loading: Trueare 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
API reference
For detailed documentation of all features and configuration options, head to theChatAnthropic API reference.