babylon.utils
Utility modules for Babylon/Babylon.
These are the tools of production - the means by which the engine transforms inputs into outputs.
- exception babylon.utils.BabylonError(message, error_code=None, details=None)[source]
Bases:
ExceptionBase exception for all Babylon/Babylon errors.
All exceptions in the system inherit from this class, allowing for unified error handling at the boundary.
- Parameters:
- Return type:
None
- message
Human-readable error description
- error_code
Machine-readable error identifier
- details
Additional context for debugging
- log(logger, level=logging.ERROR, exc_info=True)[source]
Log this exception with full structured context.
Convenience method for logging exceptions with their structured data included in the log record’s extra fields.
- Parameters:
- Return type:
Example
- try:
risky_operation()
- except BabylonError as e:
e.log(logger) # Logs with ERROR level and full context
- exception babylon.utils.ConfigurationError(message, error_code=None, details=None)[source]
Bases:
ValidationErrorRaised when configuration is invalid or missing.
The material conditions for operation have not been established.
- Parameters:
- Return type:
None
- exception babylon.utils.DatabaseError(message, error_code=None, details=None)[source]
Bases:
InfrastructureErrorRaised when database operations fail.
The Ledger cannot record the material reality.
- Parameters:
- Return type:
None
- exception babylon.utils.EmbeddingError(message, error_code=None, details=None)[source]
Bases:
BabylonErrorDEPRECATED: Use RagError instead.
Raised when embedding operations fail. The Archive cannot encode semantic meaning.
- Parameters:
- Return type:
None
- exception babylon.utils.ValidationError(message, error_code=None, details=None)[source]
Bases:
BabylonErrorRaised when data validation fails.
The input does not conform to the schema of material reality.
- Parameters:
- Return type:
None
- babylon.utils.retry_on_exception(max_retries=3, delay=1.0, backoff=2.0, exceptions=Exception, logger=None)[source]
Decorator that retries a function on specified exceptions.
Uses exponential backoff to avoid hammering failing resources. This is a materialist approach: we respect the physical constraints of the systems we depend on.
- Parameters:
- Return type:
Callable[[TypeVar(F, bound=Callable[...,Any])],TypeVar(F, bound=Callable[...,Any])]- Returns:
Decorated function with retry logic
Example
@retry_on_exception(max_retries=3, delay=1.0, exceptions=(ConnectionError,)) def fetch_data():
return requests.get(”https://api.example.com”)
- babylon.utils.quantize(value)[source]
Snap float to precision grid (ROUND_HALF_UP).
- Parameters:
value (
float) – Float to quantize (None treated as 0.0).- Return type:
- Returns:
Value on 10^-precision grid.
Examples
>>> quantize(0.123456789) 0.123457 >>> quantize(-0.123456789) -0.123457
- babylon.utils.get_precision()[source]
Current decimal places for quantization (default 6).
- Return type:
- babylon.utils.set_precision(decimal_places)[source]
Set quantization precision (1-10 decimal places).
- Parameters:
decimal_places (
int) – 1=coarse (0.1), 6=default (0.000001), 10=ultra.- Raises:
ValueError – If not in range [1, 10].
- Return type:
- class babylon.utils.SessionRecorder(metrics_collector, narrative_director=None, base_dir=None)[source]
Bases:
objectBlack box recorder for simulation forensics.
Implements SimulationObserver protocol to persist tick-by-tick simulation state to JSONL files for debugging and replay.
Each session creates a unique timestamped directory containing: - metrics.jsonl: TickMetrics snapshots (one per line) - events.jsonl: SimulationEvents (one per line) - narrative.jsonl: Narrative entries with tick numbers - summary.json: Session metadata on completion
- Parameters:
metrics_collector (
TickStateRecorder) – TickStateRecorder observer to extract TickMetrics.narrative_director (
NarrativeDirector|None) – Optional NarrativeDirector for narrative log.base_dir (
Path|None) – Base directory for sessions (default: logs/sessions).
Example
>>> from babylon.utils.recorder import SessionRecorder >>> recorder = SessionRecorder(metrics_collector=collector) >>> # Recorder is registered as observer with Simulation >>> # Files written automatically during simulation >>> zip_path = recorder.export_package() # Create debug archive
- __init__(metrics_collector, narrative_director=None, base_dir=None)[source]
Initialize SessionRecorder with observer references.
- Parameters:
metrics_collector (TickStateRecorder)
narrative_director (NarrativeDirector | None)
base_dir (Path | None)
- Return type:
None
- export_package()[source]
Create ZIP archive of session files.
Flushes all buffers and creates a compressed archive containing all session JSONL files for sharing and debugging.
- Return type:
- Returns:
Path to the created ZIP file.
- Raises:
RuntimeError – If no session has been started.
- on_simulation_end(final_state)[source]
Close file handles and write summary.
- Parameters:
final_state (
WorldState) – Final WorldState when simulation ends.- Return type:
- on_simulation_start(_initial_state, _config)[source]
Create session directory and open file handles.
- Parameters:
_initial_state (
WorldState) – WorldState at tick 0 (unused, required by protocol)._config (
SimulationConfig) – SimulationConfig for this run (unused, required by protocol).
- Return type:
- on_tick(_previous_state, new_state)[source]
Record tick data to JSONL files.
- Parameters:
_previous_state (
WorldState) – WorldState before tick (unused, required by protocol).new_state (
WorldState) – WorldState after tick (contains events).
- Return type:
Modules
Exception hierarchy for Babylon/Babylon. |
|
Custom logging utilities for Babylon. |
|
Mathematical utilities for simulation precision. |
|
Black box recorder for simulation forensics. |
|
Retry decorator for transient failure handling. |