llm-large-files 0.1.0 → 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/CHANGELOG.md +147 -0
- package/README.md +32 -6
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +5 -1
- package/dist/analyze.js.map +1 -1
- package/dist/extract.d.ts +30 -7
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +94 -23
- package/dist/extract.js.map +1 -1
- package/dist/gemini/chat.d.ts +38 -2
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +83 -32
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/generate.d.ts +34 -4
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +51 -8
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -2
- package/dist/gemini/index.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +37 -1
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +59 -7
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +7 -0
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +58 -16
- package/dist/map-reduce.js.map +1 -1
- package/dist/pdf-layout.d.ts +39 -0
- package/dist/pdf-layout.d.ts.map +1 -0
- package/dist/pdf-layout.js +820 -0
- package/dist/pdf-layout.js.map +1 -0
- package/dist/pdf-pages.d.ts +45 -0
- package/dist/pdf-pages.d.ts.map +1 -0
- package/dist/pdf-pages.js +336 -0
- package/dist/pdf-pages.js.map +1 -0
- package/dist/pdf-pictures.d.ts +20 -0
- package/dist/pdf-pictures.d.ts.map +1 -0
- package/dist/pdf-pictures.js +336 -0
- package/dist/pdf-pictures.js.map +1 -0
- package/dist/plan.d.ts +13 -3
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +27 -18
- package/dist/plan.js.map +1 -1
- package/dist/search.d.ts +17 -4
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +90 -24
- package/dist/search.js.map +1 -1
- package/dist/stores.d.ts +7 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +37 -5
- package/dist/stores.js.map +1 -1
- package/dist/text.d.ts +18 -4
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +155 -15
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +11 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +156 -16
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +63 -3
- package/dist/types.d.ts.map +1 -1
- package/docs/api.md +56 -11
- package/docs/configuration.md +298 -6
- package/docs/getting-started.md +41 -7
- package/docs/how-it-works.md +77 -11
- package/docs/security.md +54 -6
- package/package.json +96 -91
- package/src/analyze.ts +3 -1
- package/src/extract.ts +105 -24
- package/src/gemini/chat.ts +116 -34
- package/src/gemini/generate.ts +66 -10
- package/src/gemini/index.ts +3 -3
- package/src/index.ts +4 -3
- package/src/library.ts +308 -226
- package/src/map-reduce.ts +69 -16
- package/src/node/handlers.ts +122 -122
- package/src/pdf-layout.ts +807 -0
- package/src/pdf-pages.ts +315 -0
- package/src/pdf-pictures.ts +324 -0
- package/src/plan.ts +120 -98
- package/src/search.ts +85 -25
- package/src/stores.ts +165 -132
- package/src/text.ts +131 -14
- package/src/tools.ts +408 -264
- package/src/types.ts +228 -168
package/src/tools.ts
CHANGED
|
@@ -1,264 +1,408 @@
|
|
|
1
|
-
import { analyzeWholeDocument, splitIntoParts } from "./map-reduce.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
const
|
|
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
|
-
if (
|
|
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
|
-
|
|
1
|
+
import { analyzeWholeDocument, splitIntoParts } from "./map-reduce.js";
|
|
2
|
+
import { cutPdfPages } from "./pdf-pages.js";
|
|
3
|
+
import { grep, rankPassages, type SearchableDocument } from "./search.js";
|
|
4
|
+
import { formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
|
|
5
|
+
import type { Budget, GenerateText, ProgressListener, ToolDeclaration, ToolFileLimits, ToolOutput, ToolResult, ToolSet } from "./types.js";
|
|
6
|
+
|
|
7
|
+
const DEFAULT_READ_LINES = 200;
|
|
8
|
+
const MAX_READ_LINES = 600;
|
|
9
|
+
/** The most pages one `view_pages` call shows. A page costs a model about 530 tokens. */
|
|
10
|
+
export const MAX_VIEW_PAGES = 5;
|
|
11
|
+
/** Below this, no page fits: a cut of one page of plain text is larger. */
|
|
12
|
+
const MIN_FILE_BYTES = 1_024;
|
|
13
|
+
|
|
14
|
+
export const TOOL_NAMES = {
|
|
15
|
+
search: "search_document",
|
|
16
|
+
read: "read_document",
|
|
17
|
+
overview: "get_document_overview",
|
|
18
|
+
analyze: "analyze_whole_document",
|
|
19
|
+
view: "view_pages",
|
|
20
|
+
} as const;
|
|
21
|
+
|
|
22
|
+
const documentId = { type: "string" as const, description: "The document_id from the file's card." };
|
|
23
|
+
|
|
24
|
+
const DECLARATIONS: Record<keyof typeof TOOL_NAMES, ToolDeclaration> = {
|
|
25
|
+
search: {
|
|
26
|
+
name: TOOL_NAMES.search,
|
|
27
|
+
description: "Search a large attached file. mode \"keywords\" returns the most relevant passages for a question; \"exact\" returns every line containing the text; \"regex\" returns lines matching a JavaScript regular expression. Results include line numbers to read further with read_document.",
|
|
28
|
+
parameters: {
|
|
29
|
+
type: "object",
|
|
30
|
+
properties: {
|
|
31
|
+
document_id: documentId,
|
|
32
|
+
query: { type: "string", description: "Keywords, exact text, or a regex, depending on mode." },
|
|
33
|
+
mode: { type: "string", enum: ["keywords", "exact", "regex"], description: "Defaults to keywords." },
|
|
34
|
+
max_results: { type: "integer", description: "Up to 50 for exact/regex (default 20), up to 10 passages for keywords (default 5)." },
|
|
35
|
+
context_lines: { type: "integer", description: "exact/regex only: lines to show before and after each match, 0-5." },
|
|
36
|
+
case_sensitive: { type: "boolean", description: "exact/regex only. Defaults to false." },
|
|
37
|
+
},
|
|
38
|
+
required: ["document_id", "query"],
|
|
39
|
+
},
|
|
40
|
+
},
|
|
41
|
+
read: {
|
|
42
|
+
name: TOOL_NAMES.read,
|
|
43
|
+
description: `Read a range of lines from a large attached file, with line numbers. Up to ${MAX_READ_LINES} lines per call; long results are cut and tell you where to continue.`,
|
|
44
|
+
parameters: {
|
|
45
|
+
type: "object",
|
|
46
|
+
properties: {
|
|
47
|
+
document_id: documentId,
|
|
48
|
+
start_line: { type: "integer", description: "First line to read (1-based)." },
|
|
49
|
+
end_line: { type: "integer", description: `Last line to read. Defaults to start_line + ${DEFAULT_READ_LINES - 1}.` },
|
|
50
|
+
},
|
|
51
|
+
required: ["document_id", "start_line"],
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
overview: {
|
|
55
|
+
name: TOOL_NAMES.overview,
|
|
56
|
+
description: "Get the full outline (headings with line numbers), log profile (levels, time range, most frequent errors), and the first and last lines of a large attached file.",
|
|
57
|
+
parameters: { type: "object", properties: { document_id: documentId }, required: ["document_id"] },
|
|
58
|
+
},
|
|
59
|
+
analyze: {
|
|
60
|
+
name: TOOL_NAMES.analyze,
|
|
61
|
+
description: "Read an entire large file in parts and answer a task that needs all of it, such as a full summary, a timeline, or every occurrence of something. Slow and costly: prefer search_document and read_document for specific questions.",
|
|
62
|
+
parameters: {
|
|
63
|
+
type: "object",
|
|
64
|
+
properties: {
|
|
65
|
+
document_id: documentId,
|
|
66
|
+
task: { type: "string", description: "What to find or produce from the whole file, stated completely." },
|
|
67
|
+
},
|
|
68
|
+
required: ["document_id", "task"],
|
|
69
|
+
},
|
|
70
|
+
},
|
|
71
|
+
view: {
|
|
72
|
+
name: TOOL_NAMES.view,
|
|
73
|
+
description: `Look at pages of an attached PDF as they are printed. Use it when the answer depends on something the text of the file cannot show: a picture, photo, chart, diagram, map, handwriting, a stamp or signature, or how a page is laid out. It is not for reading text. Up to ${MAX_VIEW_PAGES} pages per call.`,
|
|
74
|
+
parameters: {
|
|
75
|
+
type: "object",
|
|
76
|
+
properties: {
|
|
77
|
+
document_id: { type: "string", description: "The document_id of the PDF." },
|
|
78
|
+
from_page: { type: "integer", description: "First page to look at (1-based, the N of the \"--- Page N ---\" lines in the text)." },
|
|
79
|
+
to_page: { type: "integer", description: "Last page to look at. Defaults to from_page." },
|
|
80
|
+
},
|
|
81
|
+
required: ["document_id", "from_page"],
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
/** Says so when a tool that returns files is run through `execute`, which has nowhere to put them. */
|
|
87
|
+
const FILES_NOT_DELIVERED = "The pages could not be shown: this application does not pass files from tools to the model. Answer from the text.";
|
|
88
|
+
|
|
89
|
+
function integer(value: unknown, fallback: number, min: number, max: number): number {
|
|
90
|
+
const number = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
|
|
91
|
+
// The fallback is clamped too: a default end line must not point past the end of the file.
|
|
92
|
+
return Math.min(max, Math.max(min, Math.trunc(Number.isFinite(number) ? number : fallback)));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const INCOMPLETE_ANALYSIS = "Incomplete: the model's output limit was reached, so some relevant items are missing from this answer. Tell the user it is incomplete. For a complete list or an exact count, use search_document in exact or regex mode (it returns total_matching_lines), or ask about a narrower part of the file.";
|
|
96
|
+
|
|
97
|
+
function text(value: unknown, name: string): string {
|
|
98
|
+
if (typeof value !== "string" || !value.trim()) throw new Error(`${name} is required.`);
|
|
99
|
+
return value;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** A page number given by the model. Unlike a line number it is not clamped: a wrong page is a wrong picture. */
|
|
103
|
+
function pageNumber(value: unknown, name: string): number {
|
|
104
|
+
const number = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : Number.NaN;
|
|
105
|
+
if (!Number.isFinite(number) || Math.trunc(number) < 1) throw new Error(`${name} must be a page number: 1 or higher.`);
|
|
106
|
+
return Math.trunc(number);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const pageRange = (from: number, to: number): string => (to > from ? `${from}-${to}` : String(from));
|
|
110
|
+
|
|
111
|
+
/** Trims a result to the character budget by dropping trailing list entries, then cutting text. */
|
|
112
|
+
function fit(result: ToolResult, listKey: string | null, limit: number): ToolResult {
|
|
113
|
+
if (JSON.stringify(result).length <= limit) return result;
|
|
114
|
+
const list = listKey ? result[listKey] : undefined;
|
|
115
|
+
if (Array.isArray(list)) {
|
|
116
|
+
const kept = [...list];
|
|
117
|
+
const note = () => `Showing ${kept.length} of ${list.length} results to stay within the size limit. Narrow the query or read specific lines.`;
|
|
118
|
+
const trimmed = () => ({ ...result, [listKey!]: kept, note: note() });
|
|
119
|
+
while (kept.length > 1 && JSON.stringify(trimmed()).length > limit) kept.pop();
|
|
120
|
+
if (JSON.stringify(trimmed()).length <= limit) return trimmed();
|
|
121
|
+
}
|
|
122
|
+
// Last resort: a raw prefix. Escaping grows the text, so shrink until the whole result fits.
|
|
123
|
+
const serialized = JSON.stringify(result);
|
|
124
|
+
let size = limit;
|
|
125
|
+
let cut: ToolResult;
|
|
126
|
+
do {
|
|
127
|
+
size = Math.floor(size * 0.85);
|
|
128
|
+
cut = { truncated: true, partial: serialized.slice(0, size), note: "Result cut to the size limit. Ask for a smaller range." };
|
|
129
|
+
} while (JSON.stringify(cut).length > limit && size > 100);
|
|
130
|
+
return cut;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* What a finished tool call found, as a suffix for its `describe()` label, for a steps list:
|
|
135
|
+
* "Search app.log (exact) for “timeout”" + " — 12 matching lines".
|
|
136
|
+
*/
|
|
137
|
+
export function toolResultSummary(label: string, result: ToolResult): string {
|
|
138
|
+
if (typeof result.error === "string") return ` — failed: ${result.error}`;
|
|
139
|
+
if (typeof result.total_matching_lines === "number") return ` — ${result.total_matching_lines.toLocaleString("en-US")} matching lines`;
|
|
140
|
+
if (Array.isArray(result.passages)) return ` — ${result.passages.length} passages`;
|
|
141
|
+
if (typeof result.parts_read === "number") {
|
|
142
|
+
const incomplete = result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
|
|
143
|
+
return ` — ${result.parts_read} parts, ${String(result.parts_with_relevant_content ?? 0)} relevant${incomplete}`;
|
|
144
|
+
}
|
|
145
|
+
// A read reports its range only when it was cut short of what was asked.
|
|
146
|
+
if (typeof result.lines === "string" && typeof result.total_lines === "number") return label.endsWith(result.lines) ? "" : ` — got ${result.lines}`;
|
|
147
|
+
// So does a look at pages.
|
|
148
|
+
if (typeof result.pages === "string" && typeof result.total_pages === "number") {
|
|
149
|
+
return label.endsWith(` ${result.pages}`) ? "" : ` — got ${result.pages.includes("-") ? "pages" : "page"} ${result.pages}`;
|
|
150
|
+
}
|
|
151
|
+
return "";
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function createDocumentTools(options: {
|
|
155
|
+
/** Loads a document the tools may access. Return undefined for anything out of scope. */
|
|
156
|
+
load(documentId: string): Promise<SearchableDocument | undefined>;
|
|
157
|
+
documentIds: string[];
|
|
158
|
+
/** File names by document ID, so `describe` can name files before they are loaded. */
|
|
159
|
+
names?: Record<string, string>;
|
|
160
|
+
budget: Budget;
|
|
161
|
+
generate?: GenerateText;
|
|
162
|
+
onProgress?: ProgressListener;
|
|
163
|
+
signal?: AbortSignal;
|
|
164
|
+
/**
|
|
165
|
+
* PDFs whose pages `view_pages` may show. The tool is declared only when there is at least one
|
|
166
|
+
* and `loadOriginal` is given. They need not be among `documentIds`: a PDF whose text is in the
|
|
167
|
+
* prompt has nothing to search, but its pages can still be looked at.
|
|
168
|
+
*/
|
|
169
|
+
viewableIds?: string[];
|
|
170
|
+
/** Loads the uploaded file of a document, for `view_pages`. */
|
|
171
|
+
loadOriginal?(documentId: string): Promise<Uint8Array | undefined>;
|
|
172
|
+
}): ToolSet {
|
|
173
|
+
const allowed = new Set(options.documentIds);
|
|
174
|
+
const viewable = new Set(options.loadOriginal ? options.viewableIds ?? [] : []);
|
|
175
|
+
const names = new Map<string, string>(Object.entries(options.names ?? {}));
|
|
176
|
+
// The text tools are left out only when there are pages to look at and no document to search.
|
|
177
|
+
const textTools = allowed.size > 0 || viewable.size === 0;
|
|
178
|
+
const declarations = [
|
|
179
|
+
...(textTools ? [DECLARATIONS.search, DECLARATIONS.read, DECLARATIONS.overview, ...(options.generate ? [DECLARATIONS.analyze] : [])] : []),
|
|
180
|
+
...(viewable.size > 0 ? [DECLARATIONS.view] : []),
|
|
181
|
+
];
|
|
182
|
+
const known = new Set(declarations.map((declaration) => declaration.name));
|
|
183
|
+
const limit = options.budget.toolResultCharacters;
|
|
184
|
+
// When no limit is given with a call: three eighths of a request, so that two looks still fit.
|
|
185
|
+
const defaultFileBytes = Math.floor((options.budget.maxRequestBytes - REQUEST_BYTES_MARGIN) * 3 / 8);
|
|
186
|
+
|
|
187
|
+
async function documentFor(args: Record<string, unknown>): Promise<SearchableDocument> {
|
|
188
|
+
const id = text(args.document_id, "document_id");
|
|
189
|
+
// Scope check: a model can only reach files attached to this conversation.
|
|
190
|
+
if (!allowed.has(id)) throw new Error(`Unknown document_id ${id}. Use an ID from a file card.`);
|
|
191
|
+
const document = await options.load(id);
|
|
192
|
+
if (!document) throw new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
|
|
193
|
+
names.set(id, document.meta.name);
|
|
194
|
+
return document;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const handlers: Record<string, (args: Record<string, unknown>) => Promise<ToolResult>> = {
|
|
198
|
+
async [TOOL_NAMES.search](args) {
|
|
199
|
+
const document = await documentFor(args);
|
|
200
|
+
const query = text(args.query, "query");
|
|
201
|
+
const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
|
|
202
|
+
// Page numbers are added only for a PDF whose pages can be looked at: they are what
|
|
203
|
+
// view_pages takes. Everything else gets the results of 0.2.0 unchanged.
|
|
204
|
+
const paged = viewable.has(document.meta.id);
|
|
205
|
+
if (mode === "keywords") {
|
|
206
|
+
const topK = integer(args.max_results, 5, 1, 10);
|
|
207
|
+
const ranked = rankPassages(document, query, topK);
|
|
208
|
+
return fit({
|
|
209
|
+
document: document.meta.name,
|
|
210
|
+
mode,
|
|
211
|
+
passages: ranked.map((passage) => {
|
|
212
|
+
const pages = paged ? document.pagesOfLines(passage.from, passage.to) : undefined;
|
|
213
|
+
return {
|
|
214
|
+
lines: `${passage.from}-${passage.to}`,
|
|
215
|
+
...(pages ? { pages } : {}),
|
|
216
|
+
score: passage.score,
|
|
217
|
+
text: document.lines.numbered(passage.from, passage.to),
|
|
218
|
+
};
|
|
219
|
+
}),
|
|
220
|
+
...(ranked.length === 0 ? { note: "No passage contains these keywords. Try other words, synonyms, or exact mode." } : {}),
|
|
221
|
+
}, "passages", limit);
|
|
222
|
+
}
|
|
223
|
+
const result = grep(document, query, {
|
|
224
|
+
regex: mode === "regex",
|
|
225
|
+
caseSensitive: args.case_sensitive === true,
|
|
226
|
+
maxResults: integer(args.max_results, 20, 1, 50),
|
|
227
|
+
contextLines: integer(args.context_lines, 0, 0, 5),
|
|
228
|
+
});
|
|
229
|
+
return fit({
|
|
230
|
+
document: document.meta.name,
|
|
231
|
+
mode,
|
|
232
|
+
total_matching_lines: result.totalMatchingLines,
|
|
233
|
+
...(result.stoppedEarly ? { note: "The scan stopped early; the total is a lower bound." } : {}),
|
|
234
|
+
matches: paged ? result.matches.map(({ line, ...rest }) => {
|
|
235
|
+
const page = document.pageOfLine(line);
|
|
236
|
+
return { line, ...(page ? { page } : {}), ...rest };
|
|
237
|
+
}) : result.matches,
|
|
238
|
+
}, "matches", limit);
|
|
239
|
+
},
|
|
240
|
+
|
|
241
|
+
async [TOOL_NAMES.read](args) {
|
|
242
|
+
const document = await documentFor(args);
|
|
243
|
+
const total = document.lines.lineCount;
|
|
244
|
+
const start = integer(args.start_line, 1, 1, total);
|
|
245
|
+
const end = integer(args.end_line, start + DEFAULT_READ_LINES - 1, start, Math.min(total, start + MAX_READ_LINES - 1));
|
|
246
|
+
let to = end;
|
|
247
|
+
let body = document.lines.numbered(start, to);
|
|
248
|
+
while (body.length > limit - 500 && to > start) {
|
|
249
|
+
to = start + Math.max(0, Math.floor((to - start) * 0.7));
|
|
250
|
+
body = document.lines.numbered(start, to);
|
|
251
|
+
}
|
|
252
|
+
const pages = viewable.has(document.meta.id) ? document.pagesOfLines(start, to) : undefined;
|
|
253
|
+
return {
|
|
254
|
+
document: document.meta.name,
|
|
255
|
+
lines: `${start}-${to}`,
|
|
256
|
+
...(pages ? { pages } : {}),
|
|
257
|
+
total_lines: total,
|
|
258
|
+
text: body.slice(0, limit - 500),
|
|
259
|
+
...(to < total ? { next_start_line: to + 1 } : { note: "End of file." }),
|
|
260
|
+
};
|
|
261
|
+
},
|
|
262
|
+
|
|
263
|
+
async [TOOL_NAMES.overview](args) {
|
|
264
|
+
const document = await documentFor(args);
|
|
265
|
+
const { meta, lines } = document;
|
|
266
|
+
const tail = Math.max(1, lines.lineCount - 19);
|
|
267
|
+
return fit({
|
|
268
|
+
document: meta.name,
|
|
269
|
+
format: meta.format,
|
|
270
|
+
size: formatBytes(meta.bytes),
|
|
271
|
+
lines: meta.lines,
|
|
272
|
+
estimated_tokens: meta.estimatedTokens,
|
|
273
|
+
...(meta.pages ? { pages: meta.pages } : {}),
|
|
274
|
+
parts_for_whole_document_analysis: splitIntoParts(document, options.budget).length,
|
|
275
|
+
...(meta.logProfile ? { log_profile: meta.logProfile } : {}),
|
|
276
|
+
first_lines: lines.numbered(1, Math.min(30, lines.lineCount)),
|
|
277
|
+
last_lines: lines.lineCount > 30 ? lines.numbered(tail, lines.lineCount) : "",
|
|
278
|
+
outline: meta.outline.length ? outlineLines(meta.outline) : [],
|
|
279
|
+
}, "outline", limit);
|
|
280
|
+
},
|
|
281
|
+
|
|
282
|
+
async [TOOL_NAMES.analyze](args) {
|
|
283
|
+
if (!options.generate) throw new Error("Whole-document analysis is not enabled.");
|
|
284
|
+
const document = await documentFor(args);
|
|
285
|
+
const task = text(args.task, "task");
|
|
286
|
+
const result = await analyzeWholeDocument({
|
|
287
|
+
document,
|
|
288
|
+
task,
|
|
289
|
+
generate: options.generate,
|
|
290
|
+
budget: options.budget,
|
|
291
|
+
onProgress: options.onProgress,
|
|
292
|
+
signal: options.signal,
|
|
293
|
+
});
|
|
294
|
+
const notesCutShort = result.truncatedParts + result.truncatedMerges;
|
|
295
|
+
return fit({
|
|
296
|
+
document: document.meta.name,
|
|
297
|
+
parts_read: result.parts,
|
|
298
|
+
parts_with_relevant_content: result.relevantParts,
|
|
299
|
+
...(result.failedParts ? { parts_that_failed: result.failedParts } : {}),
|
|
300
|
+
...(notesCutShort ? { notes_cut_short: notesCutShort } : {}),
|
|
301
|
+
...(result.answerTruncated ? { answer_cut_short: true } : {}),
|
|
302
|
+
...(notesCutShort || result.answerTruncated ? { note: INCOMPLETE_ANALYSIS } : {}),
|
|
303
|
+
answer: result.answer,
|
|
304
|
+
}, null, Math.max(limit, 40_000));
|
|
305
|
+
},
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
/** `view_pages`: the pages as one small PDF, next to a short JSON result. */
|
|
309
|
+
async function viewPages(args: Record<string, unknown>, limits: ToolFileLimits): Promise<ToolOutput> {
|
|
310
|
+
const id = text(args.document_id, "document_id");
|
|
311
|
+
// The same scope check as the text tools, on its own list: a PDF can be looked at without
|
|
312
|
+
// being searchable, and the other way round.
|
|
313
|
+
if (!viewable.has(id)) {
|
|
314
|
+
throw new Error(allowed.has(id)
|
|
315
|
+
? `The pages of ${names.get(id) ?? id} cannot be shown: only its text was kept. Answer from the text.`
|
|
316
|
+
: `Unknown document_id ${id}. Use the document_id of an attached PDF.`);
|
|
317
|
+
}
|
|
318
|
+
const document = await options.load(id);
|
|
319
|
+
if (!document) throw new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
|
|
320
|
+
const file = document.meta.name;
|
|
321
|
+
names.set(id, file);
|
|
322
|
+
const from = pageNumber(args.from_page, "from_page");
|
|
323
|
+
const asked = args.to_page === undefined || args.to_page === null ? from : pageNumber(args.to_page, "to_page");
|
|
324
|
+
if (asked < from) throw new Error(`to_page (${asked}) is before from_page (${from}).`);
|
|
325
|
+
const total = document.meta.pages;
|
|
326
|
+
if (total && from > total) throw new Error(`${file} has ${total} ${total === 1 ? "page" : "pages"}. There is no page ${from}.`);
|
|
327
|
+
const whole = (value: number | undefined, fallback: number) => (typeof value === "number" && Number.isFinite(value) ? Math.trunc(value) : fallback);
|
|
328
|
+
const mostPages = Math.min(MAX_VIEW_PAGES, whole(limits.maxPages, MAX_VIEW_PAGES));
|
|
329
|
+
if (mostPages < 1) throw new Error("No more pages can be looked at for this question. Answer from the pages and the text you already have.");
|
|
330
|
+
const maxBytes = whole(limits.maxFileBytes, defaultFileBytes);
|
|
331
|
+
if (maxBytes < MIN_FILE_BYTES) throw new Error("There is no room left in this request to show more pages. Answer from the pages and the text you already have.");
|
|
332
|
+
const original = await options.loadOriginal!(id);
|
|
333
|
+
if (!original) throw new Error(`The original file of ${file} is no longer on the server, so its pages cannot be shown. Answer from the text.`);
|
|
334
|
+
let cut;
|
|
335
|
+
try {
|
|
336
|
+
cut = await cutPdfPages(original, from, Math.min(asked, from + mostPages - 1), maxBytes, total);
|
|
337
|
+
} catch (error) {
|
|
338
|
+
throw new Error(`${file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
339
|
+
}
|
|
340
|
+
const pages = pageRange(cut.from, cut.to);
|
|
341
|
+
const shown = cut.to - cut.from + 1;
|
|
342
|
+
// What was asked for, as far as the file goes.
|
|
343
|
+
const wanted = Math.min(asked, cut.pageCount);
|
|
344
|
+
const showing = `Showing ${shown} of the ${wanted - cut.from + 1} pages asked for`;
|
|
345
|
+
const again = `Call view_pages from page ${cut.to + 1} if you need them.`;
|
|
346
|
+
const rest: ToolResult = cut.to >= wanted ? {}
|
|
347
|
+
: shown < mostPages ? { next_page: cut.to + 1, note: `${showing}: the others did not fit in this request. ${again}` }
|
|
348
|
+
: mostPages < MAX_VIEW_PAGES ? { note: `${showing}: no more pages can be looked at for this question.` }
|
|
349
|
+
: { next_page: cut.to + 1, note: `${showing}: one call shows at most ${MAX_VIEW_PAGES}. ${again}` };
|
|
350
|
+
const name = `pages-${pages}.pdf`;
|
|
351
|
+
return {
|
|
352
|
+
result: { document: file, pages, total_pages: cut.pageCount, file: name, ...rest },
|
|
353
|
+
files: [{ name, mimeType: "application/pdf", bytes: cut.bytes }],
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
const failure = (error: unknown): ToolResult => ({ error: error instanceof Error ? error.message : String(error) });
|
|
358
|
+
|
|
359
|
+
async function execute(name: string, args: Record<string, unknown>): Promise<ToolResult> {
|
|
360
|
+
if (!known.has(name)) return { error: `Unknown tool ${name}.` };
|
|
361
|
+
// The pages are a file, and this method returns only JSON. Saying that pages are attached
|
|
362
|
+
// with nothing attached would be worse than saying that they could not be shown.
|
|
363
|
+
if (name === TOOL_NAMES.view) return { error: FILES_NOT_DELIVERED };
|
|
364
|
+
try {
|
|
365
|
+
return await handlers[name]!(args);
|
|
366
|
+
} catch (error) {
|
|
367
|
+
if (options.signal?.aborted) throw error;
|
|
368
|
+
return failure(error);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
return {
|
|
373
|
+
declarations,
|
|
374
|
+
has: (name) => known.has(name),
|
|
375
|
+
execute,
|
|
376
|
+
async executeWithFiles(name, args, limits = {}) {
|
|
377
|
+
if (name !== TOOL_NAMES.view || !known.has(name)) return { result: await execute(name, args), files: [] };
|
|
378
|
+
try {
|
|
379
|
+
return await viewPages(args, limits);
|
|
380
|
+
} catch (error) {
|
|
381
|
+
if (options.signal?.aborted) throw error;
|
|
382
|
+
return { result: failure(error), files: [] };
|
|
383
|
+
}
|
|
384
|
+
},
|
|
385
|
+
describe(name, args) {
|
|
386
|
+
const id = typeof args.document_id === "string" ? args.document_id : "";
|
|
387
|
+
const file = names.get(id) ?? "the file";
|
|
388
|
+
if (name === TOOL_NAMES.view) {
|
|
389
|
+
// Read the numbers the way the tool will: a model sometimes sends them as text.
|
|
390
|
+
const from = integer(args.from_page, 1, 1, Number.MAX_SAFE_INTEGER);
|
|
391
|
+
const to = integer(args.to_page, from, from, Number.MAX_SAFE_INTEGER);
|
|
392
|
+
return `Look at ${file} ${to > from ? "pages" : "page"} ${pageRange(from, to)}`;
|
|
393
|
+
}
|
|
394
|
+
if (name === TOOL_NAMES.search) {
|
|
395
|
+
const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
|
|
396
|
+
return `Search ${file} (${mode}) for “${String(args.query ?? "").slice(0, 80)}”`;
|
|
397
|
+
}
|
|
398
|
+
if (name === TOOL_NAMES.read) {
|
|
399
|
+
const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
|
|
400
|
+
const end = typeof args.end_line === "number" && args.end_line >= start ? `-${Math.trunc(args.end_line)}` : "";
|
|
401
|
+
return `Read ${file} lines ${start}${end}`;
|
|
402
|
+
}
|
|
403
|
+
if (name === TOOL_NAMES.overview) return `Overview of ${file}`;
|
|
404
|
+
if (name === TOOL_NAMES.analyze) return `Read all of ${file} for “${String(args.task ?? "").slice(0, 100)}”`;
|
|
405
|
+
return name;
|
|
406
|
+
},
|
|
407
|
+
};
|
|
408
|
+
}
|