Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import requests
|
| 3 |
+
import os
|
| 4 |
+
from openai import OpenAI
|
| 5 |
+
|
| 6 |
+
# Initialize the OpenAI client
|
| 7 |
+
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
| 8 |
+
|
| 9 |
+
def fetch_data_from_api(url):
|
| 10 |
+
response = requests.get(url)
|
| 11 |
+
if response.status_code == 200:
|
| 12 |
+
return response.json()
|
| 13 |
+
else:
|
| 14 |
+
return None
|
| 15 |
+
|
| 16 |
+
def generate_summary(data):
|
| 17 |
+
if data is None or not isinstance(data, dict):
|
| 18 |
+
return "Error: Data is not available or not in the expected format"
|
| 19 |
+
text = " ".join(str(value) for value in data.values())
|
| 20 |
+
return text
|
| 21 |
+
|
| 22 |
+
def generate_chat_response(summary, data, client):
|
| 23 |
+
try:
|
| 24 |
+
chat_completion = client.chat.completions.create(
|
| 25 |
+
messages=[{"role": "user", "content": f"{summary} {data}"}],
|
| 26 |
+
model="gpt-3.5-turbo",
|
| 27 |
+
)
|
| 28 |
+
return chat_completion.choices[0].message['content']
|
| 29 |
+
except Exception as e:
|
| 30 |
+
return f"Failed to generate chat response: {e}"
|
| 31 |
+
|
| 32 |
+
def main():
|
| 33 |
+
st.title("Display Data from API and Generate Chat Response")
|
| 34 |
+
|
| 35 |
+
# Fetch OpenAI API key from UI input
|
| 36 |
+
openai_api_key = st.text_input("Enter your OpenAI API key:", type="password")
|
| 37 |
+
|
| 38 |
+
api_endpoint = st.text_input("Enter the API endpoint:")
|
| 39 |
+
if api_endpoint and openai_api_key:
|
| 40 |
+
# Initialize the OpenAI client with the UI provided API key
|
| 41 |
+
client = OpenAI(api_key=openai_api_key)
|
| 42 |
+
|
| 43 |
+
data = fetch_data_from_api(api_endpoint)
|
| 44 |
+
if data:
|
| 45 |
+
st.subheader("Data from API")
|
| 46 |
+
st.write(data)
|
| 47 |
+
summary = generate_summary(data)
|
| 48 |
+
st.subheader("Summary Generated")
|
| 49 |
+
st.write(summary)
|
| 50 |
+
chat_response = generate_chat_response(summary, data, client)
|
| 51 |
+
st.subheader("Chat Response Generated")
|
| 52 |
+
st.write(chat_response)
|
| 53 |
+
else:
|
| 54 |
+
st.write("Error: Failed to fetch data from the API endpoint")
|
| 55 |
+
elif not openai_api_key:
|
| 56 |
+
st.warning("Please enter your OpenAI API key.")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
if __name__ == "__main__":
|
| 60 |
+
main()
|
| 61 |
+
|