
GPT Researcher 提示词系统实战PromptFamily 类设计、报告类型分发与四大核心提示模板源码剖析【免费下载链接】gpt-researcherAn autonomous agent that conducts deep research on any data using any LLM providers项目地址: https://gitcode.com/GitHub_Trending/gp/gpt-researcherGPT Researchergpt-researcher的提示词系统集中定义在 gpt_researcher/prompts.py 的PromptFamily类中通过「按报告类型分发提示生成器」与「模型专属提示族」两个机制支撑从智能体角色选择、搜索查询规划、报告撰写到 MCP 工具挑选的完整研究流程。本文基于仓库内的提示系统参考文档 .claude/references/prompts.md 展开逐条对照gpt_researcher/prompts.py的真实源码讲解每个提示模板的签名、参数语义、注入位置以及失败兜底逻辑帮助你在二次开发或自定义提示词时做到有据可依。提示词集中管理PromptFamily 类的设计与分组参考文档的核心结论是所有提示词都集中放在PromptFamily类中以便派生出面向特定模型model-specific的提示变体。构造器接收一个Config实例并保存为self.cfg派生类可以据此根据已配置模型/提供方选择正确的提示格式。查看 gpt_researcher/prompts.py 的类实现类文档字符串把方法明确划分为两组这是理解整个提示系统的关键Prompt Generators提示生成器遵循标准签名、与ReportType枚举一一对应必须通过get_prompt_by_report_type间接访问Prompt Methods提示方法针对具体情境、没有统一签名由 agent 代码直接调用如auto_agent_instructions()、curate_sources()、generate_quick_summary_prompt()等。文档同时强调了一条硬性约定所有派生类必须保留相同的方法名集合但允许覆写其中的单个方法All derived classes must retain the same set of method names, but may override individual methods。这条约定保证了调用方actions/、skills/各模块可以无差别地把任何提示族实例当作PromptFamily使用。参考文档中展示的类骨架如下简化形式class PromptFamily: General purpose class for prompt formatting. Can be overwritten with model-specific derived classes. def __init__(self, config: Config): self.cfg config真实实现与文档一致见 gpt_researcher/prompts.py差别在于真实类中承载了十余个静态方法覆盖 MCP、图像生成、查询规划、报告撰写、详报子话题等全部场景。报告类型到提示生成器的映射get_prompt_by_report_type参考文档以match语句展示了「按报告类型返回对应提示生成器」的分发思路staticmethod def get_prompt_by_report_type(report_type: str): Returns the appropriate prompt generator for the report type. match report_type: case ReportType.ResearchReport.value: return PromptFamily.generate_report_prompt case ReportType.DetailedReport.value: return PromptFamily.generate_report_prompt case ReportType.OutlineReport.value: return PromptFamily.generate_outline_report_prompt # ... etc从源码结构看当前实现采用了更稳妥的「映射表 模块级函数」方案而不是把分发逻辑写进类里。gpt_researcher/prompts.py 中定义了映射表与分发函数report_type_mapping { ReportType.ResearchReport.value: generate_report_prompt, ReportType.ResourceReport.value: generate_resource_report_prompt, ReportType.OutlineReport.value: generate_outline_report_prompt, ReportType.CustomReport.value: generate_custom_report_prompt, ReportType.SubtopicReport.value: generate_subtopic_report_prompt, ReportType.DeepResearch.value: generate_deep_research_prompt, } def get_prompt_by_report_type( report_type: str, prompt_family: type[PromptFamily] | PromptFamily, ): prompt_by_type getattr(prompt_family, report_type_mapping.get(report_type, ), None) default_report_type ReportType.ResearchReport.value if not prompt_by_type: warnings.warn( fInvalid report type: {report_type}.\n fPlease use one of the following: {, .join([enum_value for enum_value in report_type_mapping.keys()])}\n fUsing default report type: {default_report_type} prompt., UserWarning, ) prompt_by_type getattr(prompt_family, report_type_mapping.get(default_report_type)) return prompt_by_type三个值得注意的工程细节分发目标可以是类也可以是实例prompt_family参数类型是type[PromptFamily] | PromptFamilygetattr对两者都成立因此调用方可以传入基类或任意派生族实例未知类型不抛异常而是降级非法report_type会触发UserWarning并回退到research_report的提示生成器保证研究主流程不因类型拼写错误而中断映射表的键来自 ReportType 枚举取值为research_report、resource_report、outline_report、custom_report、detailed_report、subtopic_report与deep。注意DetailedReport并不在映射表内详报的实际执行走SubtopicReport分支这与文档中「DetailedReport 直接映射到 generate_report_prompt」的简化写法不同以源码为准。该分发函数在报告撰写入口被调用gpt_researcher/actions/report_generation.py 的generate_report()中根据report_type与custom_prompt走三条不同路径generate_prompt get_prompt_by_report_type(report_type, prompt_family) if report_type subtopic_report: content f{generate_prompt(query, existing_headers, relevant_written_contents, main_topic, context, report_formatcfg.report_format, tonetone, total_wordscfg.total_words, languagecfg.language)} elif custom_prompt: content f{custom_prompt}\n\nContext: {context} else: content f{generate_prompt(query, context, report_source, report_formatcfg.report_format, tonetone, total_wordscfg.total_words, languagecfg.language)}即详报走子话题分支额外携带existing_headers与relevant_written_contents防止内容重复用户自定义提示直接拼接上下文其余类型走标准七参签名question、context、report_source、report_format、tone、total_words、language与源码中PROMPT_GENERATOR类型别名gpt_researcher/prompts.py声明的标准签名一致。核心提示模板一智能体角色选择提示参考文档给出的智能体选择提示示例generate_agent_role_prompt简化形式如下staticmethod def generate_agent_role_prompt(query: str, parent_query: str ) - str: return fAnalyze the research query and select the most appropriate agent role. Query: {query} {fParent Query: {parent_query} if parent_query else } Based on the query, determine: 1. The domain expertise needed 2. The research approach required 3. The appropriate agent persona Return a JSON object with: - agent: The agent type (e.g., Research Analyst, Technical Writer) - role: A detailed role description for how the agent should approach this research 其设计意图是让 LLM 依据查询内容判断所需领域专长、研究路径与人格设定并强制返回结构化的 JSON。对照当前源码这个职责由auto_agent_instructions()系统提示与choose_agent()动作共同承担系统提示auto_agent_instructions() 用 few-shot 示例Finance Agent、Business Analyst Agent、Travel Agent示范期望输出格式返回包含server智能体名与agent_role_prompt角色提示词两个键的 JSON 对象调用动作choose_agent() 将auto_agent_instructions()作为 system 消息、task: {query}作为 user 消息以temperature0.15调用smart_llm_model若存在parent_query会先拼成{parent_query} - {query}以保留主研究上下文JSON 解析三级兜底优先json_repair.loads修复带围栏或轻微损坏的 JSON其次正则提取{...}最后回退到内置的 Default Agent 角色提示见 gpt_researcher/actions/agent_creator.py。该兜底链有对应测试 tests/test_create_agent_json_repair_primary.py 覆盖测试中用SimpleNamespace(auto_agent_instructionslambda: sys)模拟提示族印证了「派生类只需保留同名方法」这一约定的实际价值。核心提示模板二搜索查询生成提示研究规划参考文档展示的查询规划提示简化形式staticmethod def generate_search_queries_prompt( query: str, parent_query: str , report_type: str , max_iterations: int 3, context: str , ) - str: return fGenerate {max_iterations} focused search queries to research: {query} Context from initial search: {context} Requirements: - Each query should explore a different aspect - Queries should be specific and searchable - Consider the report type: {report_type} Return a JSON array of query strings. 真实实现 generate_search_queries_prompt() 的参数为(question, parent_query, report_type, max_iterations3, context)其中context是List[Dict[str, Any]]类型的实时网页信息。相比文档示例源码版本增加了四条对检索质量影响显著的约束详报任务拼接当report_type为detailed_report或subtopic_report时任务串写成f{parent_query} - {question}使子话题查询始终锚定在主查询上禁用搜索操作符明确禁止site:、filetype:、inurl:、intitle:、OR、AND、NOT等语法因为「这些操作符并非被所有搜索后端支持会在很多后端上返回空结果」注入当前日期以 UTC 时间的%B %d, %Y格式写入提示缓解时效性问题严格输出格式要求只输出形如[query 1, query 2, query 3]的字符串列表且示例由max_iterations动态生成dynamic_example。该提示在 gpt_researcher/actions/query_processing.py 中被调用生成的查询列表随后驱动多轮检索循环。核心提示模板三报告生成提示含图片嵌入参考文档展示了带图片嵌入指令的报告提示简化形式staticmethod def generate_report_prompt( question: str, context: str, report_source: str, report_formatapa, total_words1000, toneNone, languageenglish, available_images: list [], ) - str: # Build image embedding instruction if images available image_instruction if available_images: image_list \n.join([ f- Title: {img.get(title)}\n URL: {img[url]} for img in available_images ]) image_instruction f AVAILABLE IMAGES (embed where relevant): {image_list} Use markdown format: Title return fInformation: {context} --- Using the above information, answer: {question} in a detailed report. - Format: {report_format} - Length: ~{total_words} words - Tone: {tone.value if tone else Objective} - Language: {language} - Include citations for all factual claims {image_instruction} 真实实现 generate_report_prompt() 没有把图片参数放进生成器而是先处理引用reference策略再把图片指令放到调用层。两个要点引用策略按来源分支。当report_source ReportSource.Web.value时要求报告末尾以超链接形式去重列出所有来源 URL并给出 APA 示例格式Author, A. A. (Year, Month Date). Title of web page. Website Name. url website非 Web 来源本地文档等则要求列出所用源文档名称。ReportSource枚举支持web、local、azure、langchain_documents、langchain_vectorstore、static、hybrid七种取值见 gpt_researcher/utils/enum.py。写作约束清单。真实提示强制了至少total_words字、Markdown 标题层级# / ## / ###、禁用目录TOC、每条实质性陈述/数字/引用必须带in-text citation形式的行内引用、禁止引用未出现在上下文中的来源、优先可信且更新的来源、以{date.today()}声明当前日期、按language参数定稿。tone为None时不注入语气指令非空时写成Write the report in a {tone.value} tone.Tone枚举提供 Objective、Formal、Analytical、Persuasive 等 17 种语气见 gpt_researcher/utils/enum.py。图片嵌入实际发生在调用层generate_report()available_images列表在提示拼接阶段被逐条做防御性校验——跳过非 dict 元素与缺少url的条目源码注释说明这是为了防止「部分 LLM 元数据」中的脏行触发KeyError/TypeError中断整个报告写入路径随后生成- Image N: alt - section_hint行并要求模型把每张图片单独成行、放在相关小节标题或段落之后。生成失败时还有一次重试把 system 角色提示合并进单条 user 消息再次请求gpt_researcher/actions/report_generation.py。核心提示模板四MCP 工具选择提示参考文档给出的 MCP 工具选择提示简化形式staticmethod def generate_mcp_tool_selection_prompt(query: str, tools_info: list, max_tools: int 3) - str: return fSelect the most relevant tools for researching: {query} AVAILABLE TOOLS: {json.dumps(tools_info, indent2)} Select exactly {max_tools} tools ranked by relevance. Return JSON: {{ selected_tools: [ {{index: 0, name: tool_name, relevance_score: 9, reason: ...}} ] }} 真实实现 generate_mcp_tool_selection_prompt() 与该示例同构并补充了四条明确的选择准则SELECTION CRITERIA选择能为查询提供信息、数据或洞察的工具优先能搜索/检索/访问相关内容的工具考虑工具之间的互补性例如不同数据源排除与研究主题明显无关的工具。返回的 JSON 要求「exact format」selected_tools数组含index、name、relevance_score、reason加上一个整体策略说明字段selection_reasoning并两次强调「恰好选择 {max_tools} 个工具、按相关性排序」。配套的 generate_mcp_research_prompt() 则负责第二步——基于被选中的工具执行研究它对selected_tools做了兼容处理对象取.name否则str(tool)并给出五条执行指令包括「工具调用失败或返回空时尝试替代方案」「尽量综合多来源信息」「聚焦与查询直接相关的事实性信息」。MCP 侧的工具选择逻辑位于 gpt_researcher/mcp/tool_selector.py相关健壮性可参考 tests/test_mcp_tool_selector_json_repair.py。模型专属提示族get_prompt_family 与 Granite 系列参考文档强调PromptFamily「允许以模型专属派生类覆写」而当前仓库中真正落地的模型专属变体就是 IBM Granite 系列。gpt_researcher/prompts.py 底部的工厂函数负责按名称实例化prompt_family_mapping { PromptFamilyEnum.Default.value: PromptFamily, PromptFamilyEnum.Granite.value: GranitePromptFamily, PromptFamilyEnum.Granite3.value: Granite3PromptFamily, PromptFamilyEnum.Granite31.value: Granite3PromptFamily, PromptFamilyEnum.Granite32.value: Granite3PromptFamily, PromptFamilyEnum.Granite33.value: Granite33PromptFamily, } def get_prompt_family( prompt_family_name: PromptFamilyEnum | str, config: Config, ) - PromptFamily: Get a prompt family by name or value. if isinstance(prompt_family_name, PromptFamilyEnum): prompt_family_name prompt_family_name.value if prompt_family : prompt_family_mapping.get(prompt_family_name): return prompt_family(config) warnings.warn(...) return PromptFamily()PromptFamilyEnum定义了default、granite、granite3、granite3.1、granite3.2、granite3.3六个取值gpt_researcher/utils/enum.py未知名称同样走「警告 回退默认族」策略。两个 Granite 派生类各自覆写了文档上下文格式化方法Granite3PromptFamily3.0–3.2pretty_print_docs把所有文档包进|start_of_role|documents|end_of_role| ... |end_of_text|角色块并统一在join_local_web_documents中合并本地与网络上下文后重新包裹Granite33PromptFamily3.3改用逐文档模板|start_of_role|document {document_id: ...}|end_of_role| ... |end_of_text|文档 ID 取自metadata[source]标题会拼进正文GranitePromptFamily 则是「版本路由器」它依据self.cfg.smart_llm字符串判断版本——含3.3用 Granite33含3用 Granite3否则回退基类pretty_print_docs与join_local_web_documents两个方法都委托给解析出的具体类。这正是构造器持有config的实际用途。提示族在 agent 初始化时被解析gpt_researcher/agent.py 中self.prompt_family get_prompt_family(prompt_family or self.cfg.prompt_family, self.cfg)随后作为参数贯穿全部下游模块——查询规划gpt_researcher/actions/query_processing.py、报告生成gpt_researcher/actions/report_generation.py、智能体选择gpt_researcher/actions/agent_creator.py、上下文压缩gpt_researcher/context/compression.py 中调用pretty_print_docs以及 skills 层的 researcher/writer/curator/context_manager如 gpt_researcher/skills/researcher.py 中用join_local_web_documents合并本地与网络上下文。这解释了为什么pretty_print_docs这类「看似只是格式化」的方法必须纳入提示族契约不同模型对文档上下文的分词格式要求完全不同。如何基于 PromptFamily 做二次扩展综合参考文档的约定与源码的调用方式扩展路径可以归纳为三步继承并只覆写需要的方法。派生类必须保留generate_report_prompt、generate_search_queries_prompt、auto_agent_instructions、pretty_print_docs、join_local_web_documents等同名方法可覆写其中任意子集否则get_prompt_by_report_type的getattr与各处直接调用会失败注册到工厂映射。把新族加入prompt_family_mappinggpt_researcher/prompts.py并扩展PromptFamilyEnum即可通过GPTResearcher(prompt_familyyour_family)或Config中的prompt_family字段全局启用用仓库现有测试模式验证。提示族被调用方以「任意对象 同名方法」的方式消费因此测试可以用SimpleNamespace或最小桩替代完整提示族例如 tests/test_create_agent_json_repair_primary.py 只保留auto_agent_instructions类似的快速摘要与来源筛选测试tests/test_quick_search_summary_context.py、tests/test_source_curator_json_parsing.py也展示了提示变更后的回归验证方式。需要留意的边界generate_report_prompt等标准生成器必须保持七参签名question、context、report_source、report_format、tone、total_words、language因为它由report_type_mapping间接调用而subtopic_report分支的调用签名是特殊的六参形式query、existing_headers、relevant_written_contents、main_topic、context 关键字参数自定义提示族覆写该方法时需同时满足这两种调用形态。小结GPT Researcher 的提示系统以PromptFamily为单一事实来源report_type_mappingget_prompt_by_report_type实现了报告类型到提示生成器的可降级分发智能体选择、查询规划、报告撰写、MCP 工具选择四类关键提示都以「结构化输出JSON/严格列表 明确约束引用、去重、日期、语言、语气」为共同设计范式get_prompt_family工厂与 Granite 派生族则演示了「同一契约、模型专属格式」的扩展机制。参考文档 .claude/references/prompts.md 提供的是这些机制的概念化模板落地实现细节如图片指令位于generate_report调用层、智能体选择实际由auto_agent_instructions()承担、Granite 文档块格式应以 gpt_researcher/prompts.py 及其调用方源码为准。【免费下载链接】gpt-researcherAn autonomous agent that conducts deep research on any data using any LLM providers项目地址: https://gitcode.com/GitHub_Trending/gp/gpt-researcher创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考