File size: 1,985 Bytes
8fa6b29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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()