当前位置: 首页 > news >正文

本地部署 MySQL + Qwen3-1.5B + Flask + Dify 工作流

一、 本地部署Dify

 注意:v100显卡会出现不适配,不推荐使用

 1. 安装 Docker

ubuntu 22.04 docker 安装&使用_ubuntu22.04 安装docker-CSDN博客

 2. 安装vllm

pip install -U xformers torch torchvision torchaudio triton --index-url https://download.pytorch.org/whl/cu121
pip install modelscope vllm 

3. 下载Qwen开源模型

#模型下载
from modelscope import snapshot_download
model_dir = snapshot_download('Qwen/Qwen2.5-0.5B-Instruct')

4. 部署Dify到本地

git clone https://github.com/langgenius/dify

启动 Dify

  1. 进入 Dify 源代码的 Docker 目录

    cd dify/docker
    
  2. 复制环境配置文件

    cp .env.example .env
    

修改端口:

如果使用云服务器请先确认暴露端口

以闪电云为例:

sudo apt install rinetd
echo "0.0.0.0 8880 127.0.0.1 9000" > /etc/rinetd.conf
sudo systemctl restart rinetd

更新 Dify

进入 dify 源代码的 docker 目录,按顺序执行以下命令:

cd dify/docker
docker compose down
git pull origin main
docker compose pull
docker compose up -d

访问 Dify

你可以先前往管理员初始化页面设置设置管理员账户:

# 本地环境
http://localhost/install# 服务器环境
http://your_server_ip/install

Dify 主页面:

# 本地环境
http://localhost# 服务器环境
http://your_server_ip

 5. 启动 vLLM 的 OpenAI 兼容服务

启动vllm服务 

命令行输入 vllm serve Qwen/Qwen2.5-1.5B-Instruct --port 9999 --dtype float16

# 使用绝对路径
vllm serve /root/.cache/modelscope/hub/models/Qwen/Qwen2.5-0.5B-Instruct --port 8000 --dtype float16

二、 安装MySQL和PyMySQL

安装MySQL

# 在Ubuntu/Debian上安装
sudo apt update
sudo apt install mysql-server
sudo mysql_secure_installation# 启动MySQL服务
sudo systemctl start mysql
sudo systemctl enable mysql

安装PyMySQL

pip install pymysql

使用 apt 安装 MySQL 后,默认情况下 root 用户没有密码,但需要通过 sudo 权限访问。

如果希望设置密码(推荐)

使用 mysql_secure_installation

运行以下命令交互式设置密码:

sudo mysql_secure_installation

按照提示:

  1. 选择密码强度验证策略(通常选 0 跳过)

  2. 输入新密码并确认

  3. 后续选项建议全部选 Y(移除匿名用户、禁止远程 root 登录等)

用 sudo 登录 MySQL

sudo mysql -u root

检查 MySQL 用户认证方式

登录 MySQL 后,执行:

SELECT user, host, plugin FROM mysql.user WHERE user='root';

修改 root 用户认证方式为密码 

假设你已经用 sudo mysql 进入了 MySQL,执行:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '12345678';
FLUSH PRIVILEGES;

创建数据库和表 

import pymysql# 替换为你的MySQL root密码
MYSQL_PASSWORD = 'your_root_password'connection = pymysql.connect(host='localhost',user='root',password='12345678'
)try:with connection.cursor() as cursor:# 创建数据库cursor.execute("CREATE DATABASE IF NOT EXISTS qwen_demo")cursor.execute("USE qwen_demo")# 创建产品表cursor.execute("""CREATE TABLE IF NOT EXISTS products (id INT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(100),category VARCHAR(50),price DECIMAL(10,2),stock INT)""")# 插入示例数据cursor.execute("""INSERT INTO products (name, category, price, stock)VALUES ('笔记本电脑', '电子产品', 5999.00, 50),('智能手机', '电子产品', 3999.00, 100),('平板电脑', '电子产品', 2999.00, 30),('办公椅', '家具', 899.00, 20),('书桌', '家具', 1299.00, 15)""")connection.commit()print("数据库和表创建成功,示例数据已插入!")
finally:connection.close()

三、构建text2SQL

# qwen_sql.py
from transformers import AutoModelForCausalLM, AutoTokenizermodel = AutoModelForCausalLM.from_pretrained("/root/.cache/modelscope/hub/models/Qwen/Qwen2.5-1.5B-Instruct", device_map="auto")
tokenizer = AutoTokenizer.from_pretrained("/root/.cache/modelscope/hub/models/Qwen/Qwen2.5-1.5B-Instruct")def generate_sql(query):prompt = f"""将中文转换为SQL查询。只返回SQL语句,不要有其他解释或说明。数据库表结构:表名:products字段:id, name, category, price, stock问题:{query}SQL:"""inputs = tokenizer(prompt, return_tensors="pt").to(model.device)outputs = model.generate(**inputs, max_new_tokens=300)# 先解码模型输出output_text = tokenizer.decode(outputs[0], skip_special_tokens=True)# print("模型输出:", output_text)  # 可调试用# 提取SQL部分if "SQL:" in output_text:sql = output_text.split("SQL:")[-1].strip()else:sql = output_text.strip()return sql

四、 启动FlakAPI

# api.py
from flask import Flask, request, jsonify
import pymysql
from qwen_sql import generate_sqlapp = Flask(__name__)@app.route('/sql', methods=['POST'])
def handle_sql():user_query = request.json['query']try:sql = generate_sql(user_query)conn = pymysql.connect(host='localhost', user='root', password='12345678', database='qwen_demo')with conn.cursor(pymysql.cursors.DictCursor) as cursor:cursor.execute(sql)result = cursor.fetchall()return jsonify({"sql": sql, "data": str(result)})except Exception as e:return jsonify({"error": str(e)}), 500if __name__ == '__main__':app.run(host='0.0.0.0', port=8000)

测试代码:

import requestsurl = "http://192.168.122.200:8000/sql"
data = {"query": "价格大于1000的产品"  # 这里可以换成你想测试的自然语言问题
}response = requests.post(url, json=data)
print("Status Code:", response.status_code)
print("Response:", response.json())

 

五、 Dify工作流

 

执行代码节点代码如下:

import requests
import jsondef main(user_query):# 配置API端点api_url = "http://192.168.122.200:8000/sql"#api_url = "http://host.docker.internal:8000/sql"# 1. 发送请求到SQL转换服务response = requests.post(api_url,json={"query": user_query},timeout=30  # 建议超时设置为30秒)result = response.json()# 5. 标准化输出格式(匹配Dify结束节点模板)return  {"result": result["data"]}

相关文章:

  • 动态规划-91.解码方法-力扣(LeetCode)
  • SPSS系统发育分析中的聚类相关part
  • 端口安全讲解
  • 《Python星球日记》 第44天: 线性回归与逻辑回归
  • 轻松管理房间预约——启辰智慧预约小程序端使用教程
  • 【图书管理系统】详细讲解用户登录:后端代码实现及讲解、前端代码讲解
  • feign负载均衡
  • 4.系统定时器基本定时器
  • 当“信任”遇上“安全”:如何用Curtain Logtrace记录文件操作活动 守护团队与数据的双重底线?
  • 从Huggingface下载模型的方法小结
  • 如何从路由表优化的角度理解[CIDR]无类别域间路由选择技术?
  • 针对Mkdocs部署到Githubpages加速访问速度的一些心得
  • 2021年下半年试题四:论微服务架构及其应用
  • Spring AI 之 AI核心概念
  • 2025年渗透测试面试题总结-渗透岗位全职工作面试(附回答)(题目+回答)
  • SWiRL:数据合成、多步推理与工具使用
  • 前端代码规范详细配置
  • QT:qt5调用打开exe程序并获取调用按钮控件实例2025.5.7
  • 2025年高校辅导员考试高频考点有哪些?
  • qsort函数
  • 婚姻登记“全国通办”首日观察:数据多跑路,群众少跑腿
  • 龙湖集团:今年前4个月销售220.8亿元,4月新增两块土地储备
  • 读图|展现城市品格,上海城市影像走进南美
  • 眉山“笑气”迷局:草莓熊瓶背后的隐秘与危机
  • 首批证券公司科创债来了!拟发行规模超160亿元
  • 追光|铁皮房、土操场,这有一座“筑梦”摔跤馆