基于Sanic(Python)和ChatGPT的超级简易聊天应用


一、项目简介:

本项目是一个简易的聊天应用,基于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.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <!-- 引入markdown-it库 -->
    <script src="https://cdn.jsdelivr.net/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 以查看聊天界面。

五、完善建议:

接口很慢,所以下一步准备先实现流式响应。之后可以考虑以下的建议来完善和提高聊天应用的功能和用户体验:

  1. 用户鉴权和注册:为了提高安全性,可以添加用户注册和登录功能。

  2. 持久化聊天历史记录:将用户的聊天历史记录保存在数据库中,如 SQLite、PostgreSQL 或 MongoDB。这样用户在不同设备上登录时,可以查看之前的聊天记录。

六、代码在这里

https://download.csdn.net/download/fengtaokelly/87755940

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
这个包不完整,到这里可下载完整的文档,程序代码,数据库脚本等http://download.csdn.net/source/1140485 一个用于Web游戏中的即时聊天代码 使用内存进行消息投递 支持私聊和供聊 支持统计在线人数 可开多个房间 注意:有人反映这个不能直接使用,在这里特做一下说明 =============================================== 这个程序是从游戏中拿出来的,并不是一个独立的应用程序 发上去的部分是不能直接运行的,发出来的目的只是想给有这方面兴趣的朋友做个参考,因为我自己才做这块的时候确实走了不少弯路 里面有类设计图,类设计图是用powerdesign 12.5设计的 可以通过类设计图看服务端的设计 客户端是一个demo html文件 要运行还需要配数据库,还需要微软的企业库开发包 不了解企业库的可以去这里看看 http://www.codeplex.com/entlib 你也可以修改一下代码让程序不需要访问数据库 访问数据库主要是加载房间信息,你可以在代码里弄几个模拟的房间信息 聊天消息的中专是不依赖数据库的 ====================================== 再次补充说明 这个代码的开发环境为:vs2008+sqlserver2005+微软企业库+net fwk3.5 其实用vs2005+2.0框架也可以,虽然使用的是3.5的框架,但是并没有使用3.5框架的新特性 经检查发现里面确实没有类设计图,也没有服务器端的源代码 现在传上去的这部分只是一个demo,包含客户端和编译过的服务器端代码 非常的抱歉,我将不上源代码和相关设计文件 =========================================================== 目录结构说明 ChatDemo-包含客户端和编译过的服务器端 ChatDemo/ChatDemo.HttpHandler-客户端http处理器(客户端和服务器端的交互就靠这些文件了) ChatDemo/ChatWebDemo-客户端的实现代码 ChatDemo/ChatWebDemo/ServerManager.aspx-此文件可控制服务器的启动和关闭(客户端和服务器端是存在于同一台电脑上测试的,所以在一个工程里) ChatDemo/ChatWebDemo/SelectChatRoom.aspx-可选择进入哪一个聊天ChatDemo/ChatWebDemo/Chat.aspx-聊天客户端界面 DinosaurEmpery-包含服务器端的源代码和相关设计文档-数据库文档等 DinosaurEmpery/src-服务端源代码 DinosaurEmpery/using-程序中用引用到到第3方dll(微软企业库)

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

搬码侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值