space_turtle / pages /OpenAI_Response.py
Akash190104's picture
Fixing Streaming and openai API issues
2b3c6a6
import os
from dotenv import load_dotenv
load_dotenv()
import streamlit as st
from openai import OpenAI
st.title("OpenAI LLM Response")
# Retrieve generated text and prompt from session state
if 'generated_text' not in st.session_state or 'prompt_text' not in st.session_state:
st.error("No generated text found. Please generate text on the main page first.")
else:
generated_text = st.session_state.generated_text
prompt_text = st.session_state.prompt_text
st.markdown("### Generated Output")
st.text_area("", value=generated_text, height=200, key="openai_generated_output")
# Use text input prefilled with the OpenAI API key from .env
default_openai_key = os.getenv("OPENAI_API_KEY") or ""
openai_api_key = st.text_input("Enter your OpenAI API Key", type="password", value=default_openai_key)
if st.button("Send to GPT-4o Mini"):
if openai_api_key:
client = OpenAI(api_key=openai_api_key)
completion = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": generated_text}
]
)
gpt_response = completion.choices[0].message.content
st.markdown("**GPT-4o Mini Response:**")
st.text_area("", value=gpt_response, height=200, key="gpt4o_response")
else:
st.error("Please provide your OpenAI API Key.")