GenAICoder commited on
Commit
2b40c53
·
verified ·
1 Parent(s): e1e9406

Create ai_assistant.py

Browse files
Files changed (1) hide show
  1. analytics/ai_assistant.py +346 -0
analytics/ai_assistant.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import re
4
+ import pandas as pd
5
+
6
+ try:
7
+ from huggingface_hub import InferenceClient
8
+ except ImportError as exc:
9
+ raise ImportError(
10
+ "huggingface_hub is required for AI assistant support. "
11
+ "Install it with `pip install huggingface_hub`."
12
+ ) from exc
13
+
14
+ from analytics.performance_analysis import generate_metric_view
15
+
16
+ HF_MODEL_ID = os.environ.get("HF_MODEL_ID", "Qwen/Qwen2.5-7B-Instruct")
17
+ HF_TOKEN = os.environ.get("HUGGINGFACE_API_TOKEN")
18
+ HF_MAX_TOKENS = int(os.environ.get("HF_MAX_TOKENS", 512))
19
+ HF_TEMPERATURE = float(os.environ.get("HF_TEMPERATURE", 0.3))
20
+
21
+ RISK_METRICS = ["30+@3", "30+@6", "60+@6", "Yr1 NCL"]
22
+ GROUPING_MAP = {
23
+ "fico": "fico_band",
24
+ "fico_band": "fico_band",
25
+ "channel": "sourcing_channel",
26
+ "sourcing_channel": "sourcing_channel",
27
+ "city": "city_tier",
28
+ "city_tier": "city_tier",
29
+ "occupation": "occupation_type",
30
+ "occupation_type": "occupation_type"
31
+ }
32
+
33
+
34
+ def _detect_date_column(df: pd.DataFrame):
35
+ candidates = [
36
+ "reporting_month",
37
+ "observation_date",
38
+ "observation_month",
39
+ "obs_date",
40
+ "date",
41
+ "calendar_month",
42
+ "month",
43
+ "report_date"
44
+ ]
45
+ for c in candidates:
46
+ if c in df.columns:
47
+ return c
48
+ return None
49
+
50
+
51
+ def _filter_by_month(df: pd.DataFrame, as_of_month: str | None):
52
+ if not as_of_month or as_of_month == "All":
53
+ return df.copy()
54
+
55
+ date_col = _detect_date_column(df)
56
+ if date_col is None:
57
+ return df.copy()
58
+
59
+ ser = pd.to_datetime(df[date_col], errors="coerce").dt.to_period("M").astype(str)
60
+ return df[ser == as_of_month].copy()
61
+
62
+
63
+ def _fmt_pct(value):
64
+ try:
65
+ return f"{round(float(value), 2)}%"
66
+ except Exception:
67
+ return "N/A"
68
+
69
+
70
+ def build_portfolio_context(df: pd.DataFrame, as_of_month: str | None = None, segment: str | None = None):
71
+ df = _filter_by_month(df, as_of_month)
72
+
73
+ total_accounts = int(df["account_id"].nunique()) if "account_id" in df.columns else 0
74
+ open_accounts = int(df.loc[df["balance"] > 0, "account_id"].nunique()) if "balance" in df.columns else total_accounts
75
+ bad_accounts = int(df.loc[df["dpd"].fillna(0) >= 30, "account_id"].nunique()) if "dpd" in df.columns else 0
76
+ total_balance = float(df["balance"].sum(skipna=True)) if "balance" in df.columns else 0.0
77
+
78
+ ncl_cols = [c for c in df.columns if "ncl" in c.lower()]
79
+ if len(ncl_cols) > 0 and total_balance > 0:
80
+ overall_ncl_rate = df[ncl_cols[0]].sum(skipna=True) / total_balance * 100
81
+ elif total_balance > 0 and "dpd" in df.columns:
82
+ bad_balance = float(df.loc[df["dpd"].fillna(0) >= 30, "balance"].sum())
83
+ overall_ncl_rate = bad_balance / total_balance * 100
84
+ else:
85
+ overall_ncl_rate = None
86
+
87
+ if overall_ncl_rate is None:
88
+ overall_ncl_rate_text = "N/A"
89
+ else:
90
+ overall_ncl_rate_text = _fmt_pct(overall_ncl_rate)
91
+
92
+ if "fico_score" in df.columns:
93
+ avg_fico = round(df["fico_score"].dropna().mean(), 1)
94
+ elif "fico_band" in df.columns:
95
+ def band_mid(val):
96
+ try:
97
+ lo, hi = val.split("-")
98
+ return (int(lo) + int(hi)) / 2
99
+ except Exception:
100
+ return None
101
+ mid_vals = df["fico_band"].dropna().apply(band_mid).dropna()
102
+ avg_fico = round(mid_vals.mean(), 1) if not mid_vals.empty else None
103
+ else:
104
+ avg_fico = None
105
+
106
+ as_of_month_text = (
107
+ "all data" if as_of_month == "All" else (as_of_month or "latest available")
108
+ )
109
+
110
+ lines = [
111
+ f"As of month: {as_of_month_text}",
112
+ f"Total accounts: {total_accounts}",
113
+ f"Open accounts: {open_accounts}",
114
+ f"Bad accounts (dpd>=30): {bad_accounts}",
115
+ f"Overall NCL rate: {overall_ncl_rate_text}",
116
+ f"Average FICO: {avg_fico if avg_fico is not None else 'N/A'}"
117
+ ]
118
+
119
+ if segment and segment in df.columns:
120
+ segment_summary = (
121
+ df.groupby(segment)
122
+ .agg(
123
+ accounts=("account_id", "nunique"),
124
+ balance=("balance", "sum"),
125
+ bad_balance=("balance", lambda x: x[df.loc[x.index, "dpd"].fillna(0) >= 30].sum() if "dpd" in df.columns else 0)
126
+ )
127
+ .reset_index()
128
+ )
129
+ if "balance" in df.columns:
130
+ segment_summary["ncl_rate"] = (segment_summary["bad_balance"] / segment_summary["balance"] * 100).round(2).fillna(0)
131
+ else:
132
+ segment_summary["ncl_rate"] = 0
133
+
134
+ lines.append(f"Segment breakdown by {segment}:")
135
+ for _, row in segment_summary.sort_values("ncl_rate", ascending=False).head(5).iterrows():
136
+ lines.append(
137
+ f" - {row[segment]}: accounts={int(row['accounts'])}, balance={row['balance']:.0f}, ncl={_fmt_pct(row['ncl_rate'])}"
138
+ )
139
+
140
+ return "\n".join(lines)
141
+
142
+
143
+ def _extract_json(text: str):
144
+ match = re.search(r"\{.*\}", text, re.S)
145
+ if not match:
146
+ return None
147
+ payload = match.group(0)
148
+ try:
149
+ return json.loads(payload)
150
+ except json.JSONDecodeError:
151
+ try:
152
+ cleaned = re.sub(r"[\n\r]+", " ", payload)
153
+ cleaned = re.sub(r"(['\"])?([a-zA-Z0-9_]+)(['\"])?\s*:\s*", r'"\2": ', cleaned)
154
+ return json.loads(cleaned)
155
+ except Exception:
156
+ return None
157
+
158
+
159
+ def _extract_grouping(question: str, segment: str | None = None):
160
+ lower = question.lower()
161
+ for keyword, group_col in GROUPING_MAP.items():
162
+ if keyword in lower:
163
+ return group_col
164
+ return segment if segment else None
165
+
166
+
167
+ def _extract_metrics(question: str):
168
+ lower = question.lower()
169
+ selected = []
170
+ for metric in RISK_METRICS:
171
+ if metric.lower() in lower:
172
+ selected.append(metric)
173
+ return selected if selected else ["All"]
174
+
175
+
176
+ def _infer_data_request(question: str, as_of_month: str | None = None, segment: str | None = None):
177
+ client = _get_inference_client()
178
+ prompt = (
179
+ "You are a data planning assistant for a risk analytics system. "
180
+ "Translate the user's natural language question into a structured data request. "
181
+ "Return only valid JSON with keys: data_req, grouping, metrics, as_of_month, segment. "
182
+ "data_req should be a list containing one or more of: [\"vintage\", \"calendar\", \"portfolio\", \"classification\"]. "
183
+ "grouping should be one of [\"fico_band\", \"sourcing_channel\", \"city_tier\", \"occupation_type\"] or null. "
184
+ "metrics should be [\"All\"] or a list of one or more of: [\"30+@3\", \"30+@6\", \"60+@6\", \"Yr1 NCL\"]. "
185
+ "as_of_month should be the requested month in YYYY-MM format, or \"All\" if the query wants full data or no explicit month. "
186
+ "segment should be the selected UI segment value or null.\n\n"
187
+ "Question: " + question + "\n"
188
+ "Selected UI month: " + (as_of_month or "All") + "\n"
189
+ "Selected UI segment: " + (segment or "None") + "\n"
190
+ )
191
+
192
+ response = client.chat.completions.create(
193
+ model=HF_MODEL_ID,
194
+ messages=[
195
+ {"role": "system", "content": "You are a system that returns only JSON structured data requests."},
196
+ {"role": "user", "content": prompt}
197
+ ],
198
+ max_tokens=200,
199
+ temperature=0.0,
200
+ top_p=0.95
201
+ )
202
+ text = response.choices[0].message.content if hasattr(response, 'choices') else str(response)
203
+ spec = _extract_json(text)
204
+ if not spec:
205
+ spec = {
206
+ "data_req": [],
207
+ "grouping": _extract_grouping(question, segment),
208
+ "metrics": _extract_metrics(question),
209
+ "as_of_month": as_of_month or "All",
210
+ "segment": segment or None
211
+ }
212
+
213
+ if not spec.get("data_req"):
214
+ q_lower = question.lower()
215
+ reqs = []
216
+ if any(token in q_lower for token in ["vintage", "booking", "trend", "performance"]):
217
+ reqs.append("vintage")
218
+ if any(token in q_lower for token in ["month", "calendar", "snapshot", "as of"]):
219
+ reqs.append("calendar")
220
+ if any(token in q_lower for token in ["segment", "classification", "ranking", "category", "group"]):
221
+ reqs.append("classification")
222
+ if not reqs:
223
+ reqs.append("portfolio")
224
+ spec["data_req"] = reqs
225
+
226
+ spec["as_of_month"] = spec.get("as_of_month") or as_of_month or "All"
227
+ spec["grouping"] = spec.get("grouping") or _extract_grouping(question, segment)
228
+ spec["metrics"] = spec.get("metrics") or ["All"]
229
+ spec["segment"] = spec.get("segment") or segment or None
230
+ return spec
231
+
232
+
233
+ def _build_vintage_context(df: pd.DataFrame, grouping: str | None = None, metrics: list[str] | None = None):
234
+ metrics = metrics or ["All"]
235
+ if metrics == ["All"]:
236
+ metrics = RISK_METRICS
237
+
238
+ lines = ["Vintage performance context:"]
239
+ for metric in metrics:
240
+ try:
241
+ view = generate_metric_view(df, metric_name=metric, group_col=grouping)
242
+ if view.empty:
243
+ continue
244
+ rate_col = [c for c in view.columns if "rate" in c.lower()][0]
245
+ if grouping:
246
+ top_rows = view.sort_values(rate_col, ascending=False).head(3)
247
+ lines.append(f"{metric} top vintage/group combinations:")
248
+ for _, row in top_rows.iterrows():
249
+ lines.append(
250
+ f" - vintage {row['booking_vintage']}, {grouping}={row[grouping]}, rate={_fmt_pct(row[rate_col])}"
251
+ )
252
+ else:
253
+ highest = view.sort_values(rate_col, ascending=False).head(1).iloc[0]
254
+ lowest = view.sort_values(rate_col, ascending=True).head(1).iloc[0]
255
+ lines.append(
256
+ f"{metric}: highest vintage {highest['booking_vintage']} at {_fmt_pct(highest[rate_col])}, "
257
+ f"lowest vintage {lowest['booking_vintage']} at {_fmt_pct(lowest[rate_col])}."
258
+ )
259
+ except Exception:
260
+ continue
261
+ return "\n".join(lines)
262
+
263
+
264
+ def _build_calendar_context(df: pd.DataFrame, as_of_month: str | None):
265
+ if not as_of_month or as_of_month == "All":
266
+ return ""
267
+
268
+ month_df = _filter_by_month(df, as_of_month)
269
+ if month_df.empty:
270
+ return f"No data found for {as_of_month}."
271
+
272
+ month_lines = [f"Calendar month performance context for {as_of_month}:"]
273
+ month_lines.append(f" - Total accounts: {month_df['account_id'].nunique() if 'account_id' in month_df.columns else 0}")
274
+ if 'balance' in month_df.columns:
275
+ month_lines.append(f" - Total balance: {month_df['balance'].sum(skipna=True):.0f}")
276
+ if 'dpd' in month_df.columns:
277
+ month_lines.append(f" - Accounts with dpd>=30: {month_df.loc[month_df['dpd'].fillna(0) >= 30, 'account_id'].nunique() if 'account_id' in month_df.columns else 0}")
278
+
279
+ return "\n".join(month_lines)
280
+
281
+
282
+ def _build_context_from_spec(df: pd.DataFrame, spec: dict):
283
+ sections = []
284
+
285
+ if 'portfolio' in spec.get('data_req', []):
286
+ sections.append(build_portfolio_context(df, as_of_month=spec.get('as_of_month'), segment=spec.get('segment')))
287
+
288
+ if 'calendar' in spec.get('data_req', []):
289
+ calendar_section = _build_calendar_context(df, spec.get('as_of_month'))
290
+ if calendar_section:
291
+ sections.append(calendar_section)
292
+
293
+ if 'vintage' in spec.get('data_req', []):
294
+ vintage_section = _build_vintage_context(df, grouping=spec.get('grouping'), metrics=spec.get('metrics'))
295
+ if vintage_section:
296
+ sections.append(vintage_section)
297
+
298
+ if 'classification' in spec.get('data_req', []):
299
+ classification = build_portfolio_context(df, as_of_month=spec.get('as_of_month'), segment=spec.get('segment'))
300
+ if classification:
301
+ sections.append(classification)
302
+
303
+ if not sections:
304
+ sections.append(build_portfolio_context(df, as_of_month=spec.get('as_of_month'), segment=spec.get('segment')))
305
+
306
+ return "\n\n".join(sections)
307
+
308
+
309
+ def _get_inference_client():
310
+ if not HF_TOKEN:
311
+ raise RuntimeError(
312
+ "HUGGINGFACE_API_TOKEN is required for AI assistant. "
313
+ "Set it in your environment before running the app."
314
+ )
315
+ return InferenceClient(token=HF_TOKEN)
316
+
317
+
318
+ def generate_ai_answer(question: str, df: pd.DataFrame, as_of_month: str | None = None, segment: str | None = None):
319
+ request_spec = _infer_data_request(question, as_of_month=as_of_month, segment=segment)
320
+ context = _build_context_from_spec(df, request_spec)
321
+ prompt = (
322
+ "You are a senior risk manager assistant responding to portfolio analytics questions. "
323
+ "Use the risk context below and answer the user clearly, describing what is happening, why it is happening, and what actions should be considered. "
324
+ "If you cannot answer from the data, say so clearly.\n\n"
325
+ "Data request spec:\n" + json.dumps(request_spec, indent=2) + "\n\n"
326
+ "Context:\n" + context + "\n\n"
327
+ "Question: " + question + "\n\n"
328
+ "Answer as a risk manager with practical, concise guidance."
329
+ )
330
+
331
+ client = _get_inference_client()
332
+ messages = [
333
+ {"role": "system", "content": "You are a senior risk manager assistant."},
334
+ {"role": "user", "content": prompt}
335
+ ]
336
+
337
+ response = client.chat.completions.create(
338
+ model=HF_MODEL_ID,
339
+ messages=messages,
340
+ max_tokens=HF_MAX_TOKENS,
341
+ temperature=HF_TEMPERATURE,
342
+ top_p=0.95
343
+ )
344
+
345
+ output_text = response.choices[0].message.content if hasattr(response, 'choices') else (response[0].get('generated_text') if isinstance(response, list) else str(response))
346
+ return output_text