API Reference
robotsix_cost_monitor
robotsix-cost-monitor — multi-Langfuse cost monitoring dashboard.
__version__ = '0.9.3'
module-attribute
robotsix_cost_monitor.aggregations
Pure cost-aggregation and transformation functions over trace dicts.
No I/O, no HTTP, no LangfuseClient dependency — only typing and
datetime. Trivially testable without httpx mocking.
BackendKind = Literal['openrouter', 'claude-sdk', 'all']
module-attribute
_PERIODIC_SESSION_RE = re.compile('(?:^|.*[·|]\\s*)([a-z_]+)-\\d{8}T\\d{6}Z-')
module-attribute
LangfuseTrace
Bases: BaseModel
A single trace from the Langfuse /api/public/traces response.
Handles both sessionId (canonical Langfuse API key) and
session_id (observed in some responses) via populate_by_name.
extra is "ignore" — and must stay that way. Cached trace lists are
the dominant memory consumer in this process: a 168 h window across the
fleet is ~21 k traces, and Langfuse returns each one with its full input
/ output / metadata payload. Under extra="allow" Pydantic
retained all of it in __pydantic_extra__ — ~777 MB of raw JSON held
live, which pegged the 2 GB container limit. Nothing here reads those
fields (aggregation only needs the seven declared ones), so they are
dropped at the validation boundary rather than cached forever.
Source code in src/robotsix_cost_monitor/clients/models.py
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | |
_empty_model_slot()
Source code in src/robotsix_cost_monitor/aggregations.py
54 55 56 57 58 59 60 61 | |
_model_rows(acc)
Format a model→totals accumulator into rows sorted by cost desc.
Source code in src/robotsix_cost_monitor/aggregations.py
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | |
_parse_ts(trace)
Source code in src/robotsix_cost_monitor/aggregations.py
184 185 186 187 188 189 190 191 | |
_sorted_cost_rows(acc, key_field='name')
Convert a {key: {cost, count}} accumulator into rows sorted by cost desc.
Source code in src/robotsix_cost_monitor/aggregations.py
81 82 83 84 85 86 87 88 89 90 | |
_trace_cost(trace)
Extract a trace's total cost, tolerant of Langfuse field-name variants.
Source code in src/robotsix_cost_monitor/aggregations.py
31 32 33 34 35 36 37 | |
_trace_label(trace)
Display label for a trace in the by-agent view.
Prefers the trace name (the stage/agent). Some traces reach Langfuse without a name (a pydantic-ai/claude_sdk span became the trace root in a context where the session was lost — see robotsix-llmio's trace-name handling); rather than dumping their cost into one opaque "(unnamed)" bucket, attribute it to its session so it's still actionable.
Source code in src/robotsix_cost_monitor/aggregations.py
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
_utc_now()
Source code in src/robotsix_cost_monitor/aggregations.py
40 41 | |
aggregate_by_name(traces)
Cost + count grouped by trace name (the pipeline stage/agent).
Source code in src/robotsix_cost_monitor/aggregations.py
154 155 156 157 158 159 160 161 162 | |
aggregate_by_name_backend(rows, backend)
Merge per-(stage, backend) observation rows for a single backend.
rows are pre-flattened dicts (each with at least name, backend,
cost and count). Rows whose backend does not match are
silently dropped. Multiple projects' rows can be passed together — they
are summed by stage name, producing the {"name", "cost", "count"}
shape returned by :func:aggregate_by_name.
Source code in src/robotsix_cost_monitor/aggregations.py
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | |
aggregate_by_session(traces)
Cost + trace-count grouped by sessionId.
What a session means is the traced component's business, not this dashboard's: a mill ticket run, a chat conversation, a cognee ingest batch. Group and report by the id; never name it after one component's unit of work.
Source code in src/robotsix_cost_monitor/aggregations.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | |
backend_cost_series(parts, backend)
Merge per-project cost maps into a sorted time series.
{time_bucket -> {backend -> cost}} maps are merged into a cost
series [{bucket_start, cost}] for backend (or the all-backends total
when backend is "all"), sorted by time bucket.
Source code in src/robotsix_cost_monitor/aggregations.py
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 | |
backend_for_model(model)
Map a model name to its serving backend (transport).
Keys on the model-ID shape, not specific names, so it survives model
version bumps: OpenRouter model IDs are always vendor/model (contain a
/); the Claude SDK uses bare aliases (opus/haiku/sonnet).
Source code in src/robotsix_cost_monitor/aggregations.py
44 45 46 47 48 49 50 51 | |
cost_trend(traces, hours, buckets=48)
Bucket total cost over the time window into buckets equal slots.
Source code in src/robotsix_cost_monitor/aggregations.py
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | |
merge_model_costs(parts)
Merge per-model usage rows from several projects, summing by model.
Source code in src/robotsix_cost_monitor/aggregations.py
120 121 122 123 124 125 126 127 128 129 130 131 | |
most_expensive_session(traces)
Return the single most-expensive session for cost display.
Source code in src/robotsix_cost_monitor/aggregations.py
256 257 258 259 | |
most_expensive_trace(traces)
Return the single most-expensive trace for cost display.
Source code in src/robotsix_cost_monitor/aggregations.py
242 243 244 245 246 247 248 249 250 251 252 253 | |
robotsix_cost_monitor.app
FastAPI app: cost dashboard + reconciliation endpoints, server-rendered UI.
_AUTH_EXEMPT_PATHS = ('/health', '/health/live', '/readyz', '/metrics')
module-attribute
_WEB = Path(__file__).resolve().parent / 'web'
module-attribute
__version__ = '0.9.3'
module-attribute
cache_warm_failure = Counter('robotsix_cost_monitor_cache_warm_failure_total', 'Total number of failed dashboard cache warm-ups.')
module-attribute
cache_warm_success = Counter('robotsix_cost_monitor_cache_warm_success_total', 'Total number of successful dashboard cache warm-ups.')
module-attribute
config_router = APIRouter()
module-attribute
logger = structlog.get_logger(__name__)
module-attribute
router = APIRouter()
module-attribute
Config
Bases: BaseModel
Top-level config: registry-driven project discovery + global settings.
Project credentials are discovered at runtime from the central-deploy registry — there is no hardcoded project list.
Source code in src/robotsix_cost_monitor/config/__init__.py
215 216 217 218 219 220 221 222 | |
CostMonitorError
Bases: Exception
Base exception for all cost-monitor errors.
Source code in src/robotsix_cost_monitor/exceptions.py
26 27 28 29 30 31 32 33 34 35 36 37 38 | |
__init__(detail='', *, status_code=None)
Initialise with an optional detail message and status code override.
Source code in src/robotsix_cost_monitor/exceptions.py
33 34 35 36 37 38 | |
CostService
Cross-project cost aggregation service with per-window TTL cache.
All five internal caches share a single :attr:last_updated timestamp
(the youngest refresh across all caches) so the dashboard can display
data freshness.
Source code in src/robotsix_cost_monitor/service/core.py
53 54 55 56 57 58 59 60 61 62 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 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 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 | |
last_updated
property
UTC datetime of the most recent cache refresh, or None when cold.
__init__(config, registry_client)
Initialise the service with config and a registry client.
Starts with an empty project/client map — call :meth:refresh_projects
during startup to populate from the registry.
Source code in src/robotsix_cost_monitor/service/core.py
61 62 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 | |
backend_trend(slug, hours, backend)
async
Return the cost trend for a backend, merged across selected projects.
Window-accurate; time-bucket granularity scales with the window.
Source code in src/robotsix_cost_monitor/service/core.py
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 | |
by_agent(slug, hours, backend='all')
async
Cost by trace name (stage/agent), merged across selected projects.
When backend is "all" (default), uses trace-level cost
(aggregate_by_name) — unchanged from the original behavior.
When a specific backend is selected, uses per-(stage, backend) observation-metrics so that each stage's cost is attributed to the backend(s) it actually used.
Source code in src/robotsix_cost_monitor/service/core.py
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | |
by_model(slug, hours)
async
Cost + token usage by model, merged across selected projects.
Window-accurate (see :meth:LangfuseClient.fetch_model_usage_window).
Source code in src/robotsix_cost_monitor/service/core.py
356 357 358 359 360 361 362 | |
components()
Return discovered projects grouped by owning component.
Insertion order follows the registry, so the dashboard's component list is stable across refreshes. Projects whose component is unknown are grouped under their own slug rather than dropped.
Source code in src/robotsix_cost_monitor/service/core.py
140 141 142 143 144 145 146 147 148 149 150 | |
highlights(slug, hours, backend='all')
async
Return dashboard highlights: top trace, session, and summary stats.
When backend is not "all", traces are filtered to only those
whose name appears in the agent-usage rows for that backend, keeping
the highlights consistent with the backend selector.
Source code in src/robotsix_cost_monitor/service/core.py
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 | |
invalidate_all()
Clear every internal cache so the next request fetches fresh data.
Source code in src/robotsix_cost_monitor/service/core.py
101 102 103 104 105 | |
projects()
Return every discovered project, in registry order.
Source code in src/robotsix_cost_monitor/service/core.py
136 137 138 | |
refresh_projects()
async
Query the registry and rebuild the project/client map.
Best-effort: on failure the existing project list is kept unchanged.
Source code in src/robotsix_cost_monitor/service/core.py
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 | |
summary(slug, hours, backend='all')
async
Per-project totals + the aggregate, for the window.
Cost is observation-based (the same window-accurate metrics source as the
by-model / by-backend breakdowns), so the headline total, the per-model
rows, and the per-backend totals all reconcile — a backend can never
exceed the total. trace_count comes from a server-side view=traces
count metric (not by paging every trace), so this stays fast.
When backend is not "all", only observation rows attributed to that
backend are counted, so the per-component rollup and total reflect costs
for the selected backend alone.
Source code in src/robotsix_cost_monitor/service/core.py
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 | |
trend(slug, hours, buckets=48)
async
Return a cost trend series across the window.
Source code in src/robotsix_cost_monitor/service/core.py
402 403 404 405 406 407 408 | |
MillAPIError
Bases: RuntimeError
The mill board API could not be queried (network or HTTP error).
Raised instead of returning an empty result so callers can tell a failed check apart from a successful check that found nothing. Callers must treat this as "unknown": preserve the last known stuck-ticket state rather than overwriting it with an empty list.
Source code in src/robotsix_cost_monitor/clients/mill.py
22 23 24 25 26 27 28 29 | |
MillClient
dataclass
HTTP client for the robotsix-mill board API.
Used by the stuck-ticket background loop to periodically query the
mill's GET /tickets endpoint and identify tickets that have been
in a non-terminal state longer than the configured threshold.
Source code in src/robotsix_cost_monitor/clients/mill.py
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 178 179 180 181 182 183 184 185 186 187 188 189 190 | |
base_url
property
Return the mill API base URL with trailing slash stripped.
__post_init__()
Initialise lazy HTTP client holder to None.
Source code in src/robotsix_cost_monitor/clients/mill.py
84 85 86 | |
close()
async
Release the underlying HTTP client.
Source code in src/robotsix_cost_monitor/clients/mill.py
186 187 188 189 190 | |
fetch_stuck_tickets()
async
Query the mill for tickets stuck in non-terminal states.
Calls GET /tickets (include_closed=false is the default,
so terminal states are already excluded). Each returned ticket
whose updated_at is older than the configured threshold is
flagged as stuck.
Returns an empty list when detection is disabled. Raises
:class:MillAPIError when the mill API is unreachable, returns
an error status, or returns an unexpected payload — the caller
must then keep the previous results instead of treating the
check as a clean empty result.
Source code in src/robotsix_cost_monitor/clients/mill.py
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 178 179 180 181 182 183 184 | |
RegistryClient
Discovers Langfuse-enabled components from the central-deploy registry.
The central-deploy registry exposes an authenticated GET /fleet/langfuse
endpoint that returns every registered component and, for each
Langfuse-enabled one, its langfuse_host and projects
(each with alias, public_key, secret_key).
Source code in src/robotsix_cost_monitor/clients/registry.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | |
__init__(base_url, api_key, timeout=30.0)
Initialise with the central-deploy registry URL and API key.
Source code in src/robotsix_cost_monitor/clients/registry.py
30 31 32 33 34 | |
fetch_projects()
async
Query the registry for all Langfuse-enabled components.
Returns a (possibly empty) list of RegistryProject instances. Logs and returns empty on any transient failure — the service keeps its last-known-good project list.
Source code in src/robotsix_cost_monitor/clients/registry.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | |
_cache_refresh_loop(cfg, service, interval_s)
async
Periodically re-fetch dashboard aggregates so the cache stays warm.
Runs forever until cancelled; sleeps interval_s between refreshes.
Source code in src/robotsix_cost_monitor/app.py
119 120 121 122 123 124 125 126 127 128 | |
_cost_monitor_error_handler(request, exc)
async
Render a typed :class:CostMonitorError via the canonical envelope.
Maps the domain exception onto :class:robotsix_http.fastapi.DomainError
so its status_code / error_code drive the shared
{"error": {"code", "detail"}} envelope built by
:func:robotsix_http.fastapi.domain_error_handler.
Source code in src/robotsix_cost_monitor/app.py
39 40 41 42 43 44 45 46 47 48 49 50 51 | |
_readiness_checks(cfg, service)
Build the named readiness checks for the shared health router.
projects— the registry has yielded at least one Langfuse project (in-memory; populated byrefresh_projectsat startup and on poll). Without it every cost endpoint serves empty data.data_dir— the reconciliation snapshot directory exists and is writable (reconcile persists snapshots there before comparing).
Source code in src/robotsix_cost_monitor/app.py
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | |
_reconcile_loop(cfg, service, hours)
async
Reconcile all projects on a schedule until cancelled.
Runs every hours hours (with an initial run so the banner has data immediately).
Source code in src/robotsix_cost_monitor/app.py
70 71 72 73 74 75 76 77 78 79 80 81 82 | |
_stuck_ticket_loop(mill, interval_s)
async
Periodically check the mill board for tickets stuck in non-terminal states.
Each run queries GET /tickets and logs a warning for every ticket
whose updated_at is older than stuck_ticket_threshold_hours.
When the mill API is unreachable the gauge keeps its previous value —
a failed check must never reset stuck_ticket_count to zero,
otherwise downstream alerting would silently clear during outages.
Source code in src/robotsix_cost_monitor/app.py
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 | |
_warm_cache(cfg, service)
async
Pre-fetch aggregates for all dashboard window presets on startup.
Every window-selector option is warmed so window switches are near-instant from the first page load. Best-effort — failures are logged and discarded.
Source code in src/robotsix_cost_monitor/app.py
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 | |
create_app(config=None)
Assemble the FastAPI application.
Loads the project :class:~robotsix_cost_monitor.config.Config (when config
is None, reads from the path given by ROBOTSIX_CONFIG_FILE), builds a
:class:~robotsix_cost_monitor.service.CostService, wires the lifespan
(reconciliation background loop), mounts the route handlers from
:mod:robotsix_cost_monitor.routes, registers exception handlers, and serves
the static web assets.
Source code in src/robotsix_cost_monitor/app.py
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 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 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 | |
data_dir(settings=None)
Resolve the runtime-state directory for persistence.
When settings is given, the settings.data_dir field is used (relative
paths are resolved against the repo root). Without settings the legacy
default .data relative to the repo root is returned for backward
compatibility.
Source code in src/robotsix_cost_monitor/config/__init__.py
225 226 227 228 229 230 231 232 233 234 235 236 237 238 | |
load_config(path=None)
Load and validate the configuration via ROBOTSIX_CONFIG_FILE.
When path is given (tests), passes it through directly to
:func:robotsix_config.load_config.
Source code in src/robotsix_cost_monitor/config/__init__.py
241 242 243 244 245 246 247 248 249 | |
reconcile_all(config, service)
async
Reconcile every project, persist the result, and return it.
The stored last.json powers the dashboard's warning banner and the
/api/reconcile/last endpoint.
Source code in src/robotsix_cost_monitor/reconcile.py
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | |
register_error_handlers(app)
Wire the shared exception-handler suite plus the domain-error adapter.
Delegates the standard handlers (validation, HTTPException,
ExternalHTTPError, catch-all) to
:func:robotsix_http.fastapi.register_exception_handlers, then registers
:func:_cost_monitor_error_handler so the typed :class:CostMonitorError
hierarchy keeps its status/code mapping.
Source code in src/robotsix_cost_monitor/app.py
54 55 56 57 58 59 60 61 62 63 64 | |
resolve_registry_api_key(settings)
Return the effective registry API key.
When deployed by robotsix-central-deploy with the robotsix.deploy.access:
"agent" label, the deploy API key is auto-injected as the
DEPLOY_API_KEY environment variable — no manual config needed. Falls
back to settings.registry_api_key for local development.
Source code in src/robotsix_cost_monitor/config/__init__.py
187 188 189 190 191 192 193 194 195 196 197 198 | |
robotsix_cost_monitor.cli
Command-line entrypoint: run the dashboard server, or print a cost summary.
CostService
Cross-project cost aggregation service with per-window TTL cache.
All five internal caches share a single :attr:last_updated timestamp
(the youngest refresh across all caches) so the dashboard can display
data freshness.
Source code in src/robotsix_cost_monitor/service/core.py
53 54 55 56 57 58 59 60 61 62 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 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 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 | |
last_updated
property
UTC datetime of the most recent cache refresh, or None when cold.
__init__(config, registry_client)
Initialise the service with config and a registry client.
Starts with an empty project/client map — call :meth:refresh_projects
during startup to populate from the registry.
Source code in src/robotsix_cost_monitor/service/core.py
61 62 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 | |
backend_trend(slug, hours, backend)
async
Return the cost trend for a backend, merged across selected projects.
Window-accurate; time-bucket granularity scales with the window.
Source code in src/robotsix_cost_monitor/service/core.py
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 | |
by_agent(slug, hours, backend='all')
async
Cost by trace name (stage/agent), merged across selected projects.
When backend is "all" (default), uses trace-level cost
(aggregate_by_name) — unchanged from the original behavior.
When a specific backend is selected, uses per-(stage, backend) observation-metrics so that each stage's cost is attributed to the backend(s) it actually used.
Source code in src/robotsix_cost_monitor/service/core.py
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | |
by_model(slug, hours)
async
Cost + token usage by model, merged across selected projects.
Window-accurate (see :meth:LangfuseClient.fetch_model_usage_window).
Source code in src/robotsix_cost_monitor/service/core.py
356 357 358 359 360 361 362 | |
components()
Return discovered projects grouped by owning component.
Insertion order follows the registry, so the dashboard's component list is stable across refreshes. Projects whose component is unknown are grouped under their own slug rather than dropped.
Source code in src/robotsix_cost_monitor/service/core.py
140 141 142 143 144 145 146 147 148 149 150 | |
highlights(slug, hours, backend='all')
async
Return dashboard highlights: top trace, session, and summary stats.
When backend is not "all", traces are filtered to only those
whose name appears in the agent-usage rows for that backend, keeping
the highlights consistent with the backend selector.
Source code in src/robotsix_cost_monitor/service/core.py
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 | |
invalidate_all()
Clear every internal cache so the next request fetches fresh data.
Source code in src/robotsix_cost_monitor/service/core.py
101 102 103 104 105 | |
projects()
Return every discovered project, in registry order.
Source code in src/robotsix_cost_monitor/service/core.py
136 137 138 | |
refresh_projects()
async
Query the registry and rebuild the project/client map.
Best-effort: on failure the existing project list is kept unchanged.
Source code in src/robotsix_cost_monitor/service/core.py
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 | |
summary(slug, hours, backend='all')
async
Per-project totals + the aggregate, for the window.
Cost is observation-based (the same window-accurate metrics source as the
by-model / by-backend breakdowns), so the headline total, the per-model
rows, and the per-backend totals all reconcile — a backend can never
exceed the total. trace_count comes from a server-side view=traces
count metric (not by paging every trace), so this stays fast.
When backend is not "all", only observation rows attributed to that
backend are counted, so the per-component rollup and total reflect costs
for the selected backend alone.
Source code in src/robotsix_cost_monitor/service/core.py
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 | |
trend(slug, hours, buckets=48)
async
Return a cost trend series across the window.
Source code in src/robotsix_cost_monitor/service/core.py
402 403 404 405 406 407 408 | |
RegistryClient
Discovers Langfuse-enabled components from the central-deploy registry.
The central-deploy registry exposes an authenticated GET /fleet/langfuse
endpoint that returns every registered component and, for each
Langfuse-enabled one, its langfuse_host and projects
(each with alias, public_key, secret_key).
Source code in src/robotsix_cost_monitor/clients/registry.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | |
__init__(base_url, api_key, timeout=30.0)
Initialise with the central-deploy registry URL and API key.
Source code in src/robotsix_cost_monitor/clients/registry.py
30 31 32 33 34 | |
fetch_projects()
async
Query the registry for all Langfuse-enabled components.
Returns a (possibly empty) list of RegistryProject instances. Logs and returns empty on any transient failure — the service keeps its last-known-good project list.
Source code in src/robotsix_cost_monitor/clients/registry.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | |
load_config(path=None)
Load and validate the configuration via ROBOTSIX_CONFIG_FILE.
When path is given (tests), passes it through directly to
:func:robotsix_config.load_config.
Source code in src/robotsix_cost_monitor/config/__init__.py
241 242 243 244 245 246 247 248 249 | |
main(argv=None)
CLI entrypoint: dispatch to serve, summary, or reconcile.
Source code in src/robotsix_cost_monitor/cli.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | |
reconcile_all(config, service)
async
Reconcile every project, persist the result, and return it.
The stored last.json powers the dashboard's warning banner and the
/api/reconcile/last endpoint.
Source code in src/robotsix_cost_monitor/reconcile.py
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | |
reconcile_project(project, settings)
async
Reconcile one project's OpenRouter spend vs Langfuse traced cost.
Snapshots the key's cumulative usage and diffs against the previous snapshot; compares the provider delta to the Langfuse traced cost over the same interval. Returns a status dict (also includes the remaining balance). The snapshot is updated on every call.
Source code in src/robotsix_cost_monitor/reconcile.py
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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 | |
resolve_registry_api_key(settings)
Return the effective registry API key.
When deployed by robotsix-central-deploy with the robotsix.deploy.access:
"agent" label, the deploy API key is auto-injected as the
DEPLOY_API_KEY environment variable — no manual config needed. Falls
back to settings.registry_api_key for local development.
Source code in src/robotsix_cost_monitor/config/__init__.py
187 188 189 190 191 192 193 194 195 196 197 198 | |
robotsix_cost_monitor.clients
External API clients (Langfuse, Registry) for robotsix-cost-monitor.
__all__ = ['RegistryClient', 'RegistryProject']
module-attribute
RegistryClient
Discovers Langfuse-enabled components from the central-deploy registry.
The central-deploy registry exposes an authenticated GET /fleet/langfuse
endpoint that returns every registered component and, for each
Langfuse-enabled one, its langfuse_host and projects
(each with alias, public_key, secret_key).
Source code in src/robotsix_cost_monitor/clients/registry.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | |
__init__(base_url, api_key, timeout=30.0)
Initialise with the central-deploy registry URL and API key.
Source code in src/robotsix_cost_monitor/clients/registry.py
30 31 32 33 34 | |
fetch_projects()
async
Query the registry for all Langfuse-enabled components.
Returns a (possibly empty) list of RegistryProject instances. Logs and returns empty on any transient failure — the service keeps its last-known-good project list.
Source code in src/robotsix_cost_monitor/clients/registry.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | |
RegistryProject
Bases: BaseModel
One Langfuse project discovered from the central-deploy registry.
A project is a single LLM function, not a component: a component with
two tracing subsystems declares two projects (e.g. robotsix-chat and
robotsix-chat-cognee). :attr:component_id records which component
owns it, so the dashboard can roll a component's projects up without any
per-component code.
Source code in src/robotsix_cost_monitor/clients/models.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | |
robotsix_cost_monitor.config
Configuration models + loader for robotsix-cost-monitor.
Cost-monitor discovers projects at runtime from the central-deploy registry instead of carrying hardcoded Langfuse credentials. The config file only holds generic settings: the registry URL + API key, polling/window defaults, and auth/reconcile knobs.
The config is located via the ROBOTSIX_CONFIG_FILE environment variable
(default config/config.json). config/config.example.json is the
committed template (gitignored real keys).
_REPO_ROOT = Path(__file__).resolve().parents[3]
module-attribute
AuthConfig
Bases: BaseModel
HTTP Basic auth for the dashboard.
The dashboard has no other access control, so when it is exposed through
the central-deploy gateway (an unauthenticated reverse proxy) this MUST
be set — otherwise the cost data is public. When either field is empty
the dashboard is served open (local dev / SSH-tunnel only). /health
is always exempt so the container healthcheck works.
Source code in src/robotsix_cost_monitor/config/__init__.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | |
Config
Bases: BaseModel
Top-level config: registry-driven project discovery + global settings.
Project credentials are discovered at runtime from the central-deploy registry — there is no hardcoded project list.
Source code in src/robotsix_cost_monitor/config/__init__.py
215 216 217 218 219 220 221 222 | |
Settings
Bases: BaseModel
Global dashboard settings — no per-project config (registry-driven).
Source code in src/robotsix_cost_monitor/config/__init__.py
52 53 54 55 56 57 58 59 60 61 62 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 178 179 180 181 182 183 184 | |
data_dir(settings=None)
Resolve the runtime-state directory for persistence.
When settings is given, the settings.data_dir field is used (relative
paths are resolved against the repo root). Without settings the legacy
default .data relative to the repo root is returned for backward
compatibility.
Source code in src/robotsix_cost_monitor/config/__init__.py
225 226 227 228 229 230 231 232 233 234 235 236 237 238 | |
load_config(path=None)
Load and validate the configuration via ROBOTSIX_CONFIG_FILE.
When path is given (tests), passes it through directly to
:func:robotsix_config.load_config.
Source code in src/robotsix_cost_monitor/config/__init__.py
241 242 243 244 245 246 247 248 249 | |
resolve_mill_api_key(settings)
Return the effective mill API key.
Follows the same convention as :func:resolve_registry_api_key: the
DEPLOY_API_KEY environment variable is the default when deployed by
robotsix-central-deploy. Falls back to settings.mill_api_key for
local development.
Source code in src/robotsix_cost_monitor/config/__init__.py
201 202 203 204 205 206 207 208 209 210 211 212 | |
resolve_registry_api_key(settings)
Return the effective registry API key.
When deployed by robotsix-central-deploy with the robotsix.deploy.access:
"agent" label, the deploy API key is auto-injected as the
DEPLOY_API_KEY environment variable — no manual config needed. Falls
back to settings.registry_api_key for local development.
Source code in src/robotsix_cost_monitor/config/__init__.py
187 188 189 190 191 192 193 194 195 196 197 198 | |
robotsix_cost_monitor.exceptions
Typed exception hierarchy for cost-monitor.
Distinguishes retriable network errors from terminal configuration errors,
so catch-sites can make deliberate choices instead of blanket except Exception.
The HTTP exception classes inherit from both :class:CostMonitorError (for
the FastAPI exception handler and local catch-blocks) and the corresponding
:mod:robotsix_http exception classes (so the shared :class:RetryClient
can raise them directly while existing except clauses still match).
CacheError
Bases: CostMonitorError
Cache corruption or deadline overflow — retriable.
Source code in src/robotsix_cost_monitor/exceptions.py
111 112 113 114 115 | |
CostMonitorError
Bases: Exception
Base exception for all cost-monitor errors.
Source code in src/robotsix_cost_monitor/exceptions.py
26 27 28 29 30 31 32 33 34 35 36 37 38 | |
__init__(detail='', *, status_code=None)
Initialise with an optional detail message and status code override.
Source code in src/robotsix_cost_monitor/exceptions.py
33 34 35 36 37 38 | |
ExternalAuthError
Bases: ExternalServiceError, ExternalAuthError
Bad API key or credentials — NOT retriable.
Source code in src/robotsix_cost_monitor/exceptions.py
90 91 92 93 94 | |
ExternalRateLimitError
Bases: ExternalServiceError, ExternalRateLimitError
429 rate limit — retriable with backoff.
Source code in src/robotsix_cost_monitor/exceptions.py
97 98 99 100 101 | |
ExternalServiceError
Bases: CostMonitorError, ExternalServiceError
An external API (Langfuse, OpenRouter) returned an error.
Transient failures (timeout, 5xx, 429) should be retried; terminal failures (401, 403, 404) should surface immediately.
Source code in src/robotsix_cost_monitor/exceptions.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 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 | |
__init__(detail='', *, status_code=None, response=None)
Initialise from a detail string, optionally with an HTTP response.
When response is None (constructed locally), a synthetic
:class:httpx.Response with the class-level status_code is
created to satisfy :class:ExternalHTTPError's required keyword
arguments.
Source code in src/robotsix_cost_monitor/exceptions.py
50 51 52 53 54 55 56 57 58 59 60 61 62 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 | |
ProjectNotFoundError
Bases: CostMonitorError
A project slug does not match any configured project.
Source code in src/robotsix_cost_monitor/exceptions.py
104 105 106 107 108 | |
robotsix_cost_monitor.reconcile
OpenRouter ↔ Langfuse cost reconciliation via cumulative-usage snapshots.
OpenRouter exposes only cumulative key usage, so we snapshot it (under
.data/reconcile/<slug>.json) and diff successive readings to get the spend
in the interval, then compare that to the Langfuse traced cost over the same
interval. Drift above the tolerance is flagged.
logger = structlog.get_logger(__name__)
module-attribute
reconcile_duration = Gauge('robotsix_cost_monitor_reconcile_duration_seconds', 'Duration of the last reconciliation run in seconds.')
module-attribute
reconcile_runs = Counter('robotsix_cost_monitor_reconcile_runs_total', 'Total number of reconciliation runs.')
module-attribute
Config
Bases: BaseModel
Top-level config: registry-driven project discovery + global settings.
Project credentials are discovered at runtime from the central-deploy registry — there is no hardcoded project list.
Source code in src/robotsix_cost_monitor/config/__init__.py
215 216 217 218 219 220 221 222 | |
CostService
Cross-project cost aggregation service with per-window TTL cache.
All five internal caches share a single :attr:last_updated timestamp
(the youngest refresh across all caches) so the dashboard can display
data freshness.
Source code in src/robotsix_cost_monitor/service/core.py
53 54 55 56 57 58 59 60 61 62 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 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 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 | |
last_updated
property
UTC datetime of the most recent cache refresh, or None when cold.
__init__(config, registry_client)
Initialise the service with config and a registry client.
Starts with an empty project/client map — call :meth:refresh_projects
during startup to populate from the registry.
Source code in src/robotsix_cost_monitor/service/core.py
61 62 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 | |
backend_trend(slug, hours, backend)
async
Return the cost trend for a backend, merged across selected projects.
Window-accurate; time-bucket granularity scales with the window.
Source code in src/robotsix_cost_monitor/service/core.py
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 | |
by_agent(slug, hours, backend='all')
async
Cost by trace name (stage/agent), merged across selected projects.
When backend is "all" (default), uses trace-level cost
(aggregate_by_name) — unchanged from the original behavior.
When a specific backend is selected, uses per-(stage, backend) observation-metrics so that each stage's cost is attributed to the backend(s) it actually used.
Source code in src/robotsix_cost_monitor/service/core.py
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | |
by_model(slug, hours)
async
Cost + token usage by model, merged across selected projects.
Window-accurate (see :meth:LangfuseClient.fetch_model_usage_window).
Source code in src/robotsix_cost_monitor/service/core.py
356 357 358 359 360 361 362 | |
components()
Return discovered projects grouped by owning component.
Insertion order follows the registry, so the dashboard's component list is stable across refreshes. Projects whose component is unknown are grouped under their own slug rather than dropped.
Source code in src/robotsix_cost_monitor/service/core.py
140 141 142 143 144 145 146 147 148 149 150 | |
highlights(slug, hours, backend='all')
async
Return dashboard highlights: top trace, session, and summary stats.
When backend is not "all", traces are filtered to only those
whose name appears in the agent-usage rows for that backend, keeping
the highlights consistent with the backend selector.
Source code in src/robotsix_cost_monitor/service/core.py
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 | |
invalidate_all()
Clear every internal cache so the next request fetches fresh data.
Source code in src/robotsix_cost_monitor/service/core.py
101 102 103 104 105 | |
projects()
Return every discovered project, in registry order.
Source code in src/robotsix_cost_monitor/service/core.py
136 137 138 | |
refresh_projects()
async
Query the registry and rebuild the project/client map.
Best-effort: on failure the existing project list is kept unchanged.
Source code in src/robotsix_cost_monitor/service/core.py
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 | |
summary(slug, hours, backend='all')
async
Per-project totals + the aggregate, for the window.
Cost is observation-based (the same window-accurate metrics source as the
by-model / by-backend breakdowns), so the headline total, the per-model
rows, and the per-backend totals all reconcile — a backend can never
exceed the total. trace_count comes from a server-side view=traces
count metric (not by paging every trace), so this stays fast.
When backend is not "all", only observation rows attributed to that
backend are counted, so the per-component rollup and total reflect costs
for the selected backend alone.
Source code in src/robotsix_cost_monitor/service/core.py
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 | |
trend(slug, hours, buckets=48)
async
Return a cost trend series across the window.
Source code in src/robotsix_cost_monitor/service/core.py
402 403 404 405 406 407 408 | |
ExternalServiceError
Bases: CostMonitorError, ExternalServiceError
An external API (Langfuse, OpenRouter) returned an error.
Transient failures (timeout, 5xx, 429) should be retried; terminal failures (401, 403, 404) should surface immediately.
Source code in src/robotsix_cost_monitor/exceptions.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 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 | |
__init__(detail='', *, status_code=None, response=None)
Initialise from a detail string, optionally with an HTTP response.
When response is None (constructed locally), a synthetic
:class:httpx.Response with the class-level status_code is
created to satisfy :class:ExternalHTTPError's required keyword
arguments.
Source code in src/robotsix_cost_monitor/exceptions.py
50 51 52 53 54 55 56 57 58 59 60 61 62 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 | |
LangfuseClient
Read-only cost/trace client for a single Langfuse project.
Composes :class:AsyncLangfuseReadClient for auth/URL helpers and
async REST transport; owns its own domain aggregation.
Source code in src/robotsix_cost_monitor/clients/langfuse.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | |
__init__(*, public_key, secret_key, base_url, timeout=30.0)
Initialise the Langfuse client with credentials and a timeout.
Source code in src/robotsix_cost_monitor/clients/langfuse.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | |
fetch_agent_usage_window(hours)
async
Per-(stage, backend) cost over the exact last hours.
Groups observations by trace name AND model, then maps each model to its
serving backend via :func:backend_for_model. Returns rows shaped
{"name": <stage>, "backend": <backend>, "cost": <float>,
"count": <int>} sorted by cost descending.
Observations with no model name carry no cost and are skipped. Uses the
same window-accurate metrics source as :meth:fetch_model_usage_window.
Source code in src/robotsix_cost_monitor/clients/langfuse.py
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 | |
fetch_backend_cost_window(hours)
async
{time_bucket -> {backend -> cost}} over the exact last hours.
Same metrics source as :meth:fetch_model_usage_window, bucketed over
time (granularity scaled to the window) and folded per backend (see
:func:backend_for_model) for the per-backend cost trend.
Source code in src/robotsix_cost_monitor/clients/langfuse.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | |
fetch_cost_by_backend(hours)
async
Total cost per serving backend over the exact last hours.
{backend -> cost} (e.g. {"openrouter": .., "claude-sdk": ..}).
Used by reconciliation to compare like-for-like: OpenRouter's per-key
spend only reconciles against the openrouter-backend traced cost —
Claude-SDK traffic is traced here but billed by Anthropic, not OpenRouter.
Source code in src/robotsix_cost_monitor/clients/langfuse.py
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | |
fetch_model_usage_window(hours)
async
Per-model cost + token usage over the exact last hours.
Window-accurate (see :meth:_metrics). Observations with no model
(non-generation spans) are skipped; they carry no cost.
Source code in src/robotsix_cost_monitor/clients/langfuse.py
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | |
fetch_trace_count_window(hours)
async
Count traces in the exact last hours via a server-side metrics query.
Uses view=traces, ungrouped count. One /api/public/metrics
request — O(1), vs paging every trace just to len() them (which is
~27s over a week of all-project data).
Source code in src/robotsix_cost_monitor/clients/langfuse.py
118 119 120 121 122 123 124 125 126 127 128 129 130 131 | |
fetch_traces_window(hours)
async
Return all traces with timestamp within the last hours.
hours may be fractional (reconciliation passes the exact snapshot
interval). Delegates to
:meth:AsyncLangfuseReadClient.fetch_traces_window.
Source code in src/robotsix_cost_monitor/clients/langfuse.py
57 58 59 60 61 62 63 64 65 66 67 | |
RegistryProject
Bases: BaseModel
One Langfuse project discovered from the central-deploy registry.
A project is a single LLM function, not a component: a component with
two tracing subsystems declares two projects (e.g. robotsix-chat and
robotsix-chat-cognee). :attr:component_id records which component
owns it, so the dashboard can roll a component's projects up without any
per-component code.
Source code in src/robotsix_cost_monitor/clients/models.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | |
Settings
Bases: BaseModel
Global dashboard settings — no per-project config (registry-driven).
Source code in src/robotsix_cost_monitor/config/__init__.py
52 53 54 55 56 57 58 59 60 61 62 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 178 179 180 181 182 183 184 | |
_atomic_write_text(path, text, root=None)
Write text to path atomically (temp file + fsync + os.replace).
A crash mid-write leaves the previous file content intact instead of a
truncated file. The temp file lives in the same directory so
os.replace stays on one filesystem (atomic on POSIX).
path must resolve inside root (default: its own parent directory);
otherwise ValueError is raised so a crafted slug such as ../x
cannot escape the state directory.
Source code in src/robotsix_cost_monitor/reconcile.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | |
_fetch_credits(api_key)
async
Fetch account-level credit balance from OpenRouter (informational).
Source code in src/robotsix_cost_monitor/reconcile.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
_fetch_or_error(label, transient, coro, result)
async
Await coro, catching transient and unexpected exceptions uniformly.
On failure, records result["error"] and returns None so the
caller can return the result dict immediately.
Source code in src/robotsix_cost_monitor/reconcile.py
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | |
_hours_between(a, b)
Source code in src/robotsix_cost_monitor/reconcile.py
92 93 | |
_last_path(settings=None)
Source code in src/robotsix_cost_monitor/reconcile.py
255 256 | |
_load_snapshot(slug, settings=None)
Source code in src/robotsix_cost_monitor/reconcile.py
76 77 78 79 | |
_save_snapshot(slug, cumulative, at, settings=None)
Source code in src/robotsix_cost_monitor/reconcile.py
82 83 84 85 86 87 88 89 | |
_snapshot_path(slug, settings=None)
Source code in src/robotsix_cost_monitor/reconcile.py
42 43 | |
_state_dir(settings=None)
Source code in src/robotsix_cost_monitor/reconcile.py
36 37 38 39 | |
data_dir(settings=None)
Resolve the runtime-state directory for persistence.
When settings is given, the settings.data_dir field is used (relative
paths are resolved against the repo root). Without settings the legacy
default .data relative to the repo root is returned for backward
compatibility.
Source code in src/robotsix_cost_monitor/config/__init__.py
225 226 227 228 229 230 231 232 233 234 235 236 237 238 | |
load_last_reconcile(settings=None)
Return the last stored reconcile result (for the banner); empty when none yet.
Source code in src/robotsix_cost_monitor/reconcile.py
302 303 304 305 306 307 | |
reconcile_all(config, service)
async
Reconcile every project, persist the result, and return it.
The stored last.json powers the dashboard's warning banner and the
/api/reconcile/last endpoint.
Source code in src/robotsix_cost_monitor/reconcile.py
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | |
reconcile_project(project, settings)
async
Reconcile one project's OpenRouter spend vs Langfuse traced cost.
Snapshots the key's cumulative usage and diffs against the previous snapshot; compares the provider delta to the Langfuse traced cost over the same interval. Returns a status dict (also includes the remaining balance). The snapshot is updated on every call.
Source code in src/robotsix_cost_monitor/reconcile.py
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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 | |
reconcile_status(results)
Overall status across per-project reconcile results.
warning if any configured project errored or drifted beyond tolerance;
pending while every configured project is still on its first snapshot;
ok otherwise. Unconfigured projects are ignored.
Source code in src/robotsix_cost_monitor/reconcile.py
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 | |
safe_load_json(path, default)
Load and parse path as JSON, returning default on any error.
Catches FileNotFoundError (via .exists() returning False),
json.JSONDecodeError, and most OSError subclasses during the
read. PermissionError raised by .exists() itself is NOT caught
— it propagates to the caller.
Source code in src/robotsix_cost_monitor/_utils.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
robotsix_cost_monitor.routes
HTTP route handlers (APIRouter).
All route handlers that were previously inline inside create_app now live
here, using FastAPI dependency injection to obtain Config and CostService
from app.state.
Exception handling and the /health, /health/live and /readyz probe
routes are provided by the shared :mod:robotsix_http.fastapi bootstrap and
wired up in :mod:.app.
BackendKind = Literal['openrouter', 'claude-sdk', 'all']
module-attribute
MAX_WINDOW_HOURS = 168
module-attribute
_CHAT_SKILL = '# robotsix-cost-monitor — Chat Agent Skill\n\n## Base URL\n\n```\nhttp://cost-monitor:8080\n```\n\n## Authentication\n\nHTTP Basic auth **may** be required (configured at deploy time — ask the\noperator for credentials). All endpoints return 401 when auth is enabled\nand no valid credentials are supplied. The probes (`/health`,\n`/health/live`, `/readyz`) are always exempt.\n\n## Read endpoints\n\nAll read endpoints accept an optional `?project=<scope>` query parameter\n(default `all`) and an optional `?hours=<n>` time window (see\n[Time window](#time-window) below).\n\n`<scope>` resolves at either level:\n\n- a **component id** (e.g. `chat`) — every Langfuse project that component\n owns, aggregated;\n- a **project slug** (e.g. `robotsix-chat-cognee`) — that one LLM function.\n\nA component owns one project per LLM function, so `chat` covers both\n`robotsix-chat` and `robotsix-chat-cognee`. Components and their projects\nare discovered from the central-deploy registry — anything with a Langfuse\nconfig is monitored automatically, so do not assume a fixed list; call\n`GET /api/components` to see what exists right now.\n\nAn unmatched `<scope>` (stale or mistyped slug) returns `404` with error\ncode `PROJECT_NOT_FOUND` — distinct from a valid-but-empty project and from\n`?project=all` which always returns `200`.\n\n## Time window\n\nEvery windowed endpoint accepts `?hours=<n>`, the number of hours of history\nto report on:\n\n- **Default (omitted or `hours=0`)** — the server\'s configured default\n window is used (currently **168 h** = 7 days).\n- **Ceiling** — the maximum accepted window is **168 h**. A request for\n `hours` **greater than 168** is *rejected*, not silently clamped: the\n response is `422` with error code `validation_error` and a field-level\n message naming the limit. `hours` below `0` is rejected the same way.\n- **Config-default clamping** — only the *server-side* default is clamped to\n the 168 h ceiling if an operator misconfigures it; a client-supplied value\n is always either honoured (0-168) or rejected.\n\nTo remove any ambiguity about which window was applied, every windowed\nresponse advertises the resolved value:\n\n- **`X-Effective-Hours`** response header — present on *all* windowed\n endpoints (including the list-shaped breakdowns and trends).\n- **`effective_hours`** JSON field — additionally included in the body of\n the object-shaped endpoints (`GET /api/summary`, `GET /api/highlights`).\n\nRead the effective window from either place rather than inferring it from\ntrend bucket sizes.\n\n### Pagination\n\nList-shaped endpoints (`GET /api/components`, `GET /api/projects`,\n`GET /api/by-agent`, `GET /api/by-model`) accept `?offset=` & `?limit=`.\n\n### Cost summaries\n\n| Endpoint | Description |\n|---|---|\n| `GET /api/summary` | Cost summary by project & component. Optional `?backend=`. |\n| `GET /api/components` | Components + owning projects. Paged `?offset=`/`?limit=`. |\n| `GET /api/projects` | Discovered projects. Paged `?offset=`/`?limit=`. |\n\n### Per-agent / per-model breakdowns\n\n| Endpoint | Description |\n|---|---|\n| `GET /api/by-agent` | By agent. Optional `?backend=`. Paged `?offset=`/`?limit=`. |\n| `GET /api/by-model` | By model. Paged `?offset=`/`?limit=`. |\n\n### Trends\n\n| Endpoint | Description |\n|---|---|\n| `GET /api/trend` | Cost trend series bucketed by time. Optional `?buckets=`. |\n| `GET /api/backend-trend` | Cost trend per backend. Optional `?backend=`. |\n\n### Highlights & reconciliation\n\n| Endpoint | Description |\n|---|---|\n| `GET /api/highlights` | Most expensive trace and session. Optional `?backend=`. |\n| `GET /api/reconcile` | Run reconciliation now (writes snapshots — see Safety). |\n| `GET /api/reconcile/last` | Most recent reconciliation result. |\n\n### Stuck tickets\n\n| Endpoint | Description |\n|---|---|\n| `GET /api/stuck-tickets` | Mill tickets stuck in non-terminal states. 503 = unknown. |\n\n`GET /api/stuck-tickets` queries the mill board live on every call. An\nempty list means no stuck tickets (or detection is disabled). A `503`\nmeans the mill board is unreachable: the stuck-ticket state is\n**unknown, not zero** — never report it as "no stuck tickets".\n\n### Health\n\n| Endpoint | Description |\n|---|---|\n| `GET /health` | Health check (`{"status": "ok"}`). Always unauthenticated. |\n| `GET /health/live` | Liveness probe (no dependency checks). Always unauthenticated. |\n| `GET /readyz` | Readiness probe (`projects`, `data_dir` checks); 503 if any fail. |\n\n## Safety\n\n**Mutating endpoints** — these change server state (invalidate caches,\npersist reconciliation snapshots, call the OpenRouter API). The chat\nagent MUST ask for explicit operator confirmation before calling any of\nthem:\n\n| Endpoint | What it does |\n|---|---|\n| `POST /api/refresh` | Invalidate all caches; next request fetches fresh data. |\n| `GET /api/reconcile` | Fetch OpenRouter usage; overwrite reconciliation snapshots. |\n\nEvery other read endpoint (`GET`) is safe and requires no confirmation.\nTo inspect reconciliation without side effects, use\n`GET /api/reconcile/last`.\n\nThere is no `POST /api/reconcile/run` endpoint; reconciliation runs on\nthe server\'s schedule or via `GET /api/reconcile` above.\n\n`GET /metrics` (Prometheus scrape) and the HTML pages (`/`, `/settings`)\nare operator/browser-facing and intentionally not part of this skill.\n'
module-attribute
_WEB = Path(__file__).resolve().parent.parent / 'web'
module-attribute
router = APIRouter()
module-attribute
Config
Bases: BaseModel
Top-level config: registry-driven project discovery + global settings.
Project credentials are discovered at runtime from the central-deploy registry — there is no hardcoded project list.
Source code in src/robotsix_cost_monitor/config/__init__.py
215 216 217 218 219 220 221 222 | |
CostService
Cross-project cost aggregation service with per-window TTL cache.
All five internal caches share a single :attr:last_updated timestamp
(the youngest refresh across all caches) so the dashboard can display
data freshness.
Source code in src/robotsix_cost_monitor/service/core.py
53 54 55 56 57 58 59 60 61 62 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 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 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 | |
last_updated
property
UTC datetime of the most recent cache refresh, or None when cold.
__init__(config, registry_client)
Initialise the service with config and a registry client.
Starts with an empty project/client map — call :meth:refresh_projects
during startup to populate from the registry.
Source code in src/robotsix_cost_monitor/service/core.py
61 62 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 | |
backend_trend(slug, hours, backend)
async
Return the cost trend for a backend, merged across selected projects.
Window-accurate; time-bucket granularity scales with the window.
Source code in src/robotsix_cost_monitor/service/core.py
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 | |
by_agent(slug, hours, backend='all')
async
Cost by trace name (stage/agent), merged across selected projects.
When backend is "all" (default), uses trace-level cost
(aggregate_by_name) — unchanged from the original behavior.
When a specific backend is selected, uses per-(stage, backend) observation-metrics so that each stage's cost is attributed to the backend(s) it actually used.
Source code in src/robotsix_cost_monitor/service/core.py
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | |
by_model(slug, hours)
async
Cost + token usage by model, merged across selected projects.
Window-accurate (see :meth:LangfuseClient.fetch_model_usage_window).
Source code in src/robotsix_cost_monitor/service/core.py
356 357 358 359 360 361 362 | |
components()
Return discovered projects grouped by owning component.
Insertion order follows the registry, so the dashboard's component list is stable across refreshes. Projects whose component is unknown are grouped under their own slug rather than dropped.
Source code in src/robotsix_cost_monitor/service/core.py
140 141 142 143 144 145 146 147 148 149 150 | |
highlights(slug, hours, backend='all')
async
Return dashboard highlights: top trace, session, and summary stats.
When backend is not "all", traces are filtered to only those
whose name appears in the agent-usage rows for that backend, keeping
the highlights consistent with the backend selector.
Source code in src/robotsix_cost_monitor/service/core.py
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 | |
invalidate_all()
Clear every internal cache so the next request fetches fresh data.
Source code in src/robotsix_cost_monitor/service/core.py
101 102 103 104 105 | |
projects()
Return every discovered project, in registry order.
Source code in src/robotsix_cost_monitor/service/core.py
136 137 138 | |
refresh_projects()
async
Query the registry and rebuild the project/client map.
Best-effort: on failure the existing project list is kept unchanged.
Source code in src/robotsix_cost_monitor/service/core.py
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 | |
summary(slug, hours, backend='all')
async
Per-project totals + the aggregate, for the window.
Cost is observation-based (the same window-accurate metrics source as the
by-model / by-backend breakdowns), so the headline total, the per-model
rows, and the per-backend totals all reconcile — a backend can never
exceed the total. trace_count comes from a server-side view=traces
count metric (not by paging every trace), so this stays fast.
When backend is not "all", only observation rows attributed to that
backend are counted, so the per-component rollup and total reflect costs
for the selected backend alone.
Source code in src/robotsix_cost_monitor/service/core.py
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 | |
trend(slug, hours, buckets=48)
async
Return a cost trend series across the window.
Source code in src/robotsix_cost_monitor/service/core.py
402 403 404 405 406 407 408 | |
MillAPIError
Bases: RuntimeError
The mill board API could not be queried (network or HTTP error).
Raised instead of returning an empty result so callers can tell a failed check apart from a successful check that found nothing. Callers must treat this as "unknown": preserve the last known stuck-ticket state rather than overwriting it with an empty list.
Source code in src/robotsix_cost_monitor/clients/mill.py
22 23 24 25 26 27 28 29 | |
MillClient
dataclass
HTTP client for the robotsix-mill board API.
Used by the stuck-ticket background loop to periodically query the
mill's GET /tickets endpoint and identify tickets that have been
in a non-terminal state longer than the configured threshold.
Source code in src/robotsix_cost_monitor/clients/mill.py
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 178 179 180 181 182 183 184 185 186 187 188 189 190 | |
base_url
property
Return the mill API base URL with trailing slash stripped.
__post_init__()
Initialise lazy HTTP client holder to None.
Source code in src/robotsix_cost_monitor/clients/mill.py
84 85 86 | |
close()
async
Release the underlying HTTP client.
Source code in src/robotsix_cost_monitor/clients/mill.py
186 187 188 189 190 | |
fetch_stuck_tickets()
async
Query the mill for tickets stuck in non-terminal states.
Calls GET /tickets (include_closed=false is the default,
so terminal states are already excluded). Each returned ticket
whose updated_at is older than the configured threshold is
flagged as stuck.
Returns an empty list when detection is disabled. Raises
:class:MillAPIError when the mill API is unreachable, returns
an error status, or returns an unexpected payload — the caller
must then keep the previous results instead of treating the
check as a clean empty result.
Source code in src/robotsix_cost_monitor/clients/mill.py
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 178 179 180 181 182 183 184 | |
ProjectWindow
Bases: NamedTuple
Resolved project slug and effective window hours for a request.
Source code in src/robotsix_cost_monitor/routes/__init__.py
50 51 52 53 54 | |
_paginate(items, offset, limit)
Wrap a full result set in a standard offset/limit pagination envelope.
Source code in src/robotsix_cost_monitor/routes/__init__.py
258 259 260 261 262 263 264 265 266 267 | |
_window(hours, config)
Resolve the effective window: fall back to the default, clamp to the max.
Source code in src/robotsix_cost_monitor/routes/__init__.py
64 65 66 | |
backend_trend(backend=Query('all'), pw=Depends(project_window), service=Depends(get_service))
async
GET /api/backend-trend — cost trend per backend for a project and window.
Source code in src/robotsix_cost_monitor/routes/__init__.py
370 371 372 373 374 375 376 377 | |
by_agent(backend=Query('all'), offset=Query(0, ge=0), limit=Query(100, ge=1, le=1000), pw=Depends(project_window), service=Depends(get_service))
async
GET /api/by-agent — cost breakdown by agent name (paginated).
Source code in src/robotsix_cost_monitor/routes/__init__.py
345 346 347 348 349 350 351 352 353 354 355 | |
by_model(offset=Query(0, ge=0), limit=Query(100, ge=1, le=1000), pw=Depends(project_window), service=Depends(get_service))
async
GET /api/by-model — cost breakdown by model (paginated).
Source code in src/robotsix_cost_monitor/routes/__init__.py
358 359 360 361 362 363 364 365 366 367 | |
chat_skill()
GET /chat-skill — robotsix-chat agent skill document (Markdown).
Source code in src/robotsix_cost_monitor/routes/__init__.py
252 253 254 255 | |
components(offset=Query(0, ge=0), limit=Query(100, ge=1, le=1000), service=Depends(get_service))
async
GET /api/components — components and the projects they own (paginated).
Drives the dashboard's selector. Everything here comes from registry discovery, so a newly onboarded component with a Langfuse config appears without any change to this service.
Source code in src/robotsix_cost_monitor/routes/__init__.py
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 | |
get_config(request)
Return the :class:Config stored on app.state during startup.
Source code in src/robotsix_cost_monitor/routes/__init__.py
35 36 37 | |
get_service(request)
Return the :class:CostService stored on app.state during startup.
Source code in src/robotsix_cost_monitor/routes/__init__.py
40 41 42 | |
highlights(backend=Query('all'), pw=Depends(project_window), service=Depends(get_service))
async
GET /api/highlights — most expensive trace and session for the window.
Accepts an optional backend query parameter to filter results to
a specific backend (e.g. openrouter). Defaults to all.
Source code in src/robotsix_cost_monitor/routes/__init__.py
390 391 392 393 394 395 396 397 398 399 400 401 402 403 | |
index()
GET / — serve the main dashboard HTML page.
Source code in src/robotsix_cost_monitor/routes/__init__.py
459 460 461 462 | |
load_last_reconcile(settings=None)
Return the last stored reconcile result (for the banner); empty when none yet.
Source code in src/robotsix_cost_monitor/reconcile.py
302 303 304 305 306 307 | |
project_window(response, project=Depends(resolve_project), hours=Depends(resolve_hours))
Composite dependency: validated project slug + resolved window hours.
Advertises the resolved window on every windowed endpoint via the
X-Effective-Hours response header, so a caller can always tell which
window was actually used — the requested value, the config default (when
hours is omitted), or the clamped ceiling — without inferring it from
the payload. Dict-shaped endpoints additionally echo it in-body as
effective_hours.
Source code in src/robotsix_cost_monitor/routes/__init__.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | |
projects(offset=Query(0, ge=0), limit=Query(100, ge=1, le=1000), service=Depends(get_service))
async
GET /api/projects — discovered projects with name and slug (paginated).
Source code in src/robotsix_cost_monitor/routes/__init__.py
270 271 272 273 274 275 276 277 278 279 280 281 | |
reconcile(project=Query('all'), cfg=Depends(get_config), service=Depends(get_service))
async
GET /api/reconcile — reconcile OpenRouter usage against Langfuse traced costs.
Source code in src/robotsix_cost_monitor/routes/__init__.py
406 407 408 409 410 411 412 413 414 415 416 417 | |
reconcile_all(config, service)
async
Reconcile every project, persist the result, and return it.
The stored last.json powers the dashboard's warning banner and the
/api/reconcile/last endpoint.
Source code in src/robotsix_cost_monitor/reconcile.py
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | |
reconcile_last(cfg=Depends(get_config))
GET /api/reconcile/last — return the most recent reconciliation result.
Source code in src/robotsix_cost_monitor/routes/__init__.py
420 421 422 423 | |
reconcile_project(project, settings)
async
Reconcile one project's OpenRouter spend vs Langfuse traced cost.
Snapshots the key's cumulative usage and diffs against the previous snapshot; compares the provider delta to the Langfuse traced cost over the same interval. Returns a status dict (also includes the remaining balance). The snapshot is updated on every call.
Source code in src/robotsix_cost_monitor/reconcile.py
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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 | |
refresh_cache(service=Depends(get_service))
async
POST /api/refresh — invalidate all caches and force a fresh fetch.
The next dashboard request will block on a fresh Langfuse fetch (cold start), then subsequent requests within the TTL will be served from cache with stale-while-revalidate background refresh.
Source code in src/robotsix_cost_monitor/routes/__init__.py
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 | |
resolve_hours(hours=Query(0, ge=0, le=MAX_WINDOW_HOURS), cfg=Depends(get_config))
Return hours (clamped to :data:MAX_WINDOW_HOURS), or the config default.
Source code in src/robotsix_cost_monitor/routes/__init__.py
76 77 78 79 80 | |
resolve_project(project=Query('all'), cfg=Depends(get_config))
Validate and return the project slug query parameter.
Source code in src/robotsix_cost_monitor/routes/__init__.py
69 70 71 72 73 | |
settings_page()
GET /settings — serve the settings page (shared config panel).
Source code in src/robotsix_cost_monitor/routes/__init__.py
465 466 467 468 | |
stuck_tickets(request)
async
GET /api/stuck-tickets — return tickets stuck in non-terminal states.
Fetches fresh results from the mill board on every call. Returns an empty list when stuck-ticket detection is disabled (no mill_base_url or stuck_ticket_threshold_hours = 0). Returns 503 when the mill board API is unreachable — the caller must not treat that as "no stuck tickets".
Source code in src/robotsix_cost_monitor/routes/__init__.py
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 | |
summary(backend=Query('all'), pw=Depends(project_window), service=Depends(get_service))
async
GET /api/summary — total cost and per-project totals for the window.
Source code in src/robotsix_cost_monitor/routes/__init__.py
313 314 315 316 317 318 319 320 321 322 323 324 325 | |
trend(buckets=Query(48, ge=1, le=200), pw=Depends(project_window), service=Depends(get_service))
async
GET /api/trend — cost trend series bucketed by time for a project and window.
Source code in src/robotsix_cost_monitor/routes/__init__.py
380 381 382 383 384 385 386 387 | |
robotsix_cost_monitor.service
Service layer: cross-project cost aggregation with a small TTL cache.
The implementation lives in :mod:robotsix_cost_monitor.service.core; this
package re-exports its public names so from robotsix_cost_monitor.service
import CostService keeps working.
DASHBOARD_WINDOW_PRESETS = (1, 6, 24, 168)
module-attribute
__all__ = ['DASHBOARD_WINDOW_PRESETS', 'CostService']
module-attribute
CostService
Cross-project cost aggregation service with per-window TTL cache.
All five internal caches share a single :attr:last_updated timestamp
(the youngest refresh across all caches) so the dashboard can display
data freshness.
Source code in src/robotsix_cost_monitor/service/core.py
53 54 55 56 57 58 59 60 61 62 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 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 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 | |
last_updated
property
UTC datetime of the most recent cache refresh, or None when cold.
__init__(config, registry_client)
Initialise the service with config and a registry client.
Starts with an empty project/client map — call :meth:refresh_projects
during startup to populate from the registry.
Source code in src/robotsix_cost_monitor/service/core.py
61 62 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 | |
backend_trend(slug, hours, backend)
async
Return the cost trend for a backend, merged across selected projects.
Window-accurate; time-bucket granularity scales with the window.
Source code in src/robotsix_cost_monitor/service/core.py
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 | |
by_agent(slug, hours, backend='all')
async
Cost by trace name (stage/agent), merged across selected projects.
When backend is "all" (default), uses trace-level cost
(aggregate_by_name) — unchanged from the original behavior.
When a specific backend is selected, uses per-(stage, backend) observation-metrics so that each stage's cost is attributed to the backend(s) it actually used.
Source code in src/robotsix_cost_monitor/service/core.py
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | |
by_model(slug, hours)
async
Cost + token usage by model, merged across selected projects.
Window-accurate (see :meth:LangfuseClient.fetch_model_usage_window).
Source code in src/robotsix_cost_monitor/service/core.py
356 357 358 359 360 361 362 | |
components()
Return discovered projects grouped by owning component.
Insertion order follows the registry, so the dashboard's component list is stable across refreshes. Projects whose component is unknown are grouped under their own slug rather than dropped.
Source code in src/robotsix_cost_monitor/service/core.py
140 141 142 143 144 145 146 147 148 149 150 | |
highlights(slug, hours, backend='all')
async
Return dashboard highlights: top trace, session, and summary stats.
When backend is not "all", traces are filtered to only those
whose name appears in the agent-usage rows for that backend, keeping
the highlights consistent with the backend selector.
Source code in src/robotsix_cost_monitor/service/core.py
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 | |
invalidate_all()
Clear every internal cache so the next request fetches fresh data.
Source code in src/robotsix_cost_monitor/service/core.py
101 102 103 104 105 | |
projects()
Return every discovered project, in registry order.
Source code in src/robotsix_cost_monitor/service/core.py
136 137 138 | |
refresh_projects()
async
Query the registry and rebuild the project/client map.
Best-effort: on failure the existing project list is kept unchanged.
Source code in src/robotsix_cost_monitor/service/core.py
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 | |
summary(slug, hours, backend='all')
async
Per-project totals + the aggregate, for the window.
Cost is observation-based (the same window-accurate metrics source as the
by-model / by-backend breakdowns), so the headline total, the per-model
rows, and the per-backend totals all reconcile — a backend can never
exceed the total. trace_count comes from a server-side view=traces
count metric (not by paging every trace), so this stays fast.
When backend is not "all", only observation rows attributed to that
backend are counted, so the per-component rollup and total reflect costs
for the selected backend alone.
Source code in src/robotsix_cost_monitor/service/core.py
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 | |
trend(slug, hours, buckets=48)
async
Return a cost trend series across the window.
Source code in src/robotsix_cost_monitor/service/core.py
402 403 404 405 406 407 408 | |