mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-12-06 11:03:52 +00:00
feat(models): advertise and discover model vision capability
GET /v1/models now carries a known vision flag in two forms: architecture.input_modalities for OpenRouter-style clients and other gateways, and info.meta.capabilities.vision for Open WebUI. An unknown flag adds no field. Discovery through metadataPath reads the same two forms from the upstream. Thus a flag set in modelMeta on one gateway reaches the next gateway and Open WebUI. A field in another shape is ignored and does not fail the fetch. The flag resolves from the alias modelMeta entry, then the target modelMeta entry, then discovery. The smart router uses the resolved flag. An unknown flag still counts as capable.
This commit is contained in:
@@ -1106,7 +1106,7 @@ changes what a request is billed.
|
||||
| `inputCostPerMTokMicroUsd` | `int64` | `0` (not overridden) | Input cost per 1,000,000 tokens, in micro-USD (1 USD = 1,000,000). `0` falls through to the next layer unless `free` is set. Must not be negative. |
|
||||
| `outputCostPerMTokMicroUsd` | `int64` | `0` (not overridden) | Output cost per 1,000,000 tokens, in micro-USD. Same fallthrough rule as `inputCostPerMTokMicroUsd`. |
|
||||
| `free` | `bool` | `false` | `true` sets both cost fields to an explicit, known zero — distinct from leaving them at `0`, which means "not overridden here, keep looking." Rejected at construction when combined with a non-zero cost field (contradictory). |
|
||||
| `vision` | `bool` | unset (treated as capable) | Declares whether the model accepts image input. A [smart router](#smart-routers) skips a model with `vision: false` when the request carries an image. An unset value or a missing entry counts as capable. |
|
||||
| `vision` | `bool` | unset (discovery, then treated as capable) | Declares whether the model accepts image input. It wins over a flag that discovery captured. A [smart router](#smart-routers) skips a model with `vision: false` when the request carries an image. When neither `modelMeta` nor discovery sets it, the model counts as capable. `GET /v1/models` advertises a known value (see [extension fields](#get-v1models-extension-fields)). |
|
||||
|
||||
### `TargetConfig` (an `mcpServers` entry)
|
||||
|
||||
@@ -1604,7 +1604,7 @@ The gateway picks the highest tier below the first attempted tier, and goes lowe
|
||||
- **Estimate**: the prompt estimate counts one token per four bytes of these inputs: message text, the system prompt, the `tools` schema, OpenAI `tool_calls` arguments, and Anthropic `tool_use` input. Each image adds 1000 tokens. Very large structured payloads count as a lower bound.
|
||||
- **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`.
|
||||
- **Vision**: a request with an image skips models whose resolved vision flag is `false`: from `modelMeta`, else from discovery.
|
||||
- **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.
|
||||
|
||||
@@ -1741,6 +1741,13 @@ providers:
|
||||
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`).
|
||||
The same response can carry a vision flag per model, in one of two
|
||||
dialects. Open WebUI's `info.meta.capabilities.vision` wins. Otherwise a
|
||||
non-empty `architecture.input_modalities` list (OpenRouter, llama.cpp)
|
||||
means vision when it names `image`. A field in another shape is ignored
|
||||
and does not fail the fetch. vLLM, TensorFold and TEI send neither field,
|
||||
so set `modelMeta.<model>.vision` for their vision models.
|
||||
|
||||
`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
|
||||
@@ -1783,7 +1790,9 @@ known:
|
||||
"context_length": 400000,
|
||||
"max_model_len": 400000,
|
||||
"max_context_length": 400000,
|
||||
"pricing": {"input_per_mtok_usd": 1.25, "output_per_mtok_usd": 10}
|
||||
"pricing": {"input_per_mtok_usd": 1.25, "output_per_mtok_usd": 10},
|
||||
"architecture": {"input_modalities": ["text", "image"]},
|
||||
"info": {"meta": {"capabilities": {"vision": true}}}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1804,6 +1813,13 @@ known:
|
||||
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
|
||||
field.
|
||||
- `architecture.input_modalities` and `info.meta.capabilities.vision` —
|
||||
the resolved vision flag (`modelMeta.vision`, then discovery), in two
|
||||
dialects, omitted together when unknown. Open WebUI copies `info` into
|
||||
its model record and enables image upload from it. A saved Open WebUI
|
||||
model entry or `DEFAULT_MODEL_METADATA` still overrides it on the Open
|
||||
WebUI side. A downstream gateway reads either field through its
|
||||
`metadataPath`, so a flag set on one gateway reaches the next one.
|
||||
|
||||
The admin dashboard's `GET /admin/api/overview` exposes the identical
|
||||
resolved values per provider (`providers[].modelMeta`, keyed by upstream
|
||||
|
||||
+3
-2
@@ -670,8 +670,9 @@ type ModelPricing struct {
|
||||
// fallback a zero cost field means when Free is false. Setting Free
|
||||
// true together with a non-zero cost field is rejected at construction
|
||||
// (validateModelMeta) as a contradictory config. Vision, when set, declares
|
||||
// whether the model accepts image input; nil means unknown, treated as
|
||||
// capable (modelVisionCapable, modelmeta.go).
|
||||
// whether the model accepts image input and wins over a discovered flag; nil
|
||||
// falls back to discovery, and unknown is treated as capable (visionCapable,
|
||||
// modelmeta.go).
|
||||
type ModelMetaConfig struct {
|
||||
Vision *bool `json:"vision,omitempty"`
|
||||
ContextTokens int `json:"contextTokens,omitempty"`
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
package traefikllmgateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func boolPtr(v bool) *bool { return &v }
|
||||
|
||||
func TestDiscoveredVisionOf(t *testing.T) {
|
||||
t.Parallel()
|
||||
tests := []struct {
|
||||
want *bool
|
||||
name string
|
||||
entry string
|
||||
}{
|
||||
{nil, "vllm sends nothing", `{"id":"m","max_model_len":8192}`},
|
||||
{boolPtr(false), "llama.cpp text only", `{"id":"m","architecture":{"input_modalities":["text"],"output_modalities":["text"]}}`},
|
||||
{boolPtr(true), "openrouter image", `{"id":"m","architecture":{"input_modalities":["text","image"]}}`},
|
||||
{nil, "empty modality list is unknown", `{"id":"m","architecture":{"input_modalities":[]}}`},
|
||||
{boolPtr(true), "open webui true", `{"id":"m","info":{"meta":{"capabilities":{"vision":true}}}}`},
|
||||
{boolPtr(false), "open webui false beats image modality", `{"id":"m","architecture":{"input_modalities":["image"]},"info":{"meta":{"capabilities":{"vision":false}}}}`},
|
||||
{nil, "architecture as a string is ignored", `{"id":"m","architecture":"llama"}`},
|
||||
{boolPtr(true), "info without vision falls back to modalities", `{"id":"m","architecture":{"input_modalities":["text","image"]},"info":{"meta":{}}}`},
|
||||
{nil, "vision of wrong type is ignored", `{"id":"m","info":{"meta":{"capabilities":{"vision":"yes"}}}}`},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
var e modelMetadataEntry
|
||||
require.NoError(t, json.Unmarshal([]byte(tt.entry), &e))
|
||||
got := discoveredVisionOf(e.Architecture, e.Info)
|
||||
if tt.want == nil {
|
||||
assert.Nil(t, got)
|
||||
return
|
||||
}
|
||||
require.NotNil(t, got)
|
||||
assert.Equal(t, *tt.want, *got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A llama.cpp-style `capabilities` array next to the fields we read must not fail the whole payload.
|
||||
func TestFetchModelMetadata_CapturesVisionPerUpstream(t *testing.T) {
|
||||
t.Parallel()
|
||||
main := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = fmt.Fprint(w, `{"data":[{"id":"main","max_model_len":4096,"capabilities":["completion"],"architecture":{"input_modalities":["text"]}}]}`)
|
||||
}))
|
||||
t.Cleanup(main.Close)
|
||||
vis := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = fmt.Fprint(w, `{"data":[{"id":"ds","max_model_len":1048576,"info":{"meta":{"capabilities":{"vision":true}}}},{"id":"main","architecture":{"input_modalities":["image"]}}]}`)
|
||||
}))
|
||||
t.Cleanup(vis.Close)
|
||||
ad := newOpenAIAdapter("d1", main.URL, "")
|
||||
ad.modelBases = map[string]string{"ds": vis.URL}
|
||||
ad.metadataPath = "/v1/models"
|
||||
|
||||
ctxs, err := ad.fetchModelMetadata(context.Background())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, map[string]int{"main": 4096, "ds": 1048576}, ctxs)
|
||||
|
||||
got := ad.discoveredVision()
|
||||
require.Len(t, got, 2)
|
||||
assert.False(t, got["main"], "main's own upstream wins over another upstream's entry for the same id")
|
||||
assert.True(t, got["ds"])
|
||||
}
|
||||
|
||||
func TestRegistry_ResolveMetaUsesDiscoveredVision(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = fmt.Fprint(w, `{"data":[{"id":"ds","info":{"meta":{"capabilities":{"vision":true}}}},{"id":"txt","architecture":{"input_modalities":["text"]}},{"id":"plain"}]}`)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
ad := newOpenAIAdapter("d1", srv.URL, "")
|
||||
ad.metadataPath = "/v1/models"
|
||||
cfg := &Config{
|
||||
Providers: map[string]*ProviderConfig{"d1": {Discovery: true, MetadataPath: "/v1/models"}},
|
||||
ModelMeta: map[string]*ModelMetaConfig{"txt": {Vision: boolPtr(true)}},
|
||||
}
|
||||
reg, err := newModelRegistry(map[string]providerAdapter{"d1": ad}, cfg, func(string, ...any) {})
|
||||
require.NoError(t, err)
|
||||
reg.captureModelMetadata(context.Background(), "d1", ad, reg.states["d1"])
|
||||
|
||||
ds := reg.resolveMetaFor("d1", "ds")
|
||||
require.NotNil(t, ds.Vision)
|
||||
assert.True(t, *ds.Vision)
|
||||
|
||||
txt := reg.resolveMetaFor("d1", "txt")
|
||||
require.NotNil(t, txt.Vision)
|
||||
assert.True(t, *txt.Vision, "operator modelMeta beats discovery")
|
||||
|
||||
assert.Nil(t, reg.resolveMetaFor("d1", "plain").Vision, "nothing known stays unknown")
|
||||
}
|
||||
|
||||
func TestResolveAliasModelMeta_AliasVisionWins(t *testing.T) {
|
||||
t.Parallel()
|
||||
cfg := map[string]*ModelMetaConfig{
|
||||
"m": {Vision: boolPtr(true)},
|
||||
"fast": {Vision: boolPtr(false)},
|
||||
}
|
||||
got := resolveAliasModelMeta("fast", "p", "m", cfg, 0, false)
|
||||
require.NotNil(t, got.Vision)
|
||||
assert.False(t, *got.Vision)
|
||||
|
||||
inherited := resolveAliasModelMeta("other", "p", "m", cfg, 0, false)
|
||||
require.NotNil(t, inherited.Vision)
|
||||
assert.True(t, *inherited.Vision)
|
||||
}
|
||||
|
||||
func TestModelObject_Capabilities(t *testing.T) {
|
||||
t.Parallel()
|
||||
tests := []struct {
|
||||
vision *bool
|
||||
name string
|
||||
modalities []any
|
||||
}{
|
||||
{name: "unknown omits both fields"},
|
||||
{name: "vision", vision: boolPtr(true), modalities: []any{"text", "image"}},
|
||||
{name: "text only", vision: boolPtr(false), modalities: []any{"text"}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
raw, err := json.Marshal(modelObject("m", "p", resolvedModelMeta{Vision: tt.vision}))
|
||||
require.NoError(t, err)
|
||||
var obj map[string]any
|
||||
require.NoError(t, json.Unmarshal(raw, &obj))
|
||||
if tt.vision == nil {
|
||||
assert.NotContains(t, obj, "architecture")
|
||||
assert.NotContains(t, obj, "info")
|
||||
return
|
||||
}
|
||||
assert.Equal(t, tt.modalities, obj["architecture"].(map[string]any)["input_modalities"])
|
||||
caps := obj["info"].(map[string]any)["meta"].(map[string]any)["capabilities"].(map[string]any)
|
||||
assert.Equal(t, *tt.vision, caps["vision"])
|
||||
|
||||
var e modelMetadataEntry
|
||||
require.NoError(t, json.Unmarshal(raw, &e))
|
||||
back := discoveredVisionOf(e.Architecture, e.Info)
|
||||
require.NotNil(t, back, "a downstream gateway reads back what this one emits")
|
||||
assert.Equal(t, *tt.vision, *back)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleModels_EmitsVision(t *testing.T) {
|
||||
t.Parallel()
|
||||
cfg := CreateConfig()
|
||||
cfg.Providers = map[string]*ProviderConfig{
|
||||
"uni": {Type: "openai", APIKey: "sk-test", Models: []string{"ds", "plain"}},
|
||||
}
|
||||
cfg.ModelMeta = map[string]*ModelMetaConfig{"ds": {Vision: boolPtr(true)}}
|
||||
cfg.ModelAliases = map[string]string{"model-fast": "uni/ds"}
|
||||
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 []modelMetadataEntry `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))
|
||||
got := map[string]*bool{}
|
||||
for _, e := range body.Data {
|
||||
got[e.ID] = discoveredVisionOf(e.Architecture, e.Info)
|
||||
}
|
||||
for _, id := range []string{"ds", "model-fast"} {
|
||||
require.NotNil(t, got[id], id)
|
||||
assert.True(t, *got[id], id)
|
||||
}
|
||||
assert.Nil(t, got["plain"])
|
||||
}
|
||||
|
||||
func TestVisionCapable(t *testing.T) {
|
||||
t.Parallel()
|
||||
assert.True(t, visionCapable(nil), "unknown keeps the candidate")
|
||||
assert.True(t, visionCapable(boolPtr(true)))
|
||||
assert.False(t, visionCapable(boolPtr(false)))
|
||||
}
|
||||
+9
-6
@@ -188,12 +188,11 @@ func lookupModelMetaConfig(provider, model string, cfg map[string]*ModelMetaConf
|
||||
return nil
|
||||
}
|
||||
|
||||
// modelVisionCapable reports whether (provider, model) accepts image input.
|
||||
// An unset Vision, or no modelMeta entry, counts as capable so existing
|
||||
// deployments keep today's behaviour. The exact "provider/model" key wins
|
||||
// over the bare key only when it sets Vision itself.
|
||||
func modelVisionCapable(provider, model string, cfg map[string]*ModelMetaConfig) bool {
|
||||
if v := configuredVision(provider, model, cfg); v != nil {
|
||||
// visionCapable reports whether a resolved vision flag admits image input.
|
||||
// An unknown flag counts as capable so existing deployments keep today's
|
||||
// behaviour.
|
||||
func visionCapable(v *bool) bool {
|
||||
if v != nil {
|
||||
return *v
|
||||
}
|
||||
return true
|
||||
@@ -230,6 +229,10 @@ func resolveAliasModelMeta(alias, targetProvider, targetModel string, cfg map[st
|
||||
if !ok || override == nil {
|
||||
return out
|
||||
}
|
||||
if override.Vision != nil {
|
||||
v := *override.Vision
|
||||
out.Vision = &v
|
||||
}
|
||||
if override.ContextTokens > 0 {
|
||||
out.ContextTokens, out.ContextKnown = override.ContextTokens, true
|
||||
}
|
||||
|
||||
+2
-2
@@ -479,8 +479,8 @@ func TestModelVisionCapable(t *testing.T) {
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
if got := modelVisionCapable("p", "m", tt.cfg); got != tt.want {
|
||||
t.Errorf("modelVisionCapable = %v, want %v", got, tt.want)
|
||||
if got := visionCapable(configuredVision("p", "m", tt.cfg)); got != tt.want {
|
||||
t.Errorf("visionCapable(configuredVision) = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+89
-14
@@ -41,7 +41,9 @@ type openaiAdapter struct {
|
||||
upstreamErrs []upstreamFailure
|
||||
// metaLast is the last good metadata per upstream base; metaErrs the metadata failures of the latest fetchModelMetadata. Guarded by upstreamMu.
|
||||
metaLast map[string]map[string]int
|
||||
metaErrs []upstreamFailure
|
||||
// visionLast is the last good per-model vision flag per upstream base. Guarded by upstreamMu.
|
||||
visionLast map[string]map[string]bool
|
||||
metaErrs []upstreamFailure
|
||||
// timeout is this adapter's resolved per-request timeout
|
||||
// (resolveProviderTimeout, timeout.go) — UNLIKE retry above, it is NOT
|
||||
// left at its zero value by a bare newOpenAIAdapter call: a
|
||||
@@ -728,12 +730,59 @@ func (a *openaiAdapter) listModelsFrom(ctx context.Context, base string) ([]stri
|
||||
// Distinct from modelsPayload above, which is the same /v1/models
|
||||
// endpoint decoded for ids alone.
|
||||
type modelMetadataPayload struct {
|
||||
Data []struct {
|
||||
ID string `json:"id"`
|
||||
MaxContextLength int `json:"max_context_length"`
|
||||
LoadedContextLength int `json:"loaded_context_length"`
|
||||
MaxModelLen int `json:"max_model_len"`
|
||||
} `json:"data"`
|
||||
Data []modelMetadataEntry `json:"data"`
|
||||
}
|
||||
|
||||
// modelMetadataEntry is one model in a metadata response. Architecture and
|
||||
// Info stay raw: their shape varies between engines, and a field this gateway
|
||||
// cannot read must not fail the whole payload.
|
||||
type modelMetadataEntry struct {
|
||||
ID string `json:"id"`
|
||||
Architecture json.RawMessage `json:"architecture"`
|
||||
Info json.RawMessage `json:"info"`
|
||||
MaxContextLength int `json:"max_context_length"`
|
||||
LoadedContextLength int `json:"loaded_context_length"`
|
||||
MaxModelLen int `json:"max_model_len"`
|
||||
}
|
||||
|
||||
// imageModality names image input in architecture.input_modalities
|
||||
// (OpenRouter and llama.cpp).
|
||||
const imageModality = "image"
|
||||
|
||||
// discoveredVisionOf reads a model's vision flag from the two dialects an
|
||||
// upstream can send: Open WebUI's info.meta.capabilities.vision, which wins,
|
||||
// then architecture.input_modalities. It returns nil when neither says.
|
||||
func discoveredVisionOf(architecture, info json.RawMessage) *bool {
|
||||
if len(info) > 0 {
|
||||
var i struct {
|
||||
Meta struct {
|
||||
Capabilities struct {
|
||||
Vision *bool `json:"vision"`
|
||||
} `json:"capabilities"`
|
||||
} `json:"meta"`
|
||||
}
|
||||
if json.Unmarshal(info, &i) == nil && i.Meta.Capabilities.Vision != nil {
|
||||
v := *i.Meta.Capabilities.Vision
|
||||
return &v
|
||||
}
|
||||
}
|
||||
if len(architecture) == 0 {
|
||||
return nil
|
||||
}
|
||||
var a struct {
|
||||
InputModalities []string `json:"input_modalities"`
|
||||
}
|
||||
if json.Unmarshal(architecture, &a) != nil || len(a.InputModalities) == 0 {
|
||||
return nil
|
||||
}
|
||||
v := false
|
||||
for _, m := range a.InputModalities {
|
||||
if m == imageModality {
|
||||
v = true
|
||||
break
|
||||
}
|
||||
}
|
||||
return &v
|
||||
}
|
||||
|
||||
// fetchModelMetadata implements modelMetadataFetcher (feature v0.23,
|
||||
@@ -758,9 +807,10 @@ func (a *openaiAdapter) fetchModelMetadata(ctx context.Context) (map[string]int,
|
||||
|
||||
bases := a.upstreamBases()
|
||||
got := make([]map[string]int, len(bases))
|
||||
vis := make([]map[string]bool, len(bases))
|
||||
errs := a.queryUpstreams(ctx, bases, func(uctx context.Context, i int) error {
|
||||
var err error
|
||||
got[i], err = a.fetchModelMetadataFrom(uctx, bases[i])
|
||||
got[i], vis[i], err = a.fetchModelMetadataFrom(uctx, bases[i])
|
||||
return err
|
||||
})
|
||||
out := make(map[string]int)
|
||||
@@ -771,6 +821,9 @@ func (a *openaiAdapter) fetchModelMetadata(ctx context.Context) (map[string]int,
|
||||
if a.metaLast == nil {
|
||||
a.metaLast = make(map[string]map[string]int)
|
||||
}
|
||||
if a.visionLast == nil {
|
||||
a.visionLast = make(map[string]map[string]bool)
|
||||
}
|
||||
for i, base := range bases {
|
||||
src := got[i]
|
||||
if errs[i] != nil {
|
||||
@@ -782,6 +835,7 @@ func (a *openaiAdapter) fetchModelMetadata(ctx context.Context) (map[string]int,
|
||||
} else {
|
||||
ok = true
|
||||
a.metaLast[base] = got[i]
|
||||
a.visionLast[base] = vis[i]
|
||||
}
|
||||
for id, n := range src {
|
||||
if a.baseForModel(id) == base {
|
||||
@@ -799,29 +853,50 @@ func (a *openaiAdapter) fetchModelMetadata(ctx context.Context) (map[string]int,
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (a *openaiAdapter) fetchModelMetadataFrom(ctx context.Context, base string) (map[string]int, error) {
|
||||
// discoveredVision returns each model's vision flag from the latest good
|
||||
// metadata of the upstream that serves it. Models whose upstream said
|
||||
// nothing are absent.
|
||||
func (a *openaiAdapter) discoveredVision() map[string]bool {
|
||||
a.upstreamMu.Lock()
|
||||
defer a.upstreamMu.Unlock()
|
||||
out := make(map[string]bool)
|
||||
for base, m := range a.visionLast {
|
||||
for id, v := range m {
|
||||
if a.baseForModel(id) == base {
|
||||
out[id] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (a *openaiAdapter) fetchModelMetadataFrom(ctx context.Context, base string) (map[string]int, map[string]bool, 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
|
||||
return nil, nil, err
|
||||
}
|
||||
defer resp.Body.Close() //nolint:errcheck
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, newProviderHTTPError(resp)
|
||||
return nil, nil, newProviderHTTPError(resp)
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: read metadata response body: %w", errUpstream, err)
|
||||
return nil, nil, fmt.Errorf("%w: read metadata response body: %w", errUpstream, err)
|
||||
}
|
||||
|
||||
var payload modelMetadataPayload
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return nil, fmt.Errorf("%w: decode metadata response: %w", errUpstream, err)
|
||||
return nil, nil, fmt.Errorf("%w: decode metadata response: %w", errUpstream, err)
|
||||
}
|
||||
|
||||
out := make(map[string]int, len(payload.Data))
|
||||
vision := make(map[string]bool)
|
||||
for _, d := range payload.Data {
|
||||
if v := discoveredVisionOf(d.Architecture, d.Info); v != nil {
|
||||
vision[d.ID] = *v
|
||||
}
|
||||
// Widest declared window first, by dialect: LM Studio's
|
||||
// max_context_length, else vLLM's max_model_len. An upstream
|
||||
// reports one or the other, never both.
|
||||
@@ -839,5 +914,5 @@ func (a *openaiAdapter) fetchModelMetadataFrom(ctx context.Context, base string)
|
||||
out[d.ID] = ctxLen
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
return out, vision, nil
|
||||
}
|
||||
|
||||
+55
-4
@@ -187,6 +187,9 @@ type providerState struct {
|
||||
// failed capture leaves the previous map in place rather than
|
||||
// clearing it (captureModelMetadata, below).
|
||||
discoveredContext map[string]int
|
||||
// discoveredVision holds discovery-captured vision flags, keyed by
|
||||
// upstream model id; same stale-while-error rule as discoveredContext.
|
||||
discoveredVision map[string]bool
|
||||
// lastErr is the most recent finishRefresh call's error message, or
|
||||
// "" when that call succeeded (or discovery is disabled and
|
||||
// finishRefresh was never called at all). Read by snapshot for the
|
||||
@@ -273,6 +276,24 @@ func (st *providerState) contextFor(id string) (int, bool) {
|
||||
return n, ok
|
||||
}
|
||||
|
||||
// visionFor returns id's discovery-captured vision flag, or nil when the
|
||||
// upstream did not report one.
|
||||
func (st *providerState) visionFor(id string) *bool {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
v, ok := st.discoveredVision[id]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return &v
|
||||
}
|
||||
|
||||
func (st *providerState) setDiscoveredVision(m map[string]bool) {
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
st.discoveredVision = m
|
||||
}
|
||||
|
||||
// setDiscoveredContext replaces st's discoveredContext wholesale on a
|
||||
// successful metadata capture (feature v0.23, captureModelMetadata below)
|
||||
// — the same replace-on-success, stale-while-error shape finishRefresh
|
||||
@@ -1326,6 +1347,12 @@ type modelMetadataFetcher interface {
|
||||
fetchModelMetadata(ctx context.Context) (map[string]int, error)
|
||||
}
|
||||
|
||||
// modelVisionReporter is an optional capability of a modelMetadataFetcher:
|
||||
// the vision flags its latest fetchModelMetadata call captured.
|
||||
type modelVisionReporter interface {
|
||||
discoveredVision() map[string]bool
|
||||
}
|
||||
|
||||
// captureModelMetadata is warmFill/refreshProvider's shared, best-effort
|
||||
// discovery-metadata step (feature v0.23): when adapter also implements
|
||||
// modelMetadataFetcher (see that interface's own doc comment for why
|
||||
@@ -1372,6 +1399,9 @@ func (m *modelRegistry) captureModelMetadata(ctx context.Context, name string, a
|
||||
return
|
||||
}
|
||||
st.setDiscoveredContext(meta)
|
||||
if vr, ok := adapter.(modelVisionReporter); ok {
|
||||
st.setDiscoveredVision(vr.discoveredVision())
|
||||
}
|
||||
}
|
||||
|
||||
// infof writes msg through the info field, falling back to log when no
|
||||
@@ -2405,6 +2435,17 @@ func modelObject(id, ownedBy string, meta resolvedModelMeta) map[string]any {
|
||||
"output_per_mtok_usd": microUSDPerMTokToUSD(meta.OutputCostPerMTokMicroUSD),
|
||||
}
|
||||
}
|
||||
if meta.Vision != nil {
|
||||
// Two dialects: architecture for OpenRouter-style clients and a
|
||||
// downstream gateway, info for Open WebUI, which spreads the entry
|
||||
// into its own model record.
|
||||
modalities := []string{"text"}
|
||||
if *meta.Vision {
|
||||
modalities = append(modalities, imageModality)
|
||||
}
|
||||
obj["architecture"] = map[string]any{"input_modalities": modalities}
|
||||
obj["info"] = map[string]any{"meta": map[string]any{"capabilities": map[string]any{"vision": *meta.Vision}}}
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
@@ -2414,10 +2455,15 @@ func modelObject(id, ownedBy string, meta resolvedModelMeta) map[string]any {
|
||||
func (m *modelRegistry) resolveMetaFor(provider, bareModel string) resolvedModelMeta {
|
||||
var ctxVal int
|
||||
var ctxKnown bool
|
||||
if st, ok := m.states[provider]; ok {
|
||||
st, ok := m.states[provider]
|
||||
if ok {
|
||||
ctxVal, ctxKnown = st.contextFor(bareModel)
|
||||
}
|
||||
return resolveModelMeta(provider, bareModel, m.modelMeta, ctxVal, ctxKnown)
|
||||
out := resolveModelMeta(provider, bareModel, m.modelMeta, ctxVal, ctxKnown)
|
||||
if out.Vision == nil && ok {
|
||||
out.Vision = st.visionFor(bareModel)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// resolveMetaForAliasName resolves alias's metadata for the admin
|
||||
@@ -2449,10 +2495,15 @@ func (m *modelRegistry) resolveMetaForAliasName(alias string) resolvedModelMeta
|
||||
func (m *modelRegistry) resolveMetaForAlias(alias, targetProvider, targetModel string) resolvedModelMeta {
|
||||
var ctxVal int
|
||||
var ctxKnown bool
|
||||
if st, ok := m.states[targetProvider]; ok {
|
||||
st, ok := m.states[targetProvider]
|
||||
if ok {
|
||||
ctxVal, ctxKnown = st.contextFor(targetModel)
|
||||
}
|
||||
return resolveAliasModelMeta(alias, targetProvider, targetModel, m.modelMeta, ctxVal, ctxKnown)
|
||||
out := resolveAliasModelMeta(alias, targetProvider, targetModel, m.modelMeta, ctxVal, ctxKnown)
|
||||
if out.Vision == nil && ok {
|
||||
out.Vision = st.visionFor(targetModel)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// providerSnapshot is one provider's read-only view for the admin
|
||||
|
||||
@@ -337,7 +337,7 @@ func (g *Gateway) routerTargetCandidates(rt *smartRouter, tier, target string, f
|
||||
}
|
||||
|
||||
func (g *Gateway) routerCandidateSkipped(cand resolveCandidate, tier string, rt *smartRouter, facts routerRequestFacts, skips *routerSkips) bool {
|
||||
if facts.hasImage && !modelVisionCapable(cand.providerName, cand.upstreamModel, g.cfg.ModelMeta) {
|
||||
if facts.hasImage && !visionCapable(g.registry.resolveMetaFor(cand.providerName, cand.upstreamModel).Vision) {
|
||||
skips.vision++
|
||||
return true
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user