Claude API LangChain Integration Example
Claude API LangChain Integration Example
If you're building with LangChain and want Claude as your model backend, the integration is straightforward: install langchain-anthropic, set an API key, and instantiate ChatAnthropic like you would any other chat model. LangChain treats Claude as a first-class LLM, so prompt templates, chains, memory, tool calling, and agents all work the same way they do with other providers.
This guide walks through a working setup — from installation to a full chain with tool use and streaming — plus a note on how to point your LangChain app at a managed API gateway instead of a raw provider key, which matters once you move from a prototype to something with real users.
Installing the dependencies
LangChain's Anthropic integration lives in its own package:
pip install langchain-anthropic langchain-core
Set your API key as an environment variable, which LangChain reads automatically:
export ANTHROPIC_API_KEY="sk-ant-..."
Basic chat model example
The simplest integration is instantiating ChatAnthropic and invoking it directly:
from langchain_anthropic import ChatAnthropic
llm = ChatAnthropic(
model="claude-sonnet-4-5",
temperature=0.3,
max_tokens=1024,
)
response = llm.invoke("Summarize the benefits of connection pooling in three bullet points.")
print(response.content)
ChatAnthropic returns a AIMessage object, so response.content gives you the text. This is the pattern most LangChain tutorials start with, and it's enough for single-turn requests.
Using Claude inside a chain
The real value of LangChain is composing prompts, models, and parsers into a pipeline. Here's a chain that takes structured input and runs it through a prompt template before calling Claude:
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_anthropic import ChatAnthropic
prompt = ChatPromptTemplate.from_messages([
("system", "You are a precise technical writer. Keep answers under 100 words."),
("human", "{question}"),
])
llm = ChatAnthropic(model="claude-sonnet-4-5")
chain = prompt | llm | StrOutputParser()
result = chain.invoke({"question": "What is idempotency in REST APIs?"})
print(result)
The | operator chains the prompt, model, and output parser using LangChain's expression language (LCEL). This is the pattern you'll reuse for RAG pipelines, multi-step reasoning, and agent tool wrappers.
Tool calling with Claude in LangChain
Claude supports native tool use, and LangChain exposes it through bind_tools. This lets Claude decide when to call a function you've defined, rather than always returning plain text:
from langchain_core.tools import tool
from langchain_anthropic import ChatAnthropic
@tool
def get_weather(city: str) -> str:
"""Get current weather for a city."""
return f"It's 18°C and cloudy in {city}."
llm = ChatAnthropic(model="claude-sonnet-4-5")
llm_with_tools = llm.bind_tools([get_weather])
response = llm_with_tools.invoke("What's the weather in Lisbon?")
print(response.tool_calls)
response.tool_calls contains the structured call Claude wants to make, including arguments. You run the function yourself and feed the result back into the conversation as a tool message. This is the same tool-calling contract Claude exposes natively — LangChain just wraps it in a consistent interface across providers.
Streaming responses
For chat UIs, streaming is usually non-negotiable. LangChain supports it directly on the chain:
llm = ChatAnthropic(model="claude-sonnet-4-5")
for chunk in llm.stream("Write a short changelog entry for a new rate-limiter feature."):
print(chunk.content, end="", flush=True)
This works identically whether you call llm.stream() on the model alone or on a full LCEL chain.
Memory and multi-turn conversations
LangChain's RunnableWithMessageHistory or a simple list of HumanMessage/AIMessage objects both work with ChatAnthropic:
from langchain_core.messages import HumanMessage, AIMessage
history = [
HumanMessage(content="What's a good caching strategy for a read-heavy API?"),
]
response = llm.invoke(history)
history.append(AIMessage(content=response.content))
history.append(HumanMessage(content="How would that change for write-heavy workloads?"))
response2 = llm.invoke(history)
print(response2.content)
Claude doesn't maintain state between calls, so the full message history has to be sent on every request — LangChain just manages that list for you.
Routing LangChain through a managed gateway
One thing LangChain's ChatAnthropic doesn't solve is operational control: per-app API keys, usage breakdowns across environments, or team seat management. If you're deploying multiple LangChain apps (a staging bot, a production chatbot, an internal tool), sharing one raw Anthropic key across all of them makes it hard to track usage or rotate access without breaking everything at once.
This is where SubToAPI fits in. It turns your Claude access into a standard HTTPS API with its own sub_live_... keys, so each LangChain app can get its own key, you can see usage per key in one dashboard, and you can add teammates without sharing credentials. ChatAnthropic accepts a custom anthropic_api_url, so you can point it at SubToAPI's endpoint and keep the rest of your LangChain code unchanged:
from langchain_anthropic import ChatAnthropic
llm = ChatAnthropic(
model="claude-sonnet-4-5",
anthropic_api_url="https://api.subtoapi.app/v1",
anthropic_api_key="sub_live_...",
)
Everything else — chains, tools, streaming, memory — keeps working exactly as shown above, because SubToAPI mirrors the Messages API shape. See the quickstart and messages docs for request details, streaming for SSE specifics, and tools for the tool-use contract. Pricing starts at Solo for €9/month, with Team and Scale plans for multi-seat setups — details on the pricing page, and you can start a free trial at signup.
questions
Does LangChain support Claude's native tool calling, or only text generation? LangChain fully supports Claude's native tool use through bind_tools(). Claude returns structured tool calls with arguments, which you execute and feed back into the conversation as tool results — the same flow available in Claude's raw API.
Can I use LangChain's agents (not just chains) with Claude? Yes. Claude works with LangChain's agent executors and the newer LangGraph framework, since agents are built on the same ChatAnthropic model interface and tool-calling contract shown above.
Do I need a separate API key for each LangChain app I deploy? Not with raw Anthropic access, but it's good practice once you have more than one app. A gateway like SubToAPI lets you issue a distinct sub_live_... key per app while billing and usage stay consolidated in one dashboard.