Skip to content

Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.

feat(llm): record the model that wrote rubric scores and Tier 3 insights (#308)

Narendran Raghavanc928d82fc361
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5bf50af4..a36cdd85 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -114,6 +114,17 @@ All notable changes to SkillEvaluator are documented in this file.
- CI-native per-skill HTML pages link Download JSON to the retained
`skillevaluator-tier1.json` and do not embed a second copy of the report
JSON. Standalone CLI HTML reports embed it for Export JSON.
+- Rubric evaluation JSON reports name the provider and model that gave each
+ score as `llm_provider` and `llm_model_used` in the skill's `rubric_eval`
+ success detail and, for a single skill, also in `rubric_eval`. Tier 3
+ conclusions and recommendations written by the LLM, and LLM-written
+ dimensions returned by `compute_dimensions`, record the model that wrote
+ them as `model`. For a Claude 5.5 or later model on the native Claude API
+ this is the model the reply names: the server-side refusal fallback model,
+ not the configured model, when the fallback answered. Otherwise it is the
+ configured model, unless a server-side `fallback` block in the reply names
+ another model.
+
- Tier 3 runs can be limited to the first N eval cases with the opt-in
`--max-cases N` flag on `validate`, `tier3`, and `tier3 evaluate`, or the
`harbor.max_cases` key in `evals/config.yml`; the CLI value wins. Unset, every
@@ -546,6 +557,14 @@ All notable changes to SkillEvaluator are documented in this file.
scoring agree, while scoped searches and slash-valued patterns retain their
classification.
+- On the native Claude API, the Tier 3 judges' `judge_model_used` names the
+ server-side fallback model when the API serves a repeated request straight
+ from that model. Such a reply has no `fallback` content block, so the label
+ now comes from the reply's own `model` field instead of the configured
+ model. `judge_fallback_used` is then `true`, and Skill Lift treats such a
+ case like an in-call fallback: when another condition, attempt or step of
+ the case was judged by the configured model, the case leaves that judge
+ metric's lift and is counted in `judge_mixed_cases`.
- Tier 2 `similarity-check` and `context-optimization-check` no longer abort
with a "symlink or reparse point" error when a skill or collection aliases
one agent directory to another, such as `.agents -> .claude`. A directory
diff --git a/docs/reports.mdx b/docs/reports.mdx
index 225d5251..5c5c3c45 100644
--- a/docs/reports.mdx
+++ b/docs/reports.mdx
@@ -668,7 +668,13 @@ For CI and tooling, two JSON entry points matter:
Both paths speak the same dialect: standalone `tier3 evaluate` and
`validate --tier3` share one HTML renderer for `report.html`, and both embed
-the Tier 3 payload at schema version `2.0`.
+the Tier 3 payload at schema version `2.0`. In that payload, conclusions and
+recommendations written by the LLM carry `source: "llm"` and name the model
+that wrote them as `model`. For a Claude 5.5 or later model on the native
+Claude API this is the model the reply names, which can be the server-side
+refusal fallback model rather than the configured model. Otherwise it is the
+configured model, unless a server-side `fallback` block in the reply names
+another model.
Exit codes and a ready-made JSON gating recipe live in
[Gate Your CI](ci-integration.mdx).
diff --git a/docs/tier1-validation.mdx b/docs/tier1-validation.mdx
index d99efab0..04136b3b 100644
--- a/docs/tier1-validation.mdx
+++ b/docs/tier1-validation.mdx
@@ -373,6 +373,8 @@ For `validate`, the default set is `schema`, `version`, `security`, `pii`, `lice
Each criterion is scored from 0 to 10. The local evaluator, not the model's boolean, treats 7 or higher as passing. The overall score is an importance-weighted mean, and the rubric passes only when that score reaches `--min-score` and every criterion passes.
+ The JSON report names the provider and model that gave each score as `llm_provider` and `llm_model_used` in the skill's `rubric_eval` success detail and, for a single skill, also in the `rubric_eval` object. For a Claude 5.5 or later model on the native Claude API, the model is the one the reply names; otherwise it is the configured model, unless a server-side `fallback` block in the reply names another model. A Claude 5.5 or later model's refusal can be answered by the server-side fallback model, and the API can send a repeat of that request straight to it; the report then names the fallback model, not the configured model.
+
```bash title="Rubric evaluation"
skillevaluator rubric-eval ./my-skill --min-score 70
```
diff --git a/src/skillevaluator/evaluation/dimension_judge.py b/src/skillevaluator/evaluation/dimension_judge.py
index 53c6fd7d..417ec243 100644
--- a/src/skillevaluator/evaluation/dimension_judge.py
+++ b/src/skillevaluator/evaluation/dimension_judge.py
@@ -30,6 +30,7 @@ from skillevaluator.constants import (
TIER3_LIFT_PASS_THRESHOLD,
)
from skillevaluator.inference.client import LLMClient
+from skillevaluator.inference.diagnostics import safe_llm_model
from skillevaluator.logging_config import get_logger
logger = get_logger(__name__)
@@ -181,9 +182,14 @@ class DimensionJudge(LLMClient):
dims = data.get("dimensions", data) if isinstance(data, dict) else data
if not isinstance(dims, list) or len(dims) < 5:
raise ValueError(f"Expected 5 dimensions, got {len(dims) if isinstance(dims, list) else type(dims)}")
+ # The model that answered, which on the native Anthropic API can be
+ # the server-side fallback.
+ model = safe_llm_model(self.model_used) if self.model_used else None
for dim in dims:
if isinstance(dim, dict):
_normalise_reasoning_fields(dim)
+ if model:
+ dim["model"] = model
return dims
def get_fallback_response(self, **kwargs: Any) -> list[dict]:
@@ -420,7 +426,9 @@ def compute_dimensions(
use_llm: If False, skip LLM and use deterministic fallback.
Returns:
- List of 5 dimension dicts with id, score, verdict, explanation.
+ List of 5 dimension dicts with id, score, verdict, explanation. A
+ dimension the LLM wrote also names the model that wrote it as
+ ``model``; deterministic dimensions have no ``model``.
"""
if not use_llm:
return compute_dimensions_deterministic(evaluators)
diff --git a/src/skillevaluator/evaluation/insights_judge.py b/src/skillevaluator/evaluation/insights_judge.py
index 66fe3573..1cad3492 100644
--- a/src/skillevaluator/evaluation/insights_judge.py
+++ b/src/skillevaluator/evaluation/insights_judge.py
@@ -31,6 +31,7 @@ from skillevaluator.constants import (
INSIGHTS_JUDGE_TEMPERATURE,
)
from skillevaluator.inference.client import LLMClient
+from skillevaluator.inference.diagnostics import safe_llm_model
from skillevaluator.logging_config import get_logger
logger = get_logger(__name__)
@@ -535,6 +536,9 @@ class InsightsJudge(LLMClient):
raise ValueError(f"Expected JSON object, got {type(data).__name__}")
canonical = kwargs.get("canonical") if isinstance(kwargs.get("canonical"), dict) else {}
grounding = _negative_control_grounding(canonical)
+ # Each entry names the model that wrote it, which on the native
+ # Anthropic API can be the server-side fallback.
+ provenance = {"model": safe_llm_model(self.model_used)} if self.model_used else {}
conclusions: list[dict] = []
for item in (data.get("conclusions") or [])[:INSIGHTS_JUDGE_MAX_CONCLUSIONS]:
@@ -553,6 +557,7 @@ class InsightsJudge(LLMClient):
"message": message or title,
"severity": _coerce_severity(item.get("severity")),
"source": "llm",
+ **provenance,
"evidence_case_ids": _declared_case_ids(item),
}
)
@@ -575,6 +580,7 @@ class InsightsJudge(LLMClient):
"category": _coerce_category(item.get("category")),
"severity": _coerce_severity(item.get("severity")),
"source": "llm",
+ **provenance,
"evidence_case_ids": _declared_case_ids(item),
}
)
diff --git a/src/skillevaluator/inference/client.py b/src/skillevaluator/inference/client.py
index 83c2ea40..ed9b1a3e 100644
--- a/src/skillevaluator/inference/client.py
+++ b/src/skillevaluator/inference/client.py
@@ -22,6 +22,7 @@ import io
import json
import os
import re
+import threading
import urllib.error
from collections.abc import Callable
from dataclasses import replace
@@ -328,6 +329,30 @@ def _checked_content(content: str, stop_reason: object, refusal: object = None)
return content
+def _anthropic_served_model(response: Any, *, requested_fallback: bool) -> str | None:
+ """Return the model that wrote an Anthropic reply when it can differ from the requested one.
+
+ A server-side ``fallback`` block names the model that took over. A turn
+ served by sticky routing, which sends repeats of a fallen-back request
+ straight to the fallback model, carries no block. For a request that asked
+ for server-side fallback, the top-level ``model`` then names the model
+ that wrote the reply. ``None`` means the requested model answered.
+ """
+ served_model = None
+ for block in getattr(response, "content", None) or []:
+ if getattr(block, "type", None) != "fallback":
+ continue
+ served = getattr(block, "to", None)
+ model = served.get("model") if isinstance(served, dict) else getattr(served, "model", None)
+ if isinstance(model, str) and model:
+ served_model = model
+ if served_model is None and requested_fallback:
+ model = getattr(response, "model", None)
+ if isinstance(model, str) and model:
+ served_model = model
+ return served_model
+
+
def _extract_choice_content(response: Any) -> str:
choices = getattr(response, "choices", None) or []
first_choice = choices[0] if choices else None
@@ -410,6 +435,8 @@ class LLMClient:
self._client: Any = None
self._provider_config: ProviderConfig | None = None
self.last_failure: str | None = None
+ # Per thread, because one client can serve concurrent calls.
+ self._call_state = threading.local()
# -- public read-only properties for introspection --------------------
@@ -417,6 +444,23 @@ class LLMClient:
def model(self) -> str:
return self._model or self._resolved_config().model
+ @property
+ def provider(self) -> str:
+ return self._resolved_config().provider
+
+ @property
+ def model_used(self) -> str | None:
+ """Return the model that answered this thread's last :meth:`completions` call.
+
+ For an Anthropic reply, a server-side ``fallback`` content block names
+ the model that answered, on any endpoint. Only a native Claude API
+ request for a Claude 5.5 or later model, which asks for server-side
+ fallback, also reads the reply's top-level ``model`` when there is no
+ block. Otherwise it is the configured model. ``None`` before a call
+ succeeds and after a call fails.
+ """
+ return getattr(self._call_state, "model_used", None)
+
@property
def base_url(self) -> str | None:
return self._base_url or self._resolved_config().base_url
@@ -570,17 +614,22 @@ class LLMClient:
) -> str:
"""Send a chat completion request and return the response text.
- Raises :class:`LLMClientError` when the response is empty.
+ Raises :class:`LLMClientError` when the response is empty. On success
+ :attr:`model_used` names the model that answered.
"""
+ self._call_state.model_used = None
config = self._resolved_config()
client = self._get_client()
target_key = SchemaTargetKey(config.provider, config.base_url or "", config.model)
max_tokens = self._request_max_tokens(config)
reasoning_effort = self.reasoning_effort
+ answered_by = config.model
def _invoke_provider() -> str:
+ nonlocal answered_by
use_schema = response_schema is not None and target_key not in _SCHEMA_UNSUPPORTED_TARGETS
if config.provider == "anthropic":
+ requests_fallback = is_claude_5_5_or_later(config.model) and _is_native_anthropic_endpoint(config)
def _anthropic_kwargs(include_schema: bool) -> dict[str, Any]:
call_kwargs: dict[str, Any] = {
@@ -597,7 +646,7 @@ class LLMClient:
output_config["effort"] = reasoning_effort
if output_config:
call_kwargs["output_config"] = output_config
- if is_claude_5_5_or_later(config.model) and _is_native_anthropic_endpoint(config):
+ if requests_fallback:
# Server-side fallback (beta): a safety-classifier refusal is retried on
# the fallback model within the same call. Older SDKs lack typed fields.
call_kwargs["extra_headers"] = {"anthropic-beta": ANTHROPIC_SERVER_SIDE_FALLBACK_BETA}
@@ -610,6 +659,7 @@ class LLMClient:
target_key=target_key,
use_schema=use_schema,
)
+ answered_by = _anthropic_served_model(response, requested_fallback=requests_fallback) or config.model
content = "".join(
str(block.text) for block in response.content if getattr(block, "type", None) == "text"
)
@@ -684,7 +734,9 @@ class LLMClient:
raise
return _extract_choice_content(response)
- return retry_call_with_backoff(_invoke_provider, config=self._retry_config)
+ content = retry_call_with_backoff(_invoke_provider, config=self._retry_config)
+ self._call_state.model_used = answered_by
+ return content
def extract_json_from_response(
self,
diff --git a/src/skillevaluator/inference/diagnostics.py b/src/skillevaluator/inference/diagnostics.py
index fa630b64..05f69abb 100644
--- a/src/skillevaluator/inference/diagnostics.py
+++ b/src/skillevaluator/inference/diagnostics.py
@@ -40,15 +40,19 @@ _PROVIDERS = frozenset({"openai", "anthropic", "nv_build", "bedrock", "openai-co
def safe_llm_labels(provider: object, model: object) -> tuple[str, str]:
"""Keep configured identifiers readable without emitting URLs or control text."""
safe_provider = provider if isinstance(provider, str) and provider in _PROVIDERS else "unresolved"
- safe_model = "unresolved"
+ return safe_provider, safe_llm_model(model)
+
+
+def safe_llm_model(model: object) -> str:
+ """Return a model identifier fit for reports, or ``unresolved``."""
if (
isinstance(model, str)
and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,159}", model)
and "://" not in model
and not model.startswith(("sk-", "nvapi-"))
):
- safe_model = model
- return safe_provider, safe_model
+ return model
+ return "unresolved"
def llm_failure_diagnostic(exc: Exception) -> str:
diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.py
index 9980b8f1..811f12de 100644
--- a/src/skillevaluator/tier3/harbor/templates/eval.py
+++ b/src/skillevaluator/tier3/harbor/templates/eval.py
@@ -1715,10 +1715,18 @@ def _call_anthropic(prompt, model, max_tokens, temperature, response_schema=None
if body.get("stop_reason") == "refusal":
raise _JudgeRefusedError("judge model declined the request (stop_reason=refusal)")
blocks = [block for block in body.get("content", []) if isinstance(block, dict)]
+ served_model = None
for block in blocks:
served = block.get("to") if block.get("type") == "fallback" else None
- if provenance is not None and isinstance(served, dict) and isinstance(served.get("model"), str):
- provenance["model"] = served["model"]
+ if isinstance(served, dict) and isinstance(served.get("model"), str) and served["model"]:
+ served_model = served["model"]
+ # A turn served by sticky routing, which sends repeats of a fallen-back
+ # request straight to the fallback model, carries no fallback block; the
+ # top-level model then names the model that wrote the reply.
+ if served_model is None and server_side_fallback and isinstance(body.get("model"), str) and body["model"]:
+ served_model = body["model"]
+ if provenance is not None and served_model is not None:
+ provenance["model"] = served_model
content = "".join(str(block.get("text", "")) for block in blocks if block.get("type") == "text")
return content.strip(), None
diff --git a/src/skillevaluator/validators/rubric_eval.py b/src/skillevaluator/validators/rubric_eval.py
index ff8ceaa4..f9816766 100644
--- a/src/skillevaluator/validators/rubric_eval.py
+++ b/src/skillevaluator/validators/rubric_eval.py
@@ -35,6 +35,7 @@ from skillevaluator.constants import (
SKILL_MANIFEST_VARIANTS,
)
from skillevaluator.inference.client import LLMClient
+from skillevaluator.inference.diagnostics import safe_llm_labels
from skillevaluator.logging_config import get_logger
from skillevaluator.models.result import Finding, Severity, ValidationResult
from skillevaluator.utils.secure_fs import SecureRoot
@@ -558,6 +559,17 @@ class RubricEvalValidator(ValidatorBase):
return result
+ def _judge_labels(self) -> dict[str, str]:
+ """Name the provider and model that gave the score, when the judge answered.
+
+ On the native Anthropic API the model can be the server-side fallback,
+ which scores differently from the configured model.
+ """
+ if self._judge.model_used is None:
+ return {}
+ provider, model = safe_llm_labels(self._judge.provider, self._judge.model_used)
+ return {"llm_provider": provider, "llm_model_used": model}
+
@staticmethod
def _record_judge_failure(
result: ValidationResult,
@@ -739,6 +751,7 @@ class RubricEvalValidator(ValidatorBase):
)
)
+ judge_labels = self._judge_labels()
result.metadata["rubric_eval"] = {
"execution_status": "succeeded",
"overall_score": overall_score,
@@ -755,13 +768,17 @@ class RubricEvalValidator(ValidatorBase):
"criterion_pass_score": _CRITERION_PASS_SCORE,
"requires_all_criteria_pass": True,
},
+ **judge_labels,
}
+ # The success detail also names the model, so each skill of a folder
+ # run keeps its own.
result.add_success(
check_name="rubric_eval",
message=f"LLM Rubric Score: {overall_score}/100",
overall_score=overall_score,
overall_pass=overall_pass,
+ **judge_labels,
)
return result
diff --git a/tests/inference/test_diagnostics.py b/tests/inference/test_diagnostics.py
index df3b30e3..e8e6519b 100644
--- a/tests/inference/test_diagnostics.py
+++ b/tests/inference/test_diagnostics.py
@@ -10,7 +10,7 @@ import pytest
from openai import APIConnectionError, APIStatusError, APITimeoutError
from skillevaluator.inference import LLMClientError
-from skillevaluator.inference.diagnostics import llm_failure_diagnostic, safe_llm_labels
+from skillevaluator.inference.diagnostics import llm_failure_diagnostic, safe_llm_labels, safe_llm_model
@pytest.mark.parametrize("status", [400, 401, 403, 404, 410, 422, 429, 500])
@@ -82,6 +82,7 @@ def test_transport_and_response_errors_do_not_echo_raw_content(exception, expect
)
def test_model_labels_reject_urls_tokens_and_control_text(model):
assert safe_llm_labels("nv_build", model) == ("nv_build", "unresolved")
+ assert safe_llm_model(model) == "unresolved"
def test_model_labels_preserve_real_model_ids_and_bound_unknown_provider():
diff --git a/tests/inference/test_llm_client.py b/tests/inference/test_llm_client.py
index c40ecdc3..17a8e202 100644
--- a/tests/inference/test_llm_client.py
+++ b/tests/inference/test_llm_client.py
@@ -6,6 +6,7 @@
from __future__ import annotations
import json
+import threading
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
@@ -1130,3 +1131,203 @@ class TestRefusalAndTruncation:
assert client.process() == "fallback"
assert client.last_failure is not None
+
+
+def _anthropic_fallback_response(text: str, served_by: object):
+ """Return a reply whose server-side fallback block names the model that served it."""
+ response = _anthropic_response(text)
+ response.content.insert(0, SimpleNamespace(type="fallback", to=served_by))
+ return response
+
+
+class TestModelProvenance:
+ def test_model_used_names_the_configured_model_after_a_success_only(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _use_provider(monkeypatch, "openai", CHAT_DEFAULT_OPENAI)
+ mock_openai = MagicMock()
+ mock_openai.chat.completions.create.side_effect = [
+ _openai_choice_response("Done"),
+ _openai_choice_response("", finish_reason="content_filter"),
+ ]
+ client = LLMClient()
+
+ with patch("openai.OpenAI", return_value=mock_openai):
+ assert client.model_used is None
+ client.completions("system", "user")
+ assert client.model_used == CHAT_DEFAULT_OPENAI
+ with pytest.raises(LLMClientRefusedError):
+ client.completions("system", "user")
+
+ assert client.model_used is None
+
+ @pytest.mark.parametrize(
+ "served_by",
+ [{"model": ANTHROPIC_REFUSAL_FALLBACK_MODEL}, SimpleNamespace(model=ANTHROPIC_REFUSAL_FALLBACK_MODEL)],
+ ids=["untyped-block", "typed-block"],
+ )
+ def test_model_used_names_the_server_side_fallback_model(
+ self, monkeypatch: pytest.MonkeyPatch, served_by: object
+ ) -> None:
+ _use_provider(monkeypatch, "anthropic", "claude-opus-5-5")
+ mock_anthropic = MagicMock()
+ mock_anthropic.messages.create.return_value = _anthropic_fallback_response("Done", served_by)
+ client = LLMClient()
+
+ with patch("anthropic.Anthropic", return_value=mock_anthropic):
+ assert client.completions("system", "user") == "Done"
+
+ assert client.model == "claude-opus-5-5"
+ assert client.model_used == ANTHROPIC_REFUSAL_FALLBACK_MODEL
+
+ @pytest.mark.parametrize(
+ ("base_url", "expected_model"),
+ [(None, ANTHROPIC_REFUSAL_FALLBACK_MODEL), ("https://gateway.example", "claude-opus-5-5")],
+ ids=["native-sticky-turn", "gateway-without-fallback"],
+ )
+ def test_model_used_reads_the_reply_model_only_when_fallback_was_requested(
+ self, monkeypatch: pytest.MonkeyPatch, base_url: str | None, expected_model: str
+ ) -> None:
+ """A sticky-served turn has no fallback block; its top-level model names the model that wrote it."""
+ pytest.importorskip("anthropic")
+ httpx = pytest.importorskip("httpx")
+ _use_provider(monkeypatch, "anthropic", "claude-opus-5-5")
+ if base_url:
+ monkeypatch.setenv("ANTHROPIC_BASE_URL", base_url)
+ sent: list[dict] = []
+
+ def handler(request):
+ sent.append(json.loads(request.content))
+ return httpx.Response(
+ 200,
+ json={
+ "id": "msg_test",
+ "type": "message",
+ "role": "assistant",
+ "model": ANTHROPIC_REFUSAL_FALLBACK_MODEL,
+ "content": [{"type": "text", "text": "Done"}],
+ "stop_reason": "end_turn",
+ "stop_sequence": None,
+ "usage": {
+ "input_tokens": 1,
+ "output_tokens": 1,
+ "iterations": [{"type": "fallback_message", "model": ANTHROPIC_REFUSAL_FALLBACK_MODEL}],
+ },
+ },
+ )
+
+ with httpx.Client(transport=httpx.MockTransport(handler)) as http_client:
+ client = LLMClient(http_client=http_client)
+ assert client.completions("system", "user") == "Done"
+
+ assert ("fallbacks" in sent[0]) is (base_url is None)
+ assert client.model_used == expected_model
+
+ @pytest.mark.parametrize(
+ "base_url", [None, "https://gateway.example"], ids=["native-with-fallback", "gateway-without-fallback"]
+ )
+ def test_model_used_reads_the_fallback_block_before_the_reply_model(
+ self, monkeypatch: pytest.MonkeyPatch, base_url: str | None
+ ) -> None:
+ """The block wins over a different top-level model, and a block is honored on any Anthropic endpoint."""
+ pytest.importorskip("anthropic")
+ httpx = pytest.importorskip("httpx")
+ _use_provider(monkeypatch, "anthropic", "claude-opus-5-5")
+ if base_url:
+ monkeypatch.setenv("ANTHROPIC_BASE_URL", base_url)
+ sent: list[dict] = []
+
+ def handler(request):
+ sent.append(json.loads(request.content))
+ return httpx.Response(
+ 200,
+ json={
+ "id": "msg_test",
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-opus-5-5",
+ "content": [
+ {
+ "type": "fallback",
+ "from": {"model": "claude-opus-5-5"},
+ "to": {"model": ANTHROPIC_REFUSAL_FALLBACK_MODEL},
+ },
+ {"type": "text", "text": "Done"},
+ ],
+ "stop_reason": "end_turn",
+ "stop_sequence": None,
+ "usage": {"input_tokens": 1, "output_tokens": 1},
+ },
+ )
+
+ with httpx.Client(transport=httpx.MockTransport(handler)) as http_client:
+ client = LLMClient(http_client=http_client)
+ assert client.completions("system", "user") == "Done"
+
+ assert ("fallbacks" in sent[0]) is (base_url is None)
+ assert client.model_used == ANTHROPIC_REFUSAL_FALLBACK_MODEL
+
+ def test_model_used_is_kept_per_thread(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _use_provider(monkeypatch, "openai", CHAT_DEFAULT_OPENAI)
+ mock_openai = MagicMock()
+ mock_openai.chat.completions.create.return_value = _openai_choice_response("Done")
+ client = LLMClient()
+ with patch("openai.OpenAI", return_value=mock_openai):
+ client.completions("system", "user")
+ seen: list[str | None] = []
+
+ thread = threading.Thread(target=lambda: seen.append(client.model_used))
+ thread.start()
+ thread.join()
+
+ assert seen == [None]
+ assert client.model_used == CHAT_DEFAULT_OPENAI
+
+ def test_llm_insights_name_the_model_that_wrote_them(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skillevaluator.evaluation.insights_judge import InsightsJudge
+
+ _use_provider(monkeypatch, "anthropic", "claude-opus-5-5")
+ claim = {"claim_type": "general", "severity": "warn", "evidence_case_ids": ["positive-001"]}
+ reply = json.dumps(
+ {
+ "conclusions": [{**claim, "title": "Slow", "message": "positive-001 took longer."}],
+ "recommendations": [{**claim, "title": "Clarify", "message": "Clarify positive-001's output."}],
+ }
+ )
+ mock_anthropic = MagicMock()
+ mock_anthropic.messages.create.return_value = _anthropic_fallback_response(
+ reply, {"model": ANTHROPIC_REFUSAL_FALLBACK_MODEL}
+ )
+ canonical = {"dataset": [{"id": "positive-001", "expected_skill": "calculator"}]}
+
+ with patch("anthropic.Anthropic", return_value=mock_anthropic):
+ insights = InsightsJudge().process(canonical=canonical, deterministic={})
+
+ entries = insights["conclusions"] + insights["recommendations"]
+ assert len(entries) == 2
+ assert {entry["model"] for entry in entries} == {ANTHROPIC_REFUSAL_FALLBACK_MODEL}
+
+ def test_only_llm_written_dimensions_name_a_model(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ from skillevaluator.constants import DIMENSION_MAPPING
+ from skillevaluator.evaluation.dimension_judge import compute_dimensions
+
+ _use_provider(monkeypatch, "openai", CHAT_DEFAULT_OPENAI)
+ reply = json.dumps(
+ {
+ "dimensions": [
+ {"id": dimension, "score": 0.8, "verdict": "pass", "explanation": "Strong evidence."}
+ for dimension in DIMENSION_MAPPING
+ ]
+ }
+ )
+ mock_openai = MagicMock()
+ mock_openai.chat.completions.create.side_effect = [
+ _openai_choice_response(reply),
+ _openai_choice_response("not json"),
+ ]
+ evaluators = {"accuracy": {"with_skill": 0.8, "baseline": 0.6}}
+
+ with patch("openai.OpenAI", return_value=mock_openai):
+ written = compute_dimensions(evaluators, [], 0.2)
+ deterministic = compute_dimensions(evaluators, [], 0.2)
+
+ assert {dimension["model"] for dimension in written} == {CHAT_DEFAULT_OPENAI}
+ assert not any("model" in dimension for dimension in deterministic)
diff --git a/tests/tier3/test_judge_parse_robustness.py b/tests/tier3/test_judge_parse_robustness.py
index e30318f9..4fb72446 100644
--- a/tests/tier3/test_judge_parse_robustness.py
+++ b/tests/tier3/test_judge_parse_robustness.py
@@ -752,13 +752,16 @@ def judge_env(monkeypatch):
return monkeypatch
-def _anthropic_body(text, *, stop_reason="end_turn", served_by=None):
+def _anthropic_body(text, *, stop_reason="end_turn", served_by=None, model=None):
content = []
if served_by:
content.append({"type": "fallback", "from": {"model": "requested"}, "to": {"model": served_by}})
if text:
content.append({"type": "text", "text": text})
- return {"content": content, "stop_reason": stop_reason}
+ body = {"content": content, "stop_reason": stop_reason}
+ if model:
+ body["model"] = model
+ return body
def _replay(monkeypatch, replies):
@@ -802,11 +805,29 @@ def test_template_anthropic_gateway_gets_effort_without_server_side_fallback(jud
assert "fallbacks" not in payload
-def test_template_required_judge_records_the_model_that_answered(judge_env):
+ "reply",
+ [
+ _anthropic_body(VALID_GOAL_RESPONSE, served_by="claude-opus-4-8", model="claude-opus-4-8"),
+ # Only the fallback block names the model that answered.
+ _anthropic_body(VALID_GOAL_RESPONSE, served_by="claude-opus-4-8"),
+ # The fallback block is read before the reply's top-level model.
+ _anthropic_body(VALID_GOAL_RESPONSE, served_by="claude-opus-4-8", model="claude-opus-5-5"),
+ # A turn served by sticky routing carries no fallback block.
+ _anthropic_body(VALID_GOAL_RESPONSE, model="claude-opus-4-8"),
+ ],
+ ids=[
+ "fallback-in-this-call",
+ "fallback-block-only",
+ "fallback-block-before-reply-model",
+ "sticky-fallback-turn",
+ ],
+)
+def test_template_required_judge_records_the_model_that_answered(judge_env, reply):
judge_env.setenv("SKILL_EVAL_LLM_PROVIDER", "anthropic")
judge_env.setenv("ANTHROPIC_API_KEY", "test-key")
judge_env.setenv("LLM_JUDGE_MODEL", "claude-opus-5-5")
- _replay(judge_env, [_anthropic_body(VALID_GOAL_RESPONSE, served_by="claude-opus-4-8")])
+ _replay(judge_env, [reply])
result = eval_template._call_required_judge(
"goal_accuracy", eval_template._judge_goal_accuracy_custom, "q", "gt", "agent", ""
@@ -818,6 +839,19 @@ def test_template_required_judge_records_the_model_that_answered(judge_env):
assert result["judge_fallback_used"] is True
+def test_template_anthropic_reply_model_is_ignored_without_server_side_fallback(judge_env):
+ judge_env.setenv("ANTHROPIC_API_KEY", "test-key")
+ judge_env.setenv("ANTHROPIC_BASE_URL", "https://gateway.example")
+ _replay(judge_env, [_anthropic_body("Done", model="gateway-deployment-name")])
+ provenance = {"provider": "anthropic", "model": "claude-opus-5-5"}
+
+ assert eval_template._call_anthropic("prompt", "claude-opus-5-5", 4096, 0.0, provenance=provenance) == (
+ "Done",
+ None,
+ )
+ assert provenance["model"] == "claude-opus-5-5"
+
+
def test_template_anthropic_refusal_tries_the_configured_fallback_model(judge_env):
judge_env.setenv("SKILL_EVAL_LLM_PROVIDER", "anthropic")
judge_env.setenv("ANTHROPIC_API_KEY", "test-key")
diff --git a/tests/validators/test_rubric_eval.py b/tests/validators/test_rubric_eval.py
index 825637ce..a575cf22 100644
--- a/tests/validators/test_rubric_eval.py
+++ b/tests/validators/test_rubric_eval.py
@@ -1007,3 +1007,62 @@ class TestRubricEvalValidator:
assert result.metadata["rubric_eval"]["execution_status"] == "failed"
assert result.metadata["rubric_eval"]["overall_score"] is None
assert result.metadata["rubric_eval"]["overall_pass"] is False
+
+ @pytest.mark.parametrize(
+ ("answered_by", "with_fallback_block"),
+ [("claude-opus-5-5", False), ("claude-opus-4-8", True), ("claude-opus-4-8", False)],
+ ids=["configured-model", "fallback-in-this-call", "sticky-fallback-turn"],
+ )
+ def test_json_report_names_the_model_that_scored(
+ self, tmp_path, monkeypatch: pytest.MonkeyPatch, answered_by: str, with_fallback_block: bool
+ ):
+ """A score from the server-side fallback model is labeled with that model, not the configured one.
+
+ A turn served by sticky routing carries no fallback block; only its top-level model names the fallback.
+ """
+ pytest.importorskip("anthropic")
+ httpx = pytest.importorskip("httpx")
+ from skillevaluator.reporting import JSONReporter
+
+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "anthropic")
+ monkeypatch.setenv("SKILL_EVAL_LLM_MODEL", "claude-opus-5-5")
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
+ for name in ("SKILL_EVAL_LLM_BASE_URL", "ANTHROPIC_BASE_URL"):
+ monkeypatch.delenv(name, raising=False)
+ content = [{"type": "text", "text": json.dumps({"checks": _complete_checks(), "summary": "ok"})}]
+ usage = {"input_tokens": 1, "output_tokens": 1}
+ if with_fallback_block:
+ content.insert(0, {"type": "fallback", "from": {"model": "claude-opus-5-5"}, "to": {"model": answered_by}})
+ usage["iterations"] = [
+ {"type": "message", "model": "claude-opus-5-5"},
+ {"type": "fallback_message", "model": answered_by},
+ ]
+ elif answered_by != "claude-opus-5-5":
+ usage["iterations"] = [{"type": "fallback_message", "model": answered_by}]
+
+ def handler(request):
+ return httpx.Response(
+ 200,
+ json={
+ "id": "msg_test",
+ "type": "message",
+ "role": "assistant",
+ "model": answered_by,
+ "content": content,
+ "stop_reason": "end_turn",
+ "stop_sequence": None,
+ "usage": usage,
+ },
+ )
+
+ validator = RubricEvalValidator()
+ with httpx.Client(transport=httpx.MockTransport(handler)) as http_client:
+ validator._judge = RubricJudge(http_client=http_client)
+ result = validator.validate(_write_skill(tmp_path))
+
+ data = json.loads(JSONReporter(include_timestamp=False).render_all([result]))
+ assert data["rubric_eval"]["execution_status"] == "succeeded"
+ assert data["rubric_eval"]["llm_provider"] == "anthropic"
+ assert data["rubric_eval"]["llm_model_used"] == answered_by
+ (success,) = data["results"][0]["success_details"]
+ assert success["metadata"]["llm_model_used"] == answered_by