zenaight commited on
Commit
2169ed9
·
1 Parent(s): fcf07bf

Enhance intent extraction and update logging in AI chat

Browse files

- Added detailed logging for LLM responses and intent field updates in the `extract_and_update_intent` function to improve traceability and debugging.
- Implemented content cleanup for JSON responses to handle markdown formatting, ensuring robust parsing of intent data.
- Updated the `update_user_intent` function to include checks for session validity and added logging for successful updates and errors, enhancing error handling and user intent management.

Files changed (2) hide show
  1. ai_chat.py +17 -2
  2. database.py +15 -6
ai_chat.py CHANGED
@@ -148,6 +148,7 @@ async def extract_and_update_intent(state):
148
  """
149
 
150
  response = await llm.ainvoke([{"role":"user","content":extraction_prompt}])
 
151
 
152
  # Check if response is an explanatory answer rather than JSON
153
  if not response.content.strip().startswith("{"):
@@ -156,17 +157,31 @@ async def extract_and_update_intent(state):
156
 
157
  import json
158
  try:
159
- extracted = json.loads(response.content)
160
- except:
 
 
 
 
 
 
 
 
161
  print("Failed to parse intent JSON:", response.content)
 
162
  extracted = {}
163
 
164
  for field in intent_fields:
165
  new_val = extracted.get(field)
166
  old_val = intent.get(field)
167
  if new_val is not None and new_val != old_val:
 
168
  await update_user_intent(session_id, {field: new_val})
169
  intent[field] = new_val
 
 
 
 
170
 
171
  state["intent"] = intent
172
 
 
148
  """
149
 
150
  response = await llm.ainvoke([{"role":"user","content":extraction_prompt}])
151
+ print(f"LLM response for intent extraction: {response.content}")
152
 
153
  # Check if response is an explanatory answer rather than JSON
154
  if not response.content.strip().startswith("{"):
 
157
 
158
  import json
159
  try:
160
+ # Clean up the response content (remove markdown formatting if present)
161
+ content = response.content.strip()
162
+ if content.startswith('```json'):
163
+ content = content[7:] # Remove ```json
164
+ if content.endswith('```'):
165
+ content = content[:-3] # Remove ```
166
+ content = content.strip()
167
+
168
+ extracted = json.loads(content)
169
+ except Exception as e:
170
  print("Failed to parse intent JSON:", response.content)
171
+ print("Error:", e)
172
  extracted = {}
173
 
174
  for field in intent_fields:
175
  new_val = extracted.get(field)
176
  old_val = intent.get(field)
177
  if new_val is not None and new_val != old_val:
178
+ print(f"Updating intent field {field}: {old_val} -> {new_val}")
179
  await update_user_intent(session_id, {field: new_val})
180
  intent[field] = new_val
181
+ elif new_val is not None:
182
+ print(f"Intent field {field} unchanged: {new_val}")
183
+ else:
184
+ print(f"Intent field {field} not extracted")
185
 
186
  state["intent"] = intent
187
 
database.py CHANGED
@@ -272,9 +272,18 @@ async def update_user_intent(session_id: str, updates: dict):
272
  """
273
  Patch the intent record with any changed fields.
274
  """
275
- updates_with_ts = { **updates, "updated_at": datetime.utcnow().isoformat() }
276
- supabase \
277
- .table("user_intents") \
278
- .update(updates_with_ts) \
279
- .eq("session_id", session_id) \
280
- .execute()
 
 
 
 
 
 
 
 
 
 
272
  """
273
  Patch the intent record with any changed fields.
274
  """
275
+ if not supabase or session_id == "local_session":
276
+ print(f"Skipping intent update for session {session_id} (no supabase or local session)")
277
+ return
278
+
279
+ try:
280
+ updates_with_ts = { **updates, "updated_at": datetime.utcnow().isoformat() }
281
+ print(f"Updating user_intents table for session {session_id} with: {updates_with_ts}")
282
+ supabase \
283
+ .table("user_intents") \
284
+ .update(updates_with_ts) \
285
+ .eq("session_id", session_id) \
286
+ .execute()
287
+ print(f"Successfully updated intent for session {session_id}")
288
+ except Exception as e:
289
+ print(f"Error updating user intent: {e}")