🔍 Code Extractor

function api_save_template

Maturity: 50

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

File:
/tf/active/vicechatdev/vice_ai/app.py
Lines:
1268 - 1286
Complexity:
simple

Purpose

This endpoint provides a REST API interface for persisting user-defined instruction templates. It validates that both a template name and instructions are provided, then uses the chat engine's save_instruction_template method to store the template. It's designed to be used in a web application where users can create and save custom instruction templates for later reuse in chat interactions.

Source Code

def api_save_template():
    """Save a new instruction template"""
    try:
        data = request.get_json()
        name = data.get('name', '').strip()
        instructions = data.get('instructions', '').strip()
        
        if not name or not instructions:
            return jsonify({'error': 'Template name and instructions are required'}), 400
        
        if chat_engine and hasattr(chat_engine, 'save_instruction_template'):
            chat_engine.save_instruction_template(name, instructions)
            return jsonify({'message': 'Template saved successfully'})
        else:
            return jsonify({'error': 'Template saving not available'}), 500
            
    except Exception as e:
        logger.error(f"Save template API error: {e}")
        return jsonify({'error': 'Failed to save template'}), 500

Return Value

Returns a Flask JSON response tuple. On success: (jsonify({'message': 'Template saved successfully'}), 200). On validation error: (jsonify({'error': 'Template name and instructions are required'}), 400). On unavailable feature: (jsonify({'error': 'Template saving not available'}), 500). On exception: (jsonify({'error': 'Failed to save template'}), 500).

Dependencies

  • flask
  • logging

Required Imports

from flask import Flask
from flask import request
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 which must have save_instruction_template method

Required (conditional)

Usage Example

# Server-side setup
from flask import Flask, request, jsonify
import logging

app = Flask(__name__)
logger = logging.getLogger(__name__)

# Initialize chat_engine with save_instruction_template capability
from hybrid_rag_engine import OneCo_hybrid_RAG
chat_engine = OneCo_hybrid_RAG()

@app.route('/api/save-template', methods=['POST'])
@require_auth
def api_save_template():
    # Function implementation here
    pass

# Client-side usage example (JavaScript/fetch)
# fetch('/api/save-template', {
#     method: 'POST',
#     headers: {'Content-Type': 'application/json'},
#     body: JSON.stringify({
#         name: 'My Template',
#         instructions: 'You are a helpful assistant...'
#     })
# }).then(response => response.json())
#   .then(data => console.log(data.message));

Best Practices

  • Always validate that both 'name' and 'instructions' fields are present and non-empty before processing
  • Ensure the chat_engine object is properly initialized before the endpoint is called
  • Use proper authentication middleware (@require_auth) to protect this endpoint
  • Handle exceptions gracefully and log errors for debugging
  • Return appropriate HTTP status codes (400 for validation errors, 500 for server errors)
  • Strip whitespace from input fields to prevent accidental empty submissions
  • Check for the existence of the save_instruction_template method using hasattr before calling it
  • Consider implementing rate limiting to prevent abuse of template creation
  • Validate template name for uniqueness if duplicate names should be prevented
  • Consider adding maximum length constraints for name and instructions fields

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_save_template_v1 98.2% similar

    Flask API endpoint that saves a new instruction template by accepting a POST request with template name and instructions, then persisting it via the chat_engine.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function api_save_template_v2 85.7% 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_v2 81.5% 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 81.1% 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 80.9% 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
← Back to Browse