ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

DB-GPT Agent 连接数据库实战指南:Connector、Resource 与 DataScientist 的完整链路解析

DB-GPT Agent 连接数据库实战指南:Connector、Resource 与 DataScientist 的完整链路解析 DB-GPT Agent 连接数据库实战指南Connector、Resource 与 DataScientist 的完整链路解析【免费下载链接】DB-GPTopen-source agentic AI data assistant for the next generation of AI Data products.项目地址: https://gitcode.com/GitHub_Trending/db/DB-GPT在 DB-GPT 的 Agent 体系中让 Agent 基于数据库中的数据回答问题、做出决策是 Agentic AI Data 产品的核心场景。本文围绕 docs/docs/agents/introduction/database.md 展开完整演示从安装依赖、创建数据库连接器Connector、封装为 Agent 资源Resource到通过DataScientistAgent完成自然语言 → SQL → 表格化结果全流程的实操方法并辅以仓库源码解析其底层原理帮助读者在几分钟内构建一个可运行的数据库问答 Agent。一、Agent 使用数据库的整体思路在 DB-GPT 的 Agent 架构中数据库被视为一种Resource资源。Agent 并不直接操作数据库而是通过资源层完成数据读取、Schema 获取与 SQL 执行实现能力与数据解耦Connector连接器封装具体数据库的建连与 SQL 执行细节统一继承自RDBMSConnector抽象基类Resource资源将 Connector 包装成 Agent 可感知、可注入、可查询的标准化对象如RDBMSConnectorResource并提供get_promptSchema 信息注入提示词、querySQL 查询等能力Agent智能体如DataScientistAgent在收到用户问题时读取资源中的表结构生成并校验 SQL最后以结构化结果回复。从源码结构看这一分层在仓库中对应两条核心链路连接器实现在 packages/dbgpt-ext/src/dbgpt_ext/datasource/rdbms/ 下资源与智能体实现在 packages/dbgpt-core/src/dbgpt/agent/resource/database.py 与 packages/dbgpt-core/src/dbgpt/agent/expand/data_scientist_agent.py 中。二、安装依赖在 Agent 中使用数据库需要安装包含 Agent 能力与数据源扩展的基础依赖pip install dbgpt[agent,simple_framework]0.7.0 dbgpt_ext0.7.0dbgpt[agent,simple_framework]安装 DB-GPT 核心及 Agent 框架simple_framework提供轻量级的 Agent 运行环境dbgpt_extDB-GPT 的扩展包包含各类数据库连接器SQLite、MySQL、ClickHouse、Doris、DuckDB、Hive、MSSQL、OceanBase、PostgreSQL、StarRocks、Vertica 等与扩展能力是dbgpt_ext.datasource.rdbms模块的来源。需要说明的是0.7.0是文档给定的最低版本约束若使用 MySQL 等需要驱动的数据库还需确保对应 Python 驱动如pymysql已安装。三、创建数据库连接器ConnectorDB-GPT 的 RDBMS 连接器统一继承自RDBMSConnector其from_uri_db类方法会根据host / port / user / pwd / db_name拼接driver://user:passhost:port/db_name形式的 SQLAlchemy URL 并创建引擎见 packages/dbgpt-core/src/dbgpt/datasource/rdbms/base.py#L181-L205。下面给出三种最常用的连接器创建方式。3.1 SQLite临时数据库DB-GPT 提供开箱即用的临时 SQLite 数据库用于测试数据库文件创建在系统临时目录程序退出后自动删除。from dbgpt_ext.datasource.rdbms.conn_sqlite import SQLiteTempConnector connector SQLiteTempConnector.create_temporary_db() connector.create_temp_tables( { user: { columns: { id: INTEGER PRIMARY KEY, name: TEXT, age: INTEGER, }, data: [ (1, Tom, 10), (2, Jerry, 16), (3, Jack, 18), (4, Alice, 20), (5, Bob, 22), ], } } )从 packages/dbgpt-ext/src/dbgpt_ext/datasource/rdbms/conn_sqlite.py#L253-L342 的实现可以看到其工作方式create_temporary_db()内部通过tempfile.NamedTemporaryFile生成临时文件并创建 SQLAlchemy 引擎create_temp_tables(tables_info)依次执行CREATE TABLE与参数化INSERT最后调用_sync_tables_from_db()刷新表元数据close()/__exit__/__del__会清理临时文件因此支持with上下文管理器用法。3.2 SQLite文件数据库连接已有 SQLite 数据库文件只需提供正确的文件路径from dbgpt_ext.datasource.rdbms.conn_sqlite import SQLiteConnector connector SQLiteConnector.from_file_path(path/to/your/database.db)from_file_path会自动确保父目录存在并以check_same_threadFalse作为默认连接参数允许连接跨线程共享见 conn_sqlite.py#L93-L104。此外SQLite 还支持通过参数类以sqlite:///:memory:创建内存数据库。3.3 MySQL通过连接信息创建 MySQL 连接器from dbgpt_ext.datasource.rdbms.conn_mysql import MySQLConnector connector MySQLConnector.from_uri_db( hostlocalhost, port3307, userroot, pwd********, db_nameuser_manager, engine_args{connect_args: {charset: utf8mb4}}, )要点说明MySQLConnector的默认驱动为mysqlpymysql见 packages/dbgpt-ext/src/dbgpt_ext/datasource/rdbms/conn_mysql.py#L40-L47因此需要安装pymysqlengine_args会被原样透传给 SQLAlchemycreate_engine这里的connect_args.charsetutf8mb4用于保证中文等字符集正确from_uri_db是RDBMSConnector提供的通用工厂方法所有继承RDBMSConnector的连接器如DorisConnector、ClickhouseConnector、PostgreSQLConnector等均支持相同签名只是driver与db_dialect不同。3.4 更多数据库支持DB-GPT 的 RDBMS 连接器家族覆盖了非常广泛的数据库类型可在 packages/dbgpt-ext/src/dbgpt_ext/datasource/rdbms/ 目录下看到对应实现conn_clickhouse.py、conn_doris.py、conn_duckdb.py、conn_hive.py、conn_mssql.py、conn_oceanbase.py、conn_postgresql.py、conn_starrocks.py、conn_vertica.py等。它们都遵循相同的RDBMSConnector基类约定因此下面的 Resource 封装方式对以上所有数据库通用。四、将数据库封装为 Agent 资源Resource有了 Connector 之后需要用RDBMSConnectorResource将其封装为 Agent 可用的资源from dbgpt.agent.resource import RDBMSConnectorResource db_resource RDBMSConnectorResource(user_manager, connectorconnector)4.1 参数与自动推断RDBMSConnectorResource的构造签名见 packages/dbgpt-core/src/dbgpt/agent/resource/database.py#L144-L172为参数说明name资源名称用于在 Agent 对话中标识该数据库connectorRDBMSConnector实例SQLite、MySQL 等均可db_name数据库名缺省时自动取connector.get_current_db_name()db_type数据库类型缺省时自动取connector.db_typedialectSQL 方言缺省时自动取connector.dialectexecutor执行异步查询的线程池缺省自动创建ThreadPoolExecutor也就是说只需传入name和connectordb_type、dialect、db_name均会从连接器自动推断极大简化了使用成本。4.2 资源的核心能力DBResource基类RDBMSConnectorResource的父类定义了资源的两大职责Schema 注入get_prompt()通过get_schema_link()获取数据库表结构摘要并按默认模板Database type: {db_type}, related table structure definition: {schemas}生成注入给 LLM 的提示词见 database.py#L18-L96。RDBMSConnectorResource.get_schema_link实际调用dbgpt_ext.rag.summary.rdbms_db_summary._parse_db_summary完成表结构解析SQL 执行query(sql, db)/query_to_df(sql, db)将同步查询放入线程池异步执行_sync_query内部调用connector.run(sql)并返回(列名, 数据行)元组便于后续渲染。4.3 资源在 Agent 交互中的作用资源一旦绑定到 AgentDataScientistAgent会通过DBResource.from_resource(self.resource)取出数据库资源并将其dialect方言如sqlite/mysql注入到回复上下文中引导 LLM 生成正确方言的 SQL见 data_scientist_agent.py#L80-L100。同时Agent 的 profile goal 明确为基于资源中给出的数据库数据结构使用正确的{{dialect}}SQL 分析并解决用户输入目标。五、在 Agent 中使用数据库完整示例以下完整示例演示如何构建一个数据库问答 Agent用户提问DataScientistAgent默认名字 Edgar生成 SQL 查询并返回结构化结果。import asyncio import os from dbgpt.agent import AgentContext, AgentMemory, LLMConfig, UserProxyAgent from dbgpt.agent.expand.data_scientist_agent import DataScientistAgent from dbgpt.model.proxy import OpenAILLMClient async def main(): llm_client OpenAILLMClient( model_aliasgpt-3.5-turbo, # or other models, eg. gpt-4o api_baseos.getenv(OPENAI_API_BASE), api_keyos.getenv(OPENAI_API_KEY), ) context: AgentContext AgentContext( conv_idtest123, languageen, temperature0.5, max_new_tokens2048 ) agent_memory AgentMemory() agent_memory.gpts_memory.init(conv_idtest123) user_proxy await UserProxyAgent().bind(agent_memory).bind(context).build() sql_boy ( await DataScientistAgent() .bind(context) .bind(LLMConfig(llm_clientllm_client)) .bind(db_resource) .bind(agent_memory) .build() ) await user_proxy.initiate_chat( recipientsql_boy, revieweruser_proxy, messageWhat is the name and age of the user with age less than 18, ) ## dbgpt-vis message infos print(await agent_memory.gpts_memory.app_link_chat_message(test123)) if __name__ __main__: asyncio.run(main())5.1 代码结构拆解组件作用OpenAILLMClient代理 LLM 客户端通过OPENAI_API_BASE/OPENAI_API_KEY环境变量接入 OpenAI 兼容接口model_alias指定模型名如gpt-3.5-turbo、gpt-4oAgentContextAgent 运行上下文conv_id标识会话temperature控制生成随机性max_new_tokens限制生成长度AgentMemoryAgent 记忆容器gpts_memory.init(conv_id...)初始化指定会话的对话记忆UserProxyAgent用户代理代表人类参与对话此处同时作为 Reviewer 对 Edgar 的回答进行评审DataScientistAgent数据科学家 Agent默认名为 Edgar绑定db_resource后即可访问数据库.bind(...)链式绑定上下文、LLM 配置、资源与记忆最后.build()完成构建5.2 运行输出解析运行上述示例控制台输出大致如下-------------------------------------------------------------------------------- User (to Edgar)-[]: What is the name and age of the user with age less than 18 -------------------------------------------------------------------------------- un_stream ai response: { display_type: response_table, sql: SELECT name, age FROM user WHERE age 18, thought: I have selected a response_table to display the names and ages of users with an age less than 18. The SQL query retrieves the name and age columns from the user table where the age is less than 18. } -------------------------------------------------------------------------------- Edgar (to User)-[gpt-3.5-turbo]: {\n \display_type\: \response_table\,\n \sql\: \SELECT name, age FROM user WHERE age 18\,\n \thought\: \I have selected a response_table to display the names and ages of users with an age less than 18. The SQL query retrieves the name and age columns from the user table where the age is less than 18.\\n} Edgar Review info: Pass(None) Edgar Action report: execution succeeded, {display_type:response_table,sql:SELECT name, age FROM user WHERE age 18,thought:I have selected a response_table to display the names and ages of users with an age less than 18. The SQL query retrieves the name and age columns from the user table where the age is less than 18.} -------------------------------------------------------------------------------- agent-plans [{name: What is the name and age of the user with age less than 18, num: 1, status: complete, agent: Human, markdown: agent-messages\n[{\sender\: \DataScientist\, \receiver\: \Human\, \model\: \gpt-3.5-turbo\, \markdown\: \vis-db-chart\n{\sql\: \SELECT name, age FROM user WHERE age 18\, \type\: \response_table\, \title\: \\, \describe\: \I have selected a response_table to display the names and ages of users with an age less than 18. The SQL query retrieves the name and age columns from the user table where the age is less than 18.\, \data\: [{\name\: \Tom\, \age\: 10}, {\name\: \Jerry\, \age\: 16}]}\n\}]\n}这段输出完整展示了 Agent 的思考与执行过程LLM 生成Edgar 生成 JSON 结构包含display_type展示类型、sqlSQL 语句与thought推理说明Reviewer 评审Edgar Review info: Pass(None)表示评审通过SQL 执行Edgar Action report显示 SQL 执行成功age 18命中Tom(10)与Jerry(16)两条数据结果归档最终消息被封装为agent-plans计划块其中以vis-db-chart协议描述了表格型结果。5.3 GPT-Vis 协议结构化输出的底层约定输出中最关键的部分是末尾遵循 GPT-Vis 协议的结构化结果[ { name: What is the name and age of the user with age less than 18, num: 1, status: complete, agent: Human, markdown: agent-messages\n[{\sender\: \DataScientist\, \receiver\: \Human\, \model\: \gpt-3.5-turbo\, \markdown\: \vis-db-chart\\n{\\\sql\\\: \\\SELECT name, age FROM user WHERE age 18\\\, \\\type\\\: \\\response_table\\\, \\\title\\\: \\\\\\, \\\describe\\\: \\\I have selected a response_table to display the names and ages of users with an age less than 18. The SQL query retrieves the name and age columns from the user table where the age is less than 18.\\\, \\\data\\\: [{\\\name\\\: \\\Tom\\\, \\\age\\\: 10}, {\\\name\\\: \\\Jerry\\\, \\\age\\\: 16}]}\\n\}]\n } ]GPT-Vis 是一套面向 GPTs / 生成式 AI / LLM 项目的组件集合它定义了一种自定义 Markdown 代码语法协议来描述 AI 模型的输出并由前端组件将协议渲染为丰富的 UI 组件。在本例中内层vis-db-chart块携带sql、type如response_table、title、describe与data查询结果数组response_table类型意味着前端会将结果渲染为一张数据表表格内容即年龄小于 18 的用户的name与age。这也解释了为什么DataScientistAgent的ChartAction会在约束中要求从支持的展示类型中选择合适类型找不到合适类型时默认使用response_table——它保证了 Agent 的输出总能被 UI 层可靠渲染。六、源码级机制补充SQL 是如何被校验的DataScientistAgent并不仅仅生成 SQL还会对 SQL 进行正确性校验correctness_check见 data_scientist_agent.py#L102-L156其校验逻辑是检查是否生成了可执行的 SQLaction_report非空且is_exe_success为真从执行结果 JSON 中解析出sql字段缺失则判为失败调用self.database.query(sql, db...)实际执行查询若查询结果为空则判为失败并提示当前 SQL 无法找到数据请检查是否使用了不当的过滤字段值或过滤条件执行抛错时要求 Agent 重读历史信息修正 SQL。这一机制与示例输出中Pass(None)评审通过、Action report 显示execution succeeded一一对应也解释了为什么 Agent 能稳定产出可执行的 SQL生成 → 执行 → 校验 → 修正的闭环保障了最终答案的可靠性。七、小结与延伸通过本文读者可以掌握 DB-GPT 中Agent 数据库的完整套路安装dbgpt[agent,simple_framework]与dbgpt_ext用SQLiteTempConnector/SQLiteConnector/MySQLConnector或其他RDBMSConnector子类创建连接器用RDBMSConnectorResource(name, connector...)封装为 Agent 资源将资源绑定到DataScientistAgent配合UserProxyAgent与AgentMemory完成自然语言 → SQL → 表格结果的问答闭环理解 GPT-Vis 协议掌握vis-db-chart/response_table等结构化输出约定为自定义 Agent 展示层打基础。如果想进一步深入可以继续阅读仓库中的以下文件连接器基类与工厂方法packages/dbgpt-core/src/dbgpt/datasource/rdbms/base.py各类数据库连接器实现packages/dbgpt-ext/src/dbgpt_ext/datasource/rdbms/数据库资源封装packages/dbgpt-core/src/dbgpt/agent/resource/database.py数据科学家 Agent 与 SQL 校验packages/dbgpt-core/src/dbgpt/agent/expand/data_scientist_agent.py可运行的 Agent 示例examples/agents/sql_agent_dialogue_example.py【免费下载链接】DB-GPTopen-source agentic AI data assistant for the next generation of AI Data products.项目地址: https://gitcode.com/GitHub_Trending/db/DB-GPT创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表