调用ChatGPT API

时间:2023-01-11 01:24:45

安装

pip install openai

找到openai.api_key

  1. 首先登录到OpenAI API界面(https://platform.openai.com/),点击右上角的账号弹出的列表中,点击view API keys。
  2. 跳转到API key界面,点击Create new secret key(如果你已经生成过key并且记录下来就不用添加)
  3. 然后生成新的key并且复制这个key。

api document

Chat/Create chat completion
Example request:
调用ChatGPT API
Example Response:
调用ChatGPT API

多轮对话(OpenAI API设置的4096个token限制)

import openai

openai.api_key = "{上面复制的key}"

completion = openai.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?"}
    ]
)

print(completion.choices[0].message)

print内容的就是返回的结果了。
注意这里的messages包括user(你自己的输入)和ChatGPT生成的内容(assistant),默认的API是不会进行上下文关联的,所以需要你在messages中添加对话的历史记录。

字典中每一个role的取值,对应的功能都不太一样,

  • system 用于在会话开始之初给定chatGPT一个指示或声明,使得后续的回答更具有个性化和专业化。
  • user 是用于给用户提问的或者说是用来给用户输入prompt的。
  • assistant 是用于输入chatGPT的回答内容。

参考补充

chatgpt token 工具
Introducing ChatGPT and Whisper APIs
Using the OpenAI Chat API, you can build your own applications with gpt-3.5-turbo and gpt-4
chatgpt prompt design
如何快速调用ChatGPT API
chatgpt api github 项目:解决了OpenAI API设置的4096个token限制
python-openai遇到ssl问题,应该如何解决?
调用chatGPT的api,并形成上下文详解
chatgpt finetune