Observers API Reference
ProcessorObserver
async_batch_llm.observers.ProcessorObserver
Bases: ABC
Abstract base class for processor event observers.
on_event
abstractmethod
async
Handle processor event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event
|
ProcessingEvent
|
The event type |
required |
data
|
dict[str, Any]
|
Event-specific data |
required |
BaseObserver
async_batch_llm.observers.BaseObserver
Bases: ProcessorObserver
Base observer with no-op implementation.
MetricsObserver
async_batch_llm.observers.MetricsObserver
Bases: BaseObserver
Collect metrics for monitoring (thread-safe).
Initialize metrics collector.
Source code in src/async_batch_llm/observers/metrics.py
export_dict
async
Export metrics as a dictionary.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary containing all metrics and computed statistics |
Example
observer = MetricsObserver()
... process items ...
data = await observer.export_dict() print(data["success_rate"])
Source code in src/async_batch_llm/observers/metrics.py
export_json
async
Export metrics as JSON string.
Returns:
| Type | Description |
|---|---|
str
|
JSON string containing all metrics and computed statistics |
Example
observer = MetricsObserver()
... process items ...
json_str = await observer.export_json() print(json_str)
Source code in src/async_batch_llm/observers/metrics.py
export_prometheus
async
Export metrics in Prometheus text format.
Returns:
| Type | Description |
|---|---|
str
|
Prometheus-formatted metrics string |
Example
observer = MetricsObserver()
... process items ...
prom_text = await observer.export_prometheus() print(prom_text)
HELP async_batch_llm_items_processed Total items processed
TYPE async_batch_llm_items_processed counter
async_batch_llm_items_processed 100 ...
Source code in src/async_batch_llm/observers/metrics.py
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 | |
get_metrics
async
Get collected metrics with computed statistics (thread-safe).
Source code in src/async_batch_llm/observers/metrics.py
on_event
async
Collect metrics from events (thread-safe).
Source code in src/async_batch_llm/observers/metrics.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | |
reset
async
Reset all metrics (thread-safe).
Async since v0.16: the reset acquires the same lock as
on_event, so counts from an in-flight event can no longer land
in the discarded pre-reset dict.
Source code in src/async_batch_llm/observers/metrics.py
ProcessingEvent
async_batch_llm.ProcessingEvent
Bases: Enum
Events that can be observed during processing.
Event contracts
Interface for observers that monitor processing events.
class ProcessorObserver(ABC):
@abstractmethod
async def on_event(
self, event: ProcessingEvent, data: dict[str, Any]
) -> None: ...
Events:
BATCH_STARTED:{total, max_workers, start_time}BATCH_COMPLETED:{processed, succeeded, failed, total, total_tokens, cached_input_tokens, total_admission_wait_seconds, max_admission_wait_seconds, total_quota_wait_seconds, max_quota_wait_seconds, quota_wait_p50/p95/p99_seconds, estimated_input_tokens, estimated_output_tokens, reserved_tokens, reported_reconciliation_tokens, refunded_tokens, underestimated_tokens, unknown_usage_attempts, known_zero_usage_attempts, token_estimation_failures, quota_scope_count, admission_wait_p50/p95/p99_seconds, execution_p50/p95/p99_seconds, structured_output_recoveries, structured_output_retries_avoided, structured_output_recovery_reasons, input_queue_high_water_mark, result_queue_high_water_mark, duration}BATCH_ABORTED:{kind, reason, error_category, triggering_item_id, abort_mode}WORKER_STARTED/WORKER_STOPPED:{worker_id}ITEM_STARTED:{item_id, worker_id}ITEM_ADMITTED:{item_id, worker_id, attempt, wait_seconds, capacity, startup_ramp_wait_seconds}QUOTA_ADMITTED:{item_id, worker_id, attempt, try_number, quota_scope_id, wait_seconds, request_reserved, estimated_input_tokens, estimated_output_tokens, estimated_total_tokens, reserved_tokens, rpm_configured, tpm_configured, limited_by}QUOTA_RECONCILED:{item_id, worker_id, attempt, try_number, quota_scope_id, reserved_tokens, reported_tokens, known_usage, delta_tokens, disposition}ITEM_COMPLETED:{item_id, duration, tokens, admission_wait_seconds, structured_output_recovered, structured_output_recovery_reason, structured_output_retries_avoided}ITEM_FAILED:{item_id, submission_index, error_type, error_category}ITEM_REPLAYED:{item_id, submission_index, success, error_type, error_category}ITEM_DEADLINE_EXCEEDED:{item_id}RATE_LIMIT_HIT:{item_id, worker_id, quota_scope_id, strategy_type}COOLDOWN_STARTED:{worker_id, duration, consecutive, quota_scope_id?, strategy_type?}COOLDOWN_ENDED:{duration, error?}
A key marked ? may be absent. The keys listed here are the documented payload that
API stability covers; an event may carry more keys, which are
diagnostic and can change in a minor release.
add_work() raises public BatchAdmissionClosedError (a RuntimeError) when
finish, shutdown, or batch abort has stopped admission. Rejected items receive
no submission index. Use a new processor for additional work.
Observers may be duck-typed objects with a callable on_event(event, data);
subclassing ProcessorObserver is optional. The callback must return an awaitable.
Invalid callbacks are rejected at processor construction. Observer exceptions and
callback timeouts are logged without failing the item.
Each finalized item emits exactly one of ITEM_COMPLETED, ITEM_FAILED, or
ITEM_REPLAYED, after its checkpoint and before any fail-fast BATCH_ABORTED event.
A budget stop is different: the provider attempt that reaches the budget emits
BATCH_ABORTED (kind="budget_exceeded") before that item's own terminal event.
Middleware-filtered items count as failed; middleware recovery and after_process
changes determine the final event. Fatal checkpoint failures and cancellation before
finalization produce no terminal item event or processed-stat increment. Early
shutdown may abandon accepted items, so processed counts can be lower than total.
Replay does not emit an additional success/failure event or consume live tokens.
For live provider successes, duration and tokens retain final-attempt values;
new recovery-only success events use the final result's timing and token totals.
Cleanup note:
- Preferred: wrap
ParallelBatchProcessorinasync withso the ordered close runs automatically. - If you do not use a context manager, call
await processor.shutdown()afterprocess_all(). It stops workers and callbacks, releases admission state, runs strategy cleanups, and closes the artifact store. Repeated calls are safe and retry only what did not complete.