VAH6002's picture
Create app.py
f4ad05c verified
Raw History Blame Contribute Delete
29.7 kB
import streamlit as st
import pandas as pd
import json
import os
import time
from datetime import datetime
import random
from typing import List, Dict, Any, Tuple
import uuid
import matplotlib.pyplot as plt
import networkx as nx
from PIL import Image
from io import BytesIO
import base64
# Simulated API libraries - in production these would be real connectors
class OracleConnector:
def query(self, sql):
# Simulates querying legacy Oracle database
time.sleep(0.5) # Simulate network latency
if "customer" in sql.lower() and "account" in sql.lower():
return pd.DataFrame({
'customer_id': [1001, 1002, 1003, 1004, 1005],
'name': ['John Smith', 'Sarah Johnson', 'Michael Lee', 'Emma Davis', 'Robert Wilson'],
'risk_score': [65, 42, 78, 31, 92],
'account_balance': [120000, 45000, 67000, 18000, 250000],
'account_age_years': [8, 2, 5, 1, 12]
})
return pd.DataFrame() # Empty result for other queries
class PostgreSQLConnector:
def query(self, sql):
# Simulates querying AWS RDS PostgreSQL
time.sleep(0.3)
if "loan" in sql.lower():
return pd.DataFrame({
'customer_id': [1001, 1003, 1005, 1002, 1004],
'loan_id': ['L-7734', 'L-9982', 'L-2341', 'L-6654', 'L-1122'],
'loan_type': ['Mortgage', 'Auto', 'Personal', 'Mortgage', 'Credit Line'],
'loan_amount': [320000, 45000, 15000, 275000, 10000],
'interest_rate': [3.2, 4.5, 7.8, 3.1, 9.9],
'payment_status': ['Current', 'Current', 'Late30', 'Current', 'Current']
})
return pd.DataFrame()
class MongoDBConnector:
def query(self, query_dict):
# Simulates querying MongoDB for customer interactions
time.sleep(0.4)
if "customer_interactions" in str(query_dict):
return pd.DataFrame({
'customer_id': [1001, 1001, 1002, 1003, 1004, 1005, 1005],
'interaction_type': ['complaint', 'inquiry', 'inquiry', 'complaint', 'feedback', 'complaint', 'complaint'],
'channel': ['phone', 'email', 'web', 'branch', 'app', 'phone', 'email'],
'date': ['2023-10-12', '2023-11-03', '2023-09-18', '2023-10-30', '2023-11-15', '2023-08-22', '2023-10-05'],
'sentiment': ['negative', 'neutral', 'positive', 'negative', 'positive', 'negative', 'negative']
})
return pd.DataFrame()
class AzureBlobConnector:
def get_documents(self, customer_id):
# Simulates retrieving documents from Azure Blob Storage
time.sleep(0.6)
docs = {
1001: ["Mortgage agreement", "Identity verification"],
1002: ["Identity verification", "Proof of income"],
1003: ["Auto loan agreement", "Credit check"],
1004: ["Identity verification"],
1005: ["Mortgage agreement", "Investment portfolio", "Risk disclosure acknowledgment"]
}
return docs.get(customer_id, [])
class SalesforceConnector:
def query(self, soql):
# Simulates querying Salesforce for CRM data
time.sleep(0.5)
if "contact" in soql.lower():
return pd.DataFrame({
'customer_id': [1001, 1002, 1003, 1004, 1005],
'customer_segment': ['Premium', 'Standard', 'Premium', 'Standard', 'Private Banking'],
'relationship_manager': ['Alice Thompson', 'Bob Jenkins', 'Alice Thompson', 'Charlie Davis', 'Diana Wilson'],
'acquisition_date': ['2015-03-15', '2021-08-22', '2018-05-10', '2022-11-03', '2010-01-18'],
'lifetime_value': [125000, 12000, 78000, 5000, 320000]
})
return pd.DataFrame()
# Simulated LLM API for various levels of reasoning
class LLMClient:
def simple_completion(self, prompt):
time.sleep(0.5) # Simulate API latency
return f"Processed: {prompt[:50]}..."
def tool_using_completion(self, prompt, tools):
time.sleep(0.7)
# Simulate an LLM that can use tools
if "risk" in prompt.lower() and "customer" in prompt.lower():
return {
"thought": "I need to retrieve customer risk information from multiple sources",
"action": "query_oracle_database",
"action_input": "SELECT customer_id, name, risk_score FROM customer_accounts"
}
return {"thought": "I'm not sure how to proceed with this query", "action": None}
def reasoning_completion(self, prompt, context=None):
time.sleep(1.0)
# Simulate a more advanced reasoning model
if "high risk" in prompt.lower():
reasoning = """
To identify high-risk customers, I need to:
1. Get risk scores from the core banking system
2. Check loan payment status from the loan database
3. Analyze customer complaints from the interaction database
4. Look for risk disclosure documents in document storage
5. Check customer segment information from CRM
I'll consider a customer high-risk if they have at least two of:
- Risk score > 70
- Late loan payments
- Multiple complaints
- Missing risk disclosure documents
- In Private Banking segment (larger exposure)
"""
return {"reasoning": reasoning, "next_step": "retrieve_risk_scores"}
return {"reasoning": "I need more context to answer this question", "next_step": "ask_clarification"}
def autonomous_completion(self, situation, history=None):
time.sleep(1.2)
# Simulate a model that can take autonomous actions
actions = [
"I'll proactively run a daily scan of all high-risk customers",
"I'll alert risk officers about any customers with sudden changes in risk profiles",
"I notice customer 1005 has a very high risk score (92), multiple complaints, and is in Private Banking - flagging for immediate review",
"Based on historical patterns, I recommend focusing on mortgage customers with recent complaints"
]
return random.choice(actions)
def self_improving_completion(self, task, performance_metrics=None):
time.sleep(1.5)
improvements = [
"I've identified that MongoDB queries are taking longer than SQL queries. Implementing connection pooling for MongoDB.",
"I've created a cached query layer for frequently accessed customer data, reducing latency by 35%",
"I'm developing a specialized risk assessment workflow based on the patterns observed in 500+ risk officer queries",
"I've added a new data connector for Thomson Reuters risk data to enrich our analysis capabilities"
]
return {"improvement": random.choice(improvements), "new_workflow_created": True}
# Utility function to create a small network graph visualization
def create_graph(level):
G = nx.DiGraph()
if level >= 0: # L0: Simple connections
G.add_node("User", pos=(0, 0))
G.add_node("API Gateway", pos=(1, 0))
G.add_edge("User", "API Gateway")
if level >= 1: # L1: Basic tool use
G.add_node("LLM", pos=(2, 0))
G.add_node("Tool Router", pos=(3, 0))
G.add_edge("API Gateway", "LLM")
G.add_edge("LLM", "Tool Router")
if level >= 2: # L2: Reasoning and planning
G.add_node("Planning Module", pos=(2, 1))
G.add_node("Memory System", pos=(3, 1))
G.add_edge("LLM", "Planning Module")
G.add_edge("Planning Module", "LLM")
G.add_edge("LLM", "Memory System")
G.add_edge("Memory System", "LLM")
if level >= 3: # L3: Autonomous actions
G.add_node("Autonomous Agent", pos=(4, 0))
G.add_node("Monitoring System", pos=(4, 1))
G.add_edge("Tool Router", "Autonomous Agent")
G.add_edge("Autonomous Agent", "Monitoring System")
G.add_edge("Monitoring System", "LLM")
if level >= 4: # L4: Self-improvement
G.add_node("Workflow Creator", pos=(5, 0))
G.add_node("Performance Analyzer", pos=(5, 1))
G.add_edge("Autonomous Agent", "Workflow Creator")
G.add_edge("Monitoring System", "Performance Analyzer")
G.add_edge("Performance Analyzer", "Workflow Creator")
G.add_edge("Workflow Creator", "LLM")
# Add data sources at all levels
datasources = ["Oracle DB", "PostgreSQL", "MongoDB", "Azure Blob", "Salesforce"]
for i, source in enumerate(datasources):
G.add_node(source, pos=(i+1, -1))
if level == 0:
G.add_edge("API Gateway", source)
else:
G.add_edge("Tool Router", source)
# Create matplotlib figure
plt.figure(figsize=(10, 6))
pos = nx.get_node_attributes(G, 'pos')
nx.draw(G, pos, with_labels=True, node_size=1500, node_color="lightblue",
font_size=8, font_weight="bold", arrows=True, arrowsize=15)
# Convert plot to image
buf = BytesIO()
plt.savefig(buf, format="png")
buf.seek(0)
img = Image.open(buf)
return img
# ------------------- STREAMLIT APP ----------------------
st.set_page_config(page_title="Banking Data Agent", layout="wide")
st.title("Banking Data Agent: Solving Multi-Source Data Challenges")
st.markdown("""
This application demonstrates how different levels of AI agency can help banks integrate and query data
across fragmented systems resulting from mergers, acquisitions, and legacy infrastructure.
""")
# Initialize connectors
if 'connectors' not in st.session_state:
st.session_state.connectors = {
'oracle': OracleConnector(),
'postgres': PostgreSQLConnector(),
'mongodb': MongoDBConnector(),
'azure_blob': AzureBlobConnector(),
'salesforce': SalesforceConnector()
}
if 'llm' not in st.session_state:
st.session_state.llm = LLMClient()
if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
# Agency level selection
level_descriptions = {
0: "L0: No decision-making, simple API calls",
1: "L1: Basic tool use and decision-making",
2: "L2: Structured reasoning and sequential planning",
3: "L3: Autonomous, proactive actions without user prompts",
4: "L4: Self-improving AI that creates workflows and utilities"
}
level = st.sidebar.selectbox(
"Select Agent Level",
list(range(5)),
format_func=lambda x: level_descriptions[x]
)
# Show architecture diagram based on level
st.sidebar.subheader("System Architecture")
architecture_img = create_graph(level)
st.sidebar.image(architecture_img)
# Simulated data sources section
st.sidebar.subheader("Connected Data Sources")
with st.sidebar.expander("View All Data Sources"):
st.write("πŸ—„οΈ Oracle Database (Legacy Core Banking)")
st.write("πŸ—„οΈ AWS RDS PostgreSQL (Loan Management)")
st.write("πŸ—„οΈ MongoDB (Customer Interactions)")
st.write("πŸ—„οΈ Azure Blob Storage (Document Management)")
st.write("πŸ—„οΈ Salesforce (CRM & Customer Data)")
# Main query interface
st.header("Risk Officer Query Interface")
with st.form("query_form"):
query = st.text_area("Enter your query:", placeholder="e.g., Show me all high-risk customers with recent complaints")
submitted = st.form_submit_button("Submit Query")
if submitted and query:
# Display thinking animation
with st.spinner("Processing your request..."):
# Add user query to history
st.session_state.chat_history.append({"role": "user", "content": query})
# Process based on agency level
if level == 0:
# L0: Simple API calls without decision making
st.subheader("Level 0: Simple API Calls")
# Create tabs for each data source
tabs = st.tabs(["Oracle", "PostgreSQL", "MongoDB", "Azure Blob", "Salesforce"])
with tabs[0]:
st.write("Querying Oracle Database...")
oracle_data = st.session_state.connectors['oracle'].query("SELECT * FROM customer_accounts")
st.dataframe(oracle_data)
with tabs[1]:
st.write("Querying PostgreSQL Database...")
postgres_data = st.session_state.connectors['postgres'].query("SELECT * FROM loans")
st.dataframe(postgres_data)
with tabs[2]:
st.write("Querying MongoDB...")
mongo_data = st.session_state.connectors['mongodb'].query({"collection": "customer_interactions"})
st.dataframe(mongo_data)
with tabs[3]:
st.write("Cannot query documents without specific customer ID")
with tabs[4]:
st.write("Querying Salesforce...")
sf_data = st.session_state.connectors['salesforce'].query("SELECT * FROM contact")
st.dataframe(sf_data)
# Add response to history
response = "Here are the raw results from each system. You'll need to manually combine them to find your answer."
st.session_state.chat_history.append({"role": "assistant", "content": response})
elif level == 1:
# L1: Basic tool use and decision-making
st.subheader("Level 1: Basic Tool Use")
# Simulate LLM using tools
tool_response = st.session_state.llm.tool_using_completion(query, ["query_database", "retrieve_documents"])
st.write("πŸ€” AI Thought:", tool_response["thought"])
st.write("πŸ”§ Tool Selected:", tool_response["action"] if tool_response["action"] else "None")
if tool_response["action"] == "query_oracle_database":
st.write("Executing Oracle database query...")
oracle_data = st.session_state.connectors['oracle'].query(tool_response["action_input"])
st.dataframe(oracle_data)
# Further processing based on results
st.write("πŸ€” AI Thought: Now that I have risk scores, I should check loan payment status")
st.write("πŸ”§ Tool Selected: query_postgres_database")
postgres_data = st.session_state.connectors['postgres'].query("SELECT customer_id, loan_id, payment_status FROM loans")
st.dataframe(postgres_data)
# Simple merge of datasets
merged_data = pd.merge(oracle_data, postgres_data, on="customer_id", how="left")
st.subheader("Preliminary Results")
st.dataframe(merged_data)
# Add response to history
response = "I've retrieved and merged risk scores and loan payment status. Based on this data, customers 1003 and 1005 appear to have elevated risk levels."
st.session_state.chat_history.append({"role": "assistant", "content": response})
else:
# Add response to history
response = "I'm not sure how to process this query with my current tools."
st.session_state.chat_history.append({"role": "assistant", "content": response})
elif level == 2:
# L2: Structured reasoning and sequential planning
st.subheader("Level 2: Structured Reasoning & Planning")
# Show reasoning process
reasoning_response = st.session_state.llm.reasoning_completion(query)
st.write("πŸ“ Reasoning Process:")
st.info(reasoning_response["reasoning"])
# Execute multi-step plan
st.write("πŸ”„ Executing multi-step plan...")
col1, col2 = st.columns(2)
with col1:
st.write("Step 1: Retrieve risk scores")
oracle_data = st.session_state.connectors['oracle'].query("SELECT customer_id, name, risk_score FROM customer_accounts")
high_risk_customers = oracle_data[oracle_data['risk_score'] > 70]
st.dataframe(high_risk_customers)
with col2:
st.write("Step 2: Check loan payment status")
postgres_data = st.session_state.connectors['postgres'].query("SELECT customer_id, loan_id, payment_status FROM loans")
late_payments = postgres_data[postgres_data['payment_status'].str.contains('Late')]
st.dataframe(late_payments)
col3, col4 = st.columns(2)
with col3:
st.write("Step 3: Analyze customer complaints")
mongo_data = st.session_state.connectors['mongodb'].query({"collection": "customer_interactions"})
complaints = mongo_data[mongo_data['interaction_type'] == 'complaint']
complaint_counts = complaints['customer_id'].value_counts().reset_index()
complaint_counts.columns = ['customer_id', 'complaint_count']
multiple_complaints = complaint_counts[complaint_counts['complaint_count'] > 1]
st.dataframe(multiple_complaints)
with col4:
st.write("Step 4: Check customer segments")
sf_data = st.session_state.connectors['salesforce'].query("SELECT customer_id, customer_segment FROM contact")
private_banking = sf_data[sf_data['customer_segment'] == 'Private Banking']
st.dataframe(private_banking)
# Comprehensive risk analysis by joining all data
st.subheader("Comprehensive Risk Analysis")
# Simulate a complex join and analysis
risk_factors = pd.DataFrame({
'customer_id': [1001, 1002, 1003, 1004, 1005],
'high_risk_score': [False, False, True, False, True],
'late_payments': [False, False, False, False, True],
'multiple_complaints': [False, False, False, False, True],
'private_banking': [False, False, False, False, True]
})
risk_factors['total_risk_factors'] = risk_factors.iloc[:, 1:].sum(axis=1)
high_risk = risk_factors[risk_factors['total_risk_factors'] >= 2]
st.dataframe(high_risk)
# Add customer names for clarity
high_risk_with_names = pd.merge(high_risk,
oracle_data[['customer_id', 'name']],
on='customer_id',
how='left')
st.subheader("High Risk Customers Identified")
st.table(high_risk_with_names[['customer_id', 'name', 'total_risk_factors']])
# Add response to history
response = f"""
Based on a comprehensive analysis across all systems, I've identified {len(high_risk)} high-risk customers who meet at least two risk criteria.
Customer 1005 (Robert Wilson) is the highest risk with 4/4 risk factors:
- High risk score (92)
- Late loan payments
- Multiple complaints
- Private Banking customer (higher exposure)
Customer 1003 (Michael Lee) is also flagged with 1/4 risk factors:
- High risk score (78)
Would you like me to prepare a detailed report on any of these customers?
"""
st.session_state.chat_history.append({"role": "assistant", "content": response})
elif level == 3:
# L3: Autonomous, proactive actions
st.subheader("Level 3: Autonomous Agent")
# Show autonomous thinking and actions
st.write("πŸ” Agent is autonomously monitoring systems...")
# Simulate previous interactions and monitoring
previous_observations = [
"Detected increase in risk score for customer 1005 from 85 to 92 in the last week",
"Customer 1005 has filed 2 complaints in the past month",
"New loan application detected for high-risk customer 1005"
]
for obs in previous_observations:
st.info(f"πŸ“Š Observation: {obs}")
time.sleep(0.5)
# Autonomous action based on the situation
autonomous_action = st.session_state.llm.autonomous_completion("high risk customer with new application")
st.warning(f"πŸ€– Autonomous Action: {autonomous_action}")
# Show detailed customer risk profile that was proactively prepared
st.subheader("Proactively Generated Risk Profile")
# Create tabs for different aspects of the profile
profile_tabs = st.tabs(["Overview", "Transactions", "Documents", "Interactions", "Recommendations"])
with profile_tabs[0]:
col1, col2 = st.columns(2)
with col1:
st.metric("Customer", "Robert Wilson (ID: 1005)")
st.metric("Risk Score", "92", "↑7")
st.metric("Customer Segment", "Private Banking")
with col2:
st.metric("Account Balance", "$250,000")
st.metric("Total Loan Exposure", "$15,000", "-$3,000")
st.metric("Account Age", "12 years")
with profile_tabs[1]:
st.write("Recent large transactions:")
transactions = pd.DataFrame({
'date': ['2023-10-15', '2023-10-22', '2023-11-01'],
'amount': ['$45,000', '$32,000', '$18,000'],
'type': ['Withdrawal', 'Wire Transfer', 'Withdrawal'],
'destination': ['Unknown', 'Offshore Account', 'Cash']
})
st.table(transactions)
with profile_tabs[2]:
st.write("Documents from Azure Blob Storage:")
for doc in st.session_state.connectors['azure_blob'].get_documents(1005):
st.write(f"- {doc}")
with profile_tabs[3]:
st.write("Recent customer interactions:")
interactions = st.session_state.connectors['mongodb'].query({"collection": "customer_interactions"})
customer_interactions = interactions[interactions['customer_id'] == 1005]
st.dataframe(customer_interactions)
with profile_tabs[4]:
st.write("Automated recommendations:")
st.write("1. Conduct enhanced due diligence review")
st.write("2. Schedule call with relationship manager (Diana Wilson)")
st.write("3. Request updated financial statements")
st.write("4. Review recent large withdrawals")
# Add response to history
response = f"""
I noticed several concerning patterns while monitoring our systems and have proactively prepared a risk analysis for Robert Wilson (ID: 1005).
Key findings:
- Risk score increased from 85 to 92 in the past week
- Two recent complaints through different channels
- Three large withdrawals/transfers in the past month
- One of the transfers was to an offshore account
This customer is in the Private Banking segment with significant exposure. I recommend immediate review of this account and have prepared a detailed report with recommended actions.
Would you like me to schedule a meeting with the relationship manager?
"""
st.session_state.chat_history.append({"role": "assistant", "content": response})
else: # level == 4
# L4: Self-improving AI
st.subheader("Level 4: Self-Improving Agent")
# Show system improvements
improvement = st.session_state.llm.self_improving_completion("optimize risk assessment", {"avg_query_time": 2.3, "accuracy": 0.89})
st.info(f"πŸ”„ System Improvement: {improvement['improvement']}")
# Show newly created workflow
st.subheader("Automatically Generated Workflow")
st.write("The agent has created a specialized workflow based on patterns in risk officer queries")
# Display the workflow diagram
workflow_stages = [
("Data Collection", "Parallel queries to all data sources with optimized connection pooling"),
("Risk Factor Extraction", "Extract 15 key risk indicators using fine-tuned model"),
("Pattern Analysis", "Compare to historical patterns of fraudulent activity"),
("Document Verification", "Check completeness of required documentation"),
("Risk Scoring", "Calculate composite risk score with confidence intervals"),
("Recommendation Engine", "Generate actionable recommendations"),
("Monitoring Setup", "Create personalized monitoring alerts")
]
for i, (stage, desc) in enumerate(workflow_stages):
col1, col2 = st.columns([1, 3])
with col1:
st.write(f"**Stage {i+1}**")
st.write(f"**{stage}**")
with col2:
st.write(desc)
# Don't add a separator after the last item
if i < len(workflow_stages) - 1:
st.write("↓")
# Show a sample newly discovered risk pattern
st.subheader("Newly Discovered Risk Pattern")
st.write("The agent has discovered this pattern through analysis of historical data")
pattern_data = pd.DataFrame({
'indicator': ['Multiple address changes', 'Frequent large round-number transactions',
'Interactions only through digital channels', 'Recently updated KYC documents',
'Multiple new beneficiaries added'],
'correlation_with_fraud': [0.68, 0.72, 0.53, 0.47, 0.81]
})
fig, ax = plt.subplots(figsize=(10, 5))
bars = ax.barh(pattern_data['indicator'], pattern_data['correlation_with_fraud'], color='skyblue')
ax.set_xlabel('Correlation with Fraudulent Activity')
ax.set_title('Newly Discovered Risk Indicators')
ax.axvline(x=0.5, color='red', linestyle='--')
plt.tight_layout()
st.pyplot(fig)
# Show performance improvements
st.subheader("Performance Improvements")
metrics = {
'Query Latency': [2.3, 0.8, '-65%'],
'Data Coverage': [76, 98, '+22%'],
'Risk Detection Rate': [82, 95, '+13%'],
'False Positive Rate': [15, 7, '-8%']
}
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Query Latency (s)", metrics['Query Latency'][1], metrics['Query Latency'][2])
with col2:
st.metric("Data Coverage (%)", metrics['Data Coverage'][1], metrics['Data Coverage'][2])
with col3:
st.metric("Risk Detection (%)", metrics['Risk Detection Rate'][1], metrics['Risk Detection Rate'][2])
with col4:
st.metric("False Positives (%)", metrics['False Positive Rate'][1], metrics['False Positive Rate'][2])
# Add response to history
response = f"""
I've analyzed our risk assessment processes and made several improvements:
1. Created a specialized risk assessment workflow optimized for our specific data sources
2. Discovered new risk indicators highly correlated with fraudulent activity
3. Improved system performance with 65% lower query latency and 22% better data coverage
4. Reduced false positives by 8% while increasing risk detection rate by 13%
Based on these improvements, I've identified a previously undetected pattern of high-risk activity in 7 customer accounts. Would you like me to present detailed findings for these accounts?
I'm continuing to refine my understanding and will develop further optimizations as I learn from user interactions and system performance.
"""
st.session_state.chat_history.append({"role": "assistant", "content": response})
# Display chat history
st.header("Conversation History")
for message in reversed(st.session_state.chat_history):
if message["role"] == "user":
st.write(f'πŸ‘€ **You**: {message["content"]}')
else:
st.write(f'πŸ€– **Assistant**: {message["content"]}')