拓冰建站拓冰建站
首页 / 资讯中心 / 正文

gpt-researcher 定向研究完全指南:source_urls、本地文档与 LangChain 文档源的实战配置

gpt-researcher 定向研究完全指南source_urls、本地文档与 LangChain 文档源的实战配置【免费下载链接】gpt-researcherAn autonomous agent that conducts deep research on any data using any LLM providers项目地址: https://gitcode.com/GitHub_Trending/gp/gpt-researchergpt-researcher 不仅支持基于 LLM 的自主联网研究还提供了多种定制研究来源的能力你可以限定它只研究你指定的 URL、让它基于本地文件夹中的文档做问答、把 LangChain 的文档对象直接喂给它甚至把这些方式组合成混合研究。本文以官方文档 docs/docs/gpt-researcher/context/tailored-research.md 为主线结合仓库源码逐项拆解source_urls、complement_source_urls、report_source、DOC_PATH、自定义提示词等关键参数在 gpt_researcher/agent.py 与 gpt_researcher/skills/researcher.py 中的真实行为读完你就能在项目中自主配置只查指定 URL只查本地文档web 本地混合以及自定义报告版式等场景。一、定制研究的入口GPTResearcher 构造函数所有定制研究能力都汇聚在GPTResearcher类的构造函数中。在 gpt_researcher/agent.py 中与研究来源直接相关的参数如下参数类型默认值作用report_sourcestrweb见ReportSource.Web研究信息来源web/local/hybrid/azure/langchain_documents/langchain_vectorstore/staticsource_urlslist[str]None指定一组要研究的 URL传入后优先走 URL 研究路径complement_source_urlsboolFalse是否在指定 URL 之外补充联网搜索默认False表示只研究你给的 URLdocument_urlslist[str]None在线文档 URLhybrid 模式下可用query_domainslist[str]None限定搜索域名documentslistNoneLangChain 文档对象列表vector_store/vector_store_filterobject / dictNone自定义向量库及检索过滤条件这些参数对应的来源枚举定义在 gpt_researcher/utils/enum.py 的ReportSource类中七个取值的字符串标识正是你在代码中要传给report_source的值。值得注意的是构造函数内部还会把这些参数与配置对象Config打通gpt_researcher/agent.py因此report_source也可以放在配置文件里通过REPORT_SOURCE环境变量或test_local.json这类配置下发见 gpt_researcher/config/variables/default.py。二、指定 URL 研究source_urls 与 complement_source_urls2.1 只研究给定 URL当你在构造函数传入source_urls时研究流程会切换到给定 URL分支。从 gpt_researcher/skills/researcher.py 可以看到判断逻辑if self.researcher.source_urls: research_data await self._get_context_by_urls(self.researcher.source_urls)即一旦source_urls非空Agent 就不会再自行检索网络而是进入_get_context_by_urls()gpt_researcher/skills/researcher.py先通过_get_new_urls过滤掉visited_urls中已访问过的地址再由scraper_manager.browse_urls()抓取页面内容最后交给上下文管理器按查询相关性压缩。这也是文档示例能直接运行的原因from gpt_researcher import GPTResearcher import asyncio async def get_report(query: str, report_type: str, sources: list) - str: researcher GPTResearcher(queryquery, report_typereport_type, source_urlssources, complement_source_urlsFalse) await researcher.conduct_research() report await researcher.write_report() return report if __name__ __main__: query What are the biggest trends in AI lately? report_source static sources [ https://en.wikipedia.org/wiki/Artificial_intelligence, https://www.ibm.com/think/insights/artificial-intelligence-trends, https://www.forbes.com/advisor/business/ai-statistics ] report asyncio.run(get_report(queryquery, report_sourcereport_source, sourcessources)) print(report)需要注意两点其一示例代码里的report_source static对应 gpt_researcher/utils/enum.py 中ReportSource.Static的取值它与给定 URL属于不同分支——传入source_urls时实际生效的是 URL 分支report_source更多用于标明来源语义其二source_urls传入的页面若与查询不相关Agent 会通过 WebSocket 输出unable to find relevant context提示gpt_researcher/skills/researcher.py并尝试在无相关上下文的情况下继续。2.2 在指定 URL 之外补充联网搜索complement_source_urls控制是否越界研究。源码中这个开关紧随 URL 分支之后生效if self.researcher.complement_source_urls: additional_research await self._get_context_by_web_search(self.researcher.query, [], self.researcher.query_domains) research_data .join(additional_research)也就是说complement_source_urlsFalse默认只抓取source_urls里给的页面不执行任何额外搜索complement_source_urlsTrue在完成指定 URL 研究后再以原始查询走一遍标准联网检索把搜索结果补充进上下文。_get_context_by_web_search的实现gpt_researcher/skills/researcher.py会先规划子查询plan_research再对每个子查询并发执行搜索 → 抓取 → 相似内容压缩最终把多路子查询结果合并为一个上下文串。因此开启补充后报告的事实来源 你指定的 URL 检索器默认 Tavily见 gpt_researcher/config/config.py搜到的页面二者都会出现在引用列表中。三、自定义 Agent 提示词custom_report如果你不想让 Agent 按默认版式写报告可以把整段指令作为query传入并配合report_typecustom_reportfrom gpt_researcher import GPTResearcher import asyncio async def get_report(prompt: str, report_type: str) - str: researcher GPTResearcher(queryprompt, report_typereport_type) await researcher.conduct_research() report await researcher.write_report() return report if __name__ __main__: report_type custom_report prompt Research the latest advancements in AI and provide a detailed report in APA format including sources. report asyncio.run(get_report(promptprompt, report_typereport_type)) print(report)这个机制的原理在 gpt_researcher/actions/report_generation.pyelif custom_prompt: content f{custom_prompt}\n\nContext: {context}即custom_report类型下你的query提示词会原样作为报告生成指令紧随其后拼接研究上下文。而提示词生成侧custom_report对应的generate_custom_report_prompt只做最简单的拼接gpt_researcher/prompts.pyreturn f{context}\n\n{query_prompt}映射关系位于 gpt_researcher/prompts.py 的report_type_mappingReportType.CustomReport.value即custom_report所以只要report_typecustom_report你的 prompt 就会直接驱动报告的结构、语气与格式要求例如 APA 格式、章节安排、引用规范研究上下文本体不变。这是定向研究中最灵活的一环——查询词本身成了写作指令。四、本地文档研究DOC_PATH 与 report_sourcelocal4.1 两步配置文档给出的本地研究流程分两步且与源码实现严格对应Step 1设置环境变量DOC_PATH指向文档所在文件夹export DOC_PATH./my-docsStep 2创建GPTResearcher实例时传report_sourcelocalfrom gpt_researcher import GPTResearcher import asyncio async def get_report(query: str, report_source: str) - str: researcher GPTResearcher(queryquery, report_sourcereport_source) await researcher.conduct_research() report await researcher.write_report() return report if __name__ __main__: query What can you tell me about myself based on my documents? report_source local # local or web report asyncio.run(get_report(queryquery, report_sourcereport_source)) print(report)配置文件中DOC_PATH的默认值是./my-docsgpt_researcher/config/variables/default.py与文档示例保持一致。若未设置DOC_PATH且REPORT_SOURCE不为webConfig._set_doc_pathgpt_researcher/config/config.py会自动校验路径路径不存在时validate_doc_path会用os.makedirs尝试创建目录gpt_researcher/config/config.py创建失败则回退到默认值。4.2 local 分支的真实执行路径report_sourcelocal在 gpt_researcher/skills/researcher.py 中的实现是elif self.researcher.report_source ReportSource.Local.value: document_data await DocumentLoader(self.researcher.cfg.doc_path).load() if self.researcher.vector_store: self.researcher.vector_store.load(document_data) research_data await self._get_context_by_web_search(self.researcher.query, document_data, self.researcher.query_domains)关键点有三DocumentLoader会递归遍历DOC_PATH下所有文件os.walk逐个按扩展名分发到对应的 LangChain 加载器gpt_researcher/document/document.py加载后的文档会作为scraped_data直接喂给_get_context_by_web_search在子查询处理中走已有数据 → 相似内容压缩路径gpt_researcher/skills/researcher.py不会再对这些本地文档发起网络抓取若你同时传入了vector_store本地文档会先灌入向量库供后续相似度检索使用。4.3 支持的文件格式文档提到支持 PDF、纯文本、CSV、Excel、Markdown、PowerPoint 和 Word。从 gpt_researcher/document/document.py 的loader_dict看实际支持的扩展名比文档列举的更多扩展名加载器说明pdfPyMuPDFLoaderPDF 文档epubUnstructuredEPubLoaderEPUB 电子书txtTextLoader纯文本doc/docxUnstructuredWordDocumentLoaderWord 文档pptxUnstructuredPowerPointLoaderPowerPoint 演示文稿csvUnstructuredCSVLoader(modeelements)CSV按元素切分xls/xlsxUnstructuredExcelLoader(modeelements)Excel 表格mdUnstructuredMarkdownLoaderMarkdownhtml/htmBSHTMLLoader网页 HTML即仓库实现还额外支持epub与html/htm。加载时每个文档会被转为{raw_content: ..., url: 文件名}的记录gpt_researcher/document/document.py其中url字段取的是文件名——这也是为什么本地研究生成的报告能标注出来源文件。若DOC_PATH下没有任何可加载文件load()会抛出Failed to load any documents!异常gpt_researcher/document/document.py所以请务必保证目录内有支持的格式。五、混合研究hybrid 同时使用 web 与本地文档5.1 用法与前置条件混合研究把前几节的能力组合起来既研究本地文档又补充联网检索。官方用法是传入report_sourcehybrid并自行准备两样东西——web 检索器通过RETRIEVER环境变量配置和本地文档目录DOC_PATH。hybrid 分支在 gpt_researcher/skills/researcher.py 的实现非常清晰elif self.researcher.report_source ReportSource.Hybrid.value: if self.researcher.document_urls: document_data await OnlineDocumentLoader(self.researcher.document_urls).load() else: document_data await DocumentLoader(self.researcher.cfg.doc_path).load() if self.researcher.vector_store: self.researcher.vector_store.load(document_data) docs_context, web_context await asyncio.gather( self._get_context_by_web_search(self.researcher.query, document_data, self.researcher.query_domains), self._get_context_by_web_search(self.researcher.query, [], self.researcher.query_domains), ) research_data self.researcher.prompt_family.join_local_web_documents(docs_context, web_context)从源码可见 hybrid 模式的三个事实本地文档来源可切换传document_urls时走OnlineDocumentLoadergpt_researcher/document/online_document.py支持按 URL 下载 PDF/文本/Office 文档等并对目标 URL 做 SSRF 安全校验否则走DocumentLoader读取DOC_PATH目录两条研究路径并发执行asyncio.gather同时运行基于本地文档的上下文提取与纯网络检索visited_urls集合仍会跨两条路径去重避免同一 URL 被重复抓取结果由提示词家族拼接join_local_web_documents负责把本地文档上下文与 web 上下文按固定格式合并再交给报告生成器。下图展示了 hybrid 模式多来源研究 → 向量库/上下文 → 报告生成的整体流程5.2 混合模式实践要点检索器配置hybrid 的 web 部分依赖你配置的检索器。默认RETRIEVERtavilygpt_researcher/config/config.py可用环境变量换成仓库支持的 Google、Bing、Brave、SearXNG 等对应 gpt_researcher/retrievers/ 下的实现若未配置任何有效检索器web 部分可能拿不到搜索结果。文档目录不传document_urls时必须保证DOC_PATH目录存在且含受支持格式的文件否则DocumentLoader会抛异常。向量库选配vector_store传入后本地文档会先灌库不传则完全依赖内存中的上下文压缩context_manager.get_similar_content_by_query。六、研究 LangChain 文档report_sourcelangchain_documents6.1 标准用法对于已经存在于 LangChain 生态例如从 PGVector 等向量库检索出来的的Document对象可以直接传给GPTResearcher无需落盘from langchain_core.documents import Document from typing import List, Dict from gpt_researcher import GPTResearcher from langchain_postgres.vectorstores import PGVector from langchain_openai import OpenAIEmbeddings from sqlalchemy import create_engine import asyncio CONNECTION_STRING postgresql://someuser:somepasslocalhost:5432/somedatabase def get_retriever(collection_name: str, search_kwargs: Dict[str, str]): engine create_engine(CONNECTION_STRING) embeddings OpenAIEmbeddings() index PGVector.from_existing_index( use_jsonbTrue, embeddingembeddings, collection_namecollection_name, connectionengine, ) return index.as_retriever(search_kwargssearch_kwargs) async def get_report(query: str, report_type: str, report_source: str, documents: List[Document]) - str: researcher GPTResearcher(queryquery, report_typereport_type, report_sourcereport_source, documentsdocuments) await researcher.conduct_research() report await researcher.write_report() return report if __name__ __main__: query What can you tell me about blue cheese based on my documents? report_type research_report report_source langchain_documents langchain_retriever get_retriever(cheese_collection, { k: 3 }) documents langchain_retriever.invoke(All the documents about cheese) report asyncio.run(get_report(queryquery, report_typereport_type, report_sourcereport_source, documentsdocuments)) print(report)6.2 底层处理逻辑report_sourcelangchain_documents分支在 gpt_researcher/skills/researcher.pyelif self.researcher.report_source ReportSource.LangChainDocuments.value: langchain_documents_data await LangChainDocumentLoader( self.researcher.documents ).load() if self.researcher.vector_store: self.researcher.vector_store.load(langchain_documents_data) research_data await self._get_context_by_web_search( self.researcher.query, langchain_documents_data, self.researcher.query_domains )LangChainDocumentLoadergpt_researcher/document/langchain_document.py会把每个Document转成{raw_content: document.page_content, url: document.metadata.get(title, )}两条记录——注意 URL 字段取自文档元数据中的title因此研究报告中的引用来源会显示为文档标题。随后这些记录与 local 模式一样作为scraped_data进入上下文压缩流程不会触发网络抓取。该模式非常适合把检索增强生成RAG流水线里已有的检索结果无缝接入 gpt-researcher 的报告生成。七、相关检索器与向量库的配合定向研究虽然把来源限定在指定 URL、本地文档或 LangChain 文档但整个检索-压缩链路仍依赖底层组件检索器Retrieverweb/hybrid 模式由RETRIEVER环境变量决定使用哪个搜索引擎实现Tavily、Google、Bing、Brave、SearXNG、Exa、Serper 等均位于 gpt_researcher/retrievers/。complement_source_urlsTrue时补充联网研究同样使用这些检索器。上下文压缩所有来源的原始内容都会经 gpt_researcher/context/compression.py 与 gpt_researcher/skills/context_manager.py 做相关性筛选与摘要控制最终喂给 LLM 的上下文规模这也是指定来源模式下控制成本与噪声的关键。向量库VectorStore通过vector_store参数可传入自定义向量库如 PGVectorlocal/hybrid/langchain_documents 模式下文档会先灌库_get_context_by_vectorstoregpt_researcher/skills/researcher.py则支持纯向量库检索的langchain_vectorstore来源。各模式与参数组合的对应关系可总结为下表便于快速选择目标场景report_source关键参数是否联网只研究指定 URL任意语义上可用staticsource_urlscomplement_source_urlsFalse否指定 URL 联网补充任意source_urlscomplement_source_urlsTrue是只研究本地目录文档localDOC_PATH或doc_path配置否web 本地文档混合hybridDOC_PATH或document_urls 有效检索器是研究内存中的 LangChain 文档langchain_documentsdocuments否纯向量库检索langchain_vectorstorevector_storevector_store_filter否自定义报告版式custom_report把写作指令作为query传入视其他参数八、快速自检与常见问题source_urls不生效检查是否在GPTResearcher构造函数中传入了非空列表传入后 Agent 会走_get_context_by_urls分支若想同时联网需显式设置complement_source_urlsTrue。local 模式报 Failed to load any documents!DOC_PATH目录为空或文件格式不在支持清单内pdf/epub/txt/doc/docx/pptx/csv/xls/xlsx/md/html/htm。可用export DOC_PATH...后运行DocumentLoader(cfg.doc_path).load()单测验证。hybrid 模式 web 部分无结果确认RETRIEVER已配置且 API Key 有效如 Tavily 需要TAVILY_API_KEY本地文档与 web 两条路径是并发执行的单独失败不会中断另一条。自定义 prompt 未体现版式要求确认report_typecustom_report的字符串准确无误它是 gpt_researcher/utils/enum.py 中ReportType.CustomReport.valueprompt 会原样拼在上下文之前gpt_researcher/actions/report_generation.py。引用来源显示为文件名而非 URL这是DocumentLoader/LangChainDocumentLoader将文档文件名或元数据title写入url字段所致属于预期行为。九、小结gpt-researcher 的定向研究本质上是一条可插拔的上下文管线report_source决定信息来源的门类web / local / hybrid / langchain_documents / langchain_vectorstoresource_urlscomplement_source_urls控制网络研究的边界DOC_PATH与documents提供本地与内存文档而custom_report把提示词变成报告版式的遥控器。理解 gpt_researcher/skills/researcher.py 中的分支调度你就能在私有知识库问答、指定站点资料整理、混合检索报告等场景中精准控制 gpt-researcher 的数据来源让研究始终落在你划定的范围内。【免费下载链接】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),仅供参考
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门