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

# Execute Risk Matrix

> Run risk matrix scoring on a person or company entity using the gu1 rules engine with configurable triggers and matrix automations.

## Overview

Manually triggers risk matrix analysis for an entity using configured rules. The risk matrix evaluates the entity against all active rules and calculates a risk score. Optionally enriches the entity before analysis.

This is the same endpoint used for [Analyze Entity](/en/api-reference/entities/analyze), but documented here for convenience when specifically working with risk matrices.

## Endpoint

```
POST http://api.gu1.ai/entities/{entityId}/analyze
```

## Authentication

Requires a valid API key in the Authorization header:

```bash theme={null}
Authorization: Bearer YOUR_API_KEY
```

## Path Parameters

<ParamField path="entityId" type="string" required>
  UUID of the entity (company or person) to analyze
</ParamField>

## Request Body

<ParamField body="entityType" type="string" required>
  Type of entity to analyze

  * `person` - Individual/person entity
  * `company` - Company/business entity
  * `transaction` - Transaction entity
</ParamField>

<ParamField body="enrichIfNeeded" type="boolean" default="false">
  Whether to run data enrichment before analysis. If `true`, will execute all active enrichment integrations configured for this organization.
</ParamField>

<ParamField body="providerCodes" type="array<string>">
  Specific enrichment provider codes to execute before analysis. Only used when `enrichIfNeeded` is `true`. See [Provider Codes Reference](/en/api-reference/integrations/provider-codes).
</ParamField>

<ParamField body="rulesEngineConfig" type="object">
  Per-run rules engine behavior. See [Analyze Entity — rulesEngineConfig](/en/api-reference/entities/analyze#request-body) (`partialCoverage`, `omitCoverage`; both default `false`).
</ParamField>

## Response

<ResponseField name="success" type="boolean">
  Whether the analysis was successful
</ResponseField>

<ResponseField name="data" type="object">
  Analysis result data:

  * `id` (string) - Audit ID for this analysis
  * `entityId` (string) - Entity that was analyzed
  * `entityType` (string) - Type of entity
  * `overallRiskScore` (number) - Overall risk score (0-100)
  * `riskLevel` (string) - Risk level: `LOW`, `MEDIUM`, `HIGH`, `CRITICAL`
  * `confidence` (number) - Confidence level of the analysis (0-100)
  * `rulesTriggered` (number) - Number of rules that matched
  * `rulesExecuted` (number) - Total number of rules evaluated
  * `executionTimeMs` (number) - Total execution time in milliseconds
  * `riskFactors` (array) - Rules that matched/triggered
  * `recommendations` (array) - Recommended actions
  * `analyzedAt` (string) - ISO timestamp of analysis
  * `triggeredBy` (string) - Who/what triggered the analysis
  * `metadata` (object) - Additional metadata including matrix info
</ResponseField>

<ResponseField name="rulesResult" type="object">
  Full rules execution result when analysis ran: **success**, **executed**, **result**, **rulesTriggered**, **executionTimeMs**, **auditId**, **isNewAudit**, **rulesExecutionSummary** (same as root field below).
</ResponseField>

<ResponseField name="rulesExecutionSummary" type="object">
  **At the root of the response** (same as transactions API). Same value as `rulesResult.rulesExecutionSummary`. Only present when rules ran. Summary of which rules matched (hit) vs did not (no hit), executed actions, and total score. Structure: **rulesHit**, **rulesNoHit**, **actionsExecuted** (includes **alerts**, **suggestion**, **status**, **assignedUser**, **customKeys** — array of custom action keys from matched rules, for integrations/workflows), **totalScore**.
</ResponseField>

## Examples

### Basic Risk Matrix Execution

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000/analyze \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "entityType": "person"
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000/analyze',
    {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        entityType: 'person'
      })
    }
  );

  const data = await response.json();
  console.log(`Risk Score: ${data.data.overallRiskScore}`);
  console.log(`Risk Level: ${data.data.riskLevel}`);
  console.log(`Rules Triggered: ${data.data.rulesTriggered}`);
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000/analyze',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'entityType': 'person'
      }
  )

  data = response.json()
  print(f"Risk Score: {data['data']['overallRiskScore']}")
  print(f"Risk Level: {data['data']['riskLevel']}")
  print(f"Rules Triggered: {data['data']['rulesTriggered']}")
  ```
</CodeGroup>

### Execute with Auto-Enrichment

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000/analyze \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "entityType": "company",
      "enrichIfNeeded": true
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000/analyze',
    {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        entityType: 'company',
        enrichIfNeeded: true
      })
    }
  );

  const data = await response.json();
  console.log(`Enrichment + Analysis completed in ${data.data.executionTimeMs}ms`);
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000/analyze',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'entityType': 'company',
          'enrichIfNeeded': True
      }
  )

  data = response.json()
  print(f"Analysis completed in {data['data']['executionTimeMs']}ms")
  ```
</CodeGroup>

### Execute with Specific Enrichments

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000/analyze \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "entityType": "person",
      "enrichIfNeeded": true,
      "providerCodes": [
        "br_cpfcnpj_complete_person_enrichment",
        "global_complyadvantage_person_search_enrichment"
      ]
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000/analyze',
    {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        entityType: 'person',
        enrichIfNeeded: true,
        providerCodes: [
          'br_cpfcnpj_complete_person_enrichment',
          'global_complyadvantage_person_search_enrichment'
        ]
      })
    }
  );
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000/analyze',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'entityType': 'person',
          'enrichIfNeeded': True,
          'providerCodes': [
              'br_cpfcnpj_complete_person_enrichment',
              'global_complyadvantage_person_search_enrichment'
          ]
      }
  )
  ```
</CodeGroup>

## Response Example

### Successful Analysis

```json theme={null}
{
  "success": true,
  "data": {
    "id": "audit_789xyz",
    "entityId": "550e8400-e29b-41d4-a716-446655440000",
    "entityType": "person",
    "overallRiskScore": 75,
    "riskLevel": "HIGH",
    "confidence": 85,
    "rulesTriggered": 3,
    "rulesExecuted": 15,
    "executionTimeMs": 1250,
    "riskFactors": [
      {
        "ruleId": "rule_pep_detection",
        "ruleName": "PEP Detection",
        "matched": true,
        "score": 35,
        "severity": "HIGH",
        "category": "compliance",
        "priority": 1,
        "description": "Entity identified as politically exposed person",
        "actionsExecuted": [
          {
            "type": "createAlert",
            "details": {
              "title": "PEP Detected",
              "severity": "HIGH"
            }
          },
          {
            "type": "updateEntityStatus",
            "details": {
              "status": "under_review"
            }
          }
        ]
      },
      {
        "ruleId": "rule_high_income",
        "ruleName": "High Income Threshold",
        "matched": true,
        "score": 25,
        "severity": "MEDIUM",
        "category": "financial",
        "priority": 3
      },
      {
        "ruleId": "rule_age_verification",
        "ruleName": "Age Verification",
        "matched": true,
        "score": 15,
        "severity": "LOW",
        "category": "identity",
        "priority": 5
      }
    ],
    "recommendations": [
      "Enhanced due diligence required",
      "Review PEP relationships",
      "Verify source of funds"
    ],
    "analyzedAt": "2024-12-24T10:30:00.000Z",
    "triggeredBy": "manual_evaluation",
    "metadata": {
      "matrixId": "rm_abc123",
      "matrixName": "AML Risk Matrix",
      "matrixVersion": 1,
      "totalRulesEvaluated": 15,
      "rulesMatched": 3,
      "cached": false
    }
  }
}
```

### No Active Rules Warning

```json theme={null}
{
  "success": true,
  "warning": {
    "code": "NO_RULES_FOUND",
    "message": "No active rules found for this entity type. Please configure rules in the Risk Matrix to enable risk analysis."
  },
  "data": {
    "entityId": "550e8400-e29b-41d4-a716-446655440000",
    "entityType": "person",
    "overallRiskScore": 0,
    "rulesTriggered": 0,
    "rulesExecuted": 0,
    "analyzedAt": "2024-12-24T10:30:00.000Z"
  }
}
```

### Incomplete Data Coverage

```json theme={null}
{
  "success": false,
  "error": {
    "code": "INCOMPLETE_DATA_COVERAGE",
    "message": "Cannot calculate risk score without complete data coverage",
    "details": {
      "missingFields": ["taxId", "dateOfBirth", "nationality"],
      "recommendedProviders": [
        "br_cpfcnpj_complete_person_enrichment"
      ],
      "warnings": [
        "Required field 'taxId' is missing",
        "Required field 'dateOfBirth' is missing"
      ]
    }
  }
}
```

## Risk Levels

The system calculates risk levels based on the overall risk score:

* **LOW** (0-29): Minimal risk, standard processing
* **MEDIUM** (30-59): Moderate risk, standard monitoring required
* **HIGH** (60-79): Elevated risk, enhanced monitoring required
* **CRITICAL** (80-100): Severe risk, immediate action and enhanced due diligence required

## Rule Actions

When rules match, they can trigger automatic actions:

* **createAlert** - Creates an alert for manual review
* **updateEntityStatus** - Changes entity status (e.g., to `under_review`)
* **addTag** - Adds tags to the entity for categorization
* **sendEmail** - Sends email notification
* **webhook** - Triggers webhook for external integration

## Error Responses

### 404 Not Found - Entity Not Found

```json theme={null}
{
  "success": false,
  "error": {
    "code": "ENTITY_NOT_FOUND",
    "message": "Entity not found"
  }
}
```

### 401 Unauthorized

```json theme={null}
{
  "success": false,
  "error": {
    "code": "UNAUTHORIZED",
    "message": "User ID is required"
  }
}
```

### 422 Unprocessable Entity - Incomplete Data

```json theme={null}
{
  "success": false,
  "error": {
    "code": "INCOMPLETE_DATA_COVERAGE",
    "message": "Cannot calculate risk score without complete data coverage",
    "details": {
      "missingFields": ["taxId"],
      "recommendedProviders": ["br_cpfcnpj_complete_person_enrichment"]
    }
  }
}
```

## Real-Time Notifications

When risk matrix execution completes, a real-time notification is sent via WebSocket:

```json theme={null}
{
  "notificationType": "RISK_MATRIX_EXECUTED",
  "title": "Risk Matrix Executed",
  "message": "Risk analysis completed for entity",
  "severity": "INFO",
  "details": {
    "entityId": "550e8400-e29b-41d4-a716-446655440000",
    "riskScore": 75,
    "riskLevel": "HIGH",
    "rulesTriggered": 3
  }
}
```

## Best Practices

1. **Enrich First**: For best results, enrich entity data before analysis using `enrichIfNeeded: true`
2. **Handle Warnings**: Check for `NO_RULES_FOUND` warning and configure rules if needed
3. **Data Coverage**: Ensure required fields are populated to avoid `INCOMPLETE_DATA_COVERAGE` errors
4. **Monitor Actions**: Review `actionsExecuted` to understand what automated actions were taken
5. **Caching**: Results are cached for performance - use `cached` field to check if analysis is fresh

## Use Cases

### Onboarding Risk Assessment

```javascript theme={null}
// Enrich and analyze new customer during onboarding
const analysis = await fetch(
  `http://api.gu1.ai/entities/${customerId}/analyze`,
  {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      entityType: 'person',
      enrichIfNeeded: true
    })
  }
);

const result = await analysis.json();

// Make decision based on risk level
if (result.data.riskLevel === 'CRITICAL') {
  await rejectOnboarding(customerId);
} else if (result.data.riskLevel === 'HIGH') {
  await requestManualReview(customerId);
} else {
  await approveOnboarding(customerId);
}
```

### Periodic Re-assessment

```python theme={null}
import schedule
import time

def reassess_high_value_customers():
    """Periodically re-assess high-value customers"""
    customers = get_high_value_customers()

    for customer in customers:
        response = requests.post(
            f'http://api.gu1.ai/entities/{customer["id"]}/analyze',
            headers={'Authorization': 'Bearer YOUR_API_KEY'},
            json={'entityType': 'person'}
        )

        result = response.json()
        if result['data']['riskLevel'] in ['HIGH', 'CRITICAL']:
            notify_compliance_team(customer['id'], result['data'])

# Run daily at 2 AM
schedule.every().day.at("02:00").do(reassess_high_value_customers)

while True:
    schedule.run_pending()
    time.sleep(60)
```

### Transaction Risk Scoring

```javascript theme={null}
// Analyze risk before processing high-value transaction
async function processTransaction(transaction) {
  // First, analyze sender
  const senderAnalysis = await analyzeEntity(
    transaction.senderId,
    'person'
  );

  // Then analyze receiver
  const receiverAnalysis = await analyzeEntity(
    transaction.receiverId,
    'person'
  );

  // Calculate combined risk
  const combinedRisk = Math.max(
    senderAnalysis.data.overallRiskScore,
    receiverAnalysis.data.overallRiskScore
  );

  if (combinedRisk >= 80) {
    return { approved: false, reason: 'High risk participants' };
  }

  return { approved: true };
}
```

## Next Steps

* [Create Risk Matrix](/en/api-reference/risk-matrix/create) - Configure your risk assessment rules
* [Create Rule](/en/api-reference/rules/create) - Add individual rules to your matrix
* [Execute Enrichment](/en/api-reference/risk-matrix/execute-enrichment) - Enrich data before analysis
* [List Alerts](/en/api-reference/alerts/list) - View alerts generated by rules
* [Provider Codes Reference](/en/api-reference/integrations/provider-codes) - Available enrichment providers
