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
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
"""Model backends.

Every backend implements `complete(prompt) -> str`. The harness treats a raised
exception as a failed case rather than aborting the run, so a single flaky
response cannot destroy a multi-hour evaluation.
"""

from __future__ import annotations

import json
import urllib.error
import urllib.request
from dataclasses import dataclass
from typing import Any, Mapping, Sequence

from .prompts import render_call
from .schema import Case, ExpectCall, ExpectNoCall, Protocol


@dataclass(frozen=True)
class Prompt:
    case: Case
    protocol: Protocol
    messages: tuple[Mapping[str, str], ...]


class Runner:
    name: str = "runner"

    def complete(self, prompt: Prompt) -> str:  # pragma: no cover - interface
        raise NotImplementedError

    def complete_many(self, prompts: Sequence[Prompt]) -> list[str]:
        """Default: sequential. Backends that can batch override this."""
        return [self.complete(prompt) for prompt in prompts]


@dataclass(frozen=True)
class BatchOutput:
    text: str | None = None
    error: str = ""


def run_batch(runner: Runner, prompts: Sequence[Prompt], batch_size: int) -> list[BatchOutput]:
    """Run a chunk, degrading to one-by-one if the backend refuses the batch."""
    if batch_size > 1:
        try:
            return [BatchOutput(text=text) for text in runner.complete_many(prompts)]
        except Exception:  # noqa: BLE001 - a poisoned batch must not lose its neighbours
            pass
    outputs: list[BatchOutput] = []
    for prompt in prompts:
        try:
            outputs.append(BatchOutput(text=runner.complete(prompt)))
        except Exception as error:  # noqa: BLE001
            outputs.append(BatchOutput(error=f"runner error: {type(error).__name__}: {error}"))
    return outputs


class OracleRunner(Runner):
    """Emits exactly what the corpus expects. Used to validate the grader itself."""

    name = "oracle"

    def complete(self, prompt: Prompt) -> str:
        expect = prompt.case.expect
        if isinstance(expect, ExpectCall):
            return render_call(expect.name, expect.args, prompt.protocol)
        needles: list[str] = list(expect.answer_contains_all)
        needles.extend(group[0] for group in expect.answer_contains_any if group)
        if needles:
            return "Here is the answer: " + ", ".join(needles) + "."
        return "I can answer that from what I already know."


class NullRunner(Runner):
    """Answers politely and never calls a tool."""

    name = "null"

    def complete(self, prompt: Prompt) -> str:
        return "I am not sure about that."


class FencedRunner(OracleRunner):
    """Wraps every call in a markdown fence behind a sentence of prose."""

    name = "fenced"

    def complete(self, prompt: Prompt) -> str:
        raw = super().complete(prompt)
        if isinstance(prompt.case.expect, ExpectCall):
            fence = "json" if prompt.protocol == "json" else "text"
            return f"Sure, calling the tool now.\n\n```{fence}\n{raw}\n```\n"
        return raw


class ThinkingRunner(OracleRunner):
    """Prefixes every call with a reasoning block, the way a thinking model does."""

    name = "thinking"

    def complete(self, prompt: Prompt) -> str:
        raw = super().complete(prompt)
        if isinstance(prompt.case.expect, ExpectCall):
            return f"<thinking>\nThe user wants a tool call. Pick {prompt.case.expect.name}.\n</thinking>\n{raw}"
        return f"<thinking>No tool applies here.</thinking>\n{raw}"


class ScriptedRunner(Runner):
    """Deterministic per-case overrides, for unit tests and demos."""

    name = "scripted"

    def __init__(self, overrides: Mapping[str, str], default: str = ""):
        self._overrides = dict(overrides)
        self._default = default

    def complete(self, prompt: Prompt) -> str:
        return self._overrides.get(prompt.case.id, self._default)


class OpenAICompatibleRunner(Runner):
    """Any `/chat/completions` endpoint: vLLM, llama.cpp server, Ollama, OpenAI, OpenRouter."""

    def __init__(
        self,
        model: str,
        base_url: str = "https://api.openai.com/v1",
        api_key: str = "",
        max_tokens: int = 256,
        temperature: float = 0.0,
        timeout: float = 120.0,
        name: str | None = None,
    ):
        self.model = model
        self.base_url = base_url.rstrip("/")
        self.api_key = api_key
        self.max_tokens = max_tokens
        self.temperature = temperature
        self.timeout = timeout
        self.name = name or model

    def complete(self, prompt: Prompt) -> str:
        body = json.dumps(
            {
                "model": self.model,
                "messages": [dict(message) for message in prompt.messages],
                "max_tokens": self.max_tokens,
                "temperature": self.temperature,
                "stream": False,
            }
        ).encode("utf-8")
        request = urllib.request.Request(
            f"{self.base_url}/chat/completions",
            data=body,
            method="POST",
            headers={
                "Content-Type": "application/json",
                **({"Authorization": f"Bearer {self.api_key}"} if self.api_key else {}),
            },
        )
        try:
            with urllib.request.urlopen(request, timeout=self.timeout) as response:
                payload = json.loads(response.read().decode("utf-8"))
        except urllib.error.HTTPError as error:
            detail = error.read().decode("utf-8", "replace")[:400]
            raise RuntimeError(f"HTTP {error.code}: {detail}") from error
        choices = payload.get("choices") or []
        if not choices:
            return ""
        message = choices[0].get("message") or {}
        content = message.get("content")
        if isinstance(content, list):
            return "".join(part.get("text", "") for part in content if isinstance(part, Mapping))
        return content or message.get("reasoning_content") or ""


class TransformersRunner(Runner):
    """Local HF checkpoint, greedy decoding.

    Handles three realities of modern checkpoints: vision-capable conditional
    generation architectures (`AutoModelForImageTextToText`), the `dtype` rename,
    and chat templates with a reasoning switch that must be turned off for tool
    calls to be emitted instead of a thinking trace.
    """

    def __init__(
        self,
        model_id: str,
        max_new_tokens: int = 256,
        dtype: str = "auto",
        device_map: str = "auto",
        trust_remote_code: bool = True,
        revision: str | None = None,
        system_override: str | None = None,
        disable_thinking: bool = True,
    ):
        import torch

        self._torch = torch
        self.name = model_id
        self.model_id = model_id
        self.max_new_tokens = max_new_tokens
        self.system_override = system_override
        self.disable_thinking = disable_thinking
        self.tokenizer = _load_processor(model_id, trust_remote_code, revision)
        if getattr(self.tokenizer, "pad_token", None) is None:
            self.tokenizer.pad_token = self.tokenizer.eos_token
        self.model, self.load_info = _load_model(model_id, dtype, device_map, trust_remote_code, revision)
        self.model.eval()
        self._eos_ids = _end_of_turn_ids(self.model, self.tokenizer)

    def _render(self, messages: Sequence[Mapping[str, str]]) -> str:
        kwargs: dict[str, Any] = {"tokenize": False, "add_generation_prompt": True}
        if self.disable_thinking:
            kwargs["enable_thinking"] = False
        try:
            return self.tokenizer.apply_chat_template(messages, **kwargs)
        except TypeError:
            kwargs.pop("enable_thinking", None)
            return self.tokenizer.apply_chat_template(messages, **kwargs)

    def _prepare(self, prompt: Prompt) -> str:
        messages = [dict(message) for message in prompt.messages]
        if self.system_override and messages and messages[0]["role"] == "system":
            messages[0]["content"] = self.system_override
        return self._render(messages)

    def _inputs(self, texts: Sequence[str], padding: bool) -> dict[str, Any]:
        previous_side = getattr(self.tokenizer, "padding_side", "right")
        if padding:
            # Decoder-only generation must continue after the padded prefix, so the
            # padding belongs on the left; the slice below then trims uniformly.
            self.tokenizer.padding_side = "left"
        try:
            try:
                inputs = self.tokenizer(text=list(texts), return_tensors="pt", padding=padding)
            except TypeError:
                inputs = self.tokenizer(list(texts), return_tensors="pt", padding=padding)
        finally:
            self.tokenizer.padding_side = previous_side
        if hasattr(inputs, "to"):
            inputs = inputs.to(self.model.device)
        return {key: value for key, value in dict(inputs).items()}

    def _generate(self, inputs: dict[str, Any]) -> list[str]:
        input_length = inputs["input_ids"].shape[-1]
        with self._torch.inference_mode():
            generated = self.model.generate(
                **inputs,
                max_new_tokens=self.max_new_tokens,
                do_sample=False,
                pad_token_id=self.tokenizer.pad_token_id or self.tokenizer.eos_token_id,
                eos_token_id=self._eos_ids,
            )
        return [self.tokenizer.decode(row[input_length:], skip_special_tokens=True) for row in generated]

    def complete(self, prompt: Prompt) -> str:
        return self._generate(self._inputs([self._prepare(prompt)], padding=False))[0]

    def complete_many(self, prompts: Sequence[Prompt]) -> list[str]:
        """One padded `generate` call per batch.

        Memory is not the constraint here — a 0.8B model in bfloat16 leaves several
        gigabytes free on a 6 GB card — GPU *utilisation* is. Batching turns a decode
        loop that idles between kernel launches into a saturated one.
        """
        if not prompts:
            return []
        if len(prompts) == 1:
            return self.complete(prompts[0])
        return self._generate(self._inputs([self._prepare(prompt) for prompt in prompts], padding=True))


def _load_processor(model_id: str, trust_remote_code: bool, revision: str | None):
    from transformers import AutoProcessor, AutoTokenizer

    errors: list[str] = []
    for loader in (AutoTokenizer, AutoProcessor):
        try:
            return loader.from_pretrained(model_id, trust_remote_code=trust_remote_code, revision=revision)
        except Exception as error:  # noqa: BLE001
            errors.append(f"{loader.__name__}: {type(error).__name__}: {error}")
    raise RuntimeError("could not load a tokenizer/processor for " + model_id + "\n" + "\n".join(errors))


LOAD_CANDIDATES: tuple[str, ...] = ("AutoModelForCausalLM", "AutoModelForImageTextToText", "AutoModel")

_IGNORABLE_MISSING: tuple[str, ...] = (
    "inv_freq",
    "rotary",
    "causal_mask",
    "position_ids",
    "mtp.",
    "logit_scale",
    "temperature",
)


def _core_missing(missing: Sequence[str]) -> list[str]:
    return [key for key in missing if not any(token in key for token in _IGNORABLE_MISSING)]


def _end_of_turn_ids(model: Any, tokenizer: Any) -> list[int]:
    """Every token that legitimately ends an assistant turn.

    Chat checkpoints ship two of them: `<|im_end|>` closes the message, while the
    model configuration frequently keeps a pre-training `<|endoftext|>` as the
    single `eos_token_id`. Stopping on only one of the two makes an otherwise
    correct answer run to `max_new_tokens` and emit the same call over and over,
    which the grader then scores as several calls in one turn. The union is what
    the template actually means, so that is what decoding stops on.
    """
    ids: set[int] = set()
    for source in (
        getattr(tokenizer, "eos_token_id", None),
        getattr(getattr(model, "generation_config", None), "eos_token_id", None),
        getattr(getattr(model, "config", None), "eos_token_id", None),
    ):
        if isinstance(source, int):
            ids.add(source)
        elif isinstance(source, (list, tuple)):
            ids.update(int(value) for value in source if isinstance(value, int))
    return sorted(ids)


def _load_model(
    model_id: str,
    dtype: str,
    device_map: str,
    trust_remote_code: bool,
    revision: str | None,
):
    """Load the first architecture whose weights actually match the checkpoint.

    `from_pretrained` emits a warning, not an error, when a class expects keys the
    checkpoint does not contain — the result is a randomly initialised model that still
    produces fluent-looking text. Nova ships text-only keys (`model.layers.*`) and also
    carries a vision tower, so the vision wrapper loads "successfully" and generates
    noise. Every candidate is therefore verified against its loading report before it is
    accepted, and the caller is told how it was loaded.
    """
    import transformers

    errors: list[str] = []
    for name in LOAD_CANDIDATES:
        loader = getattr(transformers, name, None)
        if loader is None:
            continue
        for dtype_kwarg in ("dtype", "torch_dtype"):
            try:
                model, info = loader.from_pretrained(
                    model_id,
                    trust_remote_code=trust_remote_code,
                    revision=revision,
                    device_map=device_map,
                    output_loading_info=True,
                    **{dtype_kwarg: dtype},
                )
            except Exception as error:  # noqa: BLE001
                errors.append(f"{name}.{dtype_kwarg}: {type(error).__name__}: {error}")
                continue
            missing = _core_missing(list(info.get("missing_keys") or []))
            if missing:
                errors.append(
                    f"{name}: {len(missing)} checkpoint weights missing, e.g. {missing[0]} — refusing a random model"
                )
                del model
                continue
            unexpected = len(list(info.get("unexpected_keys") or []))
            note = f"{name} ({dtype_kwarg}={dtype})" + (f", {unexpected} extra keys ignored" if unexpected else "")
            return model, note
    raise RuntimeError("could not load " + model_id + ":\n" + "\n".join(errors))


class ScriptedFileRunner(ScriptedRunner):
    """Loads `{"case_id": "output"}` from a JSON file — hand-graded runs, ablations."""

    @staticmethod
    def from_file(path: str, default: str = "") -> "ScriptedFileRunner":
        with open(path, encoding="utf-8") as handle:
            payload: dict[str, Any] = json.load(handle)
        return ScriptedFileRunner({str(key): str(value) for key, value in payload.items()}, default=default)


def build_runner(backend: str, **kwargs: Any) -> Runner:
    if backend == "oracle":
        return OracleRunner()
    if backend == "null":
        return NullRunner()
    if backend == "fenced":
        return FencedRunner()
    if backend == "thinking":
        return ThinkingRunner()
    if backend in ("transformers", "local"):
        return TransformersRunner(
            model_id=kwargs["model"],
            max_new_tokens=kwargs.get("max_new_tokens", 256),
            dtype=kwargs.get("dtype", "auto"),
            revision=kwargs.get("revision"),
            disable_thinking=kwargs.get("disable_thinking", True),
        )
    if backend in ("openai", "vllm", "ollama", "llamacpp"):
        return OpenAICompatibleRunner(
            model=kwargs["model"],
            base_url=kwargs.get("base_url", "http://localhost:8000/v1"),
            api_key=kwargs.get("api_key", ""),
            max_tokens=kwargs.get("max_new_tokens", 256),
        )
    if backend == "scripted":
        return ScriptedFileRunner.from_file(kwargs["scripted_file"])
    raise ValueError(f"unknown backend: {backend}")


def rendered_calls(expect: Any, protocol: Protocol) -> Sequence[str]:
    if isinstance(expect, ExpectCall):
        return (render_call(expect.name, expect.args, protocol),)
    if isinstance(expect, ExpectNoCall):
        return ()
    return ()