Skip to main content

Template Variables

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

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

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 world

Template Variables in Execution

For both synchronous and asynchronous cognitive diagram execution, template variables work the same way:

{
"Action": "Execute",
"UserSays": "[{\"userSays\":\"Your message here\", \"customField\":\"value\"}]"
}

For long-running jobs:

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

Here are some common use cases for template variables:

Basic User Input

API Request:

{
"Action": "Execute",
"UserSays": "[{\"userSays\":\"How can I improve my sales?\"}]"
}

Template in Node:

{{userSays}}

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

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

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

  1. 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.

  2. In Your API Calls: Structure the JSON object within the UserSays string 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

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

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

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

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

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

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

Naming Conventions

  • Use clear and descriptive variable names (e.g., userName instead of n)
  • Follow camelCase convention for consistency: firstName, orderId, customerTier

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

// Usage
const templateData = sanitizeTemplateData({
userSays: message,
userName: user.name,
userId: user.id,
preferences: user.preferences // Will be stringified
});

Performance Optimization

  • Only pass necessary data - Don't include unused variables as they 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 structure
const requestData = {
userSays: message,
userId: user.id, // ID only
sessionId: session.id // Reference to cached session data
};

// Avoid: Bloated data structure
const requestData = {
userSays: message,
fullUserProfile: user, // Large object with many unused fields
fullSessionData: session // Another large object
};

Troubleshooting

Common Error Messages

  • "General error: variable not populated" or "General error: 'variableName'": This error occurs when a template variable referenced in your cognitive diagram (e.g., {{variableName}}) does not exist in the JSON object within your UserSays string. Check that the variable name in your template matches the field name in your API request JSON exactly (including case).

Security Considerations

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

Avoid passing sensitive information through template variables:

// ❌ Bad: Exposing sensitive data
const 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 IDs
const goodTemplate = {
userSays: message,
userId: user.id, // Safe identifier
sessionToken: session.token, // Temporary session reference
orderRef: order.referenceId // Safe reference number
};

By following these guidelines, you'll be able to effectively use template variables to create dynamic, personalized AI agents while maintaining security and performance best practices.