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\"}]"}```text**In a Cognitive Diagram Node:**
```textHello {{userName}}! You said: {{userSays}}```text**Resulting Output:**
```textHello John! You said: Hello world```text## Template Variables in Different Execution Types
### Synchronous Execution
For regular cognitive diagram execution, template variables work as shown above:
```json{ "Action": "Execute", "UserSays": "[{\"userSays\":\"Your message here\", \"customField\":\"value\"}]"}```text### Asynchronous Job Execution
For long-running jobs, template variables work the same way but within the job execution context:
```json{ "Action": "Execute", "UserSays": "[{\"userSays\":\"start\", \"dataSource\":\"https://docs.example.com\", \"processingType\":\"full\"}]", "RobotSays": "", "CallerSource": 1}```text**Template Usage in Job Context:**
```textProcess data from: {{dataSource}}Processing type: {{processingType}}User command: {{userSays}}```text## Common Template Variables
Here are some common use cases for template variables:
### Basic User Input
**API Request:**
```json{ "Action": "Execute", "UserSays": "[{\"userSays\":\"How can I improve my sales?\"}]"}```text**Template in Node:**
```text{{userSays}}```text### User Context
Provide information about the user to personalize the interaction.
**API Request:**
```json{ "Action": "Execute", "UserSays": "[{ \"userSays\":\"What's my account status?\", \"userId\":\"12345\", \"userName\":\"Alice\", \"userEmail\":\"alice@example.com\" }]"}```text**Template in Node:**
```textHello {{userName}}, let me check the account status for user ID {{userId}}.
User query: {{userSays}}```text### Conversation Context
Maintain context across multiple turns in a conversation.
**API Request:**
```json{ "Action": "Execute", "UserSays": "[{ \"userSays\":\"Can you help me with that?\", \"conversationId\":\"conv-123\", \"previousContext\":\"User was asking about pricing\" }]"}```text**Template in Node:**
```textBased on our previous conversation ({{previousContext}}), here's how I can help: {{userSays}}
Conversation ID: {{conversationId}}```text### System and Metadata Variables
Pass system information and metadata to your cognitive diagrams:
**API Request:**
```json{ "Action": "Execute", "UserSays": "[{ \"userSays\":\"Generate a report\", \"requestId\":\"req-456\", \"timestamp\":\"2024-01-15T10:30:00Z\", \"requestSource\":\"mobile-app\", \"apiVersion\":\"v1.2\" }]"}```text**Template in Node:**
```textProcessing request: {{requestId}}Initiated at: {{timestamp}}Source: {{requestSource}}API Version: {{apiVersion}}
User request: {{userSays}}```text## 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.
```javascript 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:**
```json{ "Action": "Execute", "UserSays": "[{ \"userSays\":\"I want to return this item\", \"orderId\":\"ORD-789\", \"customerTier\":\"Premium\", \"purchaseDate\":\"2024-01-15\", \"itemName\":\"Wireless Headphones\" }]"}```text**Template in Node (Azure OpenAI):**
```textYou 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.```text### Multi-language Support
**API Request:**
```json{ "Action": "Execute", "UserSays": "[{ \"userSays\":\"¿Cómo puedo cambiar mi contraseña?\", \"language\":\"es\", \"userLocale\":\"es-MX\" }]"}```text**Template in Node:**
```textRespond in {{language}} (locale: {{userLocale}}) to this user question: {{userSays}}```text### Dynamic Prompting
**API Request:**
```json{ "Action": "Execute", "UserSays": "[{ \"userSays\":\"Explain quantum computing\", \"audienceLevel\":\"beginner\", \"responseStyle\":\"friendly\", \"maxWords\":200 }]"}```text**Template in Node:**
```textExplain this topic to a {{audienceLevel}} audience using a {{responseStyle}} tone.Keep your response under {{maxWords}} words.
Topic: {{userSays}}```text### Training Data Processing
For agents that process training data, you can pass configuration through template variables:
**API Request:**
```json{ "Action": "Execute", "UserSays": "[{ \"userSays\":\"go\", \"sourceUrl\":\"https://docs.yourcompany.com\", \"maxPages\":100, \"includeImages\":false, \"processingSeed\":\"training-2024-01\" }]", "RobotSays": "", "CallerSource": 1}```text**Template in Training Node:**
```textSource: {{sourceUrl}}Max pages to process: {{maxPages}}Include images: {{includeImages}}Processing identifier: {{processingSeed}}Command: {{userSays}}```text## Complex Data Structures
### Nested Objects
You can pass complex data structures through template variables:
**API Request:**
```json{ "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\\\"}\" }]"}```text**Template Usage:**
```textUser Profile: {{userProfile}}Order Details: {{orderData}}Query: {{userSays}}```text**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:**
```json{ "Action": "Execute", "UserSays": "[{ \"userSays\":\"Analyze these items\", \"itemList\":\"[\\\"item1\\\",\\\"item2\\\",\\\"item3\\\"]\", \"itemCount\":3 }]"}```text**Template Usage:**
```textProcessing {{itemCount}} items: {{itemList}}User request: {{userSays}}```text## Best Practices
### Naming Conventions
* **Use clear and descriptive variable names** (e.g., `userName` instead of `n`)* **Follow camelCase convention** for consistency: `firstName`, `orderId`, `customerTier`* **Use meaningful prefixes** for related data: `user_id`, `user_name`, `user_email`
### Data Validation and Sanitization
**Before sending your API request, validate and sanitize data:**
```javascriptfunction 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});```text### Default Values and Error Handling
**Handle missing variables gracefully in your cognitive diagram:**
```textHello {{userName || "valued customer"}}!Processing request: {{userSays}}Order ID: {{orderId || "Not provided"}}```text**Or use conditional logic in your templates:**
```text{{#if userName}}Hello {{userName}}!{{else}}Hello there!{{/if}}
Your request: {{userSays}}```text### 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
```javascript// 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};```text## Integration Patterns
### Building Dynamic Templates
**Create reusable template builders:**
```javascriptclass 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();```text### Template Variable Mapping
**Map your application data to template variables consistently:**
```javascriptconst 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)) };}```text## Troubleshooting
### 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 `UserSays` string is valid * The data type is compatible (strings, numbers, booleans work best)
### Debugging Template Variables
**Add debugging information to your requests:**
```json{ "Action": "Execute", "UserSays": "[{ \"userSays\":\"Debug request\", \"debugInfo\":\"Template test\", \"timestamp\":\"2024-01-15T10:30:00Z\", \"requestId\":\"req-debug-001\" }]"}```text**In your cognitive diagram, create a debug node:**
```textDEBUG INFO:- Request ID: {{requestId}}- Timestamp: {{timestamp}}- Debug Info: {{debugInfo}}- User Says: {{userSays}}- All variables received successfully!```text### JSON Structure Validation
**Validate your JSON structure before sending:**
```javascriptfunction 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;}```text## Security Considerations
### Data Sanitization
**Always sanitize user input before using in template variables:**
```javascriptfunction 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();}```text### Sensitive Data Handling
**Avoid passing sensitive information through template variables:**
```javascript// ❌ 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};```textBy 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.