File size: 29,676 Bytes
f4ad05c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
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"]}')