llm-large-files 0.5.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1719 -466
- package/README.md +190 -60
- package/dist/analyze.d.ts +8 -1
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +198 -54
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts +14 -3
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +194 -40
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +63 -7
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +1131 -214
- package/dist/ask.js.map +1 -1
- package/dist/decode.d.ts +19 -0
- package/dist/decode.d.ts.map +1 -0
- package/dist/decode.js +97 -0
- package/dist/decode.js.map +1 -0
- package/dist/encoding.d.ts +17 -0
- package/dist/encoding.d.ts.map +1 -0
- package/dist/encoding.js +852 -0
- package/dist/encoding.js.map +1 -0
- package/dist/errors.d.ts +59 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +80 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +339 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +163 -0
- package/dist/events.js.map +1 -0
- package/dist/evidence.d.ts +2 -0
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +9 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +26 -7
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +180 -314
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +17 -8
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +117 -66
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +23 -3
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +6 -2
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +5 -1
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +11 -2
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/errors.d.ts +9 -4
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +32 -0
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +10 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +33 -10
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -2
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -1
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -1
- package/dist/gemini/sse.js.map +1 -1
- package/dist/groups.d.ts +54 -0
- package/dist/groups.d.ts.map +1 -0
- package/dist/groups.js +136 -0
- package/dist/groups.js.map +1 -0
- package/dist/html.d.ts +11 -0
- package/dist/html.d.ts.map +1 -0
- package/dist/html.js +1112 -0
- package/dist/html.js.map +1 -0
- package/dist/http.d.ts +116 -0
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +347 -1
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +13 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -5
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +67 -5
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +449 -93
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +2 -1
- package/dist/limiter.d.ts.map +1 -1
- package/dist/limiter.js +3 -2
- package/dist/limiter.js.map +1 -1
- package/dist/map-reduce.d.ts +28 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +240 -52
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +84 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +190 -2
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +20 -4
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +184 -28
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +4 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +38 -0
- package/dist/node/ingest-child.d.ts.map +1 -0
- package/dist/node/ingest-child.js +42 -0
- package/dist/node/ingest-child.js.map +1 -0
- package/dist/node/isolated.d.ts +88 -0
- package/dist/node/isolated.d.ts.map +1 -0
- package/dist/node/isolated.js +381 -0
- package/dist/node/isolated.js.map +1 -0
- package/dist/node/sse.d.ts +59 -0
- package/dist/node/sse.d.ts.map +1 -0
- package/dist/node/sse.js +174 -0
- package/dist/node/sse.js.map +1 -0
- package/dist/office.d.ts +105 -0
- package/dist/office.d.ts.map +1 -0
- package/dist/office.js +1092 -0
- package/dist/office.js.map +1 -0
- package/dist/openai/adapter.d.ts +29 -5
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +325 -37
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +14 -2
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +39 -10
- package/dist/output-limit.js.map +1 -1
- package/dist/pause.d.ts +24 -0
- package/dist/pause.d.ts.map +1 -0
- package/dist/pause.js +38 -0
- package/dist/pause.js.map +1 -0
- package/dist/pdf-pages.d.ts +32 -2
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +277 -20
- package/dist/pdf-pages.js.map +1 -1
- package/dist/pdf-pictures.d.ts +30 -3
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +50 -8
- package/dist/pdf-pictures.js.map +1 -1
- package/dist/pdf-work.d.ts +40 -0
- package/dist/pdf-work.d.ts.map +1 -0
- package/dist/pdf-work.js +734 -0
- package/dist/pdf-work.js.map +1 -0
- package/dist/peers.d.ts +8 -0
- package/dist/peers.d.ts.map +1 -0
- package/dist/peers.js +32 -0
- package/dist/peers.js.map +1 -0
- package/dist/plan.d.ts +22 -4
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +61 -12
- package/dist/plan.js.map +1 -1
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +4 -2
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +23 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +33 -3
- package/dist/retry.js.map +1 -1
- package/dist/search.d.ts +107 -24
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +803 -149
- package/dist/search.js.map +1 -1
- package/dist/sse.d.ts +35 -2
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +145 -31
- package/dist/sse.js.map +1 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +5 -2
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +9 -1
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +28 -9
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +87 -3
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +526 -24
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +61 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +461 -46
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +103 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/word-styles.d.ts +102 -0
- package/dist/word-styles.d.ts.map +1 -0
- package/dist/word-styles.js +419 -0
- package/dist/word-styles.js.map +1 -0
- package/dist/xlsx.d.ts +23 -0
- package/dist/xlsx.d.ts.map +1 -0
- package/dist/xlsx.js +511 -0
- package/dist/xlsx.js.map +1 -0
- package/dist/xml-stream.d.ts +55 -0
- package/dist/xml-stream.d.ts.map +1 -0
- package/dist/xml-stream.js +235 -0
- package/dist/xml-stream.js.map +1 -0
- package/dist/zip-directory.d.ts +43 -0
- package/dist/zip-directory.d.ts.map +1 -0
- package/dist/zip-directory.js +130 -0
- package/dist/zip-directory.js.map +1 -0
- package/docs/README.md +288 -0
- package/docs/api.md +37 -381
- package/docs/configuration.md +28 -558
- package/docs/getting-started.md +407 -223
- package/docs/guides/anthropic.md +590 -0
- package/docs/guides/conversations.md +629 -0
- package/docs/guides/costs-and-limits.md +728 -0
- package/docs/guides/deployment.md +720 -0
- package/docs/guides/errors-and-reliability.md +748 -0
- package/docs/guides/explorer-model.md +399 -0
- package/docs/guides/openai-compatible.md +602 -0
- package/docs/guides/own-adapter-and-loop.md +1169 -0
- package/docs/guides/pdfs.md +1024 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1203 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1590 -0
- package/docs/how-it-works.md +1035 -164
- package/docs/measurements.md +881 -0
- package/docs/publishing.md +274 -46
- package/docs/reference/anthropic.md +427 -0
- package/docs/reference/ask.md +910 -0
- package/docs/reference/errors-and-retries.md +760 -0
- package/docs/reference/events.md +1001 -0
- package/docs/reference/gemini.md +827 -0
- package/docs/reference/library.md +1598 -0
- package/docs/reference/node.md +706 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +1031 -0
- package/docs/security.md +940 -101
- package/docs/troubleshooting.md +1410 -0
- package/package.json +7 -3
- package/src/analyze.ts +204 -49
- package/src/anthropic/adapter.ts +200 -40
- package/src/ask.ts +1151 -210
- package/src/decode.ts +89 -0
- package/src/encoding.ts +850 -0
- package/src/errors.ts +125 -0
- package/src/events.ts +451 -0
- package/src/evidence.ts +11 -2
- package/src/extract.ts +191 -308
- package/src/gemini/adapter.ts +127 -70
- package/src/gemini/chat.ts +28 -4
- package/src/gemini/endpoints.ts +12 -2
- package/src/gemini/errors.ts +34 -1
- package/src/gemini/generate.ts +42 -13
- package/src/gemini/index.ts +3 -3
- package/src/gemini/sse.ts +1 -1
- package/src/groups.ts +162 -0
- package/src/html.ts +1071 -0
- package/src/http.ts +376 -1
- package/src/index.ts +29 -6
- package/src/library.ts +498 -93
- package/src/limiter.ts +6 -1
- package/src/map-reduce.ts +252 -51
- package/src/model.ts +244 -4
- package/src/node/handlers.ts +196 -31
- package/src/node/index.ts +4 -0
- package/src/node/ingest-child.ts +61 -0
- package/src/node/isolated.ts +464 -0
- package/src/node/sse.ts +198 -0
- package/src/office.ts +1047 -0
- package/src/openai/adapter.ts +319 -38
- package/src/output-limit.ts +44 -8
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +270 -20
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/peers.ts +29 -0
- package/src/plan.ts +70 -12
- package/src/ranged.ts +4 -2
- package/src/retry.ts +49 -5
- package/src/search.ts +800 -155
- package/src/sse.ts +153 -28
- package/src/stores.ts +5 -2
- package/src/text-index.ts +30 -9
- package/src/text.ts +524 -23
- package/src/tools.ts +445 -46
- package/src/types.ts +108 -5
- package/src/word-styles.ts +420 -0
- package/src/xlsx.ts +478 -0
- package/src/xml-stream.ts +224 -0
- package/src/zip-directory.ts +136 -0
package/dist/ask.js
CHANGED
|
@@ -1,18 +1,23 @@
|
|
|
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
|
+
import { eventErrorOf, EventEmitter, eventStream, newRunId } from "./events.js";
|
|
3
4
|
import { evidenceOf, stubResult } from "./evidence.js";
|
|
5
|
+
import { isCutReply, until } from "./http.js";
|
|
4
6
|
import { Limiter } from "./limiter.js";
|
|
5
|
-
import { DocumentsNotFoundError, UsageMeter, } from "./model.js";
|
|
7
|
+
import { DocumentsNotFoundError, errorKindOf, laterResult, rateAllowanceOf, UsageMeter, } from "./model.js";
|
|
6
8
|
import { estimateParts, REQUEST_BYTES_MARGIN } from "./plan.js";
|
|
7
9
|
import { statusOf, withRetry } from "./retry.js";
|
|
8
|
-
import { estimateTokens, jsonBytes } from "./text.js";
|
|
9
|
-
import { MAX_WHOLE_DOCUMENT_READS, TOOL_NAMES, toolResultSummary } from "./tools.js";
|
|
10
|
+
import { estimateTokens, jsonBytes, wellFormedJson } from "./text.js";
|
|
11
|
+
import { alreadyShown, failureKind, fitAnswer, LEAST_RESULT_CHARACTERS, MAX_WHOLE_DOCUMENT_READS, repeatedFailureHint, stepLine, TOOL_NAMES, toolCallKey, toolResultSummary, unknownToolName, } from "./tools.js";
|
|
10
12
|
/** Sent (invisibly to the user) when the model must stop using tools and answer. */
|
|
11
|
-
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.";
|
|
13
|
+
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.";
|
|
12
14
|
/** The same, when the only tool was `view_pages`: the text of the files is in the prompt, not in tool results. */
|
|
13
|
-
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.";
|
|
14
|
-
/**
|
|
15
|
-
|
|
15
|
+
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.";
|
|
16
|
+
/**
|
|
17
|
+
* Sent when no tool ran (an explorer model called none, the first reply was empty, or no turn was
|
|
18
|
+
* left for tools), so there is no tool result to answer from.
|
|
19
|
+
*/
|
|
20
|
+
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. Answer in the language of my question.";
|
|
16
21
|
/**
|
|
17
22
|
* Added to the system instruction of an explorer model's requests: it gathers what the answer
|
|
18
23
|
* needs, and the other model writes the answer.
|
|
@@ -31,18 +36,39 @@ const BYTES_PER_CHARACTER = 3;
|
|
|
31
36
|
/** Tool rounds whose results are kept in full when older ones are dropped to make room. */
|
|
32
37
|
const ROUNDS_KEPT = [3, 2, 1];
|
|
33
38
|
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.";
|
|
39
|
+
/** Why a request of a whole-file read that its read left behind ended with its call. */
|
|
40
|
+
const CALL_ENDED = "The tool call ended before this request did.";
|
|
34
41
|
const count = (value) => Math.max(0, Math.round(value)).toLocaleString("en-US");
|
|
42
|
+
/** How many of a model's tokens one token of the library's estimate comes to. */
|
|
43
|
+
const scaleOf = (adapter) => (adapter.capabilities.tokenScale && adapter.capabilities.tokenScale > 0 ? adapter.capabilities.tokenScale : 1);
|
|
44
|
+
/** What a page costs when a model does not say: the OpenAI adapter's default. */
|
|
45
|
+
const DEFAULT_PAGE_TOKENS = 1_000;
|
|
46
|
+
/**
|
|
47
|
+
* What a page costs a model, in its tokens: its `pageTokens`, or `DEFAULT_PAGE_TOKENS` when that is
|
|
48
|
+
* missing or not a finite number (an adapter written in JavaScript). NaN took away the page limit
|
|
49
|
+
* of the question and every count of the room left once a page was shown.
|
|
50
|
+
*/
|
|
51
|
+
const pageTokensOf = (adapter) => {
|
|
52
|
+
const declared = adapter.capabilities.pageTokens;
|
|
53
|
+
return typeof declared === "number" && Number.isFinite(declared) && declared >= 0 ? declared : DEFAULT_PAGE_TOKENS;
|
|
54
|
+
};
|
|
35
55
|
const isRound = (message) => message.role === "tools";
|
|
36
56
|
/** How many pages a `view_pages` result showed: its `pages` is "12" or "12-14". */
|
|
37
57
|
function pagesShown(result) {
|
|
38
58
|
const [first, last] = String(result.pages ?? "").split("-").map(Number);
|
|
39
59
|
return Number.isFinite(first) ? (Number.isFinite(last) ? last - first + 1 : 1) : 0;
|
|
40
60
|
}
|
|
61
|
+
/**
|
|
62
|
+
* A result of a tool round of an earlier question, as it is sent again: without its
|
|
63
|
+
* `tool_turns_left`, which counted the turns of that question, not of this one, and with no half of a
|
|
64
|
+
* character in it (0.5.0 cut some search windows inside an emoji, and Claude's API refuses them).
|
|
65
|
+
*/
|
|
66
|
+
const carriedResult = (result) => wellFormedJson(laterResult(result));
|
|
41
67
|
/** The conversation as the loop keeps it: copies, so that nothing of the caller's is changed. */
|
|
42
68
|
function toMessages(given) {
|
|
43
69
|
const messages = given.map((message) => {
|
|
44
70
|
if (message.role === "tools") {
|
|
45
|
-
const answers = message.calls.map(({ result, ...call }) => ({ call, result }));
|
|
71
|
+
const answers = message.calls.map(({ result, ...call }) => ({ call, result: carriedResult(result) }));
|
|
46
72
|
return { role: "tools", calls: answers.map((answer) => answer.call), answers };
|
|
47
73
|
}
|
|
48
74
|
const role = message.role === "user" ? "user" : "assistant";
|
|
@@ -82,6 +108,8 @@ class RequestMeter {
|
|
|
82
108
|
sizes = new WeakMap();
|
|
83
109
|
/** How much larger the provider counted the last request than the estimate did. Never below 1. */
|
|
84
110
|
factor = 1;
|
|
111
|
+
/** The least `factor` may be for the rest of the question: what a request refused as too large showed. */
|
|
112
|
+
floor = 1;
|
|
85
113
|
constructor(pageTokens) {
|
|
86
114
|
this.pageTokens = pageTokens;
|
|
87
115
|
}
|
|
@@ -132,17 +160,147 @@ class RequestMeter {
|
|
|
132
160
|
const size = this.estimate(messages);
|
|
133
161
|
return { tokens: Math.ceil(size.tokens * this.factor), bytes: size.bytes };
|
|
134
162
|
}
|
|
135
|
-
/**
|
|
163
|
+
/**
|
|
164
|
+
* Takes note of what the provider counted for a request that was estimated at `estimated` tokens.
|
|
165
|
+
* A report raises the estimate up to twice; it never lowers it below what a refusal showed.
|
|
166
|
+
*/
|
|
136
167
|
observe(estimated, counted) {
|
|
137
168
|
if (estimated > 0 && typeof counted === "number" && counted > 0)
|
|
138
|
-
this.factor = Math.min(2, Math.max(1, counted / estimated));
|
|
169
|
+
this.factor = Math.max(this.floor, Math.min(2, Math.max(1, counted / estimated)));
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Takes note of a request the provider refused as too large: it counted `counted` tokens (in the
|
|
173
|
+
* library's tokens by the model's scale) of one estimated at `estimated`, or, when it did not say,
|
|
174
|
+
* a quarter more than the estimate. Unlike `observe`, nothing caps it at twice the estimate: the
|
|
175
|
+
* refusal is the provider's word that the estimate was too low, and it holds for the rest of the
|
|
176
|
+
* question: a later report does not take it back.
|
|
177
|
+
*/
|
|
178
|
+
overflowed(estimated, counted) {
|
|
179
|
+
const ratio = estimated > 0 && typeof counted === "number" && counted > 0 ? counted / estimated : this.factor * 1.25;
|
|
180
|
+
this.factor = Math.min(8, Math.max(this.factor, ratio));
|
|
181
|
+
this.floor = this.factor;
|
|
139
182
|
}
|
|
140
183
|
}
|
|
184
|
+
/**
|
|
185
|
+
* Shares `room` characters among tool calls whose results may be up to `caps` characters. A call
|
|
186
|
+
* gets no more than its cap, and the others split what it leaves. Calls that cannot each get
|
|
187
|
+
* `LEAST_ROOM_CHARACTERS` (or their cap, when it is smaller) are not run, the last ones first:
|
|
188
|
+
* their share is undefined.
|
|
189
|
+
*/
|
|
190
|
+
export function shareRoom(caps, room) {
|
|
191
|
+
const least = (cap) => Math.min(cap, LEAST_ROOM_CHARACTERS);
|
|
192
|
+
let count = caps.length;
|
|
193
|
+
let needed = caps.reduce((sum, cap) => sum + least(cap), 0);
|
|
194
|
+
while (count > 0 && needed > room)
|
|
195
|
+
needed -= least(caps[--count]);
|
|
196
|
+
const shares = caps.map(() => undefined);
|
|
197
|
+
// The smallest caps first: each call takes its cap or an even share of what is left, whichever is less.
|
|
198
|
+
const order = caps.slice(0, count).map((cap, index) => ({ cap, index })).sort((left, right) => left.cap - right.cap);
|
|
199
|
+
let left = Math.max(0, Math.floor(room));
|
|
200
|
+
order.forEach(({ cap, index }, position) => {
|
|
201
|
+
const share = Math.min(cap, Math.floor(left / (order.length - position)));
|
|
202
|
+
shares[index] = share;
|
|
203
|
+
left -= share;
|
|
204
|
+
});
|
|
205
|
+
return shares;
|
|
206
|
+
}
|
|
141
207
|
function retryMessage({ error, delayMs }) {
|
|
142
208
|
const status = statusOf(error);
|
|
143
209
|
const seconds = delayMs >= 1_000 ? ` in ${Math.round(delayMs / 1_000)} s` : "";
|
|
144
|
-
|
|
210
|
+
const what = errorKindOf(error) === "timeout" && status === 0 ? "The model sent nothing for too long"
|
|
211
|
+
// The model was reached, and its reply began to arrive.
|
|
212
|
+
: isCutReply(error) ? "The model's reply was cut off on its way"
|
|
213
|
+
: status ? `The model did not answer (HTTP ${status})` : "The model could not be reached";
|
|
214
|
+
return `${what}. Trying again${seconds}…`;
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* What the question had found when it failed, by the error it threw: see `partialResultOf`. With
|
|
218
|
+
* the question it came from, and no result once a second question threw the same error.
|
|
219
|
+
*/
|
|
220
|
+
const partialResults = new WeakMap();
|
|
221
|
+
/**
|
|
222
|
+
* Keeps what the question run with `owner` had done when it threw `error`. The same error can be
|
|
223
|
+
* thrown by several questions: the reason of a signal they share (`AbortSignal.any` passes the
|
|
224
|
+
* reason on as it is). Then `partialResultOf` gives none of them a result for it, rather than one
|
|
225
|
+
* question's tool rounds and usage for another's. The question's own `run.error` still has its own.
|
|
226
|
+
*/
|
|
227
|
+
function keepPartial(error, owner, result) {
|
|
228
|
+
if (error === null || typeof error !== "object")
|
|
229
|
+
return;
|
|
230
|
+
owner.failed = { error, result };
|
|
231
|
+
const kept = partialResults.get(error);
|
|
232
|
+
const shared = kept !== undefined && (kept.owner !== owner || kept.result === undefined);
|
|
233
|
+
partialResults.set(error, { owner, result: shared ? undefined : result });
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* What a question that failed had done before it failed: its tool steps, evidence, tool rounds and
|
|
237
|
+
* usage, with `answered: false`. `askWithFiles` throws the provider's error as it came (a
|
|
238
|
+
* `ModelRequestError` that was not worth sending again, or still failed after the retries); this
|
|
239
|
+
* gives what was found and paid for until then, so that an application can keep the tool rounds
|
|
240
|
+
* with the conversation and count the usage. Undefined for an error that did not come from a
|
|
241
|
+
* question under way (a document that is missing, a budget that does not work).
|
|
242
|
+
*/
|
|
243
|
+
export function partialResultOf(error) {
|
|
244
|
+
return error !== null && typeof error === "object" ? partialResults.get(error)?.result : undefined;
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Thrown inside a question whose first requests were too large for the model before any tool ran,
|
|
248
|
+
* when nothing can be shortened: the documents are planned again for a smaller window. Never
|
|
249
|
+
* leaves `askWithFiles`.
|
|
250
|
+
*/
|
|
251
|
+
class Replan extends Error {
|
|
252
|
+
carried;
|
|
253
|
+
overflow;
|
|
254
|
+
partial;
|
|
255
|
+
constructor(carried, overflow, partial) {
|
|
256
|
+
super("replan");
|
|
257
|
+
this.carried = carried;
|
|
258
|
+
this.overflow = overflow;
|
|
259
|
+
this.partial = partial;
|
|
260
|
+
}
|
|
145
261
|
}
|
|
262
|
+
/** Sent, once, after a tool turn whose call could not be read. Not kept in the conversation. */
|
|
263
|
+
const MALFORMED_CALL_NUDGE = "Your last reply tried to call a tool, but the call could not be read. Call the tools again, with arguments that match their declarations, or answer if you already have enough.";
|
|
264
|
+
const MALFORMED_EXPLORER_NUDGE = "Your last reply tried to call a tool, but the call could not be read. Call the tools again, with arguments that match their declarations, or reply DONE if the results above already hold what the answer needs.";
|
|
265
|
+
/** Sent, once, after a first reply that was empty. Not kept in the conversation. */
|
|
266
|
+
const EMPTY_REPLY_NUDGE = "Your last reply was empty. Use the tools to read the files the question is about, or answer the question.";
|
|
267
|
+
const EMPTY_EXPLORER_NUDGE = "Your last reply was empty. Call the tools to gather what the answer needs from the files, then reply DONE.";
|
|
268
|
+
/**
|
|
269
|
+
* Sent, once, after a reply to the answer's request that had no text: it was empty, or held a tool
|
|
270
|
+
* call that the model was told not to make. Not kept in the conversation.
|
|
271
|
+
*/
|
|
272
|
+
const ANSWER_AGAIN_NOTE = "Your last reply had no text. No tool can be called in this reply: write the answer now, in text, from what is above.";
|
|
273
|
+
/** The most such second tries in one question, the answer's included. */
|
|
274
|
+
const MOST_NUDGES = 2;
|
|
275
|
+
/** The most requests sent again, smaller, after the provider refused one as too large. */
|
|
276
|
+
const MOST_OVERFLOW_RECOVERIES = 2;
|
|
277
|
+
/**
|
|
278
|
+
* The limits of a question, checked. A field that is NaN (`Number(process.env.X)` of a variable
|
|
279
|
+
* that is not set) or not a number is an error, as a budget field is: NaN fails every comparison,
|
|
280
|
+
* so it turned off the ceilings and the cap on whole-file reads, or every tool.
|
|
281
|
+
*/
|
|
282
|
+
function checkedLimits(given) {
|
|
283
|
+
for (const field of ["toolTurns", "callsPerTurn", "wholeDocumentReads", "inputTokens", "requests"]) {
|
|
284
|
+
const value = given?.[field];
|
|
285
|
+
if (value === undefined)
|
|
286
|
+
continue;
|
|
287
|
+
if (typeof value !== "number")
|
|
288
|
+
throw new TypeError(`limits.${field} must be a number, and is ${typeof value === "string" ? JSON.stringify(value) : typeof value}.`);
|
|
289
|
+
if (Number.isNaN(value))
|
|
290
|
+
throw new RangeError(`limits.${field} must be a number, and is NaN. Leave it out for the default.`);
|
|
291
|
+
}
|
|
292
|
+
return given ?? {};
|
|
293
|
+
}
|
|
294
|
+
/** Said, once, when a ceiling of `limits` stops the tools. */
|
|
295
|
+
const BUDGET_REACHED = "No more tools: the question reached its limit of input tokens or requests.";
|
|
296
|
+
/** A document as an event names it. */
|
|
297
|
+
const documentRef = (meta) => ({
|
|
298
|
+
id: meta.id,
|
|
299
|
+
name: meta.name,
|
|
300
|
+
format: meta.format,
|
|
301
|
+
estimatedTokens: meta.estimatedTokens,
|
|
302
|
+
...(meta.pages !== undefined ? { pages: meta.pages } : {}),
|
|
303
|
+
});
|
|
146
304
|
/**
|
|
147
305
|
* Answers a chat turn about large documents with any model that has an adapter.
|
|
148
306
|
* Documents that fit go into the prompt whole; otherwise the model gets search and read tools and
|
|
@@ -150,19 +308,109 @@ function retryMessage({ error, delayMs }) {
|
|
|
150
308
|
* an answer. With an `explorer`, that model runs the tool loop and `model` writes the answer.
|
|
151
309
|
*/
|
|
152
310
|
export async function askWithFiles(options) {
|
|
311
|
+
const events = new EventEmitter(options.runId ?? newRunId(), options.onEvent);
|
|
312
|
+
const state = { events, requests: 0, calls: 0, budgetSaid: false };
|
|
313
|
+
try {
|
|
314
|
+
if (events.active) {
|
|
315
|
+
// Always first, whatever the options hold: they are checked after it, and a question whose
|
|
316
|
+
// options do not work ends with run.error like any other.
|
|
317
|
+
const { model, explorer, documentIds } = options;
|
|
318
|
+
const other = explorer && explorer !== model ? explorer : undefined;
|
|
319
|
+
events.emit({
|
|
320
|
+
type: "run.start",
|
|
321
|
+
models: { answer: model?.id ?? "", ...(other ? { explorer: other.id } : {}) },
|
|
322
|
+
documentIds: Array.isArray(documentIds) ? [...documentIds] : [],
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
const result = await askPlanned(options, state);
|
|
326
|
+
if (events.active)
|
|
327
|
+
events.emit({ type: "run.finish", result: eventResultOf(result, options.eventResults === true) });
|
|
328
|
+
return result;
|
|
329
|
+
}
|
|
330
|
+
catch (error) {
|
|
331
|
+
if (events.active) {
|
|
332
|
+
// The question's own, also when another question threw the same error (a shared signal's reason).
|
|
333
|
+
const partial = state.failed && state.failed.error === error ? state.failed.result : partialResultOf(error);
|
|
334
|
+
events.emit({ type: "run.error", error: eventErrorOf(error), ...(partial ? { partial: eventResultOf(partial, options.eventResults === true) } : {}) });
|
|
335
|
+
}
|
|
336
|
+
throw error;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* A result as `run.finish` and `run.error` carry it: a copy, so that a listener cannot change the
|
|
341
|
+
* caller's, without the tool rounds and with the plan naming documents only (both hold text of
|
|
342
|
+
* the documents: tool results, outline headings, the commonest lines of a log) unless `withTurns`.
|
|
343
|
+
*/
|
|
344
|
+
function eventResultOf(result, withTurns) {
|
|
345
|
+
if (withTurns)
|
|
346
|
+
return { ...result };
|
|
347
|
+
const { toolTurns: _toolTurns, plan, ...rest } = result;
|
|
348
|
+
return { ...rest, plan: { inline: plan.inline.map(documentRef), searchable: plan.searchable.map(documentRef) } };
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* `askWithFiles` as a stream of its events, for a page that shows the question as it goes: see
|
|
352
|
+
* `AskEvent`. Leaving the loop early (`break`) stops the question. `result` is what `askWithFiles`
|
|
353
|
+
* returns. `onEvent`, when given, gets each event too, after the stream. The model is asked for
|
|
354
|
+
* the answer as it is written unless `streamText` is false. New in 0.7.0.
|
|
355
|
+
*/
|
|
356
|
+
export function askStream(options) {
|
|
357
|
+
return eventStream((onEvent, signal) => askWithFiles({
|
|
358
|
+
...options,
|
|
359
|
+
// A page that reads the events shows the text as it is written, unless told not to.
|
|
360
|
+
streamText: options.streamText !== false,
|
|
361
|
+
signal,
|
|
362
|
+
onEvent: (event) => {
|
|
363
|
+
// The stream first: a throw of the caller's listener cannot keep an event, the last one
|
|
364
|
+
// included, from the stream.
|
|
365
|
+
onEvent(event);
|
|
366
|
+
options.onEvent?.(event);
|
|
367
|
+
},
|
|
368
|
+
}), { signal: options.signal });
|
|
369
|
+
}
|
|
370
|
+
/** The question, planned again once when its first requests were too large for the model. */
|
|
371
|
+
async function askPlanned(options, state) {
|
|
372
|
+
try {
|
|
373
|
+
return await ask(options, undefined, state);
|
|
374
|
+
}
|
|
375
|
+
catch (error) {
|
|
376
|
+
if (!(error instanceof Replan))
|
|
377
|
+
throw error;
|
|
378
|
+
// The first requests were too large for the model, and nothing in them could be shortened: the
|
|
379
|
+
// documents are planned again for the window the provider named, or a smaller one. Once. The
|
|
380
|
+
// window is a limit of the model's, as one it declares: the application's budget is fitted to it.
|
|
381
|
+
try {
|
|
382
|
+
return await ask(options, error.carried, state);
|
|
383
|
+
}
|
|
384
|
+
catch (again) {
|
|
385
|
+
// Failed before it sent anything (a budget of the application's that cannot work with the
|
|
386
|
+
// smaller window): the provider's error, with what the first try found, is the one to report.
|
|
387
|
+
// (The question's own record: `partialResultOf` gives nothing for an error another question threw too.)
|
|
388
|
+
if (state.failed?.error !== again && again?.status === undefined) {
|
|
389
|
+
keepPartial(error.overflow, state, error.partial);
|
|
390
|
+
throw error.overflow;
|
|
391
|
+
}
|
|
392
|
+
throw again;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
async function ask(options, carried, state) {
|
|
153
397
|
const { files, model, signal } = options;
|
|
398
|
+
const { events } = state;
|
|
154
399
|
// A second model for the requests that use tools. The answering model itself is not one.
|
|
155
400
|
const explorer = options.explorer && options.explorer !== model ? options.explorer : undefined;
|
|
156
401
|
const toolModel = explorer ?? model;
|
|
157
402
|
const models = explorer ? [model, explorer] : [model];
|
|
158
|
-
const limits = options.limits
|
|
159
|
-
|
|
403
|
+
const limits = checkedLimits(options.limits);
|
|
404
|
+
// A question planned again goes on counting what its first try paid for.
|
|
405
|
+
const usage = carried?.usage ?? new UsageMeter();
|
|
160
406
|
// The budget is counted in the library's estimate of tokens. A model whose tokenizer counts
|
|
161
407
|
// more of them for the same text has, in those terms, a smaller window.
|
|
162
|
-
const scale = Math.max(...models.map(
|
|
408
|
+
const scale = Math.max(...models.map(scaleOf));
|
|
163
409
|
const declared = (pick) => models.map(pick).filter((value) => typeof value === "number" && value > 0);
|
|
164
410
|
const own = files.budgetFor(options.budget);
|
|
165
|
-
|
|
411
|
+
// The window in the models' own tokens, and in the library's.
|
|
412
|
+
const modelWindow = Math.min(own.contextTokens, carried?.contextTokens ?? Number.POSITIVE_INFINITY, ...declared((adapter) => adapter.capabilities.contextTokens));
|
|
413
|
+
const windowTokens = Math.floor(modelWindow / scale);
|
|
166
414
|
// A reply that is counted against the window: that part of it is not there for the prompt.
|
|
167
415
|
const replyTokens = Math.ceil(Math.max(0, ...declared((adapter) => adapter.capabilities.outputTokens)) / scale);
|
|
168
416
|
const requestBytesLimit = declared((adapter) => adapter.capabilities.maxRequestBytes);
|
|
@@ -171,10 +419,14 @@ export async function askWithFiles(options) {
|
|
|
171
419
|
...(requestBytesLimit.length > 0 ? { maxRequestBytes: Math.min(...requestBytesLimit) } : {}),
|
|
172
420
|
});
|
|
173
421
|
// What a page costs, in the same terms. Pages are shown to every model of the question.
|
|
174
|
-
const pageTokens = Math.max(1, ...models.map(
|
|
175
|
-
|
|
422
|
+
const pageTokens = Math.max(1, ...models.map(pageTokensOf)) / scale;
|
|
423
|
+
// A value the type does not have (left out by an adapter in JavaScript) counts as "none".
|
|
424
|
+
const canShowFiles = models.every((adapter) => adapter.capabilities.toolFiles === "inside" || adapter.capabilities.toolFiles === "beside");
|
|
176
425
|
// Every model must be able to take a conversation whose earlier turns were made shorter.
|
|
177
426
|
const canShrink = models.every((adapter) => !adapter.capabilities.appendOnly);
|
|
427
|
+
// A call made again is answered with a pointer to its earlier result only while that result stays
|
|
428
|
+
// in the conversation: a provider that clears old tool results on its side may have removed it.
|
|
429
|
+
const canPoint = models.every((adapter) => !adapter.capabilities.clearsToolResults);
|
|
178
430
|
const messages = toMessages(options.messages);
|
|
179
431
|
const meter = new RequestMeter(pageTokens);
|
|
180
432
|
const asText = textSize(messages, options.system);
|
|
@@ -182,6 +434,8 @@ export async function askWithFiles(options) {
|
|
|
182
434
|
const prepared = await files.prepare(options.documentIds, { tokens: asText.tokens + earlier.tokens, bytes: asText.bytes + earlier.bytes }, {
|
|
183
435
|
...(options.owner !== undefined ? { owner: options.owner } : {}),
|
|
184
436
|
viewPages: options.viewPages !== false && canShowFiles,
|
|
437
|
+
// The guide and the cards name `analyze_whole_document` only when the tools will have it.
|
|
438
|
+
wholeDocumentAnalysis: options.wholeDocumentAnalysis !== false && typeof toolModel.generateText === "function",
|
|
185
439
|
budget,
|
|
186
440
|
});
|
|
187
441
|
if (prepared.missing.length)
|
|
@@ -209,20 +463,48 @@ export async function askWithFiles(options) {
|
|
|
209
463
|
meter.fixed.bytes += jsonBytes(block);
|
|
210
464
|
}
|
|
211
465
|
let text = "";
|
|
212
|
-
let turns = 0;
|
|
466
|
+
let turns = carried?.turns ?? 0;
|
|
213
467
|
let finishReason;
|
|
214
468
|
let blockReason;
|
|
215
469
|
let lastUsage;
|
|
216
470
|
const steps = [];
|
|
217
471
|
const evidence = [];
|
|
218
|
-
const emit = (delta) => {
|
|
472
|
+
const emit = (delta, requestId) => {
|
|
219
473
|
text += delta;
|
|
220
474
|
options.onText?.(delta);
|
|
475
|
+
events.emit({ type: "text", requestId, delta });
|
|
221
476
|
};
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
477
|
+
/**
|
|
478
|
+
* A step can quote what the model sent: it is made one line of plain text before anyone sees it.
|
|
479
|
+
* A step that is not a tool call's is also a notice, with that code. Returns the line.
|
|
480
|
+
*/
|
|
481
|
+
const step = (line, code) => {
|
|
482
|
+
const plain = stepLine(line);
|
|
483
|
+
steps.push(plain);
|
|
484
|
+
options.onStep?.(plain);
|
|
485
|
+
if (code)
|
|
486
|
+
events.emit({ type: "notice", code, message: plain, display: "step" });
|
|
487
|
+
return plain;
|
|
488
|
+
};
|
|
489
|
+
/** Short-lived status that is also a notice. */
|
|
490
|
+
const activity = (code, message) => {
|
|
491
|
+
options.onActivity?.(message);
|
|
492
|
+
events.emit({ type: "notice", code, message, display: "activity" });
|
|
225
493
|
};
|
|
494
|
+
/** A notice that earlier versions did not show. */
|
|
495
|
+
const notice = (code, message) => events.emit({ type: "notice", code, message, display: "none" });
|
|
496
|
+
const budgetReached = () => {
|
|
497
|
+
if (state.budgetSaid)
|
|
498
|
+
return;
|
|
499
|
+
state.budgetSaid = true;
|
|
500
|
+
notice("budget_reached", BUDGET_REACHED);
|
|
501
|
+
};
|
|
502
|
+
// What a first try that was planned again showed is part of this question; then why it was planned again.
|
|
503
|
+
steps.push(...carried?.steps ?? []);
|
|
504
|
+
if (carried)
|
|
505
|
+
step(carried.step, "replanned");
|
|
506
|
+
if (events.active)
|
|
507
|
+
events.emit({ type: "plan", inline: prepared.plan.inline.map(documentRef), searchable: prepared.plan.searchable.map(documentRef) });
|
|
226
508
|
// A model turn in its provider's own form goes back only to the adapter it came from. Any other
|
|
227
509
|
// model gets the tool calls alone: a thought signature belongs to the model that wrote it, and
|
|
228
510
|
// an explorer's thoughts and remarks are not what the files say.
|
|
@@ -236,45 +518,105 @@ export async function askWithFiles(options) {
|
|
|
236
518
|
}
|
|
237
519
|
return known;
|
|
238
520
|
};
|
|
239
|
-
|
|
521
|
+
/**
|
|
522
|
+
* Turns that hold a note for the model that explores, kept in the conversation because that model
|
|
523
|
+
* may not have it rewritten (see `notedMessages`), with the turn as it was before the note, or
|
|
524
|
+
* undefined for a turn that is only the note. The other model never gets them.
|
|
525
|
+
*/
|
|
526
|
+
const notes = new Map();
|
|
527
|
+
const viewFor = (adapter, list = messages) => list.flatMap((message) => {
|
|
528
|
+
if (adapter !== toolModel && notes.has(message)) {
|
|
529
|
+
const before = notes.get(message);
|
|
530
|
+
return before ? [before] : [];
|
|
531
|
+
}
|
|
532
|
+
return [isRound(message) && message.raw !== undefined && rawOwner.get(message) !== adapter ? callsOnly(message) : message];
|
|
533
|
+
});
|
|
240
534
|
/**
|
|
241
535
|
* One model request of the chat. Text is passed on as it arrives when it is `shown`: an
|
|
242
536
|
* explorer's words are not, because the answer comes from the other model. A request that
|
|
243
537
|
* failed is sent again by the rule of `retry`, unless text of it was already shown.
|
|
244
538
|
*/
|
|
245
|
-
|
|
539
|
+
/** Chat requests of the question that were answered, those of a first try included: each took a tool turn. */
|
|
540
|
+
let answeredRequests = carried?.answered ?? 0;
|
|
541
|
+
const streamText = options.streamText ?? options.onText !== undefined;
|
|
542
|
+
const request = async (adapter, body, shown, kind) => {
|
|
246
543
|
turns++;
|
|
544
|
+
const requestId = `req_${++state.requests}`;
|
|
545
|
+
const began = Date.now();
|
|
247
546
|
let separated = text.length === 0;
|
|
248
547
|
let got = "";
|
|
249
548
|
const write = (delta) => {
|
|
250
|
-
|
|
549
|
+
// Nothing more is shown once the question was stopped, by an adapter that goes on regardless.
|
|
550
|
+
if (!delta || signal?.aborted)
|
|
251
551
|
return;
|
|
252
552
|
if (!separated) {
|
|
253
|
-
emit("\n\n");
|
|
553
|
+
emit("\n\n", requestId);
|
|
254
554
|
separated = true;
|
|
255
555
|
}
|
|
256
556
|
got += delta;
|
|
257
|
-
emit(delta);
|
|
557
|
+
emit(delta, requestId);
|
|
258
558
|
};
|
|
259
559
|
const estimated = meter.estimate(body.messages).tokens;
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
560
|
+
let reply;
|
|
561
|
+
try {
|
|
562
|
+
// In the try: a listener that throws on the start still gets its end.
|
|
563
|
+
events.emit({ type: "request.start", requestId, role: kind.role, purpose: kind.purpose, model: adapter.id, turn: turns, estimatedInputTokens: estimated });
|
|
564
|
+
reply = await withRetry(() => {
|
|
565
|
+
// Nothing is sent once the question was stopped.
|
|
566
|
+
signal?.throwIfAborted();
|
|
567
|
+
const sending = adapter.send(body, {
|
|
568
|
+
...(signal ? { signal } : {}),
|
|
569
|
+
// The adapter streams only when the text is asked for as it is written: a listener of
|
|
570
|
+
// the events alone does not change how the model is asked.
|
|
571
|
+
...(shown && streamText ? { onText: write } : {}),
|
|
572
|
+
});
|
|
573
|
+
// The question stops when the signal aborts, whether the adapter does or not: one that does
|
|
574
|
+
// not look at it would hold the question, and the user, until its request ends, if it ever
|
|
575
|
+
// does. That holds when the signal aborted while the adapter was called (its onText ran the
|
|
576
|
+
// caller's code): `until` then ends at once with the signal's reason.
|
|
577
|
+
return until(sending, signal);
|
|
578
|
+
}, {
|
|
579
|
+
retry: options.retry,
|
|
580
|
+
signal,
|
|
581
|
+
canRetry: () => got.length === 0,
|
|
582
|
+
onRetry: (retried) => {
|
|
583
|
+
const message = retryMessage(retried);
|
|
584
|
+
options.onActivity?.(message);
|
|
585
|
+
if (events.active)
|
|
586
|
+
events.emit({ type: "retry", requestId, attempt: retried.attempt, delayMs: retried.delayMs, error: eventErrorOf(retried.error), message });
|
|
587
|
+
},
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
catch (error) {
|
|
591
|
+
if (events.active)
|
|
592
|
+
events.emit({ type: "request.end", requestId, ms: Date.now() - began, outcome: "error", error: eventErrorOf(error) });
|
|
593
|
+
throw error;
|
|
594
|
+
}
|
|
269
595
|
// Text the adapter did not pass on as it came (no streaming was asked for, or it cannot).
|
|
270
596
|
if (shown && reply.text.length > got.length && reply.text.startsWith(got))
|
|
271
597
|
write(reply.text.slice(got.length));
|
|
598
|
+
answeredRequests++;
|
|
272
599
|
usage.add(adapter.id, reply.usage);
|
|
273
|
-
|
|
600
|
+
// The count of the model that answered, in the library's tokens by that model's own scale: how
|
|
601
|
+
// much more than its scale says the text costs it, which the other model will see too. By the
|
|
602
|
+
// larger scale of the two, a count of the model with the smaller one was taken for no more.
|
|
603
|
+
meter.observe(estimated, typeof reply.usage?.inputTokens === "number" ? reply.usage.inputTokens / scaleOf(adapter) : undefined);
|
|
274
604
|
if (reply.blockReason)
|
|
275
605
|
blockReason = reply.blockReason;
|
|
276
606
|
finishReason = reply.finishReason ?? finishReason;
|
|
277
607
|
lastUsage = reply.providerUsage ?? lastUsage;
|
|
608
|
+
events.emit({
|
|
609
|
+
type: "request.end",
|
|
610
|
+
requestId,
|
|
611
|
+
ms: Date.now() - began,
|
|
612
|
+
outcome: "ok",
|
|
613
|
+
...(reply.usage ? { usage: reply.usage } : {}),
|
|
614
|
+
...(reply.finish ? { finish: reply.finish } : {}),
|
|
615
|
+
...(reply.finishReason !== undefined ? { finishReason: reply.finishReason } : {}),
|
|
616
|
+
toolCalls: reply.calls.length,
|
|
617
|
+
});
|
|
618
|
+
if (reply.blockReason)
|
|
619
|
+
notice("blocked", `The provider refused the prompt: ${reply.blockReason}.`);
|
|
278
620
|
return reply;
|
|
279
621
|
};
|
|
280
622
|
// What a model wrote before it was stopped by a refusal is not an answer.
|
|
@@ -301,39 +643,6 @@ export async function askWithFiles(options) {
|
|
|
301
643
|
usage: usage.totals,
|
|
302
644
|
...(lastUsage ? { lastUsage } : {}),
|
|
303
645
|
});
|
|
304
|
-
// Tools are needed for a file that is too large to send whole, and for a PDF whose pages can be
|
|
305
|
-
// looked at: that one may have its whole text in the prompt and still hide a chart from the model.
|
|
306
|
-
const { searchable } = prepared.plan;
|
|
307
|
-
const { viewable } = prepared;
|
|
308
|
-
if (searchable.length === 0 && viewable.length === 0)
|
|
309
|
-
return result(wrote(await request(model, { system, messages }, true)));
|
|
310
|
-
// Reading a whole file in parts is exploring too: the explorer model's work, when there is one.
|
|
311
|
-
const partReader = options.wholeDocumentAnalysis === false ? undefined : toolModel.generateText;
|
|
312
|
-
const generate = partReader && ((part) => partReader({
|
|
313
|
-
...part,
|
|
314
|
-
onUsage: (used) => {
|
|
315
|
-
usage.add(toolModel.id, used);
|
|
316
|
-
part.onUsage?.(used);
|
|
317
|
-
},
|
|
318
|
-
}));
|
|
319
|
-
const tools = files.tools(searchable, {
|
|
320
|
-
...(generate ? { generate } : {}),
|
|
321
|
-
onProgress: (event) => options.onActivity?.(`${event.message}…`),
|
|
322
|
-
...(signal ? { signal } : {}),
|
|
323
|
-
...(viewable.length > 0 ? { viewPages: viewable } : {}),
|
|
324
|
-
maxWholeDocumentReads: limits.wholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS,
|
|
325
|
-
...(options.retry ? { retry: options.retry } : {}),
|
|
326
|
-
budget,
|
|
327
|
-
});
|
|
328
|
-
const declarations = tools.declarations;
|
|
329
|
-
// The requests that use the tools are the chat's own, or an explorer model's: the same
|
|
330
|
-
// conversation, and a line that says what its part is.
|
|
331
|
-
const toolSystem = explorer ? `${system}\n\n${EXPLORER_INSTRUCTION}` : system;
|
|
332
|
-
const sentTools = JSON.stringify(declarations);
|
|
333
|
-
meter.fixed.tokens += estimateTokens(sentTools) + (explorer ? estimateTokens(EXPLORER_INSTRUCTION) : 0);
|
|
334
|
-
meter.fixed.bytes += Buffer.byteLength(sentTools) + (explorer ? EXPLORER_INSTRUCTION.length : 0);
|
|
335
|
-
if (searchable.length > 0)
|
|
336
|
-
options.onActivity?.(`Too large to read at once: ${searchable.map((meta) => meta.name).join(", ")}. Searching instead…`);
|
|
337
646
|
// Pages the model looks at stay in the request until the question is answered, so they are
|
|
338
647
|
// counted twice: as bytes against the request limit, and as tokens against half of what the
|
|
339
648
|
// budget keeps free for tool results and the answer.
|
|
@@ -341,8 +650,9 @@ export async function askWithFiles(options) {
|
|
|
341
650
|
const bytesKeptFree = Math.max(REQUEST_BYTES_MARGIN, Math.floor(maxRequestBytes / 10));
|
|
342
651
|
let pagesLeft = Math.floor(reservedTokens / 2 / pageTokens);
|
|
343
652
|
// The results of the text tools may fill the context window up to half of what is kept free (the
|
|
344
|
-
// other half is the answer's), and the request up to a small margin.
|
|
345
|
-
|
|
653
|
+
// other half is the answer's), and the request up to a small margin. A provider that refuses a
|
|
654
|
+
// request as too large, and names its window, makes it smaller.
|
|
655
|
+
let tokenLimit = budget.contextTokens - Math.floor(reservedTokens / 2);
|
|
346
656
|
const byteLimit = maxRequestBytes - Math.max(32_768, Math.floor(maxRequestBytes / 50));
|
|
347
657
|
/** Characters of tool results that still fit, with a model turn that is about to be answered. */
|
|
348
658
|
const room = (pending) => {
|
|
@@ -375,166 +685,773 @@ export async function askWithFiles(options) {
|
|
|
375
685
|
messages[index] = smaller;
|
|
376
686
|
changed = true;
|
|
377
687
|
}
|
|
688
|
+
if (changed)
|
|
689
|
+
unpoint();
|
|
378
690
|
return changed;
|
|
379
691
|
};
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
692
|
+
/**
|
|
693
|
+
* A pointer ("already shown above") whose result is no longer in the conversation in full (it was
|
|
694
|
+
* shortened to make room, here or in an earlier question) is made a stand-in that says so: the
|
|
695
|
+
* model must not be told to use what it no longer has. Every round is looked at, the kept ones too.
|
|
696
|
+
* With a provider that clears old tool results on its side, every pointer is. So is a pointer to a
|
|
697
|
+
* read of one line made in an earlier question than the pointer: 0.5.0 cut such reads without
|
|
698
|
+
* saying so, and `shownBefore` does not point to them either.
|
|
699
|
+
*/
|
|
700
|
+
function unpoint() {
|
|
701
|
+
// What the answers before the one looked at hold, as they are now, found once in one pass:
|
|
702
|
+
// the calls whose result is shown in full, by key, and the reads shown in full, by document,
|
|
703
|
+
// with the question each was made in (stored questions are told apart by their user turns).
|
|
704
|
+
const shownKeys = new Set();
|
|
705
|
+
const shownReads = new Map();
|
|
706
|
+
let question = 0;
|
|
707
|
+
messages.forEach((message, index) => {
|
|
708
|
+
if (!isRound(message)) {
|
|
709
|
+
if (message.role === "user")
|
|
710
|
+
question++;
|
|
711
|
+
return;
|
|
712
|
+
}
|
|
713
|
+
let touched = false;
|
|
714
|
+
/** The answers of this round so far that are not stand-ins, by key: a call made twice in a turn points to the first. */
|
|
715
|
+
const inRound = new Map();
|
|
716
|
+
const answers = [];
|
|
717
|
+
for (const answer of message.answers) {
|
|
718
|
+
const key = toolCallKey(answer.call.name, answer.call.args);
|
|
719
|
+
let now = answer;
|
|
720
|
+
if (answer.result.already_shown === true) {
|
|
721
|
+
const held = canPoint && ((key !== undefined && (inRound.has(key) || (answer.call.name !== TOOL_NAMES.read && shownKeys.has(key))))
|
|
722
|
+
|| (answer.call.name === TOOL_NAMES.read && (shownReads.get(answer.call.args.document_id) ?? [])
|
|
723
|
+
.some((read) => alreadyShown(answer.call, read.answer, read.index < asked && read.question !== question) !== undefined)));
|
|
724
|
+
if (!held) {
|
|
725
|
+
touched = true;
|
|
726
|
+
now = {
|
|
727
|
+
call: answer.call,
|
|
728
|
+
result: {
|
|
729
|
+
...(typeof answer.result.document === "string" ? { document: answer.result.document } : {}),
|
|
730
|
+
dropped: true,
|
|
731
|
+
note: "Not run then: it repeated an earlier call whose result was later dropped from the conversation to make room. Call it again if you need it.",
|
|
732
|
+
},
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
else if (key !== undefined && alreadyShown(answer.call, answer) !== undefined) {
|
|
737
|
+
// A result in full: what a later pointer may point to.
|
|
738
|
+
if (answer.call.name === TOOL_NAMES.read) {
|
|
739
|
+
const reads = shownReads.get(answer.call.args.document_id) ?? [];
|
|
740
|
+
reads.push({ answer, index, question });
|
|
741
|
+
shownReads.set(answer.call.args.document_id, reads);
|
|
742
|
+
}
|
|
743
|
+
else {
|
|
744
|
+
shownKeys.add(key);
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
if (key !== undefined && now.result.dropped !== true)
|
|
748
|
+
inRound.set(key, now);
|
|
749
|
+
answers.push(now);
|
|
750
|
+
}
|
|
751
|
+
if (!touched)
|
|
752
|
+
return;
|
|
753
|
+
const smaller = { ...message, answers };
|
|
754
|
+
const owner = rawOwner.get(message);
|
|
755
|
+
if (owner)
|
|
756
|
+
rawOwner.set(smaller, owner);
|
|
757
|
+
messages[index] = smaller;
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
// Rounds of earlier questions are stored as the model last had them: a pointer may have lost its result there.
|
|
761
|
+
unpoint();
|
|
762
|
+
/** Calls answered in this question, refused ones included: none means that no tool ran. */
|
|
763
|
+
let callsAnswered = 0;
|
|
764
|
+
let recoveries = carried?.recoveries ?? 0;
|
|
765
|
+
let nudges = carried?.nudges ?? 0;
|
|
766
|
+
/**
|
|
767
|
+
* After the provider refused `sent` as larger than the model takes: the meter learns what the
|
|
768
|
+
* provider counted, the window it named, and old tool results are shortened until the request
|
|
769
|
+
* fits by the meter's new count. True when anything was shortened, so that sending it again can
|
|
770
|
+
* work. A model whose conversation may only grow (Claude) has nothing shortened.
|
|
771
|
+
*/
|
|
772
|
+
const makeRoom = (adapter, sent, error) => {
|
|
773
|
+
const refused = error;
|
|
774
|
+
const own = scaleOf(adapter);
|
|
775
|
+
meter.overflowed(meter.estimate(sent.messages).tokens, refused.requestedTokens !== undefined ? refused.requestedTokens / own : undefined);
|
|
776
|
+
if (refused.limitTokens !== undefined) {
|
|
777
|
+
tokenLimit = Math.min(tokenLimit, Math.floor(refused.limitTokens / own) - replyTokens - Math.floor(reservedTokens / 2));
|
|
397
778
|
}
|
|
398
|
-
if (
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
if (
|
|
403
|
-
|
|
779
|
+
if (!canShrink)
|
|
780
|
+
return false;
|
|
781
|
+
let changed = false;
|
|
782
|
+
for (const keep of [...ROUNDS_KEPT, 0]) {
|
|
783
|
+
if (changed && meter.current(messages).tokens <= tokenLimit)
|
|
784
|
+
break;
|
|
785
|
+
if (shrink(keep))
|
|
786
|
+
changed = true;
|
|
787
|
+
}
|
|
788
|
+
return changed;
|
|
789
|
+
};
|
|
790
|
+
/**
|
|
791
|
+
* The window to plan the documents for again, in the models' tokens, after the first request was
|
|
792
|
+
* refused as too large: the one the provider named, made smaller by how much more than the
|
|
793
|
+
* estimate it counted. Without its numbers, seven tenths of the window the budget assumed.
|
|
794
|
+
*/
|
|
795
|
+
const smallerWindow = (adapter, sent, error) => {
|
|
796
|
+
const refused = error;
|
|
797
|
+
const estimated = meter.estimate(sent.messages).tokens;
|
|
798
|
+
const ratio = refused.requestedTokens !== undefined && estimated > 0 ? refused.requestedTokens / scaleOf(adapter) / estimated : undefined;
|
|
799
|
+
const limit = refused.limitTokens;
|
|
800
|
+
let contextTokens = Math.floor((limit ?? modelWindow * 0.7) / Math.max(1, ratio ?? (limit !== undefined ? 1.25 : 1)));
|
|
801
|
+
if (contextTokens >= modelWindow)
|
|
802
|
+
contextTokens = Math.floor(modelWindow * 0.7);
|
|
803
|
+
// The limit may be the tokens a minute of the provider allows (OpenAI's TPM), not the window.
|
|
804
|
+
const period = rateAllowanceOf(error);
|
|
805
|
+
return {
|
|
806
|
+
contextTokens,
|
|
807
|
+
step: limit !== undefined
|
|
808
|
+
? period
|
|
809
|
+
? `The first request was larger than the ${count(limit)} tokens a ${period} that the provider allows: the files were planned again to fit it`
|
|
810
|
+
: `The first request was larger than the model's window of ${count(limit)} tokens: the files were planned again to fit it`
|
|
811
|
+
: period
|
|
812
|
+
? `The first request was larger than the provider allows in a ${period}: the files were planned again for a smaller request`
|
|
813
|
+
: "The first request was larger than the model takes: the files were planned again for a smaller window",
|
|
814
|
+
};
|
|
815
|
+
};
|
|
816
|
+
/**
|
|
817
|
+
* `request`, for a request the provider may refuse as larger than the model takes. Then room is
|
|
818
|
+
* made, and it is sent once more, at most twice in a question. When nothing can be made smaller
|
|
819
|
+
* and nothing has happened yet in this question, the documents are planned again for a smaller
|
|
820
|
+
* window (`Replan`). `build` makes the request from the conversation as it is then.
|
|
821
|
+
*/
|
|
822
|
+
const send = async (adapter, build, shown, kind) => {
|
|
823
|
+
for (let again = false;; again = true) {
|
|
824
|
+
const body = build();
|
|
825
|
+
try {
|
|
826
|
+
return await request(adapter, body, shown, kind);
|
|
827
|
+
}
|
|
828
|
+
catch (error) {
|
|
829
|
+
if (errorKindOf(error) !== "context_overflow" || signal?.aborted)
|
|
830
|
+
throw error;
|
|
831
|
+
if (!again && recoveries < MOST_OVERFLOW_RECOVERIES && makeRoom(adapter, body, error)) {
|
|
832
|
+
recoveries++;
|
|
833
|
+
const period = rateAllowanceOf(error);
|
|
834
|
+
step(period
|
|
835
|
+
? `The request was larger than the provider allows in a ${period}: older tool results were shortened, and it was sent again`
|
|
836
|
+
: "The request was larger than the model takes: older tool results were shortened, and it was sent again", "room_made");
|
|
837
|
+
continue;
|
|
838
|
+
}
|
|
839
|
+
if (carried === undefined && callsAnswered === 0 && !text) {
|
|
840
|
+
const smaller = smallerWindow(adapter, body, error);
|
|
841
|
+
throw new Replan({ usage, steps: [...steps], turns, answered: answeredRequests, nudges, recoveries, contextTokens: smaller.contextTokens, step: smaller.step }, error, result(false));
|
|
842
|
+
}
|
|
843
|
+
throw error;
|
|
844
|
+
}
|
|
404
845
|
}
|
|
405
|
-
return undefined;
|
|
406
846
|
};
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
847
|
+
/** The conversation with a note at its end: in the last user turn, or in one of its own after a tool round. */
|
|
848
|
+
const withNote = (list, note) => {
|
|
849
|
+
const last = list.at(-1);
|
|
850
|
+
if (last && !isRound(last) && last.role === "user")
|
|
851
|
+
return [...list.slice(0, -1), { role: "user", parts: [...last.parts, { text: note }] }];
|
|
852
|
+
return [...list, { role: "user", parts: [{ text: note }] }];
|
|
853
|
+
};
|
|
854
|
+
/**
|
|
855
|
+
* The tool request with a note at its end. The note is not kept in the conversation, so that the
|
|
856
|
+
* start of the later requests is the one the provider's cache holds. A model that explores whose
|
|
857
|
+
* conversation may only grow (Claude ties its thinking to the turns it was written after) keeps
|
|
858
|
+
* it: what it thinks next follows the note. The answering model, when it is another, never gets it.
|
|
859
|
+
*/
|
|
860
|
+
const notedMessages = (note) => {
|
|
861
|
+
if (!toolModel.capabilities.appendOnly)
|
|
862
|
+
return () => withNote(viewFor(toolModel), note);
|
|
863
|
+
const last = messages.at(-1);
|
|
864
|
+
if (last && !isRound(last) && last.role === "user") {
|
|
865
|
+
const noted = { role: "user", parts: [...last.parts, { text: note }] };
|
|
866
|
+
notes.set(noted, notes.has(last) ? notes.get(last) : last);
|
|
867
|
+
messages[messages.length - 1] = noted;
|
|
868
|
+
}
|
|
869
|
+
else {
|
|
870
|
+
const noted = { role: "user", parts: [{ text: note }] };
|
|
871
|
+
notes.set(noted, undefined);
|
|
872
|
+
messages.push(noted);
|
|
419
873
|
}
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
874
|
+
return () => viewFor(toolModel);
|
|
875
|
+
};
|
|
876
|
+
// The tool calls run with a signal of their own. The question's aborts it, and so does a turn
|
|
877
|
+
// that fails (a listener that threw): the calls still waiting for a slot, or running, stop. A
|
|
878
|
+
// failed turn ends the question, so one signal serves every turn, with the tool set that counts
|
|
879
|
+
// the whole-file reads of the question.
|
|
880
|
+
const halt = new AbortController();
|
|
881
|
+
const stopTools = () => halt.abort(signal?.reason);
|
|
882
|
+
if (signal?.aborted)
|
|
883
|
+
halt.abort(signal.reason);
|
|
884
|
+
else
|
|
885
|
+
signal?.addEventListener("abort", stopTools, { once: true });
|
|
886
|
+
try {
|
|
887
|
+
// Tools are needed for a file that is too large to send whole, and for a PDF whose pages can be
|
|
888
|
+
// looked at: that one may have its whole text in the prompt and still hide a chart from the model.
|
|
889
|
+
const { searchable } = prepared.plan;
|
|
890
|
+
const { viewable } = prepared;
|
|
891
|
+
if (searchable.length === 0 && viewable.length === 0)
|
|
892
|
+
return result(wrote(await send(model, () => ({ system, messages }), true, { role: "answer", purpose: "direct" })));
|
|
893
|
+
// Reading a whole file in parts is exploring too: the explorer model's work, when there is one.
|
|
894
|
+
// Bound to its adapter: a class with a `generateText` method that uses `this` keeps it.
|
|
895
|
+
const partReader = options.wholeDocumentAnalysis === false ? undefined : toolModel.generateText?.bind(toolModel);
|
|
896
|
+
const generate = partReader && (async (part) => {
|
|
897
|
+
let reported = false;
|
|
898
|
+
const text = await partReader({
|
|
899
|
+
...part,
|
|
900
|
+
onUsage: (used) => {
|
|
901
|
+
reported = true;
|
|
902
|
+
usage.add(toolModel.id, used);
|
|
903
|
+
part.onUsage?.(used);
|
|
904
|
+
},
|
|
905
|
+
});
|
|
906
|
+
// A part reader that does not report its usage (`onUsage` is optional) still made a request,
|
|
907
|
+
// and `limits.requests` counts it.
|
|
908
|
+
if (!reported)
|
|
909
|
+
usage.add(toolModel.id, undefined);
|
|
910
|
+
return text;
|
|
911
|
+
});
|
|
912
|
+
const tools = files.tools(searchable, {
|
|
913
|
+
...(generate ? { generate } : {}),
|
|
914
|
+
onProgress: (event) => options.onActivity?.(`${event.message}…`),
|
|
915
|
+
signal: halt.signal,
|
|
916
|
+
...(viewable.length > 0 ? { viewPages: viewable } : {}),
|
|
917
|
+
maxWholeDocumentReads: limits.wholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS,
|
|
918
|
+
...(options.retry ? { retry: options.retry } : {}),
|
|
919
|
+
budget,
|
|
920
|
+
});
|
|
921
|
+
const declarations = tools.declarations;
|
|
922
|
+
// The requests that use the tools are the chat's own, or an explorer model's: the same
|
|
923
|
+
// conversation, and a line that says what its part is.
|
|
924
|
+
const toolSystem = explorer ? `${system}\n\n${EXPLORER_INSTRUCTION}` : system;
|
|
925
|
+
const sentTools = JSON.stringify(declarations);
|
|
926
|
+
meter.fixed.tokens += estimateTokens(sentTools) + (explorer ? estimateTokens(EXPLORER_INSTRUCTION) : 0);
|
|
927
|
+
meter.fixed.bytes += Buffer.byteLength(sentTools) + (explorer ? EXPLORER_INSTRUCTION.length : 0);
|
|
928
|
+
if (searchable.length > 0)
|
|
929
|
+
activity("searching_instead", `Too large to read at once: ${searchable.map((meta) => meta.name).join(", ")}. Searching instead…`);
|
|
930
|
+
const maxTurns = Math.max(1, Math.trunc(limits.toolTurns ?? DEFAULT_TOOL_TURNS));
|
|
931
|
+
const maxCalls = Math.max(1, Math.trunc(limits.callsPerTurn ?? DEFAULT_CALLS_PER_TURN));
|
|
932
|
+
/** True once the question has used what it may: no more tools run. One request is kept for the answer. */
|
|
933
|
+
const spent = () => ((limits.inputTokens !== undefined && usage.totals.inputTokens >= limits.inputTokens)
|
|
934
|
+
|| (limits.requests !== undefined && usage.totals.requests >= limits.requests - 1));
|
|
935
|
+
/**
|
|
936
|
+
* A whole-file read is many requests at once: one that would pass a ceiling of the question is
|
|
937
|
+
* not started. `reserved` is what the reads already let through in this turn will take: they run
|
|
938
|
+
* together, and the totals do not show them yet.
|
|
939
|
+
*/
|
|
940
|
+
const tooCostly = (call, reserved) => {
|
|
941
|
+
if (call.name !== TOOL_NAMES.analyze)
|
|
942
|
+
return {};
|
|
943
|
+
const meta = searchable.find((document) => document.id === call.args.document_id);
|
|
944
|
+
if (!meta)
|
|
945
|
+
return {};
|
|
946
|
+
// A read of a document read whole as often as it may be is refused by the tool, at no cost: it
|
|
947
|
+
// takes nothing from the reads of other documents.
|
|
948
|
+
const before = evidence.filter((shown) => shown.whole && shown.documentId === meta.id).length + (reserved.reads.get(meta.id) ?? 0);
|
|
949
|
+
if (before >= (limits.wholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS))
|
|
950
|
+
return {};
|
|
951
|
+
// The parts are read by the model that explores, in its own tokens.
|
|
952
|
+
const tokens = Math.ceil(meta.estimatedTokens * scaleOf(toolModel));
|
|
953
|
+
// The parts, a merge of their notes, the answer of the read, and the answer of the question.
|
|
954
|
+
const requests = estimateParts(meta, budget) + 3;
|
|
955
|
+
if (limits.inputTokens !== undefined) {
|
|
956
|
+
const left = Math.max(0, limits.inputTokens - usage.totals.inputTokens - reserved.inputTokens);
|
|
957
|
+
if (tokens > left)
|
|
958
|
+
return { refusal: `Not run: reading all of ${meta.name} takes about ${count(tokens)} input tokens, and ${count(left)} are left of the ${count(limits.inputTokens)} this question may use. Use search_document and read_document.` };
|
|
959
|
+
}
|
|
960
|
+
if (limits.requests !== undefined) {
|
|
961
|
+
const left = Math.max(0, limits.requests - usage.totals.requests - reserved.requests);
|
|
962
|
+
if (requests > left)
|
|
963
|
+
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.` };
|
|
964
|
+
}
|
|
965
|
+
reserved.inputTokens += tokens;
|
|
966
|
+
// The answer of the question is one request, whatever number of reads come before it.
|
|
967
|
+
reserved.requests += requests - 1;
|
|
968
|
+
reserved.reads.set(meta.id, (reserved.reads.get(meta.id) ?? 0) + 1);
|
|
969
|
+
// The read's own requests: its parts, a merge of their notes, and its answer.
|
|
970
|
+
return { own: requests - 1 };
|
|
971
|
+
};
|
|
972
|
+
/**
|
|
973
|
+
* A pointer for a call whose result is already in the conversation, in full: an earlier result
|
|
974
|
+
* (of this question or of one before it) holds what this one would return. The files do not
|
|
975
|
+
* change, so running it again would only take room.
|
|
976
|
+
*/
|
|
977
|
+
const shownBefore = (call) => {
|
|
978
|
+
if (!canPoint)
|
|
979
|
+
return undefined;
|
|
980
|
+
for (let at = messages.length - 1; at >= 0; at--) {
|
|
981
|
+
const message = messages[at];
|
|
982
|
+
if (!isRound(message))
|
|
983
|
+
continue;
|
|
984
|
+
// The rounds before `asked` are those of earlier questions, which an older version may have written.
|
|
985
|
+
for (const answer of message.answers) {
|
|
986
|
+
const pointer = alreadyShown(call, answer, at < asked);
|
|
987
|
+
if (pointer)
|
|
988
|
+
return pointer;
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
return undefined;
|
|
992
|
+
};
|
|
993
|
+
/** The tool and mode of the calls that failed last, and how many failed in a row. */
|
|
994
|
+
let failing;
|
|
995
|
+
let answered = false;
|
|
996
|
+
let outOfRoom = false;
|
|
997
|
+
// Tools run in at most maxTurns - 1 requests. The last request is the one below that must be
|
|
998
|
+
// answered in text, so a model that never stops calling tools does not cost a request whose
|
|
999
|
+
// calls are thrown away.
|
|
1000
|
+
const toolRole = explorer ? "explorer" : "tools";
|
|
1001
|
+
/** 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. */
|
|
1002
|
+
const labelOf = (call) => stepLine(tools.has(call.name) ? tools.describe(call.name, call.args) : `Call ${unknownToolName(call.name)}`);
|
|
1003
|
+
for (let round = 1 + (carried?.answered ?? 0); round < maxTurns && !outOfRoom; round++) {
|
|
1004
|
+
if (spent()) {
|
|
1005
|
+
budgetReached();
|
|
432
1006
|
break;
|
|
433
|
-
if (shrink(keep)) {
|
|
434
|
-
dropped = true;
|
|
435
|
-
left = room(pending);
|
|
436
1007
|
}
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
//
|
|
443
|
-
if (
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
return { call, label, refusal: NO_ROOM };
|
|
1008
|
+
const toolRequest = () => ({ system: toolSystem, messages: viewFor(toolModel), tools: declarations, toolChoice: "auto" });
|
|
1009
|
+
let reply = await send(toolModel, () => toolRequest(), !explorer, { role: toolRole, purpose: "turn" });
|
|
1010
|
+
// A turn whose tool call could not be read, or a first reply with nothing in it, is asked
|
|
1011
|
+
// for once more, with a note that says what was wrong: the answer would otherwise be written
|
|
1012
|
+
// from the cards alone, and look like any other. The note is not kept in the conversation.
|
|
1013
|
+
// It is a request of the chat like any other: it takes a tool turn, and the last turn is still the answer's.
|
|
1014
|
+
if (reply.calls.length === 0 && nudges < MOST_NUDGES && round + 1 < maxTurns && !reply.blockReason && !spent()) {
|
|
1015
|
+
const malformed = reply.finish === "malformed_call";
|
|
1016
|
+
const empty = !reply.text.trim() && callsAnswered === 0 && reply.finish !== "cut" && reply.finish !== "filtered";
|
|
1017
|
+
if (malformed || empty) {
|
|
1018
|
+
nudges++;
|
|
1019
|
+
round++;
|
|
1020
|
+
step(malformed ? "The model's tool call could not be read: it was asked to send it again" : "The model's first reply was empty: it was asked again", "nudged");
|
|
1021
|
+
const note = malformed ? (explorer ? MALFORMED_EXPLORER_NUDGE : MALFORMED_CALL_NUDGE) : explorer ? EMPTY_EXPLORER_NUDGE : EMPTY_REPLY_NUDGE;
|
|
1022
|
+
const withIt = notedMessages(note);
|
|
1023
|
+
reply = await send(toolModel, () => ({ system: toolSystem, messages: withIt(), tools: declarations, toolChoice: "auto" }), !explorer, { role: toolRole, purpose: "nudge" });
|
|
1024
|
+
}
|
|
455
1025
|
}
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
1026
|
+
if (reply.calls.length === 0) {
|
|
1027
|
+
// Text from this turn is the answer. A remark made earlier, before a tool call, is not.
|
|
1028
|
+
// Neither is anything an explorer model writes: the answer is asked for below.
|
|
1029
|
+
answered = wrote(reply) && !explorer;
|
|
1030
|
+
break;
|
|
1031
|
+
}
|
|
1032
|
+
const pending = { role: "tools", calls: reply.calls, answers: [], ...(reply.raw !== undefined ? { raw: reply.raw } : {}) };
|
|
1033
|
+
if (reply.raw !== undefined)
|
|
1034
|
+
rawOwner.set(pending, toolModel);
|
|
1035
|
+
// Every call must be answered, but not every call is run: a turn of sixty reads would build
|
|
1036
|
+
// a request that no model accepts, and a file can ask a model for exactly that.
|
|
1037
|
+
const run = reply.calls.slice(0, maxCalls);
|
|
1038
|
+
const most = (call) => tools.resultCharacters(call.name);
|
|
1039
|
+
const reserved = { inputTokens: 0, requests: 0, reads: new Map() };
|
|
1040
|
+
/** The first call of this turn with each key: the same call made again in the turn is not run twice. */
|
|
1041
|
+
const seen = new Map();
|
|
1042
|
+
const planned = run.map((call, index) => {
|
|
1043
|
+
const label = labelOf(call);
|
|
1044
|
+
// A call that did not arrive whole is not run: the model is told, and can send it again.
|
|
1045
|
+
if (call.problem)
|
|
1046
|
+
return { call, label, refusal: call.problem };
|
|
1047
|
+
// A look at pages returns a file and a few words: the file has its own room, worked out when it runs.
|
|
1048
|
+
if (call.name === TOOL_NAMES.view)
|
|
1049
|
+
return { call, label };
|
|
1050
|
+
const key = toolCallKey(call.name, call.args);
|
|
1051
|
+
if (key !== undefined && canPoint) {
|
|
1052
|
+
const twin = seen.get(key);
|
|
1053
|
+
if (twin !== undefined)
|
|
1054
|
+
return { call, label, twinOf: twin, pointer: { already_shown: true, note: `Not run: call ${twin + 1} of this turn is the same call, and its result is next to this one. Use it.` } };
|
|
1055
|
+
seen.set(key, index);
|
|
1056
|
+
}
|
|
1057
|
+
const pointer = shownBefore(call);
|
|
1058
|
+
if (pointer)
|
|
1059
|
+
return { call, label, pointer, earlier: true };
|
|
1060
|
+
const cost = tooCostly(call, reserved);
|
|
1061
|
+
if (cost.refusal)
|
|
1062
|
+
return { call, label, refusal: cost.refusal };
|
|
1063
|
+
return { call, label, ...(cost.own !== undefined ? { own: cost.own } : {}) };
|
|
1064
|
+
});
|
|
1065
|
+
// The requests each whole-file read of the turn may make, once all of them are reserved: its
|
|
1066
|
+
// own, and an even share of what the question has left over them (a part read as two halves
|
|
1067
|
+
// takes one more). Together they never pass limits.requests.
|
|
1068
|
+
const reads = planned.filter((plan) => plan.own !== undefined);
|
|
1069
|
+
if (limits.requests !== undefined && reads.length > 0) {
|
|
1070
|
+
const slack = Math.max(0, limits.requests - usage.totals.requests - 1 - reserved.requests);
|
|
1071
|
+
for (const plan of reads)
|
|
1072
|
+
plan.limits = { ...plan.limits, maxRequests: plan.own + Math.floor(slack / reads.length) };
|
|
1073
|
+
}
|
|
1074
|
+
// The calls that return text, and the most they may return: a call that is refused, or
|
|
1075
|
+
// answered with a pointer to what is already shown, needs no room.
|
|
1076
|
+
const sized = planned.filter((plan) => !plan.refusal && !plan.pointer && plan.call.name !== TOOL_NAMES.view);
|
|
1077
|
+
const needed = sized.reduce((sum, plan) => sum + most(plan.call), 0);
|
|
1078
|
+
let left = room(pending);
|
|
1079
|
+
let dropped = false;
|
|
1080
|
+
for (const keep of canShrink ? ROUNDS_KEPT : []) {
|
|
1081
|
+
if (left >= needed)
|
|
1082
|
+
break;
|
|
1083
|
+
if (shrink(keep)) {
|
|
1084
|
+
dropped = true;
|
|
1085
|
+
left = room(pending);
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
if (dropped) {
|
|
1089
|
+
step("Older tool results were shortened to make room in the request", "results_shortened");
|
|
1090
|
+
// A result that was shortened is no longer shown in full: a call that pointed to it is run after all.
|
|
1091
|
+
for (const plan of planned) {
|
|
1092
|
+
if (!plan.earlier)
|
|
1093
|
+
continue;
|
|
1094
|
+
const pointer = shownBefore(plan.call);
|
|
1095
|
+
if (pointer) {
|
|
1096
|
+
plan.pointer = pointer;
|
|
476
1097
|
}
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
1098
|
+
else {
|
|
1099
|
+
delete plan.pointer;
|
|
1100
|
+
delete plan.earlier;
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
const runsNow = planned.filter((plan) => !plan.refusal && !plan.pointer && plan.call.name !== TOOL_NAMES.view);
|
|
1105
|
+
// The room is shared by those calls. A result is most often far smaller than its cap, so a call
|
|
1106
|
+
// that was given its whole cap first could leave none for the next ones, and a turn of small
|
|
1107
|
+
// searches ended the question.
|
|
1108
|
+
const shares = shareRoom(runsNow.map((plan) => most(plan.call)), left);
|
|
1109
|
+
runsNow.forEach((plan, index) => {
|
|
1110
|
+
const share = shares[index];
|
|
1111
|
+
const cap = most(plan.call);
|
|
1112
|
+
if (share === undefined) {
|
|
1113
|
+
if (!outOfRoom)
|
|
1114
|
+
notice("no_room", "There is no room left in this conversation for another tool result.");
|
|
1115
|
+
outOfRoom = true;
|
|
1116
|
+
plan.refusal = NO_ROOM;
|
|
1117
|
+
}
|
|
1118
|
+
else if (plan.call.name === TOOL_NAMES.analyze) {
|
|
1119
|
+
// The answer of a whole-file read cannot be asked for again. It is not cut to an even share
|
|
1120
|
+
// up front: it gets all the room the other results of the turn leave, once they are in.
|
|
1121
|
+
plan.late = true;
|
|
1122
|
+
}
|
|
1123
|
+
else if (share < cap) {
|
|
1124
|
+
plan.limits = { ...plan.limits, maxResultCharacters: share };
|
|
1125
|
+
}
|
|
1126
|
+
});
|
|
1127
|
+
// A call made twice in the turn whose first was refused (no room, or not whole) is refused the
|
|
1128
|
+
// same way: there is no result next to it to use.
|
|
1129
|
+
for (const plan of planned) {
|
|
1130
|
+
const source = plan.twinOf === undefined ? undefined : planned[plan.twinOf];
|
|
1131
|
+
if (source?.refusal) {
|
|
1132
|
+
plan.refusal = source.refusal;
|
|
1133
|
+
delete plan.pointer;
|
|
1134
|
+
}
|
|
487
1135
|
}
|
|
488
|
-
|
|
1136
|
+
// Each call of the turn, those over `maxCalls` too, has an id for its events, in call order.
|
|
1137
|
+
const callIds = reply.calls.map(() => `call_${++state.calls}`);
|
|
1138
|
+
/**
|
|
1139
|
+
* The calls of this turn whose `tool.start` went out and whose `tool.end` has not, by index:
|
|
1140
|
+
* when each started, and how to end the requests of a whole-file read still under way.
|
|
1141
|
+
*/
|
|
1142
|
+
const openCalls = new Map();
|
|
1143
|
+
/** True once the turn failed (the question was stopped): nothing more of it is reported. */
|
|
1144
|
+
let turnFailed = false;
|
|
1145
|
+
/**
|
|
1146
|
+
* The first throw of a listener told of a whole-file read while it runs (`onEvent`,
|
|
1147
|
+
* `onActivity`). It must reach the caller, not become the read's own failure: the calls of the
|
|
1148
|
+
* question stop, and the turn ends with it.
|
|
1149
|
+
*/
|
|
1150
|
+
let listenerError;
|
|
1151
|
+
const tell = (told) => {
|
|
489
1152
|
try {
|
|
490
|
-
|
|
491
|
-
return await tools.executeWithFiles(call.name, call.args, callLimits);
|
|
1153
|
+
told();
|
|
492
1154
|
}
|
|
493
|
-
|
|
494
|
-
|
|
1155
|
+
catch (error) {
|
|
1156
|
+
if (listenerError)
|
|
1157
|
+
return;
|
|
1158
|
+
listenerError = { error };
|
|
1159
|
+
halt.abort(error);
|
|
495
1160
|
}
|
|
1161
|
+
};
|
|
1162
|
+
const startTool = (index, call, label) => {
|
|
1163
|
+
if (turnFailed)
|
|
1164
|
+
return;
|
|
1165
|
+
openCalls.set(index, { began: Date.now(), requests: new Set() });
|
|
1166
|
+
if (!events.active)
|
|
1167
|
+
return;
|
|
1168
|
+
events.emit({
|
|
1169
|
+
type: "tool.start",
|
|
1170
|
+
callId: callIds[index],
|
|
1171
|
+
...(call.id !== undefined ? { providerCallId: call.id } : {}),
|
|
1172
|
+
tool: call.name,
|
|
1173
|
+
args: call.args,
|
|
1174
|
+
label,
|
|
1175
|
+
...(typeof call.args?.document_id === "string" ? { documentId: call.args.document_id } : {}),
|
|
1176
|
+
round,
|
|
1177
|
+
});
|
|
1178
|
+
};
|
|
1179
|
+
/** `sent`: the result as the model gets it. `line`: the step, as `onStep` got it. */
|
|
1180
|
+
const endTool = (index, outcome, sent, line, shown) => {
|
|
1181
|
+
const open = openCalls.get(index);
|
|
1182
|
+
openCalls.delete(index);
|
|
1183
|
+
// A request of a whole-file read that its read left behind ends before its call does.
|
|
1184
|
+
for (const end of [...open?.requests ?? []])
|
|
1185
|
+
end(new Error(CALL_ENDED));
|
|
1186
|
+
if (!events.active || turnFailed)
|
|
1187
|
+
return;
|
|
1188
|
+
events.emit({
|
|
1189
|
+
type: "tool.end",
|
|
1190
|
+
callId: callIds[index],
|
|
1191
|
+
outcome,
|
|
1192
|
+
ms: open ? Date.now() - open.began : 0,
|
|
1193
|
+
...(line !== undefined ? { step: line } : {}),
|
|
1194
|
+
...(shown ? { evidence: { ...shown, callId: callIds[index] } } : {}),
|
|
1195
|
+
resultCharacters: JSON.stringify(sent).length,
|
|
1196
|
+
...(typeof sent.error === "string" ? { error: sent.error } : {}),
|
|
1197
|
+
...(options.eventResults === true ? { result: sent } : {}),
|
|
1198
|
+
});
|
|
1199
|
+
};
|
|
1200
|
+
/** Ends every call of the turn still open, and its requests, in call order, when the turn failed. */
|
|
1201
|
+
const failTurn = (error) => {
|
|
1202
|
+
const open = [...openCalls].sort(([first], [second]) => first - second);
|
|
1203
|
+
openCalls.clear();
|
|
1204
|
+
turnFailed = true;
|
|
1205
|
+
const why = events.active ? eventErrorOf(error).message : "";
|
|
1206
|
+
for (const [index, call] of open) {
|
|
1207
|
+
for (const end of [...call.requests])
|
|
1208
|
+
end(error);
|
|
1209
|
+
if (!events.active)
|
|
1210
|
+
continue;
|
|
1211
|
+
events.emit({ type: "tool.end", callId: callIds[index], outcome: "error", ms: Date.now() - call.began, error: why, resultCharacters: 0 });
|
|
1212
|
+
}
|
|
1213
|
+
};
|
|
1214
|
+
/** A model request of a whole-file read, for its events. */
|
|
1215
|
+
const readerRequest = (index, start) => {
|
|
1216
|
+
const open = openCalls.get(index);
|
|
1217
|
+
// The call was ended already (the question was stopped): nothing more of it is reported.
|
|
1218
|
+
if (!open)
|
|
1219
|
+
return { retry: () => undefined, end: () => undefined };
|
|
1220
|
+
const requestId = `req_${++state.requests}`;
|
|
1221
|
+
const began = Date.now();
|
|
1222
|
+
let ended = false;
|
|
1223
|
+
const end = (last) => {
|
|
1224
|
+
if (ended)
|
|
1225
|
+
return;
|
|
1226
|
+
ended = true;
|
|
1227
|
+
open.requests.delete(abandon);
|
|
1228
|
+
tell(() => events.emit({
|
|
1229
|
+
type: "request.end",
|
|
1230
|
+
requestId,
|
|
1231
|
+
ms: Date.now() - began,
|
|
1232
|
+
outcome: last.outcome,
|
|
1233
|
+
...(last.usage ? { usage: last.usage } : {}),
|
|
1234
|
+
...(last.error !== undefined ? { error: eventErrorOf(last.error) } : {}),
|
|
1235
|
+
}));
|
|
1236
|
+
};
|
|
1237
|
+
const abandon = (error) => end({ outcome: "error", error });
|
|
1238
|
+
// Before its start goes out: a listener that throws on the start still gets the end.
|
|
1239
|
+
open.requests.add(abandon);
|
|
1240
|
+
tell(() => events.emit({ type: "request.start", requestId, role: "reader", purpose: start.purpose, model: toolModel.id, callId: callIds[index], detail: start.detail }));
|
|
1241
|
+
return {
|
|
1242
|
+
retry: (retried) => {
|
|
1243
|
+
if (!ended && events.active)
|
|
1244
|
+
tell(() => events.emit({ type: "retry", requestId, attempt: retried.attempt, delayMs: retried.delayMs, error: eventErrorOf(retried.error), message: retryMessage(retried) }));
|
|
1245
|
+
},
|
|
1246
|
+
end,
|
|
1247
|
+
};
|
|
1248
|
+
};
|
|
1249
|
+
/**
|
|
1250
|
+
* The listeners of one call: its progress goes to `onActivity` as before (in place of the
|
|
1251
|
+
* tool set's shared listener) and is told apart by call in the events, with its requests.
|
|
1252
|
+
*/
|
|
1253
|
+
const hooksFor = (index) => ({
|
|
1254
|
+
onProgress: (event) => tell(() => {
|
|
1255
|
+
options.onActivity?.(`${event.message}…`);
|
|
1256
|
+
if (openCalls.has(index))
|
|
1257
|
+
events.emit({ type: "tool.progress", callId: callIds[index], stage: event.kind, done: event.done, total: event.total, message: event.message });
|
|
1258
|
+
}),
|
|
1259
|
+
...(events.active ? { onRequest: (start) => readerRequest(index, start) } : {}),
|
|
496
1260
|
});
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
1261
|
+
// The calls of a turn run together, a few at a time. Looks at pages take their turns, one
|
|
1262
|
+
// after another: each is given the room the ones before it left.
|
|
1263
|
+
const together = new Limiter(CALLS_AT_ONCE);
|
|
1264
|
+
let looks = Promise.resolve();
|
|
1265
|
+
// The size of the request as it stands, worked out when the first look at pages in this turn needs it.
|
|
1266
|
+
let requestBytes;
|
|
1267
|
+
const runCall = ({ call, label, refusal, pointer, limits: callLimits }, index) => {
|
|
1268
|
+
if (refusal || pointer)
|
|
1269
|
+
startTool(index, call, label);
|
|
1270
|
+
if (refusal)
|
|
1271
|
+
return Promise.resolve({ result: { error: refusal }, files: [] });
|
|
1272
|
+
if (pointer)
|
|
1273
|
+
return Promise.resolve({ result: pointer, files: [] });
|
|
1274
|
+
if (call.name === TOOL_NAMES.view) {
|
|
1275
|
+
const look = looks.then(async () => {
|
|
1276
|
+
halt.signal.throwIfAborted();
|
|
1277
|
+
options.onActivity?.(`${label}…`);
|
|
1278
|
+
startTool(index, call, label);
|
|
1279
|
+
if (requestBytes === undefined) {
|
|
1280
|
+
const waiting = { system: toolSystem, messages: [...viewFor(toolModel), pending], tools: declarations, toolChoice: "auto" };
|
|
1281
|
+
requestBytes = toolModel.requestBytes?.(waiting) ?? meter.estimate(waiting.messages).bytes;
|
|
1282
|
+
}
|
|
1283
|
+
// Base64 turns three bytes into four characters.
|
|
1284
|
+
const output = await tools.executeWithFiles(call.name, call.args, { maxFileBytes: Math.floor((maxRequestBytes - bytesKeptFree - requestBytes) * 3 / 4), maxPages: pagesLeft });
|
|
1285
|
+
for (const file of output.files)
|
|
1286
|
+
requestBytes += Math.ceil(file.bytes.length / 3) * 4 + 512;
|
|
1287
|
+
if (output.files.length > 0)
|
|
1288
|
+
pagesLeft -= pagesShown(output.result);
|
|
1289
|
+
return output;
|
|
1290
|
+
});
|
|
1291
|
+
looks = look.catch(() => undefined);
|
|
1292
|
+
return look;
|
|
1293
|
+
}
|
|
1294
|
+
return together.acquire(halt.signal).then(async (release) => {
|
|
1295
|
+
try {
|
|
1296
|
+
// The turn may have failed while this call waited for its slot.
|
|
1297
|
+
halt.signal.throwIfAborted();
|
|
1298
|
+
options.onActivity?.(`${label}…`);
|
|
1299
|
+
startTool(index, call, label);
|
|
1300
|
+
return await tools.executeWithFiles(call.name, call.args, callLimits, hooksFor(index));
|
|
1301
|
+
}
|
|
1302
|
+
finally {
|
|
1303
|
+
release();
|
|
1304
|
+
}
|
|
1305
|
+
});
|
|
1306
|
+
};
|
|
1307
|
+
const turnsLeft = outOfRoom ? 0 : maxTurns - round - 1;
|
|
1308
|
+
const answers = [];
|
|
1309
|
+
try {
|
|
1310
|
+
const outputs = [];
|
|
1311
|
+
for (const [index, plan] of planned.entries()) {
|
|
1312
|
+
const output = runCall(plan, index);
|
|
1313
|
+
// One that fails (the question was stopped) is reported below, in call order; the others must not go unheard.
|
|
1314
|
+
output.catch(() => undefined);
|
|
1315
|
+
outputs.push(output);
|
|
1316
|
+
}
|
|
1317
|
+
/**
|
|
1318
|
+
* The room of each whole-file read of the turn: what the other results left, shared among the
|
|
1319
|
+
* reads, the smaller answers first. Worked out when the first of them is reached, by which time
|
|
1320
|
+
* the other calls, which are quick, have most often returned.
|
|
1321
|
+
*/
|
|
1322
|
+
let lateRoom;
|
|
1323
|
+
const roomOfReads = async () => {
|
|
1324
|
+
const sizes = await Promise.all(outputs.map(async (output) => JSON.stringify((await output).result).length));
|
|
1325
|
+
const reads = planned.flatMap((plan, index) => (plan.late ? [index] : []));
|
|
1326
|
+
let free = left - sizes.reduce((sum, size, index) => sum + (planned[index].late ? 0 : size), 0);
|
|
1327
|
+
const shares = new Map();
|
|
1328
|
+
[...reads].sort((first, second) => sizes[first] - sizes[second]).forEach((index, position) => {
|
|
1329
|
+
const share = Math.min(sizes[index], Math.floor(free / (reads.length - position)));
|
|
1330
|
+
shares.set(index, share);
|
|
1331
|
+
free -= share;
|
|
1332
|
+
});
|
|
1333
|
+
return shares;
|
|
1334
|
+
};
|
|
1335
|
+
// The answers in call order. Each call's `tool.end` goes out here, in the same order.
|
|
1336
|
+
for (const [index, { call, label, late, refusal, pointer }] of planned.entries()) {
|
|
1337
|
+
let output = await outputs[index];
|
|
1338
|
+
if (listenerError)
|
|
1339
|
+
throw listenerError.error;
|
|
1340
|
+
callsAnswered++;
|
|
1341
|
+
if (late) {
|
|
1342
|
+
lateRoom ??= await roomOfReads();
|
|
1343
|
+
const share = lateRoom.get(index);
|
|
1344
|
+
if (JSON.stringify(output.result).length > share)
|
|
1345
|
+
output = { ...output, result: fitAnswer(output.result, Math.max(LEAST_RESULT_CHARACTERS, share)) };
|
|
1346
|
+
}
|
|
1347
|
+
if (pointer) {
|
|
1348
|
+
const line = step(`${label} — already shown above`);
|
|
1349
|
+
const sent = { ...output.result, tool_turns_left: turnsLeft };
|
|
1350
|
+
answers.push({ call, result: sent, files: [] });
|
|
1351
|
+
endTool(index, "already_shown", sent, line);
|
|
1352
|
+
continue;
|
|
1353
|
+
}
|
|
1354
|
+
// Two searches in a row that failed in the same mode: the second says to try another way.
|
|
1355
|
+
if (!refusal) {
|
|
1356
|
+
const kind = failureKind(call);
|
|
1357
|
+
if (kind === undefined) {
|
|
1358
|
+
failing = undefined;
|
|
1359
|
+
}
|
|
1360
|
+
else if (typeof output.result.error === "string") {
|
|
1361
|
+
failing = failing?.kind === kind ? { kind, count: failing.count + 1 } : { kind, count: 1 };
|
|
1362
|
+
if (failing.count >= 2)
|
|
1363
|
+
output = { ...output, result: { ...output.result, error: `${output.result.error} ${repeatedFailureHint(call)}` } };
|
|
1364
|
+
}
|
|
1365
|
+
else {
|
|
1366
|
+
failing = undefined;
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
const line = step(`${label}${toolResultSummary(label, output.result)}`);
|
|
1370
|
+
const shown = evidenceOf(call, output.result);
|
|
1371
|
+
if (shown)
|
|
1372
|
+
evidence.push({ ...shown, callId: callIds[index] });
|
|
1373
|
+
const sent = { ...output.result, tool_turns_left: turnsLeft };
|
|
1374
|
+
answers.push({ call, result: sent, files: output.files });
|
|
1375
|
+
const outcome = call.problem ? "error" : refusal ? "refused" : typeof output.result.error === "string" ? "error" : "ok";
|
|
1376
|
+
endTool(index, outcome, sent, line, shown);
|
|
1377
|
+
}
|
|
1378
|
+
// A listener of a read that went on after its call returned (its progress).
|
|
1379
|
+
if (listenerError)
|
|
1380
|
+
throw listenerError.error;
|
|
1381
|
+
}
|
|
1382
|
+
catch (error) {
|
|
1383
|
+
// The calls of the turn still waiting for a slot, or running, stop.
|
|
1384
|
+
halt.abort(error);
|
|
1385
|
+
failTurn(error);
|
|
1386
|
+
throw error;
|
|
1387
|
+
}
|
|
1388
|
+
for (const [offset, call] of reply.calls.slice(maxCalls).entries()) {
|
|
1389
|
+
callsAnswered++;
|
|
1390
|
+
const sent = { error: `Not run: one turn runs at most ${maxCalls} tool calls. Send this call again if you still need it.`, tool_turns_left: turnsLeft };
|
|
1391
|
+
answers.push({ call, result: sent, files: [] });
|
|
1392
|
+
if (events.active) {
|
|
1393
|
+
startTool(maxCalls + offset, call, labelOf(call));
|
|
1394
|
+
endTool(maxCalls + offset, "not_run", sent);
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
const notRun = reply.calls.length - maxCalls;
|
|
1398
|
+
if (notRun > 0)
|
|
1399
|
+
step(`${notRun} more tool ${notRun === 1 ? "call in this turn was" : "calls in this turn were"} not run (at most ${maxCalls} a turn)`, "calls_not_run");
|
|
1400
|
+
const done = { ...pending, answers };
|
|
1401
|
+
if (reply.raw !== undefined)
|
|
1402
|
+
rawOwner.set(done, toolModel);
|
|
1403
|
+
messages.push(done);
|
|
510
1404
|
}
|
|
511
|
-
|
|
512
|
-
|
|
1405
|
+
// Out of tool turns or of room, or the last turn had no text (cut off, or a malformed tool call):
|
|
1406
|
+
// ask once more, for an answer in text. A blocked prompt would only be blocked again.
|
|
1407
|
+
// With an explorer model this request is always made: it is the one the answering model gets.
|
|
1408
|
+
if (!answered && !blockReason) {
|
|
1409
|
+
activity("writing_answer", "Writing the answer…");
|
|
1410
|
+
let closing = searchable.length > 0 ? FINAL_ANSWER_REQUEST : FINAL_ANSWER_AFTER_PAGES;
|
|
1411
|
+
// No tool ran (the explorer needed none, the first reply was empty, or no turn was left for
|
|
1412
|
+
// tools): there is no tool result to answer from. The answering model gets the explorer's
|
|
1413
|
+
// calls and what they returned, and nothing else of it.
|
|
1414
|
+
if (callsAnswered === 0)
|
|
1415
|
+
closing = FINAL_ANSWER_WITHOUT_TOOLS;
|
|
1416
|
+
const answerRequest = (note) => () => ({
|
|
1417
|
+
system,
|
|
1418
|
+
messages: [...viewFor(model), { role: "user", parts: [{ text: closing }, ...(note ? [{ text: note }] : [])] }],
|
|
1419
|
+
tools: declarations,
|
|
1420
|
+
toolChoice: "none",
|
|
1421
|
+
});
|
|
1422
|
+
let reply = await send(model, answerRequest(), true, { role: "answer", purpose: "closing" });
|
|
1423
|
+
// A reply with no text (empty, or a tool call the model was told not to make, or one that
|
|
1424
|
+
// could not be read) is asked for once more, with a note that is not kept: otherwise the
|
|
1425
|
+
// question ends with nothing to show. Not after a refusal or a filter, which would come again,
|
|
1426
|
+
// nor a reply cut off at the output limit with nothing in it, nor once a ceiling of `limits`
|
|
1427
|
+
// is reached. It is one of the second tries of the question, and may be one request past
|
|
1428
|
+
// `limits.toolTurns`, which counts the answer's first request.
|
|
1429
|
+
const calledInstead = reply.calls.length > 0 || reply.finish === "malformed_call";
|
|
1430
|
+
const ceilingReached = (limits.inputTokens !== undefined && usage.totals.inputTokens >= limits.inputTokens)
|
|
1431
|
+
|| (limits.requests !== undefined && usage.totals.requests >= limits.requests);
|
|
1432
|
+
if (!wrote(reply) && !reply.blockReason && reply.finish !== "filtered" && (calledInstead || reply.finish !== "cut") && nudges < MOST_NUDGES) {
|
|
1433
|
+
if (ceilingReached) {
|
|
1434
|
+
budgetReached();
|
|
1435
|
+
}
|
|
1436
|
+
else {
|
|
1437
|
+
nudges++;
|
|
1438
|
+
step(calledInstead ? "The model called a tool instead of answering: it was asked again for the answer" : "The model's answer was empty: it was asked again", "answer_again");
|
|
1439
|
+
reply = await send(model, answerRequest(ANSWER_AGAIN_NOTE), true, { role: "answer", purpose: "answer_again" });
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
answered = wrote(reply);
|
|
513
1443
|
}
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
1444
|
+
return result(answered);
|
|
1445
|
+
}
|
|
1446
|
+
catch (error) {
|
|
1447
|
+
// What the question found and paid for until it failed, for the application to keep. The usage is
|
|
1448
|
+
// a copy: a part reader that went on after the question was stopped may still report its own.
|
|
1449
|
+
if (!(error instanceof Replan) && error !== null && typeof error === "object")
|
|
1450
|
+
keepPartial(error, state, { ...result(false), usage: structuredClone(usage.totals) });
|
|
1451
|
+
throw error;
|
|
520
1452
|
}
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
// With an explorer model this request is always made: it is the one the answering model gets.
|
|
524
|
-
if (!answered && !blockReason) {
|
|
525
|
-
options.onActivity?.("Writing the answer…");
|
|
526
|
-
let closing = searchable.length > 0 ? FINAL_ANSWER_REQUEST : FINAL_ANSWER_AFTER_PAGES;
|
|
527
|
-
// The answering model gets the explorer's calls and what they returned, and nothing else of it.
|
|
528
|
-
if (explorer && steps.length === 0)
|
|
529
|
-
closing = FINAL_ANSWER_WITHOUT_TOOLS;
|
|
530
|
-
const reply = await request(model, {
|
|
531
|
-
system,
|
|
532
|
-
messages: [...viewFor(model), { role: "user", parts: [{ text: closing }] }],
|
|
533
|
-
tools: declarations,
|
|
534
|
-
toolChoice: "none",
|
|
535
|
-
}, true);
|
|
536
|
-
answered = wrote(reply);
|
|
1453
|
+
finally {
|
|
1454
|
+
signal?.removeEventListener("abort", stopTools);
|
|
537
1455
|
}
|
|
538
|
-
return result(answered);
|
|
539
1456
|
}
|
|
540
1457
|
//# sourceMappingURL=ask.js.map
|