Flask+GPT-3.5 Turbo聊天应用无响应问题求助及代码修复
问题修复方案
后端(app.py)问题及修复:
- Flask初始化错误:
app = Flask(name)需改为app = Flask(__name__),缺少双下划线会导致Flask无法正确识别应用路径。 - 函数缩进错误:Python是缩进敏感语言,
index()和api()函数内的代码必须严格缩进。 - 请求参数不匹配:前端发送的是表单格式数据,后端用
request.json.get("message")无法获取,需改为request.form.get("message")。 - 返回值错误:
completion.choices[0].message是包含role和content的字典,直接返回会序列化失败,应返回content字段。 - 主函数判断错误:
if name=='main':需改为if __name__ == '__main__':,缺少双下划线会导致启动逻辑失效。 - 缺少异常处理:OpenAI API调用可能因网络、配额等出错,添加异常捕获避免服务崩溃。
前端(index.html)问题及修复:
- 发送消息后未清空输入框:添加
$("#message").val("")提升用户体验。 - 空消息拦截:增加输入内容判断,避免发送空消息。
修复后的app.py代码:
from flask import Flask, render_template, request import openai app = Flask(__name__) openai.api_key = 'MY VALID API KEY' @app.route("/") def index(): return render_template("index.html") @app.route("/api", methods=["POST"]) def api(): message = request.form.get("message") if not message: return "请输入消息内容" try: completion = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "user", "content": message} ] ) return completion.choices[0].message['content'] except Exception as e: return f"生成响应失败: {str(e)}" if __name__ == '__main__': app.run(debug=True) # 开启debug模式便于调试
修复后的index.html代码:
<!DOCTYPE html> <html> <head> <title>Chat App</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.7.2/animate.min.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <style> body { background-color: #f5f5f5; padding-top: 20px; } #chat-box { max-width: 800px; margin: auto; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } #chat-header { background-color: #f8f9fa; border-bottom: 1px solid #e9ecef; padding: 10px; font-weight: bold; text-align: center; } #message-list { height: 400px; overflow-y: scroll; padding: 10px; } .user-message { background-color: #ffc107; color: white; margin-bottom: 10px; padding: 10px; border-radius: 10px; text-align: right; } .bot-message { background-color: #007bff; color: white; margin-bottom: 10px; padding: 10px; border-radius: 10px; text-align: left; } input[type="text"] { width: 100%; border: none; border-top: 1px solid #e9ecef; padding: 10px; font-size: 16px; outline: none; } input[type="text"]:focus { border-color: #007bff; box-shadow: 0 0 10px rgba(0, 123, 255, 0.5); } .btn-send { background-color: #007bff; color: white; border: none; padding: 10px 20px; margin-top: 10px; border-radius: 5px; } .btn-send:hover { background-color: #0069d9; cursor: pointer; } </style> </head> <body> <div id="chat-box" class="container"> <div id="chat-header">Chat App</div> <div id="message-list"></div> <form id="message-form" class="d-flex flex-column align-items-center"> <input type="text" id="message" placeholder="Type a message..."> <button type="submit" class="btn btn-send">Send</button> </form> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> <script> $(function() { $("#message-form").submit(function(e) { e.preventDefault(); var message = $("#message").val().trim(); if (!message) return; displayMessage(message, "user-message"); $("#message").val(""); // 清空输入框 $.ajax({ url: "/api", type: "POST", data: { message: message }, success: function(response) { displayMessage(response, "bot-message"); $("#message-list").animate({ scrollTop: $("#message-list")[0].scrollHeight }, 1000); }, error: function(error) { console.log("Error:", error); displayMessage("请求失败,请稍后重试", "bot-message"); } }); }); function displayMessage(message, className) { var messageElement = $("<div>").addClass(className).text(message); $("#message-list").append(messageElement); } }); </script> </body> </html>
内容的提问来源于stack exchange,提问作者Roderio
相关产品推荐
相关产品推荐

