Skip to main content
POST
http://api.gu1.ai
/
rules
/
{ruleId}
/
execute
Execute Rule
curl --request POST \
  --url http://api.gu1.ai/rules/{ruleId}/execute \
  --header 'Authorization: Bearer <token>' \
  --header 'Content-Type: application/json' \
  --data '
{
  "entityId": "<string>",
  "testMode": true,
  "includeDebug": true
}
'
{
  "matched": true,
  "score": 123,
  "executionTime": 123,
  "conditions": {},
  "actions": [
    {}
  ],
  "debug": {}
}

Overview

Executes a specific rule against an entity to test rule logic, validate conditions, and preview results before deploying to production. Useful for testing rules in shadow mode or debugging rule behavior.

Endpoint

POST http://api.gu1.ai/rules/{ruleId}/execute

Authentication

Requires a valid API key in the Authorization header:
Authorization: Bearer YOUR_API_KEY

Path Parameters

ruleId
string
required
UUID of the rule to execute

Request Body

entityId
string
required
UUID of the entity to evaluate against the rule
testMode
boolean
default:"false"
If true, executes in test mode without creating alerts or modifying entities
includeDebug
boolean
default:"false"
If true, includes detailed debug information about condition evaluation

Response

matched
boolean
Whether the rule conditions matched
score
number
Risk score assigned by the rule (if matched)
executionTime
number
Execution time in milliseconds
conditions
object
Detailed evaluation results for each condition
actions
array
Actions that would be executed (or were executed if not in test mode)
debug
object
Debug information (if includeDebug=true)

Example Requests

Execute Rule in Test Mode

curl -X POST http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea/execute \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "entityId": "550e8400-e29b-41d4-a716-446655440000",
    "testMode": true,
    "includeDebug": true
  }'

Execute Rule in Production Mode

curl -X POST http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea/execute \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "entityId": "550e8400-e29b-41d4-a716-446655440000",
    "testMode": false
  }'

Response Examples

Successful Match with Debug Info

{
  "matched": true,
  "score": 85,
  "executionTime": 45,
  "conditions": {
    "operator": "AND",
    "result": true,
    "conditions": [
      {
        "id": "cond-1",
        "field": "enrichmentData.normalized.taxId",
        "operator": "eq",
        "expectedValue": "33.592.510/0001-54",
        "actualValue": "33.592.510/0001-54",
        "result": true
      }
    ]
  },
  "actions": [
    {
      "type": "createAlert",
      "status": "would_execute",
      "details": {
        "type": "COMPLIANCE",
        "title": "Blocklisted Company Detected",
        "severity": "CRITICAL"
      }
    },
    {
      "type": "updateEntityStatus",
      "status": "would_execute",
      "details": {
        "status": "blocked",
        "reason": "CNPJ in blocklist"
      }
    }
  ],
  "debug": {
    "entitySnapshot": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "type": "company",
      "taxId": "33.592.510/0001-54",
      "name": "Test Company"
    },
    "conditionEvaluationOrder": ["cond-1"],
    "shortCircuited": false,
    "cacheHits": 0
  }
}

No Match

{
  "matched": false,
  "score": 0,
  "executionTime": 23,
  "conditions": {
    "operator": "AND",
    "result": false,
    "conditions": [
      {
        "id": "cond-1",
        "field": "enrichmentData.normalized.taxId",
        "operator": "eq",
        "expectedValue": "33.592.510/0001-54",
        "actualValue": "12.345.678/0001-90",
        "result": false
      }
    ]
  },
  "actions": [],
  "debug": null
}

Production Mode - Actions Executed

{
  "matched": true,
  "score": 85,
  "executionTime": 156,
  "conditions": {
    "operator": "AND",
    "result": true,
    "conditions": [...]
  },
  "actions": [
    {
      "type": "createAlert",
      "status": "executed",
      "alertId": "alert-uuid-123",
      "details": {
        "type": "COMPLIANCE",
        "title": "Blocklisted Company Detected",
        "severity": "CRITICAL"
      }
    },
    {
      "type": "updateEntityStatus",
      "status": "executed",
      "details": {
        "previousStatus": "active",
        "newStatus": "blocked",
        "reason": "CNPJ in blocklist"
      }
    }
  ]
}

Error Responses

404 Not Found - Rule

{
  "error": "Rule not found",
  "ruleId": "e2cdd639-52cc-4749-9b16-927bfa5dfaea"
}

404 Not Found - Entity

{
  "error": "Entity not found",
  "entityId": "550e8400-e29b-41d4-a716-446655440000"
}

400 Bad Request - Type Mismatch

{
  "error": "Entity type mismatch",
  "details": {
    "ruleTargetTypes": ["company"],
    "entityType": "person",
    "message": "This rule only applies to company entities"
  }
}

400 Bad Request - Disabled Rule

{
  "error": "Rule is disabled",
  "ruleId": "e2cdd639-52cc-4749-9b16-927bfa5dfaea"
}

Use Cases

Testing New Rules

// Test a new rule against sample entities before enabling
async function testRuleAgainstSamples(ruleId, sampleEntityIds) {
  const results = [];

  for (const entityId of sampleEntityIds) {
    const response = await fetch(
      `http://api.gu1.ai/rules/${ruleId}/execute`,
      {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          entityId,
          testMode: true,
          includeDebug: true
        })
      }
    );

    const result = await response.json();
    results.push({
      entityId,
      matched: result.matched,
      executionTime: result.executionTime
    });
  }

  console.log('Test Results:', results);
  console.log('Match rate:',
    results.filter(r => r.matched).length / results.length * 100 + '%'
  );

  return results;
}

Debugging Rule Behavior

def debug_rule_execution(rule_id, entity_id):
    """Get detailed debug information for rule execution"""
    response = requests.post(
        f'http://api.gu1.ai/rules/{rule_id}/execute',
        headers={
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json'
        },
        json={
            'entityId': entity_id,
            'testMode': True,
            'includeDebug': True
        }
    )

    result = response.json()

    print(f"Rule Matched: {result['matched']}")
    print(f"Execution Time: {result['executionTime']}ms")
    print("\nCondition Evaluation:")

    for condition in result['conditions']['conditions']:
        print(f"  - {condition['field']}: ", end='')
        print(f"{condition['actualValue']} {condition['operator']} {condition['expectedValue']}")
        print(f"    Result: {'✅ Pass' if condition['result'] else '❌ Fail'}")

    if result.get('debug'):
        print("\nDebug Info:")
        print(f"  Short-circuited: {result['debug']['shortCircuited']}")
        print(f"  Cache hits: {result['debug']['cacheHits']}")

    return result

Batch Testing

// Test multiple entities against a rule
async function batchTestRule(ruleId, entityIds) {
  const batchSize = 10;
  const results = {
    total: entityIds.length,
    matched: 0,
    failed: 0,
    avgExecutionTime: 0
  };

  for (let i = 0; i < entityIds.length; i += batchSize) {
    const batch = entityIds.slice(i, i + batchSize);
    const promises = batch.map(entityId =>
      fetch(`http://api.gu1.ai/rules/${ruleId}/execute`, {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          entityId,
          testMode: true
        })
      }).then(r => r.json())
    );

    const batchResults = await Promise.all(promises);

    batchResults.forEach(result => {
      if (result.matched) results.matched++;
      results.avgExecutionTime += result.executionTime;
    });
  }

  results.avgExecutionTime = Math.round(
    results.avgExecutionTime / entityIds.length
  );

  console.log('Batch Test Results:', results);
  return results;
}

Best Practices

  1. Always Test First: Use testMode: true before running rules in production
  2. Enable Debug for Development: Use includeDebug: true to understand rule behavior
  3. Test Edge Cases: Test with entities that should and shouldn’t match
  4. Monitor Execution Time: Optimize rules that take longer than 200ms
  5. Validate Actions: Review action details before enabling production mode
  6. Use Shadow Mode: Deploy rules with status: "shadow" to log matches without executing actions

Performance Notes

  • Average execution time: 50-150ms
  • Sync rules block the request, async rules return immediately
  • Complex nested conditions may increase execution time
  • Array field evaluations with filters add ~10-30ms per array

See Also