在 AI Agent 领域,简单的工具调用循环往往只能处理浅层任务。对于需要多步骤、深度研究的复杂任务,我们需要更强大的架构设计。本文将深入解析 Spring AI Alibaba 框架中的 DeepResearch Agent 示例,展示如何构建一个具备任务规划、子 Agent 协作、上下文管理等高级能力的深度研究系统。
Spring AI Alibaba DeepResearch Agent 开源地址:https://github.com/alibaba/spring-ai-alibaba/tree/main/examples/deepresearch
一、项目依赖解析
1.1 核心技术栈
DeepResearch 项目基于以下技术栈构建:
- Spring Boot 3.5.7:提供 Web 应用框架和自动配置能力
- Java 17:使用现代 Java 特性
- Spring AI 1.1.0:Spring 官方 AI 框架
- Spring AI Alibaba 1.1.0.0-RC2:阿里云 Spring AI 扩展
1.2 核心依赖模块
<dependencies>
<!-- Agent Studio UI - 提供可视化界面 -->
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-studio</artifactId>
</dependency>
<!-- DashScope 通义千问集成 -->
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
</dependency>
<!-- Agent 框架核心 -->
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-agent-framework</artifactId>
</dependency>
<!-- MCP 客户端 - 集成外部工具 -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-mcp-client</artifactId>
</dependency>
<!-- Web 服务支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
1.3 依赖关系说明
- spring-ai-alibaba-studio:提供 Agent Studio UI,用于可视化 Agent 状态和交互
- spring-ai-alibaba-starter-dashscope:集成阿里云通义千问大模型
- spring-ai-alibaba-agent-framework:提供 ReAct Agent、拦截器、钩子等核心能力
- spring-ai-starter-mcp-client:实现 Model Context Protocol (MCP) 客户端,用于集成外部工具服务(如 Jina AI)
二、系统架构设计
2.1 整体架构图
┌─────────────────────────────────────────────────────────┐
│ 用户交互层 (Chat UI) │
│ http://localhost:8080/chatui/index.html │
└─────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────┐
│ Spring Boot Web Layer │
│ - REST API │
│ - SSE (Server-Sent Events) │
└─────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────┐
│ Agent Studio Framework │
│ - AgentLoader Interface │
│ - Agent Management & Discovery │
└─────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────┐
│ DeepResearchAgent (ReactAgent) │
│ ┌─────────────────────────────────────┐ │
│ │ Main Agent: 协调工作流 │ │
│ │ - 任务分解 │ │
│ │ - 子 Agent 调度 │ │
│ │ - 结果汇总 │ │
│ └─────────────────────────────────────┘ │
│ ┌─────────────────────────────────────┐ │
│ │ Sub-Agents: │ │
│ │ - research-agent: 深度研究 │ │
│ │ - critique-agent: 报告审查 │ │
│ └─────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────┐
│ Interceptors Layer (拦截器层) │
│ ┌─────────────────────────────────────┐ │
│ │ TodoListInterceptor │ │
│ │ - 任务列表管理 │ │
│ └─────────────────────────────────────┘ │
│ ┌─────────────────────────────────────┐ │
│ │ FilesystemInterceptor │ │
│ │ - 文件系统访问控制 │ │
│ └─────────────────────────────────────┘ │
│ ┌─────────────────────────────────────┐ │
│ │ SubAgentInterceptor │ │
│ │ - 子 Agent 创建与协调 │ │
│ └─────────────────────────────────────┘ │
│ ┌─────────────────────────────────────┐ │
│ │ LargeResultEvictionInterceptor │ │
│ │ - 大结果自动转存 │ │
│ └─────────────────────────────────────┘ │
│ ┌─────────────────────────────────────┐ │
│ │ PatchToolCallsInterceptor │ │
│ │ - 工具调用修复 │ │
│ └─────────────────────────────────────┘ │
│ ┌─────────────────────────────────────┐ │
│ │ ToolRetryInterceptor │ │
│ │ - 失败重试机制 │ │
│ └─────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────┐
│ Hooks Layer (钩子层) │
│ ┌─────────────────────────────────────┐ │
│ │ SummarizationHook │ │
│ │ - 对话历史摘要 │ │
│ └─────────────────────────────────────┘ │
│ ┌─────────────────────────────────────┐ │
│ │ HumanInTheLoopHook │ │
│ │ - 人工审批机制 │ │
│ └─────────────────────────────────────┘ │
│ ┌─────────────────────────────────────┐ │
│ │ ToolCallLimitHook │ │
│ │ - 工具调用限制 │ │
│ └─────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────┐
│ Tools Layer (工具层) │
│ ┌─────────────────────────────────────┐ │
│ │ MCP Tools │ │
│ │ - Jina AI Search │ │
│ │ - Web Search │ │
│ └─────────────────────────────────────┘ │
│ ┌─────────────────────────────────────┐ │
│ │ Filesystem Tools │ │
│ │ - ls, read_file, write_file │ │
│ │ - edit_file, glob, grep │ │
│ └─────────────────────────────────────┘ │
│ ┌─────────────────────────────────────┐ │
│ │ Shell Tools │ │
│ │ - ShellToolAgentHook │ │
│ └─────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────┐
│ LLM Layer (大模型层) │
│ ┌─────────────────────────────────────┐ │
│ │ DashScope Chat Model │ │
│ │ - 通义千问 API │ │
│ │ - API Key: AI_DASHSCOPE_API_KEY │ │
│ └─────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
2.2 核心设计理念
2.2.1 分层架构
系统采用清晰的分层架构,每一层都有明确的职责:
- 用户交互层:提供友好的 Web UI 界面
- Web 服务层:处理 HTTP 请求和 SSE 实时通信
- Agent 管理层:Agent 的注册、发现和加载
- Agent 执行层:核心的 Agent 逻辑和子 Agent 协调
- 中间件层:拦截器和钩子提供横切关注点处理
- 工具层:各种外部工具和服务的集成
- 模型层:底层大语言模型的调用
2.2.2 工作流程
用户输入研究问题
↓
主 Agent 接收任务
↓
TodoListInterceptor 分解任务
↓
并行调用多个 research-agent 子 Agent
├─→ research-agent 1: 研究子问题 A
├─→ research-agent 2: 研究子问题 B
└─→ research-agent 3: 研究子问题 C
↓
汇总研究结果
↓
写入 final_report.md
↓
调用 critique-agent 审查报告
↓
根据反馈迭代优化
↓
输出最终研究报告
2.3 关键特性
🎯 任务规划与分解
- 使用
TodoListInterceptor将复杂任务分解为离散步骤 - 动态跟踪进度并适应新信息
- 支持独立研究子任务的并行执行
📁 文件系统与上下文管理
- 提供完整的文件操作工具(ls, read_file, write_file, edit_file, glob, grep)
- 自动将大型工具结果转存到文件系统,防止上下文窗口溢出
- 支持研究过程和结果的持久化
🤝 子 Agent 协作
- research-agent:专门用于深度研究,可并行处理多个子问题
- critique-agent:审查和改进报告质量
- 主 Agent 协调子 Agent,保持上下文清洁和隔离
🔧 MCP 工具集成
- 通过 Spring AI MCP Client 集成外部工具
- 支持第三方服务(如 Jina AI 搜索)
- 可扩展到任何 MCP 兼容的工具
三、配置文件解析
3.1 application.yml 配置
spring:
application:
name: DeepResearch # 应用名称
ai:
dashscope:
# 从环境变量读取通义千问 API Key
api-key: ${AI_DASHSCOPE_API_KEY}
mcp:
client:
enabled: true # 启用 MCP 客户端
toolcallback:
enabled: true # 启用工具回调
sse:
connections:
jina:
# Jina AI MCP 服务地址
url: "https://mcp.jina.ai"
request-timeout: 60000 # 请求超时 60 秒
server:
port: 8080 # Web 服务端口
3.2 配置要点解析
- 环境变量管理:敏感信息(API Key)通过环境变量注入,提高安全性
- MCP 客户端配置:
- 启用 MCP 客户端和工具回调
- 配置 Jina AI 的 SSE 连接
- 设置合理的请求超时时间
- 服务端口:默认 8080,可通过环境变量覆盖
3.3 环境变量要求
# 必需的环境变量
export AI_DASHSCOPE_API_KEY=your_dashscope_api_key
# 可选的环境变量(用于 MCP 工具)
export JINA_API_KEY=your_jina_api_key
四、Application 主类解析
4.1 类结构
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
// Bean 配置方法...
}
4.2 核心 Bean 配置
4.2.1 MCP 客户端请求定制器
@Bean
public McpSyncHttpClientRequestCustomizer mcpSyncHttpClientRequestCustomizer() {
return new McpSyncHttpClientRequestCustomizer() {
@Override
public void customize(HttpRequest.Builder builder, String method,
URI endpoint, String body, McpTransportContext context) {
// 添加 Jina API Key 认证
builder.header("Authorization", "Bearer " + System.getenv("JINA_API_KEY"));
// 设置 120 秒超时
builder.timeout(java.time.Duration.ofSeconds(120));
}
};
}
功能说明:
- 为所有 MCP HTTP 请求添加认证头
- 从环境变量
JINA_API_KEY读取 API Key - 设置请求超时时间为 120 秒
设计意图:
- 统一管理 MCP 请求的认证和超时配置
- 通过定制器模式实现请求的个性化配置
4.2.2 应用就绪事件监听器
@Bean
public ApplicationListener<ApplicationReadyEvent> applicationReadyEventListener(
Environment environment) {
return event -> {
String port = environment.getProperty("server.port", "8080");
String contextPath = environment.getProperty("server.servlet.context-path", "");
String accessUrl = "http://localhost:" + port + contextPath + "/chatui/index.html";
System.out.println("\n🎉========================================🎉");
System.out.println("✅ Application is ready!");
System.out.println("🚀 Chat with you agent: " + accessUrl);
System.out.println("🎉========================================🎉\n");
};
}
功能说明:
- 监听应用启动完成事件
- 动态获取服务端口和上下文路径
- 输出友好的访问地址提示
五、AgentStaticLoader 解析
5.1 类职责
AgentStaticLoader 实现了 AgentLoader 接口,提供静态 Agent 加载器。它负责在应用启动时创建和注册 Agent 实例。
5.2 核心实现
@Component
class AgentStaticLoader implements AgentLoader {
private Map<String, Agent> agents = new ConcurrentHashMap<>();
public AgentStaticLoader(ToolCallbackProvider toolCallbackProvider) {
// 1. 获取 MCP 工具回调
List<ToolCallback> toolCallbacks = Arrays.asList(
toolCallbackProvider.getToolCallbacks()
);
System.out.println("Loaded MCP tool callbacks: " + toolCallbacks.size());
// 2. 创建 DeepResearchAgent 实例
ReactAgent researchAgent = new DeepResearchAgent()
.getResearchAgent(toolCallbacks);
// 3. 编译并打印 Agent 状态图
GraphRepresentation representation = researchAgent
.getAndCompileGraph()
.stateGraph
.getGraph(GraphRepresentation.Type.PLANTUML);
System.out.println(representation.content());
// 4. 注册 Agent
this.agents.put("research_agent", researchAgent);
}
@Override
public List<String> listAgents() {
return agents.keySet().stream().toList();
}
@Override
public Agent loadAgent(String name) {
if (name == null || name.trim().isEmpty()) {
throw new IllegalArgumentException("Agent name cannot be null or empty");
}
Agent agent = agents.get(name);
if (agent == null) {
throw new NoSuchElementException("Agent not found: " + name);
}
return agent;
}
}
5.3 设计模式分析
5.3.1 工厂模式
- 构造函数负责创建 Agent 实例
- 封装了复杂的 Agent 构建逻辑
5.3.2 注册表模式
- 使用
ConcurrentHashMap存储 Agent 实例 - 提供统一的 Agent 发现和加载接口
5.3.3 依赖注入
- 通过构造函数注入
ToolCallbackProvider - 实现与 Spring 容器的无缝集成
5.4 关键特性
- 工具集成:自动从 MCP 客户端获取工具回调
- 可视化支持:生成 PlantUML 格式的状态图,便于理解 Agent 结构
- 线程安全:使用
ConcurrentHashMap保证并发安全 - 错误处理:完善的参数校验和异常处理
六、DeepResearchAgent 核心解析
6.1 类结构概览
DeepResearchAgent 是整个系统的核心,它构建了一个功能完整的 ReactAgent,包含多个拦截器、钩子和子 Agent。
6.2 初始化流程
public DeepResearchAgent() {
// 1. 创建 DashScope API 客户端
DashScopeApi dashScopeApi = DashScopeApi.builder()
.apiKey(System.getenv("AI_DASHSCOPE_API_KEY"))
.build();
// 2. 创建 ChatModel
this.chatModel = DashScopeChatModel.builder()
.dashScopeApi(dashScopeApi)
.build();
// 3. 构建系统提示词
this.systemPrompt = researchInstructions + "\n\n" + BASE_AGENT_PROMPT;
// 4. 初始化所有 Interceptors 和 Hooks
// ...
}
6.3 Interceptors 详解
6.3.1 LargeResultEvictionInterceptor
this.largeResultEvictionInterceptor = LargeResultEvictionInterceptor
.builder()
.excludeFilesystemTools() // 排除文件系统工具
.toolTokenLimitBeforeEvict(5000) // 5000 tokens 阈值
.build();
功能:自动将大型工具结果转存到文件系统
工作原理:
- 监控工具返回结果的大小
- 当结果超过 5000 tokens 时,自动写入文件
- 在上下文中用文件引用替换原始结果
- 排除文件系统工具,避免循环转存
应用场景:
- Web 搜索结果过大
- 文件读取内容过长
- 任何可能超出上下文限制的工具输出
6.3.2 FilesystemInterceptor
this.filesystemInterceptor = FilesystemInterceptor.builder()
.readOnly(false) // 非只读模式
.build();
功能:提供文件系统访问工具
提供的工具:
ls:列出目录内容read_file:读取文件内容write_file:写入文件edit_file:编辑文件glob:文件模式匹配grep:文件内容搜索
安全考虑:
- 可以配置为只读模式
- 支持沙箱机制,限制访问范围
6.3.3 TodoListInterceptor
this.todoListInterceptor = TodoListInterceptor.builder().build();
功能:任务列表管理和跟踪
核心能力:
- 将复杂任务分解为待办事项列表
- 跟踪每个任务的完成状态
- 支持任务的动态添加和更新
- 提供任务优先级管理
工作流程:
- Agent 分析用户请求
- 创建初始待办事项列表
- 逐步执行任务并更新状态
- 根据执行结果动态调整计划
6.3.4 PatchToolCallsInterceptor
this.patchToolCallsInterceptor = PatchToolCallsInterceptor.builder().build();
功能:修复和补丁工具调用
应用场景:
- 修复格式错误的工具调用
- 补充缺失的工具参数
- 纠正工具名称拼写错误
- 优化工具调用参数
6.3.5 ToolRetryInterceptor
this.toolRetryInterceptor = ToolRetryInterceptor.builder()
.maxRetries(1) // 最大重试 1 次
.onFailure(ToolRetryInterceptor.OnFailureBehavior.RETURN_MESSAGE) // 失败时返回消息
.build();
功能:工具调用失败重试机制
重试策略:
- 最大重试次数:1 次
- 失败行为:返回错误消息而不是抛出异常
- 适用于网络请求等可能临时失败的操作
6.3.6 ContextEditingInterceptor(已注释)
// this.contextEditingInterceptor = ContextEditingInterceptor.builder()
// .trigger(10000) // 触发阈值 10000 tokens
// .clearAtLeast(6000) // 至少清除 6000 tokens
// .keep(4) // 保留 4 条消息
// .excludeTools("write_todos") // 排除 write_todos 工具
// .build();
功能:自动压缩上下文
设计考虑:
- 当前被注释掉,可能因为与 SummarizationHook 功能重叠
- 可以作为 SummarizationHook 的补充或替代方案
6.4 Hooks 详解
6.4.1 SummarizationHook
this.summarizationHook = SummarizationHook.builder()
.model(chatModel) // 使用相同模型进行摘要
.maxTokensBeforeSummary(120000) // 触发阈值 120K tokens
.messagesToKeep(6) // 保留 6 条消息
.build();
功能:对话历史摘要
工作原理:
- 监控对话历史的总 token 数
- 当超过 120K tokens 时触发摘要
- 使用 LLM 将历史消息压缩为摘要
- 保留最近的 6 条消息,其余替换为摘要
6.4.2 HumanInTheLoopHook
this.humanInTheLoopHook = HumanInTheLoopHook.builder()
.approvalOn("search_web", "Please approve the search_web tool.")
.build();
功能:关键操作人工审批
应用场景:
- 对
search_web工具调用需要人工审批 - 防止 Agent 执行敏感或高成本操作
- 提供人工监督机制
工作流程:
- Agent 尝试调用
search_web - Hook 拦截调用
- 暂停执行,等待人工审批
- 审批通过后继续执行
6.4.3 ToolCallLimitHook
this.toolCallLimitHook = ToolCallLimitHook.builder()
.runLimit(25) // 限制 25 次工具调用
.build();
功能:限制每次运行的工具调用次数
目的:
- 防止 Agent 陷入无限循环
- 控制成本和执行时间
- 强制 Agent 更高效地使用工具
6.4.4 ShellToolAgentHook
this.shellToolAgent = ShellToolAgentHook.builder().build();
功能:提供 Shell 命令执行能力
安全考虑:
- Shell 工具具有强大的系统访问能力
- 需要谨慎配置权限和访问范围
- 建议在生产环境中禁用或严格限制
6.5 Sub-Agent 设计
6.5.1 research-agent
private static SubAgentSpec createResearchAgent(
List<ToolCallback> toolsFromMcp, String subResearchPrompt) {
return SubAgentSpec.builder()
.name("research-agent")
.description("Used to research in-depth questions. Only give one topic at a time. " +
"Break down large topics into components and call multiple research agents " +
"in parallel for each sub-question.")
.systemPrompt(subResearchPrompt)
.tools(toolsFromMcp) // 使用 MCP 工具
.enableLoopingLog(true) // 启用循环日志
.build();
}
特点:
- 专门用于深度研究
- 可以并行调用多个实例
- 每个实例处理一个子问题
- 使用 MCP 工具(如 Jina AI 搜索)
Prompt 设计:
public static String subResearchPrompt = """
You are a dedicated researcher. Your job is to conduct research
based on the user's questions.
Conduct thorough research and then reply to the user with a
detailed answer to their question.
IMPORTANT: Only your FINAL answer will be passed on to the user.
They will have NO knowledge of anything except your final message,
so your final report should be comprehensive and self-contained!
""";
关键设计点:
- 强调最终答案必须完整自包含
- 用户看不到中间过程,只有最终结果
- 要求研究深入且全面
6.5.2 critique-agent
private static SubAgentSpec createCritiqueAgent(String subCritiquePrompt) {
return SubAgentSpec.builder()
.name("critique-agent")
.description("Used to critique the final report. Provide information about " +
"how you want the report to be critiqued.")
.systemPrompt(subCritiquePrompt)
.enableLoopingLog(true)
.build();
}
特点:
- 专门用于审查报告质量
- 读取
final_report.md和question.txt - 提供详细的改进建议
- 不直接修改报告,只提供反馈
Prompt 设计:
public static String subCritiquePrompt = """
You are a dedicated editor. You are being tasked to critique a report.
You can find the report at `final_report.md`.
You can find the question/topic for this report at `question.txt`.
The user may ask for specific areas to critique the report in.
Respond with a detailed critique of the report. Focus on areas
that could be improved.
You can use the search tool to search for information, if that
will help you critique the report.
Do not write to the `final_report.md` yourself.
Things to check:
- Each section is appropriately named and structured
- The report is written in essay/textbook style - text heavy,
not just bullet points
- The report is comprehensive without missing important details
- The article covers key areas ensuring overall understanding
- The article deeply analyzes causes, impacts, and trends with
valuable insights
- The article closely follows the research topic and directly
answers questions
- The article has clear structure, fluent language, and is easy
to understand
""";
审查维度:
- 结构和组织
- 内容深度和完整性
- 语言流畅性
- 与问题的相关性
- 洞察力和分析质量
6.6 Agent 构建方法
public ReactAgent getResearchAgent(List<ToolCallback> toolsFromMcp) {
return ReactAgent.builder()
.name("DeepResearchAgent")
.model(chatModel)
.tools(toolsFromMcp)
.systemPrompt(systemPrompt)
.enableLogging(true)
.interceptors(
todoListInterceptor,
filesystemInterceptor,
largeResultEvictionInterceptor,
patchToolCallsInterceptor,
// contextEditingInterceptor, // 已注释
toolRetryInterceptor,
subAgentAsInterceptors(toolsFromMcp) // 子 Agent 拦截器
)
.hooks(
humanInTheLoopHook,
summarizationHook,
toolCallLimitHook
)
.saver(new MemorySaver()) // 内存状态保存
.build();
}
构建要点:
-
拦截器顺序:拦截器按顺序执行,顺序很重要
- TodoListInterceptor:首先进行任务规划
- FilesystemInterceptor:提供文件操作能力
- LargeResultEvictionInterceptor:处理大结果
- PatchToolCallsInterceptor:修复工具调用
- ToolRetryInterceptor:处理失败重试
- SubAgentInterceptor:最后处理子 Agent 调用
-
钩子配置:钩子在特定事件触发
- HumanInTheLoopHook:工具调用前
- SummarizationHook:上下文过大时
- ToolCallLimitHook:每次工具调用后
-
状态管理:使用 MemorySaver 保存对话状态
- 支持对话历史的持久化
- 可以恢复之前的对话状态
6.7 Prompt 设计哲学
6.7.1 主研究指令(researchInstructions)
public static String researchInstructions = """
You are an expert researcher. Your job is to conduct thorough
research and write a polished report.
**Workflow:**
1. First, write the original user question to `question.txt`
for reference
2. Use the research-agent to conduct deep research on sub-topics
- Break down complex topics into specific sub-questions
- Call multiple research agents in parallel for independent
sub-questions
3. When you have enough information, write the final report to
`final_report.md`
4. Call the critique-agent to get feedback on the report
5. Iterate: Do more research and edit `final_report.md` based
on critique
6. Repeat steps 4-5 until satisfied with the quality
**Report Format Requirements:**
- CRITICAL: Write in the SAME language as the user's question!
- Use clear Markdown with proper structure (# for title, ## for
sections, ### for subsections)
- Include specific facts and insights from research
- Reference sources using [Title](URL) format
- Provide balanced, thorough analysis
- Be comprehensive - users expect detailed, in-depth answers
- End with a "### Sources" section listing all references
**Citation Rules:**
- Assign each unique URL a single citation number [1], [2], etc.
- Number sources sequentially without gaps in the final list
- Each source should be a separate list item
- Format: [1] Source Title: URL
Structure your report appropriately for the question type:
- Comparison: intro → overview A → overview B → comparison →
conclusion
- List: Simple numbered/bulleted list or separate sections per item
- Overview/Summary: intro → concept 1 → concept 2 → ... →
conclusion
- Analysis: thesis → evidence → analysis → conclusion
""";
设计亮点:
- 明确的工作流程:6 步清晰的工作流程
- 多语言支持:强调使用用户问题的语言
- 格式规范:详细的 Markdown 格式要求
- 引用规范:统一的引用格式和编号规则
- 结构化指导:根据问题类型提供结构建议
6.7.2 Prompt 工程最佳实践
- 角色定义:明确 Agent 的角色和职责
- 步骤分解:将复杂任务分解为清晰步骤
- 格式要求:详细的输出格式规范
- 约束条件:明确的限制和规则
- 示例引导:通过示例说明期望行为
七、完整工作流程示例
7.1 用户输入示例
用户:研究 Spring AI Alibaba 的核心架构设计
7.2 Agent 执行流程
步骤 1:任务分解
TodoListInterceptor 创建待办事项:
1. 将问题写入 question.txt
2. 研究 Spring AI Alibaba 的整体架构
3. 研究 Agent 框架设计
4. 研究工具集成机制
5. 研究拦截器和钩子系统
6. 汇总研究结果
7. 编写最终报告
8. 审查报告质量
步骤 2:并行研究
主 Agent 调用多个 research-agent:
- research-agent-1: 研究整体架构
- research-agent-2: 研究 Agent 框架
- research-agent-3: 研究工具集成
- research-agent-4: 研究拦截器系统
每个 research-agent:
- 使用 Jina AI 搜索相关文档
- 阅读 GitHub 源码
- 分析技术博客
- 整理研究结果
步骤 3:结果汇总
主 Agent 收集所有研究结果
写入 final_report.md
步骤 4:质量审查
调用 critique-agent:
- 读取 final_report.md
- 读取 question.txt
- 审查报告质量
- 提供改进建议
步骤 5:迭代优化
根据 critique-agent 的反馈:
- 补充缺失的信息
- 改进报告结构
- 优化语言表达
- 更新 final_report.md
步骤 6:最终输出
用户收到最终研究报告
包含完整的架构分析和引用来源
八、总结
Spring AI Alibaba DeepResearch Agent 展示了如何构建一个功能完整、架构清晰的 AI Agent 系统。通过合理的分层设计、丰富的中间件支持和精心设计的 Prompt,它能够处理复杂的多步骤研究任务。
核心价值:
- 🎯 任务规划:TodoList 机制实现复杂任务分解
- 🤝 协作能力:多 Agent 并行处理提高效率
- 📁 上下文管理:智能的上下文压缩和文件管理
- 🔧 工具集成:通过 MCP 协议轻松扩展能力
- ✨ 质量控制:审查机制确保输出质量
这个项目为构建生产级 AI Agent 系统提供了优秀的参考范例,值得深入学习和实践。