LangChain is an open-source framework for building LLM-powered agents and applications.
Installation
Install LangChain using uv (recommended, requires Python 3.10+):
# 安装核心包
uv add langchain
# 安装模型提供商集成
uv add langchain-anthropic # Anthropic/Claude
uv add langchain-openai # OpenAI
Quick Reference
Core Workflow
用户查询 -> create_agent() -> ReAct 循环 -> Tool 调用 -> 返回结果
Create an Agent
See Agent Basics
from langchain.agents import create_agent
agent = create_agent(
model="claude-sonnet-4-5-20250929",
tools=[get_weather],
system_prompt="You are a helpful assistant",
)
# 运行 agent
result = agent.invoke(
{"messages": [{"role": "user", "content": "what is the weather in sf"}]}
)
Define a Tool
See Tool Basics
from langchain.tools import tool
@tool
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
Access Runtime Context
Use ToolRuntime to access state, context, store:
from langchain.tools import tool, ToolRuntime
from dataclasses import dataclass
@dataclass
class Context:
user_id: str
@tool
def get_user_location(runtime: ToolRuntime[Context]) -> str:
"""Retrieve user location based on user ID."""
user_id = runtime.context.user_id
return "Florida" if user_id == "1" else "SF"
Manage Memory
See Short-term Memory See Long-term Memory
from langgraph.checkpoint.memory import InMemorySaver
agent = create_agent(
model,
tools,
checkpointer=InMemorySaver(), # 短期记忆
)
# 使用 thread_id 维护会话
config = {"configurable": {"thread_id": "1"}}
agent.invoke({"messages": [...]}, config)
Add Middleware
from langchain.agents.middleware import before_model, after_model
@before_model
def trim_messages(state, runtime):
# 消息修剪逻辑
return None
Advanced Topics
| Topic | Documentation | Description |
|---|---|---|
| Streaming | Streaming | Real-time output streaming updates |
| Structured Output | Structured Output | Pydantic/dataclass output format |
| Runtime | Runtime | ToolRuntime and context access |
| Guardrails | Guardrails | PII detection, content filtering |
| MCP | MCP | Model Context Protocol integration |
Integration Topics
| Topic | Documentation | Description |
|---|---|---|
| Models | Models | Multi-provider model initialization |
| Messages | Messages | Message types and content blocks |
| Retrieval | Retrieval | RAG and knowledge base construction |
Key Concepts
Agent
The core abstraction of LangChain 1.0, built on LangGraph. Use create_agent() to create.
Tool
Use the @tool decorator to define. Optional ToolRuntime to access state, context, and store.
Memory
- Checkpointer: Short-term session memory (InMemorySaver, PostgresSaver)
- Store: Long-term persistent storage (InMemoryStore)
Middleware
Decorator-style extension mechanism:
@before_model- Pre-model call processing@after_model- Post-model call processing@wrap_tool_call- Tool call wrapping@dynamic_prompt- Dynamic system prompt
Common Patterns
Basic Agent
from langchain.agents import create_agent
agent = create_agent(
model="claude-sonnet-4-5-20250929",
tools=[my_tool],
system_prompt="You are helpful.",
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "hello"}]}
)
Agent with Memory (session persistence)
from langgraph.checkpoint.memory import InMemorySaver
agent = create_agent(
model="claude-sonnet-4-5-20250929",
tools=[my_tool],
checkpointer=InMemorySaver(),
)
# 使用 thread_id 标识会话
config = {"configurable": {"thread_id": "1"}}
agent.invoke(
{"messages": [{"role": "user", "content": "My name is Bob"}]},
config
)
agent.invoke(
{"messages": [{"role": "user", "content": "What's my name?"}]},
config
)
Production Memory (using a database)
from langgraph.checkpoint.postgres import PostgresSaver
DB_URI = "postgresql://postgres:postgres@localhost:5432/postgres"
with PostgresSaver.from_conn_string(DB_URI) as checkpointer:
checkpointer.setup() # 自动创建表
agent = create_agent(
model="claude-sonnet-4-5-20250929",
tools=[my_tool],
checkpointer=checkpointer,
)
Agent with Context (Runtime Context)
from dataclasses import dataclass
from langchain.tools import tool, ToolRuntime
@dataclass
class Context:
user_id: str
@tool
def get_user_info(runtime: ToolRuntime[Context]) -> str:
"""Get user information."""
user_id = runtime.context.user_id
return f"User ID: {user_id}"
agent = create_agent(
model="claude-sonnet-4-5-20250929",
tools=[get_user_info],
context_schema=Context,
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "get my info"}]},
context=Context(user_id="user_123")
)
Agent with Structured Output
from dataclasses import dataclass
from langchain.agents.structured_output import ToolStrategy
@dataclass
class Response:
answer: str
confidence: float
agent = create_agent(
model="claude-sonnet-4-5-20250929",
tools=[my_tool],
response_format=ToolStrategy(Response),
)
result = agent.invoke(
{"messages": [{"role": "user", "content": "what is 2+2?"}]}
)
print(result['structured_response'])
# Response(answer="4", confidence=1.0)
Complete Example (production-grade Agent)
from dataclasses import dataclass
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain.tools import tool, ToolRuntime
from langgraph.checkpoint.memory import InMemorySaver
from langchain.agents.structured_output import ToolStrategy
@dataclass
class Context:
user_id: str
@dataclass
class ResponseFormat:
answer: str
confidence: float | None = None
@tool
def get_weather(city: str) -> str:
"""Get weather for a city."""
return f"Sunny in {city}"
@tool
def get_user_location(runtime: ToolRuntime[Context]) -> str:
"""Get user's location."""
return "San Francisco" if runtime.context.user_id == "1" else "Unknown"
# 配置模型
model = init_chat_model(
"claude-sonnet-4-5-20250929",
temperature=0.5,
max_tokens=1000
)
# 创建 agent
agent = create_agent(
model=model,
system_prompt="You are a weather assistant.",
tools=[get_weather, get_user_location],
context_schema=Context,
response_format=ToolStrategy(ResponseFormat),
checkpointer=InMemorySaver(),
)
# 运行 agent
config = {"configurable": {"thread_id": "1"}}
result = agent.invoke(
{"messages": [{"role": "user", "content": "What's the weather?"}]},
config=config,
context=Context(user_id="1")
)
Resource Links
- Core Concepts - LangChain Overview
- Quick Start - Create an Agent in 10 lines of code
- Official Documentation
- API Reference