SQLAlchemy SQLite unable to open database file 修复
先确认数据库文件的位置,再处理异步问题。sqlite:///resources/Chinook.db 使用的是相对当前工作目录的路径。Jupyter 里可能能跑,换到 IDE 后 cwd 可能变成项目根目录、脚本目录或其他位置,resources/Chinook.db 就找不到了,SQLite 随之报 unable to open database file。目录不存在、文件不存在、路径指向目录或权限不足,也会得到同一个报错。
1. 用绝对路径确认数据库
from pathlib import Path
from langchain_community.utilities import SQLDatabase
db_path = Path('resources/Chinook.db').resolve()
print('cwd:', Path.cwd())
print('db_path:', db_path)
print('exists:', db_path.exists(), 'is_file:', db_path.is_file())
db = SQLDatabase.from_uri(f'sqlite:///{db_path.as_posix()}')
当 db_path 是绝对路径时,拼出来的 URI 通常是 sqlite:////home/.../resources/Chinook.db,这个形式没问题。不要写成 sqlite:///resources/Chinook.db 后假定它一定按 notebook 所在目录解析。
如果文件不存在,把课程仓库里的 resources/Chinook.db 复制到项目对应目录,或直接下载 Chinook SQLite 示例库放到该路径。目录不存在时先建目录:
db_path.parent.mkdir(parents=True, exist_ok=True)
再用 sqlite3 做一次最小测试:
import sqlite3
con = sqlite3.connect(db_path)
print(con.execute('select 1').fetchone())
con.close()
如果这样也打不开,先查路径、权限以及文件是否存在,别急着怀疑 LangChain。
2. 异步结构合并到一个入口
你现在的代码中,tools 是 async def main() 内部的局部变量,而 travel_agent = create_agent(..., tools=tools) 写在外面的模块级作用域,执行到那里会找不到 tools。Jupyter 本身已有事件循环,不能再用 asyncio.run();在 IDE 脚本里,也建议只保留一个 asyncio.run(main())。
可以按下面的方式调整:
import asyncio
from langchain_mcp_adapters.client import MultiServerMCPClient
from langchain.agents import create_agent
from langchain.messages import HumanMessage
async def main():
client = MultiServerMCPClient({
'travel_server': {
'transport': 'streamable_http',
'url': 'https://mcp.kiwi.com'
}
})
tools = await client.get_tools()
travel_agent = create_agent(
model='gpt-5-nano',
tools=tools,
system_prompt='...'
)
# 其他 agent、tool、coordinator 也在这里创建,
# 保证它们能拿到 tools 和 travel_agent
response = await coordinator.ainvoke(
{'messages': [HumanMessage(content='I am from London and I would like a wedding in Paris for 100 guests, jazz-genre')]},
config={'tags': ['WP'], 'recursion_limit': 40},
)
print(response['messages'][-1].content)
if __name__ == '__main__':
asyncio.run(main())
在 Jupyter 中不要执行 asyncio.run(main()),直接运行:
await main()
如果确实要把构建 tools 和 coordinator 拆开,就让函数返回 tools 或 agent,不要依赖 main() 中的局部变量。async def 里用 await,同步 tool 用普通 def。search_flights 这类会调用 travel_agent.ainvoke() 的 tool 可以继续保持 async def,但要确保 travel_agent 在它的可见作用域内。
3. 容易忽略的路径细节
sqlite:///foo.db是相对路径;sqlite:////abs/path/foo.db才是常见的 POSIX 绝对路径写法。- 父目录不存在时,不要指望 SQLite 自动建库。SQLite 能创建文件,但父目录不存在仍会报
unable to open database file。 - 只读场景要保证文件可读;需要写入时,要保证目录可写。
- 在 IDE 中运行脚本时,
Path.cwd()不一定是脚本所在目录。用Path(__file__).parent / 'resources/Chinook.db'更稳。Jupyter 里没有__file__,可以用绝对路径,或从项目根目录拼接。
先修数据库路径,再合并异步入口。多数情况下,改完 SQLDatabase.from_uri() 的路径后,这个 SQLite 报错就会消失。
备注:内容仅供参考。
