docker_changes

#1
by npkits - opened
Files changed (4) hide show
  1. Dockerfile +1 -2
  2. src/afhtp.md +0 -107
  3. src/afhtp.py +615 -635
  4. src/afhtp_v0.0.py +0 -616
Dockerfile CHANGED
@@ -30,5 +30,4 @@ EXPOSE 8501
30
 
31
  HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
32
 
33
- #ENTRYPOINT ["streamlit", "run", "src/streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"]
34
- ENTRYPOINT ["streamlit", "run", "src/afhtp.py", "--server.port=8501", "--server.address=0.0.0.0"]
 
30
 
31
  HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
32
 
33
+ ENTRYPOINT ["streamlit", "run", "src/streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"]
 
src/afhtp.md DELETED
@@ -1,107 +0,0 @@
1
- #### <img src="https://npkum.github.io/agenticai/images/robotic_1.gif" width="35" height="35"/> Agentic Generative AI for Autonomous Financial Hardship Treatment Planner (AFTP)
2
- The AFHTP demonstrates an Agentic AI system built using LangGraph and an LLM (google/flan-t5-smalle / fallback to flan-t5-base) for managing customer hardship requests in a financial setting. It showcases Planning, Reasoning, Tool Use, Reactivity, and Proactivity in a multi-step autonomous process. It represents a modular blueprint for autonomous decision-making systems in financial services.
3
-
4
- The application autonomously analyzes financial hardship applications and generates optimized treatment plans.
5
-
6
- ---
7
-
8
- ##### 🧩 Agentic AI Capabilities in AFHTP
9
-
10
- | Agentic Capability | Role in AFHTP | Function Name |
11
- |------------------------|--------------------------------------|-------------------|
12
- | Planning | Determines the next appropriate action based on state and goals | `decide_next_node` |
13
- | Reasoning | Selects plans based on eligibility and risk ranking | `reason_and_rank` |
14
- | Tool Use | Assigns caseworkers and stores in vector memory (CRM, FAISS) | `assign_case_worker`, `store_context`, `match_from_ltm` |
15
- | Reactivity | Responds to user feedback (e.g. request for alternative or half payment) | Feedback logic in `results` step |
16
- | Proactivity | Escalates risky cases (late payments, abuse) before plan selection | `check_proactive_escalation` |
17
-
18
- ---
19
-
20
- ##### 📚 Overview: How LLMs Enable Agentic Generative AI in AFHTP
21
-
22
- | Agentic Capability | LLM Role | Code Reference| Explanation |
23
- |------------------------|--------------|-------------------------------------|-----------------|
24
- | Planning | Predicts next node in the workflow | `decide_next_node` | Uses few-shot prompting and current state to guide LangGraph transition |
25
- | Reasoning | Encodes context for plan matching and reasoning | `reason_and_rank`, `match_from_ltm` | LLM helps support ranking and fallback when plan not found |
26
- | Reactivity | Adjusts plan logic based on user feedback | `results` step (streamlit) | Dynamically adjusts state using LLM-recommended flow |
27
- | Tool Use | Indirect (e.g. prompt includes status and CRM metadata) | `decide_next_node` | LLM understands CRM assignment and escalation history through prompt |
28
- | Memory | LLM uses historical memory info in prompts | `decide_next_node` | LLM leverages LTM matching info for decision making |
29
-
30
- ---
31
-
32
- ##### 🔍 How LLM is Used in AFHTP
33
-
34
- | Function Name | Uses LLM (Y/N) | Rule-based / Generative / Hybrid | Input Source | Output Use |
35
- |------------------|-------------------|--------------------------------------|------------------|----------------|
36
- | `decide_next_node` | Y | Generative | `agent_state`, user profile, previous plans, escalation flags | Determines LangGraph transition |
37
- | `reason_and_rank` | N | Rule-based + Memory Match | `application` dict | Selects or escalates hardship plan |
38
- | `take_action` | N | Rule-based | `selected_plan`, `application` | Logs decision, stores in vector memory |
39
- | `match_from_ltm` | N | Hybrid (Vector + Heuristic) | `application` + `encoder` → query vector | Returns similar plan from LTM |
40
- | `validate` | N | Rule-based | `application`, `history` | Triggers escalation if abuse or too many late payments |
41
- | UI Feedback Handlers | Y (indirect via re-routing) | Reactive / Generative | User input (feedback: "half", "suggest alternative") | Updates state and reprocesses planning |
42
-
43
- ---
44
-
45
- ##### 🔄 Deterministic and LLM-driven LangGraph Nodes
46
-
47
- | Node | Activation Method | Description |
48
- |----------|------------------------|-----------------|
49
- | `validate` | Deterministic | Checks escalation needs before continuing |
50
- | `reason_and_rank` | Deterministic | Performs eligibility checks, ranking, and LTM matching |
51
- | `take_action` | Deterministic | Logs plan, stores memory, assigns caseworker |
52
- | `decide_next_node` | LLM-planned | Routes to next step using LLM-prompted logic |
53
- | `END` | Reactive Loop / Deterministic | Terminates graph if escalation handled or plan accepted |
54
-
55
- ---
56
-
57
- ##### 🧠 How Short-Term Memory (STM) and Long-Term Memory (LTM) are Used in AFHTP
58
-
59
- | Short-Term Memory (STM) | Implementation | Used Where | Purpose |
60
- |-----------------------------|---------------------|----------------|-------------|
61
- | Session State (`agent_state`) | `st.session_state.agent_state` | Entire graph run and UI flow | Maintains runtime plan, feedback, current node |
62
- | LTM via Vector DB | FAISS + `vector_store` dict | `match_from_ltm`, `take_action` | Recommends plans based on previous similar customer cases |
63
- | History Logs | `agent_logs` list | Throughout all nodes | Transparency and debugging for every decision |
64
- | Feedback Memory | `submitted_feedbacks` set | `results` step | Prevents repeated options shown to user |
65
-
66
- ---
67
-
68
- ##### 🧭 Agentic Features in AFHTP
69
-
70
- | Feature | Agentic Trait | Mechanism |
71
- |-------------|-------------------|---------------|
72
- | Workflow Routing | Planning | LLM-decides next node (`decide_next_node`) |
73
- | Plan Selection | Reasoning | Eligibility + Risk Score sorting (`reason_and_rank`) |
74
- | Vector Memory | Tool use | FAISS vector search (`match_from_ltm`) |
75
- | CRM + Scheduler | Tool use | Assigning workers from DataFrame (`assign_case_worker`) |
76
- | User Feedback Integration | Reactivity | Adjusts state based on user selection (`results`) |
77
- | Escalation Checks | Proactivity | Triggers agent escalation if risky profile (`check_proactive_escalation`) |
78
-
79
- ---
80
-
81
- ##### 🔍 Explanation of `decide_next_node(state: AgentState)`
82
-
83
- This function acts as a **planning and routing brain** for the Agentic workflow. It:
84
-
85
- 1. Reads the **current node** and application data from `AgentState`.
86
- 2. Defines valid next nodes based on the current position in the graph.
87
- 3. Constructs a **few-shot prompt** containing scenarios from prior decisions.
88
- 4. Uses the **LLM (Flan-T5)** to predict the next best node based on:
89
- - Hardship reason
90
- - Escalation status
91
- - Selected or eligible plans
92
- - User history (e.g. late payments, flagged abuse)
93
- 5. Routes the workflow accordingly or overrides LLM suggestion if invalid.
94
-
95
- ---
96
-
97
- ##### 📌 Key Design Takeaways
98
-
99
- - Agentic AI isn’t just about calling LLMs — it combines deterministic control, reactive logic, planning, and human fallback.
100
- - **LangGraph integration** brings structure to autonomous reasoning, combining determinism with LLM-driven planning.
101
- - **LLM is not used for content generation**, but for **intent routing and decision sequencing**.
102
- - Memory is **multi-layered**: STM (session) and LTM (vector database).
103
- - Escalation and fallback paths ensure safety in plan recommendation.
104
- - Minimal manual intervention is needed—workflow adapts autonomously.
105
- - Reusable, explainable agent logs are built into every step for transparency.
106
-
107
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/afhtp.py CHANGED
@@ -1,636 +1,616 @@
1
- ## version v0.1
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 sentence_transformers import SentenceTransformer
11
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
12
- from langgraph.graph import StateGraph, END
13
- from langgraph.graph.state import CompiledStateGraph
14
- from typing import Dict, Any, Optional, TypedDict
15
-
16
- # ---- SETUP ----
17
- BASE = Path(__file__).resolve().parent # directory of afhtp.py
18
- doc_path = BASE / "afhtp.md"
19
-
20
- # ---- PAGE CONFIG ----
21
- st.set_page_config(page_title="AFTP Hardship Planner", layout="centered")
22
- st.sidebar.title("🔍 Navigation")
23
- app_mode = st.sidebar.radio("Go to", ["🏛️ AFHTP Planner", "📄 View Documentation"])
24
-
25
- # ---- DOCUMENTATION VIEW ----
26
- if app_mode == "📄 View Documentation":
27
- if doc_path.is_file():
28
- with open(doc_path, "r", encoding="utf-8") as f:
29
- markdown_content = f.read()
30
- st.markdown(markdown_content, unsafe_allow_html=True)
31
- else:
32
- st.error("📄 Documentation file 'afhtp.md' not found.")
33
- st.stop()
34
-
35
-
36
- #st.title("🏛️ AFTP Hardship Treatment Planner")
37
- st.subheader("![image/png](https://cdn-uploads.huggingface.co/production/uploads/688abc51f5077dea074b2f8d/dSu3n5I9OyaIQtNWP6kt5.png) Autonomous Financial Hardship Treatment Planner")
38
-
39
- # ---- LLM LOAD ----
40
- @st.cache_resource
41
- def load_llm():
42
- model_id = "google/flan-t5-small"
43
- tokenizer = AutoTokenizer.from_pretrained(model_id)
44
- model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
45
- return model, tokenizer
46
-
47
- llm_model, llm_tokenizer = load_llm()
48
- llm_model.eval()
49
-
50
- # ---- VECTOR STORE ----
51
- encoder = SentenceTransformer("all-MiniLM-L6-v2")
52
- index = faiss.IndexFlatL2(384)
53
- vector_store = {}
54
-
55
- def build_embedding(app: dict) -> str:
56
- return f"{app['hardship_reason']} income:{app['income']} expenses:{app['expenses']}"
57
-
58
- def store_context(customer_id: str, embedding_text: str, context: dict):
59
- vector = encoder.encode([embedding_text])[0]
60
- index.add(np.array([vector]))
61
- vector_store[customer_id] = {"vector": vector, "context": context}
62
-
63
- ## Sample Hardship treatment plans Prepopulation
64
- def prepopulate_sample_cases():
65
- """
66
- Prepopulate vector store with realistic historical cases for similarity matching.
67
- """
68
- sample_cases = [
69
- {"customer_id": "C100", "app": {"hardship_reason": "Job Loss", "income": 1500,"expenses": 2200}, "context": {"plan": "3-month deferral",
70
- "status": "completed"}},
71
- {"customer_id": "C101", "app": {"hardship_reason": "Natural Disaster", "income": 1800, "expenses": 2100}, "context": {"plan": "interest reduction",
72
- "status": "completed"}},
73
- {"customer_id": "C102", "app": {"hardship_reason": "Medical", "income": 2000, "expenses": 2500}, "context": {"plan": "partial payment suspension",
74
- "status": "completed"}},
75
- {"customer_id": "C103", "app": {"hardship_reason": "Job Loss", "income": 1400, "expenses": 2000}, "context": {"plan": "3-month deferral",
76
- "status": "completed"}},
77
- {"customer_id": "C104", "app": {"hardship_reason": "Natural Disaster", "income": 2500, "expenses": 2600}, "context": {"plan": "payment extension",
78
- "status": "completed"}}
79
- ]
80
-
81
- for case in sample_cases:
82
- embedding_text = build_embedding(case["app"])
83
- store_context(case["customer_id"], embedding_text, case["context"])
84
-
85
- if len(vector_store) == 0: #avoid repopulating on every rerun,
86
- prepopulate_sample_cases()
87
-
88
-
89
- # ---- Hardcoded Plans ----
90
- hardship_plans = {
91
- "3-month deferral": {"description": "Suspend payments for 3 months.", "risk_score": 2},
92
- "partial payment suspension": {"description": "Pay only 50% for 3 months.", "risk_score": 3},
93
- "interest reduction": {"description": "Reduce interest by 25% for 6 months.", "risk_score": 1},
94
- "payment extension": {"description": "Extend term by 12 months.", "risk_score": 4},
95
- "restructure repayment": {"description": "Restructure repayment terms based on income profile.", "risk_score": 3},
96
- "defer interest only": {"description": "Pay only interest for 3 months.", "risk_score": 2},
97
- "grace period": {"description": "Grace period of 1 month with no payment.", "risk_score": 1}
98
- }
99
-
100
- # ---- Sample Case Workers ----
101
- case_worker_df = pd.DataFrame([
102
- {"name": "Peter Swift", "plan": "3-month deferral", "experience_years": 5, "on_leave": False},
103
- {"name": "Anthony Mackay", "plan": "interest reduction", "experience_years": 7, "on_leave": False},
104
- {"name": "Sara Keeves", "plan": "partial payment suspension", "experience_years": 4, "on_leave": True},
105
- {"name": "Lara Brent", "plan": "partial payment suspension", "experience_years": 5, "on_leave": False},
106
- {"name": "David Ray", "plan": "payment extension", "experience_years": 6, "on_leave": False},
107
- ])
108
-
109
- def assign_case_worker(plan: str):
110
- available = case_worker_df[(case_worker_df["plan"] == plan) & (~case_worker_df["on_leave"])]
111
- if not available.empty:
112
- return available.sample(1).iloc[0]
113
- return None
114
-
115
- def assign_human_caseworker():
116
- available = case_worker_df[(case_worker_df["experience_years"] >= 5) & (~case_worker_df["on_leave"])]
117
- if not available.empty:
118
- return available.sample(1).iloc[0]
119
- return None
120
-
121
- # ---- AgentState TypedDict ----
122
- class AgentState(TypedDict):
123
- application: Optional[Dict[str, Any]]
124
- selected_plan: Optional[str]
125
- escalated: bool
126
- handled: bool
127
- matched_case_df: Optional[pd.DataFrame]
128
- ltm_match_history: list
129
- feedback: Optional[str]
130
- submitted_feedbacks: set
131
- reference_id: Optional[str]
132
- agent_logs: list
133
- current_node: str
134
- eligible_plans: Optional[list]
135
- previous_plans: list
136
-
137
- # ---- Eligibility and Matching Functions ----
138
- def check_eligibility(app: Dict) -> list:
139
- # Debug inside eligibility
140
- 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']}")
141
- if app["hardship_reason"] == "Job Loss" and app["income"] < app["expenses"]:
142
- return ["3-month deferral", "partial payment suspension"]
143
- return ["payment extension", "interest reduction"]
144
-
145
- def check_proactive_escalation(app: Dict) -> bool:
146
- return app["history"]["late_payments"] > 3 or app.get("flagged_abuse", False)
147
-
148
- def match_from_ltm(app: Dict[str, Any]) -> Optional[pd.DataFrame]:
149
- if len(vector_store) == 0:
150
- return None
151
-
152
- query_vector = encoder.encode([build_embedding(app)])[0]
153
- similarity_threshold = 10.0
154
- D, I = index.search(np.array([query_vector]), k=1)
155
- distance = D[0][0]
156
-
157
- if distance <= similarity_threshold:
158
- match_id = list(vector_store.keys())[I[0][0]]
159
- matched_context = vector_store[match_id]["context"]
160
- matched_df = pd.DataFrame([{
161
- "Customer ID": match_id,
162
- "Plan": matched_context["plan"],
163
- "Status": matched_context.get("status", "N/A")
164
- }])
165
- return matched_df
166
- else:
167
- st.session_state.agent_state["agent_logs"].append(f"[Debug] No similar case found. Distance: {distance:.2f}")
168
- return None
169
-
170
- # ---- Node Functions ----
171
- # Hardcoded, safe validate() , this temporary fixed version that hard-forces the downstream steps unless escalation is needed:
172
- def validate(state: AgentState) -> AgentState:
173
- logs = state["agent_logs"]
174
- logs.append("[Node] Entered validate")
175
- app = state["application"]
176
- state["current_node"] = "validate"
177
-
178
- # Only escalate if absolutely needed
179
- if check_proactive_escalation(app):
180
- logs.append("[Info] Escalation triggered in validate()")
181
- state["escalated"] = True
182
- worker = assign_human_caseworker()
183
- if worker is not None:
184
- logs.append(f"[Escalation] Assigned to case worker: {worker['name']}")
185
- else:
186
- logs.append("[Escalation] No available senior case workers. Case queued.")
187
- state["handled"] = True
188
- else:
189
- logs.append("[Info] No escalation triggered in validate()")
190
- state["escalated"] = False
191
- state["handled"] = False # FORCE this
192
- logs.append(f"[Info] Post validate() state: escalated={state['escalated']}, handled={state['handled']}") # debug
193
- return state
194
-
195
- def reason_and_rank(state: AgentState) -> AgentState:
196
- logs = state["agent_logs"]
197
- logs.append("[Node] Entered reason_and_rank")
198
-
199
- app = state["application"]
200
- state["current_node"] = "reason_and_rank"
201
-
202
- # 1. Check eligibility
203
- eligible = check_eligibility(app)
204
- state["eligible_plans"] = eligible
205
-
206
- if eligible:
207
- top_plan = sorted(eligible, key=lambda p: hardship_plans[p]["risk_score"])[0]
208
- desc = hardship_plans[top_plan]["description"]
209
- logs.append(f"[Node: reason_and_rank] Eligible Plan: {top_plan} → {desc}")
210
- else:
211
- logs.append("[Node: reason_and_rank] No eligible plans found.")
212
-
213
- # 2. Try to match from Long-Term Memory (LTM)
214
- matched_df = match_from_ltm(app)
215
- if matched_df is not None:
216
- matched_plan = matched_df.iloc[0]["Plan"]
217
-
218
- # Check if user already saw this LTM plan
219
- if matched_plan not in state.get("previous_plans", []):
220
- logs.append(f"[LTM Match] Found matching plan from long-term memory: {matched_plan}")
221
- state["selected_plan"] = matched_plan
222
- state.setdefault("previous_plans", []).append(matched_plan)
223
- state["matched_case_df"] = matched_df
224
- state.setdefault("ltm_match_history", []).append(matched_df.copy()) # append the matched_df
225
- logs.append(f"[Plan Selection] Selected Plan from LTM: {matched_plan}")
226
- return state
227
- else:
228
- logs.append(f"[LTM Match] Skipped LTM plan {matched_plan} (already proposed)")
229
-
230
- # 3. No LTM match – proceed with ranking eligible hardcoded plans
231
- if not eligible:
232
- state["escalated"] = True
233
- state["handled"] = True
234
- logs.append("[Warning] No eligible plans found. Escalating to human agent.")
235
- return state
236
-
237
- # 4. Rank and pick plan from eligible ones
238
- ranked = sorted(eligible, key=lambda p: hardship_plans[p]["risk_score"])
239
- previous = state.get("previous_plans", [])
240
- ranked_filtered = [p for p in ranked if p not in previous]
241
-
242
- if not ranked_filtered:
243
- logs.append("[Plan Selection] No new plans left after filtering. Escalating.")
244
- state["escalated"] = True
245
- state["handled"] = True
246
- return state
247
-
248
- selected_plan = ranked_filtered[0]
249
- state["selected_plan"] = selected_plan
250
- state.setdefault("previous_plans", []).append(selected_plan)
251
-
252
- logs.append(f"[Plan Selection] Selected new plan: {selected_plan}")
253
-
254
- worker = assign_case_worker(selected_plan)
255
- if worker is not None:
256
- logs.append(f"[CRM] Assigned to {worker['name']} for plan: {selected_plan}")
257
- else:
258
- logs.append(f"[CRM] No available case worker for plan: {selected_plan}")
259
-
260
- return state
261
-
262
-
263
- def take_action(state: AgentState) -> AgentState:
264
- logs = state["agent_logs"]
265
- logs.append("[Node] Entered take_action()")
266
- app = state["application"]
267
- plan = state["selected_plan"]
268
- state["current_node"] = "take_action"
269
-
270
- # Defensive check in case already assigned earlier
271
- if "crm_logged" not in state:
272
- worker = assign_case_worker(plan)
273
- if worker is not None:
274
- logs.append(f"[CRM] Logged case for {app['name']} - Plan: {plan} → Assigned to {worker['name']}")
275
- else:
276
- logs.append(f"[CRM] No available case worker for plan: {plan}")
277
- state["crm_logged"] = True # prevent future re-logging
278
-
279
- # Store the decision in long-term memory (LTM)
280
- store_context(app["customer_id"], build_embedding(app), {"plan": plan, "status": "active"})
281
-
282
- state["handled"] = True
283
- return state
284
-
285
-
286
- # ---- Decide Next Node ----
287
- def decide_next_node(state: AgentState) -> str:
288
- logs = state["agent_logs"]
289
- current_node = state["current_node"]
290
- app = state.get("application", {})
291
- history = app.get("history", {})
292
- logs.append(f"[Router] At node: {current_node}") # debug code
293
- logs.append(f"[Info] decide_next_node() called at node: {current_node}") # debug code
294
-
295
- if state["handled"] or state["escalated"]:
296
- logs.append("[Router] Already handled or escalated - routing to END") # debug code
297
- return END
298
-
299
- # Define valid next nodes
300
- valid_next_nodes = {
301
- "validate": ["reason_and_rank", END],
302
- "reason_and_rank": ["take_action", END],
303
- "take_action": [END]
304
- }.get(current_node, [END])
305
-
306
- # Few-shot prompt
307
- few_shot = """
308
- Current Node: validate, flagged_abuse=False, selected_plan=None, handled=False → reason_and_rank
309
- Current Node: reason_and_rank, selected_plan=interest reduction, handled=False → take_action
310
- Current Node: take_action, handled=True → END
311
- Current Node: validate, escalated=True, handled=True → END
312
- """
313
-
314
- prompt = f"""
315
- You are an AI agent orchestrating a financial hardship planner.
316
- Given the current node and customer data, choose the next step in the process.
317
- {few_shot}
318
- Customer Info:
319
- - Name: {app.get('name', 'Unknown')}
320
- - Hardship Reason: {app.get('hardship_reason', 'Unknown')}
321
- - Income: {app.get('income', 'N/A')}
322
- - Expenses: {app.get('expenses', 'N/A')}
323
- - Late Payments: {history.get('late_payments', 0)}
324
- - Flagged Abuse: {app.get('flagged_abuse', False)}
325
- - Escalated: {state.get('escalated', False)}
326
- - Handled: {state.get('handled', False)}
327
- - Selected Plan: {state.get('selected_plan')}
328
- - Eligible Plans: {state.get('eligible_plans', [])}
329
- - Current Node: {current_node}
330
- Next: {', '.join(valid_next_nodes)}
331
- """
332
-
333
- with torch.no_grad():
334
- start = time.time()
335
- input_ids = llm_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512).input_ids
336
- outputs = llm_model.generate(input_ids=input_ids, max_new_tokens=10, do_sample=False)
337
- end = time.time()
338
- response = llm_tokenizer.decode(outputs[0], skip_special_tokens=True).strip().lower()
339
- response = response.split()[0] # Only take first word to normalize
340
- logs.append(f"[Router] LLM output: {response}") # debug code
341
- #st.markdown(f"⏲ **LLM inference time:** `{end - start:.2f} seconds`")
342
- st.markdown(f"⏳ **LLM inference time:** `{end - start:.2f} seconds`")
343
-
344
- if response not in valid_next_nodes:
345
- logs.append(f"[Router Warning] Invalid LLM output '{response}', defaulting to {valid_next_nodes[0]}") # debug code
346
- return valid_next_nodes[0]
347
-
348
- if response == "end" or state["escalated"]:
349
- logs.append("[Router] Routing to END due to LLM output or escalation.")
350
- return END
351
-
352
- if state["selected_plan"] is None and response == "take_action":
353
- logs.append("[Router Warning] LLM tried to skip reasoning. Forcing reason_and_rank.") # debug code
354
- return "reason_and_rank"
355
-
356
- logs.append(f"[Router] Moving from {current_node} to {response}")
357
- return response
358
-
359
- # ---- LangGraph Workflow Setup ----
360
- workflow = StateGraph(AgentState)
361
- workflow.add_node("validate", validate)
362
- workflow.add_node("reason_and_rank", reason_and_rank)
363
- workflow.add_node("take_action", take_action)
364
-
365
- workflow.add_conditional_edges(
366
- "validate",
367
- decide_next_node,
368
- {
369
- "reason_and_rank": "reason_and_rank",
370
- END: END
371
- }
372
- )
373
- workflow.add_conditional_edges(
374
- "reason_and_rank",
375
- decide_next_node,
376
- {
377
- "take_action": "take_action",
378
- END: END
379
- }
380
- )
381
- workflow.add_conditional_edges(
382
- "take_action",
383
- decide_next_node,
384
- {
385
- END: END
386
- }
387
- )
388
- workflow.set_entry_point("validate")
389
- graph: CompiledStateGraph = workflow.compile()
390
-
391
- # ---- Initialize session state ----
392
- def init_session():
393
- if "step" not in st.session_state:
394
- st.session_state.step = "form"
395
- if "application" not in st.session_state:
396
- st.session_state.application = None
397
- if "plan_accepted" not in st.session_state:
398
- st.session_state.plan_accepted = False
399
- if "escalated" not in st.session_state:
400
- st.session_state.escalated = False
401
- if "handled" not in st.session_state:
402
- st.session_state.handled = False
403
- if "matched_case_df" not in st.session_state:
404
- st.session_state.matched_case_df = None
405
- if "feedback" not in st.session_state:
406
- st.session_state.feedback = None
407
- if "submitted_feedbacks" not in st.session_state:
408
- st.session_state.submitted_feedbacks = set()
409
- if "reference_id" not in st.session_state:
410
- st.session_state.reference_id = None
411
- if "agent_logs" not in st.session_state:
412
- st.session_state.agent_logs = []
413
- if "previous_plans" not in st.session_state:
414
- st.session_state.previous_plans = []
415
- if "agent_state" not in st.session_state or st.session_state.agent_state is None:
416
- st.session_state.agent_state = AgentState(
417
- application=None,
418
- selected_plan=None,
419
- escalated=False,
420
- handled=False,
421
- matched_case_df=None,
422
- ltm_match_history=[],
423
- feedback=None,
424
- submitted_feedbacks=set(),
425
- reference_id=None,
426
- agent_logs=[],
427
- current_node="validate",
428
- eligible_plans=None,
429
- previous_plans=[]
430
- )
431
-
432
- init_session()
433
-
434
- # ---- UI and workflow execution ----
435
- if st.session_state.step == "form":
436
- with st.form("user_input"):
437
- #st.subheader("📝 Enter Your Details")
438
- st.subheader("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/6Om0nXTbrf8Mew4zJ7Gsh.png) Enter Your Details")
439
- name = st.text_input("First Name")
440
- customer_id = st.text_input("Customer ID")
441
- account_type = st.selectbox("Account Type", ["mortgage", "credit card", "personal loan"])
442
- hardship_reason = st.selectbox("Reason for Hardship", ["Job Loss", "Medical", "Natural Disaster"])
443
- income = st.number_input("Monthly Income", min_value=0.0)
444
- expenses = st.number_input("Monthly Expenses", min_value=0.0)
445
- late_payments = st.number_input("Late Payments (last 12 months)", min_value=0, step=1)
446
- flagged_abuse = st.radio("Previously defaulted or rejected?", ["No", "Yes"]) == "Yes"
447
- submitted = st.form_submit_button("Submit")
448
-
449
- if submitted:
450
- if not name.strip():
451
- st.warning("⚠️ Please enter your name.")
452
- elif not customer_id.strip():
453
- st.warning("⚠️ Please enter your customer ID.")
454
- elif income == 0.0:
455
- st.warning("⚠️ Please enter your income.")
456
- elif expenses == 0.0:
457
- st.warning("⚠️ Please enter your expenses.")
458
- else:
459
- st.session_state.application = {
460
- "name": name.strip(),
461
- "account_type": account_type,
462
- "hardship_reason": hardship_reason,
463
- "income": income,
464
- "expenses": expenses,
465
- "history": {"late_payments": late_payments},
466
- "flagged_abuse": flagged_abuse,
467
- "customer_id": customer_id,
468
- }
469
- st.session_state.agent_state["application"] = st.session_state.application
470
- st.session_state.agent_state["current_node"] = "validate"
471
- st.session_state.agent_state["selected_plan"] = None
472
- st.session_state.agent_state["escalated"] = False
473
- st.session_state.agent_state["handled"] = False
474
- st.session_state.agent_state["matched_case_df"] = None
475
- st.session_state.agent_state["feedback"] = None
476
- st.session_state.agent_state["eligible_plans"] = None
477
- st.session_state.agent_state["submitted_feedbacks"] = set()
478
- st.session_state.agent_state["agent_logs"] = []
479
- st.session_state.step = "processing"
480
- st.rerun()
481
-
482
- elif st.session_state.step == "processing":
483
- #st.info("📡 Processing your request...")
484
- st.info("![image/gif](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/8tQqf9gWdbl9Sb3bO6O6C.gif) Processing your request...")
485
- state = st.session_state.agent_state
486
- logs = state["agent_logs"] # This line is required
487
- logs.append("[Node] Processing plan recommendation...")
488
-
489
- # Run the graph streaming to execute the workflow nodes including reason_and_rank and take_action
490
- for updated_state in graph.stream(state):
491
- node_name, inner_state = list(updated_state.items())[0]
492
-
493
- # Update session state with the new state
494
- st.session_state.agent_state = inner_state
495
- st.session_state.agent_logs = inner_state.get("agent_logs", [])
496
- st.session_state.ltm_match_history = inner_state.get("ltm_match_history", [])
497
- st.session_state.escalated = inner_state.get("escalated", False)
498
- st.session_state.handled = inner_state.get("handled", False)
499
- st.session_state.matched_case_df = inner_state.get("matched_case_df")
500
- st.session_state.reference_id = inner_state.get("reference_id")
501
-
502
- state = inner_state # Feed updated state back to next iteration
503
-
504
- #inner_state["agent_logs"].append(f"[Debug] Node executed: {node_name}") # debug code
505
- inner_state["agent_logs"].append(f"[Info] node executed]: {node_name}")
506
-
507
- if node_name == END:
508
- break
509
-
510
- #st.write("✅ Final state from LangGraph:") # debug code
511
- #st.json(state) # debug code
512
-
513
- # Move to results after processing the entire graph
514
- st.session_state.step = "results"
515
- st.rerun()
516
-
517
-
518
- elif st.session_state.step == "results":
519
- state = st.session_state.agent_state
520
-
521
- if st.session_state.escalated:
522
- st.warning("⚠️ Your case has been assigned to a agent for review.")
523
- ref = f"{state['application']['customer_id'].upper()}-{datetime.now().strftime('%d%m%y%H%M%S')}"
524
- state["reference_id"] = ref
525
- st.markdown(f"**Reference#:** `{ref}`")
526
- if st.button("⮎ Continue"):
527
- for k in list(st.session_state.keys()):
528
- del st.session_state[k]
529
- st.rerun()
530
- st.session_state.step = "done"
531
- st.stop()
532
-
533
- elif state.get("selected_plan"):
534
- plan = state["selected_plan"]
535
- st.success(f"✅ Proposed Plan: **{plan}**")
536
- st.markdown(f"**{hardship_plans[plan]['description']}**")
537
-
538
- #Suggestion (Optional)
539
- #ranked = sorted(state.get("eligible_plans", []), key=lambda p: hardship_plans[p]["risk_score"])
540
- #if plan in ranked and len(ranked) > 1:
541
- # alternatives = [p for p in ranked if p != plan]
542
- # second_best = alternatives[0]
543
- # st.info(f"💡 You might also consider: **{second_best}** — {hardship_plans[second_best]['description']}")
544
-
545
- submitted = state["submitted_feedbacks"]
546
- remaining = {"Accept", "I can only afford half", "Suggest alternative"} - submitted
547
-
548
- if "Accept" in submitted:
549
- st.success("Thank you for your response.")
550
- st.success(f"You have accepted the proposed plan: **{plan}**")
551
- ref = state.get("reference_id")
552
- if ref:
553
- st.markdown(f"**Reference#:** `{ref}`")
554
- if st.button("🔁 Submit New Request"):
555
- for k in list(st.session_state.keys()):
556
- del st.session_state[k]
557
- st.rerun()
558
- st.session_state.step = "done"
559
- st.stop()
560
-
561
- # Show feedback options only if not already accepted
562
- options = [opt for opt in ["Accept", "I can only afford half", "Suggest alternative"] if opt in remaining] #options = list(remaining)
563
- feedback = st.radio("Feedback (choose one):", options, key="feedback_choice")
564
-
565
- if st.button("Submit Feedback"):
566
- submitted.add(feedback)
567
- state["submitted_feedbacks"] = submitted
568
- state["agent_logs"].append(f"[Feedback] User selected: {feedback}")
569
-
570
- if feedback == "Accept":
571
- state["handled"] = True
572
- ref = f"{state['application']['customer_id'].upper()}-{datetime.now().strftime('%d%m%y%H%M%S')}"
573
- state["reference_id"] = ref
574
- st.session_state.step = "done"
575
- st.rerun()
576
-
577
-
578
- elif "half" in feedback.lower():
579
- state["agent_logs"].append("[Feedback Action] User selected 'half'. Reducing income and rerunning reason_and_rank")
580
- state["application"]["income"] = state["application"]["income"] / 2 # Adjust income
581
- state["feedback"] = "half"
582
- state["handled"] = False
583
- state.pop("selected_plan", None) # Force recomputation
584
- state.pop("matched_case_df", None) #clear matched case display (but keep history)
585
- state["current_node"] = "reason_and_rank"
586
- st.session_state.step = "processing"
587
- st.rerun()
588
-
589
- elif feedback == "Suggest alternative":
590
- state["feedback"] = "wants_alternative"
591
- state["handled"] = False
592
- state["current_node"] = "reason_and_rank"
593
- state["agent_logs"].append("[Feedback Action] User requested alternative. Clearing selected_plan and rerunning reason_and_rank")
594
- state.pop("selected_plan", None) #clear old plan so it doesn't get reused
595
- state.pop("matched_case_df", None) # clear matched case display (but keep history)
596
- st.session_state.step = "processing"
597
- st.rerun()
598
- else:
599
- st.warning("⚠️ No plan could be proposed.")
600
- st.session_state.step = "done"
601
- st.rerun()
602
-
603
- elif st.session_state.step == "done":
604
- state = st.session_state.agent_state
605
- #st.success("🎉 Thank you for your response.")
606
- st.success("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/2KNwWbE-GjSYTOpfcA0N3.png) Thank you for your response.")
607
- if state.get("selected_plan"):
608
- st.markdown(f"**You have accepted the proposed plan:** `{state['selected_plan']}`")
609
- if state.get("reference_id"):
610
- st.markdown(f"**Reference#:** `{state['reference_id']}`")
611
- #if st.button("🔁 Submit New Request"):
612
- if st.button("🔂 Submit New Request"):
613
- for k in list(st.session_state.keys()):
614
- del st.session_state[k]
615
- st.rerun()
616
-
617
- # Show Agent Logs only after user has submitted their details
618
- if st.session_state.step in {"processing", "results", "done"}:
619
- #if "agent_state" in st.session_state and st.session_state.agent_state: OR #if st.session_state.agent_logs:
620
- st.markdown("---")
621
- #st.markdown("### 📜 Agent Logs")
622
- st.markdown("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/-h1QdYhvBfI-15wWmD6iT.png) Agent Logs")
623
- logs = st.session_state.agent_state["agent_logs"]
624
- for log in logs:
625
- st.markdown(f"- {log}")
626
- st.markdown("---")
627
-
628
- # ----- Matched Cases from Long‑Term Memory -----
629
- if st.session_state.ltm_match_history:
630
- #st.markdown("### 🧠 Matched Cases from Long‑Term Memory")
631
- st.markdown("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/LogBa8z0GRqlmfMKEGCCG.png) Matched Cases from Long‑Term Memory")
632
- for idx, df in enumerate(st.session_state.ltm_match_history, 1):
633
- st.markdown(f"#### Match {idx}")
634
- st.table(df)
635
- else:
636
  st.info("No similar cases found in long‑term memory.")
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import faiss
5
+ import torch
6
+ import time
7
+ from datetime import datetime
8
+ from sentence_transformers import SentenceTransformer
9
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
10
+ from langgraph.graph import StateGraph, END
11
+ from langgraph.graph.state import CompiledStateGraph
12
+ from typing import Dict, Any, Optional, TypedDict
13
+
14
+ # ---- SETUP ----
15
+ st.set_page_config(page_title="AFTP Hardship Planner", layout="centered")
16
+ #st.title("🏛️ AFTP Hardship Treatment Planner")
17
+ st.subheader("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/Jz4D18-ugDEuazyyU-7QG.png) Autonomous Financial Hardship Treatment Planner (AFTP)")
18
+
19
+ # ---- LLM LOAD ----
20
+ @st.cache_resource
21
+ def load_llm():
22
+ model_id = "google/flan-t5-small"
23
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
24
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
25
+ return model, tokenizer
26
+
27
+ llm_model, llm_tokenizer = load_llm()
28
+ llm_model.eval()
29
+
30
+ # ---- VECTOR STORE ----
31
+ encoder = SentenceTransformer("all-MiniLM-L6-v2")
32
+ index = faiss.IndexFlatL2(384)
33
+ vector_store = {}
34
+
35
+ def build_embedding(app: dict) -> str:
36
+ return f"{app['hardship_reason']} income:{app['income']} expenses:{app['expenses']}"
37
+
38
+ def store_context(customer_id: str, embedding_text: str, context: dict):
39
+ vector = encoder.encode([embedding_text])[0]
40
+ index.add(np.array([vector]))
41
+ vector_store[customer_id] = {"vector": vector, "context": context}
42
+
43
+ ## Sample Hardship treatment plans Prepopulation
44
+ def prepopulate_sample_cases():
45
+ """
46
+ Prepopulate vector store with realistic historical cases for similarity matching.
47
+ """
48
+ sample_cases = [
49
+ {"customer_id": "C100", "app": {"hardship_reason": "Job Loss", "income": 1500,"expenses": 2200}, "context": {"plan": "3-month deferral",
50
+ "status": "completed"}},
51
+ {"customer_id": "C101", "app": {"hardship_reason": "Natural Disaster", "income": 1800, "expenses": 2100}, "context": {"plan": "interest reduction",
52
+ "status": "completed"}},
53
+ {"customer_id": "C102", "app": {"hardship_reason": "Medical", "income": 2000, "expenses": 2500}, "context": {"plan": "partial payment suspension",
54
+ "status": "completed"}},
55
+ {"customer_id": "C103", "app": {"hardship_reason": "Job Loss", "income": 1400, "expenses": 2000}, "context": {"plan": "3-month deferral",
56
+ "status": "completed"}},
57
+ {"customer_id": "C104", "app": {"hardship_reason": "Natural Disaster", "income": 2500, "expenses": 2600}, "context": {"plan": "payment extension",
58
+ "status": "completed"}}
59
+ ]
60
+
61
+ for case in sample_cases:
62
+ embedding_text = build_embedding(case["app"])
63
+ store_context(case["customer_id"], embedding_text, case["context"])
64
+
65
+ if len(vector_store) == 0: #avoid repopulating on every rerun,
66
+ prepopulate_sample_cases()
67
+
68
+
69
+ # ---- Hardcoded Plans ----
70
+ hardship_plans = {
71
+ "3-month deferral": {"description": "Suspend payments for 3 months.", "risk_score": 2},
72
+ "partial payment suspension": {"description": "Pay only 50% for 3 months.", "risk_score": 3},
73
+ "interest reduction": {"description": "Reduce interest by 25% for 6 months.", "risk_score": 1},
74
+ "payment extension": {"description": "Extend term by 12 months.", "risk_score": 4},
75
+ "restructure repayment": {"description": "Restructure repayment terms based on income profile.", "risk_score": 3},
76
+ "defer interest only": {"description": "Pay only interest for 3 months.", "risk_score": 2},
77
+ "grace period": {"description": "Grace period of 1 month with no payment.", "risk_score": 1}
78
+ }
79
+
80
+ # ---- Sample Case Workers ----
81
+ case_worker_df = pd.DataFrame([
82
+ {"name": "Peter Swift", "plan": "3-month deferral", "experience_years": 5, "on_leave": False},
83
+ {"name": "Anthony Mackay", "plan": "interest reduction", "experience_years": 7, "on_leave": False},
84
+ {"name": "Sara Keeves", "plan": "partial payment suspension", "experience_years": 4, "on_leave": True},
85
+ {"name": "Lara Brent", "plan": "partial payment suspension", "experience_years": 5, "on_leave": False},
86
+ {"name": "David Ray", "plan": "payment extension", "experience_years": 6, "on_leave": False},
87
+ ])
88
+
89
+ def assign_case_worker(plan: str):
90
+ available = case_worker_df[(case_worker_df["plan"] == plan) & (~case_worker_df["on_leave"])]
91
+ if not available.empty:
92
+ return available.sample(1).iloc[0]
93
+ return None
94
+
95
+ def assign_human_caseworker():
96
+ available = case_worker_df[(case_worker_df["experience_years"] >= 5) & (~case_worker_df["on_leave"])]
97
+ if not available.empty:
98
+ return available.sample(1).iloc[0]
99
+ return None
100
+
101
+ # ---- AgentState TypedDict ----
102
+ class AgentState(TypedDict):
103
+ application: Optional[Dict[str, Any]]
104
+ selected_plan: Optional[str]
105
+ escalated: bool
106
+ handled: bool
107
+ matched_case_df: Optional[pd.DataFrame]
108
+ ltm_match_history: list
109
+ feedback: Optional[str]
110
+ submitted_feedbacks: set
111
+ reference_id: Optional[str]
112
+ agent_logs: list
113
+ current_node: str
114
+ eligible_plans: Optional[list]
115
+ previous_plans: list
116
+
117
+ # ---- Eligibility and Matching Functions ----
118
+ def check_eligibility(app: Dict) -> list:
119
+ # Debug inside eligibility
120
+ 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']}")
121
+ if app["hardship_reason"] == "Job Loss" and app["income"] < app["expenses"]:
122
+ return ["3-month deferral", "partial payment suspension"]
123
+ return ["payment extension", "interest reduction"]
124
+
125
+ def check_proactive_escalation(app: Dict) -> bool:
126
+ return app["history"]["late_payments"] > 3 or app.get("flagged_abuse", False)
127
+
128
+ def match_from_ltm(app: Dict[str, Any]) -> Optional[pd.DataFrame]:
129
+ if len(vector_store) == 0:
130
+ return None
131
+
132
+ query_vector = encoder.encode([build_embedding(app)])[0]
133
+ similarity_threshold = 10.0
134
+ D, I = index.search(np.array([query_vector]), k=1)
135
+ distance = D[0][0]
136
+
137
+ if distance <= similarity_threshold:
138
+ match_id = list(vector_store.keys())[I[0][0]]
139
+ matched_context = vector_store[match_id]["context"]
140
+ matched_df = pd.DataFrame([{
141
+ "Customer ID": match_id,
142
+ "Plan": matched_context["plan"],
143
+ "Status": matched_context.get("status", "N/A")
144
+ }])
145
+ return matched_df
146
+ else:
147
+ st.session_state.agent_state["agent_logs"].append(f"[Debug] No similar case found. Distance: {distance:.2f}")
148
+ return None
149
+
150
+ # ---- Node Functions ----
151
+ # Hardcoded, safe validate() , this temporary fixed version that hard-forces the downstream steps unless escalation is needed:
152
+ def validate(state: AgentState) -> AgentState:
153
+ logs = state["agent_logs"]
154
+ logs.append("[Node] Entered validate")
155
+ app = state["application"]
156
+ state["current_node"] = "validate"
157
+
158
+ # Only escalate if absolutely needed
159
+ if check_proactive_escalation(app):
160
+ logs.append("[Debug] Escalation triggered in validate()")
161
+ state["escalated"] = True
162
+ worker = assign_human_caseworker()
163
+ if worker is not None:
164
+ logs.append(f"[Escalation] Assigned to case worker: {worker['name']}")
165
+ else:
166
+ logs.append("[Escalation] No available senior case workers. Case queued.")
167
+ state["handled"] = True
168
+ else:
169
+ logs.append("[Info] No escalation triggered in validate()")
170
+ state["escalated"] = False
171
+ state["handled"] = False # FORCE this
172
+ logs.append(f"[Info] Post validate() state: escalated={state['escalated']}, handled={state['handled']}") # debug
173
+ return state
174
+
175
+ def reason_and_rank(state: AgentState) -> AgentState:
176
+ logs = state["agent_logs"]
177
+ logs.append("[Node] Entered reason_and_rank")
178
+
179
+ app = state["application"]
180
+ state["current_node"] = "reason_and_rank"
181
+
182
+ # 1. Check eligibility
183
+ eligible = check_eligibility(app)
184
+ state["eligible_plans"] = eligible
185
+
186
+ if eligible:
187
+ top_plan = sorted(eligible, key=lambda p: hardship_plans[p]["risk_score"])[0]
188
+ desc = hardship_plans[top_plan]["description"]
189
+ logs.append(f"[Node: reason_and_rank] Eligible Plan: {top_plan} → {desc}")
190
+ else:
191
+ logs.append("[Node: reason_and_rank] No eligible plans found.")
192
+
193
+ # 2. Try to match from Long-Term Memory (LTM)
194
+ matched_df = match_from_ltm(app)
195
+ if matched_df is not None:
196
+ matched_plan = matched_df.iloc[0]["Plan"]
197
+
198
+ # Check if user already saw this LTM plan
199
+ if matched_plan not in state.get("previous_plans", []):
200
+ logs.append(f"[LTM Match] Found matching plan from long-term memory: {matched_plan}")
201
+ state["selected_plan"] = matched_plan
202
+ state.setdefault("previous_plans", []).append(matched_plan)
203
+ state["matched_case_df"] = matched_df
204
+ state.setdefault("ltm_match_history", []).append(matched_df.copy()) # append the matched_df
205
+ logs.append(f"[Plan Selection] Selected Plan from LTM: {matched_plan}")
206
+ return state
207
+ else:
208
+ logs.append(f"[LTM Match] Skipped LTM plan {matched_plan} (already proposed)")
209
+
210
+ # 3. No LTM match – proceed with ranking eligible hardcoded plans
211
+ if not eligible:
212
+ state["escalated"] = True
213
+ state["handled"] = True
214
+ logs.append("[Warning] No eligible plans found. Escalating to human agent.")
215
+ return state
216
+
217
+ # 4. Rank and pick plan from eligible ones
218
+ ranked = sorted(eligible, key=lambda p: hardship_plans[p]["risk_score"])
219
+ previous = state.get("previous_plans", [])
220
+ ranked_filtered = [p for p in ranked if p not in previous]
221
+
222
+ if not ranked_filtered:
223
+ logs.append("[Plan Selection] No new plans left after filtering. Escalating.")
224
+ state["escalated"] = True
225
+ state["handled"] = True
226
+ return state
227
+
228
+ selected_plan = ranked_filtered[0]
229
+ state["selected_plan"] = selected_plan
230
+ state.setdefault("previous_plans", []).append(selected_plan)
231
+
232
+ logs.append(f"[Plan Selection] Selected new plan: {selected_plan}")
233
+
234
+ worker = assign_case_worker(selected_plan)
235
+ if worker is not None:
236
+ logs.append(f"[CRM] Assigned to {worker['name']} for plan: {selected_plan}")
237
+ else:
238
+ logs.append(f"[CRM] No available case worker for plan: {selected_plan}")
239
+
240
+ return state
241
+
242
+
243
+ def take_action(state: AgentState) -> AgentState:
244
+ logs = state["agent_logs"]
245
+ logs.append("[Node] Entered take_action()")
246
+ app = state["application"]
247
+ plan = state["selected_plan"]
248
+ state["current_node"] = "take_action"
249
+
250
+ # Defensive check in case already assigned earlier
251
+ if "crm_logged" not in state:
252
+ worker = assign_case_worker(plan)
253
+ if worker is not None:
254
+ logs.append(f"[CRM] Logged case for {app['name']} - Plan: {plan} → Assigned to {worker['name']}")
255
+ else:
256
+ logs.append(f"[CRM] No available case worker for plan: {plan}")
257
+ state["crm_logged"] = True # prevent future re-logging
258
+
259
+ # Store the decision in long-term memory (LTM)
260
+ store_context(app["customer_id"], build_embedding(app), {"plan": plan, "status": "active"})
261
+
262
+ state["handled"] = True
263
+ return state
264
+
265
+
266
+ # ---- Decide Next Node ----
267
+ def decide_next_node(state: AgentState) -> str:
268
+ logs = state["agent_logs"]
269
+ current_node = state["current_node"]
270
+ app = state.get("application", {})
271
+ history = app.get("history", {})
272
+ logs.append(f"[Router] At node: {current_node}") # debug code
273
+ logs.append(f"[Info] decide_next_node() called at node: {current_node}") # debug code
274
+
275
+ if state["handled"] or state["escalated"]:
276
+ logs.append("[Router] Already handled or escalated - routing to END") # debug code
277
+ return END
278
+
279
+ # Define valid next nodes
280
+ valid_next_nodes = {
281
+ "validate": ["reason_and_rank", END],
282
+ "reason_and_rank": ["take_action", END],
283
+ "take_action": [END]
284
+ }.get(current_node, [END])
285
+
286
+ # Few-shot prompt
287
+ few_shot = """
288
+ Current Node: validate, flagged_abuse=False, selected_plan=None, handled=False → reason_and_rank
289
+ Current Node: reason_and_rank, selected_plan=interest reduction, handled=False → take_action
290
+ Current Node: take_action, handled=True → END
291
+ Current Node: validate, escalated=True, handled=True → END
292
+ """
293
+
294
+ prompt = f"""
295
+ You are an AI agent orchestrating a financial hardship planner.
296
+ Given the current node and customer data, choose the next step in the process.
297
+ {few_shot}
298
+ Customer Info:
299
+ - Name: {app.get('name', 'Unknown')}
300
+ - Hardship Reason: {app.get('hardship_reason', 'Unknown')}
301
+ - Income: {app.get('income', 'N/A')}
302
+ - Expenses: {app.get('expenses', 'N/A')}
303
+ - Late Payments: {history.get('late_payments', 0)}
304
+ - Flagged Abuse: {app.get('flagged_abuse', False)}
305
+ - Escalated: {state.get('escalated', False)}
306
+ - Handled: {state.get('handled', False)}
307
+ - Selected Plan: {state.get('selected_plan')}
308
+ - Eligible Plans: {state.get('eligible_plans', [])}
309
+ - Current Node: {current_node}
310
+ Next: {', '.join(valid_next_nodes)}
311
+ """
312
+
313
+ with torch.no_grad():
314
+ start = time.time()
315
+ input_ids = llm_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512).input_ids
316
+ outputs = llm_model.generate(input_ids=input_ids, max_new_tokens=10, do_sample=False)
317
+ end = time.time()
318
+ response = llm_tokenizer.decode(outputs[0], skip_special_tokens=True).strip().lower()
319
+ response = response.split()[0] # Only take first word to normalize
320
+ logs.append(f"[Router] LLM output: {response}") # debug code
321
+ #st.markdown(f"⏲ **LLM inference time:** `{end - start:.2f} seconds`")
322
+ st.markdown(f"⏳ **LLM inference time:** `{end - start:.2f} seconds`")
323
+
324
+ if response not in valid_next_nodes:
325
+ logs.append(f"[Router Warning] Invalid LLM output '{response}', defaulting to {valid_next_nodes[0]}") # debug code
326
+ return valid_next_nodes[0]
327
+
328
+ if response == "end" or state["escalated"]:
329
+ logs.append("[Router] Routing to END due to LLM output or escalation.")
330
+ return END
331
+
332
+ if state["selected_plan"] is None and response == "take_action":
333
+ logs.append("[Router Warning] LLM tried to skip reasoning. Forcing reason_and_rank.") # debug code
334
+ return "reason_and_rank"
335
+
336
+ logs.append(f"[Router] Moving from {current_node} to {response}")
337
+ return response
338
+
339
+ # ---- LangGraph Workflow Setup ----
340
+ workflow = StateGraph(AgentState)
341
+ workflow.add_node("validate", validate)
342
+ workflow.add_node("reason_and_rank", reason_and_rank)
343
+ workflow.add_node("take_action", take_action)
344
+
345
+ workflow.add_conditional_edges(
346
+ "validate",
347
+ decide_next_node,
348
+ {
349
+ "reason_and_rank": "reason_and_rank",
350
+ END: END
351
+ }
352
+ )
353
+ workflow.add_conditional_edges(
354
+ "reason_and_rank",
355
+ decide_next_node,
356
+ {
357
+ "take_action": "take_action",
358
+ END: END
359
+ }
360
+ )
361
+ workflow.add_conditional_edges(
362
+ "take_action",
363
+ decide_next_node,
364
+ {
365
+ END: END
366
+ }
367
+ )
368
+ workflow.set_entry_point("validate")
369
+ graph: CompiledStateGraph = workflow.compile()
370
+
371
+ # ---- Initialize session state ----
372
+ def init_session():
373
+ if "step" not in st.session_state:
374
+ st.session_state.step = "form"
375
+ if "application" not in st.session_state:
376
+ st.session_state.application = None
377
+ if "plan_accepted" not in st.session_state:
378
+ st.session_state.plan_accepted = False
379
+ if "escalated" not in st.session_state:
380
+ st.session_state.escalated = False
381
+ if "handled" not in st.session_state:
382
+ st.session_state.handled = False
383
+ if "matched_case_df" not in st.session_state:
384
+ st.session_state.matched_case_df = None
385
+ if "feedback" not in st.session_state:
386
+ st.session_state.feedback = None
387
+ if "submitted_feedbacks" not in st.session_state:
388
+ st.session_state.submitted_feedbacks = set()
389
+ if "reference_id" not in st.session_state:
390
+ st.session_state.reference_id = None
391
+ if "agent_logs" not in st.session_state:
392
+ st.session_state.agent_logs = []
393
+ if "previous_plans" not in st.session_state:
394
+ st.session_state.previous_plans = []
395
+ if "agent_state" not in st.session_state or st.session_state.agent_state is None:
396
+ st.session_state.agent_state = AgentState(
397
+ application=None,
398
+ selected_plan=None,
399
+ escalated=False,
400
+ handled=False,
401
+ matched_case_df=None,
402
+ ltm_match_history=[],
403
+ feedback=None,
404
+ submitted_feedbacks=set(),
405
+ reference_id=None,
406
+ agent_logs=[],
407
+ current_node="validate",
408
+ eligible_plans=None,
409
+ previous_plans=[]
410
+ )
411
+
412
+ init_session()
413
+
414
+ # ---- UI and workflow execution ----
415
+ if st.session_state.step == "form":
416
+ with st.form("user_input"):
417
+ #st.subheader("📝 Enter Your Details")
418
+ st.subheader("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/6Om0nXTbrf8Mew4zJ7Gsh.png) Enter Your Details")
419
+ name = st.text_input("First Name")
420
+ customer_id = st.text_input("Customer ID")
421
+ account_type = st.selectbox("Account Type", ["mortgage", "credit card", "personal loan"])
422
+ hardship_reason = st.selectbox("Reason for Hardship", ["Job Loss", "Medical", "Natural Disaster"])
423
+ income = st.number_input("Monthly Income", min_value=0.0)
424
+ expenses = st.number_input("Monthly Expenses", min_value=0.0)
425
+ late_payments = st.number_input("Late Payments (last 12 months)", min_value=0, step=1)
426
+ flagged_abuse = st.radio("Previously defaulted or rejected?", ["No", "Yes"]) == "Yes"
427
+ submitted = st.form_submit_button("Submit")
428
+
429
+ if submitted:
430
+ if not name.strip():
431
+ st.warning("⚠️ Please enter your name.")
432
+ elif not customer_id.strip():
433
+ st.warning("⚠️ Please enter your customer ID.")
434
+ elif income == 0.0:
435
+ st.warning("⚠️ Please enter your income.")
436
+ elif expenses == 0.0:
437
+ st.warning("⚠️ Please enter your expenses.")
438
+ else:
439
+ st.session_state.application = {
440
+ "name": name.strip(),
441
+ "account_type": account_type,
442
+ "hardship_reason": hardship_reason,
443
+ "income": income,
444
+ "expenses": expenses,
445
+ "history": {"late_payments": late_payments},
446
+ "flagged_abuse": flagged_abuse,
447
+ "customer_id": customer_id,
448
+ }
449
+ st.session_state.agent_state["application"] = st.session_state.application
450
+ st.session_state.agent_state["current_node"] = "validate"
451
+ st.session_state.agent_state["selected_plan"] = None
452
+ st.session_state.agent_state["escalated"] = False
453
+ st.session_state.agent_state["handled"] = False
454
+ st.session_state.agent_state["matched_case_df"] = None
455
+ st.session_state.agent_state["feedback"] = None
456
+ st.session_state.agent_state["eligible_plans"] = None
457
+ st.session_state.agent_state["submitted_feedbacks"] = set()
458
+ st.session_state.agent_state["agent_logs"] = []
459
+ st.session_state.step = "processing"
460
+ st.rerun()
461
+
462
+ elif st.session_state.step == "processing":
463
+ #st.info("📡 Processing your request...")
464
+ st.info("![image/gif](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/8tQqf9gWdbl9Sb3bO6O6C.gif) Processing your request...")
465
+ state = st.session_state.agent_state
466
+ logs = state["agent_logs"] # This line is required
467
+ logs.append("[Node] Processing plan recommendation...")
468
+
469
+ # Run the graph streaming to execute the workflow nodes including reason_and_rank and take_action
470
+ for updated_state in graph.stream(state):
471
+ node_name, inner_state = list(updated_state.items())[0]
472
+
473
+ # Update session state with the new state
474
+ st.session_state.agent_state = inner_state
475
+ st.session_state.agent_logs = inner_state.get("agent_logs", [])
476
+ st.session_state.ltm_match_history = inner_state.get("ltm_match_history", [])
477
+ st.session_state.escalated = inner_state.get("escalated", False)
478
+ st.session_state.handled = inner_state.get("handled", False)
479
+ st.session_state.matched_case_df = inner_state.get("matched_case_df")
480
+ st.session_state.reference_id = inner_state.get("reference_id")
481
+
482
+ state = inner_state # Feed updated state back to next iteration
483
+
484
+ #inner_state["agent_logs"].append(f"[Debug] Node executed: {node_name}") # debug code
485
+ inner_state["agent_logs"].append(f"[Info] node executed]: {node_name}")
486
+
487
+ if node_name == END:
488
+ break
489
+
490
+ #st.write("✅ Final state from LangGraph:") # debug code
491
+ #st.json(state) # debug code
492
+
493
+ # Move to results after processing the entire graph
494
+ st.session_state.step = "results"
495
+ st.rerun()
496
+
497
+
498
+ elif st.session_state.step == "results":
499
+ state = st.session_state.agent_state
500
+
501
+ if st.session_state.escalated:
502
+ st.warning("⚠️ Your case has been assigned to a agent for review.")
503
+ ref = f"{state['application']['customer_id'].upper()}-{datetime.now().strftime('%d%m%y%H%M%S')}"
504
+ state["reference_id"] = ref
505
+ st.markdown(f"**Reference#:** `{ref}`")
506
+ if st.button("⮎ Submit New Request"):
507
+ for k in list(st.session_state.keys()):
508
+ del st.session_state[k]
509
+ st.rerun()
510
+ st.session_state.step = "done"
511
+ st.stop()
512
+
513
+ elif state.get("selected_plan"):
514
+ plan = state["selected_plan"]
515
+ st.success(f"✅ Proposed Plan: **{plan}**")
516
+ st.markdown(f"**{hardship_plans[plan]['description']}**")
517
+
518
+ #Suggestion (Optional)
519
+ #ranked = sorted(state.get("eligible_plans", []), key=lambda p: hardship_plans[p]["risk_score"])
520
+ #if plan in ranked and len(ranked) > 1:
521
+ # alternatives = [p for p in ranked if p != plan]
522
+ # second_best = alternatives[0]
523
+ # st.info(f"💡 You might also consider: **{second_best}** — {hardship_plans[second_best]['description']}")
524
+
525
+ submitted = state["submitted_feedbacks"]
526
+ remaining = {"Accept", "I can only afford half", "Suggest alternative"} - submitted
527
+
528
+ if "Accept" in submitted:
529
+ st.success("Thank you for your response.")
530
+ st.success(f"You have accepted the proposed plan: **{plan}**")
531
+ ref = state.get("reference_id")
532
+ if ref:
533
+ st.markdown(f"**Reference#:** `{ref}`")
534
+ if st.button("🔁 Submit New Request"):
535
+ for k in list(st.session_state.keys()):
536
+ del st.session_state[k]
537
+ st.rerun()
538
+ st.session_state.step = "done"
539
+ st.stop()
540
+
541
+ # Show feedback options only if not already accepted
542
+ options = [opt for opt in ["Accept", "I can only afford half", "Suggest alternative"] if opt in remaining] #options = list(remaining)
543
+ feedback = st.radio("Feedback (choose one):", options, key="feedback_choice")
544
+
545
+ if st.button("Submit Feedback"):
546
+ submitted.add(feedback)
547
+ state["submitted_feedbacks"] = submitted
548
+ state["agent_logs"].append(f"[Feedback] User selected: {feedback}")
549
+
550
+ if feedback == "Accept":
551
+ state["handled"] = True
552
+ ref = f"{state['application']['customer_id'].upper()}-{datetime.now().strftime('%d%m%y%H%M%S')}"
553
+ state["reference_id"] = ref
554
+ st.session_state.step = "done"
555
+ st.rerun()
556
+
557
+
558
+ elif "half" in feedback.lower():
559
+ state["agent_logs"].append("[Feedback Action] User selected 'half'. Reducing income and rerunning reason_and_rank")
560
+ state["application"]["income"] = state["application"]["income"] / 2 # Adjust income
561
+ state["feedback"] = "half"
562
+ state["handled"] = False
563
+ state.pop("selected_plan", None) # Force recomputation
564
+ state.pop("matched_case_df", None) #clear matched case display (but keep history)
565
+ state["current_node"] = "reason_and_rank"
566
+ st.session_state.step = "processing"
567
+ st.rerun()
568
+
569
+ elif feedback == "Suggest alternative":
570
+ state["feedback"] = "wants_alternative"
571
+ state["handled"] = False
572
+ state["current_node"] = "reason_and_rank"
573
+ state["agent_logs"].append("[Feedback Action] User requested alternative. Clearing selected_plan and rerunning reason_and_rank")
574
+ state.pop("selected_plan", None) #clear old plan so it doesn't get reused
575
+ state.pop("matched_case_df", None) # clear matched case display (but keep history)
576
+ st.session_state.step = "processing"
577
+ st.rerun()
578
+ else:
579
+ st.warning("⚠️ No plan could be proposed.")
580
+ st.session_state.step = "done"
581
+ st.rerun()
582
+
583
+ elif st.session_state.step == "done":
584
+ state = st.session_state.agent_state
585
+ #st.success("🎉 Thank you for your response.")
586
+ st.success("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/2KNwWbE-GjSYTOpfcA0N3.png) Thank you for your response.")
587
+ if state.get("selected_plan"):
588
+ st.markdown(f"**You have accepted the proposed plan:** `{state['selected_plan']}`")
589
+ if state.get("reference_id"):
590
+ st.markdown(f"**Reference#:** `{state['reference_id']}`")
591
+ #if st.button("🔁 Submit New Request"):
592
+ if st.button("🔂 Submit New Request"):
593
+ for k in list(st.session_state.keys()):
594
+ del st.session_state[k]
595
+ st.rerun()
596
+
597
+ # Show Agent Logs only after user has submitted their details
598
+ if st.session_state.step in {"processing", "results", "done"}:
599
+ #if "agent_state" in st.session_state and st.session_state.agent_state: OR #if st.session_state.agent_logs:
600
+ st.markdown("---")
601
+ #st.markdown("### 📜 Agent Logs")
602
+ st.markdown("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/-h1QdYhvBfI-15wWmD6iT.png) Agent Logs")
603
+ logs = st.session_state.agent_state["agent_logs"]
604
+ for log in logs:
605
+ st.markdown(f"- {log}")
606
+ st.markdown("---")
607
+
608
+ # ----- Matched Cases from Long‑Term Memory -----
609
+ if st.session_state.ltm_match_history:
610
+ #st.markdown("### 🧠 Matched Cases from Long‑Term Memory")
611
+ st.markdown("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/LogBa8z0GRqlmfMKEGCCG.png) Matched Cases from Long‑Term Memory")
612
+ for idx, df in enumerate(st.session_state.ltm_match_history, 1):
613
+ st.markdown(f"#### Match {idx}")
614
+ st.table(df)
615
+ else:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
616
  st.info("No similar cases found in long‑term memory.")
src/afhtp_v0.0.py DELETED
@@ -1,616 +0,0 @@
1
- import streamlit as st
2
- import pandas as pd
3
- import numpy as np
4
- import faiss
5
- import torch
6
- import time
7
- from datetime import datetime
8
- from sentence_transformers import SentenceTransformer
9
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
10
- from langgraph.graph import StateGraph, END
11
- from langgraph.graph.state import CompiledStateGraph
12
- from typing import Dict, Any, Optional, TypedDict
13
-
14
- # ---- SETUP ----
15
- st.set_page_config(page_title="AFTP Hardship Planner", layout="centered")
16
- #st.title("🏛️ AFTP Hardship Treatment Planner")
17
- st.subheader("![image/png](https://cdn-uploads.huggingface.co/production/uploads/688abc51f5077dea074b2f8d/dSu3n5I9OyaIQtNWP6kt5.png) Autonomous Financial Hardship Treatment Planner")
18
-
19
- # ---- LLM LOAD ----
20
- @st.cache_resource
21
- def load_llm():
22
- model_id = "google/flan-t5-small"
23
- tokenizer = AutoTokenizer.from_pretrained(model_id)
24
- model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
25
- return model, tokenizer
26
-
27
- llm_model, llm_tokenizer = load_llm()
28
- llm_model.eval()
29
-
30
- # ---- VECTOR STORE ----
31
- encoder = SentenceTransformer("all-MiniLM-L6-v2")
32
- index = faiss.IndexFlatL2(384)
33
- vector_store = {}
34
-
35
- def build_embedding(app: dict) -> str:
36
- return f"{app['hardship_reason']} income:{app['income']} expenses:{app['expenses']}"
37
-
38
- def store_context(customer_id: str, embedding_text: str, context: dict):
39
- vector = encoder.encode([embedding_text])[0]
40
- index.add(np.array([vector]))
41
- vector_store[customer_id] = {"vector": vector, "context": context}
42
-
43
- ## Sample Hardship treatment plans Prepopulation
44
- def prepopulate_sample_cases():
45
- """
46
- Prepopulate vector store with realistic historical cases for similarity matching.
47
- """
48
- sample_cases = [
49
- {"customer_id": "C100", "app": {"hardship_reason": "Job Loss", "income": 1500,"expenses": 2200}, "context": {"plan": "3-month deferral",
50
- "status": "completed"}},
51
- {"customer_id": "C101", "app": {"hardship_reason": "Natural Disaster", "income": 1800, "expenses": 2100}, "context": {"plan": "interest reduction",
52
- "status": "completed"}},
53
- {"customer_id": "C102", "app": {"hardship_reason": "Medical", "income": 2000, "expenses": 2500}, "context": {"plan": "partial payment suspension",
54
- "status": "completed"}},
55
- {"customer_id": "C103", "app": {"hardship_reason": "Job Loss", "income": 1400, "expenses": 2000}, "context": {"plan": "3-month deferral",
56
- "status": "completed"}},
57
- {"customer_id": "C104", "app": {"hardship_reason": "Natural Disaster", "income": 2500, "expenses": 2600}, "context": {"plan": "payment extension",
58
- "status": "completed"}}
59
- ]
60
-
61
- for case in sample_cases:
62
- embedding_text = build_embedding(case["app"])
63
- store_context(case["customer_id"], embedding_text, case["context"])
64
-
65
- if len(vector_store) == 0: #avoid repopulating on every rerun,
66
- prepopulate_sample_cases()
67
-
68
-
69
- # ---- Hardcoded Plans ----
70
- hardship_plans = {
71
- "3-month deferral": {"description": "Suspend payments for 3 months.", "risk_score": 2},
72
- "partial payment suspension": {"description": "Pay only 50% for 3 months.", "risk_score": 3},
73
- "interest reduction": {"description": "Reduce interest by 25% for 6 months.", "risk_score": 1},
74
- "payment extension": {"description": "Extend term by 12 months.", "risk_score": 4},
75
- "restructure repayment": {"description": "Restructure repayment terms based on income profile.", "risk_score": 3},
76
- "defer interest only": {"description": "Pay only interest for 3 months.", "risk_score": 2},
77
- "grace period": {"description": "Grace period of 1 month with no payment.", "risk_score": 1}
78
- }
79
-
80
- # ---- Sample Case Workers ----
81
- case_worker_df = pd.DataFrame([
82
- {"name": "Peter Swift", "plan": "3-month deferral", "experience_years": 5, "on_leave": False},
83
- {"name": "Anthony Mackay", "plan": "interest reduction", "experience_years": 7, "on_leave": False},
84
- {"name": "Sara Keeves", "plan": "partial payment suspension", "experience_years": 4, "on_leave": True},
85
- {"name": "Lara Brent", "plan": "partial payment suspension", "experience_years": 5, "on_leave": False},
86
- {"name": "David Ray", "plan": "payment extension", "experience_years": 6, "on_leave": False},
87
- ])
88
-
89
- def assign_case_worker(plan: str):
90
- available = case_worker_df[(case_worker_df["plan"] == plan) & (~case_worker_df["on_leave"])]
91
- if not available.empty:
92
- return available.sample(1).iloc[0]
93
- return None
94
-
95
- def assign_human_caseworker():
96
- available = case_worker_df[(case_worker_df["experience_years"] >= 5) & (~case_worker_df["on_leave"])]
97
- if not available.empty:
98
- return available.sample(1).iloc[0]
99
- return None
100
-
101
- # ---- AgentState TypedDict ----
102
- class AgentState(TypedDict):
103
- application: Optional[Dict[str, Any]]
104
- selected_plan: Optional[str]
105
- escalated: bool
106
- handled: bool
107
- matched_case_df: Optional[pd.DataFrame]
108
- ltm_match_history: list
109
- feedback: Optional[str]
110
- submitted_feedbacks: set
111
- reference_id: Optional[str]
112
- agent_logs: list
113
- current_node: str
114
- eligible_plans: Optional[list]
115
- previous_plans: list
116
-
117
- # ---- Eligibility and Matching Functions ----
118
- def check_eligibility(app: Dict) -> list:
119
- # Debug inside eligibility
120
- 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']}")
121
- if app["hardship_reason"] == "Job Loss" and app["income"] < app["expenses"]:
122
- return ["3-month deferral", "partial payment suspension"]
123
- return ["payment extension", "interest reduction"]
124
-
125
- def check_proactive_escalation(app: Dict) -> bool:
126
- return app["history"]["late_payments"] > 3 or app.get("flagged_abuse", False)
127
-
128
- def match_from_ltm(app: Dict[str, Any]) -> Optional[pd.DataFrame]:
129
- if len(vector_store) == 0:
130
- return None
131
-
132
- query_vector = encoder.encode([build_embedding(app)])[0]
133
- similarity_threshold = 10.0
134
- D, I = index.search(np.array([query_vector]), k=1)
135
- distance = D[0][0]
136
-
137
- if distance <= similarity_threshold:
138
- match_id = list(vector_store.keys())[I[0][0]]
139
- matched_context = vector_store[match_id]["context"]
140
- matched_df = pd.DataFrame([{
141
- "Customer ID": match_id,
142
- "Plan": matched_context["plan"],
143
- "Status": matched_context.get("status", "N/A")
144
- }])
145
- return matched_df
146
- else:
147
- st.session_state.agent_state["agent_logs"].append(f"[Debug] No similar case found. Distance: {distance:.2f}")
148
- return None
149
-
150
- # ---- Node Functions ----
151
- # Hardcoded, safe validate() , this temporary fixed version that hard-forces the downstream steps unless escalation is needed:
152
- def validate(state: AgentState) -> AgentState:
153
- logs = state["agent_logs"]
154
- logs.append("[Node] Entered validate")
155
- app = state["application"]
156
- state["current_node"] = "validate"
157
-
158
- # Only escalate if absolutely needed
159
- if check_proactive_escalation(app):
160
- logs.append("[Info] Escalation triggered in validate()")
161
- state["escalated"] = True
162
- worker = assign_human_caseworker()
163
- if worker is not None:
164
- logs.append(f"[Escalation] Assigned to case worker: {worker['name']}")
165
- else:
166
- logs.append("[Escalation] No available senior case workers. Case queued.")
167
- state["handled"] = True
168
- else:
169
- logs.append("[Info] No escalation triggered in validate()")
170
- state["escalated"] = False
171
- state["handled"] = False # FORCE this
172
- logs.append(f"[Info] Post validate() state: escalated={state['escalated']}, handled={state['handled']}") # debug
173
- return state
174
-
175
- def reason_and_rank(state: AgentState) -> AgentState:
176
- logs = state["agent_logs"]
177
- logs.append("[Node] Entered reason_and_rank")
178
-
179
- app = state["application"]
180
- state["current_node"] = "reason_and_rank"
181
-
182
- # 1. Check eligibility
183
- eligible = check_eligibility(app)
184
- state["eligible_plans"] = eligible
185
-
186
- if eligible:
187
- top_plan = sorted(eligible, key=lambda p: hardship_plans[p]["risk_score"])[0]
188
- desc = hardship_plans[top_plan]["description"]
189
- logs.append(f"[Node: reason_and_rank] Eligible Plan: {top_plan} → {desc}")
190
- else:
191
- logs.append("[Node: reason_and_rank] No eligible plans found.")
192
-
193
- # 2. Try to match from Long-Term Memory (LTM)
194
- matched_df = match_from_ltm(app)
195
- if matched_df is not None:
196
- matched_plan = matched_df.iloc[0]["Plan"]
197
-
198
- # Check if user already saw this LTM plan
199
- if matched_plan not in state.get("previous_plans", []):
200
- logs.append(f"[LTM Match] Found matching plan from long-term memory: {matched_plan}")
201
- state["selected_plan"] = matched_plan
202
- state.setdefault("previous_plans", []).append(matched_plan)
203
- state["matched_case_df"] = matched_df
204
- state.setdefault("ltm_match_history", []).append(matched_df.copy()) # append the matched_df
205
- logs.append(f"[Plan Selection] Selected Plan from LTM: {matched_plan}")
206
- return state
207
- else:
208
- logs.append(f"[LTM Match] Skipped LTM plan {matched_plan} (already proposed)")
209
-
210
- # 3. No LTM match – proceed with ranking eligible hardcoded plans
211
- if not eligible:
212
- state["escalated"] = True
213
- state["handled"] = True
214
- logs.append("[Warning] No eligible plans found. Escalating to human agent.")
215
- return state
216
-
217
- # 4. Rank and pick plan from eligible ones
218
- ranked = sorted(eligible, key=lambda p: hardship_plans[p]["risk_score"])
219
- previous = state.get("previous_plans", [])
220
- ranked_filtered = [p for p in ranked if p not in previous]
221
-
222
- if not ranked_filtered:
223
- logs.append("[Plan Selection] No new plans left after filtering. Escalating.")
224
- state["escalated"] = True
225
- state["handled"] = True
226
- return state
227
-
228
- selected_plan = ranked_filtered[0]
229
- state["selected_plan"] = selected_plan
230
- state.setdefault("previous_plans", []).append(selected_plan)
231
-
232
- logs.append(f"[Plan Selection] Selected new plan: {selected_plan}")
233
-
234
- worker = assign_case_worker(selected_plan)
235
- if worker is not None:
236
- logs.append(f"[CRM] Assigned to {worker['name']} for plan: {selected_plan}")
237
- else:
238
- logs.append(f"[CRM] No available case worker for plan: {selected_plan}")
239
-
240
- return state
241
-
242
-
243
- def take_action(state: AgentState) -> AgentState:
244
- logs = state["agent_logs"]
245
- logs.append("[Node] Entered take_action()")
246
- app = state["application"]
247
- plan = state["selected_plan"]
248
- state["current_node"] = "take_action"
249
-
250
- # Defensive check in case already assigned earlier
251
- if "crm_logged" not in state:
252
- worker = assign_case_worker(plan)
253
- if worker is not None:
254
- logs.append(f"[CRM] Logged case for {app['name']} - Plan: {plan} → Assigned to {worker['name']}")
255
- else:
256
- logs.append(f"[CRM] No available case worker for plan: {plan}")
257
- state["crm_logged"] = True # prevent future re-logging
258
-
259
- # Store the decision in long-term memory (LTM)
260
- store_context(app["customer_id"], build_embedding(app), {"plan": plan, "status": "active"})
261
-
262
- state["handled"] = True
263
- return state
264
-
265
-
266
- # ---- Decide Next Node ----
267
- def decide_next_node(state: AgentState) -> str:
268
- logs = state["agent_logs"]
269
- current_node = state["current_node"]
270
- app = state.get("application", {})
271
- history = app.get("history", {})
272
- logs.append(f"[Router] At node: {current_node}") # debug code
273
- logs.append(f"[Info] decide_next_node() called at node: {current_node}") # debug code
274
-
275
- if state["handled"] or state["escalated"]:
276
- logs.append("[Router] Already handled or escalated - routing to END") # debug code
277
- return END
278
-
279
- # Define valid next nodes
280
- valid_next_nodes = {
281
- "validate": ["reason_and_rank", END],
282
- "reason_and_rank": ["take_action", END],
283
- "take_action": [END]
284
- }.get(current_node, [END])
285
-
286
- # Few-shot prompt
287
- few_shot = """
288
- Current Node: validate, flagged_abuse=False, selected_plan=None, handled=False → reason_and_rank
289
- Current Node: reason_and_rank, selected_plan=interest reduction, handled=False → take_action
290
- Current Node: take_action, handled=True → END
291
- Current Node: validate, escalated=True, handled=True → END
292
- """
293
-
294
- prompt = f"""
295
- You are an AI agent orchestrating a financial hardship planner.
296
- Given the current node and customer data, choose the next step in the process.
297
- {few_shot}
298
- Customer Info:
299
- - Name: {app.get('name', 'Unknown')}
300
- - Hardship Reason: {app.get('hardship_reason', 'Unknown')}
301
- - Income: {app.get('income', 'N/A')}
302
- - Expenses: {app.get('expenses', 'N/A')}
303
- - Late Payments: {history.get('late_payments', 0)}
304
- - Flagged Abuse: {app.get('flagged_abuse', False)}
305
- - Escalated: {state.get('escalated', False)}
306
- - Handled: {state.get('handled', False)}
307
- - Selected Plan: {state.get('selected_plan')}
308
- - Eligible Plans: {state.get('eligible_plans', [])}
309
- - Current Node: {current_node}
310
- Next: {', '.join(valid_next_nodes)}
311
- """
312
-
313
- with torch.no_grad():
314
- start = time.time()
315
- input_ids = llm_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512).input_ids
316
- outputs = llm_model.generate(input_ids=input_ids, max_new_tokens=10, do_sample=False)
317
- end = time.time()
318
- response = llm_tokenizer.decode(outputs[0], skip_special_tokens=True).strip().lower()
319
- response = response.split()[0] # Only take first word to normalize
320
- logs.append(f"[Router] LLM output: {response}") # debug code
321
- #st.markdown(f"⏲ **LLM inference time:** `{end - start:.2f} seconds`")
322
- st.markdown(f"⏳ **LLM inference time:** `{end - start:.2f} seconds`")
323
-
324
- if response not in valid_next_nodes:
325
- logs.append(f"[Router Warning] Invalid LLM output '{response}', defaulting to {valid_next_nodes[0]}") # debug code
326
- return valid_next_nodes[0]
327
-
328
- if response == "end" or state["escalated"]:
329
- logs.append("[Router] Routing to END due to LLM output or escalation.")
330
- return END
331
-
332
- if state["selected_plan"] is None and response == "take_action":
333
- logs.append("[Router Warning] LLM tried to skip reasoning. Forcing reason_and_rank.") # debug code
334
- return "reason_and_rank"
335
-
336
- logs.append(f"[Router] Moving from {current_node} to {response}")
337
- return response
338
-
339
- # ---- LangGraph Workflow Setup ----
340
- workflow = StateGraph(AgentState)
341
- workflow.add_node("validate", validate)
342
- workflow.add_node("reason_and_rank", reason_and_rank)
343
- workflow.add_node("take_action", take_action)
344
-
345
- workflow.add_conditional_edges(
346
- "validate",
347
- decide_next_node,
348
- {
349
- "reason_and_rank": "reason_and_rank",
350
- END: END
351
- }
352
- )
353
- workflow.add_conditional_edges(
354
- "reason_and_rank",
355
- decide_next_node,
356
- {
357
- "take_action": "take_action",
358
- END: END
359
- }
360
- )
361
- workflow.add_conditional_edges(
362
- "take_action",
363
- decide_next_node,
364
- {
365
- END: END
366
- }
367
- )
368
- workflow.set_entry_point("validate")
369
- graph: CompiledStateGraph = workflow.compile()
370
-
371
- # ---- Initialize session state ----
372
- def init_session():
373
- if "step" not in st.session_state:
374
- st.session_state.step = "form"
375
- if "application" not in st.session_state:
376
- st.session_state.application = None
377
- if "plan_accepted" not in st.session_state:
378
- st.session_state.plan_accepted = False
379
- if "escalated" not in st.session_state:
380
- st.session_state.escalated = False
381
- if "handled" not in st.session_state:
382
- st.session_state.handled = False
383
- if "matched_case_df" not in st.session_state:
384
- st.session_state.matched_case_df = None
385
- if "feedback" not in st.session_state:
386
- st.session_state.feedback = None
387
- if "submitted_feedbacks" not in st.session_state:
388
- st.session_state.submitted_feedbacks = set()
389
- if "reference_id" not in st.session_state:
390
- st.session_state.reference_id = None
391
- if "agent_logs" not in st.session_state:
392
- st.session_state.agent_logs = []
393
- if "previous_plans" not in st.session_state:
394
- st.session_state.previous_plans = []
395
- if "agent_state" not in st.session_state or st.session_state.agent_state is None:
396
- st.session_state.agent_state = AgentState(
397
- application=None,
398
- selected_plan=None,
399
- escalated=False,
400
- handled=False,
401
- matched_case_df=None,
402
- ltm_match_history=[],
403
- feedback=None,
404
- submitted_feedbacks=set(),
405
- reference_id=None,
406
- agent_logs=[],
407
- current_node="validate",
408
- eligible_plans=None,
409
- previous_plans=[]
410
- )
411
-
412
- init_session()
413
-
414
- # ---- UI and workflow execution ----
415
- if st.session_state.step == "form":
416
- with st.form("user_input"):
417
- #st.subheader("📝 Enter Your Details")
418
- st.subheader("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/6Om0nXTbrf8Mew4zJ7Gsh.png) Enter Your Details")
419
- name = st.text_input("First Name")
420
- customer_id = st.text_input("Customer ID")
421
- account_type = st.selectbox("Account Type", ["mortgage", "credit card", "personal loan"])
422
- hardship_reason = st.selectbox("Reason for Hardship", ["Job Loss", "Medical", "Natural Disaster"])
423
- income = st.number_input("Monthly Income", min_value=0.0)
424
- expenses = st.number_input("Monthly Expenses", min_value=0.0)
425
- late_payments = st.number_input("Late Payments (last 12 months)", min_value=0, step=1)
426
- flagged_abuse = st.radio("Previously defaulted or rejected?", ["No", "Yes"]) == "Yes"
427
- submitted = st.form_submit_button("Submit")
428
-
429
- if submitted:
430
- if not name.strip():
431
- st.warning("⚠️ Please enter your name.")
432
- elif not customer_id.strip():
433
- st.warning("⚠️ Please enter your customer ID.")
434
- elif income == 0.0:
435
- st.warning("⚠️ Please enter your income.")
436
- elif expenses == 0.0:
437
- st.warning("⚠️ Please enter your expenses.")
438
- else:
439
- st.session_state.application = {
440
- "name": name.strip(),
441
- "account_type": account_type,
442
- "hardship_reason": hardship_reason,
443
- "income": income,
444
- "expenses": expenses,
445
- "history": {"late_payments": late_payments},
446
- "flagged_abuse": flagged_abuse,
447
- "customer_id": customer_id,
448
- }
449
- st.session_state.agent_state["application"] = st.session_state.application
450
- st.session_state.agent_state["current_node"] = "validate"
451
- st.session_state.agent_state["selected_plan"] = None
452
- st.session_state.agent_state["escalated"] = False
453
- st.session_state.agent_state["handled"] = False
454
- st.session_state.agent_state["matched_case_df"] = None
455
- st.session_state.agent_state["feedback"] = None
456
- st.session_state.agent_state["eligible_plans"] = None
457
- st.session_state.agent_state["submitted_feedbacks"] = set()
458
- st.session_state.agent_state["agent_logs"] = []
459
- st.session_state.step = "processing"
460
- st.rerun()
461
-
462
- elif st.session_state.step == "processing":
463
- #st.info("📡 Processing your request...")
464
- st.info("![image/gif](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/8tQqf9gWdbl9Sb3bO6O6C.gif) Processing your request...")
465
- state = st.session_state.agent_state
466
- logs = state["agent_logs"] # This line is required
467
- logs.append("[Node] Processing plan recommendation...")
468
-
469
- # Run the graph streaming to execute the workflow nodes including reason_and_rank and take_action
470
- for updated_state in graph.stream(state):
471
- node_name, inner_state = list(updated_state.items())[0]
472
-
473
- # Update session state with the new state
474
- st.session_state.agent_state = inner_state
475
- st.session_state.agent_logs = inner_state.get("agent_logs", [])
476
- st.session_state.ltm_match_history = inner_state.get("ltm_match_history", [])
477
- st.session_state.escalated = inner_state.get("escalated", False)
478
- st.session_state.handled = inner_state.get("handled", False)
479
- st.session_state.matched_case_df = inner_state.get("matched_case_df")
480
- st.session_state.reference_id = inner_state.get("reference_id")
481
-
482
- state = inner_state # Feed updated state back to next iteration
483
-
484
- #inner_state["agent_logs"].append(f"[Debug] Node executed: {node_name}") # debug code
485
- inner_state["agent_logs"].append(f"[Info] node executed]: {node_name}")
486
-
487
- if node_name == END:
488
- break
489
-
490
- #st.write("✅ Final state from LangGraph:") # debug code
491
- #st.json(state) # debug code
492
-
493
- # Move to results after processing the entire graph
494
- st.session_state.step = "results"
495
- st.rerun()
496
-
497
-
498
- elif st.session_state.step == "results":
499
- state = st.session_state.agent_state
500
-
501
- if st.session_state.escalated:
502
- st.warning("⚠️ Your case has been assigned to a agent for review.")
503
- ref = f"{state['application']['customer_id'].upper()}-{datetime.now().strftime('%d%m%y%H%M%S')}"
504
- state["reference_id"] = ref
505
- st.markdown(f"**Reference#:** `{ref}`")
506
- if st.button("⮎ Continue"):
507
- for k in list(st.session_state.keys()):
508
- del st.session_state[k]
509
- st.rerun()
510
- st.session_state.step = "done"
511
- st.stop()
512
-
513
- elif state.get("selected_plan"):
514
- plan = state["selected_plan"]
515
- st.success(f"✅ Proposed Plan: **{plan}**")
516
- st.markdown(f"**{hardship_plans[plan]['description']}**")
517
-
518
- #Suggestion (Optional)
519
- #ranked = sorted(state.get("eligible_plans", []), key=lambda p: hardship_plans[p]["risk_score"])
520
- #if plan in ranked and len(ranked) > 1:
521
- # alternatives = [p for p in ranked if p != plan]
522
- # second_best = alternatives[0]
523
- # st.info(f"💡 You might also consider: **{second_best}** — {hardship_plans[second_best]['description']}")
524
-
525
- submitted = state["submitted_feedbacks"]
526
- remaining = {"Accept", "I can only afford half", "Suggest alternative"} - submitted
527
-
528
- if "Accept" in submitted:
529
- st.success("Thank you for your response.")
530
- st.success(f"You have accepted the proposed plan: **{plan}**")
531
- ref = state.get("reference_id")
532
- if ref:
533
- st.markdown(f"**Reference#:** `{ref}`")
534
- if st.button("🔁 Submit New Request"):
535
- for k in list(st.session_state.keys()):
536
- del st.session_state[k]
537
- st.rerun()
538
- st.session_state.step = "done"
539
- st.stop()
540
-
541
- # Show feedback options only if not already accepted
542
- options = [opt for opt in ["Accept", "I can only afford half", "Suggest alternative"] if opt in remaining] #options = list(remaining)
543
- feedback = st.radio("Feedback (choose one):", options, key="feedback_choice")
544
-
545
- if st.button("Submit Feedback"):
546
- submitted.add(feedback)
547
- state["submitted_feedbacks"] = submitted
548
- state["agent_logs"].append(f"[Feedback] User selected: {feedback}")
549
-
550
- if feedback == "Accept":
551
- state["handled"] = True
552
- ref = f"{state['application']['customer_id'].upper()}-{datetime.now().strftime('%d%m%y%H%M%S')}"
553
- state["reference_id"] = ref
554
- st.session_state.step = "done"
555
- st.rerun()
556
-
557
-
558
- elif "half" in feedback.lower():
559
- state["agent_logs"].append("[Feedback Action] User selected 'half'. Reducing income and rerunning reason_and_rank")
560
- state["application"]["income"] = state["application"]["income"] / 2 # Adjust income
561
- state["feedback"] = "half"
562
- state["handled"] = False
563
- state.pop("selected_plan", None) # Force recomputation
564
- state.pop("matched_case_df", None) #clear matched case display (but keep history)
565
- state["current_node"] = "reason_and_rank"
566
- st.session_state.step = "processing"
567
- st.rerun()
568
-
569
- elif feedback == "Suggest alternative":
570
- state["feedback"] = "wants_alternative"
571
- state["handled"] = False
572
- state["current_node"] = "reason_and_rank"
573
- state["agent_logs"].append("[Feedback Action] User requested alternative. Clearing selected_plan and rerunning reason_and_rank")
574
- state.pop("selected_plan", None) #clear old plan so it doesn't get reused
575
- state.pop("matched_case_df", None) # clear matched case display (but keep history)
576
- st.session_state.step = "processing"
577
- st.rerun()
578
- else:
579
- st.warning("⚠️ No plan could be proposed.")
580
- st.session_state.step = "done"
581
- st.rerun()
582
-
583
- elif st.session_state.step == "done":
584
- state = st.session_state.agent_state
585
- #st.success("🎉 Thank you for your response.")
586
- st.success("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/2KNwWbE-GjSYTOpfcA0N3.png) Thank you for your response.")
587
- if state.get("selected_plan"):
588
- st.markdown(f"**You have accepted the proposed plan:** `{state['selected_plan']}`")
589
- if state.get("reference_id"):
590
- st.markdown(f"**Reference#:** `{state['reference_id']}`")
591
- #if st.button("🔁 Submit New Request"):
592
- if st.button("🔂 Submit New Request"):
593
- for k in list(st.session_state.keys()):
594
- del st.session_state[k]
595
- st.rerun()
596
-
597
- # Show Agent Logs only after user has submitted their details
598
- if st.session_state.step in {"processing", "results", "done"}:
599
- #if "agent_state" in st.session_state and st.session_state.agent_state: OR #if st.session_state.agent_logs:
600
- st.markdown("---")
601
- #st.markdown("### 📜 Agent Logs")
602
- st.markdown("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/-h1QdYhvBfI-15wWmD6iT.png) Agent Logs")
603
- logs = st.session_state.agent_state["agent_logs"]
604
- for log in logs:
605
- st.markdown(f"- {log}")
606
- st.markdown("---")
607
-
608
- # ----- Matched Cases from Long‑Term Memory -----
609
- if st.session_state.ltm_match_history:
610
- #st.markdown("### 🧠 Matched Cases from Long‑Term Memory")
611
- st.markdown("![image/png](https://cdn-uploads.huggingface.co/production/uploads/6517e1b82b4fffcb41d1ba31/LogBa8z0GRqlmfMKEGCCG.png) Matched Cases from Long‑Term Memory")
612
- for idx, df in enumerate(st.session_state.ltm_match_history, 1):
613
- st.markdown(f"#### Match {idx}")
614
- st.table(df)
615
- else:
616
- st.info("No similar cases found in long‑term memory.")