llm-large-files 0.9.0 → 0.10.1
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 +500 -0
- package/README.md +13 -7
- package/dist/access.d.ts +45 -3
- package/dist/access.d.ts.map +1 -1
- package/dist/access.js +106 -3
- package/dist/access.js.map +1 -1
- package/dist/aggregate.d.ts +6 -0
- package/dist/aggregate.d.ts.map +1 -1
- package/dist/aggregate.js +86 -13
- package/dist/aggregate.js.map +1 -1
- package/dist/analyze.d.ts +4 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +2 -2
- package/dist/analyze.js.map +1 -1
- package/dist/answer-info.d.ts +26 -0
- package/dist/answer-info.d.ts.map +1 -0
- package/dist/answer-info.js +32 -0
- package/dist/answer-info.js.map +1 -0
- package/dist/anthropic/adapter.d.ts +5 -1
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +35 -10
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +115 -14
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +572 -103
- package/dist/ask.js.map +1 -1
- package/dist/citations.d.ts +36 -0
- package/dist/citations.d.ts.map +1 -0
- package/dist/citations.js +298 -0
- package/dist/citations.js.map +1 -0
- package/dist/error-info.d.ts +13 -0
- package/dist/error-info.d.ts.map +1 -1
- package/dist/error-info.js +37 -1
- package/dist/error-info.js.map +1 -1
- package/dist/errors.d.ts +3 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +3 -1
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +27 -8
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +21 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +6 -1
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +35 -4
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +68 -29
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +28 -55
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +20 -27
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +59 -11
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +33 -7
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/errors.d.ts +39 -5
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +70 -9
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +53 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +100 -50
- 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/http.d.ts +41 -3
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +40 -2
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +7 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +9 -1
- package/dist/ingest.d.ts.map +1 -1
- package/dist/ingest.js +50 -25
- package/dist/ingest.js.map +1 -1
- package/dist/library.d.ts +129 -2
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +224 -149
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +176 -10
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +804 -58
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +36 -4
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +17 -1
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +29 -8
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +148 -126
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +1 -1
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.js +2 -2
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/spool.d.ts +9 -5
- package/dist/node/spool.d.ts.map +1 -1
- package/dist/node/spool.js +28 -15
- package/dist/node/spool.js.map +1 -1
- package/dist/node/sse.d.ts +6 -5
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +8 -7
- package/dist/node/sse.js.map +1 -1
- package/dist/openai/adapter.d.ts +5 -1
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +53 -12
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +2 -1
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +5 -2
- package/dist/output-limit.js.map +1 -1
- package/dist/pdf-outline.d.ts +71 -0
- package/dist/pdf-outline.d.ts.map +1 -0
- package/dist/pdf-outline.js +414 -0
- package/dist/pdf-outline.js.map +1 -0
- package/dist/plan.d.ts +137 -7
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +248 -26
- package/dist/plan.js.map +1 -1
- package/dist/prepare.d.ts +50 -0
- package/dist/prepare.d.ts.map +1 -0
- package/dist/prepare.js +207 -0
- package/dist/prepare.js.map +1 -0
- package/dist/ranged.d.ts +2 -1
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +16 -3
- package/dist/ranged.js.map +1 -1
- package/dist/search.d.ts +7 -0
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +72 -10
- package/dist/search.js.map +1 -1
- package/dist/stores.d.ts +6 -0
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +82 -11
- package/dist/stores.js.map +1 -1
- package/dist/tools.d.ts +22 -2
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +323 -76
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +49 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/whole-cost.d.ts +37 -0
- package/dist/whole-cost.d.ts.map +1 -0
- package/dist/whole-cost.js +46 -0
- package/dist/whole-cost.js.map +1 -0
- package/docs/README.md +4 -0
- package/docs/guides/anthropic.md +5 -2
- package/docs/guides/conversations.md +1 -1
- package/docs/guides/costs-and-limits.md +133 -36
- package/docs/guides/deployment.md +106 -13
- package/docs/guides/errors-and-reliability.md +158 -45
- package/docs/guides/explorer-model.md +4 -1
- package/docs/guides/openai-compatible.md +47 -7
- package/docs/guides/own-adapter-and-loop.md +33 -6
- package/docs/guides/pdfs.md +96 -7
- package/docs/guides/storage.md +46 -3
- package/docs/guides/testing.md +71 -0
- package/docs/guides/vertex-and-gemini.md +159 -50
- package/docs/guides/web-app.md +10 -6
- package/docs/how-it-works.md +120 -22
- package/docs/measurements.md +172 -5
- package/docs/publishing.md +76 -4
- package/docs/reference/anthropic.md +12 -7
- package/docs/reference/ask.md +264 -35
- package/docs/reference/errors-and-retries.md +30 -2
- package/docs/reference/events.md +27 -10
- package/docs/reference/gemini.md +189 -68
- package/docs/reference/library.md +190 -23
- package/docs/reference/node.md +51 -17
- package/docs/reference/openai.md +21 -10
- package/docs/reference/tools.md +273 -26
- package/docs/security.md +101 -12
- package/docs/troubleshooting.md +14 -12
- package/docs/upgrading-0.10.md +484 -0
- package/package.json +5 -1
- package/src/access.ts +127 -4
- package/src/aggregate.ts +92 -14
- package/src/analyze.ts +2 -2
- package/src/answer-info.ts +45 -0
- package/src/anthropic/adapter.ts +40 -11
- package/src/ask.ts +646 -106
- package/src/citations.ts +301 -0
- package/src/error-info.ts +36 -1
- package/src/errors.ts +3 -1
- package/src/events.ts +31 -7
- package/src/evidence.ts +21 -2
- package/src/extract.ts +6 -1
- package/src/gemini/adapter.ts +99 -32
- package/src/gemini/chat.ts +53 -82
- package/src/gemini/endpoints.ts +89 -16
- package/src/gemini/errors.ts +74 -11
- package/src/gemini/generate.ts +147 -57
- package/src/gemini/index.ts +3 -3
- package/src/http.ts +65 -4
- package/src/index.ts +7 -5
- package/src/ingest.ts +58 -27
- package/src/library.ts +336 -142
- package/src/map-reduce.ts +855 -67
- package/src/model.ts +44 -4
- package/src/node/handlers.ts +159 -118
- package/src/node/index.ts +1 -0
- package/src/node/ingest-child.ts +2 -2
- package/src/node/spool.ts +28 -14
- package/src/node/sse.ts +8 -7
- package/src/openai/adapter.ts +56 -13
- package/src/output-limit.ts +5 -2
- package/src/pdf-outline.ts +400 -0
- package/src/plan.ts +287 -36
- package/src/prepare.ts +253 -0
- package/src/ranged.ts +16 -3
- package/src/search.ts +69 -13
- package/src/stores.ts +76 -11
- package/src/tools.ts +327 -75
- package/src/types.ts +45 -1
- package/src/whole-cost.ts +64 -0
package/dist/tools.js
CHANGED
|
@@ -2,7 +2,7 @@ import { safeErrorMessage } from "./errors.js";
|
|
|
2
2
|
import { until } from "./http.js";
|
|
3
3
|
import { aggregateTable, FILTER_OPS, MAX_SHOWN_GROUPS } from "./aggregate.js";
|
|
4
4
|
import { GROUP_BY_VALUES, MAX_GROUP_KEYS } from "./groups.js";
|
|
5
|
-
import { analyzeWholeDocument, NothingReadError } from "./map-reduce.js";
|
|
5
|
+
import { analyzeWholeDocument, listWholeDocumentItems, MAX_ITEM_LABELS, MAX_LABEL_CHARACTERS, NothingReadError, storeGaveUp } from "./map-reduce.js";
|
|
6
6
|
import { cutPdfPages } from "./pdf-pages.js";
|
|
7
7
|
import { DocumentGoneError } from "./ranged.js";
|
|
8
8
|
import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS } from "./search.js";
|
|
@@ -86,12 +86,18 @@ const DECLARATIONS = {
|
|
|
86
86
|
},
|
|
87
87
|
analyze: {
|
|
88
88
|
name: TOOL_NAMES.analyze,
|
|
89
|
+
// 0.9.0's words, kept: with a sentence on items here, Gemini Flash-Lite stopped choosing the
|
|
90
|
+
// read for a full summary. What items do is said in the description of `output` alone.
|
|
89
91
|
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 items that must be judged by meaning. To count or list lines that contain a word, an ID or a pattern, use search_document in exact or regex mode instead: its count is exact, and this can miss items. Slow and costly: prefer search_document and read_document for specific questions.",
|
|
90
92
|
parameters: {
|
|
91
93
|
type: "object",
|
|
92
94
|
properties: {
|
|
93
95
|
document_id: documentId,
|
|
94
96
|
task: { type: "string", description: "What to find or produce from the whole file, stated completely." },
|
|
97
|
+
// "answer" is named for a summary and a timeline: told that items list things, Flash-Lite
|
|
98
|
+
// chose them for a timeline of events, whose items explain nothing, and lost events.
|
|
99
|
+
output: { type: "string", enum: ["answer", "items"], description: "\"answer\" (the default): one answer written from the notes of every part, for a summary, a timeline, or a description of events. \"items\": to count the items of a kind that must be judged by meaning, such as the clauses that set a fine: each part lists them, each with its line and a quote checked against the file, and the result counts them, by label." },
|
|
100
|
+
labels: { type: "array", items: { type: "string" }, description: `output "items" only: the kinds of item to label each one with, such as ["penalty", "deadline"]. Up to ${MAX_ITEM_LABELS}, each up to ${MAX_LABEL_CHARACTERS} characters.` },
|
|
95
101
|
},
|
|
96
102
|
required: ["document_id", "task"],
|
|
97
103
|
},
|
|
@@ -140,6 +146,18 @@ const DECLARATIONS = {
|
|
|
140
146
|
},
|
|
141
147
|
},
|
|
142
148
|
};
|
|
149
|
+
/** The keys of `DECLARATIONS` in the order a tool set declares them. */
|
|
150
|
+
const DECLARATION_ORDER = ["search", "read", "overview", "aggregate", "analyze", "view"];
|
|
151
|
+
/**
|
|
152
|
+
* The declarations of the tools `names`, in the order a tool set declares them (search, read,
|
|
153
|
+
* overview, aggregate, analyze, view), whatever the order of `names`: those `files.tools(…,
|
|
154
|
+
* { declare: names })` gives. For planning the size of a request before the tools are made. A name
|
|
155
|
+
* that is not a tool's is left out. New in 0.10.0.
|
|
156
|
+
*/
|
|
157
|
+
export function declarationsFor(names) {
|
|
158
|
+
const wanted = new Set(names);
|
|
159
|
+
return DECLARATION_ORDER.filter((key) => wanted.has(TOOL_NAMES[key])).map((key) => DECLARATIONS[key]);
|
|
160
|
+
}
|
|
143
161
|
/** Says so when a tool that returns files is run through `execute`, which has nowhere to put them. */
|
|
144
162
|
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.";
|
|
145
163
|
function integer(value, fallback, min, max) {
|
|
@@ -158,6 +176,57 @@ function flag(value) {
|
|
|
158
176
|
return typeof value === "string" && /^\s*(?:true|1)\s*$/i.test(value);
|
|
159
177
|
}
|
|
160
178
|
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.";
|
|
179
|
+
/** The note of a read that stopped merging at the question's limit on model requests (N12, new in 0.10.0). */
|
|
180
|
+
const notesLeftOutNote = (leftOut, relevant) => `Incomplete: this read reached the question's limit on model requests before it could combine the notes of every part, so the notes of ${leftOut} of the ${relevant} relevant parts are not in 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.`;
|
|
181
|
+
/** The items a read that lists them shows in its result; `total_items` counts them all. */
|
|
182
|
+
const MAX_SHOWN_ITEMS = 50;
|
|
183
|
+
/** The `labels` of a read that lists items, as the model sent them: up to `MAX_ITEM_LABELS`, each up to `MAX_LABEL_CHARACTERS`. */
|
|
184
|
+
function itemLabels(value) {
|
|
185
|
+
const list = stringList(value, "labels")?.map((label) => label.trim()).filter(Boolean);
|
|
186
|
+
if (!list || list.length === 0)
|
|
187
|
+
return undefined;
|
|
188
|
+
const distinct = [...new Set(list)];
|
|
189
|
+
if (distinct.length > MAX_ITEM_LABELS || distinct.some((label) => [...label].length > MAX_LABEL_CHARACTERS)) {
|
|
190
|
+
throw new Error(`labels takes up to ${MAX_ITEM_LABELS} labels, each up to ${MAX_LABEL_CHARACTERS} characters.`);
|
|
191
|
+
}
|
|
192
|
+
return distinct;
|
|
193
|
+
}
|
|
194
|
+
/** A task as a note quotes it: ending in a stop, so that the sentence after it starts as one. */
|
|
195
|
+
const quotedTask = (task) => {
|
|
196
|
+
const trimmed = task.trim();
|
|
197
|
+
return /[.!?…:;]$/u.test(trimmed) ? trimmed : `${trimmed}.`;
|
|
198
|
+
};
|
|
199
|
+
/** The sentence of a note on the items a result shows, when not all of them: as `itemsResult` and `fitItems` write it. */
|
|
200
|
+
const itemsShown = (shown, cut) => `The first ${shown} ${plural(shown, "item")} ${shown === 1 ? "is" : "are"} shown${cut ? ", to stay within the size limit" : ""}; total_items counts them all.`;
|
|
201
|
+
const ITEMS_SHOWN = /The first \d+ items? (?:is|are) shown(?:, to stay within the size limit)?; total_items counts them all\.\s*/;
|
|
202
|
+
/**
|
|
203
|
+
* The result of a read that lists items (`output: "items"`): the totals, counted by code from the
|
|
204
|
+
* items each part listed and checked against its lines, and the first items in the order of the file.
|
|
205
|
+
*/
|
|
206
|
+
function itemsResult(file, task, read) {
|
|
207
|
+
const shown = read.items.slice(0, MAX_SHOWN_ITEMS);
|
|
208
|
+
const more = read.items.length - shown.length;
|
|
209
|
+
const notes = [
|
|
210
|
+
// With items listed and none found on its line, the note on those that are not counted follows.
|
|
211
|
+
...(read.items.length === 0 ? [read.unverified > 0 ? `No item was found on its line for: ${quotedTask(task)}` : `No part of ${file} listed an item for: ${quotedTask(task)}`] : []),
|
|
212
|
+
...(more > 0 ? [itemsShown(shown.length, false)] : []),
|
|
213
|
+
...(read.unverified > 0 ? [`${read.unverified} listed ${plural(read.unverified, "item")} ${read.unverified === 1 ? "is" : "are"} not counted: ${read.unverified === 1 ? "its" : "their"} quote is not on the line ${read.unverified === 1 ? "it names" : "they name"}, nor on just one other line of the part.`] : []),
|
|
214
|
+
...(read.failedParts > 0 ? [`${read.failedParts} ${plural(read.failedParts, "part")} could not be read (${read.firstFailure ?? "see the notes"}), so items may be missing: tell the user the count may be incomplete.`] : []),
|
|
215
|
+
...(read.truncatedParts > 0 ? [`${read.truncatedParts} ${plural(read.truncatedParts, "part")} listed more items than fit the model's output limit, even read in smaller pieces, so items may be missing: tell the user the count may be incomplete.`] : []),
|
|
216
|
+
];
|
|
217
|
+
return {
|
|
218
|
+
document: file,
|
|
219
|
+
total_items: read.items.length,
|
|
220
|
+
...(Object.keys(read.countsByLabel).length > 0 ? { counts_by_label: read.countsByLabel } : {}),
|
|
221
|
+
items: shown.map(({ line, label, value, quote }) => ({ line, ...(label !== undefined ? { label } : {}), ...(value !== undefined ? { value } : {}), quote })),
|
|
222
|
+
...(more > 0 ? { more_items: more } : {}),
|
|
223
|
+
unverified_items: read.unverified,
|
|
224
|
+
parts_read: read.parts,
|
|
225
|
+
...(read.failedParts > 0 ? { parts_failed: read.failedParts } : {}),
|
|
226
|
+
...(read.truncatedParts > 0 ? { parts_cut_short: read.truncatedParts } : {}),
|
|
227
|
+
...(notes.length > 0 ? { note: notes.join(" ") } : {}),
|
|
228
|
+
};
|
|
229
|
+
}
|
|
161
230
|
function text(value, name) {
|
|
162
231
|
if (typeof value !== "string" || !value.trim())
|
|
163
232
|
throw new Error(`${name} is required.`);
|
|
@@ -201,9 +270,13 @@ function fit(result, listKey, limit) {
|
|
|
201
270
|
}
|
|
202
271
|
/**
|
|
203
272
|
* The result of a whole-document read within `limit` characters: its answer is cut at the end,
|
|
204
|
-
* and says so, rather than the result being cut as JSON, which loses what the other fields say.
|
|
273
|
+
* and says so, rather than the result being cut as JSON, which loses what the other fields say. A
|
|
274
|
+
* read that lists items (`output: "items"`, new in 0.10.0) loses items from the end of its list,
|
|
275
|
+
* and keeps its counts.
|
|
205
276
|
*/
|
|
206
277
|
export function fitAnswer(result, limit) {
|
|
278
|
+
if (JSON.stringify(result).length > limit && typeof result.answer !== "string" && Array.isArray(result.items) && result.items.length > 0)
|
|
279
|
+
return fitItems(result, limit);
|
|
207
280
|
if (JSON.stringify(result).length <= limit || typeof result.answer !== "string")
|
|
208
281
|
return fit(result, null, limit);
|
|
209
282
|
const answer = result.answer;
|
|
@@ -225,6 +298,35 @@ export function fitAnswer(result, limit) {
|
|
|
225
298
|
}
|
|
226
299
|
return fit(cutAt(low), null, limit);
|
|
227
300
|
}
|
|
301
|
+
/**
|
|
302
|
+
* The result of a read that lists items within `limit` characters: items are dropped from the end of
|
|
303
|
+
* its list, at least one kept, `more_items` counts every item not shown, and the note says how many
|
|
304
|
+
* are shown. Its counts stay whole. A result cut before (`askWithFiles` fits a result again to the
|
|
305
|
+
* room left) is cut the same way, from what it still shows.
|
|
306
|
+
*/
|
|
307
|
+
function fitItems(result, limit) {
|
|
308
|
+
const items = result.items;
|
|
309
|
+
const total = typeof result.total_items === "number" ? result.total_items : items.length;
|
|
310
|
+
const others = typeof result.note === "string" ? result.note.replace(ITEMS_SHOWN, "").trim() : "";
|
|
311
|
+
const build = (kept) => {
|
|
312
|
+
const more = total - kept;
|
|
313
|
+
const out = {};
|
|
314
|
+
// The fields in their order, with more_items after the items.
|
|
315
|
+
for (const [key, value] of Object.entries(result)) {
|
|
316
|
+
if (key === "more_items" || key === "note")
|
|
317
|
+
continue;
|
|
318
|
+
out[key] = key === "items" ? items.slice(0, kept) : value;
|
|
319
|
+
if (key === "items" && more > 0)
|
|
320
|
+
out.more_items = more;
|
|
321
|
+
}
|
|
322
|
+
out.note = [itemsShown(kept, true), others].filter(Boolean).join(" ");
|
|
323
|
+
return out;
|
|
324
|
+
};
|
|
325
|
+
let kept = items.length;
|
|
326
|
+
while (kept > 1 && JSON.stringify(build(kept)).length > limit)
|
|
327
|
+
kept--;
|
|
328
|
+
return fit(build(kept), null, limit);
|
|
329
|
+
}
|
|
228
330
|
/**
|
|
229
331
|
* The result of an exact or regex search that read the whole file: the first matches, then the
|
|
230
332
|
* last one of the file, and a note that says how many of how many are shown when that is not all.
|
|
@@ -583,6 +685,9 @@ export function alreadyShown(call, earlier, stored = false) {
|
|
|
583
685
|
return undefined;
|
|
584
686
|
if (result.dropped === true || result.already_shown === true || typeof result.error === "string" || result.truncated === true)
|
|
585
687
|
return undefined;
|
|
688
|
+
// A result the application replaced (`onToolResult`, since 0.10.0) does not hold what the call returns.
|
|
689
|
+
if (result.redacted === true)
|
|
690
|
+
return undefined;
|
|
586
691
|
// A search stored by 0.7.0 with case_sensitive or whole_word as text or 1 ("true", 1): 0.7.0 read
|
|
587
692
|
// those as off, 0.8.0 as on, so the call made now would not return what was stored.
|
|
588
693
|
if (stored && call.name === TOOL_NAMES.search && [earlier.call.args.case_sensitive, earlier.call.args.whole_word].some((value) => value !== undefined && value !== true && value !== false && flag(value)))
|
|
@@ -662,8 +767,13 @@ export function toolResultSummary(label, result) {
|
|
|
662
767
|
const groups = typeof result.total_groups === "number" ? `, ${result.total_groups.toLocaleString("en-US")} ${plural(result.total_groups, "group")}` : "";
|
|
663
768
|
return ` — ${result.rows_matched.toLocaleString("en-US")} ${plural(result.rows_matched, "row")}${groups}`;
|
|
664
769
|
}
|
|
770
|
+
if (typeof result.total_items === "number" && typeof result.parts_read === "number") {
|
|
771
|
+
const unverified = typeof result.unverified_items === "number" && result.unverified_items > 0 ? `, ${result.unverified_items.toLocaleString("en-US")} not counted` : "";
|
|
772
|
+
const incomplete = result.parts_failed || result.parts_cut_short ? ", incomplete" : "";
|
|
773
|
+
return ` — ${result.total_items.toLocaleString("en-US")} ${plural(result.total_items, "item")} in ${result.parts_read} ${plural(result.parts_read, "part")}${unverified}${incomplete}`;
|
|
774
|
+
}
|
|
665
775
|
if (typeof result.parts_read === "number") {
|
|
666
|
-
const incomplete = result.notes_only ? ", notes only" : result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
|
|
776
|
+
const incomplete = result.notes_only ? ", notes only" : result.notes_cut_short || result.notes_left_out || result.answer_cut_short ? ", incomplete" : "";
|
|
667
777
|
return ` — ${result.parts_read} ${plural(result.parts_read, "part")}, ${String(result.parts_with_relevant_content ?? 0)} relevant${incomplete}`;
|
|
668
778
|
}
|
|
669
779
|
// A read reports its range only when it was cut short of what was asked.
|
|
@@ -713,19 +823,38 @@ export function createDocumentTools(options) {
|
|
|
713
823
|
const allowed = new Set(options.documentIds);
|
|
714
824
|
const viewable = new Set(options.loadOriginal ? options.viewableIds ?? [] : []);
|
|
715
825
|
const names = new Map(Object.entries(options.names ?? {}));
|
|
826
|
+
const inline = new Set(options.inline ?? []);
|
|
827
|
+
const declared = options.declare ? new Set(options.declare) : undefined;
|
|
716
828
|
// The text tools are left out only when there are pages to look at and no document to search.
|
|
717
829
|
const textTools = allowed.size > 0 || viewable.size === 0;
|
|
718
|
-
const declarations = [
|
|
830
|
+
const declarations = options.declare ? declarationsFor(options.declare) : [
|
|
719
831
|
...(textTools ? [DECLARATIONS.search, DECLARATIONS.read, DECLARATIONS.overview, ...(options.tables ? [DECLARATIONS.aggregate] : []), ...(options.generate && options.wholeReads !== false ? [DECLARATIONS.analyze] : [])] : []),
|
|
720
832
|
...(viewable.size > 0 ? [DECLARATIONS.view] : []),
|
|
721
833
|
];
|
|
722
834
|
const known = new Set(declarations.map((declaration) => declaration.name));
|
|
723
|
-
//
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
835
|
+
// With `declare`, the tool set answers the tools it declares and no other: a call of one it does
|
|
836
|
+
// not declare (a whole-file read, many requests) is not run.
|
|
837
|
+
if (!declared) {
|
|
838
|
+
// Answered for any document, declared or not: a model may know the tool from earlier in the conversation.
|
|
839
|
+
if (textTools)
|
|
840
|
+
known.add(TOOL_NAMES.aggregate);
|
|
841
|
+
// Not declared for files that are all too large for it, but still answered: with the reason, not "unknown tool".
|
|
842
|
+
if (textTools && options.generate)
|
|
843
|
+
known.add(TOOL_NAMES.analyze);
|
|
844
|
+
}
|
|
845
|
+
/**
|
|
846
|
+
* Why a declared tool cannot run in this tool set, when it cannot: each call of it answers with
|
|
847
|
+
* this. A caller may declare a tool (`ToolOptions.declare`) that has nothing to work on here.
|
|
848
|
+
*/
|
|
849
|
+
const cannotRun = (name) => {
|
|
850
|
+
if (!declared?.has(name))
|
|
851
|
+
return undefined;
|
|
852
|
+
if (name === TOOL_NAMES.aggregate && !options.tables)
|
|
853
|
+
return "No attached file has a table: aggregate_table needs one.";
|
|
854
|
+
if (name === TOOL_NAMES.view && viewable.size === 0)
|
|
855
|
+
return "No attached file has pages to look at: view_pages needs a PDF whose original file is kept. Answer from the text.";
|
|
856
|
+
return undefined;
|
|
857
|
+
};
|
|
729
858
|
const cap = options.budget.toolResultCharacters;
|
|
730
859
|
/** The cap on the result of one call: the tool set's own, or the room its caller has left when that is less. */
|
|
731
860
|
const limitOf = (limits, own = cap) => {
|
|
@@ -755,11 +884,55 @@ export function createDocumentTools(options) {
|
|
|
755
884
|
const wholeReads = new Map();
|
|
756
885
|
/** Why the last whole-document read of a document failed, when no part of it could be read. */
|
|
757
886
|
const failedWholeReads = new Map();
|
|
887
|
+
const wholeReadsDeclared = declarations.some((declaration) => declaration.name === TOOL_NAMES.analyze);
|
|
888
|
+
/**
|
|
889
|
+
* What a `read_document` result cut short of its range by the size limit adds (`whole_file`), as
|
|
890
|
+
* the lines it shows of the file from `start` (`shown`, or none whole when `cut`: the text of the
|
|
891
|
+
* first line was cut): that `analyze_whole_document` reads all of it. Gemini Flash-Lite and Flash
|
|
892
|
+
* read a contract to summarize in ranges of about 16 lines, and answered from those
|
|
893
|
+
* (`evals/results/0100-t-live-3.md`). Only when this tool set declares the read and would run it on
|
|
894
|
+
* the file, by the estimate of its parts: a part reader, a file not sent whole, a read of it left,
|
|
895
|
+
* and its parts within `maxMapChunks` and within the requests the call says a whole read may make
|
|
896
|
+
* (`limits.maxRequests`), the checks the read makes before it sends a part (`partsToRead`). The
|
|
897
|
+
* parts are `estimateParts`'s, without the margin `canBeReadWhole` gives the estimate. The read
|
|
898
|
+
* counts its own, and at a border may count one more than the estimate: then it is refused, before
|
|
899
|
+
* it sends a request. `askWithFiles` gives a read 0 requests when the question would not start a
|
|
900
|
+
* whole read of its file on the next turn, the first the model can call it on (its ceilings on
|
|
901
|
+
* input tokens and requests, with that turn's request counted, its whole reads made). New in 0.10.0.
|
|
902
|
+
*/
|
|
903
|
+
const wholeFileHint = (document, start, shown, cut, limits) => {
|
|
904
|
+
const id = document.meta.id;
|
|
905
|
+
if (!wholeReadsDeclared || !options.generate || inline.has(id) || failedWholeReads.has(id) || (wholeReads.get(id) ?? 0) >= maxWholeReads)
|
|
906
|
+
return undefined;
|
|
907
|
+
const requests = typeof limits.maxRequests === "number" && !Number.isNaN(limits.maxRequests) ? limits.maxRequests : Number.POSITIVE_INFINITY;
|
|
908
|
+
// Every part is one request.
|
|
909
|
+
if (requests < 1)
|
|
910
|
+
return undefined;
|
|
911
|
+
const parts = estimateParts(document.meta, options.budget);
|
|
912
|
+
// Metadata that does not give its size (a record an application kept in part): as `canBeReadWhole`, not held back.
|
|
913
|
+
if (Number.isFinite(parts) && (parts > options.budget.maxMapChunks || parts > requests))
|
|
914
|
+
return undefined;
|
|
915
|
+
const total = document.lineCount.toLocaleString("en-US");
|
|
916
|
+
const fitting = cut
|
|
917
|
+
? `Not even one line fits here: the text of line ${start.toLocaleString("en-US")} is cut.`
|
|
918
|
+
: `Only ${shown.toLocaleString("en-US")} ${shown === 1 ? "line fits" : "lines fit"} here.`;
|
|
919
|
+
return `${fitting} To read all ${total} lines for a task that needs all of them, such as a full summary or a timeline, use analyze_whole_document.`;
|
|
920
|
+
};
|
|
758
921
|
// When no limit is given with a call: three eighths of a request, so that two looks still fit.
|
|
759
922
|
const defaultFileBytes = Math.floor((options.budget.maxRequestBytes - REQUEST_BYTES_MARGIN) * 3 / 8);
|
|
760
923
|
/** The documents the calls under way loaded, by the arguments of the call: checked once it ends (`checkRead`). */
|
|
761
924
|
const loaded = new WeakMap();
|
|
762
|
-
|
|
925
|
+
/**
|
|
926
|
+
* The signal of one call: the tool set's, joined with the call's own (`ToolCallHooks.signal`, new
|
|
927
|
+
* in 0.10.0) when it has one. The call's own ends that call alone.
|
|
928
|
+
*/
|
|
929
|
+
const signalOf = (hooks) => {
|
|
930
|
+
const own = hooks.signal;
|
|
931
|
+
if (!own)
|
|
932
|
+
return options.signal;
|
|
933
|
+
return options.signal ? AbortSignal.any([options.signal, own]) : own;
|
|
934
|
+
};
|
|
935
|
+
async function documentFor(args, signal) {
|
|
763
936
|
const id = text(args.document_id, "document_id");
|
|
764
937
|
// Scope check: a model can only reach files attached to this conversation.
|
|
765
938
|
if (!allowed.has(id)) {
|
|
@@ -769,7 +942,8 @@ export function createDocumentTools(options) {
|
|
|
769
942
|
? `Unknown document_id ${shownId(id)}. No attached file is read with this tool in this conversation.`
|
|
770
943
|
: `Unknown document_id ${shownId(id)}. Use one of: ${usable.join(", ")}${allowed.size > 20 ? ", …" : ""}.`);
|
|
771
944
|
}
|
|
772
|
-
|
|
945
|
+
// A load that hangs does not hold a call that was stopped.
|
|
946
|
+
const document = await until(options.load(id), signal);
|
|
773
947
|
if (!document)
|
|
774
948
|
throw gone(id);
|
|
775
949
|
for (const reads of loaded.get(args) ?? [])
|
|
@@ -780,10 +954,10 @@ export function createDocumentTools(options) {
|
|
|
780
954
|
/**
|
|
781
955
|
* Waits for the turn of a look at pages of `file`, for at most `pageLookWaitMs`, or the call's
|
|
782
956
|
* `maxWaitMs` when that is less. Returns the function that gives the turn back. Past the wait, a
|
|
783
|
-
* `PagesBusyError`. The wait ends at once when the
|
|
784
|
-
* stopped for.
|
|
957
|
+
* `PagesBusyError`. The wait ends at once when the call is stopped (`signal`), with the reason it
|
|
958
|
+
* was stopped for.
|
|
785
959
|
*/
|
|
786
|
-
async function pageLookTurn(id, file, limits) {
|
|
960
|
+
async function pageLookTurn(id, file, limits, signal) {
|
|
787
961
|
const turns = options.pageLooks;
|
|
788
962
|
if (!turns)
|
|
789
963
|
return () => undefined;
|
|
@@ -793,10 +967,10 @@ export function createDocumentTools(options) {
|
|
|
793
967
|
const timer = waitMs <= LONGEST_WAIT_MS ? setTimeout(() => waited.abort(), waitMs) : undefined;
|
|
794
968
|
timer?.unref?.();
|
|
795
969
|
try {
|
|
796
|
-
return await turns.limiter.acquire(
|
|
970
|
+
return await turns.limiter.acquire(signal ? AbortSignal.any([signal, waited.signal]) : waited.signal);
|
|
797
971
|
}
|
|
798
972
|
catch (error) {
|
|
799
|
-
if (
|
|
973
|
+
if (signal?.aborted || !waited.signal.aborted)
|
|
800
974
|
throw error;
|
|
801
975
|
throw new PagesBusyError(id, file);
|
|
802
976
|
}
|
|
@@ -806,10 +980,10 @@ export function createDocumentTools(options) {
|
|
|
806
980
|
}
|
|
807
981
|
/**
|
|
808
982
|
* The original file of a look, read while the look holds its turn: for at most `holdMs`, and
|
|
809
|
-
* only while the
|
|
983
|
+
* only while the call runs. A read given up on goes on, but holds no turn.
|
|
810
984
|
*/
|
|
811
|
-
async function originalOf(id, file) {
|
|
812
|
-
const reading = until(options.loadOriginal(id),
|
|
985
|
+
async function originalOf(id, file, signal) {
|
|
986
|
+
const reading = until(options.loadOriginal(id), signal);
|
|
813
987
|
const holdMs = options.pageLooks?.holdMs;
|
|
814
988
|
if (holdMs === undefined || !(holdMs <= LONGEST_WAIT_MS))
|
|
815
989
|
return reading;
|
|
@@ -826,10 +1000,11 @@ export function createDocumentTools(options) {
|
|
|
826
1000
|
clearTimeout(timer);
|
|
827
1001
|
}
|
|
828
1002
|
}
|
|
1003
|
+
/** The tools that return JSON. `signal` is the call's (`signalOf`). */
|
|
829
1004
|
const handlers = {
|
|
830
|
-
async [TOOL_NAMES.search](args, limits) {
|
|
1005
|
+
async [TOOL_NAMES.search](args, limits, _hooks, signal) {
|
|
831
1006
|
const limit = limitOf(limits);
|
|
832
|
-
const document = await documentFor(args);
|
|
1007
|
+
const document = await documentFor(args, signal);
|
|
833
1008
|
const query = text(args.query, "query");
|
|
834
1009
|
const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
|
|
835
1010
|
// Page numbers are added only for a PDF whose pages can be looked at: they are what
|
|
@@ -850,7 +1025,7 @@ export function createDocumentTools(options) {
|
|
|
850
1025
|
if (groupBy)
|
|
851
1026
|
throw new Error("group_by counts the lines of an exact or regex search: use mode \"exact\" or \"regex\".");
|
|
852
1027
|
const topK = integer(args.max_results, 5, 1, 10);
|
|
853
|
-
const ranked = await rankSource(document, query, topK,
|
|
1028
|
+
const ranked = await rankSource(document, query, topK, signal, ranged ? range : undefined);
|
|
854
1029
|
const texts = await Promise.all(ranked.map((passage) => document.readLines(passage.from, passage.to)));
|
|
855
1030
|
return fit({
|
|
856
1031
|
document: document.meta.name,
|
|
@@ -881,7 +1056,7 @@ export function createDocumentTools(options) {
|
|
|
881
1056
|
maxResults: integer(args.max_results, DEFAULT_GREP_RESULTS, 1, MAX_GREP_RESULTS),
|
|
882
1057
|
contextLines: integer(args.context_lines, 0, 0, 5),
|
|
883
1058
|
...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
|
|
884
|
-
...(
|
|
1059
|
+
...(signal ? { signal } : {}),
|
|
885
1060
|
...(ranged ? { fromLine: range.from, toLine: range.to } : {}),
|
|
886
1061
|
...(order === "last" ? { order } : {}),
|
|
887
1062
|
...(groupBy ? { groupBy } : {}),
|
|
@@ -928,9 +1103,9 @@ export function createDocumentTools(options) {
|
|
|
928
1103
|
matches,
|
|
929
1104
|
}, "matches", limit);
|
|
930
1105
|
},
|
|
931
|
-
async [TOOL_NAMES.read](args, limits) {
|
|
1106
|
+
async [TOOL_NAMES.read](args, limits, _hooks, signal) {
|
|
932
1107
|
const limit = limitOf(limits);
|
|
933
|
-
const document = await documentFor(args);
|
|
1108
|
+
const document = await documentFor(args, signal);
|
|
934
1109
|
const total = document.lineCount;
|
|
935
1110
|
const start = integer(args.start_line, 1, 1, total);
|
|
936
1111
|
const end = integer(args.end_line, start + DEFAULT_READ_LINES - 1, start, Math.min(total, start + MAX_READ_LINES - 1));
|
|
@@ -945,20 +1120,28 @@ export function createDocumentTools(options) {
|
|
|
945
1120
|
body = numberLines(read.slice(0, to - start + 1), start);
|
|
946
1121
|
}
|
|
947
1122
|
const pages = viewable.has(document.meta.id) ? document.pagesOfLines(start, to) : undefined;
|
|
948
|
-
|
|
1123
|
+
const cut = !fits(body);
|
|
1124
|
+
const result = {
|
|
949
1125
|
document: document.meta.name,
|
|
950
1126
|
lines: `${start}-${to}`,
|
|
951
1127
|
...(pages ? { pages } : {}),
|
|
952
1128
|
total_lines: total,
|
|
953
|
-
text:
|
|
1129
|
+
text: cut ? sliceWhole(body, Math.floor((limit - 500) / 2)) : body,
|
|
954
1130
|
// One line longer than the room: its text was cut, so the lines are not all shown.
|
|
955
|
-
...(
|
|
1131
|
+
...(cut ? { text_cut: true } : {}),
|
|
956
1132
|
...(to < total ? { next_start_line: to + 1 } : { note: "End of file." }),
|
|
957
1133
|
};
|
|
1134
|
+
// Cut short of the range asked by the size limit: the way to all of the file, when there is
|
|
1135
|
+
// one. Left out when it would take the result past its cap.
|
|
1136
|
+
const hint = to < end ? wholeFileHint(document, start, to - start + 1, cut, limits) : undefined;
|
|
1137
|
+
if (!hint)
|
|
1138
|
+
return result;
|
|
1139
|
+
const hinted = { ...result, whole_file: hint };
|
|
1140
|
+
return JSON.stringify(hinted).length <= limit ? hinted : result;
|
|
958
1141
|
},
|
|
959
|
-
async [TOOL_NAMES.overview](args, limits) {
|
|
1142
|
+
async [TOOL_NAMES.overview](args, limits, _hooks, signal) {
|
|
960
1143
|
const limit = limitOf(limits);
|
|
961
|
-
const document = await documentFor(args);
|
|
1144
|
+
const document = await documentFor(args, signal);
|
|
962
1145
|
const { meta, lineCount } = document;
|
|
963
1146
|
const tail = Math.max(1, lineCount - 19);
|
|
964
1147
|
// Counting the parts means reading the whole text, for a number that only says how costly a
|
|
@@ -982,11 +1165,11 @@ export function createDocumentTools(options) {
|
|
|
982
1165
|
outline: meta.outline.length ? outlineLines(meta.outline) : [],
|
|
983
1166
|
}, "outline", limit);
|
|
984
1167
|
},
|
|
985
|
-
async [TOOL_NAMES.aggregate](args, limits) {
|
|
1168
|
+
async [TOOL_NAMES.aggregate](args, limits, _hooks, signal) {
|
|
986
1169
|
const limit = limitOf(limits);
|
|
987
|
-
const document = await documentFor(args);
|
|
1170
|
+
const document = await documentFor(args, signal);
|
|
988
1171
|
const request = aggregateRequest(args);
|
|
989
|
-
const result = await aggregateTable(document, request,
|
|
1172
|
+
const result = await aggregateTable(document, request, signal);
|
|
990
1173
|
const groups = result.groups.map((group) => ({
|
|
991
1174
|
...(Object.keys(group.key).length > 0 ? { group: group.key } : {}),
|
|
992
1175
|
...group.values,
|
|
@@ -1010,24 +1193,41 @@ export function createDocumentTools(options) {
|
|
|
1010
1193
|
...(result.repeatedHeaders > 0 ? { repeated_header_rows: result.repeatedHeaders } : {}),
|
|
1011
1194
|
...(result.distinctCapped ? { distinct_note: "count_distinct stopped telling values apart after 1,000,000 in all: its counts are lower bounds. Filter, or group by fewer values." } : {}),
|
|
1012
1195
|
...(result.irregularRows > 0 ? { irregular_rows: result.irregularRows, irregular_note: "Rows with values past the header's columns: check columns and header_rows." } : {}),
|
|
1196
|
+
// A filter whose value named a column compared two cells of each row (since 0.10.0): said, so that no one takes it for a value.
|
|
1197
|
+
...(result.compared ? { filter_note: result.compared.map((one) => `Each row's ${JSON.stringify(one.column)} was compared with its own ${JSON.stringify(one.with)} (${one.op}), as the filter's value names that column.`).join(" ") } : {}),
|
|
1013
1198
|
};
|
|
1014
1199
|
const note = groups.length < result.totalGroups
|
|
1015
1200
|
? { note: `${groups.length} of the ${result.totalGroups} groups are shown, ${request.orderBy === "key" ? "in the order of their values" : "the largest first"}. Raise limit, or filter, for the others.` }
|
|
1016
1201
|
: {};
|
|
1017
|
-
|
|
1202
|
+
// Over a table shown in full, Flash-Lite answered with the count alone, citing no line: the
|
|
1203
|
+
// result says how to cite the lines it lists, with the file's name (since 0.10.0).
|
|
1204
|
+
const firstLines = groups[0]?.lines ?? [];
|
|
1205
|
+
const cite = inline.has(document.meta.id) && firstLines.length > 0
|
|
1206
|
+
? { cite: `Cite the lines listed in your answer, like (${document.meta.name} ${firstLines.map((line) => `L${line}`).join(", ")}).` }
|
|
1207
|
+
: {};
|
|
1208
|
+
return fit({ ...base, ...note, groups, ...cite }, "groups", limit);
|
|
1018
1209
|
},
|
|
1019
|
-
async [TOOL_NAMES.analyze](args, limits, hooks) {
|
|
1210
|
+
async [TOOL_NAMES.analyze](args, limits, hooks, signal) {
|
|
1020
1211
|
if (!options.generate)
|
|
1021
1212
|
throw new Error("Whole-document analysis is not enabled.");
|
|
1022
|
-
|
|
1213
|
+
// A document sent whole is not read again in parts: the model has every line of it.
|
|
1214
|
+
const asked = text(args.document_id, "document_id");
|
|
1215
|
+
if (inline.has(asked))
|
|
1216
|
+
throw new Error(`${names.get(asked) ?? shownId(asked)} is shown in full above: answer from it, and use search_document or aggregate_table for exact counts.`);
|
|
1217
|
+
const document = await documentFor(args, signal);
|
|
1023
1218
|
const task = text(args.task, "task");
|
|
1219
|
+
const items = args.output === "items";
|
|
1220
|
+
// Read before the count is taken: a call with labels it cannot use is no read.
|
|
1221
|
+
const labels = items ? itemLabels(args.labels) : undefined;
|
|
1024
1222
|
// A read of the whole file is many model requests. A model that asks for it again, with the
|
|
1025
1223
|
// task put another way, is told to use what it has. The count is taken before the read
|
|
1026
1224
|
// starts, so that two calls in one turn do not both pass.
|
|
1027
1225
|
const id = document.meta.id;
|
|
1028
1226
|
const reads = wholeReads.get(id) ?? 0;
|
|
1029
|
-
|
|
1030
|
-
|
|
1227
|
+
const failure = failedWholeReads.get(id);
|
|
1228
|
+
// A read that could read no part is not tried again, whatever the cap: another would most
|
|
1229
|
+
// likely fail the same way, and `wholeReadsLeft` says 0 for it.
|
|
1230
|
+
if (reads >= maxWholeReads || failure !== undefined) {
|
|
1031
1231
|
throw new Error(maxWholeReads === 0
|
|
1032
1232
|
? `Whole-file reads are turned off for this question. Use search_document and read_document on ${document.meta.name}.`
|
|
1033
1233
|
: failure !== undefined
|
|
@@ -1036,20 +1236,21 @@ export function createDocumentTools(options) {
|
|
|
1036
1236
|
: `${document.meta.name} was already read whole for this question${maxWholeReads > 1 ? ` ${maxWholeReads} times` : ""}, and is not read whole again. Use the answer of that read, or search_document and read_document for the details.`);
|
|
1037
1237
|
}
|
|
1038
1238
|
wholeReads.set(id, reads + 1);
|
|
1239
|
+
const read = {
|
|
1240
|
+
document,
|
|
1241
|
+
task,
|
|
1242
|
+
generate: options.generate,
|
|
1243
|
+
budget: options.budget,
|
|
1244
|
+
// The call's own listener, when it has one, in place of the tool set's.
|
|
1245
|
+
onProgress: hooks.onProgress ?? options.onProgress,
|
|
1246
|
+
...(hooks.onRequest ? { onRequest: hooks.onRequest } : {}),
|
|
1247
|
+
signal,
|
|
1248
|
+
...(options.retry ? { retry: options.retry } : {}),
|
|
1249
|
+
...(typeof limits.maxRequests === "number" && Number.isFinite(limits.maxRequests) ? { maxRequests: limits.maxRequests } : {}),
|
|
1250
|
+
};
|
|
1039
1251
|
let result;
|
|
1040
1252
|
try {
|
|
1041
|
-
result = await analyzeWholeDocument(
|
|
1042
|
-
document,
|
|
1043
|
-
task,
|
|
1044
|
-
generate: options.generate,
|
|
1045
|
-
budget: options.budget,
|
|
1046
|
-
// The call's own listener, when it has one, in place of the tool set's.
|
|
1047
|
-
onProgress: hooks.onProgress ?? options.onProgress,
|
|
1048
|
-
...(hooks.onRequest ? { onRequest: hooks.onRequest } : {}),
|
|
1049
|
-
signal: options.signal,
|
|
1050
|
-
...(options.retry ? { retry: options.retry } : {}),
|
|
1051
|
-
...(typeof limits.maxRequests === "number" && Number.isFinite(limits.maxRequests) ? { maxRequests: limits.maxRequests } : {}),
|
|
1052
|
-
});
|
|
1253
|
+
result = items ? await listWholeDocumentItems({ ...read, ...(labels ? { labels } : {}) }) : await analyzeWholeDocument(read);
|
|
1053
1254
|
}
|
|
1054
1255
|
catch (error) {
|
|
1055
1256
|
// Parts were sent and none could be read: that read is counted, since another would most
|
|
@@ -1064,24 +1265,36 @@ export function createDocumentTools(options) {
|
|
|
1064
1265
|
throw error;
|
|
1065
1266
|
}
|
|
1066
1267
|
failedWholeReads.delete(id);
|
|
1268
|
+
const room = limitOf(limits, Math.max(cap, ANALYSIS_RESULT_CHARACTERS));
|
|
1269
|
+
if ("items" in result)
|
|
1270
|
+
return fitAnswer(itemsResult(document.meta.name, task, result), room);
|
|
1067
1271
|
const notesCutShort = result.truncatedParts + result.truncatedMerges;
|
|
1272
|
+
const cutNote = notesCutShort ? " Some of them were cut off at the output limit, so they are incomplete: tell the user." : "";
|
|
1068
1273
|
return fitAnswer({
|
|
1069
1274
|
document: document.meta.name,
|
|
1070
1275
|
parts_read: result.parts,
|
|
1071
1276
|
parts_with_relevant_content: result.relevantParts,
|
|
1072
1277
|
...(result.failedParts ? { parts_that_failed: result.failedParts } : {}),
|
|
1073
1278
|
...(notesCutShort ? { notes_cut_short: notesCutShort } : {}),
|
|
1279
|
+
...(result.notesLeftOut ? { notes_left_out: result.notesLeftOut } : {}),
|
|
1074
1280
|
...(result.answerTruncated ? { answer_cut_short: true } : {}),
|
|
1075
|
-
...(result.answerFailed !== undefined ? { notes_only: true } : {}),
|
|
1281
|
+
...(result.answerFailed !== undefined || result.answerSkipped ? { notes_only: true } : {}),
|
|
1076
1282
|
...(result.answerFailed !== undefined
|
|
1077
|
-
? { note: `The last step of this read, which writes one answer from the notes of the parts, failed (${result.answerFailed}). The answer is those notes: answer from them.${
|
|
1078
|
-
:
|
|
1283
|
+
? { note: `The last step of this read, which writes one answer from the notes of the parts, failed (${result.answerFailed}). The answer is those notes: answer from them.${cutNote}` }
|
|
1284
|
+
: result.answerSkipped
|
|
1285
|
+
? { note: `This read reached the question's limit on model requests before its last step, which writes one answer from the notes of the parts. The answer is those notes: answer from them.${cutNote}` }
|
|
1286
|
+
: result.notesLeftOut
|
|
1287
|
+
? { note: notesLeftOutNote(result.notesLeftOut, result.relevantParts) }
|
|
1288
|
+
: notesCutShort || result.answerTruncated ? { note: INCOMPLETE_ANALYSIS } : {}),
|
|
1079
1289
|
answer: result.answer,
|
|
1080
|
-
},
|
|
1290
|
+
}, room);
|
|
1081
1291
|
},
|
|
1082
1292
|
};
|
|
1083
1293
|
/** `view_pages`: the pages as one small PDF, next to a short JSON result. */
|
|
1084
|
-
async function viewPages(args, limits) {
|
|
1294
|
+
async function viewPages(args, limits, signal) {
|
|
1295
|
+
const reason = cannotRun(TOOL_NAMES.view);
|
|
1296
|
+
if (reason)
|
|
1297
|
+
throw new Error(reason);
|
|
1085
1298
|
const id = text(args.document_id, "document_id");
|
|
1086
1299
|
// The same scope check as the text tools, on its own list: a PDF can be looked at without
|
|
1087
1300
|
// being searchable, and the other way round.
|
|
@@ -1090,7 +1303,7 @@ export function createDocumentTools(options) {
|
|
|
1090
1303
|
? `The pages of ${names.get(id) ?? id} cannot be shown: only its text was kept. Answer from the text.`
|
|
1091
1304
|
: `Unknown document_id ${shownId(id)}. Use the document_id of an attached PDF.`);
|
|
1092
1305
|
}
|
|
1093
|
-
const document = await options.load(id);
|
|
1306
|
+
const document = await until(options.load(id), signal);
|
|
1094
1307
|
if (!document)
|
|
1095
1308
|
throw gone(id);
|
|
1096
1309
|
const file = document.meta.name;
|
|
@@ -1114,13 +1327,13 @@ export function createDocumentTools(options) {
|
|
|
1114
1327
|
// look that waits holds none of its bytes, and the memory left is looked at then (`cutPdfPages`).
|
|
1115
1328
|
// A question stopped while its original is read gives the turn back at once, and so does a
|
|
1116
1329
|
// read that takes longer than the library allows its store calls (`holdMs`).
|
|
1117
|
-
const release = await pageLookTurn(id, file, limits);
|
|
1330
|
+
const release = await pageLookTurn(id, file, limits, signal);
|
|
1118
1331
|
let cut;
|
|
1119
1332
|
try {
|
|
1120
|
-
|
|
1121
|
-
const original = await originalOf(id, file);
|
|
1333
|
+
signal?.throwIfAborted();
|
|
1334
|
+
const original = await originalOf(id, file, signal);
|
|
1122
1335
|
// Stopped while the original was read: no pages are cut for a question that has left.
|
|
1123
|
-
|
|
1336
|
+
signal?.throwIfAborted();
|
|
1124
1337
|
if (original) {
|
|
1125
1338
|
try {
|
|
1126
1339
|
cut = await cutPdfPages(original, from, Math.min(asked, from + mostPages - 1), maxBytes, total);
|
|
@@ -1135,7 +1348,7 @@ export function createDocumentTools(options) {
|
|
|
1135
1348
|
}
|
|
1136
1349
|
if (!cut) {
|
|
1137
1350
|
// The document may have gone while the look waited for its turn: that is told as such.
|
|
1138
|
-
if (!await options.load(id))
|
|
1351
|
+
if (!await until(options.load(id), signal))
|
|
1139
1352
|
throw gone(id);
|
|
1140
1353
|
throw new Error(`The original file of ${file} is no longer on the server, so its pages cannot be shown. Answer from the text.`);
|
|
1141
1354
|
}
|
|
@@ -1167,31 +1380,50 @@ export function createDocumentTools(options) {
|
|
|
1167
1380
|
hooks.onPagesBusy?.(error.documentId);
|
|
1168
1381
|
return { error: safeErrorMessage(error) };
|
|
1169
1382
|
};
|
|
1383
|
+
/**
|
|
1384
|
+
* True for an error the call throws rather than tells the model: the call, or the tool set, was
|
|
1385
|
+
* stopped; or the store did not answer in time, or was not asked because too many store calls are
|
|
1386
|
+
* stuck (since 0.10.0), which ends the question with an error and shows the model nothing.
|
|
1387
|
+
*/
|
|
1388
|
+
const thrown = (error, signal) => signal?.aborted === true || storeGaveUp(error);
|
|
1170
1389
|
async function execute(name, args, limits = {}, hooks = {}) {
|
|
1171
1390
|
if (!known.has(name))
|
|
1172
1391
|
return { error: `Unknown tool ${unknownToolName(name)}.` };
|
|
1173
1392
|
// The pages are a file, and this method returns only JSON. Saying that pages are attached
|
|
1174
1393
|
// with nothing attached would be worse than saying that they could not be shown.
|
|
1175
1394
|
if (name === TOOL_NAMES.view)
|
|
1176
|
-
return { error: FILES_NOT_DELIVERED };
|
|
1395
|
+
return { error: cannotRun(name) ?? FILES_NOT_DELIVERED };
|
|
1396
|
+
const reason = cannotRun(name);
|
|
1397
|
+
if (reason)
|
|
1398
|
+
return { error: reason };
|
|
1399
|
+
const signal = signalOf(hooks);
|
|
1177
1400
|
// The documents this call loads (`documentFor`), by its arguments: calls given the same object
|
|
1178
1401
|
// at once each note them all.
|
|
1179
1402
|
const reads = [];
|
|
1180
1403
|
const calls = typeof args === "object" && args !== null ? loaded.get(args) ?? new Set() : undefined;
|
|
1181
1404
|
if (calls)
|
|
1182
1405
|
loaded.set(args, calls.add(reads));
|
|
1406
|
+
/**
|
|
1407
|
+
* Asks the store, once the call has ended, whether each document it read is still the one it
|
|
1408
|
+
* loaded. A call with a signal of its own ends when it aborts, even while this store call hangs.
|
|
1409
|
+
*/
|
|
1183
1410
|
const checkReads = async () => {
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1411
|
+
const checking = (async () => {
|
|
1412
|
+
for (const document of reads)
|
|
1413
|
+
if (options.checkRead && !await options.checkRead(document))
|
|
1414
|
+
throw gone(document.meta.id);
|
|
1415
|
+
})();
|
|
1416
|
+
await (hooks.signal ? until(checking, signal) : checking);
|
|
1187
1417
|
};
|
|
1188
1418
|
try {
|
|
1189
1419
|
let result;
|
|
1190
1420
|
try {
|
|
1191
|
-
|
|
1421
|
+
// A call with a signal of its own ends when it aborts, even in a store call that hangs.
|
|
1422
|
+
const running = handlers[name](args, limits, hooks, signal);
|
|
1423
|
+
result = await (hooks.signal ? until(running, signal) : running);
|
|
1192
1424
|
}
|
|
1193
1425
|
catch (error) {
|
|
1194
|
-
if (
|
|
1426
|
+
if (thrown(error, signal))
|
|
1195
1427
|
throw error;
|
|
1196
1428
|
await checkReads();
|
|
1197
1429
|
throw error;
|
|
@@ -1200,7 +1432,7 @@ export function createDocumentTools(options) {
|
|
|
1200
1432
|
return result;
|
|
1201
1433
|
}
|
|
1202
1434
|
catch (error) {
|
|
1203
|
-
if (
|
|
1435
|
+
if (thrown(error, signal))
|
|
1204
1436
|
throw error;
|
|
1205
1437
|
return failure(error, args, hooks);
|
|
1206
1438
|
}
|
|
@@ -1212,19 +1444,31 @@ export function createDocumentTools(options) {
|
|
|
1212
1444
|
declarations,
|
|
1213
1445
|
has: (name) => known.has(name),
|
|
1214
1446
|
execute: (name, args) => execute(name, args),
|
|
1215
|
-
|
|
1447
|
+
// A name the tool set does not answer, a declared tool that cannot run, and a whole-file read
|
|
1448
|
+
// with no part reader each get an error of a few words: no more room is kept for them.
|
|
1449
|
+
resultCharacters: (name) => (!known.has(name) || cannotRun(name) !== undefined || (name === TOOL_NAMES.analyze && !options.generate) ? LEAST_RESULT_CHARACTERS
|
|
1450
|
+
: name === TOOL_NAMES.analyze ? Math.max(cap, ANALYSIS_RESULT_CHARACTERS) : name === TOOL_NAMES.view ? LEAST_RESULT_CHARACTERS : cap),
|
|
1216
1451
|
async executeWithFiles(name, args, limits = {}, hooks = {}) {
|
|
1217
1452
|
if (name !== TOOL_NAMES.view || !known.has(name))
|
|
1218
1453
|
return { result: await execute(name, args, limits, hooks), files: [] };
|
|
1454
|
+
const signal = signalOf(hooks);
|
|
1219
1455
|
try {
|
|
1220
|
-
|
|
1456
|
+
const running = viewPages(args, limits, signal);
|
|
1457
|
+
return await (hooks.signal ? until(running, signal) : running);
|
|
1221
1458
|
}
|
|
1222
1459
|
catch (error) {
|
|
1223
|
-
if (
|
|
1460
|
+
if (thrown(error, signal))
|
|
1224
1461
|
throw error;
|
|
1225
1462
|
return { result: failure(error, args, hooks), files: [] };
|
|
1226
1463
|
}
|
|
1227
1464
|
},
|
|
1465
|
+
wholeReadsLeft(documentId) {
|
|
1466
|
+
// None for a document this tool set cannot read whole: no part reader, not one of its
|
|
1467
|
+
// documents, or one sent whole; none once a read of it could read no part.
|
|
1468
|
+
if (!options.generate || !allowed.has(documentId) || inline.has(documentId) || failedWholeReads.has(documentId))
|
|
1469
|
+
return 0;
|
|
1470
|
+
return Math.max(0, maxWholeReads - (wholeReads.get(documentId) ?? 0));
|
|
1471
|
+
},
|
|
1228
1472
|
describe(name, args) {
|
|
1229
1473
|
const id = typeof args.document_id === "string" ? args.document_id : "";
|
|
1230
1474
|
const file = names.get(id) ?? "the file";
|
|
@@ -1242,9 +1486,12 @@ export function createDocumentTools(options) {
|
|
|
1242
1486
|
return `Search ${file} (${mode}) for “${sliceWhole(String(args.query ?? ""), 80)}”${where}${how}`;
|
|
1243
1487
|
}
|
|
1244
1488
|
if (name === TOOL_NAMES.read) {
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1489
|
+
// The lines as the tool reads them (`requestedLines`): an end sent as text ("250") too, and
|
|
1490
|
+
// never past the most lines one read shows. The end is shown when the call gave one, not
|
|
1491
|
+
// before the start.
|
|
1492
|
+
const [start, end] = requestedLines(args);
|
|
1493
|
+
const given = args.end_line !== undefined && args.end_line !== null && args.end_line !== "" && Number(args.end_line) >= start;
|
|
1494
|
+
return `Read ${file} lines ${start}${given ? `-${end}` : ""}`;
|
|
1248
1495
|
}
|
|
1249
1496
|
if (name === TOOL_NAMES.overview)
|
|
1250
1497
|
return `Overview of ${file}`;
|
|
@@ -1264,7 +1511,7 @@ export function createDocumentTools(options) {
|
|
|
1264
1511
|
return sliceWhole(`Aggregate ${file}${table}: ${metrics}${by}${where}`, 200);
|
|
1265
1512
|
}
|
|
1266
1513
|
if (name === TOOL_NAMES.analyze)
|
|
1267
|
-
return `Read all of ${file} for “${sliceWhole(String(args.task ?? ""), 100)}
|
|
1514
|
+
return `Read all of ${file} for “${sliceWhole(String(args.task ?? ""), 100)}”${args.output === "items" ? ", as a list of items" : ""}`;
|
|
1268
1515
|
return name;
|
|
1269
1516
|
},
|
|
1270
1517
|
};
|