🔍 Code Extractor

function list_custom_instructions

Maturity: 46

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

File:
/tf/active/vicechatdev/docchat/app.py
Lines:
1740 - 1753
Complexity:
simple

Purpose

This function serves as a REST API endpoint to list all saved custom instruction files. It scans the 'instructions' directory relative to the current file location, filters for markdown (.md) files, and returns them as a JSON response. It handles cases where the directory doesn't exist and provides error handling for exceptions.

Source Code

def list_custom_instructions():
    """List all saved custom instruction files"""
    try:
        instructions_dir = os.path.join(os.path.dirname(__file__), 'instructions')
        
        if not os.path.exists(instructions_dir):
            return jsonify({'files': []})
        
        files = [f for f in os.listdir(instructions_dir) if f.endswith('.md')]
        return jsonify({'files': files})
        
    except Exception as e:
        logger.error(f"Error listing instructions: {e}")
        return jsonify({'error': str(e)}), 500

Return Value

Returns a Flask JSON response object. On success, returns a JSON object with structure {'files': [list of .md filenames]} with HTTP status 200. If the instructions directory doesn't exist, returns {'files': []} with status 200. On error, returns {'error': error_message_string} with HTTP status 500.

Dependencies

  • flask
  • logging

Required Imports

from flask import jsonify
import os
import logging

Usage Example

# Assuming Flask app is set up and this function is registered as a route
# Client-side usage:
import requests

response = requests.get('http://localhost:5000/api/instructions/list')
if response.status_code == 200:
    data = response.json()
    files = data.get('files', [])
    print(f"Found {len(files)} instruction files: {files}")
else:
    error = response.json().get('error')
    print(f"Error: {error}")

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

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

@app.route('/api/instructions/list', methods=['GET'])
def list_custom_instructions():
    try:
        instructions_dir = os.path.join(os.path.dirname(__file__), 'instructions')
        if not os.path.exists(instructions_dir):
            return jsonify({'files': []})
        files = [f for f in os.listdir(instructions_dir) if f.endswith('.md')]
        return jsonify({'files': files})
    except Exception as e:
        logger.error(f"Error listing instructions: {e}")
        return jsonify({'error': str(e)}), 500

Best Practices

  • Ensure the logger instance is properly configured before using this function
  • The function assumes markdown files (.md) are the only custom instruction format
  • Directory path is relative to the current file location using __file__, ensure this is appropriate for your deployment
  • Consider adding authentication/authorization if this endpoint exposes sensitive instruction files
  • The function returns an empty list rather than an error when the directory doesn't exist, which may be desired behavior
  • Consider adding pagination if the number of instruction files could be very large
  • File names are returned without validation - ensure downstream consumers handle potentially malicious filenames safely
  • The endpoint uses GET method which is appropriate for read-only operations

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function save_custom_instructions 80.6% similar

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

    From: /tf/active/vicechatdev/docchat/app.py
  • function load_custom_instructions 76.5% 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 get_instruction_templates 63.9% similar

    Flask API endpoint that returns a dictionary of predefined instruction templates for different document types including SOPs, work instructions, quality forms, and document comparison guidelines.

    From: /tf/active/vicechatdev/docchat/app.py
  • function api_templates_v2 60.4% 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_templates 60.2% similar

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

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