@exulu/backend 5.1.2 → 5.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/dist/{chunk-37MKZIH2.js → chunk-PU3LGCBR.js} +281 -33
- package/dist/{convert-exulu-tools-to-ai-sdk-tools-BNDHJH7B.js → convert-exulu-tools-to-ai-sdk-tools-77FLVHEA.js} +3 -1
- package/dist/index.cjs +2800 -376
- package/dist/index.js +2412 -285
- package/ee/agentic-retrieval/pipeline/config.test.ts +42 -0
- package/ee/agentic-retrieval/pipeline/config.ts +36 -0
- package/ee/agentic-retrieval/pipeline/index.test.ts +3 -3
- package/ee/agentic-retrieval/pipeline/index.ts +43 -1
- package/ee/agentic-retrieval/pipeline/micro-call.test.ts +58 -0
- package/ee/agentic-retrieval/pipeline/micro-call.ts +20 -3
- package/ee/agentic-retrieval/pipeline/near-duplicates.test.ts +50 -0
- package/ee/agentic-retrieval/pipeline/near-duplicates.ts +74 -0
- package/ee/agentic-retrieval/pipeline/prefilter.test.ts +32 -0
- package/ee/agentic-retrieval/pipeline/prefilter.ts +13 -1
- package/ee/agentic-retrieval/pipeline/rerank.test.ts +79 -0
- package/ee/agentic-retrieval/pipeline/rerank.ts +61 -6
- package/ee/claim-check/agent-config.ts +26 -0
- package/ee/claim-check/concurrency.test.ts +33 -0
- package/ee/claim-check/concurrency.ts +30 -0
- package/ee/claim-check/evidence.test.ts +198 -0
- package/ee/claim-check/evidence.ts +162 -0
- package/ee/claim-check/prompts/decompose.ts +52 -0
- package/ee/claim-check/prompts/disambiguate.ts +58 -0
- package/ee/claim-check/prompts/select-disambiguate.ts +17 -0
- package/ee/claim-check/prompts/select.ts +55 -0
- package/ee/claim-check/prompts/shared.test.ts +193 -0
- package/ee/claim-check/prompts/shared.ts +89 -0
- package/ee/claim-check/prompts/verify.ts +56 -0
- package/ee/claim-check/rate-limit.test.ts +40 -0
- package/ee/claim-check/rate-limit.ts +82 -0
- package/ee/claim-check/routes.test.ts +1188 -0
- package/ee/claim-check/routes.ts +682 -0
- package/ee/claim-check/run.test.ts +1317 -0
- package/ee/claim-check/run.ts +710 -0
- package/ee/claim-check/score.test.ts +108 -0
- package/ee/claim-check/score.ts +75 -0
- package/ee/claim-check/second-chance.test.ts +89 -0
- package/ee/claim-check/second-chance.ts +80 -0
- package/ee/claim-check/split.test.ts +179 -0
- package/ee/claim-check/split.ts +220 -0
- package/ee/claim-check/stages/decompose.test.ts +129 -0
- package/ee/claim-check/stages/decompose.ts +64 -0
- package/ee/claim-check/stages/disambiguate.test.ts +130 -0
- package/ee/claim-check/stages/disambiguate.ts +74 -0
- package/ee/claim-check/stages/select-disambiguate.test.ts +137 -0
- package/ee/claim-check/stages/select-disambiguate.ts +90 -0
- package/ee/claim-check/stages/select.test.ts +155 -0
- package/ee/claim-check/stages/select.ts +94 -0
- package/ee/claim-check/stages/usage.ts +11 -0
- package/ee/claim-check/stages/verify.test.ts +154 -0
- package/ee/claim-check/stages/verify.ts +78 -0
- package/ee/claim-check/types.ts +178 -0
- package/ee/entitlements.ts +3 -0
- package/ee/invoke-skills/create-sandbox.ts +18 -1
- package/ee/python/requirements.txt +3 -0
- package/ee/schemas.ts +71 -0
- package/ee/workers.ts +13 -0
- package/package.json +1 -1
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// ee/claim-check/split.ts
|
|
2
|
+
//
|
|
3
|
+
// Sentence segmentation for claim extraction. Two jobs the paper's NLTK
|
|
4
|
+
// splitter does not have to do: keep character offsets into the ORIGINAL
|
|
5
|
+
// answer (the UI highlights by offset), and ignore the parts of a Markdown
|
|
6
|
+
// answer that carry no claim (headings, fenced code, table rows).
|
|
7
|
+
//
|
|
8
|
+
// List items and numbered steps ARE prose: in a German maintenance answer the
|
|
9
|
+
// specifics (causes, steps, part numbers) live in exactly those lines, and a
|
|
10
|
+
// sentence that is never emitted is never checked, never counted and never
|
|
11
|
+
// reported — the answer would come back "ok" without having been read.
|
|
12
|
+
import { preprocessQuery } from "@SRC/utils/query-preprocessing";
|
|
13
|
+
import type { Sentence, SentenceWindow } from "./types";
|
|
14
|
+
|
|
15
|
+
/** ISO 639-3 (franc) -> ISO 639-1 (Intl.Segmenter). */
|
|
16
|
+
const LOCALE_BY_LANGUAGE: Record<string, string> = {
|
|
17
|
+
eng: "en", deu: "de", fra: "fr", spa: "es", ita: "it",
|
|
18
|
+
por: "pt", rus: "ru", nld: "nl", swe: "sv", nor: "no", dan: "da",
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Abbreviations that ICU's sentence-break suppressions do not reliably cover
|
|
23
|
+
* across ICU builds. A segment ending with one of these is glued back onto
|
|
24
|
+
* the next one, so "z. B." never ends a sentence.
|
|
25
|
+
*
|
|
26
|
+
* "z." (bare) was added for this machine's ICU build: it breaks "z. B."
|
|
27
|
+
* between the two abbreviated words ("Die Ursache ist z. " | "B. ein ...")
|
|
28
|
+
* rather than after the pair, so the two-word forms "z. b." / "z.b." never
|
|
29
|
+
* match as a suffix and the bare form is what actually needs gluing here.
|
|
30
|
+
* A bare single-letter entry is only safe because the match below requires a
|
|
31
|
+
* word boundary before it — otherwise "z." also matches ordinary nouns like
|
|
32
|
+
* "Platz." (and "no." would match "Casino.", "Domino.", "Piano."), gluing
|
|
33
|
+
* unrelated sentences together while leaving offsets looking exact.
|
|
34
|
+
*/
|
|
35
|
+
const ABBREVIATIONS = [
|
|
36
|
+
"z. b.", "z.b.", "z.", "u. a.", "u.a.", "d. h.", "d.h.", "bzw.", "ggf.", "ca.",
|
|
37
|
+
"nr.", "abs.", "art.", "abb.", "tab.", "evtl.", "inkl.", "exkl.", "max.",
|
|
38
|
+
"min.", "vgl.", "sog.", "bspw.", "etc.", "e.g.", "i.e.", "fig.", "no.",
|
|
39
|
+
];
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* One boundary-guarded regex per abbreviation, built once at module load:
|
|
43
|
+
* matches only when the abbreviation is preceded by start-of-text or
|
|
44
|
+
* whitespace, so "z." glues "… ist z." but not "… am Platz.", and "no."
|
|
45
|
+
* glues "… ist no." but not "… im Casino.".
|
|
46
|
+
*/
|
|
47
|
+
const ABBREVIATION_PATTERNS = ABBREVIATIONS.map(
|
|
48
|
+
(a) => new RegExp(`(?:^|\\s)${a.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}$`, "i"),
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
function endsWithAbbreviation(text: string): boolean {
|
|
52
|
+
const trimmed = text.trimEnd();
|
|
53
|
+
return ABBREVIATION_PATTERNS.some((re) => re.test(trimmed));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
type Block = { start: number; end: number; headingPath: string[] };
|
|
57
|
+
|
|
58
|
+
export function localeFromText(text: string): string {
|
|
59
|
+
if (!text.trim()) return "en";
|
|
60
|
+
const { language } = preprocessQuery(text, { enableStemming: false, detectLanguage: true, silent: true });
|
|
61
|
+
return LOCALE_BY_LANGUAGE[language] ?? "en";
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* A list bullet ("- ", "* ", "+ ") or a numbered step ("1. ", "1) "),
|
|
66
|
+
* including its indentation and the whitespace after the marker. The match
|
|
67
|
+
* length is where the item's CONTENT starts, which is what keeps offsets
|
|
68
|
+
* exact: a sentence's `start` points at the content, never at the marker, so
|
|
69
|
+
* answer.slice(start, end) === text still holds.
|
|
70
|
+
*/
|
|
71
|
+
const LIST_MARKER = /^(?:\s*)(?:[-*+]|\d+[.)])\s+/;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* True for lines that carry no claim: blank lines, table rows (a fragment
|
|
75
|
+
* whose claim semantics need their own treatment), horizontal rules and block
|
|
76
|
+
* quotes. Fences are handled by the caller, which also tracks their state.
|
|
77
|
+
* List items are NOT here — they are prose, see listContentStart.
|
|
78
|
+
*/
|
|
79
|
+
function isNonProseLine(line: string): boolean {
|
|
80
|
+
const t = line.trim();
|
|
81
|
+
if (!t) return true;
|
|
82
|
+
if (t.startsWith("|")) return true;
|
|
83
|
+
if (/^(-{3,}|_{3,}|\*{3,})$/.test(t)) return true;
|
|
84
|
+
// A marker with nothing after it ("-", "1.") carries no content at all.
|
|
85
|
+
if (/^(?:[-*+]|\d+[.)])$/.test(t)) return true;
|
|
86
|
+
if (t.startsWith(">")) return true;
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Offset of a list item's content within the line, or null when the line is not a list item. */
|
|
91
|
+
function listContentStart(line: string): number | null {
|
|
92
|
+
const match = LIST_MARKER.exec(line);
|
|
93
|
+
return match ? match[0].length : null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Walk the answer line by line and collect maximal runs of prose lines. A run
|
|
98
|
+
* is segmented as one unit, so a sentence may span a soft line break; offsets
|
|
99
|
+
* stay absolute because a run is addressed by slice bounds into the answer.
|
|
100
|
+
*/
|
|
101
|
+
function collectBlocks(answer: string): Block[] {
|
|
102
|
+
const blocks: Block[] = [];
|
|
103
|
+
const headingPath: string[] = [];
|
|
104
|
+
let inFence = false;
|
|
105
|
+
let offset = 0;
|
|
106
|
+
let runStart: number | null = null;
|
|
107
|
+
let runEnd = 0;
|
|
108
|
+
let runHeadings: string[] = [];
|
|
109
|
+
|
|
110
|
+
const closeRun = () => {
|
|
111
|
+
if (runStart !== null && runEnd > runStart) {
|
|
112
|
+
blocks.push({ start: runStart, end: runEnd, headingPath: [...runHeadings] });
|
|
113
|
+
}
|
|
114
|
+
runStart = null;
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
for (const line of answer.split("\n")) {
|
|
118
|
+
const lineStart = offset;
|
|
119
|
+
const lineEnd = offset + line.length;
|
|
120
|
+
offset = lineEnd + 1; // the "\n" that split consumed
|
|
121
|
+
const trimmed = line.trim();
|
|
122
|
+
|
|
123
|
+
if (/^(```|~~~)/.test(trimmed)) {
|
|
124
|
+
closeRun();
|
|
125
|
+
inFence = !inFence;
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (inFence) continue;
|
|
129
|
+
|
|
130
|
+
const heading = /^(#{1,6})\s+(.*)$/.exec(trimmed);
|
|
131
|
+
if (heading) {
|
|
132
|
+
closeRun();
|
|
133
|
+
const depth = heading[1]!.length;
|
|
134
|
+
headingPath.length = depth - 1;
|
|
135
|
+
headingPath[depth - 1] = heading[2]!.trim();
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if (isNonProseLine(line)) {
|
|
140
|
+
closeRun();
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// A list item is its own block: the marker is excluded from the block, so
|
|
145
|
+
// it can never leak into a sentence's text, and the items of one list are
|
|
146
|
+
// never segmented as a single flowing sentence (they rarely end in a
|
|
147
|
+
// period, so one unit would glue them all together).
|
|
148
|
+
const contentStart = listContentStart(line);
|
|
149
|
+
if (contentStart !== null) {
|
|
150
|
+
closeRun();
|
|
151
|
+
const start = lineStart + contentStart;
|
|
152
|
+
if (lineEnd > start) {
|
|
153
|
+
blocks.push({
|
|
154
|
+
start,
|
|
155
|
+
end: lineEnd,
|
|
156
|
+
headingPath: headingPath.filter((h): h is string => Boolean(h)),
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (runStart === null) {
|
|
163
|
+
runStart = lineStart;
|
|
164
|
+
runHeadings = headingPath.filter((h): h is string => Boolean(h));
|
|
165
|
+
}
|
|
166
|
+
runEnd = lineEnd;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
closeRun();
|
|
170
|
+
return blocks;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function splitIntoSentences(answer: string, locale?: string): Sentence[] {
|
|
174
|
+
if (!answer.trim()) return [];
|
|
175
|
+
const resolved = locale ?? localeFromText(answer);
|
|
176
|
+
const segmenter = new Intl.Segmenter(resolved, { granularity: "sentence" });
|
|
177
|
+
const sentences: Sentence[] = [];
|
|
178
|
+
|
|
179
|
+
for (const block of collectBlocks(answer)) {
|
|
180
|
+
const raw = answer.slice(block.start, block.end);
|
|
181
|
+
const pieces: { text: string; start: number }[] = [];
|
|
182
|
+
|
|
183
|
+
for (const seg of segmenter.segment(raw)) {
|
|
184
|
+
const previous = pieces[pieces.length - 1];
|
|
185
|
+
if (previous !== undefined && endsWithAbbreviation(previous.text)) {
|
|
186
|
+
previous.text += seg.segment;
|
|
187
|
+
} else {
|
|
188
|
+
pieces.push({ text: seg.segment, start: block.start + seg.index });
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
for (const piece of pieces) {
|
|
193
|
+
const leading = piece.text.length - piece.text.trimStart().length;
|
|
194
|
+
const trimmed = piece.text.trim();
|
|
195
|
+
if (!trimmed) continue;
|
|
196
|
+
const start = piece.start + leading;
|
|
197
|
+
sentences.push({
|
|
198
|
+
index: sentences.length,
|
|
199
|
+
start,
|
|
200
|
+
end: start + trimmed.length,
|
|
201
|
+
text: trimmed,
|
|
202
|
+
headingPath: block.headingPath,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
return sentences;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export function buildWindows(
|
|
211
|
+
sentences: Sentence[],
|
|
212
|
+
preceding: number,
|
|
213
|
+
following: number,
|
|
214
|
+
): SentenceWindow[] {
|
|
215
|
+
return sentences.map((sentence, i) => ({
|
|
216
|
+
sentence,
|
|
217
|
+
preceding: sentences.slice(Math.max(0, i - preceding), i),
|
|
218
|
+
following: sentences.slice(i + 1, i + 1 + following),
|
|
219
|
+
}));
|
|
220
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
jest.mock("@EE/agentic-retrieval/pipeline/micro-call", () => ({
|
|
2
|
+
microCall: jest.fn(),
|
|
3
|
+
microCallProviderOptions: jest.fn(),
|
|
4
|
+
}));
|
|
5
|
+
import { microCall } from "@EE/agentic-retrieval/pipeline/micro-call";
|
|
6
|
+
import { splitIntoSentences, buildWindows } from "../split";
|
|
7
|
+
import { runDecomposition } from "./decompose";
|
|
8
|
+
import { CLAIM_CHECK_MAX_OUTPUT_TOKENS } from "../types";
|
|
9
|
+
import { SAME_LANGUAGE_RULE, UNTRUSTED_TEXT_RULE } from "../prompts/shared";
|
|
10
|
+
|
|
11
|
+
const ANSWER = "Die FST-2XT arbeitet mit 230 Volt und wird im Schaltschrank montiert.";
|
|
12
|
+
const windows = () => buildWindows(splitIntoSentences(ANSWER, "de"), 5, 0);
|
|
13
|
+
|
|
14
|
+
beforeEach(() => (microCall as jest.Mock).mockReset());
|
|
15
|
+
|
|
16
|
+
describe("runDecomposition", () => {
|
|
17
|
+
it("splits a conjunction into independently checkable claims", async () => {
|
|
18
|
+
(microCall as jest.Mock).mockResolvedValue({
|
|
19
|
+
output: {
|
|
20
|
+
sentences: [
|
|
21
|
+
{
|
|
22
|
+
index: 0,
|
|
23
|
+
claims: [
|
|
24
|
+
{ text: "Die FST-2XT arbeitet mit 230 Volt.", inferred: false },
|
|
25
|
+
{ text: "Die FST-2XT wird im Schaltschrank montiert.", inferred: false },
|
|
26
|
+
],
|
|
27
|
+
},
|
|
28
|
+
],
|
|
29
|
+
},
|
|
30
|
+
text: "",
|
|
31
|
+
usage: { inputTokens: 700, outputTokens: 150 },
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
const { outcomes, usage } = await runDecomposition({
|
|
35
|
+
windows: windows(),
|
|
36
|
+
question: "Womit arbeitet die FST-2XT?",
|
|
37
|
+
sentenceTexts: new Map(),
|
|
38
|
+
model: {} as any,
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
expect(usage).toEqual({ calls: 1, inputTokens: 700, outputTokens: 150 });
|
|
42
|
+
expect(outcomes[0]!.claims).toHaveLength(2);
|
|
43
|
+
expect(outcomes[0]!.claims[0]!.inferred).toBe(false);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it("keeps bracketed context and its inferred flag", async () => {
|
|
47
|
+
(microCall as jest.Mock).mockResolvedValue({
|
|
48
|
+
output: {
|
|
49
|
+
sentences: [{ index: 0, claims: [{ text: "Die FST-2XT [eine Aufzugssteuerung] arbeitet mit 230 Volt.", inferred: true }] }],
|
|
50
|
+
},
|
|
51
|
+
text: "",
|
|
52
|
+
usage: { inputTokens: 10, outputTokens: 10 },
|
|
53
|
+
});
|
|
54
|
+
const { outcomes } = await runDecomposition({ windows: windows(), question: "q", sentenceTexts: new Map(), model: {} as any });
|
|
55
|
+
expect(outcomes[0]!.claims[0]!.text).toContain("[eine Aufzugssteuerung]");
|
|
56
|
+
expect(outcomes[0]!.claims[0]!.inferred).toBe(true);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("returns an empty claim list when the model extracts nothing, without inventing one", async () => {
|
|
60
|
+
(microCall as jest.Mock).mockResolvedValue({
|
|
61
|
+
output: { sentences: [{ index: 0, claims: [] }] },
|
|
62
|
+
text: "",
|
|
63
|
+
usage: { inputTokens: 10, outputTokens: 10 },
|
|
64
|
+
});
|
|
65
|
+
const { outcomes } = await runDecomposition({ windows: windows(), question: "q", sentenceTexts: new Map(), model: {} as any });
|
|
66
|
+
expect(outcomes[0]!.claims).toEqual([]);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it("drops blank claim texts and claims for indexes not in the batch", async () => {
|
|
70
|
+
(microCall as jest.Mock).mockResolvedValue({
|
|
71
|
+
output: {
|
|
72
|
+
sentences: [
|
|
73
|
+
{ index: 0, claims: [{ text: " ", inferred: false }, { text: "Gültige Aussage.", inferred: false }] },
|
|
74
|
+
{ index: 77, claims: [{ text: "Fremder Index.", inferred: false }] },
|
|
75
|
+
],
|
|
76
|
+
},
|
|
77
|
+
text: "",
|
|
78
|
+
usage: { inputTokens: 10, outputTokens: 10 },
|
|
79
|
+
});
|
|
80
|
+
const { outcomes } = await runDecomposition({ windows: windows(), question: "q", sentenceTexts: new Map(), model: {} as any });
|
|
81
|
+
expect(outcomes.map((o) => o.index)).toEqual([0]);
|
|
82
|
+
expect(outcomes[0]!.claims.map((c) => c.text)).toEqual(["Gültige Aussage."]);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it("decomposes the disambiguated text when one was supplied", async () => {
|
|
86
|
+
(microCall as jest.Mock).mockResolvedValue({ output: { sentences: [] }, text: "", usage: { inputTokens: 1, outputTokens: 1 } });
|
|
87
|
+
await runDecomposition({
|
|
88
|
+
windows: windows(),
|
|
89
|
+
question: "q",
|
|
90
|
+
sentenceTexts: new Map([[0, "Die FST-2XT arbeitet mit 230 Volt."]]),
|
|
91
|
+
model: {} as any,
|
|
92
|
+
});
|
|
93
|
+
const prompt = String((microCall as jest.Mock).mock.calls[0][0].prompt);
|
|
94
|
+
expect(prompt).toContain("[0] Die FST-2XT arbeitet mit 230 Volt.");
|
|
95
|
+
expect(prompt).not.toContain("im Schaltschrank montiert");
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it("passes the raised output cap and uses temperature 0", async () => {
|
|
99
|
+
(microCall as jest.Mock).mockResolvedValue({
|
|
100
|
+
output: { sentences: [] },
|
|
101
|
+
text: "",
|
|
102
|
+
usage: { inputTokens: 1, outputTokens: 1 },
|
|
103
|
+
});
|
|
104
|
+
await runDecomposition({
|
|
105
|
+
windows: windows(),
|
|
106
|
+
question: "q",
|
|
107
|
+
sentenceTexts: new Map(),
|
|
108
|
+
model: {} as any,
|
|
109
|
+
});
|
|
110
|
+
const args = (microCall as jest.Mock).mock.calls[0][0];
|
|
111
|
+
expect(args.maxOutputTokens).toBe(CLAIM_CHECK_MAX_OUTPUT_TOKENS);
|
|
112
|
+
expect(args.temperature).toBe(0);
|
|
113
|
+
});
|
|
114
|
+
// Finding 10: see select.test.ts.
|
|
115
|
+
it("pins the output language in the system prompt", async () => {
|
|
116
|
+
(microCall as jest.Mock).mockResolvedValue({ output: { sentences: [] }, text: "", usage: { inputTokens: 1, outputTokens: 1 } });
|
|
117
|
+
await runDecomposition({ windows: windows(), question: "q", sentenceTexts: new Map(), model: {} as any });
|
|
118
|
+
expect(String((microCall as jest.Mock).mock.calls[0][0].system)).toContain(SAME_LANGUAGE_RULE);
|
|
119
|
+
});
|
|
120
|
+
// Finding 13: see verify.test.ts.
|
|
121
|
+
it("fences the caller-supplied excerpt and explains the fences", async () => {
|
|
122
|
+
(microCall as jest.Mock).mockResolvedValue({ output: { sentences: [] }, text: "", usage: { inputTokens: 1, outputTokens: 1 } });
|
|
123
|
+
await runDecomposition({ windows: windows(), question: "q", sentenceTexts: new Map(), model: {} as any });
|
|
124
|
+
const args = (microCall as jest.Mock).mock.calls[0][0];
|
|
125
|
+
expect(String(args.prompt)).toContain("<<<BEGIN EXCERPT>>>");
|
|
126
|
+
expect(String(args.prompt)).toContain("<<<END EXCERPT>>>");
|
|
127
|
+
expect(String(args.system)).toContain(UNTRUSTED_TEXT_RULE);
|
|
128
|
+
});
|
|
129
|
+
});
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import type { LanguageModel } from "ai";
|
|
3
|
+
import { microCall } from "@EE/agentic-retrieval/pipeline/micro-call";
|
|
4
|
+
import { CLAIM_CHECK_MAX_OUTPUT_TOKENS, type DecompositionOutcome, type SentenceWindow } from "../types";
|
|
5
|
+
import { DECOMPOSE_SYSTEM, decomposeUserPrompt } from "../prompts/decompose";
|
|
6
|
+
import { excerptFor } from "./select";
|
|
7
|
+
import type { StageUsage } from "./usage";
|
|
8
|
+
|
|
9
|
+
const schema = z.object({
|
|
10
|
+
sentences: z.array(
|
|
11
|
+
z.object({
|
|
12
|
+
index: z.number().int(),
|
|
13
|
+
claims: z.array(z.object({ text: z.string(), inferred: z.boolean() })),
|
|
14
|
+
}),
|
|
15
|
+
),
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
export async function runDecomposition(args: {
|
|
19
|
+
windows: SentenceWindow[];
|
|
20
|
+
question: string;
|
|
21
|
+
/** Disambiguated (or selection-rewritten) text by index; falls back to the original. */
|
|
22
|
+
sentenceTexts: Map<number, string>;
|
|
23
|
+
model: LanguageModel;
|
|
24
|
+
temperature?: number;
|
|
25
|
+
/** Cancels the provider call when the request's deadline passes. */
|
|
26
|
+
signal?: AbortSignal;
|
|
27
|
+
}): Promise<{ outcomes: DecompositionOutcome[]; usage: StageUsage }> {
|
|
28
|
+
const targets = args.windows.map((w) => ({
|
|
29
|
+
index: w.sentence.index,
|
|
30
|
+
text: args.sentenceTexts.get(w.sentence.index) ?? w.sentence.text,
|
|
31
|
+
}));
|
|
32
|
+
const allowed = new Set(targets.map((t) => t.index));
|
|
33
|
+
|
|
34
|
+
// Pass sentenceTexts to excerptFor so the excerpt shows the disambiguated text
|
|
35
|
+
// the pipeline kept, not the original wording. This ensures the excerpt and the
|
|
36
|
+
// numbered target lines are consistent with each other.
|
|
37
|
+
const { output, usage } = await microCall({
|
|
38
|
+
model: args.model,
|
|
39
|
+
system: DECOMPOSE_SYSTEM,
|
|
40
|
+
prompt: decomposeUserPrompt({
|
|
41
|
+
question: args.question,
|
|
42
|
+
excerpt: excerptFor(args.windows, args.sentenceTexts),
|
|
43
|
+
targets,
|
|
44
|
+
}),
|
|
45
|
+
schema,
|
|
46
|
+
temperature: args.temperature ?? 0,
|
|
47
|
+
maxOutputTokens: CLAIM_CHECK_MAX_OUTPUT_TOKENS,
|
|
48
|
+
...(args.signal ? { abortSignal: args.signal } : {}),
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const outcomes: DecompositionOutcome[] = [];
|
|
52
|
+
for (const sentence of output?.sentences ?? []) {
|
|
53
|
+
// A hallucinated index has no sentence to highlight, so it cannot be scored.
|
|
54
|
+
if (!allowed.has(sentence.index)) continue;
|
|
55
|
+
outcomes.push({
|
|
56
|
+
index: sentence.index,
|
|
57
|
+
claims: sentence.claims
|
|
58
|
+
.filter((c) => c.text.trim().length > 0)
|
|
59
|
+
.map((c) => ({ text: c.text.trim(), inferred: c.inferred })),
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return { outcomes, usage: { calls: 1, ...usage } };
|
|
64
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
jest.mock("@EE/agentic-retrieval/pipeline/micro-call", () => ({
|
|
2
|
+
microCall: jest.fn(),
|
|
3
|
+
microCallProviderOptions: jest.fn(),
|
|
4
|
+
}));
|
|
5
|
+
import { microCall } from "@EE/agentic-retrieval/pipeline/micro-call";
|
|
6
|
+
import { splitIntoSentences, buildWindows } from "../split";
|
|
7
|
+
import { runDisambiguation } from "./disambiguate";
|
|
8
|
+
import { CLAIM_CHECK_MAX_OUTPUT_TOKENS } from "../types";
|
|
9
|
+
import { SAME_LANGUAGE_RULE, UNTRUSTED_TEXT_RULE } from "../prompts/shared";
|
|
10
|
+
|
|
11
|
+
const ANSWER = "Die FST-2XT meldet einen Fehler. Sie wurde dort getauscht.";
|
|
12
|
+
const windows = () => buildWindows(splitIntoSentences(ANSWER, "de"), 5, 0);
|
|
13
|
+
|
|
14
|
+
beforeEach(() => (microCall as jest.Mock).mockReset());
|
|
15
|
+
|
|
16
|
+
describe("runDisambiguation", () => {
|
|
17
|
+
it("returns the clarified sentence when every ambiguity resolves", async () => {
|
|
18
|
+
(microCall as jest.Mock).mockResolvedValue({
|
|
19
|
+
output: {
|
|
20
|
+
sentences: [
|
|
21
|
+
{ index: 0, resolvable: true, clarified: null, reason: "no ambiguity" },
|
|
22
|
+
{ index: 1, resolvable: true, clarified: "Die FST-2XT wurde im Schaltschrank getauscht.", reason: "'Sie' and 'dort' resolved from context" },
|
|
23
|
+
],
|
|
24
|
+
},
|
|
25
|
+
text: "",
|
|
26
|
+
usage: { inputTokens: 800, outputTokens: 90 },
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
const { outcomes, usage } = await runDisambiguation({
|
|
30
|
+
windows: windows(),
|
|
31
|
+
question: "Was wurde getauscht?",
|
|
32
|
+
sentenceTexts: new Map(),
|
|
33
|
+
model: {} as any,
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
expect(usage).toEqual({ calls: 1, inputTokens: 800, outputTokens: 90 });
|
|
37
|
+
expect(outcomes[1]).toEqual({
|
|
38
|
+
index: 1,
|
|
39
|
+
resolvable: true,
|
|
40
|
+
clarified: "Die FST-2XT wurde im Schaltschrank getauscht.",
|
|
41
|
+
reason: "'Sie' and 'dort' resolved from context",
|
|
42
|
+
answered: true,
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
// Finding 4: an unanswered sentence is excluded, as before, but flagged so
|
|
47
|
+
// the orchestrator does not report the model's silence as a judgement about
|
|
48
|
+
// the sentence's ambiguity.
|
|
49
|
+
it("marks a sentence the model omitted as unanswered", async () => {
|
|
50
|
+
(microCall as jest.Mock).mockResolvedValue({
|
|
51
|
+
output: { sentences: [{ index: 0, resolvable: true, clarified: null, reason: "clear" }] },
|
|
52
|
+
text: "",
|
|
53
|
+
usage: { inputTokens: 10, outputTokens: 10 },
|
|
54
|
+
});
|
|
55
|
+
const { outcomes } = await runDisambiguation({
|
|
56
|
+
windows: windows(),
|
|
57
|
+
question: "q",
|
|
58
|
+
sentenceTexts: new Map(),
|
|
59
|
+
model: {} as any,
|
|
60
|
+
});
|
|
61
|
+
expect(outcomes[1]).toEqual({
|
|
62
|
+
index: 1,
|
|
63
|
+
resolvable: false,
|
|
64
|
+
clarified: null,
|
|
65
|
+
reason: "no disambiguation returned for this sentence",
|
|
66
|
+
answered: false,
|
|
67
|
+
});
|
|
68
|
+
expect(outcomes[0]!.answered).toBe(true);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it("marks a sentence unresolvable when readers would not reach consensus", async () => {
|
|
72
|
+
(microCall as jest.Mock).mockResolvedValue({
|
|
73
|
+
output: {
|
|
74
|
+
sentences: [{ index: 0, resolvable: false, clarified: null, reason: "two mutually exclusive readings" }],
|
|
75
|
+
},
|
|
76
|
+
text: "",
|
|
77
|
+
usage: { inputTokens: 10, outputTokens: 10 },
|
|
78
|
+
});
|
|
79
|
+
const { outcomes } = await runDisambiguation({
|
|
80
|
+
windows: windows().slice(0, 1),
|
|
81
|
+
question: "q",
|
|
82
|
+
sentenceTexts: new Map(),
|
|
83
|
+
model: {} as any,
|
|
84
|
+
});
|
|
85
|
+
expect(outcomes[0]!.resolvable).toBe(false);
|
|
86
|
+
expect(outcomes[0]!.clarified).toBeNull();
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it("judges Selection's rewrite rather than the original sentence", async () => {
|
|
90
|
+
(microCall as jest.Mock).mockResolvedValue({ output: { sentences: [] }, text: "", usage: { inputTokens: 1, outputTokens: 1 } });
|
|
91
|
+
await runDisambiguation({
|
|
92
|
+
windows: windows(),
|
|
93
|
+
question: "q",
|
|
94
|
+
sentenceTexts: new Map([[0, "Die FST-2XT meldet einen Fehler."], [1, "Sie wurde getauscht."]]),
|
|
95
|
+
model: {} as any,
|
|
96
|
+
});
|
|
97
|
+
const prompt = String((microCall as jest.Mock).mock.calls[0][0].prompt);
|
|
98
|
+
expect(prompt).toContain("[1] Sie wurde getauscht.");
|
|
99
|
+
expect(prompt).not.toContain("Sie wurde dort getauscht.");
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it("treats an omitted sentence as unresolvable and passes the raised output cap", async () => {
|
|
103
|
+
(microCall as jest.Mock).mockResolvedValue({ output: { sentences: [] }, text: "", usage: { inputTokens: 1, outputTokens: 1 } });
|
|
104
|
+
const { outcomes } = await runDisambiguation({
|
|
105
|
+
windows: windows(),
|
|
106
|
+
question: "q",
|
|
107
|
+
sentenceTexts: new Map(),
|
|
108
|
+
model: {} as any,
|
|
109
|
+
});
|
|
110
|
+
expect(outcomes).toHaveLength(2);
|
|
111
|
+
expect(outcomes.every((o) => o.resolvable === false)).toBe(true);
|
|
112
|
+
expect(outcomes[0]!.reason).toBe("no disambiguation returned for this sentence");
|
|
113
|
+
expect((microCall as jest.Mock).mock.calls[0][0].maxOutputTokens).toBe(CLAIM_CHECK_MAX_OUTPUT_TOKENS);
|
|
114
|
+
});
|
|
115
|
+
// Finding 10: see select.test.ts.
|
|
116
|
+
it("pins the output language in the system prompt", async () => {
|
|
117
|
+
(microCall as jest.Mock).mockResolvedValue({ output: { sentences: [] }, text: "", usage: { inputTokens: 1, outputTokens: 1 } });
|
|
118
|
+
await runDisambiguation({ windows: windows(), question: "q", sentenceTexts: new Map(), model: {} as any });
|
|
119
|
+
expect(String((microCall as jest.Mock).mock.calls[0][0].system)).toContain(SAME_LANGUAGE_RULE);
|
|
120
|
+
});
|
|
121
|
+
// Finding 13: see verify.test.ts.
|
|
122
|
+
it("fences the caller-supplied excerpt and explains the fences", async () => {
|
|
123
|
+
(microCall as jest.Mock).mockResolvedValue({ output: { sentences: [] }, text: "", usage: { inputTokens: 1, outputTokens: 1 } });
|
|
124
|
+
await runDisambiguation({ windows: windows(), question: "q", sentenceTexts: new Map(), model: {} as any });
|
|
125
|
+
const args = (microCall as jest.Mock).mock.calls[0][0];
|
|
126
|
+
expect(String(args.prompt)).toContain("<<<BEGIN EXCERPT>>>");
|
|
127
|
+
expect(String(args.prompt)).toContain("<<<END EXCERPT>>>");
|
|
128
|
+
expect(String(args.system)).toContain(UNTRUSTED_TEXT_RULE);
|
|
129
|
+
});
|
|
130
|
+
});
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import type { LanguageModel } from "ai";
|
|
3
|
+
import { microCall } from "@EE/agentic-retrieval/pipeline/micro-call";
|
|
4
|
+
import { CLAIM_CHECK_MAX_OUTPUT_TOKENS, type DisambiguationOutcome, type SentenceWindow } from "../types";
|
|
5
|
+
import { DISAMBIGUATE_SYSTEM, disambiguateUserPrompt } from "../prompts/disambiguate";
|
|
6
|
+
import { excerptFor } from "./select";
|
|
7
|
+
import type { StageUsage } from "./usage";
|
|
8
|
+
|
|
9
|
+
const schema = z.object({
|
|
10
|
+
sentences: z.array(
|
|
11
|
+
z.object({
|
|
12
|
+
index: z.number().int(),
|
|
13
|
+
resolvable: z.boolean(),
|
|
14
|
+
clarified: z.string().nullable(),
|
|
15
|
+
reason: z.string(),
|
|
16
|
+
}),
|
|
17
|
+
),
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
export async function runDisambiguation(args: {
|
|
21
|
+
windows: SentenceWindow[];
|
|
22
|
+
question: string;
|
|
23
|
+
/** Selection's rewrites by sentence index; falls back to the original text. */
|
|
24
|
+
sentenceTexts: Map<number, string>;
|
|
25
|
+
model: LanguageModel;
|
|
26
|
+
temperature?: number;
|
|
27
|
+
/** Cancels the provider call when the request's deadline passes. */
|
|
28
|
+
signal?: AbortSignal;
|
|
29
|
+
}): Promise<{ outcomes: DisambiguationOutcome[]; usage: StageUsage }> {
|
|
30
|
+
const targets = args.windows.map((w) => ({
|
|
31
|
+
index: w.sentence.index,
|
|
32
|
+
text: args.sentenceTexts.get(w.sentence.index) ?? w.sentence.text,
|
|
33
|
+
}));
|
|
34
|
+
|
|
35
|
+
const { output, usage } = await microCall({
|
|
36
|
+
model: args.model,
|
|
37
|
+
system: DISAMBIGUATE_SYSTEM,
|
|
38
|
+
prompt: disambiguateUserPrompt({
|
|
39
|
+
question: args.question,
|
|
40
|
+
excerpt: excerptFor(args.windows, args.sentenceTexts),
|
|
41
|
+
targets,
|
|
42
|
+
}),
|
|
43
|
+
schema,
|
|
44
|
+
temperature: args.temperature ?? 0,
|
|
45
|
+
maxOutputTokens: CLAIM_CHECK_MAX_OUTPUT_TOKENS,
|
|
46
|
+
...(args.signal ? { abortSignal: args.signal } : {}),
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
const returned = new Map((output?.sentences ?? []).map((s) => [s.index, s]));
|
|
50
|
+
|
|
51
|
+
// An unanswered sentence is excluded, not assumed clear: this stage exists
|
|
52
|
+
// to refuse rather than guess, and a missing answer is not a resolution.
|
|
53
|
+
const outcomes = targets.map(({ index }) => {
|
|
54
|
+
const hit = returned.get(index);
|
|
55
|
+
if (!hit) {
|
|
56
|
+
return {
|
|
57
|
+
index,
|
|
58
|
+
resolvable: false,
|
|
59
|
+
clarified: null,
|
|
60
|
+
reason: "no disambiguation returned for this sentence",
|
|
61
|
+
answered: false,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
index,
|
|
66
|
+
resolvable: hit.resolvable,
|
|
67
|
+
clarified: hit.resolvable && hit.clarified && hit.clarified.trim() ? hit.clarified.trim() : null,
|
|
68
|
+
reason: hit.reason,
|
|
69
|
+
answered: true,
|
|
70
|
+
};
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
return { outcomes, usage: { calls: 1, ...usage } };
|
|
74
|
+
}
|