CoolFace
Apppublic

RAHULJUNEJA33/AgenticAI_DecisionTree_app

sourceHugging Facemitupdated 2y agoView on Hugging Face
3likes
app.py163 linesDownload Raw Back to root
1import streamlit as st2from faiss import IndexFlatL23import numpy as np4from transformers import T5Tokenizer, T5ForConditionalGeneration5from graphviz import Digraph6import torch7 8# Initialize T5 model for both summarization and feature extraction9tokenizer = T5Tokenizer.from_pretrained("t5-large")10model = T5ForConditionalGeneration.from_pretrained("t5-large")11 12# Initialize FAISS index13index = IndexFlatL2(1024)  # T5 embeddings are 1024-dimensional14responses = []  # Store responses for FAISS15 16# Streamlit page setup17st.title("Banking AI Decision-Making Assistant πŸ€–")18st.markdown("""19### **Understanding AI Reasoning Methods**20Before answering, here’s how AI chooses the best reasoning method for your banking use case:21| Method | How It Works | Best For | Example Use Cases |22|--------|-------------|----------|------------------|23| **Chain-of-Thought (CoT)** | Step-by-step reasoning | Math, logic, coding | Solving word problems, code generation |24| **Tree-of-Thoughts (ToT)** | Explores multiple solution paths | Games, decision-making | Chess, strategic planning |25| **Self-Consistency (SC)** | Selects the most frequent correct answer | Fact-checking, accuracy | Medical diagnosis, legal cases |26| **PAL (Program-Aided LMs)** | Uses external tools for precise answers | Math, finance, databases | Financial projections, data queries |27| **ReAct (Reasoning + Acting)** | AI interacts with tools & takes actions | AI Agents, automation | AI assistants, automated workflows |28| **Graph-of-Thoughts (GoT)** | Thoughts form a flexible network | Research, innovation | Scientific discovery, brainstorming |29""")30 31# Collect use case from the user32st.markdown("### **Describe Your Banking Use Case:**")33use_case = st.text_area("Enter your banking use case:")34 35# Initialize session state for responses36if 'responses' not in st.session_state:37    st.session_state.responses = {}38 39# Collect responses from user - checkboxes for independent selection40st.session_state.responses['multiple_factors'] = st.checkbox(41    "πŸ”„ Does this involve multiple decision factors? (e.g., risk, compliance, fraud)",42    value=False,43    key="multiple_factors"44)45 46st.session_state.responses['real_time_validation'] = st.checkbox(47    "⏳ Does this require real-time validation? (e.g., fraud detection, transaction monitoring)",48    value=False,49    key="real_time_validation"50)51 52st.session_state.responses['user_feedback'] = st.checkbox(53    "πŸ‘₯ Does this need user feedback handling? (e.g., customer disputes, support tickets)",54    value=False,55    key="user_feedback"56)57 58st.session_state.responses['complexity'] = st.checkbox(59    "🧩 Is the decision-making process complex? (e.g., multi-step approvals, AI model predictions)",60    value=False,61    key="complexity"62)63 64st.session_state.responses['security_concern'] = st.checkbox(65    "πŸ” Are there security concerns? (e.g., sensitive data, encryption, compliance)",66    value=False,67    key="security_concern"68)69 70st.session_state.responses['automation_level'] = st.checkbox(71    "πŸ€– Is this process fully automated? (e.g., auto-loan approvals, AI-driven compliance checks)",72    value=False,73    key="automation_level"74)75 76# Function to determine the best AI method based on responses77def determine_method(responses):78    """Determines the best AI method based on user responses."""79    if responses['multiple_factors'] and responses['complexity']:80        rationale = "Yes, this requires multi-step decision-making, strategic planning."81        return "Tree-of-Thoughts (ToT)", rationale82    elif responses['real_time_validation']:83        rationale = "Yes, this requires real-time data validation for fraud detection or monitoring."84        return "PAL (Program-Aided LMs)", rationale85    elif responses['user_feedback']:86        rationale = "Yes, this involves dynamic user feedback handling."87        return "ReAct (Reasoning + Acting)", rationale88    elif responses['security_concern']:89        rationale = "Yes, there are concerns regarding data security and accuracy."90        return "Self-Consistency (SC)", rationale91    elif responses['automation_level']:92        rationale = "Yes, this process requires a fully automated system with external tools."93        return "PAL (Program-Aided LMs)", rationale94    else:95        rationale = "No, this decision-making is more straightforward and does not involve complex factors."96        return "Chain-of-Thought (CoT)", rationale97 98# Function to store responses in FAISS index99def store_response(responses):100    """Stores user responses in FAISS."""101    response_str = " ".join([f"{key}: {value}" for key, value in responses.items()])102    inputs = tokenizer(response_str, return_tensors="pt", padding=True, truncation=True)103    with torch.no_grad():  # Disable gradient calculation for inference104        outputs = model.encoder(inputs["input_ids"])  # Encoder for feature extraction105        embeddings = outputs.last_hidden_state.mean(dim=1).detach().numpy()  # Use mean of hidden states as embedding106 107    # Add the embeddings to the FAISS index108    index.add(np.array(embeddings))109 110# Function to generate a decision tree visualization111def visualize_decision_tree(responses, selected_method, rationale):112    """Generates a decision tree visualization using Graphviz."""113    dot = Digraph()114    dot.node("Use Case Input", "🏦 Banking Use Case")115    dot.node("Multiple Decision Factors", f"Yes: {responses['multiple_factors']}" if responses['multiple_factors'] else "No")116    dot.node("Real-Time Validation", f"Yes: {responses['real_time_validation']}" if responses['real_time_validation'] else "No")117    dot.node("User Feedback Handling", f"Yes: {responses['user_feedback']}" if responses['user_feedback'] else "No")118    dot.node("Complexity", f"High: {responses['complexity']}" if responses['complexity'] else "Low")119    dot.node("Security Concern", f"Yes: {responses['security_concern']}" if responses['security_concern'] else "No")120    dot.node("Automation Level", f"Automated: {responses['automation_level']}" if responses['automation_level'] else "Human Oversight")121    dot.node("Final Method", f"🎯 {selected_method}\nRationale: {rationale}")122 123    # Connect nodes124    dot.edge("Use Case Input", "Multiple Decision Factors")125    dot.edge("Multiple Decision Factors", "Real-Time Validation")126    dot.edge("Real-Time Validation", "User Feedback Handling")127    dot.edge("User Feedback Handling", "Complexity")128    dot.edge("Complexity", "Security Concern")129    dot.edge("Security Concern", "Automation Level")130    dot.edge("Automation Level", "Final Method")131 132    st.graphviz_chart(dot)133 134# Summarization using T5135def get_summary(use_case):136    """Generates a summary using T5."""137    try:138        inputs = tokenizer(f"summarize: {use_case}", return_tensors="pt", max_length=512, truncation=True)139        summary_ids = model.generate(inputs["input_ids"], max_length=200, num_beams=4, early_stopping=True)140        summary = tokenizer.decode(summary_ids[0], skip_special_tokens=True)141        return summary142    except Exception as e:143        st.error(f"❌ Error generating summary: {e}")144        return None145 146# Analyze button147if st.button("πŸ” Analyze Use Case"):148    # Get summary of the use case149    summary = get_summary(use_case)150    if summary:151        st.write("### **πŸ“„ Summary of Your Use Case:**")152        st.write(summary)153 154        # Determine the best AI method155        method, rationale = determine_method(st.session_state.responses)156        st.write(f"## πŸš€ Recommended AI Method: {method}")157        st.write(f"### Reasoning: {rationale}")158 159        # Store response in FAISS index160        store_response(st.session_state.responses)161 162        # Visualize the decision tree163        visualize_decision_tree(st.session_state.responses, method, rationale)