sammy786 commited on
Commit
f4d2b08
Β·
verified Β·
1 Parent(s): 5aa4a62

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +233 -7
app.py CHANGED
@@ -146,6 +146,153 @@ from utils.api_client import RewardPilotClient
146
  from utils.llm_explainer import get_llm_explainer
147
  import config
148
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  # Initialize clients
150
  client = RewardPilotClient(config.ORCHESTRATOR_URL)
151
  llm = get_llm_explainer()
@@ -561,9 +708,13 @@ Get AI-powered credit card recommendations that maximize your rewards based on:
561
  ---
562
  """
563
  )
564
- # LLM Status Indicator
565
- llm_status = "πŸ€– **AI Explanations:** βœ… Enabled" if config.LLM_ENABLED else "⚠️ **AI Explanations:** Disabled (using rule-based mode)"
566
- gr.Markdown(llm_status)
 
 
 
 
567
 
568
 
569
  # Ensure all tabs are siblings at the same level
@@ -672,10 +823,10 @@ Get AI-powered credit card recommendations that maximize your rewards based on:
672
 
673
 
674
  recommend_btn.click(
675
- fn=get_recommendation_with_ai,
676
- inputs=[user_dropdown, merchant_dropdown, category_dropdown, amount_input],
677
- outputs=[recommendation_output, recommendation_chart]
678
- )
679
  # def get_recommendation_with_loading(user_id, merchant, category, amount):
680
  # """Wrapper to show loading state"""
681
  # # Show loading first
@@ -1072,6 +1223,81 @@ Get AI-powered credit card recommendations that maximize your rewards based on:
1072
  ],
1073
  inputs=[msg]
1074
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1075
  # ========== Tab 3: About ==========
1076
  with gr.Tab("ℹ️ About"):
1077
  gr.Markdown(
 
146
  from utils.llm_explainer import get_llm_explainer
147
  import config
148
 
149
+ from agents.agent_core import RewardPilotAgent
150
+
151
+ # Initialize agent
152
+ agent = RewardPilotAgent()
153
+
154
+ def get_recommendation_with_agent(user_id, merchant, category, amount):
155
+ """
156
+ Get recommendation using autonomous agent
157
+ Shows loading state, then agent's reasoning
158
+ """
159
+ import httpx
160
+
161
+ # Show loading first
162
+ yield "⏳ **Agent is thinking...** Analyzing your transaction and cards...", None
163
+
164
+ try:
165
+ transaction = {
166
+ "user_id": user_id,
167
+ "merchant": merchant,
168
+ "category": category,
169
+ "mcc": MCC_CATEGORIES.get(category, "5999"),
170
+ "amount_usd": float(amount)
171
+ }
172
+
173
+ # Call orchestrator (which now uses agent)
174
+ response = httpx.post(
175
+ f"{config.ORCHESTRATOR_URL}/recommend",
176
+ json=transaction,
177
+ timeout=60.0 # Agent needs more time
178
+ )
179
+
180
+ if response.status_code != 200:
181
+ yield f"❌ Error: API returned status {response.status_code}", None
182
+ return
183
+
184
+ result = response.json()
185
+
186
+ # Extract agent data safely
187
+ recommended_card = safe_get(result, 'recommended_card', {})
188
+ if isinstance(recommended_card, dict):
189
+ card_name = safe_get(recommended_card, 'card_name', 'Unknown Card')
190
+ else:
191
+ card_name = str(recommended_card)
192
+
193
+ # Format response with agent insights
194
+ output = f"""
195
+ ## πŸ€– AI Agent Recommendation
196
+
197
+ ### πŸ’³ Recommended Card: **{card_name}**
198
+
199
+ ### 🧠 Agent's Reasoning:
200
+ {safe_get(result, 'final_recommendation', 'No reasoning provided')}
201
+
202
+ ---
203
+
204
+ ### πŸ“Š Quick Stats:
205
+ - **Amount**: ${safe_get(result, 'amount_usd', amount):.2f}
206
+ - **Merchant**: {safe_get(result, 'merchant', merchant)}
207
+ - **Category**: {safe_get(result, 'category', category)}
208
+ - **Services Used**: {', '.join(safe_get(result, 'services_used', []))}
209
+ - **Processing Time**: {safe_get(result, 'orchestration_time_ms', 0):.0f}ms
210
+
211
+ ---
212
+
213
+ ### πŸ’‘ Why This Card?
214
+ The AI agent analyzed your transaction context, card portfolio, and spending patterns to determine this is your optimal choice.
215
+
216
+ **Confidence Level**: High βœ…
217
+ """
218
+
219
+ # Create simple comparison chart
220
+ chart = create_agent_recommendation_chart(result)
221
+
222
+ yield output, chart
223
+
224
+ except httpx.TimeoutException:
225
+ yield "⏱️ **Request timed out.** The agent is taking longer than expected. Please try again.", None
226
+ except Exception as e:
227
+ import traceback
228
+ error_details = traceback.format_exc()
229
+ print(f"Agent recommendation error: {error_details}")
230
+ yield f"❌ **Error**: {str(e)}\n\nPlease check the orchestrator service or try again.", None
231
+
232
+
233
+ def create_agent_recommendation_chart(result: Dict) -> go.Figure:
234
+ """Create simple chart showing agent's recommendation"""
235
+ try:
236
+ # Extract card info
237
+ recommended = result.get('recommended_card', {})
238
+ alternatives = result.get('alternative_cards', [])[:2] # Top 2 alternatives
239
+
240
+ if isinstance(recommended, dict):
241
+ rec_name = recommended.get('card_name', 'Recommended Card')
242
+ rec_reward = recommended.get('reward_amount', 0)
243
+ else:
244
+ rec_name = str(recommended)
245
+ rec_reward = 0
246
+
247
+ cards = [rec_name]
248
+ rewards = [rec_reward]
249
+ colors = ['#667eea'] # Purple for recommended
250
+
251
+ # Add alternatives
252
+ for alt in alternatives:
253
+ if isinstance(alt, dict):
254
+ cards.append(alt.get('card_name', 'Alternative'))
255
+ rewards.append(alt.get('reward_amount', 0))
256
+ colors.append('#cbd5e0') # Gray for alternatives
257
+
258
+ # Create bar chart
259
+ fig = go.Figure(data=[
260
+ go.Bar(
261
+ x=cards,
262
+ y=rewards,
263
+ marker=dict(color=colors, line=dict(color='white', width=2)),
264
+ text=[f'${r:.2f}' for r in rewards],
265
+ textposition='outside',
266
+ hovertemplate='<b>%{x}</b><br>Rewards: $%{y:.2f}<extra></extra>'
267
+ )
268
+ ])
269
+
270
+ fig.update_layout(
271
+ title={'text': '🎯 Agent\'s Card Comparison', 'x': 0.5, 'xanchor': 'center'},
272
+ xaxis_title='Credit Card',
273
+ yaxis_title='Rewards Earned ($)',
274
+ template='plotly_white',
275
+ height=400,
276
+ showlegend=False,
277
+ margin=dict(t=60, b=50, l=50, r=50)
278
+ )
279
+
280
+ return fig
281
+
282
+ except Exception as e:
283
+ print(f"Chart error: {e}")
284
+ fig = go.Figure()
285
+ fig.add_annotation(
286
+ text="Chart unavailable",
287
+ xref="paper", yref="paper",
288
+ x=0.5, y=0.5, showarrow=False,
289
+ font=dict(size=14, color="#666")
290
+ )
291
+ fig.update_layout(height=400, template='plotly_white')
292
+ return fig
293
+
294
+
295
+
296
  # Initialize clients
297
  client = RewardPilotClient(config.ORCHESTRATOR_URL)
298
  llm = get_llm_explainer()
 
708
  ---
709
  """
710
  )
711
+ # Agent Status Indicator
712
+ agent_status = """
713
+ πŸ€– **Autonomous Agent:** βœ… Active (Claude 3.5 Sonnet)
714
+ πŸ“Š **Mode:** Dynamic Planning + Reasoning
715
+ ⚑ **Services:** Smart Wallet + RAG + Forecast
716
+ """
717
+ gr.Markdown(agent_status)
718
 
719
 
720
  # Ensure all tabs are siblings at the same level
 
823
 
824
 
825
  recommend_btn.click(
826
+ fn=get_recommendation_with_agent,
827
+ inputs=[user_dropdown, merchant_dropdown, category_dropdown, amount_input],
828
+ outputs=[recommendation_output, recommendation_chart]
829
+ )
830
  # def get_recommendation_with_loading(user_id, merchant, category, amount):
831
  # """Wrapper to show loading state"""
832
  # # Show loading first
 
1223
  ],
1224
  inputs=[msg]
1225
  )
1226
+ # ========== Tab: Agent Insights (NEW) ==========
1227
+ with gr.Tab("πŸ€– Agent Insights"):
1228
+ gr.Markdown("""
1229
+ ## How the Autonomous Agent Works
1230
+
1231
+ RewardPilot uses **Claude 3.5 Sonnet** as an autonomous agent to provide intelligent card recommendations.
1232
+
1233
+ ### 🎯 **Phase 1: Planning**
1234
+ The agent analyzes your transaction and decides:
1235
+ - Which microservices to call (Smart Wallet, RAG, Forecast)
1236
+ - In what order to call them
1237
+ - What to optimize for (rewards, caps, benefits)
1238
+ - Confidence level of the plan
1239
+
1240
+ ### πŸ€” **Phase 2: Execution**
1241
+ The agent dynamically:
1242
+ - Calls services based on the plan
1243
+ - Handles failures gracefully
1244
+ - Adapts if services are unavailable
1245
+ - Collects all relevant data
1246
+
1247
+ ### 🧠 **Phase 3: Reasoning**
1248
+ The agent synthesizes results to:
1249
+ - Explain **why** this card is best
1250
+ - Identify potential risks or warnings
1251
+ - Suggest alternative options
1252
+ - Calculate annual impact
1253
+
1254
+ ### πŸ“š **Phase 4: Learning**
1255
+ The agent improves over time by:
1256
+ - Storing past decisions
1257
+ - Learning from user feedback
1258
+ - Adjusting strategies for similar transactions
1259
+ - Building a knowledge base
1260
+
1261
+ ---
1262
+
1263
+ ### πŸ”‘ **Key Features**
1264
+
1265
+ βœ… **Natural Language Explanations** - Understands context like a human
1266
+ βœ… **Dynamic Planning** - Adapts to your specific situation
1267
+ βœ… **Confidence Scoring** - Tells you how certain it is
1268
+ βœ… **Multi-Service Coordination** - Orchestrates 3 microservices
1269
+ βœ… **Self-Correction** - Learns from mistakes
1270
+
1271
+ ---
1272
+
1273
+ ### πŸ“Š **Example Agent Plan**
1274
+
1275
+ ```json
1276
+ {
1277
+ "strategy": "Optimize for grocery rewards with cap monitoring",
1278
+ "service_calls": [
1279
+ {"service": "smart_wallet", "priority": 1, "reason": "Get base recommendation"},
1280
+ {"service": "spend_forecast", "priority": 2, "reason": "Check spending caps"},
1281
+ {"service": "rewards_rag", "priority": 3, "reason": "Get detailed benefits"}
1282
+ ],
1283
+ "confidence": 0.92,
1284
+ "expected_outcome": "Recommend Amex Gold for 4x grocery points"
1285
+ }
1286
+ ```
1287
+
1288
+ ---
1289
+
1290
+ ### πŸŽ“ **Powered By**
1291
+ - **Model**: Claude 3.5 Sonnet (Anthropic)
1292
+ - **Architecture**: Autonomous Agent Pattern
1293
+ - **Framework**: LangChain + Custom Logic
1294
+ - **Memory**: Redis (for learning)
1295
+
1296
+ ---
1297
+
1298
+ **Try it out in the "Get Recommendation" tab!** πŸš€
1299
+ """)
1300
+
1301
  # ========== Tab 3: About ==========
1302
  with gr.Tab("ℹ️ About"):
1303
  gr.Markdown(