## 1. 引言:为什么需要 AI 智能体
传统的大语言模型(LLM)像一个知识渊博的「百科全书」------它能回答你的问题,但本质上是静态的:无法主动查询最新信息、不能操作外部系统、更谈不上自主完成多步骤任务。AI 智能体(Agent)的出现打破了这一边界,它为模型装上了「手和脚」,使其能够调用 API、搜索数据库、执行代码,甚至编排多个模型协同完成复杂项目。
当你让 ChatGPT 查询天气时,它调用了函数;当你让 AutoGPT 编写并部署一个网站时,它实际上是在循环执行「思考→行动→观察」的推理链路。这就是智能体的核心价值:从"能说"到"能做"。
本文将采取"硬核"路线------不只讲概念,更从底层架构出发,逐一拆解 AI 智能体的五大核心模块(感知、记忆、规划、行动、反馈),并给出可直接运行的 Python 代码实现。我们会在向量数据库上构建长期记忆、用 JSON Schema 注册工具链、实现 ReAct 推理循环,最终组装一个可落地的博客写作智能体。
无论你是在用 LangChain、LlamaIndex 还是自研框架,这些底层原理都将帮助你真正理解并调优自己的智能体系统。
2. AI 智能体的核心组件
一个生产级 AI 智能体通常由以下模块组成,它们相互协作形成闭环:
#mermaid-svg-FuvLGjz1b4g46Bp9{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-FuvLGjz1b4g46Bp9 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-FuvLGjz1b4g46Bp9 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-FuvLGjz1b4g46Bp9 .error-icon{fill:#552222;}#mermaid-svg-FuvLGjz1b4g46Bp9 .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-FuvLGjz1b4g46Bp9 .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-FuvLGjz1b4g46Bp9 .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-FuvLGjz1b4g46Bp9 .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-FuvLGjz1b4g46Bp9 .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-FuvLGjz1b4g46Bp9 .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-FuvLGjz1b4g46Bp9 .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-FuvLGjz1b4g46Bp9 .marker{fill:#333333;stroke:#333333;}#mermaid-svg-FuvLGjz1b4g46Bp9 .marker.cross{stroke:#333333;}#mermaid-svg-FuvLGjz1b4g46Bp9 svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-FuvLGjz1b4g46Bp9 p{margin:0;}#mermaid-svg-FuvLGjz1b4g46Bp9 .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-FuvLGjz1b4g46Bp9 .cluster-label text{fill:#333;}#mermaid-svg-FuvLGjz1b4g46Bp9 .cluster-label span{color:#333;}#mermaid-svg-FuvLGjz1b4g46Bp9 .cluster-label span p{background-color:transparent;}#mermaid-svg-FuvLGjz1b4g46Bp9 .label text,#mermaid-svg-FuvLGjz1b4g46Bp9 span{fill:#333;color:#333;}#mermaid-svg-FuvLGjz1b4g46Bp9 .node rect,#mermaid-svg-FuvLGjz1b4g46Bp9 .node circle,#mermaid-svg-FuvLGjz1b4g46Bp9 .node ellipse,#mermaid-svg-FuvLGjz1b4g46Bp9 .node polygon,#mermaid-svg-FuvLGjz1b4g46Bp9 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-FuvLGjz1b4g46Bp9 .rough-node .label text,#mermaid-svg-FuvLGjz1b4g46Bp9 .node .label text,#mermaid-svg-FuvLGjz1b4g46Bp9 .image-shape .label,#mermaid-svg-FuvLGjz1b4g46Bp9 .icon-shape .label{text-anchor:middle;}#mermaid-svg-FuvLGjz1b4g46Bp9 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-FuvLGjz1b4g46Bp9 .rough-node .label,#mermaid-svg-FuvLGjz1b4g46Bp9 .node .label,#mermaid-svg-FuvLGjz1b4g46Bp9 .image-shape .label,#mermaid-svg-FuvLGjz1b4g46Bp9 .icon-shape .label{text-align:center;}#mermaid-svg-FuvLGjz1b4g46Bp9 .node.clickable{cursor:pointer;}#mermaid-svg-FuvLGjz1b4g46Bp9 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-FuvLGjz1b4g46Bp9 .arrowheadPath{fill:#333333;}#mermaid-svg-FuvLGjz1b4g46Bp9 .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-FuvLGjz1b4g46Bp9 .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-FuvLGjz1b4g46Bp9 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-FuvLGjz1b4g46Bp9 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-FuvLGjz1b4g46Bp9 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-FuvLGjz1b4g46Bp9 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-FuvLGjz1b4g46Bp9 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-FuvLGjz1b4g46Bp9 .cluster text{fill:#333;}#mermaid-svg-FuvLGjz1b4g46Bp9 .cluster span{color:#333;}#mermaid-svg-FuvLGjz1b4g46Bp9 div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-FuvLGjz1b4g46Bp9 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-FuvLGjz1b4g46Bp9 rect.text{fill:none;stroke-width:0;}#mermaid-svg-FuvLGjz1b4g46Bp9 .icon-shape,#mermaid-svg-FuvLGjz1b4g46Bp9 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-FuvLGjz1b4g46Bp9 .icon-shape p,#mermaid-svg-FuvLGjz1b4g46Bp9 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-FuvLGjz1b4g46Bp9 .icon-shape .label rect,#mermaid-svg-FuvLGjz1b4g46Bp9 .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-FuvLGjz1b4g46Bp9 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-FuvLGjz1b4g46Bp9 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-FuvLGjz1b4g46Bp9 :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 智能体内部
用户输入
感知模块
记忆系统
规划与推理
行动/工具执行
环境反馈
- 感知模块:负责解析用户意图,将多模态输入(文本、图像、语音)转化为智能体可理解的语义表示。在多模态场景下,需要对齐不同模态的语义空间(如图像 Caption 与用户指令的向量匹配)。
- 记忆系统:分两层设计。短期记忆基于上下文窗口维护最近几轮对话;长期记忆依赖向量嵌入(Embedding)将历史交互、领域知识存入向量数据库,供后续检索。
- 规划与推理:智能体的"大脑"。采用 ReAct(Reasoning + Acting)、Plan-and-Solve 等策略,将复杂目标拆解为可执行的原子步骤,并在执行中动态调整计划。
- 行动引擎:通过统一的工具注册与执行框架,将外部能力(API 调用、代码运行、文件操作)封装为标准工具,模型只需生成工具名和参数即可调度。
- 反馈循环:每次工具执行的结果、环境状态的变化,都会作为新的"观察"注入到模型的上下文中,驱动下一轮推理。
3. 记忆系统设计:从对话缓存到长期记忆
记忆是智能体的基础能力之一。没有记忆,智能体就像每次对话都失忆------无法积累经验、无法参考历史。我们将其分为短期记忆和长期记忆两个层次。
3.1 短期记忆
短期记忆直接利用模型的上下文窗口存储最近几轮对话,是最直接、延迟最低的方式。但上下文窗口长度有限(如 GPT-4 的 128K tokens),当对话轮次增多或单次工具返回内容过长时,必须引入滑动窗口或摘要压缩策略。
以下是滑动窗口式短期记忆的实现:
python
from typing import List, Dict
class ShortTermMemory:
def __init__(self, max_tokens: int = 4096):
self.max_tokens = max_tokens
self.history: List[Dict[str, str]] = []
def add(self, role: str, content: str):
self.history.append({"role": role, "content": content})
# 简单的 token 计数模拟:字符数 / 4(英文场景约 4 字符/token)
while sum(len(m["content"]) for m in self.history) / 4 > self.max_tokens:
self.history.pop(0) # 移除最早的消息
def get_history(self) -> List[Dict[str, str]]:
return self.history
进阶优化:生产环境中,建议采用"摘要压缩"策略------当历史消息超过阈值时,不直接丢弃,而是调用 LLM 将早期对话压缩为一段摘要,保留关键信息的同时释放窗口空间。
3.2 长期记忆与向量检索
短期记忆随会话结束而消失,而长期记忆将知识、偏好、历史交互持久化。实现方式是将文本通过 Embedding 模型转为向量,存入向量数据库(Chroma、Milvus、Pinecone 等),智能体在推理时根据语义相似度检索最相关的记忆片段,注入到当前上下文。
python
from chromadb.config import Settings
import chromadb
class LongTermMemory:
def __init__(self, collection_name: str = "agent_memory"):
self.client = chromadb.Client(Settings(anonymized_telemetry=False))
self.collection = self.client.get_or_create_collection(collection_name)
def store(self, doc_id: str, text: str, metadata: dict = None):
"""存储记忆片段。
生产环境应使用 embedding 模型生成向量,这里以文本直接存储作演示。
"""
self.collection.add(
ids=[doc_id],
documents=[text],
metadatas=[metadata or {}]
)
def retrieve(self, query: str, n_results: int = 3) -> List[str]:
"""基于语义相似度检索 top-n 记忆"""
results = self.collection.query(query_texts=[query], n_results=n_results)
return results["documents"][0] if results and results["documents"] else []
硬核提示 :生产环境务必采用
text-embedding-3-large或bge-large-zh等高质量 Embedding 模型。为提升检索精度,建议配合重排序模型(如 Cohere Rerank、BGE-Reranker)对初步召回的候选记忆进行二次排序,将最相关的片段置于上下文前列。
4. 工具调用与函数注册机制
如果说记忆是智能体的"海马体",那么工具调用就是它的"四肢"。我们将外部能力(查天气、搜网页、发邮件、执行代码)抽象为统一接口,通过 JSON Schema(或等效的结构化描述)告知模型:你有哪些工具可用、各自需要什么参数、返回什么结果。模型只需生成结构化的调用指令,由宿主程序执行并返回结果。
4.1 工具定义与注册
以下实现基于 Pydantic 定义工具参数 Schema,并构建一个可扩展的工具注册中心:
python
from pydantic import BaseModel
from typing import Callable, Any
import json
class ToolParameter(BaseModel):
name: str
type: str
description: str
required: bool = True
class ToolDefinition(BaseModel):
name: str
description: str
parameters: list[ToolParameter]
class Tool:
def __init__(self, definition: ToolDefinition, func: Callable):
self.definition = definition
self.func = func
def execute(self, **kwargs) -> Any:
return self.func(**kwargs)
class ToolRegistry:
def __init__(self):
self.tools: dict[str, Tool] = {}
def register(self, tool: Tool):
self.tools[tool.definition.name] = tool
def get_tool_schemas(self) -> list[dict]:
"""生成 OpenAI Function Calling 兼容的 tools 描述"""
schemas = []
for tool in self.tools.values():
schema = {
"name": tool.definition.name,
"description": tool.definition.description,
"parameters": {
"type": "object",
"properties": {
p.name: {"type": p.type, "description": p.description}
for p in tool.definition.parameters
},
"required": [p.name for p in tool.definition.parameters if p.required]
}
}
schemas.append(schema)
return schemas
def execute(self, name: str, **kwargs) -> Any:
if name not in self.tools:
raise ValueError(f"工具 {name} 未注册")
return self.tools[name].execute(**kwargs)
此设计的优势在于:新增工具只需定义 Schema + 绑定函数,无需改动注册中心代码,符合开闭原则。get_tool_schemas() 输出的格式可直接喂给 OpenAI / Anthropic 等 API。
4.2 示例:构建一个天气查询工具
python
def get_weather(city: str) -> str:
"""模拟天气接口,生产环境替换为真实 API 调用"""
# 实际应调用 OpenWeatherMap / 和风天气 等 API
return f"{city} 当前天气:晴朗,25°C,湿度 60%。"
weather_tool = Tool(
definition=ToolDefinition(
name="get_weather",
description="查询指定城市的实时天气信息",
parameters=[ToolParameter(name="city", type="string", description="城市名称,例如 Beijing")]
),
func=get_weather
)
registry = ToolRegistry()
registry.register(weather_tool)
5. 规划与推理:ReAct 模式详解
ReAct(Reasoning + Acting)是当前主流智能体框架(LangChain、AutoGPT、OpenAI Agents SDK)的核心推理范式。它的工作原理是交替进行"思考"和"行动":
- Thought(思考):基于当前上下文和可用工具,推理下一步该做什么。
- Action(行动):生成工具调用的具体指令(工具名 + 参数)。
- Observation(观察):接收工具执行结果。
- 循环执行,直到模型认为可以给出最终答案。
#mermaid-svg-JxVWPDZ630b3DYoO{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-JxVWPDZ630b3DYoO .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-JxVWPDZ630b3DYoO .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-JxVWPDZ630b3DYoO .error-icon{fill:#552222;}#mermaid-svg-JxVWPDZ630b3DYoO .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-JxVWPDZ630b3DYoO .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-JxVWPDZ630b3DYoO .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-JxVWPDZ630b3DYoO .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-JxVWPDZ630b3DYoO .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-JxVWPDZ630b3DYoO .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-JxVWPDZ630b3DYoO .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-JxVWPDZ630b3DYoO .marker{fill:#333333;stroke:#333333;}#mermaid-svg-JxVWPDZ630b3DYoO .marker.cross{stroke:#333333;}#mermaid-svg-JxVWPDZ630b3DYoO svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-JxVWPDZ630b3DYoO p{margin:0;}#mermaid-svg-JxVWPDZ630b3DYoO .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-JxVWPDZ630b3DYoO .cluster-label text{fill:#333;}#mermaid-svg-JxVWPDZ630b3DYoO .cluster-label span{color:#333;}#mermaid-svg-JxVWPDZ630b3DYoO .cluster-label span p{background-color:transparent;}#mermaid-svg-JxVWPDZ630b3DYoO .label text,#mermaid-svg-JxVWPDZ630b3DYoO span{fill:#333;color:#333;}#mermaid-svg-JxVWPDZ630b3DYoO .node rect,#mermaid-svg-JxVWPDZ630b3DYoO .node circle,#mermaid-svg-JxVWPDZ630b3DYoO .node ellipse,#mermaid-svg-JxVWPDZ630b3DYoO .node polygon,#mermaid-svg-JxVWPDZ630b3DYoO .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-JxVWPDZ630b3DYoO .rough-node .label text,#mermaid-svg-JxVWPDZ630b3DYoO .node .label text,#mermaid-svg-JxVWPDZ630b3DYoO .image-shape .label,#mermaid-svg-JxVWPDZ630b3DYoO .icon-shape .label{text-anchor:middle;}#mermaid-svg-JxVWPDZ630b3DYoO .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-JxVWPDZ630b3DYoO .rough-node .label,#mermaid-svg-JxVWPDZ630b3DYoO .node .label,#mermaid-svg-JxVWPDZ630b3DYoO .image-shape .label,#mermaid-svg-JxVWPDZ630b3DYoO .icon-shape .label{text-align:center;}#mermaid-svg-JxVWPDZ630b3DYoO .node.clickable{cursor:pointer;}#mermaid-svg-JxVWPDZ630b3DYoO .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-JxVWPDZ630b3DYoO .arrowheadPath{fill:#333333;}#mermaid-svg-JxVWPDZ630b3DYoO .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-JxVWPDZ630b3DYoO .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-JxVWPDZ630b3DYoO .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-JxVWPDZ630b3DYoO .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-JxVWPDZ630b3DYoO .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-JxVWPDZ630b3DYoO .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-JxVWPDZ630b3DYoO .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-JxVWPDZ630b3DYoO .cluster text{fill:#333;}#mermaid-svg-JxVWPDZ630b3DYoO .cluster span{color:#333;}#mermaid-svg-JxVWPDZ630b3DYoO div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-JxVWPDZ630b3DYoO .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-JxVWPDZ630b3DYoO rect.text{fill:none;stroke-width:0;}#mermaid-svg-JxVWPDZ630b3DYoO .icon-shape,#mermaid-svg-JxVWPDZ630b3DYoO .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-JxVWPDZ630b3DYoO .icon-shape p,#mermaid-svg-JxVWPDZ630b3DYoO .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-JxVWPDZ630b3DYoO .icon-shape .label rect,#mermaid-svg-JxVWPDZ630b3DYoO .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-JxVWPDZ630b3DYoO .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-JxVWPDZ630b3DYoO .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-JxVWPDZ630b3DYoO :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} Thought: 我需要查天气
Action: get_weather(city='Beijing')
Observation: 北京晴朗,25°C
Thought: 信息足够,可以回答
Final Answer: 北京今天晴朗,25°C
为什么需要 ReAct? 因为复杂任务往往需要多步推理 + 外部信息获取。例如"比较北京和上海本周天气并推荐出行建议",模型需要:查询两地天气 → 比较 → 生成建议。仅凭单次模型调用无法完成。
5.1 提示词模板设计
模板是 ReAct 的灵魂。它限定了模型的输出格式,使得程序可以可靠地解析"思考"和"行动":
python
REACT_PROMPT = """你是一个具备工具调用能力的 AI 智能体。请使用以下工具,按指定格式逐步回答问题。
可用工具:
{tools}
回答格式(严格遵守):
Question: 用户的问题
Thought: 分析当前状态,思考下一步应采取的行动
Action: tool_name(param1=value1, param2=value2)
Observation: 工具返回的结果
... (可重复 Thought/Action/Observation 多次)
Thought: 我已获得足够信息
Final Answer: 对用户问题的最终答案
开始!
Question: {input}
{agent_scratchpad}"""
其中 {agent_scratchpad} 用于累积历史思考-行动-观察链,让模型记住已经做过什么。
5.2 解析器实现
模型生成的文本需要被精确解析以提取动作和最终答案:
python
import re
import ast
def parse_action(text: str):
"""从模型输出中提取 Action 指令"""
pattern = r"Action:\s*(.+?)\((.+)\)"
match = re.search(pattern, text)
if not match:
return None, None
tool_name = match.group(1).strip()
params_str = match.group(2).strip()
# 生产环境使用 ast.literal_eval 代替 eval,防止代码注入
try:
kwargs = ast.literal_eval(f"dict({params_str})")
except (ValueError, SyntaxError):
return tool_name, None
return tool_name, kwargs
def parse_final_answer(text: str) -> str:
"""提取 Final Answer"""
pattern = r"Final Answer:\s*(.*)"
match = re.search(pattern, text, re.DOTALL)
return match.group(1).strip() if match else None
安全提醒 :永远不要对模型输出使用
eval()。应使用ast.literal_eval()或手写安全解析器,避免恶意代码注入。
6. 多智能体协作架构
当任务复杂度超出单一智能体的能力边界时,我们需要多个专业智能体分工协作。常见的组织架构有三种:
- 层级式:一个主控智能体(Orchestrator)负责任务分解,调度若干子智能体各自求解子任务,最后汇总。适合流程固定、分工明确的任务。
- 辩论式:多个智能体独立求解同一问题,然后互相审阅、反驳,最终通过投票或仲裁得到最优解。适合需要高质量答案且容错成本高的场景(如法律分析)。
- 流水线式:前一个智能体的输出直接作为后一个智能体的输入,像工业流水线一样串联处理。适合顺序依赖强的任务(如"搜索→分析→报告生成")。
6.1 简易多智能体调度器
以下实现了一个支持流水线模式的轻量级调度器:
python
from typing import Any
class MultiAgentOrchestrator:
def __init__(self, agents: dict[str, Any]):
self.agents = agents # name -> agent 实例
def run_pipeline(self, steps: list[tuple[str, str]], initial_input: str) -> str:
"""
steps: [(agent_name, task_desc), ...]
每个 agent 需实现 run(task_desc: str, input: str) -> str 方法
"""
current_input = initial_input
for agent_name, task_desc in steps:
agent = self.agents[agent_name]
result = agent.run(task_desc, current_input)
print(f"[{agent_name}] 输出: {result[:100]}...")
current_input = result
return current_input
6.2 通信协议设计
多智能体之间需要一种结构化的消息格式,确保信息传递清晰、可追溯:
json
{
"from": "researcher_agent",
"to": "writer_agent",
"type": "research_report",
"payload": {
"summary": "2026年AI智能体领域的最新进展包括...",
"references": ["https://arxiv.org/abs/...", "https://blog.example.com/..."]
},
"metadata": {
"timestamp": 1698849600,
"priority": "normal"
}
}
此协议的优点:type 字段区分消息类型(报告、请求、确认),metadata 携带优先级和时间戳,payload 承载业务数据,便于日志追踪和流控。
7. 实战:构建一个博客写作智能体
现在我们将前述所有组件------记忆系统、工具注册、ReAct 推理------整合为一个完整的博客写作智能体。其工作流程如下:
- 检索资料:调用 Web 搜索工具获取选题相关背景。
- 存储记忆:将搜索结果存入长期记忆,供后续章节引用。
- 生成大纲:基于资料用 LLM 生成文章大纲。
- 分章节写作:对每个章节,检索相关记忆作为参考,用 LLM 撰写初稿。
- 事实核查:可选步骤,调用验证工具检查关键事实。
- 汇总输出:拼接各章节形成最终文章。
python
class BlogWriterAgent:
def __init__(self, llm, tools_registry, memory):
self.llm = llm
self.tools = tools_registry
self.memory = memory
def run(self, topic: str) -> str:
# 步骤 1:检索题目相关背景资料
search_result = self.tools.execute("web_search", query=topic)
self.memory.store("topic_background", search_result)
# 步骤 2:生成大纲
outline_prompt = f"根据以下资料为技术博客《{topic}》生成详细大纲(以减号列表输出):\n{search_result}"
outline = self.llm.generate(outline_prompt)
# 步骤 3:分章节写作并调用工具核实准确性
chapters = [ch.strip("- ") for ch in outline.split("\n") if ch.strip()]
final_article = []
for chap in chapters:
related_memories = self.memory.retrieve(chap)
memory_context = "\n".join(related_memories) if related_memories else "无相关记忆"
section_prompt = (
f"撰写以下章节的技术博客内容(风格:深入浅出、带代码示例):\n"
f"章节:{chap}\n"
f"参考资料:\n{memory_context}"
)
draft = self.llm.generate(section_prompt)
# 可选:事实核查(如检测引用的论文是否存在、API 名称是否正确)
verification = self.tools.execute("fact_check", statement=draft)
if "错误" in verification:
draft = self.llm.generate(
f"修正以下内容中的事实错误并保持原有风格:\n{draft}\n注记:{verification}"
)
final_article.append(draft)
return "\n\n".join(final_article)
落地建议:以上架构可基于 LangChain、LlamaIndex 等框架快速搭建,但深入理解底层的记忆检索机制、提示词模板设计和工具注册流程,对于调优智能体的行为质量至关重要。
8. 总结与展望
本文从底层原理出发,完整拆解了 AI 智能体的五大核心组件,并付诸可直接运行的 Python 代码:滑动窗口短期记忆、基于 Chroma 的向量化长期记忆、JSON Schema 驱动的工具注册中心、ReAct 推理循环、多智能体流水线调度器,以及一个整合所有模块的博客写作智能体。
未来演进方向:
- 更安全:引入安全护栏(Guardrails)和人工审核节点,防止智能体执行危险操作。
- 更自主:结合长期记忆与元认知(Metacognition),智能体能够自我评估、自我纠错。
- 更可观测:构建 OpenTelemetry 风格的追踪体系,记录每一步思考-行动-观察链,便于调试和审计。
- 多模态融合:如图像生成、语音交互、视频理解,扩展智能体的感知和表达能力。
AI 智能体正从概念验证走向生产落地。掌握本文所述的底层机制,你就能在 LangChain、AutoGPT 等框架之外,自如地构建和调优自己的智能体系统。