pythonopenai-apichatgpt-apichat-gpt-4

OpenAI API error: "Module 'openai' has no attribute 'ChatCompletion', did you mean 'Completion'?"


I can't seem to figure out what the issue is here, I am running version 0.28.1:

enter image description here

from what I have read I should be using ChatCompletion rather than Completion as that's what gpt-4 and 3.5-turbo supports.

response = openai.ChatCompletion.create(
    prompt=question,
    temperature=0,
    max_tokens=3700,
    top_p=1,
    frequency_penalty=0,
    presence_penalty=0,
    stop=None,
    model="gpt-4",
)

Looking at other answers I can also tell you that my file isn't named openai.py or anything like that.

Thanks for any help in advance.


Solution

  • First of all, be sure you have an up-to-date OpenAI package version.

    If not, upgrade the OpenAI package.

    Python:

    pip install --upgrade openai
    

    NodeJS:

    npm update openai
    

    The code posted in your question above has a mistake. The Chat Completions API doesn't have the prompt parameter as the Completions API does. Instead, it has the messages parameter. See the official OpenAI documentation.

    Try the following:

    import os
    import openai
    openai.api_key = os.getenv("OPENAI_API_KEY")
    
    completion = openai.ChatCompletion.create(
      model = "gpt-4",
      messages = [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello!"}
      ]
    )
    
    print(completion.choices[0].message)