Skip to main content
POST
http://api.gu1.ai
/
rules
/
{ruleId}
/
execute
Executar Regra
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": {}
}

Visão Geral

Ejecuta una regla específica contra una entidad para probar la lógica de la regla, validar condiciones y previsualizar resultados antes de desplegar a producción. Útil para probar reglas en modo shadow o depurar comportamiento de reglas.

Endpoint

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

Autenticação

Requer uma chave API válida no cabeçalho de Authorization:
Authorization: Bearer YOUR_API_KEY

Parâmetros de Rota

ruleId
string
required
UUID de la regla a ejecutar

Corpo da Requisição

entityId
string
required
UUID de la entidad a evaluar contra la regla
testMode
boolean
default:"false"
Si es true, ejecuta en modo de prueba sin crear alertas o modificar entidades
includeDebug
boolean
default:"false"
Si es true, incluye información de depuración detallada sobre evaluación de condiciones

Respuesta

matched
boolean
Si las condiciones de la regla coincidieron
score
number
Puntaje de riesgo asignado por la regla (si coincidió)
executionTime
number
Tiempo de ejecución en milisegundos
conditions
object
Resultados de evaluación detallados para cada condición
actions
array
Acciones que se ejecutarían (o fueron ejecutadas si no está en modo de prueba)
debug
object
Información de depuración (si includeDebug=true)

Exemplos de Requisições

Executar Regra en Modo de Prueba

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
  }'

Executar Regra en Modo de Producción

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
  }'

Ejemplos de Respuestas

Coincidencia Exitosa con Información de Depuración

{
  "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
  }
}

Sin Coincidencia

{
  "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
}

Modo de Producción - Acciones Ejecutadas

{
  "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"
      }
    }
  ]
}

Respostas de Erro

404 Not Found - Regla

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

404 Not Found - Entidad

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

400 Bad Request - Desajuste de Tipo

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

400 Bad Request - Regla Deshabilitada

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

Casos de Uso

Probar Nuevas Reglas

// Probar una nueva regla contra entidades de muestra antes de habilitar
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('Resultados de Prueba:', results);
  console.log('Tasa de coincidencia:',
    results.filter(r => r.matched).length / results.length * 100 + '%'
  );

  return results;
}

Depurar Comportamiento de Regla

def debug_rule_execution(rule_id, entity_id):
    """Obtener información detallada de depuración para ejecución de regla"""
    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"Regla Coincidió: {result['matched']}")
    print(f"Tiempo de Ejecución: {result['executionTime']}ms")
    print("\nEvaluación de Condiciones:")

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

    if result.get('debug'):
        print("\nInformación de Depuración:")
        print(f"  Short-circuited: {result['debug']['shortCircuited']}")
        print(f"  Cache hits: {result['debug']['cacheHits']}")

    return result

Pruebas por Lotes

// Probar múltiples entidades contra una regla
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('Resultados de Prueba por Lotes:', results);
  return results;
}

Melhores Práticas

  1. Siempre Probar Primero: Use testMode: true antes de ejecutar reglas en producción
  2. Habilitar Depuración para Desarrollo: Use includeDebug: true para entender comportamiento de reglas
  3. Probar Casos Extremos: Pruebe con entidades que deberían y no deberían coincidir
  4. Monitorear Tiempo de Ejecución: Optimice reglas que toman más de 200ms
  5. Validar Acciones: Revise detalles de acciones antes de habilitar modo de producción
  6. Usar Modo Shadow: Despliegue reglas con status: "shadow" para registrar coincidencias sin ejecutar acciones

Notas de Rendimiento

  • Tiempo promedio de ejecución: 50-150ms
  • Reglas sync bloquean la solicitud, reglas async retornan inmediatamente
  • Condiciones anidadas complejas pueden aumentar tiempo de ejecución
  • Evaluaciones de campos de array con filtros agregan ~10-30ms por array

Veja Também