自然语言数据库管理系统

一个通过自然语言交互实现多数据库CRUD操作的系统,支持MySQL和PostgreSQL,集成LLM智能查询处理。

  • by chibbi1
  • Python
  • 本地部署
  • 更新于

使用说明

MCP驱动的数据管理系统

此存储库包含多层数据管理系统的代码,该系统允许用户使用自然语言与异构数据库(MySQL和PostgreSQL)进行交互。它利用FastMCP框架进行服务器端工具编排,并集成了用于智能查询处理和响应生成的大型语言模型(LLM)。 目录

  1. 概述

  2. 建筑

  3. 主要特点

  4. 设置和安装

    • 先决条件
    • 环境变量(.env)
    • 数据库配置(MySQL的Aiven控制台和Postgres的Supabase)
    • 运行服务器
    • 运行客户端
  5. 用法

  6. 故障排除

1.概述

该系统提供了一个对话界面,用于在多个数据库之间执行创建、读取、更新和删除(CRUD)操作。它智能地将用户请求路由到适当的后端工具,并以用户友好的格式显示结果,包括高级数据格式化选项。

2.建筑

该系统遵循分层架构:

客户端层 (客户1.py- 流线型UI):面向用户的自然语言交互web应用程序。

应用层 (主1.py- FastMCP服务器):承载数据库交互工具、与LLM集成并管理客户端和数据库之间数据流的核心编排层。

AI/LLM层 (OpenAI API):一个外部大型语言模型,负责理解用户意图、选择工具、提取参数和生成自然语言响应。

数据库层 (Aiven控制台和Supabase- MySQL和PostgreSQL):客户、产品和销售数据的持久存储。

概念图:

+-------------------+
|   User (Human)    |
+---------+---------+
          |
          | (Types Query)
          v
+-------------------+
|   Client Layer    |
|   (client1.py)    |
|   (Streamlit UI)  |
+---------+---------+
          |
          | (Async HTTP Request)
          v
+-------------------+
|  Application Layer|
| (main1.py)|
|  (FastMCP Server) |
+---------+---------+
          |  ^
          |  | (API Calls)
          |  |
          |  v
+---------+---------+
|   AI / LLM Layer  |
|   (OpenAI API)    |
+-------------------+
          |  ^
          |  | (DB Connections & Queries)
          |  |
          |  v
+---------+---------+
|   Database Layer  |
+---------+---------+
|  MySQL RDS        |
|  - Customers      |
|  - Sales          |
|  - Careplan       |
+-------------------+
|  PostgreSQL RDS   |
|  - products       |
+-------------------+

3.主要特点

- Natural Language Interface: Interact with databases using conversational prompts.

- Intelligent Tool Routing: LLM-powered selection of the correct database tool (sqlserver_crud, postgresql_crud, sales_crud) based on user intent.

- Heterogeneous Database Support: Manages data across MySQL (for Customers, Sales, ProductsCache) and PostgreSQL (for master products data).

- Cross-Database Operations: The sales_crud tool performs conceptual "joins" by linking sales records (MySQL) with customer data (MySQL) and product details (MySQL ProductsCache, mirrored from PostgreSQL).

- Dynamic Data Formatting: Client-side dropdown allows users to select how sales data is displayed:

    - - Data Format Conversion: Formats sale_date for readability.

    - - Decimal Value Formatting: Limits prices to two decimal places.

    - - String Concatenation: Combines customer names and product details into single fields.

    - - Null Value Removal/Handling: Demonstrates filtering out records with null values or replacing nulls with placeholders.

- Asynchronous Communication: Efficient, non-blocking client-server and server-database interactions using asyncio.

- Automated Database Seeding: The server automatically sets up and populates necessary tables on startup.

4.设置和安装

先决条件

Python 3.10+

pip (Python package installer)

环境变量(.env) 在项目的根目录(main1.py和client1.py所在的目录)中创建一个.env文件,并使用数据库凭据和API密钥填充该文件:

# OpenAI API Key for LLM integration
GROQ_API_KEY=your_api_key

# MCP Server URL (if deploying, this will be your server's public URL)
MCP_SERVER_URL=http://localhost:8000 # Change for deployment --> it will be the public URL for AWS EC2 instance and the onrender.com link for the Render Web service.
!!!!ADD THE PORT NUMBER AFTER THE URL --->    <url>:8000/


# MySQL Configuration
MYSQL_HOST=your_mysql_rds_endpoint
MYSQL_PORT=3306
MYSQL_USER=your_mysql_username
MYSQL_PASSWORD=your_mysql_password
MYSQL_DB=your_mysql_database_name

# PostgreSQL Configuration
PG_HOST=your_postgresql_rds_endpoint
PG_PORT=5432
PG_DB=your_postgresql_database_name
PG_USER=your_postgresql_username
PG_PASSWORD=your_postgresql_password

PG_SALES_HOST=your_postgresql_rds_endpoint
PG_SALES_PORT=5432
PG_SALES_DB=your_postgresql_database_name
PG_SALES_USER=your_postgresql_username
PG_SALES_PASSWORD=your_postgresql_password

数据库配置(AWS RDS)

  1. 在Aiven控制台上创建MySQL
  2. 创建PostgreSQL Supabase实例

记下他们的端点、IP地址、密码、主机名、用户名和数据库名称!!!检查 .env 上述文件格式☝️

安装Python依赖项

导航到终端中的项目目录并安装所需的Python包:

pip install fastmcp mysql-connector-python psycopg2-binary groq uvicorn pyodbc streamlit pandas pillow openai fastmcp mcp mcp-server python-dotenv asyncio langchain_groq langchain_core plotly

运行服务器

首选 渲染 并注册。然后创建一个 Web服务

在设置时,请提供存储库(具有服务器代码的存储库)的公共链接。

服务器(main1.py)承载数据库工具并与LLM通信。

nohup python -u main1.py > server.log 2>&1 &

此命令将:

Initialize and seed your MySQL and PostgreSQL databases (dropping and recreating tables if they exist).

Start the FastMCP server, typically listening on http://localhost:8000.

运行客户端

客户端(client1.py)提供Streamlit web界面。我们目前正在使用Streamlit云运行它。

streamlit run client1.py

这将在您的web浏览器中打开Streamlit应用程序。

5.使用方法

服务器和客户端都运行后,您可以通过Streamlit聊天界面与系统进行交互。

示例提示:

  • “通过电子邮件添加一位名为John Smith的新客户john.smith@email.com"
  • “将Widget的价格更新为29.99美元”
  • “从数据库中删除客户Alice Johnson”
  • “创建一款名为‘高级小工具’的新产品,售价149.99美元,描述为‘高端小工具’”
  • “将Bob Wilson的电子邮件更改为bob.wilson@newcompany.com"
  • “使用按产品列出的总销售额条形图显示所有销售数据”
  • “用饼图显示客户信息,按姓名首字母显示分布情况”
  • “列出所有带价格的产品,并创建价格分布直方图”
  • “用折线图显示随时间变化的销售趋势”
  • “通过可视化显示总价大于50的销售额”
  • 仅显示客户姓名和电子邮件,不包括其他字段
  • 列出价格在20美元到50美元之间的产品,按价格排序
  • “按数量显示最畅销的产品”
  • “显示尚未进行任何购买的客户”
  • “按时间可视化销售分布”
  • “以可视化形式显示销售数据”

6.故障排除

->_mysql_connector。MySQLInterfaceError:命令不同步:如果在同一游标上发送多个SQL命令过快,或者自动提交管理不当,则经常在数据库种子设定期间发生这种情况。当前的seed_tabases实现试图通过分离命令和显式管理事务来缓解这种情况。

->如果您无法使用 pyodbc 库,具体取决于部署计算机的操作系统-使用适当的cmd。检查 这里

->对于UI问题,请检查您的 client1.py 文件

  • 数据库连接错误(例如,“服务器不可访问”、“超时”):

      Verify your .env variables are correct (host, port, user, password, URL).
    
      Ensure your DB instances are "Available".
    
  • “未发现工具”/LLM错误:

      Ensure your main1.py is running and accessible at the MCP_SERVER_URL specified in your .env.
    
      Verify your GROQ_API_KEY is correct and has sufficient permissions.
    
      Check server logs for any errors during tool registration or LLM calls.
    
  • “列表销售”未显示任何结果:

      The Sales table starts empty. You must first use a "record a sale" prompt to add transactions.
    
      Confirm that the "record a sale" command returns a success message, indicating the data was inserted.
    
      Verify that the customer_id and product_id in your sales records have matching entries in the Customers and ProductsCache tables, respectively.