
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的场景中调用)
解决步骤
- 可优先尝试:升级
langchain-core和langchain-openai到最新版本(查看官方修复)。 - 如果升级无法解决,或需要立即规避警告,可在调用异步函数前确保已存在运行中的事件循环(如使用
asyncio.run(main()))。 - 对于开发者或自定义代码:修改三个受影响函数,将
asyncio.get_event_loop()替换为asyncio.get_running_loop()。具体位置包括:libs/core/langchain_core/callbacks/manager.py—_ahandle_event_for_handlerlibs/core/langchain_core/runnables/graph_mermaid.py—_render_mermaid_using_pyppeteerlibs/partners/openai/langchain_openai/chat_models/_client_utils.py—async_api_key_wrapper
- 保存更改后,刷新模块或重新启动应用。
验证方法
运行原有异步代码路径,观察是否仍输出 DeprecationWarning: asyncio.get_event_loop() deprecated in async contexts。若警告消失且异步功能正常,则问题已解决。如无报错输出,可进一步检查日志确认无异常。

![[Bug]: github_copilot provider: 'no choices' error for claude-opus-4.8 despite #29392 fix](https://www.chat-gpts.plus/wp-content/uploads/2026/06/30927-f9610a47-768x403.jpg)
![[Bug]: Custom `input_cost_per_token_above_ _tokens` tiers are silently dropped unless N is 128k/200k/272k](https://www.chat-gpts.plus/wp-content/uploads/2026/06/30344-fbe5ac89-768x403.jpg)
