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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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(" 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(" 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(" 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(" 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(" 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(" 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.")
|