llm-large-files 0.4.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +127 -0
- package/README.md +48 -8
- package/dist/anthropic/adapter.d.ts +106 -0
- package/dist/anthropic/adapter.d.ts.map +1 -0
- package/dist/anthropic/adapter.js +391 -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 +144 -0
- package/dist/ask.d.ts.map +1 -0
- package/dist/ask.js +540 -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/evidence.d.ts +40 -0
- package/dist/evidence.d.ts.map +1 -0
- package/dist/evidence.js +137 -0
- package/dist/evidence.js.map +1 -0
- package/dist/gemini/adapter.d.ts +50 -0
- package/dist/gemini/adapter.d.ts.map +1 -0
- package/dist/gemini/adapter.js +179 -0
- package/dist/gemini/adapter.js.map +1 -0
- package/dist/gemini/chat.d.ts +31 -75
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +38 -300
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +11 -0
- package/dist/gemini/errors.d.ts.map +1 -0
- package/dist/gemini/errors.js +14 -0
- package/dist/gemini/errors.js.map +1 -0
- package/dist/gemini/generate.d.ts +9 -20
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +43 -92
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -1
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -1
- 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 +20 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +55 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +13 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +29 -3
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +10 -12
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +9 -0
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +25 -19
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +196 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/model.js +41 -0
- package/dist/model.js.map +1 -0
- package/dist/openai/adapter.d.ts +85 -0
- package/dist/openai/adapter.d.ts.map +1 -0
- package/dist/openai/adapter.js +293 -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 +30 -0
- package/dist/output-limit.d.ts.map +1 -0
- package/dist/output-limit.js +92 -0
- package/dist/output-limit.js.map +1 -0
- package/dist/retry.d.ts +54 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +111 -0
- package/dist/retry.js.map +1 -0
- package/dist/sse.d.ts +3 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +39 -0
- package/dist/sse.js.map +1 -0
- package/dist/tools.d.ts +11 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +85 -31
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +28 -3
- package/dist/types.d.ts.map +1 -1
- package/docs/api.md +245 -27
- package/docs/configuration.md +83 -9
- package/docs/getting-started.md +67 -16
- package/docs/how-it-works.md +38 -2
- package/docs/security.md +18 -0
- package/package.json +21 -3
- package/src/anthropic/adapter.ts +454 -0
- package/src/anthropic/index.ts +2 -0
- package/src/ask.ts +675 -0
- package/src/budget.ts +71 -0
- package/src/evidence.ts +162 -0
- package/src/gemini/adapter.ts +218 -0
- package/src/gemini/chat.ts +61 -353
- package/src/gemini/errors.ts +15 -0
- package/src/gemini/generate.ts +50 -90
- package/src/gemini/index.ts +3 -1
- package/src/gemini/sse.ts +1 -34
- package/src/http.ts +59 -0
- package/src/index.ts +33 -4
- package/src/library.ts +39 -13
- package/src/map-reduce.ts +22 -16
- package/src/model.ts +200 -0
- package/src/openai/adapter.ts +345 -0
- package/src/openai/index.ts +2 -0
- package/src/output-limit.ts +99 -0
- package/src/retry.ts +132 -0
- package/src/sse.ts +34 -0
- package/src/tools.ts +91 -34
- package/src/types.ts +24 -3
package/src/retry.ts
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// One rule for sending a model request again, used by the chat loop and by whole-file part reads.
|
|
2
|
+
|
|
3
|
+
/** How a model request that failed is sent again. */
|
|
4
|
+
export type RetryOptions = {
|
|
5
|
+
/** How many times a failed request is sent again. Defaults to 3. 0 turns it off. */
|
|
6
|
+
retries?: number;
|
|
7
|
+
/** The first wait in milliseconds. Each later one is twice as long. Defaults to 500. */
|
|
8
|
+
baseDelayMs?: number;
|
|
9
|
+
/**
|
|
10
|
+
* The longest wait in milliseconds. Defaults to 60,000. When the provider asks for a longer one
|
|
11
|
+
* (`Retry-After`), the request is not sent again and the error is reported.
|
|
12
|
+
*/
|
|
13
|
+
maxDelayMs?: number;
|
|
14
|
+
/** For tests: the wait itself. */
|
|
15
|
+
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
16
|
+
/** For tests: the source of the jitter, a number from 0 up to 1. */
|
|
17
|
+
random?: () => number;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export const DEFAULT_RETRIES = 3;
|
|
21
|
+
const DEFAULT_BASE_DELAY_MS = 500;
|
|
22
|
+
const DEFAULT_MAX_DELAY_MS = 60_000;
|
|
23
|
+
|
|
24
|
+
/** The HTTP status of an error, when it carries one. 0 stands for a connection that failed. */
|
|
25
|
+
export function statusOf(error: unknown): number | undefined {
|
|
26
|
+
const status = (error as { status?: unknown } | null)?.status;
|
|
27
|
+
return typeof status === "number" && Number.isFinite(status) ? status : undefined;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Whether a request that failed with this status is worth sending again: the model could not be
|
|
32
|
+
* reached, timed out, was busy, or failed on its side. A request it refused (400, 401, 403, 404)
|
|
33
|
+
* would be refused again.
|
|
34
|
+
*/
|
|
35
|
+
export function isRetryableStatus(status: number): boolean {
|
|
36
|
+
return status === 0 || status === 408 || status === 409 || status === 429 || status >= 500;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** A wait that ends early, with the signal's reason, when the signal aborts. */
|
|
40
|
+
export function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
41
|
+
return new Promise<void>((resolve, reject) => {
|
|
42
|
+
if (signal?.aborted) {
|
|
43
|
+
reject(signal.reason);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
const done = () => {
|
|
47
|
+
signal?.removeEventListener("abort", stop);
|
|
48
|
+
resolve();
|
|
49
|
+
};
|
|
50
|
+
const timer = setTimeout(done, ms);
|
|
51
|
+
const stop = () => {
|
|
52
|
+
clearTimeout(timer);
|
|
53
|
+
reject(signal!.reason);
|
|
54
|
+
};
|
|
55
|
+
signal?.addEventListener("abort", stop, { once: true });
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The wait a provider asked for, in milliseconds: the `retry-after-ms` or `Retry-After` header
|
|
61
|
+
* (seconds, or a date), or the `retryDelay` of a `google.rpc.RetryInfo` in the error body ("17s").
|
|
62
|
+
*/
|
|
63
|
+
export function retryAfterMs(headers: Headers | undefined, body?: unknown, now: () => number = Date.now): number | undefined {
|
|
64
|
+
const exact = Number(headers?.get("retry-after-ms"));
|
|
65
|
+
if (headers?.get("retry-after-ms") && Number.isFinite(exact) && exact >= 0) return exact;
|
|
66
|
+
const header = headers?.get("retry-after");
|
|
67
|
+
if (header) {
|
|
68
|
+
const seconds = Number(header);
|
|
69
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.round(seconds * 1000);
|
|
70
|
+
const date = Date.parse(header);
|
|
71
|
+
if (Number.isFinite(date)) return Math.max(0, date - now());
|
|
72
|
+
}
|
|
73
|
+
const details = (body as { error?: { details?: unknown } } | null)?.error?.details;
|
|
74
|
+
if (Array.isArray(details)) {
|
|
75
|
+
for (const detail of details as Array<{ retryDelay?: unknown }>) {
|
|
76
|
+
const match = typeof detail?.retryDelay === "string" ? /^(\d+(?:\.\d+)?)s$/.exec(detail.retryDelay) : null;
|
|
77
|
+
if (match) return Math.round(Number(match[1]) * 1000);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export type RetryNotice = { error: unknown; attempt: number; delayMs: number };
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Runs a model request, and runs it again when it failed in a way that another try can mend.
|
|
87
|
+
* - An error with a retryable status (see `isRetryableStatus`) is retried after a wait that doubles
|
|
88
|
+
* each time, with jitter, or after the wait the provider asked for.
|
|
89
|
+
* - An error with another status is not retried.
|
|
90
|
+
* - An error without a status is retried once, at once, when `unknownErrors` is "once"; otherwise not.
|
|
91
|
+
* Nothing is retried after the signal aborted, or once `canRetry` says no.
|
|
92
|
+
*/
|
|
93
|
+
export async function withRetry<T>(run: () => Promise<T>, options: {
|
|
94
|
+
retry?: RetryOptions | undefined;
|
|
95
|
+
signal?: AbortSignal | undefined;
|
|
96
|
+
/** False once the attempt did something that must not happen twice: text was shown to the user. */
|
|
97
|
+
canRetry?: () => boolean;
|
|
98
|
+
onRetry?: (notice: RetryNotice) => void;
|
|
99
|
+
unknownErrors?: "once" | "never";
|
|
100
|
+
} = {}): Promise<T> {
|
|
101
|
+
const retries = Math.max(0, Math.trunc(options.retry?.retries ?? DEFAULT_RETRIES));
|
|
102
|
+
const base = Math.max(0, options.retry?.baseDelayMs ?? DEFAULT_BASE_DELAY_MS);
|
|
103
|
+
const longest = Math.max(0, options.retry?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS);
|
|
104
|
+
const wait = options.retry?.sleep ?? sleep;
|
|
105
|
+
const random = options.retry?.random ?? Math.random;
|
|
106
|
+
let unknownRetried = false;
|
|
107
|
+
for (let attempt = 0; ; attempt++) {
|
|
108
|
+
try {
|
|
109
|
+
return await run();
|
|
110
|
+
} catch (error) {
|
|
111
|
+
if (options.signal?.aborted || options.canRetry?.() === false) throw error;
|
|
112
|
+
const status = statusOf(error);
|
|
113
|
+
if (status === undefined) {
|
|
114
|
+
if (options.unknownErrors !== "once" || unknownRetried || retries === 0) throw error;
|
|
115
|
+
unknownRetried = true;
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
if (!isRetryableStatus(status) || attempt >= retries) throw error;
|
|
119
|
+
const asked = (error as { retryAfterMs?: unknown }).retryAfterMs;
|
|
120
|
+
let delayMs: number;
|
|
121
|
+
if (typeof asked === "number" && Number.isFinite(asked) && asked >= 0) {
|
|
122
|
+
// Waiting longer than the caller allows helps no one who is waiting for an answer.
|
|
123
|
+
if (asked > longest) throw error;
|
|
124
|
+
delayMs = asked;
|
|
125
|
+
} else {
|
|
126
|
+
delayMs = Math.min(longest, base * 2 ** attempt * (0.5 + random() / 2));
|
|
127
|
+
}
|
|
128
|
+
options.onRetry?.({ error, attempt: attempt + 1, delayMs });
|
|
129
|
+
await wait(delayMs, options.signal);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
package/src/sse.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** Parses a `text/event-stream` body into JSON objects, one per `data:` event. */
|
|
2
|
+
export async function* parseSseJson<T>(stream: ReadableStream<Uint8Array>): AsyncGenerator<T> {
|
|
3
|
+
const reader = stream.getReader();
|
|
4
|
+
const decoder = new TextDecoder();
|
|
5
|
+
let buffer = "";
|
|
6
|
+
const parse = (block: string): T | undefined => {
|
|
7
|
+
const data = block
|
|
8
|
+
.split("\n")
|
|
9
|
+
.filter((line) => line.startsWith("data:"))
|
|
10
|
+
.map((line) => line.slice(5).trimStart())
|
|
11
|
+
.join("\n");
|
|
12
|
+
return data && data !== "[DONE]" ? JSON.parse(data) as T : undefined;
|
|
13
|
+
};
|
|
14
|
+
try {
|
|
15
|
+
while (true) {
|
|
16
|
+
const { done, value } = await reader.read();
|
|
17
|
+
buffer += decoder.decode(value, { stream: !done });
|
|
18
|
+
buffer = buffer.replace(/\r\n/g, "\n");
|
|
19
|
+
let boundary = buffer.indexOf("\n\n");
|
|
20
|
+
while (boundary >= 0) {
|
|
21
|
+
const event = parse(buffer.slice(0, boundary));
|
|
22
|
+
buffer = buffer.slice(boundary + 2);
|
|
23
|
+
if (event !== undefined) yield event;
|
|
24
|
+
boundary = buffer.indexOf("\n\n");
|
|
25
|
+
}
|
|
26
|
+
if (done) break;
|
|
27
|
+
}
|
|
28
|
+
const last = buffer.trim() ? parse(buffer.trim()) : undefined;
|
|
29
|
+
if (last !== undefined) yield last;
|
|
30
|
+
} finally {
|
|
31
|
+
await reader.cancel().catch(() => undefined);
|
|
32
|
+
reader.releaseLock();
|
|
33
|
+
}
|
|
34
|
+
}
|
package/src/tools.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { safeErrorMessage } from "./errors.js";
|
|
2
|
-
import { analyzeWholeDocument } from "./map-reduce.js";
|
|
2
|
+
import { analyzeWholeDocument, TooManyPartsError } from "./map-reduce.js";
|
|
3
3
|
import { cutPdfPages } from "./pdf-pages.js";
|
|
4
4
|
import { grepSource, numberLines, rankSource, REGEX_TIME_LIMIT_MS, type DocumentSource } from "./search.js";
|
|
5
5
|
import { estimateParts, formatBytes, outlineLines, REQUEST_BYTES_MARGIN } from "./plan.js";
|
|
6
|
-
import type {
|
|
6
|
+
import type { RetryOptions } from "./retry.js";
|
|
7
|
+
import type { Budget, GenerateText, ProgressListener, ToolCallLimits, ToolDeclaration, ToolOutput, ToolResult, ToolSet } from "./types.js";
|
|
7
8
|
|
|
8
9
|
const DEFAULT_READ_LINES = 200;
|
|
9
10
|
const MAX_READ_LINES = 600;
|
|
@@ -16,6 +17,16 @@ export const MAX_VIEW_PAGES = 5;
|
|
|
16
17
|
export const REGEX_BUDGET_MS = 6_000;
|
|
17
18
|
/** Below this, no page fits: a cut of one page of plain text is larger. */
|
|
18
19
|
const MIN_FILE_BYTES = 1_024;
|
|
20
|
+
/** The answer of a whole-document read may be this long, when the cap on tool results is lower. */
|
|
21
|
+
const ANALYSIS_RESULT_CHARACTERS = 40_000;
|
|
22
|
+
/** A result is never cut below this, whatever room a caller names: less holds no line of a file. */
|
|
23
|
+
const LEAST_RESULT_CHARACTERS = 600;
|
|
24
|
+
/**
|
|
25
|
+
* How many times one document is read whole by the tools of one tool set (one question, in
|
|
26
|
+
* `askWithFiles`), unless `maxWholeDocumentReads` says otherwise. One read of a large file is
|
|
27
|
+
* up to `maxMapChunks` model requests.
|
|
28
|
+
*/
|
|
29
|
+
export const MAX_WHOLE_DOCUMENT_READS = 1;
|
|
19
30
|
|
|
20
31
|
export const TOOL_NAMES = {
|
|
21
32
|
search: "search_document",
|
|
@@ -169,6 +180,10 @@ export function createDocumentTools(options: {
|
|
|
169
180
|
signal?: AbortSignal;
|
|
170
181
|
/** The most time, in milliseconds, that the regex searches of this tool set may take together. Defaults to `REGEX_BUDGET_MS`. */
|
|
171
182
|
regexBudgetMs?: number;
|
|
183
|
+
/** How many times each document may be read whole by this tool set. Defaults to `MAX_WHOLE_DOCUMENT_READS`. */
|
|
184
|
+
maxWholeDocumentReads?: number;
|
|
185
|
+
/** How a model request of a whole-document read that failed is sent again. */
|
|
186
|
+
retry?: RetryOptions;
|
|
172
187
|
/**
|
|
173
188
|
* False when every document is too large for a whole-document read: `analyze_whole_document` is
|
|
174
189
|
* then not declared. A call of it still answers with the reason. Defaults to true.
|
|
@@ -195,11 +210,27 @@ export function createDocumentTools(options: {
|
|
|
195
210
|
const known = new Set(declarations.map((declaration) => declaration.name));
|
|
196
211
|
// Not declared for files that are all too large for it, but still answered: with the reason, not "unknown tool".
|
|
197
212
|
if (textTools && options.generate) known.add(TOOL_NAMES.analyze);
|
|
198
|
-
const
|
|
213
|
+
const cap = options.budget.toolResultCharacters;
|
|
214
|
+
/** The cap on the result of one call: the tool set's own, or the room its caller has left when that is less. */
|
|
215
|
+
const limitOf = (limits: ToolCallLimits, own = cap): number => {
|
|
216
|
+
const room = limits.maxResultCharacters;
|
|
217
|
+
return typeof room === "number" && Number.isFinite(room) ? Math.max(LEAST_RESULT_CHARACTERS, Math.min(own, Math.trunc(room))) : own;
|
|
218
|
+
};
|
|
199
219
|
// The model writes the regex, and a file it reads can ask for a slow one: the time is counted
|
|
200
220
|
// over every search of this tool set, not only within one.
|
|
201
221
|
const regexBudget = Math.max(0, options.regexBudgetMs ?? REGEX_BUDGET_MS);
|
|
202
222
|
const regexClock = { usedMs: 0 };
|
|
223
|
+
// Calls of one turn may run together. Regex searches still take their turns, one after another:
|
|
224
|
+
// each must know how much of the time the ones before it used.
|
|
225
|
+
let regexQueue: Promise<unknown> = Promise.resolve();
|
|
226
|
+
const inRegexTurn = <T>(run: () => Promise<T>): Promise<T> => {
|
|
227
|
+
const next = regexQueue.then(run, run);
|
|
228
|
+
regexQueue = next.catch(() => undefined);
|
|
229
|
+
return next;
|
|
230
|
+
};
|
|
231
|
+
const maxWholeReads = Math.max(0, Math.trunc(options.maxWholeDocumentReads ?? MAX_WHOLE_DOCUMENT_READS));
|
|
232
|
+
/** Whole-document reads started, by document. */
|
|
233
|
+
const wholeReads = new Map<string, number>();
|
|
203
234
|
// When no limit is given with a call: three eighths of a request, so that two looks still fit.
|
|
204
235
|
const defaultFileBytes = Math.floor((options.budget.maxRequestBytes - REQUEST_BYTES_MARGIN) * 3 / 8);
|
|
205
236
|
|
|
@@ -213,8 +244,9 @@ export function createDocumentTools(options: {
|
|
|
213
244
|
return document;
|
|
214
245
|
}
|
|
215
246
|
|
|
216
|
-
const handlers: Record<string, (args: Record<string, unknown
|
|
217
|
-
async [TOOL_NAMES.search](args) {
|
|
247
|
+
const handlers: Record<string, (args: Record<string, unknown>, limits: ToolCallLimits) => Promise<ToolResult>> = {
|
|
248
|
+
async [TOOL_NAMES.search](args, limits) {
|
|
249
|
+
const limit = limitOf(limits);
|
|
218
250
|
const document = await documentFor(args);
|
|
219
251
|
const query = text(args.query, "query");
|
|
220
252
|
const mode = args.mode === "exact" || args.mode === "regex" ? args.mode : "keywords";
|
|
@@ -241,18 +273,21 @@ export function createDocumentTools(options: {
|
|
|
241
273
|
}, "passages", limit);
|
|
242
274
|
}
|
|
243
275
|
const regex = mode === "regex";
|
|
244
|
-
const
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
276
|
+
const grep = async () => {
|
|
277
|
+
const regexLeft = regexBudget - regexClock.usedMs;
|
|
278
|
+
if (regex && regexLeft <= 0) {
|
|
279
|
+
throw new Error("The time for regex searches is used up for this answer. Search with mode \"exact\" or \"keywords\" instead.");
|
|
280
|
+
}
|
|
281
|
+
return grepSource(document, query, {
|
|
282
|
+
regex,
|
|
283
|
+
caseSensitive: args.case_sensitive === true,
|
|
284
|
+
maxResults: integer(args.max_results, 20, 1, 50),
|
|
285
|
+
contextLines: integer(args.context_lines, 0, 0, 5),
|
|
286
|
+
...(regex ? { timeLimitMs: Math.min(REGEX_TIME_LIMIT_MS, regexLeft), regexClock } : {}),
|
|
287
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
288
|
+
});
|
|
289
|
+
};
|
|
290
|
+
const result = await (regex ? inRegexTurn(grep) : grep());
|
|
256
291
|
return fit({
|
|
257
292
|
document: document.meta.name,
|
|
258
293
|
mode,
|
|
@@ -265,7 +300,8 @@ export function createDocumentTools(options: {
|
|
|
265
300
|
}, "matches", limit);
|
|
266
301
|
},
|
|
267
302
|
|
|
268
|
-
async [TOOL_NAMES.read](args) {
|
|
303
|
+
async [TOOL_NAMES.read](args, limits) {
|
|
304
|
+
const limit = limitOf(limits);
|
|
269
305
|
const document = await documentFor(args);
|
|
270
306
|
const total = document.lineCount;
|
|
271
307
|
const start = integer(args.start_line, 1, 1, total);
|
|
@@ -291,7 +327,8 @@ export function createDocumentTools(options: {
|
|
|
291
327
|
};
|
|
292
328
|
},
|
|
293
329
|
|
|
294
|
-
async [TOOL_NAMES.overview](args) {
|
|
330
|
+
async [TOOL_NAMES.overview](args, limits) {
|
|
331
|
+
const limit = limitOf(limits);
|
|
295
332
|
const document = await documentFor(args);
|
|
296
333
|
const { meta, lineCount } = document;
|
|
297
334
|
const tail = Math.max(1, lineCount - 19);
|
|
@@ -316,18 +353,37 @@ export function createDocumentTools(options: {
|
|
|
316
353
|
}, "outline", limit);
|
|
317
354
|
},
|
|
318
355
|
|
|
319
|
-
async [TOOL_NAMES.analyze](args) {
|
|
356
|
+
async [TOOL_NAMES.analyze](args, limits) {
|
|
320
357
|
if (!options.generate) throw new Error("Whole-document analysis is not enabled.");
|
|
321
358
|
const document = await documentFor(args);
|
|
322
359
|
const task = text(args.task, "task");
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
360
|
+
// A read of the whole file is many model requests. A model that asks for it again, with the
|
|
361
|
+
// task put another way, is told to use what it has. The count is taken before the read
|
|
362
|
+
// starts, so that two calls in one turn do not both pass.
|
|
363
|
+
const id = document.meta.id;
|
|
364
|
+
const reads = wholeReads.get(id) ?? 0;
|
|
365
|
+
if (reads >= maxWholeReads) {
|
|
366
|
+
throw new Error(maxWholeReads === 0
|
|
367
|
+
? `Whole-file reads are turned off for this question. Use search_document and read_document on ${document.meta.name}.`
|
|
368
|
+
: `${document.meta.name} was already read whole for this question${maxWholeReads > 1 ? ` ${maxWholeReads} times` : ""}, and is not read whole again. Use the answer of that read, or search_document and read_document for the details.`);
|
|
369
|
+
}
|
|
370
|
+
wholeReads.set(id, reads + 1);
|
|
371
|
+
let result;
|
|
372
|
+
try {
|
|
373
|
+
result = await analyzeWholeDocument({
|
|
374
|
+
document,
|
|
375
|
+
task,
|
|
376
|
+
generate: options.generate,
|
|
377
|
+
budget: options.budget,
|
|
378
|
+
onProgress: options.onProgress,
|
|
379
|
+
signal: options.signal,
|
|
380
|
+
...(options.retry ? { retry: options.retry } : {}),
|
|
381
|
+
});
|
|
382
|
+
} catch (error) {
|
|
383
|
+
// Refused before any model call: that was no read.
|
|
384
|
+
if (error instanceof TooManyPartsError) wholeReads.set(id, reads);
|
|
385
|
+
throw error;
|
|
386
|
+
}
|
|
331
387
|
const notesCutShort = result.truncatedParts + result.truncatedMerges;
|
|
332
388
|
return fit({
|
|
333
389
|
document: document.meta.name,
|
|
@@ -338,12 +394,12 @@ export function createDocumentTools(options: {
|
|
|
338
394
|
...(result.answerTruncated ? { answer_cut_short: true } : {}),
|
|
339
395
|
...(notesCutShort || result.answerTruncated ? { note: INCOMPLETE_ANALYSIS } : {}),
|
|
340
396
|
answer: result.answer,
|
|
341
|
-
}, null, Math.max(
|
|
397
|
+
}, null, limitOf(limits, Math.max(cap, ANALYSIS_RESULT_CHARACTERS)));
|
|
342
398
|
},
|
|
343
399
|
};
|
|
344
400
|
|
|
345
401
|
/** `view_pages`: the pages as one small PDF, next to a short JSON result. */
|
|
346
|
-
async function viewPages(args: Record<string, unknown>, limits:
|
|
402
|
+
async function viewPages(args: Record<string, unknown>, limits: ToolCallLimits): Promise<ToolOutput> {
|
|
347
403
|
const id = text(args.document_id, "document_id");
|
|
348
404
|
// The same scope check as the text tools, on its own list: a PDF can be looked at without
|
|
349
405
|
// being searchable, and the other way round.
|
|
@@ -394,13 +450,13 @@ export function createDocumentTools(options: {
|
|
|
394
450
|
// What a tool could not do goes to the model, and from there to a user's screen: never a server path.
|
|
395
451
|
const failure = (error: unknown): ToolResult => ({ error: safeErrorMessage(error) });
|
|
396
452
|
|
|
397
|
-
async function execute(name: string, args: Record<string, unknown
|
|
453
|
+
async function execute(name: string, args: Record<string, unknown>, limits: ToolCallLimits = {}): Promise<ToolResult> {
|
|
398
454
|
if (!known.has(name)) return { error: `Unknown tool ${name}.` };
|
|
399
455
|
// The pages are a file, and this method returns only JSON. Saying that pages are attached
|
|
400
456
|
// with nothing attached would be worse than saying that they could not be shown.
|
|
401
457
|
if (name === TOOL_NAMES.view) return { error: FILES_NOT_DELIVERED };
|
|
402
458
|
try {
|
|
403
|
-
return await handlers[name]!(args);
|
|
459
|
+
return await handlers[name]!(args, limits);
|
|
404
460
|
} catch (error) {
|
|
405
461
|
if (options.signal?.aborted) throw error;
|
|
406
462
|
return failure(error);
|
|
@@ -410,9 +466,10 @@ export function createDocumentTools(options: {
|
|
|
410
466
|
return {
|
|
411
467
|
declarations,
|
|
412
468
|
has: (name) => known.has(name),
|
|
413
|
-
execute,
|
|
469
|
+
execute: (name, args) => execute(name, args),
|
|
470
|
+
resultCharacters: (name) => (name === TOOL_NAMES.analyze ? Math.max(cap, ANALYSIS_RESULT_CHARACTERS) : name === TOOL_NAMES.view ? LEAST_RESULT_CHARACTERS : cap),
|
|
414
471
|
async executeWithFiles(name, args, limits = {}) {
|
|
415
|
-
if (name !== TOOL_NAMES.view || !known.has(name)) return { result: await execute(name, args), files: [] };
|
|
472
|
+
if (name !== TOOL_NAMES.view || !known.has(name)) return { result: await execute(name, args, limits), files: [] };
|
|
416
473
|
try {
|
|
417
474
|
return await viewPages(args, limits);
|
|
418
475
|
} catch (error) {
|
package/src/types.ts
CHANGED
|
@@ -172,8 +172,8 @@ export type ToolFile = {
|
|
|
172
172
|
/** A tool's JSON result, and the files that belong to it. Most tools return no files. */
|
|
173
173
|
export type ToolOutput = { result: ToolResult; files: ToolFile[] };
|
|
174
174
|
|
|
175
|
-
/** What
|
|
176
|
-
export type
|
|
175
|
+
/** What one tool call is allowed to use of the request its result will be sent in. */
|
|
176
|
+
export type ToolCallLimits = {
|
|
177
177
|
/**
|
|
178
178
|
* The most bytes the files of this call may have together. Give the room left in your request,
|
|
179
179
|
* times 3/4 when files are sent as base64. Defaults to about a third of `maxRequestBytes`.
|
|
@@ -181,7 +181,15 @@ export type ToolFileLimits = {
|
|
|
181
181
|
maxFileBytes?: number;
|
|
182
182
|
/** The most pages this call may show. Lower it as the pages already shown use up your token budget. */
|
|
183
183
|
maxPages?: number;
|
|
184
|
+
/**
|
|
185
|
+
* The most characters the JSON result of this call may have, when that is less than the tool's
|
|
186
|
+
* own cap (`toolResultCharacters`): the room left in the request. The result is cut to it, and
|
|
187
|
+
* says where to go on.
|
|
188
|
+
*/
|
|
189
|
+
maxResultCharacters?: number;
|
|
184
190
|
};
|
|
191
|
+
/** The name of `ToolCallLimits` before 0.5.0. */
|
|
192
|
+
export type ToolFileLimits = ToolCallLimits;
|
|
185
193
|
|
|
186
194
|
export type ToolSet = {
|
|
187
195
|
declarations: ToolDeclaration[];
|
|
@@ -195,11 +203,19 @@ export type ToolSet = {
|
|
|
195
203
|
* Runs a tool call and also returns the files it produced, to be sent to the model with the
|
|
196
204
|
* result. Use it in place of `execute` in a loop that can send files.
|
|
197
205
|
*/
|
|
198
|
-
executeWithFiles(name: string, args: Record<string, unknown>, limits?:
|
|
206
|
+
executeWithFiles(name: string, args: Record<string, unknown>, limits?: ToolCallLimits): Promise<ToolOutput>;
|
|
199
207
|
/** A short, human-readable line describing a call, for progress UIs. */
|
|
200
208
|
describe(name: string, args: Record<string, unknown>): string;
|
|
209
|
+
/**
|
|
210
|
+
* The most characters the JSON result of a tool can have: what a loop sets aside in its request
|
|
211
|
+
* before it runs a call.
|
|
212
|
+
*/
|
|
213
|
+
resultCharacters(name: string): number;
|
|
201
214
|
};
|
|
202
215
|
|
|
216
|
+
/** Tokens one model request used, as far as the provider said. */
|
|
217
|
+
export type GenerateUsage = { inputTokens?: number; cachedInputTokens?: number; outputTokens?: number; thoughtTokens?: number };
|
|
218
|
+
|
|
203
219
|
/** A plain text completion. The package stays provider-neutral by taking this as a function. */
|
|
204
220
|
export type GenerateText = (request: {
|
|
205
221
|
system: string;
|
|
@@ -212,6 +228,11 @@ export type GenerateText = (request: {
|
|
|
212
228
|
* as before, without that warning.
|
|
213
229
|
*/
|
|
214
230
|
onTruncated?: () => void;
|
|
231
|
+
/**
|
|
232
|
+
* Call this once for every request that was answered, with the tokens it used, so that the cost
|
|
233
|
+
* of a whole-document read is counted. Optional: without it those requests are not in the totals.
|
|
234
|
+
*/
|
|
235
|
+
onUsage?: (usage: GenerateUsage) => void;
|
|
215
236
|
}) => Promise<string>;
|
|
216
237
|
|
|
217
238
|
export type ProgressEvent = {
|