From 14c5422901d76e4360a452b3cfd7f2b998e91c13 Mon Sep 17 00:00:00 2001 From: Sycun <165354365+Sycun@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:41:55 +0800 Subject: [PATCH] feat(config): apply context optimization automatically and detect oMLX --- docs/en-US/configuration.md | 7 +- docs/en-US/token-usage-monitoring.md | 2 +- docs/zh-CN/configuration.md | 12 ++- docs/zh-CN/token-usage-monitoring.md | 2 +- internal/config/config.go | 5 +- internal/config/context_profile.go | 12 ++- internal/config/context_profile_test.go | 20 +++- internal/handler/config.go | 30 ++++-- internal/handler/config_context_test.go | 27 ++++++ .../handler/config_testopenai_headers_test.go | 37 ++++++++ internal/modelmeta/context.go | 58 +++++++++++- internal/modelmeta/context_test.go | 51 ++++++++++ web/static/i18n/en-US.json | 6 -- web/static/i18n/ru-RU.json | 6 -- web/static/i18n/zh-CN.json | 6 -- web/static/js/settings-pi-resilience.test.cjs | 92 +++++++++++++++++++ web/static/js/settings.js | 70 +++++++++++--- web/templates/index.html | 10 -- 18 files changed, 382 insertions(+), 71 deletions(-) diff --git a/docs/en-US/configuration.md b/docs/en-US/configuration.md index 0c910f32..932f6f1d 100644 --- a/docs/en-US/configuration.md +++ b/docs/en-US/configuration.md @@ -73,7 +73,7 @@ ai: | `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) enables input savings for the official DeepSeek endpoint or an explicit DeepSeek reasoning profile. Select `economy` to enable savings on another channel, `custom` to use runtime settings, or `local` to tighten context budgets and tool overhead for 32K–256K local models. | +| `context_profile` | Managed in the background. `auto` enables input savings based on the DeepSeek endpoint, reasoning profile or model name. Channel saves probe backend metadata and record `local_auto` for recognized local inference servers. Configuration files also accept `economy`, `custom` and manual `local` overrides. | | `reasoning` | Default reasoning fields for the channel. Gateway support varies; try `mode: off` first when a provider rejects requests. | ### Local Model Context (32K–256K) @@ -81,7 +81,10 @@ 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, 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. +2. **Automatic local budgets**. Saving a channel, testing its connection or detecting its context probes Ollama, llama.cpp, LM Studio, vLLM and oMLX metadata. Recognized backends activate local optimization automatically. The budget is capped at 60% of the window and reserves output space. Smaller manual windows are preserved. Generic compatible responses and private IP addresses alone do not identify a local backend. Failed probes allow saving the channel, and configuration files still accept `context_profile: local`. + + oMLX is identified by `owned_by: omlx`. Its matching `/v1/models/status` entry supplies `max_context_window`, including model aliases. If status access is unavailable, discovery falls back to `max_model_len` in `/v1/models`. Reverse-proxy prefixes are supported. New channels whose runtime window remains unknown use the local default budget. Changing the endpoint or model clears the previous automatic classification. [oMLX implementation](https://github.com/jundot/omlx/blob/main/omlx/server.py) + 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**: diff --git a/docs/en-US/token-usage-monitoring.md b/docs/en-US/token-usage-monitoring.md index 279418bb..7b76df7c 100644 --- a/docs/en-US/token-usage-monitoring.md +++ b/docs/en-US/token-usage-monitoring.md @@ -14,4 +14,4 @@ In the channel’s reasoning settings, use `off` for simple Q&A and format conve The official API automatically caches reusable request prefixes. Pi orders MCP tool definitions by name so the same catalog introduces fewer prefix changes across requests. The provider reports the actual cache hits. [DeepSeek Context Caching](https://api-docs.deepseek.com/guides/kv_cache/) -The default `auto` context profile enables input savings for the official DeepSeek endpoint and explicit `deepseek` / `deepseek_compat` reasoning profiles. At 16 tools, native discovery keeps six catalog entries plus core tools and explicit always-visible tools available. Other builtins load on demand. With authorized file access, results over 8,000 bytes become head/tail previews backed by the full output. Tighter configured limits take precedence. Valid JSON tool results lose formatting whitespace, including when replaying older sessions. Strings and numeric lexemes retain their original text. Select `custom` to use the configured runtime settings. Compare complete tasks, including discovery/readback calls and evidence quality, to measure actual savings. +Input savings activate in the background for the official DeepSeek endpoint, explicit `deepseek` / `deepseek_compat` reasoning profiles, and model names containing `deepseek` (case-insensitive). At 16 tools, native discovery keeps six catalog entries plus core tools and explicit always-visible tools available. Other builtins load on demand. With authorized file access, results over 8,000 bytes become head/tail previews backed by the full output. Tighter configured limits take precedence. Valid JSON tool results lose formatting whitespace, including when replaying older sessions. Strings and numeric lexemes retain their original text. Existing configuration-file overrides remain supported. Compare complete tasks, including discovery/readback calls and evidence quality, to measure actual savings. diff --git a/docs/zh-CN/configuration.md b/docs/zh-CN/configuration.md index d28a97ba..a7418984 100644 --- a/docs/zh-CN/configuration.md +++ b/docs/zh-CN/configuration.md @@ -74,7 +74,7 @@ ai: | `max_total_tokens` | 上下文压缩、攻击链构建、多代理摘要等共用的总预算。已知 `context_window` 时会收紧到“窗口 − 输出预留”。 | | `max_completion_tokens` | 单次模型输出上限;未填时使用默认值,并会被压到已知/假定窗口的一半以内。 | | `context_window` | 模型原生上下文窗口(token)。填写后运行时会按窗口收紧 `max_total_tokens`;0/省略表示未知。 | -| `context_profile` | `auto`(默认)为官方 DeepSeek 地址或显式 DeepSeek 推理线路启用节省输入;其他通道可选 `economy` 启用。`custom` 使用运行时配置。`local` 面向 32K–256K 本地模型,收紧上下文预算与工具开销。 | +| `context_profile` | 后台配置项,页面自动处理。`auto`(默认)通过 DeepSeek 官方地址、推理线路或模型名启用节省输入。保存通道时识别到本地推理服务会记录 `local_auto` 并应用本地预算。配置文件兼容 `economy`、`custom` 和手动 `local`。 | | `reasoning` | 该通道的默认推理扩展字段。不同网关支持差异较大,异常时先尝试 `mode: off`。 | ### 按提供商和模型关闭推理 @@ -91,20 +91,24 @@ GPT-5.6 和 GPT-6 Sol/Luna 在 Chat Completions 中使用函数工具时,应 ### DeepSeek 输入优化 -升级后,`auto` 在 `api.deepseek.com` 或推理线路为 `deepseek` / `deepseek_compat` 的通道启用以下规则。第三方通道可显式选择 `economy`。 +升级后,后台默认通过 `api.deepseek.com`、`deepseek` / `deepseek_compat` 推理线路或包含 `deepseek`(大小写不敏感)的模型名识别通道,自动启用以下规则。用户配置模型后即可使用。 - 工具数达到 16 时使用 Pi 原生 `tool_search`,默认常驻前 6 个工具和会话、执行控制、读取文件等核心工具。配置的 `tool_search_always_visible_tools` 继续作为常驻清单,其他内置工具按需发现和调用。 - 有本地文件读取权限时,超过 8,000 字节的工具结果保存全文并返回首尾预览,模型可用 `read_file` 按行读取中间证据。更小的已配置阈值优先,落盘失败时返回完整内容。 - 发送给模型的 JSON 工具回包精简格式空白,保留字符串、数字原文和字段顺序。已有会话中的 JSON 工具回包也会在请求时精简,原始会话记录保留完整文本。 -输出上限和推理强度由通道与对话设置决定。工具检索和分段回读会增加必要调用,收益随工具目录和任务变化。可在「上下文优化档位」选 `custom`,按已有运行时参数控制工具发现与结果缩减。 +输出上限和推理强度由通道与对话设置决定。工具检索和分段回读会增加必要调用,收益随工具目录和任务变化。已有配置文件中的档位覆盖继续生效,保存页面设置时会保留它们。 ### 本地模型(32K–256K)上下文要点 本地模型的有效上下文通常明显小于标称窗口,且不同后端的“模型上限”和“运行时窗口”可能不一致。建议: +保存通道、测试连接或检测上下文时,系统会通过服务元数据自动识别本地后端。探测失败时可继续保存,后续探测成功后应用优化。Ollama 使用 `/api/version` 与 `/api/ps`,llama.cpp 使用 `/props`,LM Studio 使用模型状态信息,vLLM 和 oMLX 使用模型列表中的 `owned_by` 标识。普通 OpenAI 兼容列表或内网 IP 地址本身不足以触发本地档位。 + +oMLX 优先使用 `/v1/models/status` 中匹配模型或别名的 `max_context_window`,状态接口不可读时使用 `/v1/models` 的 `max_model_len`。支持反向代理路径。自动检测只读取元数据,按服务给出的窗口收紧过大的已有配置。更小的手动窗口继续生效。仅取得架构上限时,新通道保留窗口未知状态,运行时采用本地默认预算。切换服务或模型后会重新判定。[oMLX 接口实现](https://github.com/jundot/omlx/blob/main/omlx/server.py) + 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% 计算,同时不超过“窗口 − 输出预留”(例如 32K 窗口、默认输出上限 16K 时预算为 16K);单次输出上限也会被压到窗口的一半以内。摘要更早触发;工具输出截断阈值约为窗口/6(8–32 KB),历史工具结果清理阈值约为预算的 35%;常驻工具收敛到核心集合,内置工具也进入 `tool_search` 动态池,其余工具按需解锁。token 估算会额外放大 10%,抵消本地 tokenizer 与 tiktoken 在中英文上的差异。该档位还会把输出上限字段切换为更通用的 `max_tokens`(Ollama/llama.cpp 等常不识别 `max_completion_tokens`),攻击链、FOFA 语法生成、工作流草稿、HITL 审计等旁路调用同样生效。 +2. **自动应用本地预算**。识别到本地服务后,预算按窗口 60% 计算,同时不超过“窗口 − 输出预留”。例如 32K 窗口、默认输出上限 16K 时,预算为 16K。常驻工具和工具回包按窗口收紧,输出上限字段采用 `max_tokens`。配置文件仍可用 `context_profile: local` 手动指定。 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 与前缀缓存**: diff --git a/docs/zh-CN/token-usage-monitoring.md b/docs/zh-CN/token-usage-monitoring.md index 0bc5900e..c6a5fd40 100644 --- a/docs/zh-CN/token-usage-monitoring.md +++ b/docs/zh-CN/token-usage-monitoring.md @@ -25,4 +25,4 @@ 官方接口自动缓存可复用的请求前缀。Pi 按名称固定 MCP 工具定义的顺序,以减少相同工具目录在请求之间的前缀变化。缓存命中以供应商返回的用量为准。[DeepSeek 上下文缓存](https://api-docs.deepseek.com/guides/kv_cache/) -默认 `auto` 上下文档位会为官方 DeepSeek 地址及显式 DeepSeek 线路启用按需工具发现、JSON 回包精简与可回读的大结果预览。具体阈值和 `custom` 选项见[配置说明](configuration.md#deepseek-输入优化)。验证节省效果时,对照完整任务的输入、输出、缓存命中和调用次数,并检查任务产物与证据完整性。 +后台默认根据官方 DeepSeek 地址、DeepSeek 线路或模型名自动启用按需工具发现、JSON 回包精简与可回读的大结果预览。用户配置模型后即可使用。验证节省效果时,对照完整任务的输入、输出、缓存命中和调用次数,并检查任务产物与证据完整性。具体阈值见[配置说明](configuration.md#deepseek-输入优化)。 diff --git a/internal/config/config.go b/internal/config/config.go index 15ae7eb9..85518c74 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -731,7 +731,8 @@ type OpenAIConfig struct { Headers map[string]string `yaml:"headers,omitempty" json:"headers,omitempty"` // ContextWindow 是模型原生上下文窗口(token);0 表示未知。用于校验/压缩 max_total_tokens。 ContextWindow int `yaml:"context_window,omitempty" json:"context_window,omitempty"` - // ContextProfile selects auto (DeepSeek input savings), economy, custom or local. + // ContextProfile selects auto, economy, custom or local; local_auto records + // a local backend identified through the model metadata probe. ContextProfile string `yaml:"context_profile,omitempty" json:"context_profile,omitempty"` // Reasoning 控制 Agent ChatModel 的 thinking / reasoning_effort / output_config 等(Agent 单/多代理路径生效)。 Reasoning OpenAIReasoningConfig `yaml:"reasoning,omitempty" json:"reasoning,omitempty"` @@ -1678,7 +1679,7 @@ func ValidateContextSettings(prefix string, window int, profile string) error { } if raw := strings.TrimSpace(profile); raw != "" && !strings.EqualFold(raw, "auto") && NormalizeContextProfile(raw) == "" { - return fmt.Errorf("%s.context_profile 只支持 auto、economy、custom 或 local", prefix) + return fmt.Errorf("%s.context_profile 只支持 auto、economy、custom、local 或 local_auto", prefix) } return nil } diff --git a/internal/config/context_profile.go b/internal/config/context_profile.go index 4f5fe9af..b58ff37f 100644 --- a/internal/config/context_profile.go +++ b/internal/config/context_profile.go @@ -26,7 +26,7 @@ const ( // NormalizeContextProfile returns an explicit profile, or empty for auto. func NormalizeContextProfile(raw string) string { switch profile := strings.ToLower(strings.TrimSpace(raw)); profile { - case "local", "economy", "custom": + case "local", "local_auto", "economy", "custom": return profile } return "" @@ -38,15 +38,19 @@ func (c OpenAIConfig) IsEconomyContextProfile() bool { switch NormalizeContextProfile(c.ContextProfile) { case "economy": return true - case "custom", "local": + case "custom", "local", "local_auto": return false } profile := c.Reasoning.ProfileEffective() - return c.IsDeepSeekOfficialEndpoint() || profile == "deepseek" || profile == "deepseek_compat" + // Model-name detection only selects input savings. The gateway's wire + // protocol and reasoning parameters still follow its provider profile. + return c.IsDeepSeekOfficialEndpoint() || profile == "deepseek" || profile == "deepseek_compat" || + strings.Contains(strings.ToLower(c.Model), "deepseek") } func (c OpenAIConfig) IsLocalContextProfile() bool { - return NormalizeContextProfile(c.ContextProfile) == "local" + profile := NormalizeContextProfile(c.ContextProfile) + return profile == "local" || profile == "local_auto" } // TokenEstimateSafetyPercent 供 token 计数器使用:local 档位放大估算,auto 保持原值。 diff --git a/internal/config/context_profile_test.go b/internal/config/context_profile_test.go index 37b6655c..46b35182 100644 --- a/internal/config/context_profile_test.go +++ b/internal/config/context_profile_test.go @@ -314,10 +314,14 @@ func TestEconomyContextProfileSelectionAndLimits(t *testing.T) { }{ {"official default", OpenAIConfig{BaseURL: "https://api.deepseek.com/v1"}, true}, {"gateway explicit profile", OpenAIConfig{Reasoning: OpenAIReasoningConfig{Profile: "deepseek_compat"}}, true}, - {"model name alone", OpenAIConfig{Model: "deepseek-flash", BaseURL: "https://gateway.example/v1"}, false}, + {"gateway model name", OpenAIConfig{Model: "deepseek-flash", BaseURL: "https://gateway.example/v1"}, true}, + {"namespaced model", OpenAIConfig{Model: "deepseek-ai/DeepSeek-V4", Reasoning: OpenAIReasoningConfig{Profile: "openai_compat"}}, true}, + {"other model", OpenAIConfig{Model: "gpt-example", BaseURL: "https://gateway.example/v1"}, false}, + {"gateway custom opt out", OpenAIConfig{Model: "deepseek-flash", ContextProfile: "custom"}, false}, {"lookalike host", OpenAIConfig{BaseURL: "https://api.deepseek.com.example/v1"}, false}, {"custom opt out", OpenAIConfig{BaseURL: "https://api.deepseek.com", ContextProfile: "custom"}, false}, {"local opt in", OpenAIConfig{BaseURL: "https://api.deepseek.com", ContextProfile: "local"}, false}, + {"detected local DeepSeek", OpenAIConfig{Model: "deepseek-flash", ContextProfile: "local_auto"}, false}, {"economy opt in", OpenAIConfig{ContextProfile: " ECONOMY "}, true}, } { t.Run(tc.name, func(t *testing.T) { @@ -345,7 +349,7 @@ func TestEconomyContextProfileSelectionAndLimits(t *testing.T) { if again := EffectiveRuntimeForChannel(out, oa); !reflect.DeepEqual(out, again) { t.Fatal("economy profile loosened tighter limits") } - for _, profile := range []string{"auto", "economy", "custom", "local"} { + for _, profile := range []string{"auto", "economy", "custom", "local", "local_auto"} { if err := ValidateContextSettings("channel", 0, profile); err != nil { t.Fatal(err) } @@ -356,6 +360,18 @@ func TestEconomyContextProfileSelectionAndLimits(t *testing.T) { } } +func TestDetectedLocalProfileUsesLocalBudgets(t *testing.T) { + manual := OpenAIConfig{ContextProfile: "local", ContextWindow: 65536, MaxCompletionTokens: 8192} + detected := manual + detected.ContextProfile = "local_auto" + if !detected.IsLocalContextProfile() || detected.EffectiveMaxTotalTokens() != manual.EffectiveMaxTotalTokens() || detected.OutputLimitField() != "max_tokens" { + t.Fatalf("detected backend lost local limits: %+v", detected) + } + if !reflect.DeepEqual(EffectiveRuntimeForChannel(AgentTuningConfig{}, detected), EffectiveRuntimeForChannel(AgentTuningConfig{}, manual)) { + t.Fatal("detected backend lost local runtime tuning") + } +} + func TestWithEffectiveContextBudgetIsIdempotent(t *testing.T) { t.Parallel() cfg := &Config{ diff --git a/internal/handler/config.go b/internal/handler/config.go index 2e33bbc6..fe943610 100644 --- a/internal/handler/config.go +++ b/internal/handler/config.go @@ -1341,12 +1341,23 @@ func addModelContextToResponse(resp gin.H, info modelmeta.ContextInfo, maxTotalT resp["context_runtime_unknown"] = true } profile := config.NormalizeContextProfile(contextProfile) + if profile == "" || profile == "local_auto" { + if info.IsLocalBackend() { + profile = "local_auto" + } else if info.Source != "" { + profile = "" + } + } + resp["context_profile"] = profile oa := config.OpenAIConfig{ ContextWindow: info.ContextWindow, ContextProfile: profile, MaxTotalTokens: maxTotalTokens, MaxCompletionTokens: maxCompletionTokens, } + if profile == "local_auto" && info.RuntimeUnknown { + oa.ContextWindow = 0 + } if info.ContextWindow > 0 || profile != "" { resp["effective_max_total_tokens"] = oa.EffectiveMaxTotalTokens() } @@ -1454,8 +1465,12 @@ func (h *ConfigHandler) TestOpenAI(c *gin.Context) { } } - // 构造一个最小的 chat completion 请求;本地档位使用更通用的 max_tokens。 - maxTokensField := (config.OpenAIConfig{ContextProfile: req.ContextProfile}).OutputLimitField() + // Identify local servers before the completion so the first connection + // test already uses the output-limit field supported by that backend. + metadata := gin.H{} + addModelContextToResponse(metadata, probeModelContext(c.Request.Context(), req.Provider, baseURL, req.APIKey, req.Model, resolvedHeaders), req.MaxTotalTokens, req.MaxCompletionTokens, req.ContextProfile) + detectedProfile, _ := metadata["context_profile"].(string) + maxTokensField := (config.OpenAIConfig{ContextProfile: detectedProfile}).OutputLimitField() payload := map[string]interface{}{ "model": req.Model, "messages": []map[string]string{ @@ -1528,13 +1543,10 @@ func (h *ConfigHandler) TestOpenAI(c *gin.Context) { return } - resp := gin.H{ - "success": true, - "model": chatResp.Model, - "latency_ms": latency.Milliseconds(), - } - addModelContextToResponse(resp, probeModelContext(c.Request.Context(), req.Provider, baseURL, req.APIKey, req.Model, resolvedHeaders), req.MaxTotalTokens, req.MaxCompletionTokens, req.ContextProfile) - c.JSON(http.StatusOK, resp) + metadata["success"] = true + metadata["model"] = chatResp.Model + metadata["latency_ms"] = latency.Milliseconds() + c.JSON(http.StatusOK, metadata) } // TestTypeSafeRequest 测试 TypeSafe / Jev 连接。 diff --git a/internal/handler/config_context_test.go b/internal/handler/config_context_test.go index d36ced57..7011ec29 100644 --- a/internal/handler/config_context_test.go +++ b/internal/handler/config_context_test.go @@ -74,6 +74,33 @@ func TestAddModelContextToResponseAutoProfileKeepsNoPreviewWithoutWindow(t *test } } +func TestDetectedBackendAutomaticallySelectsLocalProfile(t *testing.T) { + for _, backend := range []string{modelmeta.BackendOllama, modelmeta.BackendLlamaCpp, modelmeta.BackendLMStudio, modelmeta.BackendOMLX, modelmeta.BackendVLLM} { + resp := gin.H{} + addModelContextToResponse(resp, modelmeta.ContextInfo{Backend: backend, ContextWindow: 65536}, 120000, 8192, "auto") + if resp["context_profile"] != "local_auto" || resp["effective_max_total_tokens"] != 39321 { + t.Fatalf("%s: %+v", backend, resp) + } + } + for _, profile := range []string{"custom", "economy", "local"} { + resp := gin.H{} + addModelContextToResponse(resp, modelmeta.ContextInfo{Backend: modelmeta.BackendOMLX, ContextWindow: 65536}, 120000, 8192, profile) + if resp["context_profile"] != profile { + t.Fatalf("explicit profile changed: %+v", resp) + } + } + resp := gin.H{} + addModelContextToResponse(resp, modelmeta.ContextInfo{Backend: modelmeta.BackendOpenAICompatible, ContextWindow: 131072, Source: "openai_models_context_length"}, 120000, 8192, "local_auto") + if resp["context_profile"] != "" { + t.Fatalf("generic gateway was treated as local: %+v", resp) + } + resp = gin.H{} + addModelContextToResponse(resp, modelmeta.ContextInfo{Backend: modelmeta.BackendOllama, ContextWindow: 262144, RuntimeUnknown: true}, 120000, 8192, "auto") + if resp["effective_max_total_tokens"] != 19660 { + t.Fatalf("architecture limit treated as runtime limit: %+v", resp) + } +} + func TestAddModelContextToResponseDedupesWarnings(t *testing.T) { t.Parallel() resp := gin.H{} diff --git a/internal/handler/config_testopenai_headers_test.go b/internal/handler/config_testopenai_headers_test.go index fc4423dd..6b69cb16 100644 --- a/internal/handler/config_testopenai_headers_test.go +++ b/internal/handler/config_testopenai_headers_test.go @@ -13,6 +13,43 @@ import ( "cyberstrike-ai/internal/config" ) +func TestFirstOMLXConnectionProbeUsesDetectedLocalOutputLimit(t *testing.T) { + var completions int + mux := http.NewServeMux() + mux.HandleFunc("/v1/models", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"data":[{"id":"local-model","owned_by":"omlx","max_model_len":65536}]}`)) + }) + mux.HandleFunc("/v1/chat/completions", func(w http.ResponseWriter, r *http.Request) { + completions++ + var payload map[string]any + if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { + t.Error(err) + } + if payload["max_tokens"] != float64(5) || payload["max_completion_tokens"] != nil { + t.Errorf("first probe missed local output cap: %+v", payload) + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"id":"fixture","model":"local-model","choices":[{"message":{"role":"assistant","content":"Hi"}}]}`)) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + h := &ConfigHandler{config: &config.Config{}, logger: zap.NewNop()} + body, _ := json.Marshal(map[string]any{"provider": "openai_compatible", "base_url": srv.URL + "/v1", "api_key": "fixture", "model": "local-model"}) + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodPost, "/api/config/test-openai", strings.NewReader(string(body))) + c.Request.Header.Set("Content-Type", "application/json") + h.TestOpenAI(c) + var result map[string]any + if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil { + t.Fatal(err) + } + if result["success"] != true || result["context_backend"] != "omlx" || result["context_profile"] != "local_auto" || completions != 1 { + t.Fatalf("unexpected probe result: %s, completions=%d", w.Body.String(), completions) + } +} + // TestTestOpenAIForwardsCustomHeaders 校验「测试连接」与真实对话一样会带上渠道自定义请求头: // 静态头原样发送,%session_id% 用探测值填充,Authorization 仍按 api_key 生成。 func TestTestOpenAIForwardsCustomHeaders(t *testing.T) { diff --git a/internal/modelmeta/context.go b/internal/modelmeta/context.go index b69b1469..746c8fd0 100644 --- a/internal/modelmeta/context.go +++ b/internal/modelmeta/context.go @@ -17,6 +17,8 @@ const ( BackendOllama = "ollama" BackendLlamaCpp = "llamacpp" BackendLMStudio = "lmstudio" + BackendOMLX = "omlx" + BackendVLLM = "vllm" BackendOpenAICompatible = "openai_compatible" WarningOllamaV1IgnoresNumCtx = "ollama_v1_ignores_num_ctx" @@ -38,6 +40,16 @@ type ContextInfo struct { Warnings []string `json:"context_warnings,omitempty"` } +// IsLocalBackend requires a recognizable inference-server response. +func (info ContextInfo) IsLocalBackend() bool { + switch info.Backend { + case BackendOllama, BackendLlamaCpp, BackendLMStudio, BackendOMLX, BackendVLLM: + return true + default: + return false + } +} + // DetectContext probes the endpoint in local-backend-first order and returns the // most authoritative context window it can find. It never returns an error: a // failed probe is represented by an empty ContextWindow plus a warning. @@ -113,7 +125,7 @@ func detectOllama(ctx context.Context, client *http.Client, root, base, model, a var version struct { Version string `json:"version"` } - if status, err := probeJSON(ctx, client, http.MethodGet, root+"/api/version", apiKey, nil, &version); err != nil || status != http.StatusOK { + if status, err := probeJSON(ctx, client, http.MethodGet, root+"/api/version", apiKey, nil, &version); err != nil || status != http.StatusOK || strings.TrimSpace(version.Version) == "" { return ContextInfo{}, false } @@ -238,6 +250,9 @@ func detectLlamaCpp(ctx context.Context, client *http.Client, root, model, apiKe if n <= 0 { n = props.NCtx } + if n <= 0 && props.TotalSlots <= 0 { + return ContextInfo{}, false + } info := ContextInfo{Backend: BackendLlamaCpp, Loaded: true} if props.TotalSlots > 0 { info.RuntimeSlots = props.TotalSlots @@ -289,8 +304,8 @@ func detectLMStudio(ctx context.Context, client *http.Client, root, model, apiKe models = list.Models } chosen := pickLMModel(models, model) - if chosen == nil { - return ContextInfo{Backend: BackendLMStudio, Warnings: []string{WarningContextUnknown}}, true + if chosen == nil || (chosen.Type == "" && chosen.State == "" && chosen.LoadedContextLength <= 0 && len(chosen.LoadedInstances) == 0) { + continue } info := ContextInfo{Backend: BackendLMStudio} if chosen.LoadedContextLength > 0 { @@ -342,6 +357,7 @@ func detectOpenAICompatible(ctx context.Context, client *http.Client, base, mode var list struct { Data []struct { ID string `json:"id"` + OwnedBy string `json:"owned_by"` MaxModelLen int `json:"max_model_len"` ContextLength json.RawMessage `json:"context_length"` MaxContextLength int `json:"max_context_length"` @@ -364,6 +380,11 @@ func detectOpenAICompatible(ctx context.Context, client *http.Client, base, mode } if chosen >= 0 { m := list.Data[chosen] + // A compatible model list alone does not identify a local runtime. + switch strings.ToLower(strings.TrimSpace(m.OwnedBy)) { + case BackendOMLX, BackendVLLM: + info.Backend = strings.ToLower(strings.TrimSpace(m.OwnedBy)) + } switch { case m.MaxModelLen > 0: info.ContextWindow = m.MaxModelLen @@ -375,8 +396,16 @@ func detectOpenAICompatible(ctx context.Context, client *http.Client, base, mode info.ContextWindow = m.MaxContextLength info.Source = "openai_models_max_context_length" } + if info.Backend == BackendOMLX { + if runtime, ok := detectOMLXRuntime(ctx, client, base, m.ID, apiKey); ok { + return runtime + } + if info.ContextWindow > 0 { + info.Source = strings.Replace(info.Source, "openai_", "omlx_", 1) + } + } if info.ContextWindow > 0 { - info.Loaded = true + info.Loaded = info.Backend != BackendOMLX return info } } @@ -384,6 +413,27 @@ func detectOpenAICompatible(ctx context.Context, client *http.Client, base, mode return info } +func detectOMLXRuntime(ctx context.Context, client *http.Client, base, model, apiKey string) (ContextInfo, bool) { + var status struct { + Models []struct { + ID string `json:"id"` + Alias string `json:"model_alias"` + MaxContextWindow int `json:"max_context_window"` + Loaded bool `json:"loaded"` + } `json:"models"` + } + code, err := probeJSON(ctx, client, http.MethodGet, strings.TrimRight(base, "/")+"/models/status", apiKey, nil, &status) + if err != nil || code != http.StatusOK { + return ContextInfo{}, false + } + for _, m := range status.Models { + if (modelMatches(m.ID, model) || modelMatches(m.Alias, model)) && m.MaxContextWindow > 0 { + return ContextInfo{Backend: BackendOMLX, ContextWindow: m.MaxContextWindow, Source: "omlx_models_status", Loaded: m.Loaded}, true + } + } + return ContextInfo{}, false +} + func probeJSON(ctx context.Context, client *http.Client, method, target, apiKey string, body interface{}, out interface{}) (int, error) { reqCtx, cancel := context.WithTimeout(ctx, probeTimeout) defer cancel() diff --git a/internal/modelmeta/context_test.go b/internal/modelmeta/context_test.go index 20121a56..3a598523 100644 --- a/internal/modelmeta/context_test.go +++ b/internal/modelmeta/context_test.go @@ -201,6 +201,57 @@ func TestDetectContextVLLMModels(t *testing.T) { } } +func TestDetectContextOMLXAndVLLMIdentity(t *testing.T) { + for _, tc := range []struct { + name, owner, backend, source string + status, window int + }{ + {"omlx runtime alias", "omlx", BackendOMLX, "omlx_models_status", 200, 32768}, + {"omlx inference key", "omlx", BackendOMLX, "omlx_models_max_model_len", 403, 262144}, + {"vllm", "vllm", BackendVLLM, "openai_models_max_model_len", 404, 262144}, + {"gateway", "gateway", BackendOpenAICompatible, "openai_models_max_model_len", 404, 262144}, + } { + t.Run(tc.name, func(t *testing.T) { + statusCalls := 0 + mux := http.NewServeMux() + mux.HandleFunc("/edge/v1/models", func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("Authorization") != "Bearer fixture" { + t.Error("missing credential") + } + _ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{{"id": "alias", "owned_by": tc.owner, "max_model_len": 262144}}}) + }) + mux.HandleFunc("/edge/v1/models/status", func(w http.ResponseWriter, r *http.Request) { + statusCalls++ + if r.Method != http.MethodGet { + t.Error("probe must be read-only") + } + w.WriteHeader(tc.status) + _ = json.NewEncoder(w).Encode(map[string]any{"models": []map[string]any{{"id": "mlx-community/model", "model_alias": "alias", "max_context_window": 32768, "loaded": true}}}) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + info := DetectContext(context.Background(), srv.URL+"/edge/v1", "alias", "fixture", srv.Client()) + if info.Backend != tc.backend || info.ContextWindow != tc.window || info.Source != tc.source { + t.Fatalf("unexpected metadata: %+v", info) + } + if (statusCalls > 0) != (tc.owner == "omlx") || info.IsLocalBackend() != (tc.owner != "gateway") { + t.Fatalf("backend identity mismatch: %+v, status probes=%d", info, statusCalls) + } + }) + } +} + +func TestGenericGatewaySuccessResponsesDoNotIdentifyLocalBackend(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]any{{"id": "generic", "context_length": 65536}}}) + })) + defer srv.Close() + info := DetectContext(context.Background(), srv.URL+"/v1", "generic", "", srv.Client()) + if info.IsLocalBackend() || info.Backend != BackendOpenAICompatible || info.ContextWindow != 65536 { + t.Fatalf("generic JSON success misidentified: %+v", info) + } +} + func TestDetectContextOpenAISingleModelFallback(t *testing.T) { t.Parallel() mux := http.NewServeMux() diff --git a/web/static/i18n/en-US.json b/web/static/i18n/en-US.json index 7b0d950c..9284f510 100644 --- a/web/static/i18n/en-US.json +++ b/web/static/i18n/en-US.json @@ -3096,12 +3096,6 @@ "contextWindow": "Model Context Window (tokens)", "contextWindowPlaceholder": "131072", "contextWindowHint": "Native model window used to validate and clamp the budget. For local models, match the server num_ctx/ctx-size.", - "contextProfile": "Context Optimization Profile", - "contextProfileAuto": "Auto (input savings for DeepSeek)", - "contextProfileEconomy": "Save input tokens", - "contextProfileCustom": "Custom (use runtime settings)", - "contextProfileLocal": "Local model (32K-256K optimized)", - "contextProfileHint": "Input savings load tools on demand, compact JSON results and preview large results with access to the full output. The local profile also tightens context budgets.", "detectContext": "Auto-detect", "detectContextFillRequired": "Fill in Base URL and model first", "detectedContext": "Detected {tokens} tokens", diff --git a/web/static/i18n/ru-RU.json b/web/static/i18n/ru-RU.json index b063eb8d..3998bccd 100644 --- a/web/static/i18n/ru-RU.json +++ b/web/static/i18n/ru-RU.json @@ -3109,12 +3109,6 @@ "contextWindow": "Окно контекста модели (токены)", "contextWindowPlaceholder": "131072", "contextWindowHint": "Собственное окно модели для проверки и ограничения бюджета. Для локальных моделей укажите серверный num_ctx/ctx-size.", - "contextProfile": "Профиль оптимизации контекста", - "contextProfileAuto": "Авто (экономия для DeepSeek)", - "contextProfileEconomy": "Экономия входных токенов", - "contextProfileCustom": "Свой профиль (настройки среды)", - "contextProfileLocal": "Локальная модель (32K-256K)", - "contextProfileHint": "Экономия загружает инструменты по запросу, уплотняет JSON и показывает превью больших результатов с доступом к полному выводу. Локальный профиль также ограничивает контекст.", "detectContext": "Автоопределение", "detectContextFillRequired": "Сначала заполните Base URL и модель", "detectedContext": "Обнаружено {tokens} токенов", diff --git a/web/static/i18n/zh-CN.json b/web/static/i18n/zh-CN.json index f2e38aa3..c466c8ac 100644 --- a/web/static/i18n/zh-CN.json +++ b/web/static/i18n/zh-CN.json @@ -3084,12 +3084,6 @@ "contextWindow": "模型上下文窗口(Token)", "contextWindowPlaceholder": "131072", "contextWindowHint": "模型原生窗口;用于校验并收紧预算。本地模型请按服务端 num_ctx/ctx-size 填写。", - "contextProfile": "上下文优化档位", - "contextProfileAuto": "自动(DeepSeek 启用节省)", - "contextProfileEconomy": "节省输入", - "contextProfileCustom": "自定义(使用运行时配置)", - "contextProfileLocal": "本地模型(32K-256K 优化)", - "contextProfileHint": "节省输入按需加载工具、精简 JSON 回包,并为大结果提供可回读的预览。本地档位同时收紧上下文预算。", "detectContext": "自动检测", "detectContextFillRequired": "请先填写 Base URL 和模型", "detectedContext": "检测到 {tokens} tokens", diff --git a/web/static/js/settings-pi-resilience.test.cjs b/web/static/js/settings-pi-resilience.test.cjs index ad5f1ecf..8780efdd 100644 --- a/web/static/js/settings-pi-resilience.test.cjs +++ b/web/static/js/settings-pi-resilience.test.cjs @@ -2,6 +2,7 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); +const vm = require('node:vm'); const root = process.cwd(); const settings = fs.readFileSync(path.join(root, 'web/static/js/settings.js'), 'utf8'); @@ -66,3 +67,94 @@ test('切换或新增 AI 通道时会刷新推理线路下拉显示', () => { assert.match(settings, /syncSettingsCustomSelect\(profileEl\);/); assert.match(settings, /reasoning:\s*\{\s*mode:\s*'auto',\s*effort:\s*'',\s*profile:\s*'auto'/); }); + +test('隐藏上下文档位后保存和探测仍保留已有配置', async () => { + assert.doesNotMatch(template, /openai-context-profile|settingsBasic\.contextProfile/); + const formCode = settings.slice(settings.indexOf('function normalizeAIChannelId('), settings.indexOf('function writeAIChannelToMainForm(')); + const probeCode = settings.slice(settings.indexOf('async function detectAIContext('), settings.indexOf('// 保存工具配置(独立函数')); + const fields = { + 'openai-provider': 'openai_compatible', + 'openai-base-url': 'https://gateway.example/v1', + 'openai-api-key': 'fixture-key', + 'openai-model': 'deepseek-flash' + }; + for (const profile of [undefined, 'local', 'local_auto', 'economy', 'custom']) { + const requests = []; + const context = { + URL, + document: { getElementById: id => Object.hasOwn(fields, id) ? { value: fields[id] } : null }, + currentConfig: { ai: { channels: { main: { context_profile: profile, provider: fields['openai-provider'], base_url: fields['openai-base-url'], model: fields['openai-model'] } } } }, + selectedAIChannelId: 'main', + aiChannelProbeResults: {}, + window: {}, + settingsT: (_, fallback) => fallback, + syncSelectedAIChannelUI() {}, + updateAIChannelSelectOption() {}, + setConnectionTestResult() {}, + applyDetectedContext() {}, + apiFetch: async (url, options) => { + requests.push(JSON.parse(options.body)); + return { json: async () => ({ success: true, context_window: 131072 }) }; + } + }; + vm.createContext(context); + vm.runInContext(formCode + '\n' + probeCode, context); + const saved = context.readAIChannelFromMainForm('main'); + assert.equal(saved.context_profile, profile); + await context.detectAIContext(); + await context.testOpenAIConnection(); + assert.equal(requests.length, 2); + for (const request of requests) assert.equal(request.context_profile, profile || ''); + } +}); + +test('保存通道自动识别本地服务,切换服务清除自动判定', async () => { + const formCode = settings.slice(settings.indexOf('function normalizeAIChannelId('), settings.indexOf('function writeAIChannelToMainForm(')); + const detectionCode = settings.slice(settings.indexOf('async function detectChannelContextForSave('), settings.indexOf('async function persistAIConfigOnlyToServer(')); + const fields = { 'openai-provider': 'openai_compatible', 'openai-base-url': 'http://127.0.0.1:8000/v1', 'openai-model': 'local-model' }; + let probes = 0; + let result = { success: true, context_profile: 'local_auto', context_window: 65536 }; + const context = { + URL, AbortSignal, + document: { getElementById: id => Object.hasOwn(fields, id) ? { value: fields[id] } : null }, + currentConfig: { ai: { channels: {} } }, + apiFetch: async () => { + probes++; + return { ok: true, json: async () => result }; + } + }; + vm.createContext(context); + vm.runInContext(formCode + '\n' + detectionCode, context); + const channel = context.readAIChannelFromMainForm('main'); + await context.detectChannelContextForSave('main', channel); + assert.equal(channel.context_profile, 'local_auto'); + assert.equal(channel.context_window, 65536); + assert.equal(probes, 1); + context.currentConfig.ai.channels.main = channel; + fields['openai-base-url'] = 'https://gateway.example/v1'; + const changed = context.readAIChannelFromMainForm('main'); + assert.equal(changed.context_profile, ''); + + for (const profile of ['local', 'custom', 'economy']) { + const manual = { ...channel, context_profile: profile }; + await context.detectChannelContextForSave('main', manual); + assert.equal(manual.context_profile, profile); + } + assert.equal(probes, 1); + const manualWindow = { ...changed, context_window: 16384 }; + await context.detectChannelContextForSave('main', manualWindow); + assert.equal(manualWindow.context_window, 16384); + const oversizedWindow = { ...changed, context_window: 131072 }; + await context.detectChannelContextForSave('main', oversizedWindow); + assert.equal(oversizedWindow.context_window, 65536); + result = { success: true, context_profile: 'local_auto', context_window: 262144, context_runtime_unknown: true }; + const unknownRuntime = { ...changed, context_window: 0 }; + await context.detectChannelContextForSave('main', unknownRuntime); + assert.equal(unknownRuntime.context_profile, 'local_auto'); + assert.equal(unknownRuntime.context_window, 0); + + context.apiFetch = async () => { throw new Error('offline'); }; + const offline = { ...changed }; + await context.detectChannelContextForSave('main', offline); + assert.equal(offline.context_profile, ''); +}); diff --git a/web/static/js/settings.js b/web/static/js/settings.js index 70b7c29e..5c472a8d 100644 --- a/web/static/js/settings.js +++ b/web/static/js/settings.js @@ -2026,6 +2026,7 @@ async function applySettings() { currentConfig.ai = ensureAIConfigShape(currentConfig); const activeChannelId = normalizeAIChannelId(selectedAIChannelId || currentConfig.ai.default_channel || 'default'); currentConfig.ai.channels[activeChannelId] = readAIChannelFromMainForm(activeChannelId); + await detectChannelContextForSave(activeChannelId, currentConfig.ai.channels[activeChannelId]); currentConfig.ai.default_channel = activeChannelId; currentConfig.ai = normalizeAIConfigProviderProfiles(currentConfig.ai); renderAIChannelSelect(); @@ -2651,7 +2652,7 @@ function formatCustomHeaders(headers) { function readAIChannelFromMainForm(id) { const prev = currentConfig?.ai?.channels?.[id] || {}; const maxCompletionTokens = parseInt(document.getElementById('openai-max-completion-tokens')?.value, 10) || 32768; - return normalizeAIChannelProviderProfile({ + const channel = normalizeAIChannelProviderProfile({ ...prev, name: (document.getElementById('ai-channel-name')?.value || '').trim() || prev.name || id, provider: document.getElementById('openai-provider')?.value || 'openai', @@ -2662,7 +2663,6 @@ function readAIChannelFromMainForm(id) { max_completion_tokens: maxCompletionTokens, headers: parseCustomHeadersInput(), context_window: parseInt(document.getElementById('openai-context-window')?.value, 10) || 0, - context_profile: document.getElementById('openai-context-profile')?.value || '', reasoning: { ...(prev.reasoning || {}), mode: document.getElementById('openai-reasoning-mode')?.value || 'auto', @@ -2671,6 +2671,10 @@ function readAIChannelFromMainForm(id) { allow_client_reasoning: document.getElementById('openai-reasoning-allow-client')?.checked !== false } }); + if (channel.context_profile === 'local_auto' && ['provider', 'base_url', 'model'].some(key => channel[key] !== prev[key])) { + channel.context_profile = ''; + } + return channel; } function writeAIChannelToMainForm(id) { @@ -2699,8 +2703,6 @@ function writeAIChannelToMainForm(id) { if (customHeadersEl) customHeadersEl.value = formatCustomHeaders(ch.headers); const contextWindowEl = document.getElementById('openai-context-window'); if (contextWindowEl) contextWindowEl.value = ch.context_window || ''; - const contextProfileEl = document.getElementById('openai-context-profile'); - if (contextProfileEl) contextProfileEl.value = ['auto', 'economy', 'custom', 'local'].includes(String(ch.context_profile || '').toLowerCase()) ? String(ch.context_profile).toLowerCase() : 'auto'; const r = ch.reasoning || {}; const modeEl = document.getElementById('openai-reasoning-mode'); if (modeEl) { @@ -2809,8 +2811,7 @@ function bindAIChannelEditorPreviewSync() { 'openai-custom-headers', 'openai-max-total-tokens', 'openai-max-completion-tokens', - 'openai-context-window', - 'openai-context-profile' + 'openai-context-window' ]; ids.forEach((fieldId) => { const el = document.getElementById(fieldId); @@ -3039,6 +3040,7 @@ async function persistAIChannelsToServer(successMessage, options = {}) { renderAIChannelSelect(); showAIChannelSaveHint(settingsT('settingsBasic.aiChannelSaving', '正在保存通道...'), true); try { + await detectChannelContextForSave(id, channelPayload); const shouldMergeLatest = options.mergeLatest !== false; const latestResponse = shouldMergeLatest ? await apiFetch('/api/config') : null; if (latestResponse && latestResponse.ok) { @@ -3078,6 +3080,36 @@ async function persistAIChannelsToServer(successMessage, options = {}) { } } +async function detectChannelContextForSave(id, channel) { + if (!['', 'auto', 'local_auto'].includes(channel.context_profile || '') || ['claude', 'anthropic'].includes(channel.provider)) return; + // These public services already have a known policy. Unknown endpoints + // are identified by metadata, including local services behind proxies. + if (['api.deepseek.com', 'api.openai.com', 'api.anthropic.com'].includes(aiChannelBaseURLHost(channel.base_url))) return; + try { + const response = await apiFetch('/api/config/detect-context', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + signal: AbortSignal.timeout(9000), + body: JSON.stringify({ ...channel, channel_id: id }) + }); + const result = await response.json(); + if (response.ok && result.success) applyChannelContextDetection(channel, result); + } catch (_) { + // Metadata discovery is best-effort. Saving a working channel is valid + // when the server is offline or does not publish runtime metadata. + } +} + +function applyChannelContextDetection(channel, result) { + if (!channel || !result) return; + if (['', 'auto', 'local_auto'].includes(channel.context_profile || '') && ['', 'local_auto'].includes(result.context_profile)) { + channel.context_profile = result.context_profile; + } + if (result.context_window > 0 && !result.context_runtime_unknown && + (!channel.context_window || (channel.context_profile === 'local_auto' && channel.context_window > result.context_window))) { + channel.context_window = result.context_window; + } +} + async function persistAIConfigOnlyToServer(successMessage) { if (typeof requirePermission === 'function' && !requirePermission('config:write')) return false; if (!currentConfig) return false; @@ -3263,6 +3295,7 @@ async function probeSelectedAIChannels() { }); const result = await response.json().catch(() => ({})); if (response.ok && result.success) { + applyChannelContextDetection(ch, result); okCount += 1; const latency = result.latency_ms ? ` ${result.latency_ms}ms` : ''; const context = result.context_window ? ` · ${result.context_window} tokens` : ''; @@ -3954,11 +3987,15 @@ function formatDetectedContext(result) { } function applyDetectedContext(result, force) { - if (!result || !result.context_window) return; + if (!result) return; + const channel = currentConfig?.ai?.channels?.[selectedAIChannelId]; + applyChannelContextDetection(channel, result); + if (!result.context_window) return; const input = document.getElementById('openai-context-window'); // 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())) { + if (input && !result.context_runtime_unknown && (force || !String(input.value || '').trim() || + (channel?.context_profile === 'local_auto' && Number(input.value) > result.context_window))) { input.value = String(result.context_window); } const resultEl = document.getElementById('detect-context-result'); @@ -3976,6 +4013,9 @@ async function detectAIContext() { const apiKey = document.getElementById('openai-api-key')?.value.trim() || ''; const model = document.getElementById('openai-model')?.value.trim() || ''; const channelId = normalizeAIChannelId(selectedAIChannelId || currentConfig?.ai?.default_channel || 'default'); + const isCurrentRequest = () => selectedAIChannelId === channelId && + document.getElementById('openai-base-url')?.value.trim() === baseUrl && + document.getElementById('openai-model')?.value.trim() === model; if (!baseUrl || !model) { if (resultEl) { resultEl.textContent = settingsT('settingsBasic.detectContextFillRequired', '请先填写 Base URL 和模型'); @@ -4004,13 +4044,13 @@ async function detectAIContext() { headers: parseCustomHeadersInput(), 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 || '' + context_profile: currentConfig?.ai?.channels?.[channelId]?.context_profile || '' }) }); const result = await response.json().catch(() => ({})); - if (result.success && result.context_window) { - applyDetectedContext(result, true); - } else { + if (!isCurrentRequest()) return; + if (result.success) applyDetectedContext(result, true); + if (!result.success || !result.context_window) { const message = result.error || contextWarningText('context_window_unknown'); if (resultEl) { resultEl.textContent = formatConnectionTestError(message).message; @@ -4039,7 +4079,9 @@ async function testOpenAIConnection() { const apiKey = document.getElementById('openai-api-key').value.trim(); const model = document.getElementById('openai-model').value.trim(); const channelId = normalizeAIChannelId(selectedAIChannelId || currentConfig?.ai?.default_channel || 'default'); - const isTestingSameChannel = () => normalizeAIChannelId(selectedAIChannelId || currentConfig?.ai?.default_channel || 'default') === channelId; + const isTestingSameChannel = () => normalizeAIChannelId(selectedAIChannelId || currentConfig?.ai?.default_channel || 'default') === channelId && + document.getElementById('openai-base-url')?.value.trim() === baseUrl && + document.getElementById('openai-model')?.value.trim() === model; if (!baseUrl || !apiKey || !model) { const message = typeof window.t === 'function' ? window.t('settingsBasic.testFillRequired') : '请先填写 Base URL、API Key 和模型'; @@ -4075,7 +4117,7 @@ async function testOpenAIConnection() { headers: currentConfig?.ai?.channels?.[channelId]?.headers || {}, 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 || '' + context_profile: currentConfig?.ai?.channels?.[channelId]?.context_profile || '' }) }); diff --git a/web/templates/index.html b/web/templates/index.html index 75c4ea5d..c2d01156 100644 --- a/web/templates/index.html +++ b/web/templates/index.html @@ -3785,16 +3785,6 @@ 模型原生窗口;用于校验并收紧预算。本地模型请按服务端 num_ctx/ctx-size 填写。 -