Claude API LangChain Example

Use Claude with LangChain in Python. Install langchain-anthropic, build chains, use LCEL, add memory, and stream responses — working 2026 examples.

💥 50p impulse-buy: Power Prompts PDF (first 10 buyers) 30 battle-tested Claude Code prompts · 8-page PDF · paste into CLAUDE.md and never re-type a prompt again · 50p impulse-buy, no commitment

LangChain's langchain-anthropic package wraps the Anthropic SDK so Claude fits natively into any LangChain pipeline — chains, agents, retrievers, and memory.

Installation

pip install langchain langchain-anthropic

Basic chat call

from langchain_anthropic import ChatAnthropic
from langchain_core.messages import HumanMessage

llm = ChatAnthropic(model="claude-sonnet-4-6")  # reads ANTHROPIC_API_KEY from env

response = llm.invoke([HumanMessage(content="Explain LangChain in two sentences.")])
print(response.content)

LCEL chain (prompt → model → parser)

from langchain_anthropic import ChatAnthropic
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a concise technical writer."),
    ("human", "{question}")
])

llm = ChatAnthropic(model="claude-sonnet-4-6", max_tokens=512)

chain = prompt | llm | StrOutputParser()

answer = chain.invoke({"question": "What is prompt caching?"})
print(answer)

Streaming with LCEL

for chunk in chain.stream({"question": "Explain agentic AI step by step."}):
    print(chunk, end="", flush=True)

Conversation with memory

from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain

llm = ChatAnthropic(model="claude-sonnet-4-6", max_tokens=1024)
memory = ConversationBufferMemory()

conversation = ConversationChain(llm=llm, memory=memory)

print(conversation.predict(input="Hi, my name is Alex."))
print(conversation.predict(input="What's my name?"))  # Claude remembers "Alex"

RAG chain (retrieval-augmented generation)

from langchain_anthropic import ChatAnthropic
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough

# Assume 'retriever' is any LangChain retriever (Chroma, FAISS, Pinecone, etc.)
prompt = ChatPromptTemplate.from_template("""
Answer the question based only on the following context:
{context}

Question: {question}
""")

llm = ChatAnthropic(model="claude-sonnet-4-6")

rag_chain = (
    {"context": retriever, "question": RunnablePassthrough()}
    | prompt
    | llm
    | StrOutputParser()
)

answer = rag_chain.invoke("What are Claude's context window limits?")

LangChain vs raw Anthropic SDK

CriterionRaw Anthropic SDKLangChain + langchain-anthropic
Setup complexityMinimal (1 package)2+ packages, more concepts
Switching models/providersManual refactorSwap one class name
Retrieval (RAG)DIYBuilt-in retrievers + vectorstores
AgentsCustom loop neededLangGraph / AgentExecutor
ObservabilitySDK callbacksLangSmith built in
StreamingNative SDK stream().stream() on any chain
When to useDirect API, minimal depsRAG, multi-provider, agent graphs

Use the raw SDK when you want minimal dependencies and direct control. Use LangChain when you need retrievers, multi-provider portability, or LangSmith tracing. Estimate costs for either approach at Claude API Cost Calculator.

Frequently asked questions

Which LangChain package do I use with Claude?
Install `langchain-anthropic` — the official Anthropic integration for LangChain. It provides `ChatAnthropic`, the LangChain-compatible wrapper for the Anthropic API. Also install `langchain` for core chains and prompts.
Can I use Claude with LangChain Expression Language (LCEL)?
Yes. `ChatAnthropic` is a standard LangChain chat model and implements the Runnable interface, so you can compose it in LCEL chains with `|` operators: `prompt | model | StrOutputParser()`.
How do I add conversation memory in LangChain with Claude?
Use `ConversationBufferMemory` (simple) or `ConversationSummaryMemory` (for long conversations) with `ConversationChain`. For production apps, store history in a DB and reconstruct the `messages` list on each request — Claude's 200K context window means you rarely need to truncate.
Does streaming work with LangChain + Claude?
Yes — call `.stream()` on any LCEL chain. Each yielded chunk is an `AIMessageChunk` with a `.content` string. You can also pass a `StreamingStdOutCallbackHandler` to legacy chains.
What model string do I use for ChatAnthropic?
Pass `model='claude-sonnet-4-6'` for best price/quality in 2026. Use `claude-haiku-4-5-20251001` for fast cheap chains. Use `claude-opus-4-7` only for complex reasoning tasks where cost is secondary.

Free tools

Cost Calculator → API Cookbook → Diff Summarizer → Skills Browser →

More examples

Claude API Python QuickstartClaude API Node.js / TypeScript QuickstartClaude API Streaming in PythonClaude API Streaming in Node.js / TypeScriptClaude API Tool Use in PythonClaude API Tool Use in Node.js / TypeScript