Spaces:
Running
Running
Download core/agent/models.py from Aynkhn/WorkPilot-AI: direct link, hf CLI and curl.
- Browser
- Download file 11.3 kB
-
https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/agent/models.py
- Command line
-
hf download hf://spaces/Aynkhn/WorkPilot-AI/core/agent/models.py
-
curl -L -o models.py https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/agent/models.py
11.3 kB
| """Model tiers behind a small interface: structured output only. | |
| Agents never get free-form tool access from the model. Models return validated Pydantic | |
| objects; code decides what to call. Static instructions go first in every request so | |
| provider prompt caching applies. | |
| """ | |
| from __future__ import annotations | |
| import inspect | |
| from collections.abc import Awaitable, Callable, Sequence | |
| from contextvars import ContextVar | |
| from dataclasses import dataclass, field, replace | |
| from typing import Any, Protocol, TypeVar | |
| from pydantic import BaseModel | |
| T = TypeVar("T", bound=BaseModel) | |
| class LLM(Protocol): | |
| name: str | |
| async def structured(self, schema: type[T], system: str, user: str) -> T: ... | |
| # --------------------------------------------------------------- usage + tracing (Phase 15) | |
| class Usage: | |
| model: str | |
| input_tokens: int | |
| output_tokens: int | |
| _usage_sink: ContextVar[list[Usage] | None] = ContextVar("workpilot_llm_usage", default=None) | |
| def report_usage(model: str, input_tokens: int, output_tokens: int) -> None: | |
| """Called by LLM implementations after a call; collected by ``InstrumentedLLM``.""" | |
| sink = _usage_sink.get() | |
| if sink is not None: | |
| sink.append(Usage(model, int(input_tokens or 0), int(output_tokens or 0))) | |
| class DailyLimitReached(RuntimeError): | |
| """The tenant used up ``max_llm_calls_per_tenant_per_day`` for today (UTC).""" | |
| _daily_calls: dict[tuple[str, str], int] = {} | |
| def _check_daily_limit() -> None: | |
| """Public-demo guard (``WP_MAX_LLM_CALLS_PER_TENANT_PER_DAY``, 0 = off): stop one tenant | |
| spending the operator's model credits without bound. Counted per process, so a split | |
| api + worker deployment allows up to twice the limit; a single-process demo is exact.""" | |
| from datetime import UTC, datetime | |
| from core.config import get_settings | |
| from core.observability.context import current_run | |
| limit = get_settings().max_llm_calls_per_tenant_per_day | |
| run = current_run() | |
| if limit <= 0 or run is None: | |
| return | |
| key = (str(run.tenant_id), datetime.now(UTC).date().isoformat()) | |
| if _daily_calls.get(key, 0) >= limit: | |
| raise DailyLimitReached( | |
| f"daily model-call limit reached ({limit}); try again tomorrow (UTC)" | |
| ) | |
| if len(_daily_calls) > 10_000: # old days: drop them | |
| today = key[1] | |
| for k in [k for k in _daily_calls if k[1] != today]: | |
| del _daily_calls[k] | |
| _daily_calls[key] = _daily_calls.get(key, 0) + 1 | |
| class InstrumentedLLM: | |
| """Wraps any ``LLM``: one ``chat <model>`` span per call with GenAI attributes, and the | |
| token cost added to the current run (``core.observability.context``), which feeds | |
| ``runs.cost_usd`` and the gateway's cost circuit breaker. Other attributes (e.g. a | |
| ScriptedLLM's ``calls``) are delegated to the wrapped model.""" | |
| def __init__(self, inner: LLM, tier: str | None = None) -> None: | |
| self.inner = inner | |
| self.name = inner.name | |
| self.tier = tier | |
| def __getattr__(self, item: str) -> Any: | |
| if item == "inner": # not yet set (copy/pickle): avoid infinite recursion | |
| raise AttributeError(item) | |
| return getattr(self.inner, item) | |
| async def structured(self, schema: type[T], system: str, user: str) -> T: | |
| from core.observability import tracing | |
| from core.observability.context import current_run | |
| from core.observability.costs import cost_usd | |
| _check_daily_limit() | |
| token = _usage_sink.set([]) | |
| try: | |
| with tracing.llm_span(self.name, schema.__name__, self.tier) as span: | |
| try: | |
| result = await self.inner.structured(schema, system, user) | |
| finally: | |
| usages = _usage_sink.get() or [] | |
| in_tok = sum(u.input_tokens for u in usages) | |
| out_tok = sum(u.output_tokens for u in usages) | |
| usd = sum(cost_usd(u.model, u.input_tokens, u.output_tokens) for u in usages) | |
| tracing.set_attrs( | |
| span, | |
| { | |
| "gen_ai.response.model": usages[-1].model if usages else None, | |
| "gen_ai.usage.input_tokens": in_tok, | |
| "gen_ai.usage.output_tokens": out_tok, | |
| "workpilot.cost_usd": usd, | |
| }, | |
| ) | |
| run = current_run() | |
| if run is not None: | |
| tracing.set_attrs( | |
| span, | |
| { | |
| "workpilot.tenant_id": str(run.tenant_id), | |
| "workpilot.run_id": str(run.run_id), | |
| }, | |
| ) | |
| await run.add_usage(in_tok, out_tok, usd) | |
| return result | |
| finally: | |
| _usage_sink.reset(token) | |
| def instrument(llm: LLM, tier: str | None = None) -> LLM: | |
| return llm if isinstance(llm, InstrumentedLLM) else InstrumentedLLM(llm, tier) | |
| # Providers the ``llm`` extra installs: init_chat_model prefix -> (package, API key env var). | |
| PROVIDERS: dict[str, tuple[str, str]] = { | |
| "anthropic": ("langchain-anthropic", "ANTHROPIC_API_KEY"), | |
| "openai": ("langchain-openai", "OPENAI_API_KEY"), | |
| "google_genai": ("langchain-google-genai", "GOOGLE_API_KEY"), | |
| "groq": ("langchain-groq", "GROQ_API_KEY"), | |
| } | |
| def provider_problem(model: str) -> str | None: | |
| """Why ``model`` cannot run here (unknown provider prefix or missing API key), or None. | |
| Other LangChain providers are allowed but not checked.""" | |
| import os | |
| provider, sep, name = model.partition(":") | |
| if not sep or not name: | |
| return None # no prefix: LangChain infers the provider from the model name | |
| known = PROVIDERS.get(provider) | |
| if known is None: | |
| return None | |
| package, key = known | |
| if not os.environ.get(key): | |
| return f"model {model!r} needs {key} (and the {package} package: pip install -e .[llm])" | |
| return None | |
| class LangChainLLM: | |
| """Any ``init_chat_model`` string with fallbacks, e.g. "anthropic:claude-sonnet-5-5", | |
| "google_genai:<gemini model>" or "groq:<model>" (see ``PROVIDERS``).""" | |
| def __init__(self, model: str, fallbacks: Sequence[str] = ()) -> None: | |
| self.name = model | |
| self._model = model | |
| self._fallbacks = list(fallbacks) | |
| async def structured(self, schema: type[T], system: str, user: str) -> T: | |
| from langchain.chat_models import init_chat_model | |
| if (problem := provider_problem(self._model)) is not None: | |
| raise RuntimeError(problem) | |
| # include_raw: keep the AIMessage so token usage reaches cost accounting (Phase 15). | |
| try: | |
| primary = init_chat_model(self._model, temperature=0).with_structured_output( | |
| schema, include_raw=True | |
| ) | |
| except ImportError as exc: # provider package not installed | |
| provider = self._model.partition(":")[0] | |
| package = PROVIDERS.get(provider, (f"langchain-{provider}", ""))[0] | |
| raise RuntimeError( | |
| f"model {self._model!r} needs the {package} package: pip install -e .[llm]" | |
| ) from exc | |
| runnable: Any = primary | |
| if self._fallbacks: | |
| runnable = primary.with_fallbacks( | |
| [ | |
| init_chat_model(m, temperature=0).with_structured_output( | |
| schema, include_raw=True | |
| ) | |
| for m in self._fallbacks | |
| ] | |
| ) | |
| out = await runnable.ainvoke([("system", system), ("user", user)]) | |
| raw = out.get("raw") if isinstance(out, dict) else None | |
| usage = getattr(raw, "usage_metadata", None) or {} | |
| meta = getattr(raw, "response_metadata", None) or {} | |
| report_usage( | |
| str(meta.get("model_name") or meta.get("model") or self._model), | |
| int(usage.get("input_tokens", 0)), | |
| int(usage.get("output_tokens", 0)), | |
| ) | |
| if isinstance(out, dict) and "parsed" in out: | |
| if out.get("parsing_error") is not None or out.get("parsed") is None: | |
| raise ValueError(f"structured output did not parse: {out.get('parsing_error')}") | |
| return schema.model_validate(out["parsed"]) | |
| return schema.model_validate(out) | |
| Responder = Callable[[type[BaseModel], str, str], BaseModel | dict | Awaitable[BaseModel | dict]] | |
| class ScriptedLLM: | |
| """Deterministic test/eval double. ``responses`` maps schema name -> dict, a list of dicts | |
| (consumed in order), or a callable(schema, system, user).""" | |
| name: str = "scripted" | |
| responses: dict[str, Any] = field(default_factory=dict) | |
| calls: list[tuple[str, str]] = field(default_factory=list) | |
| # Phase 15: synthetic token usage reported per call, (input, output) for every schema | |
| # or {schema name: (input, output)}; priced like a real model (see costs.DEFAULT_PRICES). | |
| usage: tuple[int, int] | dict[str, tuple[int, int]] | None = None | |
| async def structured(self, schema: type[T], system: str, user: str) -> T: | |
| self.calls.append((schema.__name__, user)) | |
| spec = self.responses.get(schema.__name__) | |
| if spec is None: | |
| raise LookupError(f"ScriptedLLM has no response for {schema.__name__}") | |
| if isinstance(spec, list): | |
| if not spec: | |
| raise LookupError(f"ScriptedLLM ran out of responses for {schema.__name__}") | |
| value = spec.pop(0) | |
| elif callable(spec): | |
| value = spec(schema, system, user) | |
| if inspect.isawaitable(value): | |
| value = await value | |
| else: | |
| value = spec | |
| usage = self.usage.get(schema.__name__) if isinstance(self.usage, dict) else self.usage | |
| if usage is not None: | |
| report_usage(self.name, usage[0], usage[1]) | |
| return schema.model_validate(value) | |
| class ModelTiers: | |
| router: LLM # cheap: classification | |
| worker: LLM # mid: extraction, drafting | |
| planner: LLM # frontier: multi-step plans | |
| def from_settings(cls) -> ModelTiers: | |
| from core.config import get_settings | |
| s = get_settings() | |
| return cls( | |
| router=LangChainLLM(s.model_router, s.model_fallbacks), | |
| worker=LangChainLLM(s.model_worker, s.model_fallbacks), | |
| planner=LangChainLLM(s.model_planner, s.model_fallbacks), | |
| ) | |
| def single(cls, llm: LLM) -> ModelTiers: | |
| return cls(router=llm, worker=llm, planner=llm) | |
| def instrumented(self) -> ModelTiers: | |
| """Every tier wrapped in ``InstrumentedLLM`` (spans + cost); idempotent.""" | |
| return replace( | |
| self, | |
| router=instrument(self.router, "router"), | |
| worker=instrument(self.worker, "worker"), | |
| planner=instrument(self.planner, "planner"), | |
| ) | |