17611538698
webmaster@21cto.com

创建你的第一个使用 OpenAI ChatGPT API 的程序

人工智能 0 697 2023-06-03 11:32:36

导读:本文将指导开发者如何使用 OpenAI ChatGPT AI 创建聊天助手的 Python 程序之方法。

图片

OpenAI向所有人开放了ChatGPT的能力。现在可以将 ChatGPT 的强大功能无缝集成到自己的应用程序中。

完成这些初始步骤即可开始使用,无论您是希望将 ChatGPT 集成到现有应用程序中还是使用它开发新应用程序。

目前使用成本也比较优惠,目前价格为每 1000 个Token/0.002 美元。

此模型API目前与 Whisper API 一同提供,后面的API用来做文本到语音的解决方案。目前该 API 已经具备如下功能:

  • 创建自定义对话代理或聊天机器人

  • 能够帮助开发者编写 Python 代码

  • 起草电子邮件或任何你需要的文档

  • 可以将自然语言界面集成到当前的产品/应用/服务/软件中,为你的用户提供服务

  • 自然语言翻译服务

  • 成为许多学科的导师

  • 模拟视频游戏的角色


OpenAI ChatGPT API: 入门指南

准备条件

请访问https://chat.openai.com/并创建一个账户,当然你也可以使用你的Google或微软账号登录。

创建一个账户后,生成一个专属于你的 API 密钥。只需要访问https://platform.openai.com/account/api-keys并创建一个新的秘密密钥。

图片

创建 OpenAI API 密钥

首先请记录该密钥,并请将它放在安全的地方保存好。

图片

基于安全原因,它将不会从 OpenAI 账户部分再次可见。请注意不要与任何人分享此密钥。如果你计划使用企业解决方案,请向你的组织查询 API 密钥。

由于该密钥与你的付费 OpenAI 计划相关,请务必谨慎行动。

请注意,ChatGPT API 是一个通用术语,指的是使用基于 GPT 的模型开发聊天机器人的 OpenAI API,包括 gpt -3.5-turbo和gpt-4模型。

设置开发环境

安装 Python 和 pip

本指南使用 Python 语言来调用 OpenAI API 密钥。你还可以使用 Java 或其它任何喜欢的编程语言来调用。

首先,请确保在 Linux 或 Windows 中安装 Python。如果还没有安装,请按照以下指南安装 Python。

如果你使用现代级的 Linux 发行版(例如 Ubuntu),Python 应该已经安装好了。

在安装 Python 后,确保 pip 在 Linux 发行版中可用。运行以下命令进行安装。对于 Windows,你应该确保已经安装完毕了。

Ubuntu、Debian 和其它基于 Debian 的发行版:

https://platform.openai.com/account/api-keys


Fedora、RHEL、CentOS 等:

sudo dnf install python3-pip


Arch Linux:

sudo pacman -S python-pip


将 OpenAI API 密钥设置为环境变量


上述步骤中创建的 API 密钥,你可以直接在程序中使用。但这并不是代码最佳实践。最佳实践是从文件或你系统的环境变量来调用它。

对于 Windows,请先设置一个有意义的环境变量名字,例如 API-KEY,并将密钥值添加进去。

对于 Linux,请使用超级用户权限打开 /etc/environment 文件并添加密钥。比如:

API-KEY="<你的密钥>"


对于基于文件的密钥访问,请在代码中使用如下语句:

openai.api_key_path = <你的 API 密钥路径>


对于直接在代码中访问(不建议使用),可以在代码中使用以下语句:

openai.api_key = "你的密钥"


注意:如果验证失败,OpenAI API 将抛出以下类似错误,这表示你需要验证你的密钥值、路径和其他参数以进行更正。如:openai.error.AuthenticationError: No API key provided。

安装 OpenAI API


最后一步是安装 OpenAI 的 Python 库。打开终端或命令窗口,使用以下命令安装 OpenAI API。

pip install openai


现在的阶段,我们已经准备好编写第一个程序了。

编写助手程序


OpenAI API 提供了各种接口模式。例如“聊天自动完成”、“代码自动填充”、“图像生成”等。在本指南中,我们将使用 API 的“聊天自动完成”功能。使用此功能,我们可以创建一个简单的对话聊天机器人。


首先,你需要导入 OpenAI 库。可以使用以下语句在 Python 程序中填写:

import openai


在上面的语句之后,你应该确保启用API 密钥。可以使用上面任何方法来完成。如下代码:

openai.api_key="your key here"
openai.api_key="your environment variable"
openai.api_key_path =


OpenAI Chat API 的基本功能:


openai.ChatCompletion.create 函数以 JSON 格式接受多个参数。

这些参数形式为 “角色”(role) 和 “内容”(content):

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?"}])


说明:

role: 有效的值为 system、user、assistant

  • system: 指示 API 如何行动。基本上,它是 OpenAI 的主提示。

  • user: 你要问的问题。这是单个或多个会话中的用户输入。它可以是多行文本。

  • assistant: 当你编写对话时,你需要使用此角色来添加响应。这样,API 就会记住讨论的内容。


让我们定义一个数组来保存 OpenAI 的完整消息。然后向用户展示提示并接受 system 的指令。

messages = []
system_message = input("What type of chatbot you want me to be?")
messages.append({"role":"system","content":system_message})


一旦设置好了,再次提示用户进行关于对话的进一步提问。


你可以使用 Python 的 input 函数(或任何其他文件输入方法也可),

需要为角色 user 设置 content。


print("Alright! I am ready to be your friendly chatbot"+ "\n"+ "You can now type your messages.")
message = input("")
messages.append({"role":"user","content": message})


现在,你已经准备好了具有基本 JSON 输入的数组,用于调用“聊天补充”服务的 create 函数。

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


现在,你可以对其进行适当的格式化,要么打印响应,要么解析响应。响应是以 JSON 格式提供的。输出响应提供了 choices 数组。响应在 message JSON 对象下提供,其中包括 content 值。

我们可以读取 choices 数组中的第一个对象并读取其 content。

reply = response["choices"][0]["message"]["content"]
print(reply)


接着,它将为你提供来自 API 的输出。


运行代码


你可以从自己喜观的 Python IDE 或直接从命令行中运行脚本代码。

python OpenAIDemo2.py


未格式化的 JSON 输出


以下是使用未格式化的 JSON 输出运行上述程序供参考。正如所看到的,响应在 choices 数组下具有 content。

[debugpoint@fedora python]$ python OpenAIDemo2.py
What type of chatbot you want me to be?a friendly friend
Alright! I am ready to be your friendly chatbot
You can now type your messages.
what do you think about kindness?
{
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "As an AI language model, I don't have personal opinions, but I can tell you that kindness is a very positive and essential trait to have. Kindness is about being considerate and compassionate towards others, which creates positive emotions and reduces negativity. People who are kind towards others are more likely to inspire kindness and compassion in return. It is an important quality that helps to build positive relationships, promote cooperation, and create a more peaceful world.",
"role": "assistant"
}
}
],
"created": ,
"id": "chatcmpl-",
"model": "gpt-3.5-turbo-0301",
"object": "chat.completion",
"usage": {
"completion_tokens": 91,
"prompt_tokens": 22,
"total_tokens": 113
}
}


格式化的输出


这是一个具有适当格式的对话式输出内容。

[debugpoint@fedora python]$ python OpenAIDemo2.py


What type of chatbot you want me to be?a friendly friend
Alright! I am ready to be your friendly chatbot
You can now type your messages.
what do you think about artificial general intelligence?
As an AI language model, I am programmed to be neutral andnot have personal opinions. However, artificial general intelligence (AGI) is a fascinating field of study. AGI refers to the development of machines and algorithms that can perform any intellectual task that a human being can. The potential benefits and risks of AGI are still widely debated, with some experts worried about the implications of machines reaching human-like intelligence. However, many believe that AGI has the potential to revolutionize fields such as healthcare, education, and transportation. The key is to ensure that AGI is developed in a responsible and ethical manner.


完整代码


这是上面演示中使用的完整Python代码:

import openai


openai.api_key = ""
messages = []
system_message = input("What type of chatbot you want me to be?")
messages.append({"role":"system","content":system_message})


print("Alright! I am ready to be your friendly chatbot"+ "\n"+ "You can now type your messages.")
message = input("")
messages.append({"role":"user","content": message})


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


reply = response["choices"][0]["message"]["content"]
print(reply)


作者:老王

来源: https://www.debugpoint.com/openai-chatgpt-api-python

评论