LangChain is still one of the most popular ways to build Claude apps in Python. The Claude side changed a lot this year, though, and many older tutorials now send requests that fail with a 400 error.
This guide uses the current packages and model IDs. It covers chat, streaming, tool calling, structured output, prompt caching, thinking and a full agent, plus costs and real error fixes.
- Packages:
langchain-anthropic1.9.0 (4 Dec 2026),langchain1.5.2 andlanggraph1.2.25. LangChain and the Claude package now need Python 3.11+. - Models: use
claude-opus-5-5,claude-sonnet-5-5orclaude-haiku-5-5withChatAnthropic. - Biggest gotcha: the current Anthropic SDK sends API version
2026-10-21, which rejectstemperature,top_pandtop_kon every model. Leave them out. - Structured output: use
with_structured_output(..., method="json_schema"). Forced tool calls return a 400 on Opus 5.5 and Sonnet 5.5. - Agents: build them with
create_agentfromlangchain.agents. The oldcreate_react_agentis deprecated. - Thinking: pass
effort="low"to"max". Oldbudget_tokenscode fails on the new models.
What langchain-anthropic Is and When to Use It
langchain-anthropic is the official LangChain integration for Claude. Its main class, ChatAnthropic, wraps the Anthropic Python SDK and gives Claude the same interface as every other LangChain chat model.
That shared interface is the real reason to use it. Here is when it makes sense:
- You already use LangChain or LangGraph: swap Claude in without rewriting your chains, retrievers or agents.
- You want a ready agent loop:
create_agentruns the tool loop, memory and middleware for you. - You may switch providers later: the same code can point at another model with one line.
- You want tracing: LangSmith picks up LangChain runs with no extra code.
If you only need one or two Claude calls, the plain SDK is lighter. My Claude API Python tutorial covers that route.
langchain-anthropic, set ANTHROPIC_API_KEY, then call ChatAnthropic(model="claude-sonnet-5-5").invoke("Hi"). Do not pass temperature, and use method="json_schema" for structured output.Current Versions and Model IDs (December 2026)
I checked PyPI and the installed package source on 5 December 2026. These are the versions the examples below were written against.
| Package | Version | Released | Python |
|---|---|---|---|
langchain-anthropic |
1.9.0 | 4 Dec 2026 | 3.11+ |
langchain |
1.5.2 | 18 Nov 2026 | 3.11+ |
langchain-core |
1.9.1 | 4 Dec 2026 | 3.11+ |
langgraph |
1.2.25 | 1 Dec 2026 | 3.10+ |
anthropic (pulled in) |
2.17.0 | 3 Dec 2026 | 3.10+ |
Version 1.9.0 of langchain-anthropic needs langchain-core 1.9.0 or newer. The bundled anthropic 2.17.0 SDK sends the API version header 2026-10-21 on every request, and that matters for the sampling settings covered later.
Which Claude model ID to use
| Model | ID for ChatAnthropic | Best for | Input / output per 1M tokens |
|---|---|---|---|
| Claude Haiku 5.5 | claude-haiku-5-5 |
High volume, classification, cheap chat | $0.10 / $0.50 (prompts up to 100K) |
| Claude Sonnet 5.5 | claude-sonnet-5-5 |
Most apps and agents | $2 / $10 |
| Claude Opus 5.5 | claude-opus-5-5 |
Hard reasoning and coding | $4 / $20 |
| Claude Fable 5.2 | claude-fable-5-2 |
The most demanding long tasks | $8 / $40 |
Use the IDs exactly as written, with no date suffix. All four have a 1M token context window.
Prerequisites and Setup
You need three things before the first call:
- Python 3.11 or newer: the current LangChain releases refuse to install on 3.10.
- A Claude API key: create one in the Claude Console. My guide on how to get a Claude API key walks through it.
- A little credit: the API is pay as you go, separate from a Claude.ai Pro or Max plan.
- Create a virtual environment. Run
python3 -m venv .venv, then activate it withsource .venv/bin/activate(on Windows,.venv\Scripts\activate). - Install the packages. Run
pip install -U langchain-anthropic langchain. Thelangchainpackage bringslanggraphwith it, which the agent example needs. - Set your API key. Run
export ANTHROPIC_API_KEY="sk-ant-..."(on Windows PowerShell,$env:ANTHROPIC_API_KEY="sk-ant-...").ChatAnthropicreads it automatically. - Check the install. Run
pip show langchain-anthropicand confirm the version is 1.9.0 or newer. - Run Example 1 below. If it prints a reply, you are ready for tools and agents.

Warning: never paste a real key into your code or commit it to Git. Keep it in an environment variable or a .env file that is listed in .gitignore.
Example 1: Your First ChatAnthropic Call
This script sends a system message and a user message, then prints the reply and the token usage.
from langchain_anthropic import ChatAnthropic
from langchain_core.messages import HumanMessage, SystemMessage
model = ChatAnthropic(model="claude-sonnet-5-5", max_tokens=1024)
messages = [
SystemMessage("You are a patient Python tutor. Answer in 3 sentences or less."),
HumanMessage("What is a list comprehension?"),
]
reply = model.invoke(messages)
print(reply.text)
print(reply.usage_metadata) # input_tokens, output_tokens, total_tokens
A few things to notice:
- Messages: you can also pass plain tuples like
("system", "...")and("human", "..."), or dicts withroleandcontent. - max_tokens: if you leave it out, ChatAnthropic uses the model’s maximum output from its profile. For Opus 5.5 that is 128,000, so set a smaller cap for chat apps.
- Reply text:
reply.textgives only the text blocks, without thinking or tool blocks.
For a multi-turn chat, append the returned AIMessage to your list, add the next HumanMessage, and call invoke again. Claude has no memory between calls, so you always send the history.
Tip: init_chat_model("anthropic:claude-sonnet-5-5") from langchain.chat_models returns the same ChatAnthropic object. It is handy when the model name comes from a config file.
Example 2: Streaming Responses
Streaming prints tokens as they arrive, which feels much faster in a chat UI. The classic stream() method still works and is the simplest.
from langchain_anthropic import ChatAnthropic
model = ChatAnthropic(model="claude-haiku-5-5", max_tokens=2048)
for chunk in model.stream("Write a 5 line poem about Python decorators."):
print(chunk.text, end="", flush=True)
print()
Newer langchain-core releases also offer stream_events(..., version="v3"). The LangChain docs show it like this:
stream = model.stream_events("Explain RAG in two sentences.", version="v3")
for token in stream.text:
print(token, end="", flush=True)
full_message = stream.output
For async apps, use astream() or await model.astream_events(..., version="v3"). Async streams have a 120 second wait limit between events by default. Change it with the LANGCHAIN_ANTHROPIC_STREAM_CHUNK_TIMEOUT_S environment variable.
Example 3: Tool Calling With bind_tools
Tool calling lets Claude ask your code to run a function. You describe the tool, Claude returns a tool call with arguments, you run it, and you send the result back.
The @tool decorator turns a typed Python function into a tool. Its docstring becomes the description Claude reads, so write it clearly.
from langchain_anthropic import ChatAnthropic
from langchain_core.messages import HumanMessage, ToolMessage
from langchain_core.tools import tool
@tool
def get_order_status(order_id: str) -> str:
"""Look up the shipping status of an order by its ID."""
fake_db = {"A100": "shipped", "A200": "processing"}
return fake_db.get(order_id, "not found")
model = ChatAnthropic(model="claude-sonnet-5-5", max_tokens=1024)
model_with_tools = model.bind_tools([get_order_status])
messages = [HumanMessage("Where are orders A100 and A200?")]
ai_msg = model_with_tools.invoke(messages)
messages.append(ai_msg)
# Claude may ask for several tools at once (parallel tool calls)
for call in ai_msg.tool_calls:
result = get_order_status.invoke(call["args"])
messages.append(ToolMessage(content=result, tool_call_id=call["id"]))
final = model_with_tools.invoke(messages)
print(final.text)
Useful bind_tools options in version 1.9.0:
- strict=True: makes Claude’s tool arguments match your schema exactly.
- parallel_tool_calls=False: limits Claude to one tool call per turn.
- tool_choice:
"auto"is safe everywhere."any"or a tool name forces a call, but Opus 5.5, Sonnet 5.5 and Fable 5.2 reject forced calls with a 400.
Want to go deeper on tool design, parallel calls and error results? See my Claude tool use tutorial, which covers the raw API behind bind_tools.
Example 4: Structured Output With a Pydantic Model
Structured output turns free text into a typed object. It is ideal for extraction, classification and form filling.
from pydantic import BaseModel, Field
from langchain_anthropic import ChatAnthropic
class Ticket(BaseModel):
"""A support ticket extracted from an email."""
customer_name: str = Field(description="Full name of the customer")
product: str = Field(description="Product the email is about")
priority: str = Field(description="One of: low, medium, high")
summary: str = Field(description="One sentence summary of the issue")
model = ChatAnthropic(model="claude-sonnet-5-5", max_tokens=1024)
extractor = model.with_structured_output(Ticket, method="json_schema")
email = (
"Hi, this is Priya Shah. My SmartDesk 3 stopped raising after the "
"last firmware update and I have a client demo tomorrow. Please help!"
)
ticket = extractor.invoke(email)
print(ticket.priority, "-", ticket.summary)
The method argument is the important part. In langchain-anthropic 1.9.0 the default is still "function_calling", which relies on a forced tool call.
- On Opus 5.5, Sonnet 5.5 and Fable 5.2: forced tool calls are not allowed, so LangChain sends the tool without forcing it. If Claude answers in plain text, you get an
OutputParserException. - With method=”json_schema”: LangChain uses Claude’s native structured outputs (
output_config.format), so the reply always matches the schema.
Note: if the model refuses a request, with_structured_output raises ModelRefusalError. Pass include_raw=True to get the raw message and any parsing error in a dict instead. My structured outputs guide compares this feature across providers.
Thinking, Effort and Prompt Caching via LangChain
Thinking and effort
On current Claude models you no longer set a thinking token budget. You set an effort level, and Claude decides how much to think.
from langchain_anthropic import ChatAnthropic
model = ChatAnthropic(
model="claude-opus-5-5",
effort="high", # low, medium, high, xhigh or max
thinking={"type": "adaptive", "display": "summarized"},
max_tokens=16000,
)
reply = model.invoke("Plan a database migration from MySQL 5.7 to PostgreSQL 17.")
for block in reply.content:
if block["type"] == "thinking":
print("THINKING:", block["thinking"][:300])
print(reply.text)
What LangChain does with these settings:
- effort: an alias for
reasoning_effort. It is sent asoutput_config.effort. You can also pass it per call, for examplemodel.invoke(prompt, effort="low"). - Automatic thinking: if you set effort but no
thinking, LangChain adds{"type": "adaptive", "display": "summarized"}for you. - Opus 5.5 default: effort is medium when you leave it out, and thinking cannot be turned off. Lower the effort instead.
- Old code:
{"type": "enabled", "budget_tokens": N}returns a 400 on Opus 5.5, Sonnet 5.5 and Fable 5.2.
Thinking tokens are billed as output tokens. Raise effort only where answers clearly get better. My Claude extended thinking API guide explains the levels in detail.
Prompt caching
Caching stores a long, repeated prompt prefix (system prompt, tool list, a big document) so later calls read it at a fraction of the price. On Opus 5.5 a cache hit costs $0.20 per 1M tokens, against $4 for normal input.
LangChain gives you two ways to turn it on for direct model calls:

# 1) Automatic caching for the whole request (langchain-anthropic 1.4.0+)
reply = model.invoke(messages, cache_control={"type": "ephemeral"})
# 1-hour cache instead of the default 5 minutes
reply = model.invoke(messages, cache_control={"type": "ephemeral", "ttl": "1h"})
# 2) An explicit breakpoint on one content block
from langchain_core.messages import SystemMessage
system = SystemMessage(content=[
{"type": "text", "text": LONG_POLICY_DOCUMENT,
"cache_control": {"type": "ephemeral"}},
])
Check that caching works by reading reply.usage_metadata["input_token_details"]. The cache_creation count shows a write, and cache_read shows a hit.
A cache write costs 1.25 times the input price for 5 minutes, or 2 times for 1 hour. Prefixes below a model’s minimum length silently do not cache. My prompt caching guide shows how to lay out prompts for high hit rates.
Example 5: A LangGraph Agent With create_agent
An agent is a loop: Claude picks a tool, your code runs it, and the result goes back until Claude has an answer. In LangChain 1.x you build it with create_agent, which runs on LangGraph under the hood.
The older create_react_agent from langgraph.prebuilt is marked deprecated since LangGraph 1.0, so use create_agent for new projects.
from langchain.agents import create_agent
from langchain_anthropic import ChatAnthropic
from langchain_anthropic.middleware import AnthropicPromptCachingMiddleware
from langchain_core.tools import tool
from langgraph.checkpoint.memory import InMemorySaver
@tool
def get_weather(city: str) -> str:
"""Get the current weather for a city."""
return f"It is 18 C and sunny in {city}."
@tool
def convert_c_to_f(celsius: float) -> float:
"""Convert a temperature from Celsius to Fahrenheit."""
return celsius * 9 / 5 + 32
agent = create_agent(
model=ChatAnthropic(model="claude-sonnet-5-5", effort="medium", max_tokens=4096),
tools=[get_weather, convert_c_to_f],
system_prompt="You are a friendly travel helper. Keep answers short.",
middleware=[AnthropicPromptCachingMiddleware(ttl="5m")],
checkpointer=InMemorySaver(),
)
config = {"configurable": {"thread_id": "trip-1"}}
result = agent.invoke(
{"messages": [{"role": "user", "content": "Weather in Lisbon, in Fahrenheit?"}]},
config,
)
print(result["messages"][-1].text)
# Same thread_id, so the agent remembers Lisbon
follow_up = agent.invoke(
{"messages": [{"role": "user", "content": "Is that good for a beach day?"}]},
config,
)
print(follow_up["messages"][-1].text)
Here is what each part does:
- model: a
ChatAnthropicobject, or a string like"anthropic:claude-sonnet-5-5". - tools: plain
@toolfunctions. The agent runs them and loops until Claude stops calling tools. - AnthropicPromptCachingMiddleware: adds cache breakpoints to the system prompt, tools and history on every step. It takes
ttlof"5m"or"1h"and an optionalmin_messages_to_cache. - checkpointer:
InMemorySaverkeeps each conversation bythread_id. Use a database checkpointer in production.
For typed final answers, pass response_format=YourPydanticModel (or ProviderStrategy(YourModel) from langchain.agents.structured_output). The result then appears in result["structured_response"].
Tip: agent runs make several model calls per question. Caching the system prompt and tools usually pays for itself after the second step.
The Same Request With curl
Under the hood, ChatAnthropic posts to the Messages API. This curl call is handy for checking a key or a model ID without Python.
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2026-10-21" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-5-5",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Say hello in one sentence."}]
}'
If this works but LangChain fails, the problem is in your LangChain settings, not your key or account.
Pricing and a Worked Cost Example
LangChain itself is free and open source. You pay only for Claude tokens, at the normal API rates from Anthropic’s pricing page.
| Model | Input | 5 min cache write | 1 hour cache write | Cache hit | Output |
|---|---|---|---|---|---|
| Haiku 5.5 (prompt up to 100K) | $0.10 | $0.125 | $0.20 | $0.01 | $0.50 |
| Haiku 5.5 (prompt over 100K) | $0.50 | $0.625 | $1 | $0.05 | $2.50 |
| Sonnet 5.5 | $2 | $2.50 | $4 | $0.10 | $10 |
| Opus 5.5 | $4 | $5 | $8 | $0.20 | $20 |
| Fable 5.2 | $8 | $10 | $16 | $0.20 | $40 |
All prices are US dollars per 1 million tokens. The Batch API halves both input and output prices for jobs that can wait.
Worked example: a support bot on Sonnet 5.5
Say your bot handles 10,000 requests a day. Each request has 2,000 input tokens (1,500 of them a fixed system prompt and tools) and 300 output tokens.
- Without caching: 20M input tokens x $2 = $40, plus 3M output tokens x $10 = $30. Total: about $70 a day.
- With caching: 15M cached tokens x $0.10 = $1.50, 5M fresh tokens x $2 = $10, output $30, and about $1 of cache writes. Total: about $42.50 a day, roughly 39% less.
- Same load on Haiku 5.5, no caching: $2 input plus $1.50 output, so about $3.50 a day.
- Same load on Opus 5.5, no caching: $80 input plus $60 output, so about $140 a day.
Output is the expensive side, and thinking tokens count as output. Keep max_tokens and effort as low as your quality allows. For full price details, see my Claude API pricing guide.
Limits and Defaults to Know
| Setting | Value | Notes |
|---|---|---|
| Context window | 1M tokens | Opus 5.5, Sonnet 5.5, Haiku 5.5, Fable 5.2 |
Default max_tokens in ChatAnthropic |
Model maximum (128,000 on Opus 5.5) | Set it yourself for chat |
| Max request size | 128 MB | Messages API; larger returns 413 |
max_retries |
2 | Retries 429, 5xx and connection errors |
| Request timeout | None set by LangChain | Use timeout= in seconds |
| Async stream wait between events | 120 seconds | Raises StreamChunkTimeoutError |
| Opus 5.5 default effort | medium | Haiku 5.5 is also medium; Sonnet 5.5 is high |
| Cache lifetime | 5 minutes or 1 hour | Refreshed on each hit |
temperature, top_p, top_k |
Not allowed | 400 on API version 2026-10-21 |
Rate limits depend on your account’s usage tier and are shown in the Claude Console. If you hit them often, read my guide on fixing Claude 429 and 529 errors.
Troubleshooting: Common Problems and Fixes
LangChain wraps Claude errors in its own classes, such as AnthropicRateLimitError and AnthropicAuthenticationError. They inherit from the matching anthropic SDK errors, so except anthropic.RateLimitError still catches them.
| Error or symptom | Cause | Fix |
|---|---|---|
401 invalid x-api-key (authentication_error) |
Key missing, mistyped or revoked | Check ANTHROPIC_API_KEY in the same shell, or create a new key |
400 invalid_request_error mentioning temperature |
temperature, top_p or top_k set |
Remove them; steer style in the prompt |
| 400 saying tool_choice “tool” and “any” are not supported | Forced tool use on Opus 5.5, Sonnet 5.5 or Fable 5.2 | Use tool_choice="auto" or structured output |
400 about budget_tokens or disabled thinking |
Old thinking settings | Use effort with adaptive thinking |
OutputParserException from structured output |
Default function_calling method, no tool call made |
Use method="json_schema" |
404 not_found_error |
Wrong or retired model ID | Use an ID from the table above, with no date suffix |
429 rate_limit_error |
Tier rate limit or spend cap | Back off, cache prompts, or raise your tier |
529 overloaded_error |
Claude is busy | Retry with backoff; LangChain retries twice by default |
StreamChunkTimeoutError |
No stream event for 120 s | Raise the limit with the environment variable above |
| pip cannot find version 1.9.0 | Python 3.10 or older | Upgrade to Python 3.11+ |
A simple, safe error handler for a script looks like this:
import anthropic
from langchain_anthropic import ChatAnthropic
model = ChatAnthropic(model="claude-sonnet-5-5", max_tokens=1024, max_retries=4)
try:
print(model.invoke("Hello!").text)
except anthropic.RateLimitError:
print("Rate limited. Wait and try again.")
except anthropic.AuthenticationError:
print("Check your ANTHROPIC_API_KEY.")
except anthropic.BadRequestError as e:
print("Bad request:", e)
except anthropic.APIConnectionError:
print("Network problem. Check your connection.")
Frequently Asked Questions
Is langchain-anthropic free?
Yes. The package is open source under the MIT licence. You only pay Anthropic for the tokens your requests use.
Which Claude model should I use with LangChain?
Start with claude-sonnet-5-5 for most apps and agents. Move to claude-haiku-5-5 for cheap, high-volume work, or claude-opus-5-5 when answers need deeper reasoning.
Why does setting temperature give me a 400 error?
The current Anthropic SDK sends API version 2026-10-21, which removed temperature, top_p and top_k on every model. Leave them out and control style with your prompt and the effort setting.
Should I use create_agent or create_react_agent?
Use create_agent from langchain.agents. The older create_react_agent in langgraph.prebuilt is deprecated, and new agent features such as middleware land in create_agent.
How do I turn on prompt caching in LangChain?
Pass cache_control={"type": "ephemeral"} to invoke, or add AnthropicPromptCachingMiddleware to an agent. Then check cache_read in usage_metadata to confirm hits.
Can I use Claude on Bedrock or Vertex AI through ChatAnthropic?
Yes. Pass a platform client from the Anthropic SDK, such as AnthropicBedrock or AnthropicVertex, through the client parameter. Model IDs and prices then follow that platform’s rules.
How do I see Claude’s thinking in LangChain?
Set thinking={"type": "adaptive", "display": "summarized"}, or just set an effort level. The summary arrives as a content block with type set to "thinking".



