diff --git a/app/.env.example b/app/.env.example index feda3fbc..599ab73d 100644 --- a/app/.env.example +++ b/app/.env.example @@ -48,13 +48,13 @@ LLM_JUDGE_PROVIDER= LLM_JUDGE_PROTOCOL= # The model of the LLM judgement, as its provider names it (on OpenRouter, vendor/model). It is asked the same questions as Decision and answers them as JSON; its numbers are what it states, so a choice or a score carries no confidence. LLM_JUDGE_MODEL= -# Additions to the OpenRouter provider, as a JSON object without the key: endpoints of protocols the preset does not list, {"endpoints": {"": "/path" or "https://full/url"}}. In the environment, a partial object merged over this one. +# Unsupported overrides for OpenRouter. Use a Custom provider to configure endpoints. OPENROUTER= -# Additions to the OpenAI provider, as a JSON object without the key: endpoints of protocols the preset does not list, {"endpoints": {"": "/path" or "https://full/url"}}. In the environment, a partial object merged over this one. +# Unsupported overrides for OpenAI. Use a Custom provider to configure endpoints. OPENAI= -# Additions to the Anthropic provider, as a JSON object without the key: endpoints of protocols the preset does not list, {"endpoints": {"": "/path" or "https://full/url"}}. In the environment, a partial object merged over this one. +# Unsupported overrides for Anthropic. Use a Custom provider to configure endpoints. ANTHROPIC= -# Additions to the TypeSafe provider, as a JSON object without the key: endpoints of protocols the preset does not list, {"endpoints": {"": "/path" or "https://full/url"}}. In the environment, a partial object merged over this one. +# Unsupported overrides for TypeSafe. Use a Custom provider to configure endpoints. TYPESAFE= # --- Run hosts --- diff --git a/app/nullius/providers.py b/app/nullius/providers.py index 0bffdbdd..37bd1662 100644 --- a/app/nullius/providers.py +++ b/app/nullius/providers.py @@ -42,9 +42,8 @@ "decisions": {"label": "OpenRouter Decisions", "path": "/decisions", "auth": "authorization"}, "openai-decisions": {"label": "OpenAI Decisions", "path": "/decisions", "auth": "authorization"}, } -# A preset is a provider record whose name, base, key and known endpoints are fixed here. The user adds -# only endpoints of other protocols, in the setting ``setting`` (``settings.is_record``); its key is -# the secret setting ``key``. Its ``endpoints`` are also the protocols it serves. +# A preset has fixed name, base, key setting and endpoints. Custom providers configure their own +# endpoints. A preset's endpoints are also the protocols it serves. PRESETS = { "openrouter": {"name": "OpenRouter", "base": "https://openrouter.ai/api/v1", "key": "OPENROUTER_API_KEY", "endpoints": {"chat": "/chat/completions", "responses": "/responses", "systemone": "/systemone", @@ -72,14 +71,12 @@ def key_setting(choice: str) -> str: return PRESETS[p]["key"] if p in PRESETS else endpoint_vars(e)[1] -def _entry_problem(entry, host: str = "") -> Optional[str]: +def _entry_problem(entry) -> Optional[str]: """Why ``entry`` cannot be an endpoint: a path starting with one slash, without a ``..`` segment, or a - full URL that passes the checks a base gets; on ``host`` only, when one is given (a preset's own).""" + full URL that passes the checks a base gets.""" if not isinstance(entry, str): return "a path or a URL" if entry.startswith(("http://", "https://")): - if host and urllib.parse.urlsplit(entry).hostname != host: - return f"a path, or a URL on {host}: the preset's key is sent there" return settings.endpoint_url_problem(entry) if not entry.startswith("/") or entry.startswith("//") or any(c.isspace() or ord(c) < 32 for c in entry): return "a path that starts with / or an http(s) URL" @@ -91,17 +88,15 @@ def _entry_problem(entry, host: str = "") -> Optional[str]: def record_problem(name: str, value: str) -> Optional[str]: """Why ``value`` cannot be the record setting ``name``, or None. A JSON object of ``FIELDS``: a name, a base the checks of an endpoint's URL pass, the key's setting name (only its own: never a key), and - endpoints by protocol, each a path, a full URL or null. A preset's fields and known endpoints are fixed; - a full URL it adds is on its own host, the one its key is for.""" + endpoints by protocol, each a path, a full URL or null. Presets accept no overrides.""" rec = settings.json_object(value) if rec is None: return 'a JSON object, such as {"base": "https://…/v1"}' preset = next((p for p in PRESETS if p.upper() == name), "") if set(rec) - set(FIELDS): return "an object of " + ", ".join(FIELDS) - fixed = [k for k in ("name", "base", "key") if preset and k in rec] - if fixed: - return f"a record without {', '.join(fixed)}: they are fixed for {PRESETS[preset]['name']}" + if preset and rec: + return f"a custom provider instead: endpoints and fields are fixed for {PRESETS[preset]['name']}" if rec.get("name") is not None and (not isinstance(rec["name"], str) or not 0 < len(rec["name"]) <= 400 or any(ord(c) < 32 for c in rec["name"])): return "a record whose name is one line of 400 characters at most" @@ -117,9 +112,7 @@ def record_problem(name: str, value: str) -> Optional[str]: for proto, entry in ends.items(): if proto not in PROTOCOLS: return f"a record whose endpoints are some of {', '.join(PROTOCOLS)}" - if preset and proto in PRESETS[preset]["endpoints"]: - return f"a record without the {proto} endpoint: it is fixed for {PRESETS[preset]['name']}" - why = entry is not None and _entry_problem(entry, urllib.parse.urlsplit(PRESETS[preset]["base"]).hostname if preset else "") + why = entry is not None and _entry_problem(entry) if why: return f"a record whose {proto} endpoint is {why}" return None @@ -134,8 +127,8 @@ def join(base: str, entry: str) -> str: def record(choice: str, env=None) -> dict: - """A provider's record, the three layers merged field by field (the later wins): the preset in code, - the file's and then the environment's record setting (``settings.load`` merged those two). A custom + """A preset's fixed record, or a custom record from file and environment (``settings.load`` merges + those two field by field, the environment winning). A custom provider reads its old settings where its record says nothing (a null says: none): MODEL__NAME as ``name``, MODEL__API_URL (MODEL_API_URL, unnamed) as ``base``; ``ignored`` names an old setting the record overrides. ``{id, name, base, key, endpoints, preset, ignored}``, where ``key`` is a setting name only.""" @@ -145,10 +138,7 @@ def record(choice: str, env=None) -> dict: own = settings.json_object(env.get(setting_of(choice))) if setting_of(choice) else None if own is not None and record_problem(setting_of(choice), json.dumps(own)): own = None # a record that does not validate is no record - rec = settings.merge_patch({k: v for k, v in (preset or {}).items()}, own or {}) - if preset: - rec.update({k: preset[k] for k in ("name", "base", "key")}, - endpoints={**(rec.get("endpoints") or {}), **preset["endpoints"]}) + rec = dict(preset) if preset else dict(own or {}) ignored = [] if not preset: old_name, old_url = (f"MODEL_{e}_NAME" if e else ""), endpoint_vars(e)[0] diff --git a/app/nullius/settings.py b/app/nullius/settings.py index 9c964a97..290b93cf 100644 --- a/app/nullius/settings.py +++ b/app/nullius/settings.py @@ -217,8 +217,7 @@ def validate(self, value: str) -> Optional[str]: Variable("LLM_JUDGE_PROVIDER", GROUPS[0], "The provider of the LLM judgement, the second judgement beside Decision: openrouter, openai, anthropic, custom (the endpoint at MODEL_API_URL) or custom: (a custom provider), asked with that provider's own key and base from the model providers above. local and local: are read as custom. Unset: the first of them that is set, Anthropic last.", "llmprovider"), Variable("LLM_JUDGE_PROTOCOL", GROUPS[0], "The protocol the LLM judge is asked in, on a provider that serves both: chat (OpenAI Chat Completions) or messages (Anthropic Messages). Unset, or one the provider does not serve: the first the provider serves, chat before messages.", "llmprotocol"), Variable("LLM_JUDGE_MODEL", GROUPS[0], "The model of the LLM judgement, as its provider names it (on OpenRouter, vendor/model). It is asked the same questions as Decision and answers them as JSON; its numbers are what it states, so a choice or a score carries no confidence.", "model"), - *(Variable(name, GROUPS[0], f"Additions to the {title} provider, as a JSON object without the key: endpoints of protocols the preset does not list, " - '{"endpoints": {"": "/path" or "https://full/url"}}. In the environment, a partial object merged over this one.', "provider") + *(Variable(name, GROUPS[0], f"Unsupported overrides for {title}. Use a Custom provider to configure endpoints.", "provider") for name, title in (("OPENROUTER", "OpenRouter"), ("OPENAI", "OpenAI"), ("ANTHROPIC", "Anthropic"), ("TYPESAFE", "TypeSafe"))), Variable("AGENT_KEYS", GROUPS[2], "The names of the agent keys this file holds, comma-separated: the keys an agent needs of its own vendor, beside the model's (Cursor's CLI agent a CURSOR_API_KEY, Copilot's a GH_TOKEN). Each is a line of its own in this file. A Harbor run gets every one of them in its environment - over stdin to a host - and a Nullius standard run's never; none is ever written into a recipe or a log.", "envnames"), Variable("HOSTS", GROUPS[1], "Machines a recipe can run on, over ssh: an alias from ~/.ssh/config, or user@host[:port][:/path/to/key]. Only the name is stored; keys stay where they are.", "hosts", "user@host[:port][:/path/to/key]"), diff --git a/app/tests/test_execution.py b/app/tests/test_execution.py index 5cb81d6f..88cea537 100644 --- a/app/tests/test_execution.py +++ b/app/tests/test_execution.py @@ -98,7 +98,8 @@ def test_a_run_on_a_named_endpoint_gets_its_url_and_key_alone(self): that one's URL and key, never the default's or another endpoint's; a run on one that is gone fails before it starts, and is never sent to another.""" held = {"MODEL_API_URL": "http://default/v1", "MODEL_API_KEY": "sk-held-default", - "MODEL_GPU_NAME": "GPU box", "MODEL_GPU_API_URL": "http://gpu/v1", "MODEL_GPU_API_KEY": "sk-held-gpu", + "MODEL_GPU_NAME": "GPU box", "MODEL_GPU_API_URL": "http://old-gpu/v1", "MODEL_GPU_API_KEY": "sk-held-gpu", + "MODEL_GPU": json.dumps({"base": "http://gpu/v1", "endpoints": {"messages": "/messages"}}), "MODEL_LAPTOP_API_URL": "http://laptop/v1", "MODEL_LAPTOP_API_KEY": "sk-held-laptop"} url_var, key_var = providers.endpoint_vars("GPU") with mock.patch.dict(os.environ, held): @@ -112,6 +113,11 @@ def test_a_run_on_a_named_endpoint_gets_its_url_and_key_alone(self): env = dict(l.split("=", 1) for l in (self.tmp / "gpu" / "run-run.log").read_text().splitlines() if "=" in l) self.assertEqual({k: v for k, v in env.items() if v.startswith("sk-held-")}, {n: "sk-held-gpu" for n in execution.KEY_NAMES}) self.assertEqual({k: v for k, v in env.items() if v.startswith("http://")}, {n: "http://gpu/v1" for n in execution.URL_NAMES}) + from nullius.standard import cli + from nullius.standard.runner import run + handed = cli.run_env("custom", env) + self.assertEqual(run.provider_endpoint("custom", handed), ("http://gpu/v1", "sk-held-gpu")) + self.assertEqual(run.key_header("custom", {"model": {"apis": ["messages"]}}, handed), "x-api-key") self.assertEqual((gone.state, gone.step), ("failed", "credentials")) self.assertIn("MODEL_GONE_API_URL is not set in Settings", gone.error) diff --git a/app/tests/test_judge_decisions.py b/app/tests/test_judge_decisions.py index d12e082c..c7afd0a0 100644 --- a/app/tests/test_judge_decisions.py +++ b/app/tests/test_judge_decisions.py @@ -80,11 +80,11 @@ def test_a_chosen_protocol_wins_where_the_provider_serves_it_else_the_automatic_ self.assertEqual(got(dict(router, DECISION_PROTOCOL="openai-decisions")), ("systemone", "https://openrouter.ai/api/v1/systemone")) # not served: automatic self.assertEqual(client.decision_judge_providers(dict(router, DECISION_PROTOCOL="decisions"))["openrouter"]["protocol"], "decisions") self.assertEqual(client.decision_judge_providers(router)["openrouter"]["listed"], ["systemone", "decisions"]) - both = {"ANTHROPIC_API_KEY": "k", "ANTHROPIC": '{"endpoints": {"chat": "/chat/completions"}}', "LLM_JUDGE_PROVIDER": "anthropic", "LLM_JUDGE_MODEL": "m"} + both = {"MODEL_GW_API_KEY": "k", "MODEL_GW": '{"base": "https://gw.example/v1", "endpoints": {"chat": "/custom/chat", "messages": "/custom/messages"}}', "LLM_JUDGE_PROVIDER": "custom:GW", "LLM_JUDGE_MODEL": "m"} llm = lambda env: (client.llm_judge(env).protocol, client.llm_judge(env).url) - self.assertEqual(llm(both), ("chat", "https://api.anthropic.com/v1/chat/completions")) # unset: chat before messages - self.assertEqual(llm(dict(both, LLM_JUDGE_PROTOCOL="messages")), ("messages", "https://api.anthropic.com/v1/messages")) - self.assertEqual(client.llm_providers(both)["anthropic"]["listed"], ["chat", "messages"]) + self.assertEqual(llm(both), ("chat", "https://gw.example/v1/custom/chat")) # unset: chat before messages + self.assertEqual(llm(dict(both, LLM_JUDGE_PROTOCOL="messages")), ("messages", "https://gw.example/v1/custom/messages")) + self.assertEqual(client.llm_providers(both)["custom:GW"]["listed"], ["chat", "messages"]) self.assertEqual(llm({"OPENROUTER_API_KEY": "k", "LLM_JUDGE_MODEL": "m", "LLM_JUDGE_PROTOCOL": "messages"}), ("chat", "https://openrouter.ai/api/v1/chat/completions")) # not served: automatic for name, spoken in (("LLM_JUDGE_PROTOCOL", client.LLM_PROTOCOLS), ("DECISION_PROTOCOL", client.DECISION_PROTOCOLS)): diff --git a/app/tests/test_provider_pins.py b/app/tests/test_provider_pins.py index 7cccb86e..6a0f1110 100644 --- a/app/tests/test_provider_pins.py +++ b/app/tests/test_provider_pins.py @@ -32,9 +32,12 @@ def test_openrouter_protocol_checks_and_serving_pins_both_apply(self): with self.assertRaisesRegex(run.Refused, "does not serve"): run.Run(self.bench, self.agent, **options) env["OPENROUTER"] = json.dumps({"endpoints": {"messages": "/messages"}}) + with self.assertRaisesRegex(run.Refused, "does not serve"): + run.Run(self.bench, self.agent, **options) + self.agent["model"]["apis"] = ["chat"] started = run.Run(self.bench, self.agent, **options) self.assertEqual((started.base, started.key_header, started.serving), - (providers.PRESETS["openrouter"]["base"], "x-api-key", {"m": ["prov-a"]})) + (providers.PRESETS["openrouter"]["base"], "authorization", {"m": ["prov-a"]})) with patch.dict(os.environ, env): compiled = recipe.compile(recipes.a_recipe(model="m", served_by={"model": ["prov-a"]}), self.defs) self.assertEqual(compiled["errors"], []) diff --git a/app/tests/test_provider_registry.py b/app/tests/test_provider_registry.py index 72aded9a..131c4d87 100644 --- a/app/tests/test_provider_registry.py +++ b/app/tests/test_provider_registry.py @@ -20,24 +20,20 @@ class Records(unittest.TestCase): - def test_a_preset_is_its_fixed_fields_and_the_user_adds_only_other_protocols(self): - env = {"OPENROUTER": json.dumps({"endpoints": {"messages": "/messages"}})} - rec = providers.record("openrouter", env) - self.assertEqual((rec["name"], rec["base"], rec["key"]), ("OpenRouter", "https://openrouter.ai/api/v1", "OPENROUTER_API_KEY")) - self.assertEqual(providers.url(rec, "messages"), "https://openrouter.ai/api/v1/messages") - self.assertEqual(providers.url(rec, "decisions"), "https://openrouter.ai/api/alpha/decisions") # outside its base: a full URL - for fixed in ({"base": "https://proxy/v1"}, {"name": "X"}, {"key": "OTHER_API_KEY"}, {"endpoints": {"chat": "/x"}}): - self.assertIn("fixed", providers.record_problem("OPENROUTER", json.dumps(fixed)), fixed) - self.assertEqual(providers.record("openrouter", {"OPENROUTER": json.dumps(fixed)})["base"], "https://openrouter.ai/api/v1") - - def test_a_preset_adds_a_full_url_only_on_its_own_host(self): - for name, proto, bad in (("TYPESAFE", "decisions", "https://evil.example/d"), ("OPENROUTER", "messages", "https://evil.example/m"), - ("OPENAI", "messages", "https://api.openai.com.evil.example/m")): - why = providers.record_problem(name, json.dumps({"endpoints": {proto: bad}})) - self.assertIn("the preset's key is sent there", why or "", name) - self.assertNotIn("evil", providers.url(providers.record(name.lower(), {name: json.dumps({"endpoints": {proto: bad}})}), proto)) - self.assertIsNone(providers.record_problem("OPENROUTER", json.dumps({"endpoints": {"messages": "https://openrouter.ai/api/v1/messages"}}))) - self.assertIsNone(providers.record_problem("TYPESAFE", json.dumps({"endpoints": {"decisions": "/decisions"}}))) + def test_presets_ignore_and_reject_overrides_for_every_protocol(self): + for provider, preset in providers.PRESETS.items(): + for proto in providers.PROTOCOLS: + for entry in ("/other", "https://other.example/path", None): + with self.subTest(provider=provider, protocol=proto, entry=entry): + value = json.dumps({"endpoints": {proto: entry}}) + self.assertIn("custom provider", providers.record_problem(provider.upper(), value)) + rec = providers.record(provider, {provider.upper(): value}) + self.assertEqual(rec["endpoints"], preset["endpoints"]) + self.assertEqual(providers.serves(rec, proto), proto in preset["endpoints"]) + for fixed in ({"base": "https://proxy/v1"}, {"name": "X"}, {"key": "OTHER_API_KEY"}): + self.assertIn("fixed", providers.record_problem("OPENROUTER", json.dumps(fixed))) + self.assertEqual(providers.record("openrouter", {"OPENROUTER": json.dumps(fixed)})["base"], + providers.PRESETS["openrouter"]["base"]) def test_a_custom_record_merges_per_protocol_and_null_removes(self): file = {"name": "Gateway", "base": "https://gw.example/v1", "endpoints": {"chat": "/chat/completions", "decisions": "/alpha/decisions"}} @@ -159,6 +155,20 @@ def setUp(self): saved = kept.copy() self.addCleanup(lambda k=kept, s=saved: (k.clear(), k.update(s))) + def test_saved_preset_overrides_are_reported_and_do_not_change_protocols(self): + for provider, preset in providers.PRESETS.items(): + name = provider.upper() + with self.subTest(provider=provider), patch.dict(os.environ): + os.environ.pop(name, None) + value = json.dumps({"endpoints": {p: "/override" for p in providers.PROTOCOLS}}) + Path(self.file).write_text(json.dumps({name: value})) + settings.load(self.file) + self.assertEqual(providers.record(provider)["endpoints"], preset["endpoints"]) + state = settings.state(settings.BY_NAME[name], settings.in_file(self.file)) + self.assertIn("custom provider", state["problem"]) + with self.assertRaises(ValueError): + settings.save(self.file, name, value) + def test_the_environment_sets_only_its_fields(self): Path(self.file).write_text(json.dumps({"MODEL_GW": json.dumps({"name": "Gateway", "base": "https://gw.example/v1", "endpoints": {"chat": "/c", "decisions": "/d"}})})) diff --git a/app/ui_tests/evidence/provider-endpoints/after.png b/app/ui_tests/evidence/provider-endpoints/after.png new file mode 100644 index 00000000..d0b3ee21 Binary files /dev/null and b/app/ui_tests/evidence/provider-endpoints/after.png differ diff --git a/app/ui_tests/evidence/provider-endpoints/before.png b/app/ui_tests/evidence/provider-endpoints/before.png new file mode 100644 index 00000000..8a2eb4ba Binary files /dev/null and b/app/ui_tests/evidence/provider-endpoints/before.png differ diff --git a/app/ui_tests/test_settings_page.py b/app/ui_tests/test_settings_page.py index eac6ec3b..72b491aa 100644 --- a/app/ui_tests/test_settings_page.py +++ b/app/ui_tests/test_settings_page.py @@ -117,8 +117,8 @@ def test_every_variable_is_listed_with_its_state_and_no_secret_value(self): settings.load(self.env_file) html = self.page() for v in settings.VARIABLES: - added = v.kind == "provider" and next(p for p in providers.PROTOCOLS if p not in providers.PRESETS[v.name.lower()]["endpoints"]) - self.assertIn(f'id="{v.name}.endpoints.{added}"' if added else f'id="{v.name}"', html) # a preset's record: a row it may add + if v.kind != "provider": + self.assertIn(f'id="{v.name}"', html) self.assertIn('title="Held by the process', html) # the token, from the process self.assertEqual(html.count('********'), 3) # the token and the OpenRouter and OpenAI keys: eight stars each, self.assertNotIn("characters", html) # never their length @@ -157,7 +157,10 @@ def test_a_judge_s_protocol_is_a_quiet_line_unless_its_provider_lists_two(self): self.assertIn('

via Anthropic Messages

', llm) self.assertIn('id="LLM_JUDGE_PROTOCOL" data-source="unset" data-secret="no" hidden>', llm) self.assertNotIn("messages<", llm); self.assertNotIn(">chat<", llm) # names, never keys - self.post({"ANTHROPIC": '{"endpoints": {"chat": "/chat/completions"}}', "LLM_JUDGE_PROTOCOL": "messages"}) + self.addCleanup(lambda: [os.environ.pop(n, None) for n in settings.endpoint_names()]) + self.post({"MODEL_BOTH.base": "https://gw.example/v1", "MODEL_BOTH.endpoints.chat": "/chat/completions", + "MODEL_BOTH.endpoints.messages": "/messages"}) + self.post({"LLM_JUDGE_PROVIDER": "custom:BOTH", "LLM_JUDGE_PROTOCOL": "messages"}) llm = (html := self.page())[html.index('id="LLM_JUDGE_PROVIDER"'):html.index('id="LLM_JUDGE_MODEL"')] self.assertIn('data-judge-via hidden>via Anthropic Messages

', llm) self.assertIn('id="LLM_JUDGE_PROTOCOL" data-source="file" data-secret="no">', llm) @@ -369,7 +372,7 @@ def row(text, name): def test_a_record_s_environment_fields_are_read_only_and_its_endpoints_are_saved(self): """A partial record in the environment locks only its own fields; the - Endpoints rows save into the file's record, a preset only adds + Endpoints rows save into the custom provider's record; presets reject protocols, and no key ever reaches the page.""" self.addCleanup(lambda: [os.environ.pop(n, None) for n in settings.endpoint_names()]) saved = settings.ENV_PART.copy(); self.addCleanup(lambda: (settings.ENV_PART.clear(), settings.ENV_PART.update(saved))) @@ -383,23 +386,26 @@ def test_a_record_s_environment_fields_are_read_only_and_its_endpoints_are_saved self.assertIn('placeholder="https://gw-eu.example/v1/chat/completions"', html) # the default, as a placeholder self.assertIn('title="chat">OpenAI Chat Completions', html) # the format by name, its key as a tooltip self.assertNotIn('name="value:OPENROUTER.endpoints.chat"', html) # a preset's own endpoint is fixed - self.assertIn('name="value:OPENROUTER.endpoints.messages"', html) + for preset in providers.PRESETS: + self.assertNotIn(f'name="value:{preset.upper()}.endpoints.', html) + for protocol in providers.PROTOCOLS: + self.assertIn(f'name="value:MODEL_GW.endpoints.{protocol}"', html) self.assertNotIn("sk-gw-0123456789", html); self.assertNotIn("sk-or-0123456789", html) r = self.client.post("/settings/save", data={"csrf": self.token(), "value:MODEL_GW.name": "Gateway", - "value:MODEL_GW.endpoints.decisions": "https://gw-eu.example/alpha/decisions", - "value:OPENROUTER.endpoints.messages": "/messages"}, + "value:MODEL_GW.endpoints.decisions": "https://gw-eu.example/alpha/decisions"}, headers={"Origin": "http://localhost", "Accept": "application/json"}) self.addCleanup(r.close) self.assertEqual(r.status_code, 200, r.get_json()) filed = settings.in_file(self.env_file) self.assertEqual(json.loads(filed["MODEL_GW"]), {"name": "Gateway", "endpoints": {"decisions": "https://gw-eu.example/alpha/decisions"}}) - self.assertEqual(json.loads(filed["OPENROUTER"]), {"endpoints": {"messages": "/messages"}}) + self.assertNotIn("OPENROUTER", filed) rec = providers.record("custom:GW") self.assertEqual((rec["name"], rec["base"]), ("Gateway", "https://gw-eu.example/v1")) # the environment's base still wins - r = self.client.post("/settings/save", data={"csrf": self.token(), "value:OPENROUTER.endpoints.messages": ""}, + r = self.client.post("/settings/save", data={"csrf": self.token(), "value:OPENROUTER.endpoints.messages": "/messages"}, headers={"Origin": "http://localhost", "Accept": "application/json"}) self.addCleanup(r.close) - self.assertNotIn("OPENROUTER", settings.in_file(self.env_file)) # emptied: the record goes + self.assertEqual(r.status_code, 400) + self.assertNotIn("OPENROUTER", settings.in_file(self.env_file)) r = self.client.post("/settings/save", data={"csrf": self.token(), "value:OPENROUTER.endpoints.chat": "/x"}, headers={"Origin": "http://localhost", "Accept": "application/json"}) self.addCleanup(r.close) diff --git a/app/web/settings.py b/app/web/settings.py index 743dad0b..656df7ce 100644 --- a/app/web/settings.py +++ b/app/web/settings.py @@ -419,7 +419,7 @@ def provider_cards(by: dict, env=None) -> list: {"protocol": p, "format": d["label"], "fixed": providers.url(rec, p) if rec["preset"] and p in providers.PRESETS[rec["id"]]["endpoints"] else "", "row": _record_row(setting, f"endpoints.{p}", rec["endpoints"].get(p, ""), held), "placeholder": settings.endpoint_url_shown(providers.join(rec["base"], d["path"])) or d["path"], "suggestion": hint.get(p, "")} - for p, d in providers.PROTOCOLS.items()] + for p, d in providers.PROTOCOLS.items() if not rec["preset"] or p in rec["endpoints"]] names = _provider_settings(rec["id"], settings.endpoint_ids(env)) configured = any(by.get(n, {}).get("source", "unset") != "unset" for n in names) ready = providers.ready(rec, env) diff --git a/docs/settings/model-providers.md b/docs/settings/model-providers.md index ee063572..64692d42 100644 --- a/docs/settings/model-providers.md +++ b/docs/settings/model-providers.md @@ -11,9 +11,8 @@ Where model calls go, and with which key. | Custom | A name, a base URL, an optional key | Ollama, vLLM, LM Studio, a gateway or a hosted service | Any; the endpoints you list come first | The first four are presets: their name, base, key setting and listed -endpoints are fixed. You can add endpoints for other protocols. An added -endpoint is a path, or a full URL on the preset's own host, because the preset's -key goes there. +endpoints are fixed. To configure other endpoints, add a Custom provider. +Existing preset overrides are ignored; move them to a Custom provider. ## Protocols @@ -83,14 +82,16 @@ A rename does not break a recipe. ### Endpoints -**Endpoints**, on a card, has one row per protocol. An empty row uses the base +**Endpoints** lists only supported, read-only endpoints for presets. Custom +providers have an editable row for every protocol. An empty row uses the base and the protocol's default path. A row holds a path, appended to the base with one slash (`/v2/chat` on `https://gw.example/v1` is `https://gw.example/v1/v2/chat`), or a full URL, which passes the checks a base gets. A path has no `..` segment. A row you fill also says that the provider serves that protocol: pickers list such providers first, and a judge uses a protocol that the provider lists before one that it does not. A base on a -preset's host suggests that preset's endpoints. +preset's host suggests that preset's endpoints. Run relays forward the agent's +paths below the base URL; endpoint rows configure provider tests and judges. If one provider serves both decision formats, set at least one of them: both default to `/decisions`. @@ -104,7 +105,7 @@ a setting of its own. | --- | --- | | `MODEL_` | A custom provider: `name`, `base`, `endpoints` | | `MODEL__API_KEY` | Its key (secret) | -| `OPENROUTER`, `OPENAI`, `ANTHROPIC`, `TYPESAFE` | Endpoints you add to a preset | +| `OPENROUTER`, `OPENAI`, `ANTHROPIC`, `TYPESAFE` | Unsupported overrides; use Custom instead | | `_API_KEY` | The preset's key (secret) | | `MODEL_API_URL`, `MODEL_API_KEY` | The custom provider named OpenAI-compatible; recipes with no endpoint id use it | @@ -115,15 +116,14 @@ a setting of its own. } ``` -A provider is three layers merged field by field, the later one winning: the -preset in code, then `settings.json`, then the environment. An environment +A custom provider merges `settings.json` and the environment field by field, +the environment winning. An environment value is a partial object: it changes only the fields it names. `endpoints` merges by protocol, and `null` removes a field. An older setting does not replace a field that `null` removes. ```sh -export MODEL_GW='{"base": "https://gw-eu.example/v1"}' -export OPENROUTER='{"endpoints": {"messages": "/messages"}}' +export MODEL_GW='{"base": "https://gw-eu.example/v1", "endpoints": {"messages": "/messages"}}' ``` | Rule | |