@onigeya/dsh-kanabo-memory 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,150 @@
1
+ /**
2
+ * 召回融合之后的两级判定:重排(cross-encoder)与 decision 模型(Hindsight 的 ranker 用法)。
3
+ *
4
+ * 为什么分成独立的纯函数:融合(`fuseArms`)是可解释的、确定性的 RRF;这两级是**外部模型**,
5
+ * 会超时、会 401、会返回形状不对的东西。把「网络失败」与「排序数学」分开,才能让探针在没有
6
+ * 网络时断言「失败也保持原顺序」,在有网络时断言「确实改变了顺序」。
7
+ *
8
+ * 顺序与 Hindsight 一致:RRF → rerank(CE) → decision(judge)。Hindsight 在配置了 decision
9
+ * reranker 时会让 CE 的 recency 加成失效(`decision_reranker.py` 顶部注释:order is final),
10
+ * 这里保持同一语义:judge 存在时,它的顺序就是最终顺序,CE 只决定「judge 之前」的顺序。
11
+ */
12
+
13
+ import { keepQuestion, rankAnswers } from './providers.js'
14
+
15
+ function stageError(code, message, detail) {
16
+ const error = new Error(message)
17
+ error.code = code
18
+ if (detail !== undefined) error.details = detail
19
+ return error
20
+ }
21
+
22
+ const idsOf = (list) => list.map((hit) => hit.id)
23
+
24
+ /**
25
+ * 重排:只对前 `maxCandidates` 条问 CE,尾部不动。
26
+ * 最终分 = `weight × ce + (1 - weight) × rrfNorm`,平分时保持原 RRF 顺序(稳定排序)。
27
+ * 失败(无配置/超时/HTTP 错误)一律返回原列表 + `applied:false` 的阶段报告,绝不抛。
28
+ */
29
+ export async function applyRerank(fused, query, options = {}) {
30
+ const client = options.client ?? null
31
+ const base = { provider: 'rerank', model: client?.model ?? null }
32
+ if (client === null || client.enabled !== true) return { list: fused, stage: { ...base, applied: false, reason: 'not-configured' } }
33
+ if (fused.length === 0) return { list: fused, stage: { ...base, applied: false, reason: 'empty' } }
34
+ const max = Math.max(1, Math.min(options.maxCandidates ?? 24, fused.length))
35
+ const weight = Number.isFinite(options.weight) ? Math.max(0, Math.min(1, options.weight)) : 0.6
36
+ const head = fused.slice(0, max)
37
+ const tail = fused.slice(max)
38
+ let result
39
+ try {
40
+ result = await client.score(query, head.map((hit) => (hit.text === '' ? '(empty)' : hit.text)))
41
+ } catch (error) {
42
+ result = { ok: false, ms: 0, error: { code: 'KANABO_RERANK_THREW', message: String(error?.message ?? error) } }
43
+ }
44
+ if (result?.ok !== true) {
45
+ return {
46
+ list: fused,
47
+ stage: { ...base, applied: false, candidates: max, ms: result?.ms ?? 0, degraded: result?.error ?? { code: 'KANABO_RERANK', message: '重排没有结果' } },
48
+ }
49
+ }
50
+ const maxRrf = head.reduce((best, hit) => Math.max(best, Number(hit.rrf) || 0), 0) || 1
51
+ const scored = head.map((hit, index) => {
52
+ const ce = Math.max(0, Math.min(1, Number(result.scores[index]) || 0))
53
+ const rrfNorm = Math.max(0, Math.min(1, (Number(hit.rrf) || 0) / maxRrf))
54
+ const combined = weight * ce + (1 - weight) * rrfNorm
55
+ return { hit, ce, rrfNorm, combined, index }
56
+ })
57
+ scored.sort((left, right) => right.combined - left.combined || left.index - right.index)
58
+ const ranked = scored.map((row) => ({
59
+ ...row.hit,
60
+ score: row.combined,
61
+ why: { ...row.hit.why, rerank: { ce: row.ce, rrfNorm: row.rrfNorm, combined: row.combined, weight } },
62
+ }))
63
+ const list = [...ranked, ...tail]
64
+ const before = idsOf(fused).slice(0, max)
65
+ const after = idsOf(ranked)
66
+ return {
67
+ list,
68
+ stage: {
69
+ ...base,
70
+ applied: true,
71
+ candidates: max,
72
+ ms: result.ms ?? 0,
73
+ weight,
74
+ changed: before.some((id, index) => id !== after[index]),
75
+ top1: after[0] ?? null,
76
+ scores: scored.map((row) => ({ id: row.hit.id, ce: row.ce, combined: row.combined })),
77
+ },
78
+ }
79
+ }
80
+
81
+ /**
82
+ * decision 模型:对前 `maxCandidates` 条逐条问 KEEP 题(一次批量请求),按答案排名并剪除。
83
+ * 分数是名次而不是置信度(与 Hindsight 一致),最佳候选永远保留。
84
+ *
85
+ * `required:true` 时失败即抛 `KANABO_RECALL_JUDGE`——此时它**是** ranker,rank 坏了排序就是假的;
86
+ * 默认 `required:false`,失败只记 `degraded` 并保持上一级顺序。
87
+ */
88
+ export async function applyJudge(list, query, options = {}) {
89
+ const client = options.client ?? null
90
+ const base = { provider: 'decision', model: client?.model ?? null, protocol: client?.protocol ?? null }
91
+ if (client === null || client.enabled !== true) return { list, stage: { ...base, applied: false, reason: 'not-configured' } }
92
+ if (list.length === 0) return { list, stage: { ...base, applied: false, reason: 'empty' } }
93
+ const max = Math.max(1, Math.min(options.maxCandidates ?? 12, list.length))
94
+ const head = list.slice(0, max)
95
+ const tail = list.slice(max)
96
+ const questions = head.map((hit, index) => ({ ...keepQuestion(index, hit.text === '' ? '(empty)' : hit.text), type: 'noul' }))
97
+ let result
98
+ try {
99
+ result = await client.judge(options.state ?? `Question: ${String(query ?? '')}`, questions)
100
+ } catch (error) {
101
+ result = { ok: false, ms: 0, error: { code: 'KANABO_DECISION_THREW', message: String(error?.message ?? error) } }
102
+ }
103
+ if (result?.ok !== true) {
104
+ if (options.required === true) {
105
+ throw stageError(
106
+ 'KANABO_RECALL_JUDGE',
107
+ `decision 模型被配置为必需(required),但这次判定失败:${result?.error?.message ?? '未知错误'}`,
108
+ { model: client?.model ?? null, error: result?.error ?? null })
109
+ }
110
+ return {
111
+ list,
112
+ stage: { ...base, applied: false, candidates: max, ms: result?.ms ?? 0, degraded: result?.error ?? { code: 'KANABO_DECISION', message: '判定没有结果' } },
113
+ }
114
+ }
115
+ const keys = questions.map((question) => question.key)
116
+ const rank = rankAnswers(result.probabilities, keys, {
117
+ minProbability: options.minProbability,
118
+ keepBest: options.keepBest,
119
+ })
120
+ const judged = rank.kept.map((index) => ({
121
+ ...head[index],
122
+ why: {
123
+ ...head[index].why,
124
+ judge: {
125
+ probability: result.probabilities?.[keys[index]] ?? 0,
126
+ position: rank.scores[index],
127
+ },
128
+ },
129
+ }))
130
+ const finalList = [...judged, ...tail]
131
+ const before = idsOf(list).slice(0, max)
132
+ const after = idsOf(judged)
133
+ return {
134
+ list: finalList,
135
+ stage: {
136
+ ...base,
137
+ applied: true,
138
+ candidates: max,
139
+ ms: result.ms ?? 0,
140
+ floor: rank.floor,
141
+ best: rank.best,
142
+ kept: judged.length,
143
+ pruned: rank.dropped.length,
144
+ changed: before.length !== after.length || before.some((id, index) => id !== after[index]),
145
+ probabilities: keys.map((key) => ({ id: head[keys.indexOf(key)]?.id ?? null, probability: result.probabilities?.[key] ?? null })),
146
+ },
147
+ }
148
+ }
149
+
150
+ export default applyRerank