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

数据库 网页 和 deepseek 并在一起,直接选择问题,


flask_app/                  # 项目根目录

├── app.py                  # Flask 主程序
├── templates/              # 存放 HTML 模板文件
│   └── index.html          # 前端页面
├── static/                 # 存放静态文件
│   └── script.js           # JavaScript 文件
└── requirements.txt        # 项目依赖文件


requirements.txt


PyMySQL~=1.1.1
flask~=3.1.0
openai~=1.65.4



$(document).ready(function() {
    // 加载系统列表
    $.get('/get_systems', function(data) {
        data.forEach(function(system) {
            // 检查是否已经存在相同的选项
            if (!$('#system-select option[value="' + system.id + '"]').length) {
                $('#system-select').append(`<option value="${system.id}">${system.systm}</option>`);
            }
        });
    });

    // 当选择系统时,加载对应的用户内容
    $('#system-select').change(function() {
        const systemId = $(this).val();
        $('#user-select').empty().append('<option value="">--Select a User Content--</option>');
        if (systemId) {
            $.get(`/get_users/${systemId}`, function(data) {
                data.forEach(function(user) {
                    // 检查是否已经存在相同的选项
                    if (!$('#user-select option[value="' + user.content + '"]').length) {
                        $('#user-select').append(`<option value="${user.content}">${user.content}</option>`);
                    }
                });
            });
        }
    });

    // 当选择用户内容时,将其放入文本框
    $('#user-select').change(function() {
        const userContent = $(this).val();
        $('#message-box').val(userContent);
    });

    // 发送消息到 DeepSeek
    $('#send-button').click(function() {
        const systemId = $('#system-select').val();
        const userMessage = $('#message-box').val();

        if (!systemId || !userMessage) {
            alert('请选择系统和输入消息内容!');
            return;
        }

        // 清空响应区域
        $('#response-text').text('');

        $.ajax({
            url: '/ask_deepseek',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
                system_id: systemId,
                user_message: userMessage
            }),
            success: function(data) {
                const htmlContent = marked.parse(data.response);
                $('#response-text').text(htmlContent);
                document.getElementById('response-text').innerHTML = htmlContent;
            },
            error: function(xhr, status, error) {
                console.error('Error:', error);
                alert('请求失败,请稍后重试!');
            }
        });
    });
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask App</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <script src="{{ url_for('static', filename='script.js') }}"></script>


</head>
<body>
    <h1>准备咨询的内容:</h1>

    <label for="system-select">选择大类:</label>
    <select id="system-select">
        <option value="">--请选择--</option>
    </select>
    <br>
    <br>
    <label for="user-select">选择细节:</label>
    <select id="user-select" multiple size="10">
        <option value="">--请选择--</option>
    </select>
    <br>
    <br>
    <textarea id="message-box"  rows = 10,  placeholder="在这里输入您的信息..."></textarea>
    <button id="send-button">Send</button>

    <div id="response-area" width ="80%">
        <h2>反馈[请稍等]:</h2>
        <div id="response-text"> </div>


    </div>

    <script src="{{ url_for('static', filename='script.js') }}"></script>
</body>
</html>
from flask import Flask, render_template, request, jsonify
import pymysql
from openai import OpenAI

app = Flask(__name__)

# MySQL数据库配置
DB_CONFIG = {
    'host': 'mysql.sqlpub.com',
    'port': 3306,
    'user': 'laocooon',
    'password': 'fc12f7a5215e8e0a',  # 替换为你的密码
    'database': 'huangjin',
    'cursorclass': pymysql.cursors.DictCursor  # 返回字典格式的结果
}


def get_db_connection():
    return pymysql.connect(**DB_CONFIG)


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/get_systems')
def get_systems():
    conn = get_db_connection()
    try:
        with conn.cursor() as cursor:
            cursor.execute('SELECT id, systm FROM systm')
            systems = cursor.fetchall()
            # print(systems)
            return jsonify(systems)
    finally:
        conn.close()


@app.route('/get_users/<int:system_id>')
def get_users(system_id):
    conn = get_db_connection()
    try:
        with conn.cursor() as cursor:
            cursor.execute('SELECT id, content FROM user WHERE systemid = %s', (system_id,))
            users = cursor.fetchall()
            return jsonify(users)
    finally:
        conn.close()


@app.route('/ask_deepseek', methods=['POST'])
def ask_deepseek():
    # print(request.json)
    system_id = request.json.get('system_id')
    user_message = request.json.get('user_message')

    conn = get_db_connection()
    try:
        with conn.cursor() as cursor:
            cursor.execute('SELECT systm FROM systm where id = %s', (system_id,))
            systems = cursor.fetchall()
            system_name = systems[0]['systm']
    finally:
        conn.close()


    # 这里调用DeepSeek的API
    # 假设你有一个函数 `call_deepseek_api(system_name, user_message)` 来处理API调用
    response = call_deepseek_api(system_id, user_message)

    # 假设response是DeepSeek的API返回的结果
    # print(response)
    return jsonify({'response': response})


def call_deepseek_api(system_name, user_message):
    # 这里是调用DeepSeek API的逻辑
    # 你需要根据DeepSeek的API文档来实现
    # 这里只是一个示例

    client = OpenAI(api_key="sk-382a17fc1a914b4e804332c46a41ba46", base_url="https://api.deepseek.com")

    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {"role": "system", "content": system_name},
            {"role": "user", "content": user_message},
        ],
        stream=False
    )

    return response.choices[0].message.content


if __name__ == '__main__':
    # print(get_systems())
    app.run(debug=True)

相关文章:

  • nginx服务器实现上传文件功能_使用nginx-upload-module模块
  • STM32点亮LED灯
  • 利用 HAI 平台进行 DeepSeek 模型训练的详细指南
  • 梯度本质论:从黎曼流形到神经网络的拓扑寻优
  • 最近很火的通用人工智能Manus复现链接
  • 在NVIDIA RTX 4090显卡上部署阿里千问QwQ-32B-AWQ模型教程
  • PTA 7-8 哈利·波特的考试
  • SpringBoot - 用责任链模式实现业务编排
  • 工具介绍《githack》以及Git 命令行
  • Sora模型的技术原理与应用:开创多模态学习新局面
  • Nginx解决前端跨域问题
  • 2025/03/07训练
  • 现代密码学体系架构设计原则与实践:基于Python的实现与GPU加速GUI演示
  • 虚拟系统配置
  • react中的fiber和初次渲染
  • 揭开AI-OPS 的神秘面纱 第二讲-技术架构与选型分析 -- 数据采集层技术架构与组件选型分析
  • Seata
  • 从 Faith 与 Belief 的语义与语境辨析中解析其宗教哲学内涵
  • PyTorch中的损失函数:F.nll_loss 与 nn.CrossEntropyLoss
  • react拖曳组件react-dnd的简单封装使用
  • 湖北响应式网站建设设计/免费学生网页制作成品
  • 网站做支付链接安全吗/深圳今天重大事件新闻
  • p2p 金融网站开发/百度提交网站
  • 一个公司做网站需要注意什么/seo模拟点击工具
  • 沈阳微信网站开发/网站排名
  • 徐州建站推广/seo顾问什么职位