An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Simplify multimodal model settings https://github.com/siyuan-note/siyuan/issues/17797
Daniel3f87f303ad15
diff --git a/app/src/config/tabs/aiUi.ts b/app/src/config/tabs/aiUi.tsindex c328dbed4d..5de05d563b 100644--- a/app/src/config/tabs/aiUi.ts+++ b/app/src/config/tabs/aiUi.ts@@ -9,18 +9,6 @@ import {aiConfigApi} from "./aiRuntime";type ModelPickerGroup = "editing" | "agent" | "vision" | "imageGeneration";-const modelCapabilities = ["text-input", "text-output", "tool-calling", "image-input", "image-output"];--const capabilityForGroup = (group: ModelPickerGroup): string => {- if (group === "vision") {- return "image-input";- }- if (group === "imageGeneration") {- return "image-output";- }- return "";-};-export const getProvidersBlockKeywords = (): string[] => [window.siyuan.languages.apiProvider,window.siyuan.languages.apiProviderTip,@@ -642,7 +630,7 @@ const syncModelPickerSelects = (root: HTMLElement) => {// 提供商优先级:UI 选中(已启用)→ 配置归属(已启用)→ 空const providerId = pickProviderId(enabledProviders, [uiProviderId, savedProviderId]);- const enabledModels = getEnabledModels(providerId, group);+ const enabledModels = getEnabledModels(providerId);// 模型优先级:UI 选中 → 配置保存值,无效时回退到第一个可用模型const modelId = pickModelId(enabledModels, [uiModelId, storedModelId]);@@ -678,13 +666,12 @@ const lookupModelOwner = (modelId: string): {providerId: string; modelId: stringconst getEnabledProviders = () =>window.siyuan.config.ai.providers.filter((provider) => provider.enabled);-const getEnabledModels = (providerId: string, group?: ModelPickerGroup): Config.IModel[] => {+const getEnabledModels = (providerId: string): Config.IModel[] => {const provider = findProvider(providerId);if (!provider) {return [];}- const requiredCapability = group ? capabilityForGroup(group) : "";- return provider.models.filter((model) => model.enabled && (!requiredCapability || !model.capabilities?.length || model.capabilities.includes(requiredCapability)));+ return provider.models.filter((model) => model.enabled);};const buildProviderOptionsHtml = (enabledProviders: Config.IProvider[], providerId: string): string =>@@ -732,7 +719,6 @@ const openModelDialog = (root: HTMLElement, providerId: string, modelId: stringid: "",name: "",enabled: true,- capabilities: ["text-input", "text-output"],} : provider.models.find((item) => item.id === modelId);if (!isNew && !initialModel) {return;@@ -759,11 +745,6 @@ const openModelDialog = (root: HTMLElement, providerId: string, modelId: string<div class="fn__hr"></div><input class="b3-text-field fn__block" id="aiModelDisplayName" type="text" spellcheck="false" value="${Lute.EscapeHTMLStr(initialModel.displayName ?? "")}"/></div>- <div class="b3-label b3-label--inner">- <div class="config-name">${window.siyuan.languages.type}</div>- <div class="fn__hr--small"></div>- ${modelCapabilities.map((capability) => `<label class="b3-label__text" style="display: block;margin: 6px 0;"><input type="checkbox" data-type="aiModelCapability" value="${capability}"${initialModel.capabilities?.includes(capability) ? " checked" : ""}/> <code class="fn__code">${capability}</code></label>`).join("")}- </div><div style="text-align: right;"><button class="b3-button b3-button--outline" id="aiModelTestBtn"><svg class="b3-button__icon"><use xlink:href="#iconPlugZap"></use></svg><span>${window.siyuan.languages.testConnection}</span></button></div>@@ -781,7 +762,6 @@ const openModelDialog = (root: HTMLElement, providerId: string, modelId: stringconst el = dialog.element.querySelector<HTMLInputElement | HTMLSelectElement>("#aiModelName");return (el?.value ?? "").trim();};- const getModelCapabilities = () => Array.from(dialog.element.querySelectorAll<HTMLInputElement>("[data-type='aiModelCapability']:checked")).map((item) => item.value);btns[0].addEventListener("click", () => dialog.destroy());// 拉取 Provider 可用模型清单,成功后把文本框替换为下拉框供选择dialog.element.querySelector<HTMLElement>("#aiModelFetchBtn")?.addEventListener("click", () => {@@ -838,7 +818,7 @@ const openModelDialog = (root: HTMLElement, providerId: string, modelId: stringsvgEl.style.animation = "";labelSpan.textContent = window.siyuan.languages.testConnection;};- fetchPost("/api/ai/testModel", {provider: providerId, model: modelName, capabilities: getModelCapabilities()}, (response) => {+ fetchPost("/api/ai/testModel", {provider: providerId, model: modelName}, (response) => {restoreBtn();const data = response.data || {};if (data.matched) {@@ -868,7 +848,6 @@ const openModelDialog = (root: HTMLElement, providerId: string, modelId: string...initialModel,name: modelName,displayName: dialog.element.querySelector<HTMLInputElement>("#aiModelDisplayName").value,- capabilities: getModelCapabilities(),};const nextProviders = window.siyuan.config.ai.providers.map((item) => {if (item.id !== providerId) {@@ -913,7 +892,7 @@ export const genModelPickerHtml = (group: ModelPickerGroup): string => {const savedModelId = window.siyuan.config.ai[group].modelId;const {providerId, modelId: storedModelId} = lookupModelOwner(savedModelId);const enabledProviders = getEnabledProviders();- const enabledModels = getEnabledModels(providerId, group);+ const enabledModels = getEnabledModels(providerId);const modelId = pickModelId(enabledModels, [storedModelId]);let desc: string;if (group === "editing") {@@ -965,7 +944,7 @@ export const mountModelPickerBlock = (root: HTMLElement, group: ModelPickerGroup}const providerId = providerSelect.value;const {modelId: storedModelId} = lookupModelOwner(window.siyuan.config.ai[group].modelId);- const enabledModels = getEnabledModels(providerId, group);+ const enabledModels = getEnabledModels(providerId);const isProviderChange = selectEl.dataset.type === "modelPickerProvider";const modelId = pickModelId(enabledModels, isProviderChange ? [storedModelId] : [modelSelect.value]);if (isProviderChange) {diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.tsindex e853620920..241da37111 100644--- a/app/src/types/config.d.ts+++ b/app/src/types/config.d.ts@@ -228,7 +228,6 @@ declare namespace Config {enabled: boolean;name: string;displayName?: string;- capabilities?: string[];}/**diff --git a/kernel/api/ai.go b/kernel/api/ai.goindex 6b4378114a..998f2c2a4f 100644--- a/kernel/api/ai.go+++ b/kernel/api/ai.go@@ -75,11 +75,9 @@ func testModel(c *gin.Context) {}var providerID, modelName string- var rawCapabilities []anyif !util.ParseJsonArgs(arg, ret,util.BindJsonArg("provider", &providerID, true, true),util.BindJsonArg("model", &modelName, true, true),- util.BindJsonArg("capabilities", &rawCapabilities, false, false),) {return}@@ -98,13 +96,7 @@ func testModel(c *gin.Context) {return}- capabilities := make([]string, 0, len(rawCapabilities))- for _, rawCapability := range rawCapabilities {- if capability, ok := rawCapability.(string); ok {- capabilities = append(capabilities, capability)- }- }- available, matched, err := util.TestModelWithCapabilities(provider.APIKey, provider.BaseURL, modelName, capabilities, provider.RequestTimeout)+ available, matched, err := util.TestModel(provider.APIKey, provider.BaseURL, modelName, provider.RequestTimeout)// 可用模型清单裁剪到前 50 条,避免响应体过大if 50 < len(available) {available = available[:50]diff --git a/kernel/conf/ai.go b/kernel/conf/ai.goindex 38f1c99839..0226671578 100644--- a/kernel/conf/ai.go+++ b/kernel/conf/ai.go@@ -115,11 +115,10 @@ type Provider struct {// MaxContexts remain the persisted UI-facing config (the settings page still// reads/writes them). Editing holds the runtime view derived from them.type Model struct {- ID string `json:"id"`- DisplayName string `json:"displayName,omitempty"`- Enabled bool `json:"enabled"`- Name string `json:"name"`- Capabilities []string `json:"capabilities,omitempty"`+ ID string `json:"id"`+ DisplayName string `json:"displayName,omitempty"`+ Enabled bool `json:"enabled"`+ Name string `json:"name"`}type MCP struct {@@ -481,17 +480,6 @@ func (ai *AI) Normalize() {m.Name = "model"}m.DisplayName = strings.TrimSpace(m.DisplayName)- capabilities := make([]string, 0, len(m.Capabilities))- seenCapabilities := map[string]bool{}- for _, capability := range m.Capabilities {- capability = strings.ToLower(strings.TrimSpace(capability))- if capability == "" || seenCapabilities[capability] {- continue- }- seenCapabilities[capability] = true- capabilities = append(capabilities, capability)- }- m.Capabilities = capabilitiesif !ast.IsNodeIDPattern(m.ID) {m.ID = ast.NewNodeID()}diff --git a/kernel/conf/ai_multimodal_test.go b/kernel/conf/ai_multimodal_test.goindex 53836008a9..2f6bcfc896 100644--- a/kernel/conf/ai_multimodal_test.go+++ b/kernel/conf/ai_multimodal_test.go@@ -18,8 +18,8 @@ package confimport "testing"-func TestNormalizeMultimodalDefaultsAndCapabilities(t *testing.T) {- ai := &AI{Providers: []*Provider{{Enabled: true, Models: []*Model{{Enabled: true, Name: " vision ", Capabilities: []string{" Image-Input ", "image-input", " image-output "}}}}}}+func TestNormalizeMultimodalDefaults(t *testing.T) {+ ai := &AI{Providers: []*Provider{{Enabled: true, Models: []*Model{{Enabled: true, Name: " vision "}}}}}ai.Normalize()if ai.Vision == nil || ai.Vision.RequestTimeout != 300 || ai.Vision.MaxImageBytes != 20*1024*1024 || ai.Vision.MaxEdge != 2048 {t.Fatalf("unexpected vision defaults: %#v", ai.Vision)@@ -31,9 +31,8 @@ func TestNormalizeMultimodalDefaultsAndCapabilities(t *testing.T) {if provider.Protocol != "openai" {t.Fatalf("unexpected provider protocol: %q", provider.Protocol)}- capabilities := provider.Models[0].Capabilities- if len(capabilities) != 2 || capabilities[0] != "image-input" || capabilities[1] != "image-output" {- t.Fatalf("unexpected normalized capabilities: %#v", capabilities)+ if provider.Models[0].Name != "vision" {+ t.Fatalf("unexpected normalized model name: %q", provider.Models[0].Name)}}diff --git a/kernel/model/assets.go b/kernel/model/assets.goindex 16358b6119..5bfb53cc80 100644--- a/kernel/model/assets.go+++ b/kernel/model/assets.go@@ -283,11 +283,6 @@ type ImageArtifactRef struct {DocumentID string `json:"documentId,omitempty"`}-const (- capabilityImageInput = "image-input"- capabilityImageOutput = "image-output"-)-type DocumentImageList struct {DocumentID string `json:"documentId"`Images []ImageArtifactRef `json:"images"`@@ -424,7 +419,7 @@ func AnalyzeImage(ctx context.Context, data []byte, question, detail string) (Anreturn AnalyzeImageResult{}, errors.New("AI configuration is unavailable")}provider, visionModel := Conf.AI.GetVisionModel()- if err := validateMultimodalModel(provider, visionModel, capabilityImageInput); err != nil {+ if err := validateImageModel(provider, visionModel); err != nil {return AnalyzeImageResult{}, err}prepared, err := util.PrepareForVision(data, Conf.AI.Vision.MaxImageBytes, Conf.AI.Vision.MaxPixels, Conf.AI.Vision.MaxEdge)@@ -446,7 +441,7 @@ func GenerateImage(ctx context.Context, request GenerateImageRequest) (GenerateIreturn GenerateImageResult{}, errors.New("AI configuration is unavailable")}provider, generationModel := Conf.AI.GetImageGenerationModel()- if err := validateMultimodalModel(provider, generationModel, capabilityImageOutput); err != nil {+ if err := validateImageModel(provider, generationModel); err != nil {return GenerateImageResult{}, err}prompt := strings.TrimSpace(request.Prompt)@@ -507,23 +502,14 @@ func resolveMultimodalDocument(documentID string) (*treenode.BlockTree, error) {return bt, nil}-func validateMultimodalModel(provider *conf.Provider, imageModel *conf.Model, capability string) error {+func validateImageModel(provider *conf.Provider, imageModel *conf.Model) error {if provider == nil || imageModel == nil {- return fmt.Errorf("model for capability %s is not configured", capability)+ return errors.New("image model is not configured")}if provider.Protocol != "" && provider.Protocol != "openai" {return fmt.Errorf("unsupported multimodal provider protocol: %s", provider.Protocol)}- if len(imageModel.Capabilities) == 0 {- // 旧配置没有能力声明时保持兼容,新配置通过能力标记收窄选择范围。- return nil- }- for _, current := range imageModel.Capabilities {- if current == capability {- return nil- }- }- return fmt.Errorf("model %s does not declare capability %s", imageModel.Name, capability)+ return nil}func documentReferencesImage(rootID, assetPath string) bool {diff --git a/kernel/model/assets_test.go b/kernel/model/assets_test.goindex e00091bcb0..7bc12c8b47 100644--- a/kernel/model/assets_test.go+++ b/kernel/model/assets_test.go@@ -47,7 +47,7 @@ func TestAnalyzeImageDoesNotRequireDocument(t *testing.T) {modelID := "20260715130000-abcdefg"ai.Providers = []*conf.Provider{{ID: "provider", Enabled: true, APIKey: "test", BaseURL: server.URL + "/v1", Protocol: "openai", RequestTimeout: 5,- Models: []*conf.Model{{ID: modelID, Enabled: true, Name: "vision-model", Capabilities: []string{"image-input"}}},+ Models: []*conf.Model{{ID: modelID, Enabled: true, Name: "vision-model"}},}}ai.Vision.ModelID = modelIDConf = NewAppConf()@@ -83,7 +83,7 @@ func TestGenerateImageDoesNotRequireDocument(t *testing.T) {modelID := "20260715130000-hijklmn"ai.Providers = []*conf.Provider{{ID: "provider", Enabled: true, APIKey: "test", BaseURL: server.URL + "/v1", Protocol: "openai", RequestTimeout: 5,- Models: []*conf.Model{{ID: modelID, Enabled: true, Name: "image-model", Capabilities: []string{"image-output"}}},+ Models: []*conf.Model{{ID: modelID, Enabled: true, Name: "image-model"}},}}ai.ImageGeneration.ModelID = modelIDConf = NewAppConf()@@ -112,8 +112,8 @@ func TestMultimodalProviderErrorsPreventAutomaticRetry(t *testing.T) {ai.Providers = []*conf.Provider{{ID: "provider", Enabled: true, APIKey: "test", BaseURL: server.URL + "/v1", Protocol: "openai", RequestTimeout: 5,Models: []*conf.Model{- {ID: visionModelID, Enabled: true, Name: "vision-model", Capabilities: []string{"image-input"}},- {ID: generationModelID, Enabled: true, Name: "image-model", Capabilities: []string{"image-output"}},+ {ID: visionModelID, Enabled: true, Name: "vision-model"},+ {ID: generationModelID, Enabled: true, Name: "image-model"},},}}ai.Vision.ModelID = visionModelIDdiff --git a/kernel/util/openai.go b/kernel/util/openai.goindex ee3747630c..de4436422a 100644--- a/kernel/util/openai.go+++ b/kernel/util/openai.go@@ -232,11 +232,6 @@ func NewOpenAIClientWithModel(apiKey, apiBaseURL, model string) *openai.Client {// 返回值:available 为可用模型清单(仅 ListModels 成功时填充),matched 表示 model 是否可用,// err 为请求错误(鉴权失败、网络异常、模型不存在等,原样返回便于调用方展示原因)。func TestModel(apiKey, apiBaseURL, model string, timeout int) (available []string, matched bool, err error) {- return TestModelWithCapabilities(apiKey, apiBaseURL, model, nil, timeout)-}--// TestModelWithCapabilities 根据模型能力选择安全的回退测试。图片生成模型不会为测试连接而产生计费图片。-func TestModelWithCapabilities(apiKey, apiBaseURL, model string, capabilities []string, timeout int) (available []string, matched bool, err error) {if 1 > timeout {timeout = 30}@@ -258,28 +253,9 @@ func TestModelWithCapabilities(apiKey, apiBaseURL, model string, capabilities []return}- if hasModelCapability(capabilities, "image-output") {- return nil, false, fmt.Errorf("list models failed and image generation capability cannot be tested without creating a potentially billed image: %w", listErr)- }-// ListModels 不可用时回退到极简 Chat Completion 验证连通性与鉴权logging.LogInfof("list models failed [%s], fallback to chat completion: %s", apiBaseURL, listErr)messages := []openai.ChatCompletionMessage{{Role: "user", Content: "1"}}- if hasModelCapability(capabilities, "image-input") {- messages = []openai.ChatCompletionMessage{{- Role: openai.ChatMessageRoleUser,- MultiContent: []openai.ChatMessagePart{- {Type: openai.ChatMessagePartTypeText, Text: "Reply with 1."},- {- Type: openai.ChatMessagePartTypeImageURL,- ImageURL: &openai.ChatMessageImageURL{- URL: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",- Detail: openai.ImageURLDetailLow,- },- },- },- }}- }_, err = client.CreateChatCompletion(ctx, openai.ChatCompletionRequest{Model: model,Messages: messages,@@ -294,15 +270,6 @@ func TestModelWithCapabilities(apiKey, apiBaseURL, model string, capabilities []return}-func hasModelCapability(capabilities []string, target string) bool {- for _, capability := range capabilities {- if strings.EqualFold(strings.TrimSpace(capability), target) {- return true- }- }- return false-}-// TestEmbeddingModel 测试嵌入模型可用性,发送极简文本并返回首个向量维度。// 返回值:matched 表示是否连通成功,dimensions 为返回的向量维度(便于核对配置),// err 为请求错误(鉴权失败、网络异常、模型不存在等,原样返回便于调用方展示原因)。diff --git a/kernel/util/openai_multimodal_test.go b/kernel/util/openai_multimodal_test.goindex 31d7233d62..17c68363ee 100644--- a/kernel/util/openai_multimodal_test.go+++ b/kernel/util/openai_multimodal_test.go@@ -31,7 +31,7 @@ import ("testing")-func TestModelWithImageInputCapability(t *testing.T) {+func TestModelFallsBackToChatCompletion(t *testing.T) {var chatRequests atomic.Int32server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {switch r.URL.Path {@@ -43,9 +43,8 @@ func TestModelWithImageInputCapability(t *testing.T) {if err := json.NewDecoder(r.Body).Decode(&body); err != nil {t.Error(err)}- encoded, _ := json.Marshal(body)- if !strings.Contains(string(encoded), "data:image/png;base64,") {- t.Errorf("vision capability test did not include an image: %s", encoded)+ if body["model"] != "test-model" {+ t.Errorf("unexpected model test request: %#v", body)}w.Header().Set("Content-Type", "application/json")_, _ = w.Write([]byte(`{"choices":[{"message":{"role":"assistant","content":"1"}}]}`))@@ -55,30 +54,9 @@ func TestModelWithImageInputCapability(t *testing.T) {}))defer server.Close()- _, matched, err := TestModelWithCapabilities("test", server.URL+"/v1", "vision-model", []string{"image-input"}, 5)+ _, matched, err := TestModel("test", server.URL+"/v1", "test-model", 5)if err != nil || !matched || chatRequests.Load() != 1 {- t.Fatalf("unexpected vision model test result: matched=%v requests=%d err=%v", matched, chatRequests.Load(), err)- }-}--func TestModelWithImageOutputDoesNotGenerateBillableImage(t *testing.T) {- var nonListRequests atomic.Int32- server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.URL.Path == "/v1/models" {- http.Error(w, "unsupported", http.StatusNotFound)- return- }- nonListRequests.Add(1)- http.NotFound(w, r)- }))- defer server.Close()-- _, matched, err := TestModelWithCapabilities("test", server.URL+"/v1", "image-model", []string{"image-output"}, 5)- if err == nil || matched || nonListRequests.Load() != 0 {- t.Fatalf("image generation test must stop after model listing: matched=%v requests=%d err=%v", matched, nonListRequests.Load(), err)- }- if !strings.Contains(err.Error(), "potentially billed image") {- t.Fatalf("unexpected image generation test error: %v", err)+ t.Fatalf("unexpected model test result: matched=%v requests=%d err=%v", matched, chatRequests.Load(), err)}}