function api_save_template_v1
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.
/tf/active/vicechatdev/vice_ai/complex_app.py
2389 - 2407
simple
Purpose
This endpoint provides a REST API interface for creating and storing instruction templates. It validates incoming JSON data, checks for required fields (name and instructions), and delegates the actual saving operation to the chat_engine's save_instruction_template method. It's designed to be used in a web application where users can create reusable instruction templates for chat interactions.
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 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 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: (jsonify({'message': 'Template saved successfully'}), 200). On validation error: (jsonify({'error': 'Template name and instructions are required'}), 400). On unsupported operation: (jsonify({'error': 'Template saving not supported'}), 400). On exception: (jsonify({'error': 'Failed to save template'}), 500).
Dependencies
flasklogginghybrid_rag_engine
Required Imports
from flask import Flask
from flask import request
from flask import jsonify
import logging
from hybrid_rag_engine import OneCo_hybrid_RAG
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: 'customer_support_template',
instructions: 'You are a helpful customer support agent. Be polite and professional.'
})
})
.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': 'code_review_template',
'instructions': 'Review code for best practices and security issues.'
},
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 chat_engine is properly initialized before this endpoint is called
- 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 to avoid overwriting existing templates (validation depends on chat_engine implementation)
- Consider implementing rate limiting to prevent abuse of template creation
- The function relies on global 'chat_engine' and 'logger' objects - ensure these are properly initialized in the application context
- Error messages are logged server-side but generic messages are returned to clients for security
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function api_save_template 98.2% similar
-
function api_save_template_v2 85.5% similar
-
function api_load_template_v2 81.5% similar
-
function api_templates_v2 80.6% similar
-
function api_load_template 80.4% similar