admin管理员组文章数量:1667065
文章目录
- 一、项目简介:
- 二、代码结构:
- 三、具体代码:
- main.py
- templates/index.html
- static/css/custom.css
- static/js/custom.js
- 四、使用方法:
- 1. 安装依赖:
- 2. 在main.py中替换自己的openai_key
- 3. 运行项目:
- 4. 打开浏览器,访问 http://localhost:8000 以查看聊天界面。
- 五、完善建议:
- 六、[代码在这里](https://download.csdn/download/fengtaokelly/87755940)
一、项目简介:
本项目是一个简易的聊天应用,基于Sanic Web框架搭建后端,使用Bootstrap 3和JavaScript搭建前端,通过调用ChatGPT API实现智能对话。项目包含一个简单的Token认证,以及一些页面的简单美化处理。
非常之简易,只有150行左右的代码(还包括很多空行)。前提是你得有openai的api_key,而且不建议在墙内搭建。
二、代码结构:
├── main.py
├── templates
│ └── index.html
└── static
├── css
│ └── custom.css
└── js
└── custom.js
三、具体代码:
main.py
from sanic import Sanic
from sanic.response import json, text, html
from sanic.log import logger
from sanic.exceptions import Unauthorized
import openai
app = Sanic(__name__)
app.static('/static', './static')
openai.api_key = 'your_openai_key'
VALID_TOKEN = '2RTjaZSfgzLHW3in'
@app.middleware('request')
async def check_token(request):
if request.path == '/api/chat':
token = request.headers.get('Authorization', '').split(' ')[-1]
if token != VALID_TOKEN:
raise Unauthorized('Invalid token')
@app.get("/")
async def index(request):
with open('templates/index.html', 'r', encoding='utf-8') as file:
return html(file.read())
@app.post('/api/chat')
async def api_chat_handler(request):
chat_history = request.json.get('message', [])
if not chat_history:
return json({'error': 'Message cannot be empty'}, status=400)
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
temperature=0.7,
messages=chat_history
)
logger.info(response)
reply = response['choices'][0]['message']['content'].strip()
return json({'reply': reply})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000, dev=True)
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ChatGPT</title>
<!-- 引入Bootstrap3 -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- 引入markdown-it库 -->
<script src="https://cdn.jsdelivr/npm/markdown-it/dist/markdown-it.min.js"></script>
<!-- 引入自定义的CSS和JS文件 -->
<link rel="stylesheet" href="/static/css/custom.css">
<script src="/static/js/custom.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1 class="text-center">EasyChatGPT</h1>
<div id="chat-container" class="well">
<!-- 聊天消息将显示在这里 -->
</div>
<form id="chat-form">
<div class="form-group">
<label for="token-input">Token:</label>
<input type="text" id="token-input" class="form-control" placeholder="Enter your token here..." value="2RTjaZSfgzLHW3in">
</div>
<div class="input-group">
<input type="text" id="user-input" class="form-control" placeholder="Type your message here...">
<span class="input-group-btn">
<button id="send-btn" class="btn btn-primary" type="submit">Send</button>
</span>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
static/css/custom.css
body {
font-family: Arial, sans-serif;
margin-top: 50px;
}
#chat-container {
height: 400px;
overflow-y: auto;
border: 1px solid #ccc;
border-radius: 4px;
padding: 10px;
background-color: #f8f8f8;
}
.alert {
padding: 10px;
margin-bottom: 10px;
border-radius: 4px;
}
.alert-info {
background-color: #d9edf7;
border-color: #bce8f1;
color: #31708f;
}
.alert-warning {
background-color: #fcf8e3;
border-color: #faebcc;
color: #8a6d3b;
}
.input-group {
margin-top: 20px;
}
static/js/custom.js
const chatHistory = [
{role: 'system', content: '您现在是一位乐于助人的助手。'}
];
// 初始化markdown-it库
const md = window.markdownit();
$(document).ready(function () {
document.getElementById('chat-form').addEventListener('submit', async (event) => {
event.preventDefault();
const userInput = document.getElementById('user-input');
const tokenInput = document.getElementById('token-input');
const message = userInput.value.trim();
if (!message) return;
// 显示用户发送的消息
displayMessage('user', message);
// 清空输入框
userInput.value = '';
// 调用后端API获取ChatGPT的回复
const response = await fetch('/api/chat', {
method: 'POST',
headers: {'Content-Type': 'application/json', 'Authorization': `Bearer ${tokenInput.value}`},
body: JSON.stringify({message: chatHistory})
});
if (response.ok) {
const data = await response.json();
displayMessage('assistant', data.reply);
} else {
displayMessage('error', JSON.stringify(await response.json()));
}
});
});
function displayMessage(type, message) {
// 将新的消息添加到聊天记录
chatHistory.push({role: type, content: message});
console.log(chatHistory)
const chatContainer = document.getElementById('chat-container');
const messageDiv = document.createElement('div');
messageDiv.className = type === 'user' ? 'alert alert-info' : 'alert alert-warning';
// 如果消息来自助手,将Markdown转换为HTML
if (type === 'assistant') {
message = md.render(message);
}
// 将消息内容设置为messageDiv的innerHTML
messageDiv.innerHTML = message;
chatContainer.appendChild(messageDiv);
chatContainer.scrollTop = chatContainer.scrollHeight;
}
四、使用方法:
1. 安装依赖:
pip install -r requirements.txt
2. 在main.py中替换自己的openai_key
3. 运行项目:
python main.py
4. 打开浏览器,访问 http://localhost:8000 以查看聊天界面。
五、完善建议:
接口很慢,所以下一步准备先实现流式响应。之后可以考虑以下的建议来完善和提高聊天应用的功能和用户体验:
-
用户鉴权和注册:为了提高安全性,可以添加用户注册和登录功能。
-
持久化聊天历史记录:将用户的聊天历史记录保存在数据库中,如 SQLite、PostgreSQL 或 MongoDB。这样用户在不同设备上登录时,可以查看之前的聊天记录。
六、代码在这里
https://download.csdn/download/fengtaokelly/87755940
版权声明:本文标题:基于Sanic(Python)和ChatGPT的超级简易聊天应用 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dongtai/1730084427a1222173.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论