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.1.tar.gz (49.3 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.1-py3-none-any.whl (18.6 kB view details)

Uploaded Python 3

File details

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

File metadata

File hashes

Hashes for langchain_claude_agent_sdk-0.1.1.tar.gz
Algorithm Hash digest
SHA256 408c5108acfd7958976caf814c2bd5218ff95806681652dfbcb007106d6b242d
MD5 d23734fb68b3e01cbfe36f06de5f32ce
BLAKE2b-256 a019a3b8cc53379604e24765069f752ce84f6122ee64bfadde27d06e46fe49c4

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for langchain_claude_agent_sdk-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 dd83891e9cd954d51d2452ebbddb230d497df5fe671bc0da9ec8ec7aa6c19835
MD5 ba0d3c101b2095e3925ef2a4cc376095
BLAKE2b-256 82a2f748590918c0b41020e82742201adc6c5f87ded02721f27e3baa73511fa7

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