Dify + Agent实现自然语言查询Mysql数据库并分析

问题是,我配置完AGENT中的提示词、变量、知识库、工具后,比如我输入“查询用户信息”,按照 【知识库】中的文件信息,生成的sql应该是 “select  *  from  sys_user”等sql,但现在情况是,生成的sql中的表信息,与我配置的知识库中的信息不一致,问题出在哪里,虚心请教,感谢!!!!

1. python的sql处理工具

from flask import Flask, request, jsonify
from sqlalchemy import create_engine, text
import datetime

app = Flask(__name__)
DATABASE_URI = 'mysql+pymysql://root:1111111@127.0.0.1:3306/ai-test'
engine = create_engine(DATABASE_URI)


@app.route('/query', methods=['POST'])
def query_database():
    sql_query = request.json.get('sql')

    # 获取当前时间
    current_time = datetime.datetime.now()
    # 格式化时间,精确到时分秒
    formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")

    print("======"+formatted_time+"=======用户输入的信息为:"+sql_query+" ==================")
    if not sql_query:
        return jsonify({"error": "SQL query is required"}), 400

    try:
        with engine.connect() as connection:
            result = connection.execute(text(sql_query))
            rows = result.fetchall()

            columns = result.keys()
            result_dict = []
            for row in rows:
                row_data = {}
                for col in columns:
                    value = row._mapping[col]
                    # 处理 bytes 类型数据(转字符串)
                    if isinstance(value, bytes):
                        value = value.decode('utf-8', errors='ignore')  # 按实际编码调整
                    row_data[col] = value
                result_dict.append(row_data)
            return jsonify(result_dict)

    except Exception as e:
        return jsonify({"error": str(e)}), 500


if __name__ == '__main__':
    #app.run(debug=True)
    #指定运行端口,开启外部访问
    app.run(debug=True, host='0.0.0.0', port=5000)  # 添加 host='0.0.0.0'


2.ollana中部署 千问  模型

3.docker desktop中安装 dify

4.工作流配置

4.1 开始

4.2 自然语言生成sql

SYSTEM

你是一位精通SQL语言的数据库专家,熟悉MySQL数据库。你的任务是根据用户的自然语言输入,编写出可直接执行的SQL查询语句。输出内容必须是可以执行的SQL语句,不能包含任何多余的信息。
核心规则:
1.根据用户的查询需求,确定涉及的表和字段。
2.确保SQL语句的语法符合MVSOL的规范。
3.输出的SQL语句必须完整且可执行,不包含注释或多余的换行符。
关键技巧:
WHERE 子句:用于过滤数据。例如,`WHERE column_name ='value'
**日期处理:**使用`STR_TO_DATE`函数将字符串转换为日期类型。例如,`STR_TO_DATE('2025-03-14','%Y-%m-%d')`。
**聚合函数:**如'COUNT'、'SUM`、'AVG'等,用于计算汇总信息。
-**除法处理:**在进行除法运算时,需考虑除数为零的情况,避免错误。
-**日期范围示例:**查询特定日期范围的数据时,使用`BETWEEN`关键字。例如,`WHERE date_coumn BETWEEN'2025-01-01'
AND'2025-12-31'。
**注章事项,**
1.确保字段名和表名的正确性,避免拼写错误。
2.对于字符串类型的字段,使用单引号括起来。例如,"sample_text'
3.在使用聚合函数时,如果需要根据特定字段分组,使用`GROUPBY'子句
4.在进行除法运算时,需判断除数是否为零,以避免运行时错误。
5.生成的sq1语句不能有换行符比如\n
6.在计算用户总数的时候,直接计算用户的个数就可以了

USER  

表结构描述:
表名称:'sys_user', 用户信息表
字段列表:
`user_id`,用户id, 整数
`dept_id`,部门id, 整数
`user_name`,用户名称,字符串
`nick_name`,用户昵称,字符串
`user_type` ,'用户类型(00系统用户)',字符串
`email`, '用户邮箱',字符串
`phonenumber`,'手机号码',字符串
`sex` ,'用户性别(0男 1女 2未知)',字符串
`avatar`, '头像地址',字符串
`password` ,账号密码,字符串
`status` , '帐号状态(0正常 1停用)',字符串
`del_flag` , '删除标志(0代表存在 2代表删除)',字符串
`login_ip` , '最后登录IP',字符串
`login_date` , '最后登录时间',日期类型
`create_by` , '创建者',字符串
`create_time`,'创建时间',日期类型
`update_by` , '更新者',字符串
`update_time`  '更新时间',日期类型
`remark` ,'备注',字符串

表结构描述:
表名称:'sys_dept', 单位信息表
字段列表:
`dept_id`,'单位id',整数
`parent_id`,'上级单位id',整数
`ancestors`,'祖级列表',字符串
`dept_name`,'单位名称',字符串
`order_num` ,'显示顺序',整数
`leader` ,'负责人',字符串
`phone` ,'联系电话',字符串
`email` ,'邮箱',字符串
`status`,'部门状态(0正常 1停用)',字符串
`del_flag` ,'删除标志(0代表存在 2代表删除)',字符串
`create_by`,创建人,字符串
`create_time`,'创建时间',日期类型
`update_by`, '更新者',字符串
`update_time`,更新时间,日期类型

4.3  代码执行

from urllib import request
import urllib.request
import json


def main(sql: str) -> dict:

    data = {"sql": sql}
    url = 'http://127.0.0.1:5000/query'

    json_data = json.dumps(data)
    byte_data = json_data.encode('utf-8')

    req = urllib.request.Request(url, data=byte_data, headers={'Content-Type': 'application/json'})

    response = urllib.request.urlopen(req)
    response_data = response.read().decode('utf-8')

    return {
        "result": response_data,
    }

4.4  查询结果分析

SYSTEM

你是系统行业数据分析专家,分析JSON格式的sql查询结果,回答用户问题。
关键规则:
1.所有数据已经复核用户问题中的条件
2.直接使用提供的数据分析,不质疑3数据是否符合条件
3.不需要在此筛选或确认数据类别/时间范围
4.数据为[]或为空或者未None时直接回复“没有查询到相关数据”,不得编造数据

USER 

数据是:{{#1742266695658.result#}}
问题是:{{#1742266651455.sql#}}
回答要求:
1.列出详细数据,优先以表格方式列出数据。
2.识别趋势、异常、并提供分析和建议
3.分析sql语句<{{#1742266695658.result#}}和用户的问题{{#1742266651455.sql#}}是否匹配
4.最后附上查询的sql语句

5. 知识库

表结构描述:
表名称:'sys_user'  用户信息表
字段列表:
`user_id`,用户id, 整数
`dept_id`,部门id, 整数
`user_name`,用户名称,字符串
`nick_name`,用户昵称,字符串
`user_type` ,'用户类型(00系统用户)',字符串
`email`, '用户邮箱',字符串
`phonenumber`,'手机号码',字符串
`sex` ,'用户性别(0男 1女 2未知)',字符串
`avatar`, '头像地址',字符串
`password` ,账号密码,字符串
`status` , '帐号状态(0正常 1停用)',字符串
`del_flag` , '删除标志(0代表存在 2代表删除)',字符串
`login_ip` , '最后登录IP',字符串
`login_date` , '最后登录时间',日期类型
`create_by` , '创建者',字符串
`create_time`,'创建时间',日期类型
`update_by` , '更新者',字符串
`update_time`  '更新时间',日期类型
`remark` ,'备注',字符串

表结构描述:
表名称:'sys_dept'  单位信息表
字段列表:
`dept_id`,'单位id',整数
`parent_id`,'上级单位id',整数
`ancestors`,'祖级列表',字符串
`dept_name`,'单位名称',字符串
`order_num` ,'显示顺序',整数
`leader` ,'负责人',字符串
`phone` ,'联系电话',字符串
`email` ,'邮箱',字符串
`status`,'部门状态(0正常 1停用)',字符串
`del_flag` ,'删除标志(0代表存在 2代表删除)',字符串
`create_by`,创建人,字符串
`create_time`,'创建时间',日期类型
`update_by`, '更新者',字符串
`update_time`,更新时间,日期类型

6.AGENT 配置

7.测试

问题是,我配置完AGENT中的提示词、变量、知识库、工具后,比如我输入“查询用户信息”,按照 【知识库】中的文件信息,生成的sql应该是 “select  *  from  sys_user”等sql,但现在情况是,生成的sql中的表信息,与我配置的知识库中的信息不一致,问题出在哪里,虚心请教,感谢!!!!

### DIFY Agent Database Configuration and Management For configuring and managing the database related to a DIFY agent, understanding how such an AI-driven tool interacts with databases is essential. An effective method involves setting up configurations that allow seamless communication between the application (in this case, potentially something similar to what's described in GitHub repositories like CodePhiliaX/Chat2DB[^1]) and various types of relational or non-relational databases. #### Setting Up Environment Variables Configuration often starts by defining environment variables specific to your project needs. These settings typically include connection strings which specify details about accessing different kinds of databases supported by tools mentioned previously, including MySQL, Oracle, PostgreSQL among others. ```bash export DATABASE_URL="postgresql://username:password@localhost:5432/mydatabase" ``` This line sets `DATABASE_URL` as an example for connecting to a PostgreSQL instance using credentials provided within the string itself. #### Connecting Through Application Settings Beyond just establishing connections via URLs, applications may require additional parameters configured through files such as JSON or YAML formats depending on their architecture design choices made during development phases. For projects inspired by frameworks discussed around advanced clients supporting multiple RDBMS systems, these might look somewhat alike: ```yaml db: host: localhost port: 5432 name: mydatabase user: username password: password ``` Such snippets define where exactly one wishes to establish contact points towards backend storage solutions while also specifying authentication mechanisms necessary when interfacing directly against those services. #### Managing Schema Migrations Maintaining schema consistency across deployments can be achieved through migration scripts written either manually or generated automatically based upon changes detected within models defined inside codebases associated closely alongside any given API endpoint responsible for handling requests coming from agents interacting over networks securely encrypted at all times according to best practices outlined elsewhere but relevant here due to implications surrounding data integrity concerns whenever dealing extensively with external storages outside immediate control boundaries set forth initially before starting implementation efforts aimed specifically toward achieving interoperability goals established early stages planning sessions involving stakeholders who have vested interests ensuring successful outcomes derived therefrom.
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王大锤4391

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值