The platform for continuously improving AI agents.
Disable OpenRouter chat proxy unless it is turned on (#342)
Pritam Sonic76cc6ac03ea
diff --git a/.env.example b/.env.exampleindex a583203b..b1965ab5 100644--- a/.env.example+++ b/.env.example@@ -38,6 +38,9 @@ CELERY_RESULT_BACKEND=redis://redis:6379/0# trace scoring and other routed model calls. Get a key at# https://openrouter.ai/keys.OPENROUTER_API_KEY=+# Chat completions proxy for frontier model ids. Judges and evals ignore this.+# Set to 1 to list those models and forward them to OpenRouter.+OPENROUTER_PROXY_ENABLED=0JEV_REQUESTS_PER_MINUTE=1200JEV_TOKENS_PER_SECOND=250000# Optional. OPENAI_API_KEY is read only by the embeddings helper in overbae/core/llms.py; no platform feature calls it.diff --git a/README.md b/README.mdindex 4266c986..a02bceb1 100644--- a/README.md+++ b/README.md@@ -75,16 +75,17 @@ The API refuses to start until every required key is set, and the error names ea| Required | Used for || --------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |-| `OPENROUTER_API_KEY` | Judges, evals, trace scoring, optimiser scoring, frontier inference |+| `OPENROUTER_API_KEY` | Judges, evals, trace scoring, optimiser scoring. Frontier chat proxy only when `OPENROUTER_PROXY_ENABLED=1` || `MODAL_TOKEN_ID`, `MODAL_TOKEN_SECRET` | Modal training and serving workers (set `MODAL_ENVIRONMENT` explicitly) || `INFERENCE_API_URL`, `INFERENCE_API_KEY` | Serving trained models — the endpoint printed by `modal deploy` and its shared secret || `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_BUCKET_NAME` | The fine-tuning checkpoint archive || `HF_TOKEN` | Gated Hugging Face base models; also set it in the Modal secret || `SANDBOX_URL`, `SANDBOX_TOKEN` | The isolated Workshop sandbox; `.env.example` and compose set local values — change the token in production |-| Optional | Effect |-| ------------------- | ----------------------------------------------------------------------- |-| `STRIPE_SECRET_KEY` | Paid plans and the credit cap; without it, usage is metered with no cap |+| Optional | Effect |+| -------------------------- | ---------------------------------------------------------------------------------------------- |+| `STRIPE_SECRET_KEY` | Paid plans and the credit cap; without it, usage is metered with no cap |+| `OPENROUTER_PROXY_ENABLED` | `1` lists frontier models on `/api/v1/models` and proxies their chat completions to OpenRouter |Fine-tuning and serving also need the Modal workers deployed (`modal deploy overbae/modal/modal_vllm_worker.py`, `register_model.py` and `modal_sft_worker.py`; native decision models also use `modal_decision_evaluation.py` and `modal_decision_serving.py`) and a Modal secret named `overmind-inference` with the AWS keys, `INFERENCE_API_KEY` and `HF_TOKEN`.diff --git a/overbae/api/completions.py b/overbae/api/completions.pyindex f856388b..441e8be4 100644--- a/overbae/api/completions.py+++ b/overbae/api/completions.py@@ -2,8 +2,8 @@Errors keep OpenAI's ``{"error": {...}}`` shape, never DRF's ``detail``, sothird-party SDKs keep working — that is why this module gates credits itself-instead of calling ``credit_gate``. Non-finetuned model ids route to OpenRouter;-deployed fine-tunes route to Modal vLLM.+instead of calling ``credit_gate``. When ``OPENROUTER_PROXY_ENABLED`` is set,+non-finetuned model ids route to OpenRouter; deployed fine-tunes route to Modal vLLM."""from __future__ import annotations@@ -450,19 +450,23 @@ def chat_completions(request: Request) -> Response | StreamingHttpResponse:isinstance(request.auth, APIToken)and request.headers.get(OPTIMISER_ROUTING_HEADER, "") == "1")- if deployed is None and is_optimiser_run:- if "/" not in model_id:+ routed = model_id+ if deployed is None and is_optimiser_run and settings.OPENROUTER_PROXY_ENABLED:+ if "/" not in routed:# A patched capability may send the bare slug it had hardcoded; the routing# branch below requires a ``provider/model`` form. Re-attach the provider# so the request routes instead of 404ing. Unresolvable names keep the# existing DeployedModel lookup / 404 path.- model_id = resolve_bare_openrouter_slug(model_id) or model_id+ routed = resolve_bare_openrouter_slug(routed) or routed# The ``openrouter/`` namespace is a platform-side alias, not an id# OpenRouter serves — strip it so the slug routes upstream.- model_id = model_id.removeprefix("openrouter/")- if deployed is None and (- is_inference_model(model_id) or (is_optimiser_run and "/" in model_id)+ routed = routed.removeprefix("openrouter/")+ if (+ deployed is None+ and settings.OPENROUTER_PROXY_ENABLED+ and (is_inference_model(routed) or (is_optimiser_run and "/" in routed))):+ model_id = routedif not getattr(settings, "OPENROUTER_API_KEY", None):return Response({@@ -1062,7 +1066,7 @@ def models_list(request: Request) -> Response:}for m in inference_models()]- if getattr(settings, "OPENROUTER_API_KEY", None)+ if settings.OPENROUTER_PROXY_ENABLED and getattr(settings, "OPENROUTER_API_KEY", None)else [])diff --git a/overbae/settings.py b/overbae/settings.pyindex 75feab19..f8fc9ab3 100644--- a/overbae/settings.py+++ b/overbae/settings.py@@ -600,6 +600,9 @@ OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")ANTHROPIC_API_KEY = os.environ.get("ANTHROPIC_API_KEY", "")GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY", "")OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY", "")+# Chat-completions proxy only. Judges, evals and scoring ignore this and keep+# using OPENROUTER_API_KEY. "1" lists frontier models and forwards them upstream.+OPENROUTER_PROXY_ENABLED = os.environ.get("OPENROUTER_PROXY_ENABLED", "0") == "1"# Feedback-channel incoming webhook; blank disables the notification.SLACK_FEEDBACK_WEBHOOK_URL = os.environ.get("SLACK_FEEDBACK_WEBHOOK_URL", "")diff --git a/tests/journeys/test_ledger.py b/tests/journeys/test_ledger.pyindex c45a1b63..a54cc5a5 100644--- a/tests/journeys/test_ledger.py+++ b/tests/journeys/test_ledger.py@@ -17,6 +17,7 @@ MODEL = "openai/gpt-4.1-mini"@pytest.fixturedef billed(settings, cli, sample_agent, fake_llm, worker, request):+ settings.OPENROUTER_PROXY_ENABLED = Truesettings.STRIPE_WEBHOOK_SECRET = WEBHOOK_SECRETif request.param == "self_host":settings.STRIPE_SECRET_KEY = ""diff --git a/tests/journeys/test_serve.py b/tests/journeys/test_serve.pyindex dbcfc398..dffc404c 100644--- a/tests/journeys/test_serve.py+++ b/tests/journeys/test_serve.py@@ -59,7 +59,6 @@ def test_serve()client = Client(api_key=key, base_url=live_api.url)fake_llm.on(lambda r: "inference.test" in r.url, "Order 42 shipped today.")- fake_llm.on(lambda r: "openrouter.ai" in r.url, "Order 42 is in transit.")served = client.chat.completions.create(model="ft-sdk-journey", messages=MESSAGES)assert served.choices[0].message.content == "Order 42 shipped today."@@ -68,8 +67,8 @@ def test_serve(model="ft-sdk-journey", messages=MESSAGES, stream=True)assert "".join(c.choices[0].delta.content or "" for c in streamed) == "Order 42 shipped today."- frontier = client.chat.completions.create(model="openai/gpt-5-mini", messages=MESSAGES)- assert frontier.choices[0].message.content == "Order 42 is in transit."+ with pytest.raises(OvermindInferenceError, match="HTTP 404"):+ client.chat.completions.create(model="openai/gpt-5-mini", messages=MESSAGES)assert "ft-sdk-journey" in {model.id for model in client.models.list().data}assert client.models.get("ft-sdk-journey").id == "ft-sdk-journey"with pytest.raises(OvermindInferenceError, match="HTTP 404"):diff --git a/tests/journeys/test_train.py b/tests/journeys/test_train.pyindex 1a0cdc8f..1521182b 100644--- a/tests/journeys/test_train.py+++ b/tests/journeys/test_train.py@@ -194,12 +194,8 @@ def test_train(base_url = re.search(r"Overmind inference base URL: (\S+)", prompt)[1]agent = sample_agent.repo / "support_desk" / "agent.py"source = agent.read_text()- agent.write_text(- source.replace(- "model=MODEL, messages=messages, tools=[LOOKUP_ORDER]",- f'model="{alias}", messages=messages, tools=[LOOKUP_ORDER]',- )- )+ # One OpenAI base URL serves the process, so triage uses the deployed alias.+ agent.write_text(source.replace("model=MODEL", f'model="{alias}"'))replies = sample_agent.run("Refund order 42 please",diff --git a/tests/test_completions_api.py b/tests/test_completions_api.pyindex 46d8f2d3..d74253e3 100644--- a/tests/test_completions_api.py+++ b/tests/test_completions_api.py@@ -150,7 +150,7 @@ class TestModelsListEndpoint:r = APIClient().get(self.URL)assert r.status_code == status.HTTP_401_UNAUTHORIZED- @override_settings(OPENROUTER_API_KEY="or-test")+ @override_settings(OPENROUTER_API_KEY="or-test", OPENROUTER_PROXY_ENABLED=True)def test_returns_finetuned_and_frontier(self):u, p = _user(), _project()_membership(u, p)@@ -176,6 +176,7 @@ class TestModelsListEndpoint:assert "base_model" in ftdef test_no_openrouter_key_omits_frontier(self, settings):+ settings.OPENROUTER_PROXY_ENABLED = Truesettings.OPENROUTER_API_KEY = ""u, p = _user(), _project()_membership(u, p)@@ -408,6 +409,19 @@ class TestChatCompletionsEndpoint:)assert r.status_code == status.HTTP_404_NOT_FOUND+ @override_settings(OPENROUTER_API_KEY="or-test", OPENROUTER_PROXY_ENABLED=False)+ def test_proxy_disabled_does_not_forward_frontier_models(self):+ u, p = _user(), _project()+ _membership(u, p)+ chat = _jwt_client(u).post(+ self.URL,+ {"model": "anthropic/claude-sonnet-5", "messages": self.MESSAGES},+ format="json",+ )+ listed = _jwt_client(u).get("/api/v1/models")+ assert chat.status_code == status.HTTP_404_NOT_FOUND+ assert all(row["finetuned"] for row in listed.json()["data"])+def test_unlisted_slug_without_optimiser_header_returns_404(self):u, p = _user(), _project()_membership(u, p)@@ -418,7 +432,7 @@ class TestChatCompletionsEndpoint:)assert r.status_code == status.HTTP_404_NOT_FOUND- @override_settings(OPENROUTER_API_KEY="or-test")+ @override_settings(OPENROUTER_API_KEY="or-test", OPENROUTER_PROXY_ENABLED=True)def test_optimiser_header_bypasses_the_allowlist_for_api_keys_only(self):u, p = _user(), _project()_membership(u, p)@@ -459,7 +473,7 @@ class TestChatCompletionsEndpoint:)assert jwt.status_code == status.HTTP_404_NOT_FOUND- @override_settings(OPENROUTER_API_KEY="or-test")+ @override_settings(OPENROUTER_API_KEY="or-test", OPENROUTER_PROXY_ENABLED=True)def test_optimiser_bare_model_name_resolves_to_full_slug(self):u, p = _user(), _project()_membership(u, p)@@ -499,7 +513,7 @@ class TestChatCompletionsEndpoint:)assert r.status_code == status.HTTP_404_NOT_FOUND- @override_settings(OPENROUTER_API_KEY="or-test")+ @override_settings(OPENROUTER_API_KEY="or-test", OPENROUTER_PROXY_ENABLED=True)def test_response_format_is_forwarded_upstream(self):u, p = _user(), _project()_membership(u, p)@@ -567,6 +581,7 @@ class TestChatCompletionsEndpoint:assert r.status_code == status.HTTP_503_SERVICE_UNAVAILABLEdef test_frontier_model_without_openrouter_key_returns_503(self, settings):+ settings.OPENROUTER_PROXY_ENABLED = Truesettings.OPENROUTER_API_KEY = ""u, p = _user(), _project()_membership(u, p)@@ -577,7 +592,7 @@ class TestChatCompletionsEndpoint:)assert r.status_code == status.HTTP_503_SERVICE_UNAVAILABLE- @override_settings(OPENROUTER_API_KEY="or-test")+ @override_settings(OPENROUTER_API_KEY="or-test", OPENROUTER_PROXY_ENABLED=True)def test_frontier_model_non_stream_proxies_to_openrouter(self):u, p = _user(), _project()_membership(u, p)@@ -606,7 +621,7 @@ class TestChatCompletionsEndpoint:assert r.status_code == status.HTTP_200_OKassert r.json()["id"] == "chatcmpl-123"- @override_settings(OPENROUTER_API_KEY="or-test")+ @override_settings(OPENROUTER_API_KEY="or-test", OPENROUTER_PROXY_ENABLED=True)def test_frontier_model_openrouter_error_returns_502(self):u, p = _user(), _project()_membership(u, p)diff --git a/tests/test_sdk_permutations.py b/tests/test_sdk_permutations.pyindex fcc2b836..c3bab3bc 100644--- a/tests/test_sdk_permutations.py+++ b/tests/test_sdk_permutations.py@@ -30,6 +30,7 @@ MESSAGES = [{"role": "user", "content": "Hello"}]@pytest.fixturedef gateway(fake_llm, settings):settings.OPENROUTER_API_KEY = "or-test"+ settings.OPENROUTER_PROXY_ENABLED = Truedef post(model_id: str, *, optimiser_header: bool = True) -> tuple[int, str]:user, project = make_user(), make_project()@@ -82,6 +83,7 @@ class TestGatewayModelNamePermutations:from overbae.models import BillingService, BillingTelemetrysettings.OPENROUTER_API_KEY = "or-test"+ settings.OPENROUTER_PROXY_ENABLED = Truefake_llm.on(lambda r: r.model == "openai/gpt-5-mini",{"content": "Hi!", "usage": {"prompt_tokens": 10, "completion_tokens": 5}},