@drsamonline/verify 0.0.0-stage → 0.12.3
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/package.json +23 -4
- package/src/index.js +217 -0
- package/README.md +0 -3
package/package.json
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drsamonline/verify",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.12.3",
|
|
4
|
+
"description": "Reference-free confidence scoring and fail-closed escalation (B3.4).",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"main": "./src/index.js",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": "./src/index.js",
|
|
10
|
+
"./src/*": "./src/*"
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"src"
|
|
14
|
+
],
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git://github.com/drsamonline/sui.git",
|
|
18
|
+
"directory": "packages/verify"
|
|
19
|
+
},
|
|
20
|
+
"homepage": "https://github.com/drsamonline/sui#readme",
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public",
|
|
23
|
+
"registry": "https://registry.npmjs.org/"
|
|
24
|
+
}
|
|
25
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @drsamonline/verify — reference-free confidence scoring (B3.4).
|
|
3
|
+
*
|
|
4
|
+
* The spec asks for "verification escalation, fail-closed, confidence threshold
|
|
5
|
+
* 0.7". There is no judge model here on purpose: a judge costs the same quota the
|
|
6
|
+
* gateway is trying to conserve, and a judge that cannot explain itself is worse
|
|
7
|
+
* than a heuristic that can.
|
|
8
|
+
*
|
|
9
|
+
* So this is a set of deterministic signals about an answer, each of which can
|
|
10
|
+
* be pointed at in a test:
|
|
11
|
+
*
|
|
12
|
+
* empty or near-empty · refusal markers · hedging density · repetition ·
|
|
13
|
+
* truncated by the token limit · asked for JSON and returned prose ·
|
|
14
|
+
* asked a question and answered a different one (overlap)
|
|
15
|
+
*
|
|
16
|
+
* Every signal lowers confidence for a stated reason. `scoreAnswer` returns the
|
|
17
|
+
* reasons, not just the number, so a low score is always explainable.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/** Words that mean "I am guessing" rather than "I know". */
|
|
21
|
+
const HEDGES = [
|
|
22
|
+
'i think', 'i believe', 'probably', 'maybe', 'perhaps', 'possibly', 'might be',
|
|
23
|
+
'not sure', "i'm not sure", 'unclear', 'as far as i know', 'roughly', 'approximately',
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
/** Words that mean "I am declining" — legitimate, but not a confident answer. */
|
|
27
|
+
const REFUSALS = [
|
|
28
|
+
'i cannot', "i can't", 'i will not', "i won't", 'i am unable', "i'm unable",
|
|
29
|
+
'not able to help', 'i must decline', 'cannot assist',
|
|
30
|
+
];
|
|
31
|
+
|
|
32
|
+
/** Phrases that suggest the model lost the thread. */
|
|
33
|
+
const LOOP_MARKERS = ['as mentioned above', 'as i said before', 'to repeat myself'];
|
|
34
|
+
|
|
35
|
+
export const DEFAULT_THRESHOLD = 0.7;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* @param {{text: string, prompt?: string, finishReason?: string|null, wantsJson?: boolean}} input
|
|
39
|
+
* @returns {{confidence: number, reasons: Array<{signal: string, penalty: number, detail: string}>}}
|
|
40
|
+
*/
|
|
41
|
+
export function scoreAnswer(input) {
|
|
42
|
+
const text = String(input.text ?? '');
|
|
43
|
+
const prompt = String(input.prompt ?? '');
|
|
44
|
+
const trimmed = text.trim();
|
|
45
|
+
const lower = trimmed.toLowerCase();
|
|
46
|
+
/** @type {Array<{signal: string, penalty: number, detail: string}>} */
|
|
47
|
+
const reasons = [];
|
|
48
|
+
|
|
49
|
+
const penalise = (signal, penalty, detail) => reasons.push({ signal, penalty, detail });
|
|
50
|
+
|
|
51
|
+
// 1. an empty or near-empty answer is a failure, not a short answer
|
|
52
|
+
if (trimmed.length === 0) penalise('empty', 1, 'the provider returned no text');
|
|
53
|
+
else if (trimmed.length < 8) penalise('near_empty', 0.5, `only ${trimmed.length} characters`);
|
|
54
|
+
|
|
55
|
+
// 2. truncation: the model stopped because it ran out of room
|
|
56
|
+
if (input.finishReason === 'length' || input.finishReason === 'max_tokens') {
|
|
57
|
+
penalise('truncated', 0.35, 'the answer was cut off by the token limit');
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// 3. a refusal is honest, but it is not a confident answer to the question
|
|
61
|
+
const refusal = REFUSALS.find((r) => lower.includes(r));
|
|
62
|
+
if (refusal) penalise('refusal', 0.3, `declined with "${refusal}"`);
|
|
63
|
+
|
|
64
|
+
// 4. hedging: count distinct hedge phrases, capped
|
|
65
|
+
const hedges = HEDGES.filter((h) => lower.includes(h));
|
|
66
|
+
if (hedges.length) {
|
|
67
|
+
penalise('hedging', Math.min(0.4, 0.12 * hedges.length), `${hedges.length} hedge phrase(s): ${hedges.slice(0, 3).join(', ')}`);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// 5. repetition: the same sentence twice is a sign of a loop
|
|
71
|
+
const sentences = trimmed.split(/(?<=[.!?])\s+/).map((s) => s.trim().toLowerCase()).filter((s) => s.length > 20);
|
|
72
|
+
const dupes = sentences.length - new Set(sentences).size;
|
|
73
|
+
if (dupes > 0) penalise('repetition', Math.min(0.3, 0.15 * dupes), `${dupes} repeated sentence(s)`);
|
|
74
|
+
if (LOOP_MARKERS.some((m) => lower.includes(m))) penalise('looping', 0.15, 'the answer refers back to itself');
|
|
75
|
+
|
|
76
|
+
// 6. shape: JSON was asked for, prose came back
|
|
77
|
+
if (input.wantsJson) {
|
|
78
|
+
const fenced = trimmed.match(/```(?:json)?\s*([\s\S]*?)```/);
|
|
79
|
+
const body = (fenced ? fenced[1] : trimmed).trim();
|
|
80
|
+
let isJson = false;
|
|
81
|
+
try {
|
|
82
|
+
const parsed = JSON.parse(body);
|
|
83
|
+
isJson = typeof parsed === 'object' && parsed !== null;
|
|
84
|
+
} catch {
|
|
85
|
+
isJson = false;
|
|
86
|
+
}
|
|
87
|
+
if (!isJson) penalise('wrong_shape', 0.4, 'JSON was requested and the answer is not JSON');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// 7. relevance: does the answer share any content words with the question?
|
|
91
|
+
if (prompt) {
|
|
92
|
+
const overlap = contentOverlap(prompt, trimmed);
|
|
93
|
+
if (overlap < 0.08) penalise('off_topic', 0.25, `only ${Math.round(overlap * 100)}% of the answer's terms come from the question`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const total = reasons.reduce((a, r) => a + r.penalty, 0);
|
|
97
|
+
const confidence = Math.max(0, Math.round((1 - Math.min(1, total)) * 100) / 100);
|
|
98
|
+
return { confidence, reasons };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function contentOverlap(prompt, answer) {
|
|
102
|
+
const stop = new Set('a an the and or but if then than that this these those is are was were be been of to in on at by for with from as it its we you they he she i not no do does did have has had will would can could should may might must just very really'.split(' '));
|
|
103
|
+
const terms = (s) =>
|
|
104
|
+
new Set(
|
|
105
|
+
String(s)
|
|
106
|
+
.toLowerCase()
|
|
107
|
+
.split(/[^a-z0-9']+/)
|
|
108
|
+
.filter((w) => w.length > 3 && !stop.has(w)),
|
|
109
|
+
);
|
|
110
|
+
const q = terms(prompt);
|
|
111
|
+
const a = terms(answer);
|
|
112
|
+
if (!a.size) return 0;
|
|
113
|
+
let hit = 0;
|
|
114
|
+
for (const t of a) if (q.has(t)) hit += 1;
|
|
115
|
+
return hit / a.size;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* B7.6 — the grounding check.
|
|
120
|
+
*
|
|
121
|
+
* An answer that cites a URL, quotes a sentence or states a number that is not in
|
|
122
|
+
* the context it was given is not grounded: it is plausible. Three checks, all
|
|
123
|
+
* deterministic, all pointable at:
|
|
124
|
+
*
|
|
125
|
+
* url every URL in the answer must appear in the context
|
|
126
|
+
* quote every quoted span of 8+ characters must appear in the context
|
|
127
|
+
* number every money, percentage, year or unit-bearing number must appear
|
|
128
|
+
*
|
|
129
|
+
* When there is no context, there is nothing to ground against and the check
|
|
130
|
+
* says so rather than passing the answer by default.
|
|
131
|
+
*
|
|
132
|
+
* @param {{answer: string, context: string}} input
|
|
133
|
+
* @returns {{checked: boolean, supported: boolean, findings: Array<{kind: string, claim: string}>}}
|
|
134
|
+
*/
|
|
135
|
+
export function checkGrounding(input) {
|
|
136
|
+
const answer = String(input.answer ?? '');
|
|
137
|
+
const context = normalise(input.context ?? '');
|
|
138
|
+
|
|
139
|
+
if (!context.trim()) {
|
|
140
|
+
return { checked: false, supported: true, findings: [] };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const findings = [];
|
|
144
|
+
const inContext = (needle) => context.includes(normalise(needle));
|
|
145
|
+
|
|
146
|
+
// 1. URLs
|
|
147
|
+
for (const raw of answer.match(/https?:\/\/[^\s<>"')]+/g) ?? []) {
|
|
148
|
+
// a URL followed by a comma is a URL and a comma, not a different URL
|
|
149
|
+
const url = raw.replace(/[.,;:]+$/, '');
|
|
150
|
+
if (!inContext(url)) findings.push({ kind: 'url', claim: url });
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// 2. quoted spans — a quote that is not in the source is a fabricated quote
|
|
154
|
+
for (const m of answer.matchAll(/["“']([^"”']{8,200})["”']/g)) {
|
|
155
|
+
const quote = m[1].trim();
|
|
156
|
+
if (!inContext(quote)) findings.push({ kind: 'quote', claim: quote });
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// 3. numbers that carry a unit or a currency, plus years
|
|
160
|
+
const numberPatterns = [
|
|
161
|
+
/\$\s?\d[\d,.]*(?:\s?(?:k|m|b|bn|million|billion))?/gi,
|
|
162
|
+
/\b\d[\d,.]*\s?%/g,
|
|
163
|
+
/\b(?:19|20)\d{2}\b/g,
|
|
164
|
+
/\b\d[\d,.]*\s?(?:ms|s|sec|seconds|minutes|hours|days|tokens?|chars?|requests?)\b/gi,
|
|
165
|
+
];
|
|
166
|
+
const seen = new Set();
|
|
167
|
+
for (const pattern of numberPatterns) {
|
|
168
|
+
for (const m of answer.matchAll(pattern)) {
|
|
169
|
+
const claim = m[0].trim();
|
|
170
|
+
if (seen.has(claim.toLowerCase())) continue;
|
|
171
|
+
seen.add(claim.toLowerCase());
|
|
172
|
+
// a year or a number with no context match is the classic hallucination
|
|
173
|
+
if (!inContext(claim) && !inContext(claim.replace(/[\s,]/g, ''))) {
|
|
174
|
+
findings.push({ kind: 'number', claim });
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return { checked: true, supported: findings.length === 0, findings };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function normalise(text) {
|
|
183
|
+
return String(text).replace(/\s+/g, ' ').toLowerCase();
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Should this answer be escalated to a stronger target?
|
|
188
|
+
*
|
|
189
|
+
* @param {{confidence: number, threshold?: number, escalationsLeft?: number}} input
|
|
190
|
+
*/
|
|
191
|
+
export function shouldEscalate(input) {
|
|
192
|
+
const threshold = input.threshold ?? DEFAULT_THRESHOLD;
|
|
193
|
+
if ((input.escalationsLeft ?? 1) <= 0) return false;
|
|
194
|
+
return input.confidence < threshold;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Fail-closed verdict: an answer below the threshold may still be returned (the
|
|
199
|
+
* user asked a question and half an answer beats none), but it must never be
|
|
200
|
+
* presented as a verified one.
|
|
201
|
+
*
|
|
202
|
+
* @param {{confidence: number, threshold?: number, reasons: any[]}} input
|
|
203
|
+
*/
|
|
204
|
+
export function verdict(input) {
|
|
205
|
+
const threshold = input.threshold ?? DEFAULT_THRESHOLD;
|
|
206
|
+
const ok = input.confidence >= threshold;
|
|
207
|
+
return {
|
|
208
|
+
ok,
|
|
209
|
+
confidence: input.confidence,
|
|
210
|
+
threshold,
|
|
211
|
+
// Fail-closed means the default assumption is "not verified".
|
|
212
|
+
verified: ok,
|
|
213
|
+
summary: ok
|
|
214
|
+
? `confidence ${input.confidence} clears the ${threshold} threshold`
|
|
215
|
+
: `confidence ${input.confidence} is below the ${threshold} threshold: ${input.reasons.map((r) => r.detail).join('; ') || 'no detail'}`,
|
|
216
|
+
};
|
|
217
|
+
}
|
package/README.md
DELETED