1. Claude Agent Teams 实战手册:从零开始搭建多 Agent 系统

最近在AI领域,多Agent系统(Multi-Agent System)越来越受到关注。作为一个长期关注AI技术落地的开发者,我发现Claude API在构建多Agent系统方面有着独特的优势。本文将分享我从零开始搭建Claude多Agent系统的完整过程,包括环境配置、架构设计、核心代码实现以及实战中的经验教训。

多Agent系统本质上是由多个智能体组成的协作网络,每个Agent都有特定的职责和能力。通过Claude API,我们可以快速构建这样的系统,实现复杂任务的分解与协作。无论你是想开发智能客服团队、自动化流程系统,还是探索AI协作的新可能,这篇文章都能给你实用的指导。

1.1 为什么选择Claude构建多Agent系统

Claude作为新一代大语言模型,在以下几个方面特别适合构建多Agent系统:

  1. 上下文理解能力强 :支持超长上下文窗口,这对于Agent之间的信息传递至关重要
  2. API稳定性高 :相比一些开源模型,Claude API的稳定性和响应速度更适合生产环境
  3. 角色扮演能力突出 :可以很好地模拟不同专业角色的思维方式和表达风格
  4. 安全机制完善 :内置的内容安全机制减少了意外输出的风险

在实际项目中,我发现Claude Agent在以下场景表现尤为出色:

  • 需要多个专业角色协作的复杂任务
  • 需要长期记忆和上下文保持的对话系统
  • 需要高度定制化响应的工作流

2. 环境准备与基础配置

2.1 Python环境搭建

构建Claude多Agent系统需要Python 3.8或更高版本。我推荐使用conda创建独立环境:

conda create -n claude_agents python=3.10
conda activate claude_agents

核心依赖包包括:

  • anthropic :官方Claude API客户端
  • python-dotenv :管理环境变量
  • asyncio :处理并发请求
  • pydantic :数据验证和设置管理

安装命令:

pip install anthropic python-dotenv pydantic

注意:某些环境下可能需要额外安装SSL证书。如果遇到SSL错误,可以尝试:

conda install -c anaconda openssl

2.2 Claude API密钥配置

  1. 登录Claude官网获取API密钥
  2. 在项目根目录创建 .env 文件:
CLAUDE_API_KEY=your_api_key_here
CLAUDE_API_VERSION=2023-06-01
  1. 创建配置类管理API设置:
from pydantic import BaseSettings

class ClaudeConfig(BaseSettings):
    api_key: str
    api_version: str = "2023-06-01"
    max_tokens: int = 1000
    temperature: float = 0.7
    
    class Config:
        env_file = ".env"

config = ClaudeConfig()

2.3 基础Agent类实现

我们先实现一个基础Agent类,作为所有特定Agent的父类:

import anthropic
from typing import Optional, Dict, Any

class BaseAgent:
    def __init__(self, role: str, expertise: str):
        self.client = anthropic.Client(config.api_key)
        self.role = role
        self.expertise = expertise
        self.memory = []
        
    async def query(self, prompt: str) -> str:
        response = await self.client.acreate(
            prompt=f"{self.role} ({self.expertise}): {prompt}",
            stop_sequences=[anthropic.HUMAN_PROMPT],
            max_tokens_to_sample=config.max_tokens,
            temperature=config.temperature,
        )
        self.memory.append((prompt, response.completion))
        return response.completion

这个基础类提供了:

  • 角色和专业领域定义
  • 对话记忆功能
  • 异步查询接口

3. 多Agent系统架构设计

3.1 系统拓扑结构

在实践中,我发现星型结构和网状结构各有优劣:

星型结构(推荐初学者)

                [协调Agent]
                /    |    \
        [Agent1] [Agent2] [Agent3]
  • 优点:实现简单,调试方便
  • 缺点:协调Agent可能成为瓶颈

网状结构(高级用法)

        [Agent1] ↔ [Agent2]
           ↑         ↑
        [Agent3] → [Agent4]
  • 优点:更灵活的通信
  • 缺点:需要处理循环依赖

3.2 消息协议设计

Agent间通信需要统一的消息格式。我采用JSON格式,包含以下字段:

{
    "sender": "AgentName",
    "recipients": ["Agent1", "Agent2"],
    "content": "实际消息内容",
    "priority": "normal",  # low/normal/high/critical
    "context": {}  # 附加上下文
}

在Python中可以用dataclass实现:

from dataclasses import dataclass
from typing import List, Dict, Optional

@dataclass
class AgentMessage:
    sender: str
    recipients: List[str]
    content: str
    priority: str = "normal"
    context: Optional[Dict] = None

3.3 任务分解与分配策略

多Agent系统的核心是任务分解。我开发了一个基于Claude的任务分解器:

class TaskDecomposer(BaseAgent):
    def __init__(self):
        super().__init__("Task Decomposer", "Breaking down complex tasks")
        
    async def decompose(self, main_task: str) -> List[Dict]:
        prompt = f"""
        请将以下任务分解为适合不同专家Agent完成的子任务。
        每个子任务应该包含:
        - 描述
        - 所需专家类型
        - 预期输出格式
        - 优先级
        
        任务:{main_task}
        
        请用JSON格式返回分解结果,格式如下:
        {{
            "subtasks": [
                {{
                    "description": "...",
                    "expertise_required": "...",
                    "output_format": "...",
                    "priority": "..."
                }}
            ]
        }}
        """
        
        response = await self.query(prompt)
        try:
            return json.loads(response)["subtasks"]
        except json.JSONDecodeError:
            # 错误处理逻辑
            return self._handle_invalid_response(response)

4. 实现特定功能Agent

4.1 协调Agent实现

协调Agent是多Agent系统的大脑,负责:

  1. 接收初始任务
  2. 调用任务分解器
  3. 分配子任务
  4. 整合结果
class Coordinator(BaseAgent):
    def __init__(self, agents: Dict[str, BaseAgent]):
        super().__init__("Coordinator", "Task coordination")
        self.agents = agents
        self.decomposer = TaskDecomposer()
        
    async def coordinate(self, task: str) -> Dict:
        # 任务分解
        subtasks = await self.decomposer.decompose(task)
        
        # 任务分配
        results = {}
        for subtask in subtasks:
            expert_type = subtask["expertise_required"]
            if expert_type not in self.agents:
                raise ValueError(f"No agent with expertise {expert_type}")
                
            agent = self.agents[expert_type]
            results[subtask["description"]] = await agent.query(subtask["description"])
        
        # 结果整合
        integration_prompt = f"""
        请整合以下任务结果:
        原始任务:{task}
        
        子任务结果:
        {json.dumps(results, indent=2)}
        
        请提供完整的最终答案。
        """
        
        final_result = await self.query(integration_prompt)
        return {
            "original_task": task,
            "subtasks": subtasks,
            "final_result": final_result
        }

4.2 专业领域Agent示例

以技术文档编写Agent为例:

class TechnicalWriter(BaseAgent):
    def __init__(self):
        super().__init__("Technical Writer", "Creating clear technical documentation")
        
    async def write_documentation(self, spec: str) -> str:
        prompt = f"""
        根据以下技术规范编写专业文档:
        
        规范:
        {spec}
        
        要求:
        - 使用Markdown格式
        - 包含概述、使用示例、API参考
        - 技术术语准确
        - 代码示例要完整可运行
        """
        return await self.query(prompt)

4.3 记忆与上下文管理

在多轮交互中,上下文管理至关重要。我扩展了基础Agent的记忆功能:

class ContextAwareAgent(BaseAgent):
    def __init__(self, role: str, expertise: str, context_window: int = 10):
        super().__init__(role, expertise)
        self.context_window = context_window
        
    def get_relevant_context(self, current_query: str) -> str:
        # 简单的基于相似度的上下文检索
        # 实际项目中可以用向量数据库优化
        context_str = ""
        for i, (query, response) in enumerate(self.memory[-self.context_window:]):
            if current_query.lower() in query.lower() or current_query.lower() in response.lower():
                context_str += f"Previous Interaction {i+1}:\nQ: {query}\nA: {response}\n\n"
        return context_str
    
    async def query_with_context(self, prompt: str) -> str:
        context = self.get_relevant_context(prompt)
        full_prompt = f"相关上下文:\n{context}\n\n新问题:{prompt}"
        return await self.query(full_prompt)

5. 系统集成与实战示例

5.1 完整系统初始化

async def initialize_agent_team():
    agents = {
        "technical": TechnicalWriter(),
        "creative": CreativeWriter(),
        "analytical": DataAnalyst(),
        "coordinator": Coordinator({})  # 先创建空协调器
    }
    
    # 将各专业Agent注册到协调器
    agents["coordinator"].agents = {
        "technical writing": agents["technical"],
        "creative writing": agents["creative"],
        "data analysis": agents["analytical"]
    }
    
    return agents

5.2 实际运行案例

假设我们要完成"为新的Python数据分析库编写介绍文章和技术文档"的任务:

async def main():
    team = await initialize_agent_team()
    coordinator = team["coordinator"]
    
    task = """
    我们需要为新开发的Python数据分析库"PyAnalytica"创建以下材料:
    1. 面向技术用户的技术文档,包括安装指南、API参考和代码示例
    2. 面向非技术用户的介绍文章,说明库的价值和主要功能
    3. 对比分析与其他流行库(如Pandas, Polars)的性能差异
    """
    
    result = await coordinator.coordinate(task)
    print(result["final_result"])

5.3 性能优化技巧

在实际运行中,我发现以下优化手段特别有效:

  1. 异步并发控制
async def dispatch_tasks(coordinator: Coordinator, tasks: List[str]):
    semaphore = asyncio.Semaphore(5)  # 控制并发量
    
    async def limited_task(task):
        async with semaphore:
            return await coordinator.coordinate(task)
            
    return await asyncio.gather(*[limited_task(t) for t in tasks])
  1. 缓存常见响应
from functools import lru_cache

class CachedAgent(BaseAgent):
    @lru_cache(maxsize=100)
    async def cached_query(self, prompt: str) -> str:
        return await self.query(prompt)
  1. 动态温度调节
def dynamic_temperature(agent_type: str) -> float:
    """不同任务类型使用不同temperature参数"""
    if agent_type == "creative":
        return 0.9  # 更高创造性
    elif agent_type == "technical":
        return 0.3  # 更准确
    else:
        return 0.7

6. 常见问题与调试技巧

6.1 API错误处理

Claude API常见错误及解决方法:

错误代码 原因 解决方案
400 无效请求 检查prompt格式是否符合要求
429 速率限制 实现指数退避重试机制
500 服务端错误 等待后重试,检查服务状态

实现一个健壮的API调用封装:

import time
from tenacity import retry, stop_after_attempt, wait_exponential

class RobustClient:
    def __init__(self, api_key):
        self.client = anthropic.Client(api_key)
        
    @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
    async def safe_query(self, prompt: str) -> str:
        try:
            response = await self.client.acreate(
                prompt=prompt,
                max_tokens_to_sample=config.max_tokens,
                temperature=config.temperature
            )
            return response.completion
        except anthropic.APIError as e:
            if e.status_code == 429:
                time.sleep(10)  # 额外等待
            raise

6.2 Agent协作问题排查

当Agent之间协作出现问题时,可以:

  1. 记录完整的交互历史
  2. 可视化消息流
  3. 添加验证层检查消息格式

我常用的调试代码片段:

def debug_agent_interaction(messages: List[AgentMessage]):
    print("=== Agent Interaction Debug ===")
    for i, msg in enumerate(messages):
        print(f"Step {i+1}: {msg.sender} → {msg.recipients}")
        print(f"Content: {msg.content[:200]}...")
        if msg.context:
            print(f"Context Keys: {list(msg.context.keys())}")
        print("-" * 40)

6.3 提示工程优化

针对多Agent系统的提示优化技巧:

  1. 角色定义明确化
def create_role_prompt(role: str, expertise: str) -> str:
    return f"""
    你是一个专业的{role},专长是{expertise}。
    你的回答应该:
    - 体现专业领域的知识深度
    - 使用行业术语但解释关键概念
    - 提供可执行的建议
    - 在不确定时询问澄清问题
    
    当前任务:
    """
  1. 多阶段提示
async def multi_stage_query(agent: BaseAgent, stages: List[str]):
    context = ""
    for stage in stages:
        response = await agent.query(f"{context}\n{stage}")
        context += f"\n{stage}\n{response}"
    return context
  1. 输出格式化强制
def format_enforcer_prompt(instruction: str, format_example: str) -> str:
    return f"""
    {instruction}
    
    请严格按照以下格式回应:
    {format_example}
    
    你的回应必须以```format```开头,以```结尾。
    """

7. 高级主题与扩展方向

7.1 动态Agent创建

根据任务需求动态生成Agent配置:

def dynamic_agent_factory(expertise: str) -> BaseAgent:
    role_map = {
        "technical writing": TechnicalWriter,
        "data analysis": DataAnalyst,
        "creative writing": CreativeWriter
    }
    
    if expertise not in role_map:
        # 通用Agent作为回退
        return BaseAgent("Generalist", expertise)
    
    return role_map[expertise]()

7.2 长期记忆与知识库集成

将向量数据库集成到Agent系统中:

from qdrant_client import QdrantClient

class KnowledgeEnhancedAgent(BaseAgent):
    def __init__(self, role: str, expertise: str, collection_name: str):
        super().__init__(role, expertise)
        self.qdrant = QdrantClient("localhost", port=6333)
        self.collection = collection_name
        
    async def retrieve_relevant_knowledge(self, query: str, top_k: int = 3) -> List[str]:
        # 实际项目中需要实现文本嵌入
        results = self.qdrant.search(
            collection_name=self.collection,
            query_vector=get_embedding(query),
            top=top_k
        )
        return [hit.payload["content"] for hit in results]

7.3 多模态扩展

虽然Claude主要是文本模型,但可以通过以下方式扩展多模态能力:

class MultimodalCoordinator(Coordinator):
    def __init__(self, agents: Dict[str, BaseAgent], vision_agent: Optional[BaseAgent] = None):
        super().__init__(agents)
        self.vision_agent = vision_agent
        
    async def analyze_image(self, image_url: str, question: str) -> str:
        if not self.vision_agent:
            raise ValueError("Vision agent not configured")
            
        prompt = f"""
        图片URL: {image_url}
        问题: {question}
        
        请分析图片并回答问题。
        """
        return await self.vision_agent.query(prompt)

8. 实际项目经验分享

在开发商业级多Agent系统时,我总结了以下关键经验:

  1. Agent专业化程度 :不是越专越好,需要平衡专业深度和泛化能力。实践中发现3-5个核心专业Agent加2-3个通用Agent的组合效果最佳。

  2. 错误传播控制 :实现错误隔离机制,防止单个Agent的错误影响整个系统:

class FaultIsolatedAgent(BaseAgent):
    async def safe_query(self, prompt: str, fallback: str = "") -> str:
        try:
            return await self.query(prompt)
        except Exception as e:
            print(f"Agent {self.role} error: {str(e)}")
            return fallback or f"抱歉,作为{self.role},我暂时无法回答这个问题。"
  1. 人机协作设计 :关键节点加入人工审核接口:
async def human_in_the_loop(agent: BaseAgent, prompt: str) -> str:
    response = await agent.query(prompt)
    print(f"Agent建议:\n{response}")
    human_input = input("接受建议?(y/n/edit) ")
    
    if human_input.lower() == 'y':
        return response
    elif human_input.lower() == 'edit':
        return input("请输入修正内容:")
    else:
        return await human_in_the_loop(agent, prompt)  # 重试
  1. 性能监控指标 :实施全面的监控:
class MonitoredAgent(BaseAgent):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.metrics = {
            "query_count": 0,
            "avg_response_time": 0,
            "error_count": 0
        }
        
    async def query(self, prompt: str) -> str:
        start_time = time.time()
        self.metrics["query_count"] += 1
        
        try:
            response = await super().query(prompt)
            elapsed = time.time() - start_time
            # 更新平均响应时间(指数移动平均)
            self.metrics["avg_response_time"] = (
                0.9 * self.metrics["avg_response_time"] + 0.1 * elapsed
            )
            return response
        except Exception:
            self.metrics["error_count"] += 1
            raise

9. 安全与合规考量

开发生产级多Agent系统时,必须考虑以下安全因素:

  1. 内容过滤层
def safety_filter(text: str) -> str:
    # 实际项目中应使用更完善的过滤机制
    blocked_terms = ["敏感词1", "敏感词2"]
    for term in blocked_terms:
        if term in text.lower():
            raise ValueError(f"内容包含受限术语: {term}")
    return text

class SafeAgent(BaseAgent):
    async def filtered_query(self, prompt: str) -> str:
        prompt = safety_filter(prompt)
        response = await self.query(prompt)
        return safety_filter(response)
  1. API调用限制
from cachetools import TTLCache

class RateLimitedAgent(BaseAgent):
    def __init__(self, *args, max_calls: int = 30, period: int = 60, **kwargs):
        super().__init__(*args, **kwargs)
        self.cache = TTLCache(maxsize=max_calls, ttl=period)
        
    async def query(self, prompt: str) -> str:
        key = hash(prompt)  # 简单的去重键
        if key in self.cache:
            return self.cache[key]
            
        response = await super().query(prompt)
        self.cache[key] = response
        return response
  1. 数据隐私保护
def anonymize_text(text: str) -> str:
    # 简单的隐私信息替换
    import re
    text = re.sub(r"\b\d{4}[- ]?\d{4}[- ]?\d{4}\b", "[信用卡号]", text)
    text = re.sub(r"\b\d{3}[- ]?\d{2}[- ]?\d{4}\b", "[SSN]", text)
    return text

class PrivacyAwareAgent(BaseAgent):
    async def query(self, prompt: str) -> str:
        return await super().query(anonymize_text(prompt))

10. 测试与评估策略

为确保多Agent系统质量,我建立了以下测试框架:

  1. 单元测试示例
import pytest

@pytest.mark.asyncio
async def test_technical_writer_basic():
    writer = TechnicalWriter()
    response = await writer.write_documentation("Python函数sorted()")
    assert "sorted(iterable, *, key=None, reverse=False)" in response
    assert "```python" in response  # 检查代码块
  1. 集成测试框架
class AgentTestHarness:
    def __init__(self):
        self.team = None
        
    async def setup(self):
        self.team = await initialize_agent_team()
        
    async def test_end_to_end(self, task: str, expected_keywords: List[str]):
        result = await self.team["coordinator"].coordinate(task)
        for keyword in expected_keywords:
            assert keyword.lower() in result["final_result"].lower()
  1. 性能基准测试
import timeit

async def benchmark_agent(agent: BaseAgent, prompt: str, iterations: int = 10):
    def _run():
        return await agent.query(prompt)
        
    time = timeit.timeit(_run, number=iterations)
    print(f"平均响应时间: {time/iterations:.2f}秒")
  1. 质量评估指标
def evaluate_response(question: str, response: str) -> Dict[str, float]:
    """简单的自动评估"""
    return {
        "relevance": calculate_relevance(question, response),
        "accuracy": check_factual_accuracy(response),
        "completeness": len(response.split()) / len(question.split())
    }

11. 部署与规模化考量

当系统需要投入生产环境时,需要考虑以下方面:

  1. 容器化部署
FROM python:3.10-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .
CMD ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
  1. 水平扩展策略
from fastapi import FastAPI
import uvicorn

app = FastAPI()

@app.post("/query/{agent_type}")
async def query_agent(agent_type: str, prompt: str):
    agent = agent_pool.get_agent(agent_type)  # 实现Agent池
    return await agent.query(prompt)

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
  1. 负载均衡实现
class AgentLoadBalancer:
    def __init__(self, agent_class, pool_size=5):
        self.pool = [agent_class() for _ in range(pool_size)]
        self.counter = 0
        
    async def query(self, prompt: str) -> str:
        agent = self.pool[self.counter % len(self.pool)]
        self.counter += 1
        return await agent.query(prompt)
  1. 配置管理进阶
import yaml

class ConfigManager:
    def __init__(self, config_path: str):
        with open(config_path) as f:
            self.config = yaml.safe_load(f)
            
    def get_agent_config(self, agent_type: str) -> Dict:
        return self.config["agents"].get(agent_type, {})
    
    def get_system_params(self) -> Dict:
        return self.config["system"]

12. 成本优化技巧

Claude API按token计费,以下方法可显著降低成本:

  1. 响应长度预测
def estimate_token_count(text: str) -> int:
    # 简单估算:英文平均1 token≈4字符,中文≈2字符
    chinese_chars = sum(1 for c in text if '\u4e00' <= c <= '\u9fff')
    other_chars = len(text) - chinese_chars
    return (chinese_chars // 2) + (other_chars // 4)

class CostAwareAgent(BaseAgent):
    async def query(self, prompt: str, max_cost_tokens: int = 500) -> str:
        estimated_prompt_tokens = estimate_token_count(prompt)
        remaining_tokens = max_cost_tokens - estimated_prompt_tokens
        
        if remaining_tokens <= 0:
            raise ValueError("提示过长,超出预算")
            
        return await super().query(
            prompt,
            max_tokens_to_sample=min(remaining_tokens, config.max_tokens)
        )
  1. 结果缓存策略
from diskcache import Cache

cache = Cache("agent_cache")

@cache.memoize()
async def cached_query(agent: BaseAgent, prompt: str) -> str:
    return await agent.query(prompt)
  1. 精简提示工程
def optimize_prompt(original: str) -> str:
    """去除不必要的内容,保留核心指令"""
    lines = original.splitlines()
    return "\n".join(
        line for line in lines 
        if not line.strip().startswith(("请", "要求", "注意"))
    )
  1. 批量处理模式
async def batch_process(agent: BaseAgent, prompts: List[str]) -> List[str]:
    """利用Claude的上下文窗口批量处理相关查询"""
    combined_prompt = "\n\n".join(
        f"问题 {i+1}: {p}" for i, p in enumerate(prompts)
    )
    response = await agent.query(combined_prompt)
    return response.split("\n\n")[:len(prompts)]  # 简单分割

13. 替代方案与迁移策略

虽然本文聚焦Claude,但系统设计应保持一定可移植性:

  1. 抽象模型接口
from abc import ABC, abstractmethod

class LLMProvider(ABC):
    @abstractmethod
    async def query(self, prompt: str) -> str:
        pass

class ClaudeProvider(LLMProvider):
    def __init__(self, api_key: str):
        self.client = anthropic.Client(api_key)
        
    async def query(self, prompt: str) -> str:
        response = await self.client.acreate(
            prompt=prompt,
            max_tokens_to_sample=config.max_tokens
        )
        return response.completion

class Agent:
    def __init__(self, llm: LLMProvider, role: str):
        self.llm = llm
        self.role = role
        
    async def query(self, prompt: str) -> str:
        return await self.llm.query(f"{self.role}: {prompt}")
  1. 配置驱动模型切换
# config.yaml
llm_provider: "claude"  # 可切换为 openai/gemini/etc
claude:
  api_key: ${CLAUDE_API_KEY}
openai:
  api_key: ${OPENAI_API_KEY}
  1. 统一错误处理
class UnifiedAPIError(Exception):
    def __init__(self, original_exception: Exception, provider: str):
        self.original = original_exception
        self.provider = provider
        
    def __str__(self):
        return f"{self.provider} error: {str(self.original)}"

async def safe_query(llm: LLMProvider, prompt: str) -> str:
    try:
        return await llm.query(prompt)
    except Exception as e:
        raise UnifiedAPIError(e, llm.__class__.__name__)

14. 行业应用案例

多Agent系统已在多个领域展现价值:

  1. 客户支持系统
  • 路由Agent:分析客户问题类型
  • 技术Agent:处理技术问题
  • 账单Agent:解决支付问题
  • 情感Agent:检测并安抚不满情绪
  1. 内容创作流水线
async def content_pipeline(topic: str):
    team = await initialize_agent_team()
    outline = await team["planner"].query(f"创建'{topic}'的内容大纲")
    research = await team["researcher"].query(f"收集关于'{topic}'的资料")
    draft = await team["writer"].query(f"根据以下内容撰写文章:\n{outline}\n{research}")
    seo = await team["seo"].query(f"优化以下内容的SEO:\n{draft}")
    return await team["editor"].query(f"编辑并润色:\n{seo}")
  1. 数据分析工作流
  • 数据清洗Agent
  • 分析规划Agent
  • 可视化生成Agent
  • 洞察解释Agent
  1. 教育辅导系统
class TutorSystem:
    def __init__(self):
        self.agents = {
            "explainer": ConceptExplainer(),
            "example": ExampleGenerator(),
            "practice": ProblemCreator(),
            "feedback": FeedbackProvider()
        }
        
    async def teach(self, concept: str):
        explanation = await self.agents["explainer"].query(concept)
        example = await self.agents["example"].query(f"为'{concept}'创建示例")
        problem = await self.agents["practice"].query(f"关于'{concept}'的练习题")
        return {
            "explanation": explanation,
            "example": example,
            "problem": problem
        }

15. 未来发展方向

基于当前实践经验,我认为多Agent系统将朝以下方向演进:

  1. 自主目标分解
class SelfDecomposingAgent(BaseAgent):
    async def solve_complex_task(self, task: str, depth: int = 0) -> str:
        if depth > 3:  # 防止无限递归
            return await self.query(f"请直接回答:{task}")
            
        prompt = f"""
        判断以下任务是否需要分解为子任务:
        任务:{task}
        
        如果可以直接回答,请直接提供答案。
        如果需要分解,请提供JSON格式的子任务列表。
        """
        
        response = await self.query(prompt)
        try:
            subtasks = json.loads(response)
            results = {}
            for st in subtasks:
                results[st["description"]] = await self.solve_complex_task(
                    st["description"], depth+1
                )
            return json.dumps(results)
        except json.JSONDecodeError:
            return response
  1. 动态角色调整
class AdaptiveAgent(BaseAgent):
    def __init__(self, base_role: str):
        super().__init__(base_role, "Adaptive expertise")
        self.current_role = base_role
        
    async def adapt_role(self, new_role: str, description: str):
        prompt = f"""
        你现在的角色将从'{self.current_role}'转变为'{new_role}'。
        新角色描述:{description}
        
        请确认你已理解角色转变,并用适合新角色的方式回答接下来的问题。
        """
        await self.query(prompt)  # 不返回结果,只更新内部状态
        self.current_role = new_role
  1. 跨平台协作
class CrossPlatformAgent(BaseAgent):
    async def query_external_api(self, api_config: Dict, query: Dict) -> Dict:
        prompt = f"""
        根据以下API规范构建请求:
        {json.dumps(api_config, indent=2)}
        
        查询参数:
        {json.dumps(query, indent=2)}
        
        请返回:
        1. 完整的请求URL
        2. 请求方法(GET/POST等)
        3. 请求体(如适用)
        4. 预期的响应处理方式
        """
        plan = await self.query(prompt)
        # 实际实现会解析plan并执行请求
        return execute_api_plan(plan)
  1. 持续学习机制
class LearningAgent(BaseAgent):
    def __init__(self, *args, knowledge_base: str = None, **kwargs):
        super().__init__(*args, **kwargs)
        self.knowledge_base = knowledge_base or "agent_knowledge.txt"
        
    async def update_knowledge(self, new_info: str):
        with open(self.knowledge_base, "a") as f:
            f.write(f"\n{datetime.now()}\n{new_info}\n")
            
    async def query(self, prompt: str) -> str:
        with open(self.knowledge_base) as f:
            knowledge = f.read()
            
        enhanced_prompt = f"""
        已知知识:
        {knowledge[-5000:]}  # 防止过长
        
        新问题:
        {prompt}
        """
        response = await super().query(enhanced_prompt)
        
        # 自动判断是否需要更新知识库
        if "新知识" in response or "更新记录" in response:
            await self.update_knowledge(response)
            
        return response

16. 开发者资源推荐

为了帮助开发者更好地构建多Agent系统,我整理了一些实用资源:

  1. 开源框架
  • AutoGen:微软开发的多Agent对话框架
  • LangChain:虽然不专为多Agent设计,但提供了有用组件
  • CrewAI:专门面向多Agent协作的框架
  1. 开发工具
# 调试工具:实时显示Agent间通信
class DebugMiddleware:
    def __init__(self, agent: BaseAgent):
        self.agent = agent
        
    async def query(self, prompt: str) -> str:
        print(f"-> {self.agent.role} 接收:{prompt[:100]}...")
        start = time.time()
        response = await self.agent.query(prompt)
        elapsed = time.time() - start
        print(f"<- {self.agent.role} 响应 ({elapsed:.2f}s):{response[:100]}...")
        return response
  1. 学习资料
  • 《Multi-Agent Systems: Algorithmic, Game-Theoretic, and Logical Foundations》
  • 斯坦福AI课程中的多Agent系统章节
  • Anthropic官方文档中的最佳实践指南
  1. 性能分析工具
# 简单的性能分析装饰器
def profile_agent(func):
    async def wrapper(*args, **kwargs):
        start_time = time.time()
        result = await func(*args, **kwargs)
        elapsed = time.time() - start_time
        print(f"{func.__name__} 耗时: {elapsed:.2f}秒")
        return result
    return wrapper

class ProfiledAgent(BaseAgent

更多推荐