diff --git a/README.md b/README.md index 476ff56..3efd1a2 100755 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ An evaluation function for [Lambda Feedback](https://lambdafeedback.com) that us ## How It Works -Each evaluation runs up to three LLM calls using the model specified in `configuration.params.model`. Moderation and correctness run in parallel; feedback runs after both: +Each evaluation runs up to three LLM calls using the model or [model tier](#model-tiers) specified in `configuration.params.model`. Moderation and correctness run in parallel; feedback runs after both: 1. **Moderation** — checks the student response for prompt-injection or manipulation attempts. The model returns a JSON object with a single `passes_moderation` boolean. If it is `false`, the response is marked incorrect and returned with the fixed message `"Response did not pass moderation."`; the correctness result is discarded and feedback is skipped. If the provider's own content filter rejects the submission (a 400 with `provider_error_code: content_filter`, e.g. Azure's jailbreak filter), that also counts as failing moderation. 2. **Correctness** — judges whether the response is correct given the question and answer. The model returns a JSON object with a single `is_correct` boolean. Its result is only used if moderation passed. @@ -14,7 +14,7 @@ Splitting these into separate calls keeps each prompt focused on a single concer ### Timeouts and retries -All calls in one evaluation share a 22s deadline, 3s under the worker's send timeout (`FUNCTION_WORKER_SEND_TIMEOUT=25s` in the `Dockerfile`), which in turn sits inside API Gateway's ~29s limit. Each attempt is capped at 8s, and a timeout, connection error, 408, 429 or 5xx is retried once if at least 2s of the deadline would remain. Other errors (400, 401, 402, 403, 404, content filter) are not retried. +All calls in one evaluation share a 22s deadline, 3s under the worker's send timeout (`FUNCTION_WORKER_SEND_TIMEOUT=25s` in the `Dockerfile`), which in turn sits inside API Gateway's ~29s limit. Each attempt is capped at 8s. A timeout, connection error, 408, 429 or 5xx is retried if at least 2s of the deadline would remain. Each retry moves to the next fallback model (a tier's built-in fallback, then any `fallback_models`), reusing the last model once they run out. Each step gets at least two attempts and can try every model in the list if time allows. If there is a next model, a 400 or 404 (e.g. OpenRouter's "not a valid model ID" for a retired model) or output that isn't valid JSON also moves on to it. Other errors (401, 402, 403, content filter) are not retried. JSON wrapped in a Markdown code fence or surrounded by text is accepted, since Claude models tend to add one despite `response_format`. Fallbacks are handled here rather than by OpenRouter's `models` field, because OpenRouter only falls back on errors it sees and never on our own 8s timeout. Logs record only the step, attempt timings and error descriptions — never the student's response, the answer, the prompts or the generated feedback. @@ -45,12 +45,13 @@ Requests are sent to `POST /evaluate` in µEd format. | `submission.type` | yes | Artefact type: `TEXT`, `CODE`, `MATH`, `MODEL` | | `submission.content.text` | yes (TEXT) | The student's response | | `task.referenceSolution.text` | yes | The reference answer (may be empty string) | -| `configuration.params.model` | no | OpenRouter model ID; must have a ZDR endpoint. Defaults to `openai/gpt-4o-mini` if omitted | +| `configuration.params.model` | no | A [model tier](#model-tiers) (`small`, `medium`, `large`, `reasoning`) or an OpenRouter model ID with a ZDR endpoint. Defaults to the `medium` tier if omitted | +| `configuration.params.provider` | no | With a tier `model`, use that provider's version of the tier instead: `openai`, `google`, `anthropic` or `deepseek` (see [Provider tiers](#provider-tiers)). Ignored for explicit model IDs. An unknown provider is a configuration error | | `configuration.params.correctness_decision` | no | Describes the evaluation criteria used to decide correctness. Falls back to a generic "compare response to answer" prompt if omitted (the fallback adapts depending on whether `context` is also provided) | | `configuration.params.feedback_guidance` | no | Guidance for feedback generation. Falls back to a generic constructive-feedback prompt if omitted; pass `""` to skip feedback entirely | | `configuration.params.context` | no | Question/purpose text; injected into prompts via `{{context}}` | | `configuration.params.moderation_prompt` | no | Overrides the default moderation prompt | -| `configuration.params.fallback_models` | no | List of OpenRouter model IDs to try, in order, if the primary model's provider returns an error. Each must have a ZDR endpoint | +| `configuration.params.fallback_models` | no | List of OpenRouter model IDs to try, in order, if the primary model times out, errors or doesn't exist (see [Timeouts and retries](#timeouts-and-retries)). Each must have a ZDR endpoint. When `model` is a tier, these come after the tier's built-in fallbacks | ### Prompt Template Variables @@ -97,7 +98,7 @@ Returns an array with one feedback object: }, "configuration": { "params": { - "model": "openai/gpt-4o-mini", + "model": "small", "correctness_decision": "The student must identify a risk and explain how it can cause harm.", "feedback_guidance": "" } @@ -211,6 +212,42 @@ Returns an array with one feedback object: } ``` +## Model Tiers + +Instead of a specific model ID, `model` can be a tier name. A tier stands for a capability level, and this repo decides which models sit behind it, so tasks keep working when a model is retired. + +| Tier | Primary model | Built-in fallback | Notes | +|------|---------------|-------------------|-------| +| `small` | `openai/gpt-6-luna` | `anthropic/claude-haiku-5.5` | Fastest and cheapest | +| `medium` | `google/gemini-3.8-flash` | `openai/gpt-6.1-terra` | Default when `model` is omitted | +| `large` | `anthropic/claude-sonnet-5.5` | `openai/gpt-6.2-sol` | Strongest general-purpose models | +| `reasoning` | `openai/gpt-6.2-sol` | `anthropic/claude-sonnet-5.5` | Sends `reasoning: {"effort": "low"}` | + +If the primary model times out, returns a retryable error or no longer exists, the next attempt uses the built-in fallback. Any `fallback_models` you pass are tried after it. + +### Provider tiers + +Models from different providers give noticeably different feedback. To keep one provider's style, set `provider` alongside a tier name, e.g. `{"model": "medium", "provider": "openai"}`. A provider tier's fallback comes from **the same provider**, so feedback stays consistent, but an outage at that provider fails the evaluation unless you also pass `fallback_models`. + +| Provider | `small` | `medium` | `large` | `reasoning` (effort low) | +|----------|---------|----------|---------|--------------------------| +| `openai` | `gpt-6-luna` → `gpt-5.6-luna` | `gpt-6.1-terra` → `gpt-5.6-terra` | `gpt-6.2-sol` → `gpt-6.1-sol` | `gpt-6.2-sol` → `gpt-6.1-sol` | +| `google` | `gemini-3.5-flash-lite` → `gemini-3.1-flash-lite` | `gemini-3.8-flash` → `gemini-3.7-flash` | `gemini-4-carbon` → `gemini-4-hydrogen` | `gemini-4-argon` → `gemini-4-carbon` | +| `anthropic` | `claude-haiku-5.5` → `claude-haiku-4.5` | `claude-sonnet-5.5` → `claude-sonnet-5` | `claude-opus-5.5` → `claude-opus-5` | `claude-sonnet-5.5` → `claude-sonnet-5` | +| `deepseek` | `deepseek-v4.1-flash` → `deepseek-v4-flash` | `deepseek-v4-pro-0813` → `deepseek-v4-pro` | `deepseek-v4-pro-0813` → `deepseek-v4-pro` | `deepseek-v4-pro-0813` → `deepseek-r1-0528` | + +Each ID is prefixed with the provider (e.g. `openai/gpt-6-luna`). DeepSeek has no model above V4 Pro, so its `large` repeats `medium`. Provider names must be exact and lowercase. + +### Updating a tier + +The tiers are defined in [`evaluation_function/models.py`](evaluation_function/models.py). To replace a retired model, edit `MODEL_TIERS` or `PROVIDER_TIERS` and redeploy. Every model must have a ZDR endpoint that supports `response_format`. In `MODEL_TIERS`, each tier's fallback should come from a different provider than its primary; in `PROVIDER_TIERS`, every model must come from that provider (a test enforces this). To add a provider, add a key to `PROVIDER_TIERS` covering every tier. To check all tiers against OpenRouter's live ZDR list: + +```bash +CHECK_MODEL_TIERS_ZDR=1 poetry run pytest evaluation_function/models_test.py -k zdr +``` + +Also update the table above. + ## Model Examples Models are specified as OpenRouter IDs in the format `provider/model-name`. See the full list at [openrouter.ai/models](https://openrouter.ai/models). @@ -220,7 +257,7 @@ Because every call requires [Zero Data Retention](#zero-data-retention), the mod | Provider | Model ID | Notes | |----------|----------|-------| | OpenAI | `openai/gpt-4o` | Strong general-purpose option | -| OpenAI | `openai/gpt-4o-mini` | Fast and cheap; good default | +| OpenAI | `openai/gpt-4o-mini` | Fast and cheap | | Anthropic | `anthropic/claude-sonnet-5` | Strong reasoning | | Anthropic | `anthropic/claude-haiku-4.5` | Fast Anthropic option | | Google | `google/gemini-3.5-flash` | Very fast and low cost | @@ -249,6 +286,8 @@ curl -s https://openrouter.ai/api/v1/endpoints/zdr | jq -r '.data[].model_id' | ``` evaluation_function/main.py # entrypoint — starts the RPC server evaluation_function/evaluation.py # evaluation logic +evaluation_function/models.py # model tier definitions +evaluation_function/models_test.py # model tier tests evaluation_function/preview.py # preview logic evaluation_function/evaluation_test.py # evaluation tests evaluation_function/preview_test.py # preview tests diff --git a/docs/user.md b/docs/user.md index 6a4fde8..d27c753 100644 --- a/docs/user.md +++ b/docs/user.md @@ -6,7 +6,11 @@ Makes up to three calls to the nominated LLM. The first two run at the same time - **Main prompt (`correctness_decision`)** + built-in JSON-output instruction → returns an `is_correct` Boolean - **Main prompt (`correctness_decision`)** + **feedback prompt (`feedback_guidance`)**, told the correctness verdict → returns a `feedback` string. If this call fails, the correctness verdict is still returned, with the feedback "Could not evaluate the response, please try again." -Slow or failed calls are retried once while time allows. You can also set `fallback_models` to a list of model IDs that OpenRouter tries if the nominated model's provider returns an error. +The model can be a specific OpenRouter model ID or one of the tiers `small`, `medium`, `large` or `reasoning`. Each tier points to a current model (plus a backup from another provider), and the maintainers update it when models are retired, so a tier is the safest choice for long-lived tasks. If no model is given, `medium` is used. + +Different providers give noticeably different feedback. To stick with one, add `provider` (`openai`, `google`, `anthropic` or `deepseek`) next to a tier, e.g. `"model": "medium", "provider": "openai"`. The tier's backup then comes from the same provider too. + +Slow or failed calls are retried while time allows. Each retry uses the next backup model: a tier's built-in backup first, then any model IDs you list in `fallback_models`. If the LLM is still too slow or unavailable after retrying, the function returns a retryable error (HTTP 424, code `UPSTREAM_TIMEOUT` or `UPSTREAM_UNAVAILABLE`) with a "please try again" message instead of a generic failure. Configuration problems, such as an invalid API key or model, still return HTTP 500. diff --git a/evaluation_function/dev.py b/evaluation_function/dev.py index 0668636..335d82e 100644 --- a/evaluation_function/dev.py +++ b/evaluation_function/dev.py @@ -4,7 +4,7 @@ from .evaluation import evaluation_function DEFAULT_PARAMS = { - "model": "openai/gpt-4o-mini", + "model": "medium", "correctness_decision": "You are evaluating a student's answer to the question '{{context}}'. The correct answer is '{{answer}}'. Output only 'True' if the student's answer is correct, or 'False' if it is incorrect.", "feedback_guidance": "Provide one sentence of feedback explaining why the student's answer was right or wrong.", "context": "", @@ -18,7 +18,7 @@ def dev(): parser = argparse.ArgumentParser(description="Test the evaluation function locally.") parser.add_argument("response", help="The student's response") parser.add_argument("answer", help="The correct answer") - parser.add_argument("--model", default=None, help="OpenRouter model ID (overrides params)") + parser.add_argument("--model", default=None, help="OpenRouter model ID or tier: small, medium, large, reasoning (overrides params)") parser.add_argument("--params", default=None, help="JSON string of params (merged over defaults)") args = parser.parse_args() diff --git a/evaluation_function/evaluation.py b/evaluation_function/evaluation.py index 1be592d..cb08df5 100755 --- a/evaluation_function/evaluation.py +++ b/evaluation_function/evaluation.py @@ -14,6 +14,8 @@ from lf_toolkit import EvaluationFunctionError, UpstreamTimeoutError, UpstreamUnavailableError from lf_toolkit.evaluation import Result, Params +from .models import DEFAULT_TIER, get_tier, resolve_models + load_dotenv() logger = logging.getLogger(__name__) @@ -25,8 +27,6 @@ logger.addHandler(_handler) logger.propagate = False -DEFAULT_MODEL = "openai/gpt-4o-mini" - # Every LLM call in one eval shares a deadline, 3s under the shim's 25s worker # send timeout (itself inside API Gateway's ~29s), so a slow call is retried # rather than failing the eval while there is still time to answer. Calls @@ -343,26 +343,46 @@ def expire(): return raw -def _retry_wait(error, attempt, deadline): - """Seconds to wait before retrying after error, or None to give up.""" - if not isinstance(error, (LLMTimeoutError, LLMUnavailableError)): +def _retry_wait(error, attempt, max_attempts, deadline, switching): + """Seconds to wait before retrying after error, or None to give up. + + switching is whether the next attempt uses a different model. + """ + retryable = isinstance(error, (LLMTimeoutError, LLMUnavailableError)) + # A model OpenRouter rejects (an invalid or retired ID is a 400 "not a + # valid model ID", or a 404) may be fine to replace with the next one; a + # submission blocked by a content filter is not the model's fault. + model_rejected = error.status_code in (400, 404) and not _is_input_content_filter(error) + if not retryable and not (switching and model_rejected): return None - if attempt >= LLM_MAX_ATTEMPTS: + if attempt >= max_attempts: return None - wait = LLM_RETRY_BACKOFF_SECONDS if error.retry_after is None else error.retry_after + # Retry-After applies to the model that was rate limited, not the next one. + if switching or error.retry_after is None: + wait = LLM_RETRY_BACKOFF_SECONDS + else: + wait = error.retry_after if deadline - time.monotonic() - wait < LLM_MIN_ATTEMPT_SECONDS: return None return wait -def _request_json(client, model, system_prompt, response, step, deadline, extra_body): - """Call OpenRouter, retrying transient failures while the eval deadline allows. +def _request_json(client, models, system_prompt, response, step, deadline, extra_body): + """Call OpenRouter, retrying failures while the eval deadline allows. - Returns the parsed JSON, or None if the model's output is not valid JSON. + Each retry moves to the next of models (the last is reused once they run + out), so the fallbacks are tried after a timeout or provider error on the + primary, if OpenRouter rejects the primary (e.g. a retired model ID), or + if its output isn't valid JSON. + + Returns the parsed JSON object, or None if no model gave valid JSON. Logs only the step, timings and error descriptions - never the prompt, the submission or the model's output. """ - for attempt in range(1, LLM_MAX_ATTEMPTS + 1): + max_attempts = max(LLM_MAX_ATTEMPTS, len(models)) + for attempt in range(1, max_attempts + 1): + model = models[min(attempt - 1, len(models) - 1)] + next_model = models[min(attempt, len(models) - 1)] remaining = deadline - time.monotonic() if remaining < LLM_MIN_ATTEMPT_SECONDS: error = _call_error( @@ -382,7 +402,7 @@ def _request_json(client, model, system_prompt, response, step, deadline, extra_ logger.debug( "%s attempt %d failed after %.2fs", step, attempt, time.monotonic() - started ) - wait = _retry_wait(error, attempt, deadline) + wait = _retry_wait(error, attempt, max_attempts, deadline, next_model != model) if wait is None: # A content-filtered submission is the student's doing, not a # fault, so it doesn't warrant an ERROR. @@ -390,32 +410,57 @@ def _request_json(client, model, system_prompt, response, step, deadline, extra_ logger.log(level, "%s", error.detail) raise logger.warning( - "retrying %s after %s (attempt %d/%d, %.1fs left)", - step, error.reason, attempt + 1, LLM_MAX_ATTEMPTS, deadline - time.monotonic(), + "retrying %s with %s after %s from %s (attempt %d/%d, %.1fs left)", + step, next_model, error.reason, model, attempt + 1, max_attempts, + deadline - time.monotonic(), ) time.sleep(wait) continue logger.debug("%s attempt %d took %.2fs", step, attempt, time.monotonic() - started) + data = _parse_json(raw) + if data is not None: + return data + # Only whether the output was fenced is logged, never its content. + fenced = raw.startswith("```") + if ( + next_model != model + and attempt < max_attempts + and deadline - time.monotonic() >= LLM_MIN_ATTEMPT_SECONDS + ): + logger.warning( + "retrying %s with %s after unparseable JSON from %s (fenced=%s, attempt %d/%d)", + step, next_model, model, fenced, attempt + 1, max_attempts, + ) + continue + logger.error("failed to parse %s result as JSON (model=%s, fenced=%s)", step, model, fenced) + return None + + +def _parse_json(raw): + """Parse a model's output as a JSON object, or return None. + + Tolerates a Markdown code fence or other text around the object, which + some models (e.g. Claude) add despite response_format=json_object. + """ + for candidate in (raw, raw[raw.find("{"):raw.rfind("}") + 1]): try: - return json.loads(raw) + data = json.loads(candidate) except json.JSONDecodeError: - logger.error("failed to parse %s result as JSON", step) - return None + continue + if isinstance(data, dict): + return data + return None -def _extra_body(model, fallback_models): +def _extra_body(reasoning=None): # Only route to OpenRouter endpoints with Zero Data Retention policies, - # preferring the lowest-latency one among them. + # preferring the lowest-latency one among them. Fallback models are tried + # by _request_json's retries rather than OpenRouter's `models` field, which + # doesn't act on our client timeout and hides which model answered. extra_body = {"provider": {"zdr": True, "sort": "latency"}} - # OpenRouter moves to the next model only on a provider error, not on our - # client timeout, so this supplements the retries rather than replacing them. - if ( - isinstance(fallback_models, list) - and fallback_models - and all(isinstance(m, str) for m in fallback_models) - ): - extra_body["models"] = [model, *fallback_models] + if reasoning: + extra_body["reasoning"] = reasoning return extra_body @@ -424,11 +469,11 @@ def _is_input_content_filter(error): return error.status_code == 400 and error.provider_error_code == "content_filter" -def check_moderation(client, model, moderation_prompt, response, deadline, extra_body): +def check_moderation(client, models, moderation_prompt, response, deadline, extra_body): logger.debug("running moderation check") try: data = _request_json( - client, model, moderation_prompt, response, "moderation", deadline, extra_body + client, models, moderation_prompt, response, "moderation", deadline, extra_body ) except LLMCallError as e: # A provider that blocks the submission outright has, in effect, @@ -448,7 +493,7 @@ def check_moderation(client, model, moderation_prompt, response, deadline, extra return passes_moderation -def check_correctness(client, model, correctness_decision, response, deadline, extra_body): +def check_correctness(client, models, correctness_decision, response, deadline, extra_body): logger.debug("running correctness check") correctness_system = ( f"{correctness_decision}" @@ -456,7 +501,7 @@ def check_correctness(client, model, correctness_decision, response, deadline, e '"is_correct" (boolean, true if the student response is correct, false otherwise).' ) data = _request_json( - client, model, correctness_system, response, "correctness", deadline, extra_body + client, models, correctness_system, response, "correctness", deadline, extra_body ) if data is None: return None @@ -470,7 +515,7 @@ def check_correctness(client, model, correctness_decision, response, deadline, e def generate_feedback( - client, model, correctness_decision, feedback_guidance, is_correct, response, + client, models, correctness_decision, feedback_guidance, is_correct, response, deadline, extra_body, ): logger.debug("running feedback check") @@ -481,7 +526,7 @@ def generate_feedback( '"feedback" (string, feedback for the student).' ) data = _request_json( - client, model, feedback_system, response, "feedback", deadline, extra_body + client, models, feedback_system, response, "feedback", deadline, extra_body ) if data is None: return FALLBACK_FEEDBACK @@ -591,9 +636,12 @@ def evaluation_function( try: context = params.get("context") - model = params.get('model', DEFAULT_MODEL) - logger.debug("model=%r", model) - extra_body = _extra_body(model, params.get("fallback_models")) + requested = params.get("model", DEFAULT_TIER) + provider = params.get("provider") + tier = get_tier(requested, provider) or {} + models = resolve_models(requested, params.get("fallback_models"), provider) + logger.debug("model=%r provider=%r -> %s", requested, provider, models) + extra_body = _extra_body(tier.get("reasoning")) correctness_decision_raw = params.get( 'correctness_decision', default_correctness_decision(context) @@ -619,10 +667,10 @@ def evaluation_function( # in flight when the client is closed. with ThreadPoolExecutor(max_workers=2) as pool: moderation_future = pool.submit( - check_moderation, client, model, moderation_prompt, response, deadline, extra_body + check_moderation, client, models, moderation_prompt, response, deadline, extra_body ) correctness_future = pool.submit( - check_correctness, client, model, correctness_decision, response, deadline, extra_body + check_correctness, client, models, correctness_decision, response, deadline, extra_body ) # A response that hasn't passed moderation can't be graded, so its @@ -643,7 +691,7 @@ def evaluation_function( try: feedback_text = generate_feedback( - client, model, correctness_decision, feedback_guidance, is_correct, response, + client, models, correctness_decision, feedback_guidance, is_correct, response, deadline, extra_body, ) except LLMCallError as e: diff --git a/evaluation_function/evaluation_test.py b/evaluation_function/evaluation_test.py index 44f8422..dad422c 100755 --- a/evaluation_function/evaluation_test.py +++ b/evaluation_function/evaluation_test.py @@ -20,6 +20,7 @@ LLMUnavailableError, evaluation_function, ) +from .models import DEFAULT_TIER, MODEL_TIERS, PROVIDER_TIERS BASE_PARAMS = { "model": "openai/gpt-4o-mini", @@ -213,6 +214,22 @@ def test_correctness_parse_failure(self): self.assertEqual(result["feedback"], FALLBACK_FEEDBACK) self.assertEqual(len(fake.all_calls()), 2) + def test_json_in_code_fence_or_text_is_parsed(self): + # Claude models tend to wrap JSON in a Markdown fence despite json_object. + for wrapped in (f"```json\n{CORRECT}\n```", f"Here you go: {CORRECT}"): + with self.subTest(wrapped=wrapped): + with _openrouter([MOD_PASS], [wrapped], [FEEDBACK]): + result = evaluation_function("Paris", "Paris", BASE_PARAMS).to_dict() + + self.assertTrue(result["is_correct"]) + + def test_json_that_is_not_an_object_is_a_parse_failure(self): + with _openrouter([MOD_PASS], ["true"]): + result = evaluation_function("Paris", "Paris", BASE_PARAMS).to_dict() + + self.assertFalse(result["is_correct"]) + self.assertEqual(result["feedback"], FALLBACK_FEEDBACK) + def test_moderation_parse_failure(self): with _openrouter(["not json"], [CORRECT]): result = evaluation_function("Paris", "Paris", BASE_PARAMS).to_dict() @@ -299,37 +316,84 @@ def test_uses_default_model_when_omitted(self): evaluation_function("Paris", "Paris", params) for call in fake.all_calls(): - self.assertEqual(call["model"], "openai/gpt-4o-mini") + self.assertEqual(call["model"], MODEL_TIERS[DEFAULT_TIER]["models"][0]) - def test_requests_zero_data_retention_and_low_latency(self): + def test_model_tier_uses_its_primary_model(self): + params = {**BASE_PARAMS, "model": "large"} with _openrouter([MOD_PASS], [CORRECT], [FEEDBACK]) as fake: - evaluation_function("Paris", "Paris", BASE_PARAMS) + evaluation_function("Paris", "Paris", params) for call in fake.all_calls(): + self.assertEqual(call["model"], MODEL_TIERS["large"]["models"][0]) self.assertEqual( call["extra_body"], {"provider": {"zdr": True, "sort": "latency"}} ) - def test_fallback_models(self): - params = {**BASE_PARAMS, "fallback_models": ["anthropic/claude-haiku-5-5"]} + def test_reasoning_tier_requests_reasoning(self): + params = {**BASE_PARAMS, "model": "reasoning"} + with _openrouter([MOD_PASS], [CORRECT], [FEEDBACK]) as fake: + evaluation_function("Paris", "Paris", params) + + tier = MODEL_TIERS["reasoning"] + for call in fake.all_calls(): + self.assertEqual(call["model"], tier["models"][0]) + self.assertEqual(call["extra_body"]["reasoning"], tier["reasoning"]) + + def test_provider_tier_uses_that_providers_model(self): + params = {**BASE_PARAMS, "model": "medium", "provider": "anthropic"} with _openrouter([MOD_PASS], [CORRECT], [FEEDBACK]) as fake: evaluation_function("Paris", "Paris", params) + for call in fake.all_calls(): + self.assertEqual(call["model"], PROVIDER_TIERS["anthropic"]["medium"]["models"][0]) + self.assertNotIn("reasoning", call["extra_body"]) + + def test_provider_reasoning_tier_requests_reasoning(self): + params = {**BASE_PARAMS, "model": "reasoning", "provider": "google"} + with _openrouter([MOD_PASS], [CORRECT], [FEEDBACK]) as fake: + evaluation_function("Paris", "Paris", params) + + tier = PROVIDER_TIERS["google"]["reasoning"] + for call in fake.all_calls(): + self.assertEqual(call["model"], tier["models"][0]) + self.assertEqual(call["extra_body"]["reasoning"], tier["reasoning"]) + + def test_unknown_provider_raises(self): + params = {**BASE_PARAMS, "model": "medium", "provider": "acme"} + with _openrouter([], [], []) as fake: + with self.assertRaises(ValueError): + evaluation_function("Paris", "Paris", params) + self.assertEqual(fake.all_calls(), []) + + def test_requests_zero_data_retention_and_low_latency(self): + with _openrouter([MOD_PASS], [CORRECT], [FEEDBACK]) as fake: + evaluation_function("Paris", "Paris", BASE_PARAMS) + for call in fake.all_calls(): self.assertEqual( - call["extra_body"]["models"], - ["openai/gpt-4o-mini", "anthropic/claude-haiku-5-5"], + call["extra_body"], {"provider": {"zdr": True, "sort": "latency"}} ) - self.assertTrue(call["extra_body"]["provider"]["zdr"]) - def test_invalid_fallback_models_ignored(self): - params = {**BASE_PARAMS, "fallback_models": "anthropic/claude-haiku-5-5"} + def test_fallback_models_unused_when_primary_succeeds(self): + params = {**BASE_PARAMS, "fallback_models": ["anthropic/claude-haiku-5.5"]} with _openrouter([MOD_PASS], [CORRECT], [FEEDBACK]) as fake: evaluation_function("Paris", "Paris", params) for call in fake.all_calls(): + self.assertEqual(call["model"], "openai/gpt-4o-mini") self.assertNotIn("models", call["extra_body"]) + def test_invalid_fallback_models_ignored(self): + params = {**BASE_PARAMS, "fallback_models": "anthropic/claude-haiku-5.5"} + with _openrouter([_timeout(), MOD_PASS], [CORRECT], [FEEDBACK]) as fake: + evaluation_function("Paris", "Paris", params) + + # The retry reuses the primary, as there is no valid fallback. + self.assertEqual( + [c["model"] for c in fake.calls["moderation"]], + ["openai/gpt-4o-mini", "openai/gpt-4o-mini"], + ) + def test_default_correctness_decision_without_context(self): params = {"model": "openai/gpt-4o-mini"} with _openrouter([MOD_PASS], [CORRECT], [FEEDBACK]) as fake: @@ -375,10 +439,116 @@ def test_retry_logs_warning(self): evaluation_function("Paris", "Paris", BASE_PARAMS) self.assertTrue( - any("retrying moderation after timeout after 8s (attempt 2/2" in line + any("retrying moderation with openai/gpt-4o-mini after timeout after 8s " + "from openai/gpt-4o-mini (attempt 2/2" in line for line in logs.output) ) + def test_timeout_retries_with_fallback_model(self): + params = {**BASE_PARAMS, "model": "medium"} + with _openrouter([_timeout(), MOD_PASS], [CORRECT], [FEEDBACK]) as fake: + result = evaluation_function("Paris", "Paris", params).to_dict() + + self.assertTrue(result["is_correct"]) + self.assertEqual( + [c["model"] for c in fake.calls["moderation"]], MODEL_TIERS["medium"]["models"] + ) + # The other steps weren't affected, so they stay on the primary. + self.assertEqual(fake.calls["correctness"][0]["model"], MODEL_TIERS["medium"]["models"][0]) + + def test_provider_error_retries_with_fallback_model(self): + params = {**BASE_PARAMS, "fallback_models": ["anthropic/claude-haiku-5.5"]} + error = _status_error(502, {"code": 502, "message": "down"}) + with _openrouter([error, MOD_PASS], [CORRECT], [FEEDBACK]) as fake: + evaluation_function("Paris", "Paris", params) + + self.assertEqual( + [c["model"] for c in fake.calls["moderation"]], + ["openai/gpt-4o-mini", "anthropic/claude-haiku-5.5"], + ) + + def test_missing_model_falls_back(self): + # e.g. a tier's primary model has been retired. + params = {**BASE_PARAMS, "model": "small"} + error = _status_error(404, {"code": 404, "message": "No endpoints found"}) + with _openrouter([error, MOD_PASS], [CORRECT], [FEEDBACK]) as fake: + result = evaluation_function("Paris", "Paris", params).to_dict() + + self.assertTrue(result["is_correct"]) + self.assertEqual( + [c["model"] for c in fake.calls["moderation"]], MODEL_TIERS["small"]["models"] + ) + + def test_invalid_model_id_falls_back(self): + # What OpenRouter returns for an unknown or retired model ID. + params = {**BASE_PARAMS, "model": "openai/retired", "fallback_models": ["x/backup"]} + error = _status_error(400, {"code": 400, "message": "openai/retired is not a valid model ID"}) + with _openrouter([error, MOD_PASS], [error, CORRECT], [FEEDBACK]) as fake: + result = evaluation_function("Paris", "Paris", params).to_dict() + + self.assertTrue(result["is_correct"]) + self.assertEqual( + [c["model"] for c in fake.calls["correctness"]], ["openai/retired", "x/backup"] + ) + + def test_other_errors_do_not_fall_back(self): + params = {**BASE_PARAMS, "model": "small"} + for status in (401, 402, 403): + with self.subTest(status=status): + error = _status_error(status, {"code": status, "message": "nope"}) + with _openrouter([error, MOD_PASS], [CORRECT]) as fake: + with self.assertRaises(LLMCallError): + evaluation_function("Paris", "Paris", params) + + self.assertEqual(len(fake.calls["moderation"]), 1) + + def test_content_filter_does_not_fall_back(self): + params = {**BASE_PARAMS, "model": "small"} + with _openrouter([_content_filter_error()], [CORRECT]) as fake: + result = evaluation_function("Paris", "Paris", params).to_dict() + + self.assertFalse(result["is_correct"]) + self.assertEqual(len(fake.calls["moderation"]), 1) + + def test_unparseable_json_falls_back(self): + params = {**BASE_PARAMS, "model": "large"} + with _openrouter([MOD_PASS], ["not json", CORRECT], [FEEDBACK]) as fake: + result = evaluation_function("Paris", "Paris", params).to_dict() + + self.assertTrue(result["is_correct"]) + self.assertEqual( + [c["model"] for c in fake.calls["correctness"]], MODEL_TIERS["large"]["models"] + ) + + def test_unparseable_json_from_every_model(self): + params = {**BASE_PARAMS, "model": "large"} + with _openrouter([MOD_PASS], ["not json", "still not json"]) as fake: + result = evaluation_function("Paris", "Paris", params).to_dict() + + self.assertFalse(result["is_correct"]) + self.assertEqual(result["feedback"], FALLBACK_FEEDBACK) + self.assertEqual(len(fake.calls["correctness"]), 2) + + def test_every_model_tried_while_time_allows(self): + params = {**BASE_PARAMS, "model": "large", "fallback_models": ["x/backup"]} + models = [*MODEL_TIERS["large"]["models"], "x/backup"] + with _openrouter([_timeout(), _timeout(), MOD_PASS], [CORRECT], [FEEDBACK]) as fake: + result = evaluation_function("Paris", "Paris", params).to_dict() + + self.assertTrue(result["is_correct"]) + self.assertEqual([c["model"] for c in fake.calls["moderation"]], models) + + def test_retry_after_ignored_when_switching_model(self): + params = {**BASE_PARAMS, "fallback_models": ["anthropic/claude-haiku-5.5"]} + error = _status_error(429, {"code": 429, "message": "slow down"}, {"Retry-After": "30"}) + with _openrouter([error, MOD_PASS], [CORRECT], [FEEDBACK]) as fake: + result = evaluation_function("Paris", "Paris", params).to_dict() + sleeps = [c.args[0] for c in evaluation.time.sleep.call_args_list] + + self.assertTrue(result["is_correct"]) + self.assertEqual(fake.calls["moderation"][1]["model"], "anthropic/claude-haiku-5.5") + self.assertNotIn(30.0, sleeps) + def test_no_second_attempt_without_time_left(self): params = {**BASE_PARAMS, "feedback_guidance": ""} with patch.object(evaluation, "EVAL_DEADLINE_SECONDS", 2.1), \ diff --git a/evaluation_function/models.py b/evaluation_function/models.py new file mode 100644 index 0000000..ae2bd9e --- /dev/null +++ b/evaluation_function/models.py @@ -0,0 +1,110 @@ +"""Model tiers: stable names that stand in for specific OpenRouter models. + +Tasks can set `model` to a tier name instead of an OpenRouter ID, so retiring +a model means editing this file and redeploying rather than updating every +task that used it. + +Each tier lists its primary model first, followed by built-in fallbacks. Each +retry after a timeout, provider error or missing model moves to the next one +(see evaluation._request_json). When updating a tier: + +- Every model must have a Zero Data Retention endpoint that supports + `response_format`; check with + `curl -s https://openrouter.ai/api/v1/endpoints/zdr | jq -r '.data[].model_id' | sort -u`. +- In MODEL_TIERS, the fallback should come from a different provider than the + primary, so a provider outage doesn't take out the whole tier. +- In PROVIDER_TIERS, every model must come from that provider: these tiers + exist for tasks that want one provider's style consistently, so they + deliberately don't fall back to another provider. +- A tier may set `reasoning`, passed through as OpenRouter's `reasoning` + request field. Keep the effort low: every attempt is capped at 8s. + +Tasks pick a provider tier with `provider` alongside `model`, e.g. +`{"model": "medium", "provider": "openai"}`. To add a provider, add a key to +PROVIDER_TIERS covering every tier name in MODEL_TIERS. +""" + +MODEL_TIERS = { + "small": { + "models": ["openai/gpt-6-luna", "anthropic/claude-haiku-5.5"], + }, + "medium": { + "models": ["google/gemini-3.8-flash", "openai/gpt-6.1-terra"], + }, + "large": { + "models": ["anthropic/claude-sonnet-5.5", "openai/gpt-6.2-sol"], + }, + "reasoning": { + "models": ["openai/gpt-6.2-sol", "anthropic/claude-sonnet-5.5"], + "reasoning": {"effort": "low"}, + }, +} + +PROVIDER_TIERS = { + "openai": { + "small": {"models": ["openai/gpt-6-luna", "openai/gpt-5.6-luna"]}, + "medium": {"models": ["openai/gpt-6.1-terra", "openai/gpt-5.6-terra"]}, + "large": {"models": ["openai/gpt-6.2-sol", "openai/gpt-6.1-sol"]}, + "reasoning": { + "models": ["openai/gpt-6.2-sol", "openai/gpt-6.1-sol"], + "reasoning": {"effort": "low"}, + }, + }, + "google": { + "small": {"models": ["google/gemini-3.5-flash-lite", "google/gemini-3.1-flash-lite"]}, + "medium": {"models": ["google/gemini-3.8-flash", "google/gemini-3.7-flash"]}, + "large": {"models": ["google/gemini-4-carbon", "google/gemini-4-hydrogen"]}, + "reasoning": { + "models": ["google/gemini-4-argon", "google/gemini-4-carbon"], + "reasoning": {"effort": "low"}, + }, + }, + "anthropic": { + "small": {"models": ["anthropic/claude-haiku-5.5", "anthropic/claude-haiku-4.5"]}, + "medium": {"models": ["anthropic/claude-sonnet-5.5", "anthropic/claude-sonnet-5"]}, + "large": {"models": ["anthropic/claude-opus-5.5", "anthropic/claude-opus-5"]}, + "reasoning": { + "models": ["anthropic/claude-sonnet-5.5", "anthropic/claude-sonnet-5"], + "reasoning": {"effort": "low"}, + }, + }, + "deepseek": { + "small": {"models": ["deepseek/deepseek-v4.1-flash", "deepseek/deepseek-v4-flash"]}, + # DeepSeek has no model above V4 Pro, so large repeats medium. + "medium": {"models": ["deepseek/deepseek-v4-pro-0813", "deepseek/deepseek-v4-pro"]}, + "large": {"models": ["deepseek/deepseek-v4-pro-0813", "deepseek/deepseek-v4-pro"]}, + "reasoning": { + "models": ["deepseek/deepseek-v4-pro-0813", "deepseek/deepseek-r1-0528"], + "reasoning": {"effort": "low"}, + }, + }, +} + +DEFAULT_TIER = "medium" + + +def get_tier(model, provider=None): + """The tier definition model names, or None if model isn't a tier name. + + With provider, a tier name resolves in that provider's tiers; an unknown + provider raises ValueError. provider is ignored for explicit model IDs, + which already name their provider.""" + if model not in MODEL_TIERS: + return None + if provider is None: + return MODEL_TIERS[model] + if provider not in PROVIDER_TIERS: + raise ValueError( + f"unknown provider {provider!r}; expected one of {sorted(PROVIDER_TIERS)}" + ) + return PROVIDER_TIERS[provider][model] + + +def resolve_models(model, fallback_models=None, provider=None): + """The models to try for model, in order: a tier's models, or model itself, + followed by fallback_models (ignored unless it is a list of strings).""" + tier = get_tier(model, provider) + models = list(tier["models"]) if tier else [model] + if isinstance(fallback_models, list) and all(isinstance(m, str) for m in fallback_models): + models += fallback_models + return models diff --git a/evaluation_function/models_test.py b/evaluation_function/models_test.py new file mode 100644 index 0000000..1d57677 --- /dev/null +++ b/evaluation_function/models_test.py @@ -0,0 +1,112 @@ +import json +import os +import unittest +import urllib.request + +from .models import DEFAULT_TIER, MODEL_TIERS, PROVIDER_TIERS, get_tier, resolve_models + +MODEL_ID = r"^[\w.-]+/[\w.:-]+$" + + +class TestResolveModels(unittest.TestCase): + + def test_explicit_model_passes_through(self): + self.assertEqual(resolve_models("openai/gpt-4o-mini"), ["openai/gpt-4o-mini"]) + + def test_tier_expands_to_its_models(self): + self.assertEqual(resolve_models("small"), MODEL_TIERS["small"]["models"]) + + def test_resolving_does_not_mutate_tier(self): + resolve_models("large", ["meta-llama/llama-3.3-70b-instruct"]) + self.assertNotIn("meta-llama/llama-3.3-70b-instruct", MODEL_TIERS["large"]["models"]) + resolve_models("large", ["meta-llama/llama-3.3-70b-instruct"], "google") + self.assertNotIn( + "meta-llama/llama-3.3-70b-instruct", PROVIDER_TIERS["google"]["large"]["models"] + ) + + def test_user_fallbacks_follow_tier_models(self): + self.assertEqual( + resolve_models("large", ["meta-llama/llama-3.3-70b-instruct"]), + [*MODEL_TIERS["large"]["models"], "meta-llama/llama-3.3-70b-instruct"], + ) + + def test_invalid_fallbacks_ignored(self): + self.assertEqual(resolve_models("openai/gpt-4o-mini", "x/y"), ["openai/gpt-4o-mini"]) + self.assertEqual(resolve_models("openai/gpt-4o-mini", ["x/y", 1]), ["openai/gpt-4o-mini"]) + + def test_provider_tier_expands_to_providers_models(self): + self.assertEqual( + resolve_models("medium", provider="openai"), + PROVIDER_TIERS["openai"]["medium"]["models"], + ) + + def test_user_fallbacks_follow_provider_tier_models(self): + self.assertEqual( + resolve_models("small", ["x/backup"], "deepseek"), + [*PROVIDER_TIERS["deepseek"]["small"]["models"], "x/backup"], + ) + + def test_provider_ignored_for_explicit_model(self): + self.assertEqual( + resolve_models("openai/gpt-4o-mini", provider="google"), ["openai/gpt-4o-mini"] + ) + self.assertIsNone(get_tier("openai/gpt-4o-mini", "acme")) + + def test_unknown_provider_raises(self): + with self.assertRaisesRegex(ValueError, "unknown provider"): + resolve_models("medium", provider="acme") + with self.assertRaises(ValueError): + get_tier("medium", "OpenAI") + + def test_get_tier_without_provider_uses_generic_tiers(self): + self.assertIs(get_tier("reasoning"), MODEL_TIERS["reasoning"]) + + def test_tiers_are_well_formed(self): + self.assertIn(DEFAULT_TIER, MODEL_TIERS) + for name, tier in MODEL_TIERS.items(): + with self.subTest(tier=name): + self.assertEqual(name, name.lower()) + self.assertTrue(tier["models"]) + for model in tier["models"]: + self.assertRegex(model, MODEL_ID) + self.assertNotIn(model, MODEL_TIERS) + + def test_provider_tiers_are_well_formed(self): + for provider, tiers in PROVIDER_TIERS.items(): + with self.subTest(provider=provider): + self.assertEqual(provider, provider.lower()) + self.assertEqual(set(tiers), set(MODEL_TIERS)) + for name, tier in tiers.items(): + self.assertTrue(tier["models"]) + for model in tier["models"]: + self.assertRegex(model, MODEL_ID) + # Provider tiers never fall back to another provider. + self.assertTrue(model.startswith(f"{provider}/"), (name, model)) + + +def _all_tier_models(): + for name, tier in MODEL_TIERS.items(): + for model in tier["models"]: + yield name, model + for provider, tiers in PROVIDER_TIERS.items(): + for name, tier in tiers.items(): + for model in tier["models"]: + yield f"{provider}:{name}", model + + +@unittest.skipUnless( + os.environ.get("CHECK_MODEL_TIERS_ZDR"), + "set CHECK_MODEL_TIERS_ZDR=1 to check tiers against OpenRouter's live ZDR list", +) +class TestModelTiersZdr(unittest.TestCase): + + def test_every_tier_model_has_zdr_json_endpoint(self): + with urllib.request.urlopen("https://openrouter.ai/api/v1/endpoints/zdr", timeout=30) as r: + endpoints = json.load(r)["data"] + json_capable = { + e["model_id"] for e in endpoints + if "response_format" in (e.get("supported_parameters") or []) + } + for name, model in _all_tier_models(): + with self.subTest(tier=name, model=model): + self.assertIn(model, json_capable)