-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcore.ts
More file actions
398 lines (347 loc) · 10.7 KB
/
Copy pathcore.ts
File metadata and controls
398 lines (347 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/** TreeDex: Tree-based document RAG framework. */
import { autoLoader } from "./loaders.js";
import { groupPages } from "./pdf-parser.js";
import {
assignNodeIds,
assignPageRanges,
embedTextInTree,
findLargeNodes,
listToTree,
} from "./tree-builder.js";
import {
collectNodeTexts,
countNodes,
createNodeMapping,
extractJson,
getLeafNodes,
printTree,
stripTextFromTree,
} from "./tree-utils.js";
import {
structureExtractionPrompt,
structureContinuePrompt,
retrievalPrompt,
answerPrompt,
imageDescriptionPrompt,
} from "./prompts.js";
import { countTokens } from "./pdf-parser.js";
import type { Page, TreeNode, IndexData, Stats } from "./types.js";
import type { BaseLLM } from "./llm-backends.js";
/** Append image descriptions to page text, modifying pages in place. */
async function describeImages(
pages: Page[],
llm?: BaseLLM | null,
verbose: boolean = false,
): Promise<void> {
for (const page of pages) {
if (!page.images || page.images.length === 0) continue;
const descriptions: string[] = [];
for (const img of page.images) {
const alt = (img.alt_text ?? "").trim();
if (alt) {
descriptions.push(`[Image: ${alt}]`);
} else if (llm?.supportsVision && img.data) {
try {
const desc = await llm.generateWithImage(
imageDescriptionPrompt(),
img.data,
img.mime_type,
);
descriptions.push(`[Image: ${desc.trim()}]`);
} catch {
descriptions.push("[Image present]");
}
} else {
descriptions.push("[Image present]");
}
}
if (descriptions.length > 0) {
page.text = page.text + "\n" + descriptions.join("\n");
page.token_count = countTokens(page.text);
}
if (verbose && descriptions.length > 0) {
console.log(` Page ${page.page_num}: ${descriptions.length} image(s) described`);
}
}
}
/** Result of a TreeDex query. */
export class QueryResult {
readonly context: string;
readonly nodeIds: string[];
readonly pageRanges: [number, number][];
readonly reasoning: string;
readonly answer: string;
constructor(
context: string,
nodeIds: string[],
pageRanges: [number, number][],
reasoning: string,
answer: string = "",
) {
this.context = context;
this.nodeIds = nodeIds;
this.pageRanges = pageRanges;
this.reasoning = reasoning;
this.answer = answer;
}
/** Human-readable page ranges like 'pages 5-8, 12-15'. */
get pagesStr(): string {
if (this.pageRanges.length === 0) return "no pages";
const parts: string[] = [];
for (const [start, end] of this.pageRanges) {
if (start === end) {
parts.push(String(start + 1));
} else {
parts.push(`${start + 1}-${end + 1}`);
}
}
return "pages " + parts.join(", ");
}
toString(): string {
return (
`QueryResult(nodes=${JSON.stringify(this.nodeIds)}, ${this.pagesStr}, ` +
`context_len=${this.context.length})`
);
}
}
/** Tree-based document index for RAG retrieval. */
export class TreeDex {
readonly tree: TreeNode[];
readonly pages: Page[];
llm: BaseLLM | null;
private _nodeMap: Record<string, TreeNode>;
constructor(tree: TreeNode[], pages: Page[], llm: BaseLLM | null = null) {
this.tree = tree;
this.pages = pages;
this.llm = llm;
this._nodeMap = createNodeMapping(tree);
}
/**
* Build a TreeDex index from a file.
*
* @param path - Path to document (PDF, TXT, HTML, DOCX)
* @param llm - LLM backend with .generate(prompt) method
* @param options - Optional configuration
*/
static async fromFile(
path: string,
llm: BaseLLM,
options?: {
loader?: { load(path: string): Promise<Page[]> };
maxTokens?: number;
overlap?: number;
verbose?: boolean;
extractImages?: boolean;
},
): Promise<TreeDex> {
const {
loader,
maxTokens = 20000,
overlap = 1,
verbose = true,
extractImages = false,
} = options ?? {};
if (verbose) {
const { basename } = await import("node:path");
console.log(`Loading: ${basename(path)}`);
}
let pages: Page[];
if (loader) {
pages = await loader.load(path);
} else {
pages = await autoLoader(path, { extractImages });
}
if (verbose) {
const totalTokens = pages.reduce((s, p) => s + p.token_count, 0);
console.log(` ${pages.length} pages, ${totalTokens.toLocaleString()} tokens`);
}
return TreeDex.fromPages(pages, llm, { maxTokens, overlap, verbose });
}
/** Build a TreeDex index from pre-extracted pages. */
static async fromPages(
pages: Page[],
llm: BaseLLM,
options?: {
maxTokens?: number;
overlap?: number;
verbose?: boolean;
},
): Promise<TreeDex> {
const { maxTokens = 20000, overlap = 1, verbose = true } = options ?? {};
// Describe images before grouping — appends text markers to pages
await describeImages(pages, llm, verbose);
const groups = groupPages(pages, maxTokens, overlap);
if (verbose) {
console.log(` ${groups.length} page group(s) for structure extraction`);
}
const allSections: Array<{
structure: string;
title: string;
physical_index: number;
}> = [];
for (let i = 0; i < groups.length; i++) {
if (verbose) {
console.log(
` Extracting structure from group ${i + 1}/${groups.length}...`,
);
}
let prompt: string;
if (i === 0) {
prompt = structureExtractionPrompt(groups[i]);
} else {
const prevJson = JSON.stringify(allSections, null, 2);
prompt = structureContinuePrompt(prevJson, groups[i]);
}
const response = await llm.generate(prompt);
const sections = extractJson(response);
if (Array.isArray(sections)) {
allSections.push(
...(sections as Array<{
structure: string;
title: string;
physical_index: number;
}>),
);
} else if (
sections !== null &&
typeof sections === "object" &&
"sections" in (sections as Record<string, unknown>)
) {
allSections.push(
...((sections as { sections: Array<{ structure: string; title: string; physical_index: number }> }).sections),
);
}
}
if (verbose) {
console.log(` Extracted ${allSections.length} sections`);
}
// Build tree
const tree = listToTree(allSections);
assignPageRanges(tree, pages.length);
assignNodeIds(tree);
embedTextInTree(tree, pages);
if (verbose) {
console.log(` Tree: ${countNodes(tree)} nodes`);
}
return new TreeDex(tree, pages, llm);
}
/** Create a TreeDex from an existing tree and pages. */
static fromTree(
tree: TreeNode[],
pages: Page[],
llm: BaseLLM | null = null,
): TreeDex {
return new TreeDex(tree, pages, llm);
}
/**
* Query the index and return relevant context.
*
* @param question - The user's question
* @param options - Optional LLM override or agentic mode
*/
async query(
question: string,
options?: BaseLLM | { llm?: BaseLLM; agentic?: boolean },
): Promise<QueryResult> {
// Support both query(q, llm) and query(q, { llm, agentic })
let activeLlm: BaseLLM | null;
let agentic = false;
if (options && typeof (options as BaseLLM).generate === "function") {
activeLlm = options as BaseLLM;
} else if (options && typeof options === "object") {
const opts = options as { llm?: BaseLLM; agentic?: boolean };
activeLlm = opts.llm ?? this.llm;
agentic = opts.agentic ?? false;
} else {
activeLlm = this.llm;
}
if (!activeLlm) {
throw new Error(
"No LLM provided. Pass llm to query() or TreeDex constructor.",
);
}
// Build lightweight tree structure for the prompt
const stripped = stripTextFromTree(this.tree);
const treeJson = JSON.stringify(stripped, null, 2);
const prompt = retrievalPrompt(treeJson, question);
const response = await activeLlm.generate(prompt);
const result = extractJson(response) as {
node_ids?: string[];
reasoning?: string;
};
const nodeIds = result.node_ids ?? [];
const reasoning = result.reasoning ?? "";
// Collect context text and page ranges
const context = collectNodeTexts(nodeIds, this._nodeMap);
const pageRanges: [number, number][] = [];
for (const nid of nodeIds) {
const node = this._nodeMap[nid];
if (node) {
const start = node.start_index ?? 0;
const end = node.end_index ?? 0;
pageRanges.push([start, end]);
}
}
// Agentic mode: generate an answer from the retrieved context
let answer = "";
if (agentic && context.length > 0) {
const aPrompt = answerPrompt(context, question);
answer = await activeLlm.generate(aPrompt);
}
return new QueryResult(context, nodeIds, pageRanges, reasoning, answer);
}
/** Save the index to a JSON file. */
async save(path: string): Promise<string> {
const fs = await import("node:fs/promises");
const stripped = stripTextFromTree(this.tree);
// Strip images from pages — descriptions are already in text
const cleanPages: Page[] = this.pages.map(({ images: _images, ...rest }) => rest);
const data: IndexData = {
version: "1.0",
framework: "TreeDex",
tree: stripped,
pages: cleanPages,
};
await fs.writeFile(path, JSON.stringify(data, null, 2), "utf-8");
return path;
}
/** Load a TreeDex index from a JSON file. */
static async load(path: string, llm?: BaseLLM | null): Promise<TreeDex> {
const fs = await import("node:fs/promises");
const raw = await fs.readFile(path, "utf-8");
const data = JSON.parse(raw) as IndexData;
const tree = data.tree;
const pages = data.pages;
// Re-embed text from pages
assignPageRanges(tree, pages.length);
embedTextInTree(tree, pages);
return new TreeDex(tree, pages, llm ?? null);
}
/** Pretty-print the tree structure. */
showTree(): void {
printTree(this.tree);
}
/** Return index statistics. */
stats(): Stats {
const totalTokens = this.pages.reduce((s, p) => s + p.token_count, 0);
const leaves = getLeafNodes(this.tree);
return {
total_pages: this.pages.length,
total_tokens: totalTokens,
total_nodes: countNodes(this.tree),
leaf_nodes: leaves.length,
root_sections: this.tree.length,
};
}
/** Find sections that exceed size thresholds. */
findLargeSections(options?: {
maxPages?: number;
maxTokens?: number;
}): TreeNode[] {
return findLargeNodes(this.tree, {
maxPages: options?.maxPages ?? 10,
maxTokens: options?.maxTokens ?? 20000,
pages: this.pages,
});
}
}