ChatGPT API 是 OpenAI 在 2023 年 3 月 1 日推出的一个 API,它引入了 ChatGPT 和 Whisper API,允许任何企业将 ChatGPT 技术集成到他们的应用程序、网站、产品和服务中。

ChatGPT API 由 OpenAI 最受欢迎的 ChatGPT AI 模型提供支持,该模型被称为“gpt-3.5-turbo”。GPT-3.5是OpenAI通过其API套件提供的最强大的文本生成模型;“turbo”是指 GPT-3.5 的一个优化、更具响应性的版本。

在 API 的以前版本中,使用的是 text-davinci-003 模型,该模型没有上下文对话能力,生成的内容比 ChatGPT 差得多。现在,正式发布了 API 的官方 ChatGPT 版本,这对开发者来说是个好消息,当然,对于 OpenAI 甚至整个行业来说,这都具有重要意义。

与 Python 一起使用 ChatGPT

要使用 Python 调用 ChatGPT,首先需要一个 OpenAI 账户。

生成 API 密钥

注册并登录成功,你可以通过“Personal” -> “View API keys”生成一个API密钥。

现在你已经有了 API 密钥,下一步是创建一个 ChatGPT 项目:

linuxmi@linuxmi:~/www.linuxmi.com$ mkdir python-chatgpt
linuxmi@linuxmi:~/www.linuxmi.com$ cd python-chatgpt
linuxmi@linuxmi:~/www.linuxmi.com/python-chatgpt$ python3.10 -m venv openai
linuxmi@linuxmi:~/www.linuxmi.com/python-chatgpt$ source venv/bin/active

安装OpenAI Python客户端库

OpenAI Python 库提供了从使用 Python 语言编写的应用程序中访问 OpenAI API 的便捷方式。它包括一组预定义的API资源类,这些类可以从 API 响应动态地初始化自己,这使其与 OpenAI API 的各种版本兼容。

有关此库的详细信息,请访问:https://github.com/openai/openai-python

  • openai 0.27.0+
(openai) linuxmi@linuxmi:~/www.linuxmi.com/python-chatgpt/openai/bin$ pip install -U pip
Requirement already satisfied: pip in /home/linuxmi/www.linuxmi.com/python-chatgpt/openai/lib/python3.10/site-packages (22.0.2)
Collecting pip
  Using cached pip-23.0.1-py3-none-any.whl (2.1 MB)
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 22.0.2
    Uninstalling pip-22.0.2:
      Successfully uninstalled pip-22.0.2
Successfully installed pip-23.0.1

(openai) linuxmi@linuxmi:~/www.linuxmi.com/python-chatgpt/openai/bin$ pip install openai
Collecting openai
  Downloading openai-0.27.4-py3-none-any.whl (70 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 70.3/70.3 kB 190.6 kB/s eta 0:00:00
Collecting tqdm
  Downloading tqdm-4.65.0-py3-none-any.whl (77 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 77.1/77.1 kB 247.9 kB/s eta 0:00:00
......省略......

演示 Python 代码

然后让我们在 python-chatgpt 项目文件夹中创建一个 chatbot.py 文件,其中包含以下内容:

Chatgpt 模型

import openai

openai.api_key = "sk-xxxx"

response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
            {"role": "system", "content": "You are a chatbot"},
            {"role": "user", "content": "Why should DevOps engineer learn kubernetes?"},
        ]
)

result = ''
for choice in response.choices:
    result += choice.message.content

print(result)

输出将如下所示:

DevOps engineers should learn Kubernetes because it is a widely used and highly popular container orchestration tool. It enables the deployment, scaling, and management of containerized applications. Learning Kubernetes allows for efficient management of containerized applications, reduces the risk of downtime, increases scalability, streamlines the DevOps process, and improves collaboration between teams. Additionally, many organizations are now using Kubernetes as their preferred platform for container management, so knowledge of Kubernetes is becoming increasingly important for DevOps engineers.

import openai

# Define OpenAI API key 
openai.api_key = "YOUR_API_KEY"

# Set up the model and prompt
model_engine = "text-davinci-003"
prompt = "Once upon a time, in a land far, far away, there was a princess who..."

# Generate a response
completion = openai.Completion.create(
    engine=model_engine,
    prompt=prompt,
    max_tokens=1024,
    n=1,
    stop=None,
    temperature=0.5,
)

response = completion.choices[0].text
print(response)

以上代码将使用ChatGPT模型对所定义的提示生成响应,并将响应作为字符串返回到response变量中。

temperature参数控制输出中的随机性水平。temperature越高,响应输出越多变且不太一致,您可以根据实验进行调整。stop定义停止条件。

让我们尝试执行上述代码几次:

(openai)$ python chatbot.py
 lived in a grand castle. She was beloved by all of the people in her kingdom 
and had many loyal subjects who would do anything to make her happy. 
One day, the princess decided to go on a journey to explore the world outside 
her kingdom. She traveled to many strange and wonderful places, meeting new 
people and having amazing adventures. Everywhere she went, she was welcomed 
with open arms and treated with kindness and respect. Eventually, she 
returned home to her beloved kingdom, where she was greeted with much joy 
and happiness. The people of the kingdom celebrated her return with a grand 
feast and a parade in her honor. From that day forward, the princess was 
remembered as a brave and kind-hearted leader who had ventured into the 
unknown and returned with stories of her travels.

(openai) $ python chatbot.py
lived in a castle surrounded by a vast kingdom. She was beloved by all, 
for she was kind and generous. Every day, she would go out into the kingdom 
and help those in need, whether it be healing the sick, providing food for 
the hungry, or simply lending a listening ear to those who needed it. 
Her people adored her, and she was the happiest princess in all the land.

如果遇到错误:

Error: No API key provided. You can set your API key in code using 'openai.api_key = <API-KEY>', or you can set the environment variable OPENAI_API_KEY=<API-KEY>). If your API key is stored in a file, you can point the openai module at it with 'openai.api_key_path = <PATH>'. You can generate API keys in the OpenAI web interface. See https://onboard.openai.com for details, or email support@openai.com if you have any questions.

您可以尝试设置环境变量:

export OPENAI_API_KEY=xxxx

命令行界面

此库还提供了一个openai命令行实用程序,可以轻松地从终端与API交互。运行openai api -h来查看用法。

# list engines
$ openai api engines.list
[organization=user-mib5ehdmvyxeqog6toqudcyl] {
  "data": [
    {
      "created": null,
      "id": "babbage",
      "object": "engine",
      "owner": "openai",
      "permissions": null,
      "ready": true
    },
    {
      "created": null,
      "id": "ada",
      "object": "engine",
      "owner": "openai",
      "permissions": null,
      "ready": true
    },
...

# create a completion
$ openai api completions.create -e ada -p "Hello world"
Hello world. just a nerds thing, what's well put in the game!

# generate images via DALL·E API
$ openai api image.create -p "two linuxmi playing soccer, cartoon" -n 1
{
  "created": 1681023356,
  "data": [
    {
      "url": "https://oaidalleapiprodscus.blob.core.windows.net/private/org-SMp9VisNxVH0oojOT1QpDWe/user-miB5EHDmvYxeQoG6TOqudCyl/img-KtIloC0JH93KORzxS7imL3sY.png?st=2023-01-12T00%3A24%3A11Z&se=2023-01-12T02%3A24%3A11Z&sp=r&sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2023-01-11T23%3A52%3A22Z&ske=2023-01-12T23%3A52%3A22Z&sks=b&skv=2021-08-06&sig=HFbdTdWJMV7/zWVaE2oWg2rCdk1bimXeGtU8r3jHmcY%3D"
    }
  ]
}

并且生成的图像看起来像:

或者:

就是这样! 您可以看到在您的 Python 程序中使用 ChatGPT 非常容易。 祝你玩得开心!

发表回复