Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:art: Improve AI model context length detection https://github.com/siyuan-note/siyuan/issues/18442

Daniel6d23075f6fd5
diff --git a/app/src/config/tabs/ai/aiProviderUi.ts b/app/src/config/tabs/ai/aiProviderUi.ts
index 2216e1d121..f517ae5606 100644
--- a/app/src/config/tabs/ai/aiProviderUi.ts
+++ b/app/src/config/tabs/ai/aiProviderUi.ts
@@ -448,10 +448,13 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPr
const fetchModelsButton = view.querySelector<HTMLButtonElement>("[data-action='fetchModels']");
const confirmButton = view.querySelector<HTMLButtonElement>("[data-action='confirm']");
let availableModels: string[] = [];
+ let availableModelContextLengths: Record<string, number> = {};
let hasFetchedModels = false;
let fetchingModels = false;
+ const getAvailableModelContextLength = (name: string) =>
+ availableModelContextLengths[name] || availableModelContextLengths[name.toLowerCase()] || 0;
const updateModelActionButtons = () => {
- const disabled = fetchingModels || !draft.apiKey.trim();
+ const disabled = fetchingModels || !draft.baseURL.trim();
addModelButton.disabled = disabled;
fetchModelsButton.disabled = disabled;
};
@@ -478,11 +481,6 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPr
if (fetchingModels) {
return;
}
- if (!draft.apiKey.trim()) {
- view.querySelector<HTMLInputElement>("[data-provider-field='apiKey']")?.focus();
- showMessage(window.siyuan.languages.apiKeyTip, undefined, "error");
- return;
- }
if (!draft.baseURL.trim()) {
view.querySelector<HTMLInputElement>("[data-provider-field='baseURL']")?.focus();
showMessage(window.siyuan.languages.apiBaseURLTip, undefined, "error");
@@ -503,6 +501,16 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPr
const models = responseModels
.filter((name): name is string => typeof name === "string" && name.trim() !== "")
.map((name) => name.trim());
+ availableModelContextLengths = {};
+ const responseContextLengths = data.contextLengths;
+ if (responseContextLengths && typeof responseContextLengths === "object") {
+ Object.entries(responseContextLengths as Record<string, unknown>).forEach(([name, value]) => {
+ if (typeof value === "number" && Number.isSafeInteger(value) && value > 0) {
+ availableModelContextLengths[name] = value;
+ availableModelContextLengths[name.toLowerCase()] = value;
+ }
+ });
+ }
if (models.length === 0) {
showMessage(
data.msg
@@ -514,13 +522,24 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPr
return;
}
availableModels = [...new Set(models)].sort((first, second) => first.localeCompare(second));
+ draft.models.forEach((model) => {
+ const contextLength = getAvailableModelContextLength(model.name);
+ if (contextLength > 0) {
+ model.contextLength = contextLength;
+ }
+ });
if (draft.models.length === 0) {
- draft.models.push({
+ const model: Config.IModel = {
id: "",
enabled: true,
name: availableModels[0],
displayName: "",
- });
+ };
+ const contextLength = getAvailableModelContextLength(model.name);
+ if (contextLength > 0) {
+ model.contextLength = contextLength;
+ }
+ draft.models.push(model);
}
renderDraftModels(modelsContainer, draft.models, availableModels);
showMessage(
@@ -566,7 +585,7 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPr
} else {
draft[providerField] = target.value;
}
- if (providerField === "apiKey") {
+ if (providerField === "baseURL") {
updateModelActionButtons();
}
if (providerField === "displayName" || providerField === "baseURL") {
@@ -578,6 +597,14 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPr
const modelIndex = Number(target.closest<HTMLElement>("[data-model-index]")?.dataset.modelIndex);
if (modelField && draft.models[modelIndex]) {
draft.models[modelIndex][modelField] = target.value;
+ if (modelField === "name") {
+ const contextLength = getAvailableModelContextLength(target.value);
+ if (contextLength > 0) {
+ draft.models[modelIndex].contextLength = contextLength;
+ } else {
+ delete draft.models[modelIndex].contextLength;
+ }
+ }
}
});
@@ -613,10 +640,6 @@ const openProviderDetail = (root: HTMLElement, providerId?: string, preset?: IPr
return;
}
if (action === "addModel") {
- if (!draft.apiKey.trim()) {
- view.querySelector<HTMLInputElement>("[data-provider-field='apiKey']")?.focus();
- return;
- }
if (!hasFetchedModels) {
const modelCount = draft.models.length;
fetchModels(() => {
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index 79450c9cd8..af498ccd44 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -224,13 +224,14 @@ declare namespace Config {
/**
* AI model configuration. Behavior params (maxTokens/temperature/maxContexts)
- * live on IEditing; Model holds only identity fields.
+ * live on IEditing; Model holds identity and provider metadata.
*/
export interface IModel {
id: string;
enabled: boolean;
name: string;
displayName?: string;
+ contextLength?: number;
}
/**
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index aa22d142cd..3fc9d67cc1 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -431,7 +431,7 @@ type agentCheckpoint struct {
LastCommittedTurnID string `json:"lastCommittedTurnID,omitempty"`
}
-func AgentChat(ctx context.Context, client *openai.Client, model string, sessionID string, userEntryID string, contentRevision int64, userMessage string, language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction, regenerate bool, confirmTimeout time.Duration, maxRetries int, reasoningEffort string, requestTimeout, streamIdleTimeout time.Duration) <-chan AgentEvent {
+func AgentChat(ctx context.Context, client *openai.Client, model string, contextLimit int, sessionID string, userEntryID string, contentRevision int64, userMessage string, language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction, regenerate bool, confirmTimeout time.Duration, maxRetries int, reasoningEffort string, requestTimeout, streamIdleTimeout time.Duration) <-chan AgentEvent {
ch := make(chan AgentEvent, 256)
go func() {
@@ -460,7 +460,6 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
var messages []openai.ChatCompletionMessage
var checkpointMsgs []AgentMessage
var totalPrompt, totalCompletion, lastPromptTokens, lastCachedTokens int
- contextLimit := GetModelContextLimit(model)
alwaysAllow := map[string]bool{}
var doomLoop doomLoopTracker
var compactCount int
diff --git a/kernel/agent/modelmeta.go b/kernel/agent/modelmeta.go
index d17527b638..c8f295f524 100644
--- a/kernel/agent/modelmeta.go
+++ b/kernel/agent/modelmeta.go
@@ -90,3 +90,11 @@ func GetModelContextLimit(model string) int {
}
return 0
}
+
+// ResolveModelContextLimit 优先使用具体 Provider 模型配置中的上下文窗口,未配置时回退到内置表。
+func ResolveModelContextLimit(model string, configured int) int {
+ if 0 < configured {
+ return configured
+ }
+ return GetModelContextLimit(model)
+}
diff --git a/kernel/agent/modelmeta_test.go b/kernel/agent/modelmeta_test.go
new file mode 100644
index 0000000000..5a4fcf6344
--- /dev/null
+++ b/kernel/agent/modelmeta_test.go
@@ -0,0 +1,23 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+package agent
+
+import "testing"
+
+func TestResolveModelContextLimit(t *testing.T) {
+ if got := ResolveModelContextLimit("kimi-k3", 32768); got != 32768 {
+ t.Fatalf("configured context limit = %d, want 32768", got)
+ }
+ if got := ResolveModelContextLimit("moonshotai/kimi-k3", 0); got != 1048576 {
+ t.Fatalf("built-in context limit = %d, want 1048576", got)
+ }
+ if got := ResolveModelContextLimit("unknown-model", 0); got != 0 {
+ t.Fatalf("unknown context limit = %d, want 0", got)
+ }
+}
diff --git a/kernel/agent/stream_timeout_test.go b/kernel/agent/stream_timeout_test.go
index 016f1a14ea..2666ad9f50 100644
--- a/kernel/agent/stream_timeout_test.go
+++ b/kernel/agent/stream_timeout_test.go
@@ -210,7 +210,7 @@ func TestAgentChatPartialStreamTimeoutSavesInterruptedWithoutRetry(t *testing.T)
}))
defer server.Close()
- events := AgentChat(context.Background(), newTestOpenAIClient(server.URL), "test-model", testSessionID, "user-1", 1, "hello", "English", nil, EditorContext{}, nil, false, time.Second, 3, "", time.Second, 50*time.Millisecond)
+ events := AgentChat(context.Background(), newTestOpenAIClient(server.URL), "test-model", 0, testSessionID, "user-1", 1, "hello", "English", nil, EditorContext{}, nil, false, time.Second, 3, "", time.Second, 50*time.Millisecond)
contentSeen := false
errorSeen := false
for event := range events {
diff --git a/kernel/api/agent.go b/kernel/api/agent.go
index 140775bf6b..ae0b8373a8 100644
--- a/kernel/api/agent.go
+++ b/kernel/api/agent.go
@@ -134,7 +134,8 @@ func agentChat(c *gin.Context) {
if req.ContentRevision != nil {
contentRevision = *req.ContentRevision
}
- eventCh := agent.AgentChat(ctx, client, selectedModel.Name, req.SessionID, req.UserEntryID, contentRevision, req.Message, req.Language, req.References, req.EditorContext, req.PluginActions, req.Regenerate, confirmTimeout, maxRetries, req.ReasoningEffort, requestTimeout, streamIdleTimeout)
+ contextLimit := agent.ResolveModelContextLimit(selectedModel.Name, selectedModel.ContextLength)
+ eventCh := agent.AgentChat(ctx, client, selectedModel.Name, contextLimit, req.SessionID, req.UserEntryID, contentRevision, req.Message, req.Language, req.References, req.EditorContext, req.PluginActions, req.Regenerate, confirmTimeout, maxRetries, req.ReasoningEffort, requestTimeout, streamIdleTimeout)
defer cancel()
streamClosed := false
defer func() {
diff --git a/kernel/api/ai.go b/kernel/api/ai.go
index 285a31b49d..67617a1905 100644
--- a/kernel/api/ai.go
+++ b/kernel/api/ai.go
@@ -220,9 +220,20 @@ func listModels(c *gin.Context) {
return
}
- models, err := util.ListAvailableModels(provider.APIKey, provider.BaseURL, provider.RequestTimeout)
+ metadata, err := util.ListAvailableModelsWithContext(provider.APIKey, provider.BaseURL, provider.RequestTimeout)
+ models := make([]string, 0, len(metadata))
+ contextLengths := map[string]int{}
+ for _, item := range metadata {
+ models = append(models, item.ID)
+ if 0 < item.ContextLength {
+ if current := contextLengths[item.ID]; current < item.ContextLength {
+ contextLengths[item.ID] = item.ContextLength
+ }
+ }
+ }
result := map[string]any{
- "models": models,
+ "models": models,
+ "contextLengths": contextLengths,
}
if nil != err {
result["msg"] = err.Error()
diff --git a/kernel/conf/ai.go b/kernel/conf/ai.go
index d7bbc24090..6824249d13 100644
--- a/kernel/conf/ai.go
+++ b/kernel/conf/ai.go
@@ -116,10 +116,11 @@ 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"`
+ ID string `json:"id"`
+ DisplayName string `json:"displayName,omitempty"`
+ Enabled bool `json:"enabled"`
+ Name string `json:"name"`
+ ContextLength int `json:"contextLength,omitempty"`
}
type MCP struct {
@@ -544,6 +545,9 @@ func (ai *AI) Normalize() {
m.Name = "model"
}
m.DisplayName = strings.TrimSpace(m.DisplayName)
+ if m.ContextLength < 0 || 100000000 < m.ContextLength {
+ m.ContextLength = 0
+ }
if !ast.IsNodeIDPattern(m.ID) {
m.ID = ast.NewNodeID()
}
diff --git a/kernel/conf/ai_provider_test.go b/kernel/conf/ai_provider_test.go
index f890361e7d..27f8971284 100644
--- a/kernel/conf/ai_provider_test.go
+++ b/kernel/conf/ai_provider_test.go
@@ -72,6 +72,27 @@ func TestAIDisabledKeylessProviderOrModelIsUnavailable(t *testing.T) {
}
}
+func TestAINormalizeModelContextLength(t *testing.T) {
+ ai := &AI{Providers: []*Provider{{
+ Models: []*Model{
+ {Name: "negative", ContextLength: -1},
+ {Name: "valid", ContextLength: 1048576},
+ {Name: "too-large", ContextLength: 100000001},
+ },
+ }}}
+
+ ai.Normalize()
+ if got := ai.Providers[0].Models[0].ContextLength; got != 0 {
+ t.Fatalf("negative context length = %d, want 0", got)
+ }
+ if got := ai.Providers[0].Models[1].ContextLength; got != 1048576 {
+ t.Fatalf("valid context length = %d, want 1048576", got)
+ }
+ if got := ai.Providers[0].Models[2].ContextLength; got != 0 {
+ t.Fatalf("too-large context length = %d, want 0", got)
+ }
+}
+
func TestAssignDefaultModelIDsUsesKeylessProvider(t *testing.T) {
model := &Model{ID: "model-id", Name: "local-model", Enabled: true}
ai := &AI{
diff --git a/kernel/util/openai.go b/kernel/util/openai.go
index de4436422a..e7be4beb31 100644
--- a/kernel/util/openai.go
+++ b/kernel/util/openai.go
@@ -33,6 +33,7 @@ import (
"net/http"
"net/netip"
"net/url"
+ "strconv"
"strings"
"sync"
"syscall"
@@ -50,6 +51,7 @@ const (
maxGeneratedImageBytes = 50 * 1024 * 1024
maxGeneratedImagePixels = 100 * 1000 * 1000
imageAnalysisMaxTokens = 4096
+ maxModelContextLength = 100 * 1000 * 1000
)
type PreparedImage struct {
@@ -298,27 +300,106 @@ func TestEmbeddingModel(apiKey, apiBaseURL, model string, dimensions, timeout in
return
}
+type availableModelPayload struct {
+ ID string `json:"id"`
+ ContextLength json.RawMessage `json:"context_length"`
+ MaxContextLength json.RawMessage `json:"max_context_length"`
+ MaxInputTokens json.RawMessage `json:"max_input_tokens"`
+}
+
+type availableModelsPayload struct {
+ Data []availableModelPayload `json:"data"`
+}
+
+// AvailableModel 描述 Provider 返回的模型及其可选上下文窗口。
+type AvailableModel struct {
+ ID string
+ ContextLength int
+}
+
// ListAvailableModels 拉取 Provider 的可用模型清单(GET /v1/models),仅返回模型 ID 列表。
-// 用于填充前端模型名称下拉框。不支持该端点的服务会返回错误,由调用方回退为手动输入。
+// 用于兼容不需要模型元数据的调用方。
func ListAvailableModels(apiKey, apiBaseURL string, timeout int) (models []string, err error) {
+ metadata, err := ListAvailableModelsWithContext(apiKey, apiBaseURL, timeout)
+ if err != nil {
+ return nil, err
+ }
+ for _, model := range metadata {
+ models = append(models, model.ID)
+ }
+ return
+}
+
+// ListAvailableModelsWithContext 拉取 Provider 的模型清单及可选上下文窗口。
+// 通用 OpenAI 兼容接口不保证返回上下文长度,缺失或非法时保留模型并将 ContextLength 置为 0。
+func ListAvailableModelsWithContext(apiKey, apiBaseURL string, timeout int) (models []AvailableModel, err error) {
if 1 > timeout {
timeout = 30
}
- client := NewOpenAIClient(apiKey, apiBaseURL)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
defer cancel()
- list, err := client.ListModels(ctx)
- if nil != err {
+ endpoint := strings.TrimRight(apiBaseURL, "/") + "/models"
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
+ if err != nil {
+ return nil, err
+ }
+ if apiKey != "" {
+ req.Header.Set("Authorization", "Bearer "+apiKey)
+ }
+ resp, err := httpclient.NewUserAgentClient(nil).Do(req)
+ if err != nil {
+ logging.LogErrorf("list models [%s] failed: %s", apiBaseURL, err)
+ return
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode < http.StatusOK || http.StatusBadRequest <= resp.StatusCode {
+ body, readErr := io.ReadAll(io.LimitReader(resp.Body, 64*1024))
+ if readErr != nil {
+ err = fmt.Errorf("list models HTTP %d", resp.StatusCode)
+ } else {
+ err = fmt.Errorf("list models HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
+ }
logging.LogErrorf("list models [%s] failed: %s", apiBaseURL, err)
return
}
- for _, m := range list.Models {
- models = append(models, m.ID)
+
+ payload := &availableModelsPayload{}
+ if err = json.NewDecoder(resp.Body).Decode(payload); err != nil {
+ logging.LogErrorf("decode models [%s] failed: %s", apiBaseURL, err)
+ return
+ }
+ for _, item := range payload.Data {
+ id := strings.TrimSpace(item.ID)
+ if id == "" {
+ continue
+ }
+ models = append(models, AvailableModel{
+ ID: id,
+ ContextLength: firstValidModelContextLength(
+ item.ContextLength,
+ item.MaxContextLength,
+ item.MaxInputTokens,
+ ),
+ })
}
return
}
+func firstValidModelContextLength(values ...json.RawMessage) int {
+ for _, value := range values {
+ if len(value) == 0 || value[0] == '"' {
+ continue
+ }
+ parsed, err := strconv.ParseInt(strings.TrimSpace(string(value)), 10, 64)
+ if err != nil || parsed < 1 || maxModelContextLength < parsed {
+ continue
+ }
+ return int(parsed)
+ }
+ return 0
+}
+
func IsNetworkError(err error) bool {
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "actively refused") ||
diff --git a/kernel/util/openai_models_test.go b/kernel/util/openai_models_test.go
new file mode 100644
index 0000000000..f27d2d6f25
--- /dev/null
+++ b/kernel/util/openai_models_test.go
@@ -0,0 +1,79 @@
+// SiYuan - Refactor your thinking
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+package util
+
+import (
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func TestListAvailableModelsWithContext(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/v1/models" {
+ t.Fatalf("path = %q", r.URL.Path)
+ }
+ if authorization := r.Header.Get("Authorization"); authorization != "Bearer test-key" {
+ t.Fatalf("authorization = %q", authorization)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = fmt.Fprint(w, `{"data":[
+ {"id":"context","context_length":1048576},
+ {"id":"max-context","max_context_length":262144},
+ {"id":"max-input","max_input_tokens":131072},
+ {"id":"fallback","context_length":"invalid","max_input_tokens":65536},
+ {"id":"invalid-float","context_length":8192.5},
+ {"id":"invalid-negative","context_length":-1},
+ {"id":"invalid-large","context_length":100000001},
+ {"id":"unknown"},
+ {"id":"","context_length":4096}
+ ]}`)
+ }))
+ defer server.Close()
+
+ models, err := ListAvailableModelsWithContext("test-key", server.URL+"/v1", 5)
+ if err != nil {
+ t.Fatal(err)
+ }
+ expected := []AvailableModel{
+ {ID: "context", ContextLength: 1048576},
+ {ID: "max-context", ContextLength: 262144},
+ {ID: "max-input", ContextLength: 131072},
+ {ID: "fallback", ContextLength: 65536},
+ {ID: "invalid-float"},
+ {ID: "invalid-negative"},
+ {ID: "invalid-large"},
+ {ID: "unknown"},
+ }
+ if len(models) != len(expected) {
+ t.Fatalf("model count = %d, want %d: %#v", len(models), len(expected), models)
+ }
+ for i, want := range expected {
+ if got := models[i]; got != want {
+ t.Fatalf("model %d = %#v, want %#v", i, got, want)
+ }
+ }
+}
+
+func TestListAvailableModelsCompatibility(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = fmt.Fprint(w, `{"data":[{"id":"first","context_length":8192},{"id":"second"}]}`)
+ }))
+ defer server.Close()
+
+ models, err := ListAvailableModels("", server.URL, 5)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(models) != 2 || models[0] != "first" || models[1] != "second" {
+ t.Fatalf("models = %#v", models)
+ }
+}