diff --git a/docs/en-US/configuration.md b/docs/en-US/configuration.md index b18d9a76..34017e06 100644 --- a/docs/en-US/configuration.md +++ b/docs/en-US/configuration.md @@ -70,8 +70,8 @@ ai: | `name` | Display name in the Web UI; falls back to the ID. | | `provider` | `openai_compatible` or `claude`. OpenAI-compatible channels map to runtime `openai`; Claude channels use Eino's native Anthropic Messages API component. | | `base_url/api_key/model` | Required. Base URL usually includes a version path such as `/v1`. | -| `max_total_tokens` | Shared context budget for compression, attack-chain generation, multi-agent summaries, and similar paths. | -| `max_completion_tokens` | Per-response output cap; default is used when empty. | +| `max_total_tokens` | Shared context budget for compression, attack-chain generation, multi-agent summaries, and similar paths. When `context_window` is known, it is clamped to the window minus the output reserve. | +| `max_completion_tokens` | Per-response output cap; default is used when empty, and it is clamped to half of the known/assumed window. | | `context_window` | Native model context window in tokens. When set, the runtime clamps `max_total_tokens` to it; 0/omitted means unknown. | | `context_profile` | `auto` (default) or `local`. `local` targets 32K–256K local models: the budget is 60% of the window (capped at 128K), while summary reserve, tool-output truncation/clearing, user-message and ledger caps are tightened, and `tool_search` with a small always-visible tool set is enabled. It only tightens numeric middleware settings and enables tool_search/reduction where needed. | | `reasoning` | Default reasoning fields for the channel. Gateway support varies; try `mode: off` first when a provider rejects requests. | @@ -81,16 +81,17 @@ ai: A local model's effective context is usually much smaller than its advertised window, and the “model maximum” can differ from the runtime window. Recommended setup: 1. **Confirm the runtime window**: click **Auto-detect** next to the context window field in **System Settings → Basic Settings → AI Channel Configuration**. The probe checks Ollama `/api/ps`/`/api/show`, llama.cpp `/props`, LM Studio `/api/v0/models`, then vLLM/OpenAI-compatible `/v1/models`; reverse-proxy subpaths such as `https://host/ollama/v1` are supported. The result also shows the effective budget for the current profile. Enter the server's actual value if detection fails. -2. **Enable the local profile**: set `context_profile: local`. The budget becomes 60% of the window and compaction triggers earlier; tool-output truncation is roughly window/6 (8–32 KB), historical tool-result clearing is roughly 35% of the budget, and always-visible tools shrink to a core set; backend builtins also join the `tool_search` dynamic pool, and the rest are unlocked on demand. Token estimates are inflated by 10% to absorb tokenizer differences between local models and tiktoken. The profile also switches the output cap to the more widely accepted `max_tokens` field, because many local servers do not recognize `max_completion_tokens`; the same applies to attack-chain, FOFA query, workflow draft, and HITL audit calls. +2. **Enable the local profile**: set `context_profile: local`. The budget becomes 60% of the window, also bounded by “window − output reserve” (for example, a 32K window with the default 16K output cap yields a 16K budget), and the per-request output cap is clamped to half the window; compaction triggers earlier. Tool-output truncation is roughly window/6 (8–32 KB), historical tool-result clearing is roughly 35% of the budget, and always-visible tools shrink to a core set; backend builtins also join the `tool_search` dynamic pool, and the rest are unlocked on demand. Token estimates are inflated by 10% to absorb tokenizer differences between local models and tiktoken. The profile also switches the output cap to the more widely accepted `max_tokens` field, because many local servers do not recognize `max_completion_tokens`; the same applies to attack-chain, FOFA query, workflow draft, and HITL audit calls. 3. **Do not plan around a nominal 1M window**: Qwen3.5-class models ship with 262,144 native context and can be extended to 1M with YaRN, but local VRAM limits and context rot degrade quality. For tool-using agents, keep the effective budget around 64K–128K. 4. **Ollama requires `num_ctx`**: Ollama's `/v1` compatibility endpoint ignores `num_ctx` in requests and picks a default window from VRAM (roughly 4K/32K/256K). Oversized prompts are truncated from the beginning, dropping the system prompt and tool definitions first. Use `OLLAMA_CONTEXT_LENGTH=65536 ollama serve` or a Modelfile `PARAMETER num_ctx 65536`, then confirm `CONTEXT` in `ollama ps` after restart. 5. **KV cache and prefix caching**: - - llama.cpp: `--ctx-size 65536 --cache-type-k q8_0 --cache-type-v q8_0 -fa`; `--cache-prompt` is on by default. `--parallel` splits the context across slots. + - llama.cpp: `--ctx-size 65536 --cache-type-k q8_0 --cache-type-v q8_0 -fa`; `--cache-prompt` is on by default. `--parallel` splits the context across slots; detection returns `context_slots` and warns when it is greater than 1, so confirm the per-request window for your KV mode (for example `--kv-unified`). - vLLM: `--max-model-len 65536 --enable-prefix-caching --kv-cache-dtype fp8`; use `--max-num-seqs` to bound concurrent KV usage. - Ollama: `OLLAMA_KV_CACHE_TYPE=q8_0`, `OLLAMA_NUM_PARALLEL=1`; larger windows consume more KV cache. - LM Studio: set Context Length explicitly in the model settings and enable KV-cache quantization when available. 6. **Thinking models**: Qwen3.5-class models enable thinking by default, which burns context inside tool loops. Disable it per channel with `reasoning.extra_request_fields.chat_template_kwargs.enable_thinking: false` (supported by vLLM and llama.cpp with `--jinja`). `reasoning.mode: off` only clears OpenAI/DeepSeek reasoning fields and may not disable the local chat template's thinking. 7. **Minimum viable window**: an agent with 90+ tools is unreliable below 16K. 32K depends on `tool_search` and `context_profile: local`; 64K and above is closer to a cloud-model experience. +8. **Failover channels are not re-budgeted**: `multi_agent.eino_middleware.model_failover_channels` only switches the model endpoint; the budget still follows the primary channel. Keep each failover channel's available window at least as large as the primary, or expect overflow compaction/retry. The chat page reads saved channels into the “AI Channel” selector. A non-empty request `aiChannelId` selects a channel for that run/session without sending API credentials through the prompt path. Empty `aiChannelId` follows `ai.default_channel`. diff --git a/docs/zh-CN/configuration.md b/docs/zh-CN/configuration.md index 5137f6f0..8c241f8b 100644 --- a/docs/zh-CN/configuration.md +++ b/docs/zh-CN/configuration.md @@ -71,8 +71,8 @@ ai: | `name` | Web UI 展示名。留空时使用通道 ID。 | | `provider` | `openai_compatible` 或 `claude`。`openai_compatible` 会在运行时映射为 `openai`;`claude` 使用 Eino 原生 Anthropic Messages API。 | | `base_url/api_key/model` | 必填。Base URL 通常需要包含版本路径,如 OpenAI/兼容网关的 `/v1`。 | -| `max_total_tokens` | 上下文压缩、攻击链构建、多代理摘要等共用的总预算。 | -| `max_completion_tokens` | 单次模型输出上限;未填时使用默认值。 | +| `max_total_tokens` | 上下文压缩、攻击链构建、多代理摘要等共用的总预算。已知 `context_window` 时会收紧到“窗口 − 输出预留”。 | +| `max_completion_tokens` | 单次模型输出上限;未填时使用默认值,并会被压到已知/假定窗口的一半以内。 | | `context_window` | 模型原生上下文窗口(token)。填写后运行时会按窗口收紧 `max_total_tokens`;0/省略表示未知。 | | `context_profile` | `auto`(默认)或 `local`。`local` 面向 32K–256K 本地模型:预算折到窗口的 60%(上限 128K),收紧摘要预留、工具输出截断/清理、用户消息与账本上限,并启用 `tool_search` 与精简常驻工具。数值参数只收紧、不放大,同时按需启用 tool_search/reduction。 | | `reasoning` | 该通道的默认推理扩展字段。不同网关支持差异较大,异常时先尝试 `mode: off`。 | @@ -82,16 +82,17 @@ ai: 本地模型的有效上下文通常明显小于标称窗口,且不同后端的“模型上限”和“运行时窗口”可能不一致。建议: 1. **先确认运行时窗口**:在 **系统设置 → 基本设置 → AI 通道配置 → 模型上下文窗口** 右侧点击「自动检测」。探测顺序为 Ollama `/api/ps`、`/api/show`,llama.cpp `/props`,LM Studio `/api/v0/models`,vLLM/OpenAI 兼容 `/v1/models`;同时支持反向代理子路径(如 `https://host/ollama/v1`)。检测结果会显示按当前档位折算后的有效预算。检测不到时请手动填写服务端实际配置。 -2. **启用本地档位**:把 `context_profile` 设为 `local`。预算按窗口 60% 计算,摘要更早触发;工具输出截断阈值约为窗口/6(8–32 KB),历史工具结果清理阈值约为预算的 35%;常驻工具收敛到核心集合,内置工具也进入 `tool_search` 动态池,其余工具按需解锁。token 估算会额外放大 10%,抵消本地 tokenizer 与 tiktoken 在中英文上的差异。该档位还会把输出上限字段切换为更通用的 `max_tokens`(Ollama/llama.cpp 等常不识别 `max_completion_tokens`),攻击链、FOFA 语法生成、工作流草稿、HITL 审计等旁路调用同样生效。 +2. **启用本地档位**:把 `context_profile` 设为 `local`。预算按窗口 60% 计算,同时不超过“窗口 − 输出预留”(例如 32K 窗口、默认输出上限 16K 时预算为 16K);单次输出上限也会被压到窗口的一半以内。摘要更早触发;工具输出截断阈值约为窗口/6(8–32 KB),历史工具结果清理阈值约为预算的 35%;常驻工具收敛到核心集合,内置工具也进入 `tool_search` 动态池,其余工具按需解锁。token 估算会额外放大 10%,抵消本地 tokenizer 与 tiktoken 在中英文上的差异。该档位还会把输出上限字段切换为更通用的 `max_tokens`(Ollama/llama.cpp 等常不识别 `max_completion_tokens`),攻击链、FOFA 语法生成、工作流草稿、HITL 审计等旁路调用同样生效。 3. **不要按标称 1M 规划**:Qwen3.5 等模型原生 262,144,可用 YaRN 扩到 1M,但本地显存与长上下文性能衰减(context rot)会让实际效果明显下降;带工具的 agent 建议把有效预算控制在 64K–128K。 4. **Ollama 必须设置 `num_ctx`**:Ollama 的 `/v1` 兼容端点会忽略请求里的 `num_ctx`,并按显存选择默认窗口(约 4K/32K/256K);超长时从开头截断,系统提示词和工具定义会先丢失。请用 `OLLAMA_CONTEXT_LENGTH=65536 ollama serve` 或 Modelfile `PARAMETER num_ctx 65536`,重启后用 `ollama ps` 确认 `CONTEXT`。 5. **KV cache 与前缀缓存**: - - llama.cpp:`--ctx-size 65536 --cache-type-k q8_0 --cache-type-v q8_0 -fa`;`--cache-prompt` 默认开启。`--parallel` 会让每个槽位分摊上下文。 + - llama.cpp:`--ctx-size 65536 --cache-type-k q8_0 --cache-type-v q8_0 -fa`;`--cache-prompt` 默认开启。`--parallel` 会让每个槽位分摊上下文;检测结果会返回 `context_slots` 并在大于 1 时提示,请按实际 KV 模式(如 `--kv-unified`)确认单请求可用窗口。 - vLLM:`--max-model-len 65536 --enable-prefix-caching --kv-cache-dtype fp8`;用 `--max-num-seqs` 控制并发 KV 占用。 - Ollama:`OLLAMA_KV_CACHE_TYPE=q8_0`、`OLLAMA_NUM_PARALLEL=1`;窗口越大 KV cache 越大。 - LM Studio:在模型设置中显式设置 Context Length,并开启可用的 KV cache 量化。 6. **思考模型**:Qwen3.5 等默认开启 thinking,会在工具循环中消耗大量上下文。可通过通道的 `reasoning.extra_request_fields.chat_template_kwargs.enable_thinking: false` 关闭(vLLM、llama.cpp `--jinja` 支持);`reasoning.mode: off` 只清理 OpenAI/DeepSeek 推理字段,不一定能关闭本地 chat template 的 thinking。 7. **建议窗口下限**:带 90+ 工具的 agent 在 16K 以下很难稳定运行;32K 需要依赖 `tool_search` 和 `context_profile: local`;64K 以上更接近云端模型的使用体验。 +8. **故障转移通道不会重新预算**:`multi_agent.eino_middleware.model_failover_channels` 只切换模型端点,预算仍按主通道计算;请让 failover 通道的可用窗口不小于主通道,否则可能依赖超窗压缩/重试。 对话页的“AI 通道”下拉框会读取已保存通道。请求体中的 `aiChannelId` 非空时仅对本次/本会话运行配置生效,不会把 API Key 发送给模型;为空时跟随 `ai.default_channel`。 diff --git a/internal/config/config.go b/internal/config/config.go index 5e2ffc02..435aedec 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -999,8 +999,8 @@ func (c OpenAIConfig) MaxCompletionTokensEffective() int { if out <= 0 { out = DefaultMaxCompletionTokens } - if c.ContextWindow > 0 && out > c.ContextWindow/2 { - out = c.ContextWindow / 2 + if window := c.EffectiveContextWindow(); window > 0 && out > window/2 { + out = window / 2 } return out } diff --git a/internal/config/context_profile.go b/internal/config/context_profile.go index 5e5a400e..12aaf478 100644 --- a/internal/config/context_profile.go +++ b/internal/config/context_profile.go @@ -17,9 +17,10 @@ const ( // 本地 tokenizer 与 tiktoken 不一致(CJK 尤甚),留出余量避免踩到运行时窗口。 LocalTokenEstimateSafetyPercent = 110 - ContextWarningLocalWindowUnknown = "local_context_window_unknown" - ContextWarningLocalWindowSmall = "local_context_window_small" - ContextWarningMaxTotalClamped = "max_total_tokens_clamped" + ContextWarningLocalWindowUnknown = "local_context_window_unknown" + ContextWarningLocalWindowSmall = "local_context_window_small" + ContextWarningMaxTotalClamped = "max_total_tokens_clamped" + ContextWarningMaxCompletionClamped = "max_completion_tokens_clamped" ) // NormalizeContextProfile 只接受 auto(空)与 local;未知值按 auto 处理,避免配置拼写错误放大预算。 @@ -107,6 +108,9 @@ func (c OpenAIConfig) EffectiveMaxTotalTokens() int { if budget < 1024 { budget = 1024 } + if window > 0 && budget > window { + budget = window + } return budget } @@ -127,6 +131,9 @@ func (c OpenAIConfig) ContextBudgetWarnings() []string { if c.EffectiveContextWindow() > 0 && configured > c.EffectiveMaxTotalTokens() { out = append(out, ContextWarningMaxTotalClamped) } + if c.EffectiveContextWindow() > 0 && c.MaxCompletionTokens > c.MaxCompletionTokensEffective() { + out = append(out, ContextWarningMaxCompletionClamped) + } return out } diff --git a/internal/config/context_profile_test.go b/internal/config/context_profile_test.go index 23c28860..ace780c1 100644 --- a/internal/config/context_profile_test.go +++ b/internal/config/context_profile_test.go @@ -5,6 +5,16 @@ import ( "testing" ) +func TestEffectiveMaxTotalTokensNeverExceedsWindow(t *testing.T) { + t.Parallel() + for _, window := range []int{512, 1024, 2048, 4096, 8192} { + oa := OpenAIConfig{ContextWindow: window, ContextProfile: "local", MaxTotalTokens: 120000} + if got := oa.EffectiveMaxTotalTokens(); got > window { + t.Fatalf("window %d: effective budget %d exceeds window", window, got) + } + } +} + func TestTokenEstimateSafetyPercent(t *testing.T) { t.Parallel() if got := (OpenAIConfig{}).TokenEstimateSafetyPercent(); got != 100 { @@ -129,6 +139,7 @@ func TestMaxCompletionTokensEffectiveClampsToWindow(t *testing.T) { {name: "no window uses configured", oa: OpenAIConfig{MaxCompletionTokens: 32768}, want: 32768}, {name: "no window uses default", oa: OpenAIConfig{}, want: DefaultMaxCompletionTokens}, {name: "32k window halves output", oa: OpenAIConfig{ContextWindow: 32768, MaxCompletionTokens: 32768}, want: 16384}, + {name: "local missing window assumes 32k", oa: OpenAIConfig{ContextProfile: "local", MaxCompletionTokens: 32768}, want: 16384}, {name: "128k window keeps output", oa: OpenAIConfig{ContextWindow: 131072, MaxCompletionTokens: 16384}, want: 16384}, } for _, tc := range cases { @@ -168,6 +179,11 @@ func TestContextBudgetWarnings(t *testing.T) { oa: OpenAIConfig{ContextWindow: 32768, MaxTotalTokens: 64000}, want: []string{ContextWarningMaxTotalClamped}, }, + { + name: "oversized output cap warns", + oa: OpenAIConfig{ContextWindow: 32768, MaxCompletionTokens: 32768}, + want: []string{ContextWarningMaxTotalClamped, ContextWarningMaxCompletionClamped}, + }, } for _, tc := range cases { tc := tc diff --git a/internal/handler/config.go b/internal/handler/config.go index de44273a..e0fcd78f 100644 --- a/internal/handler/config.go +++ b/internal/handler/config.go @@ -1277,26 +1277,28 @@ func (h *ConfigHandler) UpdateConfig(c *gin.Context) { // TestOpenAIRequest 测试OpenAI连接请求 type TestOpenAIRequest struct { - CredentialScope string `json:"credential_scope,omitempty"` - ChannelID string `json:"channel_id,omitempty"` - Provider string `json:"provider"` - BaseURL string `json:"base_url"` - APIKey string `json:"api_key"` - Model string `json:"model"` - MaxTotalTokens int `json:"max_total_tokens,omitempty"` - ContextProfile string `json:"context_profile,omitempty"` + CredentialScope string `json:"credential_scope,omitempty"` + ChannelID string `json:"channel_id,omitempty"` + Provider string `json:"provider"` + BaseURL string `json:"base_url"` + APIKey string `json:"api_key"` + Model string `json:"model"` + MaxTotalTokens int `json:"max_total_tokens,omitempty"` + MaxCompletionTokens int `json:"max_completion_tokens,omitempty"` + ContextProfile string `json:"context_profile,omitempty"` } // DetectContextRequest probes model metadata without issuing a completion. type DetectContextRequest struct { - CredentialScope string `json:"credential_scope,omitempty"` - ChannelID string `json:"channel_id,omitempty"` - Provider string `json:"provider"` - BaseURL string `json:"base_url"` - APIKey string `json:"api_key"` - Model string `json:"model"` - MaxTotalTokens int `json:"max_total_tokens,omitempty"` - ContextProfile string `json:"context_profile,omitempty"` + CredentialScope string `json:"credential_scope,omitempty"` + ChannelID string `json:"channel_id,omitempty"` + Provider string `json:"provider"` + BaseURL string `json:"base_url"` + APIKey string `json:"api_key"` + Model string `json:"model"` + MaxTotalTokens int `json:"max_total_tokens,omitempty"` + MaxCompletionTokens int `json:"max_completion_tokens,omitempty"` + ContextProfile string `json:"context_profile,omitempty"` } func probeModelContext(ctx context.Context, provider, baseURL, apiKey, model string) modelmeta.ContextInfo { @@ -1308,7 +1310,7 @@ func probeModelContext(ctx context.Context, provider, baseURL, apiKey, model str return modelmeta.DetectContext(probeCtx, baseURL, model, apiKey, nil) } -func addModelContextToResponse(resp gin.H, info modelmeta.ContextInfo, maxTotalTokens int, contextProfile string) { +func addModelContextToResponse(resp gin.H, info modelmeta.ContextInfo, maxTotalTokens, maxCompletionTokens int, contextProfile string) { if info.Backend != "" { resp["context_backend"] = info.Backend } @@ -1321,14 +1323,18 @@ func addModelContextToResponse(resp gin.H, info modelmeta.ContextInfo, maxTotalT if info.Loaded { resp["context_loaded"] = true } + if info.RuntimeSlots > 0 { + resp["context_slots"] = info.RuntimeSlots + } if info.RuntimeUnknown { resp["context_runtime_unknown"] = true } profile := config.NormalizeContextProfile(contextProfile) oa := config.OpenAIConfig{ - ContextWindow: info.ContextWindow, - ContextProfile: profile, - MaxTotalTokens: maxTotalTokens, + ContextWindow: info.ContextWindow, + ContextProfile: profile, + MaxTotalTokens: maxTotalTokens, + MaxCompletionTokens: maxCompletionTokens, } if info.ContextWindow > 0 || profile != "" { resp["effective_max_total_tokens"] = oa.EffectiveMaxTotalTokens() @@ -1391,7 +1397,7 @@ func (h *ConfigHandler) DetectContext(c *gin.Context) { } info := probeModelContext(c.Request.Context(), req.Provider, baseURL, req.APIKey, req.Model) resp := gin.H{"success": true, "model": req.Model} - addModelContextToResponse(resp, info, req.MaxTotalTokens, req.ContextProfile) + addModelContextToResponse(resp, info, req.MaxTotalTokens, req.MaxCompletionTokens, req.ContextProfile) c.JSON(http.StatusOK, resp) } @@ -1523,7 +1529,7 @@ func (h *ConfigHandler) TestOpenAI(c *gin.Context) { "model": chatResp.Model, "latency_ms": latency.Milliseconds(), } - addModelContextToResponse(resp, probeModelContext(c.Request.Context(), req.Provider, baseURL, req.APIKey, req.Model), req.MaxTotalTokens, req.ContextProfile) + addModelContextToResponse(resp, probeModelContext(c.Request.Context(), req.Provider, baseURL, req.APIKey, req.Model), req.MaxTotalTokens, req.MaxCompletionTokens, req.ContextProfile) c.JSON(http.StatusOK, resp) } diff --git a/internal/handler/config_context_test.go b/internal/handler/config_context_test.go index 5421306f..615412e3 100644 --- a/internal/handler/config_context_test.go +++ b/internal/handler/config_context_test.go @@ -16,11 +16,15 @@ func TestAddModelContextToResponseLocalProfilePreview(t *testing.T) { ContextWindow: 131072, Source: "ollama_ps", Loaded: true, - }, 120000, "local") + RuntimeSlots: 2, + }, 120000, 0, "local") if got := resp["context_window"]; got != 131072 { t.Fatalf("context_window = %#v, want 131072", got) } + if got := resp["context_slots"]; got != 2 { + t.Fatalf("context_slots = %#v, want 2", got) + } if got := resp["effective_max_total_tokens"]; got != 78643 { t.Fatalf("effective_max_total_tokens = %#v, want 78643", got) } @@ -39,7 +43,7 @@ func TestAddModelContextToResponseLocalProfilePreview(t *testing.T) { func TestAddModelContextToResponseLocalUnknownWindowAssumes32K(t *testing.T) { t.Parallel() resp := gin.H{} - addModelContextToResponse(resp, modelmeta.ContextInfo{}, 120000, "local") + addModelContextToResponse(resp, modelmeta.ContextInfo{}, 120000, 0, "local") if got := resp["effective_max_total_tokens"]; got != 16384 { t.Fatalf("effective_max_total_tokens = %#v, want 16384", got) } @@ -49,10 +53,19 @@ func TestAddModelContextToResponseLocalUnknownWindowAssumes32K(t *testing.T) { } } +func TestAddModelContextToResponseHonorsOutputCap(t *testing.T) { + t.Parallel() + resp := gin.H{} + addModelContextToResponse(resp, modelmeta.ContextInfo{ContextWindow: 32768}, 120000, 4096, "local") + if got := resp["effective_max_total_tokens"]; got != 19660 { + t.Fatalf("effective_max_total_tokens = %#v, want 19660", got) + } +} + func TestAddModelContextToResponseAutoProfileKeepsNoPreviewWithoutWindow(t *testing.T) { t.Parallel() resp := gin.H{} - addModelContextToResponse(resp, modelmeta.ContextInfo{}, 120000, "auto") + addModelContextToResponse(resp, modelmeta.ContextInfo{}, 120000, 0, "auto") if _, ok := resp["effective_max_total_tokens"]; ok { t.Fatalf("auto profile without window should not preview a budget: %#v", resp) } @@ -64,7 +77,7 @@ func TestAddModelContextToResponseDedupesWarnings(t *testing.T) { addModelContextToResponse(resp, modelmeta.ContextInfo{ ContextWindow: 32768, Warnings: []string{modelmeta.WarningContextUnknown, modelmeta.WarningContextUnknown}, - }, 64000, "auto") + }, 64000, 0, "auto") warnings := resp["context_warnings"].([]string) if countWarning(warnings, modelmeta.WarningContextUnknown) != 1 { t.Fatalf("warnings not deduped: %#v", warnings) diff --git a/internal/handler/openapi.go b/internal/handler/openapi.go index 6abc4003..b9d4e93b 100644 --- a/internal/handler/openapi.go +++ b/internal/handler/openapi.go @@ -5033,10 +5033,13 @@ func (h *OpenAPIHandler) GetOpenAPISpec(c *gin.Context) { "type": "object", "required": []string{"api_key", "model"}, "properties": map[string]interface{}{ - "provider": map[string]interface{}{"type": "string", "description": "LLM提供商(openai/claude)", "example": "openai"}, - "base_url": map[string]interface{}{"type": "string", "description": "API基地址(可选,默认根据provider自动选择)"}, - "api_key": map[string]interface{}{"type": "string", "description": "API密钥"}, - "model": map[string]interface{}{"type": "string", "description": "模型名称", "example": "gpt-4"}, + "provider": map[string]interface{}{"type": "string", "description": "LLM提供商(openai/claude)", "example": "openai"}, + "base_url": map[string]interface{}{"type": "string", "description": "API基地址(可选,默认根据provider自动选择)"}, + "api_key": map[string]interface{}{"type": "string", "description": "API密钥"}, + "model": map[string]interface{}{"type": "string", "description": "模型名称", "example": "gpt-4"}, + "max_total_tokens": map[string]interface{}{"type": "integer", "description": "可选:当前最大上下文预算,用于计算有效预算预览"}, + "max_completion_tokens": map[string]interface{}{"type": "integer", "description": "可选:当前单次输出上限,用于计算有效预算预览"}, + "context_profile": map[string]interface{}{"type": "string", "enum": []string{"auto", "local"}, "description": "可选:上下文优化档位"}, }, }, }, @@ -5050,10 +5053,14 @@ func (h *OpenAPIHandler) GetOpenAPISpec(c *gin.Context) { "schema": map[string]interface{}{ "type": "object", "properties": map[string]interface{}{ - "success": map[string]interface{}{"type": "boolean", "description": "是否连接成功"}, - "error": map[string]interface{}{"type": "string", "description": "失败原因(success=false时)"}, - "model": map[string]interface{}{"type": "string", "description": "实际使用的模型(success=true时)"}, - "latency_ms": map[string]interface{}{"type": "number", "description": "延迟毫秒数(success=true时)"}, + "success": map[string]interface{}{"type": "boolean", "description": "是否连接成功"}, + "error": map[string]interface{}{"type": "string", "description": "失败原因(success=false时)"}, + "model": map[string]interface{}{"type": "string", "description": "实际使用的模型(success=true时)"}, + "latency_ms": map[string]interface{}{"type": "number", "description": "延迟毫秒数(success=true时)"}, + "context_window": map[string]interface{}{"type": "integer", "description": "探测到的运行时上下文窗口(可选)"}, + "context_slots": map[string]interface{}{"type": "integer", "description": "llama.cpp 并行槽位数(可选)"}, + "effective_max_total_tokens": map[string]interface{}{"type": "integer", "description": "按档位折算后的有效预算(可选)"}, + "context_warnings": map[string]interface{}{"type": "array", "items": map[string]interface{}{"type": "string"}, "description": "上下文告警码(可选)"}, }, }, }, @@ -5078,14 +5085,15 @@ func (h *OpenAPIHandler) GetOpenAPISpec(c *gin.Context) { "type": "object", "required": []string{"model"}, "properties": map[string]interface{}{ - "provider": map[string]interface{}{"type": "string", "description": "LLM提供商(openai_compatible/claude等)", "example": "openai_compatible"}, - "base_url": map[string]interface{}{"type": "string", "description": "API基地址(可选,默认 OpenAI)", "example": "http://127.0.0.1:11434/v1"}, - "api_key": map[string]interface{}{"type": "string", "description": "API密钥(可选,可回退到已保存通道)"}, - "model": map[string]interface{}{"type": "string", "description": "模型名称", "example": "qwen3:8b"}, - "channel_id": map[string]interface{}{"type": "string", "description": "已保存的 AI 通道 ID(用于复用密钥)"}, - "credential_scope": map[string]interface{}{"type": "string", "description": "凭据作用域(可选)"}, - "max_total_tokens": map[string]interface{}{"type": "integer", "description": "当前配置的最大上下文预算,用于计算有效预算与告警"}, - "context_profile": map[string]interface{}{"type": "string", "enum": []string{"auto", "local"}, "description": "上下文优化档位"}, + "provider": map[string]interface{}{"type": "string", "description": "LLM提供商(openai_compatible/claude等)", "example": "openai_compatible"}, + "base_url": map[string]interface{}{"type": "string", "description": "API基地址(可选,默认 OpenAI)", "example": "http://127.0.0.1:11434/v1"}, + "api_key": map[string]interface{}{"type": "string", "description": "API密钥(可选,可回退到已保存通道)"}, + "model": map[string]interface{}{"type": "string", "description": "模型名称", "example": "qwen3:8b"}, + "channel_id": map[string]interface{}{"type": "string", "description": "已保存的 AI 通道 ID(用于复用密钥)"}, + "credential_scope": map[string]interface{}{"type": "string", "description": "凭据作用域(可选)"}, + "max_total_tokens": map[string]interface{}{"type": "integer", "description": "当前配置的最大上下文预算,用于计算有效预算与告警"}, + "max_completion_tokens": map[string]interface{}{"type": "integer", "description": "当前配置的单次输出上限,用于计算有效预算与输出预留"}, + "context_profile": map[string]interface{}{"type": "string", "enum": []string{"auto", "local"}, "description": "上下文优化档位"}, }, }, }, @@ -5105,6 +5113,7 @@ func (h *OpenAPIHandler) GetOpenAPISpec(c *gin.Context) { "context_window": map[string]interface{}{"type": "integer", "description": "运行时上下文窗口(token)"}, "context_source": map[string]interface{}{"type": "string", "description": "窗口来源(如 ollama_ps、llamacpp_props)"}, "context_loaded": map[string]interface{}{"type": "boolean", "description": "窗口是否来自已加载实例"}, + "context_slots": map[string]interface{}{"type": "integer", "description": "llama.cpp 并行槽位数(--parallel);大于 1 时单请求窗口可能小于 n_ctx"}, "context_runtime_unknown": map[string]interface{}{"type": "boolean", "description": "只能确认模型上限,无法确认运行时窗口"}, "effective_max_total_tokens": map[string]interface{}{"type": "integer", "description": "按 context_profile 折算后的有效预算"}, "context_warnings": map[string]interface{}{"type": "array", "items": map[string]interface{}{"type": "string"}, "description": "告警码列表(如 ollama_v1_ignores_num_ctx、max_total_tokens_clamped)"}, diff --git a/internal/modelmeta/context.go b/internal/modelmeta/context.go index 064d01f8..b69b1469 100644 --- a/internal/modelmeta/context.go +++ b/internal/modelmeta/context.go @@ -22,6 +22,7 @@ const ( WarningOllamaV1IgnoresNumCtx = "ollama_v1_ignores_num_ctx" WarningOllamaRuntimeUnknown = "ollama_runtime_context_unknown" WarningRuntimeUnknown = "context_runtime_unknown" + WarningLlamaCppParallelSlots = "llamacpp_parallel_slots" WarningContextUnknown = "context_window_unknown" WarningBudgetExceedsWindow = "configured_budget_exceeds_context_window" probeTimeout = 2 * time.Second @@ -32,6 +33,7 @@ type ContextInfo struct { ContextWindow int `json:"context_window,omitempty"` Source string `json:"context_source,omitempty"` Loaded bool `json:"context_loaded,omitempty"` + RuntimeSlots int `json:"context_slots,omitempty"` RuntimeUnknown bool `json:"context_runtime_unknown,omitempty"` Warnings []string `json:"context_warnings,omitempty"` } @@ -237,6 +239,14 @@ func detectLlamaCpp(ctx context.Context, client *http.Client, root, model, apiKe n = props.NCtx } info := ContextInfo{Backend: BackendLlamaCpp, Loaded: true} + if props.TotalSlots > 0 { + info.RuntimeSlots = props.TotalSlots + } + if props.TotalSlots > 1 { + // n_ctx is the shared pool; per-slot capacity depends on the KV mode + // (--parallel historically divides it, unified KV may not). + info.Warnings = append(info.Warnings, WarningLlamaCppParallelSlots) + } if n > 0 { info.ContextWindow = n info.Source = "llamacpp_props" diff --git a/internal/modelmeta/context_test.go b/internal/modelmeta/context_test.go index ec71792f..20121a56 100644 --- a/internal/modelmeta/context_test.go +++ b/internal/modelmeta/context_test.go @@ -92,6 +92,48 @@ func TestDetectContextOllamaShowModelMax(t *testing.T) { } } +func TestDetectContextLlamaCppParallelSlotsWarns(t *testing.T) { + t.Parallel() + mux := http.NewServeMux() + mux.HandleFunc("/props", func(w http.ResponseWriter, _ *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]interface{}{ + "default_generation_settings": map[string]interface{}{"n_ctx": 32768}, + "total_slots": 2, + }) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + + info := DetectContext(context.Background(), srv.URL+"/v1", "local-model", "", srv.Client()) + if info.ContextWindow != 32768 || info.RuntimeSlots != 2 { + t.Fatalf("unexpected info: %+v", info) + } + if !contains(info.Warnings, WarningLlamaCppParallelSlots) { + t.Fatalf("missing parallel-slots warning: %+v", info.Warnings) + } +} + +func TestDetectContextLlamaCppSingleSlotNoWarning(t *testing.T) { + t.Parallel() + mux := http.NewServeMux() + mux.HandleFunc("/props", func(w http.ResponseWriter, _ *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]interface{}{ + "default_generation_settings": map[string]interface{}{"n_ctx": 32768}, + "total_slots": 1, + }) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + + info := DetectContext(context.Background(), srv.URL+"/v1", "local-model", "", srv.Client()) + if info.RuntimeSlots != 1 { + t.Fatalf("slots = %d, want 1", info.RuntimeSlots) + } + if contains(info.Warnings, WarningLlamaCppParallelSlots) { + t.Fatalf("unexpected parallel-slots warning: %+v", info.Warnings) + } +} + func TestDetectContextLlamaCpp(t *testing.T) { t.Parallel() mux := http.NewServeMux() diff --git a/internal/multiagent/context_budget_test.go b/internal/multiagent/context_budget_test.go index c285e398..bcebe525 100644 --- a/internal/multiagent/context_budget_test.go +++ b/internal/multiagent/context_budget_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "strings" + "sync/atomic" "testing" "cyberstrike-ai/internal/config" @@ -16,6 +17,8 @@ import ( "go.uber.org/zap/zaptest/observer" ) +var budgetWarningTestSeq atomic.Int64 + func TestIsEinoContextOverflowError(t *testing.T) { t.Parallel() cases := []struct { @@ -96,8 +99,11 @@ func TestLogContextBudgetWarningsKeepsConfiguredValue(t *testing.T) { t.Parallel() core, logs := observer.New(zapcore.WarnLevel) logger := zap.New(core) + // The warning dedupe map is process-global; use a unique window so + // -count>1 keeps exercising the logging path. + window := 131000 + int(budgetWarningTestSeq.Add(1)) configured := config.OpenAIConfig{ - ContextWindow: 131073, + ContextWindow: window, ContextProfile: "local", MaxTotalTokens: 120000, } @@ -113,8 +119,8 @@ func TestLogContextBudgetWarningsKeepsConfiguredValue(t *testing.T) { if got, ok := fields["configured_max_total_tokens"].(int64); !ok || got != 120000 { t.Fatalf("configured_max_total_tokens = %#v, want 120000", fields["configured_max_total_tokens"]) } - if got, ok := fields["effective_max_total_tokens"].(int64); !ok || got != 78643 { - t.Fatalf("effective_max_total_tokens = %#v, want 78643", fields["effective_max_total_tokens"]) + if got, ok := fields["effective_max_total_tokens"].(int64); !ok || got != int64(effective.MaxTotalTokens) { + t.Fatalf("effective_max_total_tokens = %#v, want %d", fields["effective_max_total_tokens"], effective.MaxTotalTokens) } warnings := warningCodes(fields["warnings"]) if !hasWarningCode(warnings, config.ContextWarningMaxTotalClamped) { diff --git a/web/static/i18n/en-US.json b/web/static/i18n/en-US.json index 2dbd473b..73904186 100644 --- a/web/static/i18n/en-US.json +++ b/web/static/i18n/en-US.json @@ -3107,10 +3107,12 @@ "contextWarnWindowUnknown": "No window set for the local profile; assuming 32768", "contextWarnWindowSmall": "Window below 16384; tool-using agents may be unreliable", "contextWarnBudgetClamped": "Max context budget was clamped to the model window", + "contextWarnCompletionClamped": "Max output tokens were clamped to the model window", "contextWarnBudgetExceedsWindow": "Configured budget exceeds the model window; it will be clamped at runtime", "contextWarnOllamaV1": "Ollama's /v1 endpoint ignores num_ctx; set OLLAMA_CONTEXT_LENGTH or a Modelfile parameter", "contextWarnOllamaRuntime": "Ollama may cap the window below the model maximum based on VRAM; check ollama ps after loading", "contextWarnRuntimeUnknown": "Runtime window could not be confirmed and may be below the model maximum", + "contextWarnLlamaCppSlots": "llama.cpp is running multiple parallel slots; the per-request window may be smaller than n_ctx. Check --parallel and the KV mode", "contextWarnUnknown": "No context window detected; enter it manually", "openaiReasoningTitle": "Reasoning settings", "openaiReasoningHint": "Default reasoning settings for this AI channel; chat Session settings can override them.", diff --git a/web/static/i18n/ru-RU.json b/web/static/i18n/ru-RU.json index 9c186f4a..bc81752e 100644 --- a/web/static/i18n/ru-RU.json +++ b/web/static/i18n/ru-RU.json @@ -3120,10 +3120,12 @@ "contextWarnWindowUnknown": "Для локального профиля не задано окно; используется 32768", "contextWarnWindowSmall": "Окно меньше 16384; агент с инструментами может работать нестабильно", "contextWarnBudgetClamped": "Бюджет контекста ограничен размером окна модели", + "contextWarnCompletionClamped": "Максимум выходных токенов ограничен размером окна модели", "contextWarnBudgetExceedsWindow": "Бюджет превышает окно модели и будет ограничен во время работы", "contextWarnOllamaV1": "Эндпоинт Ollama /v1 игнорирует num_ctx; задайте OLLAMA_CONTEXT_LENGTH или параметр Modelfile", "contextWarnOllamaRuntime": "Ollama может уменьшить окно ниже максимума модели в зависимости от VRAM; проверьте ollama ps", "contextWarnRuntimeUnknown": "Не удалось подтвердить рабочее окно; оно может быть меньше максимума модели", + "contextWarnLlamaCppSlots": "llama.cpp запущен с несколькими параллельными слотами; окно одного запроса может быть меньше n_ctx. Проверьте --parallel и режим KV", "contextWarnUnknown": "Окно контекста не обнаружено; укажите его вручную", "openaiReasoningTitle": "Настройки рассуждения", "openaiReasoningHint": "Настройки рассуждения этого канала ИИ по умолчанию; настройки сессии чата могут их переопределить.", diff --git a/web/static/i18n/zh-CN.json b/web/static/i18n/zh-CN.json index 40c08282..650998c8 100644 --- a/web/static/i18n/zh-CN.json +++ b/web/static/i18n/zh-CN.json @@ -3095,10 +3095,12 @@ "contextWarnWindowUnknown": "本地档位未填写窗口,按 32768 估算", "contextWarnWindowSmall": "窗口小于 16384,带工具的 agent 可能无法稳定运行", "contextWarnBudgetClamped": "最大上下文预算已按模型窗口收紧", + "contextWarnCompletionClamped": "最大输出 Token 数已按模型窗口收紧", "contextWarnBudgetExceedsWindow": "填写的预算超过模型窗口,运行时会自动收紧", "contextWarnOllamaV1": "Ollama 的 /v1 接口忽略 num_ctx,请在服务端设置 OLLAMA_CONTEXT_LENGTH 或 Modelfile", "contextWarnOllamaRuntime": "Ollama 可能按显存把窗口压到模型上限以下,建议启动后查看 ollama ps", "contextWarnRuntimeUnknown": "无法确认运行时窗口,可能小于模型上限", + "contextWarnLlamaCppSlots": "llama.cpp 配置了多个并行槽位,单请求可用窗口可能小于 n_ctx;请按 --parallel/KV 模式确认", "contextWarnUnknown": "未检测到上下文窗口,请手动填写", "openaiReasoningTitle": "推理设置", "openaiReasoningHint": "作为该 AI 通道的默认推理设置;对话页「会话设置」可覆盖。", diff --git a/web/static/js/settings.js b/web/static/js/settings.js index 0bfcd0e8..a42b8fa4 100644 --- a/web/static/js/settings.js +++ b/web/static/js/settings.js @@ -3238,6 +3238,7 @@ async function probeSelectedAIChannels() { api_key: ch.api_key || '', model: ch.model || '', max_total_tokens: parseInt(ch.max_total_tokens, 10) || 0, + max_completion_tokens: parseInt(ch.max_completion_tokens, 10) || 0, context_profile: ch.context_profile || '' }) }); @@ -3900,10 +3901,12 @@ function contextWarningText(code) { local_context_window_unknown: settingsT('settingsBasic.contextWarnWindowUnknown', '本地档位未填写窗口,按 32768 估算'), local_context_window_small: settingsT('settingsBasic.contextWarnWindowSmall', '窗口小于 16384,带工具的 agent 可能无法稳定运行'), max_total_tokens_clamped: settingsT('settingsBasic.contextWarnBudgetClamped', '最大上下文预算已按模型窗口收紧'), + max_completion_tokens_clamped: settingsT('settingsBasic.contextWarnCompletionClamped', '最大输出 Token 数已按模型窗口收紧'), configured_budget_exceeds_context_window: settingsT('settingsBasic.contextWarnBudgetExceedsWindow', '填写的预算超过模型窗口,运行时会自动收紧'), ollama_v1_ignores_num_ctx: settingsT('settingsBasic.contextWarnOllamaV1', 'Ollama 的 /v1 接口忽略 num_ctx,请在服务端设置 OLLAMA_CONTEXT_LENGTH 或 Modelfile'), ollama_runtime_context_unknown: settingsT('settingsBasic.contextWarnOllamaRuntime', 'Ollama 可能按显存把窗口压到模型上限以下,建议启动后查看 ollama ps'), context_runtime_unknown: settingsT('settingsBasic.contextWarnRuntimeUnknown', '无法确认运行时窗口,可能小于模型上限'), + llamacpp_parallel_slots: settingsT('settingsBasic.contextWarnLlamaCppSlots', 'llama.cpp 配置了多个并行槽位,单请求可用窗口可能小于 n_ctx;请按 --parallel/KV 模式确认'), context_window_unknown: settingsT('settingsBasic.contextWarnUnknown', '未检测到上下文窗口,请手动填写') }; return messages[code] || code; @@ -3923,10 +3926,12 @@ function formatDetectedContext(result) { return parts.join(' · '); } -function applyDetectedContext(result) { +function applyDetectedContext(result, force) { if (!result || !result.context_window) return; const input = document.getElementById('openai-context-window'); - if (input && !String(input.value || '').trim()) { + // Explicit auto-detect overwrites the field so the effective-budget preview + // matches what will be saved; a connection test only fills an empty field. + if (input && (force || !String(input.value || '').trim())) { input.value = String(result.context_window); } const resultEl = document.getElementById('detect-context-result'); @@ -3970,16 +3975,13 @@ async function detectAIContext() { api_key: apiKey, model: model, max_total_tokens: parseInt(document.getElementById('openai-max-total-tokens')?.value, 10) || 0, + max_completion_tokens: parseInt(document.getElementById('openai-max-completion-tokens')?.value, 10) || 0, context_profile: document.getElementById('openai-context-profile')?.value || '' }) }); const result = await response.json().catch(() => ({})); if (result.success && result.context_window) { - applyDetectedContext(result); - if (resultEl) { - resultEl.textContent = formatDetectedContext(result); - resultEl.className = 'form-inline-result is-success'; - } + applyDetectedContext(result, true); } else { const message = result.error || contextWarningText('context_window_unknown'); if (resultEl) { @@ -4043,6 +4045,7 @@ async function testOpenAIConnection() { api_key: apiKey, model: model, max_total_tokens: parseInt(document.getElementById('openai-max-total-tokens')?.value, 10) || 0, + max_completion_tokens: parseInt(document.getElementById('openai-max-completion-tokens')?.value, 10) || 0, context_profile: document.getElementById('openai-context-profile')?.value || '' }) });