gpt-researcher 流式日志接入实战:通过自定义 WebSocket 处理器捕获研究过程日志 📅 发布时间:2026/9/11 21:36:47 👁 浏览次数: gpt-researcher 流式日志接入实战通过自定义 WebSocket 处理器捕获研究过程日志【免费下载链接】gpt-researcherAn autonomous agent that conducts deep research on any data using any LLM providers项目地址: https://gitcode.com/GitHub_Trending/gp/gpt-researcher本文基于开源项目 gpt-researcher 提供的最小化代码示例simple-logs-example.md讲解如何在 Python 程序中自定义send_json处理器并将其作为websocket参数注入GPTResearcher从而实时捕获研究任务的流式日志。读完本文你将掌握日志消息的 JSON 结构、关键事件类型、日志文件持久化机制并能基于源码与测试用例扩展出适合自己应用的日志处理方案。一、为什么需要自定义日志处理器gpt-researcher 的GPTResearcher在conduct_research()与write_report()的整个研究链路中会持续产生结构化的事件消息。默认情况下这些消息仅输出到终端而当你希望将日志用于实时展示、持久化分析或二次处理时就需要提供一个实现了send_json方法的对象。从源码结构看GPTResearcher构造函数的websocket参数gpt_researcher/agent.py是一个鸭子类型接口它并不强制要求是真正的 WebSocket 连接只要求实现异步的send_json方法。这意味着任何满足该接口的类——无论是 FastAPI WebSocket、Mock 对象还是自建的普通 Python 类——都可以作为日志接收器。二、最小可运行示例完整代码与逐段解析以下代码出自官方文档并在官方脚本 tests/gptr-logs-handler.py 中有等价实现可直接复制运行需先安装 gpt-researcherfrom typing import Dict, Any import asyncio from gpt_researcher import GPTResearcher class CustomLogsHandler: A custom Logs handler class to handle JSON data. def __init__(self): self.logs [] # Initialize logs to store data async def send_json(self, data: Dict[str, Any]) - None: Send JSON data and log it. self.logs.append(data) # Append data to logs print(fMy custom Log: {data}) # For demonstration, print the log async def run(): # Define the necessary parameters with sample values query What happened in the latest burning man floods? report_type research_report # Type of report to generate report_source online # Could specify source like online, books, etc. tone informative # Tone of the report (informative, casual, etc.) config_path None # Path to a config file, if needed # Initialize researcher with a custom WebSocket custom_logs_handler CustomLogsHandler() researcher GPTResearcher( queryquery, report_typereport_type, report_sourcereport_source, tonetone, config_pathconfig_path, websocketcustom_logs_handler ) await researcher.conduct_research() # Conduct the research report await researcher.write_report() # Write the research report return report # Run the asynchronous function using asyncio if __name__ __main__: asyncio.run(run())2.1 参数说明query研究任务的核心问题例如示例中的What happened in the latest burning man floods?最终会由 LLM 拆分为多个子查询。report_type报告类型如research_report基础研究报告、detailed_report详细报告、deep_research_report深度研究等可选值由report_type模块决定。report_source信息来源online表示在线检索也可设为local或langchain_documents等。tone报告语气如informative、casual、formal等。config_path配置文件路径None时使用环境变量与默认配置gpt_researcher/config 定义了完整的参数体系。2.2 运行结果运行完成后研究过程产生的每一条日志都会被追加到CustomLogsHandler.logs列表中控制台会逐条打印。官方文档给出的单条日志示例{ type: logs, content: added_source_url, output: ✅ Added source url to research: https://www.npr.org/2023/09/28/1202110410/how-rumors-and-conspiracy-theories-got-in-the-way-of-mauis-fire-recovery\n, metadata: https://www.npr.org/2023/09/28/1202110410/how-rumors-and-conspiracy-theories-got-in-the-way-of-mauis-fire-recovery }metadata字段会携带与该日志条目相关的信息如来源 URL、图片 URL 列表等。让上述脚本完整运行即可获得一次完整研究任务的全部日志输出。三、日志消息的 JSON 结构与消息类型3.1 消息结构从源码 gpt_researcher/actions/utils.py 的stream_output函数可以看出每条推送到 websocket 的消息都是一个包含四个字段的字典type消息大类如logs研究流程日志、report报告内容片段见 gpt_researcher/llm_provider/generic/base.py、cost成本信息。content事件描述符如starting_research、added_source_url、scraping_content。output面向用户的详细消息常含 emoji 视觉指示符。metadata与该事件相关的附加数据可为null、字符串或数组如 URL 列表。3.2 主要事件类型结合文档 all-about-logs.md 中完整的 26 类事件清单常见事件包括content 类型含义starting_research研究任务开始output 包含查询文本agent_generated显示当前使用的 agent 名称planning_research正在浏览与规划subqueries已生成子查询metadata 为子查询数组running_subquery_research正在执行某个子查询added_source_url发现相关来源 URLmetadata 为实际 URLscraping_urls/scraping_content正在抓取 / 已抓取内容writing_report/report_written开始撰写 / 完成报告writing_conclusion/conclusion_written开始撰写 / 完成结论四、进阶继承官方 CustomLogsHandler 实现日志持久化若想同时获得「实时转发」与「JSON 文件持久化」可直接复用后端实现 backend/server/server_utils.py 中的CustomLogsHandler与示例中的同名类是不同实现后者用于将日志落盘到outputs目录from backend.server.server_utils import CustomLogsHandler import asyncio from gpt_researcher import GPTResearcher async def run() - None: query What happened in the latest burning man floods? custom_logs_handler CustomLogsHandler(None, query) # websocket 传 None仅落盘 researcher GPTResearcher( queryquery, report_typeresearch_report, report_sourceonline, toneinformative, websocketcustom_logs_handler ) await researcher.conduct_research() report await researcher.write_report() return report asyncio.run(run())该实现的行为初始化时在outputs目录创建task_时间戳_任务哈希.json预置timestamp、events、content结构。send_json收到type logs的消息时将事件追加到events数组其他类型消息则合并更新content如query、sources、report、costs等字段。对应测试 tests/test_logging.py 验证了三条核心行为log 文件被创建、日志事件被正确写入、content 更新字段被正确持久化。五、底层原理日志如何在研究链路中流动入口gpt_researcher/__init__.py导出GPTResearcherwebsocket参数在 gpt_researcher/agent.py 被保存为self.websocket。转发中枢研究过程中几乎所有关键步骤都会调用stream_output(type, content, output, websocketNone, ...)它负责将结构化消息编码为 JSON 并通过await websocket.send_json(...)推送gpt_researcher/actions/utils.py。容错保障同文件还提供了safe_send_json包装器gpt_researcher/actions/utils.py在发送异常时捕获并记录错误避免日志通道问题影响主流程。报告流式输出LLM 生成报告内容时_send_output会推送{type: report, output: content}消息gpt_researcher/llm_provider/generic/base.py适合驱动前端逐段渲染。测试 tests/test_logging_output.py 展示了如何使用自定义TestWebSocket验证事件被完整捕获通过断言websocket.events非空来确认日志流确实打通。六、注意事项与最佳实践必须实现异步send_json处理器的方法必须是async def因为源码统一使用await websocket.send_json(...)调用。在合适层级做异常兜底若你的处理器内部抛错建议用try/except包装或参考safe_send_json的容错模式避免拖垮研究主流程。区分消息类型处理logs类消息适合追加事件流report类适合驱动界面渲染cost类适合展示 token 与费用字段见 gpt_researcher/actions/utils.py。日志用途可用于故障排查还原查询、来源与生成步骤、透明度审计展示访问过的 URL 与选中的图片、流程理解与可复现性追踪。完整事件语义若需覆盖全部事件描述符planning_research、subqueries、scraping_images等 26 类及其字段含义可查阅 all-about-logs.md开发者调试还可参考logs目录下更底层的.log与.json文件。通过上述方式你可以将 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),仅供参考