🔍 Code Extractor

function api_load_template_v1

Maturity: 48

Flask API endpoint that loads and returns instruction templates from a RAG (Retrieval-Augmented Generation) engine based on the provided template name.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
2314 - 2334
Complexity:
moderate

Purpose

This endpoint serves as a REST API interface to retrieve pre-defined instruction templates stored in the RAG engine. It's used to load reusable instruction sets for AI interactions, allowing users to quickly apply standardized prompts or configurations. The function handles authentication, validates RAG engine availability, retrieves the template, and returns it as JSON with appropriate error handling and logging.

Source Code

def api_load_template(template_name):
    """Load an instruction template"""
    logger.info(f"🔍 Template load request received for: '{template_name}'")
    try:
        if RAG_AVAILABLE and rag_engine and hasattr(rag_engine, 'get_instruction_template'):
            logger.info(f"RAG engine available, attempting to get template: '{template_name}'")
            template_instructions = rag_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("❌ RAG 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 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 name is used to query the RAG engine's template storage. Expected to be a valid template identifier that exists in the system. Passed as a URL path parameter from the route.

Return Value

Returns a Flask JSON response object. On success (200): {'instructions': <template_content_string>} containing the template instructions. On template not found (404): {'error': 'Template not found'}. On RAG unavailability (500): {'error': 'Template loading not available'}. On general failure (500): {'error': 'Failed to load template'}. All responses include appropriate HTTP status codes.

Dependencies

  • flask
  • logging

Required Imports

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 RAG engine functionality. The function checks RAG_AVAILABLE flag and rag_engine instance availability at runtime.

Required (conditional)

Usage Example

# Assuming Flask app setup with RAG engine initialized
# Client-side usage (JavaScript fetch example):
fetch('/api/load-template/standard_analysis', {
  method: 'GET',
  headers: {
    'Authorization': 'Bearer <auth_token>'
  }
})
.then(response => response.json())
.then(data => {
  if (data.instructions) {
    console.log('Template loaded:', data.instructions);
  } else {
    console.error('Error:', data.error);
  }
});

# Python requests example:
import requests
response = requests.get(
  'http://localhost:5000/api/templates/standard_analysis',
  headers={'Authorization': 'Bearer <token>'}
)
if response.status_code == 200:
  instructions = response.json()['instructions']
  print(f'Loaded template: {instructions}')
else:
  print(f'Error: {response.json()["error"]}')

Best Practices

  • Always ensure RAG engine is properly initialized before calling this endpoint
  • The endpoint requires authentication via the require_auth decorator - ensure valid credentials are provided
  • Template names should be validated on the client side before making requests to avoid unnecessary 404 errors
  • Monitor logs with the emoji prefixes (🔍, ✅, ⚠️, ❌) for debugging template loading issues
  • Handle all three possible error responses (404, 500) appropriately in client code
  • The function checks both RAG_AVAILABLE flag and hasattr for get_instruction_template method - ensure RAG engine implements this method
  • Consider caching frequently used templates on the client side to reduce server load
  • Template names in URLs should be URL-encoded if they contain special characters
  • The endpoint is accessible via two routes for flexibility - use the more semantic /api/templates/<name> route when possible

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_templates_v1 90.2% similar

    Flask API endpoint that retrieves and returns a list of available instruction templates from the RAG engine.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_save_template_v2 85.2% similar

    Flask API endpoint that saves a new instruction template by accepting JSON data with a template name and instructions, then persisting it via the RAG engine.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_load_template 81.7% similar

    Flask API endpoint that loads and returns instruction template content by template name, with authentication required.

    From: /tf/active/vicechatdev/vice_ai/app.py
  • function api_load_template_v2 80.7% similar

    Flask API endpoint that retrieves and returns an instruction template by name from the chat engine.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function api_templates_v2 72.2% similar

    Flask API endpoint that retrieves and returns a list of available instruction templates from the chat engine.

    From: /tf/active/vicechatdev/vice_ai/app.py
← Back to Browse