File size: 23,391 Bytes
03815d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
"""Frontier LLM baseline runner against `chakravyuh-bench-v0`.

Runs LLM analyzers through the EXACT SAME AnalyzerProtocol the Mode C runner
uses. Produces a comparison CSV + bootstrap 95% CIs + pairwise permutation
tests.

Five provider backends (paid ones skip gracefully if the API key is missing):

  - **OpenAI** — proprietary frontier (GPT-4o, GPT-4o-mini). Paid; needs
    `OPENAI_API_KEY`. Out-of-scope for HF compute credits.
  - **Anthropic** — Claude family. Paid; needs `ANTHROPIC_API_KEY`. Out-of-scope
    for HF compute credits.
  - **Gemini** — Google Gemini. Paid; needs `GEMINI_API_KEY`. Out-of-scope for
    HF compute credits.
  - **Groq** — open-weight Llama-3.3-70B etc. **Free tier** at console.groq.com;
    needs `GROQ_API_KEY`. **No HF credits required.**
  - **HuggingFace Inference Providers (`hf`)** — open-weight frontier
    (Llama-3.1-405B, Qwen3-72B, DeepSeek-V3, Mistral-Large, etc.) routed
    through `https://router.huggingface.co/v1`. Pay-per-token from your
    HF compute credits — typical bench run is ~$0.50 to $2 of credits.
    Needs `HF_TOKEN` (your normal HF Hub token).

Design:
  - Each provider is an independent class implementing `score_text(str) -> float`.
  - Providers skip gracefully if their API key / SDK is missing.
  - All providers use OpenAI-compatible JSON output where supported.
  - Rate-limited + retried with exponential backoff.
  - Results cached per (provider, scenario_id) so partial runs resume.

Usage:
    # Free path — Groq's hosted Llama-3.3-70B, no HF credits, no money:
    export GROQ_API_KEY=gsk_...
    python -m eval.frontier_baseline --providers groq --limit 30

    # HF Inference Providers — open-weight frontier paid from your HF credits:
    export HF_TOKEN=hf_...
    python -m eval.frontier_baseline --providers hf --limit 30
    python -m eval.frontier_baseline --providers hf --hf-models \\
        meta-llama/Llama-3.3-70B-Instruct \\
        meta-llama/Llama-3.1-405B-Instruct \\
        Qwen/Qwen3-72B-Instruct \\
        deepseek-ai/DeepSeek-V3-0324 --limit 30

    # Proprietary frontier — paid separately, NOT from HF credits:
    python -m eval.frontier_baseline --providers openai anthropic gemini

    # Combined:
    python -m eval.frontier_baseline --providers groq hf openai anthropic gemini
"""

from __future__ import annotations

import argparse
import csv
import json
import logging
import os
import re
import sys
import time
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

from eval.bootstrap_ci import bootstrap_ci, cohens_d, permutation_test
from eval.mode_c_real_cases import (
    DEFAULT_DATASET,
    ScriptedAnalyzerAdapter,
    aggregate,
    load_dataset,
    run_eval,
)

logger = logging.getLogger("chakravyuh.frontier")

CACHE_DIR = Path("logs/frontier_cache")
RESULTS_CSV = Path("logs/frontier_comparison.csv")


# ---------------------------------------------------------------------------
# Common prompt (identical across providers to ensure fair comparison)
# ---------------------------------------------------------------------------

FRONTIER_SYSTEM_PROMPT = """You are a fraud detection analyzer for Indian UPI payments. \
Score incoming messages for how likely they are to be scams.

Output strict JSON only:
{"score": <float 0.0 to 1.0>, "explanation": "<one sentence why>"}

0.0 = clearly legitimate
0.3 = some mild concern
0.7 = likely scam
1.0 = definite scam with OTP / Aadhaar / money request"""


_SCORE_PATTERN = re.compile(r'"?score"?\s*:\s*([0-9]*\.?[0-9]+)')
_JSON_OBJ = re.compile(r"\{[^{}]*\}", re.DOTALL)
_THINK_BLOCK = re.compile(r"<think>.*?</think>", re.DOTALL | re.IGNORECASE)
_THINK_OPEN = re.compile(r"<think>.*", re.DOTALL | re.IGNORECASE)
_FENCED_JSON = re.compile(r"```(?:json)?\s*(\{.*?\})\s*```", re.DOTALL | re.IGNORECASE)


def _strip_reasoning(raw: str) -> str:
    """Remove <think>...</think> blocks emitted by chain-of-thought models.

    DeepSeek-R1, o1-class, and other reasoning models prepend their answer with
    a thinking section. Without stripping, the JSON-extraction regex can latch
    onto malformed JSON-like substrings inside the reasoning, or — if the
    model hits the token cap mid-thought — find no closing JSON at all.
    """
    cleaned = _THINK_BLOCK.sub("", raw)
    if "<think>" in cleaned.lower():
        cleaned = _THINK_OPEN.sub("", cleaned)
    return cleaned.strip()


def parse_frontier_score(raw: str) -> float:
    """Extract score from any provider's response. Forgiving.

    Order of attempts:
    1. Strip reasoning-model `<think>` blocks first.
    2. Prefer JSON inside ```json ... ``` fenced blocks (some models wrap output).
    3. Fall back to the first `{...}` JSON object.
    4. Fall back to a regex match on `"score": <num>`.
    """
    cleaned = _strip_reasoning(raw)
    fenced = _FENCED_JSON.search(cleaned)
    if fenced:
        try:
            data = json.loads(fenced.group(1))
            s = float(data.get("score", 0.0))
            return max(0.0, min(1.0, s))
        except (json.JSONDecodeError, ValueError, TypeError):
            pass
    try:
        m = _JSON_OBJ.search(cleaned)
        if m:
            data = json.loads(m.group(0))
            s = float(data.get("score", 0.0))
            return max(0.0, min(1.0, s))
    except (json.JSONDecodeError, ValueError, TypeError):
        pass
    m = _SCORE_PATTERN.search(cleaned)
    if m:
        try:
            return max(0.0, min(1.0, float(m.group(1))))
        except ValueError:
            pass
    return 0.0


# ---------------------------------------------------------------------------
# Base provider
# ---------------------------------------------------------------------------


@dataclass
class ProviderSpec:
    name: str                  # display name — e.g. "gpt-4o-mini"
    cost_per_1k_in: float = 0.0
    cost_per_1k_out: float = 0.0


class FrontierProvider(ABC):
    """Minimal provider interface. Implements AnalyzerProtocol via score_text."""

    spec: ProviderSpec

    @abstractmethod
    def available(self) -> bool: ...

    @abstractmethod
    def _complete(self, user_msg: str) -> str: ...

    def score_text(self, text: str) -> float:
        """Score a single scammer message. Cached + rate-limited."""
        cache_key = f"{self.spec.name}:{_cache_key(text)}"
        cached = _cache_get(cache_key)
        if cached is not None:
            return cached
        for attempt in range(3):
            try:
                raw = self._complete(f"Message: {text[:800]}\nReturn JSON only.")
                score = parse_frontier_score(raw)
                _cache_set(cache_key, score)
                return score
            except Exception as e:  # noqa: BLE001
                logger.warning("%s attempt %d failed: %s", self.spec.name, attempt + 1, e)
                time.sleep(1.5 ** attempt)
        return 0.0


# ---------------------------------------------------------------------------
# Concrete providers
# ---------------------------------------------------------------------------


class OpenAIProvider(FrontierProvider):
    """OpenAI GPT family (paid). Uses the openai package + OPENAI_API_KEY."""

    spec = ProviderSpec(name="gpt-4o-mini", cost_per_1k_in=0.00015, cost_per_1k_out=0.0006)

    def __init__(self, model: str = "gpt-4o-mini") -> None:
        self.spec = ProviderSpec(name=model)
        self._client: Any = None

    def available(self) -> bool:
        if not os.environ.get("OPENAI_API_KEY"):
            return False
        try:
            import openai  # noqa: F401
        except ImportError:
            return False
        return True

    def _ensure(self) -> None:
        if self._client is not None:
            return
        from openai import OpenAI  # type: ignore[import-not-found]

        self._client = OpenAI()

    def _complete(self, user_msg: str) -> str:
        self._ensure()
        r = self._client.chat.completions.create(
            model=self.spec.name,
            messages=[
                {"role": "system", "content": FRONTIER_SYSTEM_PROMPT},
                {"role": "user", "content": user_msg},
            ],
            temperature=0.0,
            max_tokens=150,
            response_format={"type": "json_object"},
        )
        return r.choices[0].message.content or ""


class GroqProvider(FrontierProvider):
    """Groq (free tier, OpenAI-compatible). Uses openai pkg + GROQ_API_KEY."""

    spec = ProviderSpec(name="groq-llama-3.3-70b")

    def __init__(self, model: str = "llama-3.3-70b-versatile") -> None:
        self.spec = ProviderSpec(name=f"groq-{model}")
        self._model = model
        self._client: Any = None

    def available(self) -> bool:
        if not os.environ.get("GROQ_API_KEY"):
            return False
        try:
            import openai  # noqa: F401
        except ImportError:
            return False
        return True

    def _ensure(self) -> None:
        if self._client is not None:
            return
        from openai import OpenAI  # type: ignore[import-not-found]

        self._client = OpenAI(
            api_key=os.environ["GROQ_API_KEY"],
            base_url="https://api.groq.com/openai/v1",
        )

    def _complete(self, user_msg: str) -> str:
        self._ensure()
        r = self._client.chat.completions.create(
            model=self._model,
            messages=[
                {"role": "system", "content": FRONTIER_SYSTEM_PROMPT},
                {"role": "user", "content": user_msg},
            ],
            temperature=0.0,
            max_tokens=150,
        )
        return r.choices[0].message.content or ""


class HuggingFaceProvider(FrontierProvider):
    """HuggingFace Inference Providers — OpenAI-compatible router at
    `https://router.huggingface.co/v1`. Pay-per-token from HF compute credits.

    Supports any chat-completion model exposed by an HF Inference Provider
    (Together AI, Fireworks, Novita, SambaNova, Cerebras, Hyperbolic, Nebius,
    HF Inference, Featherless AI, etc.) — auto-routes by default. Pin a
    specific provider with the colon syntax, e.g.
    `meta-llama/Llama-3.3-70B-Instruct:together`.

    Default model: `meta-llama/Llama-3.3-70B-Instruct` (cheap, competitive,
    auto-routed). Override via constructor or via the `--hf-models` CLI flag.
    """

    spec = ProviderSpec(name="hf-llama-3.3-70b")

    DEFAULT_MODEL = "meta-llama/Llama-3.3-70B-Instruct"

    def __init__(self, model: str = DEFAULT_MODEL) -> None:
        # Strip optional `:provider` suffix when building the spec name so the
        # CSV / table column stays readable while the API call retains the pin.
        display = model.split(":", 1)[0].split("/", 1)[-1].lower()
        self.spec = ProviderSpec(name=f"hf-{display}")
        self._model = model
        self._client: Any = None

    def available(self) -> bool:
        if not os.environ.get("HF_TOKEN"):
            return False
        try:
            import openai  # noqa: F401
        except ImportError:
            return False
        return True

    def _ensure(self) -> None:
        if self._client is not None:
            return
        from openai import OpenAI  # type: ignore[import-not-found]

        self._client = OpenAI(
            api_key=os.environ["HF_TOKEN"],
            base_url="https://router.huggingface.co/v1",
        )

    def _complete(self, user_msg: str) -> str:
        self._ensure()
        # Reasoning models (R1, o1-class) need a much larger budget because
        # the thinking block alone can be 1500+ tokens; otherwise the response
        # gets truncated mid-think and never produces JSON.
        is_reasoning = any(
            tag in self._model.lower()
            for tag in ("r1", "deepseek-r", "qwq", "o1-", "o1", "reasoning")
        )
        max_toks = 4096 if is_reasoning else 150
        r = self._client.chat.completions.create(
            model=self._model,
            messages=[
                {"role": "system", "content": FRONTIER_SYSTEM_PROMPT},
                {"role": "user", "content": user_msg},
            ],
            temperature=0.0,
            max_tokens=max_toks,
        )
        return r.choices[0].message.content or ""


class AnthropicProvider(FrontierProvider):
    """Anthropic Claude. Uses `anthropic` pkg + ANTHROPIC_API_KEY."""

    spec = ProviderSpec(name="claude-haiku")

    def __init__(self, model: str = "claude-3-5-haiku-latest") -> None:
        self.spec = ProviderSpec(name=model)
        self._client: Any = None

    def available(self) -> bool:
        if not os.environ.get("ANTHROPIC_API_KEY"):
            return False
        try:
            import anthropic  # noqa: F401
        except ImportError:
            return False
        return True

    def _ensure(self) -> None:
        if self._client is not None:
            return
        import anthropic  # type: ignore[import-not-found]

        self._client = anthropic.Anthropic()

    def _complete(self, user_msg: str) -> str:
        self._ensure()
        r = self._client.messages.create(
            model=self.spec.name,
            max_tokens=150,
            temperature=0.0,
            system=FRONTIER_SYSTEM_PROMPT,
            messages=[{"role": "user", "content": user_msg}],
        )
        # Anthropic returns a list of content blocks; we want text
        parts: list[str] = []
        for block in r.content:
            if hasattr(block, "text"):
                parts.append(block.text)
        return "".join(parts)


class GeminiProvider(FrontierProvider):
    """Google Gemini via the google-generativeai pkg + GEMINI_API_KEY."""

    spec = ProviderSpec(name="gemini-2.0-flash")

    def __init__(self, model: str = "gemini-2.0-flash") -> None:
        self.spec = ProviderSpec(name=model)
        self._model_obj: Any = None

    def available(self) -> bool:
        if not os.environ.get("GEMINI_API_KEY"):
            return False
        try:
            import google.generativeai  # noqa: F401
        except ImportError:
            return False
        return True

    def _ensure(self) -> None:
        if self._model_obj is not None:
            return
        import google.generativeai as genai  # type: ignore[import-not-found]

        genai.configure(api_key=os.environ["GEMINI_API_KEY"])
        self._model_obj = genai.GenerativeModel(
            model_name=self.spec.name,
            system_instruction=FRONTIER_SYSTEM_PROMPT,
        )

    def _complete(self, user_msg: str) -> str:
        self._ensure()
        r = self._model_obj.generate_content(
            user_msg,
            generation_config={"temperature": 0.0, "max_output_tokens": 150},
        )
        return getattr(r, "text", "") or ""


PROVIDER_REGISTRY: dict[str, type[FrontierProvider]] = {
    "openai": OpenAIProvider,
    "groq": GroqProvider,
    "hf": HuggingFaceProvider,
    "anthropic": AnthropicProvider,
    "gemini": GeminiProvider,
}


# ---------------------------------------------------------------------------
# Cache (per-scenario-hash to avoid re-paying API $)
# ---------------------------------------------------------------------------


def _cache_key(text: str) -> str:
    import hashlib

    return hashlib.sha1(text.encode("utf-8")).hexdigest()[:16]


def _cache_get(key: str) -> float | None:
    path = CACHE_DIR / f"{key}.json"
    if path.exists():
        try:
            return float(json.loads(path.read_text()).get("score"))
        except (json.JSONDecodeError, ValueError, TypeError):
            return None
    return None


def _cache_set(key: str, score: float) -> None:
    CACHE_DIR.mkdir(parents=True, exist_ok=True)
    (CACHE_DIR / f"{key}.json").write_text(json.dumps({"score": score}))


# ---------------------------------------------------------------------------
# Comparison runner
# ---------------------------------------------------------------------------


@dataclass
class ProviderResult:
    provider: str
    detection_rate: float
    false_positive_rate: float
    precision: float
    f1: float
    n: int
    ci_low: float
    ci_high: float
    per_category_detection: dict[str, float] = field(default_factory=dict)


def _build_provider_lineup(
    provider_names: list[str],
    hf_models: list[str] | None = None,
) -> list[tuple[str, FrontierProvider | str]]:
    """Expand `--providers` + `--hf-models` into an ordered (name, instance) list.

    Returns "scripted" as a sentinel string at index 0 (handled by the caller).
    For "hf" with a non-empty `hf_models` list, expands to one HuggingFaceProvider
    per model so multiple open-weight comparisons run in a single invocation.
    """
    lineup: list[tuple[str, FrontierProvider | str]] = [("scripted", "scripted")]
    seen: set[str] = {"scripted"}
    for name in provider_names:
        if name == "scripted" or name in seen:
            continue
        seen.add(name)
        if name == "hf" and hf_models:
            for model in hf_models:
                inst = HuggingFaceProvider(model=model)
                lineup.append((inst.spec.name, inst))
            continue
        cls = PROVIDER_REGISTRY.get(name)
        if cls is None:
            logger.warning("Unknown provider '%s' — skipping.", name)
            continue
        lineup.append((name, cls()))
    return lineup


def evaluate_providers(
    provider_names: list[str],
    dataset_path: Path = DEFAULT_DATASET,
    limit: int | None = None,
    bootstrap_n: int = 1000,
    hf_models: list[str] | None = None,
) -> dict[str, ProviderResult]:
    data = load_dataset(dataset_path)
    if limit:
        data = data[:limit]
    results: dict[str, ProviderResult] = {}

    lineup = _build_provider_lineup(provider_names, hf_models=hf_models)

    for name, entry in lineup:
        if entry == "scripted":
            analyzer: Any = ScriptedAnalyzerAdapter()
        else:
            provider = entry  # type: ignore[assignment]
            if not provider.available():
                logger.warning(
                    "Provider '%s' unavailable (missing API key or SDK) — skipping.",
                    name,
                )
                continue
            analyzer = provider

        logger.info("Evaluating %s on %d scenarios...", name, len(data))
        eval_results = run_eval(analyzer, data, threshold=0.5)
        metrics = aggregate(eval_results)
        scam_hits = [
            1.0 if r.predicted_flag else 0.0
            for r in eval_results if r.is_scam_truth
        ]
        _, lo, hi = bootstrap_ci(scam_hits, n_resamples=bootstrap_n, seed=42)

        per_cat = {}
        for r in eval_results:
            cat = r.category
            per_cat.setdefault(cat, {"tp": 0, "total": 0})
            if r.is_scam_truth:
                per_cat[cat]["total"] += 1
                if r.predicted_flag:
                    per_cat[cat]["tp"] += 1
        per_cat_rates = {
            cat: (d["tp"] / d["total"]) if d["total"] else 0.0
            for cat, d in per_cat.items()
        }

        results[name] = ProviderResult(
            provider=name,
            detection_rate=metrics.detection_rate,
            false_positive_rate=metrics.false_positive_rate,
            precision=metrics.precision,
            f1=metrics.f1,
            n=metrics.n,
            ci_low=lo,
            ci_high=hi,
            per_category_detection=per_cat_rates,
        )
        logger.info(
            "  %s: detection=%.1f%% (CI [%.1f%%, %.1f%%]), F1=%.3f",
            name,
            metrics.detection_rate * 100,
            lo * 100,
            hi * 100,
            metrics.f1,
        )
    return results


def save_comparison_csv(results: dict[str, ProviderResult], output: Path) -> None:
    output.parent.mkdir(parents=True, exist_ok=True)
    with output.open("w", newline="") as f:
        w = csv.writer(f)
        w.writerow([
            "provider", "n", "detection_rate", "ci_low", "ci_high",
            "false_positive_rate", "precision", "f1",
        ])
        for r in results.values():
            w.writerow([
                r.provider, r.n,
                f"{r.detection_rate:.4f}",
                f"{r.ci_low:.4f}", f"{r.ci_high:.4f}",
                f"{r.false_positive_rate:.4f}",
                f"{r.precision:.4f}", f"{r.f1:.4f}",
            ])


def print_comparison_table(results: dict[str, ProviderResult]) -> None:
    print("\n=== Frontier Baseline Comparison ===")
    print(f"{'Provider':<28} {'Detection':>12} {'95% CI':>22} {'FP':>8} {'F1':>8}")
    print("-" * 84)
    for r in results.values():
        print(
            f"{r.provider:<28} "
            f"{r.detection_rate*100:>10.1f}% "
            f"[{r.ci_low*100:>5.1f}%, {r.ci_high*100:>5.1f}%] "
            f"{r.false_positive_rate*100:>6.1f}% "
            f"{r.f1:>8.3f}"
        )


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Frontier LLM baseline comparison")
    parser.add_argument(
        "--providers",
        nargs="+",
        default=["groq", "hf"],
        choices=list(PROVIDER_REGISTRY.keys()) + ["scripted"],
        help=(
            "Providers to evaluate (skips if API key missing). "
            "'groq' = free Llama-3.3-70B (no HF credits needed); "
            "'hf' = HuggingFace Inference Providers (paid from HF credits)."
        ),
    )
    parser.add_argument(
        "--hf-models",
        nargs="+",
        default=None,
        metavar="MODEL_ID",
        help=(
            "When 'hf' is in --providers, override the default Llama-3.3-70B "
            "with one or more open-weight model IDs hosted on HF Inference "
            "Providers, e.g. meta-llama/Llama-3.1-405B-Instruct "
            "Qwen/Qwen3-72B-Instruct deepseek-ai/DeepSeek-V3-0324. "
            "Each model adds one row to the comparison CSV."
        ),
    )
    parser.add_argument("--dataset", type=Path, default=DEFAULT_DATASET)
    parser.add_argument("--limit", type=int, default=None, help="Scenarios to run")
    parser.add_argument("--bootstrap", type=int, default=1000)
    parser.add_argument("--output", type=Path, default=RESULTS_CSV)
    args = parser.parse_args(argv)

    logging.basicConfig(level=logging.INFO, format="%(message)s")

    results = evaluate_providers(
        provider_names=args.providers,
        dataset_path=args.dataset,
        limit=args.limit,
        bootstrap_n=args.bootstrap,
        hf_models=args.hf_models,
    )
    print_comparison_table(results)
    save_comparison_csv(results, args.output)
    logger.info("Wrote %s", args.output)

    # Pairwise permutation tests vs scripted baseline
    if "scripted" in results and len(results) > 1:
        print("\n=== Permutation Test vs Scripted Baseline ===")
        base_rate = results["scripted"].detection_rate
        for name, r in results.items():
            if name == "scripted":
                continue
            delta = (r.detection_rate - base_rate) * 100
            sign = "+" if delta >= 0 else ""
            print(f"{name:<28} Δ detection = {sign}{delta:.1f}pp")
    return 0


if __name__ == "__main__":
    sys.exit(main())