AI智能体架构与开发范式详解

AI 智能体架构与开发范式详解


一、什么是 Agent

1.1 定义与核心特征

Agent(智能体):具备自主感知、规划、记忆和工具使用能力的数字化实体,能够在复杂环境中自主完成任务。

核心特征

  • 自主性:无需人工干预,自主决策和执行
  • 适应性:根据环境变化调整策略
  • 目标导向:有明确的目标并努力实现
  • 社交能力:能够与其他 Agent 或人类交互

1.2 与传统程序的区别

维度 传统程序 Agent
决策方式 预定义规则 自主推理决策
灵活性 固定流程 自适应调整
学习能力 从经验中学习
交互方式 被动响应 主动感知和行动

二、智能体核心能力

2.1 能力体系

能力 描述 实现方式 示例
感知 理解用户指令和环境信息 NLP 理解、信息提取 解析自然语言问题
规划 将复杂任务分解为子任务 任务分解、计划生成 制定执行计划
记忆 存储和检索历史信息 短期记忆、长期记忆 记住用户偏好
工具 调用外部 API 和服务 Function Calling、API 调用 查询数据库、调用计算器
反馈 根据结果调整策略 反思机制、迭代优化 失败后重试或换方法

2.2 智能体架构图

复制代码
┌──────────────────────────────────────────────────────────────┐
│                      Agent 架构                             │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────┐    │
│  │   Perception │───→│   Planning   │───→│   Execution  │    │
│  │   (感知)      │    │   (规划)      │    │   (执行)      │    │
│  └──────────────┘    └──────────────┘    └──────┬───────┘    │
│         ↑                                       │            │
│         │                                       ↓            │
│  ┌──────────────┐    ┌──────────────┐    ┌──────────────┐    │
│  │    Memory    │←───│   Feedback   │←───│    Tools     │    │
│  │   (记忆)      │    │   (反馈)      │    │   (工具)      │    │
│  └──────────────┘    └──────────────┘    └──────────────┘    │
│                                                              │
└──────────────────────────────────────────────────────────────┘

三、智能体的主流开发范式

3.1 范式对比

范式 复杂度 自主性 可控性 适用场景
简单 LLM 应用 简单问答、内容生成
单智能体 特定任务处理、工具调用
工作流 流程清晰、可拆解任务
多智能体系统 复杂系统开发、团队协作模拟

3.2 范式一:简单 LLM 应用

定义:直接调用模型 API 实现内容生成,完全依赖模型服务。

架构

复制代码
用户输入 → LLM API → 直接输出

适用场景

  • 内容生成(写作、翻译、摘要)
  • 简单问答
  • 代码生成

代码示例

python 复制代码
import openai

client = openai.OpenAI(api_key="your-api-key")

def generate_content(prompt):
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": prompt}]
    )
    return response.choices[0].message.content

# 使用示例
result = generate_content("请写一篇关于 AI 的文章")
print(result)

3.3 范式二:单智能体(Single Agent)

定义:为 LLM 增加 RAG、Tool、Memory 等能力,让模型具备与特定环境交互的能力。

架构

复制代码
用户输入 → Agent → [LLM + RAG + Tools + Memory] → 输出

核心组件

组件 作用 实现方式
LLM 核心推理引擎 GPT、Claude、开源模型
RAG 知识库检索 向量数据库 + Embedding
Tools 外部工具调用 Function Calling、API
Memory 记忆管理 短期记忆、长期记忆

代码示例

python 复制代码
class SimpleAgent:
    def __init__(self, llm, tools, memory, rag_system):
        self.llm = llm
        self.tools = tools
        self.memory = memory
        self.rag_system = rag_system
    
    def run(self, user_input):
        # 1. 检索相关知识
        context = self.rag_system.search(user_input)
        
        # 2. 获取记忆
        history = self.memory.get_recent()
        
        # 3. 构建 Prompt
        prompt = f"""
        历史对话:{history}
        
        相关知识:{context}
        
        用户问题:{user_input}
        
        可用工具:{self.tools.describe()}
        
        请分析是否需要调用工具,如果需要请调用合适的工具。
        """
        
        # 4. 调用 LLM
        response = self.llm.generate(prompt)
        
        # 5. 检查是否需要调用工具
        if response.needs_tool_call:
            tool_result = self.tools.call(response.tool_name, response.params)
            self.memory.store(f"工具调用:{response.tool_name} → {tool_result}")
            return self.run(user_input)  # 递归处理
        
        # 6. 存储记忆
        self.memory.store(f"用户:{user_input}\n助手:{response.content}")
        
        return response.content

3.4 范式三:工作流(Workflow)

定义:将应用拆分为多个独立子智能体,按预定义流程编排。

特点

  • 确定性强、可调试性高、可控性好
  • 适合流程清晰、可拆解的任务

类型

  • Chain(链式):任务分解为一系列顺序执行的子任务
  • Routing(路由):通过意图识别分派到不同处理路径

链式工作流示例

python 复制代码
from langchain.chains import LLMChain, SimpleSequentialChain
from langchain.prompts import PromptTemplate

# 链 1:任务分析
analysis_prompt = PromptTemplate(
    input_variables=["task"],
    template="请分析以下任务的关键步骤:{task}"
)
analysis_chain = LLMChain(llm=llm, prompt=analysis_prompt)

# 链 2:方案生成
solution_prompt = PromptTemplate(
    input_variables=["analysis"],
    template="基于以下分析生成解决方案:{analysis}"
)
solution_chain = LLMChain(llm=llm, prompt=solution_prompt)

# 链 3:执行计划
plan_prompt = PromptTemplate(
    input_variables=["solution"],
    template="基于以下解决方案生成执行计划:{solution}"
)
plan_chain = LLMChain(llm=llm, prompt=plan_prompt)

# 组合链
overall_chain = SimpleSequentialChain(
    chains=[analysis_chain, solution_chain, plan_chain],
    verbose=True
)

# 执行
result = overall_chain.run("优化我们的客户服务流程")

路由工作流示例

python 复制代码
class RouterAgent:
    def __init__(self, agents):
        self.agents = agents
    
    def route(self, user_input):
        # 意图识别
        intent = self._detect_intent(user_input)
        
        # 根据意图路由到不同 Agent
        if intent == "sales":
            return self.agents["sales_agent"].run(user_input)
        elif intent == "support":
            return self.agents["support_agent"].run(user_input)
        elif intent == "finance":
            return self.agents["finance_agent"].run(user_input)
        else:
            return self.agents["general_agent"].run(user_input)
    
    def _detect_intent(self, text):
        # 使用 LLM 进行意图识别
        prompt = f"请判断以下文本的意图(sales/support/finance/general):{text}"
        return self.agents["intent_agent"].run(prompt)

3.5 范式四:多智能体系统(Multi-Agent)

定义:多个子智能体协作,具备更多自主决策权,采用模型驱动的对话式流程编排。

特点

  • 自治协作模式,每个 Agent 有自己的角色和能力
  • 灵活性和适应性强
  • 挑战:难以预测和调试

架构模式

模式 描述 示例
角色分工 不同 Agent 扮演不同角色 产品经理、设计师、工程师
层级架构 上级 Agent 协调下级 Agent 项目经理 → 开发团队
市场模式 Agent 之间通过市场机制协作 任务市场、资源交易
辩论模式 Agent 之间辩论以达成共识 多视角分析、决策优化

代码示例

python 复制代码
class MultiAgentSystem:
    def __init__(self, agents):
        self.agents = agents
        self.coordinator = Coordinator(agents)
    
    def solve(self, task):
        # 1. 任务分解
        subtasks = self.coordinator.decompose(task)
        
        # 2. 任务分配
        assignments = self.coordinator.assign(subtasks)
        
        # 3. 并行执行
        results = {}
        for agent_name, subtask in assignments.items():
            results[agent_name] = self.agents[agent_name].run(subtask)
        
        # 4. 结果整合
        final_result = self.coordinator.integrate(results)
        
        return final_result

# 角色定义
class ProductManagerAgent:
    def run(self, task):
        # 需求分析、优先级确定
        return f"产品需求文档:{task}"

class DeveloperAgent:
    def run(self, task):
        # 技术实现
        return f"代码实现:{task}"

class TesterAgent:
    def run(self, task):
        # 测试验证
        return f"测试报告:{task}"

class Coordinator:
    def decompose(self, task):
        return ["需求分析", "技术设计", "代码实现", "测试验证"]
    
    def assign(self, subtasks):
        return {
            "product_manager": "需求分析",
            "developer": "技术设计 + 代码实现",
            "tester": "测试验证"
        }
    
    def integrate(self, results):
        return "\n".join(results.values())

# 使用示例
agents = {
    "product_manager": ProductManagerAgent(),
    "developer": DeveloperAgent(),
    "tester": TesterAgent()
}
system = MultiAgentSystem(agents)
result = system.solve("开发一个在线购物网站")

四、单智能体的典型问题

4.1 问题分析

问题 原因 影响
工具太多难以选择 模型面对大量工具时决策困难 选择错误工具或无法选择
上下文膨胀 多轮执行后历史对话过长 超出窗口限制,性能下降
专业领域技能不足 通用模型在特定领域表现不佳 回答不准确
可维护性变差 逻辑越来越复杂 难以调试和扩展

4.2 解决方案

问题 1:工具太多难以选择

解决方案:动态工具注入

python 复制代码
class ToolSelector:
    def __init__(self, tools):
        self.tools = tools
    
    def select_relevant_tools(self, query, max_tools=5):
        """
        根据查询选择相关工具
        
        参数:
            query: 用户查询
            max_tools: 最大返回工具数
        
        返回:
            相关工具列表
        """
        # 使用 LLM 评估工具相关性
        tool_descriptions = "\n".join([
            f"{t['name']}: {t['description']}" 
            for t in self.tools
        ])
        
        prompt = f"""
        用户查询:{query}
        
        可用工具:
        {tool_descriptions}
        
        请选择最相关的 {max_tools} 个工具,返回工具名称列表。
        """
        
        response = llm.generate(prompt)
        relevant_tool_names = self._parse_tool_names(response)
        
        return [t for t in self.tools if t["name"] in relevant_tool_names]
问题 2:上下文膨胀

解决方案:上下文压缩

python 复制代码
class ContextCompressor:
    def __init__(self, max_tokens=4096):
        self.max_tokens = max_tokens
    
    def compress(self, messages):
        """
        压缩上下文
        
        参数:
            messages: 消息列表
        
        返回:
            压缩后的消息列表
        """
        # 策略:保留系统消息 + 关键信息摘要 + 最近对话
        compressed = []
        
        # 保留系统消息
        system_messages = [m for m in messages if m["role"] == "system"]
        compressed.extend(system_messages)
        
        # 提取关键信息
        user_messages = [m for m in messages if m["role"] == "user"]
        if len(user_messages) > 5:
            # 生成摘要
            history_text = "\n".join([m["content"] for m in user_messages[:-5]])
            summary = self._generate_summary(history_text)
            compressed.append({
                "role": "system",
                "content": f"历史对话摘要:{summary}"
            })
        
        # 保留最近 5 轮对话
        compressed.extend(messages[-10:])
        
        return compressed
    
    def _generate_summary(self, text):
        prompt = f"请简要总结以下对话内容:{text}"
        return llm.generate(prompt)["response"]

五、工作流特点

5.1 优势

优势 说明
确定性强 流程预定义,结果可预测
可调试性高 每个步骤独立,便于排查问题
可控性好 人工可以干预每个环节
性能稳定 不受模型随机性影响

5.2 适用场景

场景 说明
流程清晰的任务 如审批流程、数据处理管道
合规要求高的场景 如金融、医疗领域
需要审计追踪的任务 每个步骤都有记录
团队协作流程 需要多人参与的任务

5.3 工作流引擎对比

引擎 特点 适用场景
LangChain Python 生态,灵活 开发者友好,快速原型
Dify 可视化编排,低代码 业务人员,快速构建
Airflow 数据管道,调度强 数据工程,定时任务
Prefect 现代数据栈,灵活 数据工作流

六、多智能体系统特点

6.1 优势

优势 说明
灵活性强 可以适应复杂和动态的环境
适应性好 可以从经验中学习和改进
鲁棒性高 单个 Agent 失败不影响整体
能力互补 不同 Agent 可以弥补彼此的不足

6.2 挑战

挑战 说明
难以预测 多 Agent 交互可能产生意外结果
调试困难 需要追踪多个 Agent 的状态
协调成本 Agent 之间的通信和协调开销
一致性问题 多个 Agent 可能产生冲突的决策

6.3 协作模式

模式 描述 示例
主从模式 一个主 Agent 控制多个从 Agent 项目经理 + 开发团队
对等模式 Agent 之间平等协作 团队成员协作
层级模式 Agent 按层级组织 公司组织结构
市场模式 Agent 通过市场机制协作 任务分发、资源交易

七、实战:构建一个简单的智能体

7.1 项目结构

复制代码
simple-agent/
├── agent.py
├── tools/
│   ├── weather.py
│   └── calculator.py
├── memory/
│   └── memory.py
├── rag/
│   └── rag_system.py
└── main.py

7.2 代码实现

python 复制代码
# agent.py
class Agent:
    def __init__(self, llm, tools, memory, rag_system):
        self.llm = llm
        self.tools = tools
        self.memory = memory
        self.rag_system = rag_system
    
    def run(self, user_input):
        # 1. 获取上下文
        context = self.rag_system.search(user_input)
        history = self.memory.get_recent()
        
        # 2. 构建 Prompt
        prompt = self._build_prompt(user_input, context, history)
        
        # 3. 调用 LLM
        response = self.llm.generate(prompt)
        
        # 4. 处理工具调用
        if self._needs_tool_call(response):
            tool_result = self._execute_tool_call(response)
            self.memory.store(f"工具调用结果:{tool_result}")
            return self.run(user_input)
        
        # 5. 存储记忆
        self.memory.store(f"用户:{user_input}\n助手:{response}")
        
        return response
    
    def _build_prompt(self, user_input, context, history):
        return f"""
        你是一位专业的智能助手。
        
        历史对话:
        {history}
        
        相关知识:
        {context}
        
        可用工具:
        {self.tools.describe()}
        
        用户问题:{user_input}
        
        如果需要调用工具,请输出工具调用格式。
        """
    
    def _needs_tool_call(self, response):
        return "工具调用" in response
    
    def _execute_tool_call(self, response):
        # 解析工具调用
        tool_name = self._extract_tool_name(response)
        params = self._extract_params(response)
        return self.tools.call(tool_name, params)
python 复制代码
# main.py
from agent import Agent
from tools.weather import WeatherTool
from tools.calculator import CalculatorTool
from memory.memory import Memory
from rag.rag_system import RAGSystem
from llm.mock_llm import MockLLM

# 初始化组件
llm = MockLLM()
tools = [WeatherTool(), CalculatorTool()]
memory = Memory()
rag_system = RAGSystem()

# 创建 Agent
agent = Agent(llm, tools, memory, rag_system)

# 运行
result = agent.run("北京明天的天气怎么样?")
print(result)

八、总结

核心要点

  1. Agent 定义:具备自主感知、规划、记忆和工具使用能力的数字化实体
  2. 四大开发范式:简单 LLM 应用、单智能体、工作流、多智能体系统
  3. 单智能体挑战:工具选择、上下文膨胀、专业技能、可维护性
  4. 工作流优势:确定性强、可调试性高、可控性好
  5. 多智能体特点:灵活性强但调试困难

选型建议

场景 推荐范式 理由
简单问答 简单 LLM 应用 快速实现
需要工具调用 单智能体 灵活扩展
流程清晰的任务 工作流 可控性强
复杂系统开发 多智能体系统 能力互补

学习路径

复制代码
简单 LLM 应用 → 单智能体(+ Tools + Memory)→ 
工作流编排 → 多智能体系统 → 智能体协作协议

下一步建议

  1. 从单智能体开始,逐步添加工具和记忆能力
  2. 学习使用 LangChain 或 Dify 构建工作流
  3. 探索多智能体系统的协作模式
  4. 关注智能体间通信协议(A2A Protocol)