Advanced Template Variables
Advanced template variables guide for the Builder API - covers complex data structures, dynamic prompting, integration patterns, sanitization, security, and troubleshooting for {{placeholder}} syntax in cognitive diagram nodes.
Template variables are a powerful feature in Synthreo that allow you to pass data from your API calls directly into your cognitive diagram nodes. This enables you to create dynamic and context-aware AI agents that can generate personalized responses based on user input and other contextual information.
How Template Variables Work
Section titled “How Template Variables Work”When you execute a cognitive diagram via the API, you can include any number of fields in the JSON object within the UserSays string. These fields can then be referenced as template variables within your cognitive diagram nodes using double curly braces (e.g., {{variableName}}).
API Request to Template Variable Mapping
Section titled “API Request to Template Variable Mapping”API Request:
{ "Action": "Execute", "UserSays": "[{\"userSays\":\"Hello world\", \"userName\":\"John\"}]"}In a Cognitive Diagram Node:
Hello {{userName}}! You said: {{userSays}}Resulting Output:
Hello John! You said: Hello worldTemplate Variables in Different Execution Types
Section titled “Template Variables in Different Execution Types”Synchronous Execution
Section titled “Synchronous Execution”For regular cognitive diagram execution, template variables work as shown above:
{ "Action": "Execute", "UserSays": "[{\"userSays\":\"Your message here\", \"customField\":\"value\"}]"}Asynchronous Job Execution
Section titled “Asynchronous Job Execution”For long-running jobs, template variables work the same way but within the job execution context:
{ "Action": "Execute", "UserSays": "[{\"userSays\":\"start\", \"dataSource\":\"https://docs.example.com\", \"processingType\":\"full\"}]", "RobotSays": "", "CallerSource": 1}Template Usage in Job Context:
Process data from: {{dataSource}}Processing type: {{processingType}}User command: {{userSays}}Common Template Variables
Section titled “Common Template Variables”Here are some common use cases for template variables:
Basic User Input
Section titled “Basic User Input”API Request:
{ "Action": "Execute", "UserSays": "[{\"userSays\":\"How can I improve my sales?\"}]"}Template in Node:
{{userSays}}User Context
Section titled “User Context”Provide information about the user to personalize the interaction.
API Request:
{ "Action": "Execute", "UserSays": "[{ \"userSays\":\"What's my account status?\", \"userId\":\"12345\", \"userName\":\"Alice\", \"userEmail\":\"alice@example.com\" }]"}Template in Node:
Hello {{userName}}, let me check the account status for user ID {{userId}}.
User query: {{userSays}}Conversation Context
Section titled “Conversation Context”Maintain context across multiple turns in a conversation.
API Request:
{ "Action": "Execute", "UserSays": "[{ \"userSays\":\"Can you help me with that?\", \"conversationId\":\"conv-123\", \"previousContext\":\"User was asking about pricing\" }]"}Template in Node:
Based on our previous conversation ({{previousContext}}), here's how I can help: {{userSays}}
Conversation ID: {{conversationId}}System and Metadata Variables
Section titled “System and Metadata Variables”Pass system information and metadata to your cognitive diagrams:
API Request:
{ "Action": "Execute", "UserSays": "[{ \"userSays\":\"Generate a report\", \"requestId\":\"req-456\", \"timestamp\":\"2024-01-15T10:30:00Z\", \"requestSource\":\"mobile-app\", \"apiVersion\":\"v1.2\" }]"}Template in Node:
Processing request: {{requestId}}Initiated at: {{timestamp}}Source: {{requestSource}}API Version: {{apiVersion}}
User request: {{userSays}}Setting Up Template Variables
Section titled “Setting Up Template Variables”-
In Your Cognitive Diagram: When configuring your nodes (especially AI nodes like Azure OpenAI), use the
{{variableName}}syntax to insert placeholders for your dynamic data. The variable names are case-sensitive and must match the field names in your API request JSON exactly. -
In Your API Calls: Structure the JSON object within the
UserSaysstring to include all the data your template variables require.
const requestBody = { Action: "Execute", UserSays: JSON.stringify([{ userSays: message, // Maps to {{userSays}} userName: user.name, // Maps to {{userName}} userRole: user.role, // Maps to {{userRole}} timestamp: new Date().toISOString() // Maps to {{timestamp}} }])};Advanced Examples
Section titled “Advanced Examples”E-commerce Assistant
Section titled “E-commerce Assistant”API Request:
{ "Action": "Execute", "UserSays": "[{ \"userSays\":\"I want to return this item\", \"orderId\":\"ORD-789\", \"customerTier\":\"Premium\", \"purchaseDate\":\"2024-01-15\", \"itemName\":\"Wireless Headphones\" }]"}Template in Node (Azure OpenAI):
You are a customer service agent helping a {{customerTier}} customer.
Customer inquiry: {{userSays}}Order ID: {{orderId}}Item: {{itemName}}Purchase Date: {{purchaseDate}}
Please provide a helpful response about their return request, considering their Premium status.Multi-language Support
Section titled “Multi-language Support”API Request:
{ "Action": "Execute", "UserSays": "[{ \"userSays\":\"¿Cómo puedo cambiar mi contraseña?\", \"language\":\"es\", \"userLocale\":\"es-MX\" }]"}Template in Node:
Respond in {{language}} (locale: {{userLocale}}) to this user question: {{userSays}}Dynamic Prompting
Section titled “Dynamic Prompting”API Request:
{ "Action": "Execute", "UserSays": "[{ \"userSays\":\"Explain quantum computing\", \"audienceLevel\":\"beginner\", \"responseStyle\":\"friendly\", \"maxWords\":200 }]"}Template in Node:
Explain this topic to a {{audienceLevel}} audience using a {{responseStyle}} tone.Keep your response under {{maxWords}} words.
Topic: {{userSays}}Training Data Processing
Section titled “Training Data Processing”For agents that process training data, you can pass configuration through template variables:
API Request:
{ "Action": "Execute", "UserSays": "[{ \"userSays\":\"go\", \"sourceUrl\":\"https://docs.yourcompany.com\", \"maxPages\":100, \"includeImages\":false, \"processingSeed\":\"training-2024-01\" }]", "RobotSays": "", "CallerSource": 1}Template in Training Node:
Source: {{sourceUrl}}Max pages to process: {{maxPages}}Include images: {{includeImages}}Processing identifier: {{processingSeed}}Command: {{userSays}}Complex Data Structures
Section titled “Complex Data Structures”Nested Objects
Section titled “Nested Objects”You can pass complex data structures through template variables:
API Request:
{ "Action": "Execute", "UserSays": "[{ \"userSays\":\"Process my order\", \"userProfile\":\"{\\\"name\\\":\\\"John\\\",\\\"tier\\\":\\\"Gold\\\",\\\"preferences\\\":{\\\"language\\\":\\\"en\\\",\\\"timezone\\\":\\\"UTC-5\\\"}}\", \"orderData\":\"{\\\"items\\\":3,\\\"total\\\":299.99,\\\"currency\\\":\\\"USD\\\"}\" }]"}Template Usage:
User Profile: {{userProfile}}Order Details: {{orderData}}Query: {{userSays}}Note: Complex nested objects are passed as JSON strings and can be parsed within your cognitive diagram logic.
Array Data
Section titled “Array Data”Pass array data for batch processing or multiple items:
API Request:
{ "Action": "Execute", "UserSays": "[{ \"userSays\":\"Analyze these items\", \"itemList\":\"[\\\"item1\\\",\\\"item2\\\",\\\"item3\\\"]\", \"itemCount\":3 }]"}Template Usage:
Processing {{itemCount}} items: {{itemList}}User request: {{userSays}}Best Practices
Section titled “Best Practices”Naming Conventions
Section titled “Naming Conventions”- Use clear and descriptive variable names (e.g.,
userNameinstead ofn) - Follow camelCase convention for consistency:
firstName,orderId,customerTier - Use meaningful prefixes for related data:
userId,userName,userEmail
Data Validation and Sanitization
Section titled “Data Validation and Sanitization”Before sending your API request, validate and sanitize data:
function sanitizeTemplateData(data) { const sanitized = {};
for (const [key, value] of Object.entries(data)) { if (typeof value === 'string') { // Remove potentially harmful characters but preserve functionality sanitized[key] = value.replace(/[<>]/g, '').trim(); } else if (typeof value === 'number' && !isNaN(value)) { sanitized[key] = value; } else if (typeof value === 'boolean') { sanitized[key] = value; } else { // For objects/arrays, stringify them sanitized[key] = JSON.stringify(value); } }
return sanitized;}
// Usageconst templateData = sanitizeTemplateData({ userSays: message, userName: user.name, userId: user.id, preferences: user.preferences // Will be stringified});Default Values and Error Handling
Section titled “Default Values and Error Handling”Handle missing variables gracefully in your cognitive diagram:
Hello {{userName || "valued customer"}}!Processing request: {{userSays}}Order ID: {{orderId || "Not provided"}}Or use conditional logic in your templates:
{{#if userName}}Hello {{userName}}!{{else}}Hello there!{{/if}}
Your request: {{userSays}}Performance Optimization
Section titled “Performance Optimization”- Only pass necessary data - unused variables consume bandwidth and processing time
- Use efficient data formats - consider passing IDs instead of full objects when possible
- Cache frequently used data rather than passing it in every request
// Good: Lean data structureconst requestData = { userSays: message, userId: user.id, // ID only sessionId: session.id // Reference to cached session data};
// Avoid: Bloated data structureconst requestData = { userSays: message, fullUserProfile: user, // Large object with many unused fields fullSessionData: session // Another large object};Integration Patterns
Section titled “Integration Patterns”Building Dynamic Templates
Section titled “Building Dynamic Templates”Create reusable template builders:
class TemplateBuilder { constructor() { this.data = {}; }
addUser(user) { this.data.userId = user.id; this.data.userName = user.name; this.data.userEmail = user.email; return this; }
addMessage(message) { this.data.userSays = message; return this; }
addContext(context) { Object.assign(this.data, context); return this; }
build() { return JSON.stringify([this.data]); }}
// Usageconst userSays = new TemplateBuilder() .addUser(currentUser) .addMessage("Hello AI") .addContext({ sessionId: "sess-123", requestId: generateId() }) .build();Template Variable Mapping
Section titled “Template Variable Mapping”Map your application data to template variables consistently:
const TemplateMapper = { mapUser: (user) => ({ userId: user.id, userName: user.displayName || user.name, userEmail: user.email, userRole: user.role, userTier: user.subscriptionTier }),
mapOrder: (order) => ({ orderId: order.id, orderTotal: order.total, orderCurrency: order.currency, orderItems: order.items.length, orderDate: order.createdAt }),
mapSession: (session) => ({ sessionId: session.id, conversationId: session.conversationId, timestamp: new Date().toISOString(), requestCount: session.requestCount })};
// Build comprehensive template datafunction buildTemplateData(message, user, order = null, session = null) { return { userSays: message, ...TemplateMapper.mapUser(user), ...(order && TemplateMapper.mapOrder(order)), ...(session && TemplateMapper.mapSession(session)) };}Troubleshooting
Section titled “Troubleshooting”Common Error Messages
Section titled “Common Error Messages”-
“General error: variable not populated”: This error typically means that a template variable in your cognitive diagram was not populated by your API call. Check that the variable name in your template matches the field name in your API request JSON exactly (including case).
-
“General error: ‘variableName’”: Similar to above - the specific variable name mentioned is missing from your API request JSON.
-
Empty Template Variables: If a variable is appearing as empty in the output, double-check:
- The spelling and case of the variable name
- The JSON structure in your
UserSaysstring is valid - The data type is compatible (strings, numbers, booleans work best)
Debugging Template Variables
Section titled “Debugging Template Variables”Add debugging information to your requests:
{ "Action": "Execute", "UserSays": "[{ \"userSays\":\"Debug request\", \"debugInfo\":\"Template test\", \"timestamp\":\"2024-01-15T10:30:00Z\", \"requestId\":\"req-debug-001\" }]"}In your cognitive diagram, create a debug node:
DEBUG INFO:- Request ID: {{requestId}}- Timestamp: {{timestamp}}- Debug Info: {{debugInfo}}- User Says: {{userSays}}- All variables received successfully!JSON Structure Validation
Section titled “JSON Structure Validation”Validate your JSON structure before sending:
function validateTemplateVariables(templateData) { const errors = [];
// Check required fields if (!templateData.userSays) { errors.push('userSays is required'); }
// Check data types for (const [key, value] of Object.entries(templateData)) { if (typeof value === 'object' && value !== null) { try { JSON.stringify(value); } catch (e) { errors.push(`${key} contains non-serializable data`); } } }
// Check variable names (no spaces, special chars) for (const key of Object.keys(templateData)) { if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)) { errors.push(`Invalid variable name: ${key}`); } }
return errors;}Security Considerations
Section titled “Security Considerations”Data Sanitization
Section titled “Data Sanitization”Always sanitize user input before using in template variables:
function sanitizeForTemplate(input) { if (typeof input !== 'string') return input;
return input .replace(/[<>]/g, '') // Remove angle brackets .replace(/javascript:/gi, '') // Remove javascript: protocol .replace(/on\w+\s*=/gi, '') // Remove event handlers .trim();}Sensitive Data Handling
Section titled “Sensitive Data Handling”Avoid passing sensitive information through template variables:
// Bad: Exposing sensitive dataconst badTemplate = { userSays: message, userPassword: user.password, // Never do this apiKey: process.env.API_KEY, // Never expose API keys creditCard: user.paymentInfo // Avoid sensitive payment data};
// Good: Use references and IDsconst goodTemplate = { userSays: message, userId: user.id, // Safe identifier sessionToken: session.token, // Temporary session reference orderRef: order.referenceId // Safe reference number};By following these comprehensive guidelines, you’ll be able to effectively use template variables to create dynamic, personalized AI agents while maintaining security and performance best practices.
Related pages:
- Template Variables - introductory template variables guide
- Cognitive Diagrams API - the Execute endpoint where
UserSaysis sent - Best Practices - input sanitization and security patterns
- Examples - complete code examples using template variables