GPT:多轮对话并搭建简单的聊天机器人

1 多轮对话

多轮对话能力至关重要,它不仅能深化交流,精准捕捉对方意图,还能促进有效沟通,增强理解。在智能客服、教育辅导等领域,多轮对话更是提升服务质量、增强用户体验的关键。
注意:大模型没有多轮对话的能力,但基于大模型开发的对话产品是具有对话能力的。换句话说,就是GPT系列模型没有多轮对话能力,但是ChatGPT是能完成多轮对话能力的。 举例如下(ChaGpt结合上一次的对话识别出"好冷啊"这句话的意思是笑话不好笑,而GPT做不到):

ChatGPT结果

GPT结果

2 使用OpenAI API简单搭建聊天机器人

利用OpenAI API实现多轮对话的原理很简单,即:将之前对话的内容传递给GPT模型,以帮助模型生成更准确的回复。具体代码文件目录如下:

各个文件的具体代码如下:
driver.py(python实现)

python 复制代码
from flask import Flask,request,jsonify
from flask import render_template
from openai import OpenAI
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())
client=OpenAI()
#先加入一些对GPT聊天的基本要求,这两个要一直上传给大模型
history=[{"role":"system","content":"你是一个聊天机器人,你叫Bot."},{"role":"user","content":"每次输出的内容限定在50字以内。"}] 
# 生成对话内容
def chat(message):
	#将过去5轮对话的内容传递给大模型
    if len(history)>10:
        messages=history[:2]+history[-8:]
    else:
        messages=history[-10:]
    #正常结束
    if message.lower()=="stop":
        return "对话结束"
    messages.append({"role":"user","content":message})
    response=client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=messages,
        temperature=0.7,
    )
    #处理GPT没有输出的情况(比如token用完)
    if response.choices is None:
        return "对话结束"
    reply=response.choices[0].message.content
    history.append({"role":"user","content":message})
    history.append({"role":"assistant","content":reply})
    return reply

app=Flask(__name__)
@app.route('/')
def index():
    return render_template('chat.html')

@app.route('/submit_message',methods=['POST','GET'])
def submit():
    if request.method == 'POST':
        message = request.form['input-message']
    elif request.method == 'GET':
        message = request.args.get('input-message')
    if len(message)>0:
        reply=chat(message)
        return jsonify({"reply_message":reply})

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

前端页面代码:chat.html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat Window</title>
<style>
    .chat-container {
        display: flex;
        flex-direction: column;
        width: 600px;
        height: 500px;
        border: 1px solid #ccc;
        overflow-y: scroll;
        padding: 10px;
        margin-left:400px;
    }
    .chat-message {
        padding: 5px;
        margin-bottom: 10px;
        border-radius: 5px;
    }
    .user-message {
        align-self: flex-end;
        background-color: chartreuse;
    }
    .bot-message {
        align-self: flex-start;
        background-color:bisque;
        
    }
    .input-message {
        width: 600px;
        padding: 5px;
        margin-top: 10px;
        margin-left: 400px;
    }
    button {
        padding: 5px 10px;
        background: orange;
        border: 1px solid #ccc;
        border-radius: 5px;
        cursor: pointer;
        margin-left: 400px;
        margin-top: 10px;
    }
</style>
</head>
<body>
<div class="chat-container" id="chat-container">
    <div class="chat-message bot-message">我是一个聊天机器人,我叫Bot,现在我们可以开始聊天了!</div>
</div>
<form action='/submit_message'  method="GET">
<input type="text" class="input-message" id="input-message" name="input-message" placeholder="Type your message here">
</form>
<button onclick="sendMessage()">Send</button>
<script>
    async function sendMessage() {
        const input_message = document.getElementById('input-message').value;
        const chatContainer = document.getElementById('chat-container');
        const userMessage = document.createElement('div');
        userMessage.className = 'chat-message user-message';
        userMessage.textContent = input_message;
        chatContainer.appendChild(userMessage);
        
        const response=await fetch('http://127.0.0.1:5000/submit_message?input-message='+input_message,{
            method:'GET',
            mode:"cors",
            headers:{
                'Content-Type':'application/json'
            },
        });
        let result=await response.json();
        const reply_message=result.reply_message;
        const botMessage = document.createElement('div');
        botMessage.className = 'chat-message bot-message';
        botMessage.textContent = reply_message;
        chatContainer.appendChild(botMessage);
        document.getElementById('input-message').value = '';
    }
</script>
</body>
</html>

最后聊天界面如下(PS: token用光了,后续会替换掉这张图):

最后,关于多轮对话注意一下几点:

  • **多轮对话费token!多轮对话费token!多轮对话费token!**所以传递多少过去的对话内容给大模型需要仔细衡量。
  • 目前代码只是实现了多轮对话的能力,距离解决特定问题的智能客服等产品还很遥远。

参考资料

  1. https://blog.csdn.net/qq_38100666/article/details/130948824
相关推荐
小R资源4 小时前
什么是chatgpt?国内有哪些类gpt模型?
gpt
小R资源5 小时前
3款免费的GPT类工具
人工智能·gpt·chatgpt·ai作画·ai模型·国内免费
高兴就好(石5 小时前
DB-GPT部署和试用
数据库·gpt
知来者逆11 小时前
讨论人机交互研究中大语言模型的整合与伦理问题
人工智能·gpt·语言模型·自然语言处理·人机交互
故厶13 小时前
完整gpt应用(自用)
gpt
聚梦小课堂1 天前
OpenAI GPT o1技术报告阅读(1):通过学习,以及报告中有趣的部分-密文解析思维链✨
gpt·解密·openai o1·技术解读·案例解释·论文导读·案例解析
散一世繁华,颠半世琉璃1 天前
GPT如何理解人类语言:从向量化到智能涌现
gpt
李小星同志1 天前
DroidBot-GPT: GPT-powered UI Automation for Android论文学习
gpt·学习
TechQuester2 天前
OpenAI 刚刚推出 o1 大模型!!突破LLM极限
人工智能·python·gpt·算法·chatgpt
勤劳兔码农2 天前
NLP与文本生成:使用GPT模型构建自动写作系统
gpt·自然语言处理·ai写作