Using Prompt Templates
Apply templates with variables to generate prompts for AI responses.
Using a Template
Using cURL
curl -X POST http://localhost/api/v1/prompt-templates/customer_support/use \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"variables": {
"company": "Acme Corp",
"tone": "professional and helpful",
"issue_type": "technical",
"user_issue": "Cannot connect to API"
}
}'
Using Python
import requests
response = requests.post(
"http://localhost/api/v1/prompt-templates/customer_support/use",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"variables": {
"company": "Acme Corp",
"tone": "professional and helpful",
"issue_type": "technical",
"user_issue": "Cannot connect to API"
}
}
)
result = response.json()
print(f"Generated Prompt:\n{result['prompt']}")
Using JavaScript
const response = await fetch(
'http://localhost/api/v1/prompt-templates/customer_support/use',
{
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
variables: {
company: 'Acme Corp',
tone: 'professional and helpful',
issue_type: 'technical',
user_issue: 'Cannot connect to API'
}
})
}
);
const result = await response.json();
console.log('Generated Prompt:', result.prompt);
Using in Chatbots
import requests
# Create chatbot with template
response = requests.post(
"http://localhost/api/v1/chatbot/create",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"name": "support_bot",
"model": "gpt-4",
"template_name": "customer_support",
"template_variables": {
"company": "Acme Corp",
"tone": "professional"
}
}
)
chatbot_id = response.json()["id"]
# Chat with template applied
chat_response = requests.post(
"http://localhost/api/v1/chatbot/chat",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"chatbot_id": chatbot_id,
"message": "I can't log in to my account"
}
)
print(f"Response: {chat_response.json()['response']}")
Using in Agents
import requests
# Create agent with template
response = requests.post(
"http://localhost/api/v1/agent/configs",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"name": "research_agent",
"model": "gpt-4",
"template_name": "research_assistant",
"template_variables": {
"focus_areas": ["technical", "business"],
"output_format": "detailed"
},
"builtin_tools": ["web_search", "rag_search"]
}
)
agent_id = response.json()["id"]
# Chat with template applied
chat_response = requests.post(
"http://localhost/api/v1/agent/chat",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"agent_id": agent_id,
"message": "What are the latest trends in AI?"
}
)
print(f"Response: {chat_response.json()['response']}")
Variable Substitution Examples
Basic Substitution
# Template: "Hello {{name}}, welcome to {{service}}!"
result = requests.post(
"http://localhost/api/v1/prompt-templates/greeting/use",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"variables": {
"name": "Alice",
"service": "Enclava"
}
}
)
# Output: "Hello Alice, welcome to Enclava!"
Default Values
# Template: "Response length: {{max_length | default: '300 words'}}"
result = requests.post(
"http://localhost/api/v1/prompt-templates/configure/use",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"variables": {}
# Uses default value since max_length not provided
}
)
# Output: "Response length: 300 words"
Conditional Variables
# Template with conditional:
# {\{#if show_details}}
# Details: {{details}}
# {{/if}}
result = requests.post(
"http://localhost/api/v1/prompt-templates/response/use",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"variables": {
"show_details": True,
"details": "Full transaction details here"
}
}
)
# Output includes details section
List Iteration
# Template:
# Items:
# {\{#each items}}
# - {{this}}
# {{/each}}
result = requests.post(
"http://localhost/api/v1/prompt-templates/list/use",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"variables": {
"items": ["Apple", "Banana", "Orange"]
}
}
)
# Output:
# Items:
# - Apple
# - Banana
# - Orange
Advanced Usage
Dynamic Variables
def get_dynamic_variables(user_context):
return {
"user_name": user_context.get("name", "Guest"),
"user_role": user_context.get("role", "user"),
"preferences": user_context.get("preferences", {}),
"session_data": user_context.get("session", {})
}
# Use dynamic variables
variables = get_dynamic_variables({
"name": "John",
"role": "admin",
"preferences": {"language": "en", "theme": "dark"}
})
response = requests.post(
"http://localhost/api/v1/prompt-templates/personalized/use",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={"variables": variables}
)
Template Composition
# Use one template's output in another
# First, generate base prompt
base_response = requests.post(
"http://localhost/api/v1/prompt-templates/base/use",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={"variables": {"topic": "AI trends"}}
)
base_prompt = base_response.json()["prompt"]
# Then use as input to another template
final_response = requests.post(
"http://localhost/api/v1/prompt-templates/refined/use",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={
"variables": {
"base_prompt": base_prompt,
"refinement": "make it more technical"
}
}
)
print(final_response.json()["prompt"])
Error Handling
def use_template_safely(template_name, variables, max_retries=3):
for attempt in range(max_retries):
try:
response = requests.post(
f"http://localhost/api/v1/prompt-templates/{template_name}/use",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={"variables": variables},
timeout=10
)
if response.status_code == 200:
return response.json()
elif response.status_code == 404:
raise ValueError(f"Template '{template_name}' not found")
elif response.status_code == 400:
error = response.json()
raise ValueError(f"Invalid variables: {error.get('error', 'Unknown error')}")
except requests.exceptions.RequestException as e:
if attempt == max_retries - 1:
raise
time.sleep(1)
raise Exception("Failed to use template after retries")
# Use template with error handling
try:
result = use_template_safely(
"customer_support",
{
"company": "Acme",
"issue_type": "login"
}
)
print(f"Prompt: {result['prompt']}")
except Exception as e:
print(f"Error: {e}")
React Integration
import React, { useState } from 'react';
function TemplateForm() {
const [company, setCompany] = useState('');
const [tone, setTone] = useState('professional');
const [issueType, setIssueType] = useState('');
const [generatedPrompt, setGeneratedPrompt] = useState('');
const [loading, setLoading] = useState(false);
const applyTemplate = async () => {
setLoading(true);
try {
const response = await fetch(
'http://localhost/api/v1/prompt-templates/customer_support/use',
{
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
variables: {
company,
tone,
issue_type: issueType,
user_issue: 'Sample issue'
}
})
}
);
const result = await response.json();
setGeneratedPrompt(result.prompt);
} catch (error) {
console.error('Error:', error);
} finally {
setLoading(false);
}
};
return (
<div className="p-6">
<h2 className="text-2xl font-bold mb-4">Apply Template</h2>
<div className="space-y-4 mb-4">
<div>
<label className="block mb-1">Company:</label>
<input
type="text"
value={company}
onChange={(e) => setCompany(e.target.value)}
className="w-full px-4 py-2 border rounded"
/>
</div>
<div>
<label className="block mb-1">Tone:</label>
<select
value={tone}
onChange={(e) => setTone(e.target.value)}
className="w-full px-4 py-2 border rounded"
>
<option value="professional">Professional</option>
<option value="friendly">Friendly</option>
<option value="technical">Technical</option>
</select>
</div>
<div>
<label className="block mb-1">Issue Type:</label>
<input
type="text"
value={issueType}
onChange={(e) => setIssueType(e.target.value)}
className="w-full px-4 py-2 border rounded"
/>
</div>
</div>
<button
onClick={applyTemplate}
disabled={loading || !company || !issueType}
className="px-6 py-2 bg-blue-500 text-white rounded"
>
{loading ? 'Generating...' : 'Generate Prompt'}
</button>
{generatedPrompt && (
<div className="mt-6 p-4 border rounded">
<h3 className="font-bold mb-2">Generated Prompt:</h3>
<pre className="whitespace-pre-wrap text-sm">{generatedPrompt}</pre>
</div>
)}
</div>
);
}
export default TemplateForm;
Best Practices
- Validate variables - Check required variables before calling
- Use defaults - Provide sensible default values
- Handle errors - Catch and display template errors
- Cache templates - Store frequently used templates locally
- Test thoroughly - Verify output with sample inputs
- Document variables - Keep list of expected variables
Troubleshooting
Template Not Found
Problem: {"error": "Template not found"}
Solution:
- Verify template name is correct
- Check template exists using list endpoint
- Confirm template spelling
Missing Required Variable
Problem: {"error": "Missing required variable: xxx"}
Solution:
- Provide all required variables
- Check variable names match template
- Review template definition
Invalid Variable Type
Problem: Variable type doesn't match definition
Solution:
- Ensure variable type matches (string, number, boolean, array)
- Convert types if necessary
- Review variable definitions
Next Steps
- Creating Templates - Define new templates
- Chatbot Documentation - Integrate with chatbots
- Agent Documentation - Integrate with agents