🎨 Sistema de Variables Personalizadas - Guía Completa
📅 Fecha de Implementación: 24 de Octubre, 2025
🎯 ¿Qué son las Variables Personalizadas?
Las Variables Personalizadas son un sistema extensible que permite a los agentes IA y nodos de workflow almacenar y compartir cualquier tipo de dato entre pasos del workflow, más allá de solo proyectos y tareas.
🆚 Diferencia con Variables Dinámicas Estándar
| Característica | Variables Estándar | Variables Personalizadas |
|---|---|---|
| Propósito | IDs de proyectos/tareas | Cualquier dato de contexto |
| Nombres | Predefinidos (PROJECT_, TASKS_) |
Personalizados por el usuario |
| Tipos | Solo strings e IDs | string, number, object, array, boolean, api_response |
| Límite | Ilimitadas por tipo | Sin límite (recomendado 10-20 por ejecución) |
| Uso | Flujo de entidades | Contexto, datos de APIs, resultados de IA |
🚀 Casos de Uso
1. 📊 Almacenar Análisis de IA
// Agente IA analiza proyecto y guarda resumen
storeAIResult(workflowId, executionId, 'node_1', 'project_analysis', {
status: 'En progreso',
completion: 45,
blockers: ['Falta documentación'],
recommendations: ['Añadir tests unitarios']
});
// Nodo posterior usa el análisis
const analysis = getCustomVariableValue(workflowId, executionId, 'project_analysis');
console.log(analysis.recommendations); // ['Añadir tests unitarios']
2. 🌐 Guardar Respuestas de APIs
// Agente hace llamada a API externa
const response = await fetch('https://api.example.com/data');
const data = await response.json();
storeAPIResponse(
workflowId,
executionId,
'node_2',
'weather_data',
data,
'https://api.example.com/data'
);
// Siguiente nodo usa los datos
const weather = getCustomVariableValue(workflowId, executionId, 'weather_data');
3. 📝 Contexto Entre Múltiples Pasos
// Paso 1: Recopilar información
setCustomVariable(workflowId, executionId, 'node_1', 'user_preferences', {
theme: 'dark',
language: 'es',
notifications: true
}, 'object');
// Paso 2: Usar preferencias para configurar
const prefs = getCustomVariableValue(workflowId, executionId, 'user_preferences');
console.log(`Configurar tema: ${prefs.theme}`); // "dark"
4. 🔢 Contadores y Métricas
// Inicializar contador
setCustomVariable(workflowId, executionId, 'node_1', 'tasks_created_count', 0, 'number');
// Incrementar en cada paso
let count = getCustomVariableValue(workflowId, executionId, 'tasks_created_count');
count += 5;
setCustomVariable(workflowId, executionId, 'node_2', 'tasks_created_count', count, 'number');
// Final: Total de tareas creadas
const total = getCustomVariableValue(workflowId, executionId, 'tasks_created_count');
console.log(`Total tareas creadas: ${total}`); // 5
5. 🗂️ Datos Temporales de Configuración
// Almacenar configuración temporal
setCustomVariable(workflowId, executionId, 'node_1', 'build_config', {
environment: 'production',
version: '2.1.0',
features: ['auth', 'payments', 'notifications']
}, 'object', {
description: 'Configuración de build',
source: 'manual'
});
📚 API Completa
🔨 Crear/Actualizar Variable
setCustomVariable()
setCustomVariable(
workflowId, // ID del workflow
executionId, // ID de ejecución
nodeId, // ID del nodo que crea la variable
varName, // Nombre personalizado (letras, números, _)
value, // Valor de cualquier tipo
type, // 'string' | 'number' | 'object' | 'array' | 'boolean' | 'api_response'
metadata // { description, source, ...custom }
)
// Ejemplo
setCustomVariable(
'workflow_123',
'exec_456',
'node_ai_1',
'project_summary',
'Proyecto avanzando según plan',
'string',
{ description: 'Resumen generado por IA', source: 'ai_agent' }
);
Retorna: true si exitoso, false si error
Validación: Nombres solo pueden contener letras, números y guiones bajos (_)
📖 Obtener Variable
getCustomVariable()
getCustomVariable(workflowId, executionId, varName)
// Retorna objeto completo
{
value: "...",
type: "string",
nodeId: "node_ai_1",
timestamp: 1729800000000,
metadata: { description: "...", source: "..." }
}
getCustomVariableValue()
// Solo obtener el valor
const value = getCustomVariableValue(workflowId, executionId, 'project_summary');
console.log(value); // "Proyecto avanzando según plan"
📋 Listar Variables
getAllCustomVariables()
const allVars = getAllCustomVariables(workflowId, executionId);
// Retorna
{
"project_summary": { value: "...", type: "string", ... },
"user_count": { value: 42, type: "number", ... },
"api_data": { value: {...}, type: "object", ... }
}
getCustomVariablesByType()
// Filtrar por tipo
const objects = getCustomVariablesByType(workflowId, executionId, 'object');
const numbers = getCustomVariablesByType(workflowId, executionId, 'number');
getCustomVariablesByNode()
// Variables creadas por un nodo específico
const varsFromNode = getCustomVariablesByNode(workflowId, executionId, 'node_ai_1');
🗑️ Eliminar Variable
deleteCustomVariable()
deleteCustomVariable(workflowId, executionId, 'old_variable');
🎯 Funciones Especializadas
storeAIResult() - Para resultados de IA
storeAIResult(workflowId, executionId, nodeId, varName, aiResult)
// Ejemplo
storeAIResult(
workflowId,
executionId,
'node_ai_1',
'analysis_result',
{
sentiment: 'positive',
confidence: 0.95,
summary: 'Cliente satisfecho con el servicio'
}
);
storeAPIResponse() - Para respuestas de APIs
storeAPIResponse(workflowId, executionId, nodeId, varName, apiResponse, apiUrl)
// Ejemplo
const response = await fetch('https://api.github.com/repos/user/repo');
const data = await response.json();
storeAPIResponse(
workflowId,
executionId,
'node_api_1',
'github_repo_data',
data,
'https://api.github.com/repos/user/repo'
);
setMultipleCustomVariables() - Crear varias a la vez
setMultipleCustomVariables(workflowId, executionId, nodeId, {
'user_name': { value: 'John Doe', type: 'string' },
'user_age': { value: 30, type: 'number' },
'user_active': { value: true, type: 'boolean' },
'user_preferences': {
value: { theme: 'dark' },
type: 'object',
metadata: { description: 'User settings' }
}
});
// Retorna: 4 (número de variables creadas)
📊 Estadísticas
getCustomVariablesStats()
const stats = getCustomVariablesStats(workflowId, executionId);
// Retorna
{
total: 15,
byType: {
string: 5,
number: 3,
object: 4,
array: 2,
api_response: 1
},
byNode: {
'node_ai_1': 8,
'node_ai_2': 5,
'node_api_1': 2
},
oldestTimestamp: 1729800000000,
newestTimestamp: 1729800500000
}
🎨 Uso en Prompts de Agentes IA
Las variables personalizadas se pueden usar en prompts con la sintaxis ${varName}:
// Crear variable
setCustomVariable(workflowId, executionId, 'node_1', 'team_size', 5, 'number');
// Usar en prompt de siguiente nodo
const prompt = `
Crea un plan de proyecto para un equipo de ${team_size} personas.
Considera que cada persona puede manejar ${tasks_per_person} tareas simultáneas.
`;
// El sistema resolverá automáticamente:
// "Crea un plan de proyecto para un equipo de 5 personas..."
🔄 Integración con workflowAIHelpers.js
Para que los agentes IA puedan crear variables personalizadas automáticamente, se puede extender executeOutputActions:
// En workflowAIHelpers.js
if (aiResponse.customVariables) {
setMultipleCustomVariables(
workflowId,
executionId,
nodeId,
aiResponse.customVariables
);
}
Ejemplo de respuesta de IA con variables personalizadas:
{
"action": "create_task",
"tasks": [...],
"customVariables": {
"project_risk_level": {
"value": "medium",
"type": "string",
"metadata": { "description": "Nivel de riesgo evaluado" }
},
"estimated_duration_days": {
"value": 30,
"type": "number"
}
}
}
🎯 Tipos de Datos Soportados
1. string - Texto
setCustomVariable(wId, eId, nId, 'status', 'En progreso', 'string');
2. number - Números
setCustomVariable(wId, eId, nId, 'progress', 75.5, 'number');
3. boolean - Booleanos
setCustomVariable(wId, eId, nId, 'is_approved', true, 'boolean');
4. object - Objetos
setCustomVariable(wId, eId, nId, 'config', {
environment: 'production',
features: ['auth', 'api']
}, 'object');
5. array - Arrays
setCustomVariable(wId, eId, nId, 'tags', ['urgent', 'backend', 'api'], 'array');
6. api_response - Respuestas de API
storeAPIResponse(wId, eId, nId, 'weather', responseData, apiUrl);
🧪 Ejemplo Completo de Workflow
// ========================================
// NODO 1: Inicializar Contexto
// ========================================
const executionId = initializeExecutionContext(workflowId);
// Configurar variables iniciales
setMultipleCustomVariables(workflowId, executionId, 'node_init', {
'project_name': { value: 'Sistema de Tickets', type: 'string' },
'team_size': { value: 5, type: 'number' },
'sprint_duration': { value: 14, type: 'number' },
'technologies': { value: ['React', 'Node.js', 'PostgreSQL'], type: 'array' }
});
// ========================================
// NODO 2: IA Analiza y Planifica
// ========================================
const projectName = getCustomVariableValue(workflowId, executionId, 'project_name');
const teamSize = getCustomVariableValue(workflowId, executionId, 'team_size');
const prompt = `
Crea un plan para el proyecto "${projectName}" con un equipo de ${teamSize} personas.
`;
// IA ejecuta y guarda resultado
storeAIResult(workflowId, executionId, 'node_ai_plan', 'project_plan', {
phases: ['Diseño', 'Desarrollo', 'Testing', 'Deploy'],
estimatedWeeks: 8,
tasksCount: 25
});
// ========================================
// NODO 3: Crear Proyecto y Tareas
// ========================================
const plan = getCustomVariableValue(workflowId, executionId, 'project_plan');
// Crear proyecto dinámico
const project = { id: 'proj_123', name: projectName };
registerDynamicProject(workflowId, executionId, 'node_create_proj', project);
// Crear tareas basadas en el plan
const tasks = [];
for (let i = 0; i < plan.tasksCount; i++) {
tasks.push({ id: `task_${i}`, title: `Tarea ${i+1}`, projectId: project.id });
}
registerDynamicTasks(workflowId, executionId, 'node_create_tasks', tasks);
// ========================================
// NODO 4: Guardar Métricas
// ========================================
setCustomVariable(
workflowId,
executionId,
'node_metrics',
'workflow_metrics',
{
projectsCreated: 1,
tasksCreated: plan.tasksCount,
estimatedCompletion: new Date(Date.now() + plan.estimatedWeeks * 7 * 24 * 60 * 60 * 1000),
status: 'initialized'
},
'object',
{ description: 'Métricas del workflow', source: 'workflow_engine' }
);
// ========================================
// NODO 5: Resumen Final
// ========================================
const stats = getCustomVariablesStats(workflowId, executionId);
console.log(`Variables personalizadas creadas: ${stats.total}`);
console.log(`Proyectos creados: ${getExecutionStats(workflowId, executionId).projectsCreated}`);
console.log(`Tareas creadas: ${getExecutionStats(workflowId, executionId).tasksCreated}`);
// Limpiar al finalizar
clearExecutionContext(workflowId, executionId);
🎓 Mejores Prácticas
1. ✅ Usa nombres descriptivos
// ❌ Mal
setCustomVariable(wId, eId, nId, 'var1', 'test', 'string');
// ✅ Bien
setCustomVariable(wId, eId, nId, 'user_authentication_token', 'abc123', 'string');
2. ✅ Especifica el tipo correcto
// ❌ Mal
setCustomVariable(wId, eId, nId, 'count', '42', 'string'); // Número como string
// ✅ Bien
setCustomVariable(wId, eId, nId, 'count', 42, 'number');
3. ✅ Añade metadata descriptivo
setCustomVariable(
wId, eId, nId,
'api_key',
'sk_live_...',
'string',
{
description: 'API key de Stripe para pagos',
source: 'config',
expiresAt: Date.now() + 30 * 24 * 60 * 60 * 1000
}
);
4. ✅ Limpia variables no necesarias
// Al final de un workflow
deleteCustomVariable(workflowId, executionId, 'temp_cache');
5. ✅ Usa funciones especializadas
// ❌ Manual
setCustomVariable(wId, eId, nId, 'api_data', response, 'object', {
source: 'api',
apiUrl: url
});
// ✅ Con función especializada
storeAPIResponse(wId, eId, nId, 'api_data', response, url);
🔮 Futuras Mejoras
Planeadas
- Persistencia en localStorage
- Exportar/Importar variables entre ejecuciones
- Variables encriptadas para datos sensibles
- TTL (Time To Live) para variables temporales
- Validación de esquemas con JSON Schema
- Versionado de variables
- Variables globales compartidas entre workflows
En Consideración
- Compresión automática de objetos grandes
- Búsqueda full-text en valores de variables
- GraphQL API para consultar variables
- Webhooks cuando se crean/modifican variables
- Integración con Redis para caché distribuido
📞 Soporte
Para dudas o sugerencias sobre el sistema de variables personalizadas:
- Documentación técnica:
dynamicVariables.js(líneas 330+) - Ejemplos de uso: Este documento
- Debug:
debugExecutionContext(workflowId, executionId)
Versión: 2.0 - Sistema de Variables Personalizadas Última actualización: 24 de Octubre, 2025