Spaces:
Paused
Paused
Download src/afhtp.py from npkits/afhtp: direct link, hf CLI and curl.
- Browser
- Download file 27.6 kB
-
https://huggingface.co/spaces/npkits/afhtp/resolve/main/src/afhtp.py
- Command line
-
hf download hf://spaces/npkits/afhtp/src/afhtp.py
-
curl -L -o afhtp.py https://huggingface.co/spaces/npkits/afhtp/resolve/main/src/afhtp.py
27.6 kB
| ## version v0.1 | |
| import streamlit as st | |
| from pathlib import Path | |
| import pandas as pd | |
| import numpy as np | |
| import faiss | |
| import torch | |
| import time | |
| from datetime import datetime | |
| from sentence_transformers import SentenceTransformer | |
| from transformers import AutoTokenizer, AutoModelForSeq2SeqLM | |
| from langgraph.graph import StateGraph, END | |
| from langgraph.graph.state import CompiledStateGraph | |
| from typing import Dict, Any, Optional, TypedDict | |
| # ---- SETUP ---- | |
| BASE = Path(__file__).resolve().parent # directory of afhtp.py | |
| doc_path = BASE / "afhtp.md" | |
| # ---- PAGE CONFIG ---- | |
| st.set_page_config(page_title="AFTP Hardship Planner", layout="centered") | |
| st.sidebar.title("🔍 Navigation") | |
| app_mode = st.sidebar.radio("Go to", ["🏛️ AFHTP Planner", "📄 View Documentation"]) | |
| # ---- DOCUMENTATION VIEW ---- | |
| if app_mode == "📄 View Documentation": | |
| if doc_path.is_file(): | |
| with open(doc_path, "r", encoding="utf-8") as f: | |
| markdown_content = f.read() | |
| st.markdown(markdown_content, unsafe_allow_html=True) | |
| else: | |
| st.error("📄 Documentation file 'afhtp.md' not found.") | |
| st.stop() | |
| #st.title("🏛️ AFTP Hardship Treatment Planner") | |
| st.subheader(" Autonomous Financial Hardship Treatment Planner") | |
| # ---- LLM LOAD ---- | |
| def load_llm(): | |
| model_id = "google/flan-t5-small" | |
| tokenizer = AutoTokenizer.from_pretrained(model_id) | |
| model = AutoModelForSeq2SeqLM.from_pretrained(model_id) | |
| return model, tokenizer | |
| llm_model, llm_tokenizer = load_llm() | |
| llm_model.eval() | |
| # ---- VECTOR STORE ---- | |
| encoder = SentenceTransformer("all-MiniLM-L6-v2") | |
| index = faiss.IndexFlatL2(384) | |
| vector_store = {} | |
| def build_embedding(app: dict) -> str: | |
| return f"{app['hardship_reason']} income:{app['income']} expenses:{app['expenses']}" | |
| def store_context(customer_id: str, embedding_text: str, context: dict): | |
| vector = encoder.encode([embedding_text])[0] | |
| index.add(np.array([vector])) | |
| vector_store[customer_id] = {"vector": vector, "context": context} | |
| ## Sample Hardship treatment plans Prepopulation | |
| def prepopulate_sample_cases(): | |
| """ | |
| Prepopulate vector store with realistic historical cases for similarity matching. | |
| """ | |
| sample_cases = [ | |
| {"customer_id": "C100", "app": {"hardship_reason": "Job Loss", "income": 1500,"expenses": 2200}, "context": {"plan": "3-month deferral", | |
| "status": "completed"}}, | |
| {"customer_id": "C101", "app": {"hardship_reason": "Natural Disaster", "income": 1800, "expenses": 2100}, "context": {"plan": "interest reduction", | |
| "status": "completed"}}, | |
| {"customer_id": "C102", "app": {"hardship_reason": "Medical", "income": 2000, "expenses": 2500}, "context": {"plan": "partial payment suspension", | |
| "status": "completed"}}, | |
| {"customer_id": "C103", "app": {"hardship_reason": "Job Loss", "income": 1400, "expenses": 2000}, "context": {"plan": "3-month deferral", | |
| "status": "completed"}}, | |
| {"customer_id": "C104", "app": {"hardship_reason": "Natural Disaster", "income": 2500, "expenses": 2600}, "context": {"plan": "payment extension", | |
| "status": "completed"}} | |
| ] | |
| for case in sample_cases: | |
| embedding_text = build_embedding(case["app"]) | |
| store_context(case["customer_id"], embedding_text, case["context"]) | |
| if len(vector_store) == 0: #avoid repopulating on every rerun, | |
| prepopulate_sample_cases() | |
| # ---- Hardcoded Plans ---- | |
| hardship_plans = { | |
| "3-month deferral": {"description": "Suspend payments for 3 months.", "risk_score": 2}, | |
| "partial payment suspension": {"description": "Pay only 50% for 3 months.", "risk_score": 3}, | |
| "interest reduction": {"description": "Reduce interest by 25% for 6 months.", "risk_score": 1}, | |
| "payment extension": {"description": "Extend term by 12 months.", "risk_score": 4}, | |
| "restructure repayment": {"description": "Restructure repayment terms based on income profile.", "risk_score": 3}, | |
| "defer interest only": {"description": "Pay only interest for 3 months.", "risk_score": 2}, | |
| "grace period": {"description": "Grace period of 1 month with no payment.", "risk_score": 1} | |
| } | |
| # ---- Sample Case Workers ---- | |
| case_worker_df = pd.DataFrame([ | |
| {"name": "Peter Swift", "plan": "3-month deferral", "experience_years": 5, "on_leave": False}, | |
| {"name": "Anthony Mackay", "plan": "interest reduction", "experience_years": 7, "on_leave": False}, | |
| {"name": "Sara Keeves", "plan": "partial payment suspension", "experience_years": 4, "on_leave": True}, | |
| {"name": "Lara Brent", "plan": "partial payment suspension", "experience_years": 5, "on_leave": False}, | |
| {"name": "David Ray", "plan": "payment extension", "experience_years": 6, "on_leave": False}, | |
| ]) | |
| def assign_case_worker(plan: str): | |
| available = case_worker_df[(case_worker_df["plan"] == plan) & (~case_worker_df["on_leave"])] | |
| if not available.empty: | |
| return available.sample(1).iloc[0] | |
| return None | |
| def assign_human_caseworker(): | |
| available = case_worker_df[(case_worker_df["experience_years"] >= 5) & (~case_worker_df["on_leave"])] | |
| if not available.empty: | |
| return available.sample(1).iloc[0] | |
| return None | |
| # ---- AgentState TypedDict ---- | |
| class AgentState(TypedDict): | |
| application: Optional[Dict[str, Any]] | |
| selected_plan: Optional[str] | |
| escalated: bool | |
| handled: bool | |
| matched_case_df: Optional[pd.DataFrame] | |
| ltm_match_history: list | |
| feedback: Optional[str] | |
| submitted_feedbacks: set | |
| reference_id: Optional[str] | |
| agent_logs: list | |
| current_node: str | |
| eligible_plans: Optional[list] | |
| previous_plans: list | |
| # ---- Eligibility and Matching Functions ---- | |
| def check_eligibility(app: Dict) -> list: | |
| # Debug inside eligibility | |
| 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']}") | |
| if app["hardship_reason"] == "Job Loss" and app["income"] < app["expenses"]: | |
| return ["3-month deferral", "partial payment suspension"] | |
| return ["payment extension", "interest reduction"] | |
| def check_proactive_escalation(app: Dict) -> bool: | |
| return app["history"]["late_payments"] > 3 or app.get("flagged_abuse", False) | |
| def match_from_ltm(app: Dict[str, Any]) -> Optional[pd.DataFrame]: | |
| if len(vector_store) == 0: | |
| return None | |
| query_vector = encoder.encode([build_embedding(app)])[0] | |
| similarity_threshold = 10.0 | |
| D, I = index.search(np.array([query_vector]), k=1) | |
| distance = D[0][0] | |
| if distance <= similarity_threshold: | |
| match_id = list(vector_store.keys())[I[0][0]] | |
| matched_context = vector_store[match_id]["context"] | |
| matched_df = pd.DataFrame([{ | |
| "Customer ID": match_id, | |
| "Plan": matched_context["plan"], | |
| "Status": matched_context.get("status", "N/A") | |
| }]) | |
| return matched_df | |
| else: | |
| st.session_state.agent_state["agent_logs"].append(f"[Debug] No similar case found. Distance: {distance:.2f}") | |
| return None | |
| # ---- Node Functions ---- | |
| # Hardcoded, safe validate() , this temporary fixed version that hard-forces the downstream steps unless escalation is needed: | |
| def validate(state: AgentState) -> AgentState: | |
| logs = state["agent_logs"] | |
| logs.append("[Node] Entered validate") | |
| app = state["application"] | |
| state["current_node"] = "validate" | |
| # Only escalate if absolutely needed | |
| if check_proactive_escalation(app): | |
| logs.append("[Info] Escalation triggered in validate()") | |
| state["escalated"] = True | |
| worker = assign_human_caseworker() | |
| if worker is not None: | |
| logs.append(f"[Escalation] Assigned to case worker: {worker['name']}") | |
| else: | |
| logs.append("[Escalation] No available senior case workers. Case queued.") | |
| state["handled"] = True | |
| else: | |
| logs.append("[Info] No escalation triggered in validate()") | |
| state["escalated"] = False | |
| state["handled"] = False # FORCE this | |
| logs.append(f"[Info] Post validate() state: escalated={state['escalated']}, handled={state['handled']}") # debug | |
| return state | |
| def reason_and_rank(state: AgentState) -> AgentState: | |
| logs = state["agent_logs"] | |
| logs.append("[Node] Entered reason_and_rank") | |
| app = state["application"] | |
| state["current_node"] = "reason_and_rank" | |
| # 1. Check eligibility | |
| eligible = check_eligibility(app) | |
| state["eligible_plans"] = eligible | |
| if eligible: | |
| top_plan = sorted(eligible, key=lambda p: hardship_plans[p]["risk_score"])[0] | |
| desc = hardship_plans[top_plan]["description"] | |
| logs.append(f"[Node: reason_and_rank] Eligible Plan: {top_plan} → {desc}") | |
| else: | |
| logs.append("[Node: reason_and_rank] No eligible plans found.") | |
| # 2. Try to match from Long-Term Memory (LTM) | |
| matched_df = match_from_ltm(app) | |
| if matched_df is not None: | |
| matched_plan = matched_df.iloc[0]["Plan"] | |
| # Check if user already saw this LTM plan | |
| if matched_plan not in state.get("previous_plans", []): | |
| logs.append(f"[LTM Match] Found matching plan from long-term memory: {matched_plan}") | |
| state["selected_plan"] = matched_plan | |
| state.setdefault("previous_plans", []).append(matched_plan) | |
| state["matched_case_df"] = matched_df | |
| state.setdefault("ltm_match_history", []).append(matched_df.copy()) # append the matched_df | |
| logs.append(f"[Plan Selection] Selected Plan from LTM: {matched_plan}") | |
| return state | |
| else: | |
| logs.append(f"[LTM Match] Skipped LTM plan {matched_plan} (already proposed)") | |
| # 3. No LTM match – proceed with ranking eligible hardcoded plans | |
| if not eligible: | |
| state["escalated"] = True | |
| state["handled"] = True | |
| logs.append("[Warning] No eligible plans found. Escalating to human agent.") | |
| return state | |
| # 4. Rank and pick plan from eligible ones | |
| ranked = sorted(eligible, key=lambda p: hardship_plans[p]["risk_score"]) | |
| previous = state.get("previous_plans", []) | |
| ranked_filtered = [p for p in ranked if p not in previous] | |
| if not ranked_filtered: | |
| logs.append("[Plan Selection] No new plans left after filtering. Escalating.") | |
| state["escalated"] = True | |
| state["handled"] = True | |
| return state | |
| selected_plan = ranked_filtered[0] | |
| state["selected_plan"] = selected_plan | |
| state.setdefault("previous_plans", []).append(selected_plan) | |
| logs.append(f"[Plan Selection] Selected new plan: {selected_plan}") | |
| worker = assign_case_worker(selected_plan) | |
| if worker is not None: | |
| logs.append(f"[CRM] Assigned to {worker['name']} for plan: {selected_plan}") | |
| else: | |
| logs.append(f"[CRM] No available case worker for plan: {selected_plan}") | |
| return state | |
| def take_action(state: AgentState) -> AgentState: | |
| logs = state["agent_logs"] | |
| logs.append("[Node] Entered take_action()") | |
| app = state["application"] | |
| plan = state["selected_plan"] | |
| state["current_node"] = "take_action" | |
| # Defensive check in case already assigned earlier | |
| if "crm_logged" not in state: | |
| worker = assign_case_worker(plan) | |
| if worker is not None: | |
| logs.append(f"[CRM] Logged case for {app['name']} - Plan: {plan} → Assigned to {worker['name']}") | |
| else: | |
| logs.append(f"[CRM] No available case worker for plan: {plan}") | |
| state["crm_logged"] = True # prevent future re-logging | |
| # Store the decision in long-term memory (LTM) | |
| store_context(app["customer_id"], build_embedding(app), {"plan": plan, "status": "active"}) | |
| state["handled"] = True | |
| return state | |
| # ---- Decide Next Node ---- | |
| def decide_next_node(state: AgentState) -> str: | |
| logs = state["agent_logs"] | |
| current_node = state["current_node"] | |
| app = state.get("application", {}) | |
| history = app.get("history", {}) | |
| logs.append(f"[Router] At node: {current_node}") # debug code | |
| logs.append(f"[Info] decide_next_node() called at node: {current_node}") # debug code | |
| if state["handled"] or state["escalated"]: | |
| logs.append("[Router] Already handled or escalated - routing to END") # debug code | |
| return END | |
| # Define valid next nodes | |
| valid_next_nodes = { | |
| "validate": ["reason_and_rank", END], | |
| "reason_and_rank": ["take_action", END], | |
| "take_action": [END] | |
| }.get(current_node, [END]) | |
| # Few-shot prompt | |
| few_shot = """ | |
| Current Node: validate, flagged_abuse=False, selected_plan=None, handled=False → reason_and_rank | |
| Current Node: reason_and_rank, selected_plan=interest reduction, handled=False → take_action | |
| Current Node: take_action, handled=True → END | |
| Current Node: validate, escalated=True, handled=True → END | |
| """ | |
| prompt = f""" | |
| You are an AI agent orchestrating a financial hardship planner. | |
| Given the current node and customer data, choose the next step in the process. | |
| {few_shot} | |
| Customer Info: | |
| - Name: {app.get('name', 'Unknown')} | |
| - Hardship Reason: {app.get('hardship_reason', 'Unknown')} | |
| - Income: {app.get('income', 'N/A')} | |
| - Expenses: {app.get('expenses', 'N/A')} | |
| - Late Payments: {history.get('late_payments', 0)} | |
| - Flagged Abuse: {app.get('flagged_abuse', False)} | |
| - Escalated: {state.get('escalated', False)} | |
| - Handled: {state.get('handled', False)} | |
| - Selected Plan: {state.get('selected_plan')} | |
| - Eligible Plans: {state.get('eligible_plans', [])} | |
| - Current Node: {current_node} | |
| Next: {', '.join(valid_next_nodes)} | |
| """ | |
| with torch.no_grad(): | |
| start = time.time() | |
| input_ids = llm_tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512).input_ids | |
| outputs = llm_model.generate(input_ids=input_ids, max_new_tokens=10, do_sample=False) | |
| end = time.time() | |
| response = llm_tokenizer.decode(outputs[0], skip_special_tokens=True).strip().lower() | |
| response = response.split()[0] # Only take first word to normalize | |
| logs.append(f"[Router] LLM output: {response}") # debug code | |
| #st.markdown(f"⏲ **LLM inference time:** `{end - start:.2f} seconds`") | |
| st.markdown(f"⏳ **LLM inference time:** `{end - start:.2f} seconds`") | |
| if response not in valid_next_nodes: | |
| logs.append(f"[Router Warning] Invalid LLM output '{response}', defaulting to {valid_next_nodes[0]}") # debug code | |
| return valid_next_nodes[0] | |
| if response == "end" or state["escalated"]: | |
| logs.append("[Router] Routing to END due to LLM output or escalation.") | |
| return END | |
| if state["selected_plan"] is None and response == "take_action": | |
| logs.append("[Router Warning] LLM tried to skip reasoning. Forcing reason_and_rank.") # debug code | |
| return "reason_and_rank" | |
| logs.append(f"[Router] Moving from {current_node} to {response}") | |
| return response | |
| # ---- LangGraph Workflow Setup ---- | |
| workflow = StateGraph(AgentState) | |
| workflow.add_node("validate", validate) | |
| workflow.add_node("reason_and_rank", reason_and_rank) | |
| workflow.add_node("take_action", take_action) | |
| workflow.add_conditional_edges( | |
| "validate", | |
| decide_next_node, | |
| { | |
| "reason_and_rank": "reason_and_rank", | |
| END: END | |
| } | |
| ) | |
| workflow.add_conditional_edges( | |
| "reason_and_rank", | |
| decide_next_node, | |
| { | |
| "take_action": "take_action", | |
| END: END | |
| } | |
| ) | |
| workflow.add_conditional_edges( | |
| "take_action", | |
| decide_next_node, | |
| { | |
| END: END | |
| } | |
| ) | |
| workflow.set_entry_point("validate") | |
| graph: CompiledStateGraph = workflow.compile() | |
| # ---- Initialize session state ---- | |
| def init_session(): | |
| if "step" not in st.session_state: | |
| st.session_state.step = "form" | |
| if "application" not in st.session_state: | |
| st.session_state.application = None | |
| if "plan_accepted" not in st.session_state: | |
| st.session_state.plan_accepted = False | |
| if "escalated" not in st.session_state: | |
| st.session_state.escalated = False | |
| if "handled" not in st.session_state: | |
| st.session_state.handled = False | |
| if "matched_case_df" not in st.session_state: | |
| st.session_state.matched_case_df = None | |
| if "feedback" not in st.session_state: | |
| st.session_state.feedback = None | |
| if "submitted_feedbacks" not in st.session_state: | |
| st.session_state.submitted_feedbacks = set() | |
| if "reference_id" not in st.session_state: | |
| st.session_state.reference_id = None | |
| if "agent_logs" not in st.session_state: | |
| st.session_state.agent_logs = [] | |
| if "previous_plans" not in st.session_state: | |
| st.session_state.previous_plans = [] | |
| if "agent_state" not in st.session_state or st.session_state.agent_state is None: | |
| st.session_state.agent_state = AgentState( | |
| application=None, | |
| selected_plan=None, | |
| escalated=False, | |
| handled=False, | |
| matched_case_df=None, | |
| ltm_match_history=[], | |
| feedback=None, | |
| submitted_feedbacks=set(), | |
| reference_id=None, | |
| agent_logs=[], | |
| current_node="validate", | |
| eligible_plans=None, | |
| previous_plans=[] | |
| ) | |
| init_session() | |
| # ---- UI and workflow execution ---- | |
| if st.session_state.step == "form": | |
| with st.form("user_input"): | |
| #st.subheader("📝 Enter Your Details") | |
| st.subheader(" Enter Your Details") | |
| name = st.text_input("First Name") | |
| customer_id = st.text_input("Customer ID") | |
| account_type = st.selectbox("Account Type", ["mortgage", "credit card", "personal loan"]) | |
| hardship_reason = st.selectbox("Reason for Hardship", ["Job Loss", "Medical", "Natural Disaster"]) | |
| income = st.number_input("Monthly Income", min_value=0.0) | |
| expenses = st.number_input("Monthly Expenses", min_value=0.0) | |
| late_payments = st.number_input("Late Payments (last 12 months)", min_value=0, step=1) | |
| flagged_abuse = st.radio("Previously defaulted or rejected?", ["No", "Yes"]) == "Yes" | |
| submitted = st.form_submit_button("Submit") | |
| if submitted: | |
| if not name.strip(): | |
| st.warning("⚠️ Please enter your name.") | |
| elif not customer_id.strip(): | |
| st.warning("⚠️ Please enter your customer ID.") | |
| elif income == 0.0: | |
| st.warning("⚠️ Please enter your income.") | |
| elif expenses == 0.0: | |
| st.warning("⚠️ Please enter your expenses.") | |
| else: | |
| st.session_state.application = { | |
| "name": name.strip(), | |
| "account_type": account_type, | |
| "hardship_reason": hardship_reason, | |
| "income": income, | |
| "expenses": expenses, | |
| "history": {"late_payments": late_payments}, | |
| "flagged_abuse": flagged_abuse, | |
| "customer_id": customer_id, | |
| } | |
| st.session_state.agent_state["application"] = st.session_state.application | |
| st.session_state.agent_state["current_node"] = "validate" | |
| st.session_state.agent_state["selected_plan"] = None | |
| st.session_state.agent_state["escalated"] = False | |
| st.session_state.agent_state["handled"] = False | |
| st.session_state.agent_state["matched_case_df"] = None | |
| st.session_state.agent_state["feedback"] = None | |
| st.session_state.agent_state["eligible_plans"] = None | |
| st.session_state.agent_state["submitted_feedbacks"] = set() | |
| st.session_state.agent_state["agent_logs"] = [] | |
| st.session_state.step = "processing" | |
| st.rerun() | |
| elif st.session_state.step == "processing": | |
| #st.info("📡 Processing your request...") | |
| st.info(" Processing your request...") | |
| state = st.session_state.agent_state | |
| logs = state["agent_logs"] # This line is required | |
| logs.append("[Node] Processing plan recommendation...") | |
| # Run the graph streaming to execute the workflow nodes including reason_and_rank and take_action | |
| for updated_state in graph.stream(state): | |
| node_name, inner_state = list(updated_state.items())[0] | |
| # Update session state with the new state | |
| st.session_state.agent_state = inner_state | |
| st.session_state.agent_logs = inner_state.get("agent_logs", []) | |
| st.session_state.ltm_match_history = inner_state.get("ltm_match_history", []) | |
| st.session_state.escalated = inner_state.get("escalated", False) | |
| st.session_state.handled = inner_state.get("handled", False) | |
| st.session_state.matched_case_df = inner_state.get("matched_case_df") | |
| st.session_state.reference_id = inner_state.get("reference_id") | |
| state = inner_state # Feed updated state back to next iteration | |
| #inner_state["agent_logs"].append(f"[Debug] Node executed: {node_name}") # debug code | |
| inner_state["agent_logs"].append(f"[Info] node executed]: {node_name}") | |
| if node_name == END: | |
| break | |
| #st.write("✅ Final state from LangGraph:") # debug code | |
| #st.json(state) # debug code | |
| # Move to results after processing the entire graph | |
| st.session_state.step = "results" | |
| st.rerun() | |
| elif st.session_state.step == "results": | |
| state = st.session_state.agent_state | |
| if st.session_state.escalated: | |
| st.warning("⚠️ Your case has been assigned to a agent for review.") | |
| ref = f"{state['application']['customer_id'].upper()}-{datetime.now().strftime('%d%m%y%H%M%S')}" | |
| state["reference_id"] = ref | |
| st.markdown(f"**Reference#:** `{ref}`") | |
| if st.button("⮎ Continue"): | |
| for k in list(st.session_state.keys()): | |
| del st.session_state[k] | |
| st.rerun() | |
| st.session_state.step = "done" | |
| st.stop() | |
| elif state.get("selected_plan"): | |
| plan = state["selected_plan"] | |
| st.success(f"✅ Proposed Plan: **{plan}**") | |
| st.markdown(f"**{hardship_plans[plan]['description']}**") | |
| #Suggestion (Optional) | |
| #ranked = sorted(state.get("eligible_plans", []), key=lambda p: hardship_plans[p]["risk_score"]) | |
| #if plan in ranked and len(ranked) > 1: | |
| # alternatives = [p for p in ranked if p != plan] | |
| # second_best = alternatives[0] | |
| # st.info(f"💡 You might also consider: **{second_best}** — {hardship_plans[second_best]['description']}") | |
| submitted = state["submitted_feedbacks"] | |
| remaining = {"Accept", "I can only afford half", "Suggest alternative"} - submitted | |
| if "Accept" in submitted: | |
| st.success("Thank you for your response.") | |
| st.success(f"You have accepted the proposed plan: **{plan}**") | |
| ref = state.get("reference_id") | |
| if ref: | |
| st.markdown(f"**Reference#:** `{ref}`") | |
| if st.button("🔁 Submit New Request"): | |
| for k in list(st.session_state.keys()): | |
| del st.session_state[k] | |
| st.rerun() | |
| st.session_state.step = "done" | |
| st.stop() | |
| # Show feedback options only if not already accepted | |
| options = [opt for opt in ["Accept", "I can only afford half", "Suggest alternative"] if opt in remaining] #options = list(remaining) | |
| feedback = st.radio("Feedback (choose one):", options, key="feedback_choice") | |
| if st.button("Submit Feedback"): | |
| submitted.add(feedback) | |
| state["submitted_feedbacks"] = submitted | |
| state["agent_logs"].append(f"[Feedback] User selected: {feedback}") | |
| if feedback == "Accept": | |
| state["handled"] = True | |
| ref = f"{state['application']['customer_id'].upper()}-{datetime.now().strftime('%d%m%y%H%M%S')}" | |
| state["reference_id"] = ref | |
| st.session_state.step = "done" | |
| st.rerun() | |
| elif "half" in feedback.lower(): | |
| state["agent_logs"].append("[Feedback Action] User selected 'half'. Reducing income and rerunning reason_and_rank") | |
| state["application"]["income"] = state["application"]["income"] / 2 # Adjust income | |
| state["feedback"] = "half" | |
| state["handled"] = False | |
| state.pop("selected_plan", None) # Force recomputation | |
| state.pop("matched_case_df", None) #clear matched case display (but keep history) | |
| state["current_node"] = "reason_and_rank" | |
| st.session_state.step = "processing" | |
| st.rerun() | |
| elif feedback == "Suggest alternative": | |
| state["feedback"] = "wants_alternative" | |
| state["handled"] = False | |
| state["current_node"] = "reason_and_rank" | |
| state["agent_logs"].append("[Feedback Action] User requested alternative. Clearing selected_plan and rerunning reason_and_rank") | |
| state.pop("selected_plan", None) #clear old plan so it doesn't get reused | |
| state.pop("matched_case_df", None) # clear matched case display (but keep history) | |
| st.session_state.step = "processing" | |
| st.rerun() | |
| else: | |
| st.warning("⚠️ No plan could be proposed.") | |
| st.session_state.step = "done" | |
| st.rerun() | |
| elif st.session_state.step == "done": | |
| state = st.session_state.agent_state | |
| #st.success("🎉 Thank you for your response.") | |
| st.success(" Thank you for your response.") | |
| if state.get("selected_plan"): | |
| st.markdown(f"**You have accepted the proposed plan:** `{state['selected_plan']}`") | |
| if state.get("reference_id"): | |
| st.markdown(f"**Reference#:** `{state['reference_id']}`") | |
| #if st.button("🔁 Submit New Request"): | |
| if st.button("🔂 Submit New Request"): | |
| for k in list(st.session_state.keys()): | |
| del st.session_state[k] | |
| st.rerun() | |
| # Show Agent Logs only after user has submitted their details | |
| if st.session_state.step in {"processing", "results", "done"}: | |
| #if "agent_state" in st.session_state and st.session_state.agent_state: OR #if st.session_state.agent_logs: | |
| st.markdown("---") | |
| #st.markdown("### 📜 Agent Logs") | |
| st.markdown(" Agent Logs") | |
| logs = st.session_state.agent_state["agent_logs"] | |
| for log in logs: | |
| st.markdown(f"- {log}") | |
| st.markdown("---") | |
| # ----- Matched Cases from Long‑Term Memory ----- | |
| if st.session_state.ltm_match_history: | |
| #st.markdown("### 🧠 Matched Cases from Long‑Term Memory") | |
| st.markdown(" Matched Cases from Long‑Term Memory") | |
| for idx, df in enumerate(st.session_state.ltm_match_history, 1): | |
| st.markdown(f"#### Match {idx}") | |
| st.table(df) | |
| else: | |
| st.info("No similar cases found in long‑term memory.") |