OpenAI ChatGPT 3.5以及4.0最新Python API简易教程

ChatGPT API was just released. Explore everything you can do with the ChatGPT API in Python.
ChatGPT API 刚刚发布。探索 Python 中的 ChatGPT API 可以做的所有事情。

OpenAI just released ChatGPT API. This is an API that calls gpt-3.5-turbo, which is the same model used in the ChatGPT product.
OpenAI刚刚发布了ChatGPT API。这是一个调用gpt-3.5-turbo的API,它与ChatGPT产品中使用的模型相同。

For those already familiar with the OpenAI API in Python, learning how to use the ChatGPT API should be simple, but there are still some concepts that are exclusive to this API that we’ll learn in this guide.
对于那些已经熟悉 Python 中的 OpenAI API 的人来说,学习如何使用 ChatGPT API 应该很简单,但我们仍将在本指南中学习一些此 API 独有的概念。

Let’s explore the ChatGPT API in Python.
让我们来探索一下 Python 中的 ChatGPT API。

*Note: The API is priced at $0.002 per 1K tokens. You have free credit to use, though. It seems now I have another reason to cancel my ChatGPT Plus subscription.*
注意:API 的价格为每 1K 个代币 0.002 美元。不过,您可以使用免费信用额度。现在看来我有另一个理由取消我的 ChatGPT Plus 订阅 .

Generate Your API Key生成您的 API 密钥

Before we start working with the ChatGPT API, we need to login into our OpenAI account and generate our API keys.
在我们开始使用 ChatGPT API 之前,我们需要登录我们的 OpenAI 帐户并生成我们的 API 密钥 .

Remember that OpenAI won’t display your secret API key again after you generate it, so copy your API key and save it. I’ll create an environment variable named OPENAI_API_KEY that will contain my API key for this tutorial.
请记住,OpenAI 在您生成私有 API 密钥后不会再次显示它,因此请复制您的 API 密钥并保存它。我将创建一个名为 OPENAI_API_KEY 的环境变量,该变量将包含本教程的 API 密钥。

Installing the library安装库

To work with the ChatGPT API, first, we have to install the openai library by running the following command.
要使用 ChatGPT API,首先,我们必须通过运行以下命令来安装 openai 库。

1
pip install openai

There are a lot of things you can do with the OpenAI library, but today we’re going to focus on the Completion endpoint. To be more precise, we’ll use “ChatCompletion” gpt-3.5-turbo, which is the same model used by ChatGPT.
您可以使用 OpenAI 库做很多事情,但今天我们将重点介绍完成端点。更准确地说,我们将使用 “ChatCompletion” gpt-3.5-turbo ,这与 ChatGPT 使用的模型相同。

开始使用 Python 的 ChatGPT API

To get started, we’re going to use the code snippet below that I got from the official documentation.
首先,我们将使用下面我从官方文档中获得的代码片段。

1
2
3
4
5
6
7
8
9
10
11
12
import os\
import openai\
openai.api_key = os.getenv("OPENAI_API_KEY")

completion = openai.ChatCompletion.create(\
model="gpt-3.5-turbo",\
messages=[\
{"role": "user", "content": "Tell the world about the ChatGPT API in the style of a pirate."}\
]\
)

print(completion.choices[0].message.content)

This is a very simple way to interact with the API. The main thing to know is that the messages list has a dictionary with 2 keys: roles and content.
这是与 API 交互的一种非常简单的方法。要知道的主要事情是 messages 列表有一个包含 2 个键的字典: roles 和 content .

The content is simply the content of the message, while there are three main roles : “system”, “user”, or “assistant”. The “user” is the one who gives the instructions and is being used in the code above.
content 只是消息的内容,而有三个主要的 roles :”系统”,”用户”或”助手”。”用户”是给出指令并在上面的代码中使用的人。

If we run the code above, we’ll get the following.
如果我们运行上面的代码,我们将得到以下内容。

This is the same as asking ChatGPT “Tell the world about the ChatGPT API in the style of a pirate.”
这就像问 ChatGPT”以海盗的风格向世界介绍 ChatGPT API”一样。

Now, the code snippet we took from the docs is very basic, we can add more code to interact with the API as if we were chatting with ChatGPT. Also, we should add the system role to set the behavior of the assistant and the assistant role to store prior responses.
现在,我们从文档中获取的代码片段非常基本,我们可以添加更多代码来与 API 交互,就像我们与 ChatGPT 聊天一样。此外,我们应该添加 system 角色来设置助手的行为,并添加 assistant 角色来存储先前的响应。

System Role

Let’s add a system role to set the behavior of the assistant. You can tell the assistant to be a “helpful assistant that translates English to French” or anything you want.
让我们添加一个系统角色来设置助手的行为。你可以告诉助手是一个”将英语翻译成法语的有用助手”或任何你想要的东西。

To make it simple, I’ll set the system role to be a “kind helpful assistant” through the messages list
为了简单起见,我将通过消息列表将系统角色设置为”乐于助人的助手

1
2
3
messages = [\
{"role": "system", "content" : "You're a kind helpful assistant"}\
]

Now I’m going to append the users role to the previous list and add the input function in order to interact with the API as if we’re working with ChatGPT.
现在,我将把 users 角色附加到前面的列表中,并添加输入函数,以便与 API 进行交互,就像我们在使用 ChatGPT 一样。

1
2
3
4
5
6
7
8
9
10
11
12
import openai

content = input("User: ")\
messages.append({"role": "user", "content": content})

completion = openai.ChatCompletion.create(\
model="gpt-3.5-turbo",\
messages=messages\
)

chat_response = completion.choices[0].message.content\
print(f'ChatGPT: {chat_response}')

Now if we ask “who was the first man on the moon?” the system will behave as a “helpful assistant and tells us the answer”
现在,如果我们问”谁是第一个登上月球的人?”系统将表现得像一个”乐于助人的助手,告诉我们答案”。

There’s only one little detail, though. The assistant isn’t storing the previous responses, so the system might not remember our previous responses and give us a proper response.
不过,只有一个小细节。 assistant 不存储以前的响应,因此系统可能不会记住我们以前的响应并给我们正确的响应。

Let’s now ask “where is he from?” and then “how tall is he?” I will now add a while loop to ask multiple questions.
现在让我们问”他来自哪里?”然后问”他有多高?”我现在将添加一个 while 循环来提出多个问题。

As you can see, now the system is answering each new question, but it’s accumulating the information from the previous replies.
如您所见,现在系统正在回答每个新问题,但它正在积累以前回复的信息。

We can solve this issue with the assistant role.
我们可以用 assistant 角色来解决这个问题。

Assistant Role

We use the assistant role to store prior responses. By storing previous responses, we can build a conversation history that will come in handy when user instructions refer to prior messages.
我们使用助理角色来存储先前的响应。通过存储以前的响应,我们可以构建一个对话历史记录,当用户指令引用以前的消息时,该历史记录将派上用场。

With the code below, we add the assistant role to our messages list.
使用下面的代码,我们将助理角色添加到我们的消息列表中。

1
messages.append({"role": "assistant", "content": chat_response})

Note that in the content we have to add the chat_response in order to store the responses.
请注意,在内容中,我们必须添加chat_response才能存储响应。

Now we add the previous line of code to our while loop.
现在我们将上一行代码添加到 while 循环中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import openai

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.choices[0].message.content\
print(f'ChatGPT: {chat_response}')\
messages.append({"role": "assistant", "content": chat_response})

Now if we ask the same question we asked before, we’ll get better responses.
现在,如果我们问之前问过的相同问题,我们会得到更好的回答。

And that’s it! Now you know how to work with the 3 roles, you can use the API as you want. Besides the model and messages in the request body, you can also add other parameters to customize your request.
就是这样!现在您知道如何使用 3 个角色,您可以根据需要使用 API。除了请求正文中的模型和消息外,还可以添加其他参数来自定义请求。

Here are some extra parameters:以下是一些额外的参数:

  • max_token: The maximum number of tokens to generate in the completion (here you can see the tokenizer that OpenAI uses)
    max_token :完成时要生成的最大令牌数(在这里您可以看到 OpenAI 使用的标记器)
  • temperature: The sampling temperature to use. Values close to 1 will give the model more risk/creativity, while values close to 0 will generate well-defined answers.
    temperature :要使用的采样温度。接近 1 的值将赋予模型更多的风险/创造力,而接近 0 的值将生成明确定义的答案。
  • n: The number of chat completion choices to generate for each input message.
    n :要为每个输入消息生成的聊天完成选项数。

To see all the parameters available, go to the official documentation.
要查看所有可用的参数,请转到 官方文档 .

其他GPT教程

ChatGPT开发视频教程合集:https://xueshu.fun/?s=gpt

  • ChatGPT Flutter 应用程序开发
  • ChatGPT 4 和 Midjourney提示工程
  • OpenAI Python API 训练营
  • 使用Django创建ChatGPT AI 机器人
  • ChatGPT Javascript开发教程