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