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

# Create Rule

> Create a new rule for risk detection and compliance monitoring — in the gu1 rules engine for compliance and risk detection, with examples for create use cases.

## Overview

Creates a new rule for automated risk detection, compliance monitoring, and fraud prevention. **Every create runs a synchronous AI review** (included; not debited from your AI token wallet) before the rule is persisted. New rules are always stored as **`in_progress`** with **`enabled: false`** so you can review suggestions and activate manually.

<Note>
  Request fields `status` and `enabled` on create are **ignored** — the API coerces `status: in_progress` and `enabled: false`. Expect **several seconds** of latency while the review completes. Bundle or template flows that create many rules run one review per rule.
</Note>

## Endpoint

```
POST http://api.gu1.ai/rules
```

## Authentication

Requires a valid API key in the Authorization header:

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

## Request Body

<ParamField body="name" type="string" required>
  Descriptive name for the rule
</ParamField>

<ParamField body="description" type="string" required>
  Detailed description of what the rule detects
</ParamField>

<ParamField body="category" type="string" required>
  Category of the rule: `kyc`, `kyb`, `aml`, `fraud`, `compliance`, `custom`
</ParamField>

<ParamField body="targetEntityTypes" type="array" required>
  Array of entity types this rule applies to: `["person"]`, `["company"]`, `["transaction"]`, `["person", "company"]`
</ParamField>

<ParamField body="conditions" type="object" required>
  Condition logic structure (see [Condition Structure](#condition-structure) below)
</ParamField>

<ParamField body="actions" type="array" required>
  Array of actions to execute when conditions match (see [Actions](#actions) below)
</ParamField>

<ParamField body="enabled" type="boolean">
  Ignored on create — rules are always stored with `enabled: false`.
</ParamField>

<ParamField body="priority" type="number" default="50">
  Rule priority (1-100). Higher values = higher priority
</ParamField>

<ParamField body="score" type="number">
  Risk score to assign when rule matches (0-100). Used in score-based risk matrices
</ParamField>

<ParamField body="status" type="string">
  Ignored on create — rules are always stored as `in_progress` (configuration).
</ParamField>

<ParamField body="evaluationMode" type="string" default="async">
  Evaluation mode: `sync` (immediate) or `async` (background processing)
</ParamField>

<ParamField body="riskMatrixId" type="string">
  UUID of the risk matrix to associate this rule with
</ParamField>

<ParamField body="countries" type="array">
  Array of ISO country codes to restrict rule execution: `["BR", "AR", "US"]`
</ParamField>

<ParamField body="scope" type="object">
  Additional scope configuration including temporal windows and triggers
</ParamField>

<ParamField body="tags" type="array">
  Array of tags for organizing rules: `["high-risk", "pep", "sanctions"]`
</ParamField>

<ParamField body="creationProvenance" type="object">
  Optional origin metadata persisted on the rule. If omitted, the API defaults to `sourceType: api` (API key) or `user` (session). Fields: `sourceType` (`user` | `agent` | `import_json` | `template` | `bundle` | `api`), `conversationId`, `messageId`, `platformAgentCategory`, `triggeredByUserId`.
</ParamField>

## Condition Structure

Rules use a nested condition structure with logical operators:

```json theme={null}
{
  "operator": "AND" | "OR" | "NOT" | "XOR",
  "conditions": [
    {
      "id": "cond-unique-id",
      "type": "simple",
      "field": "enrichmentData.normalized.taxId",
      "operator": "eq",
      "value": "12.345.678/0001-90",
      "filters": [],
      "countryMetadata": {
        "countryCode": "BR",
        "confidence": 100,
        "manuallySet": true,
        "autoDetected": false,
        "reason": "Selected from BR enrichment fields"
      }
    }
  ]
}
```

### Condition Fields

* **operator**: Logical operator connecting conditions (`AND`, `OR`, `NOT`, `XOR`)
* **conditions**: Array of condition objects (can be nested for complex logic)
* **id**: Unique identifier for the condition
* **type**: Condition type (`simple`, `complex`, `array`, `object`)
* **field**: Field path to evaluate (e.g., `taxId`, `entityData.company.revenue`, `enrichmentData.normalized.sanctions.$.type`)
* **operator**: Comparison operator (see [Operators](#operators) below)
* **value**: Value to compare against
* **filters**: Array of filters for array/object fields
* **countryMetadata**: Country-specific metadata for the condition

### Operators

#### Comparison Operators

* `eq` - Equals
* `neq` - Not equals
* `gt` - Greater than
* `gte` - Greater than or equal
* `lt` - Less than
* `lte` - Less than or equal

#### String Operators

* `contains` - Contains substring
* `notContains` - Does not contain substring
* `startsWith` - Starts with
* `endsWith` - Ends with
* `regex` - Matches regular expression

#### Array Operators

* `in` - Value is in array
* `notIn` - Value is not in array
* `hasAny` - Has any of the values
* `hasAll` - Has all of the values

#### List Operators

* `inList` - Value exists in a data list
* `notInList` - Value does not exist in a data list

#### Existence Operators

* `exists` - Field exists
* `notExists` - Field does not exist
* `isEmpty` - Field is empty/null
* `isNotEmpty` - Field is not empty/null

#### Boolean Operators

* `isTrue` - Boolean field is true
* `isFalse` - Boolean field is false

## Array Field Syntax

For fields within arrays, use the `$` symbol:

```json theme={null}
{
  "field": "enrichmentData.normalized.sanctions.$.type",
  "operator": "in",
  "value": "terrorism",
  "filters": []
}
```

This evaluates if ANY item in the `sanctions` array has `type` equal to `"terrorism"`.

### Filters

You can pre-filter array items before evaluation:

```json theme={null}
{
  "field": "enrichmentData.normalized.legalProceedings.$.amount",
  "operator": "gt",
  "value": 100000,
  "filters": [
    {
      "field": "status",
      "operator": "eq",
      "value": "active"
    }
  ]
}
```

This evaluates if ANY active legal proceeding has an amount greater than 100,000.

## Actions

Rules support multiple action types:

### Create Alert

```json theme={null}
{
  "type": "createAlert",
  "createAlert": {
    "type": "FRAUD" | "COMPLIANCE" | "AML" | "KYC" | "OTHER",
    "title": "High Risk Transaction Detected",
    "description": "Transaction exceeds threshold",
    "severity": "LOW" | "MEDIUM" | "HIGH" | "CRITICAL",
    "recipients": ["user@example.com"]
  },
  "tags": ["high-value", "cross-border"]
}
```

### Update Entity Status

```json theme={null}
{
  "type": "updateEntityStatus",
  "updateEntityStatus": {
    "status": "blocked",
    "reason": "Failed sanctions check"
  }
}
```

### Send Notification

```json theme={null}
{
  "type": "sendNotification",
  "sendNotification": {
    "channel": "email" | "sms" | "webhook",
    "recipients": ["compliance@company.com"],
    "message": "Urgent: High risk entity detected"
  }
}
```

### Create Case

```json theme={null}
{
  "type": "createCase",
  "createCase": {
    "title": "PEP Investigation Required",
    "description": "Entity flagged as politically exposed person",
    "assignee": "user-uuid"
  }
}
```

## Example Requests

### Simple KYC Rule - Check Tax ID

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST http://api.gu1.ai/rules \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "CNPJ Blocklist Check",
      "description": "Block companies with specific CNPJ",
      "category": "kyb",
      "targetEntityTypes": ["company"],
      "enabled": true,
      "priority": 100,
      "score": 85,
      "conditions": {
        "operator": "AND",
        "conditions": [
          {
            "id": "cond-1",
            "type": "simple",
            "field": "enrichmentData.normalized.taxId",
            "operator": "eq",
            "value": "33.592.510/0001-54",
            "filters": [],
            "countryMetadata": {
              "countryCode": "BR",
              "confidence": 100,
              "manuallySet": true,
              "autoDetected": false,
              "reason": "Selected from BR enrichment fields"
            }
          }
        ]
      },
      "actions": [
        {
          "type": "createAlert",
          "createAlert": {
            "type": "COMPLIANCE",
            "title": "Blocklisted Company Detected",
            "description": "Company CNPJ found in blocklist",
            "severity": "CRITICAL",
            "recipients": ["compliance@company.com"]
          },
          "tags": ["blocklist", "high-priority"]
        },
        {
          "type": "updateEntityStatus",
          "updateEntityStatus": {
            "status": "blocked",
            "reason": "CNPJ in blocklist"
          }
        }
      ],
      "scope": {
        "type": "entity",
        "countries": ["BR"],
        "entityTypes": ["company"]
      },
      "status": "active",
      "evaluationMode": "sync"
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('http://api.gu1.ai/rules', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      name: 'CNPJ Blocklist Check',
      description: 'Block companies with specific CNPJ',
      category: 'kyb',
      targetEntityTypes: ['company'],
      enabled: true,
      priority: 100,
      score: 85,
      conditions: {
        operator: 'AND',
        conditions: [
          {
            id: 'cond-1',
            type: 'simple',
            field: 'enrichmentData.normalized.taxId',
            operator: 'eq',
            value: '33.592.510/0001-54',
            filters: [],
            countryMetadata: {
              countryCode: 'BR',
              confidence: 100,
              manuallySet: true,
              autoDetected: false,
              reason: 'Selected from BR enrichment fields'
            }
          }
        ]
      },
      actions: [
        {
          type: 'createAlert',
          createAlert: {
            type: 'COMPLIANCE',
            title: 'Blocklisted Company Detected',
            description: 'Company CNPJ found in blocklist',
            severity: 'CRITICAL',
            recipients: ['compliance@company.com']
          },
          tags: ['blocklist', 'high-priority']
        }
      ],
      scope: {
        type: 'entity',
        countries: ['BR'],
        entityTypes: ['company']
      },
      status: 'active',
      evaluationMode: 'sync'
    })
  });

  const rule = await response.json();
  console.log('Rule created:', rule.id);
  ```

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

  response = requests.post(
      'http://api.gu1.ai/rules',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'name': 'CNPJ Blocklist Check',
          'description': 'Block companies with specific CNPJ',
          'category': 'kyb',
          'targetEntityTypes': ['company'],
          'enabled': True,
          'priority': 100,
          'score': 85,
          'conditions': {
              'operator': 'AND',
              'conditions': [
                  {
                      'id': 'cond-1',
                      'type': 'simple',
                      'field': 'enrichmentData.normalized.taxId',
                      'operator': 'eq',
                      'value': '33.592.510/0001-54',
                      'filters': [],
                      'countryMetadata': {
                          'countryCode': 'BR',
                          'confidence': 100,
                          'manuallySet': True,
                          'autoDetected': False,
                          'reason': 'Selected from BR enrichment fields'
                      }
                  }
              ]
          },
          'actions': [
              {
                  'type': 'createAlert',
                  'createAlert': {
                      'type': 'COMPLIANCE',
                      'title': 'Blocklisted Company Detected',
                      'description': 'Company CNPJ found in blocklist',
                      'severity': 'CRITICAL',
                      'recipients': ['compliance@company.com']
                  },
                  'tags': ['blocklist', 'high-priority']
              }
          ],
          'scope': {
              'type': 'entity',
              'countries': ['BR'],
              'entityTypes': ['company']
          },
          'status': 'active',
          'evaluationMode': 'sync'
      }
  )

  rule = response.json()
  print(f"Rule created: {rule['id']}")
  ```
</CodeGroup>

### Complex Rule - Sanctions Check with Multiple Conditions

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST http://api.gu1.ai/rules \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "Terrorism Sanctions Check",
      "description": "Detect entities with terrorism-related sanctions",
      "category": "aml",
      "targetEntityTypes": ["person", "company"],
      "enabled": true,
      "priority": 100,
      "score": 95,
      "conditions": {
        "operator": "OR",
        "conditions": [
          {
            "id": "cond-1",
            "type": "simple",
            "field": "enrichmentData.normalized.sanctions.$.type",
            "operator": "in",
            "value": "terrorism",
            "filters": [],
            "countryMetadata": {
              "countryCode": "GLOBAL",
              "confidence": 100,
              "manuallySet": true,
              "autoDetected": false,
              "reason": "Global sanctions field"
            }
          },
          {
            "id": "cond-2",
            "type": "simple",
            "field": "enrichmentData.normalized.sanctioned",
            "operator": "isTrue",
            "value": true,
            "filters": []
          }
        ]
      },
      "actions": [
        {
          "type": "createAlert",
          "createAlert": {
            "type": "AML",
            "title": "Sanctions Match - Immediate Review Required",
            "description": "Entity matched terrorism sanctions list",
            "severity": "CRITICAL",
            "recipients": ["aml-team@company.com"]
          },
          "tags": ["sanctions", "terrorism", "critical"]
        },
        {
          "type": "updateEntityStatus",
          "updateEntityStatus": {
            "status": "blocked",
            "reason": "Terrorism sanctions match"
          }
        },
        {
          "type": "createCase",
          "createCase": {
            "title": "Sanctions Investigation Required",
            "description": "Entity flagged for terrorism-related sanctions",
            "assignee": "compliance-lead-uuid"
          }
        }
      ],
      "scope": {
        "type": "entity",
        "entityTypes": ["person", "company"]
      },
      "status": "active",
      "evaluationMode": "sync",
      "tags": ["sanctions", "aml", "critical"]
    }'
  ```
</CodeGroup>

### Transaction Monitoring Rule

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST http://api.gu1.ai/rules \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "name": "High Value Transaction Alert",
      "description": "Alert on transactions over $50,000 USD",
      "category": "fraud",
      "targetEntityTypes": ["transaction"],
      "enabled": true,
      "priority": 80,
      "score": 70,
      "conditions": {
        "operator": "AND",
        "conditions": [
          {
            "id": "cond-1",
            "type": "simple",
            "field": "amountInUsd",
            "operator": "gt",
            "value": 50000,
            "filters": []
          },
          {
            "id": "cond-2",
            "type": "simple",
            "field": "status",
            "operator": "eq",
            "value": "PENDING",
            "filters": []
          }
        ]
      },
      "actions": [
        {
          "type": "createAlert",
          "createAlert": {
            "type": "FRAUD",
            "title": "High Value Transaction Detected",
            "description": "Transaction exceeds $50,000 threshold",
            "severity": "HIGH",
            "recipients": ["fraud-team@company.com"]
          },
          "tags": ["high-value", "pending-review"]
        }
      ],
      "scope": {
        "type": "transaction"
      },
      "status": "active",
      "evaluationMode": "sync"
    }'
  ```
</CodeGroup>

## Response

<ResponseField name="id" type="string">
  UUID of the created rule
</ResponseField>

<ResponseField name="name" type="string">
  Rule name
</ResponseField>

<ResponseField name="description" type="string">
  Rule description
</ResponseField>

<ResponseField name="organizationId" type="string">
  Your organization ID
</ResponseField>

<ResponseField name="status" type="string">
  Current rule status
</ResponseField>

<ResponseField name="enabled" type="boolean">
  Whether rule is enabled
</ResponseField>

<ResponseField name="version" type="number">
  Rule version number
</ResponseField>

<ResponseField name="createdAt" type="string">
  ISO timestamp of creation
</ResponseField>

<ResponseField name="createdBy" type="string">
  User ID who created the rule
</ResponseField>

<ResponseField name="creationProvenance" type="object">
  Origin metadata (`sourceType`, optional agent chat ids).
</ResponseField>

<ResponseField name="aiReview" type="object">
  Synchronous AI review summary: `verified`, `reason`, `functionalityDescription`, `suggestions`, `issues`.
</ResponseField>

## Response Example

```json theme={null}
{
  "success": true,
  "message": "Rule created successfully",
  "rule": {
  "id": "e2cdd639-52cc-4749-9b16-927bfa5dfaea",
  "organizationId": "71e8f908-e032-4fcb-b0ce-ad0cd0ffb236",
  "name": "CNPJ Blocklist Check",
  "description": "Block companies with specific CNPJ",
  "category": "kyb",
  "status": "in_progress",
  "enabled": false,
  "priority": 100,
  "score": 85,
  "conditions": {
    "operator": "AND",
    "conditions": [...]
  },
  "actions": [
    {
      "type": "createAlert",
      "createAlert": {...},
      "tags": ["blocklist", "high-priority"]
    }
  ],
  "scope": {
    "type": "entity",
    "countries": ["BR"],
    "entityTypes": ["company"]
  },
  "targetEntityTypes": ["company"],
  "evaluationMode": "sync",
  "version": 1,
  "previousVersionId": null,
  "tags": [],
  "createdBy": "f35c10cb-9b67-4cda-9aea-f36567375dba",
  "createdAt": "2024-12-23T10:00:00.000Z",
  "updatedAt": "2024-12-23T10:00:00.000Z",
  "stats": {
    "executions": 0,
    "successes": 0,
    "failures": 0
  }
  },
  "aiReview": {
    "verified": true,
    "reason": "Conditions align with description.",
    "functionalityDescription": "Creates a KYB alert when the CNPJ matches the blocklist.",
    "suggestions": [],
    "issues": []
  }
}
```

## Error Responses

### 400 Bad Request - Invalid Condition

```json theme={null}
{
  "error": "Validation failed",
  "details": {
    "field": "conditions",
    "message": "Invalid operator 'xyz'"
  }
}
```

### 400 Bad Request - Missing Required Fields

```json theme={null}
{
  "error": "Validation failed",
  "details": {
    "missingFields": ["name", "targetEntityTypes", "conditions"]
  }
}
```

### 401 Unauthorized

```json theme={null}
{
  "error": "Invalid or missing API key"
}
```

## Best Practices

1. **Start with Shadow Mode**: Use `status: "shadow"` to test rules without affecting production
2. **Use Descriptive Names**: Make rule names clear and searchable
3. **Set Appropriate Priorities**: Higher priority rules execute first (1-100 scale)
4. **Tag Your Rules**: Use tags for organization and filtering
5. **Country-Specific Rules**: Use `scope.countries` for geo-specific compliance
6. **Test Thoroughly**: Test rules with sample data before enabling
7. **Monitor Performance**: Use sync mode for critical real-time rules, async for batch processing
8. **Score Strategically**: Align scores with your risk matrix thresholds

## See Also

* [Condition Fields Reference](/en/api-reference/rules/conditions) - Complete list of available condition fields by entity type and country
* [Execute Rule](/en/api-reference/rules/execute) - Test rules against specific entities
* [List Rules](/en/api-reference/rules/list) - Query and filter rules
* [Update Rule](/en/api-reference/rules/update) - Modify existing rules
