import json import os import statistics import time import pandas as pd import requests import streamlit as st RATE_LIMIT_REQUESTS = 8 RATE_LIMIT_WINDOW_SECONDS = 60 ROUTING_OPTIONS = [ "Auto-approve", "Escalate to manager", "Send to committee", "Reject", ] FACTOR_WEIGHTS = { "Amount Risk": 0.24, "Urgency Risk": 0.19, "Category Risk": 0.21, "Department Risk": 0.17, "Historical Outcome Risk": 0.19, } @st.cache_data def load_history(): history_df = pd.read_csv("data/historical_approvals.csv") history_df["created_at"] = pd.to_datetime(history_df["created_at"], errors="coerce") history_df["amount"] = pd.to_numeric(history_df["amount"], errors="coerce") history_df["urgency"] = pd.to_numeric(history_df["urgency"], errors="coerce") history_df["amount"] = history_df["amount"].fillna(0.0) history_df["urgency"] = history_df["urgency"].fillna(0.0) history_df["override"] = history_df["override"].astype(str).str.lower().eq("true") return history_df def default_state(history_df): departments = sorted(history_df["business_unit"].dropna().unique().tolist()) categories = sorted(history_df["category"].dropna().unique().tolist()) return { "department_options": departments, "category_options": categories, "step_unlocked": 1, "request_timestamps": [], "step1_description": "", "step1_department": departments[0] if departments else "Engineering", "step1_amount": 0.0, "step1_category": categories[0] if categories else "Software", "step1_urgency": "Medium", "step2_risk_sliders": {}, "step2_ai": None, "step2_adjusted_total": None, "step2_similar": None, "step2_ai_vs_user": None, "step3_suggested_route": None, "step3_selected_route": None, "step3_route_override_reason": "", "step3_confidence": 0.0, "step3_explanation": "", "step3_gemini_error": None, "step4_audit": None, "show_sample_toast": False, } def init_state(history_df): for key, value in default_state(history_df).items(): if key not in st.session_state: st.session_state[key] = value def clear_dependent_state(): st.session_state["step2_risk_sliders"] = {} st.session_state["step2_ai"] = None st.session_state["step2_adjusted_total"] = None st.session_state["step2_similar"] = None st.session_state["step2_ai_vs_user"] = None st.session_state["step3_suggested_route"] = None st.session_state["step3_selected_route"] = None st.session_state["step3_route_override_reason"] = "" st.session_state["step3_confidence"] = 0.0 st.session_state["step3_explanation"] = "" st.session_state["step3_gemini_error"] = None st.session_state["step4_audit"] = None def start_new_request(history_df): preserved = st.session_state.get("request_timestamps", []) base = default_state(history_df) for key, value in base.items(): st.session_state[key] = value st.session_state["request_timestamps"] = preserved def load_sample_request(): st.session_state["step1_description"] = ( "We need a budget exception to expand Databricks capacity for two enterprise clients " "signed in Q4. Without additional spend, analytics SLAs will be missed in 30 days." ) st.session_state["step1_department"] = "Finance" st.session_state["step1_amount"] = 84500.0 st.session_state["step1_category"] = "Cloud Infrastructure" st.session_state["step1_urgency"] = "High" st.session_state["show_sample_toast"] = True clear_dependent_state() st.session_state["step_unlocked"] = 1 def check_rate_limit(): now = time.time() timeline = st.session_state.get("request_timestamps", []) timeline = [t for t in timeline if now - t <= RATE_LIMIT_WINDOW_SECONDS] st.session_state["request_timestamps"] = timeline if len(timeline) >= RATE_LIMIT_REQUESTS: return False, max(1, int(RATE_LIMIT_WINDOW_SECONDS - (now - timeline[0]))) timeline.append(now) st.session_state["request_timestamps"] = timeline return True, 0 def normalized_amount_risk(amount, history_df): cap = max(50000.0, float(history_df["amount"].quantile(0.90))) return min(1.0, max(0.0, float(amount) / cap)) def urgency_to_score(urgency): return { "Low": 0.25, "Medium": 0.52, "High": 0.84, "Critical": 0.96, }.get(urgency, 0.5) def to_float(value, default=0.0): if isinstance(value, (int, float)): return float(value) if isinstance(value, str): try: return float(value) except ValueError: return float(default) return float(default) def category_historical_risk(history_df, category): rows = history_df[history_df["category"] == category].copy() if rows.empty: return 0.5 rejected_share = rows["outcome"].eq("Rejected").mean() override_share = rows["override"].mean() committee_share = rows["routing"].str.contains("Risk|Compliance", case=False, na=False).mean() return min(1.0, 0.55 * rejected_share + 0.20 * override_share + 0.25 * committee_share + 0.2) def department_historical_risk(history_df, department): rows = history_df[history_df["business_unit"] == department].copy() if rows.empty: return 0.5 rejected_share = rows["outcome"].eq("Rejected").mean() high_urgency_share = (rows["urgency"] >= 60).mean() return min(1.0, 0.62 * rejected_share + 0.38 * high_urgency_share + 0.15) def similar_case_risk(history_df, department, category, amount): subset = history_df[ (history_df["business_unit"] == department) & (history_df["category"] == category) ].copy() if subset.empty: subset = history_df[history_df["category"] == category].copy() if subset.empty: subset = history_df.copy() subset["amount_diff"] = (subset["amount"] - amount).abs() nearest = subset.sort_values(["amount_diff", "created_at"], ascending=[True, False]).head(6) rejected_share = nearest["outcome"].eq("Rejected").mean() if not nearest.empty else 0.4 override_share = nearest["override"].mean() if not nearest.empty else 0.2 blended = min(1.0, rejected_share * 0.65 + override_share * 0.35 + 0.15) return blended, nearest def compute_heuristic_assessment(request_payload, history_df): amount_score = normalized_amount_risk(request_payload["amount"], history_df) urgency_score = urgency_to_score(request_payload["urgency"]) category_score = category_historical_risk(history_df, request_payload["category"]) department_score = department_historical_risk(history_df, request_payload["department"]) historical_score, similar = similar_case_risk( history_df, request_payload["department"], request_payload["category"], request_payload["amount"], ) factor_scores = { "Amount Risk": amount_score, "Urgency Risk": urgency_score, "Category Risk": category_score, "Department Risk": department_score, "Historical Outcome Risk": historical_score, } weighted_total = 0.0 for name, score in factor_scores.items(): weighted_total += FACTOR_WEIGHTS[name] * score confidence = min( 0.97, max( 0.56, 0.60 + 0.14 * min(1.0, len(similar) / 6) + 0.09 * (1.0 - abs(weighted_total - 0.5) * 1.8), ), ) baseline = { "overall_score": round(float(weighted_total), 4), "confidence": round(float(confidence), 4), "explanation": "", "factors": [ { "name": name, "weight": FACTOR_WEIGHTS[name], "score": round(float(score), 4), "weighted": round(float(FACTOR_WEIGHTS[name] * score), 4), } for name, score in factor_scores.items() ], } return baseline, similar def parse_gemini_json(text): try: payload = json.loads(text) if not isinstance(payload, dict): return None if "overall_score" not in payload or "factors" not in payload: return None factors = payload.get("factors", []) if not isinstance(factors, list): return None fixed_factors = [] for item in factors: if not isinstance(item, dict): continue name = str(item.get("name", "")).strip() if name not in FACTOR_WEIGHTS: continue score = float(item.get("score", 0.5)) fixed_factors.append( { "name": name, "weight": FACTOR_WEIGHTS[name], "score": round(min(1.0, max(0.0, score)), 4), } ) if len(fixed_factors) < 3: return None weighted = sum(row["weight"] * row["score"] for row in fixed_factors) for row in fixed_factors: row["weighted"] = round(row["weight"] * row["score"], 4) return { "overall_score": round(min(1.0, max(0.0, weighted)), 4), "confidence": round(min(0.97, max(0.55, float(payload.get("confidence", 0.68)))), 4), "factors": fixed_factors, "explanation": str(payload.get("explanation", "")).strip(), } except (TypeError, ValueError, json.JSONDecodeError): return None def gemini_risk_assessment(request_payload, historical_slice): api_key = os.getenv("GEMINI_API_KEY") if not api_key: return None, "Missing GEMINI_API_KEY" preview_cols = [ "request_id", "amount", "category", "business_unit", "urgency", "outcome", "routing", "override", ] preview_data = historical_slice[preview_cols].head(8).to_dict("records") prompt = ( "You are an approval intelligence scorer. Return strict JSON only with keys: " "overall_score (0-1), confidence (0-1), factors (array of 5 objects), explanation. " "Each factor object must include name and score. Use these exact factor names: " f"{list(FACTOR_WEIGHTS.keys())}. " "Score is risk where 1 is highest." "\n\n" f"Request: {json.dumps(request_payload)}\n" f"Historical examples: {json.dumps(preview_data)}" ) body = { "contents": [{"parts": [{"text": prompt}]}], "generationConfig": { "temperature": 0.2, "maxOutputTokens": 350, }, } endpoint = ( "https://generativelanguage.googleapis.com/v1beta/models/" "gemini-2.5-flash:generateContent" ) try: response = requests.post( f"{endpoint}?key={api_key}", json=body, timeout=25, ) except requests.RequestException as exc: return None, f"Unable to reach Gemini: {exc}" if response.status_code != 200: return None, f"Gemini API status {response.status_code}" payload = response.json() candidates = payload.get("candidates", []) if not candidates: return None, "Gemini returned no candidates" parts = candidates[0].get("content", {}).get("parts", []) text = "\n".join(part.get("text", "") for part in parts if part.get("text")) parsed = parse_gemini_json(text.strip()) if parsed is None: return None, "Gemini response was not parseable JSON" return parsed, None def route_from_score(score): if score < 0.34: return "Auto-approve" if score < 0.56: return "Escalate to manager" if score < 0.78: return "Send to committee" return "Reject" def explanation_from_assessment(request_payload, ai_assessment, adjusted_total, selected_route): factors_sorted = sorted(ai_assessment["factors"], key=lambda item: item["weighted"], reverse=True) top_names = ", ".join(item["name"] for item in factors_sorted[:3]) decision_text = ( f"The request for ${request_payload['amount']:,.0f} in {request_payload['category']} from " f"{request_payload['department']} lands at a risk score of {adjusted_total:.1%}. " f"Primary pressure points are {top_names}. " f"Given this profile and historical behavior, the decision engine routes it to '{selected_route}' " f"with {ai_assessment['confidence']:.1%} confidence." ) return decision_text def build_audit_trail(history_df): ai_data = st.session_state["step2_ai"] request_data = { "description": st.session_state["step1_description"], "department": st.session_state["step1_department"], "amount": float(st.session_state["step1_amount"]), "category": st.session_state["step1_category"], "urgency": st.session_state["step1_urgency"], "submitted_at": pd.Timestamp.utcnow().isoformat(), } slider_map = st.session_state["step2_risk_sliders"] adjusted_factors = [] for factor in ai_data["factors"]: name = factor["name"] score = float(slider_map.get(name, factor["score"])) adjusted_factors.append( { "name": name, "weight": factor["weight"], "ai_score": factor["score"], "user_adjusted_score": round(score, 4), "user_weighted": round(factor["weight"] * score, 4), } ) ai_score = float(ai_data["overall_score"]) user_score = float(st.session_state["step2_adjusted_total"]) suggested_route = st.session_state["step3_suggested_route"] selected_route = st.session_state["step3_selected_route"] override_used = suggested_route != selected_route similar_df = st.session_state["step2_similar"] similar_records = [] if similar_df is not None and not similar_df.empty: for _, row in similar_df.head(8).iterrows(): similar_records.append( { "request_id": str(row.get("request_id", "")), "created_at": str(pd.to_datetime(row.get("created_at"), errors="coerce").date()), "amount": float(row.get("amount", 0.0)), "category": str(row.get("category", "")), "department": str(row.get("business_unit", "")), "outcome": str(row.get("outcome", "")), "routing": str(row.get("routing", "")), "override": bool(row.get("override", False)), } ) return { "request": request_data, "risk_assessment": { "ai_overall_score": round(ai_score, 4), "user_adjusted_score": round(user_score, 4), "confidence": float(st.session_state["step3_confidence"]), "factors": adjusted_factors, "comparison": st.session_state["step2_ai_vs_user"], }, "routing_decision": { "ai_recommendation": suggested_route, "final_selection": selected_route, "override_used": override_used, "override_reason": st.session_state["step3_route_override_reason"].strip(), "explanation": st.session_state["step3_explanation"], }, "similar_cases_considered": similar_records, "engine_metadata": { "rate_limit": f"{RATE_LIMIT_REQUESTS} requests / {RATE_LIMIT_WINDOW_SECONDS}s", "model": "gemini-2.5-flash with deterministic fallback", "historical_rows": int(len(history_df)), }, } def factor_table(factors, include_user=False): rows = [] slider_values = st.session_state.get("step2_risk_sliders", {}) for item in factors: name = item["name"] row = { "Factor": name, "Weight": f"{item['weight']:.0%}", "AI Score": f"{item['score']:.2f}", "AI Weighted": f"{item['weighted']:.2f}", } if include_user: user_score = float(slider_values.get(name, item["score"])) row["Your Score"] = f"{user_score:.2f}" row["Your Weighted"] = f"{(item['weight'] * user_score):.2f}" rows.append(row) return pd.DataFrame(rows) def dataset_view(history_df): df = history_df.copy() df["created_at"] = df["created_at"].dt.strftime("%Y-%m-%d") df["amount"] = df["amount"].map(lambda amt: f"${amt:,.0f}") return df st.set_page_config( page_title="Approval Intelligence Engine | Arcalab XYZ", page_icon="🧠", layout="wide", ) st.markdown( """ """, unsafe_allow_html=True, ) history = load_history() init_state(history) st.title("AI-Powered Approval Intelligence Engine") st.caption( "An AI decision engine that auto-scores approval requests and routes them through smart automation with transparent confidence scores." ) if st.session_state["show_sample_toast"]: st.toast("Sample request loaded. Tweak details, then run analysis.") st.session_state["show_sample_toast"] = False tabs = st.tabs( [ "1. Describe Request", "2. Risk Assessment", "3. Routing Decision", "4. Decision Summary", ] ) with tabs[0]: st.markdown("
", unsafe_allow_html=True) st.subheader("Describe Your Request") st.write( "Start with plain language, then add quick configuration details. The request stays empty by default so you can model real scenarios." ) st.text_area( "Describe the approval request in your own words", key="step1_description", placeholder=( "Example: We need a temporary budget override to expand cloud analytics capacity " "for two signed enterprise contracts while existing spend is capped." ), height=160, ) st.caption("Describe business impact, constraints, and why timing matters.") c1, c2 = st.columns(2) with c1: st.selectbox( "Department", options=st.session_state["department_options"], key="step1_department", ) st.markdown("
Who owns budget accountability for this request.
", unsafe_allow_html=True) with c2: st.number_input( "Amount (USD)", min_value=0.0, max_value=5000000.0, step=500.0, key="step1_amount", ) st.markdown("
Total spend requested for approval.
", unsafe_allow_html=True) c3, c4 = st.columns(2) with c3: st.selectbox( "Category", options=st.session_state["category_options"], key="step1_category", ) st.markdown("
Used to match precedent and policy risk patterns.
", unsafe_allow_html=True) with c4: st.selectbox( "Urgency", options=["Low", "Medium", "High", "Critical"], key="step1_urgency", ) st.markdown("
Higher urgency increases scrutiny when precedent is weak.
", unsafe_allow_html=True) st.button("Try with sample", key="step1_sample_link", on_click=load_sample_request) analyze_clicked = st.button("Analyze Request ->", type="primary", use_container_width=True) if analyze_clicked: message_holder = st.empty() clean_description = st.session_state["step1_description"].strip() if not clean_description: message_holder.warning("Please describe the request before running analysis.") elif st.session_state["step1_amount"] <= 0: message_holder.warning("Amount must be greater than 0 to assess risk.") else: allowed, wait_seconds = check_rate_limit() if not allowed: message_holder.error( f"Rate limit reached: max {RATE_LIMIT_REQUESTS} requests per {RATE_LIMIT_WINDOW_SECONDS}s. Try again in ~{wait_seconds}s." ) else: request_payload = { "description": clean_description, "department": st.session_state["step1_department"], "amount": float(st.session_state["step1_amount"]), "category": st.session_state["step1_category"], "urgency": st.session_state["step1_urgency"], } clear_dependent_state() with st.spinner("Scoring 5 risk factors..."): heuristic_assessment, similar_df = compute_heuristic_assessment(request_payload, history) gemini_assessment, gemini_error = gemini_risk_assessment(request_payload, similar_df) with st.spinner("Finding similar cases..."): similar_df = similar_df.copy() similar_df["created_at"] = pd.to_datetime(similar_df["created_at"], errors="coerce") ai_assessment = gemini_assessment if gemini_assessment else heuristic_assessment factors_raw = ai_assessment.get("factors", []) if isinstance(ai_assessment, dict) else [] factors = factors_raw if isinstance(factors_raw, list) else [] overall_score = to_float(ai_assessment.get("overall_score", 0.5), 0.5) if isinstance(ai_assessment, dict) else 0.5 confidence_score = to_float( ai_assessment.get("confidence", heuristic_assessment["confidence"]), to_float(heuristic_assessment["confidence"], 0.65), ) if isinstance(ai_assessment, dict) else to_float(heuristic_assessment["confidence"], 0.65) explanation_text = str(ai_assessment.get("explanation", "")).strip() if isinstance(ai_assessment, dict) else "" slider_defaults = { str(row.get("name", "Factor")): to_float(row.get("score", 0.5), 0.5) for row in factors if isinstance(row, dict) and row.get("name") } st.session_state["step2_risk_sliders"] = slider_defaults st.session_state["step2_ai"] = ai_assessment st.session_state["step2_adjusted_total"] = overall_score st.session_state["step2_similar"] = similar_df st.session_state["step2_ai_vs_user"] = { "ai": overall_score, "user": overall_score, } suggested_route = route_from_score(overall_score) st.session_state["step3_suggested_route"] = suggested_route st.session_state["step3_selected_route"] = suggested_route st.session_state["step3_confidence"] = confidence_score if not explanation_text: explanation_text = explanation_from_assessment( request_payload, ai_assessment, overall_score, suggested_route, ) st.session_state["step3_explanation"] = explanation_text st.session_state["step3_gemini_error"] = gemini_error st.session_state["step_unlocked"] = 2 message_holder.success("Assessment complete. Move to Step 2.") st.markdown("
", unsafe_allow_html=True) with tabs[1]: unlocked = st.session_state["step_unlocked"] >= 2 and st.session_state["step2_ai"] is not None if not unlocked: st.markdown("
", unsafe_allow_html=True) st.subheader("Risk Assessment") st.write("Complete Step 1 to unlock AI risk analysis, adjustable factor sliders, and similar-case evidence.") st.markdown("
", unsafe_allow_html=True) else: st.markdown("
", unsafe_allow_html=True) st.subheader("Risk Assessment") st.write("Review AI factor weights, adjust what you disagree with, and watch total risk recalculate live.") ai_assessment = st.session_state["step2_ai"] slider_values = {} for item in ai_assessment["factors"]: slider_values[item["name"]] = st.slider( f"{item['name']} ({item['weight']:.0%} weight)", min_value=0.0, max_value=1.0, value=float(st.session_state["step2_risk_sliders"].get(item["name"], item["score"])), step=0.01, key=f"slider_{item['name']}", ) adjusted_total = sum( FACTOR_WEIGHTS[name] * score for name, score in slider_values.items() ) st.session_state["step2_risk_sliders"] = slider_values st.session_state["step2_adjusted_total"] = float(adjusted_total) st.session_state["step2_ai_vs_user"] = { "ai": float(ai_assessment["overall_score"]), "user": float(adjusted_total), } st.session_state["step3_suggested_route"] = route_from_score(float(adjusted_total)) if st.session_state["step3_selected_route"] not in ROUTING_OPTIONS: st.session_state["step3_selected_route"] = st.session_state["step3_suggested_route"] metric_c1, metric_c2, metric_c3 = st.columns(3) metric_c1.metric("AI Assessment", f"{float(ai_assessment['overall_score']):.1%}") metric_c2.metric("Your Adjusted Assessment", f"{float(adjusted_total):.1%}") metric_c3.metric( "Delta", f"{(float(adjusted_total) - float(ai_assessment['overall_score'])):+.1%}", ) compare_left, compare_right = st.columns(2) with compare_left: st.markdown("**AI Assessment**") st.dataframe(factor_table(ai_assessment["factors"]), use_container_width=True, hide_index=True) with compare_right: st.markdown("**Your Adjusted Assessment**") st.dataframe( factor_table(ai_assessment["factors"], include_user=True), use_container_width=True, hide_index=True, ) st.markdown("**Similar Past Decisions**") similar_df = st.session_state["step2_similar"] if similar_df is not None and not similar_df.empty: view = similar_df.copy() view["created_at"] = pd.to_datetime(view["created_at"], errors="coerce").dt.strftime("%Y-%m-%d") view["amount"] = view["amount"].map(lambda v: f"${v:,.0f}") display = view[ [ "request_id", "created_at", "business_unit", "category", "amount", "urgency", "outcome", "routing", "override", ] ].rename( columns={ "business_unit": "department", } ) st.dataframe(display, use_container_width=True, hide_index=True) else: st.info("No similar historical cases matched this request.") continue_step3 = st.button("Continue to Routing ->", type="primary", use_container_width=True) if continue_step3: st.session_state["step_unlocked"] = max(3, st.session_state["step_unlocked"]) st.success("Routing step unlocked.") st.markdown("
", unsafe_allow_html=True) with tabs[2]: unlocked = st.session_state["step_unlocked"] >= 3 and st.session_state["step2_ai"] is not None if not unlocked: st.markdown("
", unsafe_allow_html=True) st.subheader("Routing Decision") st.write("Complete Step 2 first to produce a calibrated risk score and unlock routing controls.") st.markdown("
", unsafe_allow_html=True) else: st.markdown("
", unsafe_allow_html=True) st.subheader("Routing Decision") st.write("Choose the final path. You can accept the recommendation or override it with accountability.") adjusted_score = float(st.session_state["step2_adjusted_total"]) suggested_route = route_from_score(adjusted_score) st.session_state["step3_suggested_route"] = suggested_route score_band = "Low" if adjusted_score < 0.34 else "Moderate" if adjusted_score < 0.56 else "Elevated" if adjusted_score < 0.78 else "Severe" st.markdown( """
Risk Band: {} AI Route: {}
""".format(score_band, suggested_route), unsafe_allow_html=True, ) selected_route = st.radio( "Routing path", ROUTING_OPTIONS, index=ROUTING_OPTIONS.index(st.session_state["step3_selected_route"]) if st.session_state["step3_selected_route"] in ROUTING_OPTIONS else ROUTING_OPTIONS.index(suggested_route), key="step3_selected_route", horizontal=False, ) override_active = selected_route != suggested_route if override_active: st.text_input( "Reason for override", key="step3_route_override_reason", placeholder="Explain why the final route should differ from the model recommendation.", ) confidence = float(st.session_state["step3_confidence"]) st.write("**Confidence Meter**") st.progress(min(1.0, max(0.0, confidence)), text=f"{confidence:.1%} confidence") st.write("**AI Explanation**") request_payload = { "description": st.session_state["step1_description"], "department": st.session_state["step1_department"], "amount": float(st.session_state["step1_amount"]), "category": st.session_state["step1_category"], "urgency": st.session_state["step1_urgency"], } live_explanation = explanation_from_assessment( request_payload, st.session_state["step2_ai"], adjusted_score, selected_route, ) if st.session_state["step3_gemini_error"]: st.info(f"Gemini unavailable, using heuristic explanation: {st.session_state['step3_gemini_error']}") st.write(live_explanation) st.session_state["step3_explanation"] = live_explanation can_finalize = True if override_active and not st.session_state["step3_route_override_reason"].strip(): can_finalize = False st.warning("Add a reason for override before finalizing.") finalize = st.button("Finalize Decision ->", type="primary", use_container_width=True, disabled=not can_finalize) if finalize: st.session_state["step4_audit"] = build_audit_trail(history) st.session_state["step_unlocked"] = max(4, st.session_state["step_unlocked"]) st.success("Decision finalized. Review audit trail in Step 4.") st.markdown("
", unsafe_allow_html=True) with tabs[3]: unlocked = st.session_state["step_unlocked"] >= 4 and st.session_state["step4_audit"] is not None if not unlocked: st.markdown("
", unsafe_allow_html=True) st.subheader("Decision Summary & Audit Trail") st.write("Finalize the routing decision in Step 3 to generate a complete audit report and export package.") st.markdown("
", unsafe_allow_html=True) else: audit = st.session_state["step4_audit"] st.markdown("
", unsafe_allow_html=True) st.subheader("Decision Summary & Audit Trail") st.write("A full audit-grade report of request inputs, AI assessment, user adjustments, and final routing outcome.") req = audit["request"] st.markdown("**Original Request**") req_col_1, req_col_2, req_col_3 = st.columns(3) req_col_1.metric("Department", req["department"]) req_col_2.metric("Category", req["category"]) req_col_3.metric("Amount", f"${req['amount']:,.0f}") st.write(req["description"]) st.markdown("**Risk Assessment**") risk = audit["risk_assessment"] risk_col_1, risk_col_2, risk_col_3 = st.columns(3) risk_col_1.metric("AI Score", f"{risk['ai_overall_score']:.1%}") risk_col_2.metric("Adjusted Score", f"{risk['user_adjusted_score']:.1%}") risk_col_3.metric("Confidence", f"{risk['confidence']:.1%}") factor_rows = [] for row in risk["factors"]: factor_rows.append( { "factor": row["name"], "weight": f"{row['weight']:.0%}", "ai_score": f"{row['ai_score']:.2f}", "user_score": f"{row['user_adjusted_score']:.2f}", "user_weighted": f"{row['user_weighted']:.2f}", } ) st.dataframe(pd.DataFrame(factor_rows), use_container_width=True, hide_index=True) st.markdown("**Routing Decision**") route = audit["routing_decision"] routing_col_1, routing_col_2 = st.columns(2) routing_col_1.metric("AI Recommendation", route["ai_recommendation"]) routing_col_2.metric("Final Selection", route["final_selection"]) if route["override_used"]: st.warning(f"Override reason: {route['override_reason']}") st.write(route["explanation"]) export_payload = json.dumps(audit, indent=2) st.download_button( "Download Decision Trail (JSON)", data=export_payload, file_name="approval_decision_audit_trail.json", mime="application/json", use_container_width=True, ) st.button( "Start New Request", use_container_width=True, on_click=start_new_request, args=(history,), ) st.markdown("
", unsafe_allow_html=True) st.markdown("---") with st.expander("Historical Dataset", expanded=False): st.write( f"{len(history)} decisions loaded. This historical set is used for similarity matching, trend learning, and fallback scoring." ) st.dataframe(dataset_view(history), use_container_width=True, hide_index=True) st.download_button( "Download historical CSV", data=history.to_csv(index=False), file_name="historical_approvals.csv", mime="text/csv", ) try: history_reject_rate = history["outcome"].eq("Rejected").mean() history_override_rate = history["override"].mean() avg_amount = statistics.mean(history["amount"].tolist()) if len(history) > 0 else 0.0 st.caption( f"Engine baseline: {history_reject_rate:.1%} reject rate, {history_override_rate:.1%} override rate, ${avg_amount:,.0f} average request size." ) except Exception: st.caption("Engine baseline available after historical data loads.")