🔍 Code Extractor

function api_templates_v1

Maturity: 41

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

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
2280 - 2287
Complexity:
simple

Purpose

This endpoint provides a REST API interface to query available instruction templates stored in the RAG (Retrieval-Augmented Generation) engine. It's used by client applications to discover what template options are available for generating or processing instructions. The endpoint handles cases where the RAG engine is unavailable or not initialized, returning an empty list gracefully.

Source Code

def api_templates():
    """Get available instruction templates"""
    try:
        templates = list(getattr(rag_engine, 'instruction_templates', {}).keys()) if RAG_AVAILABLE and rag_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 JSON response with a 'templates' key containing a list of template names (strings). On success, returns status 200 with {'templates': [list of template names]}. On error, returns status 500 with {'error': 'Failed to retrieve templates'}. If RAG is unavailable or rag_engine is None, returns an empty list with status 200.

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 the rag_engine global variable to be available. Must be imported in the module scope.

Required (conditional)

Usage Example

# Client-side usage example
import requests

# Assuming the Flask app is running on localhost:5000
# and authentication is handled (e.g., via session cookies)
response = requests.get('http://localhost:5000/api/templates')

if response.status_code == 200:
    data = response.json()
    templates = data.get('templates', [])
    print(f"Available templates: {templates}")
    # Example output: ['template1', 'template2', 'template3']
else:
    error = response.json().get('error')
    print(f"Error: {error}")

# Server-side setup example
from flask import Flask, jsonify
from hybrid_rag_engine import OneCo_hybrid_RAG
import logging

app = Flask(__name__)
logger = logging.getLogger(__name__)
RAG_AVAILABLE = True
rag_engine = OneCo_hybrid_RAG()
rag_engine.instruction_templates = {'template1': {}, 'template2': {}}

@app.route('/api/templates')
@require_auth
def api_templates():
    try:
        templates = list(getattr(rag_engine, 'instruction_templates', {}).keys()) if RAG_AVAILABLE and rag_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

Best Practices

  • Always check RAG_AVAILABLE flag before accessing rag_engine to prevent errors when RAG is not initialized
  • Use getattr with a default value ({}) to safely access instruction_templates attribute
  • Implement proper error logging for debugging template retrieval issues
  • Return empty list instead of error when RAG is unavailable to maintain API consistency
  • Ensure the require_auth decorator is applied to protect this endpoint from unauthorized access
  • The endpoint returns 500 status code only for unexpected exceptions, not for missing RAG engine
  • Client applications should handle both successful empty lists and error responses appropriately
  • Consider caching template lists if they don't change frequently to improve performance

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_load_template_v1 90.2% similar

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

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_save_template_v2 82.6% 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_templates_v2 81.9% 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
  • function api_templates 81.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/complex_app.py
  • function api_load_template_v2 73.1% 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
← Back to Browse