mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-11-26 10:06:31 +00:00
feat(provider): per-model and per-path upstreams (#8)
Add modelBaseUrls and pathBaseUrls to openai-type providers.
This commit is contained in:
@@ -420,6 +420,8 @@ 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). |
|
||||
| `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. |
|
||||
|
||||
@@ -1611,6 +1613,41 @@ only once it has something to authorize:
|
||||
will see every Gemini passthrough request denied. Route Gemini traffic
|
||||
for a model-restricted group through the unified `/v1/*` API instead.
|
||||
|
||||
### Several upstreams per provider
|
||||
|
||||
One `openai`-type provider can front several servers. `baseUrl` stays the
|
||||
default upstream; `modelBaseUrls` and `pathBaseUrls` override it. Both are
|
||||
off when absent, and then every request goes to `baseUrl` as before.
|
||||
|
||||
```yaml
|
||||
providers:
|
||||
gx10:
|
||||
type: openai
|
||||
baseUrl: http://llm-api.llm.svc.cluster.local:8000
|
||||
discovery: true
|
||||
models: ["current"]
|
||||
modelBaseUrls:
|
||||
Qwen3.8-27B: http://qwen27.llm.svc.cluster.local:8000
|
||||
text-embedding-multilingual-e5-base: http://embed-e5.llm.svc.cluster.local:8000
|
||||
text-embedding-bge-reranker-v2: http://rerank-bge-v2.llm.svc.cluster.local:8000
|
||||
pathBaseUrls:
|
||||
/v1/decide: http://thx02.llm.svc.cluster.local:8200
|
||||
```
|
||||
|
||||
- **Unified routes** (chat, embeddings, images, audio): a request for
|
||||
`gx10/Qwen3.8-27B` goes to the `modelBaseUrls` entry for the bare id
|
||||
`Qwen3.8-27B`. A model without an entry goes to `baseUrl`.
|
||||
- **Native passthrough** (`/gx10/v1/rerank`, `/gx10/v1/decide`): the gateway
|
||||
reads the body's top-level `model` (bare or `gx10/`-prefixed, within the
|
||||
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.
|
||||
- **Auth** reuses the provider's `apiKey` for every upstream.
|
||||
- **Failover health** is tracked per provider, not per upstream. One failing
|
||||
upstream marks the whole provider unhealthy, so with failover enabled its
|
||||
other models can be tried after another provider for the breaker window.
|
||||
|
||||
## Anthropic Messages API (`/v1/messages`)
|
||||
|
||||
`POST /v1/messages` serves Anthropic SDK clients — including Claude
|
||||
|
||||
@@ -12,8 +12,8 @@ var nonSecretConfigKeys = map[string]bool{
|
||||
"agents": true, "allowedCIDRs": true, "backoff": true, "cacheTTL": true,
|
||||
"card": true, "discoveryInterval": true, "file": true, "group": true,
|
||||
"groups": true, "maxOpenDuration": true, "mcpServers": true,
|
||||
"metadataPath": true, "modelAliases": true, "models": true, "name": true,
|
||||
"openDuration": true, "passthroughPaths": true, "path": true,
|
||||
"metadataPath": true, "modelAliases": true, "modelBaseUrls": true, "models": true, "name": true,
|
||||
"openDuration": true, "passthroughPaths": true, "path": true, "pathBaseUrls": true,
|
||||
"probeInterval": true, "providers": true, "requestTimeout": true,
|
||||
"ttl": true, "type": true,
|
||||
}
|
||||
|
||||
@@ -148,6 +148,7 @@ func setConcurrencyHeader(h http.Header, n int) {
|
||||
// learning and the RateLimit-Policy header on w. The returned func must run
|
||||
// when the upstream exchange ends.
|
||||
func (g *Gateway) trackUpstream(ctx context.Context, w http.ResponseWriter, provider, model string) (context.Context, func()) {
|
||||
ctx = withUpstreamModel(ctx, model)
|
||||
c := g.concurrency
|
||||
if c == nil {
|
||||
return withAttemptRecorder(ctx, func(resp *http.Response, attemptErr error) {
|
||||
|
||||
@@ -230,6 +230,16 @@ type ProviderConfig struct {
|
||||
// also unset); a non-empty value that fails to parse, or parses to a
|
||||
// duration <= 0, is a construction error naming this provider.
|
||||
RequestTimeout string `json:"requestTimeout,omitempty"`
|
||||
// ModelBaseURLs maps a bare model id (the id sent upstream) to the base
|
||||
// URL that serves it, overriding BaseURL for that model. Its keys are
|
||||
// declared models of the provider, like Models. Static: never polled by
|
||||
// discovery. openai-type providers only. Empty keeps single-upstream
|
||||
// behavior.
|
||||
ModelBaseURLs map[string]string `json:"modelBaseUrls,omitempty"`
|
||||
// PathBaseURLs maps a native passthrough path prefix (e.g. "/v1/decide")
|
||||
// to a base URL for requests that name no model in ModelBaseURLs. Longest
|
||||
// prefix wins; no match uses BaseURL. openai-type providers only.
|
||||
PathBaseURLs map[string]string `json:"pathBaseUrls,omitempty"`
|
||||
// MetadataPath is an optional second discovery endpoint (feature
|
||||
// v0.23), fetched alongside the provider's normal listModels call
|
||||
// when set: a path such as "/api/v0/models" (LM Studio's own,
|
||||
|
||||
+11
-6
@@ -14,7 +14,12 @@ import (
|
||||
// itself, and any OpenAI-compatible upstream (the operator's own gateway
|
||||
// included — a real deployment target for this adapter is keyless).
|
||||
type openaiAdapter struct {
|
||||
client *http.Client
|
||||
// modelBases and pathBases are ProviderConfig.ModelBaseURLs and
|
||||
// PathBaseURLs, validated and slash-trimmed by buildAdapters. Both nil
|
||||
// (the default) means every request uses baseURL.
|
||||
modelBases map[string]string
|
||||
pathBases map[string]string
|
||||
client *http.Client
|
||||
// retry is nil for every adapter built by a bare newOpenAIAdapter call
|
||||
// (every v0.1 test, and any caller that never wires one) — nil-safe,
|
||||
// per retryPolicy.do's own contract, so leaving it unset is exactly
|
||||
@@ -161,7 +166,7 @@ func (a *openaiAdapter) chatCompletion(ctx context.Context, w http.ResponseWrite
|
||||
hdr.Set("Accept", "text/event-stream")
|
||||
}
|
||||
|
||||
resp, err := upstreamJSON(ctx, a.client, http.MethodPost, a.baseURL+"/v1/chat/completions", hdr, req, a.retry, a.timeout, a.adapterName)
|
||||
resp, err := upstreamJSON(ctx, a.client, http.MethodPost, a.baseForCtx(ctx)+"/v1/chat/completions", hdr, req, a.retry, a.timeout, a.adapterName)
|
||||
if err != nil {
|
||||
return usage{}, err
|
||||
}
|
||||
@@ -186,7 +191,7 @@ func (a *openaiAdapter) chatCompletion(ctx context.Context, w http.ResponseWrite
|
||||
// non-streaming path.
|
||||
func (a *openaiAdapter) embeddings(ctx context.Context, w http.ResponseWriter, req map[string]any) (usage, error) {
|
||||
delete(req, gatewayAliasKey) // see chatCompletion's identical delete for why
|
||||
resp, err := upstreamJSON(ctx, a.client, http.MethodPost, a.baseURL+"/v1/embeddings", a.requestHeaders(true), req, a.retry, a.timeout, a.adapterName)
|
||||
resp, err := upstreamJSON(ctx, a.client, http.MethodPost, a.baseForCtx(ctx)+"/v1/embeddings", a.requestHeaders(true), req, a.retry, a.timeout, a.adapterName)
|
||||
if err != nil {
|
||||
return usage{}, err
|
||||
}
|
||||
@@ -295,7 +300,7 @@ func (a *openaiAdapter) imagesGeneration(ctx context.Context, w http.ResponseWri
|
||||
// it — the same defensive posture chatCompletion/embeddings already
|
||||
// take.
|
||||
delete(req, gatewayAliasKey)
|
||||
resp, err := upstreamJSON(ctx, a.client, http.MethodPost, a.baseURL+"/v1/images/generations", a.requestHeaders(true), req, a.retry, a.timeout, a.adapterName)
|
||||
resp, err := upstreamJSON(ctx, a.client, http.MethodPost, a.baseForCtx(ctx)+"/v1/images/generations", a.requestHeaders(true), req, a.retry, a.timeout, a.adapterName)
|
||||
if err != nil {
|
||||
return usage{}, err
|
||||
}
|
||||
@@ -321,7 +326,7 @@ func (a *openaiAdapter) audioSpeech(ctx context.Context, w http.ResponseWriter,
|
||||
if contentType != "" {
|
||||
hdr.Set("Content-Type", contentType)
|
||||
}
|
||||
resp, err := upstreamRawBytes(ctx, a.client, http.MethodPost, a.baseURL+"/v1/audio/speech", hdr, body, a.retry, a.timeout, a.adapterName)
|
||||
resp, err := upstreamRawBytes(ctx, a.client, http.MethodPost, a.baseForCtx(ctx)+"/v1/audio/speech", hdr, body, a.retry, a.timeout, a.adapterName)
|
||||
if err != nil {
|
||||
return usage{}, err
|
||||
}
|
||||
@@ -358,7 +363,7 @@ func (a *openaiAdapter) audioTranscription(ctx context.Context, w http.ResponseW
|
||||
if contentType != "" {
|
||||
hdr.Set("Content-Type", contentType)
|
||||
}
|
||||
resp, err := upstreamRawBytes(ctx, a.client, http.MethodPost, a.baseURL+"/v1/audio/transcriptions", hdr, body, a.retry, a.timeout, a.adapterName)
|
||||
resp, err := upstreamRawBytes(ctx, a.client, http.MethodPost, a.baseForCtx(ctx)+"/v1/audio/transcriptions", hdr, body, a.retry, a.timeout, a.adapterName)
|
||||
if err != nil {
|
||||
return usage{}, err
|
||||
}
|
||||
|
||||
@@ -662,9 +662,23 @@ func buildAdapters(cfg *Config) (map[string]providerAdapter, error) {
|
||||
return nil, timeoutErr
|
||||
}
|
||||
|
||||
modelBases, baseErr := validateUpstreamBases(name, "modelBaseUrls", pc.ModelBaseURLs, false)
|
||||
if baseErr != nil {
|
||||
return nil, baseErr
|
||||
}
|
||||
pathBases, baseErr := validateUpstreamBases(name, "pathBaseUrls", pc.PathBaseURLs, true)
|
||||
if baseErr != nil {
|
||||
return nil, baseErr
|
||||
}
|
||||
if pc.Type != providerTypeOpenAI && (len(modelBases) > 0 || len(pathBases) > 0) {
|
||||
return nil, fmt.Errorf("llmgateway: provider %q: modelBaseUrls and pathBaseUrls are supported for type %q only", name, providerTypeOpenAI)
|
||||
}
|
||||
|
||||
switch pc.Type {
|
||||
case providerTypeOpenAI:
|
||||
a := newOpenAIAdapter(name, base, apiKey)
|
||||
a.modelBases = modelBases
|
||||
a.pathBases = pathBases
|
||||
a.retry = policy
|
||||
a.metadataPath = pc.MetadataPath
|
||||
// timeout/client are re-resolved here rather than left at the
|
||||
|
||||
@@ -877,6 +877,10 @@ func newModelRegistry(adapters map[string]providerAdapter, cfg *Config, log func
|
||||
explicit[id] = true
|
||||
explicitModels[id] = true
|
||||
}
|
||||
for id := range pc.ModelBaseURLs {
|
||||
explicit[id] = true
|
||||
explicitModels[id] = true
|
||||
}
|
||||
|
||||
m.states[name] = &providerState{
|
||||
explicit: explicit,
|
||||
|
||||
+16
-1
@@ -1291,7 +1291,22 @@ func (g *Gateway) handlePassthrough(w http.ResponseWriter, r *http.Request, u *u
|
||||
}
|
||||
}
|
||||
|
||||
upstreamURL := adapter.base() + "/" + rest
|
||||
upstreamBase := adapter.base()
|
||||
if oa, isOpenAI := adapter.(*openaiAdapter); isOpenAI && oa.hasUpstreamOverrides() {
|
||||
var model string
|
||||
if len(oa.modelBases) > 0 {
|
||||
m, hasModel, truncated, peekErr := peekPassthroughModel(r)
|
||||
if peekErr != nil {
|
||||
writeOAIError(w, http.StatusBadRequest, "invalid_request_error", "cannot read request body")
|
||||
return
|
||||
}
|
||||
if hasModel && !truncated {
|
||||
model = m
|
||||
}
|
||||
}
|
||||
upstreamBase = oa.passthroughBase(model, "/"+rest)
|
||||
}
|
||||
upstreamURL := upstreamBase + "/" + rest
|
||||
if r.URL.RawQuery != "" {
|
||||
upstreamURL += "?" + r.URL.RawQuery
|
||||
}
|
||||
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package traefikllmgateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Yaegi unifies context key types of identical shape (see
|
||||
// latencyRecorderCtxKey), so this one must differ in size from the others.
|
||||
type upstreamModelCtxKey struct{ _ [2]byte }
|
||||
|
||||
// withUpstreamModel carries the resolved bare upstream model id to the
|
||||
// adapter, so it can pick a per-model base URL. An empty model returns ctx
|
||||
// unchanged.
|
||||
func withUpstreamModel(ctx context.Context, model string) context.Context {
|
||||
if model == "" {
|
||||
return ctx
|
||||
}
|
||||
return context.WithValue(ctx, upstreamModelCtxKey{}, model)
|
||||
}
|
||||
|
||||
func upstreamModelFromContext(ctx context.Context) string {
|
||||
model, _ := ctx.Value(upstreamModelCtxKey{}).(string)
|
||||
return model
|
||||
}
|
||||
|
||||
// baseForCtx returns the base URL for the model ctx carries, else baseURL.
|
||||
func (a *openaiAdapter) baseForCtx(ctx context.Context) string {
|
||||
if len(a.modelBases) == 0 {
|
||||
return a.baseURL
|
||||
}
|
||||
return a.baseForModel(upstreamModelFromContext(ctx))
|
||||
}
|
||||
|
||||
func (a *openaiAdapter) baseForModel(model string) string {
|
||||
if b, ok := a.modelBases[model]; ok {
|
||||
return b
|
||||
}
|
||||
return a.baseURL
|
||||
}
|
||||
|
||||
// hasUpstreamOverrides reports whether any per-model or per-path upstream is set.
|
||||
func (a *openaiAdapter) hasUpstreamOverrides() bool {
|
||||
return len(a.modelBases) > 0 || len(a.pathBases) > 0
|
||||
}
|
||||
|
||||
// passthroughBase picks the base URL for a native passthrough request:
|
||||
// a model entry first, then the longest matching path prefix, else baseURL.
|
||||
// path starts with "/"; model may be empty or carry the "<provider>/" prefix.
|
||||
func (a *openaiAdapter) passthroughBase(model, path string) string {
|
||||
if model != "" {
|
||||
model = strings.TrimPrefix(model, a.adapterName+"/")
|
||||
if b, ok := a.modelBases[model]; ok {
|
||||
return b
|
||||
}
|
||||
}
|
||||
best := ""
|
||||
found := false
|
||||
for prefix := range a.pathBases {
|
||||
if !pathHasPrefix(path, prefix) {
|
||||
continue
|
||||
}
|
||||
if !found || len(prefix) > len(best) {
|
||||
best = prefix
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if found {
|
||||
return a.pathBases[best]
|
||||
}
|
||||
return a.baseURL
|
||||
}
|
||||
|
||||
// pathHasPrefix matches on whole path segments: "/v1/decide" covers
|
||||
// "/v1/decide" and "/v1/decide/batch" but not "/v1/decider".
|
||||
func pathHasPrefix(path, prefix string) bool {
|
||||
if path == prefix {
|
||||
return true
|
||||
}
|
||||
return strings.HasPrefix(path, strings.TrimSuffix(prefix, "/")+"/")
|
||||
}
|
||||
|
||||
// validateUpstreamBases checks and normalizes a ModelBaseURLs or PathBaseURLs
|
||||
// map. pathKeys requires each key to start with "/". Errors name the key
|
||||
// only, never the URL, which may be malformed in a credential-bearing way.
|
||||
func validateUpstreamBases(providerName, field string, in map[string]string, pathKeys bool) (map[string]string, error) {
|
||||
if len(in) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
out := make(map[string]string, len(in))
|
||||
for key, raw := range in {
|
||||
if key == "" {
|
||||
return nil, fmt.Errorf("llmgateway: provider %q: %s has an empty key", providerName, field)
|
||||
}
|
||||
if pathKeys && !strings.HasPrefix(key, "/") {
|
||||
return nil, fmt.Errorf("llmgateway: provider %q: %s key %q must start with \"/\"", providerName, field, key)
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
||||
return nil, fmt.Errorf("llmgateway: provider %q: %s[%q] must be an absolute http(s) URL", providerName, field, key)
|
||||
}
|
||||
if u.User != nil || u.RawQuery != "" || u.Fragment != "" {
|
||||
return nil, fmt.Errorf("llmgateway: provider %q: %s[%q] must not carry userinfo, query or fragment", providerName, field, key)
|
||||
}
|
||||
out[key] = strings.TrimSuffix(raw, "/")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
package traefikllmgateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPassthroughBase_Resolution(t *testing.T) {
|
||||
a := newOpenAIAdapter("gx10", "http://base", "")
|
||||
a.modelBases = map[string]string{"m1": "http://m1"}
|
||||
a.pathBases = map[string]string{
|
||||
"/v1/decide": "http://decide",
|
||||
"/v1/decide/batch": "http://batch",
|
||||
}
|
||||
tests := []struct {
|
||||
name, model, path, want string
|
||||
}{
|
||||
{"model hit bare", "m1", "/v1/rerank", "http://m1"},
|
||||
{"model hit prefixed", "gx10/m1", "/v1/rerank", "http://m1"},
|
||||
{"model beats path", "m1", "/v1/decide", "http://m1"},
|
||||
{"model miss falls to base", "other", "/v1/rerank", "http://base"},
|
||||
{"other provider prefix is not stripped", "x/m1", "/v1/rerank", "http://base"},
|
||||
{"path exact", "", "/v1/decide", "http://decide"},
|
||||
{"path longest prefix wins", "", "/v1/decide/batch", "http://batch"},
|
||||
{"path sub-segment uses shorter prefix", "", "/v1/decide/other", "http://decide"},
|
||||
{"path segment boundary respected", "", "/v1/decider", "http://base"},
|
||||
{"path miss", "", "/v1/chat/completions", "http://base"},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert.Equal(t, tc.want, a.passthroughBase(tc.model, tc.path))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseForCtx(t *testing.T) {
|
||||
a := newOpenAIAdapter("gx10", "http://base", "")
|
||||
assert.Equal(t, "http://base", a.baseForCtx(withUpstreamModel(context.Background(), "m1")))
|
||||
a.modelBases = map[string]string{"m1": "http://m1"}
|
||||
assert.Equal(t, "http://m1", a.baseForCtx(withUpstreamModel(context.Background(), "m1")))
|
||||
assert.Equal(t, "http://base", a.baseForCtx(withUpstreamModel(context.Background(), "m2")))
|
||||
assert.Equal(t, "http://base", a.baseForCtx(context.Background()))
|
||||
}
|
||||
|
||||
func TestBuildAdapters_UpstreamURLValidation(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
wantErr string
|
||||
pc ProviderConfig
|
||||
}{
|
||||
{"valid", "", ProviderConfig{Type: "openai", ModelBaseURLs: map[string]string{"m": "http://h:8000/"}, PathBaseURLs: map[string]string{"/v1/decide": "https://h"}}},
|
||||
{"malformed model url", "modelBaseUrls", ProviderConfig{Type: "openai", ModelBaseURLs: map[string]string{"m": "http://[::1"}}},
|
||||
{"no scheme", "absolute http(s) URL", ProviderConfig{Type: "openai", ModelBaseURLs: map[string]string{"m": "host:8000"}}},
|
||||
{"bad scheme", "absolute http(s) URL", ProviderConfig{Type: "openai", ModelBaseURLs: map[string]string{"m": "ftp://h"}}},
|
||||
{"userinfo", "userinfo", ProviderConfig{Type: "openai", ModelBaseURLs: map[string]string{"m": "http://u:p@h"}}}, //nolint:gosec // deliberately credential-bearing input
|
||||
{"query", "userinfo, query or fragment", ProviderConfig{Type: "openai", PathBaseURLs: map[string]string{"/p": "http://h?x=1"}}},
|
||||
{"empty model key", "empty key", ProviderConfig{Type: "openai", ModelBaseURLs: map[string]string{"": "http://h"}}},
|
||||
{"path key without slash", "must start with", ProviderConfig{Type: "openai", PathBaseURLs: map[string]string{"v1/decide": "http://h"}}},
|
||||
{"bad path url", "pathBaseUrls", ProviderConfig{Type: "openai", PathBaseURLs: map[string]string{"/p": "::"}}},
|
||||
{"non-openai type", "type \"openai\" only", ProviderConfig{Type: "anthropic", APIKey: "k", ModelBaseURLs: map[string]string{"m": "http://h"}}},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
pc := tc.pc
|
||||
adapters, err := buildAdapters(&Config{Providers: map[string]*ProviderConfig{"p": &pc}})
|
||||
if tc.wantErr == "" {
|
||||
require.NoError(t, err)
|
||||
oa, ok := adapters["p"].(*openaiAdapter)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "http://h:8000", oa.modelBases["m"])
|
||||
return
|
||||
}
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), tc.wantErr)
|
||||
assert.NotContains(t, err.Error(), "u:p@", "error must not echo the URL")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildAdapters_NoUpstreamFields_Unchanged(t *testing.T) {
|
||||
adapters, err := buildAdapters(&Config{Providers: map[string]*ProviderConfig{
|
||||
"p": {Type: "openai", BaseURL: "http://base/"},
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
oa, ok := adapters["p"].(*openaiAdapter)
|
||||
require.True(t, ok)
|
||||
assert.Nil(t, oa.modelBases)
|
||||
assert.Nil(t, oa.pathBases)
|
||||
assert.False(t, oa.hasUpstreamOverrides())
|
||||
assert.Equal(t, "http://base", oa.baseForCtx(withUpstreamModel(context.Background(), "any")))
|
||||
assert.Equal(t, "http://base", oa.passthroughBase("any", "/v1/decide"))
|
||||
}
|
||||
|
||||
type upstreamHit struct{ server, path, auth, model string }
|
||||
|
||||
type upstreamRecorder struct {
|
||||
hits []upstreamHit
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (u *upstreamRecorder) handler(server, respContentType, respBody string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
model := ""
|
||||
if i := strings.Index(string(b), `"model":"`); i >= 0 {
|
||||
rest := string(b)[i+len(`"model":"`):]
|
||||
model = rest[:strings.Index(rest, `"`)]
|
||||
}
|
||||
u.mu.Lock()
|
||||
u.hits = append(u.hits, upstreamHit{server, r.URL.Path, r.Header.Get("Authorization"), model})
|
||||
u.mu.Unlock()
|
||||
w.Header().Set("Content-Type", respContentType)
|
||||
_, _ = w.Write([]byte(respBody))
|
||||
}
|
||||
}
|
||||
|
||||
func (u *upstreamRecorder) snapshot() []upstreamHit {
|
||||
u.mu.Lock()
|
||||
defer u.mu.Unlock()
|
||||
return append([]upstreamHit(nil), u.hits...)
|
||||
}
|
||||
|
||||
func newUpstreamsGateway(t *testing.T, pc *ProviderConfig) http.Handler {
|
||||
t.Helper()
|
||||
cfg := CreateConfig()
|
||||
cfg.Providers = map[string]*ProviderConfig{"gx10": pc}
|
||||
cfg.Groups = map[string]*GroupConfig{"default": {}}
|
||||
cfg.Users = &UsersConfig{Inline: []*UserConfig{{Name: "alice", Group: "default", APIKey: "sk-alice", Limits: &LimitsConfig{}}}}
|
||||
h, err := New(context.Background(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), cfg, "llmgw")
|
||||
require.NoError(t, err)
|
||||
return h
|
||||
}
|
||||
|
||||
const upstreamsSSE = "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\ndata: {\"choices\":[],\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":1}}\n\ndata: [DONE]\n\n"
|
||||
|
||||
func TestUpstreams_StreamingChat_TwoModelsTwoServers(t *testing.T) {
|
||||
rec := &upstreamRecorder{}
|
||||
base := httptest.NewServer(rec.handler("base", "text/event-stream", upstreamsSSE))
|
||||
defer base.Close()
|
||||
qwen := httptest.NewServer(rec.handler("qwen", "text/event-stream", upstreamsSSE))
|
||||
defer qwen.Close()
|
||||
embed := httptest.NewServer(rec.handler("embed", "application/json", `{"data":[],"usage":{"prompt_tokens":1}}`))
|
||||
defer embed.Close()
|
||||
|
||||
h := newUpstreamsGateway(t, &ProviderConfig{
|
||||
Type: "openai", BaseURL: base.URL, APIKey: "sk-up", Models: []string{"current"},
|
||||
ModelBaseURLs: map[string]string{"Qwen3.8-27B": qwen.URL, "e5": embed.URL},
|
||||
})
|
||||
|
||||
chat := func(model string) string {
|
||||
req := newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice",
|
||||
map[string]any{"model": model, "stream": true, "messages": []any{map[string]any{"role": "user", "content": "hi"}}})
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
||||
return w.Body.String()
|
||||
}
|
||||
assert.Contains(t, chat("gx10/Qwen3.8-27B"), "[DONE]")
|
||||
assert.Contains(t, chat("gx10/current"), "[DONE]")
|
||||
|
||||
req := newUnifiedRequest(t, http.MethodPost, "/v1/embeddings", "sk-alice", map[string]any{"model": "gx10/e5", "input": "x"})
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
||||
|
||||
assert.Equal(t, []upstreamHit{
|
||||
{"qwen", "/v1/chat/completions", "Bearer sk-up", "Qwen3.8-27B"},
|
||||
{"base", "/v1/chat/completions", "Bearer sk-up", "current"},
|
||||
{"embed", "/v1/embeddings", "Bearer sk-up", "e5"},
|
||||
}, rec.snapshot())
|
||||
|
||||
// ModelBaseURLs ids are declared models: they appear in /v1/models.
|
||||
mreq := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
|
||||
mreq.Header.Set("Authorization", "Bearer sk-alice")
|
||||
mw := httptest.NewRecorder()
|
||||
h.ServeHTTP(mw, mreq)
|
||||
require.Equal(t, http.StatusOK, mw.Code)
|
||||
assert.Contains(t, mw.Body.String(), `"id":"Qwen3.8-27B"`)
|
||||
assert.Contains(t, mw.Body.String(), `"id":"e5"`)
|
||||
}
|
||||
|
||||
func TestUpstreams_Passthrough_ModelAndPath(t *testing.T) {
|
||||
rec := &upstreamRecorder{}
|
||||
base := httptest.NewServer(rec.handler("base", "application/json", `{}`))
|
||||
defer base.Close()
|
||||
rr := httptest.NewServer(rec.handler("rerank", "application/json", `{}`))
|
||||
defer rr.Close()
|
||||
thx := httptest.NewServer(rec.handler("thx", "application/json", `{}`))
|
||||
defer thx.Close()
|
||||
|
||||
h := newUpstreamsGateway(t, &ProviderConfig{
|
||||
Type: "openai", BaseURL: base.URL, Models: []string{"current"},
|
||||
ModelBaseURLs: map[string]string{"bge": rr.URL},
|
||||
PathBaseURLs: map[string]string{"/v1/decide": thx.URL},
|
||||
})
|
||||
post := func(path, body string) {
|
||||
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
|
||||
req.Header.Set("Authorization", "Bearer sk-alice")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
||||
}
|
||||
post("/gx10/v1/rerank", `{"model":"gx10/bge","query":"q"}`)
|
||||
post("/gx10/v1/rerank", `{"model":"bge","query":"q"}`)
|
||||
post("/gx10/v1/decide", `{"x":1}`)
|
||||
post("/gx10/v1/decide/batch", `{"x":1}`)
|
||||
post("/gx10/v1/other", `{"model":"current"}`)
|
||||
|
||||
var servers, paths []string
|
||||
for _, hit := range rec.snapshot() {
|
||||
servers = append(servers, hit.server)
|
||||
paths = append(paths, hit.path)
|
||||
}
|
||||
assert.Equal(t, []string{"rerank", "rerank", "thx", "thx", "base"}, servers)
|
||||
assert.Equal(t, []string{"/v1/rerank", "/v1/rerank", "/v1/decide", "/v1/decide/batch", "/v1/other"}, paths)
|
||||
}
|
||||
|
||||
func TestUpstreams_Passthrough_PathOnly(t *testing.T) {
|
||||
rec := &upstreamRecorder{}
|
||||
base := httptest.NewServer(rec.handler("base", "application/json", `{}`))
|
||||
defer base.Close()
|
||||
thx := httptest.NewServer(rec.handler("thx", "application/json", `{}`))
|
||||
defer thx.Close()
|
||||
|
||||
h := newUpstreamsGateway(t, &ProviderConfig{
|
||||
Type: "openai", BaseURL: base.URL, Models: []string{"current"},
|
||||
PathBaseURLs: map[string]string{"/v1/decide": thx.URL},
|
||||
})
|
||||
post := func(path, body string) {
|
||||
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
|
||||
req.Header.Set("Authorization", "Bearer sk-alice")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
||||
}
|
||||
post("/gx10/v1/decide", `{"model":"current"}`)
|
||||
post("/gx10/v1/other", `{"model":"current"}`)
|
||||
|
||||
var servers []string
|
||||
for _, hit := range rec.snapshot() {
|
||||
servers = append(servers, hit.server)
|
||||
}
|
||||
assert.Equal(t, []string{"thx", "base"}, servers)
|
||||
}
|
||||
|
||||
type failingBody struct{ read bool }
|
||||
|
||||
func (f *failingBody) Read(p []byte) (int, error) {
|
||||
if !f.read {
|
||||
f.read = true
|
||||
return copy(p, `{"mod`), nil
|
||||
}
|
||||
return 0, io.ErrClosedPipe
|
||||
}
|
||||
|
||||
func TestUpstreams_Passthrough_BodyReadError_400(t *testing.T) {
|
||||
rec := &upstreamRecorder{}
|
||||
base := httptest.NewServer(rec.handler("base", "application/json", `{}`))
|
||||
defer base.Close()
|
||||
h := newUpstreamsGateway(t, &ProviderConfig{
|
||||
Type: "openai", BaseURL: base.URL, Models: []string{"current"},
|
||||
ModelBaseURLs: map[string]string{"bge": base.URL},
|
||||
})
|
||||
req := httptest.NewRequest(http.MethodPost, "/gx10/v1/rerank", &failingBody{})
|
||||
req.Header.Set("Authorization", "Bearer sk-alice")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
assert.Equal(t, http.StatusBadRequest, w.Code, w.Body.String())
|
||||
assert.Empty(t, rec.snapshot())
|
||||
}
|
||||
|
||||
func TestUpstreams_NoNewFields_AllTrafficToBaseURL(t *testing.T) {
|
||||
rec := &upstreamRecorder{}
|
||||
base := httptest.NewServer(rec.handler("base", "application/json", `{"usage":{"prompt_tokens":1,"completion_tokens":1}}`))
|
||||
defer base.Close()
|
||||
h := newUpstreamsGateway(t, &ProviderConfig{Type: "openai", BaseURL: base.URL, Models: []string{"current"}})
|
||||
|
||||
req := newUnifiedRequest(t, http.MethodPost, "/v1/chat/completions", "sk-alice",
|
||||
map[string]any{"model": "gx10/current", "messages": []any{map[string]any{"role": "user", "content": "hi"}}})
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
|
||||
|
||||
preq := httptest.NewRequest(http.MethodPost, "/gx10/v1/decide", strings.NewReader(`{"model":"current"}`))
|
||||
preq.Header.Set("Authorization", "Bearer sk-alice")
|
||||
preq.Header.Set("Content-Type", "application/json")
|
||||
pw := httptest.NewRecorder()
|
||||
h.ServeHTTP(pw, preq)
|
||||
require.Equal(t, http.StatusOK, pw.Code)
|
||||
|
||||
hits := rec.snapshot()
|
||||
require.Len(t, hits, 2)
|
||||
assert.Equal(t, "base", hits[0].server)
|
||||
assert.Equal(t, "base", hits[1].server)
|
||||
assert.Equal(t, "/v1/decide", hits[1].path)
|
||||
}
|
||||
Reference in New Issue
Block a user