Template Variables
Template variables guide for the Builder API — use {{placeholder}} syntax to pass dynamic request data into cognitive diagram nodes for personalized, context-aware AI agent responses.
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 Execution
For both synchronous and asynchronous cognitive diagram execution, template variables work the same way:
```json{ "Action": "Execute", "UserSays": "[{\"userSays\":\"Your message here\", \"customField\":\"value\"}]"}```textFor long-running jobs:
```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`
### 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### 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## 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:**
```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 guidelines, you'll be able to effectively use template variables to create dynamic, personalized AI agents while maintaining security and performance best practices.