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/src/tools.ts
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
import { safeErrorMessage } from "./errors.js";
|
|
2
|
+
import { until } from "./http.js";
|
|
2
3
|
import { aggregateTable, FILTER_OPS, MAX_SHOWN_GROUPS, type AggregateRequest, type FilterOp } from "./aggregate.js";
|
|
3
4
|
import { GROUP_BY_VALUES, MAX_GROUP_KEYS, type GroupBy, type GroupResult } from "./groups.js";
|
|
4
|
-
import { analyzeWholeDocument, NothingReadError } from "./map-reduce.js";
|
|
5
|
-
import { cutPdfPages } from "./pdf-pages.js";
|
|
5
|
+
import { analyzeWholeDocument, listWholeDocumentItems, MAX_ITEM_LABELS, MAX_LABEL_CHARACTERS, NothingReadError, storeGaveUp, type WholeItemsResult } from "./map-reduce.js";
|
|
6
|
+
import { cutPdfPages, type PageCut } from "./pdf-pages.js";
|
|
7
|
+
import type { Limiter } from "./limiter.js";
|
|
8
|
+
import { DocumentGoneError } from "./ranged.js";
|
|
6
9
|
import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS, type DocumentSource, type LineMatch } from "./search.js";
|
|
7
10
|
import { estimateParts, formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
|
|
8
11
|
import type { RetryOptions } from "./retry.js";
|
|
9
12
|
import { plural, removeInvisible, sliceWhole, wellFormedJson } from "./text.js";
|
|
10
|
-
import type { Budget, GenerateText, ProgressListener, ToolCallHooks, ToolCallLimits, ToolDeclaration, ToolOutput, ToolResult, ToolSet } from "./types.js";
|
|
13
|
+
import type { Budget, GenerateText, ProgressListener, ToolCallHooks, ToolCallLimits, ToolDeclaration, ToolName, ToolOutput, ToolResult, ToolSet } from "./types.js";
|
|
11
14
|
|
|
12
15
|
const DEFAULT_READ_LINES = 200;
|
|
13
16
|
/** Matching lines an exact or regex search shows: the default, and the most a call may ask for. */
|
|
@@ -44,7 +47,7 @@ export const TOOL_NAMES = {
|
|
|
44
47
|
analyze: "analyze_whole_document",
|
|
45
48
|
view: "view_pages",
|
|
46
49
|
aggregate: "aggregate_table",
|
|
47
|
-
} as const
|
|
50
|
+
} as const satisfies Record<string, ToolName>;
|
|
48
51
|
|
|
49
52
|
const documentId = { type: "string" as const, description: "The document_id from the file's card." };
|
|
50
53
|
|
|
@@ -90,12 +93,18 @@ const DECLARATIONS: Record<keyof typeof TOOL_NAMES, ToolDeclaration> = {
|
|
|
90
93
|
},
|
|
91
94
|
analyze: {
|
|
92
95
|
name: TOOL_NAMES.analyze,
|
|
96
|
+
// 0.9.0's words, kept: with a sentence on items here, Gemini Flash-Lite stopped choosing the
|
|
97
|
+
// read for a full summary. What items do is said in the description of `output` alone.
|
|
93
98
|
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.",
|
|
94
99
|
parameters: {
|
|
95
100
|
type: "object",
|
|
96
101
|
properties: {
|
|
97
102
|
document_id: documentId,
|
|
98
103
|
task: { type: "string", description: "What to find or produce from the whole file, stated completely." },
|
|
104
|
+
// "answer" is named for a summary and a timeline: told that items list things, Flash-Lite
|
|
105
|
+
// chose them for a timeline of events, whose items explain nothing, and lost events.
|
|
106
|
+
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." },
|
|
107
|
+
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.` },
|
|
99
108
|
},
|
|
100
109
|
required: ["document_id", "task"],
|
|
101
110
|
},
|
|
@@ -145,6 +154,20 @@ const DECLARATIONS: Record<keyof typeof TOOL_NAMES, ToolDeclaration> = {
|
|
|
145
154
|
},
|
|
146
155
|
};
|
|
147
156
|
|
|
157
|
+
/** The keys of `DECLARATIONS` in the order a tool set declares them. */
|
|
158
|
+
const DECLARATION_ORDER = ["search", "read", "overview", "aggregate", "analyze", "view"] as const satisfies ReadonlyArray<keyof typeof TOOL_NAMES>;
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* The declarations of the tools `names`, in the order a tool set declares them (search, read,
|
|
162
|
+
* overview, aggregate, analyze, view), whatever the order of `names`: those `files.tools(…,
|
|
163
|
+
* { declare: names })` gives. For planning the size of a request before the tools are made. A name
|
|
164
|
+
* that is not a tool's is left out. New in 0.10.0.
|
|
165
|
+
*/
|
|
166
|
+
export function declarationsFor(names: readonly ToolName[]): ToolDeclaration[] {
|
|
167
|
+
const wanted = new Set<string>(names);
|
|
168
|
+
return DECLARATION_ORDER.filter((key) => wanted.has(TOOL_NAMES[key])).map((key) => DECLARATIONS[key]);
|
|
169
|
+
}
|
|
170
|
+
|
|
148
171
|
/** Says so when a tool that returns files is run through `execute`, which has nowhere to put them. */
|
|
149
172
|
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.";
|
|
150
173
|
|
|
@@ -166,6 +189,64 @@ function flag(value: unknown): boolean {
|
|
|
166
189
|
|
|
167
190
|
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.";
|
|
168
191
|
|
|
192
|
+
/** The note of a read that stopped merging at the question's limit on model requests (N12, new in 0.10.0). */
|
|
193
|
+
const notesLeftOutNote = (leftOut: number, relevant: number): string =>
|
|
194
|
+
`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.`;
|
|
195
|
+
|
|
196
|
+
/** The items a read that lists them shows in its result; `total_items` counts them all. */
|
|
197
|
+
const MAX_SHOWN_ITEMS = 50;
|
|
198
|
+
|
|
199
|
+
/** The `labels` of a read that lists items, as the model sent them: up to `MAX_ITEM_LABELS`, each up to `MAX_LABEL_CHARACTERS`. */
|
|
200
|
+
function itemLabels(value: unknown): string[] | undefined {
|
|
201
|
+
const list = stringList(value, "labels")?.map((label) => label.trim()).filter(Boolean);
|
|
202
|
+
if (!list || list.length === 0) return undefined;
|
|
203
|
+
const distinct = [...new Set(list)];
|
|
204
|
+
if (distinct.length > MAX_ITEM_LABELS || distinct.some((label) => [...label].length > MAX_LABEL_CHARACTERS)) {
|
|
205
|
+
throw new Error(`labels takes up to ${MAX_ITEM_LABELS} labels, each up to ${MAX_LABEL_CHARACTERS} characters.`);
|
|
206
|
+
}
|
|
207
|
+
return distinct;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** A task as a note quotes it: ending in a stop, so that the sentence after it starts as one. */
|
|
211
|
+
const quotedTask = (task: string): string => {
|
|
212
|
+
const trimmed = task.trim();
|
|
213
|
+
return /[.!?…:;]$/u.test(trimmed) ? trimmed : `${trimmed}.`;
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
/** The sentence of a note on the items a result shows, when not all of them: as `itemsResult` and `fitItems` write it. */
|
|
217
|
+
const itemsShown = (shown: number, cut: boolean): string =>
|
|
218
|
+
`The first ${shown} ${plural(shown, "item")} ${shown === 1 ? "is" : "are"} shown${cut ? ", to stay within the size limit" : ""}; total_items counts them all.`;
|
|
219
|
+
const ITEMS_SHOWN = /The first \d+ items? (?:is|are) shown(?:, to stay within the size limit)?; total_items counts them all\.\s*/;
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* The result of a read that lists items (`output: "items"`): the totals, counted by code from the
|
|
223
|
+
* items each part listed and checked against its lines, and the first items in the order of the file.
|
|
224
|
+
*/
|
|
225
|
+
function itemsResult(file: string, task: string, read: WholeItemsResult): ToolResult {
|
|
226
|
+
const shown = read.items.slice(0, MAX_SHOWN_ITEMS);
|
|
227
|
+
const more = read.items.length - shown.length;
|
|
228
|
+
const notes = [
|
|
229
|
+
// With items listed and none found on its line, the note on those that are not counted follows.
|
|
230
|
+
...(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)}`] : []),
|
|
231
|
+
...(more > 0 ? [itemsShown(shown.length, false)] : []),
|
|
232
|
+
...(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.`] : []),
|
|
233
|
+
...(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.`] : []),
|
|
234
|
+
...(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.`] : []),
|
|
235
|
+
];
|
|
236
|
+
return {
|
|
237
|
+
document: file,
|
|
238
|
+
total_items: read.items.length,
|
|
239
|
+
...(Object.keys(read.countsByLabel).length > 0 ? { counts_by_label: read.countsByLabel } : {}),
|
|
240
|
+
items: shown.map(({ line, label, value, quote }) => ({ line, ...(label !== undefined ? { label } : {}), ...(value !== undefined ? { value } : {}), quote })),
|
|
241
|
+
...(more > 0 ? { more_items: more } : {}),
|
|
242
|
+
unverified_items: read.unverified,
|
|
243
|
+
parts_read: read.parts,
|
|
244
|
+
...(read.failedParts > 0 ? { parts_failed: read.failedParts } : {}),
|
|
245
|
+
...(read.truncatedParts > 0 ? { parts_cut_short: read.truncatedParts } : {}),
|
|
246
|
+
...(notes.length > 0 ? { note: notes.join(" ") } : {}),
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
169
250
|
function text(value: unknown, name: string): string {
|
|
170
251
|
if (typeof value !== "string" || !value.trim()) throw new Error(`${name} is required.`);
|
|
171
252
|
return value;
|
|
@@ -208,9 +289,12 @@ function fit(result: ToolResult, listKey: string | null, limit: number): ToolRes
|
|
|
208
289
|
|
|
209
290
|
/**
|
|
210
291
|
* The result of a whole-document read within `limit` characters: its answer is cut at the end,
|
|
211
|
-
* and says so, rather than the result being cut as JSON, which loses what the other fields say.
|
|
292
|
+
* and says so, rather than the result being cut as JSON, which loses what the other fields say. A
|
|
293
|
+
* read that lists items (`output: "items"`, new in 0.10.0) loses items from the end of its list,
|
|
294
|
+
* and keeps its counts.
|
|
212
295
|
*/
|
|
213
296
|
export function fitAnswer(result: ToolResult, limit: number): ToolResult {
|
|
297
|
+
if (JSON.stringify(result).length > limit && typeof result.answer !== "string" && Array.isArray(result.items) && result.items.length > 0) return fitItems(result, limit);
|
|
214
298
|
if (JSON.stringify(result).length <= limit || typeof result.answer !== "string") return fit(result, null, limit);
|
|
215
299
|
const answer = result.answer;
|
|
216
300
|
const cutAt = (keep: number): ToolResult => ({
|
|
@@ -230,6 +314,33 @@ export function fitAnswer(result: ToolResult, limit: number): ToolResult {
|
|
|
230
314
|
return fit(cutAt(low), null, limit);
|
|
231
315
|
}
|
|
232
316
|
|
|
317
|
+
/**
|
|
318
|
+
* The result of a read that lists items within `limit` characters: items are dropped from the end of
|
|
319
|
+
* its list, at least one kept, `more_items` counts every item not shown, and the note says how many
|
|
320
|
+
* are shown. Its counts stay whole. A result cut before (`askWithFiles` fits a result again to the
|
|
321
|
+
* room left) is cut the same way, from what it still shows.
|
|
322
|
+
*/
|
|
323
|
+
function fitItems(result: ToolResult, limit: number): ToolResult {
|
|
324
|
+
const items = result.items as unknown[];
|
|
325
|
+
const total = typeof result.total_items === "number" ? result.total_items : items.length;
|
|
326
|
+
const others = typeof result.note === "string" ? result.note.replace(ITEMS_SHOWN, "").trim() : "";
|
|
327
|
+
const build = (kept: number): ToolResult => {
|
|
328
|
+
const more = total - kept;
|
|
329
|
+
const out: ToolResult = {};
|
|
330
|
+
// The fields in their order, with more_items after the items.
|
|
331
|
+
for (const [key, value] of Object.entries(result)) {
|
|
332
|
+
if (key === "more_items" || key === "note") continue;
|
|
333
|
+
out[key] = key === "items" ? items.slice(0, kept) : value;
|
|
334
|
+
if (key === "items" && more > 0) out.more_items = more;
|
|
335
|
+
}
|
|
336
|
+
out.note = [itemsShown(kept, true), others].filter(Boolean).join(" ");
|
|
337
|
+
return out;
|
|
338
|
+
};
|
|
339
|
+
let kept = items.length;
|
|
340
|
+
while (kept > 1 && JSON.stringify(build(kept)).length > limit) kept--;
|
|
341
|
+
return fit(build(kept), null, limit);
|
|
342
|
+
}
|
|
343
|
+
|
|
233
344
|
/**
|
|
234
345
|
* The result of an exact or regex search that read the whole file: the first matches, then the
|
|
235
346
|
* last one of the file, and a note that says how many of how many are shown when that is not all.
|
|
@@ -567,6 +678,8 @@ export function alreadyShown(call: { name: string; args: Record<string, unknown>
|
|
|
567
678
|
const { result } = earlier;
|
|
568
679
|
if (earlier.call.name !== call.name || earlier.call.args.document_id !== call.args.document_id) return undefined;
|
|
569
680
|
if (result.dropped === true || result.already_shown === true || typeof result.error === "string" || result.truncated === true) return undefined;
|
|
681
|
+
// A result the application replaced (`onToolResult`, since 0.10.0) does not hold what the call returns.
|
|
682
|
+
if (result.redacted === true) return undefined;
|
|
570
683
|
// A search stored by 0.7.0 with case_sensitive or whole_word as text or 1 ("true", 1): 0.7.0 read
|
|
571
684
|
// those as off, 0.8.0 as on, so the call made now would not return what was stored.
|
|
572
685
|
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))) return undefined;
|
|
@@ -639,8 +752,13 @@ export function toolResultSummary(label: string, result: ToolResult): string {
|
|
|
639
752
|
const groups = typeof result.total_groups === "number" ? `, ${result.total_groups.toLocaleString("en-US")} ${plural(result.total_groups, "group")}` : "";
|
|
640
753
|
return ` — ${result.rows_matched.toLocaleString("en-US")} ${plural(result.rows_matched, "row")}${groups}`;
|
|
641
754
|
}
|
|
755
|
+
if (typeof result.total_items === "number" && typeof result.parts_read === "number") {
|
|
756
|
+
const unverified = typeof result.unverified_items === "number" && result.unverified_items > 0 ? `, ${result.unverified_items.toLocaleString("en-US")} not counted` : "";
|
|
757
|
+
const incomplete = result.parts_failed || result.parts_cut_short ? ", incomplete" : "";
|
|
758
|
+
return ` — ${result.total_items.toLocaleString("en-US")} ${plural(result.total_items, "item")} in ${result.parts_read} ${plural(result.parts_read, "part")}${unverified}${incomplete}`;
|
|
759
|
+
}
|
|
642
760
|
if (typeof result.parts_read === "number") {
|
|
643
|
-
const incomplete = result.notes_only ? ", notes only" : result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
|
|
761
|
+
const incomplete = result.notes_only ? ", notes only" : result.notes_cut_short || result.notes_left_out || result.answer_cut_short ? ", incomplete" : "";
|
|
644
762
|
return ` — ${result.parts_read} ${plural(result.parts_read, "part")}, ${String(result.parts_with_relevant_content ?? 0)} relevant${incomplete}`;
|
|
645
763
|
}
|
|
646
764
|
// A read reports its range only when it was cut short of what was asked.
|
|
@@ -677,9 +795,42 @@ export const unknownToolName = (name: string): string => `“${sliceWhole(name,
|
|
|
677
795
|
*/
|
|
678
796
|
const shownId = (id: string): string => (id.length > 64 ? `${sliceWhole(id, 64)}…` : id);
|
|
679
797
|
|
|
798
|
+
/** 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. */
|
|
799
|
+
const gone = (id: string) => new DocumentGoneError(`${id} is no longer available on the server. Ask the user to attach the file again.`);
|
|
800
|
+
|
|
801
|
+
/** A look at pages that waited its turn for too long: its message is the model's. */
|
|
802
|
+
class PagesBusyError extends Error {
|
|
803
|
+
constructor(readonly documentId: string, file: string) {
|
|
804
|
+
super(`${file}: The pages cannot be looked at right now; the server is busy. Answer from the text, or look again later.`);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
/** A timer may wait at most this long (2^31 - 1 ms, 24.8 days). */
|
|
809
|
+
const LONGEST_WAIT_MS = 2_147_483_647;
|
|
810
|
+
|
|
811
|
+
/** How the looks at pages of a library take their turns (`maxConcurrentPageLooks`, `pageLookWaitMs`). */
|
|
812
|
+
export type PageLookTurns = {
|
|
813
|
+
/** Shared by every tool set of the library: one look at a time, by default. */
|
|
814
|
+
limiter: Limiter;
|
|
815
|
+
/** How long a look waits for its turn before the model is told that the server is busy. Infinity: without end. */
|
|
816
|
+
waitMs: number;
|
|
817
|
+
/**
|
|
818
|
+
* How long a look may hold its turn while its original file is read from the store. Past it, the
|
|
819
|
+
* turn goes back and the model is told that the file could not be read in time: a store that
|
|
820
|
+
* never answers holds no turn for good. Left out, or Infinity: without end.
|
|
821
|
+
*/
|
|
822
|
+
holdMs?: number;
|
|
823
|
+
};
|
|
824
|
+
|
|
680
825
|
export function createDocumentTools(options: {
|
|
681
826
|
/** Loads a document the tools may access. Return undefined for anything out of scope. */
|
|
682
827
|
load(documentId: string): Promise<DocumentSource | undefined>;
|
|
828
|
+
/**
|
|
829
|
+
* Asked, once a call of a text tool has ended, about the document it read: false when the store
|
|
830
|
+
* no longer describes it as it was loaded, so that what was read of it may be another document's.
|
|
831
|
+
* The call then answers that the document is no longer available.
|
|
832
|
+
*/
|
|
833
|
+
checkRead?(document: DocumentSource): Promise<boolean>;
|
|
683
834
|
documentIds: string[];
|
|
684
835
|
/** File names by document ID, so `describe` can name files before they are loaded. */
|
|
685
836
|
names?: Record<string, string>;
|
|
@@ -706,26 +857,58 @@ export function createDocumentTools(options: {
|
|
|
706
857
|
viewableIds?: string[];
|
|
707
858
|
/** Loads the uploaded file of a document, for `view_pages`. */
|
|
708
859
|
loadOriginal?(documentId: string): Promise<Uint8Array | undefined>;
|
|
860
|
+
/**
|
|
861
|
+
* The turns of the looks at pages, shared by the tool sets of one library: a look waits for its
|
|
862
|
+
* turn before the original file is loaded. Without it, looks do not wait.
|
|
863
|
+
*/
|
|
864
|
+
pageLooks?: PageLookTurns;
|
|
709
865
|
/**
|
|
710
866
|
* True when a document may hold a table (a CSV, a workbook, a document with `| cell |` rows):
|
|
711
867
|
* `aggregate_table` is then declared. A call of it is answered either way. Defaults to false.
|
|
712
868
|
*/
|
|
713
869
|
tables?: boolean;
|
|
870
|
+
/**
|
|
871
|
+
* Declare exactly these tools, in the order of `declarationsFor`, in place of those the documents
|
|
872
|
+
* call for. A declared tool that cannot run answers each call with its reason. New in 0.10.0.
|
|
873
|
+
*/
|
|
874
|
+
declare?: readonly ToolName[];
|
|
875
|
+
/**
|
|
876
|
+
* The IDs of documents sent whole in the prompt: `analyze_whole_document` refuses them, as the
|
|
877
|
+
* model has every line of them already, and `aggregate_table` says how to cite their lines. New in
|
|
878
|
+
* 0.10.0.
|
|
879
|
+
*/
|
|
880
|
+
inline?: readonly string[];
|
|
714
881
|
}): ToolSet {
|
|
715
882
|
const allowed = new Set(options.documentIds);
|
|
716
883
|
const viewable = new Set(options.loadOriginal ? options.viewableIds ?? [] : []);
|
|
717
884
|
const names = new Map<string, string>(Object.entries(options.names ?? {}));
|
|
885
|
+
const inline = new Set(options.inline ?? []);
|
|
886
|
+
const declared = options.declare ? new Set<string>(options.declare) : undefined;
|
|
718
887
|
// The text tools are left out only when there are pages to look at and no document to search.
|
|
719
888
|
const textTools = allowed.size > 0 || viewable.size === 0;
|
|
720
|
-
const declarations = [
|
|
889
|
+
const declarations = options.declare ? declarationsFor(options.declare) : [
|
|
721
890
|
...(textTools ? [DECLARATIONS.search, DECLARATIONS.read, DECLARATIONS.overview, ...(options.tables ? [DECLARATIONS.aggregate] : []), ...(options.generate && options.wholeReads !== false ? [DECLARATIONS.analyze] : [])] : []),
|
|
722
891
|
...(viewable.size > 0 ? [DECLARATIONS.view] : []),
|
|
723
892
|
];
|
|
724
893
|
const known = new Set(declarations.map((declaration) => declaration.name));
|
|
725
|
-
//
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
894
|
+
// With `declare`, the tool set answers the tools it declares and no other: a call of one it does
|
|
895
|
+
// not declare (a whole-file read, many requests) is not run.
|
|
896
|
+
if (!declared) {
|
|
897
|
+
// Answered for any document, declared or not: a model may know the tool from earlier in the conversation.
|
|
898
|
+
if (textTools) known.add(TOOL_NAMES.aggregate);
|
|
899
|
+
// Not declared for files that are all too large for it, but still answered: with the reason, not "unknown tool".
|
|
900
|
+
if (textTools && options.generate) known.add(TOOL_NAMES.analyze);
|
|
901
|
+
}
|
|
902
|
+
/**
|
|
903
|
+
* Why a declared tool cannot run in this tool set, when it cannot: each call of it answers with
|
|
904
|
+
* this. A caller may declare a tool (`ToolOptions.declare`) that has nothing to work on here.
|
|
905
|
+
*/
|
|
906
|
+
const cannotRun = (name: string): string | undefined => {
|
|
907
|
+
if (!declared?.has(name)) return undefined;
|
|
908
|
+
if (name === TOOL_NAMES.aggregate && !options.tables) return "No attached file has a table: aggregate_table needs one.";
|
|
909
|
+
if (name === TOOL_NAMES.view && viewable.size === 0) return "No attached file has pages to look at: view_pages needs a PDF whose original file is kept. Answer from the text.";
|
|
910
|
+
return undefined;
|
|
911
|
+
};
|
|
729
912
|
const cap = options.budget.toolResultCharacters;
|
|
730
913
|
/** 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
914
|
const limitOf = (limits: ToolCallLimits, own = cap): number => {
|
|
@@ -755,10 +938,54 @@ export function createDocumentTools(options: {
|
|
|
755
938
|
const wholeReads = new Map<string, number>();
|
|
756
939
|
/** Why the last whole-document read of a document failed, when no part of it could be read. */
|
|
757
940
|
const failedWholeReads = new Map<string, string>();
|
|
941
|
+
const wholeReadsDeclared = declarations.some((declaration) => declaration.name === TOOL_NAMES.analyze);
|
|
942
|
+
/**
|
|
943
|
+
* What a `read_document` result cut short of its range by the size limit adds (`whole_file`), as
|
|
944
|
+
* the lines it shows of the file from `start` (`shown`, or none whole when `cut`: the text of the
|
|
945
|
+
* first line was cut): that `analyze_whole_document` reads all of it. Gemini Flash-Lite and Flash
|
|
946
|
+
* read a contract to summarize in ranges of about 16 lines, and answered from those
|
|
947
|
+
* (`evals/results/0100-t-live-3.md`). Only when this tool set declares the read and would run it on
|
|
948
|
+
* the file, by the estimate of its parts: a part reader, a file not sent whole, a read of it left,
|
|
949
|
+
* and its parts within `maxMapChunks` and within the requests the call says a whole read may make
|
|
950
|
+
* (`limits.maxRequests`), the checks the read makes before it sends a part (`partsToRead`). The
|
|
951
|
+
* parts are `estimateParts`'s, without the margin `canBeReadWhole` gives the estimate. The read
|
|
952
|
+
* counts its own, and at a border may count one more than the estimate: then it is refused, before
|
|
953
|
+
* it sends a request. `askWithFiles` gives a read 0 requests when the question would not start a
|
|
954
|
+
* whole read of its file on the next turn, the first the model can call it on (its ceilings on
|
|
955
|
+
* input tokens and requests, with that turn's request counted, its whole reads made). New in 0.10.0.
|
|
956
|
+
*/
|
|
957
|
+
const wholeFileHint = (document: DocumentSource, start: number, shown: number, cut: boolean, limits: ToolCallLimits): string | undefined => {
|
|
958
|
+
const id = document.meta.id;
|
|
959
|
+
if (!wholeReadsDeclared || !options.generate || inline.has(id) || failedWholeReads.has(id) || (wholeReads.get(id) ?? 0) >= maxWholeReads) return undefined;
|
|
960
|
+
const requests = typeof limits.maxRequests === "number" && !Number.isNaN(limits.maxRequests) ? limits.maxRequests : Number.POSITIVE_INFINITY;
|
|
961
|
+
// Every part is one request.
|
|
962
|
+
if (requests < 1) return undefined;
|
|
963
|
+
const parts = estimateParts(document.meta, options.budget);
|
|
964
|
+
// Metadata that does not give its size (a record an application kept in part): as `canBeReadWhole`, not held back.
|
|
965
|
+
if (Number.isFinite(parts) && (parts > options.budget.maxMapChunks || parts > requests)) return undefined;
|
|
966
|
+
const total = document.lineCount.toLocaleString("en-US");
|
|
967
|
+
const fitting = cut
|
|
968
|
+
? `Not even one line fits here: the text of line ${start.toLocaleString("en-US")} is cut.`
|
|
969
|
+
: `Only ${shown.toLocaleString("en-US")} ${shown === 1 ? "line fits" : "lines fit"} here.`;
|
|
970
|
+
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.`;
|
|
971
|
+
};
|
|
758
972
|
// When no limit is given with a call: three eighths of a request, so that two looks still fit.
|
|
759
973
|
const defaultFileBytes = Math.floor((options.budget.maxRequestBytes - REQUEST_BYTES_MARGIN) * 3 / 8);
|
|
760
974
|
|
|
761
|
-
|
|
975
|
+
/** The documents the calls under way loaded, by the arguments of the call: checked once it ends (`checkRead`). */
|
|
976
|
+
const loaded = new WeakMap<object, Set<DocumentSource[]>>();
|
|
977
|
+
|
|
978
|
+
/**
|
|
979
|
+
* The signal of one call: the tool set's, joined with the call's own (`ToolCallHooks.signal`, new
|
|
980
|
+
* in 0.10.0) when it has one. The call's own ends that call alone.
|
|
981
|
+
*/
|
|
982
|
+
const signalOf = (hooks: ToolCallHooks): AbortSignal | undefined => {
|
|
983
|
+
const own = hooks.signal;
|
|
984
|
+
if (!own) return options.signal;
|
|
985
|
+
return options.signal ? AbortSignal.any([options.signal, own]) : own;
|
|
986
|
+
};
|
|
987
|
+
|
|
988
|
+
async function documentFor(args: Record<string, unknown>, signal: AbortSignal | undefined): Promise<DocumentSource> {
|
|
762
989
|
const id = text(args.document_id, "document_id");
|
|
763
990
|
// Scope check: a model can only reach files attached to this conversation.
|
|
764
991
|
if (!allowed.has(id)) {
|
|
@@ -768,16 +995,64 @@ export function createDocumentTools(options: {
|
|
|
768
995
|
? `Unknown document_id ${shownId(id)}. No attached file is read with this tool in this conversation.`
|
|
769
996
|
: `Unknown document_id ${shownId(id)}. Use one of: ${usable.join(", ")}${allowed.size > 20 ? ", …" : ""}.`);
|
|
770
997
|
}
|
|
771
|
-
|
|
772
|
-
|
|
998
|
+
// A load that hangs does not hold a call that was stopped.
|
|
999
|
+
const document = await until(options.load(id), signal);
|
|
1000
|
+
if (!document) throw gone(id);
|
|
1001
|
+
for (const reads of loaded.get(args) ?? []) reads.push(document);
|
|
773
1002
|
names.set(id, document.meta.name);
|
|
774
1003
|
return document;
|
|
775
1004
|
}
|
|
776
1005
|
|
|
777
|
-
|
|
778
|
-
|
|
1006
|
+
/**
|
|
1007
|
+
* Waits for the turn of a look at pages of `file`, for at most `pageLookWaitMs`, or the call's
|
|
1008
|
+
* `maxWaitMs` when that is less. Returns the function that gives the turn back. Past the wait, a
|
|
1009
|
+
* `PagesBusyError`. The wait ends at once when the call is stopped (`signal`), with the reason it
|
|
1010
|
+
* was stopped for.
|
|
1011
|
+
*/
|
|
1012
|
+
async function pageLookTurn(id: string, file: string, limits: ToolCallLimits, signal: AbortSignal | undefined): Promise<() => void> {
|
|
1013
|
+
const turns = options.pageLooks;
|
|
1014
|
+
if (!turns) return () => undefined;
|
|
1015
|
+
const waited = new AbortController();
|
|
1016
|
+
const callWait = typeof limits.maxWaitMs === "number" && !Number.isNaN(limits.maxWaitMs) ? limits.maxWaitMs : Infinity;
|
|
1017
|
+
const waitMs = Math.max(0, Math.min(turns.waitMs, callWait));
|
|
1018
|
+
const timer = waitMs <= LONGEST_WAIT_MS ? setTimeout(() => waited.abort(), waitMs) : undefined;
|
|
1019
|
+
timer?.unref?.();
|
|
1020
|
+
try {
|
|
1021
|
+
return await turns.limiter.acquire(signal ? AbortSignal.any([signal, waited.signal]) : waited.signal);
|
|
1022
|
+
} catch (error) {
|
|
1023
|
+
if (signal?.aborted || !waited.signal.aborted) throw error;
|
|
1024
|
+
throw new PagesBusyError(id, file);
|
|
1025
|
+
} finally {
|
|
1026
|
+
clearTimeout(timer);
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
/**
|
|
1031
|
+
* The original file of a look, read while the look holds its turn: for at most `holdMs`, and
|
|
1032
|
+
* only while the call runs. A read given up on goes on, but holds no turn.
|
|
1033
|
+
*/
|
|
1034
|
+
async function originalOf(id: string, file: string, signal: AbortSignal | undefined): Promise<Uint8Array | undefined> {
|
|
1035
|
+
const reading = until(options.loadOriginal!(id), signal);
|
|
1036
|
+
const holdMs = options.pageLooks?.holdMs;
|
|
1037
|
+
if (holdMs === undefined || !(holdMs <= LONGEST_WAIT_MS)) return reading;
|
|
1038
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
1039
|
+
// The timer keeps the process alive: a read that never ends may hold nothing that does, and
|
|
1040
|
+
// the question waiting for it would be lost.
|
|
1041
|
+
const late = new Promise<never>((_, reject) => {
|
|
1042
|
+
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));
|
|
1043
|
+
});
|
|
1044
|
+
try {
|
|
1045
|
+
return await Promise.race([reading, late]);
|
|
1046
|
+
} finally {
|
|
1047
|
+
clearTimeout(timer);
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
/** The tools that return JSON. `signal` is the call's (`signalOf`). */
|
|
1052
|
+
const handlers: Record<string, (args: Record<string, unknown>, limits: ToolCallLimits, hooks: ToolCallHooks, signal: AbortSignal | undefined) => Promise<ToolResult>> = {
|
|
1053
|
+
async [TOOL_NAMES.search](args, limits, _hooks, signal) {
|
|
779
1054
|
const limit = limitOf(limits);
|
|
780
|
-
const document = await documentFor(args);
|
|
1055
|
+
const document = await documentFor(args, signal);
|
|
781
1056
|
const query = text(args.query, "query");
|
|
782
1057
|
const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
|
|
783
1058
|
// Page numbers are added only for a PDF whose pages can be looked at: they are what
|
|
@@ -795,7 +1070,7 @@ export function createDocumentTools(options: {
|
|
|
795
1070
|
if (mode === "keywords") {
|
|
796
1071
|
if (groupBy) throw new Error("group_by counts the lines of an exact or regex search: use mode \"exact\" or \"regex\".");
|
|
797
1072
|
const topK = integer(args.max_results, 5, 1, 10);
|
|
798
|
-
const ranked = await rankSource(document, query, topK,
|
|
1073
|
+
const ranked = await rankSource(document, query, topK, signal, ranged ? range : undefined);
|
|
799
1074
|
const texts = await Promise.all(ranked.map((passage) => document.readLines(passage.from, passage.to)));
|
|
800
1075
|
return fit({
|
|
801
1076
|
document: document.meta.name,
|
|
@@ -826,7 +1101,7 @@ export function createDocumentTools(options: {
|
|
|
826
1101
|
maxResults: integer(args.max_results, DEFAULT_GREP_RESULTS, 1, MAX_GREP_RESULTS),
|
|
827
1102
|
contextLines: integer(args.context_lines, 0, 0, 5),
|
|
828
1103
|
...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
|
|
829
|
-
...(
|
|
1104
|
+
...(signal ? { signal } : {}),
|
|
830
1105
|
...(ranged ? { fromLine: range.from, toLine: range.to } : {}),
|
|
831
1106
|
...(order === "last" ? { order } : {}),
|
|
832
1107
|
...(groupBy ? { groupBy } : {}),
|
|
@@ -872,9 +1147,9 @@ export function createDocumentTools(options: {
|
|
|
872
1147
|
}, "matches", limit);
|
|
873
1148
|
},
|
|
874
1149
|
|
|
875
|
-
async [TOOL_NAMES.read](args, limits) {
|
|
1150
|
+
async [TOOL_NAMES.read](args, limits, _hooks, signal) {
|
|
876
1151
|
const limit = limitOf(limits);
|
|
877
|
-
const document = await documentFor(args);
|
|
1152
|
+
const document = await documentFor(args, signal);
|
|
878
1153
|
const total = document.lineCount;
|
|
879
1154
|
const start = integer(args.start_line, 1, 1, total);
|
|
880
1155
|
const end = integer(args.end_line, start + DEFAULT_READ_LINES - 1, start, Math.min(total, start + MAX_READ_LINES - 1));
|
|
@@ -889,21 +1164,28 @@ export function createDocumentTools(options: {
|
|
|
889
1164
|
body = numberLines(read.slice(0, to - start + 1), start);
|
|
890
1165
|
}
|
|
891
1166
|
const pages = viewable.has(document.meta.id) ? document.pagesOfLines(start, to) : undefined;
|
|
892
|
-
|
|
1167
|
+
const cut = !fits(body);
|
|
1168
|
+
const result: ToolResult = {
|
|
893
1169
|
document: document.meta.name,
|
|
894
1170
|
lines: `${start}-${to}`,
|
|
895
1171
|
...(pages ? { pages } : {}),
|
|
896
1172
|
total_lines: total,
|
|
897
|
-
text:
|
|
1173
|
+
text: cut ? sliceWhole(body, Math.floor((limit - 500) / 2)) : body,
|
|
898
1174
|
// One line longer than the room: its text was cut, so the lines are not all shown.
|
|
899
|
-
...(
|
|
1175
|
+
...(cut ? { text_cut: true } : {}),
|
|
900
1176
|
...(to < total ? { next_start_line: to + 1 } : { note: "End of file." }),
|
|
901
1177
|
};
|
|
1178
|
+
// Cut short of the range asked by the size limit: the way to all of the file, when there is
|
|
1179
|
+
// one. Left out when it would take the result past its cap.
|
|
1180
|
+
const hint = to < end ? wholeFileHint(document, start, to - start + 1, cut, limits) : undefined;
|
|
1181
|
+
if (!hint) return result;
|
|
1182
|
+
const hinted = { ...result, whole_file: hint };
|
|
1183
|
+
return JSON.stringify(hinted).length <= limit ? hinted : result;
|
|
902
1184
|
},
|
|
903
1185
|
|
|
904
|
-
async [TOOL_NAMES.overview](args, limits) {
|
|
1186
|
+
async [TOOL_NAMES.overview](args, limits, _hooks, signal) {
|
|
905
1187
|
const limit = limitOf(limits);
|
|
906
|
-
const document = await documentFor(args);
|
|
1188
|
+
const document = await documentFor(args, signal);
|
|
907
1189
|
const { meta, lineCount } = document;
|
|
908
1190
|
const tail = Math.max(1, lineCount - 19);
|
|
909
1191
|
// Counting the parts means reading the whole text, for a number that only says how costly a
|
|
@@ -928,11 +1210,11 @@ export function createDocumentTools(options: {
|
|
|
928
1210
|
}, "outline", limit);
|
|
929
1211
|
},
|
|
930
1212
|
|
|
931
|
-
async [TOOL_NAMES.aggregate](args, limits) {
|
|
1213
|
+
async [TOOL_NAMES.aggregate](args, limits, _hooks, signal) {
|
|
932
1214
|
const limit = limitOf(limits);
|
|
933
|
-
const document = await documentFor(args);
|
|
1215
|
+
const document = await documentFor(args, signal);
|
|
934
1216
|
const request = aggregateRequest(args);
|
|
935
|
-
const result = await aggregateTable(document, request,
|
|
1217
|
+
const result = await aggregateTable(document, request, signal);
|
|
936
1218
|
const groups = result.groups.map((group) => ({
|
|
937
1219
|
...(Object.keys(group.key).length > 0 ? { group: group.key } : {}),
|
|
938
1220
|
...group.values,
|
|
@@ -956,24 +1238,40 @@ export function createDocumentTools(options: {
|
|
|
956
1238
|
...(result.repeatedHeaders > 0 ? { repeated_header_rows: result.repeatedHeaders } : {}),
|
|
957
1239
|
...(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." } : {}),
|
|
958
1240
|
...(result.irregularRows > 0 ? { irregular_rows: result.irregularRows, irregular_note: "Rows with values past the header's columns: check columns and header_rows." } : {}),
|
|
1241
|
+
// 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.
|
|
1242
|
+
...(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(" ") } : {}),
|
|
959
1243
|
};
|
|
960
1244
|
const note = groups.length < result.totalGroups
|
|
961
1245
|
? { 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.` }
|
|
962
1246
|
: {};
|
|
963
|
-
|
|
1247
|
+
// Over a table shown in full, Flash-Lite answered with the count alone, citing no line: the
|
|
1248
|
+
// result says how to cite the lines it lists, with the file's name (since 0.10.0).
|
|
1249
|
+
const firstLines = groups[0]?.lines ?? [];
|
|
1250
|
+
const cite = inline.has(document.meta.id) && firstLines.length > 0
|
|
1251
|
+
? { cite: `Cite the lines listed in your answer, like (${document.meta.name} ${firstLines.map((line) => `L${line}`).join(", ")}).` }
|
|
1252
|
+
: {};
|
|
1253
|
+
return fit({ ...base, ...note, groups, ...cite }, "groups", limit);
|
|
964
1254
|
},
|
|
965
1255
|
|
|
966
|
-
async [TOOL_NAMES.analyze](args, limits, hooks) {
|
|
1256
|
+
async [TOOL_NAMES.analyze](args, limits, hooks, signal) {
|
|
967
1257
|
if (!options.generate) throw new Error("Whole-document analysis is not enabled.");
|
|
968
|
-
|
|
1258
|
+
// A document sent whole is not read again in parts: the model has every line of it.
|
|
1259
|
+
const asked = text(args.document_id, "document_id");
|
|
1260
|
+
if (inline.has(asked)) 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.`);
|
|
1261
|
+
const document = await documentFor(args, signal);
|
|
969
1262
|
const task = text(args.task, "task");
|
|
1263
|
+
const items = args.output === "items";
|
|
1264
|
+
// Read before the count is taken: a call with labels it cannot use is no read.
|
|
1265
|
+
const labels = items ? itemLabels(args.labels) : undefined;
|
|
970
1266
|
// A read of the whole file is many model requests. A model that asks for it again, with the
|
|
971
1267
|
// task put another way, is told to use what it has. The count is taken before the read
|
|
972
1268
|
// starts, so that two calls in one turn do not both pass.
|
|
973
1269
|
const id = document.meta.id;
|
|
974
1270
|
const reads = wholeReads.get(id) ?? 0;
|
|
975
|
-
|
|
976
|
-
|
|
1271
|
+
const failure = failedWholeReads.get(id);
|
|
1272
|
+
// A read that could read no part is not tried again, whatever the cap: another would most
|
|
1273
|
+
// likely fail the same way, and `wholeReadsLeft` says 0 for it.
|
|
1274
|
+
if (reads >= maxWholeReads || failure !== undefined) {
|
|
977
1275
|
throw new Error(maxWholeReads === 0
|
|
978
1276
|
? `Whole-file reads are turned off for this question. Use search_document and read_document on ${document.meta.name}.`
|
|
979
1277
|
: failure !== undefined
|
|
@@ -982,20 +1280,21 @@ export function createDocumentTools(options: {
|
|
|
982
1280
|
: `${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.`);
|
|
983
1281
|
}
|
|
984
1282
|
wholeReads.set(id, reads + 1);
|
|
1283
|
+
const read = {
|
|
1284
|
+
document,
|
|
1285
|
+
task,
|
|
1286
|
+
generate: options.generate,
|
|
1287
|
+
budget: options.budget,
|
|
1288
|
+
// The call's own listener, when it has one, in place of the tool set's.
|
|
1289
|
+
onProgress: hooks.onProgress ?? options.onProgress,
|
|
1290
|
+
...(hooks.onRequest ? { onRequest: hooks.onRequest } : {}),
|
|
1291
|
+
signal,
|
|
1292
|
+
...(options.retry ? { retry: options.retry } : {}),
|
|
1293
|
+
...(typeof limits.maxRequests === "number" && Number.isFinite(limits.maxRequests) ? { maxRequests: limits.maxRequests } : {}),
|
|
1294
|
+
};
|
|
985
1295
|
let result;
|
|
986
1296
|
try {
|
|
987
|
-
result = await analyzeWholeDocument(
|
|
988
|
-
document,
|
|
989
|
-
task,
|
|
990
|
-
generate: options.generate,
|
|
991
|
-
budget: options.budget,
|
|
992
|
-
// The call's own listener, when it has one, in place of the tool set's.
|
|
993
|
-
onProgress: hooks.onProgress ?? options.onProgress,
|
|
994
|
-
...(hooks.onRequest ? { onRequest: hooks.onRequest } : {}),
|
|
995
|
-
signal: options.signal,
|
|
996
|
-
...(options.retry ? { retry: options.retry } : {}),
|
|
997
|
-
...(typeof limits.maxRequests === "number" && Number.isFinite(limits.maxRequests) ? { maxRequests: limits.maxRequests } : {}),
|
|
998
|
-
});
|
|
1297
|
+
result = items ? await listWholeDocumentItems({ ...read, ...(labels ? { labels } : {}) }) : await analyzeWholeDocument(read);
|
|
999
1298
|
} catch (error) {
|
|
1000
1299
|
// Parts were sent and none could be read: that read is counted, since another would most
|
|
1001
1300
|
// likely fail the same way. Anything else (too many parts, a store that could not be read)
|
|
@@ -1007,25 +1306,35 @@ export function createDocumentTools(options: {
|
|
|
1007
1306
|
throw error;
|
|
1008
1307
|
}
|
|
1009
1308
|
failedWholeReads.delete(id);
|
|
1309
|
+
const room = limitOf(limits, Math.max(cap, ANALYSIS_RESULT_CHARACTERS));
|
|
1310
|
+
if ("items" in result) return fitAnswer(itemsResult(document.meta.name, task, result), room);
|
|
1010
1311
|
const notesCutShort = result.truncatedParts + result.truncatedMerges;
|
|
1312
|
+
const cutNote = notesCutShort ? " Some of them were cut off at the output limit, so they are incomplete: tell the user." : "";
|
|
1011
1313
|
return fitAnswer({
|
|
1012
1314
|
document: document.meta.name,
|
|
1013
1315
|
parts_read: result.parts,
|
|
1014
1316
|
parts_with_relevant_content: result.relevantParts,
|
|
1015
1317
|
...(result.failedParts ? { parts_that_failed: result.failedParts } : {}),
|
|
1016
1318
|
...(notesCutShort ? { notes_cut_short: notesCutShort } : {}),
|
|
1319
|
+
...(result.notesLeftOut ? { notes_left_out: result.notesLeftOut } : {}),
|
|
1017
1320
|
...(result.answerTruncated ? { answer_cut_short: true } : {}),
|
|
1018
|
-
...(result.answerFailed !== undefined ? { notes_only: true } : {}),
|
|
1321
|
+
...(result.answerFailed !== undefined || result.answerSkipped ? { notes_only: true } : {}),
|
|
1019
1322
|
...(result.answerFailed !== undefined
|
|
1020
|
-
? { 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.${
|
|
1021
|
-
:
|
|
1323
|
+
? { 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}` }
|
|
1324
|
+
: result.answerSkipped
|
|
1325
|
+
? { 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}` }
|
|
1326
|
+
: result.notesLeftOut
|
|
1327
|
+
? { note: notesLeftOutNote(result.notesLeftOut, result.relevantParts) }
|
|
1328
|
+
: notesCutShort || result.answerTruncated ? { note: INCOMPLETE_ANALYSIS } : {}),
|
|
1022
1329
|
answer: result.answer,
|
|
1023
|
-
},
|
|
1330
|
+
}, room);
|
|
1024
1331
|
},
|
|
1025
1332
|
};
|
|
1026
1333
|
|
|
1027
1334
|
/** `view_pages`: the pages as one small PDF, next to a short JSON result. */
|
|
1028
|
-
async function viewPages(args: Record<string, unknown>, limits: ToolCallLimits): Promise<ToolOutput> {
|
|
1335
|
+
async function viewPages(args: Record<string, unknown>, limits: ToolCallLimits, signal: AbortSignal | undefined): Promise<ToolOutput> {
|
|
1336
|
+
const reason = cannotRun(TOOL_NAMES.view);
|
|
1337
|
+
if (reason) throw new Error(reason);
|
|
1029
1338
|
const id = text(args.document_id, "document_id");
|
|
1030
1339
|
// The same scope check as the text tools, on its own list: a PDF can be looked at without
|
|
1031
1340
|
// being searchable, and the other way round.
|
|
@@ -1034,8 +1343,8 @@ export function createDocumentTools(options: {
|
|
|
1034
1343
|
? `The pages of ${names.get(id) ?? id} cannot be shown: only its text was kept. Answer from the text.`
|
|
1035
1344
|
: `Unknown document_id ${shownId(id)}. Use the document_id of an attached PDF.`);
|
|
1036
1345
|
}
|
|
1037
|
-
const document = await options.load(id);
|
|
1038
|
-
if (!document) throw
|
|
1346
|
+
const document = await until(options.load(id), signal);
|
|
1347
|
+
if (!document) throw gone(id);
|
|
1039
1348
|
const file = document.meta.name;
|
|
1040
1349
|
names.set(id, file);
|
|
1041
1350
|
const from = pageNumber(args.from_page, "from_page");
|
|
@@ -1048,13 +1357,32 @@ export function createDocumentTools(options: {
|
|
|
1048
1357
|
if (mostPages < 1) throw new Error("No more pages can be looked at for this question. Answer from the pages and the text you already have.");
|
|
1049
1358
|
const maxBytes = whole(limits.maxFileBytes, defaultFileBytes);
|
|
1050
1359
|
if (maxBytes < MIN_FILE_BYTES) throw new Error("There is no room left in this request to show more pages. Answer from the pages and the text you already have.");
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1360
|
+
// Looks take their turns in the library (`maxConcurrentPageLooks`): they share one thread, and
|
|
1361
|
+
// more of them at once only hold more memory. The original is loaded once the turn comes, so a
|
|
1362
|
+
// look that waits holds none of its bytes, and the memory left is looked at then (`cutPdfPages`).
|
|
1363
|
+
// A question stopped while its original is read gives the turn back at once, and so does a
|
|
1364
|
+
// read that takes longer than the library allows its store calls (`holdMs`).
|
|
1365
|
+
const release = await pageLookTurn(id, file, limits, signal);
|
|
1366
|
+
let cut: PageCut | undefined;
|
|
1054
1367
|
try {
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1368
|
+
signal?.throwIfAborted();
|
|
1369
|
+
const original = await originalOf(id, file, signal);
|
|
1370
|
+
// Stopped while the original was read: no pages are cut for a question that has left.
|
|
1371
|
+
signal?.throwIfAborted();
|
|
1372
|
+
if (original) {
|
|
1373
|
+
try {
|
|
1374
|
+
cut = await cutPdfPages(original, from, Math.min(asked, from + mostPages - 1), maxBytes, total);
|
|
1375
|
+
} catch (error) {
|
|
1376
|
+
throw new Error(`${file}: ${safeErrorMessage(error)}`);
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
} finally {
|
|
1380
|
+
release();
|
|
1381
|
+
}
|
|
1382
|
+
if (!cut) {
|
|
1383
|
+
// The document may have gone while the look waited for its turn: that is told as such.
|
|
1384
|
+
if (!await until(options.load(id), signal)) throw gone(id);
|
|
1385
|
+
throw new Error(`The original file of ${file} is no longer on the server, so its pages cannot be shown. Answer from the text.`);
|
|
1058
1386
|
}
|
|
1059
1387
|
const pages = pageRange(cut.from, cut.to);
|
|
1060
1388
|
const shown = cut.to - cut.from + 1;
|
|
@@ -1073,19 +1401,65 @@ export function createDocumentTools(options: {
|
|
|
1073
1401
|
};
|
|
1074
1402
|
}
|
|
1075
1403
|
|
|
1076
|
-
|
|
1077
|
-
|
|
1404
|
+
/**
|
|
1405
|
+
* What a tool could not do goes to the model, and from there to a user's screen: never a server
|
|
1406
|
+
* path. A document found gone, or a look that waited too long, is also told to the call's hooks.
|
|
1407
|
+
*/
|
|
1408
|
+
const failure = (error: unknown, args: Record<string, unknown>, hooks: ToolCallHooks): ToolResult => {
|
|
1409
|
+
// Found gone when the call began, or while a read by range went through its text.
|
|
1410
|
+
if (error instanceof DocumentGoneError && typeof args.document_id === "string") hooks.onDocumentGone?.(args.document_id);
|
|
1411
|
+
else if (error instanceof PagesBusyError) hooks.onPagesBusy?.(error.documentId);
|
|
1412
|
+
return { error: safeErrorMessage(error) };
|
|
1413
|
+
};
|
|
1414
|
+
|
|
1415
|
+
/**
|
|
1416
|
+
* True for an error the call throws rather than tells the model: the call, or the tool set, was
|
|
1417
|
+
* stopped; or the store did not answer in time, or was not asked because too many store calls are
|
|
1418
|
+
* stuck (since 0.10.0), which ends the question with an error and shows the model nothing.
|
|
1419
|
+
*/
|
|
1420
|
+
const thrown = (error: unknown, signal: AbortSignal | undefined): boolean => signal?.aborted === true || storeGaveUp(error);
|
|
1078
1421
|
|
|
1079
1422
|
async function execute(name: string, args: Record<string, unknown>, limits: ToolCallLimits = {}, hooks: ToolCallHooks = {}): Promise<ToolResult> {
|
|
1080
1423
|
if (!known.has(name)) return { error: `Unknown tool ${unknownToolName(name)}.` };
|
|
1081
1424
|
// The pages are a file, and this method returns only JSON. Saying that pages are attached
|
|
1082
1425
|
// with nothing attached would be worse than saying that they could not be shown.
|
|
1083
|
-
if (name === TOOL_NAMES.view) return { error: FILES_NOT_DELIVERED };
|
|
1426
|
+
if (name === TOOL_NAMES.view) return { error: cannotRun(name) ?? FILES_NOT_DELIVERED };
|
|
1427
|
+
const reason = cannotRun(name);
|
|
1428
|
+
if (reason) return { error: reason };
|
|
1429
|
+
const signal = signalOf(hooks);
|
|
1430
|
+
// The documents this call loads (`documentFor`), by its arguments: calls given the same object
|
|
1431
|
+
// at once each note them all.
|
|
1432
|
+
const reads: DocumentSource[] = [];
|
|
1433
|
+
const calls = typeof args === "object" && args !== null ? loaded.get(args) ?? new Set<DocumentSource[]>() : undefined;
|
|
1434
|
+
if (calls) loaded.set(args, calls.add(reads));
|
|
1435
|
+
/**
|
|
1436
|
+
* Asks the store, once the call has ended, whether each document it read is still the one it
|
|
1437
|
+
* loaded. A call with a signal of its own ends when it aborts, even while this store call hangs.
|
|
1438
|
+
*/
|
|
1439
|
+
const checkReads = async () => {
|
|
1440
|
+
const checking = (async () => {
|
|
1441
|
+
for (const document of reads) if (options.checkRead && !await options.checkRead(document)) throw gone(document.meta.id);
|
|
1442
|
+
})();
|
|
1443
|
+
await (hooks.signal ? until(checking, signal) : checking);
|
|
1444
|
+
};
|
|
1084
1445
|
try {
|
|
1085
|
-
|
|
1446
|
+
let result: ToolResult;
|
|
1447
|
+
try {
|
|
1448
|
+
// A call with a signal of its own ends when it aborts, even in a store call that hangs.
|
|
1449
|
+
const running = handlers[name]!(args, limits, hooks, signal);
|
|
1450
|
+
result = await (hooks.signal ? until(running, signal) : running);
|
|
1451
|
+
} catch (error) {
|
|
1452
|
+
if (thrown(error, signal)) throw error;
|
|
1453
|
+
await checkReads();
|
|
1454
|
+
throw error;
|
|
1455
|
+
}
|
|
1456
|
+
await checkReads();
|
|
1457
|
+
return result;
|
|
1086
1458
|
} catch (error) {
|
|
1087
|
-
if (
|
|
1088
|
-
return failure(error);
|
|
1459
|
+
if (thrown(error, signal)) throw error;
|
|
1460
|
+
return failure(error, args, hooks);
|
|
1461
|
+
} finally {
|
|
1462
|
+
calls?.delete(reads);
|
|
1089
1463
|
}
|
|
1090
1464
|
}
|
|
1091
1465
|
|
|
@@ -1093,16 +1467,27 @@ export function createDocumentTools(options: {
|
|
|
1093
1467
|
declarations,
|
|
1094
1468
|
has: (name) => known.has(name),
|
|
1095
1469
|
execute: (name, args) => execute(name, args),
|
|
1096
|
-
|
|
1470
|
+
// A name the tool set does not answer, a declared tool that cannot run, and a whole-file read
|
|
1471
|
+
// with no part reader each get an error of a few words: no more room is kept for them.
|
|
1472
|
+
resultCharacters: (name) => (!known.has(name) || cannotRun(name) !== undefined || (name === TOOL_NAMES.analyze && !options.generate) ? LEAST_RESULT_CHARACTERS
|
|
1473
|
+
: name === TOOL_NAMES.analyze ? Math.max(cap, ANALYSIS_RESULT_CHARACTERS) : name === TOOL_NAMES.view ? LEAST_RESULT_CHARACTERS : cap),
|
|
1097
1474
|
async executeWithFiles(name, args, limits = {}, hooks = {}) {
|
|
1098
1475
|
if (name !== TOOL_NAMES.view || !known.has(name)) return { result: await execute(name, args, limits, hooks), files: [] };
|
|
1476
|
+
const signal = signalOf(hooks);
|
|
1099
1477
|
try {
|
|
1100
|
-
|
|
1478
|
+
const running = viewPages(args, limits, signal);
|
|
1479
|
+
return await (hooks.signal ? until(running, signal) : running);
|
|
1101
1480
|
} catch (error) {
|
|
1102
|
-
if (
|
|
1103
|
-
return { result: failure(error), files: [] };
|
|
1481
|
+
if (thrown(error, signal)) throw error;
|
|
1482
|
+
return { result: failure(error, args, hooks), files: [] };
|
|
1104
1483
|
}
|
|
1105
1484
|
},
|
|
1485
|
+
wholeReadsLeft(documentId) {
|
|
1486
|
+
// None for a document this tool set cannot read whole: no part reader, not one of its
|
|
1487
|
+
// documents, or one sent whole; none once a read of it could read no part.
|
|
1488
|
+
if (!options.generate || !allowed.has(documentId) || inline.has(documentId) || failedWholeReads.has(documentId)) return 0;
|
|
1489
|
+
return Math.max(0, maxWholeReads - (wholeReads.get(documentId) ?? 0));
|
|
1490
|
+
},
|
|
1106
1491
|
describe(name, args) {
|
|
1107
1492
|
const id = typeof args.document_id === "string" ? args.document_id : "";
|
|
1108
1493
|
const file = names.get(id) ?? "the file";
|
|
@@ -1120,9 +1505,12 @@ export function createDocumentTools(options: {
|
|
|
1120
1505
|
return `Search ${file} (${mode}) for “${sliceWhole(String(args.query ?? ""), 80)}”${where}${how}`;
|
|
1121
1506
|
}
|
|
1122
1507
|
if (name === TOOL_NAMES.read) {
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1508
|
+
// The lines as the tool reads them (`requestedLines`): an end sent as text ("250") too, and
|
|
1509
|
+
// never past the most lines one read shows. The end is shown when the call gave one, not
|
|
1510
|
+
// before the start.
|
|
1511
|
+
const [start, end] = requestedLines(args);
|
|
1512
|
+
const given = args.end_line !== undefined && args.end_line !== null && args.end_line !== "" && Number(args.end_line) >= start;
|
|
1513
|
+
return `Read ${file} lines ${start}${given ? `-${end}` : ""}`;
|
|
1126
1514
|
}
|
|
1127
1515
|
if (name === TOOL_NAMES.overview) return `Overview of ${file}`;
|
|
1128
1516
|
if (name === TOOL_NAMES.aggregate) {
|
|
@@ -1139,7 +1527,7 @@ export function createDocumentTools(options: {
|
|
|
1139
1527
|
const table = request.table !== undefined && request.table !== "" ? ` (${typeof request.table === "number" ? `table ${request.table}` : request.table})` : "";
|
|
1140
1528
|
return sliceWhole(`Aggregate ${file}${table}: ${metrics}${by}${where}`, 200);
|
|
1141
1529
|
}
|
|
1142
|
-
if (name === TOOL_NAMES.analyze) return `Read all of ${file} for “${sliceWhole(String(args.task ?? ""), 100)}
|
|
1530
|
+
if (name === TOOL_NAMES.analyze) return `Read all of ${file} for “${sliceWhole(String(args.task ?? ""), 100)}”${args.output === "items" ? ", as a list of items" : ""}`;
|
|
1143
1531
|
return name;
|
|
1144
1532
|
},
|
|
1145
1533
|
};
|