argo-search 2.14.1 → 2.16.0
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/AGENTS.md +8 -6
- package/README.es.md +57 -813
- package/README.ja.md +56 -814
- package/README.ko.md +56 -812
- package/README.md +160 -754
- package/README.zh.md +152 -872
- package/SKILL.md +22 -23
- package/assets/readme/counts.json +1 -1
- package/assets/readme/hero.svg +23 -23
- package/backends/concept_vectors.bin +0 -0
- package/backends/domain_profiles.json +149 -6
- package/backends/engine_concept_vectors.json +1525 -1525
- package/backends/engine_registry.yaml +139 -30
- package/backends/quota_profiles.json +83 -3
- package/bin/argo +33 -17
- package/config.yaml +189 -33
- package/docs/ADDING_NEW_ENGINE.md +10 -0
- package/docs/ARGO_INTRO.md +1 -1
- package/docs/CHANGELOG.md +38 -0
- package/docs/ENGINE_CATALOG.md +102 -89
- package/docs/MCP_SETUP.md +10 -1
- package/docs/RELEASE_NOTES_v2.14.1.md +4 -4
- package/docs/RELEASE_NOTES_v2.15.0.md +50 -0
- package/docs/RELEASE_NOTES_v2.16.0.md +58 -0
- package/docs/RELEASING.md +1 -1
- package/engines/specs/ai_labs.yaml +89 -0
- package/engines/specs/archive_org.yaml +1 -1
- package/engines/specs/bilibili_hot.yaml +11 -1
- package/engines/specs/brave.yaml +3 -3
- package/engines/specs/carbon_intensity.yaml +1 -1
- package/engines/specs/cisa_alerts.yaml +40 -0
- package/engines/specs/cn_ai_news.yaml +10 -8
- package/engines/specs/crates.yaml +1 -1
- package/engines/specs/crossref.yaml +4 -2
- package/engines/specs/crt_sh.yaml +1 -1
- package/engines/specs/dblp.yaml +1 -1
- package/engines/specs/devto.yaml +1 -1
- package/engines/specs/digup.yaml +11 -6
- package/engines/specs/docker_hub.yaml +1 -1
- package/engines/specs/douyin_hot.yaml +11 -1
- package/engines/specs/dw_news.yaml +4 -2
- package/engines/specs/eng_blogs.yaml +63 -0
- package/engines/specs/europeana.yaml +3 -4
- package/engines/specs/europepmc.yaml +1 -1
- package/engines/specs/felo.yaml +3 -3
- package/engines/specs/firecrawl.yaml +3 -0
- package/engines/specs/fourget.yaml +5 -2
- package/engines/specs/france24.yaml +6 -4
- package/engines/specs/fxtwitter.yaml +30 -7
- package/engines/specs/gbfs_nyc.yaml +1 -1
- package/engines/specs/gleif.yaml +1 -1
- package/engines/specs/gov_regulations.yaml +1 -1
- package/engines/specs/grepapp_mcp.yaml +62 -0
- package/engines/specs/guardian_rss.yaml +6 -4
- package/engines/specs/hf_datasets.yaml +1 -1
- package/engines/specs/huggingface.yaml +1 -1
- package/engines/specs/itotii.yaml +13 -1
- package/engines/specs/keenable.yaml +7 -1
- package/engines/specs/linux_do.yaml +63 -0
- package/engines/specs/lobsters.yaml +41 -0
- package/engines/specs/local_crossref.yaml +3 -1
- package/engines/specs/local_github.yaml +1 -1
- package/engines/specs/local_npm.yaml +6 -0
- package/engines/specs/local_openstreetmap.yaml +1 -1
- package/engines/specs/local_seek.yaml +6 -0
- package/engines/specs/maven.yaml +1 -1
- package/engines/specs/mdn.yaml +1 -1
- package/engines/specs/musicbrainz.yaml +1 -1
- package/engines/specs/nasa_images.yaml +1 -1
- package/engines/specs/nhtsa_vpic.yaml +6 -3
- package/engines/specs/npm.yaml +1 -1
- package/engines/specs/nuget.yaml +1 -1
- package/engines/specs/nvd.yaml +1 -1
- package/engines/specs/open_meteo.yaml +1 -1
- package/engines/specs/openalex.yaml +4 -2
- package/engines/specs/openreview.yaml +1 -1
- package/engines/specs/polymarket.yaml +1 -1
- package/engines/specs/redskill.yaml +2 -0
- package/engines/specs/searxng.yaml +4 -2
- package/engines/specs/sec_edgar.yaml +9 -4
- package/engines/specs/steam.yaml +1 -1
- package/engines/specs/tinyfish.yaml +2 -0
- package/engines/specs/tinyfish_news.yaml +2 -0
- package/engines/specs/tinyfish_paper.yaml +2 -0
- package/engines/specs/toutiao_hot.yaml +11 -1
- package/engines/specs/train.yaml +3 -0
- package/engines/specs/twitter.yaml +4 -0
- package/engines/specs/unpaywall.yaml +6 -0
- package/engines/specs/vam.yaml +17 -3
- package/engines/specs/weibo_hot.yaml +11 -1
- package/engines/specs/wikidata.yaml +1 -1
- package/engines/specs/wikipedia.yaml +1 -1
- package/engines/specs/wolframalpha.yaml +3 -3
- package/engines/specs/xiaohongshu.yaml +2 -0
- package/engines/specs/zhihu.yaml +3 -18
- package/engines/specs/zhihu_hot_app.yaml +1 -1
- package/engines/specs/zhihu_kb.yaml +18 -0
- package/engines/specs/zhihu_questions.yaml +19 -0
- package/package.json +4 -2
- package/packages/dsh-plugin/README.md +9 -14
- package/packages/dsh-plugin/dsh/client.js +481 -1037
- package/packages/dsh-plugin/dsh/diagnostics.js +71 -20
- package/packages/dsh-plugin/dsh/index.js +6 -0
- package/packages/dsh-plugin/dsh/runner.js +3 -1
- package/packages/dsh-plugin/dsh/workbench-client.js +796 -0
- package/packages/dsh-plugin/dsh/workbench-md.js +386 -0
- package/packages/dsh-plugin/dsh/workbench-suggestions.js +148 -0
- package/packages/dsh-plugin/dsh/workbench.js +966 -0
- package/packages/dsh-plugin/icon.svg +23 -0
- package/packages/dsh-plugin/package.json +10 -3
- package/packages/dsh-plugin/scripts/sync-local.mjs +87 -0
- package/packages/dsh-plugin/scripts/sync-local.sh +13 -1
- package/packages/dsh-plugin/test/diagnostics.test.js +38 -1
- package/packages/dsh-plugin/test/size-gate.test.js +2 -9
- package/packages/dsh-plugin/test/workbench.test.js +92 -0
- package/scripts/adaptive.py +7 -1
- package/scripts/archive_run.py +112 -53
- package/scripts/argo_paths.py +42 -5
- package/scripts/badcase_ledger.py +117 -9
- package/scripts/build_concept_table.py +112 -55
- package/scripts/cache.py +6 -2
- package/scripts/caliber_isolation.py +60 -23
- package/scripts/circuit_breaker.py +72 -11
- package/scripts/cli_io.py +20 -2
- package/scripts/config_cache.py +44 -1
- package/scripts/daemon.py +151 -51
- package/scripts/dormant_ledger.py +23 -9
- package/scripts/engine_dispatch.py +8 -5
- package/scripts/engine_env.py +191 -1
- package/scripts/engine_families.py +50 -7
- package/scripts/engine_states.py +3 -50
- package/scripts/engine_validate.py +13 -45
- package/scripts/engines.py +15 -31
- package/scripts/engines_base.py +66 -61
- package/scripts/engines_builders.py +0 -15
- package/scripts/engines_builders_archive.py +4 -3
- package/scripts/engines_builders_batch10.py +346 -100
- package/scripts/engines_builders_batch11.py +4 -76
- package/scripts/engines_builders_batch13.py +4 -3
- package/scripts/engines_builders_batch14.py +2 -1
- package/scripts/engines_builders_batch15.py +2 -1
- package/scripts/engines_builders_batch9.py +16 -25
- package/scripts/engines_builders_cn.py +7 -201
- package/scripts/engines_builders_data.py +12 -11
- package/scripts/engines_builders_data_macro.py +5 -4
- package/scripts/engines_builders_dsh.py +2 -1
- package/scripts/engines_builders_feeds.py +76 -11
- package/scripts/engines_builders_finance.py +2 -1
- package/scripts/engines_builders_intl.py +18 -117
- package/scripts/engines_builders_media.py +59 -12
- package/scripts/engines_builders_pixiv.py +2 -16
- package/scripts/engines_builders_science.py +8 -7
- package/scripts/engines_builders_search.py +7 -14
- package/scripts/engines_builders_skill.py +2 -1
- package/scripts/engines_builders_tech.py +8 -17
- package/scripts/engines_builders_weather.py +241 -0
- package/scripts/engines_fields.py +91 -0
- package/scripts/engines_http.py +184 -0
- package/scripts/engines_mcp.py +405 -0
- package/scripts/engines_parsers.py +13 -369
- package/scripts/engines_schema_drift.py +260 -0
- package/scripts/evidence.py +13 -0
- package/scripts/evidence_loop.py +19 -4
- package/scripts/extend_route_labels.py +6 -0
- package/scripts/fetch_jina.py +98 -0
- package/scripts/fetch_jsrun.py +15 -11
- package/scripts/fetch_v3.py +79 -120
- package/scripts/fulltext_store.py +42 -1
- package/scripts/fxtwitter_api.py +8 -7
- package/scripts/gen_engine_catalog.py +2 -2
- package/scripts/general_pool.py +15 -4
- package/scripts/health_check.py +1 -1
- package/scripts/image_vision/vision_probe +0 -0
- package/scripts/install.sh +2 -0
- package/scripts/link_source.py +65 -24
- package/scripts/local_seek_adapter.py +57 -17
- package/scripts/matrix_search_eval.py +8 -10
- package/scripts/mcp_handlers.py +53 -31
- package/scripts/mcp_handlers_surface.py +6 -18
- package/scripts/mcp_transport.py +10 -5
- package/scripts/min_version_scan.py +7 -3
- package/scripts/network_aware.py +7 -13
- package/scripts/numeric_verify.py +3 -2
- package/scripts/output_transparency.py +3 -0
- package/scripts/pre-commit +45 -43
- package/scripts/query_understanding.py +30 -6
- package/scripts/quota.py +36 -30
- package/scripts/rank_signals.py +9 -0
- package/scripts/recompute.py +15 -5
- package/scripts/recovery.py +38 -29
- package/scripts/recovery_runner.py +29 -10
- package/scripts/redskill/redskill_engine.py +2 -1
- package/scripts/release.py +14 -26
- package/scripts/release_check.py +5 -25
- package/scripts/replay_eval.py +2 -2
- package/scripts/research_cli.py +40 -0
- package/scripts/research_notes.py +368 -0
- package/scripts/route.py +40 -70
- package/scripts/route_audit.py +259 -0
- package/scripts/route_combo.py +21 -6
- package/scripts/route_domains.py +150 -23
- package/scripts/route_lang.py +20 -7
- package/scripts/route_log.py +26 -9
- package/scripts/route_policy.py +85 -6
- package/scripts/route_telemetry_export.py +199 -0
- package/scripts/rrf_classic.py +5 -22
- package/scripts/search.py +2 -1
- package/scripts/search_attribution.py +53 -10
- package/scripts/search_entry.py +32 -1
- package/scripts/search_output.py +23 -11
- package/scripts/search_pipeline.py +15 -3
- package/scripts/search_rank.py +21 -11
- package/scripts/semantic_evidence.py +394 -178
- package/scripts/serp_guard.py +13 -1
- package/scripts/settings_page.py +4 -3
- package/scripts/single_flight.py +1 -1
- package/scripts/social_engines/hackernews_engine.py +2 -1
- package/scripts/social_engines/reddit_engine.py +2 -1
- package/scripts/social_engines/xiaohongshu_engine.py +2 -1
- package/scripts/social_engines/zhihu_engine.py +252 -43
- package/scripts/sogou_weixin_browser.py +5 -6
- package/scripts/source_audit.py +44 -9
- package/scripts/source_ledger.py +2 -15
- package/scripts/source_selection.py +45 -20
- package/scripts/straggler_policy.py +1 -2
- package/scripts/sync_backends.py +17 -0
- package/scripts/tfidf_router.py +23 -11
- package/scripts/time_utils.py +54 -1
- package/scripts/train.py +68 -2
- package/scripts/usage_log.py +50 -10
- package/scripts/watch.py +3 -3
- package/scripts/zhihu_quota.py +2 -1
- package/sub-skills/argo-wide-research/SKILL.md +70 -0
- package/sub-skills/ego-search/{SKILL.md → README.md} +15 -47
- package/sub-skills/ego-search/scripts/ego_search.py +13 -4
- package/sub-skills/js-run/{SKILL.md → README.md} +3 -20
- package/sub-skills/local-search/{SKILL.md → README.md} +3 -8
- package/sub-skills/local-search/engine_registry.py +32 -7
- package/sub-skills/local-seek/SKILL.md +20 -22
- package/sub-skills/local-seek/scripts/seek_fts.py +58 -3
- package/scripts/caliber_dedupe.py +0 -66
- package/scripts/engines_builders_batch16.py +0 -13
- package/scripts/health_probe.py +0 -253
- package/scripts/social_engines/twitter_engine.py +0 -514
- package/scripts/sync_installs.py +0 -29
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
|
-
"""semantic_evidence.py —
|
|
2
|
+
"""semantic_evidence.py — 可选的语义证据层(三级阶梯降级,默认关闭)。
|
|
3
3
|
|
|
4
4
|
## 为什么存在
|
|
5
5
|
|
|
@@ -47,11 +47,17 @@ logger = logging.getLogger("unified_search.semantic_evidence")
|
|
|
47
47
|
|
|
48
48
|
DEFAULT_ENDPOINT = "https://classifier.dev"
|
|
49
49
|
DEFAULT_TIMEOUT_S = 5.0
|
|
50
|
-
# 未声明 transport
|
|
51
|
-
# classifier.dev
|
|
52
|
-
DEFAULT_TRANSPORT = "
|
|
50
|
+
# 未声明 transport 时的默认通道。优先级:Gemini Decision 1 ➔ TypeSafe JEV ➔
|
|
51
|
+
# 本地启发式(allow_heuristic=True 时);classifier.dev 匿名路径自 2026-10-22 起回 403。
|
|
52
|
+
DEFAULT_TRANSPORT = "gemini"
|
|
53
|
+
VALID_TRANSPORTS = ("gemini", "jev", "classify")
|
|
53
54
|
|
|
54
|
-
# ──
|
|
55
|
+
# ── Google Gemini Decision 1 通道(首选优先通道)─────────────────────────
|
|
56
|
+
DEFAULT_GEMINI_ENDPOINT = "https://generativelanguage.googleapis.com/v1beta/decisions"
|
|
57
|
+
DEFAULT_GEMINI_MODEL = "gemini-decision-1"
|
|
58
|
+
GEMINI_KEY_ENV = ("ARGO_GEMINI_API_KEY", "GEMINI_API_KEY")
|
|
59
|
+
|
|
60
|
+
# ── JEV / System One 通道(TypeSafe 备选通道)───────────────────────────
|
|
55
61
|
# 官方 API:POST https://api.typesafe.ai/v1/systemone,Bearer 鉴权
|
|
56
62
|
# (docs.typesafe.ai/api/system-one)。与 classifier.dev 的 /v1/classify 是
|
|
57
63
|
# **两种形状**:那边一次发 N 条文本 + 一组标签;这边一次发一个 state + 若干
|
|
@@ -71,8 +77,16 @@ JEV_LONG_CONTEXT_CHARS = 24000
|
|
|
71
77
|
# 并发上限。官方 cookbook(classifying_rag_passages)取 4,理由是端点限流;
|
|
72
78
|
# 429/529 要求指数退避,所以不铺大。
|
|
73
79
|
JEV_MAX_WORKERS = 4
|
|
74
|
-
#
|
|
80
|
+
# 多并发**整批**硬截止(秒):实测冷调用在 0.55s 左右,取 1.2s(覆盖 p95),
|
|
81
|
+
# 防止网络抖动导致的误杀 fail-open,也防止某条卡死把整批拖住。
|
|
82
|
+
# 注意与 config 的 `timeout_s` 区分:那是**每条请求**的超时,这是整批预算。
|
|
75
83
|
DEFAULT_JEV_DEADLINE_S = 1.2
|
|
84
|
+
# Gemini 通道的**整批**硬截止(秒):与 JEV 分开,因为两者延迟特征不同。
|
|
85
|
+
# 2026-11-13 本机实测(gemini-decision-1,10 条冷调用):单条中位 689ms、
|
|
86
|
+
# p95 2251ms;4 条并发批量 670~1652ms、8 条 910~1534ms。取 5.0s 覆盖 8 条
|
|
87
|
+
# 两波的最坏情况(2×2.3s)并留抖动余量。沿用 1.2s 会截断:实测 6 组 4 条里
|
|
88
|
+
# 1 组只回 3/4(静默丢结果),故独立取值。
|
|
89
|
+
DEFAULT_GEMINI_DEADLINE_S = 5.0
|
|
76
90
|
|
|
77
91
|
# 结果级缓存(TTL 7 天):常见事实与热点二次判定 0ms 响应,API 消耗清零
|
|
78
92
|
_JEV_MEMORY_CACHE: dict[str, tuple[float, dict[str, Any]]] = {}
|
|
@@ -164,11 +178,13 @@ def _normalize_cache_text(text: str) -> str:
|
|
|
164
178
|
|
|
165
179
|
def _get_cache_key(text: str, labels: tuple[str, ...] | list[str],
|
|
166
180
|
instructions: str | None,
|
|
167
|
-
criteria: dict[str, str] | None = None
|
|
181
|
+
criteria: dict[str, str] | None = None,
|
|
182
|
+
salt: str = "") -> str:
|
|
168
183
|
import hashlib
|
|
169
184
|
crit_repr = str(sorted((criteria or {}).items())) if criteria else str(sorted(str(l) for l in labels))
|
|
170
185
|
norm_text = _normalize_cache_text(text)
|
|
171
|
-
|
|
186
|
+
prefix = f"{salt}::" if salt else ""
|
|
187
|
+
raw = f"{prefix}{instructions or ''}::{crit_repr}::{norm_text}"
|
|
172
188
|
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
|
173
189
|
|
|
174
190
|
|
|
@@ -200,8 +216,8 @@ def _get_cached_result(key: str) -> Optional[dict[str, Any]]:
|
|
|
200
216
|
if isinstance(res, dict):
|
|
201
217
|
_JEV_MEMORY_CACHE[key] = (rec.get("ts", time.time()), res)
|
|
202
218
|
return dict(res)
|
|
203
|
-
except
|
|
204
|
-
|
|
219
|
+
except (OSError, json.JSONDecodeError, TypeError, ValueError) as e:
|
|
220
|
+
logger.debug("读取语义缓存失败: %s", type(e).__name__)
|
|
205
221
|
return None
|
|
206
222
|
|
|
207
223
|
|
|
@@ -211,21 +227,30 @@ def _set_cached_result(key: str, result: dict[str, Any]) -> None:
|
|
|
211
227
|
now = time.time()
|
|
212
228
|
_JEV_MEMORY_CACHE[key] = (now, result)
|
|
213
229
|
try:
|
|
214
|
-
|
|
230
|
+
import argo_paths
|
|
231
|
+
from argo_paths import file_lock, state_path
|
|
215
232
|
p = Path(state_path("semantic_cache.json"))
|
|
216
|
-
data_map = {}
|
|
217
|
-
if p.is_file():
|
|
218
|
-
try:
|
|
219
|
-
data_map = json.loads(p.read_text(encoding="utf-8"))
|
|
220
|
-
except Exception:
|
|
221
|
-
data_map = {}
|
|
222
|
-
if len(data_map) > 500:
|
|
223
|
-
data_map.clear()
|
|
224
|
-
data_map[key] = {"ts": now, "result": result}
|
|
225
233
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
234
|
+
# 读改写全程持锁 + 原子写:此前裸 write_text 且无锁,并发 CLI 互丢
|
|
235
|
+
# 缓存、崩溃残留半截 JSON 让后续全部读到 miss(与 usage_log 同教训)
|
|
236
|
+
with file_lock(p):
|
|
237
|
+
data_map: dict = {}
|
|
238
|
+
if p.is_file():
|
|
239
|
+
try:
|
|
240
|
+
data_map = json.loads(p.read_text(encoding="utf-8"))
|
|
241
|
+
except (OSError, json.JSONDecodeError, ValueError):
|
|
242
|
+
data_map = {}
|
|
243
|
+
data_map[key] = {"ts": now, "result": result}
|
|
244
|
+
if len(data_map) > 500:
|
|
245
|
+
# 淘汰最旧而非清空:悬崖式 clear() 会把全部新鲜条目一次丢光
|
|
246
|
+
data_map = dict(sorted(
|
|
247
|
+
data_map.items(),
|
|
248
|
+
key=lambda kv: kv[1].get("ts", 0) if isinstance(kv[1], dict) else 0.0,
|
|
249
|
+
reverse=True,
|
|
250
|
+
)[:500])
|
|
251
|
+
argo_paths.atomic_write_json(p, data_map)
|
|
252
|
+
except (OSError, TypeError, ValueError) as e:
|
|
253
|
+
logger.debug("写入语义缓存失败: %s", type(e).__name__)
|
|
229
254
|
|
|
230
255
|
|
|
231
256
|
def _config() -> dict[str, Any]:
|
|
@@ -264,34 +289,41 @@ def _timeout() -> float:
|
|
|
264
289
|
return DEFAULT_TIMEOUT_S
|
|
265
290
|
|
|
266
291
|
|
|
267
|
-
def
|
|
268
|
-
"""
|
|
292
|
+
def _read_env_key(names: tuple[str, ...]) -> str:
|
|
293
|
+
"""按候选名读取密钥:os.environ 优先,~/.config/argo/env 热读保底。"""
|
|
269
294
|
try:
|
|
270
295
|
from engine_env import get_env
|
|
271
|
-
return (get_env(list(
|
|
296
|
+
return (get_env(list(names)) or "").strip()
|
|
272
297
|
except Exception: # pragma: no cover - 环境层不可用时不冒险
|
|
273
|
-
|
|
274
|
-
for _n in JEV_KEY_ENV:
|
|
298
|
+
for _n in names:
|
|
275
299
|
_v = (os.environ.get(_n) or "").strip()
|
|
276
300
|
if _v:
|
|
277
301
|
return _v
|
|
278
302
|
return ""
|
|
279
303
|
|
|
280
304
|
|
|
281
|
-
def
|
|
282
|
-
"""
|
|
305
|
+
def jev_api_key() -> str:
|
|
306
|
+
"""JEV(TypeSafe)key:os.environ 优先,~/.config/argo/env 热读保底。"""
|
|
307
|
+
return _read_env_key(JEV_KEY_ENV)
|
|
283
308
|
|
|
284
|
-
**纯配置驱动,不做「按键就绪自动选」**。初版按 jev_api_key() 是否就绪自动
|
|
285
|
-
选,结果是通道取决于本机 ~/.config/argo/env 里有没有那把 key——同一份代码
|
|
286
|
-
在开发机与 CI 上走不同分支,既有测试在开发机上会静默改道(实测:写进 key
|
|
287
|
-
后 test_semantic_evidence 的 5 条 HttpClient 桩里 1 条改走 JEV 路径而挂)。
|
|
288
|
-
机器状态不该改变代码路径。
|
|
289
309
|
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
310
|
+
def gemini_api_key() -> str:
|
|
311
|
+
"""Gemini Decision 1 key:os.environ 优先,~/.config/argo/env 热读保底。"""
|
|
312
|
+
return _read_env_key(GEMINI_KEY_ENV)
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _gemini_endpoint() -> str:
|
|
316
|
+
return str(_config().get("gemini_endpoint") or DEFAULT_GEMINI_ENDPOINT).rstrip("/")
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _gemini_model() -> str:
|
|
320
|
+
return str(_config().get("gemini_model") or DEFAULT_GEMINI_MODEL)
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _transport() -> str:
|
|
324
|
+
"""通道选择:`gemini`(Gemini Decision 1,默认)、`jev`(TypeSafe System One)或 `classify`。"""
|
|
293
325
|
declared = str(_config().get("transport") or "").strip().lower()
|
|
294
|
-
return declared if declared in
|
|
326
|
+
return declared if declared in VALID_TRANSPORTS else DEFAULT_TRANSPORT
|
|
295
327
|
|
|
296
328
|
|
|
297
329
|
def _jev_endpoint() -> str:
|
|
@@ -311,6 +343,23 @@ def _jev_model() -> str:
|
|
|
311
343
|
or DEFAULT_JEV_MODEL)
|
|
312
344
|
|
|
313
345
|
|
|
346
|
+
def _post_json(url: str, body: dict[str, Any], headers: dict[str, str],
|
|
347
|
+
timeout: float, tag: str) -> Optional[dict[str, Any]]:
|
|
348
|
+
"""统一 JSON POST 请求与 fail-open 错误处理。"""
|
|
349
|
+
try:
|
|
350
|
+
from http_client import HttpClient
|
|
351
|
+
resp = HttpClient(timeout=timeout, max_retries=1, jitter=False).post(
|
|
352
|
+
url, body, extra_headers=headers)
|
|
353
|
+
if resp.get("status") != 200:
|
|
354
|
+
logger.debug("%s 非 200: %s %s", tag, resp.get("status"),
|
|
355
|
+
str(resp.get("text") or resp.get("error") or "")[:160])
|
|
356
|
+
return None
|
|
357
|
+
return json.loads(resp.get("text") or "{}")
|
|
358
|
+
except Exception as e: # fail-open:语义层任何问题都不阻断核验
|
|
359
|
+
logger.debug("%s 请求失败: %s", tag, type(e).__name__)
|
|
360
|
+
return None
|
|
361
|
+
|
|
362
|
+
|
|
314
363
|
def _jev_post(path_state: Any, questions: dict[str, Any], *,
|
|
315
364
|
timeout: float) -> Optional[dict[str, Any]]:
|
|
316
365
|
"""一次 System One 请求;失败返回 None(fail-open 的全部出口都在这里)。"""
|
|
@@ -323,28 +372,13 @@ def _jev_post(path_state: Any, questions: dict[str, Any], *,
|
|
|
323
372
|
"state": path_state,
|
|
324
373
|
"questions": questions,
|
|
325
374
|
}
|
|
326
|
-
# Content-Type 必须显式给:HttpClient.post
|
|
327
|
-
# 但**从不设 Content-Type**(头只来自浏览器 UA 模板 + extra_headers)。
|
|
328
|
-
# 缺它时 FastAPI 侧把 body 当字符串,回
|
|
329
|
-
# 422 {"loc":["body"],"msg":"Input should be a valid dictionary…"}
|
|
330
|
-
# ——报错指向「请求体不是对象」,而真因是少了一个头(2026-10-22 实测踩中)。
|
|
375
|
+
# Content-Type 必须显式给:HttpClient.post 从不自动设它;缺头时服务端把 body 当字符串返回 422。
|
|
331
376
|
headers = {"Authorization": f"Bearer {key}",
|
|
332
377
|
"Content-Type": "application/json"}
|
|
333
|
-
#
|
|
378
|
+
# 长上下文显式带头,避免 >32K tokens 时触发 400 max_tokens_exceeded。
|
|
334
379
|
if len(json.dumps(path_state, ensure_ascii=False)) > JEV_LONG_CONTEXT_CHARS:
|
|
335
380
|
headers["TypeSafe-Danger-Zone-Long-Context"] = "true"
|
|
336
|
-
|
|
337
|
-
from http_client import HttpClient
|
|
338
|
-
resp = HttpClient(timeout=timeout, max_retries=1, jitter=False).post(
|
|
339
|
-
_jev_endpoint(), body, extra_headers=headers)
|
|
340
|
-
if resp.get("status") != 200:
|
|
341
|
-
logger.debug("JEV 非 200: %s %s", resp.get("status"),
|
|
342
|
-
str(resp.get("text") or resp.get("error") or "")[:200])
|
|
343
|
-
return None
|
|
344
|
-
return json.loads(resp.get("text") or "{}")
|
|
345
|
-
except Exception as e: # fail-open:语义层任何问题都不阻断核验
|
|
346
|
-
logger.debug("JEV 请求失败: %s", type(e).__name__)
|
|
347
|
-
return None
|
|
381
|
+
return _post_json(_jev_endpoint(), body, headers, timeout, "JEV")
|
|
348
382
|
|
|
349
383
|
|
|
350
384
|
def _jev_choice(text: str, labels: tuple[str, ...] | list[str],
|
|
@@ -390,37 +424,40 @@ def _jev_choice(text: str, labels: tuple[str, ...] | list[str],
|
|
|
390
424
|
return res
|
|
391
425
|
|
|
392
426
|
|
|
393
|
-
def
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
427
|
+
def _run_choice_batch(texts_len: int,
|
|
428
|
+
keep: list[tuple[int, str]],
|
|
429
|
+
choice_fn: Any,
|
|
430
|
+
*,
|
|
431
|
+
timeout: float,
|
|
432
|
+
deadline_s: float | None = None) -> Optional[list[dict[str, Any]]]:
|
|
433
|
+
"""每条文本一个请求,并发受限 + 总体硬截止预算(超时即取消未完成任务)。
|
|
398
434
|
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
435
|
+
`timeout` 是**每条请求**的超时(已通过 choice_fn 闭包传给 HttpClient),
|
|
436
|
+
不是整批预算。整批预算取 `deadline_s`,缺省 DEFAULT_JEV_DEADLINE_S;
|
|
437
|
+
Gemini 通道传 DEFAULT_GEMINI_DEADLINE_S(实测延迟显著高于 JEV,见常量注释)。
|
|
438
|
+
这是一条保护性硬上限,防止某条卡死把整批拖住(也防止调用方把 timeout_s
|
|
439
|
+
调大后整批无上限等待)。
|
|
440
|
+
|
|
441
|
+
保留 `timeout` 形参是为了兼容既有调用点与测试 patch,内部不再读它。
|
|
402
442
|
"""
|
|
403
443
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
404
|
-
texts_kept = [t[:MAX_TEXT_CHARS] for
|
|
405
|
-
|
|
444
|
+
texts_kept = [(idx, t[:MAX_TEXT_CHARS]) for idx, t in keep]
|
|
445
|
+
budget_s = float(deadline_s) if deadline_s and deadline_s > 0 else DEFAULT_JEV_DEADLINE_S
|
|
406
446
|
results: list[Optional[dict[str, Any]]] = [None] * len(texts_kept)
|
|
407
447
|
|
|
408
448
|
# 不能用 `with ThreadPoolExecutor(...)`:with 退出时 shutdown(wait=True)
|
|
409
|
-
# 会把 as_completed 超时后仍在跑的请求全部 join
|
|
410
|
-
# (实测 sleep 3s 的任务让整轮耗时 3.01s)。这里显式建池、超时后
|
|
411
|
-
# shutdown(wait=False, cancel_futures=True),只保留已完成的结果就返回。
|
|
412
|
-
# 未完成的任务内部仍由 HttpClient 的 timeout 兜底,不阻塞调用方。
|
|
449
|
+
# 会把 as_completed 超时后仍在跑的请求全部 join 完,硬截止形同虚设。
|
|
413
450
|
pool = ThreadPoolExecutor(max_workers=min(JEV_MAX_WORKERS, len(texts_kept)))
|
|
414
451
|
try:
|
|
415
|
-
futures = {pool.submit(
|
|
416
|
-
for
|
|
452
|
+
futures = {pool.submit(choice_fn, t): pos
|
|
453
|
+
for pos, (_orig_idx, t) in enumerate(texts_kept)}
|
|
417
454
|
try:
|
|
418
|
-
for fut in as_completed(futures, timeout=max(0.1,
|
|
419
|
-
|
|
455
|
+
for fut in as_completed(futures, timeout=max(0.1, budget_s)):
|
|
456
|
+
pos = futures[fut]
|
|
420
457
|
try:
|
|
421
|
-
results[
|
|
458
|
+
results[pos] = fut.result()
|
|
422
459
|
except Exception:
|
|
423
|
-
results[
|
|
460
|
+
results[pos] = None
|
|
424
461
|
except TimeoutError:
|
|
425
462
|
pass
|
|
426
463
|
finally:
|
|
@@ -428,25 +465,98 @@ def _classify_jev(texts: list[str], labels: tuple[str, ...] | list[str], *,
|
|
|
428
465
|
|
|
429
466
|
if not any(r for r in results):
|
|
430
467
|
return None
|
|
431
|
-
out: list[Optional[dict[str, Any]]] = [None] *
|
|
432
|
-
for (
|
|
468
|
+
out: list[Optional[dict[str, Any]]] = [None] * texts_len
|
|
469
|
+
for (orig_idx, _t), r in zip(texts_kept, results):
|
|
433
470
|
if isinstance(r, dict):
|
|
434
|
-
out[
|
|
471
|
+
out[orig_idx] = r
|
|
435
472
|
return out # type: ignore[return-value]
|
|
436
473
|
|
|
437
474
|
|
|
475
|
+
def _classify_jev(texts: list[str], labels: tuple[str, ...] | list[str], *,
|
|
476
|
+
instructions: str | None, criteria: dict[str, str] | None = None,
|
|
477
|
+
keep: list[tuple[int, str]],
|
|
478
|
+
timeout: float) -> Optional[list[dict[str, Any]]]:
|
|
479
|
+
"""JEV 通道:每条文本一个请求,并发 4,带总体时间硬截止预算。"""
|
|
480
|
+
return _run_choice_batch(
|
|
481
|
+
len(texts), keep,
|
|
482
|
+
lambda t: _jev_choice(t, labels, instructions, timeout, criteria),
|
|
483
|
+
timeout=timeout,
|
|
484
|
+
)
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _gemini_choice(text: str, labels: tuple[str, ...] | list[str],
|
|
488
|
+
instructions: str | None, timeout: float,
|
|
489
|
+
criteria: dict[str, str] | None = None) -> Optional[dict[str, Any]]:
|
|
490
|
+
key = gemini_api_key()
|
|
491
|
+
if not key:
|
|
492
|
+
logger.debug("Gemini key 未配置(%s),跳过 Gemini 通道", " / ".join(GEMINI_KEY_ENV))
|
|
493
|
+
return None
|
|
494
|
+
cache_key = _get_cache_key(text, labels, instructions, criteria=criteria,
|
|
495
|
+
salt=f"gemini:{_gemini_model()}")
|
|
496
|
+
cached = _get_cached_result(cache_key)
|
|
497
|
+
if cached is not None:
|
|
498
|
+
return cached
|
|
499
|
+
question_payload: dict[str, Any] = {
|
|
500
|
+
"type": "choice",
|
|
501
|
+
"instructions": instructions or ("Classify the text into one of: " + ", ".join(labels)),
|
|
502
|
+
"criteria": criteria if criteria else {str(l): str(l) for l in labels},
|
|
503
|
+
}
|
|
504
|
+
body = {
|
|
505
|
+
"model": _gemini_model(),
|
|
506
|
+
"input": text[:MAX_TEXT_CHARS],
|
|
507
|
+
"questions": {"eval": question_payload},
|
|
508
|
+
}
|
|
509
|
+
headers = {
|
|
510
|
+
"x-goog-api-key": key,
|
|
511
|
+
"Content-Type": "application/json",
|
|
512
|
+
}
|
|
513
|
+
data = _post_json(_gemini_endpoint(), body, headers, timeout, "Gemini")
|
|
514
|
+
if not isinstance(data, dict):
|
|
515
|
+
return None
|
|
516
|
+
ans = data.get("answers", {}).get("eval", {})
|
|
517
|
+
choice = ans.get("choice")
|
|
518
|
+
if not choice:
|
|
519
|
+
return None
|
|
520
|
+
probs = ans.get("probabilities", {})
|
|
521
|
+
res = {
|
|
522
|
+
"label": str(choice),
|
|
523
|
+
"confidence": float(ans.get("confidence", 0.0)),
|
|
524
|
+
"scores": probs,
|
|
525
|
+
"probabilities": probs,
|
|
526
|
+
}
|
|
527
|
+
_set_cached_result(cache_key, res)
|
|
528
|
+
return res
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def _classify_gemini(texts: list[str], labels: tuple[str, ...] | list[str], *,
|
|
532
|
+
instructions: str | None = None,
|
|
533
|
+
criteria: dict[str, str] | None = None,
|
|
534
|
+
keep: list[tuple[int, str]],
|
|
535
|
+
timeout: float = 5.0) -> Optional[list[Optional[dict[str, Any]]]]:
|
|
536
|
+
"""Gemini 通道:每条文本一个请求,并发 4,整批硬截止取 DEFAULT_GEMINI_DEADLINE_S。
|
|
537
|
+
|
|
538
|
+
与 JEV 的 1.2s 分开取值:Gemini 单条 p95 实测 2251ms(见常量注释),
|
|
539
|
+
沿用 1.2s 会在批量里静默截断(实测 6 组 4 条里 1 组只回 3/4)。
|
|
540
|
+
"""
|
|
541
|
+
if not gemini_api_key():
|
|
542
|
+
return None
|
|
543
|
+
return _run_choice_batch(
|
|
544
|
+
len(texts), keep,
|
|
545
|
+
lambda t: _gemini_choice(t, labels, instructions, timeout, criteria),
|
|
546
|
+
timeout=timeout,
|
|
547
|
+
deadline_s=DEFAULT_GEMINI_DEADLINE_S,
|
|
548
|
+
)
|
|
549
|
+
|
|
550
|
+
|
|
438
551
|
def classify(texts: list[str], labels: tuple[str, ...] | list[str], *,
|
|
439
552
|
instructions: str | None = None,
|
|
440
553
|
criteria: dict[str, str] | None = None,
|
|
441
554
|
timeout: float | None = None,
|
|
442
555
|
tier: str | None = None) -> Optional[list[dict[str, Any]]]:
|
|
443
|
-
"""
|
|
556
|
+
"""一次批量远程语义分类。任何异常/非 200/条数不匹配 → None。
|
|
444
557
|
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
两个通道的实现分居 _classify_jev(TypeSafe,每条一请求)与下方内联的
|
|
449
|
-
classifier.dev 路径(一次发 N 条);开关判定见 _transport。
|
|
558
|
+
远程通道按优先级自适应:Gemini Decision 1 ➔ TypeSafe JEV(互为备选),
|
|
559
|
+
或显式走 classify。本地启发式兜底由上层 assess_*(allow_heuristic=True)承担。
|
|
450
560
|
"""
|
|
451
561
|
if not texts or len(labels) < 2:
|
|
452
562
|
return None
|
|
@@ -454,9 +564,25 @@ def classify(texts: list[str], labels: tuple[str, ...] | list[str], *,
|
|
|
454
564
|
if not keep:
|
|
455
565
|
return None
|
|
456
566
|
to = timeout or _timeout()
|
|
457
|
-
|
|
567
|
+
|
|
568
|
+
tp = _transport()
|
|
569
|
+
if tp == "gemini":
|
|
570
|
+
res = _classify_gemini(texts, labels, instructions=instructions,
|
|
571
|
+
criteria=criteria, keep=keep, timeout=to)
|
|
572
|
+
if res is not None:
|
|
573
|
+
return res
|
|
574
|
+
# 降级至 JEV 备用通道
|
|
458
575
|
return _classify_jev(texts, labels, instructions=instructions,
|
|
459
576
|
criteria=criteria, keep=keep, timeout=to)
|
|
577
|
+
|
|
578
|
+
if tp == "jev":
|
|
579
|
+
res = _classify_jev(texts, labels, instructions=instructions,
|
|
580
|
+
criteria=criteria, keep=keep, timeout=to)
|
|
581
|
+
if res is not None:
|
|
582
|
+
return res
|
|
583
|
+
# 降级至 Gemini 备用通道
|
|
584
|
+
return _classify_gemini(texts, labels, instructions=instructions,
|
|
585
|
+
criteria=criteria, keep=keep, timeout=to)
|
|
460
586
|
body: dict[str, Any] = {
|
|
461
587
|
"labels": [str(x) for x in labels],
|
|
462
588
|
"inputs": [t[:MAX_TEXT_CHARS] for _i, t in keep],
|
|
@@ -490,31 +616,46 @@ def classify(texts: list[str], labels: tuple[str, ...] | list[str], *,
|
|
|
490
616
|
return out # type: ignore[return-value]
|
|
491
617
|
|
|
492
618
|
|
|
493
|
-
def
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
619
|
+
def _prepare_usable_texts(
|
|
620
|
+
items: list[dict[str, Any]], *, require_text: bool = True
|
|
621
|
+
) -> tuple[list[dict[str, Any]], list[str]]:
|
|
622
|
+
"""过滤非本地目标并拼装截断文本,统一三路语义评估的前置隔离逻辑。"""
|
|
623
|
+
usable = []
|
|
624
|
+
for it in items:
|
|
625
|
+
url = it.get("url")
|
|
626
|
+
if not url or is_local_target(url):
|
|
627
|
+
continue
|
|
628
|
+
has_text = bool((it.get("text") or "").strip())
|
|
629
|
+
has_title = bool((it.get("title") or "").strip())
|
|
630
|
+
if has_text or (not require_text and has_title):
|
|
631
|
+
usable.append(it)
|
|
632
|
+
texts = [
|
|
633
|
+
f"{it.get('title') or ''}\n{(it.get('text') or '')[:MAX_TEXT_CHARS]}"
|
|
634
|
+
for it in usable
|
|
635
|
+
]
|
|
636
|
+
return usable, texts
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
def _assess_batch(
|
|
640
|
+
items: list[dict[str, Any]],
|
|
641
|
+
*,
|
|
642
|
+
require_text: bool,
|
|
643
|
+
labels: tuple[str, ...],
|
|
644
|
+
instructions: str,
|
|
645
|
+
criteria: dict[str, str] | None = None,
|
|
646
|
+
heuristic_fn: Any,
|
|
647
|
+
allow_heuristic: bool,
|
|
648
|
+
build_extra: Any,
|
|
649
|
+
) -> Optional[dict[str, dict]]:
|
|
650
|
+
"""三路语义评估的统一批处理框架:隔离本地目标、调用远程分类、按需启发式兜底与阈值判定。"""
|
|
651
|
+
usable, texts = _prepare_usable_texts(items, require_text=require_text)
|
|
504
652
|
if not usable:
|
|
505
653
|
return None
|
|
506
|
-
|
|
507
|
-
for it in usable]
|
|
508
|
-
instructions = (
|
|
509
|
-
f"Judge whether each passage supports the claim implied by this query: {query!r}. "
|
|
510
|
-
"Answer 'supports the query' when the passage backs the claim, "
|
|
511
|
-
"'contradicts the query' when it states the opposite or a conflicting figure, "
|
|
512
|
-
"'neutral' when it is on-topic but neither supports nor contradicts, "
|
|
513
|
-
"and 'none of these' when it is unrelated to the query."
|
|
514
|
-
)
|
|
515
|
-
results = classify(texts, SUPPORT_LABELS, instructions=instructions)
|
|
654
|
+
results = classify(texts, labels, instructions=instructions, criteria=criteria)
|
|
516
655
|
if results is None:
|
|
517
|
-
|
|
656
|
+
if not allow_heuristic:
|
|
657
|
+
return None
|
|
658
|
+
results = [heuristic_fn(it) for it in usable]
|
|
518
659
|
out: dict[str, dict] = {}
|
|
519
660
|
for it, r in zip(usable, results):
|
|
520
661
|
if not r:
|
|
@@ -522,85 +663,160 @@ def assess_support(query: str, items: list[dict[str, Any]]) -> Optional[dict[str
|
|
|
522
663
|
label = str(r.get("label") or "")
|
|
523
664
|
conf = r.get("confidence")
|
|
524
665
|
conf_f = float(conf) if isinstance(conf, (int, float)) else 0.0
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
"supports": label == "supports the query" and conf_f >= SUPPORT_THRESHOLD,
|
|
529
|
-
"contradicts": label == "contradicts the query" and conf_f >= SUPPORT_THRESHOLD,
|
|
530
|
-
}
|
|
666
|
+
entry: dict[str, Any] = {"label": label, "confidence": conf_f}
|
|
667
|
+
entry.update(build_extra(label, conf_f))
|
|
668
|
+
out[str(it["url"])] = entry
|
|
531
669
|
return out or None
|
|
532
670
|
|
|
533
671
|
|
|
534
|
-
def
|
|
535
|
-
"""
|
|
672
|
+
def assess_support(query: str, items: list[dict[str, Any]], *, allow_heuristic: bool = False) -> Optional[dict[str, dict]]:
|
|
673
|
+
"""对已抓取的正文批量判定「是否支持查询隐含的主张」。"""
|
|
674
|
+
instructions = (
|
|
675
|
+
f"Judge whether each passage supports the claim implied by this query: {query!r}. "
|
|
676
|
+
"Answer 'supports the query' when the passage backs the claim, "
|
|
677
|
+
"'contradicts the query' when it states the opposite or a conflicting figure, "
|
|
678
|
+
"'neutral' when it is on-topic but neither supports nor contradicts, "
|
|
679
|
+
"and 'none of these' when it is unrelated to the query."
|
|
680
|
+
)
|
|
681
|
+
return _assess_batch(
|
|
682
|
+
items,
|
|
683
|
+
require_text=True,
|
|
684
|
+
labels=SUPPORT_LABELS,
|
|
685
|
+
instructions=instructions,
|
|
686
|
+
heuristic_fn=lambda it: heuristic_support(query, it.get("text") or "", it.get("title") or ""),
|
|
687
|
+
allow_heuristic=allow_heuristic,
|
|
688
|
+
build_extra=lambda label, conf_f: {
|
|
689
|
+
"supports": label == "supports the query" and conf_f >= SUPPORT_THRESHOLD,
|
|
690
|
+
"contradicts": label == "contradicts the query" and conf_f >= SUPPORT_THRESHOLD,
|
|
691
|
+
},
|
|
692
|
+
)
|
|
536
693
|
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
694
|
+
|
|
695
|
+
_NON_CJK_EAST_ASIAN_RE = re.compile(r"[\u3040-\u30ff]{2,}|[\uac00-\ud7af]{2,}")
|
|
696
|
+
_SENTENCE_SPLIT_RE = re.compile(r"[。!?.!?\n]+")
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def _heuristic_tokens(text: str) -> list[str]:
|
|
700
|
+
"""复用 cjk_tokens 切分中英信号,并扩展日文假名/韩文音节重叠 2-gram。"""
|
|
701
|
+
from cjk_tokens import cjk_ngrams, signal_tokens
|
|
702
|
+
tokens = signal_tokens(text)
|
|
703
|
+
for run in _NON_CJK_EAST_ASIAN_RE.findall(text or ""):
|
|
704
|
+
tokens.extend(cjk_ngrams(run))
|
|
705
|
+
deduped = list(dict.fromkeys(t for t in tokens if len(t) >= 2))
|
|
706
|
+
if not deduped and (text or "").strip():
|
|
707
|
+
return [(text or "").strip().lower()]
|
|
708
|
+
return deduped
|
|
709
|
+
|
|
710
|
+
|
|
711
|
+
def heuristic_substantive_discussion(topic: str, text: str, title: str = "") -> dict[str, Any]:
|
|
712
|
+
"""本地高精度启发式深度判定:区分实质深入探讨 vs 顺带提及(零网络、零外部 Key 依赖)。"""
|
|
713
|
+
t_clean = (topic or "").strip().lower()
|
|
714
|
+
full_text = f"{title}\n{text}".lower()
|
|
715
|
+
if not t_clean or not full_text.strip():
|
|
716
|
+
return {"label": "none of these", "confidence": 0.5}
|
|
717
|
+
|
|
718
|
+
tokens = _heuristic_tokens(topic)
|
|
719
|
+
title_low = (title or "").lower()
|
|
720
|
+
title_hit = any(tok in title_low for tok in tokens)
|
|
721
|
+
sentences = [s.strip() for s in _SENTENCE_SPLIT_RE.split(text.lower()) if s.strip()]
|
|
722
|
+
sent_hits = sum(1 for s in sentences if any(tok in s for tok in tokens))
|
|
723
|
+
token_hits = sum(1 for tok in tokens if tok in full_text)
|
|
724
|
+
text_len = len(text.strip())
|
|
725
|
+
|
|
726
|
+
# 实质探讨:(标题明确命中且正文 >= 30 字) 或 (至少 2 个独立句命中主题且篇幅 >= 60 字)
|
|
727
|
+
if (title_hit and text_len >= 30) or (sent_hits >= 2 and text_len >= 60):
|
|
728
|
+
return {"label": "substantive in-depth discussion", "confidence": 0.88}
|
|
729
|
+
# 顺带提及:单句提及或篇幅不足
|
|
730
|
+
if token_hits >= 1 or sent_hits >= 1 or text_len >= 40:
|
|
731
|
+
return {"label": "passing mention or brief reference", "confidence": 0.78}
|
|
732
|
+
return {"label": "unrelated chatter", "confidence": 0.72}
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
def heuristic_source_type(url: str, title: str = "", text: str = "") -> dict[str, Any]:
|
|
736
|
+
"""本地高精度启发式来源类型分级(零网络、零外部依赖)。"""
|
|
737
|
+
u_low = (url or "").lower()
|
|
738
|
+
full_text = f"{title}\n{text}".lower()
|
|
739
|
+
|
|
740
|
+
primary_domains = (
|
|
741
|
+
".gov", ".edu", "sec.gov", "arxiv.org", "biorxiv.org", "github.com",
|
|
742
|
+
"rfc-editor.org", "federalregister.gov", "w3.org", "nature.com"
|
|
743
|
+
)
|
|
744
|
+
primary_keywords = ("official announcement", "press release", "filing", "whitepaper", "documentation", "公报", "公告", "官方发布")
|
|
745
|
+
if any(d in u_low for d in primary_domains) or any(k in full_text for k in primary_keywords):
|
|
746
|
+
return {"label": "primary data or official announcement", "confidence": 0.86}
|
|
747
|
+
|
|
748
|
+
social_domains = ("x.com", "twitter.com", "reddit.com", "weibo.com", "zhihu.com", "v2ex.com", "news.ycombinator.com")
|
|
749
|
+
if any(d in u_low for d in social_domains):
|
|
750
|
+
return {"label": "social narrative", "confidence": 0.82}
|
|
751
|
+
|
|
752
|
+
opinion_keywords = ("analysis", "opinion", "commentary", "review", "perspective", "评论", "专栏", "深度分析")
|
|
753
|
+
if any(k in full_text for k in opinion_keywords):
|
|
754
|
+
return {"label": "analysis or opinion", "confidence": 0.76}
|
|
755
|
+
|
|
756
|
+
return {"label": "secondary reporting", "confidence": 0.75}
|
|
757
|
+
|
|
758
|
+
|
|
759
|
+
def heuristic_support(query: str, text: str, title: str = "") -> dict[str, Any]:
|
|
760
|
+
"""本地高精度启发式证据支持度初筛(零网络、零外部依赖,支持 CJK/多语 2-gram 与同句极性窗口)。"""
|
|
761
|
+
full_text = f"{title}\n{text}".lower()
|
|
762
|
+
tokens = _heuristic_tokens(query)
|
|
763
|
+
if not tokens:
|
|
764
|
+
return {"label": "neutral", "confidence": 0.70}
|
|
765
|
+
hits = sum(1 for tok in tokens if tok in full_text)
|
|
766
|
+
contra_words = (
|
|
767
|
+
"keep unchanged", "remain unchanged", "defying", "opposite", "denied", "contrary",
|
|
768
|
+
"未降息", "维持不变", "并未", "未如", "反驳", "并非", "否认",
|
|
769
|
+
)
|
|
770
|
+
sentences = [s.strip() for s in _SENTENCE_SPLIT_RE.split(full_text) if s.strip()]
|
|
771
|
+
has_contra = any(
|
|
772
|
+
any(w in s for w in contra_words) and any(tok in s for tok in tokens)
|
|
773
|
+
for s in sentences
|
|
774
|
+
)
|
|
775
|
+
if has_contra:
|
|
776
|
+
return {"label": "contradicts the query", "confidence": 0.85}
|
|
777
|
+
ratio = hits / len(tokens)
|
|
778
|
+
has_cjk = any(ord(c) > 0x2E80 for c in query)
|
|
779
|
+
min_hits = 2 if (has_cjk and len(tokens) > 2) else 1
|
|
780
|
+
threshold = 0.25 if has_cjk else 0.65
|
|
781
|
+
if ratio >= threshold and hits >= min_hits:
|
|
782
|
+
return {"label": "supports the query", "confidence": 0.80}
|
|
783
|
+
return {"label": "neutral", "confidence": 0.70}
|
|
784
|
+
|
|
785
|
+
|
|
786
|
+
def assess_source_types(items: list[dict[str, Any]], *, allow_heuristic: bool = False) -> Optional[dict[str, dict]]:
|
|
787
|
+
"""来源类型分级(研究取证链路用):一手数据 / 二手报道 / 分析观点 / 社交叙事。"""
|
|
547
788
|
instructions = (
|
|
548
789
|
"Classify each source by its nature: 'primary data or official announcement' "
|
|
549
790
|
"for original datasets, filings, official releases; 'secondary reporting' for "
|
|
550
791
|
"news coverage of someone else's work; 'analysis or opinion' for commentary; "
|
|
551
792
|
"'social narrative' for forum/social posts."
|
|
552
793
|
)
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
"label": label,
|
|
565
|
-
"confidence": conf_f,
|
|
566
|
-
"is_primary": (label == "primary data or official announcement" and conf_f >= SUPPORT_THRESHOLD),
|
|
567
|
-
}
|
|
568
|
-
return out or None
|
|
569
|
-
|
|
794
|
+
return _assess_batch(
|
|
795
|
+
items,
|
|
796
|
+
require_text=False,
|
|
797
|
+
labels=SOURCE_TYPE_LABELS,
|
|
798
|
+
instructions=instructions,
|
|
799
|
+
heuristic_fn=lambda it: heuristic_source_type(it.get("url") or "", it.get("title") or "", it.get("text") or ""),
|
|
800
|
+
allow_heuristic=allow_heuristic,
|
|
801
|
+
build_extra=lambda label, conf_f: {
|
|
802
|
+
"is_primary": label == "primary data or official announcement" and conf_f >= SUPPORT_THRESHOLD,
|
|
803
|
+
},
|
|
804
|
+
)
|
|
570
805
|
|
|
571
|
-
def assess_substantive_discussion(topic: str, items: list[dict[str, Any]]) -> Optional[dict[str, dict]]:
|
|
572
|
-
"""对正文/播客单集转录/长篇段落批量判定「是否对主题进行了实质性深入探讨」。
|
|
573
806
|
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
criteria=SUBSTANTIVE_DISCUSSION_CRITERIA)
|
|
590
|
-
if results is None:
|
|
591
|
-
return None
|
|
592
|
-
out: dict[str, dict] = {}
|
|
593
|
-
for it, r in zip(usable, results):
|
|
594
|
-
if not r:
|
|
595
|
-
continue
|
|
596
|
-
label = str(r.get("label") or "")
|
|
597
|
-
conf = r.get("confidence")
|
|
598
|
-
conf_f = float(conf) if isinstance(conf, (int, float)) else 0.0
|
|
599
|
-
out[str(it["url"])] = {
|
|
600
|
-
"label": label,
|
|
601
|
-
"confidence": conf_f,
|
|
602
|
-
"is_substantive": (label == "substantive in-depth discussion" and conf_f >= SUPPORT_THRESHOLD),
|
|
603
|
-
"is_passing_mention": (label == "passing mention or brief reference" and conf_f >= SUPPORT_THRESHOLD),
|
|
604
|
-
}
|
|
605
|
-
return out or None
|
|
807
|
+
def assess_substantive_discussion(topic: str, items: list[dict[str, Any]], *, allow_heuristic: bool = False) -> Optional[dict[str, dict]]:
|
|
808
|
+
"""批量判定正文对主题是否进行了实质性深入探讨(或顺带提及 / 闲聊)。"""
|
|
809
|
+
return _assess_batch(
|
|
810
|
+
items,
|
|
811
|
+
require_text=True,
|
|
812
|
+
labels=SUBSTANTIVE_DISCUSSION_LABELS,
|
|
813
|
+
instructions=f"Determine the depth of discussion regarding the topic {topic!r} in the text.",
|
|
814
|
+
criteria=SUBSTANTIVE_DISCUSSION_CRITERIA,
|
|
815
|
+
heuristic_fn=lambda it: heuristic_substantive_discussion(topic, it.get("text") or "", it.get("title") or ""),
|
|
816
|
+
allow_heuristic=allow_heuristic,
|
|
817
|
+
build_extra=lambda label, conf_f: {
|
|
818
|
+
"is_substantive": label == "substantive in-depth discussion" and conf_f >= SUPPORT_THRESHOLD,
|
|
819
|
+
"is_passing_mention": label == "passing mention or brief reference" and conf_f >= SUPPORT_THRESHOLD,
|
|
820
|
+
},
|
|
821
|
+
)
|
|
606
822
|
|