=1.0.0." Could someo" /> =1.0.0." Could someo" /> =1.0.0." Could someo"/>

Python ChatGPT bot issue with openai.Completion

33 Views Asked by At

I'm trying to write a chatbot. I get the error, "You tried to access openai.Completion, but this is no longer supported in openai>=1.0.0."

Could someone help me figure out how to rewrite this to work with v1.0.0 of openAI API?

import openai

# Replace 'your_api_key_here' with your actual OpenAI API key
openai.api_key = 'your_api_key_here'

def chat_with_gpt(prompt):
    """
    Sends a prompt to GPT and returns the generated response.
    
    :param prompt: The input text to send.
    :return: The text of the generated response.
    """
    try:
        response = openai.Completion.create(
            model="gpt-3.5-turbo",  # Adjust with the appropriate model you have access to
            prompt=prompt,
            temperature=0.7,
            max_tokens=150,
            n=1,
            stop=None
        )
        return response.choices[0].text.strip()
    except Exception as e:
        return f"An error occurred: {str(e)}"

def main():
    print("GPT-3.5: Hello! How can I assist you today? Type 'quit' to exit.")
    chat_history = []  # To store the conversation history

    while True:
        user_input = input("You: ")
        if user_input.lower() == "quit":
            print("GPT-3.5: Goodbye! Have a great day!")
            break
        
        # Concatenate the chat history with the new message for context
        prompt = "\n".join(chat_history + [f"You: {user_input}", "GPT-3.5:"])
        response = chat_with_gpt(prompt)
        
        print(f"GPT-3.5: {response}")
        
        # Update the chat history
        chat_history.extend([f"You: {user_input}", f"GPT-3.5: {response}"])
        # Optional: Limit the history size to the last few exchanges to manage token limits
        chat_history = chat_history[-6:]

if __name__ == "__main__":
    main()

I also tried openai.ChatCompletion with similar error.

1

There are 1 best solutions below

0
FanaticExplorer On

Instead of using openai.Completion.create(), you need to instantiate a client object using client = openai.OpenAI() and then utilize client.chat.completions.create() method for generating completions.

Here's an example which shows how you can do it (taken from official OpenAI documentation):

from openai import OpenAI
client = OpenAI()

completion = client.chat.completions.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "system", "content": "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair."},
    {"role": "user", "content": "Compose a poem that explains the concept of recursion in programming."}
  ]
)

print(completion.choices[0].message)