sammy786 commited on
Commit
651e67e
Β·
verified Β·
1 Parent(s): 85bab3a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -95
app.py CHANGED
@@ -182,45 +182,32 @@ def get_recommendation_with_agent(user_id, merchant, category, amount):
182
 
183
  result = response.json()
184
 
185
- # βœ… FIX: Ensure result is a dict
186
  if not isinstance(result, dict):
187
- yield f"❌ Invalid response type: {type(result)}\n\n```\n{str(result)[:500]}\n```", None
188
  return
189
 
190
  print(f"πŸ” KEYS: {list(result.keys())}")
191
 
192
- # Extract with safe_get (handles None/non-dict)
193
- recommendation = result.get('recommendation') if isinstance(result, dict) else {}
194
- if not isinstance(recommendation, dict):
195
- recommendation = {}
196
-
197
- if not recommendation:
198
- rec_card = result.get('recommended_card', {})
199
- if isinstance(rec_card, dict):
200
- recommendation = {
201
- 'card_name': rec_card.get('card_name', 'Unknown'),
202
- 'rewards_earned': rec_card.get('reward_amount', 0),
203
- 'rewards_rate': f"{rec_card.get('reward_rate', 0)}x",
204
- 'confidence': 0.85
205
- }
206
-
207
- reasoning_data = result.get('reasoning', {})
208
- if not isinstance(reasoning_data, dict):
209
- reasoning_data = {}
210
-
211
- if not reasoning_data.get('main'):
212
- reasoning_data = {'main': result.get('final_recommendation', 'No reasoning provided')}
213
-
214
- card_name = recommendation.get('card_name', 'Unknown Card')
215
- rewards_earned = float(recommendation.get('rewards_earned', 0))
216
- rewards_rate = recommendation.get('rewards_rate', 'N/A')
217
- confidence = float(recommendation.get('confidence', 0))
218
-
219
- print(f"βœ… PARSED: {card_name}, ${rewards_earned}, {rewards_rate}")
220
-
221
- if card_name == 'Unknown Card' and rewards_earned == 0:
222
- yield f"⚠️ **Debug:** Response received but empty\n\n```json\n{json.dumps(result, indent=2)[:1000]}\n```", None
223
- return
224
 
225
  output = f"""## πŸ€– AI Agent Recommendation
226
 
@@ -233,9 +220,33 @@ def get_recommendation_with_agent(user_id, merchant, category, amount):
233
 
234
  ### 🧠 Agent's Reasoning:
235
 
236
- {reasoning_data.get('main', 'No reasoning')}
237
 
238
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
 
240
  ### πŸ“Š Transaction Details:
241
  - **Amount:** ${amount:.2f}
@@ -250,95 +261,63 @@ def get_recommendation_with_agent(user_id, merchant, category, amount):
250
  import traceback
251
  print(f"❌ ERROR: {traceback.format_exc()}")
252
  yield f"❌ **Error:** {str(e)}", None
253
-
254
 
255
  def create_agent_recommendation_chart_enhanced(result: Dict) -> go.Figure:
256
- """Create enhanced chart showing agent's recommendation with alternatives"""
257
  try:
258
- # Extract recommendation data
259
- recommendation = safe_get(result, 'recommendation', {})
260
- reasoning_data = safe_get(result, 'reasoning', {})
261
-
262
- # Get recommended card
263
- rec_name = safe_get(recommendation, 'card_name',
264
- safe_get(recommendation, 'recommended_card', 'Recommended Card'))
265
- rec_reward = float(safe_get(recommendation, 'rewards_earned', 0))
266
 
267
- # Get alternatives
268
- alternatives = safe_get(reasoning_data, 'alternative_options', [])
 
269
 
270
  cards = [rec_name]
271
  rewards = [rec_reward]
272
- colors = ['#667eea'] # Purple for recommended
273
-
274
- # Add alternatives
275
- for alt in alternatives[:3]: # Limit to top 3
276
- if isinstance(alt, dict):
277
- alt_card = safe_get(alt, 'card', 'Alternative')
278
- # Try to extract reward amount from reason text if available
279
- alt_reward = rec_reward * 0.8 # Estimate if not provided
280
- cards.append(alt_card)
281
- rewards.append(alt_reward)
282
- colors.append('#cbd5e0') # Gray for alternatives
283
-
284
- # Only create chart if we have valid data
285
- if not cards or all(r == 0 for r in rewards):
286
- fig = go.Figure()
287
- fig.add_annotation(
288
- text="No comparison data available",
289
- xref="paper", yref="paper",
290
- x=0.5, y=0.5, showarrow=False,
291
- font=dict(size=14, color="#666")
292
- )
293
- fig.update_layout(height=400, template='plotly_white')
294
- return fig
295
 
296
- # Create bar chart
297
  fig = go.Figure(data=[
298
  go.Bar(
299
  x=cards,
300
  y=rewards,
301
- marker=dict(
302
- color=colors,
303
- line=dict(color='white', width=2)
304
- ),
305
  text=[f'${r:.2f}' for r in rewards],
306
- textposition='outside',
307
- hovertemplate='<b>%{x}</b><br>Rewards: $%{y:.2f}<extra></extra>'
308
  )
309
  ])
310
 
311
  fig.update_layout(
312
- title={
313
- 'text': '🎯 Agent\'s Card Comparison',
314
- 'x': 0.5,
315
- 'xanchor': 'center'
316
- },
317
  xaxis_title='Credit Card',
318
- yaxis_title='Rewards Earned ($)',
319
  template='plotly_white',
320
  height=400,
321
- showlegend=False,
322
- margin=dict(t=60, b=50, l=50, r=50)
323
  )
324
 
325
  return fig
326
 
327
  except Exception as e:
328
  print(f"Chart error: {e}")
329
- import traceback
330
- print(traceback.format_exc())
331
-
332
  fig = go.Figure()
333
- fig.add_annotation(
334
- text="Chart unavailable",
335
- xref="paper", yref="paper",
336
- x=0.5, y=0.5, showarrow=False,
337
- font=dict(size=14, color="#666")
338
- )
339
  fig.update_layout(height=400, template='plotly_white')
340
  return fig
341
-
342
 
343
  # Initialize clients
344
  client = RewardPilotClient(config.ORCHESTRATOR_URL)
 
182
 
183
  result = response.json()
184
 
 
185
  if not isinstance(result, dict):
186
+ yield f"❌ Invalid response type: {type(result)}", None
187
  return
188
 
189
  print(f"πŸ” KEYS: {list(result.keys())}")
190
 
191
+ # βœ… FIX: Data is at top level, not nested
192
+ card_id = result.get('recommended_card', 'Unknown')
193
+ rewards_earned = float(result.get('rewards_earned', 0))
194
+ rewards_rate = result.get('rewards_rate', 'N/A')
195
+ confidence = float(result.get('confidence', 0))
196
+ reasoning = result.get('reasoning', 'No reasoning provided')
197
+ alternatives = result.get('alternative_options', [])
198
+ warnings = result.get('warnings', [])
199
+ annual_impact = result.get('annual_impact', {})
200
+
201
+ # Map card_id to card_name
202
+ card_name_map = {
203
+ 'c_citi_custom_cash': 'Citi Custom Cash',
204
+ 'c_amex_gold': 'American Express Gold',
205
+ 'c_chase_sapphire_reserve': 'Chase Sapphire Reserve',
206
+ 'c_chase_freedom_unlimited': 'Chase Freedom Unlimited'
207
+ }
208
+ card_name = card_name_map.get(card_id, card_id.replace('c_', '').replace('_', ' ').title())
209
+
210
+ print(f"βœ… PARSED: {card_name}, ${rewards_earned}, {rewards_rate}, {confidence}")
 
 
 
 
 
 
 
 
 
 
 
 
211
 
212
  output = f"""## πŸ€– AI Agent Recommendation
213
 
 
220
 
221
  ### 🧠 Agent's Reasoning:
222
 
223
+ {reasoning}
224
 
225
  ---
226
+ """
227
+
228
+ if alternatives:
229
+ output += "\n### πŸ”„ Alternative Options:\n\n"
230
+ for alt in alternatives[:3]:
231
+ alt_card_id = alt.get('card', '')
232
+ alt_card_name = card_name_map.get(alt_card_id, alt_card_id.replace('c_', '').replace('_', ' ').title())
233
+ alt_reason = alt.get('reason', '')
234
+ output += f"**{alt_card_name}:**\n{alt_reason}\n\n"
235
+
236
+ if warnings:
237
+ output += "\n### ⚠️ Important Warnings:\n\n"
238
+ for warning in warnings:
239
+ output += f"- {warning}\n"
240
+
241
+ if annual_impact:
242
+ potential_savings = annual_impact.get('potential_savings', 0)
243
+ optimization_score = annual_impact.get('optimization_score', 0)
244
+ output += f"\n### πŸ’° Annual Impact:\n"
245
+ output += f"- **Potential Savings:** ${potential_savings:.2f}/year\n"
246
+ output += f"- **Optimization Score:** {optimization_score}/100\n"
247
+
248
+ output += f"""
249
+ ---
250
 
251
  ### πŸ“Š Transaction Details:
252
  - **Amount:** ${amount:.2f}
 
261
  import traceback
262
  print(f"❌ ERROR: {traceback.format_exc()}")
263
  yield f"❌ **Error:** {str(e)}", None
264
+
265
 
266
  def create_agent_recommendation_chart_enhanced(result: Dict) -> go.Figure:
 
267
  try:
268
+ # βœ… FIX: Extract from top level
269
+ rec_name_map = {
270
+ 'c_citi_custom_cash': 'Citi Custom Cash',
271
+ 'c_amex_gold': 'Amex Gold',
272
+ 'c_chase_sapphire_reserve': 'Sapphire Reserve',
273
+ 'c_chase_freedom_unlimited': 'Freedom Unlimited'
274
+ }
 
275
 
276
+ rec_id = result.get('recommended_card', '')
277
+ rec_name = rec_name_map.get(rec_id, rec_id)
278
+ rec_reward = float(result.get('rewards_earned', 0))
279
 
280
  cards = [rec_name]
281
  rewards = [rec_reward]
282
+ colors = ['#667eea']
283
+
284
+ alternatives = result.get('alternative_options', [])
285
+ for alt in alternatives[:3]:
286
+ alt_id = alt.get('card', '')
287
+ alt_name = rec_name_map.get(alt_id, alt_id)
288
+ # Extract reward from reason text if possible
289
+ alt_reward = rec_reward * 0.8 # Estimate
290
+ cards.append(alt_name)
291
+ rewards.append(alt_reward)
292
+ colors.append('#cbd5e0')
 
 
 
 
 
 
 
 
 
 
 
 
293
 
 
294
  fig = go.Figure(data=[
295
  go.Bar(
296
  x=cards,
297
  y=rewards,
298
+ marker=dict(color=colors, line=dict(color='white', width=2)),
 
 
 
299
  text=[f'${r:.2f}' for r in rewards],
300
+ textposition='outside'
 
301
  )
302
  ])
303
 
304
  fig.update_layout(
305
+ title='🎯 Card Comparison',
 
 
 
 
306
  xaxis_title='Credit Card',
307
+ yaxis_title='Rewards ($)',
308
  template='plotly_white',
309
  height=400,
310
+ showlegend=False
 
311
  )
312
 
313
  return fig
314
 
315
  except Exception as e:
316
  print(f"Chart error: {e}")
 
 
 
317
  fig = go.Figure()
318
+ fig.add_annotation(text="Chart unavailable", xref="paper", yref="paper", x=0.5, y=0.5, showarrow=False)
 
 
 
 
 
319
  fig.update_layout(height=400, template='plotly_white')
320
  return fig
 
321
 
322
  # Initialize clients
323
  client = RewardPilotClient(config.ORCHESTRATOR_URL)