import openai import gradio as gr from gtts import gTTS from io import BytesIO from IPython.display import Audio, display import os import time # Set OpenAI API key openai.api_key = os.environ.get("OPENAI_API_KEY") # Set OpenAI GPT-3 model MODEL = "gpt-3.5-turbo" def chat(input_text, history): global chat_history if len(input_text) == 0: return "", None response = openai.Completion.create( model=MODEL, prompt=history + input_text, max_tokens=1024, n=1, stop=None, temperature=0.5, ) message = response.choices[0].text.strip() chat_history += f"\nUser: {input_text}\nAI: {message}\n" # create speech output using gTTS speech_output = gTTS(message) # create byte buffer to store speech output speech_buffer = BytesIO() speech_output.write_to_fp(speech_buffer) speech_buffer.seek(0) # display speech output using IPython.display display(Audio(speech_buffer.read(), format='audio/mp3')) return message, speech_buffer.getvalue() def run(): global chat_history chat_history = "" interface = gr.Interface( fn=chat, inputs=["text", gr.inputs.Dropdown(["en-US-Wavenet-A", "en-US-Wavenet-B", "en-US-Wavenet-C", "en-US-Wavenet-D"])], outputs=["text", "audio"], layout="vertical", title="OpenAI Chatbot with Speech Output", description="Chat with the OpenAI GPT-3 chatbot and get speech output of the bot's response." ) interface.launch() while True: time.sleep(0.1) with open("chat_history.txt", "w") as f: f.write(chat_history)