Search code examples
pythonchatopenai-apigpt-3

Convert Python Script to Work with "GPT-3.5-turbo" model


I have the following python code working for the text-davinci-003

import openai
import time

openai.api_key = "skXXXXXXX"
model_engine = "text-davinci-003"

# Define the prompt for the conversation
prompt = "Conversation with an AI:"

while True:
    # Get the user's input
    user_input = input(prompt + " ")
    
    # Check if the user wants to exit
    if user_input.lower() in ["quit", "exit", "bye"]:
        print("Goodbye!")
        break
    
    # Generate a response from the OpenAI API
    response = openai.Completion.create(
        engine=model_engine,
        prompt=prompt + " " + user_input,
        max_tokens=1024,
        n=1,
        stop=None,
        temperature=0.7,
    )

    # Print the AI's response
    message = response.choices[0].text.strip()
    print("AI: " + message)

    # Wait for a bit before continuing
    time.sleep(1)

For the life of me I can't get it to work with "GPT-3.5-turbo". I have tried the following code from a github repo but I get errors:

import openai

# load and set our key
openai.api_key = open("key.txt", "r").read().strip("\n")

completion = openai.ChatCompletion.create(
  model="gpt-3.5-turbo", # this is "ChatGPT" $0.002 per 1k tokens
  messages=[{"role": "user", "content": "What is the circumference in km of the planet Earth?"}]
)

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

But it fails with the error: AttributeError: module 'openai' has no attribute 'ChatCompletion'

Can someone kindly help!!!

Thanks.


Solution

  • It sounds like you might have an old version of the OpenAI package. You could try this:

    pip install --upgrade openai