如何把 WrenAI 接入 Pydantic AI 代理查询 Wren 项目数据
【免费下载链接】WrenAIGenBI (Generative BI) for AI agents, an open-source, governed text-to-SQL through an open context layer that turns natural-language questions into trusted dashboards, charts, and SQL across 20+ data sources, such as BigQuery, Snowflake, PostgreSQL, ClickHouse, Amazon Redshift, Databricks and more.项目地址: https://gitcode.com/GitHub_Trending/wr/WrenAI
如果你的数据代理是基于 Pydantic AI 构建的,模型面对真实数据时的典型困难是:它只拿到一句自然语言问题,却不知道该用哪些表、字段的业务含义是什么、SQL 里应该写模型名还是物理表名。WrenAI 的wren-pydantic包解决的就是这件事:把一个用wrenCLI 准备好的 Wren 项目挂到 Pydantic AI 的Agent上作为 toolkit,代理就能通过工具获取上下文、召回历史查询、并通过 Wren 的上下文层写 SQL、执行 SQL。
前提条件是:Wren 项目必须由 CLI 提前准备好(profile + MDL + 可选 memory 索引)。wren-pydantic的文档明确说明它只是 CLI 准备好的项目之上的一个薄适配器,缺了这些,WrenToolkit.from_project()在构造时就会失败。本文按「CLI 准备项目 → 安装 SDK → 接入代理 → 运行验证」的顺序展开,最后给出文档列出的报错对照和已知限制。
准备:用 wren CLI 把项目备好
按快速开始文档(quickstart.md)的前置要求,环境需要 Python 3.11+,建议先建虚拟环境再装包:
python3 -m venv ~/.venvs/wren source ~/.venvs/wren/bin/activate安装 CLI,并带上数据源 connector 与 memory extra:
pip install "wrenai[memory,postgres]"然后是 SDK 文档给出的最小 CLI 引导流程(pydantic.md):
wren profile add my_project --datasource postgres # or mysql, duckdb, ... wren context init wren context set-profile my_project # binds profile to project wren context build # produces target/mdl.json wren memory index # optional but recommended几个直接影响后续步骤的细节:
wren profile add除--datasource外还支持--ui(浏览器表单)、--interactive(CLI 交互)、--from-file connection.yml(从 YAML 导入)。连接文档推荐 agent 驱动的场景用--from-file,让密钥放在.env里。不确定某个 connector 需要哪些连接字段时,运行wren docs connection-info <ds>(如wren docs connection-info postgres)查询,输出直接由已安装wrenai版本的连接 schema 生成。wren context set-profile my_project会把profile: my_project和data_source: <ds>写进项目的wren_project.yml,锁定项目与连接的绑定。此后该项目的 CLI 和 SDK 调用都用这个 profile,不受全局激活的 profile 影响——这正是 troubleshooting 表中「连接连到错误数据库」一行的修复手段。wren memory index是可选但推荐的。它生成的.wren/memory/目录决定代理能否获得 3 个 memory 工具(见下文工具表)。
用以下命令确认连接和项目就绪:
wren profile debug # show resolved config (secrets masked) wren --sql "SELECT 1" wren context show wren memory status连接失败时,连接文档给出的检查项是:凭据、网络可达性、SSL 设置、以及云数据库侧的 IP 白名单。
安装 wren-pydantic
选择与项目data_source匹配的 datasource extra 安装:
pip install "wren-pydantic[postgres,memory]" # or mysql, bigquery, ...| Extra | 用途 |
|---|---|
postgres/mysql/bigquery/snowflake/clickhouse/trino/mssql/databricks/redshift/spark/athena/oracle | 数据源透传(DuckDB 无需 extra) |
memory | 启用 3 个 memory 工具(wren_fetch_context、wren_recall_queries、wren_store_query) |
all | 一次装齐所有数据源——适合实验,生产环境偏重 |
由于前置步骤已经装过wrenai,实际上直接pip install wren-pydantic就够——已安装的 extras 会沿用。
文档给出的版本兼容矩阵:
wren-pydantic | wrenai | pydantic-ai |
|---|---|---|
| 0.1.x | >= 0.7.0 | >= 1.0, < 2.0 |
把项目接入 Pydantic AI 代理
核心接入代码只有几行:
from wren_pydantic import WrenToolkit from pydantic_ai import Agent toolkit = WrenToolkit.from_project("./analytics_db") agent = Agent( "openai:gpt-4o", instructions=toolkit.instructions(), toolsets=[toolkit.toolset()], ) result = agent.run_sync("Top 5 customers by revenue last quarter?") print(result.output)"./analytics_db"是文档示例中的项目路径,指包含wren_project.yml的项目根目录,换成你实际项目的路径;"openai:gpt-4o"是官方示例使用的模型,换成你自己可用的模型并配置相应 API key。
toolkit 会读取项目的 MDL、连接 profile 和instructions.md。toolkit.instructions()生成的指令字符串会按当前启用的工具自适应,并教会代理推荐工作流:召回历史查询 → 取上下文 → 写 SQL → 存储结果。
关键参数:
WrenToolkit.from_project(path, *, profile=None):path是项目根目录(含wren_project.yml的目录)。profile可选,解析顺序为:该 kwarg →wren_project.yml中的profile:字段 → 全局激活的 profile。toolkit.toolset(include_memory_write=True, takes_ctx=False):include_memory_write=False时 memory 变为只读(移除wren_store_query);takes_ctx=True会给每个工具注入ctx: RunContext首参,仅在你同时混用deps_type=类型工具时才需要。- memory 是自动探测的:存在
<path>/.wren/memory/时,3 个 memory 工具与 3 个 runtime 工具一起暴露;不存在则只有 runtime 工具。没有覆盖参数,要禁用 memory 就删除该目录,要启用就运行wren memory index。
代理可见的 6 个工具:
| Tool | 返回值 | 用途 |
|---|---|---|
wren_query | WrenQueryResult | 通过 Wren 上下文层执行 SQL;单次上限 1000 行 |
wren_dry_plan | str | 只做规划不执行;验证 SQL 是否正确指向 MDL 模型 |
wren_list_models | list[ModelSummary] | 列出项目模型,含列数和描述 |
wren_fetch_context | FetchContextResult | 为自然语言问题取回 schema 与业务上下文 |
wren_recall_queries | list[RecalledPair] | 返回相似的历史 NL→SQL 对作为 few-shot 示例 |
wren_store_query | str | 持久化一条确认过的 NL→SQL 对(注册时retries=0,写失败不会循环重试) |
每个工具以retries=2注册,SQL 或元数据错误时模型有两次自我修正机会;被归类为基础设施层的错误(连接失败、文件缺失)会以WrenError向上传播,而不是变成ModelRetry。
运行官方示例验证
仓库提供了可直接运行的示例 pydantic_ai_demo.py。它先校验项目是否有效:如果PROJECT_PATH指向的目录里没有wren_project.yml,会向 stderr 打印「不是 Wren 项目,请先运行wren context init,或把PROJECT_PATH设为已有项目」并以状态码 1 退出。
按示例文件头的说明运行(sk-...替换为你自己的 key):
PROJECT_PATH=/path/to/your/wren-project \ OPENAI_API_KEY=sk-... \ python sdk/wren-pydantic/examples/pydantic_ai_demo.pyPROJECT_PATH指向你的 Wren 项目根目录(不设置时默认为./analytics_db)。示例向代理提问 "How many rows are in each model in this project?" 并打印result.output——代理会实际调用wren_list_models、wren_query等工具后给出每个模型的行数,这同时验证了项目挂载、SQL 执行和输出三条链路。
可选的集成变体
以下分支都来自 pydantic.md 的 Integration patterns,按需选用。
结构化输出(output_type=)
让模型把答案返回为带类型的 Pydantic 实例,由框架校验:
from pydantic import BaseModel class TopCustomers(BaseModel): period: str customers: list[str] agent = Agent( "openai:gpt-4o", instructions=toolkit.instructions(), toolsets=[toolkit.toolset()], output_type=TopCustomers, # ← framework validates output into this type ) result = agent.run_sync("Top 5 customers last quarter?") print(result.output.customers) # already a list[str], no parsing needed仓库中的 pydantic_ai_structured_demo.py 是可运行版本,输出模型还带了一个可选的notes字段。
只读 memory(共享/人工维护的项目)
代理应学习历史查询、但不该污染 memory 存储时:
toolset = toolkit.toolset(include_memory_write=False) agent = Agent( "openai:gpt-4o", instructions=toolkit.instructions(toolset=toolset), # keep prompt in sync toolsets=[toolset], )注意instructions(toolset=...)要传入同一个 toolset,这样工作流会去掉「存储查询」这一步,而不是指示代理去调用一个不存在的工具。
与 deps_type= 工具混用
同一个 agent 里同时用 Wren 工具和你自己的依赖注入工具时,takes_ctx=True是必需的:
agent = Agent( "openai:gpt-4o", deps_type=MyDeps, toolsets=[toolkit.toolset(takes_ctx=True)], # ← required when deps_type is set )Wren 工具内部会忽略这个 context(toolkit 自己持有状态),takes_ctx=True只是让工具签名与 Pydantic AI 的 deps 类型注册兼容。
一个程序接多个项目
一个 toolkit 绑定一个项目。要查多个 Wren 项目,就分别构建 toolkit 和 agent,在 Python 里协调:
loans = WrenToolkit.from_project("./loans_proj") events = WrenToolkit.from_project("./events_proj") loans_agent = Agent(model=..., toolsets=[loans.toolset()], instructions=loans.instructions()) events_agent = Agent(model=..., toolsets=[events.toolset()], instructions=events.instructions())跨项目 join 只能在 Python 里做,不能在 SQL 里做——每个项目有自己的 MDL 和连接。
直接 Python API(跳过 agent 循环)
想不经过代理直接调 Wren 时:
toolkit.query("SELECT ...") # → pyarrow.Table toolkit.dry_plan("SELECT ...") # → str (target-dialect SQL) toolkit.dry_run("SELECT ...") # → None (validates without execution) toolkit.memory.fetch("revenue trends") toolkit.memory.recall("top customers", limit=3) toolkit.memory.store(nl="...", sql="...", tags=["revenue"])文档说明这是同步 API,没有aquery/afetch变体:底层引擎是同步 I/O,Pydantic AI 会自动把同步工具桥接进它的异步 run loop,再包一层asyncio.to_thread只是假异步,没有并发收益。
排查与限制
文档 troubleshooting 表列出的四个已知症状:
| 症状 | 原因 | 修复 |
|---|---|---|
SQL_PLANNING 阶段报table 'wren.<schema>.<x>' not found | 代理写了schema.table而不是 MDL 模型名 | 收紧 instructions 禁止使用物理表名;或让代理先调wren_list_models |
| 连接连到了错误的数据库 | 项目没有profile:固定 → 回退到全局激活 profile | 运行wren context set-profile <name>固定绑定 |
MissingSecretError | profile 里的${VAR}未解析 | 在<project>/.env中补上对应的 key |
wren_query返回的行数被截断 | 每次工具调用硬上限 1000 行 | 在 SQL 里加LIMIT;更大的拉取走直接 API(toolkit.query) |
已知限制(v0.1):
- 直接 API 只有同步版(理由见上一节)。
- 一个 agent 一个 toolkit;多个项目走「多 toolkit + 多 agent + Python 协调」。
- 无热重载机制,但
target/mdl.json在每次工具调用时重新读取,所以wren context build的更新会即时生效;profile 变更则需要重新构造 toolkit。 - 不要在代理正在使用同一项目时运行
wren memory index——该操作会删除并重建 LanceDB schema 表,并发读可能瞬时失败。
进一步操作可参考仓库中的 连接指南(含.env配置与连接字段查询)、CLI 参考 和 项目生命周期。
【免费下载链接】WrenAIGenBI (Generative BI) for AI agents, an open-source, governed text-to-SQL through an open context layer that turns natural-language questions into trusted dashboards, charts, and SQL across 20+ data sources, such as BigQuery, Snowflake, PostgreSQL, ClickHouse, Amazon Redshift, Databricks and more.项目地址: https://gitcode.com/GitHub_Trending/wr/WrenAI
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考