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

# Analyze Entity

> Manual risk analysis of entity using rules engine — in the gu1 universal entity model for KYC, KYB, and risk analysis, with examples for analyze use cases.

## Overview

Manually triggers risk analysis for an entity using the configured risk matrix and rules. Optionally enriches the entity before analysis.

## Endpoint

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

## Path Parameters

<ParamField path="entityId" type="string" required>
  UUID of the entity to analyze
</ParamField>

## Request Body

<ParamField body="entityType" type="string" required>
  Entity type: person, company, or transaction
</ParamField>

<ParamField body="enrichIfNeeded" type="boolean" default="false">
  Whether to run enrichment before analysis
</ParamField>

<ParamField body="providerCodes" type="array">
  Specific provider codes to execute for enrichment
</ParamField>

<ParamField body="rulesEngineConfig" type="object">
  Per-run rules engine behavior. All fields optional; omitted fields default to `false`.

  * **`partialCoverage`** (boolean, default `false`): With **multiple assigned risk matrices**, validate data coverage **per matrix**. Matrices without coverage are skipped; others still run. If none have coverage, returns `422`.
  * **`omitCoverage`** (boolean, default `false`): Skip data coverage gates entirely (main entity pre-check and shareholder coverage). Takes precedence over `partialCoverage` when both are `true`.

  Does not change org-level `shareholderCoverageMode`.
</ParamField>

## Example Requests

### Basic Analysis

```bash theme={null}
curl -X POST http://api.gu1.ai/entities/entity-123/analyze \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "entityType": "person"
  }'
```

### Analysis with Enrichment

```bash theme={null}
curl -X POST http://api.gu1.ai/entities/entity-123/analyze \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "entityType": "company",
    "enrichIfNeeded": true
  }'
```

### Analysis with Specific Providers

```bash theme={null}
curl -X POST http://api.gu1.ai/entities/entity-123/analyze \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "entityType": "person",
    "providerCodes": [
      "global_complyadvantage_pep_enrichment",
      "global_complyadvantage_sanctions_enrichment"
    ]
  }'
```

### Multi-Matrix Analysis with Per-Matrix Coverage

Use when an entity has several risk matrices but you want matrices with sufficient data to run even if others are missing enrichments:

```bash theme={null}
curl -X POST http://api.gu1.ai/entities/entity-123/analyze \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "entityType": "company",
    "rulesEngineConfig": {
      "partialCoverage": true
    }
  }'
```

## Response - Success

The response includes `data` (analysis details), and when rules ran also **`rulesResult`** and **`rulesExecutionSummary`** at the root (same as create, enrich, refresh).

<ResponseField name="rulesResult" type="object">
  Full rules execution result when analysis ran: **success**, **executed**, **result**, **rulesTriggered**, **executionTimeMs**, **auditId**, **isNewAudit**, **rulesExecutionSummary** (same object 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**, **totalScore**.
</ResponseField>

```json theme={null}
{
  "success": true,
  "data": {
    "id": "audit-789",
    "entityId": "entity-123",
    "entityType": "person",
    "overallRiskScore": 75,
    "riskLevel": "HIGH",
    "rulesTriggered": 3,
    "rulesExecuted": 15,
    "executionTimeMs": 342,
    "riskFactors": [
      {
        "ruleName": "PEP Detection",
        "ruleId": "rule-456",
        "matched": true,
        "score": 35,
        "severity": "HIGH",
        "category": "compliance"
      }
    ],
    "recommendations": [
      "Enhanced due diligence required",
      "Review PEP relationships"
    ],
    "analyzedAt": "2024-12-23T10:00:00Z",
    "metadata": {
      "matrixId": "rm-123",
      "matrixName": "AML Risk Matrix",
      "matrixVersion": 1
    }
  },
  "rulesResult": {
    "success": true,
    "executed": true,
    "rulesTriggered": 3,
    "executionTimeMs": 342,
    "auditId": "audit-789",
    "isNewAudit": true,
    "rulesExecutionSummary": { "rulesHit": [], "rulesNoHit": [], "actionsExecuted": {}, "totalScore": 75 }
  },
  "rulesExecutionSummary": { "rulesHit": [], "rulesNoHit": [], "actionsExecuted": {}, "totalScore": 75 }
}
```

## Response - Partial matrix execution (`rulesEngineConfig.partialCoverage: true`)

When some assigned matrices lack data coverage but at least one matrix can run, the request succeeds (`200`). Skipped matrices are listed at the root:

```json theme={null}
{
  "success": true,
  "data": { "entityId": "entity-123", "overallRiskScore": 42 },
  "rulesExecutionSummary": { "totalScore": 42 },
  "warnings": [
    "Risk matrix Onboarding missing enrichment for field sanctioned"
  ],
  "matricesSkippedForCoverage": [
    {
      "riskMatrixId": "rm-onboarding",
      "riskMatrixName": "Onboarding",
      "errorCode": "INCOMPLETE_DATA_COVERAGE",
      "coverageSummary": "Risk matrix Onboarding missing enrichment for field sanctioned"
    }
  ]
}
```

The audit row stores executed matrix IDs in `risk_matrix_ids`; skipped matrices appear in `analysisResult.matricesSkippedForCoverage`.

## Response - No Rules Configured

```json theme={null}
{
  "success": true,
  "warning": {
    "code": "NO_RULES_FOUND",
    "message": "No active rules found for this entity type"
  },
  "data": {
    "entityId": "entity-123",
    "entityType": "person",
    "rulesTriggered": 0,
    "analyzedAt": "2024-12-23T10:00:00Z"
  }
}
```

## Response - Incomplete Data

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

## Risk Levels

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

## Use Cases

### Analyze After Data Update

```javascript theme={null}
// Update entity data
await updateEntity(entityId, newData);

// Re-analyze to get updated risk score
const analysis = await fetch(
  `http://api.gu1.ai/entities/${entityId}/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();
console.log(`Risk Score: ${result.data.overallRiskScore}`);
```

### Batch Analysis

```python theme={null}
import asyncio
import aiohttp

async def analyze_entities(entity_ids):
    async with aiohttp.ClientSession() as session:
        tasks = []
        for entity_id in entity_ids:
            task = session.post(
                f'http://api.gu1.ai/entities/{entity_id}/analyze',
                headers={'Authorization': 'Bearer YOUR_API_KEY'},
                json={'entityType': 'company'}
            )
            tasks.append(task)

        results = await asyncio.gather(*tasks)
        return [await r.json() for r in results]

# Analyze multiple entities
entity_ids = ['entity-1', 'entity-2', 'entity-3']
results = asyncio.run(analyze_entities(entity_ids))

for result in results:
    print(f"Entity: {result['data']['entityId']}")
    print(f"Risk Score: {result['data']['overallRiskScore']}")
```

## See Also

* [Materialize relationships](/en/api-reference/entities/materialize-relationships) — shareholders / related entities from normalized data (e.g. Brazil QSA)
* [Create Risk Matrix](/en/api-reference/risk-matrix/create)
* [Create Rule](/en/api-reference/rules/create)
* [List Alerts](/en/api-reference/alerts/list)
* [Person Provider Codes](/en/api-reference/integrations/person-provider-codes)
* [Company Provider Codes](/en/api-reference/integrations/company-provider-codes)
