ChatCompletion issues. Can anyone help?

Hello. I’m new to coding. I have an openAI API key, but I’m getting errors like this: AttributeError: module ‘openai’ has no attribute ‘ChatCompletion’ I had it working a few days ago but it seems all the end points have changed, or am I imagining things? For instance are there errors in this: response = openai.ChatCompletion.create(
engine=“text-davinci-003”,
prompt=query_text Any help at all would be very gratefully received! Thanks in advance. Mike McD

1 Like

The new version of openai python lib does not have the ChatCompletion endpoint anymore. You can refer to OpenAI Platform for the new endpoints.

1 Like

Hi Jerry, Many thanks for your quick reply. And apols, but I am super inexperienced! Do you happen to know what is wrong with the following. I am ultimately trying to write an app that scans text docs:

def get_completion(prompt, model=“gpt-3.5-turbo”):
messages = [{“role”: “user”, “content”: prompt}]
response = openai.completions.create(
model=model,
messages=messages,
max_tokens=50,
temperature=0,
)
return response.choices[0].message[“content”]

I don’t really understand the documentation, but I did see this:

from openai import OpenAI
client = OpenAI()

response = client.chat.completions.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Who won the world series in 2020?"},
    {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
    {"role": "user", "content": "Where was it played?"}
  ]
)

So I’m interested in knowing whether: response = openai.completions.create(
or: response = client.chat.completions.create(

is going to work. I hope you can help, and huge thanks in advance. Best wishes Mike

The recommended use of the new Python lib is to create an instance of the OpenAI class before use. and then use the instance, which is the client variable here, to do all the API calls.
You should do something like:

from openai import OpenAI
client = OpenAI()

def get_completion(prompt, client_instance, model=“gpt-3.5-turbo”):
  messages = [{“role”: “user”, “content”: prompt}]
  response = client_instance.chat.completions.create(
  model=model,
  messages=messages,
  max_tokens=50,
  temperature=0,
  )
  return response.choices[0].message[“content”]

get_completion(prompt, client) # call your function
3 Likes

Thank you so much, Jerry. I will try that. Very much appreciate you taking the time to help me out.

1 Like

Unfortunately, I got this in the terminal:
TypeError: ‘ChatCompletionMessage’ object is not subscriptable
With this as the little script:
from openai import OpenAI
client = OpenAI()
OpenAI.api_key = ‘xxxxxxxxxxxxxxxxxxxxxxxx’

def get_completion(prompt, client_instance, model=“gpt-3.5-turbo”):
messages = [{“role”: “user”, “content”: prompt}]
response = client_instance.chat.completions.create(
model=model,
messages=messages,
max_tokens=50,
temperature=0,
)
return response.choices[0].message[“content”]

prompt = “How far away is the moon?”
get_completion(prompt, client)

Any ideas about what I’m still doing wrong?

Change it to:

response.choices[0].message.content

4 Likes

Dear w.elabbar,
Thank you SO SO much - saved me hours of fruitless experiments.
Your solution worked!
Very much appreciate your kind help and have a lovely evening / day - depending on where you are!
Very best wishes
Mike

I’m in a similar position (also new to this) - would greatly appreciate if someone could help out? Trying to run this code:

PROMPT_MESSAGES = [
{
“role”: “user”,
“content”: [
“These are frames from a video that I want to upload. Generate a compelling description that I can upload along with the video.”,
*map(lambda x: {“image”: x, “resize”: 768}, base64Frames[0::10]),
],
},
]
params = {
“model”: “gpt-4-vision-preview”,
“messages”: PROMPT_MESSAGES,
“api_key”: os.environ[“OPENAI_API_KEY”],
“headers”: {“Openai-Version”: “2020-11-07”},
“max_tokens”: 200,
}

result = openai.ChatCompletion.create(**params)
print(result.choices[0].message.content)

Error:

AttributeError Traceback (most recent call last)

in <cell line: 18>()
16 }
17
—> 18 result = openai.ChatCompletion.create(**params)
19 print(result.choices[0].message.content)

AttributeError: module ‘openai’ has no attribute ‘ChatCompletion’

I defined environment variables as such:

from IPython.display import display, Image, Audio

import cv2 # We’re using OpenCV to read video

import base64

import time

import openai

import os

import requests

os.environ[‘OPENAI_API_KEY’] = ‘API_KEY’ #replaced with my key

Howdie. I am absoltely not an expert, but I think ChatCompletion has suddenly become outdated and may not work any more. So I think the above line may be your problem. I used w.elebbar’s advice and used this for the response:
def get_completion(prompt, client_instance, model=“gpt-3.5-turbo”):
messages = [{“role”: “user”, “content”: prompt}]
response = client_instance.chat.completions.create(
model=model,
messages=messages,
max_tokens=200,
temperature=0,
)
return response.choices[0].message.content
And it worked. key difference is that it’s .chat.completions.create( not ChatCompletion.create(. But you also need to set up with a client like this at the top of your script: from openai import OpenAI
client = OpenAI()

1 Like

You also can benefit by simply reading what’s above.

The openai python module changed significantly yesterday, so if you don’t install with pip install openai==0.28.1, you’re going to need to use different coding methods.

before

import json
import openai

completion = openai.Completion.create(
    model='gpt-3.5-turbo-instruct',
    ...)
print(completion.choices[0].text)
print(completion['choices'][0]['text'])
print(completion.get('usage'))
print(json.dumps(completion, indent=2))

after

from openai import OpenAI

client = OpenAI()

completion = client.completions.create(
    model='gpt-3.5-turbo-instruct',
    prompt='hey, bro\n\n',
     ...)
print(completion.choices[0].text)
print(dict(completion).get('usage'))
print(completion.model_dump_json(indent=2))

See more migration tips:

4 Likes

ChatCompletionMessage(content=‘1. Choose the correct article to complete the sentence: “My friend has _______ pet hamster.”\n\na) a\nb) an\nc) the\nd) no article needed\n\n2. Select the appropriate article for the blank: “I saw ________ beautiful bird at the zoo yesterday.”\n\na) a\nb) an\nc) the\nd) no article needed’, role=‘assistant’, function_call=None, tool_calls=None)
Traceback (most recent call last):
File “D:\codeflux_projects\question_generator\qu-generate.py”, line 72, in
questions = generate_mcq_new(subject, num_questions,classname,topic)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “D:\codeflux_projects\question_generator\qu-generate.py”, line 32, in generate_mcq_new
print(completion.choices[0].message[‘content’])
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^
TypeError: ‘ChatCompletionMessage’ object is not subscriptable

I am using updated api

You are not using updated methods of the API return object to extract parts of the response quite right:

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