RAHULJUNEJA33 commited on
Commit
e41598d
Β·
verified Β·
1 Parent(s): ab76f75

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +163 -0
app.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from faiss import IndexFlatL2
3
+ import numpy as np
4
+ from transformers import T5Tokenizer, T5ForConditionalGeneration
5
+ from graphviz import Digraph
6
+ import torch
7
+
8
+ # Initialize T5 model for both summarization and feature extraction
9
+ tokenizer = T5Tokenizer.from_pretrained("t5-large")
10
+ model = T5ForConditionalGeneration.from_pretrained("t5-large")
11
+
12
+ # Initialize FAISS index
13
+ index = IndexFlatL2(1024) # T5 embeddings are 1024-dimensional
14
+ responses = [] # Store responses for FAISS
15
+
16
+ # Streamlit page setup
17
+ st.title("Banking AI Decision-Making Assistant πŸ€–")
18
+ st.markdown("""
19
+ ### **Understanding AI Reasoning Methods**
20
+ Before 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 user
32
+ st.markdown("### **Describe Your Banking Use Case:**")
33
+ use_case = st.text_area("Enter your banking use case:")
34
+
35
+ # Initialize session state for responses
36
+ if 'responses' not in st.session_state:
37
+ st.session_state.responses = {}
38
+
39
+ # Collect responses from user - checkboxes for independent selection
40
+ st.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
+
46
+ st.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
+
52
+ st.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
+
58
+ st.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
+
64
+ st.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
+
70
+ st.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 responses
77
+ def 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)", rationale
82
+ 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)", rationale
85
+ elif responses['user_feedback']:
86
+ rationale = "Yes, this involves dynamic user feedback handling."
87
+ return "ReAct (Reasoning + Acting)", rationale
88
+ elif responses['security_concern']:
89
+ rationale = "Yes, there are concerns regarding data security and accuracy."
90
+ return "Self-Consistency (SC)", rationale
91
+ elif responses['automation_level']:
92
+ rationale = "Yes, this process requires a fully automated system with external tools."
93
+ return "PAL (Program-Aided LMs)", rationale
94
+ else:
95
+ rationale = "No, this decision-making is more straightforward and does not involve complex factors."
96
+ return "Chain-of-Thought (CoT)", rationale
97
+
98
+ # Function to store responses in FAISS index
99
+ def 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 inference
104
+ outputs = model.encoder(inputs["input_ids"]) # Encoder for feature extraction
105
+ embeddings = outputs.last_hidden_state.mean(dim=1).detach().numpy() # Use mean of hidden states as embedding
106
+
107
+ # Add the embeddings to the FAISS index
108
+ index.add(np.array(embeddings))
109
+
110
+ # Function to generate a decision tree visualization
111
+ def 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 nodes
124
+ 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 T5
135
+ def 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 summary
142
+ except Exception as e:
143
+ st.error(f"❌ Error generating summary: {e}")
144
+ return None
145
+
146
+ # Analyze button
147
+ if st.button("πŸ” Analyze Use Case"):
148
+ # Get summary of the use case
149
+ 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 method
155
+ 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 index
160
+ store_response(st.session_state.responses)
161
+
162
+ # Visualize the decision tree
163
+ visualize_decision_tree(st.session_state.responses, method, rationale)