1. 直接 Prompt 驱动(静态 Agent)

  • 思路:把 Agent 的角色、人设、目标、约束条件等全部写进一个系统 Prompt,模型每次调用时依赖 Prompt 决策。

  • 优点

    • 实现简单,不需要额外的代码逻辑。
    • 适合一次性任务或人设类聊天机器人。
  • 缺点

    • 无长期记忆,无法主动执行任务。
    • 所有“能力”都被固定在 Prompt 里,灵活性差。
  • 适用场景

    • 人设聊天(虚拟角色)
    • FAQ 问答
  • 示例

      
      import openai
      from typing import List, Dict, Any
      import json
      import time
      
      class SimplePromptAgent:
          """最简单的 Prompt 驱动 Agent"""
          
          def __init__(self, api_key: str, model: str = "gpt-3.5-turbo"):
              self.client = openai.OpenAI(api_key=api_key)
              self.model = model
              self.system_prompt = """
              你是一个专业的数据分析助手。
              特点:
              1. 善于解释复杂概念
              2. 提供结构化的分析
              3. 基于事实和数据说话
              """
          
          def chat(self, user_input: str) -> str:
              response = self.client.chat.completions.create(
                  model=self.model,
                  messages=[
                      {"role": "system", "content": self.system_prompt},
                      {"role": "user", "content": user_input}
                  ]
              )
              return response.choices[0].message.content
      	
      	# 使用示例
      	# agent = SimplePromptAgent(api_key="your_key")
      	# result = agent.chat("分析一下Python和Java的优缺点")
      	# print(result)
    

2. 规则 + LLM(程序驱动型 Agent)

  • 思路:用代码写任务执行逻辑,LLM 负责推理、生成决策,代码负责调用外部 API、数据库等。

  • 优点

    • 可以调用真实世界的工具(API、数据库、爬虫)。
    • 程序控制可预测性高。
  • 缺点

    • 对开发者要求高,要设计好调用流程。
    • 灵活性比自主型 Agent 低。
  • 常用框架

    • LangChain Tools / Agents
    • OpenAI function calling
    • LlamaIndex Tool Nodes
  • 适用场景

    • 数据分析助手
    • 带外部 API 调用的业务机器人
  • 示例

      class ToolCallingAgent:
          """带工具调用的 Agent"""
          
          def __init__(self, api_key: str):
              self.client = openai.OpenAI(api_key=api_key)
              self.tools = {
                  "calculate": self.calculate,
                  "search_database": self.search_database,
                  "get_weather": self.get_weather
              }
          
          def calculate(self, expression: str) -> float:
              """计算数学表达式"""
              try:
                  return eval(expression)
              except:
                  return "计算错误"
          
          def search_database(self, query: str) -> Dict:
              """模拟数据库查询"""
              # 实际项目中这里连接真实数据库
              mock_data = {
                  "用户数": 10000,
                  "活跃率": 0.65,
                  "增长率": 0.12
              }
              return mock_data
          
          def get_weather(self, city: str) -> Dict:
              """模拟天气查询"""
              # 实际项目中调用天气API
              return {
                  "city": city,
                  "temperature": 25,
                  "weather": "晴天"
              }
          
          def run(self, user_input: str) -> str:
              # 让 LLM 决定是否需要调用工具
              functions = [
                  {
                      "name": "calculate",
                      "description": "计算数学表达式",
                      "parameters": {
                          "type": "object",
                          "properties": {
                              "expression": {"type": "string", "description": "数学表达式"}
                          },
                          "required": ["expression"]
                      }
                  },
                  {
                      "name": "get_weather",
                      "description": "查询城市天气",
                      "parameters": {
                          "type": "object",
                          "properties": {
                              "city": {"type": "string", "description": "城市名"}
                          },
                          "required": ["city"]
                      }
                  }
              ]
              
              response = self.client.chat.completions.create(
                  model="gpt-3.5-turbo",
                  messages=[{"role": "user", "content": user_input}],
                  functions=functions,
                  function_call="auto"
              )
              
              message = response.choices[0].message
              
              # 如果需要调用函数
              if message.function_call:
                  function_name = message.function_call.name
                  function_args = json.loads(message.function_call.arguments)
                  
                  # 执行函数
                  result = self.tools[function_name](**function_args)
                  
                  # 将结果返回给 LLM 生成最终回答
                  final_response = self.client.chat.completions.create(
                      model="gpt-3.5-turbo",
                      messages=[
                          {"role": "user", "content": user_input},
                          {"role": "function", "name": function_name, "content": str(result)}
                      ]
                  )
                  return final_response.choices[0].message.content
              
              return message.content
      	
      	# 使用示例
      	# agent = ToolCallingAgent(api_key="your_key")
      	# result = agent.run("北京今天天气怎么样?")
      	# result = agent.run("计算 15 * 23 + 100")
    
    

3. 规划 + 工具调用(任务链 Agent)

  • 思路:Agent 会先规划执行步骤,然后调用不同的工具完成任务(多步推理)。

  • 优点

    • 支持复杂任务拆解(Task Decomposition)。
    • 灵活组合多个能力模块。
  • 缺点

    • 需要良好的“任务分解+工具调用”机制,否则容易陷入循环或出错。
  • 常用框架

    • LangChain Agent(ReAct / Plan-and-Execute)
    • LlamaIndex Workflow
    • Microsoft AutoGen
  • 适用场景

    • 多数据源分析
    • 自动化办公
    • 多 API 组合任务
  • 示例架构

    用户需求 → Agent → 任务规划器 → 工具调用器 → 汇总结果 → 回复
    
    class PlanAndExecuteAgent:
    """能够规划和执行多步任务的 Agent"""
    
    def __init__(self, api_key: str):
        self.client = openai.OpenAI(api_key=api_key)
        self.max_steps = 5
        
    def plan(self, goal: str) -> List[str]:
        """将目标分解为步骤"""
        prompt = f"""
        将以下目标分解为具体的执行步骤(最多5步):
        目标:{goal}
        
        请以JSON数组格式返回,每步包含action和description。
        示例:[{{"action": "search", "description": "搜索相关信息"}}]
        """
        
        response = self.client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": prompt}]
        )
        
        try:
            steps = json.loads(response.choices[0].message.content)
            return steps
        except:
            return [{"action": "think", "description": "思考问题"}]
    
    def execute_step(self, step: Dict, context: str) -> str:
        """执行单个步骤"""
        action = step.get("action", "think")
        description = step.get("description", "")
        
        # 根据不同的 action 执行不同操作
        if action == "search":
            return f"[搜索结果] 找到了关于 {description} 的信息"
        elif action == "analyze":
            return f"[分析结果] 完成了 {description}"
        elif action == "calculate":
            return f"[计算结果] 计算了 {description}"
        else:
            # 默认让 LLM 思考
            prompt = f"基于上下文:{context}\n执行:{description}"
            response = self.client.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=[{"role": "user", "content": prompt}]
            )
            return response.choices[0].message.content
    
    def run(self, goal: str) -> str:
        """运行完整的规划-执行流程"""
        print(f"目标:{goal}\n")
        
        # 1. 制定计划
        steps = self.plan(goal)
        print(f"计划步骤:")
        for i, step in enumerate(steps):
            print(f"  {i+1}. {step['description']}")
        print()
        
        # 2. 执行计划
        context = f"目标:{goal}"
        results = []
        
        for i, step in enumerate(steps):
            print(f"执行步骤 {i+1}: {step['description']}")
            result = self.execute_step(step, context)
            results.append(result)
            context += f"\n步骤{i+1}结果:{result}"
            print(f"结果:{result}\n")
        
        # 3. 总结
        summary_prompt = f"""
        基于以下执行结果,总结任务完成情况:
        目标:{goal}
        执行结果:{json.dumps(results, ensure_ascii=False)}
        """
        
        final = self.client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": summary_prompt}]
        )
        
        return final.choices[0].message.content
    
    # 使用示例
    # agent = PlanAndExecuteAgent(api_key="your_key")
    # result = agent.run("分析一家创业公司的商业模式")
    

4. 自主型 Agent(Self-Looping / Auto Agent)

  • 思路:Agent 自我循环执行(Perception → Plan → Action → Reflection),直到目标完成。

  • 优点

    • 高度自动化,可长时间运行。
    • 能主动发现并执行新任务。
  • 缺点

    • 不稳定,可能陷入死循环或跑偏。
    • 需要安全机制(如最大循环次数、任务边界)。
  • 常见实现

    • AutoGPT
    • BabyAGI
    • Camel-AI
  • 适用场景

    • 自动研究(爬取资料、总结、报告)
    • 长期目标执行
  • 示例架构

    目标输入 → 任务生成器 → 执行器(调用工具) → 结果反思 → 生成新任务 → 循环
    
	
class AutonomousAgent:
    """自主循环执行的 Agent"""
    
    def __init__(self, api_key: str, max_iterations: int = 5):
        self.client = openai.OpenAI(api_key=api_key)
        self.max_iterations = max_iterations
        self.memory = []  # 任务记忆
        self.completed_tasks = []  # 已完成任务
        
    def think(self, goal: str, context: str) -> Dict:
        """思考下一步要做什么"""
        prompt = f"""
        目标:{goal}
        当前进展:{context}
        
        请决定下一步行动,返回JSON格式:
        {{
            "thought": "你的思考过程",
            "action": "next_task/research/analyze/complete",
            "task": "具体任务描述",
            "reason": "为什么要这样做"
        }}
        
        如果目标已完成,action设为"complete"
        """
        
        response = self.client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": prompt}]
        )
        
        try:
            return json.loads(response.choices[0].message.content)
        except:
            return {
                "thought": "继续执行",
                "action": "next_task",
                "task": "继续分析",
                "reason": "需要更多信息"
            }
    
    def execute_action(self, action: Dict) -> str:
        """执行具体行动"""
        action_type = action.get("action", "think")
        task = action.get("task", "")
        
        # 模拟不同类型的行动
        if action_type == "research":
            return f"[研究] 收集了关于 {task} 的资料"
        elif action_type == "analyze":
            return f"[分析] 分析了 {task}"
        elif action_type == "complete":
            return f"[完成] 任务已完成"
        else:
            # 通用任务执行
            time.sleep(0.5)  # 模拟执行时间
            return f"[执行] 完成了 {task}"
    
    def reflect(self, history: List[Dict]) -> str:
        """反思执行历史,提取经验"""
        if not history:
            return "刚开始执行"
        
        prompt = f"""
        回顾执行历史:{json.dumps(history[-3:], ensure_ascii=False)}
        
        总结:1) 完成了什么 2) 还需要什么 3) 有什么问题
        """
        
        response = self.client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": prompt}]
        )
        
        return response.choices[0].message.content
    
    def run(self, goal: str) -> str:
        """自主运行直到完成目标"""
        print(f"🎯 目标:{goal}\n")
        
        context = "开始执行"
        history = []
        
        for i in range(self.max_iterations):
            print(f"--- 迭代 {i+1} ---")
            
            # 1. 思考
            decision = self.think(goal, context)
            print(f"💭 思考:{decision['thought']}")
            print(f"📋 任务:{decision['task']}")
            
            # 2. 执行
            result = self.execute_action(decision)
            print(f"✅ 结果:{result}")
            
            # 3. 记录
            history.append({
                "iteration": i+1,
                "decision": decision,
                "result": result
            })
            
            # 4. 反思
            if i > 0 and i % 2 == 0:  # 每两次反思一次
                reflection = self.reflect(history)
                print(f"🔍 反思:{reflection}")
                context = reflection
            else:
                context = result
            
            # 5. 检查是否完成
            if decision.get("action") == "complete":
                print(f"\n✨ 目标完成!")
                break
            
            print()
        
        # 最终总结
        return self.generate_report(goal, history)
    
    def generate_report(self, goal: str, history: List[Dict]) -> str:
        """生成执行报告"""
        prompt = f"""
        生成任务执行报告:
        目标:{goal}
        执行历史:{json.dumps(history, ensure_ascii=False)}
        
        请总结关键成果和发现。
        """
        
        response = self.client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": prompt}]
        )
        
        return response.choices[0].message.content

# 使用示例
# agent = AutonomousAgent(api_key="your_key", max_iterations=5)
# report = agent.run("研究如何提高代码质量")


5. 多 Agent 协作(Multi-Agent System)

  • 思路:多个 LLM Agent 各自有角色和能力,通过对话或消息队列协作完成复杂任务。

  • 优点

    • 可以模拟团队(工程师、分析师、设计师等)。
    • 易于扩展不同角色。
  • 缺点

    • 协调成本高,通信开销大。
  • 常用框架

    • Microsoft AutoGen
    • LangGraph(有状态多Agent)
    • ChatDev(模拟软件公司)
  • 适用场景

    • 软件开发团队模拟
    • 复杂决策任务
    • 大规模数据分析
  • 典型流程

    需求 → 项目经理Agent → 分配任务给不同角色Agent → 各Agent调用工具 → 汇总结果
    
	
class MultiAgentSystem:
    """多个专业 Agent 协作的系统"""
    
    def __init__(self, api_key: str):
        self.client = openai.OpenAI(api_key=api_key)
        self.agents = {
            "产品经理": ProductManagerAgent(self.client),
            "工程师": EngineerAgent(self.client),
            "设计师": DesignerAgent(self.client),
            "测试员": TesterAgent(self.client)
        }
        self.conversation_history = []
    
    def collaborate(self, project: str) -> str:
        """多 Agent 协作完成项目"""
        print(f"🚀 项目:{project}\n")
        
        # 1. 产品经理分析需求
        pm_analysis = self.agents["产品经理"].analyze_requirements(project)
        self.log_conversation("产品经理", pm_analysis)
        
        # 2. 设计师提供设计方案
        design = self.agents["设计师"].create_design(pm_analysis)
        self.log_conversation("设计师", design)
        
        # 3. 工程师实现
        implementation = self.agents["工程师"].implement(pm_analysis, design)
        self.log_conversation("工程师", implementation)
        
        # 4. 测试员测试
        test_result = self.agents["测试员"].test(implementation)
        self.log_conversation("测试员", test_result)
        
        # 5. 产品经理总结
        final_report = self.agents["产品经理"].summarize(self.conversation_history)
        
        return final_report
    
    def log_conversation(self, agent_name: str, message: str):
        """记录对话历史"""
        self.conversation_history.append({
            "agent": agent_name,
            "message": message,
            "timestamp": time.time()
        })
        print(f"[{agent_name}]: {message}\n")


class ProductManagerAgent:
    """产品经理 Agent"""
    
    def __init__(self, client):
        self.client = client
        self.role = "产品经理"
        
    def analyze_requirements(self, project: str) -> str:
        prompt = f"""
        作为产品经理,分析项目需求:{project}
        
        输出:
        1. 核心功能点
        2. 用户价值
        3. 技术要求
        """
        
        response = self.client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": prompt}]
        )
        return response.choices[0].message.content
    
    def summarize(self, history: List[Dict]) -> str:
        prompt = f"""
        基于团队讨论历史,生成项目总结报告:
        {json.dumps(history, ensure_ascii=False)}
        """
        
        response = self.client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": prompt}]
        )
        return response.choices[0].message.content


class EngineerAgent:
    """工程师 Agent"""
    
    def __init__(self, client):
        self.client = client
        self.role = "工程师"
        
    def implement(self, requirements: str, design: str) -> str:
        prompt = f"""
        作为工程师,基于需求和设计实现方案:
        需求:{requirements}
        设计:{design}
        
        输出技术实现方案和代码架构。
        """
        
        response = self.client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": prompt}]
        )
        return response.choices[0].message.content


class DesignerAgent:
    """设计师 Agent"""
    
    def __init__(self, client):
        self.client = client
        self.role = "设计师"
        
    def create_design(self, requirements: str) -> str:
        prompt = f"""
        作为UI/UX设计师,基于需求创建设计方案:
        需求:{requirements}
        
        输出设计理念和界面布局建议。
        """
        
        response = self.client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": prompt}]
        )
        return response.choices[0].message.content


class TesterAgent:
    """测试员 Agent"""
    
    def __init__(self, client):
        self.client = client
        self.role = "测试员"
        
    def test(self, implementation: str) -> str:
        prompt = f"""
        作为测试工程师,评估实现方案:
        实现:{implementation}
        
        输出测试策略和潜在问题。
        """
        
        response = self.client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": prompt}]
        )
        return response.choices[0].message.content

# 使用示例
# system = MultiAgentSystem(api_key="your_key")
# report = system.collaborate("开发一个任务管理APP")

总结对比

方法类型 自主性 难度 工具调用能力 适用场景
1. Prompt 驱动 单轮/人设对话
2. 规则 + LLM 业务机器人、API助手
3. 规划 + 工具调用 中高 中高 多步任务链
4. 自主型 Agent 自动研究、持续执行任务
5. 多 Agent 协作 模拟团队、复杂协作
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐