llm-large-files 0.5.0 → 0.8.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 +1719 -466
- package/README.md +190 -60
- package/dist/analyze.d.ts +8 -1
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +198 -54
- 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 +194 -40
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +63 -7
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +1131 -214
- package/dist/ask.js.map +1 -1
- package/dist/decode.d.ts +19 -0
- package/dist/decode.d.ts.map +1 -0
- package/dist/decode.js +97 -0
- package/dist/decode.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 +59 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +80 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +339 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +163 -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 +9 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +26 -7
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +180 -314
- 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 +117 -66
- 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/endpoints.d.ts +5 -1
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +11 -2
- package/dist/gemini/endpoints.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 +33 -10
- 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/groups.d.ts +54 -0
- package/dist/groups.d.ts.map +1 -0
- package/dist/groups.js +136 -0
- package/dist/groups.js.map +1 -0
- package/dist/html.d.ts +11 -0
- package/dist/html.d.ts.map +1 -0
- package/dist/html.js +1112 -0
- package/dist/html.js.map +1 -0
- 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 +13 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -5
- 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 +449 -93
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +2 -1
- package/dist/limiter.d.ts.map +1 -1
- package/dist/limiter.js +3 -2
- package/dist/limiter.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 +190 -2
- 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 +184 -28
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +4 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +38 -0
- package/dist/node/ingest-child.d.ts.map +1 -0
- package/dist/node/ingest-child.js +42 -0
- package/dist/node/ingest-child.js.map +1 -0
- package/dist/node/isolated.d.ts +88 -0
- package/dist/node/isolated.d.ts.map +1 -0
- package/dist/node/isolated.js +381 -0
- package/dist/node/isolated.js.map +1 -0
- 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/office.d.ts +105 -0
- package/dist/office.d.ts.map +1 -0
- package/dist/office.js +1092 -0
- package/dist/office.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 +325 -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 +277 -20
- 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/peers.d.ts +8 -0
- package/dist/peers.d.ts.map +1 -0
- package/dist/peers.js +32 -0
- package/dist/peers.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/ranged.d.ts.map +1 -1
- package/dist/ranged.js +4 -2
- package/dist/ranged.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 +107 -24
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +803 -149
- 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 +9 -1
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +28 -9
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +87 -3
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +526 -24
- 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 +461 -46
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +103 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/word-styles.d.ts +102 -0
- package/dist/word-styles.d.ts.map +1 -0
- package/dist/word-styles.js +419 -0
- package/dist/word-styles.js.map +1 -0
- package/dist/xlsx.d.ts +23 -0
- package/dist/xlsx.d.ts.map +1 -0
- package/dist/xlsx.js +511 -0
- package/dist/xlsx.js.map +1 -0
- package/dist/xml-stream.d.ts +55 -0
- package/dist/xml-stream.d.ts.map +1 -0
- package/dist/xml-stream.js +235 -0
- package/dist/xml-stream.js.map +1 -0
- 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 +728 -0
- package/docs/guides/deployment.md +720 -0
- package/docs/guides/errors-and-reliability.md +748 -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 +1024 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1203 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1590 -0
- package/docs/how-it-works.md +1035 -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 +910 -0
- package/docs/reference/errors-and-retries.md +760 -0
- package/docs/reference/events.md +1001 -0
- package/docs/reference/gemini.md +827 -0
- package/docs/reference/library.md +1598 -0
- package/docs/reference/node.md +706 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +1031 -0
- package/docs/security.md +940 -101
- package/docs/troubleshooting.md +1410 -0
- package/package.json +7 -3
- package/src/analyze.ts +204 -49
- package/src/anthropic/adapter.ts +200 -40
- package/src/ask.ts +1151 -210
- package/src/decode.ts +89 -0
- package/src/encoding.ts +850 -0
- package/src/errors.ts +125 -0
- package/src/events.ts +451 -0
- package/src/evidence.ts +11 -2
- package/src/extract.ts +191 -308
- package/src/gemini/adapter.ts +127 -70
- package/src/gemini/chat.ts +28 -4
- package/src/gemini/endpoints.ts +12 -2
- package/src/gemini/errors.ts +34 -1
- package/src/gemini/generate.ts +42 -13
- package/src/gemini/index.ts +3 -3
- package/src/gemini/sse.ts +1 -1
- package/src/groups.ts +162 -0
- package/src/html.ts +1071 -0
- package/src/http.ts +376 -1
- package/src/index.ts +29 -6
- package/src/library.ts +498 -93
- package/src/limiter.ts +6 -1
- package/src/map-reduce.ts +252 -51
- package/src/model.ts +244 -4
- package/src/node/handlers.ts +196 -31
- package/src/node/index.ts +4 -0
- package/src/node/ingest-child.ts +61 -0
- package/src/node/isolated.ts +464 -0
- package/src/node/sse.ts +198 -0
- package/src/office.ts +1047 -0
- package/src/openai/adapter.ts +319 -38
- package/src/output-limit.ts +44 -8
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +270 -20
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/peers.ts +29 -0
- package/src/plan.ts +70 -12
- package/src/ranged.ts +4 -2
- package/src/retry.ts +49 -5
- package/src/search.ts +800 -155
- package/src/sse.ts +153 -28
- package/src/stores.ts +5 -2
- package/src/text-index.ts +30 -9
- package/src/text.ts +524 -23
- package/src/tools.ts +445 -46
- package/src/types.ts +108 -5
- package/src/word-styles.ts +420 -0
- package/src/xlsx.ts +478 -0
- package/src/xml-stream.ts +224 -0
- package/src/zip-directory.ts +136 -0
package/dist/tools.js
CHANGED
|
@@ -1,14 +1,22 @@
|
|
|
1
1
|
import { safeErrorMessage } from "./errors.js";
|
|
2
|
-
import {
|
|
2
|
+
import { GROUP_BY_VALUES, MAX_GROUP_KEYS } from "./groups.js";
|
|
3
|
+
import { analyzeWholeDocument, NothingReadError } from "./map-reduce.js";
|
|
3
4
|
import { cutPdfPages } from "./pdf-pages.js";
|
|
4
5
|
import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS } from "./search.js";
|
|
5
6
|
import { estimateParts, formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
|
|
7
|
+
import { plural, removeInvisible, sliceWhole, wellFormedJson } from "./text.js";
|
|
6
8
|
const DEFAULT_READ_LINES = 200;
|
|
9
|
+
/** Matching lines an exact or regex search shows: the default, and the most a call may ask for. */
|
|
10
|
+
const DEFAULT_GREP_RESULTS = 20;
|
|
11
|
+
const MAX_GREP_RESULTS = 50;
|
|
12
|
+
/** Groups a search with `group_by` shows: the default, and the most a call may ask for. */
|
|
13
|
+
const DEFAULT_GROUPS = 50;
|
|
14
|
+
const MAX_GROUPS = 200;
|
|
7
15
|
const MAX_READ_LINES = 600;
|
|
8
16
|
/** The most pages one `view_pages` call shows. A page costs a model about 530 tokens. */
|
|
9
17
|
export const MAX_VIEW_PAGES = 5;
|
|
10
18
|
/**
|
|
11
|
-
* The time the regex searches of one tool set (one question, in `
|
|
19
|
+
* The time the regex searches of one tool set (one question, in `askWithFiles`) may take together,
|
|
12
20
|
* unless `regexBudgetMs` says otherwise. An ordinary search of a 60 MB log takes about 0.15 s.
|
|
13
21
|
*/
|
|
14
22
|
export const REGEX_BUDGET_MS = 6_000;
|
|
@@ -17,7 +25,7 @@ const MIN_FILE_BYTES = 1_024;
|
|
|
17
25
|
/** The answer of a whole-document read may be this long, when the cap on tool results is lower. */
|
|
18
26
|
const ANALYSIS_RESULT_CHARACTERS = 40_000;
|
|
19
27
|
/** A result is never cut below this, whatever room a caller names: less holds no line of a file. */
|
|
20
|
-
const LEAST_RESULT_CHARACTERS = 600;
|
|
28
|
+
export const LEAST_RESULT_CHARACTERS = 600;
|
|
21
29
|
/**
|
|
22
30
|
* How many times one document is read whole by the tools of one tool set (one question, in
|
|
23
31
|
* `askWithFiles`), unless `maxWholeDocumentReads` says otherwise. One read of a large file is
|
|
@@ -35,16 +43,21 @@ const documentId = { type: "string", description: "The document_id from the file
|
|
|
35
43
|
const DECLARATIONS = {
|
|
36
44
|
search: {
|
|
37
45
|
name: TOOL_NAMES.search,
|
|
38
|
-
description: "Search a large attached file. mode \"keywords\" returns the most relevant passages for a question; \"exact\"
|
|
46
|
+
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 (\\w and \\b know the letters of every language). 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; search again from next_from_line for the ones after those shown, or with order \"last\" for the last ones. To count by group (per hour or day, per error code, per message shape), pass group_by: the result then counts each group, and shows no lines. from_line and to_line search part of the file. Results include line numbers to read further with read_document.",
|
|
39
47
|
parameters: {
|
|
40
48
|
type: "object",
|
|
41
49
|
properties: {
|
|
42
50
|
document_id: documentId,
|
|
43
51
|
query: { type: "string", description: "Keywords, exact text, or a regex, depending on mode." },
|
|
44
52
|
mode: { type: "string", enum: ["keywords", "exact", "regex"], description: "Defaults to keywords." },
|
|
45
|
-
max_results: { type: "integer", description:
|
|
53
|
+
max_results: { type: "integer", description: `Up to ${MAX_GREP_RESULTS} for exact/regex (default ${DEFAULT_GREP_RESULTS}), up to ${MAX_GROUPS} groups with group_by (default ${DEFAULT_GROUPS}), up to 10 passages for keywords (default 5).` },
|
|
46
54
|
context_lines: { type: "integer", description: "exact/regex only: lines to show before and after each match, 0-5." },
|
|
47
55
|
case_sensitive: { type: "boolean", description: "exact/regex only. Defaults to false." },
|
|
56
|
+
from_line: { type: "integer", description: "Search only from this line on (1-based). Pass a result's next_from_line to see the matches after those it shows." },
|
|
57
|
+
to_line: { type: "integer", description: "Search only up to this line." },
|
|
58
|
+
order: { type: "string", enum: ["first", "last"], description: "exact/regex only: \"last\" shows the last max_results matching lines (in file order) instead of the first. Defaults to \"first\"." },
|
|
59
|
+
group_by: { type: "string", enum: [...GROUP_BY_VALUES], description: "exact/regex only: count the matching lines by group instead of showing them. \"capture\": by the text of the regex's first (group); \"minute\", \"hour\", \"day\": by the timestamp on the line; \"shape\": by the line with its numbers, IDs and quoted values taken out." },
|
|
60
|
+
whole_word: { type: "boolean", description: "exact only: match the text only as a whole word, not inside a longer one. Defaults to false." },
|
|
48
61
|
},
|
|
49
62
|
required: ["document_id", "query"],
|
|
50
63
|
},
|
|
@@ -69,7 +82,7 @@ const DECLARATIONS = {
|
|
|
69
82
|
},
|
|
70
83
|
analyze: {
|
|
71
84
|
name: TOOL_NAMES.analyze,
|
|
72
|
-
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
|
|
85
|
+
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.",
|
|
73
86
|
parameters: {
|
|
74
87
|
type: "object",
|
|
75
88
|
properties: {
|
|
@@ -100,6 +113,16 @@ function integer(value, fallback, min, max) {
|
|
|
100
113
|
// The fallback is clamped too: a default end line must not point past the end of the file.
|
|
101
114
|
return Math.min(max, Math.max(min, Math.trunc(Number.isFinite(number) ? number : fallback)));
|
|
102
115
|
}
|
|
116
|
+
/**
|
|
117
|
+
* A boolean given by the model: on for `true`, and for "true" (in any case) or 1, as a number or as
|
|
118
|
+
* text. A model sometimes sends a boolean as text, as it does numbers; read as off, "true" gave
|
|
119
|
+
* another search than true without a word about it. Anything else is off.
|
|
120
|
+
*/
|
|
121
|
+
function flag(value) {
|
|
122
|
+
if (value === true || value === 1)
|
|
123
|
+
return true;
|
|
124
|
+
return typeof value === "string" && /^\s*(?:true|1)\s*$/i.test(value);
|
|
125
|
+
}
|
|
103
126
|
const INCOMPLETE_ANALYSIS = "Incomplete: the model's output limit was reached, so some relevant items are missing from this answer. Tell the user it is incomplete. For a complete list or an exact count, use search_document in exact or regex mode (it returns total_matching_lines), or ask about a narrower part of the file.";
|
|
104
127
|
function text(value, name) {
|
|
105
128
|
if (typeof value !== "string" || !value.trim())
|
|
@@ -114,14 +137,18 @@ function pageNumber(value, name) {
|
|
|
114
137
|
return Math.trunc(number);
|
|
115
138
|
}
|
|
116
139
|
const pageRange = (from, to) => (to > from ? `${from}-${to}` : String(from));
|
|
117
|
-
/**
|
|
140
|
+
/**
|
|
141
|
+
* Trims a result to the character budget by dropping trailing list entries, then cutting text. A
|
|
142
|
+
* note the result already has (a search that stopped early) is kept, before the one that says so.
|
|
143
|
+
*/
|
|
118
144
|
function fit(result, listKey, limit) {
|
|
119
145
|
if (JSON.stringify(result).length <= limit)
|
|
120
146
|
return result;
|
|
121
147
|
const list = listKey ? result[listKey] : undefined;
|
|
122
148
|
if (Array.isArray(list)) {
|
|
123
149
|
const kept = [...list];
|
|
124
|
-
const
|
|
150
|
+
const before = typeof result.note === "string" ? `${result.note} ` : "";
|
|
151
|
+
const note = () => `${before}Showing ${kept.length} of ${list.length} results to stay within the size limit. Narrow the query or read specific lines.`;
|
|
125
152
|
const trimmed = () => ({ ...result, [listKey]: kept, note: note() });
|
|
126
153
|
while (kept.length > 1 && JSON.stringify(trimmed()).length > limit)
|
|
127
154
|
kept.pop();
|
|
@@ -134,10 +161,300 @@ function fit(result, listKey, limit) {
|
|
|
134
161
|
let cut;
|
|
135
162
|
do {
|
|
136
163
|
size = Math.floor(size * 0.85);
|
|
137
|
-
cut = { truncated: true, partial: serialized
|
|
164
|
+
cut = { truncated: true, partial: sliceWhole(serialized, size), note: "Result cut to the size limit. Ask for a smaller range." };
|
|
138
165
|
} while (JSON.stringify(cut).length > limit && size > 100);
|
|
139
166
|
return cut;
|
|
140
167
|
}
|
|
168
|
+
/**
|
|
169
|
+
* The result of a whole-document read within `limit` characters: its answer is cut at the end,
|
|
170
|
+
* and says so, rather than the result being cut as JSON, which loses what the other fields say.
|
|
171
|
+
*/
|
|
172
|
+
export function fitAnswer(result, limit) {
|
|
173
|
+
if (JSON.stringify(result).length <= limit || typeof result.answer !== "string")
|
|
174
|
+
return fit(result, null, limit);
|
|
175
|
+
const answer = result.answer;
|
|
176
|
+
const cutAt = (keep) => ({
|
|
177
|
+
...result,
|
|
178
|
+
answer: `${sliceWhole(answer, keep)}…`,
|
|
179
|
+
answer_shortened: "The rest of this answer did not fit in the room left in this conversation.",
|
|
180
|
+
});
|
|
181
|
+
// The longest start of the answer that fits. Escapes (quotes, line breaks) make the JSON longer
|
|
182
|
+
// than the text by as much as the text holds of them, so it is found by halving, not worked out.
|
|
183
|
+
let low = 0;
|
|
184
|
+
let high = answer.length;
|
|
185
|
+
while (low < high) {
|
|
186
|
+
const middle = Math.ceil((low + high) / 2);
|
|
187
|
+
if (JSON.stringify(cutAt(middle)).length <= limit)
|
|
188
|
+
low = middle;
|
|
189
|
+
else
|
|
190
|
+
high = middle - 1;
|
|
191
|
+
}
|
|
192
|
+
return fit(cutAt(low), null, limit);
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* The result of an exact or regex search that read the whole file: the first matches, then the
|
|
196
|
+
* last one of the file, and a note that says how many of how many are shown when that is not all.
|
|
197
|
+
* Without the last one, a model asked when something last happened named the last line it was
|
|
198
|
+
* shown. To fit `limit`, matches are dropped from the end of the first ones: the last one stays.
|
|
199
|
+
*/
|
|
200
|
+
function firstAndLastMatches(base, first, last, total, limit) {
|
|
201
|
+
const which = (kept) => (kept === 0 ? `the last (line ${last.line})` : `the first${kept > 1 ? ` ${kept}` : ""} and the last (line ${last.line})`);
|
|
202
|
+
const shown = (kept) => `${kept + 1} of the ${total} matching lines`;
|
|
203
|
+
// Where a search for the ones in between goes on: after the last of the first ones shown.
|
|
204
|
+
const next = (kept) => (kept > 0 ? first[kept - 1].line + 1 : undefined);
|
|
205
|
+
const between = (kept) => (next(kept) !== undefined ? `To see the ones in between, search again with from_line ${next(kept)}, or count them with group_by.` : "Narrow the query or read specific lines.");
|
|
206
|
+
const withFirst = (kept, cut) => ({
|
|
207
|
+
...base,
|
|
208
|
+
...(cut
|
|
209
|
+
? { note: `Showing ${shown(kept)} to stay within the size limit: ${which(kept)}. ${between(kept)}` }
|
|
210
|
+
// When every match is shown, there is nothing to say.
|
|
211
|
+
: kept + 1 < total ? { note: `${shown(kept)} are shown: ${which(kept)}. ${between(kept)}` } : {}),
|
|
212
|
+
...(kept + 1 < total && next(kept) !== undefined ? { next_from_line: next(kept) } : {}),
|
|
213
|
+
matches: [...first.slice(0, kept), last],
|
|
214
|
+
});
|
|
215
|
+
const whole = withFirst(first.length, false);
|
|
216
|
+
if (JSON.stringify(whole).length <= limit)
|
|
217
|
+
return whole;
|
|
218
|
+
let kept = first.length;
|
|
219
|
+
while (kept > 0 && JSON.stringify(withFirst(kept, true)).length > limit)
|
|
220
|
+
kept--;
|
|
221
|
+
const cut = withFirst(kept, true);
|
|
222
|
+
if (JSON.stringify(cut).length <= limit)
|
|
223
|
+
return cut;
|
|
224
|
+
// Only the last match is left, and its note is too long for the room: a shorter one. It still
|
|
225
|
+
// starts with "Showing ", so the result is taken as cut. `fit` must not put its own note in its
|
|
226
|
+
// place, which would say "1 of 1 results" and drop the line of the last match. When even this
|
|
227
|
+
// does not fit, `fit` cuts the result as text: the note, with that line, comes before the match.
|
|
228
|
+
const lastOnly = { ...base, note: `Showing 1 of the ${total} matching lines: ${which(0)}. Narrow the search.`, matches: [last] };
|
|
229
|
+
return fit(lastOnly, null, limit);
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* The result of a search with `order: "last"`: the last matching lines, in the order of the file,
|
|
233
|
+
* with a note that says so, and on which line the first match is. To fit `limit`, the earliest of
|
|
234
|
+
* them are dropped first: the very last stays. `stopped` is given when the scan stopped early: the
|
|
235
|
+
* last line of the lines searched, and the `to_line` of the call, which a search for the lines after
|
|
236
|
+
* those it found keeps.
|
|
237
|
+
*/
|
|
238
|
+
function lastMatches(base, first, last, total, limit, stopped) {
|
|
239
|
+
const build = (kept, cut) => {
|
|
240
|
+
const shown = last.slice(last.length - kept);
|
|
241
|
+
const end = shown.at(-1)?.line;
|
|
242
|
+
// A scan that stopped early found these last: the lines after them were not all looked at. Its
|
|
243
|
+
// note starts as those of the other searches that stopped early do, which `alreadyShown` looks
|
|
244
|
+
// for: a later question has time of its own, and the call made then is run, not pointed back to.
|
|
245
|
+
if (stopped) {
|
|
246
|
+
// Nothing found means out of time (an exact search stops only past its limit on matches). It
|
|
247
|
+
// is not known where the scan stopped, so no line is named to search from.
|
|
248
|
+
if (end === undefined) {
|
|
249
|
+
return { ...base, note: "The scan stopped early, out of time, before it found a matching line: the lines it did not reach may have some. Try a simpler pattern, mode \"exact\", or fewer lines with from_line and to_line.", matches: shown };
|
|
250
|
+
}
|
|
251
|
+
const lines = `${shown.length} ${plural(shown.length, "matching line")}`;
|
|
252
|
+
const which = cut ? `Showing the last ${lines} it found to stay within the size limit` : `These are the last ${lines} it found`;
|
|
253
|
+
// The search goes on after the last line found, in the same range. When that line is the last
|
|
254
|
+
// of the range, the scan stopped there and missed none of it: there is nothing to search on.
|
|
255
|
+
const later = end < stopped.end
|
|
256
|
+
? ` There may be later ones, after line ${end}: search again with from_line ${end + 1}${stopped.toLine !== undefined ? ` and to_line ${stopped.toLine}` : ""}.`
|
|
257
|
+
: "";
|
|
258
|
+
return { ...base, note: `The scan stopped early; the total is a lower bound. ${which}, in the order of the file.${later}`, matches: shown };
|
|
259
|
+
}
|
|
260
|
+
const note = shown.length < total
|
|
261
|
+
// A cut result's note starts with "Showing ", as `alreadyShown` looks for: a call made later may have more room.
|
|
262
|
+
? cut
|
|
263
|
+
? `Showing the last ${shown.length} of the ${total} matching lines to stay within the size limit, in the order of the file: the last match is on line ${end}${first ? `, and the first on line ${first.line}` : ""}. Narrow the query or read specific lines.`
|
|
264
|
+
: `These are the last ${shown.length} of the ${total} matching lines, in the order of the file: the last match is on line ${end}${first ? `, and the first on line ${first.line}` : ""}.`
|
|
265
|
+
: undefined;
|
|
266
|
+
return { ...base, ...(note ? { note: typeof base.note === "string" ? `${base.note} ${note}` : note } : {}), matches: shown };
|
|
267
|
+
};
|
|
268
|
+
const whole = build(last.length, false);
|
|
269
|
+
if (JSON.stringify(whole).length <= limit)
|
|
270
|
+
return whole;
|
|
271
|
+
let kept = last.length;
|
|
272
|
+
while (kept > 1 && JSON.stringify(build(kept, true)).length > limit)
|
|
273
|
+
kept--;
|
|
274
|
+
return fit(build(kept, true), null, limit);
|
|
275
|
+
}
|
|
276
|
+
/** The result of a search with `group_by`: the total, then up to `shown` groups, cut further to fit `limit`. */
|
|
277
|
+
function groupedResult(base, counted, shown, limit) {
|
|
278
|
+
const byTime = base.group_by === "minute" || base.group_by === "hour" || base.group_by === "day";
|
|
279
|
+
const all = counted.groups.map(({ key, count, firstLine, lastLine }) => ({ key, count, first_line: firstLine, last_line: lastLine }));
|
|
280
|
+
// By time, the groups shown are the largest, put back in time order; so are those kept when the
|
|
281
|
+
// result is cut to its room. Cutting the end of the list there kept the earliest groups, while the
|
|
282
|
+
// note said the largest, and a model named the wrong hour as the busiest. The sort is stable: of
|
|
283
|
+
// groups of the same size, the earlier comes first.
|
|
284
|
+
const largest = byTime ? [...all].sort((left, right) => right.count - left.count) : all;
|
|
285
|
+
const pick = (kept) => (byTime ? largest.slice(0, kept).sort((left, right) => left.first_line - right.first_line) : all.slice(0, kept));
|
|
286
|
+
const most = Math.min(shown, all.length);
|
|
287
|
+
const extra = {
|
|
288
|
+
total_groups: counted.totalGroups,
|
|
289
|
+
...(counted.otherCount > 0 ? { other_count: counted.otherCount, other_note: `Lines of groups past the first ${MAX_GROUP_KEYS.toLocaleString("en-US")} found.` } : {}),
|
|
290
|
+
...(counted.ungrouped > 0 ? { lines_without_group: counted.ungrouped } : {}),
|
|
291
|
+
};
|
|
292
|
+
const build = (kept, cut) => {
|
|
293
|
+
const groups = pick(kept);
|
|
294
|
+
const order = byTime ? (groups.length < all.length ? "the largest, in time order" : "in time order") : "the largest first";
|
|
295
|
+
const note = groups.length < counted.totalGroups ? `${cut ? "Showing " : ""}${groups.length} of the ${counted.totalGroups} groups${cut ? " to stay within the size limit" : " are shown"}, ${order}. Narrow the search, or use from_line and to_line, for the others.` : undefined;
|
|
296
|
+
return { ...base, ...extra, ...(note ? { note: typeof base.note === "string" ? `${base.note} ${note}` : note } : {}), groups };
|
|
297
|
+
};
|
|
298
|
+
const whole = build(most, false);
|
|
299
|
+
if (JSON.stringify(whole).length <= limit)
|
|
300
|
+
return whole;
|
|
301
|
+
let kept = most;
|
|
302
|
+
while (kept > 1 && JSON.stringify(build(kept, true)).length > limit)
|
|
303
|
+
kept--;
|
|
304
|
+
return fit(build(kept, true), null, limit);
|
|
305
|
+
}
|
|
306
|
+
const searchMode = (mode) => (mode === "exact" || mode === "regex" ? mode : "keywords");
|
|
307
|
+
/** `group_by` as the search reads it: undefined when not given. A value it does not know is an error. */
|
|
308
|
+
function groupByOf(value) {
|
|
309
|
+
if (value === undefined || value === null || value === "" || value === "none")
|
|
310
|
+
return undefined;
|
|
311
|
+
if (typeof value === "string" && GROUP_BY_VALUES.includes(value))
|
|
312
|
+
return value;
|
|
313
|
+
throw new Error(`group_by must be one of ${GROUP_BY_VALUES.map((name) => `"${name}"`).join(", ")}.`);
|
|
314
|
+
}
|
|
315
|
+
/** A line number of a search's range, as the search reads it: undefined when not given. */
|
|
316
|
+
const rangeLine = (value) => (value === undefined || value === null || value === "" ? undefined : integer(value, 1, 1, Number.MAX_SAFE_INTEGER));
|
|
317
|
+
/**
|
|
318
|
+
* The arguments of a search that choose which lines it looks at and how it shows them, as the
|
|
319
|
+
* search reads them. The search, its key and its label all read them here, so that they agree.
|
|
320
|
+
*/
|
|
321
|
+
function searchScope(args) {
|
|
322
|
+
const fromLine = rangeLine(args.from_line);
|
|
323
|
+
const toLine = rangeLine(args.to_line);
|
|
324
|
+
let groupBy;
|
|
325
|
+
try {
|
|
326
|
+
groupBy = groupByOf(args.group_by);
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
groupBy = undefined;
|
|
330
|
+
}
|
|
331
|
+
return {
|
|
332
|
+
...(fromLine !== undefined ? { fromLine } : {}),
|
|
333
|
+
...(toLine !== undefined ? { toLine } : {}),
|
|
334
|
+
order: args.order === "last" ? "last" : "first",
|
|
335
|
+
...(groupBy ? { groupBy } : {}),
|
|
336
|
+
wholeWord: flag(args.whole_word),
|
|
337
|
+
caseSensitive: flag(args.case_sensitive),
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
/** The lines a `read_document` call asks for, as its handler reads them, before the end of the file is known. */
|
|
341
|
+
function requestedLines(args) {
|
|
342
|
+
const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
|
|
343
|
+
return [start, integer(args.end_line, start + DEFAULT_READ_LINES - 1, start, start + MAX_READ_LINES - 1)];
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* A call's arguments as its tool reads them, with the defaults filled in: two calls with the same
|
|
347
|
+
* key get the same result from a file that has not changed. Undefined for a tool whose calls are
|
|
348
|
+
* not compared (a whole-file read has a count of its own; a look at pages returns a file).
|
|
349
|
+
*/
|
|
350
|
+
export function toolCallKey(name, args) {
|
|
351
|
+
const id = typeof args.document_id === "string" && args.document_id ? args.document_id : undefined;
|
|
352
|
+
if (!id)
|
|
353
|
+
return undefined;
|
|
354
|
+
if (name === TOOL_NAMES.search) {
|
|
355
|
+
if (typeof args.query !== "string" || !args.query.trim())
|
|
356
|
+
return undefined;
|
|
357
|
+
const mode = searchMode(args.mode);
|
|
358
|
+
// A group_by the search refuses: the call answers with an error, and is not compared.
|
|
359
|
+
try {
|
|
360
|
+
groupByOf(args.group_by);
|
|
361
|
+
}
|
|
362
|
+
catch {
|
|
363
|
+
return undefined;
|
|
364
|
+
}
|
|
365
|
+
const { fromLine, toLine, order, groupBy, wholeWord, caseSensitive } = searchScope(args);
|
|
366
|
+
// The arguments of 0.8.0 are added only when given: a call without them has the key it had.
|
|
367
|
+
const scope = [
|
|
368
|
+
...(fromLine !== undefined || toLine !== undefined ? [fromLine ?? 1, toLine ?? null] : []),
|
|
369
|
+
...(mode !== "keywords" && (order === "last" || groupBy || wholeWord) ? [order, groupBy ?? null, mode === "exact" && wholeWord] : []),
|
|
370
|
+
];
|
|
371
|
+
return JSON.stringify(mode === "keywords"
|
|
372
|
+
? [name, id, args.query, mode, integer(args.max_results, 5, 1, 10), ...scope]
|
|
373
|
+
: [name, id, args.query, mode, groupBy ? integer(args.max_results, DEFAULT_GROUPS, 1, MAX_GROUPS) : integer(args.max_results, DEFAULT_GREP_RESULTS, 1, MAX_GREP_RESULTS), groupBy ? 0 : integer(args.context_lines, 0, 0, 5), caseSensitive, ...scope]);
|
|
374
|
+
}
|
|
375
|
+
if (name === TOOL_NAMES.read)
|
|
376
|
+
return JSON.stringify([name, id, ...requestedLines(args)]);
|
|
377
|
+
if (name === TOOL_NAMES.overview)
|
|
378
|
+
return JSON.stringify([name, id]);
|
|
379
|
+
return undefined;
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* When an earlier call's result already holds all that `call` would return, and is still in the
|
|
383
|
+
* conversation in full: a short result that says so, in place of running the call again. A result
|
|
384
|
+
* that was cut to the room it had, or replaced by a stand-in, or failed, is not pointed to: the call
|
|
385
|
+
* is run, and may get more. A read of lines inside a read that is shown in full is pointed to.
|
|
386
|
+
* `stored` is true for a result in the tool rounds of an earlier question, which an older version
|
|
387
|
+
* may have written: 0.5.0 cut the text of a read of one long line without saying so (no
|
|
388
|
+
* `text_cut`), so a read of one line from there is not taken as shown in full.
|
|
389
|
+
*/
|
|
390
|
+
export function alreadyShown(call, earlier, stored = false) {
|
|
391
|
+
const { result } = earlier;
|
|
392
|
+
if (earlier.call.name !== call.name || earlier.call.args.document_id !== call.args.document_id)
|
|
393
|
+
return undefined;
|
|
394
|
+
if (result.dropped === true || result.already_shown === true || typeof result.error === "string" || result.truncated === true)
|
|
395
|
+
return undefined;
|
|
396
|
+
// A search stored by 0.7.0 with case_sensitive or whole_word as text or 1 ("true", 1): 0.7.0 read
|
|
397
|
+
// those as off, 0.8.0 as on, so the call made now would not return what was stored.
|
|
398
|
+
if (stored && call.name === TOOL_NAMES.search && [earlier.call.args.case_sensitive, earlier.call.args.whole_word].some((value) => value !== undefined && value !== true && value !== false && flag(value)))
|
|
399
|
+
return undefined;
|
|
400
|
+
// A list that `fit` cut to the room it had, a read whose text was cut, or a search that ran out of
|
|
401
|
+
// time ("the total is a lower bound"; a later question has time of its own): a call made now may get more.
|
|
402
|
+
if (typeof result.note === "string" && (result.note.startsWith("Showing ") || result.note.startsWith("The scan stopped early")))
|
|
403
|
+
return undefined;
|
|
404
|
+
if (result.text_cut === true)
|
|
405
|
+
return undefined;
|
|
406
|
+
// An exact or regex search that an earlier version stored: the first matches, without the last one
|
|
407
|
+
// and without a note. Run now, the call returns more (the last match), not the same.
|
|
408
|
+
if (call.name === TOOL_NAMES.search && typeof result.total_matching_lines === "number" && Array.isArray(result.matches)
|
|
409
|
+
&& result.matches.length < result.total_matching_lines && typeof result.note !== "string")
|
|
410
|
+
return undefined;
|
|
411
|
+
const document = typeof result.document === "string" ? { document: result.document } : {};
|
|
412
|
+
if (call.name === TOOL_NAMES.read) {
|
|
413
|
+
const shown = typeof result.lines === "string" ? /^(\d+)-(\d+)$/.exec(result.lines) : null;
|
|
414
|
+
const total = result.total_lines;
|
|
415
|
+
if (!shown || typeof total !== "number")
|
|
416
|
+
return undefined;
|
|
417
|
+
const [first, last] = [Number(shown[1]), Number(shown[2])];
|
|
418
|
+
if (stored && first === last)
|
|
419
|
+
return undefined;
|
|
420
|
+
const [start, end] = requestedLines(call.args);
|
|
421
|
+
const from = Math.min(start, total);
|
|
422
|
+
const to = Math.min(end, total);
|
|
423
|
+
if (from < first || to > last)
|
|
424
|
+
return undefined;
|
|
425
|
+
return {
|
|
426
|
+
...document,
|
|
427
|
+
lines: `${from}-${to}`,
|
|
428
|
+
already_shown: true,
|
|
429
|
+
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.`,
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
const key = toolCallKey(call.name, call.args);
|
|
433
|
+
if (key === undefined || key !== toolCallKey(earlier.call.name, earlier.call.args))
|
|
434
|
+
return undefined;
|
|
435
|
+
return {
|
|
436
|
+
...document,
|
|
437
|
+
already_shown: true,
|
|
438
|
+
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.",
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* A hint added to the error of a search that failed twice in a row in the same mode, so that the
|
|
443
|
+
* model tries another way instead of sending the same kind of call a third time.
|
|
444
|
+
*/
|
|
445
|
+
export function repeatedFailureHint(call) {
|
|
446
|
+
return searchMode(call.args.mode) === "regex"
|
|
447
|
+
? "Two regex searches in a row failed. Try mode \"exact\" with a plain word or ID from the file, or mode \"keywords\"."
|
|
448
|
+
: "This search failed twice in a row. Check the arguments against the tool's description, or answer from what you have.";
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* The tool and mode of a search, to tell whether two failures in a row were of the same kind.
|
|
452
|
+
* Undefined for the other tools: their errors say what to do (a whole-file read that is not made
|
|
453
|
+
* again, a page that does not exist), and a hint would only blur that.
|
|
454
|
+
*/
|
|
455
|
+
export function failureKind(call) {
|
|
456
|
+
return call.name === TOOL_NAMES.search ? `${call.name}|${searchMode(call.args.mode)}` : undefined;
|
|
457
|
+
}
|
|
141
458
|
/**
|
|
142
459
|
* What a finished tool call found, as a suffix for its `describe()` label, for a steps list:
|
|
143
460
|
* "Search app.log (exact) for “timeout”" + " — 12 matching lines".
|
|
@@ -145,13 +462,15 @@ function fit(result, listKey, limit) {
|
|
|
145
462
|
export function toolResultSummary(label, result) {
|
|
146
463
|
if (typeof result.error === "string")
|
|
147
464
|
return ` — failed: ${result.error}`;
|
|
148
|
-
if (typeof result.total_matching_lines === "number")
|
|
149
|
-
|
|
465
|
+
if (typeof result.total_matching_lines === "number") {
|
|
466
|
+
const groups = typeof result.total_groups === "number" ? ` in ${result.total_groups.toLocaleString("en-US")} ${plural(result.total_groups, "group")}` : "";
|
|
467
|
+
return ` — ${result.total_matching_lines.toLocaleString("en-US")} ${plural(result.total_matching_lines, "matching line")}${groups}`;
|
|
468
|
+
}
|
|
150
469
|
if (Array.isArray(result.passages))
|
|
151
|
-
return ` — ${result.passages.length} passages`;
|
|
470
|
+
return ` — ${result.passages.length} ${plural(result.passages.length, "passage")}`;
|
|
152
471
|
if (typeof result.parts_read === "number") {
|
|
153
|
-
const incomplete = result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
|
|
154
|
-
return ` — ${result.parts_read}
|
|
472
|
+
const incomplete = result.notes_only ? ", notes only" : result.notes_cut_short || result.answer_cut_short ? ", incomplete" : "";
|
|
473
|
+
return ` — ${result.parts_read} ${plural(result.parts_read, "part")}, ${String(result.parts_with_relevant_content ?? 0)} relevant${incomplete}`;
|
|
155
474
|
}
|
|
156
475
|
// A read reports its range only when it was cut short of what was asked.
|
|
157
476
|
if (typeof result.lines === "string" && typeof result.total_lines === "number")
|
|
@@ -162,6 +481,28 @@ export function toolResultSummary(label, result) {
|
|
|
162
481
|
}
|
|
163
482
|
return "";
|
|
164
483
|
}
|
|
484
|
+
/**
|
|
485
|
+
* A step, or a label of one, as one line of plain text. Steps quote what the model sent (a query, a
|
|
486
|
+
* task, the name of a tool, arguments that were not JSON), and they reach users' screens: the
|
|
487
|
+
* invisible characters that file text and names lose are dropped (`removeInvisible`: text-direction
|
|
488
|
+
* overrides and isolates, zero-width spaces, tag characters), a line break, a tab or another control
|
|
489
|
+
* character becomes one space with the blanks around it, and "](" gets a space, so that a markdown
|
|
490
|
+
* link or picture in a query stays text. A line without them is unchanged.
|
|
491
|
+
*/
|
|
492
|
+
export function stepLine(text) {
|
|
493
|
+
// Each control character, tab and line break is a "\n" first, which `removeInvisible` keeps (it
|
|
494
|
+
// would drop the others): an invisible character between two of them then leaves one space, not
|
|
495
|
+
// two. A soft hyphen it keeps before one goes too. Then a run of blanks with a "\n" in it is one space.
|
|
496
|
+
const marked = removeInvisible(text.replace(/[\p{Cc}\p{Zl}\p{Zp}]/gu, "\n")).replace(/\xAD+(?=\n)/g, "");
|
|
497
|
+
return marked.replace(/\s+/g, (blank) => (blank.includes("\n") ? " " : blank)).replaceAll("](", "] (");
|
|
498
|
+
}
|
|
499
|
+
/** An unknown tool's name as a step or an error quotes it: the model chose it, at any length. */
|
|
500
|
+
export const unknownToolName = (name) => `“${sliceWhole(name, 64)}”`;
|
|
501
|
+
/**
|
|
502
|
+
* A document_id the model sent, as an error quotes it: whole when it is as long as a real one can
|
|
503
|
+
* be, cut otherwise. The model chose it, at any length, and the error goes into steps too.
|
|
504
|
+
*/
|
|
505
|
+
const shownId = (id) => (id.length > 64 ? `${sliceWhole(id, 64)}…` : id);
|
|
165
506
|
export function createDocumentTools(options) {
|
|
166
507
|
const allowed = new Set(options.documentIds);
|
|
167
508
|
const viewable = new Set(options.loadOriginal ? options.viewableIds ?? [] : []);
|
|
@@ -194,16 +535,29 @@ export function createDocumentTools(options) {
|
|
|
194
535
|
regexQueue = next.catch(() => undefined);
|
|
195
536
|
return next;
|
|
196
537
|
};
|
|
538
|
+
const givenReads = options.maxWholeDocumentReads;
|
|
539
|
+
// NaN failed every comparison, so it let a document be read whole any number of times.
|
|
540
|
+
if (givenReads !== undefined && (typeof givenReads !== "number" || Number.isNaN(givenReads))) {
|
|
541
|
+
const shown = typeof givenReads === "number" ? String(givenReads) : typeof givenReads === "string" ? JSON.stringify(givenReads) : typeof givenReads;
|
|
542
|
+
throw new (typeof givenReads === "number" ? RangeError : TypeError)(`maxWholeDocumentReads must be a number, and is ${shown}.`);
|
|
543
|
+
}
|
|
197
544
|
const maxWholeReads = Math.max(0, Math.trunc(options.maxWholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS));
|
|
198
545
|
/** Whole-document reads started, by document. */
|
|
199
546
|
const wholeReads = new Map();
|
|
547
|
+
/** Why the last whole-document read of a document failed, when no part of it could be read. */
|
|
548
|
+
const failedWholeReads = new Map();
|
|
200
549
|
// When no limit is given with a call: three eighths of a request, so that two looks still fit.
|
|
201
550
|
const defaultFileBytes = Math.floor((options.budget.maxRequestBytes - REQUEST_BYTES_MARGIN) * 3 / 8);
|
|
202
551
|
async function documentFor(args) {
|
|
203
552
|
const id = text(args.document_id, "document_id");
|
|
204
553
|
// Scope check: a model can only reach files attached to this conversation.
|
|
205
|
-
if (!allowed.has(id))
|
|
206
|
-
|
|
554
|
+
if (!allowed.has(id)) {
|
|
555
|
+
// The IDs it may use, with their file names, so that the next call is right.
|
|
556
|
+
const usable = [...allowed].slice(0, 20).map((known) => `${known}${names.has(known) ? ` (${JSON.stringify(names.get(known))})` : ""}`);
|
|
557
|
+
throw new Error(usable.length === 0
|
|
558
|
+
? `Unknown document_id ${shownId(id)}. No attached file is read with this tool in this conversation.`
|
|
559
|
+
: `Unknown document_id ${shownId(id)}. Use one of: ${usable.join(", ")}${allowed.size > 20 ? ", …" : ""}.`);
|
|
560
|
+
}
|
|
207
561
|
const document = await options.load(id);
|
|
208
562
|
if (!document)
|
|
209
563
|
throw new Error(`${id} is no longer available on the server. Ask the user to attach the file again.`);
|
|
@@ -219,13 +573,27 @@ export function createDocumentTools(options) {
|
|
|
219
573
|
// Page numbers are added only for a PDF whose pages can be looked at: they are what
|
|
220
574
|
// view_pages takes. Everything else gets the results of 0.2.0 unchanged.
|
|
221
575
|
const paged = viewable.has(document.meta.id);
|
|
576
|
+
const groupBy = groupByOf(args.group_by);
|
|
577
|
+
const { fromLine, toLine, order, wholeWord, caseSensitive } = searchScope(args);
|
|
578
|
+
const total = document.lineCount;
|
|
579
|
+
if (fromLine !== undefined && fromLine > total)
|
|
580
|
+
throw new Error(`from_line ${fromLine} is past the end of the file, which has ${total} ${plural(total, "line")}.`);
|
|
581
|
+
if (toLine !== undefined && toLine < (fromLine ?? 1))
|
|
582
|
+
throw new Error(`to_line ${toLine} is before from_line ${fromLine ?? 1}.`);
|
|
583
|
+
const ranged = fromLine !== undefined || toLine !== undefined;
|
|
584
|
+
const range = { from: fromLine ?? 1, to: Math.min(total, toLine ?? total) };
|
|
585
|
+
// Said in the result when part of the file was searched: the counts are of those lines.
|
|
586
|
+
const searched = ranged ? { searched_lines: `${range.from}-${range.to}` } : {};
|
|
222
587
|
if (mode === "keywords") {
|
|
588
|
+
if (groupBy)
|
|
589
|
+
throw new Error("group_by counts the lines of an exact or regex search: use mode \"exact\" or \"regex\".");
|
|
223
590
|
const topK = integer(args.max_results, 5, 1, 10);
|
|
224
|
-
const ranked = await rankSource(document, query, topK, options.signal);
|
|
591
|
+
const ranked = await rankSource(document, query, topK, options.signal, ranged ? range : undefined);
|
|
225
592
|
const texts = await Promise.all(ranked.map((passage) => document.readLines(passage.from, passage.to)));
|
|
226
593
|
return fit({
|
|
227
594
|
document: document.meta.name,
|
|
228
595
|
mode,
|
|
596
|
+
...searched,
|
|
229
597
|
passages: ranked.map((passage, index) => {
|
|
230
598
|
const pages = paged ? document.pagesOfLines(passage.from, passage.to) : undefined;
|
|
231
599
|
return {
|
|
@@ -239,6 +607,7 @@ export function createDocumentTools(options) {
|
|
|
239
607
|
}, "passages", limit);
|
|
240
608
|
}
|
|
241
609
|
const regex = mode === "regex";
|
|
610
|
+
const shownGroups = integer(args.max_results, DEFAULT_GROUPS, 1, MAX_GROUPS);
|
|
242
611
|
const grep = async () => {
|
|
243
612
|
const regexLeft = regexBudget - regexClock.usedMs;
|
|
244
613
|
if (regex && regexLeft <= 0) {
|
|
@@ -246,23 +615,46 @@ export function createDocumentTools(options) {
|
|
|
246
615
|
}
|
|
247
616
|
return grepSource(document, query, {
|
|
248
617
|
regex,
|
|
249
|
-
caseSensitive
|
|
250
|
-
maxResults: integer(args.max_results,
|
|
618
|
+
caseSensitive,
|
|
619
|
+
maxResults: integer(args.max_results, DEFAULT_GREP_RESULTS, 1, MAX_GREP_RESULTS),
|
|
251
620
|
contextLines: integer(args.context_lines, 0, 0, 5),
|
|
252
621
|
...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
|
|
253
622
|
...(options.signal ? { signal: options.signal } : {}),
|
|
623
|
+
...(ranged ? { fromLine: range.from, toLine: range.to } : {}),
|
|
624
|
+
...(order === "last" ? { order } : {}),
|
|
625
|
+
...(groupBy ? { groupBy } : {}),
|
|
626
|
+
...(wholeWord && !regex ? { wholeWord } : {}),
|
|
254
627
|
});
|
|
255
628
|
};
|
|
256
629
|
const result = await (regex ? inRegexTurn(grep) : grep());
|
|
630
|
+
const placed = (match) => {
|
|
631
|
+
if (!paged)
|
|
632
|
+
return match;
|
|
633
|
+
const { line, ...rest } = match;
|
|
634
|
+
const page = document.pageOfLine(line);
|
|
635
|
+
return { line, ...(page ? { page } : {}), ...rest };
|
|
636
|
+
};
|
|
637
|
+
const base = { document: document.meta.name, mode, ...searched, total_matching_lines: result.totalMatchingLines };
|
|
638
|
+
const stopped = result.stoppedEarly ? { note: "The scan stopped early; the counts are lower bounds." } : {};
|
|
639
|
+
if (result.groups)
|
|
640
|
+
return groupedResult({ ...base, group_by: groupBy, ...stopped }, result.groups, shownGroups, limit);
|
|
641
|
+
const matches = result.matches.map(placed);
|
|
642
|
+
if (order === "last") {
|
|
643
|
+
// The range a search for the lines after those found goes on in, when the scan stopped early.
|
|
644
|
+
const rest = result.stoppedEarly ? { end: range.to, ...(toLine !== undefined ? { toLine: range.to } : {}) } : undefined;
|
|
645
|
+
return lastMatches({ ...base, order }, result.first ? placed(result.first) : undefined, matches, result.totalMatchingLines, limit, rest);
|
|
646
|
+
}
|
|
647
|
+
if (!result.stoppedEarly && result.totalMatchingLines >= 2) {
|
|
648
|
+
// The last match is `last`, or, when every match is among the first ones, the last of them.
|
|
649
|
+
return result.last
|
|
650
|
+
? firstAndLastMatches(base, matches, placed(result.last), result.totalMatchingLines, limit)
|
|
651
|
+
: firstAndLastMatches(base, matches.slice(0, -1), matches.at(-1), result.totalMatchingLines, limit);
|
|
652
|
+
}
|
|
257
653
|
return fit({
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
matches: paged ? result.matches.map(({ line, ...rest }) => {
|
|
263
|
-
const page = document.pageOfLine(line);
|
|
264
|
-
return { line, ...(page ? { page } : {}), ...rest };
|
|
265
|
-
}) : result.matches,
|
|
654
|
+
...base,
|
|
655
|
+
// The description says the last match is shown: here it is not known.
|
|
656
|
+
...(result.stoppedEarly ? { note: "The scan stopped early; the total is a lower bound, and the last match in the file is not known." } : {}),
|
|
657
|
+
matches,
|
|
266
658
|
}, "matches", limit);
|
|
267
659
|
},
|
|
268
660
|
async [TOOL_NAMES.read](args, limits) {
|
|
@@ -287,7 +679,9 @@ export function createDocumentTools(options) {
|
|
|
287
679
|
lines: `${start}-${to}`,
|
|
288
680
|
...(pages ? { pages } : {}),
|
|
289
681
|
total_lines: total,
|
|
290
|
-
text: fits(body) ? body : body
|
|
682
|
+
text: fits(body) ? body : sliceWhole(body, Math.floor((limit - 500) / 2)),
|
|
683
|
+
// One line longer than the room: its text was cut, so the lines are not all shown.
|
|
684
|
+
...(fits(body) ? {} : { text_cut: true }),
|
|
291
685
|
...(to < total ? { next_start_line: to + 1 } : { note: "End of file." }),
|
|
292
686
|
};
|
|
293
687
|
},
|
|
@@ -310,13 +704,14 @@ export function createDocumentTools(options) {
|
|
|
310
704
|
...(meta.pages ? { pages: meta.pages } : {}),
|
|
311
705
|
parts_for_whole_document_analysis: parts,
|
|
312
706
|
...(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.` } : {}),
|
|
313
|
-
|
|
707
|
+
// 0.5.0 stored some log templates cut inside an emoji: half of a character is not sent.
|
|
708
|
+
...(meta.logProfile ? { log_profile: wellFormedJson(meta.logProfile) } : {}),
|
|
314
709
|
first_lines: numberLines(await document.readLines(1, first), 1),
|
|
315
710
|
last_lines: lineCount > 30 ? numberLines(await document.readLines(tail, lineCount), tail) : "",
|
|
316
711
|
outline: meta.outline.length ? outlineLines(meta.outline) : [],
|
|
317
712
|
}, "outline", limit);
|
|
318
713
|
},
|
|
319
|
-
async [TOOL_NAMES.analyze](args, limits) {
|
|
714
|
+
async [TOOL_NAMES.analyze](args, limits, hooks) {
|
|
320
715
|
if (!options.generate)
|
|
321
716
|
throw new Error("Whole-document analysis is not enabled.");
|
|
322
717
|
const document = await documentFor(args);
|
|
@@ -327,9 +722,13 @@ export function createDocumentTools(options) {
|
|
|
327
722
|
const id = document.meta.id;
|
|
328
723
|
const reads = wholeReads.get(id) ?? 0;
|
|
329
724
|
if (reads >= maxWholeReads) {
|
|
725
|
+
const failure = failedWholeReads.get(id);
|
|
330
726
|
throw new Error(maxWholeReads === 0
|
|
331
727
|
? `Whole-file reads are turned off for this question. Use search_document and read_document on ${document.meta.name}.`
|
|
332
|
-
:
|
|
728
|
+
: failure !== undefined
|
|
729
|
+
// There is no answer to use: saying "use the answer of that read" would invite one made up.
|
|
730
|
+
? `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.`
|
|
731
|
+
: `${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.`);
|
|
333
732
|
}
|
|
334
733
|
wholeReads.set(id, reads + 1);
|
|
335
734
|
let result;
|
|
@@ -339,28 +738,41 @@ export function createDocumentTools(options) {
|
|
|
339
738
|
task,
|
|
340
739
|
generate: options.generate,
|
|
341
740
|
budget: options.budget,
|
|
342
|
-
|
|
741
|
+
// The call's own listener, when it has one, in place of the tool set's.
|
|
742
|
+
onProgress: hooks.onProgress ?? options.onProgress,
|
|
743
|
+
...(hooks.onRequest ? { onRequest: hooks.onRequest } : {}),
|
|
343
744
|
signal: options.signal,
|
|
344
745
|
...(options.retry ? { retry: options.retry } : {}),
|
|
746
|
+
...(typeof limits.maxRequests === "number" && Number.isFinite(limits.maxRequests) ? { maxRequests: limits.maxRequests } : {}),
|
|
345
747
|
});
|
|
346
748
|
}
|
|
347
749
|
catch (error) {
|
|
348
|
-
//
|
|
349
|
-
|
|
350
|
-
|
|
750
|
+
// Parts were sent and none could be read: that read is counted, since another would most
|
|
751
|
+
// likely fail the same way. Anything else (too many parts, a store that could not be read)
|
|
752
|
+
// failed before any model request: that was no read. Its count is given back, not set to
|
|
753
|
+
// what it was when the read started, which would take back the count of another read of
|
|
754
|
+
// the same document running in this turn.
|
|
755
|
+
if (error instanceof NothingReadError)
|
|
756
|
+
failedWholeReads.set(id, error.reason);
|
|
757
|
+
else
|
|
758
|
+
wholeReads.set(id, Math.max(0, (wholeReads.get(id) ?? 1) - 1));
|
|
351
759
|
throw error;
|
|
352
760
|
}
|
|
761
|
+
failedWholeReads.delete(id);
|
|
353
762
|
const notesCutShort = result.truncatedParts + result.truncatedMerges;
|
|
354
|
-
return
|
|
763
|
+
return fitAnswer({
|
|
355
764
|
document: document.meta.name,
|
|
356
765
|
parts_read: result.parts,
|
|
357
766
|
parts_with_relevant_content: result.relevantParts,
|
|
358
767
|
...(result.failedParts ? { parts_that_failed: result.failedParts } : {}),
|
|
359
768
|
...(notesCutShort ? { notes_cut_short: notesCutShort } : {}),
|
|
360
769
|
...(result.answerTruncated ? { answer_cut_short: true } : {}),
|
|
361
|
-
...(
|
|
770
|
+
...(result.answerFailed !== undefined ? { notes_only: true } : {}),
|
|
771
|
+
...(result.answerFailed !== undefined
|
|
772
|
+
? { 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." : ""}` }
|
|
773
|
+
: notesCutShort || result.answerTruncated ? { note: INCOMPLETE_ANALYSIS } : {}),
|
|
362
774
|
answer: result.answer,
|
|
363
|
-
},
|
|
775
|
+
}, limitOf(limits, Math.max(cap, ANALYSIS_RESULT_CHARACTERS)));
|
|
364
776
|
},
|
|
365
777
|
};
|
|
366
778
|
/** `view_pages`: the pages as one small PDF, next to a short JSON result. */
|
|
@@ -371,7 +783,7 @@ export function createDocumentTools(options) {
|
|
|
371
783
|
if (!viewable.has(id)) {
|
|
372
784
|
throw new Error(allowed.has(id)
|
|
373
785
|
? `The pages of ${names.get(id) ?? id} cannot be shown: only its text was kept. Answer from the text.`
|
|
374
|
-
: `Unknown document_id ${id}. Use the document_id of an attached PDF.`);
|
|
786
|
+
: `Unknown document_id ${shownId(id)}. Use the document_id of an attached PDF.`);
|
|
375
787
|
}
|
|
376
788
|
const document = await options.load(id);
|
|
377
789
|
if (!document)
|
|
@@ -420,15 +832,15 @@ export function createDocumentTools(options) {
|
|
|
420
832
|
}
|
|
421
833
|
// What a tool could not do goes to the model, and from there to a user's screen: never a server path.
|
|
422
834
|
const failure = (error) => ({ error: safeErrorMessage(error) });
|
|
423
|
-
async function execute(name, args, limits = {}) {
|
|
835
|
+
async function execute(name, args, limits = {}, hooks = {}) {
|
|
424
836
|
if (!known.has(name))
|
|
425
|
-
return { error: `Unknown tool ${name}.` };
|
|
837
|
+
return { error: `Unknown tool ${unknownToolName(name)}.` };
|
|
426
838
|
// The pages are a file, and this method returns only JSON. Saying that pages are attached
|
|
427
839
|
// with nothing attached would be worse than saying that they could not be shown.
|
|
428
840
|
if (name === TOOL_NAMES.view)
|
|
429
841
|
return { error: FILES_NOT_DELIVERED };
|
|
430
842
|
try {
|
|
431
|
-
return await handlers[name](args, limits);
|
|
843
|
+
return await handlers[name](args, limits, hooks);
|
|
432
844
|
}
|
|
433
845
|
catch (error) {
|
|
434
846
|
if (options.signal?.aborted)
|
|
@@ -441,9 +853,9 @@ export function createDocumentTools(options) {
|
|
|
441
853
|
has: (name) => known.has(name),
|
|
442
854
|
execute: (name, args) => execute(name, args),
|
|
443
855
|
resultCharacters: (name) => (name === TOOL_NAMES.analyze ? Math.max(cap, ANALYSIS_RESULT_CHARACTERS) : name === TOOL_NAMES.view ? LEAST_RESULT_CHARACTERS : cap),
|
|
444
|
-
async executeWithFiles(name, args, limits = {}) {
|
|
856
|
+
async executeWithFiles(name, args, limits = {}, hooks = {}) {
|
|
445
857
|
if (name !== TOOL_NAMES.view || !known.has(name))
|
|
446
|
-
return { result: await execute(name, args, limits), files: [] };
|
|
858
|
+
return { result: await execute(name, args, limits, hooks), files: [] };
|
|
447
859
|
try {
|
|
448
860
|
return await viewPages(args, limits);
|
|
449
861
|
}
|
|
@@ -464,7 +876,10 @@ export function createDocumentTools(options) {
|
|
|
464
876
|
}
|
|
465
877
|
if (name === TOOL_NAMES.search) {
|
|
466
878
|
const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
|
|
467
|
-
|
|
879
|
+
const { fromLine, toLine, order, groupBy } = searchScope(args);
|
|
880
|
+
const where = fromLine !== undefined || toLine !== undefined ? ` in lines ${fromLine ?? 1}-${toLine ?? "end"}` : "";
|
|
881
|
+
const how = mode === "keywords" ? "" : groupBy ? `, counted by ${groupBy}` : order === "last" ? ", the last ones" : "";
|
|
882
|
+
return `Search ${file} (${mode}) for “${sliceWhole(String(args.query ?? ""), 80)}”${where}${how}`;
|
|
468
883
|
}
|
|
469
884
|
if (name === TOOL_NAMES.read) {
|
|
470
885
|
const start = integer(args.start_line, 1, 1, Number.MAX_SAFE_INTEGER);
|
|
@@ -474,7 +889,7 @@ export function createDocumentTools(options) {
|
|
|
474
889
|
if (name === TOOL_NAMES.overview)
|
|
475
890
|
return `Overview of ${file}`;
|
|
476
891
|
if (name === TOOL_NAMES.analyze)
|
|
477
|
-
return `Read all of ${file} for “${String(args.task ?? "")
|
|
892
|
+
return `Read all of ${file} for “${sliceWhole(String(args.task ?? ""), 100)}”`;
|
|
478
893
|
return name;
|
|
479
894
|
},
|
|
480
895
|
};
|