GPT / app.py
JaganathC's picture
Create app.py
14d23d5 verified
# app.py
import os
import streamlit as st
import pyttsx3
from openai import OpenAI
# Load API key from environment variable
api_key = os.getenv("OPENAI_API_KEY")
# Check if API key exists
if not api_key:
st.error("OpenAI API key not found. Please set 'OPENAI_API_KEY' in environment variables.")
st.stop()
# OpenAI client setup
Model = "gpt-4o"
client = OpenAI(api_key=api_key)
# Text-to-speech setup
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
def speak(text):
engine.say(text)
engine.runAndWait()
# GPT response function
def Reply(question):
completion = client.chat.completions.create(
model=Model,
messages=[
{'role': "system", "content": "You are a helpful assistant"},
{'role': 'user', 'content': question}
],
max_tokens=200
)
return completion.choices[0].message.content
# Streamlit UI
st.set_page_config(page_title="GPT Voice Assistant", page_icon="🗣️")
st.title("🗣️ Voice Assistant using GPT-4o")
st.write("Type your query below and get a spoken AI response!")
user_query = st.text_input("Enter your query:")
if st.button("Ask"):
if user_query:
with st.spinner("Thinking..."):
response = Reply(user_query)
st.success(response)
speak(response)
else:
st.warning("Please enter a query first.")