第2课:Agent系统架构与设计模式

发布于:2025-09-15 ⋅ 阅读:(17) ⋅ 点赞:(0)

第2课:Agent系统架构与设计模式

课程目标

  • 理解Agent的基本概念和特性
  • 掌握多Agent系统的设计模式
  • 学习Agent通信协议和消息传递
  • 实践创建简单的Agent框架

课程内容

2.1 Agent基础概念

什么是Agent?

Agent是一个具有自主性、反应性、社会性和主动性的计算实体,能够:

  • 自主性:独立运行,无需人工干预
  • 反应性:对环境变化做出响应
  • 社会性:与其他Agent协作
  • 主动性:主动发起行动
Agent的核心组件
┌─────────────────────────────────────┐
│              Agent                  │
├─────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐   │
│  │   感知层     │  │   决策层     │   │
│  │ Perception  │  │ Decision    │   │
│  └─────────────┘  └─────────────┘   │
│  ┌─────────────┐  ┌─────────────┐   │
│  │   执行层     │  │   通信层     │   │
│  │ Execution   │  │ Communication│   │
│  └─────────────┘  └─────────────┘   │
└─────────────────────────────────────┘

2.2 Agent设计模式

1. 主从模式(Master-Slave)
    Master Agent
         │
    ┌────┼────┐
    │    │    │
Slave1  Slave2  Slave3
  • 特点:集中式控制,简单易实现
  • 适用场景:任务分解、并行处理
  • 缺点:单点故障,扩展性差
2. 对等模式(Peer-to-Peer)
    Agent1 ←→ Agent2
       ↕        ↕
    Agent3 ←→ Agent4
  • 特点:分布式控制,高可用性
  • 适用场景:协作任务、分布式计算
  • 缺点:协调复杂,一致性难保证
3. 层次模式(Hierarchical)
    Top Agent
         │
    ┌────┼────┐
    │    │    │
Mid1   Mid2   Mid3
  │     │     │
┌─┼─┐ ┌─┼─┐ ┌─┼─┐
│ │ │ │ │ │ │ │ │
L1 L2 L3 L4 L5 L6 L7 L8
  • 特点:分层管理,职责明确
  • 适用场景:大型系统、组织管理
  • 缺点:通信开销大,响应延迟
4. 联邦模式(Federated)
    Federation Manager
         │
    ┌────┼────┐
    │    │    │
Group1 Group2 Group3
  │     │     │
┌─┼─┐ ┌─┼─┐ ┌─┼─┐
│ │ │ │ │ │ │ │ │
A1 A2 A3 A4 A5 A6 A7 A8
  • 特点:分组管理,灵活扩展
  • 适用场景:多域协作、模块化系统
  • 缺点:管理复杂,跨组协调困难

2.3 Agent通信协议

消息传递模式
  1. 同步通信:请求-响应模式
  2. 异步通信:发布-订阅模式
  3. 广播通信:一对多模式
  4. 多播通信:多对多模式
通信协议设计
// 消息格式定义
const MessageType = {
  REQUEST: 'request',
  RESPONSE: 'response',
  NOTIFICATION: 'notification',
  ERROR: 'error'
};

class AgentMessage {
  constructor(type, from, to, content, id = null) {
    this.type = type;
    this.from = from;
    this.to = to;
    this.content = content;
    this.id = id || this.generateId();
    this.timestamp = Date.now();
  }

  generateId() {
    return Math.random().toString(36).substr(2, 9);
  }
}

实践项目

项目1:基础Agent框架

// agent.js
class Agent {
  constructor(id, name, capabilities = []) {
    this.id = id;
    this.name = name;
    this.capabilities = capabilities;
    this.state = 'idle';
    this.messageQueue = [];
    this.messageHandlers = new Map();
  }

  // 发送消息
  async sendMessage(to, type, content) {
    const message = new AgentMessage(type, this.id, to, content);
    
    // 这里应该通过通信层发送
    console.log(`${this.name} 发送消息到 ${to}:`, message);
    
    return message;
  }

  // 接收消息
  receiveMessage(message) {
    this.messageQueue.push(message);
    this.processMessages();
  }

  // 处理消息
  async processMessages() {
    while (this.messageQueue.length > 0) {
      const message = this.messageQueue.shift();
      await this.handleMessage(message);
    }
  }

  // 消息处理
  async handleMessage(message) {
    const handler = this.messageHandlers.get(message.type);
    if (handler) {
      await handler(message);
    } else {
      console.log(`${this.name} 收到未知类型消息:`, message);
    }
  }

  // 注册消息处理器
  onMessage(type, handler) {
    this.messageHandlers.set(type, handler);
  }

  // 执行能力
  async executeCapability(capability, params) {
    if (this.capabilities.includes(capability)) {
      console.log(`${this.name} 执行能力: ${capability}`, params);
      // 这里实现具体的能力逻辑
      return { success: true, result: `执行了 ${capability}` };
    } else {
      throw new Error(`Agent ${this.name} 不具备能力: ${capability}`);
    }
  }
}

项目2:多Agent协作系统

// multi-agent-system.js
class MultiAgentSystem {
  constructor() {
    this.agents = new Map();
    this.messageRouter = new MessageRouter();
  }

  // 注册Agent
  registerAgent(agent) {
    this.agents.set(agent.id, agent);
    this.messageRouter.registerAgent(agent);
    console.log(`Agent ${agent.name} 已注册`);
  }

  // 启动系统
  start() {
    console.log('多Agent系统已启动');
    this.agents.forEach(agent => {
      agent.state = 'running';
    });
  }

  // 停止系统
  stop() {
    console.log('多Agent系统已停止');
    this.agents.forEach(agent => {
      agent.state = 'stopped';
    });
  }

  // 获取Agent
  getAgent(id) {
    return this.agents.get(id);
  }

  // 广播消息
  broadcast(type, content, excludeId = null) {
    this.agents.forEach((agent, id) => {
      if (id !== excludeId) {
        agent.receiveMessage(new AgentMessage(type, 'system', id, content));
      }
    });
  }
}

// 消息路由器
class MessageRouter {
  constructor() {
    this.routes = new Map();
  }

  registerAgent(agent) {
    this.routes.set(agent.id, agent);
  }

  routeMessage(message) {
    const targetAgent = this.routes.get(message.to);
    if (targetAgent) {
      targetAgent.receiveMessage(message);
    } else {
      console.error(`目标Agent不存在: ${message.to}`);
    }
  }
}

项目3:任务协作示例

// task-collaboration.js
class TaskCollaborationSystem extends MultiAgentSystem {
  constructor() {
    super();
    this.tasks = new Map();
    this.taskQueue = [];
  }

  // 创建任务
  createTask(taskId, description, requirements) {
    const task = {
      id: taskId,
      description,
      requirements,
      status: 'pending',
      assignedAgents: [],
      results: []
    };
    
    this.tasks.set(taskId, task);
    this.taskQueue.push(task);
    this.assignTasks();
  }

  // 分配任务
  assignTasks() {
    while (this.taskQueue.length > 0) {
      const task = this.taskQueue.shift();
      const availableAgents = this.findAvailableAgents(task.requirements);
      
      if (availableAgents.length > 0) {
        this.assignTaskToAgents(task, availableAgents);
      } else {
        // 没有可用Agent,重新加入队列
        this.taskQueue.push(task);
        break;
      }
    }
  }

  // 查找可用Agent
  findAvailableAgents(requirements) {
    const available = [];
    
    this.agents.forEach(agent => {
      if (agent.state === 'idle' && 
          requirements.every(req => agent.capabilities.includes(req))) {
        available.push(agent);
      }
    });
    
    return available;
  }

  // 分配任务给Agent
  assignTaskToAgents(task, agents) {
    task.assignedAgents = agents.map(agent => agent.id);
    task.status = 'in_progress';
    
    agents.forEach(agent => {
      agent.state = 'busy';
      agent.receiveMessage(new AgentMessage(
        'task_assignment',
        'system',
        agent.id,
        { taskId: task.id, description: task.description }
      ));
    });
  }

  // 处理任务完成
  handleTaskCompletion(agentId, taskId, result) {
    const task = this.tasks.get(taskId);
    if (task) {
      task.results.push({ agentId, result });
      
      // 检查是否所有Agent都完成了任务
      if (task.results.length === task.assignedAgents.length) {
        task.status = 'completed';
        this.consolidateResults(task);
      }
    }
  }

  // 整合结果
  consolidateResults(task) {
    console.log(`任务 ${task.id} 已完成,结果:`, task.results);
    
    // 释放Agent
    task.assignedAgents.forEach(agentId => {
      const agent = this.getAgent(agentId);
      if (agent) {
        agent.state = 'idle';
      }
    });
    
    // 继续处理队列中的任务
    this.assignTasks();
  }
}

项目4:使用示例

// example.js
async function main() {
  // 创建多Agent系统
  const system = new TaskCollaborationSystem();
  
  // 创建不同类型的Agent
  const dataAgent = new Agent('data-001', '数据分析Agent', ['data_analysis', 'statistics']);
  const reportAgent = new Agent('report-001', '报告生成Agent', ['report_generation', 'formatting']);
  const emailAgent = new Agent('email-001', '邮件发送Agent', ['email_sending', 'notification']);
  
  // 注册Agent
  system.registerAgent(dataAgent);
  system.registerAgent(reportAgent);
  system.registerAgent(emailAgent);
  
  // 设置消息处理
  dataAgent.onMessage('task_assignment', async (message) => {
    console.log(`${dataAgent.name} 收到任务: ${message.content.description}`);
    // 模拟任务执行
    await new Promise(resolve => setTimeout(resolve, 2000));
    system.handleTaskCompletion(dataAgent.id, message.content.taskId, '数据分析完成');
  });
  
  reportAgent.onMessage('task_assignment', async (message) => {
    console.log(`${reportAgent.name} 收到任务: ${message.content.description}`);
    await new Promise(resolve => setTimeout(resolve, 1500));
    system.handleTaskCompletion(reportAgent.id, message.content.taskId, '报告生成完成');
  });
  
  emailAgent.onMessage('task_assignment', async (message) => {
    console.log(`${emailAgent.name} 收到任务: ${message.content.description}`);
    await new Promise(resolve => setTimeout(resolve, 1000));
    system.handleTaskCompletion(emailAgent.id, message.content.taskId, '邮件发送完成');
  });
  
  // 启动系统
  system.start();
  
  // 创建任务
  system.createTask('task-001', '分析销售数据并生成报告', ['data_analysis', 'report_generation']);
  system.createTask('task-002', '发送通知邮件', ['email_sending']);
  
  // 等待任务完成
  await new Promise(resolve => setTimeout(resolve, 5000));
  
  system.stop();
}

main().catch(console.error);

课后练习

  1. 基础练习:实现一个简单的聊天Agent系统
  2. 进阶练习:创建支持任务分解的协作系统
  3. 挑战练习:实现动态Agent发现和注册机制

学习资源

下节课预告

下一课我们将学习大模型集成与API设计,了解如何将大模型能力集成到Agent系统中。


学习时间建议:3-4小时
难度等级:⭐⭐⭐☆☆
实践重点:Agent框架设计和多Agent协作