core, openai: asyncio.get_event_loop() deprecated in async contexts

用户在使用 LangChain 的异步调用功能时触发,例如通过异步回调管理器处理事件、渲染 Mermaid 图表(使用 pyppeteer)、或调用 OpenAI 聊天模型时获取 API Key。具体涉及文件中包含三个异步函数: _ahandle_event_for_handler 、 _rende

core, openai: asyncio.get_event_loop() deprecated in async contexts

core, openai: asyncio.get_event_loop() deprecated in async contexts

快速结论:该报错通常在 Python 3.10 及以上版本运行 LangChain 异步(async)代码时触发,优先排查 LangChain 依赖版本并检查是否使用了最新的补丁版本。

问题场景

用户在使用 LangChain 的异步调用功能时触发,例如通过异步回调管理器处理事件、渲染 Mermaid 图表(使用 pyppeteer)、或调用 OpenAI 聊天模型时获取 API Key。具体涉及文件中包含三个异步函数:_ahandle_event_for_handler_render_mermaid_using_pyppeteer、以及 _async_api_key_wrapper

报错原文

asyncio.get_event_loop() deprecated in async contexts
DeprecationWarning: There is no current event loop

(注:上述报错为 Python 3.10+ 环境中调用 asyncio.get_event_loop() 时的典型警告,实际运行时可能仅输出 DeprecationWarning 而非中断执行,但会影响异步上下文稳定性。)

原因分析

在 Python 3.10 及以上版本中,asyncio.get_event_loop() 在异步上下文(async def 内部)已被标为 deprecated,正确做法是使用 asyncio.get_running_loop()。LangChain 的三个函数内依然使用了前者,导致触发 deprecation 警告,并可能在缺少当前事件循环时引发 RuntimeError。该问题仅影响异步调用路径,不影响同步代码。

环境排查

  • Python 版本是否为 3.10 或更高?(建议确认是否为 deprecation 触发条件)
  • LangChain 版本(特别是 langchain-core)是否较旧?(需检查已发布的补丁是否修复此问题)
  • 是否使用了 langchain-openai 组件?
  • 异步环境中是否缺少正在运行的事件循环?(例如在未配置 asyncio.run()nest_asyncio 的场景中调用)

解决步骤

  1. 可优先尝试:升级 langchain-corelangchain-openai 到最新版本(查看官方修复)。
  2. 如果升级无法解决,或需要立即规避警告,可在调用异步函数前确保已存在运行中的事件循环(如使用 asyncio.run(main()))。
  3. 对于开发者或自定义代码:修改三个受影响函数,将 asyncio.get_event_loop() 替换为 asyncio.get_running_loop()。具体位置包括:
    • libs/core/langchain_core/callbacks/manager.py_ahandle_event_for_handler
    • libs/core/langchain_core/runnables/graph_mermaid.py_render_mermaid_using_pyppeteer
    • libs/partners/openai/langchain_openai/chat_models/_client_utils.pyasync_api_key_wrapper
  4. 保存更改后,刷新模块或重新启动应用。

验证方法

运行原有异步代码路径,观察是否仍输出 DeprecationWarning: asyncio.get_event_loop() deprecated in async contexts。若警告消失且异步功能正常,则问题已解决。如无报错输出,可进一步检查日志确认无异常。

参考来源

langchain-ai/langchain #35726

GamsGo AI

AI 工具推荐

想把多个 AI 模型放在一个入口?

GamsGo AI 集成 ChatGPT、DeepSeek、Gemini、Claude、Midjourney、Veo 等常用模型,适合写作、绘图、视频和日常 AI 工作流。

了解 GamsGo AI

推广链接:通过此链接购买,我可能获得佣金,不影响你的价格。

celebrityanime
celebrityanime
文章: 9733

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注