function list_custom_instructions
Flask API endpoint that retrieves and returns a list of all custom instruction markdown files stored in the 'instructions' directory.
/tf/active/vicechatdev/docchat/app.py
1740 - 1753
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
flasklogging
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function save_custom_instructions 80.6% similar
-
function load_custom_instructions 76.5% similar
-
function get_instruction_templates 63.9% similar
-
function api_templates_v2 60.4% similar
-
function api_templates 60.2% similar