backend/src/reflection/resolvers.py) enables dynamic loading of Python modules, classes, and variables from string paths. This powers the configuration-driven architecture, allowing users to add new models, tools, and providers without modifying code.
Core Functions
resolve_variable()
backend/src/reflection/resolvers.py:28-73
resolve_class()
backend/src/reflection/resolvers.py:76-98
Path Format
Both functions use the format:module.path:attribute_name
Examples:
- Before
:: Module path (using.separators) - After
:: Attribute name (variable, class, or function)
Usage Patterns
1. Model Instantiation
Configuration (config.yaml):
backend/src/models/factory.py:26):
- Add new models without code changes
- Type safety via
base_classvalidation - Clear error messages for invalid configurations
2. Tool Loading
Configuration (config.yaml):
backend/src/tools/__init__.py):
3. Sandbox Provider Selection
Configuration (config.yaml):
backend/src/sandbox/__init__.py):
Error Handling
Missing Module
Missing Attribute
Type Validation Failure
Subclass Validation Failure
Dependency Hints
The reflection system provides actionable install hints for missing dependencies:Implementation Details
Path Parsing
- Must contain exactly one
:separator - Module path uses
.separators (standard Python import format) - Attribute name cannot contain
.or:
Module Import
ModuleNotFoundError: Package not installed → Install hint- Other
ImportError: Syntax error, circular import, etc. → Original error
Attribute Resolution
Type Validation (resolve_variable)
- Single type:
expected_type=BaseTool - Multiple types:
expected_type=(BaseTool, StructuredTool) - Uses
isinstance()for validation
Class Validation (resolve_class)
- Verify resolved object is a class (using
isinstance(obj, type)) - Verify class is subclass of base_class (using
issubclass())
Advanced Usage
1. Dynamic Tool Registration
2. Plugin System
3. Configuration-Driven Middleware
Testing
Performance Considerations
Caching
Reflection calls are typically executed once at startup, not per-request:Import Cost
First import of a module may be slow (e.g., TensorFlow, PyTorch):Security Considerations
Path Injection
Risk: User-controlled paths could import arbitrary modules. Mitigation: Validate paths against allowlist:Code Execution
Reflection enables arbitrary code execution if config is user-controlled. Best Practice: Load config from trusted sources only (local files, not user input).Best Practices
-
Always validate types:
-
Use base_class for classes:
-
Cache resolved values:
-
Handle errors gracefully:
-
Document expected types in config schema:
See Also
- Model Factory - Primary consumer of reflection system
- Configuration - How config files drive reflection
- Tools - Dynamic tool loading via reflection