llm-large-files 0.4.1 → 0.5.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.
Files changed (121) hide show
  1. package/CHANGELOG.md +127 -0
  2. package/README.md +48 -8
  3. package/dist/anthropic/adapter.d.ts +106 -0
  4. package/dist/anthropic/adapter.d.ts.map +1 -0
  5. package/dist/anthropic/adapter.js +391 -0
  6. package/dist/anthropic/adapter.js.map +1 -0
  7. package/dist/anthropic/index.d.ts +3 -0
  8. package/dist/anthropic/index.d.ts.map +1 -0
  9. package/dist/anthropic/index.js +2 -0
  10. package/dist/anthropic/index.js.map +1 -0
  11. package/dist/ask.d.ts +144 -0
  12. package/dist/ask.d.ts.map +1 -0
  13. package/dist/ask.js +540 -0
  14. package/dist/ask.js.map +1 -0
  15. package/dist/budget.d.ts +23 -0
  16. package/dist/budget.d.ts.map +1 -0
  17. package/dist/budget.js +64 -0
  18. package/dist/budget.js.map +1 -0
  19. package/dist/evidence.d.ts +40 -0
  20. package/dist/evidence.d.ts.map +1 -0
  21. package/dist/evidence.js +137 -0
  22. package/dist/evidence.js.map +1 -0
  23. package/dist/gemini/adapter.d.ts +50 -0
  24. package/dist/gemini/adapter.d.ts.map +1 -0
  25. package/dist/gemini/adapter.js +179 -0
  26. package/dist/gemini/adapter.js.map +1 -0
  27. package/dist/gemini/chat.d.ts +31 -75
  28. package/dist/gemini/chat.d.ts.map +1 -1
  29. package/dist/gemini/chat.js +38 -300
  30. package/dist/gemini/chat.js.map +1 -1
  31. package/dist/gemini/errors.d.ts +11 -0
  32. package/dist/gemini/errors.d.ts.map +1 -0
  33. package/dist/gemini/errors.js +14 -0
  34. package/dist/gemini/errors.js.map +1 -0
  35. package/dist/gemini/generate.d.ts +9 -20
  36. package/dist/gemini/generate.d.ts.map +1 -1
  37. package/dist/gemini/generate.js +43 -92
  38. package/dist/gemini/generate.js.map +1 -1
  39. package/dist/gemini/index.d.ts +3 -1
  40. package/dist/gemini/index.d.ts.map +1 -1
  41. package/dist/gemini/index.js +2 -1
  42. package/dist/gemini/index.js.map +1 -1
  43. package/dist/gemini/sse.d.ts +1 -2
  44. package/dist/gemini/sse.d.ts.map +1 -1
  45. package/dist/gemini/sse.js +1 -38
  46. package/dist/gemini/sse.js.map +1 -1
  47. package/dist/http.d.ts +20 -0
  48. package/dist/http.d.ts.map +1 -0
  49. package/dist/http.js +55 -0
  50. package/dist/http.js.map +1 -0
  51. package/dist/index.d.ts +13 -2
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +11 -4
  54. package/dist/index.js.map +1 -1
  55. package/dist/library.d.ts +29 -3
  56. package/dist/library.d.ts.map +1 -1
  57. package/dist/library.js +10 -12
  58. package/dist/library.js.map +1 -1
  59. package/dist/map-reduce.d.ts +9 -0
  60. package/dist/map-reduce.d.ts.map +1 -1
  61. package/dist/map-reduce.js +25 -19
  62. package/dist/map-reduce.js.map +1 -1
  63. package/dist/model.d.ts +196 -0
  64. package/dist/model.d.ts.map +1 -0
  65. package/dist/model.js +41 -0
  66. package/dist/model.js.map +1 -0
  67. package/dist/openai/adapter.d.ts +85 -0
  68. package/dist/openai/adapter.d.ts.map +1 -0
  69. package/dist/openai/adapter.js +293 -0
  70. package/dist/openai/adapter.js.map +1 -0
  71. package/dist/openai/index.d.ts +3 -0
  72. package/dist/openai/index.d.ts.map +1 -0
  73. package/dist/openai/index.js +2 -0
  74. package/dist/openai/index.js.map +1 -0
  75. package/dist/output-limit.d.ts +30 -0
  76. package/dist/output-limit.d.ts.map +1 -0
  77. package/dist/output-limit.js +92 -0
  78. package/dist/output-limit.js.map +1 -0
  79. package/dist/retry.d.ts +54 -0
  80. package/dist/retry.d.ts.map +1 -0
  81. package/dist/retry.js +111 -0
  82. package/dist/retry.js.map +1 -0
  83. package/dist/sse.d.ts +3 -0
  84. package/dist/sse.d.ts.map +1 -0
  85. package/dist/sse.js +39 -0
  86. package/dist/sse.js.map +1 -0
  87. package/dist/tools.d.ts +11 -0
  88. package/dist/tools.d.ts.map +1 -1
  89. package/dist/tools.js +85 -31
  90. package/dist/tools.js.map +1 -1
  91. package/dist/types.d.ts +28 -3
  92. package/dist/types.d.ts.map +1 -1
  93. package/docs/api.md +245 -27
  94. package/docs/configuration.md +83 -9
  95. package/docs/getting-started.md +67 -16
  96. package/docs/how-it-works.md +38 -2
  97. package/docs/security.md +18 -0
  98. package/package.json +21 -3
  99. package/src/anthropic/adapter.ts +454 -0
  100. package/src/anthropic/index.ts +2 -0
  101. package/src/ask.ts +675 -0
  102. package/src/budget.ts +71 -0
  103. package/src/evidence.ts +162 -0
  104. package/src/gemini/adapter.ts +218 -0
  105. package/src/gemini/chat.ts +61 -353
  106. package/src/gemini/errors.ts +15 -0
  107. package/src/gemini/generate.ts +50 -90
  108. package/src/gemini/index.ts +3 -1
  109. package/src/gemini/sse.ts +1 -34
  110. package/src/http.ts +59 -0
  111. package/src/index.ts +33 -4
  112. package/src/library.ts +39 -13
  113. package/src/map-reduce.ts +22 -16
  114. package/src/model.ts +200 -0
  115. package/src/openai/adapter.ts +345 -0
  116. package/src/openai/index.ts +2 -0
  117. package/src/output-limit.ts +99 -0
  118. package/src/retry.ts +132 -0
  119. package/src/sse.ts +34 -0
  120. package/src/tools.ts +91 -34
  121. package/src/types.ts +24 -3
package/src/ask.ts ADDED
@@ -0,0 +1,675 @@
1
+ // The tool loop, for any model: plan the documents, offer the tools, run the calls within the
2
+ // limits of the request, and end with an answer. A provider is an adapter (see model.ts).
3
+ import { evidenceOf, stubResult, type Evidence } from "./evidence.js";
4
+ import type { LargeFiles } from "./library.js";
5
+ import { Limiter } from "./limiter.js";
6
+ import {
7
+ DocumentsNotFoundError,
8
+ UsageMeter,
9
+ type ChatMessage,
10
+ type ModelAdapter,
11
+ type ModelMessage,
12
+ type ModelReply,
13
+ type ModelRequest,
14
+ type ModelTextMessage,
15
+ type ModelToolRound,
16
+ type ToolAnswer,
17
+ type ToolCall,
18
+ type ToolTurn,
19
+ type UsageTotals,
20
+ } from "./model.js";
21
+ import { estimateParts, REQUEST_BYTES_MARGIN } from "./plan.js";
22
+ import { statusOf, withRetry, type RetryNotice, type RetryOptions } from "./retry.js";
23
+ import { estimateTokens, jsonBytes } from "./text.js";
24
+ import { MAX_WHOLE_DOCUMENT_READS, TOOL_NAMES, toolResultSummary } from "./tools.js";
25
+ import type { Budget, DocumentPlan, GenerateText, ToolCallLimits, ToolOutput, ToolResult } from "./types.js";
26
+
27
+ /** Sent (invisibly to the user) when the model must stop using tools and answer. */
28
+ 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.";
29
+ /** The same, when the only tool was `view_pages`: the text of the files is in the prompt, not in tool results. */
30
+ 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.";
31
+ /** Sent to the answering model when an explorer model used no tool, so there is no tool result to answer from. */
32
+ export const FINAL_ANSWER_WITHOUT_TOOLS = "Answer my question now, from what is in this conversation. No tools are available for this reply: if the answer needs a part of a file that is not shown here, say so plainly.";
33
+ /**
34
+ * Added to the system instruction of an explorer model's requests: it gathers what the answer
35
+ * needs, and the other model writes the answer.
36
+ */
37
+ 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.";
38
+
39
+ /** The limits of one question. */
40
+ export type AskLimits = {
41
+ /**
42
+ * The most model requests of the chat for one question, counting the answer. Tools can run in
43
+ * all but the last: if the model is still calling tools then, the last request must be answered
44
+ * in text. Defaults to 12. With an explorer model the answer is always a request of its own, so
45
+ * the explorer has one less than this.
46
+ */
47
+ toolTurns?: number;
48
+ /**
49
+ * The most tool calls of one model turn that are run. A turn with more gets an error for each
50
+ * of the others, which tells the model to send it again if it is still needed. Defaults to 8.
51
+ */
52
+ callsPerTurn?: number;
53
+ /**
54
+ * How many times each document may be read whole (`analyze_whole_document`) for one question.
55
+ * One read of a large file is up to `maxMapChunks` model requests. Defaults to 1; 0 refuses
56
+ * every whole-file read.
57
+ */
58
+ wholeDocumentReads?: number;
59
+ /**
60
+ * A ceiling on the input tokens of one question, over all its requests, whole-file part reads
61
+ * included. Once it is reached no more tools run and the next request is the answer; a
62
+ * whole-file read that would pass it is refused. Unset: no ceiling.
63
+ */
64
+ inputTokens?: number;
65
+ /** The same ceiling, on the number of model requests: the chat's and the part reads' together. */
66
+ requests?: number;
67
+ };
68
+
69
+ export type AskOptions = {
70
+ files: LargeFiles;
71
+ /**
72
+ * The model that answers. With an `explorer` it only writes the answer, from what the explorer's
73
+ * tool calls returned. Without one it does both.
74
+ */
75
+ model: ModelAdapter;
76
+ /**
77
+ * A second model that explores the documents: it makes the tool calls (search, read, look at
78
+ * pages) and reads a whole file in parts. It may be of another provider than `model`. Left out,
79
+ * or the same adapter as `model`: one model does both.
80
+ */
81
+ explorer?: ModelAdapter | undefined;
82
+ /** Documents this conversation may use. Where their text or cards go: see `documentPlacement`. */
83
+ documentIds: string[];
84
+ /**
85
+ * Where document text and cards are added. "first" (the default) puts them at the start of the
86
+ * first user turn, where they stay as the conversation grows, so a provider's prompt cache can
87
+ * reuse them on every follow-up question. "last" appends them to the latest user turn; the
88
+ * document then moves on every turn and is billed in full each time.
89
+ */
90
+ documentPlacement?: "first" | "last";
91
+ /**
92
+ * The conversation; the last message must be the user's question. Plain turns
93
+ * (`{ role, text }`), the tool rounds an earlier question returned (`AskResult.toolTurns`), and
94
+ * turns with parts in the provider's own form (`{ role, parts: [{ text }, { native }] }`).
95
+ */
96
+ messages: ChatMessage[];
97
+ system?: string;
98
+ /** The user asking. Documents ingested with a different owner are treated as missing. */
99
+ owner?: string;
100
+ limits?: AskLimits;
101
+ /** How a model request that failed is sent again. Defaults to three more tries, with a wait that doubles. */
102
+ retry?: RetryOptions;
103
+ /**
104
+ * Budget fields for this question, in place of the library's. The budget is also made to fit
105
+ * what the adapters say of their models (`capabilities.contextTokens`, `maxRequestBytes`).
106
+ */
107
+ budget?: Partial<Budget>;
108
+ /** Offer `analyze_whole_document`, which reads a whole file in many model calls. Defaults to true. */
109
+ wholeDocumentAnalysis?: boolean;
110
+ /**
111
+ * Offer `view_pages` for PDFs whose original file is kept (`keepOriginals`), so the model can
112
+ * look at pictures, charts and layout. Defaults to true. It is offered only when every model of
113
+ * the question can be sent a file, and changes nothing for a library that keeps no originals.
114
+ */
115
+ viewPages?: boolean;
116
+ /** Answer text as it arrives. The adapter streams when this is set and it can. */
117
+ onText?: (delta: string) => void;
118
+ /** Short-lived status, such as "Searching app.log for “timeout”…". */
119
+ onActivity?: (text: string) => void;
120
+ /** A finished step, such as "Search app.log (exact) for “timeout” — 12 matching lines". */
121
+ onStep?: (text: string) => void;
122
+ signal?: AbortSignal;
123
+ };
124
+
125
+ export type AskResult = {
126
+ /**
127
+ * Everything the model wrote, including any remark it made before calling a tool. With an
128
+ * explorer model, only what the answering model wrote: the explorer's words are not shown.
129
+ */
130
+ text: string;
131
+ /**
132
+ * False when the model's last turn had no text: the prompt was blocked, the reply was cut off
133
+ * before any text, or the model produced a malformed tool call. `text` may then be empty or
134
+ * hold only an earlier remark, so show your own message instead of treating it as the answer.
135
+ */
136
+ answered: boolean;
137
+ /** Why the provider refused the prompt, when it did. */
138
+ blockReason?: string;
139
+ /** Every tool step taken, in order (also delivered through `onStep`). */
140
+ steps: string[];
141
+ /** What each tool call showed the model: the document, and the lines or pages. In call order. */
142
+ evidence: Evidence[];
143
+ /**
144
+ * The tool rounds of this question as plain JSON. Kept with the conversation and passed back in
145
+ * `messages` between this question and its answer, they let a later question use what was
146
+ * found here. Pages that were shown are not in them: only that they were.
147
+ */
148
+ toolTurns: ToolTurn[];
149
+ /** Which documents went in whole and which were searched. */
150
+ plan: DocumentPlan;
151
+ /** The budget the question ran with: the library's, fitted to the models. */
152
+ budget: Budget;
153
+ /** Model requests made for the chat itself, an explorer model's among them (whole-document part reads not included). */
154
+ turns: number;
155
+ finishReason?: string;
156
+ /** Tokens and requests of the whole question, part reads included, in all and for each model. */
157
+ usage: UsageTotals;
158
+ /** The provider's own usage object of the last chat response, as it came. */
159
+ lastUsage?: Record<string, unknown>;
160
+ };
161
+
162
+ const DEFAULT_TOOL_TURNS = 12;
163
+ const DEFAULT_CALLS_PER_TURN = 8;
164
+ /** Tool calls of one turn that run at the same time. */
165
+ const CALLS_AT_ONCE = 4;
166
+ /** With less room than this for its result, a call is not run. */
167
+ const LEAST_ROOM_CHARACTERS = 1_500;
168
+ /** Characters of a tool result for each token of room. A log full of IDs and numbers comes to about two. */
169
+ const CHARACTERS_PER_TOKEN = 2;
170
+ /** Bytes a character of a tool result may take in the request. */
171
+ const BYTES_PER_CHARACTER = 3;
172
+ /** Tool rounds whose results are kept in full when older ones are dropped to make room. */
173
+ const ROUNDS_KEPT = [3, 2, 1];
174
+
175
+ 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.";
176
+
177
+ type Size = { tokens: number; bytes: number };
178
+
179
+ const count = (value: number) => Math.max(0, Math.round(value)).toLocaleString("en-US");
180
+ const isRound = (message: ModelMessage): message is ModelToolRound => message.role === "tools";
181
+
182
+ /** How many pages a `view_pages` result showed: its `pages` is "12" or "12-14". */
183
+ function pagesShown(result: ToolResult): number {
184
+ const [first, last] = String(result.pages ?? "").split("-").map(Number);
185
+ return Number.isFinite(first) ? (Number.isFinite(last) ? last! - first! + 1 : 1) : 0;
186
+ }
187
+
188
+ /** The conversation as the loop keeps it: copies, so that nothing of the caller's is changed. */
189
+ function toMessages(given: ChatMessage[]): ModelMessage[] {
190
+ const messages = given.map((message): ModelMessage => {
191
+ if (message.role === "tools") {
192
+ const answers = message.calls.map(({ result, ...call }) => ({ call, result }));
193
+ return { role: "tools", calls: answers.map((answer) => answer.call), answers };
194
+ }
195
+ const role = message.role === "user" ? "user" : "assistant";
196
+ return "parts" in message ? { role, parts: [...message.parts] } : { role, parts: [{ text: message.text }] };
197
+ });
198
+ if (messages.at(-1)?.role !== "user") throw new Error("The last message must be the user's.");
199
+ return messages;
200
+ }
201
+
202
+ /** The size of the turns of text, and of the system instruction, with a margin for what frames them. */
203
+ function textSize(messages: ModelMessage[], system: string | undefined): Size {
204
+ let tokens = estimateTokens(system ?? "") + 2_000;
205
+ let bytes = jsonBytes(system ?? "") + 8_000;
206
+ for (const message of messages) {
207
+ if (isRound(message)) continue;
208
+ for (const part of message.parts) {
209
+ if (typeof part.text === "string") {
210
+ tokens += estimateTokens(part.text);
211
+ bytes += jsonBytes(part.text);
212
+ } else {
213
+ const size = (JSON.stringify(part.native) ?? "").length;
214
+ bytes += size;
215
+ // Media: about 258 tokens per image or PDF page; ~4 tokens/KB is a cautious stand-in.
216
+ tokens += Math.ceil(size / 256);
217
+ }
218
+ }
219
+ }
220
+ return { tokens, bytes };
221
+ }
222
+
223
+ /** Keeps count of how large the request is, in the library's estimate of tokens and in bytes. */
224
+ class RequestMeter {
225
+ /** Everything that does not change during the question: the conversation as asked, the documents, the tool list. */
226
+ fixed: Size = { tokens: 0, bytes: 0 };
227
+ private readonly sizes = new WeakMap<ModelToolRound, Size>();
228
+ /** How much larger the provider counted the last request than the estimate did. Never below 1. */
229
+ private factor = 1;
230
+
231
+ constructor(private readonly pageTokens: number) {}
232
+
233
+ private round(round: ModelToolRound): Size {
234
+ const known = this.sizes.get(round);
235
+ if (known) return known;
236
+ let tokens = 0;
237
+ let bytes = round.raw === undefined ? 0 : (JSON.stringify(round.raw) ?? "").length;
238
+ for (const call of round.calls) {
239
+ const sent = `${call.name}${JSON.stringify(call.args)}`;
240
+ tokens += estimateTokens(sent) + 8;
241
+ if (round.raw === undefined) bytes += Buffer.byteLength(sent) + 64;
242
+ }
243
+ for (const answer of round.answers) {
244
+ const sent = JSON.stringify(answer.result);
245
+ tokens += estimateTokens(sent) + 8;
246
+ bytes += Buffer.byteLength(sent) + 96;
247
+ for (const file of answer.files ?? []) bytes += Math.ceil(file.bytes.length / 3) * 4 + 512;
248
+ if (answer.files?.length) tokens += pagesShown(answer.result) * this.pageTokens;
249
+ }
250
+ const size = { tokens, bytes };
251
+ this.sizes.set(round, size);
252
+ return size;
253
+ }
254
+
255
+ /** The size of the tool rounds among these messages. */
256
+ rounds(messages: ModelMessage[]): Size {
257
+ const sum = { tokens: 0, bytes: 0 };
258
+ for (const message of messages) {
259
+ if (!isRound(message)) continue;
260
+ const size = this.round(message);
261
+ sum.tokens += size.tokens;
262
+ sum.bytes += size.bytes;
263
+ }
264
+ return sum;
265
+ }
266
+
267
+ /** The estimate for a request with these messages, as it is. */
268
+ estimate(messages: ModelMessage[]): Size {
269
+ const rounds = this.rounds(messages);
270
+ return { tokens: this.fixed.tokens + rounds.tokens, bytes: this.fixed.bytes + rounds.bytes };
271
+ }
272
+
273
+ /** The same, raised by what the provider's own count of an earlier request showed. */
274
+ current(messages: ModelMessage[]): Size {
275
+ const size = this.estimate(messages);
276
+ return { tokens: Math.ceil(size.tokens * this.factor), bytes: size.bytes };
277
+ }
278
+
279
+ /** Takes note of what the provider counted for a request that was estimated at `estimated` tokens. */
280
+ observe(estimated: number, counted: number | undefined): void {
281
+ if (estimated > 0 && typeof counted === "number" && counted > 0) this.factor = Math.min(2, Math.max(1, counted / estimated));
282
+ }
283
+ }
284
+
285
+ function retryMessage({ error, delayMs }: RetryNotice): string {
286
+ const status = statusOf(error);
287
+ const seconds = delayMs >= 1_000 ? ` in ${Math.round(delayMs / 1_000)} s` : "";
288
+ return `${status ? `The model did not answer (HTTP ${status})` : "The model could not be reached"}. Trying again${seconds}…`;
289
+ }
290
+
291
+ /**
292
+ * Answers a chat turn about large documents with any model that has an adapter.
293
+ * Documents that fit go into the prompt whole; otherwise the model gets search and read tools and
294
+ * this runs the tool loop, ending with a request that must be answered in text, so there is always
295
+ * an answer. With an `explorer`, that model runs the tool loop and `model` writes the answer.
296
+ */
297
+ export async function askWithFiles(options: AskOptions): Promise<AskResult> {
298
+ const { files, model, signal } = options;
299
+ // A second model for the requests that use tools. The answering model itself is not one.
300
+ const explorer = options.explorer && options.explorer !== model ? options.explorer : undefined;
301
+ const toolModel = explorer ?? model;
302
+ const models = explorer ? [model, explorer] : [model];
303
+ const limits = options.limits ?? {};
304
+ const usage = new UsageMeter();
305
+
306
+ // The budget is counted in the library's estimate of tokens. A model whose tokenizer counts
307
+ // more of them for the same text has, in those terms, a smaller window.
308
+ const scale = Math.max(...models.map((adapter) => (adapter.capabilities.tokenScale && adapter.capabilities.tokenScale > 0 ? adapter.capabilities.tokenScale : 1)));
309
+ const declared = (pick: (adapter: ModelAdapter) => number | undefined): number[] => models.map(pick).filter((value): value is number => typeof value === "number" && value > 0);
310
+ const own = files.budgetFor(options.budget);
311
+ const windowTokens = Math.floor(Math.min(own.contextTokens, ...declared((adapter) => adapter.capabilities.contextTokens)) / scale);
312
+ // A reply that is counted against the window: that part of it is not there for the prompt.
313
+ const replyTokens = Math.ceil(Math.max(0, ...declared((adapter) => adapter.capabilities.outputTokens)) / scale);
314
+ const requestBytesLimit = declared((adapter) => adapter.capabilities.maxRequestBytes);
315
+ const budget = files.budgetFor(options.budget, {
316
+ contextTokens: Math.max(Math.floor(windowTokens / 4), windowTokens - replyTokens),
317
+ ...(requestBytesLimit.length > 0 ? { maxRequestBytes: Math.min(...requestBytesLimit) } : {}),
318
+ });
319
+ // What a page costs, in the same terms. Pages are shown to every model of the question.
320
+ const pageTokens = Math.max(1, ...models.map((adapter) => adapter.capabilities.pageTokens)) / scale;
321
+ const canShowFiles = models.every((adapter) => adapter.capabilities.toolFiles !== "none");
322
+ // Every model must be able to take a conversation whose earlier turns were made shorter.
323
+ const canShrink = models.every((adapter) => !adapter.capabilities.appendOnly);
324
+
325
+ const messages = toMessages(options.messages);
326
+ const meter = new RequestMeter(pageTokens);
327
+ const asText = textSize(messages, options.system);
328
+ const earlier = meter.rounds(messages);
329
+ const prepared = await files.prepare(options.documentIds, { tokens: asText.tokens + earlier.tokens, bytes: asText.bytes + earlier.bytes }, {
330
+ ...(options.owner !== undefined ? { owner: options.owner } : {}),
331
+ viewPages: options.viewPages !== false && canShowFiles,
332
+ budget,
333
+ });
334
+ if (prepared.missing.length) throw new DocumentsNotFoundError(prepared.missing);
335
+
336
+ const blocks = [...new Set(options.documentIds)].map((id) => prepared.blocks.get(id)).filter((block): block is string => Boolean(block));
337
+ if (blocks.length) {
338
+ const block = { text: blocks.join("\n\n") };
339
+ if (options.documentPlacement === "last") (messages.at(-1) as ModelTextMessage).parts.push(block);
340
+ // The last turn is the user's, so there is always a first user turn.
341
+ else (messages.find((message) => message.role === "user") as ModelTextMessage).parts.unshift(block);
342
+ }
343
+ const system = [options.system?.trim(), prepared.instruction].filter(Boolean).join("\n\n");
344
+
345
+ // The size of what stays in every request: the text as asked, the documents, the tool guide.
346
+ const whole = new Set(prepared.plan.inline.map((meta) => meta.id));
347
+ meter.fixed = {
348
+ tokens: asText.tokens + prepared.plan.inlineTokens + estimateTokens(prepared.instruction),
349
+ bytes: asText.bytes + prepared.plan.inlineBytes + jsonBytes(prepared.instruction),
350
+ };
351
+ for (const [id, block] of prepared.blocks) {
352
+ if (whole.has(id)) continue;
353
+ meter.fixed.tokens += estimateTokens(block);
354
+ meter.fixed.bytes += jsonBytes(block);
355
+ }
356
+
357
+ let text = "";
358
+ let turns = 0;
359
+ let finishReason: string | undefined;
360
+ let blockReason: string | undefined;
361
+ let lastUsage: Record<string, unknown> | undefined;
362
+ const steps: string[] = [];
363
+ const evidence: Evidence[] = [];
364
+ const emit = (delta: string) => {
365
+ text += delta;
366
+ options.onText?.(delta);
367
+ };
368
+ const step = (line: string) => {
369
+ steps.push(line);
370
+ options.onStep?.(line);
371
+ };
372
+
373
+ // A model turn in its provider's own form goes back only to the adapter it came from. Any other
374
+ // model gets the tool calls alone: a thought signature belongs to the model that wrote it, and
375
+ // an explorer's thoughts and remarks are not what the files say.
376
+ const rawOwner = new WeakMap<ModelToolRound, ModelAdapter>();
377
+ const plain = new WeakMap<ModelToolRound, ModelToolRound>();
378
+ const callsOnly = (round: ModelToolRound): ModelToolRound => {
379
+ let known = plain.get(round);
380
+ if (!known) {
381
+ known = { role: "tools", calls: round.calls, answers: round.answers };
382
+ plain.set(round, known);
383
+ }
384
+ return known;
385
+ };
386
+ const viewFor = (adapter: ModelAdapter, list: ModelMessage[] = messages): ModelMessage[] => list.map((message) => (
387
+ isRound(message) && message.raw !== undefined && rawOwner.get(message) !== adapter ? callsOnly(message) : message
388
+ ));
389
+
390
+ /**
391
+ * One model request of the chat. Text is passed on as it arrives when it is `shown`: an
392
+ * explorer's words are not, because the answer comes from the other model. A request that
393
+ * failed is sent again by the rule of `retry`, unless text of it was already shown.
394
+ */
395
+ const request = async (adapter: ModelAdapter, body: ModelRequest, shown: boolean): Promise<ModelReply> => {
396
+ turns++;
397
+ let separated = text.length === 0;
398
+ let got = "";
399
+ const write = (delta: string) => {
400
+ if (!delta) return;
401
+ if (!separated) {
402
+ emit("\n\n");
403
+ separated = true;
404
+ }
405
+ got += delta;
406
+ emit(delta);
407
+ };
408
+ const estimated = meter.estimate(body.messages).tokens;
409
+ const reply = await withRetry(() => adapter.send(body, {
410
+ ...(signal ? { signal } : {}),
411
+ ...(shown && options.onText ? { onText: write } : {}),
412
+ }), {
413
+ retry: options.retry,
414
+ signal,
415
+ canRetry: () => got.length === 0,
416
+ onRetry: (notice) => options.onActivity?.(retryMessage(notice)),
417
+ });
418
+ // Text the adapter did not pass on as it came (no streaming was asked for, or it cannot).
419
+ if (shown && reply.text.length > got.length && reply.text.startsWith(got)) write(reply.text.slice(got.length));
420
+ usage.add(adapter.id, reply.usage);
421
+ meter.observe(estimated, typeof reply.usage?.inputTokens === "number" ? reply.usage.inputTokens / scale : undefined);
422
+ if (reply.blockReason) blockReason = reply.blockReason;
423
+ finishReason = reply.finishReason ?? finishReason;
424
+ lastUsage = reply.providerUsage ?? lastUsage;
425
+ return reply;
426
+ };
427
+ // What a model wrote before it was stopped by a refusal is not an answer.
428
+ const wrote = (reply: ModelReply) => reply.text.trim().length > 0 && !reply.blockReason;
429
+
430
+ const asked = messages.length;
431
+ const result = (answered: boolean): AskResult => ({
432
+ text,
433
+ answered,
434
+ ...(blockReason ? { blockReason } : {}),
435
+ steps,
436
+ evidence,
437
+ // The rounds as the model last had them. A file cannot be kept as JSON: what is kept says that it was shown.
438
+ toolTurns: messages.slice(asked).filter(isRound).map((round) => ({
439
+ role: "tools" as const,
440
+ calls: round.answers.map(({ call: { problem: _problem, ...call }, result: returned, files: shownFiles }) => ({
441
+ ...call,
442
+ result: shownFiles?.length ? stubResult(call, returned, true) ?? returned : returned,
443
+ })),
444
+ })),
445
+ plan: prepared.plan,
446
+ budget,
447
+ turns,
448
+ ...(finishReason ? { finishReason } : {}),
449
+ usage: usage.totals,
450
+ ...(lastUsage ? { lastUsage } : {}),
451
+ });
452
+
453
+ // Tools are needed for a file that is too large to send whole, and for a PDF whose pages can be
454
+ // looked at: that one may have its whole text in the prompt and still hide a chart from the model.
455
+ const { searchable } = prepared.plan;
456
+ const { viewable } = prepared;
457
+ if (searchable.length === 0 && viewable.length === 0) return result(wrote(await request(model, { system, messages }, true)));
458
+
459
+ // Reading a whole file in parts is exploring too: the explorer model's work, when there is one.
460
+ const partReader = options.wholeDocumentAnalysis === false ? undefined : toolModel.generateText;
461
+ const generate: GenerateText | undefined = partReader && ((part) => partReader({
462
+ ...part,
463
+ onUsage: (used) => {
464
+ usage.add(toolModel.id, used);
465
+ part.onUsage?.(used);
466
+ },
467
+ }));
468
+ const tools = files.tools(searchable, {
469
+ ...(generate ? { generate } : {}),
470
+ onProgress: (event) => options.onActivity?.(`${event.message}…`),
471
+ ...(signal ? { signal } : {}),
472
+ ...(viewable.length > 0 ? { viewPages: viewable } : {}),
473
+ maxWholeDocumentReads: limits.wholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS,
474
+ ...(options.retry ? { retry: options.retry } : {}),
475
+ budget,
476
+ });
477
+ const declarations = tools.declarations;
478
+ // The requests that use the tools are the chat's own, or an explorer model's: the same
479
+ // conversation, and a line that says what its part is.
480
+ const toolSystem = explorer ? `${system}\n\n${EXPLORER_INSTRUCTION}` : system;
481
+ const sentTools = JSON.stringify(declarations);
482
+ meter.fixed.tokens += estimateTokens(sentTools) + (explorer ? estimateTokens(EXPLORER_INSTRUCTION) : 0);
483
+ meter.fixed.bytes += Buffer.byteLength(sentTools) + (explorer ? EXPLORER_INSTRUCTION.length : 0);
484
+ if (searchable.length > 0) options.onActivity?.(`Too large to read at once: ${searchable.map((meta) => meta.name).join(", ")}. Searching instead…`);
485
+
486
+ // Pages the model looks at stay in the request until the question is answered, so they are
487
+ // counted twice: as bytes against the request limit, and as tokens against half of what the
488
+ // budget keeps free for tool results and the answer.
489
+ const { maxRequestBytes, reservedTokens } = budget;
490
+ const bytesKeptFree = Math.max(REQUEST_BYTES_MARGIN, Math.floor(maxRequestBytes / 10));
491
+ let pagesLeft = Math.floor(reservedTokens / 2 / pageTokens);
492
+ // The results of the text tools may fill the context window up to half of what is kept free (the
493
+ // other half is the answer's), and the request up to a small margin.
494
+ const tokenLimit = budget.contextTokens - Math.floor(reservedTokens / 2);
495
+ const byteLimit = maxRequestBytes - Math.max(32_768, Math.floor(maxRequestBytes / 50));
496
+ /** Characters of tool results that still fit, with a model turn that is about to be answered. */
497
+ const room = (pending: ModelToolRound): number => {
498
+ const now = meter.current([...messages, pending]);
499
+ return Math.floor(Math.min((tokenLimit - now.tokens) * CHARACTERS_PER_TOKEN, (byteLimit - now.bytes) / BYTES_PER_CHARACTER));
500
+ };
501
+ /**
502
+ * Makes room: the results of every tool round but the last `keep` are replaced by short
503
+ * stand-ins that say which lines or pages they showed. True when anything was replaced.
504
+ */
505
+ const shrink = (keep: number): boolean => {
506
+ const rounds = messages.flatMap((message, index) => (isRound(message) ? [index] : []));
507
+ let changed = false;
508
+ for (const index of rounds.slice(0, Math.max(0, rounds.length - keep))) {
509
+ const round = messages[index] as ModelToolRound;
510
+ let touched = false;
511
+ const answers = round.answers.map((answer): ToolAnswer => {
512
+ const stub = stubResult(answer.call, answer.result, (answer.files?.length ?? 0) > 0);
513
+ if (!stub) return answer;
514
+ touched = true;
515
+ return { call: answer.call, result: stub };
516
+ });
517
+ if (!touched) continue;
518
+ const smaller: ModelToolRound = { ...round, answers };
519
+ const owner = rawOwner.get(round);
520
+ if (owner) rawOwner.set(smaller, owner);
521
+ messages[index] = smaller;
522
+ changed = true;
523
+ }
524
+ return changed;
525
+ };
526
+
527
+ const maxTurns = Math.max(1, Math.trunc(limits.toolTurns ?? DEFAULT_TOOL_TURNS));
528
+ const maxCalls = Math.max(1, Math.trunc(limits.callsPerTurn ?? DEFAULT_CALLS_PER_TURN));
529
+ /** True once the question has used what it may: no more tools run. One request is kept for the answer. */
530
+ const spent = (): boolean => (
531
+ (limits.inputTokens !== undefined && usage.totals.inputTokens >= limits.inputTokens)
532
+ || (limits.requests !== undefined && usage.totals.requests >= limits.requests - 1)
533
+ );
534
+ /** A whole-file read is many requests at once: one that would pass a ceiling of the question is not started. */
535
+ const tooCostly = (call: ToolCall): string | undefined => {
536
+ if (call.name !== TOOL_NAMES.analyze) return undefined;
537
+ const meta = searchable.find((document) => document.id === call.args.document_id);
538
+ if (!meta) return undefined;
539
+ if (limits.inputTokens !== undefined) {
540
+ const cost = Math.ceil(meta.estimatedTokens * scale);
541
+ const left = limits.inputTokens - usage.totals.inputTokens;
542
+ if (cost > left) return `Not run: reading all of ${meta.name} takes about ${count(cost)} input tokens, and ${count(left)} are left of the ${count(limits.inputTokens)} this question may use. Use search_document and read_document.`;
543
+ }
544
+ if (limits.requests !== undefined) {
545
+ // The parts, a merge of their notes, the answer of the read, and the answer of the question.
546
+ const cost = estimateParts(meta, budget) + 3;
547
+ const left = limits.requests - usage.totals.requests;
548
+ if (cost > left) return `Not run: reading all of ${meta.name} takes about ${count(cost)} model requests, and ${count(left)} are left of the ${count(limits.requests)} this question may make. Use search_document and read_document.`;
549
+ }
550
+ return undefined;
551
+ };
552
+
553
+ let answered = false;
554
+ let outOfRoom = false;
555
+ // Tools run in at most maxTurns - 1 requests. The last request is the one below that must be
556
+ // answered in text, so a model that never stops calling tools does not cost a request whose
557
+ // calls are thrown away.
558
+ for (let round = 1; round < maxTurns && !outOfRoom && !spent(); round++) {
559
+ const reply = await request(toolModel, { system: toolSystem, messages: viewFor(toolModel), tools: declarations, toolChoice: "auto" }, !explorer);
560
+ if (reply.calls.length === 0) {
561
+ // Text from this turn is the answer. A remark made earlier, before a tool call, is not.
562
+ // Neither is anything an explorer model writes: the answer is asked for below.
563
+ answered = wrote(reply) && !explorer;
564
+ break;
565
+ }
566
+ const pending: ModelToolRound = { role: "tools", calls: reply.calls, answers: [], ...(reply.raw !== undefined ? { raw: reply.raw } : {}) };
567
+ if (reply.raw !== undefined) rawOwner.set(pending, toolModel);
568
+ // Every call must be answered, but not every call is run: a turn of sixty reads would build
569
+ // a request that no model accepts, and a file can ask a model for exactly that.
570
+ const run = reply.calls.slice(0, maxCalls);
571
+ const most = (call: ToolCall) => tools.resultCharacters(call.name);
572
+ const needed = run.reduce((sum, call) => sum + (call.name === TOOL_NAMES.view ? 0 : most(call)), 0);
573
+ let left = room(pending);
574
+ let dropped = false;
575
+ for (const keep of canShrink ? ROUNDS_KEPT : []) {
576
+ if (left >= needed) break;
577
+ if (shrink(keep)) {
578
+ dropped = true;
579
+ left = room(pending);
580
+ }
581
+ }
582
+ if (dropped) step("Older tool results were shortened to make room in the request");
583
+
584
+ type Planned = { call: ToolCall; label: string; refusal?: string; limits?: ToolCallLimits };
585
+ const planned = run.map((call): Planned => {
586
+ const label = tools.has(call.name) ? tools.describe(call.name, call.args) : call.name;
587
+ // A call that did not arrive whole is not run: the model is told, and can send it again.
588
+ if (call.problem) return { call, label, refusal: call.problem };
589
+ // A look at pages returns a file and a few words: the file has its own room, worked out when it runs.
590
+ if (call.name === TOOL_NAMES.view) return { call, label };
591
+ const refusal = tooCostly(call);
592
+ if (refusal) return { call, label, refusal };
593
+ const cap = most(call);
594
+ if (left < Math.min(cap, LEAST_ROOM_CHARACTERS)) {
595
+ outOfRoom = true;
596
+ return { call, label, refusal: NO_ROOM };
597
+ }
598
+ const allowed = Math.min(cap, left);
599
+ left -= allowed;
600
+ return { call, label, ...(allowed < cap ? { limits: { maxResultCharacters: allowed } } : {}) };
601
+ });
602
+
603
+ // The calls of a turn run together, a few at a time. Looks at pages take their turns, one
604
+ // after another: each is given the room the ones before it left.
605
+ const together = new Limiter(CALLS_AT_ONCE);
606
+ let looks: Promise<unknown> = Promise.resolve();
607
+ // The size of the request as it stands, worked out when the first look at pages in this turn needs it.
608
+ let requestBytes: number | undefined;
609
+ const outputs = planned.map(({ call, label, refusal, limits: callLimits }): Promise<ToolOutput> => {
610
+ if (refusal) return Promise.resolve({ result: { error: refusal }, files: [] });
611
+ if (call.name === TOOL_NAMES.view) {
612
+ const look = looks.then(async () => {
613
+ signal?.throwIfAborted();
614
+ options.onActivity?.(`${label}…`);
615
+ if (requestBytes === undefined) {
616
+ const waiting: ModelRequest = { system: toolSystem, messages: [...viewFor(toolModel), pending], tools: declarations, toolChoice: "auto" };
617
+ requestBytes = toolModel.requestBytes?.(waiting) ?? meter.estimate(waiting.messages).bytes;
618
+ }
619
+ // Base64 turns three bytes into four characters.
620
+ const output = await tools.executeWithFiles(call.name, call.args, { maxFileBytes: Math.floor((maxRequestBytes - bytesKeptFree - requestBytes) * 3 / 4), maxPages: pagesLeft });
621
+ for (const file of output.files) requestBytes += Math.ceil(file.bytes.length / 3) * 4 + 512;
622
+ if (output.files.length > 0) pagesLeft -= pagesShown(output.result);
623
+ return output;
624
+ });
625
+ looks = look.catch(() => undefined);
626
+ return look;
627
+ }
628
+ return together.acquire(signal).then(async (release) => {
629
+ try {
630
+ options.onActivity?.(`${label}…`);
631
+ return await tools.executeWithFiles(call.name, call.args, callLimits);
632
+ } finally {
633
+ release();
634
+ }
635
+ });
636
+ });
637
+ // One that fails (the question was stopped) is reported below, in call order; the others must not go unheard.
638
+ for (const output of outputs) output.catch(() => undefined);
639
+
640
+ const turnsLeft = outOfRoom ? 0 : maxTurns - round - 1;
641
+ const answers: ToolAnswer[] = [];
642
+ for (const [index, { call, label }] of planned.entries()) {
643
+ const output = await outputs[index]!;
644
+ step(`${label}${toolResultSummary(label, output.result)}`);
645
+ const shown = evidenceOf(call, output.result);
646
+ if (shown) evidence.push(shown);
647
+ answers.push({ call, result: { ...output.result, tool_turns_left: turnsLeft }, files: output.files });
648
+ }
649
+ for (const call of reply.calls.slice(maxCalls)) {
650
+ answers.push({ call, result: { error: `Not run: one turn runs at most ${maxCalls} tool calls. Send this call again if you still need it.`, tool_turns_left: turnsLeft }, files: [] });
651
+ }
652
+ if (reply.calls.length > maxCalls) step(`${reply.calls.length - maxCalls} more tool calls in this turn were not run (at most ${maxCalls} a turn)`);
653
+ const done: ModelToolRound = { ...pending, answers };
654
+ if (reply.raw !== undefined) rawOwner.set(done, toolModel);
655
+ messages.push(done);
656
+ }
657
+
658
+ // Out of tool turns or of room, or the last turn had no text (cut off, or a malformed tool call):
659
+ // ask once more, for an answer in text. A blocked prompt would only be blocked again.
660
+ // With an explorer model this request is always made: it is the one the answering model gets.
661
+ if (!answered && !blockReason) {
662
+ options.onActivity?.("Writing the answer…");
663
+ let closing = searchable.length > 0 ? FINAL_ANSWER_REQUEST : FINAL_ANSWER_AFTER_PAGES;
664
+ // The answering model gets the explorer's calls and what they returned, and nothing else of it.
665
+ if (explorer && steps.length === 0) closing = FINAL_ANSWER_WITHOUT_TOOLS;
666
+ const reply = await request(model, {
667
+ system,
668
+ messages: [...viewFor(model), { role: "user", parts: [{ text: closing }] }],
669
+ tools: declarations,
670
+ toolChoice: "none",
671
+ }, true);
672
+ answered = wrote(reply);
673
+ }
674
+ return result(answered);
675
+ }