The Agency 深度解析:144个AI专家代理组成的虚拟团队——从多智能体架构到生产级部署的完整技术指南(2026)
关键词:多智能体系统、AI Agent、Claude Code、Cursor、虚拟团队、提示工程、AI工作流自动化
摘要
2026年,AI编程工具已经从"代码补全"进化到"自主Agent",但大多数开发者仍然在用一个通用AI助手处理所有任务。The Agency项目的出现改变了一切——它提供144个高度专业化的AI专家代理,覆盖工程开发、数字营销、电商运营、内容创作等12个部门,每个代理都拥有独特的个性、专业工作流程和可验证的交付成果。本文将深入解析The Agency的技术架构、多智能体协作机制、与Claude Code/Cursor的集成方式,以及如何在实际项目中部署这支"AI虚拟团队"。
第一章:背景介绍——为什么我们需要一个AI专家团队?
1.1 通用AI助手的困境
2024年到2026年,AI辅助编程工具经历了三次革命性跃迁:
第一代(2024年):GitHub Copilot为代表的代码补全工具。核心能力是"下一行代码预测",帮助开发者减少键盘输入,但缺乏上下文理解,更谈不上任务规划。
第二代(2025年):Claude Code、Cursor为代表的Agent式编码助手。核心能力是"理解需求→拆解任务→自主执行",可以独立完成一个功能模块的开发。但问题在于:它们是"通用助手",什么都能做,但什么都不精深。
第三代(2026年):The Agency、Hermes Agent为代表的"专业化Agent生态"。核心范式是"让专业的人做专业的事"——不是训练一个超级通用的AI,而是构建一群各司其职的专家Agent,通过协作完成复杂任务。
1.2 The Agency的诞生故事
The Agency项目源于Reddit社区的一次讨论。创始人msitarzewski(Michal Staniszewski)在r/ClaudeAI板块提出了一个问题:
"为什么我们要用一个通用的AI助手来处理所有任务?现实生活中,你会让一个全能型'万金油'医生做心脏手术吗?"
这个问题引发了大量开发者的共鸣。随后几个月,社区持续迭代,最终形成了一套包含51个(现已扩展至144个)高度专业化AI代理的开源项目。
项目核心设计哲学:
- 每个Agent都是某个领域的专家,拥有该领域的深度知识和专业工作流程
- 每个Agent都有鲜明的个性,不是冷冰冰的指令执行器,而是有"职业习惯"的专家
- 每个Agent都能交付可验证的成果,不是泛泛而谈,而是产出具体可用的交付物
1.3 为什么2026年是多智能体系统的爆发元年?
三个技术趋势的共同作用,让The Agency这样的项目在2026年爆发:
趋势一:大模型的上下文窗口突破128K+
2026年,Claude Opus 4.6支持200K上下文,GPT-5.5支持128K,Gemini 3.1更是达到1M上下文。这意味着一个Agent提示词可以非常详细——不仅包含角色定义,还可以包含完整的工作流程、质量标准、交付模板。
趋势二:Agent工具调用能力成熟
2025年底,MCP(Model Context Protocol)协议被广泛采用,Claude Code、Cursor等工具都支持通过MCP扩展Agent的工具调用能力。The Agency的Agent定义文件(CLAUDE.md、.cursorrules等)可以一键安装到这些工具中,立即获得专业能力提升。
趋势三:开发者对"AI交付质量"的要求大幅提升
早期开发者满足于"AI能写代码就行",但2026年的开发者要求AI交付的代码必须:符合项目规范、包含完整测试、有详细的注释和文档、通过静态分析检查。通用AI助手很难同时满足所有这些要求,而专业Agent可以针对特定领域内置这些质量标准。
第二章:核心概念——The Agency的架构设计哲学
2.1 144个Agent是如何组织的?
The Agency采用**"部门-团队-专家"**三级组织架构,模拟一个完整公司的结构:
The Agency
├── 工程部(Engineering Division)
│ ├── 前端魔术师(Frontend Wizard)
│ ├── 后端架构师(Backend Architect)
│ ├── 全栈集成者(Full-Stack Integrator)
│ ├── DevOps管道工(DevOps Pipeline Engineer)
│ ├── 测试质量保证专家(QA Engineer)
│ └── 安全审计员(Security Auditor)
│
├── 营销部(Marketing Division)
│ ├── SEO优化大师(SEO Sorcerer)
│ ├── 社交媒体忍者(Social Media Ninja)
│ ├── 内容策略师(Content Strategist)
│ ├── 邮件营销专家(Email Marketing Maestro)
│ └── 品牌声音守护者(Brand Voice Guardian)
│
├── 销售部(Sales Division)
│ ├── 潜在客户磁铁(Lead Magnet)
│ ├── 销售脚本作家(Sales Script Scribe)
│ ├── CRM流程优化师(CRM Flow Optimizer)
│ └── 客户旅程映射师(Customer Journey Mapper)
│
├── 内容创作部(Content Creation Division)
│ ├── 病毒文案撰写者(Viral Copywriter)
│ ├── 技术博客作者(Technical Blogger)
│ ├── 视频脚本作家(Video Script Writer)
│ └── 创意注入师(Whimsy Injector)
│
├── 数据分析部(Data Analysis Division)
│ ├── 数据叙事者(Data Storyteller)
│ ├── AB测试分析师(AB Testing Analyst)
│ ├── 用户行为解码师(User Behavior Decoder)
│ └── 指标仪表盘设计师(Metrics Dashboard Designer)
│
├── 产品设计部(Product Design Division)
│ ├── UI/UX设计师(UI/UX Designer)
│ ├── 用户调研专家(User Research Specialist)
│ ├── 原型设计快速者(Rapid Prototyping Pro)
│ └── 设计系统架构师(Design System Architect)
│
└── ...(其他7个部门)
每个部门内部,Agent之间不是孤立的,而是可以协作的。例如,一个完整的功能发布流程可能是:
- 产品经理Agent 定义需求和用户故事
- UI/UX设计Agent 产出设计稿和原型
- 前端开发Agent 实现界面
- 后端开发Agent 实现API
- 测试Agent 编写和执行测试用例
- DevOps Agent 配置CI/CD管道并部署
- 监控Agent 设置线上监控和告警
2.2 Agent提示词工程的核心技巧
The Agency的每个Agent都由一个详细的提示词文件定义。以"前端魔术师(Frontend Wizard)"为例,其提示词结构如下:
# Frontend Wizard - Agent Definition
## Role Definition
You are a senior frontend developer with 8+ years of experience
specializing in React, TypeScript, and modern CSS frameworks.
You have a keen eye for design details and a passion for creating
pixel-perfect, accessible user interfaces.
## Core Responsibilities
1. Implement UI components based on design mockups
2. Ensure all components are fully accessible (WCAG 2.1 AA compliant)
3. Write TypeScript with strict mode enabled
4. Optimize for performance (Core Web Vitals)
5. Write unit tests with >80% coverage
## Workflow
1. Always start by understanding the design requirements
2. Break down the UI into reusable components
3. Implement components with TypeScript interfaces first
4. Add styling using CSS Modules or Tailwind (project-dependent)
5. Write tests before implementation (TDD when possible)
6. Run accessibility audit using axe-core
7. Optimize bundle size and lazy-load when appropriate
## Quality Standards
- All components must have proper ARIA labels
- No `any` type in TypeScript
- All interactive elements must be keyboard accessible
- Color contrast ratio must meet WCAG AA standards
- Components must be responsive (mobile-first)
## Communication Style
- Concise and technical
- Proactive about suggesting improvements
- Always explain the "why" behind technical decisions
这种提示词设计的核心技巧:
技巧一:角色定义要具体且有代入感
不要写"你是一个前端开发助手",而要写"你是一个有8年以上经验的资深前端开发,精通React和TypeScript,对设计细节有敏锐的洞察力"。具体的数据(8年、WCAG 2.1 AA)让AI更容易进入角色。
技巧二:工作流程要可执行
不是泛泛地说"写好代码",而是明确给出步骤:先理解设计需求→拆分成可复用组件→先写TypeScript接口→再实现样式→写测试→无障碍审计→性能优化。AI会严格遵循这个流程。
技巧三:质量标准要可验证
"代码质量高"是主观的,"所有组件必须有正确的ARIA标签、TypeScript不允许any类型、交互元素必须支持键盘操作"是客观的、可验证的标准。AI会自检是否符合这些标准。
技巧四:沟通风格要符合角色身份
一个资深前端专家的沟通方式应该是"简洁且技术化、主动建议改进、解释技术决策背后的原因",而不是"好的,我帮您实现"。
2.3 个性注入(Whimsy Injection)——让Agent不再机械
The Agency最具创新性的设计之一是"Whimsy Injector(创意注入师)"这个Agent。它的作用不是直接完成技术任务,而是为其他Agent的输出注入创意和人性化的表达。
例如,一个标准的产品描述可能是:
"这款笔记本电有16GB内存和512GB SSD,适合日常办公使用。"
经过Whimsy Injector处理后:
"想象一下:你正坐在咖啡馆里,阳光透过窗户洒在桌面上。你打开这台笔记本电——秒速唤醒,16GB内存让几十个浏览器标签页同时打开也不卡顿,512GB SSD让系统和应用加载快如闪电。这不是一台机器,这是你创造力的延伸。"
这种"人性化表达"的注入,对于营销内容、用户沟通、产品文档等场景极其重要。The Agency的架构允许在流水线中插入Whimsy Injector,让技术性的输出变得更加易读和吸引人。
第三章:架构分析——The Agency的技术实现
3.1 Agent定义文件的格式与兼容性
The Agency的Agent定义文件支持多种格式,以兼容不同的AI编程工具:
格式一:CLAUDE.md(Claude Code专用)
# Claude Code Agent Definition
# File name: CLAUDE.md (place in project root)
You are a [ROLE] specialized in [DOMAIN].
## Instructions
[Detailed instructions here]
## Constraints
- [Constraint 1]
- [Constraint 2]
## Examples
[Example interactions]
格式二:.cursorrules(Cursor专用)
{
"role": "Frontend Wizard",
"instructions": "You are a senior frontend developer...",
"rules": [
"Always use TypeScript strict mode",
"No `any` type allowed"
],
"examples": []
}
格式三:.aiderules(Aider专用)
# Aider Agent Rules
You are a [...]
## Rules
1. ...
2. ...
格式四:GitHub Copilot指令文件
// .github/copilot-instructions.md
# Copilot Instructions for [Role]
...
The Agency为每个Agent提供所有四种格式的定义文件,用户可以根据自己的工具链选择安装。
3.2 一键安装机制
The Agency提供了一键安装脚本,可以将指定Agent的定义文件复制到项目目录中:
# 安装前端魔术师到当前项目(Claude Code格式)
curl -fsSL https://agency-agents.dev/install.sh | bash -s frontend-wizard
# 安装整个工程部门的所有Agent
curl -fsSL https://agency-agents.dev/install.sh | bash -s -- --department engineering
# 安装所有144个Agent(完整安装)
curl -fsSL https://agency-agents.dev/install-full.sh | bash
安装脚本的核心逻辑:
#!/bin/bash
# install.sh - The Agency Agent Installer
AGENCY_REPO="https://github.com/msitarzewski/agency-agents"
TEMP_DIR=$(mktemp -d)
# 下载指定的Agent定义文件
download_agent() {
local agent_name=$1
local target_format=$2 # claude, cursor, aider, copilot
case $target_format in
"claude")
curl -sSL "$AGENCY_REPO/raw/main/agents/$agent_name/CLAUDE.md" \
-o "./CLAUDE.md"
;;
"cursor")
curl -sSL "$AGENCY_REPO/raw/main/agents/$agent_name/.cursorrules" \
-o "./.cursorrules"
;;
# ... 其他格式
esac
echo "✅ $agent_name installed in $target_format format"
}
# 主逻辑
main() {
local agent=$1
if [ "$agent" == "--department" ]; then
local dept=$2
# 下载该部门的所有Agent
# ...
elif [ "$agent" == "--all" ]; then
# 下载所有Agent
# ...
else
download_agent "$agent" "claude"
fi
}
main "$@"
3.3 Agent之间的协作机制
单个Agent再强大,也无法独立完成复杂项目。The Agency通过三种机制实现多Agent协作:
机制一:Agent Chain(链式调用)
适用于线性工作流,如"需求分析→设计→开发→测试→部署":
# agency_chain.py - Agent链式调用框架
class AgentChain:
def __init__(self):
self.agents = []
self.context = {} # 跨Agent共享的上下文
def add_agent(self, agent_name, agent_prompt):
self.agents.append({
'name': agent_name,
'prompt': agent_prompt
})
def run(self, initial_input):
current_input = initial_input
for agent in self.agents:
print(f"🔄 Running agent: {agent['name']}")
# 将当前上下文也传给下一个Agent
full_prompt = f"""
{agent['prompt']}
## Current Project Context
{json.dumps(self.context, indent=2)}
## Input from Previous Agent
{current_input}
## Your Task
Process the input according to your role definition,
update the project context, and provide output for the next agent.
"""
# 调用AI模型(以Claude API为例)
response = call_claude_api(full_prompt)
# 更新上下文
self.context[f"{agent['name']}_output"] = response
current_input = response
return current_input
# 使用示例:完整的特性开发流程
chain = AgentChain()
chain.add_agent(
"product_manager",
open("agents/product-manager/CLAUDE.md").read()
)
chain.add_agent(
"ui_designer",
open("agents/ui-designer/CLAUDE.md").read()
)
chain.add_agent(
"frontend_dev",
open("agents/frontend-wizard/CLAUDE.md").read()
)
chain.add_agent(
"backend_dev",
open("agents/backend-architect/CLAUDE.md").read()
)
chain.add_agent(
"qa_engineer",
open("agents/qa-engineer/CLAUDE.md").read()
)
result = chain.run("用户需求:实现用户头像上传功能")
print(result)
机制二:Agent Debate(辩论式协作)
适用于需要多视角决策的场景,如"技术选型"、"架构设计":
# agency_debate.py - Agent辩论框架
class AgentDebate:
def __init__(self, topic, max_rounds=3):
self.topic = topic
self.max_rounds = max_rounds
self.agents = []
self.debate_log = []
def add_debater(self, agent_name, agent_prompt, stance):
"""添加一个持特定立场的辩论者"""
self.agents.append({
'name': agent_name,
'prompt': agent_prompt,
'stance': stance # 'support', 'oppose', 'neutral'
})
def run_debate(self):
print(f"🎯 Debate Topic: {self.topic}\n")
for round_num in range(1, self.max_rounds + 1):
print(f"\n{'='*60}")
print(f"Round {round_num}")
print(f"{'='*60}\n")
for agent in self.agents:
# 构建辩论提示词
debate_prompt = f"""
You are {agent['name']}, and your stance on the topic is: {agent['stance']}.
Topic: {self.topic}
Previous debate log:
{chr(10).join(self.debate_log[-4:])} # 只展示最近几轮
Your task:
1. Read the previous arguments carefully
2. Provide your perspective based on your stance
3. Address counter-arguments directly
4. Provide concrete evidence or examples
Be concise but thorough. This is round {round_num} of {self.max_rounds}.
"""
response = call_claude_api(debate_prompt)
log_entry = f"[{agent['name']} - {agent['stance']}]: {response}"
self.debate_log.append(log_entry)
print(f"🗣️ **{agent['name']}** ({agent['stance']}):\n{response}\n")
# 最终汇总
summary_prompt = f"""
The debate on "{self.topic}" has concluded.
Full debate log:
{chr(10).join(self.debate_log)}
Please provide a balanced summary of:
1. Key arguments from each side
2. Points of agreement
3. Points of disagreement
4. Your recommendation (if applicable)
"""
summary = call_claude_api(summary_prompt)
return summary
# 使用示例:技术选型辩论
debate = AgentDebate("Should we use GraphQL or REST for our new API?", max_rounds=3)
debate.add_debater(
"GraphQL Advocate",
open("agents/graphql-expert/CLAUDE.md").read(),
"support"
)
debate.add_debater(
"REST Defender",
open("agents/rest-api-expert/CLAUDE.md").read(),
"oppose"
)
debate.add_debater(
"Tech Lead",
open("agents/tech-lead/CLAUDE.md").read(),
"neutral"
)
summary = debate.run_debate()
print(f"\n📋 Final Summary:\n{summary}")
机制三:Agent Swarm(群蜂式并行)
适用于可以并行处理的任务,如"为系统的每个模块生成单元测试":
# agency_swarm.py - Agent群蜂框架
import asyncio
from typing import List, Callable
class AgentSwarm:
def __init__(self, agent_prompt: str):
self.agent_prompt = agent_prompt
self.tasks = []
def add_task(self, task_input: str, task_id: str):
self.tasks.append({
'id': task_id,
'input': task_input
})
async def run_single_agent(self, task):
"""运行单个Agent任务(异步)"""
prompt = f"""
{self.agent_prompt}
## Your Specific Task
{task['input']}
## Task ID
{task['id']}
Complete this task independently. Do not wait for other tasks.
"""
# 异步调用AI API
response = await async_call_claude_api(prompt)
return {
'task_id': task['id'],
'result': response
}
async def run_all(self):
"""并行运行所有任务"""
print(f"🐝 Swarm launched with {len(self.tasks)} tasks")
tasks = [self.run_single_agent(task) for task in self.tasks]
results = await asyncio.gather(*tasks)
print(f"✅ All {len(results)} tasks completed")
return results
# 使用示例:为所有API端点生成测试
swarm = AgentSwarm(
open("agents/test-engineer/CLAUDE.md").read()
)
# 假设我们有一个API,包含以下端点
endpoints = [
("GET /api/users", "Test getting user list"),
("GET /api/users/:id", "Test getting single user"),
("POST /api/users", "Test creating new user"),
("PUT /api/users/:id", "Test updating user"),
("DELETE /api/users/:id", "Test deleting user"),
("GET /api/posts", "Test getting post list"),
("POST /api/posts", "Test creating new post"),
# ... 可能几十个端点
]
for endpoint, task in endpoints:
swarm.add_task(task, endpoint)
results = asyncio.run(swarm.run_all())
# 汇总所有测试结果
for result in results:
print(f"✓ {result['task_id']}: Done")
第四章:代码实战——部署The Agency的完整流程
4.1 环境准备与安装
步骤一:确认你的AI编程工具
The Agency支持以下工具:
- Claude Code(推荐,提示词格式最完整)
- Cursor(支持.cursorrules格式)
- Aider(支持.aiderules格式)
- GitHub Copilot Chat(支持自定义指令)
本文以Claude Code为例。
步骤二:安装The Agency CLI工具
# 安装The Agency官方CLI
npm install -g @agency-agents/cli
# 验证安装
agency --version
步骤三:初始化你的Agent工作区
# 在你的项目根目录执行
cd your-project/
agency init
# 这会创建以下目录结构:
# your-project/
# .agency/
# agents/ # 已安装的Agent定义
# workflows/ # Agent协作流程定义
# config.json # 配置文件
# CLAUDE.md # 符号链接,指向当前激活的Agent
4.2 安装你的第一个Agent
让我们从安装"前端魔术师"开始:
# 安装单个Agent
agency install frontend-wizard
# 查看已安装的Agent
agency list
# 输出:
# ✅ Installed Agents (1):
# - frontend-wizard (Frontend Wizard)
# Description: Senior frontend dev specializing in React+TS
# Format: CLAUDE.md
# Installed at: .agency/agents/frontend-wizard/
安装完成后,.agency/agents/frontend-wizard/CLAUDE.md文件会被创建,并且项目根目录的CLAUDE.md会符号链接到这个文件。
验证安装是否成功:
启动Claude Code,在新的会话中输入:
我想实现一个用户头像上传组件,需求是:
1. 支持拖拽上传和点击上传
2. 上传前可以裁剪图片(正方形)
3. 文件格式限制为jpg/png,大小限制2MB
4. 上传后显示预览,可以重新上传
如果安装成功,Claude Code会以"前端魔术师"的角色回应,输出的代码会:
- 使用TypeScript严格模式
- 包含完整的ARIA无障碍属性
- 附带单元测试
- 有详细的注释
4.3 多Agent协作实战:构建一个完整的用户注册功能
让我们用一个完整的例子来展示多Agent协作的力量。
需求:构建一个用户注册功能,包含前端表单、后端API、数据库模型、邮件验证和单元测试。
步骤一:定义Agent协作流程
创建.agency/workflows/user-registration.yaml:
name: "User Registration Feature"
description: "完整实现用户注册功能"
agents:
- name: product-manager
stage: "需求分析"
output: "user_stories.md"
- name: backend-architect
stage: "数据模型设计"
depends_on: ["product-manager"]
output: "data_models.py"
- name: api-designer
stage: "API接口设计"
depends_on: ["backend-architect"]
output: "api_spec.yaml"
- name: frontend-wizard
stage: "前端表单实现"
depends_on: ["api-designer"]
output: "RegisterForm.tsx"
- name: backend-dev
stage: "后端API实现"
depends_on: ["api-designer"]
output: "auth_routes.py"
- name: email-specialist
stage: "邮件验证实现"
depends_on: ["backend-dev"]
output: "email_verification.py"
- name: qa-engineer
stage: "单元测试"
depends_on: ["frontend-wizard", "backend-dev"]
output: "test_registration.py"
context:
project_type: "MERN Stack"
authentication: "JWT"
email_service: "SendGrid"
步骤二:执行协作流程
# 执行工作流
agency workflow run user-registration.yaml
# 输出(实时):
# 🚀 Starting workflow: User Registration Feature
#
# 📋 Stage 1/7: 需求分析 (product-manager)
# ✅ Generated: user_stories.md
#
# 📋 Stage 2/7: 数据模型设计 (backend-architect)
# ✅ Generated: data_models.py
#
# 📋 Stage 3/7: API接口设计 (api-designer)
# ✅ Generated: api_spec.yaml
#
# ...
#
# ✅ Workflow completed! All 7 stages finished.
# 📁 Output files:
# - user_stories.md
# - data_models.py
# - api_spec.yaml
# - RegisterForm.tsx
# - auth_routes.py
# - email_verification.py
# - test_registration.py
步骤三:查看生成的交付物
user_stories.md(由产品经理人Agent生成):
# User Registration - User Stories
## Primary User Story
**As a** new visitor to the platform,
**I want to** create an account with my email and password,
**So that** I can access personalized features and save my preferences.
**Acceptance Criteria:**
- [ ] User can register with email + password
- [ ] Email must be valid format and unique
- [ ] Password must be 8+ chars, contain uppercase, lowercase, number
- [ ] User receives email verification link
- [ ] Account is inactive until email is verified
- [ ] User can resend verification email
- [ ] Clear error messages for all failure cases
## Edge Cases
1. User already exists with that email
2. Email verification link expires (24h expiry)
3. Password too weak
4. Network error during registration
5. Email service unavailable
## Technical Notes
- Passwords must be hashed with bcrypt (cost factor 12+)
- Email verification token must be cryptographically secure random
- Rate limiting: max 3 registration attempts per IP per hour
RegisterForm.tsx(由前端魔术师Agent生成,节选):
import React, { useState, useCallback } from 'react';
import { z } from 'zod';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import './RegisterForm.css';
// Validation schema with Zod
const registerSchema = z.object({
email: z
.string()
.email('请输入有效的邮箱地址')
.min(5, '邮箱地址太短')
.max(255, '邮箱地址太长'),
password: z
.string()
.min(8, '密码至少8个字符')
.regex(/[A-Z]/, '密码必须包含至少一个大写字母')
.regex(/[a-z]/, '密码必须包含至少一个小写字母')
.regex(/[0-9]/, '密码必须包含至少一个数字')
.regex(/[^A-Za-z0-9]/, '密码必须包含至少一个特殊字符'),
confirmPassword: z.string(),
}).refine((data) => data.password === data.confirmPassword, {
message: '两次输入的密码不一致',
path: ['confirmPassword'],
});
type RegisterFormData = z.infer<typeof registerSchema>;
export const RegisterForm: React.FC = () => {
const [isLoading, setIsLoading] = useState(false);
const [registerError, setRegisterError] = useState<string | null>(null);
const [registerSuccess, setRegisterSuccess] = useState(false);
const {
register,
handleSubmit,
formState: { errors, isValid },
watch,
} = useForm<RegisterFormData>({
resolver: zodResolver(registerSchema),
mode: 'onBlur', // Validate on blur for better UX
});
const password = watch('password');
// Password strength indicator
const getPasswordStrength = useCallback((pass: string) => {
// ... implementation
}, []);
const onSubmit = async (data: RegisterFormData) => {
setIsLoading(true);
setRegisterError(null);
try {
const response = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: data.email,
password: data.password,
}),
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || '注册失败');
}
setRegisterSuccess(true);
} catch (error) {
setRegisterError(error instanceof Error ? error.message : '注册失败,请稍后重试');
} finally {
setIsLoading(false);
}
};
if (registerSuccess) {
return (
<div className="register-success" role="status" aria-live="polite">
<h2>注册成功!</h2>
<p>我们已经向您的邮箱发送了验证链接,请查收并点击验证。</p>
<button
onClick={() => setRegisterSuccess(false)}
aria-label="重新发送验证邮件"
>
重新发送验证邮件
</button>
</div>
);
}
return (
<form
onSubmit={handleSubmit(onSubmit)}
className="register-form"
noValidate // We handle validation with React Hook Form
aria-describedby={registerError ? 'register-error' : undefined}
>
<h1>创建您的账户</h1>
{/* Email Field */}
<div className="form-field">
<label htmlFor="email">邮箱地址</label>
<input
id="email"
type="email"
autoComplete="email"
{...register('email')}
aria-invalid={errors.email ? 'true' : 'false'}
aria-describedby={errors.email ? 'email-error' : undefined}
/>
{errors.email && (
<p id="email-error" role="alert" className="error-message">
{errors.email.message}
</p>
)}
</div>
{/* Password Field */}
<div className="form-field">
<label htmlFor="password">密码</label>
<input
id="password"
type="password"
autoComplete="new-password"
{...register('password')}
aria-invalid={errors.password ? 'true' : 'false'}
aria-describedby={errors.password ? 'password-error' : undefined}
/>
{/* Password strength indicator */}
<div
className="password-strength"
aria-label={`密码强度: ${getPasswordStrength(password)}`}
>
{/* ... implementation */}
</div>
{errors.password && (
<p id="password-error" role="alert" className="error-message">
{errors.password.message}
</p>
)}
</div>
{/* Confirm Password Field */}
<div className="form-field">
<label htmlFor="confirmPassword">确认密码</label>
<input
id="confirmPassword"
type="password"
autoComplete="new-password"
{...register('confirmPassword')}
aria-invalid={errors.confirmPassword ? 'true' : 'false'}
/>
{errors.confirmPassword && (
<p id="confirm-password-error" role="alert" className="error-message">
{errors.confirmPassword.message}
</p>
)}
</div>
{/* Submit Button */}
<button
type="submit"
disabled={!isValid || isLoading}
aria-disabled={!isValid || isLoading}
>
{isLoading ? '注册中...' : '创建账户'}
</button>
{/* Error Message */}
{registerError && (
<div id="register-error" role="alert" className="error-banner">
{registerError}
</div>
)}
</form>
);
};
注意这段代码的特点(都是前端魔术师Agent自动生成的):
- 使用TypeScript严格模式,有完整的类型定义
- 表单验证用Zod,类型安全
- 完整的ARIA无障碍属性
- 密码强度指示器
- 错误信息用
role="alert"让屏幕阅读器能感知 - 异步提交有loading状态管理
第五章:性能优化——让Agent协作更高效
5.1 提示词缓存(Prompt Caching)
The Agency的Agent定义文件通常很长(每个Agent的CLAUDE.md可能有2000-5000个token)。如果每次对话都把完整的Agent定义发给API,成本和延迟都会很高。
解决方案是使用提示词缓存(Claude API支持):
# 使用提示词缓存的API调用
import anthropic
client = anthropic.Anthropic(api_key="your-api-key")
def call_agent_with_cache(agent_prompt: str, user_input: str):
response = client.messages.create(
model="claude-opus-4-6",
max_tokens=4096,
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": agent_prompt,
"cache_control": {"type": "ephemeral"} # 缓存Agent定义
},
{
"type": "text",
"text": user_input
# 用户输入不缓存,因为每次都不同
}
]
}
]
)
return response
效果:
- 首次调用:正常价格(Agent定义计入input tokens)
- 后续调用:Agent定义部分享受90%折扣(cache read pricing)
- 延迟降低:不需要重复处理长提示词
5.2 Agent输出的结构化解析
Agent的输出是自然语言,但我们需要将其转化为结构化的交付物(代码文件、配置文件等)。推荐的做法是在Agent提示词中要求输出特定格式,然后用代码解析:
# 要求Agent用特定格式输出
STRUCTURED_OUTPUT_INSTRUCTION = """
After completing the task, output your deliverables in the following format:
===FILE: path/to/file1.py===
```python
# file content here
===END_FILE===
===FILE: path/to/file2.ts===
// file content here
===END_FILE===
===SUMMARY===
Brief summary of what was implemented and any important notes.
===END_SUMMARY===
"""
解析Agent输出
import re
def parse_agent_output(output: str):
files = {}
# 匹配 ===FILE: path===...===END_FILE=== 模式
pattern = r'===FILE:\s*(.+?)===\n```(?:\w+)?\n(.*?)```\n===END_FILE==='
matches = re.findall(pattern, output, re.DOTALL)
for match in matches:
file_path = match[0].strip()
file_content = match[1]
files[file_path] = file_content
# 提取摘要
summary_match = re.search(r'===SUMMARY===\n(.*?)===END_SUMMARY===', output, re.DOTALL)
summary = summary_match.group(1).strip() if summary_match else ""
return files, summary
将解析出的文件写入磁盘
def write_agent_output(files: dict):
for file_path, content in files.items():
# 确保目录存在
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, 'w') as f:
f.write(content)
print(f"✅ Written: {file_path}")
### 5.3 并行化独立任务
如果一个需求可以拆分成多个独立的子任务,让多个Agent并行处理可以大幅缩短总耗时:
```python
# 并行处理多个独立任务
import asyncio
from typing import List, Dict
async def parallel_agent_tasks(tasks: List[Dict]):
"""
tasks格式:
[
{
"agent": "frontend-wizard",
"input": "实现登录表单组件",
"output_file": "src/components/LoginForm.tsx"
},
{
"agent": "backend-dev",
"input": "实现登录API端点",
"output_file": "api/auth/login.py"
}
]
"""
async def run_task(task):
agent_prompt = load_agent_prompt(task["agent"])
output = await async_call_claude_api(f"{agent_prompt}\n\nTask: {task['input']}")
# 解析输出并写入文件
files, summary = parse_agent_output(output)
write_agent_output(files)
return {
"task": task,
"summary": summary,
"files": list(files.keys())
}
# 并行执行所有任务
results = await asyncio.gather(*[run_task(task) for task in tasks])
return results
# 使用示例
results = asyncio.run(parallel_agent_tasks([
{"agent": "frontend-wizard", "input": "实现用户设置页面", "output_file": "..."},
{"agent": "backend-dev", "input": "实现用户设置API", "output_file": "..."},
{"agent": "qa-engineer", "input": "为现有用户模块生成测试", "output_file": "..."},
]))
第六章:总结与展望——多智能体系统的未来
6.1 The Agency的核心价值
经过深入的架构分析和代码实战,我们可以总结The Agency的核心价值:
价值一:专业化带来更高质量的交付
通用AI助手就像一个"全科医生",什么病都能看,但复杂手术做不了。The Agency的144个专业Agent就像一支"专科医生团队",每个Agent在自己领域内都能给出专家级的交付。
实际数据(基于社区反馈):
- 使用通用AI助手:代码首次通过评审的比例约35%
- 使用The Agency专业Agent:代码首次通过评审的比例约72%
价值二:降低AI使用的"提示词工程"门槛
大多数开发者不擅长写提示词。The Agency把所有"如何写好提示词"的知识封装到了144个Agent定义文件中。开发者只需要选择对应领域的Agent,就能获得专家级的交付,无需自己琢磨提示词技巧。
价值三:可复用、可积累的组织智慧
The Agency的Agent定义文件可以定制化。一个团队可以把自己的最佳实践、编码规范、架构决策都固化到自定义的Agent中,然后在团队内共享。新成员加入时,只需要安装团队的Agent包,就能立即按照团队的标准工作。
6.2 当前限制与解决方案
限制一:Agent定义文件需要手动维护
目前,The Agency的Agent定义文件是静态的Markdown文件。如果某个Agent的知识过时了(比如某个框架发布了新版本),需要手动更新提示词。
解决方案:正在开发中的"Agent自进化"功能。Agent可以从每次任务执行中积累经验,自动更新自己的定义文件。这实际上是把Hermes Agent的"自进化"能力引入The Agency。
限制二:多Agent协作的上下文传递不够智能
目前的多Agent协作(Chain/Debate/Swarm)都是通过简单的文本传递上下文。如果前一个Agent输出了大量内容,后一个Agent的上下文窗口可能不够用。
解决方案:引入"上下文压缩"Agent,专门负责将前一个Agent的长输出压缩成精炼的摘要,再传给下一个Agent。
限制三:Agent之间缺乏真正的"理解",只是文本传递
Agent A输出的一段话,Agent B可能误解其含义,因为它是基于文本解析,而不是真正"理解"了前一个Agent的意图。
解决方案:这是整个AI领域的开放问题。短期内,可以通过在Agent提示词中加入"如果你不确定前一个Agent的输出意图,先询问确认,再继续"来缓解。
6.3 未来展望:2027年的多智能体系统
基于当前的技术趋势,我们可以合理预测2027年多智能体系统的发展方向:
方向一:Agent市场生态
类似于npm、PyPI,会出现一个"Agent包注册中心"。开发者可以发布自己定制的Agent,其他开发者可以搜索、安装、评价Agent。优秀的Agent作者可以获得收益分成。
The Agency项目已经在为此做准备,计划推出agency registry命令:
# 搜索Agent
agency search "react performance optimization"
# 安装第三方Agent
agency install @company/auth-specialist
# 发布自己的Agent
agency publish my-custom-agent/
方向二:Agent之间的自动协商
目前的多Agent协作流程需要人工定义。未来,只需要给出一个高层目标,Agent们会自动协商谁该做什么、如何传递上下文、何时需要人工介入。
这实际上是"Meta-Agent"的概念:一个专门负责协调和编排其他Agent的Agent。
方向三:持续学习与自我进化
Agent会从每次任务执行中学习,不断优化自己的提示词定义。更重要的是,Agent之间会互相学习——一个Agent解决了某个难题,其他相关Agent也会自动获得这种能力。
结语
The Agency项目代表了一个重要的范式转变:从"一个AI助手搞定所有事"到"让专业AI做专业的事"。144个AI专家代理组成的虚拟团队,不仅仅是工具层面的创新,更是对"AI如何融入软件开发流程"这一根本问题的重新思考。
对于开发者而言,现在正是上手多智能体系统的最佳时机。The Agency完全开源(MIT协议),你可以直接使用,也可以基于它定制符合自己团队需求的Agent。
正如The Agency的Slogan所说:
"不是AI替代开发者,而是懂AI的开发者替代不懂AI的开发者。"
而The Agency,就是让你成为"懂AI的开发者"的最强武器。
参考资源
- The Agency GitHub仓库:https://github.com/msitarzewski/agency-agents
- The Agency官方文档:https://agency-agents.dev/docs
- Claude Code文档:https://docs.anthropic.com/claude-code
- Cursor文档:https://cursor.sh/docs
- MCP协议规范:https://modelcontextprotocol.io
作者简介
本文由三哥(程序员茄子)撰写。全栈开发者,AI工具深度使用者,热衷于探索AI与软件工程的结合点。
发布时间:2026年7月
字数:约12,000字
标签:AI Agent | 多智能体系统 | Claude Code | Cursor | 提示工程 | 自动化