Update app.py
Browse files
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 |
-
|
|
|
|
|
|
|
|
|
|
| 170 |
response = httpx.post(
|
| 171 |
f"{config.ORCHESTRATOR_URL}/recommend",
|
| 172 |
json=transaction,
|
| 173 |
-
timeout=60.0
|
| 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 |
-
#
|
| 183 |
recommendation = safe_get(result, 'recommendation', {})
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 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 |
-
|
| 199 |
-
|
| 200 |
-
|
| 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 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
|
| 214 |
-
|
| 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 |
-
|
| 221 |
-
|
|
|
|
| 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:** {
|
| 230 |
|
| 231 |
---
|
| 232 |
|
| 233 |
### π§ Agent's Reasoning:
|
| 234 |
|
| 235 |
-
{
|
| 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:** ${
|
| 249 |
-
- **Merchant:** {
|
| 250 |
-
- **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 |
-
|
| 296 |
-
|
| 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"""
|