Issue with OpenAI Python Library
I’m encountered some challenges while using the OpenAI Python package. Even though I updated to the latest version, it seems like certain functions are still absent. I attempted to uninstall and reinstall the package, yet the problem persists.
As I’m relatively new to Python, I may be overlooking something basic. This code is sourced from an online tutorial.
import openai
import pyttsx3
import speech_recognition as sr
from config import SECRET_KEY
openai.api_key = SECRET_KEY
tts_engine = pyttsx3.init()
speech_rec = sr.Recognizer()
audio_input = sr.Microphone(device_index=0)
chat_history = ""
user_label = "User"
ai_label = "Assistant"
while True:
with audio_input as source:
print("\nListening for input...")
speech_rec.adjust_for_ambient_noise(source, duration=0.3)
recorded_audio = speech_rec.listen(source)
print("Processing audio...\n")
try:
spoken_text = speech_rec.recognize_google(recorded_audio)
except:
continue
message = user_label + ": " + spoken_text + "\n" + ai_label + ": "
chat_history += message
# Call OpenAI API
api_response = openai.Completion.create(
engine='text-davinci-003',
prompt=chat_history,
max_tokens=150
)
reply = api_response["choices"][0]["text"].replace("\n", "")
reply = reply.split(user_label + ": ", 1)[0].split(ai_label + ": ", 1)[0]
chat_history += reply + "\n"
print(reply)
tts_engine.say(reply)
tts_engine.runAndWait()
Update: I resolved the initial issue, but now I’m facing a different error related to audio source management. It seems there are issues with the microphone context manager. Any advice would be greatly appreciated as I continue to learn.