在有些场景下,我们希望智能体根据数据库中的数据来回答用户问题,或者根据数据库中的数据做出决策。在这种情况下,我们需要将智能体连接到数据库。

安装

为了在智能体中使用数据库,你需要安装DB-GPT框架提供的必要依赖。

  1. pip install "dbgpt[simple_framework]>=0.5.9rc0"

创建数据库连接

SQLite(临时)

提醒: 我们提供了SQLite数据库,主要是用于测试。临时数据库将在临时目录中创建,并在程序退出之后删除。

  1. from dbgpt.datasource.rdbms.conn_sqlite import SQLiteTempConnector
  2. connector = SQLiteTempConnector.create_temporary_db()
  3. connector.create_temp_tables(
  4. {
  5. "user": {
  6. "columns": {
  7. "id": "INTEGER PRIMARY KEY",
  8. "name": "TEXT",
  9. "age": "INTEGER",
  10. },
  11. "data": [
  12. (1, "Tom", 10),
  13. (2, "Jerry", 16),
  14. (3, "Jack", 18),
  15. (4, "Alice", 20),
  16. (5, "Bob", 22),
  17. ],
  18. }
  19. }
  20. )
SQLite

通过给定的路径连接到SQLite数据库,请确保文件路径正确。

  1. from dbgpt.datasource.rdbms.conn_sqlite import SQLiteConnector
  2. connector = SQLiteConnector.from_file_path("path/to/your/database.db"
MySQL

通过给定数据库连接信息来连接MySQL数据库,请确保连接信息正确。

  1. from dbgpt.datasource.rdbms.conn_mysql import MySQLConnector
  2. connector = MySQLConnector.from_uri_db(
  3. host="localhost",
  4. port=3307,
  5. user="root",
  6. pwd="**",
  7. db_name="user_manager",
  8. engine_args={"connect_args": {"charset": "utf8mb4"}},
  9. )

创建数据库资源

  1. from dbgpt.agent.resource import RDBMSConnectorResource
  2. db_resource = RDBMSConnectorResource("user_manager", connector=connector)

正如前面所说,Database也是一种资源,我们可以使用DB-GPT支持的大多数数据库,比如SQLite、MySQL、ClickHouse、ApacheDoris、DuckDB、Hive、MSSQL、OceanBase、PostgresSQL、StarRocks、Vertica等等

在智能体中使用数据库

  1. import asyncio
  2. import os
  3. from dbgpt.agent import AgentContext, AgentMemory, LLMConfig, UserProxyAgent
  4. from dbgpt.agent.expand.data_scientist_agent import DataScientistAgent
  5. from dbgpt.model.proxy import OpenAILLMClient
  6. async def main():
  7. llm_client = OpenAILLMClient(
  8. model_alias="gpt-3.5-turbo", # or other models, eg. "gpt-4o"
  9. api_base=os.getenv("OPENAI_API_BASE"),
  10. api_key=os.getenv("OPENAI_API_KEY"),
  11. )
  12. context: AgentContext = AgentContext(
  13. conv_id="test123", language="en", temperature=0.5, max_new_tokens=2048
  14. )
  15. agent_memory = AgentMemory()
  16. user_proxy = await UserProxyAgent().bind(agent_memory).bind(context).build()
  17. sql_boy = (
  18. await DataScientistAgent()
  19. .bind(context)
  20. .bind(LLMConfig(llm_client=llm_client))
  21. .bind(db_resource)
  22. .bind(agent_memory)
  23. .build()
  24. )
  25. await user_proxy.initiate_chat(
  26. recipient=sql_boy,
  27. reviewer=user_proxy,
  28. message="What is the name and age of the user with age less than 18",
  29. )
  30. ## dbgpt-vis message infos
  31. print(await agent_memory.gpts_memory.one_chat_completions("test123"))
  32. if __name__ == "__main__":
  33. asyncio.run(main())

查看输出

  1. --------------------------------------------------------------------------------
  2. User (to Edgar)-[]:
  3. "What is the name and age of the user with age less than 18"
  4. --------------------------------------------------------------------------------
  5. un_stream ai response: {
  6. "display_type": "response_table",
  7. "sql": "SELECT name, age FROM user WHERE age < 18",
  8. "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."
  9. }
  10. --------------------------------------------------------------------------------
  11. Edgar (to User)-[gpt-3.5-turbo]:
  12. "{\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}"
  13. >>>>>>>>Edgar Review info:
  14. Pass(None)
  15. >>>>>>>>Edgar Action report:
  16. execution succeeded,
  17. {"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."}
  18. --------------------------------------------------------------------------------
  19. ```agent-plans
  20. [{"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-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```"}]
  1. 让我们解析上面的输出结果,我们可以只关注最后的部分(通过[GPT-Vis](https://github.com/eosphoros-ai/GPT-Vis)可视化协议输出)
  2. ```json
  3. [
  4. {
  5. "name": "What is the name and age of the user with age less than 18",
  6. "num": 1,
  7. "status": "complete",
  8. "agent": "Human",
  9. "markdown": "```agent-messages\n[{\"sender\": \"DataScientist\", \"receiver\": \"Human\", \"model\": \"gpt-3.5-turbo\", \"markdown\": \"```vis-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```"
  10. }
  11. ]

什么是GPT-Vis协议? GPT-Vis是为生成式AI和大模型项目开发的一组可视化组件。提供了一组可视化协议来展示模型的输出, 并将其直接渲染到前端。支持丰富的类型,如表格、图表、代码等,同时支持自定义拓展。

在本案例中,输出的是一个表格,包含年龄小于18岁的用户的姓名和年龄。

附录