diff --git a/AGENTS.md b/AGENTS.md index 0af26345..240fd4ff 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,6 +56,14 @@ `model_info.base_model` or public-route prefix still withholds identity, bar the `accounts` model-path segment; never reinterpret those as a namespace. Reduce every deployment before choosing transport, capabilities, limits, prices, or catalog authority; never shallow-merge duplicate route rows. +- `model_info.pricing_provider` (LiteLLM v1.109.0+) is the operator naming the catalog whose rows price a deployment, + so `resolveCatalogProvider` returns it ahead of every inference, including the conflicts that otherwise withhold an + identity (a deployment id equal to another provider's catalog key, such as `baseten/zai-org/GLM-5.2` routed through + `custom_llm_provider: openai`). A conflict withholds the identity in `resolveBackendIdentity` before that helper is + reached, so `resolveModelInfoCatalog` re-reads the row without its `custom_llm_provider` to get the bare model id the + declared catalog is keyed by; without that the declared provider never prices the rows it exists for. It settles the + catalog only, so the identity stays withheld for family and routing, and `routesOnlyThrough` must keep ignoring it. + LiteLLM itself falls back to `custom_llm_provider` when it is unset. The Go port mirrors it. - Keep catalog lookup provider-aware. Unqualified or conflicting identities must not scan every Pi provider catalog. - `supported_endpoints` pins transport except for `azure_ai` deployments on a proxy older than LiteLLM v1.103.0 or of unknown version. Those releases bridge them to Chat Completions regardless of that cost-map list, so they take @@ -65,15 +73,15 @@ for a deployment LiteLLM reports as `anthropic` through `base_model`) takes native Messages only when `litellm_params.model` contains `claude` (LiteLLM picks its native config by that name alone) and the proxy reports v1.80.12 or later (`AZURE_AI_MESSAGES_FLOOR`; v1.80.10 and v1.80.11 send `api-key` where Azure wants `x-api-key`, - earlier releases bridge to Chat). `publishesVersionGatedTransport` probes for it only when the group would be + earlier releases bridge to Chat). `publishesVersionGatedBehavior` probes for it only when the group would be published on Messages at that floor. -- When the version was asked for and could not be read, `reportUnreadProxyVersion` names the routes that stay on Chat - Completions, once per route and process like the other route diagnostics. A readable version below a floor is not - reported. Collect the routes where the probe is decided, so the warning and the probe cannot disagree. +- When the version was asked for and could not be read, `reportUnreadProxyVersion` names the routes that keep the + conservative fallback, once per route and process like the other route diagnostics. A readable version below a floor + is not reported. Collect the routes where the probe is decided, so the warning and the probe cannot disagree. - `toLiteLLMApi` (`protocols.ProxyAPI` in Go) maps a model's API to the protocol the proxy serves: the three LiteLLM APIs, plus Pi's `azure-openai-responses` as `openai-responses`. The stored-model restore, `filterModels` and the stream guard all go through it, so an Azure catalog API never selects Azure URLs or auth against the proxy; any other API stays rejected. The startup seed reader (`src/models-store.ts`, `models_store.go`) stays strict: a store holding such an entry is discovered again instead of seeded. - Version-gated workarounds read the proxy version through `src/proxy-version.ts`. An unknown version satisfies no floor, so every gate fails toward the workaround, and a pre-release orders before the release it names. Probe only - when a published deployment's outcome depends on the version (`publishesVersionGatedTransport`), at most once per + when a published deployment's outcome depends on the version (`publishesVersionGatedBehavior`), at most once per discovery: the probe draws an error reply, so an unconditional one would add a failed request to every operator's logs. A listed deployment is not yet a published one: a withheld group publishes nothing, and a wildcard route publishes nothing until `/v1/models` expands it, so its probe waits for the expansion. `scripts/probe-proxy.ts` @@ -199,6 +207,16 @@ - A declared `reasoning_effort_levels` list answers every level for its deployment, ahead of the per-level flags. - Catalog level maps are tristate, not complete lists: an omitted standard level keeps Pi's default. - Null/absent flags have no opinion; explicit denials win and extended effort levels need explicit support. A router flag is the more specific evidence, so an explicit `true` grants a level over a catalog map that denies it. +- `thinking_always_on` denies Pi's `off` level outright, and `thinking_on_by_default` denies it below LiteLLM v1.110.0 + (`THINKING_DISABLE_FLOOR`), which is the release that turns `reasoning_effort: "none"` into + `thinking: {"type": "disabled"}`; earlier releases sent nothing, so the backend kept thinking and billing it. Both + are read in `reportedLevel` ahead of the declared `reasoning_effort_levels` list, because an accepted `none` still + does not stop the thinking, so they reach the Chat, Responses and native Messages level maps alike. Pi's Anthropic + catalog already denies `off` for always-on Claude, but its Bedrock and other hosted catalogs do not, which is where + this evidence lands. A think-by-default route makes `publishesVersionGatedBehavior` probe on its own, with no + transport gate, but only where the published `off` level actually differs across the floor: a sibling that always + thinks denies it at every version, and probing for that would add a failed request and a warning explaining nothing. + The Go port mirrors both. - Close thinking levels against the protocol and accepted carrier actually used after wildcard expansion. Responses compatibility contains only Responses fields. - GPT-5.5 and later reject `reasoning_effort` with function tools on Chat Completions. Discovery sets `litellmPolicy.dropToolReasoning` for Chat routes when any deployment's backend id (never the route name) is GPT-5.5+, and wildcard combinators take any parent's flag: dropping reasoning only degrades a request, keeping it fails one. The request hook uses the route name only for a model without `litellmBackendFamily` evidence. It sends the model's declared `thinkingLevelMap.off` effort, and without one omits the field, except under `explicitToolReasoningOff` (GPT-6+ backend evidence, or the route name without evidence), which sends `none` because GPT-6 falls back to its default effort when the field is omitted. `off: null` from `NO_TRANSMISSIBLE_LEVELS` means no carrier evidence, not a model that cannot turn reasoning off. @@ -206,9 +224,12 @@ - Provider-specific request compatibility belongs in discovered model `compat` metadata, not broad runtime mutation. - `promptCache: { short: 300, long: 3600 }` (Pi's built-in Anthropic values) needs unanimous Claude backend evidence plus Messages, or Chat with `cacheControlFormat: "anthropic"`. Never Responses, route text, or the `/v1/models` fallback; wildcard children inherit it; the Go port mirrors it. +- Any deployment whose `supports_prompt_caching` is explicitly `false` withholds every `promptCache` block + (`deniesPromptCache`), whatever its family documents: a relay can host a Claude or GPT generation that bills no + cache (`kyma/claude-fable-5`). An absent flag is not a denial. The Go port mirrors it. - `promptCache: { short: 1800 }` (OpenAI's and Azure's documented 30-minute default minimum for GPT-5.6 and later) needs every deployment's backend id, never the route name, to be OpenAI-family GPT-5.6+, routed (`routesOnlyThrough`) only through `openai`, `azure` or `azure_ai`, on Responses only. Relays such as OpenRouter or Copilot document no lifetime of their own. No `long`: the 12-hour lifetime needs `prompt_cache_options.ttl`, which Pi's long retention does not send. Same inheritance and Go mirror as the Claude rule. - Native Messages requires unanimous compatible Claude deployment evidence; evidence-free fallback and health discovery never select it. Keep Messages compatibility separate from Chat and Responses fields. -- Native Messages routes declare `supportsMidConvoEffort: false` unless every deployment routes only through Anthropic (`routesOnlyThrough`, as for strict tools): managed effort sends `thinking.block_binding` with its betas, and hosted Claude endpoints (Azure among them) reject it. `closeSerializerPolicy` keeps that field so the offline cache does not drop the denial; the Go port mirrors both. +- Native Messages routes declare `supportsMidConvoEffort: false` unless every deployment routes only through Anthropic (`routesOnlyThrough`, as for strict tools), or only through `azure_ai` on a proxy reporting LiteLLM v1.109.0 or later (`AZURE_AI_THINKING_BINDING_FLOOR`), the release that stopped dropping the `thinking-binding-controls-2026-08-01` beta header on the way to Foundry: managed effort sends `thinking.block_binding` with its betas, and a hosted Claude endpoint rejects it without that header. Read the azure_ai grant from declared routing, never `routesThroughAzureAi`, whose `model_info.litellm_provider` arm is a cost-map lookup: a Bedrock-routed deployment priced through an Azure row reaches Bedrock, where the beta means nothing. Those groups already probe for the Messages floor, so the gate adds no request. No release is evidence for Bedrock or Vertex, which stay denied. `closeSerializerPolicy` keeps that field so the offline cache does not drop the denial; the Go port mirrors both. - Strict tools require every deployment's declared routing (`custom_llm_provider` and the `litellm_params.model` prefix) to name Anthropic. `model_info.litellm_provider` is a cost-map lookup of `base_model`, not routing, and `supports_response_schema` / `supports_native_structured_output` describe JSON output, not tool definitions; neither is strict-tool evidence. - Chat Completions `strict` tool schemas: since Pi 0.87 the `openai-completions` default for unknown endpoints is `supportsStrictMode: false`, so LiteLLM Chat routes send no `strict` field. Pi only ever sent `strict: true` for tools diff --git a/pig/PORTING.md b/pig/PORTING.md index 62647315..aff501b2 100644 --- a/pig/PORTING.md +++ b/pig/PORTING.md @@ -68,7 +68,7 @@ aliases come from settings and from the multi-provider environment variables, as - **Claude on Azure AI Foundry.** `azure_ai` is in `claudeCapableAdapters` like the TypeScript `CLAUDE_CAPABLE_ADAPTERS`, under the same two conditions: the configured model contains `claude` (`isAzureAIClaudeDeployment`, LiteLLM's own test for its native config) and the proxy reports v1.80.12 or later - (`azureAIMessagesFloor`). `publishesVersionGatedTransport` asks for the version only when the group would be + (`azureAIMessagesFloor`). `publishesVersionGatedBehavior` asks for the version only when the group would be published on Messages at that floor, and never for `/health` groups, which never select Messages. The same rule binds a hosted deployment reported as `anthropic` through `base_model` (`routesThroughAzureAI`), and `reportUnreadProxyVersion` prints the TypeScript warning when the version was asked for and could not be read. diff --git a/pig/extensions/litellm/internal/backend/backend.go b/pig/extensions/litellm/internal/backend/backend.go index a6c618be..c9af21c4 100644 --- a/pig/extensions/litellm/internal/backend/backend.go +++ b/pig/extensions/litellm/internal/backend/backend.go @@ -183,6 +183,14 @@ func ResolveIdentity(entry types.ModelInfoEntry) *Identity { // ResolveCatalogProvider is resolveCatalogProvider; "" means undefined. func ResolveCatalogProvider(entry types.ModelInfoEntry) string { + // model_info.pricing_provider (LiteLLM 1.109.0+) is the operator naming the catalog that prices + // this deployment. It outranks every inference, and it is a pricing statement, not routing + // evidence, so RoutesOnlyThrough keeps ignoring it. + if entry.ModelInfo != nil { + if priced := strings.ToLower(strings.TrimSpace(entry.ModelInfo.PricingProvider)); priced != "" { + return priced + } + } row := fieldsOf(entry) identity := ResolveIdentity(entry) if identity != nil && identity.Provider != "" && !genericCatalogProviders[identity.Provider] { diff --git a/pig/extensions/litellm/internal/backend/backend_test.go b/pig/extensions/litellm/internal/backend/backend_test.go index 3656e15e..d785f58f 100644 --- a/pig/extensions/litellm/internal/backend/backend_test.go +++ b/pig/extensions/litellm/internal/backend/backend_test.go @@ -257,7 +257,7 @@ func TestResolveBackendIdentity(t *testing.T) { t.Errorf("%s should not be OpenAI", id) } } - if DiscoveryVersion != 16 { + if DiscoveryVersion != 17 { t.Errorf("DiscoveryVersion = %d", DiscoveryVersion) } }) @@ -340,6 +340,40 @@ func TestResolveCatalogProvider(t *testing.T) { }) } +func TestResolveCatalogProviderPricingProvider(t *testing.T) { + t.Run("takes a declared pricing_provider over every inference, including a conflicting one", func(t *testing.T) { + // LiteLLM 1.109.0+: the operator names the catalog that prices the deployment. + got := ResolveCatalogProvider(types.ModelInfoEntry{ + ModelInfo: &types.ModelInfoDetails{BaseModel: "zai-org/GLM-5.2", LiteLLMProvider: "openai", PricingProvider: "baseten"}, + LiteLLMParams: &types.ModelInfoParams{Model: "openai/zai-org/GLM-5.2", CustomLLMProvider: "openai"}, + }) + if got != "baseten" { + t.Errorf("got %q", got) + } + // Trimmed and lowercased like the other wire providers, and a blank one changes nothing. + got = ResolveCatalogProvider(types.ModelInfoEntry{ModelInfo: &types.ModelInfoDetails{BaseModel: "gpt-5.2", PricingProvider: " BaseTen "}}) + if got != "baseten" { + t.Errorf("got %q", got) + } + got = ResolveCatalogProvider(types.ModelInfoEntry{ModelInfo: &types.ModelInfoDetails{BaseModel: "anthropic/claude-sonnet-5-5", PricingProvider: " "}}) + if got != "anthropic" { + t.Errorf("got %q", got) + } + }) + t.Run("keeps pricing_provider out of routing evidence", func(t *testing.T) { + row := types.ModelInfoEntry{ + ModelInfo: &types.ModelInfoDetails{BaseModel: "claude-sonnet-5-5", PricingProvider: "anthropic"}, + LiteLLMParams: &types.ModelInfoParams{Model: "bedrock/claude-sonnet-5-5", CustomLLMProvider: "bedrock"}, + } + if got := ResolveCatalogProvider(row); got != "anthropic" { + t.Errorf("got %q", got) + } + if RoutesOnlyThrough(row, map[string]bool{"anthropic": true}) { + t.Error("pricing_provider reached routing evidence") + } + }) +} + func TestRoutesOnlyThrough(t *testing.T) { anthropic := map[string]bool{"anthropic": true} t.Run("requires every declared routing signal to name an allowed provider", func(t *testing.T) { diff --git a/pig/extensions/litellm/internal/discover/catalog.go b/pig/extensions/litellm/internal/discover/catalog.go index 99caa1b7..adfc4752 100644 --- a/pig/extensions/litellm/internal/discover/catalog.go +++ b/pig/extensions/litellm/internal/discover/catalog.go @@ -247,6 +247,10 @@ func messagesCompatOf(model *ai.GeneratedModel) *modelgroups.MessagesBackendComp var anthropicRoutes = map[string]bool{"anthropic": true} +// azureAIRoutes is declared routing, not model_info.litellm_provider, which is a cost-map lookup of +// base_model: a Bedrock-routed deployment priced through an Azure row must not claim Foundry's beta handling. +var azureAIRoutes = map[string]bool{"azure_ai": true} + // messagesStrictToolEvidence: the Anthropic catalog describes the Anthropic API, so only deployments // whose declared routing names Anthropic keep its grant. A hosted route (Bedrock, Vertex) can reject // tools[].strict for the same model, and LiteLLM reports no per-route strict-tool capability, so it @@ -508,21 +512,32 @@ func ResolveModelInfoCatalog(entry types.ModelInfoEntry, publicCatalog catalog.P return nil } identity := backend.ResolveIdentity(entry) + // A declared pricing_provider settles which catalog prices the row, so the provider conflict that + // withheld the identity no longer decides this lookup. Re-read the row without its routing claim, the + // half the conflict was about, for the bare model id that catalog is keyed by. Only the catalog is + // settled: the identity stays withheld for family and routing decisions. + priced := "" + if entry.ModelInfo != nil { + priced = lowerTrim(entry.ModelInfo.PricingProvider) + } + if identity == nil && priced != "" { + unrouted := entry + if entry.LiteLLMParams != nil { + params := *entry.LiteLLMParams + params.CustomLLMProvider = "" + unrouted.LiteLLMParams = ¶ms + } + identity = backend.ResolveIdentity(unrouted) + if identity == nil { + return nil + } + return lookupCatalog(entry, publicCatalog, priced, identity.ModelID, priced+"/"+identity.ModelID) + } if identity == nil { return nil } lookup := func(provider string) *modelgroups.CatalogResolution { - var record *catalog.PublicCatalogRecord - if publicCatalog != nil { - record = publicCatalog.Lookup(provider, identity.ModelID) - } - resolution := adaptPublicCatalogRecord(provider, identity.QualifiedID, record) - if native, ok := nativeMessagesCatalog(entry); ok { - resolution.MessagesCompat = native.MessagesCompat - resolution.MessagesStrictTools = native.MessagesStrictTools - resolution.MessagesThinkingLevelMap = native.MessagesThinkingLevelMap - } - return &resolution + return lookupCatalog(entry, publicCatalog, provider, identity.ModelID, identity.QualifiedID) } if provider := backend.ResolveCatalogProvider(entry); provider != "" { return lookup(provider) @@ -533,6 +548,21 @@ func ResolveModelInfoCatalog(entry types.ModelInfoEntry, publicCatalog catalog.P return lookup(publicCatalogProviderByFamily[identity.Family]) } +// lookupCatalog prices an entry from one provider's catalog row, keeping its native Messages fields. +func lookupCatalog(entry types.ModelInfoEntry, publicCatalog catalog.PublicCatalog, provider, modelID, qualifiedID string) *modelgroups.CatalogResolution { + var record *catalog.PublicCatalogRecord + if publicCatalog != nil { + record = publicCatalog.Lookup(provider, modelID) + } + resolution := adaptPublicCatalogRecord(provider, qualifiedID, record) + if native, ok := nativeMessagesCatalog(entry); ok { + resolution.MessagesCompat = native.MessagesCompat + resolution.MessagesStrictTools = native.MessagesStrictTools + resolution.MessagesThinkingLevelMap = native.MessagesThinkingLevelMap + } + return &resolution +} + // awaitEnrichmentWithinBudget is awaitEnrichmentWithinBudget: it returns the zero value when the budget // elapses first, and ctx's error when ctx ends first. func awaitEnrichmentWithinBudget[T any](ctx context.Context, result <-chan T, budget time.Duration) (T, error) { diff --git a/pig/extensions/litellm/internal/discover/discover.go b/pig/extensions/litellm/internal/discover/discover.go index 26fe72e5..b466ad00 100644 --- a/pig/extensions/litellm/internal/discover/discover.go +++ b/pig/extensions/litellm/internal/discover/discover.go @@ -150,7 +150,7 @@ func discoverFromModelInfo( } var versionGatedRoutes []string for _, route := range groups.routes { - if !strings.Contains(route, "*") && publishesVersionGatedTransport(groups.rows[route], publicCatalog, true) { + if !strings.Contains(route, "*") && publishesVersionGatedBehavior(groups.rows[route], publicCatalog, true) { versionGatedRoutes = append(versionGatedRoutes, route) } } @@ -260,7 +260,7 @@ func discoverFromModelInfo( continue } parents := selectedWildcardRows(entry.ID, wildcardRows, publishedWildcardIDs) - if parents != nil && publishesVersionGatedTransport(parents, publicCatalog, true) { + if parents != nil && publishesVersionGatedBehavior(parents, publicCatalog, true) { versionGatedRoutes = append(versionGatedRoutes, entry.ID) expansionAwaitsProxyVersion = true } @@ -490,7 +490,7 @@ func discoverFromHealth(ctx context.Context, base, apiKey string, options Option var versionGatedRoutes []string for _, route := range groups.routes { // Health discovery never selects Messages, so only Responses can await the version. - if publishesVersionGatedTransport(entriesOf(groups.rows[route]), publicCatalog, false) { + if publishesVersionGatedBehavior(entriesOf(groups.rows[route]), publicCatalog, false) { versionGatedRoutes = append(versionGatedRoutes, route) } } diff --git a/pig/extensions/litellm/internal/discover/fallbacks_test.go b/pig/extensions/litellm/internal/discover/fallbacks_test.go index a18c74c4..d45b4e7e 100644 --- a/pig/extensions/litellm/internal/discover/fallbacks_test.go +++ b/pig/extensions/litellm/internal/discover/fallbacks_test.go @@ -798,7 +798,7 @@ func TestFallbacks_WildcardCombinesOverlappingMetadataConservativelyRegardlessOf }) fbEqual(t, result.Models, `[{"id":"team/claude-sonnet-4-6","name":"Claude Sonnet 4.6","api":"openai-completions",`+ - `"litellmDiscoveryVersion":16,"reasoning":false,"input":["text"],"contextWindow":40000,"maxTokens":4000,`+ + `"litellmDiscoveryVersion":17,"reasoning":false,"input":["text"],"contextWindow":40000,"maxTokens":4000,`+ `"cost":{"input":3,"output":15,"cacheRead":0.3,"cacheWrite":3.75},`+ `"compat":{"supportsStore":false,"cacheControlFormat":"anthropic"}}]`) } @@ -1335,8 +1335,8 @@ func TestFallbacks_VersionGateWarnsOnceNamingTheDependentRoutesWhenTheProxyCanno } fbExpectStrings(t, fbVersionLines(stderr), - "LiteLLM discovery: the proxy reported no readable version (x-litellm-version header); 2 azure_ai route(s) "+ - "whose transport depends on it stay on Chat Completions: claude-opus-5-5, gpt-6-astra\n") + "LiteLLM discovery: the proxy reported no readable version (x-litellm-version header); 2 route(s) "+ + "whose transport or off thinking level depends on it keep the conservative fallback: claude-opus-5-5, gpt-6-astra\n") }) } } @@ -1368,8 +1368,8 @@ func TestFallbacks_VersionGateWarnsAboutIDsExpandedFromAnAzureAIWildcardRouteAnd fbVersionProbe: fbDropConnection, }) - const prefix = "LiteLLM discovery: the proxy reported no readable version (x-litellm-version header); 1 azure_ai route(s) " + - "whose transport depends on it stay on Chat Completions: " + const prefix = "LiteLLM discovery: the proxy reported no readable version (x-litellm-version header); 1 route(s) " + + "whose transport or off thinking level depends on it keep the conservative fallback: " fbExpectStrings(t, fbVersionLines(wildcard), prefix+"foundry/claude-opus-5-5\n") fbExpectStrings(t, fbVersionLines(health), prefix+"gpt-6-astra\n") } @@ -2452,6 +2452,141 @@ func TestFallbacks_NativeMessagesLeavesMidConversationEffortUndeclaredForARouteO } } +func TestFallbacks_VersionGateDecidesAzureAIClaudeMidConversationEffortForTheReportedProxyVersion(t *testing.T) { + for _, tc := range []struct { + version string + denied bool + }{ + {"1.109.0", false}, + {"1.110.4", false}, + {"1.108.21", true}, + {"1.109.0-rc.1", true}, + {"1.106.4", true}, + } { + t.Run(tc.version, func(t *testing.T) { + result, _ := fbDiscover(t, map[string]http.HandlerFunc{ + "/model/info": fbData(fbAzureAIClaude), + fbVersionProbe: fbVersionReply(tc.version), + }) + + model := result.Models[0] + if model.API != ai.APIAnthropicMessages || model.Compat == nil { + t.Fatalf("api = %s compat = %s", model.API, modelInfoBJSON(model.Compat)) + } + if tc.denied != (model.Compat.SupportsMidConvoEffort != nil && !*model.Compat.SupportsMidConvoEffort) || + (!tc.denied && model.Compat.SupportsMidConvoEffort != nil) { + t.Errorf("supportsMidConvoEffort = %v, denied want %v", model.Compat.SupportsMidConvoEffort, tc.denied) + } + }) + } +} + +func TestFallbacks_VersionGateKeepsMidConversationEffortDeniedForAHostedClaudeAPricingLabelCallsAzureAI(t *testing.T) { + // model_info.litellm_provider is a cost-map lookup of base_model, not routing: a Bedrock-routed + // deployment priced through an Azure row reaches Bedrock, so only declared azure_ai routing takes the grant. + bedrockPricedAsAzure := `{"model_name":"claude-opus-5-5","litellm_params":{"model":"bedrock/claude-opus-5-5","custom_llm_provider":"bedrock"},` + + `"model_info":{"mode":"chat","litellm_provider":"azure_ai","supports_reasoning":true}}` + result, _ := fbDiscover(t, map[string]http.HandlerFunc{ + "/model/info": fbData(bedrockPricedAsAzure), + fbVersionProbe: fbVersionReply("1.111.1"), + }) + + model := result.Models[0] + if model.API != ai.APIAnthropicMessages { + t.Fatalf("api = %s, want anthropic-messages", model.API) + } + if model.Compat == nil || model.Compat.SupportsMidConvoEffort == nil || *model.Compat.SupportsMidConvoEffort { + t.Errorf("compat = %s, want supportsMidConvoEffort false", modelInfoBJSON(model.Compat)) + } +} + +func TestFallbacks_PricesAConflictingIdentityFromItsDeclaredPricingProvider(t *testing.T) { + row := func(pricing string) string { + extra := "" + if pricing != "" { + extra = `,"pricing_provider":"` + pricing + `"` + } + return `{"model_name":"team-claude","litellm_params":{"model":"bedrock/claude-sonnet-5-5","custom_llm_provider":"bedrock"},` + + `"model_info":{"mode":"chat","base_model":"anthropic/claude-sonnet-5-5"` + extra + `}}` + } + discoverRow := func(pricing string) types.DiscoveredModel { + result, _ := fbDiscover(t, map[string]http.HandlerFunc{"/model/info": fbData(row(pricing))}) + return result.Models[0] + } + + priced := discoverRow("anthropic") + unpriced := discoverRow("") + + if priced.ContextWindow != 1_000_000 || priced.Cost.Input != 2 || priced.Cost.Output != 10 { + t.Errorf("priced = window %d cost %+v, want 1000000 and input 2 output 10", priced.ContextWindow, priced.Cost) + } + if unpriced.ContextWindow != 128_000 || unpriced.Cost.Input != 0 || unpriced.Cost.Output != 0 { + t.Errorf("unpriced = window %d cost %+v, want the default window and zero cost", unpriced.ContextWindow, unpriced.Cost) + } +} + +const fbThinkByDefault = `{"model_name":"opus-5","litellm_params":{"model":"bedrock/claude-opus-5","custom_llm_provider":"bedrock",` + + `"allowed_openai_params":["reasoning_effort"]},"model_info":{"mode":"chat","supports_reasoning":true,` + + `"supports_none_reasoning_effort":true,"thinking_on_by_default":true}}` + +func TestFallbacks_VersionGateDecidesTheOffLevelOfAThinkByDefaultBackendForTheReportedProxyVersion(t *testing.T) { + for _, tc := range []struct{ version, want string }{ + {"1.110.0", `{"thinkingLevelMap":{"off":"none"}}`}, + {"1.111.1", `{"thinkingLevelMap":{"off":"none"}}`}, + {"1.109.5", `{"thinkingLevelMap":{"off":null}}`}, + {"1.110.0-rc.1", `{"thinkingLevelMap":{"off":null}}`}, + {"", `{"thinkingLevelMap":{"off":null}}`}, + } { + t.Run(tc.version, func(t *testing.T) { + result, _ := fbDiscover(t, map[string]http.HandlerFunc{ + "/model/info": fbData(fbThinkByDefault), + fbVersionProbe: fbVersionReply(tc.version), + }) + + fbMatch(t, result.Models[0], tc.want) + }) + } +} + +func TestFallbacks_VersionGateAsksForTheVersionForAThinkByDefaultRouteThatNeedsNoTransportGate(t *testing.T) { + _, proxy, _ := fbDiscoverProxy(t, map[string]http.HandlerFunc{ + "/model/info": fbData(fbThinkByDefault), + fbVersionProbe: fbVersionReply("1.110.0"), + }) + + if got := fbCount(proxy.Requests(), fbVersionProbe); got != 1 { + t.Errorf("version probes = %d, want 1", got) + } +} + +func TestFallbacks_VersionGateDoesNotAskForTheVersionWhenASiblingDeniesTheOffLevelAtEveryVersion(t *testing.T) { + alwaysOn := `{"model_name":"opus-5","litellm_params":{"model":"bedrock/claude-opus-5","custom_llm_provider":"bedrock",` + + `"allowed_openai_params":["reasoning_effort"]},"model_info":{"mode":"chat","supports_reasoning":true,"thinking_always_on":true}}` + result, proxy, _ := fbDiscoverProxy(t, map[string]http.HandlerFunc{ + "/model/info": fbData(fbThinkByDefault, alwaysOn), + fbVersionProbe: fbVersionReply("1.110.0"), + }) + + if got := fbCount(proxy.Requests(), fbVersionProbe); got != 0 { + t.Errorf("version probes = %d, want 0", got) + } + if off, ok := result.Models[0].ThinkingLevelMap["off"]; !ok || off != nil { + t.Errorf("off = %v (present %t), want null", off, ok) + } +} + +func TestFallbacks_DeniesTheOffLevelForABackendWhoseThinkingIsAlwaysOn(t *testing.T) { + // An accepted `none` cannot stop thinking the backend always does, and no proxy release can either, + // so this needs no version gate. + result, _ := fbDiscover(t, map[string]http.HandlerFunc{ + "/model/info": fbData(`{"model_name":"custom/always-thinking","litellm_params":{"allowed_openai_params":["reasoning_effort"]},` + + `"model_info":{"mode":"chat","supports_reasoning":true,"supports_none_reasoning_effort":true,` + + `"thinking_always_on":true,"supports_max_reasoning_effort":true}}`), + }) + + fbMatch(t, result.Models[0], `{"thinkingLevelMap":{"off":null,"max":"max"}}`) +} + func TestFallbacks_NativeMessagesKeepsAMidConversationEffortDenialThroughTheOfflineCache(t *testing.T) { forced, denied := true, false cached := types.DiscoveredModel{ @@ -2507,6 +2642,27 @@ func TestFallbacks_PromptCacheDeclaresLifetimesForUnanimousClaudeEvidenceOnNativ fbMatch(t, result.Models[0], `{"api":"anthropic-messages","promptCache":{"short":300,"long":3600}}`) } +func TestFallbacks_PromptCacheDeclaresNoneWhenADeploymentReportsItBillsNoPromptCache(t *testing.T) { + // A relay can host a Claude generation without prompt caching; the family's documented lifetimes + // do not apply to a deployment LiteLLM says has none. + messages, _ := fbDiscover(t, map[string]http.HandlerFunc{ + "/model/info": fbData(fbClaudeRow("claude", `,"supports_prompt_caching":false`, "anthropic/claude-sonnet-4-5")), + }) + chat, _ := fbDiscover(t, map[string]http.HandlerFunc{ + "/model/info": fbData(fbClaudeRow("claude-chat", `,"supported_endpoints":["/v1/chat/completions"],"supports_prompt_caching":false`, + "anthropic/claude-sonnet-4-5")), + }) + absent, _ := fbDiscover(t, map[string]http.HandlerFunc{ + "/model/info": fbData(fbClaudeRow("claude", "", "anthropic/claude-sonnet-4-5")), + }) + + fbMatch(t, messages.Models[0], `{"api":"anthropic-messages"}`) + fbLacks(t, messages.Models[0], "promptCache") + fbLacks(t, chat.Models[0], "promptCache") + // An absent flag is not a denial. + fbMatch(t, absent.Models[0], `{"promptCache":{"short":300,"long":3600}}`) +} + func TestFallbacks_PromptCacheDeclaresLifetimesForAClaudeBackedChatCompletionsRoute(t *testing.T) { result, _ := fbDiscover(t, map[string]http.HandlerFunc{ "/model/info": fbData(fbClaudeRow("claude-chat", `,"supported_endpoints":["/v1/chat/completions"]`, "anthropic/claude-sonnet-4-5")), @@ -2600,6 +2756,15 @@ func TestFallbacks_PromptCacheDeclaresTheThirtyMinuteLifetimeForGpt56AndLaterOnR } } +func TestFallbacks_PromptCacheDeclaresNoneForGpt56AndLaterThatReportsItBillsNoPromptCache(t *testing.T) { + result, _ := fbDiscover(t, map[string]http.HandlerFunc{ + "/model/info": fbData(fbGptRow("sol", "openai/gpt-6.1-sol", `,"supports_prompt_caching":false`)), + }) + + fbMatch(t, result.Models[0], `{"api":"openai-responses"}`) + fbLacks(t, result.Models[0], "promptCache") +} + func TestFallbacks_PromptCacheDeclaresNoneForGpt56AndLaterOnChatCompletions(t *testing.T) { result, _ := fbDiscover(t, map[string]http.HandlerFunc{ "/model/info": fbData(`{"model_name":"sol-chat","litellm_params":{"model":"openai/gpt-6.1-sol"},` + diff --git a/pig/extensions/litellm/internal/discover/fetch.go b/pig/extensions/litellm/internal/discover/fetch.go index 441480bb..760b1a8d 100644 --- a/pig/extensions/litellm/internal/discover/fetch.go +++ b/pig/extensions/litellm/internal/discover/fetch.go @@ -298,12 +298,12 @@ func reportIncompatibleDeploymentModes(routes []string, options Options) { }, options) } -// reportUnreadProxyVersion: the version decides these routes' transport, and nothing else tells an -// operator why they stay on the workaround when the proxy does not say which release it is. +// reportUnreadProxyVersion: the version decides these routes' transport or off thinking level, and nothing +// else tells an operator why they stay on the workaround when the proxy does not say which release it is. func reportUnreadProxyVersion(routes []string, options Options) { reportBoundedRoutes(&reportedUnreadVersionRoutes, unique(routes), func(count int) string { - return fmt.Sprintf("LiteLLM discovery: the proxy reported no readable version (x-litellm-version header); %d azure_ai "+ - "route(s) whose transport depends on it stay on Chat Completions", count) + return fmt.Sprintf("LiteLLM discovery: the proxy reported no readable version (x-litellm-version header); %d "+ + "route(s) whose transport or off thinking level depends on it keep the conservative fallback", count) }, options) } diff --git a/pig/extensions/litellm/internal/discover/group.go b/pig/extensions/litellm/internal/discover/group.go index cfe73d79..223dc40c 100644 --- a/pig/extensions/litellm/internal/discover/group.go +++ b/pig/extensions/litellm/internal/discover/group.go @@ -74,7 +74,7 @@ func mapFromModelInfoGroup( resolution.SemanticModel = generation } return &resolution - }) + }, options.proxyVersion) if reduced == nil { return nil } @@ -153,9 +153,13 @@ func mapFromModelInfoGroup( if reduced.MessagesStrictTools { messagesCompat.SupportsStrictTools = boolPtr(true) } - // Managed effort adds thinking.block_binding, which hosted Claude endpoints (Azure among them) reject. - // LiteLLM reports no per-route support, so only a group routed solely through Anthropic may keep it. - if slices.ContainsFunc(entries, func(entry types.ModelInfoEntry) bool { return !backend.RoutesOnlyThrough(entry, anthropicRoutes) }) { + // Managed effort adds thinking.block_binding, which hosted Claude endpoints reject unless the proxy + // forwards its beta header. LiteLLM reports no per-route support, so a group keeps it only where every + // deployment routes solely through Anthropic, or through azure_ai on a proxy that forwards the beta. + if slices.ContainsFunc(entries, func(entry types.ModelInfoEntry) bool { + return !backend.RoutesOnlyThrough(entry, anthropicRoutes) && + !(backend.RoutesOnlyThrough(entry, azureAIRoutes) && proxyversion.AtLeast(options.proxyVersion, azureAIThinkingBindingFloor)) + }) { messagesCompat.SupportsMidConvoEffort = boolPtr(false) } } @@ -260,12 +264,12 @@ func mapFromModelInfoGroup( } relaysAnthropicCache := api == types.APIAnthropicMessages || (api == types.APIOpenAICompletions && policy.Compat != nil && policy.Compat.CacheControlFormat == "anthropic") - if len(families) == 1 && family == types.FamilyClaude && relaysAnthropicCache { + if len(families) == 1 && family == types.FamilyClaude && relaysAnthropicCache && !deniesPromptCache(entries) { model.PromptCache = claudePromptCache() } // OpenAI's and Azure's documented 30-minute default minimum for GPT-5.6 and later. No `long`: the 12-hour // lifetime needs `prompt_cache_options.ttl`, which Pi's long retention does not request. - if api == types.APIOpenAIResponses && openAIGpt56 { + if api == types.APIOpenAIResponses && openAIGpt56 && !deniesPromptCache(entries) { model.PromptCache = ai.ModelPromptCache{"short": 1800} } return model @@ -279,13 +283,46 @@ func claudePromptCache() ai.ModelPromptCache { return ai.ModelPromptCache{"short": 300, "long": 3600} } -// publishesVersionGatedTransport: whether a group that will be published has its transport decided by -// the proxy version. Mapping without collectors leaves no diagnostic behind, and whether a group is -// published does not depend on the version. -func publishesVersionGatedTransport(group []types.ModelInfoEntry, publicCatalog catalog.PublicCatalog, allowMessages bool) bool { +// azureAIThinkingBindingFloor: LiteLLM dropped the `thinking-binding-controls-2026-08-01` beta header on the +// way to Azure AI Foundry, which answered 400 for the `thinking.block_binding` managed effort sends. +// v1.109.0 forwards it on native Messages. +var azureAIThinkingBindingFloor = proxyversion.Floor{1, 109, 0} + +// deniesPromptCache: a deployment LiteLLM reports as billing no prompt cache cannot honor Pi's cache +// markers. Only an explicit denial counts; an absent flag says nothing. +func deniesPromptCache(entries []types.ModelInfoEntry) bool { + return slices.ContainsFunc(entries, func(entry types.ModelInfoEntry) bool { + return entry.ModelInfo != nil && isFalsePtr(entry.ModelInfo.SupportsPromptCaching) + }) +} + +func isFalsePtr(value *bool) bool { return value != nil && !*value } + +// reasoningAwaitsProxyVersion: below the floor a think-by-default backend keeps thinking however the off +// level is sent. `thinking_always_on` needs no version, since no release can disable that thinking. +func reasoningAwaitsProxyVersion(entry types.ModelInfoEntry) bool { + return entry.ModelInfo != nil && entry.ModelInfo.ThinkingOnByDefault != nil && *entry.ModelInfo.ThinkingOnByDefault +} + +// publishesVersionGatedBehavior: whether a group that will be published has its transport or its off +// thinking level decided by the proxy version. Mapping without collectors leaves no diagnostic behind, +// and whether a group is published does not depend on the version. +func publishesVersionGatedBehavior(group []types.ModelInfoEntry, publicCatalog catalog.PublicCatalog, allowMessages bool) bool { if slices.ContainsFunc(group, transportAwaitsProxyVersion) { return mapFromModelInfoGroup(group, publicCatalog, nil) != nil } + // A think-by-default route awaits the version only where the off level differs across the floor. A + // sibling that always thinks, or a declared effort list without `none`, denies it at every version, + // and probing would add a failed request and a warning that explains nothing. + if slices.ContainsFunc(group, reasoningAwaitsProxyVersion) { + below := mapFromModelInfoGroup(group, publicCatalog, nil) + if below != nil { + atFloor := mapFromModelInfoGroup(group, publicCatalog, &groupOptions{proxyVersion: &modelgroups.ThinkingDisableFloorVersion}) + if !offLevelEqual(below, atFloor) { + return true + } + } + } // Messages awaits the version only where a proxy at the floor would get it: an endpoint list or a // sibling deployment can keep the group on Chat regardless. if !allowMessages || !slices.ContainsFunc(group, messagesAwaitProxyVersion) { @@ -296,6 +333,19 @@ func publishesVersionGatedTransport(group []types.ModelInfoEntry, publicCatalog return model != nil && model.API == ai.APIAnthropicMessages } +// offLevelEqual compares the published `off` entries of two mappings, where absent and null differ. +func offLevelEqual(a, b *types.DiscoveredModel) bool { + if b == nil { + return false + } + av, aok := a.ThinkingLevelMap["off"] + bv, bok := b.ThinkingLevelMap["off"] + if aok != bok { + return false + } + return (av == nil) == (bv == nil) && (av == nil || *av == *bv) +} + // mapFromModelsList: an evidence-free fallback entry has no deployment or adapter evidence. Its route // name authorizes nothing; the Pi catalog entry for its id supplies its protocol and presentation // metadata, while an unknown id stays on Chat Completions until /model/info can be read. diff --git a/pig/extensions/litellm/internal/discover/model_info_a_test.go b/pig/extensions/litellm/internal/discover/model_info_a_test.go index 449c8518..af5e5759 100644 --- a/pig/extensions/litellm/internal/discover/model_info_a_test.go +++ b/pig/extensions/litellm/internal/discover/model_info_a_test.go @@ -189,7 +189,7 @@ func TestModelInfoA_ReducesMixedAzureDeploymentVersionsToChatCompletions(t *test model := firstModel(t, base, options) if model.ID != "gpt-production" || model.API != ai.APIOpenAICompletions || model.LiteLLMBackendFamily != types.FamilyOpenAI || - model.LiteLLMDiscoveryVersion != 16 { + model.LiteLLMDiscoveryVersion != 17 { t.Errorf("model = %+v", model) } } diff --git a/pig/extensions/litellm/internal/modelgroups/helpers_test.go b/pig/extensions/litellm/internal/modelgroups/helpers_test.go index 0ec9c428..4ca7654d 100644 --- a/pig/extensions/litellm/internal/modelgroups/helpers_test.go +++ b/pig/extensions/litellm/internal/modelgroups/helpers_test.go @@ -191,7 +191,7 @@ func near(t *testing.T, got, want float64) { func mustReduce(t *testing.T, entries []types.ModelInfoEntry, resolver CatalogResolver) *ReducedModelGroup { t.Helper() - group := ReduceModelGroup(entries, resolver) + group := ReduceModelGroup(entries, resolver, nil) if group == nil { t.Fatal("expected a reduced model group, got nil") } diff --git a/pig/extensions/litellm/internal/modelgroups/modelgroups.go b/pig/extensions/litellm/internal/modelgroups/modelgroups.go index f80fa1df..1fd0bfc9 100644 --- a/pig/extensions/litellm/internal/modelgroups/modelgroups.go +++ b/pig/extensions/litellm/internal/modelgroups/modelgroups.go @@ -15,6 +15,7 @@ import ( "github.com/MichaelKinsy/PiG/ai" "github.com/balcsida/pi-provider-litellm/pig/extensions/litellm/internal/backend" + "github.com/balcsida/pi-provider-litellm/pig/extensions/litellm/internal/proxyversion" "github.com/balcsida/pi-provider-litellm/pig/extensions/litellm/internal/thinking" "github.com/balcsida/pi-provider-litellm/pig/extensions/litellm/internal/types" ) @@ -427,11 +428,22 @@ func stringPtr(value string) *string { return &value } // reportedLevel: LiteLLM reads a declared `reasoning_effort_levels` list whole, ahead of the // per-level flags, because flags cannot state a set such as low/high/max: medium has no opt-out. A // declared list therefore answers every level for its deployment. Nil is absent. -func reportedLevel(entry types.ModelInfoEntry, level ai.ModelThinkingLevel) *bool { +func reportedLevel(entry types.ModelInfoEntry, level ai.ModelThinkingLevel, proxyVersion *proxyversion.Version) *bool { info := entry.ModelInfo if info == nil { return nil } + // A backend that always thinks cannot honor Pi's off level, and one that thinks by default needs a + // proxy that forwards the disable. Both deny the level whatever carrier the route accepts, so they + // are read ahead of the declared list. + if level == ai.ThinkingOff { + if isTrue(info.ThinkingAlwaysOn) { + return boolPtr(false) + } + if isTrue(info.ThinkingOnByDefault) && !proxyversion.AtLeast(proxyVersion, thinkingDisableFloor) { + return boolPtr(false) + } + } if info.ReasoningEffortLevels != nil { for _, effort := range info.ReasoningEffortLevels { if normalized, ok := normalizeEffort(effort); ok && normalized == level { @@ -443,6 +455,13 @@ func reportedLevel(entry types.ModelInfoEntry, level ai.ModelThinkingLevel) *boo return levelFlag(info, level) } +// thinkingDisableFloor: until LiteLLM 1.110.0, `reasoning_effort: "none"` sent nothing to a backend whose +// thinking is on by default; 1.110.0 translates it to `thinking: {"type": "disabled"}`. +var thinkingDisableFloor = proxyversion.Floor{1, 110, 0} + +// ThinkingDisableFloorVersion is a proxy version exactly at that floor. +var ThinkingDisableFloorVersion = proxyversion.Version{Major: thinkingDisableFloor[0], Minor: thinkingDisableFloor[1], Patch: thinkingDisableFloor[2]} + func isTrue(value *bool) bool { return value != nil && *value } func isFalse(value *bool) bool { return value != nil && !*value } @@ -461,6 +480,7 @@ func reasoningLevelMap( entries []types.ModelInfoEntry, catalogEfforts [][]string, catalogMaps []ai.ThinkingLevelMap, + proxyVersion *proxyversion.Version, ) ai.ThinkingLevelMap { var publicSets []map[ai.ModelThinkingLevel]bool for _, levels := range catalogEfforts { @@ -506,7 +526,7 @@ func reasoningLevelMap( allTrue := len(entries) > 0 anyFalse := false for _, entry := range entries { - reported := reportedLevel(entry, level) + reported := reportedLevel(entry, level, proxyVersion) anyFalse = anyFalse || isFalse(reported) allTrue = allTrue && isTrue(reported) } @@ -519,7 +539,7 @@ func reasoningLevelMap( for _, level := range []ai.ModelThinkingLevel{ai.ThinkingXHigh, ai.ThinkingMax} { every := true for _, entry := range entries { - every = every && isTrue(reportedLevel(entry, level)) + every = every && isTrue(reportedLevel(entry, level, proxyVersion)) } if !every { out[level] = nil @@ -1300,7 +1320,7 @@ func infoOf(entry types.ModelInfoEntry) *types.ModelInfoDetails { // ReduceModelGroup reduces every deployment behind one public route into a single model, or nil when // the group is empty or contains a non-chat deployment. -func ReduceModelGroup(entries []types.ModelInfoEntry, resolveCatalog CatalogResolver) *ReducedModelGroup { +func ReduceModelGroup(entries []types.ModelInfoEntry, resolveCatalog CatalogResolver, proxyVersion *proxyversion.Version) *ReducedModelGroup { canonical := canonicalModelInfoDeployments(entries) candidates, candidateModes, deployments := canonical.candidates, canonical.candidateModes, canonical.routable if len(candidates) == 0 { @@ -1558,7 +1578,7 @@ func ReduceModelGroup(entries []types.ModelInfoEntry, resolveCatalog CatalogReso publicEfforts[i], authorityMaps[i] = authority.EffortLevels, authority.ThinkingLevelMap } } - evidenceLevelMap := reasoningLevelMap(deployments, publicEfforts, []ai.ThinkingLevelMap{thinking.Intersect(authorityMaps)}) + evidenceLevelMap := reasoningLevelMap(deployments, publicEfforts, []ai.ThinkingLevelMap{thinking.Intersect(authorityMaps)}, proxyVersion) var thinkingLevelMap ai.ThinkingLevelMap if reasoning && acceptsResponsesReasoningControl { thinkingLevelMap = evidenceLevelMap @@ -1576,7 +1596,7 @@ func ReduceModelGroup(entries []types.ModelInfoEntry, resolveCatalog CatalogReso for _, level := range extendedLevels { anyFalse, anyDefined, allTrue := false, false, true for _, entry := range deployments { - reported := reportedLevel(entry, level) + reported := reportedLevel(entry, level, proxyVersion) anyFalse = anyFalse || isFalse(reported) anyDefined = anyDefined || reported != nil allTrue = allTrue && isTrue(reported) @@ -1617,7 +1637,7 @@ func ReduceModelGroup(entries []types.ModelInfoEntry, resolveCatalog CatalogReso isFalse(semanticReasoningPolicy.Compat.SupportsReasoningEffort) && !hasEvidenceLevels explicitOffDenial := false for _, entry := range deployments { - explicitOffDenial = explicitOffDenial || isFalse(reportedLevel(entry, ai.ThinkingOff)) + explicitOffDenial = explicitOffDenial || isFalse(reportedLevel(entry, ai.ThinkingOff, proxyVersion)) } reasoningPolicy := semanticReasoningPolicy if semanticMap != nil { diff --git a/pig/extensions/litellm/internal/modelgroups/reduce_test.go b/pig/extensions/litellm/internal/modelgroups/reduce_test.go index 0fba0dd1..27609540 100644 --- a/pig/extensions/litellm/internal/modelgroups/reduce_test.go +++ b/pig/extensions/litellm/internal/modelgroups/reduce_test.go @@ -39,7 +39,7 @@ func TestReduceModelGroup(t *testing.T) { ReasoningPolicy: ReasoningPolicy{Reasoning: false}, } for _, order := range permutations(deployments) { - eq(t, ReduceModelGroup(order, resolveCatalog), expected) + eq(t, ReduceModelGroup(order, resolveCatalog, nil), expected) } }) @@ -48,14 +48,14 @@ func TestReduceModelGroup(t *testing.T) { conflicting := row(idMode("deployment-a", "chat"), info(func(i *types.ModelInfoDetails) { i.MaxInputTokens = f(8_000) })) anonymous := row(idMode("", "chat")) - eq(t, ReduceModelGroup([]types.ModelInfoEntry{repeated, repeated}, resolveCatalog), - ReduceModelGroup([]types.ModelInfoEntry{repeated}, resolveCatalog)) + eq(t, ReduceModelGroup([]types.ModelInfoEntry{repeated, repeated}, resolveCatalog, nil), + ReduceModelGroup([]types.ModelInfoEntry{repeated}, resolveCatalog, nil)) // Conflicting variants of one deployment id both stay in the reduction. expected := mustReduce(t, []types.ModelInfoEntry{repeated, conflicting}, resolveCatalog) if expected.ContextWindow != 8_000 { t.Fatalf("contextWindow %v", expected.ContextWindow) } - eq(t, ReduceModelGroup([]types.ModelInfoEntry{conflicting, repeated}, resolveCatalog), expected) + eq(t, ReduceModelGroup([]types.ModelInfoEntry{conflicting, repeated}, resolveCatalog, nil), expected) // Exact id-less repeats remain plural: equal content is not enough evidence that two rows // describe the same deployment. @@ -63,7 +63,7 @@ func TestReduceModelGroup(t *testing.T) { ReduceModelGroup([]types.ModelInfoEntry{anonymous, anonymous}, func(types.ModelInfoEntry) *CatalogResolution { calls++ return nil - }) + }, nil) if calls != 2 { t.Fatalf("calls %d", calls) } @@ -118,7 +118,7 @@ func TestReduceModelGroup(t *testing.T) { deployment := func(id, mode string) types.ModelInfoEntry { return row(idMode(id, mode), backendModel("internal/"+id)) } - if got := ReduceModelGroup([]types.ModelInfoEntry{deployment("first", c.first), deployment("second", c.second)}, resolveCatalog); got != nil { + if got := ReduceModelGroup([]types.ModelInfoEntry{deployment("first", c.first), deployment("second", c.second)}, resolveCatalog, nil); got != nil { t.Fatalf("expected nil, got %s", dump(got)) } }) @@ -225,7 +225,7 @@ func TestReduceModelGroup(t *testing.T) { t.Fatalf("%v %s", got.ContextWindow, got.API) } // Genuinely non-chat: rejects the entire mixed route. - if ReduceModelGroup([]types.ModelInfoEntry{roomy, embedding}, resolveCatalog) != nil { + if ReduceModelGroup([]types.ModelInfoEntry{roomy, embedding}, resolveCatalog, nil) != nil { t.Fatal("expected nil") } // A lone unreadable row is surfaced conservatively rather than silently hidden. @@ -236,7 +236,7 @@ func TestReduceModelGroup(t *testing.T) { }) t.Run("drops a group when every deployment is non-chat", func(t *testing.T) { - got := ReduceModelGroup([]types.ModelInfoEntry{row(idMode("embed-a", "embedding")), row(idMode("embed-b", "embedding"))}, resolveCatalog) + got := ReduceModelGroup([]types.ModelInfoEntry{row(idMode("embed-a", "embedding")), row(idMode("embed-b", "embedding"))}, resolveCatalog, nil) if got != nil { t.Fatal("expected nil") } diff --git a/pig/extensions/litellm/internal/modelgroups/regressions_test.go b/pig/extensions/litellm/internal/modelgroups/regressions_test.go index 5268f549..3187796b 100644 --- a/pig/extensions/litellm/internal/modelgroups/regressions_test.go +++ b/pig/extensions/litellm/internal/modelgroups/regressions_test.go @@ -72,16 +72,16 @@ func TestUpstreamReductionRegressions(t *testing.T) { other := row(idMode("other", "chat")) conflicting := row(idMode("chat", "chat"), info(func(i *types.ModelInfoDetails) { i.MaxInputTokens = f(8_000) })) - ReduceModelGroup([]types.ModelInfoEntry{chat}, record) + ReduceModelGroup([]types.ModelInfoEntry{chat}, record, nil) eq(t, seen, []types.ModelInfoEntry{chat}) seen = nil - ReduceModelGroup([]types.ModelInfoEntry{chat, chat}, record) + ReduceModelGroup([]types.ModelInfoEntry{chat, chat}, record, nil) eq(t, seen, []types.ModelInfoEntry{chat}) // An incompatible sibling withholds the route before catalog resolution. seen = nil - if ReduceModelGroup([]types.ModelInfoEntry{chat, embedding}, record) != nil { + if ReduceModelGroup([]types.ModelInfoEntry{chat, embedding}, record, nil) != nil { t.Fatal("expected nil") } if len(seen) != 0 { @@ -89,11 +89,11 @@ func TestUpstreamReductionRegressions(t *testing.T) { } seen = nil - ReduceModelGroup([]types.ModelInfoEntry{chat, other}, record) + ReduceModelGroup([]types.ModelInfoEntry{chat, other}, record, nil) eq(t, seen, []types.ModelInfoEntry{chat, other}) seen = nil - ReduceModelGroup([]types.ModelInfoEntry{chat, conflicting}, record) + ReduceModelGroup([]types.ModelInfoEntry{chat, conflicting}, record, nil) if len(seen) != 2 { t.Fatalf("seen %d", len(seen)) } @@ -106,8 +106,8 @@ func TestUpstreamReductionRegressions(t *testing.T) { i.MaxInputTokens, i.MaxOutputTokens = f(1), f(1) }), backendModel("internal/embedding")) - if ReduceModelGroup([]types.ModelInfoEntry{responses, unsupported}, resolveCatalog) != nil || - ReduceModelGroup([]types.ModelInfoEntry{chat, unsupported}, resolveCatalog) != nil { + if ReduceModelGroup([]types.ModelInfoEntry{responses, unsupported}, resolveCatalog, nil) != nil || + ReduceModelGroup([]types.ModelInfoEntry{chat, unsupported}, resolveCatalog, nil) != nil { t.Fatal("expected nil") } if !HasMixedIncompatibleDeploymentModes([]types.ModelInfoEntry{chat, unsupported}) { diff --git a/pig/extensions/litellm/internal/modelgroups/wire_test.go b/pig/extensions/litellm/internal/modelgroups/wire_test.go index 3de8b98f..04133e66 100644 --- a/pig/extensions/litellm/internal/modelgroups/wire_test.go +++ b/pig/extensions/litellm/internal/modelgroups/wire_test.go @@ -56,7 +56,7 @@ func TestMistypedWireFields(t *testing.T) { if got.ContextWindow != 8_000 || got.API != types.APIOpenAICompletions { t.Fatalf("%v %s", got.ContextWindow, got.API) } - if ReduceModelGroup([]types.ModelInfoEntry{roomy, embedding}, resolveCatalog) != nil { + if ReduceModelGroup([]types.ModelInfoEntry{roomy, embedding}, resolveCatalog, nil) != nil { t.Fatal("expected nil") } got = mustReduce(t, []types.ModelInfoEntry{unreadable}, resolveCatalog) diff --git a/pig/extensions/litellm/internal/types/types.go b/pig/extensions/litellm/internal/types/types.go index e46f1f81..c44b3964 100644 --- a/pig/extensions/litellm/internal/types/types.go +++ b/pig/extensions/litellm/internal/types/types.go @@ -27,7 +27,7 @@ const ( ) // DiscoveryVersion is LITELLM_DISCOVERY_VERSION. -const DiscoveryVersion = 16 +const DiscoveryVersion = 17 // BackendFamily is a backend vendor family; the empty string means no family. type BackendFamily string @@ -140,6 +140,7 @@ type ModelInfoDetails struct { Mode *string `json:"mode,omitempty"` BaseModel string `json:"base_model,omitempty"` LiteLLMProvider string `json:"litellm_provider,omitempty"` + PricingProvider string `json:"pricing_provider,omitempty"` SupportedEndpoints []string `json:"supported_endpoints,omitempty"` SupportedOpenAIParams []string `json:"supported_openai_params,omitempty"` InputCostPerToken *float64 `json:"input_cost_per_token,omitempty"` @@ -157,6 +158,9 @@ type ModelInfoDetails struct { SupportsHighReasoningEffort *bool `json:"supports_high_reasoning_effort,omitempty"` SupportsXHighReasoningEffort *bool `json:"supports_xhigh_reasoning_effort,omitempty"` SupportsMaxReasoningEffort *bool `json:"supports_max_reasoning_effort,omitempty"` + ThinkingAlwaysOn *bool `json:"thinking_always_on,omitempty"` + ThinkingOnByDefault *bool `json:"thinking_on_by_default,omitempty"` + SupportsPromptCaching *bool `json:"supports_prompt_caching,omitempty"` SupportsVision *bool `json:"supports_vision,omitempty"` } diff --git a/scripts/minimize-proxy-snapshot.ts b/scripts/minimize-proxy-snapshot.ts index 0bb3f48d..eae0f7fe 100644 --- a/scripts/minimize-proxy-snapshot.ts +++ b/scripts/minimize-proxy-snapshot.ts @@ -9,6 +9,7 @@ const MODEL_INFO = [ "blocked", "base_model", "litellm_provider", + "pricing_provider", "mode", "supported_endpoints", "supported_openai_params", @@ -24,8 +25,15 @@ const MODEL_INFO = [ "supports_none_reasoning_effort", "supports_minimal_reasoning_effort", "supports_low_reasoning_effort", + // medium and high were missing here while src read them, the same omission AGENTS.md records + // for the request-side flag table: a captured snapshot dropped the flags discovery acts on. + "supports_medium_reasoning_effort", + "supports_high_reasoning_effort", "supports_xhigh_reasoning_effort", "supports_max_reasoning_effort", + "thinking_always_on", + "thinking_on_by_default", + "supports_prompt_caching", ] as const; const FORBIDDEN_FIXTURE_FIELDS = new Set(["api_key", "extra_headers", "access_groups", "tenant"]); const GROUP_FIELDS = [ diff --git a/src/backend-identity.ts b/src/backend-identity.ts index 48f7e945..1f31690e 100644 --- a/src/backend-identity.ts +++ b/src/backend-identity.ts @@ -1,11 +1,11 @@ -export const LITELLM_DISCOVERY_VERSION = 16 as const; +export const LITELLM_DISCOVERY_VERSION = 17 as const; export type BackendFamily = "claude" | "deepseek" | "gemini" | "kimi" | "openai"; export interface BackendIdentityRow { model_name?: string; litellm_params?: { model?: string; custom_llm_provider?: string }; - model_info?: { base_model?: string; litellm_provider?: string }; + model_info?: { base_model?: string; litellm_provider?: string; pricing_provider?: string }; } export interface BackendIdentity { @@ -122,6 +122,12 @@ export function resolveCatalogProvider( row: BackendIdentityRow, identity = resolveBackendIdentity(row), ): string | undefined { + // `model_info.pricing_provider` (LiteLLM 1.109.0+) is the operator naming the catalog that + // prices this deployment, which is what this lookup asks. It outranks every inference below, + // including the conflicts that otherwise withhold an identity. It is a pricing statement, not + // routing evidence, so `routesOnlyThrough` must keep ignoring it. + const priced = wireString(row.model_info?.pricing_provider)?.trim().toLowerCase(); + if (priced) return priced; if (identity?.provider && !GENERIC_CATALOG_PROVIDERS.has(identity.provider)) return identity.provider; const reported = wireString(row.model_info?.litellm_provider)?.toLowerCase(); const custom = wireString(row.litellm_params?.custom_llm_provider)?.toLowerCase(); diff --git a/src/discover.ts b/src/discover.ts index 3f084a2f..84c7b529 100644 --- a/src/discover.ts +++ b/src/discover.ts @@ -25,6 +25,8 @@ import { reduceModelGroup, type SemanticFamily, type SemanticModel, + THINKING_DISABLE_FLOOR_VERSION, + wireBoolean, wireString, } from "./model-groups.js"; import { type ProxyVersion, type ProxyVersionFloor, probeProxyVersion, proxyVersionAtLeast } from "./proxy-version.js"; @@ -415,6 +417,27 @@ function messagesCompatOf(model: Model): MessagesBackendCompat | undefined } const ANTHROPIC_ROUTES: ReadonlySet = new Set(["anthropic"]); +// Declared routing, not `model_info.litellm_provider`, which is a cost-map lookup of `base_model`: +// a Bedrock-routed deployment priced through an Azure row must not claim Foundry's beta handling. +const AZURE_AI_ROUTES: ReadonlySet = new Set(["azure_ai"]); + +// LiteLLM dropped the `thinking-binding-controls-2026-08-01` beta header on the way to Azure AI +// Foundry, so Foundry answered 400 for the `thinking.block_binding` that managed effort sends. +// v1.109.0 forwards it (and the client's `anthropic-version`) on native Messages. +const AZURE_AI_THINKING_BINDING_FLOOR: ProxyVersionFloor = [1, 109, 0]; + +// A deployment LiteLLM reports as billing no prompt cache cannot honor Pi's cache markers, whatever +// its backend family documents. Only an explicit denial counts; an absent flag says nothing. +function deniesPromptCache(entries: readonly ModelInfoEntry[]): boolean { + return entries.some((entry) => wireBoolean(entry.model_info?.supports_prompt_caching) === false); +} + +// Whether the proxy version decides this deployment's off thinking level: below the floor a +// think-by-default backend keeps thinking however the level is sent. `thinking_always_on` needs +// no version, since no release can disable that thinking. +function reasoningAwaitsProxyVersion(entry: ModelInfoEntry): boolean { + return wireBoolean(entry.model_info?.thinking_on_by_default) === true; +} function messagesStrictToolEvidence(entry: ModelInfoEntry, model: Model): boolean | undefined { // The Anthropic catalog describes the Anthropic API, so only deployments whose @@ -602,6 +625,23 @@ export function resolveModelInfoCatalog( ); if (!hasBackendIdentity) return undefined; const identity = resolveBackendIdentity(entry); + // A declared pricing_provider settles which catalog prices the row, so the provider conflict that + // withheld the identity no longer decides this lookup. Re-read the row without its routing claim, + // which is the half the conflict was about, to get the bare model id the declared catalog is keyed + // by. Only the catalog is settled: the identity stays withheld for family and routing decisions. + const priced = wireString(entry.model_info?.pricing_provider)?.trim().toLowerCase(); + if (!identity && priced) { + const unrouted = resolveBackendIdentity({ + ...entry, + litellm_params: { ...entry.litellm_params, custom_llm_provider: undefined }, + }); + if (!unrouted) return undefined; + const record = publicCatalog?.lookup(priced, unrouted.modelId); + return { + ...adaptPublicCatalogRecord(priced, `${priced}/${unrouted.modelId}`, record), + ...nativeMessagesCatalog(entry), + }; + } if (!identity) return undefined; const provider = resolveCatalogProvider(entry, identity); if (provider) { @@ -726,16 +766,16 @@ function reportAmbiguousCatalogAuthority(report: Report, routes: readonly string const reportedUnreadVersionRoutes = new Set(); -// The version decides these routes' transport, and nothing else tells an operator -// why they stay on the workaround when the proxy does not say which release it is. +// The version decides these routes' transport or off thinking level, and nothing else tells an +// operator why they stay on the workaround when the proxy does not say which release it is. function reportUnreadProxyVersion(report: Report, routes: readonly string[]): void { reportBoundedRoutes( report, reportedUnreadVersionRoutes, routes, (count) => - `LiteLLM discovery: the proxy reported no readable version (x-litellm-version header); ${count} azure_ai ` + - "route(s) whose transport depends on it stay on Chat Completions", + `LiteLLM discovery: the proxy reported no readable version (x-litellm-version header); ${count} ` + + "route(s) whose transport or off thinking level depends on it keep the conservative fallback", ); } @@ -766,30 +806,34 @@ function mapFromModelInfoGroup( modelOverrides?: DiscoveryOptions["modelOverrides"]; } = {}, ): DiscoveredModel | undefined { - const reduced = reduceModelGroup(entries, (entry) => { - const resolved = resolveModelInfoCatalog(entry, publicCatalog); - const limitOverrides = - resolved?.piProvider && resolved.catalogModelId - ? options.modelOverrides?.[resolved.piProvider]?.[resolved.catalogModelId] - : undefined; - const catalog = limitOverrides ? { ...resolved, limitOverrides } : resolved; - const family = deploymentFamily(entry); - const generations = [entry.litellm_params?.model, entry.model_info?.base_model] - .map((id) => wireString(id)?.trim()) - .filter((id): id is string => Boolean(id)) - .map(semanticModel) - .filter((model): model is SemanticModel => model !== undefined); - const model = new Set(generations).size === 1 && family !== "conflicting" ? generations[0] : undefined; - return { - ...catalog, - ...(options.allowMessages === false || - (messagesAwaitProxyVersion(entry) && !proxyVersionAtLeast(options.proxyVersion, AZURE_AI_MESSAGES_FLOOR)) - ? { messagesCompat: undefined, messagesStrictTools: undefined } - : {}), - ...(family ? { semanticFamily: family } : {}), - ...(model ? { semanticModel: model } : {}), - }; - }); + const reduced = reduceModelGroup( + entries, + (entry) => { + const resolved = resolveModelInfoCatalog(entry, publicCatalog); + const limitOverrides = + resolved?.piProvider && resolved.catalogModelId + ? options.modelOverrides?.[resolved.piProvider]?.[resolved.catalogModelId] + : undefined; + const catalog = limitOverrides ? { ...resolved, limitOverrides } : resolved; + const family = deploymentFamily(entry); + const generations = [entry.litellm_params?.model, entry.model_info?.base_model] + .map((id) => wireString(id)?.trim()) + .filter((id): id is string => Boolean(id)) + .map(semanticModel) + .filter((model): model is SemanticModel => model !== undefined); + const model = new Set(generations).size === 1 && family !== "conflicting" ? generations[0] : undefined; + return { + ...catalog, + ...(options.allowMessages === false || + (messagesAwaitProxyVersion(entry) && !proxyVersionAtLeast(options.proxyVersion, AZURE_AI_MESSAGES_FLOOR)) + ? { messagesCompat: undefined, messagesStrictTools: undefined } + : {}), + ...(family ? { semanticFamily: family } : {}), + ...(model ? { semanticModel: model } : {}), + }; + }, + options.proxyVersion, + ); if (!reduced) return undefined; if (reduced.contextWindowDefaulted) options.defaultedContextRoutes?.add(reduced.id); if (reduced.catalogAuthorityAmbiguous) options.ambiguousRoutes?.push(reduced.id); @@ -822,9 +866,15 @@ function mapFromModelInfoGroup( ? { ...reduced.messagesCompat, ...(reduced.messagesStrictTools !== undefined ? { supportsStrictTools: reduced.messagesStrictTools } : {}), - // Managed effort adds thinking.block_binding, which hosted Claude endpoints (Azure among them) reject. - // LiteLLM reports no per-route support, so only a group routed solely through Anthropic may keep it. - ...(entries.every((entry) => routesOnlyThrough(entry, ANTHROPIC_ROUTES)) + // Managed effort adds thinking.block_binding, which hosted Claude endpoints reject unless the proxy + // forwards its beta header. LiteLLM reports no per-route support, so a group keeps it only where every + // deployment routes solely through Anthropic, or through azure_ai on a proxy that forwards the beta. + ...(entries.every( + (entry) => + routesOnlyThrough(entry, ANTHROPIC_ROUTES) || + (routesOnlyThrough(entry, AZURE_AI_ROUTES) && + proxyVersionAtLeast(options.proxyVersion, AZURE_AI_THINKING_BINDING_FLOOR)), + ) ? {} : { supportsMidConvoEffort: false }), } @@ -892,7 +942,7 @@ function mapFromModelInfoGroup( ? { litellmResponsesReasoningControl: true as const } : {}), ...(families.size === 1 && family ? { litellmBackendFamily: family } : {}), - ...(families.size === 1 && family === "claude" && relaysAnthropicCacheMarkers + ...(families.size === 1 && family === "claude" && relaysAnthropicCacheMarkers && !deniesPromptCache(entries) ? { promptCache: { ...CLAUDE_PROMPT_CACHE } } : {}), ...(api === "openai-responses" && @@ -901,7 +951,8 @@ function mapFromModelInfoGroup( identity?.family === "openai" && isGpt56OrNewerModel(identity.modelId) && routesOnlyThrough(entries[index]!, OPENAI_PROMPT_CACHE_ROUTES), - ) + ) && + !deniesPromptCache(entries) ? { promptCache: { ...OPENAI_PROMPT_CACHE } } : {}), ...(modelPolicy ? { litellmPolicy: modelPolicy } : {}), @@ -912,15 +963,29 @@ function mapFromModelInfoGroup( // An evidence-free fallback entry has no deployment or adapter evidence. Its route name // authorizes nothing; the Pi catalog entry for its id supplies its protocol and presentation // metadata, while an unknown id stays on Chat Completions until /model/info can be read. -// Whether a group that will be published has its transport decided by the proxy -// version. Mapping without collectors leaves no diagnostic behind, and whether a -// group is published does not depend on the version. -function publishesVersionGatedTransport( +// Whether a group that will be published has its transport or its off thinking level decided by +// the proxy version. Mapping without collectors leaves no diagnostic behind, and whether a group +// is published does not depend on the version. +function publishesVersionGatedBehavior( group: readonly ModelInfoEntry[], publicCatalog: PublicCatalog | undefined, allowMessages = true, ): boolean { if (group.some(transportAwaitsProxyVersion)) return mapFromModelInfoGroup(group, publicCatalog) !== undefined; + // A think-by-default route awaits the version only where the off level actually differs across the + // floor. A sibling that always thinks, or a declared effort list without `none`, denies the level at + // every version, and probing for it would add a failed request and a warning that explains nothing. + if (group.some(reasoningAwaitsProxyVersion)) { + const below = mapFromModelInfoGroup(group, publicCatalog); + if ( + below !== undefined && + below.thinkingLevelMap?.off !== + mapFromModelInfoGroup(group, publicCatalog, { proxyVersion: THINKING_DISABLE_FLOOR_VERSION })?.thinkingLevelMap + ?.off + ) { + return true; + } + } // Messages awaits the version only where a proxy at the floor would get it: an // endpoint list or a sibling deployment can keep the group on Chat regardless. return ( @@ -1025,7 +1090,7 @@ async function discoverFromHealth( const versionGatedRoutes = [...groups] .filter(([, group]) => // Health discovery never selects Messages, so only Responses can await the version. - publishesVersionGatedTransport( + publishesVersionGatedBehavior( group.map(({ entry }) => entry), publicCatalog, false, @@ -1325,7 +1390,7 @@ export async function discoverModels( return probeProxyVersion(base, apiKey, options); }; const versionGatedRoutes = [...groups] - .filter(([route, group]) => !route.includes("*") && publishesVersionGatedTransport(group, publicCatalog)) + .filter(([route, group]) => !route.includes("*") && publishesVersionGatedBehavior(group, publicCatalog)) .map(([route]) => route); let proxyVersion = versionGatedRoutes.length > 0 ? await readProxyVersion() : undefined; const ambiguousRoutes: string[] = []; @@ -1393,7 +1458,7 @@ export async function discoverModels( const id = wireString(entry.id); if (!id || id.includes("*")) return []; const parents = selectedWildcardRows(id, wildcardRows, publishedWildcardIds); - return parents !== undefined && publishesVersionGatedTransport(parents, publicCatalog) ? [id] : []; + return parents !== undefined && publishesVersionGatedBehavior(parents, publicCatalog) ? [id] : []; }); versionGatedRoutes.push(...versionGatedExpansions); if (!proxyVersionRead && versionGatedExpansions.length > 0) { diff --git a/src/model-groups.ts b/src/model-groups.ts index 8348219e..e3abe536 100644 --- a/src/model-groups.ts +++ b/src/model-groups.ts @@ -1,8 +1,20 @@ import type { Api, Model } from "@earendil-works/pi-ai"; import { routesOnlyThrough } from "./backend-identity.js"; +import { type ProxyVersion, type ProxyVersionFloor, proxyVersionAtLeast } from "./proxy-version.js"; import { intersectThinkingLevelMaps, THINKING_LEVEL_DEFINITIONS } from "./thinking-levels.js"; import type { DiscoveredModel, ModelInfoEntry } from "./types.js"; +// Until LiteLLM 1.110.0, `reasoning_effort: "none"` sent nothing to a backend whose thinking is +// on by default, so the model kept thinking (and billing it) with no way to stop it through the +// effort carrier. 1.110.0 translates that level to `thinking: {"type": "disabled"}`. +const THINKING_DISABLE_FLOOR: ProxyVersionFloor = [1, 110, 0]; +export const THINKING_DISABLE_FLOOR_VERSION: ProxyVersion = { + major: THINKING_DISABLE_FLOOR[0], + minor: THINKING_DISABLE_FLOOR[1], + patch: THINKING_DISABLE_FLOOR[2], + prerelease: false, +}; + const BUILTIN_CONTEXT_WINDOW = 128_000; /** @@ -123,7 +135,7 @@ export function wireString(value: unknown): string | undefined { // Unreadable capability flags are withheld rather than coerced. In particular, // string values such as `"false"` must not become truthy capability evidence. -function wireBoolean(value: unknown): boolean | undefined { +export function wireBoolean(value: unknown): boolean | undefined { return typeof value === "boolean" ? value : undefined; } @@ -219,7 +231,23 @@ function normalizeEffort(level: string): (typeof EXTENDED_LEVELS)[number] | unde // LiteLLM reads a declared `reasoning_effort_levels` list whole, ahead of the // per-level flags, because flags cannot state a set such as low/high/max: medium // has no opt-out. A declared list therefore answers every level for its deployment. -function reportedLevel(entry: ModelInfoEntry, level: (typeof EXTENDED_LEVELS)[number]): boolean | undefined { +function reportedLevel( + entry: ModelInfoEntry, + level: (typeof EXTENDED_LEVELS)[number], + proxyVersion?: ProxyVersion, +): boolean | undefined { + // A backend that always thinks cannot honor Pi's off level, and one that thinks by default needs + // a proxy that forwards the disable. Both deny the level whatever carrier the route accepts, so + // they are read ahead of the declared list: an accepted `none` still would not stop the thinking. + if (level === "off") { + if (wireBoolean(entry.model_info?.thinking_always_on) === true) return false; + if ( + wireBoolean(entry.model_info?.thinking_on_by_default) === true && + !proxyVersionAtLeast(proxyVersion, THINKING_DISABLE_FLOOR) + ) { + return false; + } + } const declared: unknown = entry.model_info?.reasoning_effort_levels; if (Array.isArray(declared)) { return declared.some((effort) => typeof effort === "string" && normalizeEffort(effort) === level); @@ -235,6 +263,7 @@ function reasoningLevelMap( entries: readonly ModelInfoEntry[], catalogEfforts: readonly (readonly string[] | undefined)[], catalogMaps: readonly DiscoveredModel["thinkingLevelMap"][], + proxyVersion?: ProxyVersion, ): DiscoveredModel["thinkingLevelMap"] { const publicSets = catalogEfforts .filter((levels): levels is readonly string[] => levels !== undefined) @@ -257,14 +286,14 @@ function reasoningLevelMap( } for (const level of EXTENDED_LEVELS) { - const reported = entries.map((entry) => reportedLevel(entry, level)); + const reported = entries.map((entry) => reportedLevel(entry, level, proxyVersion)); if (reported.some((value) => value === false)) map[level] = null; else if (reported.length > 0 && reported.every((value) => value === true)) { map[level] = level === "off" ? "none" : level; } } for (const level of ["xhigh", "max"] as const) { - if (!entries.every((entry) => reportedLevel(entry, level) === true)) map[level] = null; + if (!entries.every((entry) => reportedLevel(entry, level, proxyVersion) === true)) map[level] = null; } return map; } @@ -809,6 +838,7 @@ function kimiDeploymentEvidence(entry: ModelInfoEntry): { export function reduceModelGroup( entries: readonly ModelInfoEntry[], resolveCatalog: CatalogResolver, + proxyVersion?: ProxyVersion, ): ReducedModelGroup | undefined { const { candidates, candidateModes, routable: deployments } = canonicalModelInfoDeployments(entries); if (candidates.length === 0) return undefined; @@ -940,16 +970,19 @@ export function reduceModelGroup( deployments.length > 0 && deployments.every((entry) => acceptedParams(entry).has("reasoning_effort") || optsIntoEffortCarrier(entry))); const publicEfforts = catalogAuthority.map((catalog) => catalog?.effortLevels); - const evidenceLevelMap = reasoningLevelMap(deployments, publicEfforts, [ - intersectThinkingLevelMaps(catalogAuthority.map((catalog) => catalog?.thinkingLevelMap)), - ]); + const evidenceLevelMap = reasoningLevelMap( + deployments, + publicEfforts, + [intersectThinkingLevelMaps(catalogAuthority.map((catalog) => catalog?.thinkingLevelMap))], + proxyVersion, + ); let thinkingLevelMap = reasoning && acceptsResponsesReasoningControl ? evidenceLevelMap : undefined; if (api === "anthropic-messages") { thinkingLevelMap = intersectThinkingLevelMaps(catalogs.map((catalog) => catalog?.messagesThinkingLevelMap)); // Native serializer restrictions apply even when catalog pricing is withheld. // Router flags can also deny Pi's implicit default levels, never add a level. for (const level of EXTENDED_LEVELS) { - const reported = deployments.map((entry) => reportedLevel(entry, level)); + const reported = deployments.map((entry) => reportedLevel(entry, level, proxyVersion)); if ( reported.some((value) => value === false) || ((level === "xhigh" || level === "max") && @@ -984,7 +1017,7 @@ export function reduceModelGroup( const semanticMap = semanticReasoningPolicy.thinkingLevelMap; const hasEvidenceLevels = Object.values(evidenceLevelMap ?? {}).some((level) => level !== null); const semanticBinary = semanticReasoningPolicy.compat?.supportsReasoningEffort === false && !hasEvidenceLevels; - const explicitOffDenial = deployments.some((entry) => reportedLevel(entry, "off") === false); + const explicitOffDenial = deployments.some((entry) => reportedLevel(entry, "off", proxyVersion) === false); const reasoningPolicy = semanticMap ? { ...semanticReasoningPolicy, diff --git a/src/types.ts b/src/types.ts index 7a78eb04..5b14682f 100644 --- a/src/types.ts +++ b/src/types.ts @@ -107,6 +107,9 @@ export interface ModelInfoEntry { mode?: string | null; base_model?: string; litellm_provider?: string; + // The provider whose cost-map rows price this deployment (LiteLLM 1.109.0+). + // Operator-declared, and LiteLLM itself falls back to `custom_llm_provider`. + pricing_provider?: string; supported_endpoints?: string[] | null; supported_openai_params?: string[]; input_cost_per_token?: number; @@ -125,6 +128,11 @@ export interface ModelInfoEntry { supports_high_reasoning_effort?: boolean; supports_xhigh_reasoning_effort?: boolean; supports_max_reasoning_effort?: boolean; + // Thinking this backend cannot turn off at all, whatever carrier the route accepts. + thinking_always_on?: boolean; + // Thinking left on unless a request disables it explicitly (Claude 5 rows). + thinking_on_by_default?: boolean; + supports_prompt_caching?: boolean; supports_vision?: boolean; }; } diff --git a/tests/backend-identity.test.ts b/tests/backend-identity.test.ts index b67ee306..8e42c128 100644 --- a/tests/backend-identity.test.ts +++ b/tests/backend-identity.test.ts @@ -290,7 +290,7 @@ describe("resolveBackendIdentity", () => { for (const id of ["azure/kimi-k3", "deepseek-v4", "glm-5"]) { expect(isOpenAIBackend(id)).toBe(false); } - expect(LITELLM_DISCOVERY_VERSION).toBe(16); + expect(LITELLM_DISCOVERY_VERSION).toBe(17); }); it("takes the family from the model id, never from an adapter prefix", () => { @@ -332,6 +332,37 @@ describe("resolveBackendIdentity", () => { }); describe("resolveCatalogProvider", () => { + it("takes a declared pricing_provider over every inference, including a conflicting one", () => { + // LiteLLM 1.109.0+: the operator names the catalog that prices the deployment. A deployment id + // equal to another provider's catalog key is exactly the conflict this settles. + expect( + resolveCatalogProvider({ + model_info: { base_model: "zai-org/GLM-5.2", litellm_provider: "openai", pricing_provider: "baseten" }, + litellm_params: { model: "openai/zai-org/GLM-5.2", custom_llm_provider: "openai" }, + }), + ).toBe("baseten"); + // Trimmed and lowercased like the other wire providers, and an unset one changes nothing. + expect(resolveCatalogProvider({ model_info: { base_model: "gpt-5.2", pricing_provider: " BaseTen " } })).toBe( + "baseten", + ); + expect( + resolveCatalogProvider({ + model_info: { base_model: "anthropic/claude-sonnet-5-5", pricing_provider: " " }, + }), + ).toBe("anthropic"); + }); + + it("keeps pricing_provider out of routing evidence", () => { + // It prices a deployment; it never says which API the request goes to, so the strict-tool, + // Messages and prompt-cache gates must not see it. + const row = { + model_info: { base_model: "claude-sonnet-5-5", pricing_provider: "anthropic" }, + litellm_params: { model: "bedrock/claude-sonnet-5-5", custom_llm_provider: "bedrock" }, + }; + expect(resolveCatalogProvider(row)).toBe("anthropic"); + expect(routesOnlyThrough(row, new Set(["anthropic"]))).toBe(false); + }); + it.each(["azure", "azure_ai", "custom_openai", "openai", "openai_like", "text-completion-openai"])( "prefers the configured adapter over generic %s metadata", (reported) => { diff --git a/tests/discover.test.ts b/tests/discover.test.ts index 32b433b7..10f54497 100644 --- a/tests/discover.test.ts +++ b/tests/discover.test.ts @@ -11,6 +11,7 @@ vi.mock("@earendil-works/pi-coding-agent", () => ({ getAgentDir: () => agentDir, })); +import { LITELLM_DISCOVERY_VERSION } from "../src/backend-identity.js"; import { buildCompat, discoverModels, @@ -1220,7 +1221,7 @@ describe("discoverModels via /model/info", () => { id: "gpt-production", api: "openai-completions", litellmBackendFamily: "openai", - litellmDiscoveryVersion: 16, + litellmDiscoveryVersion: LITELLM_DISCOVERY_VERSION, }); }); @@ -1324,6 +1325,61 @@ describe("discoverModels via /model/info", () => { }); }); + it("prices a conflicting identity from its declared pricing_provider", async () => { + // base_model names Anthropic while the route is declared through Bedrock, so the identity is + // withheld and nothing could price it. The operator's pricing_provider settles the catalog, which + // is what the earlier unit test on resolveCatalogProvider alone never proved reachable from here. + const row = (pricingProvider?: string) => ({ + model_name: "team-claude", + litellm_params: { model: "bedrock/claude-sonnet-5-5", custom_llm_provider: "bedrock" }, + model_info: { + mode: "chat", + base_model: "anthropic/claude-sonnet-5-5", + ...(pricingProvider ? { pricing_provider: pricingProvider } : {}), + }, + }); + const discoverRow = async (pricingProvider?: string) => { + vi.restoreAllMocks(); + mockEndpoints({ "/model/info": () => jsonResponse(200, { data: [row(pricingProvider)] }) }); + return (await discoverModels("https://litellm.example.com", "sk-test", { modelsDev: false })).models[0]; + }; + + const priced = await discoverRow("anthropic"); + const unpriced = await discoverRow(); + + expect(priced).toMatchObject({ contextWindow: 1_000_000, cost: { input: 2, output: 10 } }); + // Without the declaration the conflict still withholds everything, so the window is the default. + expect(unpriced?.contextWindow).toBe(128_000); + expect(unpriced?.cost).toEqual({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }); + }); + + it("denies the off level for a backend whose thinking is always on", async () => { + vi.spyOn(globalThis, "fetch").mockResolvedValue( + jsonResponse(200, { + data: [ + { + model_name: "custom/always-thinking", + litellm_params: { allowed_openai_params: ["reasoning_effort"] }, + model_info: { + mode: "chat", + supports_reasoning: true, + // An accepted `none` cannot stop thinking the backend always does, and no proxy + // release can either, so this needs no version gate. + supports_none_reasoning_effort: true, + thinking_always_on: true, + supports_max_reasoning_effort: true, + }, + }, + ], + }), + ); + + const result = await discoverModels("https://litellm.example.com", "sk-test", { modelsDev: false }); + + expect(result.models[0]?.thinkingLevelMap?.off).toBeNull(); + expect(result.models[0]?.thinkingLevelMap?.max).toBe("max"); + }); + it("maps router medium and high effort flags for a singleton", async () => { vi.spyOn(globalThis, "fetch").mockResolvedValue( jsonResponse(200, { @@ -5604,7 +5660,7 @@ describe("discoverModels wildcard expansion via /v1/models", () => { id: "team/claude-sonnet-4-6", name: "Claude Sonnet 4.6", api: "openai-completions", - litellmDiscoveryVersion: 16, + litellmDiscoveryVersion: LITELLM_DISCOVERY_VERSION, reasoning: false, input: ["text"], contextWindow: 40_000, @@ -6196,6 +6252,115 @@ describe("discoverModels proxy version gate", () => { }); }); + // LiteLLM 1.109.0 forwards the thinking-binding-controls beta to Foundry, which Foundry needs for the + // thinking.block_binding that managed effort sends; before that it answered 400. + it.each([ + ["1.109.0", undefined], + ["1.110.4", undefined], + ["1.108.21", false], + ["1.109.0-rc.1", false], + ["1.106.4", false], + ])("decides azure_ai Claude mid-conversation effort on a proxy reporting %s", async (version, denied) => { + mockEndpoints({ + "/model/info": () => jsonResponse(200, { data: [azureAiClaude] }), + [VERSION_PROBE]: versionReply(version), + }); + + const { models } = await discoverModels("https://litellm.example.com", "sk-test", { modelsDev: false }); + + expect(models[0]?.api).toBe("anthropic-messages"); + expect((models[0]?.compat as { supportsMidConvoEffort?: boolean })?.supportsMidConvoEffort).toBe(denied); + }); + + it("keeps mid-conversation effort denied for a hosted Claude a pricing label calls azure_ai", async () => { + // `model_info.litellm_provider` is a cost-map lookup of base_model, not routing. A Bedrock-routed + // deployment priced through an Azure row reaches Bedrock, where the binding beta means nothing, so + // only declared azure_ai routing may take the 1.109.0 grant. + const bedrockPricedAsAzure = { + model_name: "claude-opus-5-5", + litellm_params: { model: "bedrock/claude-opus-5-5", custom_llm_provider: "bedrock" }, + model_info: { mode: "chat", litellm_provider: "azure_ai", supports_reasoning: true }, + }; + mockEndpoints({ + "/model/info": () => jsonResponse(200, { data: [bedrockPricedAsAzure] }), + [VERSION_PROBE]: versionReply("1.111.1"), + }); + + const { models } = await discoverModels("https://litellm.example.com", "sk-test", { modelsDev: false }); + + // Asserted unconditionally: a guarded check would pass silently if the route stopped reaching Messages. + expect(models[0]?.api).toBe("anthropic-messages"); + expect((models[0]?.compat as { supportsMidConvoEffort?: boolean })?.supportsMidConvoEffort).toBe(false); + }); + + // Until 1.110.0 `reasoning_effort: "none"` sent nothing to a think-by-default backend, so it kept + // thinking and billing it; the level cannot be offered against a proxy that would drop it. + const thinkByDefault = { + model_name: "opus-5", + litellm_params: { + model: "bedrock/claude-opus-5", + custom_llm_provider: "bedrock", + allowed_openai_params: ["reasoning_effort"], + }, + model_info: { + mode: "chat", + supports_reasoning: true, + supports_none_reasoning_effort: true, + thinking_on_by_default: true, + }, + }; + + it.each([ + ["1.110.0", "none"], + ["1.111.1", "none"], + ["1.109.5", null], + ["1.110.0-rc.1", null], + [undefined, null], + ])("decides the off level of a think-by-default backend on a proxy reporting %s", async (version, off) => { + mockEndpoints({ + "/model/info": () => jsonResponse(200, { data: [thinkByDefault] }), + [VERSION_PROBE]: versionReply(version), + }); + + const { models } = await discoverModels("https://litellm.example.com", "sk-test", { modelsDev: false }); + + expect(models[0]?.thinkingLevelMap?.off).toBe(off); + }); + + it("asks for the version for a think-by-default route that needs no transport gate", async () => { + const urls = recordUrls({ + "/model/info": () => jsonResponse(200, { data: [thinkByDefault] }), + [VERSION_PROBE]: versionReply("1.110.0"), + }); + + await discoverModels("https://litellm.example.com", "sk-test", { modelsDev: false }); + + expect(urls.filter((url) => url.endsWith(VERSION_PROBE))).toHaveLength(1); + }); + + it("does not ask for the version when a sibling denies the off level at every version", async () => { + // A deployment that always thinks denies off whatever the proxy is, so the group's published off + // level cannot depend on the version and the probe would only add a failed request and a warning. + const alwaysOn = { + model_name: "opus-5", + litellm_params: { + model: "bedrock/claude-opus-5", + custom_llm_provider: "bedrock", + allowed_openai_params: ["reasoning_effort"], + }, + model_info: { mode: "chat", supports_reasoning: true, thinking_always_on: true }, + }; + const urls = recordUrls({ + "/model/info": () => jsonResponse(200, { data: [thinkByDefault, alwaysOn] }), + [VERSION_PROBE]: versionReply("1.110.0"), + }); + + const { models } = await discoverModels("https://litellm.example.com", "sk-test", { modelsDev: false }); + + expect(urls.filter((url) => url.endsWith(VERSION_PROBE))).toHaveLength(0); + expect(models[0]?.thinkingLevelMap?.off).toBeNull(); + }); + it.each([ ["1.106.4", "anthropic-messages"], [undefined, "openai-completions"], @@ -6290,8 +6455,8 @@ describe("discoverModels proxy version gate", () => { await discoverModels("https://litellm.example.com", "sk-test", options); expect(diagnostics).toEqual([ - "LiteLLM discovery: the proxy reported no readable version (x-litellm-version header); 2 azure_ai route(s) " + - `whose transport depends on it stay on Chat Completions: claude-${suffix}, astra-${suffix}`, + "LiteLLM discovery: the proxy reported no readable version (x-litellm-version header); 2 route(s) " + + `whose transport or off thinking level depends on it keep the conservative fallback: claude-${suffix}, astra-${suffix}`, ]); }); @@ -7941,6 +8106,24 @@ describe("prompt cache lifetimes", () => { expect(model).toMatchObject({ api: "anthropic-messages", promptCache: { short: 300, long: 3600 } }); }); + it("declares none when a deployment reports it bills no prompt cache", async () => { + // A relay can host a Claude generation without prompt caching (`kyma/claude-fable-5`); the + // family's documented lifetimes do not apply to a deployment LiteLLM says has none. + const [messages] = await discoverRows([claudeRow("claude", { supports_prompt_caching: false })]); + const [chat] = await discoverRows([ + claudeRow("claude-chat", { supported_endpoints: ["/v1/chat/completions"], supports_prompt_caching: false }), + ]); + + expect(messages?.api).toBe("anthropic-messages"); + expect(messages).not.toHaveProperty("promptCache"); + expect(chat).not.toHaveProperty("promptCache"); + // An absent flag is not a denial. + expect(await discoverRows([claudeRow("claude")]).then(([m]) => m?.promptCache)).toEqual({ + short: 300, + long: 3600, + }); + }); + it("declares lifetimes for a Claude-backed Chat Completions route", async () => { const [model] = await discoverRows([claudeRow("claude-chat", { supported_endpoints: ["/v1/chat/completions"] })]); @@ -8030,6 +8213,13 @@ describe("prompt cache lifetimes", () => { } }); + it("declares none for GPT-5.6 and later that reports it bills no prompt cache", async () => { + const [model] = await discoverRows([gptRow("sol", "openai/gpt-6.1-sol", { supports_prompt_caching: false })]); + + expect(model?.api).toBe("openai-responses"); + expect(model).not.toHaveProperty("promptCache"); + }); + it("declares none for GPT-5.6 and later on Chat Completions", async () => { const [model] = await discoverRows([ gptRow("sol-chat", "openai/gpt-6.1-sol", { mode: "chat", supported_endpoints: ["/v1/chat/completions"] }), diff --git a/tests/provider.test.ts b/tests/provider.test.ts index 92b26b20..c1246177 100644 --- a/tests/provider.test.ts +++ b/tests/provider.test.ts @@ -130,7 +130,7 @@ describe("createLiteLLMProvider", () => { it("restores current-version stored models offline without discovery", async () => { const discover = vi.fn(async () => discovered("fresh")); const value = controller({ discover }); - const stored = { ...native("stored"), litellmDiscoveryVersion: 16 as const }; + const stored = { ...native("stored"), litellmDiscoveryVersion: LITELLM_DISCOVERY_VERSION }; await value.refreshModels?.(context([stored], false)); @@ -153,7 +153,7 @@ describe("createLiteLLMProvider", () => { ...discovered("claude-fable-5-1").models[0], api: "anthropic-messages", compat: { forceAdaptiveThinking: true }, - litellmDiscoveryVersion: 16, + litellmDiscoveryVersion: LITELLM_DISCOVERY_VERSION, }, ], }; @@ -167,7 +167,7 @@ describe("createLiteLLMProvider", () => { await value.refreshModels?.(context([stale], true)); expect(discover).toHaveBeenCalledOnce(); expect(value.getModels()[0]).toMatchObject({ - litellmDiscoveryVersion: 16, + litellmDiscoveryVersion: LITELLM_DISCOVERY_VERSION, compat: { forceAdaptiveThinking: true }, }); }); @@ -178,7 +178,7 @@ describe("createLiteLLMProvider", () => { ...discovered("claude-sonnet-5").models[0], api: "anthropic-messages", compat: { supportsStrictTools: true }, - litellmDiscoveryVersion: 16, + litellmDiscoveryVersion: LITELLM_DISCOVERY_VERSION, }, ]); const stale = { @@ -232,7 +232,7 @@ describe("createLiteLLMProvider", () => { it("still requires a network refresh for legacy entries startup discovery did not replace", async () => { const [seed] = toNativeModels("litellm", "https://proxy.example/v1", [ - { ...discovered("claude-sonnet-5").models[0], litellmDiscoveryVersion: 16 }, + { ...discovered("claude-sonnet-5").models[0], litellmDiscoveryVersion: LITELLM_DISCOVERY_VERSION }, ]); const seededLegacy = { ...seed, litellmDiscoveryVersion: 2 as const }; const unseededLegacy = native("stored"); @@ -277,7 +277,7 @@ describe("createLiteLLMProvider", () => { name: "opus-5 (no metadata)", reasoning: false, maxTokens: 16_384, - litellmDiscoveryVersion: 16 as const, + litellmDiscoveryVersion: LITELLM_DISCOVERY_VERSION, }; const value = controller({ discover }); @@ -292,7 +292,7 @@ describe("createLiteLLMProvider", () => { it("ignores non-chat entries in Pi's model store", async () => { const discover = vi.fn(async () => discovered("fresh")); - const current = (id: string) => ({ ...native(id), litellmDiscoveryVersion: 16 as const }); + const current = (id: string) => ({ ...native(id), litellmDiscoveryVersion: LITELLM_DISCOVERY_VERSION }); const untyped = current("untyped-chat"); const typed = { ...current("typed-chat"), type: "chat" as const }; const image = { ...current("image"), type: "image" as const }; @@ -354,7 +354,7 @@ describe("createLiteLLMProvider", () => { name: "opus-5 (no metadata)", reasoning: false, maxTokens: 16_384, - litellmDiscoveryVersion: 16, + litellmDiscoveryVersion: LITELLM_DISCOVERY_VERSION, } as LiteLLMModel, ], false, @@ -388,7 +388,7 @@ describe("createLiteLLMProvider", () => { name: "openai/gpt-5.5 (no metadata)", reasoning: false, maxTokens: 16_384, - litellmDiscoveryVersion: 16, + litellmDiscoveryVersion: LITELLM_DISCOVERY_VERSION, compat: undefined, } as LiteLLMModel, ], @@ -419,7 +419,7 @@ describe("createLiteLLMProvider", () => { name: "openai/gpt-5.5 (no metadata)", reasoning: false, maxTokens: 16_384, - litellmDiscoveryVersion: 16, + litellmDiscoveryVersion: LITELLM_DISCOVERY_VERSION, } as LiteLLMModel, ], false, @@ -446,7 +446,7 @@ describe("createLiteLLMProvider", () => { cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 128_000, maxTokens: 16_384, - litellmDiscoveryVersion: 16, + litellmDiscoveryVersion: LITELLM_DISCOVERY_VERSION, }; const partialCached: Model[] = [ { ...legacyFallback, reasoning: true },