sammy786 commited on
Commit
3faedf5
Β·
verified Β·
1 Parent(s): e3d42e6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -98
app.py CHANGED
@@ -148,13 +148,9 @@ import config
148
 
149
 
150
  def get_recommendation_with_agent(user_id, merchant, category, amount):
151
- """
152
- Get recommendation using autonomous agent
153
- Shows loading state, then agent's reasoning
154
- """
155
  import httpx
 
156
 
157
- # Show loading first
158
  yield "⏳ **Agent is thinking...** Analyzing your transaction and cards...", None
159
 
160
  try:
@@ -166,136 +162,82 @@ def get_recommendation_with_agent(user_id, merchant, category, amount):
166
  "amount_usd": float(amount)
167
  }
168
 
169
- # Call orchestrator (which now uses agent)
 
 
 
170
  response = httpx.post(
171
  f"{config.ORCHESTRATOR_URL}/recommend",
172
  json=transaction,
173
- timeout=60.0 # Agent needs more time
174
  )
175
 
 
 
 
 
176
  if response.status_code != 200:
177
  yield f"❌ Error: API returned status {response.status_code}", None
178
  return
179
 
180
  result = response.json()
 
181
 
182
- # βœ… FIXED: Extract data from new response format
183
  recommendation = safe_get(result, 'recommendation', {})
184
- reasoning_data = safe_get(result, 'reasoning', {})
185
- services_data = safe_get(result, 'services_used', {})
186
- metadata = safe_get(result, 'agent_metadata', {})
187
- transaction_info = safe_get(result, 'transaction', {})
188
- plan = safe_get(result, 'plan', {})
189
-
190
- # Extract card info
191
- card_name = safe_get(recommendation, 'card_name',
192
- safe_get(recommendation, 'recommended_card', 'Unknown Card'))
193
- rewards_earned = safe_get(recommendation, 'rewards_earned', 0)
194
- rewards_rate = safe_get(recommendation, 'rewards_rate', 'N/A')
195
- confidence = safe_get(recommendation, 'confidence', 0)
196
- confidence_label = safe_get(recommendation, 'confidence_label', 'Unknown')
197
 
198
- # Extract reasoning
199
- main_reasoning = safe_get(reasoning_data, 'main', 'No reasoning provided')
200
- why_points = safe_get(reasoning_data, 'why_this_card', [])
201
- alternatives = safe_get(reasoning_data, 'alternative_options', [])
202
- warnings = safe_get(reasoning_data, 'warnings', [])
203
-
204
- # Extract insights
205
- insights = safe_get(result, 'insights', {})
206
- annual_impact = safe_get(insights, 'annual_impact', {})
207
- optimization_score = safe_get(insights, 'optimization_score', 0)
208
 
209
- # Extract transaction details
210
- tx_amount = safe_get(transaction_info, 'amount', amount)
211
- tx_merchant = safe_get(transaction_info, 'merchant', merchant)
212
- tx_category = safe_get(transaction_info, 'category', category)
213
 
214
- # Extract service statuses
215
- services_used = []
216
- for service_name, service_data in services_data.items():
217
- if isinstance(service_data, dict) and safe_get(service_data, 'status') == 'success':
218
- services_used.append(service_name)
219
 
220
- # Processing time
221
- processing_time = safe_get(metadata, 'processing_time_ms', 0)
 
222
 
223
- # βœ… Format comprehensive output
224
  output = f"""## πŸ€– AI Agent Recommendation
225
 
226
  ### πŸ’³ Recommended Card: **{card_name}**
227
 
228
  **Rewards Earned:** ${rewards_earned:.2f} ({rewards_rate})
229
- **Confidence:** {confidence_label} ({confidence*100:.0f}%)
230
 
231
  ---
232
 
233
  ### 🧠 Agent's Reasoning:
234
 
235
- {main_reasoning}
236
- """
237
-
238
- # Add key points
239
- if why_points:
240
- output += "\n\n**Why This Card:**\n"
241
- for point in why_points[:3]:
242
- output += f"- {point}\n"
243
-
244
- output += f"""
245
  ---
246
 
247
  ### πŸ“Š Transaction Details:
248
- - **Amount:** ${tx_amount:.2f}
249
- - **Merchant:** {tx_merchant}
250
- - **Category:** {tx_category}
251
-
252
- ### βš™οΈ Agent Performance:
253
- - **Services Used:** {', '.join(services_used) if services_used else 'N/A'}
254
- - **Processing Time:** {processing_time:.0f}ms
255
- - **Planning Confidence:** {safe_get(metadata, 'planning_confidence', 0)*100:.0f}%
256
  """
257
 
258
- # Add annual impact if available
259
- if annual_impact:
260
- potential_savings = safe_get(annual_impact, 'potential_savings', 0)
261
- if potential_savings > 0:
262
- output += f"\n### πŸ’° Annual Impact:\n- **Potential Savings:** ${potential_savings:.2f}/year\n"
263
- output += f"- **Optimization Score:** {optimization_score}/100\n"
264
-
265
- # Add warnings
266
- if warnings:
267
- output += "\n\n### ⚠️ Important Warnings:\n"
268
- for warning in warnings:
269
- output += f"- {warning}\n"
270
-
271
- # Add alternatives
272
- if alternatives:
273
- output += "\n\n### πŸ”„ Alternative Options:\n"
274
- for alt in alternatives[:3]:
275
- alt_card = safe_get(alt, 'card', 'Unknown')
276
- alt_reason = safe_get(alt, 'reason', 'Alternative option')
277
- output += f"- **{alt_card}:** {alt_reason}\n"
278
-
279
- # Add plan strategy
280
- strategy = safe_get(plan, 'strategy', '')
281
- if strategy:
282
- output += f"\n\n### 🎯 Agent Strategy:\n{strategy}\n"
283
-
284
- output += "\n---\n\nπŸ’‘ **The AI agent analyzed your transaction context, card portfolio, and spending patterns to determine this is your optimal choice.**"
285
-
286
- # βœ… Create enhanced comparison chart
287
  chart = create_agent_recommendation_chart_enhanced(result)
288
-
289
  yield output, chart
290
 
291
- except httpx.TimeoutException:
292
- yield "⏱️ **Request timed out.** The agent is taking longer than expected. Please try again.", None
293
  except Exception as e:
294
  import traceback
295
- error_details = traceback.format_exc()
296
- print(f"Agent recommendation error: {error_details}")
297
- yield f"❌ **Error:** {str(e)}\n\nPlease check the orchestrator service or try again.", None
298
-
299
 
300
  def create_agent_recommendation_chart_enhanced(result: Dict) -> go.Figure:
301
  """Create enhanced chart showing agent's recommendation with alternatives"""
 
148
 
149
 
150
  def get_recommendation_with_agent(user_id, merchant, category, amount):
 
 
 
 
151
  import httpx
152
+ import json
153
 
 
154
  yield "⏳ **Agent is thinking...** Analyzing your transaction and cards...", None
155
 
156
  try:
 
162
  "amount_usd": float(amount)
163
  }
164
 
165
+ print("=" * 80)
166
+ print(f"πŸš€ REQUEST: {config.ORCHESTRATOR_URL}/recommend")
167
+ print(f"PAYLOAD: {json.dumps(transaction, indent=2)}")
168
+
169
  response = httpx.post(
170
  f"{config.ORCHESTRATOR_URL}/recommend",
171
  json=transaction,
172
+ timeout=60.0
173
  )
174
 
175
+ print(f"πŸ“₯ STATUS: {response.status_code}")
176
+ print(f"πŸ“¦ RESPONSE: {response.text[:2000]}")
177
+ print("=" * 80)
178
+
179
  if response.status_code != 200:
180
  yield f"❌ Error: API returned status {response.status_code}", None
181
  return
182
 
183
  result = response.json()
184
+ print(f"πŸ” KEYS: {list(result.keys())}")
185
 
186
+ # Extract with fallbacks
187
  recommendation = safe_get(result, 'recommendation', {})
188
+ if not recommendation:
189
+ rec_card = safe_get(result, 'recommended_card', {})
190
+ if isinstance(rec_card, dict):
191
+ recommendation = {
192
+ 'card_name': safe_get(rec_card, 'card_name', 'Unknown'),
193
+ 'rewards_earned': safe_get(rec_card, 'reward_amount', 0),
194
+ 'rewards_rate': f"{safe_get(rec_card, 'reward_rate', 0)}x",
195
+ 'confidence': 0.85
196
+ }
 
 
 
 
197
 
198
+ reasoning_data = safe_get(result, 'reasoning', {})
199
+ if not reasoning_data.get('main'):
200
+ reasoning_data = {'main': safe_get(result, 'final_recommendation', 'No reasoning provided')}
 
 
 
 
 
 
 
201
 
202
+ card_name = safe_get(recommendation, 'card_name', 'Unknown Card')
203
+ rewards_earned = float(safe_get(recommendation, 'rewards_earned', 0))
204
+ rewards_rate = safe_get(recommendation, 'rewards_rate', 'N/A')
205
+ confidence = float(safe_get(recommendation, 'confidence', 0))
206
 
207
+ print(f"βœ… PARSED: {card_name}, ${rewards_earned}, {rewards_rate}")
 
 
 
 
208
 
209
+ if card_name == 'Unknown Card' and rewards_earned == 0:
210
+ yield f"⚠️ **Debug:** Response received but empty\n\n```json\n{json.dumps(result, indent=2)[:1000]}\n```", None
211
+ return
212
 
 
213
  output = f"""## πŸ€– AI Agent Recommendation
214
 
215
  ### πŸ’³ Recommended Card: **{card_name}**
216
 
217
  **Rewards Earned:** ${rewards_earned:.2f} ({rewards_rate})
218
+ **Confidence:** {confidence*100:.0f}%
219
 
220
  ---
221
 
222
  ### 🧠 Agent's Reasoning:
223
 
224
+ {safe_get(reasoning_data, 'main', 'No reasoning')}
225
+
 
 
 
 
 
 
 
 
226
  ---
227
 
228
  ### πŸ“Š Transaction Details:
229
+ - **Amount:** ${amount:.2f}
230
+ - **Merchant:** {merchant}
231
+ - **Category:** {category}
 
 
 
 
 
232
  """
233
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234
  chart = create_agent_recommendation_chart_enhanced(result)
 
235
  yield output, chart
236
 
 
 
237
  except Exception as e:
238
  import traceback
239
+ print(f"❌ ERROR: {traceback.format_exc()}")
240
+ yield f"❌ **Error:** {str(e)}", None
 
 
241
 
242
  def create_agent_recommendation_chart_enhanced(result: Dict) -> go.Figure:
243
  """Create enhanced chart showing agent's recommendation with alternatives"""