llm-large-files 0.4.1 → 0.7.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 +1400 -338
- package/README.md +217 -49
- package/dist/analyze.d.ts +5 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +96 -47
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts +117 -0
- package/dist/anthropic/adapter.d.ts.map +1 -0
- package/dist/anthropic/adapter.js +542 -0
- package/dist/anthropic/adapter.js.map +1 -0
- package/dist/anthropic/index.d.ts +3 -0
- package/dist/anthropic/index.d.ts.map +1 -0
- package/dist/anthropic/index.js +2 -0
- package/dist/anthropic/index.js.map +1 -0
- package/dist/ask.d.ts +200 -0
- package/dist/ask.d.ts.map +1 -0
- package/dist/ask.js +1402 -0
- package/dist/ask.js.map +1 -0
- package/dist/budget.d.ts +23 -0
- package/dist/budget.d.ts.map +1 -0
- package/dist/budget.js +64 -0
- package/dist/budget.js.map +1 -0
- package/dist/encoding.d.ts +17 -0
- package/dist/encoding.d.ts.map +1 -0
- package/dist/encoding.js +852 -0
- package/dist/encoding.js.map +1 -0
- package/dist/errors.d.ts +4 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +15 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +333 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +159 -0
- package/dist/events.js.map +1 -0
- package/dist/evidence.d.ts +42 -0
- package/dist/evidence.d.ts.map +1 -0
- package/dist/evidence.js +138 -0
- package/dist/evidence.js.map +1 -0
- package/dist/extract.d.ts +35 -3
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +626 -58
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +59 -0
- package/dist/gemini/adapter.d.ts.map +1 -0
- package/dist/gemini/adapter.js +226 -0
- package/dist/gemini/adapter.js.map +1 -0
- package/dist/gemini/chat.d.ts +53 -77
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +42 -300
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +16 -0
- package/dist/gemini/errors.d.ts.map +1 -0
- package/dist/gemini/errors.js +46 -0
- package/dist/gemini/errors.js.map +1 -0
- package/dist/gemini/generate.d.ts +18 -21
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +49 -92
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +6 -4
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +4 -3
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -2
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -38
- package/dist/gemini/sse.js.map +1 -1
- package/dist/http.d.ts +136 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +401 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +18 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +96 -8
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +414 -96
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +37 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +255 -61
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +278 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/model.js +222 -0
- package/dist/model.js.map +1 -0
- package/dist/node/handlers.d.ts +20 -4
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +122 -20
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/sse.d.ts +59 -0
- package/dist/node/sse.d.ts.map +1 -0
- package/dist/node/sse.js +174 -0
- package/dist/node/sse.js.map +1 -0
- package/dist/openai/adapter.d.ts +109 -0
- package/dist/openai/adapter.d.ts.map +1 -0
- package/dist/openai/adapter.js +567 -0
- package/dist/openai/adapter.js.map +1 -0
- package/dist/openai/index.d.ts +3 -0
- package/dist/openai/index.d.ts.map +1 -0
- package/dist/openai/index.js +2 -0
- package/dist/openai/index.js.map +1 -0
- package/dist/output-limit.d.ts +42 -0
- package/dist/output-limit.d.ts.map +1 -0
- package/dist/output-limit.js +121 -0
- package/dist/output-limit.js.map +1 -0
- package/dist/pause.d.ts +24 -0
- package/dist/pause.d.ts.map +1 -0
- package/dist/pause.js +38 -0
- package/dist/pause.js.map +1 -0
- package/dist/pdf-pages.d.ts +32 -2
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +275 -14
- package/dist/pdf-pages.js.map +1 -1
- package/dist/pdf-pictures.d.ts +30 -3
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +50 -8
- package/dist/pdf-pictures.js.map +1 -1
- package/dist/pdf-work.d.ts +40 -0
- package/dist/pdf-work.d.ts.map +1 -0
- package/dist/pdf-work.js +734 -0
- package/dist/pdf-work.js.map +1 -0
- package/dist/plan.d.ts +22 -4
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +61 -12
- package/dist/plan.js.map +1 -1
- package/dist/retry.d.ts +76 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +141 -0
- package/dist/retry.js.map +1 -0
- package/dist/search.d.ts +8 -2
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +60 -10
- package/dist/search.js.map +1 -1
- package/dist/sse.d.ts +36 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +153 -0
- package/dist/sse.js.map +1 -0
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +5 -2
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +6 -0
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +25 -8
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +62 -2
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +314 -14
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +72 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +341 -60
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +128 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/zip-directory.d.ts +43 -0
- package/dist/zip-directory.d.ts.map +1 -0
- package/dist/zip-directory.js +130 -0
- package/dist/zip-directory.js.map +1 -0
- package/docs/README.md +288 -0
- package/docs/api.md +58 -184
- package/docs/configuration.md +34 -490
- package/docs/getting-started.md +412 -177
- package/docs/guides/anthropic.md +590 -0
- package/docs/guides/conversations.md +629 -0
- package/docs/guides/costs-and-limits.md +726 -0
- package/docs/guides/deployment.md +654 -0
- package/docs/guides/errors-and-reliability.md +735 -0
- package/docs/guides/explorer-model.md +399 -0
- package/docs/guides/openai-compatible.md +602 -0
- package/docs/guides/own-adapter-and-loop.md +1169 -0
- package/docs/guides/pdfs.md +971 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1199 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1589 -0
- package/docs/how-it-works.md +1022 -138
- package/docs/measurements.md +881 -0
- package/docs/publishing.md +274 -46
- package/docs/reference/anthropic.md +427 -0
- package/docs/reference/ask.md +892 -0
- package/docs/reference/errors-and-retries.md +758 -0
- package/docs/reference/events.md +993 -0
- package/docs/reference/gemini.md +823 -0
- package/docs/reference/library.md +1467 -0
- package/docs/reference/node.md +528 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +883 -0
- package/docs/security.md +902 -90
- package/docs/troubleshooting.md +1390 -0
- package/package.json +22 -4
- package/src/analyze.ts +93 -42
- package/src/anthropic/adapter.ts +611 -0
- package/src/anthropic/index.ts +2 -0
- package/src/ask.ts +1560 -0
- package/src/budget.ts +71 -0
- package/src/encoding.ts +850 -0
- package/src/errors.ts +17 -0
- package/src/events.ts +442 -0
- package/src/evidence.ts +165 -0
- package/src/extract.ts +602 -62
- package/src/gemini/adapter.ts +271 -0
- package/src/gemini/chat.ts +87 -355
- package/src/gemini/errors.ts +48 -0
- package/src/gemini/generate.ts +67 -94
- package/src/gemini/index.ts +6 -4
- package/src/gemini/sse.ts +1 -34
- package/src/http.ts +434 -0
- package/src/index.ts +55 -4
- package/src/library.ts +497 -97
- package/src/map-reduce.ts +266 -59
- package/src/model.ts +433 -0
- package/src/node/handlers.ts +137 -22
- package/src/node/index.ts +2 -0
- package/src/node/sse.ts +198 -0
- package/src/openai/adapter.ts +613 -0
- package/src/openai/index.ts +2 -0
- package/src/output-limit.ts +135 -0
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +268 -15
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/plan.ts +68 -12
- package/src/retry.ts +176 -0
- package/src/search.ts +63 -10
- package/src/sse.ts +159 -0
- package/src/stores.ts +5 -2
- package/src/text-index.ts +26 -7
- package/src/text.ts +323 -13
- package/src/tools.ts +338 -62
- package/src/types.ts +129 -5
- package/src/zip-directory.ts +136 -0
package/src/tools.ts
CHANGED
|
@@ -1,21 +1,33 @@
|
|
|
1
1
|
import { safeErrorMessage } from "./errors.js";
|
|
2
|
-
import { analyzeWholeDocument } from "./map-reduce.js";
|
|
2
|
+
import { analyzeWholeDocument, NothingReadError } from "./map-reduce.js";
|
|
3
3
|
import { cutPdfPages } from "./pdf-pages.js";
|
|
4
|
-
import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS, type DocumentSource } from "./search.js";
|
|
4
|
+
import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS, type DocumentSource, type LineMatch } from "./search.js";
|
|
5
5
|
import { estimateParts, formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
|
|
6
|
-
import type {
|
|
6
|
+
import type { RetryOptions } from "./retry.js";
|
|
7
|
+
import { plural, removeInvisible, sliceWhole, wellFormedJson } from "./text.js";
|
|
8
|
+
import type { Budget, GenerateText, ProgressListener, ToolCallHooks, ToolCallLimits, ToolDeclaration, ToolOutput, ToolResult, ToolSet } from "./types.js";
|
|
7
9
|
|
|
8
10
|
const DEFAULT_READ_LINES = 200;
|
|
9
11
|
const MAX_READ_LINES = 600;
|
|
10
12
|
/** The most pages one `view_pages` call shows. A page costs a model about 530 tokens. */
|
|
11
13
|
export const MAX_VIEW_PAGES = 5;
|
|
12
14
|
/**
|
|
13
|
-
* The time the regex searches of one tool set (one question, in `
|
|
15
|
+
* The time the regex searches of one tool set (one question, in `askWithFiles`) may take together,
|
|
14
16
|
* unless `regexBudgetMs` says otherwise. An ordinary search of a 60 MB log takes about 0.15 s.
|
|
15
17
|
*/
|
|
16
18
|
export const REGEX_BUDGET_MS = 6_000;
|
|
17
19
|
/** Below this, no page fits: a cut of one page of plain text is larger. */
|
|
18
20
|
const MIN_FILE_BYTES = 1_024;
|
|
21
|
+
/** The answer of a whole-document read may be this long, when the cap on tool results is lower. */
|
|
22
|
+
const ANALYSIS_RESULT_CHARACTERS = 40_000;
|
|
23
|
+
/** A result is never cut below this, whatever room a caller names: less holds no line of a file. */
|
|
24
|
+
export const LEAST_RESULT_CHARACTERS = 600;
|
|
25
|
+
/**
|
|
26
|
+
* How many times one document is read whole by the tools of one tool set (one question, in
|
|
27
|
+
* `askWithFiles`), unless `maxWholeDocumentReads` says otherwise. One read of a large file is
|
|
28
|
+
* up to `maxMapChunks` model requests.
|
|
29
|
+
*/
|
|
30
|
+
export const MAX_WHOLE_DOCUMENT_READS = 1;
|
|
19
31
|
|
|
20
32
|
export const TOOL_NAMES = {
|
|
21
33
|
search: "search_document",
|
|
@@ -30,7 +42,7 @@ const documentId = { type: "string" as const, description: "The document_id from
|
|
|
30
42
|
const DECLARATIONS: Record<keyof typeof TOOL_NAMES, ToolDeclaration> = {
|
|
31
43
|
search: {
|
|
32
44
|
name: TOOL_NAMES.search,
|
|
33
|
-
description: "Search a large attached file. mode \"keywords\" returns the most relevant passages for a question; \"exact\"
|
|
45
|
+
description: "Search a large attached file. mode \"keywords\" returns the most relevant passages for a question; \"exact\" finds the lines that contain the text; \"regex\" finds the lines that match a JavaScript regular expression. For exact and regex, total_matching_lines counts every matching line, and the result shows the first max_results of them and the last one. Results include line numbers to read further with read_document.",
|
|
34
46
|
parameters: {
|
|
35
47
|
type: "object",
|
|
36
48
|
properties: {
|
|
@@ -64,7 +76,7 @@ const DECLARATIONS: Record<keyof typeof TOOL_NAMES, ToolDeclaration> = {
|
|
|
64
76
|
},
|
|
65
77
|
analyze: {
|
|
66
78
|
name: TOOL_NAMES.analyze,
|
|
67
|
-
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
|
|
79
|
+
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.",
|
|
68
80
|
parameters: {
|
|
69
81
|
type: "object",
|
|
70
82
|
properties: {
|
|
@@ -114,13 +126,17 @@ function pageNumber(value: unknown, name: string): number {
|
|
|
114
126
|
|
|
115
127
|
const pageRange = (from: number, to: number): string => (to > from ? `${from}-${to}` : String(from));
|
|
116
128
|
|
|
117
|
-
/**
|
|
129
|
+
/**
|
|
130
|
+
* Trims a result to the character budget by dropping trailing list entries, then cutting text. A
|
|
131
|
+
* note the result already has (a search that stopped early) is kept, before the one that says so.
|
|
132
|
+
*/
|
|
118
133
|
function fit(result: ToolResult, listKey: string | null, limit: number): ToolResult {
|
|
119
134
|
if (JSON.stringify(result).length <= limit) return result;
|
|
120
135
|
const list = listKey ? result[listKey] : undefined;
|
|
121
136
|
if (Array.isArray(list)) {
|
|
122
137
|
const kept = [...list];
|
|
123
|
-
const
|
|
138
|
+
const before = typeof result.note === "string" ? `${result.note} ` : "";
|
|
139
|
+
const note = () => `${before}Showing ${kept.length} of ${list.length} results to stay within the size limit. Narrow the query or read specific lines.`;
|
|
124
140
|
const trimmed = () => ({ ...result, [listKey!]: kept, note: note() });
|
|
125
141
|
while (kept.length > 1 && JSON.stringify(trimmed()).length > limit) kept.pop();
|
|
126
142
|
if (JSON.stringify(trimmed()).length <= limit) return trimmed();
|
|
@@ -131,22 +147,174 @@ function fit(result: ToolResult, listKey: string | null, limit: number): ToolRes
|
|
|
131
147
|
let cut: ToolResult;
|
|
132
148
|
do {
|
|
133
149
|
size = Math.floor(size * 0.85);
|
|
134
|
-
cut = { truncated: true, partial: serialized
|
|
150
|
+
cut = { truncated: true, partial: sliceWhole(serialized, size), note: "Result cut to the size limit. Ask for a smaller range." };
|
|
135
151
|
} while (JSON.stringify(cut).length > limit && size > 100);
|
|
136
152
|
return cut;
|
|
137
153
|
}
|
|
138
154
|
|
|
155
|
+
/**
|
|
156
|
+
* The result of a whole-document read within `limit` characters: its answer is cut at the end,
|
|
157
|
+
* and says so, rather than the result being cut as JSON, which loses what the other fields say.
|
|
158
|
+
*/
|
|
159
|
+
export function fitAnswer(result: ToolResult, limit: number): ToolResult {
|
|
160
|
+
if (JSON.stringify(result).length <= limit || typeof result.answer !== "string") return fit(result, null, limit);
|
|
161
|
+
const answer = result.answer;
|
|
162
|
+
const cutAt = (keep: number): ToolResult => ({
|
|
163
|
+
...result,
|
|
164
|
+
answer: `${sliceWhole(answer, keep)}…`,
|
|
165
|
+
answer_shortened: "The rest of this answer did not fit in the room left in this conversation.",
|
|
166
|
+
});
|
|
167
|
+
// The longest start of the answer that fits. Escapes (quotes, line breaks) make the JSON longer
|
|
168
|
+
// than the text by as much as the text holds of them, so it is found by halving, not worked out.
|
|
169
|
+
let low = 0;
|
|
170
|
+
let high = answer.length;
|
|
171
|
+
while (low < high) {
|
|
172
|
+
const middle = Math.ceil((low + high) / 2);
|
|
173
|
+
if (JSON.stringify(cutAt(middle)).length <= limit) low = middle;
|
|
174
|
+
else high = middle - 1;
|
|
175
|
+
}
|
|
176
|
+
return fit(cutAt(low), null, limit);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* The result of an exact or regex search that read the whole file: the first matches, then the
|
|
181
|
+
* last one of the file, and a note that says how many of how many are shown when that is not all.
|
|
182
|
+
* Without the last one, a model asked when something last happened named the last line it was
|
|
183
|
+
* shown. To fit `limit`, matches are dropped from the end of the first ones: the last one stays.
|
|
184
|
+
*/
|
|
185
|
+
function firstAndLastMatches(base: ToolResult, first: LineMatch[], last: LineMatch, total: number, limit: number): ToolResult {
|
|
186
|
+
const which = (kept: number) => (kept === 0 ? `the last (line ${last.line})` : `the first${kept > 1 ? ` ${kept}` : ""} and the last (line ${last.line})`);
|
|
187
|
+
const shown = (kept: number) => `${kept + 1} of the ${total} matching lines`;
|
|
188
|
+
const withFirst = (kept: number, cut: boolean): ToolResult => ({
|
|
189
|
+
...base,
|
|
190
|
+
...(cut
|
|
191
|
+
? { note: `Showing ${shown(kept)} to stay within the size limit: ${which(kept)}. Narrow the query or read specific lines.` }
|
|
192
|
+
// When every match is shown, there is nothing to say.
|
|
193
|
+
: kept + 1 < total ? { note: `${shown(kept)} are shown: ${which(kept)}. To see the ones in between, narrow the search.` } : {}),
|
|
194
|
+
matches: [...first.slice(0, kept), last],
|
|
195
|
+
});
|
|
196
|
+
const whole = withFirst(first.length, false);
|
|
197
|
+
if (JSON.stringify(whole).length <= limit) return whole;
|
|
198
|
+
let kept = first.length;
|
|
199
|
+
while (kept > 0 && JSON.stringify(withFirst(kept, true)).length > limit) kept--;
|
|
200
|
+
const cut = withFirst(kept, true);
|
|
201
|
+
if (JSON.stringify(cut).length <= limit) return cut;
|
|
202
|
+
// Only the last match is left, and its note is too long for the room: a shorter one. It still
|
|
203
|
+
// starts with "Showing ", so the result is taken as cut. `fit` must not put its own note in its
|
|
204
|
+
// place, which would say "1 of 1 results" and drop the line of the last match. When even this
|
|
205
|
+
// does not fit, `fit` cuts the result as text: the note, with that line, comes before the match.
|
|
206
|
+
const lastOnly = { ...base, note: `Showing 1 of the ${total} matching lines: ${which(0)}. Narrow the search.`, matches: [last] };
|
|
207
|
+
return fit(lastOnly, null, limit);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const searchMode = (mode: unknown): "keywords" | "exact" | "regex" => (mode === "exact" || mode === "regex" ? mode : "keywords");
|
|
211
|
+
|
|
212
|
+
/** The lines a `read_document` call asks for, as its handler reads them, before the end of the file is known. */
|
|
213
|
+
function requestedLines(args: Record<string, unknown>): [number, number] {
|
|
214
|
+
const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
|
|
215
|
+
return [start, integer(args.end_line, start + DEFAULT_READ_LINES - 1, start, start + MAX_READ_LINES - 1)];
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* A call's arguments as its tool reads them, with the defaults filled in: two calls with the same
|
|
220
|
+
* key get the same result from a file that has not changed. Undefined for a tool whose calls are
|
|
221
|
+
* not compared (a whole-file read has a count of its own; a look at pages returns a file).
|
|
222
|
+
*/
|
|
223
|
+
export function toolCallKey(name: string, args: Record<string, unknown>): string | undefined {
|
|
224
|
+
const id = typeof args.document_id === "string" && args.document_id ? args.document_id : undefined;
|
|
225
|
+
if (!id) return undefined;
|
|
226
|
+
if (name === TOOL_NAMES.search) {
|
|
227
|
+
if (typeof args.query !== "string" || !args.query.trim()) return undefined;
|
|
228
|
+
const mode = searchMode(args.mode);
|
|
229
|
+
return JSON.stringify(mode === "keywords"
|
|
230
|
+
? [name, id, args.query, mode, integer(args.max_results, 5, 1, 10)]
|
|
231
|
+
: [name, id, args.query, mode, integer(args.max_results, 20, 1, 50), integer(args.context_lines, 0, 0, 5), args.case_sensitive === true]);
|
|
232
|
+
}
|
|
233
|
+
if (name === TOOL_NAMES.read) return JSON.stringify([name, id, ...requestedLines(args)]);
|
|
234
|
+
if (name === TOOL_NAMES.overview) return JSON.stringify([name, id]);
|
|
235
|
+
return undefined;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* When an earlier call's result already holds all that `call` would return, and is still in the
|
|
240
|
+
* conversation in full: a short result that says so, in place of running the call again. A result
|
|
241
|
+
* that was cut to the room it had, or replaced by a stand-in, or failed, is not pointed to: the call
|
|
242
|
+
* is run, and may get more. A read of lines inside a read that is shown in full is pointed to.
|
|
243
|
+
* `stored` is true for a result in the tool rounds of an earlier question, which an older version
|
|
244
|
+
* may have written: 0.5.0 cut the text of a read of one long line without saying so (no
|
|
245
|
+
* `text_cut`), so a read of one line from there is not taken as shown in full.
|
|
246
|
+
*/
|
|
247
|
+
export function alreadyShown(call: { name: string; args: Record<string, unknown> }, earlier: { call: { name: string; args: Record<string, unknown> }; result: ToolResult }, stored = false): ToolResult | undefined {
|
|
248
|
+
const { result } = earlier;
|
|
249
|
+
if (earlier.call.name !== call.name || earlier.call.args.document_id !== call.args.document_id) return undefined;
|
|
250
|
+
if (result.dropped === true || result.already_shown === true || typeof result.error === "string" || result.truncated === true) return undefined;
|
|
251
|
+
// A list that `fit` cut to the room it had, a read whose text was cut, or a search that ran out of
|
|
252
|
+
// time ("the total is a lower bound"; a later question has time of its own): a call made now may get more.
|
|
253
|
+
if (typeof result.note === "string" && (result.note.startsWith("Showing ") || result.note.startsWith("The scan stopped early"))) return undefined;
|
|
254
|
+
if (result.text_cut === true) return undefined;
|
|
255
|
+
// An exact or regex search that an earlier version stored: the first matches, without the last one
|
|
256
|
+
// and without a note. Run now, the call returns more (the last match), not the same.
|
|
257
|
+
if (call.name === TOOL_NAMES.search && typeof result.total_matching_lines === "number" && Array.isArray(result.matches)
|
|
258
|
+
&& result.matches.length < result.total_matching_lines && typeof result.note !== "string") return undefined;
|
|
259
|
+
const document = typeof result.document === "string" ? { document: result.document } : {};
|
|
260
|
+
if (call.name === TOOL_NAMES.read) {
|
|
261
|
+
const shown = typeof result.lines === "string" ? /^(\d+)-(\d+)$/.exec(result.lines) : null;
|
|
262
|
+
const total = result.total_lines;
|
|
263
|
+
if (!shown || typeof total !== "number") return undefined;
|
|
264
|
+
const [first, last] = [Number(shown[1]), Number(shown[2])];
|
|
265
|
+
if (stored && first === last) return undefined;
|
|
266
|
+
const [start, end] = requestedLines(call.args);
|
|
267
|
+
const from = Math.min(start, total);
|
|
268
|
+
const to = Math.min(end, total);
|
|
269
|
+
if (from < first || to > last) return undefined;
|
|
270
|
+
return {
|
|
271
|
+
...document,
|
|
272
|
+
lines: `${from}-${to}`,
|
|
273
|
+
already_shown: true,
|
|
274
|
+
note: `Not run: lines ${from}-${to} are already shown above in full, in the result that has lines ${first}-${last} of this file, and the file has not changed. Use them. To see more, read other lines.`,
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
const key = toolCallKey(call.name, call.args);
|
|
278
|
+
if (key === undefined || key !== toolCallKey(earlier.call.name, earlier.call.args)) return undefined;
|
|
279
|
+
return {
|
|
280
|
+
...document,
|
|
281
|
+
already_shown: true,
|
|
282
|
+
note: "Not run: this exact call was answered earlier in this conversation, and its result is still shown above in full. The file has not changed, so it would return the same. Use that result. For more, read other lines, or search with other words or another mode.",
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* A hint added to the error of a search that failed twice in a row in the same mode, so that the
|
|
288
|
+
* model tries another way instead of sending the same kind of call a third time.
|
|
289
|
+
*/
|
|
290
|
+
export function repeatedFailureHint(call: { name: string; args: Record<string, unknown> }): string {
|
|
291
|
+
return searchMode(call.args.mode) === "regex"
|
|
292
|
+
? "Two regex searches in a row failed. Try mode \"exact\" with a plain word or ID from the file, or mode \"keywords\"."
|
|
293
|
+
: "This search failed twice in a row. Check the arguments against the tool's description, or answer from what you have.";
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* The tool and mode of a search, to tell whether two failures in a row were of the same kind.
|
|
298
|
+
* Undefined for the other tools: their errors say what to do (a whole-file read that is not made
|
|
299
|
+
* again, a page that does not exist), and a hint would only blur that.
|
|
300
|
+
*/
|
|
301
|
+
export function failureKind(call: { name: string; args: Record<string, unknown> }): string | undefined {
|
|
302
|
+
return call.name === TOOL_NAMES.search ? `${call.name}|${searchMode(call.args.mode)}` : undefined;
|
|
303
|
+
}
|
|
304
|
+
|
|
139
305
|
/**
|
|
140
306
|
* What a finished tool call found, as a suffix for its `describe()` label, for a steps list:
|
|
141
307
|
* "Search app.log (exact) for “timeout”" + " — 12 matching lines".
|
|
142
308
|
*/
|
|
143
309
|
export function toolResultSummary(label: string, result: ToolResult): string {
|
|
144
310
|
if (typeof result.error === "string") return ` — failed: ${result.error}`;
|
|
145
|
-
if (typeof result.total_matching_lines === "number")
|
|
146
|
-
|
|
311
|
+
if (typeof result.total_matching_lines === "number") {
|
|
312
|
+
return ` — ${result.total_matching_lines.toLocaleString("en-US")} ${plural(result.total_matching_lines, "matching line")}`;
|
|
313
|
+
}
|
|
314
|
+
if (Array.isArray(result.passages)) return ` — ${result.passages.length} ${plural(result.passages.length, "passage")}`;
|
|
147
315
|
if (typeof result.parts_read === "number") {
|
|
148
|
-
const incomplete = result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
|
|
149
|
-
return ` — ${result.parts_read}
|
|
316
|
+
const incomplete = result.notes_only ? ", notes only" : result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
|
|
317
|
+
return ` — ${result.parts_read} ${plural(result.parts_read, "part")}, ${String(result.parts_with_relevant_content ?? 0)} relevant${incomplete}`;
|
|
150
318
|
}
|
|
151
319
|
// A read reports its range only when it was cut short of what was asked.
|
|
152
320
|
if (typeof result.lines === "string" && typeof result.total_lines === "number") return label.endsWith(result.lines) ? "" : ` — got ${result.lines}`;
|
|
@@ -157,6 +325,31 @@ export function toolResultSummary(label: string, result: ToolResult): string {
|
|
|
157
325
|
return "";
|
|
158
326
|
}
|
|
159
327
|
|
|
328
|
+
/**
|
|
329
|
+
* A step, or a label of one, as one line of plain text. Steps quote what the model sent (a query, a
|
|
330
|
+
* task, the name of a tool, arguments that were not JSON), and they reach users' screens: the
|
|
331
|
+
* invisible characters that file text and names lose are dropped (`removeInvisible`: text-direction
|
|
332
|
+
* overrides and isolates, zero-width spaces, tag characters), a line break, a tab or another control
|
|
333
|
+
* character becomes one space with the blanks around it, and "](" gets a space, so that a markdown
|
|
334
|
+
* link or picture in a query stays text. A line without them is unchanged.
|
|
335
|
+
*/
|
|
336
|
+
export function stepLine(text: string): string {
|
|
337
|
+
// Each control character, tab and line break is a "\n" first, which `removeInvisible` keeps (it
|
|
338
|
+
// would drop the others): an invisible character between two of them then leaves one space, not
|
|
339
|
+
// two. A soft hyphen it keeps before one goes too. Then a run of blanks with a "\n" in it is one space.
|
|
340
|
+
const marked = removeInvisible(text.replace(/[\p{Cc}\p{Zl}\p{Zp}]/gu, "\n")).replace(/\xAD+(?=\n)/g, "");
|
|
341
|
+
return marked.replace(/\s+/g, (blank) => (blank.includes("\n") ? " " : blank)).replaceAll("](", "] (");
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** An unknown tool's name as a step or an error quotes it: the model chose it, at any length. */
|
|
345
|
+
export const unknownToolName = (name: string): string => `“${sliceWhole(name, 64)}”`;
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* A document_id the model sent, as an error quotes it: whole when it is as long as a real one can
|
|
349
|
+
* be, cut otherwise. The model chose it, at any length, and the error goes into steps too.
|
|
350
|
+
*/
|
|
351
|
+
const shownId = (id: string): string => (id.length > 64 ? `${sliceWhole(id, 64)}…` : id);
|
|
352
|
+
|
|
160
353
|
export function createDocumentTools(options: {
|
|
161
354
|
/** Loads a document the tools may access. Return undefined for anything out of scope. */
|
|
162
355
|
load(documentId: string): Promise<DocumentSource | undefined>;
|
|
@@ -169,6 +362,10 @@ export function createDocumentTools(options: {
|
|
|
169
362
|
signal?: AbortSignal;
|
|
170
363
|
/** The most time, in milliseconds, that the regex searches of this tool set may take together. Defaults to `REGEX_BUDGET_MS`. */
|
|
171
364
|
regexBudgetMs?: number;
|
|
365
|
+
/** How many times each document may be read whole by this tool set. Defaults to `MAX_WHOLE_DOCUMENT_READS`. */
|
|
366
|
+
maxWholeDocumentReads?: number;
|
|
367
|
+
/** How a model request of a whole-document read that failed is sent again. */
|
|
368
|
+
retry?: RetryOptions;
|
|
172
369
|
/**
|
|
173
370
|
* False when every document is too large for a whole-document read: `analyze_whole_document` is
|
|
174
371
|
* then not declared. A call of it still answers with the reason. Defaults to true.
|
|
@@ -195,26 +392,51 @@ export function createDocumentTools(options: {
|
|
|
195
392
|
const known = new Set(declarations.map((declaration) => declaration.name));
|
|
196
393
|
// Not declared for files that are all too large for it, but still answered: with the reason, not "unknown tool".
|
|
197
394
|
if (textTools && options.generate) known.add(TOOL_NAMES.analyze);
|
|
198
|
-
const
|
|
395
|
+
const cap = options.budget.toolResultCharacters;
|
|
396
|
+
/** The cap on the result of one call: the tool set's own, or the room its caller has left when that is less. */
|
|
397
|
+
const limitOf = (limits: ToolCallLimits, own = cap): number => {
|
|
398
|
+
const room = limits.maxResultCharacters;
|
|
399
|
+
return typeof room === "number" && Number.isFinite(room) ? Math.max(LEAST_RESULT_CHARACTERS, Math.min(own, Math.trunc(room))) : own;
|
|
400
|
+
};
|
|
199
401
|
// The model writes the regex, and a file it reads can ask for a slow one: the time is counted
|
|
200
402
|
// over every search of this tool set, not only within one.
|
|
201
403
|
const regexBudget = Math.max(0, options.regexBudgetMs ?? REGEX_BUDGET_MS);
|
|
202
404
|
const regexClock = { usedMs: 0 };
|
|
405
|
+
// Calls of one turn may run together. Regex searches still take their turns, one after another:
|
|
406
|
+
// each must know how much of the time the ones before it used.
|
|
407
|
+
let regexQueue: Promise<unknown> = Promise.resolve();
|
|
408
|
+
const inRegexTurn = <T>(run: () => Promise<T>): Promise<T> => {
|
|
409
|
+
const next = regexQueue.then(run, run);
|
|
410
|
+
regexQueue = next.catch(() => undefined);
|
|
411
|
+
return next;
|
|
412
|
+
};
|
|
413
|
+
const maxWholeReads = Math.max(0, Math.trunc(options.maxWholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS));
|
|
414
|
+
/** Whole-document reads started, by document. */
|
|
415
|
+
const wholeReads = new Map<string, number>();
|
|
416
|
+
/** Why the last whole-document read of a document failed, when no part of it could be read. */
|
|
417
|
+
const failedWholeReads = new Map<string, string>();
|
|
203
418
|
// When no limit is given with a call: three eighths of a request, so that two looks still fit.
|
|
204
419
|
const defaultFileBytes = Math.floor((options.budget.maxRequestBytes - REQUEST_BYTES_MARGIN) * 3 / 8);
|
|
205
420
|
|
|
206
421
|
async function documentFor(args: Record<string, unknown>): Promise<DocumentSource> {
|
|
207
422
|
const id = text(args.document_id, "document_id");
|
|
208
423
|
// Scope check: a model can only reach files attached to this conversation.
|
|
209
|
-
if (!allowed.has(id))
|
|
424
|
+
if (!allowed.has(id)) {
|
|
425
|
+
// The IDs it may use, with their file names, so that the next call is right.
|
|
426
|
+
const usable = [...allowed].slice(0, 20).map((known) => `${known}${names.has(known) ? ` (${JSON.stringify(names.get(known))})` : ""}`);
|
|
427
|
+
throw new Error(usable.length === 0
|
|
428
|
+
? `Unknown document_id ${shownId(id)}. No attached file is read with this tool in this conversation.`
|
|
429
|
+
: `Unknown document_id ${shownId(id)}. Use one of: ${usable.join(", ")}${allowed.size > 20 ? ", …" : ""}.`);
|
|
430
|
+
}
|
|
210
431
|
const document = await options.load(id);
|
|
211
432
|
if (!document) throw new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
|
|
212
433
|
names.set(id, document.meta.name);
|
|
213
434
|
return document;
|
|
214
435
|
}
|
|
215
436
|
|
|
216
|
-
const handlers: Record<string, (args: Record<string, unknown
|
|
217
|
-
async [TOOL_NAMES.search](args) {
|
|
437
|
+
const handlers: Record<string, (args: Record<string, unknown>, limits: ToolCallLimits, hooks: ToolCallHooks) => Promise<ToolResult>> = {
|
|
438
|
+
async [TOOL_NAMES.search](args, limits) {
|
|
439
|
+
const limit = limitOf(limits);
|
|
218
440
|
const document = await documentFor(args);
|
|
219
441
|
const query = text(args.query, "query");
|
|
220
442
|
const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
|
|
@@ -241,31 +463,45 @@ export function createDocumentTools(options: {
|
|
|
241
463
|
}, "passages", limit);
|
|
242
464
|
}
|
|
243
465
|
const regex = mode === "regex";
|
|
244
|
-
const
|
|
245
|
-
|
|
246
|
-
|
|
466
|
+
const grep = async () => {
|
|
467
|
+
const regexLeft = regexBudget - regexClock.usedMs;
|
|
468
|
+
if (regex && regexLeft <= 0) {
|
|
469
|
+
throw new Error("The time for regex searches is used up for this answer. Search with mode \"exact\" or \"keywords\" instead.");
|
|
470
|
+
}
|
|
471
|
+
return grepSource(document, query, {
|
|
472
|
+
regex,
|
|
473
|
+
caseSensitive: args.case_sensitive === true,
|
|
474
|
+
maxResults: integer(args.max_results, 20, 1, 50),
|
|
475
|
+
contextLines: integer(args.context_lines, 0, 0, 5),
|
|
476
|
+
...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
|
|
477
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
478
|
+
});
|
|
479
|
+
};
|
|
480
|
+
const result = await (regex ? inRegexTurn(grep) : grep());
|
|
481
|
+
const placed = (match: LineMatch): LineMatch => {
|
|
482
|
+
if (!paged) return match;
|
|
483
|
+
const { line, ...rest } = match;
|
|
484
|
+
const page = document.pageOfLine(line);
|
|
485
|
+
return { line, ...(page ? { page } : {}), ...rest };
|
|
486
|
+
};
|
|
487
|
+
const base = { document: document.meta.name, mode, total_matching_lines: result.totalMatchingLines };
|
|
488
|
+
const matches = result.matches.map(placed);
|
|
489
|
+
if (!result.stoppedEarly && result.totalMatchingLines >= 2) {
|
|
490
|
+
// The last match is `last`, or, when every match is among the first ones, the last of them.
|
|
491
|
+
return result.last
|
|
492
|
+
? firstAndLastMatches(base, matches, placed(result.last), result.totalMatchingLines, limit)
|
|
493
|
+
: firstAndLastMatches(base, matches.slice(0, -1), matches.at(-1)!, result.totalMatchingLines, limit);
|
|
247
494
|
}
|
|
248
|
-
const result = await grepSource(document, query, {
|
|
249
|
-
regex,
|
|
250
|
-
caseSensitive: args.case_sensitive === true,
|
|
251
|
-
maxResults: integer(args.max_results, 20, 1, 50),
|
|
252
|
-
contextLines: integer(args.context_lines, 0, 0, 5),
|
|
253
|
-
...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
|
|
254
|
-
...(options.signal ? { signal: options.signal } : {}),
|
|
255
|
-
});
|
|
256
495
|
return fit({
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
matches: paged ? result.matches.map(({ line, ...rest }) => {
|
|
262
|
-
const page = document.pageOfLine(line);
|
|
263
|
-
return { line, ...(page ? { page } : {}), ...rest };
|
|
264
|
-
}) : result.matches,
|
|
496
|
+
...base,
|
|
497
|
+
// The description says the last match is shown: here it is not known.
|
|
498
|
+
...(result.stoppedEarly ? { note: "The scan stopped early; the total is a lower bound, and the last match in the file is not known." } : {}),
|
|
499
|
+
matches,
|
|
265
500
|
}, "matches", limit);
|
|
266
501
|
},
|
|
267
502
|
|
|
268
|
-
async [TOOL_NAMES.read](args) {
|
|
503
|
+
async [TOOL_NAMES.read](args, limits) {
|
|
504
|
+
const limit = limitOf(limits);
|
|
269
505
|
const document = await documentFor(args);
|
|
270
506
|
const total = document.lineCount;
|
|
271
507
|
const start = integer(args.start_line, 1, 1, total);
|
|
@@ -286,12 +522,15 @@ export function createDocumentTools(options: {
|
|
|
286
522
|
lines: `${start}-${to}`,
|
|
287
523
|
...(pages ? { pages } : {}),
|
|
288
524
|
total_lines: total,
|
|
289
|
-
text: fits(body) ? body : body
|
|
525
|
+
text: fits(body) ? body : sliceWhole(body, Math.floor((limit - 500) / 2)),
|
|
526
|
+
// One line longer than the room: its text was cut, so the lines are not all shown.
|
|
527
|
+
...(fits(body) ? {} : { text_cut: true }),
|
|
290
528
|
...(to < total ? { next_start_line: to + 1 } : { note: "End of file." }),
|
|
291
529
|
};
|
|
292
530
|
},
|
|
293
531
|
|
|
294
|
-
async [TOOL_NAMES.overview](args) {
|
|
532
|
+
async [TOOL_NAMES.overview](args, limits) {
|
|
533
|
+
const limit = limitOf(limits);
|
|
295
534
|
const document = await documentFor(args);
|
|
296
535
|
const { meta, lineCount } = document;
|
|
297
536
|
const tail = Math.max(1, lineCount - 19);
|
|
@@ -309,48 +548,84 @@ export function createDocumentTools(options: {
|
|
|
309
548
|
...(meta.pages ? { pages: meta.pages } : {}),
|
|
310
549
|
parts_for_whole_document_analysis: parts,
|
|
311
550
|
...(parts > options.budget.maxMapChunks ? { whole_document_analysis: `Not available for this file: it would take about ${parts} parts, and the limit is ${options.budget.maxMapChunks}. Use search_document and read_document.` } : {}),
|
|
312
|
-
|
|
551
|
+
// 0.5.0 stored some log templates cut inside an emoji: half of a character is not sent.
|
|
552
|
+
...(meta.logProfile ? { log_profile: wellFormedJson(meta.logProfile) } : {}),
|
|
313
553
|
first_lines: numberLines(await document.readLines(1, first), 1),
|
|
314
554
|
last_lines: lineCount > 30 ? numberLines(await document.readLines(tail, lineCount), tail) : "",
|
|
315
555
|
outline: meta.outline.length ? outlineLines(meta.outline) : [],
|
|
316
556
|
}, "outline", limit);
|
|
317
557
|
},
|
|
318
558
|
|
|
319
|
-
async [TOOL_NAMES.analyze](args) {
|
|
559
|
+
async [TOOL_NAMES.analyze](args, limits, hooks) {
|
|
320
560
|
if (!options.generate) throw new Error("Whole-document analysis is not enabled.");
|
|
321
561
|
const document = await documentFor(args);
|
|
322
562
|
const task = text(args.task, "task");
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
563
|
+
// A read of the whole file is many model requests. A model that asks for it again, with the
|
|
564
|
+
// task put another way, is told to use what it has. The count is taken before the read
|
|
565
|
+
// starts, so that two calls in one turn do not both pass.
|
|
566
|
+
const id = document.meta.id;
|
|
567
|
+
const reads = wholeReads.get(id) ?? 0;
|
|
568
|
+
if (reads >= maxWholeReads) {
|
|
569
|
+
const failure = failedWholeReads.get(id);
|
|
570
|
+
throw new Error(maxWholeReads === 0
|
|
571
|
+
? `Whole-file reads are turned off for this question. Use search_document and read_document on ${document.meta.name}.`
|
|
572
|
+
: failure !== undefined
|
|
573
|
+
// There is no answer to use: saying "use the answer of that read" would invite one made up.
|
|
574
|
+
? `The whole-file read of ${document.meta.name} failed earlier in this question (${failure}), and is not tried again. Use search_document and read_document.`
|
|
575
|
+
: `${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.`);
|
|
576
|
+
}
|
|
577
|
+
wholeReads.set(id, reads + 1);
|
|
578
|
+
let result;
|
|
579
|
+
try {
|
|
580
|
+
result = await analyzeWholeDocument({
|
|
581
|
+
document,
|
|
582
|
+
task,
|
|
583
|
+
generate: options.generate,
|
|
584
|
+
budget: options.budget,
|
|
585
|
+
// The call's own listener, when it has one, in place of the tool set's.
|
|
586
|
+
onProgress: hooks.onProgress ?? options.onProgress,
|
|
587
|
+
...(hooks.onRequest ? { onRequest: hooks.onRequest } : {}),
|
|
588
|
+
signal: options.signal,
|
|
589
|
+
...(options.retry ? { retry: options.retry } : {}),
|
|
590
|
+
...(typeof limits.maxRequests === "number" && Number.isFinite(limits.maxRequests) ? { maxRequests: limits.maxRequests } : {}),
|
|
591
|
+
});
|
|
592
|
+
} catch (error) {
|
|
593
|
+
// Parts were sent and none could be read: that read is counted, since another would most
|
|
594
|
+
// likely fail the same way. Anything else (too many parts, a store that could not be read)
|
|
595
|
+
// failed before any model request: that was no read. Its count is given back, not set to
|
|
596
|
+
// what it was when the read started, which would take back the count of another read of
|
|
597
|
+
// the same document running in this turn.
|
|
598
|
+
if (error instanceof NothingReadError) failedWholeReads.set(id, error.reason);
|
|
599
|
+
else wholeReads.set(id, Math.max(0, (wholeReads.get(id) ?? 1) - 1));
|
|
600
|
+
throw error;
|
|
601
|
+
}
|
|
602
|
+
failedWholeReads.delete(id);
|
|
331
603
|
const notesCutShort = result.truncatedParts + result.truncatedMerges;
|
|
332
|
-
return
|
|
604
|
+
return fitAnswer({
|
|
333
605
|
document: document.meta.name,
|
|
334
606
|
parts_read: result.parts,
|
|
335
607
|
parts_with_relevant_content: result.relevantParts,
|
|
336
608
|
...(result.failedParts ? { parts_that_failed: result.failedParts } : {}),
|
|
337
609
|
...(notesCutShort ? { notes_cut_short: notesCutShort } : {}),
|
|
338
610
|
...(result.answerTruncated ? { answer_cut_short: true } : {}),
|
|
339
|
-
...(
|
|
611
|
+
...(result.answerFailed !== undefined ? { notes_only: true } : {}),
|
|
612
|
+
...(result.answerFailed !== undefined
|
|
613
|
+
? { 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.${notesCutShort ? " Some of them were cut off at the output limit, so they are incomplete: tell the user." : ""}` }
|
|
614
|
+
: notesCutShort || result.answerTruncated ? { note: INCOMPLETE_ANALYSIS } : {}),
|
|
340
615
|
answer: result.answer,
|
|
341
|
-
},
|
|
616
|
+
}, limitOf(limits, Math.max(cap, ANALYSIS_RESULT_CHARACTERS)));
|
|
342
617
|
},
|
|
343
618
|
};
|
|
344
619
|
|
|
345
620
|
/** `view_pages`: the pages as one small PDF, next to a short JSON result. */
|
|
346
|
-
async function viewPages(args: Record<string, unknown>, limits:
|
|
621
|
+
async function viewPages(args: Record<string, unknown>, limits: ToolCallLimits): Promise<ToolOutput> {
|
|
347
622
|
const id = text(args.document_id, "document_id");
|
|
348
623
|
// The same scope check as the text tools, on its own list: a PDF can be looked at without
|
|
349
624
|
// being searchable, and the other way round.
|
|
350
625
|
if (!viewable.has(id)) {
|
|
351
626
|
throw new Error(allowed.has(id)
|
|
352
627
|
? `The pages of ${names.get(id) ?? id} cannot be shown: only its text was kept. Answer from the text.`
|
|
353
|
-
: `Unknown document_id ${id}. Use the document_id of an attached PDF.`);
|
|
628
|
+
: `Unknown document_id ${shownId(id)}. Use the document_id of an attached PDF.`);
|
|
354
629
|
}
|
|
355
630
|
const document = await options.load(id);
|
|
356
631
|
if (!document) throw new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
|
|
@@ -394,13 +669,13 @@ export function createDocumentTools(options: {
|
|
|
394
669
|
// What a tool could not do goes to the model, and from there to a user's screen: never a server path.
|
|
395
670
|
const failure = (error: unknown): ToolResult => ({ error: safeErrorMessage(error) });
|
|
396
671
|
|
|
397
|
-
async function execute(name: string, args: Record<string, unknown
|
|
398
|
-
if (!known.has(name)) return { error: `Unknown tool ${name}.` };
|
|
672
|
+
async function execute(name: string, args: Record<string, unknown>, limits: ToolCallLimits = {}, hooks: ToolCallHooks = {}): Promise<ToolResult> {
|
|
673
|
+
if (!known.has(name)) return { error: `Unknown tool ${unknownToolName(name)}.` };
|
|
399
674
|
// The pages are a file, and this method returns only JSON. Saying that pages are attached
|
|
400
675
|
// with nothing attached would be worse than saying that they could not be shown.
|
|
401
676
|
if (name === TOOL_NAMES.view) return { error: FILES_NOT_DELIVERED };
|
|
402
677
|
try {
|
|
403
|
-
return await handlers[name]!(args);
|
|
678
|
+
return await handlers[name]!(args, limits, hooks);
|
|
404
679
|
} catch (error) {
|
|
405
680
|
if (options.signal?.aborted) throw error;
|
|
406
681
|
return failure(error);
|
|
@@ -410,9 +685,10 @@ export function createDocumentTools(options: {
|
|
|
410
685
|
return {
|
|
411
686
|
declarations,
|
|
412
687
|
has: (name) => known.has(name),
|
|
413
|
-
execute,
|
|
414
|
-
|
|
415
|
-
|
|
688
|
+
execute: (name, args) => execute(name, args),
|
|
689
|
+
resultCharacters: (name) => (name === TOOL_NAMES.analyze ? Math.max(cap, ANALYSIS_RESULT_CHARACTERS) : name === TOOL_NAMES.view ? LEAST_RESULT_CHARACTERS : cap),
|
|
690
|
+
async executeWithFiles(name, args, limits = {}, hooks = {}) {
|
|
691
|
+
if (name !== TOOL_NAMES.view || !known.has(name)) return { result: await execute(name, args, limits, hooks), files: [] };
|
|
416
692
|
try {
|
|
417
693
|
return await viewPages(args, limits);
|
|
418
694
|
} catch (error) {
|
|
@@ -431,7 +707,7 @@ export function createDocumentTools(options: {
|
|
|
431
707
|
}
|
|
432
708
|
if (name === TOOL_NAMES.search) {
|
|
433
709
|
const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
|
|
434
|
-
return `Search ${file} (${mode}) for “${String(args.query ?? "")
|
|
710
|
+
return `Search ${file} (${mode}) for “${sliceWhole(String(args.query ?? ""), 80)}”`;
|
|
435
711
|
}
|
|
436
712
|
if (name === TOOL_NAMES.read) {
|
|
437
713
|
const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
|
|
@@ -439,7 +715,7 @@ export function createDocumentTools(options: {
|
|
|
439
715
|
return `Read ${file} lines ${start}${end}`;
|
|
440
716
|
}
|
|
441
717
|
if (name === TOOL_NAMES.overview) return `Overview of ${file}`;
|
|
442
|
-
if (name === TOOL_NAMES.analyze) return `Read all of ${file} for “${String(args.task ?? "")
|
|
718
|
+
if (name === TOOL_NAMES.analyze) return `Read all of ${file} for “${sliceWhole(String(args.task ?? ""), 100)}”`;
|
|
443
719
|
return name;
|
|
444
720
|
},
|
|
445
721
|
};
|