> ## Documentation Index
> Fetch the complete documentation index at: https://docs.aiagentshouse.com/llms.txt
> Use this file to discover all available pages before exploring further.

# API Reference Overview

> Complete reference for the AI Agents House SDK API

The AI Agents House 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

<CardGroup cols={2}>
  <Card title="AgentMonitor" icon="chart-line" href="/api-reference/agent-monitor">
    Main monitoring class for manual event tracking and agent registration
  </Card>

  <Card title="ComplianceEngine" icon="shield-check" href="/api-reference/compliance-engine">
    Offline compliance checking with built-in and custom rules
  </Card>

  <Card title="AnthropicAgentMonitor" icon="brain" href="/integrations/anthropic">
    Automatic monitoring wrapper for Anthropic Claude API
  </Card>

  <Card title="OpenAIAgentMonitor" icon="brain" href="/integrations/openai">
    Automatic monitoring wrapper for OpenAI GPT API
  </Card>
</CardGroup>

## Quick Reference

### Installation

```bash theme={null}
npm install @agent-governance/node
```

### Basic Import

```javascript theme={null}
import {
  AgentMonitor,
  AnthropicAgentMonitor,
  OpenAIAgentMonitor,
  ComplianceEngine
} from '@agent-governance/node';
```

### Core Configuration

```typescript theme={null}
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

```typescript theme={null}
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

```typescript theme={null}
// 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

```typescript theme={null}
// Flush pending events immediately
await monitor.flush();

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

## Type Definitions

### Agent Categories

```typescript theme={null}
type AgentCategory = 'persona' | 'tool_calling' | 'workflow' | 'autonomous';
```

### Banking Specialties

```typescript theme={null}
type BankingSpecialty =
  | 'generalist'
  | 'personal_banking'
  | 'business_banking'
  | 'wealth_management'
  | 'mortgage_lending'
  | 'investment_services'
  | 'fraud_detection'
  | 'customer_service'
  | 'compliance';
```

### Event Types

```typescript theme={null}
type EventType =
  | 'conversation_start'
  | 'user_message'
  | 'agent_response'
  | 'tool_call'
  | 'tool_result'
  | 'error'
  | 'conversation_end';
```

### Compliance Categories

```typescript theme={null}
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:

```typescript theme={null}
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

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

### Production Environment

```javascript theme={null}
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

```javascript theme={null}
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

```javascript theme={null}
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

```javascript theme={null}
// 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

<AccordionGroup>
  <Accordion title="Configuration Management">
    * 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
  </Accordion>

  <Accordion title="Event Tracking">
    * 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
  </Accordion>

  <Accordion title="Performance Optimization">
    * Adjust batch sizes based on your volume
    * Use appropriate flush intervals
    * Consider disabling logging in production
    * Monitor memory usage with large batches
  </Accordion>

  <Accordion title="Error Handling">
    * 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
  </Accordion>
</AccordionGroup>

## Integration Patterns

### Middleware Pattern

```javascript theme={null}
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

```javascript theme={null}
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

<CardGroup cols={2}>
  <Card title="AgentMonitor Class" icon="chart-line" href="/api-reference/agent-monitor">
    Detailed documentation for the main monitoring class
  </Card>

  <Card title="Type Definitions" icon="code" href="/api-reference/types">
    Complete TypeScript type definitions
  </Card>

  <Card title="Error Handling" icon="exclamation-triangle" href="/api-reference/errors">
    Error types and handling strategies
  </Card>

  <Card title="Examples" icon="play" href="/examples/basic-usage">
    Practical examples and use cases
  </Card>
</CardGroup>
