Seth0330 commited on
Commit
b22ffb2
·
verified ·
1 Parent(s): ed83876

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -65
app.py CHANGED
@@ -98,6 +98,7 @@ function_map = {
98
  # --- Conversation memory: Use Streamlit session state
99
  if "messages" not in st.session_state:
100
  st.session_state.messages = []
 
101
  if "temp_input" not in st.session_state:
102
  st.session_state.temp_input = ""
103
 
@@ -135,78 +136,74 @@ for i, msg in enumerate(st.session_state.messages[1:]): # Skip system message f
135
  except Exception:
136
  st.markdown(f"<b>Function '{msg['name']}' output:</b> {msg['content']}", unsafe_allow_html=True)
137
 
138
- # --- User input box at bottom (like ChatGPT)
139
- if df is not None:
140
- user_input = st.text_input("Your message:", value=st.session_state.temp_input, key="temp_input")
141
- send = st.button("Send")
142
- else:
143
- user_input = None
144
- send = False
145
-
146
- if send and user_input and user_input.strip():
147
- # Append user's message to conversation
148
- st.session_state.messages.append({"role": "user", "content": user_input})
149
-
150
- # Compose messages for OpenAI (entire chat history)
151
- chat_messages = st.session_state.messages.copy()
152
-
153
- # First OpenAI call: Check for function call
154
- chat_resp = requests.post(
155
- "https://api.openai.com/v1/chat/completions",
156
- headers=HEADERS,
157
- json={
158
- "model": "gpt-3.5-turbo-1106",
159
- "messages": chat_messages,
160
- "functions": function_schema,
161
- "function_call": "auto",
162
- "temperature": 0,
163
- "max_tokens": 1000,
164
- },
165
- timeout=60,
166
- )
167
- chat_resp.raise_for_status()
168
- response_json = chat_resp.json()
169
- msg = response_json["choices"][0]["message"]
170
-
171
- # If OpenAI requests a function call
172
- if msg.get("function_call"):
173
- func_name = msg["function_call"]["name"]
174
- args_json = msg["function_call"]["arguments"]
175
- args = json.loads(args_json)
176
- # Call the correct Python function
177
- if func_name in function_map:
178
- function_result = function_map[func_name](**args)
179
- else:
180
- function_result = {"error": f"Unknown function: {func_name}"}
181
- # Append function call and output to history
182
- st.session_state.messages.append({
183
- "role": "function",
184
- "name": func_name,
185
- "content": json.dumps(function_result),
186
- })
187
-
188
- # Second OpenAI call: Get final answer with function result
189
- followup_messages = st.session_state.messages.copy()
190
- final_resp = requests.post(
191
  "https://api.openai.com/v1/chat/completions",
192
  headers=HEADERS,
193
  json={
194
  "model": "gpt-3.5-turbo-1106",
195
- "messages": followup_messages,
 
 
196
  "temperature": 0,
197
- "max_tokens": 1500,
198
  },
199
  timeout=60,
200
  )
201
- final_resp.raise_for_status()
202
- answer = final_resp.json()["choices"][0]["message"]["content"]
203
- # Add assistant's reply to chat
204
- st.session_state.messages.append({"role": "assistant", "content": answer})
205
- else:
206
- # No function call: Just add model's reply
207
- st.session_state.messages.append({"role": "assistant", "content": msg["content"]})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
 
209
- # Clear input after sending (no session state error!)
210
- st.session_state.temp_input = ""
211
- # The UI will update automatically
212
 
 
 
 
 
98
  # --- Conversation memory: Use Streamlit session state
99
  if "messages" not in st.session_state:
100
  st.session_state.messages = []
101
+
102
  if "temp_input" not in st.session_state:
103
  st.session_state.temp_input = ""
104
 
 
136
  except Exception:
137
  st.markdown(f"<b>Function '{msg['name']}' output:</b> {msg['content']}", unsafe_allow_html=True)
138
 
139
+ # --- Sending user input and OpenAI call logic using a callback
140
+ def send_message():
141
+ user_input = st.session_state.temp_input
142
+ if user_input and user_input.strip():
143
+ st.session_state.messages.append({"role": "user", "content": user_input})
144
+
145
+ # Compose messages for OpenAI (entire chat history)
146
+ chat_messages = st.session_state.messages.copy()
147
+
148
+ # First OpenAI call: Check for function call
149
+ chat_resp = requests.post(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  "https://api.openai.com/v1/chat/completions",
151
  headers=HEADERS,
152
  json={
153
  "model": "gpt-3.5-turbo-1106",
154
+ "messages": chat_messages,
155
+ "functions": function_schema,
156
+ "function_call": "auto",
157
  "temperature": 0,
158
+ "max_tokens": 1000,
159
  },
160
  timeout=60,
161
  )
162
+ chat_resp.raise_for_status()
163
+ response_json = chat_resp.json()
164
+ msg = response_json["choices"][0]["message"]
165
+
166
+ # If OpenAI requests a function call
167
+ if msg.get("function_call"):
168
+ func_name = msg["function_call"]["name"]
169
+ args_json = msg["function_call"]["arguments"]
170
+ args = json.loads(args_json)
171
+ # Call the correct Python function
172
+ if func_name in function_map:
173
+ function_result = function_map[func_name](**args)
174
+ else:
175
+ function_result = {"error": f"Unknown function: {func_name}"}
176
+ # Append function call and output to history
177
+ st.session_state.messages.append({
178
+ "role": "function",
179
+ "name": func_name,
180
+ "content": json.dumps(function_result),
181
+ })
182
+
183
+ # Second OpenAI call: Get final answer with function result
184
+ followup_messages = st.session_state.messages.copy()
185
+ final_resp = requests.post(
186
+ "https://api.openai.com/v1/chat/completions",
187
+ headers=HEADERS,
188
+ json={
189
+ "model": "gpt-3.5-turbo-1106",
190
+ "messages": followup_messages,
191
+ "temperature": 0,
192
+ "max_tokens": 1500,
193
+ },
194
+ timeout=60,
195
+ )
196
+ final_resp.raise_for_status()
197
+ answer = final_resp.json()["choices"][0]["message"]["content"]
198
+ # Add assistant's reply to chat
199
+ st.session_state.messages.append({"role": "assistant", "content": answer})
200
+ else:
201
+ # No function call: Just add model's reply
202
+ st.session_state.messages.append({"role": "assistant", "content": msg["content"]})
203
 
204
+ # Clear input after sending (now legal and safe)
205
+ st.session_state.temp_input = ""
 
206
 
207
+ # --- User input box at bottom (like ChatGPT)
208
+ if df is not None:
209
+ st.text_input("Your message:", key="temp_input", on_change=send_message)