function api_templates
Flask API endpoint that retrieves and returns a list of available instruction templates from the chat engine.
/tf/active/vicechatdev/vice_ai/complex_app.py
2378 - 2385
simple
Purpose
This endpoint provides a REST API interface to query available instruction templates stored in the chat_engine object. It's designed to allow clients to discover what template options are available for configuring chat interactions. The function safely handles cases where the chat_engine might not be initialized or lacks the instruction_templates attribute, returning an empty list in such cases.
Source Code
def api_templates():
"""Get available instruction templates"""
try:
templates = list(getattr(chat_engine, 'instruction_templates', {}).keys()) if chat_engine else []
return jsonify({'templates': templates})
except Exception as e:
logger.error(f"Templates API error: {e}")
return jsonify({'error': 'Failed to retrieve templates'}), 500
Return Value
Returns a Flask JSON response object. On success (HTTP 200), returns a dictionary with key 'templates' containing a list of template names (strings). On error (HTTP 500), returns a dictionary with key 'error' containing an error message string.
Dependencies
flasklogging
Required Imports
from flask import jsonify
import logging
Usage Example
# Client-side usage example (JavaScript fetch)
fetch('/api/templates', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer <token>' // If required by require_auth
}
})
.then(response => response.json())
.then(data => {
console.log('Available templates:', data.templates);
// Example output: ['default', 'technical', 'creative', 'concise']
})
.catch(error => console.error('Error:', error));
# Python requests example
import requests
response = requests.get('http://localhost:5000/api/templates')
if response.status_code == 200:
templates = response.json()['templates']
print(f'Available templates: {templates}')
else:
print(f'Error: {response.json()["error"]}')
Best Practices
- This endpoint requires authentication via the require_auth decorator - ensure proper authentication tokens are provided
- The function gracefully handles missing chat_engine or instruction_templates attributes by returning an empty list
- Error responses include descriptive messages and appropriate HTTP status codes (500 for server errors)
- The function uses getattr with a default value to safely access potentially missing attributes
- Logging is implemented for debugging and monitoring purposes when errors occur
- The endpoint is read-only (GET) and does not modify any state
- Consider caching the template list if it doesn't change frequently to improve performance
- Ensure the chat_engine is properly initialized before this endpoint is called in production
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function api_templates_v2 95.8% similar
-
function api_load_template_v2 86.3% similar
-
function api_load_template 84.6% similar
-
function api_templates_v1 81.2% similar
-
function api_save_template 77.6% similar