Agent 预检索与 search_articles 工具
约 484 字大约 2 分钟
布欧-Lewyon
2026-06-08
首页 › Agent Spring Boot › RAG 检索增强
Agent 里的 RAG 两种路径
1. 预检索(rag / search 模式)
AgentService.agentChat() 在组 messages 前:
if ("rag".equals(mode) || "search".equals(mode)) {
List<Article> hits = articleService.search(ragQuery).block();
ragContext = buildRagContext(hits, mode);
}
String systemPrompt = memoryManager.buildSystemPrompt(userId, ragContext);
// tools 列表移除 search_articles,避免重复检索
.tools(toolsWithout("search_articles"))buildRagContext 把命中文章格式化为 system 片段:
## 知识库检索结果
[1] 标题 (相似度 0.82)
正文摘要...- rag 模式:模型基于检索内容总结回答
- search 模式:模型被要求逐条列出标题与相似度,偏运维核对
2. Tool 路径(默认 agent 或无预检索)
保留 search_articles Tool,模型自行决定何时检索:
case "search_articles":
String query = (String) args.get("query");
result = articleService.search(query).block();
break;7 个 Tool 全览
| Tool | 模块 |
|---|---|
| get_weather | ToolService |
| get_current_time | ToolService |
| save_memory | LongTermMemoryService |
| search_memory | LongTermMemoryService |
| list_memories | LongTermMemoryService |
| delete_memory | LongTermMemoryService |
| search_articles | ArticleService |
前端 mode 传递
ChatInput.tsx 在 Agent 模式显示 rag / search 药丸按钮:
await agentChat({
message,
userId,
sessionId,
history,
mode: ragMode, // 'rag' | 'search' | undefined
});仅 POST /api/agent/chat 携带;流式 chat 模式无 RAG。
与 Spring AI QuestionAnswerAdvisor 对照
Spring AI:
.defaultAdvisors(new QuestionAnswerAdvisor(vectorStore, searchRequest))本项目等价逻辑:
- 预检索 ≈ Advisor 在 call 前检索并改 system
search_articlesTool ≈ 模型自主检索
手写版便于面试逐步讲清数据流。
时序(rag 模式)
学习点
- 预检索省一轮 Tool,延迟更低;Tool 路径更灵活。
mode是产品语义,不是技术必须。- RAG 与 Memory 同在 system 里拼接,注意 Token 总长。
小结
rag/search模式走预检索 + 去掉search_articlesTool。- 默认 Agent 保留 Tool 自主检索。
- 前端用 mode 药丸切换回答风格。
上一节:MySQL 向量检索
下一节:检索调优
