chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,464 @@
|
||||
package runtime_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"academy/internal/models"
|
||||
"academy/internal/models/api"
|
||||
"academy/internal/models/providers"
|
||||
modelruntime "academy/internal/models/runtime"
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func registerTestVendors(t *testing.T) {
|
||||
t.Helper()
|
||||
before := modelruntime.SnapshotCurrent()
|
||||
t.Cleanup(func() { modelruntime.RestoreSnapshot(before) })
|
||||
modelruntime.Register(&providers.Definition{
|
||||
ID: providers.GenericID, Name: "Custom", API: api.APIOpenAICompletions,
|
||||
DefaultBaseURLs: map[types.ModelType]string{},
|
||||
ModelTypes: []types.ModelType{types.ModelTypeKnowledgeQA},
|
||||
Compat: providers.VendorCompat{OpenAICompletions: api.OpenAICompletionsCompat{
|
||||
MaxTokensField: api.Ptr("max_tokens"),
|
||||
ThinkingFormat: api.Ptr(api.ThinkingFormatChatTemplateKwargs),
|
||||
}},
|
||||
})
|
||||
modelruntime.Register(&providers.Definition{
|
||||
ID: "acme", Name: "Acme", Names: map[string]string{"zh-CN": "极目"},
|
||||
API: api.APIOpenAICompletions,
|
||||
RequiresAuth: true,
|
||||
URLPatterns: []string{"api.acme.ai", "acme"},
|
||||
DefaultBaseURLs: map[types.ModelType]string{
|
||||
types.ModelTypeKnowledgeQA: "https://api.acme.ai/v1",
|
||||
types.ModelTypeRerank: "https://api.acme.ai/rerank",
|
||||
},
|
||||
ModelTypes: []types.ModelType{types.ModelTypeKnowledgeQA, types.ModelTypeRerank},
|
||||
Compat: providers.VendorCompat{OpenAICompletions: api.OpenAICompletionsCompat{
|
||||
ThinkingFormat: api.Ptr(api.ThinkingFormatThinkingType),
|
||||
SupportsReasoningEffort: api.Ptr(true),
|
||||
MaxTokensField: api.Ptr("max_tokens"),
|
||||
}},
|
||||
ThinkingLevels: api.ThinkingLevelMap{api.ReasoningMax: api.StringPtr("max")},
|
||||
}, []models.ModelSpec{
|
||||
{
|
||||
ID: "acme-pro", Name: "Acme Pro", Reasoning: true,
|
||||
Input: []string{"text", "image"}, ContextWindow: 200000,
|
||||
Compat: json.RawMessage(`{"supports_temperature": false}`),
|
||||
},
|
||||
{ID: "acme-r1", Reasoning: true, ThinkingLevels: api.ThinkingLevelMap{api.ReasoningOff: nil}},
|
||||
{Match: "acme-lite*", Reasoning: false, Compat: json.RawMessage(`{"thinking_format": "none"}`)},
|
||||
{Match: "acme-lite-vision*", Input: []string{"text", "image"}},
|
||||
{ID: "acme-embed", Type: types.ModelTypeEmbedding, Dimension: 1024},
|
||||
{
|
||||
ID: "acme-claude", API: api.APIAnthropicMessages, Reasoning: true,
|
||||
Compat: json.RawMessage(`{"thinking_mode": "adaptive", "supports_effort": true}`),
|
||||
},
|
||||
}...)
|
||||
modelruntime.Register(&providers.Definition{
|
||||
ID: "tencent-lkeap", Name: "LKEAP", API: api.APIOpenAICompletions,
|
||||
URLPatterns: []string{"api.lkeap.cloud.tencent.com", "tencent"},
|
||||
DefaultBaseURLs: map[types.ModelType]string{
|
||||
types.ModelTypeKnowledgeQA: "https://api.lkeap.cloud.tencent.com/v1",
|
||||
},
|
||||
ModelTypes: []types.ModelType{types.ModelTypeKnowledgeQA},
|
||||
})
|
||||
// acme-nim mirrors the NVIDIA NIM entries before #3489: a chat-template
|
||||
// switch that carries only the enable_thinking boolean, while the models
|
||||
// carry ladders the branch cannot encode.
|
||||
modelruntime.Register(&providers.Definition{
|
||||
ID: "acme-nim", Name: "Acme NIM", API: api.APIOpenAICompletions,
|
||||
ModelTypes: []types.ModelType{types.ModelTypeKnowledgeQA},
|
||||
Compat: providers.VendorCompat{OpenAICompletions: api.OpenAICompletionsCompat{
|
||||
MaxTokensField: api.Ptr("max_tokens"),
|
||||
ThinkingFormat: api.Ptr(api.ThinkingFormatChatTemplateKwargs),
|
||||
}},
|
||||
}, []models.ModelSpec{
|
||||
{
|
||||
ID: "acme-nim-glm", Reasoning: true,
|
||||
ThinkingLevels: api.ThinkingLevelMap{
|
||||
api.ReasoningOff: nil,
|
||||
api.ReasoningMinimal: api.StringPtr("low"),
|
||||
api.ReasoningHigh: api.StringPtr("high"),
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "acme-nim-effort", Reasoning: true,
|
||||
Compat: json.RawMessage(`{"supports_reasoning_effort": true}`),
|
||||
ThinkingLevels: api.ThinkingLevelMap{api.ReasoningHigh: api.StringPtr("high")},
|
||||
},
|
||||
}...)
|
||||
}
|
||||
|
||||
func TestFindModel_ExactAliasAndGlob(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
v, _ := modelruntime.Get("acme")
|
||||
|
||||
chat := types.ModelTypeKnowledgeQA
|
||||
m, ok := v.FindModel("ACME-PRO", chat)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "acme-pro", m.ID)
|
||||
|
||||
m, ok = v.FindModel("acme-lite-2", chat)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "acme-lite*", m.Match)
|
||||
|
||||
m, ok = v.FindModel("acme-lite-vision-2", chat)
|
||||
require.True(t, ok, "longest literal prefix wins")
|
||||
assert.Equal(t, "acme-lite-vision*", m.Match)
|
||||
|
||||
_, ok = v.FindModel("unknown", chat)
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
// A lookup only sees entries of the row's own type. A VLM row is a chat
|
||||
// model that accepts images, so it sees the chat entries.
|
||||
func TestFindModel_IsTyped(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
v, _ := modelruntime.Get("acme")
|
||||
|
||||
_, ok := v.FindModel("acme-embed", types.ModelTypeKnowledgeQA)
|
||||
assert.False(t, ok, "a chat row must not pick up an embedding entry")
|
||||
m, ok := v.FindModel("acme-embed", types.ModelTypeEmbedding)
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "acme-embed", m.ID)
|
||||
|
||||
_, ok = v.FindModel("acme-lite-embed", types.ModelTypeEmbedding)
|
||||
assert.False(t, ok, "an embedding row must not pick up a chat glob")
|
||||
_, ok = v.FindModel("acme-lite-2", types.ModelTypeVLLM)
|
||||
assert.True(t, ok)
|
||||
}
|
||||
|
||||
// The failure a typed lookup prevents: a chat family's glob carries chat
|
||||
// compat, and handing it to an embedding or rerank row fails the strict
|
||||
// overlay decode, so the row could not be built at all.
|
||||
func TestResolve_ModelNameInsideAChatGlobStillResolvesForOtherTypes(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
for _, modelType := range []types.ModelType{types.ModelTypeEmbedding, types.ModelTypeRerank} {
|
||||
r, err := modelruntime.Resolve(
|
||||
modelruntime.Ref{
|
||||
Provider: "acme",
|
||||
Model: "acme-lite-embed",
|
||||
ModelType: modelType,
|
||||
},
|
||||
)
|
||||
require.NoError(t, err, modelType)
|
||||
assert.False(t, r.Cataloged, modelType)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectByURL_LongestPatternWins(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
assert.Equal(t, "tencent-lkeap", modelruntime.DetectByURL("https://api.lkeap.cloud.tencent.com/v1"))
|
||||
assert.Equal(t, "acme", modelruntime.DetectByURL("https://api.acme.ai/v1"))
|
||||
assert.Equal(t, providers.GenericID, modelruntime.DetectByURL("http://localhost:8000/v1"))
|
||||
assert.Equal(t, providers.GenericID, modelruntime.DetectByURL(""))
|
||||
}
|
||||
|
||||
func TestResolve_MergesVendorModelAndOverrideLayers(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
|
||||
r, err := modelruntime.Resolve(modelruntime.Ref{Provider: "acme", Model: "acme-pro"})
|
||||
require.NoError(t, err)
|
||||
assert.True(t, r.Cataloged)
|
||||
assert.Equal(t, api.APIOpenAICompletions, r.API)
|
||||
assert.Equal(t, "https://api.acme.ai/v1", r.BaseURL, "default base URL is filled in")
|
||||
assert.Equal(t, "max_tokens", r.OpenAICompletions.MaxTokensField)
|
||||
assert.Equal(t, api.ThinkingFormatThinkingType, r.OpenAICompletions.ThinkingFormat)
|
||||
assert.True(t, r.OpenAICompletions.SupportsReasoningEffort)
|
||||
assert.False(t, r.OpenAICompletions.SupportsTemperature, "model compat overrides the protocol default")
|
||||
assert.True(t, r.OpenAICompletions.SupportsUsageInStreaming, "untouched defaults survive")
|
||||
assert.Equal(t, "max", r.ThinkingLevels.Value(api.ReasoningMax))
|
||||
assert.True(t, r.ThinkingLevels.Supports(api.ReasoningMax))
|
||||
assert.Equal(t, 200000, r.Spec.ContextWindow)
|
||||
|
||||
caps := r.Capabilities()
|
||||
assert.True(t, caps.Reasoning)
|
||||
assert.Equal(t, []string{"text", "image"}, caps.Input)
|
||||
assert.Contains(t, caps.ThinkingLevels, api.ReasoningOff)
|
||||
assert.Contains(t, caps.ThinkingLevels, api.ReasoningMax)
|
||||
|
||||
// Row-level override wins over everything.
|
||||
on := true
|
||||
r, err = modelruntime.Resolve(modelruntime.Ref{
|
||||
Provider: "acme", Model: "acme-pro", BaseURL: "https://proxy.example.com/v1/",
|
||||
Override: &types.ModelSpecOverride{
|
||||
ContextWindow: 1000,
|
||||
Reasoning: &on,
|
||||
ThinkingLevels: map[string]*string{"off": nil},
|
||||
Compat: map[string]any{"supports_temperature": true, "max_tokens_field": "max_completion_tokens"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "https://proxy.example.com/v1", r.BaseURL, "trailing slash trimmed, override kept")
|
||||
assert.Equal(t, 1000, r.Spec.ContextWindow)
|
||||
assert.True(t, r.OpenAICompletions.SupportsTemperature)
|
||||
assert.Equal(t, "max_completion_tokens", r.OpenAICompletions.MaxTokensField)
|
||||
assert.False(t, r.ThinkingLevels.Supports(api.ReasoningOff))
|
||||
}
|
||||
|
||||
func TestResolve_UnknownModelAndVendorDegradeToGeneric(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
|
||||
r, err := modelruntime.Resolve(modelruntime.Ref{Provider: "acme", Model: "brand-new"})
|
||||
require.NoError(t, err)
|
||||
assert.False(t, r.Cataloged)
|
||||
assert.Equal(t, "brand-new", r.Spec.ID)
|
||||
assert.Equal(
|
||||
t,
|
||||
api.ThinkingFormatThinkingType,
|
||||
r.OpenAICompletions.ThinkingFormat,
|
||||
"vendor defaults still apply",
|
||||
)
|
||||
|
||||
r, err = modelruntime.Resolve(modelruntime.Ref{Provider: "nope", Model: "x", BaseURL: "http://localhost:8000/v1"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, providers.GenericID, r.Vendor.ID)
|
||||
assert.Equal(t, api.ThinkingFormatChatTemplateKwargs, r.OpenAICompletions.ThinkingFormat)
|
||||
|
||||
r, err = modelruntime.Resolve(modelruntime.Ref{Model: "x", BaseURL: "https://api.acme.ai/v1"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "acme", r.Vendor.ID, "provider detected from URL when empty")
|
||||
}
|
||||
|
||||
func TestResolve_ProtocolInference(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
|
||||
r, err := modelruntime.Resolve(modelruntime.Ref{Provider: "acme", Model: "acme-claude"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, api.APIAnthropicMessages, r.API)
|
||||
assert.Equal(t, api.AnthropicThinkingAdaptive, r.AnthropicMessages.ThinkingMode)
|
||||
assert.True(t, r.AnthropicMessages.SupportsEffort)
|
||||
assert.Equal(t, "thinking.adaptive", r.Capabilities().ThinkingFormat)
|
||||
|
||||
r, err = modelruntime.Resolve(
|
||||
modelruntime.Ref{
|
||||
Provider: "acme",
|
||||
Model: "acme-pro",
|
||||
BaseURL: "https://api.acme.ai/anthropic",
|
||||
},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, api.APIAnthropicMessages, r.API, "/anthropic suffix switches protocol")
|
||||
|
||||
r, err = modelruntime.Resolve(
|
||||
modelruntime.Ref{
|
||||
Provider: "acme",
|
||||
Model: "acme-pro",
|
||||
Extra: map[string]string{
|
||||
models.ExtraAPI: "openai-responses",
|
||||
},
|
||||
},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, api.APIOpenAIResponses, r.API, "extra_config.api forces the protocol")
|
||||
|
||||
_, err = modelruntime.Resolve(
|
||||
modelruntime.Ref{
|
||||
Provider: "acme",
|
||||
Model: "acme-pro",
|
||||
Extra: map[string]string{
|
||||
models.ExtraAPI: "bogus",
|
||||
},
|
||||
},
|
||||
)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestResolve_LegacyThinkingControlAndRemoteModelName(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
r, err := modelruntime.Resolve(modelruntime.Ref{Provider: "acme", Model: "acme-pro", Extra: map[string]string{
|
||||
models.ExtraThinkingControl: "enable_thinking",
|
||||
models.ExtraRemoteModelName: "acme-pro-2026",
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, api.ThinkingFormatEnableThinking, r.OpenAICompletions.ThinkingFormat)
|
||||
assert.Equal(t, "acme-pro-2026", r.RemoteModel)
|
||||
|
||||
r, err = modelruntime.Resolve(
|
||||
modelruntime.Ref{
|
||||
Provider: "acme",
|
||||
Model: "acme-pro",
|
||||
Extra: map[string]string{
|
||||
models.ExtraThinkingControl: "none",
|
||||
},
|
||||
},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, r.Capabilities().ThinkingLevels, "none disables the selector")
|
||||
}
|
||||
|
||||
func TestResolve_AlwaysOnModelCannotBeSwitchedOff(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
r, err := modelruntime.Resolve(modelruntime.Ref{Provider: "acme", Model: "acme-r1"})
|
||||
require.NoError(t, err)
|
||||
assert.False(t, r.ThinkingLevels.Supports(api.ReasoningOff))
|
||||
assert.NotContains(t, r.Capabilities().ThinkingLevels, api.ReasoningOff)
|
||||
}
|
||||
|
||||
// A chat-template switch carries only the enable_thinking boolean, so every
|
||||
// graded rung is silently dropped on the wire — and a relay backend that does
|
||||
// not know enable_thinking drops the boolean too. Capabilities must not
|
||||
// advertise levels the wire format cannot express, or the UI renders a
|
||||
// selector whose choice does nothing. #3489 fixed the two catalogued NIM
|
||||
// entries with this defect; this pins the generic fallback and the
|
||||
// boolean-only vendor shape in general.
|
||||
func TestResolve_BooleanThinkingSwitchHidesGradedLevels(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
|
||||
// Uncatalogued model on the generic vendor — a relay row. The empty level
|
||||
// map's missing-key pass-through used to advertise six rungs here.
|
||||
r, err := modelruntime.Resolve(modelruntime.Ref{
|
||||
Provider: "generic", Model: "glm-5.3", BaseURL: "https://relay.example.com/v1",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.False(t, r.Cataloged)
|
||||
assert.Equal(t, []api.ReasoningEffort{api.ReasoningOff, api.ReasoningAuto},
|
||||
r.Capabilities().ThinkingLevels, "only the boolean the switch can carry")
|
||||
|
||||
// Catalogued model whose ladder the chat-template branch cannot encode:
|
||||
// the graded rungs stay hidden from the selector.
|
||||
r, err = modelruntime.Resolve(modelruntime.Ref{Provider: "acme-nim", Model: "acme-nim-glm"})
|
||||
require.NoError(t, err)
|
||||
caps := r.Capabilities()
|
||||
assert.Equal(t, []api.ReasoningEffort{api.ReasoningAuto}, caps.ThinkingLevels,
|
||||
"always-on entry: off was already hidden, graded rungs must not appear")
|
||||
assert.NotContains(t, caps.ThinkingLevels, api.ReasoningMinimal)
|
||||
assert.NotContains(t, caps.ThinkingLevels, api.ReasoningHigh)
|
||||
|
||||
// A vendor that opts into a top-level effort field alongside the switch
|
||||
// keeps its ladder (the future combo #3489's entries moved to).
|
||||
r, err = modelruntime.Resolve(modelruntime.Ref{Provider: "acme-nim", Model: "acme-nim-effort"})
|
||||
require.NoError(t, err)
|
||||
caps = r.Capabilities()
|
||||
assert.Contains(t, caps.ThinkingLevels, api.ReasoningMinimal, "pass-through rung kept")
|
||||
assert.Contains(t, caps.ThinkingLevels, api.ReasoningHigh, "explicit ladder rung kept")
|
||||
}
|
||||
|
||||
func TestResolve_RejectsUnknownCompatKeys(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
_, err := modelruntime.Resolve(
|
||||
modelruntime.Ref{
|
||||
Provider: "acme",
|
||||
Model: "acme-pro",
|
||||
Override: &types.ModelSpecOverride{
|
||||
Compat: map[string]any{"max_token_field": "max_tokens"},
|
||||
},
|
||||
},
|
||||
)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "max_token_field")
|
||||
}
|
||||
|
||||
func TestModelsByType(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
v, _ := modelruntime.Get("acme")
|
||||
chat := v.ModelsByType(types.ModelTypeKnowledgeQA)
|
||||
ids := make([]string, 0, len(chat))
|
||||
for _, m := range chat {
|
||||
ids = append(ids, m.ID)
|
||||
}
|
||||
assert.ElementsMatch(t, []string{"acme-pro", "acme-r1", "acme-claude"}, ids, "pattern-only entries are hidden")
|
||||
vlm := v.ModelsByType(types.ModelTypeVLLM)
|
||||
require.Len(t, vlm, 1)
|
||||
assert.Equal(t, "acme-pro", vlm[0].ID, "VLM picker lists chat models with image input")
|
||||
embed := v.ModelsByType(types.ModelTypeEmbedding)
|
||||
require.Len(t, embed, 1)
|
||||
assert.Equal(t, 1024, embed[0].Dimension)
|
||||
}
|
||||
|
||||
func TestApplyOverlay(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
t.Setenv("ACME_KEY", "sk-from-env")
|
||||
overlay := `{
|
||||
"providers": {
|
||||
"acme": {
|
||||
"base_url": "https://acme.internal/v1",
|
||||
"api_key": "${ACME_KEY}",
|
||||
"headers": {"X-Team": "$ACME_KEY"},
|
||||
"thinking_levels": {"xhigh": "max"},
|
||||
"models": [{"id": "acme-ultra", "reasoning": true, "context_window": 400000}],
|
||||
"model_overrides": {"acme-pro": {"context_window": 123, "compat": {"supports_temperature": true}}}
|
||||
},
|
||||
"my-vllm": {
|
||||
"name": "Lab vLLM",
|
||||
"names": {"zh-CN": "实验室 vLLM"},
|
||||
"base_url": "http://vllm.lab:8000/v1",
|
||||
"requires_auth": false,
|
||||
"compat": {"thinking_format": "chat-template-kwargs", "max_tokens_field": "max_tokens"},
|
||||
"models": [{"id": "Qwen/Qwen3-32B", "reasoning": true}]
|
||||
}
|
||||
}
|
||||
}`
|
||||
require.NoError(t, modelruntime.ApplyOverlay([]byte(overlay), t.TempDir()))
|
||||
|
||||
acme, ok := modelruntime.Get("acme")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "https://acme.internal/v1", acme.GetDefaultURL(types.ModelTypeKnowledgeQA))
|
||||
assert.Equal(t, "https://api.acme.ai/rerank", acme.GetDefaultURL(types.ModelTypeRerank), "other URLs untouched")
|
||||
assert.Equal(t, "sk-from-env", acme.DefaultAPIKey)
|
||||
assert.Equal(t, "sk-from-env", acme.Headers["X-Team"])
|
||||
assert.Equal(t, "max", acme.ThinkingLevels.Value(api.ReasoningXHigh))
|
||||
assert.Equal(t, "max", acme.ThinkingLevels.Value(api.ReasoningMax), "existing levels kept")
|
||||
|
||||
r, err := modelruntime.Resolve(modelruntime.Ref{Provider: "acme", Model: "acme-ultra"})
|
||||
require.NoError(t, err)
|
||||
assert.True(t, r.Cataloged)
|
||||
assert.Equal(t, 400000, r.Spec.ContextWindow)
|
||||
|
||||
r, err = modelruntime.Resolve(modelruntime.Ref{Provider: "acme", Model: "acme-pro"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 123, r.Spec.ContextWindow)
|
||||
assert.True(t, r.OpenAICompletions.SupportsTemperature, "model_overrides compat merges over the built-in compat")
|
||||
|
||||
lab, ok := modelruntime.Get("my-vllm")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "实验室 vLLM", lab.LocalizedName("zh-CN"))
|
||||
assert.Equal(t, "Lab vLLM", lab.LocalizedName("en-US"))
|
||||
assert.False(t, lab.RequiresAuth)
|
||||
r, err = modelruntime.Resolve(modelruntime.Ref{Provider: "my-vllm", Model: "Qwen/Qwen3-32B"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, api.ThinkingFormatChatTemplateKwargs, r.OpenAICompletions.ThinkingFormat)
|
||||
assert.Equal(t, "max_tokens", r.OpenAICompletions.MaxTokensField)
|
||||
assert.True(t, r.Spec.Reasoning)
|
||||
assert.Equal(t, "http://vllm.lab:8000/v1", r.BaseURL)
|
||||
|
||||
assert.Error(
|
||||
t,
|
||||
modelruntime.ApplyOverlay(
|
||||
[]byte(
|
||||
`{"providers": {"x": {"bogus": 1}}}`,
|
||||
),
|
||||
t.TempDir(),
|
||||
),
|
||||
"unknown keys rejected",
|
||||
)
|
||||
assert.Error(t, modelruntime.ApplyOverlay([]byte(`{"providers": {"x": {"api": "nope"}}}`), t.TempDir()))
|
||||
}
|
||||
|
||||
func TestThinkingLevelMap(t *testing.T) {
|
||||
m := api.ThinkingLevelMap{
|
||||
api.ReasoningMedium: nil,
|
||||
api.ReasoningMax: api.StringPtr("max"),
|
||||
api.ReasoningOff: api.StringPtr("none"),
|
||||
}
|
||||
assert.False(t, m.Supports(api.ReasoningMedium))
|
||||
assert.True(t, m.Supports(api.ReasoningMax))
|
||||
assert.False(t, m.Supports(api.ReasoningXHigh), "xhigh needs an explicit entry")
|
||||
assert.Equal(t, api.ReasoningHigh, m.Clamp(api.ReasoningMedium), "clamps upward first")
|
||||
assert.Equal(t, api.ReasoningMax, m.Clamp(api.ReasoningXHigh))
|
||||
assert.Equal(t, "none", m.Value(api.ReasoningOff))
|
||||
assert.Equal(t, "low", m.Value(api.ReasoningLow), "unmapped levels pass through")
|
||||
assert.Equal(t, []api.ReasoningEffort{
|
||||
api.ReasoningOff, api.ReasoningAuto, api.ReasoningMinimal,
|
||||
api.ReasoningLow, api.ReasoningHigh, api.ReasoningMax,
|
||||
}, m.SupportedLevels())
|
||||
|
||||
level, ok := api.ParseReasoningEffort("true")
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, api.ReasoningAuto, level)
|
||||
_, ok = api.ParseReasoningEffort("ultra")
|
||||
assert.False(t, ok)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
"academy/internal/models/internal/configcopy"
|
||||
)
|
||||
|
||||
// ApplyCompat writes the set fields of an overlay struct onto a settings struct
|
||||
// with matching field names, dereferencing pointers. Slices and maps
|
||||
// replace the default wholesale (no element merge) except map[string]any
|
||||
// ExtraBody-style fields, which merge key by key.
|
||||
func ApplyCompat(settings any, compat any) {
|
||||
sv := reflect.ValueOf(settings).Elem()
|
||||
cv := reflect.ValueOf(compat).Elem()
|
||||
ct := cv.Type()
|
||||
for i := 0; i < cv.NumField(); i++ {
|
||||
field := ct.Field(i)
|
||||
if !field.IsExported() {
|
||||
continue
|
||||
}
|
||||
target := sv.FieldByName(field.Name)
|
||||
if !target.IsValid() {
|
||||
panic(fmt.Sprintf("catalog: overlay field %s.%s has no settings counterpart", ct.Name(), field.Name))
|
||||
}
|
||||
f := cv.Field(i)
|
||||
switch f.Kind() {
|
||||
case reflect.Pointer:
|
||||
if f.IsNil() {
|
||||
continue
|
||||
}
|
||||
if target.Kind() == reflect.Pointer {
|
||||
target.Set(configcopy.Value(f))
|
||||
} else {
|
||||
target.Set(configcopy.Value(f.Elem()))
|
||||
}
|
||||
case reflect.Slice:
|
||||
if f.Len() > 0 {
|
||||
target.Set(configcopy.Value(f))
|
||||
}
|
||||
case reflect.Map:
|
||||
if f.Len() == 0 {
|
||||
continue
|
||||
}
|
||||
if target.IsNil() {
|
||||
target.Set(reflect.MakeMap(target.Type()))
|
||||
}
|
||||
iter := f.MapRange()
|
||||
for iter.Next() {
|
||||
target.SetMapIndex(iter.Key(), configcopy.Value(iter.Value()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// DecodeCompat unmarshals a flat compat object into the overlay type for an
|
||||
// API. Unknown keys are rejected so typos in models.json surface early.
|
||||
func DecodeCompat(raw json.RawMessage, into any) error {
|
||||
if len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
dec := json.NewDecoder(bytesReader(raw))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(into); err != nil {
|
||||
return fmt.Errorf("decode compat: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func bytesReader(b []byte) *bytes.Reader { return bytes.NewReader(b) }
|
||||
@@ -0,0 +1,78 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"academy/internal/models/api"
|
||||
"academy/internal/models/providers"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// Connection contains only one configured model's credentials and transport
|
||||
// settings. It is never cached in the provider registry or model catalog.
|
||||
type Connection struct {
|
||||
ModelID string
|
||||
Credentials api.Credentials
|
||||
Headers map[string]string
|
||||
Extra map[string]string
|
||||
Client *http.Client
|
||||
}
|
||||
|
||||
// Endpoint assembles authentication, headers and vendor endpoint routing for
|
||||
// every capability. Protocol clients receive the result without knowing vendors.
|
||||
func (r *Resolved) Endpoint(kind types.ModelType, c Connection) (api.Endpoint, error) {
|
||||
v := r.Vendor
|
||||
creds := c.Credentials
|
||||
if creds.APIKey == "" {
|
||||
creds.APIKey = v.DefaultAPIKey
|
||||
}
|
||||
protocol := v.API
|
||||
label := strings.ToLower(string(kind))
|
||||
if kind == types.ModelTypeKnowledgeQA || kind == types.ModelTypeVLLM {
|
||||
protocol, label = r.API, "provider"
|
||||
}
|
||||
if v.AuthStyleFor(protocol) == providers.AuthSigned {
|
||||
if creds.AppID == "" {
|
||||
return api.Endpoint{}, fmt.Errorf("%s %s: AppID is required", v.Name, label)
|
||||
}
|
||||
if creds.AppSecret == "" {
|
||||
return api.Endpoint{}, fmt.Errorf("%s %s: AppSecret is required", v.Name, label)
|
||||
}
|
||||
} else if v.RequiresAuth && protocol == api.APIAnthropicMessages &&
|
||||
(kind == types.ModelTypeKnowledgeQA || kind == types.ModelTypeVLLM) && strings.TrimSpace(creds.APIKey) == "" {
|
||||
return api.Endpoint{}, fmt.Errorf("%s provider: API key is required", v.Name)
|
||||
}
|
||||
headers := make(map[string]string, len(v.Headers)+len(c.Headers))
|
||||
for k, val := range v.Headers {
|
||||
headers[k] = val
|
||||
}
|
||||
for k, val := range c.Headers {
|
||||
headers[k] = val
|
||||
}
|
||||
ep := api.Endpoint{
|
||||
BaseURL: r.BaseURL, Model: r.RemoteModel, ModelID: c.ModelID,
|
||||
Auth: v.AuthFunc(protocol, creds), Headers: headers, Client: c.Client,
|
||||
}
|
||||
if v.Endpoint != nil {
|
||||
req := providers.EndpointRequest{
|
||||
BaseURL: r.BaseURL,
|
||||
Model: r.RemoteModel,
|
||||
ModelType: kind,
|
||||
API: protocol,
|
||||
Extra: c.Extra,
|
||||
}
|
||||
if kind == types.ModelTypeEmbedding {
|
||||
req.EmbeddingAPI = r.EmbeddingAPI
|
||||
}
|
||||
// Preserve historical rerank hook input; its routing uses ModelType.
|
||||
if kind == types.ModelTypeRerank {
|
||||
req.API = ""
|
||||
}
|
||||
if url, query := v.Endpoint(req); url != "" {
|
||||
ep.URL, ep.Query = url, query
|
||||
}
|
||||
}
|
||||
return ep, nil
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestLooksLikeSVG(t *testing.T) {
|
||||
for _, in := range []string{
|
||||
`<svg xmlns="http://www.w3.org/2000/svg"></svg>`,
|
||||
" \n<svg/>",
|
||||
"\ufeff<?xml version=\"1.0\"?>\n<!-- brand mark --><svg >x</svg>",
|
||||
"<?xml version=\"1.0\"?><!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"x.dtd\"><svg>y</svg>",
|
||||
"<SVG></SVG>",
|
||||
} {
|
||||
assert.True(t, looksLikeSVG([]byte(in)), "want SVG: %q", in)
|
||||
}
|
||||
for _, in := range []string{
|
||||
"", " ", "<svg", "<svgx>", "not markup at all",
|
||||
"<html><svg></svg></html>", "<?xml version=\"1.0\"?>", "<!-- unterminated",
|
||||
"root:x:0:0::/root:/bin/sh",
|
||||
} {
|
||||
assert.False(t, looksLikeSVG([]byte(in)), "want not SVG: %q", in)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package runtime
|
||||
|
||||
// WithOverlay builds an independent candidate on top of this generation.
|
||||
// It never publishes partial changes or mutates either input layer. Unlike
|
||||
// Reload, this explicitly retains the deployment layer beneath a UI overlay.
|
||||
func (rt *Runtime) WithOverlay(data []byte, baseDir string) (*Runtime, error) {
|
||||
snapshot := rt.SnapshotCurrent()
|
||||
candidate := &Runtime{providers: cloneProviders(snapshot.current), builtins: cloneProviders(snapshot.current)}
|
||||
if err := candidate.Reload(data, baseDir); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
candidate.builtins = cloneProviders(snapshot.base)
|
||||
return candidate, nil
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"academy/internal/models/api"
|
||||
)
|
||||
|
||||
// inferAPIFromURL preserves protocol selection for legacy URLs.
|
||||
func inferAPIFromURL(baseURL string, current api.API) api.API {
|
||||
lower := strings.ToLower(strings.TrimRight(baseURL, "/"))
|
||||
switch {
|
||||
case strings.HasSuffix(lower, "/anthropic") || strings.HasSuffix(lower, "/anthropic/v1"):
|
||||
return api.APIAnthropicMessages
|
||||
case current == api.APIGoogleGenerativeAI &&
|
||||
(strings.HasSuffix(lower, "/openai") || strings.Contains(lower, "/openai/")):
|
||||
return api.APIOpenAICompletions
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
// applyLegacyThinkingControl maps the pre-catalog thinking_control value
|
||||
// onto the new settings. Unknown non-empty values keep the historical
|
||||
// fallback (chat_template_kwargs). It reports whether a stored value was
|
||||
// applied, so the caller can still silence catalogued non-reasoning models
|
||||
// when a legacy default is ignored.
|
||||
func applyLegacyThinkingControl(s *api.OpenAICompletionsSettings, value string) bool {
|
||||
normalized := strings.ToLower(strings.TrimSpace(value))
|
||||
if normalized == "" {
|
||||
return false
|
||||
}
|
||||
// The pre-catalog editor persisted "none" as OpenRouter's default for
|
||||
// every remote model row. It was not an explicit request to suppress the
|
||||
// provider's newer native reasoning format, which is needed to honor the
|
||||
// caller's thinking=false setting. Keep honoring every non-default legacy
|
||||
// encoding as an explicit per-row override.
|
||||
if normalized == "none" && s.ThinkingFormat == api.ThinkingFormatOpenRouter {
|
||||
return false
|
||||
}
|
||||
switch normalized {
|
||||
case "none":
|
||||
s.ThinkingFormat = api.ThinkingFormatNone
|
||||
case "enable_thinking":
|
||||
s.ThinkingFormat = api.ThinkingFormatEnableThinking
|
||||
case "thinking_type":
|
||||
s.ThinkingFormat = api.ThinkingFormatThinkingType
|
||||
default:
|
||||
s.ThinkingFormat = api.ThinkingFormatChatTemplateKwargs
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,432 @@
|
||||
package runtime_test
|
||||
|
||||
// Backward-compatibility guard for model rows written before the vendor
|
||||
// catalog existed (internal/models/provider). Every shape in this file is one
|
||||
// that a production `models` table can already contain, so a failure here
|
||||
// means an existing deployment breaks on upgrade without a migration.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"academy/internal/models/api"
|
||||
"academy/internal/models/providers"
|
||||
modelruntime "academy/internal/models/runtime"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// legacyProviderIDs is the complete set of parameters.provider values the
|
||||
// pre-catalog code could write: provider.AllProviders() plus academycloud,
|
||||
// as of internal/models/provider/provider.go before the refactor.
|
||||
var legacyProviderIDs = []string{
|
||||
"generic", "academycloud", "aliyun", "zhipu", "volcengine", "hunyuan",
|
||||
"siliconflow", "deepseek", "minimax", "moonshot", "modelscope", "qianfan",
|
||||
"qiniu", "openai", "anthropic", "gemini", "openrouter", "litellm",
|
||||
"requesty", "jina", "mimo", "longcat", "lkeap", "gpustack", "nvidia",
|
||||
"novita", "azure_openai",
|
||||
}
|
||||
|
||||
// TestLegacyProviderIDsStillRegistered asserts that no provider id an old row
|
||||
// may carry has disappeared from the catalog. A missing id would silently
|
||||
// degrade that row to the generic OpenAI baseline (wrong auth, wrong URL,
|
||||
// wrong thinking encoding).
|
||||
func TestLegacyProviderIDsStillRegistered(t *testing.T) {
|
||||
for _, id := range legacyProviderIDs {
|
||||
if _, ok := modelruntime.Get(id); !ok {
|
||||
t.Errorf("provider id %q was writable by the old code but has no vendor now", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// legacyRow is one realistic pre-refactor `models` row.
|
||||
type legacyRow struct {
|
||||
name string
|
||||
model string
|
||||
typ types.ModelType
|
||||
params types.ModelParameters
|
||||
}
|
||||
|
||||
// legacyRows covers the shapes the old write paths produced: the model editor
|
||||
// (provider + base_url + api_key, no extra_config at all), the initialization
|
||||
// wizard (thinking_control / api_version / remote_model_name), YAML builtin
|
||||
// models, and rows hand-written against an older release.
|
||||
func legacyRows() []legacyRow {
|
||||
rows := []legacyRow{
|
||||
{
|
||||
name: "editor row, catalogued model, no extra_config",
|
||||
model: "deepseek-chat", typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{Provider: "deepseek", BaseURL: "https://api.deepseek.com/v1", APIKey: "sk-x"},
|
||||
},
|
||||
{
|
||||
name: "editor row, model the vendor has since retired",
|
||||
model: "gpt-3.5-turbo-0301", typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{Provider: "openai", BaseURL: "https://api.openai.com/v1", APIKey: "sk-x"},
|
||||
},
|
||||
{
|
||||
name: "self-hosted fine-tune behind a generic endpoint",
|
||||
model: "acme-corp/llama-3.1-70b-finetune-v7", typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{Provider: "generic", BaseURL: "http://vllm.internal:8000/v1"},
|
||||
},
|
||||
{
|
||||
name: "row written before parameters.provider existed",
|
||||
model: "qwen-plus", typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{BaseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"},
|
||||
},
|
||||
{
|
||||
name: "row with neither provider nor base_url",
|
||||
model: "some-model", typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{},
|
||||
},
|
||||
{
|
||||
name: "provider id a hand-edited row invented",
|
||||
model: "grok-4", typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{Provider: "xai", BaseURL: "https://api.x.ai/v1"},
|
||||
},
|
||||
{
|
||||
name: "VLM row", model: "qwen-vl-max", typ: types.ModelTypeVLLM,
|
||||
params: types.ModelParameters{
|
||||
Provider: "aliyun", BaseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
|
||||
InterfaceType: "openai", SupportsVision: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "local Ollama VLM row (interface_type ollama)", model: "llava:13b", typ: types.ModelTypeVLLM,
|
||||
params: types.ModelParameters{
|
||||
InterfaceType: "ollama", ParameterSize: "13B", BaseURL: "http://localhost:11434",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "AcademyCloud row with app credentials", model: "academy-chat", typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{
|
||||
Provider: "academycloud", BaseURL: "https://weknora.weixin.qq.com",
|
||||
AppID: "app", AppSecret: "secret",
|
||||
ExtraConfig: map[string]string{"remote_model_name": "hunyuan-turbos"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Azure row from the initialization wizard", model: "gpt-4o-deployment",
|
||||
typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{
|
||||
Provider: "azure_openai", BaseURL: "https://my-resource.openai.azure.com",
|
||||
ExtraConfig: map[string]string{"api_version": "2024-10-21"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Azure row created from the model editor (no api_version)", model: "gpt-4o-deployment",
|
||||
typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{
|
||||
Provider: "azure_openai", BaseURL: "https://my-resource.openai.azure.com",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "every legacy extra_config key at once, plus an unknown one",
|
||||
model: "custom-model", typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{
|
||||
Provider: "generic", BaseURL: "http://vllm.internal:8000/v1",
|
||||
ExtraConfig: map[string]string{
|
||||
"thinking_control": "chat_template_kwargs",
|
||||
"remote_model_name": "Qwen/Qwen3-32B",
|
||||
"api_version": "2024-10-21",
|
||||
"secret_key": "sk",
|
||||
"region": "ap-guangzhou",
|
||||
"instruction": "rank these",
|
||||
"truncate_prompt_tokens": "4096",
|
||||
"deployment": "prod",
|
||||
"freshness": "week",
|
||||
"a_key_no_release_ever_wrote": "1",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "embedding row with dimension override", model: "text-embedding-v4", typ: types.ModelTypeEmbedding,
|
||||
params: types.ModelParameters{
|
||||
Provider: "aliyun", BaseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
|
||||
EmbeddingParameters: types.EmbeddingParameters{
|
||||
Dimension: 1024, TruncatePromptTokens: 2048, SupportsDimensionOverride: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "LKEAP signed rerank row", model: "lkeap-rerank", typ: types.ModelTypeRerank,
|
||||
params: types.ModelParameters{
|
||||
Provider: "lkeap", BaseURL: "https://lkeap.tencentcloudapi.com",
|
||||
ExtraConfig: map[string]string{"secret_key": "sk", "region": "ap-guangzhou"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "custom headers row", model: "gateway-model", typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{
|
||||
Provider: "generic", BaseURL: "https://gateway.corp.example.com/v1",
|
||||
CustomHeaders: map[string]string{"X-Corp-Route": "llm"},
|
||||
ContextWindow: 128000, MaxOutputTokens: 8192, MaxConcurrency: 4,
|
||||
},
|
||||
},
|
||||
}
|
||||
// Every legacy provider id, carrying a model name no models.json knows.
|
||||
// This is the "custom fine-tune / retired model / self-hosted name" case
|
||||
// for each vendor at once.
|
||||
for _, id := range legacyProviderIDs {
|
||||
rows = append(rows, legacyRow{
|
||||
name: "uncatalogued model on provider " + id, model: "a-model-no-catalog-knows",
|
||||
typ: types.ModelTypeKnowledgeQA,
|
||||
params: types.ModelParameters{Provider: id},
|
||||
})
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// TestLegacyRowsValidateAndResolve is the core guarantee: opening an existing
|
||||
// model in the UI and saving it (PUT /models/{id} runs modelruntime.ValidateRow)
|
||||
// must not 400, and the chat path must still resolve the row.
|
||||
func TestLegacyRowsValidateAndResolve(t *testing.T) {
|
||||
for _, row := range legacyRows() {
|
||||
t.Run(row.name, func(t *testing.T) {
|
||||
params := row.params
|
||||
if err := modelruntime.ValidateRow(row.model, row.typ, ¶ms); err != nil {
|
||||
t.Fatalf("ValidateRow rejected a row the old code accepted: %v", err)
|
||||
}
|
||||
resolved, err := modelruntime.Resolve(modelruntime.Ref{
|
||||
Provider: params.Provider, Model: row.model, BaseURL: params.BaseURL,
|
||||
ModelType: row.typ, Extra: params.ExtraConfig, Override: params.Spec,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve failed: %v", err)
|
||||
}
|
||||
if resolved.Vendor == nil {
|
||||
t.Fatal("resolved with a nil vendor")
|
||||
}
|
||||
// Each model type resolves to its own protocol vocabulary. They
|
||||
// are separate Go types, so a row can never land on the wrong one.
|
||||
switch row.typ {
|
||||
case types.ModelTypeRerank:
|
||||
if !resolved.RerankAPI.Known() {
|
||||
t.Fatalf("resolved to an unknown rerank protocol %q", resolved.RerankAPI)
|
||||
}
|
||||
case types.ModelTypeEmbedding:
|
||||
if !resolved.EmbeddingAPI.Known() {
|
||||
t.Fatalf("resolved to an unknown embedding protocol %q", resolved.EmbeddingAPI)
|
||||
}
|
||||
default:
|
||||
if !resolved.API.Known() {
|
||||
t.Fatalf("resolved to an unknown protocol %q", resolved.API)
|
||||
}
|
||||
}
|
||||
if resolved.RemoteModel == "" && row.model != "" {
|
||||
t.Fatal("resolved to an empty remote model id")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestEveryCataloguedModelResolves walks the whole catalog so a row naming any
|
||||
// shipped model id — which is what the old model picker wrote — is known to
|
||||
// resolve.
|
||||
func TestEveryCataloguedModelResolves(t *testing.T) {
|
||||
for _, v := range modelruntime.List() {
|
||||
for _, m := range v.Models() {
|
||||
if m.ID == "" {
|
||||
continue
|
||||
}
|
||||
// An entry that declares this build cannot serve it must refuse,
|
||||
// on save as at construction; vendors_test pins that it does.
|
||||
if bytes.Contains(m.Compat, []byte("unsupported_reason")) {
|
||||
continue
|
||||
}
|
||||
modelType := m.Type
|
||||
if modelType == "" {
|
||||
modelType = types.ModelTypeKnowledgeQA
|
||||
}
|
||||
if err := modelruntime.ValidateRow(m.ID, modelType, &types.ModelParameters{Provider: v.ID}); err != nil {
|
||||
t.Errorf("%s/%s: ValidateRow: %v", v.ID, m.ID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// legacyThinkingControl is the old chat.parseThinkingOverride mapping, from
|
||||
// internal/models/chat/thinking.go before the refactor. The four values are
|
||||
// the only ones the old frontend wrote (frontend/src/utils/thinkingControl.ts),
|
||||
// but an unrecognized non-empty value historically fell back to
|
||||
// chat_template_kwargs and must keep doing so.
|
||||
var legacyThinkingControl = map[string]api.ThinkingFormat{
|
||||
"none": api.ThinkingFormatNone,
|
||||
"enable_thinking": api.ThinkingFormatEnableThinking,
|
||||
"thinking_type": api.ThinkingFormatThinkingType,
|
||||
"chat_template_kwargs": api.ThinkingFormatChatTemplateKwargs,
|
||||
"enabled": api.ThinkingFormatChatTemplateKwargs,
|
||||
"ENABLE_THINKING": api.ThinkingFormatEnableThinking,
|
||||
" thinking_type ": api.ThinkingFormatThinkingType,
|
||||
}
|
||||
|
||||
// TestLegacyThinkingControlMapping pins extra_config.thinking_control to the
|
||||
// old semantics for every value a stored row can hold, including on a
|
||||
// catalogued non-reasoning model where the new silencing pass would otherwise
|
||||
// drop the thinking fields.
|
||||
func TestLegacyThinkingControlMapping(t *testing.T) {
|
||||
for value, want := range legacyThinkingControl {
|
||||
t.Run(value, func(t *testing.T) {
|
||||
resolved, err := modelruntime.Resolve(modelruntime.Ref{
|
||||
Provider: "generic", Model: "Qwen/Qwen3-32B",
|
||||
BaseURL: "http://vllm.internal:8000/v1", ModelType: types.ModelTypeKnowledgeQA,
|
||||
Extra: map[string]string{"thinking_control": value},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
if got := resolved.OpenAICompletions.ThinkingFormat; got != want {
|
||||
t.Fatalf("thinking_control=%q resolved to %q, old code selected %q", value, got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLegacyThinkingControlSurvivesCatalogSilencing guards the interaction
|
||||
// between a stored thinking_control and silenceThinkingForNonReasoningModel:
|
||||
// an operator who explicitly picked an encoding must keep it even when the
|
||||
// catalog marks the model non-reasoning.
|
||||
func TestLegacyThinkingControlSurvivesCatalogSilencing(t *testing.T) {
|
||||
resolved, err := modelruntime.Resolve(modelruntime.Ref{
|
||||
Provider: "openai", Model: "gpt-4o", ModelType: types.ModelTypeKnowledgeQA,
|
||||
Extra: map[string]string{"thinking_control": "chat_template_kwargs"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
if resolved.OpenAICompletions.ThinkingFormat != api.ThinkingFormatChatTemplateKwargs {
|
||||
t.Fatalf("explicit thinking_control was overridden by the catalog: %q",
|
||||
resolved.OpenAICompletions.ThinkingFormat)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUncataloguedModelKeepsThinkingSwitch documents the deliberate asymmetry
|
||||
// in silenceThinkingForNonReasoningModel: a model nobody catalogued (the
|
||||
// self-hosted case) keeps its thinking switch, which is what old rows relied
|
||||
// on, while a catalogued non-reasoning model loses it.
|
||||
func TestUncataloguedModelKeepsThinkingSwitch(t *testing.T) {
|
||||
unknown, err := modelruntime.Resolve(modelruntime.Ref{
|
||||
Provider: "generic", Model: "acme/llama-3.1-70b-finetune",
|
||||
BaseURL: "http://vllm.internal:8000/v1", ModelType: types.ModelTypeKnowledgeQA,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
if unknown.Cataloged {
|
||||
t.Fatal("expected the fine-tune to be uncatalogued")
|
||||
}
|
||||
if unknown.OpenAICompletions.ThinkingFormat != api.ThinkingFormatChatTemplateKwargs {
|
||||
t.Fatalf("uncatalogued model lost its thinking switch: %q",
|
||||
unknown.OpenAICompletions.ThinkingFormat)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLegacyRemoteModelNameHonoured pins extra_config.remote_model_name, which
|
||||
// the old chat and embedding paths both read.
|
||||
func TestLegacyRemoteModelNameHonoured(t *testing.T) {
|
||||
resolved, err := modelruntime.Resolve(modelruntime.Ref{
|
||||
Provider: "generic", Model: "display-name", BaseURL: "http://vllm.internal:8000/v1",
|
||||
ModelType: types.ModelTypeKnowledgeQA,
|
||||
Extra: map[string]string{"remote_model_name": "Qwen/Qwen3-32B"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
if resolved.RemoteModel != "Qwen/Qwen3-32B" {
|
||||
t.Fatalf("remote_model_name ignored: wire model is %q", resolved.RemoteModel)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnknownProviderFallsBackToGeneric checks the reverse direction: a row
|
||||
// naming a provider this build does not ship degrades to the generic
|
||||
// OpenAI-compatible baseline instead of failing the write.
|
||||
func TestUnknownProviderFallsBackToGeneric(t *testing.T) {
|
||||
resolved, err := modelruntime.Resolve(modelruntime.Ref{
|
||||
Provider: "a-vendor-from-the-future", Model: "m",
|
||||
BaseURL: "https://example.com/v1", ModelType: types.ModelTypeKnowledgeQA,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
if resolved.Vendor.ID != providers.GenericID {
|
||||
t.Fatalf("unknown provider resolved to %q, want %q", resolved.Vendor.ID, providers.GenericID)
|
||||
}
|
||||
if resolved.API != api.APIOpenAICompletions {
|
||||
t.Fatalf("unknown provider resolved to protocol %q", resolved.API)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLegacyStoredBaseURLSelectsSameProtocol pins the protocol an existing
|
||||
// row resolves to. Old rows always store an explicit base_url (the model
|
||||
// editor pre-filled the provider default), so the stored URL — not the new
|
||||
// vendor default — decides the wire protocol on upgrade. The Gemini case and
|
||||
// the first-party OpenAI move to Responses are covered in
|
||||
// internal/models/parity; what is asserted here is the relay case, where the
|
||||
// same provider id must NOT follow OpenAI onto /responses.
|
||||
func TestLegacyStoredBaseURLSelectsSameProtocol(t *testing.T) {
|
||||
cases := []struct {
|
||||
provider, baseURL string
|
||||
want api.API
|
||||
why string
|
||||
}{
|
||||
{
|
||||
provider: "openai", baseURL: "https://llm-relay.corp.example.com/v1",
|
||||
want: api.APIOpenAICompletions,
|
||||
why: "a relay that only speaks Chat Completions must stay on it",
|
||||
},
|
||||
{
|
||||
provider: "openai", baseURL: "https://litellm.corp.example.com/v1",
|
||||
want: api.APIOpenAICompletions,
|
||||
why: "an OpenAI row pointed at a LiteLLM proxy keeps Chat Completions",
|
||||
},
|
||||
{
|
||||
provider: "anthropic", baseURL: "https://api.anthropic.com/v1",
|
||||
want: api.APIAnthropicMessages,
|
||||
why: "the old code already dispatched anthropic to the Messages protocol",
|
||||
},
|
||||
{
|
||||
provider: "generic", baseURL: "http://vllm.internal:8000/v1",
|
||||
want: api.APIOpenAICompletions, why: "unchanged",
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.provider+" "+tc.baseURL, func(t *testing.T) {
|
||||
resolved, err := modelruntime.Resolve(modelruntime.Ref{
|
||||
Provider: tc.provider, Model: "some-model", BaseURL: tc.baseURL,
|
||||
ModelType: types.ModelTypeKnowledgeQA,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve: %v", err)
|
||||
}
|
||||
if resolved.API != tc.want {
|
||||
t.Fatalf("protocol %q, want %q (%s)", resolved.API, tc.want, tc.why)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLegacyFreeFormAPIExtraKeyIsRejected documents the one stored shape this
|
||||
// refactor does break, so the trade-off stays visible.
|
||||
//
|
||||
// extra_config has always been a free-form map[string]string: the old backend
|
||||
// read only thinking_control, remote_model_name, api_version, secret_key,
|
||||
// region, instruction and truncate_prompt_tokens from it and ignored every
|
||||
// other key. The catalog gave the key "api" a meaning — it forces the wire
|
||||
// protocol — and ValidateRow now rejects a value that is not one of the five
|
||||
// protocol names. A row that an operator hand-populated with, say,
|
||||
// {"api": "v1"} therefore fails PUT /models/{id} with 400 and fails every
|
||||
// chat call, even though nothing about that row changed.
|
||||
//
|
||||
// Nothing in Academy ever wrote this key, so only hand-built rows and
|
||||
// hand-written builtin_models.yaml entries are affected. If that is judged too
|
||||
// sharp, the fix is to ignore an unparseable extra_config.api in Resolve and
|
||||
// keep the strict check for Spec.API, which no old row can carry.
|
||||
func TestLegacyFreeFormAPIExtraKeyIsRejected(t *testing.T) {
|
||||
err := modelruntime.ValidateRow("gpt-4o", types.ModelTypeKnowledgeQA, &types.ModelParameters{
|
||||
Provider: "openai", BaseURL: "https://api.openai.com/v1",
|
||||
ExtraConfig: map[string]string{"api": "v1"},
|
||||
})
|
||||
if err == nil {
|
||||
t.Skip("extra_config.api is now tolerant of legacy free-form values; " +
|
||||
"delete this test and the release note that goes with it")
|
||||
}
|
||||
t.Logf("documented break: %v", err)
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"academy/internal/models"
|
||||
"academy/internal/models/api"
|
||||
"academy/internal/models/catalog"
|
||||
"academy/internal/models/internal/configcopy"
|
||||
"academy/internal/models/providers"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// OverlayFile is the schema of config/models.json. It mirrors pi's
|
||||
// ~/.pi/agent/models.json: a "providers" object keyed by provider id where
|
||||
// each entry either patches a built-in vendor or declares a new one.
|
||||
type OverlayFile struct {
|
||||
Providers map[string]OverlayProvider `json:"providers"`
|
||||
}
|
||||
|
||||
// OverlayProvider patches or declares one vendor.
|
||||
type OverlayProvider struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Names map[string]string `json:"names,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Descriptions map[string]string `json:"descriptions,omitempty"`
|
||||
Website string `json:"website,omitempty"`
|
||||
// API is the default chat protocol for new vendors (and overrides it
|
||||
// for built-in ones).
|
||||
API api.API `json:"api,omitempty"`
|
||||
// BaseURL sets the chat base URL; BaseURLs sets per-type URLs keyed by
|
||||
// chat | embedding | rerank | vlm | asr.
|
||||
BaseURL string `json:"base_url,omitempty"`
|
||||
BaseURLs map[string]string `json:"base_urls,omitempty"`
|
||||
// APIKey is the deployment-level key used when a model row stores none.
|
||||
// Supports ${ENV} / $ENV interpolation.
|
||||
APIKey string `json:"api_key,omitempty"`
|
||||
Headers map[string]string `json:"headers,omitempty"`
|
||||
Auth providers.AuthStyle `json:"auth,omitempty"`
|
||||
RequiresAuth *bool `json:"requires_auth,omitempty"`
|
||||
ModelTypes []string `json:"model_types,omitempty"`
|
||||
URLPatterns []string `json:"url_patterns,omitempty"`
|
||||
// Icon is a path to an SVG file (relative to the overlay file) or an
|
||||
// inline "<svg ...>" string.
|
||||
Icon string `json:"icon,omitempty"`
|
||||
// Compat is the flat protocol overlay applied at vendor level for API.
|
||||
Compat json.RawMessage `json:"compat,omitempty"`
|
||||
// ThinkingLevels patches the vendor level map.
|
||||
ThinkingLevels map[string]*string `json:"thinking_levels,omitempty"`
|
||||
// Models are upserted by id into the vendor catalog. Entries stay raw so
|
||||
// an upsert against an existing id can patch only the keys the operator
|
||||
// actually wrote (see applyOverlayProvider).
|
||||
Models []json.RawMessage `json:"models,omitempty"`
|
||||
// ModelOverrides patch existing entries by id without restating them.
|
||||
ModelOverrides map[string]ModelSpecPatch `json:"model_overrides,omitempty"`
|
||||
}
|
||||
|
||||
// ModelSpecPatch is a partial models.ModelSpec.
|
||||
type ModelSpecPatch struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
API api.API `json:"api,omitempty"`
|
||||
Reasoning *bool `json:"reasoning,omitempty"`
|
||||
Input []string `json:"input,omitempty"`
|
||||
ContextWindow int `json:"context_window,omitempty"`
|
||||
MaxOutputTokens int `json:"max_output_tokens,omitempty"`
|
||||
Cost *models.ModelCost `json:"cost,omitempty"`
|
||||
ThinkingLevels api.ThinkingLevelMap `json:"thinking_levels,omitempty"`
|
||||
Compat json.RawMessage `json:"compat,omitempty"`
|
||||
Aliases []string `json:"aliases,omitempty"`
|
||||
Deprecated *bool `json:"deprecated,omitempty"`
|
||||
}
|
||||
|
||||
var envPattern = regexp.MustCompile(`\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)`)
|
||||
|
||||
// interpolateEnv expands ${NAME} and $NAME. Unset variables expand to the
|
||||
// empty string so a missing key fails loudly upstream rather than sending
|
||||
// the literal placeholder.
|
||||
func interpolateEnv(s string) string {
|
||||
return envPattern.ReplaceAllStringFunc(s, func(m string) string {
|
||||
name := strings.Trim(strings.TrimPrefix(m, "$"), "{}")
|
||||
return os.Getenv(name)
|
||||
})
|
||||
}
|
||||
|
||||
// LoadOverlay reads config/models.json (or the path in MODELS_CONFIG) and
|
||||
// applies it to the registry. A missing file is not an error.
|
||||
func (rt *Runtime) LoadOverlay(configDir string) error {
|
||||
return rt.loadOverlayValidated(configDir, nil)
|
||||
}
|
||||
|
||||
// ReadDeploymentOverlay reads config/models.json (or the path in
|
||||
// MODELS_CONFIG). A missing file returns nil data and no error; baseDir
|
||||
// resolves the overlay's relative icon paths.
|
||||
func ReadDeploymentOverlay(configDir string) (data []byte, baseDir string, err error) {
|
||||
path := os.Getenv("MODELS_CONFIG")
|
||||
if path == "" {
|
||||
path = filepath.Join(configDir, "models.json")
|
||||
}
|
||||
data, err = os.ReadFile(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, "", nil
|
||||
}
|
||||
return nil, "", fmt.Errorf("read %s: %w", path, err)
|
||||
}
|
||||
return data, filepath.Dir(path), nil
|
||||
}
|
||||
|
||||
// loadOverlayValidated validates every candidate before publishing a generation.
|
||||
func (rt *Runtime) loadOverlayValidated(configDir string, validate func(*Provider) error) error {
|
||||
data, baseDir, err := ReadDeploymentOverlay(configDir)
|
||||
if err != nil || data == nil {
|
||||
return err
|
||||
}
|
||||
return rt.applyOverlayValidated(data, baseDir, validate)
|
||||
}
|
||||
|
||||
// ApplyOverlay applies overlay JSON to the registry. baseDir resolves
|
||||
// relative icon paths.
|
||||
func (rt *Runtime) ApplyOverlay(data []byte, baseDir string) error {
|
||||
return rt.applyOverlayValidated(data, baseDir, nil)
|
||||
}
|
||||
|
||||
// applyOverlayValidated rebuilds the overlay and validates it transactionally.
|
||||
// The validator must not access the live registry while the writer lock is held.
|
||||
func (rt *Runtime) applyOverlayValidated(data []byte, baseDir string, validate func(*Provider) error) error {
|
||||
var file OverlayFile
|
||||
dec := json.NewDecoder(bytesReader(data))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&file); err != nil {
|
||||
return fmt.Errorf("parse models overlay: %w", err)
|
||||
}
|
||||
if err := dec.Decode(new(any)); err != io.EOF {
|
||||
return fmt.Errorf("parse models overlay: expected a single JSON document")
|
||||
}
|
||||
// Build a fresh generation under the registry lock, then publish once.
|
||||
// A failure leaves both the current generation and built-in baseline intact.
|
||||
rt.mu.Lock()
|
||||
defer rt.mu.Unlock()
|
||||
next := cloneProviders(rt.builtins)
|
||||
for id, p := range file.Providers {
|
||||
id = strings.ToLower(strings.TrimSpace(id))
|
||||
if id == "" {
|
||||
return fmt.Errorf("provider id is empty")
|
||||
}
|
||||
vendor, exists := next[id]
|
||||
if !exists {
|
||||
vendor = &Provider{Definition: &providers.Definition{
|
||||
ID: id,
|
||||
Name: id,
|
||||
API: api.APIOpenAICompletions,
|
||||
DefaultBaseURLs: map[types.ModelType]string{},
|
||||
ModelTypes: []types.ModelType{
|
||||
types.ModelTypeKnowledgeQA,
|
||||
},
|
||||
RequiresAuth: true,
|
||||
Auth: providers.AuthBearer,
|
||||
Order: 1000,
|
||||
}, catalog: catalog.New(nil)}
|
||||
}
|
||||
if err := applyOverlayProvider(vendor, p, baseDir); err != nil {
|
||||
return fmt.Errorf("provider %s: %w", id, err)
|
||||
}
|
||||
normalizeProvider(vendor)
|
||||
if validate != nil {
|
||||
if err := validate(vendor); err != nil {
|
||||
return fmt.Errorf("provider %s: %w", id, err)
|
||||
}
|
||||
}
|
||||
next[id] = vendor
|
||||
}
|
||||
rt.providers = next
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyOverlayProvider(v *Provider, p OverlayProvider, baseDir string) error {
|
||||
entries := v.Models()
|
||||
if p.Name != "" {
|
||||
v.Name = p.Name
|
||||
}
|
||||
if len(p.Names) > 0 {
|
||||
v.Names = p.Names
|
||||
}
|
||||
if p.Description != "" {
|
||||
v.Description = p.Description
|
||||
}
|
||||
if len(p.Descriptions) > 0 {
|
||||
v.Descriptions = p.Descriptions
|
||||
}
|
||||
if p.Website != "" {
|
||||
v.Website = p.Website
|
||||
}
|
||||
if p.API != "" {
|
||||
if !p.API.Known() {
|
||||
return fmt.Errorf("unknown api %q", p.API)
|
||||
}
|
||||
v.API = p.API
|
||||
}
|
||||
if p.BaseURL != "" {
|
||||
v.DefaultBaseURLs[types.ModelTypeKnowledgeQA] = interpolateEnv(p.BaseURL)
|
||||
}
|
||||
for k, u := range p.BaseURLs {
|
||||
t, ok := models.ParseModelType(k)
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown model type %q in base_urls", k)
|
||||
}
|
||||
v.DefaultBaseURLs[t] = interpolateEnv(u)
|
||||
}
|
||||
if p.APIKey != "" {
|
||||
v.DefaultAPIKey = interpolateEnv(p.APIKey)
|
||||
}
|
||||
if len(p.Headers) > 0 {
|
||||
headers := make(map[string]string, len(p.Headers))
|
||||
for k, val := range p.Headers {
|
||||
headers[k] = interpolateEnv(val)
|
||||
}
|
||||
v.Headers = headers
|
||||
}
|
||||
if p.Auth != "" {
|
||||
v.Auth = p.Auth
|
||||
}
|
||||
if p.RequiresAuth != nil {
|
||||
v.RequiresAuth = *p.RequiresAuth
|
||||
}
|
||||
if len(p.ModelTypes) > 0 {
|
||||
v.ModelTypes = v.ModelTypes[:0]
|
||||
for _, s := range p.ModelTypes {
|
||||
t, ok := models.ParseModelType(s)
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown model type %q", s)
|
||||
}
|
||||
v.ModelTypes = append(v.ModelTypes, t)
|
||||
}
|
||||
}
|
||||
if len(p.URLPatterns) > 0 {
|
||||
v.URLPatterns = p.URLPatterns
|
||||
}
|
||||
if p.Icon != "" {
|
||||
icon, err := loadOverlayIcon(baseDir, p.Icon)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v.Icon = icon
|
||||
}
|
||||
if len(p.Compat) > 0 {
|
||||
var err error
|
||||
switch v.API {
|
||||
case api.APIOpenAICompletions:
|
||||
err = DecodeCompat(p.Compat, &v.Compat.OpenAICompletions)
|
||||
case api.APIOpenAIResponses:
|
||||
err = DecodeCompat(p.Compat, &v.Compat.OpenAIResponses)
|
||||
case api.APIAnthropicMessages:
|
||||
err = DecodeCompat(p.Compat, &v.Compat.AnthropicMessages)
|
||||
case api.APIGoogleGenerativeAI:
|
||||
err = DecodeCompat(p.Compat, &v.Compat.GoogleGenerativeAI)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if len(p.ThinkingLevels) > 0 {
|
||||
levels := api.ThinkingLevelMap{}
|
||||
for k, val := range v.ThinkingLevels {
|
||||
levels[k] = val
|
||||
}
|
||||
for k, val := range p.ThinkingLevels {
|
||||
levels[api.ReasoningEffort(k)] = val
|
||||
}
|
||||
v.ThinkingLevels = levels
|
||||
}
|
||||
for _, raw := range p.Models {
|
||||
if err := upsertOverlayModel(&entries, raw); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for id, patch := range p.ModelOverrides {
|
||||
matches := 0
|
||||
for _, m := range entries {
|
||||
if strings.EqualFold(m.ID, id) {
|
||||
matches++
|
||||
}
|
||||
}
|
||||
if matches > 1 {
|
||||
return fmt.Errorf("model_overrides %s matches multiple types; use models with an explicit type", id)
|
||||
}
|
||||
found := false
|
||||
for i := range entries {
|
||||
if strings.EqualFold(entries[i].ID, id) {
|
||||
// Keep the candidate entry independent while applying the patch.
|
||||
spec := cloneModelSpec(entries[i])
|
||||
applyPatch(&spec, patch)
|
||||
entries[i] = spec
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
spec := models.ModelSpec{ID: id}
|
||||
applyPatch(&spec, patch)
|
||||
entries = append(entries, spec)
|
||||
}
|
||||
}
|
||||
v.catalog = catalog.New(entries)
|
||||
return nil
|
||||
}
|
||||
|
||||
// maxIconBytes caps a vendor icon. Icons are base64'd into every
|
||||
// GET /models/providers response, so an oversized file is a response-size
|
||||
// problem for every viewer, not just a disk read.
|
||||
const maxIconBytes = 256 * 1024
|
||||
|
||||
// loadOverlayIcon resolves providers.*.icon to SVG bytes.
|
||||
//
|
||||
// The bytes are handed to every viewer of the model pages as a data: URI, so
|
||||
// the path is treated as untrusted even though writing the overlay already
|
||||
// requires filesystem access: an operator (or a config-management template)
|
||||
// that points `icon` at /etc/shadow or ../../secrets must not turn the
|
||||
// provider list into a file-disclosure endpoint for read-only tenants.
|
||||
// Hence: no absolute paths, no escaping the overlay's own directory
|
||||
// (symlinks included), a size cap, and the content must really be an SVG.
|
||||
func loadOverlayIcon(baseDir, ref string) ([]byte, error) {
|
||||
if looksLikeSVG([]byte(ref)) {
|
||||
if len(ref) > maxIconBytes {
|
||||
return nil, fmt.Errorf("icon: inline svg is %d bytes, limit is %d", len(ref), maxIconBytes)
|
||||
}
|
||||
return []byte(ref), nil
|
||||
}
|
||||
if filepath.IsAbs(ref) || strings.HasPrefix(ref, "/") || filepath.VolumeName(ref) != "" {
|
||||
return nil, fmt.Errorf("icon: absolute paths are not allowed: %q", ref)
|
||||
}
|
||||
clean := filepath.Clean(filepath.FromSlash(ref))
|
||||
if clean == ".." || strings.HasPrefix(clean, ".."+string(filepath.Separator)) {
|
||||
return nil, fmt.Errorf("icon: path escapes the overlay directory: %q", ref)
|
||||
}
|
||||
if baseDir == "" {
|
||||
baseDir = "."
|
||||
}
|
||||
full, err := resolveInsideDir(baseDir, clean)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("icon: %w", err)
|
||||
}
|
||||
info, err := os.Stat(full)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read icon: %w", err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return nil, fmt.Errorf("icon: %q is not a regular file", ref)
|
||||
}
|
||||
if info.Size() > maxIconBytes {
|
||||
return nil, fmt.Errorf("icon: %q is %d bytes, limit is %d", ref, info.Size(), maxIconBytes)
|
||||
}
|
||||
data, err := os.ReadFile(full)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read icon: %w", err)
|
||||
}
|
||||
if len(data) > maxIconBytes {
|
||||
return nil, fmt.Errorf("icon: %q is %d bytes, limit is %d", ref, len(data), maxIconBytes)
|
||||
}
|
||||
if !looksLikeSVG(data) {
|
||||
return nil, fmt.Errorf("icon: %q is not an SVG document", ref)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// resolveInsideDir joins rel onto dir and fails unless the result stays
|
||||
// inside it. Both sides are resolved through EvalSymlinks so a symlink
|
||||
// planted in the overlay directory cannot point out of it; a path that does
|
||||
// not exist is compared unresolved and left to the caller's os.Stat, which
|
||||
// reports it with a clearer message.
|
||||
func resolveInsideDir(dir, rel string) (string, error) {
|
||||
realDir, err := filepath.EvalSymlinks(dir)
|
||||
if err != nil {
|
||||
realDir = filepath.Clean(dir)
|
||||
}
|
||||
full := filepath.Join(realDir, rel)
|
||||
if resolved, err := filepath.EvalSymlinks(full); err == nil {
|
||||
full = resolved
|
||||
}
|
||||
if full != realDir && !strings.HasPrefix(full, realDir+string(filepath.Separator)) {
|
||||
return "", fmt.Errorf("path escapes the overlay directory: %q", rel)
|
||||
}
|
||||
return full, nil
|
||||
}
|
||||
|
||||
// looksLikeSVG reports whether data is an SVG document: an optional XML
|
||||
// prologue (declaration, doctype, comments, whitespace) followed by <svg.
|
||||
func looksLikeSVG(data []byte) bool {
|
||||
s := strings.TrimPrefix(string(data), "\ufeff")
|
||||
for {
|
||||
s = strings.TrimSpace(s)
|
||||
switch {
|
||||
case strings.HasPrefix(s, "<?"):
|
||||
s = skipPast(s, "?>")
|
||||
case strings.HasPrefix(s, "<!--"):
|
||||
s = skipPast(s, "-->")
|
||||
case strings.HasPrefix(s, "<!"):
|
||||
s = skipPast(s, ">")
|
||||
default:
|
||||
lower := strings.ToLower(s)
|
||||
if !strings.HasPrefix(lower, "<svg") || len(lower) == len("<svg") {
|
||||
return false
|
||||
}
|
||||
// Reject "<svgfoo": the tag must end right after the name.
|
||||
return strings.ContainsRune(" \t\r\n>/", rune(lower[len("<svg")]))
|
||||
}
|
||||
if s == "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// skipPast returns what follows the first occurrence of end, or "" if the
|
||||
// token never closes.
|
||||
func skipPast(s, end string) string {
|
||||
i := strings.Index(s, end)
|
||||
if i < 0 {
|
||||
return ""
|
||||
}
|
||||
return s[i+len(end):]
|
||||
}
|
||||
|
||||
// upsertOverlayModel applies one providers.*.models entry.
|
||||
//
|
||||
// A new id creates a full entry. An id that already exists is *patched*, not
|
||||
// replaced: both config/models.json.example and the docs present `models` as
|
||||
// the way to restate a known model with corrected facts, and most fields of
|
||||
// models.ModelSpec cannot tell "absent" from "zero" — Reasoning is a plain bool, so
|
||||
// an entry that only fixes context_window used to silently turn reasoning
|
||||
// off and drop thinking levels, compat and input along with it. Unmarshaling
|
||||
// the operator's JSON onto a copy of the stored entry leaves every key they
|
||||
// did not write exactly as it was.
|
||||
func upsertOverlayModel(target *[]models.ModelSpec, raw json.RawMessage) error {
|
||||
entries := *target
|
||||
defer func() { *target = entries }()
|
||||
// Decode strictly first: this is what rejects typos and wrong types, the
|
||||
// same guarantee the rest of the overlay gives. The value is used only
|
||||
// for the id, since the merge below re-reads the raw bytes.
|
||||
var spec models.ModelSpec
|
||||
dec := json.NewDecoder(bytesReader(raw))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&spec); err != nil {
|
||||
return fmt.Errorf("model entry: %w", err)
|
||||
}
|
||||
if spec.ID == "" {
|
||||
return fmt.Errorf("model without id")
|
||||
}
|
||||
if spec.Type == "" {
|
||||
matches := 0
|
||||
for _, m := range entries {
|
||||
if strings.EqualFold(m.ID, spec.ID) {
|
||||
matches++
|
||||
}
|
||||
}
|
||||
if matches > 1 {
|
||||
return fmt.Errorf("model %s matches multiple types; specify type", spec.ID)
|
||||
}
|
||||
}
|
||||
for i := range entries {
|
||||
if !strings.EqualFold(entries[i].ID, spec.ID) {
|
||||
continue
|
||||
}
|
||||
if spec.Type != "" && catalog.EntryType(entries[i].Type) != catalog.EntryType(spec.Type) {
|
||||
continue
|
||||
}
|
||||
// Decode into an owned entry so a failed patch never modifies the catalog.
|
||||
merged := cloneModelSpec(entries[i])
|
||||
if err := json.Unmarshal(raw, &merged); err != nil {
|
||||
return fmt.Errorf("model %s: %w", spec.ID, err)
|
||||
}
|
||||
entries[i] = merged
|
||||
return nil
|
||||
}
|
||||
entries = append(entries, spec)
|
||||
return nil
|
||||
}
|
||||
|
||||
// cloneModelSpec deep-copies the reference-typed fields of a spec.
|
||||
func cloneModelSpec(m models.ModelSpec) models.ModelSpec {
|
||||
return configcopy.Clone(m)
|
||||
}
|
||||
|
||||
func applyPatch(m *models.ModelSpec, p ModelSpecPatch) {
|
||||
if p.Name != "" {
|
||||
m.Name = p.Name
|
||||
}
|
||||
if p.API != "" {
|
||||
m.API = p.API
|
||||
}
|
||||
if p.Reasoning != nil {
|
||||
m.Reasoning = *p.Reasoning
|
||||
}
|
||||
if len(p.Input) > 0 {
|
||||
m.Input = p.Input
|
||||
}
|
||||
if p.ContextWindow > 0 {
|
||||
m.ContextWindow = p.ContextWindow
|
||||
}
|
||||
if p.MaxOutputTokens > 0 {
|
||||
m.MaxOutputTokens = p.MaxOutputTokens
|
||||
}
|
||||
if p.Cost != nil {
|
||||
m.Cost = p.Cost
|
||||
}
|
||||
if len(p.ThinkingLevels) > 0 {
|
||||
levels := api.ThinkingLevelMap{}
|
||||
for k, v := range m.ThinkingLevels {
|
||||
levels[k] = v
|
||||
}
|
||||
for k, v := range p.ThinkingLevels {
|
||||
levels[k] = v
|
||||
}
|
||||
m.ThinkingLevels = levels
|
||||
}
|
||||
if len(p.Compat) > 0 {
|
||||
m.Compat = mergeRawObjects(m.Compat, p.Compat)
|
||||
}
|
||||
if len(p.Aliases) > 0 {
|
||||
m.Aliases = append(m.Aliases, p.Aliases...)
|
||||
}
|
||||
if p.Deprecated != nil {
|
||||
m.Deprecated = *p.Deprecated
|
||||
}
|
||||
}
|
||||
|
||||
// mergeRawObjects shallow-merges two JSON objects (b wins).
|
||||
func mergeRawObjects(a, b json.RawMessage) json.RawMessage {
|
||||
merged := map[string]json.RawMessage{}
|
||||
if len(a) > 0 {
|
||||
_ = json.Unmarshal(a, &merged)
|
||||
}
|
||||
patch := map[string]json.RawMessage{}
|
||||
if len(b) > 0 {
|
||||
_ = json.Unmarshal(b, &patch)
|
||||
}
|
||||
for k, v := range patch {
|
||||
merged[k] = v
|
||||
}
|
||||
out, _ := json.Marshal(merged)
|
||||
return out
|
||||
}
|
||||
|
||||
// ApplyOverlay and LoadOverlay retain the legacy unvalidated composition API.
|
||||
// Application configuration uses Initialize/Reload, which validate before publication.
|
||||
func ApplyOverlay(data []byte, baseDir string) error { return Default().ApplyOverlay(data, baseDir) }
|
||||
|
||||
// LoadOverlay loads deployment JSON into the default runtime without resolution validation.
|
||||
func LoadOverlay(configDir string) error { return Default().LoadOverlay(configDir) }
|
||||
@@ -0,0 +1,183 @@
|
||||
package runtime_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/models/api"
|
||||
modelruntime "academy/internal/models/runtime"
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// An overlay entry under "models" that restates an existing id must patch it.
|
||||
// The docs and config/models.json.example both present "models" as the way to
|
||||
// correct a known model, and ModelSpec cannot tell absent from zero: before
|
||||
// this, fixing max_output_tokens alone silently cleared reasoning (a plain
|
||||
// bool), the thinking levels, the compat overlay and the input modalities.
|
||||
func TestApplyOverlay_ModelsUpsertPatchesExistingEntry(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
overlay := `{"providers": {"acme": {"models": [
|
||||
{"id": "acme-pro", "max_output_tokens": 8192},
|
||||
{"id": "acme-r1", "context_window": 128000}
|
||||
]}}}`
|
||||
require.NoError(t, modelruntime.ApplyOverlay([]byte(overlay), t.TempDir()))
|
||||
|
||||
r, err := modelruntime.Resolve(modelruntime.Ref{Provider: "acme", Model: "acme-pro"})
|
||||
require.NoError(t, err)
|
||||
assert.True(t, r.Spec.Reasoning, "omitted reasoning must not turn thinking off")
|
||||
assert.Equal(t, []string{"text", "image"}, r.Spec.Input, "omitted input survives")
|
||||
assert.Equal(t, 200000, r.Spec.ContextWindow, "omitted context_window survives")
|
||||
assert.Equal(t, 8192, r.Spec.MaxOutputTokens, "the field that was written is applied")
|
||||
assert.False(t, r.OpenAICompletions.SupportsTemperature, "omitted compat survives")
|
||||
|
||||
r, err = modelruntime.Resolve(modelruntime.Ref{Provider: "acme", Model: "acme-r1"})
|
||||
require.NoError(t, err)
|
||||
assert.True(t, r.Spec.Reasoning)
|
||||
assert.Equal(t, 128000, r.Spec.ContextWindow)
|
||||
assert.False(t, r.ThinkingLevels.Supports(api.ReasoningOff),
|
||||
"omitted thinking_levels survive: acme-r1 still cannot be switched off")
|
||||
}
|
||||
|
||||
// Patching must not write through to the built-in definition: the vendor copy
|
||||
// made by ApplyOverlay is shallow, so the spec's slices and maps are shared
|
||||
// with the vendor package's own (package-level) models.json data.
|
||||
func TestApplyOverlay_ModelsUpsertDoesNotMutateBuiltinVendor(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
builtin, ok := modelruntime.Get("acme")
|
||||
require.True(t, ok)
|
||||
|
||||
overlay := `{"providers": {"acme": {"models": [{"id": "acme-pro", "input": ["audio"]}]}}}`
|
||||
require.NoError(t, modelruntime.ApplyOverlay([]byte(overlay), t.TempDir()))
|
||||
|
||||
require.Equal(t, "acme-pro", builtin.Models()[0].ID)
|
||||
assert.Equal(t, []string{"text", "image"}, builtin.Models()[0].Input,
|
||||
"the built-in spec must be untouched by the overlay")
|
||||
|
||||
r, err := modelruntime.Resolve(modelruntime.Ref{Provider: "acme", Model: "acme-pro"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"audio"}, r.Spec.Input, "the written field is still applied")
|
||||
}
|
||||
|
||||
func TestApplyOverlay_ModelsUpsertExplicitFalseAndNewEntries(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
overlay := `{"providers": {"acme": {"models": [
|
||||
{"id": "acme-pro", "reasoning": false},
|
||||
{"id": "acme-ultra", "context_window": 400000}
|
||||
]}}}`
|
||||
require.NoError(t, modelruntime.ApplyOverlay([]byte(overlay), t.TempDir()))
|
||||
|
||||
r, err := modelruntime.Resolve(modelruntime.Ref{Provider: "acme", Model: "acme-pro"})
|
||||
require.NoError(t, err)
|
||||
assert.False(t, r.Spec.Reasoning, "an explicit false still turns reasoning off")
|
||||
|
||||
r, err = modelruntime.Resolve(modelruntime.Ref{Provider: "acme", Model: "acme-ultra"})
|
||||
require.NoError(t, err)
|
||||
assert.True(t, r.Cataloged, "an unknown id creates a full entry")
|
||||
assert.Equal(t, 400000, r.Spec.ContextWindow)
|
||||
assert.False(t, r.Spec.Reasoning)
|
||||
}
|
||||
|
||||
func TestApplyOverlay_ModelsEntryValidation(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
dir := t.TempDir()
|
||||
assert.ErrorContains(t,
|
||||
modelruntime.ApplyOverlay([]byte(`{"providers": {"acme": {"models": [{"id": "x", "bogus": 1}]}}}`), dir),
|
||||
"bogus", "unknown keys inside a model entry are still rejected")
|
||||
assert.ErrorContains(t,
|
||||
modelruntime.ApplyOverlay([]byte(`{"providers": {"acme": {"models": [{"context_window": 1}]}}}`), dir),
|
||||
"model without id")
|
||||
}
|
||||
|
||||
const testSVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"></svg>`
|
||||
|
||||
func overlayWithIcon(icon string) string {
|
||||
return `{"providers": {"lab": {"icon": ` + quoteJSON(icon) + `}}}`
|
||||
}
|
||||
|
||||
// quoteJSON is enough for the paths used here (no escaping needed).
|
||||
func quoteJSON(s string) string { return `"` + strings.ReplaceAll(s, `"`, `\"`) + `"` }
|
||||
|
||||
func TestApplyOverlay_IconAcceptsInlineAndContainedFiles(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
dir := t.TempDir()
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(dir, "icons"), 0o755))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "icons", "lab.svg"), []byte(testSVG), 0o600))
|
||||
|
||||
require.NoError(t, modelruntime.ApplyOverlay([]byte(overlayWithIcon("icons/lab.svg")), dir))
|
||||
lab, ok := modelruntime.Get("lab")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, testSVG, string(lab.Icon))
|
||||
|
||||
require.NoError(t, modelruntime.ApplyOverlay([]byte(overlayWithIcon("<svg><rect/></svg>")), dir))
|
||||
lab, _ = modelruntime.Get("lab")
|
||||
assert.Equal(t, "<svg><rect/></svg>", string(lab.Icon))
|
||||
}
|
||||
|
||||
// The icon bytes are served as a data: URI to every viewer of the model
|
||||
// pages, so an overlay must not be able to turn the provider list into a
|
||||
// file-disclosure endpoint.
|
||||
func TestApplyOverlay_IconRejectsUncontainedPaths(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
dir := t.TempDir()
|
||||
outside := filepath.Join(t.TempDir(), "secret.svg")
|
||||
require.NoError(t, os.WriteFile(outside, []byte(testSVG), 0o600))
|
||||
|
||||
assert.ErrorContains(t, modelruntime.ApplyOverlay([]byte(overlayWithIcon(outside)), dir),
|
||||
"absolute paths are not allowed")
|
||||
assert.ErrorContains(t, modelruntime.ApplyOverlay([]byte(overlayWithIcon("/etc/passwd")), dir),
|
||||
"absolute paths are not allowed")
|
||||
assert.ErrorContains(t, modelruntime.ApplyOverlay([]byte(overlayWithIcon("../secret.svg")), dir),
|
||||
"escapes the overlay directory")
|
||||
assert.ErrorContains(t, modelruntime.ApplyOverlay([]byte(overlayWithIcon("icons/../../secret.svg")), dir),
|
||||
"escapes the overlay directory")
|
||||
|
||||
link := filepath.Join(dir, "link.svg")
|
||||
if err := os.Symlink(outside, link); err == nil {
|
||||
assert.ErrorContains(t, modelruntime.ApplyOverlay([]byte(overlayWithIcon("link.svg")), dir),
|
||||
"escapes the overlay directory", "a symlink out of the directory is still out of it")
|
||||
}
|
||||
|
||||
_, exists := modelruntime.Get("lab")
|
||||
assert.False(t, exists, "a rejected icon must not register the provider")
|
||||
}
|
||||
|
||||
func TestApplyOverlay_IconRejectsNonSVGAndOversizedFiles(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
dir := t.TempDir()
|
||||
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "passwd.svg"), []byte("root:x:0:0:root:/root:/bin/sh\n"), 0o600))
|
||||
assert.ErrorContains(t,
|
||||
modelruntime.ApplyOverlay([]byte(overlayWithIcon("passwd.svg")), dir), "not an SVG document")
|
||||
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "png.svg"), []byte("\x89PNG\r\n\x1a\n"), 0o600))
|
||||
assert.ErrorContains(t, modelruntime.ApplyOverlay([]byte(overlayWithIcon("png.svg")), dir), "not an SVG document")
|
||||
|
||||
big := append([]byte(`<svg xmlns="http://www.w3.org/2000/svg">`), make([]byte, 256*1024)...)
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "big.svg"), big, 0o600))
|
||||
assert.ErrorContains(t, modelruntime.ApplyOverlay([]byte(overlayWithIcon("big.svg")), dir), "limit is")
|
||||
|
||||
require.NoError(t, os.MkdirAll(filepath.Join(dir, "dir.svg"), 0o755))
|
||||
assert.ErrorContains(t, modelruntime.ApplyOverlay([]byte(overlayWithIcon("dir.svg")), dir), "not a regular file")
|
||||
|
||||
assert.ErrorContains(t, modelruntime.ApplyOverlay([]byte(overlayWithIcon("missing.svg")), dir), "read icon")
|
||||
}
|
||||
|
||||
// The icon path is relative to the overlay file's own directory.
|
||||
func TestLoadOverlay_ResolvesIconRelativeToConfigDir(t *testing.T) {
|
||||
registerTestVendors(t)
|
||||
dir := t.TempDir()
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "lab.svg"), []byte(testSVG), 0o600))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(dir, "models.json"),
|
||||
[]byte(overlayWithIcon("lab.svg")), 0o600))
|
||||
t.Setenv("MODELS_CONFIG", "")
|
||||
|
||||
require.NoError(t, modelruntime.LoadOverlay(dir))
|
||||
lab, ok := modelruntime.Get("lab")
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, testSVG, string(lab.Icon))
|
||||
assert.Equal(t, []types.ModelType{types.ModelTypeKnowledgeQA}, lab.ModelTypes)
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package runtime_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"academy/internal/models/api"
|
||||
"academy/internal/models/providers"
|
||||
modelruntime "academy/internal/models/runtime"
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestExplicitChatProtocolSurvivesVendorPreference(t *testing.T) {
|
||||
for _, protocol := range []api.API{api.APIOpenAICompletions, api.APIOpenAIResponses} {
|
||||
r, err := modelruntime.Resolve(
|
||||
modelruntime.Ref{
|
||||
Provider: "openai",
|
||||
Model: "gpt-5",
|
||||
BaseURL: "https://api.openai.com/v1",
|
||||
Override: &types.ModelSpecOverride{
|
||||
API: string(
|
||||
protocol,
|
||||
),
|
||||
},
|
||||
},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, protocol, r.API)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtocolOverrideDoesNotDecodeCatalogCompatAsAnotherProtocol(t *testing.T) {
|
||||
r, err := modelruntime.Resolve(modelruntime.Ref{
|
||||
Provider: "aliyun", Model: "qwen-plus",
|
||||
Override: &types.ModelSpecOverride{
|
||||
API: string(api.APIAnthropicMessages),
|
||||
Compat: map[string]any{"thinking_mode": "adaptive"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, api.APIAnthropicMessages, r.API)
|
||||
require.Equal(t, api.AnthropicThinkingAdaptive, r.AnthropicMessages.ThinkingMode)
|
||||
}
|
||||
|
||||
func TestEveryProviderKeepsModelCredentialsIsolated(t *testing.T) {
|
||||
for _, v := range modelruntime.List() {
|
||||
t.Run(v.ID, func(t *testing.T) {
|
||||
r, err := modelruntime.Resolve(
|
||||
modelruntime.Ref{
|
||||
Provider: v.ID,
|
||||
Model: "test",
|
||||
BaseURL: "https://example.com/v1",
|
||||
},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
for _, key := range []string{"first-model-key", "second-model-key", "first-model-key"} {
|
||||
ep, err := r.Endpoint(
|
||||
types.ModelTypeKnowledgeQA,
|
||||
modelruntime.Connection{
|
||||
ModelID: key,
|
||||
Credentials: api.Credentials{
|
||||
APIKey: key,
|
||||
AppID: key,
|
||||
AppSecret: key,
|
||||
},
|
||||
Headers: map[string]string{
|
||||
"X-Model": key,
|
||||
},
|
||||
},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
req, err := http.NewRequestWithContext(context.Background(), "POST", "https://example.com/v1", nil)
|
||||
require.NoError(t, err)
|
||||
ep.Auth(req, []byte(`{}`))
|
||||
switch v.AuthStyleFor(r.API) {
|
||||
case providers.AuthBearer:
|
||||
require.Equal(t, "Bearer "+key, req.Header.Get("Authorization"))
|
||||
case providers.AuthAPIKeyHeader:
|
||||
require.Equal(t, key, req.Header.Get("api-key"))
|
||||
case providers.AuthXAPIKey:
|
||||
require.Equal(t, key, req.Header.Get("x-api-key"))
|
||||
case providers.AuthGoogleAPIKey:
|
||||
require.Equal(t, key, req.Header.Get("x-goog-api-key"))
|
||||
case providers.AuthSigned:
|
||||
require.Equal(t, key, req.Header.Get("X-APPID"))
|
||||
}
|
||||
require.Equal(t, key, ep.ModelID)
|
||||
require.Equal(t, key, ep.Headers["X-Model"])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOverlayReloadRestoresBaselineAndRollsBackFailure(t *testing.T) {
|
||||
before := modelruntime.SnapshotCurrent()
|
||||
t.Cleanup(func() { modelruntime.RestoreSnapshot(before) })
|
||||
original, _ := modelruntime.Get("openai")
|
||||
require.NoError(t, modelruntime.ApplyOverlay([]byte(`{
|
||||
"providers": {
|
||||
"openai": {
|
||||
"base_url": "https://relay.example/v1",
|
||||
"models": [
|
||||
{
|
||||
"id": "gpt-5",
|
||||
"cost": {
|
||||
"input": 999
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"temporary": {
|
||||
"name": "Temporary"
|
||||
}
|
||||
}
|
||||
}`), ""))
|
||||
changed, _ := modelruntime.Get("openai")
|
||||
require.Equal(t, "https://relay.example/v1", changed.GetDefaultURL(types.ModelTypeKnowledgeQA))
|
||||
require.Error(
|
||||
t,
|
||||
modelruntime.ApplyOverlay(
|
||||
[]byte(
|
||||
`{"providers":{"openai":{"base_url":"https://wrong.example"},"broken":{"api":"typo"}}}`,
|
||||
),
|
||||
"",
|
||||
),
|
||||
)
|
||||
current, _ := modelruntime.Get("openai")
|
||||
require.Equal(t, changed.DefaultBaseURLs, current.DefaultBaseURLs)
|
||||
require.Equal(t, changed.Models(), current.Models())
|
||||
require.Error(t, modelruntime.ApplyOverlay([]byte(`{"providers":{}} {"providers":{}}`), ""))
|
||||
require.NoError(t, modelruntime.ApplyOverlay([]byte(`{"providers":{}}`), ""))
|
||||
restored, _ := modelruntime.Get("openai")
|
||||
require.Equal(t, original.DefaultBaseURLs, restored.DefaultBaseURLs)
|
||||
require.Equal(t, original.Models(), restored.Models())
|
||||
_, exists := modelruntime.Get("temporary")
|
||||
require.False(t, exists)
|
||||
}
|
||||
|
||||
func TestConcurrentOverlayAndModelResolution(t *testing.T) {
|
||||
before := modelruntime.SnapshotCurrent()
|
||||
t.Cleanup(func() { modelruntime.RestoreSnapshot(before) })
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 4; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for j := 0; j < 30; j++ {
|
||||
r, err := modelruntime.Resolve(modelruntime.Ref{Provider: "openai", Model: "gpt-5"})
|
||||
if err != nil || r.RemoteModel != "gpt-5" {
|
||||
t.Errorf("resolve during reload: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
for i := 0; i < 20; i++ {
|
||||
require.NoError(
|
||||
t,
|
||||
modelruntime.ApplyOverlay(
|
||||
[]byte(
|
||||
`{"providers":{"openai":{"headers":{"X-Deployment":"one"}}}}`,
|
||||
),
|
||||
"",
|
||||
),
|
||||
)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestEveryProviderDefinitionCanBeReloaded(t *testing.T) {
|
||||
before := modelruntime.SnapshotCurrent()
|
||||
t.Cleanup(func() { modelruntime.RestoreSnapshot(before) })
|
||||
entries := map[string]any{}
|
||||
for _, v := range modelruntime.List() {
|
||||
entries[v.ID] = map[string]any{}
|
||||
}
|
||||
data, err := json.Marshal(map[string]any{"providers": entries})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, modelruntime.Reload(data, ""))
|
||||
require.ErrorContains(
|
||||
t,
|
||||
modelruntime.Reload(
|
||||
[]byte(
|
||||
`{"providers":{"openai":{"models":[{"id":"gpt-5","compat":{"typo":true}}]}}}`,
|
||||
),
|
||||
"",
|
||||
),
|
||||
"unknown field",
|
||||
)
|
||||
r, err := modelruntime.Resolve(modelruntime.Ref{Provider: "openai", Model: "gpt-5"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "gpt-5", r.RemoteModel)
|
||||
}
|
||||
|
||||
func TestOverlayCanDeclareSameModelNameForDifferentCapabilities(t *testing.T) {
|
||||
before := modelruntime.SnapshotCurrent()
|
||||
t.Cleanup(func() { modelruntime.RestoreSnapshot(before) })
|
||||
require.NoError(t, modelruntime.Reload([]byte(`{
|
||||
"providers": {
|
||||
"generic": {
|
||||
"models": [
|
||||
{
|
||||
"id": "shared-name",
|
||||
"type": "KnowledgeQA",
|
||||
"context_window": 64000
|
||||
},
|
||||
{
|
||||
"id": "shared-name",
|
||||
"type": "Embedding",
|
||||
"dimension": 768,
|
||||
"compat": {
|
||||
"dimensions_field": "dimensions"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}`), ""))
|
||||
chat, err := modelruntime.Resolve(modelruntime.Ref{
|
||||
Provider: "generic", Model: "shared-name", ModelType: types.ModelTypeKnowledgeQA,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 64000, chat.Spec.ContextWindow)
|
||||
embed, err := modelruntime.Resolve(modelruntime.Ref{
|
||||
Provider: "generic", Model: "shared-name", ModelType: types.ModelTypeEmbedding,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 768, embed.Spec.Dimension)
|
||||
require.Equal(t, "dimensions", embed.Embeddings.DimensionsField)
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"academy/internal/models"
|
||||
"academy/internal/models/api"
|
||||
"academy/internal/models/catalog"
|
||||
"academy/internal/models/internal/configcopy"
|
||||
"academy/internal/models/providers"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// Provider combines a provider definition with a catalog from the same runtime
|
||||
// generation. Public queries return owned definitions; the catalog is immutable.
|
||||
type Provider struct {
|
||||
*providers.Definition
|
||||
catalog *catalog.Catalog
|
||||
}
|
||||
|
||||
// Models returns owned entries from this view, including hidden rules.
|
||||
func (p *Provider) Models() []models.ModelSpec { return p.catalog.Models() }
|
||||
|
||||
// ModelsByType returns visible entries for the requested capability.
|
||||
func (p *Provider) ModelsByType(kind types.ModelType) []models.ModelSpec {
|
||||
return p.catalog.ModelsByType(kind)
|
||||
}
|
||||
|
||||
// FindModel matches an exact ID, alias or family within this view.
|
||||
func (p *Provider) FindModel(name string, kind types.ModelType) (models.ModelSpec, bool) {
|
||||
return p.catalog.FindModel(name, kind)
|
||||
}
|
||||
|
||||
// Resolve uses this view's definition and catalog even after the runtime reloads.
|
||||
func (p *Provider) Resolve(ref Ref) (*Resolved, error) {
|
||||
return resolveWithVendor(ref, p)
|
||||
}
|
||||
|
||||
func (p *Provider) clone() *Provider {
|
||||
return &Provider{Definition: configcopy.Clone(p.Definition), catalog: p.catalog}
|
||||
}
|
||||
|
||||
// Runtime owns provider definitions, model catalogs and deployment overrides.
|
||||
// Separate instances can be configured without changing any other instance.
|
||||
type Runtime struct {
|
||||
mu sync.RWMutex
|
||||
providers map[string]*Provider
|
||||
builtins map[string]*Provider
|
||||
}
|
||||
|
||||
// New explicitly composes fresh built-in definitions and independent catalogs.
|
||||
func New() *Runtime {
|
||||
rt := &Runtime{providers: map[string]*Provider{}, builtins: map[string]*Provider{}}
|
||||
for _, definition := range providers.Builtins() {
|
||||
rt.Register(definition, catalog.BuiltinModels(definition.ID)...)
|
||||
}
|
||||
return rt
|
||||
}
|
||||
|
||||
// Default is the application runtime used by the existing model factories.
|
||||
// New is available to callers that need an isolated configuration.
|
||||
func Default() *Runtime { return sharedRuntime }
|
||||
|
||||
var sharedRuntime = New()
|
||||
|
||||
// Register adds an owned built-in definition and its independently supplied
|
||||
// catalog. Deployment overrides never mutate this baseline.
|
||||
func (rt *Runtime) Register(definition *providers.Definition, entries ...models.ModelSpec) {
|
||||
if definition == nil || definition.ID == "" {
|
||||
panic("runtime: provider without id")
|
||||
}
|
||||
p := &Provider{Definition: configcopy.Clone(definition), catalog: catalog.New(entries)}
|
||||
normalizeProvider(p)
|
||||
rt.mu.Lock()
|
||||
defer rt.mu.Unlock()
|
||||
rt.providers[p.ID] = p
|
||||
rt.builtins[p.ID] = p.clone()
|
||||
}
|
||||
|
||||
func normalizeProvider(p *Provider) {
|
||||
if p.API == "" {
|
||||
p.API = api.APIOpenAICompletions
|
||||
}
|
||||
if p.Auth == "" {
|
||||
p.Auth = providers.AuthBearer
|
||||
}
|
||||
if p.RerankAPI == "" && p.SupportsType(types.ModelTypeRerank) {
|
||||
p.RerankAPI = api.RerankCohere
|
||||
}
|
||||
if p.EmbeddingAPI == "" && p.SupportsType(types.ModelTypeEmbedding) {
|
||||
p.EmbeddingAPI = api.EmbeddingOpenAI
|
||||
}
|
||||
if p.TranscriptionAPI == "" && p.SupportsType(types.ModelTypeASR) {
|
||||
p.TranscriptionAPI = api.TranscriptionOpenAI
|
||||
}
|
||||
entries := p.Models()
|
||||
for i := range entries {
|
||||
if entries[i].Type == "" {
|
||||
entries[i].Type = types.ModelTypeKnowledgeQA
|
||||
}
|
||||
if entries[i].API == "" && entries[i].Type == types.ModelTypeKnowledgeQA {
|
||||
entries[i].API = p.API
|
||||
}
|
||||
}
|
||||
p.catalog = catalog.New(entries)
|
||||
}
|
||||
|
||||
// Get returns an owned provider view from the current generation.
|
||||
func (rt *Runtime) Get(id string) (*Provider, bool) {
|
||||
rt.mu.RLock()
|
||||
defer rt.mu.RUnlock()
|
||||
p, ok := rt.providers[strings.ToLower(strings.TrimSpace(id))]
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
return p.clone(), true
|
||||
}
|
||||
|
||||
// selectProvider retains one immutable generation for the entire resolution.
|
||||
// Its result stays private; Resolve copies the connection definition before
|
||||
// returning it to callers, without copying the full model catalog.
|
||||
func (rt *Runtime) selectProvider(id, baseURL string) *Provider {
|
||||
rt.mu.RLock()
|
||||
defer rt.mu.RUnlock()
|
||||
id = strings.ToLower(strings.TrimSpace(id))
|
||||
if id == "" {
|
||||
id = detectByURL(rt.providers, baseURL)
|
||||
}
|
||||
if p, ok := rt.providers[id]; ok {
|
||||
return p
|
||||
}
|
||||
return rt.providers[providers.GenericID]
|
||||
}
|
||||
|
||||
func detectByURL(definitions map[string]*Provider, baseURL string) string {
|
||||
id, bestLen, bestOrder := providers.GenericID, 0, int(^uint(0)>>1)
|
||||
lower := strings.ToLower(baseURL)
|
||||
for candidate, p := range definitions {
|
||||
for _, pattern := range p.URLPatterns {
|
||||
if pattern != "" && strings.Contains(lower, strings.ToLower(pattern)) &&
|
||||
(len(pattern) > bestLen || len(pattern) == bestLen &&
|
||||
(p.Order < bestOrder || p.Order == bestOrder && candidate < id)) {
|
||||
id, bestLen, bestOrder = candidate, len(pattern), p.Order
|
||||
}
|
||||
}
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// DetectByURL applies legacy provider inference without exposing registry state.
|
||||
func (rt *Runtime) DetectByURL(baseURL string) string {
|
||||
rt.mu.RLock()
|
||||
defer rt.mu.RUnlock()
|
||||
return detectByURL(rt.providers, baseURL)
|
||||
}
|
||||
|
||||
// List returns owned provider views from one generation, ordered by Order and ID.
|
||||
func (rt *Runtime) List() []*Provider {
|
||||
rt.mu.RLock()
|
||||
defer rt.mu.RUnlock()
|
||||
out := make([]*Provider, 0, len(rt.providers))
|
||||
for _, p := range rt.providers {
|
||||
out = append(out, p.clone())
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if out[i].Order != out[j].Order {
|
||||
return out[i].Order < out[j].Order
|
||||
}
|
||||
return out[i].ID < out[j].ID
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// ListByType returns owned views supporting the requested capability.
|
||||
func (rt *Runtime) ListByType(kind types.ModelType) []*Provider {
|
||||
out := make([]*Provider, 0)
|
||||
for _, p := range rt.List() {
|
||||
if p.SupportsType(kind) {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func cloneProviders(in map[string]*Provider) map[string]*Provider {
|
||||
out := make(map[string]*Provider, len(in))
|
||||
for id, p := range in {
|
||||
out[id] = p.clone()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Register adds a built-in definition and separate catalog to the default runtime.
|
||||
func Register(definition *providers.Definition, entries ...models.ModelSpec) {
|
||||
Default().Register(definition, entries...)
|
||||
}
|
||||
|
||||
// Get queries the default runtime.
|
||||
func Get(id string) (*Provider, bool) { return Default().Get(id) }
|
||||
|
||||
// List queries the default runtime.
|
||||
func List() []*Provider { return Default().List() }
|
||||
|
||||
// ListByType queries the default runtime for one capability.
|
||||
func ListByType(kind types.ModelType) []*Provider { return Default().ListByType(kind) }
|
||||
|
||||
// DetectByURL infers a legacy provider using the default runtime.
|
||||
func DetectByURL(baseURL string) string { return Default().DetectByURL(baseURL) }
|
||||
@@ -0,0 +1,133 @@
|
||||
package runtime_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"academy/internal/models"
|
||||
"academy/internal/models/api"
|
||||
"academy/internal/models/providers"
|
||||
modelruntime "academy/internal/models/runtime"
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestRuntimeOwnsDefinitionsAndQueryResults(t *testing.T) {
|
||||
rt := modelruntime.New()
|
||||
definition := &providers.Definition{
|
||||
ID: "owned", Name: "Owned", Auth: providers.AuthBearer,
|
||||
ModelTypes: []types.ModelType{types.ModelTypeKnowledgeQA},
|
||||
Headers: map[string]string{"X-Owner": "original"},
|
||||
Compat: providers.VendorCompat{OpenAICompletions: api.OpenAICompletionsCompat{
|
||||
ExtraBody: map[string]any{"nested": map[string]any{"value": "original", "empty": nil}},
|
||||
}},
|
||||
}
|
||||
entry := models.ModelSpec{
|
||||
ID: "sample", Input: []string{"text", "image"},
|
||||
Cost: &models.ModelCost{Input: 1},
|
||||
ThinkingLevels: api.ThinkingLevelMap{api.ReasoningHigh: api.StringPtr("high")},
|
||||
Compat: json.RawMessage(`{"supports_temperature":false}`),
|
||||
}
|
||||
rt.Register(definition, entry)
|
||||
definition.Headers["X-Owner"] = "input mutation"
|
||||
definition.Compat.OpenAICompletions.ExtraBody["nested"].(map[string]any)["value"] = "input mutation"
|
||||
entry.Input[0], entry.Cost.Input = "audio", 99
|
||||
|
||||
p, ok := rt.Get("owned")
|
||||
require.True(t, ok)
|
||||
check := func() {
|
||||
t.Helper()
|
||||
resolved, err := rt.Resolve(modelruntime.Ref{Provider: "owned", Model: "sample"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "original", resolved.Vendor.Headers["X-Owner"])
|
||||
require.Equal(t, "original", resolved.OpenAICompletions.ExtraBody["nested"].(map[string]any)["value"])
|
||||
require.Nil(t, resolved.OpenAICompletions.ExtraBody["nested"].(map[string]any)["empty"])
|
||||
require.Equal(t, []string{"text", "image"}, resolved.Spec.Input)
|
||||
require.Equal(t, float64(1), resolved.Spec.Cost.Input)
|
||||
require.Equal(t, "high", *resolved.Spec.ThinkingLevels[api.ReasoningHigh])
|
||||
require.False(t, resolved.OpenAICompletions.SupportsTemperature)
|
||||
resolved.Vendor.Headers["X-Owner"] = "resolved mutation"
|
||||
resolved.OpenAICompletions.ExtraBody["nested"].(map[string]any)["value"] = "resolved mutation"
|
||||
}
|
||||
check()
|
||||
p.Headers["X-Owner"] = "query mutation"
|
||||
p.Compat.OpenAICompletions.ExtraBody["nested"].(map[string]any)["value"] = "query mutation"
|
||||
for _, entries := range [][]models.ModelSpec{p.Models(), p.ModelsByType(types.ModelTypeKnowledgeQA)} {
|
||||
entries[0].Input[0], entries[0].Cost.Input = "audio", 99
|
||||
*entries[0].ThinkingLevels[api.ReasoningHigh] = "changed"
|
||||
entries[0].Compat[0] = 'x'
|
||||
}
|
||||
for _, view := range rt.List() {
|
||||
if view.ID == "owned" {
|
||||
view.Headers["X-Owner"] = "list mutation"
|
||||
}
|
||||
}
|
||||
check()
|
||||
// Rebuilding from the baseline must not reintroduce any input/query mutations.
|
||||
require.NoError(t, rt.Reload([]byte(`{"providers":{}}`), ""))
|
||||
check()
|
||||
}
|
||||
|
||||
func TestRuntimeInstancesAndRetainedViewsAreIndependent(t *testing.T) {
|
||||
first, second := modelruntime.New(), modelruntime.New()
|
||||
old, ok := first.Get("openai")
|
||||
require.True(t, ok)
|
||||
ref := modelruntime.Ref{Provider: "openai", Model: "gpt-5"}
|
||||
before, err := old.Resolve(ref)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, first.Reload([]byte(`{"providers":{"openai":{
|
||||
"base_url":"https://relay.example/v1", "models":[{"id":"gpt-5","context_window":12345}]
|
||||
}}}`), ""))
|
||||
changed, err := first.Resolve(ref)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "https://relay.example/v1", changed.BaseURL)
|
||||
require.Equal(t, 12345, changed.Spec.ContextWindow)
|
||||
for _, resolve := range []func(modelruntime.Ref) (*modelruntime.Resolved, error){old.Resolve, second.Resolve} {
|
||||
unchanged, err := resolve(ref)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, before.BaseURL, unchanged.BaseURL)
|
||||
require.Equal(t, before.Spec, unchanged.Spec)
|
||||
}
|
||||
require.NoError(t, first.Reload([]byte(`{"providers":{}}`), ""))
|
||||
restored, err := first.Resolve(ref)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, before.Spec, restored.Spec)
|
||||
}
|
||||
|
||||
func TestResolveKeepsOneGenerationDuringReload(t *testing.T) {
|
||||
rt := modelruntime.New()
|
||||
overlay := func(generation int) []byte {
|
||||
return []byte(fmt.Sprintf(`{"providers":{"openai":{
|
||||
"base_url":"https://generation-%d.example/v1", "headers":{"X-Generation":"%d"},
|
||||
"models":[{"id":"gpt-5","context_window":%d}]
|
||||
}}}`, generation, generation, generation))
|
||||
}
|
||||
require.NoError(t, rt.Reload(overlay(1), ""))
|
||||
var wg sync.WaitGroup
|
||||
for range 4 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for range 30 {
|
||||
resolved, err := rt.Resolve(modelruntime.Ref{Provider: "openai", Model: "gpt-5"})
|
||||
if err != nil {
|
||||
t.Errorf("resolve: %v", err)
|
||||
return
|
||||
}
|
||||
generation := resolved.Vendor.Headers["X-Generation"]
|
||||
if resolved.BaseURL != "https://generation-"+generation+".example/v1" ||
|
||||
fmt.Sprint(resolved.Spec.ContextWindow) != generation {
|
||||
t.Errorf("mixed provider/catalog generation: %s, %s, %d",
|
||||
generation, resolved.BaseURL, resolved.Spec.ContextWindow)
|
||||
}
|
||||
resolved.Vendor.Headers["X-Generation"] = "caller mutation"
|
||||
}
|
||||
}()
|
||||
}
|
||||
for generation := 2; generation < 12; generation++ {
|
||||
require.NoError(t, rt.Reload(overlay(generation), ""))
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -0,0 +1,576 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"academy/internal/models"
|
||||
"academy/internal/models/api"
|
||||
"academy/internal/models/catalog"
|
||||
"academy/internal/models/internal/configcopy"
|
||||
"academy/internal/models/providers"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// Ref identifies one configured model.
|
||||
type Ref struct {
|
||||
Provider string
|
||||
Model string
|
||||
BaseURL string
|
||||
ModelType types.ModelType
|
||||
Extra map[string]string
|
||||
Override *types.ModelSpecOverride
|
||||
// TruncatePromptTokens is an embedding row's
|
||||
// embedding_parameters.truncate_prompt_tokens. It is a first-class column
|
||||
// rather than an extra_config key, which is why it arrives here instead
|
||||
// of in Extra.
|
||||
TruncatePromptTokens int
|
||||
}
|
||||
|
||||
// Resolved is the fully merged view of one model: which vendor, which
|
||||
// protocol, which settings.
|
||||
type Resolved struct {
|
||||
Vendor *providers.Definition
|
||||
// Spec is the effective catalog entry (synthesized when unknown).
|
||||
Spec models.ModelSpec
|
||||
// Cataloged reports whether the model name matched a catalog entry.
|
||||
Cataloged bool
|
||||
API api.API
|
||||
BaseURL string
|
||||
// RemoteModel is the id sent on the wire.
|
||||
RemoteModel string
|
||||
ThinkingLevels api.ThinkingLevelMap
|
||||
|
||||
OpenAICompletions api.OpenAICompletionsSettings
|
||||
OpenAIResponses api.OpenAIResponsesSettings
|
||||
AnthropicMessages api.AnthropicMessagesSettings
|
||||
GoogleGenerativeAI api.GoogleGenerativeAISettings
|
||||
|
||||
// RerankAPI and Rerank are filled only when the reference asked for a
|
||||
// rerank model. Chat resolution is on every request's hot path, so the
|
||||
// rerank overlay is not merged for it.
|
||||
RerankAPI api.RerankAPI
|
||||
Rerank api.RerankSettings
|
||||
|
||||
// EmbeddingAPI and Embeddings are filled only for an embedding reference,
|
||||
// for the same reason.
|
||||
EmbeddingAPI api.EmbeddingAPI
|
||||
Embeddings api.EmbeddingsSettings
|
||||
|
||||
// TranscriptionAPI and Transcriptions are filled only for an ASR
|
||||
// reference.
|
||||
TranscriptionAPI api.TranscriptionAPI
|
||||
Transcriptions api.TranscriptionsSettings
|
||||
}
|
||||
|
||||
// Resolve merges the vendor, catalog entry, extra-config and per-row
|
||||
// overrides for a model reference. It never fails for unknown vendors or
|
||||
// models: they degrade to the generic OpenAI-compatible baseline.
|
||||
func Resolve(ref Ref) (*Resolved, error) { return Default().Resolve(ref) }
|
||||
|
||||
// Resolve merges one model against a single generation of this runtime.
|
||||
func (rt *Runtime) Resolve(ref Ref) (*Resolved, error) {
|
||||
return resolveWithVendor(ref, rt.selectProvider(ref.Provider, ref.BaseURL))
|
||||
}
|
||||
|
||||
func resolveWithVendor(ref Ref, vendor *Provider) (*Resolved, error) {
|
||||
if vendor == nil {
|
||||
return nil, fmt.Errorf("catalog: no vendors registered")
|
||||
}
|
||||
modelType := ref.ModelType
|
||||
if modelType == "" {
|
||||
modelType = types.ModelTypeKnowledgeQA
|
||||
}
|
||||
|
||||
baseURL := strings.TrimRight(strings.TrimSpace(ref.BaseURL), "/")
|
||||
if baseURL == "" {
|
||||
baseURL = strings.TrimRight(vendor.GetDefaultURL(modelType), "/")
|
||||
}
|
||||
|
||||
spec, cataloged := vendor.FindModel(ref.Model, modelType)
|
||||
if !cataloged {
|
||||
spec = models.ModelSpec{ID: ref.Model, Type: catalog.EntryType(modelType)}
|
||||
}
|
||||
if spec.API == "" {
|
||||
spec.API = vendor.API
|
||||
}
|
||||
catalogAPI := spec.API
|
||||
if ref.Override != nil {
|
||||
applySpecOverride(&spec, ref.Override)
|
||||
}
|
||||
|
||||
if modelType == types.ModelTypeRerank {
|
||||
return resolveRerank(ref, vendor, spec, cataloged, baseURL)
|
||||
}
|
||||
if modelType == types.ModelTypeEmbedding {
|
||||
return resolveEmbeddings(ref, vendor, spec, cataloged, baseURL)
|
||||
}
|
||||
if modelType == types.ModelTypeASR {
|
||||
return resolveTranscriptions(ref, vendor, spec, cataloged, baseURL)
|
||||
}
|
||||
|
||||
resolvedAPI := spec.API
|
||||
if forced := strings.TrimSpace(ref.Extra[models.ExtraAPI]); forced != "" {
|
||||
resolvedAPI = api.API(forced)
|
||||
} else if ref.Override == nil || ref.Override.API == "" {
|
||||
resolvedAPI = inferAPIFromURL(baseURL, resolvedAPI)
|
||||
if vendor.PreferAPI != nil {
|
||||
if preferred := vendor.PreferAPI(baseURL, spec); preferred != "" {
|
||||
resolvedAPI = preferred
|
||||
}
|
||||
}
|
||||
}
|
||||
if !resolvedAPI.Known() {
|
||||
return nil, fmt.Errorf("catalog: unknown api %q for provider %s", resolvedAPI, vendor.ID)
|
||||
}
|
||||
|
||||
levels := api.ThinkingLevelMap{}
|
||||
for k, v := range vendor.ThinkingLevels {
|
||||
levels[k] = v
|
||||
}
|
||||
for k, v := range spec.ThinkingLevels {
|
||||
levels[k] = v
|
||||
}
|
||||
if ref.Override != nil {
|
||||
for k, v := range ref.Override.ThinkingLevels {
|
||||
levels[api.ReasoningEffort(k)] = v
|
||||
}
|
||||
}
|
||||
|
||||
out := &Resolved{
|
||||
Vendor: configcopy.Clone(vendor.Definition),
|
||||
Spec: spec,
|
||||
Cataloged: cataloged,
|
||||
API: resolvedAPI,
|
||||
BaseURL: baseURL,
|
||||
RemoteModel: ref.Model,
|
||||
ThinkingLevels: levels,
|
||||
}
|
||||
if override := strings.TrimSpace(ref.Extra[models.ExtraRemoteModelName]); override != "" {
|
||||
out.RemoteModel = override
|
||||
}
|
||||
|
||||
overrideCompat := ref.Override.CompatJSON()
|
||||
|
||||
// Every protocol's settings are resolved so callers can inspect any of
|
||||
// them, but only the layers whose API matches contribute model/override
|
||||
// compat (a flat compat object is meaningless for another protocol).
|
||||
completions := api.DefaultOpenAICompletions()
|
||||
ApplyCompat(&completions, &vendor.Compat.OpenAICompletions)
|
||||
if err := applyRawCompat(
|
||||
&completions, &api.OpenAICompletionsCompat{}, spec.Compat, catalogAPI, api.APIOpenAICompletions,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := applyRawCompat(
|
||||
&completions, &api.OpenAICompletionsCompat{}, overrideCompat, resolvedAPI, api.APIOpenAICompletions,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
legacyThinkingControlApplied := applyLegacyThinkingControl(
|
||||
&completions, ref.Extra[models.ExtraThinkingControl],
|
||||
)
|
||||
out.OpenAICompletions = completions
|
||||
|
||||
responses := api.DefaultOpenAIResponses()
|
||||
ApplyCompat(&responses, &vendor.Compat.OpenAIResponses)
|
||||
if err := applyRawCompat(
|
||||
&responses, &api.OpenAIResponsesCompat{}, spec.Compat, catalogAPI, api.APIOpenAIResponses,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := applyRawCompat(
|
||||
&responses, &api.OpenAIResponsesCompat{}, overrideCompat, resolvedAPI, api.APIOpenAIResponses,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out.OpenAIResponses = responses
|
||||
|
||||
anthropic := api.DefaultAnthropicMessages()
|
||||
ApplyCompat(&anthropic, &vendor.Compat.AnthropicMessages)
|
||||
if err := applyRawCompat(
|
||||
&anthropic, &api.AnthropicMessagesCompat{}, spec.Compat, catalogAPI, api.APIAnthropicMessages,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := applyRawCompat(
|
||||
&anthropic, &api.AnthropicMessagesCompat{}, overrideCompat, resolvedAPI, api.APIAnthropicMessages,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out.AnthropicMessages = anthropic
|
||||
|
||||
google := api.DefaultGoogleGenerativeAI()
|
||||
ApplyCompat(&google, &vendor.Compat.GoogleGenerativeAI)
|
||||
if err := applyRawCompat(
|
||||
&google, &api.GoogleGenerativeAICompat{}, spec.Compat, catalogAPI, api.APIGoogleGenerativeAI,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := applyRawCompat(
|
||||
&google, &api.GoogleGenerativeAICompat{}, overrideCompat, resolvedAPI, api.APIGoogleGenerativeAI,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out.GoogleGenerativeAI = google
|
||||
// A non-default legacy thinking_control is an explicit per-row override.
|
||||
// An ignored provider default lets the catalog's reasoning metadata apply.
|
||||
if !legacyThinkingControlApplied {
|
||||
out.silenceThinkingForNonReasoningModel()
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// silenceThinkingForNonReasoningModel drops every thinking field for a
|
||||
// catalogued model the vendor documents as non-reasoning (DeepSeek's
|
||||
// non-thinking alias, LKEAP's V3-0324 generation, plain instruct models).
|
||||
// Without this, a caller that asks for thinking — an agent whose config says
|
||||
// so, or the model debug drawer — would send a switch the model does not
|
||||
// understand, and some vendors answer 400.
|
||||
//
|
||||
// The gate deliberately applies only to catalogued entries: an unknown model
|
||||
// on a self-hosted runtime carries Reasoning=false simply because nobody
|
||||
// described it, and those deployments do rely on the thinking switch.
|
||||
func (r *Resolved) silenceThinkingForNonReasoningModel() {
|
||||
if !r.Cataloged || r.Spec.Reasoning {
|
||||
return
|
||||
}
|
||||
r.OpenAICompletions.ThinkingFormat = api.ThinkingFormatNone
|
||||
r.OpenAICompletions.ThinkingBudgetField = ""
|
||||
r.OpenAICompletions.SupportsReasoningEffort = false
|
||||
r.GoogleGenerativeAI.ThinkingMode = api.GoogleThinkingNone
|
||||
r.ThinkingLevels = api.ThinkingLevelMap{}
|
||||
for _, level := range api.ReasoningLadder {
|
||||
r.ThinkingLevels[level] = nil
|
||||
}
|
||||
r.ThinkingLevels[api.ReasoningAuto] = nil
|
||||
}
|
||||
|
||||
// applyRawCompat decodes raw into the overlay type and applies it when the
|
||||
// layer's API matches the target protocol.
|
||||
func applyRawCompat(settings any, overlayPtr any, raw json.RawMessage, layerAPI, target api.API) error {
|
||||
if len(raw) == 0 || layerAPI != target {
|
||||
return nil
|
||||
}
|
||||
if err := DecodeCompat(raw, overlayPtr); err != nil {
|
||||
return fmt.Errorf("%s compat: %w", target, err)
|
||||
}
|
||||
ApplyCompat(settings, overlayPtr)
|
||||
return nil
|
||||
}
|
||||
|
||||
func applySpecOverride(spec *models.ModelSpec, o *types.ModelSpecOverride) {
|
||||
if o == nil {
|
||||
return
|
||||
}
|
||||
if o.API != "" {
|
||||
spec.API = api.API(o.API)
|
||||
}
|
||||
if o.Reasoning != nil {
|
||||
spec.Reasoning = *o.Reasoning
|
||||
}
|
||||
if len(o.Input) > 0 {
|
||||
spec.Input = o.Input
|
||||
}
|
||||
if o.ContextWindow > 0 {
|
||||
spec.ContextWindow = o.ContextWindow
|
||||
}
|
||||
if o.MaxOutputTokens > 0 {
|
||||
spec.MaxOutputTokens = o.MaxOutputTokens
|
||||
}
|
||||
}
|
||||
|
||||
// Capabilities is the frontend contract, independent of runtime assembly.
|
||||
type Capabilities = models.Capabilities
|
||||
|
||||
// Capabilities summarizes the resolved model for API responses.
|
||||
func (r *Resolved) Capabilities() Capabilities {
|
||||
if r == nil {
|
||||
return Capabilities{}
|
||||
}
|
||||
caps := Capabilities{
|
||||
Provider: r.Vendor.ID,
|
||||
API: r.API,
|
||||
Cataloged: r.Cataloged,
|
||||
Reasoning: r.Spec.Reasoning,
|
||||
Input: r.Spec.Input,
|
||||
ContextWindow: r.Spec.ContextWindow,
|
||||
MaxOutputTokens: r.Spec.MaxOutputTokens,
|
||||
}
|
||||
// Embedding, rerank and ASR references resolve no chat protocol, and an
|
||||
// empty level map reads as "every level supported"; they do not think.
|
||||
if r.API == "" {
|
||||
caps.ThinkingLevels = []api.ReasoningEffort{}
|
||||
return caps
|
||||
}
|
||||
switch r.API {
|
||||
case api.APIOpenAICompletions:
|
||||
caps.ThinkingFormat = string(r.OpenAICompletions.ThinkingFormat)
|
||||
caps.MaxTokensField = r.OpenAICompletions.MaxTokensField
|
||||
if caps.ThinkingFormat == string(api.ThinkingFormatNone) {
|
||||
caps.ThinkingLevels = []api.ReasoningEffort{}
|
||||
return caps
|
||||
}
|
||||
case api.APIOpenAIResponses:
|
||||
caps.ThinkingFormat = "reasoning.effort"
|
||||
caps.MaxTokensField = "max_output_tokens"
|
||||
case api.APIAnthropicMessages:
|
||||
caps.ThinkingFormat = "thinking." + string(r.AnthropicMessages.ThinkingMode)
|
||||
caps.MaxTokensField = "max_tokens"
|
||||
case api.APIGoogleGenerativeAI:
|
||||
caps.ThinkingFormat = "thinkingConfig." + string(r.GoogleGenerativeAI.ThinkingMode)
|
||||
caps.MaxTokensField = "maxOutputTokens"
|
||||
if r.GoogleGenerativeAI.ThinkingMode == api.GoogleThinkingNone {
|
||||
caps.ThinkingLevels = []api.ReasoningEffort{}
|
||||
return caps
|
||||
}
|
||||
case api.APIOllama:
|
||||
caps.ThinkingFormat = "think"
|
||||
caps.MaxTokensField = "num_predict"
|
||||
}
|
||||
caps.ThinkingLevels = r.ThinkingLevels.SupportedLevels()
|
||||
// A chat-template switch carries only the enable_thinking boolean: every
|
||||
// graded rung is silently dropped on the wire (and a relay backend that
|
||||
// does not know enable_thinking drops the boolean too), so the selector
|
||||
// must not offer rungs the request cannot express. Vendors that opt into
|
||||
// a top-level effort field keep their ladders (#3489 moved its NIM
|
||||
// entries to that shape).
|
||||
if r.API == api.APIOpenAICompletions &&
|
||||
r.OpenAICompletions.ThinkingFormat == api.ThinkingFormatChatTemplateKwargs &&
|
||||
!r.OpenAICompletions.SupportsReasoningEffort {
|
||||
keep := make([]api.ReasoningEffort, 0, 2)
|
||||
for _, level := range caps.ThinkingLevels {
|
||||
if !level.Graded() {
|
||||
keep = append(keep, level)
|
||||
}
|
||||
}
|
||||
caps.ThinkingLevels = keep
|
||||
}
|
||||
return caps
|
||||
}
|
||||
|
||||
// resolveRerank merges the rerank layers. Rerank has one settings struct
|
||||
// rather than one per protocol, so the model entry's compat object is decoded
|
||||
// unconditionally instead of being matched against a protocol.
|
||||
func resolveRerank(
|
||||
ref Ref, vendor *Provider, spec models.ModelSpec, cataloged bool, baseURL string,
|
||||
) (*Resolved, error) {
|
||||
protocol := vendor.RerankAPI
|
||||
if protocol == "" {
|
||||
protocol = api.RerankCohere
|
||||
}
|
||||
if !protocol.Known() {
|
||||
return nil, fmt.Errorf("catalog: unknown rerank api %q for provider %s", protocol, vendor.ID)
|
||||
}
|
||||
|
||||
// Lowest precedence first: protocol default, vendor, model entry, row spec
|
||||
// override. extra_config is the operator speaking about this one row, so it
|
||||
// comes last.
|
||||
settings := api.DefaultRerank()
|
||||
ApplyCompat(&settings, &vendor.Compat.Rerank)
|
||||
if len(spec.Compat) > 0 {
|
||||
overlay := &api.RerankCompat{}
|
||||
if err := DecodeCompat(spec.Compat, overlay); err != nil {
|
||||
return nil, fmt.Errorf("rerank compat: %w", err)
|
||||
}
|
||||
ApplyCompat(&settings, overlay)
|
||||
}
|
||||
if raw := ref.Override.CompatJSON(); len(raw) > 0 {
|
||||
overlay := &api.RerankCompat{}
|
||||
if err := DecodeCompat(raw, overlay); err != nil {
|
||||
return nil, fmt.Errorf("rerank compat: %w", err)
|
||||
}
|
||||
ApplyCompat(&settings, overlay)
|
||||
}
|
||||
|
||||
if raw := strings.TrimSpace(ref.Extra[models.ExtraScoreScale]); raw != "" {
|
||||
scale := api.ScoreScale(strings.ToLower(raw))
|
||||
if scale != api.ScoreProbability && scale != api.ScoreLogit {
|
||||
return nil, fmt.Errorf(
|
||||
"catalog: invalid %s in extra_config: %q (expected %q or %q)",
|
||||
models.ExtraScoreScale, raw, api.ScoreProbability, api.ScoreLogit,
|
||||
)
|
||||
}
|
||||
settings.ScoreScale = scale
|
||||
}
|
||||
if raw := strings.TrimSpace(ref.Extra[models.ExtraTruncatePromptTokens]); raw != "" {
|
||||
if !settings.AcceptsTruncatePromptTokens {
|
||||
return nil, fmt.Errorf(
|
||||
"catalog: %s is a vLLM extension and %s does not implement it; "+
|
||||
"remove it from extra_config (it is accepted by self-hosted runtimes only)",
|
||||
models.ExtraTruncatePromptTokens, vendor.ID,
|
||||
)
|
||||
}
|
||||
budget, err := strconv.Atoi(raw)
|
||||
if err != nil || budget <= 0 {
|
||||
return nil, fmt.Errorf("catalog: invalid %s in extra_config: %q", models.ExtraTruncatePromptTokens, raw)
|
||||
}
|
||||
settings.TruncatePromptTokens = budget
|
||||
}
|
||||
// Checked after every layer: a model entry is what declares a dialect
|
||||
// this build cannot speak.
|
||||
if settings.UnsupportedReason != "" {
|
||||
return nil, &UnsupportedModelError{Provider: vendor.ID, Model: spec.ID, Reason: settings.UnsupportedReason}
|
||||
}
|
||||
out := &Resolved{
|
||||
Vendor: configcopy.Clone(vendor.Definition),
|
||||
Spec: spec,
|
||||
Cataloged: cataloged,
|
||||
BaseURL: baseURL,
|
||||
RemoteModel: ref.Model,
|
||||
RerankAPI: protocol,
|
||||
Rerank: settings,
|
||||
}
|
||||
if override := strings.TrimSpace(ref.Extra[models.ExtraRemoteModelName]); override != "" {
|
||||
out.RemoteModel = override
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// resolveEmbeddings merges the embedding layers, in the same order as
|
||||
// resolveRerank: protocol default, vendor, model entry, row spec override,
|
||||
// then extra_config, which is the operator speaking about this one row.
|
||||
func resolveEmbeddings(
|
||||
ref Ref, vendor *Provider, spec models.ModelSpec, cataloged bool, baseURL string,
|
||||
) (*Resolved, error) {
|
||||
protocol := vendor.EmbeddingAPI
|
||||
if protocol == "" {
|
||||
protocol = api.EmbeddingOpenAI
|
||||
}
|
||||
if !protocol.Known() {
|
||||
return nil, fmt.Errorf("catalog: unknown embedding api %q for provider %s", protocol, vendor.ID)
|
||||
}
|
||||
|
||||
settings := api.DefaultEmbeddings()
|
||||
ApplyCompat(&settings, &vendor.Compat.Embeddings)
|
||||
if len(spec.Compat) > 0 {
|
||||
overlay := &api.EmbeddingsCompat{}
|
||||
if err := DecodeCompat(spec.Compat, overlay); err != nil {
|
||||
return nil, fmt.Errorf("embeddings compat: %w", err)
|
||||
}
|
||||
ApplyCompat(&settings, overlay)
|
||||
}
|
||||
if raw := ref.Override.CompatJSON(); len(raw) > 0 {
|
||||
overlay := &api.EmbeddingsCompat{}
|
||||
if err := DecodeCompat(raw, overlay); err != nil {
|
||||
return nil, fmt.Errorf("embeddings compat: %w", err)
|
||||
}
|
||||
ApplyCompat(&settings, overlay)
|
||||
}
|
||||
// The row may carry a truncation budget, but the extension is vLLM's and
|
||||
// appears in no managed vendor's schema. Dropping it where the vendor
|
||||
// does not implement it is the quiet direction on purpose: unlike the
|
||||
// rerank opt-in, this field has a UI control that every embedding row
|
||||
// has always carried, so refusing to resolve would break rows whose only
|
||||
// mistake is a non-zero default.
|
||||
//
|
||||
// Where it is accepted, an unset row keeps the budget the pre-catalog
|
||||
// client always sent. A self-hosted index was built with long chunks cut
|
||||
// at that length; embedding new chunks uncut would put them in a
|
||||
// different place from the old ones without anything failing.
|
||||
if settings.AcceptsTruncatePromptTokens {
|
||||
settings.TruncatePromptTokens = ref.TruncatePromptTokens
|
||||
if settings.TruncatePromptTokens <= 0 {
|
||||
settings.TruncatePromptTokens = models.LegacyTruncatePromptTokens
|
||||
}
|
||||
}
|
||||
|
||||
// A model entry may name a different dialect than the vendor default.
|
||||
if settings.API != "" {
|
||||
if !settings.API.Known() {
|
||||
return nil, fmt.Errorf(
|
||||
"catalog: unknown embedding api %q on %s/%s", settings.API, vendor.ID, spec.ID)
|
||||
}
|
||||
protocol = settings.API
|
||||
}
|
||||
settings.API = protocol
|
||||
if !settings.ImageFormat.Known() {
|
||||
return nil, fmt.Errorf(
|
||||
"catalog: unknown embedding image_format %q on %s/%s (expected %q or %q)",
|
||||
settings.ImageFormat, vendor.ID, spec.ID, api.EmbeddingImageObject, api.EmbeddingImageMessages)
|
||||
}
|
||||
// A row that declares image input on the OpenAI embedding shape still
|
||||
// needs a wire format: that shape has none of its own, and only Jina
|
||||
// names one. vLLM, the usual server behind these gateways, takes one
|
||||
// chat conversation in messages. Jina and SGLang stay explicit
|
||||
// (image_format=object plus image_field). An object format without a
|
||||
// field is left alone, so a half-filled row is refused instead of resent
|
||||
// as messages. Text stays on input unless the row sets text_as_messages.
|
||||
if protocol == api.EmbeddingOpenAI && spec.AcceptsImages() &&
|
||||
settings.ImageFormat == "" && settings.ImageField == "" {
|
||||
settings.ImageFormat = api.EmbeddingImageMessages
|
||||
}
|
||||
|
||||
out := &Resolved{
|
||||
Vendor: configcopy.Clone(vendor.Definition),
|
||||
Spec: spec,
|
||||
Cataloged: cataloged,
|
||||
BaseURL: baseURL,
|
||||
RemoteModel: ref.Model,
|
||||
EmbeddingAPI: protocol,
|
||||
Embeddings: settings,
|
||||
}
|
||||
if override := strings.TrimSpace(ref.Extra[models.ExtraRemoteModelName]); override != "" {
|
||||
out.RemoteModel = override
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// resolveTranscriptions merges the speech-to-text layers, in the same order
|
||||
// as resolveEmbeddings: protocol default, vendor compat, the catalog entry,
|
||||
// the row's own compat, then remote_model_name.
|
||||
func resolveTranscriptions(
|
||||
ref Ref, vendor *Provider, spec models.ModelSpec, cataloged bool, baseURL string,
|
||||
) (*Resolved, error) {
|
||||
protocol := vendor.TranscriptionAPI
|
||||
if protocol == "" {
|
||||
protocol = api.TranscriptionOpenAI
|
||||
}
|
||||
settings := api.DefaultTranscriptions()
|
||||
ApplyCompat(&settings, &vendor.Compat.Transcriptions)
|
||||
for _, raw := range []json.RawMessage{spec.Compat, ref.Override.CompatJSON()} {
|
||||
if len(raw) == 0 {
|
||||
continue
|
||||
}
|
||||
overlay := &api.TranscriptionsCompat{}
|
||||
if err := DecodeCompat(raw, overlay); err != nil {
|
||||
return nil, fmt.Errorf("transcriptions compat: %w", err)
|
||||
}
|
||||
ApplyCompat(&settings, overlay)
|
||||
}
|
||||
if settings.API != "" {
|
||||
protocol = settings.API
|
||||
}
|
||||
if !protocol.Known() {
|
||||
return nil, fmt.Errorf("catalog: unknown transcription api %q for %s/%s", protocol, vendor.ID, spec.ID)
|
||||
}
|
||||
settings.API = protocol
|
||||
switch settings.LanguageParam {
|
||||
case "", api.LanguageForm, api.LanguageHeader, api.LanguageASROptions:
|
||||
default:
|
||||
return nil, fmt.Errorf("catalog: unknown language_param %q for %s/%s",
|
||||
settings.LanguageParam, vendor.ID, spec.ID)
|
||||
}
|
||||
// Checked after every layer: an entry may lift a vendor-wide refusal for
|
||||
// the one model that takes the audio in the request.
|
||||
if settings.UnsupportedReason != "" {
|
||||
return nil, &UnsupportedModelError{Provider: vendor.ID, Model: spec.ID, Reason: settings.UnsupportedReason}
|
||||
}
|
||||
|
||||
out := &Resolved{
|
||||
Vendor: configcopy.Clone(vendor.Definition),
|
||||
Spec: spec,
|
||||
Cataloged: cataloged,
|
||||
BaseURL: baseURL,
|
||||
RemoteModel: ref.Model,
|
||||
TranscriptionAPI: protocol,
|
||||
Transcriptions: settings,
|
||||
}
|
||||
if override := strings.TrimSpace(ref.Extra[models.ExtraRemoteModelName]); override != "" {
|
||||
out.RemoteModel = override
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// Package runtime resolves one model's effective settings and assembles its
|
||||
// authenticated endpoint. Provider definitions and catalog metadata are shared;
|
||||
// model credentials and connection settings are resolved independently per row.
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"academy/internal/models"
|
||||
"academy/internal/models/providers"
|
||||
)
|
||||
|
||||
// Initialize is the application composition entry point. A failed deployment
|
||||
// overlay leaves the previous catalog generation untouched.
|
||||
func Initialize(configDir string) error { return Default().Initialize(configDir) }
|
||||
|
||||
// Initialize loads and validates deployment configuration for this instance.
|
||||
func (rt *Runtime) Initialize(configDir string) error {
|
||||
return rt.loadOverlayValidated(configDir, validateDefinition)
|
||||
}
|
||||
|
||||
// Reload replaces the deployment overlay without retaining removed overrides.
|
||||
func Reload(data []byte, baseDir string) error { return Default().Reload(data, baseDir) }
|
||||
|
||||
// Reload validates and publishes a replacement deployment overlay for this instance.
|
||||
func (rt *Runtime) Reload(data []byte, baseDir string) error {
|
||||
return rt.applyOverlayValidated(data, baseDir, validateDefinition)
|
||||
}
|
||||
|
||||
func validateDefinition(v *Provider) error {
|
||||
switch v.Auth {
|
||||
case providers.AuthBearer, providers.AuthAPIKeyHeader, providers.AuthXAPIKey,
|
||||
providers.AuthGoogleAPIKey, providers.AuthNone, providers.AuthSigned:
|
||||
default:
|
||||
return fmt.Errorf("unknown auth style %q", v.Auth)
|
||||
}
|
||||
for _, kind := range v.ModelTypes {
|
||||
_, err := resolveWithVendor(Ref{Provider: v.ID, Model: "custom-model", ModelType: kind}, v)
|
||||
var unsupported *UnsupportedModelError
|
||||
if err != nil && !errors.As(err, &unsupported) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, entry := range v.Models() {
|
||||
name := entry.ID
|
||||
if name == "" {
|
||||
name = strings.ReplaceAll(entry.Match, "*", "snapshot")
|
||||
}
|
||||
_, err := resolveWithVendor(Ref{Provider: v.ID, Model: name, ModelType: entry.Type}, v)
|
||||
// Unsupported entries deliberately remain as tombstones for old rows; they
|
||||
// are hidden from pickers and must continue to produce a useful error.
|
||||
var unsupported *UnsupportedModelError
|
||||
if err != nil && (!errors.As(err, &unsupported) || (!entry.Deprecated && entry.ID != "")) {
|
||||
return err
|
||||
}
|
||||
if entry.ContextWindow < 0 || entry.MaxOutputTokens < 0 || entry.Dimension < 0 {
|
||||
return fmt.Errorf("model %s: negative model limit", name)
|
||||
}
|
||||
if _, valid := models.ParseModelType(string(entry.Type)); entry.Type != "" && !valid {
|
||||
return fmt.Errorf("model %s: unsupported type %q", name, entry.Type)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// UnsupportedModelError records an intentional refusal for an unimplemented API.
|
||||
type UnsupportedModelError struct{ Provider, Model, Reason string }
|
||||
|
||||
func (e *UnsupportedModelError) Error() string {
|
||||
return fmt.Sprintf(
|
||||
"catalog: %s does not serve %q through a protocol this build implements: %s",
|
||||
e.Provider,
|
||||
e.Model,
|
||||
e.Reason,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package runtime
|
||||
|
||||
// Snapshot captures provider definitions and their model catalogs together.
|
||||
// It also retains the built-in baseline used when replacing deployment overrides.
|
||||
type Snapshot struct {
|
||||
current map[string]*Provider
|
||||
base map[string]*Provider
|
||||
}
|
||||
|
||||
// SnapshotCurrent retains the current generation and its built-in baseline.
|
||||
func (rt *Runtime) SnapshotCurrent() Snapshot {
|
||||
rt.mu.RLock()
|
||||
defer rt.mu.RUnlock()
|
||||
return Snapshot{cloneProviders(rt.providers), cloneProviders(rt.builtins)}
|
||||
}
|
||||
|
||||
// RestoreSnapshot restores an owned copy for rollback or isolated tests.
|
||||
func (rt *Runtime) RestoreSnapshot(s Snapshot) {
|
||||
rt.mu.Lock()
|
||||
defer rt.mu.Unlock()
|
||||
rt.providers, rt.builtins = cloneProviders(s.current), cloneProviders(s.base)
|
||||
}
|
||||
|
||||
// SnapshotCurrent captures the default runtime for rollback or isolated tests.
|
||||
func SnapshotCurrent() Snapshot { return Default().SnapshotCurrent() }
|
||||
|
||||
// RestoreSnapshot restores the default runtime.
|
||||
func RestoreSnapshot(s Snapshot) { Default().RestoreSnapshot(s) }
|
||||
@@ -0,0 +1,51 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"academy/internal/models/api"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// ValidateRow checks that a stored model row resolves against the catalog.
|
||||
//
|
||||
// It is the one gate shared by every write path — the REST create/update
|
||||
// handlers and the declarative builtin_models.yaml loader — so an unknown
|
||||
// protocol, a bad compat key or an invalid thinking level is rejected where
|
||||
// it is written instead of surfacing as a failed chat call much later.
|
||||
//
|
||||
// Every model type is checked: all of them are built from runtime.Resolve,
|
||||
// so a row that does not resolve cannot be used and should fail the save
|
||||
// rather than the first call.
|
||||
func ValidateRow(modelName string, modelType types.ModelType, params *types.ModelParameters) error {
|
||||
if params == nil || !resolvesThroughCatalog(modelType) {
|
||||
return nil
|
||||
}
|
||||
if params.Spec != nil {
|
||||
for level := range params.Spec.ThinkingLevels {
|
||||
if _, ok := api.ParseReasoningEffort(level); !ok || level == "" {
|
||||
return fmt.Errorf("spec.thinking_levels: unknown level %q", level)
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, err := Resolve(Ref{
|
||||
Provider: params.Provider,
|
||||
Model: modelName,
|
||||
BaseURL: params.BaseURL,
|
||||
ModelType: modelType,
|
||||
Extra: params.ExtraConfig,
|
||||
Override: params.Spec,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("model parameters: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func resolvesThroughCatalog(modelType types.ModelType) bool {
|
||||
switch modelType {
|
||||
case types.ModelTypeKnowledgeQA, types.ModelTypeVLLM, types.ModelTypeEmbedding, types.ModelTypeRerank,
|
||||
types.ModelTypeASR:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package runtime_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
modelruntime "academy/internal/models/runtime"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
func TestValidateRow(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
modelName string
|
||||
modelType types.ModelType
|
||||
params *types.ModelParameters
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "nil parameters", modelName: "x", modelType: types.ModelTypeKnowledgeQA,
|
||||
},
|
||||
{
|
||||
name: "a catalogued embedding row resolves", modelName: "text-embedding-v4",
|
||||
modelType: types.ModelTypeEmbedding,
|
||||
params: &types.ModelParameters{Provider: "aliyun"},
|
||||
},
|
||||
{
|
||||
// Embedding is built from Resolve too, so a bad overlay fails
|
||||
// every call; it must fail the save instead.
|
||||
name: "unknown embedding compat key is rejected", modelName: "text-embedding-v4",
|
||||
modelType: types.ModelTypeEmbedding,
|
||||
params: &types.ModelParameters{
|
||||
Provider: "aliyun", Spec: &types.ModelSpecOverride{Compat: map[string]any{"max_tokens_field": "x"}},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "unknown embedding protocol is rejected", modelName: "text-embedding-v4",
|
||||
modelType: types.ModelTypeEmbedding,
|
||||
params: &types.ModelParameters{
|
||||
Provider: "aliyun", Spec: &types.ModelSpecOverride{Compat: map[string]any{"api": "openai-completions"}},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "an embedding name inside a chat glob is accepted", modelName: "qwen3.8-text-embedding",
|
||||
modelType: types.ModelTypeEmbedding,
|
||||
params: &types.ModelParameters{Provider: "aliyun"},
|
||||
},
|
||||
{
|
||||
name: "rerank truncation on a vendor without the extension is rejected", modelName: "gte-rerank-v2",
|
||||
modelType: types.ModelTypeRerank,
|
||||
params: &types.ModelParameters{
|
||||
Provider: "aliyun", ExtraConfig: map[string]string{"truncate_prompt_tokens": "512"},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "a catalogued asr row resolves", modelName: "whisper-1",
|
||||
modelType: types.ModelTypeASR,
|
||||
params: &types.ModelParameters{Provider: "openai"},
|
||||
},
|
||||
{
|
||||
name: "unknown asr compat key is rejected", modelName: "whisper-1",
|
||||
modelType: types.ModelTypeASR,
|
||||
params: &types.ModelParameters{
|
||||
Provider: "openai", Spec: &types.ModelSpecOverride{Compat: map[string]any{"dimensions_field": "x"}},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "a catalogued chat row resolves", modelName: "deepseek-v4-pro",
|
||||
modelType: types.ModelTypeKnowledgeQA,
|
||||
params: &types.ModelParameters{Provider: "deepseek"},
|
||||
},
|
||||
{
|
||||
name: "unknown protocol is rejected", modelName: "deepseek-v4-pro",
|
||||
modelType: types.ModelTypeKnowledgeQA,
|
||||
params: &types.ModelParameters{
|
||||
Provider: "deepseek", Spec: &types.ModelSpecOverride{API: "openai-chat-v9"},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "misspelled thinking level is rejected", modelName: "deepseek-v4-pro",
|
||||
modelType: types.ModelTypeKnowledgeQA,
|
||||
params: &types.ModelParameters{
|
||||
Provider: "deepseek",
|
||||
Spec: &types.ModelSpecOverride{ThinkingLevels: map[string]*string{"hgih": nil}},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "unknown compat key is rejected", modelName: "deepseek-v4-pro",
|
||||
modelType: types.ModelTypeKnowledgeQA,
|
||||
params: &types.ModelParameters{
|
||||
Provider: "deepseek",
|
||||
Spec: &types.ModelSpecOverride{Compat: map[string]any{"max_tokens_fields": "max_tokens"}},
|
||||
},
|
||||
wantErr: true,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := modelruntime.ValidateRow(tc.modelName, tc.modelType, tc.params)
|
||||
if tc.wantErr && err == nil {
|
||||
t.Fatalf("expected an error, got nil")
|
||||
}
|
||||
if !tc.wantErr && err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user