Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat:auto模式真切换

jdfff594e7b126735
diff --git a/jiuwenswarm/agents/harness/common/rails/model_routing/__init__.py b/jiuwenswarm/agents/harness/common/rails/model_routing/__init__.py
index 160531b5e6..abb9da5c62 100644
--- a/jiuwenswarm/agents/harness/common/rails/model_routing/__init__.py
+++ b/jiuwenswarm/agents/harness/common/rails/model_routing/__init__.py
@@ -1,4 +1,4 @@
-"""ModelRoutingRail package — 四档模式(写死)模型路由。"""
+"""ModelRoutingRail package — auto 档分类器模型路由。"""
from __future__ import annotations
from .capability import ModelCapability, build_capability_table_from_config
diff --git a/jiuwenswarm/agents/harness/common/rails/model_routing/classifier.py b/jiuwenswarm/agents/harness/common/rails/model_routing/classifier.py
new file mode 100644
index 0000000000..8c059d5864
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/model_routing/classifier.py
@@ -0,0 +1,423 @@
+"""model_routing.classifier — auto 档任务分类器(自包含)。
+
+混合策略:规则引擎为主(chat / summarization 强项),TF-IDF 质心兜底
+(reasoning / coding / format 强项)。判定顺序:
+
+ 1. 续写/确认指令(is_continuation_utterance)→ 短路返回哨兵,rail 跳过重路由
+ 2. summarization 专项关键词命中 → 直接 summarization
+ 3. 规则引擎有命中 → 用规则结果
+ 4. 规则无命中 → TF-IDF 质心余弦:reasoning/coding/format 需 >= _TFIDF_HIGH_CONF,
+ chat 需 >= _TFIDF_CHAT_CONF,更低置信度一律兜底 chat
+
+score = SCORE_TABLE[(category, difficulty)];缺项按难度兜底(DEFAULT_SCORE_BY_DIFFICULTY),
+再缺兜底 DEFAULT_SCORE_FALLBACK。规则 / 阈值 / score 表硬编码在本模块,TF-IDF 语料在同目录
+classifier_corpus.py;两个引擎在首次 classify 时惰性构建并缓存。
+"""
+from __future__ import annotations
+
+import math
+import re
+from collections import Counter
+from typing import Any
+
+from jiuwenswarm.common.utils import logger as _log
+
+from .classifier_corpus import CATEGORY_UTTERANCES
+
+# 兜底分:category 无法识别时按难度给分;难度也无法识别时用最终兜底。
+DEFAULT_SCORE_BY_DIFFICULTY: dict[str, int] = {"easy": 25, "medium": 40, "hard": 60}
+DEFAULT_SCORE_FALLBACK: int = 60
+
+# 续写/确认哨兵:多轮对话里「继续 / 好的」不该触发换模型,classify 前先短路。
+CONTINUATION_CATEGORY = "continuation"
+CONTINUATION_SCORE = -1
+
+# 纯续写/确认短语(骨架形式:已去标点/空白/小写,并去掉「请 / please」)。
+_CONTINUATION_PHRASES: frozenset[str] = frozenset(
+ {
+ "继续", "继续吧", "继续做", "继续写", "继续改", "继续优化", "继续加油", "继续往下",
+ "接着", "接着来", "接着做", "接着写", "往下", "往下走",
+ "同意", "好的", "好", "行", "可以", "嗯", "对", "是", "是的", "没错", "就这样", "可以了",
+ "continue", "goahead", "goon", "proceed", "keepgoing", "keepitup", "carryon", "pleasecontinue",
+ "ok", "okay", "yes", "yep", "yeah", "sure", "agreed", "agree", "right", "correct", "gotit",
+ }
+)
+
+# 中文续写前缀只认短形式(继续 + ≤2 字补语);「继续优化这个函数」这类带实义的长句不算续写。
+_CONTINUATION_PREFIXES_ZH: tuple[str, ...] = ("继续", "接着", "往下")
+_CONTINUATION_PREFIX_MAX_LEN = 4
+
+# 「确认词 + 续写动词」组合:好继续 / 对继续 / 好的请继续 …
+_CONFIRMATION_LEADERS: frozenset[str] = frozenset(
+ {"对", "好", "好的", "行", "可以", "嗯", "是", "是的", "没错", "同意",
+ "ok", "okay", "yes", "yeah", "sure", "right", "correct", "gotit", "agreed"}
+)
+_CONTINUATION_ACTIONS: frozenset[str] = frozenset(
+ {"继续", "接着", "往下", "continue", "goahead", "goon", "proceed"}
+)
+
+_STRIP_CHARS = " \t\r\n 。.!?!?.,,、;;::…~~-—_'\"`()()[]【】"
+
+
+def _skeleton(text: str) -> str:
+ """去空白与标点、转小写,返回精确匹配用的骨架。"""
+ s = (text or "").strip().lower()
+ return "".join(ch for ch in s if ch not in _STRIP_CHARS and not ch.isspace())
+
+
+def _strip_polite_prefix(s: str) -> str:
+ """去掉开头的「请 / please」敬语前缀(如「请继续」「please continue」)。"""
+ while s.startswith("请"):
+ s = s[1:]
+ while s.startswith("please"):
+ s = s[len("please"):]
+ return s
+
+
+def is_continuation_utterance(text: str) -> bool:
+ """是否为纯续写/确认指令(骨架去掉「请 / please」后精确匹配)。
+
+ 命中任一即算:① 精确短语(继续 / 好的 / ok / continue …);② 短中文续写前缀
+ (继续X,X ≤ 2 字);③ 「确认词 + 续写动词」组合(好继续 / 好的请继续 …)。
+ """
+ s = _skeleton(text)
+ if not s:
+ return False
+ s = _strip_polite_prefix(s)
+ if not s:
+ return False
+ if s in _CONTINUATION_PHRASES:
+ return True
+ if len(s) <= _CONTINUATION_PREFIX_MAX_LEN and s.startswith(_CONTINUATION_PREFIXES_ZH):
+ return True
+ for lead in _CONFIRMATION_LEADERS:
+ if s.startswith(lead) and _strip_polite_prefix(s[len(lead):]) in _CONTINUATION_ACTIONS:
+ return True
+ return False
+
+
+# --------------------------------------------------------------------------- #
+# 分类数据
+# --------------------------------------------------------------------------- #
+
+CATEGORIES: tuple[str, ...] = ("chat", "reasoning", "coding", "summarization", "format")
+
+DIFFICULTIES: tuple[str, ...] = ("easy", "medium", "hard")
+
+SCORE_TABLE: dict[tuple[str, str], int] = {
+ ("chat", "easy"): 5, ("chat", "medium"): 20, ("chat", "hard"): 40,
+ ("reasoning", "easy"): 20, ("reasoning", "medium"): 40, ("reasoning", "hard"): 60,
+ ("coding", "easy"): 25, ("coding", "medium"): 45, ("coding", "hard"): 65,
+ ("summarization", "easy"): 15, ("summarization", "medium"): 25, ("summarization", "hard"): 45,
+ ("format", "easy"): 5, ("format", "medium"): 10, ("format", "hard"): 30,
+}
+
+# 规则表:(id, 正则, category | None, category 分, difficulty | None, difficulty 分)。
+# category 分可为负(negate.* 抵消误判);difficulty 为 None 表示该规则只判类别。
+RULES: list[tuple[str, str, str | None, int, str | None, int]] = [
+ ("coding.write_program",
+ r"(?i)\b(write|implement|build|create|develop|design)\s+(a|an|the|this)?\s{0,3}(function|class|module|program|scri"
+ r"pt|algorithm|app|service|api|method|sort|sorting|search|searching)\b",
+ "coding", 3, "medium", 1),
+ ("coding.debug_fix",
+ r"(?i)\b(debug|fix|refactor|optimize|troubleshoot)\s+(this|the|a)?\s{0,3}(bug|error|issue|code|function|problem|cr"
+ r"ash|exception)\b",
+ "coding", 3, "hard", 2),
+ ("coding.chinese", r"(?i)(代码|编程|写代码|调试|重构|实现|修复|报错|算法|排序|函数|变量)", "coding", 2, None, 0),
+ ("coding.bare_error", r"(?i)\b(bug|error|exception|crash|syntax)\b", "coding", 1, None, 0),
+ ("coding.bare_generic", r"(?i)\b(code|program|script|compile|runtime)\b", "coding", 1, None, 0),
+ ("reasoning.prove", r"(?i)\b(prove|demonstrate|verify)\s+that\b", "reasoning", 3, "hard", 3),
+ ("reasoning.analyze",
+ r"(?i)\b(analyze|examine|investigate|evaluate)\s+(the|this|a)?\s{0,3}(problem|issue|data|pattern|trend|relationshi"
+ r"p|situation)\b",
+ "reasoning", 3, "hard", 2),
+ ("reasoning.compare", r"(?i)\b(compare|contrast)\s+(and|with|between)\b", "reasoning", 2, "hard", 1),
+ ("reasoning.chinese", r"(?i)(证明|推理|论证|分析|演绎|推导|比较|评估|逻辑)", "reasoning", 2, None, 0),
+ ("reasoning.bare", r"(?i)\b(math|logic|reason|deduce)\b", "reasoning", 1, None, 0),
+ ("reasoning.arithmetic", r"\d+[\+\-\*/\^]\d+", "reasoning", 1, None, 0),
+ ("summarize.action",
+ r"(?i)\b(summarize|condense|compress|abridge)\s+(this|the|a)?\s{0,3}(article|text|document|report|paper|book|conte"
+ r"nt|meeting)\b",
+ "summarization", 3, None, 0),
+ ("summarize.keyword", r"(?i)\b(tldr|总结|摘要|概括|提炼)\b", "summarization", 3, None, 0),
+ ("summarize.partial", r"(?i)\b(key\s+points|main\s+ideas|要点|概述|overview)\b", "summarization", 2, None, 0),
+ ("summarize.bare", r"(?i)\b(brief|abstract)\b", "summarization", 1, None, 0),
+ ("format.convert",
+ r"(?i)\b(convert|transform|translate)\s+\w+(\s+\w+){0,3}\s+(to|into|as)\s+\w+",
+ "format", 3, None, 0),
+ ("format.reformat",
+ r"(?i)\b(format|rewrite|rephrase)\s+(this|the|data)?\s{0,3}(as|to|into)\b",
+ "format", 3, None, 0),
+ ("format.chinese", r"(?i)(格式化|转换|翻译|改写|排版)", "format", 2, None, 0),
+ ("format.bare_format_name", r"(?i)\b(json|csv|xml|yaml|markdown)\b", "format", 1, None, 0),
+ ("chat.greeting",
+ r"(?i)^(hello|hi|hey|你好|嗨|good\s+(morning|afternoon|evening)|greetings|yo|sup)\b",
+ "chat", 3, "easy", 2),
+ ("chat.factual", r"(?i)^(what|who|where|when|how)\s+(is|are|was|were|does|do|can)\b", "chat", 2, "easy", 2),
+ ("chat.casual",
+ r"(?i)\b(how\s+are\s+you|what'?s\s+up|nice\s+to\s+meet|let'?s\s+(chat|talk|hang)|just\s+(chatting|talking|wonderin"
+ r"g)|casual\s+(chat|conversation))\b",
+ "chat", 3, "easy", 1),
+ ("chat.roleplay",
+ r"(?i)\b(pretend|act\s+as|roleplay|imagine\s+(you|yourself)|embrace\s+the\s+role|assume\s+the\s+role)\b",
+ "chat", 3, "medium", 1),
+ ("chat.opinion",
+ r"(?i)\b(what\s+(do|is)\s+your\s+(opinion|favorite|thought)|do\s+you\s+(prefer|like|think|believe)|recommend\s+(a|"
+ r"me|some))\b",
+ "chat", 3, "easy", 1),
+ ("chat.compose_letter",
+ r"(?i)\b(draft|compose|write)\s+(a|an)?\s*(professional\s+)?(email|letter|blog\s+post|message)\b",
+ "chat", 2, "medium", 1),
+ ("chat.chinese", r"(?i)(聊天|闲聊|什么是|介绍一下|随便聊聊|怎么样|聊聊|推荐|你觉|想聊|聊聊|心情|爱好|认识)", "chat", 2, None, 0),
+ ("chat.feeling",
+ r"(?i)\b(I'?m\s+(feeling|bored|happy|sad|tired|excited|looking\s+for)|what\s+should\s+I\s+do|tell\s+me\s+a\s+joke)"
+ r"\b",
+ "chat", 2, "easy", 1),
+ ("chat.tell_me",
+ r"(?i)\b(tell\s+me\s+about|help\s+me\s+(understand|find|choose)|can\s+you\s+(recommend|suggest|give\s+me))\b",
+ "chat", 1, None, 0),
+ ("chat.bare", r"(?i)\b(what\s+about|how\s+about|any\s+(idea|suggestion|recommendation))\b", "chat", 1, None, 0),
+ ("negate.write_creative",
+ r"(?i)\b(write|create|compose)\s+a\s+(poem|story|essay|letter|song|novel|小说|故事|诗歌|文章)\b",
+ "coding", -3, None, 0),
+ ("negate.realize_dream", r"(?i)(实现)(梦想|愿望|目标|理想)", "coding", -2, None, 0),
+ ("diff.easy", r"(?i)\b(quick|simple|briefly|简单|定义)\b", None, 0, "easy", 2),
+ ("diff.medium", r"(?i)\b(explain|describe|说明|详细|阐述)\b", None, 0, "medium", 2),
+ ("diff.hard", r"(?i)\b(complex|complicated|advanced|复杂|架构)\b", None, 0, "hard", 2),
+]
+
+LENGTH_SIGNAL: dict[str, int] = {
+ "easy_threshold": 20,
+ "medium_threshold": 80,
+ "adjustment_weight": 1
+}
+
+DEFAULTS: dict[str, str] = {
+ "no_hit_category": "chat"
+}
+
+
+# --------------------------------------------------------------------------- #
+# 分类逻辑
+# --------------------------------------------------------------------------- #
+
+# TF-IDF 置信度阈值:reasoning/coding/format 需高置信度才采纳,chat 中等即可。
+_TFIDF_HIGH_CONF = 0.05
+_TFIDF_CHAT_CONF = 0.03
+
+# summarization 专项关键词(优先级最高,命中即判定,不看规则 / TF-IDF)。
+_SUMM_PAT = re.compile(
+ r"(?i)(summar|tldr|condense|compress|extract.*(key|main|point|idea)"
+ r"|overview|takeaway|gist|abstract|brief.*(overview|summary|description)"
+ r"|总结|摘要|概括|提炼|概述|要点)",
+)
+
+_WORD_PAT = re.compile(r"[a-zA-Z]{2,}")
+_NUM_PAT = re.compile(r"\d+")
+_CJK_PAT = re.compile(r"[一-鿿㐀-䶿]+")
+
+# 编译后的规则:(正则, category | None, category 分, difficulty | None, difficulty 分)
+_CompiledRule = tuple[re.Pattern, str | None, int, str | None, int]
+
+_compiled_rules: list[_CompiledRule] | None = None
+_tfidf_engine: tuple[dict[str, float], dict[str, dict[str, float]]] | None = None
+
+_ASCII_WORD_START = r"(?<![A-Za-z0-9_])"
+_ASCII_WORD_END = r"(?![A-Za-z0-9_])"
+
+
+def _ascii_word_boundaries(pattern: str) -> str:
+ r"""把规则里的 ``\b`` 换成 ASCII-only 词边界环视。
+
+ Python 的 ``\b`` 以 ``\w`` 定义,而 Unicode 模式下 ``\w`` 把 CJK 也算词字符 ——
+ ``\b复杂\b`` 在「很复杂的系统」里永不命中(很/复 都是词字符,其间无边界),中文提示词
+ 因此几乎拿不到 hard 档。换成「非 ``[A-Za-z0-9_]``」环视后 CJK 关键词正常命中,英文语义
+ 与 ``\b`` 等价。本模块规则均为 ``\b(...)\b`` / ``\b...\b`` 形,故组首的 ``\b``(其后是
+ 字面量或 ``(``)判为起始边界,其余判为结束边界。
+ """
+ out: list[str] = []
+ i, n = 0, len(pattern)
+ while i < n:
+ if pattern.startswith(r"\b", i):
+ nxt = pattern[i + 2] if i + 2 < n else ""
+ out.append(_ASCII_WORD_END if nxt in (")", "") else _ASCII_WORD_START)
+ i += 2
+ continue
+ out.append(pattern[i])
+ i += 1
+ return "".join(out)
+
+
+def _rules() -> list[_CompiledRule]:
+ """编译并缓存规则引擎(首次调用时编译;单条规则编译失败只告警、不中断)。"""
+ global _compiled_rules
+ if _compiled_rules is None:
+ compiled: list[_CompiledRule] = []
+ for rule_id, pattern, cat, cat_score, diff, diff_score in RULES:
+ try:
+ compiled.append((re.compile(_ascii_word_boundaries(pattern)), cat, cat_score, diff, diff_score))
+ except re.error as exc:
+ _log.warning("[ModelRouting] rule %s compile failed: %s", rule_id, exc)
+ _compiled_rules = compiled
+ _log.info("[ModelRouting] hybrid: rule engine compiled: %d rules", len(compiled))
+ return _compiled_rules
+
+
+def _tokenize(text: str) -> list[str]:
+ """英文词(≥2 字母,小写)+ 数字 + 中文串(整串与单字都入袋)。"""
+ tokens = [w.lower() for w in _WORD_PAT.findall(text)]
+ tokens.extend(_NUM_PAT.findall(text))
+ for seq in _CJK_PAT.findall(text):
+ if len(seq) >= 2:
+ tokens.append(seq)
+ tokens.extend(seq)
+ return tokens
+
+
+def _tfidf() -> tuple[dict[str, float], dict[str, dict[str, float]]]:
+ """构建并缓存 (idf, 各类别质心)(首次调用时构建)。"""
+ global _tfidf_engine
+ if _tfidf_engine is None:
+ all_docs: list[list[str]] = []
+ cat_token_lists: dict[str, list[list[str]]] = {}
+ for cat, utterances in CATEGORY_UTTERANCES.items():
+ cat_token_lists[cat] = [_tokenize(u) for u in utterances]
+ all_docs.extend(cat_token_lists[cat])
+ n_docs = len(all_docs)
+ df: Counter = Counter()
+ for doc_tokens in all_docs:
+ for token in set(doc_tokens):
+ df[token] += 1
+ idf = {t: math.log((n_docs + 1) / (count + 1)) for t, count in df.items()}
+ centroids: dict[str, dict[str, float]] = {}
+ for cat, token_lists in cat_token_lists.items():
+ term_freq: Counter = Counter()
+ for tokens in token_lists:
+ term_freq.update(tokens)
+ n = len(token_lists)
+ centroids[cat] = {t: (term_freq[t] / n) * idf.get(t, 0) for t in term_freq}
+ _tfidf_engine = (idf, centroids)
+ _log.info(
+ "[ModelRouting] hybrid: TF-IDF engine built: %d categories, %d IDF terms",
+ len(centroids),
+ len(idf),
+ )
+ return _tfidf_engine
+
+
+def _cosine(v1: dict[str, float], v2: dict[str, float]) -> float:
+ """稀疏向量余弦相似度(任一范数为 0 → 0.0)。"""
+ shared = set(v1) & set(v2)
+ if not shared:
+ return 0.0
+ dot = sum(v1[t] * v2[t] for t in shared)
+ norm1 = math.sqrt(sum(v * v for v in v1.values()))
+ norm2 = math.sqrt(sum(v * v for v in v2.values()))
+ if norm1 == 0 or norm2 == 0:
+ return 0.0
+ return dot / (norm1 * norm2)
+
+
+def _tfidf_classify(prompt_text: str) -> tuple[str, float]:
+ """质心余弦打分 → (最高分类别, 得分)。同分取质心插入序最前者。"""
+ idf, centroids = _tfidf()
+ query_tf = Counter(_tokenize(prompt_text))
+ query_vec = {t: query_tf[t] * idf[t] for t in query_tf if t in idf}
+ scores = {cat: _cosine(query_vec, centroid) for cat, centroid in centroids.items()}
+ if not scores:
+ return "chat", 0.0
+ return max(scores, key=scores.get), max(scores.values())
+
+
+def _count_tokens(prompt_text: str) -> int:
+ """token 数(TiktokenCounter 不可用时按 4 字符 / token 粗估)。"""
+ try:
+ from openjiuwen.core.context_engine import TiktokenCounter
+
+ return int(TiktokenCounter().count(prompt_text))
+ except Exception:
+ return max(1, len(prompt_text) // 4)
+
+
+def _lookup_score(category: str, difficulty: str, score_table: dict, default_score: dict) -> int:
+ """查 SCORE_TABLE → 难度默认分 → 最终兜底。"""
+ value = (score_table or {}).get((category, difficulty))
+ if value is not None:
+ return value
+ return (default_score or DEFAULT_SCORE_BY_DIFFICULTY).get(difficulty, DEFAULT_SCORE_FALLBACK)
+
+
+def validate_score(raw: Any) -> int:
+ """校验 classify 返回的 score:必须是 0-100 的数值;否则兜底 60。"""
+ try:
+ value = int(raw)
+ except (TypeError, ValueError):
+ return DEFAULT_SCORE_FALLBACK
+ if value < 0 or value > 100:
+ return DEFAULT_SCORE_FALLBACK
+ return value
+
+
+async def classify(prompt_text: str) -> tuple[int, str, str]:
+ """给任务打分 → (score, category, difficulty)。
+
+ 续写/确认指令短路返回 (CONTINUATION_SCORE, CONTINUATION_CATEGORY, "skip"),
+ 由 rail 判定为「保留当前模型」。
+ """
+ if is_continuation_utterance(prompt_text):
+ _log.info("[ModelRouting] classifier continuation guard: prompt=%r", str(prompt_text)[:40])
+ return CONTINUATION_SCORE, CONTINUATION_CATEGORY, "skip"
+
+ category_scores: dict[str, int] = {c: 0 for c in CATEGORIES}
+ difficulty_scores: dict[str, int] = {d: 0 for d in DIFFICULTIES}
+ for pattern, cat, cat_score, diff, diff_score in _rules():
+ if not pattern.search(prompt_text):
+ continue
+ if cat is not None:
+ category_scores[cat] = category_scores.get(cat, 0) + cat_score
+ if diff is not None:
+ difficulty_scores[diff] = difficulty_scores.get(diff, 0) + diff_score
+
+ token_count = _count_tokens(prompt_text)
+ easy_threshold = LENGTH_SIGNAL.get("easy_threshold", 20)
+ medium_threshold = LENGTH_SIGNAL.get("medium_threshold", 80)
+ if token_count > medium_threshold:
+ difficulty_scores["hard"] += 1
+ elif token_count > easy_threshold:
+ difficulty_scores["medium"] += 1
+
+ rule_has_hit = any(v > 0 for v in category_scores.values())
+ if rule_has_hit:
+ rule_category = max(category_scores, key=category_scores.get)
+ else:
+ rule_category = DEFAULTS.get("no_hit_category", "chat")
+
+ if all(v == 0 for v in difficulty_scores.values()):
+ if token_count > medium_threshold:
+ difficulty = "hard"
+ elif token_count > easy_threshold:
+ difficulty = "medium"
+ else:
+ difficulty = "easy"
+ else:
+ difficulty = max(difficulty_scores, key=difficulty_scores.get)
+
+ if _SUMM_PAT.search(prompt_text):
+ category = "summarization"
+ elif rule_has_hit:
+ category = rule_category
+ else:
+ tfidf_category, tfidf_conf = _tfidf_classify(prompt_text)
+ if tfidf_category in ("reasoning", "coding", "format") and tfidf_conf >= _TFIDF_HIGH_CONF:
+ category = tfidf_category
+ elif tfidf_category == "chat" and tfidf_conf >= _TFIDF_CHAT_CONF:
+ category = "chat"
+ else:
+ category = "chat" # TF-IDF 低置信度 → 默认 chat
+
+ score = _lookup_score(category, difficulty, SCORE_TABLE, DEFAULT_SCORE_BY_DIFFICULTY)
+ _log.debug(
+ "[ModelRouting] hybrid classifier: %s/%s score=%d (rule_hit=%s rule_cat=%s)",
+ category, difficulty, score, rule_has_hit, rule_category,
+ )
+ return score, category, difficulty
diff --git a/jiuwenswarm/agents/harness/common/rails/model_routing/classifier_corpus.py b/jiuwenswarm/agents/harness/common/rails/model_routing/classifier_corpus.py
new file mode 100644
index 0000000000..5100ed8ee8
--- /dev/null
+++ b/jiuwenswarm/agents/harness/common/rails/model_routing/classifier_corpus.py
@@ -0,0 +1,122 @@
+"""model_routing.classifier_corpus — TF-IDF 训练语料(纯数据,无逻辑)。
+
+仅被 classifier.py 用于构建每个类别的 TF-IDF 质心;**键顺序即类别判定同分时的
+tie-break 顺序**,改动会改变同分下的分类结果。
+
+语料为**最小种子集**(每类 20 条短句,中英混排):当前阶段只要求“能切档”,
+不追求分类精度,故不再携带原始大语料;每条一行、不超行宽,便于 review。
+"""
+from __future__ import annotations
+
+CATEGORY_UTTERANCES: dict[str, list[str]] = {
+ "reasoning": [
+ "Solve for x: 3x + 7 = 22, showing each step of the derivation.",
+ "Prove that the square root of 2 is irrational.",
+ "If all roses are flowers and some flowers fade quickly, do some roses fade?",
+ "A train leaves at 9:00 at 60 km/h. When does it cover 210 km?",
+ "Explain step by step why the sum of two odd numbers is always even.",
+ "What is the next number in the sequence 2, 6, 12, 20, 30?",
+ "How many distinct ways can you arrange the letters of the word LEVEL?",
+ "Reason through this logic puzzle and justify every deduction.",
+ "Calculate the probability of drawing two aces from a standard deck.",
+ "Derive the quadratic formula starting from ax^2 + bx + c = 0.",
+ "Is this conclusion deductively valid? Explain why or why not.",
+ "Which of these two arguments is logically sound, and why?",
+ "Estimate the answer first, then explain how you reasoned about it.",
+ "Break this word problem into equations, then solve it.",
+ "What assumptions did you make in your answer, and are they valid?",
+ "请逐步推导这个数学证明。",
+ "帮我算一下这道概率题,要写清推理过程。",
+ "逻辑推理:三个人里只有一个人说真话,谁在说谎?",
+ "这道题的解题思路是什么?请一步一步分析。",
+ "证明勾股定理,给出完整推导过程。",
+ ],
+ "summarization": [
+ "Summarize this article in three bullet points.",
+ "Give me a TL;DR of the following report.",
+ "Condense these meeting notes into the key decisions.",
+ "Extract the main points from this research paper.",
+ "Write a brief overview of the attached document.",
+ "What are the key takeaways from this transcript?",
+ "Reduce this long email to two sentences.",
+ "Summarize the customer feedback and flag recurring themes.",
+ "Provide a short abstract of the study below.",
+ "Pull the action items out of these minutes.",
+ "Summarize the changelog for a non-technical reader.",
+ "Condense this thread into a single paragraph.",
+ "List the main arguments and what each one concludes.",
+ "Give me the gist of this contract in plain language.",
+ "Distill this incident report into a short timeline.",
+ "请总结这篇文章的要点。",
+ "把这份报告浓缩成一段话。",
+ "概括一下这次会议的结论。",
+ "提炼这段对话的核心诉求。",
+ "用三句话概述这份文档。",
+ ],
+ "coding": [
+ "Write a function that reverses a linked list.",
+ "Implement quicksort in Python.",
+ "Fix the bug in this JavaScript snippet.",
+ "Refactor this class to use dependency injection.",
+ "Write unit tests for the parse_config function.",
+ "Explain what this regex matches, then simplify it.",
+ "Build a REST endpoint for user registration.",
+ "Why does this code throw a NullPointerException?",
+ "Optimize this SQL query and explain the plan.",
+ "Convert this Python 2 script to Python 3.",
+ "Add retry and error handling to this HTTP client.",
+ "Generate a Dockerfile for a Node application.",
+ "Implement binary search together with its tests.",
+ "Trace this stack trace back to the root cause.",
+ "What is the time complexity of this function?",
+ "帮我写一个快速排序函数。",
+ "这段代码报错了,帮我看看怎么修。",
+ "用 TypeScript 实现一个防抖函数。",
+ "把这个函数重构成更清晰的结构。",
+ "写一个正则匹配邮箱地址。",
+ ],
+ "chat": [
+ "你好",
+ "hello",
+ "今天天气怎么样?",
+ "给我讲个笑话吧。",
+ "你是谁?",
+ "What can you help me with?",
+ "推荐几部好看的电影。",
+ "谢谢你的帮助!",
+ "聊聊你最喜欢的季节。",
+ "Help me pick a name for my cat.",
+ "早上好,今天有什么安排?",
+ "Tell me something interesting about space.",
+ "你怎么看远程办公这件事?",
+ "周末去哪儿玩比较好?",
+ "Give me a fun fact about octopuses.",
+ "我有点累,说点轻松的。",
+ "What is a good podcast to start with?",
+ "随便聊聊吧。",
+ "How do you usually spend your mornings?",
+ "有什么好喝的咖啡推荐吗?",
+ ],
+ "format": [
+ "Convert this JSON to CSV.",
+ "把这段 JSON 转成 CSV。",
+ "Reformat the following list as a Markdown table.",
+ "Return the result as valid JSON only, with no prose.",
+ "Extract all dates and output them as YYYY-MM-DD.",
+ "Normalize this address into separate fields.",
+ "Translate this to French and keep the formatting.",
+ "Parse this log line into key=value pairs.",
+ "Format the output as a bulleted list.",
+ "Convert this YAML into TOML.",
+ "Escape the quotes so the string stays valid JSON.",
+ "Split this paragraph into one sentence per line.",
+ "Map these column names to snake_case.",
+ "Render this data as an HTML table.",
+ "Output CSV with a header row.",
+ "把这段文本转成表格。",
+ "输出成 JSON 数组,不要多余解释。",
+ "把这些行按字母顺序重排。",
+ "把这段内容整理成编号清单。",
+ "从这段话里抽出人名和地名,输出 JSON。",
+ ],
+}
diff --git a/jiuwenswarm/agents/harness/common/model_gears.py b/jiuwenswarm/agents/harness/common/rails/model_routing/compressor_sync.py
similarity index 63%
rename from jiuwenswarm/agents/harness/common/model_gears.py
rename to jiuwenswarm/agents/harness/common/rails/model_routing/compressor_sync.py
index 4317d50c31..f9085324f8 100644
--- a/jiuwenswarm/agents/harness/common/model_gears.py
+++ b/jiuwenswarm/agents/harness/common/rails/model_routing/compressor_sync.py
@@ -1,67 +1,26 @@
-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+"""主对话换模后,把仍攥着旧 ``Model`` 的下游组件一起换掉。
-"""四档模式(model gear)关键字 → 具体模型 id 的唯一映射源。
+根因:``ContextProcessorRail.init`` 在 agent 创建时把 ``model_config`` 烤进
+DialogueCompressor / RoundLevelCompressor 等实例;随后 ``ModelRoutingRail`` /
+``interface_deep._apply_model_to_react_agent`` 只 ``set_llm`` 主对话模型,**不**更新
+已缓存的 context pool 里的压缩器。结果主对话已是具体模型,压缩器仍拿着过期 id →
+上游报模型无效,压缩 noop,上下文膨胀。
-前端把 ``fast`` / ``balanced`` / ``extreme`` / ``auto`` 这四个「档位关键字」当作
-``model_name`` 下发,由 :class:`ModelRoutingRail` 在**单 agent 主链路**里翻成具体
-模型 id(读 request param 注入的 ``run_context.extra["model_selection"]``)。
+会话记忆(``SessionMemoryManager``)不在 context processor 列表里。这里只重绑当初
+从主模型继承来的 ``memory.model`` / ``model_client``,并清掉已缓存的 update agent。
+调用方显式配置的记忆模型不会被覆盖。
-但档位关键字还有第二条通道:宿主把它原样写进有效模型 env → sidecar 的
-``MODEL_NAME`` → 租户 tip / ``config.yaml``。**这条通道不经过任何 rail**。于是
-任何只吃 env 派生配置、没有 rail 也没有 request params 的消费方(典型:
-DeepResearch 隔离子进程)会拿到裸档位关键字,当真实模型名直送上游网关 →
-模型不存在 / Invalid model 类错误。
-
-本模块是那张表的唯一出处:rail 与 deepresearch 共用,保证两侧同表同源不漂移。
-放在 ``common/`` 顶层是为了让 deepresearch 侧能干净地 import ——
-``rails/`` 包的 ``__init__`` 会连带拉起 team/symphony 等重依赖,不能进隔离链路。
+本模块原先住在 ``common/model_gears.py``(那张「档位关键字 → 具体模型 id」的表)。
+档位翻译整体收回 relay 侧后,四档表连同 ``model_gears`` 一起删除;换模同步压缩器
+与档位无关,故单独迁到这里,由 rail 与 adapter 共用。
"""
from __future__ import annotations
import importlib
-import logging
-
-logger = logging.getLogger(__name__)
-
-# 模式名 → 固定模型名。与宿主产品侧档位表同表同源;勿擅自改 id。
-MODE_MODEL_MAP: dict[str, str] = {
- "fast": "deepseek-v4.1-flash",
- "balanced": "deepseek-v4.1-flash",
- "extreme": "glm-5.2",
- "auto": "deepseek-v4.1-flash",
-}
-
-# 当前已支持的档位关键字集合(新增档位时同步改本表,并与宿主产品侧映射对齐)。
-MODEL_GEAR_NAMES: frozenset[str] = frozenset(MODE_MODEL_MAP)
-
-# 模式名 → 思考深度。
-MODE_THINKING_MAP: dict[str, str] = {
- "fast": "off", # 关闭思考
- "balanced": "medium", # 中等思考
- "extreme": "deep", # 深度思考
- "auto": "medium", # 中等思考
-}
-
-# 四档写死映射里的「官方模型」标记:宿主写 models.json 时给官方供应商标记
-# ``model_provider``(见下方常量)。四档查找优先命中此标,避免撞到用户自定义的同名模型。
-MODE_PREFERRED_PROVIDER = "huawei_maas"
-
-
-def is_model_gear(name: object) -> bool:
- """``name`` 是否为档位关键字(忽略大小写与首尾空白)。"""
- return isinstance(name, str) and name.strip().lower() in MODE_MODEL_MAP
+from typing import Any
-
-def resolve_model_gear(name: str) -> str:
- """把档位关键字翻成具体模型 id;不是档位则原样返回(含原始空白)。
-
- 刻意比 rail 的 ``_MODE_MODEL_MAP.get(selection)`` 宽松一档(忽略大小写):
- 这里的入参来自 env,大小写不由本进程控制,宽松匹配只可能多翻、不会漏翻。
- """
- if not isinstance(name, str):
- return name
- return MODE_MODEL_MAP.get(name.strip().lower(), name)
+from jiuwenswarm.common.utils import logger
def _assign_attr(target: object, name: str, value: object) -> bool:
@@ -150,9 +109,8 @@ def _rebind_session_memory_managers(
"""换模后重绑继承自主模型的会话记忆。显式配置的 memory.model 保持不动。
``ContextProcessorRail`` 只在 ``memory.model is None`` 时把主模型对象抄进去,
- 之后 ``bind_model_defaults`` 不再覆盖。因此用对象身份判断「继承」;档位关键字
- 同样视为未显式配置。已惰性建出的 update agent / direct model 必须丢掉,否则
- 仍拿旧 ``Model`` 实例。
+ 之后 ``bind_model_defaults`` 不再覆盖。因此用对象身份判断「继承」。
+ 已惰性建出的 update agent / direct model 必须丢掉,否则仍拿旧 ``Model`` 实例。
"""
prev_config = getattr(previous_model, "model_config", None)
prev_client = getattr(previous_model, "model_client_config", None)
@@ -163,12 +121,11 @@ def _rebind_session_memory_managers(
continue
current_model = getattr(cfg, "model", None)
inherited_model = prev_config is not None and current_model is prev_config
- gear_model = is_model_gear(getattr(current_model, "model_name", None))
inherited_client = (
prev_client is not None and getattr(cfg, "model_client", None) is prev_client
)
# G.CTL.03: if 内布尔条件不超过 3 个,复合判断先收成变量
- rebind_model = inherited_model or gear_model
+ rebind_model = inherited_model
rebind_client = inherited_client or rebind_model
if not rebind_client:
continue
@@ -194,24 +151,14 @@ def _rebind_session_memory_managers(
def sync_agent_compressor_models(
- react_agent: object,
- model: object,
+ react_agent: Any,
+ model: Any,
*,
host: object | None = None,
previous_model: object | None = None,
) -> int:
"""把上下文压缩器绑到与主对话相同的 ``Model`` 实例。
- 根因:``ContextProcessorRail.init`` 在 agent 创建时把 ``model_config`` 烤进
- DialogueCompressor / RoundLevelCompressor 等实例;随后 ``ModelRoutingRail`` /
- ``_apply_model_to_react_agent`` 只 ``set_llm`` 主对话模型,**不**更新已缓存的
- context pool 里的压缩器。结果主对话已是具体模型,压缩器仍拿着档位关键字或
- 过期 id → 上游报模型无效,压缩 noop,上下文膨胀。
-
- 会话记忆(``SessionMemoryManager``)不在 context processor 列表里。这里只重绑
- 当初从主模型继承来的 ``memory.model`` / ``model_client``,并清掉已缓存的
- update agent。调用方显式配置的记忆模型不会被覆盖。
-
``host`` 是挂着 rail 的 DeepAgent;``previous_model`` 是 ``set_llm`` 之前的
主模型,用来识别继承来的配置对象。
diff --git a/jiuwenswarm/agents/harness/common/rails/model_routing/model_routing_rail.py b/jiuwenswarm/agents/harness/common/rails/model_routing/model_routing_rail.py
index 93c4cc091a..cdb3b2ed20 100644
--- a/jiuwenswarm/agents/harness/common/rails/model_routing/model_routing_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/model_routing/model_routing_rail.py
@@ -1,19 +1,16 @@
"""model_routing.rail — ModelRoutingRail."""
from __future__ import annotations
+import os
from dataclasses import asdict
from datetime import datetime, timezone
-from typing import Any, Optional
+from typing import Any, Callable, Optional
from openjiuwen.core.context_engine import TiktokenCounter
from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
from openjiuwen.harness.rails.base import DeepAgentRail
from jiuwenswarm.common.utils import logger
-from jiuwenswarm.agents.harness.common.model_gears import (
- MODE_MODEL_MAP,
- MODE_PREFERRED_PROVIDER,
- MODE_THINKING_MAP,
- sync_agent_compressor_models,
-)
from .capability import ModelCapability
+from .classifier import CONTINUATION_CATEGORY, validate_score
+from .compressor_sync import sync_agent_compressor_models
from .types import (
PriorModelCall, TaskAnalysis, RoutingDecision,
_agent_model_name, _extract_agent_info, _new_trace_id,
@@ -21,43 +18,60 @@ from .types import (
)
-# 四档模式(先写死):模式名 → 固定 (模型名, 思考深度)。
-# fast/balanced/auto → deepseek-v4.1-flash(思考 off/medium/medium)
-# extreme → glm-5.2(思考 deep)
-# 具体模型名不在此表内(走 skip 分支,保留 adapter 已应用的具体/默认模型)。
-# 与宿主产品侧档位映射同表同源(见 model_gears.MODE_MODEL_MAP)。
-# 表本体在 jiuwenswarm.agents.harness.common.model_gears(deepresearch 隔离子进程
-# 也要用同一张表把档位翻成具体模型),此处只做别名,避免两处各写一份漂移。
-_MODE_MODEL_MAP: dict[str, str] = MODE_MODEL_MAP
+# auto 档(relay 下发 enable_routing=True)的分类器阈值与切换目标:
+# 分类器给任务打 0-100 分,大于等于 40 才把模型换成 glm-5.3,否则保留当前模型。
+_CLASSIFIER_SCORE_THRESHOLD: int = 40
+_CLASSIFIER_TARGET_MODEL: str = "glm-5.3"
+
+# ``classifier`` 未显式传入时的哨兵,与显式 ``None``(关闭 auto 档路由)区分开。
+_UNSET: Any = object()
-_MODE_THINKING_MAP: dict[str, str] = MODE_THINKING_MAP
+# 懒加载的默认分类器缓存(``_UNSET`` 表示尚未装载)。
+_DEFAULT_CLASSIFIER: Any = _UNSET
-# 四档写死映射里的「官方模型」标记:宿主写 models.json 时给官方供应商标记
-# model_provider(见 model_gears.MODE_PREFERRED_PROVIDER;config.yaml 亦可手写)。
-# 四档查找优先命中此标,避免撞到用户自定义的同名模型;无标则退回第一个同名。
-_MODE_PREFERRED_PROVIDER = MODE_PREFERRED_PROVIDER
-# 四档附带的思考语义 → 产品 depth(再经 vendor_map 按模型族翻译)。
-# 具体模型 / default:仅 GLM-5.3 族自动注入产品默认 depth(当前 low);其余 no-op。
-_GEAR_THINKING_TO_DEPTH: dict[str, str] = {
- "off": "off",
- "medium": "medium",
- "deep": "high",
- "default": "default",
-}
+def model_routing_enabled(config: Any = None) -> bool:
+ """model_routing 总开关:config ``model_routing.enabled``(默认 false)+ env 覆盖。
+
+ 单一事实来源:单 agent adapter(``interface_deep._model_routing_enabled``)与 swarm
+ 成员 provider(``swarm.model_routing``)共用同一判定,避免两处各读一次开关而漂移。
+ relay 可经 spawn env 注入 ``JIUWENSWARM_MODEL_ROUTING_ENABLED``(进程级,仿
+ ``JIUWENSWARM_CODE_COAUTHOR_HEADER_ENABLED``);env 显式设置时优先于 config。
+ """
+ from jiuwenswarm.common.kv_cache_affinity_config import parse_bool
+
+ raw = config.get("model_routing") if isinstance(config, dict) else None
+ enabled = parse_bool(raw.get("enabled")) if isinstance(raw, dict) else False
+ env_val = os.getenv("JIUWENSWARM_MODEL_ROUTING_ENABLED")
+ if env_val is not None and env_val.strip():
+ enabled = parse_bool(env_val)
+ return enabled
+
+
+def _load_default_classifier() -> Optional[Any]:
+ """懒加载内置分类器(``.classifier.classify``),import 失败返回 ``None`` 降级。"""
+ global _DEFAULT_CLASSIFIER
+ if _DEFAULT_CLASSIFIER is _UNSET:
+ try:
+ from .classifier import classify
+
+ _DEFAULT_CLASSIFIER = classify
+ except Exception as exc: # noqa: BLE001 - 装载失败必须降级而非冒泡
+ logger.warning("[ModelRouting] default classifier unavailable: %s", exc)
+ _DEFAULT_CLASSIFIER = None
+ return _DEFAULT_CLASSIFIER
class ModelRoutingRail(DeepAgentRail):
- """模型路由 Rail —— 产出推荐模型 + 任务分析;按请求的模型选择路由。
+ """模型路由 Rail —— auto 档跑分类器,超阈值时切换模型。
+
+ auto 档(带 ``enable_routing`` 开关)跑分类器打分,score >= 40 换成 glm-5.3,
+ 否则保留 adapter 已应用的模型;具体模型名 / 空选择走 skip 分支。
- 请求模型选择(前端下拉框,经 relay frame ``params.model_name`` → request.params →
- ``run_context.extra["model_selection"]``)取值决定行为:
- - "fast"/"balanced"/"extreme"/"auto" → 四档模式(写死)→ 固定 (模型, 思考深度);
- - 具体模型名(非关键字)→ 跳过路由,保留 adapter 已应用的具体/默认模型。
- 始终真切换(set_llm);日志里体现所选模式(mode=…)。
+ 分类器与 Model 构造器都不需要 adapter 注入:未注入时懒加载内置
+ ``rails/model_routing/classifier.py``,构造器用 openjiuwen 直构兜底。
- 路由在 before_invoke 中执行(每个 invoke 一次);before_model_call 用于按档位
- 注入思考深度(off/medium/deep)。
+ 路由在 before_invoke 中执行(每个 invoke 一次)。
"""
priority: int = 95 # 早于 TaskPlanningRail(90),确保路由先生效
@@ -66,27 +80,29 @@ class ModelRoutingRail(DeepAgentRail):
self,
capability_table: Optional[list[ModelCapability]] = None,
*,
+ classifier: Any = _UNSET,
+ model_builder: Optional[Callable[[dict, dict], Any]] = None,
apply_routing: bool = True,
) -> None:
super().__init__()
self._capability_table: list[ModelCapability] = capability_table or []
+ # auto 档打分器:async (prompt_text) -> (score, category, difficulty)。
+ # 缺省(_UNSET)→ 懒加载内置实现;显式传 None → 关闭 auto 档路由。
+ self._classifier: Any = classifier
+ # 换 glm-5.3 用的 Model 构造器;不传则用 openjiuwen 直构。入参是当前已建好
+ # 模型的 client config 克隆,凭证(api_base / api_key / 鉴权头)已在其中。
+ self._model_builder: Optional[Callable[[dict, dict], Any]] = model_builder
self._call_history: list[PriorModelCall] = []
self._token_counter = TiktokenCounter()
self._apply_routing: bool = apply_routing
- self._request_thinking: str = "default"
- self._request_mode: str = ""
self._trace_id: str = _new_trace_id()
# ---- 路由 ---- #
def _resolve_request_selection(self, ctx: AgentCallbackContext) -> str:
- """每请求读取前端下拉选择值(经 relay frame params.model_name → run_context.extra 注入)。
+ """每请求读取前端下拉选择值(adapter 经 ``run_context.extra["model_selection"]`` 注入)。
- - fast/balanced/extreme/auto → 四档模式(_MODE_MODEL_MAP 写死映射);
- - 其它(具体模型名 / 空)→ 跳过路由(返回 "",before_invoke 走 skip 分支)。
- 注入链:adapter 把 request.params["model_name"] 写入
- ``inputs["run"]["context"]["extra"]["model_selection"]``,DeepAgent
- ``_normalize_inputs`` 再把它带进 ``InvokeInputs.run_context.extra``。
+ 仅用于日志/决策留痕,不参与路由决策。
"""
run_context = getattr(getattr(ctx, "inputs", None), "run_context", None)
extra = getattr(run_context, "extra", None)
@@ -96,33 +112,64 @@ class ModelRoutingRail(DeepAgentRail):
return raw.strip()
return ""
- def _find_cap_by_name(
- self, name: str, *, prefer_provider: Optional[str] = None
- ) -> Optional[ModelCapability]:
- """按 model_name(忽略大小写/空白)在能力表中查找。
+ def _resolve_request_routing_enabled(self, ctx: AgentCallbackContext) -> bool:
+ """每请求读取 auto 档开关(``enable_routing``),先 run_context、再 team 侧兜底。
+
+ 单 agent 走 ``run_context.extra``;team 成员拿不到 run_context,回落到成员
+ 自身的 ``BuildContext.request_metadata``(见 :func:`_team_request_metadata`)。
- ``prefer_provider`` 非空时,在所有同名 cap 里优先返回 ``model_provider``
- 匹配的条目(四档写死映射用,优先带官方供应商标记的同名模型);找不到标才退回第一个
- 同名(向后兼容:无标能力表行为不变)。
+ 严格判 ``is True``:任何非布尔真值(含字符串 "true")都不算开启。
"""
+ run_context = getattr(getattr(ctx, "inputs", None), "run_context", None)
+ extra = getattr(run_context, "extra", None)
+ if isinstance(extra, dict) and extra.get("enable_routing") is True:
+ return True
+ return _team_request_metadata(ctx).get("enable_routing") is True
+
+ def _bind_request_id(self, ctx: AgentCallbackContext) -> None:
+ """把本请求的 request_id 重绑到日志 ContextVar,修正 ``[req=]`` 标签串号。
+
+ agent 执行跑在与 handler **不同的 task**(warm-pool / 长生命周期复用),日志
+ record factory 读到的 ContextVar 可能是**上一个请求**捕获的陈旧值。adapter 已把
+ ``request_id`` 经 ``run_context.extra`` 逐请求注入(与 enable_routing 同一通道,
+ 已被证明逐请求正确),这里在 invoke 起点重新绑定,使 rail 及同 task 后续日志
+ 带上正确的 ``[req=]`` 标签。
+
+ 绑定失败(openjiuwen 未暴露该 API)只降级为 debug 日志,不影响路由决策。
+ """
+ run_context = getattr(getattr(ctx, "inputs", None), "run_context", None)
+ extra = getattr(run_context, "extra", None)
+ rid = extra.get("request_id") if isinstance(extra, dict) else None
+ if not rid:
+ return
+ try:
+ from openjiuwen.extensions.observability.span_context import (
+ set_current_request_id,
+ )
+
+ set_current_request_id(str(rid))
+ except Exception as exc: # noqa: BLE001 - 重绑失败不影响路由
+ logger.debug("[ModelRouting] rebind request_id failed: %s", exc)
+
+ def _resolve_classifier(self) -> Optional[Any]:
+ """取本次打分用的分类器:显式注入优先,未注入(``_UNSET``)则懒加载内置实现。"""
+ if self._classifier is _UNSET:
+ return _load_default_classifier()
+ return self._classifier
+
+ def _find_cap_by_name(self, name: str) -> Optional[ModelCapability]:
+ """按 model_name(忽略大小写/空白)在能力表中查找,返回首个同名条目。"""
key = (name or "").strip().lower()
- preferred = (prefer_provider or "").strip().lower()
- fallback: Optional[ModelCapability] = None
for cap in self._capability_table:
- if (cap.model_name or "").strip().lower() != key:
- continue
- if fallback is None:
- fallback = cap
- if preferred and (cap.model_provider or "").strip().lower() == preferred:
+ if (cap.model_name or "").strip().lower() == key:
return cap
- return fallback
+ return None
async def before_invoke(self, ctx: AgentCallbackContext) -> None:
"""invoke 开始时:重置 trace_id / call_history,执行路由决策。"""
+ self._bind_request_id(ctx)
self._trace_id = _new_trace_id()
self._call_history = []
- self._request_thinking = "default"
- self._request_mode = ""
try:
# 从 ctx.inputs.query 提取用户查询文本(before_invoke 时无 messages 列表)
@@ -131,73 +178,18 @@ class ModelRoutingRail(DeepAgentRail):
input_tokens = self._count_text_tokens(prompt_text)
agent_info = _extract_agent_info(ctx)
- # --- 四档模式(写死)→ 固定 (模型, 思考深度);具体模型/空 → 跳过 ---
- selection = self._resolve_request_selection(ctx)
- mode_model = _MODE_MODEL_MAP.get(selection)
- if mode_model is not None:
- thinking = _MODE_THINKING_MAP.get(selection, "medium")
- self._request_thinking = thinking
- self._request_mode = selection
- cap = self._find_cap_by_name(mode_model, prefer_provider=_MODE_PREFERRED_PROVIDER)
- if cap is None:
- # keep current:不注入档位 thinking kwargs(当前模型 vendor 未知,
- # DeepSeek/GLM 风格 extra_body.thinking 对 OpenAI 官方端点会 400)
- self._request_thinking = "default"
- logger.warning(
- "[ModelRouting] mode=%s model=%s not in capability table (%d models); "
- "keep current model, thinking=%s",
- selection, mode_model, len(self._capability_table), thinking,
- )
- self._emit_decision(
- ctx,
- recommended_cap=None,
- category=selection,
- difficulty=thinking,
- input_tokens=input_tokens,
- agent_info=agent_info,
- reasoning=(
- f"mode={selection} model={mode_model} not found; "
- f"keep current model, thinking={thinking}"
- ),
- )
- return
- if cap.model is None:
- # keep current(无 Model 对象可切):同上,不注入 thinking kwargs
- self._request_thinking = "default"
- logger.warning(
- "[ModelRouting] mode=%s model=%s has no Model object (builder missing); "
- "cannot switch, thinking=%s",
- selection, mode_model, thinking,
- )
- self._emit_decision(
- ctx,
- recommended_cap=None,
- category=selection,
- difficulty=thinking,
- input_tokens=input_tokens,
- agent_info=agent_info,
- reasoning=(
- f"mode={selection} model={mode_model} has no Model object; "
- f"keep current, thinking={thinking}"
- ),
- )
- return
- self._emit_decision(
+ # --- auto 档:分类器打分,超阈值才 set_llm 换模型 ---
+ if self._resolve_request_routing_enabled(ctx):
+ await self._route_by_classifier(
ctx,
- recommended_cap=cap,
- category=selection,
- difficulty=thinking,
+ prompt_text=prompt_text,
input_tokens=input_tokens,
agent_info=agent_info,
- reasoning=f"mode={selection} -> model={cap.model_name} thinking={thinking}",
- )
- logger.info(
- "[ModelRouting] mode=%s -> model=%s thinking=%s",
- selection, cap.model_name, thinking,
)
return
- # --- 具体模型 / 空:不路由,保留 adapter 已应用的具体/默认模型 ---
+ # --- 具体模型 / 空:不路由,保留 adapter 已应用的模型 ---
+ selection = self._resolve_request_selection(ctx)
self._emit_decision(
ctx,
recommended_cap=None,
@@ -215,30 +207,25 @@ class ModelRoutingRail(DeepAgentRail):
logger.warning("[ModelRouting] before_invoke failed: %s", exc, exc_info=True)
async def before_model_call(self, ctx: AgentCallbackContext) -> None:
- """按请求档位 / 模型族注入思考参数(经 vendor_map)。
+ """按模型族注入思考参数(经 vendor_map)。
- - 四档:fast=off / balanced|auto=medium / extreme=deep→high
- - 具体模型:``_request_thinking=default`` → 仅 GLM-5.3 族注入产品默认 depth(low)
+ 路由只选模型,不管思考深度:档位关键字已全部收回 relay 侧,这里只剩
+ 「具体模型」一种输入 → 仅 GLM-5.3 族注入产品默认 depth(low),其余 no-op。
写 ``ctx.extra["llm_call_kwargs"]``,由 ReActAgent 每次 model call 消费。
不支持思考控制的模型:adapt 降级为空 kwargs,本方法不写入。
"""
from jiuwenswarm.common.thinking.adapter import adapt_thinking
from jiuwenswarm.common.thinking.types import thaw_llm_call_kwargs
- depth = _GEAR_THINKING_TO_DEPTH.get(
- self._request_thinking, self._request_thinking or "default"
- )
model_name = _agent_model_name(ctx)
- used_cap = None
extra_probe = getattr(ctx, "extra", None)
- if isinstance(extra_probe, dict):
- used_cap = extra_probe.get("_model_routing_used_cap")
+ used_cap = extra_probe.get("_model_routing_used_cap") if isinstance(extra_probe, dict) else None
if used_cap is not None:
cap_name = getattr(used_cap, "model_name", None)
if isinstance(cap_name, str) and cap_name.strip():
model_name = cap_name.strip()
try:
- profile = adapt_thinking(depth, model_name=model_name)
+ profile = adapt_thinking("default", model_name=model_name)
if not profile.injected or not profile.llm_call_kwargs:
return
extra = getattr(ctx, "extra", None)
@@ -247,8 +234,7 @@ class ModelRoutingRail(DeepAgentRail):
kwargs = thaw_llm_call_kwargs(profile.llm_call_kwargs)
extra["llm_call_kwargs"] = kwargs
logger.info(
- "[ModelRouting] thinking inject mode=%s thinking=%s model=%r kwargs=%r",
- self._request_mode or "(none)",
+ "[ModelRouting] thinking inject thinking=%s model=%r kwargs=%r",
profile.thinking,
model_name,
kwargs,
@@ -256,6 +242,142 @@ class ModelRoutingRail(DeepAgentRail):
except Exception as exc:
logger.debug("[ModelRouting] thinking inject failed: %s", exc)
+ async def _route_by_classifier(
+ self,
+ ctx: AgentCallbackContext,
+ *,
+ prompt_text: str,
+ input_tokens: int,
+ agent_info: dict[str, Any],
+ ) -> None:
+ """auto 档:跑分类器给任务打分,score >= 40 时把模型换成 glm-5.3。
+
+ 分类器缺失/异常、续写指令(``CONTINUATION_CATEGORY``)、低分 → 保留当前模型。
+ 切换时用**当前模型**的 client config 克隆出 glm-5.3(api_base / api_key /
+ 鉴权头逐字不变,只换 model_name),经 ``_emit_decision`` 走 set_llm。
+ """
+ classifier = self._resolve_classifier()
+ if classifier is None:
+ logger.warning(
+ "[ModelRouting] enable_routing=true but classifier unavailable; keep current model"
+ )
+ return
+ try:
+ raw_score, category, difficulty = await classifier(prompt_text)
+ except Exception as exc:
+ logger.warning("[ModelRouting] classifier failed: %s", exc, exc_info=True)
+ return
+
+ if category == CONTINUATION_CATEGORY:
+ # 多轮对话里的「继续/同意」不能触发换模型
+ self._emit_decision(
+ ctx,
+ recommended_cap=None,
+ category="skipped",
+ difficulty="skipped",
+ input_tokens=input_tokens,
+ agent_info=agent_info,
+ reasoning="continuation utterance, keep current model",
+ )
+ logger.info("[ModelRouting] enable_routing: continuation, keep current model")
+ return
+
+ score = validate_score(raw_score)
+ if score < _CLASSIFIER_SCORE_THRESHOLD:
+ self._emit_decision(
+ ctx,
+ recommended_cap=None,
+ category=category,
+ difficulty=difficulty,
+ target_score=score,
+ input_tokens=input_tokens,
+ agent_info=agent_info,
+ reasoning=(
+ f"classifier score={score} < {_CLASSIFIER_SCORE_THRESHOLD}, keep current model"
+ ),
+ )
+ logger.info(
+ "[ModelRouting] enable_routing: score=%d < %d (category=%s difficulty=%s), keep current model",
+ score, _CLASSIFIER_SCORE_THRESHOLD, category, difficulty,
+ )
+ return
+
+ cap = self._build_switch_cap(ctx, _CLASSIFIER_TARGET_MODEL)
+ if cap is None or cap.model is None:
+ self._emit_decision(
+ ctx,
+ recommended_cap=None,
+ category=category,
+ difficulty=difficulty,
+ target_score=score,
+ input_tokens=input_tokens,
+ agent_info=agent_info,
+ reasoning=(
+ f"classifier score={score} but {_CLASSIFIER_TARGET_MODEL} model unavailable; "
+ f"keep current"
+ ),
+ )
+ logger.warning(
+ "[ModelRouting] enable_routing: score=%d but cannot build %s; keep current model",
+ score, _CLASSIFIER_TARGET_MODEL,
+ )
+ return
+
+ self._emit_decision(
+ ctx,
+ recommended_cap=cap,
+ category=category,
+ difficulty=difficulty,
+ target_score=score,
+ input_tokens=input_tokens,
+ agent_info=agent_info,
+ reasoning=(
+ f"classifier score={score} >= {_CLASSIFIER_SCORE_THRESHOLD} "
+ f"-> switch to {_CLASSIFIER_TARGET_MODEL}"
+ ),
+ )
+ logger.info(
+ "[ModelRouting] enable_routing: score=%d >= %d (category=%s difficulty=%s) -> set_llm %s",
+ score, _CLASSIFIER_SCORE_THRESHOLD, category, difficulty, _CLASSIFIER_TARGET_MODEL,
+ )
+
+ def _build_switch_cap(
+ self, ctx: AgentCallbackContext, target_model: str
+ ) -> Optional[ModelCapability]:
+ """用**当前模型**的 client config 克隆出 ``target_model`` 的 cap(凭证不变)。
+
+ 只换 ``model_name``,其余字段(api_base / api_key / client_provider /
+ Authorization 头 / 超时 / verify_ssl 等)逐字保留 —— 换模型不换 api/key。
+ 取不到当前模型配置 → 返回 None,调用方保留当前模型。
+ """
+ try:
+ react_agent = _resolve_react_agent(ctx.agent)
+ cfg = getattr(react_agent, "_config", None) or getattr(react_agent, "config", None)
+ mcc = getattr(cfg, "model_client_config", None) if cfg is not None else None
+ mrc = getattr(cfg, "model_config_obj", None) if cfg is not None else None
+ if mcc is None:
+ # 回退:按当前 model_name 在能力表里找同款(同 api_base/api_key)的 Model
+ current_name = _agent_model_name(ctx)
+ cur_cap = self._find_cap_by_name(current_name) if current_name else None
+ if cur_cap is None or cur_cap.model is None:
+ return None
+ mcc = cur_cap.model.model_client_config
+ mrc = cur_cap.model.model_config
+ new_mcc = _clone_cfg_with_model_name(mcc, target_model)
+ if new_mcc is None:
+ return None
+ new_mrc = _clone_cfg_with_model_name(mrc, target_model) or {}
+ builder = self._model_builder or _default_model_builder
+ model = builder(new_mcc, new_mrc)
+ if model is None:
+ return None
+ return ModelCapability(model_name=target_model, model_id=target_model, model=model)
+ except Exception as exc:
+ logger.warning(
+ "[ModelRouting] build %s model failed: %s", target_model, exc, exc_info=True
+ )
+ return None
+
async def after_model_call(self, ctx: AgentCallbackContext) -> None:
try:
response = getattr(getattr(ctx, "inputs", None), "response", None)
@@ -264,7 +386,7 @@ class ModelRoutingRail(DeepAgentRail):
output_tokens = int(getattr(usage, "output_tokens", 0) or 0)
model_name = _agent_model_name(ctx) or "unknown"
end_time = datetime.now(tz=timezone.utc).isoformat()
- # 1) 累积到本次 invoke 的前置调用链(完整 OTel span)
+ # 累积到本次 invoke 的前置调用链(完整 OTel span)
self._call_history.append(
PriorModelCall(
model=model_name,
@@ -272,7 +394,7 @@ class ModelRoutingRail(DeepAgentRail):
output_tokens=output_tokens,
iteration=len(self._call_history),
trace_id=self._trace_id,
- start_time=end_time, # before_model_call 已移除,无精确 start_time
+ start_time=end_time, # 无独立起始钩子,用 end_time 近似
end_time=end_time,
)
)
@@ -317,14 +439,8 @@ class ModelRoutingRail(DeepAgentRail):
or recommended_cap.model_name
)
if mname:
- # 供 RuntimePromptRail 注入「当前模型」用:档位关键字(fast/balanced/
- # extreme/auto)是作为 model_name 下发的,runtime_state 与 agent.model_name
- # 记的都是路由前的取值,这里落一份路由后真正生效的模型名。
- # 必须落进按引用透传的 RunContext:本 rail 的 before_invoke 只注册在外层
- # DeepAgent 的 ctx 上,读取方 RuntimePromptRail.before_model_call 却跑在
- # 内层 ReActAgent 新建的 ctx 上(extra 是另一个 dict),外层 ctx.extra
- # 传不过去;RunContext 则经 effective_inputs 原样带进内层,内层可从
- # ctx.extra["run_context"].extra 读回。
+ # 供 RuntimePromptRail 注入「当前模型」用。外层 rail 写、内层 rail 读,
+ # 只能落进按引用透传的 run_context(ctx.extra 不跨层)。
run_context = getattr(getattr(ctx, "inputs", None), "run_context", None)
rc_extra = getattr(run_context, "extra", None)
if isinstance(rc_extra, dict):
@@ -362,8 +478,9 @@ class ModelRoutingRail(DeepAgentRail):
setattr(ctx.agent, "model_name", mname)
except Exception as exc:
logger.debug("[ModelRouting] setattr model_name failed: %s", exc)
- # 主对话换模后,同步已缓存的上下文压缩器 Model,避免压缩仍用档位关键字
- # / 过期 id → 模型调用失败,压缩 noop。
+ # 主对话换模后,同步已缓存的上下文压缩器 / 会话记忆的 Model。它们
+ # 在 agent 创建时把 model_config 烤了进去,不跟着换就会继续拿旧 id
+ # 调上游 → 模型无效、压缩 noop、上下文膨胀。
synced = sync_agent_compressor_models(
react_agent,
recommended_cap.model,
@@ -403,12 +520,58 @@ class ModelRoutingRail(DeepAgentRail):
# ---- Helpers ---- #
+def _clone_cfg_with_model_name(cfg_obj: Any, model_name: str) -> Optional[dict]:
+ """把 openjiuwen 配置对象(pydantic)或 dict 摊成 dict,只替换 ``model_name``。
+
+ 其余字段原样保留,实现「换模型不换 api/key」。
+ 既没有 ``model_dump`` 也不是 dict → 返回 None(调用方放弃切换)。
+ """
+ if cfg_obj is None:
+ return None
+ dump = getattr(cfg_obj, "model_dump", None)
+ if callable(dump):
+ try:
+ fields = dump()
+ except Exception:
+ return None
+ if not isinstance(fields, dict):
+ return None
+ return {**fields, "model_name": model_name}
+ if isinstance(cfg_obj, dict):
+ return {**cfg_obj, "model_name": model_name}
+ return None
+
+
+def _team_request_metadata(ctx: AgentCallbackContext) -> dict[str, Any]:
+ """从成员自身的 ``BuildContext`` 取 ``request_metadata``(team 成员拿不到 run_context)。
+
+ ``ctx.agent`` 就是成员的 ``NativeHarness``,其 ``build_context`` 是 jiuwenswarm 的
+ ``SwarmBuildContext``,``request_metadata`` 由 assembly 塞进 ``build_context_seed``
+ 还原到成员侧。取不到(单 agent / 非 swarm)→ 空 dict。
+ """
+ build_context = getattr(getattr(ctx, "agent", None), "build_context", None)
+ metadata = getattr(build_context, "request_metadata", None)
+ return metadata if isinstance(metadata, dict) else {}
+
+
+def _default_model_builder(mcc_fields: dict, mco_fields: dict) -> Any:
+ """无注入 builder 时的兜底构造(openjiuwen 直构)。
+
+ 入参是当前已建好模型的 client config 克隆,鉴权头已在其中,故直构也带得上凭证。
+ """
+ from openjiuwen.core.foundation.llm import Model, ModelClientConfig
+ from openjiuwen.core.foundation.llm.model_clients.base_model_client import ModelRequestConfig
+
+ return Model(
+ model_client_config=ModelClientConfig(**mcc_fields),
+ model_config=ModelRequestConfig(**mco_fields),
+ )
+
+
def _resolve_react_agent(agent: Any) -> Any:
"""Return the inner ReActAgent if *agent* is a DeepAgent, else *agent* itself.
- DeepAgent does not expose ``set_llm``; its inner ``_react_agent``
- (a ReActAgent) does. This mirrors the adapter-level pattern in
- ``interface_deep._apply_model_to_react_agent``.
+ DeepAgent does not expose ``set_llm``; its inner ``_react_agent`` does.
"""
if callable(getattr(agent, "set_llm", None)):
return agent
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch_task_manager.py b/jiuwenswarm/agents/harness/common/tools/deepresearch_task_manager.py
index 3e20bdcf88..8f71d3386b 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch_task_manager.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch_task_manager.py
@@ -11,10 +11,6 @@ import re
from collections.abc import Mapping
from typing import Any, Dict
-from jiuwenswarm.agents.harness.common.model_gears import (
- is_model_gear,
- resolve_model_gear,
-)
from jiuwenswarm.common.local_env_config import (
get_local_config,
read_default_headers_raw,
@@ -283,19 +279,6 @@ class DeepResearchTaskManager:
return DeepResearchTaskManager._read_config_value(name, default, env)
llm_model_name = read("LLM_MODEL_NAME").strip() or read("MODEL_NAME").strip()
- # 档位关键字(fast/balanced/extreme/auto)只对**单 agent 主链路**成立:那里
- # ModelRoutingRail 会读 request param 把它翻成具体模型。DeepResearch 子进程
- # 走的是 env 通道(宿主有效模型 env → MODEL_NAME),**没有 rail 也没有
- # request params**,裸档位关键字会被当真实模型名直送上游 → Invalid model。
- # 故在把配置交给隔离子进程前先翻成具体模型 id。
- if is_model_gear(llm_model_name):
- resolved_gear_model = resolve_model_gear(llm_model_name)
- logger.info(
- "[DeepResearch] model gear %r resolved to %r for child config",
- llm_model_name,
- resolved_gear_model,
- )
- llm_model_name = resolved_gear_model
llm_model_type = (
read("LLM_MODEL_TYPE").strip().lower()
or read("MODEL_PROVIDER").strip().lower()
diff --git a/jiuwenswarm/agents/swarm/config_specs.py b/jiuwenswarm/agents/swarm/config_specs.py
index b233adbe93..d5a81313d1 100644
--- a/jiuwenswarm/agents/swarm/config_specs.py
+++ b/jiuwenswarm/agents/swarm/config_specs.py
@@ -89,6 +89,10 @@ def _kv_cache_affinity_config(config: dict[str, Any]) -> KVCacheAffinityConfig:
# provider name re-exported from the registry (no hard-coded strings).
_COMMON_RAIL_NAMES: tuple[str, ...] = (
registry.RUNTIME_PROMPT,
+ # auto 档(relay 下发 enable_routing)成员级路由:每个成员各自跑分类器。
+ # 自身按 config.yaml::model_routing.enabled + JIUWENSWARM_MODEL_ROUTING_ENABLED
+ # 门控,关闭时 provider 返回 None(不挂载)。
+ registry.MODEL_ROUTING,
registry.REQUEST_SCOPED_MCP_TOOLS,
registry.TEAM_SKILL_STORAGE_POLICY,
registry.TEAM_SHARED_SKILL_LINK_REFRESH,
@@ -140,6 +144,8 @@ _COMMON_TOOL_NAMES: tuple[str, ...] = (
# carry params and are appended separately.
_CODE_RAIL_NAMES: tuple[str, ...] = (
registry.CODE_RUNTIME_PROMPT,
+ # 同 _COMMON_RAIL_NAMES:code.team / team.plan 成员也要能 auto 档路由。
+ registry.MODEL_ROUTING,
registry.REQUEST_SCOPED_MCP_TOOLS,
registry.RESPONSE_PROMPT,
registry.STREAM_EVENT,
diff --git a/jiuwenswarm/agents/swarm/providers/member_rails.py b/jiuwenswarm/agents/swarm/providers/member_rails.py
index 7f5b7b7d02..e711c95fa2 100644
--- a/jiuwenswarm/agents/swarm/providers/member_rails.py
+++ b/jiuwenswarm/agents/swarm/providers/member_rails.py
@@ -36,6 +36,10 @@ from openjiuwen.harness.rails.personal_context import PersonalContextRail
from jiuwenswarm.agents.harness.common.plugins.rail_manager import get_rail_manager
from jiuwenswarm.common.utils import get_user_workspace_dir
from jiuwenswarm.server.runtime.runtime_scope import RuntimeScopeKey
+from jiuwenswarm.agents.harness.common.rails.model_routing.model_routing_rail import (
+ ModelRoutingRail,
+ model_routing_enabled,
+)
from jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail import (
RuntimePromptRail,
)
@@ -84,6 +88,48 @@ A2A_OUTBOUND_TOOLKIT = "swarm.a2a_outbound_toolkit"
TEAM_PERMISSION_POLICY = "swarm.team_permission_policy"
DISABLED_TOOLS = "swarm.disabled_tools"
REQUEST_SCOPED_MCP_TOOLS = "swarm.request_scoped_mcp_tools"
+MODEL_ROUTING = "swarm.model_routing"
+
+
+@harness_element(
+ kind=ElementKind.RAIL,
+ name=MODEL_ROUTING,
+ description="auto gear: each member scores its own task and may switch its own model.",
+)
+def _build_model_routing_rail(
+ params: dict[str, Any],
+ context: SwarmBuildContext,
+) -> ModelRoutingRail | None:
+ """auto 档路由 rail —— **成员级**,每个成员各自跑分类器。
+
+ 开关不走 ``run_context``(成员拿不到):relay 在 chat.send ``params.enable_routing``
+ 上下发,``team_helpers`` 写进 ``request_metadata``,随 ``build_context_seed`` 还原到
+ 成员自身的 ``BuildContext``;rail 侧 ``_resolve_request_routing_enabled`` 走该兜底分支。
+
+ 能力表留空:切换用的 cap 由 ``_build_switch_cap`` 从**当前成员模型**的 client config
+ 克隆(只换 model_name,api_base / api_key / 鉴权头逐字保留),能力表仅在该 config
+ 取不到时才兜底。故成员 rail 不需要 adapter 注入任何构造器。
+ """
+ del params
+ if not model_routing_enabled(getattr(context, "config", None)):
+ return None
+ try:
+ rail = ModelRoutingRail(apply_routing=True)
+ except Exception as exc: # noqa: BLE001 - 可选 Rail,构造失败只降级
+ logger.warning(
+ "[swarm.model_routing] Rail construction failed (%s)",
+ type(exc).__name__,
+ )
+ return None
+ # 与 interface_deep 的单 agent 构建日志同形,便于确认成员确实挂上了 rail
+ # (成功路径否则完全静默,日志里分不清「没挂」和「挂了但没触发」)。
+ logger.info(
+ "[swarm.model_routing] ModelRoutingRail mounted (team=%s member=%s role=%s)",
+ getattr(context, "team_id", "") or "?",
+ getattr(context, "member_name", None) or "?",
+ getattr(context, "role", None) or "?",
+ )
+ return rail
@harness_element(
diff --git a/jiuwenswarm/agents/swarm/registry.py b/jiuwenswarm/agents/swarm/registry.py
index c7dc286dd5..9e7dfdd27d 100644
--- a/jiuwenswarm/agents/swarm/registry.py
+++ b/jiuwenswarm/agents/swarm/registry.py
@@ -86,6 +86,7 @@ SYMPHONY_ORCHESTRATION_PROMPT = _member_rails.SYMPHONY_ORCHESTRATION_PROMPT
A2A_OUTBOUND_TOOLKIT = _member_rails.A2A_OUTBOUND_TOOLKIT
DISABLED_TOOLS = _member_rails.DISABLED_TOOLS
REQUEST_SCOPED_MCP_TOOLS = _member_rails.REQUEST_SCOPED_MCP_TOOLS
+MODEL_ROUTING = _member_rails.MODEL_ROUTING
TEAM_PERMISSION = _member_rails.TEAM_PERMISSION
TEAM_PERMISSION_POLICY = _member_rails.TEAM_PERMISSION_POLICY
TEAM_SKILL_EVOLUTION = _evolution_rails.TEAM_SKILL_EVOLUTION
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
index 1e2c29cc5b..9ae15e4272 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
@@ -762,11 +762,9 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
self._build_a2a_outbound_toolkit_rail,
),
)
- # 四档档位路由(ModelRoutingRail)同样只在单 agent code 模式挂载。
- # relay 的单 agent 通道不下发具体模型 id,档位关键字(fast/balanced/
- # extreme/auto)原样进 params.model_name,靠这条 rail 翻成具体模型 +
- # 思考深度;code.team / team.plan 已由 relay 侧翻成具体 id,挂上只会
- # 拿到具体名走能力表兜底,故与 team profile 一并排除。
+ # 模型路由(ModelRoutingRail)只在单 agent code 模式挂载:auto 档
+ # (params.enable_routing=True)跑分类器、超阈值才切模型,具体模型名走 skip。
+ # code.team / team.plan 由 relay 侧翻成具体 id,故与 team profile 一并排除。
rail_infos.append(
_RailBuildInfo(
"_model_routing_rail",
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 4fb86726e9..a22773e6ca 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -78,8 +78,14 @@ from openjiuwen.harness.rails import (
unconfigure_skill_evolution,
)
from openjiuwen.harness.rails.personal_context import PersonalContextRail
-from openjiuwen.harness.personal_context.im.search_tool import ImSearchTool
-from openjiuwen.harness.personal_context.im.sqlite_search import SqliteImSearchStore
+# personal_context.im 子模块仅较新 openjiuwen 提供;缺失时降级(不挂载 im_search 工具),
+# 与下方 PersonalContextRail 的可选语义、以及本文件 TTSEConfig 的降级写法保持一致。
+try:
+ from openjiuwen.harness.personal_context.im.search_tool import ImSearchTool
+ from openjiuwen.harness.personal_context.im.sqlite_search import SqliteImSearchStore
+except ImportError:
+ ImSearchTool = None # type: ignore[misc, assignment]
+ SqliteImSearchStore = None # type: ignore[misc, assignment]
from openjiuwen.harness.rails.evolution import EvolutionReviewRuntime
try:
from openjiuwen.harness.rails.evolution import (
@@ -1718,12 +1724,15 @@ def _model_routing_enabled(config: dict[str, Any] | None) -> bool:
relay 侧可经 spawn env 注入 ``JIUWENSWARM_MODEL_ROUTING_ENABLED``(进程级开关,
仿 JIUWENSWARM_CODE_COAUTHOR_HEADER_ENABLED);env 显式设置时优先于 config.yaml。
+
+ 判定委托给 rail 侧 ``model_routing_enabled``:swarm 成员 provider(``swarm.model_routing``)
+ 读的是同一个函数,两处不能各读一遍开关。
"""
- enabled = _parse_bool((config or {}).get("model_routing", {}).get("enabled"))
- env_val = os.getenv("JIUWENSWARM_MODEL_ROUTING_ENABLED")
- if env_val is not None and env_val.strip():
- enabled = _parse_bool(env_val)
- return enabled
+ from jiuwenswarm.agents.harness.common.rails.model_routing.model_routing_rail import (
+ model_routing_enabled,
+ )
+
+ return model_routing_enabled(config)
def _resolve_instance_config_base(config_base: dict[str, Any] | None) -> dict[str, Any]:
@@ -5855,6 +5864,57 @@ class JiuWenSwarmDeepAdapter:
"[JiuWenSwarmDeepAdapter] model_selection injected: value=%s", raw
)
+ @staticmethod
+ def _inject_model_routing_into_inputs(
+ request: AgentRequest, inputs: dict[str, Any]
+ ) -> None:
+ """把 ``params.enable_routing`` 注入 ``inputs["run"]["context"]["extra"]["enable_routing"]``。
+
+ relay 的 auto 档在 ``params.model_name`` 上仍下发**保底具体模型名**,另置
+ ``enable_routing=True`` 表达「本帧模型名可被路由覆盖」。开关经这里写进
+ ``run_context.extra``,供 ``ModelRoutingRail.before_invoke`` 每请求读取。
+
+ 严格判 ``is True``:缺省 / ``False`` / 非布尔(含字符串 "true")一律**不写**,
+ 避免任何异常输入把 rail 从「跳过」翻成「真路由」。params 是白名单消费
+ (``_build_inputs`` 逐键 ``params.get``),故 relay 侧必须显式列出该键。
+ """
+ params = request.params if isinstance(request.params, dict) else {}
+ if params.get("enable_routing") is not True:
+ return
+ run_extra = (
+ inputs.setdefault("run", {})
+ .setdefault("context", {})
+ .setdefault("extra", {})
+ )
+ if isinstance(run_extra, dict):
+ run_extra["enable_routing"] = True
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] enable_routing injected: value=True"
+ )
+
+ @staticmethod
+ def _inject_request_id_into_inputs(
+ request: AgentRequest, inputs: dict[str, Any]
+ ) -> None:
+ """把 ``request.request_id`` 注入 ``inputs["run"]["context"]["extra"]["request_id"]``。
+
+ 供 ``ModelRoutingRail.before_invoke`` 在 invoke 起点重绑日志的 ``[req=]``
+ ContextVar。agent 执行跑在与 handler **不同的 task**(warm-pool / 长生命周期
+ 复用),其 ContextVar 可能是**上一个请求**捕获的陈旧值,导致 rail 决策日志
+ 带错 req 标签。这里把本请求 id 作为**数据**随 inputs 传入(与 model_selection /
+ enable_routing 同一条通道,逐请求正确),rail 侧据此重绑即可修正标签。
+ """
+ rid = str(getattr(request, "request_id", "") or "").strip()
+ if not rid:
+ return
+ run_extra = (
+ inputs.setdefault("run", {})
+ .setdefault("context", {})
+ .setdefault("extra", {})
+ )
+ if isinstance(run_extra, dict):
+ run_extra["request_id"] = rid
+
def _refresh_multimodal_configs(
self,
config_base: dict[str, Any],
@@ -6450,14 +6510,8 @@ class JiuWenSwarmDeepAdapter:
@staticmethod
def _build_model_from_entry(mcc: dict, mco: dict) -> Model:
"""根据单个模型条目的 model_client_config / model_config_obj 构建 Model 实例。"""
- # 档位关键字(fast/balanced/extreme/auto)是宿主前端的选择器,不是模型 id。
- # 无 rail 的消费方(子代理继承 _deep_config.model、code 模式、DeepResearch 子进程)
- # 会把它直送上游 → Invalid model。在构建 Model 的唯一入口翻成具体模型;只改
- # Model 的请求模型名,不动 mcc(cache key / identity 仍按档位登记)。
- from jiuwenswarm.agents.harness.common.model_gears import resolve_model_gear
-
- name = resolve_model_gear(mcc.get("model_name", ""))
- # models.json 在宿主 spawn 前落盘;未登录时官方通道条目 api_base/api_key 为空,
+ name = mcc.get("model_name", "")
+ # models.json 在 relay spawn 前落盘;未登录时 maas 条目 api_base/api_key 为空,
# Model 构建会失败(整批跳过,四档路由只能 keep current)。登录后 invoke 同步
# 把官方通道凭证 env(API_BASE/API_KEY/default_headers)注入 tip,这里在 api_base
# 缺失时原位回填:仅当候选 base 命中官方通道端点标记才填,避免把自定义 OpenAI
@@ -7121,7 +7175,7 @@ class JiuWenSwarmDeepAdapter:
config.model_config_obj = model.model_config
# 与 ModelRoutingRail 同口径:主模型切换后同步压缩器,避免压缩仍用无效模型名。
try:
- from jiuwenswarm.agents.harness.common.model_gears import (
+ from jiuwenswarm.agents.harness.common.rails.model_routing.compressor_sync import (
sync_agent_compressor_models,
)
@@ -9924,9 +9978,8 @@ class JiuWenSwarmDeepAdapter:
- 使能:config.yaml ``model_routing.enabled`` = true,或进程级 env
``JIUWENSWARM_MODEL_ROUTING_ENABLED``(relay spawn 注入,见 _model_routing_enabled)。
- 始终真切换(apply_routing=True)。
- - 模型选择由前端下拉框与具体模型同级:四档(fast / balanced / extreme / auto)
- 与具体模型统一经 frame ``params.model_name`` 注入(四档写死模式,或具体
- 模型名),见 ModelRoutingRail。
+ - 只对 auto 档生效:relay 置 ``params.enable_routing=True`` 时 rail 跑分类器,
+ score >= 40 换 glm-5.3,否则保留 relay 下发的模型;具体模型名走 skip 分支。
- 能力表来自 ``routing_state/models.json``(sidecar)或 config.yaml ``models.defaults``
+ ``models.vision``(后者作 model_type="vision" 候选);model_builder 传
_build_model_from_entry 使能力表带 Model 对象(真切换前置)。
@@ -12475,19 +12528,25 @@ class JiuWenSwarmDeepAdapter:
# Mount the read-only im_search tool under the same switch so the
# agent can retrieve learned IM history without being told to.
+ # im_search 依赖 openjiuwen 的 personal_context.im;缺失时静默降级(不挂载)。
+ _im_search_available = ImSearchTool is not None and SqliteImSearchStore is not None
self._im_search_tools, self._im_search_tools_registered = (
self._sync_tool_group(
current_tools=self._im_search_tools,
registered=self._im_search_tools_registered,
- enabled=True,
- create_fn=lambda: [
- ImSearchTool(
- SqliteImSearchStore(
- get_user_workspace_dir() / ".personal_context"
- ),
- language=self._resolve_runtime_language(),
- )
- ],
+ enabled=_im_search_available,
+ create_fn=lambda: (
+ [
+ ImSearchTool(
+ SqliteImSearchStore(
+ get_user_workspace_dir() / ".personal_context"
+ ),
+ language=self._resolve_runtime_language(),
+ )
+ ]
+ if _im_search_available
+ else []
+ ),
warn_label="im search tool",
)
)
@@ -19447,6 +19506,8 @@ class JiuWenSwarmDeepAdapter:
self._inject_extension_config_into_inputs(inputs)
self._inject_model_selection_into_inputs(request, inputs)
+ self._inject_model_routing_into_inputs(request, inputs)
+ self._inject_request_id_into_inputs(request, inputs)
_req_model = (request.params.get("model_name") or "") if isinstance(request.params, dict) else ""
if not self._has_valid_model_config(_req_model):
@@ -20241,6 +20302,8 @@ class JiuWenSwarmDeepAdapter:
self._inject_extension_config_into_inputs(inputs)
self._inject_model_selection_into_inputs(request, inputs)
+ self._inject_model_routing_into_inputs(request, inputs)
+ self._inject_request_id_into_inputs(request, inputs)
is_skill_turbo_resume_request = bool(_params.get("answers")) and (
str(_params.get("source") or "").strip() == "ask_user_interrupt"
diff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
index 0978d6d09e..41e7348777 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py
@@ -2152,6 +2152,11 @@ async def process_team_message_stream(
"supports_user_interaction",
request.params.get("supports_user_interaction") is not False,
)
+ # auto 档开关:成员 rail 拿不到 run_context,改从自身
+ # BuildContext.request_metadata 读;这里让它随 build_context_seed 带到成员侧。
+ request_metadata.setdefault(
+ "enable_routing", request.params.get("enable_routing") is True
+ )
resolved_mode = str(request_metadata.get("mode") or "").strip()
# Relay-provided model_ref is authoritative for a uniform selection or
# a member-level auto assignment. A name-only request remains a
diff --git a/tests/unit_tests/agents/harness/common/rails/test_model_routing_applied_model_boundary.py b/tests/unit_tests/agents/harness/common/rails/test_model_routing_applied_model_boundary.py
index d14a4ea708..44f80e5b2f 100644
--- a/tests/unit_tests/agents/harness/common/rails/test_model_routing_applied_model_boundary.py
+++ b/tests/unit_tests/agents/harness/common/rails/test_model_routing_applied_model_boundary.py
@@ -2,15 +2,12 @@
"""回归:路由后实际生效的模型名必须跨过「外层 ctx → 内层 ctx」这道边界。
-`ModelRoutingRail.before_invoke` 跑在外层 DeepAgent 的回调上下文上(`BEFORE_INVOKE`
-属 openjiuwen 的 outer-only 事件),`RuntimePromptRail.before_model_call` 被桥接到内层
-ReActAgent(`BEFORE_MODEL_CALL` 属 bridge 事件),内层每次 invoke 都新建
-`AgentCallbackContext`、`extra` 是全新 dict,两边不共享。唯一的通道是按引用透传的
-`RunContext`:外层写 ``ctx.inputs.run_context.extra``,内层经
-``ctx.extra["run_context"].extra`` 读回。
-
-本文件走**真实 DeepAgent 事件链**。既有 UT 手工造单一 ctx 直接调 rail —— 那条路径恰好
-绕开这道边界,会让跨 ctx 缺陷在 CI 全绿下合入。
+`ModelRoutingRail.before_invoke` 跑在外层 DeepAgent 的回调上下文上,
+`RuntimePromptRail.before_model_call` 跑在内层 ReActAgent 新建的 ctx 上(`extra` 是
+另一个 dict)。唯一通道是按引用透传的 `RunContext`:外层写
+``ctx.inputs.run_context.extra``,内层经 ``ctx.extra["run_context"].extra`` 读回。
+
+本文件走**真实 DeepAgent 事件链**;手工造单一 ctx 直接调 rail 会绕开这道边界。
"""
from __future__ import annotations
@@ -94,7 +91,7 @@ def _build_model(name: str) -> Model:
def _write_runtime_state(tmp_path: Path, *, model: str, available_models: list[str]) -> Path:
- """落一份 runtime_state.yaml,复现「档位关键字被当成模型名写进去」的现场。"""
+ """落一份 runtime_state.yaml(路由前写入的模型名)。"""
state_dir = tmp_path / "runtime_state"
state_dir.mkdir(parents=True, exist_ok=True)
state_file = state_dir / "boundary-session.yaml"
@@ -126,7 +123,7 @@ def _current_model(content: str) -> str:
raise AssertionError(f"runtime.setting 里没有「当前模型」行:\n{content}")
-async def _run_real_chain(selection: str) -> list[str]:
+async def _run_real_chain(extra: dict) -> list[str]:
"""真实 DeepAgent 事件链跑一轮,返回 runtime.setting 的内容。"""
agent = DeepAgent(AgentCard(id="boundary_agent", name="Boundary"))
agent.configure(
@@ -137,6 +134,9 @@ async def _run_real_chain(selection: str) -> list[str]:
)
)
+ async def _classify(_prompt_text: str):
+ return 80, "coding", "hard"
+
routing_rail = ModelRoutingRail(
capability_table=[
ModelCapability(
@@ -145,11 +145,12 @@ async def _run_real_chain(selection: str) -> list[str]:
model=_build_model("deepseek-v4.1-flash"),
),
ModelCapability(
- model_name="glm-5.2",
- model_id="glm-52",
- model=_build_model("glm-5.2"),
+ model_name="glm-5.3",
+ model_id="glm-53",
+ model=_build_model("glm-5.3"),
),
- ]
+ ],
+ classifier=_classify,
)
runtime_rail = RuntimePromptRail(language="cn", channel="web")
runtime_rail.set_session_id("boundary-session")
@@ -172,7 +173,7 @@ async def _run_real_chain(selection: str) -> list[str]:
"conversation_id": "boundary-session",
# DeepAgent._normalize_inputs 只认嵌套的 run.context;
# adapter 正是把 request.params["model_name"] 写在这里。
- "run": {"kind": "normal", "context": {"extra": {"model_selection": selection}}},
+ "run": {"kind": "normal", "context": {"extra": extra}},
},
)
finally:
@@ -182,31 +183,35 @@ async def _run_real_chain(selection: str) -> list[str]:
@pytest.mark.asyncio
async def test_applied_model_crosses_outer_to_inner_ctx_boundary(tmp_path, monkeypatch):
- """选 fast 档:内层 RuntimePromptRail 必须报真实模型名,而不是档位关键字。
+ """auto 档切到 glm-5.3:内层 RuntimePromptRail 必须报**路由后**的模型名。
- 修复前 `model_routing_applied_model` 写在外层 ctx.extra 上,内层读不到 →
- `routed_model` 恒为空 → 回退到 runtime_state 里的 `fast`,本用例失败。
+ 内层读不到外层写的 `model_routing_applied_model` 时,会回退到 runtime_state 里的
+ 路由**前**取值(relay 下发的 deepseek-v4.1-flash),本用例失败。
"""
- state_file = _write_runtime_state(tmp_path, model="fast", available_models=["fast"])
+ state_file = _write_runtime_state(
+ tmp_path, model="deepseek-v4.1-flash", available_models=["deepseek-v4.1-flash"]
+ )
monkeypatch.setattr(
_runtime_prompt_mod, "get_runtime_state_path", lambda session_id=None: state_file
)
- contents = await _run_real_chain("fast")
+ contents = await _run_real_chain(
+ {"model_selection": "deepseek-v4.1-flash", "enable_routing": True}
+ )
assert contents, "runtime.setting 没有被注入,真实事件链没跑到内层 before_model_call"
- assert _current_model(contents[-1]) == "deepseek-v4.1-flash"
+ assert _current_model(contents[-1]) == "glm-5.3"
@pytest.mark.asyncio
async def test_concrete_model_selection_keeps_runtime_state_model(tmp_path, monkeypatch):
- """具体模型名走 skip 分支:不写路由结果,回退链行为与合入前一致。"""
+ """具体模型名走 skip 分支:不写路由结果,回退链取 runtime_state 的值。"""
state_file = _write_runtime_state(tmp_path, model="glm-5.2", available_models=["glm-5.2"])
monkeypatch.setattr(
_runtime_prompt_mod, "get_runtime_state_path", lambda session_id=None: state_file
)
- contents = await _run_real_chain("glm-5.2")
+ contents = await _run_real_chain({"model_selection": "glm-5.2"})
assert contents
assert _current_model(contents[-1]) == "glm-5.2"
diff --git a/tests/unit_tests/agents/harness/common/rails/test_model_routing_classifier.py b/tests/unit_tests/agents/harness/common/rails/test_model_routing_classifier.py
new file mode 100644
index 0000000000..c29084823f
--- /dev/null
+++ b/tests/unit_tests/agents/harness/common/rails/test_model_routing_classifier.py
@@ -0,0 +1,174 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Unit tests for the auto-gear task classifier (``rails/model_routing/classifier.py``).
+
+The classifier is now a self-contained Python module — score table, rules and the
+TF-IDF corpus are hardcoded (no runtime config loading). These tests pin the contract
+the rail depends on:
+
+ score = SCORE_TABLE[(category, difficulty)] (difficulty fallback 25/40/60)
+ continuation utterances -> (CONTINUATION_SCORE, CONTINUATION_CATEGORY, "skip")
+
+The prompt -> (score, category, difficulty) rows below are recorded from the previous
+JSON-driven implementation, so they double as an equivalence regression on the port.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from jiuwenswarm.agents.harness.common.rails.model_routing.classifier import (
+ CATEGORIES,
+ CONTINUATION_CATEGORY,
+ CONTINUATION_SCORE,
+ DEFAULT_SCORE_BY_DIFFICULTY,
+ DEFAULT_SCORE_FALLBACK,
+ DIFFICULTIES,
+ SCORE_TABLE,
+ classify,
+ validate_score,
+)
+
+
+def test_score_table_is_the_expected_15_entries():
+ assert SCORE_TABLE == {
+ ("chat", "easy"): 5,
+ ("chat", "medium"): 20,
+ ("chat", "hard"): 40,
+ ("reasoning", "easy"): 20,
+ ("reasoning", "medium"): 40,
+ ("reasoning", "hard"): 60,
+ ("coding", "easy"): 25,
+ ("coding", "medium"): 45,
+ ("coding", "hard"): 65,
+ ("summarization", "easy"): 15,
+ ("summarization", "medium"): 25,
+ ("summarization", "hard"): 45,
+ ("format", "easy"): 5,
+ ("format", "medium"): 10,
+ ("format", "hard"): 30,
+ }
+ assert CATEGORIES == ("chat", "reasoning", "coding", "summarization", "format")
+ assert DIFFICULTIES == ("easy", "medium", "hard")
+ assert DEFAULT_SCORE_BY_DIFFICULTY == {"easy": 25, "medium": 40, "hard": 60}
+
+
+ "prompt, expected",
+ [
+ ("", (5, "chat", "easy")),
+ (" ", (5, "chat", "easy")),
+ ("你好", (5, "chat", "easy")),
+ ("hello", (5, "chat", "easy")),
+ ("帮我写一个快速排序函数", (25, "coding", "easy")),
+ ("debug this code", (65, "coding", "hard")),
+ ("请总结这篇文章的要点", (15, "summarization", "easy")),
+ ("请逐步推导这个数学证明", (20, "reasoning", "easy")),
+ ("1+1", (20, "reasoning", "easy")),
+ ("把这段 JSON 转成 CSV", (5, "format", "easy")),
+ # 长输入触发长度信号 → 难度抬到 medium(无规则命中时按 chat 兜底)
+ ("x" * 400, (20, "chat", "medium")),
+ ],
+)
+async def test_classify_known_prompts(prompt, expected):
+ assert await classify(prompt) == expected
+
+
+ "prompt",
+ ["继续", "好的", "ok", "continue", "请继续", "please continue", "好继续", "好的请继续"],
+)
+async def test_continuation_utterances_return_sentinel(prompt):
+ """续写/确认指令短路:哨兵让 rail 跳过重路由(否则 -1 会被 validate_score 兜成 60)。"""
+ assert await classify(prompt) == (CONTINUATION_SCORE, CONTINUATION_CATEGORY, "skip")
+
+
+async def test_classify_only_returns_known_categories_and_difficulties():
+ for prompt in ("你好", "debug this code", "把这段 JSON 转成 CSV", "请总结要点"):
+ score, category, difficulty = await classify(prompt)
+ assert category in (*CATEGORIES, CONTINUATION_CATEGORY)
+ assert difficulty in (*DIFFICULTIES, "skip")
+ assert score == SCORE_TABLE.get((category, difficulty), score)
+
+
+ "raw, expected",
+ [
+ (0, 0),
+ (50, 50),
+ (100, 100),
+ (-1, DEFAULT_SCORE_FALLBACK), # 越界(continuation 哨兵若漏到此处)→ 兜底
+ (101, DEFAULT_SCORE_FALLBACK),
+ ("80", 80),
+ ("abc", DEFAULT_SCORE_FALLBACK),
+ (None, DEFAULT_SCORE_FALLBACK),
+ ],
+)
+def test_validate_score(raw, expected):
+ assert validate_score(raw) == expected
+
+
+# ---- CJK 词边界回归:`\b` 与 CJK 相邻时永不匹配 ---- #
+
+
+ "prompt",
+ [
+ "很复杂的系统怎么设计",
+ "分析架构问题",
+ "架构分析",
+ "请说明一下",
+ ],
+)
+def test_ascii_word_boundaries_make_cjk_keywords_match(prompt):
+ r"""CJK 关键词在**紧邻**其他 CJK 字时也要命中。
+
+ 旧行为:规则用 ``\b(complex|...|复杂|架构)\b``,而 Python 的 ``\b`` 以 ``\w``
+ 定义、Unicode 下 ``\w`` 把 CJK 也算词字符 —— 「很复杂的系统」里 很/复 都是词字符、
+ 其间无边界,规则永不命中(只有写成「很 复杂 的系统」加空格才行)。
+ """
+ from jiuwenswarm.agents.harness.common.rails.model_routing.classifier import _rules
+
+ for pattern, *_ in _rules():
+ if pattern.search(prompt):
+ return
+ pytest.fail(f"no rule matched {prompt!r} — CJK 词边界回归")
+
+
+ "prompt, expected_category, expected_difficulty",
+ [
+ ("很复杂的系统怎么设计", "chat", "hard"),
+ ("请分析架构问题", "reasoning", "hard"),
+ ("架构分析", "reasoning", "hard"),
+ ],
+)
+async def test_cjk_hard_prompts_reach_hard_difficulty(prompt, expected_category, expected_difficulty):
+ """中文 hard 提示词能拿到 hard 档(修复前封顶 easy/medium,永远到不了切换线)。"""
+ score, category, difficulty = await classify(prompt)
+ assert (category, difficulty) == (expected_category, expected_difficulty)
+ assert score == SCORE_TABLE[(expected_category, expected_difficulty)]
+ assert score >= 40 # 至少达到 rail 的切换阈值
+
+
+ "prompt, should_match",
+ [
+ ("a complex system", True),
+ ("a complicated design", True),
+ ("complexity", False), # ASCII 词内不得误命中(与 \b 语义等价)
+ ("hint", False), # `hi` 前缀规则同理
+ ],
+)
+def test_ascii_boundaries_keep_english_semantics(prompt, should_match):
+ """英文语义与 ``\b`` 等价:不得在更大的 ASCII 词内部命中。"""
+ from jiuwenswarm.agents.harness.common.rails.model_routing.classifier import _ascii_word_boundaries
+ import re
+
+ pat = re.compile(_ascii_word_boundaries(r"(?i)\b(complex|complicated|advanced|复杂|架构)\b"))
+ assert (pat.search(prompt) is not None) is should_match
+
diff --git a/tests/unit_tests/agents/harness/common/rails/test_model_routing_rail.py b/tests/unit_tests/agents/harness/common/rails/test_model_routing_rail.py
index 203212e971..5c8b4e97e7 100644
--- a/tests/unit_tests/agents/harness/common/rails/test_model_routing_rail.py
+++ b/tests/unit_tests/agents/harness/common/rails/test_model_routing_rail.py
@@ -1,17 +1,13 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-"""Unit tests for ModelRoutingRail (四档模型路由).
+"""Unit tests for ModelRoutingRail(auto 档模型路由).
-Covers the written-down four-tier contract:
+Covers the written-down contract:
- fast -> deepseek-v4.1-flash 思考 off
- balanced -> deepseek-v4.1-flash 思考 medium
- extreme -> glm-5.2 思考 deep
- auto -> deepseek-v4.1-flash 思考 medium
+ auto -> 分类器打分:score >= 40 换 glm-5.3(凭证不变),否则保留当前模型
and the skip branch: a concrete model name / empty selection keeps the
-adapter-applied model; ``default`` thinking is no-op except GLM-5.3 family
-(auto-inject product default depth low).
+adapter-applied model and never switches.
"""
from __future__ import annotations
@@ -24,6 +20,9 @@ from jiuwenswarm.agents.harness.common.rails.model_routing import (
ModelCapability,
ModelRoutingRail,
)
+from jiuwenswarm.agents.harness.common.rails.model_routing import (
+ model_routing_rail as _rail_module,
+)
class _FakeModel:
@@ -41,14 +40,28 @@ class _FakeAgent:
self.model_name = model_name
self._config = SimpleNamespace(
model_name=model_name,
- model_client_config={},
- model_config_obj=None,
+ # 当前生效模型的凭证:换 glm-5.3 时必须逐字保留(api_base / api_key 不变)
+ model_client_config={
+ "model_name": model_name,
+ "api_base": "https://maas.example.com/v1",
+ "api_key": "sk-current",
+ "client_provider": "OpenAI",
+ },
+ model_config_obj={"model_name": model_name, "temperature": 0},
)
def set_llm(self, model) -> None:
self.model_name = model.model_config.model_name
+def _fake_model_builder(mcc_fields: dict, mco_fields: dict) -> _FakeModel:
+ """记录构造入参,返回只认 model_name 的假 Model(真实 Model 会拉起 Runner)。"""
+ built = _FakeModel(mcc_fields.get("model_name", ""))
+ built.built_mcc = mcc_fields
+ built.built_mco = mco_fields
+ return built
+
+
def _ctx(selection: str = "", agent: _FakeAgent | None = None) -> SimpleNamespace:
return SimpleNamespace(
agent=agent,
@@ -68,11 +81,14 @@ def _rail() -> ModelRoutingRail:
model=_FakeModel("deepseek-v4.1-flash"),
)
glm_cap = ModelCapability(
- model_name="glm-5.2",
- model_id="glm-52",
- model=_FakeModel("glm-5.2"),
+ model_name="glm-5.3",
+ model_id="glm-53",
+ model=_FakeModel("glm-5.3"),
+ )
+ return ModelRoutingRail(
+ capability_table=[flash_cap, glm_cap],
+ model_builder=_fake_model_builder,
)
- return ModelRoutingRail(capability_table=[flash_cap, glm_cap])
# ---- selection resolution ---- #
@@ -86,194 +102,346 @@ def test_resolve_request_selection_reads_run_context_extra():
assert rail._resolve_request_selection(_ctx("")) == ""
-# ---- four-tier thinking selection ---- #
+# ---- skip branch ---- #
@pytest.mark.asyncio
- "selection, thinking",
- [
- ("fast", "off"),
- ("balanced", "medium"),
- ("extreme", "deep"),
- ("auto", "medium"),
- ],
-)
-async def test_before_invoke_sets_thinking_per_tier(selection, thinking):
[email protected]("selection", ["", "gpt-5.4", "deepseek-v4.1-flash"])
+async def test_concrete_or_empty_selection_skips(selection):
rail = _rail()
- await rail.before_invoke(_ctx(selection))
- assert rail._request_thinking == thinking
- assert rail._request_mode == selection
+ agent = _FakeAgent("gpt-5.4")
+ ctx = _ctx(selection, agent=agent)
+ await rail.before_invoke(ctx)
+ assert agent.model_name == "gpt-5.4"
+ assert "_model_routing_used_cap" not in ctx.extra
+ assert "llm_call_kwargs" not in ctx.extra
+ assert ctx.extra["model_routing_decision"]["analysis"]["category"] == "skipped"
-async def test_before_model_call_injects_off_kwargs():
+# ---- _find_cap_by_name ---- #
+
+
+def test_find_cap_by_name_returns_first_same_name_ignoring_case_and_space():
+ rail = ModelRoutingRail(
+ capability_table=[
+ ModelCapability(model_name="deepseek-v4.1-flash", model_id="first"),
+ ModelCapability(model_name="deepseek-v4.1-flash", model_id="second"),
+ ],
+ )
+ cap = rail._find_cap_by_name(" DeepSeek-V4.1-Flash ")
+ assert cap is not None
+ assert cap.model_id == "first"
+ assert rail._find_cap_by_name("no-such-model") is None
+
+
+# ---- auto 档 enable_routing:分类器打分 → score >= 40 换 glm-5.3 ---- #
+
+
+def _ctx_extra(extra: dict, agent: _FakeAgent | None = None) -> SimpleNamespace:
+ return SimpleNamespace(
+ agent=agent,
+ inputs=SimpleNamespace(
+ query="你好,帮我写一个函数",
+ run_context=SimpleNamespace(extra=extra),
+ response=None,
+ ),
+ extra={},
+ )
+
+
+class _FakeTeamAgent(_FakeAgent):
+ """team 成员假 agent:额外带 build_context(成员侧读取链路)。"""
+
+ def __init__(self, model_name: str = "deepseek-v4.1-flash", metadata: dict | None = None) -> None:
+ super().__init__(model_name)
+ self.build_context = SimpleNamespace(request_metadata=metadata)
+
+
+def _team_ctx(agent: _FakeAgent | None = None) -> SimpleNamespace:
+ """team 成员 ctx:inputs **没有** run_context(openjiuwen 只传 query + conversation_id)。"""
+ return SimpleNamespace(
+ agent=agent,
+ inputs=SimpleNamespace(query="你好,帮我写一个函数", response=None),
+ extra={},
+ )
+
+
+def _classifier(score: int, category: str = "coding", difficulty: str = "hard"):
+ """假分类器:返回固定 (score, category, difficulty)。"""
+
+ async def _classify(_prompt_text: str):
+ return score, category, difficulty
+
+ return _classify
+
+
+def _routing_rail(classifier=None) -> ModelRoutingRail:
+ return ModelRoutingRail(
+ capability_table=[],
+ classifier=classifier,
+ model_builder=_fake_model_builder,
+ )
+
+
+def test_resolve_request_routing_enabled_only_accepts_strict_true():
rail = _rail()
- agent = _FakeAgent("deepseek-v4.1-flash")
- ctx = _ctx("fast", agent=agent)
+ assert rail._resolve_request_routing_enabled(_ctx_extra({"enable_routing": True})) is True
+ # 非布尔真值一律不算开启:adapter 侧已按 is True 过滤,这里再兜一层。
+ for value in (False, None, "true", "True", 1, 0, {}, []):
+ assert rail._resolve_request_routing_enabled(_ctx_extra({"enable_routing": value})) is False
+ assert rail._resolve_request_routing_enabled(_ctx_extra({})) is False
+
+
+def test_resolve_request_routing_enabled_false_without_run_context():
+ rail = _rail()
+ ctx = SimpleNamespace(agent=None, inputs=SimpleNamespace(query=""), extra={})
+ assert rail._resolve_request_routing_enabled(ctx) is False
+
+
+# ---- team 成员侧读取链路(成员拿不到 run_context)---- #
+
+
+def test_resolve_request_routing_enabled_reads_team_build_context():
+ """team 成员无 run_context → 回落到成员自身 BuildContext.request_metadata。"""
+ rail = _rail()
+ assert rail._resolve_request_routing_enabled(
+ _team_ctx(_FakeTeamAgent(metadata={"enable_routing": True}))
+ ) is True
+ # 与单 agent 同款严格判 is True
+ for value in (False, None, "true", 1, 0, {}, []):
+ assert rail._resolve_request_routing_enabled(
+ _team_ctx(_FakeTeamAgent(metadata={"enable_routing": value}))
+ ) is False
+ assert rail._resolve_request_routing_enabled(
+ _team_ctx(_FakeTeamAgent(metadata={}))
+ ) is False
+ assert rail._resolve_request_routing_enabled(_team_ctx(_FakeTeamAgent())) is False
+ # 无 build_context(普通单 agent)→ False,不抛
+ assert rail._resolve_request_routing_enabled(_team_ctx(_FakeAgent())) is False
+
+
+def test_resolve_request_routing_enabled_run_context_wins_over_team_metadata():
+ """单 agent 链路优先;team 侧只是 run_context 缺省时的兜底。"""
+ rail = _rail()
+ agent = _FakeTeamAgent(metadata={"enable_routing": True})
+ ctx = _ctx_extra({"enable_routing": False}, agent=agent)
+ ctx.inputs.run_context.extra = {} # 单 agent 链路没有开关 → 落到 team 侧
+ assert rail._resolve_request_routing_enabled(ctx) is True
+ ctx.inputs.run_context.extra = {"enable_routing": False} # 显式 False → 仍落到 team 侧
+ assert rail._resolve_request_routing_enabled(ctx) is True
+
+
+async def test_enable_routing_team_member_high_score_switches_to_glm():
+ """team 成员(无 run_context)同样按开关打分换模型,凭证不变。"""
+ rail = _routing_rail(_classifier(80))
+ agent = _FakeTeamAgent(metadata={"enable_routing": True})
+ ctx = _team_ctx(agent)
+
await rail.before_invoke(ctx)
- await rail.before_model_call(ctx)
- assert ctx.extra["llm_call_kwargs"] == {"extra_body": {"thinking": {"type": "disabled"}}}
+
+ assert agent.model_name == "glm-5.3"
+ used = ctx.extra["_model_routing_used_cap"]
+ assert used.model.built_mcc["api_key"] == "sk-current"
+ assert used.model.built_mcc["api_base"] == "https://maas.example.com/v1"
@pytest.mark.asyncio
-async def test_before_model_call_injects_deep_kwargs():
- rail = _rail()
- agent = _FakeAgent("glm-5.2")
- ctx = _ctx("extreme", agent=agent)
+async def test_enable_routing_team_member_low_score_keeps_fallback_model():
+ """team 成员低分 → 保留保底模型。"""
+ rail = _routing_rail(_classifier(5, category="chat", difficulty="easy"))
+ agent = _FakeTeamAgent(metadata={"enable_routing": True})
+ ctx = _team_ctx(agent)
+
await rail.before_invoke(ctx)
- await rail.before_model_call(ctx)
- assert ctx.extra["llm_call_kwargs"] == {
- "extra_body": {"thinking": {"type": "enabled"}},
- "reasoning_effort": "high",
- }
+
+ assert agent.model_name == "deepseek-v4.1-flash"
+ assert ctx.extra.get("_model_routing_used_cap") is None
@pytest.mark.asyncio
-async def test_injected_kwargs_are_isolated_per_call():
- rail = _rail()
+async def test_enable_routing_high_score_switches_to_glm():
+ """score >= 40 → set_llm 换 glm-5.3,且 api_base / api_key 逐字不变。"""
+ rail = _routing_rail(_classifier(80))
agent = _FakeAgent("deepseek-v4.1-flash")
- ctx = _ctx("balanced", agent=agent)
+ ctx = _ctx_extra({"enable_routing": True, "model_selection": "auto"}, agent=agent)
+
await rail.before_invoke(ctx)
- await rail.before_model_call(ctx)
- # Mutating the injected dict must not affect the next call's kwargs.
- ctx.extra["llm_call_kwargs"]["extra_body"]["thinking"]["type"] = "disabled"
- ctx2 = _ctx("balanced", agent=_FakeAgent("deepseek-v4.1-flash"))
- await rail.before_invoke(ctx2)
- await rail.before_model_call(ctx2)
- assert ctx2.extra["llm_call_kwargs"]["extra_body"]["thinking"]["type"] == "enabled"
+ assert agent.model_name == "glm-5.3"
+ used = ctx.extra["_model_routing_used_cap"]
+ assert used.model_name == "glm-5.3"
+ # 换模型不换凭证
+ assert used.model.built_mcc["api_base"] == "https://maas.example.com/v1"
+ assert used.model.built_mcc["api_key"] == "sk-current"
+ assert used.model.built_mcc["client_provider"] == "OpenAI"
+ assert used.model.built_mcc["model_name"] == "glm-5.3"
-# ---- skip branch ---- #
+
[email protected]("score", [0, 25, 39])
+async def test_enable_routing_low_score_keeps_current_model(score):
+ """score < 40(含边界 39)→ 保留 adapter 已应用的保底模型,不 set_llm。"""
+ rail = _routing_rail(_classifier(score))
+ agent = _FakeAgent("deepseek-v4.1-flash")
+ ctx = _ctx_extra({"enable_routing": True, "model_selection": "auto"}, agent=agent)
+
+ await rail.before_invoke(ctx)
+
+ assert agent.model_name == "deepseek-v4.1-flash"
+ assert ctx.extra.get("_model_routing_used_cap") is None
+ assert ctx.extra["model_routing_decision"]["analysis"]["target_score"] == score
@pytest.mark.asyncio
[email protected]("selection", ["", "gpt-5.4"])
-async def test_concrete_unsupported_model_skips_thinking_inject(selection):
- rail = _rail()
- agent = _FakeAgent("gpt-5.4")
- ctx = _ctx(selection, agent=agent)
[email protected]("score", [40, 41, 45, 60, 65])
+async def test_enable_routing_at_or_above_threshold_switches(score):
+ """score >= 40(含边界 40)→ 换 glm-5.3。边界含 40 是本契约的一部分。"""
+ rail = _routing_rail(_classifier(score))
+ agent = _FakeAgent("deepseek-v4.1-flash")
+ ctx = _ctx_extra({"enable_routing": True, "model_selection": "auto"}, agent=agent)
+
await rail.before_invoke(ctx)
- await rail.before_model_call(ctx)
- assert rail._request_thinking == "default"
- assert agent.model_name == "gpt-5.4"
- assert "_model_routing_used_cap" not in ctx.extra
- assert "llm_call_kwargs" not in ctx.extra
- assert ctx.extra["model_routing_decision"]["analysis"]["category"] == "skipped"
+
+ assert agent.model_name == "glm-5.3"
+ assert ctx.extra["_model_routing_used_cap"].model_name == "glm-5.3"
@pytest.mark.asyncio
-async def test_concrete_non_glm53_allowlisted_skips_default_inject():
- rail = _rail()
+async def test_enable_routing_continuation_keeps_current_model():
+ """续写/确认指令(分类器哨兵)→ 不换模型,即使哨兵值会被 validate_score 兜底成 60。"""
+ from jiuwenswarm.agents.harness.common.rails.model_routing.classifier import (
+ CONTINUATION_CATEGORY,
+ CONTINUATION_SCORE,
+ )
+
+ rail = _routing_rail(_classifier(CONTINUATION_SCORE, category=CONTINUATION_CATEGORY))
agent = _FakeAgent("deepseek-v4.1-flash")
- ctx = _ctx("deepseek-v4.1-flash", agent=agent)
+ ctx = _ctx_extra({"enable_routing": True, "model_selection": "auto"}, agent=agent)
+
await rail.before_invoke(ctx)
- await rail.before_model_call(ctx)
- assert rail._request_thinking == "default"
- assert "llm_call_kwargs" not in ctx.extra
+
+ assert agent.model_name == "deepseek-v4.1-flash"
+ assert ctx.extra["model_routing_decision"]["analysis"]["category"] == "skipped"
@pytest.mark.asyncio
-async def test_concrete_glm53_injects_effort_low():
- rail = _rail()
- agent = _FakeAgent("glm-5.3-test")
- ctx = _ctx("glm-5.3-test", agent=agent)
+async def test_enable_routing_without_classifier_keeps_current_model():
+ """显式 classifier=None(关闭 auto 档路由)→ 保留保底模型,不报错、不换模型。"""
+ rail = _routing_rail(None)
+ agent = _FakeAgent("deepseek-v4.1-flash")
+ ctx = _ctx_extra({"enable_routing": True, "model_selection": "auto"}, agent=agent)
+
await rail.before_invoke(ctx)
- await rail.before_model_call(ctx)
- assert ctx.extra["llm_call_kwargs"]["extra_body"]["thinking"]["type"] == "enabled"
- assert ctx.extra["llm_call_kwargs"]["reasoning_effort"] == "low"
+ assert agent.model_name == "deepseek-v4.1-flash"
+ assert ctx.extra.get("_model_routing_used_cap") is None
+
+
+async def test_enable_routing_lazily_loads_default_classifier():
+ """未注入 classifier → 懒加载内置 classifier.py 打分。"""
+ rail = ModelRoutingRail(capability_table=[], model_builder=_fake_model_builder)
+ agent = _FakeAgent("deepseek-v4.1-flash")
+ ctx = _ctx_extra({"enable_routing": True, "model_selection": "auto"}, agent=agent)
+ ctx.inputs.query = "debug this code"
+
+ await rail.before_invoke(ctx)
-# ---- switch branch ---- #
+ assert agent.model_name == "glm-5.3"
@pytest.mark.asyncio
-async def test_mode_switch_applies_set_llm():
- rail = _rail()
- agent = _FakeAgent("gpt-5.4")
- ctx = _ctx("balanced", agent=agent)
+async def test_enable_routing_default_classifier_load_failure_keeps_current_model(monkeypatch):
+ """内置分类器装载失败(import 报错)→ 降级保留保底模型,不影响 invoke。"""
+ monkeypatch.setattr(_rail_module, "_load_default_classifier", lambda: None)
+ rail = ModelRoutingRail(capability_table=[], model_builder=_fake_model_builder)
+ agent = _FakeAgent("deepseek-v4.1-flash")
+ ctx = _ctx_extra({"enable_routing": True, "model_selection": "auto"}, agent=agent)
+
await rail.before_invoke(ctx)
+
assert agent.model_name == "deepseek-v4.1-flash"
- assert ctx.extra["_model_routing_used_cap"].model_name == "deepseek-v4.1-flash"
+ assert ctx.extra.get("_model_routing_used_cap") is None
@pytest.mark.asyncio
-async def test_extreme_switches_to_glm():
- rail = _rail()
- agent = _FakeAgent("gpt-5.4")
- ctx = _ctx("extreme", agent=agent)
+async def test_enable_routing_classifier_exception_keeps_current_model():
+ """分类器抛异常 → 保留保底模型,不让异常冒泡出 before_invoke。"""
+
+ async def _boom(_prompt_text: str):
+ raise RuntimeError("classifier exploded")
+
+ rail = _routing_rail(_boom)
+ agent = _FakeAgent("deepseek-v4.1-flash")
+ ctx = _ctx_extra({"enable_routing": True, "model_selection": "auto"}, agent=agent)
+
await rail.before_invoke(ctx)
- assert agent.model_name == "glm-5.2"
+
+ assert agent.model_name == "deepseek-v4.1-flash"
@pytest.mark.asyncio
-async def test_mode_model_missing_keeps_current_without_thinking_injection():
- """档位目标模型不在能力表 → keep current,且不注入档位 thinking kwargs。
+async def test_enable_routing_logs_high_score_switch(monkeypatch):
+ """换模型时日志可见(llm.log 是 E2E 的观测面)。
- CR-2:keep-current 路径当前模型 vendor 未知,DeepSeek/GLM 风格 extra_body.thinking
- 对 OpenAI 官方端点会 400,故 _request_thinking 保持 "default"、before_model_call no-op。
+ 直接 patch 模块级 ``logger``:``jiuwenswarm.common.utils`` 的 logger 自带 handler、
+ 不向 root propagate,且 handler 在导入期就绑定了原始 stderr 流 —— caplog(root 级)
+ 与 capfd(fd 级)都抓不到。
"""
- rail = ModelRoutingRail(capability_table=[])
- agent = _FakeAgent("gpt-5.4")
- ctx = _ctx("fast", agent=agent)
+ logged: list[str] = []
+ monkeypatch.setattr(
+ _rail_module.logger,
+ "info",
+ lambda msg, *args, **kwargs: logged.append(msg % args if args else msg),
+ )
+ rail = _routing_rail(_classifier(80))
+ agent = _FakeAgent("deepseek-v4.1-flash")
+ ctx = _ctx_extra({"enable_routing": True, "model_selection": "auto"}, agent=agent)
+
await rail.before_invoke(ctx)
- assert agent.model_name == "gpt-5.4"
- assert rail._request_thinking == "default"
- await rail.before_model_call(ctx)
- assert "llm_call_kwargs" not in ctx.extra
+ assert any("set_llm glm-5.3" in line for line in logged)
-# ---- 优先 maas 官方模型(避免撞用户自定义同名模型)---- #
+# ---- auto 档端到端:真分类器 + 真阈值 ---- #
-def test_find_cap_prefers_marked_provider():
- """同名 cap 里带 maas 标的(即使排后面)优先命中,不撞用户自定义同名模型。"""
- rail = ModelRoutingRail(
- capability_table=[
- ModelCapability(model_name="deepseek-v4.1-flash", model_id="custom", model_provider="openai"),
- ModelCapability(model_name="deepseek-v4.1-flash", model_id="maas", model_provider="huawei_maas"),
- ],
- )
- cap = rail._find_cap_by_name("deepseek-v4.1-flash", prefer_provider="huawei_maas")
- assert cap is not None
- assert cap.model_id == "maas"
+def _real_classifier_rail() -> ModelRoutingRail:
+ from jiuwenswarm.agents.harness.common.rails.model_routing.classifier import classify
-def test_find_cap_falls_back_to_first_when_no_mark():
- """无标能力表(现状/向后兼容):退回第一个同名,行为与旧实现一致。"""
- rail = ModelRoutingRail(
- capability_table=[
- ModelCapability(model_name="deepseek-v4.1-flash", model_id="first"),
- ModelCapability(model_name="deepseek-v4.1-flash", model_id="second"),
- ],
+ return ModelRoutingRail(
+ capability_table=[],
+ classifier=classify,
+ model_builder=_fake_model_builder,
)
- cap = rail._find_cap_by_name("deepseek-v4.1-flash", prefer_provider="huawei_maas")
- assert cap is not None
- assert cap.model_id == "first"
@pytest.mark.asyncio
-async def test_mode_switch_prefers_marked_model_even_when_later():
- """四档 before_invoke 端到端:同名自定义模型排前、maas 排后,仍切到 maas。"""
- rail = ModelRoutingRail(
- capability_table=[
- ModelCapability(
- model_name="deepseek-v4.1-flash",
- model_id="custom",
- model=_FakeModel("deepseek-v4.1-flash"),
- model_provider="openai",
- ),
- ModelCapability(
- model_name="deepseek-v4.1-flash",
- model_id="maas",
- model=_FakeModel("deepseek-v4.1-flash"),
- model_provider="huawei_maas",
- ),
- ],
- )
- agent = _FakeAgent("gpt-5.4")
- ctx = _ctx("balanced", agent=agent)
+async def test_real_classifier_high_score_prompt_switches_to_glm():
+ """真分类器把「debug this code」打成 65(coding/hard)>= 40 → set_llm glm-5.3,凭证不变。"""
+ rail = _real_classifier_rail()
+ agent = _FakeAgent("deepseek-v4.1-flash")
+ ctx = _ctx_extra({"enable_routing": True, "model_selection": "auto"}, agent=agent)
+ ctx.inputs.query = "debug this code"
+
await rail.before_invoke(ctx)
- used = ctx.extra.get("_model_routing_used_cap")
- assert used is not None
- assert used.model_id == "maas"
+
+ assert agent.model_name == "glm-5.3"
+ used = ctx.extra["_model_routing_used_cap"]
+ assert used.model.built_mcc["api_key"] == "sk-current"
+ assert used.model.built_mcc["api_base"] == "https://maas.example.com/v1"
+
+
+async def test_real_classifier_low_score_prompt_keeps_fallback_model():
+ """真分类器把「你好」打成 5(chat/easy)< 40 → 保留保底模型。"""
+ rail = _real_classifier_rail()
+ agent = _FakeAgent("deepseek-v4.1-flash")
+ ctx = _ctx_extra({"enable_routing": True, "model_selection": "auto"}, agent=agent)
+ ctx.inputs.query = "你好"
+
+ await rail.before_invoke(ctx)
+
+ assert agent.model_name == "deepseek-v4.1-flash"
+ assert ctx.extra.get("_model_routing_used_cap") is None
diff --git a/tests/unit_tests/agentserver/test_deepresearch_task_manager.py b/tests/unit_tests/agentserver/test_deepresearch_task_manager.py
index d7dbb1ffb5..892374f256 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_task_manager.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_task_manager.py
@@ -419,32 +419,22 @@ def test_explicit_petal_snapshot_never_reads_bound_tenant_overlay():
assert tenant_a_url not in repr((detected, loaded))
-def test_load_config_translates_model_gear_to_concrete_model():
- """档位关键字只能到隔离子进程边界为止,必须翻成具体模型 id。
-
- DeepResearch 子进程走 env 通道(宿主有效模型 env → MODEL_NAME),
- 没有 rail 也没有 request params。裸档位关键字直送上游会被判无效模型
- (Invalid model,211800/181001 那串报错的根因)。
- """
+def test_load_config_passes_model_name_through_unchanged():
+ """模型名原样透传给隔离子进程(不做任何翻译)。"""
from jiuwenswarm.agents.harness.common.tools.deepresearch_task_manager import (
load_deepresearch_config,
)
- base = {"API_BASE": "https://llm.example/v2/", "API_KEY": "k"}
-
- assert load_deepresearch_config({**base, "MODEL_NAME": "extreme"})["LLM_MODEL_NAME"] == "glm-5.2"
- for gear in ("fast", "balanced", "auto"):
- assert load_deepresearch_config({**base, "MODEL_NAME": gear})["LLM_MODEL_NAME"] == "deepseek-v4.1-flash"
- # 显式 LLM_MODEL_NAME 优先,但同样要过表(同一通道,同一风险)。
- assert load_deepresearch_config({**base, "LLM_MODEL_NAME": "extreme", "MODEL_NAME": "glm-5.2"})[
- "LLM_MODEL_NAME"
- ] == "glm-5.2"
+ base = {"API_BASE": "https://maas.example/v2/", "API_KEY": "k"}
- # 具体模型名原样透传,不能被误翻。
assert load_deepresearch_config({**base, "MODEL_NAME": "glm-5.2"})["LLM_MODEL_NAME"] == "glm-5.2"
assert load_deepresearch_config({**base, "MODEL_NAME": "deepseek-v4.1-flash"})["LLM_MODEL_NAME"] == (
"deepseek-v4.1-flash"
)
+ # 显式 LLM_MODEL_NAME 优先。
+ assert load_deepresearch_config({**base, "LLM_MODEL_NAME": "glm-5.2", "MODEL_NAME": "deepseek-v4.1-flash"})[
+ "LLM_MODEL_NAME"
+ ] == "glm-5.2"
@pytest.mark.parametrize(
diff --git a/tests/unit_tests/agentserver/test_enable_routing_injection.py b/tests/unit_tests/agentserver/test_enable_routing_injection.py
new file mode 100644
index 0000000000..7d8d2ccc9a
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_enable_routing_injection.py
@@ -0,0 +1,82 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Unit tests for the auto-gear ``enable_routing`` request injection.
+
+relay 的 auto 档在 ``params.model_name`` 上仍下发**保底具体模型名**,另置
+``params.enable_routing=True`` 表达「本帧模型名可被路由覆盖」。adapter 侧把它写进
+``inputs["run"]["context"]["extra"]["enable_routing"]``,供 ``ModelRoutingRail``
+每请求读取(本阶段只打日志、不切换模型)。
+
+关键约束:
+- 严格判 ``is True``:缺省 / ``False`` / 非布尔(含字符串 "true")一律**不写**,
+ 避免任何异常输入把 rail 从「跳过」翻成「真路由」。
+- 与 ``model_selection`` 共用同一层 ``run_context.extra``,互不覆盖。
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapter
+
+
+def _request(params: object) -> SimpleNamespace:
+ return SimpleNamespace(params=params)
+
+
+def _extra_of(inputs: dict) -> dict:
+ return inputs["run"]["context"]["extra"]
+
+
+def test_inject_writes_flag_for_strict_true():
+ inputs: dict = {}
+ JiuWenSwarmDeepAdapter._inject_model_routing_into_inputs(
+ _request({"enable_routing": True}), inputs
+ )
+ assert _extra_of(inputs)["enable_routing"] is True
+
+
[email protected]("value", [False, None, "true", "True", 1, 0, "1", {}, []])
+def test_inject_skips_every_non_boolean_true(value):
+ inputs: dict = {}
+ JiuWenSwarmDeepAdapter._inject_model_routing_into_inputs(
+ _request({"enable_routing": value}), inputs
+ )
+ assert inputs == {}
+
+
+def test_inject_skips_when_key_absent():
+ inputs: dict = {}
+ JiuWenSwarmDeepAdapter._inject_model_routing_into_inputs(_request({"model_name": "auto"}), inputs)
+ assert inputs == {}
+
+
+def test_inject_skips_non_dict_params():
+ for params in (None, "enable_routing=true", ["enable_routing"], 1):
+ inputs: dict = {}
+ JiuWenSwarmDeepAdapter._inject_model_routing_into_inputs(_request(params), inputs)
+ assert inputs == {}
+
+
+def test_inject_coexists_with_model_selection():
+ """两个键写进同一层 run_context.extra,互不覆盖。"""
+ inputs: dict = {}
+ request = _request({"model_name": "deepseek-v4.1-flash", "enable_routing": True})
+ JiuWenSwarmDeepAdapter._inject_model_selection_into_inputs(request, inputs)
+ JiuWenSwarmDeepAdapter._inject_model_routing_into_inputs(request, inputs)
+
+ extra = _extra_of(inputs)
+ assert extra["model_selection"] == "deepseek-v4.1-flash"
+ assert extra["enable_routing"] is True
+
+
+def test_inject_is_idempotent_and_preserves_other_extra_keys():
+ inputs = {"run": {"context": {"extra": {"model_selection": "auto"}}}}
+ request = _request({"enable_routing": True})
+ JiuWenSwarmDeepAdapter._inject_model_routing_into_inputs(request, inputs)
+ JiuWenSwarmDeepAdapter._inject_model_routing_into_inputs(request, inputs)
+
+ extra = _extra_of(inputs)
+ assert extra == {"model_selection": "auto", "enable_routing": True}
diff --git a/tests/unit_tests/agentserver/test_evolve_command_edges.py b/tests/unit_tests/agentserver/test_evolve_command_edges.py
index 857a7bdea4..98f6381dfb 100644
--- a/tests/unit_tests/agentserver/test_evolve_command_edges.py
+++ b/tests/unit_tests/agentserver/test_evolve_command_edges.py
@@ -541,8 +541,14 @@ async def test_agent_non_stream_slash_followup_continues_into_runner(monkeypatch
{"query": "/evolve code-runner"},
)
+ # run.context.extra.request_id 由 adapter 逐请求注入,供 ModelRouting rail
+ # 重绑日志的 [req=] 标签(agent 跑在跨请求复用的 task 上,ContextVar 可能是陈旧值)。
assert seen_inputs == [
- {"query": "review and evolve code-runner", "_invoke_turn_id": "req-followup"}
+ {
+ "query": "review and evolve code-runner",
+ "run": {"context": {"extra": {"request_id": "req-followup"}}},
+ "_invoke_turn_id": "req-followup",
+ }
]
assert response.ok is True
assert response.payload == {"content": "agent completed"}
@@ -582,7 +588,11 @@ async def test_agent_stream_slash_followup_continues_into_runner(monkeypatch):
chunks.append(chunk)
assert seen_inputs == [
- {"query": "review and simplify code-runner", "_invoke_turn_id": "req-followup-stream"}
+ {
+ "query": "review and simplify code-runner",
+ "run": {"context": {"extra": {"request_id": "req-followup-stream"}}},
+ "_invoke_turn_id": "req-followup-stream",
+ }
]
assert chunks[0].payload == {"event_type": "chat.delta", "content": "agent delta"}
assert chunks[-1].is_complete is True
diff --git a/tests/unit_tests/agentserver/test_model_gear_translation.py b/tests/unit_tests/agentserver/test_model_gear_translation.py
deleted file mode 100644
index 4bd972eb0b..0000000000
--- a/tests/unit_tests/agentserver/test_model_gear_translation.py
+++ /dev/null
@@ -1,220 +0,0 @@
-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
-
-"""档位关键字(fast/balanced/extreme/auto)必须在构建 Model 的唯一入口翻成具体模型。
-
-背景:档位关键字有两条通道。单 agent 主链路走 request param,由 ModelRoutingRail
-翻译;另一条经有效模型 env → MODEL_NAME → config.yaml models.defaults 直接流进
-``_build_model_from_entry`` 构建 Model。没有 rail 的消费方——子代理(deep_agent
-直接继承 ``_deep_config.model``,且 ``subagent_rails=None`` 不继承父 rail)、code
-模式、DeepResearch 隔离子进程——会把裸档位当模型名直送上游网关,触发模型无效类错误。
-"""
-
-from __future__ import annotations
-
-import pytest
-
-from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapter
-
-
-def _entry(model_name: str) -> dict:
- return {
- "is_default": True,
- "model_client_config": {
- "model_name": model_name,
- "client_provider": "OpenAI",
- "api_base": "https://llm.example/v2/",
- "api_key": "k",
- },
- "model_config_obj": {},
- }
-
-
-def _wire_model_name(model) -> str:
- """实际发往上游网关的模型名(ModelRequestConfig.model_name,alias="model")。"""
- return str(getattr(model.model_config, "model_name", "") or "")
-
-
- ("gear", "concrete"),
- [
- ("extreme", "glm-5.2"),
- ("fast", "deepseek-v4.1-flash"),
- ("balanced", "deepseek-v4.1-flash"),
- ("auto", "deepseek-v4.1-flash"),
- ],
-)
-def test_build_model_from_entry_translates_gear_for_wire_name(gear: str, concrete: str) -> None:
- mcc = _entry(gear)["model_client_config"]
- model = JiuWenSwarmDeepAdapter._build_model_from_entry(mcc, {})
-
- assert _wire_model_name(model) == concrete
- # mcc 不被改写:cache key / identity 仍按档位关键字登记,relay 按档位选择不受影响。
- assert mcc["model_name"] == gear
-
-
[email protected]("concrete", ["glm-5.2", "deepseek-v4.1-flash", "gpt-4"])
-def test_build_model_from_entry_passes_through_concrete_model(concrete: str) -> None:
- model = JiuWenSwarmDeepAdapter._build_model_from_entry(_entry(concrete)["model_client_config"], {})
-
- assert _wire_model_name(model) == concrete
-
-
-def test_subagent_resolving_by_gear_gets_concrete_wire_model() -> None:
- """子代理按档位关键字解析时,拿到的 Model 必须发具体模型 id。"""
- adapter = object.__new__(JiuWenSwarmDeepAdapter)
- adapter._model_cache = {}
- adapter._model_name_to_keys = {}
- adapter._model_identity_to_keys = {}
- adapter._model_identity_owners = {}
- adapter._tier_model_cache = {}
- adapter._model = None
- adapter._instance = None
-
- adapter._register_model_cache_entry(_entry("extreme"), {})
-
- # 档位关键字仍是合法查找键(relay 按档位下发 model_name / model_ref 时命中)。
- assert "extreme" in adapter._model_cache
- # 真实链路里 _create_model 一定会给出默认 Model;子代理解析入口要求它非空。
- adapter._model = adapter._model_cache["extreme"]
-
- model, _fallback = adapter._resolve_model_for_subagent(model_name="extreme")
-
- assert _wire_model_name(model) == "glm-5.2"
-
-
-def test_mode_model_map_covers_four_gears() -> None:
- """四档关键字必须全部出现在 MODE_MODEL_MAP,避免漏档导致上游模型无效。
-
- 宿主产品若另有档位映射表,须与本表同表同源;新增档位时两边同步改。
- 本测试锁当前四档集合与市场 wire id。
- """
- from jiuwenswarm.agents.harness.common.model_gears import MODE_MODEL_MAP, MODEL_GEAR_NAMES
-
- expected_gears = {
- "fast": "deepseek-v4.1-flash",
- "balanced": "deepseek-v4.1-flash",
- "extreme": "glm-5.2",
- "auto": "deepseek-v4.1-flash",
- }
- assert MODEL_GEAR_NAMES == frozenset(expected_gears)
- assert MODE_MODEL_MAP == expected_gears
-
-
-def test_sync_agent_compressor_models_rebinds_live_processors() -> None:
- """主对话换模后,已缓存的压缩器 _model 必须跟着换。"""
- from types import SimpleNamespace
-
- from jiuwenswarm.agents.harness.common.model_gears import sync_agent_compressor_models
-
- class _Proc:
- def __init__(self) -> None:
- self._model = SimpleNamespace(model_config=SimpleNamespace(model_name="extreme"))
- self._compression_executor = object()
-
- old_model = SimpleNamespace(
- model_config=SimpleNamespace(model_name="extreme"),
- model_client_config={"api_base": "https://old"},
- )
- new_model = SimpleNamespace(
- model_config=SimpleNamespace(model_name="glm-5.2"),
- model_client_config={"api_base": "https://new"},
- )
- proc = _Proc()
- pcfg = SimpleNamespace(model=old_model.model_config, model_client=old_model.model_client_config)
- react = SimpleNamespace(
- _config=SimpleNamespace(context_processors=[("DialogueCompressor", pcfg)]),
- context_engine=SimpleNamespace(_context_pool={"sid_ctx": SimpleNamespace(_processors=[proc])}),
- )
-
- updated = sync_agent_compressor_models(react, new_model)
-
- assert updated == 1
- assert proc._model is new_model
- assert pcfg.model is new_model.model_config
- assert pcfg.model_client is new_model.model_client_config
- # 依赖在位时 CompressionExecutor 必须重建成功,且不再是换模前的 sentinel。
- assert proc._compression_executor is not None
-
-
-def test_sync_agent_compressor_models_skips_failed_executor_rebuild(monkeypatch) -> None:
- """执行器重建失败时置空,且不把该 processor 算进成功数。"""
- from types import SimpleNamespace
-
- from jiuwenswarm.agents.harness.common import model_gears
-
- class _Proc:
- def __init__(self) -> None:
- self._model = None
- self._compression_executor = object()
-
- def _boom(_model: object) -> object:
- raise RuntimeError("executor unavailable")
-
- monkeypatch.setattr(model_gears, "_new_compression_executor", _boom)
- new_model = SimpleNamespace(
- model_config=SimpleNamespace(model_name="glm-5.2"),
- model_client_config={"api_base": "https://new"},
- )
- proc = _Proc()
- react = SimpleNamespace(
- context_engine=SimpleNamespace(_context_pool={"sid": SimpleNamespace(_processors=[proc])}),
- )
-
- updated = model_gears.sync_agent_compressor_models(react, new_model)
-
- assert updated == 0
- assert proc._model is new_model
- assert proc._compression_executor is None
-
-
-def test_sync_rebinds_inherited_session_memory_and_keeps_explicit_model() -> None:
- """只重绑从主模型继承来的会话记忆,显式 memory.model 不动。"""
- from types import SimpleNamespace
-
- from jiuwenswarm.agents.harness.common.model_gears import sync_agent_compressor_models
-
- old_model = SimpleNamespace(
- model_config=SimpleNamespace(model_name="extreme"),
- model_client_config={"api_base": "https://old"},
- )
- new_model = SimpleNamespace(
- model_config=SimpleNamespace(model_name="glm-5.2"),
- model_client_config={"api_base": "https://new"},
- )
- explicit_model = SimpleNamespace(model_name="custom-memory")
- explicit_client = {"api_base": "https://explicit"}
- inherited = SimpleNamespace(
- config=SimpleNamespace(
- model=old_model.model_config,
- model_client=old_model.model_client_config,
- ),
- _update_agent=SimpleNamespace(_agent=object(), _direct_model=object(), _workspace_root="/old"),
- )
- explicit = SimpleNamespace(
- config=SimpleNamespace(model=explicit_model, model_client=explicit_client),
- _update_agent=SimpleNamespace(_agent=object(), _direct_model=object(), _workspace_root="/keep"),
- )
- host = SimpleNamespace(
- _registered_rails=[
- SimpleNamespace(_session_memory_mgr=inherited),
- SimpleNamespace(_session_memory_mgr=explicit),
- ],
- )
- react = SimpleNamespace()
-
- updated = sync_agent_compressor_models(
- react,
- new_model,
- host=host,
- previous_model=old_model,
- )
-
- assert updated == 1
- assert inherited.config.model is new_model.model_config
- assert inherited.config.model_client is new_model.model_client_config
- assert inherited._update_agent._agent is None
- assert inherited._update_agent._direct_model is None
- assert inherited._update_agent._workspace_root is None
- assert explicit.config.model is explicit_model
- assert explicit.config.model_client is explicit_client
- assert explicit._update_agent._agent is not None