多彩编程 多彩编程MZPH · CODE BLOG
ARTICLE DETAIL

文章详情

深耕前端与后端开发技术的一线实战笔记与踩坑复盘。

如何把 WrenAI 接入 Pydantic AI 代理查询 Wren 项目数据

如何把 WrenAI 接入 Pydantic AI 代理查询 Wren 项目数据 如何把 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 extrapip install wrenai[memory,postgres]然后是 SDK 文档给出的最小 CLI 引导流程pydantic.mdwren 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浏览器表单、--interactiveCLI 交互、--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 无需 extramemory启用 3 个 memory 工具wren_fetch_context、wren_recall_queries、wren_store_queryall一次装齐所有数据源——适合实验生产环境偏重由于前置步骤已经装过wrenai实际上直接pip install wren-pydantic就够——已安装的 extras 会沿用。文档给出的版本兼容矩阵wren-pydanticwrenaipydantic-ai0.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, instructionstoolkit.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, *, profileNone)path是项目根目录含wren_project.yml的目录。profile可选解析顺序为该 kwarg →wren_project.yml中的profile:字段 → 全局激活的 profile。toolkit.toolset(include_memory_writeTrue, takes_ctxFalse)include_memory_writeFalse时 memory 变为只读移除wren_store_querytakes_ctxTrue会给每个工具注入ctx: RunContext首参仅在你同时混用deps_type类型工具时才需要。memory 是自动探测的存在path/.wren/memory/时3 个 memory 工具与 3 个 runtime 工具一起暴露不存在则只有 runtime 工具。没有覆盖参数要禁用 memory 就删除该目录要启用就运行wren memory index。代理可见的 6 个工具Tool返回值用途wren_queryWrenQueryResult通过 Wren 上下文层执行 SQL单次上限 1000 行wren_dry_planstr只做规划不执行验证 SQL 是否正确指向 MDL 模型wren_list_modelslist[ModelSummary]列出项目模型含列数和描述wren_fetch_contextFetchContextResult为自然语言问题取回 schema 与业务上下文wren_recall_querieslist[RecalledPair]返回相似的历史 NL→SQL 对作为 few-shot 示例wren_store_querystr持久化一条确认过的 NL→SQL 对注册时retries0写失败不会循环重试每个工具以retries2注册SQL 或元数据错误时模型有两次自我修正机会被归类为基础设施层的错误连接失败、文件缺失会以WrenError向上传播而不是变成ModelRetry。运行官方示例验证仓库提供了可直接运行的示例 pydantic_ai_demo.py。它先校验项目是否有效如果PROJECT_PATH指向的目录里没有wren_project.yml会向 stderr 打印「不是 Wren 项目请先运行wren context init或把PROJECT_PATH设为已有项目」并以状态码 1 退出。按示例文件头的说明运行sk-...替换为你自己的 keyPROJECT_PATH/path/to/your/wren-project \ OPENAI_API_KEYsk-... \ 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, instructionstoolkit.instructions(), toolsets[toolkit.toolset()], output_typeTopCustomers, # ← 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_writeFalse) agent Agent( openai:gpt-4o, instructionstoolkit.instructions(toolsettoolset), # keep prompt in sync toolsets[toolset], )注意instructions(toolset...)要传入同一个 toolset这样工作流会去掉「存储查询」这一步而不是指示代理去调用一个不存在的工具。与 deps_type 工具混用同一个 agent 里同时用 Wren 工具和你自己的依赖注入工具时takes_ctxTrue是必需的agent Agent( openai:gpt-4o, deps_typeMyDeps, toolsets[toolkit.toolset(takes_ctxTrue)], # ← required when deps_type is set )Wren 工具内部会忽略这个 contexttoolkit 自己持有状态takes_ctxTrue只是让工具签名与 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()], instructionsloans.instructions()) events_agent Agent(model..., toolsets[events.toolset()], instructionsevents.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, limit3) toolkit.memory.store(nl..., sql..., tags[revenue])文档说明这是同步 API没有aquery/afetch变体底层引擎是同步 I/OPydantic 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固定绑定MissingSecretErrorprofile 里的${VAR}未解析在project/.env中补上对应的 keywren_query返回的行数被截断每次工具调用硬上限 1000 行在 SQL 里加LIMIT更大的拉取走直接 APItoolkit.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),仅供参考
返回列表