chore(ollama): close the remaining increment-5 items

- DetectModelPlatform: document why ollama_cloud intentionally has no branch
  (model-name-only input, resold families collide with existing prefixes such as
  gpt- -> openai; adding one would silently misroute) and pin current behaviour
  with table-driven tests
- match models.dev provider by host for ollama.com using the measured registry id
  "ollama-cloud"
- include ollama_cloud (and opencode_go) in the codex model catalog platform list
- let reverse-proxy ollama_cloud accounts pick the anthropic auth scheme via extra
  (official host still forces Bearer)
- use the adaptive chat-protocol base url in the upstream billing probe
- add ollama_cloud to the remaining admin UI badges and spec expectations
This commit is contained in:
alfadb committed 2026-10-08 15:24:05 +08:00
1 parent c6125d8d01
commit 340ff7ffad
12 files changed
+196 -3

No files matched your search

@@ -16,12 +16,15 @@ const (
// Anthropic API-key accounts. Missing or invalid values keep the historical
// x-api-key behavior. CN providers using their native Anthropic endpoints
// (api_protocol=anthropic) share the same override knob — Kimi/DeepSeek default
// to x-api-key, Zhipu can opt into Authorization: Bearer.
// to x-api-key, Zhipu can opt into Authorization: Bearer. Ollama Cloud accounts
// may read the knob too: it only matters for relay bases (the official
// ollama.com base is forced to Bearer by host in setAnthropicAPIKeyAuthHeader
// regardless of this value).
func (a *Account) GetAnthropicAPIKeyAuthScheme() string {
if a == nil || a.Type != AccountTypeAPIKey {
return AnthropicAPIKeyAuthSchemeXAPIKey
}
if a.Platform != PlatformAnthropic && !a.IsCNProvider() {
if a.Platform != PlatformAnthropic && !a.IsCNProvider() && a.Platform != PlatformOllamaCloud {
return AnthropicAPIKeyAuthSchemeXAPIKey
}
@@ -142,6 +142,60 @@ func TestSetAnthropicAPIKeyAuthHeader_OllamaCloudForcesBearer(t *testing.T) {
}
}
// TestGetAnthropicAPIKeyAuthScheme_OllamaCloudRelayOverride:C34 残余——平台化
// 的 ollama_cloud 账号挂反代 base 时可经 extra 显式选 Bearer;缺省仍 x-api-key;
// 官方 ollama.com base 的强制 Bearer 不经本函数、不受影响(host 分支先行)。
func TestGetAnthropicAPIKeyAuthScheme_OllamaCloudRelayOverride(t *testing.T) {
tests := []struct {
name string
base string
extra map[string]any
want string
}{
{
name: "反代 base + extra 显式 Bearer → Bearer",
base: "https://relay.example.com",
extra: map[string]any{anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeAuthorizationBearer},
want: AnthropicAPIKeyAuthSchemeAuthorizationBearer,
},
{
name: "反代 base 无 extra → 保持 x-api-key",
base: "https://relay.example.com",
want: AnthropicAPIKeyAuthSchemeXAPIKey,
},
{
name: "官方 ollama.com base 也读 extra(强制 Bearer 由 host 分支保证)",
base: "https://ollama.com",
extra: map[string]any{anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeAuthorizationBearer},
want: AnthropicAPIKeyAuthSchemeAuthorizationBearer,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
account := newOllamaCloudAnthropicAuthAccount(tt.base, tt.extra)
account.Platform = PlatformOllamaCloud
require.Equal(t, tt.want, account.GetAnthropicAPIKeyAuthScheme())
})
}
// 官方 base 恒 Bearer 不受 extra 影响:ollama_cloud 账号 + 显式 x_api_key
// extra,host 分支仍强制 Bearer。
account := newOllamaCloudAnthropicAuthAccount("https://ollama.com", map[string]any{
anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeXAPIKey,
})
account.Platform = PlatformOllamaCloud
header := http.Header{}
setAnthropicAPIKeyAuthHeader(header, account, "ollama-cloud-key", "https://ollama.com")
require.Equal(t, "Bearer ollama-cloud-key", header.Get("Authorization"))
require.Empty(t, header.Get("x-api-key"))
// Anthropic 平台回归:显式 x_api_key extra → x-api-key 不变。
anthropicAccount := newOllamaCloudAnthropicAuthAccount("https://api.anthropic.com", map[string]any{
anthropicAPIKeyAuthSchemeExtraKey: AnthropicAPIKeyAuthSchemeXAPIKey,
})
require.Equal(t, AnthropicAPIKeyAuthSchemeXAPIKey, anthropicAccount.GetAnthropicAPIKeyAuthScheme())
}
// TestSetAnthropicAPIKeyAuthHeader_CNAdaptiveBaseURLResolution:adaptive 账号经
// GetCNProtocolBaseURL(anthropic) / GetAnthropicProtocolBaseURL 选出的分协议地址
// 才是判定依据,Chat Completions 地址(GetOpenAIBaseURL 选到的 CC base)不参与。
@@ -149,6 +149,12 @@ func CompositeRouteSourceFromContext(ctx context.Context) (string, bool) {
// DetectModelPlatform maps common public model IDs to the concrete provider
// platform used by sub2api. It intentionally returns false for ambiguous model
// names so composite groups fail closed instead of guessing.
//
// ollama_cloud(与 opencode_go 同理)刻意不在本表:本函数只有模型名入参、没有
// host 入参,而 ollama 转售的模型家族(gpt-oss / kimi-k2 / glm / deepseek /
// qwen)与上方前缀规则直接冲突(如 gpt- 已映射 openai)——在这里加 ollama
// 分支等于按名字前缀静默错投。ollama_cloud 进入 composite 只走显式 route 与
// ownership resolver(账号目录),不要给本函数加 ollama 分支。
func DetectModelPlatform(model string) (string, bool) {
normalized := strings.ToLower(strings.TrimSpace(model))
if normalized == "" {
@@ -201,6 +201,41 @@ func TestDetectModelPlatform(t *testing.T) {
{name: "abab unrelated namespace", model: "abab-other", ok: false},
{name: "unknown k3 alias", model: "k3-preview", ok: false},
{name: "unknown", model: "llama-4-maverick", ok: false},
// --- 行为钉(设计决策,不是漏配)---
// DetectModelPlatform 刻意不加 ollama 分支(无 host 入参,ollama 转售
// gpt-oss/kimi-k2/glm/deepseek 家族与上方前缀规则直接冲突,按字面加
// 分支 = 静默错投)。以下用例钉住 ollama_cloud 默认目录
// (DefaultOllamaCloudModelIDs)中的典型模型名的当前返回:将来有人
// 「顺手加 ollama 分支」时这些用例会红灯,提示先回到该决策。
{
name: "ollama-cloud resale gpt-oss pins to openai (intentional: no ollama branch)",
model: "gpt-oss:120b",
platform: PlatformOpenAI,
ok: true,
},
{
name: "ollama-cloud resale glm pins to zhipu (intentional: no ollama branch)",
model: "glm-5.3",
platform: PlatformZhipu,
ok: true,
},
{
name: "ollama-cloud resale kimi pins to kimi (intentional: no ollama branch)",
model: "kimi-k2.6",
platform: PlatformKimi,
ok: true,
},
{
name: "ollama-cloud resale deepseek pins to deepseek (intentional: no ollama branch)",
model: "deepseek-v4.1-flash",
platform: PlatformDeepseek,
ok: true,
},
{
name: "ollama-cloud qwen stays unmatched (intentional: fail closed)",
model: "qwen3.5:397b",
ok: false,
},
}
for _, tt := range tests {
@@ -263,6 +263,9 @@ func loadCodexGroupCatalogAccounts(ctx context.Context, repo AccountRepository,
PlatformZhipu,
PlatformDeepseek,
PlatformMiniMax,
PlatformOllamaCloud,
// PlatformOpenCodeGo 是方案标注的同类历史漏点:同为转售型平台,
// 不进目录则 Codex 客户端同样看不到其映射模型,随本行一并补上。
PlatformOpenCodeGo,
},
false,
@@ -1120,6 +1120,7 @@ func TestBuildCodexModelsManifestForGroupLoadsAccountsOnce(t *testing.T) {
require.Contains(t, repo.platforms, PlatformGrok)
require.Contains(t, repo.platforms, PlatformDeepseek)
require.Contains(t, repo.platforms, PlatformMiniMax)
require.Contains(t, repo.platforms, PlatformOllamaCloud)
require.Contains(t, repo.platforms, PlatformOpenCodeGo)
require.NotContains(t, repo.platforms, PlatformComposite)
}
@@ -626,7 +626,9 @@ func (s *UpstreamBillingProbeService) probeLoadedAccount(ctx context.Context, ac
return s.persistProbeFailure(ctx, account, intervalMinutes, now, 0, "missing_api_key", 0)
}
baseURL := account.GetCredential("base_url")
if account.IsCNProvider() && account.IsAdaptiveAPIProtocol() {
// 多协议 adaptive 账号(CN 供应商 / ollama_cloud)的探测 base 与出站
// base 同源:优先读 api_base_urls 分协议地址,而不是 legacy credentials.base_url。
if (account.IsCNProvider() || account.IsOllamaCloud()) && account.IsAdaptiveAPIProtocol() {
baseURL = account.GetCNProtocolBaseURL(APIProtocolChatCompletions)
}
if account.Platform == PlatformOpenAI {
@@ -372,6 +372,40 @@ func TestUpstreamBillingProbeAdaptiveCNUsesChatProtocolBaseURL(t *testing.T) {
require.Equal(t, "https://chat-relay.example/v1/sub2api/billing", upstream.lastReq.URL.String())
}
// Scenario: ollama_cloud adaptive 账号配置 api_base_urls[chat_completions] 时,
// 探测 base 与出站 base 同源(读分协议地址,而非 legacy credentials.base_url)。
func TestUpstreamBillingProbeAdaptiveOllamaCloudUsesChatProtocolBaseURL(t *testing.T) {
account := &Account{
ID: 19,
Platform: PlatformOllamaCloud,
Type: AccountTypeAPIKey,
Status: StatusActive,
Concurrency: 1,
Credentials: map[string]any{
"api_key": "sk-sensitive",
"api_protocol": APIProtocolAdaptive,
"base_url": "https://legacy-relay.example/v1",
"api_base_urls": map[string]any{
APIProtocolChatCompletions: "https://chat.example/v1",
},
},
Extra: map[string]any{UpstreamBillingProbeEnabledExtraKey: true},
}
repo := &upstreamBillingProbeAccountRepo{accounts: map[int64]*Account{account.ID: account}}
upstream := &httpUpstreamRecorder{resp: &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: upstreamBillingProbeValidBody(),
}}
svc := newUpstreamBillingProbeTestService(repo, upstream, &upstreamBillingProbeSettingRepo{})
snapshot, err := svc.ProbeAccount(context.Background(), account.ID)
require.NoError(t, err)
require.Equal(t, UpstreamBillingProbeStatusOK, snapshot.Status)
require.Equal(t, "https://chat.example/v1/sub2api/billing", upstream.lastReq.URL.String())
}
func TestUpstreamBillingProbeSyncsResolvedRateForAllAPIKeyPlatforms(t *testing.T) {
for _, platform := range []string{
PlatformOpenAI,
@@ -687,6 +687,12 @@ func matchModelsDevProviderByKnownHost(registry map[string]modelsDevProvider, ac
providerID = "openai"
case "opencode.ai":
providerID = "opencode-go"
case "ollama.com":
// 实测 models.dev registry(api.json):provider ID 是 `ollama-cloud`
// (不是 "ollama"),且其 api 字段为 https://ollama.com/v1 —— 常规
// base 走上方 API-URL 匹配即可命中;本 case 兜底 registry 形态漂移
// (api 字段缺失/变更)或非常规路径形式,避免官方 host 静默丢元数据。
providerID = "ollama-cloud"
default:
return modelsDevProvider{}, false
}
@@ -929,6 +929,50 @@ func TestMatchModelsDevProviderFallsBackToOpenAIProviderWithoutAPIField(t *testi
require.Equal(t, "opencode", provider.ID)
}
// Scenario: ollama.com 账号的模型 registry 元数据能匹配到 models.dev 的
// ollama-cloud provider(实测 provider ID 为 `ollama-cloud`,非 "ollama")。
// registry 带 api 字段(当前真实形态 https://ollama.com/v1)时走 API-URL
// 匹配;api 字段缺失(registry 形态漂移)时 known-host 兜底仍命中;
// 反代 host 不继承官方 provider,避免跨厂商错误归因。
func TestMatchModelsDevProviderOllamaCloud(t *testing.T) {
t.Parallel()
newRegistry := func(withAPI bool) map[string]modelsDevProvider {
provider := modelsDevProvider{
ID: "ollama-cloud",
Name: "Ollama Cloud",
Models: map[string]modelsDevModel{
"gpt-oss:120b": {ID: "gpt-oss:120b", Name: "GPT-OSS 120B"},
},
}
if withAPI {
provider.API = "https://ollama.com/v1"
}
return map[string]modelsDevProvider{"ollama-cloud": provider}
}
// registry 带 api 字段:API-URL 匹配直接命中。
for _, baseURL := range []string{
"https://ollama.com/v1",
"https://ollama.com",
} {
provider, ok := matchModelsDevProvider(newRegistry(true), baseURL)
require.True(t, ok, baseURL)
require.Equal(t, "ollama-cloud", provider.ID, baseURL)
require.Contains(t, provider.Models, "gpt-oss:120b", baseURL)
}
// registry api 字段缺失(形态漂移):known-host 兜底命中官方 host。
provider, ok := matchModelsDevProvider(newRegistry(false), "https://ollama.com/v1")
require.True(t, ok)
require.Equal(t, "ollama-cloud", provider.ID)
require.Contains(t, provider.Models, "gpt-oss:120b")
// 反代/自定义 host 不命中:同前缀名字不得跨厂商归因到 ollama-cloud。
_, ok = matchModelsDevProvider(newRegistry(true), "https://relay.example.com/v1")
require.False(t, ok, "custom hosts must not inherit the official ollama-cloud provider by name")
}
// Scenario: 官方 OpenAI ID-only /models + 无 api 字段的 models.dev openai 条目仍能补齐并落库。
func TestSyncUpstreamModelCatalogEnrichesOfficialOpenAIHostWithoutRegistryAPIField(t *testing.T) {
upstream := &httpUpstreamRecorder{responses: []*http.Response{
+4
View File
@@ -158,6 +158,8 @@
? 'bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-400'
: value === 'opencode_go'
? 'bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300'
: value === 'ollama_cloud'
? 'bg-stone-100 text-stone-800 dark:bg-stone-900/30 dark:text-stone-300'
: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
]"
>
@@ -3835,6 +3837,8 @@
? 'bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-400'
: group.platform === 'opencode_go'
? 'bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300'
: group.platform === 'ollama_cloud'
? 'bg-stone-100 text-stone-800 dark:bg-stone-900/30 dark:text-stone-300'
: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
]"
>
@@ -12,5 +12,6 @@ describe('Composite channel platform options', () => {
expect(declaration).toContain("'deepseek'")
expect(declaration).toContain("'minimax'")
expect(declaration).toContain("'opencode_go'")
expect(declaration).toContain("'ollama_cloud'")
})
})