function api_templates_v2
Flask API endpoint that retrieves and returns a list of available instruction templates from the chat engine.
/tf/active/vicechatdev/vice_ai/app.py
1257 - 1264
simple
Purpose
This endpoint provides a REST API interface to query available instruction templates that can be used with the chat engine. It's designed to allow clients to discover what template options are available for formatting chat instructions. The endpoint is protected by authentication and handles errors gracefully by returning appropriate HTTP status codes.
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 get templates'}), 500
Return Value
Returns a Flask JSON response object. On success (HTTP 200), returns {'templates': [list of template names as strings]}. On failure (HTTP 500), returns {'error': 'Failed to get templates'}. The templates list is extracted from the chat_engine's instruction_templates attribute, or an empty list if chat_engine is not available.
Dependencies
flasklogging
Required Imports
from flask import Flask
from flask import jsonify
import logging
Usage Example
# Assuming Flask app setup with authentication
from flask import Flask, jsonify
import logging
app = Flask(__name__)
logger = logging.getLogger(__name__)
# Mock chat engine with templates
class MockChatEngine:
instruction_templates = {
'default': 'Default template',
'technical': 'Technical template',
'casual': 'Casual template'
}
chat_engine = MockChatEngine()
# Mock auth decorator
def require_auth(f):
return f
@app.route('/api/templates')
@require_auth
def api_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 get templates'}), 500
# Client usage:
# GET /api/templates
# Response: {"templates": ["default", "technical", "casual"]}
Best Practices
- Always ensure chat_engine is properly initialized before the Flask app starts accepting requests
- The function uses getattr with a default empty dict to safely handle cases where instruction_templates attribute doesn't exist
- Error logging is implemented to help with debugging when template retrieval fails
- The require_auth decorator should be properly implemented to prevent unauthorized access
- Consider adding rate limiting to prevent API abuse
- The endpoint returns an empty list rather than an error when chat_engine is None, which may mask configuration issues
- HTTP 500 errors are returned for all exceptions - consider more granular error handling for production use
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function api_templates 95.8% similar
-
function api_load_template_v2 87.5% similar
-
function api_load_template 86.0% similar
-
function api_templates_v1 81.9% similar
-
function api_save_template 81.1% similar