argo-search 2.10.1 → 2.10.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +30 -4
- package/README.es.md +30 -4
- package/README.ja.md +30 -4
- package/README.ko.md +30 -4
- package/README.md +30 -24
- package/SKILL.md +1 -1
- package/backends/concept_vectors.bin +0 -0
- package/backends/engine_concept_vectors.json +3104 -0
- package/config.yaml +82 -14
- package/docs/RELEASE_NOTES_v2.10.2.md +48 -0
- package/package.json +2 -1
- package/packages/dsh-plugin/dsh/diagnostics.js +8 -3
- package/packages/dsh-plugin/dsh/index.js +7 -7
- package/packages/dsh-plugin/dsh/runner.js +72 -46
- package/packages/dsh-plugin/package.json +1 -1
- package/packages/dsh-plugin/test/index.test.js +43 -0
- package/scripts/argo_engine_registry.py +30 -4
- package/scripts/argo_paths.py +7 -1
- package/scripts/build_concept_table.py +612 -0
- package/scripts/build_route_labels.py +285 -0
- package/scripts/caliber_dedupe.py +66 -0
- package/scripts/caliber_isolation.py +4 -2
- package/scripts/circuit_breaker.py +25 -3
- package/scripts/concept_lookup.py +212 -0
- package/scripts/engines.py +24 -7
- package/scripts/engines_base.py +17 -2
- package/scripts/engines_builders_skill.py +87 -10
- package/scripts/extend_route_labels.py +239 -0
- package/scripts/extend_route_labels_by_capability.py +344 -0
- package/scripts/gen_routing_snapshot.py +22 -3
- package/scripts/lang_detect.py +12 -3
- package/scripts/local_seek.py +13 -3
- package/scripts/mcp_transport.py +1 -1
- package/scripts/numeric_verify.py +330 -0
- package/scripts/plan.py +25 -4
- package/scripts/pre-commit +2 -2
- package/scripts/rank_signals.py +48 -4
- package/scripts/ranking_eval.py +23 -1
- package/scripts/regression_p0p1.py +7 -2
- package/scripts/route.py +24 -3
- package/scripts/route_accuracy_eval.py +191 -0
- package/scripts/route_combo.py +32 -1
- package/scripts/route_domains.py +242 -5
- package/scripts/route_primary.py +101 -0
- package/scripts/search.py +1 -0
- package/scripts/search_cli.py +89 -7
- package/scripts/search_output.py +59 -1
- package/scripts/search_pipeline.py +5 -0
- package/scripts/snippet_clean.py +60 -0
- package/scripts/social_engines/twitter_engine.py +127 -43
- package/scripts/social_engines/xiaohongshu_engine.py +11 -1
- package/scripts/tfidf_router.py +52 -2
- package/scripts/train.py +15 -0
- package/scripts/verify_with.py +124 -0
- package/sub-skills/local-search/SKILL.md +3 -2
- package/sub-skills/local-search/bm25.py +89 -8
- package/sub-skills/local-search/config.yaml +12 -0
- package/sub-skills/local-search/parse_maps.yaml +8 -0
- package/sub-skills/local-search/parsers.py +5 -2
- package/sub-skills/local-search/search_v3.py +87 -1
- package/sub-skills/local-search/smart_router.py +1 -1
- package/sub-skills/local-seek/SKILL.md +6 -5
- package/sub-skills/local-seek/scripts/eval_rank.py +1 -1
- package/sub-skills/local-seek/scripts/seek.py +152 -36
- package/sub-skills/local-seek/scripts/seek_rank.py +191 -11
- package/scripts/image_vision/vision_probe +0 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""route_accuracy_eval.py — 真实查询分布上的路由回归与分布视图(离线,不联网)。
|
|
3
|
+
|
|
4
|
+
## 与既有门的关系
|
|
5
|
+
|
|
6
|
+
- `test_routing_snapshot`:判 201 条语料的 `domain+kind` **不漂移**(回归门);
|
|
7
|
+
- `test_route_accuracy_labeled`:判 13 条人工标注的**意图对不对**(准确率门);
|
|
8
|
+
- 本脚本:在 ~500 条真实查询上算**回归一致率与分布视图**(评测门,出数字)。
|
|
9
|
+
|
|
10
|
+
三者互补:快照防回归,人工集判意图,本脚本看真实分布。
|
|
11
|
+
|
|
12
|
+
## 关键定位:回归一致率,不是准确率
|
|
13
|
+
|
|
14
|
+
弱标注的 `expect_domain` 是**历史路由的输出**,不是真值。2026-11-04 实测:
|
|
15
|
+
31 条「路由输出 != 弱标注期望」的失配里,人工复核 20 条,**19 条是弱标注错、
|
|
16
|
+
路由对**。因此本脚本的 `domain_accuracy` 实际含义是「路由输出与历史输出
|
|
17
|
+
的一致率」,**不是「路由决策的正确率」**。
|
|
18
|
+
|
|
19
|
+
正确率由 `test_route_accuracy_labeled`(13 条人工集)承担。本脚本回答的是
|
|
20
|
+
「路由在真实查询分布上稳不稳、覆没覆盖到」。
|
|
21
|
+
|
|
22
|
+
## 指标
|
|
23
|
+
|
|
24
|
+
| 指标 | 定义 |
|
|
25
|
+
|---|---|
|
|
26
|
+
| `consistency` | 路由输出的 domain == 历史输出的比例(回归一致率) |
|
|
27
|
+
| `family_consistency` | 路由主源的族 == 历史主源族的比例 |
|
|
28
|
+
| `abstain_rate` | 路由落到 `general_search` / `general` 的比例(过度兜底 = 路由没做事) |
|
|
29
|
+
| `stale_labels` | 期望域已不在 config 的条目数(历史遗留噪声,不计入分母) |
|
|
30
|
+
|
|
31
|
+
## 用法
|
|
32
|
+
|
|
33
|
+
python3 scripts/route_accuracy_eval.py # 全量
|
|
34
|
+
python3 scripts/route_accuracy_eval.py --evidence badcase
|
|
35
|
+
python3 scripts/route_accuracy_eval.py --json
|
|
36
|
+
python3 scripts/route_accuracy_eval.py --show-miss 20 # 打印失配样例
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
from __future__ import annotations
|
|
40
|
+
|
|
41
|
+
import argparse
|
|
42
|
+
import json
|
|
43
|
+
import sys
|
|
44
|
+
from collections import Counter, defaultdict
|
|
45
|
+
from pathlib import Path
|
|
46
|
+
from typing import Any
|
|
47
|
+
|
|
48
|
+
ROOT = Path(__file__).resolve().parent.parent
|
|
49
|
+
SCRIPTS = ROOT / "scripts"
|
|
50
|
+
sys.path.insert(0, str(SCRIPTS))
|
|
51
|
+
|
|
52
|
+
LABELS = ROOT / "tests" / "golden" / "route_labeled.jsonl"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _load_labels(evidence: str | None = None) -> list[dict[str, Any]]:
|
|
56
|
+
if not LABELS.is_file():
|
|
57
|
+
return []
|
|
58
|
+
out = []
|
|
59
|
+
for line in LABELS.read_text(encoding="utf-8").splitlines():
|
|
60
|
+
if not line.strip():
|
|
61
|
+
continue
|
|
62
|
+
d = json.loads(line)
|
|
63
|
+
if evidence and d.get("evidence") != evidence:
|
|
64
|
+
continue
|
|
65
|
+
out.append(d)
|
|
66
|
+
return out
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def evaluate(evidence: str | None = None, show_miss: int = 0) -> dict[str, Any]:
|
|
70
|
+
from route import route_query
|
|
71
|
+
from engine_families import family_of
|
|
72
|
+
from config import get_domains
|
|
73
|
+
|
|
74
|
+
labels = _load_labels(evidence)
|
|
75
|
+
if not labels:
|
|
76
|
+
return {"error": "标注集为空"}
|
|
77
|
+
|
|
78
|
+
# 期望域已不在 config 的条目是**历史遗留噪声**(如 general / general_search
|
|
79
|
+
# 两个域已被合并/改名),不是路由错误——单独归类,不计入准确率分母。
|
|
80
|
+
live_domains = {d.get("name") for d in get_domains()}
|
|
81
|
+
|
|
82
|
+
total = 0
|
|
83
|
+
domain_hit = 0
|
|
84
|
+
family_total = 0
|
|
85
|
+
family_hit = 0
|
|
86
|
+
abstain = 0
|
|
87
|
+
stale = 0
|
|
88
|
+
misses: list[dict[str, Any]] = []
|
|
89
|
+
by_domain: dict[str, dict[str, int]] = defaultdict(lambda: {"n": 0, "hit": 0})
|
|
90
|
+
|
|
91
|
+
for e in labels:
|
|
92
|
+
q = e["query"]
|
|
93
|
+
if e.get("expect_domain") not in live_domains:
|
|
94
|
+
stale += 1
|
|
95
|
+
continue
|
|
96
|
+
try:
|
|
97
|
+
r = route_query(q, mode="auto", depth="fast")
|
|
98
|
+
except Exception:
|
|
99
|
+
continue
|
|
100
|
+
total += 1
|
|
101
|
+
got_dom = r.get("domain")
|
|
102
|
+
got_eng = r.get("engine") or ""
|
|
103
|
+
got_fam = family_of(got_eng)
|
|
104
|
+
want_dom = e.get("expect_domain")
|
|
105
|
+
want_fam = e.get("expect_family")
|
|
106
|
+
|
|
107
|
+
hit = got_dom == want_dom
|
|
108
|
+
domain_hit += hit
|
|
109
|
+
by_domain[want_dom]["n"] += 1
|
|
110
|
+
by_domain[want_dom]["hit"] += hit
|
|
111
|
+
|
|
112
|
+
if want_fam:
|
|
113
|
+
family_total += 1
|
|
114
|
+
if got_eng == want_fam or got_fam == want_fam:
|
|
115
|
+
family_hit += 1
|
|
116
|
+
|
|
117
|
+
if got_dom in ("general_search", "general"):
|
|
118
|
+
abstain += 1
|
|
119
|
+
|
|
120
|
+
if not hit and len(misses) < max(show_miss, 200):
|
|
121
|
+
misses.append({
|
|
122
|
+
"query": q, "want": want_dom, "got": got_dom,
|
|
123
|
+
"engine": got_eng, "family": got_fam,
|
|
124
|
+
"evidence": e.get("evidence"),
|
|
125
|
+
"quality": e.get("quality"),
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
result: dict[str, Any] = {
|
|
129
|
+
"total": total,
|
|
130
|
+
"stale_labels": stale,
|
|
131
|
+
"domain_accuracy": round(domain_hit / total, 4) if total else 0.0,
|
|
132
|
+
"family_accuracy": round(family_hit / family_total, 4) if family_total else None,
|
|
133
|
+
"family_total": family_total,
|
|
134
|
+
"abstain_rate": round(abstain / total, 4) if total else 0.0,
|
|
135
|
+
"domain_hit": domain_hit,
|
|
136
|
+
"abstain": abstain,
|
|
137
|
+
"by_domain": {k: {"n": v["n"], "hit": v["hit"],
|
|
138
|
+
"acc": round(v["hit"] / v["n"], 3)}
|
|
139
|
+
for k, v in sorted(by_domain.items(),
|
|
140
|
+
key=lambda kv: -kv[1]["n"])},
|
|
141
|
+
}
|
|
142
|
+
if show_miss:
|
|
143
|
+
result["misses"] = misses[:show_miss]
|
|
144
|
+
return result
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _print_text(r: dict[str, Any]) -> None:
|
|
148
|
+
if r.get("error"):
|
|
149
|
+
print(f"[route_accuracy] {r['error']}")
|
|
150
|
+
return
|
|
151
|
+
print(f"[route_accuracy] 样本 {r['total']} 条"
|
|
152
|
+
+ (f"(另有 {r['stale_labels']} 条期望域已不存在,不计入)"
|
|
153
|
+
if r.get("stale_labels") else ""))
|
|
154
|
+
print(f" domain_accuracy = {r['domain_accuracy']:.1%}"
|
|
155
|
+
f"({r['domain_hit']}/{r['total']})")
|
|
156
|
+
if r["family_accuracy"] is not None:
|
|
157
|
+
print(f" family_accuracy = {r['family_accuracy']:.1%}"
|
|
158
|
+
f"({r['family_total']} 条有期望族)")
|
|
159
|
+
print(f" abstain_rate = {r['abstain_rate']:.1%}"
|
|
160
|
+
f"({r['abstain']} 条落到 general)")
|
|
161
|
+
print(" 域分布(样本数 / 命中 / 准确率):")
|
|
162
|
+
for dom, v in list(r["by_domain"].items())[:15]:
|
|
163
|
+
print(f" {dom:24} {v['n']:4} / {v['hit']:4} / {v['acc']:.1%}")
|
|
164
|
+
if r.get("misses"):
|
|
165
|
+
print(f" 失配样例(前 {len(r['misses'])} 条):")
|
|
166
|
+
for m in r["misses"][:20]:
|
|
167
|
+
print(f" {m['query'][:34]!r:38} want={m['want']:20} "
|
|
168
|
+
f"got={m['got']:20} ev={m['evidence']}")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def main() -> int:
|
|
172
|
+
ap = argparse.ArgumentParser(description="路由准确率评测(离线)")
|
|
173
|
+
ap.add_argument("--evidence", default=None,
|
|
174
|
+
choices=["badcase", "usage_error", "usage_ok"])
|
|
175
|
+
ap.add_argument("--json", action="store_true", dest="json_output")
|
|
176
|
+
ap.add_argument("--show-miss", type=int, default=0)
|
|
177
|
+
args = ap.parse_args()
|
|
178
|
+
|
|
179
|
+
r = evaluate(args.evidence, args.show_miss)
|
|
180
|
+
if args.json_output:
|
|
181
|
+
# 走 cli_io.dumps(紧凑 JSON):CLI stdout 的既有契约,门禁
|
|
182
|
+
# tests/test_context_budget.py::TestStdoutJsonIsCompact 会拦缩进输出。
|
|
183
|
+
from cli_io import dumps
|
|
184
|
+
print(dumps(r))
|
|
185
|
+
else:
|
|
186
|
+
_print_text(r)
|
|
187
|
+
return 0
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
if __name__ == "__main__":
|
|
191
|
+
raise SystemExit(main())
|
package/scripts/route_combo.py
CHANGED
|
@@ -168,6 +168,28 @@ def _hard_down_blocked(engine_id: str) -> bool:
|
|
|
168
168
|
return False
|
|
169
169
|
|
|
170
170
|
|
|
171
|
+
def _dep_ready(engine_id: str, specs: dict | None = None) -> bool:
|
|
172
|
+
"""引擎声明的外部依赖(CLI 工具等)是否就绪。
|
|
173
|
+
|
|
174
|
+
路由准入此前不查依赖,只查 enabled/熔断/配额/死源/语言,而执行层
|
|
175
|
+
另有一套(engine_status 的 dep_ready)。两套判据的后果是 primary
|
|
176
|
+
可以是一个「路由认为可用、执行必然失败」的引擎:实测本机
|
|
177
|
+
xiaohongshu 缺 xhs CLI,路由仍把它放首位,结果由 fallback 悄悄
|
|
178
|
+
接管,reason 却写着「→ 小红书」。让路由与执行共用同一个依赖判据。
|
|
179
|
+
"""
|
|
180
|
+
spec = (specs or {}).get(engine_id)
|
|
181
|
+
if not isinstance(spec, dict):
|
|
182
|
+
return True
|
|
183
|
+
requires = spec.get("requires")
|
|
184
|
+
if not requires:
|
|
185
|
+
return True
|
|
186
|
+
try:
|
|
187
|
+
from engine_requires import requires_status
|
|
188
|
+
return bool(requires_status(spec).get("dep_ready", True))
|
|
189
|
+
except Exception:
|
|
190
|
+
return True
|
|
191
|
+
|
|
192
|
+
|
|
171
193
|
def is_engine_routable(
|
|
172
194
|
engine_id: str,
|
|
173
195
|
*,
|
|
@@ -175,12 +197,15 @@ def is_engine_routable(
|
|
|
175
197
|
check_breaker: bool = True,
|
|
176
198
|
check_hard_down: bool = True,
|
|
177
199
|
check_dead: bool = False,
|
|
200
|
+
check_deps: bool = True,
|
|
178
201
|
lang: str = "",
|
|
179
202
|
specs: dict | None = None,
|
|
180
203
|
) -> bool:
|
|
181
|
-
"""单一引擎路由准入谓词:统一收口 enabled / 熔断 / 配额硬耗尽 /
|
|
204
|
+
"""单一引擎路由准入谓词:统一收口 enabled / 依赖 / 熔断 / 配额硬耗尽 / 死源 / 语言可达。"""
|
|
182
205
|
if enabled is not None and engine_id not in enabled:
|
|
183
206
|
return False
|
|
207
|
+
if check_deps and not _dep_ready(engine_id, specs):
|
|
208
|
+
return False
|
|
184
209
|
if lang and not lang_allows(engine_id, lang, (specs or {}).get(engine_id)):
|
|
185
210
|
return False
|
|
186
211
|
if check_dead and engine_is_dead(engine_id):
|
|
@@ -288,6 +313,7 @@ def select_tfidf_best(query: str,
|
|
|
288
313
|
semantic_route,
|
|
289
314
|
min_score: float = 0.12,
|
|
290
315
|
enabled: set[str] | None = None,
|
|
316
|
+
vetoed: set[str] | None = None,
|
|
291
317
|
) -> tuple[str | None, float, list]:
|
|
292
318
|
"""TF-IDF 语义路由选源:返回 (最佳引擎, 分数, 候选表)。
|
|
293
319
|
|
|
@@ -303,6 +329,9 @@ def select_tfidf_best(query: str,
|
|
|
303
329
|
顶到首位——实测 thesportsdb 0.084 仍是「NBA
|
|
304
330
|
总决赛」类查询的第一候选,注入后撤销 GEC 地板
|
|
305
331
|
过滤并占 wave-1 竞速首位,白等它的单引擎超时。
|
|
332
|
+
⑤ 域规则否决(vetoed):域已用 unless 否决过该引擎所属域时,词面分
|
|
333
|
+
不得复活它——实测「怎么写论文 查重 降重」域判 chinese_general,
|
|
334
|
+
TF-IDF 仍按「论文」高分把 cnii(日文学术)注入首位。
|
|
306
335
|
|
|
307
336
|
semantic_route 由调用方传入:route.py 经模块属性
|
|
308
337
|
访问解析(测试打桩 patch("route.semantic_route")
|
|
@@ -343,6 +372,8 @@ def select_tfidf_best(query: str,
|
|
|
343
372
|
if near_miss is None:
|
|
344
373
|
near_miss = (cand, score)
|
|
345
374
|
continue
|
|
375
|
+
if vetoed and cand in vetoed:
|
|
376
|
+
continue
|
|
346
377
|
tfidf_best = cand
|
|
347
378
|
tfidf_best_score = score
|
|
348
379
|
break
|
package/scripts/route_domains.py
CHANGED
|
@@ -169,8 +169,12 @@ def _get_candidate_domain_indices(query: str) -> set[int] | None:
|
|
|
169
169
|
return candidates
|
|
170
170
|
|
|
171
171
|
|
|
172
|
-
def _ensure_domain_compiled(domain: dict[str, Any]) -> list[tuple[
|
|
173
|
-
"""按需编译单个域的触发词与意图正则(扫到哪个域才编译哪个域)。
|
|
172
|
+
def _ensure_domain_compiled(domain: dict[str, Any]) -> list[tuple[Any, Any]]:
|
|
173
|
+
"""按需编译单个域的触发词与意图正则(扫到哪个域才编译哪个域)。
|
|
174
|
+
|
|
175
|
+
返回的 matcher 是鸭子类型:`re.Pattern` 或 `_LiteralMatcher`,两者都提供
|
|
176
|
+
`.search(query)`(前者返回 `re.Match`,后者返回 `_LiteralMatch`,均带 `.span()`)。
|
|
177
|
+
"""
|
|
174
178
|
rules = domain.get("_rules")
|
|
175
179
|
if rules is not None:
|
|
176
180
|
return rules
|
|
@@ -204,9 +208,124 @@ def _compile_domain_patterns(domains: list[dict[str, Any]]) -> list[dict[str, An
|
|
|
204
208
|
return compiled
|
|
205
209
|
|
|
206
210
|
|
|
207
|
-
|
|
211
|
+
# 纯字面 alternation 判定:只认「剥掉开头 (?i) 与最外层括号后,由 | 分隔、
|
|
212
|
+
# 每段都是纯字面字符」的 pattern。字符类里出现正则元字符(. * + ? ^ $ \ [ ] ( ) |)
|
|
213
|
+
# 或内联结构一律不认——判定必须保守,判不准就交回 re.compile,宁可少优化。
|
|
214
|
+
_LITERAL_CHAR = re.compile(r"^[\w\u4e00-\u9fff \-/#&:,.'’]+\Z", re.UNICODE)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _literal_alternatives(src: str) -> tuple[list[str], bool] | None:
|
|
218
|
+
"""判定 pattern 是否为纯字面 alternation;是则返回 (词表, 是否忽略大小写)。
|
|
219
|
+
|
|
220
|
+
等价性:`(?i)(a|b)` 的 `re.search` 与「query 含 a 或 b(忽略大小写)」等价;
|
|
221
|
+
无 `(?i)` 时与「query 含 a 或 b(区分大小写)」等价。含非 ASCII 拉丁字母
|
|
222
|
+
(é/ß 等)时 `(?i)` 与 `str.lower()` 的 Unicode 规则不完全一致,故退回。
|
|
223
|
+
"""
|
|
224
|
+
if not src:
|
|
225
|
+
return None
|
|
226
|
+
s = src
|
|
227
|
+
ignore_case = False
|
|
228
|
+
if s.startswith("(?i)"):
|
|
229
|
+
s = s[4:]
|
|
230
|
+
ignore_case = True
|
|
231
|
+
# `(?i)` 只作用于其后的表达式。若顶层还有 `|` 且不是「整体被一对括号
|
|
232
|
+
# 包裹」,flag 作用域只覆盖第一个分支(如 `(?i)foo|bar` 的 bar 区分
|
|
233
|
+
# 大小写),此时按整体忽略大小写处理会误判 → 退回 re.compile。
|
|
234
|
+
wrapped = (s.startswith("(") and s.endswith(")")
|
|
235
|
+
and s.count("(") == 1 and s.count(")") == 1)
|
|
236
|
+
if not wrapped:
|
|
237
|
+
depth = 0
|
|
238
|
+
for ch in s:
|
|
239
|
+
if ch == "(":
|
|
240
|
+
depth += 1
|
|
241
|
+
elif ch == ")":
|
|
242
|
+
depth -= 1
|
|
243
|
+
elif ch == "|" and depth == 0:
|
|
244
|
+
return None
|
|
245
|
+
# 只剥「整体被一对括号包裹」的情形(顶层无其他内容)
|
|
246
|
+
if s.startswith("(") and s.endswith(")") and s.count("(") == 1 and s.count(")") == 1:
|
|
247
|
+
s = s[1:-1]
|
|
248
|
+
parts: list[str] = []
|
|
249
|
+
depth = 0
|
|
250
|
+
cur: list[str] = []
|
|
251
|
+
for ch in s:
|
|
252
|
+
if ch == "(":
|
|
253
|
+
depth += 1
|
|
254
|
+
elif ch == ")":
|
|
255
|
+
depth -= 1
|
|
256
|
+
if ch == "|" and depth == 0:
|
|
257
|
+
parts.append("".join(cur))
|
|
258
|
+
cur = []
|
|
259
|
+
else:
|
|
260
|
+
cur.append(ch)
|
|
261
|
+
parts.append("".join(cur))
|
|
262
|
+
if not parts:
|
|
263
|
+
return None
|
|
264
|
+
words: list[str] = []
|
|
265
|
+
for p in parts:
|
|
266
|
+
if not p or not _LITERAL_CHAR.match(p):
|
|
267
|
+
return None
|
|
268
|
+
if ignore_case:
|
|
269
|
+
if any(ord(c) > 127 and not ("\u4e00" <= c <= "\u9fff") for c in p):
|
|
270
|
+
return None
|
|
271
|
+
p = p.lower()
|
|
272
|
+
words.append(p)
|
|
273
|
+
return words, ignore_case
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
class _LiteralMatch:
|
|
277
|
+
"""`_LiteralMatcher.search` 的返回值:只提供调用方用到的 `.span()`。"""
|
|
278
|
+
|
|
279
|
+
__slots__ = ("_span",)
|
|
280
|
+
|
|
281
|
+
def __init__(self, span: tuple[int, int]):
|
|
282
|
+
self._span = span
|
|
283
|
+
|
|
284
|
+
def span(self) -> tuple[int, int]:
|
|
285
|
+
return self._span
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
class _LiteralMatcher:
|
|
289
|
+
"""纯字面 alternation 的匹配器:子串查找替代 `re.compile` + `re.search`。
|
|
290
|
+
|
|
291
|
+
为什么值得(2026-11-04 实测):域规则 326 条 pattern 里 134 条是纯字面
|
|
292
|
+
alternation(如 `(?i)(金十|jin10)`、`(?i)(技术社区|程序员社区)`),它们每次
|
|
293
|
+
冷进程都要付一次 `re.compile`(326 条全量实测 23.8 ms),而子串查找零编译、
|
|
294
|
+
更快。判定由 `_literal_alternatives` 保守把关,判不准的一律走原正则路径。
|
|
295
|
+
"""
|
|
296
|
+
|
|
297
|
+
__slots__ = ("_words", "_ignore_case")
|
|
298
|
+
|
|
299
|
+
def __init__(self, words: list[str], ignore_case: bool):
|
|
300
|
+
self._words = words
|
|
301
|
+
self._ignore_case = ignore_case
|
|
302
|
+
|
|
303
|
+
def search(self, query: str) -> _LiteralMatch | None:
|
|
304
|
+
hay = query.lower() if self._ignore_case else query
|
|
305
|
+
best: tuple[int, int] | None = None
|
|
306
|
+
for w in self._words:
|
|
307
|
+
pos = hay.find(w)
|
|
308
|
+
if pos < 0:
|
|
309
|
+
continue
|
|
310
|
+
# 与 re 的 leftmost 语义一致:取最早出现;同位置取分支顺序在前者
|
|
311
|
+
if best is None or pos < best[0]:
|
|
312
|
+
best = (pos, pos + len(w))
|
|
313
|
+
return _LiteralMatch(best) if best is not None else None
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _try_compile(src: Any) -> Any:
|
|
317
|
+
"""编译域规则:纯字面 alternation 走子串匹配,其余走 `re.compile`。
|
|
318
|
+
|
|
319
|
+
返回值是鸭子类型(均提供 `.search(query)`,返回值带 `.span()`):
|
|
320
|
+
`_LiteralMatcher` 或 `re.Pattern`。写坏的正则仍返回 None 被丢弃,
|
|
321
|
+
「编译失败静默丢弃」的既有语义不变(纯字面判定本身保证每段都是字面
|
|
322
|
+
字符,不可能写坏)。
|
|
323
|
+
"""
|
|
208
324
|
if not isinstance(src, str) or not src:
|
|
209
325
|
return None
|
|
326
|
+
literal = _literal_alternatives(src)
|
|
327
|
+
if literal is not None:
|
|
328
|
+
return _LiteralMatcher(*literal)
|
|
210
329
|
try:
|
|
211
330
|
return re.compile(src)
|
|
212
331
|
except re.error:
|
|
@@ -230,14 +349,76 @@ _UNLESS_MACROS: dict[str, str] = {
|
|
|
230
349
|
r"价格|多少钱|商业化|市场预测|行情|股价|龙头股|概念股|"
|
|
231
350
|
r"market\s+size|market\s+share|sales|revenue|valuation|market\s+forecast|pricing)"
|
|
232
351
|
),
|
|
352
|
+
# 比较决策/获奖新闻否决集(2026-10-31 评测基线):「…是什么」尾部触发词在
|
|
353
|
+
# cn_encyclopedia 与 fact_check 两处各自存在,把比较题(「A 和 B 的区别/
|
|
354
|
+
# 优劣/怎么选」)与得主类新闻题整类锁进点查域。共用一份否决词,新增守卫域
|
|
355
|
+
# 时在 config.yaml 引用 @compare_or_award,不要复制粘贴展开后的正则。
|
|
356
|
+
"@compare_or_award": (
|
|
357
|
+
r"(?i)(区别|比较|对比|怎么选|哪个好|优劣|利弊|差异|权衡|\bvs\b|得主|获奖)"
|
|
358
|
+
),
|
|
359
|
+
# 本地/免 key 镜像通道否决集(2026-11-04):`local_*` 六个域是用户**显式
|
|
360
|
+
# 选择**本地化通道的意图(`references/usage.md`:「local_ 前缀是本地化/免 key
|
|
361
|
+
# 镜像通道」),但它们在 config 里排在末尾(idx 92-97),而域匹配先到先得——
|
|
362
|
+
# 于是「本地搜索」「arxiv api」「wikipedia api」「bing news」「百度」全部被
|
|
363
|
+
# 靠前的 catch-all / academic / code_search / news_realtime 截走,那六个域
|
|
364
|
+
# 永远拿不到主位(实测 6/6 失配)。
|
|
365
|
+
#
|
|
366
|
+
# 修法:加 `_channel_intent_gate`(见文件下方),查询含本宏意图词时把
|
|
367
|
+
# local_* 域提到首位。词表与 local_* 六域的 patterns 对齐。
|
|
368
|
+
#
|
|
369
|
+
# **词表只收「带通道语义的写法」,不收裸平台名**:`github repo`、
|
|
370
|
+
# `stackoverflow`、`npm package` 既是通道意图也是普通技术词,收进来会误伤
|
|
371
|
+
# 「github repo 教程 推荐」(实测被误判 local_code)。裸平台名交给各域
|
|
372
|
+
# 自己的 patterns 处理,通道门只认明确的通道修饰语——即「平台名 + 本地/
|
|
373
|
+
# 镜像/免 key」的组合,或「本地 + 平台名」的组合。
|
|
374
|
+
"@local_channel": (
|
|
375
|
+
r"(?i)(本地搜索|local search|零成本|free search|本地新闻|本地中文|"
|
|
376
|
+
r"本地代码|本地学术|本地参考|本地通用|"
|
|
377
|
+
r"arxiv api|semantic scholar|crossref|pubmed|site:arxiv\.org|"
|
|
378
|
+
r"wikipedia api|wiktionary|wikiquote|nominatim|openstreetmap|"
|
|
379
|
+
r"site:baidu|site:sogou|"
|
|
380
|
+
r"(?:github|gitlab|stackoverflow|npm|pip|cargo)\s+(?:repo|package)(?:\s+(?:本地|镜像|免\s?key|local|mirror))|"
|
|
381
|
+
r"(?:本地|镜像)\s+(?:github|gitlab|stackoverflow|npm|pip|cargo))"
|
|
382
|
+
),
|
|
233
383
|
}
|
|
234
384
|
|
|
235
385
|
|
|
236
386
|
def _split_pattern_entry(entry: Any) -> tuple[Any, Any]:
|
|
237
|
-
"""触发词条目的两种形态:字符串,或 `{match, unless}`(unless 支持 @宏名 展开)。
|
|
387
|
+
"""触发词条目的两种形态:字符串,或 `{match, unless}`(unless 支持 @宏名 展开)。
|
|
388
|
+
|
|
389
|
+
`unless` 可以是:
|
|
390
|
+
|
|
391
|
+
- 字符串正则(原样编译);
|
|
392
|
+
- `@宏名`(整体替换成宏的正则);
|
|
393
|
+
- **列表**:每项是字符串正则或 `@宏名`,展开后用 `|` 拼接成一个正则。
|
|
394
|
+
|
|
395
|
+
列表形态是 2026-11-04 为「一个触发词要挂多个否决集」加的:academic 的
|
|
396
|
+
论文条目原有写作技巧否决,又要加本地通道否决,两个都要生效——拼接成
|
|
397
|
+
一个字符串会让 `(?i)` 的作用域只覆盖前半段(实测宏不展开),而整体
|
|
398
|
+
替换成宏名又会丢掉原有否决。列表让两类否决各占一项、语义清晰。
|
|
399
|
+
"""
|
|
238
400
|
if isinstance(entry, dict):
|
|
239
401
|
unless = entry.get("unless")
|
|
240
|
-
if isinstance(unless,
|
|
402
|
+
if isinstance(unless, list):
|
|
403
|
+
parts: list[str] = []
|
|
404
|
+
for item in unless:
|
|
405
|
+
if isinstance(item, str) and item in _UNLESS_MACROS:
|
|
406
|
+
parts.append(_UNLESS_MACROS[item])
|
|
407
|
+
elif isinstance(item, str) and item:
|
|
408
|
+
parts.append(item)
|
|
409
|
+
# 拼接前剥掉后续项开头的 `(?i)`:Python 3.11+ 不允许内联 flag
|
|
410
|
+
# 出现在非开头位置(`(?i)a|(?i)b` 编译失败),而宏与正则都自带
|
|
411
|
+
# `(?i)`,剥掉后语义不变(整条仍由第一个 `(?i)` 控制)。
|
|
412
|
+
if parts:
|
|
413
|
+
merged = parts[0]
|
|
414
|
+
for p in parts[1:]:
|
|
415
|
+
if p.startswith("(?i)"):
|
|
416
|
+
p = p[4:]
|
|
417
|
+
merged += "|" + p
|
|
418
|
+
unless = merged
|
|
419
|
+
else:
|
|
420
|
+
unless = None
|
|
421
|
+
elif isinstance(unless, str) and unless in _UNLESS_MACROS:
|
|
241
422
|
unless = _UNLESS_MACROS[unless]
|
|
242
423
|
return entry.get("match"), unless
|
|
243
424
|
return entry, None
|
|
@@ -415,6 +596,59 @@ def _intent_gate(hits: list[dict[str, Any]], query: str) -> list[dict[str, Any]]
|
|
|
415
596
|
return kept
|
|
416
597
|
|
|
417
598
|
|
|
599
|
+
# ── 阶段 4:显式通道意图门(2026-11-04)──────────────────────────────────────
|
|
600
|
+
#
|
|
601
|
+
# 与 `_intent_gate` 对称但方向相反:那个是「点查域在主题句下让位」,这个是
|
|
602
|
+
# 「泛化域在显式通道意图下让位」。
|
|
603
|
+
#
|
|
604
|
+
# 为什么需要:`local_*` 六个域是用户**显式选择**本地化/免 key 通道的意图
|
|
605
|
+
# (`references/usage.md`:「local_ 前缀是本地化/免 key 镜像通道」),但它们在
|
|
606
|
+
# config 里排在末尾(idx 92-97),而域匹配先到先得——「本地搜索」「arxiv api」
|
|
607
|
+
# 「wikipedia api」「github repo」「bing news」「百度」全部被靠前的泛化域截走,
|
|
608
|
+
# 那六个域永远拿不到主位(实测 6/6 失配)。
|
|
609
|
+
#
|
|
610
|
+
# 为什么不在每个泛化域上加 unless:那是打地鼠——code_search 有四条 pattern
|
|
611
|
+
# 命中同一个查询,逐个加否决总会漏(实测加到第三条仍失配)。而且新增泛化域
|
|
612
|
+
# 时又会漏。门放在匹配层,一次覆盖所有泛化域。
|
|
613
|
+
#
|
|
614
|
+
# 判据:查询含 `@local_channel` 宏的意图词,且命中列表里有 `local_*` 域时,
|
|
615
|
+
# 把非 local_ 的命中域降级为次域(保留在列表里,不删除——它们仍可能补位)。
|
|
616
|
+
|
|
617
|
+
_CHANNEL_INTENT_RE: re.Pattern | None = None
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def _channel_intent_re() -> re.Pattern | None:
|
|
621
|
+
"""惰性编译通道意图正则(复用 @local_channel 宏,避免词表两处维护)。"""
|
|
622
|
+
global _CHANNEL_INTENT_RE
|
|
623
|
+
if _CHANNEL_INTENT_RE is None:
|
|
624
|
+
src = _UNLESS_MACROS.get("@local_channel")
|
|
625
|
+
if not src:
|
|
626
|
+
return None
|
|
627
|
+
try:
|
|
628
|
+
_CHANNEL_INTENT_RE = re.compile(src, re.I)
|
|
629
|
+
except re.error:
|
|
630
|
+
return None
|
|
631
|
+
return _CHANNEL_INTENT_RE
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def _channel_intent_gate(hits: list[dict[str, Any]], query: str) -> list[dict[str, Any]]:
|
|
635
|
+
"""显式通道意图存在时,把 local_* 域提到首位(泛化域降为次域)。
|
|
636
|
+
|
|
637
|
+
不删除泛化域——它们仍可能在 local 通道不可用时补位(fallback 语义)。
|
|
638
|
+
只调整顺序:主域是 local_*,泛化域退到次域位置。
|
|
639
|
+
"""
|
|
640
|
+
if not hits:
|
|
641
|
+
return hits
|
|
642
|
+
re_ = _channel_intent_re()
|
|
643
|
+
if re_ is None or re_.search(query) is None:
|
|
644
|
+
return hits
|
|
645
|
+
local_hits = [h for h in hits if str(h.get("name", "")).startswith("local_")]
|
|
646
|
+
if not local_hits:
|
|
647
|
+
return hits # 没有 local 域命中:不调整(说明 local 域规则没覆盖)
|
|
648
|
+
others = [h for h in hits if not str(h.get("name", "")).startswith("local_")]
|
|
649
|
+
return local_hits + others
|
|
650
|
+
|
|
651
|
+
|
|
418
652
|
# ── 对外入口 ──────────────────────────────────────────────────────────────────
|
|
419
653
|
|
|
420
654
|
def match_domains(query: str, domains: list[dict[str, Any]] | None = None,
|
|
@@ -469,6 +703,9 @@ def match_domains(query: str, domains: list[dict[str, Any]] | None = None,
|
|
|
469
703
|
|
|
470
704
|
hits = _social_domain_first(hits)
|
|
471
705
|
hits = _intent_gate(hits, query)
|
|
706
|
+
# 显式通道意图门放在最后:它只重排已命中列表(local_* 提前),不改变
|
|
707
|
+
# 「哪些域命中」这个事实,因此不影响前面的意图门与社交提前逻辑。
|
|
708
|
+
hits = _channel_intent_gate(hits, query)
|
|
472
709
|
hits = hits[:max_n]
|
|
473
710
|
return hits if hits else ([catch_all] if catch_all else [])
|
|
474
711
|
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""route_primary.py — primary 可执行性顺位与域否决查询。
|
|
3
|
+
|
|
4
|
+
## 为什么单独成模块
|
|
5
|
+
|
|
6
|
+
`route.py` 已压着 1000 行硬限,而这两件事都是**独立的判定**,与路由主干的
|
|
7
|
+
装配流程无关:
|
|
8
|
+
|
|
9
|
+
1. `promote_executable_primary`:combo 定稿后把 primary 顺位到第一个
|
|
10
|
+
「路由与执行都判可用」的引擎;
|
|
11
|
+
2. `domain_vetoed_engines` / `vetoes_apply`:把域规则的 `unless` 否决
|
|
12
|
+
事实交给 TF-IDF 注入层。
|
|
13
|
+
|
|
14
|
+
放在这里,route.py 只留两个调用点。
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from config import get_engines
|
|
22
|
+
from route_combo import is_engine_routable
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def promote_executable_primary(combo: list[str], specs: dict | None = None,
|
|
26
|
+
enabled: set[str] | None = None
|
|
27
|
+
) -> tuple[list[str], str | None]:
|
|
28
|
+
"""把 primary 顺位到第一个「路由与执行都判可用」的引擎。
|
|
29
|
+
|
|
30
|
+
路由准入与执行准入此前不是同一套判据:`is_engine_routable` 查
|
|
31
|
+
enabled/依赖/熔断/配额/死源/语言,而执行层的 `engine_status` 另算
|
|
32
|
+
dep_ready——两者在 2026-11-02 才对齐。即便对齐后仍有一个缺口:
|
|
33
|
+
`is_engine_routable` 默认 check_deps=True,但域装配早期
|
|
34
|
+
(_get_engines_combo 与 policy 截断)不看依赖,于是 xiaohongshu 这类缺
|
|
35
|
+
CLI 的引擎能一路占住首位,实际交付由 fallback 接管,reason 却写着
|
|
36
|
+
「→ 小红书」。
|
|
37
|
+
|
|
38
|
+
顺位不改写 combo 内容,只把「执行不了」的成员换到后面;全组都不可执行
|
|
39
|
+
时保持原序(fail-open,由执行层报错而不是路由层静默换源)。
|
|
40
|
+
"""
|
|
41
|
+
if not combo:
|
|
42
|
+
return combo, None
|
|
43
|
+
# 必须自己取 specs:route 的 _specs_snapshot() 只读已加载的 engines 模块,
|
|
44
|
+
# 路由路径下它恒为空表,依赖判据会因此对全部引擎失效。
|
|
45
|
+
if specs is None:
|
|
46
|
+
try:
|
|
47
|
+
specs = get_engines()
|
|
48
|
+
except Exception:
|
|
49
|
+
specs = {}
|
|
50
|
+
if is_engine_routable(combo[0], enabled=enabled, specs=specs):
|
|
51
|
+
return combo, None
|
|
52
|
+
for cand in combo[1:]:
|
|
53
|
+
if is_engine_routable(cand, enabled=enabled, specs=specs):
|
|
54
|
+
rest = [e for e in combo if e != cand]
|
|
55
|
+
return [cand] + rest, combo[0]
|
|
56
|
+
return combo, None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def domain_vetoed_engines(query: str,
|
|
60
|
+
domains: list[dict[str, Any]] | None = None) -> set[str]:
|
|
61
|
+
"""被域规则显式否决的引擎集合(供 TF-IDF 注入层不再复活)。
|
|
62
|
+
|
|
63
|
+
域规则与 TF-IDF 选源此前是两条互不知情的路径:域规则用 `unless` 否决了
|
|
64
|
+
某个意图(例如 academic 的「查重/降重」写作语境),TF-IDF 却可以按词面
|
|
65
|
+
高分把该域的主源重新注入首位——实测「怎么写论文 查重 降重」域判到
|
|
66
|
+
chinese_general、reason 仍写「[TF-IDF→cnii]」,primary 变成日文学术源。
|
|
67
|
+
把「否决」这个事实交给注入层,让词面分不能覆盖域规则的语义判断。
|
|
68
|
+
|
|
69
|
+
判据:某域**本可命中**(match 成立)但因 unless 被否决时,该域声明的
|
|
70
|
+
引擎即视为被否决。与 match_domains 共用 `_ensure_domain_compiled`。
|
|
71
|
+
"""
|
|
72
|
+
if domains is None:
|
|
73
|
+
from route_domains import get_domains as _gd, _get_compiled_domains, \
|
|
74
|
+
_ensure_domain_compiled
|
|
75
|
+
domains = _gd()
|
|
76
|
+
else:
|
|
77
|
+
from route_domains import _get_compiled_domains, _ensure_domain_compiled
|
|
78
|
+
compiled = _get_compiled_domains(domains)
|
|
79
|
+
vetoed: set[str] = set()
|
|
80
|
+
for domain in compiled:
|
|
81
|
+
for match_re, unless_re in _ensure_domain_compiled(domain):
|
|
82
|
+
if unless_re is not None and unless_re.search(query):
|
|
83
|
+
if match_re.search(query):
|
|
84
|
+
vetoed.update(domain.get("engines_combo") or [])
|
|
85
|
+
vetoed.update([domain["primary"]] if domain.get("primary") else [])
|
|
86
|
+
break
|
|
87
|
+
return vetoed
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def vetoes_apply(query: str, domains: list[dict[str, Any]] | None = None,
|
|
91
|
+
hard_domain: bool = False) -> bool:
|
|
92
|
+
"""本次路由是否处在「域规则已否决」状态。
|
|
93
|
+
|
|
94
|
+
只有**没有实域命中**时才让否决生效:零实域命中说明所有域要么未匹配、
|
|
95
|
+
要么被 unless 否决,此时 TF-IDF 注入是唯一能改变主源的力量,必须受
|
|
96
|
+
域规则约束。一旦已有实域命中,该域自身的引擎选择是声明式的,注入只作
|
|
97
|
+
辅源,不否决。
|
|
98
|
+
"""
|
|
99
|
+
if hard_domain:
|
|
100
|
+
return False
|
|
101
|
+
return bool(domain_vetoed_engines(query, domains))
|
package/scripts/search.py
CHANGED
|
@@ -641,6 +641,7 @@ def super_search(query: str, engine: str = "auto", n: int = 5, explain: bool = F
|
|
|
641
641
|
engine=engine if not local_first else "local_search",
|
|
642
642
|
input_kind=input_kind,
|
|
643
643
|
context=context,
|
|
644
|
+
timing=timing,
|
|
644
645
|
)
|
|
645
646
|
if kind == "known-url" and not force_search:
|
|
646
647
|
plan_info = build_plan(
|