ChatGPT 是一种用于生成文本的顶级大型语言模型。它已经改变了咱们编写几乎一切类型文本的方法,从像这样的教程,到主动生成的产品描绘、Bing 的搜索引擎成果,以及ChatGPT for Data Science 备忘单中描绘的数十个数据用例。

关于交互式运用,ChatGPT 的 Web 界面是理想的选择。但是,OpenAI(ChatGPT 背后的公司)也有一个应用程序编程接口 (API),可让您运用代码与 ChatGPT 及其其他模型进行交互。

在本教程中,您将学习怎么运用openaiPython 包以编程方法与 ChatGPT 进行对话。

请注意,OpenAI 运用 GPT API 是收费的。(有时会向新用户供给免费积分,但谁获得积分以及这笔交易将持续多长时刻并不通明。)它的本钱为 0.002 美元/1000 个代币,其间 1000 个代币约等于 750 个单词。运转本教程中的一切示例一次本钱应该低于 2 美分(但假如您重新运转使命,则每次都会付费)。

什么时候应该运用 API 而不是 Web 界面?

ChatGPT Web 应用程序是 GPT 模型的绝佳接口。但是,假如你想将人工智能归入数据管道或软件中,API 更合适。数据从业者的一些或许的用例包括:

  • 从数据库或其他 API 中提取数据,然后要求 GPT 对其进行汇总或生成相关陈述
  • 在仪表板中嵌入 GPT 功能以主动供给成果的文本摘要
  • 为您的数据集市供给自然语言界面
  • 经过学术( PyPI、Conda)包提取期刊论文来进行研究,并让 GPT 总结成果

设置 OpenAI 开发者帐户

要运用该 API,您需求运用 OpenAI 创立开发者帐户。您需求准备好您的电子邮件地址、电话号码以及借记卡或信用卡详细信息。

按着这些次第:

  1. 转至API 注册页面。
  2. 创立您的帐户(您需求供给您的电子邮件地址和电话号码)。
  3. 转至API 密钥页面。
  4. 创立一个新的密钥。
  5. 获取此密钥的副本。(假如丢失,请删去该密钥并创立一个新密钥。)
  6. 转到付款方法页面。
  7. 点击“增加付款方法”并填写您的银行卡详细信息。

安全地存储您的帐户凭据

密钥需求保密!否则,其他人能够运用它来拜访API,而你将为此付费。以下步骤描绘了怎么运用 DataCamp Workspace 安全地存储密钥。假如您运用不同的渠道,请查看该渠道的文档。您还能够向 ChatGPT 寻求建议。这是建议的提示:

您是一名 IT 安全专家。您正在与一位数据科学家交谈。解释安全存储用于 API 拜访的私钥的最佳实践。

  1. 在您的作业区中,单击“集成”
  2. 单击“创立集成”加号按钮
  3. 选择“环境变量”集成
  4. 在“称号”字段中,输入“OPENAI”。在“值”字段中,张贴您的密钥
  5. 单击“创立”,然后连接新的集成

设置Python

要经过 API 运用 GPT,您需求导入osopenaiPython 包。

假如您运用的是 Jupyter Notebook(例如 DataCamp Workspace),从 导入一些函数也很有协助

IPython.display

一个示例还运用 yfinance 包来检索股票价格。

#Importtheospackage
importos
#Importtheopenaipackage
importopenai
#FromtheIPython.displaypackage,importdisplayandMarkdown
fromIPython.displayimportdisplay,Markdown
#Importyfinanceasyf
importyfinanceasyf

另一个设置使命是将刚刚创立的环境变量放在 openai 包能够看到的方位。

#Setopenai.api_keytotheOPENAIenvironmentvariable
openai.api_key=os.environ["OPENAI"]

经过API调用GPT的Code Pattern

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

response=openai.ChatCompletion.create(
model="MODEL_NAME",
messages=[{"role":"system","content":'SPECIFYHOWTHEAIASSISTANTSHOULDBEHAVE'},
{"role":"user","content":'SPECIFYWANTYOUWANTTHEAIASSISTANTTOSAY'}
])

这里有几件事需求解开。

GPT 的 OpenAI API 模型称号

模型称号列在开发人员文档的“模型概述”页面中。在本教程中,您将运用gpt-3.5-turbo,这是 ChatGPT 运用的具有公共 API 拜访权限的最新模型。(当它广泛可用时,您将需求切换到gpt-4。)

OpenAI API GPT 音讯类型

谈天简介文档中记录了三种类型的音讯:

  • system音讯描绘了人工智能帮手的行为。关于数据科学用例来说,一条有用的体系音讯是“您是了解数据科学的有用帮手”。
  • user音讯描绘了您希望人工智能帮手说的话。咱们将在本教程中介绍用户音讯的示例
  • assistant音讯描绘了对话中之前的呼应。咱们将在后边的使命中介绍怎么进行交互式对话

第一条音讯应该是体系音讯。其他音讯应在用户和帮手之间替换显现。

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

生成示例数据集关于依据不同的数据场景测试代码或向其他人演示代码十分有用。要从 GPT 获得有用的呼应,您需求精确并指定数据集的详细信息,包括:

  • 行数和列数
  • 列的称号
  • 每列包括内容的描绘
  • 数据集的输出格局

以下是创立数据集的用户音讯示例。

Createasmalldatasetabouttotalsalesoverthelastyear.
Theformatofthedatasetshouldbeadataframewith12rowsand2columns.
Thecolumnsshouldbecalled"month"and"total_sales_usd".
The"month"columnshouldcontaintheshortenedformsofmonthnames
from"Jan"to"Dec".The"total_sales_usd"columnshould
containrandomnumericvaluestakenfromanormaldistribution
withmean100000andstandarddeviation5000.ProvidePythoncodeto
generatethedataset,thenprovidetheoutputintheformatofamarkdowntable.

让咱们将此音讯包括在前面的 Code Pattern 中。

#Definethesystemmessage
system_msg='Youareahelpfulassistantwhounderstandsdatascience.'
#Definetheusermessage
user_msg='Createasmalldatasetabouttotalsalesoverthelastyear.Theformatofthedatasetshouldbeadataframewith12rowsand2columns.Thecolumnsshouldbecalled"month"and"total_sales_usd".The"month"columnshouldcontaintheshortenedformsofmonthnamesfrom"Jan"to"Dec".The"total_sales_usd"columnshouldcontainrandomnumericvaluestakenfromanormaldistributionwithmean100000andstandarddeviation5000.ProvidePythoncodetogeneratethedataset,thenprovidetheoutputintheformatofamarkdowntable.'
#CreateadatasetusingGPT
response=openai.ChatCompletion.create(model="gpt-3.5-turbo",
messages=[{"role":"system","content":system_msg},{"role":"user","content":user_msg}])

查看 GPT 的呼应是否正常

API 调用是“有风险的”,因为问题或许发生在笔记本外部,例如互联网连接问题、发送数据的服务器出现问题,或者因为您用完了 API 积分。您应该查看您收到的呼应是否正常。

GPT 模型回来带有四个值之一的状况代码,这些值记录在谈天文档的呼应格局部分中。

  • stop:API回来完好的模型输出
  • length:因为 max_tokens 参数或 token 限制导致模型输出不完好
  • content_filter:因为咱们的内容过滤器中的标记而省掉了内容
  • null:API 呼应仍在进行中或不完好

GPT API 以 JSON 格局将数据发送到 Python,因此呼应变量包括深度嵌套的列表和字典。作业起来有点苦楚!

关于名为 的呼应变量response,状况代码存储在以下方位。

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

提取AI帮手的音讯

隐藏在呼应变量中的是咱们要求 GPT 生成的文本。走运的是,它总是在同一个地方。

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

呼应内容能够像往常一样打印print(content),但它是 Markdown 内容,Jupyter 笔记本能够经过以下方法烘托:display(Markdown(content))

Here'sthePythoncodetogeneratethedataset:
importnumpyasnp
importpandasaspd
#Setrandomseedforreproducibility
np.random.seed(42)
#Generaterandomsalesdata
sales_data=np.random.normal(loc=100000,scale=5000,size=12)
#Createmonthabbreviationlist
month_abbr=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
#Createdataframe
sales_df=pd.DataFrame({'month':month_abbr,'total_sales_usd':sales_data})
#Printdataframe
print(sales_df)
Andhere'stheoutputinmarkdownformat:
|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:包括体系音讯的字符串。
  • user_assistant:替换用户音讯和助理音讯的字符串数组。

回来值是生成的内容。

defchat(system,user_assistant):
assertisinstance(system,str),"`system`shouldbeastring"
assertisinstance(user_assistant,list),"`user_assistant`shouldbealist"
system_msg=[{"role":"system","content":system}]
user_assistant_msgs=[
{"role":"assistant","content":user_assistant[i]}ifi%2else{"role":"user","content":user_assistant[i]}
foriinrange(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"]
assertstatus_code=="stop",f"Thestatuscodewas{status_code}."
returnresponse["choices"][0]["message"]["content"]

该函数的用法示例是

response_fn_test=chat("Youareamachinelearningexpert.",["Explainwhataneuralnetworkis."])
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 帮手的呼应

在许多情况下,您会希望与人工智能进行更长时刻的对话。也就是说,您向 GPT 发送提示,收到呼应,然后发送另一个提示以继续谈天。在这种情况下,您需求在第二次调用 API 时包括 GPT 之前的呼应,以便 GPT 具有完好的上下文。这将提高呼应的准确性并提高对话的一致性。

为了重用 GPT 的音讯,您能够从呼应中检索它,然后将其传递到新的谈天调用中。

示例:剖析样本数据集

让咱们尝试依据之前生成的数据集计算销售列的平均值。chat()请注意,因为咱们第一次没有运用该函数,所以咱们有必要运用较长的子集代码来获取之前的呼应文本。假如运用chat(),代码会更简略。

#AssignthecontentfromtheresponseinTask1toassistant_msg
assistant_msg=response["choices"][0]["message"]["content"]
#Defineanewusermessage
user_msg2='Usingthedatasetyoujustcreated,writecodetocalculatethemeanofthe`total_sales_usd`column.Alsoincludetheresultofthecalculation.'
#Createanarrayofuserandassistantmessages
user_assistant_msgs=[user_msg,assistant_msg,user_msg2]
#GetGPTtoperformtherequest
response_calc=chat(system_msg,user_assistant_msgs)
#Displaythegeneratedcontent
display(Markdown(response_calc))
Sure!Here'sthecodetocalculatethemeanofthe`total_sales_usd`column:
```python
mean_sales=sales_df['total_sales_usd'].mean()
print("Meansales:$",round(mean_sales,2))
```
Andhere'stheoutputofthiscode:
```
Meansales:$100077.57
```
Therefore,themeanoftotalsalesoverthelastyearisabout$100,077.57.

在管道中运用 GPT

相关于 Web 界面运用 API 的一个巨大优势是您能够将 GPT 与其他 API 结合起来。从一个或多个来历提取数据,然后将人工智能应用到其间,这是一种强壮的作业流程。

将 GPT AI 应用于气候数据

在这里,咱们将运用 Weather2 包 ( PyPI)获取气候预报,并运用 GPT 提出活动想法。

#Importtheweather2package
importweather
#GettheforecastforMiami
location="Miami"
forecast=weather.forecast(location)
#Pulloutforecastdataformiddaytomorrow
fcast=forecast.tomorrow["12:00"]
#Createaprompt
user_msg_weather=f"In{location}atmiddaytomorrow,thetemperatureisforecasttobe{fcast.temp},thewindspeedisforecasttobe{fcast.wind.speed}m/s,andtheamountofprecipitationisforecasttobe{fcast.precip}.Makealistofsuitableleisureactivities."
#CallGPT
response_activities=chat("Youareatravelguide.",[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.