From d28fa6accb7dda6f67854767003e5bc9e5dca44a Mon Sep 17 00:00:00 2001 From: Lukasz Raczylo Date: Sat, 28 Nov 2026 01:02:52 +0000 Subject: [PATCH] feat(models): advertise max_context_length and query every modelBaseUrls upstream GET /v1/models now emits max_context_length next to the other context fields, so a downstream gateway can read it through metadataPath. The field is omitted when the context window is unknown. Discovery and metadataPath now query baseUrl and each distinct modelBaseUrls upstream. The gateway keeps an id only from the upstream that serves it. Discovery fails when any upstream fails and keeps the last-known set. Metadata keeps the ids of the upstreams that answered. --- README.md | 37 ++++++---- models_max_context_length_test.go | 116 ++++++++++++++++++++++++++++++ provider_openai.go | 71 +++++++++++++++++- registry.go | 10 +-- registry_modelmeta_test.go | 4 +- smart_router_listing_test.go | 4 +- upstreams_discovery_test.go | 78 ++++++++++++++++++++ 7 files changed, 297 insertions(+), 23 deletions(-) create mode 100644 models_max_context_length_test.go create mode 100644 upstreams_discovery_test.go diff --git a/README.md b/README.md index b662930..78d3932 100644 --- a/README.md +++ b/README.md @@ -469,7 +469,7 @@ also a construction error, never a panic (`providers.go`, `mcp_a2a.go`, | `models` | `[]string` | `[]` | Explicit model ids this provider serves. Combined with any discovered ids. | | `discovery` | `bool` | `false` | Pull the provider's own model-listing endpoint at startup, then no more often than `discoveryInterval` when requests arrive. A discovery failure is logged and non-fatal; construction still succeeds on `models` alone. | | `metadataPath` | `string` | `""` (no metadata capture) | Only read by `openai`-type providers. A second endpoint, fetched alongside `discovery`, that reports per-model context length — for example `/api/v0/models` on an LM Studio server. Must start with `/` when set (checked at construction). See [Model metadata](#model-metadata). | -| `modelBaseUrls` | `map[string]string` | `{}` | Only for `openai`-type providers. Maps a bare model id (the id sent upstream) to the base URL that serves it, instead of `baseUrl`. Its keys are declared models of the provider, like `models`, and are never polled by `discovery`. Each URL must be absolute `http(s)` with no userinfo, query or fragment (checked at construction). See [Several upstreams per provider](#several-upstreams-per-provider). | +| `modelBaseUrls` | `map[string]string` | `{}` | Only for `openai`-type providers. Maps a bare model id (the id sent upstream) to the base URL that serves it, instead of `baseUrl`. Its keys are declared models of the provider, like `models`, and are never added or removed by `discovery`, though `discovery` and `metadataPath` also query each distinct URL. Each URL must be absolute `http(s)` with no userinfo, query or fragment (checked at construction). See [Several upstreams per provider](#several-upstreams-per-provider). | | `pathBaseUrls` | `map[string]string` | `{}` | Only for `openai`-type providers. Maps a native passthrough path prefix (such as `/v1/decide`) to a base URL, for requests whose body names no `modelBaseUrls` model. Longest prefix wins, matched on whole path segments. Same URL rules as `modelBaseUrls`. | | `passthrough` | `*bool` | `nil` (enabled) | `nil` or `true`: this provider's native passthrough route (`/{name}/...`) stays reachable, unchanged from before this field existed. `false`: the route is disabled — `ServeHTTP` treats it exactly like an unconfigured provider name, falling through to the ordinary unknown-route 404 without even reaching authentication. Does not affect the MCP/A2A target proxy, which has its own routing prefix. | | `requestTimeout` | `string` (Go duration) | Inherits the top-level `requestTimeout` (`5m` if that is also unset) | Overrides the global request timeout for this provider alone, including its native passthrough route — see [Request timeout](#request-timeout). An explicit override always wins over the global default. Empty inherits; a value that fails to parse, or parses to zero or a negative duration, is a construction error. | @@ -1418,7 +1418,7 @@ The gateway picks the highest tier below the first attempted tier, and goes lowe - **Learned ratio**: after 50 served requests with provider-reported usage, the gateway learns bytes per token for each upstream model. The ratio stays between 1.5 and 6.0 and lives in memory on each instance. - **No fit**: when the check would skip every target, the gateway uses the model with the largest known window instead of returning `404`. - **Vision**: a request with an image skips models that set `vision: false` in `modelMeta`. -- **Advertised window**: `GET /v1/models` lists a router when the group may use its name and at least one target. With `contextEscalation` on, the entry advertises the largest known window of all targets in `context_window`, `context_length`, and `max_model_len`. With `contextEscalation: false`, it advertises the smallest known window. Targets with an unknown window do not count. When no target has a known window, the fields are omitted. +- **Advertised window**: `GET /v1/models` lists a router when the group may use its name and at least one target. With `contextEscalation` on, the entry advertises the largest known window of all targets in `context_window`, `context_length`, `max_model_len`, and `max_context_length`. With `contextEscalation: false`, it advertises the smallest known window. Targets with an unknown window do not count. When no target has a known window, the fields are omitted. - **Override**: a `modelMeta` entry keyed by the router name replaces the value. It needs `contextTokens` above zero. The gateway logs a one-time warning when the override exceeds the largest known target window. ### Access and response headers @@ -1551,8 +1551,10 @@ providers: metadataPath: "/api/v0/models" ``` -The response's `loaded_context_length` field is preferred over -`max_context_length` when both are present — it reflects the context +The response's context fields rank `loaded_context_length`, then +`max_context_length`, then `max_model_len` (vLLM and TensorFold report +only the last, so a plain `/v1/models` works as `metadataPath`). +`loaded_context_length` is preferred when present — it reflects the context actually usable right now, which an operator can configure smaller than the model's own maximum under VRAM-constrained runtime settings. This means the reported context window can **change** across a discovery @@ -1593,17 +1595,24 @@ known: "context_window": 400000, "context_length": 400000, "max_model_len": 400000, + "max_context_length": 400000, "pricing": {"input_per_mtok_usd": 1.25, "output_per_mtok_usd": 10} } ``` -- `context_window`, `context_length`, `max_model_len` — the same integer - token count under all three dialect spellings, omitted together when - unknown. OpenAI's own schema has no context field, so each client reads - whichever vendor dialect it was built against: `context_length` is the - OpenRouter spelling, `max_model_len` the vLLM one. A client whose - dialect is missing does not ask — it silently substitutes its own - default (128k is a common one), so all three are emitted. +- `context_window`, `context_length`, `max_model_len`, + `max_context_length` — the same integer token count under all four + dialect spellings, omitted together when unknown. OpenAI's own schema + has no context field, so each client reads whichever vendor dialect it + was built against: `context_length` is the OpenRouter spelling, + `max_model_len` the vLLM one, `max_context_length` the LM Studio one. + A client whose dialect is missing does not ask — it silently + substitutes its own default (128k is a common one), so all four are + emitted. A downstream gateway whose provider sets + `metadataPath: "/v1/models"` against this gateway reads + `max_context_length`. The value follows the normal resolution + (`modelMeta`, then discovery, then the built-in table) for plain ids, + `provider/model` ids, aliases and smart router models. - `pricing` — `{input_per_mtok_usd, output_per_mtok_usd}`, both floats in USD per 1,000,000 tokens. Omitted when unknown; present with `0` values for an explicitly free model — a known zero, not an absent @@ -2390,7 +2399,11 @@ providers: first 64KiB). A `modelBaseUrls` hit wins; otherwise the longest matching `pathBaseUrls` prefix; otherwise `baseUrl`. Only providers that set `modelBaseUrls` read the body for this purpose. -- **Discovery** polls `baseUrl` only. `modelBaseUrls` ids are static. +- **Discovery and `metadataPath`** query `baseUrl` and every distinct + `modelBaseUrls` upstream, one request per upstream. An id is taken only from + the upstream its requests route to. Discovery fails as a whole when any + upstream fails, keeping the last-known set; metadata keeps the ids of the + upstreams that answered. `modelBaseUrls` ids stay declared models. - **Admin catalog**: each `pathBaseUrls` key appears as a pseudo-model row (`gx10/v1/decide`). It is display only and never routable as a model. `kinds` labels a model id or a path key. The Models page then groups the diff --git a/models_max_context_length_test.go b/models_max_context_length_test.go new file mode 100644 index 0000000..324eef7 --- /dev/null +++ b/models_max_context_length_test.go @@ -0,0 +1,116 @@ +package traefikllmgateway + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func newModelsCatalogGateway(t *testing.T, cfg *Config) http.Handler { + t.Helper() + cfg.Groups = map[string]*GroupConfig{"default": {}} + cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "tester", Group: "default", APIKey: "sk-user"}}} + h, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), cfg, "llmgw") + require.NoError(t, err) + return h +} + +func TestHandleModels_MaxContextLength(t *testing.T) { + t.Parallel() + cfg := CreateConfig() + cfg.Providers = map[string]*ProviderConfig{ + "openai": {Type: "openai", APIKey: "sk-test", Models: []string{"known", "mystery-model", "big", "small", "shared"}}, + "other": {Type: "openai", APIKey: "sk-test", Models: []string{"shared"}}, + } + cfg.ModelMeta = map[string]*ModelMetaConfig{ + "known": {ContextTokens: 128000}, + "openai/shared": {ContextTokens: 64000}, + "big": {ContextTokens: 200000}, + "small": {ContextTokens: 32000}, + "override": {ContextTokens: 8000}, + } + cfg.ModelAliases = map[string]string{ + "inherit": "openai/known", + "override": "openai/known", + } + cfg.SmartRouters = map[string]*SmartRouterConfig{ + "smart": {Tiers: []SmartRouterTier{{Name: "low", Models: []string{"openai/big", "openai/small"}}}}, + } + h := newModelsCatalogGateway(t, cfg) + + req := httptest.NewRequest(http.MethodGet, "/v1/models", nil) + req.Header.Set("Authorization", "Bearer sk-user") + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + + var body struct { + Data []map[string]any `json:"data"` + } + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body)) + byID := make(map[string]map[string]any, len(body.Data)) + for _, e := range body.Data { + byID[e["id"].(string)] = e + } + + cases := []struct { + name string + id string + want int + }{ + {"modelMeta contextTokens set", "known", 128000}, + {"provider/model form", "openai/shared", 64000}, + {"provider/model form without metadata", "other/shared", 0}, + {"unknown omits the field", "mystery-model", 0}, + {"alias inherits target", "inherit", 128000}, + {"alias with own override", "override", 8000}, + {"smart router largest target window", "smart", 200000}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + entry, ok := byID[tc.id] + require.True(t, ok, "missing %q in %v", tc.id, byID) + got, present := entry["max_context_length"] + if tc.want == 0 { + assert.False(t, present, "max_context_length must be omitted, got %v", got) + return + } + assert.Equal(t, float64(tc.want), got) + assert.Equal(t, entry["context_window"], got) + }) + } +} + +// A downstream gateway reading this gateway's /v1/models through +// metadataPath must learn the same context values the producer advertises. +func TestHandleModels_MaxContextLength_RoundTripsThroughMetadataFetcher(t *testing.T) { + t.Parallel() + cfg := CreateConfig() + cfg.Providers = map[string]*ProviderConfig{ + "openai": {Type: "openai", APIKey: "sk-test", Models: []string{"known", "mystery-model"}}, + } + cfg.ModelMeta = map[string]*ModelMetaConfig{"known": {ContextTokens: 128000}} + cfg.ModelAliases = map[string]string{"inherit": "openai/known"} + h := newModelsCatalogGateway(t, cfg) + + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.Header.Set("Authorization", "Bearer sk-user") + h.ServeHTTP(w, r) + })) + defer upstream.Close() + + a := newOpenAIAdapter("down", upstream.URL, "sk-user") + a.metadataPath = "/v1/models" + got, err := a.fetchModelMetadata(context.Background()) + require.NoError(t, err) + + assert.Equal(t, map[string]int{ + "known": 128000, + "inherit": 128000, + }, got) +} diff --git a/provider_openai.go b/provider_openai.go index 7ee1988..41f4265 100644 --- a/provider_openai.go +++ b/provider_openai.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "net/http" + "sort" "strings" "time" ) @@ -440,9 +441,48 @@ type modelsPayload struct { } `json:"data"` } -// listModels implements providerAdapter. +// listModels implements providerAdapter. It queries baseURL and every +// distinct modelBaseUrls upstream; an id counts only when the upstream +// that lists it is the one requests for that id are routed to. Any failing +// upstream fails the whole listing, so a refresh never drops the models of +// an upstream that is briefly down. func (a *openaiAdapter) listModels(ctx context.Context) ([]string, error) { - resp, err := upstreamJSON(ctx, a.client, http.MethodGet, a.baseURL+"/v1/models", a.requestHeaders(false), nil, a.retry, a.timeout, a.adapterName) + var ids []string + seen := make(map[string]bool) + for _, base := range a.upstreamBases() { + listed, err := a.listModelsFrom(ctx, base) + if err != nil { + return nil, err + } + for _, id := range listed { + if a.baseForModel(id) != base || seen[id] { + continue + } + seen[id] = true + ids = append(ids, id) + } + } + return ids, nil +} + +// upstreamBases returns baseURL followed by the other distinct modelBaseUrls +// values in sorted order. +func (a *openaiAdapter) upstreamBases() []string { + bases := []string{a.baseURL} + var extra []string + seen := map[string]bool{a.baseURL: true} + for _, b := range a.modelBases { + if !seen[b] { + seen[b] = true + extra = append(extra, b) + } + } + sort.Strings(extra) + return append(bases, extra...) +} + +func (a *openaiAdapter) listModelsFrom(ctx context.Context, base string) ([]string, error) { + resp, err := upstreamJSON(ctx, a.client, http.MethodGet, base+"/v1/models", a.requestHeaders(false), nil, a.retry, a.timeout, a.adapterName) if err != nil { return nil, err } @@ -516,7 +556,32 @@ func (a *openaiAdapter) fetchModelMetadata(ctx context.Context) (map[string]int, return nil, nil } - resp, err := upstreamJSON(ctx, a.client, http.MethodGet, a.baseURL+a.metadataPath, a.requestHeaders(false), nil, a.retry, a.timeout, a.adapterName) + out := make(map[string]int) + var firstErr error + ok := false + for _, base := range a.upstreamBases() { + got, err := a.fetchModelMetadataFrom(ctx, base) + if err != nil { + if firstErr == nil { + firstErr = err + } + continue + } + ok = true + for id, n := range got { + if a.baseForModel(id) == base { + out[id] = n + } + } + } + if !ok { + return nil, firstErr + } + return out, nil +} + +func (a *openaiAdapter) fetchModelMetadataFrom(ctx context.Context, base string) (map[string]int, error) { + resp, err := upstreamJSON(ctx, a.client, http.MethodGet, base+a.metadataPath, a.requestHeaders(false), nil, a.retry, a.timeout, a.adapterName) if err != nil { return nil, err } diff --git a/registry.go b/registry.go index fa7a33b..092b5f5 100644 --- a/registry.go +++ b/registry.go @@ -2264,13 +2264,14 @@ func (m *modelRegistry) aliasEntriesFor(grp *group) map[string]map[string]any { // both cost fields 0) — that is a known, meaningful zero, not an absent // one. // -// The context window is emitted under THREE keys carrying the identical -// integer: "context_window", "context_length" (the OpenRouter spelling) -// and "max_model_len" (the vLLM spelling). OpenAI's own /v1/models +// The context window is emitted under FOUR keys carrying the identical +// integer: "context_window", "context_length" (the OpenRouter spelling), +// "max_model_len" (the vLLM spelling) and "max_context_length" (the LM +// Studio spelling, read by a downstream gateway's metadataPath fetcher). OpenAI's own /v1/models // schema has no context field at all, so every client that wants one // reads some vendor dialect, and a client whose dialect is missing // silently substitutes its own default instead of asking. Emitting all -// three costs two map entries and removes that whole failure class — +// four costs three map entries and removes that whole failure class — // the same reason the metadata FETCHER already parses all of these // dialects on the inbound side (provider_openai.go's modelMetadata). func modelObject(id, ownedBy string, meta resolvedModelMeta) map[string]any { @@ -2279,6 +2280,7 @@ func modelObject(id, ownedBy string, meta resolvedModelMeta) map[string]any { obj["context_window"] = meta.ContextTokens obj["context_length"] = meta.ContextTokens obj["max_model_len"] = meta.ContextTokens + obj["max_context_length"] = meta.ContextTokens } if meta.CostKnown { obj["pricing"] = map[string]any{ diff --git a/registry_modelmeta_test.go b/registry_modelmeta_test.go index d492369..6196a19 100644 --- a/registry_modelmeta_test.go +++ b/registry_modelmeta_test.go @@ -395,14 +395,14 @@ func TestModelObject_ContextDialectMirrors(t *testing.T) { t.Parallel() known := modelObject("m", "prov", resolvedModelMeta{ContextTokens: 1048576, ContextKnown: true}) - for _, key := range []string{"context_window", "context_length", "max_model_len"} { + for _, key := range []string{"context_window", "context_length", "max_model_len", "max_context_length"} { if known[key] != 1048576 { t.Errorf("known[%q] = %v, want 1048576", key, known[key]) } } unknown := modelObject("m", "prov", resolvedModelMeta{}) - for _, key := range []string{"context_window", "context_length", "max_model_len"} { + for _, key := range []string{"context_window", "context_length", "max_model_len", "max_context_length"} { if v, present := unknown[key]; present { t.Errorf("unknown[%q] present (%v), want omitted entirely", key, v) } diff --git a/smart_router_listing_test.go b/smart_router_listing_test.go index 1ebdece..fbe8022 100644 --- a/smart_router_listing_test.go +++ b/smart_router_listing_test.go @@ -90,13 +90,13 @@ func TestModelRegistry_ListFor_RouterAdvertisesTargetContext(t *testing.T) { } entry := routerListEntry(t, cfg, "smart") if !tc.known { - for _, k := range []string{"context_window", "context_length", "max_model_len"} { + for _, k := range []string{"context_window", "context_length", "max_model_len", "max_context_length"} { _, present := entry[k] assert.False(t, present, "%s must be omitted", k) } return } - for _, k := range []string{"context_window", "context_length", "max_model_len"} { + for _, k := range []string{"context_window", "context_length", "max_model_len", "max_context_length"} { assert.Equal(t, tc.want, entry[k], k) } }) diff --git a/upstreams_discovery_test.go b/upstreams_discovery_test.go new file mode 100644 index 0000000..88e881f --- /dev/null +++ b/upstreams_discovery_test.go @@ -0,0 +1,78 @@ +package traefikllmgateway + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func modelsServer(t *testing.T, body string, hits *atomic.Int32) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if hits != nil { + hits.Add(1) + } + if r.URL.Path != "/v1/models" { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = fmt.Fprint(w, body) + })) + t.Cleanup(srv.Close) + return srv +} + +func TestOpenAIAdapter_ModelBaseURLs_DiscoveryAndMetadataQueryEveryUpstream(t *testing.T) { + t.Parallel() + var hitsA, hitsB atomic.Int32 + // Upstream B also lists "only-on-main", which is routed to baseURL, so + // B's claim on it must be ignored. + a := modelsServer(t, `{"data":[{"id":"main-model","max_model_len":1000},{"id":"only-on-main","max_model_len":2000}]}`, &hitsA) + b := modelsServer(t, `{"data":[{"id":"glm","max_model_len":524288},{"id":"qwen","max_model_len":262144,"loaded_context_length":100000},{"id":"only-on-main","max_model_len":999}]}`, &hitsB) + + ad := newOpenAIAdapter("d1", a.URL, "") + ad.modelBases = map[string]string{"glm": b.URL, "qwen": b.URL} + ad.metadataPath = "/v1/models" + + ids, err := ad.listModels(context.Background()) + require.NoError(t, err) + assert.Equal(t, []string{"main-model", "only-on-main", "glm", "qwen"}, ids) + + got, err := ad.fetchModelMetadata(context.Background()) + require.NoError(t, err) + assert.Equal(t, map[string]int{ + "main-model": 1000, + "only-on-main": 2000, + "glm": 524288, + "qwen": 100000, + }, got) + assert.EqualValues(t, 2, hitsA.Load(), "baseURL queried once per call") + assert.EqualValues(t, 2, hitsB.Load(), "shared modelBaseUrls upstream queried once per call, not once per model") +} + +func TestOpenAIAdapter_ModelBaseURLs_FailingUpstream(t *testing.T) { + t.Parallel() + good := modelsServer(t, `{"data":[{"id":"main-model","max_model_len":1000}]}`, nil) + bad := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + })) + t.Cleanup(bad.Close) + + ad := newOpenAIAdapter("d1", good.URL, "") + ad.modelBases = map[string]string{"glm": bad.URL} + ad.metadataPath = "/v1/models" + + _, err := ad.listModels(context.Background()) + assert.Error(t, err, "discovery must fail rather than drop the failing upstream's models") + + got, err := ad.fetchModelMetadata(context.Background()) + require.NoError(t, err) + assert.Equal(t, map[string]int{"main-model": 1000}, got, "metadata keeps the healthy upstream's ids") +}