Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/llm/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class ProviderConfig(BaseModel):

api_key: Optional[str] = None
base_url: Optional[str] = None
model: str = "gpt-4o"
model: str = "openai/gpt-oss-20b"
temperature: float = 0.7
max_tokens: int = 2048
timeout: float = 30.0
Expand Down
60 changes: 60 additions & 0 deletions app/llm/openrouter_models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
"""Exact model ids from OpenRouter's 2026-10-19 retirement notice.

This policy applies only to OpenRouter requests, including BYOK. It says
nothing about the availability of a model on a direct OpenAI endpoint.
"""

from __future__ import annotations

from datetime import date
import logging
from urllib.parse import urlparse

RETIREMENT_DATE = date(2027, 1, 14)
RETIRING_MODEL_IDS = frozenset(
{
"openai/gpt-4o",
"openai/gpt-4o-2024-05-13",
"openai/gpt-4o-2024-08-06",
"openai/gpt-4o-2024-11-20",
"openai/gpt-4o-mini",
"openai/gpt-4o-mini-2024-07-18",
"openai/gpt-4.1",
"openai/gpt-4.1-mini",
}
)
# Only known legacy spellings; never guess arbitrary model families or suffixes.
_RETIRING_SHORT_IDS = {model.removeprefix("openai/"): model for model in RETIRING_MODEL_IDS}


def is_openrouter_url(base_url: str) -> bool:
return urlparse(str(base_url)).hostname == "openrouter.ai"


def retiring_model_id(model: str) -> str | None:
model = (model or "").strip()
canonical = _RETIRING_SHORT_IDS.get(model, model)
return canonical if canonical in RETIRING_MODEL_IDS else None


def retirement_warning(model: str) -> str | None:
canonical = retiring_model_id(model)
if canonical is None:
return None
return (
f"OpenRouter model '{canonical}' retires on {RETIREMENT_DATE.isoformat()}, including BYOK. "
"Choose a supported model explicitly (for example openai/gpt-oss-20b); "
"old cost estimates retain the original model's rates."
)


def prepare_openrouter_model(model: str, *, today: date | None = None) -> str:
"""Keep explicit legacy choices until retirement; never silently switch a paid model."""
canonical = retiring_model_id(model)
if canonical is None:
return model
warning = retirement_warning(model)
if (today or date.today()) >= RETIREMENT_DATE:
raise ValueError(warning)
logging.getLogger(__name__).warning(warning)
return canonical
7 changes: 7 additions & 0 deletions app/llm/providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from typing import Optional

from .base import LLMProvider, LLMResponse
from .openrouter_models import is_openrouter_url, prepare_openrouter_model


class MockProvider(LLMProvider):
Expand Down Expand Up @@ -128,6 +129,12 @@ def generate(self, prompt: str, system_prompt: Optional[str] = None, **kwargs) -
"max_tokens": kwargs.get("max_tokens", self.config.max_tokens),
}

if is_openrouter_url(base_url):
try:
payload["model"] = prepare_openrouter_model(payload["model"])
except ValueError as exc:
return LLMResponse(content=f"Error: {exc}", latency_ms=0)

start = time.time()
try:
resp = self.client.post(url, json=payload, headers=headers, timeout=self.config.timeout)
Expand Down
3 changes: 3 additions & 0 deletions app/llm_engine/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from .schemas import WorkerResponse, QualityReport, LLMFixResponse
from .skill_output_fidelity import build_output_fidelity_guidance
from app.heuristics.security import scan_text
from app.llm.openrouter_models import is_openrouter_url, prepare_openrouter_model

OPENROUTER_DEFAULT_MODEL = "openai/gpt-oss-20b"
OPENROUTER_DEFAULT_BASE_URL = "https://openrouter.ai/api/v1"
Expand Down Expand Up @@ -426,6 +427,8 @@ def _call_api(
"temperature": 0.2, # Low temp for deterministic structure
"max_tokens": max_tokens,
}
if is_openrouter_url(self.base_url):
kwargs["model"] = prepare_openrouter_model(kwargs["model"])
if request_timeout_seconds is not None:
kwargs["timeout"] = request_timeout_seconds
if reasoning_effort and self._supports_swarm_reasoning_control(kwargs["model"]):
Expand Down
7 changes: 7 additions & 0 deletions app/optimizer/estimator.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
get_model_metadata,
)
from .models import OptimizationConfig
from app.llm.openrouter_models import retirement_warning

# Pricing per 1M tokens (USD), sourced from the reviewed OpenRouter snapshot.
# Keep the public mapping for older callers, but do not add a fake default rate:
Expand Down Expand Up @@ -49,6 +50,7 @@ def estimate_run_cost(config: OptimizationConfig, initial_prompt: str) -> Dict[s
Dict containing 'min_cost', 'max_cost', and a formatted 'message'.
"""
model_name = (config.model or "").strip()
warning = retirement_warning(model_name)
metadata = get_model_metadata(model_name)
pricing = MODEL_PRICING.get(canonical_model_id(model_name))

Expand Down Expand Up @@ -113,6 +115,7 @@ def estimate_run_cost(config: OptimizationConfig, initial_prompt: str) -> Dict[s
# 5. Cost Calculation. A missing rate is a real unknown, not a free call.
if pricing is None or metadata is None:
return {
"warnings": [warning] if warning else [],
"min_cost": None,
"max_cost": None,
"message": (
Expand Down Expand Up @@ -146,7 +149,11 @@ def estimate_run_cost(config: OptimizationConfig, initial_prompt: str) -> Dict[s
f"({config.model}, {total_llm_calls} calls, ~{int(final_input_tokens + final_output_tokens)} tokens)"
)

if warning:
msg += "\n" + warning

return {
"warnings": [warning] if warning else [],
"min_cost": round(min_cost, 4),
"max_cost": round(max_cost, 4),
"message": msg,
Expand Down
4 changes: 4 additions & 0 deletions app/optimizer/language_costs.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
get_model_metadata,
)
from app.text_utils import estimate_tokens
from app.llm.openrouter_models import retirement_warning

try:
import tiktoken
Expand Down Expand Up @@ -211,6 +212,9 @@ def estimate_prompt_cost(
pricing_known = metadata is not None and not warnings
pricing_source = OPENROUTER_MODELS_URL if pricing_known else None
pricing_verified_at = metadata.verified_at if metadata else None
warning = retirement_warning(resolved_model)
if warning:
warnings.append(warning)
if metadata is None:
tokenizer_name = None
else:
Expand Down
9 changes: 5 additions & 4 deletions app/optimizer/model_catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,9 @@ class OpenRouterModel:
name="OpenAI: gpt-oss-20b",
tokenizer="GPT",
context_length=131_072,
input_rate_per_million=0.03,
output_rate_per_million=0.13,
input_rate_per_million=0.018,
output_rate_per_million=0.09,
verified_at="2026-10-21",
),
"openai/gpt-oss-120b": OpenRouterModel(
id="openai/gpt-oss-120b",
Expand Down Expand Up @@ -109,8 +110,8 @@ class OpenRouterModel:
input_rate_per_million=0.30,
output_rate_per_million=2.50,
),
# These legacy aliases are still live OpenRouter ids and keep the
# evolutionary optimizer's existing configurations usable.
# Historical pricing compatibility: these ids retire on 2027-01-14.
# Keep their own prices for saved runs; never alias them to a replacement.
"openai/gpt-4o": OpenRouterModel(
id="openai/gpt-4o",
name="OpenAI: GPT-4o",
Expand Down
2 changes: 1 addition & 1 deletion app/optimizer/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class OptimizationConfig(BaseModel):
max_generations: int = 3
candidates_per_generation: int = 3
target_score: float = 1.0 # Stop if this score is reached
model: str = "gpt-4o" # Model used for the Mutation Agent
model: str = "openai/gpt-oss-20b" # Model used for the Mutation Agent
custom_system_prompt: Optional[str] = None
interactive_every: int = 0 # Pause for human input every N generations (0 = never)
adversarial_every: int = 0 # Run adversarial generation every N generations (0 = never)
Expand Down
4 changes: 2 additions & 2 deletions cli/commands/optimize.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def optimize_run(
"mock", "--provider", "-p", help="LLM provider: openai, ollama, or mock"
),
model: Optional[str] = typer.Option(
None, "--model", "-m", help="Model identifier (e.g., gpt-4o, llama3)"
None, "--model", "-m", help="Model identifier (e.g., openai/gpt-oss-20b, llama3)"
),
interactive_every: int = typer.Option(
0, "--interactive-every", "-i", help="Pause every N generations for human input (0 = never)"
Expand Down Expand Up @@ -202,7 +202,7 @@ def optimize_resume(
"mock", "--provider", "-p", help="LLM provider: openai, ollama, or mock"
),
model: Optional[str] = typer.Option(
None, "--model", "-m", help="Model identifier (e.g., gpt-4o, llama3)"
None, "--model", "-m", help="Model identifier (e.g., openai/gpt-oss-20b, llama3)"
),
):
"""
Expand Down
62 changes: 62 additions & 0 deletions docs/qa/2026-10-21-openrouter-retirement.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# OpenRouter retirement audit — 21 October 2026

Base inspected: `996efc59085cefd131ffaa2b3d62efb276211133` (`main`). Open PRs were checked; none covered this migration. No production traffic or deployed environment settings were inspected.

## Dependency classification

| Surface | Evidence / behavior | Change |
| --- | --- | --- |
| `app/llm_engine/client.py` / `WorkerClient._call_api` | Actual SDK request path for cloud product features; default `openai/gpt-oss-20b`, configurable via env/model override | Preserve default; apply retirement policy to the effective request model only when destination hostname is `openrouter.ai` |
| `app/llm/base.py` / `ProviderConfig` | Generic provider configuration had bare `gpt-4o` default | Align new configurations with existing OpenRouter default `openai/gpt-oss-20b` |
| `app/llm/providers.py` / `OpenAIProvider` | Class name means OpenAI-compatible HTTP, but default endpoint/key are OpenRouter | Normalize exact known retiring short ids; warn before deadline; return actionable error without posting at/after deadline |
| `app/llm/factory.py` | Already defaults its OpenAI-compatible cloud configuration to GPT-OSS-20B | Preserve env/config overrides |
| `app/optimizer/models.py` / `OptimizationConfig` | `gpt-4o` default influences estimates and persisted run metadata, not necessarily the provider actually executing mutations | Set new configuration default to GPT-OSS-20B; deserialize existing explicit values unchanged |
| `app/optimizer/model_catalog.py` | Reviewed price/tokenizer snapshot, not a list of executed calls or a runtime model selector | Keep GPT-4o and mini rows and aliases for saved estimates; mark compatibility comment; refresh only GPT-OSS-20B price/date |
| `language_costs.py`, `estimator.py`, `costs.py` | Prompt/run estimates and accumulated estimated cost | Add retirement warnings to user-facing estimates; retain original legacy-model prices, never replacement prices |
| `web/app/benchmark/models.json` | Frontend model metadata snapshot; current defaults already GPT-OSS-20B | Match refreshed GPT-OSS-20B backend rates and verification date |
| Tests using GPT-4o strings | Offline fixtures for historical pricing, persistence, reporting and validation | Keep compatibility fixtures; add exact retirement/date/host-scope tests |
| `examples/openai_pipe.py` | Optional direct `OpenAI()` example, using `OPENAI_API_KEY`; not the default OpenRouter integration | Leave unchanged. This notice is not sufficient evidence to change a direct OpenAI integration. |
| CLI `--model` help | Suggested an obsolete GPT-4o identifier | Replace example with the supported cloud default |

All eight exact ids in the OpenRouter 19 October notice are recognized, together with their exact unqualified legacy spellings. The notification includes dated GPT-4o snapshots and OpenRouter BYOK. No family-prefix migration is used. This change does not establish that direct OpenAI requests retire on the same date.

## Compatibility policy

- New defaults use `openai/gpt-oss-20b`, matching current cloud behavior rather than introducing another model family.
- Existing explicit choices are not silently switched. Before 14 January 2027, a retiring short spelling is sent as its original provider-qualified id with a warning. At/after the deadline the request is rejected locally with a supported-model instruction, without spending an API call.
- Only the exact destination hostname `openrouter.ai` receives this policy. Explicit direct OpenAI or other compatible endpoints retain their supplied model ids. Proxy/custom domains cannot be identified reliably as OpenRouter and remain the operator's responsibility.
- Saved runs deserialize their original `model` strings unchanged. Legacy `gpt-4o` / `gpt-4o-mini` price aliases still describe those models, not a substituted model. Dated variants without a reviewed price remain unknown; no guessed price is added.
- Prompt and evolutionary-run estimates now warn about retirement. Estimates for old models can still be used as historical estimates after the deadline; this is not an availability claim.

## Models and costs

The Models API was retrieved on 21 October 2026. GPT-OSS-20B's base text rates were $0.018 input / $0.09 output per million tokens, replacing the September snapshot's $0.03 / $0.13 in both backend and frontend records. Other catalog records retain their own September verification dates; they have not been relabeled as current.

Candidate alternatives (USD per million input / output tokens):

| Model | Rates | Relevant compatibility |
| --- | --- | --- |
| `openai/gpt-oss-20b` | $0.018 / $0.09 | Existing default; JSON response format and current request behavior already supported. Lowest-change choice for Compiler. |
| `openai/gpt-6-luna` | $0.10 / $0.50 | Text/JSON/structured outputs; no temperature; optional reasoning supports `none`. Suitable candidate for bounded JSON tasks only after adapting Compiler's sampling parameters and testing outputs. Not substituted here. |
| `openai/gpt-5.6-luna` | $0.20 / $1.20 | Existing catalog/benchmark option; no temperature, optional reasoning. Its existing selection is preserved, but no new claim that all current Compiler requests are compatible is made. |
| `google/gemini-2.5-flash-lite` | $0.10 / $0.40 | JSON/structured outputs and temperature supported. Different model/provider behavior needs task-specific evaluation before changing defaults. |

Luna's catalog includes increased pricing above 272,000 prompt tokens; cached input and service tiers also vary. The existing static price estimator does not model all routing, long-context tiers or reasoning usage. Provider-reported usage/cost remains separate. Adding more flat-price aliases would hide this limitation, so no new Luna pricing entry or automatic migration was introduced.

Sources: [Models API](https://openrouter.ai/api/v1/models), [GPT-OSS-20B](https://openrouter.ai/openai/gpt-oss-20b), [GPT-6 Luna](https://openrouter.ai/openai/gpt-6-luna), [Luna endpoints](https://openrouter.ai/api/v1/models/openai/gpt-6-luna/endpoints), [GPT-5.6 Luna](https://openrouter.ai/openai/gpt-5.6-luna), [Gemini Flash Lite](https://openrouter.ai/google/gemini-2.5-flash-lite).

## Pre-existing limits kept out of this patch

`cli/commands/optimize.py` passes its model string as the factory's `config` positional argument. `get_provider` expects `ProviderConfig`, so an explicit CLI `--model` may fail initialization and fall back to mock; run-cost metadata can also differ from the provider's effective env-selected model. Resume reloads saved configuration. This is not fixed by changing a default and needs a separate focused CLI configuration/reporting change. No successful live CLI model migration is claimed.

No API key was available, so paid completions, JSON-output quality and production usage are unverified. The PR remains draft. Reviewers should explicitly replace retiring deployment/env selections before the deadline, then run an authenticated compile/optimize smoke check. No merge or deployment was performed.

## Validation

- `python -m pytest tests/ -q`: **2,758 passed, 5 skipped**, 30 existing collection/deprecation warnings; 152.56 seconds. Live provider tests are opt-in and were skipped.
- Focused provider/catalog/estimator suite: **114 passed, 5 skipped**. Additional retirement/evolution/report/API subset: **46 passed**. Final new retirement test file: **20 passed**. These overlap with the full suite and are not additional unique tests.
- `npm run test -- --run app/benchmark/page.test.tsx app/__tests__/optimizer-page.test.tsx`: **21 passed**, 2 test files.
- `npm run build`: passed, including TypeScript checks and static generation.
- Ruff checks on all changed Python files and `git diff --check`: passed.
- The first backend run failed because the environment's SOCKS proxy required `socksio`; installing it in the isolated test environment resolved those failures. No dependency manifest was changed for this environment-specific package.
- No authenticated upstream completion or production end-to-end check was run.
8 changes: 4 additions & 4 deletions tests/optimizer/test_language_costs.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ def test_turkish_prompt_can_cost_more_tokens_than_english_equivalent():
def test_default_openrouter_gpt_oss_20b_pricing_is_applied():
estimate = estimate_prompt_cost("hello world", token_count_override=1_000_000)

assert estimate.input_rate_per_million == pytest.approx(0.03)
assert estimate.output_rate_per_million == pytest.approx(0.13)
assert estimate.estimated_cost_usd == pytest.approx(0.03)
assert estimate.input_rate_per_million == pytest.approx(0.018)
assert estimate.output_rate_per_million == pytest.approx(0.09)
assert estimate.estimated_cost_usd == pytest.approx(0.018)
assert estimate.pricing_known is True
assert estimate.pricing_verified_at == "2026-09-12"
assert estimate.pricing_verified_at == "2026-10-21"


def test_gemini_flash_lite_pricing_is_applied():
Expand Down
2 changes: 1 addition & 1 deletion tests/test_llm_providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
class TestProviderConfig:
def test_default_values(self):
config = ProviderConfig()
assert config.model == "gpt-4o"
assert config.model == "openai/gpt-oss-20b"
assert config.temperature == 0.7
assert config.max_tokens == 2048

Expand Down
Loading
Loading