仿chatgpt简约前后端

该文章面向小白非常友好,原生html+css+js,后端采用flask

而且借用了开源项目的api接口,不必在去chatgpt买自己的接口(又省一笔,这不得来个点赞收藏加关注)

该文章前端借鉴【ChatGPT】原生JS实现ChatGPT小型Demo

效果图

部署前端

<html>

<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <title>Chat GPT客服</title>
</head>

<body>
    <div class="rightSide">
        <div class="header">
            <div class="imgText">
                <div class="userimg">
                    <img src="https://image.51uhj.com/wx/676e4ff60ad46337f9b39d8757766bf581b9b89f5927b1bdf4766a456efdd3d3.png"
                        class="cover">
                </div>
                <h4>梯梯助手Chat GPT客服<br><span>在线</span></h4>
            </div>
        </div>
        <!--chatbox-->
        <div id="chatBox" class="chatBox">
            <div class="message frnd_message">
                <p>欢迎使用梯梯助手Chat GPT客服,有什么问题都可以问我。</span><br><span id="time"></span> </p>
            </div>
        </div>

        <!--chat input-->
        <div class="chatbox_input">
            <div class="chatbox_input_div">
                <input id="chatInput" type="text">
                <button id="chatbox_input_send" class="chatbox_input_send">发送</button>
            </div>
        </div>
    </div>
</body>
<script>
    document.getElementById('time').innerHTML = new Date().toLocaleString();

    var defuleValue = ''

    function debounce(fn, delay = 2000) {
        // 是闭包中的
        let timer
        let changeDom = document.getElementById('chatbox_input_send')
        // input事件调用的函数,相当于obj调用函数 this指向Input
        return function () {
            defuleValue = document.getElementById('chatInput').value
            // 这个if 判断不做也没关系,判断了(除第一次非空的情况)也就是执行从第二次开始,在延迟时间内多次触发才会走该判断
            if (timer) {
                clearTimeout(timer)
            } else {
                changeDom.innerHTML = '正在询问'
                changeDom.disabled = true
                document.getElementById('chatInput').value = ""
            }
            // 此时的箭头函数的this 和 arguments 都是从外部函数继承而来
            // 如果用普通函数就要用词法作用域 var that = this var arg = arguments
            timer = setTimeout(() => {
                // 使得传入的回调函数的this 指向Input这个元素对象
                // arguments是该事件的详情,可以获得该函数被调用时的所有参数,是一个event 对象(所有Dom事件都会传event对象进入)
                // 直接使用 fn() 问题也不大
                fn.apply(this, arguments)
                timer = null
            }, delay)
        }
    }
    // 直接使用
    document.getElementById('chatbox_input_send').addEventListener('click', debounce(() => {
        // 可直接使用this.value获得输入框的值; arguments可用于获取具体触发事件的信息
        // console.log(defuleValue)
        this.handleSend(defuleValue)
    }))

    document.getElementById('chatInput').addEventListener('keydown', function (event) {
        if (event.keyCode == "13") {
            document.getElementById('chatbox_input_send').click();
        }
    })

    function handleSend(inputValue) {
        // console.log(1);
        let inputDom = document.getElementById('chatBox');
        if (!inputValue.length) {
            alert('请输入您的问题!');
            document.getElementById('chatbox_input_send').innerHTML = '发送'
            document.getElementById('chatbox_input_send').disabled = false
            defuleValue = ""
            return
        }
        if (inputValue.length > 50) {
            alert('您输入的问题过长!');
            document.getElementById('chatbox_input_send').innerHTML = '发送'
            document.getElementById('chatbox_input_send').disabled = false
            defuleValue = ""
            return
        }

        inputDom.innerHTML = inputDom.innerHTML + '<div class="message my_message"><p>' + inputValue +
            '</span><br><span>' + new Date().toLocaleString() + '</span> </p></div>'

        let xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://127.0.0.1:5000/chat');
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

        xhr.onload = function () {
            let response = xhr.responseText; // 获取后端返回的字符串数据
            inputDom.innerHTML = inputDom.innerHTML +
                '<div class="message frnd_message"><p>' + response + '</span><br><span>' +
                new Date().toLocaleString() +
                '</span> </p></div>';
            document.getElementById('chatbox_input_send').innerHTML = '发送';
            document.getElementById('chatbox_input_send').disabled = false;
            defuleValue = "";
        }


        let userInput = inputValue;  // 这里是用户在聊天界面输入的内容
        let params = new URLSearchParams();
        params.append('user_input', userInput);
        xhr.send(params);


    }
</script>

</html>
<style>
    .chatbox_input_div {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .chatbox_input_send {
        width: 80px;
        height: 30px;
    }

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: 'Open Sans', sans-serif;
    }

    body {
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 100vh;
        background: linear-gradient(#009688 0%, #009688 130px, #d9dbd5 130px, #d9dbd5 100%)
    }


    .rightside {
        background: #e5ddd5;
        width: 100%;
        position: fixed;
        top: 50px;
    }

    .rightside::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: url(img6-bg.jpg);
        opacity: 0.06;
    }

    .header {
        position: relative;
        width: 100%;
        height: 60px;
        background: #ededed;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 15px;
    }

    .userimg {
        position: relative;
        width: 40px;
        height: 40px;
        overflow: hidden;
        border-radius: 50%;
        cursor: pointer;
    }

    .cover {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .imgText {
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .imgText h4 {
        font-weight: 500;
        line-height: 1.2em;
        margin-left: 15px;
    }

    .imgText h4 span {
        font-size: 0.8em;
        color: #555;
    }

    .chatBox {
        position: relative;
        width: 100%;
        /* height: calc(100%-120px); */
        height: 70vh;
        padding: 50px;
        overflow-y: auto;
    }

    .message {
        position: relative;
        display: flex;
        width: 100%;
        margin: 5px 0;
    }

    .message p {
        position: relative;
        right: 0;
        text-align: right;
        max-width: 65%;
        padding: 12px;
        background: #dcf8c6;
        border-radius: 10px;
        font-size: 0.9em;
    }

    .message p::before {
        content: '';
        position: absolute;
        top: 0;
        right: -12px;
        width: 20px;
        height: 20px;
        background: linear-gradient(135deg, #dcf8c6 0%, #dcf8c6 50%, transparent 50%, transparent);
    }

    .message p span {
        display: block;
        margin-top: 5px;
        font-size: 0.85em;
        opacity: 0.5;
    }

    .my_message {
        justify-content: flex-end;
    }

    .frnd_message {
        justify-content: flex-start;
    }

    .frnd_message p {
        background: #fff;
        text-align: left;
    }

    .message.frnd_message p::before {
        content: '';
        position: absolute;
        top: 0;
        left: -12px;
        width: 20px;
        height: 20px;
        background: linear-gradient(225deg, #fff 0%, #fff 50%, transparent 50%, transparent);
    }

    .chatbox_input {
        position: relative;
        width: 100%;
        /* height: 150px; */
        background: #f0f0f0;
        padding: 15px;
        justify-content: space-between;
        align-items: center;
    }

    .chatbox_input input {
        position: relative;
        width: 90%;

        margin: 0 20px;
        padding: 10px 20px;
        border: none;
        outline: none;
        border-radius: 30px;
        font-size: 1em;
    }
</style>

如果准备把后端部署到云服务器上可以把

        xhr.open('POST', 'http://127.0.0.1:5000/chat');

改成自己的云服务器地址,在这里介绍的只是本地的就先这样写了

后端部署   app.py文件

from flask import Flask, request, jsonify
from flask_cors import CORS

from gpt import ChatBot
app = Flask(__name__)
CORS(app)  # This will enable CORS for all routes
chatbot = ChatBot()



@app.route('/chat', methods=['POST'])
def chat():
    try:
        print("chat")
        user_input = request.form['user_input']  # 通过 'user_input' 键获取 POST 请求中的字符串数据
        response=chatbot.interact_with_openai(user_input)
        return response
    except Exception as e:
        print(str(e))  # 添加调试语句
        return jsonify({'error': str(e)})



if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000, debug=True)


gpt.py文件

from openai import OpenAI

class ChatBot:
    def __init__(self):
        self.chat_history = []
        self.client = self.initialize_openai_client()

    def initialize_openai_client(self):
        return OpenAI(
            api_key="sk-7fZ6aA8........",
            base_url="https://api.chatanywhere.tech/v1"
        )

    def ask_openai_question(self, messages):
        response = self.client.chat.completions.create(model="gpt-3.5-turbo", messages=messages)
        return response.choices[0].message.content

    def interact_with_openai(self, user_input):
        # print(self.chat_history)
        self.chat_history.append({'role': 'user', 'content': user_input})
        response = self.ask_openai_question(self.chat_history)
        print("AI回复:", response)
        self.chat_history.append({'role': 'assistant', 'content': response})
        return response

if __name__ == '__main__':
    chatbot = ChatBot()
    while True:
        user_input = input("请输入问题(或者直接回车退出): ")
        if user_input.strip() == "":
            break
        chatbot.interact_with_openai(user_input)

此处gpt.py文件需要把

            api_key="sk-7fZ6aA8........",

换成你自己的key,接下来就是讲怎么免费获得gpt接口属于你自己的key

去到这个开源项目

在这里注册拿到你自己的key然后替换文中代码的就行,其他关于这个开源项目的更多细节请自行了解

最后运行app.py

然后打开client.html,前后端都搞定了,请享用你自己的ai

  • 9
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值