iohanngrig commited on
Commit
1b9bad9
·
verified ·
1 Parent(s): 31dc75f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -112
app.py CHANGED
@@ -12,121 +12,125 @@ client = OpenAI()
12
  # Your chosen model
13
  MODEL = st.secrets["MODEL"]
14
 
15
- # Initialize session state variables
16
- if "session_id" not in st.session_state:
17
- st.session_state.session_id = str(uuid.uuid4())
18
-
19
- if "run" not in st.session_state:
20
- st.session_state.run = {"status": None}
21
-
22
- if "messages" not in st.session_state:
23
- st.session_state.messages = []
24
-
25
- if "retry_error" not in st.session_state:
26
- st.session_state.retry_error = 0
27
-
28
- # Set up the page
29
- st.set_page_config(page_title="Physics Instructor", page_icon="⚖️")
30
- st.header("Feynman AI (GPT based)")
31
- st.sidebar.title("Physics Instructor")
32
- #st.sidebar.divider()
33
-
34
- # File uploader for CSV, XLS, XLSX
35
- uploaded_file = st.file_uploader("Upload your file", type=["csv", "xls", "xlsx"])
36
-
37
- if uploaded_file is not None:
38
- # Determine the file type
39
- file_type = uploaded_file.type
40
- try:
41
- # Read the file into a Pandas DataFrame
42
- if file_type == "text/csv":
43
- df = pd.read_csv(uploaded_file)
44
- elif file_type in ["application/vnd.ms-excel",
45
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]:
46
- df = pd.read_excel(uploaded_file)
47
-
48
- # Convert DataFrame to JSON
49
- json_str = df.to_json(orient='records', indent=4)
50
- file_stream = io.BytesIO(json_str.encode())
51
-
52
- # Upload JSON data to OpenAI and store the file ID
53
- file_response = client.files.create(file=file_stream, purpose='answers')
54
- st.session_state.file_id = file_response.id
55
- st.success("File uploaded successfully to OpenAI!")
56
-
57
- # Optional: Display and Download JSON
58
- st.text_area("JSON Output", json_str, height=300)
59
- st.download_button(label="Download JSON", data=json_str, file_name="converted.json", mime="application/json")
60
- except Exception as e:
61
- st.error(f"An error occurred: {e}")
62
-
63
- # Initialize OpenAI assistant
64
- if "assistant" not in st.session_state:
65
- openai.api_key = st.secrets["OPENAIAPIKEY"]
66
- st.session_state.assistant = openai.beta.assistants.retrieve(st.secrets["OPENAIASSISTANT"])
67
- st.session_state.thread = client.beta.threads.create(
68
- metadata={'session_id': st.session_state.session_id}
69
- )
70
-
71
- # Display chat messages
72
- elif hasattr(st.session_state.run, 'status') and st.session_state.run.status == "completed":
73
- st.session_state.messages = client.beta.threads.messages.list(
74
- thread_id=st.session_state.thread.id
75
- )
76
- for message in reversed(st.session_state.messages.data):
77
- if message.role in ["user", "assistant"]:
78
- with st.chat_message(message.role):
79
- for content_part in message.content:
80
- message_text = content_part.text.value
81
- st.markdown(message_text)
82
-
83
- # Chat input and message creation with file ID
84
- if prompt := st.chat_input("How can I help you?"):
85
- with st.chat_message('user'):
86
- st.write(prompt)
87
-
88
- message_data = {
89
- "thread_id": st.session_state.thread.id,
90
- "role": "user",
91
- "content": prompt
92
- }
93
- # Include file ID in the request if available
94
- if "file_id" in st.session_state:
95
- message_data["file_ids"] = [st.session_state.file_id]
96
-
97
- st.session_state.messages = client.beta.threads.messages.create(**message_data)
98
-
99
- st.session_state.run = client.beta.threads.runs.create(
100
- thread_id=st.session_state.thread.id,
101
- assistant_id=st.session_state.assistant.id,
102
- )
103
- if st.session_state.retry_error < 3:
104
- time.sleep(1)
105
- st.rerun()
106
-
107
- # Handle run status
108
- if hasattr(st.session_state.run, 'status'):
109
- if st.session_state.run.status == "running":
110
- with st.chat_message('assistant'):
111
- st.write("Thinking ......")
112
  if st.session_state.retry_error < 3:
113
  time.sleep(1)
114
  st.rerun()
115
- elif st.session_state.run.status == "failed":
116
- st.session_state.retry_error += 1
117
- with st.chat_message('assistant'):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  if st.session_state.retry_error < 3:
119
- st.write("Run failed, retrying ......")
120
  time.sleep(3)
121
  st.rerun()
122
- else:
123
- st.error(
124
- "FAILED: The OpenAI API is currently processing too many requests. Please try again later ......")
125
- elif st.session_state.run.status != "completed":
126
- st.session_state.run = client.beta.threads.runs.retrieve(
127
- thread_id=st.session_state.thread.id,
128
- run_id=st.session_state.run.id,
129
- )
130
- if st.session_state.retry_error < 3:
131
- time.sleep(3)
132
- st.rerun()
 
12
  # Your chosen model
13
  MODEL = st.secrets["MODEL"]
14
 
15
+ def main():
16
+ # Initialize session state variables
17
+ if "session_id" not in st.session_state:
18
+ st.session_state.session_id = str(uuid.uuid4())
19
+
20
+ if "run" not in st.session_state:
21
+ st.session_state.run = {"status": None}
22
+
23
+ if "messages" not in st.session_state:
24
+ st.session_state.messages = []
25
+
26
+ if "retry_error" not in st.session_state:
27
+ st.session_state.retry_error = 0
28
+
29
+ # Set up the page
30
+ st.set_page_config(page_title="Physics Instructor", page_icon="⚖️")
31
+ st.header("Feynman AI (GPT based)")
32
+ st.sidebar.title("Physics Instructor")
33
+ #st.sidebar.divider()
34
+
35
+ # File uploader for CSV, XLS, XLSX
36
+ uploaded_file = st.file_uploader("Upload your file", type=["csv", "xls", "xlsx"])
37
+
38
+ if uploaded_file is not None:
39
+ # Determine the file type
40
+ file_type = uploaded_file.type
41
+ try:
42
+ # Read the file into a Pandas DataFrame
43
+ if file_type == "text/csv":
44
+ df = pd.read_csv(uploaded_file)
45
+ elif file_type in ["application/vnd.ms-excel",
46
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]:
47
+ df = pd.read_excel(uploaded_file)
48
+
49
+ # Convert DataFrame to JSON
50
+ json_str = df.to_json(orient='records', indent=4)
51
+ file_stream = io.BytesIO(json_str.encode())
52
+
53
+ # Upload JSON data to OpenAI and store the file ID
54
+ file_response = client.files.create(file=file_stream, purpose='answers')
55
+ st.session_state.file_id = file_response.id
56
+ st.success("File uploaded successfully to OpenAI!")
57
+
58
+ # Optional: Display and Download JSON
59
+ st.text_area("JSON Output", json_str, height=300)
60
+ st.download_button(label="Download JSON", data=json_str, file_name="converted.json", mime="application/json")
61
+ except Exception as e:
62
+ st.error(f"An error occurred: {e}")
63
+
64
+ # Initialize OpenAI assistant
65
+ if "assistant" not in st.session_state:
66
+ openai.api_key = st.secrets["OPENAIAPIKEY"]
67
+ st.session_state.assistant = openai.beta.assistants.retrieve(st.secrets["OPENAIASSISTANT"])
68
+ st.session_state.thread = client.beta.threads.create(
69
+ metadata={'session_id': st.session_state.session_id}
70
+ )
71
+
72
+ # Display chat messages
73
+ elif hasattr(st.session_state.run, 'status') and st.session_state.run.status == "completed":
74
+ st.session_state.messages = client.beta.threads.messages.list(
75
+ thread_id=st.session_state.thread.id
76
+ )
77
+ for message in reversed(st.session_state.messages.data):
78
+ if message.role in ["user", "assistant"]:
79
+ with st.chat_message(message.role):
80
+ for content_part in message.content:
81
+ message_text = content_part.text.value
82
+ st.markdown(message_text)
83
+
84
+ # Chat input and message creation with file ID
85
+ if prompt := st.chat_input("How can I help you?"):
86
+ with st.chat_message('user'):
87
+ st.write(prompt)
88
+
89
+ message_data = {
90
+ "thread_id": st.session_state.thread.id,
91
+ "role": "user",
92
+ "content": prompt
93
+ }
94
+ # Include file ID in the request if available
95
+ if "file_id" in st.session_state:
96
+ message_data["file_ids"] = [st.session_state.file_id]
97
+
98
+ st.session_state.messages = client.beta.threads.messages.create(**message_data)
99
+
100
+ st.session_state.run = client.beta.threads.runs.create(
101
+ thread_id=st.session_state.thread.id,
102
+ assistant_id=st.session_state.assistant.id,
103
+ )
 
 
 
 
 
 
 
 
104
  if st.session_state.retry_error < 3:
105
  time.sleep(1)
106
  st.rerun()
107
+
108
+ # Handle run status
109
+ if hasattr(st.session_state.run, 'status'):
110
+ if st.session_state.run.status == "running":
111
+ with st.chat_message('assistant'):
112
+ st.write("Thinking ......")
113
+ if st.session_state.retry_error < 3:
114
+ time.sleep(1)
115
+ st.rerun()
116
+ elif st.session_state.run.status == "failed":
117
+ st.session_state.retry_error += 1
118
+ with st.chat_message('assistant'):
119
+ if st.session_state.retry_error < 3:
120
+ st.write("Run failed, retrying ......")
121
+ time.sleep(3)
122
+ st.rerun()
123
+ else:
124
+ st.error(
125
+ "FAILED: The OpenAI API is currently processing too many requests. Please try again later ......")
126
+ elif st.session_state.run.status != "completed":
127
+ st.session_state.run = client.beta.threads.runs.retrieve(
128
+ thread_id=st.session_state.thread.id,
129
+ run_id=st.session_state.run.id,
130
+ )
131
  if st.session_state.retry_error < 3:
 
132
  time.sleep(3)
133
  st.rerun()
134
+
135
+ if __name__ == "__main__":
136
+ main()