Seth0330 commited on
Commit
0405f80
·
verified ·
1 Parent(s): 3c83ca9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -56
app.py CHANGED
@@ -2,10 +2,10 @@ import streamlit as st
2
  import os
3
  import json
4
  import requests
 
5
 
6
  # --- Page config
7
  st.set_page_config(page_title="JSON-Backed AI Chat Agent", layout="wide")
8
-
9
  st.title("JSON-Backed AI Chat Agent")
10
 
11
  # --- Load API key
@@ -66,7 +66,6 @@ if uploaded_files:
66
  "If the user does not specify a file, make your best guess based on keys/fields mentioned."
67
  ),
68
  }
69
- # Reset chat if new files loaded
70
  st.session_state.messages = [system_message]
71
  else:
72
  st.session_state.json_data.clear()
@@ -77,10 +76,10 @@ def search_json(file_name, key, value):
77
  try:
78
  data = st.session_state.json_data[file_name]
79
  if isinstance(data, list):
80
- results = [item for item in data if isinstance(item, dict) and item.get(key) == value]
81
  return results[:10]
82
  elif isinstance(data, dict):
83
- if key in data and data[key] == value:
84
  return [{key: value}]
85
  else:
86
  return []
@@ -180,69 +179,81 @@ def send_message():
180
  chat_messages = [chat_messages[0]] + chat_messages[-9:]
181
  else:
182
  chat_messages = chat_messages.copy()
183
- # OpenAI call
184
- chat_resp = requests.post(
185
- "https://api.openai.com/v1/chat/completions",
186
- headers=HEADERS,
187
- json={
188
- "model": "gpt-4.1", # Use latest available model for this purpose
189
- "messages": chat_messages,
190
- "functions": function_schema,
191
- "function_call": "auto",
192
- "temperature": 0,
193
- "max_tokens": 1000,
194
- },
195
- timeout=60,
196
- )
197
- chat_resp.raise_for_status()
198
- response_json = chat_resp.json()
199
- msg = response_json["choices"][0]["message"]
200
-
201
- # If OpenAI requests a function call
202
- if msg.get("function_call"):
203
- func_name = msg["function_call"]["name"]
204
- args_json = msg["function_call"]["arguments"]
205
- args = json.loads(args_json)
206
- if func_name == "search_json":
207
- function_result = search_json(args.get("file_name"), args.get("key"), args.get("value"))
208
- elif func_name == "list_keys":
209
- function_result = list_keys(args.get("file_name"))
210
- elif func_name == "count_key_occurrences":
211
- function_result = count_key_occurrences(args.get("file_name"), args.get("key"))
212
- else:
213
- function_result = {"error": f"Unknown function: {func_name}"}
214
- st.session_state.messages.append({
215
- "role": "function",
216
- "name": func_name,
217
- "content": json.dumps(function_result),
218
- })
219
- # Second call to OpenAI for the final answer
220
- followup_messages = st.session_state.messages
221
- if len(followup_messages) > 12:
222
- followup_messages = [followup_messages[0]] + followup_messages[-11:]
223
- else:
224
- followup_messages = followup_messages.copy()
225
- final_resp = requests.post(
226
  "https://api.openai.com/v1/chat/completions",
227
  headers=HEADERS,
228
  json={
229
  "model": "gpt-4.1",
230
- "messages": followup_messages,
 
 
231
  "temperature": 0,
232
- "max_tokens": 1500,
233
  },
234
  timeout=60,
235
  )
236
- final_resp.raise_for_status()
237
- answer = final_resp.json()["choices"][0]["message"]["content"]
238
- st.session_state.messages.append({"role": "assistant", "content": answer})
239
- else:
240
- st.session_state.messages.append({"role": "assistant", "content": msg["content"]})
241
 
242
- st.session_state.temp_input = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
 
244
  if st.session_state.json_data:
245
  st.text_input("Your message:", key="temp_input", on_change=send_message)
246
  else:
247
  st.info("Please upload at least one JSON file to start chatting.")
248
-
 
2
  import os
3
  import json
4
  import requests
5
+ import traceback
6
 
7
  # --- Page config
8
  st.set_page_config(page_title="JSON-Backed AI Chat Agent", layout="wide")
 
9
  st.title("JSON-Backed AI Chat Agent")
10
 
11
  # --- Load API key
 
66
  "If the user does not specify a file, make your best guess based on keys/fields mentioned."
67
  ),
68
  }
 
69
  st.session_state.messages = [system_message]
70
  else:
71
  st.session_state.json_data.clear()
 
76
  try:
77
  data = st.session_state.json_data[file_name]
78
  if isinstance(data, list):
79
+ results = [item for item in data if isinstance(item, dict) and str(item.get(key)) == str(value)]
80
  return results[:10]
81
  elif isinstance(data, dict):
82
+ if key in data and str(data[key]) == str(value):
83
  return [{key: value}]
84
  else:
85
  return []
 
179
  chat_messages = [chat_messages[0]] + chat_messages[-9:]
180
  else:
181
  chat_messages = chat_messages.copy()
182
+ try:
183
+ # OpenAI call
184
+ chat_resp = requests.post(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  "https://api.openai.com/v1/chat/completions",
186
  headers=HEADERS,
187
  json={
188
  "model": "gpt-4.1",
189
+ "messages": chat_messages,
190
+ "functions": function_schema,
191
+ "function_call": "auto",
192
  "temperature": 0,
193
+ "max_tokens": 1000,
194
  },
195
  timeout=60,
196
  )
197
+ chat_resp.raise_for_status()
198
+ response_json = chat_resp.json()
199
+ st.write("RAW LLM RESPONSE:", response_json) # DEBUG
 
 
200
 
201
+ msg = response_json["choices"][0]["message"]
202
+
203
+ # If OpenAI requests a function call
204
+ if msg.get("function_call"):
205
+ func_name = msg["function_call"]["name"]
206
+ args_json = msg["function_call"]["arguments"]
207
+ args = json.loads(args_json)
208
+ st.write("Function Call:", func_name, "Args:", args) # DEBUG
209
+
210
+ if func_name == "search_json":
211
+ result = search_json(
212
+ args.get("file_name"), args.get("key"), args.get("value")
213
+ )
214
+ elif func_name == "list_keys":
215
+ result = list_keys(args.get("file_name"))
216
+ elif func_name == "count_key_occurrences":
217
+ result = count_key_occurrences(args.get("file_name"), args.get("key"))
218
+ else:
219
+ result = {"error": f"Unknown function: {func_name}"}
220
+
221
+ st.session_state.messages.append({
222
+ "role": "function",
223
+ "name": func_name,
224
+ "content": json.dumps(result),
225
+ })
226
+ # Second call to OpenAI for the final answer
227
+ followup_messages = st.session_state.messages
228
+ if len(followup_messages) > 12:
229
+ followup_messages = [followup_messages[0]] + followup_messages[-11:]
230
+ else:
231
+ followup_messages = followup_messages.copy()
232
+ final_resp = requests.post(
233
+ "https://api.openai.com/v1/chat/completions",
234
+ headers=HEADERS,
235
+ json={
236
+ "model": "gpt-4.1",
237
+ "messages": followup_messages,
238
+ "temperature": 0,
239
+ "max_tokens": 1500,
240
+ },
241
+ timeout=60,
242
+ )
243
+ final_resp.raise_for_status()
244
+ final_json = final_resp.json()
245
+ st.write("RAW FINAL RESPONSE:", final_json) # DEBUG
246
+ answer = final_json["choices"][0]["message"]["content"]
247
+ st.session_state.messages.append({"role": "assistant", "content": answer})
248
+ else:
249
+ st.session_state.messages.append({"role": "assistant", "content": msg["content"]})
250
+ except Exception as e:
251
+ st.error("Exception: " + str(e))
252
+ st.code(traceback.format_exc())
253
+ finally:
254
+ st.session_state.temp_input = ""
255
 
256
  if st.session_state.json_data:
257
  st.text_input("Your message:", key="temp_input", on_change=send_message)
258
  else:
259
  st.info("Please upload at least one JSON file to start chatting.")