OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.
Python
feat: route Azure AI Foundry over its OpenAI-compatible v1 surface (#2445)
Rico Furtado2c1e56b5364a
diff --git a/enhancements/providers/azure/__init__.py b/enhancements/providers/azure/__init__.pynew file mode 100644index 000000000..3d0e7b9b7--- /dev/null+++ b/enhancements/providers/azure/__init__.py@@ -0,0 +1 @@+"""Microsoft Azure model providers that need more than the declarative path."""diff --git a/enhancements/providers/azure/foundry.py b/enhancements/providers/azure/foundry.pynew file mode 100644index 000000000..a266b7129--- /dev/null+++ b/enhancements/providers/azure/foundry.py@@ -0,0 +1,595 @@+"""Azure AI Foundry, reached over its OpenAI-compatible `/openai/v1` surface.++Foundry exposes the same resource through two inference surfaces:++- ``https://<resource>.services.ai.azure.com/openai/v1`` (and the project form,+ ``.../api/projects/<project>/openai/v1``) — the OpenAI-compatible surface+ Microsoft recommends for new integrations;+- ``https://<resource>.services.ai.azure.com/models`` — the older Foundry+ Models inference route, kept here as a compatibility path for deployments+ already configured against it.++`azure_ai` stays the OpenRAG provider key throughout: it is what a saved model+id (`azure_ai:<deployment>`) carries, what an indexed embedding space is tagged+with (`utils.embedding_fields.get_embedding_space_id`), and what credentials+are stored under. Only the *transport* differs per surface.+++Why `hosted_vllm` is the transport for `/openai/v1`+---------------------------------------------------+LiteLLM's own `azure_ai` provider cannot address the v1 surface. Its chat+transformation picks the request path from the **hostname**, not from the path+the operator supplied::++ # litellm/llms/azure_ai/chat/transformation.py+ if "services.ai.azure.com" in api_base:+ new_url = _add_path_to_api_base(api_base, ending_path="/models/chat/completions")+ else:+ new_url = _add_path_to_api_base(api_base, ending_path="/chat/completions")++`_add_path_to_api_base` only collapses *overlapping* segments, and `openai/v1`+does not overlap `models/chat/completions`, so the rewrite lands after the+operator's path. Captured on the wire against a Foundry-shaped hostname:++=========================== =============================================+`api_base` path litellm actually requests+=========================== =============================================+``…/openai/v1`` ``/openai/v1/models/chat/completions`` (404)+``…/api/projects/p/openai/v1`` ``/api/projects/p/openai/v1/models/chat/completions`` (404)+``…/models`` ``/models/chat/completions`` (correct)+=========================== =============================================++The embedding path does the same. An earlier revision of this module claimed+embeddings were unaffected, on the strength of `AzureAIEmbedding` inheriting+the plain OpenAI implementation and defining no `get_complete_url` of its own.+That was measured on litellm 1.84.0 and is wrong on the pinned floor: 1.102.0+emits ``/openai/v1/models/embeddings`` for a v1 base, captured on the wire and+confirmed live against a real resource. So **both** call kinds need the+transport, not just chat.++There is no flag, kwarg or `api_version` that opts out — the branch is+unconditional. Verified identical in litellm 1.102.0 (the pinned floor) and+1.103.1 (the newest release inside `>=1.96.2,<2.0.0`), so this is not something+a version bump is about to fix.++So the v1 surface needs an OpenAI-compatible transport that appends nothing but+the endpoint path. Of the candidates, only `hosted_vllm` serves the whole+contract — chat, tool calls, streaming **and** embeddings — on both v1 forms:++====================== ===== ===== ====== ==========+LiteLLM key chat tools stream embeddings+====================== ===== ===== ====== ==========+``hosted_vllm`` yes yes yes yes+``custom_openai`` yes yes yes **no** (unmapped provider)+``openai_like`` **no** — not dispatchable by ``acompletion`` at all+``openai`` **no** — OpenRAG sends a bare model name for this key+ (`llm_gateway.resolve_call`), which litellm rejects+====================== ===== ===== ====== ==========++`hosted_vllm` is a generic OpenAI-compatible HTTP transport in litellm; nothing+about it is vLLM-specific on this path. It forwards `tools`, `tool_choice`,+`stream` and `response_format` unchanged, and it is already the transport+`enhancements/providers/redhat/openshift_ai.py` routes as, so its behaviour is+exercised elsewhere in this codebase.++**It is a transport, not an identity.** Nothing outside `litellm_route` should+treat Foundry as `hosted_vllm`: the catalogue, credentials, embedding spaces,+health checks and the settings UI all key on `azure_ai`. The reroute guard in+`llm_gateway` compares the route litellm resolved against what `litellm_route`+asked for, precisely so this intentional difference does not read as a fault,+and `llm_gateway._model_info` looks metadata up under the logical key rather+than the transport.++Unrecognised endpoints+----------------------+There is no catch-all route. An endpoint outside the supported shapes raises+`UnsupportedEndpointError` from `litellm_route`, which the gateway turns into a+400. Falling back would mean guessing, and both guesses are bad: the native+handler builds a wrong URL for v1, and the OpenAI-compatible one builds a+plausible-looking URL for literally any input, so either turns a fixable+configuration error into an opaque upstream failure.++One shape is kept for compatibility by name rather than by fallback —+`legacy_deployment_uri`, a per-deployment Target URI on an `openai.azure.com`+host, which is what LiteLLM's own placeholder told operators to paste. It+worked there, so it still routes; it is refused at save time, because it pins+every selected model to the one deployment in the URL. The same shape on a+`services.ai.azure.com` host never worked and is simply unsupported.++What the transport costs+------------------------+Routing as `hosted_vllm` takes the model id out of litellm's `azure_ai/*` price+table. Measured:++- ``azure_ai/gpt-6-luna`` -> cost and capability metadata resolve;+- ``hosted_vllm/gpt-6-luna`` -> ``This model isn't mapped yet``.++Capability metadata is unaffected, because `llm_gateway._model_info` is given+the logical provider key and tries `azure_ai/<model>` before the bare name. So+``Phi-4`` — Foundry-exclusive, with no bare row — resolves, and ``gpt-6-luna``+resolves to *Azure's* row rather than OpenAI's. Only a deployment named+something no table knows (``prod-llm-01``) resolves under neither, which is+true on the native route too.++Cost is the part still given up, and it costs nothing today: OpenRAG does not+compute it. When it does, `completion_cost(..., base_model="azure_ai/<model>")`+restores attribution exactly — verified to the cent against the native route.+That is why a deployment's base model is worth capturing then; it is not+collected here because nothing would read it yet.++Not in scope here+-----------------+Microsoft Entra credentials (`azure_ad_token`, service principal) are+`azure`-only for now. The credential form below is shaped so they can be added+without invalidating anything already stored: add the fields, mirror the+`auth_method` pruning `config_manager.set_credentials` does for `azure`, and+make `api_key` conditionally required.++This module is a leaf on purpose. `config_manager`, `model_catalog` and+`llm_gateway` all import it, so it must not import OpenRAG config.+"""++from __future__ import annotations++from collections.abc import Mapping+from typing import Any, Literal+from urllib.parse import SplitResult, urlsplit, urlunsplit++from utils.logging_config import get_logger++logger = get_logger(__name__)++#: OpenRAG's key for the provider: the name in `model_providers.yaml`, in the+#: settings payload, in an `azure_ai:<deployment>` id, and in the+#: `provider:model` embedding-space id persisted with every indexed chunk.+PROVIDER_KEY = "azure_ai"++#: The route for the legacy `/models` surface and the resource root, where+#: LiteLLM's own `azure_ai` handler is correct and keeps its Foundry price+#: table. Also the *static* alias, which is what callers that have no stored+#: credentials to classify — `litellm_provider_key(provider)` with no second+#: argument — resolve to. It is deliberately not a fallback for an endpoint+#: that `litellm_route` cannot classify; that is an error, not a default.+LITELLM_PROVIDER = "azure_ai"++#: The transport for the OpenAI-compatible surface. See the module docstring.+OPENAI_COMPATIBLE_ROUTE = "hosted_vllm"++#: The two kinds of call the gateway makes. Foundry serves both from one+#: endpoint, so `kind` changes nothing here; it is accepted to match the+#: enhancement contract.+CallKind = Literal["chat", "embedding"]++#: Endpoint shapes this module recognises.+#:+#: `legacy_deployment_uri` is the one shape kept purely for compatibility: a+#: per-deployment Target URI on an `openai.azure.com` host, which is what+#: LiteLLM's own `api_base` placeholder told operators to paste. It worked —+#: `_add_path_to_api_base` collapses the `/chat/completions` overlap on that+#: host, so the call reached the deployment named in the URL. It is still+#: routed, and still refused at save time, because it serves exactly one+#: deployment: every model the operator picks resolves to the one baked into+#: the path. The same shape on a `services.ai.azure.com` host never worked at+#: all (the rewrite appends `/models/chat/completions` after it), so it is+#: `unknown` rather than compatible.+#:+#: `unknown` is everything else, and is an error rather than a guess.+Profile = Literal[+ "resource_openai_v1",+ "project_openai_v1",+ "legacy_models",+ "legacy_deployment_uri",+ "unknown",+]+++#: One message for both the save-time rejection and the routing failure, so an+#: operator who hits it at either point is told the same thing.+UNSUPPORTED_ENDPOINT_MESSAGE = (+ "The Azure AI Foundry endpoint should be the resource endpoint ending in "+ "/openai/v1 (recommended), its project form "+ ".../api/projects/<project>/openai/v1, or the older /models endpoint. Copy "+ "it from the resource's Overview page rather than from a single "+ "deployment's Target URI."+)++#: Refused at save time even though it still routes: it serves exactly one+#: deployment, so every model the operator picks resolves to the one in the URL.+DEPLOYMENT_URI_MESSAGE = (+ "This is a single deployment's Target URI, so every model selected would be "+ "sent to that one deployment. Use the resource endpoint ending in /openai/v1 "+ "and name the deployment when selecting a model."+)+++class UnsupportedEndpointError(ValueError):+ """The endpoint is not a Foundry surface this provider can address.++ Raised rather than falling back to a route, because every fallback here is+ a guess that fails later and less legibly: the native handler builds a+ wrong URL for the v1 surface, and the OpenAI-compatible one builds a+ plausible URL for anything at all.+ """+++#: Path suffix of the OpenAI-compatible surface, resource and project forms.+_V1_SUFFIX = "/openai/v1"+#: Path suffix of the older Foundry Models inference route.+_LEGACY_SUFFIX = "/models"+#: Marks the project form, which hangs off `/api/projects/<project>`.+_PROJECT_MARKER = "/api/projects/"++#: Marks a per-deployment Target URI. Only compatible on the host below.+_DEPLOYMENT_MARKER = "/openai/deployments/"++#: Azure OpenAI Service hosts, where the legacy Target URI shape still routes.+_AZURE_OPENAI_HOST_SUFFIX = ".openai.azure.com"++#: The Foundry hostname family. LiteLLM's `azure_ai` handler keys the legacy+#: call path off this string: on it a bare resource root becomes+#: `/models/chat/completions`, and on anything else plain `/chat/completions`.+_FOUNDRY_HOST_SUFFIX = ".services.ai.azure.com"++#: Endpoint paths an operator pastes from a curl example or the portal's+#: "Target URI" box. They name one call, not the base, and LiteLLM appends its+#: own — so `.../chat/completions` becomes `.../chat/completions/chat/completions`.+_CALL_SUFFIXES = ("/chat/completions", "/embeddings", "/responses")+++CREDENTIAL_FIELDS: list[dict[str, Any]] = [+ {+ "key": "api_base",+ "label": "Endpoint",+ "placeholder": "https://<resource>.services.ai.azure.com/openai/v1",+ "tooltip": (+ "The resource endpoint, not a per-deployment Target URI. Copy the "+ "'Azure AI Foundry' endpoint from your resource's Overview page and keep "+ "the /openai/v1 suffix. A Target URI that names one deployment "+ "(.../openai/deployments/<name>/chat/completions) pins every model you "+ "select to that one deployment. The older /models endpoint is still "+ "accepted for deployments already using it."+ ),+ "required": True,+ "field_type": "text",+ "options": None,+ "default_value": None,+ },+ {+ "key": "api_key",+ "label": "API key",+ "placeholder": None,+ "tooltip": "A key from the resource's Keys and Endpoint page.",+ "required": True,+ "field_type": "password",+ "options": None,+ "default_value": None,+ },+ {+ "key": "api_version",+ "label": "API version",+ "placeholder": "2024-05-01-preview",+ "tooltip": (+ "Only for the older /models endpoint, which dates its API. Leave blank "+ "for /openai/v1, which is versionless — sending one there is at best "+ "ignored."+ ),+ "required": False,+ "field_type": "text",+ "options": None,+ "default_value": None,+ },+]+++def _clean(value: Any) -> str:+ return str(value or "").strip()+++def normalized_api_base(value: Any) -> str:+ """The endpoint as LiteLLM needs it: no trailing slash, no call path, no query.++ Operators paste three things that all have to work. The portal's endpoint+ box gives the base. A curl example gives the base plus `/chat/completions`.+ LiteLLM's own (misleading) placeholder gives a per-deployment Target URI+ with `?api-version=` attached.++ Nothing is ever *appended* here. Guessing a suffix is how `/openai/v1` and+ `/models` get confused for one another, and the two are different APIs.+ """+ raw = _clean(value)+ if not raw:+ return ""++ parts = urlsplit(raw)+ if not parts.scheme or not parts.netloc:+ return raw.rstrip("/")++ path = parts.path.rstrip("/")+ for suffix in _CALL_SUFFIXES:+ if path.endswith(suffix):+ path = path[: -len(suffix)]+ break++ # A pasted *listing* URL for the v1 surface names the same endpoint as its+ # parent: `.../openai/v1/models` is where the deployments are read from,+ # not where calls go. Left on, it matches `_LEGACY_SUFFIX` first and the+ # endpoint is classified legacy, so LiteLLM builds+ # `.../openai/v1/models/chat/completions` — a 404, and precisely the+ # confusion this module exists to prevent. Only the v1 parent is stripped:+ # on the legacy route the `/models` suffix *is* the base, and removing it+ # there would break the endpoint that is spelled correctly.+ if path.lower().endswith(_LEGACY_SUFFIX):+ parent = path[: -len(_LEGACY_SUFFIX)].rstrip("/")+ if parent.lower().endswith(_V1_SUFFIX):+ path = parent++ # The query is always dropped: `api-version` belongs in its own field, and+ # a v1 endpoint has no use for it at all.+ normalized = urlunsplit((parts.scheme, parts.netloc, path.rstrip("/"), "", ""))+ if normalized != raw:+ # Deliberately not logging `raw`. The value an operator pastes can+ # carry credentials in its query string — a Target URI copied from the+ # portal already carries `?api-version=`, and nothing stops a key or+ # SAS token being in there too. `normalized` has the query stripped by+ # construction; `_loggable` takes off the other half, because a URL can+ # also carry `user:password@` in its netloc and that survives+ # normalization. Whether anything was dropped is the only other fact+ # worth having when diagnosing.+ logger.debug(+ "Normalized the Azure AI Foundry endpoint",+ normalized=_loggable(normalized),+ dropped_query=bool(parts.query),+ )+ return normalized+++def _loggable(api_base: str) -> str:+ """`api_base` with any `user:password@` removed, safe to record.++ Userinfo is a credential wherever it appears, and this module's own+ invariant is that nothing an operator pastes reaches a log line unredacted.+ `normalized_api_base` refuses to return such an endpoint to a caller that+ would *use* it (see `_reject_userinfo`), but the diagnostic log runs first+ and has to be safe on its own.+ """+ parts = urlsplit(api_base)+ if not (parts.username or parts.password):+ return api_base+ host = parts.hostname or ""+ if parts.port:+ host = f"{host}:{parts.port}"+ return urlunsplit((parts.scheme, host, parts.path, "", ""))+++def _is_foundry_host(parts: SplitResult) -> bool:+ """Whether a split URL points at the Foundry hostname family."""+ return (parts.hostname or "").lower().endswith(_FOUNDRY_HOST_SUFFIX)+++def endpoint_profile(api_base: Any) -> Profile:+ """Which Foundry surface `api_base` names.++ Classified on the path wherever the path is enough, which is every spelled-+ out endpoint: a Foundry resource can serve Azure OpenAI deployments too, so+ the host usually says nothing about which API is being addressed — the same+ reason `provider_validation.is_azure_ai_foundry_endpoint` exists+ separately.++ The two exceptions are endpoints that carry no path to read. A bare+ resource root is one (see below), and a per-deployment Target URI is the+ other.+ """+ base = normalized_api_base(api_base)+ if not base:+ return "unknown"+ parts = urlsplit(base)+ if parts.username or parts.password:+ # Credentials in the URL. Refused rather than routed: the value is+ # passed to LiteLLM and to this module's own health check, so httpx+ # would send it as Basic auth alongside the real API key, and it would+ # be stored in config.yaml in the clear.+ return "unknown"+ path = parts.path.rstrip("/").lower()+ if path.endswith(_V1_SUFFIX):+ return "project_openai_v1" if _PROJECT_MARKER in path else "resource_openai_v1"+ if not path:+ # A bare resource root is only unambiguous on the Foundry hostname.+ # LiteLLM's `azure_ai` handler picks the legacy call path by testing+ # the host: on `*.services.ai.azure.com` it appends+ # `/models/chat/completions` and reaches the right place, and on any+ # other host — `*.cognitiveservices.azure.com`, a private-link or+ # custom domain — it appends plain `/chat/completions`, which 404s.+ #+ # Spelling `/models` onto the root would fix the path on both, but not+ # the auth header: LiteLLM picks that by hostname too, sending+ # `api-key` on the Foundry and Azure OpenAI families and+ # `Authorization: Bearer` everywhere else. Fixing half of a+ # host-dependent pair would turn a legible 404 into a puzzling 401, so+ # the root is refused off the Foundry host and the operator is asked+ # for the endpoint in full.+ return "legacy_models" if _is_foundry_host(parts) else "unknown"+ if path.endswith(_LEGACY_SUFFIX):+ return "legacy_models"+ if _DEPLOYMENT_MARKER in path and (parts.hostname or "").lower().endswith(+ _AZURE_OPENAI_HOST_SUFFIX+ ):+ return "legacy_deployment_uri"+ return "unknown"+++def litellm_route(stored: Mapping[str, Any] | None) -> str:+ """The LiteLLM transport for the endpoint in `stored`.++ The one place that maps a Foundry surface onto a transport. Everything else+ — the catalogue, the settings form, credentials, embedding spaces — keeps+ calling this provider `azure_ai`.++ Raises `UnsupportedEndpointError` for a shape this module does not+ recognise, rather than picking a route for it. There is no safe default:+ the native handler builds the wrong URL for the v1 surface, and the+ OpenAI-compatible one builds a plausible-looking URL for literally any+ input, so either choice turns a fixable configuration error into an opaque+ upstream failure.+ """+ api_base = (stored or {}).get("api_base")+ profile = endpoint_profile(api_base)+ if profile in ("resource_openai_v1", "project_openai_v1"):+ return OPENAI_COMPATIBLE_ROUTE+ if profile in ("legacy_models", "legacy_deployment_uri"):+ return LITELLM_PROVIDER+ raise UnsupportedEndpointError(UNSUPPORTED_ENDPOINT_MESSAGE)+++def _require_https(api_base: str) -> None:+ """Refuse an `http://` Foundry endpoint outright.++ `openshift_ai` only warns about this, because a cluster-local predictor or+ an `oc port-forward` is legitimately plain HTTP. Foundry has no such case:+ it is a public cloud service, and a cleartext endpoint means the API key+ crosses the internet in the clear. `docling_service` already rejects+ non-HTTPS for both Azure providers, so this matches the stricter of the two+ precedents in this repository.++ A value with *no* scheme is not judged here. It is not a URL at all, and+ `endpoint_profile` reports that in terms the operator can act on — telling+ someone who typed a hostname that it "must use https://" sends them to fix+ the wrong half of it.+ """+ if not api_base:+ return+ scheme = urlsplit(api_base).scheme.lower()+ if scheme and scheme != "https":+ raise ValueError(+ "The Azure AI Foundry endpoint must use https://. A plain-HTTP endpoint "+ "would send the API key in cleartext."+ )+++def _reject_userinfo(api_base: str) -> None:+ """Refuse an endpoint with `user:password@` in it.++ The value reaches three places that all treat it as trustworthy: LiteLLM+ builds the request URL from it, `models_url` is fetched with httpx, which+ turns userinfo into a Basic auth header, and it is written to config.yaml+ as ordinary non-secret configuration. None of those is a reasonable home+ for a credential, and Foundry authenticates with the API key field rather+ than with the URL, so there is no shape of this that is correct.+ """+ if not api_base:+ return+ parts = urlsplit(api_base)+ if parts.username or parts.password:+ raise ValueError(+ "The Azure AI Foundry endpoint must not carry credentials in the URL. "+ "Remove the 'user:password@' part and put the key in the API key field."+ )+++def litellm_credentials(stored: Mapping[str, Any], *, kind: CallKind = "chat") -> dict[str, Any]:+ """LiteLLM kwargs for a Foundry call.++ `kind` is accepted for the enhancement contract and ignored: Foundry serves+ chat and embeddings from one endpoint.+ """+ del kind # one endpoint serves both++ api_base = normalized_api_base(stored.get("api_base"))+ _require_https(api_base)+ _reject_userinfo(api_base)++ credentials: dict[str, Any] = {+ name: value for name, value in stored.items() if name not in {"api_base", "api_version"}+ }+ if api_base:+ credentials["api_base"] = api_base++ # `api-version` is a legacy-route concept. On `/openai/v1` it is at best+ # ignored, and LiteLLM would append it as a query parameter, so it is+ # dropped rather than forwarded onto a versionless API.+ api_version = _clean(stored.get("api_version"))+ if api_version and endpoint_profile(api_base) == "legacy_models":+ credentials["api_version"] = api_version++ return credentials+++#: Read-only listing used to check credentials. It needs no deployment and+#: bills nothing, which is what makes it a check the provider can pass before+#: anything has been selected in Settings. Both surfaces expose it directly+#: under the endpoint.+MODELS_PATH = "/models"++#: A human is waiting on the pre-save check, so it fails fast.+HEALTH_TIMEOUT_SECONDS = 15.0+++def models_url(api_base: str) -> str:+ """The deployment/model listing URL for an endpoint.++ On the v1 surface this is `…/openai/v1/models`. On the legacy route the+ endpoint *is* `…/models`, and the listing hangs off the resource root+ instead, so the suffix is not doubled.+ """+ base = normalized_api_base(api_base)+ if endpoint_profile(base) == "legacy_models":+ return (+ base if base.rstrip("/").endswith(MODELS_PATH) else f"{base.rstrip('/')}{MODELS_PATH}"+ )+ return f"{base.rstrip('/')}{MODELS_PATH}"+++def health_headers(stored: Mapping[str, Any]) -> dict[str, str]:+ """Auth headers for OpenRAG's own read-only calls to Foundry.++ Both header styles are sent. Microsoft's v1 surface takes+ `Authorization: Bearer`, the legacy `/models` route documents `api-key`,+ and litellm itself is inconsistent across the two — its `azure_ai` chat+ path sends `api-key` while its embedding path sends `Bearer` to the same+ endpoint. Sending both costs nothing and keeps the probe from failing for+ a reason that has nothing to do with whether the credential is valid.+ """+ api_key = _clean(stored.get("api_key"))+ if not api_key:+ return {}+ return {"api-key": api_key, "Authorization": f"Bearer {api_key}"}+++async def lightweight_health_check(credentials: Mapping[str, Any]) -> None:+ """Validate the endpoint and key without selecting or billing a deployment.++ Raises `ValueError` for a form that cannot be called at all, and a plain+ `Exception` carrying the upstream detail for a call that was rejected.++ A 403 is *not* treated as a bad credential: listing deployments can need a+ permission an inference-only identity lacks, and reporting "invalid key"+ for it would send the operator after the wrong problem. See the message+ below.+ """+ import httpx++ api_base = normalized_api_base(credentials.get("api_base"))+ if not api_base:+ raise ValueError("The Azure AI Foundry endpoint is required")+ _require_https(api_base)+ profile = endpoint_profile(api_base)+ if profile == "unknown":+ raise UnsupportedEndpointError(UNSUPPORTED_ENDPOINT_MESSAGE)+ if profile == "legacy_deployment_uri":+ # Still routable, so an install already configured this way keeps+ # working — but it must not be saved again in that shape.+ raise UnsupportedEndpointError(DEPLOYMENT_URI_MESSAGE)+ headers = health_headers(credentials)+ if not headers:+ raise ValueError("An Azure AI Foundry API key is required")++ async with httpx.AsyncClient(timeout=HEALTH_TIMEOUT_SECONDS) as client:+ response = await client.get(models_url(api_base), headers=headers)++ if response.status_code == 403:+ raise PermissionError(+ "The credentials were accepted but this identity cannot list deployments. "+ "Inference may still work; type the deployment name into the model field."+ )+ if response.status_code >= 400:+ detail = response.text[:400] if response.text else f"HTTP {response.status_code}"+ raise Exception(detail)diff --git a/enhancements/providers/registry.py b/enhancements/providers/registry.pyindex 00ae4ceee..e0bb26468 100644--- a/enhancements/providers/registry.py+++ b/enhancements/providers/registry.py@@ -13,6 +13,7 @@ from collections.abc import Mappingfrom types import ModuleTypefrom typing import Any, Literal+from enhancements.providers.azure import foundryfrom enhancements.providers.redhat import openshift_aifrom enhancements.providers.watsonx import onprem@@ -21,6 +22,7 @@ CallKind = Literal["chat", "embedding"]_ENHANCEMENTS: dict[str, ModuleType] = {onprem.PROVIDER_KEY: onprem,openshift_ai.PROVIDER_KEY: openshift_ai,+ foundry.PROVIDER_KEY: foundry,}@@ -30,7 +32,13 @@ def get(provider: str) -> ModuleType | None:def route_aliases() -> dict[str, str]:- """OpenRAG provider keys that LiteLLM must route under another key."""+ """OpenRAG provider keys that LiteLLM must route under another key.++ The *static* half of routing: one alias per provider, fixed at import. A+ provider whose route depends on how it was configured declares+ `litellm_route` as well — see `litellm_route_for`. This mapping is still+ what that provider falls back to, so it must stay the safe default.+ """return {key: enhancement.LITELLM_PROVIDERfor key, enhancement in _ENHANCEMENTS.items()@@ -38,6 +46,30 @@ def route_aliases() -> dict[str, str]:}+def litellm_route_for(provider: str, stored: Mapping[str, Any] | None) -> str | None:+ """The LiteLLM key `provider` routes as *for this configuration*.++ Most providers reach one API one way, and `LITELLM_PROVIDER` says which.+ Azure AI Foundry does not: the endpoint an operator pastes decides which+ LiteLLM transport can even produce a correct URL for it, so the route has+ to be recomputed per configuration rather than fixed at import.++ Returns `None` when `provider` has no enhancement or the enhancement has+ nothing to say, leaving the caller on the static alias.+ """+ enhancement = get(provider)+ if enhancement is None:+ return None+ resolve = getattr(enhancement, "litellm_route", None)+ if resolve is None:+ return getattr(enhancement, "LITELLM_PROVIDER", None)+ # Deliberately not guarded. A hook that raises is reporting a configuration+ # it cannot route, and quietly substituting the static alias would turn+ # that into a wrong request rather than a clear error — the caller decides+ # how to surface it.+ return resolve(stored or {}) or None++def credential_field_overrides() -> dict[str, list[dict[str, object]]]:"""Settings forms supplied by provider enhancements instead of LiteLLM."""return {diff --git a/frontend/components/models/model-helpers.test.ts b/frontend/components/models/model-helpers.test.tsindex 89f05c219..b3f63fd25 100644--- a/frontend/components/models/model-helpers.test.ts+++ b/frontend/components/models/model-helpers.test.ts@@ -20,6 +20,7 @@ import {isProviderConfigured,LLM_PROVIDER_ORDER,orderProviders,+ requiresExplicitModelSelection,} from "./model-helpers";describe("orderProviders", () => {@@ -192,3 +193,16 @@ describe("canRemoveProvider", () => {assert.equal(canRemoveProvider(custom, "anthropic"), true);});});++describe("requiresExplicitModelSelection", () => {+ it("covers both Azure providers, whose deployment names are operator-chosen", () => {+ assert.equal(requiresExplicitModelSelection("azure"), true);+ assert.equal(requiresExplicitModelSelection("azure_ai"), true);+ });++ it("does not stop other providers defaulting to their top-ranked model", () => {+ assert.equal(requiresExplicitModelSelection("openai"), false);+ assert.equal(requiresExplicitModelSelection("anthropic"), false);+ assert.equal(requiresExplicitModelSelection(undefined), false);+ });+});diff --git a/frontend/components/models/model-helpers.tsx b/frontend/components/models/model-helpers.tsxindex 6886bdebb..461c5b6a1 100644--- a/frontend/components/models/model-helpers.tsx+++ b/frontend/components/models/model-helpers.tsx@@ -37,9 +37,12 @@ export type KnownModelProvider = (typeof KNOWN_PROVIDERS)[number];export function requiresExplicitModelSelection(provider: ModelProvider | undefined,): boolean {- // Azure lets customers name deployments independently of the underlying- // model family, so a catalogue row such as `gpt-4.1` is only a suggestion.- return provider === "azure";+ // Both Azure providers let customers name deployments independently of the+ // underlying model family, so a catalogue row such as `gpt-4.1` is only a+ // suggestion. For Foundry this is stronger than a preference: its catalogue+ // listing is of models available to deploy, not of models deployed, so+ // auto-selecting from it picks something that usually is not callable.+ return provider === "azure" || provider === "azure_ai";}// Preferred auto-select order for the LLM onboarding step. Only a preference:diff --git a/src/api/provider_validation.py b/src/api/provider_validation.pyindex dce10af92..d753bce6a 100644--- a/src/api/provider_validation.py+++ b/src/api/provider_validation.py@@ -932,7 +932,7 @@ async def _test_litellm_provider("""Validate arbitrary providers through the same LiteLLM adapter used at runtime."""import litellm- from services.llm_gateway import with_stale_connection_retry+ from services.llm_gateway import LlmGatewayError, with_stale_connection_retryfrom services.model_catalog import litellm_provider_keymodel = embedding_model or llm_model@@ -940,7 +940,11 @@ async def _test_litellm_provider(raise ValueError("A model is required to validate the provider")# Same aliasing the gateway applies, so the probe hits the route the real# call will: `watsonx_onprem/<model>` is not a prefix LiteLLM can resolve.- litellm_model = f"{litellm_provider_key(provider)}/{model}"+ try:+ route = litellm_provider_key(provider, credentials)+ except ValueError as exc:+ raise LlmGatewayError(str(exc), 400) from exc+ litellm_model = f"{route}/{model}"# And the same retry: a dead pooled connection is not a provider failure,# and reporting one would block a save or raise the banner for nothing.if embedding_model:diff --git a/src/services/llm_gateway.py b/src/services/llm_gateway.pyindex 2bf1f3215..7e40fcc49 100644--- a/src/services/llm_gateway.py+++ b/src/services/llm_gateway.py@@ -12,7 +12,7 @@ import contextlibimport functoolsimport jsonimport re-from collections import deque+from collections import OrderedDict, dequefrom collections.abc import AsyncIterator, Awaitable, Callable, Mappingfrom typing import Any, Literalfrom uuid import uuid4@@ -521,11 +521,111 @@ def resolve_call(# An OpenRAG provider that LiteLLM does not know by that name is routed# under the key it aliases (`watsonx_onprem` -> `watsonx`). The OpenRAG key# is still what the caller sees and what credentials are stored under.- route = litellm_provider_key(provider)+ #+ # The stored (untranslated) form is passed because one provider's transport+ # depends on how it was configured: Azure AI Foundry routes as `azure_ai`+ # on its legacy `/models` endpoint and as an OpenAI-compatible transport on+ # `/openai/v1`, which LiteLLM's `azure_ai` handler cannot address.+ try:+ route = litellm_provider_key(provider, _stored_credentials(provider, cfg))+ except ValueError as exc:+ # The provider knows its own endpoint shapes and this is not one of+ # them. Surfaced here rather than routed on a guess, which would reach+ # the wrong handler and fail as an opaque upstream error.+ raise LlmGatewayError(str(exc), 400) from exclitellm_model = f"{route}/{name}" if route != "openai" else name+ _warn_on_unexpected_route(provider, litellm_model, route)return litellm_model, provider, credentials+def _stored_credentials(provider: str, config) -> dict[str, Any]:+ """A provider's credentials as the operator entered them, or `{}`.++ Only routing reads this here; the call itself uses the translated form.++ `{}` means "this configuration does not keep the untranslated form", which+ is true of some test doubles and of any config object predating it. It does+ *not* swallow a failure to read: an empty mapping sends+ `litellm_provider_key` to the static alias, and for a provider whose+ transport depends on its endpoint that is a silent wrong route — the opaque+ upstream 404 this module exists to prevent. A real error belongs in the+ caller's face instead.+ """+ providers = getattr(config, "providers", None)+ reader = getattr(providers, "stored_credentials", None)+ if reader is None:+ return {}+ return dict(reader(provider))+++#: Model ids `_warn_on_unexpected_route` has already checked, so the resolver+#: runs once per distinct id rather than on every request, and a mismatch is+#: logged once rather than repeatedly.+#:+#: Bounded, and an LRU rather than a set: the key contains the model id, which+#: on `/v1/chat/completions` comes straight from the request body, so an+#: unbounded memo is a cache an unauthenticated caller can grow. Evicting the+#: oldest entry costs at worst a repeated warning for a model nobody has used+#: in the last `_ROUTE_CHECK_MEMO_MAX` distinct ids.+_ROUTE_CHECK_MEMO_MAX = 256+_CHECKED_ROUTES: OrderedDict[tuple[str, str], None] = OrderedDict()+++def _warn_on_unexpected_route(provider: str, litellm_model: str, intended_route: str) -> None:+ """Warn when LiteLLM resolves a model to a different provider than intended.++ Not a check that the route differs from the OpenRAG provider key — for+ Foundry on `/openai/v1` it deliberately does, and comparing against+ `azure_ai` would fire on every healthy request. The comparison is against+ the route this gateway *asked* for, so what it catches is LiteLLM+ re-deciding underneath us.++ That is not hypothetical: litellm 1.84.0 silently rerouted+ `azure_ai/gpt-4o` and other OpenAI-family names to the `azure` provider, so+ a Foundry hostname was called with the Azure OpenAI handler and failed as+ an opaque 404. The floor this repo pins no longer does it; this makes a+ return visible instead of mysterious.+ """+ if not litellm_model.startswith(f"{intended_route}/"):+ # Nothing was asserted, so there is nothing to check. This is the bare+ # name form that `openai` alone uses: the id goes out unprefixed, so+ # LiteLLM resolves it from the name and is entitled to its own answer.+ # A model whose *name* carries a vendor segment — `meta-llama/...` on+ # an OpenAI-compatible server — lands here too, and would otherwise+ # warn on every healthy request. A prefixed id is still checked even+ # when the route equals the provider key: `azure_ai/gpt-4o` silently+ # becoming `azure` is the regression this guard was written for.+ return+ key = (provider, litellm_model)+ if key in _CHECKED_ROUTES:+ _CHECKED_ROUTES.move_to_end(key)+ return+ _CHECKED_ROUTES[key] = None+ while len(_CHECKED_ROUTES) > _ROUTE_CHECK_MEMO_MAX:+ _CHECKED_ROUTES.popitem(last=False)+ try:+ from litellm import get_llm_provider++ _model, resolved, _key, _base = get_llm_provider(model=litellm_model)+ except Exception:+ return+ if resolved == intended_route:+ return+ logger.warning(+ "LiteLLM resolved this model to a different provider than the gateway "+ "selected; the request will be built by that provider's handler",+ provider=provider,+ model=litellm_model,+ intended_route=intended_route,+ resolved_route=resolved,+ )+++def forget_route_mismatches() -> None:+ """Clear the once-per-route warning memo. For tests."""+ _CHECKED_ROUTES.clear()++_UPSTREAM_FAILURE_MESSAGE = "The model provider could not be reached. Please try again."_UPSTREAM_CREDENTIAL_MESSAGE = ("The configured API key is invalid or has been revoked. Update it in Settings and retry."@@ -595,7 +695,24 @@ _PRIVATE_HOST_PATTERN = re.compile(_ANSI_PATTERN = re.compile(r"\x1b\[[0-9;]*m")-def _call_label(provider: str, model: str) -> str:+def _label_route(provider: str) -> str:+ """The transport `provider` resolves to, for display only.++ Never raises. This feeds error messages, and a provider misconfigured badly+ enough to fail here is already on its way to an error the caller needs to+ read — losing the label's prefix-stripping is a cosmetic degradation, while+ raising would replace the real failure with this one.+ """+ try:+ return litellm_provider_key(provider, _stored_credentials(provider, _get_config()))+ except Exception:+ try:+ return litellm_provider_key(provider)+ except Exception:+ return ""+++def _call_label(provider: str, model: str, route: str = "") -> str:"""`provider/model` for humans, without repeating a prefix LiteLLM already added.The model here is the routed id, so for an aliased provider it carries the@@ -603,7 +720,12 @@ def _call_label(provider: str, model: str) -> str:"watsonx_onprem/watsonx/openai/gpt-oss-120b", which names two providers andreads like a bug in the error it appears in."""- route = litellm_provider_key(provider) if provider else ""+ # `route` is passed by callers that already have it. The rest resolve it+ # the same way `resolve_call` did, from the stored configuration: the+ # static alias answers `azure_ai` for a Foundry endpoint routed over+ # `hosted_vllm`, which leaves the transport prefix on and produces exactly+ # the two-provider label this function exists to avoid.+ route = route or (_label_route(provider) if provider else "")if route and route != provider and model.startswith(f"{route}/"):model = model[len(route) + 1 :]if model and provider and not model.startswith(f"{provider}/"):@@ -1046,14 +1168,35 @@ def _log_completion_shape(payload: dict[str, Any], provider: str, model: str) ->_TOOLS_NEED_REASONING_OFF: set[str] = set()-def _model_info(model: str) -> dict[str, Any]:- """LiteLLM's row for `model`, by its full id or its bare name."""+def _model_info(model: str, provider: str | None = None) -> dict[str, Any]:+ """LiteLLM's row for `model`: transport id, then logical id, then bare name.++ A provider routed under a transport alias has two identities, and only one+ of them is in LiteLLM's table. Azure AI Foundry on its v1 surface is called+ as `hosted_vllm/<deployment>` — a transport that owns no model rows — while+ its metadata lives under `azure_ai/<deployment>`, which is LiteLLM's own+ key for the provider and the key OpenRAG stores it under.++ So `provider` is tried before the bare name. For a Foundry-exclusive model+ (`Phi-4`) the bare name matches nothing and only the logical id resolves;+ for one that a public vendor also serves (`gpt-6-luna`) the logical id is+ the more accurate of the two rows, since it carries Azure's pricing rather+ than OpenAI's.+ """try:import litellmtable = litellm.model_cost- info = table.get(model) or table.get(model.rsplit("/", 1)[-1])- return info if isinstance(info, dict) else {}+ bare = model.rsplit("/", 1)[-1]+ candidates = [model]+ if provider:+ candidates.append(f"{provider}/{bare}")+ candidates.append(bare)+ for candidate in candidates:+ info = table.get(candidate)+ if isinstance(info, dict):+ return info+ return {}except Exception:return {}@@ -1070,7 +1213,7 @@ def _is_reasoning_tool_conflict(detail: str) -> bool:return "reasoning_effort" in lowered and "tool" in lowered-def _reasoning_off_retry(model: str, kwargs: dict[str, Any]) -> bool:+def _reasoning_off_retry(model: str, kwargs: dict[str, Any], provider: str | None = None) -> bool:"""Set `reasoning_effort="none"` for a retry, if that can help here.False when the caller chose an effort itself — overriding a deliberate@@ -1079,7 +1222,7 @@ def _reasoning_off_retry(model: str, kwargs: dict[str, Any]) -> bool:"""if not kwargs.get("tools") or "reasoning_effort" in kwargs:return False- if not _model_info(model).get("supports_none_reasoning_effort"):+ if not _model_info(model, provider).get("supports_none_reasoning_effort"):return Falsekwargs["reasoning_effort"] = "none"return True@@ -1126,7 +1269,7 @@ async def chat_completions(stream = bool(body.get("stream"))if litellm_model in _TOOLS_NEED_REASONING_OFF:# Already learned about this model; do not spend a round-trip relearning.- _reasoning_off_retry(litellm_model, kwargs)+ _reasoning_off_retry(litellm_model, kwargs, provider)messages, repairs = _sanitise_messages(body.get("messages"))if repairs:logger.warning(@@ -1168,7 +1311,7 @@ async def chat_completions(# parameter, just not one this model accepts beside tools. Retry# once with the value the provider's own error asks for.if not _is_reasoning_tool_conflict(f"{exc}") or not _reasoning_off_retry(- litellm_model, kwargs+ litellm_model, kwargs, provider):raiselogger.info(diff --git a/src/services/model_catalog.py b/src/services/model_catalog.pyindex 4c542cc79..cba943cef 100644--- a/src/services/model_catalog.py+++ b/src/services/model_catalog.py@@ -26,6 +26,7 @@ from __future__ import annotationsimport datetimeimport json+from collections.abc import Mappingfrom fnmatch import fnmatchfrom functools import lru_cachefrom typing import Any@@ -33,6 +34,7 @@ from typing import Anyfrom config.model_providers import ProviderEntry, visible_provider_entriesfrom enhancements.providers.registry import (credential_field_overrides,+ litellm_route_for,route_aliases,)from enhancements.providers.registry import (@@ -107,9 +109,21 @@ PROVIDER_ROUTE_ALIASES: dict[str, str] = route_aliases()_CREDENTIAL_FIELD_OVERRIDES: dict[str, list[dict[str, Any]]] = credential_field_overrides()-def litellm_provider_key(provider: str) -> str:- """The name LiteLLM routes `provider` under, which is usually itself."""+def litellm_provider_key(provider: str, stored: Mapping[str, Any] | None = None) -> str:+ """The name LiteLLM routes `provider` under, which is usually itself.++ `stored` is the provider's untranslated credentials. Pass them whenever the+ caller has them: a provider whose transport depends on how it was+ configured — Azure AI Foundry, where the endpoint decides which LiteLLM+ handler can build a correct URL — can only answer with them in hand.+ Without them the static alias is used, which every enhancement keeps as its+ safe default.+ """key = (provider or "").strip().lower()+ if stored:+ dynamic = litellm_route_for(key, stored)+ if dynamic:+ return dynamicreturn PROVIDER_ROUTE_ALIASES.get(key, key)diff --git a/tests/unit/enhancements/providers/azure/test_foundry.py b/tests/unit/enhancements/providers/azure/test_foundry.pynew file mode 100644index 000000000..6d0175f13--- /dev/null+++ b/tests/unit/enhancements/providers/azure/test_foundry.py@@ -0,0 +1,1118 @@+"""Azure AI Foundry: endpoint classification, transport selection, credentials.++`azure_ai` is the OpenRAG provider key throughout. `hosted_vllm` appears only+as the LiteLLM transport for the OpenAI-compatible `/openai/v1` surface, which+LiteLLM's own `azure_ai` handler cannot address — see the module docstring in+`enhancements/providers/azure/foundry.py` for the captured evidence.+"""++from __future__ import annotations++import pytest++from enhancements.providers.azure import foundry+from enhancements.providers.registry import get as get_enhancement+from enhancements.providers.registry import litellm_route_for, route_aliases++RESOURCE = "https://contoso.services.ai.azure.com"+++class TestEndpointProfile:+ """The surface is classified from the path wherever the path says enough.++ A Foundry resource can serve Azure OpenAI deployments too, so a spelled-out+ path says which API is being addressed and the host does not. The host is+ consulted only for the shapes that carry no path to read.+ """++ @pytest.mark.parametrize(+ "api_base, expected",+ [+ (f"{RESOURCE}/openai/v1", "resource_openai_v1"),+ (f"{RESOURCE}/openai/v1/", "resource_openai_v1"),+ (f"{RESOURCE}/api/projects/proj-1/openai/v1", "project_openai_v1"),+ (f"{RESOURCE}/api/projects/proj-1/openai/v1/", "project_openai_v1"),+ (f"{RESOURCE}/models", "legacy_models"),+ (f"{RESOURCE}/models/", "legacy_models"),+ # A bare resource root is the legacy route's own default *on this+ # host*: litellm's azure_ai handler appends `/models/...` and+ # reaches the right place. See the host test below.+ (RESOURCE, "legacy_models"),+ (f"{RESOURCE}/", "legacy_models"),+ # The model *listing* URL names the same surface as its parent.+ # Pasted whole it used to match `/models` first and route as+ # legacy, so litellm built `.../openai/v1/models/chat/completions`.+ (f"{RESOURCE}/openai/v1/models", "resource_openai_v1"),+ (f"{RESOURCE}/openai/v1/models/", "resource_openai_v1"),+ (f"{RESOURCE}/api/projects/proj-1/openai/v1/models", "project_openai_v1"),+ ],+ )+ def test_the_supported_shapes(self, api_base, expected) -> None:+ assert foundry.endpoint_profile(api_base) == expected++ @pytest.mark.parametrize(+ "host, expected",+ [+ ("contoso.services.ai.azure.com", "legacy_models"),+ # LiteLLM picks the legacy call path by testing the hostname for+ # `services.ai.azure.com`. Off it, a bare root becomes plain+ # `/chat/completions` and 404s, and the auth header changes from+ # `api-key` to `Authorization` as well — so the root is refused+ # rather than routed on a host-dependent guess.+ ("contoso.cognitiveservices.azure.com", "unknown"),+ ("foundry.internal.example", "unknown"),+ ],+ )+ def test_a_bare_root_is_only_unambiguous_on_the_foundry_host(self, host, expected) -> None:+ assert foundry.endpoint_profile(f"https://{host}") == expected++ def test_an_explicit_models_path_routes_on_any_host(self) -> None:+ """Spelled out, the path is enough and the host stops mattering.++ This is what an operator on a non-Foundry hostname is asked for when+ the bare root is refused, so it has to keep working.+ """+ assert (+ foundry.endpoint_profile("https://contoso.cognitiveservices.azure.com/models")+ == "legacy_models"+ )++ @pytest.mark.parametrize(+ "api_base",+ [+ # A deployment Target URI on a *Foundry* host never worked: the+ # native rewrite appends `/models/chat/completions` after it.+ f"{RESOURCE}/openai/deployments/gpt-4o",+ f"{RESOURCE}/openai/deployments/gpt-4o/chat/completions",+ f"{RESOURCE}/anthropic/v1",+ "not-a-url",+ "",+ None,+ # Credentials in the URL. httpx would send the userinfo as Basic+ # auth next to the real API key, and the value is stored as+ # ordinary non-secret configuration, so it is refused outright+ # rather than classified and used.+ "https://user:[email protected]/openai/v1",+ "https://[email protected]/models",+ ],+ )+ def test_anything_else_is_unknown_rather_than_guessed_at(self, api_base) -> None:+ assert foundry.endpoint_profile(api_base) == "unknown"++ @pytest.mark.parametrize(+ "api_base",+ [+ "https://contoso.openai.azure.com/openai/deployments/gpt-4o/chat/completions",+ "https://contoso.openai.azure.com/openai/deployments/gpt-4o",+ ],+ )+ def test_the_one_compatibility_shape_is_named_not_lumped_into_unknown(self, api_base) -> None:+ """LiteLLM's own placeholder told operators to paste this.++ On an `openai.azure.com` host it genuinely worked — the native+ rewrite collapses the `/chat/completions` overlap — so an install+ configured this way keeps routing. It is still refused at save time,+ because it serves exactly one deployment.+ """+ assert foundry.endpoint_profile(api_base) == "legacy_deployment_uri"+++class TestNormalization:+ """Nothing is ever appended. Guessing a suffix confuses the two APIs."""++ @pytest.mark.parametrize(+ "raw, expected",+ [+ (f"{RESOURCE}/openai/v1/", f"{RESOURCE}/openai/v1"),+ (f"{RESOURCE}/models///", f"{RESOURCE}/models"),+ (f"{RESOURCE}/", RESOURCE),+ # Pasted from a curl example.+ (f"{RESOURCE}/openai/v1/chat/completions", f"{RESOURCE}/openai/v1"),+ (f"{RESOURCE}/openai/v1/embeddings", f"{RESOURCE}/openai/v1"),+ # Pasted from the portal's Target URI box, query and all.+ (+ f"{RESOURCE}/openai/v1/chat/completions?api-version=2024-05-01-preview",+ f"{RESOURCE}/openai/v1",+ ),+ # Already canonical: unchanged.+ (f"{RESOURCE}/openai/v1", f"{RESOURCE}/openai/v1"),+ (" " + f"{RESOURCE}/models" + " ", f"{RESOURCE}/models"),+ ],+ )+ def test_shapes_an_operator_actually_pastes(self, raw, expected) -> None:+ assert foundry.normalized_api_base(raw) == expected++ @pytest.mark.parametrize("raw", ["", None, " "])+ def test_blank_stays_blank(self, raw) -> None:+ assert foundry.normalized_api_base(raw) == ""++ def test_a_non_url_is_left_alone_for_the_health_check_to_reject(self) -> None:+ """Rewriting a malformed value would hide what the operator typed."""+ assert foundry.normalized_api_base("not-a-url") == "not-a-url"++ def test_normalization_is_idempotent(self) -> None:+ once = foundry.normalized_api_base(f"{RESOURCE}/openai/v1/chat/completions?x=1")+ assert foundry.normalized_api_base(once) == once++ def test_a_query_string_secret_never_reaches_the_logs(self, monkeypatch) -> None:+ """The pasted value is not logged, only what it normalizes to.++ An operator's endpoint can carry credentials in its query string — a+ Target URI copied from the portal already carries `?api-version=`, and+ nothing stops a key being in there too. Logging the raw value would+ put it in plaintext in the application log.+ """+ records: list[tuple[str, dict]] = []++ class _Recorder:+ def debug(self, message, **fields):+ records.append((message, fields))++ def __getattr__(self, _name):+ return lambda *args, **kwargs: None++ monkeypatch.setattr(foundry, "logger", _Recorder())++ secret = "super-secret-key-value"+ foundry.normalized_api_base(+ f"{RESOURCE}/openai/v1/chat/completions?api-version=2024-05-01&api-key={secret}"+ )++ assert records, "normalization should have been logged"+ rendered = repr(records)+ assert secret not in rendered+ assert "api-key" not in rendered+ assert "api-version" not in rendered+ _message, fields = records[0]+ assert fields == {+ "normalized": f"{RESOURCE}/openai/v1",+ "dropped_query": True,+ }++ def test_url_embedded_credentials_never_reach_the_logs(self, monkeypatch) -> None:+ """Stripping the query is only half of it.++ `user:password@` survives normalization — it lives in the netloc, not+ the query — so the diagnostic log has to take it off separately. The+ endpoint is refused elsewhere, but the log runs first and has to be+ safe on its own.+ """+ records: list[dict] = []++ class _Recorder:+ def debug(self, _message, **fields):+ records.append(fields)++ def __getattr__(self, _name):+ return lambda *args, **kwargs: None++ monkeypatch.setattr(foundry, "logger", _Recorder())++ secret = "url-embedded-password"+ foundry.normalized_api_base(+ f"https://operator:{secret}@contoso.services.ai.azure.com/openai/v1/chat/completions"+ )++ assert records, "normalization should have been logged"+ rendered = repr(records)+ assert secret not in rendered+ assert "operator" not in rendered+ assert records[0]["normalized"] == f"{RESOURCE}/openai/v1"++ def test_no_query_is_reported_as_none_dropped(self, monkeypatch) -> None:+ records: list[dict] = []++ class _Recorder:+ def debug(self, _message, **fields):+ records.append(fields)++ def __getattr__(self, _name):+ return lambda *args, **kwargs: None++ monkeypatch.setattr(foundry, "logger", _Recorder())+ foundry.normalized_api_base(f"{RESOURCE}/openai/v1/")++ assert records == [{"normalized": f"{RESOURCE}/openai/v1", "dropped_query": False}]+++class TestTransportSelection:+ """`hosted_vllm` is a transport. `azure_ai` stays the provider identity."""++ @pytest.mark.parametrize(+ "api_base, expected_route",+ [+ (f"{RESOURCE}/openai/v1", foundry.OPENAI_COMPATIBLE_ROUTE),+ (f"{RESOURCE}/openai/v1/", foundry.OPENAI_COMPATIBLE_ROUTE),+ (f"{RESOURCE}/api/projects/p/openai/v1", foundry.OPENAI_COMPATIBLE_ROUTE),+ (f"{RESOURCE}/openai/v1/chat/completions", foundry.OPENAI_COMPATIBLE_ROUTE),+ (f"{RESOURCE}/models", "azure_ai"),+ (RESOURCE, "azure_ai"),+ ],+ )+ def test_the_endpoint_picks_the_transport(self, api_base, expected_route) -> None:+ assert foundry.litellm_route({"api_base": api_base}) == expected_route++ @pytest.mark.parametrize(+ "stored",+ [+ {},+ None,+ {"api_base": ""},+ {"api_base": "not-a-url"},+ {"api_base": f"{RESOURCE}/anthropic/v1"},+ {"api_base": f"{RESOURCE}/openai/deployments/gpt-4o"},+ ],+ )+ def test_an_unclassifiable_endpoint_is_refused_not_routed(self, stored) -> None:+ """There is no safe default, so there is no fallback.++ The native handler builds a wrong URL for the v1 surface, and the+ OpenAI-compatible one builds a plausible-looking URL for literally any+ input — either guess turns a fixable configuration error into an+ opaque upstream failure.+ """+ with pytest.raises(foundry.UnsupportedEndpointError, match="/openai/v1"):+ foundry.litellm_route(stored)++ def test_the_compatibility_shape_still_routes_natively(self) -> None:+ """An install already configured this way must not break."""+ assert (+ foundry.litellm_route(+ {"api_base": "https://c.openai.azure.com/openai/deployments/gpt-4o"}+ )+ == "azure_ai"+ )++ def test_the_static_alias_is_the_native_route(self) -> None:+ """So every caller without stored credentials stays on the safe default."""+ assert route_aliases()["azure_ai"] == "azure_ai"++ def test_the_registry_resolves_the_dynamic_route(self) -> None:+ assert (+ litellm_route_for("azure_ai", {"api_base": f"{RESOURCE}/openai/v1"})+ == foundry.OPENAI_COMPATIBLE_ROUTE+ )+ assert litellm_route_for("azure_ai", {"api_base": f"{RESOURCE}/models"}) == "azure_ai"++ def test_a_provider_without_the_hook_keeps_its_static_alias(self) -> None:+ assert litellm_route_for("watsonx_onprem", {"api_base": "https://cpd.example.com"}) == (+ "watsonx"+ )++ def test_an_unknown_provider_has_no_route_of_its_own(self) -> None:+ assert litellm_route_for("openai", {}) is None++ def test_the_registry_propagates_the_refusal_rather_than_masking_it(self) -> None:+ """Substituting the static alias would turn a clear error into a wrong request."""+ with pytest.raises(foundry.UnsupportedEndpointError):+ litellm_route_for("azure_ai", {"api_base": "not-a-url"})++ def test_foundry_is_registered_under_its_openrag_key(self) -> None:+ assert get_enhancement("azure_ai") is foundry+ assert foundry.PROVIDER_KEY == "azure_ai"+++class TestCredentials:+ def test_the_endpoint_is_normalized_on_the_way_to_litellm(self) -> None:+ credentials = foundry.litellm_credentials(+ {"api_base": f"{RESOURCE}/openai/v1/chat/completions", "api_key": "k"}+ )+ assert credentials["api_base"] == f"{RESOURCE}/openai/v1"+ assert credentials["api_key"] == "k"++ def test_api_version_is_dropped_on_the_versionless_v1_surface(self) -> None:+ """Forwarding it would append `?api-version=` to an API that has none."""+ credentials = foundry.litellm_credentials(+ {"api_base": f"{RESOURCE}/openai/v1", "api_key": "k", "api_version": "2024-05-01"}+ )+ assert "api_version" not in credentials++ def test_api_version_survives_on_the_legacy_route_that_dates_its_api(self) -> None:+ credentials = foundry.litellm_credentials(+ {"api_base": f"{RESOURCE}/models", "api_key": "k", "api_version": "2024-05-01"}+ )+ assert credentials["api_version"] == "2024-05-01"++ @pytest.mark.parametrize(+ "api_base",+ [+ "https://operator:[email protected]/openai/v1",+ "https://[email protected]/openai/v1",+ ],+ )+ def test_credentials_in_the_url_are_refused(self, api_base) -> None:+ """The endpoint is handed to LiteLLM, to httpx and to config.yaml.++ httpx turns userinfo into a Basic auth header sent alongside the real+ API key, and config.yaml stores the endpoint as plain non-secret+ configuration. Foundry authenticates with the key field, so there is+ no correct form of this.+ """+ with pytest.raises(ValueError, match="credentials in the URL"):+ foundry.litellm_credentials({"api_base": api_base, "api_key": "k"})++ @pytest.mark.parametrize("scheme", ["http", "ftp"])+ def test_a_cleartext_endpoint_is_refused(self, scheme) -> None:+ """Foundry is a public cloud service; there is no port-forward case.++ `openshift_ai` only warns, because a cluster-local predictor can+ legitimately be plain HTTP. Nothing here can be.+ """+ with pytest.raises(ValueError, match="https"):+ foundry.litellm_credentials(+ {"api_base": f"{scheme}://contoso.services.ai.azure.com/openai/v1", "api_key": "k"}+ )+++class TestCredentialForm:+ def test_every_secret_is_typed_so_it_is_encrypted_at_rest(self) -> None:+ """Encryption keys off `field_type`, not off the field's name.++ A secret declared `text` is written to config.yaml in cleartext.+ """+ from services.model_catalog import secret_field_keys++ assert "api_key" in secret_field_keys("azure_ai")++ def test_the_form_replaces_litellms_deployment_pinning_placeholder(self) -> None:+ """LiteLLM's own `api_base` placeholder is a per-deployment Target URI.++ Following it produces a provider that serves exactly one deployment:+ every model selected resolves to the one baked into the URL.+ """+ from services.model_catalog import credential_fields++ api_base = next(f for f in credential_fields("azure_ai") if f["key"] == "api_base")+ assert "/openai/v1" in (api_base["placeholder"] or "")+ assert "deployments/" not in (api_base["placeholder"] or "")++ def test_the_form_asks_only_for_what_this_release_consumes(self) -> None:+ """No field is offered that nothing reads.++ A deployment list belongs here eventually — the catalogue cannot know+ names an operator chose — but the hook that would surface it does not+ exist yet, and a form field that silently does nothing is worse than+ its absence.+ """+ from services.model_catalog import credential_fields++ keys = {field["key"] for field in credential_fields("azure_ai")}+ assert keys == {"api_base", "api_key", "api_version"}+++class TestModelsUrl:+ @pytest.mark.parametrize(+ "api_base, expected",+ [+ (f"{RESOURCE}/openai/v1", f"{RESOURCE}/openai/v1/models"),+ (f"{RESOURCE}/api/projects/p/openai/v1", f"{RESOURCE}/api/projects/p/openai/v1/models"),+ # The legacy endpoint already *is* the listing path.+ (f"{RESOURCE}/models", f"{RESOURCE}/models"),+ (RESOURCE, f"{RESOURCE}/models"),+ ],+ )+ def test_the_listing_path_is_not_doubled(self, api_base, expected) -> None:+ assert foundry.models_url(api_base) == expected++ def test_both_auth_header_styles_are_sent(self) -> None:+ """litellm itself disagrees with itself here.++ Its `azure_ai` chat path sends `api-key` while its embedding path sends+ `Bearer` to the same endpoint, so the probe sends both rather than+ failing for a reason unrelated to credential validity.+ """+ headers = foundry.health_headers({"api_key": "k"})+ assert headers["api-key"] == "k"+ assert headers["Authorization"] == "Bearer k"++ def test_no_headers_without_a_key(self) -> None:+ assert foundry.health_headers({}) == {}+++class TestLightweightHealthCheck:+ """The pre-save probe: authenticated, read-only, and never billed."""++ @pytest.mark.asyncio+ async def test_a_good_endpoint_and_key_pass_without_an_inference_call(+ self, monkeypatch+ ) -> None:+ requests: list[tuple[str, dict]] = []++ class _Response:+ status_code = 200+ text = ""++ class _Client:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *exc):+ return False++ async def get(self, url, headers=None):+ requests.append((url, headers or {}))+ return _Response()++ monkeypatch.setattr("httpx.AsyncClient", lambda **_kw: _Client())++ await foundry.lightweight_health_check(+ {"api_base": f"{RESOURCE}/openai/v1", "api_key": "k"}+ )++ assert len(requests) == 1+ url, headers = requests[0]+ assert url == f"{RESOURCE}/openai/v1/models"+ # A listing, not a completion: nothing that bills a deployment.+ assert "chat/completions" not in url+ assert "embeddings" not in url+ assert headers["api-key"] == "k"++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "stored, match",+ [+ ({"api_key": "k"}, "endpoint is required"),+ ({"api_base": f"{RESOURCE}/openai/v1"}, "API key is required"),+ (+ {"api_base": f"{RESOURCE}/openai/deployments/gpt-4o", "api_key": "k"},+ "/openai/v1",+ ),+ ({"api_base": "not-a-url", "api_key": "k"}, "/openai/v1"),+ ],+ )+ async def test_a_form_that_cannot_be_called_fails_before_any_request(+ self, monkeypatch, stored, match+ ) -> None:+ def _no_calls(**_kw):+ raise AssertionError("the health check must not reach the network here")++ monkeypatch.setattr("httpx.AsyncClient", _no_calls)++ with pytest.raises(ValueError, match=match):+ await foundry.lightweight_health_check(stored)++ @pytest.mark.asyncio+ async def test_a_403_is_a_permission_result_not_a_bad_credential(self, monkeypatch) -> None:+ """Listing deployments can need a permission inference does not.++ Reporting "invalid key" for it sends the operator after the wrong+ problem.+ """++ class _Response:+ status_code = 403+ text = "Forbidden"++ class _Client:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *exc):+ return False++ async def get(self, url, headers=None):+ return _Response()++ monkeypatch.setattr("httpx.AsyncClient", lambda **_kw: _Client())++ with pytest.raises(PermissionError, match="cannot list deployments"):+ await foundry.lightweight_health_check(+ {"api_base": f"{RESOURCE}/openai/v1", "api_key": "k"}+ )++ @pytest.mark.asyncio+ async def test_a_rejected_credential_surfaces_the_upstream_detail(self, monkeypatch) -> None:+ class _Response:+ status_code = 401+ text = "Access denied due to invalid subscription key"++ class _Client:+ async def __aenter__(self):+ return self++ async def __aexit__(self, *exc):+ return False++ async def get(self, url, headers=None):+ return _Response()++ monkeypatch.setattr("httpx.AsyncClient", lambda **_kw: _Client())++ with pytest.raises(Exception, match="invalid subscription key"):+ await foundry.lightweight_health_check(+ {"api_base": f"{RESOURCE}/openai/v1", "api_key": "bad"}+ )+++class TestTransportMetadataCost:+ """What routing as `hosted_vllm` gives up, pinned so it stays visible."""++ def test_the_native_route_keeps_litellms_foundry_price_row(self) -> None:+ import litellm++ assert "azure_ai/gpt-6-luna" in litellm.model_cost++ def test_the_transport_route_has_no_price_row_of_its_own(self) -> None:+ """Cost attribution is lost for a deployment named after a model.++ Harmless today — OpenRAG computes no cost — and recoverable when it+ does: `completion_cost(..., base_model="azure_ai/<model>")` returns the+ native figure exactly.+ """+ import litellm++ assert "hosted_vllm/gpt-6-luna" not in litellm.model_cost++ def test_base_model_restores_cost_attribution_on_the_transport_route(self) -> None:+ from litellm import completion_cost+ from litellm.types.utils import Choices, Message, ModelResponse, Usage++ def _response(model: str) -> ModelResponse:+ response = ModelResponse(+ id="1",+ model=model,+ object="chat.completion",+ created=0,+ choices=[+ Choices(+ index=0,+ message=Message(role="assistant", content="ok"),+ finish_reason="stop",+ )+ ],+ )+ # `usage` is set after construction, not as a field: litellm+ # attaches it dynamically and its model does not declare it.+ response.usage = Usage( # type: ignore[attr-defined]+ prompt_tokens=1000, completion_tokens=1000, total_tokens=2000+ )+ return response++ native = completion_cost(+ completion_response=_response("azure_ai/gpt-6-luna"), model="azure_ai/gpt-6-luna"+ )+ via_transport = completion_cost(+ completion_response=_response("hosted_vllm/prod-llm-01"),+ model="hosted_vllm/prod-llm-01",+ base_model="azure_ai/gpt-6-luna",+ )+ assert native > 0+ assert via_transport == native++ def test_transport_identity_and_metadata_identity_stay_separate(self) -> None:+ """`hosted_vllm/<model>` is how it is called; `azure_ai/<model>` is what it is.++ LiteLLM has no rows under the transport, so metadata is looked up under+ the logical provider key — which is also LiteLLM's own key for Foundry.+ """+ from services.llm_gateway import _model_info++ # Foundry-exclusive: the bare name matches nothing, so only the+ # logical identity resolves it.+ assert not _model_info("hosted_vllm/Phi-4")+ assert _model_info("hosted_vllm/Phi-4", "azure_ai")+ assert _model_info("hosted_vllm/Phi-4", "azure_ai") == _model_info("azure_ai/Phi-4")++ def test_the_logical_identity_is_preferred_over_a_public_vendors_row(self) -> None:+ """A shared name resolves either way, but not to the same numbers.++ `gpt-6-luna` exists bare (OpenAI's row) and under `azure_ai` (Azure's).+ Trying the logical id first is what keeps Azure's pricing from being+ reported as OpenAI's.+ """+ from services.llm_gateway import _model_info++ assert _model_info("hosted_vllm/gpt-6-luna", "azure_ai") == _model_info(+ "azure_ai/gpt-6-luna"+ )++ def test_an_operator_named_deployment_resolves_under_neither(self) -> None:+ """No table can know a name its owner invented. The remaining limitation."""+ from services.llm_gateway import _model_info++ assert not _model_info("hosted_vllm/prod-llm-01", "azure_ai")+++def _config(api_base: str, **extra):+ """A config carrying one configured `azure_ai` provider."""+ from types import SimpleNamespace++ from config.config_manager import (+ AnthropicConfig,+ GenericProviderConfig,+ OllamaConfig,+ OpenAIConfig,+ ProvidersConfig,+ WatsonXConfig,+ )++ credentials = {"api_base": api_base, "api_key": "k", **extra}+ return SimpleNamespace(+ providers=ProvidersConfig(+ openai=OpenAIConfig(),+ anthropic=AnthropicConfig(),+ watsonx=WatsonXConfig(),+ ollama=OllamaConfig(),+ custom={"azure_ai": GenericProviderConfig(credentials=credentials, configured=True)},+ ),+ agent=SimpleNamespace(llm_model="", llm_provider="openai"),+ knowledge=SimpleNamespace(embedding_model="", embedding_provider="openai"),+ )+++class TestGatewayRouting:+ """`resolve_call` picks the transport from the stored endpoint."""++ @pytest.mark.parametrize("kind", ["chat", "embedding"])+ def test_the_v1_surface_is_routed_over_the_openai_compatible_transport(self, kind) -> None:+ from services.llm_gateway import resolve_call++ litellm_model, provider, credentials = resolve_call(+ "azure_ai:my-deployment", kind=kind, config=_config(f"{RESOURCE}/openai/v1")+ )++ assert litellm_model == "hosted_vllm/my-deployment"+ # The OpenRAG key is unchanged: it is what the caller, the credential+ # store and every indexed embedding space still see.+ assert provider == "azure_ai"+ assert credentials["api_base"] == f"{RESOURCE}/openai/v1"++ @pytest.mark.parametrize("kind", ["chat", "embedding"])+ def test_the_project_surface_is_routed_the_same_way(self, kind) -> None:+ from services.llm_gateway import resolve_call++ litellm_model, provider, _credentials = resolve_call(+ "azure_ai:my-deployment",+ kind=kind,+ config=_config(f"{RESOURCE}/api/projects/proj-1/openai/v1"),+ )++ assert litellm_model == "hosted_vllm/my-deployment"+ assert provider == "azure_ai"++ @pytest.mark.parametrize("api_base", [f"{RESOURCE}/models", RESOURCE])+ def test_the_legacy_surface_keeps_the_native_route(self, api_base) -> None:+ from services.llm_gateway import resolve_call++ litellm_model, provider, _credentials = resolve_call(+ "azure_ai:my-deployment", kind="chat", config=_config(api_base)+ )++ assert litellm_model == "azure_ai/my-deployment"+ assert provider == "azure_ai"++ def test_the_endpoint_reaches_litellm_normalized(self) -> None:+ from services.llm_gateway import resolve_call++ _model, _provider, credentials = resolve_call(+ "azure_ai:my-deployment",+ kind="chat",+ config=_config(f"{RESOURCE}/openai/v1/chat/completions"),+ )++ assert credentials["api_base"] == f"{RESOURCE}/openai/v1"++ def test_the_provider_id_round_trips_for_an_indexed_embedding_space(self) -> None:+ """`space:azure_ai:<model>` must still resolve after the transport change.++ The space id is persisted per chunk, so a change in routing that broke+ it would orphan indexed vectors.+ """+ from services.llm_gateway import resolve_call++ litellm_model, provider, _credentials = resolve_call(+ "space:azure_ai:my-deployment",+ kind="embedding",+ config=_config(f"{RESOURCE}/openai/v1"),+ )++ assert provider == "azure_ai"+ assert litellm_model == "hosted_vllm/my-deployment"+++class TestErrorLabels:+ """What the user is told the call was, when it fails.++ The label is built from the *routed* id, so for Foundry on `/openai/v1` it+ carries `hosted_vllm/`. Joined naively onto the OpenRAG key that produces+ `azure_ai/hosted_vllm/<deployment>`, which names two providers and reads+ like a bug in the error it appears in.+ """++ def test_the_transport_prefix_is_stripped_for_a_v1_foundry_model(self, monkeypatch) -> None:+ from services import llm_gateway++ monkeypatch.setattr(llm_gateway, "_get_config", lambda: _config(f"{RESOURCE}/openai/v1"))+ assert (+ llm_gateway._call_label("azure_ai", "hosted_vllm/my-deployment")+ == "azure_ai/my-deployment"+ )++ def test_the_legacy_route_needs_no_stripping(self, monkeypatch) -> None:+ from services import llm_gateway++ monkeypatch.setattr(llm_gateway, "_get_config", lambda: _config(f"{RESOURCE}/models"))+ assert (+ llm_gateway._call_label("azure_ai", "azure_ai/my-deployment")+ == "azure_ai/my-deployment"+ )++ def test_a_models_name_that_contains_a_slash_is_left_whole(self, monkeypatch) -> None:+ """Only a *transport* prefix comes off, never part of the model id.++ watsonx serves `openai/gpt-oss-120b`, whose own name starts with a+ provider key. Deriving the route from the id's first segment instead+ of from the configuration would eat it.+ """+ from services import llm_gateway++ monkeypatch.setattr(llm_gateway, "_get_config", lambda: _config(f"{RESOURCE}/openai/v1"))+ assert (+ llm_gateway._call_label("watsonx_onprem", "watsonx/openai/gpt-oss-120b")+ == "watsonx_onprem/openai/gpt-oss-120b"+ )++ def test_a_broken_configuration_still_produces_a_label(self, monkeypatch) -> None:+ """This runs while building an error message; it cannot raise its own."""+ from services import llm_gateway++ def _explode():+ raise RuntimeError("config is unreadable")++ monkeypatch.setattr(llm_gateway, "_get_config", _explode)+ assert llm_gateway._call_label("azure_ai", "hosted_vllm/my-deployment")+++class TestRouteResolutionFailsClosed:+ """A configuration that cannot be read must not fall back to a guess.++ `litellm_provider_key` treats an empty mapping as "nothing to go on" and+ answers with the static alias, which for Foundry is `azure_ai` — the+ native handler, and the wrong URL for a `/openai/v1` endpoint. Swallowing+ a read failure therefore turns a fixable error into the opaque upstream+ 404 this module exists to prevent.+ """++ def test_a_config_without_the_untranslated_form_is_not_an_error(self) -> None:+ """Some config objects simply do not keep it; that is not a failure."""+ from types import SimpleNamespace++ from services.llm_gateway import _stored_credentials++ assert _stored_credentials("azure_ai", SimpleNamespace(providers=object())) == {}+ assert _stored_credentials("azure_ai", SimpleNamespace()) == {}++ def test_a_failure_to_read_surfaces_instead_of_routing_on_the_alias(self) -> None:+ from types import SimpleNamespace++ from services.llm_gateway import _stored_credentials++ def _explode(_provider):+ raise RuntimeError("credential store is down")++ config = SimpleNamespace(providers=SimpleNamespace(stored_credentials=_explode))+ with pytest.raises(RuntimeError, match="credential store is down"):+ _stored_credentials("azure_ai", config)+++class TestRerouteGuardHygiene:+ """The guard runs on every `resolve_call`, so its memo is on a hot path."""++ def test_the_memo_is_bounded(self) -> None:+ """Its key holds the model id, which arrives in the request body.++ Unbounded, that is a cache an unauthenticated caller can grow without+ limit by varying the model name.+ """+ from services import llm_gateway++ llm_gateway.forget_route_mismatches()+ try:+ for index in range(llm_gateway._ROUTE_CHECK_MEMO_MAX * 2):+ llm_gateway._warn_on_unexpected_route(+ "azure_ai", f"hosted_vllm/model-{index}", "hosted_vllm"+ )+ assert len(llm_gateway._CHECKED_ROUTES) <= llm_gateway._ROUTE_CHECK_MEMO_MAX+ finally:+ llm_gateway.forget_route_mismatches()++ def test_a_repeated_model_does_not_re_run_the_resolver(self, monkeypatch) -> None:+ """One resolver call per distinct id, not one per request."""+ import litellm++ from services import llm_gateway++ calls: list[str] = []++ def _counting(model, **_kwargs):+ calls.append(model)+ return model, "hosted_vllm", None, None++ monkeypatch.setattr(litellm, "get_llm_provider", _counting)+ llm_gateway.forget_route_mismatches()+ try:+ for _ in range(5):+ llm_gateway._warn_on_unexpected_route(+ "azure_ai", "hosted_vllm/my-deployment", "hosted_vllm"+ )+ assert calls == ["hosted_vllm/my-deployment"]+ finally:+ llm_gateway.forget_route_mismatches()++ @pytest.mark.parametrize(+ "provider, litellm_model, route",+ [+ # `openai` sends the id unprefixed, so nothing was asserted.+ ("openai", "claude-sonnet-4", "openai"),+ # A model whose own *name* carries a vendor segment. The id still+ # does not begin with the route that was asked for.+ ("openai", "meta-llama/Llama-3-70B", "openai"),+ ],+ )+ def test_an_unasserted_route_is_not_second_guessed(+ self, monkeypatch, provider, litellm_model, route+ ) -> None:+ """LiteLLM resolving these elsewhere is not evidence of anything.++ The guard's claim is "we asked for `<route>/<name>`". Where the id+ does not carry the route, there is no claim, and an OpenAI-compatible+ server serving either of these would warn on every healthy request.+ """+ import litellm++ from services import llm_gateway++ def _unexpected(**_kwargs):+ pytest.fail("an unasserted route has nothing to check")++ monkeypatch.setattr(litellm, "get_llm_provider", _unexpected)+ llm_gateway.forget_route_mismatches()+ try:+ llm_gateway._warn_on_unexpected_route(provider, litellm_model, route)+ finally:+ llm_gateway.forget_route_mismatches()++ def test_a_prefixed_id_is_checked_even_when_the_route_is_the_provider_key(+ self, monkeypatch+ ) -> None:+ """The regression this guard exists for is an identity route.++ litellm 1.84.0 silently rerouted `azure_ai/gpt-4o` to `azure`, calling+ a Foundry hostname with the Azure OpenAI handler. Skipping the check+ wherever route == provider would have missed exactly that.+ """+ import litellm++ from services import llm_gateway++ warnings: list[dict] = []++ monkeypatch.setattr(+ litellm, "get_llm_provider", lambda model, **_k: (model, "azure", None, None)+ )+ monkeypatch.setattr(+ llm_gateway.logger,+ "warning",+ lambda _message, **fields: warnings.append(fields),+ )+ llm_gateway.forget_route_mismatches()+ try:+ llm_gateway._warn_on_unexpected_route("azure_ai", "azure_ai/gpt-4o", "azure_ai")+ finally:+ llm_gateway.forget_route_mismatches()++ assert warnings and warnings[0]["resolved_route"] == "azure"+++class TestSaveTimeModelProbe:+ """The validator's model probe must use the same transport the gateway will.++ These two have separate route-building code. Resolving the route without+ the stored credentials picks the static alias, so the probe called+ `azure_ai/<model>` against a `/openai/v1` endpoint — which LiteLLM rewrites+ to `/openai/v1/models/chat/completions`. A correctly configured provider+ then failed to save with "Resource not found", for every model, which read+ as a credential or endpoint problem rather than a routing one.+ """++ @pytest.mark.asyncio+ @pytest.mark.parametrize("kind", ["chat", "embedding"])+ @pytest.mark.parametrize("unsupported_endpoint", [False, True])+ async def test_route_errors_use_the_gateway_400(+ self, monkeypatch, kind, unsupported_endpoint+ ) -> None:+ from api.provider_validation import validate_provider_setup+ from services.llm_gateway import LlmGatewayError++ error = (+ foundry.UnsupportedEndpointError(foundry.UNSUPPORTED_ENDPOINT_MESSAGE)+ if unsupported_endpoint+ else ValueError("Invalid provider route")+ )++ def reject_route(*_args):+ raise error++ async def unexpected_call(**_kwargs):+ pytest.fail("An invalid route must fail before calling the provider")++ monkeypatch.setattr("services.model_catalog.litellm_provider_key", reject_route)+ monkeypatch.setattr("litellm.acompletion", unexpected_call)+ monkeypatch.setattr("litellm.aembedding", unexpected_call)++ with pytest.raises(LlmGatewayError) as caught:+ await validate_provider_setup(+ provider="azure_ai",+ credentials={"api_base": f"{RESOURCE}/openai/v1", "api_key": "k"},+ llm_model="my-deployment" if kind == "chat" else None,+ embedding_model="my-embed-deployment" if kind == "embedding" else None,+ verify_model=True,+ )++ assert caught.value.status_code == 400+ assert caught.value.message == str(error)+ assert caught.value.__cause__ is error++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "api_base, expected_route",+ [+ (f"{RESOURCE}/openai/v1", "hosted_vllm"),+ (f"{RESOURCE}/api/projects/p/openai/v1", "hosted_vllm"),+ (f"{RESOURCE}/models", "azure_ai"),+ ],+ )+ async def test_the_probe_routes_like_the_gateway(+ self, monkeypatch, api_base, expected_route+ ) -> None:+ from api import provider_validation++ captured: dict = {}++ async def _capture(model, **kwargs):+ captured["model"] = model+ raise AssertionError("stop before the network call")++ monkeypatch.setattr("litellm.acompletion", _capture)+ credentials = {"api_base": api_base, "api_key": "k"}++ with pytest.raises(AssertionError):+ await provider_validation._test_litellm_provider(+ provider="azure_ai",+ credentials=credentials,+ runtime_kwargs={},+ embedding_model=None,+ llm_model="my-deployment",+ )++ assert captured["model"] == f"{expected_route}/my-deployment"++ @pytest.mark.asyncio+ async def test_the_embedding_probe_routes_the_same_way(self, monkeypatch) -> None:+ from api import provider_validation++ captured: dict = {}++ async def _capture(model, **kwargs):+ captured["model"] = model+ raise AssertionError("stop before the network call")++ monkeypatch.setattr("litellm.aembedding", _capture)++ with pytest.raises(AssertionError):+ await provider_validation._test_litellm_provider(+ provider="azure_ai",+ credentials={"api_base": f"{RESOURCE}/openai/v1", "api_key": "k"},+ runtime_kwargs={},+ embedding_model="my-embed-deployment",+ llm_model=None,+ )++ assert captured["model"] == "hosted_vllm/my-embed-deployment"++ def test_a_provider_without_a_dynamic_route_is_unaffected(self) -> None:+ """The static alias stays the answer for everything else."""+ from services.model_catalog import litellm_provider_key++ stored = {"api_base": "https://cpd.example.com", "username": "u", "api_key": "k"}+ assert litellm_provider_key("watsonx_onprem", stored) == "watsonx"+ assert litellm_provider_key("openai", {"api_key": "k"}) == "openai"+++class TestRerouteGuard:+ """The guard compares against the route the gateway chose, not the key.++ For Foundry on `/openai/v1` the route and the provider key differ *by+ design*, so comparing against `azure_ai` would warn on every healthy call.+ """++ @staticmethod+ def _recorded_warnings(monkeypatch) -> list[str]:+ """Warnings the gateway emits, read off its module logger.++ Logging goes through structlog, which does not route to caplog.+ """+ from services import llm_gateway++ messages: list[str] = []++ class _Recorder:+ def warning(self, message, **fields):+ messages.append(f"{message} {fields}")++ def __getattr__(self, _name):+ return lambda *args, **kwargs: None++ monkeypatch.setattr(llm_gateway, "logger", _Recorder())+ llm_gateway.forget_route_mismatches()+ return messages++ @pytest.mark.parametrize("api_base", [f"{RESOURCE}/openai/v1", f"{RESOURCE}/models"])+ def test_the_chosen_transport_is_never_reported_as_a_mismatch(+ self, monkeypatch, api_base+ ) -> None:+ """Including the v1 case, where route and provider key differ."""+ from services.llm_gateway import resolve_call++ warnings = self._recorded_warnings(monkeypatch)+ resolve_call("azure_ai:my-deployment", kind="chat", config=_config(api_base))++ assert not [w for w in warnings if "different provider" in w]++ def test_litellm_redeciding_underneath_us_is_reported(self, monkeypatch) -> None:+ """What the litellm 1.84.0 `azure_ai` -> `azure` reroute looked like.++ The floor this repo pins no longer does it. This makes a return+ visible rather than an opaque 404 against a Foundry hostname.+ """+ from services import llm_gateway++ warnings = self._recorded_warnings(monkeypatch)+ monkeypatch.setattr(+ "litellm.get_llm_provider",+ lambda model, **_kw: (model.split("/", 1)[-1], "azure", None, None),+ )++ llm_gateway.resolve_call(+ "azure_ai:my-deployment", kind="chat", config=_config(f"{RESOURCE}/models")+ )++ reported = [w for w in warnings if "different provider" in w]+ assert reported+ assert "'resolved_route': 'azure'" in reported[0]+ assert "'intended_route': 'azure_ai'" in reported[0]++ def test_a_mismatch_is_reported_once_not_per_request(self, monkeypatch) -> None:+ from services import llm_gateway++ warnings = self._recorded_warnings(monkeypatch)+ monkeypatch.setattr(+ "litellm.get_llm_provider",+ lambda model, **_kw: (model.split("/", 1)[-1], "azure", None, None),+ )+ config = _config(f"{RESOURCE}/models")++ for _ in range(3):+ llm_gateway.resolve_call("azure_ai:my-deployment", kind="chat", config=config)++ assert len([w for w in warnings if "different provider" in w]) == 1diff --git a/tests/unit/services/test_llm_gateway.py b/tests/unit/services/test_llm_gateway.pyindex cefbaab08..b0eb86175 100644--- a/tests/unit/services/test_llm_gateway.py+++ b/tests/unit/services/test_llm_gateway.py@@ -2004,7 +2004,10 @@ class TestToolsBesideReasoningEffort:monkeypatch.setattr(llm_gateway,"_model_info",- lambda _m: {"supports_none_reasoning_effort": supports_none},+ # Takes the logical provider too: a model routed under a transport+ # alias has no row under the transport id, so lookups pass the+ # provider key alongside it.+ lambda _m, _provider=None: {"supports_none_reasoning_effort": supports_none},)@pytest.mark.asyncio