llm-large-files 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +446 -0
- package/README.md +13 -7
- package/dist/access.d.ts +45 -3
- package/dist/access.d.ts.map +1 -1
- package/dist/access.js +106 -3
- package/dist/access.js.map +1 -1
- package/dist/aggregate.d.ts +6 -0
- package/dist/aggregate.d.ts.map +1 -1
- package/dist/aggregate.js +86 -13
- package/dist/aggregate.js.map +1 -1
- package/dist/analyze.d.ts +4 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +2 -2
- package/dist/analyze.js.map +1 -1
- package/dist/answer-info.d.ts +26 -0
- package/dist/answer-info.d.ts.map +1 -0
- package/dist/answer-info.js +32 -0
- package/dist/answer-info.js.map +1 -0
- package/dist/anthropic/adapter.d.ts +5 -1
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +35 -10
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +115 -14
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +572 -103
- package/dist/ask.js.map +1 -1
- package/dist/citations.d.ts +36 -0
- package/dist/citations.d.ts.map +1 -0
- package/dist/citations.js +291 -0
- package/dist/citations.js.map +1 -0
- package/dist/error-info.d.ts +13 -0
- package/dist/error-info.d.ts.map +1 -1
- package/dist/error-info.js +37 -1
- package/dist/error-info.js.map +1 -1
- package/dist/errors.d.ts +3 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +3 -1
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +25 -7
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +21 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +6 -1
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +35 -4
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +68 -29
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +28 -55
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +20 -27
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +59 -11
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +33 -7
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/errors.d.ts +39 -5
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +70 -9
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +53 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +100 -50
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/http.d.ts +41 -3
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +40 -2
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +6 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +9 -1
- package/dist/ingest.d.ts.map +1 -1
- package/dist/ingest.js +50 -25
- package/dist/ingest.js.map +1 -1
- package/dist/library.d.ts +129 -2
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +224 -149
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +176 -10
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +804 -58
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +36 -4
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +17 -1
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +29 -8
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +148 -126
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +1 -1
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.js +2 -2
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/spool.d.ts +9 -5
- package/dist/node/spool.d.ts.map +1 -1
- package/dist/node/spool.js +28 -15
- package/dist/node/spool.js.map +1 -1
- package/dist/node/sse.d.ts +6 -5
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +8 -7
- package/dist/node/sse.js.map +1 -1
- package/dist/openai/adapter.d.ts +5 -1
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +53 -12
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +2 -1
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +5 -2
- package/dist/output-limit.js.map +1 -1
- package/dist/pdf-outline.d.ts +71 -0
- package/dist/pdf-outline.d.ts.map +1 -0
- package/dist/pdf-outline.js +414 -0
- package/dist/pdf-outline.js.map +1 -0
- package/dist/plan.d.ts +137 -7
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +248 -26
- package/dist/plan.js.map +1 -1
- package/dist/prepare.d.ts +50 -0
- package/dist/prepare.d.ts.map +1 -0
- package/dist/prepare.js +207 -0
- package/dist/prepare.js.map +1 -0
- package/dist/ranged.d.ts +2 -1
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +16 -3
- package/dist/ranged.js.map +1 -1
- package/dist/search.d.ts +7 -0
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +72 -10
- package/dist/search.js.map +1 -1
- package/dist/stores.d.ts +6 -0
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +82 -11
- package/dist/stores.js.map +1 -1
- package/dist/tools.d.ts +22 -2
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +323 -76
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +49 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/whole-cost.d.ts +37 -0
- package/dist/whole-cost.d.ts.map +1 -0
- package/dist/whole-cost.js +46 -0
- package/dist/whole-cost.js.map +1 -0
- package/docs/README.md +4 -0
- package/docs/guides/anthropic.md +5 -2
- package/docs/guides/conversations.md +1 -1
- package/docs/guides/costs-and-limits.md +132 -36
- package/docs/guides/deployment.md +106 -13
- package/docs/guides/errors-and-reliability.md +157 -45
- package/docs/guides/explorer-model.md +4 -1
- package/docs/guides/openai-compatible.md +47 -7
- package/docs/guides/own-adapter-and-loop.md +33 -6
- package/docs/guides/pdfs.md +96 -7
- package/docs/guides/storage.md +46 -3
- package/docs/guides/testing.md +71 -0
- package/docs/guides/vertex-and-gemini.md +159 -50
- package/docs/guides/web-app.md +10 -6
- package/docs/how-it-works.md +120 -22
- package/docs/measurements.md +172 -5
- package/docs/publishing.md +76 -4
- package/docs/reference/anthropic.md +12 -7
- package/docs/reference/ask.md +262 -35
- package/docs/reference/errors-and-retries.md +30 -2
- package/docs/reference/events.md +27 -10
- package/docs/reference/gemini.md +184 -68
- package/docs/reference/library.md +190 -23
- package/docs/reference/node.md +51 -17
- package/docs/reference/openai.md +21 -10
- package/docs/reference/tools.md +271 -26
- package/docs/security.md +101 -12
- package/docs/troubleshooting.md +14 -12
- package/docs/upgrading-0.10.md +472 -0
- package/package.json +5 -1
- package/src/access.ts +127 -4
- package/src/aggregate.ts +92 -14
- package/src/analyze.ts +2 -2
- package/src/answer-info.ts +45 -0
- package/src/anthropic/adapter.ts +40 -11
- package/src/ask.ts +646 -106
- package/src/citations.ts +294 -0
- package/src/error-info.ts +36 -1
- package/src/errors.ts +3 -1
- package/src/events.ts +29 -6
- package/src/evidence.ts +21 -2
- package/src/extract.ts +6 -1
- package/src/gemini/adapter.ts +99 -32
- package/src/gemini/chat.ts +53 -82
- package/src/gemini/endpoints.ts +89 -16
- package/src/gemini/errors.ts +74 -11
- package/src/gemini/generate.ts +147 -57
- package/src/gemini/index.ts +3 -3
- package/src/http.ts +65 -4
- package/src/index.ts +6 -4
- package/src/ingest.ts +58 -27
- package/src/library.ts +336 -142
- package/src/map-reduce.ts +855 -67
- package/src/model.ts +44 -4
- package/src/node/handlers.ts +159 -118
- package/src/node/index.ts +1 -0
- package/src/node/ingest-child.ts +2 -2
- package/src/node/spool.ts +28 -14
- package/src/node/sse.ts +8 -7
- package/src/openai/adapter.ts +56 -13
- package/src/output-limit.ts +5 -2
- package/src/pdf-outline.ts +400 -0
- package/src/plan.ts +287 -36
- package/src/prepare.ts +253 -0
- package/src/ranged.ts +16 -3
- package/src/search.ts +69 -13
- package/src/stores.ts +76 -11
- package/src/tools.ts +327 -75
- package/src/types.ts +45 -1
- package/src/whole-cost.ts +64 -0
package/dist/ask.js
CHANGED
|
@@ -1,17 +1,26 @@
|
|
|
1
1
|
// The tool loop, for any model: plan the documents, offer the tools, run the calls within the
|
|
2
2
|
// limits of the request, and end with an answer. A provider is an adapter (see model.ts).
|
|
3
3
|
import { eventErrorOf, EventEmitter, eventStream, newRunId } from "./events.js";
|
|
4
|
+
import { checkCitations } from "./citations.js";
|
|
4
5
|
import { evidenceOf, stubResult } from "./evidence.js";
|
|
5
6
|
import { isCutReply, until } from "./http.js";
|
|
6
7
|
import { Limiter } from "./limiter.js";
|
|
7
|
-
import { DocumentsNotFoundError, errorKindOf, laterResult, modelErrorOf, rateAllowanceOf, TOOL_TURN_VERSION, UsageMeter, } from "./model.js";
|
|
8
|
+
import { DocumentsNotFoundError, errorKindOf, laterResult, modelErrorOf, rateAllowanceOf, reportsInput, TOOL_TURN_VERSION, UsageMeter, } from "./model.js";
|
|
8
9
|
import { DocumentStoreError } from "./errors.js";
|
|
9
|
-
import { estimateParts, REQUEST_BYTES_MARGIN } from "./plan.js";
|
|
10
|
+
import { canBeReadWhole, estimateParts, inlineInstruction, questionTools, REQUEST_BYTES_MARGIN } from "./plan.js";
|
|
11
|
+
import { preparedHere } from "./prepare.js";
|
|
10
12
|
import { statusOf, withRetry } from "./retry.js";
|
|
11
13
|
import { estimateTokens, jsonBytes, wellFormedJson } from "./text.js";
|
|
12
14
|
import { alreadyShown, failureKind, fitAnswer, LEAST_RESULT_CHARACTERS, MAX_WHOLE_DOCUMENT_READS, repeatedFailureHint, stepLine, TOOL_NAMES, toolCallKey, toolResultSummary, unknownToolName, } from "./tools.js";
|
|
15
|
+
import { wholeReadCost } from "./whole-cost.js";
|
|
13
16
|
/** Sent (invisibly to the user) when the model must stop using tools and answer. */
|
|
14
17
|
export const FINAL_ANSWER_REQUEST = "Stop using tools now. Answer my question using only what the tools returned above, with line citations. Say plainly what you could not find. Answer in the language of my question.";
|
|
18
|
+
/**
|
|
19
|
+
* The same, when files were also sent whole and the tools can read them or their lines are
|
|
20
|
+
* numbered (`inlineTables`, `numberInline`): what they say is part of the answer too, not only what
|
|
21
|
+
* the tools returned. New in 0.10.0. Not exported from the package.
|
|
22
|
+
*/
|
|
23
|
+
export const FINAL_ANSWER_WITH_FILES = "Stop using tools now. Answer my question using only the files shown in full and what the tools returned above, with line citations. Say plainly what you could not find. Answer in the language of my question.";
|
|
15
24
|
/** The same, when the only tool was `view_pages`: the text of the files is in the prompt, not in tool results. */
|
|
16
25
|
export const FINAL_ANSWER_AFTER_PAGES = "Stop using tools now. Answer my question from the text of the files and the pages you looked at. Say plainly what you could not see or find. Answer in the language of my question.";
|
|
17
26
|
/**
|
|
@@ -24,6 +33,14 @@ export const FINAL_ANSWER_WITHOUT_TOOLS = "Answer my question now, from what is
|
|
|
24
33
|
* needs, and the other model writes the answer.
|
|
25
34
|
*/
|
|
26
35
|
export const EXPLORER_INSTRUCTION = "You only gather material in this conversation: another model writes the answer. It sees this conversation and what your tool calls returned, not what you thought or wrote. So call the tools until their results hold everything the answer needs from the files. Then, or at once if no tool is needed, reply with the single word DONE instead of an answer.";
|
|
36
|
+
/**
|
|
37
|
+
* The least ceiling on the input tokens of a question that sets no `limits.inputTokens`. Its
|
|
38
|
+
* ceiling is the larger of this and `toolTurns` times its first request, with the room for its
|
|
39
|
+
* whole-file reads added. New in 0.10.0.
|
|
40
|
+
*/
|
|
41
|
+
export const DEFAULT_INPUT_TOKENS = 1_000_000;
|
|
42
|
+
/** How many whole-file reads one question may make, over all its documents, by default (`limits.wholeReadsPerQuestion`). */
|
|
43
|
+
const DEFAULT_WHOLE_READS_PER_QUESTION = 2;
|
|
27
44
|
/** The line added to the system instruction when `count` documents were left out ("drop"). */
|
|
28
45
|
const missingFilesLine = (count) => (count === 1
|
|
29
46
|
? "1 of the attached files is no longer available; say so if the question needs it."
|
|
@@ -36,6 +53,36 @@ function checkMissingPolicy(given) {
|
|
|
36
53
|
return;
|
|
37
54
|
throw new TypeError(`onMissingDocuments must be "throw", "drop" or a function, and is ${shownValue(given)}.`);
|
|
38
55
|
}
|
|
56
|
+
/**
|
|
57
|
+
* `filteredAnswer` checked: a value it cannot be ("Drop", true) is an error before anything is
|
|
58
|
+
* planned. It would otherwise keep a filtered answer that the application meant to drop.
|
|
59
|
+
*/
|
|
60
|
+
function checkFilteredAnswer(given) {
|
|
61
|
+
if (given === undefined || given === "keep" || given === "drop")
|
|
62
|
+
return;
|
|
63
|
+
throw new TypeError(`filteredAnswer must be "keep" or "drop", and is ${shownValue(given)}.`);
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* `inlineTables` and `numberInline` checked: a value they cannot be ("Text", "false") is an error
|
|
67
|
+
* before anything is planned, as `prepare` would throw it, but in the words of the question.
|
|
68
|
+
*/
|
|
69
|
+
function checkInlineOptions(tables, numbered) {
|
|
70
|
+
if (tables !== undefined && tables !== "tools" && tables !== "text")
|
|
71
|
+
throw new TypeError(`inlineTables must be "tools" or "text", and is ${shownValue(tables)}.`);
|
|
72
|
+
if (numbered !== undefined && typeof numbered !== "boolean")
|
|
73
|
+
throw new TypeError(`numberInline must be true or false, and is ${shownValue(numbered)}.`);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The evidence of a document sent whole (since 0.10.0): every line of it was shown. It comes from
|
|
77
|
+
* no tool call, so it has no `callId`.
|
|
78
|
+
*/
|
|
79
|
+
const sentWhole = (meta) => ({
|
|
80
|
+
tool: "inline",
|
|
81
|
+
documentId: meta.id,
|
|
82
|
+
document: meta.name,
|
|
83
|
+
...(Number.isFinite(meta.lines) && meta.lines >= 1 ? { lines: [[1, Math.trunc(meta.lines)]] } : {}),
|
|
84
|
+
whole: true,
|
|
85
|
+
});
|
|
39
86
|
/** An object made as `{}` or `Object.create(null)` is: not a Map, an array or an instance of a class. */
|
|
40
87
|
const isPlainObject = (value) => {
|
|
41
88
|
if (value === null || typeof value !== "object")
|
|
@@ -58,6 +105,29 @@ function checkedAction(action) {
|
|
|
58
105
|
}
|
|
59
106
|
throw new TypeError(`onMissingDocuments returned ${shownValue(action)}: it must return "throw", "drop", { retry: true } or { replace: { [oldId]: newId } }.`);
|
|
60
107
|
}
|
|
108
|
+
/**
|
|
109
|
+
* What `onToolResult` returned, checked: undefined, `{ result }` with a result that is an object,
|
|
110
|
+
* or `{ reject }` with a string. A verdict with a `result` is a result, whatever else it holds.
|
|
111
|
+
* Anything else ends the question: the hook is there to keep something from the model, and a
|
|
112
|
+
* mistake in it must not let the result through.
|
|
113
|
+
*/
|
|
114
|
+
function checkedVerdict(verdict) {
|
|
115
|
+
if (verdict === undefined)
|
|
116
|
+
return undefined;
|
|
117
|
+
if (verdict !== null && typeof verdict === "object") {
|
|
118
|
+
if (Object.hasOwn(verdict, "result")) {
|
|
119
|
+
const { result } = verdict;
|
|
120
|
+
if (result !== null && typeof result === "object" && !Array.isArray(result))
|
|
121
|
+
return { result: result };
|
|
122
|
+
}
|
|
123
|
+
else if (Object.hasOwn(verdict, "reject")) {
|
|
124
|
+
const { reject } = verdict;
|
|
125
|
+
if (typeof reject === "string")
|
|
126
|
+
return { reject };
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
throw new TypeError(`onToolResult returned ${shownValue(verdict)}: it must return { result }, { reject: "why" } or undefined.`);
|
|
130
|
+
}
|
|
61
131
|
/**
|
|
62
132
|
* Plans the documents `ids`, and settles those that are missing as `onMissingDocuments` says. A
|
|
63
133
|
* retry or a replace plans them again, once.
|
|
@@ -99,13 +169,55 @@ const DEFAULT_CALLS_PER_TURN = 8;
|
|
|
99
169
|
const CALLS_AT_ONCE = 4;
|
|
100
170
|
/** With less room than this for its result, a call is not run. */
|
|
101
171
|
const LEAST_ROOM_CHARACTERS = 1_500;
|
|
102
|
-
/**
|
|
172
|
+
/**
|
|
173
|
+
* Characters of a tool result for each token of room, when the call names no document of the
|
|
174
|
+
* question. Since 0.10.0 a call that names one takes its document's own (`charactersPerToken`).
|
|
175
|
+
*/
|
|
103
176
|
const CHARACTERS_PER_TOKEN = 2;
|
|
177
|
+
/**
|
|
178
|
+
* The characters of a document's text for each token of the estimate, as its ingest counted them,
|
|
179
|
+
* from 0.8 to 4: about 0.9 for a table of numbers, 1.4 for a service log, 1.9 for Hebrew prose.
|
|
180
|
+
* The JSON of a tool result that quotes the text comes to about the same. `CHARACTERS_PER_TOKEN`
|
|
181
|
+
* when the metadata does not say. New in 0.10.0.
|
|
182
|
+
*/
|
|
183
|
+
function charactersPerToken(meta) {
|
|
184
|
+
const ratio = meta && meta.estimatedTokens > 0 ? meta.characters / meta.estimatedTokens : Number.NaN;
|
|
185
|
+
return Number.isFinite(ratio) ? Math.min(4, Math.max(0.8, ratio)) : CHARACTERS_PER_TOKEN;
|
|
186
|
+
}
|
|
187
|
+
/** The tokens of room a tool result takes in a request, as the request meter counts an answer. */
|
|
188
|
+
const resultTokens = (result) => estimateTokens(JSON.stringify(result)) + 8;
|
|
189
|
+
/**
|
|
190
|
+
* `result` cut to `tokens` of room (`resultTokens`): by `fitAnswer`, to the characters its own
|
|
191
|
+
* characters per token give, and a little less again while it is still over. Never below
|
|
192
|
+
* `LEAST_RESULT_CHARACTERS`.
|
|
193
|
+
*/
|
|
194
|
+
function cutToTokens(result, tokens) {
|
|
195
|
+
const json = JSON.stringify(result);
|
|
196
|
+
const perToken = json.length / Math.max(1, resultTokens(result));
|
|
197
|
+
let characters = Math.max(LEAST_RESULT_CHARACTERS, Math.floor(tokens * perToken));
|
|
198
|
+
let cut = fitAnswer(result, characters);
|
|
199
|
+
for (let tries = 0; tries < 4 && resultTokens(cut) > tokens && characters > LEAST_RESULT_CHARACTERS; tries++) {
|
|
200
|
+
characters = Math.max(LEAST_RESULT_CHARACTERS, Math.floor(characters * 0.85));
|
|
201
|
+
cut = fitAnswer(result, characters);
|
|
202
|
+
}
|
|
203
|
+
return cut;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* `alreadyShown`, but never a pointer to a result that `onToolResult` replaced (`redacted: true`):
|
|
207
|
+
* it does not hold what the call would return.
|
|
208
|
+
*/
|
|
209
|
+
function pointerTo(call, earlier, stored = false) {
|
|
210
|
+
return earlier.result.redacted === true ? undefined : alreadyShown(call, earlier, stored);
|
|
211
|
+
}
|
|
104
212
|
/** Bytes a character of a tool result may take in the request. */
|
|
105
213
|
const BYTES_PER_CHARACTER = 3;
|
|
106
214
|
/** Tool rounds whose results are kept in full when older ones are dropped to make room. */
|
|
107
215
|
const ROUNDS_KEPT = [3, 2, 1];
|
|
108
216
|
const NO_ROOM = "Not run: there is no room left in this conversation for another tool result. Answer now, from what the tools returned so far.";
|
|
217
|
+
/** How the error of a whole-file read that sent its parts, and could read none of them, begins (`NothingReadError`). */
|
|
218
|
+
const NOTHING_READ = "Could not read any part of ";
|
|
219
|
+
/** The answer to a call of a tool the question does not have: it is not run, and takes no room. New in 0.10.0. */
|
|
220
|
+
const unknownTool = (name, tools) => `Unknown tool ${unknownToolName(name)}. The tools are: ${tools.join(", ")}.`;
|
|
109
221
|
/** Why a request of a whole-file read that its read left behind ended with its call. */
|
|
110
222
|
const CALL_ENDED = "The tool call ended before this request did.";
|
|
111
223
|
const count = (value) => Math.max(0, Math.round(value)).toLocaleString("en-US");
|
|
@@ -272,24 +384,30 @@ class RequestMeter {
|
|
|
272
384
|
}
|
|
273
385
|
}
|
|
274
386
|
/**
|
|
275
|
-
* Shares `room`
|
|
276
|
-
*
|
|
277
|
-
*
|
|
278
|
-
*
|
|
387
|
+
* Shares `room` among tool calls whose results may be up to `caps` characters. A character of the
|
|
388
|
+
* result of call i takes `rates[i]` of the room (1 when `rates` is left out: the room is in
|
|
389
|
+
* characters; since 0.10.0 the loop gives it in tokens, and each call the tokens a character of its
|
|
390
|
+
* document takes). A call gets no more than its cap, and the others split what it leaves. Calls
|
|
391
|
+
* that cannot each get `LEAST_ROOM_CHARACTERS` (or their cap, when it is smaller) are not run, the
|
|
392
|
+
* last ones first: their share is undefined. The shares are in characters.
|
|
279
393
|
*/
|
|
280
|
-
export function shareRoom(caps, room) {
|
|
281
|
-
const
|
|
394
|
+
export function shareRoom(caps, room, rates) {
|
|
395
|
+
const rate = (index) => rates?.[index] ?? 1;
|
|
396
|
+
const least = (cap, index) => Math.min(cap, LEAST_ROOM_CHARACTERS) * rate(index);
|
|
282
397
|
let count = caps.length;
|
|
283
|
-
let needed = caps.reduce((sum, cap) => sum + least(cap), 0);
|
|
284
|
-
while (count > 0 && needed > room)
|
|
285
|
-
|
|
398
|
+
let needed = caps.reduce((sum, cap, index) => sum + least(cap, index), 0);
|
|
399
|
+
while (count > 0 && needed > room) {
|
|
400
|
+
count--;
|
|
401
|
+
needed -= least(caps[count], count);
|
|
402
|
+
}
|
|
286
403
|
const shares = caps.map(() => undefined);
|
|
287
404
|
// The smallest caps first: each call takes its cap or an even share of what is left, whichever is less.
|
|
288
|
-
const order = caps.slice(0, count).map((cap, index) => ({ cap, index })).sort((left, right) => left.cap - right.cap);
|
|
405
|
+
const order = caps.slice(0, count).map((cap, index) => ({ cap: cap * rate(index), index })).sort((left, right) => left.cap - right.cap);
|
|
289
406
|
let left = Math.max(0, Math.floor(room));
|
|
290
407
|
order.forEach(({ cap, index }, position) => {
|
|
291
408
|
const share = Math.min(cap, Math.floor(left / (order.length - position)));
|
|
292
|
-
|
|
409
|
+
// A call given its whole cap gets the cap as it is, not as it comes back from the rate.
|
|
410
|
+
shares[index] = share === cap ? caps[index] : Math.floor(share / rate(index));
|
|
293
411
|
left -= share;
|
|
294
412
|
});
|
|
295
413
|
return shares;
|
|
@@ -370,7 +488,7 @@ const MOST_OVERFLOW_RECOVERIES = 2;
|
|
|
370
488
|
* so it turned off the ceilings and the cap on whole-file reads, or every tool.
|
|
371
489
|
*/
|
|
372
490
|
function checkedLimits(given) {
|
|
373
|
-
for (const field of ["toolTurns", "callsPerTurn", "wholeDocumentReads", "inputTokens", "requests"]) {
|
|
491
|
+
for (const field of ["toolTurns", "callsPerTurn", "wholeDocumentReads", "inputTokens", "requests", "wholeReadsPerQuestion"]) {
|
|
374
492
|
const value = given?.[field];
|
|
375
493
|
if (value === undefined)
|
|
376
494
|
continue;
|
|
@@ -430,13 +548,21 @@ export async function askWithFiles(options) {
|
|
|
430
548
|
* A result as `run.finish` and `run.error` carry it: a copy, so that a listener cannot change the
|
|
431
549
|
* caller's, without the tool rounds and with the plan naming documents only (both hold text of
|
|
432
550
|
* the documents: tool results, outline headings, the commonest lines of a log) unless `withTurns`.
|
|
551
|
+
* Its plan never holds the owner, scope, SHA-256 or original of a document.
|
|
433
552
|
*/
|
|
434
553
|
function eventResultOf(result, withTurns) {
|
|
554
|
+
const { toolTurns, plan, ...rest } = result;
|
|
555
|
+
// The full metadata only with `withTurns`, and never what is to stay on the server: who owns a
|
|
556
|
+
// document, its scope, the SHA-256 and the ref of its original.
|
|
435
557
|
if (withTurns)
|
|
436
|
-
return { ...
|
|
437
|
-
const { toolTurns: _toolTurns, plan, ...rest } = result;
|
|
558
|
+
return { ...rest, toolTurns, plan: { inline: plan.inline.map(withoutServerFields), searchable: plan.searchable.map(withoutServerFields) } };
|
|
438
559
|
return { ...rest, plan: { inline: plan.inline.map(documentRef), searchable: plan.searchable.map(documentRef) } };
|
|
439
560
|
}
|
|
561
|
+
/** A document's metadata without what is to stay on the server, for an event (since 0.10.0). */
|
|
562
|
+
function withoutServerFields(meta) {
|
|
563
|
+
const { owner: _owner, scope: _scope, sha256: _sha256, original: _original, metaVersion: _metaVersion, ...rest } = meta;
|
|
564
|
+
return rest;
|
|
565
|
+
}
|
|
440
566
|
/**
|
|
441
567
|
* `askWithFiles` as a stream of its events, for a page that shows the question as it goes: see
|
|
442
568
|
* `AskEvent`. Leaving the loop early (`break`) stops the question. `result` is what `askWithFiles`
|
|
@@ -488,12 +614,18 @@ async function askPlanned(options, state) {
|
|
|
488
614
|
async function ask(options, carried, state) {
|
|
489
615
|
const { files, model, signal } = options;
|
|
490
616
|
const { events } = state;
|
|
491
|
-
// A second model for the requests that use tools. The answering model itself is not one.
|
|
492
|
-
|
|
493
|
-
const
|
|
494
|
-
const models =
|
|
617
|
+
// A second model for the requests that use tools. The answering model itself is not one. It
|
|
618
|
+
// explores only when a file is searched (see `explorer` below), but the budget is fitted to it.
|
|
619
|
+
const given = options.explorer && options.explorer !== model ? options.explorer : undefined;
|
|
620
|
+
const models = given ? [model, given] : [model];
|
|
495
621
|
const limits = checkedLimits(options.limits);
|
|
496
622
|
checkMissingPolicy(options.onMissingDocuments);
|
|
623
|
+
checkFilteredAnswer(options.filteredAnswer);
|
|
624
|
+
checkInlineOptions(options.inlineTables, options.numberInline);
|
|
625
|
+
// Since 0.10.0 by default: the tables sent whole get the tools, and the files sent whole have
|
|
626
|
+
// numbered lines. "text" and false send them as 0.9 did.
|
|
627
|
+
const inlineTables = options.inlineTables ?? "tools";
|
|
628
|
+
const numberInline = options.numberInline ?? true;
|
|
497
629
|
// A question planned again goes on counting what its first try paid for.
|
|
498
630
|
const usage = carried?.usage ?? new UsageMeter();
|
|
499
631
|
// The budget is counted in the library's estimate of tokens. A model whose tokenizer counts
|
|
@@ -524,23 +656,47 @@ async function ask(options, carried, state) {
|
|
|
524
656
|
const meter = new RequestMeter(pageTokens);
|
|
525
657
|
const asText = textSize(messages, options.system);
|
|
526
658
|
const earlier = meter.rounds(messages);
|
|
527
|
-
// Who asks: the documents are looked up, and every tool call reads them, for this owner and
|
|
659
|
+
// Who asks: the documents are looked up, and every tool call reads them, for this owner and
|
|
660
|
+
// scope. The question's signal goes with them, for a library that ends its waits for the store
|
|
661
|
+
// with it (`AccessOptions.signal`).
|
|
528
662
|
const access = {
|
|
529
663
|
...(options.owner !== undefined ? { owner: options.owner } : {}),
|
|
530
664
|
...(options.scope !== undefined ? { scope: options.scope } : {}),
|
|
665
|
+
...(signal ? { signal } : {}),
|
|
531
666
|
};
|
|
532
667
|
// Documents that are missing are settled as `onMissingDocuments` says. A question planned again
|
|
533
668
|
// starts from the documents its first try planned: the function is not asked again about them.
|
|
534
|
-
|
|
669
|
+
// The question stops when its signal aborts, whether the library does or not: a store call that
|
|
670
|
+
// hangs (a network volume that does not answer) must not hold it, with any `LargeFiles`.
|
|
671
|
+
const planned = await planDocumentsOf(options, carried?.documentIds ?? options.documentIds, (ids) => until(files.prepare(ids, { tokens: asText.tokens + earlier.tokens, bytes: asText.bytes + earlier.bytes }, {
|
|
535
672
|
...access,
|
|
536
673
|
viewPages: options.viewPages !== false && canShowFiles,
|
|
537
674
|
// The guide and the cards name `analyze_whole_document` only when the tools will have it.
|
|
538
|
-
wholeDocumentAnalysis: options.wholeDocumentAnalysis !== false && typeof
|
|
675
|
+
wholeDocumentAnalysis: options.wholeDocumentAnalysis !== false && typeof (given ?? model).generateText === "function",
|
|
539
676
|
budget,
|
|
540
|
-
|
|
677
|
+
numberInline,
|
|
678
|
+
inlineTables,
|
|
679
|
+
}), signal));
|
|
541
680
|
const { prepared, documentIds } = planned;
|
|
542
681
|
/** The documents left out of the question ("drop"), by this try and by the first. */
|
|
543
682
|
const missing = [...carried?.missing ?? [], ...planned.dropped];
|
|
683
|
+
// Tools are needed for a file that is too large to send whole, for a PDF whose pages can be
|
|
684
|
+
// looked at (that one may have its whole text in the prompt and still hide a chart from the
|
|
685
|
+
// model), and for a table sent whole whose rows they can count (`inlineTables`). A library of
|
|
686
|
+
// your own whose `prepare` gives no `toolable` has none of the last.
|
|
687
|
+
const { searchable } = prepared.plan;
|
|
688
|
+
const { viewable } = prepared;
|
|
689
|
+
const toolable = prepared.toolable ?? [];
|
|
690
|
+
// The explorer gathers what the answer needs from the files searched with the tools. When none
|
|
691
|
+
// is, and the tools are there for tables sent whole, the answering model runs the loop itself: a
|
|
692
|
+
// question that needs no count is then answered in its first request, and the whole files are
|
|
693
|
+
// not sent to two models that share no cache.
|
|
694
|
+
const explorer = given && !(searchable.length === 0 && toolable.length > 0) ? given : undefined;
|
|
695
|
+
const toolModel = explorer ?? model;
|
|
696
|
+
// The lines of the files sent whole are numbered when asked, by a library whose `prepare` is
|
|
697
|
+
// that of this package (its result has the mark, `preparedHere`): one of your own of 0.9 sends
|
|
698
|
+
// them as they are.
|
|
699
|
+
const numbered = numberInline && preparedHere(prepared);
|
|
544
700
|
const blocks = [...new Set(documentIds)].map((id) => prepared.blocks.get(id)).filter((block) => Boolean(block));
|
|
545
701
|
if (blocks.length) {
|
|
546
702
|
const block = { text: blocks.join("\n\n") };
|
|
@@ -552,12 +708,15 @@ async function ask(options, carried, state) {
|
|
|
552
708
|
}
|
|
553
709
|
// A question without some of its files says so to the model, in one line of its own.
|
|
554
710
|
const missingLine = missing.length > 0 ? missingFilesLine(missing.length) : "";
|
|
555
|
-
|
|
711
|
+
// The fixed lines for the files sent whole (since 0.10.0): that their tables can still be counted
|
|
712
|
+
// with the tools, and, when no file is searched, to cite their numbered lines.
|
|
713
|
+
const inlineLine = inlineInstruction(prepared, numbered);
|
|
714
|
+
const system = [options.system?.trim(), prepared.instruction, inlineLine, missingLine].filter(Boolean).join("\n\n");
|
|
556
715
|
// The size of what stays in every request: the text as asked, the documents, the tool guide.
|
|
557
716
|
const whole = new Set(prepared.plan.inline.map((meta) => meta.id));
|
|
558
717
|
meter.fixed = {
|
|
559
|
-
tokens: asText.tokens + prepared.plan.inlineTokens + estimateTokens(prepared.instruction) + (missingLine ? estimateTokens(missingLine) : 0),
|
|
560
|
-
bytes: asText.bytes + prepared.plan.inlineBytes + jsonBytes(prepared.instruction) + (missingLine ? jsonBytes(missingLine) : 0),
|
|
718
|
+
tokens: asText.tokens + prepared.plan.inlineTokens + estimateTokens(prepared.instruction) + (inlineLine ? estimateTokens(inlineLine) : 0) + (missingLine ? estimateTokens(missingLine) : 0),
|
|
719
|
+
bytes: asText.bytes + prepared.plan.inlineBytes + jsonBytes(prepared.instruction) + (inlineLine ? jsonBytes(inlineLine) : 0) + (missingLine ? jsonBytes(missingLine) : 0),
|
|
561
720
|
};
|
|
562
721
|
for (const [id, block] of prepared.blocks) {
|
|
563
722
|
if (whole.has(id))
|
|
@@ -567,11 +726,20 @@ async function ask(options, carried, state) {
|
|
|
567
726
|
}
|
|
568
727
|
let text = "";
|
|
569
728
|
let turns = carried?.turns ?? 0;
|
|
729
|
+
/** The last reply of the chat: its `finish` is the answer's (`AskResult.finish`). */
|
|
730
|
+
let lastReply;
|
|
731
|
+
const dropFiltered = options.filteredAnswer === "drop";
|
|
570
732
|
let finishReason;
|
|
571
733
|
let blockReason;
|
|
572
734
|
let lastUsage;
|
|
573
735
|
const steps = [];
|
|
574
|
-
|
|
736
|
+
// The files sent whole come first, in the order of their blocks: the model was shown every line
|
|
737
|
+
// of them before any tool ran (since 0.10.0).
|
|
738
|
+
const inlineById = new Map(prepared.plan.inline.map((meta) => [meta.id, meta]));
|
|
739
|
+
const evidence = [...new Set(documentIds)].flatMap((id) => {
|
|
740
|
+
const meta = inlineById.get(id);
|
|
741
|
+
return meta ? [sentWhole(meta)] : [];
|
|
742
|
+
});
|
|
575
743
|
const emit = (delta, requestId) => {
|
|
576
744
|
text += delta;
|
|
577
745
|
options.onText?.(delta);
|
|
@@ -699,11 +867,14 @@ async function ask(options, carried, state) {
|
|
|
699
867
|
events.emit({ type: "request.end", requestId, ms: Date.now() - began, outcome: "error", error: eventErrorOf(error) });
|
|
700
868
|
throw error;
|
|
701
869
|
}
|
|
702
|
-
// Text the adapter did not pass on as it came (no streaming was asked for, or it cannot).
|
|
703
|
-
|
|
870
|
+
// Text the adapter did not pass on as it came (no streaming was asked for, or it cannot). Not
|
|
871
|
+
// the text of a reply a filter stopped, when such an answer is dropped: it was not shown yet.
|
|
872
|
+
if (shown && reply.text.length > got.length && reply.text.startsWith(got) && !(dropFiltered && reply.finish === "filtered"))
|
|
704
873
|
write(reply.text.slice(got.length));
|
|
705
874
|
answeredRequests++;
|
|
706
|
-
|
|
875
|
+
lastReply = reply;
|
|
876
|
+
// A reply without its input tokens is counted by the estimate, in the model's own tokens.
|
|
877
|
+
usage.add(adapter.id, reply.usage, estimated * scaleOf(adapter));
|
|
707
878
|
// The count of the model that answered, in the library's tokens by that model's own scale: how
|
|
708
879
|
// much more than its scale says the text costs it, which the other model will see too. By the
|
|
709
880
|
// larger scale of the two, a count of the model with the smaller one was taken for no more.
|
|
@@ -721,6 +892,8 @@ async function ask(options, carried, state) {
|
|
|
721
892
|
...(reply.finish ? { finish: reply.finish } : {}),
|
|
722
893
|
...(reply.finishReason !== undefined ? { finishReason: reply.finishReason } : {}),
|
|
723
894
|
toolCalls: reply.calls.length,
|
|
895
|
+
...(typeof reply.responseId === "string" ? { responseId: reply.responseId } : {}),
|
|
896
|
+
...(typeof reply.responseModel === "string" ? { responseModel: reply.responseModel } : {}),
|
|
724
897
|
});
|
|
725
898
|
if (reply.blockReason)
|
|
726
899
|
notice("blocked", `The provider refused the prompt: ${reply.blockReason}.`);
|
|
@@ -729,6 +902,25 @@ async function ask(options, carried, state) {
|
|
|
729
902
|
// What a model wrote before it was stopped by a refusal is not an answer.
|
|
730
903
|
const wrote = (reply) => reply.text.trim().length > 0 && !reply.blockReason;
|
|
731
904
|
const asked = messages.length;
|
|
905
|
+
/** The documents of the question, by ID: their names and formats, for the citations of the answer. */
|
|
906
|
+
const documents = [...prepared.plan.inline, ...prepared.plan.searchable];
|
|
907
|
+
const citationsOf = () => {
|
|
908
|
+
const names = {};
|
|
909
|
+
const formats = {};
|
|
910
|
+
for (const meta of documents) {
|
|
911
|
+
names[meta.id] = meta.name;
|
|
912
|
+
formats[meta.id] = meta.format;
|
|
913
|
+
}
|
|
914
|
+
// A document sent whole was shown, every line of it (its evidence comes first and says so),
|
|
915
|
+
// and a whole-file read read every line: those from 1 to its last. A line past the end of the
|
|
916
|
+
// file is not supported.
|
|
917
|
+
const linesOf = new Map(documents.map((meta) => [meta.id, meta.lines]));
|
|
918
|
+
const bounded = (entry) => {
|
|
919
|
+
const lines = linesOf.get(entry.documentId);
|
|
920
|
+
return entry.whole === true && !entry.lines && typeof lines === "number" && Number.isFinite(lines) ? { ...entry, lines: lines >= 1 ? [[1, Math.trunc(lines)]] : [] } : entry;
|
|
921
|
+
};
|
|
922
|
+
return checkCitations(text, evidence.map(bounded), names, formats);
|
|
923
|
+
};
|
|
732
924
|
const result = (answered) => ({
|
|
733
925
|
text,
|
|
734
926
|
answered,
|
|
@@ -751,7 +943,34 @@ async function ask(options, carried, state) {
|
|
|
751
943
|
...(finishReason ? { finishReason } : {}),
|
|
752
944
|
usage: usage.totals,
|
|
753
945
|
...(lastUsage ? { lastUsage } : {}),
|
|
946
|
+
...(lastReply?.finish !== undefined ? { finish: lastReply.finish } : {}),
|
|
947
|
+
...(documents.length > 0 ? { citations: citationsOf() } : {}),
|
|
754
948
|
});
|
|
949
|
+
/**
|
|
950
|
+
* The result of a question that ends with an answer: one that a filter stopped, or that was cut
|
|
951
|
+
* at the output limit, says so in a notice, before `run.finish`. A filtered answer is dropped
|
|
952
|
+
* when `filteredAnswer` says so; text of it already sent is to be taken away (`discardText`).
|
|
953
|
+
*/
|
|
954
|
+
const answer = (answered) => {
|
|
955
|
+
const finish = lastReply?.finish;
|
|
956
|
+
if (finish === "filtered") {
|
|
957
|
+
const sent = text.length > 0;
|
|
958
|
+
const message = !lastReply?.text.trim()
|
|
959
|
+
? "A filter of the provider stopped the answer before any text came."
|
|
960
|
+
: dropFiltered
|
|
961
|
+
? "A filter of the provider stopped the answer before it was finished: its text was dropped."
|
|
962
|
+
: "A filter of the provider stopped the answer before it was finished.";
|
|
963
|
+
events.emit({ type: "notice", code: "answer_filtered", message, display: "none", ...(dropFiltered && sent ? { discardText: true } : {}) });
|
|
964
|
+
if (dropFiltered) {
|
|
965
|
+
text = "";
|
|
966
|
+
return result(false);
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
else if (finish === "cut") {
|
|
970
|
+
notice("answer_cut", lastReply?.text.trim() ? "The answer stopped at the model's output limit, so it is incomplete." : "The answer stopped at the model's output limit before any text came.");
|
|
971
|
+
}
|
|
972
|
+
return result(answered);
|
|
973
|
+
};
|
|
755
974
|
// Pages the model looks at stay in the request until the question is answered, so they are
|
|
756
975
|
// counted twice: as bytes against the request limit, and as tokens against half of what the
|
|
757
976
|
// budget keeps free for tool results and the answer.
|
|
@@ -763,10 +982,15 @@ async function ask(options, carried, state) {
|
|
|
763
982
|
// request as too large, and names its window, makes it smaller.
|
|
764
983
|
let tokenLimit = budget.contextTokens - Math.floor(reservedTokens / 2);
|
|
765
984
|
const byteLimit = maxRequestBytes - Math.max(32_768, Math.floor(maxRequestBytes / 50));
|
|
766
|
-
/**
|
|
767
|
-
|
|
985
|
+
/**
|
|
986
|
+
* The tokens of tool results that still fit, with a model turn that is about to be answered, for
|
|
987
|
+
* calls whose results take `rates` tokens a character: within the token limit, and within the
|
|
988
|
+
* bytes of the request for the call that takes the fewest tokens a character.
|
|
989
|
+
*/
|
|
990
|
+
const room = (pending, rates) => {
|
|
768
991
|
const now = meter.current([...messages, pending]);
|
|
769
|
-
|
|
992
|
+
const fewest = rates.length > 0 ? Math.min(...rates) : 1 / CHARACTERS_PER_TOKEN;
|
|
993
|
+
return Math.floor(Math.min(tokenLimit - now.tokens, (byteLimit - now.bytes) / BYTES_PER_CHARACTER * fewest));
|
|
770
994
|
};
|
|
771
995
|
/**
|
|
772
996
|
* Makes room: the results of every tool round but the last `keep` are replaced by short
|
|
@@ -829,7 +1053,7 @@ async function ask(options, carried, state) {
|
|
|
829
1053
|
if (answer.result.already_shown === true) {
|
|
830
1054
|
const held = canPoint && ((key !== undefined && (inRound.has(key) || (answer.call.name !== TOOL_NAMES.read && shownKeys.has(key))))
|
|
831
1055
|
|| (answer.call.name === TOOL_NAMES.read && (shownReads.get(answer.call.args.document_id) ?? [])
|
|
832
|
-
.some((read) =>
|
|
1056
|
+
.some((read) => pointerTo(answer.call, read.answer, read.index < asked && read.question !== question) !== undefined)));
|
|
833
1057
|
if (!held) {
|
|
834
1058
|
touched = true;
|
|
835
1059
|
now = {
|
|
@@ -842,7 +1066,7 @@ async function ask(options, carried, state) {
|
|
|
842
1066
|
};
|
|
843
1067
|
}
|
|
844
1068
|
}
|
|
845
|
-
else if (key !== undefined &&
|
|
1069
|
+
else if (key !== undefined && pointerTo(answer.call, answer) !== undefined) {
|
|
846
1070
|
// A result in full: what a later pointer may point to.
|
|
847
1071
|
if (answer.call.name === TOOL_NAMES.read) {
|
|
848
1072
|
const reads = shownReads.get(answer.call.args.document_id) ?? [];
|
|
@@ -1020,32 +1244,39 @@ async function ask(options, carried, state) {
|
|
|
1020
1244
|
else
|
|
1021
1245
|
signal?.addEventListener("abort", stopTools, { once: true });
|
|
1022
1246
|
try {
|
|
1023
|
-
//
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
const { viewable } = prepared;
|
|
1027
|
-
if (searchable.length === 0 && viewable.length === 0)
|
|
1028
|
-
return result(wrote(await send(model, () => ({ system, messages }), true, { role: "answer", purpose: "direct" })));
|
|
1247
|
+
// Nothing for the tools (see `toolable` above): one request, without them.
|
|
1248
|
+
if (searchable.length === 0 && viewable.length === 0 && toolable.length === 0)
|
|
1249
|
+
return answer(wrote(await send(model, () => ({ system, messages }), true, { role: "answer", purpose: "direct" })));
|
|
1029
1250
|
// Reading a whole file in parts is exploring too: the explorer model's work, when there is one.
|
|
1030
1251
|
// Bound to its adapter: a class with a `generateText` method that uses `this` keeps it.
|
|
1031
1252
|
const partReader = options.wholeDocumentAnalysis === false ? undefined : toolModel.generateText?.bind(toolModel);
|
|
1032
1253
|
const generate = partReader && (async (part) => {
|
|
1033
1254
|
let reported = false;
|
|
1255
|
+
// What the request sends, in the reader's tokens: counted for a request whose usage does not
|
|
1256
|
+
// give its input, so that `limits.inputTokens` sees it. Worked out only then.
|
|
1257
|
+
const estimate = () => (estimateTokens(part.system) + estimateTokens(part.prompt)) * scaleOf(toolModel);
|
|
1034
1258
|
const text = await partReader({
|
|
1035
1259
|
...part,
|
|
1036
1260
|
onUsage: (used) => {
|
|
1037
1261
|
reported = true;
|
|
1038
|
-
usage.add(toolModel.id, used);
|
|
1262
|
+
usage.add(toolModel.id, used, reportsInput(used) ? undefined : estimate());
|
|
1039
1263
|
part.onUsage?.(used);
|
|
1040
1264
|
},
|
|
1041
1265
|
});
|
|
1042
1266
|
// A part reader that does not report its usage (`onUsage` is optional) still made a request,
|
|
1043
1267
|
// and `limits.requests` counts it.
|
|
1044
1268
|
if (!reported)
|
|
1045
|
-
usage.add(toolModel.id, undefined);
|
|
1269
|
+
usage.add(toolModel.id, undefined, estimate());
|
|
1046
1270
|
return text;
|
|
1047
1271
|
});
|
|
1048
|
-
|
|
1272
|
+
// The tables sent whole are read by the tools too. Their question declares exactly the tools it
|
|
1273
|
+
// needs (`questionTools`): search_document, read_document and aggregate_table for them, never
|
|
1274
|
+
// get_document_overview or analyze_whole_document, which refuses a file sent whole if it is
|
|
1275
|
+
// called. With no such table, the tool set of 0.9.
|
|
1276
|
+
const declare = toolable.length > 0
|
|
1277
|
+
? { declare: questionTools({ searchable, toolable, viewable }, generate !== undefined && searchable.some((meta) => canBeReadWhole(meta, budget))), inline: prepared.plan.inline.map((meta) => meta.id) }
|
|
1278
|
+
: {};
|
|
1279
|
+
const tools = files.tools([...searchable, ...toolable], {
|
|
1049
1280
|
// The owner and scope the store holds are checked against the question's own, not against
|
|
1050
1281
|
// the metadata handed in.
|
|
1051
1282
|
access,
|
|
@@ -1056,12 +1287,14 @@ async function ask(options, carried, state) {
|
|
|
1056
1287
|
maxWholeDocumentReads: limits.wholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS,
|
|
1057
1288
|
...(options.retry ? { retry: options.retry } : {}),
|
|
1058
1289
|
budget,
|
|
1290
|
+
...declare,
|
|
1059
1291
|
});
|
|
1060
1292
|
const declarations = tools.declarations;
|
|
1061
1293
|
/** The documents a tool call found gone, told once each ("document_gone"). */
|
|
1062
1294
|
const gone = new Set();
|
|
1063
1295
|
/** The file name of a document of the question, as the plan has it. */
|
|
1064
|
-
const
|
|
1296
|
+
const metaOf = (id) => (typeof id === "string" ? [...searchable, ...toolable, ...viewable].find((meta) => meta.id === id) : undefined);
|
|
1297
|
+
const nameOf = (id) => metaOf(id)?.name;
|
|
1065
1298
|
// The requests that use the tools are the chat's own, or an explorer model's: the same
|
|
1066
1299
|
// conversation, and a line that says what its part is.
|
|
1067
1300
|
const toolSystem = explorer ? `${system}\n\n${EXPLORER_INSTRUCTION}` : system;
|
|
@@ -1072,46 +1305,148 @@ async function ask(options, carried, state) {
|
|
|
1072
1305
|
activity("searching_instead", `Too large to read at once: ${searchable.map((meta) => meta.name).join(", ")}. Searching instead…`);
|
|
1073
1306
|
const maxTurns = Math.max(1, Math.trunc(limits.toolTurns ?? DEFAULT_TOOL_TURNS));
|
|
1074
1307
|
const maxCalls = Math.max(1, Math.trunc(limits.callsPerTurn ?? DEFAULT_CALLS_PER_TURN));
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1308
|
+
const readsOfEach = limits.wholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS;
|
|
1309
|
+
// As the tool set reads its own count of reads of each document: whole numbers, none below 0.
|
|
1310
|
+
const readsInAll = Math.max(0, Math.trunc(limits.wholeReadsPerQuestion ?? DEFAULT_WHOLE_READS_PER_QUESTION));
|
|
1078
1311
|
/**
|
|
1079
|
-
*
|
|
1080
|
-
*
|
|
1081
|
-
*
|
|
1312
|
+
* The price of a whole-file read of `meta` by the model that explores, in its own tokens and
|
|
1313
|
+
* requests: a read that lists items (`output: "items"`) is its parts alone; any other, its
|
|
1314
|
+
* parts, the merges of their notes and its answer.
|
|
1082
1315
|
*/
|
|
1083
|
-
const
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
const
|
|
1096
|
-
|
|
1097
|
-
const
|
|
1098
|
-
|
|
1099
|
-
|
|
1316
|
+
const priceOf = (meta, output = "answer") => wholeReadCost(meta, budget, scaleOf(toolModel), output);
|
|
1317
|
+
/**
|
|
1318
|
+
* The ceiling on the input tokens of the question: `limits.inputTokens`, or by default the larger
|
|
1319
|
+
* of `DEFAULT_INPUT_TOKENS` and `toolTurns` times the first request, plus room for the
|
|
1320
|
+
* whole-file reads the question may make: as many as `wholeReadsPerQuestion` and the documents
|
|
1321
|
+
* that can be read whole allow, each at the price of the dearest of them.
|
|
1322
|
+
*/
|
|
1323
|
+
const ceiling = (() => {
|
|
1324
|
+
if (limits.inputTokens !== undefined)
|
|
1325
|
+
return limits.inputTokens;
|
|
1326
|
+
const first = meter.current(viewFor(toolModel)).tokens * scaleOf(toolModel);
|
|
1327
|
+
const readable = tools.has(TOOL_NAMES.analyze) && readsOfEach > 0 ? searchable.filter((meta) => canBeReadWhole(meta, budget)) : [];
|
|
1328
|
+
const reads = Math.max(0, Math.min(readsInAll, readable.length * Math.trunc(readsOfEach)));
|
|
1329
|
+
const prices = readable.map((meta) => priceOf(meta).inputTokens).filter((price) => Number.isFinite(price));
|
|
1330
|
+
const allowance = prices.length > 0 ? (Number.isFinite(reads) ? reads : readable.length) * Math.max(...prices) : 0;
|
|
1331
|
+
return Math.max(DEFAULT_INPUT_TOKENS, maxTurns * first) + allowance;
|
|
1332
|
+
})();
|
|
1333
|
+
/** The input tokens the question has used: those the providers reported, and the estimates of those they did not. */
|
|
1334
|
+
const spentTokens = () => usage.totals.inputTokens + (usage.totals.estimatedInputTokens ?? 0);
|
|
1335
|
+
/**
|
|
1336
|
+
* True once the question has used what it may: no more tools run. One request is kept for the
|
|
1337
|
+
* answer. The ceiling of input tokens looks ahead: what was spent, the tool request about to be
|
|
1338
|
+
* sent and the answer's request after it, each as the meter counts it now, must stay within it.
|
|
1339
|
+
*/
|
|
1340
|
+
const spent = () => {
|
|
1341
|
+
if (limits.requests !== undefined && usage.totals.requests >= limits.requests - 1)
|
|
1342
|
+
return true;
|
|
1343
|
+
if (!(ceiling < Number.POSITIVE_INFINITY))
|
|
1344
|
+
return false;
|
|
1345
|
+
const next = meter.current(viewFor(toolModel)).tokens * scaleOf(toolModel);
|
|
1346
|
+
const closing = meter.current(viewFor(model)).tokens * scaleOf(model);
|
|
1347
|
+
return spentTokens() + next + closing > ceiling;
|
|
1348
|
+
};
|
|
1349
|
+
/**
|
|
1350
|
+
* The whole-file reads of the question that sent requests, by document: those that returned, and
|
|
1351
|
+
* those that failed after they sent them. Counted from what the tool returned, before
|
|
1352
|
+
* `onToolResult`: a read whose answer the hook replaced or rejected still made its requests.
|
|
1353
|
+
*/
|
|
1354
|
+
const readsSent = new Map();
|
|
1355
|
+
const readsMade = (documentId) => {
|
|
1356
|
+
if (documentId !== undefined)
|
|
1357
|
+
return readsSent.get(documentId) ?? 0;
|
|
1358
|
+
let made = 0;
|
|
1359
|
+
for (const reads of readsSent.values())
|
|
1360
|
+
made += reads;
|
|
1361
|
+
return made;
|
|
1362
|
+
};
|
|
1363
|
+
/** True for the output of a whole-file read that sent its parts: its answer, or the error of a read that could read none of them. */
|
|
1364
|
+
const sentParts = (call, output) => call.name === TOOL_NAMES.analyze
|
|
1365
|
+
&& (evidenceOf(call, output)?.whole === true || (typeof output.error === "string" && output.error.startsWith(NOTHING_READ)));
|
|
1366
|
+
/**
|
|
1367
|
+
* True when no whole-file read of `meta` is left, past those of `reserved`: the tool refuses one
|
|
1368
|
+
* itself, at no cost, with its own reason (such as a read that failed earlier). The tool set says
|
|
1369
|
+
* how many reads are left; one of your own that does not is read by what the reads of this
|
|
1370
|
+
* question returned.
|
|
1371
|
+
*/
|
|
1372
|
+
const noReadLeft = (meta, reserved) => {
|
|
1373
|
+
const inTurn = reserved.reads.get(meta.id) ?? 0;
|
|
1374
|
+
const left = tools.wholeReadsLeft?.(meta.id);
|
|
1375
|
+
return typeof left === "number" ? left - inTurn <= 0 : readsMade(meta.id) + inTurn >= readsOfEach;
|
|
1376
|
+
};
|
|
1377
|
+
/**
|
|
1378
|
+
* What a whole-file read of `meta` takes, and why the question would not start it now, past the
|
|
1379
|
+
* reads of `reserved`: its whole reads made, or a ceiling it would pass. Not the tool's own
|
|
1380
|
+
* reasons (`noReadLeft`). `output` is the read's own: a read that lists items ("items") is
|
|
1381
|
+
* priced at its parts alone, any other ("answer") at its parts, merges and answer.
|
|
1382
|
+
*/
|
|
1383
|
+
const readNeeds = (meta, reserved, output) => {
|
|
1384
|
+
// The parts are read by the model that explores, in its own tokens: their lines numbered, the
|
|
1385
|
+
// prompts, and the merges of their notes (`wholeReadCost`). A read that lists items sends its
|
|
1386
|
+
// parts alone, with the rules of a list.
|
|
1387
|
+
const items = output === "items";
|
|
1388
|
+
const price = priceOf(meta, output).inputTokens;
|
|
1389
|
+
const tokens = Number.isFinite(price) ? price : Math.ceil(meta.estimatedTokens * scaleOf(toolModel));
|
|
1390
|
+
// The parts, a merge of their notes, the answer of the read, and the answer of the question;
|
|
1391
|
+
// for a list of items, the parts and the answer of the question.
|
|
1392
|
+
const requests = estimateParts(meta, budget) + (items ? 1 : 3);
|
|
1393
|
+
const allReserved = [...reserved.reads.values()].reduce((sum, reads) => sum + reads, 0);
|
|
1394
|
+
if (readsMade() + allReserved >= readsInAll) {
|
|
1395
|
+
return { tokens, requests, refusal: `Not run: one question makes at most ${count(readsInAll)} whole-file ${readsInAll === 1 ? "read" : "reads"}, and this one has made ${readsInAll === 1 ? "it" : "them"}. Use search_document and read_document on ${meta.name}.` };
|
|
1396
|
+
}
|
|
1397
|
+
if (ceiling < Number.POSITIVE_INFINITY) {
|
|
1398
|
+
const left = Math.max(0, ceiling - spentTokens() - reserved.inputTokens);
|
|
1100
1399
|
if (tokens > left)
|
|
1101
|
-
return { refusal: `Not run: reading all of ${meta.name} takes about ${count(tokens)} input tokens, and ${count(left)} are left of the ${count(
|
|
1400
|
+
return { tokens, requests, refusal: `Not run: reading all of ${meta.name} takes about ${count(tokens)} input tokens, and ${count(left)} ${count(left) === "1" ? "is" : "are"} left of the ${count(ceiling)} this question may use. Use search_document and read_document.` };
|
|
1102
1401
|
}
|
|
1103
1402
|
if (limits.requests !== undefined) {
|
|
1104
1403
|
const left = Math.max(0, limits.requests - usage.totals.requests - reserved.requests);
|
|
1105
1404
|
if (requests > left)
|
|
1106
|
-
return { refusal: `Not run: reading all of ${meta.name} takes about ${count(requests)} model requests, and ${count(left)} are left of the ${count(limits.requests)} this question may make. Use search_document and read_document.` };
|
|
1405
|
+
return { tokens, requests, refusal: `Not run: reading all of ${meta.name} takes about ${count(requests)} model requests, and ${count(left)} ${count(left) === "1" ? "is" : "are"} left of the ${count(limits.requests)} this question may make. Use search_document and read_document.` };
|
|
1107
1406
|
}
|
|
1407
|
+
return { tokens, requests };
|
|
1408
|
+
};
|
|
1409
|
+
/**
|
|
1410
|
+
* A whole-file read is many requests at once: one that would pass a ceiling of the question is
|
|
1411
|
+
* not started. `reserved` is what the reads already let through in this turn will take.
|
|
1412
|
+
*/
|
|
1413
|
+
const tooCostly = (call, reserved) => {
|
|
1414
|
+
if (call.name !== TOOL_NAMES.analyze)
|
|
1415
|
+
return {};
|
|
1416
|
+
const meta = searchable.find((document) => document.id === call.args.document_id);
|
|
1417
|
+
// A read of a document read whole as often as it may be takes nothing from the reads of other documents.
|
|
1418
|
+
if (!meta || noReadLeft(meta, reserved))
|
|
1419
|
+
return {};
|
|
1420
|
+
const { refusal, tokens, requests } = readNeeds(meta, reserved, call.args.output === "items" ? "items" : "answer");
|
|
1421
|
+
if (refusal)
|
|
1422
|
+
return { refusal };
|
|
1108
1423
|
reserved.inputTokens += tokens;
|
|
1109
1424
|
// The answer of the question is one request, whatever number of reads come before it.
|
|
1110
1425
|
reserved.requests += requests - 1;
|
|
1111
1426
|
reserved.reads.set(meta.id, (reserved.reads.get(meta.id) ?? 0) + 1);
|
|
1112
|
-
// The read's own requests: its parts, a merge of their notes, and its answer.
|
|
1427
|
+
// The read's own requests: its parts, a merge of their notes, and its answer; or its parts.
|
|
1113
1428
|
return { own: requests - 1 };
|
|
1114
1429
|
};
|
|
1430
|
+
/**
|
|
1431
|
+
* The requests a whole-file read of the document of a `read_document` call may make
|
|
1432
|
+
* (`ToolCallLimits.maxRequests`), judged as on the next turn, the first the model can call it on:
|
|
1433
|
+
* with the reads of this turn reserved, and that turn's request, of the conversation with
|
|
1434
|
+
* `pending` at least (its results are not in it yet). 0 when the question would not start one
|
|
1435
|
+
* then (`noReadLeft`, `readNeeds`), so that a read cut short of its range does not point at it
|
|
1436
|
+
* (`whole_file`); what is left of `limits.requests` with one kept for the answer, when that is
|
|
1437
|
+
* set; undefined otherwise.
|
|
1438
|
+
*/
|
|
1439
|
+
const wholeReadRequests = (call, reserved, pending) => {
|
|
1440
|
+
const meta = searchable.find((document) => document.id === call.args.document_id);
|
|
1441
|
+
if (!meta)
|
|
1442
|
+
return undefined;
|
|
1443
|
+
const nextTurn = meter.current(viewFor(toolModel, [...messages, pending])).tokens * scaleOf(toolModel);
|
|
1444
|
+
const later = { ...reserved, inputTokens: reserved.inputTokens + nextTurn, requests: reserved.requests + 1 };
|
|
1445
|
+
// The hint points at a read that gives an answer, the dearer of the two kinds.
|
|
1446
|
+
if (noReadLeft(meta, later) || readNeeds(meta, later, "answer").refusal !== undefined)
|
|
1447
|
+
return 0;
|
|
1448
|
+
return limits.requests === undefined ? undefined : Math.max(0, limits.requests - usage.totals.requests - 1 - later.requests);
|
|
1449
|
+
};
|
|
1115
1450
|
/**
|
|
1116
1451
|
* A pointer for a call whose result is already in the conversation, in full: an earlier result
|
|
1117
1452
|
* (of this question or of one before it) holds what this one would return. The files do not
|
|
@@ -1126,7 +1461,7 @@ async function ask(options, carried, state) {
|
|
|
1126
1461
|
continue;
|
|
1127
1462
|
// The rounds before `asked` are those of earlier questions, which an older version may have written.
|
|
1128
1463
|
for (const answer of message.answers) {
|
|
1129
|
-
const pointer =
|
|
1464
|
+
const pointer = pointerTo(call, answer, at < asked);
|
|
1130
1465
|
if (pointer)
|
|
1131
1466
|
return pointer;
|
|
1132
1467
|
}
|
|
@@ -1143,6 +1478,19 @@ async function ask(options, carried, state) {
|
|
|
1143
1478
|
const toolRole = explorer ? "explorer" : "tools";
|
|
1144
1479
|
/** A call as one line of plain text. An unknown tool's name is quoted and cut: no step starts with what the model chose, at any length. */
|
|
1145
1480
|
const labelOf = (call) => stepLine(tools.has(call.name) ? tools.describe(call.name, call.args) : `Call ${unknownToolName(call.name)}`);
|
|
1481
|
+
// The tools are there only for tables sent whole (`inlineTables`): without them, the question
|
|
1482
|
+
// would be the one request of 0.9 (and of "text"). It is still that, without the tools, the
|
|
1483
|
+
// line that says to count with them, or a notice, when not one tool turn fits: a ceiling or a
|
|
1484
|
+
// count of requests sized for that one request, or `toolTurns: 1`.
|
|
1485
|
+
const tablesOnly = !explorer && searchable.length === 0 && viewable.length === 0;
|
|
1486
|
+
if (tablesOnly && (1 + (carried?.answered ?? 0) >= maxTurns || spent())) {
|
|
1487
|
+
const plainLine = inlineInstruction({ plan: prepared.plan }, numbered);
|
|
1488
|
+
const plain = [options.system?.trim(), prepared.instruction, plainLine, missingLine].filter(Boolean).join("\n\n");
|
|
1489
|
+
// Its estimate, for a provider that reports no usage: no declarations, its own line.
|
|
1490
|
+
meter.fixed.tokens += -estimateTokens(sentTools) - (inlineLine ? estimateTokens(inlineLine) : 0) + (plainLine ? estimateTokens(plainLine) : 0);
|
|
1491
|
+
meter.fixed.bytes += -Buffer.byteLength(sentTools) - (inlineLine ? jsonBytes(inlineLine) : 0) + (plainLine ? jsonBytes(plainLine) : 0);
|
|
1492
|
+
return answer(wrote(await send(model, () => ({ system: plain, messages }), true, { role: "answer", purpose: "direct" })));
|
|
1493
|
+
}
|
|
1146
1494
|
for (let round = 1 + (carried?.answered ?? 0); round < maxTurns && !outOfRoom; round++) {
|
|
1147
1495
|
if (spent()) {
|
|
1148
1496
|
budgetReached();
|
|
@@ -1156,7 +1504,9 @@ async function ask(options, carried, state) {
|
|
|
1156
1504
|
// It is a request of the chat like any other: it takes a tool turn, and the last turn is still the answer's.
|
|
1157
1505
|
if (reply.calls.length === 0 && nudges < MOST_NUDGES && round + 1 < maxTurns && !reply.blockReason && !spent()) {
|
|
1158
1506
|
const malformed = reply.finish === "malformed_call";
|
|
1159
|
-
|
|
1507
|
+
// Not a reply that a filter, the output limit or another reason that asking again does not
|
|
1508
|
+
// mend ended ("other": Gemini's OTHER, LANGUAGE): it would only end the same way.
|
|
1509
|
+
const empty = !reply.text.trim() && callsAnswered === 0 && reply.finish !== "cut" && reply.finish !== "filtered" && reply.finish !== "other";
|
|
1160
1510
|
if (malformed || empty) {
|
|
1161
1511
|
nudges++;
|
|
1162
1512
|
round++;
|
|
@@ -1168,8 +1518,16 @@ async function ask(options, carried, state) {
|
|
|
1168
1518
|
}
|
|
1169
1519
|
if (reply.calls.length === 0) {
|
|
1170
1520
|
// Text from this turn is the answer. A remark made earlier, before a tool call, is not.
|
|
1171
|
-
// Neither is anything an explorer model writes: the answer is asked for below.
|
|
1172
|
-
|
|
1521
|
+
// Neither is anything an explorer model writes: the answer is asked for below. Nor the
|
|
1522
|
+
// remark of a turn whose tool call could not be read ("Let me look at the errors."), on
|
|
1523
|
+
// the last tool turn or after its nudge: the answer is asked for below.
|
|
1524
|
+
answered = wrote(reply) && !explorer && reply.finish !== "malformed_call";
|
|
1525
|
+
// Over tables sent whole alone, a reply that a filter or another reason that asking again
|
|
1526
|
+
// does not mend ended ("other"), or one cut at the output limit before any text, ends the
|
|
1527
|
+
// question, as it ends the direct request of 0.9: the request for the answer would send
|
|
1528
|
+
// the whole tables again, only to end the same way.
|
|
1529
|
+
if (tablesOnly && !answered && (reply.finish === "filtered" || reply.finish === "other" || reply.finish === "cut"))
|
|
1530
|
+
return answer(false);
|
|
1173
1531
|
break;
|
|
1174
1532
|
}
|
|
1175
1533
|
const pending = { role: "tools", calls: reply.calls, answers: [], ...(reply.raw !== undefined ? { raw: reply.raw } : {}) };
|
|
@@ -1187,6 +1545,11 @@ async function ask(options, carried, state) {
|
|
|
1187
1545
|
// A call that did not arrive whole is not run: the model is told, and can send it again.
|
|
1188
1546
|
if (call.problem)
|
|
1189
1547
|
return { call, label, refusal: call.problem };
|
|
1548
|
+
// Nor a call of a tool the question does not have: it is told which there are, and its
|
|
1549
|
+
// answer takes no room (a turn of unknown calls made room for each of them, at the cap of
|
|
1550
|
+
// a result, and shortened the results of earlier turns for nothing).
|
|
1551
|
+
if (!tools.has(call.name))
|
|
1552
|
+
return { call, label, refusal: unknownTool(call.name, declarations.map((declaration) => declaration.name)) };
|
|
1190
1553
|
// A look at pages returns a file and a few words: the file has its own room, worked out when it runs.
|
|
1191
1554
|
if (call.name === TOOL_NAMES.view)
|
|
1192
1555
|
return { call, label };
|
|
@@ -1214,18 +1577,30 @@ async function ask(options, carried, state) {
|
|
|
1214
1577
|
for (const plan of reads)
|
|
1215
1578
|
plan.limits = { ...plan.limits, maxRequests: plan.own + Math.floor(slack / reads.length) };
|
|
1216
1579
|
}
|
|
1580
|
+
// A read of lines points at a whole read of its file only when the question would start one
|
|
1581
|
+
// on the next turn, past the whole reads of this turn: each is told the requests one may make.
|
|
1582
|
+
for (const plan of planned) {
|
|
1583
|
+
if (plan.refusal || plan.call.name !== TOOL_NAMES.read)
|
|
1584
|
+
continue;
|
|
1585
|
+
const most = wholeReadRequests(plan.call, reserved, pending);
|
|
1586
|
+
if (most !== undefined)
|
|
1587
|
+
plan.limits = { ...plan.limits, maxRequests: most };
|
|
1588
|
+
}
|
|
1217
1589
|
// The calls that return text, and the most they may return: a call that is refused, or
|
|
1218
1590
|
// answered with a pointer to what is already shown, needs no room.
|
|
1219
1591
|
const sized = planned.filter((plan) => !plan.refusal && !plan.pointer && plan.call.name !== TOOL_NAMES.view);
|
|
1220
|
-
|
|
1221
|
-
|
|
1592
|
+
// The room is in tokens, and each result takes those of its document's characters.
|
|
1593
|
+
const rateOf = (call) => 1 / charactersPerToken(metaOf(call.args.document_id));
|
|
1594
|
+
const sizedRates = sized.map((plan) => rateOf(plan.call));
|
|
1595
|
+
const needed = sized.reduce((sum, plan, index) => sum + most(plan.call) * sizedRates[index], 0);
|
|
1596
|
+
let left = room(pending, sizedRates);
|
|
1222
1597
|
let dropped = false;
|
|
1223
1598
|
for (const keep of canShrink ? ROUNDS_KEPT : []) {
|
|
1224
1599
|
if (left >= needed)
|
|
1225
1600
|
break;
|
|
1226
1601
|
if (shrink(keep)) {
|
|
1227
1602
|
dropped = true;
|
|
1228
|
-
left = room(pending);
|
|
1603
|
+
left = room(pending, sizedRates);
|
|
1229
1604
|
}
|
|
1230
1605
|
}
|
|
1231
1606
|
if (dropped) {
|
|
@@ -1248,10 +1623,15 @@ async function ask(options, carried, state) {
|
|
|
1248
1623
|
// The room is shared by those calls. A result is most often far smaller than its cap, so a call
|
|
1249
1624
|
// that was given its whole cap first could leave none for the next ones, and a turn of small
|
|
1250
1625
|
// searches ended the question.
|
|
1251
|
-
const
|
|
1626
|
+
const runRates = runsNow.map((plan) => rateOf(plan.call));
|
|
1627
|
+
const shares = shareRoom(runsNow.map((plan) => most(plan.call)), left, runRates);
|
|
1628
|
+
/** The tokens of room each call that runs was given, by its index in the turn. */
|
|
1629
|
+
const given = new Map();
|
|
1252
1630
|
runsNow.forEach((plan, index) => {
|
|
1253
1631
|
const share = shares[index];
|
|
1254
1632
|
const cap = most(plan.call);
|
|
1633
|
+
if (share !== undefined)
|
|
1634
|
+
given.set(planned.indexOf(plan), share * runRates[index]);
|
|
1255
1635
|
if (share === undefined) {
|
|
1256
1636
|
if (!outOfRoom)
|
|
1257
1637
|
notice("no_room", "There is no room left in this conversation for another tool result.");
|
|
@@ -1437,12 +1817,12 @@ async function ask(options, carried, state) {
|
|
|
1437
1817
|
requestBytes = toolModel.requestBytes?.(waiting) ?? meter.estimate(waiting.messages).bytes;
|
|
1438
1818
|
}
|
|
1439
1819
|
// Base64 turns three bytes into four characters.
|
|
1440
|
-
const output = await tools.executeWithFiles(call.name, call.args, {
|
|
1820
|
+
const output = await until(tools.executeWithFiles(call.name, call.args, {
|
|
1441
1821
|
maxFileBytes: Math.floor((maxRequestBytes - bytesKeptFree - requestBytes) * 3 / 4),
|
|
1442
1822
|
maxPages: pagesLeft,
|
|
1443
1823
|
// A wait that ends busy comes once in a tool turn: after a busy look, the others run only when a turn is free now.
|
|
1444
1824
|
...(pagesBusy ? { maxWaitMs: 0 } : {}),
|
|
1445
|
-
}, hooksFor(index));
|
|
1825
|
+
}, hooksFor(index)), halt.signal);
|
|
1446
1826
|
for (const file of output.files)
|
|
1447
1827
|
requestBytes += Math.ceil(file.bytes.length / 3) * 4 + 512;
|
|
1448
1828
|
if (output.files.length > 0)
|
|
@@ -1458,7 +1838,9 @@ async function ask(options, carried, state) {
|
|
|
1458
1838
|
halt.signal.throwIfAborted();
|
|
1459
1839
|
options.onActivity?.(`${label}…`);
|
|
1460
1840
|
startTool(index, call, label);
|
|
1461
|
-
|
|
1841
|
+
// The question stops when its signal aborts, whether the tool set does or not: a store
|
|
1842
|
+
// call that hangs inside a tool of any `LargeFiles` must not hold it.
|
|
1843
|
+
return await until(tools.executeWithFiles(call.name, call.args, callLimits, hooksFor(index)), halt.signal);
|
|
1462
1844
|
}
|
|
1463
1845
|
finally {
|
|
1464
1846
|
release();
|
|
@@ -1475,6 +1857,48 @@ async function ask(options, carried, state) {
|
|
|
1475
1857
|
output.catch(() => undefined);
|
|
1476
1858
|
outputs.push(output);
|
|
1477
1859
|
}
|
|
1860
|
+
const hook = options.onToolResult;
|
|
1861
|
+
const judgedOutputs = [];
|
|
1862
|
+
for (const [index, { call, refusal, pointer, twinOf }] of planned.entries()) {
|
|
1863
|
+
const raw = outputs[index];
|
|
1864
|
+
let judging;
|
|
1865
|
+
if (hook && pointer && twinOf !== undefined) {
|
|
1866
|
+
judging = Promise.all([raw, judgedOutputs[twinOf]]).then(([own, first]) => (first.judged
|
|
1867
|
+
? { raw: own, output: { result: first.output.result, files: [] }, judged: first.judged, copied: true }
|
|
1868
|
+
: { raw: own, output: own }));
|
|
1869
|
+
}
|
|
1870
|
+
else if (hook && !refusal && !pointer) {
|
|
1871
|
+
judging = raw.then(async (own) => {
|
|
1872
|
+
const context = {
|
|
1873
|
+
call,
|
|
1874
|
+
result: own.result,
|
|
1875
|
+
...(typeof call.args.document_id === "string" ? { documentId: call.args.document_id } : {}),
|
|
1876
|
+
...(options.owner !== undefined ? { owner: options.owner } : {}),
|
|
1877
|
+
...(options.scope !== undefined ? { scope: options.scope } : {}),
|
|
1878
|
+
signal: halt.signal,
|
|
1879
|
+
};
|
|
1880
|
+
let verdict;
|
|
1881
|
+
try {
|
|
1882
|
+
// A hook that does not look at the signal does not hold the question once it is stopped.
|
|
1883
|
+
verdict = checkedVerdict(await until(Promise.resolve().then(() => hook(context)), halt.signal));
|
|
1884
|
+
}
|
|
1885
|
+
catch (error) {
|
|
1886
|
+
halt.abort(error);
|
|
1887
|
+
throw error;
|
|
1888
|
+
}
|
|
1889
|
+
if (verdict && "result" in verdict)
|
|
1890
|
+
return { raw: own, output: { ...own, result: { ...verdict.result, redacted: true } }, judged: "redacted" };
|
|
1891
|
+
if (verdict)
|
|
1892
|
+
return { raw: own, output: { result: { error: verdict.reject }, files: [] }, judged: "refused" };
|
|
1893
|
+
return { raw: own, output: own };
|
|
1894
|
+
});
|
|
1895
|
+
}
|
|
1896
|
+
else {
|
|
1897
|
+
judging = raw.then((own) => ({ raw: own, output: own }));
|
|
1898
|
+
}
|
|
1899
|
+
judging.catch(() => undefined);
|
|
1900
|
+
judgedOutputs.push(judging);
|
|
1901
|
+
}
|
|
1478
1902
|
/**
|
|
1479
1903
|
* The room of each whole-file read of the turn: what the other results left, shared among the
|
|
1480
1904
|
* reads, the smaller answers first. Worked out when the first of them is reached, by which time
|
|
@@ -1482,7 +1906,7 @@ async function ask(options, carried, state) {
|
|
|
1482
1906
|
*/
|
|
1483
1907
|
let lateRoom;
|
|
1484
1908
|
const roomOfReads = async () => {
|
|
1485
|
-
const sizes = await Promise.all(
|
|
1909
|
+
const sizes = await Promise.all(judgedOutputs.map(async (judging) => resultTokens((await judging).output.result)));
|
|
1486
1910
|
const reads = planned.flatMap((plan, index) => (plan.late ? [index] : []));
|
|
1487
1911
|
let free = left - sizes.reduce((sum, size, index) => sum + (planned[index].late ? 0 : size), 0);
|
|
1488
1912
|
const shares = new Map();
|
|
@@ -1493,19 +1917,53 @@ async function ask(options, carried, state) {
|
|
|
1493
1917
|
});
|
|
1494
1918
|
return shares;
|
|
1495
1919
|
};
|
|
1920
|
+
/**
|
|
1921
|
+
* The tokens the results of this turn took so far, of the calls that were given room and are
|
|
1922
|
+
* not whole-file reads (those are fitted to what the others left, above), and of those the
|
|
1923
|
+
* hook replaced. A result is cut when it would take more than the room leaves it once the
|
|
1924
|
+
* calls after it, and the reads, have their shares: the room shared by characters is a
|
|
1925
|
+
* guess, a tool set of your own may not keep to `maxResultCharacters`, and a hook may return
|
|
1926
|
+
* more than the tool did.
|
|
1927
|
+
*/
|
|
1928
|
+
let took = 0;
|
|
1929
|
+
const roomFor = (index) => {
|
|
1930
|
+
let others = 0;
|
|
1931
|
+
for (const [other, tokens] of given)
|
|
1932
|
+
if (other > index || planned[other].late)
|
|
1933
|
+
others += tokens;
|
|
1934
|
+
return left - took - others;
|
|
1935
|
+
};
|
|
1496
1936
|
// The answers in call order. Each call's `tool.end` goes out here, in the same order.
|
|
1497
1937
|
for (const [index, { call, label, late, refusal, pointer }] of planned.entries()) {
|
|
1498
|
-
|
|
1938
|
+
const { raw, output: judgedOutput, judged, copied } = await judgedOutputs[index];
|
|
1499
1939
|
if (listenerError)
|
|
1500
1940
|
throw listenerError.error;
|
|
1941
|
+
// A hook of a later call failed: nothing more of the turn reaches the model.
|
|
1942
|
+
if (halt.signal.aborted)
|
|
1943
|
+
throw halt.signal.reason;
|
|
1501
1944
|
callsAnswered++;
|
|
1945
|
+
// A whole-file read that sent its parts counts against `wholeReadsPerQuestion`, whatever the hook made of its answer.
|
|
1946
|
+
if (!refusal && !pointer && sentParts(call, raw.result)) {
|
|
1947
|
+
const id = String(call.args.document_id);
|
|
1948
|
+
readsSent.set(id, (readsSent.get(id) ?? 0) + 1);
|
|
1949
|
+
}
|
|
1950
|
+
let output = judgedOutput;
|
|
1502
1951
|
if (late) {
|
|
1503
1952
|
lateRoom ??= await roomOfReads();
|
|
1504
1953
|
const share = lateRoom.get(index);
|
|
1505
|
-
if (
|
|
1506
|
-
output = { ...output, result:
|
|
1954
|
+
if (resultTokens(output.result) > share)
|
|
1955
|
+
output = { ...output, result: cutToTokens(output.result, share) };
|
|
1507
1956
|
}
|
|
1508
|
-
if (
|
|
1957
|
+
else if (given.has(index) || judged) {
|
|
1958
|
+
const fits = roomFor(index);
|
|
1959
|
+
if (resultTokens(output.result) > fits)
|
|
1960
|
+
output = { ...output, result: cutToTokens(output.result, fits) };
|
|
1961
|
+
took += resultTokens(output.result);
|
|
1962
|
+
}
|
|
1963
|
+
// A cut replacement is still a replacement.
|
|
1964
|
+
if (judged === "redacted" && output.result.redacted !== true)
|
|
1965
|
+
output = { ...output, result: { ...output.result, redacted: true } };
|
|
1966
|
+
if (pointer && !copied) {
|
|
1509
1967
|
const line = step(`${label} — already shown above`);
|
|
1510
1968
|
const sent = { ...output.result, tool_turns_left: turnsLeft };
|
|
1511
1969
|
answers.push({ call, result: sent, files: [] });
|
|
@@ -1513,14 +1971,16 @@ async function ask(options, carried, state) {
|
|
|
1513
1971
|
continue;
|
|
1514
1972
|
}
|
|
1515
1973
|
// Two searches in a row that failed in the same mode: the second says to try another way.
|
|
1516
|
-
|
|
1974
|
+
// Read from what the tool returned; the hint goes only to a result the hook kept.
|
|
1975
|
+
if (!refusal && !copied) {
|
|
1976
|
+
const own = judged ? raw.result : output.result;
|
|
1517
1977
|
const kind = failureKind(call);
|
|
1518
1978
|
if (kind === undefined) {
|
|
1519
1979
|
failing = undefined;
|
|
1520
1980
|
}
|
|
1521
|
-
else if (typeof
|
|
1981
|
+
else if (typeof own.error === "string") {
|
|
1522
1982
|
failing = failing?.kind === kind ? { kind, count: failing.count + 1 } : { kind, count: 1 };
|
|
1523
|
-
if (failing.count >= 2)
|
|
1983
|
+
if (failing.count >= 2 && !judged)
|
|
1524
1984
|
output = { ...output, result: { ...output.result, error: `${output.result.error} ${repeatedFailureHint(call)}` } };
|
|
1525
1985
|
}
|
|
1526
1986
|
else {
|
|
@@ -1528,12 +1988,13 @@ async function ask(options, carried, state) {
|
|
|
1528
1988
|
}
|
|
1529
1989
|
}
|
|
1530
1990
|
const line = step(`${label}${toolResultSummary(label, output.result)}`);
|
|
1531
|
-
|
|
1991
|
+
// A copy of the first call's verdict shows nothing that the first did not.
|
|
1992
|
+
const shown = copied ? undefined : evidenceOf(call, output.result);
|
|
1532
1993
|
if (shown)
|
|
1533
1994
|
evidence.push({ ...shown, callId: callIds[index] });
|
|
1534
1995
|
const sent = { ...output.result, tool_turns_left: turnsLeft };
|
|
1535
1996
|
answers.push({ call, result: sent, files: output.files });
|
|
1536
|
-
const outcome = call.problem ? "error" : refusal ? "refused" : typeof output.result.error === "string" ? "error" : "ok";
|
|
1997
|
+
const outcome = judged ?? (call.problem ? "error" : refusal ? "refused" : typeof output.result.error === "string" ? "error" : "ok");
|
|
1537
1998
|
endTool(index, outcome, sent, line, shown);
|
|
1538
1999
|
}
|
|
1539
2000
|
// A listener of a read that went on after its call returned (its progress).
|
|
@@ -1568,7 +2029,12 @@ async function ask(options, carried, state) {
|
|
|
1568
2029
|
// With an explorer model this request is always made: it is the one the answering model gets.
|
|
1569
2030
|
if (!answered && !blockReason) {
|
|
1570
2031
|
activity("writing_answer", "Writing the answer…");
|
|
1571
|
-
|
|
2032
|
+
// With view_pages alone, the files are in the prompt and the pages were looked at. With the
|
|
2033
|
+
// text tools, the answer comes from what they returned, and from the files sent whole too when
|
|
2034
|
+
// their lines can be cited or their tables were counted: a model told "only what the tools
|
|
2035
|
+
// returned" said that a fact of a file shown in full was not there.
|
|
2036
|
+
const fromFiles = prepared.plan.inline.length > 0 && (numbered || toolable.length > 0);
|
|
2037
|
+
let closing = searchable.length === 0 && toolable.length === 0 ? FINAL_ANSWER_AFTER_PAGES : fromFiles ? FINAL_ANSWER_WITH_FILES : FINAL_ANSWER_REQUEST;
|
|
1572
2038
|
// No tool ran (the explorer needed none, the first reply was empty, or no turn was left for
|
|
1573
2039
|
// tools): there is no tool result to answer from. The answering model gets the explorer's
|
|
1574
2040
|
// calls and what they returned, and nothing else of it.
|
|
@@ -1583,14 +2049,17 @@ async function ask(options, carried, state) {
|
|
|
1583
2049
|
let reply = await send(model, answerRequest(), true, { role: "answer", purpose: "closing" });
|
|
1584
2050
|
// A reply with no text (empty, or a tool call the model was told not to make, or one that
|
|
1585
2051
|
// could not be read) is asked for once more, with a note that is not kept: otherwise the
|
|
1586
|
-
// question ends with nothing to show. Not after a refusal
|
|
1587
|
-
//
|
|
1588
|
-
//
|
|
1589
|
-
//
|
|
2052
|
+
// question ends with nothing to show. Not after a refusal, a filter or another reason that
|
|
2053
|
+
// asking again does not mend ("other"), which would come again, nor a reply cut off at the
|
|
2054
|
+
// output limit with nothing in it, nor when it would pass a ceiling of the question: the
|
|
2055
|
+
// ceiling of input tokens looks ahead, as before each tool request, by what was spent and
|
|
2056
|
+
// what this request takes, as the meter counts it now. It is one of the second tries of the
|
|
2057
|
+
// question, and may be one request past `limits.toolTurns`, which counts the answer's first
|
|
2058
|
+
// request.
|
|
1590
2059
|
const calledInstead = reply.calls.length > 0 || reply.finish === "malformed_call";
|
|
1591
|
-
const
|
|
1592
|
-
|
|
1593
|
-
if (!wrote(reply) && !reply.blockReason && reply.finish !== "filtered" && (calledInstead || reply.finish !== "cut") && nudges < MOST_NUDGES) {
|
|
2060
|
+
const again = ceiling < Number.POSITIVE_INFINITY ? meter.current(viewFor(model)).tokens * scaleOf(model) : 0;
|
|
2061
|
+
const ceilingReached = spentTokens() + again > ceiling || (limits.requests !== undefined && usage.totals.requests >= limits.requests);
|
|
2062
|
+
if (!wrote(reply) && !reply.blockReason && reply.finish !== "filtered" && reply.finish !== "other" && (calledInstead || reply.finish !== "cut") && nudges < MOST_NUDGES) {
|
|
1594
2063
|
if (ceilingReached) {
|
|
1595
2064
|
budgetReached();
|
|
1596
2065
|
}
|
|
@@ -1602,7 +2071,7 @@ async function ask(options, carried, state) {
|
|
|
1602
2071
|
}
|
|
1603
2072
|
answered = wrote(reply);
|
|
1604
2073
|
}
|
|
1605
|
-
return
|
|
2074
|
+
return answer(answered);
|
|
1606
2075
|
}
|
|
1607
2076
|
catch (error) {
|
|
1608
2077
|
// What the question found and paid for until it failed, for the application to keep. The usage is
|