Spaces:
Running

File size: 11,281 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
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
"""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)


@dataclass(frozen=True)
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]]


@dataclass
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)


@dataclass(frozen=True)
class ModelTiers:
    router: LLM  # cheap: classification
    worker: LLM  # mid: extraction, drafting
    planner: LLM  # frontier: multi-step plans

    @classmethod
    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),
        )

    @classmethod
    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"),
        )