Skip to main content

LangChain chat-model adapter for Anthropic's Claude Agent SDK

Project description

langchain-claude-agent-sdk

A LangChain BaseChatModel backed by Anthropic's official claude-agent-sdk.

Lets LangChain and LangGraph code run against the bundled claude CLI so usage counts against your local Claude authentication — Max/Pro subscription or API key — instead of per-token API billing.

Project status: alpha (0.1.0). The core surface is complete — non-streaming invoke/ainvoke, streaming astream, bind_tools for both built-in Claude Code tools and custom tools via in-process MCP, and the langchain-tests standard conformance harness — and the package is usable in real LangChain / LangGraph workloads today. See PHASES.md for the full phase tracker and CHANGELOG.md for release notes.


Why this package

The LangChain ecosystem implicitly assumes per-token API billing. Modest multi-agent workflows can burn meaningful money against that model. The same workflow run under a Claude Max subscription is effectively free at the same volume — but the LangChain wiring assumes API access.

ChatClaudeAgent is a drop-in chat model that routes calls through the local claude CLI via claude-agent-sdk. Existing LangChain / LangGraph code keeps working; the bill changes shape.

Audience. LangChain users who already pay for Claude; researchers building multi-agent designs at non-trivial scale; anyone whose LangChain bill has caught their attention.


Installation

pip install langchain-claude-agent-sdk
# or
uv add langchain-claude-agent-sdk

You must also have the claude CLI installed and authenticated locally. The Agent SDK invokes it as a subprocess.

# Install the CLI (see https://docs.claude.com/en/docs/claude-code for current instructions)
npm install -g @anthropic-ai/claude-code

# Authenticate (one-time)
claude login

Credentials live in ~/.claude/.credentials.json. This package does not take an api_key; auth is delegated entirely to the CLI you already use.


Quickstart

from langchain_claude_agent_sdk import ChatClaudeAgent
from langchain_core.messages import SystemMessage, HumanMessage

model = ChatClaudeAgent()

response = model.invoke(
    [
        SystemMessage("You answer in haiku."),
        HumanMessage("What is asyncio for?"),
    ]
)
print(response.content)
print("tokens:", response.usage_metadata)
print("session:", response.response_metadata["session_id"])
print("cost (USD):", response.response_metadata["total_cost_usd"])

Async works the same:

result = await model.ainvoke([HumanMessage("hello")])

Inside an existing event loop, use ainvoke — the sync invoke will refuse to run inside a running loop rather than dispatch surprisingly to a thread pool.

Multi-turn

LangGraph and the standard RunnableWithMessageHistory patterns work out of the box. Under the hood:

  • If the most recent AIMessage in the history carries response_metadata["session_id"] (which ChatClaudeAgent always populates from the CLI's ResultMessage), the next call sets ClaudeAgentOptions.resume=<session_id> and forwards only messages after that turn. The CLI keeps real session state; prior turns are not re-billed.
  • For arbitrary user-constructed histories without a session id, prior turns are serialized as a plain-text transcript prepended to the latest HumanMessage. This is a fallback for compatibility, not the recommended path.

How this compares

langchain-claude-agent-sdk (this) langchain-claude-code (existing)
Backend Anthropic's official claude-agent-sdk Custom subprocess + JSON parsing
AIMessage.usage_metadata ✅ populated, with cache_creation / cache_read buckets ❌ omitted (LangChain contract violation)
Tool calls field AIMessage.tool_calls (standard) ❌ stashed in response_metadata (breaks LangGraph agent loops)
Multi-turn ✅ session resume + transcript fallback varies
Typed exceptions / message types ✅ from the official SDK hand-rolled
In-process MCP for custom tools ✅ via the official SDK's create_sdk_mcp_server hand-rolled
langchain-tests standard harness ✅ unit harness passes; integration harness opt-in not advertised
Streaming (astream) ✅ chunk per content block, usage on final chunk varies

If you're already on langchain-claude-code and hitting either of the correctness deltas above, this package is the migration target.


Configuration

ChatClaudeAgent constructor parameters:

Parameter Type Default Description
model str | None None Forwarded to the CLI. None lets the CLI pick.
append_system_prompt bool True If True, SystemMessage content is appended to Claude Code's tool-enabling preset so tools keep working. If False, it replaces the preset.
max_turns int | None None Cap on agent turns per call.
cwd str | None None Working directory for the CLI.
extra_options dict[str, Any] {} Escape hatch for any ClaudeAgentOptions field not exposed above.

CLI-only goodies surfaced on AIMessage.response_metadata:

  • session_id, total_cost_usd, num_turns, duration_ms, duration_api_ms, model_name, stop_reason, thinking (preserved ThinkingBlocks).

Billing and Terms of Service

This package routes traffic through your local claude CLI auth. That auth may be a Max/Pro subscription, an API key, or both. Read Anthropic's Terms of Service before redistributing. The intended audience is individuals and teams running under their own Claude authentication, not multi-tenant SaaS resellers.

Economics note (effective 2026-06-15). Per Anthropic's Agent SDK pricing announcement, Agent SDK usage draws from a separate monthly Agent SDK credit pool (Pro $20, Max 5× $100, Max 20× $200) — not unmetered Max conversation windows. Overage falls back to API metering at standard rates. Plan accordingly.


Project documents

  • CHANGELOG.md — release notes, Keep a Changelog format.
  • CONTRIBUTING.md — dev setup, test/lint conventions, commit style, release process.
  • SECURITY.md — vulnerability reporting and supported versions.
  • CODE_OF_CONDUCT.md — Contributor Covenant 2.1.
  • PHASES.md — phase tracker; the source of truth for what's done and what's next across development sessions.
  • DESIGN.md — historical design exploration that preceded this package. Preserved for context only.

Development

make install         # uv sync --extra dev
make check           # ruff + mypy + pytest unit tests
make test            # unit tests only
make test-integration  # tests marked @pytest.mark.integration (hit the real CLI)

The full developer workflow — including pre-commit hooks, Conventional Commits, and how releases are cut — is documented in CONTRIBUTING.md.


License

MIT. Copyright © 2026 Blake Rhodes.

This project is not affiliated with or endorsed by Anthropic, PBC. "Claude" and "Claude Code" are trademarks of Anthropic.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

langchain_claude_agent_sdk-0.1.0.tar.gz (49.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

langchain_claude_agent_sdk-0.1.0-py3-none-any.whl (18.6 kB view details)

Uploaded Python 3

File details

Details for the file langchain_claude_agent_sdk-0.1.0.tar.gz.

File metadata

File hashes

Hashes for langchain_claude_agent_sdk-0.1.0.tar.gz
Algorithm Hash digest
SHA256 7b15376c41e1416d14fa09f58c7d1ba9b401d5efff5476aa9203dd5f7c3cec9f
MD5 8a87c69ab619a67573fd2deda2ec6bcd
BLAKE2b-256 dbbde4631decf602c61cde1764814afe7af81a3b221c2864be0142050115bf2c

See more details on using hashes here.

File details

Details for the file langchain_claude_agent_sdk-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for langchain_claude_agent_sdk-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f9e2ab8a47f97b70736ca4f2bc60562dcaab95a47e3106421851929f3eb71694
MD5 d087219235bcd84c82abc0de4c430e2c
BLAKE2b-256 4c9894aace63c4302d31373aaf25ad5edf9017751f6962a2ae4d8cd538f76b9d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page