google-colaboratoryopenai-apichatgpt-apigpt-4

Cannot use GPT API on Google Collab


I'm working on a project in Google Colab where I need to automatically generate text using pre-created prompts with the GPT-4 model from OpenAI. I wrote the following lines:

!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())

However, executing this code results in the following error:

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

I've looked through the OpenAI Python library documentation, the migration guide, and various resources for a solution that is compatible with Google Colab as of February 2024, but I haven't found a clear answer on how to proceed.

Could someone provide guidance or an updated code snippet that works with the latest version of the OpenAI library in Google Colab?

I don't know much about it, I need a solution that works on Google Colab and is up to date as of February 2024.


Solution

  • I assume you want to use the gpt-4 model.

    If this is the case, then first of all, you're trying to use the method name (i.e., Completion.create), which is not compatible with the Chat Completions API.

    Change this...

    openai.Completion.create
    

    ...to this.

    openai.ChatCompletion.create
    

    But if you do this, you'll still run into errors. Why?

    There are still some mistakes left to fix:

    See the full code with comments below.

    import os
    from openai import OpenAI
    client = OpenAI()
    OpenAI.api_key = os.getenv('OPENAI_API_KEY')
    
    response = client.chat.completions.create( # Changed
      model="gpt-4", 
      messages=[ # Changed
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello!"}
      ],
      temperature=0.7,
      max_tokens=150
    )
    
    print(response.choices[0].message) # Changed