🔍 Code Extractor

function save_custom_instructions

Maturity: 50

Flask API endpoint that saves custom instructions to a markdown file in a designated instructions directory with filename sanitization.

File:
/tf/active/vicechatdev/docchat/app.py
Lines:
1684 - 1712
Complexity:
moderate

Purpose

This function serves as a REST API endpoint to persist user-provided custom instructions to the filesystem. It validates input data, creates necessary directories, sanitizes filenames to prevent security issues, and writes the content to a markdown file. It's designed for applications that need to store and manage custom instruction sets or templates.

Source Code

def save_custom_instructions():
    """Save custom instructions to a file"""
    try:
        data = request.json
        name = data.get('name', '').strip()
        content = data.get('content', '').strip()
        
        if not name or not content:
            return jsonify({'error': 'Name and content required'}), 400
        
        # Create instructions directory if it doesn't exist
        instructions_dir = os.path.join(os.path.dirname(__file__), 'instructions')
        os.makedirs(instructions_dir, exist_ok=True)
        
        # Sanitize filename
        safe_name = "".join(c for c in name if c.isalnum() or c in (' ', '-', '_')).strip()
        safe_name = safe_name.replace(' ', '_')
        filepath = os.path.join(instructions_dir, f"{safe_name}.md")
        
        # Save to file
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(content)
        
        logger.info(f"Saved custom instructions: {safe_name}")
        return jsonify({'success': True, 'filename': f"{safe_name}.md"})
        
    except Exception as e:
        logger.error(f"Error saving instructions: {e}")
        return jsonify({'error': str(e)}), 500

Return Value

Returns a Flask JSON response tuple. On success: (jsonify({'success': True, 'filename': '<sanitized_name>.md'}), 200). On validation error: (jsonify({'error': 'Name and content required'}), 400). On exception: (jsonify({'error': '<error_message>'}), 500).

Dependencies

  • flask
  • logging

Required Imports

from flask import Flask
from flask import request
from flask import jsonify
import os
import logging

Usage Example

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

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

@app.route('/api/instructions/save', methods=['POST'])
def save_custom_instructions():
    # ... function code here ...
    pass

if __name__ == '__main__':
    app.run()

# Client-side usage (e.g., with requests library):
import requests

url = 'http://localhost:5000/api/instructions/save'
data = {
    'name': 'My Custom Instructions',
    'content': '# Instructions\n\nThese are my custom instructions for the AI.'
}
response = requests.post(url, json=data)
print(response.json())  # {'success': True, 'filename': 'My_Custom_Instructions.md'}

Best Practices

  • Always send POST requests with valid JSON containing both 'name' and 'content' fields
  • The function sanitizes filenames by removing special characters, keeping only alphanumeric, spaces, hyphens, and underscores
  • Spaces in names are converted to underscores in the filename
  • Files are saved with UTF-8 encoding to support international characters in content
  • The function creates the 'instructions' directory automatically if it doesn't exist
  • All saved files have a .md extension regardless of input
  • Duplicate names will overwrite existing files without warning
  • Consider implementing additional validation for content length and file size limits in production
  • The function logs successful saves and errors for debugging and audit purposes
  • Ensure proper error handling on the client side for 400 and 500 status codes

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function list_custom_instructions 80.6% similar

    Flask API endpoint that retrieves and returns a list of all custom instruction markdown files stored in the 'instructions' directory.

    From: /tf/active/vicechatdev/docchat/app.py
  • function load_custom_instructions 78.4% similar

    Flask API endpoint that loads and returns the content of custom instruction files from a designated instructions directory with security validation.

    From: /tf/active/vicechatdev/docchat/app.py
  • function api_save_template 71.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 71.1% 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 65.8% 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
← Back to Browse