Encountering 'AttributeError: module 'openai' has no attribute 'Completion'' with OpenAI Python library

Problem with OpenAI Python Library

I’m facing difficulties with the OpenAI Python package after upgrading. It seems some functionalities are either missing or altered. Specifically, using openai.Completion.create() leads to an AttributeError.

I have attempted to uninstall and reinstall the library, but the issue persists. As a beginner in Python, I might be overlooking something important.

Here’s my Code

import openai
import pyttsx3
import speech_recognition as sr
from config import OPENAI_KEY

openai.api_key = OPENAI_KEY

tts_engine = pyttsx3.init()
speech_recognizer = sr.Recognizer()
microphone = sr.Microphone(device_index=0)

chat_history = ""
user_label = "User"
bot_label = "Assistant"

while True:
    with microphone as audio_source:
        print("\nListening for input...")
        speech_recognizer.adjust_for_ambient_noise(audio_source, duration=0.3)
        recorded_audio = speech_recognizer.listen(audio_source)
    print("Processing audio...\n")

    try:
        spoken_text = speech_recognizer.recognize_google(recorded_audio)
    except:
        continue

    message = user_label + ": " + spoken_text + "\n" + bot_label + ": "
    chat_history += message

    # This line leads to the error
    api_response = openai.Completion.create(
        engine='text-davinci-003', 
        prompt=chat_history, 
        max_tokens=150
    )
    
    bot_reply = api_response["choices"][0]["text"].replace("\n", "")
    bot_reply = bot_reply.split(user_label + ": ", 1)[0].split(bot_label + ": ", 1)[0]

    chat_history += bot_reply + "\n"
    print(bot_reply)

    tts_engine.say(bot_reply)
    tts_engine.runAndWait()

New Issue

After making some adjustments, I encountered a different error regarding the speech recognition:

AssertionError: Audio source must be entered before adjusting, see documentation for AudioSource
AttributeError: 'NoneType' object has no attribute 'close'

Any advice on how to resolve these issues would be greatly appreciated. Thank you!

The AttributeError you’re encountering is likely due to the updates in the OpenAI Python library, which have altered some functionalities. The openai.Completion.create() method has been replaced with a new client-based approach. Here’s a modified version of your code:

from openai import OpenAI
client = OpenAI(api_key=OPENAI_KEY)

api_response = client.completions.create(
    model='gpt-3.5-turbo-instruct',
    prompt=chat_history,
    max_tokens=150
)

Keep in mind that text-davinci-003 is now deprecated; I’ve replaced it with gpt-3.5-turbo-instruct. Regarding your speech recognition issue, make sure to call adjust_for_ambient_noise() within the with microphone as audio_source: block to ensure the context is active when you make adjustments.