VS Code运行Streamlit RAG聊天机器人遇事件循环及Torch错误求助
问题排查与解决方案
1. 解决RuntimeError: no running event loop错误
这个错误大多出现在异步代码没正确绑定事件循环的场景,尤其是Streamlit和Asyncio、LangChain这类异步组件混用时:
- 如果你代码里用了
async def定义的异步函数,别直接调用,要用asyncio.run()包裹执行:import asyncio # 错误写法:await your_async_function() # 正确写法: asyncio.run(your_async_function()) - 要是第三方库(比如LLM SDK、PDF处理工具)内部用了异步逻辑,在Streamlit同步环境里没处理好,试试绑定Streamlit的上下文到事件循环:
from streamlit.runtime.scriptrunner import add_script_run_ctx import asyncio loop = asyncio.new_event_loop() add_script_run_ctx(loop) asyncio.set_event_loop(loop)
2. 解决RuntimeError: Tried to instantiate class '__path__._path', but it does not exist!错误
这是PyTorch的自定义类/模块加载异常,主要和版本兼容、路径解析或缓存有关:
- 检查PyTorch和NLP相关依赖(
transformers、sentence-transformers等)的版本匹配度,比如PyTorch 2.x要搭配兼容的第三方库版本,执行以下命令安装稳定兼容组合:pip install torch==2.0.1 transformers==4.30.2 sentence-transformers==2.2.2 - 要是你自己写了Torch模型加载逻辑,别直接用
torch.load(),优先用官方提供的加载方法(比如AutoModel.from_pretrained());必须用torch.load()的话,要指定map_location参数避免路径解析错误。 - 清理本地缓存:删掉项目下的
__pycache__文件夹,以及~/.cache/huggingface目录,然后重装依赖、重启VS Code。
3. Streamlit上传PDF后UI报错处理
UI报错基本是后端逻辑抛异常导致的,先解决上面两个核心问题,再做以下检查:
- 给PDF处理逻辑加异常捕获,避免崩溃直接传到UI:
import pdfplumber import streamlit as st def extract_pdf_text(file): try: with pdfplumber.open(file) as pdf: text = "\n".join([page.extract_text() for page in pdf.pages]) return text except Exception as e: st.error(f"PDF处理失败:{str(e)}") return None - 用
st.session_state管理对话历史和PDF状态时,确保在脚本开头完成初始化:import streamlit as st if "chat_history" not in st.session_state: st.session_state.chat_history = [] if "pdf_text" not in st.session_state: st.session_state.pdf_text = ""
内容的提问来源于stack exchange,提问作者Arpit shourya
相关产品推荐
相关产品推荐

