揭开ChatGPT面纱(5):使用chat.completions接口实现多轮聊天

发布于:2024-04-27 ⋅ 阅读:(24) ⋅ 点赞:(0)

openai版本==1.6.1
本系列博客源码仓库:gitlab,本博客对应文件夹05

一、参数解析

在前面的博客中,我介绍了completions接口,但实际上OpenAI1.6.1还提供了一个chat.completions接口。chat.completions接口相比completions接口有一些不同,主要体现为以下4点:

  1. 模型支持不同:

    • chat.completions接口提供了一些特定的模型支持,包括 gpt-4-1106-previewgpt-4-vision-preview 等。
    • completions接口也提供了一些特定的模型支持,如 babbage-002davinci-002gpt-3.5-turbo-instruct 等。
  2. 方法返回类型:

    • chat.completions接口在重载的 create 方法中返回 ChatCompletionStream[ChatCompletionChunk],这表明它可能用于聊天机器人场景,处理对话消息并生成相应的回复。
    • completions接口的create方法返回 CompletionStream[Completion],这表明它用于生成一般的文本完成。
  3. 参数细节:

    • chat.completions接口的 create 方法参数包括 messages,这表明它处理的是对话消息列表,而不是单一的提示(prompt)。
    • completions接口的 create 方法参数包括 prompt,这是用于生成文本完成的起始文本。
  4. 响应格式:

    • chat.completions接口的 response_format 参数允许用户指定模型输出的格式,例如 JSON 对象。

总的来说,chat.completions接口更加适合对话场景。completions接口则适用于一般的文本任务。


messages

相比completions接口,chat.completions接口的 create 方法参数包括 messages,这表明它处理的是对话消息列表,而不是单一的提示(prompt)。

  • 在messages参数中,role这个字段一共有三个角色可以选择,其中system代表系统,user代表用户,而assistant则代表AI的回答。

    • 当role是system的时候,content里面的内容代表我们给AI的一个指令,也就是告诉AI应该怎么回答用户的问题。

    • 而当role是user的时候,content里面的内容就代表用户和AI对话的内容。

在这里插入图片描述

二、多轮聊天实战

下面基于chat.completions接口实现多轮聊天。

from openai import OpenAI
import json
import httpx

# 读取配置,在上传gitlab时配置文件ignore了
with open('../config/openai.json') as config_file:
    config = json.load(config_file)

client = OpenAI(
    base_url=config['base_url'],
    api_key=config['key'],
    http_client=httpx.Client(
        base_url=config['base_url'],
        follow_redirects=True,
    ),
)

# 指定模型
MODEL = "gpt-3.5-turbo"

# 实现一个多轮问答的类
class MultiConversation:
	# 初始化对象时传入第一句指令
    def __init__(self, init_prompt):
        self.messages = []
        self.messages.append({"role": "system", "content": init_prompt})
        
	# 每调用一次这个方法,都会将问题和回答记录在self.messages列表属性中,用于记录上下文
    def qa(self, question):
        self.messages.append({"role": "user", "content": question})
        answer = client.chat.completions.create(
            model=MODEL,
            messages=self.messages,
            temperature=1.0
        )
        self.messages.append({"role": "assistant", "content": answer.choices[0].message.content})
        return answer.choices[0].message.content


if __name__ == "__main__":
    mc = MultiConversation('你是一个数学专家机器人,需要回答数学相关的问题,你的回答需要满足以下要求:'
                           '1.你的回答必须是中文'
                           '2.只回答数学相关的问题,对于非数学问题,一律只回答:对不起,无法回答不相关问题')
    print('您好,我是您的专属数学机器人,您可以向我提问任何数学问题,输入【exit】退出问答。')
    while True:
        user_input = input('Q:')
        if user_input.lower() == 'exit':
            print('bye~')
            break
        response = mc.qa(user_input)
        print('A:' + response)

  • 执行结果:

在这里插入图片描述