function api_load_template
Flask API endpoint that loads and returns instruction template content by template name, with authentication required.
/tf/active/vicechatdev/vice_ai/app.py
1290 - 1310
moderate
Purpose
This endpoint serves as a REST API to retrieve instruction templates from the chat engine. It's designed to be called by frontend applications to dynamically load template instructions for chat interactions. The function includes comprehensive logging for debugging and error tracking, and handles cases where the chat engine is unavailable or templates don't exist.
Source Code
def api_load_template(template_name):
"""Load an instruction template"""
logger.info(f"🔍 Template load request received for: '{template_name}'")
try:
if chat_engine and hasattr(chat_engine, 'get_instruction_template'):
logger.info(f"Chat engine available, attempting to get template: '{template_name}'")
template_instructions = chat_engine.get_instruction_template(template_name)
logger.info(f"Template instructions found: {len(template_instructions) if template_instructions else 0} characters")
if template_instructions:
logger.info(f"✅ Returning template '{template_name}' successfully")
return jsonify({'instructions': template_instructions})
else:
logger.warning(f"⚠️ Template '{template_name}' not found")
return jsonify({'error': 'Template not found'}), 404
else:
logger.error("❌ Chat engine not available or missing get_instruction_template method")
return jsonify({'error': 'Template loading not available'}), 500
except Exception as e:
logger.error(f"Load template API error: {e}")
return jsonify({'error': 'Failed to load template'}), 500
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
template_name |
- | - | positional_or_keyword |
Parameter Details
template_name: String identifier for the instruction template to load. This is extracted from the URL path parameter. The template name should correspond to a valid template stored in the chat engine's template system. No validation is performed on the format, so it accepts any string value passed in the URL.
Return Value
Returns a Flask JSON response object. On success (200): {'instructions': <string>} containing the template content. On template not found (404): {'error': 'Template not found'}. On chat engine unavailable (500): {'error': 'Template loading not available'}. On general exception (500): {'error': 'Failed to load template'}. All responses are JSON-formatted using Flask's jsonify() function.
Dependencies
flasklogginghybrid_rag_engine
Required Imports
from flask import Flask
from flask import jsonify
import logging
Conditional/Optional Imports
These imports are only needed under specific conditions:
from hybrid_rag_engine import OneCo_hybrid_RAG
Condition: Required for the chat_engine object that must be instantiated before this endpoint can function properly
Required (conditional)from auth.azure_auth import AzureSSO
Condition: Required for the require_auth decorator that protects this endpoint
Required (conditional)Usage Example
# Server-side setup
from flask import Flask, jsonify
import logging
from hybrid_rag_engine import OneCo_hybrid_RAG
from auth.azure_auth import AzureSSO
app = Flask(__name__)
logger = logging.getLogger(__name__)
chat_engine = OneCo_hybrid_RAG() # Initialize with appropriate config
# Assuming require_auth decorator is defined
@app.route('/api/load-template/<template_name>')
@require_auth
def api_load_template(template_name):
# ... function code ...
pass
# Client-side usage (JavaScript/fetch example)
# fetch('/api/load-template/customer_support', {
# method: 'GET',
# headers: {'Authorization': 'Bearer <token>'}
# })
# .then(response => response.json())
# .then(data => console.log(data.instructions))
# .catch(error => console.error('Error:', error));
Best Practices
- Ensure the chat_engine global variable is properly initialized before the Flask app starts accepting requests
- The chat_engine must implement the get_instruction_template() method that returns template content as a string or None
- Authentication is required via the require_auth decorator - ensure users are authenticated before accessing this endpoint
- Template names should be validated or sanitized if they're used to access file systems or databases to prevent injection attacks
- Monitor logs for template access patterns and errors using the comprehensive logging statements
- Consider implementing caching for frequently accessed templates to reduce load on the chat engine
- The function assumes chat_engine is a global variable - consider dependency injection for better testability
- Handle the 404 response appropriately in client code to provide user-friendly error messages
- Ensure proper error handling in the chat_engine.get_instruction_template() method to prevent unhandled exceptions
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function api_load_template_v2 97.1% similar
-
function api_templates_v2 86.0% similar
-
function api_templates 84.6% similar
-
function api_load_template_v1 81.7% similar
-
function api_save_template 80.9% similar