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/dist/tools.js
CHANGED
|
@@ -1,19 +1,30 @@
|
|
|
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
4
|
import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS } from "./search.js";
|
|
5
5
|
import { estimateParts, formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
|
|
6
|
+
import { plural, removeInvisible, sliceWhole, wellFormedJson } from "./text.js";
|
|
6
7
|
const DEFAULT_READ_LINES = 200;
|
|
7
8
|
const MAX_READ_LINES = 600;
|
|
8
9
|
/** The most pages one `view_pages` call shows. A page costs a model about 530 tokens. */
|
|
9
10
|
export const MAX_VIEW_PAGES = 5;
|
|
10
11
|
/**
|
|
11
|
-
* The time the regex searches of one tool set (one question, in `
|
|
12
|
+
* The time the regex searches of one tool set (one question, in `askWithFiles`) may take together,
|
|
12
13
|
* unless `regexBudgetMs` says otherwise. An ordinary search of a 60 MB log takes about 0.15 s.
|
|
13
14
|
*/
|
|
14
15
|
export const REGEX_BUDGET_MS = 6_000;
|
|
15
16
|
/** Below this, no page fits: a cut of one page of plain text is larger. */
|
|
16
17
|
const MIN_FILE_BYTES = 1_024;
|
|
18
|
+
/** The answer of a whole-document read may be this long, when the cap on tool results is lower. */
|
|
19
|
+
const ANALYSIS_RESULT_CHARACTERS = 40_000;
|
|
20
|
+
/** A result is never cut below this, whatever room a caller names: less holds no line of a file. */
|
|
21
|
+
export const LEAST_RESULT_CHARACTERS = 600;
|
|
22
|
+
/**
|
|
23
|
+
* How many times one document is read whole by the tools of one tool set (one question, in
|
|
24
|
+
* `askWithFiles`), unless `maxWholeDocumentReads` says otherwise. One read of a large file is
|
|
25
|
+
* up to `maxMapChunks` model requests.
|
|
26
|
+
*/
|
|
27
|
+
export const MAX_WHOLE_DOCUMENT_READS = 1;
|
|
17
28
|
export const TOOL_NAMES = {
|
|
18
29
|
search: "search_document",
|
|
19
30
|
read: "read_document",
|
|
@@ -25,7 +36,7 @@ const documentId = { type: "string", description: "The document_id from the file
|
|
|
25
36
|
const DECLARATIONS = {
|
|
26
37
|
search: {
|
|
27
38
|
name: TOOL_NAMES.search,
|
|
28
|
-
description: "Search a large attached file. mode \"keywords\" returns the most relevant passages for a question; \"exact\"
|
|
39
|
+
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.",
|
|
29
40
|
parameters: {
|
|
30
41
|
type: "object",
|
|
31
42
|
properties: {
|
|
@@ -59,7 +70,7 @@ const DECLARATIONS = {
|
|
|
59
70
|
},
|
|
60
71
|
analyze: {
|
|
61
72
|
name: TOOL_NAMES.analyze,
|
|
62
|
-
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
|
|
73
|
+
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.",
|
|
63
74
|
parameters: {
|
|
64
75
|
type: "object",
|
|
65
76
|
properties: {
|
|
@@ -104,14 +115,18 @@ function pageNumber(value, name) {
|
|
|
104
115
|
return Math.trunc(number);
|
|
105
116
|
}
|
|
106
117
|
const pageRange = (from, to) => (to > from ? `${from}-${to}` : String(from));
|
|
107
|
-
/**
|
|
118
|
+
/**
|
|
119
|
+
* Trims a result to the character budget by dropping trailing list entries, then cutting text. A
|
|
120
|
+
* note the result already has (a search that stopped early) is kept, before the one that says so.
|
|
121
|
+
*/
|
|
108
122
|
function fit(result, listKey, limit) {
|
|
109
123
|
if (JSON.stringify(result).length <= limit)
|
|
110
124
|
return result;
|
|
111
125
|
const list = listKey ? result[listKey] : undefined;
|
|
112
126
|
if (Array.isArray(list)) {
|
|
113
127
|
const kept = [...list];
|
|
114
|
-
const
|
|
128
|
+
const before = typeof result.note === "string" ? `${result.note} ` : "";
|
|
129
|
+
const note = () => `${before}Showing ${kept.length} of ${list.length} results to stay within the size limit. Narrow the query or read specific lines.`;
|
|
115
130
|
const trimmed = () => ({ ...result, [listKey]: kept, note: note() });
|
|
116
131
|
while (kept.length > 1 && JSON.stringify(trimmed()).length > limit)
|
|
117
132
|
kept.pop();
|
|
@@ -124,10 +139,171 @@ function fit(result, listKey, limit) {
|
|
|
124
139
|
let cut;
|
|
125
140
|
do {
|
|
126
141
|
size = Math.floor(size * 0.85);
|
|
127
|
-
cut = { truncated: true, partial: serialized
|
|
142
|
+
cut = { truncated: true, partial: sliceWhole(serialized, size), note: "Result cut to the size limit. Ask for a smaller range." };
|
|
128
143
|
} while (JSON.stringify(cut).length > limit && size > 100);
|
|
129
144
|
return cut;
|
|
130
145
|
}
|
|
146
|
+
/**
|
|
147
|
+
* The result of a whole-document read within `limit` characters: its answer is cut at the end,
|
|
148
|
+
* and says so, rather than the result being cut as JSON, which loses what the other fields say.
|
|
149
|
+
*/
|
|
150
|
+
export function fitAnswer(result, limit) {
|
|
151
|
+
if (JSON.stringify(result).length <= limit || typeof result.answer !== "string")
|
|
152
|
+
return fit(result, null, limit);
|
|
153
|
+
const answer = result.answer;
|
|
154
|
+
const cutAt = (keep) => ({
|
|
155
|
+
...result,
|
|
156
|
+
answer: `${sliceWhole(answer, keep)}…`,
|
|
157
|
+
answer_shortened: "The rest of this answer did not fit in the room left in this conversation.",
|
|
158
|
+
});
|
|
159
|
+
// The longest start of the answer that fits. Escapes (quotes, line breaks) make the JSON longer
|
|
160
|
+
// than the text by as much as the text holds of them, so it is found by halving, not worked out.
|
|
161
|
+
let low = 0;
|
|
162
|
+
let high = answer.length;
|
|
163
|
+
while (low < high) {
|
|
164
|
+
const middle = Math.ceil((low + high) / 2);
|
|
165
|
+
if (JSON.stringify(cutAt(middle)).length <= limit)
|
|
166
|
+
low = middle;
|
|
167
|
+
else
|
|
168
|
+
high = middle - 1;
|
|
169
|
+
}
|
|
170
|
+
return fit(cutAt(low), null, limit);
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* The result of an exact or regex search that read the whole file: the first matches, then the
|
|
174
|
+
* last one of the file, and a note that says how many of how many are shown when that is not all.
|
|
175
|
+
* Without the last one, a model asked when something last happened named the last line it was
|
|
176
|
+
* shown. To fit `limit`, matches are dropped from the end of the first ones: the last one stays.
|
|
177
|
+
*/
|
|
178
|
+
function firstAndLastMatches(base, first, last, total, limit) {
|
|
179
|
+
const which = (kept) => (kept === 0 ? `the last (line ${last.line})` : `the first${kept > 1 ? ` ${kept}` : ""} and the last (line ${last.line})`);
|
|
180
|
+
const shown = (kept) => `${kept + 1} of the ${total} matching lines`;
|
|
181
|
+
const withFirst = (kept, cut) => ({
|
|
182
|
+
...base,
|
|
183
|
+
...(cut
|
|
184
|
+
? { note: `Showing ${shown(kept)} to stay within the size limit: ${which(kept)}. Narrow the query or read specific lines.` }
|
|
185
|
+
// When every match is shown, there is nothing to say.
|
|
186
|
+
: kept + 1 < total ? { note: `${shown(kept)} are shown: ${which(kept)}. To see the ones in between, narrow the search.` } : {}),
|
|
187
|
+
matches: [...first.slice(0, kept), last],
|
|
188
|
+
});
|
|
189
|
+
const whole = withFirst(first.length, false);
|
|
190
|
+
if (JSON.stringify(whole).length <= limit)
|
|
191
|
+
return whole;
|
|
192
|
+
let kept = first.length;
|
|
193
|
+
while (kept > 0 && JSON.stringify(withFirst(kept, true)).length > limit)
|
|
194
|
+
kept--;
|
|
195
|
+
const cut = withFirst(kept, true);
|
|
196
|
+
if (JSON.stringify(cut).length <= limit)
|
|
197
|
+
return cut;
|
|
198
|
+
// Only the last match is left, and its note is too long for the room: a shorter one. It still
|
|
199
|
+
// starts with "Showing ", so the result is taken as cut. `fit` must not put its own note in its
|
|
200
|
+
// place, which would say "1 of 1 results" and drop the line of the last match. When even this
|
|
201
|
+
// does not fit, `fit` cuts the result as text: the note, with that line, comes before the match.
|
|
202
|
+
const lastOnly = { ...base, note: `Showing 1 of the ${total} matching lines: ${which(0)}. Narrow the search.`, matches: [last] };
|
|
203
|
+
return fit(lastOnly, null, limit);
|
|
204
|
+
}
|
|
205
|
+
const searchMode = (mode) => (mode === "exact" || mode === "regex" ? mode : "keywords");
|
|
206
|
+
/** The lines a `read_document` call asks for, as its handler reads them, before the end of the file is known. */
|
|
207
|
+
function requestedLines(args) {
|
|
208
|
+
const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
|
|
209
|
+
return [start, integer(args.end_line, start + DEFAULT_READ_LINES - 1, start, start + MAX_READ_LINES - 1)];
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* A call's arguments as its tool reads them, with the defaults filled in: two calls with the same
|
|
213
|
+
* key get the same result from a file that has not changed. Undefined for a tool whose calls are
|
|
214
|
+
* not compared (a whole-file read has a count of its own; a look at pages returns a file).
|
|
215
|
+
*/
|
|
216
|
+
export function toolCallKey(name, args) {
|
|
217
|
+
const id = typeof args.document_id === "string" && args.document_id ? args.document_id : undefined;
|
|
218
|
+
if (!id)
|
|
219
|
+
return undefined;
|
|
220
|
+
if (name === TOOL_NAMES.search) {
|
|
221
|
+
if (typeof args.query !== "string" || !args.query.trim())
|
|
222
|
+
return undefined;
|
|
223
|
+
const mode = searchMode(args.mode);
|
|
224
|
+
return JSON.stringify(mode === "keywords"
|
|
225
|
+
? [name, id, args.query, mode, integer(args.max_results, 5, 1, 10)]
|
|
226
|
+
: [name, id, args.query, mode, integer(args.max_results, 20, 1, 50), integer(args.context_lines, 0, 0, 5), args.case_sensitive === true]);
|
|
227
|
+
}
|
|
228
|
+
if (name === TOOL_NAMES.read)
|
|
229
|
+
return JSON.stringify([name, id, ...requestedLines(args)]);
|
|
230
|
+
if (name === TOOL_NAMES.overview)
|
|
231
|
+
return JSON.stringify([name, id]);
|
|
232
|
+
return undefined;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* When an earlier call's result already holds all that `call` would return, and is still in the
|
|
236
|
+
* conversation in full: a short result that says so, in place of running the call again. A result
|
|
237
|
+
* that was cut to the room it had, or replaced by a stand-in, or failed, is not pointed to: the call
|
|
238
|
+
* is run, and may get more. A read of lines inside a read that is shown in full is pointed to.
|
|
239
|
+
* `stored` is true for a result in the tool rounds of an earlier question, which an older version
|
|
240
|
+
* may have written: 0.5.0 cut the text of a read of one long line without saying so (no
|
|
241
|
+
* `text_cut`), so a read of one line from there is not taken as shown in full.
|
|
242
|
+
*/
|
|
243
|
+
export function alreadyShown(call, earlier, stored = false) {
|
|
244
|
+
const { result } = earlier;
|
|
245
|
+
if (earlier.call.name !== call.name || earlier.call.args.document_id !== call.args.document_id)
|
|
246
|
+
return undefined;
|
|
247
|
+
if (result.dropped === true || result.already_shown === true || typeof result.error === "string" || result.truncated === true)
|
|
248
|
+
return undefined;
|
|
249
|
+
// A list that `fit` cut to the room it had, a read whose text was cut, or a search that ran out of
|
|
250
|
+
// time ("the total is a lower bound"; a later question has time of its own): a call made now may get more.
|
|
251
|
+
if (typeof result.note === "string" && (result.note.startsWith("Showing ") || result.note.startsWith("The scan stopped early")))
|
|
252
|
+
return undefined;
|
|
253
|
+
if (result.text_cut === true)
|
|
254
|
+
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")
|
|
259
|
+
return undefined;
|
|
260
|
+
const document = typeof result.document === "string" ? { document: result.document } : {};
|
|
261
|
+
if (call.name === TOOL_NAMES.read) {
|
|
262
|
+
const shown = typeof result.lines === "string" ? /^(\d+)-(\d+)$/.exec(result.lines) : null;
|
|
263
|
+
const total = result.total_lines;
|
|
264
|
+
if (!shown || typeof total !== "number")
|
|
265
|
+
return undefined;
|
|
266
|
+
const [first, last] = [Number(shown[1]), Number(shown[2])];
|
|
267
|
+
if (stored && first === last)
|
|
268
|
+
return undefined;
|
|
269
|
+
const [start, end] = requestedLines(call.args);
|
|
270
|
+
const from = Math.min(start, total);
|
|
271
|
+
const to = Math.min(end, total);
|
|
272
|
+
if (from < first || to > last)
|
|
273
|
+
return undefined;
|
|
274
|
+
return {
|
|
275
|
+
...document,
|
|
276
|
+
lines: `${from}-${to}`,
|
|
277
|
+
already_shown: true,
|
|
278
|
+
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.`,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
const key = toolCallKey(call.name, call.args);
|
|
282
|
+
if (key === undefined || key !== toolCallKey(earlier.call.name, earlier.call.args))
|
|
283
|
+
return undefined;
|
|
284
|
+
return {
|
|
285
|
+
...document,
|
|
286
|
+
already_shown: true,
|
|
287
|
+
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.",
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* A hint added to the error of a search that failed twice in a row in the same mode, so that the
|
|
292
|
+
* model tries another way instead of sending the same kind of call a third time.
|
|
293
|
+
*/
|
|
294
|
+
export function repeatedFailureHint(call) {
|
|
295
|
+
return searchMode(call.args.mode) === "regex"
|
|
296
|
+
? "Two regex searches in a row failed. Try mode \"exact\" with a plain word or ID from the file, or mode \"keywords\"."
|
|
297
|
+
: "This search failed twice in a row. Check the arguments against the tool's description, or answer from what you have.";
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* The tool and mode of a search, to tell whether two failures in a row were of the same kind.
|
|
301
|
+
* Undefined for the other tools: their errors say what to do (a whole-file read that is not made
|
|
302
|
+
* again, a page that does not exist), and a hint would only blur that.
|
|
303
|
+
*/
|
|
304
|
+
export function failureKind(call) {
|
|
305
|
+
return call.name === TOOL_NAMES.search ? `${call.name}|${searchMode(call.args.mode)}` : undefined;
|
|
306
|
+
}
|
|
131
307
|
/**
|
|
132
308
|
* What a finished tool call found, as a suffix for its `describe()` label, for a steps list:
|
|
133
309
|
* "Search app.log (exact) for “timeout”" + " — 12 matching lines".
|
|
@@ -135,13 +311,14 @@ function fit(result, listKey, limit) {
|
|
|
135
311
|
export function toolResultSummary(label, result) {
|
|
136
312
|
if (typeof result.error === "string")
|
|
137
313
|
return ` — failed: ${result.error}`;
|
|
138
|
-
if (typeof result.total_matching_lines === "number")
|
|
139
|
-
return ` — ${result.total_matching_lines.toLocaleString("en-US")} matching
|
|
314
|
+
if (typeof result.total_matching_lines === "number") {
|
|
315
|
+
return ` — ${result.total_matching_lines.toLocaleString("en-US")} ${plural(result.total_matching_lines, "matching line")}`;
|
|
316
|
+
}
|
|
140
317
|
if (Array.isArray(result.passages))
|
|
141
|
-
return ` — ${result.passages.length} passages`;
|
|
318
|
+
return ` — ${result.passages.length} ${plural(result.passages.length, "passage")}`;
|
|
142
319
|
if (typeof result.parts_read === "number") {
|
|
143
|
-
const incomplete = result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
|
|
144
|
-
return ` — ${result.parts_read}
|
|
320
|
+
const incomplete = result.notes_only ? ", notes only" : result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
|
|
321
|
+
return ` — ${result.parts_read} ${plural(result.parts_read, "part")}, ${String(result.parts_with_relevant_content ?? 0)} relevant${incomplete}`;
|
|
145
322
|
}
|
|
146
323
|
// A read reports its range only when it was cut short of what was asked.
|
|
147
324
|
if (typeof result.lines === "string" && typeof result.total_lines === "number")
|
|
@@ -152,6 +329,28 @@ export function toolResultSummary(label, result) {
|
|
|
152
329
|
}
|
|
153
330
|
return "";
|
|
154
331
|
}
|
|
332
|
+
/**
|
|
333
|
+
* A step, or a label of one, as one line of plain text. Steps quote what the model sent (a query, a
|
|
334
|
+
* task, the name of a tool, arguments that were not JSON), and they reach users' screens: the
|
|
335
|
+
* invisible characters that file text and names lose are dropped (`removeInvisible`: text-direction
|
|
336
|
+
* overrides and isolates, zero-width spaces, tag characters), a line break, a tab or another control
|
|
337
|
+
* character becomes one space with the blanks around it, and "](" gets a space, so that a markdown
|
|
338
|
+
* link or picture in a query stays text. A line without them is unchanged.
|
|
339
|
+
*/
|
|
340
|
+
export function stepLine(text) {
|
|
341
|
+
// Each control character, tab and line break is a "\n" first, which `removeInvisible` keeps (it
|
|
342
|
+
// would drop the others): an invisible character between two of them then leaves one space, not
|
|
343
|
+
// two. A soft hyphen it keeps before one goes too. Then a run of blanks with a "\n" in it is one space.
|
|
344
|
+
const marked = removeInvisible(text.replace(/[\p{Cc}\p{Zl}\p{Zp}]/gu, "\n")).replace(/\xAD+(?=\n)/g, "");
|
|
345
|
+
return marked.replace(/\s+/g, (blank) => (blank.includes("\n") ? " " : blank)).replaceAll("](", "] (");
|
|
346
|
+
}
|
|
347
|
+
/** An unknown tool's name as a step or an error quotes it: the model chose it, at any length. */
|
|
348
|
+
export const unknownToolName = (name) => `“${sliceWhole(name, 64)}”`;
|
|
349
|
+
/**
|
|
350
|
+
* A document_id the model sent, as an error quotes it: whole when it is as long as a real one can
|
|
351
|
+
* be, cut otherwise. The model chose it, at any length, and the error goes into steps too.
|
|
352
|
+
*/
|
|
353
|
+
const shownId = (id) => (id.length > 64 ? `${sliceWhole(id, 64)}…` : id);
|
|
155
354
|
export function createDocumentTools(options) {
|
|
156
355
|
const allowed = new Set(options.documentIds);
|
|
157
356
|
const viewable = new Set(options.loadOriginal ? options.viewableIds ?? [] : []);
|
|
@@ -166,18 +365,41 @@ export function createDocumentTools(options) {
|
|
|
166
365
|
// Not declared for files that are all too large for it, but still answered: with the reason, not "unknown tool".
|
|
167
366
|
if (textTools && options.generate)
|
|
168
367
|
known.add(TOOL_NAMES.analyze);
|
|
169
|
-
const
|
|
368
|
+
const cap = options.budget.toolResultCharacters;
|
|
369
|
+
/** The cap on the result of one call: the tool set's own, or the room its caller has left when that is less. */
|
|
370
|
+
const limitOf = (limits, own = cap) => {
|
|
371
|
+
const room = limits.maxResultCharacters;
|
|
372
|
+
return typeof room === "number" && Number.isFinite(room) ? Math.max(LEAST_RESULT_CHARACTERS, Math.min(own, Math.trunc(room))) : own;
|
|
373
|
+
};
|
|
170
374
|
// The model writes the regex, and a file it reads can ask for a slow one: the time is counted
|
|
171
375
|
// over every search of this tool set, not only within one.
|
|
172
376
|
const regexBudget = Math.max(0, options.regexBudgetMs ?? REGEX_BUDGET_MS);
|
|
173
377
|
const regexClock = { usedMs: 0 };
|
|
378
|
+
// Calls of one turn may run together. Regex searches still take their turns, one after another:
|
|
379
|
+
// each must know how much of the time the ones before it used.
|
|
380
|
+
let regexQueue = Promise.resolve();
|
|
381
|
+
const inRegexTurn = (run) => {
|
|
382
|
+
const next = regexQueue.then(run, run);
|
|
383
|
+
regexQueue = next.catch(() => undefined);
|
|
384
|
+
return next;
|
|
385
|
+
};
|
|
386
|
+
const maxWholeReads = Math.max(0, Math.trunc(options.maxWholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS));
|
|
387
|
+
/** Whole-document reads started, by document. */
|
|
388
|
+
const wholeReads = new Map();
|
|
389
|
+
/** Why the last whole-document read of a document failed, when no part of it could be read. */
|
|
390
|
+
const failedWholeReads = new Map();
|
|
174
391
|
// When no limit is given with a call: three eighths of a request, so that two looks still fit.
|
|
175
392
|
const defaultFileBytes = Math.floor((options.budget.maxRequestBytes - REQUEST_BYTES_MARGIN) * 3 / 8);
|
|
176
393
|
async function documentFor(args) {
|
|
177
394
|
const id = text(args.document_id, "document_id");
|
|
178
395
|
// Scope check: a model can only reach files attached to this conversation.
|
|
179
|
-
if (!allowed.has(id))
|
|
180
|
-
|
|
396
|
+
if (!allowed.has(id)) {
|
|
397
|
+
// The IDs it may use, with their file names, so that the next call is right.
|
|
398
|
+
const usable = [...allowed].slice(0, 20).map((known) => `${known}${names.has(known) ? ` (${JSON.stringify(names.get(known))})` : ""}`);
|
|
399
|
+
throw new Error(usable.length === 0
|
|
400
|
+
? `Unknown document_id ${shownId(id)}. No attached file is read with this tool in this conversation.`
|
|
401
|
+
: `Unknown document_id ${shownId(id)}. Use one of: ${usable.join(", ")}${allowed.size > 20 ? ", …" : ""}.`);
|
|
402
|
+
}
|
|
181
403
|
const document = await options.load(id);
|
|
182
404
|
if (!document)
|
|
183
405
|
throw new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
|
|
@@ -185,7 +407,8 @@ export function createDocumentTools(options) {
|
|
|
185
407
|
return document;
|
|
186
408
|
}
|
|
187
409
|
const handlers = {
|
|
188
|
-
async [TOOL_NAMES.search](args) {
|
|
410
|
+
async [TOOL_NAMES.search](args, limits) {
|
|
411
|
+
const limit = limitOf(limits);
|
|
189
412
|
const document = await documentFor(args);
|
|
190
413
|
const query = text(args.query, "query");
|
|
191
414
|
const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
|
|
@@ -212,30 +435,45 @@ export function createDocumentTools(options) {
|
|
|
212
435
|
}, "passages", limit);
|
|
213
436
|
}
|
|
214
437
|
const regex = mode === "regex";
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
|
|
438
|
+
const grep = async () => {
|
|
439
|
+
const regexLeft = regexBudget - regexClock.usedMs;
|
|
440
|
+
if (regex && regexLeft <= 0) {
|
|
441
|
+
throw new Error("The time for regex searches is used up for this answer. Search with mode \"exact\" or \"keywords\" instead.");
|
|
442
|
+
}
|
|
443
|
+
return grepSource(document, query, {
|
|
444
|
+
regex,
|
|
445
|
+
caseSensitive: args.case_sensitive === true,
|
|
446
|
+
maxResults: integer(args.max_results, 20, 1, 50),
|
|
447
|
+
contextLines: integer(args.context_lines, 0, 0, 5),
|
|
448
|
+
...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
|
|
449
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
450
|
+
});
|
|
451
|
+
};
|
|
452
|
+
const result = await (regex ? inRegexTurn(grep) : grep());
|
|
453
|
+
const placed = (match) => {
|
|
454
|
+
if (!paged)
|
|
455
|
+
return match;
|
|
456
|
+
const { line, ...rest } = match;
|
|
457
|
+
const page = document.pageOfLine(line);
|
|
458
|
+
return { line, ...(page ? { page } : {}), ...rest };
|
|
459
|
+
};
|
|
460
|
+
const base = { document: document.meta.name, mode, total_matching_lines: result.totalMatchingLines };
|
|
461
|
+
const matches = result.matches.map(placed);
|
|
462
|
+
if (!result.stoppedEarly && result.totalMatchingLines >= 2) {
|
|
463
|
+
// The last match is `last`, or, when every match is among the first ones, the last of them.
|
|
464
|
+
return result.last
|
|
465
|
+
? firstAndLastMatches(base, matches, placed(result.last), result.totalMatchingLines, limit)
|
|
466
|
+
: firstAndLastMatches(base, matches.slice(0, -1), matches.at(-1), result.totalMatchingLines, limit);
|
|
218
467
|
}
|
|
219
|
-
const result = await grepSource(document, query, {
|
|
220
|
-
regex,
|
|
221
|
-
caseSensitive: args.case_sensitive === true,
|
|
222
|
-
maxResults: integer(args.max_results, 20, 1, 50),
|
|
223
|
-
contextLines: integer(args.context_lines, 0, 0, 5),
|
|
224
|
-
...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
|
|
225
|
-
...(options.signal ? { signal: options.signal } : {}),
|
|
226
|
-
});
|
|
227
468
|
return fit({
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
matches: paged ? result.matches.map(({ line, ...rest }) => {
|
|
233
|
-
const page = document.pageOfLine(line);
|
|
234
|
-
return { line, ...(page ? { page } : {}), ...rest };
|
|
235
|
-
}) : result.matches,
|
|
469
|
+
...base,
|
|
470
|
+
// The description says the last match is shown: here it is not known.
|
|
471
|
+
...(result.stoppedEarly ? { note: "The scan stopped early; the total is a lower bound, and the last match in the file is not known." } : {}),
|
|
472
|
+
matches,
|
|
236
473
|
}, "matches", limit);
|
|
237
474
|
},
|
|
238
|
-
async [TOOL_NAMES.read](args) {
|
|
475
|
+
async [TOOL_NAMES.read](args, limits) {
|
|
476
|
+
const limit = limitOf(limits);
|
|
239
477
|
const document = await documentFor(args);
|
|
240
478
|
const total = document.lineCount;
|
|
241
479
|
const start = integer(args.start_line, 1, 1, total);
|
|
@@ -256,11 +494,14 @@ export function createDocumentTools(options) {
|
|
|
256
494
|
lines: `${start}-${to}`,
|
|
257
495
|
...(pages ? { pages } : {}),
|
|
258
496
|
total_lines: total,
|
|
259
|
-
text: fits(body) ? body : body
|
|
497
|
+
text: fits(body) ? body : sliceWhole(body, Math.floor((limit - 500) / 2)),
|
|
498
|
+
// One line longer than the room: its text was cut, so the lines are not all shown.
|
|
499
|
+
...(fits(body) ? {} : { text_cut: true }),
|
|
260
500
|
...(to < total ? { next_start_line: to + 1 } : { note: "End of file." }),
|
|
261
501
|
};
|
|
262
502
|
},
|
|
263
|
-
async [TOOL_NAMES.overview](args) {
|
|
503
|
+
async [TOOL_NAMES.overview](args, limits) {
|
|
504
|
+
const limit = limitOf(limits);
|
|
264
505
|
const document = await documentFor(args);
|
|
265
506
|
const { meta, lineCount } = document;
|
|
266
507
|
const tail = Math.max(1, lineCount - 19);
|
|
@@ -278,36 +519,75 @@ export function createDocumentTools(options) {
|
|
|
278
519
|
...(meta.pages ? { pages: meta.pages } : {}),
|
|
279
520
|
parts_for_whole_document_analysis: parts,
|
|
280
521
|
...(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.` } : {}),
|
|
281
|
-
|
|
522
|
+
// 0.5.0 stored some log templates cut inside an emoji: half of a character is not sent.
|
|
523
|
+
...(meta.logProfile ? { log_profile: wellFormedJson(meta.logProfile) } : {}),
|
|
282
524
|
first_lines: numberLines(await document.readLines(1, first), 1),
|
|
283
525
|
last_lines: lineCount > 30 ? numberLines(await document.readLines(tail, lineCount), tail) : "",
|
|
284
526
|
outline: meta.outline.length ? outlineLines(meta.outline) : [],
|
|
285
527
|
}, "outline", limit);
|
|
286
528
|
},
|
|
287
|
-
async [TOOL_NAMES.analyze](args) {
|
|
529
|
+
async [TOOL_NAMES.analyze](args, limits, hooks) {
|
|
288
530
|
if (!options.generate)
|
|
289
531
|
throw new Error("Whole-document analysis is not enabled.");
|
|
290
532
|
const document = await documentFor(args);
|
|
291
533
|
const task = text(args.task, "task");
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
534
|
+
// A read of the whole file is many model requests. A model that asks for it again, with the
|
|
535
|
+
// task put another way, is told to use what it has. The count is taken before the read
|
|
536
|
+
// starts, so that two calls in one turn do not both pass.
|
|
537
|
+
const id = document.meta.id;
|
|
538
|
+
const reads = wholeReads.get(id) ?? 0;
|
|
539
|
+
if (reads >= maxWholeReads) {
|
|
540
|
+
const failure = failedWholeReads.get(id);
|
|
541
|
+
throw new Error(maxWholeReads === 0
|
|
542
|
+
? `Whole-file reads are turned off for this question. Use search_document and read_document on ${document.meta.name}.`
|
|
543
|
+
: failure !== undefined
|
|
544
|
+
// There is no answer to use: saying "use the answer of that read" would invite one made up.
|
|
545
|
+
? `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.`
|
|
546
|
+
: `${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.`);
|
|
547
|
+
}
|
|
548
|
+
wholeReads.set(id, reads + 1);
|
|
549
|
+
let result;
|
|
550
|
+
try {
|
|
551
|
+
result = await analyzeWholeDocument({
|
|
552
|
+
document,
|
|
553
|
+
task,
|
|
554
|
+
generate: options.generate,
|
|
555
|
+
budget: options.budget,
|
|
556
|
+
// The call's own listener, when it has one, in place of the tool set's.
|
|
557
|
+
onProgress: hooks.onProgress ?? options.onProgress,
|
|
558
|
+
...(hooks.onRequest ? { onRequest: hooks.onRequest } : {}),
|
|
559
|
+
signal: options.signal,
|
|
560
|
+
...(options.retry ? { retry: options.retry } : {}),
|
|
561
|
+
...(typeof limits.maxRequests === "number" && Number.isFinite(limits.maxRequests) ? { maxRequests: limits.maxRequests } : {}),
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
catch (error) {
|
|
565
|
+
// Parts were sent and none could be read: that read is counted, since another would most
|
|
566
|
+
// likely fail the same way. Anything else (too many parts, a store that could not be read)
|
|
567
|
+
// failed before any model request: that was no read. Its count is given back, not set to
|
|
568
|
+
// what it was when the read started, which would take back the count of another read of
|
|
569
|
+
// the same document running in this turn.
|
|
570
|
+
if (error instanceof NothingReadError)
|
|
571
|
+
failedWholeReads.set(id, error.reason);
|
|
572
|
+
else
|
|
573
|
+
wholeReads.set(id, Math.max(0, (wholeReads.get(id) ?? 1) - 1));
|
|
574
|
+
throw error;
|
|
575
|
+
}
|
|
576
|
+
failedWholeReads.delete(id);
|
|
300
577
|
const notesCutShort = result.truncatedParts + result.truncatedMerges;
|
|
301
|
-
return
|
|
578
|
+
return fitAnswer({
|
|
302
579
|
document: document.meta.name,
|
|
303
580
|
parts_read: result.parts,
|
|
304
581
|
parts_with_relevant_content: result.relevantParts,
|
|
305
582
|
...(result.failedParts ? { parts_that_failed: result.failedParts } : {}),
|
|
306
583
|
...(notesCutShort ? { notes_cut_short: notesCutShort } : {}),
|
|
307
584
|
...(result.answerTruncated ? { answer_cut_short: true } : {}),
|
|
308
|
-
...(
|
|
585
|
+
...(result.answerFailed !== undefined ? { notes_only: true } : {}),
|
|
586
|
+
...(result.answerFailed !== undefined
|
|
587
|
+
? { 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." : ""}` }
|
|
588
|
+
: notesCutShort || result.answerTruncated ? { note: INCOMPLETE_ANALYSIS } : {}),
|
|
309
589
|
answer: result.answer,
|
|
310
|
-
},
|
|
590
|
+
}, limitOf(limits, Math.max(cap, ANALYSIS_RESULT_CHARACTERS)));
|
|
311
591
|
},
|
|
312
592
|
};
|
|
313
593
|
/** `view_pages`: the pages as one small PDF, next to a short JSON result. */
|
|
@@ -318,7 +598,7 @@ export function createDocumentTools(options) {
|
|
|
318
598
|
if (!viewable.has(id)) {
|
|
319
599
|
throw new Error(allowed.has(id)
|
|
320
600
|
? `The pages of ${names.get(id) ?? id} cannot be shown: only its text was kept. Answer from the text.`
|
|
321
|
-
: `Unknown document_id ${id}. Use the document_id of an attached PDF.`);
|
|
601
|
+
: `Unknown document_id ${shownId(id)}. Use the document_id of an attached PDF.`);
|
|
322
602
|
}
|
|
323
603
|
const document = await options.load(id);
|
|
324
604
|
if (!document)
|
|
@@ -367,15 +647,15 @@ export function createDocumentTools(options) {
|
|
|
367
647
|
}
|
|
368
648
|
// What a tool could not do goes to the model, and from there to a user's screen: never a server path.
|
|
369
649
|
const failure = (error) => ({ error: safeErrorMessage(error) });
|
|
370
|
-
async function execute(name, args) {
|
|
650
|
+
async function execute(name, args, limits = {}, hooks = {}) {
|
|
371
651
|
if (!known.has(name))
|
|
372
|
-
return { error: `Unknown tool ${name}.` };
|
|
652
|
+
return { error: `Unknown tool ${unknownToolName(name)}.` };
|
|
373
653
|
// The pages are a file, and this method returns only JSON. Saying that pages are attached
|
|
374
654
|
// with nothing attached would be worse than saying that they could not be shown.
|
|
375
655
|
if (name === TOOL_NAMES.view)
|
|
376
656
|
return { error: FILES_NOT_DELIVERED };
|
|
377
657
|
try {
|
|
378
|
-
return await handlers[name](args);
|
|
658
|
+
return await handlers[name](args, limits, hooks);
|
|
379
659
|
}
|
|
380
660
|
catch (error) {
|
|
381
661
|
if (options.signal?.aborted)
|
|
@@ -386,10 +666,11 @@ export function createDocumentTools(options) {
|
|
|
386
666
|
return {
|
|
387
667
|
declarations,
|
|
388
668
|
has: (name) => known.has(name),
|
|
389
|
-
execute,
|
|
390
|
-
|
|
669
|
+
execute: (name, args) => execute(name, args),
|
|
670
|
+
resultCharacters: (name) => (name === TOOL_NAMES.analyze ? Math.max(cap, ANALYSIS_RESULT_CHARACTERS) : name === TOOL_NAMES.view ? LEAST_RESULT_CHARACTERS : cap),
|
|
671
|
+
async executeWithFiles(name, args, limits = {}, hooks = {}) {
|
|
391
672
|
if (name !== TOOL_NAMES.view || !known.has(name))
|
|
392
|
-
return { result: await execute(name, args), files: [] };
|
|
673
|
+
return { result: await execute(name, args, limits, hooks), files: [] };
|
|
393
674
|
try {
|
|
394
675
|
return await viewPages(args, limits);
|
|
395
676
|
}
|
|
@@ -410,7 +691,7 @@ export function createDocumentTools(options) {
|
|
|
410
691
|
}
|
|
411
692
|
if (name === TOOL_NAMES.search) {
|
|
412
693
|
const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
|
|
413
|
-
return `Search ${file} (${mode}) for “${String(args.query ?? "")
|
|
694
|
+
return `Search ${file} (${mode}) for “${sliceWhole(String(args.query ?? ""), 80)}”`;
|
|
414
695
|
}
|
|
415
696
|
if (name === TOOL_NAMES.read) {
|
|
416
697
|
const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
|
|
@@ -420,7 +701,7 @@ export function createDocumentTools(options) {
|
|
|
420
701
|
if (name === TOOL_NAMES.overview)
|
|
421
702
|
return `Overview of ${file}`;
|
|
422
703
|
if (name === TOOL_NAMES.analyze)
|
|
423
|
-
return `Read all of ${file} for “${String(args.task ?? "")
|
|
704
|
+
return `Read all of ${file} for “${sliceWhole(String(args.task ?? ""), 100)}”`;
|
|
424
705
|
return name;
|
|
425
706
|
},
|
|
426
707
|
};
|