File size: 8,699 Bytes
cb983ab
 
 
6646ff4
cb983ab
 
 
 
 
 
6646ff4
cb983ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6646ff4
 
cb983ab
 
 
 
 
 
 
 
 
6646ff4
cb983ab
 
 
 
 
 
 
 
 
6646ff4
 
 
 
 
 
 
 
 
 
 
 
cb983ab
 
 
 
6646ff4
cb983ab
 
 
 
6646ff4
cb983ab
 
 
 
 
 
 
 
 
 
 
 
6646ff4
 
cb983ab
 
 
 
 
 
6646ff4
cb983ab
 
 
 
 
 
 
 
6646ff4
cb983ab
 
 
 
 
6646ff4
cb983ab
 
 
 
6646ff4
 
cb983ab
 
 
 
6646ff4
cb983ab
 
 
 
6646ff4
 
 
cb983ab
 
 
6646ff4
cb983ab
 
6646ff4
 
 
 
 
 
cb983ab
6646ff4
cb983ab
6646ff4
 
cb983ab
 
6646ff4
cb983ab
6646ff4
cb983ab
 
6646ff4
cb983ab
 
 
 
6646ff4
cb983ab
6646ff4
 
cb983ab
6646ff4
cb983ab
 
 
 
6646ff4
cb983ab
6646ff4
cb983ab
 
6646ff4
cb983ab
 
 
 
6646ff4
cb983ab
 
6646ff4
cb983ab
6646ff4
cb983ab
 
 
6646ff4
cb983ab
6646ff4
 
 
 
cb983ab
6646ff4
 
cb983ab
6646ff4
cb983ab
6646ff4
cb983ab
6646ff4
 
 
 
 
 
 
 
cb983ab
6646ff4
cb983ab
6646ff4
 
cb983ab
 
 
6646ff4
cb983ab
 
 
 
 
 
 
 
 
 
 
6646ff4
 
 
cb983ab
6646ff4
cb983ab
 
6646ff4
cb983ab
 
6646ff4
 
cb983ab
6646ff4
cb983ab
 
 
 
 
 
6646ff4
cb983ab
6646ff4
cb983ab
6646ff4
cb983ab
6646ff4
 
cb983ab
 
 
 
6646ff4
cb983ab
 
 
 
6646ff4
cb983ab
6646ff4
 
 
 
cb983ab
6646ff4
cb983ab
6646ff4
cb983ab
 
6646ff4
cb983ab
 
 
 
6646ff4
cb983ab
6646ff4
 
cb983ab
 
 
6646ff4
cb983ab
 
 
6646ff4
 
 
cb983ab
6646ff4
cb983ab
6646ff4
 
 
 
 
 
 
 
cb983ab
6646ff4
 
 
cb983ab
 
 
 
6646ff4
6660832
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# deep_dive_agentic.py

"""
Agentic analytical code generation + execution engine using Hugging Face + IPython

FLOW:
User Question

LLM generates pandas code

IPython executes code (stateful, notebook-like)

LLM interprets results

Return code + interpretation
"""

# ---------------------------------------------------
# IMPORTS
# ---------------------------------------------------

import pandas as pd
import json
import os
import re

from IPython.core.interactiveshell import InteractiveShell

try:
    from huggingface_hub import InferenceClient
except ImportError as exc:
    raise ImportError(
        "huggingface_hub is required. Install with `pip install huggingface-hub`."
    ) from exc

from analytics.performance_analysis import generate_metric_view


# ---------------------------------------------------
# HF CONFIG
# ---------------------------------------------------

HF_MODEL_ID = os.environ.get("HF_MODEL_ID", "Qwen/Qwen2.5-7B-Instruct")
HF_TOKEN = os.environ.get("HUGGINGFACE_API_TOKEN")


# ---------------------------------------------------
# IPYTHON SHELL (STATEFUL EXECUTION ENGINE)
# ---------------------------------------------------

IPY_SHELL = InteractiveShell.instance()

# preload global tools
IPY_SHELL.user_ns["pd"] = pd
IPY_SHELL.user_ns["generate_metric_view"] = generate_metric_view


# ---------------------------------------------------
# HELPER: HF CLIENT
# ---------------------------------------------------

def _get_hf_client():
    if not HF_TOKEN:
        raise RuntimeError("HUGGINGFACE_API_TOKEN is required.")
    return InferenceClient(token=HF_TOKEN)


# ---------------------------------------------------
# HELPER: JSON EXTRACTION
# ---------------------------------------------------

def _extract_json(text: str):
    match = re.search(r"\{.*\}", text, re.S)
    if not match:
        return None
    payload = match.group(0)

    try:
        return json.loads(payload)
    except json.JSONDecodeError:
        try:
            cleaned = re.sub(r"[\n\r]+", " ", payload)
            cleaned = re.sub(r"(['\"])?([a-zA-Z0-9_]+)(['\"])?\s*:\s*", r'"\2": ', cleaned)
            return json.loads(cleaned)
        except Exception:
            return None


# ---------------------------------------------------
# HELPER: PANDAS FIXES
# ---------------------------------------------------

def _fix_pandas_compatibility(code: str):
    code = re.sub(
        r"\.reset_index\(name=(['\"])([^'\"]+)\1\)",
        r".reset_index(names=[\1\2\1])",
        code
    )

    code = re.sub(
        r"\.reset_index\(name=([a-zA-Z_][a-zA-Z0-9_]*)\)",
        r".reset_index(names=[\1])",
        code
    )

    return code


# ---------------------------------------------------
# STEP 1: REQUIREMENT GENERATION
# (UNCHANGED)
# ---------------------------------------------------

def generate_analysis_requirements(question: str, acq: pd.DataFrame, perf: pd.DataFrame, master_df: pd.DataFrame):
    client = _get_hf_client()

    acq_cols = {
        "account_id": "unique account identifier",
        "booking_date": "when account was originated",
        "booking_vintage": "year-month of origination (YYYY-MM)",
        "fico_band": "FICO score bracket",
        "sourcing_channel": "acquisition channel",
        "city_tier": "city classification",
        "occupation_type": "borrower occupation category",
        "credit_limit": "approved credit line amount"
    }

    perf_cols = {
        "account_id": "unique account identifier",
        "reporting_month": "month of performance observation",
        "mob": "months on books",
        "dpd": "days past due",
        "balance": "outstanding balance",
        "ncl_amount": "net charge-off amount",
        "payment": "payment amount"
    }

    prompt = (
        "You are a senior credit risk analyst.\n"
        "Return ONLY JSON.\n\n"
        "User Question:\n" + question
    )

    messages = [
        {"role": "system", "content": "Return only valid JSON."},
        {"role": "user", "content": prompt}
    ]

    response = client.chat.completions.create(
        model=HF_MODEL_ID,
        messages=messages,
        max_tokens=2048,
        temperature=0.1
    )

    response_text = response.choices[0].message.content
    spec = _extract_json(response_text)

    if not spec:
        return {
            "success": False,
            "requirements": [],
            "error": response_text[:300]
        }

    return {
        "success": True,
        "requirements": spec.get("requirements", [])
    }


# ---------------------------------------------------
# STEP 2: EXECUTION (IPYTHON BASED)
# ---------------------------------------------------

def execute_requirement_code(code: str, acq: pd.DataFrame, perf: pd.DataFrame, master_df: pd.DataFrame, requirement_num: int):
    """
    Execute generated pandas code using IPython (stateful + notebook-like).
    """

    try:
        print(f"\n[DEBUG] Executing requirement {requirement_num} via IPython")

        # refresh latest data into kernel
        IPY_SHELL.user_ns["acq"] = acq
        IPY_SHELL.user_ns["perf"] = perf
        IPY_SHELL.user_ns["master_df"] = master_df

        # optional fix
        code = _fix_pandas_compatibility(code)

        print("\n[EXECUTED CODE]\n", code)

        result = IPY_SHELL.run_cell(code, store_history=True)

        # error handling
        if result.error_before_exec or result.error_in_exec:
            err = str(result.error_in_exec or result.error_before_exec)
            return {
                "success": False,
                "result": None,
                "error": err
            }

        ns = IPY_SHELL.user_ns

        result_key = f"result_{requirement_num}"
        output = ns.get(result_key, ns.get("final_result", ns.get("result", None)))

        return {
            "success": True,
            "result": output,
            "error": None
        }

    except Exception as e:
        return {
            "success": False,
            "result": None,
            "error": str(e)
        }


# ---------------------------------------------------
# STEP 3: EXECUTE ALL REQUIREMENTS
# ---------------------------------------------------

def execute_all_requirements(requirements, acq, perf, master_df):
    all_results = []
    context_text = ""

    for i, req in enumerate(requirements, 1):
        code = req.get("code", "")
        title = req.get("title", "")

        exec_result = execute_requirement_code(code, acq, perf, master_df, i)

        all_results.append({
            "sequence": i,
            "title": title,
            "code": code,
            "execution_success": exec_result["success"],
            "result": exec_result["result"],
            "error": exec_result["error"]
        })

        if exec_result["success"]:
            context_text += f"\n[{title}]\n{exec_result['result']}\n"
        else:
            context_text += f"\n[{title} FAILED]\n{exec_result['error']}\n"

    return all_results, context_text


# ---------------------------------------------------
# STEP 4: INTERPRETATION (UNCHANGED LOGIC)
# ---------------------------------------------------

def interpret_all_results(question: str, all_results: list, context_text: str):
    client = _get_hf_client()

    prompt = (
        "You are a senior credit risk analyst.\n\n"
        "Question:\n" + question + "\n\n"
        "Results:\n" + context_text + "\n\n"
        "Provide insights."
    )

    messages = [
        {"role": "system", "content": "You are a senior analyst."},
        {"role": "user", "content": prompt}
    ]

    response = client.chat.completions.create(
        model=HF_MODEL_ID,
        messages=messages,
        max_tokens=1024,
        temperature=0.3
    )

    return response.choices[0].message.content


# ---------------------------------------------------
# MASTER ORCHESTRATOR
# ---------------------------------------------------

def run_deep_dive_analysis(question: str, acq: pd.DataFrame, perf: pd.DataFrame, master_df: pd.DataFrame):

    print(f"\n[DEEP DIVE START] {question}")

    req_response = generate_analysis_requirements(question, acq, perf, master_df)

    if not req_response["success"]:
        return req_response

    requirements = req_response["requirements"][:3]

    all_results, context_text = execute_all_requirements(
        requirements, acq, perf, master_df
    )

    interpretation = interpret_all_results(question, all_results, context_text)

    print("\n[DEEP DIVE COMPLETE]\n")

    return {
        "success": True,
        "requirements": requirements,
        "all_results": all_results,
        "interpretation": interpretation
    }