赞
踩
数据库记录:
流式输出就不展示了
前往阿里云大模型服务平台使用自己账号开通大模型服务平台百炼
地址:大模型服务平台_通义大模型_自然语言处理_达摩院-阿里云 (aliyun.com)
一般是有免费额度可以使用的 后期可以自己买额度 很便宜
然后到我的应用 创建好自己的应用 选择相应的模型 这时我们就哟APIkey和 自己的appid了
创建一个Python Flask项目并创建好虚拟环境解释器使用python3.8 项目结构如下图所示
key.py及其下方文件为我个人测试部署时使用 可以忽略
运行项目的文件 也就是后端
- # -*- coding: utf-8 -*-
- from flask import Flask, request, jsonify, Response, render_template, session
- from flask_session import Session
- from dashscope import Generation
- from http import HTTPStatus
- from flask_cors import CORS
- import redis
- import json
- from database import save_conversation
-
- app = Flask(__name__)
- CORS(app)
- #可以自己生成一串
- app.secret_key = '3ddd8f0da764cb34850e1da48d03da24'
-
- # 配置 Redis
- app.config['SESSION_TYPE'] = 'redis'
- app.config['SESSION_REDIS'] = redis.Redis(host='localhost', port=6379)
- app.config['SESSION_PERMANENT'] = False
- app.config['SESSION_USE_SIGNER'] = True
- Session(app)
-
- @app.route('/ChatView')
- def index():
- return render_template('index.html')
-
- @app.route('/chat', methods=['POST'])
- def chat():
- user_message = request.json.get('message', '')
-
- if not user_message:
- return jsonify({'error': '未提供消息'}), HTTPStatus.BAD_REQUEST
-
- # 从会话中加载消息或初始化一个新列表 可以自己自定义角色 修改'你是一个ai助手'内容就行
- messages = session.get('messages', [{'role': 'system', 'content': '你是一个ai助手'}])
-
- # 将用户的消息添加到列表中
- messages.append({'role': 'user', 'content': user_message})
- session['messages'] = messages # 在添加用户消息后立即保存
-
- def generate():
- responses = Generation.call(
- "qwen-max",
- app_id='自己的应用id',
- api_key='自己的api key',
- messages=messages,
- result_format='message',
- stream=True,
- incremental_output=True
- )
- buffer = ''
- for response in responses:
- if response.status_code == HTTPStatus.OK:
- content = response.output.choices[0]['message']['content'].strip()
- print(content)
- buffer += content
- yield f"{content}"
- else:
- yield f"Error: {response.message}\n\n"
- break
-
- return Response(generate(), mimetype='text/event-stream')
-
- @app.route('/update', methods=['POST'])
- def update():
- try:
- data = request.json
- bot_message = data.get('bot_message', '')
- user_message = data.get('user_message', '')
- conversation_id = data.get('conversation_id', '')
-
- if not bot_message or not user_message or not conversation_id:
- app.logger.error('Missing bot_message, user_message, or conversation_id')
- return jsonify({'error': '未提供消息或对话ID'}), HTTPStatus.BAD_REQUEST
-
- messages = session.get('messages', [])
- messages.append({'role': 'assistant', 'content': bot_message})
- session['messages'] = messages
-
- save_conversation(conversation_id, user_message, bot_message) # 保存对话
-
- return jsonify({'status': 'updated'}), HTTPStatus.OK
- except Exception as e:
- app.logger.error(f"Error in /update: {str(e)}")
- return jsonify({'error': str(e)}), HTTPStatus.INTERNAL_SERVER_ERROR
-
- @app.route('/clear', methods=['POST'])
- def clear():
- session.pop('messages', None)
- return jsonify({'status': 'cleared'}), HTTPStatus.OK
-
- if __name__ == '__main__':
- app.run(debug=True)
- # 这里是自定义本地运行的端口号和ip地址
- # app.run(host='0.0.0.0', port=8080, debug=True)
-
-
指向数据库操作 保存记录的后端文件 需要修改为自己的数据库账户和密码
- # -*- coding: utf-8 -*-
- import mysql.connector
-
- def get_db_connection():
- return mysql.connector.connect(
- host="localhost",
- user="用户名",
- password="密码",
- database="数据库名"
- )
-
- def save_conversation(conversation_id, user_message, bot_message):
- try:
- connection = get_db_connection()
- cursor = connection.cursor()
-
- # 检查对话是否存在
- conversation_query = "SELECT 1 FROM conversations WHERE conversation_id = %s"
- cursor.execute(conversation_query, (conversation_id,))
- conversation_exists = cursor.fetchone()
-
- if not conversation_exists:
- # 插入对话记录
- conversation_query = """
- INSERT INTO conversations (conversation_id)
- VALUES (%s)
- """
- cursor.execute(conversation_query, (conversation_id,))
-
- # 插入聊天记录
- chat_record_query = """
- INSERT INTO chat_records (conversation_id, user_message, bot_message)
- VALUES (%s, %s, %s)
- """
- cursor.execute(chat_record_query, (conversation_id, user_message, bot_message))
-
- connection.commit()
- except mysql.connector.Error as err:
- print(f"Error: {err}")
- raise
- finally:
- if connection.is_connected():
- cursor.close()
- connection.close()
数据库结构 sql语句
- SET NAMES utf8mb4;
- SET FOREIGN_KEY_CHECKS = 0;
-
- -- ----------------------------
- -- Table structure for chat_records
- -- ----------------------------
- DROP TABLE IF EXISTS `chat_records`;
- CREATE TABLE `chat_records` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `conversation_id` varchar(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
- `user_message` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL,
- `bot_message` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL,
- PRIMARY KEY (`id`) USING BTREE,
- INDEX `conversation_id`(`conversation_id`) USING BTREE,
- CONSTRAINT `chat_records_ibfk_1` FOREIGN KEY (`conversation_id`) REFERENCES `conversations` (`conversation_id`) ON DELETE CASCADE ON UPDATE CASCADE
- ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-
- -- ----------------------------
- -- Table structure for conversations
- -- ----------------------------
- DROP TABLE IF EXISTS `conversations`;
- CREATE TABLE `conversations` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `conversation_id` varchar(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
- `conversation_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY (`id`) USING BTREE,
- INDEX `conversation_id`(`conversation_id`) USING BTREE
- ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-
- SET FOREIGN_KEY_CHECKS = 1;
头像图片可以自定义 修改就行
- <!DOCTYPE html>
- <html lang="zh-CN">
- <head>
- <meta charset="UTF-8"/>
- <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1.0"/>
- <title>顶顶顶顶顶</title>
- <script src="https://cdn.tailwindcss.com"></script>
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/styles/github-dark.min.css"/>
- <script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/highlight.min.js"></script>
- <script src="https://cdn.jsdelivr.net/npm/highlightjs-line-numbers.js@2.8.0/dist/highlightjs-line-numbers.min.js"></script>
- <script src="https://cdn.jsdelivr.net/npm/clipboard@2.0.11/dist/clipboard.min.js"></script>
- <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css"/>
- <link rel="stylesheet" href="/static/css/style.css" />
- <link rel="icon" href="/static/images/favicon.ico" type="image/x-icon">
- </head>
- <body class="bg-blue-200 font-sans leading-normal tracking-normal">
- <div class="loader" id="loader">
- <div class="loader-text">Loading...</div>
- <h2>正在加载...请稍候</h2>
- <div class="loader-bar"></div>
- </div>
- <div class="w-full h-full sm:container sm:mx-auto sm:my-8 sm:p-4 bg-white dark:bg-zinc-800 shadow-md rounded-lg sm:overflow-hidden max-w-4xl">
- <div class="flex flex-col h-[100vh] sm:h-[80vh] md:h-[85vh]">
- <div class="px-4 py-3 border-b dark:border-zinc-700">
- <div class="flex justify-between items-center">
- <h1 class="text-2xl font-semibold text-zinc-800 dark:text-white">声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/在线问答5/article/detail/871626推荐阅读
相关标签
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。