基于flask 设计一个前端web 界面,将调用的得到大模型回复内容,可以实对话框模式
时间: 2025-07-06 20:52:47 浏览: 1
### 使用 Flask 构建 Web 应用程序并集成大模型 API
#### 创建 Flask 项目结构
为了构建一个能够与大型语言模型交互的应用,首先需要设置基本的 Flask 项目结构:
```plaintext
flask_app/
│
├── app.py # 主应用文件
├── templates/ # HTML模板目录
│ └── index.html # 前端页面模板
└── static/ # 静态资源(CSS, JS)
├── css/
│ └── styles.css # 自定义样式表
└── js/
└── script.js # JavaScript 文件处理前端逻辑
```
#### 后端开发:配置 Flask 路由和服务
在 `app.py` 中编写如下代码来启动服务器并向大模型发送请求获取回复。
```python
from flask import Flask, render_template, request, jsonify
import requests
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/get_response', methods=['POST'])
async def get_response():
user_input = request.json.get('message')
# 这里替换为实际的大规模预训练模型API地址
api_url = "https://api.example.com/v1/chat/completions"
headers = {"Authorization": "Bearer YOUR_API_KEY"}
data = {
'prompt': f'User: {user_input}\nAI:',
'max_tokens': 50,
'temperature': 0.7
}
response = requests.post(api_url, json=data, headers=headers).json()
ai_reply = response['choices'][0]['text'].strip()
return jsonify({'response': ai_reply})
if __name__ == '__main__':
app.run(debug=True)
```
此部分实现了两个主要的功能路由:一个是主页加载路径 `/` ,另一个则是用于接收从前端传来的消息并通过 POST 请求向外部 API 发送查询以获得回应的 `/get_response` 接口[^3]。
#### 前端设计:HTML 和 CSS 实现对话框效果
接下来是在 `templates/index.html` 定义网页布局,并利用简单的 CSS 来美化聊天窗口外观。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chat with Large Language Model</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
<script src="{{ url_for('static', filename='js/script.js') }}"></script>
</head>
<body>
<div id="chatbox">
<div class="messages"></div>
<input type="text" id="userInput"/>
<button onclick="sendMessage()">Send</button>
</div>
</body>
</html>
```
同时,在 `static/css/styles.css` 添加一些基础样式的定义让输入区域看起来更像真实的即时通讯工具。
```css
/* 对话框整体容器 */
#chatbox{
width: 400px;
margin:auto;
}
.messages{
border:1px solid black;
height:300px;
overflow-y:scroll;
padding:1em;
}
```
最后,在 `static/js/script.js` 编写 AJAX 函数负责监听用户的键盘事件并将新消息提交给后端处理器。
```javascript
function sendMessage(){
const userInputField = document.getElementById('userInput');
let messageText = userInputField.value.trim();
if (!messageText) return;
fetch("/get_response", {
method:"POST",
body:JSON.stringify({message:messageText}),
headers:{
"Content-Type":"application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(data =>{
displayMessage(`You: ${messageText}`);
displayMessage(`Bot: ${data.response}`);
// 清除输入框内容
userInputField.value='';
});
function displayMessage(msg){
var messagesDiv=document.querySelector('.messages');
var newMsgElement=document.createElement('p');
newMsgElement.textContent=msg;
messagesDiv.appendChild(newMsgElement);
messagesDiv.scrollTop=messagesDiv.scrollHeight;
}
}
```
上述代码片段展示了如何使用 Flask 搭配静态文件夹内的 HTML/CSS/JavaScript 来创建一个简易版的人机对话界面。当用户点击按钮或按下回车键时,会触发 JavaScript 方法将文本传递到 Python 后端进行处理,再经由 RESTful API 获取来自远程服务的回答并呈现在屏幕上[^3]。
阅读全文
相关推荐
















