ollama-deep-researcher进阶:自定义提示词工程
ollama-deep-researcher进阶:自定义提示词工程
引言:解锁本地AI研究助手的真正潜力
你是否曾遇到这样的困境:明明配置好了ollama-deep-researcher,却始终无法获得精准的研究结果?当AI生成的搜索查询偏离主题,当总结内容遗漏关键信息,当多轮研究陷入无效循环——问题可能不在于模型能力,而在于提示词工程的缺失。本文将系统拆解ollama-deep-researcher的提示词架构,提供从基础模板修改到高级动态优化的全流程指南,让你的本地研究助手真正理解并执行复杂研究任务。
读完本文,你将掌握:
- 核心提示词模板的结构与修改方法
- 基于研究场景的提示词定制策略
- 动态变量与环境感知提示词设计
- 多轮研究中的提示词迭代技巧
- 5个实战案例的完整实现代码
一、提示词工程基础:理解ollama-deep-researcher的"思维框架"
1.1 提示词模板的核心作用
在ollama-deep-researcher的架构中,提示词模板扮演着"思维框架"的角色,它定义了AI如何理解任务、处理信息和生成输出。通过分析prompts.py文件,我们可以发现系统采用了模块化的提示词设计,主要包含五大核心模板:
| 模板类型 | 主要功能 | 调用位置 |
|---|---|---|
| 查询生成器 | 将研究主题转化为精准搜索查询 | generate_query节点 |
| 摘要生成器 | 整合多源信息生成结构化总结 | summarize_sources节点 |
| 反思分析器 | 识别知识缺口并生成跟进查询 | reflect_on_summary节点 |
| JSON模式指令 | 确保输出符合特定JSON格式 | 工具调用前处理 |
| 工具调用指令 | 指导模型正确使用外部工具 | generate_search_query_with_structured_output函数 |
1.2 提示词处理流程解析
下图展示了提示词在研究流程中的作用机制:
关键发现:提示词不是静态字符串,而是动态接收上下文信息(如当前日期、研究进度、已有结论)的模板系统。这种设计允许我们通过修改模板来控制AI的"思考方式",而无需改变核心代码逻辑。
二、核心提示词模板解析与自定义方法
2.1 查询生成器(query_writer_instructions)
原始模板结构:
query_writer_instructions = """Your goal is to generate a targeted web search query.
<CONTEXT>
Current date: {current_date}
Please ensure your queries account for the most current information available as of this date.
</CONTEXT>
<TOPIC>
{research_topic}
</TOPIC>
<EXAMPLE>
Example output:
{{
"query": "machine learning transformer architecture explained",
"rationale": "Understanding the fundamental structure of transformer models"
}}
</EXAMPLE>"""
自定义策略:
- 添加领域限定词:在
<CONTEXT>中加入学科或行业术语,如"请使用计算机视觉领域专业术语" - 调整时间敏感度:修改日期提示,如"对于技术标准查询,优先返回2023年后的结果"
- 增强查询复杂度:在示例中展示布尔运算符使用,如
"query": "LLM fine-tuning AND LoRA NOT full fine-tuning"
代码示例:学术研究专用查询模板
academic_query_template = """Your goal is to generate academic search queries optimized for Google Scholar.
<CONTEXT>
Current date: {current_date}
Use academic terminology and include relevant years (last 5 years preferred).
For comparative studies, use "vs" between concepts.
For methodology-focused queries, include "methodology" or "approach".
</CONTEXT>
<TOPIC>
{research_topic}
</TOPIC>
<EXAMPLE>
Example output:
{{
"query": "attention mechanism in transformer models vs RNN 2020-2025",
"rationale": "Comparative analysis of modern sequence modeling approaches"
}}
</EXAMPLE>"""
2.2 摘要生成器(summarizer_instructions)
核心功能:该模板控制AI如何整合新搜索结果与已有总结,支持增量更新和信息融合。关键特性包括:
- 新信息检测:自动识别与现有总结不重叠的内容
- 结构化整合:将相关信息合并到对应段落
- 过渡自然化:为新增内容生成平滑过渡语句
高级自定义技巧:
- 指定信息优先级:
<REQUIREMENTS>
When creating a NEW summary:
1. Prioritize research methodology and dataset information
2. Include key performance metrics with specific numbers
3. Highlight limitations and future work sections
</REQUIREMENTS>
- 定制输出格式:
<FORMATTING>
- Start with a 2-sentence executive summary
- Use markdown headings for each major section
- Include bullet points for key findings
- Add a "Critical Analysis" section evaluating methodology strengths/weaknesses
</FORMATTING>
2.3 反思分析器(reflection_instructions)
这是实现深度研究的关键模板,控制AI识别知识缺口的能力:
reflection_instructions = """You are an expert research assistant analyzing a summary about {research_topic}.
<GOAL>
1. Identify knowledge gaps or areas that need deeper exploration
2. Generate a follow-up question that would help expand your understanding
3. Focus on technical details, implementation specifics, or emerging trends that weren't fully covered
</GOAL>"""
行业定制示例 - 市场研究场景:
market_research_reflection = """You are a market research analyst analyzing industry reports.
<GOAL>
1. Identify missing market size data, growth rates, or competitor analysis
2. Check for regional variations not covered in the current summary
3. Look for unaddressed customer segments or pain points
4. Generate follow-up questions that would reveal competitive advantages
</GOAL>
<SPECIAL_FOCUS>
- Prioritize gaps in quantitative data (market share, revenue figures)
- Look for unmentioned regulatory or compliance considerations
- Identify missing information about pricing strategies or business models
</SPECIAL_FOCUS>"""
三、动态提示词工程:环境感知与变量注入
3.1 内置动态变量解析
ollama-deep-researcher的提示词系统支持多种动态变量,这些变量在运行时被实际值替换,使提示词能够适应不同场景:
| 变量名 | 来源 | 作用 | 使用场景 |
|---|---|---|---|
| {current_date} | get_current_date()函数 |
提供当前日期 | 确保搜索结果时效性 |
| {research_topic} | 用户输入 | 研究主题 | 保持查询与主题一致性 |
| {max_tokens_per_source} | 配置文件 | 内容长度限制 | 控制输入token数量 |
| {fetch_full_page} | 配置参数 | 内容获取深度 | 平衡详细度与性能 |
3.2 自定义变量实现方法
通过修改graph.py中的节点函数,我们可以添加自定义变量。例如,添加研究领域变量以优化查询生成:
步骤1:修改配置类(configuration.py)
class Configuration(BaseModel):
# ... 现有配置 ...
research_domain: str = Field(
default="general",
title="Research Domain",
description="Domain-specific terminology to use in queries (e.g., 'medicine', 'computer science')"
)
步骤2:更新提示词模板(prompts.py)
query_writer_instructions = """Your goal is to generate a targeted web search query.
<CONTEXT>
Current date: {current_date}
Research domain: {research_domain}
Use terminology appropriate for the specified domain.
</CONTEXT>
<!-- 其余模板内容保持不变 -->
"""
步骤3:修改节点函数(graph.py)
def generate_query(state: SummaryState, config: RunnableConfig):
# ... 现有代码 ...
formatted_prompt = query_writer_instructions.format(
current_date=current_date,
research_topic=state.research_topic,
research_domain=configurable.research_domain # 新增变量
)
# ... 其余代码保持不变 ...
3.3 条件逻辑注入
通过在提示词中添加条件逻辑,可以使AI根据不同情况调整行为。例如,根据研究阶段动态调整摘要深度:
summarizer_instructions = """
<GOAL>
Generate a high-quality summary of the provided context.
</GOAL>
<REQUIREMENTS>
When creating a NEW summary (first research cycle):
1. Provide broad coverage of all key aspects
2. Include foundational background information
3. Summarize all major perspectives
When EXTENDING an existing summary (subsequent cycles):
1. Focus only on new information not previously covered
2. Emphasize connections to existing knowledge
3. Highlight contradictions or alternative viewpoints
</REQUIREMENTS>
<!-- 其余模板内容保持不变 -->
"""
四、高级提示词策略:多轮优化与模式切换
4.1 工具调用模式vs JSON模式
ollama-deep-researcher支持两种结构化输出模式,通过use_tool_calling配置参数切换,各具优势:
对比表格:
| 特性 | 工具调用模式 | JSON模式 |
|---|---|---|
| 实现方式 | 通过绑定工具类bind_tools([tool_class]) |
使用format="json"参数 |
| 输出格式 | 工具调用对象数组 | 纯JSON字符串 |
| 错误处理 | 内置工具调用验证 | 需要手动JSON解析 |
| 适用场景 | 复杂多工具交互 | 简单数据提取与转换 |
| 代码复杂度 | 较高(需定义工具类) | 较低(仅需JSON模板) |
模式切换对提示词的影响:
工具调用模式提示词:
tool_calling_query_instructions = """<INSTRUCTIONS>
Call the Query tool to format your response with the following keys:
- "query": The actual search query string
- "rationale": Brief explanation of why this query is relevant
</INSTRUCTIONS>
Call the Query Tool to generate a query for this request:"""
JSON模式提示词:
json_mode_query_instructions = """<FORMAT>
Format your response as a JSON object with ALL three of these exact keys:
- "query": The actual search query string
- "rationale": Brief explanation of why this query is relevant
</FORMAT>
Provide your response in JSON format:"""
4.2 多轮研究中的提示词迭代
研究流程本质上是提示词不断优化的过程。通过分析graph.py中的路由逻辑:
def route_research(
state: SummaryState, config: RunnableConfig
) -> Literal["finalize_summary", "web_research"]:
configurable = Configuration.from_runnable_config(config)
if state.research_loop_count <= configurable.max_web_research_loops:
return "web_research"
else:
return "finalize_summary"
我们可以设计随研究深度变化的动态提示词策略:
示例:迭代式摘要提示词
def get_summarizer_instructions(loop_count: int) -> str:
"""根据研究循环次数返回不同的摘要提示词"""
base_instructions = """
<GOAL>
Generate a high-quality summary of the provided context.
</GOAL>
"""
if loop_count == 0: # 首轮研究
return base_instructions + """
<REQUIREMENTS>
1. Create a broad overview of the topic
2. Identify major themes and key concepts
3. Note any significant controversies or debates
</REQUIREMENTS>
"""
elif loop_count < 3: # 中间轮次
return base_instructions + """
<REQUIREMENTS>
1. Focus on filling gaps in existing summary
2. Add specific details and supporting evidence
3. Connect new information to previously established concepts
</REQUIREMENTS>
"""
else: # 深度研究轮次
return base_instructions + """
<REQUIREMENTS>
1. Emphasize critical analysis and evaluation
2. Highlight methodological strengths and weaknesses
3. Identify areas requiring further research
4. Synthesize findings into coherent conclusions
</REQUIREMENTS>
"""
五、实战案例:五大场景的提示词优化
5.1 学术研究场景
挑战:需要精准的学术术语和同行评审资源
优化策略:添加学术资源偏好和方法论聚焦
自定义提示词模板:
academic_query_instructions = """Generate an academic search query for Google Scholar or IEEE Xplore.
<ACADEMIC_CONTEXT>
- Use peer-reviewed terminology
- Include specific methodologies where applicable
- Prefer recent studies (last 5 years)
- Target conference proceedings and journal articles
</ACADEMIC_CONTEXT>
<STRUCTURE>
query: "[核心概念] [方法论] [时间范围] site:.edu OR site:.ac.uk"
rationale: "Focus on academic sources for [核心概念] using [方法论]"
</STRUCTURE>
<TOPIC>
{research_topic}
</TOPIC>"""
配置设置:
config = Configuration(
max_web_research_loops=5,
search_api="tavily", # 学术资源更丰富
research_domain="computer science",
fetch_full_page=True
)
5.2 市场分析场景
挑战:需要最新市场数据和竞争情报
优化策略:强化时效性和定量数据提示
自定义反思提示词:
market_reflection_instructions = """Analyze the market research summary to identify data gaps.
<SPECIAL_FOCUS>
- Look for missing market size statistics
- Identify unaddressed competitor analysis
- Check for outdated information (>6 months old)
- Note missing regional or demographic breakdowns
</SPECIAL_FOCUS>
<OUTPUT_FORMAT>
{{
"knowledge_gap": "[具体缺失的数据类型]",
"follow_up_query": "[获取该数据的精准查询]"
}}
</OUTPUT_FORMAT>"""
5.3 技术文档场景
挑战:需要准确的技术参数和实现细节
优化策略:添加技术规格提示和版本限定
查询生成模板修改:
technical_query_instructions = """Generate a technical search query for documentation or developer resources.
<TECHNICAL_REQUIREMENTS>
- Include specific version numbers if applicable
- Prefer official documentation sources
- Target implementation examples and API references
- Include programming language or framework if relevant
</TECHNICAL_REQUIREMENTS>
<TOPIC>
{research_topic}
</TOPIC>
<EXAMPLE>
{{
"query": "ollama API v0.1.24 Python client implementation example",
"rationale": "Need recent implementation examples for specific API version"
}}
</EXAMPLE>"""
5.4 健康信息场景
挑战:需要权威健康信息和最新研究
优化策略:添加健康来源限定和证据等级提示
摘要生成模板修改:
health_summarizer_instructions = """Summarize health information with evidence-based focus.
<HEALTH_GUIDELINES>
1. Prioritize information from .gov, .edu, and health journals
2. Clearly distinguish between established facts and preliminary research
3. Note the level of evidence (RCT, meta-analysis, case study)
4. Include considerations and potential effects
</HEALTH_GUIDELINES>
<FORMATTING>
- Use IMRaD structure (Introduction, Methods, Results, Discussion)
- Include "Level of Evidence" section for each key finding
- Add "Practical Implications" section for practical applications
</FORMATTING>"""
5.5 创意写作场景
挑战:需要创意灵感和叙事结构
优化策略:放松事实约束,强化叙事元素提示
自定义提示词模板:
creative_query_instructions = """Generate search queries for creative inspiration and narrative elements.
<CREATIVE_CONTEXT>
- Focus on narrative structures and character development
- Look for thematic elements and symbolic references
- Include sensory details and descriptive language sources
- Explore diverse cultural perspectives on the theme
</CREATIVE_CONTEXT>
<OUTPUT>
{{
"query": "[主题] [叙事元素] [文化背景] creative examples",
"rationale": "Seeking inspiration for [主题] through [叙事元素] in [文化背景]"
}}
</OUTPUT>"""
六、最佳实践与故障排除
6.1 提示词设计原则
- 明确性:使用具体而非模糊的指令,如"使用不超过5个关键词"而非"保持查询简洁"
- 结构性:使用XML标签或markdown分隔不同指令部分,提高解析可靠性
- 适应性:为不同阶段(查询生成、总结、反思)设计专用模板
- 节制性:保持提示词简洁,避免冗余信息稀释核心指令
- 可测试性:设计可量化效果的提示词(如"生成3个不同角度的查询")
6.2 常见问题解决方案
| 问题症状 | 可能原因 | 解决方法 |
|---|---|---|
| 查询过于宽泛 | 主题理解不足 | 添加领域限定词,使用更具体的示例 |
| 总结缺乏深度 | 摘要模板过于简单 | 增加结构化要求,指定信息优先级 |
| 循环研究无效 | 反思提示词不足 | 强化知识缺口识别指令,添加具体缺口类型 |
| JSON解析错误 | 格式提示不清晰 | 使用更严格的格式说明,添加示例验证 |
| 结果相关性低 | 搜索API选择不当 | 根据主题切换搜索API,调整fetch_full_page参数 |
6.3 性能优化技巧
- Token控制:通过
max_tokens_per_source平衡信息完整性和性能 - 条件加载:根据研究阶段动态加载提示词模板,减少冗余
- 缓存策略:对频繁使用的静态提示
更多推荐

所有评论(0)