Home / Learn / ChatAnthropic in LangChain: import, base_url, streaming, tools and errors
Claude + LangChain. A sequence of hand-drawn chain links made from small document cards, connecting a prompt sheet to a model window and a final result.

ChatAnthropic in LangChain: import, base_url, streaming, tools and errors

ChatAnthropic from the langchain-anthropic package is LangChain's Claude chat model. It wraps the official Anthropic Python SDK, so pointing it at a gateway takes one argument, base_url, set to the host root. Everything else in your chains, agents and tools stays the same.

Install and import

terminal
pip install -U langchain-anthropic
app.py
from langchain_anthropic import ChatAnthropic

llm = ChatAnthropic(
    model="claude-sonnet-5",
    base_url="https://aiprimetech.io",           # host root: the SDK adds /v1/messages
    api_key="your_gateway_key",   # or set ANTHROPIC_API_KEY
)

print(llm.invoke("Say hello in one word.").text)
No /v1 in base_url here. The Anthropic SDK underneath appends /v1/messages itself; adding /v1 produces /v1/v1/messages and a 404 page not found.

Configure it from the environment

base_url is an alias of anthropic_api_url, and api_key an alias of anthropic_api_key. When you don't pass them, ChatAnthropic reads ANTHROPIC_API_URL first, then ANTHROPIC_BASE_URL, and the key from ANTHROPIC_API_KEY. Explicit arguments always win.

terminal
export ANTHROPIC_API_KEY=your_gateway_key
export ANTHROPIC_API_URL=https://aiprimetech.io
app.py
from langchain_anthropic import ChatAnthropic

llm = ChatAnthropic(model="claude-sonnet-5")   # picks up the gateway from the environment

Streaming

app.py
for chunk in llm.stream("Explain backpressure in two sentences."):
    print(chunk.text, end="", flush=True)

.text collects only the text blocks of each chunk, so it stays clean when the model also emits thinking or tool-use blocks. Use streaming for long answers: a long non-streaming request is the usual cause of timeouts.

Tools and structured output

tools.py
from langchain_core.tools import tool

@tool
def get_time(city: str) -> str:
    """Return the current local time in a city."""
    return "12:00"

msg = llm.bind_tools([get_time]).invoke("What time is it in Tokyo?")
print(msg.tool_calls)
structured.py
from pydantic import BaseModel

class Weather(BaseModel):
    city: str
    temperature_c: float

print(llm.with_structured_output(Weather).invoke("It is 21 degrees in Lisbon today."))

Retries, timeouts and max_tokens

max_retries defaults to 2, the same as the Anthropic SDK, which retries connection errors, 429 and 5xx responses. timeout (alias of default_request_timeout) is in seconds. If you leave max_tokens unset, it comes from the model's profile.

app.py
llm = ChatAnthropic(
    model="claude-sonnet-5",
    base_url="https://aiprimetech.io",
    max_retries=4,
    timeout=120,
    max_tokens=8000,
)

For batches, cap parallelism so you stay inside your key's concurrency: llm.batch(inputs, config={"max_concurrency": 3}).

The ChatOpenAI alternative

If your code is standardised on ChatOpenAI, the gateway's OpenAI-compatible endpoint serves Claude too. This route wants /v1 on the end, the opposite of ChatAnthropic.

app.py
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="claude-sonnet-5", base_url="https://aiprimetech.io/v1", api_key="your_gateway_key")

Prefer ChatAnthropic for Claude: it keeps native features such as prompt caching and thinking blocks.

Troubleshooting

What you see Cause Fix
404 page not found/v1 in ChatAnthropic's base_urlUse the host root, https://aiprimetech.io
Model "..." is not supportedAn ID your key's group doesn't serve, or an old dated nameUse a current ID from the table below
AuthenticationErrorANTHROPIC_API_KEY empty in the running process, or a key for another endpointPass api_key= explicitly to test
RateLimitError: Concurrency limit exceededToo many parallel calls (batch, async gather)max_concurrency in the batch config
APITimeoutErrorLong non-streaming generationsStream, or raise timeout
Model ID Use it for
claude-sonnet-5Default for coding and agent work: fast, strong, mid-priced.
claude-opus-5-5Harder reasoning, large refactors, long agent runs.
claude-fable-5-1Most capable and most expensive; save it for the hardest tasks.
claude-haiku-4-5Cheap and quick: titles, summaries, classification, small steps.

Frequently asked questions

How do I import ChatAnthropic?
pip install -U langchain-anthropic, then from langchain_anthropic import ChatAnthropic.
Does ChatAnthropic's base_url need /v1?
No. Pass the host root, e.g. https://aiprimetech.io; the Anthropic SDK appends /v1/messages. ChatOpenAI is the opposite and needs /v1.
Which environment variables does ChatAnthropic read?
ANTHROPIC_API_KEY for the key, and ANTHROPIC_API_URL, then ANTHROPIC_BASE_URL, for the endpoint when base_url isn't passed.
Is base_url the same as anthropic_api_url?
Yes. base_url is an alias of anthropic_api_url, and api_key is an alias of anthropic_api_key.
Start using Claude in minutes

Get an API key — no Anthropic account or waitlist required.

Get your API key

AI Prime Tech is an independent API gateway. It is not affiliated with, endorsed by, or a reseller of Anthropic. Claude and related model names are trademarks of their respective owners.

More Claude API guides

How to Get a Claude API KeyClaude API Pricing, ExplainedThe Cheapest Way to Use the Claude APIUnlimited Cursor with the Claude APIUnlimited Claude Code AccessClaude API Gateway vs. Anthropic DirectUsing Claude Through an OpenAI-Compatible APIClaude models explained: a Claude model comparison of Claude Opus vs Sonnet vs Haiku vs Fable — all Claude API models, Anthropic model names and prices (2026)Paying for the Claude API with CryptoClaude API Access Without a WaitlistHow to Reduce Claude Token UsageUnlimited Cline with the Claude APIUnlimited Roo Code with the Claude APIUnlimited Claude in JetBrains IDEsUnlimited Aider with the Claude APIUnlimited Claude in VS CodeOpenCode config for Claude: opencode.json setup, models and common errorsRunning an Unlimited Hermes Agent on ClaudeRunning Unlimited OpenClaw on ClaudeWhat an Anthropic-Compatible API MeansClaude Code API key — ANTHROPIC_API_KEY: how to get it, set it up, and when to use claude setup-token insteadClaude Code API Costs — Pricing and How to Cut ThemClaude API errors explained: server error 500, overloaded 529, rate limit 429, bad request 400 — and the fix for eachHow to buy Claude API credits — and why a Claude credit beats any "buy Claude account" offerClaude free API: is there a free Claude API key, and what is actually free in 2026?Claude API vs Claude Pro/Max Subscription — Which to ChooseRunning the Codex CLI on ClaudeConnecting Claude to n8nRouting LiteLLM to ClaudeUsing Claude in Kilo CodeBring Claude into GitHub CopilotWire Zed to Claude Through the GatewayConnect Cherry Studio to ClaudeAnthropic Python SDK: install, set base_url, stream, and handle errorsClaude with the Vercel AI SDK: createAnthropic baseURL, streaming and fixesRun Factory Droid on ClaudeThe Claude Code API, ExplainedIntegrating the Claude API Into Your ApplicationHow to get unlimited Claude usage — and why there is no "Claude Code cracked"