Getting error with completion object in openai>=1.0.0

I am trying to create a python3 chatbot with prompting. The issue is, that the openai api has been updated since. I can’t find a clear solution online.

The error I am getting is:

ERROR: 'Completion' object has no attribute 'get'

And here is my code

def get_api_response(prompt: str) -> str | None:
    text: str | None = None
    choices = None
    try:
        response: dict = openai.completions.create(
            model="gpt-3.5-turbo-instruct",
            prompt=prompt,
            temperature=1.2,
            max_tokens=200,
            top_p=1,
            frequency_penalty=0,
            presence_penalty=0.7,
            stop=['Human:', 'AI:']
        )
        print(response)
        choices: dict = response.get('choices')[0]
        text = choices.get('text')
    except Exception as e:
        print('ERROR:', e)
    return text

Thanks for any help

Note: Answer from kapa.ai OpenAI Discord Bot…

Based on the information provided in the extracts, it seems that the OpenAI API has indeed been updated and the way you’re trying to use the openai.completions.create method is no longer supported. In the new version of the API, you need to create an instance of the OpenAI class and then use the chat.completions.create method on that instance. Here’s how you can modify your code:

f

rom openai import OpenAI

def get_api_response(prompt: str) -> str | None:
    text: str | None = None
    choices = None
    try:
        client = OpenAI(api_key='your-api-key')
        response = client.chat.completions.create(
            model="gpt-3.5-turbo-instruct",
            messages=[
                {"role": "system", "content": "You are a helpful research assistant."},
                {"role": "user", "content": prompt}
            ],
            max_tokens=200,
            temperature=1.2,
            top_p=1,
            frequency_penalty=0,
            presence_penalty=0.7,
            stop=['Human:', 'AI:']
        )
        print(response)
        choices = response.choices[0]
        text = choices.message.content
    except Exception as e:
        print('ERROR:', e)
    return text

Please replace 'your-api-key' with your actual API key. Also, note that the response object is no longer a dictionary, but an instance of the ChatCompletion class. Therefore, you can’t use the get method on it. Instead, you can access the choices attribute directly, and each choice is an object with a message attribute, which in turn has a content attribute. This information is based on the extracts from the OpenAI Python API library Github Issues (Issues · openai/openai-python · GitHub).

I asked, “But what if you have to stick to python 3.x @kapa.ai ?”

The code provided above is compatible with Python 3. The OpenAI library supports Python versions from 3.7.1 to 3.11 according to the forum post (Difficulty Upgrading to gpt-3.5-turbo) in the extracts. If you’re using a Python version within this range, you should be able to use the code without any issues. If you’re using an older version of Python, you might need to upgrade your Python version to use the OpenAI library effectively. To check your Python version, you can use the following command in your terminal or command prompt:

python --version

If you need to upgrade Python, you can download the latest version from the official Python website (Download Python | Python.org). If you’re installing Python for the first time, you can follow the official Python installation guide for beginners (BeginnersGuide/Download - Python Wiki). Remember to also keep your OpenAI library up-to-date. You can upgrade it using pip:

pip install --upgrade openai

This information is based on the extracts from the OpenAI Python API library documentation (https://platform.openai.com/docs/quickstart?context=python). ---------------------- Note: you can ask me a follow up question by @ mentioning me again

The problem is your typing and parsing of the object, which is no longer a dictionary. It is a pydantic object. Along with simply the call.

"""Python 3.10+ OpenAI completions"""
import openai  # openai > 1.1

def get_api_response(prompt: str) -> str | None:
    client = openai.Client()
    text: str | None = None
    choices = None
    try:
        response: Any = client.completions.create(
            model="gpt-3.5-turbo-instruct",
            prompt=prompt,
            temperature=0.7,
            max_tokens=200,
            top_p=1,
        )
        # print(response)
        choices: Any = response.choices[0]
        text = choices.text
        print(response.usage.model_dump())
    except Exception as e:
        print('ERROR:', e)
    return text

if __name__ == "__main__":
    print(get_api_response(input("prompt>")))

The client gets OPENAI_API_KEY from the environment automatically.

Other than the model and version, does anything else change in the script for gpt-4-turbo using Python 3.12.3?