🔍 Code Extractor

function api_templates

Maturity: 41

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

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
2378 - 2385
Complexity:
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

  • flask
  • logging

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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_templates_v2 95.8% 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_load_template_v2 86.3% 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_load_template 84.6% 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_templates_v1 81.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 77.6% similar

    Flask API endpoint that saves a new instruction template by validating input data and delegating to the chat engine's template storage mechanism.

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