Claude Code SDK - LangChain Adapter
October 1, 2025 Β· View on GitHub
Use Claude via your Claude Code subscription ($20/month) as an LLM model in LangChain to prototype agentic applications WITHOUT additional API fees!
π― Purpose
This adapter allows you to use your existing Claude Code subscription as a backend for LangChain, enabling you to:
- β Prototype LangChain applications for free (via your subscription)
- β Test agent ideas without worrying about API costs
- β Easily migrate to the official API in production
π¦ Installation
Via GitHub (Recommended)
# Latest version from main branch
pip install git+https://github.com/kapp667/claude-code-sdk-langchain.git
# Specific version tag
pip install git+https://github.com/kapp667/claude-code-sdk-langchain.git@v0.1.0
Via Pixi
# In your pixi.toml
[pypi-dependencies]
claude-code-langchain = { git = "https://github.com/kapp667/claude-code-sdk-langchain.git" }
# Or specific version
claude-code-langchain = { git = "https://github.com/kapp667/claude-code-sdk-langchain.git", tag = "v0.1.0" }
Via GitHub Release (Manual)
- Download wheel from Releases
- Install:
pip install claude_code_langchain-0.1.0-py3-none-any.whl
Prerequisites
The Claude Code CLI must be installed and configured:
npm install -g @anthropic-ai/claude-code
π Quick Start
from claude_code_langchain import ClaudeCodeChatModel
from langchain_core.prompts import ChatPromptTemplate
# Create the model (uses your Claude Code subscription)
model = ClaudeCodeChatModel(
model="claude-sonnet-4-20250514",
temperature=0.7
)
# Simple usage
response = model.invoke("What is LangChain?")
print(response.content)
# In a LangChain chain
prompt = ChatPromptTemplate.from_messages([
("system", "You are an expert in {domain}"),
("human", "{question}")
])
chain = prompt | model
result = chain.invoke({
"domain": "Python",
"question": "How to create a REST API?"
})
π Streaming
# Response streaming
for chunk in model.stream("Tell me a story"):
print(chunk.content, end="")
# Async streaming
async for chunk in model.astream("List 5 ideas"):
print(chunk.content, end="")
π Full LangChain Integration
The adapter supports all LangChain features:
- β Synchronous/asynchronous invocation
- β Streaming
- β Batch processing
- β LCEL (LangChain Expression Language) integration
- β Chains and agents
π Examples
See the examples/ folder for complete examples:
basic_usage.py- Various usage examples- Tests in
specs/- Pragmatic flow tests
π§ͺ Tests
# Run flow tests
python specs/flow_basic_chat_test.py
python specs/flow_langchain_integration_test.py
# Or with pytest
pytest specs/
π Migration to Production
When you're ready for production, simply replace:
# Development (your subscription)
from claude_code_langchain import ClaudeCodeChatModel
model = ClaudeCodeChatModel(model="claude-sonnet-4-20250514")
# Production (official API)
from langchain_anthropic import ChatAnthropic
model = ChatAnthropic(model="claude-3-opus-20240229", api_key="sk-...")
The rest of your code remains identical!
βοΈ Configuration
model = ClaudeCodeChatModel(
model="claude-sonnet-4-20250514", # Claude Sonnet 4 model
temperature=0.7, # β οΈ NOT SUPPORTED (value ignored)
max_tokens=2000, # β οΈ NOT SUPPORTED (value ignored)
system_prompt="You are an expert...", # System prompt
permission_mode="default", # Claude Code permission mode
)
ποΈ Architecture
LangChain App
β
ClaudeCodeChatModel (this adapter)
β
claude-code-sdk (Python SDK)
β
Claude Code CLI
β
Claude (via your subscription)
β οΈ Limitations and Warnings
This section documents the adapter's known limitations. These limitations are intentional - they represent the trade-offs between cost-free prototyping and production API. The adapter emits runtime warnings to alert you when using unsupported features.
π‘οΈ Temperature and Max_Tokens
Limitation: The Claude Code CLI does not support temperature and max_tokens parameters.
Behavior:
- These parameters are accepted for API compatibility (prevents breaking your code)
- They have no effect on generation
- A warning is emitted during initialization if you specify non-default values
For Development (Claude Code):
model = ClaudeCodeChatModel() # Uses model's default values
# β οΈ temperature=0.7 and max_tokens=2000 will have no effect
For Production (with parameter control):
from langchain_anthropic import ChatAnthropic
model = ChatAnthropic(
temperature=0.7, # β
Works in production
max_tokens=1000, # β
Works in production
api_key=os.getenv("ANTHROPIC_API_KEY")
)
Why? The Claude Code CLI does not expose --temperature or --max-tokens flags. Full investigation: docs/TEMPERATURE_MAX_TOKENS_INVESTIGATION.md
Solution: If you need temperature control or token limits during development, use the production API directly with your Anthropic API key.
πΌοΈ Vision and Multimodal Content
Limitation: Images and other non-text content are not supported.
Behavior:
- Text is extracted and processed
- Images are silently ignored
- A warning is emitted when an image is detected in messages
Example:
messages = [
HumanMessage(content=[
{"type": "text", "text": "Describe this image"},
{"type": "image_url", "image_url": {"url": "https://..."}} # β οΈ Ignored
])
]
# Warning: Image content detected but NOT SUPPORTED by Claude Code SDK
Why? The Claude Code SDK does not handle multimodal messages via the CLI.
Solution: For vision tasks, use ChatAnthropic with the production API which natively supports vision.
π Async Support
Full Support β : The adapter now fully supports asynchronous operations thanks to an anyio isolation fix.
β Sync Operations (100%)
model.invoke()- Full supportmodel.stream()- Full supportmodel.batch()- Full support- Chains with sync execution - Full support
β Async Operations (100%)
model.ainvoke()- Full supportmodel.astream()- Full streaming with anyio isolationchain.astream()with parsers - Full support (anyio/asyncio fix via queue)- Stream cancellation - Supported via break or cancel()
Tests: 16/16 functional tests passing (100%) β
Technical note: A RuntimeError: cancel scope in different task issue with LangChain parsers was resolved via a queue isolation pattern. Details: CLAUDE.md
π§ System Prompt - Source Conflict
Limitation: If you specify a system_prompt in the constructor AND a SystemMessage in the messages, there is precedence.
Behavior:
SystemMessagein messages takes precedence- Constructor
system_promptis ignored - A warning is emitted if both are present
Why? To avoid having two contradictory system prompts and ensure predictable behavior.
β‘ Other Limitations
| Limitation | Impact | Solution |
|---|---|---|
| Tool calls | No native support | Can be simulated via explicit prompting |
| Latency | +10-30% vs direct API | Acceptable trade-off for prototyping |
| CLI Required | Requires npm install -g @anthropic-ai/claude-code | One-time installation |
| Quotas | Limited by your Claude Code subscription | Switch to production API if exceeded |
π Behavioral Neutrality
Overall Score: ~95%
The adapter maintains high behavioral neutrality with the production API:
- β Messages and formats: 100% compatible
- β Streaming and async: 100% compatible
- β οΈ Sampling parameters: Not supported (temperature, max_tokens)
- β οΈ Vision: Not supported
- β Core behavior: Identical to ChatAnthropic
Validation: 3 specialized agents analyzed the implementation. Full report: docs/VALIDATION_REPORT_2025-09-30.md
π‘ Recommendations
For Prototyping (this adapter):
- β Jupyter notebooks
- β CLI test scripts
- β Basic and complex LangChain chains
- β Simple agents
- β Rapid experimentation
For Production (ChatAnthropic):
- β Applications requiring temperature control
- β Vision/multimodal tasks
- β Large-scale deployments
- β Precise generation control
- β Native tool calls
Migration: Changing one line of code is sufficient (see Migration Path section above).
π€ Contributing
Contributions are welcome! Feel free to:
- Add features
- Improve documentation
- Report bugs
- Propose optimizations
π License
MIT
π Acknowledgments
- Anthropic for Claude and Claude Code
- LangChain for the framework
- StΓ©phane Wootha Richard for orchestration
Note: This adapter is perfect for prototyping and development. For large-scale production, consider the official Anthropic API.