Acumulacion de Variables

Como fluyen y se acumulan las variables entre acciones y ejecuciones

variablesacumulacionflujocontextoparentchildpropagacion

Acumulacion de Variables

Las variables fluyen y se acumulan a medida que la ejecucion avanza. Entender este flujo es esencial para diseñar automatizaciones efectivas.

Flujo de Variables

Ciclo de Vida

┌─────────────┐
│   TRIGGER   │ ──▶ Variables iniciales (evento)
└──────┬──────┘
       │
       ▼
┌─────────────┐
│  ACCION 1   │ ──▶ Lee variables + Agrega resultado
└──────┬──────┘
       │
       ▼
┌─────────────┐
│  ACCION 2   │ ──▶ Lee acumulado + Agrega resultado
└──────┬──────┘
       │
       ▼
┌─────────────┐
│  ACCION N   │ ──▶ Lee todo + Resultado final
└─────────────┘

Variables del Trigger

Origen de Variables Iniciales

Cada tipo de trigger proporciona variables especificas:

APPLICATION_CREATED:

{
  "postulantId": 123,
  "postulantName": "Juan Perez",
  "postulantEmail": "juan@email.com",
  "postulantPhone": "+52 55 1234 5678",
  "applicationId": 456,
  "jobPositionId": 789,
  "jobPositionTitle": "Desarrollador Senior",
  "processId": 10,
  "taskId": 100,
  "stepId": 1,
  "stepName": "Aplicacion",
  "source": "career_page"
}

TASK_MOVED:

{
  "taskId": 100,
  "processId": 10,
  "postulantId": 123,
  "fromStepId": 1,
  "fromStepName": "Aplicacion",
  "toStepId": 2,
  "toStepName": "Entrevista",
  "movedBy": 5,
  "isFinal": false
}

MESSAGE_RECEIVED:

{
  "threadId": 200,
  "messageId": 500,
  "postulantId": 123,
  "messageContent": "Hola, tengo una pregunta",
  "channel": "whatsapp",
  "timestamp": "2024-01-10T14:30:00Z"
}

Acumulacion por Accion

Como se Acumulan

Cada accion puede:

  1. Leer variables existentes
  2. Agregar nuevas variables al contexto
  3. Modificar variables existentes (con precaucion)

Ejemplo de Flujo

Trigger: APPLICATION_CREATED
├── postulantId: 123
├── applicationId: 456
└── jobPositionId: 789

Accion 1: analyze_cv
├── [hereda todo lo anterior]
├── skills: ["React", "Node.js"]
├── experience: { years: 5 }
└── education: "Computer Science"

Accion 2: calculate_match
├── [hereda todo lo anterior]
├── matchScore: 85
└── recommendation: "interview"

Accion 3: send_email
├── [hereda todo lo anterior]
├── emailSent: true
└── emailId: "msg_abc123"

Estado Final:
{
  postulantId: 123,
  applicationId: 456,
  jobPositionId: 789,
  skills: ["React", "Node.js"],
  experience: { years: 5 },
  education: "Computer Science",
  matchScore: 85,
  recommendation: "interview",
  emailSent: true,
  emailId: "msg_abc123"
}

Variables de Resultado de Accion

Estructura de Resultado

Cada accion retorna un resultado que se integra al contexto:

// Resultado de accion
{
  "success": true,
  "output": {
    "matchScore": 85,
    "recommendation": "interview"
  },
  "variables": {
    "matchScore": 85,
    "isQualified": true
  }
}

Variables Automaticas

VariableDescripcion
{{previousAction.success}}Si la accion anterior fue exitosa
{{previousAction.output}}Output completo de accion anterior
{{previousAction.error}}Error si fallo

Acceso a Resultados Especificos

// En la accion siguiente
{
  "message": "Tu score es {{matchScore}}%",
  "condition": "{{isQualified}} == true"
}

Variables entre Parent-Child

Pasando Variables al Hijo

Cuando un padre dispara un hijo con trigger_agent:

{
  "actionType": "trigger_agent",
  "parameters": {
    "targetAgentId": 5,
    "waitForCompletion": true,
    "passVariables": ["postulantId", "applicationId", "matchScore"]
  }
}

Si passVariables no se especifica: Se pasan TODAS las variables.

Variables Disponibles en Hijo

// Hijo recibe:
{
  "postulantId": 123,
  "applicationId": 456,
  "matchScore": 85,
  "parentExecutionId": 100,  // Referencia al padre
  "parentAgentId": 1
}

Variables de Retorno al Padre

Cuando el hijo completa, sus variables regresan al padre:

// Padre recibe al resumir:
{
  // Variables originales del padre
  "postulantId": 123,
  "applicationId": 456,
  "matchScore": 85,

  // Variables agregadas por el hijo
  "documentsCollected": true,
  "documentUrls": ["url1", "url2"],

  // Metadatos del hijo
  "triggeredExecutionId": 101,
  "childExecutionStatus": "completed",
  "childExecutionSuccess": true
}

Flujo Completo Parent-Child

PADRE (exec 100)
├── Variables: { postulantId: 123, applicationId: 456 }
│
├── Accion 1: calculate_match
│   └── Agrega: { matchScore: 85 }
│
├── Accion 2: trigger_agent (hijo)
│   │
│   └── HIJO (exec 101)
│       ├── Hereda: { postulantId, applicationId, matchScore }
│       │
│       ├── Accion 1: request_document
│       │   └── Agrega: { documentRequestId: 200 }
│       │
│       ├── Accion 2: wait_for_response
│       │   └── Agrega: { documentsUploaded: true }
│       │
│       └── COMPLETA con: { documentUrls: [...] }
│
├── [RESUME] Recibe variables del hijo
│   └── Agrega: { documentUrls, childExecutionSuccess }
│
└── Accion 3: send_confirmation
    └── Usa: {{ documentUrls }} del hijo

Variables en Espera (WAITING)

Antes de WAITING

// Estado antes de wait_for_response
{
  "postulantId": 123,
  "messageSent": true,
  "questionAsked": "Tienes disponibilidad?"
}

Despues de Resume

// Estado despues de resume
{
  "postulantId": 123,
  "messageSent": true,
  "questionAsked": "Tienes disponibilidad?",

  // Variables agregadas por resume
  "lastResponse": "Si, tengo disponibilidad esta semana",
  "responseReceived": true,
  "responseTimestamp": "2024-01-10T15:30:00Z"
}

SET_VARIABLE Action

Crear Variables Manualmente

{
  "actionType": "set_variable",
  "parameters": {
    "variables": [
      {
        "name": "isUrgent",
        "value": "{{daysOpen > 30}}"
      },
      {
        "name": "priority",
        "value": "{{matchScore >= 80 ? 'high' : 'normal'}}"
      },
      {
        "name": "fullName",
        "value": "{{postulantFirstName}} {{postulantLastName}}"
      }
    ]
  }
}

Variables Calculadas

TipoEjemplo
Booleano"{{score >= 80}}" → true
Ternario"{{score >= 80 ? 'pass' : 'fail'}}" → "pass"
Concatenacion"{{firstName}} {{lastName}}" → "Juan Perez"
Aritmetico"{{salary * 12}}" → 600000

Scope de Variables

Scope de Ejecucion

Variables viven durante la ejecucion:

Ejecucion 100 inicia
├── postulantId = 123  (disponible)
├── ... acciones ...
└── Ejecucion 100 termina
    └── Variables se persisten en execution.variables

Scope Global (Secrets)

Variables que persisten entre ejecuciones:

// Acceso a secrets
{
  "apiKey": "{{secrets.EXTERNAL_API_KEY}}",
  "webhookUrl": "{{secrets.WEBHOOK_URL}}"
}

Scope de Thread (Conversacion)

Variables que persisten en el hilo de conversacion:

// threadState persiste entre mensajes
{
  "threadState": {
    "currentTopic": "documentos",
    "collectedInfo": { ... },
    "lastQuestionAsked": "..."
  }
}

Debugging de Variables

Ver Variables en Ejecucion

SELECT
  id,
  status,
  JSON_PRETTY(variables) as variables
FROM agent_execution
WHERE id = 123;

Logs de Variables

[AgentGraph] Action analyze_cv completed
[AgentGraph] Variables updated: +skills, +experience, +education
[AgentGraph] Current context: { postulantId, applicationId, skills, ... }

Variables en UI

En el detalle de ejecucion:

CONTEXTO FINAL

VariableValorOrigen
postulantId123trigger
applicationId456trigger
skills["React", "Node"]analyze_cv
matchScore85calculate_match
emailSenttruesend_email

Buenas Practicas

Nombrado de Variables

DO:

  • Nombres descriptivos: matchScore, isQualified
  • camelCase consistente
  • Prefijos para agrupar: doc_, test_, email_

DON'T:

  • Nombres genericos: x, temp, data
  • Sobreescribir variables del trigger
  • Variables con espacios o caracteres especiales

Manejo de Valores Nulos

// Usar default para evitar errores
{
  "message": "Hola {{postulantName | default:'Candidato'}}"
}

// Verificar existencia
{
  "condition": "{{phone}} exists AND {{phone}} != ''"
}

Limpieza de Contexto

Para ejecuciones largas, considerar limpiar variables innecesarias:

{
  "actionType": "set_variable",
  "parameters": {
    "variables": [
      { "name": "tempData", "value": null },
      { "name": "intermediateResult", "value": null }
    ]
  }
}

Proximos Pasos

¿No encontraste lo que buscabas?

Nuestro equipo de soporte está listo para ayudarte.

Contactar Soporte