An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Correct Anthropic provider endpoints and authentication https://github.com/siyuan-note/siyuan/issues/17845
Daniel4776ff7cf1c9
diff --git a/app/src/config/tabs/ai/aiProviderPresets.test.ts b/app/src/config/tabs/ai/aiProviderPresets.test.tsindex 2342b96951..a4c539d761 100644--- a/app/src/config/tabs/ai/aiProviderPresets.test.ts+++ b/app/src/config/tabs/ai/aiProviderPresets.test.ts@@ -3,6 +3,7 @@ import {describe, it} from "node:test";import {findProviderPreset,getDefaultProviderProtocol,+ getProviderProtocolBaseURL,getResponsesSupport,PROVIDER_PRESETS,} from "./aiProviderPresets";@@ -34,4 +35,47 @@ describe("AI provider presets", () => {assert.equal(getResponsesSupport("https://open.bigmodel.cn/api/paas/v4"), "unsupported");assert.equal(getResponsesSupport("https://example.com/v1"), "experimental");});++ it("switches DeepSeek standard endpoints with the selected protocol", () => {+ for (const baseURL of [+ "https://api.deepseek.com", "https://api.deepseek.com/v1/",+ "https://api.deepseek.com/anthropic", "https://api.deepseek.com/anthropic/v1/",+ ]) {+ assert.equal(findProviderPreset(baseURL)?.id, "deepseek");+ assert.equal(getProviderProtocolBaseURL(baseURL, "anthropic-messages"), "https://api.deepseek.com/anthropic");+ assert.equal(getProviderProtocolBaseURL(baseURL, "openai"), "https://api.deepseek.com");+ assert.equal(getProviderProtocolBaseURL(baseURL, "openai-responses"), "https://api.deepseek.com");+ assert.equal(getProviderProtocolBaseURL(baseURL, "unknown"), baseURL);+ }+ });++ it("round-trips provider protocols without changing regions", () => {+ for (const [id, openai, anthropic] of [+ ["moonshot", "https://api.moonshot.cn/v1", "https://api.moonshot.cn/anthropic"],+ ["minimax", "https://api.minimax.io/v1", "https://api.minimax.io/anthropic"],+ ["minimax-cn", "https://api.minimax.cn/v1", "https://api.minimax.cn/anthropic"],+ ["aliyun", "https://dashscope.aliyuncs.com/compatible-mode/v1", "https://dashscope.aliyuncs.com/apps/anthropic"],+ ["aliyun-intl", "https://dashscope-intl.aliyuncs.com/compatible-mode/v1", "https://dashscope-intl.aliyuncs.com/apps/anthropic"],+ ]) {+ assert.equal(getProviderProtocolBaseURL(openai, "anthropic-messages"), anthropic);+ for (const baseURL of [anthropic, anthropic + "/v1/"]) {+ assert.equal(findProviderPreset(baseURL)?.id, id);+ assert.equal(getProviderProtocolBaseURL(baseURL, "openai"), openai);+ assert.equal(getProviderProtocolBaseURL(baseURL, "openai-responses"), openai);+ }+ for (const baseURL of [anthropic + "?route=custom", anthropic + "/custom"]) {+ assert.equal(getProviderProtocolBaseURL(baseURL, "openai"), baseURL);+ }+ }+ });++ it("preserves custom endpoints and providers without protocol-specific addresses", () => {+ for (const baseURL of [+ "https://gateway.example.com/deepseek/v1", "https://api.deepseek.com/custom",+ "https://api.deepseek.com?route=custom", "https://api.deepseek.com/anthropic?route=custom",+ "https://api.deepseek.com.example.com", "https://api.openai.com/v1",+ ]) {+ assert.equal(getProviderProtocolBaseURL(baseURL, "anthropic-messages"), baseURL);+ }+ });});diff --git a/app/src/config/tabs/ai/aiProviderPresets.ts b/app/src/config/tabs/ai/aiProviderPresets.tsindex c03a782661..62d612ddbf 100644--- a/app/src/config/tabs/ai/aiProviderPresets.ts+++ b/app/src/config/tabs/ai/aiProviderPresets.ts@@ -5,6 +5,7 @@ export interface IProviderPreset {id: string;name: string;baseURL: string;+ protocolBaseURLs?: Record<string, string>;category: AIProviderCategory;responsesSupport: AIResponsesSupport;region?: "china" | "international";@@ -14,12 +15,35 @@ export interface IProviderPreset {export const PROVIDER_PRESETS: IProviderPreset[] = [{id: "openai", name: "OpenAI", baseURL: "https://api.openai.com/v1", category: "official", responsesSupport: "supported", icon: "/stage/images/ai-providers/openai.svg"},{id: "anthropic", name: "Anthropic", baseURL: "https://api.anthropic.com/v1", category: "official", responsesSupport: "unsupported"},- {id: "deepseek", name: "DeepSeek", baseURL: "https://api.deepseek.com", category: "official", responsesSupport: "supported", icon: "/stage/images/ai-providers/deepseek.svg"},- {id: "moonshot", name: "Moonshot AI", baseURL: "https://api.moonshot.cn/v1", category: "official", responsesSupport: "experimental", icon: "/stage/images/ai-providers/moonshot.svg"},- {id: "minimax", name: "MiniMax", baseURL: "https://api.minimax.io/v1", category: "official", responsesSupport: "experimental", region: "international", icon: "/stage/images/ai-providers/minimax.svg"},- {id: "minimax-cn", name: "MiniMax", baseURL: "https://api.minimax.cn/v1", category: "official", responsesSupport: "experimental", region: "china", icon: "/stage/images/ai-providers/minimax.svg"},- {id: "aliyun", name: "Alibaba Model Studio", baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1", category: "official", responsesSupport: "supported", region: "china", icon: "/stage/images/ai-providers/aliyun.svg"},- {id: "aliyun-intl", name: "Alibaba Model Studio", baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1", category: "official", responsesSupport: "supported", region: "international", icon: "/stage/images/ai-providers/aliyun.svg"},+ {+ id: "deepseek", name: "DeepSeek", baseURL: "https://api.deepseek.com", category: "official", responsesSupport: "supported",+ icon: "/stage/images/ai-providers/deepseek.svg",+ protocolBaseURLs: {+ "openai": "https://api.deepseek.com",+ "openai-responses": "https://api.deepseek.com",+ "anthropic-messages": "https://api.deepseek.com/anthropic",+ },+ },+ {+ id: "moonshot", name: "Moonshot AI", baseURL: "https://api.moonshot.cn/v1", category: "official", responsesSupport: "experimental", icon: "/stage/images/ai-providers/moonshot.svg",+ protocolBaseURLs: {"anthropic-messages": "https://api.moonshot.cn/anthropic"},+ },+ {+ id: "minimax", name: "MiniMax", baseURL: "https://api.minimax.io/v1", category: "official", responsesSupport: "experimental", region: "international", icon: "/stage/images/ai-providers/minimax.svg",+ protocolBaseURLs: {"anthropic-messages": "https://api.minimax.io/anthropic"},+ },+ {+ id: "minimax-cn", name: "MiniMax", baseURL: "https://api.minimax.cn/v1", category: "official", responsesSupport: "experimental", region: "china", icon: "/stage/images/ai-providers/minimax.svg",+ protocolBaseURLs: {"anthropic-messages": "https://api.minimax.cn/anthropic"},+ },+ {+ id: "aliyun", name: "Alibaba Model Studio", baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1", category: "official", responsesSupport: "supported", region: "china", icon: "/stage/images/ai-providers/aliyun.svg",+ protocolBaseURLs: {"anthropic-messages": "https://dashscope.aliyuncs.com/apps/anthropic"},+ },+ {+ id: "aliyun-intl", name: "Alibaba Model Studio", baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1", category: "official", responsesSupport: "supported", region: "international", icon: "/stage/images/ai-providers/aliyun.svg",+ protocolBaseURLs: {"anthropic-messages": "https://dashscope-intl.aliyuncs.com/apps/anthropic"},+ },{id: "volcengine", name: "Volcengine Ark", baseURL: "https://ark.cn-beijing.volces.com/api/v3", category: "official", responsesSupport: "experimental", icon: "/stage/images/ai-providers/volcengine.svg"},{id: "zhipu", name: "Zhipu AI", baseURL: "https://open.bigmodel.cn/api/paas/v4", category: "official", responsesSupport: "unsupported", icon: "/stage/images/ai-providers/zhipu.svg"},{id: "gemini", name: "Gemini", baseURL: "https://generativelanguage.googleapis.com/v1beta/openai", category: "official", responsesSupport: "unsupported", icon: "/stage/images/ai-providers/gemini.svg"},@@ -34,9 +58,22 @@ export const PROVIDER_PRESETS: IProviderPreset[] = [export const normalizeProviderBaseURL = (value: string) => value.trim().replace(/\/+$/, "").toLowerCase();+const normalizePresetBaseURL = (value: string) => normalizeProviderBaseURL(value).replace(/\/v1$/, "");+export const findProviderPreset = (baseURL: string) =>PROVIDER_PRESETS.find((preset) => preset.baseURL &&- normalizeProviderBaseURL(preset.baseURL) === normalizeProviderBaseURL(baseURL));+ [preset.baseURL, ...Object.values(preset.protocolBaseURLs || {})].some((value) =>+ normalizePresetBaseURL(value) === normalizePresetBaseURL(baseURL)));++// 只切换预设的标准地址,保留用户自行配置的网关和查询参数。+export const getProviderProtocolBaseURL = (baseURL: string, protocol: string): string => {+ const preset = findProviderPreset(baseURL);+ if (!preset?.protocolBaseURLs) {+ return baseURL;+ }+ return preset.protocolBaseURLs[protocol] ||+ (["openai", "openai-responses"].includes(protocol) ? preset.baseURL : baseURL);+};export const getResponsesSupport = (baseURL: string): AIResponsesSupport =>findProviderPreset(baseURL)?.responsesSupport || "experimental";diff --git a/app/src/config/tabs/ai/aiProviderUi.ts b/app/src/config/tabs/ai/aiProviderUi.tsindex 8b9995645f..d9ba7f4274 100644--- a/app/src/config/tabs/ai/aiProviderUi.ts+++ b/app/src/config/tabs/ai/aiProviderUi.ts@@ -11,6 +11,7 @@ import {hasProviderHeaderAuth, parseProviderHeaders} from "./aiProviderHeaders";import {findProviderPreset,getDefaultProviderProtocol,+ getProviderProtocolBaseURL,getResponsesSupport,IProviderPreset,PROVIDER_PRESETS,@@ -777,6 +778,9 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPrconst target = event.target as HTMLInputElement;if (target.dataset.providerField === "protocol") {draft.protocol = target.value;+ draft.baseURL = getProviderProtocolBaseURL(draft.baseURL, draft.protocol);+ view.querySelector<HTMLInputElement>("[data-provider-field='baseURL']").value = draft.baseURL;+ updateModelActionButtons();updateResponsesCompatibility();return;}diff --git a/kernel/util/anthropic.go b/kernel/util/anthropic.goindex f3428077f5..15366560bf 100644--- a/kernel/util/anthropic.go+++ b/kernel/util/anthropic.go@@ -64,7 +64,12 @@ func newAnthropicHTTPClient(apiKey, baseURL string, headers ...map[string]stringmerged := http.Header{}merged.Set("anthropic-version", "2023-06-01")if apiKey != "" {- merged.Set("x-api-key", apiKey)+ endpoint, _ := url.Parse(strings.TrimSpace(baseURL))+ if endpoint != nil && strings.EqualFold(endpoint.Hostname(), "openrouter.ai") {+ merged.Set("Authorization", "Bearer "+apiKey)+ } else {+ merged.Set("x-api-key", apiKey)+ }}if len(headers) > 0 {if ValidateAIProviderHeaders(headers[0]) != nil {@@ -87,11 +92,12 @@ func anthropicEndpoint(baseURL, resource string) (string, error) {if err != nil || endpoint.Host == "" || (endpoint.Scheme != "http" && endpoint.Scheme != "https") {return "", errors.New("invalid Anthropic API base URL")}- endpoint.Path = strings.TrimRight(endpoint.Path, "/")- if endpoint.Path == "" {- endpoint.Path = "/v1"+ // 与 Anthropic SDK 一样在基础地址后追加版本路径,同时兼容已包含 /v1 的配置。+ if strings.HasSuffix(strings.TrimRight(endpoint.Path, "/"), "/v1") {+ endpoint = endpoint.JoinPath(resource)+ } else {+ endpoint = endpoint.JoinPath("v1", resource)}- endpoint.Path += "/" + resourcereturn endpoint.String(), nil}diff --git a/kernel/util/anthropic_models.go b/kernel/util/anthropic_models.goindex 78b894ded9..cdc34e8302 100644--- a/kernel/util/anthropic_models.go+++ b/kernel/util/anthropic_models.go@@ -16,6 +16,9 @@ func ListProviderModels(apiKey, baseURL, protocol string, timeout int, headers .if !IsAnthropicMessagesProtocol(protocol) {return ListAvailableModelsWithContext(apiKey, baseURL, timeout, headers...)}+ if modelsBaseURL := anthropicModelsBaseURL(baseURL); modelsBaseURL != "" {+ return ListAvailableModelsWithContext(apiKey, modelsBaseURL, timeout, headers...)+ }if timeout < 1 {timeout = 30}@@ -24,6 +27,26 @@ func ListProviderModels(apiKey, baseURL, protocol string, timeout int, headers .return listAnthropicModels(ctx, NewAIClientWithModel(apiKey, baseURL, "", headers...))}+// 百炼的 Messages 入口不提供模型列表,使用同一源站的 OpenAI 兼容入口。+func anthropicModelsBaseURL(baseURL string) string {+ endpoint, err := url.Parse(strings.TrimSpace(baseURL))+ if err != nil || endpoint.Scheme != "https" || endpoint.User != nil || endpoint.RawQuery != "" || endpoint.Fragment != "" {+ return ""+ }+ switch strings.ToLower(endpoint.Host) {+ case "dashscope.aliyuncs.com", "dashscope-intl.aliyuncs.com":+ default:+ return ""+ }+ path := strings.TrimRight(endpoint.Path, "/")+ if path != "/apps/anthropic" && path != "/apps/anthropic/v1" {+ return ""+ }+ endpoint.Path = "/compatible-mode/v1"+ endpoint.RawPath = ""+ return endpoint.String()+}+func listAnthropicModels(ctx context.Context, client *AIClient) ([]AvailableModel, error) {var models []AvailableModelcursor := ""diff --git a/kernel/util/anthropic_providers_test.go b/kernel/util/anthropic_providers_test.gonew file mode 100644index 0000000000..da6ce7d432--- /dev/null+++ b/kernel/util/anthropic_providers_test.go@@ -0,0 +1,84 @@+package util++import (+ "io"+ "net/http"+ "strings"+ "testing"++ "github.com/siyuan-note/httpclient"+)++type anthropicProviderRoundTrip func(*http.Request) (*http.Response, error)++func (f anthropicProviderRoundTrip) RoundTrip(r *http.Request) (*http.Response, error) {+ return f(r)+}++func TestAnthropicProviderAuthentication(t *testing.T) {+ for _, test := range []struct {+ baseURL string+ headers map[string]string+ auth string+ key string+ }{+ {"https://openrouter.ai/api/v1", nil, "Bearer key", ""},+ {"https://openrouter.ai/api", map[string]string{"authorization": "Bearer custom"}, "Bearer custom", ""},+ {"https://api.anthropic.com/v1", nil, "", "key"},+ {"https://openrouter.ai.example.com/api/v1", nil, "", "key"},+ } {+ t.Run(test.baseURL+test.auth, func(t *testing.T) {+ client := newAnthropicHTTPClient("key", test.baseURL, test.headers)+ transport := client.Transport.(*httpclient.UserAgentTransport).Base.(*aiProviderHeaderTransport)+ calls := 0+ transport.base = anthropicProviderRoundTrip(func(r *http.Request) (*http.Response, error) {+ calls+++ if calls == 1 {+ if r.Header.Get("Authorization") != test.auth || r.Header.Get("x-api-key") != test.key {+ t.Error("unexpected provider credentials")+ }+ return &http.Response{StatusCode: http.StatusTemporaryRedirect,+ Header: http.Header{"Location": {"https://other.example.com/messages"}},+ Body: io.NopCloser(strings.NewReader("")), Request: r}, nil+ }+ if r.Header.Get("Authorization") != "" || r.Header.Get("x-api-key") != "" {+ t.Error("credentials sent to redirect destination")+ }+ return &http.Response{StatusCode: http.StatusOK, Header: http.Header{},+ Body: io.NopCloser(strings.NewReader("{}")), Request: r}, nil+ })+ response, err := client.Get(test.baseURL + "/messages")+ if err != nil {+ t.Fatal(err)+ }+ response.Body.Close()+ if calls != 2 {+ t.Fatalf("expected request and redirect, got %d", calls)+ }+ })+ }+}++func TestAnthropicProviderModelsEndpoint(t *testing.T) {+ for _, host := range []string{"dashscope.aliyuncs.com", "dashscope-intl.aliyuncs.com"} {+ for _, suffix := range []string{"", "/", "/v1", "/v1/"} {+ input := "https://" + host + "/apps/anthropic" + suffix+ want := "https://" + host + "/compatible-mode/v1"+ if got := anthropicModelsBaseURL(input); got != want {+ t.Errorf("models endpoint for %s: got %s, want %s", input, got, want)+ }+ }+ }+ for _, input := range []string{+ "https://api.anthropic.com/v1", "https://gateway.example.com/apps/anthropic",+ "https://dashscope.aliyuncs.com.example.com/apps/anthropic",+ "https://dashscope.aliyuncs.com/apps/anthropic?route=custom",+ "https://dashscope.aliyuncs.com/custom/apps/anthropic",+ "https://coding.dashscope.aliyuncs.com/apps/anthropic",+ "https://dashscope.aliyuncs.com:8443/apps/anthropic",+ } {+ if got := anthropicModelsBaseURL(input); got != "" {+ t.Errorf("custom endpoint must be preserved: %s became %s", input, got)+ }+ }+}diff --git a/kernel/util/anthropic_test.go b/kernel/util/anthropic_test.goindex a0ad70e290..53ff83d5ad 100644--- a/kernel/util/anthropic_test.go+++ b/kernel/util/anthropic_test.go@@ -67,7 +67,7 @@ func TestAnthropicStreamAndNativeHistory(t *testing.T) {writeAnthropicEvents(w, anthropicToolEvents...)}))defer server.Close()- client := NewAIClientWithModel("key", server.URL+"/gateway/v1", "test", map[string]string{+ client := NewAIClientWithModel("key", server.URL+"/gateway", "test", map[string]string{"X-Api-Key": "override-key", "X-Custom": "custom",})stream, err := CreateOpenAICompletionStream(context.Background(), client, AnthropicProtocolMessages,@@ -259,7 +259,7 @@ func TestAnthropicModelsPagination(t *testing.T) {calls := 0server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {calls++- if r.URL.Path != "/v1/models" || r.Header.Get("x-api-key") != "key" || r.Header.Get("anthropic-version") == "" {+ if r.URL.Path != "/anthropic/v1/models" || r.Header.Get("x-api-key") != "key" || r.Header.Get("anthropic-version") == "" {t.Errorf("unexpected model request: %s %v", r.URL.Path, r.Header)}if r.URL.Query().Get("after_id") == "" {@@ -272,12 +272,36 @@ func TestAnthropicModelsPagination(t *testing.T) {}}))defer server.Close()- models, err := ListProviderModels("key", server.URL, AnthropicProtocolMessages, 5)+ models, err := ListProviderModels("key", server.URL+"/anthropic", AnthropicProtocolMessages, 5)if err != nil || calls != 2 || len(models) != 2 || models[0].ContextLength != 200000 || models[1].ContextLength != 0 {t.Fatalf("unexpected model list: %+v %v", models, err)}}+func TestAnthropicEndpointPrefixes(t *testing.T) {+ for _, tc := range []struct{ base, prefix string }{+ {"https://api.anthropic.com", "https://api.anthropic.com/v1/"},+ {"https://api.anthropic.com/v1/", "https://api.anthropic.com/v1/"},+ {"https://api.deepseek.com/anthropic", "https://api.deepseek.com/anthropic/v1/"},+ {"https://api.deepseek.com/anthropic/", "https://api.deepseek.com/anthropic/v1/"},+ {"https://api.deepseek.com/anthropic/v1", "https://api.deepseek.com/anthropic/v1/"},+ {"https://gateway.example.com/custom", "https://gateway.example.com/custom/v1/"},+ {"https://gateway.example.com/custom/v1/", "https://gateway.example.com/custom/v1/"},+ {"https://gateway.example.com/a%2Fb", "https://gateway.example.com/a%2Fb/v1/"},+ } {+ for _, resource := range []string{"messages", "models"} {+ got, err := anthropicEndpoint(tc.base, resource)+ if err != nil || got != tc.prefix+resource {+ t.Errorf("endpoint for %s %s: %q, %v", tc.base, resource, got, err)+ }+ }+ }+ got, err := anthropicEndpoint("https://gateway.example.com/anthropic?route=custom", "messages")+ if err != nil || got != "https://gateway.example.com/anthropic/v1/messages?route=custom" {+ t.Fatalf("query parameters changed: %q %v", got, err)+ }+}+func TestAnthropicCancellationAndCredentialRedirect(t *testing.T) {t.Run("cancel", func(t *testing.T) {server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {