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: Improve AI model configuration by allowing custom model names https://github.com/siyuan-note/siyuan/issues/19071
Daniel52bb2bb6a5b7
diff --git a/app/src/config/tabs/ai/aiProviderUi.ts b/app/src/config/tabs/ai/aiProviderUi.tsindex 23e08e0b04..96c2f7aa41 100644--- a/app/src/config/tabs/ai/aiProviderUi.ts+++ b/app/src/config/tabs/ai/aiProviderUi.ts@@ -262,8 +262,7 @@ const renderDraftModels = (container: HTMLElement, models: Config.IModel[], avaicontainer.innerHTML = `<div class="b3-label config-item b3-card__desc">${window.siyuan.languages.noModelConfigured}</div>`;return;}- const modelInputClass = availableModels.length > 0 ? "b3-select" : "b3-text-field";- const modelInputAction = availableModels.length > 0 ? ' data-action="selectModel" data-menu="true" readonly' : "";+ const modelInputAction = availableModels.length > 0 ? ' data-action="selectModel" data-menu="true"' : "";container.innerHTML = models.map((model, index) => `<div class="fn__flex b3-label config-item config-wrap config-ai-provider__model" data-model-index="${index}"><button class="block__icon block__icon--show config-ai-provider__model-drag" data-action="sortModel" type="button" draggable="true" aria-label="${window.siyuan.languages.sort}"><svg><use xlink:href="#iconDrag"></use></svg>@@ -271,7 +270,7 @@ const renderDraftModels = (container: HTMLElement, models: Config.IModel[], avai<span class="fn__space"></span><input class="b3-switch fn__flex-center" data-model-field="enabled" type="checkbox"${model.enabled ? " checked" : ""} aria-label="${window.siyuan.languages.enable}"><span class="fn__space"></span>- <input class="${modelInputClass} fn__flex-1" data-model-field="name" type="text"${modelInputAction} spellcheck="false" placeholder="${window.siyuan.languages.selectModel}" value="${escapeHTML(model.name)}">+ <input class="b3-text-field fn__flex-1" data-model-field="name" type="text"${modelInputAction} spellcheck="false" placeholder="${window.siyuan.languages.selectModel}" value="${escapeHTML(model.name)}"><span class="fn__space"></span><input class="b3-text-field fn__flex-1" data-model-field="displayName" type="text" spellcheck="false" placeholder="${window.siyuan.languages.customDisplayName}" value="${escapeHTML(model.displayName || "")}"><span class="fn__space"></span>@@ -364,7 +363,6 @@ const openAvailableModelMenu = (modelInput: HTMLInputElement, models: string[])const rect = modelInput.getBoundingClientRect();menu.open({x: rect.left, y: rect.bottom, h: rect.height, w: rect.width, target: modelInput});menu.element.querySelector(".b3-menu__items").setAttribute("style", "overflow: initial");- menu.element.querySelector<HTMLInputElement>("input").focus();};const showTestResult = (data: Record<string, unknown>) => {@@ -614,10 +612,9 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPrif (!modelInput) {return;}+ modelInput.focus();if (availableModels.length > 0) {openAvailableModelMenu(modelInput, availableModels);- } else {- modelInput.focus();}};@@ -787,7 +784,7 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPrview.addEventListener("keydown", (event) => {const target = event.target as HTMLInputElement;if (target.dataset.action !== "selectModel" ||- !["Enter", " ", "ArrowDown"].includes(event.key)) {+ !["Enter", "ArrowDown"].includes(event.key)) {return;}event.preventDefault();diff --git a/kernel/util/openai.go b/kernel/util/openai.goindex 98052e3927..658ee838bc 100644--- a/kernel/util/openai.go+++ b/kernel/util/openai.go@@ -237,7 +237,7 @@ func NewOpenAIClientWithModel(apiKey, apiBaseURL, model string) *openai.Client {}// TestModel 测试模型可用性。优先调用 ListModels(GET /v1/models)拉取可用模型清单,-// 校验 model 是否在其中;若该端点不可用,则按 Provider 协议回退到极简文本生成请求。+// 列表不包含指定模型或该端点不可用时,按 Provider 协议回退到极简文本生成请求。// 返回值:available 为可用模型清单(仅 ListModels 成功时填充),matched 表示 model 是否可用,// err 为请求错误(鉴权失败、网络异常、模型不存在等,原样返回便于调用方展示原因)。func TestModel(apiKey, apiBaseURL, protocol, model string, timeout int) (available []string, matched bool, err error) {@@ -259,11 +259,15 @@ func TestModel(apiKey, apiBaseURL, protocol, model string, timeout int) (availabmatched = true}}- return+ if matched {+ return+ }+ logging.LogInfof("model [%s] not found in available list, fallback to text completion", model)+ } else {+ // ListModels 不可用时回退到极简文本生成请求验证连通性与鉴权。+ logging.LogInfof("list models failed [%s], fallback to text completion: %s", apiBaseURL, listErr)}- // ListModels 不可用时回退到极简文本生成请求验证连通性与鉴权。- logging.LogInfof("list models failed [%s], fallback to text completion: %s", apiBaseURL, listErr)messages := []openai.ChatCompletionMessage{{Role: "user", Content: "1"}}_, err = CreateOpenAICompletion(ctx, client, protocol, openai.ChatCompletionRequest{Model: model,@@ -276,7 +280,6 @@ func TestModel(apiKey, apiBaseURL, protocol, model string, timeout int) (availabreturn}matched = true- available = nilreturn}diff --git a/kernel/util/openai_completion_test.go b/kernel/util/openai_completion_test.goindex 11fb3dae12..1cfd6da8b9 100644--- a/kernel/util/openai_completion_test.go+++ b/kernel/util/openai_completion_test.go@@ -339,3 +339,35 @@ func TestModelFallsBackToResponses(t *testing.T) {available, matched, responsesCalled)}}++func TestModelFallsBackWhenAvailableListOmitsModel(t *testing.T) {+ var completionCalled bool+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/v1/models":+ w.Header().Set("Content-Type", "application/json")+ _, _ = fmt.Fprint(w, "{\"object\":\"list\",\"data\":[{\"id\":\"listed-model\","++ "\"object\":\"model\",\"created\":0,\"owned_by\":\"test\"}]}")+ case "/v1/chat/completions":+ completionCalled = true+ w.Header().Set("Content-Type", "application/json")+ _, _ = fmt.Fprint(w, "{\"id\":\"chatcmpl-1\",\"object\":\"chat.completion\","++ "\"created\":0,\"model\":\"custom-model\",\"choices\":[{\"index\":0,"++ "\"message\":{\"role\":\"assistant\",\"content\":\"1\"},\"finish_reason\":\"stop\"}]}")+ default:+ t.Errorf("unexpected path: %s", r.URL.Path)+ w.WriteHeader(http.StatusNotFound)+ }+ }))+ defer server.Close()++ available, matched, err := TestModel(+ "test", server.URL+"/v1", OpenAIProtocolChatCompletions, "custom-model", 5)+ if err != nil {+ t.Fatal(err)+ }+ if len(available) != 1 || available[0] != "listed-model" || !matched || !completionCalled {+ t.Fatalf("unexpected model test result: available=%v, matched=%v, completion=%v",+ available, matched, completionCalled)+ }+}