无法在 Google Collab 上使用 GPT API

问题描述 投票:0回答:1

我正在 Google Colab 中开展一个项目,我需要使用预先创建的提示以及 OpenAI 的 GPT-4 模型自动生成文本。我写了以下几行:

!pip install openai
!pip install cohere tiktoken
import openai
import os
os.environ["OPENAI_API_KEY"] = "my secret api"

response = openai.Completion.create(
  model="gpt-4", 
  prompt="hi",
  temperature=0.7,
  max_tokens=150
)
print(response.choices[0].text.strip())

但是,执行此代码会导致以下错误:

APIRemovedInV1: 

You tried to access openai.Completion, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API.

You can run `openai migrate` to automatically upgrade your codebase to use the 1.0.0 interface. 

Alternatively, you can pin your installation to the old version, e.g. `pip install openai==0.28`

我已经浏览了 OpenAI Python 库文档、迁移指南以及截至 2024 年 2 月与 Google Colab 兼容的解决方案的各种资源,但我还没有找到如何继续的明确答案。

有人可以提供与 Google Colab 中最新版本的 OpenAI 库配合使用的指导或更新的代码片段吗?

我对此了解不多,我需要一个适用于 Google Colab 且截至 2024 年 2 月最新的解决方案。

api google-colaboratory openai-api chatgpt-api gpt-4
1个回答
0
投票

我假设您想使用

gpt-4
模型。

你犯了一些错误:

  • 您正在尝试使用适用于旧版 OpenAI SDK 的方法名称(即
    Completion.create
    )。
  • 即使降级 OpenAI SDK,方法名称也与 Chat Completions API 不兼容。
  • 如果您想使用聊天完成 API,则
    prompt
    参数无效。
  • 如果您想使用聊天完成 API,消息检索会有所不同。

您正在尝试使用适用于旧版 OpenAI SDK 的方法名称。

请参阅下面带有注释的完整代码。

import openai
import os
os.environ["OPENAI_API_KEY"] = "sk-xxxxxxxxxxxxxxxxxxxxxxxx"

response = openai.chat.completions.create( # Change the method name
  model="gpt-4", 
  messages=[ # Changed the parameter
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Hello!"}
  ]
  temperature=0.7,
  max_tokens=150
)

print(response.choices[0].message) # Change message retrieval
© www.soinside.com 2019 - 2024. All rights reserved.