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

Constructor

AgentMonitor(config)

Creates a new instance of the AgentMonitor with the specified configuration.
config
AgentMonitoringConfig
required
Configuration object for the monitor instance.
Example:
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.
agent
AgentInfo
required
Agent information and configuration.
Returns: Promise<void> Example:
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.
agentId
string
required
The ID of the agent handling the conversation.
sessionId
string
required
Unique identifier for the conversation session.
userId
string
Optional identifier for the user initiating the conversation.
metadata
object
Optional metadata object with additional context.
Example:
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.
agentId
string
required
The ID of the agent receiving the message.
sessionId
string
required
The conversation session identifier.
content
string
required
The content of the user’s message.
userId
string
Optional user identifier.
metadata
object
Optional metadata with additional context.
Example:
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.
agentId
string
required
The ID of the responding agent.
sessionId
string
required
The conversation session identifier.
content
string
required
The content of the agent’s response.
metadata
object
Optional metadata including performance and quality metrics.
options
MonitoringOptions
Optional monitoring configuration for this specific interaction.
Example:
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.
agentId
string
required
The ID of the agent making the tool call.
sessionId
string
required
The conversation session identifier.
toolName
string
required
The name of the tool being called.
parameters
any
required
The parameters passed to the tool.
result
any
The result returned by the tool (if available).
executionTime
number
Time taken to execute the tool in milliseconds.
metadata
object
Optional metadata with additional context.
Example:
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.
agentId
string
required
The ID of the agent where the error occurred.
sessionId
string
required
The conversation session identifier.
error
string | Error
required
The error message or Error object.
metadata
object
Optional metadata with error details.
Example:
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.
agentId
string
required
The ID of the agent ending the conversation.
sessionId
string
required
The conversation session identifier.
metadata
object
Optional metadata with conversation summary.
Example:
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.
agentId
string
required
The ID of the agent associated with the event.
event
InteractionEvent
required
The event object to track.
options
MonitoringOptions
Optional monitoring configuration.
Example:
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:
// 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:
// 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:
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:
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

Next Steps