Просмотр исходного кода

feat(agent): 模型上下文窗口可配置,压缩与预算按窗口比例计算

- agent_model.context_window_size:模型页选择 64/128/256/512/1M;
  未设置统一按 256K(262,144)下发,不再依赖厂商/模型名推断
- 压缩触发线 = 窗口 × 80%(agent.compaction.trigger-ratio 可调)
- prune 预算按窗口比例:保护最近 15%、最小裁剪量 7.5%
- 单条工具结果驱逐阈值按窗口 8%(tokens × 4 chars),钳制 8K–200K 字符
- 移除 trigger-tokens/reserved 静态阈值与 max-result-chars 配置
- 模型更新/删除后驱逐绑定该模型的池化 Agent,新窗口立即生效
- 新增/更新单测:窗口计算、prune、驱逐、未设置按 256K
cc 2 недель назад
Родитель
Сommit
a5b65c3706

+ 9 - 22
ai-server/src/main/java/com/zsjz/ai/module/agent/config/AgentProperties.java

@@ -45,25 +45,12 @@ public class AgentProperties {
         private boolean enabled = true;
 
         /**
-         * 消息条数触发阈值(非 SYSTEM 消息数)。0 = 禁用条数触发,只按 token 触发。
-         * 默认 0:对齐 ZCode 的纯 token 策略,压缩只在上下文 token 达到
-         * {@link #triggerTokens} 时进行,低 token 的短对话不做无谓的摘要调用。
+         * 压缩触发比例:默认 0.8(模型设置窗口的 80% 就压缩)。
+         *
+         * <p>窗口来自模型管理页(agent_model.context_window_size),未设置统一按 256K。
+         * 不再提供 trigger-tokens/reserved 静态阈值:模型窗口一定有值,静态阈值没有意义。
          */
-        private int triggerMessages = 0;
-
-        /**
-         * token 触发阈值(静态):上下文 token 达到该值才压缩。默认 200000。
-         * 框架会在运行时把触发线钳制到 min(triggerTokens, 模型窗口 − reserved)——
-         * 模型窗口小于阈值时不会撑爆(超窗还有 overflow 自动强制压缩重试兜底)。
-         * 0 = 动态模式(模型窗口 − {@link #reserved})。
-         */
-        private int triggerTokens = 200000;
-
-        /**
-         * 动态 token 阈值的保留量:仅 {@link #triggerTokens} 为 0(动态模式)时生效。
-         * 框架默认 20000。
-         */
-        private int reserved = 20000;
+        private double triggerRatio = 0.8;
 
         /**
          * 压缩摘要用模型 id;空 = 主模型。非空暂不支持(项目模型不经 ModelRegistry
@@ -90,10 +77,10 @@ public class AgentProperties {
     @Data
     public static class Eviction {
 
-        /** 开关(框架默认开,阈值 80k 字符;这里显式可配) */
+        /**
+         * 开关。阈值不再配置:按模型窗口的 8%(tokens × 4 chars)计算,
+         * 256K 下约 84K 字符、64K 下约 21K 字符。
+         */
         private boolean enabled = true;
-
-        /** 单条工具结果触发驱逐的字符上限 */
-        private int maxResultChars = 80000;
     }
 }

+ 88 - 13
ai-server/src/main/java/com/zsjz/ai/module/agent/config/AgentRuntimeTuning.java

@@ -1,5 +1,6 @@
 package com.zsjz.ai.module.agent.config;
 
+import io.agentscope.core.model.Model;
 import io.agentscope.harness.agent.HarnessAgent;
 import io.agentscope.harness.agent.memory.compaction.CompactionConfig;
 import io.agentscope.harness.agent.memory.compaction.ToolResultEvictionConfig;
@@ -27,22 +28,69 @@ import lombok.extern.slf4j.Slf4j;
 @Slf4j
 public final class AgentRuntimeTuning {
 
+    /** 模型窗口缺失时的统一默认窗口(256K);正常链路由 AgentModelFactory 保证有值 */
+    private static final int DEFAULT_CONTEXT_WINDOW_SIZE = 262_144;
+
+    /** 非法触发比例的兜底(80%) */
+    private static final double DEFAULT_TRIGGER_RATIO = 0.8;
+
+    /** 老工具结果 prune:保护最近 15% 窗口的工具输出 */
+    private static final double PRUNE_PROTECT_RATIO = 0.15;
+
+    /** 老工具结果 prune:可裁剪量达到窗口 7.5% 才执行 */
+    private static final double PRUNE_MINIMUM_RATIO = 0.075;
+
+    /** 单条工具结果驱逐:窗口的 8%(tokens)× 4 chars/token */
+    private static final double EVICTION_RATIO = 0.08;
+
+    /** 单条工具结果驱逐的字符上下限(约 2K / 50K tokens) */
+    private static final int EVICTION_MIN_CHARS = 8_000;
+    private static final int EVICTION_MAX_CHARS = 200_000;
+
     private AgentRuntimeTuning() {
     }
 
     /**
-     * 按配置构建 CompactionConfig;只显式设配置项,其余保持框架默认
-     * (keep 尾部动态 2k-8k token、老工具结果 prune、压缩前 flush memory、摘要用主模型)。
+     * 按配置构建 CompactionConfig(无模型窗口信息时按默认 256K)。
+     *
+     * <p>只显式设配置项,其余保持框架默认(keep 尾部动态 2k-8k token、
+     * 老工具结果 prune、压缩前 flush memory、摘要用主模型)。
      */
     public static CompactionConfig buildCompactionConfig(AgentProperties props) {
+        return buildCompactionConfig(props, 0);
+    }
+
+    /**
+     * 按配置构建 CompactionConfig:触发线 = {@code 窗口 × triggerRatio}(默认 80%)。
+     *
+     * <p>窗口一定存在(模型页设置,未设置由 AgentModelFactory 统一按 256K 下发),
+     * 因此不再保留 trigger-tokens/reserved 静态阈值配置。
+     *
+     * @param props             agent 配置
+     * @param contextWindowSize 模型上下文窗口(tokens);{@code <=0} 时按默认 256K
+     */
+    public static CompactionConfig buildCompactionConfig(AgentProperties props, int contextWindowSize) {
         AgentProperties.Compaction compaction = props.getCompaction();
+        int window = contextWindowSize > 0 ? contextWindowSize : DEFAULT_CONTEXT_WINDOW_SIZE;
+        double ratio = normalizeRatio(compaction.getTriggerRatio());
+        int trigger = Math.max(1, (int) Math.floor(window * ratio));
+        int reserved = Math.max(1, window - trigger);
+        int pruneProtect = Math.max(1_024, (int) Math.floor(window * PRUNE_PROTECT_RATIO));
+        int pruneMinimum = Math.max(512, (int) Math.floor(window * PRUNE_MINIMUM_RATIO));
         CompactionConfig.Builder builder = CompactionConfig.builder()
-                .triggerMessages(compaction.getTriggerMessages());
-        if (compaction.getTriggerTokens() > 0) {
-            // 静态 token 阈值(运行时框架会钳制到 min(阈值, 模型窗口 − reserved),防超窗)
-            builder.triggerTokens(compaction.getTriggerTokens());
-        }
-        builder.reserved(compaction.getReserved());
+                // 纯 token 策略:条数触发固定关闭
+                .triggerMessages(0)
+                .triggerTokens(trigger)
+                .reserved(reserved)
+                // 老工具结果 prune 同样按窗口比例:256K 下约 39K/20K,与框架默认基本一致;
+                // 64K 下约 9.8K/4.9K,避免保护窗口过大导致 prune 永不触发
+                .prune(CompactionConfig.PruneConfig.builder()
+                        .protectTokens(pruneProtect)
+                        .minimumTokens(pruneMinimum)
+                        .maxOutputChars(2_000)
+                        .build());
+        log.info("上下文压缩按模型窗口计算: window={}, ratio={}, trigger={}, reserved={}, pruneProtect={}, pruneMinimum={}",
+                window, ratio, trigger, reserved, pruneProtect, pruneMinimum);
         if (compaction.getSummaryModelId() != null && !compaction.getSummaryModelId().isBlank()) {
             // 项目模型不经 ModelRegistry 注册,CompactionConfig.model(String) 解析不可靠;
             // 本轮只支持主模型做摘要,配置位预留
@@ -58,22 +106,49 @@ public final class AgentRuntimeTuning {
         return builder.build();
     }
 
-    /** 按配置构建工具结果驱逐配置。 */
-    public static ToolResultEvictionConfig buildToolResultEvictionConfig(AgentProperties props) {
+    /** 比例必须在 (0,1) 内;非法值回落到默认 80% */
+    private static double normalizeRatio(double ratio) {
+        return ratio > 0 && ratio < 1 ? ratio : DEFAULT_TRIGGER_RATIO;
+    }
+
+    /**
+     * 按模型窗口构建工具结果驱逐配置:单条结果上限 ≈ 窗口的 8%(tokens)× 4 chars/token。
+     *
+     * <p>256K 下约 84K 字符(与框架默认 80K 接近);64K 下约 21K 字符,避免单条结果
+     * 吃掉三分之一窗口。
+     */
+    public static ToolResultEvictionConfig buildToolResultEvictionConfig(int contextWindowSize) {
+        int window = contextWindowSize > 0 ? contextWindowSize : DEFAULT_CONTEXT_WINDOW_SIZE;
+        long chars = Math.round(window * EVICTION_RATIO * 4);
+        int maxResultChars = (int) Math.min(EVICTION_MAX_CHARS,
+                Math.max(EVICTION_MIN_CHARS, chars));
         return ToolResultEvictionConfig.builder()
-                .maxResultChars(props.getToolResultEviction().getMaxResultChars())
+                .maxResultChars(maxResultChars)
                 .build();
     }
 
     /** 把压缩 + 工具结果驱逐配置挂到 builder 上(幂等,重复调用覆盖前值)。 */
     public static void apply(HarnessAgent.Builder builder, AgentProperties props) {
+        apply(builder, props, null);
+    }
+
+    /**
+     * 把压缩 + 工具结果驱逐配置挂到 builder 上;有模型实例时按其上下文窗口计算
+     * 80% 压缩触发线。
+     */
+    public static void apply(HarnessAgent.Builder builder, AgentProperties props, Model model) {
+        int contextWindowSize = model == null ? 0 : model.getContextWindowSize();
+        int effectiveWindow = contextWindowSize > 0 ? contextWindowSize : DEFAULT_CONTEXT_WINDOW_SIZE;
         if (props.getCompaction().isEnabled()) {
-            builder.compaction(buildCompactionConfig(props));
+            builder.compaction(buildCompactionConfig(props, contextWindowSize));
         } else {
             builder.disableCompaction();
         }
         if (props.getToolResultEviction().isEnabled()) {
-            builder.toolResultEviction(buildToolResultEvictionConfig(props));
+            ToolResultEvictionConfig eviction = buildToolResultEvictionConfig(contextWindowSize);
+            builder.toolResultEviction(eviction);
+            log.info("工具结果驱逐按模型窗口计算: window={}, maxResultChars={}",
+                    effectiveWindow, eviction.getMaxResultChars());
         } else {
             builder.disableToolResultEviction();
         }

+ 8 - 1
ai-server/src/main/java/com/zsjz/ai/module/agent/controller/AgentModelController.java

@@ -5,6 +5,7 @@ import com.zsjz.ai.module.agent.dto.CreateModelDTO;
 import com.zsjz.ai.module.agent.dto.UpdateModelDTO;
 import com.zsjz.ai.module.agent.service.AgentModelProviderService;
 import com.zsjz.ai.module.agent.service.AgentModelService;
+import com.zsjz.ai.module.agent.service.AgentService;
 import com.zsjz.ai.module.agent.vo.ModelProviderVO;
 import com.zsjz.ai.module.agent.vo.ModelTestResultVO;
 import com.zsjz.ai.module.agent.vo.ModelVO;
@@ -26,6 +27,7 @@ public class AgentModelController {
 
     private final AgentModelService agentModelService;
     private final AgentModelProviderService agentModelProviderService;
+    private final AgentService agentService;
 
     /**
      * 查询模型厂商列表
@@ -52,11 +54,15 @@ public class AgentModelController {
     }
 
     /**
-     * 更新模型
+     * 更新模型。
+     *
+     * <p>模型配置(含上下文窗口)变更后驱逐绑定该模型的池化 agent:
+     * 池 key 只含 modelId,不驱逐的话旧 Model 和旧压缩阈值会继续生效。
      */
     @PutMapping("/{id}")
     public Result<Void> updateModel(@PathVariable Long id, @Valid @RequestBody UpdateModelDTO dto) {
         agentModelService.updateModel(id, dto);
+        agentService.evictAgentsUsingModel(id);
         return Result.succeed();
     }
 
@@ -66,6 +72,7 @@ public class AgentModelController {
     @GetMapping("/{id}")
     public Result<Void> deleteModel(@PathVariable Long id) {
         agentModelService.deleteModel(id);
+        agentService.evictAgentsUsingModel(id);
         return Result.succeed();
     }
 

+ 3 - 0
ai-server/src/main/java/com/zsjz/ai/module/agent/dto/CreateModelDTO.java

@@ -32,6 +32,9 @@ public class CreateModelDTO {
 
     private Boolean defaultModel;
 
+    /** 模型上下文窗口(tokens);0/NULL = 按模型名推断 */
+    private Integer contextWindowSize;
+
     private String config;
 
     private String headersJson;

+ 3 - 0
ai-server/src/main/java/com/zsjz/ai/module/agent/dto/UpdateModelDTO.java

@@ -30,6 +30,9 @@ public class UpdateModelDTO {
 
     private Boolean defaultModel;
 
+    /** 模型上下文窗口(tokens);0/NULL = 按模型名推断 */
+    private Integer contextWindowSize;
+
     private String config;
 
     private String headersJson;

+ 7 - 0
ai-server/src/main/java/com/zsjz/ai/module/agent/entity/AgentModel.java

@@ -40,6 +40,13 @@ public class AgentModel {
     @TableField("default_model")
     private Boolean defaultModel;
 
+    /**
+     * 模型上下文窗口(tokens);0/NULL = 按模型名推断。
+     * 用于上下文压缩触发线(窗口 × 80%),同时下发给 Model 供框架预算计算。
+     */
+    @TableField("context_window_size")
+    private Integer contextWindowSize;
+
     @TableField(value="config", typeHandler = JsonbTypeHandler.class, jdbcType = JdbcType.OTHER)
     private String config;
 

+ 48 - 13
ai-server/src/main/java/com/zsjz/ai/module/agent/service/AgentModelFactory.java

@@ -32,6 +32,9 @@ public class AgentModelFactory {
     private static final String PREFIX_DASHSCOPE = "dashscope:";
     private static final String PREFIX_OPENAI = "openai:";
 
+    /** 模型未配置上下文窗口时的统一默认值(256K) */
+    private static final int DEFAULT_CONTEXT_WINDOW_SIZE = 262_144;
+
     /** config JSON 里控制「思考模式」的键名(true=开启,false=显式关闭,缺省=跟随厂商默认) */
     private static final String CONFIG_ENABLE_THINKING = "enableThinking";
 
@@ -70,6 +73,7 @@ public class AgentModelFactory {
         }
 
         String modelRef = resolvePrefix(config.getProvider()) + config.getModelId().trim();
+        JsonNode configNode = parseConfig(config);
         ModelCreationContext.Builder builder = ModelCreationContext.builder()
                 .apiKey(config.getApiKey().trim())
                 .baseUrl(StringUtils.hasText(config.getBaseUrl()) ? config.getBaseUrl().trim() : null)
@@ -79,14 +83,21 @@ public class AgentModelFactory {
         // 思考模式开关:显式覆盖优先;否则 DB config 里写了才下发;都没有则保持厂商默认行为。
         // 开启后模型会流式吐 reasoning_content / thinking,前端渲染为「思考过程」面板。
         Boolean enableThinking = enableThinkingOverride != null
-                ? enableThinkingOverride : readEnableThinking(config);
+                ? enableThinkingOverride : readEnableThinking(configNode);
         if (enableThinking != null) {
             builder.enableThinking(enableThinking);
         }
+        // 上下文窗口:填多少用多少;未设置统一按 256K。
+        // 不再依赖 provider 按模型名推断(qwen/deepseek/glm 多推断不到,且同一模型
+        // 不同部署窗口也可能不同),保证压缩触发线始终 = 设置值 × 80%。
+        int contextWindowSize = resolveContextWindowSize(
+                config.getContextWindowSize(), config.getName());
+        builder.option("contextWindowSize", contextWindowSize);
         ModelCreationContext ctx = builder.build();
         try {
             Model model = ModelRegistry.resolve(modelRef, ctx);
-            log.info("构造模型实例: ref={}, name={}, enableThinking={}", modelRef, config.getName(), enableThinking);
+            log.info("构造模型实例: ref={}, name={}, enableThinking={}, contextWindowSize={}",
+                    modelRef, config.getName(), enableThinking, contextWindowSize);
             return model;
         } catch (RuntimeException e) {
             log.error("模型实例构造失败: ref={}, error={}", modelRef, e.getMessage());
@@ -95,27 +106,51 @@ public class AgentModelFactory {
     }
 
     /**
-     * 从模型 config JSON 读取思考模式开关。
-     *
-     * <p>约定:{@code {"enableThinking": true}} 开启 / {@code false} 显式关闭;
-     * 未配置或 JSON 非法时返回 {@code null}(交给各 provider 的默认行为,不改变既有表现)。
-     *
-     * @param config 模型配置实体
-     * @return true / false / null
+     * 解析模型 config JSON;空/非法时返回 {@code null}(不阻断模型创建)。
      */
-    private static Boolean readEnableThinking(AgentModel config) {
+    private static JsonNode parseConfig(AgentModel config) {
         if (!StringUtils.hasText(config.getConfig())) {
             return null;
         }
         try {
-            JsonNode node = Json.objectMapper().readTree(config.getConfig()).path(CONFIG_ENABLE_THINKING);
-            return node.isBoolean() ? node.booleanValue() : null;
+            return Json.objectMapper().readTree(config.getConfig());
         } catch (Exception e) {
-            log.error("模型 config 解析失败,忽略思考模式开关: name={}, error={}", config.getName(), e.getMessage());
+            log.error("模型 config 解析失败,忽略扩展配置: name={}, error={}", config.getName(), e.getMessage());
             return null;
         }
     }
 
+    /**
+     * 从模型 config JSON 读取思考模式开关。
+     *
+     * <p>约定:{@code {"enableThinking": true}} 开启 / {@code false} 显式关闭;
+     * 未配置或 JSON 非法时返回 {@code null}(交给各 provider 的默认行为,不改变既有表现)。
+     */
+    private static Boolean readEnableThinking(JsonNode configNode) {
+        if (configNode == null) {
+            return null;
+        }
+        JsonNode node = configNode.path(CONFIG_ENABLE_THINKING);
+        return node.isBoolean() ? node.booleanValue() : null;
+    }
+
+    /**
+     * 解析模型上下文窗口。
+     *
+     * <p>口径:填多少用多少;未设置(0/NULL)或明显误填(小于 1024)一律按 256K。
+     */
+    private static int resolveContextWindowSize(Integer value, String modelName) {
+        if (value == null || value <= 0) {
+            return DEFAULT_CONTEXT_WINDOW_SIZE;
+        }
+        if (value < 1024) {
+            log.warn("模型上下文窗口配置过小,按默认 256K 处理: name={}, contextWindowSize={}",
+                    modelName, value);
+            return DEFAULT_CONTEXT_WINDOW_SIZE;
+        }
+        return value;
+    }
+
     /**
      * provider 归一化:DB provider 值 → agentscope SPI 前缀
      */

+ 19 - 2
ai-server/src/main/java/com/zsjz/ai/module/agent/service/AgentService.java

@@ -463,8 +463,9 @@ public class AgentService extends ServiceImpl<AgentMapper, AgentEntity> {
         // 必须注册在最后(链上最内层),才能看到前序中间件改写后的最终输入。
         b.middleware(new PromptTraceMiddleware());
 
-        // 压缩/驱逐调优要挂在 workspace 之前(eviction 落盘目录相对 workspace)
-        AgentRuntimeTuning.apply(b, agentProperties);
+        // 压缩/驱逐调优要挂在 workspace 之前(eviction 落盘目录相对 workspace)。
+        // 传入模型实例:有上下文窗口时压缩触发线按「窗口 × 80%」计算。
+        AgentRuntimeTuning.apply(b, agentProperties, model);
         b.workspace(workspace);
 
         // 用户级技能:官方 JDBC 技能仓库里归属于当前登录用户的那部分。
@@ -754,6 +755,22 @@ public class AgentService extends ServiceImpl<AgentMapper, AgentEntity> {
         }
     }
 
+    /**
+     * 驱逐所有绑定指定模型的池化实例。
+     *
+     * <p>模型配置(上下文窗口/Base URL/密钥)变更后必须调用:池 key 只含 modelId,
+     * 不换实例的话旧 Model 对象和旧压缩阈值会继续生效。
+     */
+    public void evictAgentsUsingModel(Long modelId) {
+        if (modelId == null) {
+            return;
+        }
+        int removed = agentPool.evictByMarker("-m" + modelId + "-");
+        if (removed > 0) {
+            log.info("模型配置变更,驱逐 agent 实例池: modelId={}, removed={}", modelId, removed);
+        }
+    }
+
     /**
      * 驱逐全部池化实例。
      *

+ 1 - 0
ai-server/src/main/java/com/zsjz/ai/module/agent/service/impl/AgentModelServiceImpl.java

@@ -59,6 +59,7 @@ public class AgentModelServiceImpl extends ServiceImpl<AgentModelMapper, AgentMo
         entity.setApiKey(dto.getApiKey());
         entity.setBaseUrl(dto.getBaseUrl());
         entity.setDefaultModel(dto.getDefaultModel() != null && dto.getDefaultModel());
+        entity.setContextWindowSize(dto.getContextWindowSize());
         entity.setConfig(dto.getConfig() != null ? dto.getConfig() : "{}");
         entity.setHeadersJson(dto.getHeadersJson() != null ? dto.getHeadersJson() : "{}");
         entity.setExtraJson(dto.getExtraJson() != null ? dto.getExtraJson() : "{}");

+ 1 - 0
ai-server/src/main/java/com/zsjz/ai/module/agent/vo/ModelVO.java

@@ -18,6 +18,7 @@ public class ModelVO {
     private String apiKey;
     private String baseUrl;
     private Boolean defaultModel;
+    private Integer contextWindowSize;
     private String config;
     private String headersJson;
     private String extraJson;

+ 54 - 27
ai-server/src/test/java/com/zsjz/ai/module/agent/config/AgentRuntimeTuningTest.java

@@ -1,7 +1,6 @@
 package com.zsjz.ai.module.agent.config;
 
 import io.agentscope.harness.agent.memory.compaction.CompactionConfig;
-import io.agentscope.harness.agent.memory.compaction.ToolResultEvictionConfig;
 import org.junit.jupiter.api.DisplayName;
 import org.junit.jupiter.api.Test;
 
@@ -12,50 +11,79 @@ import static org.junit.jupiter.api.Assertions.assertNull;
 /**
  * {@link AgentRuntimeTuning} 的配置映射测试(纯函数,不起 Spring)。
  *
- * <p>锁住 yaml 属性 → harness 压缩/驱逐配置的映射关系:压缩是长任务的续命机制,
- * 配错阈值(比如 triggerMessages 传 0 又没配 token 阈值)会让长任务退化回「靠 maxIters 硬掐」。
+ * <p>核心口径:压缩触发线 = 模型窗口 × triggerRatio(默认 80%)。
+ * 模型窗口由 AgentModelFactory 保证有值(未设置按 256K),因此不再有静态
+ * trigger-tokens / reserved 兜底配置。
  */
 class AgentRuntimeTuningTest {
 
     @Test
-    @DisplayName("默认配置:纯 token 触发(triggerMessages=0、triggerTokens=200000),truncateArgs/prune 保持开启")
+    @DisplayName("无窗口参数:按默认 256K 计算 80% 触发线;prune 按 15%/7.5% 计算")
     void buildWithDefaults() {
         CompactionConfig config = AgentRuntimeTuning.buildCompactionConfig(new AgentProperties());
 
-        // 纯 token 策略(对齐 ZCode):条数触发禁用,200k token 才压缩
         assertEquals(0, config.getTriggerMessages());
-        assertEquals(200000, config.getTriggerTokens());
+        assertEquals(209715, config.getTriggerTokens());
+        assertEquals(52429, config.getReserved());
         // truncateArgs 默认开启(对齐 ZCode microcompact 的参数瘦身)
         assertNotNull(config.getTruncateArgsConfig());
         assertEquals(2000, config.getTruncateArgsConfig().getMaxArgLength());
-        // 老工具结果 prune 是长上下文的另一道瘦身,必须保持默认开启
+        // prune 按窗口 15% / 7.5%:256K → 39321 / 19660
         assertNotNull(config.getPruneConfig());
+        assertEquals(39321, config.getPruneConfig().getProtectTokens());
+        assertEquals(19660, config.getPruneConfig().getMinimumTokens());
+        assertEquals(2000, config.getPruneConfig().getMaxOutputChars());
     }
 
     @Test
-    @DisplayName("动态模式:triggerTokens=0 时不设置静态阈值(走框架动态窗口−reserved)")
-    void dynamicTriggerMode() {
+    @DisplayName("64K 窗口:prune 保护量随窗口缩小,不会永不触发")
+    void pruneScalesWithSmallWindow() {
+        CompactionConfig config = AgentRuntimeTuning.buildCompactionConfig(new AgentProperties(), 65536);
+
+        assertEquals(9830, config.getPruneConfig().getProtectTokens());
+        assertEquals(4915, config.getPruneConfig().getMinimumTokens());
+    }
+
+    @Test
+    @DisplayName("模型窗口已知:触发线 = 窗口 × 80%,保留量 = 剩余 20%")
+    void modelWindowComputesTrigger() {
+        CompactionConfig config = AgentRuntimeTuning.buildCompactionConfig(new AgentProperties(), 128000);
+
+        assertEquals(102400, config.getTriggerTokens());
+        assertEquals(25600, config.getReserved());
+    }
+
+    @Test
+    @DisplayName("模型窗口已知:trigger-ratio 可覆盖(如 75%)")
+    void modelWindowUsesConfiguredRatio() {
         AgentProperties props = new AgentProperties();
-        props.getCompaction().setTriggerTokens(0);
+        props.getCompaction().setTriggerRatio(0.75);
 
-        CompactionConfig config = AgentRuntimeTuning.buildCompactionConfig(props);
+        CompactionConfig config = AgentRuntimeTuning.buildCompactionConfig(props, 200000);
 
-        assertEquals(0, config.getTriggerTokens());
-        assertEquals(20000, config.getReserved());
+        assertEquals(150000, config.getTriggerTokens());
+        assertEquals(50000, config.getReserved());
     }
 
     @Test
-    @DisplayName("属性覆盖:自定义 triggerMessages/reserved/maxArgLength 逐项映射")
-    void buildWithCustomValues() {
+    @DisplayName("非法 trigger-ratio 回落默认 80%")
+    void invalidRatioFallsBackToDefault() {
+        AgentProperties props = new AgentProperties();
+        props.getCompaction().setTriggerRatio(1.5);
+
+        CompactionConfig config = AgentRuntimeTuning.buildCompactionConfig(props, 128000);
+
+        assertEquals(102400, config.getTriggerTokens());
+    }
+
+    @Test
+    @DisplayName("truncateArgs 自定义 maxArgLength 映射")
+    void truncateArgsCustom() {
         AgentProperties props = new AgentProperties();
-        props.getCompaction().setTriggerMessages(6);
-        props.getCompaction().setReserved(8000);
         props.getCompaction().getTruncateArgs().setMaxArgLength(500);
 
         CompactionConfig config = AgentRuntimeTuning.buildCompactionConfig(props);
 
-        assertEquals(6, config.getTriggerMessages());
-        assertEquals(8000, config.getReserved());
         assertEquals(500, config.getTruncateArgsConfig().getMaxArgLength());
     }
 
@@ -71,13 +99,12 @@ class AgentRuntimeTuningTest {
     }
 
     @Test
-    @DisplayName("工具结果驱逐:maxResultChars 映射到框架配置")
-    void evictionConfig() {
-        AgentProperties props = new AgentProperties();
-        props.getToolResultEviction().setMaxResultChars(12345);
-
-        ToolResultEvictionConfig config = AgentRuntimeTuning.buildToolResultEvictionConfig(props);
-
-        assertEquals(12345, config.getMaxResultChars());
+    @DisplayName("工具结果驱逐:阈值按窗口 8%(tokens × 4 chars)计算")
+    void evictionConfigScalesWithWindow() {
+        assertEquals(83886, AgentRuntimeTuning.buildToolResultEvictionConfig(262144).getMaxResultChars());
+        assertEquals(20972, AgentRuntimeTuning.buildToolResultEvictionConfig(65536).getMaxResultChars());
+        // 1M 窗口封顶 200K 字符;8K 窗口保底 8K 字符
+        assertEquals(200000, AgentRuntimeTuning.buildToolResultEvictionConfig(1048576).getMaxResultChars());
+        assertEquals(8000, AgentRuntimeTuning.buildToolResultEvictionConfig(8192).getMaxResultChars());
     }
 }

+ 61 - 0
ai-server/src/test/java/com/zsjz/ai/module/agent/service/AgentModelFactoryTest.java

@@ -0,0 +1,61 @@
+package com.zsjz.ai.module.agent.service;
+
+import com.zsjz.ai.module.agent.entity.AgentModel;
+import io.agentscope.core.model.Model;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * {@link AgentModelFactory} 的模型字段映射测试。
+ *
+ * <p>核心口径:模型页选择的 {@code contextWindowSize} 必须真正下发到 Model,
+ * 否则框架拿不到窗口,压缩触发线会退化为 64k 兜底。
+ */
+class AgentModelFactoryTest {
+
+    private final AgentModelFactory factory = new AgentModelFactory();
+
+    @Test
+    @DisplayName("context_window_size 下发到模型实例")
+    void contextWindowFromField() {
+        Model model = factory.create(model("{\"enableThinking\":true}", 128000));
+
+        assertEquals(128000, model.getContextWindowSize());
+    }
+
+    @Test
+    @DisplayName("未配置窗口:统一按默认 256K 下发(不再按厂商/模型名推断)")
+    void contextWindowMissingUsesDefault() {
+        Model model = factory.create(model("{\"enableThinking\":true}", null));
+
+        assertEquals(262144, model.getContextWindowSize());
+    }
+
+    @Test
+    @DisplayName("0 / 过小窗口:按默认 256K 处理")
+    void invalidContextWindowUsesDefault() {
+        assertEquals(262144, factory.create(model("{}", 0)).getContextWindowSize());
+        assertEquals(262144, factory.create(model("{}", 512)).getContextWindowSize());
+    }
+
+    @Test
+    @DisplayName("config 非法:不影响窗口字段与模型创建")
+    void invalidConfigDoesNotBreak() {
+        assertEquals(128000, factory.create(model("not-json", 128000)).getContextWindowSize());
+    }
+
+    private static AgentModel model(String config, Integer contextWindowSize) {
+        AgentModel model = new AgentModel();
+        model.setProvider("Ollama");
+        model.setModelId("qwen");
+        model.setName("qwen-test");
+        model.setType("llm");
+        model.setApiKey("test-key");
+        model.setBaseUrl("http://127.0.0.1:11434/v1");
+        model.setConfig(config);
+        model.setContextWindowSize(contextWindowSize);
+        return model;
+    }
+}