Spaces:
Running
Running
Download core/observability/context.py from Aynkhn/WorkPilot-AI: direct link, hf CLI and curl.
- Browser
- Download file 2.13 kB
-
https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/observability/context.py
- Command line
-
hf download hf://spaces/Aynkhn/WorkPilot-AI/core/observability/context.py
-
curl -L -o context.py https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/observability/context.py
2.13 kB
| """The current run, as a context variable (Phase 15). | |
| ``AgentRuntime`` sets a ``RunContext`` around every graph invocation. Everything below it in | |
| the same asyncio task tree (graph nodes, the quarantine extractor, LLM wrappers) can then | |
| attribute work to the run without threading ids through every signature: | |
| * LLM spans and token costs (``core.agent.models.InstrumentedLLM``); | |
| * the tenant's non-secret config snapshot (time zone, safety profile) for prompts | |
| (ADR-0009 G5/G6). | |
| Outside a run (API helpers, NL rule compilation) ``current_run()`` is None and callers fall | |
| back to their defaults. | |
| """ | |
| from __future__ import annotations | |
| import uuid | |
| from collections.abc import Awaitable, Callable, Iterator, Mapping | |
| from contextlib import contextmanager | |
| from contextvars import ContextVar | |
| from dataclasses import dataclass, field | |
| from typing import Any | |
| CostSink = Callable[[uuid.UUID, uuid.UUID, float], Awaitable[None]] | |
| class RunContext: | |
| tenant_id: uuid.UUID | |
| run_id: uuid.UUID | |
| thread_id: str | |
| tenant_config: Mapping[str, Any] = field(default_factory=dict) | |
| # Persists a cost increment (tenant, run, usd); set by the runtime. None: count only. | |
| cost_sink: CostSink | None = None | |
| cost_usd: float = 0.0 # LLM cost attributed in this process during this invocation | |
| input_tokens: int = 0 | |
| output_tokens: int = 0 | |
| llm_calls: int = 0 | |
| async def add_usage(self, input_tokens: int, output_tokens: int, usd: float) -> None: | |
| self.llm_calls += 1 | |
| self.input_tokens += input_tokens | |
| self.output_tokens += output_tokens | |
| self.cost_usd += usd | |
| if usd > 0 and self.cost_sink is not None: | |
| await self.cost_sink(self.tenant_id, self.run_id, usd) | |
| _current: ContextVar[RunContext | None] = ContextVar("workpilot_run", default=None) | |
| def current_run() -> RunContext | None: | |
| return _current.get() | |
| def run_context(ctx: RunContext) -> Iterator[RunContext]: | |
| token = _current.set(ctx) | |
| try: | |
| yield ctx | |
| finally: | |
| _current.reset(token) | |