🔍 Code Extractor

function api_save_template_v2

Maturity: 46

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.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
2291 - 2309
Complexity:
simple

Purpose

This endpoint provides a REST API interface for creating and storing instruction templates that can be reused in RAG (Retrieval-Augmented Generation) operations. It validates input data, checks for RAG engine availability, and delegates the actual storage to the rag_engine's save_instruction_template method. This is typically used in document processing or AI-assisted writing applications where users need to save custom instruction sets for later reuse.

Source Code

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

Return Value

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

Dependencies

  • flask
  • logging
  • hybrid_rag_engine

Required Imports

from flask import Flask, request, 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 functionality; the function checks RAG_AVAILABLE flag and rag_engine instance availability at runtime

Required (conditional)

Usage Example

# Client-side usage example (JavaScript fetch)
fetch('/api/templates', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_AUTH_TOKEN'
  },
  body: JSON.stringify({
    name: 'research_summary',
    instructions: 'Summarize the research findings in 3 paragraphs focusing on methodology, results, and conclusions.'
  })
})
.then(response => response.json())
.then(data => console.log(data.message))
.catch(error => console.error('Error:', error));

# Python requests example
import requests

response = requests.post(
  'http://localhost:5000/api/templates',
  json={
    'name': 'research_summary',
    'instructions': 'Summarize the research findings in 3 paragraphs.'
  },
  headers={'Authorization': 'Bearer YOUR_AUTH_TOKEN'}
)
print(response.json())

Best Practices

  • Always include both 'name' and 'instructions' fields in the request body to avoid 400 errors
  • Ensure the RAG engine is properly initialized before calling this endpoint
  • Handle all possible HTTP status codes (200, 400, 500) in client code
  • The endpoint requires authentication via the require_auth decorator - ensure valid credentials are provided
  • Template names should be unique and descriptive to avoid confusion when retrieving templates later
  • Consider implementing additional validation for template name format (e.g., no special characters, length limits)
  • The function logs errors but returns generic error messages to clients - check server logs for detailed error information
  • Ensure the rag_engine instance has the save_instruction_template method implemented before deployment

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_save_template 85.7% 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
  • function api_save_template_v1 85.5% 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_load_template_v1 85.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_templates_v1 82.6% 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_load_template_v2 69.6% 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