From d0da1692091e634231ba73b75671b031effe5352 Mon Sep 17 00:00:00 2001 From: Sycun <165354365+Sycun@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:54:11 +0800 Subject: [PATCH] refactor(config): align context optimization with upstream Pi policy --- CHANGELOG.md | 4 +- config.example.yaml | 24 +--- docs/en-US/configuration.md | 38 ++--- docs/zh-CN/configuration.md | 49 ++----- internal/attackchain/builder.go | 28 +++- internal/config/config.go | 14 -- internal/config/context_profile.go | 122 ---------------- internal/config/context_profile_test.go | 179 ++---------------------- internal/handler/agent.go | 2 +- internal/handler/config_context_test.go | 25 ++++ internal/handler/fofa.go | 5 +- internal/handler/hitl_audit_agent.go | 5 +- internal/handler/openapi.go | 79 ++--------- internal/knowledge/wire_retriever.go | 27 ++-- internal/workflow/draft_generator.go | 9 +- web/static/css/style.css | 8 -- 16 files changed, 118 insertions(+), 500 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 96a8693d..eb47f4ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ ### Added +- 个人版上下文优化统一采用 #399 的 Pi 自动策略,清理 #367 遗留的摘要、消息和工具输出预算覆盖及辅助请求适配。DeepSeek 输入节省、本地服务窗口检测和已有通道配置兼容继续由自动策略处理。 + - 默认 Agent 运行时迁移为 Pi 1.5.2:Go 工具网关继续处理角色、审批、监控与证据;聊天、子代理及深度评估的模型提案接入 Pi。新增按源码指纹发布的 Node Worker、流式协议、会话恢复和原生工具检索。部署需 Node.js >=22.19;已删除 Eino 内核、模型适配、桥接和全部依赖,运行时仅支持 Pi。 - Workflow 改用原生 DAG 与版本化检查点,知识库改用自身文档、切分、Embedding 和检索组件。旧 Eino Workflow 检查点无法由新版直接恢复,升级前需完成或导出旧任务,详见 [Pi 迁移说明](docs/zh-CN/pi-runtime.md)。 - 个人仓库正式命名为 `Sycun/CyberStrikeAI`,原上游贡献 fork 改为 `Sycun/CyberStrikeAI-upstream-fork`。新增任务接单、阶段汇报与主动请示的设计调研文档(尚未作为产品功能上线)。 @@ -18,8 +20,6 @@ - 漏洞列表的单条下载按钮新增格式选择弹窗,支持 Markdown 与 Word(.docx),Word 下载复用漏洞读取权限并仅包含所选漏洞(#365)。 - 新增单代理与多代理异步对话 API:接收后返回任务回执,客户端断线不停止执行;支持按用户隔离的幂等提交、持久状态与结果查询、显式取消以及服务重启后的中断状态。同步接口保持兼容。 -- 本地大模型上下文优化:AI 通道新增 `context_window` 与 `context_profile: local`,支持从 Ollama / llama.cpp / LM Studio / vLLM 自动探测运行时窗口,按窗口收紧压缩预算与工具输出阈值,并让内置工具进入 `tool_search` 动态池;local 档位自动改用 `max_tokens` 兼容本地端点。 -- 本地上下文增强:检测结果展示按档位折算后的有效预算,探测支持反向代理子路径;local 档位为 token 估算保留 10% 余量,补充 llama.cpp / LM Studio / vLLM 的超窗报错识别并触发激进压缩重试;攻击链、FOFA、工作流、HITL 等旁路调用同样按档位切换输出字段,并合并通道级 `reasoning.extra_request_fields`。 - 启动时以统一最新 SQLite 定义自动检查全部项目管理表,缺表建表、缺字段补字段,无需维护逐字段迁移列表;保留已有数据和额外表/字段,结构补齐失败回滚并阻止启动。HITL 与通知表纳入统一初始化,历史漏洞外键迁移保留额外列、索引、触发器及依赖记录。 diff --git a/config.example.yaml b/config.example.yaml index 746236e1..8fe437f1 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -125,8 +125,8 @@ ai: # HITL 审计仅在未显式配置 provider/base_url/api_key 时继承主渠道 headers; # 独立审计身份如需请求头,请在 hitl.audit_model.headers 中单独配置。 # 空 headers 与未配置等价;所有自定义头值在设置接口中均按敏感值脱敏。 - context_window: 262144 # 模型原生上下文窗口(token);0/省略=未知。检测到窗口后,预算会被自动收紧 - context_profile: auto # auto=DeepSeek 自动节省输入;economy=显式启用;custom=按运行时配置;local=本地模型预算档位 + context_window: 0 # 0=未知;保存通道时按服务元数据自动检测 + context_profile: auto # 默认自动优化;识别本地服务后保存为 local_auto;custom 可使用手动运行时参数 # Pi 路径模型推理:DeepSeek/OpenAI 为 thinking / reasoning_effort;Claude 4.6+ 为 adaptive + output_config.effort(仅显式配置 effort 时下发);3.7 为 enabled+budget_tokens:10000(文档示例),effort 不映射,自定义预算用 extra_request_fields reasoning: mode: on # auto | on | off;off:OpenAI/Claude 不附加推理字段,DeepSeek 发送 thinking.type=disabled(其默认开启思考) @@ -142,24 +142,6 @@ ai: # model: qwen-plus # max_total_tokens: 120000 # max_completion_tokens: 32768 - # 本地模型示例(Ollama / llama.cpp / vLLM / LM Studio 均走 OpenAI 兼容端点) - # local-qwen: - # name: Local Qwen - # provider: openai_compatible - # base_url: http://127.0.0.1:11434/v1 - # api_key: ollama - # model: qwen3.5:9b - # max_total_tokens: 65536 # 运行时会再被 context_window * 60% 收紧 - # max_completion_tokens: 8192 - # context_window: 131072 # 建议用页面「自动检测」填入实际 runtime 窗口 - # context_profile: local - # # Ollama 的 /v1 接口忽略 num_ctx:请同时设置 OLLAMA_CONTEXT_LENGTH=131072 或 Modelfile PARAMETER num_ctx; - # # 否则 Ollama 会按显存使用 4K/32K/256K 默认值,并从开头截断系统提示词。 - # reasoning: - # mode: off - # extra_request_fields: - # chat_template_kwargs: - # enable_thinking: false # Qwen3.5 等思考模型在 agent 工具循环中建议关闭思考 # 视觉分析(analyze_image MCP 工具;图片仅在单次 VL 调用中出现,Agent 上下文只保留文字摘要) vision: enabled: false # true 且 model 非空时注册 analyze_image @@ -389,7 +371,7 @@ multi_agent: tool_search_min_tools: 20 tool_search_always_visible: 12 tool_search_always_visible_tools: [get_tool_execution, wait_tool_execution, cancel_tool_execution, search_knowledge_base] - tool_search_include_builtins: true # local context profile automatically narrows visibility + tool_search_include_builtins: true # true:后端内置工具始终常驻,绕过 tool_search plantask_enable: true plantask_rel_dir: .pi/plantask reduction_enable: true diff --git a/docs/en-US/configuration.md b/docs/en-US/configuration.md index 932f6f1d..bd4ae6de 100644 --- a/docs/en-US/configuration.md +++ b/docs/en-US/configuration.md @@ -70,34 +70,24 @@ 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 Pi'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. 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` | 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. | +| `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. | +| `context_window` | Runtime context window, or 0 when unknown. Channel saves can fill the detected value and retain a smaller configured window. | +| `context_profile` | Background policy, default `auto`. Recognized local backends use `local_auto`. Configuration files also accept manual `local`, explicit `economy` savings, and `custom` runtime settings. | | `reasoning` | Default reasoning fields for the channel. Gateway support varies; try `mode: off` first when a provider rejects requests. | -### Local Model Context (32K–256K) - -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. **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**: - - 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.runtime.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`. +### Automatic input savings + +DeepSeek endpoints, explicit DeepSeek reasoning profiles and model names containing DeepSeek enable input savings automatically. With at least 16 tools, discovery declares six catalog entries, core tools and explicitly pinned tools. JSON tool results lose formatting whitespace. When an authorized local reader is available, results over 8,000 bytes become previews backed by the full output. Provider-reported reasoning tokens are shown separately within completion usage. + +Channel saves and connection tests probe metadata from Ollama, llama.cpp, LM Studio, vLLM and oMLX. oMLX is identified by `owned_by: omlx`. Its matching model or alias in `/v1/models/status` supplies the preferred window, with the model list as a fallback when status access is unavailable. Generic compatible responses and private IP addresses alone do not select local optimization. Failed probes allow the channel to be saved. + +The local input budget is capped at 60% of the window and 131,072 tokens, with output room reserved. An unknown window uses 32,768 tokens. Local policies tighten tool discovery and result limits, and use the `max_tokens` output field. New channels reporting only an architecture maximum retain an unknown runtime window. Changing a model or endpoint clears the previous automatic classification. These policies are applied in the background. + +Compare complete tasks using input, cache hits, output and call counts to measure savings. Tool discovery and evidence readback may add calls. Explicit configuration-file overrides remain supported. + ### Disabling reasoning by provider and model Use `reasoning.mode: off` (or **Reasoning → Off** in chat) to disable reasoning. The request format depends on the channel: diff --git a/docs/zh-CN/configuration.md b/docs/zh-CN/configuration.md index a7418984..070b6294 100644 --- a/docs/zh-CN/configuration.md +++ b/docs/zh-CN/configuration.md @@ -71,12 +71,22 @@ ai: | `name` | Web UI 展示名。留空时使用通道 ID。 | | `provider` | `openai_compatible` 或 `claude`。`openai_compatible` 会在运行时映射为 `openai`;`claude` 使用 Pi 原生 Anthropic Messages API。 | | `base_url/api_key/model` | 必填。Base URL 通常需要包含版本路径,如 OpenAI/兼容网关的 `/v1`。 | -| `max_total_tokens` | 上下文压缩、攻击链构建、多代理摘要等共用的总预算。已知 `context_window` 时会收紧到“窗口 − 输出预留”。 | -| `max_completion_tokens` | 单次模型输出上限;未填时使用默认值,并会被压到已知/假定窗口的一半以内。 | -| `context_window` | 模型原生上下文窗口(token)。填写后运行时会按窗口收紧 `max_total_tokens`;0/省略表示未知。 | -| `context_profile` | 后台配置项,页面自动处理。`auto`(默认)通过 DeepSeek 官方地址、推理线路或模型名启用节省输入。保存通道时识别到本地推理服务会记录 `local_auto` 并应用本地预算。配置文件兼容 `economy`、`custom` 和手动 `local`。 | +| `max_total_tokens` | 上下文压缩、攻击链构建、多代理摘要等共用的总预算。 | +| `max_completion_tokens` | 单次模型输出上限;未填时使用默认值。 | +| `context_window` | 运行时上下文窗口,0 表示未知。保存通道时可自动填入服务报告的窗口,已填写的更小窗口优先。 | +| `context_profile` | 后台策略,默认 `auto`。识别本地服务后记录 `local_auto`。配置文件支持手动 `local`、显式节省 `economy` 和使用运行时参数的 `custom`。 | | `reasoning` | 该通道的默认推理扩展字段。不同网关支持差异较大,异常时先尝试 `mode: off`。 | +### 自动输入优化 + +DeepSeek 官方地址、明确的 DeepSeek 推理线路或包含 DeepSeek 的模型名会自动启用输入节省。达到 16 个工具时使用按需发现,默认常驻前 6 个工具、核心工具及显式常驻清单。JSON 回包精简格式空白。有授权的本地读取工具时,超过 8,000 字节的结果保存全文并返回可回读的预览。推理 Token 单列统计且计入输出总量。 + +保存通道和测试连接会探测 Ollama、llama.cpp、LM Studio、vLLM 和 oMLX 的元数据。oMLX 通过 `owned_by: omlx` 识别,优先读取 `/v1/models/status` 的匹配模型或别名窗口,权限不足时回退到模型列表。普通兼容响应和内网 IP 本身不足以触发本地策略。探测失败可继续保存。 + +本地输入预算取窗口的 60%,上限 131,072 Token,并预留输出空间。窗口未知时使用 32,768 的保守窗口。工具发现和回包上限按本地窗口收紧,输出字段使用 `max_tokens`。模型只报告架构上限时,新通道保留窗口未知状态。切换模型或服务会清除旧的自动判定。页面在后台应用这些策略。 + +验证成本时,应比较完整任务的输入、缓存命中、输出及调用次数。工具搜索和分段回读可能增加调用。已有配置文件的显式覆盖继续生效。 + ### 按提供商和模型关闭推理 使用 `reasoning.mode: off`,或在对话中选择“推理 → 关闭”。实际请求参数按通道区分: @@ -89,37 +99,6 @@ GPT-5.6 和 GPT-6 Sol/Luna 在 Chat Completions 中使用函数工具时,应 `allow_client_reasoning: false` 时忽略对话或请求的推理覆盖,按通道设置执行。 -### DeepSeek 输入优化 - -升级后,后台默认通过 `api.deepseek.com`、`deepseek` / `deepseek_compat` 推理线路或包含 `deepseek`(大小写不敏感)的模型名识别通道,自动启用以下规则。用户配置模型后即可使用。 - -- 工具数达到 16 时使用 Pi 原生 `tool_search`,默认常驻前 6 个工具和会话、执行控制、读取文件等核心工具。配置的 `tool_search_always_visible_tools` 继续作为常驻清单,其他内置工具按需发现和调用。 -- 有本地文件读取权限时,超过 8,000 字节的工具结果保存全文并返回首尾预览,模型可用 `read_file` 按行读取中间证据。更小的已配置阈值优先,落盘失败时返回完整内容。 -- 发送给模型的 JSON 工具回包精简格式空白,保留字符串、数字原文和字段顺序。已有会话中的 JSON 工具回包也会在请求时精简,原始会话记录保留完整文本。 - -输出上限和推理强度由通道与对话设置决定。工具检索和分段回读会增加必要调用,收益随工具目录和任务变化。已有配置文件中的档位覆盖继续生效,保存页面设置时会保留它们。 - -### 本地模型(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. **自动应用本地预算**。识别到本地服务后,预算按窗口 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 与前缀缓存**: - - 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.runtime.model_failover_channels` 只切换模型端点,预算仍按主通道计算;请让 failover 通道的可用窗口不小于主通道,否则可能依赖超窗压缩/重试。 - 对话页的“AI 通道”下拉框会读取已保存通道。请求体中的 `aiChannelId` 非空时仅对本次/本会话运行配置生效,不会把 API Key 发送给模型;为空时跟随 `ai.default_channel`。 常用操作: diff --git a/internal/attackchain/builder.go b/internal/attackchain/builder.go index f79120a1..c8fd252c 100644 --- a/internal/attackchain/builder.go +++ b/internal/attackchain/builder.go @@ -52,10 +52,25 @@ func NewBuilder(db *database.DB, openAIConfig *config.OpenAIConfig, logger *zap. } httpClient := &http.Client{Timeout: 5 * time.Minute, Transport: transport} - // 统一走通道的有效预算:已按 context_window / context_profile 收紧。 - maxTokens := 100000 - if openAIConfig != nil { - maxTokens = openAIConfig.EffectiveMaxTotalTokens() + // 优先使用配置文件中的统一 Token 上限(config.yaml -> openai.max_total_tokens) + maxTokens := 0 + if openAIConfig != nil && openAIConfig.MaxTotalTokens > 0 { + maxTokens = openAIConfig.MaxTotalTokens + } else if openAIConfig != nil { + // 如果未显式配置 max_total_tokens,则根据模型设置一个合理的默认值 + model := strings.ToLower(openAIConfig.Model) + if strings.Contains(model, "gpt-4") { + maxTokens = 128000 // gpt-4通常支持128k + } else if strings.Contains(model, "gpt-3.5") { + maxTokens = 16000 // gpt-3.5-turbo通常支持16k + } else if strings.Contains(model, "deepseek") { + maxTokens = 131072 // deepseek-chat通常支持131k + } else { + maxTokens = 100000 // 兜底默认值 + } + } else { + // 没有 OpenAI 配置时使用兜底值,避免为 0 + maxTokens = 100000 } return &Builder{ @@ -882,10 +897,9 @@ func (b *Builder) callAIForChainGeneration(ctx context.Context, prompt string) ( "content": prompt, }, }, - "temperature": 0.3, - b.openAIConfig.OutputLimitField(): attackChainMaxCompletionTokens(b.maxTokens), + "temperature": 0.3, + "max_completion_tokens": attackChainMaxCompletionTokens(b.maxTokens), } - config.ApplyExtraRequestFields(requestBody, b.openAIConfig.Reasoning.ExtraRequestFields) var apiResponse struct { Choices []struct { diff --git a/internal/config/config.go b/internal/config/config.go index 85518c74..26cfb4e0 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -962,20 +962,6 @@ func (c OpenAIReasoningConfig) ModeEffective() string { return m } -// ApplyExtraRequestFields merges admin-provided root JSON fields into a -// Chat Completions payload. Existing fields win, matching the Agent path. -func ApplyExtraRequestFields(payload map[string]interface{}, fields map[string]interface{}) { - if payload == nil || len(fields) == 0 { - return - } - for key, value := range fields { - if _, exists := payload[key]; exists { - continue - } - payload[key] = value - } -} - // ProfileEffective returns auto when empty. func (c OpenAIReasoningConfig) ProfileEffective() string { p := strings.ToLower(strings.TrimSpace(c.Profile)) diff --git a/internal/config/context_profile.go b/internal/config/context_profile.go index b58ff37f..2ebd5df3 100644 --- a/internal/config/context_profile.go +++ b/internal/config/context_profile.go @@ -13,9 +13,6 @@ const ( LocalContextBudgetCap = 131072 // MinLocalContextWindow 以下不建议运行带工具的 agent。 MinLocalContextWindow = 16384 - // LocalTokenEstimateSafetyPercent 是 local 档位对 token 估算的保守放大比例。 - // 本地 tokenizer 与 tiktoken 不一致(CJK 尤甚),留出余量避免踩到运行时窗口。 - LocalTokenEstimateSafetyPercent = 110 ContextWarningLocalWindowUnknown = "local_context_window_unknown" ContextWarningLocalWindowSmall = "local_context_window_small" @@ -53,14 +50,6 @@ func (c OpenAIConfig) IsLocalContextProfile() bool { return profile == "local" || profile == "local_auto" } -// TokenEstimateSafetyPercent 供 token 计数器使用:local 档位放大估算,auto 保持原值。 -func (c OpenAIConfig) TokenEstimateSafetyPercent() int { - if c.IsLocalContextProfile() { - return LocalTokenEstimateSafetyPercent - } - return 100 -} - // OutputLimitField 返回输出上限字段名。本地端点普遍只认旧字段 max_tokens。 func (c OpenAIConfig) OutputLimitField() string { if c.IsLocalContextProfile() { @@ -155,17 +144,6 @@ func (c OpenAIConfig) ContextBudgetWarnings() []string { return out } -// WithEffectiveContextBudget 返回运行期副本:预算与 local 档位中间件参数都在这里收口。 -func (c *Config) WithEffectiveContextBudget() *Config { - if c == nil { - return nil - } - out := *c - out.OpenAI.MaxTotalTokens = c.OpenAI.EffectiveMaxTotalTokens() - out.MultiAgent.Runtime = EffectiveRuntimeForChannel(c.MultiAgent.Runtime, c.OpenAI) - return &out -} - // EffectiveRuntimeForChannel applies input-saving or local-model limits to a // runtime copy. Explicit custom profiles use the configured runtime settings. func EffectiveRuntimeForChannel(mw AgentTuningConfig, oa OpenAIConfig) AgentTuningConfig { @@ -184,51 +162,13 @@ func EffectiveRuntimeForChannel(mw AgentTuningConfig, oa OpenAIConfig) AgentTuni return mw } window := oa.EffectiveContextWindow() - budget := oa.EffectiveMaxTotalTokens() out := mw - triggerRatio := mw.SummarizationTriggerRatioEffective() - if triggerRatio > 0.85 { - triggerRatio = 0.85 - } - out.SummarizationTriggerRatio = triggerRatio - - out.SummarizationOutputReserveTokens = tightenInt( - mw.SummarizationOutputReserveTokensEffective(), - localSummaryOutputReserve(window, oa.MaxCompletionTokensEffective()), - ) out.ReductionMaxLengthForTrunc = tightenInt( mw.ReductionMaxLengthForTruncEffective(), localToolTruncBytes(window), ) - out.ReductionMaxTokensForClear = tightenInt( - mw.ReductionMaxTokensForClearEffective(), - localToolClearTokens(budget), - ) out.ReductionEnable = true - out.ReductionSubAgents = true - - out.SummarizationUserIntentLedgerMaxRunes = tightenInt( - mw.SummarizationUserIntentLedgerMaxRunesEffective(), - localLedgerRunes(budget), - ) - out.SummarizationUserIntentLedgerEntryMaxRunes = tightenInt( - mw.SummarizationUserIntentLedgerEntryMaxRunesEffective(), - localLedgerEntryRunes(out.SummarizationUserIntentLedgerMaxRunes), - ) - - out.LatestUserMessageMaxRunes = tightenInt( - mw.LatestUserMessageMaxRunesEffective(), - localLatestUserRunes(budget), - ) - out.LatestUserMessageHeadRunes = tightenInt( - mw.LatestUserMessageHeadRunesEffective(), - out.LatestUserMessageMaxRunes/2, - ) - out.LatestUserMessageTailRunes = tightenInt( - mw.LatestUserMessageTailRunesEffective(), - out.LatestUserMessageMaxRunes-out.LatestUserMessageHeadRunes, - ) out.ToolSearchEnable = true if mw.ToolSearchMinTools <= 0 || mw.ToolSearchMinTools > 8 { @@ -241,10 +181,6 @@ func EffectiveRuntimeForChannel(mw AgentTuningConfig, oa OpenAIConfig) AgentTuni includeBuiltins := false out.ToolSearchIncludeBuiltins = &includeBuiltins - out.PlanExecuteMaxStepResultRunes = tightenInt( - mw.PlanExecuteMaxStepResultRunesEffective(), - 2000, - ) return out } @@ -258,20 +194,6 @@ func tightenInt(current, ceil int) int { return current } -func localSummaryOutputReserve(window, maxCompletion int) int { - reserve := window / 32 - if reserve < 2048 { - reserve = 2048 - } - if reserve > 8192 { - reserve = 8192 - } - if maxCompletion > 0 && reserve > maxCompletion { - reserve = maxCompletion - } - return reserve -} - func localToolTruncBytes(window int) int { bytes := window / 6 if bytes < 8192 { @@ -286,50 +208,6 @@ func localToolTruncBytes(window int) int { return bytes } -func localToolClearTokens(budget int) int { - tokens := budget * 35 / 100 - if tokens < 4096 { - tokens = 4096 - } - if budget > 0 && tokens > budget { - tokens = budget - } - return tokens -} - -func localLedgerRunes(budget int) int { - runes := budget * 2 - if runes > DefaultSummarizationUserIntentLedgerMaxRunes { - runes = DefaultSummarizationUserIntentLedgerMaxRunes - } - if runes < 4096 { - runes = 4096 - } - return runes -} - -func localLedgerEntryRunes(ledgerMax int) int { - runes := ledgerMax / 6 - if runes > DefaultSummarizationUserIntentLedgerEntryMaxRunes { - runes = DefaultSummarizationUserIntentLedgerEntryMaxRunes - } - if runes < 1024 { - runes = 1024 - } - return runes -} - -func localLatestUserRunes(budget int) int { - runes := budget * 2 - if runes > DefaultLatestUserMessageMaxRunes { - runes = DefaultLatestUserMessageMaxRunes - } - if runes < 4096 { - runes = 4096 - } - return runes -} - // localCoreToolNames 是本地小窗口下值得常驻的工具;其余交给 tool_search 按需解锁。 var localCoreToolNames = map[string]struct{}{ "read_file": {}, diff --git a/internal/config/context_profile_test.go b/internal/config/context_profile_test.go index 46b35182..aed34204 100644 --- a/internal/config/context_profile_test.go +++ b/internal/config/context_profile_test.go @@ -15,36 +15,6 @@ func TestEffectiveMaxTotalTokensNeverExceedsWindow(t *testing.T) { } } -func TestTokenEstimateSafetyPercent(t *testing.T) { - t.Parallel() - if got := (OpenAIConfig{}).TokenEstimateSafetyPercent(); got != 100 { - t.Fatalf("auto safety percent = %d, want 100", got) - } - if got := (OpenAIConfig{ContextProfile: "local"}).TokenEstimateSafetyPercent(); got != LocalTokenEstimateSafetyPercent { - t.Fatalf("local safety percent = %d, want %d", got, LocalTokenEstimateSafetyPercent) - } -} - -func TestApplyExtraRequestFieldsKeepsCoreFields(t *testing.T) { - t.Parallel() - payload := map[string]interface{}{"model": "qwen3", "temperature": 0.1} - ApplyExtraRequestFields(payload, map[string]interface{}{ - "model": "override", - "chat_template_kwargs": map[string]interface{}{"enable_thinking": false}, - "top_p": 0.9, - }) - if payload["model"] != "qwen3" { - t.Fatalf("core field overridden: %#v", payload) - } - if payload["top_p"] != 0.9 { - t.Fatalf("extra field missing: %#v", payload) - } - if _, ok := payload["chat_template_kwargs"]; !ok { - t.Fatalf("chat_template_kwargs missing: %#v", payload) - } - ApplyExtraRequestFields(nil, map[string]interface{}{"x": 1}) -} - func TestOutputLimitField(t *testing.T) { t.Parallel() if got := (OpenAIConfig{}).OutputLimitField(); got != "max_completion_tokens" { @@ -196,102 +166,19 @@ func TestContextBudgetWarnings(t *testing.T) { } } -func TestEffectiveAgentMiddlewareForChannelLocalTightens(t *testing.T) { - t.Parallel() - mw := AgentTuningConfig{ - SummarizationTriggerRatio: 0.8, - SummarizationOutputReserveTokens: 40960, - ReductionMaxLengthForTrunc: 100000, - ReductionMaxTokensForClear: 60000, - SummarizationUserIntentLedgerMaxRunes: 96000, - SummarizationUserIntentLedgerEntryMaxRunes: 16000, - LatestUserMessageMaxRunes: 48000, - LatestUserMessageHeadRunes: 24000, - LatestUserMessageTailRunes: 24000, - ToolSearchAlwaysVisible: 12, - PlanExecuteMaxStepResultRunes: 4000, - ToolSearchAlwaysVisibleTools: []string{ - "read_file", "glob", "grep", "analyze_image", "write_file", "edit_file", - "execute", "task", "transfer_to_agent", "exit", "write_todos", "skill", - "tool_search", "record_vulnerability", "http-framework-test", "webshell_exec", - }, - } - oa := OpenAIConfig{ContextWindow: 131072, ContextProfile: "local", MaxTotalTokens: 120000} - out := EffectiveRuntimeForChannel(mw, oa) - - if out.SummarizationTriggerRatio != 0.8 { - t.Fatalf("trigger ratio = %v, want 0.8", out.SummarizationTriggerRatio) - } - if out.SummarizationOutputReserveTokens != 4096 { - t.Fatalf("output reserve = %d, want 4096", out.SummarizationOutputReserveTokens) - } - if out.ReductionMaxLengthForTrunc != 21845 { - t.Fatalf("tool trunc bytes = %d, want 21845", out.ReductionMaxLengthForTrunc) - } - if out.ReductionMaxTokensForClear != 27525 { - t.Fatalf("tool clear tokens = %d, want 27525", out.ReductionMaxTokensForClear) - } - if out.SummarizationUserIntentLedgerMaxRunes != 96000 { - t.Fatalf("ledger runes = %d, want 96000", out.SummarizationUserIntentLedgerMaxRunes) - } - if out.SummarizationUserIntentLedgerEntryMaxRunes != 16000 { - t.Fatalf("ledger entry runes = %d, want 16000", out.SummarizationUserIntentLedgerEntryMaxRunes) - } - if out.LatestUserMessageMaxRunes != 48000 { - t.Fatalf("latest user runes = %d, want 48000", out.LatestUserMessageMaxRunes) - } - if out.ToolSearchMinTools != 8 || out.ToolSearchAlwaysVisible != 8 { - t.Fatalf("tool search = (%d,%d), want (8,8)", out.ToolSearchMinTools, out.ToolSearchAlwaysVisible) - } - wantTools := []string{ - "read_file", "glob", "grep", "analyze_image", "write_file", "edit_file", "execute", "task", - "transfer_to_agent", "exit", "write_todos", "skill", "tool_search", - "record_vulnerability", "http-framework-test", - } - if !reflect.DeepEqual(out.ToolSearchAlwaysVisibleTools, wantTools) { - t.Fatalf("always visible tools = %#v, want %#v", out.ToolSearchAlwaysVisibleTools, wantTools) - } - if out.ToolSearchIncludeBuiltinsEffective() { - t.Fatal("local profile must let backend builtins go through tool_search") - } - if out.PlanExecuteMaxStepResultRunes != 2000 { - t.Fatalf("plan step result runes = %d, want 2000", out.PlanExecuteMaxStepResultRunes) - } - if !out.ReductionEnable || !out.ReductionSubAgents { - t.Fatal("local profile must enable reduction for main agent and sub-agents") - } -} - -func TestEffectiveAgentMiddlewareForChannelLocalNeverLoosens(t *testing.T) { - t.Parallel() - mw := AgentTuningConfig{ - SummarizationTriggerRatio: 0.6, - SummarizationOutputReserveTokens: 1024, - ReductionMaxLengthForTrunc: 4096, - ReductionMaxTokensForClear: 2048, - SummarizationUserIntentLedgerMaxRunes: 8000, - SummarizationUserIntentLedgerEntryMaxRunes: 2000, - LatestUserMessageMaxRunes: 8000, - LatestUserMessageHeadRunes: 4000, - LatestUserMessageTailRunes: 4000, - ToolSearchMinTools: 4, - ToolSearchAlwaysVisible: 4, - PlanExecuteMaxStepResultRunes: 1000, - } +func TestLocalRuntimeBudgetsPreserveTighterSettings(t *testing.T) { oa := OpenAIConfig{ContextWindow: 131072, ContextProfile: "local"} - out := EffectiveRuntimeForChannel(mw, oa) - - if out.SummarizationTriggerRatio != 0.6 || - out.SummarizationOutputReserveTokens != 1024 || - out.ReductionMaxLengthForTrunc != 4096 || - out.ReductionMaxTokensForClear != 2048 || - out.SummarizationUserIntentLedgerMaxRunes != 8000 || - out.SummarizationUserIntentLedgerEntryMaxRunes != 1333 || - out.LatestUserMessageMaxRunes != 8000 || - out.ToolSearchMinTools != 4 || - out.ToolSearchAlwaysVisible != 4 || - out.PlanExecuteMaxStepResultRunes != 1000 { - t.Fatalf("local profile loosened explicit settings: %+v", out) + original := AgentTuningConfig{ReductionMaxLengthForTrunc: 100000, ToolSearchAlwaysVisible: 12} + got := EffectiveRuntimeForChannel(original, oa) + if !got.ReductionEnable || got.ReductionMaxLengthForTrunc != 21845 || !got.ToolSearchEnable || got.ToolSearchMinTools != 8 || got.ToolSearchAlwaysVisible != 8 || got.ToolSearchIncludeBuiltinsEffective() { + t.Fatalf("unexpected local tuning: %+v", got) + } + if original.ReductionEnable || original.ToolSearchEnable { + t.Fatal("runtime tuning mutated the saved config") + } + got.ReductionMaxLengthForTrunc, got.ToolSearchMinTools, got.ToolSearchAlwaysVisible = 2048, 4, 2 + if again := EffectiveRuntimeForChannel(got, oa); !reflect.DeepEqual(got, again) { + t.Fatal("tighter settings were changed") } } @@ -371,45 +258,3 @@ func TestDetectedLocalProfileUsesLocalBudgets(t *testing.T) { t.Fatal("detected backend lost local runtime tuning") } } - -func TestWithEffectiveContextBudgetIsIdempotent(t *testing.T) { - t.Parallel() - cfg := &Config{ - OpenAI: OpenAIConfig{ContextWindow: 131072, ContextProfile: "local", MaxTotalTokens: 120000}, - MultiAgent: MultiAgentConfig{ - Runtime: AgentTuningConfig{ - SummarizationTriggerRatio: 0.9, - SummarizationOutputReserveTokens: 40960, - ToolSearchAlwaysVisibleTools: []string{"read_file", "webshell_exec"}, - }, - }, - } - once := cfg.WithEffectiveContextBudget() - twice := once.WithEffectiveContextBudget() - if !reflect.DeepEqual(once.OpenAI, twice.OpenAI) { - t.Fatalf("OpenAI not idempotent: %#v vs %#v", once.OpenAI, twice.OpenAI) - } - if !reflect.DeepEqual(once.MultiAgent.Runtime, twice.MultiAgent.Runtime) { - t.Fatalf("middleware not idempotent: %#v vs %#v", once.MultiAgent.Runtime, twice.MultiAgent.Runtime) - } -} - -func TestWithEffectiveContextBudgetDoesNotMutateSource(t *testing.T) { - t.Parallel() - cfg := &Config{ - OpenAI: OpenAIConfig{ContextWindow: 131072, ContextProfile: "local", MaxTotalTokens: 120000}, - MultiAgent: MultiAgentConfig{ - Runtime: AgentTuningConfig{SummarizationTriggerRatio: 0.8}, - }, - } - out := cfg.WithEffectiveContextBudget() - if cfg.OpenAI.MaxTotalTokens != 120000 || cfg.MultiAgent.Runtime.SummarizationTriggerRatio != 0.8 { - t.Fatalf("source config mutated: %+v", cfg) - } - if out.OpenAI.MaxTotalTokens != 78643 { - t.Fatalf("effective budget = %d, want 78643", out.OpenAI.MaxTotalTokens) - } - if out.MultiAgent.Runtime.SummarizationTriggerRatio != 0.8 { - t.Fatalf("effective trigger ratio = %v, want 0.8", out.MultiAgent.Runtime.SummarizationTriggerRatio) - } -} diff --git a/internal/handler/agent.go b/internal/handler/agent.go index 72582ba3..22c6ee37 100644 --- a/internal/handler/agent.go +++ b/internal/handler/agent.go @@ -426,7 +426,7 @@ func (h *AgentHandler) configForAIChannel(channelID string) (*config.Config, str } cfgCopy := *h.config cfgCopy.OpenAI = oa - return cfgCopy.WithEffectiveContextBudget(), resolvedID, nil + return &cfgCopy, resolvedID, nil } func chatReasoningToClientIntent(r *ChatReasoningRequest) *reasoning.ClientIntent { diff --git a/internal/handler/config_context_test.go b/internal/handler/config_context_test.go index 7011ec29..79fb0d6d 100644 --- a/internal/handler/config_context_test.go +++ b/internal/handler/config_context_test.go @@ -6,11 +6,36 @@ import ( "net/http/httptest" "testing" + "cyberstrike-ai/internal/config" "cyberstrike-ai/internal/modelmeta" "github.com/gin-gonic/gin" + "gopkg.in/yaml.v3" ) +func TestDetectedContextSettingsRoundTripThroughSavedYAML(t *testing.T) { + var doc yaml.Node + if err := yaml.Unmarshal([]byte("ai:\n default_channel: local\n channels:\n local:\n model: fixture\n context_profile: custom\n context_window: 131072\n"), &doc); err != nil { + t.Fatal(err) + } + for _, profile := range []string{"local_auto", "custom", ""} { + ch := config.AIChannelConfig{Model: "fixture", ContextWindow: 32768, ContextProfile: profile} + updateAIConfig(&doc, config.AIConfig{DefaultChannel: "local", Channels: map[string]config.AIChannelConfig{"local": ch}}) + raw, err := yaml.Marshal(&doc) + if err != nil { + t.Fatal(err) + } + var saved config.Config + if err := yaml.Unmarshal(raw, &saved); err != nil { + t.Fatal(err) + } + oa := saved.AI.Channels["local"].ToOpenAIConfig() + if oa.ContextWindow != 32768 || oa.ContextProfile != profile || oa.Model != "fixture" { + t.Fatalf("context settings lost on save: %+v", oa) + } + } +} + func TestAddModelContextToResponseLocalProfilePreview(t *testing.T) { t.Parallel() resp := gin.H{} diff --git a/internal/handler/fofa.go b/internal/handler/fofa.go index 08e909e6..66545d02 100644 --- a/internal/handler/fofa.go +++ b/internal/handler/fofa.go @@ -418,10 +418,9 @@ Shodan 官方查询语法参考: {"role": "system", "content": systemPrompt}, {"role": "user", "content": userPrompt}, }, - "temperature": 0.1, - h.cfg.OpenAI.OutputLimitField(): 12000, + "temperature": 0.1, + "max_completion_tokens": 12000, } - config.ApplyExtraRequestFields(requestBody, h.cfg.OpenAI.Reasoning.ExtraRequestFields) // OpenAI 返回结构:只需要 choices[0].message.content var apiResponse struct { diff --git a/internal/handler/hitl_audit_agent.go b/internal/handler/hitl_audit_agent.go index 66a16984..c7db6119 100644 --- a/internal/handler/hitl_audit_agent.go +++ b/internal/handler/hitl_audit_agent.go @@ -49,13 +49,12 @@ func (h *AgentHandler) auditAgentReview(ctx context.Context, hitlMode, toolName {"role": "system", "content": prompt}, {"role": "user", "content": userContent}, }, - "temperature": 0.1, - llmCfg.OutputLimitField(): 1024, + "temperature": 0.1, + "max_completion_tokens": 1024, } if auditDisableThinking(llmCfg) { requestBody["thinking"] = map[string]interface{}{"type": "disabled"} } - config.ApplyExtraRequestFields(requestBody, llmCfg.Reasoning.ExtraRequestFields) var apiResponse struct { Choices []struct { diff --git a/internal/handler/openapi.go b/internal/handler/openapi.go index 0fd1c47e..bd90f2ca 100644 --- a/internal/handler/openapi.go +++ b/internal/handler/openapi.go @@ -5035,13 +5035,10 @@ 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"}, - "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": "可选:上下文优化档位"}, + "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"}, }, }, }, @@ -5055,70 +5052,10 @@ 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时)"}, - "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": "上下文告警码(可选)"}, - }, - }, - }, - }, - }, - "400": map[string]interface{}{"description": "参数错误"}, - "401": map[string]interface{}{"description": "未授权"}, - }, - }, - }, - "/api/config/detect-context": map[string]interface{}{ - "post": map[string]interface{}{ - "tags": []string{"配置管理"}, - "summary": "探测模型运行时上下文窗口", - "description": "探测 Ollama、llama.cpp、LM Studio、vLLM/OpenAI 兼容端点的运行时上下文窗口,并按当前档位计算有效预算;不会发起推理请求。", - "operationId": "detectModelContext", - "requestBody": map[string]interface{}{ - "required": true, - "content": map[string]interface{}{ - "application/json": map[string]interface{}{ - "schema": map[string]interface{}{ - "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": "当前配置的最大上下文预算,用于计算有效预算与告警"}, - "max_completion_tokens": map[string]interface{}{"type": "integer", "description": "当前配置的单次输出上限,用于计算有效预算与输出预留"}, - "context_profile": map[string]interface{}{"type": "string", "enum": []string{"auto", "local"}, "description": "上下文优化档位"}, - }, - }, - }, - }, - }, - "responses": map[string]interface{}{ - "200": map[string]interface{}{ - "description": "探测结果", - "content": map[string]interface{}{ - "application/json": map[string]interface{}{ - "schema": map[string]interface{}{ - "type": "object", - "properties": map[string]interface{}{ - "success": map[string]interface{}{"type": "boolean", "description": "探测是否执行成功"}, - "model": map[string]interface{}{"type": "string", "description": "被探测的模型"}, - "context_backend": map[string]interface{}{"type": "string", "description": "识别到的后端类型(ollama/llamacpp/lmstudio/openai_compatible)"}, - "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)"}, + "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时)"}, }, }, }, diff --git a/internal/knowledge/wire_retriever.go b/internal/knowledge/wire_retriever.go index 62351c7e..6bea92fd 100644 --- a/internal/knowledge/wire_retriever.go +++ b/internal/knowledge/wire_retriever.go @@ -38,34 +38,27 @@ func WireRetrieverPipeline(ctx context.Context, r *Retriever, oa *config.OpenAIC logger = zap.NewNop() } mq := &nativeMultiQuery{ - inner: vector, - max: maxQueries, - client: openai.NewClient(oa, &http.Client{Timeout: 120 * time.Second}, logger), - model: oa.Model, - logger: logger, - maxTokens: oa.MaxCompletionTokensEffective(), - limitField: oa.OutputLimitField(), + inner: vector, + max: maxQueries, + client: openai.NewClient(oa, &http.Client{Timeout: 120 * time.Second}, logger), + model: oa.Model, + logger: logger, } r.pipeline = newKnowledgePipelineRetriever(mq, r) return nil } type nativeMultiQuery struct { - inner DocumentRetriever - max int - client *openai.Client - model string - logger *zap.Logger - maxTokens int - limitField string + inner DocumentRetriever + max int + client *openai.Client + model string + logger *zap.Logger } func (q *nativeMultiQuery) Retrieve(ctx context.Context, query string, opts ...RetrievalOption) ([]*Document, error) { queries := []string{query} payload := map[string]any{"model": q.model, "messages": []map[string]string{{"role": "system", "content": fmt.Sprintf("Return only a JSON array containing at most %d alternative search queries for the user's knowledge search. Preserve technical identifiers and the user's language.", q.max-1)}, {"role": "user", "content": query}}} - if q.maxTokens > 0 { - payload[q.limitField] = q.maxTokens - } var answer struct { Choices []struct { Message struct { diff --git a/internal/workflow/draft_generator.go b/internal/workflow/draft_generator.go index 28f213af..9a316421 100644 --- a/internal/workflow/draft_generator.go +++ b/internal/workflow/draft_generator.go @@ -303,12 +303,11 @@ func GenerateDraftFromLLM(ctx context.Context, req DraftRequest, oa config.OpenA {"role": "system", "content": systemPrompt}, {"role": "user", "content": userPrompt}, }, - "temperature": 0, - oa.OutputLimitField(): 4096, - "response_format": map[string]interface{}{"type": "json_object"}, - "thinking": map[string]interface{}{"type": "disabled"}, + "temperature": 0, + "max_completion_tokens": 4096, + "response_format": map[string]interface{}{"type": "json_object"}, + "thinking": map[string]interface{}{"type": "disabled"}, } - config.ApplyExtraRequestFields(requestBody, oa.Reasoning.ExtraRequestFields) var apiResponse struct { Choices []struct { Message struct { diff --git a/web/static/css/style.css b/web/static/css/style.css index 238fde39..eb0a810c 100644 --- a/web/static/css/style.css +++ b/web/static/css/style.css @@ -5409,14 +5409,6 @@ html[data-theme="dark"] .conversation-reasoning-card:not(.conversation-reasoning line-height: 1.45; } -#detect-context-result.is-success { - color: var(--success-color, #38a169); -} - -#detect-context-result.is-error { - color: var(--danger-color, #e53e3e); -} - .ai-channel-reasoning-toggle { margin-top: 8px; }