llm-large-files 0.8.2 → 0.10.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 +981 -0
- package/README.md +22 -17
- package/dist/access.d.ts +128 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +234 -0
- package/dist/access.js.map +1 -0
- 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 +159 -14
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +743 -113
- package/dist/ask.js.map +1 -1
- package/dist/cache.d.ts +12 -3
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +18 -5
- package/dist/cache.js.map +1 -1
- package/dist/citations.d.ts +36 -0
- package/dist/citations.d.ts.map +1 -0
- package/dist/citations.js +291 -0
- package/dist/citations.js.map +1 -0
- package/dist/encoding.js +5 -3
- package/dist/encoding.js.map +1 -1
- package/dist/error-info.d.ts +70 -0
- package/dist/error-info.d.ts.map +1 -0
- package/dist/error-info.js +253 -0
- package/dist/error-info.js.map +1 -0
- package/dist/errors.d.ts +74 -8
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +104 -15
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +57 -13
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +42 -11
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts +4 -2
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +35 -5
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +32 -8
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +52 -36
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +54 -7
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +152 -41
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +38 -53
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +20 -25
- 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 +4 -4
- 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 +13 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -5
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +78 -0
- package/dist/ingest.d.ts.map +1 -0
- package/dist/ingest.js +893 -0
- package/dist/ingest.js.map +1 -0
- package/dist/library.d.ts +295 -33
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +458 -650
- 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 +807 -61
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +79 -6
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +80 -4
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +247 -14
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +491 -227
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +3 -2
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +7 -1
- package/dist/node/ingest-child.d.ts.map +1 -1
- package/dist/node/ingest-child.js +19 -4
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/isolated.d.ts +3 -1
- package/dist/node/isolated.d.ts.map +1 -1
- package/dist/node/isolated.js +11 -4
- package/dist/node/isolated.js.map +1 -1
- package/dist/node/originals.d.ts +19 -0
- package/dist/node/originals.d.ts.map +1 -0
- package/dist/node/originals.js +82 -0
- package/dist/node/originals.js.map +1 -0
- package/dist/node/spool.d.ts +106 -0
- package/dist/node/spool.d.ts.map +1 -0
- package/dist/node/spool.js +378 -0
- package/dist/node/spool.js.map +1 -0
- package/dist/node/sse.d.ts +6 -4
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +9 -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-layout.d.ts.map +1 -1
- package/dist/pdf-layout.js +71 -12
- package/dist/pdf-layout.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 +16 -11
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +56 -12
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +3 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +6 -2
- package/dist/retry.js.map +1 -1
- package/dist/scope.d.ts +25 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +60 -0
- package/dist/scope.js.map +1 -0
- 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/source.d.ts +60 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +170 -0
- package/dist/source.js.map +1 -0
- package/dist/stores.d.ts +126 -31
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +655 -141
- package/dist/stores.js.map +1 -1
- package/dist/testing/fake-fetch.d.ts +31 -0
- package/dist/testing/fake-fetch.d.ts.map +1 -0
- package/dist/testing/fake-fetch.js +66 -0
- package/dist/testing/fake-fetch.js.map +1 -0
- package/dist/testing/fake-model.d.ts +38 -0
- package/dist/testing/fake-model.d.ts.map +1 -0
- package/dist/testing/fake-model.js +62 -0
- package/dist/testing/fake-model.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +9 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/store-checks.d.ts +72 -0
- package/dist/testing/store-checks.d.ts.map +1 -0
- package/dist/testing/store-checks.js +619 -0
- package/dist/testing/store-checks.js.map +1 -0
- package/dist/tools.d.ts +47 -2
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +440 -71
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +165 -14
- 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 +21 -8
- package/docs/getting-started.md +18 -13
- package/docs/guides/anthropic.md +17 -10
- package/docs/guides/conversations.md +112 -47
- package/docs/guides/costs-and-limits.md +147 -42
- package/docs/guides/deployment.md +380 -86
- package/docs/guides/errors-and-reliability.md +317 -67
- package/docs/guides/explorer-model.md +4 -1
- package/docs/guides/openai-compatible.md +47 -7
- package/docs/guides/own-adapter-and-loop.md +60 -16
- package/docs/guides/pdfs.md +219 -36
- package/docs/guides/storage.md +676 -145
- package/docs/guides/testing.md +149 -129
- package/docs/guides/vertex-and-gemini.md +169 -57
- package/docs/guides/web-app.md +318 -80
- package/docs/how-it-works.md +155 -30
- package/docs/measurements.md +215 -13
- package/docs/publishing.md +185 -37
- package/docs/reference/anthropic.md +12 -7
- package/docs/reference/ask.md +415 -47
- package/docs/reference/errors-and-retries.md +194 -14
- package/docs/reference/events.md +77 -27
- package/docs/reference/gemini.md +252 -87
- package/docs/reference/library.md +886 -178
- package/docs/reference/node.md +659 -111
- package/docs/reference/openai.md +21 -10
- package/docs/reference/testing.md +311 -0
- package/docs/reference/tools.md +285 -30
- package/docs/security.md +404 -78
- package/docs/troubleshooting.md +151 -70
- package/docs/upgrading-0.10.md +472 -0
- package/docs/upgrading-0.9.md +890 -0
- package/package.json +16 -3
- package/src/access.ts +267 -0
- 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 +866 -115
- package/src/cache.ts +20 -5
- package/src/citations.ts +294 -0
- package/src/encoding.ts +6 -4
- package/src/error-info.ts +290 -0
- package/src/errors.ts +131 -15
- package/src/events.ts +112 -24
- package/src/evidence.ts +35 -5
- package/src/extract.ts +56 -34
- package/src/gemini/adapter.ts +196 -43
- package/src/gemini/chat.ts +63 -78
- 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 +4 -4
- package/src/http.ts +65 -4
- package/src/index.ts +13 -8
- package/src/ingest.ts +958 -0
- package/src/library.ts +711 -651
- package/src/map-reduce.ts +858 -70
- package/src/model.ts +113 -9
- package/src/node/handlers.ts +709 -221
- package/src/node/index.ts +14 -2
- package/src/node/ingest-child.ts +24 -6
- package/src/node/isolated.ts +11 -4
- package/src/node/originals.ts +78 -0
- package/src/node/spool.ts +379 -0
- package/src/node/sse.ts +9 -7
- package/src/openai/adapter.ts +56 -13
- package/src/output-limit.ts +5 -2
- package/src/pdf-layout.ts +69 -11
- package/src/pdf-outline.ts +400 -0
- package/src/plan.ts +287 -36
- package/src/prepare.ts +253 -0
- package/src/ranged.ts +48 -14
- package/src/retry.ts +6 -2
- package/src/scope.ts +63 -0
- package/src/search.ts +69 -13
- package/src/source.ts +178 -0
- package/src/stores.ts +702 -142
- package/src/testing/fake-fetch.ts +80 -0
- package/src/testing/fake-model.ts +78 -0
- package/src/testing/index.ts +11 -0
- package/src/testing/store-checks.ts +660 -0
- package/src/tools.ts +461 -73
- package/src/types.ts +151 -14
- package/src/whole-cost.ts +64 -0
package/dist/tools.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { safeErrorMessage } from "./errors.js";
|
|
2
|
+
import { until } from "./http.js";
|
|
2
3
|
import { aggregateTable, FILTER_OPS, MAX_SHOWN_GROUPS } from "./aggregate.js";
|
|
3
4
|
import { GROUP_BY_VALUES, MAX_GROUP_KEYS } from "./groups.js";
|
|
4
|
-
import { analyzeWholeDocument, NothingReadError } from "./map-reduce.js";
|
|
5
|
+
import { analyzeWholeDocument, listWholeDocumentItems, MAX_ITEM_LABELS, MAX_LABEL_CHARACTERS, NothingReadError, storeGaveUp } from "./map-reduce.js";
|
|
5
6
|
import { cutPdfPages } from "./pdf-pages.js";
|
|
7
|
+
import { DocumentGoneError } from "./ranged.js";
|
|
6
8
|
import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS } from "./search.js";
|
|
7
9
|
import { estimateParts, formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
|
|
8
10
|
import { plural, removeInvisible, sliceWhole, wellFormedJson } from "./text.js";
|
|
@@ -84,12 +86,18 @@ const DECLARATIONS = {
|
|
|
84
86
|
},
|
|
85
87
|
analyze: {
|
|
86
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.
|
|
87
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.",
|
|
88
92
|
parameters: {
|
|
89
93
|
type: "object",
|
|
90
94
|
properties: {
|
|
91
95
|
document_id: documentId,
|
|
92
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.` },
|
|
93
101
|
},
|
|
94
102
|
required: ["document_id", "task"],
|
|
95
103
|
},
|
|
@@ -138,6 +146,18 @@ const DECLARATIONS = {
|
|
|
138
146
|
},
|
|
139
147
|
},
|
|
140
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
|
+
}
|
|
141
161
|
/** Says so when a tool that returns files is run through `execute`, which has nowhere to put them. */
|
|
142
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.";
|
|
143
163
|
function integer(value, fallback, min, max) {
|
|
@@ -156,6 +176,57 @@ function flag(value) {
|
|
|
156
176
|
return typeof value === "string" && /^\s*(?:true|1)\s*$/i.test(value);
|
|
157
177
|
}
|
|
158
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
|
+
}
|
|
159
230
|
function text(value, name) {
|
|
160
231
|
if (typeof value !== "string" || !value.trim())
|
|
161
232
|
throw new Error(`${name} is required.`);
|
|
@@ -199,9 +270,13 @@ function fit(result, listKey, limit) {
|
|
|
199
270
|
}
|
|
200
271
|
/**
|
|
201
272
|
* The result of a whole-document read within `limit` characters: its answer is cut at the end,
|
|
202
|
-
* 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.
|
|
203
276
|
*/
|
|
204
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);
|
|
205
280
|
if (JSON.stringify(result).length <= limit || typeof result.answer !== "string")
|
|
206
281
|
return fit(result, null, limit);
|
|
207
282
|
const answer = result.answer;
|
|
@@ -223,6 +298,35 @@ export function fitAnswer(result, limit) {
|
|
|
223
298
|
}
|
|
224
299
|
return fit(cutAt(low), null, limit);
|
|
225
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
|
+
}
|
|
226
330
|
/**
|
|
227
331
|
* The result of an exact or regex search that read the whole file: the first matches, then the
|
|
228
332
|
* last one of the file, and a note that says how many of how many are shown when that is not all.
|
|
@@ -581,6 +685,9 @@ export function alreadyShown(call, earlier, stored = false) {
|
|
|
581
685
|
return undefined;
|
|
582
686
|
if (result.dropped === true || result.already_shown === true || typeof result.error === "string" || result.truncated === true)
|
|
583
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;
|
|
584
691
|
// A search stored by 0.7.0 with case_sensitive or whole_word as text or 1 ("true", 1): 0.7.0 read
|
|
585
692
|
// those as off, 0.8.0 as on, so the call made now would not return what was stored.
|
|
586
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)))
|
|
@@ -660,8 +767,13 @@ export function toolResultSummary(label, result) {
|
|
|
660
767
|
const groups = typeof result.total_groups === "number" ? `, ${result.total_groups.toLocaleString("en-US")} ${plural(result.total_groups, "group")}` : "";
|
|
661
768
|
return ` — ${result.rows_matched.toLocaleString("en-US")} ${plural(result.rows_matched, "row")}${groups}`;
|
|
662
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
|
+
}
|
|
663
775
|
if (typeof result.parts_read === "number") {
|
|
664
|
-
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" : "";
|
|
665
777
|
return ` — ${result.parts_read} ${plural(result.parts_read, "part")}, ${String(result.parts_with_relevant_content ?? 0)} relevant${incomplete}`;
|
|
666
778
|
}
|
|
667
779
|
// A read reports its range only when it was cut short of what was asked.
|
|
@@ -695,23 +807,54 @@ export const unknownToolName = (name) => `“${sliceWhole(name, 64)}”`;
|
|
|
695
807
|
* be, cut otherwise. The model chose it, at any length, and the error goes into steps too.
|
|
696
808
|
*/
|
|
697
809
|
const shownId = (id) => (id.length > 64 ? `${sliceWhole(id, 64)}…` : id);
|
|
810
|
+
/** A document that a call names is no longer in the store, as a read by range finds it: its message is the model's. */
|
|
811
|
+
const gone = (id) => new DocumentGoneError(`${id} is no longer available on the server. Ask the user to attach the file again.`);
|
|
812
|
+
/** A look at pages that waited its turn for too long: its message is the model's. */
|
|
813
|
+
class PagesBusyError extends Error {
|
|
814
|
+
documentId;
|
|
815
|
+
constructor(documentId, file) {
|
|
816
|
+
super(`${file}: The pages cannot be looked at right now; the server is busy. Answer from the text, or look again later.`);
|
|
817
|
+
this.documentId = documentId;
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
/** A timer may wait at most this long (2^31 - 1 ms, 24.8 days). */
|
|
821
|
+
const LONGEST_WAIT_MS = 2_147_483_647;
|
|
698
822
|
export function createDocumentTools(options) {
|
|
699
823
|
const allowed = new Set(options.documentIds);
|
|
700
824
|
const viewable = new Set(options.loadOriginal ? options.viewableIds ?? [] : []);
|
|
701
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;
|
|
702
828
|
// The text tools are left out only when there are pages to look at and no document to search.
|
|
703
829
|
const textTools = allowed.size > 0 || viewable.size === 0;
|
|
704
|
-
const declarations = [
|
|
830
|
+
const declarations = options.declare ? declarationsFor(options.declare) : [
|
|
705
831
|
...(textTools ? [DECLARATIONS.search, DECLARATIONS.read, DECLARATIONS.overview, ...(options.tables ? [DECLARATIONS.aggregate] : []), ...(options.generate && options.wholeReads !== false ? [DECLARATIONS.analyze] : [])] : []),
|
|
706
832
|
...(viewable.size > 0 ? [DECLARATIONS.view] : []),
|
|
707
833
|
];
|
|
708
834
|
const known = new Set(declarations.map((declaration) => declaration.name));
|
|
709
|
-
//
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
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
|
+
};
|
|
715
858
|
const cap = options.budget.toolResultCharacters;
|
|
716
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. */
|
|
717
860
|
const limitOf = (limits, own = cap) => {
|
|
@@ -741,9 +884,55 @@ export function createDocumentTools(options) {
|
|
|
741
884
|
const wholeReads = new Map();
|
|
742
885
|
/** Why the last whole-document read of a document failed, when no part of it could be read. */
|
|
743
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
|
+
};
|
|
744
921
|
// When no limit is given with a call: three eighths of a request, so that two looks still fit.
|
|
745
922
|
const defaultFileBytes = Math.floor((options.budget.maxRequestBytes - REQUEST_BYTES_MARGIN) * 3 / 8);
|
|
746
|
-
|
|
923
|
+
/** The documents the calls under way loaded, by the arguments of the call: checked once it ends (`checkRead`). */
|
|
924
|
+
const loaded = new WeakMap();
|
|
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) {
|
|
747
936
|
const id = text(args.document_id, "document_id");
|
|
748
937
|
// Scope check: a model can only reach files attached to this conversation.
|
|
749
938
|
if (!allowed.has(id)) {
|
|
@@ -753,16 +942,69 @@ export function createDocumentTools(options) {
|
|
|
753
942
|
? `Unknown document_id ${shownId(id)}. No attached file is read with this tool in this conversation.`
|
|
754
943
|
: `Unknown document_id ${shownId(id)}. Use one of: ${usable.join(", ")}${allowed.size > 20 ? ", …" : ""}.`);
|
|
755
944
|
}
|
|
756
|
-
|
|
945
|
+
// A load that hangs does not hold a call that was stopped.
|
|
946
|
+
const document = await until(options.load(id), signal);
|
|
757
947
|
if (!document)
|
|
758
|
-
throw
|
|
948
|
+
throw gone(id);
|
|
949
|
+
for (const reads of loaded.get(args) ?? [])
|
|
950
|
+
reads.push(document);
|
|
759
951
|
names.set(id, document.meta.name);
|
|
760
952
|
return document;
|
|
761
953
|
}
|
|
954
|
+
/**
|
|
955
|
+
* Waits for the turn of a look at pages of `file`, for at most `pageLookWaitMs`, or the call's
|
|
956
|
+
* `maxWaitMs` when that is less. Returns the function that gives the turn back. Past the wait, a
|
|
957
|
+
* `PagesBusyError`. The wait ends at once when the call is stopped (`signal`), with the reason it
|
|
958
|
+
* was stopped for.
|
|
959
|
+
*/
|
|
960
|
+
async function pageLookTurn(id, file, limits, signal) {
|
|
961
|
+
const turns = options.pageLooks;
|
|
962
|
+
if (!turns)
|
|
963
|
+
return () => undefined;
|
|
964
|
+
const waited = new AbortController();
|
|
965
|
+
const callWait = typeof limits.maxWaitMs === "number" && !Number.isNaN(limits.maxWaitMs) ? limits.maxWaitMs : Infinity;
|
|
966
|
+
const waitMs = Math.max(0, Math.min(turns.waitMs, callWait));
|
|
967
|
+
const timer = waitMs <= LONGEST_WAIT_MS ? setTimeout(() => waited.abort(), waitMs) : undefined;
|
|
968
|
+
timer?.unref?.();
|
|
969
|
+
try {
|
|
970
|
+
return await turns.limiter.acquire(signal ? AbortSignal.any([signal, waited.signal]) : waited.signal);
|
|
971
|
+
}
|
|
972
|
+
catch (error) {
|
|
973
|
+
if (signal?.aborted || !waited.signal.aborted)
|
|
974
|
+
throw error;
|
|
975
|
+
throw new PagesBusyError(id, file);
|
|
976
|
+
}
|
|
977
|
+
finally {
|
|
978
|
+
clearTimeout(timer);
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
/**
|
|
982
|
+
* The original file of a look, read while the look holds its turn: for at most `holdMs`, and
|
|
983
|
+
* only while the call runs. A read given up on goes on, but holds no turn.
|
|
984
|
+
*/
|
|
985
|
+
async function originalOf(id, file, signal) {
|
|
986
|
+
const reading = until(options.loadOriginal(id), signal);
|
|
987
|
+
const holdMs = options.pageLooks?.holdMs;
|
|
988
|
+
if (holdMs === undefined || !(holdMs <= LONGEST_WAIT_MS))
|
|
989
|
+
return reading;
|
|
990
|
+
let timer;
|
|
991
|
+
// The timer keeps the process alive: a read that never ends may hold nothing that does, and
|
|
992
|
+
// the question waiting for it would be lost.
|
|
993
|
+
const late = new Promise((_, reject) => {
|
|
994
|
+
timer = setTimeout(() => reject(new Error(`The original file of ${file} could not be read in time, so its pages cannot be shown. Answer from the text.`)), Math.max(0, holdMs));
|
|
995
|
+
});
|
|
996
|
+
try {
|
|
997
|
+
return await Promise.race([reading, late]);
|
|
998
|
+
}
|
|
999
|
+
finally {
|
|
1000
|
+
clearTimeout(timer);
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
/** The tools that return JSON. `signal` is the call's (`signalOf`). */
|
|
762
1004
|
const handlers = {
|
|
763
|
-
async [TOOL_NAMES.search](args, limits) {
|
|
1005
|
+
async [TOOL_NAMES.search](args, limits, _hooks, signal) {
|
|
764
1006
|
const limit = limitOf(limits);
|
|
765
|
-
const document = await documentFor(args);
|
|
1007
|
+
const document = await documentFor(args, signal);
|
|
766
1008
|
const query = text(args.query, "query");
|
|
767
1009
|
const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
|
|
768
1010
|
// Page numbers are added only for a PDF whose pages can be looked at: they are what
|
|
@@ -783,7 +1025,7 @@ export function createDocumentTools(options) {
|
|
|
783
1025
|
if (groupBy)
|
|
784
1026
|
throw new Error("group_by counts the lines of an exact or regex search: use mode \"exact\" or \"regex\".");
|
|
785
1027
|
const topK = integer(args.max_results, 5, 1, 10);
|
|
786
|
-
const ranked = await rankSource(document, query, topK,
|
|
1028
|
+
const ranked = await rankSource(document, query, topK, signal, ranged ? range : undefined);
|
|
787
1029
|
const texts = await Promise.all(ranked.map((passage) => document.readLines(passage.from, passage.to)));
|
|
788
1030
|
return fit({
|
|
789
1031
|
document: document.meta.name,
|
|
@@ -814,7 +1056,7 @@ export function createDocumentTools(options) {
|
|
|
814
1056
|
maxResults: integer(args.max_results, DEFAULT_GREP_RESULTS, 1, MAX_GREP_RESULTS),
|
|
815
1057
|
contextLines: integer(args.context_lines, 0, 0, 5),
|
|
816
1058
|
...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
|
|
817
|
-
...(
|
|
1059
|
+
...(signal ? { signal } : {}),
|
|
818
1060
|
...(ranged ? { fromLine: range.from, toLine: range.to } : {}),
|
|
819
1061
|
...(order === "last" ? { order } : {}),
|
|
820
1062
|
...(groupBy ? { groupBy } : {}),
|
|
@@ -861,9 +1103,9 @@ export function createDocumentTools(options) {
|
|
|
861
1103
|
matches,
|
|
862
1104
|
}, "matches", limit);
|
|
863
1105
|
},
|
|
864
|
-
async [TOOL_NAMES.read](args, limits) {
|
|
1106
|
+
async [TOOL_NAMES.read](args, limits, _hooks, signal) {
|
|
865
1107
|
const limit = limitOf(limits);
|
|
866
|
-
const document = await documentFor(args);
|
|
1108
|
+
const document = await documentFor(args, signal);
|
|
867
1109
|
const total = document.lineCount;
|
|
868
1110
|
const start = integer(args.start_line, 1, 1, total);
|
|
869
1111
|
const end = integer(args.end_line, start + DEFAULT_READ_LINES - 1, start, Math.min(total, start + MAX_READ_LINES - 1));
|
|
@@ -878,20 +1120,28 @@ export function createDocumentTools(options) {
|
|
|
878
1120
|
body = numberLines(read.slice(0, to - start + 1), start);
|
|
879
1121
|
}
|
|
880
1122
|
const pages = viewable.has(document.meta.id) ? document.pagesOfLines(start, to) : undefined;
|
|
881
|
-
|
|
1123
|
+
const cut = !fits(body);
|
|
1124
|
+
const result = {
|
|
882
1125
|
document: document.meta.name,
|
|
883
1126
|
lines: `${start}-${to}`,
|
|
884
1127
|
...(pages ? { pages } : {}),
|
|
885
1128
|
total_lines: total,
|
|
886
|
-
text:
|
|
1129
|
+
text: cut ? sliceWhole(body, Math.floor((limit - 500) / 2)) : body,
|
|
887
1130
|
// One line longer than the room: its text was cut, so the lines are not all shown.
|
|
888
|
-
...(
|
|
1131
|
+
...(cut ? { text_cut: true } : {}),
|
|
889
1132
|
...(to < total ? { next_start_line: to + 1 } : { note: "End of file." }),
|
|
890
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;
|
|
891
1141
|
},
|
|
892
|
-
async [TOOL_NAMES.overview](args, limits) {
|
|
1142
|
+
async [TOOL_NAMES.overview](args, limits, _hooks, signal) {
|
|
893
1143
|
const limit = limitOf(limits);
|
|
894
|
-
const document = await documentFor(args);
|
|
1144
|
+
const document = await documentFor(args, signal);
|
|
895
1145
|
const { meta, lineCount } = document;
|
|
896
1146
|
const tail = Math.max(1, lineCount - 19);
|
|
897
1147
|
// Counting the parts means reading the whole text, for a number that only says how costly a
|
|
@@ -915,11 +1165,11 @@ export function createDocumentTools(options) {
|
|
|
915
1165
|
outline: meta.outline.length ? outlineLines(meta.outline) : [],
|
|
916
1166
|
}, "outline", limit);
|
|
917
1167
|
},
|
|
918
|
-
async [TOOL_NAMES.aggregate](args, limits) {
|
|
1168
|
+
async [TOOL_NAMES.aggregate](args, limits, _hooks, signal) {
|
|
919
1169
|
const limit = limitOf(limits);
|
|
920
|
-
const document = await documentFor(args);
|
|
1170
|
+
const document = await documentFor(args, signal);
|
|
921
1171
|
const request = aggregateRequest(args);
|
|
922
|
-
const result = await aggregateTable(document, request,
|
|
1172
|
+
const result = await aggregateTable(document, request, signal);
|
|
923
1173
|
const groups = result.groups.map((group) => ({
|
|
924
1174
|
...(Object.keys(group.key).length > 0 ? { group: group.key } : {}),
|
|
925
1175
|
...group.values,
|
|
@@ -943,24 +1193,41 @@ export function createDocumentTools(options) {
|
|
|
943
1193
|
...(result.repeatedHeaders > 0 ? { repeated_header_rows: result.repeatedHeaders } : {}),
|
|
944
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." } : {}),
|
|
945
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(" ") } : {}),
|
|
946
1198
|
};
|
|
947
1199
|
const note = groups.length < result.totalGroups
|
|
948
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.` }
|
|
949
1201
|
: {};
|
|
950
|
-
|
|
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);
|
|
951
1209
|
},
|
|
952
|
-
async [TOOL_NAMES.analyze](args, limits, hooks) {
|
|
1210
|
+
async [TOOL_NAMES.analyze](args, limits, hooks, signal) {
|
|
953
1211
|
if (!options.generate)
|
|
954
1212
|
throw new Error("Whole-document analysis is not enabled.");
|
|
955
|
-
|
|
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);
|
|
956
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;
|
|
957
1222
|
// A read of the whole file is many model requests. A model that asks for it again, with the
|
|
958
1223
|
// task put another way, is told to use what it has. The count is taken before the read
|
|
959
1224
|
// starts, so that two calls in one turn do not both pass.
|
|
960
1225
|
const id = document.meta.id;
|
|
961
1226
|
const reads = wholeReads.get(id) ?? 0;
|
|
962
|
-
|
|
963
|
-
|
|
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) {
|
|
964
1231
|
throw new Error(maxWholeReads === 0
|
|
965
1232
|
? `Whole-file reads are turned off for this question. Use search_document and read_document on ${document.meta.name}.`
|
|
966
1233
|
: failure !== undefined
|
|
@@ -969,20 +1236,21 @@ export function createDocumentTools(options) {
|
|
|
969
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.`);
|
|
970
1237
|
}
|
|
971
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
|
+
};
|
|
972
1251
|
let result;
|
|
973
1252
|
try {
|
|
974
|
-
result = await analyzeWholeDocument(
|
|
975
|
-
document,
|
|
976
|
-
task,
|
|
977
|
-
generate: options.generate,
|
|
978
|
-
budget: options.budget,
|
|
979
|
-
// The call's own listener, when it has one, in place of the tool set's.
|
|
980
|
-
onProgress: hooks.onProgress ?? options.onProgress,
|
|
981
|
-
...(hooks.onRequest ? { onRequest: hooks.onRequest } : {}),
|
|
982
|
-
signal: options.signal,
|
|
983
|
-
...(options.retry ? { retry: options.retry } : {}),
|
|
984
|
-
...(typeof limits.maxRequests === "number" && Number.isFinite(limits.maxRequests) ? { maxRequests: limits.maxRequests } : {}),
|
|
985
|
-
});
|
|
1253
|
+
result = items ? await listWholeDocumentItems({ ...read, ...(labels ? { labels } : {}) }) : await analyzeWholeDocument(read);
|
|
986
1254
|
}
|
|
987
1255
|
catch (error) {
|
|
988
1256
|
// Parts were sent and none could be read: that read is counted, since another would most
|
|
@@ -997,24 +1265,36 @@ export function createDocumentTools(options) {
|
|
|
997
1265
|
throw error;
|
|
998
1266
|
}
|
|
999
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);
|
|
1000
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." : "";
|
|
1001
1273
|
return fitAnswer({
|
|
1002
1274
|
document: document.meta.name,
|
|
1003
1275
|
parts_read: result.parts,
|
|
1004
1276
|
parts_with_relevant_content: result.relevantParts,
|
|
1005
1277
|
...(result.failedParts ? { parts_that_failed: result.failedParts } : {}),
|
|
1006
1278
|
...(notesCutShort ? { notes_cut_short: notesCutShort } : {}),
|
|
1279
|
+
...(result.notesLeftOut ? { notes_left_out: result.notesLeftOut } : {}),
|
|
1007
1280
|
...(result.answerTruncated ? { answer_cut_short: true } : {}),
|
|
1008
|
-
...(result.answerFailed !== undefined ? { notes_only: true } : {}),
|
|
1281
|
+
...(result.answerFailed !== undefined || result.answerSkipped ? { notes_only: true } : {}),
|
|
1009
1282
|
...(result.answerFailed !== undefined
|
|
1010
|
-
? { 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.${
|
|
1011
|
-
:
|
|
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 } : {}),
|
|
1012
1289
|
answer: result.answer,
|
|
1013
|
-
},
|
|
1290
|
+
}, room);
|
|
1014
1291
|
},
|
|
1015
1292
|
};
|
|
1016
1293
|
/** `view_pages`: the pages as one small PDF, next to a short JSON result. */
|
|
1017
|
-
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);
|
|
1018
1298
|
const id = text(args.document_id, "document_id");
|
|
1019
1299
|
// The same scope check as the text tools, on its own list: a PDF can be looked at without
|
|
1020
1300
|
// being searchable, and the other way round.
|
|
@@ -1023,9 +1303,9 @@ export function createDocumentTools(options) {
|
|
|
1023
1303
|
? `The pages of ${names.get(id) ?? id} cannot be shown: only its text was kept. Answer from the text.`
|
|
1024
1304
|
: `Unknown document_id ${shownId(id)}. Use the document_id of an attached PDF.`);
|
|
1025
1305
|
}
|
|
1026
|
-
const document = await options.load(id);
|
|
1306
|
+
const document = await until(options.load(id), signal);
|
|
1027
1307
|
if (!document)
|
|
1028
|
-
throw
|
|
1308
|
+
throw gone(id);
|
|
1029
1309
|
const file = document.meta.name;
|
|
1030
1310
|
names.set(id, file);
|
|
1031
1311
|
const from = pageNumber(args.from_page, "from_page");
|
|
@@ -1042,15 +1322,35 @@ export function createDocumentTools(options) {
|
|
|
1042
1322
|
const maxBytes = whole(limits.maxFileBytes, defaultFileBytes);
|
|
1043
1323
|
if (maxBytes < MIN_FILE_BYTES)
|
|
1044
1324
|
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.");
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1325
|
+
// Looks take their turns in the library (`maxConcurrentPageLooks`): they share one thread, and
|
|
1326
|
+
// more of them at once only hold more memory. The original is loaded once the turn comes, so a
|
|
1327
|
+
// look that waits holds none of its bytes, and the memory left is looked at then (`cutPdfPages`).
|
|
1328
|
+
// A question stopped while its original is read gives the turn back at once, and so does a
|
|
1329
|
+
// read that takes longer than the library allows its store calls (`holdMs`).
|
|
1330
|
+
const release = await pageLookTurn(id, file, limits, signal);
|
|
1048
1331
|
let cut;
|
|
1049
1332
|
try {
|
|
1050
|
-
|
|
1333
|
+
signal?.throwIfAborted();
|
|
1334
|
+
const original = await originalOf(id, file, signal);
|
|
1335
|
+
// Stopped while the original was read: no pages are cut for a question that has left.
|
|
1336
|
+
signal?.throwIfAborted();
|
|
1337
|
+
if (original) {
|
|
1338
|
+
try {
|
|
1339
|
+
cut = await cutPdfPages(original, from, Math.min(asked, from + mostPages - 1), maxBytes, total);
|
|
1340
|
+
}
|
|
1341
|
+
catch (error) {
|
|
1342
|
+
throw new Error(`${file}: ${safeErrorMessage(error)}`);
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1051
1345
|
}
|
|
1052
|
-
|
|
1053
|
-
|
|
1346
|
+
finally {
|
|
1347
|
+
release();
|
|
1348
|
+
}
|
|
1349
|
+
if (!cut) {
|
|
1350
|
+
// The document may have gone while the look waited for its turn: that is told as such.
|
|
1351
|
+
if (!await until(options.load(id), signal))
|
|
1352
|
+
throw gone(id);
|
|
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.`);
|
|
1054
1354
|
}
|
|
1055
1355
|
const pages = pageRange(cut.from, cut.to);
|
|
1056
1356
|
const shown = cut.to - cut.from + 1;
|
|
@@ -1068,41 +1368,107 @@ export function createDocumentTools(options) {
|
|
|
1068
1368
|
files: [{ name, mimeType: "application/pdf", bytes: cut.bytes }],
|
|
1069
1369
|
};
|
|
1070
1370
|
}
|
|
1071
|
-
|
|
1072
|
-
|
|
1371
|
+
/**
|
|
1372
|
+
* What a tool could not do goes to the model, and from there to a user's screen: never a server
|
|
1373
|
+
* path. A document found gone, or a look that waited too long, is also told to the call's hooks.
|
|
1374
|
+
*/
|
|
1375
|
+
const failure = (error, args, hooks) => {
|
|
1376
|
+
// Found gone when the call began, or while a read by range went through its text.
|
|
1377
|
+
if (error instanceof DocumentGoneError && typeof args.document_id === "string")
|
|
1378
|
+
hooks.onDocumentGone?.(args.document_id);
|
|
1379
|
+
else if (error instanceof PagesBusyError)
|
|
1380
|
+
hooks.onPagesBusy?.(error.documentId);
|
|
1381
|
+
return { error: safeErrorMessage(error) };
|
|
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);
|
|
1073
1389
|
async function execute(name, args, limits = {}, hooks = {}) {
|
|
1074
1390
|
if (!known.has(name))
|
|
1075
1391
|
return { error: `Unknown tool ${unknownToolName(name)}.` };
|
|
1076
1392
|
// The pages are a file, and this method returns only JSON. Saying that pages are attached
|
|
1077
1393
|
// with nothing attached would be worse than saying that they could not be shown.
|
|
1078
1394
|
if (name === TOOL_NAMES.view)
|
|
1079
|
-
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);
|
|
1400
|
+
// The documents this call loads (`documentFor`), by its arguments: calls given the same object
|
|
1401
|
+
// at once each note them all.
|
|
1402
|
+
const reads = [];
|
|
1403
|
+
const calls = typeof args === "object" && args !== null ? loaded.get(args) ?? new Set() : undefined;
|
|
1404
|
+
if (calls)
|
|
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
|
+
*/
|
|
1410
|
+
const checkReads = async () => {
|
|
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);
|
|
1417
|
+
};
|
|
1080
1418
|
try {
|
|
1081
|
-
|
|
1419
|
+
let result;
|
|
1420
|
+
try {
|
|
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);
|
|
1424
|
+
}
|
|
1425
|
+
catch (error) {
|
|
1426
|
+
if (thrown(error, signal))
|
|
1427
|
+
throw error;
|
|
1428
|
+
await checkReads();
|
|
1429
|
+
throw error;
|
|
1430
|
+
}
|
|
1431
|
+
await checkReads();
|
|
1432
|
+
return result;
|
|
1082
1433
|
}
|
|
1083
1434
|
catch (error) {
|
|
1084
|
-
if (
|
|
1435
|
+
if (thrown(error, signal))
|
|
1085
1436
|
throw error;
|
|
1086
|
-
return failure(error);
|
|
1437
|
+
return failure(error, args, hooks);
|
|
1438
|
+
}
|
|
1439
|
+
finally {
|
|
1440
|
+
calls?.delete(reads);
|
|
1087
1441
|
}
|
|
1088
1442
|
}
|
|
1089
1443
|
return {
|
|
1090
1444
|
declarations,
|
|
1091
1445
|
has: (name) => known.has(name),
|
|
1092
1446
|
execute: (name, args) => execute(name, args),
|
|
1093
|
-
|
|
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),
|
|
1094
1451
|
async executeWithFiles(name, args, limits = {}, hooks = {}) {
|
|
1095
1452
|
if (name !== TOOL_NAMES.view || !known.has(name))
|
|
1096
1453
|
return { result: await execute(name, args, limits, hooks), files: [] };
|
|
1454
|
+
const signal = signalOf(hooks);
|
|
1097
1455
|
try {
|
|
1098
|
-
|
|
1456
|
+
const running = viewPages(args, limits, signal);
|
|
1457
|
+
return await (hooks.signal ? until(running, signal) : running);
|
|
1099
1458
|
}
|
|
1100
1459
|
catch (error) {
|
|
1101
|
-
if (
|
|
1460
|
+
if (thrown(error, signal))
|
|
1102
1461
|
throw error;
|
|
1103
|
-
return { result: failure(error), files: [] };
|
|
1462
|
+
return { result: failure(error, args, hooks), files: [] };
|
|
1104
1463
|
}
|
|
1105
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
|
+
},
|
|
1106
1472
|
describe(name, args) {
|
|
1107
1473
|
const id = typeof args.document_id === "string" ? args.document_id : "";
|
|
1108
1474
|
const file = names.get(id) ?? "the file";
|
|
@@ -1120,9 +1486,12 @@ export function createDocumentTools(options) {
|
|
|
1120
1486
|
return `Search ${file} (${mode}) for “${sliceWhole(String(args.query ?? ""), 80)}”${where}${how}`;
|
|
1121
1487
|
}
|
|
1122
1488
|
if (name === TOOL_NAMES.read) {
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
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}` : ""}`;
|
|
1126
1495
|
}
|
|
1127
1496
|
if (name === TOOL_NAMES.overview)
|
|
1128
1497
|
return `Overview of ${file}`;
|
|
@@ -1142,7 +1511,7 @@ export function createDocumentTools(options) {
|
|
|
1142
1511
|
return sliceWhole(`Aggregate ${file}${table}: ${metrics}${by}${where}`, 200);
|
|
1143
1512
|
}
|
|
1144
1513
|
if (name === TOOL_NAMES.analyze)
|
|
1145
|
-
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" : ""}`;
|
|
1146
1515
|
return name;
|
|
1147
1516
|
},
|
|
1148
1517
|
};
|