npkits commited on
Commit
cd8886e
·
verified ·
1 Parent(s): 55dec8f

Update src/afhtp.py

Browse files

added
BASE = Path(__file__).resolve().parent # directory of afhtp.py
doc_path = BASE / "afhtp.md"

Files changed (1) hide show
  1. src/afhtp.py +719 -719
src/afhtp.py CHANGED
@@ -1,720 +1,720 @@
1
- ## version v0.2
2
- import streamlit as st
3
- from pathlib import Path
4
- import pandas as pd
5
- import numpy as np
6
- import faiss
7
- import torch
8
- import time
9
- from datetime import datetime
10
- from streamlit.components.v1 import html
11
- from sentence_transformers import SentenceTransformer
12
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
13
- from langgraph.graph import StateGraph, END
14
- from langgraph.graph.state import CompiledStateGraph
15
- from typing import Dict, Any, Optional, TypedDict
16
-
17
-
18
- # ---- SETUP ----
19
- # Place this at the top of your page so the anchor exists
20
- st.markdown('<div id="top"></div>', unsafe_allow_html=True)
21
-
22
- # ---- PAGE CONFIG ----
23
- st.set_page_config(page_title="AFTP Hardship Planner", layout="centered")
24
- st.sidebar.title("🔍 Navigation")
25
- app_mode = st.sidebar.radio("Go to", ["🏛️ AFHTP Planner", "📄 View Documentation"])
26
-
27
- # ---- DOCUMENTATION VIEW ----
28
- if app_mode == "📄 View Documentation":
29
- doc_path = Path("afhtp.md")
30
- if doc_path.exists():
31
- with open(doc_path, "r", encoding="utf-8") as f:
32
- markdown_content = f.read()
33
-
34
- # Ensure top anchor exists so "back to top" has somewhere to scroll
35
- if '<div id="top">' not in markdown_content:
36
- markdown_content = '<div id="top"></div>\n' + markdown_content
37
-
38
- st.markdown(markdown_content, unsafe_allow_html=True)
39
-
40
- # Inject floating back-to-top button (only for this view)
41
- button_widget = """
42
- <style>
43
- #back-to-top {
44
- position: fixed;
45
- bottom: 24px;
46
- right: 24px;
47
- width: 52px;
48
- height: 52px;
49
- background: #1f77b4;
50
- border-radius: 50%;
51
- box-shadow: 0 6px 18px rgba(0,0,0,0.2);
52
- display: flex;
53
- align-items: center;
54
- justify-content: center;
55
- z-index: 9999;
56
- cursor: pointer;
57
- transition: opacity .25s ease, transform .2s ease;
58
- opacity: 0;
59
- font-family: system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;
60
- }
61
- #back-to-top:focus { outline: 3px solid #ffffff; }
62
- #back-to-top:hover { transform: scale(1.05); }
63
- #back-to-top svg { width: 24px; height: 24px; fill: white; }
64
- @media (max-width: 768px) {
65
- #back-to-top {
66
- bottom: 16px;
67
- right: 16px;
68
- width: 44px;
69
- height: 44px;
70
- }
71
- #back-to-top svg { width: 20px; height: 20px; }
72
- }
73
- </style>
74
-
75
- <div id="back-to-top" aria-label="Back to top" role="button" tabindex="0" title="Back to top">
76
- <svg viewBox="0 0 24 24" aria-hidden="true">
77
- <path d="M4 12l1.41 1.41L11 7.83V20h2V7.83l5.59 5.58L20 12l-8-8-8 8z"/>
78
- </svg>
79
- </div>
80
-
81
- <script>
82
- (function() {
83
- const btn = document.getElementById('back-to-top');
84
-
85
- function toggleVisibility() {
86
- if (window.scrollY > window.innerHeight / 3) {
87
- btn.style.opacity = '1';
88
- btn.setAttribute('aria-hidden','false');
89
- } else {
90
- btn.style.opacity = '0';
91
- btn.setAttribute('aria-hidden','true');
92
- }
93
- }
94
-
95
- function scrollToTop() {
96
- window.scrollTo({ top: 0, behavior: 'smooth' });
97
- }
98
-
99
- btn.addEventListener('click', scrollToTop);
100
- btn.addEventListener('keydown', function(e) {
101
- if (e.key === 'Enter' || e.key === ' ') {
102
- e.preventDefault();
103
- scrollToTop();
104
- }
105
- });
106
-
107
- document.addEventListener('scroll', toggleVisibility);
108
- toggleVisibility();
109
- })();
110
- </script>
111
- """
112
-
113
- # Use components.html so the JS/CSS executes
114
- html(button_widget, height=0)
115
- else:
116
- st.error("📄 Documentation file 'afhtp.md' not found.")
117
- st.stop()
118
-
119
-
120
- #st.title("🏛️ AFTP Hardship Treatment Planner")
121
- st.subheader("![image/png](https://cdn-uploads.huggingface.co/production/uploads/688abc51f5077dea074b2f8d/dSu3n5I9OyaIQtNWP6kt5.png) Autonomous Financial Hardship Treatment Planner")
122
-
123
- # ---- LLM LOAD ----
124
- @st.cache_resource
125
- def load_llm():
126
- model_id = "google/flan-t5-small"
127
- tokenizer = AutoTokenizer.from_pretrained(model_id)
128
- model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
129
- return model, tokenizer
130
-
131
- llm_model, llm_tokenizer = load_llm()
132
- llm_model.eval()
133
-
134
- # ---- VECTOR STORE ----
135
- encoder = SentenceTransformer("all-MiniLM-L6-v2")
136
- index = faiss.IndexFlatL2(384)
137
- vector_store = {}
138
-
139
- def build_embedding(app: dict) -> str:
140
- return f"{app['hardship_reason']} income:{app['income']} expenses:{app['expenses']}"
141
-
142
- def store_context(customer_id: str, embedding_text: str, context: dict):
143
- vector = encoder.encode([embedding_text])[0]
144
- index.add(np.array([vector]))
145
- vector_store[customer_id] = {"vector": vector, "context": context}
146
-
147
- ## Sample Hardship treatment plans Prepopulation
148
- def prepopulate_sample_cases():
149
- """
150
- Prepopulate vector store with realistic historical cases for similarity matching.
151
- """
152
- sample_cases = [
153
- {"customer_id": "C100", "app": {"hardship_reason": "Job Loss", "income": 1500,"expenses": 2200}, "context": {"plan": "3-month deferral",
154
- "status": "completed"}},
155
- {"customer_id": "C101", "app": {"hardship_reason": "Natural Disaster", "income": 1800, "expenses": 2100}, "context": {"plan": "interest reduction",
156
- "status": "completed"}},
157
- {"customer_id": "C102", "app": {"hardship_reason": "Medical", "income": 2000, "expenses": 2500}, "context": {"plan": "partial payment suspension",
158
- "status": "completed"}},
159
- {"customer_id": "C103", "app": {"hardship_reason": "Job Loss", "income": 1400, "expenses": 2000}, "context": {"plan": "3-month deferral",
160
- "status": "completed"}},
161
- {"customer_id": "C104", "app": {"hardship_reason": "Natural Disaster", "income": 2500, "expenses": 2600}, "context": {"plan": "payment extension",
162
- "status": "completed"}}
163
- ]
164
-
165
- for case in sample_cases:
166
- embedding_text = build_embedding(case["app"])
167
- store_context(case["customer_id"], embedding_text, case["context"])
168
-
169
- if len(vector_store) == 0: #avoid repopulating on every rerun,
170
- prepopulate_sample_cases()
171
-
172
-
173
- # ---- Hardcoded Plans ----
174
- hardship_plans = {
175
- "3-month deferral": {"description": "Suspend payments for 3 months.", "risk_score": 2},
176
- "partial payment suspension": {"description": "Pay only 50% for 3 months.", "risk_score": 3},
177
- "interest reduction": {"description": "Reduce interest by 25% for 6 months.", "risk_score": 1},
178
- "payment extension": {"description": "Extend term by 12 months.", "risk_score": 4},
179
- "restructure repayment": {"description": "Restructure repayment terms based on income profile.", "risk_score": 3},
180
- "defer interest only": {"description": "Pay only interest for 3 months.", "risk_score": 2},
181
- "grace period": {"description": "Grace period of 1 month with no payment.", "risk_score": 1}
182
- }
183
-
184
- # ---- Sample Case Workers ----
185
- case_worker_df = pd.DataFrame([
186
- {"name": "Peter Swift", "plan": "3-month deferral", "experience_years": 5, "on_leave": False},
187
- {"name": "Anthony Mackay", "plan": "interest reduction", "experience_years": 7, "on_leave": False},
188
- {"name": "Sara Keeves", "plan": "partial payment suspension", "experience_years": 4, "on_leave": True},
189
- {"name": "Lara Brent", "plan": "partial payment suspension", "experience_years": 5, "on_leave": False},
190
- {"name": "David Ray", "plan": "payment extension", "experience_years": 6, "on_leave": False},
191
- ])
192
-
193
- def assign_case_worker(plan: str):
194
- available = case_worker_df[(case_worker_df["plan"] == plan) & (~case_worker_df["on_leave"])]
195
- if not available.empty:
196
- return available.sample(1).iloc[0]
197
- return None
198
-
199
- def assign_human_caseworker():
200
- available = case_worker_df[(case_worker_df["experience_years"] >= 5) & (~case_worker_df["on_leave"])]
201
- if not available.empty:
202
- return available.sample(1).iloc[0]
203
- return None
204
-
205
- # ---- AgentState TypedDict ----
206
- class AgentState(TypedDict):
207
- application: Optional[Dict[str, Any]]
208
- selected_plan: Optional[str]
209
- escalated: bool
210
- handled: bool
211
- matched_case_df: Optional[pd.DataFrame]
212
- ltm_match_history: list
213
- feedback: Optional[str]
214
- submitted_feedbacks: set
215
- reference_id: Optional[str]
216
- agent_logs: list
217
- current_node: str
218
- eligible_plans: Optional[list]
219
- previous_plans: list
220
-
221
- # ---- Eligibility and Matching Functions ----
222
- def check_eligibility(app: Dict) -> list:
223
- # Debug inside eligibility
224
- st.session_state.agent_state["agent_logs"].append(f"[Info] check_eligibility called with hardship_reason={app['hardship_reason']}, income={app['income']}, expenses={app['expenses']}")
225
- if app["hardship_reason"] == "Job Loss" and app["income"] < app["expenses"]:
226
- return ["3-month deferral", "partial payment suspension"]
227
- return ["payment extension", "interest reduction"]
228
-
229
- def check_proactive_escalation(app: Dict) -> bool:
230
- return app["history"]["late_payments"] > 3 or app.get("flagged_abuse", False)
231
-
232
- def match_from_ltm(app: Dict[str, Any]) -> Optional[pd.DataFrame]:
233
- if len(vector_store) == 0:
234
- return None
235
-
236
- query_vector = encoder.encode([build_embedding(app)])[0]
237
- similarity_threshold = 10.0
238
- D, I = index.search(np.array([query_vector]), k=1)
239
- distance = D[0][0]
240
-
241
- if distance <= similarity_threshold:
242
- match_id = list(vector_store.keys())[I[0][0]]
243
- matched_context = vector_store[match_id]["context"]
244
- matched_df = pd.DataFrame([{
245
- "Customer ID": match_id,
246
- "Plan": matched_context["plan"],
247
- "Status": matched_context.get("status", "N/A")
248
- }])
249
- return matched_df
250
- else:
251
- st.session_state.agent_state["agent_logs"].append(f"[Debug] No similar case found. Distance: {distance:.2f}")
252
- return None
253
-
254
- # ---- Node Functions ----
255
- # Hardcoded, safe validate() , this temporary fixed version that hard-forces the downstream steps unless escalation is needed:
256
- def validate(state: AgentState) -> AgentState:
257
- logs = state["agent_logs"]
258
- logs.append("[Node] Entered validate")
259
- app = state["application"]
260
- state["current_node"] = "validate"
261
-
262
- # Only escalate if absolutely needed
263
- if check_proactive_escalation(app):
264
- logs.append("[Info] Escalation triggered in validate()")
265
- state["escalated"] = True
266
- worker = assign_human_caseworker()
267
- if worker is not None:
268
- logs.append(f"[Escalation] Assigned to case worker: {worker['name']}")
269
- else:
270
- logs.append("[Escalation] No available senior case workers. Case queued.")
271
- state["handled"] = True
272
- else:
273
- logs.append("[Info] No escalation triggered in validate()")
274
- state["escalated"] = False
275
- state["handled"] = False # FORCE this
276
- logs.append(f"[Info] Post validate() state: escalated={state['escalated']}, handled={state['handled']}") # debug
277
- return state
278
-
279
- def reason_and_rank(state: AgentState) -> AgentState:
280
- logs = state["agent_logs"]
281
- logs.append("[Node] Entered reason_and_rank")
282
-
283
- app = state["application"]
284
- state["current_node"] = "reason_and_rank"
285
-
286
- # 1. Check eligibility
287
- eligible = check_eligibility(app)
288
- state["eligible_plans"] = eligible
289
-
290
- if eligible:
291
- top_plan = sorted(eligible, key=lambda p: hardship_plans[p]["risk_score"])[0]
292
- desc = hardship_plans[top_plan]["description"]
293
- logs.append(f"[Node: reason_and_rank] Eligible Plan: {top_plan} → {desc}")
294
- else:
295
- logs.append("[Node: reason_and_rank] No eligible plans found.")
296
-
297
- # 2. Try to match from Long-Term Memory (LTM)
298
- matched_df = match_from_ltm(app)
299
- if matched_df is not None:
300
- matched_plan = matched_df.iloc[0]["Plan"]
301
-
302
- # Check if user already saw this LTM plan
303
- if matched_plan not in state.get("previous_plans", []):
304
- logs.append(f"[LTM Match] Found matching plan from long-term memory: {matched_plan}")
305
- state["selected_plan"] = matched_plan
306
- state.setdefault("previous_plans", []).append(matched_plan)
307
- state["matched_case_df"] = matched_df
308
- state.setdefault("ltm_match_history", []).append(matched_df.copy()) # append the matched_df
309
- logs.append(f"[Plan Selection] Selected Plan from LTM: {matched_plan}")
310
- return state
311
- else:
312
- logs.append(f"[LTM Match] Skipped LTM plan {matched_plan} (already proposed)")
313
-
314
- # 3. No LTM match – proceed with ranking eligible hardcoded plans
315
- if not eligible:
316
- state["escalated"] = True
317
- state["handled"] = True
318
- logs.append("[Warning] No eligible plans found. Escalating to human agent.")
319
- return state
320
-
321
- # 4. Rank and pick plan from eligible ones
322
- ranked = sorted(eligible, key=lambda p: hardship_plans[p]["risk_score"])
323
- previous = state.get("previous_plans", [])
324
- ranked_filtered = [p for p in ranked if p not in previous]
325
-
326
- if not ranked_filtered:
327
- logs.append("[Plan Selection] No new plans left after filtering. Escalating.")
328
- state["escalated"] = True
329
- state["handled"] = True
330
- return state
331
-
332
- selected_plan = ranked_filtered[0]
333
- state["selected_plan"] = selected_plan
334
- state.setdefault("previous_plans", []).append(selected_plan)
335
-
336
- logs.append(f"[Plan Selection] Selected new plan: {selected_plan}")
337
-
338
- worker = assign_case_worker(selected_plan)
339
- if worker is not None:
340
- logs.append(f"[CRM] Assigned to {worker['name']} for plan: {selected_plan}")
341
- else:
342
- logs.append(f"[CRM] No available case worker for plan: {selected_plan}")
343
-
344
- return state
345
-
346
-
347
- def take_action(state: AgentState) -> AgentState:
348
- logs = state["agent_logs"]
349
- logs.append("[Node] Entered take_action()")
350
- app = state["application"]
351
- plan = state["selected_plan"]
352
- state["current_node"] = "take_action"
353
-
354
- # Defensive check in case already assigned earlier
355
- if "crm_logged" not in state:
356
- worker = assign_case_worker(plan)
357
- if worker is not None:
358
- logs.append(f"[CRM] Logged case for {app['name']} - Plan: {plan} → Assigned to {worker['name']}")
359
- else:
360
- logs.append(f"[CRM] No available case worker for plan: {plan}")
361
- state["crm_logged"] = True # prevent future re-logging
362
-
363
- # Store the decision in long-term memory (LTM)
364
- store_context(app["customer_id"], build_embedding(app), {"plan": plan, "status": "active"})
365
-
366
- state["handled"] = True
367
- return state
368
-
369
-
370
- # ---- Decide Next Node ----
371
- def decide_next_node(state: AgentState) -> str:
372
- logs = state["agent_logs"]
373
- current_node = state["current_node"]
374
- app = state.get("application", {})
375
- history = app.get("history", {})
376
- logs.append(f"[Router] At node: {current_node}") # debug code
377
- logs.append(f"[Info] decide_next_node() called at node: {current_node}") # debug code
378
-
379
- if state["handled"] or state["escalated"]:
380
- logs.append("[Router] Already handled or escalated - routing to END") # debug code
381
- return END
382
-
383
- # Define valid next nodes
384
- valid_next_nodes = {
385
- "validate": ["reason_and_rank", END],
386
- "reason_and_rank": ["take_action", END],
387
- "take_action": [END]
388
- }.get(current_node, [END])
389
-
390
- # Few-shot prompt
391
- few_shot = """
392
- Current Node: validate, flagged_abuse=False, selected_plan=None, handled=False → reason_and_rank
393
- Current Node: reason_and_rank, selected_plan=interest reduction, handled=False → take_action
394
- Current Node: take_action, handled=True → END
395
- Current Node: validate, escalated=True, handled=True → END
396
- """
397
-
398
- prompt = f"""
399
- You are an AI agent orchestrating a financial hardship planner.
400
- Given the current node and customer data, choose the next step in the process.
401
- {few_shot}
402
- Customer Info:
403
- - Name: {app.get('name', 'Unknown')}
404
- - Hardship Reason: {app.get('hardship_reason', 'Unknown')}
405
- - Income: {app.get('income', 'N/A')}
406
- - Expenses: {app.get('expenses', 'N/A')}
407
- - Late Payments: {history.get('late_payments', 0)}
408
- - Flagged Abuse: {app.get('flagged_abuse', False)}
409
- - Escalated: {state.get('escalated', False)}
410
- - Handled: {state.get('handled', False)}
411
- - Selected Plan: {state.get('selected_plan')}
412
- - Eligible Plans: {state.get('eligible_plans', [])}
413
- - Current Node: {current_node}
414
- Next: {', '.join(valid_next_nodes)}
415
- """
416
-
417
- with torch.no_grad():
418
- start = time.time()
419
- input_ids = llm_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512).input_ids
420
- outputs = llm_model.generate(input_ids=input_ids, max_new_tokens=10, do_sample=False)
421
- end = time.time()
422
- response = llm_tokenizer.decode(outputs[0], skip_special_tokens=True).strip().lower()
423
- response = response.split()[0] # Only take first word to normalize
424
- logs.append(f"[Router] LLM output: {response}") # debug code
425
- #st.markdown(f"⏲ **LLM inference time:** `{end - start:.2f} seconds`")
426
- st.markdown(f"⏳ **LLM inference time:** `{end - start:.2f} seconds`")
427
-
428
- if response not in valid_next_nodes:
429
- logs.append(f"[Router Warning] Invalid LLM output '{response}', defaulting to {valid_next_nodes[0]}") # debug code
430
- return valid_next_nodes[0]
431
-
432
- if response == "end" or state["escalated"]:
433
- logs.append("[Router] Routing to END due to LLM output or escalation.")
434
- return END
435
-
436
- if state["selected_plan"] is None and response == "take_action":
437
- logs.append("[Router Warning] LLM tried to skip reasoning. Forcing reason_and_rank.") # debug code
438
- return "reason_and_rank"
439
-
440
- logs.append(f"[Router] Moving from {current_node} to {response}")
441
- return response
442
-
443
- # ---- LangGraph Workflow Setup ----
444
- workflow = StateGraph(AgentState)
445
- workflow.add_node("validate", validate)
446
- workflow.add_node("reason_and_rank", reason_and_rank)
447
- workflow.add_node("take_action", take_action)
448
-
449
- workflow.add_conditional_edges(
450
- "validate",
451
- decide_next_node,
452
- {
453
- "reason_and_rank": "reason_and_rank",
454
- END: END
455
- }
456
- )
457
- workflow.add_conditional_edges(
458
- "reason_and_rank",
459
- decide_next_node,
460
- {
461
- "take_action": "take_action",
462
- END: END
463
- }
464
- )
465
- workflow.add_conditional_edges(
466
- "take_action",
467
- decide_next_node,
468
- {
469
- END: END
470
- }
471
- )
472
- workflow.set_entry_point("validate")
473
- graph: CompiledStateGraph = workflow.compile()
474
-
475
- # ---- Initialize session state ----
476
- def init_session():
477
- if "step" not in st.session_state:
478
- st.session_state.step = "form"
479
- if "application" not in st.session_state:
480
- st.session_state.application = None
481
- if "plan_accepted" not in st.session_state:
482
- st.session_state.plan_accepted = False
483
- if "escalated" not in st.session_state:
484
- st.session_state.escalated = False
485
- if "handled" not in st.session_state:
486
- st.session_state.handled = False
487
- if "matched_case_df" not in st.session_state:
488
- st.session_state.matched_case_df = None
489
- if "feedback" not in st.session_state:
490
- st.session_state.feedback = None
491
- if "submitted_feedbacks" not in st.session_state:
492
- st.session_state.submitted_feedbacks = set()
493
- if "reference_id" not in st.session_state:
494
- st.session_state.reference_id = None
495
- if "agent_logs" not in st.session_state:
496
- st.session_state.agent_logs = []
497
- if "previous_plans" not in st.session_state:
498
- st.session_state.previous_plans = []
499
- if "agent_state" not in st.session_state or st.session_state.agent_state is None:
500
- st.session_state.agent_state = AgentState(
501
- application=None,
502
- selected_plan=None,
503
- escalated=False,
504
- handled=False,
505
- matched_case_df=None,
506
- ltm_match_history=[],
507
- feedback=None,
508
- submitted_feedbacks=set(),
509
- reference_id=None,
510
- agent_logs=[],
511
- current_node="validate",
512
- eligible_plans=None,
513
- previous_plans=[]
514
- )
515
-
516
- init_session()
517
-
518
- # ---- UI and workflow execution ----
519
- if st.session_state.step == "form":
520
- with st.form("user_input"):
521
- #st.subheader("📝 Enter Your Details")
522
- st.subheader("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/6Om0nXTbrf8Mew4zJ7Gsh.png) Enter Your Details")
523
- name = st.text_input("First Name")
524
- customer_id = st.text_input("Customer ID")
525
- account_type = st.selectbox("Account Type", ["mortgage", "credit card", "personal loan"])
526
- hardship_reason = st.selectbox("Reason for Hardship", ["Job Loss", "Medical", "Natural Disaster"])
527
- income = st.number_input("Monthly Income", min_value=0.0)
528
- expenses = st.number_input("Monthly Expenses", min_value=0.0)
529
- late_payments = st.number_input("Late Payments (last 12 months)", min_value=0, step=1)
530
- flagged_abuse = st.radio("Previously defaulted or rejected?", ["No", "Yes"]) == "Yes"
531
- submitted = st.form_submit_button("Submit")
532
-
533
- if submitted:
534
- if not name.strip():
535
- st.warning("⚠️ Please enter your name.")
536
- elif not customer_id.strip():
537
- st.warning("⚠️ Please enter your customer ID.")
538
- elif income == 0.0:
539
- st.warning("⚠️ Please enter your income.")
540
- elif expenses == 0.0:
541
- st.warning("⚠️ Please enter your expenses.")
542
- else:
543
- st.session_state.application = {
544
- "name": name.strip(),
545
- "account_type": account_type,
546
- "hardship_reason": hardship_reason,
547
- "income": income,
548
- "expenses": expenses,
549
- "history": {"late_payments": late_payments},
550
- "flagged_abuse": flagged_abuse,
551
- "customer_id": customer_id,
552
- }
553
- st.session_state.agent_state["application"] = st.session_state.application
554
- st.session_state.agent_state["current_node"] = "validate"
555
- st.session_state.agent_state["selected_plan"] = None
556
- st.session_state.agent_state["escalated"] = False
557
- st.session_state.agent_state["handled"] = False
558
- st.session_state.agent_state["matched_case_df"] = None
559
- st.session_state.agent_state["feedback"] = None
560
- st.session_state.agent_state["eligible_plans"] = None
561
- st.session_state.agent_state["submitted_feedbacks"] = set()
562
- st.session_state.agent_state["agent_logs"] = []
563
- st.session_state.step = "processing"
564
- st.rerun()
565
-
566
- elif st.session_state.step == "processing":
567
- #st.info("📡 Processing your request...")
568
- st.info("![image/gif](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/8tQqf9gWdbl9Sb3bO6O6C.gif) Processing your request...")
569
- state = st.session_state.agent_state
570
- logs = state["agent_logs"] # This line is required
571
- logs.append("[Node] Processing plan recommendation...")
572
-
573
- # Run the graph streaming to execute the workflow nodes including reason_and_rank and take_action
574
- for updated_state in graph.stream(state):
575
- node_name, inner_state = list(updated_state.items())[0]
576
-
577
- # Update session state with the new state
578
- st.session_state.agent_state = inner_state
579
- st.session_state.agent_logs = inner_state.get("agent_logs", [])
580
- st.session_state.ltm_match_history = inner_state.get("ltm_match_history", [])
581
- st.session_state.escalated = inner_state.get("escalated", False)
582
- st.session_state.handled = inner_state.get("handled", False)
583
- st.session_state.matched_case_df = inner_state.get("matched_case_df")
584
- st.session_state.reference_id = inner_state.get("reference_id")
585
-
586
- state = inner_state # Feed updated state back to next iteration
587
-
588
- #inner_state["agent_logs"].append(f"[Debug] Node executed: {node_name}") # debug code
589
- inner_state["agent_logs"].append(f"[Info] node executed]: {node_name}")
590
-
591
- if node_name == END:
592
- break
593
-
594
- #st.write("✅ Final state from LangGraph:") # debug code
595
- #st.json(state) # debug code
596
-
597
- # Move to results after processing the entire graph
598
- st.session_state.step = "results"
599
- st.rerun()
600
-
601
-
602
- elif st.session_state.step == "results":
603
- state = st.session_state.agent_state
604
-
605
- if st.session_state.escalated:
606
- st.warning("⚠️ Your case has been assigned to a agent for review.")
607
- ref = f"{state['application']['customer_id'].upper()}-{datetime.now().strftime('%d%m%y%H%M%S')}"
608
- state["reference_id"] = ref
609
- st.markdown(f"**Reference#:** `{ref}`")
610
- if st.button("⮎ Continue"):
611
- for k in list(st.session_state.keys()):
612
- del st.session_state[k]
613
- st.rerun()
614
- st.session_state.step = "done"
615
- st.stop()
616
-
617
- elif state.get("selected_plan"):
618
- plan = state["selected_plan"]
619
- st.success(f"✅ Proposed Plan: **{plan}**")
620
- st.markdown(f"**{hardship_plans[plan]['description']}**")
621
-
622
- #Suggestion (Optional)
623
- #ranked = sorted(state.get("eligible_plans", []), key=lambda p: hardship_plans[p]["risk_score"])
624
- #if plan in ranked and len(ranked) > 1:
625
- # alternatives = [p for p in ranked if p != plan]
626
- # second_best = alternatives[0]
627
- # st.info(f"💡 You might also consider: **{second_best}** — {hardship_plans[second_best]['description']}")
628
-
629
- submitted = state["submitted_feedbacks"]
630
- remaining = {"Accept", "I can only afford half", "Suggest alternative"} - submitted
631
-
632
- if "Accept" in submitted:
633
- st.success("Thank you for your response.")
634
- st.success(f"You have accepted the proposed plan: **{plan}**")
635
- ref = state.get("reference_id")
636
- if ref:
637
- st.markdown(f"**Reference#:** `{ref}`")
638
- if st.button("🔁 Submit New Request"):
639
- for k in list(st.session_state.keys()):
640
- del st.session_state[k]
641
- st.rerun()
642
- st.session_state.step = "done"
643
- st.stop()
644
-
645
- # Show feedback options only if not already accepted
646
- options = [opt for opt in ["Accept", "I can only afford half", "Suggest alternative"] if opt in remaining] #options = list(remaining)
647
- feedback = st.radio("Feedback (choose one):", options, key="feedback_choice")
648
-
649
- if st.button("Submit Feedback"):
650
- submitted.add(feedback)
651
- state["submitted_feedbacks"] = submitted
652
- state["agent_logs"].append(f"[Feedback] User selected: {feedback}")
653
-
654
- if feedback == "Accept":
655
- state["handled"] = True
656
- ref = f"{state['application']['customer_id'].upper()}-{datetime.now().strftime('%d%m%y%H%M%S')}"
657
- state["reference_id"] = ref
658
- st.session_state.step = "done"
659
- st.rerun()
660
-
661
-
662
- elif "half" in feedback.lower():
663
- state["agent_logs"].append("[Feedback Action] User selected 'half'. Reducing income and rerunning reason_and_rank")
664
- state["application"]["income"] = state["application"]["income"] / 2 # Adjust income
665
- state["feedback"] = "half"
666
- state["handled"] = False
667
- state.pop("selected_plan", None) # Force recomputation
668
- state.pop("matched_case_df", None) #clear matched case display (but keep history)
669
- state["current_node"] = "reason_and_rank"
670
- st.session_state.step = "processing"
671
- st.rerun()
672
-
673
- elif feedback == "Suggest alternative":
674
- state["feedback"] = "wants_alternative"
675
- state["handled"] = False
676
- state["current_node"] = "reason_and_rank"
677
- state["agent_logs"].append("[Feedback Action] User requested alternative. Clearing selected_plan and rerunning reason_and_rank")
678
- state.pop("selected_plan", None) #clear old plan so it doesn't get reused
679
- state.pop("matched_case_df", None) # clear matched case display (but keep history)
680
- st.session_state.step = "processing"
681
- st.rerun()
682
- else:
683
- st.warning("⚠️ No plan could be proposed.")
684
- st.session_state.step = "done"
685
- st.rerun()
686
-
687
- elif st.session_state.step == "done":
688
- state = st.session_state.agent_state
689
- #st.success("🎉 Thank you for your response.")
690
- st.success("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/2KNwWbE-GjSYTOpfcA0N3.png) Thank you for your response.")
691
- if state.get("selected_plan"):
692
- st.markdown(f"**You have accepted the proposed plan:** `{state['selected_plan']}`")
693
- if state.get("reference_id"):
694
- st.markdown(f"**Reference#:** `{state['reference_id']}`")
695
- #if st.button("🔁 Submit New Request"):
696
- if st.button("🔂 Submit New Request"):
697
- for k in list(st.session_state.keys()):
698
- del st.session_state[k]
699
- st.rerun()
700
-
701
- # Show Agent Logs only after user has submitted their details
702
- if st.session_state.step in {"processing", "results", "done"}:
703
- #if "agent_state" in st.session_state and st.session_state.agent_state: OR #if st.session_state.agent_logs:
704
- st.markdown("---")
705
- #st.markdown("### 📜 Agent Logs")
706
- st.markdown("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/-h1QdYhvBfI-15wWmD6iT.png) Agent Logs")
707
- logs = st.session_state.agent_state["agent_logs"]
708
- for log in logs:
709
- st.markdown(f"- {log}")
710
- st.markdown("---")
711
-
712
- # ----- Matched Cases from Long‑Term Memory -----
713
- if st.session_state.ltm_match_history:
714
- #st.markdown("### 🧠 Matched Cases from Long‑Term Memory")
715
- st.markdown("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/LogBa8z0GRqlmfMKEGCCG.png) Matched Cases from Long‑Term Memory")
716
- for idx, df in enumerate(st.session_state.ltm_match_history, 1):
717
- st.markdown(f"#### Match {idx}")
718
- st.table(df)
719
- else:
720
  st.info("No similar cases found in long‑term memory.")
 
1
+ ## version v0.2
2
+ import streamlit as st
3
+ from pathlib import Path
4
+ import pandas as pd
5
+ import numpy as np
6
+ import faiss
7
+ import torch
8
+ import time
9
+ from datetime import datetime
10
+ from streamlit.components.v1 import html
11
+ from sentence_transformers import SentenceTransformer
12
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
13
+ from langgraph.graph import StateGraph, END
14
+ from langgraph.graph.state import CompiledStateGraph
15
+ from typing import Dict, Any, Optional, TypedDict
16
+
17
+
18
+ # ---- SETUP ----
19
+ BASE = Path(__file__).resolve().parent # directory of afhtp.py
20
+ doc_path = BASE / "afhtp.md"
21
+
22
+ # ---- PAGE CONFIG ----
23
+ st.set_page_config(page_title="AFTP Hardship Planner", layout="centered")
24
+ st.sidebar.title("🔍 Navigation")
25
+ app_mode = st.sidebar.radio("Go to", ["🏛️ AFHTP Planner", "📄 View Documentation"])
26
+
27
+ # ---- DOCUMENTATION VIEW ----
28
+ if app_mode == "📄 View Documentation":
29
+ if doc_path.is_file():
30
+ with open(doc_path, "r", encoding="utf-8") as f:
31
+ markdown_content = f.read()
32
+
33
+ # Ensure top anchor exists so "back to top" has somewhere to scroll
34
+ if '<div id="top">' not in markdown_content:
35
+ markdown_content = '<div id="top"></div>\n' + markdown_content
36
+
37
+ st.markdown(markdown_content, unsafe_allow_html=True)
38
+
39
+ # Inject floating back-to-top button (only for this view)
40
+ button_widget = """
41
+ <style>
42
+ #back-to-top {
43
+ position: fixed;
44
+ bottom: 24px;
45
+ right: 24px;
46
+ width: 52px;
47
+ height: 52px;
48
+ background: #1f77b4;
49
+ border-radius: 50%;
50
+ box-shadow: 0 6px 18px rgba(0,0,0,0.2);
51
+ display: flex;
52
+ align-items: center;
53
+ justify-content: center;
54
+ z-index: 9999;
55
+ cursor: pointer;
56
+ transition: opacity .25s ease, transform .2s ease;
57
+ opacity: 0;
58
+ font-family: system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;
59
+ }
60
+ #back-to-top:focus { outline: 3px solid #ffffff; }
61
+ #back-to-top:hover { transform: scale(1.05); }
62
+ #back-to-top svg { width: 24px; height: 24px; fill: white; }
63
+ @media (max-width: 768px) {
64
+ #back-to-top {
65
+ bottom: 16px;
66
+ right: 16px;
67
+ width: 44px;
68
+ height: 44px;
69
+ }
70
+ #back-to-top svg { width: 20px; height: 20px; }
71
+ }
72
+ </style>
73
+
74
+ <div id="back-to-top" aria-label="Back to top" role="button" tabindex="0" title="Back to top">
75
+ <svg viewBox="0 0 24 24" aria-hidden="true">
76
+ <path d="M4 12l1.41 1.41L11 7.83V20h2V7.83l5.59 5.58L20 12l-8-8-8 8z"/>
77
+ </svg>
78
+ </div>
79
+
80
+ <script>
81
+ (function() {
82
+ const btn = document.getElementById('back-to-top');
83
+
84
+ function toggleVisibility() {
85
+ if (window.scrollY > window.innerHeight / 3) {
86
+ btn.style.opacity = '1';
87
+ btn.setAttribute('aria-hidden','false');
88
+ } else {
89
+ btn.style.opacity = '0';
90
+ btn.setAttribute('aria-hidden','true');
91
+ }
92
+ }
93
+
94
+ function scrollToTop() {
95
+ window.scrollTo({ top: 0, behavior: 'smooth' });
96
+ }
97
+
98
+ btn.addEventListener('click', scrollToTop);
99
+ btn.addEventListener('keydown', function(e) {
100
+ if (e.key === 'Enter' || e.key === ' ') {
101
+ e.preventDefault();
102
+ scrollToTop();
103
+ }
104
+ });
105
+
106
+ document.addEventListener('scroll', toggleVisibility);
107
+ toggleVisibility();
108
+ })();
109
+ </script>
110
+ """
111
+
112
+ # Use components.html so the JS/CSS executes
113
+ html(button_widget, height=0)
114
+ else:
115
+ #st.error("📄 Documentation file 'afhtp.md' not found.")
116
+ f"📄 Documentation file 'afhtp.md' not found at: {doc_path}\n"
117
+ st.stop()
118
+
119
+
120
+ #st.title("🏛️ AFTP Hardship Treatment Planner")
121
+ st.subheader("![image/png](https://cdn-uploads.huggingface.co/production/uploads/688abc51f5077dea074b2f8d/dSu3n5I9OyaIQtNWP6kt5.png) Autonomous Financial Hardship Treatment Planner")
122
+
123
+ # ---- LLM LOAD ----
124
+ @st.cache_resource
125
+ def load_llm():
126
+ model_id = "google/flan-t5-small"
127
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
128
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
129
+ return model, tokenizer
130
+
131
+ llm_model, llm_tokenizer = load_llm()
132
+ llm_model.eval()
133
+
134
+ # ---- VECTOR STORE ----
135
+ encoder = SentenceTransformer("all-MiniLM-L6-v2")
136
+ index = faiss.IndexFlatL2(384)
137
+ vector_store = {}
138
+
139
+ def build_embedding(app: dict) -> str:
140
+ return f"{app['hardship_reason']} income:{app['income']} expenses:{app['expenses']}"
141
+
142
+ def store_context(customer_id: str, embedding_text: str, context: dict):
143
+ vector = encoder.encode([embedding_text])[0]
144
+ index.add(np.array([vector]))
145
+ vector_store[customer_id] = {"vector": vector, "context": context}
146
+
147
+ ## Sample Hardship treatment plans Prepopulation
148
+ def prepopulate_sample_cases():
149
+ """
150
+ Prepopulate vector store with realistic historical cases for similarity matching.
151
+ """
152
+ sample_cases = [
153
+ {"customer_id": "C100", "app": {"hardship_reason": "Job Loss", "income": 1500,"expenses": 2200}, "context": {"plan": "3-month deferral",
154
+ "status": "completed"}},
155
+ {"customer_id": "C101", "app": {"hardship_reason": "Natural Disaster", "income": 1800, "expenses": 2100}, "context": {"plan": "interest reduction",
156
+ "status": "completed"}},
157
+ {"customer_id": "C102", "app": {"hardship_reason": "Medical", "income": 2000, "expenses": 2500}, "context": {"plan": "partial payment suspension",
158
+ "status": "completed"}},
159
+ {"customer_id": "C103", "app": {"hardship_reason": "Job Loss", "income": 1400, "expenses": 2000}, "context": {"plan": "3-month deferral",
160
+ "status": "completed"}},
161
+ {"customer_id": "C104", "app": {"hardship_reason": "Natural Disaster", "income": 2500, "expenses": 2600}, "context": {"plan": "payment extension",
162
+ "status": "completed"}}
163
+ ]
164
+
165
+ for case in sample_cases:
166
+ embedding_text = build_embedding(case["app"])
167
+ store_context(case["customer_id"], embedding_text, case["context"])
168
+
169
+ if len(vector_store) == 0: #avoid repopulating on every rerun,
170
+ prepopulate_sample_cases()
171
+
172
+
173
+ # ---- Hardcoded Plans ----
174
+ hardship_plans = {
175
+ "3-month deferral": {"description": "Suspend payments for 3 months.", "risk_score": 2},
176
+ "partial payment suspension": {"description": "Pay only 50% for 3 months.", "risk_score": 3},
177
+ "interest reduction": {"description": "Reduce interest by 25% for 6 months.", "risk_score": 1},
178
+ "payment extension": {"description": "Extend term by 12 months.", "risk_score": 4},
179
+ "restructure repayment": {"description": "Restructure repayment terms based on income profile.", "risk_score": 3},
180
+ "defer interest only": {"description": "Pay only interest for 3 months.", "risk_score": 2},
181
+ "grace period": {"description": "Grace period of 1 month with no payment.", "risk_score": 1}
182
+ }
183
+
184
+ # ---- Sample Case Workers ----
185
+ case_worker_df = pd.DataFrame([
186
+ {"name": "Peter Swift", "plan": "3-month deferral", "experience_years": 5, "on_leave": False},
187
+ {"name": "Anthony Mackay", "plan": "interest reduction", "experience_years": 7, "on_leave": False},
188
+ {"name": "Sara Keeves", "plan": "partial payment suspension", "experience_years": 4, "on_leave": True},
189
+ {"name": "Lara Brent", "plan": "partial payment suspension", "experience_years": 5, "on_leave": False},
190
+ {"name": "David Ray", "plan": "payment extension", "experience_years": 6, "on_leave": False},
191
+ ])
192
+
193
+ def assign_case_worker(plan: str):
194
+ available = case_worker_df[(case_worker_df["plan"] == plan) & (~case_worker_df["on_leave"])]
195
+ if not available.empty:
196
+ return available.sample(1).iloc[0]
197
+ return None
198
+
199
+ def assign_human_caseworker():
200
+ available = case_worker_df[(case_worker_df["experience_years"] >= 5) & (~case_worker_df["on_leave"])]
201
+ if not available.empty:
202
+ return available.sample(1).iloc[0]
203
+ return None
204
+
205
+ # ---- AgentState TypedDict ----
206
+ class AgentState(TypedDict):
207
+ application: Optional[Dict[str, Any]]
208
+ selected_plan: Optional[str]
209
+ escalated: bool
210
+ handled: bool
211
+ matched_case_df: Optional[pd.DataFrame]
212
+ ltm_match_history: list
213
+ feedback: Optional[str]
214
+ submitted_feedbacks: set
215
+ reference_id: Optional[str]
216
+ agent_logs: list
217
+ current_node: str
218
+ eligible_plans: Optional[list]
219
+ previous_plans: list
220
+
221
+ # ---- Eligibility and Matching Functions ----
222
+ def check_eligibility(app: Dict) -> list:
223
+ # Debug inside eligibility
224
+ st.session_state.agent_state["agent_logs"].append(f"[Info] check_eligibility called with hardship_reason={app['hardship_reason']}, income={app['income']}, expenses={app['expenses']}")
225
+ if app["hardship_reason"] == "Job Loss" and app["income"] < app["expenses"]:
226
+ return ["3-month deferral", "partial payment suspension"]
227
+ return ["payment extension", "interest reduction"]
228
+
229
+ def check_proactive_escalation(app: Dict) -> bool:
230
+ return app["history"]["late_payments"] > 3 or app.get("flagged_abuse", False)
231
+
232
+ def match_from_ltm(app: Dict[str, Any]) -> Optional[pd.DataFrame]:
233
+ if len(vector_store) == 0:
234
+ return None
235
+
236
+ query_vector = encoder.encode([build_embedding(app)])[0]
237
+ similarity_threshold = 10.0
238
+ D, I = index.search(np.array([query_vector]), k=1)
239
+ distance = D[0][0]
240
+
241
+ if distance <= similarity_threshold:
242
+ match_id = list(vector_store.keys())[I[0][0]]
243
+ matched_context = vector_store[match_id]["context"]
244
+ matched_df = pd.DataFrame([{
245
+ "Customer ID": match_id,
246
+ "Plan": matched_context["plan"],
247
+ "Status": matched_context.get("status", "N/A")
248
+ }])
249
+ return matched_df
250
+ else:
251
+ st.session_state.agent_state["agent_logs"].append(f"[Debug] No similar case found. Distance: {distance:.2f}")
252
+ return None
253
+
254
+ # ---- Node Functions ----
255
+ # Hardcoded, safe validate() , this temporary fixed version that hard-forces the downstream steps unless escalation is needed:
256
+ def validate(state: AgentState) -> AgentState:
257
+ logs = state["agent_logs"]
258
+ logs.append("[Node] Entered validate")
259
+ app = state["application"]
260
+ state["current_node"] = "validate"
261
+
262
+ # Only escalate if absolutely needed
263
+ if check_proactive_escalation(app):
264
+ logs.append("[Info] Escalation triggered in validate()")
265
+ state["escalated"] = True
266
+ worker = assign_human_caseworker()
267
+ if worker is not None:
268
+ logs.append(f"[Escalation] Assigned to case worker: {worker['name']}")
269
+ else:
270
+ logs.append("[Escalation] No available senior case workers. Case queued.")
271
+ state["handled"] = True
272
+ else:
273
+ logs.append("[Info] No escalation triggered in validate()")
274
+ state["escalated"] = False
275
+ state["handled"] = False # FORCE this
276
+ logs.append(f"[Info] Post validate() state: escalated={state['escalated']}, handled={state['handled']}") # debug
277
+ return state
278
+
279
+ def reason_and_rank(state: AgentState) -> AgentState:
280
+ logs = state["agent_logs"]
281
+ logs.append("[Node] Entered reason_and_rank")
282
+
283
+ app = state["application"]
284
+ state["current_node"] = "reason_and_rank"
285
+
286
+ # 1. Check eligibility
287
+ eligible = check_eligibility(app)
288
+ state["eligible_plans"] = eligible
289
+
290
+ if eligible:
291
+ top_plan = sorted(eligible, key=lambda p: hardship_plans[p]["risk_score"])[0]
292
+ desc = hardship_plans[top_plan]["description"]
293
+ logs.append(f"[Node: reason_and_rank] Eligible Plan: {top_plan} → {desc}")
294
+ else:
295
+ logs.append("[Node: reason_and_rank] No eligible plans found.")
296
+
297
+ # 2. Try to match from Long-Term Memory (LTM)
298
+ matched_df = match_from_ltm(app)
299
+ if matched_df is not None:
300
+ matched_plan = matched_df.iloc[0]["Plan"]
301
+
302
+ # Check if user already saw this LTM plan
303
+ if matched_plan not in state.get("previous_plans", []):
304
+ logs.append(f"[LTM Match] Found matching plan from long-term memory: {matched_plan}")
305
+ state["selected_plan"] = matched_plan
306
+ state.setdefault("previous_plans", []).append(matched_plan)
307
+ state["matched_case_df"] = matched_df
308
+ state.setdefault("ltm_match_history", []).append(matched_df.copy()) # append the matched_df
309
+ logs.append(f"[Plan Selection] Selected Plan from LTM: {matched_plan}")
310
+ return state
311
+ else:
312
+ logs.append(f"[LTM Match] Skipped LTM plan {matched_plan} (already proposed)")
313
+
314
+ # 3. No LTM match – proceed with ranking eligible hardcoded plans
315
+ if not eligible:
316
+ state["escalated"] = True
317
+ state["handled"] = True
318
+ logs.append("[Warning] No eligible plans found. Escalating to human agent.")
319
+ return state
320
+
321
+ # 4. Rank and pick plan from eligible ones
322
+ ranked = sorted(eligible, key=lambda p: hardship_plans[p]["risk_score"])
323
+ previous = state.get("previous_plans", [])
324
+ ranked_filtered = [p for p in ranked if p not in previous]
325
+
326
+ if not ranked_filtered:
327
+ logs.append("[Plan Selection] No new plans left after filtering. Escalating.")
328
+ state["escalated"] = True
329
+ state["handled"] = True
330
+ return state
331
+
332
+ selected_plan = ranked_filtered[0]
333
+ state["selected_plan"] = selected_plan
334
+ state.setdefault("previous_plans", []).append(selected_plan)
335
+
336
+ logs.append(f"[Plan Selection] Selected new plan: {selected_plan}")
337
+
338
+ worker = assign_case_worker(selected_plan)
339
+ if worker is not None:
340
+ logs.append(f"[CRM] Assigned to {worker['name']} for plan: {selected_plan}")
341
+ else:
342
+ logs.append(f"[CRM] No available case worker for plan: {selected_plan}")
343
+
344
+ return state
345
+
346
+
347
+ def take_action(state: AgentState) -> AgentState:
348
+ logs = state["agent_logs"]
349
+ logs.append("[Node] Entered take_action()")
350
+ app = state["application"]
351
+ plan = state["selected_plan"]
352
+ state["current_node"] = "take_action"
353
+
354
+ # Defensive check in case already assigned earlier
355
+ if "crm_logged" not in state:
356
+ worker = assign_case_worker(plan)
357
+ if worker is not None:
358
+ logs.append(f"[CRM] Logged case for {app['name']} - Plan: {plan} → Assigned to {worker['name']}")
359
+ else:
360
+ logs.append(f"[CRM] No available case worker for plan: {plan}")
361
+ state["crm_logged"] = True # prevent future re-logging
362
+
363
+ # Store the decision in long-term memory (LTM)
364
+ store_context(app["customer_id"], build_embedding(app), {"plan": plan, "status": "active"})
365
+
366
+ state["handled"] = True
367
+ return state
368
+
369
+
370
+ # ---- Decide Next Node ----
371
+ def decide_next_node(state: AgentState) -> str:
372
+ logs = state["agent_logs"]
373
+ current_node = state["current_node"]
374
+ app = state.get("application", {})
375
+ history = app.get("history", {})
376
+ logs.append(f"[Router] At node: {current_node}") # debug code
377
+ logs.append(f"[Info] decide_next_node() called at node: {current_node}") # debug code
378
+
379
+ if state["handled"] or state["escalated"]:
380
+ logs.append("[Router] Already handled or escalated - routing to END") # debug code
381
+ return END
382
+
383
+ # Define valid next nodes
384
+ valid_next_nodes = {
385
+ "validate": ["reason_and_rank", END],
386
+ "reason_and_rank": ["take_action", END],
387
+ "take_action": [END]
388
+ }.get(current_node, [END])
389
+
390
+ # Few-shot prompt
391
+ few_shot = """
392
+ Current Node: validate, flagged_abuse=False, selected_plan=None, handled=False → reason_and_rank
393
+ Current Node: reason_and_rank, selected_plan=interest reduction, handled=False → take_action
394
+ Current Node: take_action, handled=True → END
395
+ Current Node: validate, escalated=True, handled=True → END
396
+ """
397
+
398
+ prompt = f"""
399
+ You are an AI agent orchestrating a financial hardship planner.
400
+ Given the current node and customer data, choose the next step in the process.
401
+ {few_shot}
402
+ Customer Info:
403
+ - Name: {app.get('name', 'Unknown')}
404
+ - Hardship Reason: {app.get('hardship_reason', 'Unknown')}
405
+ - Income: {app.get('income', 'N/A')}
406
+ - Expenses: {app.get('expenses', 'N/A')}
407
+ - Late Payments: {history.get('late_payments', 0)}
408
+ - Flagged Abuse: {app.get('flagged_abuse', False)}
409
+ - Escalated: {state.get('escalated', False)}
410
+ - Handled: {state.get('handled', False)}
411
+ - Selected Plan: {state.get('selected_plan')}
412
+ - Eligible Plans: {state.get('eligible_plans', [])}
413
+ - Current Node: {current_node}
414
+ Next: {', '.join(valid_next_nodes)}
415
+ """
416
+
417
+ with torch.no_grad():
418
+ start = time.time()
419
+ input_ids = llm_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512).input_ids
420
+ outputs = llm_model.generate(input_ids=input_ids, max_new_tokens=10, do_sample=False)
421
+ end = time.time()
422
+ response = llm_tokenizer.decode(outputs[0], skip_special_tokens=True).strip().lower()
423
+ response = response.split()[0] # Only take first word to normalize
424
+ logs.append(f"[Router] LLM output: {response}") # debug code
425
+ #st.markdown(f"⏲ **LLM inference time:** `{end - start:.2f} seconds`")
426
+ st.markdown(f"⏳ **LLM inference time:** `{end - start:.2f} seconds`")
427
+
428
+ if response not in valid_next_nodes:
429
+ logs.append(f"[Router Warning] Invalid LLM output '{response}', defaulting to {valid_next_nodes[0]}") # debug code
430
+ return valid_next_nodes[0]
431
+
432
+ if response == "end" or state["escalated"]:
433
+ logs.append("[Router] Routing to END due to LLM output or escalation.")
434
+ return END
435
+
436
+ if state["selected_plan"] is None and response == "take_action":
437
+ logs.append("[Router Warning] LLM tried to skip reasoning. Forcing reason_and_rank.") # debug code
438
+ return "reason_and_rank"
439
+
440
+ logs.append(f"[Router] Moving from {current_node} to {response}")
441
+ return response
442
+
443
+ # ---- LangGraph Workflow Setup ----
444
+ workflow = StateGraph(AgentState)
445
+ workflow.add_node("validate", validate)
446
+ workflow.add_node("reason_and_rank", reason_and_rank)
447
+ workflow.add_node("take_action", take_action)
448
+
449
+ workflow.add_conditional_edges(
450
+ "validate",
451
+ decide_next_node,
452
+ {
453
+ "reason_and_rank": "reason_and_rank",
454
+ END: END
455
+ }
456
+ )
457
+ workflow.add_conditional_edges(
458
+ "reason_and_rank",
459
+ decide_next_node,
460
+ {
461
+ "take_action": "take_action",
462
+ END: END
463
+ }
464
+ )
465
+ workflow.add_conditional_edges(
466
+ "take_action",
467
+ decide_next_node,
468
+ {
469
+ END: END
470
+ }
471
+ )
472
+ workflow.set_entry_point("validate")
473
+ graph: CompiledStateGraph = workflow.compile()
474
+
475
+ # ---- Initialize session state ----
476
+ def init_session():
477
+ if "step" not in st.session_state:
478
+ st.session_state.step = "form"
479
+ if "application" not in st.session_state:
480
+ st.session_state.application = None
481
+ if "plan_accepted" not in st.session_state:
482
+ st.session_state.plan_accepted = False
483
+ if "escalated" not in st.session_state:
484
+ st.session_state.escalated = False
485
+ if "handled" not in st.session_state:
486
+ st.session_state.handled = False
487
+ if "matched_case_df" not in st.session_state:
488
+ st.session_state.matched_case_df = None
489
+ if "feedback" not in st.session_state:
490
+ st.session_state.feedback = None
491
+ if "submitted_feedbacks" not in st.session_state:
492
+ st.session_state.submitted_feedbacks = set()
493
+ if "reference_id" not in st.session_state:
494
+ st.session_state.reference_id = None
495
+ if "agent_logs" not in st.session_state:
496
+ st.session_state.agent_logs = []
497
+ if "previous_plans" not in st.session_state:
498
+ st.session_state.previous_plans = []
499
+ if "agent_state" not in st.session_state or st.session_state.agent_state is None:
500
+ st.session_state.agent_state = AgentState(
501
+ application=None,
502
+ selected_plan=None,
503
+ escalated=False,
504
+ handled=False,
505
+ matched_case_df=None,
506
+ ltm_match_history=[],
507
+ feedback=None,
508
+ submitted_feedbacks=set(),
509
+ reference_id=None,
510
+ agent_logs=[],
511
+ current_node="validate",
512
+ eligible_plans=None,
513
+ previous_plans=[]
514
+ )
515
+
516
+ init_session()
517
+
518
+ # ---- UI and workflow execution ----
519
+ if st.session_state.step == "form":
520
+ with st.form("user_input"):
521
+ #st.subheader("📝 Enter Your Details")
522
+ st.subheader("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/6Om0nXTbrf8Mew4zJ7Gsh.png) Enter Your Details")
523
+ name = st.text_input("First Name")
524
+ customer_id = st.text_input("Customer ID")
525
+ account_type = st.selectbox("Account Type", ["mortgage", "credit card", "personal loan"])
526
+ hardship_reason = st.selectbox("Reason for Hardship", ["Job Loss", "Medical", "Natural Disaster"])
527
+ income = st.number_input("Monthly Income", min_value=0.0)
528
+ expenses = st.number_input("Monthly Expenses", min_value=0.0)
529
+ late_payments = st.number_input("Late Payments (last 12 months)", min_value=0, step=1)
530
+ flagged_abuse = st.radio("Previously defaulted or rejected?", ["No", "Yes"]) == "Yes"
531
+ submitted = st.form_submit_button("Submit")
532
+
533
+ if submitted:
534
+ if not name.strip():
535
+ st.warning("⚠️ Please enter your name.")
536
+ elif not customer_id.strip():
537
+ st.warning("⚠️ Please enter your customer ID.")
538
+ elif income == 0.0:
539
+ st.warning("⚠️ Please enter your income.")
540
+ elif expenses == 0.0:
541
+ st.warning("⚠️ Please enter your expenses.")
542
+ else:
543
+ st.session_state.application = {
544
+ "name": name.strip(),
545
+ "account_type": account_type,
546
+ "hardship_reason": hardship_reason,
547
+ "income": income,
548
+ "expenses": expenses,
549
+ "history": {"late_payments": late_payments},
550
+ "flagged_abuse": flagged_abuse,
551
+ "customer_id": customer_id,
552
+ }
553
+ st.session_state.agent_state["application"] = st.session_state.application
554
+ st.session_state.agent_state["current_node"] = "validate"
555
+ st.session_state.agent_state["selected_plan"] = None
556
+ st.session_state.agent_state["escalated"] = False
557
+ st.session_state.agent_state["handled"] = False
558
+ st.session_state.agent_state["matched_case_df"] = None
559
+ st.session_state.agent_state["feedback"] = None
560
+ st.session_state.agent_state["eligible_plans"] = None
561
+ st.session_state.agent_state["submitted_feedbacks"] = set()
562
+ st.session_state.agent_state["agent_logs"] = []
563
+ st.session_state.step = "processing"
564
+ st.rerun()
565
+
566
+ elif st.session_state.step == "processing":
567
+ #st.info("📡 Processing your request...")
568
+ st.info("![image/gif](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/8tQqf9gWdbl9Sb3bO6O6C.gif) Processing your request...")
569
+ state = st.session_state.agent_state
570
+ logs = state["agent_logs"] # This line is required
571
+ logs.append("[Node] Processing plan recommendation...")
572
+
573
+ # Run the graph streaming to execute the workflow nodes including reason_and_rank and take_action
574
+ for updated_state in graph.stream(state):
575
+ node_name, inner_state = list(updated_state.items())[0]
576
+
577
+ # Update session state with the new state
578
+ st.session_state.agent_state = inner_state
579
+ st.session_state.agent_logs = inner_state.get("agent_logs", [])
580
+ st.session_state.ltm_match_history = inner_state.get("ltm_match_history", [])
581
+ st.session_state.escalated = inner_state.get("escalated", False)
582
+ st.session_state.handled = inner_state.get("handled", False)
583
+ st.session_state.matched_case_df = inner_state.get("matched_case_df")
584
+ st.session_state.reference_id = inner_state.get("reference_id")
585
+
586
+ state = inner_state # Feed updated state back to next iteration
587
+
588
+ #inner_state["agent_logs"].append(f"[Debug] Node executed: {node_name}") # debug code
589
+ inner_state["agent_logs"].append(f"[Info] node executed]: {node_name}")
590
+
591
+ if node_name == END:
592
+ break
593
+
594
+ #st.write("✅ Final state from LangGraph:") # debug code
595
+ #st.json(state) # debug code
596
+
597
+ # Move to results after processing the entire graph
598
+ st.session_state.step = "results"
599
+ st.rerun()
600
+
601
+
602
+ elif st.session_state.step == "results":
603
+ state = st.session_state.agent_state
604
+
605
+ if st.session_state.escalated:
606
+ st.warning("⚠️ Your case has been assigned to a agent for review.")
607
+ ref = f"{state['application']['customer_id'].upper()}-{datetime.now().strftime('%d%m%y%H%M%S')}"
608
+ state["reference_id"] = ref
609
+ st.markdown(f"**Reference#:** `{ref}`")
610
+ if st.button("⮎ Continue"):
611
+ for k in list(st.session_state.keys()):
612
+ del st.session_state[k]
613
+ st.rerun()
614
+ st.session_state.step = "done"
615
+ st.stop()
616
+
617
+ elif state.get("selected_plan"):
618
+ plan = state["selected_plan"]
619
+ st.success(f"✅ Proposed Plan: **{plan}**")
620
+ st.markdown(f"**{hardship_plans[plan]['description']}**")
621
+
622
+ #Suggestion (Optional)
623
+ #ranked = sorted(state.get("eligible_plans", []), key=lambda p: hardship_plans[p]["risk_score"])
624
+ #if plan in ranked and len(ranked) > 1:
625
+ # alternatives = [p for p in ranked if p != plan]
626
+ # second_best = alternatives[0]
627
+ # st.info(f"💡 You might also consider: **{second_best}** — {hardship_plans[second_best]['description']}")
628
+
629
+ submitted = state["submitted_feedbacks"]
630
+ remaining = {"Accept", "I can only afford half", "Suggest alternative"} - submitted
631
+
632
+ if "Accept" in submitted:
633
+ st.success("Thank you for your response.")
634
+ st.success(f"You have accepted the proposed plan: **{plan}**")
635
+ ref = state.get("reference_id")
636
+ if ref:
637
+ st.markdown(f"**Reference#:** `{ref}`")
638
+ if st.button("🔁 Submit New Request"):
639
+ for k in list(st.session_state.keys()):
640
+ del st.session_state[k]
641
+ st.rerun()
642
+ st.session_state.step = "done"
643
+ st.stop()
644
+
645
+ # Show feedback options only if not already accepted
646
+ options = [opt for opt in ["Accept", "I can only afford half", "Suggest alternative"] if opt in remaining] #options = list(remaining)
647
+ feedback = st.radio("Feedback (choose one):", options, key="feedback_choice")
648
+
649
+ if st.button("Submit Feedback"):
650
+ submitted.add(feedback)
651
+ state["submitted_feedbacks"] = submitted
652
+ state["agent_logs"].append(f"[Feedback] User selected: {feedback}")
653
+
654
+ if feedback == "Accept":
655
+ state["handled"] = True
656
+ ref = f"{state['application']['customer_id'].upper()}-{datetime.now().strftime('%d%m%y%H%M%S')}"
657
+ state["reference_id"] = ref
658
+ st.session_state.step = "done"
659
+ st.rerun()
660
+
661
+
662
+ elif "half" in feedback.lower():
663
+ state["agent_logs"].append("[Feedback Action] User selected 'half'. Reducing income and rerunning reason_and_rank")
664
+ state["application"]["income"] = state["application"]["income"] / 2 # Adjust income
665
+ state["feedback"] = "half"
666
+ state["handled"] = False
667
+ state.pop("selected_plan", None) # Force recomputation
668
+ state.pop("matched_case_df", None) #clear matched case display (but keep history)
669
+ state["current_node"] = "reason_and_rank"
670
+ st.session_state.step = "processing"
671
+ st.rerun()
672
+
673
+ elif feedback == "Suggest alternative":
674
+ state["feedback"] = "wants_alternative"
675
+ state["handled"] = False
676
+ state["current_node"] = "reason_and_rank"
677
+ state["agent_logs"].append("[Feedback Action] User requested alternative. Clearing selected_plan and rerunning reason_and_rank")
678
+ state.pop("selected_plan", None) #clear old plan so it doesn't get reused
679
+ state.pop("matched_case_df", None) # clear matched case display (but keep history)
680
+ st.session_state.step = "processing"
681
+ st.rerun()
682
+ else:
683
+ st.warning("⚠️ No plan could be proposed.")
684
+ st.session_state.step = "done"
685
+ st.rerun()
686
+
687
+ elif st.session_state.step == "done":
688
+ state = st.session_state.agent_state
689
+ #st.success("🎉 Thank you for your response.")
690
+ st.success("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/2KNwWbE-GjSYTOpfcA0N3.png) Thank you for your response.")
691
+ if state.get("selected_plan"):
692
+ st.markdown(f"**You have accepted the proposed plan:** `{state['selected_plan']}`")
693
+ if state.get("reference_id"):
694
+ st.markdown(f"**Reference#:** `{state['reference_id']}`")
695
+ #if st.button("🔁 Submit New Request"):
696
+ if st.button("🔂 Submit New Request"):
697
+ for k in list(st.session_state.keys()):
698
+ del st.session_state[k]
699
+ st.rerun()
700
+
701
+ # Show Agent Logs only after user has submitted their details
702
+ if st.session_state.step in {"processing", "results", "done"}:
703
+ #if "agent_state" in st.session_state and st.session_state.agent_state: OR #if st.session_state.agent_logs:
704
+ st.markdown("---")
705
+ #st.markdown("### 📜 Agent Logs")
706
+ st.markdown("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/-h1QdYhvBfI-15wWmD6iT.png) Agent Logs")
707
+ logs = st.session_state.agent_state["agent_logs"]
708
+ for log in logs:
709
+ st.markdown(f"- {log}")
710
+ st.markdown("---")
711
+
712
+ # ----- Matched Cases from Long‑Term Memory -----
713
+ if st.session_state.ltm_match_history:
714
+ #st.markdown("### 🧠 Matched Cases from Long‑Term Memory")
715
+ st.markdown("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/LogBa8z0GRqlmfMKEGCCG.png) Matched Cases from Long‑Term Memory")
716
+ for idx, df in enumerate(st.session_state.ltm_match_history, 1):
717
+ st.markdown(f"#### Match {idx}")
718
+ st.table(df)
719
+ else:
720
  st.info("No similar cases found in long‑term memory.")