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/src/ask.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
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, type AskEvent, type DocumentRef, type EventResult, type EventStream, type NoticeCode, type RequestPurpose, type RequestRole, type ToolOutcome } from "./events.js";
|
|
4
|
+
import { checkCitations, type CitationCheck } from "./citations.js";
|
|
4
5
|
import { evidenceOf, stubResult, type Evidence } from "./evidence.js";
|
|
5
6
|
import { isCutReply, until } from "./http.js";
|
|
6
7
|
import type { LargeFiles } from "./library.js";
|
|
@@ -11,6 +12,7 @@ import {
|
|
|
11
12
|
laterResult,
|
|
12
13
|
modelErrorOf,
|
|
13
14
|
rateAllowanceOf,
|
|
15
|
+
reportsInput,
|
|
14
16
|
TOOL_TURN_VERSION,
|
|
15
17
|
UsageMeter,
|
|
16
18
|
type ChatMessage,
|
|
@@ -26,7 +28,8 @@ import {
|
|
|
26
28
|
type UsageTotals,
|
|
27
29
|
} from "./model.js";
|
|
28
30
|
import { DocumentStoreError } from "./errors.js";
|
|
29
|
-
import { estimateParts, REQUEST_BYTES_MARGIN } from "./plan.js";
|
|
31
|
+
import { canBeReadWhole, estimateParts, inlineInstruction, questionTools, REQUEST_BYTES_MARGIN } from "./plan.js";
|
|
32
|
+
import { preparedHere } from "./prepare.js";
|
|
30
33
|
import { statusOf, withRetry, type RetryNotice, type RetryOptions } from "./retry.js";
|
|
31
34
|
import { estimateTokens, jsonBytes, wellFormedJson } from "./text.js";
|
|
32
35
|
import {
|
|
@@ -42,10 +45,17 @@ import {
|
|
|
42
45
|
toolResultSummary,
|
|
43
46
|
unknownToolName,
|
|
44
47
|
} from "./tools.js";
|
|
45
|
-
import type { Budget, DocumentMeta, DocumentPlan, DocumentScope, GenerateText, PreparedContext, ToolCallHooks, ToolCallLimits, ToolOutput, ToolRequestEnd, ToolRequestHandle, ToolRequestStart, ToolResult } from "./types.js";
|
|
48
|
+
import type { Budget, DocumentFormat, DocumentMeta, DocumentPlan, DocumentScope, GenerateText, PreparedContext, ToolCallHooks, ToolCallLimits, ToolOutput, ToolRequestEnd, ToolRequestHandle, ToolRequestStart, ToolResult } from "./types.js";
|
|
49
|
+
import { wholeReadCost } from "./whole-cost.js";
|
|
46
50
|
|
|
47
51
|
/** Sent (invisibly to the user) when the model must stop using tools and answer. */
|
|
48
52
|
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.";
|
|
53
|
+
/**
|
|
54
|
+
* The same, when files were also sent whole and the tools can read them or their lines are
|
|
55
|
+
* numbered (`inlineTables`, `numberInline`): what they say is part of the answer too, not only what
|
|
56
|
+
* the tools returned. New in 0.10.0. Not exported from the package.
|
|
57
|
+
*/
|
|
58
|
+
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.";
|
|
49
59
|
/** The same, when the only tool was `view_pages`: the text of the files is in the prompt, not in tool results. */
|
|
50
60
|
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.";
|
|
51
61
|
/**
|
|
@@ -59,6 +69,16 @@ export const FINAL_ANSWER_WITHOUT_TOOLS = "Answer my question now, from what is
|
|
|
59
69
|
*/
|
|
60
70
|
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.";
|
|
61
71
|
|
|
72
|
+
/**
|
|
73
|
+
* The least ceiling on the input tokens of a question that sets no `limits.inputTokens`. Its
|
|
74
|
+
* ceiling is the larger of this and `toolTurns` times its first request, with the room for its
|
|
75
|
+
* whole-file reads added. New in 0.10.0.
|
|
76
|
+
*/
|
|
77
|
+
export const DEFAULT_INPUT_TOKENS = 1_000_000;
|
|
78
|
+
|
|
79
|
+
/** How many whole-file reads one question may make, over all its documents, by default (`limits.wholeReadsPerQuestion`). */
|
|
80
|
+
const DEFAULT_WHOLE_READS_PER_QUESTION = 2;
|
|
81
|
+
|
|
62
82
|
/** The limits of one question. */
|
|
63
83
|
export type AskLimits = {
|
|
64
84
|
/**
|
|
@@ -82,12 +102,25 @@ export type AskLimits = {
|
|
|
82
102
|
wholeDocumentReads?: number;
|
|
83
103
|
/**
|
|
84
104
|
* A ceiling on the input tokens of one question, over all its requests, whole-file part reads
|
|
85
|
-
* included
|
|
86
|
-
*
|
|
105
|
+
* included, in the models' own tokens. Before each tool request the loop looks ahead: when what
|
|
106
|
+
* was spent, that request and the answer's request would pass it, no more tools run and the next
|
|
107
|
+
* request is the answer. A whole-file read that would pass it is refused. A request whose
|
|
108
|
+
* provider reports no input counts by the library's estimate (`UsageTotals.estimatedInputTokens`).
|
|
109
|
+
* Unset (since 0.10.0): the larger of `DEFAULT_INPUT_TOKENS` and `toolTurns` times the estimate
|
|
110
|
+
* of the question's first request, plus room for its whole-file reads: as many as
|
|
111
|
+
* `wholeReadsPerQuestion` and the documents allow, each at the price of the dearest one.
|
|
112
|
+
* `Infinity`: no ceiling, as before 0.10.0.
|
|
87
113
|
*/
|
|
88
114
|
inputTokens?: number;
|
|
89
115
|
/** The same ceiling, on the number of model requests: the chat's and the part reads' together. */
|
|
90
116
|
requests?: number;
|
|
117
|
+
/**
|
|
118
|
+
* How many whole-file reads (`analyze_whole_document`) one question may make over all its
|
|
119
|
+
* documents, next to `wholeDocumentReads` for each one. A read that sent requests counts, one
|
|
120
|
+
* that failed among them. Defaults to 2; `Infinity` keeps the rule of 0.9, one read of each
|
|
121
|
+
* document. New in 0.10.0.
|
|
122
|
+
*/
|
|
123
|
+
wholeReadsPerQuestion?: number;
|
|
91
124
|
};
|
|
92
125
|
|
|
93
126
|
export type AskOptions = {
|
|
@@ -100,7 +133,8 @@ export type AskOptions = {
|
|
|
100
133
|
/**
|
|
101
134
|
* A second model that explores the documents: it makes the tool calls (search, read, look at
|
|
102
135
|
* pages) and reads a whole file in parts. It may be of another provider than `model`. Left out,
|
|
103
|
-
* or the same adapter as `model`: one model does both.
|
|
136
|
+
* or the same adapter as `model`: one model does both. Since 0.10.0 it is not used when no file
|
|
137
|
+
* is searched and the tools are there for tables sent whole (`inlineTables`): `model` runs them.
|
|
104
138
|
*/
|
|
105
139
|
explorer?: ModelAdapter | undefined;
|
|
106
140
|
/** Documents this conversation may use. Where their text or cards go: see `documentPlacement`. */
|
|
@@ -112,6 +146,38 @@ export type AskOptions = {
|
|
|
112
146
|
* document then moves on every turn and is billed in full each time.
|
|
113
147
|
*/
|
|
114
148
|
documentPlacement?: "first" | "last";
|
|
149
|
+
/**
|
|
150
|
+
* "tools": a table sent whole (a CSV, a workbook, a file with `| cell |` rows) can still be
|
|
151
|
+
* counted and searched: the question gets `search_document`, `read_document` and
|
|
152
|
+
* `aggregate_table` for it, and runs the tool loop. When no file is searched, `model` runs that
|
|
153
|
+
* loop itself, without the explorer, so a question that needs no count is still answered in one
|
|
154
|
+
* request. "text": it is sent whole without tools, as in 0.9. Defaults to "tools". New in 0.10.0.
|
|
155
|
+
*/
|
|
156
|
+
inlineTables?: "tools" | "text";
|
|
157
|
+
/**
|
|
158
|
+
* Number the lines of the files sent whole, as the tools number them ("12| "), so that the answer
|
|
159
|
+
* can cite them. When no file is searched, the system text asks for citations like
|
|
160
|
+
* "(report.docx L12)". Defaults to true; false sends them as in 0.9. New in 0.10.0.
|
|
161
|
+
*/
|
|
162
|
+
numberInline?: boolean;
|
|
163
|
+
/**
|
|
164
|
+
* What to do with an answer that a filter of the provider stopped (`AskResult.finish`
|
|
165
|
+
* "filtered"): "keep" (the default) keeps its text, as in 0.9; "drop" gives `answered: false` and
|
|
166
|
+
* `text: ""`. Text already sent through `onText` and `text` events cannot be taken back: the
|
|
167
|
+
* "answer_filtered" notice then says `discardText`, before `run.finish`. New in 0.10.0.
|
|
168
|
+
*/
|
|
169
|
+
filteredAnswer?: "keep" | "drop";
|
|
170
|
+
/**
|
|
171
|
+
* Called with the result of every tool call that ran, before the model, the evidence, the steps
|
|
172
|
+
* and the events get it: return `{ result }` to send another result (it is sent with
|
|
173
|
+
* `redacted: true`, and the call's outcome is "redacted"), `{ reject: "why" }` to send
|
|
174
|
+
* `{ error: "why" }` in its place (outcome "refused"), or undefined to keep it. What it throws, or
|
|
175
|
+
* a value of another shape, ends the question. Each call's hook is called as soon as its result
|
|
176
|
+
* is in, so those of one turn may run at the same time; the verdicts are applied in call order,
|
|
177
|
+
* and what they let through is then fitted to the room in the request. The parts of a whole-file
|
|
178
|
+
* read go to the model that reads them, not through this. New in 0.10.0.
|
|
179
|
+
*/
|
|
180
|
+
onToolResult?: (context: ToolResultContext) => ToolResultVerdict | undefined | Promise<ToolResultVerdict | undefined>;
|
|
115
181
|
/**
|
|
116
182
|
* The conversation; the last message must be the user's question. Plain turns
|
|
117
183
|
* (`{ role, text }`), the tool rounds an earlier question returned (`AskResult.toolTurns`), and
|
|
@@ -201,16 +267,23 @@ export type AskResult = {
|
|
|
201
267
|
*/
|
|
202
268
|
text: string;
|
|
203
269
|
/**
|
|
204
|
-
* False when the
|
|
205
|
-
*
|
|
206
|
-
*
|
|
270
|
+
* False when the reply that should be the answer had no text: the prompt was blocked, or the
|
|
271
|
+
* reply was cut off or filtered before any text. A turn whose tool call could not be read is
|
|
272
|
+
* not an answer either, even with text: the answer is asked for once more. With
|
|
273
|
+
* `filteredAnswer: "drop"`, false for a filtered answer too. `text` may then be empty or hold
|
|
274
|
+
* only an earlier remark, so show your own message instead of treating it as the answer
|
|
275
|
+
* (`answerInfoOf` says which).
|
|
207
276
|
*/
|
|
208
277
|
answered: boolean;
|
|
209
278
|
/** Why the provider refused the prompt, when it did. */
|
|
210
279
|
blockReason?: string;
|
|
211
280
|
/** Every tool step taken, in order (also delivered through `onStep`). */
|
|
212
281
|
steps: string[];
|
|
213
|
-
/**
|
|
282
|
+
/**
|
|
283
|
+
* What the model was shown: first each file sent whole, in the order of its block (`tool`
|
|
284
|
+
* "inline", every line, `whole: true`, no `callId`; since 0.10.0), then what each tool call
|
|
285
|
+
* showed, the document and the lines or pages, in call order.
|
|
286
|
+
*/
|
|
214
287
|
evidence: Evidence[];
|
|
215
288
|
/**
|
|
216
289
|
* The tool rounds of this question as plain JSON. Kept with the conversation and passed back in
|
|
@@ -234,8 +307,32 @@ export type AskResult = {
|
|
|
234
307
|
usage: UsageTotals;
|
|
235
308
|
/** The provider's own usage object of the last chat response, as it came. */
|
|
236
309
|
lastUsage?: Record<string, unknown>;
|
|
310
|
+
/**
|
|
311
|
+
* How the reply whose text is the answer ended (`ModelReply.finish`), or the last reply of the
|
|
312
|
+
* chat when none answered. Absent when the adapter does not say. A "filtered" or "cut" answer
|
|
313
|
+
* also has an "answer_filtered" or "answer_cut" notice. New in 0.10.0.
|
|
314
|
+
*/
|
|
315
|
+
finish?: ModelReply["finish"];
|
|
316
|
+
/**
|
|
317
|
+
* The line citations of `text`, checked against what the tools showed (`checkCitations`): a
|
|
318
|
+
* document sent whole counts as shown. Set when the question had documents. New in 0.10.0.
|
|
319
|
+
*/
|
|
320
|
+
citations?: CitationCheck;
|
|
237
321
|
};
|
|
238
322
|
|
|
323
|
+
/**
|
|
324
|
+
* What `AskOptions.onToolResult` is given: the call and its result, as the tool returned it (before
|
|
325
|
+
* it is fitted to the room in the request), the document it names, who asks, and a signal that
|
|
326
|
+
* aborts when the question is stopped or fails. New in 0.10.0.
|
|
327
|
+
*/
|
|
328
|
+
export type ToolResultContext = { call: ToolCall; result: ToolResult; documentId?: string; owner?: string; scope?: DocumentScope; signal: AbortSignal };
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* What `AskOptions.onToolResult` returns: `{ result }` sends that result in place of the tool's,
|
|
332
|
+
* and `{ reject }` sends `{ error: reject }`. Undefined keeps the tool's result. New in 0.10.0.
|
|
333
|
+
*/
|
|
334
|
+
export type ToolResultVerdict = { result: ToolResult } | { reject: string };
|
|
335
|
+
|
|
239
336
|
/**
|
|
240
337
|
* What `AskOptions.onMissingDocuments` says to do with the documents that are missing:
|
|
241
338
|
* - "throw": fail the question with `DocumentsNotFoundError`;
|
|
@@ -263,6 +360,36 @@ function checkMissingPolicy(given: unknown): void {
|
|
|
263
360
|
throw new TypeError(`onMissingDocuments must be "throw", "drop" or a function, and is ${shownValue(given)}.`);
|
|
264
361
|
}
|
|
265
362
|
|
|
363
|
+
/**
|
|
364
|
+
* `filteredAnswer` checked: a value it cannot be ("Drop", true) is an error before anything is
|
|
365
|
+
* planned. It would otherwise keep a filtered answer that the application meant to drop.
|
|
366
|
+
*/
|
|
367
|
+
function checkFilteredAnswer(given: unknown): void {
|
|
368
|
+
if (given === undefined || given === "keep" || given === "drop") return;
|
|
369
|
+
throw new TypeError(`filteredAnswer must be "keep" or "drop", and is ${shownValue(given)}.`);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* `inlineTables` and `numberInline` checked: a value they cannot be ("Text", "false") is an error
|
|
374
|
+
* before anything is planned, as `prepare` would throw it, but in the words of the question.
|
|
375
|
+
*/
|
|
376
|
+
function checkInlineOptions(tables: unknown, numbered: unknown): void {
|
|
377
|
+
if (tables !== undefined && tables !== "tools" && tables !== "text") throw new TypeError(`inlineTables must be "tools" or "text", and is ${shownValue(tables)}.`);
|
|
378
|
+
if (numbered !== undefined && typeof numbered !== "boolean") throw new TypeError(`numberInline must be true or false, and is ${shownValue(numbered)}.`);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* The evidence of a document sent whole (since 0.10.0): every line of it was shown. It comes from
|
|
383
|
+
* no tool call, so it has no `callId`.
|
|
384
|
+
*/
|
|
385
|
+
const sentWhole = (meta: DocumentMeta): Evidence => ({
|
|
386
|
+
tool: "inline",
|
|
387
|
+
documentId: meta.id,
|
|
388
|
+
document: meta.name,
|
|
389
|
+
...(Number.isFinite(meta.lines) && meta.lines >= 1 ? { lines: [[1, Math.trunc(meta.lines)]] } : {}),
|
|
390
|
+
whole: true,
|
|
391
|
+
});
|
|
392
|
+
|
|
266
393
|
/** An object made as `{}` or `Object.create(null)` is: not a Map, an array or an instance of a class. */
|
|
267
394
|
const isPlainObject = (value: unknown): value is Record<string, unknown> => {
|
|
268
395
|
if (value === null || typeof value !== "object") return false;
|
|
@@ -284,6 +411,26 @@ function checkedAction(action: unknown): MissingDocumentsAction {
|
|
|
284
411
|
throw new TypeError(`onMissingDocuments returned ${shownValue(action)}: it must return "throw", "drop", { retry: true } or { replace: { [oldId]: newId } }.`);
|
|
285
412
|
}
|
|
286
413
|
|
|
414
|
+
/**
|
|
415
|
+
* What `onToolResult` returned, checked: undefined, `{ result }` with a result that is an object,
|
|
416
|
+
* or `{ reject }` with a string. A verdict with a `result` is a result, whatever else it holds.
|
|
417
|
+
* Anything else ends the question: the hook is there to keep something from the model, and a
|
|
418
|
+
* mistake in it must not let the result through.
|
|
419
|
+
*/
|
|
420
|
+
function checkedVerdict(verdict: unknown): ToolResultVerdict | undefined {
|
|
421
|
+
if (verdict === undefined) return undefined;
|
|
422
|
+
if (verdict !== null && typeof verdict === "object") {
|
|
423
|
+
if (Object.hasOwn(verdict, "result")) {
|
|
424
|
+
const { result } = verdict as { result: unknown };
|
|
425
|
+
if (result !== null && typeof result === "object" && !Array.isArray(result)) return { result: result as ToolResult };
|
|
426
|
+
} else if (Object.hasOwn(verdict, "reject")) {
|
|
427
|
+
const { reject } = verdict as { reject: unknown };
|
|
428
|
+
if (typeof reject === "string") return { reject };
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
throw new TypeError(`onToolResult returned ${shownValue(verdict)}: it must return { result }, { reject: "why" } or undefined.`);
|
|
432
|
+
}
|
|
433
|
+
|
|
287
434
|
/** The documents of a question once `onMissingDocuments` had its say. */
|
|
288
435
|
type PlannedDocuments = {
|
|
289
436
|
prepared: PreparedContext;
|
|
@@ -333,14 +480,60 @@ const DEFAULT_CALLS_PER_TURN = 8;
|
|
|
333
480
|
const CALLS_AT_ONCE = 4;
|
|
334
481
|
/** With less room than this for its result, a call is not run. */
|
|
335
482
|
const LEAST_ROOM_CHARACTERS = 1_500;
|
|
336
|
-
/**
|
|
483
|
+
/**
|
|
484
|
+
* Characters of a tool result for each token of room, when the call names no document of the
|
|
485
|
+
* question. Since 0.10.0 a call that names one takes its document's own (`charactersPerToken`).
|
|
486
|
+
*/
|
|
337
487
|
const CHARACTERS_PER_TOKEN = 2;
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* The characters of a document's text for each token of the estimate, as its ingest counted them,
|
|
491
|
+
* from 0.8 to 4: about 0.9 for a table of numbers, 1.4 for a service log, 1.9 for Hebrew prose.
|
|
492
|
+
* The JSON of a tool result that quotes the text comes to about the same. `CHARACTERS_PER_TOKEN`
|
|
493
|
+
* when the metadata does not say. New in 0.10.0.
|
|
494
|
+
*/
|
|
495
|
+
function charactersPerToken(meta: Pick<DocumentMeta, "characters" | "estimatedTokens"> | undefined): number {
|
|
496
|
+
const ratio = meta && meta.estimatedTokens > 0 ? meta.characters / meta.estimatedTokens : Number.NaN;
|
|
497
|
+
return Number.isFinite(ratio) ? Math.min(4, Math.max(0.8, ratio)) : CHARACTERS_PER_TOKEN;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** The tokens of room a tool result takes in a request, as the request meter counts an answer. */
|
|
501
|
+
const resultTokens = (result: ToolResult): number => estimateTokens(JSON.stringify(result)) + 8;
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* `result` cut to `tokens` of room (`resultTokens`): by `fitAnswer`, to the characters its own
|
|
505
|
+
* characters per token give, and a little less again while it is still over. Never below
|
|
506
|
+
* `LEAST_RESULT_CHARACTERS`.
|
|
507
|
+
*/
|
|
508
|
+
function cutToTokens(result: ToolResult, tokens: number): ToolResult {
|
|
509
|
+
const json = JSON.stringify(result);
|
|
510
|
+
const perToken = json.length / Math.max(1, resultTokens(result));
|
|
511
|
+
let characters = Math.max(LEAST_RESULT_CHARACTERS, Math.floor(tokens * perToken));
|
|
512
|
+
let cut = fitAnswer(result, characters);
|
|
513
|
+
for (let tries = 0; tries < 4 && resultTokens(cut) > tokens && characters > LEAST_RESULT_CHARACTERS; tries++) {
|
|
514
|
+
characters = Math.max(LEAST_RESULT_CHARACTERS, Math.floor(characters * 0.85));
|
|
515
|
+
cut = fitAnswer(result, characters);
|
|
516
|
+
}
|
|
517
|
+
return cut;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* `alreadyShown`, but never a pointer to a result that `onToolResult` replaced (`redacted: true`):
|
|
522
|
+
* it does not hold what the call would return.
|
|
523
|
+
*/
|
|
524
|
+
function pointerTo(call: { name: string; args: Record<string, unknown> }, earlier: { call: { name: string; args: Record<string, unknown> }; result: ToolResult }, stored = false): ToolResult | undefined {
|
|
525
|
+
return earlier.result.redacted === true ? undefined : alreadyShown(call, earlier, stored);
|
|
526
|
+
}
|
|
338
527
|
/** Bytes a character of a tool result may take in the request. */
|
|
339
528
|
const BYTES_PER_CHARACTER = 3;
|
|
340
529
|
/** Tool rounds whose results are kept in full when older ones are dropped to make room. */
|
|
341
530
|
const ROUNDS_KEPT = [3, 2, 1];
|
|
342
531
|
|
|
343
532
|
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.";
|
|
533
|
+
/** How the error of a whole-file read that sent its parts, and could read none of them, begins (`NothingReadError`). */
|
|
534
|
+
const NOTHING_READ = "Could not read any part of ";
|
|
535
|
+
/** 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. */
|
|
536
|
+
const unknownTool = (name: string, tools: string[]) => `Unknown tool ${unknownToolName(name)}. The tools are: ${tools.join(", ")}.`;
|
|
344
537
|
/** Why a request of a whole-file read that its read left behind ended with its call. */
|
|
345
538
|
const CALL_ENDED = "The tool call ended before this request did.";
|
|
346
539
|
|
|
@@ -511,23 +704,30 @@ class RequestMeter {
|
|
|
511
704
|
}
|
|
512
705
|
|
|
513
706
|
/**
|
|
514
|
-
* Shares `room`
|
|
515
|
-
*
|
|
516
|
-
*
|
|
517
|
-
*
|
|
707
|
+
* Shares `room` among tool calls whose results may be up to `caps` characters. A character of the
|
|
708
|
+
* result of call i takes `rates[i]` of the room (1 when `rates` is left out: the room is in
|
|
709
|
+
* characters; since 0.10.0 the loop gives it in tokens, and each call the tokens a character of its
|
|
710
|
+
* document takes). A call gets no more than its cap, and the others split what it leaves. Calls
|
|
711
|
+
* that cannot each get `LEAST_ROOM_CHARACTERS` (or their cap, when it is smaller) are not run, the
|
|
712
|
+
* last ones first: their share is undefined. The shares are in characters.
|
|
518
713
|
*/
|
|
519
|
-
export function shareRoom(caps: number[], room: number): Array<number | undefined> {
|
|
520
|
-
const
|
|
714
|
+
export function shareRoom(caps: number[], room: number, rates?: number[]): Array<number | undefined> {
|
|
715
|
+
const rate = (index: number) => rates?.[index] ?? 1;
|
|
716
|
+
const least = (cap: number, index: number) => Math.min(cap, LEAST_ROOM_CHARACTERS) * rate(index);
|
|
521
717
|
let count = caps.length;
|
|
522
|
-
let needed = caps.reduce((sum, cap) => sum + least(cap), 0);
|
|
523
|
-
while (count > 0 && needed > room)
|
|
718
|
+
let needed = caps.reduce((sum, cap, index) => sum + least(cap, index), 0);
|
|
719
|
+
while (count > 0 && needed > room) {
|
|
720
|
+
count--;
|
|
721
|
+
needed -= least(caps[count]!, count);
|
|
722
|
+
}
|
|
524
723
|
const shares: Array<number | undefined> = caps.map(() => undefined);
|
|
525
724
|
// The smallest caps first: each call takes its cap or an even share of what is left, whichever is less.
|
|
526
|
-
const order = caps.slice(0, count).map((cap, index) => ({ cap, index })).sort((left, right) => left.cap - right.cap);
|
|
725
|
+
const order = caps.slice(0, count).map((cap, index) => ({ cap: cap * rate(index), index })).sort((left, right) => left.cap - right.cap);
|
|
527
726
|
let left = Math.max(0, Math.floor(room));
|
|
528
727
|
order.forEach(({ cap, index }, position) => {
|
|
529
728
|
const share = Math.min(cap, Math.floor(left / (order.length - position)));
|
|
530
|
-
|
|
729
|
+
// A call given its whole cap gets the cap as it is, not as it comes back from the rate.
|
|
730
|
+
shares[index] = share === cap ? caps[index]! : Math.floor(share / rate(index));
|
|
531
731
|
left -= share;
|
|
532
732
|
});
|
|
533
733
|
return shares;
|
|
@@ -628,7 +828,7 @@ const MOST_OVERFLOW_RECOVERIES = 2;
|
|
|
628
828
|
* so it turned off the ceilings and the cap on whole-file reads, or every tool.
|
|
629
829
|
*/
|
|
630
830
|
function checkedLimits(given: AskLimits | undefined): AskLimits {
|
|
631
|
-
for (const field of ["toolTurns", "callsPerTurn", "wholeDocumentReads", "inputTokens", "requests"] as const) {
|
|
831
|
+
for (const field of ["toolTurns", "callsPerTurn", "wholeDocumentReads", "inputTokens", "requests", "wholeReadsPerQuestion"] as const) {
|
|
632
832
|
const value: unknown = given?.[field];
|
|
633
833
|
if (value === undefined) continue;
|
|
634
834
|
if (typeof value !== "number") throw new TypeError(`limits.${field} must be a number, and is ${typeof value === "string" ? JSON.stringify(value) : typeof value}.`);
|
|
@@ -704,13 +904,22 @@ export async function askWithFiles(options: AskOptions): Promise<AskResult> {
|
|
|
704
904
|
* A result as `run.finish` and `run.error` carry it: a copy, so that a listener cannot change the
|
|
705
905
|
* caller's, without the tool rounds and with the plan naming documents only (both hold text of
|
|
706
906
|
* the documents: tool results, outline headings, the commonest lines of a log) unless `withTurns`.
|
|
907
|
+
* Its plan never holds the owner, scope, SHA-256 or original of a document.
|
|
707
908
|
*/
|
|
708
909
|
function eventResultOf(result: AskResult, withTurns: boolean): EventResult {
|
|
709
|
-
|
|
710
|
-
|
|
910
|
+
const { toolTurns, plan, ...rest } = result;
|
|
911
|
+
// The full metadata only with `withTurns`, and never what is to stay on the server: who owns a
|
|
912
|
+
// document, its scope, the SHA-256 and the ref of its original.
|
|
913
|
+
if (withTurns) return { ...rest, toolTurns, plan: { inline: plan.inline.map(withoutServerFields), searchable: plan.searchable.map(withoutServerFields) } };
|
|
711
914
|
return { ...rest, plan: { inline: plan.inline.map(documentRef), searchable: plan.searchable.map(documentRef) } };
|
|
712
915
|
}
|
|
713
916
|
|
|
917
|
+
/** A document's metadata without what is to stay on the server, for an event (since 0.10.0). */
|
|
918
|
+
function withoutServerFields(meta: DocumentMeta): Omit<DocumentMeta, "owner" | "scope" | "sha256" | "original" | "metaVersion"> {
|
|
919
|
+
const { owner: _owner, scope: _scope, sha256: _sha256, original: _original, metaVersion: _metaVersion, ...rest } = meta;
|
|
920
|
+
return rest;
|
|
921
|
+
}
|
|
922
|
+
|
|
714
923
|
/**
|
|
715
924
|
* `askWithFiles` as a stream of its events, for a page that shows the question as it goes: see
|
|
716
925
|
* `AskEvent`. Leaving the loop early (`break`) stops the question. `result` is what `askWithFiles`
|
|
@@ -761,12 +970,18 @@ async function askPlanned(options: AskOptions, state: RunState): Promise<AskResu
|
|
|
761
970
|
async function ask(options: AskOptions, carried: Carried | undefined, state: RunState): Promise<AskResult> {
|
|
762
971
|
const { files, model, signal } = options;
|
|
763
972
|
const { events } = state;
|
|
764
|
-
// A second model for the requests that use tools. The answering model itself is not one.
|
|
765
|
-
|
|
766
|
-
const
|
|
767
|
-
const models =
|
|
973
|
+
// A second model for the requests that use tools. The answering model itself is not one. It
|
|
974
|
+
// explores only when a file is searched (see `explorer` below), but the budget is fitted to it.
|
|
975
|
+
const given = options.explorer && options.explorer !== model ? options.explorer : undefined;
|
|
976
|
+
const models = given ? [model, given] : [model];
|
|
768
977
|
const limits = checkedLimits(options.limits);
|
|
769
978
|
checkMissingPolicy(options.onMissingDocuments);
|
|
979
|
+
checkFilteredAnswer(options.filteredAnswer);
|
|
980
|
+
checkInlineOptions(options.inlineTables, options.numberInline);
|
|
981
|
+
// Since 0.10.0 by default: the tables sent whole get the tools, and the files sent whole have
|
|
982
|
+
// numbered lines. "text" and false send them as 0.9 did.
|
|
983
|
+
const inlineTables = options.inlineTables ?? "tools";
|
|
984
|
+
const numberInline = options.numberInline ?? true;
|
|
770
985
|
// A question planned again goes on counting what its first try paid for.
|
|
771
986
|
const usage = carried?.usage ?? new UsageMeter();
|
|
772
987
|
|
|
@@ -799,23 +1014,47 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
799
1014
|
const meter = new RequestMeter(pageTokens);
|
|
800
1015
|
const asText = textSize(messages, options.system);
|
|
801
1016
|
const earlier = meter.rounds(messages);
|
|
802
|
-
// Who asks: the documents are looked up, and every tool call reads them, for this owner and
|
|
1017
|
+
// Who asks: the documents are looked up, and every tool call reads them, for this owner and
|
|
1018
|
+
// scope. The question's signal goes with them, for a library that ends its waits for the store
|
|
1019
|
+
// with it (`AccessOptions.signal`).
|
|
803
1020
|
const access = {
|
|
804
1021
|
...(options.owner !== undefined ? { owner: options.owner } : {}),
|
|
805
1022
|
...(options.scope !== undefined ? { scope: options.scope } : {}),
|
|
1023
|
+
...(signal ? { signal } : {}),
|
|
806
1024
|
};
|
|
807
1025
|
// Documents that are missing are settled as `onMissingDocuments` says. A question planned again
|
|
808
1026
|
// starts from the documents its first try planned: the function is not asked again about them.
|
|
809
|
-
|
|
1027
|
+
// The question stops when its signal aborts, whether the library does or not: a store call that
|
|
1028
|
+
// hangs (a network volume that does not answer) must not hold it, with any `LargeFiles`.
|
|
1029
|
+
const planned = await planDocumentsOf(options, carried?.documentIds ?? options.documentIds, (ids) => until(files.prepare(ids, { tokens: asText.tokens + earlier.tokens, bytes: asText.bytes + earlier.bytes }, {
|
|
810
1030
|
...access,
|
|
811
1031
|
viewPages: options.viewPages !== false && canShowFiles,
|
|
812
1032
|
// The guide and the cards name `analyze_whole_document` only when the tools will have it.
|
|
813
|
-
wholeDocumentAnalysis: options.wholeDocumentAnalysis !== false && typeof
|
|
1033
|
+
wholeDocumentAnalysis: options.wholeDocumentAnalysis !== false && typeof (given ?? model).generateText === "function",
|
|
814
1034
|
budget,
|
|
815
|
-
|
|
1035
|
+
numberInline,
|
|
1036
|
+
inlineTables,
|
|
1037
|
+
}), signal));
|
|
816
1038
|
const { prepared, documentIds } = planned;
|
|
817
1039
|
/** The documents left out of the question ("drop"), by this try and by the first. */
|
|
818
1040
|
const missing = [...carried?.missing ?? [], ...planned.dropped];
|
|
1041
|
+
// Tools are needed for a file that is too large to send whole, for a PDF whose pages can be
|
|
1042
|
+
// looked at (that one may have its whole text in the prompt and still hide a chart from the
|
|
1043
|
+
// model), and for a table sent whole whose rows they can count (`inlineTables`). A library of
|
|
1044
|
+
// your own whose `prepare` gives no `toolable` has none of the last.
|
|
1045
|
+
const { searchable } = prepared.plan;
|
|
1046
|
+
const { viewable } = prepared;
|
|
1047
|
+
const toolable = prepared.toolable ?? [];
|
|
1048
|
+
// The explorer gathers what the answer needs from the files searched with the tools. When none
|
|
1049
|
+
// is, and the tools are there for tables sent whole, the answering model runs the loop itself: a
|
|
1050
|
+
// question that needs no count is then answered in its first request, and the whole files are
|
|
1051
|
+
// not sent to two models that share no cache.
|
|
1052
|
+
const explorer = given && !(searchable.length === 0 && toolable.length > 0) ? given : undefined;
|
|
1053
|
+
const toolModel = explorer ?? model;
|
|
1054
|
+
// The lines of the files sent whole are numbered when asked, by a library whose `prepare` is
|
|
1055
|
+
// that of this package (its result has the mark, `preparedHere`): one of your own of 0.9 sends
|
|
1056
|
+
// them as they are.
|
|
1057
|
+
const numbered = numberInline && preparedHere(prepared);
|
|
819
1058
|
|
|
820
1059
|
const blocks = [...new Set(documentIds)].map((id) => prepared.blocks.get(id)).filter((block): block is string => Boolean(block));
|
|
821
1060
|
if (blocks.length) {
|
|
@@ -826,13 +1065,16 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
826
1065
|
}
|
|
827
1066
|
// A question without some of its files says so to the model, in one line of its own.
|
|
828
1067
|
const missingLine = missing.length > 0 ? missingFilesLine(missing.length) : "";
|
|
829
|
-
|
|
1068
|
+
// The fixed lines for the files sent whole (since 0.10.0): that their tables can still be counted
|
|
1069
|
+
// with the tools, and, when no file is searched, to cite their numbered lines.
|
|
1070
|
+
const inlineLine = inlineInstruction(prepared, numbered);
|
|
1071
|
+
const system = [options.system?.trim(), prepared.instruction, inlineLine, missingLine].filter(Boolean).join("\n\n");
|
|
830
1072
|
|
|
831
1073
|
// The size of what stays in every request: the text as asked, the documents, the tool guide.
|
|
832
1074
|
const whole = new Set(prepared.plan.inline.map((meta) => meta.id));
|
|
833
1075
|
meter.fixed = {
|
|
834
|
-
tokens: asText.tokens + prepared.plan.inlineTokens + estimateTokens(prepared.instruction) + (missingLine ? estimateTokens(missingLine) : 0),
|
|
835
|
-
bytes: asText.bytes + prepared.plan.inlineBytes + jsonBytes(prepared.instruction) + (missingLine ? jsonBytes(missingLine) : 0),
|
|
1076
|
+
tokens: asText.tokens + prepared.plan.inlineTokens + estimateTokens(prepared.instruction) + (inlineLine ? estimateTokens(inlineLine) : 0) + (missingLine ? estimateTokens(missingLine) : 0),
|
|
1077
|
+
bytes: asText.bytes + prepared.plan.inlineBytes + jsonBytes(prepared.instruction) + (inlineLine ? jsonBytes(inlineLine) : 0) + (missingLine ? jsonBytes(missingLine) : 0),
|
|
836
1078
|
};
|
|
837
1079
|
for (const [id, block] of prepared.blocks) {
|
|
838
1080
|
if (whole.has(id)) continue;
|
|
@@ -842,11 +1084,20 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
842
1084
|
|
|
843
1085
|
let text = "";
|
|
844
1086
|
let turns = carried?.turns ?? 0;
|
|
1087
|
+
/** The last reply of the chat: its `finish` is the answer's (`AskResult.finish`). */
|
|
1088
|
+
let lastReply: ModelReply | undefined;
|
|
1089
|
+
const dropFiltered = options.filteredAnswer === "drop";
|
|
845
1090
|
let finishReason: string | undefined;
|
|
846
1091
|
let blockReason: string | undefined;
|
|
847
1092
|
let lastUsage: Record<string, unknown> | undefined;
|
|
848
1093
|
const steps: string[] = [];
|
|
849
|
-
|
|
1094
|
+
// The files sent whole come first, in the order of their blocks: the model was shown every line
|
|
1095
|
+
// of them before any tool ran (since 0.10.0).
|
|
1096
|
+
const inlineById = new Map(prepared.plan.inline.map((meta) => [meta.id, meta]));
|
|
1097
|
+
const evidence: Evidence[] = [...new Set(documentIds)].flatMap((id) => {
|
|
1098
|
+
const meta = inlineById.get(id);
|
|
1099
|
+
return meta ? [sentWhole(meta)] : [];
|
|
1100
|
+
});
|
|
850
1101
|
const emit = (delta: string, requestId: string) => {
|
|
851
1102
|
text += delta;
|
|
852
1103
|
options.onText?.(delta);
|
|
@@ -968,10 +1219,13 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
968
1219
|
if (events.active) events.emit({ type: "request.end", requestId, ms: Date.now() - began, outcome: "error", error: eventErrorOf(error) });
|
|
969
1220
|
throw error;
|
|
970
1221
|
}
|
|
971
|
-
// Text the adapter did not pass on as it came (no streaming was asked for, or it cannot).
|
|
972
|
-
|
|
1222
|
+
// Text the adapter did not pass on as it came (no streaming was asked for, or it cannot). Not
|
|
1223
|
+
// the text of a reply a filter stopped, when such an answer is dropped: it was not shown yet.
|
|
1224
|
+
if (shown && reply.text.length > got.length && reply.text.startsWith(got) && !(dropFiltered && reply.finish === "filtered")) write(reply.text.slice(got.length));
|
|
973
1225
|
answeredRequests++;
|
|
974
|
-
|
|
1226
|
+
lastReply = reply;
|
|
1227
|
+
// A reply without its input tokens is counted by the estimate, in the model's own tokens.
|
|
1228
|
+
usage.add(adapter.id, reply.usage, estimated * scaleOf(adapter));
|
|
975
1229
|
// The count of the model that answered, in the library's tokens by that model's own scale: how
|
|
976
1230
|
// much more than its scale says the text costs it, which the other model will see too. By the
|
|
977
1231
|
// larger scale of the two, a count of the model with the smaller one was taken for no more.
|
|
@@ -988,6 +1242,8 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
988
1242
|
...(reply.finish ? { finish: reply.finish } : {}),
|
|
989
1243
|
...(reply.finishReason !== undefined ? { finishReason: reply.finishReason } : {}),
|
|
990
1244
|
toolCalls: reply.calls.length,
|
|
1245
|
+
...(typeof reply.responseId === "string" ? { responseId: reply.responseId } : {}),
|
|
1246
|
+
...(typeof reply.responseModel === "string" ? { responseModel: reply.responseModel } : {}),
|
|
991
1247
|
});
|
|
992
1248
|
if (reply.blockReason) notice("blocked", `The provider refused the prompt: ${reply.blockReason}.`);
|
|
993
1249
|
return reply;
|
|
@@ -996,6 +1252,25 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
996
1252
|
const wrote = (reply: ModelReply) => reply.text.trim().length > 0 && !reply.blockReason;
|
|
997
1253
|
|
|
998
1254
|
const asked = messages.length;
|
|
1255
|
+
/** The documents of the question, by ID: their names and formats, for the citations of the answer. */
|
|
1256
|
+
const documents = [...prepared.plan.inline, ...prepared.plan.searchable];
|
|
1257
|
+
const citationsOf = (): CitationCheck => {
|
|
1258
|
+
const names: Record<string, string> = {};
|
|
1259
|
+
const formats: Record<string, DocumentFormat> = {};
|
|
1260
|
+
for (const meta of documents) {
|
|
1261
|
+
names[meta.id] = meta.name;
|
|
1262
|
+
formats[meta.id] = meta.format;
|
|
1263
|
+
}
|
|
1264
|
+
// A document sent whole was shown, every line of it (its evidence comes first and says so),
|
|
1265
|
+
// and a whole-file read read every line: those from 1 to its last. A line past the end of the
|
|
1266
|
+
// file is not supported.
|
|
1267
|
+
const linesOf = new Map(documents.map((meta) => [meta.id, meta.lines]));
|
|
1268
|
+
const bounded = (entry: Evidence): Evidence => {
|
|
1269
|
+
const lines = linesOf.get(entry.documentId);
|
|
1270
|
+
return entry.whole === true && !entry.lines && typeof lines === "number" && Number.isFinite(lines) ? { ...entry, lines: lines >= 1 ? [[1, Math.trunc(lines)]] : [] } : entry;
|
|
1271
|
+
};
|
|
1272
|
+
return checkCitations(text, evidence.map(bounded), names, formats);
|
|
1273
|
+
};
|
|
999
1274
|
const result = (answered: boolean): AskResult => ({
|
|
1000
1275
|
text,
|
|
1001
1276
|
answered,
|
|
@@ -1018,7 +1293,33 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1018
1293
|
...(finishReason ? { finishReason } : {}),
|
|
1019
1294
|
usage: usage.totals,
|
|
1020
1295
|
...(lastUsage ? { lastUsage } : {}),
|
|
1296
|
+
...(lastReply?.finish !== undefined ? { finish: lastReply.finish } : {}),
|
|
1297
|
+
...(documents.length > 0 ? { citations: citationsOf() } : {}),
|
|
1021
1298
|
});
|
|
1299
|
+
/**
|
|
1300
|
+
* The result of a question that ends with an answer: one that a filter stopped, or that was cut
|
|
1301
|
+
* at the output limit, says so in a notice, before `run.finish`. A filtered answer is dropped
|
|
1302
|
+
* when `filteredAnswer` says so; text of it already sent is to be taken away (`discardText`).
|
|
1303
|
+
*/
|
|
1304
|
+
const answer = (answered: boolean): AskResult => {
|
|
1305
|
+
const finish = lastReply?.finish;
|
|
1306
|
+
if (finish === "filtered") {
|
|
1307
|
+
const sent = text.length > 0;
|
|
1308
|
+
const message = !lastReply?.text.trim()
|
|
1309
|
+
? "A filter of the provider stopped the answer before any text came."
|
|
1310
|
+
: dropFiltered
|
|
1311
|
+
? "A filter of the provider stopped the answer before it was finished: its text was dropped."
|
|
1312
|
+
: "A filter of the provider stopped the answer before it was finished.";
|
|
1313
|
+
events.emit({ type: "notice", code: "answer_filtered", message, display: "none", ...(dropFiltered && sent ? { discardText: true as const } : {}) });
|
|
1314
|
+
if (dropFiltered) {
|
|
1315
|
+
text = "";
|
|
1316
|
+
return result(false);
|
|
1317
|
+
}
|
|
1318
|
+
} else if (finish === "cut") {
|
|
1319
|
+
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.");
|
|
1320
|
+
}
|
|
1321
|
+
return result(answered);
|
|
1322
|
+
};
|
|
1022
1323
|
|
|
1023
1324
|
// Pages the model looks at stay in the request until the question is answered, so they are
|
|
1024
1325
|
// counted twice: as bytes against the request limit, and as tokens against half of what the
|
|
@@ -1031,10 +1332,15 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1031
1332
|
// request as too large, and names its window, makes it smaller.
|
|
1032
1333
|
let tokenLimit = budget.contextTokens - Math.floor(reservedTokens / 2);
|
|
1033
1334
|
const byteLimit = maxRequestBytes - Math.max(32_768, Math.floor(maxRequestBytes / 50));
|
|
1034
|
-
/**
|
|
1035
|
-
|
|
1335
|
+
/**
|
|
1336
|
+
* The tokens of tool results that still fit, with a model turn that is about to be answered, for
|
|
1337
|
+
* calls whose results take `rates` tokens a character: within the token limit, and within the
|
|
1338
|
+
* bytes of the request for the call that takes the fewest tokens a character.
|
|
1339
|
+
*/
|
|
1340
|
+
const room = (pending: ModelToolRound, rates: number[]): number => {
|
|
1036
1341
|
const now = meter.current([...messages, pending]);
|
|
1037
|
-
|
|
1342
|
+
const fewest = rates.length > 0 ? Math.min(...rates) : 1 / CHARACTERS_PER_TOKEN;
|
|
1343
|
+
return Math.floor(Math.min(tokenLimit - now.tokens, (byteLimit - now.bytes) / BYTES_PER_CHARACTER * fewest));
|
|
1038
1344
|
};
|
|
1039
1345
|
/**
|
|
1040
1346
|
* Makes room: the results of every tool round but the last `keep` are replaced by short
|
|
@@ -1093,7 +1399,7 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1093
1399
|
if (answer.result.already_shown === true) {
|
|
1094
1400
|
const held = canPoint && ((key !== undefined && (inRound.has(key) || (answer.call.name !== TOOL_NAMES.read && shownKeys.has(key))))
|
|
1095
1401
|
|| (answer.call.name === TOOL_NAMES.read && (shownReads.get(answer.call.args.document_id) ?? [])
|
|
1096
|
-
.some((read) =>
|
|
1402
|
+
.some((read) => pointerTo(answer.call, read.answer, read.index < asked && read.question !== question) !== undefined)));
|
|
1097
1403
|
if (!held) {
|
|
1098
1404
|
touched = true;
|
|
1099
1405
|
now = {
|
|
@@ -1105,7 +1411,7 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1105
1411
|
},
|
|
1106
1412
|
};
|
|
1107
1413
|
}
|
|
1108
|
-
} else if (key !== undefined &&
|
|
1414
|
+
} else if (key !== undefined && pointerTo(answer.call, answer) !== undefined) {
|
|
1109
1415
|
// A result in full: what a later pointer may point to.
|
|
1110
1416
|
if (answer.call.name === TOOL_NAMES.read) {
|
|
1111
1417
|
const reads = shownReads.get(answer.call.args.document_id) ?? [];
|
|
@@ -1269,31 +1575,38 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1269
1575
|
else signal?.addEventListener("abort", stopTools, { once: true });
|
|
1270
1576
|
|
|
1271
1577
|
try {
|
|
1272
|
-
//
|
|
1273
|
-
|
|
1274
|
-
const { searchable } = prepared.plan;
|
|
1275
|
-
const { viewable } = prepared;
|
|
1276
|
-
if (searchable.length === 0 && viewable.length === 0) return result(wrote(await send(model, () => ({ system, messages }), true, { role: "answer", purpose: "direct" })));
|
|
1578
|
+
// Nothing for the tools (see `toolable` above): one request, without them.
|
|
1579
|
+
if (searchable.length === 0 && viewable.length === 0 && toolable.length === 0) return answer(wrote(await send(model, () => ({ system, messages }), true, { role: "answer", purpose: "direct" })));
|
|
1277
1580
|
|
|
1278
1581
|
// Reading a whole file in parts is exploring too: the explorer model's work, when there is one.
|
|
1279
1582
|
// Bound to its adapter: a class with a `generateText` method that uses `this` keeps it.
|
|
1280
1583
|
const partReader = options.wholeDocumentAnalysis === false ? undefined : toolModel.generateText?.bind(toolModel);
|
|
1281
1584
|
const generate: GenerateText | undefined = partReader && (async (part) => {
|
|
1282
1585
|
let reported = false;
|
|
1586
|
+
// What the request sends, in the reader's tokens: counted for a request whose usage does not
|
|
1587
|
+
// give its input, so that `limits.inputTokens` sees it. Worked out only then.
|
|
1588
|
+
const estimate = () => (estimateTokens(part.system) + estimateTokens(part.prompt)) * scaleOf(toolModel);
|
|
1283
1589
|
const text = await partReader({
|
|
1284
1590
|
...part,
|
|
1285
1591
|
onUsage: (used) => {
|
|
1286
1592
|
reported = true;
|
|
1287
|
-
usage.add(toolModel.id, used);
|
|
1593
|
+
usage.add(toolModel.id, used, reportsInput(used) ? undefined : estimate());
|
|
1288
1594
|
part.onUsage?.(used);
|
|
1289
1595
|
},
|
|
1290
1596
|
});
|
|
1291
1597
|
// A part reader that does not report its usage (`onUsage` is optional) still made a request,
|
|
1292
1598
|
// and `limits.requests` counts it.
|
|
1293
|
-
if (!reported) usage.add(toolModel.id, undefined);
|
|
1599
|
+
if (!reported) usage.add(toolModel.id, undefined, estimate());
|
|
1294
1600
|
return text;
|
|
1295
1601
|
});
|
|
1296
|
-
|
|
1602
|
+
// The tables sent whole are read by the tools too. Their question declares exactly the tools it
|
|
1603
|
+
// needs (`questionTools`): search_document, read_document and aggregate_table for them, never
|
|
1604
|
+
// get_document_overview or analyze_whole_document, which refuses a file sent whole if it is
|
|
1605
|
+
// called. With no such table, the tool set of 0.9.
|
|
1606
|
+
const declare = toolable.length > 0
|
|
1607
|
+
? { declare: questionTools({ searchable, toolable, viewable }, generate !== undefined && searchable.some((meta) => canBeReadWhole(meta, budget))), inline: prepared.plan.inline.map((meta) => meta.id) }
|
|
1608
|
+
: {};
|
|
1609
|
+
const tools = files.tools([...searchable, ...toolable], {
|
|
1297
1610
|
// The owner and scope the store holds are checked against the question's own, not against
|
|
1298
1611
|
// the metadata handed in.
|
|
1299
1612
|
access,
|
|
@@ -1304,12 +1617,14 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1304
1617
|
maxWholeDocumentReads: limits.wholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS,
|
|
1305
1618
|
...(options.retry ? { retry: options.retry } : {}),
|
|
1306
1619
|
budget,
|
|
1620
|
+
...declare,
|
|
1307
1621
|
});
|
|
1308
1622
|
const declarations = tools.declarations;
|
|
1309
1623
|
/** The documents a tool call found gone, told once each ("document_gone"). */
|
|
1310
1624
|
const gone = new Set<string>();
|
|
1311
1625
|
/** The file name of a document of the question, as the plan has it. */
|
|
1312
|
-
const
|
|
1626
|
+
const metaOf = (id: unknown): DocumentMeta | undefined => (typeof id === "string" ? [...searchable, ...toolable, ...viewable].find((meta) => meta.id === id) : undefined);
|
|
1627
|
+
const nameOf = (id: string): string | undefined => metaOf(id)?.name;
|
|
1313
1628
|
// The requests that use the tools are the chat's own, or an explorer model's: the same
|
|
1314
1629
|
// conversation, and a line that says what its part is.
|
|
1315
1630
|
const toolSystem = explorer ? `${system}\n\n${EXPLORER_INSTRUCTION}` : system;
|
|
@@ -1320,43 +1635,138 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1320
1635
|
|
|
1321
1636
|
const maxTurns = Math.max(1, Math.trunc(limits.toolTurns ?? DEFAULT_TOOL_TURNS));
|
|
1322
1637
|
const maxCalls = Math.max(1, Math.trunc(limits.callsPerTurn ?? DEFAULT_CALLS_PER_TURN));
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|| (limits.requests !== undefined && usage.totals.requests >= limits.requests - 1)
|
|
1327
|
-
);
|
|
1638
|
+
const readsOfEach = limits.wholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS;
|
|
1639
|
+
// As the tool set reads its own count of reads of each document: whole numbers, none below 0.
|
|
1640
|
+
const readsInAll = Math.max(0, Math.trunc(limits.wholeReadsPerQuestion ?? DEFAULT_WHOLE_READS_PER_QUESTION));
|
|
1328
1641
|
/**
|
|
1329
|
-
*
|
|
1330
|
-
*
|
|
1331
|
-
*
|
|
1642
|
+
* The price of a whole-file read of `meta` by the model that explores, in its own tokens and
|
|
1643
|
+
* requests: a read that lists items (`output: "items"`) is its parts alone; any other, its
|
|
1644
|
+
* parts, the merges of their notes and its answer.
|
|
1332
1645
|
*/
|
|
1333
|
-
const
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
const
|
|
1343
|
-
|
|
1344
|
-
const
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1646
|
+
const priceOf = (meta: DocumentMeta, output: "answer" | "items" = "answer") => wholeReadCost(meta, budget, scaleOf(toolModel), output);
|
|
1647
|
+
/**
|
|
1648
|
+
* The ceiling on the input tokens of the question: `limits.inputTokens`, or by default the larger
|
|
1649
|
+
* of `DEFAULT_INPUT_TOKENS` and `toolTurns` times the first request, plus room for the
|
|
1650
|
+
* whole-file reads the question may make: as many as `wholeReadsPerQuestion` and the documents
|
|
1651
|
+
* that can be read whole allow, each at the price of the dearest of them.
|
|
1652
|
+
*/
|
|
1653
|
+
const ceiling = ((): number => {
|
|
1654
|
+
if (limits.inputTokens !== undefined) return limits.inputTokens;
|
|
1655
|
+
const first = meter.current(viewFor(toolModel)).tokens * scaleOf(toolModel);
|
|
1656
|
+
const readable = tools.has(TOOL_NAMES.analyze) && readsOfEach > 0 ? searchable.filter((meta) => canBeReadWhole(meta, budget)) : [];
|
|
1657
|
+
const reads = Math.max(0, Math.min(readsInAll, readable.length * Math.trunc(readsOfEach)));
|
|
1658
|
+
const prices = readable.map((meta) => priceOf(meta).inputTokens).filter((price) => Number.isFinite(price));
|
|
1659
|
+
const allowance = prices.length > 0 ? (Number.isFinite(reads) ? reads : readable.length) * Math.max(...prices) : 0;
|
|
1660
|
+
return Math.max(DEFAULT_INPUT_TOKENS, maxTurns * first) + allowance;
|
|
1661
|
+
})();
|
|
1662
|
+
/** The input tokens the question has used: those the providers reported, and the estimates of those they did not. */
|
|
1663
|
+
const spentTokens = (): number => usage.totals.inputTokens + (usage.totals.estimatedInputTokens ?? 0);
|
|
1664
|
+
/**
|
|
1665
|
+
* True once the question has used what it may: no more tools run. One request is kept for the
|
|
1666
|
+
* answer. The ceiling of input tokens looks ahead: what was spent, the tool request about to be
|
|
1667
|
+
* sent and the answer's request after it, each as the meter counts it now, must stay within it.
|
|
1668
|
+
*/
|
|
1669
|
+
const spent = (): boolean => {
|
|
1670
|
+
if (limits.requests !== undefined && usage.totals.requests >= limits.requests - 1) return true;
|
|
1671
|
+
if (!(ceiling < Number.POSITIVE_INFINITY)) return false;
|
|
1672
|
+
const next = meter.current(viewFor(toolModel)).tokens * scaleOf(toolModel);
|
|
1673
|
+
const closing = meter.current(viewFor(model)).tokens * scaleOf(model);
|
|
1674
|
+
return spentTokens() + next + closing > ceiling;
|
|
1675
|
+
};
|
|
1676
|
+
/**
|
|
1677
|
+
* The whole-file reads of the question that sent requests, by document: those that returned, and
|
|
1678
|
+
* those that failed after they sent them. Counted from what the tool returned, before
|
|
1679
|
+
* `onToolResult`: a read whose answer the hook replaced or rejected still made its requests.
|
|
1680
|
+
*/
|
|
1681
|
+
const readsSent = new Map<string, number>();
|
|
1682
|
+
const readsMade = (documentId?: string): number => {
|
|
1683
|
+
if (documentId !== undefined) return readsSent.get(documentId) ?? 0;
|
|
1684
|
+
let made = 0;
|
|
1685
|
+
for (const reads of readsSent.values()) made += reads;
|
|
1686
|
+
return made;
|
|
1687
|
+
};
|
|
1688
|
+
/** 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. */
|
|
1689
|
+
const sentParts = (call: ToolCall, output: ToolResult): boolean => call.name === TOOL_NAMES.analyze
|
|
1690
|
+
&& (evidenceOf(call, output)?.whole === true || (typeof output.error === "string" && output.error.startsWith(NOTHING_READ)));
|
|
1691
|
+
/** What the whole-file reads already let through in a turn will take: they run together, and the totals do not show them yet. */
|
|
1692
|
+
type Reserved = { inputTokens: number; requests: number; reads: Map<string, number> };
|
|
1693
|
+
/**
|
|
1694
|
+
* True when no whole-file read of `meta` is left, past those of `reserved`: the tool refuses one
|
|
1695
|
+
* itself, at no cost, with its own reason (such as a read that failed earlier). The tool set says
|
|
1696
|
+
* how many reads are left; one of your own that does not is read by what the reads of this
|
|
1697
|
+
* question returned.
|
|
1698
|
+
*/
|
|
1699
|
+
const noReadLeft = (meta: DocumentMeta, reserved: Reserved): boolean => {
|
|
1700
|
+
const inTurn = reserved.reads.get(meta.id) ?? 0;
|
|
1701
|
+
const left = tools.wholeReadsLeft?.(meta.id);
|
|
1702
|
+
return typeof left === "number" ? left - inTurn <= 0 : readsMade(meta.id) + inTurn >= readsOfEach;
|
|
1703
|
+
};
|
|
1704
|
+
/**
|
|
1705
|
+
* What a whole-file read of `meta` takes, and why the question would not start it now, past the
|
|
1706
|
+
* reads of `reserved`: its whole reads made, or a ceiling it would pass. Not the tool's own
|
|
1707
|
+
* reasons (`noReadLeft`). `output` is the read's own: a read that lists items ("items") is
|
|
1708
|
+
* priced at its parts alone, any other ("answer") at its parts, merges and answer.
|
|
1709
|
+
*/
|
|
1710
|
+
const readNeeds = (meta: DocumentMeta, reserved: Reserved, output: "answer" | "items"): { refusal?: string; tokens: number; requests: number } => {
|
|
1711
|
+
// The parts are read by the model that explores, in its own tokens: their lines numbered, the
|
|
1712
|
+
// prompts, and the merges of their notes (`wholeReadCost`). A read that lists items sends its
|
|
1713
|
+
// parts alone, with the rules of a list.
|
|
1714
|
+
const items = output === "items";
|
|
1715
|
+
const price = priceOf(meta, output).inputTokens;
|
|
1716
|
+
const tokens = Number.isFinite(price) ? price : Math.ceil(meta.estimatedTokens * scaleOf(toolModel));
|
|
1717
|
+
// The parts, a merge of their notes, the answer of the read, and the answer of the question;
|
|
1718
|
+
// for a list of items, the parts and the answer of the question.
|
|
1719
|
+
const requests = estimateParts(meta, budget) + (items ? 1 : 3);
|
|
1720
|
+
const allReserved = [...reserved.reads.values()].reduce((sum, reads) => sum + reads, 0);
|
|
1721
|
+
if (readsMade() + allReserved >= readsInAll) {
|
|
1722
|
+
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}.` };
|
|
1723
|
+
}
|
|
1724
|
+
if (ceiling < Number.POSITIVE_INFINITY) {
|
|
1725
|
+
const left = Math.max(0, ceiling - spentTokens() - reserved.inputTokens);
|
|
1726
|
+
if (tokens > left) 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.` };
|
|
1348
1727
|
}
|
|
1349
1728
|
if (limits.requests !== undefined) {
|
|
1350
1729
|
const left = Math.max(0, limits.requests - usage.totals.requests - reserved.requests);
|
|
1351
|
-
if (requests > left) 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.` };
|
|
1730
|
+
if (requests > left) 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.` };
|
|
1352
1731
|
}
|
|
1732
|
+
return { tokens, requests };
|
|
1733
|
+
};
|
|
1734
|
+
/**
|
|
1735
|
+
* A whole-file read is many requests at once: one that would pass a ceiling of the question is
|
|
1736
|
+
* not started. `reserved` is what the reads already let through in this turn will take.
|
|
1737
|
+
*/
|
|
1738
|
+
const tooCostly = (call: ToolCall, reserved: Reserved): { refusal?: string; own?: number } => {
|
|
1739
|
+
if (call.name !== TOOL_NAMES.analyze) return {};
|
|
1740
|
+
const meta = searchable.find((document) => document.id === call.args.document_id);
|
|
1741
|
+
// A read of a document read whole as often as it may be takes nothing from the reads of other documents.
|
|
1742
|
+
if (!meta || noReadLeft(meta, reserved)) return {};
|
|
1743
|
+
const { refusal, tokens, requests } = readNeeds(meta, reserved, call.args.output === "items" ? "items" : "answer");
|
|
1744
|
+
if (refusal) return { refusal };
|
|
1353
1745
|
reserved.inputTokens += tokens;
|
|
1354
1746
|
// The answer of the question is one request, whatever number of reads come before it.
|
|
1355
1747
|
reserved.requests += requests - 1;
|
|
1356
1748
|
reserved.reads.set(meta.id, (reserved.reads.get(meta.id) ?? 0) + 1);
|
|
1357
|
-
// The read's own requests: its parts, a merge of their notes, and its answer.
|
|
1749
|
+
// The read's own requests: its parts, a merge of their notes, and its answer; or its parts.
|
|
1358
1750
|
return { own: requests - 1 };
|
|
1359
1751
|
};
|
|
1752
|
+
/**
|
|
1753
|
+
* The requests a whole-file read of the document of a `read_document` call may make
|
|
1754
|
+
* (`ToolCallLimits.maxRequests`), judged as on the next turn, the first the model can call it on:
|
|
1755
|
+
* with the reads of this turn reserved, and that turn's request, of the conversation with
|
|
1756
|
+
* `pending` at least (its results are not in it yet). 0 when the question would not start one
|
|
1757
|
+
* then (`noReadLeft`, `readNeeds`), so that a read cut short of its range does not point at it
|
|
1758
|
+
* (`whole_file`); what is left of `limits.requests` with one kept for the answer, when that is
|
|
1759
|
+
* set; undefined otherwise.
|
|
1760
|
+
*/
|
|
1761
|
+
const wholeReadRequests = (call: ToolCall, reserved: Reserved, pending: ModelToolRound): number | undefined => {
|
|
1762
|
+
const meta = searchable.find((document) => document.id === call.args.document_id);
|
|
1763
|
+
if (!meta) return undefined;
|
|
1764
|
+
const nextTurn = meter.current(viewFor(toolModel, [...messages, pending])).tokens * scaleOf(toolModel);
|
|
1765
|
+
const later: Reserved = { ...reserved, inputTokens: reserved.inputTokens + nextTurn, requests: reserved.requests + 1 };
|
|
1766
|
+
// The hint points at a read that gives an answer, the dearer of the two kinds.
|
|
1767
|
+
if (noReadLeft(meta, later) || readNeeds(meta, later, "answer").refusal !== undefined) return 0;
|
|
1768
|
+
return limits.requests === undefined ? undefined : Math.max(0, limits.requests - usage.totals.requests - 1 - later.requests);
|
|
1769
|
+
};
|
|
1360
1770
|
/**
|
|
1361
1771
|
* A pointer for a call whose result is already in the conversation, in full: an earlier result
|
|
1362
1772
|
* (of this question or of one before it) holds what this one would return. The files do not
|
|
@@ -1369,7 +1779,7 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1369
1779
|
if (!isRound(message)) continue;
|
|
1370
1780
|
// The rounds before `asked` are those of earlier questions, which an older version may have written.
|
|
1371
1781
|
for (const answer of message.answers) {
|
|
1372
|
-
const pointer =
|
|
1782
|
+
const pointer = pointerTo(call, answer, at < asked);
|
|
1373
1783
|
if (pointer) return pointer;
|
|
1374
1784
|
}
|
|
1375
1785
|
}
|
|
@@ -1386,6 +1796,19 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1386
1796
|
const toolRole: RequestRole = explorer ? "explorer" : "tools";
|
|
1387
1797
|
/** 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. */
|
|
1388
1798
|
const labelOf = (call: ToolCall): string => stepLine(tools.has(call.name) ? tools.describe(call.name, call.args) : `Call ${unknownToolName(call.name)}`);
|
|
1799
|
+
// The tools are there only for tables sent whole (`inlineTables`): without them, the question
|
|
1800
|
+
// would be the one request of 0.9 (and of "text"). It is still that, without the tools, the
|
|
1801
|
+
// line that says to count with them, or a notice, when not one tool turn fits: a ceiling or a
|
|
1802
|
+
// count of requests sized for that one request, or `toolTurns: 1`.
|
|
1803
|
+
const tablesOnly = !explorer && searchable.length === 0 && viewable.length === 0;
|
|
1804
|
+
if (tablesOnly && (1 + (carried?.answered ?? 0) >= maxTurns || spent())) {
|
|
1805
|
+
const plainLine = inlineInstruction({ plan: prepared.plan }, numbered);
|
|
1806
|
+
const plain = [options.system?.trim(), prepared.instruction, plainLine, missingLine].filter(Boolean).join("\n\n");
|
|
1807
|
+
// Its estimate, for a provider that reports no usage: no declarations, its own line.
|
|
1808
|
+
meter.fixed.tokens += -estimateTokens(sentTools) - (inlineLine ? estimateTokens(inlineLine) : 0) + (plainLine ? estimateTokens(plainLine) : 0);
|
|
1809
|
+
meter.fixed.bytes += -Buffer.byteLength(sentTools) - (inlineLine ? jsonBytes(inlineLine) : 0) + (plainLine ? jsonBytes(plainLine) : 0);
|
|
1810
|
+
return answer(wrote(await send(model, () => ({ system: plain, messages }), true, { role: "answer", purpose: "direct" })));
|
|
1811
|
+
}
|
|
1389
1812
|
for (let round = 1 + (carried?.answered ?? 0); round < maxTurns && !outOfRoom; round++) {
|
|
1390
1813
|
if (spent()) {
|
|
1391
1814
|
budgetReached();
|
|
@@ -1399,7 +1822,9 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1399
1822
|
// It is a request of the chat like any other: it takes a tool turn, and the last turn is still the answer's.
|
|
1400
1823
|
if (reply.calls.length === 0 && nudges < MOST_NUDGES && round + 1 < maxTurns && !reply.blockReason && !spent()) {
|
|
1401
1824
|
const malformed = reply.finish === "malformed_call";
|
|
1402
|
-
|
|
1825
|
+
// Not a reply that a filter, the output limit or another reason that asking again does not
|
|
1826
|
+
// mend ended ("other": Gemini's OTHER, LANGUAGE): it would only end the same way.
|
|
1827
|
+
const empty = !reply.text.trim() && callsAnswered === 0 && reply.finish !== "cut" && reply.finish !== "filtered" && reply.finish !== "other";
|
|
1403
1828
|
if (malformed || empty) {
|
|
1404
1829
|
nudges++;
|
|
1405
1830
|
round++;
|
|
@@ -1411,8 +1836,15 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1411
1836
|
}
|
|
1412
1837
|
if (reply.calls.length === 0) {
|
|
1413
1838
|
// Text from this turn is the answer. A remark made earlier, before a tool call, is not.
|
|
1414
|
-
// Neither is anything an explorer model writes: the answer is asked for below.
|
|
1415
|
-
|
|
1839
|
+
// Neither is anything an explorer model writes: the answer is asked for below. Nor the
|
|
1840
|
+
// remark of a turn whose tool call could not be read ("Let me look at the errors."), on
|
|
1841
|
+
// the last tool turn or after its nudge: the answer is asked for below.
|
|
1842
|
+
answered = wrote(reply) && !explorer && reply.finish !== "malformed_call";
|
|
1843
|
+
// Over tables sent whole alone, a reply that a filter or another reason that asking again
|
|
1844
|
+
// does not mend ended ("other"), or one cut at the output limit before any text, ends the
|
|
1845
|
+
// question, as it ends the direct request of 0.9: the request for the answer would send
|
|
1846
|
+
// the whole tables again, only to end the same way.
|
|
1847
|
+
if (tablesOnly && !answered && (reply.finish === "filtered" || reply.finish === "other" || reply.finish === "cut")) return answer(false);
|
|
1416
1848
|
break;
|
|
1417
1849
|
}
|
|
1418
1850
|
const pending: ModelToolRound = { role: "tools", calls: reply.calls, answers: [], ...(reply.raw !== undefined ? { raw: reply.raw } : {}) };
|
|
@@ -1435,6 +1867,10 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1435
1867
|
const label = labelOf(call);
|
|
1436
1868
|
// A call that did not arrive whole is not run: the model is told, and can send it again.
|
|
1437
1869
|
if (call.problem) return { call, label, refusal: call.problem };
|
|
1870
|
+
// Nor a call of a tool the question does not have: it is told which there are, and its
|
|
1871
|
+
// answer takes no room (a turn of unknown calls made room for each of them, at the cap of
|
|
1872
|
+
// a result, and shortened the results of earlier turns for nothing).
|
|
1873
|
+
if (!tools.has(call.name)) return { call, label, refusal: unknownTool(call.name, declarations.map((declaration) => declaration.name)) };
|
|
1438
1874
|
// A look at pages returns a file and a few words: the file has its own room, worked out when it runs.
|
|
1439
1875
|
if (call.name === TOOL_NAMES.view) return { call, label };
|
|
1440
1876
|
const key = toolCallKey(call.name, call.args);
|
|
@@ -1457,17 +1893,27 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1457
1893
|
const slack = Math.max(0, limits.requests - usage.totals.requests - 1 - reserved.requests);
|
|
1458
1894
|
for (const plan of reads) plan.limits = { ...plan.limits, maxRequests: plan.own! + Math.floor(slack / reads.length) };
|
|
1459
1895
|
}
|
|
1896
|
+
// A read of lines points at a whole read of its file only when the question would start one
|
|
1897
|
+
// on the next turn, past the whole reads of this turn: each is told the requests one may make.
|
|
1898
|
+
for (const plan of planned) {
|
|
1899
|
+
if (plan.refusal || plan.call.name !== TOOL_NAMES.read) continue;
|
|
1900
|
+
const most = wholeReadRequests(plan.call, reserved, pending);
|
|
1901
|
+
if (most !== undefined) plan.limits = { ...plan.limits, maxRequests: most };
|
|
1902
|
+
}
|
|
1460
1903
|
// The calls that return text, and the most they may return: a call that is refused, or
|
|
1461
1904
|
// answered with a pointer to what is already shown, needs no room.
|
|
1462
1905
|
const sized = planned.filter((plan) => !plan.refusal && !plan.pointer && plan.call.name !== TOOL_NAMES.view);
|
|
1463
|
-
|
|
1464
|
-
|
|
1906
|
+
// The room is in tokens, and each result takes those of its document's characters.
|
|
1907
|
+
const rateOf = (call: ToolCall) => 1 / charactersPerToken(metaOf(call.args.document_id));
|
|
1908
|
+
const sizedRates = sized.map((plan) => rateOf(plan.call));
|
|
1909
|
+
const needed = sized.reduce((sum, plan, index) => sum + most(plan.call) * sizedRates[index]!, 0);
|
|
1910
|
+
let left = room(pending, sizedRates);
|
|
1465
1911
|
let dropped = false;
|
|
1466
1912
|
for (const keep of canShrink ? ROUNDS_KEPT : []) {
|
|
1467
1913
|
if (left >= needed) break;
|
|
1468
1914
|
if (shrink(keep)) {
|
|
1469
1915
|
dropped = true;
|
|
1470
|
-
left = room(pending);
|
|
1916
|
+
left = room(pending, sizedRates);
|
|
1471
1917
|
}
|
|
1472
1918
|
}
|
|
1473
1919
|
if (dropped) {
|
|
@@ -1489,10 +1935,14 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1489
1935
|
// The room is shared by those calls. A result is most often far smaller than its cap, so a call
|
|
1490
1936
|
// that was given its whole cap first could leave none for the next ones, and a turn of small
|
|
1491
1937
|
// searches ended the question.
|
|
1492
|
-
const
|
|
1938
|
+
const runRates = runsNow.map((plan) => rateOf(plan.call));
|
|
1939
|
+
const shares = shareRoom(runsNow.map((plan) => most(plan.call)), left, runRates);
|
|
1940
|
+
/** The tokens of room each call that runs was given, by its index in the turn. */
|
|
1941
|
+
const given = new Map<number, number>();
|
|
1493
1942
|
runsNow.forEach((plan, index) => {
|
|
1494
1943
|
const share = shares[index];
|
|
1495
1944
|
const cap = most(plan.call);
|
|
1945
|
+
if (share !== undefined) given.set(planned.indexOf(plan), share * runRates[index]!);
|
|
1496
1946
|
if (share === undefined) {
|
|
1497
1947
|
if (!outOfRoom) notice("no_room", "There is no room left in this conversation for another tool result.");
|
|
1498
1948
|
outOfRoom = true;
|
|
@@ -1661,12 +2111,12 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1661
2111
|
requestBytes = toolModel.requestBytes?.(waiting) ?? meter.estimate(waiting.messages).bytes;
|
|
1662
2112
|
}
|
|
1663
2113
|
// Base64 turns three bytes into four characters.
|
|
1664
|
-
const output = await tools.executeWithFiles(call.name, call.args, {
|
|
2114
|
+
const output = await until(tools.executeWithFiles(call.name, call.args, {
|
|
1665
2115
|
maxFileBytes: Math.floor((maxRequestBytes - bytesKeptFree - requestBytes) * 3 / 4),
|
|
1666
2116
|
maxPages: pagesLeft,
|
|
1667
2117
|
// 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.
|
|
1668
2118
|
...(pagesBusy ? { maxWaitMs: 0 } : {}),
|
|
1669
|
-
}, hooksFor(index));
|
|
2119
|
+
}, hooksFor(index)), halt.signal);
|
|
1670
2120
|
for (const file of output.files) requestBytes += Math.ceil(file.bytes.length / 3) * 4 + 512;
|
|
1671
2121
|
if (output.files.length > 0) pagesLeft -= pagesShown(output.result);
|
|
1672
2122
|
return output;
|
|
@@ -1680,7 +2130,9 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1680
2130
|
halt.signal.throwIfAborted();
|
|
1681
2131
|
options.onActivity?.(`${label}…`);
|
|
1682
2132
|
startTool(index, call, label);
|
|
1683
|
-
|
|
2133
|
+
// The question stops when its signal aborts, whether the tool set does or not: a store
|
|
2134
|
+
// call that hangs inside a tool of any `LargeFiles` must not hold it.
|
|
2135
|
+
return await until(tools.executeWithFiles(call.name, call.args, callLimits, hooksFor(index)), halt.signal);
|
|
1684
2136
|
} finally {
|
|
1685
2137
|
release();
|
|
1686
2138
|
}
|
|
@@ -1698,6 +2150,54 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1698
2150
|
outputs.push(output);
|
|
1699
2151
|
}
|
|
1700
2152
|
|
|
2153
|
+
/**
|
|
2154
|
+
* The application's say on what the model gets (`onToolResult`): each call's verdict, asked
|
|
2155
|
+
* for as soon as its result is in, so that the hooks of a turn run at the same time. They are
|
|
2156
|
+
* applied below, in call order, before the result is fitted to the room in the request, and
|
|
2157
|
+
* before the evidence, the step and the events, which all tell what the model was sent.
|
|
2158
|
+
* `raw` is what the tool returned; `output`, what the hook let through. A call made twice in
|
|
2159
|
+
* the turn is given the verdict of its first (`copied`): no pointer to a result the hook
|
|
2160
|
+
* replaced or rejected. A hook that fails ends the turn at once.
|
|
2161
|
+
*/
|
|
2162
|
+
type Judged = { raw: ToolOutput; output: ToolOutput; judged?: ToolOutcome; copied?: boolean };
|
|
2163
|
+
const hook = options.onToolResult;
|
|
2164
|
+
const judgedOutputs: Array<Promise<Judged>> = [];
|
|
2165
|
+
for (const [index, { call, refusal, pointer, twinOf }] of planned.entries()) {
|
|
2166
|
+
const raw = outputs[index]!;
|
|
2167
|
+
let judging: Promise<Judged>;
|
|
2168
|
+
if (hook && pointer && twinOf !== undefined) {
|
|
2169
|
+
judging = Promise.all([raw, judgedOutputs[twinOf]!]).then(([own, first]): Judged => (first.judged
|
|
2170
|
+
? { raw: own, output: { result: first.output.result, files: [] }, judged: first.judged, copied: true }
|
|
2171
|
+
: { raw: own, output: own }));
|
|
2172
|
+
} else if (hook && !refusal && !pointer) {
|
|
2173
|
+
judging = raw.then(async (own): Promise<Judged> => {
|
|
2174
|
+
const context: ToolResultContext = {
|
|
2175
|
+
call,
|
|
2176
|
+
result: own.result,
|
|
2177
|
+
...(typeof call.args.document_id === "string" ? { documentId: call.args.document_id } : {}),
|
|
2178
|
+
...(options.owner !== undefined ? { owner: options.owner } : {}),
|
|
2179
|
+
...(options.scope !== undefined ? { scope: options.scope } : {}),
|
|
2180
|
+
signal: halt.signal,
|
|
2181
|
+
};
|
|
2182
|
+
let verdict: ToolResultVerdict | undefined;
|
|
2183
|
+
try {
|
|
2184
|
+
// A hook that does not look at the signal does not hold the question once it is stopped.
|
|
2185
|
+
verdict = checkedVerdict(await until(Promise.resolve().then(() => hook(context)), halt.signal));
|
|
2186
|
+
} catch (error) {
|
|
2187
|
+
halt.abort(error);
|
|
2188
|
+
throw error;
|
|
2189
|
+
}
|
|
2190
|
+
if (verdict && "result" in verdict) return { raw: own, output: { ...own, result: { ...verdict.result, redacted: true } }, judged: "redacted" };
|
|
2191
|
+
if (verdict) return { raw: own, output: { result: { error: verdict.reject }, files: [] }, judged: "refused" };
|
|
2192
|
+
return { raw: own, output: own };
|
|
2193
|
+
});
|
|
2194
|
+
} else {
|
|
2195
|
+
judging = raw.then((own): Judged => ({ raw: own, output: own }));
|
|
2196
|
+
}
|
|
2197
|
+
judging.catch(() => undefined);
|
|
2198
|
+
judgedOutputs.push(judging);
|
|
2199
|
+
}
|
|
2200
|
+
|
|
1701
2201
|
/**
|
|
1702
2202
|
* The room of each whole-file read of the turn: what the other results left, shared among the
|
|
1703
2203
|
* reads, the smaller answers first. Worked out when the first of them is reached, by which time
|
|
@@ -1705,7 +2205,7 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1705
2205
|
*/
|
|
1706
2206
|
let lateRoom: Map<number, number> | undefined;
|
|
1707
2207
|
const roomOfReads = async (): Promise<Map<number, number>> => {
|
|
1708
|
-
const sizes = await Promise.all(
|
|
2208
|
+
const sizes = await Promise.all(judgedOutputs.map(async (judging) => resultTokens((await judging).output.result)));
|
|
1709
2209
|
const reads = planned.flatMap((plan, index) => (plan.late ? [index] : []));
|
|
1710
2210
|
let free = left - sizes.reduce((sum, size, index) => sum + (planned[index]!.late ? 0 : size), 0);
|
|
1711
2211
|
const shares = new Map<number, number>();
|
|
@@ -1717,17 +2217,46 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1717
2217
|
return shares;
|
|
1718
2218
|
};
|
|
1719
2219
|
|
|
2220
|
+
/**
|
|
2221
|
+
* The tokens the results of this turn took so far, of the calls that were given room and are
|
|
2222
|
+
* not whole-file reads (those are fitted to what the others left, above), and of those the
|
|
2223
|
+
* hook replaced. A result is cut when it would take more than the room leaves it once the
|
|
2224
|
+
* calls after it, and the reads, have their shares: the room shared by characters is a
|
|
2225
|
+
* guess, a tool set of your own may not keep to `maxResultCharacters`, and a hook may return
|
|
2226
|
+
* more than the tool did.
|
|
2227
|
+
*/
|
|
2228
|
+
let took = 0;
|
|
2229
|
+
const roomFor = (index: number): number => {
|
|
2230
|
+
let others = 0;
|
|
2231
|
+
for (const [other, tokens] of given) if (other > index || planned[other]!.late) others += tokens;
|
|
2232
|
+
return left - took - others;
|
|
2233
|
+
};
|
|
2234
|
+
|
|
1720
2235
|
// The answers in call order. Each call's `tool.end` goes out here, in the same order.
|
|
1721
2236
|
for (const [index, { call, label, late, refusal, pointer }] of planned.entries()) {
|
|
1722
|
-
|
|
2237
|
+
const { raw, output: judgedOutput, judged, copied } = await judgedOutputs[index]!;
|
|
1723
2238
|
if (listenerError) throw listenerError.error;
|
|
2239
|
+
// A hook of a later call failed: nothing more of the turn reaches the model.
|
|
2240
|
+
if (halt.signal.aborted) throw halt.signal.reason;
|
|
1724
2241
|
callsAnswered++;
|
|
2242
|
+
// A whole-file read that sent its parts counts against `wholeReadsPerQuestion`, whatever the hook made of its answer.
|
|
2243
|
+
if (!refusal && !pointer && sentParts(call, raw.result)) {
|
|
2244
|
+
const id = String(call.args.document_id);
|
|
2245
|
+
readsSent.set(id, (readsSent.get(id) ?? 0) + 1);
|
|
2246
|
+
}
|
|
2247
|
+
let output = judgedOutput;
|
|
1725
2248
|
if (late) {
|
|
1726
2249
|
lateRoom ??= await roomOfReads();
|
|
1727
2250
|
const share = lateRoom.get(index)!;
|
|
1728
|
-
if (
|
|
2251
|
+
if (resultTokens(output.result) > share) output = { ...output, result: cutToTokens(output.result, share) };
|
|
2252
|
+
} else if (given.has(index) || judged) {
|
|
2253
|
+
const fits = roomFor(index);
|
|
2254
|
+
if (resultTokens(output.result) > fits) output = { ...output, result: cutToTokens(output.result, fits) };
|
|
2255
|
+
took += resultTokens(output.result);
|
|
1729
2256
|
}
|
|
1730
|
-
|
|
2257
|
+
// A cut replacement is still a replacement.
|
|
2258
|
+
if (judged === "redacted" && output.result.redacted !== true) output = { ...output, result: { ...output.result, redacted: true } };
|
|
2259
|
+
if (pointer && !copied) {
|
|
1731
2260
|
const line = step(`${label} — already shown above`);
|
|
1732
2261
|
const sent = { ...output.result, tool_turns_left: turnsLeft };
|
|
1733
2262
|
answers.push({ call, result: sent, files: [] });
|
|
@@ -1735,23 +2264,26 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1735
2264
|
continue;
|
|
1736
2265
|
}
|
|
1737
2266
|
// Two searches in a row that failed in the same mode: the second says to try another way.
|
|
1738
|
-
|
|
2267
|
+
// Read from what the tool returned; the hint goes only to a result the hook kept.
|
|
2268
|
+
if (!refusal && !copied) {
|
|
2269
|
+
const own = judged ? raw.result : output.result;
|
|
1739
2270
|
const kind = failureKind(call);
|
|
1740
2271
|
if (kind === undefined) {
|
|
1741
2272
|
failing = undefined;
|
|
1742
|
-
} else if (typeof
|
|
2273
|
+
} else if (typeof own.error === "string") {
|
|
1743
2274
|
failing = failing?.kind === kind ? { kind, count: failing.count + 1 } : { kind, count: 1 };
|
|
1744
|
-
if (failing.count >= 2) output = { ...output, result: { ...output.result, error: `${output.result.error} ${repeatedFailureHint(call)}` } };
|
|
2275
|
+
if (failing.count >= 2 && !judged) output = { ...output, result: { ...output.result, error: `${output.result.error} ${repeatedFailureHint(call)}` } };
|
|
1745
2276
|
} else {
|
|
1746
2277
|
failing = undefined;
|
|
1747
2278
|
}
|
|
1748
2279
|
}
|
|
1749
2280
|
const line = step(`${label}${toolResultSummary(label, output.result)}`);
|
|
1750
|
-
|
|
2281
|
+
// A copy of the first call's verdict shows nothing that the first did not.
|
|
2282
|
+
const shown = copied ? undefined : evidenceOf(call, output.result);
|
|
1751
2283
|
if (shown) evidence.push({ ...shown, callId: callIds[index]! });
|
|
1752
2284
|
const sent = { ...output.result, tool_turns_left: turnsLeft };
|
|
1753
2285
|
answers.push({ call, result: sent, files: output.files });
|
|
1754
|
-
const outcome: ToolOutcome = call.problem ? "error" : refusal ? "refused" : typeof output.result.error === "string" ? "error" : "ok";
|
|
2286
|
+
const outcome: ToolOutcome = judged ?? (call.problem ? "error" : refusal ? "refused" : typeof output.result.error === "string" ? "error" : "ok");
|
|
1755
2287
|
endTool(index, outcome, sent, line, shown);
|
|
1756
2288
|
}
|
|
1757
2289
|
// A listener of a read that went on after its call returned (its progress).
|
|
@@ -1783,7 +2315,12 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1783
2315
|
// With an explorer model this request is always made: it is the one the answering model gets.
|
|
1784
2316
|
if (!answered && !blockReason) {
|
|
1785
2317
|
activity("writing_answer", "Writing the answer…");
|
|
1786
|
-
|
|
2318
|
+
// With view_pages alone, the files are in the prompt and the pages were looked at. With the
|
|
2319
|
+
// text tools, the answer comes from what they returned, and from the files sent whole too when
|
|
2320
|
+
// their lines can be cited or their tables were counted: a model told "only what the tools
|
|
2321
|
+
// returned" said that a fact of a file shown in full was not there.
|
|
2322
|
+
const fromFiles = prepared.plan.inline.length > 0 && (numbered || toolable.length > 0);
|
|
2323
|
+
let closing = searchable.length === 0 && toolable.length === 0 ? FINAL_ANSWER_AFTER_PAGES : fromFiles ? FINAL_ANSWER_WITH_FILES : FINAL_ANSWER_REQUEST;
|
|
1787
2324
|
// No tool ran (the explorer needed none, the first reply was empty, or no turn was left for
|
|
1788
2325
|
// tools): there is no tool result to answer from. The answering model gets the explorer's
|
|
1789
2326
|
// calls and what they returned, and nothing else of it.
|
|
@@ -1797,14 +2334,17 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1797
2334
|
let reply = await send(model, answerRequest(), true, { role: "answer", purpose: "closing" });
|
|
1798
2335
|
// A reply with no text (empty, or a tool call the model was told not to make, or one that
|
|
1799
2336
|
// could not be read) is asked for once more, with a note that is not kept: otherwise the
|
|
1800
|
-
// question ends with nothing to show. Not after a refusal
|
|
1801
|
-
//
|
|
1802
|
-
//
|
|
1803
|
-
//
|
|
2337
|
+
// question ends with nothing to show. Not after a refusal, a filter or another reason that
|
|
2338
|
+
// asking again does not mend ("other"), which would come again, nor a reply cut off at the
|
|
2339
|
+
// output limit with nothing in it, nor when it would pass a ceiling of the question: the
|
|
2340
|
+
// ceiling of input tokens looks ahead, as before each tool request, by what was spent and
|
|
2341
|
+
// what this request takes, as the meter counts it now. It is one of the second tries of the
|
|
2342
|
+
// question, and may be one request past `limits.toolTurns`, which counts the answer's first
|
|
2343
|
+
// request.
|
|
1804
2344
|
const calledInstead = reply.calls.length > 0 || reply.finish === "malformed_call";
|
|
1805
|
-
const
|
|
1806
|
-
|
|
1807
|
-
if (!wrote(reply) && !reply.blockReason && reply.finish !== "filtered" && (calledInstead || reply.finish !== "cut") && nudges < MOST_NUDGES) {
|
|
2345
|
+
const again = ceiling < Number.POSITIVE_INFINITY ? meter.current(viewFor(model)).tokens * scaleOf(model) : 0;
|
|
2346
|
+
const ceilingReached = spentTokens() + again > ceiling || (limits.requests !== undefined && usage.totals.requests >= limits.requests);
|
|
2347
|
+
if (!wrote(reply) && !reply.blockReason && reply.finish !== "filtered" && reply.finish !== "other" && (calledInstead || reply.finish !== "cut") && nudges < MOST_NUDGES) {
|
|
1808
2348
|
if (ceilingReached) {
|
|
1809
2349
|
budgetReached();
|
|
1810
2350
|
} else {
|
|
@@ -1815,7 +2355,7 @@ async function ask(options: AskOptions, carried: Carried | undefined, state: Run
|
|
|
1815
2355
|
}
|
|
1816
2356
|
answered = wrote(reply);
|
|
1817
2357
|
}
|
|
1818
|
-
return
|
|
2358
|
+
return answer(answered);
|
|
1819
2359
|
} catch (error) {
|
|
1820
2360
|
// What the question found and paid for until it failed, for the application to keep. The usage is
|
|
1821
2361
|
// a copy: a part reader that went on after the question was stopped may still report its own.
|