function api_update_system_config
Flask API endpoint that allows administrators to update system configuration settings including system role, expertise, domain context, custom instructions, output style, and query languages, with persistence to disk.
/tf/active/vicechatdev/docchat/app.py
860 - 921
moderate
Purpose
This endpoint provides a secure way for administrators to modify the application's system configuration at runtime. It validates admin privileges, updates multiple configuration parameters in the config module, persists changes to a configuration file, and reinitializes the RAG engine with the new settings. This allows dynamic system behavior modification without requiring application restart.
Source Code
def api_update_system_config():
"""Update system configuration (admin only)"""
if not is_admin_user():
return jsonify({'error': 'Unauthorized - Admin access required'}), 403
try:
data = request.get_json()
config_updated = False
# Update config module values
if 'system_role' in data:
config.SYSTEM_ROLE = data['system_role']
config_updated = True
if 'system_expertise' in data:
# Convert multi-line string to list
expertise_str = data['system_expertise']
config.SYSTEM_EXPERTISE = [line.strip() for line in expertise_str.strip().split('\n') if line.strip()]
config_updated = True
if 'system_domain_context' in data:
config.SYSTEM_DOMAIN_CONTEXT = data['system_domain_context']
config_updated = True
if 'custom_system_instructions' in data:
custom_instructions = data['custom_system_instructions'].strip()
config.CUSTOM_SYSTEM_INSTRUCTIONS = custom_instructions if custom_instructions else None
config_updated = True
if 'output_style' in data:
config.OUTPUT_STYLE = data['output_style']
config_updated = True
if 'query_languages' in data:
# Validate and update supported languages for query expansion
query_langs = data['query_languages']
if isinstance(query_langs, list) and len(query_langs) > 0:
config.SUPPORTED_LANGUAGES = query_langs
logger.info(f"Query expansion languages updated to: {', '.join(query_langs)}")
config_updated = True
# Save changes to config.cfg file for persistence
if config_updated:
save_config_to_file()
# Reinitialize RAG engine with new configuration
global rag_engine
rag_engine = DocChatRAG(
collection_name=config.CHROMA_COLLECTION_NAME,
api_key=config.OPENAI_API_KEY
)
logger.info(f"System configuration updated by admin: {session['user'].get('email')}")
return jsonify({
'success': True,
'message': 'System configuration updated successfully (persisted to disk)'
})
except Exception as e:
logger.error(f"Error updating system config: {e}", exc_info=True)
return jsonify({'error': str(e)}), 500
Return Value
Returns a JSON response with status code. On success (200): {'success': True, 'message': 'System configuration updated successfully (persisted to disk)'}. On unauthorized access (403): {'error': 'Unauthorized - Admin access required'}. On error (500): {'error': '<error message>'}.
Dependencies
flaskloggingconfigrag_enginedocument_indexer
Required Imports
from flask import Flask, request, jsonify, session
import logging
import config
from rag_engine import DocChatRAG
Usage Example
# Example POST request to update system configuration
import requests
# Assuming user is logged in as admin with valid session
url = 'http://localhost:5000/api/admin/system-config'
headers = {'Content-Type': 'application/json'}
payload = {
'system_role': 'Technical Documentation Assistant',
'system_expertise': 'Python programming\nAPI design\nDatabase management',
'system_domain_context': 'Enterprise software development',
'custom_system_instructions': 'Always provide code examples',
'output_style': 'detailed',
'query_languages': ['en', 'es', 'fr']
}
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200:
print('Configuration updated:', response.json())
else:
print('Error:', response.json())
Best Practices
- Always ensure the user has admin privileges before calling this endpoint
- Validate all input data before updating configuration to prevent invalid states
- The function reinitializes the global rag_engine, which may cause brief service interruption
- Configuration changes are persisted to disk via save_config_to_file(), ensuring they survive application restarts
- Multi-line expertise strings are automatically split and cleaned into list format
- Empty custom_system_instructions are converted to None rather than empty strings
- Query languages must be provided as a non-empty list to be updated
- All configuration updates are logged with the admin user's email for audit purposes
- Consider implementing rate limiting on this endpoint to prevent abuse
- Ensure proper error handling and rollback mechanisms if RAG engine reinitialization fails
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function api_get_system_config 79.2% similar
-
function api_update_chat_config 71.8% similar
-
function api_update_section 62.8% similar
-
function save_session_settings 60.2% similar
-
function system_status 59.1% similar