> ## 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.

# AgentMonitor Class

> Complete reference for the AgentMonitor class - the core monitoring component

The `AgentMonitor` class is the core component of the AI Agents House SDK, providing comprehensive monitoring capabilities for AI agents. It handles event tracking, agent registration, compliance monitoring, and data transmission to the AI Agents House platform.

## Constructor

### AgentMonitor(config)

Creates a new instance of the AgentMonitor with the specified configuration.

<ParamField path="config" type="AgentMonitoringConfig" required>
  Configuration object for the monitor instance.

  <Expandable title="Configuration Properties">
    <ParamField path="apiKey" type="string" required>
      Your AI Agents House API key for authentication.
    </ParamField>

    <ParamField path="organizationId" type="string" required>
      Your organization identifier in the AI Agents House platform.
    </ParamField>

    <ParamField path="endpoint" type="string" default="https://api.aiagentshouse.com">
      The API endpoint for the AI Agents House platform.
    </ParamField>

    <ParamField path="environment" type="'production' | 'staging' | 'development'" default="production">
      The environment designation for your deployment.
    </ParamField>

    <ParamField path="batchSize" type="number" default="100">
      Number of events to batch before sending (1-1000).
    </ParamField>

    <ParamField path="flushInterval" type="number" default="5000">
      Time in milliseconds between automatic flushes (minimum 100).
    </ParamField>

    <ParamField path="enableComplianceChecks" type="boolean" default="true">
      Whether to enable real-time compliance monitoring.
    </ParamField>

    <ParamField path="enableLogging" type="boolean" default="true">
      Whether to enable SDK logging output.
    </ParamField>

    <ParamField path="logLevel" type="'debug' | 'info' | 'warn' | 'error'" default="info">
      The minimum log level to output.
    </ParamField>

    <ParamField path="retryAttempts" type="number" default="3">
      Number of retry attempts for failed requests (0-10).
    </ParamField>

    <ParamField path="retryDelay" type="number" default="1000">
      Base delay in milliseconds between retry attempts.
    </ParamField>
  </Expandable>
</ParamField>

**Example:**

```javascript theme={null}
const monitor = new AgentMonitor({
  apiKey: 'your-api-key',
  organizationId: 'your-org-id',
  environment: 'production',
  enableComplianceChecks: true,
  batchSize: 250,
  flushInterval: 10000
});
```

## Agent Registration

### registerAgent(agent)

Registers an agent with the monitoring system before tracking its interactions.

<ParamField path="agent" type="AgentInfo" required>
  Agent information and configuration.

  <Expandable title="Agent Properties">
    <ParamField path="id" type="string" required>
      Unique identifier for the agent within your organization.
    </ParamField>

    <ParamField path="name" type="string" required>
      Human-readable name for the agent.
    </ParamField>

    <ParamField path="category" type="AgentCategory" required>
      Type of agent: 'persona', 'tool\_calling', 'workflow', or 'autonomous'.
    </ParamField>

    <ParamField path="specialty" type="BankingSpecialty">
      Banking domain specialty if applicable.
    </ParamField>

    <ParamField path="version" type="string" required>
      Version identifier for the agent.
    </ParamField>

    <ParamField path="llmProvider" type="string" required>
      The LLM provider (e.g., 'anthropic', 'openai').
    </ParamField>

    <ParamField path="model" type="string" required>
      The specific model being used (e.g., 'claude-3-5-sonnet-20241022').
    </ParamField>

    <ParamField path="description" type="string" required>
      Detailed description of the agent's purpose and capabilities.
    </ParamField>

    <ParamField path="systemPrompt" type="string">
      The system prompt used to initialize the agent.
    </ParamField>

    <ParamField path="availableTools" type="ToolInfo[]">
      Array of tools available to the agent.
    </ParamField>

    <ParamField path="complianceSettings" type="ComplianceSettings">
      Compliance monitoring configuration for this agent.
    </ParamField>
  </Expandable>
</ParamField>

**Returns:** `Promise<void>`

**Example:**

```javascript theme={null}
await monitor.registerAgent({
  id: 'banking-assistant-v2',
  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 customer service',
  availableTools: [
    {
      name: 'get_account_balance',
      description: 'Retrieves current account balance',
      category: 'banking',
      riskLevel: 'medium'
    }
  ],
  complianceSettings: {
    sr11_7_enabled: true,
    fair_lending_monitoring: true,
    bsa_aml_checks: true
  }
});
```

## Event Tracking Methods

### trackConversationStart(agentId, sessionId, userId?, metadata?)

Tracks the beginning of a new conversation session.

<ParamField path="agentId" type="string" required>
  The ID of the agent handling the conversation.
</ParamField>

<ParamField path="sessionId" type="string" required>
  Unique identifier for the conversation session.
</ParamField>

<ParamField path="userId" type="string">
  Optional identifier for the user initiating the conversation.
</ParamField>

<ParamField path="metadata" type="object">
  Optional metadata object with additional context.
</ParamField>

**Example:**

```javascript theme={null}
monitor.trackConversationStart(
  'banking-assistant',
  'session-12345',
  'customer-67890',
  {
    userAgent: 'Mozilla/5.0...',
    ipAddress: '192.168.1.100',
    referrer: 'https://mybank.com/login'
  }
);
```

### trackUserMessage(agentId, sessionId, content, userId?, metadata?)

Tracks a message from the user to the agent.

<ParamField path="agentId" type="string" required>
  The ID of the agent receiving the message.
</ParamField>

<ParamField path="sessionId" type="string" required>
  The conversation session identifier.
</ParamField>

<ParamField path="content" type="string" required>
  The content of the user's message.
</ParamField>

<ParamField path="userId" type="string">
  Optional user identifier.
</ParamField>

<ParamField path="metadata" type="object">
  Optional metadata with additional context.
</ParamField>

**Example:**

```javascript theme={null}
monitor.trackUserMessage(
  'banking-assistant',
  'session-12345',
  'Can you help me check my account balance?',
  'customer-67890',
  {
    messageId: 'msg-001',
    channel: 'web_chat',
    customerTier: 'premium'
  }
);
```

### trackAgentResponse(agentId, sessionId, content, metadata?, options?)

Tracks a response from the agent to the user.

<ParamField path="agentId" type="string" required>
  The ID of the responding agent.
</ParamField>

<ParamField path="sessionId" type="string" required>
  The conversation session identifier.
</ParamField>

<ParamField path="content" type="string" required>
  The content of the agent's response.
</ParamField>

<ParamField path="metadata" type="object">
  Optional metadata including performance and quality metrics.

  <Expandable title="Common Metadata Fields">
    <ParamField path="llmLatency" type="number">
      Time taken for LLM processing in milliseconds.
    </ParamField>

    <ParamField path="tokensUsed" type="TokenUsage">
      Token usage statistics: `{ input: number, output: number, total: number }`.
    </ParamField>

    <ParamField path="cost" type="number">
      Calculated cost for the LLM call.
    </ParamField>

    <ParamField path="responseQuality" type="number">
      Quality score for the response (0-100).
    </ParamField>

    <ParamField path="temperature" type="number">
      LLM temperature setting used.
    </ParamField>

    <ParamField path="maxTokens" type="number">
      Maximum tokens setting used.
    </ParamField>
  </Expandable>
</ParamField>

<ParamField path="options" type="MonitoringOptions">
  Optional monitoring configuration for this specific interaction.
</ParamField>

**Example:**

```javascript theme={null}
monitor.trackAgentResponse(
  'banking-assistant',
  'session-12345',
  'Your current checking account balance is $2,547.83.',
  {
    llmLatency: 850,
    tokensUsed: { input: 125, output: 67, total: 192 },
    cost: 0.0034,
    responseQuality: 92,
    temperature: 0.7
  },
  {
    agentCategory: 'tool_calling',
    agentSpecialty: 'personal_banking'
  }
);
```

### trackToolCall(agentId, sessionId, toolName, parameters, result?, executionTime?, metadata?)

Tracks when an agent uses a tool or external function.

<ParamField path="agentId" type="string" required>
  The ID of the agent making the tool call.
</ParamField>

<ParamField path="sessionId" type="string" required>
  The conversation session identifier.
</ParamField>

<ParamField path="toolName" type="string" required>
  The name of the tool being called.
</ParamField>

<ParamField path="parameters" type="any" required>
  The parameters passed to the tool.
</ParamField>

<ParamField path="result" type="any">
  The result returned by the tool (if available).
</ParamField>

<ParamField path="executionTime" type="number">
  Time taken to execute the tool in milliseconds.
</ParamField>

<ParamField path="metadata" type="object">
  Optional metadata with additional context.
</ParamField>

**Example:**

```javascript theme={null}
monitor.trackToolCall(
  'banking-assistant',
  'session-12345',
  'get_account_balance',
  { accountId: 'acc_123', accountType: 'checking' },
  { balance: 2547.83, currency: 'USD', lastUpdated: '2024-01-15' },
  245,
  {
    toolVersion: '1.2.0',
    cacheHit: false
  }
);
```

### trackError(agentId, sessionId, error, metadata?)

Tracks errors that occur during agent interactions.

<ParamField path="agentId" type="string" required>
  The ID of the agent where the error occurred.
</ParamField>

<ParamField path="sessionId" type="string" required>
  The conversation session identifier.
</ParamField>

<ParamField path="error" type="string | Error" required>
  The error message or Error object.
</ParamField>

<ParamField path="metadata" type="object">
  Optional metadata with error details.

  <Expandable title="Error Metadata Fields">
    <ParamField path="errorType" type="string">
      Classification of the error type.
    </ParamField>

    <ParamField path="errorCode" type="string">
      Specific error code if available.
    </ParamField>

    <ParamField path="severity" type="'low' | 'medium' | 'high' | 'critical'">
      Severity level of the error.
    </ParamField>

    <ParamField path="recoverable" type="boolean">
      Whether the error is recoverable.
    </ParamField>

    <ParamField path="userImpact" type="'none' | 'minimal' | 'moderate' | 'high'">
      Impact on the user experience.
    </ParamField>

    <ParamField path="systemImpact" type="'none' | 'minimal' | 'moderate' | 'high'">
      Impact on system functionality.
    </ParamField>

    <ParamField path="errorSource" type="'client' | 'server' | 'external' | 'unknown'">
      Source of the error.
    </ParamField>
  </Expandable>
</ParamField>

**Example:**

```javascript theme={null}
monitor.trackError(
  'banking-assistant',
  'session-12345',
  new Error('Failed to connect to banking API'),
  {
    errorType: 'APIConnectionError',
    errorCode: 'BANK_API_001',
    severity: 'high',
    recoverable: true,
    userImpact: 'moderate',
    systemImpact: 'minimal',
    errorSource: 'external'
  }
);
```

### trackConversationEnd(agentId, sessionId, metadata?)

Tracks the end of a conversation session.

<ParamField path="agentId" type="string" required>
  The ID of the agent ending the conversation.
</ParamField>

<ParamField path="sessionId" type="string" required>
  The conversation session identifier.
</ParamField>

<ParamField path="metadata" type="object">
  Optional metadata with conversation summary.

  <Expandable title="Conversation End Metadata">
    <ParamField path="duration" type="number">
      Total duration of the conversation in milliseconds.
    </ParamField>

    <ParamField path="messageCount" type="number">
      Total number of messages exchanged.
    </ParamField>

    <ParamField path="userSatisfaction" type="number">
      User satisfaction rating (1-10 scale).
    </ParamField>

    <ParamField path="resolutionStatus" type="'resolved' | 'unresolved' | 'escalated' | 'abandoned'">
      How the conversation was resolved.
    </ParamField>

    <ParamField path="endReason" type="'user_initiated' | 'timeout' | 'error' | 'system_initiated'">
      Reason for conversation ending.
    </ParamField>

    <ParamField path="followUpRequired" type="boolean">
      Whether follow-up action is needed.
    </ParamField>

    <ParamField path="escalationReason" type="string">
      Reason for escalation if applicable.
    </ParamField>
  </Expandable>
</ParamField>

**Example:**

```javascript theme={null}
monitor.trackConversationEnd(
  'banking-assistant',
  'session-12345',
  {
    duration: 180000, // 3 minutes
    messageCount: 6,
    userSatisfaction: 9,
    resolutionStatus: 'resolved',
    endReason: 'user_initiated',
    followUpRequired: false
  }
);
```

### track(agentId, event, options?)

Generic method for tracking any type of interaction event.

<ParamField path="agentId" type="string" required>
  The ID of the agent associated with the event.
</ParamField>

<ParamField path="event" type="InteractionEvent" required>
  The event object to track.

  <Expandable title="InteractionEvent Properties">
    <ParamField path="sessionId" type="string" required>
      The conversation session identifier.
    </ParamField>

    <ParamField path="interactionType" type="EventType" required>
      The type of interaction being tracked.
    </ParamField>

    <ParamField path="content" type="string">
      Content for message and error events.
    </ParamField>

    <ParamField path="toolName" type="string">
      Tool name for tool-related events.
    </ParamField>

    <ParamField path="toolParameters" type="any">
      Parameters for tool calls.
    </ParamField>

    <ParamField path="toolResult" type="any">
      Results from tool execution.
    </ParamField>

    <ParamField path="metadata" type="object">
      Additional metadata for the event.
    </ParamField>
  </Expandable>
</ParamField>

<ParamField path="options" type="MonitoringOptions">
  Optional monitoring configuration.
</ParamField>

**Example:**

```javascript theme={null}
monitor.track(
  'banking-assistant',
  {
    sessionId: 'session-12345',
    interactionType: 'compliance_violation',
    metadata: {
      violationType: 'fair_lending',
      severity: 'warning',
      description: 'Potential discriminatory language detected',
      ruleId: 'fair_lending_001'
    }
  }
);
```

## Utility Methods

### flush()

Forces immediate transmission of all pending events to the platform.

**Returns:** `Promise<void>`

**Example:**

```javascript theme={null}
// Add some events
monitor.trackUserMessage('agent-1', 'session-1', 'Hello');
monitor.trackAgentResponse('agent-1', 'session-1', 'Hi there!');

// Force immediate send
await monitor.flush();
```

### shutdown()

Gracefully shuts down the monitor, flushing any remaining events and cleaning up resources.

**Returns:** `Promise<void>`

**Example:**

```javascript theme={null}
// At application shutdown
process.on('SIGTERM', async () => {
  await monitor.shutdown();
  process.exit(0);
});
```

## Properties

### complianceEngine

Access to the compliance engine instance (if enabled).

**Type:** `ComplianceEngine | undefined`

**Example:**

```javascript theme={null}
if (monitor.complianceEngine) {
  monitor.complianceEngine.addRule({
    id: 'custom-rule',
    name: 'Custom Banking Rule',
    description: 'Custom compliance check',
    category: 'custom',
    severity: 'warning',
    isActive: true,
    ruleFunction: (context) => {
      // Custom rule logic
      return {
        isCompliant: true,
        violations: [],
        riskScore: 0,
        requiresReview: false
      };
    }
  });
}
```

## Error Handling

The AgentMonitor class handles errors gracefully and provides detailed error information:

```javascript theme={null}
try {
  await monitor.registerAgent(agentInfo);
} catch (error) {
  console.error('Failed to register agent:', error.message);
  // Continue with application logic
}

// Tracking errors are logged but don't throw
monitor.trackUserMessage('agent-1', 'invalid-session-!@#', 'Hello');
// Logs validation error but continues execution
```

## Best Practices

<AccordionGroup>
  <Accordion title="Event Tracking">
    * Use consistent session IDs across related interactions
    * Include relevant metadata for better analytics
    * Track errors with sufficient context for debugging
    * Use meaningful agent IDs and descriptions
  </Accordion>

  <Accordion title="Performance">
    * Configure appropriate batch sizes for your volume
    * Use suitable flush intervals based on latency requirements
    * Monitor memory usage with large event volumes
    * Call shutdown() during application cleanup
  </Accordion>

  <Accordion title="Error Handling">
    * Wrap critical operations in try-catch blocks
    * Monitor failed requests and adjust retry settings
    * Use graceful degradation when monitoring fails
    * Log monitoring errors for debugging
  </Accordion>

  <Accordion title="Configuration">
    * Use environment variables for sensitive configuration
    * Adjust settings based on deployment environment
    * Enable compliance checks for regulated environments
    * Configure logging appropriately for each environment
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Compliance Engine" icon="shield-check" href="/api-reference/compliance-engine">
    Learn about the ComplianceEngine class and custom rules
  </Card>

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

  <Card title="Integration Examples" icon="play" href="/examples/basic-usage">
    Practical examples and integration patterns
  </Card>

  <Card title="Performance Guide" icon="gauge" href="/features/performance">
    Optimization strategies for high-volume scenarios
  </Card>
</CardGroup>
