pythontypeerroropenai-apichatgpt-api

OpenAI Python Package Error: 'ChatCompletion' object is not subscriptable


After updating my OpenAI package to version 1.1.1, I got this error when trying to read the ChatGPT API response:

'ChatCompletion' object is not subscriptable

Here is my code:

messages = [
        {"role": "system", "content": '''You answer question about some service'''
        },
        {"role": "user", "content": 'The user question is ...'},
    ]
response = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=0
    )
response_message = response["choices"][0]["message"]["content"]

How can I resolve this error?


Solution

  • In the latest OpenAI package the response.choices object type is changed and in this way you must read the response:

    print(response.choices[0].message.content)
    

    The complete working code:

    from openai import OpenAI
    
    client = OpenAI(api_key='YourKey')
    GPT_MODEL = "gpt-4-1106-preview" #"gpt-3.5-turbo-1106"
    messages = [
            {"role": "system", "content": 'You answer question about Web  services.'
            },
            {"role": "user", "content": 'the user message'},
        ]
    response = client.chat.completions.create(
            model=model,
            messages=messages,
            temperature=0
        )
    response_message = response.choices[0].message.content
    print(response_message )
    

    See this example in the project README.