← Blog

Claude API LangChain Agent Example: Working Guide

2026-11-13 · 5 min read · SubToAPI Team

Building a LangChain agent with Claude means wiring the ChatAnthropic model class into LangChain's agent executor, giving it tools, and letting the model decide when to call them. This article walks through a complete, working example — API key setup, tool definitions, agent construction, and execution — plus the common pitfalls that trip people up when Claude's tool-calling format meets LangChain's abstraction layer.

If you've tried this already and hit version mismatches, silent tool-call failures, or confusing streaming behavior, skip to the troubleshooting section below. Otherwise, here's the full setup from scratch.

Prerequisites

You'll need:

Install the Python dependencies:

pip install langchain langchain-anthropic langchain-core

Setting up the Claude chat model

LangChain's ChatAnthropic class wraps the Messages API. The minimal setup looks like this:

from langchain_anthropic import ChatAnthropic

llm = ChatAnthropic(
    model="claude-sonnet-4-5",
    temperature=0,
    max_tokens=1024,
    anthropic_api_key="sk-ant-...",
)

temperature=0 is worth setting explicitly for agents — you want deterministic tool selection, not creative variation in whether a function gets called.

Defining tools

LangChain agents need tools wrapped as Tool or @tool-decorated functions. Here's a simple weather lookup and a calculator, which are the two most common "hello world" agent tools:

from langchain_core.tools import tool

@tool
def get_weather(city: str) -> str:
    """Get the current weather for a given city."""
    # In production, call a real weather API here
    return f"The weather in {city} is 18°C and partly cloudy."

@tool
def calculate(expression: str) -> str:
    """Evaluate a basic math expression, e.g. '12 * 7'."""
    try:
        return str(eval(expression))
    except Exception as e:
        return f"Error: {e}"

tools = [get_weather, calculate]

Claude's tool-use format expects a name, a description, and a JSON schema for parameters. LangChain generates this automatically from the function signature and docstring, which is why the docstring matters — Claude uses it to decide when the tool is relevant.

Building the agent

LangChain's modern agent pattern uses create_tool_calling_agent combined with AgentExecutor:

from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful assistant. Use tools when needed."),
    ("human", "{input}"),
    ("placeholder", "{agent_scratchpad}"),
])

agent = create_tool_calling_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

response = agent_executor.invoke({
    "input": "What's the weather in Lisbon, and what's 243 times 17?"
})

print(response["output"])

With verbose=True, you'll see the agent's reasoning trace: it calls get_weather, gets a result, calls calculate, gets a result, then synthesizes a final answer combining both. This is the core agent loop — Claude decides which tool to call, LangChain executes it and feeds the result back, and the cycle repeats until Claude produces a final text response.

Adding memory for multi-turn agents

A single-shot agent is easy; a conversational agent needs memory. The current LangChain pattern uses RunnableWithMessageHistory rather than the older ConversationBufferMemory class:

from langchain_core.chat_history import InMemoryChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory

store = {}

def get_session_history(session_id: str):
    if session_id not in store:
        store[session_id] = InMemoryChatMessageHistory()
    return store[session_id]

agent_with_history = RunnableWithMessageHistory(
    agent_executor,
    get_session_history,
    input_messages_key="input",
    history_messages_key="chat_history",
)

This lets the agent reference earlier turns — important for anything beyond a single tool call, like a research agent that builds on prior results across a conversation.

Common pitfalls

Tool schema mismatches. Claude is stricter about JSON schema validity than some other models. If a tool parameter type is ambiguous (e.g., an Optional field without a default), LangChain's auto-generated schema can produce something Claude rejects at the API level. Keep tool signatures simple and fully typed.

Model name drift. LangChain's Anthropic integration doesn't always keep pace with new model releases. If ChatAnthropic throws a model-not-found error, check that your installed langchain-anthropic version supports the model string you're passing.

Streaming + tool calls together. Streaming a tool-calling agent's output is more fragile than streaming plain text, because the stream has to interleave tool-call deltas with text deltas. If you only need streaming for the final answer (not the intermediate tool reasoning), it's often simpler to disable streaming on intermediate steps and only stream the last LLM call.

Rate limits during agent loops. Agents can make several Claude calls per user request — one per tool-call round plus the final synthesis. Under load, this multiplies your effective request rate fast, which is where raw Anthropic rate limits start to bite teams running agents in production.

A simpler path for production agents

If you're building agents for an internal tool or a product and don't want to manage Anthropic billing, team seats, and key rotation yourself, SubToAPI gives you a sub_live_... key that works as a drop-in Authorization: Bearer header against https://api.subtoapi.app/v1/messages — same Messages API shape Claude's SDKs and LangChain's ChatAnthropic expect under the hood, but with per-key usage metadata, streaming, and tool use available from one dashboard instead of juggling individual Anthropic accounts per developer or environment.

Point ChatAnthropic's base URL at the SubToAPI endpoint and keep the rest of your agent code unchanged. See /docs/quickstart for the setup and /docs/tools for the tool-use request format if you want to compare it against what LangChain generates. Plans start at €9/month on the Solo tier, with Team (€19/seat) and Scale (€49/seat) tiers for multi-developer setups — check /pricing for details, or start with the free trial at /signup.

Questions

Does LangChain support Claude's native tool-calling format, or does it simulate tools with prompting? LangChain's ChatAnthropic uses Claude's native tool-use API — it sends tool schemas in the request and parses structured tool-call responses, rather than relying on prompt-based function emulation.

Can I use a Claude API proxy like SubToAPI instead of a raw Anthropic key with LangChain? Yes — ChatAnthropic accepts a custom base URL, so you can point it at an API that implements the same Messages API shape, such as SubToAPI's /v1/messages endpoint, without changing your agent or tool code.

Why does my LangChain Claude agent loop without calling tools? This usually means the tool descriptions are too vague or the system prompt doesn't clearly instruct the model to use tools. Add explicit, example-driven docstrings to each tool and confirm temperature is low for predictable tool selection.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →