Spaces:
Sleeping
Sleeping
Update app.py
Browse filesrevert to only using groq
app.py
CHANGED
|
@@ -2,319 +2,338 @@ import streamlit as st
|
|
| 2 |
import pandas as pd
|
| 3 |
import os
|
| 4 |
import warnings
|
|
|
|
| 5 |
import sqlite3
|
| 6 |
import shutil
|
| 7 |
-
import asyncio
|
| 8 |
-
import re
|
| 9 |
|
| 10 |
# ==========================================
|
| 11 |
-
#
|
| 12 |
# ==========================================
|
| 13 |
-
|
| 14 |
-
asyncio.get_running_loop()
|
| 15 |
-
except RuntimeError:
|
| 16 |
-
asyncio.set_event_loop(asyncio.new_event_loop())
|
| 17 |
|
| 18 |
-
#
|
| 19 |
-
# 1. CONFIG & IMPORTS
|
| 20 |
-
# ==========================================
|
| 21 |
-
st.set_page_config(page_title="Bank Loan Agent", layout="wide")
|
| 22 |
warnings.filterwarnings("ignore")
|
| 23 |
|
|
|
|
|
|
|
|
|
|
| 24 |
DB_FILE = "bank.db"
|
| 25 |
INDEX_PATH = "faiss_index"
|
| 26 |
REQUIRED_PDFS = ["Bank Loan Overall Risk Policy.pdf", "Bank Loan Interest Rate Policy.pdf"]
|
| 27 |
|
| 28 |
try:
|
| 29 |
-
# GROQ
|
| 30 |
from langchain_groq import ChatGroq
|
| 31 |
-
|
| 32 |
-
# GOOGLE (Native SDK)
|
| 33 |
-
import google.generativeai as genai
|
| 34 |
-
from google.generativeai.types import HarmCategory, HarmBlockThreshold
|
| 35 |
-
|
| 36 |
-
# SHARED
|
| 37 |
from langchain_huggingface import HuggingFaceEmbeddings
|
| 38 |
from langchain_community.vectorstores import FAISS
|
|
|
|
| 39 |
from langchain_community.document_loaders import PyPDFLoader
|
| 40 |
from langchain_text_splitters import CharacterTextSplitter
|
| 41 |
-
from langchain_core.prompts import
|
| 42 |
from langchain_core.runnables import RunnablePassthrough
|
| 43 |
from langchain_core.output_parsers import StrOutputParser
|
|
|
|
|
|
|
|
|
|
| 44 |
except ImportError as e:
|
| 45 |
-
st.error(f"β Import Error: {e}")
|
| 46 |
st.stop()
|
| 47 |
|
| 48 |
# ==========================================
|
| 49 |
-
#
|
| 50 |
# ==========================================
|
| 51 |
def init_db():
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
| 53 |
conn = sqlite3.connect(DB_FILE)
|
| 54 |
-
csv_files = {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
try:
|
| 56 |
for table, file in csv_files.items():
|
| 57 |
if os.path.exists(file):
|
| 58 |
df = pd.read_csv(file)
|
| 59 |
df.columns = [c.strip() for c in df.columns]
|
| 60 |
-
if 'ID' in df.columns:
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
init_db()
|
| 65 |
|
|
|
|
| 66 |
def run_query(query, params=()):
|
| 67 |
try:
|
| 68 |
with sqlite3.connect(DB_FILE) as conn:
|
| 69 |
cursor = conn.cursor()
|
| 70 |
cursor.execute(query, params)
|
| 71 |
return cursor.fetchone()
|
| 72 |
-
except Exception as e:
|
|
|
|
| 73 |
|
| 74 |
-
#
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
clean_id = ''.join(filter(str.isdigit, str(user_id)))
|
| 77 |
row = run_query("SELECT Credit_Score FROM credit_score WHERE ID = ?", (clean_id,))
|
| 78 |
-
|
|
|
|
|
|
|
| 79 |
|
| 80 |
-
|
|
|
|
|
|
|
| 81 |
clean_id = ''.join(filter(str.isdigit, str(user_id)))
|
| 82 |
-
row = run_query(
|
|
|
|
|
|
|
|
|
|
| 83 |
if row and not isinstance(row, str):
|
| 84 |
return f"Customer Name: {row[0]}, Nationality: {row[1]}, Status: {row[2]}, Email: {row[3]}"
|
| 85 |
-
return "User ID not found."
|
| 86 |
|
| 87 |
-
|
|
|
|
|
|
|
| 88 |
clean_id = ''.join(filter(str.isdigit, str(user_id)))
|
| 89 |
row = run_query("SELECT PR_Status FROM pr_status WHERE ID = ?", (clean_id,))
|
|
|
|
| 90 |
if not row or (isinstance(row, str) and "no such column" in row.lower()):
|
| 91 |
row = run_query("SELECT Is_PR FROM pr_status WHERE ID = ?", (clean_id,))
|
| 92 |
-
return f"PR Status: {row[0]}" if (row and not isinstance(row, str)) else "PR Status: False."
|
| 93 |
-
|
| 94 |
-
# ==========================================
|
| 95 |
-
# 3. HYBRID AGENT (Dynamic Model Loader)
|
| 96 |
-
# ==========================================
|
| 97 |
-
class HybridAgent:
|
| 98 |
-
def __init__(self, provider, api_key, tools_map, rag_chain):
|
| 99 |
-
self.provider = provider
|
| 100 |
-
self.api_key = api_key
|
| 101 |
-
self.tools = tools_map
|
| 102 |
-
self.rag_chain = rag_chain
|
| 103 |
-
self.max_steps = 8
|
| 104 |
-
self.gemini_model = None
|
| 105 |
-
|
| 106 |
-
# Initialize Groq
|
| 107 |
-
if "Groq" in provider:
|
| 108 |
-
self.groq_chat = ChatGroq(api_key=api_key, model_name="llama-3.3-70b-versatile", temperature=0)
|
| 109 |
-
|
| 110 |
-
# Initialize Gemini with DYNAMIC DISCOVERY
|
| 111 |
-
if "Google" in provider:
|
| 112 |
-
genai.configure(api_key=api_key)
|
| 113 |
-
self.gemini_model = self._find_best_gemini_model()
|
| 114 |
-
|
| 115 |
-
def _find_best_gemini_model(self):
|
| 116 |
-
"""Auto-detects which Gemini model is actually available to avoid 404s."""
|
| 117 |
-
try:
|
| 118 |
-
available_models = [m.name for m in genai.list_models() if 'generateContent' in m.supported_generation_methods]
|
| 119 |
-
|
| 120 |
-
# Priority 1: Flash (Fastest)
|
| 121 |
-
for m in available_models:
|
| 122 |
-
if "flash" in m and "1.5" in m: return genai.GenerativeModel(m)
|
| 123 |
-
|
| 124 |
-
# Priority 2: Pro 1.5
|
| 125 |
-
for m in available_models:
|
| 126 |
-
if "pro" in m and "1.5" in m: return genai.GenerativeModel(m)
|
| 127 |
-
|
| 128 |
-
# Priority 3: Pro 1.0 / Standard
|
| 129 |
-
for m in available_models:
|
| 130 |
-
if "gemini-pro" in m: return genai.GenerativeModel(m)
|
| 131 |
-
|
| 132 |
-
# Fallback: Just take the first one
|
| 133 |
-
if available_models: return genai.GenerativeModel(available_models[0])
|
| 134 |
-
|
| 135 |
-
return genai.GenerativeModel('gemini-pro') # Blind hope
|
| 136 |
-
except:
|
| 137 |
-
return genai.GenerativeModel('gemini-1.5-flash') # Default
|
| 138 |
-
|
| 139 |
-
def call_llm(self, prompt):
|
| 140 |
-
if "Groq" in self.provider:
|
| 141 |
-
return self.groq_chat.invoke(prompt).content
|
| 142 |
-
else:
|
| 143 |
-
try:
|
| 144 |
-
# Disable safety to prevent "list index out of range" errors
|
| 145 |
-
safety = {
|
| 146 |
-
HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,
|
| 147 |
-
HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE,
|
| 148 |
-
HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE,
|
| 149 |
-
HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
|
| 150 |
-
}
|
| 151 |
-
response = self.gemini_model.generate_content(prompt, safety_settings=safety)
|
| 152 |
-
return response.text
|
| 153 |
-
except Exception as e:
|
| 154 |
-
return f"Gemini Error: {str(e)}"
|
| 155 |
-
|
| 156 |
-
def run(self, query):
|
| 157 |
-
tool_desc = "\n".join([f"- {name}: {func.__doc__}" for name, func in self.tools.items()])
|
| 158 |
-
|
| 159 |
-
history = f"""You are a Loan Officer. Solve this request: "{query}"
|
| 160 |
-
|
| 161 |
-
TOOLS AVAILABLE:
|
| 162 |
-
{tool_desc}
|
| 163 |
-
- consult_policy_doc: Search PDF policies. Input: question string.
|
| 164 |
-
|
| 165 |
-
RULES:
|
| 166 |
-
1. You run in a loop. OUTPUT ONLY ONE STEP AT A TIME.
|
| 167 |
-
2. Format:
|
| 168 |
-
Thought: <reasoning>
|
| 169 |
-
Action: <tool_name>
|
| 170 |
-
Action Input: <input_string>
|
| 171 |
-
Observation: <result>
|
| 172 |
-
...
|
| 173 |
-
Final Answer: <the full report>
|
| 174 |
-
|
| 175 |
-
Begin!
|
| 176 |
-
"""
|
| 177 |
-
logs = []
|
| 178 |
-
|
| 179 |
-
for i in range(self.max_steps):
|
| 180 |
-
response = self.call_llm(history)
|
| 181 |
-
history += response + "\n"
|
| 182 |
-
|
| 183 |
-
if "Final Answer:" in response:
|
| 184 |
-
return response.split("Final Answer:")[-1].strip(), logs
|
| 185 |
-
|
| 186 |
-
action_match = re.search(r"Action:\s*(.+)", response)
|
| 187 |
-
input_match = re.search(r"Action Input:\s*(.+)", response)
|
| 188 |
-
|
| 189 |
-
if action_match and input_match:
|
| 190 |
-
tool_name = action_match.group(1).strip()
|
| 191 |
-
val = input_match.group(1).strip().strip('"').strip("'")
|
| 192 |
-
|
| 193 |
-
logs.append((tool_name, val))
|
| 194 |
-
|
| 195 |
-
result = "Error: Tool not found"
|
| 196 |
-
if tool_name in self.tools:
|
| 197 |
-
try: result = self.tools[tool_name](val)
|
| 198 |
-
except Exception as e: result = f"Error: {e}"
|
| 199 |
-
elif tool_name == "consult_policy_doc":
|
| 200 |
-
try: result = self.rag_chain.invoke(val)
|
| 201 |
-
except Exception as e: result = f"RAG Error: {e}"
|
| 202 |
-
|
| 203 |
-
history += f"Observation: {result}\n"
|
| 204 |
-
else:
|
| 205 |
-
if i == self.max_steps - 1: return response, logs
|
| 206 |
-
history += "Observation: Please continue. Use 'Final Answer:' when done.\n"
|
| 207 |
|
| 208 |
-
|
|
|
|
|
|
|
| 209 |
|
| 210 |
# ==========================================
|
| 211 |
-
#
|
| 212 |
# ==========================================
|
| 213 |
-
st.title("π€ Multi-
|
|
|
|
|
|
|
|
|
|
| 214 |
pdfs_missing = [f for f in REQUIRED_PDFS if not os.path.exists(f)]
|
| 215 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
with st.sidebar:
|
| 217 |
st.header("π Authentication")
|
| 218 |
-
provider_opt = st.radio("Model:", ["Groq (Llama-3)", "Google (Gemini)"])
|
| 219 |
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
st.error(f"Invalid: {e}")
|
| 243 |
else:
|
| 244 |
-
st.success("Active")
|
| 245 |
-
if st.button("
|
| 246 |
-
st.session_state
|
|
|
|
| 247 |
st.rerun()
|
| 248 |
|
| 249 |
-
|
| 250 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
st.cache_resource.clear()
|
|
|
|
|
|
|
| 252 |
st.rerun()
|
| 253 |
|
| 254 |
-
if st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
@st.cache_resource
|
| 256 |
def setup_rag():
|
| 257 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
|
|
|
|
| 259 |
if os.path.exists(INDEX_PATH):
|
| 260 |
return FAISS.load_local(INDEX_PATH, embeddings, allow_dangerous_deserialization=True).as_retriever()
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
|
| 282 |
-
|
| 283 |
-
|
| 284 |
|
| 285 |
col1, col2 = st.columns([1, 2])
|
| 286 |
with col1:
|
|
|
|
| 287 |
uid = st.text_input("Customer ID", "1111")
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
with col2:
|
| 294 |
if btn:
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
try:
|
| 302 |
-
|
| 303 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
except Exception as e:
|
| 305 |
-
st.error(f"
|
| 306 |
-
|
| 307 |
|
| 308 |
-
st.success("### Final
|
| 309 |
-
st.markdown(
|
| 310 |
-
|
| 311 |
-
with st.expander("Trace"):
|
| 312 |
-
for t, i in logs: st.write(f"**{t}**: {i}")
|
| 313 |
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
st.
|
| 318 |
|
| 319 |
-
|
| 320 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import pandas as pd
|
| 3 |
import os
|
| 4 |
import warnings
|
| 5 |
+
import time
|
| 6 |
import sqlite3
|
| 7 |
import shutil
|
|
|
|
|
|
|
| 8 |
|
| 9 |
# ==========================================
|
| 10 |
+
# 1. PAGE CONFIG (MUST BE FIRST)
|
| 11 |
# ==========================================
|
| 12 |
+
st.set_page_config(page_title="Bank Loan Agent (SQL)", layout="wide")
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
# Suppress warnings
|
|
|
|
|
|
|
|
|
|
| 15 |
warnings.filterwarnings("ignore")
|
| 16 |
|
| 17 |
+
# ==========================================
|
| 18 |
+
# 2. GLOBAL CONSTANTS & IMPORTS
|
| 19 |
+
# ==========================================
|
| 20 |
DB_FILE = "bank.db"
|
| 21 |
INDEX_PATH = "faiss_index"
|
| 22 |
REQUIRED_PDFS = ["Bank Loan Overall Risk Policy.pdf", "Bank Loan Interest Rate Policy.pdf"]
|
| 23 |
|
| 24 |
try:
|
|
|
|
| 25 |
from langchain_groq import ChatGroq
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
from langchain_huggingface import HuggingFaceEmbeddings
|
| 27 |
from langchain_community.vectorstores import FAISS
|
| 28 |
+
from langchain_community.callbacks import StreamlitCallbackHandler
|
| 29 |
from langchain_community.document_loaders import PyPDFLoader
|
| 30 |
from langchain_text_splitters import CharacterTextSplitter
|
| 31 |
+
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
| 32 |
from langchain_core.runnables import RunnablePassthrough
|
| 33 |
from langchain_core.output_parsers import StrOutputParser
|
| 34 |
+
from langchain_core.tools import tool
|
| 35 |
+
from langchain.agents import AgentExecutor, create_tool_calling_agent
|
| 36 |
+
|
| 37 |
except ImportError as e:
|
| 38 |
+
st.error(f"β Critical Import Error: {e}")
|
| 39 |
st.stop()
|
| 40 |
|
| 41 |
# ==========================================
|
| 42 |
+
# 3. DATABASE SETUP
|
| 43 |
# ==========================================
|
| 44 |
def init_db():
|
| 45 |
+
"""Converts CSV files to SQLite DB. Handles errors gracefully."""
|
| 46 |
+
if os.path.exists(DB_FILE):
|
| 47 |
+
return
|
| 48 |
+
|
| 49 |
conn = sqlite3.connect(DB_FILE)
|
| 50 |
+
csv_files = {
|
| 51 |
+
"credit_score": "credit_score.csv",
|
| 52 |
+
"account_status": "account_status.csv",
|
| 53 |
+
"pr_status": "pr_status.csv"
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
try:
|
| 57 |
for table, file in csv_files.items():
|
| 58 |
if os.path.exists(file):
|
| 59 |
df = pd.read_csv(file)
|
| 60 |
df.columns = [c.strip() for c in df.columns]
|
| 61 |
+
if 'ID' in df.columns:
|
| 62 |
+
df['ID'] = df['ID'].astype(str)
|
| 63 |
+
|
| 64 |
+
try:
|
| 65 |
+
df.to_sql(table, conn, if_exists='replace', index=False)
|
| 66 |
+
except Exception:
|
| 67 |
+
pass
|
| 68 |
+
except Exception as e:
|
| 69 |
+
st.error(f"DB Init Error: {e}")
|
| 70 |
+
finally:
|
| 71 |
+
conn.close()
|
| 72 |
+
|
| 73 |
+
# Initialize DB on startup
|
| 74 |
init_db()
|
| 75 |
|
| 76 |
+
# Helper for SQL tools
|
| 77 |
def run_query(query, params=()):
|
| 78 |
try:
|
| 79 |
with sqlite3.connect(DB_FILE) as conn:
|
| 80 |
cursor = conn.cursor()
|
| 81 |
cursor.execute(query, params)
|
| 82 |
return cursor.fetchone()
|
| 83 |
+
except Exception as e:
|
| 84 |
+
return f"DB Error: {e}"
|
| 85 |
|
| 86 |
+
# ==========================================
|
| 87 |
+
# 4. DEFINE TOOLS
|
| 88 |
+
# ==========================================
|
| 89 |
+
|
| 90 |
+
@tool
|
| 91 |
+
def get_credit_score(user_id: str) -> str:
|
| 92 |
+
"""Queries SQL DB for Credit Score."""
|
| 93 |
clean_id = ''.join(filter(str.isdigit, str(user_id)))
|
| 94 |
row = run_query("SELECT Credit_Score FROM credit_score WHERE ID = ?", (clean_id,))
|
| 95 |
+
if row and not isinstance(row, str):
|
| 96 |
+
return f"Credit Score: {row[0]}"
|
| 97 |
+
return "User ID not found in Credit DB."
|
| 98 |
|
| 99 |
+
@tool
|
| 100 |
+
def get_account_status(user_id: str) -> str:
|
| 101 |
+
"""Queries SQL DB for Name, Nationality, Status, and Email."""
|
| 102 |
clean_id = ''.join(filter(str.isdigit, str(user_id)))
|
| 103 |
+
row = run_query(
|
| 104 |
+
"SELECT Name, Nationality, Account_Status, Email FROM account_status WHERE ID = ?",
|
| 105 |
+
(clean_id,)
|
| 106 |
+
)
|
| 107 |
if row and not isinstance(row, str):
|
| 108 |
return f"Customer Name: {row[0]}, Nationality: {row[1]}, Status: {row[2]}, Email: {row[3]}"
|
| 109 |
+
return "User ID not found in Account DB."
|
| 110 |
|
| 111 |
+
@tool
|
| 112 |
+
def check_pr_status(user_id: str) -> str:
|
| 113 |
+
"""Queries SQL DB for PR Status."""
|
| 114 |
clean_id = ''.join(filter(str.isdigit, str(user_id)))
|
| 115 |
row = run_query("SELECT PR_Status FROM pr_status WHERE ID = ?", (clean_id,))
|
| 116 |
+
|
| 117 |
if not row or (isinstance(row, str) and "no such column" in row.lower()):
|
| 118 |
row = run_query("SELECT Is_PR FROM pr_status WHERE ID = ?", (clean_id,))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
+
if row and not isinstance(row, str):
|
| 121 |
+
return f"PR Status: {row[0]}"
|
| 122 |
+
return "PR Status: False (Record not found)"
|
| 123 |
|
| 124 |
# ==========================================
|
| 125 |
+
# 5. STREAMLIT APP UI
|
| 126 |
# ==========================================
|
| 127 |
+
st.title("π€ Multi-Policy Loan Assessor (SQL + RAG)")
|
| 128 |
+
st.markdown("Agent connects to **SQLite Database** and **Persistent Vector Store**")
|
| 129 |
+
|
| 130 |
+
# Calculate missing PDFs globally so everyone can see it
|
| 131 |
pdfs_missing = [f for f in REQUIRED_PDFS if not os.path.exists(f)]
|
| 132 |
|
| 133 |
+
# --- METRICS FUNCTION ---
|
| 134 |
+
def update_metrics(placeholder):
|
| 135 |
+
manual_time = 15 * 60
|
| 136 |
+
if 'execution_time' in st.session_state:
|
| 137 |
+
ai_time = st.session_state.execution_time
|
| 138 |
+
time_saved = manual_time - ai_time
|
| 139 |
+
saved_pct = (time_saved / manual_time) * 100
|
| 140 |
+
with placeholder.container():
|
| 141 |
+
col_kpi1, col_kpi2 = st.columns(2)
|
| 142 |
+
col_kpi1.metric("AI Processing", f"{ai_time:.1f}s")
|
| 143 |
+
col_kpi2.metric("Time Saved", f"{time_saved/60:.1f} min", delta=f"{saved_pct:.1f}% faster")
|
| 144 |
+
|
| 145 |
+
# --- SIDEBAR ---
|
| 146 |
with st.sidebar:
|
| 147 |
st.header("π Authentication")
|
|
|
|
| 148 |
|
| 149 |
+
# Initialize Session State for Key
|
| 150 |
+
if 'is_key_valid' not in st.session_state:
|
| 151 |
+
st.session_state['is_key_valid'] = False
|
| 152 |
+
|
| 153 |
+
# MANUAL ENTRY ONLY (No Secret Check)
|
| 154 |
+
if not st.session_state['is_key_valid']:
|
| 155 |
+
api_key_input = st.text_input("Enter Groq API Key", type="password", key="input_key")
|
| 156 |
+
if st.button("Validate API Key"):
|
| 157 |
+
if not api_key_input:
|
| 158 |
+
st.error("β οΈ Please enter a key.")
|
| 159 |
+
else:
|
| 160 |
+
try:
|
| 161 |
+
with st.spinner("Validating..."):
|
| 162 |
+
test_llm = ChatGroq(api_key=api_key_input, model_name="llama-3.3-70b-versatile")
|
| 163 |
+
test_llm.invoke("Test")
|
| 164 |
+
st.session_state['groq_api_key'] = api_key_input
|
| 165 |
+
st.session_state['is_key_valid'] = True
|
| 166 |
+
st.success("β
Valid Key!")
|
| 167 |
+
time.sleep(0.5)
|
| 168 |
+
st.rerun()
|
| 169 |
+
except Exception as e:
|
| 170 |
+
st.error(f"β Invalid Key: {e}")
|
|
|
|
| 171 |
else:
|
| 172 |
+
st.success("β
API Key Active")
|
| 173 |
+
if st.button("π΄ Reset Key"):
|
| 174 |
+
st.session_state['is_key_valid'] = False
|
| 175 |
+
st.session_state['groq_api_key'] = None
|
| 176 |
st.rerun()
|
| 177 |
|
| 178 |
+
st.divider()
|
| 179 |
+
st.subheader("π οΈ System Maintenance")
|
| 180 |
+
|
| 181 |
+
if st.button("β»οΈ Rebuild Knowledge Base"):
|
| 182 |
+
if os.path.exists(INDEX_PATH):
|
| 183 |
+
shutil.rmtree(INDEX_PATH)
|
| 184 |
st.cache_resource.clear()
|
| 185 |
+
st.success("Cache cleared.")
|
| 186 |
+
time.sleep(1)
|
| 187 |
st.rerun()
|
| 188 |
|
| 189 |
+
if st.button("πΎ Reload CSVs to DB"):
|
| 190 |
+
if os.path.exists(DB_FILE):
|
| 191 |
+
os.remove(DB_FILE)
|
| 192 |
+
init_db()
|
| 193 |
+
st.success("Database refreshed.")
|
| 194 |
+
|
| 195 |
+
st.divider()
|
| 196 |
+
|
| 197 |
+
if os.path.exists(DB_FILE) and not pdfs_missing:
|
| 198 |
+
st.success("β
System Ready")
|
| 199 |
+
else:
|
| 200 |
+
st.warning(f"β οΈ Missing: {pdfs_missing}")
|
| 201 |
+
|
| 202 |
+
st.header("π Metrics")
|
| 203 |
+
metrics_placeholder = st.empty()
|
| 204 |
+
update_metrics(metrics_placeholder)
|
| 205 |
+
|
| 206 |
+
# --- MAIN LOGIC ---
|
| 207 |
+
if st.session_state.get('is_key_valid', False):
|
| 208 |
+
|
| 209 |
+
os.environ["GROQ_API_KEY"] = st.session_state['groq_api_key']
|
| 210 |
+
|
| 211 |
+
# --- RAG SETUP ---
|
| 212 |
@st.cache_resource
|
| 213 |
def setup_rag():
|
| 214 |
+
# Check global variable here
|
| 215 |
+
if pdfs_missing:
|
| 216 |
+
st.error(f"Missing PDFs: {pdfs_missing}")
|
| 217 |
+
st.stop()
|
| 218 |
+
|
| 219 |
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
|
| 220 |
+
|
| 221 |
if os.path.exists(INDEX_PATH):
|
| 222 |
return FAISS.load_local(INDEX_PATH, embeddings, allow_dangerous_deserialization=True).as_retriever()
|
| 223 |
+
else:
|
| 224 |
+
documents = []
|
| 225 |
+
for pdf_file in REQUIRED_PDFS:
|
| 226 |
+
loader = PyPDFLoader(pdf_file)
|
| 227 |
+
documents.extend(loader.load())
|
| 228 |
+
|
| 229 |
+
text_splitter = CharacterTextSplitter(chunk_size=600, chunk_overlap=50)
|
| 230 |
+
final_docs = text_splitter.split_documents(documents)
|
| 231 |
+
|
| 232 |
+
vectorstore = FAISS.from_documents(final_docs, embeddings)
|
| 233 |
+
vectorstore.save_local(INDEX_PATH)
|
| 234 |
+
return vectorstore.as_retriever()
|
| 235 |
+
|
| 236 |
+
with st.spinner("Initializing AI..."):
|
| 237 |
+
retriever = setup_rag()
|
| 238 |
+
|
| 239 |
+
llm = ChatGroq(temperature=0, model_name="llama-3.3-70b-versatile")
|
| 240 |
+
|
| 241 |
+
rag_prompt = ChatPromptTemplate.from_template("Answer based on context:\n{context}\nQuestion: {question}")
|
| 242 |
+
rag_chain = (
|
| 243 |
+
{"context": retriever | (lambda d: "\n".join([x.page_content for x in d])), "question": RunnablePassthrough()}
|
| 244 |
+
| rag_prompt | llm | StrOutputParser()
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
@tool
|
| 248 |
+
def consult_policy_doc(query: str) -> str:
|
| 249 |
+
"""Consults Policy Documents for Risk Rules."""
|
| 250 |
+
return rag_chain.invoke(query)
|
| 251 |
+
|
| 252 |
+
tools = [get_credit_score, get_account_status, check_pr_status, consult_policy_doc]
|
| 253 |
+
|
| 254 |
+
prompt = ChatPromptTemplate.from_messages([
|
| 255 |
+
("system", "You are a Loan Risk Officer. Query SQL DB for customer info. Consult Policy Docs for rules."),
|
| 256 |
+
("human", "{input}"),
|
| 257 |
+
MessagesPlaceholder(variable_name="agent_scratchpad"),
|
| 258 |
+
])
|
| 259 |
|
| 260 |
+
agent = create_tool_calling_agent(llm, tools, prompt)
|
| 261 |
+
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, return_intermediate_steps=True)
|
| 262 |
|
| 263 |
col1, col2 = st.columns([1, 2])
|
| 264 |
with col1:
|
| 265 |
+
st.subheader("1. Customer Details")
|
| 266 |
uid = st.text_input("Customer ID", "1111")
|
| 267 |
+
use_simulation = st.checkbox("Simulation Mode")
|
| 268 |
+
|
| 269 |
+
sim_score = 650
|
| 270 |
+
sim_status = "good-standing"
|
| 271 |
+
if use_simulation:
|
| 272 |
+
sim_score = st.slider("Sim Credit Score", 300, 900, 450)
|
| 273 |
+
sim_status = st.selectbox("Sim Status", ["good-standing", "closed", "delinquent"])
|
| 274 |
+
|
| 275 |
+
st.divider()
|
| 276 |
+
btn = st.button("Assess Loan Risk", type="primary")
|
| 277 |
+
|
| 278 |
with col2:
|
| 279 |
if btn:
|
| 280 |
+
if use_simulation:
|
| 281 |
+
query = f"""
|
| 282 |
+
Process Loan for Customer ID: {uid}.
|
| 283 |
+
*** SIMULATION MODE ***
|
| 284 |
+
1. DO NOT query 'get_credit_score' or 'account_status' for Score/Status.
|
| 285 |
+
2. USE: Score: {sim_score}, Status: {sim_status}
|
| 286 |
+
3. Query 'get_account_status' ONLY for Name/Nationality.
|
| 287 |
+
4. Consult Policy Docs for risk/rates.
|
| 288 |
+
5. Provide a Final Recommendation Report that MUST include:
|
| 289 |
+
- Customer Name, ID, Email
|
| 290 |
+
- Risk Level, Interest Rate
|
| 291 |
+
- Final Decision (Approve/Reject)
|
| 292 |
+
- Justification for Decision (Cite specific PDF policies)
|
| 293 |
+
- Format in a clear markdown table.
|
| 294 |
+
"""
|
| 295 |
+
else:
|
| 296 |
+
query = f"""
|
| 297 |
+
Process Loan for Customer ID: {uid}.
|
| 298 |
+
1. Query SQL tools for Name, Email, Nationality, Status, Score.
|
| 299 |
+
2. IF Nationality is 'Singaporean', SKIP 'check_pr_status'.
|
| 300 |
+
3. Consult Policy Docs for risk/rates.
|
| 301 |
+
4. Provide a Final Recommendation Report that MUST include:
|
| 302 |
+
- Customer Name, ID, Email
|
| 303 |
+
- Risk Level, Interest Rate
|
| 304 |
+
- Final Decision (Approve/Reject)
|
| 305 |
+
- Justification for Decision (Cite specific PDF policies)
|
| 306 |
+
- Format in a clear markdown table.
|
| 307 |
+
"""
|
| 308 |
+
|
| 309 |
+
with st.status("π€ Agent is processing...", expanded=True) as status:
|
| 310 |
+
st_callback = StreamlitCallbackHandler(st.container())
|
| 311 |
try:
|
| 312 |
+
start_time = time.time()
|
| 313 |
+
res = agent_executor.invoke({"input": query}, {"callbacks": [st_callback]})
|
| 314 |
+
end_time = time.time()
|
| 315 |
+
st.session_state.execution_time = end_time - start_time
|
| 316 |
+
update_metrics(metrics_placeholder)
|
| 317 |
+
status.update(label="β
Complete!", state="complete", expanded=False)
|
| 318 |
except Exception as e:
|
| 319 |
+
st.error(f"Error: {e}")
|
| 320 |
+
st.stop()
|
| 321 |
|
| 322 |
+
st.success("### π Final Recommendation")
|
| 323 |
+
st.markdown(res['output'])
|
|
|
|
|
|
|
|
|
|
| 324 |
|
| 325 |
+
with st.expander("π Detailed Trace"):
|
| 326 |
+
steps = res.get("intermediate_steps", [])
|
| 327 |
+
for i, (action, observation) in enumerate(steps):
|
| 328 |
+
st.markdown(f"**Step {i+1}:** Tool `{action.tool}` | Output: `{observation}`")
|
| 329 |
|
| 330 |
+
if not use_simulation:
|
| 331 |
+
st.divider()
|
| 332 |
+
with st.expander("βοΈ Draft Email"):
|
| 333 |
+
email_prompt = f"Write a formal email based on this decision: {res['output']}"
|
| 334 |
+
with st.spinner("Drafting..."):
|
| 335 |
+
email_draft = llm.invoke(email_prompt).content
|
| 336 |
+
st.text_area("Email Draft", value=email_draft, height=200)
|
| 337 |
+
|
| 338 |
+
elif not st.session_state.get('is_key_valid', False):
|
| 339 |
+
st.info("π Please validate your Groq API Key.")
|