3.0 Core Components
本章介绍 LangChain 的核心组件,它们是构建 AI Agent 应用的基础模块。
组件概览
LangChain 的核心组件相互协作,构成完整的 Agent 系统:
┌─────────────────────────────────────────────────────────┐
│ Agent │
│ ┌─────────────────────────────────────────────────┐ │
│ │ System Prompt │ │
│ └─────────────────────────────────────────────────┘ │
│ │ │
│ ┌──────────┐ ┌──────────────┐ ┌───────────┐ │
│ │ Model │◄───│ Messages │───►│ Tools │ │
│ └──────────┘ └──────────────┘ └───────────┘ │
│ │ │ │ │
│ ▼ ▼ ▼ │
│ ┌──────────┐ ┌──────────────┐ ┌───────────┐ │
│ │ Streaming│ │ Memory │ │ Structured│ │
│ │ │ │ │ │ Output │ │
│ └──────────┘ └──────────────┘ └───────────┘ │
└─────────────────────────────────────────────────────────┘核心组件速览
3.1 Agents - 代理
Agent 是 LangChain 的核心,将模型与工具结合,实现自主推理和任务执行。
python
from langchain.agents import create_agent
agent = create_agent(
"gpt-4o",
tools=[search, calculate],
system_prompt="你是一个有帮助的助手"
)核心特性:ReAct 模式、多工具调用、自定义状态、中间件支持
3.2 Models - 模型
统一的模型接口,支持 OpenAI、Anthropic、Google 等主流提供商。
python
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="gpt-4o", temperature=0.7)
response = model.invoke("你好")三种调用方式:invoke(同步)、stream(流式)、batch(批量)
3.3 Messages - 消息
对话的基本单元,包含角色、内容和元数据。
python
from langchain_core.messages import SystemMessage, HumanMessage
messages = [
SystemMessage(content="你是助手"),
HumanMessage(content="你好")
]四种类型:SystemMessage、HumanMessage、AIMessage、ToolMessage
3.4 Tools - 工具
扩展 Agent 能力,让 AI 能够执行实际操作。
python
from langchain_core.tools import tool
@tool
def get_weather(city: str) -> str:
"""获取天气信息"""
return f"{city}:晴,25度"关键点:类型提示必需、描述帮助模型理解、支持复杂 Schema
3.5 Short-term Memory - 短期记忆
让 Agent 在对话中保持上下文记忆。
python
from langgraph.checkpoint.memory import InMemorySaver
agent = create_agent(
"gpt-4o",
tools=[my_tools],
checkpointer=InMemorySaver()
)管理策略:消息修剪、消息删除、消息摘要
3.6 Streaming - 流式输出
实时输出,提升用户体验。
python
for event in agent.stream({"messages": [...]}, stream_mode="updates"):
print(event)四种模式:updates(步骤)、messages(Token)、custom(自定义)、组合模式
3.7 Structured Output - 结构化输出
让 Agent 返回固定格式的数据。
python
from pydantic import BaseModel
class Result(BaseModel):
summary: str
score: float
model = model.with_structured_output(Result)Schema 支持:Pydantic、dataclass、TypedDict、JSON Schema
组件关系图
用户输入
│
▼
┌─────────┐ ┌──────────┐
│ Messages│────►│ Agent │
└─────────┘ └────┬─────┘
│
┌───────────┼───────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Model │ │ Tools │ │ Memory │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
▼ ▼ ▼
┌─────────────────────────────────┐
│ Streaming / Output │
└─────────────────────────────────┘
│
▼
最终响应本章内容
| 章节 | 内容 | 核心概念 |
|---|---|---|
| 3.1 Agents | 代理 | ReAct、工具调用、中间件 |
| 3.2 Models | 模型 | 统一接口、invoke/stream/batch |
| 3.3 Messages | 消息 | 四种类型、多模态、元数据 |
| 3.4 Tools | 工具 | @tool 装饰器、Schema、运行时 |
| 3.5 Short-term Memory | 短期记忆 | Checkpointer、修剪、摘要 |
| 3.6 Streaming | 流式输出 | 四种模式、实时更新 |
| 3.7 Structured Output | 结构化输出 | Pydantic、验证、重试 |
快速示例:完整 Agent
python
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langgraph.checkpoint.memory import InMemorySaver
from pydantic import BaseModel
# 1. 定义工具
@tool
def search(query: str) -> str:
"""搜索信息"""
return f"关于 {query} 的搜索结果..."
# 2. 定义结构化输出
class Answer(BaseModel):
response: str
confidence: float
# 3. 创建 Agent(整合所有组件)
agent = create_agent(
model=ChatOpenAI(model="gpt-4o"),
tools=[search],
system_prompt="你是一个有帮助的助手",
checkpointer=InMemorySaver(),
)
# 4. 流式调用
for event in agent.stream(
{"messages": [{"role": "user", "content": "AI 的最新进展是什么?"}]},
config={"configurable": {"thread_id": "user-001"}},
stream_mode="updates"
):
print(event)学习路径建议
- 入门:先学习 3.1 Agents 和 3.2 Models
- 基础:理解 3.3 Messages 和 3.4 Tools
- 进阶:掌握 3.5 Memory 和 3.6 Streaming
- 高级:深入 3.7 Structured Output
上一章:2.3 Philosophy
下一节:3.1 Agents