多 Agent 协作系统:让多个 AI 一起完成任务

1 阅读5分钟

多 Agent 协作系统:让多个 AI 一起完成任务

系列文章: 《AI Agent 开发实战》第 4 期
难度等级: ⭐⭐⭐⭐⭐
预计耗时: 50 分钟


🎯 本文目标

学会构建多 Agent 协作系统:

  • ✅ 角色分工
  • ✅ 任务分配
  • ✅ 通信机制
  • ✅ 结果汇总

📚 为什么需要多 Agent?

单 Agent 的局限

单 Agent = 一个人干所有活
   ↓
问题:
- 精力有限
- 专业度不够
- 容易出错
- 难以处理复杂任务

多 Agent 的优势

多 Agent = 团队协作
   ↓
优势:
- 专业分工
- 并行处理
- 互相校验
- 处理复杂任务

🔧 架构设计

经典三人组模式

┌─────────────────────────────────────┐
│           协调员 (Coordinator)       │
│  - 理解任务                          │
│  - 分配工作                          │
│  - 汇总结果                          │
└──────────────┬──────────────────────┘
               │
    ┌──────────┼──────────┐
    │          │          │
┌───▼───┐  ┌──▼───┐  ┌──▼───┐
│研究员 │  │作家  │  │审核员│
│收集信息│  │撰写  │  │审核  │
└───────┘  └──────┘  └──────┘

💻 实现方案

方案 1:顺序协作

from google.adk import Agent

# 创建专业 Agent
researcher = Agent(
    name="Researcher",
    instruction="你负责搜集信息,提供准确、全面的数据"
)

writer = Agent(
    name="Writer",
    instruction="你负责撰写文章,文笔流畅、逻辑清晰"
)

reviewer = Agent(
    name="Reviewer",
    instruction="你负责审核内容,确保准确性和专业性"
)

# 顺序执行
def collaborative_work(topic: str):
    # 步骤 1:研究
    research_result = researcher.run(f"研究主题:{topic}")
    
    # 步骤 2:写作
    article = writer.run(f"基于以下资料写文章:{research_result}")
    
    # 步骤 3:审核
    final = reviewer.run(f"审核这篇文章:{article}")
    
    return final

# 使用
result = collaborative_work("2026 年 AI 发展趋势")

方案 2:并行协作

import asyncio
from google.adk import Agent

# 创建多个 Agent
agent_a = Agent(name="AgentA", instruction="负责分析技术面")
agent_b = Agent(name="AgentB", instruction="负责分析基本面")
agent_c = Agent(name="AgentC", instruction="负责分析消息面")

async def parallel_analysis(stock: str):
    # 并行执行
    tasks = [
        agent_a.run_async(f"分析{stock}的技术面"),
        agent_b.run_async(f"分析{stock}的基本面"),
        agent_c.run_async(f"分析{stock}的消息面")
    ]
    
    results = await asyncio.gather(*tasks)
    
    # 汇总
    summary = f"""
    # {stock} 分析报告
    
    ## 技术面
    {results[0]}
    
    ## 基本面
    {results[1]}
    
    ## 消息面
    {results[2]}
    """
    
    return summary

方案 3:辩论模式

def debate_mode(topic: str):
    # 创建对立 Agent
    pro_agent = Agent(
        name="Proponent",
        instruction="你支持这个观点,提供论据"
    )
    
    con_agent = Agent(
        name="Opponent",
        instruction="你反对这个观点,找出漏洞"
    )
    
    judge_agent = Agent(
        name="Judge",
        instruction="你作为裁判,基于双方论点做出判断"
    )
    
    # 第一轮:陈述
    pro_argument = pro_agent.run(f"支持:{topic}")
    con_argument = con_agent.run(f"反对:{topic}")
    
    # 第二轮:反驳
    pro_rebuttal = pro_agent.run(f"反驳对方:{con_argument}")
    con_rebuttal = con_agent.run(f"反驳对方:{pro_argument}")
    
    # 裁判判决
    judgment = judge_agent.run(f"""
    辩题:{topic}
    
    正方论点:{pro_argument}
    正方反驳:{pro_rebuttal}
    
    反方论点:{con_argument}
    反方反驳:{con_rebuttal}
    
    请作为裁判做出公正判决:
    """)
    
    return judgment

🎓 高级模式

1. 层级管理

class AgentTeam:
    def __init__(self):
        self.manager = Agent(name="Manager", instruction="团队管理者")
        self.members = []
    
    def add_member(self, agent: Agent, specialty: str):
        self.members.append({
            "agent": agent,
            "specialty": specialty
        })
    
    def execute(self, task: str):
        # 经理分解任务
        subtasks = self.manager.run(f"分解任务:{task}")
        
        # 分配给成员
        results = []
        for subtask in subtasks:
            member = self.find_best_member(subtask)
            result = member["agent"].run(subtask)
            results.append(result)
        
        # 汇总
        return self.manager.run(f"汇总结果:{results}")
    
    def find_best_member(self, task: str):
        # 根据任务类型选择最合适的成员
        for member in self.members:
            if member["specialty"] in task:
                return member
        return self.members[0]

2. 投票决策

def voting_system(question: str, num_agents: int = 5):
    agents = [
        Agent(name=f"Agent_{i}", instruction="独立思考和判断")
        for i in range(num_agents)
    ]
    
    # 各自投票
    votes = []
    for agent in agents:
        vote = agent.run(f"投票:{question} (是/否)")
        votes.append(vote)
    
    # 统计
    yes_count = sum(1 for v in votes if "是" in v)
    no_count = len(votes) - yes_count
    
    result = "通过" if yes_count > no_count else "否决"
    
    return {
        "result": result,
        "yes": yes_count,
        "no": no_count,
        "votes": votes
    }

3. 接力模式

def relay_chain(task: str):
    """
    接力模式:每个 Agent 在前一个基础上改进
    """
    agents = [
        Agent(name="Planner", instruction="制定计划"),
        Agent(name="Executor", instruction="执行计划"),
        Agent(name="Optimizer", instruction="优化结果"),
        Agent(name="Polisher", instruction="润色完善")
    ]
    
    current_result = task
    for agent in agents:
        current_result = agent.run(f"改进:{current_result}")
    
    return current_result

💡 实战案例

案例 1:内容创作团队

class ContentTeam:
    def __init__(self):
        self.researcher = Agent(
            name="Researcher",
            instruction="搜集资料,提供数据支持"
        )
        self.writer = Agent(
            name="Writer",
            instruction="撰写文章,文笔优美"
        )
        self.editor = Agent(
            name="Editor",
            instruction="编辑校对,确保质量"
        )
        self.seo_specialist = Agent(
            name="SEO",
            instruction="优化 SEO,提高搜索排名"
        )
    
    def create_article(self, topic: str):
        # 研究
        research = self.researcher.run(f"研究:{topic}")
        
        # 写作
        draft = self.writer.run(f"基于资料写文章:{research}")
        
        # 编辑
        edited = self.editor.run(f"编辑:{draft}")
        
        # SEO 优化
        final = self.seo_specialist.run(f"SEO 优化:{edited}")
        
        return final

# 使用
team = ContentTeam()
article = team.create_article("AI Agent 开发指南")

案例 2:代码审查团队

class CodeReviewTeam:
    def __init__(self):
        self.security_expert = Agent(
            name="SecurityExpert",
            instruction="检查安全漏洞"
        )
        self.performance_expert = Agent(
            name="PerformanceExpert",
            instruction="检查性能问题"
        )
        self.style_expert = Agent(
            name="StyleExpert",
            instruction="检查代码规范"
        )
        self.logic_expert = Agent(
            name="LogicExpert",
            instruction="检查逻辑错误"
        )
    
    def review_code(self, code: str):
        import asyncio
        
        # 并行审查
        tasks = [
            self.security_expert.run_async(f"安全检查:{code}"),
            self.performance_expert.run_async(f"性能检查:{code}"),
            self.style_expert.run_async(f"规范检查:{code}"),
            self.logic_expert.run_async(f"逻辑检查:{code}")
        ]
        
        reviews = await asyncio.gather(*tasks)
        
        # 汇总报告
        report = f"""
        # 代码审查报告
        
        ## 安全检查
        {reviews[0]}
        
        ## 性能检查
        {reviews[1]}
        
        ## 规范检查
        {reviews[2]}
        
        ## 逻辑检查
        {reviews[3]}
        
        ## 综合建议
        ...
        """
        
        return report

⚠️ 注意事项

1. 通信开销

# ❌ 低效:频繁通信
for i in range(10):
    result = agent1.run(f"步骤{i}")
    result = agent2.run(f"改进{result}")

# ✅ 高效:批量处理
batch_input = [f"步骤{i}" for i in range(10)]
results = agent1.run_batch(batch_input)

2. 一致性保证

# 使用共享上下文
shared_context = {
    "topic": "AI 发展",
    "style": "专业",
    "length": "3000 字"
}

agent1.run(f"写作:{shared_context}")
agent2.run(f"编辑:{shared_context}")

3. 成本控制

# 限制调用次数
class BudgetManager:
    def __init__(self, max_calls=100):
        self.calls = 0
        self.max_calls = max_calls
    
    def can_call(self) -> bool:
        return self.calls < self.max_calls
    
    def call(self, agent, prompt):
        if not self.can_call():
            raise Exception("超出预算")
        self.calls += 1
        return agent.run(prompt)

📊 效果对比

模式适用场景优点缺点
顺序协作流程化任务简单清晰速度慢
并行协作独立任务速度快需要汇总
辩论模式决策场景全面客观成本高
层级管理大型项目组织清晰管理开销
投票决策争议问题民主公正可能平庸

📚 系列导航

期数主题状态
第 4 期多 Agent 协作
第 5 期LangChain vs Google ADK下一篇

觉得有用?点赞 👍 收藏 ⭐ 关注 ➕ 三连支持一下!