Skip to main content
The Agent Governance SDK provides a comprehensive TypeScript/JavaScript API for monitoring AI agents in banking and financial services applications. This reference covers all classes, methods, types, and configuration options.

Core Classes

AgentMonitor

Main monitoring class for manual event tracking and agent registration

ComplianceEngine

Offline compliance checking with built-in and custom rules

AnthropicAgentMonitor

Automatic monitoring wrapper for Anthropic Claude API

OpenAIAgentMonitor

Automatic monitoring wrapper for OpenAI GPT API

Quick Reference

Installation

npm install @agent-governance/node

Basic Import

import {
  AgentMonitor,
  AnthropicAgentMonitor,
  OpenAIAgentMonitor,
  ComplianceEngine
} from '@agent-governance/node';

Core Configuration

interface AgentMonitoringConfig {
  apiKey: string;                    // Required: Your governance API key
  organizationId: string;            // Required: Your organization ID
  endpoint?: string;                 // Optional: Custom API endpoint
  environment?: 'production' | 'staging' | 'development';
  batchSize?: number;               // Events per batch (1-1000)
  flushInterval?: number;           // Flush interval in ms (min 100)
  enableComplianceChecks?: boolean; // Enable compliance monitoring
  enableLogging?: boolean;          // Enable SDK logging
  logLevel?: 'debug' | 'info' | 'warn' | 'error';
  retryAttempts?: number;           // Retry attempts for failed requests
  retryDelay?: number;              // Delay between retries in ms
}

Key Methods

Agent Registration

await monitor.registerAgent({
  id: string;                       // Unique agent identifier
  name: string;                     // Human-readable agent name
  category: AgentCategory;          // Agent type classification
  specialty?: BankingSpecialty;     // Banking domain specialty
  version: string;                  // Agent version
  llmProvider: string;              // LLM provider name
  model: string;                    // Model name/version
  description: string;              // Agent description
  complianceSettings?: {            // Compliance configuration
    sr11_7_enabled: boolean;
    fair_lending_monitoring: boolean;
    bsa_aml_checks: boolean;
  };
});

Event Tracking

// Conversation lifecycle
monitor.trackConversationStart(agentId, sessionId, userId?, metadata?);
monitor.trackUserMessage(agentId, sessionId, content, userId?, metadata?);
monitor.trackAgentResponse(agentId, sessionId, content, metadata?, options?);
monitor.trackConversationEnd(agentId, sessionId, metadata?);

// Tool usage
monitor.trackToolCall(agentId, sessionId, toolName, parameters, result?, executionTime?, metadata?);

// Error tracking
monitor.trackError(agentId, sessionId, error, metadata?);

// Generic event tracking
monitor.track(agentId, event, options?);

Utility Methods

// Flush pending events immediately
await monitor.flush();

// Shutdown monitor and flush remaining events
await monitor.shutdown();

Type Definitions

Agent Categories

type AgentCategory = 'persona' | 'tool_calling' | 'workflow' | 'autonomous';

Banking Specialties

type BankingSpecialty =
  | 'generalist'
  | 'personal_banking'
  | 'business_banking'
  | 'wealth_management'
  | 'mortgage_lending'
  | 'investment_services'
  | 'fraud_detection'
  | 'customer_service'
  | 'compliance';

Event Types

type EventType =
  | 'conversation_start'
  | 'user_message'
  | 'agent_response'
  | 'tool_call'
  | 'tool_result'
  | 'error'
  | 'conversation_end';

Compliance Categories

type ComplianceCategory =
  | 'sr_11_7'           // Model validation requirements
  | 'fair_lending'      // Anti-discrimination monitoring
  | 'bsa_aml'          // Anti-money laundering
  | 'privacy'          // PII protection
  | 'consumer_protection'
  | 'custom';          // Organization-specific rules

Error Handling

The SDK uses structured error handling with detailed error information:
try {
  await monitor.registerAgent(agentInfo);
} catch (error) {
  if (error instanceof ValidationError) {
    console.error('Configuration error:', error.details);
  } else if (error instanceof NetworkError) {
    console.error('Network error:', error.message);
  } else {
    console.error('Unexpected error:', error);
  }
}

Configuration Examples

Development Environment

const monitor = new AgentMonitor({
  apiKey: 'dev-api-key',
  organizationId: 'test-org',
  environment: 'development',
  enableLogging: true,
  logLevel: 'debug',
  batchSize: 10,
  flushInterval: 1000
});

Production Environment

const monitor = new AgentMonitor({
  apiKey: process.env.AGENT_GOVERNANCE_API_KEY,
  organizationId: process.env.AGENT_GOVERNANCE_ORG_ID,
  environment: 'production',
  enableLogging: false,
  batchSize: 500,
  flushInterval: 10000,
  retryAttempts: 5,
  retryDelay: 2000
});

High-Volume Environment

const monitor = new AgentMonitor({
  apiKey: process.env.AGENT_GOVERNANCE_API_KEY,
  organizationId: process.env.AGENT_GOVERNANCE_ORG_ID,
  environment: 'production',
  enableLogging: false,
  enableComplianceChecks: true,
  batchSize: 1000,
  flushInterval: 30000,
  retryAttempts: 3
});

Compliance Configuration

Enable All Compliance Checks

await monitor.registerAgent({
  id: 'banking-agent',
  name: 'Banking Assistant',
  category: 'tool_calling',
  specialty: 'personal_banking',
  // ... other fields
  complianceSettings: {
    sr11_7_enabled: true,
    fair_lending_monitoring: true,
    bsa_aml_checks: true
  }
});

Custom Compliance Rules

// Add custom compliance rule
monitor.complianceEngine?.addRule({
  id: 'custom-banking-rule',
  name: 'Banking Hours Compliance',
  description: 'Ensures banking hours are mentioned correctly',
  category: 'consumer_protection',
  severity: 'warning',
  isActive: true,
  ruleFunction: (context) => {
    // Custom rule implementation
    return {
      isCompliant: true,
      violations: [],
      riskScore: 0,
      requiresReview: false
    };
  }
});

Best Practices

  • Store API keys in environment variables
  • Use different configurations for different environments
  • Set appropriate batch sizes based on your traffic volume
  • Configure retry settings based on your reliability requirements
  • Use consistent session IDs for related interactions
  • Include relevant metadata for better analytics
  • Track errors with sufficient context for debugging
  • Use meaningful agent IDs and names
  • Adjust batch sizes based on your volume
  • Use appropriate flush intervals
  • Consider disabling logging in production
  • Monitor memory usage with large batches
  • Implement proper error handling for all async operations
  • Monitor failed requests and adjust retry settings
  • Use graceful degradation when monitoring fails
  • Always call shutdown() in application cleanup

Integration Patterns

Middleware Pattern

function createMonitoringMiddleware(monitor, agentId) {
  return async (req, res, next) => {
    const sessionId = req.sessionID || `session-${Date.now()}`;

    req.monitoring = {
      trackUserMessage: (content) =>
        monitor.trackUserMessage(agentId, sessionId, content),
      trackAgentResponse: (content, metadata) =>
        monitor.trackAgentResponse(agentId, sessionId, content, metadata)
    };

    next();
  };
}

Decorator Pattern

function withMonitoring(agentFunction, monitor, agentId) {
  return async (input, sessionId) => {
    const startTime = Date.now();

    try {
      monitor.trackUserMessage(agentId, sessionId, input);
      const result = await agentFunction(input);

      monitor.trackAgentResponse(agentId, sessionId, result, {
        latency: Date.now() - startTime
      });

      return result;
    } catch (error) {
      monitor.trackError(agentId, sessionId, error);
      throw error;
    }
  };
}

Next Steps

AgentMonitor Class

Detailed documentation for the main monitoring class

Type Definitions

Complete TypeScript type definitions

Error Handling

Error types and handling strategies

Examples

Practical examples and use cases