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

# Compliance Engine

> Real-time, offline compliance monitoring for AI agents in financial services.

The **Compliance Engine** is a core component of the AI Agents House SDK, providing powerful, real-time compliance monitoring for AI agent interactions. It operates **offline**, evaluating conversations against a robust set of built-in and custom rules **without introducing network latency**, ensuring your agents adhere to critical banking and financial service regulations.

***

## 🔑 Key Features

* **Real-time & Offline**: Scans agent responses instantly without needing to send data to an external service, ensuring maximum performance and privacy.

* **Banking-Specific Rules**: Comes pre-configured with rulesets designed for the financial industry, including **PII detection**, **Fair Lending**, and **BSA/AML** keyword monitoring.

* **Extensible**: Easily add custom rules to enforce your organization's specific policies, brand voice, or regional compliance requirements.

* **Risk Scoring**: Each potential violation contributes to a **risk score**, helping you prioritize which interactions require manual review.

***

## ⚙️ How It Works

The Compliance Engine integrates seamlessly with the `AgentMonitor`. When enabled, it intercepts agent responses and evaluates them against all active rules before the data is batched for submission.

<Steps>
  <Step title="1. Enable Compliance">
    Set `enableComplianceChecks: true` in your AgentMonitor configuration. This activates the engine.
  </Step>

  <Step title="2. Agent Registration">
    Define agent-specific compliance settings, such as `fair_lending_monitoring: true`, when you register your agent.
  </Step>

  <Step title="3. Track Agent Response">
    When you track an agent's response using `monitor.trackAgentResponse()` or an automated wrapper, the response content is passed to the engine.
  </Step>

  <Step title="4. Rule Evaluation">
    The engine evaluates the response against all active rules (both built-in and custom).
  </Step>

  <Step title="5. Generate Compliance Result">
    The engine produces a `ComplianceResult` object, detailing any violations, a calculated risk score, and whether the interaction requires manual review. This result is attached to the event data sent to the governance dashboard.
  </Step>
</Steps>

***

## 🧪 Basic Usage Example

Enabling the engine is straightforward. The results of the compliance check are automatically included in the event data sent to the AI Agents House platform.

```js theme={null}
import { AgentMonitor } from '@agent-governance/node';

// 1. Initialize monitor with compliance checks enabled
const monitor = new AgentMonitor({
  apiKey: process.env.AGENT_GOVERNANCE_API_KEY,
  organizationId: 'your-org-id',
  enableComplianceChecks: true, // This is the key
});

// 2. Register an agent with compliance settings
await monitor.registerAgent({
  id: 'loan-officer-agent',
  name: 'Loan Officer Assistant',
  // ... other agent details
  complianceSettings: {
    sr11_7_enabled: true,
    fair_lending_monitoring: true,
    bsa_aml_checks: true,
  },
});

const sessionId = 'session-compliance-123';

// 3. Track a response that contains a PII violation
monitor.trackAgentResponse(
  'loan-officer-agent',
  sessionId,
  'To proceed, please confirm your SSN is 123-45-6789.'
);

// The SDK will now detect the SSN, flag a compliance violation,
// calculate a risk score, and send this data to your dashboard.
await monitor.shutdown();
```

## 🛠 Creating a Custom Rule

You can extend the engine's capabilities by adding your own rules.
For example, here's how to ensure a specific disclosure is made whenever a mortgage product is discussed:

```js theme={null}
// Define the custom rule
const mortgageDisclosureRule = {
  id: 'mortgage-disclosure-check',
  name: 'Mortgage Rate Disclosure Check',
  description: 'Ensures that mentioning "mortgage" is accompanied by a rate disclosure.',
  category: 'consumer_protection',
  severity: 'warning',
  isActive: true,
  ruleFunction: (context) => {
    const violations = [];
    const agentResponse = (context.agentResponse || '').toLowerCase();

    const mentionsMortgage = agentResponse.includes('mortgage');
    const hasDisclosure = agentResponse.includes('rates are subject to change');

    if (mentionsMortgage && !hasDisclosure) {
      violations.push({
        rule: 'mortgage-disclosure-check',
        severity: 'warning',
        description: 'A mortgage product was mentioned without the required interest rate disclosure.',
        context: {
          fullResponse: context.agentResponse,
          missingPhrase: 'rates are subject to change'
        },
        recommendation: 'Update agent prompts to include the standard rate disclosure when discussing mortgages.'
      });
    }

    return {
      isCompliant: violations.length === 0,
      violations,
      riskScore: violations.length * 20, // Add 20 to the risk score if violated
      requiresReview: violations.length > 0,
    };
  }
};

// Add the rule to the engine instance
if (monitor.complianceEngine) {
  monitor.complianceEngine.addRule(mortgageDisclosureRule);
  console.log('Successfully added custom mortgage disclosure rule.');
}
```

## ✅ Best Practices

<AccordionGroup>
  <Accordion title="Rule Development">
    * **Keep Rules Focused**: Each rule should check for one specific type of violation.
    * **Use Descriptive IDs**: Follow a consistent naming convention (e.g., `category-specific-check`).
    * **Provide Actionable Recommendations**: Help developers or reviewers take quick corrective action.
  </Accordion>

  <Accordion title="Performance">
    * **Optimize Regex**: Ensure your expressions are efficient since rules run frequently.
    * **Avoid Network Calls**: Rules must be synchronous and fast to preserve agent response times.
  </Accordion>

  <Accordion title="Management">
    * **Version Control Rules**: Keep rule definitions in your repo with the app code.
    * **Regularly Review**: Update rules as compliance needs evolve.
    * **Test Thoroughly**: See our Testing Guide for strategies.
  </Accordion>
</AccordionGroup>

***

## 🚀 Next Steps

<CardGroup cols={2}>
  <Card title="Custom Rules Example" icon="diagram-subtask" href="/examples/custom-rules">
    See more detailed examples of creating custom compliance rules.
  </Card>

  <Card title="ComplianceEngine API" icon="shield-check" href="/api-reference/compliance-engine">
    Explore the full API for managing rules and evaluations.
  </Card>

  <Card title="Configuration Guide" icon="gear" href="/features/configuration">
    Learn how to configure compliance settings for each agent.
  </Card>

  <Card title="Testing Guide" icon="flask" href="https://www.google.com/search?q=/guides/testing">
    Find strategies for testing your compliance setup.
  </Card>
</CardGroup>
