llm-large-files 0.5.0 → 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 +1402 -467
- package/README.md +188 -60
- 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 +14 -3
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +190 -39
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +60 -4
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +1068 -206
- package/dist/ask.js.map +1 -1
- 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 +2 -0
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +3 -2
- package/dist/evidence.js.map +1 -1
- 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 +17 -8
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +108 -61
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +23 -3
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +6 -2
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +9 -4
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +32 -0
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +10 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +13 -7
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -2
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -1
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -1
- package/dist/gemini/sse.js.map +1 -1
- package/dist/http.d.ts +116 -0
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +347 -1
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +11 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +67 -5
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +405 -85
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +28 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +240 -52
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +84 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +182 -1
- package/dist/model.js.map +1 -1
- 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 +29 -5
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +311 -37
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +14 -2
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +39 -10
- package/dist/output-limit.js.map +1 -1
- 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 +23 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +33 -3
- package/dist/retry.js.map +1 -1
- 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 +35 -2
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +145 -31
- package/dist/sse.js.map +1 -1
- 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 +61 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +269 -42
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +102 -3
- 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 +37 -381
- package/docs/configuration.md +28 -558
- package/docs/getting-started.md +407 -223
- 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 +1012 -164
- 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 +897 -103
- package/docs/troubleshooting.md +1390 -0
- package/package.json +2 -2
- package/src/analyze.ts +93 -42
- package/src/anthropic/adapter.ts +196 -39
- package/src/ask.ts +1087 -202
- package/src/encoding.ts +850 -0
- package/src/errors.ts +17 -0
- package/src/events.ts +442 -0
- package/src/evidence.ts +5 -2
- package/src/extract.ts +602 -62
- package/src/gemini/adapter.ts +118 -65
- package/src/gemini/chat.ts +28 -4
- package/src/gemini/errors.ts +34 -1
- package/src/gemini/generate.ts +23 -10
- package/src/gemini/index.ts +3 -3
- package/src/gemini/sse.ts +1 -1
- package/src/http.ts +376 -1
- package/src/index.ts +27 -5
- package/src/library.ts +459 -85
- package/src/map-reduce.ts +252 -51
- package/src/model.ts +236 -3
- 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 +306 -38
- package/src/output-limit.ts +44 -8
- 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 +49 -5
- package/src/search.ts +63 -10
- package/src/sse.ts +153 -28
- package/src/stores.ts +5 -2
- package/src/text-index.ts +26 -7
- package/src/text.ts +323 -13
- package/src/tools.ts +261 -42
- package/src/types.ts +107 -4
- package/src/zip-directory.ts +136 -0
package/src/tools.ts
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
import { safeErrorMessage } from "./errors.js";
|
|
2
|
-
import { analyzeWholeDocument,
|
|
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
6
|
import type { RetryOptions } from "./retry.js";
|
|
7
|
-
import
|
|
7
|
+
import { plural, removeInvisible, sliceWhole, wellFormedJson } from "./text.js";
|
|
8
|
+
import type { Budget, GenerateText, ProgressListener, ToolCallHooks, ToolCallLimits, ToolDeclaration, ToolOutput, ToolResult, ToolSet } from "./types.js";
|
|
8
9
|
|
|
9
10
|
const DEFAULT_READ_LINES = 200;
|
|
10
11
|
const MAX_READ_LINES = 600;
|
|
11
12
|
/** The most pages one `view_pages` call shows. A page costs a model about 530 tokens. */
|
|
12
13
|
export const MAX_VIEW_PAGES = 5;
|
|
13
14
|
/**
|
|
14
|
-
* 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,
|
|
15
16
|
* unless `regexBudgetMs` says otherwise. An ordinary search of a 60 MB log takes about 0.15 s.
|
|
16
17
|
*/
|
|
17
18
|
export const REGEX_BUDGET_MS = 6_000;
|
|
@@ -20,7 +21,7 @@ const MIN_FILE_BYTES = 1_024;
|
|
|
20
21
|
/** The answer of a whole-document read may be this long, when the cap on tool results is lower. */
|
|
21
22
|
const ANALYSIS_RESULT_CHARACTERS = 40_000;
|
|
22
23
|
/** A result is never cut below this, whatever room a caller names: less holds no line of a file. */
|
|
23
|
-
const LEAST_RESULT_CHARACTERS = 600;
|
|
24
|
+
export const LEAST_RESULT_CHARACTERS = 600;
|
|
24
25
|
/**
|
|
25
26
|
* How many times one document is read whole by the tools of one tool set (one question, in
|
|
26
27
|
* `askWithFiles`), unless `maxWholeDocumentReads` says otherwise. One read of a large file is
|
|
@@ -41,7 +42,7 @@ const documentId = { type: "string" as const, description: "The document_id from
|
|
|
41
42
|
const DECLARATIONS: Record<keyof typeof TOOL_NAMES, ToolDeclaration> = {
|
|
42
43
|
search: {
|
|
43
44
|
name: TOOL_NAMES.search,
|
|
44
|
-
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.",
|
|
45
46
|
parameters: {
|
|
46
47
|
type: "object",
|
|
47
48
|
properties: {
|
|
@@ -75,7 +76,7 @@ const DECLARATIONS: Record<keyof typeof TOOL_NAMES, ToolDeclaration> = {
|
|
|
75
76
|
},
|
|
76
77
|
analyze: {
|
|
77
78
|
name: TOOL_NAMES.analyze,
|
|
78
|
-
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.",
|
|
79
80
|
parameters: {
|
|
80
81
|
type: "object",
|
|
81
82
|
properties: {
|
|
@@ -125,13 +126,17 @@ function pageNumber(value: unknown, name: string): number {
|
|
|
125
126
|
|
|
126
127
|
const pageRange = (from: number, to: number): string => (to > from ? `${from}-${to}` : String(from));
|
|
127
128
|
|
|
128
|
-
/**
|
|
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
|
+
*/
|
|
129
133
|
function fit(result: ToolResult, listKey: string | null, limit: number): ToolResult {
|
|
130
134
|
if (JSON.stringify(result).length <= limit) return result;
|
|
131
135
|
const list = listKey ? result[listKey] : undefined;
|
|
132
136
|
if (Array.isArray(list)) {
|
|
133
137
|
const kept = [...list];
|
|
134
|
-
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.`;
|
|
135
140
|
const trimmed = () => ({ ...result, [listKey!]: kept, note: note() });
|
|
136
141
|
while (kept.length > 1 && JSON.stringify(trimmed()).length > limit) kept.pop();
|
|
137
142
|
if (JSON.stringify(trimmed()).length <= limit) return trimmed();
|
|
@@ -142,22 +147,174 @@ function fit(result: ToolResult, listKey: string | null, limit: number): ToolRes
|
|
|
142
147
|
let cut: ToolResult;
|
|
143
148
|
do {
|
|
144
149
|
size = Math.floor(size * 0.85);
|
|
145
|
-
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." };
|
|
146
151
|
} while (JSON.stringify(cut).length > limit && size > 100);
|
|
147
152
|
return cut;
|
|
148
153
|
}
|
|
149
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
|
+
|
|
150
305
|
/**
|
|
151
306
|
* What a finished tool call found, as a suffix for its `describe()` label, for a steps list:
|
|
152
307
|
* "Search app.log (exact) for “timeout”" + " — 12 matching lines".
|
|
153
308
|
*/
|
|
154
309
|
export function toolResultSummary(label: string, result: ToolResult): string {
|
|
155
310
|
if (typeof result.error === "string") return ` — failed: ${result.error}`;
|
|
156
|
-
if (typeof result.total_matching_lines === "number")
|
|
157
|
-
|
|
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")}`;
|
|
158
315
|
if (typeof result.parts_read === "number") {
|
|
159
|
-
const incomplete = result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
|
|
160
|
-
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}`;
|
|
161
318
|
}
|
|
162
319
|
// A read reports its range only when it was cut short of what was asked.
|
|
163
320
|
if (typeof result.lines === "string" && typeof result.total_lines === "number") return label.endsWith(result.lines) ? "" : ` — got ${result.lines}`;
|
|
@@ -168,6 +325,31 @@ export function toolResultSummary(label: string, result: ToolResult): string {
|
|
|
168
325
|
return "";
|
|
169
326
|
}
|
|
170
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
|
+
|
|
171
353
|
export function createDocumentTools(options: {
|
|
172
354
|
/** Loads a document the tools may access. Return undefined for anything out of scope. */
|
|
173
355
|
load(documentId: string): Promise<DocumentSource | undefined>;
|
|
@@ -231,20 +413,28 @@ export function createDocumentTools(options: {
|
|
|
231
413
|
const maxWholeReads = Math.max(0, Math.trunc(options.maxWholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS));
|
|
232
414
|
/** Whole-document reads started, by document. */
|
|
233
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>();
|
|
234
418
|
// When no limit is given with a call: three eighths of a request, so that two looks still fit.
|
|
235
419
|
const defaultFileBytes = Math.floor((options.budget.maxRequestBytes - REQUEST_BYTES_MARGIN) * 3 / 8);
|
|
236
420
|
|
|
237
421
|
async function documentFor(args: Record<string, unknown>): Promise<DocumentSource> {
|
|
238
422
|
const id = text(args.document_id, "document_id");
|
|
239
423
|
// Scope check: a model can only reach files attached to this conversation.
|
|
240
|
-
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
|
+
}
|
|
241
431
|
const document = await options.load(id);
|
|
242
432
|
if (!document) throw new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
|
|
243
433
|
names.set(id, document.meta.name);
|
|
244
434
|
return document;
|
|
245
435
|
}
|
|
246
436
|
|
|
247
|
-
const handlers: Record<string, (args: Record<string, unknown>, limits: ToolCallLimits) => Promise<ToolResult>> = {
|
|
437
|
+
const handlers: Record<string, (args: Record<string, unknown>, limits: ToolCallLimits, hooks: ToolCallHooks) => Promise<ToolResult>> = {
|
|
248
438
|
async [TOOL_NAMES.search](args, limits) {
|
|
249
439
|
const limit = limitOf(limits);
|
|
250
440
|
const document = await documentFor(args);
|
|
@@ -288,15 +478,25 @@ export function createDocumentTools(options: {
|
|
|
288
478
|
});
|
|
289
479
|
};
|
|
290
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);
|
|
494
|
+
}
|
|
291
495
|
return fit({
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
matches: paged ? result.matches.map(({ line, ...rest }) => {
|
|
297
|
-
const page = document.pageOfLine(line);
|
|
298
|
-
return { line, ...(page ? { page } : {}), ...rest };
|
|
299
|
-
}) : 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,
|
|
300
500
|
}, "matches", limit);
|
|
301
501
|
},
|
|
302
502
|
|
|
@@ -322,7 +522,9 @@ export function createDocumentTools(options: {
|
|
|
322
522
|
lines: `${start}-${to}`,
|
|
323
523
|
...(pages ? { pages } : {}),
|
|
324
524
|
total_lines: total,
|
|
325
|
-
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 }),
|
|
326
528
|
...(to < total ? { next_start_line: to + 1 } : { note: "End of file." }),
|
|
327
529
|
};
|
|
328
530
|
},
|
|
@@ -346,14 +548,15 @@ export function createDocumentTools(options: {
|
|
|
346
548
|
...(meta.pages ? { pages: meta.pages } : {}),
|
|
347
549
|
parts_for_whole_document_analysis: parts,
|
|
348
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.` } : {}),
|
|
349
|
-
|
|
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) } : {}),
|
|
350
553
|
first_lines: numberLines(await document.readLines(1, first), 1),
|
|
351
554
|
last_lines: lineCount > 30 ? numberLines(await document.readLines(tail, lineCount), tail) : "",
|
|
352
555
|
outline: meta.outline.length ? outlineLines(meta.outline) : [],
|
|
353
556
|
}, "outline", limit);
|
|
354
557
|
},
|
|
355
558
|
|
|
356
|
-
async [TOOL_NAMES.analyze](args, limits) {
|
|
559
|
+
async [TOOL_NAMES.analyze](args, limits, hooks) {
|
|
357
560
|
if (!options.generate) throw new Error("Whole-document analysis is not enabled.");
|
|
358
561
|
const document = await documentFor(args);
|
|
359
562
|
const task = text(args.task, "task");
|
|
@@ -363,9 +566,13 @@ export function createDocumentTools(options: {
|
|
|
363
566
|
const id = document.meta.id;
|
|
364
567
|
const reads = wholeReads.get(id) ?? 0;
|
|
365
568
|
if (reads >= maxWholeReads) {
|
|
569
|
+
const failure = failedWholeReads.get(id);
|
|
366
570
|
throw new Error(maxWholeReads === 0
|
|
367
571
|
? `Whole-file reads are turned off for this question. Use search_document and read_document on ${document.meta.name}.`
|
|
368
|
-
:
|
|
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.`);
|
|
369
576
|
}
|
|
370
577
|
wholeReads.set(id, reads + 1);
|
|
371
578
|
let result;
|
|
@@ -375,26 +582,38 @@ export function createDocumentTools(options: {
|
|
|
375
582
|
task,
|
|
376
583
|
generate: options.generate,
|
|
377
584
|
budget: options.budget,
|
|
378
|
-
|
|
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 } : {}),
|
|
379
588
|
signal: options.signal,
|
|
380
589
|
...(options.retry ? { retry: options.retry } : {}),
|
|
590
|
+
...(typeof limits.maxRequests === "number" && Number.isFinite(limits.maxRequests) ? { maxRequests: limits.maxRequests } : {}),
|
|
381
591
|
});
|
|
382
592
|
} catch (error) {
|
|
383
|
-
//
|
|
384
|
-
|
|
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));
|
|
385
600
|
throw error;
|
|
386
601
|
}
|
|
602
|
+
failedWholeReads.delete(id);
|
|
387
603
|
const notesCutShort = result.truncatedParts + result.truncatedMerges;
|
|
388
|
-
return
|
|
604
|
+
return fitAnswer({
|
|
389
605
|
document: document.meta.name,
|
|
390
606
|
parts_read: result.parts,
|
|
391
607
|
parts_with_relevant_content: result.relevantParts,
|
|
392
608
|
...(result.failedParts ? { parts_that_failed: result.failedParts } : {}),
|
|
393
609
|
...(notesCutShort ? { notes_cut_short: notesCutShort } : {}),
|
|
394
610
|
...(result.answerTruncated ? { answer_cut_short: true } : {}),
|
|
395
|
-
...(
|
|
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 } : {}),
|
|
396
615
|
answer: result.answer,
|
|
397
|
-
},
|
|
616
|
+
}, limitOf(limits, Math.max(cap, ANALYSIS_RESULT_CHARACTERS)));
|
|
398
617
|
},
|
|
399
618
|
};
|
|
400
619
|
|
|
@@ -406,7 +625,7 @@ export function createDocumentTools(options: {
|
|
|
406
625
|
if (!viewable.has(id)) {
|
|
407
626
|
throw new Error(allowed.has(id)
|
|
408
627
|
? `The pages of ${names.get(id) ?? id} cannot be shown: only its text was kept. Answer from the text.`
|
|
409
|
-
: `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.`);
|
|
410
629
|
}
|
|
411
630
|
const document = await options.load(id);
|
|
412
631
|
if (!document) throw new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
|
|
@@ -450,13 +669,13 @@ export function createDocumentTools(options: {
|
|
|
450
669
|
// What a tool could not do goes to the model, and from there to a user's screen: never a server path.
|
|
451
670
|
const failure = (error: unknown): ToolResult => ({ error: safeErrorMessage(error) });
|
|
452
671
|
|
|
453
|
-
async function execute(name: string, args: Record<string, unknown>, limits: ToolCallLimits = {}): Promise<ToolResult> {
|
|
454
|
-
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)}.` };
|
|
455
674
|
// The pages are a file, and this method returns only JSON. Saying that pages are attached
|
|
456
675
|
// with nothing attached would be worse than saying that they could not be shown.
|
|
457
676
|
if (name === TOOL_NAMES.view) return { error: FILES_NOT_DELIVERED };
|
|
458
677
|
try {
|
|
459
|
-
return await handlers[name]!(args, limits);
|
|
678
|
+
return await handlers[name]!(args, limits, hooks);
|
|
460
679
|
} catch (error) {
|
|
461
680
|
if (options.signal?.aborted) throw error;
|
|
462
681
|
return failure(error);
|
|
@@ -468,8 +687,8 @@ export function createDocumentTools(options: {
|
|
|
468
687
|
has: (name) => known.has(name),
|
|
469
688
|
execute: (name, args) => execute(name, args),
|
|
470
689
|
resultCharacters: (name) => (name === TOOL_NAMES.analyze ? Math.max(cap, ANALYSIS_RESULT_CHARACTERS) : name === TOOL_NAMES.view ? LEAST_RESULT_CHARACTERS : cap),
|
|
471
|
-
async executeWithFiles(name, args, limits = {}) {
|
|
472
|
-
if (name !== TOOL_NAMES.view || !known.has(name)) return { result: await execute(name, args, limits), files: [] };
|
|
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: [] };
|
|
473
692
|
try {
|
|
474
693
|
return await viewPages(args, limits);
|
|
475
694
|
} catch (error) {
|
|
@@ -488,7 +707,7 @@ export function createDocumentTools(options: {
|
|
|
488
707
|
}
|
|
489
708
|
if (name === TOOL_NAMES.search) {
|
|
490
709
|
const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
|
|
491
|
-
return `Search ${file} (${mode}) for “${String(args.query ?? "")
|
|
710
|
+
return `Search ${file} (${mode}) for “${sliceWhole(String(args.query ?? ""), 80)}”`;
|
|
492
711
|
}
|
|
493
712
|
if (name === TOOL_NAMES.read) {
|
|
494
713
|
const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
|
|
@@ -496,7 +715,7 @@ export function createDocumentTools(options: {
|
|
|
496
715
|
return `Read ${file} lines ${start}${end}`;
|
|
497
716
|
}
|
|
498
717
|
if (name === TOOL_NAMES.overview) return `Overview of ${file}`;
|
|
499
|
-
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)}”`;
|
|
500
719
|
return name;
|
|
501
720
|
},
|
|
502
721
|
};
|
package/src/types.ts
CHANGED
|
@@ -49,6 +49,19 @@ export type DocumentMeta = {
|
|
|
49
49
|
/** Lines longer than the wrap limit are split so every line stays readable by line number. */
|
|
50
50
|
wrappedLines: number;
|
|
51
51
|
pages?: number;
|
|
52
|
+
/**
|
|
53
|
+
* The older encoding a text file was read in, because it is not UTF-8: "windows-1255" for a
|
|
54
|
+
* Hebrew CSV that Excel saved. Lines of it that are valid UTF-8 are read as UTF-8 all the same.
|
|
55
|
+
* Absent for valid UTF-8, for a file read as UTF-8 with characters that are not valid (see
|
|
56
|
+
* `replacedCharacters`), for UTF-16, for PDF, DOCX and PPTX, and on documents from before 0.6.0.
|
|
57
|
+
*/
|
|
58
|
+
encoding?: string;
|
|
59
|
+
/**
|
|
60
|
+
* Characters of a text file that were not valid in the encoding it was read in, such as a
|
|
61
|
+
* character cut in two at the end of a UTF-8 log, or a byte that `encoding` does not have: each
|
|
62
|
+
* is stored as U+FFFD (�). Absent when there were none, and on documents from before 0.6.0.
|
|
63
|
+
*/
|
|
64
|
+
replacedCharacters?: number;
|
|
52
65
|
/**
|
|
53
66
|
* True when the uploaded file itself is kept in the store next to its text (see `keepOriginals`).
|
|
54
67
|
* Recorded here so that planning a request does not have to load the file to know.
|
|
@@ -72,6 +85,10 @@ export type DocumentSummary = {
|
|
|
72
85
|
lines: number;
|
|
73
86
|
estimatedTokens: number;
|
|
74
87
|
pages?: number;
|
|
88
|
+
/** See `DocumentMeta.encoding`. */
|
|
89
|
+
encoding?: string;
|
|
90
|
+
/** See `DocumentMeta.replacedCharacters`. */
|
|
91
|
+
replacedCharacters?: number;
|
|
75
92
|
expiresAt: string;
|
|
76
93
|
};
|
|
77
94
|
|
|
@@ -109,7 +126,17 @@ export interface DocumentStore {
|
|
|
109
126
|
getIndex?(id: string): Promise<Uint8Array | undefined>;
|
|
110
127
|
}
|
|
111
128
|
|
|
112
|
-
export type ExtractedText = {
|
|
129
|
+
export type ExtractedText = {
|
|
130
|
+
text: string;
|
|
131
|
+
pages?: number;
|
|
132
|
+
/**
|
|
133
|
+
* The older encoding the file was read in, when it is not UTF-8. Kept as `DocumentMeta.encoding`
|
|
134
|
+
* when it is a name, and not one of UTF-8 or UTF-16.
|
|
135
|
+
*/
|
|
136
|
+
encoding?: string;
|
|
137
|
+
/** Characters that were not valid in the encoding the file was read in, each now U+FFFD. Kept as `DocumentMeta.replacedCharacters`. */
|
|
138
|
+
replacedCharacters?: number;
|
|
139
|
+
};
|
|
113
140
|
|
|
114
141
|
export type ExtractInput = {
|
|
115
142
|
name: string;
|
|
@@ -121,6 +148,38 @@ export type ExtractInput = {
|
|
|
121
148
|
* always was. An extractor of your own may ignore it.
|
|
122
149
|
*/
|
|
123
150
|
scannedPages?: number;
|
|
151
|
+
/**
|
|
152
|
+
* Aborted when the ingest's time is up (`ingestTimeoutMs`) or the caller gave up
|
|
153
|
+
* (`IngestInput.signal`). The built-in extractors stop between pages and pieces; its `reason`
|
|
154
|
+
* is the error to throw. An extractor of your own should stop too: `ingest` stops waiting for it
|
|
155
|
+
* either way, but cannot stop the work it does.
|
|
156
|
+
*/
|
|
157
|
+
signal?: AbortSignal;
|
|
158
|
+
/**
|
|
159
|
+
* The most text to keep from this file, in UTF-8 bytes (`maxTextBytes`). The built-in extractors
|
|
160
|
+
* refuse a file as soon as its text grows past it. `ingest` refuses any larger result.
|
|
161
|
+
*/
|
|
162
|
+
maxTextBytes?: number;
|
|
163
|
+
/** The most pages to read from one PDF (`maxPdfPages`). The built-in PDF extractor refuses more. */
|
|
164
|
+
maxPages?: number;
|
|
165
|
+
/**
|
|
166
|
+
* Call it as the extraction goes on, so `ingest` can report progress (`IngestInput.onEvent`).
|
|
167
|
+
* The built-in extractors call it for each page of a PDF (also for the page check and the
|
|
168
|
+
* picture marks: `stage` "check" and "pictures"), each part of a DOCX or PPTX, and once when a
|
|
169
|
+
* text file not in UTF-8 is decoded ("decode"). Calls after the extractor returned are dropped. An
|
|
170
|
+
* extractor of your own may ignore it. New in 0.7.0.
|
|
171
|
+
*/
|
|
172
|
+
onProgress?: (progress: ExtractProgress) => void;
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
/** How far an extraction is, for `ExtractInput.onProgress`. */
|
|
176
|
+
export type ExtractProgress = {
|
|
177
|
+
/** "extract" (the default): text read; "check": pages checked before reading; "pictures": pages looked at for pictures; "decode": bytes of a text file decoded. */
|
|
178
|
+
stage?: "extract" | "check" | "pictures" | "decode";
|
|
179
|
+
done: number;
|
|
180
|
+
/** Absent when not known. */
|
|
181
|
+
total?: number;
|
|
182
|
+
unit: "pages" | "parts" | "bytes";
|
|
124
183
|
};
|
|
125
184
|
|
|
126
185
|
export type Extractor = (bytes: Uint8Array, input: ExtractInput) => Promise<ExtractedText>;
|
|
@@ -176,7 +235,8 @@ export type ToolOutput = { result: ToolResult; files: ToolFile[] };
|
|
|
176
235
|
export type ToolCallLimits = {
|
|
177
236
|
/**
|
|
178
237
|
* The most bytes the files of this call may have together. Give the room left in your request,
|
|
179
|
-
* times 3/4 when files are sent as base64. Defaults to
|
|
238
|
+
* times 3/4 when files are sent as base64. Defaults to 3/8 of `maxRequestBytes` less 262,144
|
|
239
|
+
* (the 256 KB the library keeps free in a request).
|
|
180
240
|
*/
|
|
181
241
|
maxFileBytes?: number;
|
|
182
242
|
/** The most pages this call may show. Lower it as the pages already shown use up your token budget. */
|
|
@@ -187,7 +247,49 @@ export type ToolCallLimits = {
|
|
|
187
247
|
* says where to go on.
|
|
188
248
|
*/
|
|
189
249
|
maxResultCharacters?: number;
|
|
250
|
+
/**
|
|
251
|
+
* The most model requests a whole-file read (`analyze_whole_document`) may make: what the
|
|
252
|
+
* question has left of `limits.requests`. A part the model refuses as too large is read as two
|
|
253
|
+
* halves only while that and `maxMapChunks` allow it.
|
|
254
|
+
*/
|
|
255
|
+
maxRequests?: number;
|
|
256
|
+
};
|
|
257
|
+
/**
|
|
258
|
+
* Listeners for one tool call, next to its limits. New in 0.7.0: with them, the progress of two
|
|
259
|
+
* whole-file reads that run at once can be told apart.
|
|
260
|
+
*/
|
|
261
|
+
export type ToolCallHooks = {
|
|
262
|
+
/** Progress of this call (a whole-file read), in place of `ToolOptions.onProgress` for it. */
|
|
263
|
+
onProgress?: ProgressListener;
|
|
264
|
+
/**
|
|
265
|
+
* Each model request this call makes (a whole-file read), as it starts. Tell the handle it
|
|
266
|
+
* returns about each retry of that request, and when it ends.
|
|
267
|
+
*/
|
|
268
|
+
onRequest?: (request: ToolRequestStart) => ToolRequestHandle;
|
|
190
269
|
};
|
|
270
|
+
|
|
271
|
+
/** One model request of a tool call (`ToolCallHooks.onRequest`). */
|
|
272
|
+
export type ToolRequestHandle = {
|
|
273
|
+
/** The request failed and is sent again after `delayMs`. */
|
|
274
|
+
retry(notice: { attempt: number; delayMs: number; error: unknown }): void;
|
|
275
|
+
/** The request ended, after any retries. Call it once. */
|
|
276
|
+
end(end: ToolRequestEnd): void;
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
/** A model request of a tool call, as it starts (`ToolCallHooks.onRequest`). */
|
|
280
|
+
export type ToolRequestStart = {
|
|
281
|
+
purpose: "part" | "merge" | "final";
|
|
282
|
+
/** "part 3 of 12", "first half of part 3 of 12", "round 2: 1 of 4", "the answer". */
|
|
283
|
+
detail: string;
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
/** A model request of a tool call, as it ends. */
|
|
287
|
+
export type ToolRequestEnd = {
|
|
288
|
+
outcome: "ok" | "error";
|
|
289
|
+
usage?: GenerateUsage;
|
|
290
|
+
error?: unknown;
|
|
291
|
+
};
|
|
292
|
+
|
|
191
293
|
/** The name of `ToolCallLimits` before 0.5.0. */
|
|
192
294
|
export type ToolFileLimits = ToolCallLimits;
|
|
193
295
|
|
|
@@ -203,7 +305,7 @@ export type ToolSet = {
|
|
|
203
305
|
* Runs a tool call and also returns the files it produced, to be sent to the model with the
|
|
204
306
|
* result. Use it in place of `execute` in a loop that can send files.
|
|
205
307
|
*/
|
|
206
|
-
executeWithFiles(name: string, args: Record<string, unknown>, limits?: ToolCallLimits): Promise<ToolOutput>;
|
|
308
|
+
executeWithFiles(name: string, args: Record<string, unknown>, limits?: ToolCallLimits, hooks?: ToolCallHooks): Promise<ToolOutput>;
|
|
207
309
|
/** A short, human-readable line describing a call, for progress UIs. */
|
|
208
310
|
describe(name: string, args: Record<string, unknown>): string;
|
|
209
311
|
/**
|
|
@@ -230,7 +332,8 @@ export type GenerateText = (request: {
|
|
|
230
332
|
onTruncated?: () => void;
|
|
231
333
|
/**
|
|
232
334
|
* Call this once for every request that was answered, with the tokens it used, so that the cost
|
|
233
|
-
* of a whole-document read is counted. Optional: without it
|
|
335
|
+
* of a whole-document read is counted. Optional: without it, `askWithFiles` still counts each
|
|
336
|
+
* answered request (in `usage.requests` and against `limits.requests`), but not its tokens.
|
|
234
337
|
*/
|
|
235
338
|
onUsage?: (usage: GenerateUsage) => void;
|
|
236
339
|
}) => Promise<string>;
|