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
}
'import requests
url = "http://api.gu1.ai/rules/{ruleId}/execute"
payload = {
"entityId": "<string>",
"testMode": True,
"includeDebug": True
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({entityId: '<string>', testMode: true, includeDebug: true})
};
fetch('http://api.gu1.ai/rules/{ruleId}/execute', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "http://api.gu1.ai/rules/{ruleId}/execute",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'entityId' => '<string>',
'testMode' => true,
'includeDebug' => true
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "http://api.gu1.ai/rules/{ruleId}/execute"
payload := strings.NewReader("{\n \"entityId\": \"<string>\",\n \"testMode\": true,\n \"includeDebug\": true\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("http://api.gu1.ai/rules/{ruleId}/execute")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"entityId\": \"<string>\",\n \"testMode\": true,\n \"includeDebug\": true\n}")
.asString();require 'uri'
require 'net/http'
url = URI("http://api.gu1.ai/rules/{ruleId}/execute")
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"entityId\": \"<string>\",\n \"testMode\": true,\n \"includeDebug\": true\n}"
response = http.request(request)
puts response.read_body{
"matched": true,
"score": 123,
"executionTime": 123,
"conditions": {},
"actions": [
{}
],
"debug": {}
}Referência API
Executar Regra
Executar uma regra contra uma entidade específica para testes e validação — no motor de regras gu1 para compliance e detecção de risco.
POST
/
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
}
'import requests
url = "http://api.gu1.ai/rules/{ruleId}/execute"
payload = {
"entityId": "<string>",
"testMode": True,
"includeDebug": True
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({entityId: '<string>', testMode: true, includeDebug: true})
};
fetch('http://api.gu1.ai/rules/{ruleId}/execute', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "http://api.gu1.ai/rules/{ruleId}/execute",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'entityId' => '<string>',
'testMode' => true,
'includeDebug' => true
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "http://api.gu1.ai/rules/{ruleId}/execute"
payload := strings.NewReader("{\n \"entityId\": \"<string>\",\n \"testMode\": true,\n \"includeDebug\": true\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("http://api.gu1.ai/rules/{ruleId}/execute")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"entityId\": \"<string>\",\n \"testMode\": true,\n \"includeDebug\": true\n}")
.asString();require 'uri'
require 'net/http'
url = URI("http://api.gu1.ai/rules/{ruleId}/execute")
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"entityId\": \"<string>\",\n \"testMode\": true,\n \"includeDebug\": true\n}"
response = http.request(request)
puts response.read_body{
"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
Corpo da Requisição
Si es true, incluye información de depuración detallada sobre evaluación de condiciones
Respuesta
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
}'
const response = await fetch(
'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea/execute',
{
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
entityId: '550e8400-e29b-41d4-a716-446655440000',
testMode: true,
includeDebug: true
})
}
);
const result = await response.json();
console.log('Regla coincidió:', result.matched);
console.log('Puntaje:', result.score);
console.log('Tiempo de ejecución:', result.executionTime + 'ms');
import requests
response = requests.post(
'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea/execute',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'entityId': '550e8400-e29b-41d4-a716-446655440000',
'testMode': True,
'includeDebug': True
}
)
result = response.json()
print(f"Regla coincidió: {result['matched']}")
print(f"Puntaje: {result['score']}")
print(f"Tiempo de ejecución: {result['executionTime']}ms")
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
}'
const response = await fetch(
'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea/execute',
{
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
entityId: '550e8400-e29b-41d4-a716-446655440000',
testMode: false
})
}
);
const result = await response.json();
if (result.matched) {
console.log('Regla coincidió! Acciones ejecutadas:', result.actions.length);
}
import requests
response = requests.post(
'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea/execute',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'entityId': '550e8400-e29b-41d4-a716-446655440000',
'testMode': False
}
)
result = response.json()
if result['matched']:
print(f"Regla coincidió! Acciones ejecutadas: {len(result['actions'])}")
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
- Siempre Probar Primero: Use
testMode: trueantes de ejecutar reglas en producción - Habilitar Depuración para Desarrollo: Use
includeDebug: truepara entender comportamiento de reglas - Probar Casos Extremos: Pruebe con entidades que deberían y no deberían coincidir
- Monitorear Tiempo de Ejecución: Optimice reglas que toman más de 200ms
- Validar Acciones: Revise detalles de acciones antes de habilitar modo de producción
- 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
- Criar Regra - Crear nuevas reglas
- Referência de Campos de Condições - Campos de condición disponibles
- Listar Regras - Consultar reglas
- Atualizar Regra - Modificar reglas existentes
Was this page helpful?