跳至主要内容

在 Python 中通过 OpenAI API 使用 GPT-3.5 和 GPT-4

在本教程中,您将学习如何使用 OpenAI 的 Python 软件包,以编程方式与 ChatGPT 进行对话。
· 14分钟 阅读

使用 AI 探索

ChatGPT 是一款前沿的大型语言模型,用于生成文本。它已经在改变我们撰写几乎所有类型文本的方式:从像本文这样的教程,到自动生成的产品描述、必应的搜索结果,以及 数据科学版 ChatGPT 速查表中所述的数十种数据用例。

对于交互式使用,ChatGPT 的网页版界面非常理想。不过,OpenAI(ChatGPT 背后的公司)也提供了应用程序编程接口(API),您可以用代码与 ChatGPT 以及其其他模型进行交互。

在本教程中,您将学习如何使用 openai Python 软件包,以编程方式与 ChatGPT 对话。

请注意,使用 GPT API 需要付费。(新用户有时会获得免费额度,但谁会获得以及这项优惠会持续多久并不透明。)费用为 $0.002/1000 个 token,1000 个 token 约等于 750 个英文单词。将本教程中的所有示例各运行一次,费用应低于 2 美分(但如果您重复运行任务,每次都会计费)。

何时应使用 API 而不是网页版界面?

ChatGPT 网页应用是使用 GPT 模型的绝佳界面。然而,如果您希望将 AI 集成到数据管道或软件中,API 更为合适。数据从业者的一些可能用例包括:

  • 从数据库或其他 API 拉取数据,然后让 GPT 对其进行摘要或生成报告
  • 在仪表板中嵌入 GPT 功能,自动提供结果的文本摘要
  • 为您的数据集市提供自然语言接口
  • 通过 scholarly(PyPI、Conda)软件包获取论文文献,并让 GPT 总结结果

创建 OpenAI 开发者账号

要使用 API,您需要在 OpenAI 创建一个开发者账号。您需要准备好电子邮箱、手机号以及借记卡或信用卡信息。

请按以下步骤操作:

  1. 前往 API 注册页面。
  2. 创建账号(需要提供您的电子邮箱和手机号)。
  3. 前往 API 密钥页面。
  4. 创建新的私密密钥。
  5. 保存一份密钥副本。(如果丢失,请删除该密钥并重新创建。)
  6. 前往 Payment Methods 页面。
  7. 点击“Add payment method”,并填写您的卡片信息。

安全存储您的账户凭据

私密密钥必须妥善保密!否则他人可能会用它访问 API,而费用将由您承担。以下步骤介绍如何在 DataLab(DataCamp 的 AI 加持数据笔记本)中安全存储您的密钥。如果您使用的是其他平台,请查看该平台的文档。您也可以向 ChatGPT 咨询建议。这里有一个推荐提示词:

> 您是一名 IT 安全专家。您的听众是一位数据科学家。请解释用于 API 访问的私钥安全存储最佳实践。

  1. 在您的 DataLab 工作簿中,点击“Environment”
  2. 点击“Environment”旁的加号
  3. 在“Name”字段输入“OPENAI”。在“Value”字段粘贴您的私密密钥
  4. 为这组环境变量命名(实际上可随意命名)
  5. 点击“Create”,并连接新的集成

设置 Python

要通过 API 使用 GPT,您需要导入 os 和 openai 这两个 Python 包。

如果您使用的是 Jupyter Notebook 解决方案(如 DataLab),从 IPython.display 导入一些函数也很有帮助。

其中一个示例还使用 yfinance 包来获取股票价格。

# Import the os package
import os

# Import the openai package
import openai

# From the IPython.display package, import display and Markdown
from IPython.display import display, Markdown

# Import yfinance as yf
import yfinance as yf

另一个设置任务是将您刚刚创建的环境变量放到 openai 包可见的位置。

# Set openai.api_key to the OPENAI environment variable
openai.api_key = os.environ["OPENAI"]

通过 API 调用 GPT 的代码模式

调用 OpenAI API 并获取聊天响应的代码模式如下:

response = openai.ChatCompletion.create(
              model="MODEL_NAME",
              messages=[{"role": "system", "content": 'SPECIFY HOW THE AI ASSISTANT SHOULD BEHAVE'},
                        {"role": "user", "content": 'SPECIFY WANT YOU WANT THE AI ASSISTANT TO SAY'}
              ])

这里有几个要点需要说明。

GPT 的 OpenAI API 模型名称

模型名称列在开发者文档的模型概览页面。在本教程中,您将使用 gpt-3.5-turbo,这是 ChatGPT 使用且对公众开放 API 的最新模型。(当 gpt-4 广泛可用时,您会希望切换到它。)

OpenAI API 的 GPT 消息类型

在Chat 入门文档中记录了三种消息类型:

  • system 消息用于描述 AI 助手的行为。一个对数据科学用例很有用的 system 消息是:“You are a helpful assistant who understands data science.”
  • user 消息描述您希望 AI 助手说什么。我们将在本教程中介绍 user 消息的示例
  • assistant 消息描述对话中的先前响应。我们将在后续任务中介绍如何进行交互式对话

第一条消息应为 system 消息。后续消息应在 user 和 assistant 之间交替出现。

您的第一次对话:生成一个数据集

生成示例数据集对于在不同数据场景下测试代码,或向他人演示代码都很有用。要从 GPT 获得有用的回复,您需要精确,并指定数据集的细节,包括:

  • 行数和列数
  • 列名
  • 每一列包含的内容描述
  • 数据集的输出格式

以下是一个用于创建数据集的 user 消息示例。

Create a small dataset about total sales over the last year. 
The format of the dataset should be a data frame with 12 rows and 2 columns. 
The columns should be called "month" and "total_sales_usd". 
The "month" column should contain the shortened forms of month names 
from "Jan" to "Dec". The "total_sales_usd" column should 
contain random numeric values taken from a normal distribution 
with mean 100000 and standard deviation 5000. Provide Python code to 
generate the dataset, then provide the output in the format of a markdown table.

让我们把这条消息放入之前的代码模式中。

# Define the system message
system_msg = 'You are a helpful assistant who understands data science.'

# Define the user message
user_msg = 'Create a small dataset about total sales over the last year. The format of the dataset should be a data frame with 12 rows and 2 columns. The columns should be called "month" and "total_sales_usd". The "month" column should contain the shortened forms of month names from "Jan" to "Dec". The "total_sales_usd" column should contain random numeric values taken from a normal distribution with mean 100000 and standard deviation 5000. Provide Python code to generate the dataset, then provide the output in the format of a markdown table.'

# Create a dataset using GPT
response = openai.ChatCompletion.create(model="gpt-3.5-turbo",
                                        messages=[{"role": "system", "content": system_msg},
                                         {"role": "user", "content": user_msg}])

检查 GPT 的响应是否正常

API 调用具有“不确定性”,因为问题可能发生在笔记本之外,例如网络连接问题,或提供数据的服务器出现故障,或者您的 API 额度用尽。您应检查获得的响应是否正常。

GPT 模型会返回一个状态码,取值有四种,详见 Chat 文档的响应格式部分。

  • stop:API 返回了完整的模型输出
  • length:由于 max_tokens 参数或 token 限制导致输出不完整
  • content_filter:由于内容过滤器标记而省略了内容
  • null:API 响应仍在进行中或不完整

GPT API 以 JSON 格式将数据发送到 Python,因此 response 变量包含深度嵌套的列表和字典。处理起来有点麻烦!

对于名为 response 的变量,状态码存储在以下位置。

response["choices"][0]["finish_reason"]

提取 AI 助手的消息

在 response 变量中,包含了我们要求 GPT 生成的文本。幸运的是,它总在同一个位置。

response["choices"][0]["message"]["content"]

可以像往常一样用 print(content) 打印响应内容,但这是 Markdown 内容,Jupyter 笔记本可以通过 display(Markdown(content)) 将其渲染出来。

Here's the Python code to generate the dataset:

import numpy as np
import pandas as pd
# Set random seed for reproducibility
np.random.seed(42)
# Generate random sales data
sales_data = np.random.normal(loc=100000, scale=5000, size=12)
# Create month abbreviation list
month_abbr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
# Create dataframe
sales_df = pd.DataFrame({'month': month_abbr, 'total_sales_usd': sales_data})
# Print dataframe
print(sales_df)

And here's the output in markdown format:

| month | total_sales_usd |

|-------|----------------|

| Jan | 98728.961189 |

| Feb | 106931.030292 |

| Mar | 101599.514152 |

| Apr | 97644.534384 |

| May | 103013.191014 |

| Jun | 102781.514665 |

| Jul | 100157.741173 |

| Aug | 104849.281004 |

| Sep | 100007.081991 |

| Oct | 94080.272682 |

| Nov | 96240.993328 |

| Dec | 104719.371461 |

使用辅助函数调用 GPT

要完成这三个简单操作,您需要编写大量重复的样板代码。使用一个包装函数来屏蔽这些繁琐部分很有用。这样我们就能专注于数据科学用例。

希望 OpenAI 未来能改进其 Python 包的接口,把这类功能内建起来。在此之前,您可以随意在自己的代码中使用下面的方法。

该函数接收两个参数。

  • system:包含 system 消息的字符串。
  • user_assistant:一个字符串数组,按用户消息与助手消息交替排列。

返回值是生成的内容。

def chat(system, user_assistant):
  assert isinstance(system, str), "`system` should be a string"
  assert isinstance(user_assistant, list), "`user_assistant` should be a list"
  system_msg = [{"role": "system", "content": system}]
  user_assistant_msgs = [
      {"role": "assistant", "content": user_assistant[i]} if i % 2 else {"role": "user", "content": user_assistant[i]}
      for i in range(len(user_assistant))]

  msgs = system_msg + user_assistant_msgs
  response = openai.ChatCompletion.create(model="gpt-3.5-turbo",
                                          messages=msgs)
  status_code = response["choices"][0]["finish_reason"]
  assert status_code == "stop", f"The status code was {status_code}."
  return response["choices"][0]["message"]["content"]

该函数的示例用法如下

response_fn_test = chat("You are a machine learning expert.",["Explain what a neural network is."])

display(Markdown(response_fn_test))
A neural network is a type of machine learning model that is inspired by the architecture of the human brain. It consists of layers of interconnected processing units, called neurons, that work together to process and analyze data.

Each neuron receives input from other neurons or from external sources, processes that input using a mathematical function, and then produces an output that is passed on to other neurons in the network.

The structure and behavior of a neural network can be adjusted by changing the weights and biases of the connections between neurons. During the training process, the network learns to recognize patterns and make predictions based on the input it receives.

Neural networks are often used for tasks such as image classification, speech recognition, and natural language processing, and have been shown to be highly effective at solving complex problems that are difficult to solve with traditional rule-based programming methods.

重用 AI 助手的响应

在许多情况下,您会希望与 AI 形成更长的对话。也就是说,您先向 GPT 发送提示,获得回复后,再发送另一条提示继续聊天。在这种情况下,您需要在第二次调用 API 时包含 GPT 之前的响应,以便 GPT 拥有完整上下文。这将提升回复的准确性,并提高整段对话的一致性。

要重用 GPT 的消息,您需要从响应中取回它,然后在新的聊天调用中传入。

示例:分析示例数据集

让我们尝试计算之前生成的数据集中销售列的平均值。请注意,由于第一次我们没有使用 chat() 函数,因此必须使用更长的取值代码来获取之前的响应文本。如果您使用 chat(),代码会更简单。

# Assign the content from the response in Task 1 to assistant_msg
assistant_msg = response["choices"][0]["message"]["content"]

# Define a new user message
user_msg2 = 'Using the dataset you just created, write code to calculate the mean of the `total_sales_usd` column. Also include the result of the calculation.'

# Create an array of user and assistant messages
user_assistant_msgs = [user_msg, assistant_msg, user_msg2]

# Get GPT to perform the request
response_calc = chat(system_msg, user_assistant_msgs)

# Display the generated content
display(Markdown(response_calc))
Sure! Here's the code to calculate the mean of the `total_sales_usd` column: 

```python 
mean_sales = sales_df['total_sales_usd'].mean() 
print("Mean sales: $", round(mean_sales, 2)) 
``` 

And here's the output of this code: 

``` 
Mean sales: $ 100077.57 
``` 

Therefore, the mean of total sales over the last year is about $100,077.57. 

在管道中使用 GPT

相比网页版界面,使用 API 的巨大优势在于,您可以将 GPT 与其他 API 结合使用。从一个或多个来源拉取数据,然后对其应用 AI,是一种强大的工作流。

将 GPT 应用于天气数据

在这里,我们将通过 weather2 包(PyPI)获取天气预报,并使用 GPT 提出活动建议。

# Import the weather2 package
import weather

# Get the forecast for Miami
location = "Miami"
forecast = weather.forecast(location)

# Pull out forecast data for midday tomorrow
fcast = forecast.tomorrow["12:00"]

# Create a prompt
user_msg_weather = f"In {location} at midday tomorrow, the temperature is forecast to be {fcast.temp}, the wind speed is forecast to be {fcast.wind.speed} m/s, and the amount of precipitation is forecast to be {fcast.precip}. Make a list of suitable leisure activities."

# Call GPT
response_activities = chat("You are a travel guide.", [user_msg_weather])

display(Markdown(response_activities))
With mild temperatures and calm winds, Miami is the perfect place for leisure activities. Here are some suggestions:

1. Visit Miami's beaches and soak up some sun or take a dip in the ocean!

2. Explore Miami's art scene with a visit to the Perez Art Museum Miami or the Wynwood Walls.

3. Take a stroll along the famous Ocean Drive and enjoy the colorful Art Deco architecture.

4. Head to Little Havana to experience the Cuban culture and delicious cuisine.

5. Enjoy a scenic walk or bike ride through one of Miami's many parks, such as Bayfront Park or South Pointe Park.

6. Visit the Miami Seaquarium and see some incredible marine life up close.

7. Take a boat tour to see the stunning Miami skyline from the water.

8. Shopping enthusiasts can explore the many high-end boutiques and outdoor shopping malls, such as Lincoln Road Mall.

9. Foodies can venture to one of the many food festivals happening throughout the year.

10. Finally, there are plenty of nightclubs and live music venues to keep the night going.

太棒了!我有点儿希望明天就在迈阿密!

更进一步

您可以在 Introduction to ChatGPT 课程中进一步学习如何使用 GPT。(一门关于使用 OpenAI API 的完整课程即将推出!)

想要快速参考您刚学到的内容,请保存一份 OpenAI API in Python 速查表,或观看入门 OpenAI API 与 ChatGPT直播培训录像。

如果您对语音转文本感兴趣,请阅读教程:使用 OpenAI Whisper API 将语音转换为文本。

主题