GenAICoder commited on
Commit
6a169de
·
verified ·
1 Parent(s): ae3693a

Upload deep_dive_agentic (2).py

Browse files
Files changed (1) hide show
  1. analytics/deep_dive_agentic (2).py +802 -0
analytics/deep_dive_agentic (2).py ADDED
@@ -0,0 +1,802 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # deep_dive_agentic.py
2
+
3
+ """
4
+ Agentic analytical code generation + execution engine using Hugging Face
5
+
6
+ FLOW:
7
+ User Question
8
+ ↓
9
+ LLM generates pandas code
10
+ ↓
11
+ Python executes code safely
12
+ ↓
13
+ LLM interprets results
14
+ ↓
15
+ Return code + interpretation
16
+
17
+ Environment:
18
+ export HUGGINGFACE_API_TOKEN=...
19
+
20
+ FIXES APPLIED (v2):
21
+ - FIX 1: exec() now uses a single merged namespace dict so result variables
22
+ are reliably written back (Python bug with separate globals/locals).
23
+ - FIX 2: Smart result detection — scans namespace for any new DataFrame/Series
24
+ instead of relying on hardcoded variable names (result_1, final_result).
25
+ - FIX 3: _fix_pandas_compatibility() is now actually called before exec().
26
+ """
27
+
28
+ # ---------------------------------------------------
29
+ # IMPORTS
30
+ # ---------------------------------------------------
31
+
32
+ import pandas as pd
33
+ import json
34
+ import os
35
+ import re
36
+
37
+ try:
38
+ from huggingface_hub import InferenceClient
39
+ except ImportError as exc:
40
+ raise ImportError(
41
+ "huggingface_hub is required. Install with `pip install huggingface-hub`."
42
+ ) from exc
43
+
44
+ from analytics.performance_analysis import generate_metric_view
45
+
46
+ # ---------------------------------------------------
47
+ # HF CONFIG
48
+ # ---------------------------------------------------
49
+
50
+ HF_MODEL_ID = os.environ.get("HF_MODEL_ID", "Qwen/Qwen2.5-7B-Instruct")
51
+ HF_TOKEN = os.environ.get("HUGGINGFACE_API_TOKEN")
52
+
53
+
54
+ # ---------------------------------------------------
55
+ # HELPER: GET INFERENCE CLIENT
56
+ # ---------------------------------------------------
57
+
58
+ def _get_hf_client():
59
+ if not HF_TOKEN:
60
+ raise RuntimeError(
61
+ "HUGGINGFACE_API_TOKEN is required. Set it in your environment."
62
+ )
63
+ return InferenceClient(token=HF_TOKEN)
64
+
65
+
66
+ # ---------------------------------------------------
67
+ # HELPER: EXTRACT JSON FROM LLM RESPONSE
68
+ # ---------------------------------------------------
69
+
70
+ def _extract_json(text: str):
71
+ match = re.search(r"\{.*\}", text, re.S)
72
+ if not match:
73
+ return None
74
+ payload = match.group(0)
75
+ try:
76
+ return json.loads(payload)
77
+ except json.JSONDecodeError:
78
+ try:
79
+ cleaned = re.sub(r"[\n\r]+", " ", payload)
80
+ cleaned = re.sub(r"(['\"])?([a-zA-Z0-9_]+)(['\"])?\s*:\s*", r'"\2": ', cleaned)
81
+ return json.loads(cleaned)
82
+ except Exception:
83
+ return None
84
+
85
+
86
+ # ---------------------------------------------------
87
+ # HELPER: FIX COMMON PANDAS COMPATIBILITY ISSUES
88
+ # ---------------------------------------------------
89
+
90
+ def _fix_pandas_compatibility(code: str) -> str:
91
+ """
92
+ Fix common pandas API compatibility issues in generated code.
93
+ Handles version differences between pandas versions.
94
+ """
95
+ # Fix: .reset_index(name=...) -> .reset_index(names=[...])
96
+ code = re.sub(
97
+ r"\.reset_index\(name=(['\"])([^'\"]+)\1\)",
98
+ r".reset_index(names=[\1\2\1])",
99
+ code
100
+ )
101
+
102
+ # Fix: .reset_index(name= with variable
103
+ code = re.sub(
104
+ r"\.reset_index\(name=([a-zA-Z_][a-zA-Z0-9_]*)\)",
105
+ r".reset_index(names=[\1])",
106
+ code
107
+ )
108
+
109
+ # Fix: df.append() deprecated in newer pandas -> pd.concat()
110
+ code = re.sub(
111
+ r"(\w+)\.append\((\w+),\s*ignore_index=True\)",
112
+ r"pd.concat([\1, \2], ignore_index=True)",
113
+ code
114
+ )
115
+
116
+ return code
117
+
118
+
119
+ # ---------------------------------------------------
120
+ # STEP 1: CODE GENERATION
121
+ # ---------------------------------------------------
122
+
123
+ def generate_analysis_requirements(
124
+ question: str,
125
+ acq: pd.DataFrame,
126
+ perf: pd.DataFrame,
127
+ master_df: pd.DataFrame
128
+ ):
129
+ """
130
+ LLM breaks down question into 1-3 structured analytics requirements.
131
+ Each requirement includes a description and executable pandas code.
132
+ """
133
+
134
+ client = _get_hf_client()
135
+
136
+ # Build detailed column descriptions
137
+ acq_cols = {
138
+ "account_id": "unique account identifier",
139
+ "booking_date": "when account was originated",
140
+ "booking_vintage": "year-month of origination (YYYY-MM)",
141
+ "fico_band": "FICO score bracket (e.g., 700-750, 750-800)",
142
+ "sourcing_channel": "acquisition channel (e.g., Online, Branch, Broker)",
143
+ "city_tier": "city classification (Tier-1, Tier-2, Tier-3)",
144
+ "occupation_type": "borrower occupation category",
145
+ "credit_limit": "approved credit line amount"
146
+ }
147
+
148
+ perf_cols = {
149
+ "account_id": "unique account identifier",
150
+ "reporting_month": "month of performance observation (YYYY-MM)",
151
+ "mob": "months on books (age of account in months)",
152
+ "dpd": "days past due (0, 30, 60, 90+)",
153
+ "balance": "current outstanding balance",
154
+ "ncl_amount": "net charge-off amount (dollars)",
155
+ "payment": "payment amount in period"
156
+ }
157
+
158
+ prompt = (
159
+ # ================================================================
160
+ # SECTION 1: ROLE & OBJECTIVE
161
+ # ================================================================
162
+ "You are a senior retail credit risk analyst with 15+ years of experience "
163
+ "managing consumer credit portfolios. Your job is to analyze a user question, "
164
+ "plan the right analytical approach, write executable pandas code, and return "
165
+ "a structured JSON plan.\n\n"
166
+
167
+ "You have access to credit portfolio data. You will generate up to 3 pandas "
168
+ "code blocks (requirements) to answer the question. Each requirement produces "
169
+ "one result table. A comparison of two periods can and should be done in ONE "
170
+ "requirement by building a single table with both periods as columns plus a "
171
+ "delta column — do not waste two requirements on what can be one clean table.\n\n"
172
+
173
+ # ================================================================
174
+ # SECTION 2: DATA DICTIONARY
175
+ # ================================================================
176
+ "================================================================\n"
177
+ "SECTION 2: DATA DICTIONARY\n"
178
+ "================================================================\n\n"
179
+
180
+ "THREE dataframes are available. Use master_df for any analysis that needs "
181
+ "both acquisition attributes and performance metrics together.\n\n"
182
+
183
+ "acq — acquisition data (one row per account):\n"
184
+ " - account_id : unique account identifier (string)\n"
185
+ " - booking_date : origination date (datetime)\n"
186
+ " - booking_vintage : origination month as STRING in format 'YYYY-MM' e.g. '2024-07'\n"
187
+ " - fico_band : FICO score bracket (string) e.g. '700-750', '750-800'\n"
188
+ " - sourcing_channel : acquisition channel (string) e.g. 'Online', 'Branch', 'Broker'\n"
189
+ " - city_tier : city classification (string) e.g. 'Tier-1', 'Tier-2', 'Tier-3'\n"
190
+ " - occupation_type : borrower occupation (string) e.g. 'Salaried', 'Self-Employed'\n"
191
+ " - credit_limit : approved credit line in currency units (float)\n\n"
192
+
193
+ "perf — monthly performance data (one row per account per month):\n"
194
+ " - account_id : unique account identifier (string)\n"
195
+ " - reporting_month : observation month as STRING in format 'YYYY-MM' e.g. '2024-10'\n"
196
+ " - mob : months on books — integer age of account (1, 2, 3 ... 12+)\n"
197
+ " - dpd : days past due at that mob (integer: 0, 30, 60, 90)\n"
198
+ " - balance : outstanding balance at that mob (float)\n"
199
+ " - ncl_amount : net charge-off amount at that mob (float, 0 if not charged off)\n"
200
+ " - payment : payment made in that month (float)\n\n"
201
+
202
+ "master_df — perf LEFT JOINED with acq on account_id. Contains ALL columns above.\n"
203
+ "IMPORTANT: Always use master_df when you need both segment columns AND performance columns.\n\n"
204
+
205
+ "SEGMENT COLUMNS available for groupby in master_df:\n"
206
+ " - booking_vintage, fico_band, sourcing_channel, city_tier, occupation_type\n\n"
207
+
208
+ # ================================================================
209
+ # SECTION 3: METRIC DEFINITIONS & EXACT FORMULAS
210
+ # ================================================================
211
+ "================================================================\n"
212
+ "SECTION 3: METRIC DEFINITIONS & EXACT FORMULAS\n"
213
+ "================================================================\n\n"
214
+
215
+ "--- METRIC 1: Yr1 NCL Rate (Year 1 Net Charge-Off Rate) ---\n"
216
+ "Definition: The annualised net charge-off rate for a vintage cohort over its first 12 months.\n"
217
+ "What it measures: Credit loss intensity. Higher is worse.\n"
218
+ "Formula:\n"
219
+ " Yr1 NCL Rate = sum(ncl_amount where mob IN 1..12) / (sum(balance where mob IN 1..12) / 12) x 100\n"
220
+ "Steps in pandas:\n"
221
+ " Step 1 — Filter master_df for selected vintages AND mob between 1 and 12\n"
222
+ " Step 2 — sum ncl_amount across all rows in that filter\n"
223
+ " Step 3 — sum balance across all rows in that filter, then divide by 12\n"
224
+ " Step 4 — divide Step 2 by Step 3, multiply by 100\n"
225
+ "Pandas recipe (single vintage group):\n"
226
+ " df_v = master_df[master_df['booking_vintage'].isin(vintages) & master_df['mob'].between(1,12)]\n"
227
+ " ncl_rate = (df_v['ncl_amount'].sum() / (df_v['balance'].sum() / 12)) * 100\n\n"
228
+
229
+ "--- METRIC 2: 30+@3 (Early Delinquency Rate at MOB 3) ---\n"
230
+ "Definition: Share of accounts that are 30+ days past due at exactly month 3.\n"
231
+ "What it measures: Early stress signal. Higher is worse.\n"
232
+ "Formula:\n"
233
+ " 30+@3 = count(accounts where mob==3 AND dpd>=30) / count(accounts where mob==3) x 100\n"
234
+ "Pandas recipe:\n"
235
+ " df_m3 = master_df[master_df['booking_vintage'].isin(vintages) & (master_df['mob']==3)]\n"
236
+ " rate_30_3 = (df_m3['dpd'] >= 30).sum() / len(df_m3) * 100\n\n"
237
+
238
+ "--- METRIC 3: 30+@6 (Delinquency Rate at MOB 6) ---\n"
239
+ "Definition: Share of accounts that are 30+ days past due at exactly month 6.\n"
240
+ "Formula:\n"
241
+ " 30+@6 = count(accounts where mob==6 AND dpd>=30) / count(accounts where mob==6) x 100\n"
242
+ "Pandas recipe:\n"
243
+ " df_m6 = master_df[master_df['booking_vintage'].isin(vintages) & (master_df['mob']==6)]\n"
244
+ " rate_30_6 = (df_m6['dpd'] >= 30).sum() / len(df_m6) * 100\n\n"
245
+
246
+ "--- METRIC 4: 60+@6 (Severe Delinquency Rate at MOB 6) ---\n"
247
+ "Definition: Share of accounts that are 60+ days past due at exactly month 6.\n"
248
+ "Formula:\n"
249
+ " 60+@6 = count(accounts where mob==6 AND dpd>=60) / count(accounts where mob==6) x 100\n"
250
+ "Pandas recipe:\n"
251
+ " rate_60_6 = (df_m6['dpd'] >= 60).sum() / len(df_m6) * 100\n\n"
252
+
253
+ "--- RISK BENCHMARKS (flag in output) ---\n"
254
+ "Metric | Green (Good) | Amber (Watch) | Red (Bad)\n"
255
+ "30+@3 | < 3% | 3% - 6% | > 6%\n"
256
+ "30+@6 | < 5% | 5% - 9% | > 9%\n"
257
+ "60+@6 | < 2% | 2% - 4% | > 4%\n"
258
+ "Yr1 NCL | < 3% | 3% - 6% | > 6%\n\n"
259
+
260
+ # ================================================================
261
+ # SECTION 4: DATE & VINTAGE FILTERING RECIPES
262
+ # ================================================================
263
+ "================================================================\n"
264
+ "SECTION 4: DATE & VINTAGE FILTERING RECIPES\n"
265
+ "================================================================\n\n"
266
+
267
+ "CRITICAL: booking_vintage and reporting_month are STRINGS in 'YYYY-MM' format.\n"
268
+ "Never use .dt accessor or pd.Grouper on these columns — they are not datetime.\n"
269
+ "Always filter using string operations or .isin() as shown below.\n\n"
270
+
271
+ "Single vintage:\n"
272
+ " master_df[master_df['booking_vintage'] == '2024-10']\n\n"
273
+
274
+ "Full year:\n"
275
+ " master_df[master_df['booking_vintage'].str.startswith('2024')]\n\n"
276
+
277
+ "Quarter (Q1=Jan-Mar, Q2=Apr-Jun, Q3=Jul-Sep, Q4=Oct-Dec):\n"
278
+ " q3_2024 = ['2024-07','2024-08','2024-09']\n"
279
+ " master_df[master_df['booking_vintage'].isin(q3_2024)]\n\n"
280
+
281
+ "Half year (H1=Jan-Jun, H2=Jul-Dec):\n"
282
+ " h1_2024 = ['2024-01','2024-02','2024-03','2024-04','2024-05','2024-06']\n"
283
+ " h2_2024 = ['2024-07','2024-08','2024-09','2024-10','2024-11','2024-12']\n\n"
284
+
285
+ "Comparison in ONE table (e.g. 2024 vs 2025 full year):\n"
286
+ " v2024 = master_df[master_df['booking_vintage'].str.startswith('2024') & master_df['mob'].between(1,12)]\n"
287
+ " v2025 = master_df[master_df['booking_vintage'].str.startswith('2025') & master_df['mob'].between(1,12)]\n"
288
+ " ncl_2024 = (v2024['ncl_amount'].sum() / (v2024['balance'].sum() / 12)) * 100\n"
289
+ " ncl_2025 = (v2025['ncl_amount'].sum() / (v2025['balance'].sum() / 12)) * 100\n"
290
+ " result_1 = pd.DataFrame({'Period':['2024','2025'], 'Yr1_NCL_Rate':[ncl_2024, ncl_2025]})\n"
291
+ " result_1['Delta_vs_2024'] = result_1['Yr1_NCL_Rate'] - result_1['Yr1_NCL_Rate'].iloc[0]\n\n"
292
+
293
+ "Segment-level comparison in ONE table:\n"
294
+ " # Compute metric per segment for each period, merge into one table\n"
295
+ " def ncl_rate(df): return (df['ncl_amount'].sum() / (df['balance'].sum() / 12)) * 100\n"
296
+ " seg_2024 = v2024.groupby('fico_band').apply(ncl_rate).reset_index()\n"
297
+ " seg_2024.columns = ['fico_band','NCL_2024']\n"
298
+ " seg_2025 = v2025.groupby('fico_band').apply(ncl_rate).reset_index()\n"
299
+ " seg_2025.columns = ['fico_band','NCL_2025']\n"
300
+ " result_2 = seg_2024.merge(seg_2025, on='fico_band')\n"
301
+ " result_2['Delta'] = result_2['NCL_2025'] - result_2['NCL_2024']\n"
302
+ " result_2 = result_2.sort_values('NCL_2025', ascending=False)\n\n"
303
+
304
+ # ================================================================
305
+ # SECTION 5: QUESTION TYPE GUIDE
306
+ # ================================================================
307
+ "================================================================\n"
308
+ "SECTION 5: QUESTION TYPE GUIDE — HOW TO PLAN YOUR REQUIREMENTS\n"
309
+ "================================================================\n\n"
310
+
311
+ "Read the question carefully and identify which type it is. Then plan accordingly.\n\n"
312
+
313
+ "TYPE 1 — DIRECT COMPARISON (e.g. 'compare NCL 2024 vs 2025', 'how did Q3 perform vs Q4')\n"
314
+ " Planning approach:\n"
315
+ " - Identify the two periods being compared\n"
316
+ " - Identify which metrics are relevant (if not stated, use Yr1 NCL + 30+@3 as default)\n"
317
+ " - Req 1: Overall metric comparison — ONE table with [Period, Metric, Delta]\n"
318
+ " - Req 2 (optional): Same comparison broken down by most relevant segment\n"
319
+ " - Req 3 (optional): Second segment breakdown or second metric family\n"
320
+ " - DO NOT use two requirements to compute the same thing for two periods separately.\n"
321
+ " Merge them into ONE table.\n\n"
322
+
323
+ "TYPE 2 — FOCUSED EXPLORATION (e.g. 'analyse FICO band performance', 'how is Tier-2 doing')\n"
324
+ " Planning approach:\n"
325
+ " - Identify the segment of interest\n"
326
+ " - Identify the time window (if not stated, use last 4 available quarters)\n"
327
+ " - Req 1: Metric summary across that segment — all values ranked worst to best\n"
328
+ " - Req 2: Trend over time for the highest-risk sub-segments identified in Req 1\n"
329
+ " - Req 3 (optional): Cross-segment comparison (e.g. FICO x channel interaction)\n\n"
330
+
331
+ "TYPE 3 — OPEN / DIAGNOSTIC (e.g. 'what is wrong with the portfolio', 'give me a full view')\n"
332
+ " These questions require broad scanning across all segments and metrics simultaneously.\n"
333
+ " This level of analysis requires significantly more compute, parallel execution, and\n"
334
+ " multiple LLM reasoning loops that are beyond the current system design.\n"
335
+ " ACTION: Return a single requirement that computes a high-level portfolio scorecard\n"
336
+ " (all 4 metrics for last 2 years), and include a note in the description explaining\n"
337
+ " that a full diagnostic requires an advanced multi-agent setup.\n\n"
338
+
339
+ # ================================================================
340
+ # SECTION 6: WORKED EXAMPLES
341
+ # ================================================================
342
+ "================================================================\n"
343
+ "SECTION 6: WORKED EXAMPLES\n"
344
+ "================================================================\n\n"
345
+
346
+ "EXAMPLE A — TYPE 1 COMPARISON:\n"
347
+ "User question: 'Compare Yr1 NCL for 2024 and 2025 across FICO bands'\n"
348
+ "Planning:\n"
349
+ " - Two periods: 2024 full year, 2025 full year\n"
350
+ " - Metric: Yr1 NCL\n"
351
+ " - Segment: fico_band\n"
352
+ " - Req 1: Overall NCL rate for 2024 vs 2025 in one table\n"
353
+ " - Req 2: NCL rate by fico_band for 2024 vs 2025 with delta, sorted worst first\n"
354
+ "Expected output shape for Req 2:\n"
355
+ " fico_band | NCL_2024 | NCL_2025 | Delta\n"
356
+ " 600-650 | 8.2 | 7.1 | -1.1 (improvement)\n"
357
+ " 650-700 | 5.4 | 4.8 | -0.6\n"
358
+ " 700-750 | 3.1 | 2.9 | -0.2\n"
359
+ " 750-800 | 1.8 | 1.5 | -0.3\n\n"
360
+
361
+ "EXAMPLE B — TYPE 2 EXPLORATION:\n"
362
+ "User question: 'How are different sourcing channels performing on early delinquency'\n"
363
+ "Planning:\n"
364
+ " - Segment: sourcing_channel\n"
365
+ " - Metrics: 30+@3 and 30+@6 (early delinquency family)\n"
366
+ " - Time window: last 4 quarters available in data\n"
367
+ " - Req 1: 30+@3 and 30+@6 rates per channel, sorted worst first\n"
368
+ " - Req 2: Trend of 30+@3 by channel across last 4 quarters (one row per quarter)\n"
369
+ "Expected output shape for Req 1:\n"
370
+ " sourcing_channel | rate_30_3 | rate_30_6 | risk_flag\n"
371
+ " Broker | 7.8 | 11.2 | RED\n"
372
+ " Online | 4.1 | 6.8 | AMBER\n"
373
+ " Branch | 2.3 | 4.1 | GREEN\n\n"
374
+
375
+ # ================================================================
376
+ # SECTION 7: CODE GENERATION RULES
377
+ # ================================================================
378
+ "================================================================\n"
379
+ "SECTION 7: CODE GENERATION RULES\n"
380
+ "================================================================\n\n"
381
+
382
+ "1. Always store final result in variable named exactly result_1, result_2, or result_3\n"
383
+ " matching the sequence number of the requirement.\n\n"
384
+
385
+ "2. Always use master_df when analysis needs both segment + performance columns.\n"
386
+ " Use acq only for acquisition-only analysis (e.g. credit limit distribution).\n"
387
+ " Use perf only for portfolio-wide performance with no segmentation.\n\n"
388
+
389
+ "3. booking_vintage and reporting_month are strings. Never use .dt on them.\n"
390
+ " Filter with == or .isin() or .str.startswith() only.\n\n"
391
+
392
+ "4. Column names are EXACTLY as listed in Section 2. Do not guess or invent column names.\n"
393
+ " If a column does not exist in the listed schema, do not use it.\n\n"
394
+
395
+ "5. For comparisons: build ONE merged table with both periods as columns + delta.\n"
396
+ " Do not produce two separate DataFrames for two periods.\n\n"
397
+
398
+ "6. Add a risk_flag column where relevant using benchmarks from Section 3:\n"
399
+ " df['risk_flag'] = pd.cut(df['rate'], bins=[0,3,6,100], labels=['GREEN','AMBER','RED'])\n\n"
400
+
401
+ "7. Sort final result by the primary risk metric descending (worst first).\n\n"
402
+
403
+ "8. In JSON, the code string must use \\n for newlines and escape all internal quotes.\n"
404
+ " Do not put raw newlines inside the JSON string value.\n\n"
405
+
406
+ "9. Keep code focused. No print statements. No plots. No file I/O.\n\n"
407
+
408
+ # ================================================================
409
+ # SECTION 8: JSON OUTPUT FORMAT
410
+ # ================================================================
411
+ "================================================================\n"
412
+ "SECTION 8: OUTPUT FORMAT — RETURN ONLY THIS JSON, NOTHING ELSE\n"
413
+ "================================================================\n\n"
414
+
415
+ "{\n"
416
+ ' "requirements": [\n'
417
+ ' {\n'
418
+ ' "sequence": 1,\n'
419
+ ' "title": "Short descriptive title",\n'
420
+ ' "description": "What this analysis does, why it answers the question, what the output table shows",\n'
421
+ ' "code": "# pandas code here\\nresult_1 = ..."\n'
422
+ ' }\n'
423
+ ' ]\n'
424
+ "}\n\n"
425
+
426
+ "User Question: " + question
427
+ )
428
+
429
+ messages = [
430
+ {
431
+ "role": "system",
432
+ "content": (
433
+ "You are a senior credit risk analyst who writes pandas code for portfolio analytics. "
434
+ "You MUST return ONLY valid JSON with no text before or after it. "
435
+ "Always name final result variables exactly result_1, result_2, or result_3. "
436
+ "booking_vintage and reporting_month are string columns in YYYY-MM format — never use .dt on them. "
437
+ "Always use master_df when you need both segment and performance data."
438
+ )
439
+ },
440
+ {"role": "user", "content": prompt}
441
+ ]
442
+
443
+ response = client.chat.completions.create(
444
+ model=HF_MODEL_ID,
445
+ messages=messages,
446
+ max_tokens=2048,
447
+ temperature=0.1,
448
+ top_p=0.95
449
+ )
450
+
451
+ response_text = (
452
+ response.choices[0].message.content
453
+ if hasattr(response, "choices")
454
+ else str(response)
455
+ )
456
+
457
+ # Extract JSON
458
+ spec = _extract_json(response_text)
459
+
460
+ if not spec:
461
+ return {
462
+ "success": False,
463
+ "requirements": [],
464
+ "error": f"Failed to parse JSON from LLM response: {response_text[:200]}",
465
+ "raw_response": response_text
466
+ }
467
+
468
+ requirements = spec.get("requirements", [])
469
+
470
+ if not requirements:
471
+ return {
472
+ "success": False,
473
+ "requirements": [],
474
+ "error": f"LLM returned no requirements. Response keys: {list(spec.keys())}",
475
+ "raw_response": response_text[:300]
476
+ }
477
+
478
+ print(f"[DEBUG] Generated {len(requirements)} requirements for question: {question[:80]}")
479
+ for i, req in enumerate(requirements, 1):
480
+ print(f" Req {i}: {req.get('title')}")
481
+
482
+ return {
483
+ "success": True,
484
+ "requirements": requirements,
485
+ "error": None
486
+ }
487
+
488
+
489
+ # ---------------------------------------------------
490
+ # STEP 2: CODE EXECUTION (LOOPED)
491
+ # ---------------------------------------------------
492
+
493
+ def execute_requirement_code(
494
+ code: str,
495
+ acq: pd.DataFrame,
496
+ perf: pd.DataFrame,
497
+ master_df: pd.DataFrame,
498
+ requirement_num: int
499
+ ):
500
+ """
501
+ Safely execute generated pandas code for a single requirement.
502
+
503
+ FIXES:
504
+ - FIX 1: Single namespace dict passed to exec() so variable assignments
505
+ are reliably captured (Python quirk with separate globals/locals).
506
+ - FIX 2: Smart result detection — checks named keys first, then scans
507
+ for any new DataFrame/Series, then any non-None new variable.
508
+ - FIX 3: _fix_pandas_compatibility() called before exec().
509
+ """
510
+
511
+ # FIX 3: Apply pandas compatibility patches BEFORE executing
512
+ code = _fix_pandas_compatibility(code)
513
+
514
+ # FIX 1: Merge everything into ONE dict so exec() writes back correctly.
515
+ # When you pass separate globals + locals to exec(), Python's bytecode
516
+ # compiler uses STORE_FAST which writes to an internal frame and does NOT
517
+ # update the locals dict you passed in — so result variables always come
518
+ # back None. Using a single namespace avoids this entirely.
519
+ namespace = {
520
+ "pd": pd,
521
+ "generate_metric_view": generate_metric_view,
522
+ "__builtins__": __builtins__,
523
+ # Data available to generated code
524
+ "acq": acq,
525
+ "perf": perf,
526
+ "master_df": master_df,
527
+ }
528
+
529
+ # Snapshot of keys before exec so we can detect newly created variables
530
+ keys_before = set(namespace.keys())
531
+
532
+ try:
533
+ print(f"[DEBUG] Executing requirement {requirement_num}...")
534
+ print(f"[DEBUG] Code preview: {code[:120].strip()}...")
535
+
536
+ exec(code, namespace) # FIX 1: single namespace
537
+
538
+ # FIX 2: Smart result detection — three priority tiers
539
+
540
+ # --- Tier 1: expected named result variables ---
541
+ result = None
542
+ expected_keys = [
543
+ f"result_{requirement_num}",
544
+ "final_result",
545
+ "result",
546
+ ]
547
+ for key in expected_keys:
548
+ if key in namespace and namespace[key] is not None:
549
+ result = namespace[key]
550
+ print(f"[DEBUG] Found result in expected variable: '{key}'")
551
+ break
552
+
553
+ # --- Tier 2: any NEW DataFrame or Series created during exec ---
554
+ if result is None:
555
+ new_keys = set(namespace.keys()) - keys_before
556
+ for key in new_keys:
557
+ val = namespace[key]
558
+ if isinstance(val, (pd.DataFrame, pd.Series)) and val is not None:
559
+ result = val
560
+ print(f"[DEBUG] Found result by scanning new DataFrame/Series: '{key}'")
561
+ break
562
+
563
+ # --- Tier 3: any new non-None, non-private variable ---
564
+ if result is None:
565
+ new_keys = set(namespace.keys()) - keys_before
566
+ for key in sorted(new_keys): # sorted for determinism
567
+ if key.startswith("_"):
568
+ continue
569
+ val = namespace[key]
570
+ if val is not None:
571
+ result = val
572
+ print(f"[DEBUG] Fallback: found result in new variable: '{key}'")
573
+ break
574
+
575
+ if result is None:
576
+ result = "Code executed successfully but no result variable was found in namespace."
577
+
578
+ print(f"[DEBUG] Req {requirement_num} success. Result type: {type(result).__name__}")
579
+ return {
580
+ "success": True,
581
+ "result": result,
582
+ "error": None
583
+ }
584
+
585
+ except Exception as e:
586
+ import traceback
587
+ tb = traceback.format_exc()
588
+ print(f"[DEBUG] Req {requirement_num} FAILED: {str(e)}")
589
+ print(f"[DEBUG] Traceback:\n{tb}")
590
+ return {
591
+ "success": False,
592
+ "result": None,
593
+ "error": str(e)
594
+ }
595
+
596
+
597
+ def execute_all_requirements(
598
+ requirements: list,
599
+ acq: pd.DataFrame,
600
+ perf: pd.DataFrame,
601
+ master_df: pd.DataFrame
602
+ ):
603
+ """
604
+ Execute all requirements sequentially, building context.
605
+ """
606
+
607
+ print(f"[DEBUG] Starting execution of {len(requirements)} requirements")
608
+ all_results = []
609
+ context_text = ""
610
+
611
+ for i, req in enumerate(requirements, 1):
612
+ code = req.get("code", "")
613
+ description = req.get("description", "")
614
+ title = req.get("title", f"Analysis {i}")
615
+
616
+ exec_result = execute_requirement_code(code, acq, perf, master_df, i)
617
+
618
+ all_results.append({
619
+ "sequence": i,
620
+ "title": title,
621
+ "description": description,
622
+ "code": code,
623
+ # "success" is what app.py checks via res.get("success")
624
+ # "execution_success" kept for backward compatibility
625
+ "success": exec_result["success"],
626
+ "execution_success": exec_result["success"],
627
+ "result": exec_result["result"],
628
+ "error": exec_result.get("error")
629
+ })
630
+
631
+ # Build context for interpretation
632
+ if exec_result["success"]:
633
+ context_text += f"\nAnalysis {i} ({title}):\n{str(exec_result['result'])}\n"
634
+ else:
635
+ context_text += f"\nAnalysis {i} ({title}) FAILED:\n{exec_result['error']}\n"
636
+
637
+ return all_results, context_text
638
+
639
+
640
+ # ---------------------------------------------------
641
+ # STEP 3: RESULT INTERPRETATION
642
+ # ---------------------------------------------------
643
+
644
+ def interpret_all_results(
645
+ question: str,
646
+ all_results: list,
647
+ context_text: str
648
+ ):
649
+ """
650
+ Senior risk analyst LLM interprets all results holistically.
651
+ """
652
+
653
+ print(f"[DEBUG] Interpreting results for {len(all_results)} analyses")
654
+ print(f"[DEBUG] Successful executions: {sum(1 for r in all_results if r.get('success'))}")
655
+
656
+ client = _get_hf_client()
657
+
658
+ # Format all analyses
659
+ analyses_text = ""
660
+ for res in all_results:
661
+ analyses_text += f"\n{'=' * 60}\n"
662
+ analyses_text += f"Analysis {res['sequence']}: {res['title']}\n"
663
+ analyses_text += f"Description: {res['description']}\n"
664
+ analyses_text += f"{'=' * 60}\n"
665
+ if res["success"]:
666
+ analyses_text += f"Result:\n{str(res['result'])}\n"
667
+ else:
668
+ analyses_text += f"Execution Error: {res['error']}\n"
669
+
670
+ prompt = (
671
+ "You are a senior retail credit risk analyst with 15+ years of portfolio management experience.\n\n"
672
+
673
+ "You have just run a set of pandas analyses on a credit portfolio. "
674
+ "Your task is to interpret the results and deliver a structured, specific, "
675
+ "actionable risk assessment. Do not repeat raw numbers from the tables — "
676
+ "interpret what they mean for the business.\n\n"
677
+
678
+ "RISK BENCHMARKS FOR REFERENCE:\n"
679
+ " 30+@3 : Green < 3% | Amber 3-6% | Red > 6%\n"
680
+ " 30+@6 : Green < 5% | Amber 5-9% | Red > 9%\n"
681
+ " 60+@6 : Green < 2% | Amber 2-4% | Red > 4%\n"
682
+ " Yr1 NCL: Green < 3% | Amber 3-6% | Red > 6%\n\n"
683
+
684
+ "STRUCTURE YOUR RESPONSE IN EXACTLY THESE 4 SECTIONS:\n\n"
685
+
686
+ "1. HEADLINE FINDING (2-3 sentences)\n"
687
+ " The single most important thing the data shows. Be specific — name the metric, "
688
+ " the segment or vintage, and the direction (improving/worsening).\n\n"
689
+
690
+ "2. KEY FINDINGS (3-5 bullet points)\n"
691
+ " Each bullet must:\n"
692
+ " - Name a specific segment, vintage, or metric (not generic statements)\n"
693
+ " - State the actual value and what benchmark zone it falls in (Green/Amber/Red)\n"
694
+ " - State whether it is improving, stable, or worsening vs the comparison period\n"
695
+ " Example: '• Broker channel 30+@3 is 7.8% (RED) — worsening by +2.1pp vs 2024, "
696
+ " suggesting deteriorating acquisition quality in this channel.'\n\n"
697
+
698
+ "3. RED FLAGS (list only if any metric is in Amber or Red zone)\n"
699
+ " For each red flag:\n"
700
+ " - Name the segment/vintage and metric\n"
701
+ " - State the value and benchmark zone\n"
702
+ " - Give one specific business hypothesis for why this is happening\n"
703
+ " If no red flags: write 'No red flags — all metrics within Green benchmarks.'\n\n"
704
+
705
+ "4. RECOMMENDATIONS (2-4 actionable items)\n"
706
+ " Each recommendation must be:\n"
707
+ " - Tied to a specific finding above (not generic advice)\n"
708
+ " - Actionable by a risk or credit team (tighten policy, adjust limit, investigate, monitor)\n"
709
+ " - Prioritised: label each as IMMEDIATE, SHORT-TERM, or MONITOR\n"
710
+ " Example: '[IMMEDIATE] Tighten credit bureau cut-off for Broker channel acquisitions — "
711
+ " 30+@3 at 7.8% exceeds Red threshold and is trending upward.'\n\n"
712
+
713
+ "User's Original Question:\n" + question + "\n\n"
714
+
715
+ "Analyses Performed:\n" + analyses_text + "\n\n"
716
+
717
+ "Provide your structured interpretation now:"
718
+ )
719
+
720
+ messages = [
721
+ {
722
+ "role": "system",
723
+ "content": (
724
+ "You are a senior credit risk analyst delivering a structured portfolio risk assessment. "
725
+ "Be specific — always name segments, vintages, and metrics by name. "
726
+ "Always reference benchmark zones (Green/Amber/Red). "
727
+ "Never give generic advice. Every recommendation must trace back to a specific data finding."
728
+ )
729
+ },
730
+ {"role": "user", "content": prompt}
731
+ ]
732
+
733
+ response = client.chat.completions.create(
734
+ model=HF_MODEL_ID,
735
+ messages=messages,
736
+ max_tokens=1024,
737
+ temperature=0.3,
738
+ top_p=0.95
739
+ )
740
+
741
+ interpretation = (
742
+ response.choices[0].message.content
743
+ if hasattr(response, "choices")
744
+ else str(response)
745
+ )
746
+ return interpretation
747
+
748
+
749
+ # ---------------------------------------------------
750
+ # MASTER ORCHESTRATOR FUNCTION
751
+ # ---------------------------------------------------
752
+
753
+ def run_deep_dive_analysis(
754
+ question: str,
755
+ acq: pd.DataFrame,
756
+ perf: pd.DataFrame,
757
+ master_df: pd.DataFrame
758
+ ):
759
+ """
760
+ End-to-end deep dive analysis:
761
+ 1. Break question into 1-3 structured requirements
762
+ 2. Generate code for each requirement
763
+ 3. Execute each requirement's code sequentially
764
+ 4. Synthesize results and provide senior analyst interpretation
765
+ """
766
+
767
+ print(f"\n[DEEP DIVE START] Question: {question}")
768
+ print(f"[DEBUG] Data shapes - Acq: {acq.shape}, Perf: {perf.shape}, Master: {master_df.shape}")
769
+
770
+ # Step 1: Generate requirements
771
+ print("[DEBUG] Step 1: Generating requirements...")
772
+ req_response = generate_analysis_requirements(question, acq, perf, master_df)
773
+
774
+ if not req_response["success"]:
775
+ return {
776
+ "success": False,
777
+ "question": question,
778
+ "requirements": [],
779
+ "all_results": [],
780
+ "interpretation": f"Failed to generate requirements: {req_response['error']}",
781
+ "error": req_response["error"]
782
+ }
783
+
784
+ requirements = req_response["requirements"][:3] # Cap at 3
785
+
786
+ # Step 2 & 3: Execute all requirements
787
+ print(f"[DEBUG] Step 2-3: Executing {len(requirements)} requirements...")
788
+ all_results, context_text = execute_all_requirements(requirements, acq, perf, master_df)
789
+
790
+ # Step 4: Interpret results
791
+ print("[DEBUG] Step 4: Interpreting all results...")
792
+ interpretation = interpret_all_results(question, all_results, context_text)
793
+ print("[DEEP DIVE END] Analysis complete\n")
794
+
795
+ return {
796
+ "success": True,
797
+ "question": question,
798
+ "requirements": requirements,
799
+ "all_results": all_results,
800
+ "interpretation": interpretation,
801
+ "error": None
802
+ }