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 → 直接输出

适用场景

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

代码示例

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记忆管理短期记忆、长期记忆

代码示例

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(路由):通过意图识别分派到不同处理路径

链式工作流示例

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("优化我们的客户服务流程")

路由工作流示例

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 之间辩论以达成共识多视角分析、决策优化

代码示例

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:工具太多难以选择

解决方案:动态工具注入

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:上下文膨胀

解决方案:上下文压缩

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 工作流引擎对比

引擎特点适用场景
LangChainPython 生态,灵活开发者友好,快速原型
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 代码实现

# 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)
# 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)

更多推荐