AI Agent 开发指南

概述

本文档整合了复杂 AI Agent 开发的核心方法论,涵盖架构设计、协议标准、最佳实践。

Google AI Agent 白皮书核心框架 (2024)

详见 源:Google AI Agent 白皮书

核心定义

  • Agent = 扩展了大模型出厂能力的应用程序
  • 目标:通过观察世界并使用工具来达成目标
  • 即使面对模糊指令也能推理出下一步行动

三组件架构

  1. Model: 核心决策者,支持 ReAct / CoT / ToT 推理
  2. Tool: 三种类型 — Extensions (Agent端API)、Functions (客户端)、Data Stores (RAG)
  3. Orchestration: 认知架构核心,“规划—执行—调整”循环

关键推理框架

框架特点适用场景
ReActThought -> Action -> Observation 循环通用任务
Chain-of-Thought逐步推理逻辑推理
Tree-of-Thoughts多路径探索战略前瞻

核心技术标准

MCP (Model Context Protocol)

定位:Agent ↔ 工具/数据源 的通信标准

# MCP 核心交互模式
{
    "jsonrpc": "2.0",
    "method": "tools/call",
    "params": {
        "name": "filesystem_read",
        "arguments": {"path": "/project/main.py"}
    }
}

优势

  • 统一工具调用接口
  • 插件式扩展
  • 厂商中立

A2A (Agent-to-Agent)

定位:Agent ↔ Agent 的通信协议

核心场景

  1. 任务分解与协作
  2. 专家咨询
  3. 流水线处理
  4. 任务交接

架构设计

单 Agent 架构

┌──────────────────────────────────────┐
│              User Input              │
└─────────────────┬────────────────────┘
                  ↓
┌──────────────────────────────────────┐
│          Planning Module             │
│  - 任务分解                          │
│  - 步骤排序                          │
│  - 依赖分析                          │
└─────────────────┬────────────────────┘
                  ↓
┌──────────────────────────────────────┐
│          Execution Module            │
│  - 工具选择                          │
│  - MCP 调用                          │
│  - API 请求                          │
└─────────────────┬────────────────────┘
                  ↓
┌──────────────────────────────────────┐
│         Reflection Module            │
│  - 结果评估                          │
│  - 错误处理                          │
│  - 策略调整                          │
└─────────────────┬────────────────────┘
                  ↓
┌──────────────────────────────────────┐
│            User Output               │
└──────────────────────────────────────┘

Anthropic 的 Multi-Agent Research 架构(2025)

Anthropic 官方开源的 Multi-Agent Research 系统(../sources/2026-05-05-Anthropic-Multi-Agent-Research系统;最新补充见 Claude Deep Research Architecture),采用 Orchestrator-Worker 模式:

架构:Lead Agent(协调规划)→ 并行 Sub-agents(独立研究)→ Citation Agent(引用处理)→ 最终报告

核心发现:token 使用量解释了性能差异的 80%,Tool 调用次数和模型选择只占 15%。Multi-Agent 通过将工作分散到独立上下文窗口增加并行推理容量。Opus lead + Sonnet subagents 的组合在 Anthropic 内部研究评测中比单 Opus 高 90.2%,但 multi-agent research 约消耗普通聊天 15× token。

查询类型三分法

  • Depth-first:多视角深钻同一问题(3-5 个不同方法论)
  • Breadth-first:多方向并行探索(按独立子主题拆解)
  • Straightforward:单 Agent 直接事实查找(1 agent, 3-10 tool calls)

Agent 预算管理:简单 1 agent 3-10 调用 → 标准 2-3 agent 10-15 调用 → 中等 3-5 agent → 高复杂 5-20 agent(最多 20)。Deep research 类任务还可按复杂度伸缩:简单事实查询 1 agent,直接对比 2-4 agent,开放复杂研究才进入 10+ subagent。

可靠性机制:Subagent 是“智能过滤器”,只把压缩后的关键发现回传;Citation Agent 或后处理阶段把结论绑定到来源;Claude Code /deep-research 进一步加入 cross-check / survival vote,只保留多来源一致的 claim。

Token 经济性:Multi-Agent token 消耗是聊天交互的 15 倍,对大多数编码任务并非良好适配(可并行子任务少)

评估体系:小样本快速迭代(~20 个查询)→ LLM-as-Judge 大规模评估 → 人工捕获自动化遗漏

多 Agent 架构

// 简化的多 Agent 协作示例
type MultiAgentSystem struct {
    Supervisor *Agent
    Workers    map[string]*Agent
    Registry   *AgentRegistry
}
 
// 任务分配流程
func (s *MultiAgentSystem) Distribute(task *Task) {
    subtasks := s.Supervisor.Decompose(task)
    for _, sub := range subtasks {
        worker := s.SelectWorker(sub.Type)
        s.executeAsync(worker, sub)
    }
    s.Supervisor.AggregateResults()
}

开发最佳实践

1. 上下文管理

策略适用场景Token 节省
滑动窗口长对话30-50%
摘要压缩历史信息50-70%
增量更新频繁交互40-60%
分层记忆复杂任务60-80%

2. 工具设计原则

工具设计决定 Agent 能力上限

  • 原子性:每个工具做一件事
  • 幂等性:重复调用结果一致
  • 可观测:明确的成功/失败状态
  • 可组合:工具可嵌套使用

3. 错误处理

# 分层错误处理策略
class AgentErrorHandler:
    def handle(self, error: Error, context: Context):
        if error.recoverable:
            return self.retry_with_backoff(error)
        elif error.reducible:
            return self.decompose_and_retry(error)
        else:
            return self.escalate_to_human(error)

技术选型

编程语言

语言优势适用场景
Python生态丰富、易上手快速原型
Go高并发、部署简单生产环境
Rust性能极致、安全关键路径

框架选择

  • LangChain: 快速构建、灵活性高
  • CrewAI: 多 Agent 协作
  • AutoGen: 微软开源、社区活跃
  • 自研: 完全可控、定制能力强

性能优化

1. Token 优化

  • 结构化输出减少解析开销
  • 批量请求合并
  • 缓存常见模式

2. 延迟优化

  • 预热模型
  • 异步执行
  • 流式响应

3. 可靠性优化

  • 健康检查
  • 熔断机制
  • 降级策略

相关资源

范式转变:框架 > 模型(罗福莉 2026)

From Luo-Fuli’s deep-dive on AI paradigm shift:

核心判断

中层模型 + 好框架 约等于 顶尖模型 + 简单框架

3B 端侧小模型接入 OpenClaw 后完成了千亿参数模型都可能吃力的事。瓶颈不在模型参数量。

模型是消耗品,框架是资产

用 Opus 花近 $1000 打造 Agent 框架后,日常切换更便宜模型效果同样好。框架积累不可逆,模型可以更换。

框架的三层架构

  1. 人的交互层 — 人怎么和 AI 打交道
  2. 模型沟通层 — 框架怎么和模型说话
  3. 调度层 — 感知不同模型长短板做调度优化

“前端 UI 是最薄的一层。竞争发生在框架编排的深度和精细度。“

Skills = 另类信息(Alpha)

Skills 是互联网访问不到的智能:企业规范、组织经验、个人教给 Agent 的执行标准。预训练给公开知识,Skills 给私域智能——两者合起来才是完整知识栈。

Agent 训 Agent

Agent 已有能力复原研究员 5 年科研成长路径。1-2 年内可能实现 Agent 训出比人更好的模型,“左脚踩右脚往上提升”。Post Train 算力正追平 Pre Train(35:1 → 1:1)。

MiMo V2 架构启示

MLA 已到完美临界点,无法利用 MTP 加速。Hybrid Attention 保留计算富余,MTP 正好利用:Flash 100-150 TPS,Pro 60-100 TPS(vs 常见千亿模型 30-50 TPS)。教训:架构为目标之外的变化留空间。

Sources: 2026-05-05-Luo-Fuli-framework-over-model, 2026-05-02-Luo-Fuli-AI-speed-management

标签

ai agent development architecture mcp a2a

Agent Evaluation and Testing (2026-05 Update)

See AI-Agent-Evaluation for the dedicated evaluation methodology page. The key update from the May 2026 ingest is that Agent development must include evaluation as a first-class subsystem, not a final QA step.

Core practices:

  • Build Eval datasets from real user behavior and bad cases, not only designed test cases.
  • Use deterministic sandboxes to isolate model, prompt, tool, memory, and environment variables.
  • Combine outcome metrics, process metrics, and efficiency metrics.
  • Record full traces for model calls, tool calls, context, token cost, latency, and judge rationale.
  • Connect Eval regressions to CI/CD so every model/prompt/tool change is checked automatically.

Related sources: Agent 测试统一沙盒, Agent Eval 数据集, SaaS-Bench.

Agent-Era Productivity Paradox (2026-05)

From Agent-Era Productivity Paradox (Alibaba engineer 向邦宇):

The Core Problem

Agent code generation speed grows exponentially, but organizational R&D efficiency gains are limited. The constraint is no longer code production speed but software organization structure. Traditional frontend/backend/product/dev/test separation creates context interruption, information loss, and collaboration friction for AI agents.

Key Structural Issues

  1. Code is separated from code: Client/frontend/backend/microservices in separate repos
  2. Code is separated from documentation: Requirements on Yuque, API specs in Swagger, discussions in chat
  3. Documentation maintained by humans: Always lags behind code changes

Proposed Solutions

  • All-in-Code: All R&D resources in unified version-controlled monorepo
  • Version Everything: External docs, requirements, dependencies all versioned locally
  • Agent Teams: Platform for human orchestration of heterogeneous agent teams
  • ChangeSet: Unified change tracking beyond Git branches
  • Agentic IAM: Identity & access management for autonomous software entities

Real-World One-Person Agent Business (2026-05)

From One-Person Business $20K/month:

A Chinese developer built a 7-agent system (Scout, Diagnoser, Builder, Filmer, Pitcher, Checker, Mobile) using Claude Sonnet 4.6 to automate landing page creation for US small businesses. Revenue: ~18,800/month, API cost: ~480/month. Key design principle: strict agent boundaries with human review triggers (orders >$3K, reply rate <12%).

[2026-07-17] 信息层栈成型 + Skill 工业化 + 乐高组合范式

  • Agent 信息层栈三层成型(本批次开源项目实证):① 接入层 Agent-Reach(50.7k 星 CLI 脚手架,Cookie 认证绕 API 成本 0 vs 200/月,打通 Reddit/X/小红书/B 站/公众号);② 过滤/打分层 last30days(4.6 万星 skill,并行扒多平台按真人互动量打分,v3 预研脑子先认人认圈子);③ 存储/检索层 OpenViking(2.6 万星,文件系统范式 + L0/L1/L2 + 检索轨迹可视化)。三层非同类竞品,而是 Agent 感知→记忆栈的不同分工——呼应本页 Google 白皮书三组件 Tool 层(Extensions/Functions/Data Stores)的工业化分工。
  • OpenViking vs 传统 RAG:不是扁平向量库而是文件系统范式管理上下文——L0(核心提示词每次加载)/L1(当前任务按需加载)/L2(历史记忆按需检索),先目录定位再语义匹配,检索轨迹可视化(出错能看到 Agent 先打开哪个目录、检索哪些文件)。2026-05 评测在 User Memory、Agent Memory、知识库问答三场景都比传统方案好且 Token 更省。
  • Skill 工业化实证:sansheng-write(9 阶段/19 脚本/12000+ 行/227 测试/7 质量门/状态机可恢复/verify 读像素验收/黄金快照/学习飞轮)+ apple-design(17 条 WWDC 原则蒸馏/可中断性/材质层级)+ last30days(版本号/回归测试/1000 行指令翻车写进更新记录)——Skill 从”攒提示词加脚本”演进为工程化软件,印证 Skill-EngineeringSkills-Ecosystem 的”Skill 不是 prompt 而是’什么算完成’的定义”。
  • 乐高式组合 + 日抛软件:sansheng-write 整合 baoyu-skills/gzh-design-skill/MiniMax/Gemini,每块各仓独立迭代;作者论断”Agent 时代软件正变日抛型,模型三个月一换代,一个人闭门迭代不可能”——直接呼应本页”模型是消耗品,框架是资产”(罗福莉)论断。

来源:../sources/2026-07-17-AI-Agent开源工具生态