R2R Agentic RAG 实战指南:多步推理、动态工具调用与 Research 深度研究模式
【免费下载链接】R2RSoTA production-ready AI retrieval system. Agentic Retrieval-Augmented Generation (RAG) with a RESTful API.项目地址: https://gitcode.com/GitHub_Trending/r2/R2R
本篇技术指南以 R2R 的 Agentic RAG(又称 Deep Research)功能为主线,讲解如何通过client.retrieval.agent让大模型结合向量检索、全文检索、知识图谱与网络搜索等工具进行多步推理,并围绕仓库中的源码与配置展开实现原理分析。读完本文,你将掌握 RAG 模式与 Research 模式的差异、五类检索工具与四类研究工具的选型、流式事件(thinking / tool_call / citation / final_answer)的处理方式,以及如何通过conversation_id、search_settings与生成参数定制自己的问答与研究型应用。
前置说明:Agentic RAG 是 R2R 基础检索能力的扩展。如果你是 R2R 新手,建议先阅读 Search & RAG 指南 掌握
/retrieval/search、/retrieval/rag与search_settings的基础用法,再回到本文学习智能体编排层。
核心能力:Agentic RAG 解决了什么问题
Agentic RAG 将"一次检索 + 一次生成"升级为"多轮工具调用 + 持续推理"的闭环:智能体可以链式执行多个动作(例如先搜索文档、再抓取网页、必要时引用对话历史),然后才生成最终回答;检索侧完整接入 R2R 的向量、全文与混合检索能力;通过在每个请求中携带conversation_id维持跨轮次的对话记忆;并在运行时动态决定调用哪些工具、从哪些来源收集与分析信息。
这四个特性对应仓库源码中的具体设计:
- 多步推理:
AgentConfig.max_iterations默认值为 10(见 py/core/base/agent/agent.py),即智能体最多进行 10 次迭代(工具调用)后必须收敛出结论;Research 类智能体在初始化时会把上限提升到 15(见 py/core/agent/research.py)。 - 检索增强:工具通过
ToolRegistry注册,检索行为由注入的knowledge_search_method、content_method、file_search_method三个回调函数驱动(见 py/core/agent/rag.py 中的RAGAgentMixin)。 - 对话上下文:
/v3/retrieval/agent端点会按conversation_id拉取历史消息并与新消息拼接后交给智能体(见 py/core/main/services/retrieval_service.py)。 - 动态工具使用:请求中的
rag_tools/research_tools会驱动工具注册,LLM 在每轮迭代中按需发起工具调用,智能体通过execute_tool执行并回填结果(见 py/core/base/agent/agent.py)。
两种工作模式:RAG 模式与 Research 模式
client.retrieval.agent(..., mode=...)提供两个主要运行模式,mode默认值为rag。
RAG 模式(默认)
面向"基于知识库回答问题"的标准检索增强生成场景,能力包括:
- 语义搜索与混合(hybrid)搜索;
- 文档级与 chunk 级内容检索;
- 可选接入 Serper 与 Firecrawl 的网页搜索;
- 来源引用(citation)与基于证据的回答。
从实现看,RAG 模式由 py/core/agent/rag.py 中的R2RRAGAgent/R2RStreamingRAGAgent/R2RXMLToolsRAGAgent/R2RXMLToolsStreamingRAGAgent四种智能体承载,分别对应"非流式 / 流式 / XML 工具协议 / XML 工具协议 + 流式"四种组合。
Research 模式
在 RAG 模式全部能力之上,追加面向复杂问题的深度分析、推理与计算能力:
- 专门的推理系统(
reasoning)用于复杂问题求解; - 批判性分析(
critique)用于识别推理中的潜在偏见或逻辑谬误; - Python 执行(
python_executor)用于计算型分析; - 多步推理以深入探索主题。
Research 模式由 py/core/agent/research.py 中的R2RResearchAgent、R2RStreamingResearchAgent等实现,其ResearchAgentMixin继承自RAGAgentMixin,因此天然拥有全部 RAG 检索能力,再叠加四个研究专用工具。
模式如何影响模型选择
在 py/core/main/api/v3/retrieval_router.py 的agent_app中,当请求未显式指定model时:
mode="rag"时使用配置中的quality_llm(默认openai/gpt-5-2025-08-07);mode="research"时使用planning_llm(默认anthropic/claude-3-7-sonnet-20250219),而reasoning_llm(默认openai/o3-mini)则作为reasoning工具的底层模型。
以上默认值可在 py/r2r/r2r.toml 的[app]段中修改。
可用工具全景
RAG 工具
| 工具名 | 说明 | 依赖 |
|---|---|---|
search_file_knowledge | 使用 R2R 检索能力对已入库文档做语义/混合搜索 | 无 |
search_file_descriptions | 在文件级元数据(标题、文档级描述)上搜索 | 无 |
get_file_content | 拉取完整文档或 chunk 结构做深入分析 | 无 |
web_search | 调用外部搜索 API 获取实时信息 | 需要SERPER_API_KEY环境变量 |
web_scrape | 抓取并抽取指定网页内容 | 需要FIRECRAWL_API_KEY环境变量 |
Research 工具
| 工具名 | 说明 | 依赖 |
|---|---|---|
rag | 复用底层 RAG 智能体完成信息检索与综合 | 无 |
reasoning | 调用专用模型进行复杂分析推理 | 无 |
critique | 分析对话历史,识别缺陷、偏见与替代方案 | 无 |
python_executor | 执行 Python 代码做复杂计算与分析 | 无 |
源码视角:工具如何被注册与调度
从源码结构看,工具体系的运转分为三层:
- 注册层:py/core/base/agent/tools/registry.py 中的
ToolRegistry会自动扫描built_in目录下的全部Tool子类并按其name建立索引,同时支持通过R2R_USER_TOOLS_PATH环境变量加载用户自定义工具目录(_discover_user_tools)。create_tool_instance负责为每个工具实例注入llm_format_function(结果格式化函数)与context(智能体上下文)。 - 装配层:
RAGAgentMixin._register_tools(见 py/core/agent/rag.py)遍历config.rag_tools,对每个工具名向注册表请求实例;ResearchAgentMixin._register_research_tools(见 py/core/agent/research.py)则按名称构造rag/reasoning/critique/python_executor四个研究工具。工具的默认配置定义在 py/core/base/agent/agent.py 的RAGAgentConfig中:RAG 默认启用search_file_descriptions、search_file_knowledge、get_file_content(网页工具默认关闭),Research 默认启用rag、reasoning、critique、python_executor。 - 执行层:智能体在每轮迭代中解析 LLM 返回的 function/tool 调用,通过
handle_function_or_tool_call执行并把结果以tool角色消息写回对话(Anthropic 开启extended_thinking时还会附加"Continue..."续写消息以兼容其思考 + 工具调用协议,见 py/core/base/agent/agent.py)。
三个检索类工具的底层实现分别对应 search_file_knowledge.py(调用context.knowledge_search_method)、search_file_descriptions.py(调用context.file_search_method)与 get_file_content.py(以document_id过滤后调用context.content_method);执行结果都会写入智能体的search_results_collector,为最终回答的引用(citation)收集素材。
快速开始:基本用法
下面分别给出单轮查询与多轮对话的调用示例。所有示例假定你已完成 R2R 部署并导入了相关 SDK;若开启了认证,请先执行client.users.login(...)。
Python SDK:RAG 模式 + 流式事件处理
from r2r import R2RClient from r2r import ( ThinkingEvent, ToolCallEvent, ToolResultEvent, CitationEvent, MessageEvent, FinalAnswerEvent, ) # when using auth, do client.users.login(...) # Basic RAG mode with streaming response = client.retrieval.agent( message={ "role": "user", "content": "What does DeepSeek R1 imply for the future of AI?" }, rag_generation_config={ "model": "anthropic/claude-3-7-sonnet-20250219", "extended_thinking": True, "thinking_budget": 4096, "temperature": 1, "top_p": None, "max_tokens_to_sample": 16000, "stream": True }, rag_tools=["search_file_knowledge", "get_file_content"], mode="rag" ) # Improved streaming event handling current_event_type = None for event in response: # Check if the event type has changed event_type = type(event) if event_type != current_event_type: current_event_type = event_type print() # Add newline before new event type # Print emoji based on the new event type if isinstance(event, ThinkingEvent): print(f"\n🧠 Thinking: ", end="", flush=True) elif isinstance(event, ToolCallEvent): print(f"\n🔧 Tool call: ", end="", flush=True) elif isinstance(event, ToolResultEvent): print(f"\n📊 Tool result: ", end="", flush=True) elif isinstance(event, CitationEvent): print(f"\n📑 Citation: ", end="", flush=True) elif isinstance(event, MessageEvent): print(f"\n💬 Message: ", end="", flush=True) elif isinstance(event, FinalAnswerEvent): print(f"\n✅ Final answer: ", end="", flush=True) # Print the content without the emoji if isinstance(event, ThinkingEvent): print(f"{event.data.delta.content[0].payload.value}", end="", flush=True) elif isinstance(event, ToolCallEvent): print(f"{event.data.name}({event.data.arguments})") elif isinstance(event, ToolResultEvent): print(f"{event.data.content[:60]}...") elif isinstance(event, CitationEvent): print(f"{event.data}") elif isinstance(event, MessageEvent): print(f"{event.data.delta.content[0].payload.value}", end="", flush=True) elif isinstance(event, FinalAnswerEvent): print(f"{event.data.generated_answer[:100]}...") print(f" Citations: {len(event.data.citations)} sources referenced")流式响应中会出现 6 类事件,其含义与后端实现一一对应(后端将事件封装为 SSE 流,见 py/core/main/api/v3/retrieval_router.py 的agent_app流式分支):
thinking:模型逐步推理的思考过程(extended_thinking=true时出现,XML 变体智能体会把<think>/<Thought>块映射为该事件);tool_call:智能体发起工具调用;tool_result:工具执行结果;citation:回答中出现引用来源;message:面向用户的增量文本 token;final_answer:携带完整回答与结构化引用的最终事件。
JavaScript SDK
const { r2rClient } = require("r2r-js"); const client = new r2rClient(); // when using auth, do client.users.login(...) async function main() { // Basic RAG mode with streaming const streamingResponse = await client.retrieval.agent({ message: { role: "user", content: "What does DeepSeek R1 imply for the future of AI?" }, ragTools: ["search_file_knowledge", "get_file_content"], ragGenerationConfig: { model: "anthropic/claude-3-7-sonnet-20250219", extendedThinking: true, thinkingBudget: 4096, temperature: 1, maxTokens: 16000, stream: true } }); // Improved streaming event handling if (Symbol.asyncIterator in streamingResponse) { let currentEventType = null; for await (const event of streamingResponse) { // Check if event type has changed const eventType = event.event; if (eventType !== currentEventType) { currentEventType = eventType; console.log(); // Add newline before new event type // Print emoji based on the new event type switch(eventType) { case "thinking": process.stdout.write(`🧠 Thinking: `); break; case "tool_call": process.stdout.write(`🔧 Tool call: `); break; case "tool_result": process.stdout.write(`📊 Tool result: `); break; case "citation": process.stdout.write(`📑 Citation: `); break; case "message": process.stdout.write(`💬 Message: `); break; case "final_answer": process.stdout.write(`✅ Final answer: `); break; } } // Print content based on event type switch(eventType) { case "thinking": process.stdout.write(`${event.data.delta.content[0].payload.value}`); break; case "tool_call": console.log(`${event.data.name}(${JSON.stringify(event.data.arguments)})`); break; case "tool_result": console.log(`${event.data.content.substring(0, 60)}...`); break; case "citation": console.log(`${event.data}`); break; case "message": process.stdout.write(`${event.data.delta.content[0].payload.value}`); break; case "final_answer": console.log(`${event.data.generated_answer.substring(0, 100)}...`); console.log(` Citations: ${event.data.citations.length} sources referenced`); break; } } } } main();curl:直接调用 REST API
curl -X POST "https://api.sciphi.ai/v3/retrieval/agent" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "message": { "role": "user", "content": "What does DeepSeek R1 imply for the future of AI?" }, "rag_tools": ["search_file_knowledge", "get_file_content"], "rag_generation_config": { "model": "anthropic/claude-3-7-sonnet-20250219", "extended_thinking": true, "thinking_budget": 4096, "temperature": 1, "max_tokens_to_sample": 16000, "stream": true }, "mode": "rag" }'/v3/retrieval/agent端点的完整请求参数(message、search_settings、rag_generation_config、research_generation_config、rag_tools、research_tools、mode、conversation_id、max_tool_context_length等)可参考 py/core/main/api/v3/retrieval_router.py 中agent_app的 OpenAPI 定义。
使用 Research 模式
Research 模式适合需要深度推理、多来源综合与计算的复杂问题。
完整研究工具集示例
# Research mode with all available tools response = client.retrieval.agent( message={ "role": "user", "content": "Analyze the philosophical implications of DeepSeek R1 for the future of AI reasoning" }, research_generation_config={ "model": "anthropic/claude-3-opus-20240229", "extended_thinking": True, "thinking_budget": 8192, "temperature": 0.2, "max_tokens_to_sample": 32000, "stream": True }, research_tools=["rag", "reasoning", "critique", "python_executor"], mode="research" ) # Process streaming events as shown in the previous example # ... # Research mode with computational focus # This example solves a mathematical problem using the python_executor tool compute_response = client.retrieval.agent( message={ "role": "user", "content": "Calculate the factorial of 15 multiplied by 32. Show your work." }, research_generation_config={ "model": "anthropic/claude-3-opus-20240229", "max_tokens_to_sample": 1000, "stream": False }, research_tools=["python_executor"], mode="research" ) print(f"Final answer: {compute_response.results.messages[-1].content}")JavaScript 版本:
// Research mode with all available tools const researchStream = await client.retrieval.agent({ message: { role: "user", content: "Analyze the philosophical implications of DeepSeek R1 for the future of AI reasoning" }, researchGenerationConfig: { model: "anthropic/claude-3-opus-20240229", extendedThinking: true, thinkingBudget: 8192, temperature: 0.2, maxTokens: 32000, stream: true }, researchTools: ["rag", "reasoning", "critique", "python_executor"], mode: "research" }); // Process streaming events as shown in the previous example // ... // Research mode with computational focus const computeResponse = await client.retrieval.agent({ message: { role: "user", content: "Calculate the factorial of 15 multiplied by 32. Show your work." }, researchGenerationConfig: { model: "anthropic/claude-3-opus-20240229", maxTokens: 1000, stream: false }, researchTools: ["python_executor"], mode: "research" }); console.log(`Final answer: ${computeResponse.results.messages[computeResponse.results.messages.length - 1].content}`);源码级原理:四个研究工具的内部实现
从 py/core/agent/research.py 可以看到:
rag工具(_rag):以当前配置复制一份RAGAgentConfig,强制混入web_search、web_scrape与用户配置的 RAG 工具,创建一个独立R2RRAGAgent执行查询,并把返回内容中的引用(citation)从该 RAG 智能体的search_results_collector转移给外层研究智能体,保证最终回答的引用链条完整。reasoning工具(_reason):读取对话历史,用app_config.reasoning_llm(默认openai/o3-mini)、temperature=0.1、max_tokens_to_sample=64000、reasoning_effort="high"的专用配置调用底层 LLM,完成独立于主对话的深度推理。critique工具(_critique):把对话历史组装成包含"逻辑谬误 / 认知偏差 / 被忽略的问题 / 替代方案 / 严谨性改进"五段式结构的批判提示词,再交给reasoning工具处理,实现"第二意见"。python_executor工具(_execute_python_with_process_timeout):把代码写入临时.py文件后在独立子进程中执行,默认 10 秒超时(避免卡死主流程),支持 numpy、pandas、sympy、scipy 等常见科学计算库,返回 stdout / stderr / 超时状态,并以 Markdown 格式回填给 LLM。仓库中research.py对该工具的描述与_format_python_results的输出格式均可直接复用。
此外,Research 模式加载的是 static_research_agent.yaml 提示词,它要求智能体区分"宽泛定性问题"与"窄范围学术问题"分别采用多论点研究与聚焦战略分析,并强制使用行内引用(如[c910e2e])保证可追溯。
定制智能体
工具选择
按需裁剪工具可以减少无效调用、加快响应:
# RAG mode with web capabilities response = client.retrieval.agent( message={"role": "user", "content": "What are the latest developments in AI safety?"}, rag_tools=["search_file_knowledge", "get_file_content", "web_search", "web_scrape"], mode="rag" ) # Research mode with limited tools response = client.retrieval.agent( message={"role": "user", "content": "Analyze the complexity of this algorithm"}, research_tools=["reasoning", "python_executor"], # Only reasoning and code execution mode="research" )注意:服务端会校验工具名——RAG 工具仅接受
web_search、web_scrape、search_file_descriptions、search_file_knowledge、get_file_content;Research 工具仅接受rag、reasoning、critique、python_executor(见 retrieval_router.py 中Literal[...]类型约束)。若在mode="rag"下传了research_tools,服务端会记录警告并忽略它们(见 retrieval_service.py)。
搜索设置透传
传给智能体的search_settings会原样透传给下游的每一次搜索,包括:
- 限制文档来源的过滤器(
filters); - 返回结果数量上限(
limit); - 混合搜索配置(
use_hybrid_search与hybrid_settings); - 集合(collection)限制。
# Using search settings with the agent response = client.retrieval.agent( message={"role": "user", "content": "Summarize our Q1 financial results"}, search_settings={ "use_semantic_search": True, "filters": {"collection_ids": {"$overlap": ["e43864f5-..."]}}, "limit": 25 }, rag_tools=["search_file_knowledge", "get_file_content"], mode="rag" )从实现看,search_settings由路由层经_prepare_search_settings归一化(search_mode为basic/advanced时以模式默认值为基底再做字段级合并;custom模式直接使用传入对象),随后注入到智能体的RAGAgentMixin.search_settings,最终由search_file_knowledge工具以knowledge_search_method(query, search_settings=context.search_settings)的方式消费(见 search_file_knowledge.py)。filters支持的运算符($eq、$neq、$gt、$gte、$lt、$lte、$like、$ilike、$in、$nin,以及$and/$or组合)与 Search & RAG 指南 中的高级过滤规则一致。
模型选择与生成参数
# Using a specific model with custom parameters response = client.retrieval.agent( message={"role": "user", "content": "Write a concise summary of DeepSeek R1's capabilities"}, rag_generation_config={ "model": "anthropic/claude-3-haiku-20240307", # Faster model for simpler tasks "temperature": 0.3, # Lower temperature for more deterministic output "max_tokens_to_sample": 500, # Limit response length "stream": False # Non-streaming for simpler use cases }, mode="rag" )常用生成参数一览(后端GenerationConfig):
model:LLM 标识(如anthropic/claude-3-7-sonnet-20250219、openai/gpt-5-2025-08-07),未指定时按模式回退到quality_llm/planning_llm;stream:布尔值,默认false,置为true时返回 SSE 事件流;temperature、top_p、max_tokens_to_sample:标准采样与长度控制;extended_thinking/thinking_budget:Anthropic 系列模型启用扩展思考及其 token 预算(需要模型支持)。
多轮对话与会话保持
通过conversation_id让智能体记住之前的交互并在后续回答中延续上下文。首次调用后请保存返回的conversation_id,并在后续请求中带上它;若会话还没有名称,系统会自动分配一个(见 retrieval_router.py 的needs_initial_conversation_name参数)。
# Create a new conversation conversation = client.conversations.create() conversation_id = conversation.results.id # First turn first_response = client.retrieval.agent( message={"role": "user", "content": "What does DeepSeek R1 imply for the future of AI?"}, rag_generation_config={ "model": "anthropic/claude-3-7-sonnet-20250219", "temperature": 0.7, "max_tokens_to_sample": 1000, "stream": False }, conversation_id=conversation_id, mode="rag" ) print(f"First response: {first_response.results.messages[-1].content[:100]}...") # Follow-up query in the same conversation follow_up_response = client.retrieval.agent( message={"role": "user", "content": "How does it compare to other reasoning models?"}, rag_generation_config={ "model": "anthropic/claude-3-7-sonnet-20250219", "temperature": 0.7, "max_tokens_to_sample": 1000, "stream": False }, conversation_id=conversation_id, mode="rag" ) print(f"Follow-up response: {follow_up_response.results.messages[-1].content[:100]}...") # The agent maintains context, so it knows "it" refers to DeepSeek R1JavaScript 版本:
// Create a new conversation const conversation = await client.conversations.create(); const conversationId = conversation.results.id; // First turn const firstResponse = await client.retrieval.agent({ message: { role: "user", content: "What does DeepSeek R1 imply for the future of AI?" }, ragGenerationConfig: { model: "anthropic/claude-3-7-sonnet-20250219", temperature: 0.7, maxTokens: 1000, stream: false }, conversationId: conversationId, mode: "rag" }); console.log(`First response: ${firstResponse.results.messages[firstResponse.results.messages.length - 1].content.substring(0, 100)}...`); // Follow-up query in the same conversation const followUpResponse = await client.retrieval.agent({ message: { role: "user", content: "How does it compare to other reasoning models?" }, ragGenerationConfig: { model: "anthropic/claude-3-7-sonnet-20250219", temperature: 0.7, maxTokens: 1000, stream: false }, conversationId: conversationId, mode: "rag" }); console.log(`Follow-up response: ${followUpResponse.results.messages[followUpResponse.results.messages.length - 1].content.substring(0, 100)}...`); // The agent maintains context, so it knows "it" refers to DeepSeek R1会话记忆的存储与检索由服务端完成:retrieval_service.agent在收到conversation_id后会从conversations_handler.get_conversation拉取历史消息、追加本轮message,并把parent_id串成消息链(见 retrieval_service.py)。
性能考量
根据仓库集成测试的观察,优化智能体用法时可以从响应时间与大上下文两个维度入手。
响应时间管理
响应时间受查询复杂度、使用工具数量与请求输出长度共同影响:
# For time-sensitive applications, consider: # 1. Using a smaller max_tokens value # 2. Selecting faster models like claude-3-haiku # 3. Avoiding unnecessary tools fast_response = client.retrieval.agent( message={"role": "user", "content": "Give me a quick overview of DeepSeek R1"}, rag_generation_config={ "model": "anthropic/claude-3-haiku-20240307", # Faster model "max_tokens_to_sample": 200, # Limited output "stream": True # Stream for perceived responsiveness }, rag_tools=["search_file_knowledge"], # Minimal tools mode="rag" )仓库的集成测试 test_agent.py 中test_agent_respects_max_tokens、test_agent_response_timing即分别验证了max_tokens对输出长度的约束效果与响应时间行为;test_agent_rag_tool_usage/test_agent_rag_tool_usage2验证了search_file_knowledge、get_file_content等工具的实际调用路径。此外,RAGAgentMixin中的max_tool_context_length(路由层默认 32_768)会按 token 占比截断工具返回的检索上下文,避免工具结果撑爆上下文窗口(见 py/core/agent/rag.py 的format_search_results_for_llm)。
处理大上下文
面对大型文档集合,应使用过滤器精准缩小检索范围,并限制返回 chunk 数量:
# When working with large document collections, use filters to narrow results filtered_response = client.retrieval.agent( message={"role": "user", "content": "Summarize key points from our AI ethics documentation"}, search_settings={ "filters": { "$and": [ {"document_type": {"$eq": "pdf"}}, {"metadata.category": {"$eq": "ethics"}}, {"metadata.year": {"$gt": 2023}} ] }, "limit": 10 # Limit number of chunks returned }, rag_generation_config={ "max_tokens_to_sample": 500, "stream": True }, mode="rag" )底层原理:工具是如何工作的
RAG 模式工具
search_file_knowledge:基于语义与混合检索,从已入库文档中查找相关文本 chunk 与知识图谱数据(实体、关系、社区摘要),是智能体获取"内容级"上下文的主力工具。search_file_descriptions:只检索文件级元数据(标题、文档级描述),不触碰 chunk 内容与图谱关系,适合"这份语料里有哪些相关文档"式的宽泛定位。get_file_content:当 agent 需要更完整的上下文时,按document_id拉取整篇文档或其 chunk 结构。web_search:调用 Serper 等外部搜索 API 获取实时信息,需要SERPER_API_KEY。web_scrape:借助 Firecrawl 抽取指定网页正文做深度分析,需要FIRECRAWL_API_KEY。
Research 模式工具
rag:复用底层 RAG 智能体在你的数据源上做完整检索与综合,并将引用结果上抛给外层研究智能体。reasoning:把复杂推理任务外包给专用推理模型(reasoning_llm),是"外部专家模块"式的分析引擎。critique:基于对话历史找出推理缺陷、偏见与替代方案,提升研究严谨性。python_executor:在隔离子进程中执行 Python 代码,赋予智能体计算、统计与算法实现能力。
整体上,Agentic RAG 智能体由"工具注册中心(ToolRegistry)+ 检索回调注入(RAGAgentMixin)+ 研究工具集(ResearchAgentMixin)+ 流式事件封装"构成:它根据查询需求自主决定调用哪些工具、在推理过程中动态发起调用,最终输出带引用来源的完整回答。值得留意的是,critique与python_executor在RAGAgentConfig的默认research_tools列表中存在但源码注释将其标记为"DISABLED by default",实际是否启用取决于你在请求research_tools或部署配置中的显式声明(见 py/r2r/r2r.toml 中research_tools = ["rag", "reasoning", "critique", "python_executor"])。
配置参考
默认行为均可在 py/r2r/r2r.toml 的[app]与[agent]段调整:
[app] # LLM used for user-facing output, like RAG replies quality_llm = "openai/gpt-5-2025-08-07" # Reasoning model, used for `research` agent reasoning_llm = "openai/o3-mini" # Planning model, used for `research` agent planning_llm = "anthropic/claude-3-7-sonnet-20250219" [agent] rag_agent_static_prompt = "static_rag_agent" rag_agent_dynamic_prompt = "dynamic_rag_agent" # The following tools are available to the `rag` agent rag_tools = ["search_file_descriptions", "search_file_knowledge", "get_file_content"] # can add "web_search" | "web_scrape" # The following tools are available to the `research` agent research_tools = ["rag", "reasoning", "critique", "python_executor"]其中planning_llm是 Research 模式主生成模型(即未显式指定model时 Research 模式的默认模型),reasoning_llm是reasoning/critique工具的底层模型。提示词模板位于 py/core/providers/database/prompts 目录:static_rag_agent.yaml、dynamic_rag_agent.yaml、dynamic_rag_agent_xml_tooling.yaml服务于 RAG 智能体,static_research_agent.yaml服务于研究智能体,可结合 提示词文档 进行自定义。
总结
Agentic RAG 为检索增强生成提供了一套"检索 + 推理 + 工具 + 记忆"的组合方案:RAG 模式负责基于知识库的快速、可引用问答;Research 模式在其之上叠加reasoning、critique、python_executor与内部rag工具,形成面向复杂课题的深度研究链路。结合流式事件处理、search_settings透传、conversation_id会话保持与工具级裁剪,你可以在 R2R 已入库数据之上构建从"单轮知识问答"到"多步深度调研"的完整应用。
【免费下载链接】R2RSoTA production-ready AI retrieval system. Agentic Retrieval-Augmented Generation (RAG) with a RESTful API.项目地址: https://gitcode.com/GitHub_Trending/r2/R2R
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考