class Config_v3
Configuration manager class that loads, manages, and persists configuration settings for a contract validity analyzer application, supporting YAML files and environment variable overrides.
/tf/active/vicechatdev/contract_validity_analyzer/config/config.py
13 - 117
moderate
Purpose
The Config class serves as a centralized configuration management system for the contract validity analyzer. It handles loading configuration from YAML files, provides fallback default configurations, supports environment variable overrides for sensitive data (like API keys and credentials), and allows runtime configuration updates. The class manages settings for FileCloud integration, LLM providers, document processing parameters, output formatting, and logging configuration.
Source Code
class Config:
"""Configuration manager for the contract validity analyzer."""
def __init__(self, config_path: Optional[str] = None):
"""
Initialize configuration.
Args:
config_path: Path to configuration file
"""
self.config_path = config_path or os.path.join(os.path.dirname(__file__), 'base_config.yaml')
self.config = self._load_config()
def _load_config(self) -> Dict[str, Any]:
"""Load configuration from file."""
try:
if os.path.exists(self.config_path):
with open(self.config_path, 'r') as f:
config = yaml.safe_load(f)
# Override with environment variables if present
self._override_with_env(config)
return config
else:
logger.warning(f"Config file not found: {self.config_path}. Using defaults.")
return self._get_default_config()
except Exception as e:
logger.error(f"Error loading config: {e}")
return self._get_default_config()
def _override_with_env(self, config: Dict[str, Any]):
"""Override configuration with environment variables."""
# FileCloud settings
if 'FILECLOUD_SERVER_URL' in os.environ:
config['filecloud']['server_url'] = os.environ['FILECLOUD_SERVER_URL']
if 'FILECLOUD_USERNAME' in os.environ:
config['filecloud']['username'] = os.environ['FILECLOUD_USERNAME']
if 'FILECLOUD_PASSWORD' in os.environ:
config['filecloud']['password'] = os.environ['FILECLOUD_PASSWORD']
# LLM settings
if 'OPENAI_API_KEY' in os.environ:
config['llm']['api_key'] = os.environ['OPENAI_API_KEY']
if 'AZURE_OPENAI_API_KEY' in os.environ:
config['llm']['azure_api_key'] = os.environ['AZURE_OPENAI_API_KEY']
if 'AZURE_OPENAI_ENDPOINT' in os.environ:
config['llm']['azure_endpoint'] = os.environ['AZURE_OPENAI_ENDPOINT']
def _get_default_config(self) -> Dict[str, Any]:
"""Get default configuration."""
return {
'filecloud': {
'server_url': 'https://filecloud.vicebio.com',
'username': 'wim@vicebio.com',
'password': 'Studico01!',
'base_path': '/SHARED/vicebio_shares/00_Company_Governance/08_Third Parties Management/Third Parties'
},
'llm': {
'provider': 'openai',
'model': 'gpt-4o',
'temperature': 0.0,
'max_tokens': 4000,
'retry_attempts': 3,
'api_key': None
},
'document_processing': {
'supported_extensions': ['.pdf', '.doc', '.docx'],
'max_file_size_mb': 50,
'text_extraction_timeout': 300
},
'output': {
'csv_filename': 'contract_validity_analysis.csv',
'backup_results': True,
'timestamp_format': '%Y%m%d_%H%M%S'
},
'logging': {
'level': 'INFO',
'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
'file': 'contract_analyzer.log'
}
}
def get_section(self, section: str) -> Dict[str, Any]:
"""Get a configuration section."""
return self.config.get(section, {})
def get(self, key: str, default: Any = None) -> Any:
"""Get a configuration value."""
return self.config.get(key, default)
def set(self, key: str, value: Any):
"""Set a configuration value."""
self.config[key] = value
def save(self, path: Optional[str] = None):
"""Save configuration to file."""
save_path = path or self.config_path
try:
with open(save_path, 'w') as f:
yaml.dump(self.config, f, default_flow_style=False)
logger.info(f"Configuration saved to {save_path}")
except Exception as e:
logger.error(f"Failed to save configuration: {e}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
- | - |
Parameter Details
config_path: Optional path to a YAML configuration file. If not provided, defaults to 'base_config.yaml' in the same directory as the class file. This file should contain structured configuration data for filecloud, llm, document_processing, output, and logging sections.
Return Value
Instantiation returns a Config object with loaded configuration accessible through instance attributes and methods. The 'get_section' method returns a dictionary for a specific configuration section. The 'get' method returns any configuration value (with optional default). The 'set' method returns None. The 'save' method returns None but persists configuration to disk.
Class Interface
Methods
__init__(self, config_path: Optional[str] = None)
Purpose: Initialize the Config object by loading configuration from file or defaults
Parameters:
config_path: Optional path to YAML configuration file; defaults to 'base_config.yaml' in class directory
Returns: None (constructor)
_load_config(self) -> Dict[str, Any]
Purpose: Private method to load configuration from YAML file with environment variable overrides and fallback to defaults
Returns: Dictionary containing the loaded configuration structure with sections for filecloud, llm, document_processing, output, and logging
_override_with_env(self, config: Dict[str, Any])
Purpose: Private method to override configuration values with environment variables for FileCloud and LLM settings
Parameters:
config: Configuration dictionary to be modified in-place with environment variable values
Returns: None (modifies config dictionary in-place)
_get_default_config(self) -> Dict[str, Any]
Purpose: Private method to return default configuration structure when config file is missing or fails to load
Returns: Dictionary with default configuration including FileCloud credentials, LLM settings (gpt-4o model), document processing parameters, output settings, and logging configuration
get_section(self, section: str) -> Dict[str, Any]
Purpose: Retrieve an entire configuration section (e.g., 'llm', 'filecloud') as a dictionary
Parameters:
section: Name of the configuration section to retrieve (e.g., 'llm', 'filecloud', 'document_processing', 'output', 'logging')
Returns: Dictionary containing all key-value pairs for the requested section, or empty dictionary if section doesn't exist
get(self, key: str, default: Any = None) -> Any
Purpose: Retrieve a top-level configuration value by key with optional default fallback
Parameters:
key: Top-level configuration key to retrievedefault: Default value to return if key doesn't exist (defaults to None)
Returns: Configuration value associated with the key, or the default value if key is not found
set(self, key: str, value: Any)
Purpose: Set or update a top-level configuration value at runtime
Parameters:
key: Top-level configuration key to set or updatevalue: New value to assign to the key (can be any type including nested dictionaries)
Returns: None (modifies internal config dictionary)
save(self, path: Optional[str] = None)
Purpose: Persist the current configuration to a YAML file
Parameters:
path: Optional path where configuration should be saved; defaults to the original config_path used during initialization
Returns: None (writes configuration to file and logs success or error)
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
config_path |
str | Path to the configuration YAML file, either provided during initialization or defaulting to 'base_config.yaml' in the class directory | instance |
config |
Dict[str, Any] | Main configuration dictionary containing all loaded settings organized into sections (filecloud, llm, document_processing, output, logging) | instance |
Dependencies
osyamljsonpathlibtypinglogging
Required Imports
import os
import yaml
import json
from pathlib import Path
from typing import Dict, Any, Optional
import logging
Usage Example
# Basic instantiation with default config path
config = Config()
# Instantiation with custom config path
config = Config(config_path='/path/to/custom_config.yaml')
# Get entire configuration section
llm_config = config.get_section('llm')
print(llm_config['model']) # 'gpt-4o'
# Get specific configuration value
api_key = config.get('llm', {}).get('api_key')
max_tokens = config.get_section('llm')['max_tokens'] # 4000
# Get with default fallback
some_value = config.get('nonexistent_key', 'default_value')
# Set configuration value at runtime
config.set('llm', {'model': 'gpt-4-turbo', 'temperature': 0.5})
# Save configuration to file
config.save() # Saves to original config_path
config.save('/path/to/new_config.yaml') # Saves to custom path
# Access raw config dictionary
all_config = config.config
Best Practices
- Always instantiate Config at application startup to ensure configuration is loaded before other components need it
- Use environment variables for sensitive data (API keys, passwords) rather than hardcoding in YAML files
- Call get_section() for accessing related configuration groups rather than individual get() calls for better organization
- The config is loaded once during initialization; changes via set() only affect the in-memory config unless save() is called
- Default configuration contains hardcoded credentials which should be overridden via environment variables or custom config file in production
- The class logs warnings and errors using the logger, ensure logging is configured before instantiation
- Configuration file is loaded with yaml.safe_load for security; avoid using yaml.load
- If config file doesn't exist, the class gracefully falls back to defaults without raising exceptions
- Use save() method to persist runtime configuration changes for future application runs
- Environment variable overrides are applied after file loading, giving them highest priority
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class Config 67.6% similar
-
class Config_v2 65.2% similar
-
function test_config_loading 64.7% similar
-
class Config_v1 64.5% similar
-
function main_v4 61.6% similar