pythonpipartificial-intelligenceopenai-apichatgpt-api

OpenAI API error: "You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0"


I am currently working on a chatbot, and as I am using Windows 11 it does not let me migrate to newer OpenAI library or downgrade it. Could I replace the ChatCompletion function with something else to work on my version?

This is the code:

import openai

openai.api_key = "private"

def chat_gpt(prompt):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": prompt}]
    )
    return response.choices[0].message['content'].strip()

if __name__ == "__main__":
    while True:
        user_input = input("You: ")
        if user_input.lower() in ["quit", "exit", "bye"]:
            break
        response = chat_gpt(user_input)
        print("Bot:", response)

And this is the full error:

... You tried to access openai.ChatCompletion, 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>

A detailed migration guide is available here: https://github.com/openai/openai-python/discussions/742

I tried both upgrading and downgrading through pip.


Solution

  • Try updating to the latest and using:

    from openai import OpenAI
    
    client = OpenAI(
        # defaults to os.environ.get("OPENAI_API_KEY")
        api_key="private",
    )
    
    def chat_gpt(prompt):
        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": prompt}]
        )
        return response.choices[0].message.content.strip()
    

    Link

    EDIT: message.['content'] -> message.content on the return of this function, as a message object is not subscriptable error is thrown while using message.['content']. Also, update link from pointing to the README (subject to change) to migration guide specific to this code.