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/src/map-reduce.ts
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
|
+
import { safeErrorMessage } from "./errors.js";
|
|
2
|
+
import { until } from "./http.js";
|
|
3
|
+
import { classifyModelError, errorKindOf, type ModelErrorKind } from "./model.js";
|
|
4
|
+
import { noTextReason } from "./output-limit.js";
|
|
5
|
+
import { statusOf, withRetry, type RetryOptions } from "./retry.js";
|
|
1
6
|
import { estimateTokens, jsonBytes } from "./text.js";
|
|
2
7
|
import { numberLines, scanSource, SearchableDocument, type DocumentSource, type TextChunk } from "./search.js";
|
|
3
|
-
import type { Budget, GenerateText, ProgressListener } from "./types.js";
|
|
8
|
+
import type { Budget, GenerateText, GenerateUsage, ProgressListener, ToolCallHooks, ToolRequestStart } from "./types.js";
|
|
4
9
|
|
|
5
10
|
const NOTHING = "NOTHING RELEVANT";
|
|
6
11
|
const PART_OUTPUT_TOKENS = 4_096;
|
|
@@ -18,8 +23,123 @@ export type WholeDocumentResult = {
|
|
|
18
23
|
truncatedMerges: number;
|
|
19
24
|
/** The final answer stopped at the output limit. */
|
|
20
25
|
answerTruncated: boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Why the last step, which writes one answer from the notes, failed. `answer` is then the notes
|
|
28
|
+
* themselves: every part was paid for, and they hold what was found, with line citations.
|
|
29
|
+
*/
|
|
30
|
+
answerFailed?: string;
|
|
21
31
|
};
|
|
22
32
|
|
|
33
|
+
/**
|
|
34
|
+
* What went wrong with a model request, by its kind, in words for the model that asked for the
|
|
35
|
+
* read. The request may be a part, a merge of notes, or the last step that writes the answer.
|
|
36
|
+
*/
|
|
37
|
+
const FAILED_BECAUSE: Record<ModelErrorKind, string> = {
|
|
38
|
+
context_overflow: "The request was larger than the model takes",
|
|
39
|
+
quota: "The model's quota has run out",
|
|
40
|
+
rate_limit: "The model was busy",
|
|
41
|
+
timeout: "The model took too long to answer",
|
|
42
|
+
unreachable: "The model could not be reached",
|
|
43
|
+
server: "The model failed on its side",
|
|
44
|
+
auth: "The model refused the key or token it was sent",
|
|
45
|
+
invalid: "The model refused the request",
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const knownKind = (kind: unknown): kind is ModelErrorKind => typeof kind === "string" && Object.hasOwn(FAILED_BECAUSE, kind);
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The HTTP status of a model error: its `status`, or the `statusCode` or `response.status` that
|
|
52
|
+
* the errors of other HTTP clients and SDKs carry (got, http-errors, axios). 0 is a request that
|
|
53
|
+
* got no answer. A number that is no HTTP status is not one.
|
|
54
|
+
*/
|
|
55
|
+
function httpStatusOf(error: unknown): number | undefined {
|
|
56
|
+
const other = error as { statusCode?: unknown; response?: { status?: unknown } | null } | null | undefined;
|
|
57
|
+
for (const status of [statusOf(error), other?.statusCode, other?.response?.status]) {
|
|
58
|
+
if (typeof status === "number" && Number.isInteger(status) && (status === 0 || (status >= 100 && status <= 599))) return status;
|
|
59
|
+
}
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The codes of a connection that failed, Node's and undici's, and their kind. An answer that did
|
|
65
|
+
* not come in time is a timeout.
|
|
66
|
+
*/
|
|
67
|
+
const CONNECTION_FAILURES: Record<string, ModelErrorKind> = {
|
|
68
|
+
ECONNREFUSED: "unreachable",
|
|
69
|
+
ECONNRESET: "unreachable",
|
|
70
|
+
ECONNABORTED: "unreachable",
|
|
71
|
+
ENOTFOUND: "unreachable",
|
|
72
|
+
EAI_AGAIN: "unreachable",
|
|
73
|
+
ETIMEDOUT: "unreachable",
|
|
74
|
+
EHOSTUNREACH: "unreachable",
|
|
75
|
+
ENETUNREACH: "unreachable",
|
|
76
|
+
ENETDOWN: "unreachable",
|
|
77
|
+
EPIPE: "unreachable",
|
|
78
|
+
UND_ERR_CONNECT_TIMEOUT: "unreachable",
|
|
79
|
+
UND_ERR_SOCKET: "unreachable",
|
|
80
|
+
UND_ERR_CLOSED: "unreachable",
|
|
81
|
+
UND_ERR_DESTROYED: "unreachable",
|
|
82
|
+
UND_ERR_HEADERS_TIMEOUT: "timeout",
|
|
83
|
+
UND_ERR_BODY_TIMEOUT: "timeout",
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The kind of a connection that failed, from the code of the error or of one that caused it (the
|
|
88
|
+
* `fetch failed` of undici). An `AbortSignal.timeout` of the app's (a `TimeoutError`) is a timeout.
|
|
89
|
+
* Undefined for any other error.
|
|
90
|
+
*/
|
|
91
|
+
function connectionFailure(error: unknown): ModelErrorKind | undefined {
|
|
92
|
+
let at = error;
|
|
93
|
+
for (let depth = 0; depth < 4 && typeof at === "object" && at !== null; depth++) {
|
|
94
|
+
const { code, name, cause } = at as { code?: unknown; name?: unknown; cause?: unknown };
|
|
95
|
+
if (typeof code === "string" && Object.hasOwn(CONNECTION_FAILURES, code)) return CONNECTION_FAILURES[code];
|
|
96
|
+
if (name === "TimeoutError") return "timeout";
|
|
97
|
+
at = cause;
|
|
98
|
+
}
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** A reason a provider gives for a reply with no text that is a plain word ("SAFETY", "content_filter"). */
|
|
103
|
+
const PLAIN_REASON = /^[A-Za-z_]{1,40}$/;
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Why a model request of a whole-file read failed, as the model and `onStep` are told: by its
|
|
107
|
+
* kind, its HTTP status, or the code of a connection that failed, never by its message. The
|
|
108
|
+
* provider's message, or the HTTP client's, can name a project, a host, a key or a URL of the
|
|
109
|
+
* server, and goes to the log of the app, not to the model. An error with an HTTP status and no
|
|
110
|
+
* kind (that of a provider's SDK, in a `generate` of the app's own) has its kind told from its
|
|
111
|
+
* status and message. An error with none of these is told as a request that failed. A reply with
|
|
112
|
+
* no text to a part reader of the package's is told in the package's words, as before.
|
|
113
|
+
*/
|
|
114
|
+
export function modelFailureReason(error: unknown): string {
|
|
115
|
+
try {
|
|
116
|
+
const noText = noTextReason(error);
|
|
117
|
+
if (noText !== undefined) return `The model returned no text${PLAIN_REASON.test(noText) ? ` (${noText})` : ""}.`;
|
|
118
|
+
const status = httpStatusOf(error);
|
|
119
|
+
let kind: unknown = errorKindOf(error);
|
|
120
|
+
if (!knownKind(kind) && status !== undefined && (status === 0 || status >= 400)) {
|
|
121
|
+
const code = (error as { code?: unknown } | null)?.code;
|
|
122
|
+
kind = classifyModelError(status, error instanceof Error ? error.message : "", { code: typeof code === "string" ? code : undefined }).kind;
|
|
123
|
+
}
|
|
124
|
+
if (!knownKind(kind)) kind = connectionFailure(error);
|
|
125
|
+
if (!knownKind(kind)) return `The model request failed${status ? ` (HTTP ${status})` : ""}.`;
|
|
126
|
+
// A reply that came with a status of success, and could not be read (a gateway's page).
|
|
127
|
+
if (kind === "invalid" && status !== undefined && status >= 200 && status < 300) return `The model's reply could not be read (HTTP ${status}).`;
|
|
128
|
+
return `${FAILED_BECAUSE[kind]}${status ? ` (HTTP ${status})` : ""}.`;
|
|
129
|
+
} catch {
|
|
130
|
+
// An error whose fields throw when read (a getter, a proxy): their words are not told either.
|
|
131
|
+
return "The model request failed.";
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** A whole-document read in which no part could be read: nothing was learned, and nothing is returned. */
|
|
136
|
+
export class NothingReadError extends Error {
|
|
137
|
+
constructor(name: string, readonly reason: string) {
|
|
138
|
+
super(`Could not read any part of ${name}: ${reason}`);
|
|
139
|
+
this.name = "NothingReadError";
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
23
143
|
type Parts = Array<{ from: number; to: number }>;
|
|
24
144
|
|
|
25
145
|
/**
|
|
@@ -114,26 +234,60 @@ async function pool<T>(count: number, concurrency: number, run: (index: number)
|
|
|
114
234
|
return results;
|
|
115
235
|
}
|
|
116
236
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
237
|
+
/** A whole-document read that was refused before any model call: the document has too many parts. */
|
|
238
|
+
export class TooManyPartsError extends Error {
|
|
239
|
+
constructor(name: string, readonly parts: number, readonly limit: number) {
|
|
240
|
+
super(`Reading all of ${name} needs ${parts} model calls, over the limit of ${limit}. Use search_document to narrow the question first.`);
|
|
241
|
+
this.name = "TooManyPartsError";
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Two reports of usage as one. */
|
|
246
|
+
function addUsage(sum: GenerateUsage | undefined, used: GenerateUsage): GenerateUsage {
|
|
247
|
+
const out: GenerateUsage = { ...sum };
|
|
248
|
+
for (const key of ["inputTokens", "cachedInputTokens", "outputTokens", "thoughtTokens"] as const) {
|
|
249
|
+
if (typeof used[key] === "number") out[key] = (out[key] ?? 0) + used[key];
|
|
123
250
|
}
|
|
251
|
+
return out;
|
|
124
252
|
}
|
|
125
253
|
|
|
126
|
-
/**
|
|
254
|
+
/** Who is told of each model request of a read (`ToolCallHooks.onRequest`), and what the request is. */
|
|
255
|
+
type Told = { onRequest: NonNullable<ToolCallHooks["onRequest"]>; start: ToolRequestStart };
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* One model call. A model that was busy or failed on its side (an error with an HTTP status worth
|
|
259
|
+
* retrying) is asked again after a wait, a few times; a request it refused is not. An error that
|
|
260
|
+
* says nothing of the kind is tried once more, at once. `truncated` is true when the reply that
|
|
261
|
+
* was kept hit the output limit. When the signal aborts, the call ends with its reason, whether or
|
|
262
|
+
* not the part reader stops. `told` hears when the request starts, each retry, and how it ended,
|
|
263
|
+
* with the usage its part reader reported.
|
|
264
|
+
*/
|
|
127
265
|
async function ask(
|
|
128
266
|
generate: GenerateText,
|
|
129
267
|
request: { system: string; prompt: string; maxOutputTokens: number },
|
|
130
268
|
signal: AbortSignal | undefined,
|
|
269
|
+
retry: RetryOptions | undefined,
|
|
270
|
+
told?: Told,
|
|
131
271
|
): Promise<{ text: string; truncated: boolean }> {
|
|
132
272
|
let truncated = false;
|
|
133
|
-
const
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
273
|
+
const handle = told?.onRequest(told.start);
|
|
274
|
+
let usage: GenerateUsage | undefined;
|
|
275
|
+
const onUsage = handle && ((used: GenerateUsage) => {
|
|
276
|
+
usage = addUsage(usage, used);
|
|
277
|
+
});
|
|
278
|
+
let text: string;
|
|
279
|
+
try {
|
|
280
|
+
text = await withRetry(() => {
|
|
281
|
+
truncated = false;
|
|
282
|
+
// Nothing is sent once the read was stopped: the signal may abort while a part's lines are read.
|
|
283
|
+
signal?.throwIfAborted();
|
|
284
|
+
return until(generate({ ...request, ...(signal ? { signal } : {}), onTruncated: () => { truncated = true; }, ...(onUsage ? { onUsage } : {}) }), signal);
|
|
285
|
+
}, { retry, signal, unknownErrors: "once", ...(handle ? { onRetry: (notice) => handle.retry(notice) } : {}) });
|
|
286
|
+
} catch (error) {
|
|
287
|
+
handle?.end({ outcome: "error", ...(usage ? { usage } : {}), error });
|
|
288
|
+
throw error;
|
|
289
|
+
}
|
|
290
|
+
handle?.end({ outcome: "ok", ...(usage ? { usage } : {}) });
|
|
137
291
|
return { text: text.trim(), truncated };
|
|
138
292
|
}
|
|
139
293
|
|
|
@@ -147,32 +301,73 @@ export async function analyzeWholeDocument(options: {
|
|
|
147
301
|
generate: GenerateText;
|
|
148
302
|
budget: Budget;
|
|
149
303
|
onProgress?: ProgressListener;
|
|
304
|
+
/** Told of each model request of the read as it starts: see `ToolCallHooks.onRequest`. */
|
|
305
|
+
onRequest?: ToolCallHooks["onRequest"];
|
|
150
306
|
signal?: AbortSignal;
|
|
151
307
|
concurrency?: number;
|
|
308
|
+
/** How a model request that failed is sent again. See `RetryOptions`. */
|
|
309
|
+
retry?: RetryOptions;
|
|
310
|
+
/**
|
|
311
|
+
* The most model requests this read may make, when the question has a ceiling. A part read as two
|
|
312
|
+
* halves takes one more than planned: it is halved only while this allows it.
|
|
313
|
+
*/
|
|
314
|
+
maxRequests?: number;
|
|
152
315
|
}): Promise<WholeDocumentResult> {
|
|
153
|
-
const { document, task, generate, budget, onProgress, signal } = options;
|
|
316
|
+
const { document, task, generate, budget, onProgress, onRequest, signal, retry } = options;
|
|
317
|
+
/** What `ask` tells of a request of this read, when anyone listens. */
|
|
318
|
+
const told = (purpose: ToolRequestStart["purpose"], detail: string): Told | undefined => (onRequest ? { onRequest, start: { purpose, detail } } : undefined);
|
|
154
319
|
const name = document.meta.name;
|
|
155
320
|
const parts = await partsOf(document, budget, signal);
|
|
156
|
-
if (parts.length > budget.maxMapChunks)
|
|
157
|
-
throw new Error(`Reading all of ${name} needs ${parts.length} model calls, over the limit of ${budget.maxMapChunks}. Use search_document to narrow the question first.`);
|
|
158
|
-
}
|
|
321
|
+
if (parts.length > budget.maxMapChunks) throw new TooManyPartsError(name, parts.length, budget.maxMapChunks);
|
|
159
322
|
|
|
160
323
|
let done = 0;
|
|
161
324
|
let failed = 0;
|
|
162
325
|
let firstFailure = "";
|
|
326
|
+
let firstError: unknown;
|
|
327
|
+
/** Parts whose text was read and sent to the model: with none, no model request was made. */
|
|
328
|
+
let sent = 0;
|
|
163
329
|
let truncatedParts = 0;
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
330
|
+
type Note = { from: number; to: number; text: string; read: boolean };
|
|
331
|
+
/**
|
|
332
|
+
* Parts that may be read as two halves. Each takes one request more than planned, and makes one
|
|
333
|
+
* part more: the parts stay within `maxMapChunks`, and the requests (the parts, a merge, the
|
|
334
|
+
* answer) within `maxRequests`.
|
|
335
|
+
*/
|
|
336
|
+
let halvings = Math.max(0, Math.min(
|
|
337
|
+
budget.maxMapChunks - parts.length,
|
|
338
|
+
options.maxRequests === undefined ? Number.POSITIVE_INFINITY : options.maxRequests - parts.length - 2,
|
|
339
|
+
));
|
|
340
|
+
/** The note on a part that could not be read, and why. */
|
|
341
|
+
const failedPart = (from: number, to: number, error: unknown, reason: string): Note[] => {
|
|
342
|
+
failed++;
|
|
343
|
+
if (!firstFailure) {
|
|
344
|
+
firstFailure = reason;
|
|
345
|
+
firstError = error;
|
|
346
|
+
}
|
|
347
|
+
return [{ from, to, text: `[This part could not be read: ${reason}]`, read: false }];
|
|
348
|
+
};
|
|
349
|
+
/**
|
|
350
|
+
* The notes on one part. A part the model refuses as larger than it takes (its window is smaller
|
|
351
|
+
* than the budget says) is read as two halves instead, once: a half that is still too large is
|
|
352
|
+
* reported as a part that could not be read.
|
|
353
|
+
*/
|
|
354
|
+
const readPart = async (from: number, to: number, where: string, halved: boolean, detail: string): Promise<Note[]> => {
|
|
355
|
+
let part: string;
|
|
356
|
+
try {
|
|
357
|
+
part = numberLines(await document.readLines(from, to), from);
|
|
358
|
+
} catch (error) {
|
|
359
|
+
if (signal?.aborted) throw error;
|
|
360
|
+
// The store's error, not the model's: a `DocumentStoreError` tells it in words safe to show.
|
|
361
|
+
return failedPart(from, to, error, safeErrorMessage(error));
|
|
362
|
+
}
|
|
363
|
+
sent++;
|
|
168
364
|
try {
|
|
169
|
-
const part = numberLines(await document.readLines(from, to), from);
|
|
170
365
|
const reply = await ask(generate, {
|
|
171
366
|
system: "You read one part of a larger document and take notes for a later step that combines the notes from every part.",
|
|
172
367
|
prompt: [
|
|
173
368
|
`Task: ${task}`,
|
|
174
369
|
"",
|
|
175
|
-
`Document: ${name},
|
|
370
|
+
`Document: ${name}, ${where}, lines ${from}-${to}.`,
|
|
176
371
|
`Write concise notes on everything in this part that is relevant to the task. Keep exact names, numbers, and quotes that matter. Cite line numbers like (L123). If nothing in this part is relevant, reply exactly: ${NOTHING}`,
|
|
177
372
|
"",
|
|
178
373
|
"<part>",
|
|
@@ -180,34 +375,46 @@ export async function analyzeWholeDocument(options: {
|
|
|
180
375
|
"</part>",
|
|
181
376
|
].join("\n"),
|
|
182
377
|
maxOutputTokens: PART_OUTPUT_TOKENS,
|
|
183
|
-
}, signal);
|
|
184
|
-
text = reply.text;
|
|
378
|
+
}, signal, retry, told("part", detail));
|
|
379
|
+
let text = reply.text;
|
|
185
380
|
if (reply.truncated) {
|
|
186
381
|
truncatedParts++;
|
|
187
|
-
text += "\n[These notes were cut off at the output limit. This part has more relevant content than is listed here.]";
|
|
382
|
+
text += "\n[These notes were cut off before their end, at the output limit or by the provider. This part has more relevant content than is listed here.]";
|
|
188
383
|
}
|
|
384
|
+
return [{ from, to, text, read: true }];
|
|
189
385
|
} catch (error) {
|
|
190
386
|
if (signal?.aborted) throw error;
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
387
|
+
if (!halved && to > from && errorKindOf(error) === "context_overflow" && halvings > 0) {
|
|
388
|
+
halvings--;
|
|
389
|
+
const middle = Math.floor((from + to) / 2);
|
|
390
|
+
return [
|
|
391
|
+
...await readPart(from, middle, `${where}, first half`, true, `first half of ${detail}`),
|
|
392
|
+
...await readPart(middle + 1, to, `${where}, second half`, true, `second half of ${detail}`),
|
|
393
|
+
];
|
|
394
|
+
}
|
|
395
|
+
return failedPart(from, to, error, modelFailureReason(error));
|
|
196
396
|
}
|
|
397
|
+
};
|
|
398
|
+
const notes = (await pool(parts.length, options.concurrency ?? 4, async (index) => {
|
|
399
|
+
const { from, to } = parts[index]!;
|
|
400
|
+
const where = `part ${index + 1} of ${parts.length}`;
|
|
401
|
+
const read = await readPart(from, to, where, false, where);
|
|
197
402
|
done++;
|
|
198
403
|
onProgress?.({ kind: "map", message: `Reading ${name}: part ${done} of ${parts.length}`, done, total: parts.length });
|
|
199
|
-
return
|
|
200
|
-
}, signal);
|
|
404
|
+
return read;
|
|
405
|
+
}, signal)).flat();
|
|
201
406
|
|
|
202
|
-
// Nothing was read at all: an answer written from here would be invented.
|
|
203
|
-
|
|
407
|
+
// Nothing was read at all: an answer written from here would be invented. When not one part
|
|
408
|
+
// could even be read from the store, no model request was made: that is the store's failure,
|
|
409
|
+
// and the read can be asked for again.
|
|
410
|
+
if (failed === notes.length) throw sent === 0 && firstError !== undefined ? firstError : new NothingReadError(name, firstFailure);
|
|
204
411
|
|
|
205
412
|
const relevant = notes.filter((note) => !saysNothingRelevant(note.text));
|
|
206
413
|
const relevantParts = relevant.filter((note) => note.read).length;
|
|
207
414
|
if (relevantParts === 0) {
|
|
208
415
|
return {
|
|
209
|
-
answer: `No part of ${name} contained anything relevant to: ${task}${failed ? ` (${failed} of ${
|
|
210
|
-
parts:
|
|
416
|
+
answer: `No part of ${name} contained anything relevant to: ${task}${failed ? ` (${failed} of ${notes.length} parts could not be read.)` : ""}`,
|
|
417
|
+
parts: notes.length,
|
|
211
418
|
relevantParts: 0,
|
|
212
419
|
failedParts: failed,
|
|
213
420
|
truncatedParts,
|
|
@@ -252,7 +459,7 @@ export async function analyzeWholeDocument(options: {
|
|
|
252
459
|
system: "You merge partial notes about a document into shorter notes, keeping every relevant fact and line citation.",
|
|
253
460
|
prompt: `Task: ${task}\n\nMerge these notes from ${name} into one set of notes. Keep line citations.\n\n${batch}`,
|
|
254
461
|
maxOutputTokens: PART_OUTPUT_TOKENS,
|
|
255
|
-
}, signal);
|
|
462
|
+
}, signal, retry, told("merge", `round ${round}: ${index + 1} of ${batches.length}`));
|
|
256
463
|
if (reply.truncated) truncatedMerges++;
|
|
257
464
|
merged = reply.truncated ? `${reply.text}\n[These merged notes were cut off at the output limit.]` : reply.text;
|
|
258
465
|
} catch (error) {
|
|
@@ -271,26 +478,26 @@ export async function analyzeWholeDocument(options: {
|
|
|
271
478
|
|
|
272
479
|
onProgress?.({ kind: "reduce", message: `Writing the answer from ${relevantParts} relevant parts of ${name}`, done: 0, total: 1 });
|
|
273
480
|
const cutShort = truncatedParts + truncatedMerges;
|
|
274
|
-
const
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
"",
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
};
|
|
481
|
+
const counts = { parts: notes.length, relevantParts, failedParts: failed, truncatedParts, truncatedMerges };
|
|
482
|
+
let final: { text: string; truncated: boolean };
|
|
483
|
+
try {
|
|
484
|
+
final = await ask(generate, {
|
|
485
|
+
system: "You write a complete answer from notes taken across every part of a document.",
|
|
486
|
+
prompt: [
|
|
487
|
+
`Task: ${task}`,
|
|
488
|
+
"",
|
|
489
|
+
`These notes cover all ${notes.length} parts of ${name}${failed ? ` (${failed} part(s) could not be read)` : ""}. Parts with nothing relevant are omitted.`,
|
|
490
|
+
...(cutShort ? [`Some notes were cut off at the output limit (they say so), so the notes are incomplete. Say in the answer that it is incomplete.`] : []),
|
|
491
|
+
"Write one complete answer to the task from them. Keep line citations. Point out contradictions or gaps.",
|
|
492
|
+
"",
|
|
493
|
+
layer.join("\n\n"),
|
|
494
|
+
].join("\n"),
|
|
495
|
+
maxOutputTokens: FINAL_OUTPUT_TOKENS,
|
|
496
|
+
}, signal, retry, told("final", "the answer"));
|
|
497
|
+
} catch (error) {
|
|
498
|
+
if (signal?.aborted) throw error;
|
|
499
|
+
// The notes of every part were paid for and hold what was found: they are the answer, rather than an error.
|
|
500
|
+
return { answer: layer.join("\n\n"), ...counts, answerTruncated: false, answerFailed: modelFailureReason(error) };
|
|
501
|
+
}
|
|
502
|
+
return { answer: final.text, ...counts, answerTruncated: final.truncated };
|
|
296
503
|
}
|