Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(vlm): make max_tokens configurable via VLM_MAX_TOKENS (#4478)

zhouh71c073ac0151
diff --git a/.env.example b/.env.example
index 6a5af46b4..9d88d1ecb 100644
--- a/.env.example
+++ b/.env.example
@@ -367,6 +367,10 @@ OLLAMA_BASE_URL=http://host.docker.internal:11434
# GENERATE_QUESTIONS_MAX_TOKENS=
# VLM 单次 HTTP 请求超时(秒,默认 180;慢端点超时报 context deadline 时调大)。
# VLM_HTTP_TIMEOUT_SECONDS=180
+# VLM 单次请求的补全 token 预算(默认 5000)。预算含模型隐藏的思考 token,推理型
+# 视觉模型整页扫描件易触发 finish_reason=length 截断(报 VLM completion truncated),
+# 遇到时调大此值。
+# VLM_MAX_TOKENS=5000
# LLM 流原始转储(排查上下文问题;1 启用,默认目录 ~/.weknora/investigate/llm-stream)。
# WEKNORA_LLM_STREAM_RAW_DUMP=
# WEKNORA_LLM_STREAM_RAW_DUMP_DIR=
diff --git a/docker-compose.yml b/docker-compose.yml
index daf976dcd..fd60ce9f6 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -275,6 +275,8 @@ services:
- BATCH_EMBED_SIZE=${BATCH_EMBED_SIZE:-}
# VLM 单次 HTTP 请求超时(秒,默认 180)
- VLM_HTTP_TIMEOUT_SECONDS=${VLM_HTTP_TIMEOUT_SECONDS:-}
+ # VLM 单次请求的补全 token 预算(默认 5000)
+ - VLM_MAX_TOKENS=${VLM_MAX_TOKENS:-}
# LLM 流原始转储(排查上下文问题;1 启用,默认目录 ~/.weknora/investigate/llm-stream)
- WEKNORA_LLM_STREAM_RAW_DUMP=${WEKNORA_LLM_STREAM_RAW_DUMP:-}
- WEKNORA_LLM_STREAM_RAW_DUMP_DIR=${WEKNORA_LLM_STREAM_RAW_DUMP_DIR:-}
diff --git a/internal/models/vlm/remote_api.go b/internal/models/vlm/remote_api.go
index 0c2a75039..95622758b 100644
--- a/internal/models/vlm/remote_api.go
+++ b/internal/models/vlm/remote_api.go
@@ -21,6 +21,10 @@ const (
// over a minute on slow endpoints, so this is intentionally generous and
// can be raised further via VLM_HTTP_TIMEOUT_SECONDS.
defaultTimeout = 180 * time.Second
+ // defaultMaxToks is the fallback completion budget for a single VLM
+ // request. Reasoning vision models spend part of it on hidden thinking
+ // tokens, so a dense scanned page can stop at finish_reason=length; raise
+ // it via VLM_MAX_TOKENS.
defaultMaxToks = 5000
defaultTemp = float32(0.1)
)
@@ -37,6 +41,20 @@ func vlmHTTPTimeout() time.Duration {
return defaultTimeout
}
+// vlmMaxTokens returns the completion budget for a single VLM request, read
+// from the VLM_MAX_TOKENS env var when set (and positive), falling back to
+// defaultMaxToks otherwise. The budget covers thinking tokens as well, so a
+// reasoning vision model can exhaust the default on a dense page and fail OCR
+// with finish_reason=length; this makes the cap adjustable without a rebuild.
+func vlmMaxTokens() int {
+ if v := strings.TrimSpace(os.Getenv("VLM_MAX_TOKENS")); v != "" {
+ if tokens, err := strconv.Atoi(v); err == nil && tokens > 0 {
+ return tokens
+ }
+ }
+ return defaultMaxToks
+}
+
// RemoteAPIVLM implements VLM on top of the catalog-driven chat client: a
// vision call is a chat call whose user turn carries images, so the vendor
// dialect (max_tokens field, sampling restrictions, protocol) is resolved
@@ -120,9 +138,10 @@ func (v *RemoteAPIVLM) PredictWithOptions(
logger.Infof(ctx, "[VLM] Calling chat protocol, model=%s, numImages=%d, totalImageSize=%d",
v.modelName, len(imgBytesList), totalImageSize)
+ maxTokens := vlmMaxTokens()
chatOpts := &chat.ChatOptions{
Temperature: v.temperature,
- MaxTokens: defaultMaxToks,
+ MaxTokens: maxTokens,
}
// Only an explicit preference is forwarded. The protocol layer skips the
// thinking fields entirely when nobody asked for a level, which is what
@@ -141,7 +160,7 @@ func (v *RemoteAPIVLM) PredictWithOptions(
if resp.FinishReason == "length" {
// Non-empty partial output is still incomplete and must not be indexed
// as successful OCR. Returning an error also marks the model trace failed.
- return "", fmt.Errorf("%w at %d tokens (finish_reason=length)", ErrTruncatedCompletion, defaultMaxToks)
+ return "", fmt.Errorf("%w at %d tokens (finish_reason=length)", ErrTruncatedCompletion, maxTokens)
}
logger.Infof(ctx, "[VLM] response received, len=%d", len(content))
return content, nil
diff --git a/internal/models/vlm/remote_api_max_tokens_test.go b/internal/models/vlm/remote_api_max_tokens_test.go
new file mode 100644
index 000000000..75472f3fc
--- /dev/null
+++ b/internal/models/vlm/remote_api_max_tokens_test.go
@@ -0,0 +1,104 @@
+package vlm
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+// TestVLMMaxTokensReadsEnv pins the parsing rules of VLM_MAX_TOKENS: a set and
+// positive value wins, everything else falls back to the built-in budget.
+func TestVLMMaxTokensReadsEnv(t *testing.T) {
+ cases := []struct {
+ name string
+ env string
+ want int
+ }{
+ {name: "unset", env: "", want: defaultMaxToks},
+ {name: "blank", env: " ", want: defaultMaxToks},
+ {name: "positive", env: "12000", want: 12000},
+ {name: "padded positive", env: " 8000 ", want: 8000},
+ {name: "zero", env: "0", want: defaultMaxToks},
+ {name: "negative", env: "-1", want: defaultMaxToks},
+ {name: "not a number", env: "lots", want: defaultMaxToks},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Setenv("VLM_MAX_TOKENS", tc.env)
+ if got := vlmMaxTokens(); got != tc.want {
+ t.Errorf("vlmMaxTokens() = %d, want %d", got, tc.want)
+ }
+ })
+ }
+}
+
+// TestRemoteAPIVLMSendsConfiguredMaxTokens is the regression test for the
+// hard-coded 5000-token budget: a raised VLM_MAX_TOKENS must reach the request
+// body instead of being ignored.
+func TestRemoteAPIVLMSendsConfiguredMaxTokens(t *testing.T) {
+ withVLMSSRFWhitelist(t, "127.0.0.1")
+ t.Setenv("VLM_MAX_TOKENS", "12000")
+
+ var lastRequest map[string]interface{}
+ server := newVLMChatTestServer(t, &lastRequest)
+ defer server.Close()
+
+ v, err := NewRemoteAPIVLM(&Config{
+ BaseURL: server.URL,
+ ModelName: "qwen2.5-vl-7b-instruct",
+ APIKey: "sk-test",
+ })
+ if err != nil {
+ t.Fatalf("NewRemoteAPIVLM: %v", err)
+ }
+ if _, err := v.Predict(t.Context(), [][]byte{testPNG}, "extract the text"); err != nil {
+ t.Fatalf("Predict: %v", err)
+ }
+
+ got, ok := lastRequest["max_tokens"]
+ if !ok {
+ t.Fatal("request is missing max_tokens")
+ }
+ if got != float64(12000) {
+ t.Errorf("max_tokens = %v, want 12000", got)
+ }
+}
+
+// TestRemoteAPIVLMTruncationReportsConfiguredMaxTokens checks that the
+// truncation error quotes the budget that was actually requested, so an
+// operator reading the log knows which cap to raise.
+func TestRemoteAPIVLMTruncationReportsConfiguredMaxTokens(t *testing.T) {
+ withVLMSSRFWhitelist(t, "127.0.0.1")
+ t.Setenv("VLM_MAX_TOKENS", "7000")
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "choices": []any{map[string]any{
+ "index": 0, "message": map[string]any{"role": "assistant", "content": ""},
+ "finish_reason": "length",
+ }},
+ })
+ }))
+ defer server.Close()
+
+ v, err := NewRemoteAPIVLM(&Config{BaseURL: server.URL, ModelName: "generic-vision", Provider: "generic"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := v.Predict(t.Context(), [][]byte{testPNG}, "extract text")
+ if got != "" {
+ t.Fatalf("content = %q, want empty", got)
+ }
+ if !errors.Is(err, ErrTruncatedCompletion) {
+ t.Fatalf("error = %v, want ErrTruncatedCompletion", err)
+ }
+ if want := fmt.Sprintf("at %s tokens", strconv.Itoa(7000)); !strings.Contains(err.Error(), want) {
+ t.Errorf("error = %q, want it to mention the configured budget (%s)", err, want)
+ }
+}
diff --git a/website-docs/01-getting-started/04-configuration.md b/website-docs/01-getting-started/04-configuration.md
index 0a76356b0..749c13e09 100644
--- a/website-docs/01-getting-started/04-configuration.md
+++ b/website-docs/01-getting-started/04-configuration.md
@@ -213,6 +213,7 @@ AWS S3 的 `S3_ACCESS_KEY` / `S3_SECRET_KEY` 可以**同时留空**,此时走
| `OLLAMA_OPTIONAL` | true | Ollama 不可用时仅告警不阻断启动 |
| `BATCH_EMBED_SIZE` | 空 | 批量 embedding 大小 |
| `VLM_HTTP_TIMEOUT_SECONDS` | 180 | VLM 单次请求超时 |
+| `VLM_MAX_TOKENS` | 5000 | 远程 VLM 单次请求的补全 token 预算(含模型隐藏的思考 token,整页扫描件被截断时报 `finish_reason=length` 可调大) |
| `BUILTIN_MODELS_CONFIG` | config/builtin_models.yaml | 内置模型声明文件路径(见下文) |
| `MODELS_CONFIG` | config/models.json | 模型厂商目录的部署叠加文件路径(补充厂商、覆盖地址或模型参数),格式见[模型管理](../03-features/06-models.md) |
| `WEKNORA_LLM_STREAM_RAW_DUMP` / `_DIR` | 空 | LLM 流原始转储(排障用) |