Metadata-Version: 2.4
Name: langchain-claude-agent-sdk
Version: 0.1.0
Summary: LangChain chat-model adapter for Anthropic's Claude Agent SDK
Project-URL: Homepage, https://codeberg.org/brhodes/langchain-claude-agent-sdk
Project-URL: Repository, https://codeberg.org/brhodes/langchain-claude-agent-sdk
Project-URL: Issues, https://codeberg.org/brhodes/langchain-claude-agent-sdk/issues
Project-URL: Changelog, https://codeberg.org/brhodes/langchain-claude-agent-sdk/src/branch/main/CHANGELOG.md
Project-URL: Documentation, https://codeberg.org/brhodes/langchain-claude-agent-sdk/src/branch/main/README.md
Author-email: Blake Rhodes <brhodes@linux.com>
License: MIT
License-File: LICENSE
Keywords: anthropic,claude,claude-agent-sdk,claude-code,langchain,llm
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: claude-agent-sdk<0.3.0,>=0.2.86
Requires-Dist: langchain-core<2.0.0,>=1.4.0
Requires-Dist: pydantic<3.0.0,>=2.7.4
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: commitizen>=4.0; extra == 'dev'
Requires-Dist: coverage[toml]>=7.6; extra == 'dev'
Requires-Dist: langchain-tests>=1.1.9; extra == 'dev'
Requires-Dist: mypy>=1.13.0; extra == 'dev'
Requires-Dist: pre-commit>=4.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest-socket>=0.7; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.8.0; extra == 'dev'
Requires-Dist: twine>=5.1; extra == 'dev'
Description-Content-Type: text/markdown

# langchain-claude-agent-sdk

A LangChain `BaseChatModel` backed by Anthropic's official
[`claude-agent-sdk`](https://github.com/anthropics/claude-agent-sdk-python).

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`](https://pypi.org/project/langchain-tests/)
> standard conformance harness — and the package is usable in real
> LangChain / LangGraph workloads today. See [`PHASES.md`](./PHASES.md)
> for the full phase tracker and [`CHANGELOG.md`](./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

```bash
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.

```bash
# 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

```python
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:

```python
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`](https://pypi.org/project/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
  `ThinkingBlock`s).

---

## 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`](./CHANGELOG.md) — release notes, Keep a Changelog format.
- [`CONTRIBUTING.md`](./CONTRIBUTING.md) — dev setup, test/lint conventions,
  commit style, release process.
- [`SECURITY.md`](./SECURITY.md) — vulnerability reporting and supported
  versions.
- [`CODE_OF_CONDUCT.md`](./CODE_OF_CONDUCT.md) — Contributor Covenant 2.1.
- [`PHASES.md`](./PHASES.md) — phase tracker; the source of truth for
  what's done and what's next across development sessions.
- [`DESIGN.md`](./DESIGN.md) — historical design exploration that preceded
  this package. Preserved for context only.

---

## Development

```bash
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`](./CONTRIBUTING.md).

---

## License

[MIT](./LICENSE). Copyright © 2026 Blake Rhodes.

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