veriquote 0.2.1 → 0.3.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/CITATION.cff +2 -2
- package/README.md +102 -51
- package/dist/cli/main.d.ts.map +1 -1
- package/dist/cli/main.js +42 -5
- package/dist/cli/main.js.map +1 -1
- package/dist/gate.d.ts +13 -3
- package/dist/gate.d.ts.map +1 -1
- package/dist/gate.js +20 -2
- package/dist/gate.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/match/fuzzy.d.ts +10 -2
- package/dist/match/fuzzy.d.ts.map +1 -1
- package/dist/match/fuzzy.js +87 -11
- package/dist/match/fuzzy.js.map +1 -1
- package/dist/protocol/evi1.d.ts +21 -1
- package/dist/protocol/evi1.d.ts.map +1 -1
- package/dist/protocol/evi1.js +169 -28
- package/dist/protocol/evi1.js.map +1 -1
- package/dist/protocol/prompt.d.ts +6 -0
- package/dist/protocol/prompt.d.ts.map +1 -1
- package/dist/protocol/prompt.js +35 -10
- package/dist/protocol/prompt.js.map +1 -1
- package/dist/report.d.ts.map +1 -1
- package/dist/report.js +52 -15
- package/dist/report.js.map +1 -1
- package/dist/source/html.d.ts.map +1 -1
- package/dist/source/html.js +3 -0
- package/dist/source/html.js.map +1 -1
- package/dist/types.d.ts +23 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/cli/main.ts +41 -6
- package/src/gate.ts +30 -5
- package/src/index.ts +1 -0
- package/src/match/fuzzy.ts +98 -11
- package/src/protocol/evi1.ts +174 -29
- package/src/protocol/prompt.ts +42 -9
- package/src/report.ts +53 -21
- package/src/source/html.ts +3 -0
- package/src/types.ts +20 -2
package/src/match/fuzzy.ts
CHANGED
|
@@ -3,8 +3,11 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Strategy, in order of preference:
|
|
5
5
|
* 1. exact raw substring,
|
|
6
|
-
* 2. exact substring after normalization (quotes, dashes, case, whitespace
|
|
7
|
-
*
|
|
6
|
+
* 2. exact substring after normalization (quotes, dashes, case, whitespace,
|
|
7
|
+
* an ellipsis at either end),
|
|
8
|
+
* 3. elided: the fragments around inner ellipses occur literally, in order,
|
|
9
|
+
* with at most `maxElisionGap` characters left out between them,
|
|
10
|
+
* 4. best sliding window by character-trigram Dice similarity, with a
|
|
8
11
|
* coarse scan followed by a fine refinement around the best offset.
|
|
9
12
|
*
|
|
10
13
|
* Everything here is pure and deterministic: same inputs, same result.
|
|
@@ -25,6 +28,11 @@ export interface MatchOptions {
|
|
|
25
28
|
fuzzyThreshold?: number;
|
|
26
29
|
/** Window sizes to try, as multiples of the quote length. Default [0.85, 1, 1.15]. */
|
|
27
30
|
windowScales?: number[];
|
|
31
|
+
/**
|
|
32
|
+
* Most (normalized) characters one ellipsis may stand for. Fragments further
|
|
33
|
+
* apart are separate passages, not one elided quote. Default 300.
|
|
34
|
+
*/
|
|
35
|
+
maxElisionGap?: number;
|
|
28
36
|
}
|
|
29
37
|
|
|
30
38
|
const DEFAULTS: Required<MatchOptions> = {
|
|
@@ -32,8 +40,43 @@ const DEFAULTS: Required<MatchOptions> = {
|
|
|
32
40
|
shortQuoteLength: 90,
|
|
33
41
|
fuzzyThreshold: 0.4,
|
|
34
42
|
windowScales: [0.85, 1, 1.15],
|
|
43
|
+
maxElisionGap: 300,
|
|
35
44
|
};
|
|
36
45
|
|
|
46
|
+
/** "...", "…" (NFKC turns it into "..."), "[...]", "(...)", ". . ." — in normalized text. */
|
|
47
|
+
const ELLIPSIS = /\s*(?:\[\s*\.(?:\s?\.){2,}\s*\]|\(\s*\.(?:\s?\.){2,}\s*\)|\.(?:\s?\.){2,})\s*/g;
|
|
48
|
+
/** An elided quote needs one fragment at least this long to anchor it. */
|
|
49
|
+
const MIN_ELISION_ANCHOR = 20;
|
|
50
|
+
/** Elided matches rank just below literal ones. */
|
|
51
|
+
const ELIDED_SCORE = 0.99;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Words that reverse, limit or qualify a statement, in English and German.
|
|
55
|
+
* Found in the text an ellipsis leaves out, they make the elision worth a
|
|
56
|
+
* second look: "the landlord is … permitted to terminate" may have dropped
|
|
57
|
+
* a "not".
|
|
58
|
+
*/
|
|
59
|
+
const CUE_WORDS = [
|
|
60
|
+
// negation
|
|
61
|
+
'not', 'no', 'never', 'none', 'neither', 'nor', 'without', 'cannot', 'nothing', 'nobody',
|
|
62
|
+
'nicht', 'kein', 'keine', 'keinen', 'keinem', 'keiner', 'keines', 'nie', 'niemals', 'weder', 'ohne',
|
|
63
|
+
// exception, condition, limitation
|
|
64
|
+
'except', 'unless', 'excluding', 'only', 'außer', 'ausser', 'ausgenommen', 'sofern', 'nur',
|
|
65
|
+
// contrast
|
|
66
|
+
'but', 'however', 'although', 'though', 'whereas', 'despite',
|
|
67
|
+
'aber', 'jedoch', 'obwohl', 'allerdings', 'trotz',
|
|
68
|
+
];
|
|
69
|
+
const CUE = new RegExp(`(?<![\\p{L}\\p{N}])(?:${CUE_WORDS.join('|')})(?![\\p{L}\\p{N}])|(?<=\\p{L})n't(?!\\p{L})`, 'gu');
|
|
70
|
+
|
|
71
|
+
/** Cue words in the given ranges of normalized text, deduplicated, in order of appearance. */
|
|
72
|
+
function cuesIn(text: string, ranges: Array<[number, number]>): string[] {
|
|
73
|
+
const found = new Set<string>();
|
|
74
|
+
for (const [from, to] of ranges) {
|
|
75
|
+
for (const m of text.slice(from, to).matchAll(CUE)) found.add(m[0]);
|
|
76
|
+
}
|
|
77
|
+
return [...found];
|
|
78
|
+
}
|
|
79
|
+
|
|
37
80
|
/** Multiset of character trigrams of `s` as gram -> count. */
|
|
38
81
|
export function trigramCounts(s: string): Map<string, number> {
|
|
39
82
|
const out = new Map<string, number>();
|
|
@@ -192,15 +235,31 @@ export function matchQuoteAgainstText(
|
|
|
192
235
|
const t = normalizeForMatch(text);
|
|
193
236
|
if (!q.text || !t.text) return empty;
|
|
194
237
|
|
|
195
|
-
const
|
|
196
|
-
if (
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
238
|
+
const fragments = q.text.split(ELLIPSIS).filter(Boolean);
|
|
239
|
+
if (fragments.length === 1) {
|
|
240
|
+
const normIndex = t.text.indexOf(fragments[0]);
|
|
241
|
+
if (normIndex !== -1) {
|
|
242
|
+
return {
|
|
243
|
+
method: 'normalized',
|
|
244
|
+
score: 1,
|
|
245
|
+
start: t.map[normIndex],
|
|
246
|
+
end: mapEndOffset(t.map, normIndex + fragments[0].length - 1, text),
|
|
247
|
+
field: 'text',
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
} else if (fragments.some((f) => f.length >= MIN_ELISION_ANCHOR)) {
|
|
251
|
+
const span = findElided(fragments, t.text, opts.maxElisionGap);
|
|
252
|
+
if (span) {
|
|
253
|
+
const cues = cuesIn(t.text, span.gaps);
|
|
254
|
+
return {
|
|
255
|
+
method: 'elided',
|
|
256
|
+
score: ELIDED_SCORE,
|
|
257
|
+
start: t.map[span.start],
|
|
258
|
+
end: mapEndOffset(t.map, span.end - 1, text),
|
|
259
|
+
field: 'text',
|
|
260
|
+
...(cues.length ? { omittedCues: cues } : {}),
|
|
261
|
+
};
|
|
262
|
+
}
|
|
204
263
|
}
|
|
205
264
|
|
|
206
265
|
const hit = bestFuzzyWindow(q.text, t.text, opts.windowScales);
|
|
@@ -219,6 +278,34 @@ export function matchQuoteAgainstText(
|
|
|
219
278
|
};
|
|
220
279
|
}
|
|
221
280
|
|
|
281
|
+
interface ElidedSpan {
|
|
282
|
+
start: number;
|
|
283
|
+
end: number;
|
|
284
|
+
/** The omitted stretches between fragments, as [from, to) in `text`. */
|
|
285
|
+
gaps: Array<[number, number]>;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* First span of `text` holding every fragment literally, in order, with gaps of
|
|
290
|
+
* at most `maxGap`; offsets refer to `text`. Null if there is none.
|
|
291
|
+
*/
|
|
292
|
+
function findElided(fragments: string[], text: string, maxGap: number): ElidedSpan | null {
|
|
293
|
+
for (let first = text.indexOf(fragments[0]); first !== -1; first = text.indexOf(fragments[0], first + 1)) {
|
|
294
|
+
let end = first + fragments[0].length;
|
|
295
|
+
const gaps: Array<[number, number]> = [];
|
|
296
|
+
for (const fragment of fragments.slice(1)) {
|
|
297
|
+
// The earliest occurrence leaves the most room for the fragments after it.
|
|
298
|
+
const at = text.indexOf(fragment, end);
|
|
299
|
+
if (at === -1) return null;
|
|
300
|
+
if (at - end > maxGap) break;
|
|
301
|
+
gaps.push([end, at]);
|
|
302
|
+
end = at + fragment.length;
|
|
303
|
+
}
|
|
304
|
+
if (gaps.length === fragments.length - 1) return { start: first, end, gaps };
|
|
305
|
+
}
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
|
|
222
309
|
/** Exclusive end offset in the original text for the normalized char at `lastIndex`. */
|
|
223
310
|
function mapEndOffset(map: Int32Array, lastIndex: number, original: string): number {
|
|
224
311
|
const srcIndex = map[Math.max(0, Math.min(lastIndex, map.length - 1))];
|
package/src/protocol/evi1.ts
CHANGED
|
@@ -11,7 +11,14 @@
|
|
|
11
11
|
* c1|5|"verbatim quote from source 5"
|
|
12
12
|
* END_EVI1
|
|
13
13
|
*
|
|
14
|
+
* A (claim, source) pair may have several lines when one passage does not
|
|
15
|
+
* cover the whole claim. With `evidenceFirst` prompting the block comes
|
|
16
|
+
* before the answer instead; the parser accepts either position.
|
|
17
|
+
*
|
|
14
18
|
* Quotes are single-line, with `\n`, `\"` and `\\` escapes.
|
|
19
|
+
*
|
|
20
|
+
* The parser is lenient about how the appendix is framed (see
|
|
21
|
+
* `parseEvi1Appendix`), strict about the evidence lines themselves.
|
|
15
22
|
*/
|
|
16
23
|
|
|
17
24
|
import type { Claim, EvidenceItem, ParsedAnswer } from '../types.js';
|
|
@@ -20,10 +27,25 @@ import { collapseWhitespace } from '../match/normalize.js';
|
|
|
20
27
|
export const EVI1_START = 'EVI1';
|
|
21
28
|
export const EVI1_END = 'END_EVI1';
|
|
22
29
|
|
|
23
|
-
const EVIDENCE_LINE = /^(c\d+)
|
|
30
|
+
const EVIDENCE_LINE = /^(c\d+)\s*\|\s*(\d+)\s*\|\s*"([\s\S]*)"$/;
|
|
24
31
|
const CLAIM_MARKER = /\{c(\d+)\}/g;
|
|
25
32
|
const CITATION_GROUP_BEFORE_CLAIM = /((?:\[\d+\])+)$/;
|
|
26
33
|
|
|
34
|
+
// Models and gateways garble the appendix slightly: "**EVI1**", "EVI1:",
|
|
35
|
+
// "EVI1 c1|2|...", a code fence around it, END_EVI11 or no END_EVI1 at all.
|
|
36
|
+
// The lookahead keeps a sentence about the EVI1 gene from opening an appendix.
|
|
37
|
+
const START_LINE = /^[\s*_`>#]*EVI1[\s*_`:]*(?=$|c\d+\s*\|)/;
|
|
38
|
+
const END_LINE = /^[\s*_`]*END_EVI1/;
|
|
39
|
+
const EVIDENCE_PREFIX = /^\s*c\d+\s*\|\s*\d+\s*\|/;
|
|
40
|
+
// Without END_EVI1, the appendix runs as long as lines look like evidence,
|
|
41
|
+
// malformed ones included (they get a warning, not the answer body).
|
|
42
|
+
const EVIDENCE_LIKE = /^\s*c\d+\s*\|/;
|
|
43
|
+
const FENCE_LINE = /^\s*```\s*\w*\s*$/;
|
|
44
|
+
// While streaming, the last line may be the beginning of an EVI1, evidence or END_EVI1 line.
|
|
45
|
+
const PARTIAL_START =
|
|
46
|
+
/^[\s*_`>#]*(?:E(?:V(?:I(?:1[\s*_`:]*(?:c\d*)?)?)?)?)?$|^[\s*_`]*EN(?:D(?:_(?:E(?:V(?:I1?)?)?)?)?)?$|^\s*c\d*(?:\s*\|\s*\d*)?\s*$/;
|
|
47
|
+
const PARTIAL_MARKER = /\{(?:c\d*)?$/;
|
|
48
|
+
|
|
27
49
|
/** Unescape an EVI1 quote payload (`\\`, `\n`, `\"`) in a single pass. */
|
|
28
50
|
function unescapeQuote(s: string): string {
|
|
29
51
|
return s.replace(/\\(.)/g, (_, c: string) => (c === 'n' ? '\n' : c));
|
|
@@ -35,41 +57,110 @@ function escapeQuote(s: string): string {
|
|
|
35
57
|
}
|
|
36
58
|
|
|
37
59
|
interface AppendixLocation {
|
|
38
|
-
/**
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
|
|
60
|
+
/** First line to cut: the EVI1 line (or first evidence line), or a fence opened just before it. */
|
|
61
|
+
cutStart: number;
|
|
62
|
+
/**
|
|
63
|
+
* First line after the appendix: past END_EVI1 and a closing fence, or,
|
|
64
|
+
* without END_EVI1, the first line that is not evidence (an answer after an
|
|
65
|
+
* evidence-first block), else `lines.length`.
|
|
66
|
+
*/
|
|
67
|
+
cutEnd: number;
|
|
68
|
+
/** Candidate evidence lines, the text after an inline `EVI1` header included. */
|
|
69
|
+
body: string[];
|
|
42
70
|
}
|
|
43
71
|
|
|
44
|
-
|
|
72
|
+
const isBlank = (line: string) => !line.trim();
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Whether the EVI1 line at `start` really opens the appendix: the next
|
|
76
|
+
* non-blank line is evidence, or END_EVI1 follows somewhere.
|
|
77
|
+
* A heading "## EVI1" followed by prose does not.
|
|
78
|
+
*/
|
|
79
|
+
function opensAppendix(lines: string[], start: number): boolean {
|
|
80
|
+
if (lines[start].replace(START_LINE, '').trim()) return true; // "EVI1 c1|…"
|
|
81
|
+
let i = start + 1;
|
|
82
|
+
while (i < lines.length && (isBlank(lines[i]) || FENCE_LINE.test(lines[i]))) i++;
|
|
83
|
+
if (EVIDENCE_PREFIX.test(lines[i] ?? '')) return true;
|
|
84
|
+
return lines.slice(i).some((l) => END_LINE.test(l));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Start of the appendix: the last EVI1 line, or else a run of evidence lines
|
|
89
|
+
* that ends the text. -1 if there is none.
|
|
90
|
+
*/
|
|
91
|
+
function findAppendixStart(lines: string[]): number {
|
|
45
92
|
// Scan from the end so answer text that merely mentions "EVI1" is ignored.
|
|
46
|
-
for (let
|
|
47
|
-
if (lines[
|
|
48
|
-
|
|
49
|
-
|
|
93
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
94
|
+
if (START_LINE.test(lines[i]) && opensAppendix(lines, i)) return i;
|
|
95
|
+
}
|
|
96
|
+
let i = lines.length - 1;
|
|
97
|
+
while (i >= 0 && (isBlank(lines[i]) || END_LINE.test(lines[i]) || FENCE_LINE.test(lines[i]))) i--;
|
|
98
|
+
const last = i;
|
|
99
|
+
while (i >= 0 && EVIDENCE_PREFIX.test(lines[i])) i--;
|
|
100
|
+
return i < last ? i + 1 : -1;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function locateAppendix(lines: string[]): AppendixLocation | null {
|
|
104
|
+
const start = findAppendixStart(lines);
|
|
105
|
+
if (start < 0) return null;
|
|
106
|
+
|
|
107
|
+
const headerRest = lines[start].replace(START_LINE, '');
|
|
108
|
+
let endLine = END_LINE.test(headerRest) ? start : -1;
|
|
109
|
+
for (let i = start + 1; endLine < 0 && i < lines.length; i++) {
|
|
110
|
+
if (END_LINE.test(lines[i])) endLine = i;
|
|
111
|
+
}
|
|
112
|
+
let stop = endLine >= 0 ? endLine : start + 1;
|
|
113
|
+
if (endLine < 0) {
|
|
114
|
+
while (stop < lines.length && (isBlank(lines[stop]) || FENCE_LINE.test(lines[stop]) || EVIDENCE_LIKE.test(lines[stop]))) stop++;
|
|
115
|
+
// Blank lines before the answer that follows belong to the answer.
|
|
116
|
+
if (stop < lines.length) while (stop > start + 1 && isBlank(lines[stop - 1])) stop--;
|
|
117
|
+
}
|
|
118
|
+
const body = endLine === start ? [] : [headerRest, ...lines.slice(start + 1, stop)];
|
|
119
|
+
|
|
120
|
+
// A fence the model opened around the appendix goes with it, but not one
|
|
121
|
+
// that closes an earlier code block.
|
|
122
|
+
let cutStart = start;
|
|
123
|
+
let openedFence = /^\s*```/.test(lines[start]);
|
|
124
|
+
let before = start - 1;
|
|
125
|
+
while (before >= 0 && isBlank(lines[before])) before--;
|
|
126
|
+
if (!openedFence && before >= 0 && FENCE_LINE.test(lines[before])) {
|
|
127
|
+
const fences = lines.slice(0, before + 1).filter((l) => FENCE_LINE.test(l)).length;
|
|
128
|
+
if (fences % 2 === 1) {
|
|
129
|
+
cutStart = before;
|
|
130
|
+
openedFence = true;
|
|
50
131
|
}
|
|
51
|
-
return null;
|
|
52
132
|
}
|
|
53
|
-
|
|
133
|
+
|
|
134
|
+
let cutEnd = endLine < 0 ? stop : endLine + 1;
|
|
135
|
+
if (openedFence && endLine >= 0 && !/```/.test(lines[endLine])) {
|
|
136
|
+
let after = cutEnd;
|
|
137
|
+
while (after < lines.length && isBlank(lines[after])) after++;
|
|
138
|
+
if (after < lines.length && FENCE_LINE.test(lines[after])) cutEnd = after + 1;
|
|
139
|
+
}
|
|
140
|
+
return { cutStart, cutEnd, body };
|
|
54
141
|
}
|
|
55
142
|
|
|
56
143
|
/**
|
|
57
144
|
* Parse the EVI1 appendix of a raw model answer.
|
|
58
145
|
* Returns the evidence items plus warnings for malformed lines;
|
|
59
|
-
* `null` when no
|
|
146
|
+
* `null` when no appendix is present.
|
|
147
|
+
*
|
|
148
|
+
* Tolerant of common deviations: a decorated start line (`**EVI1**`,
|
|
149
|
+
* `EVI1:`, `EVI1 c1|…`), a code fence around the appendix, a missing or
|
|
150
|
+
* garbled `END_EVI1`, and a missing `EVI1` line when the answer ends in
|
|
151
|
+
* evidence lines.
|
|
60
152
|
*/
|
|
61
153
|
export function parseEvi1Appendix(
|
|
62
154
|
answer: string,
|
|
63
155
|
): { items: EvidenceItem[]; warnings: string[] } | null {
|
|
64
|
-
const
|
|
65
|
-
const loc = locateAppendix(lines);
|
|
156
|
+
const loc = locateAppendix(String(answer).split('\n'));
|
|
66
157
|
if (!loc) return null;
|
|
67
158
|
|
|
68
159
|
const items: EvidenceItem[] = [];
|
|
69
160
|
const warnings: string[] = [];
|
|
70
|
-
for (
|
|
71
|
-
const line =
|
|
72
|
-
if (!line) continue;
|
|
161
|
+
for (const raw of loc.body) {
|
|
162
|
+
const line = raw.trim();
|
|
163
|
+
if (!line || FENCE_LINE.test(line)) continue;
|
|
73
164
|
const m = line.match(EVIDENCE_LINE);
|
|
74
165
|
if (!m) {
|
|
75
166
|
warnings.push(`EVI1: malformed evidence line ignored: ${truncate(line, 80)}`);
|
|
@@ -85,16 +176,51 @@ export function parseEvi1Appendix(
|
|
|
85
176
|
return { items, warnings };
|
|
86
177
|
}
|
|
87
178
|
|
|
179
|
+
function cutAppendix(lines: string[], loc: AppendixLocation): string {
|
|
180
|
+
const head = lines.slice(0, loc.cutStart);
|
|
181
|
+
const tail = lines.slice(loc.cutEnd);
|
|
182
|
+
// An evidence-first block leaves blank lines before the answer.
|
|
183
|
+
if (head.every(isBlank)) {
|
|
184
|
+
head.length = 0;
|
|
185
|
+
while (tail.length && isBlank(tail[0])) tail.shift();
|
|
186
|
+
}
|
|
187
|
+
return head.concat(tail).join('\n').trimEnd();
|
|
188
|
+
}
|
|
189
|
+
|
|
88
190
|
/** Remove the EVI1 appendix from a raw answer; returns the answer body. */
|
|
89
191
|
export function stripEvi1Appendix(answer: string): string {
|
|
90
192
|
const lines = String(answer).split('\n');
|
|
91
193
|
const loc = locateAppendix(lines);
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
194
|
+
return loc ? cutAppendix(lines, loc) : answer;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Whether the last line may be the beginning of an appendix (but not a fence closing a code block). */
|
|
198
|
+
function isPartialStart(lines: string[]): boolean {
|
|
199
|
+
const last = lines[lines.length - 1];
|
|
200
|
+
if (isBlank(last) || !PARTIAL_START.test(last)) return false;
|
|
201
|
+
return !/```/.test(last) || lines.filter((l) => /^\s*```/.test(l)).length % 2 === 1;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* The answer as a reader should see it, also while it is still streaming:
|
|
206
|
+
* the appendix (complete or not) is cut, as is a last line that may be the
|
|
207
|
+
* beginning of one (`E`, `EV`, `EVI`, `EVI1`, `c1|…`), and all `{cX}`
|
|
208
|
+
* markers are removed, including a half-streamed `{c…` at the end.
|
|
209
|
+
* `[n]` citation markers are kept.
|
|
210
|
+
*/
|
|
211
|
+
export function stripForDisplay(text: string): string {
|
|
212
|
+
let lines = String(text).split('\n');
|
|
213
|
+
const popBlank = () => {
|
|
214
|
+
while (lines.length && isBlank(lines[lines.length - 1])) lines.pop();
|
|
215
|
+
};
|
|
216
|
+
popBlank();
|
|
217
|
+
while (lines.length && isPartialStart(lines)) {
|
|
218
|
+
lines.pop();
|
|
219
|
+
popBlank();
|
|
220
|
+
}
|
|
221
|
+
const loc = locateAppendix(lines);
|
|
222
|
+
if (loc) lines = cutAppendix(lines, loc).split('\n');
|
|
223
|
+
return stripClaimMarkers(lines.join('\n').replace(PARTIAL_MARKER, '')).trimEnd();
|
|
98
224
|
}
|
|
99
225
|
|
|
100
226
|
/** Serialize evidence items into an EVI1 appendix block. */
|
|
@@ -173,24 +299,43 @@ export function parseAnswer(answer: string): ParsedAnswer {
|
|
|
173
299
|
|
|
174
300
|
const body = stripEvi1Appendix(answer);
|
|
175
301
|
const { claims, warnings: claimWarnings } = extractClaims(body);
|
|
176
|
-
|
|
302
|
+
// A claim marker without its [n] group still names its sources in the
|
|
303
|
+
// appendix; take them from there instead of losing the claim's evidence.
|
|
304
|
+
const noGroup = new Set<string>();
|
|
305
|
+
for (const c of claims) {
|
|
306
|
+
if (c.sourceIndexes.length) continue;
|
|
307
|
+
const fromAppendix = [...new Set(evidence.filter((e) => e.claimId === c.id).map((e) => e.sourceIndex))];
|
|
308
|
+
if (!fromAppendix.length) continue;
|
|
309
|
+
c.sourceIndexes = fromAppendix;
|
|
310
|
+
noGroup.add(`Claim ${c.id}: no citation group directly before marker.`);
|
|
311
|
+
}
|
|
312
|
+
warnings.push(
|
|
313
|
+
...claimWarnings.map((w) =>
|
|
314
|
+
noGroup.has(w) ? w.replace(/\.$/, '; sources taken from the EVI1 appendix.') : w,
|
|
315
|
+
),
|
|
316
|
+
);
|
|
177
317
|
|
|
178
318
|
const cited = new Set(
|
|
179
319
|
claims.flatMap((c) => c.sourceIndexes.map((n) => `${c.id}|${n}`)),
|
|
180
320
|
);
|
|
321
|
+
// Several lines for one (claim, source) pair are allowed: a claim may need
|
|
322
|
+
// two passages of the same source. Only repeated quotes are dropped.
|
|
181
323
|
const evidenced = new Set<string>();
|
|
324
|
+
const seenLines = new Set<string>();
|
|
182
325
|
const dedupedEvidence: typeof evidence = [];
|
|
183
326
|
for (const it of evidence) {
|
|
184
327
|
const key = `${it.claimId}|${it.sourceIndex}`;
|
|
185
|
-
|
|
186
|
-
|
|
328
|
+
const line = `${key}|${collapseWhitespace(it.quote)}`;
|
|
329
|
+
if (seenLines.has(line)) {
|
|
330
|
+
warnings.push(`EVI1: repeated quote for ${key}; keeping first occurrence.`);
|
|
187
331
|
continue;
|
|
188
332
|
}
|
|
189
|
-
|
|
333
|
+
seenLines.add(line);
|
|
190
334
|
dedupedEvidence.push(it);
|
|
191
|
-
if (!cited.has(key)) {
|
|
335
|
+
if (!evidenced.has(key) && !cited.has(key)) {
|
|
192
336
|
warnings.push(`EVI1: evidence for ${key} has no matching citation in the answer.`);
|
|
193
337
|
}
|
|
338
|
+
evidenced.add(key);
|
|
194
339
|
}
|
|
195
340
|
for (const key of cited) {
|
|
196
341
|
if (!evidenced.has(key)) {
|
package/src/protocol/prompt.ts
CHANGED
|
@@ -13,6 +13,12 @@ export interface CitationPromptOptions {
|
|
|
13
13
|
quoteLengthRange?: [number, number];
|
|
14
14
|
/** Minimum quote length in characters (with stated exceptions). Default 60. */
|
|
15
15
|
minQuoteLength?: number;
|
|
16
|
+
/**
|
|
17
|
+
* Put the EVI1 block before the answer: the model selects its passages
|
|
18
|
+
* first, then writes only what they support. The parser accepts either
|
|
19
|
+
* position; a streaming client shows nothing until END_EVI1. Default false.
|
|
20
|
+
*/
|
|
21
|
+
evidenceFirst?: boolean;
|
|
16
22
|
}
|
|
17
23
|
|
|
18
24
|
/** Build the EVI1 citation instruction block for the answering model. */
|
|
@@ -22,8 +28,25 @@ export function buildCitationInstructions(options: CitationPromptOptions = {}):
|
|
|
22
28
|
maxCitationsPerClaim = 2,
|
|
23
29
|
quoteLengthRange = [80, 240],
|
|
24
30
|
minQuoteLength = 60,
|
|
31
|
+
evidenceFirst = false,
|
|
25
32
|
} = options;
|
|
26
33
|
|
|
34
|
+
const appendixIntro = evidenceFirst
|
|
35
|
+
? `Before you write the answer, output the evidence block. Select the passages
|
|
36
|
+
you will rely on first, one line per planned claim and source, then write the
|
|
37
|
+
answer so that every cited sentence states only what its lines support.`
|
|
38
|
+
: 'After you finish the answer, append an appendix:';
|
|
39
|
+
const afterBlock = evidenceFirst
|
|
40
|
+
? '- After END_EVI1, write the user-facing answer. The claim ids {cX} in the answer must be the ones used in the block.'
|
|
41
|
+
: '- Do NOT output anything after END_EVI1.';
|
|
42
|
+
const important = evidenceFirst
|
|
43
|
+
? `- The user-facing answer starts AFTER END_EVI1. Nothing but the block comes before it.
|
|
44
|
+
- The block is required only when you use citations. If you use no
|
|
45
|
+
citations, do NOT output EVI1/END_EVI1.`
|
|
46
|
+
: `- The user-facing answer must end BEFORE the EVI1 appendix starts.
|
|
47
|
+
- The appendix is required only when you used citations. If you used no
|
|
48
|
+
citations, do NOT output EVI1/END_EVI1.`;
|
|
49
|
+
|
|
27
50
|
return `
|
|
28
51
|
[CITATION BUDGET]
|
|
29
52
|
- Keep citations sparse. Only cite new, load-bearing information.
|
|
@@ -50,17 +73,20 @@ export function buildCitationInstructions(options: CitationPromptOptions = {}):
|
|
|
50
73
|
Example: "...water expands when freezing.[2][5]{c1}"
|
|
51
74
|
Bad: "...freezing.[2] {c1}"
|
|
52
75
|
Bad: "...freezing.[2].{c1}"
|
|
53
|
-
- Every sentence OR bullet that contains citations MUST end with exactly ONE claim marker {cX}
|
|
76
|
+
- Every sentence OR bullet that contains citations MUST end with exactly ONE claim marker {cX},
|
|
77
|
+
directly after its [n] group. Never write {cX} without the [n] group, even though the
|
|
78
|
+
appendix names the source as well.
|
|
54
79
|
- X starts at 1 and increases by 1 for each new cited sentence/bullet in THIS answer.
|
|
55
80
|
- Do NOT place {cX} anywhere else. Uncited sentences get no claim marker.
|
|
56
81
|
|
|
57
|
-
[QUOTE-BASED EVIDENCE APPENDIX (MANDATORY)]
|
|
58
|
-
|
|
82
|
+
[QUOTE-BASED EVIDENCE ${evidenceFirst ? 'BLOCK' : 'APPENDIX'} (MANDATORY)]
|
|
83
|
+
${appendixIntro}
|
|
59
84
|
- Start with a line containing exactly: EVI1
|
|
60
85
|
- Then output one line per (claim, source) pair in this exact format:
|
|
61
86
|
cX|n|"QUOTE"
|
|
87
|
+
If one passage does not cover the claim, add further lines for the same pair.
|
|
62
88
|
- End with a line containing exactly: END_EVI1
|
|
63
|
-
|
|
89
|
+
${afterBlock}
|
|
64
90
|
- Do NOT wrap EVI1..END_EVI1 in code fences or markdown.
|
|
65
91
|
|
|
66
92
|
[COMPLETENESS RULES (MANDATORY)]
|
|
@@ -71,10 +97,19 @@ After you finish the answer, append an appendix:
|
|
|
71
97
|
- If you cannot provide a verbatim quote for a citation, REMOVE that citation
|
|
72
98
|
from the answer. Never leave a citation unverified.
|
|
73
99
|
|
|
100
|
+
[SUFFICIENCY RULES (MANDATORY)]
|
|
101
|
+
- The quotes of a cited sentence must together contain EVERY detail it states:
|
|
102
|
+
each number, population, time frame, place, condition, comparison and hedge.
|
|
103
|
+
- If one passage does not cover everything, add another line for the same claim
|
|
104
|
+
(same or other cited source). Otherwise remove the unquoted detail from the
|
|
105
|
+
sentence. Never add detail that no quote contains.
|
|
106
|
+
|
|
74
107
|
Rules for QUOTE:
|
|
75
108
|
- QUOTE must be copied verbatim from the provided source TEXT (not paraphrased).
|
|
76
|
-
-
|
|
77
|
-
|
|
109
|
+
- Prefer the shortest quote that still covers its part of the claim
|
|
110
|
+
(typically ${quoteLengthRange[0]}-${quoteLengthRange[1]} characters).
|
|
111
|
+
- Copy one contiguous passage per line. Do NOT shorten a quote with "..." and do
|
|
112
|
+
NOT join separate passages into one quote; write each passage on its own line.
|
|
78
113
|
- QUOTE must be at least ${minQuoteLength} characters unless it contains a numeric result or is
|
|
79
114
|
a complete standalone sentence that uniquely supports the claim.
|
|
80
115
|
- QUOTE must be a single line: escape newlines as \\n and double quotes as \\".
|
|
@@ -92,8 +127,6 @@ Rules for QUOTE:
|
|
|
92
127
|
claim; when only conclusions are visible, use cautious language.
|
|
93
128
|
|
|
94
129
|
IMPORTANT:
|
|
95
|
-
|
|
96
|
-
- The appendix is required only when you used citations. If you used no
|
|
97
|
-
citations, do NOT output EVI1/END_EVI1.
|
|
130
|
+
${important}
|
|
98
131
|
`.trim();
|
|
99
132
|
}
|
package/src/report.ts
CHANGED
|
@@ -40,39 +40,54 @@ export async function verifyAnswer(options: VerifyOptions): Promise<Verification
|
|
|
40
40
|
const warnings = [...parsed.warnings];
|
|
41
41
|
const claimById = new Map(parsed.claims.map((c) => [c.id, c]));
|
|
42
42
|
|
|
43
|
-
|
|
43
|
+
// One citation per (claim, source) pair; a pair may carry several quotes.
|
|
44
|
+
const pairs = new Map<string, { claimId: string; sourceIndex: number; quotes: string[] }>();
|
|
44
45
|
for (const item of parsed.evidence) {
|
|
45
|
-
const
|
|
46
|
-
const
|
|
46
|
+
const key = `${item.claimId}|${item.sourceIndex}`;
|
|
47
|
+
const pair = pairs.get(key) ?? { claimId: item.claimId, sourceIndex: item.sourceIndex, quotes: [] };
|
|
48
|
+
pair.quotes.push(item.quote);
|
|
49
|
+
pairs.set(key, pair);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const citations: CitationVerification[] = [];
|
|
53
|
+
for (const [key, pair] of pairs) {
|
|
54
|
+
const source = sources[pair.sourceIndex - 1];
|
|
47
55
|
if (!source) {
|
|
48
|
-
warnings.push(
|
|
49
|
-
`EVI1: evidence ${item.claimId}|${item.sourceIndex} references a source that was not provided.`,
|
|
50
|
-
);
|
|
56
|
+
warnings.push(`EVI1: evidence ${key} references a source that was not provided.`);
|
|
51
57
|
continue;
|
|
52
58
|
}
|
|
53
|
-
const textMatch:
|
|
59
|
+
const parts = pair.quotes.map((quote) => ({ quote, textMatch: matchQuoteAgainstSource(quote, source, match) }));
|
|
60
|
+
const textMatch = combineMatches(parts.map((p) => p.textMatch));
|
|
61
|
+
for (const cue of textMatch.omittedCues ?? []) {
|
|
62
|
+
warnings.push(`Citation ${key}: the ellipsis in the quote leaves out "${cue}".`);
|
|
63
|
+
}
|
|
54
64
|
citations.push({
|
|
55
|
-
claimId:
|
|
56
|
-
sourceIndex:
|
|
57
|
-
claimText:
|
|
58
|
-
quote:
|
|
65
|
+
claimId: pair.claimId,
|
|
66
|
+
sourceIndex: pair.sourceIndex,
|
|
67
|
+
claimText: claimById.get(pair.claimId)?.text ?? '',
|
|
68
|
+
quote: pair.quotes.join(' […] '),
|
|
59
69
|
textMatch,
|
|
70
|
+
...(parts.length > 1 ? { parts } : {}),
|
|
60
71
|
score: textMatch.score,
|
|
61
72
|
});
|
|
62
73
|
}
|
|
63
74
|
|
|
64
75
|
if (judge) {
|
|
65
76
|
const judgeable = citations.filter((c) => c.claimText && c.quote);
|
|
66
|
-
const inputs: EntailmentInput[] = judgeable.map((c) =>
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
77
|
+
const inputs: EntailmentInput[] = judgeable.map((c) => {
|
|
78
|
+
const source = sources[c.sourceIndex - 1];
|
|
79
|
+
const parts = c.parts ?? [{ quote: c.quote, textMatch: c.textMatch }];
|
|
80
|
+
return {
|
|
81
|
+
id: `${c.claimId}|${c.sourceIndex}`,
|
|
82
|
+
claim: c.claimText,
|
|
83
|
+
// An ellipsis must not hide what it left out (a "not", a qualifier):
|
|
84
|
+
// the judge rates the passage as the source has it.
|
|
85
|
+
quote: parts
|
|
86
|
+
.map((p) => (p.textMatch.method === 'elided' ? matchedText(source, p.textMatch) ?? p.quote : p.quote))
|
|
87
|
+
.join(' […] '),
|
|
88
|
+
context: parts.map((p) => contextWindow(source, p.textMatch, contextWindowChars)).join(' […] '),
|
|
89
|
+
};
|
|
90
|
+
});
|
|
76
91
|
const results = await judge.judge(inputs, { signal });
|
|
77
92
|
if (results.length !== inputs.length) {
|
|
78
93
|
warnings.push(
|
|
@@ -109,6 +124,23 @@ export async function verifyAnswer(options: VerifyOptions): Promise<Verification
|
|
|
109
124
|
};
|
|
110
125
|
}
|
|
111
126
|
|
|
127
|
+
/** Several quotes for one pair count as their weakest match, carrying every cue. */
|
|
128
|
+
function combineMatches(matches: QuoteMatch[]): QuoteMatch {
|
|
129
|
+
if (matches.length === 1) return matches[0];
|
|
130
|
+
const weakest = matches.reduce((a, b) => (b.score < a.score ? b : a));
|
|
131
|
+
const cues = [...new Set(matches.flatMap((m) => m.omittedCues ?? []))];
|
|
132
|
+
const { omittedCues: _, ...rest } = weakest;
|
|
133
|
+
return cues.length ? { ...rest, omittedCues: cues } : rest;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** The matched region of the source field, if its offsets are known. */
|
|
137
|
+
function matchedText(source: SourceDocument | undefined, m: QuoteMatch): string | undefined {
|
|
138
|
+
if (!source || m.start === undefined || m.end === undefined) return undefined;
|
|
139
|
+
const extra = /^extraTexts\[(\d+)\]$/.exec(m.field);
|
|
140
|
+
const text = extra ? source.extraTexts?.[Number(extra[1])] : source.text;
|
|
141
|
+
return text?.slice(m.start, m.end);
|
|
142
|
+
}
|
|
143
|
+
|
|
112
144
|
/** Source text around the matched region, for judge disambiguation. */
|
|
113
145
|
function contextWindow(
|
|
114
146
|
source: SourceDocument | undefined,
|
package/src/source/html.ts
CHANGED
|
@@ -7,6 +7,8 @@
|
|
|
7
7
|
|
|
8
8
|
const DROP_ELEMENTS = /<(script|style|noscript|template|svg|iframe|head|object|canvas)\b[\s\S]*?<\/\1\s*>/gi;
|
|
9
9
|
const COMMENTS = /<!--[\s\S]*?-->/g;
|
|
10
|
+
/** Reference markers such as Wikipedia's [12]: models quoting the page leave them out. */
|
|
11
|
+
const REF_MARKERS = /<sup\b[^>]*class="[^"]*\breference\b[^"]*"[^>]*>[\s\S]*?<\/sup\s*>/gi;
|
|
10
12
|
const BLOCK_TAGS =
|
|
11
13
|
/<\/?(?:p|div|br|hr|li|ul|ol|dl|dt|dd|h[1-6]|tr|table|thead|tbody|tfoot|section|article|aside|main|header|footer|nav|blockquote|pre|figure|figcaption|details|summary|form|fieldset|address)\b[^>]*>/gi;
|
|
12
14
|
const CELL_TAGS = /<\/?(?:td|th)\b[^>]*>/gi;
|
|
@@ -61,6 +63,7 @@ export function htmlMainContent(html: string): string | undefined {
|
|
|
61
63
|
export function htmlToText(html: string): string {
|
|
62
64
|
const text = html
|
|
63
65
|
.replace(COMMENTS, '')
|
|
66
|
+
.replace(REF_MARKERS, '')
|
|
64
67
|
.replace(DROP_ELEMENTS, ' ')
|
|
65
68
|
.replace(BLOCK_TAGS, '\n')
|
|
66
69
|
.replace(CELL_TAGS, ' ')
|