This comprehensive example demonstrates how to use the Agent Governance SDK in a realistic banking environment with multiple specialized agents, tool calling, and compliance monitoring.

Overview

This example includes:
  • Personal Banking Agent: Handles account inquiries and basic transactions
  • Business Banking Agent: Manages business account services
  • Fraud Detection Agent: Monitors for suspicious activities
  • Loan Processing Agent: Handles loan applications and inquiries
Each agent has specialized tools and compliance settings appropriate for their role.

Complete Banking Implementation

import { AnthropicAgentMonitor } from '@agent-governance/node';
import Anthropic from '@anthropic-ai/sdk';

class BankingAgentSystem {
  constructor(config) {
    this.monitor = new AnthropicAgentMonitor({
      apiKey: config.governanceApiKey,
      organizationId: config.organizationId,
      environment: config.environment || 'production',
      enableComplianceChecks: true,
      enableLogging: config.enableLogging || false,
      batchSize: 250,
      flushInterval: 10000
    });

    this.anthropic = new Anthropic({
      apiKey: config.anthropicApiKey
    });

    this.agents = new Map();
  }

  async initialize() {
    // Register all banking agents
    await this.registerPersonalBankingAgent();
    await this.registerBusinessBankingAgent();
    await this.registerFraudDetectionAgent();
    await this.registerLoanProcessingAgent();

    console.log('✅ All banking agents registered successfully');
  }

  async registerPersonalBankingAgent() {
    const agentId = 'personal-banking-agent';

    await this.monitor.registerAgent({
      id: agentId,
      name: 'Personal Banking Assistant',
      category: 'tool_calling',
      specialty: 'personal_banking',
      version: '2.1.0',
      llmProvider: 'anthropic',
      model: 'claude-3-5-sonnet-20241022',
      description: 'AI assistant for personal banking services including account management, transfers, and general inquiries',
      systemPrompt: 'You are a helpful banking assistant specializing in personal banking. Always prioritize customer security and follow banking regulations.',
      availableTools: [
        {
          name: 'get_account_summary',
          description: 'Retrieves account balances and basic information',
          category: 'banking',
          riskLevel: 'medium'
        },
        {
          name: 'get_transaction_history',
          description: 'Shows recent transaction history',
          category: 'banking',
          riskLevel: 'medium'
        },
        {
          name: 'initiate_transfer',
          description: 'Initiates money transfers between accounts',
          category: 'banking',
          riskLevel: 'high'
        },
        {
          name: 'check_fraud_alerts',
          description: 'Checks for fraud alerts on account',
          category: 'security',
          riskLevel: 'high'
        }
      ],
      complianceSettings: {
        sr11_7_enabled: true,
        fair_lending_monitoring: false, // Not applicable for general banking
        bsa_aml_checks: true
      }
    });

    // Wrap the Anthropic client for this agent
    const monitoredClient = this.monitor.wrapAnthropic(this.anthropic, agentId);
    this.agents.set(agentId, monitoredClient);
  }

  async registerBusinessBankingAgent() {
    const agentId = 'business-banking-agent';

    await this.monitor.registerAgent({
      id: agentId,
      name: 'Business Banking Assistant',
      category: 'tool_calling',
      specialty: 'business_banking',
      version: '2.0.0',
      llmProvider: 'anthropic',
      model: 'claude-3-5-sonnet-20241022',
      description: 'AI assistant for business banking services including cash management, commercial lending, and business account services',
      availableTools: [
        {
          name: 'get_business_account_summary',
          description: 'Retrieves business account information',
          category: 'business_banking',
          riskLevel: 'medium'
        },
        {
          name: 'analyze_cash_flow',
          description: 'Analyzes business cash flow patterns',
          category: 'business_banking',
          riskLevel: 'medium'
        },
        {
          name: 'check_credit_facilities',
          description: 'Reviews available credit facilities',
          category: 'business_banking',
          riskLevel: 'high'
        }
      ],
      complianceSettings: {
        sr11_7_enabled: true,
        fair_lending_monitoring: true, // Important for business lending
        bsa_aml_checks: true
      }
    });

    const monitoredClient = this.monitor.wrapAnthropic(this.anthropic, agentId);
    this.agents.set(agentId, monitoredClient);
  }

  async registerFraudDetectionAgent() {
    const agentId = 'fraud-detection-agent';

    await this.monitor.registerAgent({
      id: agentId,
      name: 'Fraud Detection Assistant',
      category: 'autonomous',
      specialty: 'fraud_detection',
      version: '3.0.0',
      llmProvider: 'anthropic',
      model: 'claude-3-5-sonnet-20241022',
      description: 'AI assistant for fraud detection, investigation, and prevention',
      availableTools: [
        {
          name: 'analyze_transaction_patterns',
          description: 'Analyzes transaction patterns for anomalies',
          category: 'fraud_detection',
          riskLevel: 'high'
        },
        {
          name: 'check_device_fingerprint',
          description: 'Validates device and location information',
          category: 'security',
          riskLevel: 'medium'
        },
        {
          name: 'escalate_to_fraud_team',
          description: 'Escalates suspicious activity to human investigators',
          category: 'escalation',
          riskLevel: 'high'
        }
      ],
      complianceSettings: {
        sr11_7_enabled: true,
        fair_lending_monitoring: false,
        bsa_aml_checks: true
      }
    });

    const monitoredClient = this.monitor.wrapAnthropic(this.anthropic, agentId);
    this.agents.set(agentId, monitoredClient);
  }

  async registerLoanProcessingAgent() {
    const agentId = 'loan-processing-agent';

    await this.monitor.registerAgent({
      id: agentId,
      name: 'Loan Processing Assistant',
      category: 'tool_calling',
      specialty: 'mortgage_lending',
      version: '1.8.0',
      llmProvider: 'anthropic',
      model: 'claude-3-5-sonnet-20241022',
      description: 'AI assistant for loan applications, mortgage processing, and lending inquiries',
      availableTools: [
        {
          name: 'check_credit_score',
          description: 'Retrieves credit score and credit report',
          category: 'lending',
          riskLevel: 'high'
        },
        {
          name: 'calculate_loan_eligibility',
          description: 'Calculates loan eligibility and terms',
          category: 'lending',
          riskLevel: 'high'
        },
        {
          name: 'submit_loan_application',
          description: 'Submits completed loan application',
          category: 'lending',
          riskLevel: 'high'
        }
      ],
      complianceSettings: {
        sr11_7_enabled: true,
        fair_lending_monitoring: true, // Critical for lending
        bsa_aml_checks: true
      }
    });

    const monitoredClient = this.monitor.wrapAnthropic(this.anthropic, agentId);
    this.agents.set(agentId, monitoredClient);
  }

  // Personal Banking Interaction
  async handlePersonalBankingInquiry(customerId, inquiry, sessionId) {
    const agentId = 'personal-banking-agent';
    const agent = this.agents.get(agentId);

    try {
      this.monitor.trackConversationStart(agentId, sessionId, customerId, {
        channel: 'web_app',
        customerType: 'personal',
        inquiryType: 'account_management'
      });

      this.monitor.trackUserMessage(agentId, sessionId, inquiry, customerId);

      const response = await agent.messages.create({
        model: 'claude-3-5-sonnet-20241022',
        max_tokens: 1000,
        messages: [
          {
            role: 'system',
            content: 'You are a personal banking assistant. Help customers with account inquiries, transfers, and general banking questions. Always verify customer identity before providing account information.'
          },
          {
            role: 'user',
            content: inquiry
          }
        ],
        tools: this.getPersonalBankingTools(),
        sessionId: sessionId
      });

      // Handle tool calls if any
      if (this.hasToolCalls(response)) {
        return await this.processToolCalls(agentId, sessionId, response);
      }

      return response.content[0].text;

    } catch (error) {
      this.monitor.trackError(agentId, sessionId, error, {
        errorType: 'PersonalBankingError',
        severity: 'high',
        customerId: customerId
      });
      throw error;
    }
  }

  // Business Banking Interaction
  async handleBusinessBankingInquiry(businessId, inquiry, sessionId) {
    const agentId = 'business-banking-agent';
    const agent = this.agents.get(agentId);

    try {
      this.monitor.trackConversationStart(agentId, sessionId, businessId, {
        channel: 'business_portal',
        customerType: 'business',
        inquiryType: 'business_services'
      });

      this.monitor.trackUserMessage(agentId, sessionId, inquiry, businessId);

      const response = await agent.messages.create({
        model: 'claude-3-5-sonnet-20241022',
        max_tokens: 1200,
        messages: [
          {
            role: 'system',
            content: 'You are a business banking specialist. Assist with business accounts, cash management, and commercial banking services. Ensure compliance with business banking regulations.'
          },
          {
            role: 'user',
            content: inquiry
          }
        ],
        tools: this.getBusinessBankingTools(),
        sessionId: sessionId
      });

      if (this.hasToolCalls(response)) {
        return await this.processToolCalls(agentId, sessionId, response);
      }

      return response.content[0].text;

    } catch (error) {
      this.monitor.trackError(agentId, sessionId, error, {
        errorType: 'BusinessBankingError',
        severity: 'high',
        businessId: businessId
      });
      throw error;
    }
  }

  // Fraud Detection Processing
  async processFraudAlert(transactionData, sessionId) {
    const agentId = 'fraud-detection-agent';
    const agent = this.agents.get(agentId);

    try {
      this.monitor.trackConversationStart(agentId, sessionId, 'system', {
        alertType: 'fraud_detection',
        automated: true,
        transactionId: transactionData.id
      });

      // Simulate fraud analysis
      this.monitor.trackToolCall(
        agentId,
        sessionId,
        'analyze_transaction_patterns',
        {
          transactionId: transactionData.id,
          amount: transactionData.amount,
          merchant: transactionData.merchant,
          location: transactionData.location
        },
        {
          riskScore: transactionData.riskScore,
          anomalies: transactionData.anomalies,
          recommendation: transactionData.riskScore > 75 ? 'block_transaction' : 'allow_transaction'
        },
        450
      );

      const fraudPrompt = `Analyze this transaction for fraud:
        Transaction ID: ${transactionData.id}
        Amount: $${transactionData.amount}
        Merchant: ${transactionData.merchant}
        Location: ${transactionData.location}
        Risk Score: ${transactionData.riskScore}/100

        Provide a fraud assessment and recommendation.`;

      const response = await agent.messages.create({
        model: 'claude-3-5-sonnet-20241022',
        max_tokens: 800,
        messages: [
          {
            role: 'system',
            content: 'You are a fraud detection specialist. Analyze transactions for suspicious patterns and provide clear recommendations.'
          },
          {
            role: 'user',
            content: fraudPrompt
          }
        ],
        sessionId: sessionId
      });

      // Log the fraud analysis result
      this.monitor.trackAgentResponse(
        agentId,
        sessionId,
        response.content[0].text,
        {
          riskScore: transactionData.riskScore,
          fraudAnalysis: true,
          requiresEscalation: transactionData.riskScore > 85
        }
      );

      return {
        analysis: response.content[0].text,
        riskScore: transactionData.riskScore,
        recommendation: transactionData.riskScore > 75 ? 'block' : 'allow'
      };

    } catch (error) {
      this.monitor.trackError(agentId, sessionId, error, {
        errorType: 'FraudDetectionError',
        severity: 'critical',
        transactionId: transactionData.id
      });
      throw error;
    }
  }

  // Helper methods
  getPersonalBankingTools() {
    return [
      {
        name: 'get_account_summary',
        description: 'Get account balance and basic information',
        input_schema: {
          type: 'object',
          properties: {
            customer_id: { type: 'string', description: 'Customer identifier' },
            account_type: { type: 'string', description: 'Account type (checking, savings, etc.)' }
          },
          required: ['customer_id']
        }
      },
      {
        name: 'get_transaction_history',
        description: 'Retrieve recent transaction history',
        input_schema: {
          type: 'object',
          properties: {
            customer_id: { type: 'string', description: 'Customer identifier' },
            days: { type: 'number', description: 'Number of days to look back' }
          },
          required: ['customer_id']
        }
      }
    ];
  }

  getBusinessBankingTools() {
    return [
      {
        name: 'get_business_account_summary',
        description: 'Get business account information',
        input_schema: {
          type: 'object',
          properties: {
            business_id: { type: 'string', description: 'Business identifier' },
            include_credit_facilities: { type: 'boolean', description: 'Include credit information' }
          },
          required: ['business_id']
        }
      },
      {
        name: 'analyze_cash_flow',
        description: 'Analyze business cash flow patterns',
        input_schema: {
          type: 'object',
          properties: {
            business_id: { type: 'string', description: 'Business identifier' },
            period: { type: 'string', description: 'Analysis period (month, quarter, year)' }
          },
          required: ['business_id', 'period']
        }
      }
    ];
  }

  hasToolCalls(response) {
    return response.content.some(content => content.type === 'tool_use');
  }

  async processToolCalls(agentId, sessionId, response) {
    // Simulate tool execution and return continuation
    for (const content of response.content) {
      if (content.type === 'tool_use') {
        // Simulate tool execution
        const toolResult = await this.simulateToolExecution(content.name, content.input);

        this.monitor.trackToolCall(
          agentId,
          sessionId,
          content.name,
          content.input,
          toolResult,
          Math.random() * 500 + 100
        );
      }
    }

    return response.content.find(c => c.type === 'text')?.text || 'Tool execution completed.';
  }

  async simulateToolExecution(toolName, parameters) {
    // Simulate various tool responses
    switch (toolName) {
      case 'get_account_summary':
        return {
          balance: 2547.83,
          currency: 'USD',
          account_status: 'active',
          last_activity: '2024-01-15'
        };

      case 'get_transaction_history':
        return {
          transactions: [
            { date: '2024-01-14', amount: -45.67, description: 'Grocery Store' },
            { date: '2024-01-13', amount: 2500.00, description: 'Direct Deposit' }
          ]
        };

      case 'analyze_cash_flow':
        return {
          net_cash_flow: 15420.30,
          trend: 'positive',
          peak_months: ['March', 'June', 'December']
        };

      default:
        return { status: 'completed', message: 'Tool executed successfully' };
    }
  }

  async shutdown() {
    await this.monitor.shutdown();
    console.log('✅ Banking agent system shutdown complete');
  }
}

// Usage Example
async function runBankingExample() {
  const bankingSystem = new BankingAgentSystem({
    governanceApiKey: process.env.AGENT_GOVERNANCE_API_KEY,
    anthropicApiKey: process.env.ANTHROPIC_API_KEY,
    organizationId: 'first-national-bank',
    environment: 'production',
    enableLogging: false
  });

  try {
    // Initialize all banking agents
    await bankingSystem.initialize();

    // Example 1: Personal Banking Inquiry
    console.log('📱 Handling personal banking inquiry...');
    const personalResponse = await bankingSystem.handlePersonalBankingInquiry(
      'customer-12345',
      'Can you show me my checking account balance and recent transactions?',
      'personal-session-001'
    );
    console.log('Personal Banking Response:', personalResponse);

    // Example 2: Business Banking Inquiry
    console.log('🏢 Handling business banking inquiry...');
    const businessResponse = await bankingSystem.handleBusinessBankingInquiry(
      'business-67890',
      'I need to analyze our company\'s cash flow for the last quarter and check available credit facilities.',
      'business-session-001'
    );
    console.log('Business Banking Response:', businessResponse);

    // Example 3: Fraud Detection
    console.log('🚨 Processing fraud alert...');
    const suspiciousTransaction = {
      id: 'txn-suspicious-001',
      amount: 2500.00,
      merchant: 'Unknown Online Retailer',
      location: 'Romania',
      riskScore: 87,
      anomalies: ['unusual_location', 'high_amount', 'new_merchant']
    };

    const fraudAnalysis = await bankingSystem.processFraudAlert(
      suspiciousTransaction,
      'fraud-session-001'
    );
    console.log('Fraud Analysis:', fraudAnalysis);

    // Example 4: Multiple Customer Interactions
    console.log('👥 Simulating multiple customer interactions...');
    await simulateMultipleCustomers(bankingSystem);

  } catch (error) {
    console.error('Banking system error:', error);
  } finally {
    await bankingSystem.shutdown();
  }
}

async function simulateMultipleCustomers(bankingSystem) {
  const customers = [
    {
      id: 'customer-001',
      type: 'personal',
      inquiry: 'I want to set up automatic bill payments for my utilities.',
      sessionId: 'multi-session-001'
    },
    {
      id: 'customer-002',
      type: 'personal',
      inquiry: 'There\'s a charge on my account I don\'t recognize. Can you help me investigate?',
      sessionId: 'multi-session-002'
    },
    {
      id: 'business-001',
      type: 'business',
      inquiry: 'We need to increase our credit line for seasonal inventory purchases.',
      sessionId: 'multi-session-003'
    }
  ];

  const promises = customers.map(async (customer) => {
    if (customer.type === 'personal') {
      return bankingSystem.handlePersonalBankingInquiry(
        customer.id,
        customer.inquiry,
        customer.sessionId
      );
    } else {
      return bankingSystem.handleBusinessBankingInquiry(
        customer.id,
        customer.inquiry,
        customer.sessionId
      );
    }
  });

  const responses = await Promise.all(promises);
  responses.forEach((response, index) => {
    console.log(`Customer ${customers[index].id} response:`, response.substring(0, 100) + '...');
  });
}

// Run the example
runBankingExample().catch(console.error);

Loan Processing Workflow

Here’s an example of a complete loan application workflow:
class LoanProcessingWorkflow {
  constructor(bankingSystem) {
    this.bankingSystem = bankingSystem;
    this.monitor = bankingSystem.monitor;
  }

  async processLoanApplication(applicationData, sessionId) {
    const agentId = 'loan-processing-agent';

    try {
      this.monitor.trackConversationStart(agentId, sessionId, applicationData.customerId, {
        applicationType: 'mortgage',
        loanAmount: applicationData.requestedAmount,
        propertyValue: applicationData.propertyValue
      });

      console.log('🏠 Starting loan application process...');

      // Step 1: Credit Check
      console.log('📊 Performing credit check...');
      const creditResult = await this.performCreditCheck(agentId, sessionId, applicationData);

      // Step 2: Income Verification
      console.log('💰 Verifying income...');
      const incomeResult = await this.verifyIncome(agentId, sessionId, applicationData);

      // Step 3: Calculate Loan Terms
      console.log('🧮 Calculating loan eligibility...');
      const eligibilityResult = await this.calculateEligibility(
        agentId,
        sessionId,
        applicationData,
        creditResult,
        incomeResult
      );

      // Step 4: Generate Loan Decision
      const decision = await this.generateLoanDecision(
        agentId,
        sessionId,
        applicationData,
        eligibilityResult
      );

      this.monitor.trackConversationEnd(agentId, sessionId, {
        duration: 300000, // 5 minutes
        messageCount: 8,
        resolutionStatus: decision.approved ? 'approved' : 'declined',
        loanAmount: applicationData.requestedAmount,
        decisionReason: decision.reason
      });

      return decision;

    } catch (error) {
      this.monitor.trackError(agentId, sessionId, error, {
        errorType: 'LoanProcessingError',
        severity: 'high',
        stage: 'loan_application',
        customerId: applicationData.customerId
      });
      throw error;
    }
  }

  async performCreditCheck(agentId, sessionId, applicationData) {
    this.monitor.trackToolCall(
      agentId,
      sessionId,
      'check_credit_score',
      {
        customerId: applicationData.customerId,
        ssn: applicationData.ssn,
        includeReport: true
      },
      {
        creditScore: 745,
        creditHistory: 'excellent',
        derogatory_marks: 0,
        credit_utilization: 0.15,
        payment_history: 0.98
      },
      2500 // Credit check takes longer
    );

    return {
      score: 745,
      rating: 'excellent',
      qualifies: true
    };
  }

  async verifyIncome(agentId, sessionId, applicationData) {
    this.monitor.trackToolCall(
      agentId,
      sessionId,
      'verify_income',
      {
        customerId: applicationData.customerId,
        employmentInfo: applicationData.employment,
        requestedDocuments: ['pay_stubs', 'tax_returns', 'bank_statements']
      },
      {
        annual_income: applicationData.income,
        employment_verified: true,
        income_stability: 'stable',
        debt_to_income_ratio: 0.28
      },
      1800
    );

    return {
      verified: true,
      monthlyIncome: applicationData.income / 12,
      debtToIncomeRatio: 0.28,
      stable: true
    };
  }

  async calculateEligibility(agentId, sessionId, applicationData, creditResult, incomeResult) {
    this.monitor.trackToolCall(
      agentId,
      sessionId,
      'calculate_loan_eligibility',
      {
        requestedAmount: applicationData.requestedAmount,
        propertyValue: applicationData.propertyValue,
        creditScore: creditResult.score,
        monthlyIncome: incomeResult.monthlyIncome,
        debtToIncomeRatio: incomeResult.debtToIncomeRatio,
        downPayment: applicationData.downPayment
      },
      {
        eligible: true,
        maxLoanAmount: 425000,
        recommendedAmount: applicationData.requestedAmount,
        interestRate: 6.75,
        monthlyPayment: 2847.23,
        loanToValue: 0.80,
        pmiRequired: false
      },
      1200
    );

    return {
      eligible: true,
      approvedAmount: applicationData.requestedAmount,
      interestRate: 6.75,
      monthlyPayment: 2847.23,
      terms: '30-year fixed'
    };
  }

  async generateLoanDecision(agentId, sessionId, applicationData, eligibilityResult) {
    const agent = this.bankingSystem.agents.get(agentId);

    const decisionPrompt = `Review this loan application and provide a decision:

    Applicant: ${applicationData.customerName}
    Requested Amount: ${applicationData.requestedAmount.toLocaleString()}
    Property Value: ${applicationData.propertyValue.toLocaleString()}
    Credit Score: 745 (Excellent)
    Annual Income: ${applicationData.income.toLocaleString()}
    Debt-to-Income Ratio: 28%
    Down Payment: ${applicationData.downPayment.toLocaleString()}

    Eligibility Analysis:
    - Approved Amount: ${eligibilityResult.approvedAmount.toLocaleString()}
    - Interest Rate: ${eligibilityResult.interestRate}%
    - Monthly Payment: ${eligibilityResult.monthlyPayment.toLocaleString()}

    Provide a loan decision with explanation.`;

    const response = await agent.messages.create({
      model: 'claude-3-5-sonnet-20241022',
      max_tokens: 800,
      messages: [
        {
          role: 'system',
          content: 'You are a loan officer reviewing mortgage applications. Provide clear decisions based on standard lending criteria and fair lending practices.'
        },
        {
          role: 'user',
          content: decisionPrompt
        }
      ],
      sessionId: sessionId
    });

    return {
      approved: true,
      amount: eligibilityResult.approvedAmount,
      interestRate: eligibilityResult.interestRate,
      monthlyPayment: eligibilityResult.monthlyPayment,
      terms: eligibilityResult.terms,
      explanation: response.content[0].text,
      reason: 'qualified_applicant'
    };
  }
}

// Example usage of loan processing
async function loanProcessingExample() {
  const bankingSystem = new BankingAgentSystem({
    governanceApiKey: process.env.AGENT_GOVERNANCE_API_KEY,
    anthropicApiKey: process.env.ANTHROPIC_API_KEY,
    organizationId: 'first-national-bank'
  });

  await bankingSystem.initialize();

  const loanProcessor = new LoanProcessingWorkflow(bankingSystem);

  const applicationData = {
    customerId: 'customer-loan-001',
    customerName: 'John and Jane Smith',
    requestedAmount: 320000,
    propertyValue: 400000,
    downPayment: 80000,
    income: 95000,
    ssn: '***-**-1234',
    employment: {
      employer: 'Tech Corp Inc',
      position: 'Software Engineer',
      yearsEmployed: 3,
      salary: 95000
    }
  };

  try {
    const decision = await loanProcessor.processLoanApplication(
      applicationData,
      'loan-session-001'
    );

    console.log('Loan Decision:', {
      approved: decision.approved,
      amount: decision.amount,
      rate: decision.interestRate,
      payment: decision.monthlyPayment
    });

  } finally {
    await bankingSystem.shutdown();
  }
}

Real-time Fraud Monitoring

Example of continuous fraud monitoring across all banking interactions:
class FraudMonitoringService {
  constructor(bankingSystem) {
    this.bankingSystem = bankingSystem;
    this.monitor = bankingSystem.monitor;
    this.fraudAgent = bankingSystem.agents.get('fraud-detection-agent');
    this.alertThresholds = {
      lowRisk: 25,
      mediumRisk: 50,
      highRisk: 75,
      criticalRisk: 90
    };
  }

  async monitorTransaction(transaction, sessionId) {
    const agentId = 'fraud-detection-agent';

    // Calculate risk score based on transaction characteristics
    const riskScore = this.calculateRiskScore(transaction);

    if (riskScore >= this.alertThresholds.mediumRisk) {
      this.monitor.trackConversationStart(agentId, sessionId, 'fraud_system', {
        transactionId: transaction.id,
        alertLevel: this.getRiskLevel(riskScore),
        automated: true
      });

      // Analyze transaction patterns
      this.monitor.trackToolCall(
        agentId,
        sessionId,
        'analyze_transaction_patterns',
        {
          transactionId: transaction.id,
          customerId: transaction.customerId,
          amount: transaction.amount,
          merchant: transaction.merchant,
          location: transaction.location,
          timestamp: transaction.timestamp
        },
        {
          riskScore: riskScore,
          riskFactors: this.identifyRiskFactors(transaction),
          similarTransactions: this.findSimilarTransactions(transaction),
          recommendation: riskScore >= this.alertThresholds.highRisk ? 'block' : 'monitor'
        },
        850
      );

      if (riskScore >= this.alertThresholds.criticalRisk) {
        return await this.escalateFraudAlert(transaction, sessionId, riskScore);
      }
    }

    return {
      allowed: riskScore < this.alertThresholds.highRisk,
      riskScore: riskScore,
      monitoring: riskScore >= this.alertThresholds.mediumRisk
    };
  }

  calculateRiskScore(transaction) {
    let score = 0;

    // Amount-based risk
    if (transaction.amount > 5000) score += 20;
    if (transaction.amount > 10000) score += 30;

    // Location-based risk
    if (transaction.location !== transaction.customer.primaryLocation) score += 15;
    if (this.isHighRiskLocation(transaction.location)) score += 35;

    // Time-based risk
    const hour = new Date(transaction.timestamp).getHours();
    if (hour < 6 || hour > 22) score += 10;

    // Merchant-based risk
    if (this.isNewMerchant(transaction.merchant, transaction.customerId)) score += 20;
    if (this.isHighRiskMerchant(transaction.merchant)) score += 40;

    // Frequency-based risk
    const recentTransactions = this.getRecentTransactions(transaction.customerId, 24); // 24 hours
    if (recentTransactions.length > 10) score += 25;

    return Math.min(score, 100);
  }

  identifyRiskFactors(transaction) {
    const factors = [];

    if (transaction.amount > 5000) factors.push('high_amount');
    if (transaction.location !== transaction.customer.primaryLocation) factors.push('unusual_location');
    if (this.isNewMerchant(transaction.merchant, transaction.customerId)) factors.push('new_merchant');

    const hour = new Date(transaction.timestamp).getHours();
    if (hour < 6 || hour > 22) factors.push('unusual_time');

    return factors;
  }

  async escalateFraudAlert(transaction, sessionId, riskScore) {
    const agentId = 'fraud-detection-agent';

    this.monitor.trackToolCall(
      agentId,
      sessionId,
      'escalate_to_fraud_team',
      {
        transactionId: transaction.id,
        riskScore: riskScore,
        urgency: 'high',
        customerId: transaction.customerId
      },
      {
        escalated: true,
        ticketId: `FRAUD-${Date.now()}`,
        assignedTo: 'fraud_team_lead',
        estimatedResponseTime: '15_minutes'
      },
      300
    );

    // Generate detailed fraud analysis
    const fraudAnalysisPrompt = `URGENT FRAUD ALERT - Risk Score: ${riskScore}/100

    Transaction Details:
    - ID: ${transaction.id}
    - Amount: ${transaction.amount}
    - Merchant: ${transaction.merchant}
    - Location: ${transaction.location}
    - Customer: ${transaction.customerId}
    - Time: ${new Date(transaction.timestamp).toISOString()}

    Risk Factors:
    ${this.identifyRiskFactors(transaction).map(factor => `- ${factor}`).join('\n')}

    Provide immediate fraud assessment and recommended actions.`;

    const response = await this.fraudAgent.messages.create({
      model: 'claude-3-5-sonnet-20241022',
      max_tokens: 600,
      messages: [
        {
          role: 'system',
          content: 'You are a senior fraud analyst. Provide immediate assessment of high-risk transactions and clear action recommendations.'
        },
        {
          role: 'user',
          content: fraudAnalysisPrompt
        }
      ],
      sessionId: sessionId
    });

    this.monitor.trackAgentResponse(
      agentId,
      sessionId,
      response.content[0].text,
      {
        criticalAlert: true,
        riskScore: riskScore,
        escalated: true,
        requiresImmediateAction: true
      }
    );

    return {
      blocked: true,
      riskScore: riskScore,
      escalated: true,
      analysis: response.content[0].text,
      ticketId: `FRAUD-${Date.now()}`
    };
  }

  getRiskLevel(score) {
    if (score >= this.alertThresholds.criticalRisk) return 'critical';
    if (score >= this.alertThresholds.highRisk) return 'high';
    if (score >= this.alertThresholds.mediumRisk) return 'medium';
    return 'low';
  }

  // Helper methods (simplified implementations)
  isHighRiskLocation(location) {
    const highRiskCountries = ['Country1', 'Country2']; // Simplified
    return highRiskCountries.includes(location);
  }

  isNewMerchant(merchant, customerId) {
    // Simplified check - in reality would query transaction history
    return Math.random() > 0.7;
  }

  isHighRiskMerchant(merchant) {
    const highRiskCategories = ['gambling', 'cryptocurrency', 'money_transfer'];
    return highRiskCategories.some(category => merchant.toLowerCase().includes(category));
  }

  getRecentTransactions(customerId, hours) {
    // Simplified - would query actual transaction database
    return Array(Math.floor(Math.random() * 15)).fill({});
  }

  findSimilarTransactions(transaction) {
    // Simplified similar transaction detection
    return {
      count: Math.floor(Math.random() * 5),
      timeframe: '30_days',
      similarity_score: Math.random()
    };
  }
}

Performance Monitoring and Analytics

Track performance across all banking agents:
class BankingAnalytics {
  constructor(bankingSystem) {
    this.bankingSystem = bankingSystem;
    this.monitor = bankingSystem.monitor;
  }

  async generateDailyReport() {
    const report = {
      date: new Date().toISOString().split('T')[0],
      summary: await this.generateSummaryMetrics(),
      agentPerformance: await this.generateAgentMetrics(),
      complianceMetrics: await this.generateComplianceMetrics(),
      customerSatisfaction: await this.generateSatisfactionMetrics()
    };

    // Track the report generation as an event
    this.monitor.track('analytics-agent', {
      sessionId: `analytics-${Date.now()}`,
      interactionType: 'custom',
      metadata: {
        reportType: 'daily_banking_report',
        reportDate: report.date,
        totalInteractions: report.summary.totalInteractions,
        averageResponseTime: report.summary.averageResponseTime,
        complianceViolations: report.complianceMetrics.totalViolations
      }
    });

    return report;
  }

  async generateSummaryMetrics() {
    return {
      totalInteractions: 1247,
      totalCustomers: 892,
      averageResponseTime: 1.2, // seconds
      successRate: 0.987,
      escalationRate: 0.034
    };
  }

  async generateAgentMetrics() {
    return {
      'personal-banking-agent': {
        interactions: 456,
        avgResponseTime: 1.1,
        customerSatisfaction: 4.6,
        toolCallSuccess: 0.98
      },
      'business-banking-agent': {
        interactions: 234,
        avgResponseTime: 1.8,
        customerSatisfaction: 4.7,
        toolCallSuccess: 0.96
      },
      'fraud-detection-agent': {
        interactions: 67,
        avgResponseTime: 0.8,
        alertsGenerated: 12,
        falsePositiveRate: 0.05
      }
    };
  }

  async generateComplianceMetrics() {
    return {
      totalViolations: 3,
      piiDetections: 1,
      fairLendingFlags: 0,
      bsaAmlAlerts: 2,
      riskScoreAverage: 15.3
    };
  }

  async generateSatisfactionMetrics() {
    return {
      averageRating: 4.6,
      responseCount: 789,
      promoterScore: 67,
      resolutionRate: 0.94
    };
  }
}

Next Steps

This banking example demonstrates enterprise-level usage patterns. In production, ensure proper error handling, security measures, and compliance with all applicable financial regulations.