api-gpt-summary / app.py
Blessin's picture
Create app.py
8fa6b29 verified
import streamlit as st
import requests
import os
from openai import OpenAI
# Initialize the OpenAI client
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
def fetch_data_from_api(url):
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return None
def generate_summary(data):
if data is None or not isinstance(data, dict):
return "Error: Data is not available or not in the expected format"
text = " ".join(str(value) for value in data.values())
return text
def generate_chat_response(summary, data, client):
try:
chat_completion = client.chat.completions.create(
messages=[{"role": "user", "content": f"{summary} {data}"}],
model="gpt-3.5-turbo",
)
return chat_completion.choices[0].message['content']
except Exception as e:
return f"Failed to generate chat response: {e}"
def main():
st.title("Display Data from API and Generate Chat Response")
# Fetch OpenAI API key from UI input
openai_api_key = st.text_input("Enter your OpenAI API key:", type="password")
api_endpoint = st.text_input("Enter the API endpoint:")
if api_endpoint and openai_api_key:
# Initialize the OpenAI client with the UI provided API key
client = OpenAI(api_key=openai_api_key)
data = fetch_data_from_api(api_endpoint)
if data:
st.subheader("Data from API")
st.write(data)
summary = generate_summary(data)
st.subheader("Summary Generated")
st.write(summary)
chat_response = generate_chat_response(summary, data, client)
st.subheader("Chat Response Generated")
st.write(chat_response)
else:
st.write("Error: Failed to fetch data from the API endpoint")
elif not openai_api_key:
st.warning("Please enter your OpenAI API key.")
if __name__ == "__main__":
main()