前言

ChatGPT最近热度继续低落,曾经成为互联网和金融投资畛域最热门的话题。

有的小伙伴可能须要在公司搭建一套ChatGPT零碎,那应用ChatGPT的API显然是最好的抉择。

不过ChatGPT的API都是无状态的,没有对话治理的性能。

你调用API发送一个问题(prompt)给ChatGPT,它就依据你发送的问题返回一个后果(completion)。

那如何通过ChatGPT的API实现带上下文性能的对话呢。

ChatGPT API

ChatGPT的API实际上是对规范的HTTP接口做了一层封装,HTTP申请的url地址如下:

https://api.openai.com/v1/chat/completions

官网封装了Python和Node.js库,能够间接应用。

咱们来看一段Python代码示例:

import osimport openai# 设置API keyopenai.api_key = os.getenv("OPENAI_API_KEY")# 给ChatGPT发送申请completion = openai.ChatCompletion.create(  model="gpt-3.5-turbo",  messages=[    {"role": "user", "content": "Hello!"}  ])# 打印申请后果print(completion.choices[0].message)

这段代码很简略,发送一条音讯"Hello!"给ChatGPT,而后打印后果。

这里有3个注意事项:

  • 用到了官网的openai库,须要装置

    $ pip install openai
  • 须要创立API key

    在上面这个链接创立你的API key

    https://platform.openai.com/account/api-keys
  • 要应用openai.ChatCompletion

    openai这个库里封装了很多类,如下所示:

    openai.Completion

    openai.ChatCompletion

    openai.Edit

    openai.Image

    openai.Embedding

    openai.Audio

    openai.FineTune

    openai.Moderation

其中,openai.ChatCompletion用于对话。

Role角色

仔细的同学可能曾经发现,给ChatGPT发送音讯的时候,参数message是个数组,数组里每个dict有role这个字段。

role目前有3个取值:

  • user。示意提交prompt的一方。
  • assistant。示意给出completion响应的一方,实际上就是ChatGPT自身。
  • system。message里role为system,是为了让ChatGPT在对话过程中设定本人的行为,目前role为system的音讯没有太大的理论作用,官网说法如下:
gpt-3.5-turbo-0301 does not always pay strong attention to system messages. Future models will be trained to pay stronger attention to system messages.
# Note: you need to be using OpenAI Python v0.27.0 for the code below to workimport openaiopenai.ChatCompletion.create(  model="gpt-3.5-turbo",  messages=[        {"role": "system", "content": "You are a helpful assistant."},        {"role": "user", "content": "Who won the world series in 2020?"},        {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},        {"role": "user", "content": "Where was it played?"}    ])

下面这段代码里,应用了3种角色的role,这个messages发送给ChatGPT后,ChatGPT就有了上下文,晓得作为user的咱们说了什么,也晓得作为assistant的本人答复了什么。

想通过API实现蕴含上下文信息的多轮对话的要害就是用好role字段。

不含上下文的对话

import osimport openaiopenai.api_key = os.getenv("OPENAI_API_KEY")while True:    content = input("User: ")    messages = [{"role": "user", "content": content}]        completion = openai.ChatCompletion.create(      model="gpt-3.5-turbo",      messages=messages    )    chat_response = completion    answer = chat_response.choices[0].message.content    print(f'ChatGPT: {answer}')

下面这个实现里,每次只发送了以后输出的信息,并没有发送对话的历史记录,所以ChatGPT无奈晓得上下文。

咱们来看对话成果如下:

$ python3 chatgpt1.py User: 你好ChatGPT: 你好!我是AI助手,有什么能够帮到您的吗?User: 我方才说了什么ChatGPT: 很道歉,因为我是AI语音助手,无奈得悉您方才说了什么,请您再次告知。

蕴含上下文的对话

import osimport openaiopenai.api_key = os.getenv("OPENAI_API_KEY")messages = []while True:    content = input("User: ")    messages.append({"role": "user", "content": content})        completion = openai.ChatCompletion.create(      model="gpt-3.5-turbo",      messages=messages    )    chat_response = completion    answer = chat_response.choices[0].message.content    print(f'ChatGPT: {answer}')    messages.append({"role": "assistant", "content": answer})

下面这个实现里,每次发送申请给ChatGPT时,把历史对话记录也一起发送,所以ChatGPT晓得对话的上下文。

咱们来看对话成果如下:

$ python3 chatgpt2.py User: 你好ChatGPT: 你好!我是AI助手,有什么须要帮忙的吗?User: 我方才说了什么ChatGPT: 你方才说了 "你好"。

潜在的坑

目前通过API实现上下文对话有2个潜在的坑:

  • token数量问题。每次要把历史对话记录传过来,会导致后续单次申请和响应耗费的token数量越来越多,超过ChatGPT模型反对的最大上下文长度,ChatGPT就无奈持续往下解决了。比方gpt-3.5-turbo反对的最大上下文长度是4097个token,如果单次申请和响应里蕴含的token数量超过这个数,ChatGPT就会返回如下谬误:

    This model's maximum context length is 4097 tokens. However, you requested 4103 tokens (2066 in the messages, 2037 in the completion). Please reduce the length of the messages or completion.
  • 费用问题。API是依照token数量免费的,这个token计算是prompt和completion的token数量总和。因为后续的申请蕴含的token数量越来越多,导致每次调用API的免费也越来越高。

那如何解决这个问题呢?

  • 第一种形式就是每次发送申请时,不必带上全副历史对话记录,只带上最近几轮对话的记录。比方就带上最近6条对话记录(3条prompt,3条completion),缩小单次申请里蕴含的token数量,防止超过ChatGPT模型的最大上下文长度。
  • 第二种形式是在调用API的时候,限度用户发问内容长度,以及限度返回的completion的token数量。后者能够通过给API调用指定max_token参数来实现,该参数的含意如下:

    The maximum number of tokens to generate in the chat completion.

    The total length of input tokens and generated tokens is limited by the model's context length.

总结

在官网和ChatGPT对话的同学可能会发现,API返回的completion后果其实没有官网的好,


通过查看官网对话的申请信息,发现普通用户(非ChatGPT Plus会员)用的模型是text-davinci-002-render-sha,而这个模型在API里无奈应用。

开源地址

想晓得如何注册ChatGPT账号以及API应用教程的能够参考我的开源教程: ChatGPT模型教程。蕴含ChatGPT和百度文心一言的入门和实战教程。

公众号:coding进阶。

集体网站:Jincheng's Blog。

知乎:无忌。

福利

我为大家整顿了一份后端开发学习材料礼包,蕴含编程语言入门到进阶常识(Go、C++、Python)、后端开发技术栈、面试题等。

关注公众号「coding进阶」,发送音讯 backend 支付材料礼包,这份材料会不定期更新,退出我感觉有价值的材料。还能够发送音讯「进群」,和同行一起交流学习,答疑解惑。

References

  • https://platform.openai.com/docs/introduction
  • https://platform.openai.com/docs/api-reference