llm-large-files 0.9.0 → 0.10.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 +446 -0
- package/README.md +13 -7
- package/dist/access.d.ts +45 -3
- package/dist/access.d.ts.map +1 -1
- package/dist/access.js +106 -3
- package/dist/access.js.map +1 -1
- package/dist/aggregate.d.ts +6 -0
- package/dist/aggregate.d.ts.map +1 -1
- package/dist/aggregate.js +86 -13
- package/dist/aggregate.js.map +1 -1
- package/dist/analyze.d.ts +4 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +2 -2
- package/dist/analyze.js.map +1 -1
- package/dist/answer-info.d.ts +26 -0
- package/dist/answer-info.d.ts.map +1 -0
- package/dist/answer-info.js +32 -0
- package/dist/answer-info.js.map +1 -0
- package/dist/anthropic/adapter.d.ts +5 -1
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +35 -10
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +115 -14
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +572 -103
- package/dist/ask.js.map +1 -1
- package/dist/citations.d.ts +36 -0
- package/dist/citations.d.ts.map +1 -0
- package/dist/citations.js +291 -0
- package/dist/citations.js.map +1 -0
- package/dist/error-info.d.ts +13 -0
- package/dist/error-info.d.ts.map +1 -1
- package/dist/error-info.js +37 -1
- package/dist/error-info.js.map +1 -1
- package/dist/errors.d.ts +3 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +3 -1
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +25 -7
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +21 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +6 -1
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +35 -4
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +68 -29
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +28 -55
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +20 -27
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +59 -11
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +33 -7
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/errors.d.ts +39 -5
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +70 -9
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +53 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +100 -50
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/http.d.ts +41 -3
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +40 -2
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +6 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +9 -1
- package/dist/ingest.d.ts.map +1 -1
- package/dist/ingest.js +50 -25
- package/dist/ingest.js.map +1 -1
- package/dist/library.d.ts +129 -2
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +224 -149
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +176 -10
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +804 -58
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +36 -4
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +17 -1
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +29 -8
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +148 -126
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +1 -1
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.js +2 -2
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/spool.d.ts +9 -5
- package/dist/node/spool.d.ts.map +1 -1
- package/dist/node/spool.js +28 -15
- package/dist/node/spool.js.map +1 -1
- package/dist/node/sse.d.ts +6 -5
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +8 -7
- package/dist/node/sse.js.map +1 -1
- package/dist/openai/adapter.d.ts +5 -1
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +53 -12
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +2 -1
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +5 -2
- package/dist/output-limit.js.map +1 -1
- package/dist/pdf-outline.d.ts +71 -0
- package/dist/pdf-outline.d.ts.map +1 -0
- package/dist/pdf-outline.js +414 -0
- package/dist/pdf-outline.js.map +1 -0
- package/dist/plan.d.ts +137 -7
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +248 -26
- package/dist/plan.js.map +1 -1
- package/dist/prepare.d.ts +50 -0
- package/dist/prepare.d.ts.map +1 -0
- package/dist/prepare.js +207 -0
- package/dist/prepare.js.map +1 -0
- package/dist/ranged.d.ts +2 -1
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +16 -3
- package/dist/ranged.js.map +1 -1
- package/dist/search.d.ts +7 -0
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +72 -10
- package/dist/search.js.map +1 -1
- package/dist/stores.d.ts +6 -0
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +82 -11
- package/dist/stores.js.map +1 -1
- package/dist/tools.d.ts +22 -2
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +323 -76
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +49 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/whole-cost.d.ts +37 -0
- package/dist/whole-cost.d.ts.map +1 -0
- package/dist/whole-cost.js +46 -0
- package/dist/whole-cost.js.map +1 -0
- package/docs/README.md +4 -0
- package/docs/guides/anthropic.md +5 -2
- package/docs/guides/conversations.md +1 -1
- package/docs/guides/costs-and-limits.md +132 -36
- package/docs/guides/deployment.md +106 -13
- package/docs/guides/errors-and-reliability.md +157 -45
- package/docs/guides/explorer-model.md +4 -1
- package/docs/guides/openai-compatible.md +47 -7
- package/docs/guides/own-adapter-and-loop.md +33 -6
- package/docs/guides/pdfs.md +96 -7
- package/docs/guides/storage.md +46 -3
- package/docs/guides/testing.md +71 -0
- package/docs/guides/vertex-and-gemini.md +159 -50
- package/docs/guides/web-app.md +10 -6
- package/docs/how-it-works.md +120 -22
- package/docs/measurements.md +172 -5
- package/docs/publishing.md +76 -4
- package/docs/reference/anthropic.md +12 -7
- package/docs/reference/ask.md +262 -35
- package/docs/reference/errors-and-retries.md +30 -2
- package/docs/reference/events.md +27 -10
- package/docs/reference/gemini.md +184 -68
- package/docs/reference/library.md +190 -23
- package/docs/reference/node.md +51 -17
- package/docs/reference/openai.md +21 -10
- package/docs/reference/tools.md +271 -26
- package/docs/security.md +101 -12
- package/docs/troubleshooting.md +14 -12
- package/docs/upgrading-0.10.md +472 -0
- package/package.json +5 -1
- package/src/access.ts +127 -4
- package/src/aggregate.ts +92 -14
- package/src/analyze.ts +2 -2
- package/src/answer-info.ts +45 -0
- package/src/anthropic/adapter.ts +40 -11
- package/src/ask.ts +646 -106
- package/src/citations.ts +294 -0
- package/src/error-info.ts +36 -1
- package/src/errors.ts +3 -1
- package/src/events.ts +29 -6
- package/src/evidence.ts +21 -2
- package/src/extract.ts +6 -1
- package/src/gemini/adapter.ts +99 -32
- package/src/gemini/chat.ts +53 -82
- package/src/gemini/endpoints.ts +89 -16
- package/src/gemini/errors.ts +74 -11
- package/src/gemini/generate.ts +147 -57
- package/src/gemini/index.ts +3 -3
- package/src/http.ts +65 -4
- package/src/index.ts +6 -4
- package/src/ingest.ts +58 -27
- package/src/library.ts +336 -142
- package/src/map-reduce.ts +855 -67
- package/src/model.ts +44 -4
- package/src/node/handlers.ts +159 -118
- package/src/node/index.ts +1 -0
- package/src/node/ingest-child.ts +2 -2
- package/src/node/spool.ts +28 -14
- package/src/node/sse.ts +8 -7
- package/src/openai/adapter.ts +56 -13
- package/src/output-limit.ts +5 -2
- package/src/pdf-outline.ts +400 -0
- package/src/plan.ts +287 -36
- package/src/prepare.ts +253 -0
- package/src/ranged.ts +16 -3
- package/src/search.ts +69 -13
- package/src/stores.ts +76 -11
- package/src/tools.ts +327 -75
- package/src/types.ts +45 -1
- package/src/whole-cost.ts +64 -0
package/src/plan.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { pageList } from "./quality.js";
|
|
2
|
+
import { numberLines } from "./search.js";
|
|
2
3
|
import { plural, sliceWhole, wellFormed } from "./text.js";
|
|
3
|
-
import type { Budget, DocumentFormat, DocumentMeta, DocumentPlan, OutlineEntry } from "./types.js";
|
|
4
|
+
import type { Budget, DocumentFormat, DocumentMeta, DocumentPlan, OutlineEntry, PreparedContext, ToolName } from "./types.js";
|
|
4
5
|
|
|
5
6
|
/** Formats whose documents may hold a table that `aggregate_table` reads. */
|
|
6
7
|
export const TABLE_FORMATS: ReadonlySet<DocumentFormat> = new Set<DocumentFormat>(["csv", "xlsx", "docx", "pptx", "pdf", "html", "markdown"]);
|
|
@@ -10,29 +11,133 @@ export const REQUEST_BYTES_MARGIN = 256 * 1024;
|
|
|
10
11
|
const CARD_HEAD_LINES = 25;
|
|
11
12
|
const CARD_OUTLINE_ENTRIES = 40;
|
|
12
13
|
|
|
14
|
+
/**
|
|
15
|
+
* How planning places documents besides their size (`planDocuments`). New in 0.10.0: without it,
|
|
16
|
+
* the plan is that of 0.9.
|
|
17
|
+
*/
|
|
18
|
+
export type PlanOptions = {
|
|
19
|
+
/** Count each document at its size with its lines numbered (`numberedSize`), as it is then sent. */
|
|
20
|
+
numbered?: boolean;
|
|
21
|
+
/**
|
|
22
|
+
* The IDs of documents to place first, in this order, each while it fits. One that does not fit
|
|
23
|
+
* is searched, and leaves its room to the others. `prepare` does not pass it.
|
|
24
|
+
*/
|
|
25
|
+
pinned?: readonly string[];
|
|
26
|
+
/** The IDs of documents that stay searched, whatever their size. `prepare` does not pass it. */
|
|
27
|
+
cards?: readonly string[];
|
|
28
|
+
/**
|
|
29
|
+
* The size of each document's card, as rendered (`renderCard`). With it, the cards count against
|
|
30
|
+
* the room of the request with the documents sent whole: a document becomes a card only for room
|
|
31
|
+
* the move frees, so one whose card is no smaller than its text stays whole (within
|
|
32
|
+
* `budget.inlineTokens`), a pinned one included. Without it, as in 0.9, the cards are not counted.
|
|
33
|
+
* `prepare` does not pass it.
|
|
34
|
+
*/
|
|
35
|
+
cardSizes?: ReadonlyMap<string, Size>;
|
|
36
|
+
/**
|
|
37
|
+
* The size of the text of documents sent whole as it was read and rendered (with 200 bytes for
|
|
38
|
+
* its frame): a document is counted at the larger of this and its estimate (`inlineSize`).
|
|
39
|
+
* `prepare` gives it for numbered text, which the estimate from metadata can count short.
|
|
40
|
+
*/
|
|
41
|
+
measured?: ReadonlyMap<string, Size>;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
type Size = { tokens: number; bytes: number };
|
|
45
|
+
|
|
46
|
+
const NO_SIZE: Size = { tokens: 0, bytes: 0 };
|
|
47
|
+
|
|
13
48
|
/**
|
|
14
49
|
* Decides which documents go into the prompt in full and which the model reaches through
|
|
15
|
-
* tools. Smaller documents are inlined first, so as many as possible are read in full.
|
|
50
|
+
* tools. Smaller documents are inlined first, so as many as possible are read in full. Since
|
|
51
|
+
* 0.10.0, `options` can count them with their lines numbered or at their measured size, place some
|
|
52
|
+
* first or keep some searched, and count the cards (`PlanOptions`). Both lists are in order of
|
|
53
|
+
* size, smallest first, as before.
|
|
16
54
|
*/
|
|
17
55
|
export function planDocuments(
|
|
18
56
|
documents: DocumentMeta[],
|
|
19
57
|
budget: Budget,
|
|
20
58
|
base: { tokens: number; bytes: number },
|
|
59
|
+
options: PlanOptions = {},
|
|
21
60
|
): DocumentPlan {
|
|
22
|
-
const
|
|
61
|
+
const contextRoom = budget.contextTokens - budget.reservedTokens - base.tokens;
|
|
62
|
+
const tokenRoom = Math.min(budget.inlineTokens, contextRoom);
|
|
23
63
|
const byteRoom = budget.maxRequestBytes - REQUEST_BYTES_MARGIN - base.bytes;
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
64
|
+
const sorted = [...documents].sort((left, right) => left.estimatedTokens - right.estimatedTokens);
|
|
65
|
+
const pinned = new Set(options.pinned ?? []);
|
|
66
|
+
const cards = new Set((options.cards ?? []).filter((id) => !pinned.has(id)));
|
|
67
|
+
const numbered = options.numbered === true;
|
|
68
|
+
const cardSizes = options.cardSizes;
|
|
69
|
+
const inline = new Set<string>();
|
|
70
|
+
let tokens = 0;
|
|
71
|
+
let bytes = 0;
|
|
72
|
+
// With the cards counted: what the documents take of the request. A document not placed yet
|
|
73
|
+
// counts at the smaller of its text and its card, and a card of an earlier question at its card.
|
|
74
|
+
const used = { ...NO_SIZE };
|
|
75
|
+
const sizeOf = (meta: DocumentMeta) => inlineSize(meta, numbered, options.measured?.get(meta.id));
|
|
76
|
+
const lower = (meta: DocumentMeta) => {
|
|
77
|
+
const size = sizeOf(meta);
|
|
78
|
+
const card = cardSizes?.get(meta.id) ?? NO_SIZE;
|
|
79
|
+
return { tokens: Math.min(size.tokens, card.tokens), bytes: Math.min(size.bytes, card.bytes) };
|
|
80
|
+
};
|
|
81
|
+
if (cardSizes) {
|
|
82
|
+
for (const meta of documents) {
|
|
83
|
+
const counted = cards.has(meta.id) ? cardSizes.get(meta.id) ?? NO_SIZE : lower(meta);
|
|
84
|
+
used.tokens += counted.tokens;
|
|
85
|
+
used.bytes += counted.bytes;
|
|
33
86
|
}
|
|
34
87
|
}
|
|
35
|
-
|
|
88
|
+
const place = (meta: DocumentMeta) => {
|
|
89
|
+
const size = sizeOf(meta);
|
|
90
|
+
if (!cardSizes) {
|
|
91
|
+
if (tokens + size.tokens <= tokenRoom && bytes + size.bytes <= byteRoom) {
|
|
92
|
+
inline.add(meta.id);
|
|
93
|
+
tokens += size.tokens;
|
|
94
|
+
bytes += size.bytes;
|
|
95
|
+
}
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const card = cardSizes.get(meta.id) ?? NO_SIZE;
|
|
99
|
+
const low = lower(meta);
|
|
100
|
+
// A move to the cards that frees no room is not made.
|
|
101
|
+
const whole = tokens + size.tokens <= budget.inlineTokens
|
|
102
|
+
&& (size.tokens <= card.tokens || used.tokens - low.tokens + size.tokens <= contextRoom)
|
|
103
|
+
&& (size.bytes <= card.bytes || used.bytes - low.bytes + size.bytes <= byteRoom);
|
|
104
|
+
const taken = whole ? size : card;
|
|
105
|
+
used.tokens += taken.tokens - low.tokens;
|
|
106
|
+
used.bytes += taken.bytes - low.bytes;
|
|
107
|
+
if (whole) {
|
|
108
|
+
inline.add(meta.id);
|
|
109
|
+
tokens += size.tokens;
|
|
110
|
+
bytes += size.bytes;
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
const byId = new Map(documents.map((meta) => [meta.id, meta]));
|
|
114
|
+
for (const id of pinned) {
|
|
115
|
+
const meta = byId.get(id);
|
|
116
|
+
if (meta) place(meta);
|
|
117
|
+
}
|
|
118
|
+
for (const meta of sorted) if (!pinned.has(meta.id) && !cards.has(meta.id)) place(meta);
|
|
119
|
+
return {
|
|
120
|
+
inline: sorted.filter((meta) => inline.has(meta.id)),
|
|
121
|
+
searchable: sorted.filter((meta) => !inline.has(meta.id)),
|
|
122
|
+
inlineTokens: tokens,
|
|
123
|
+
inlineBytes: bytes,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* What a document sent whole takes of the request, as planning counts it: its tokens, and its
|
|
129
|
+
* bytes with 200 for its frame. `numbered` counts its line numbers too (`numberedSize`), rounded up.
|
|
130
|
+
* `measured` is the size of its text as rendered, when it is known: the larger of the two counts.
|
|
131
|
+
*/
|
|
132
|
+
export function inlineSize(meta: DocumentMeta, numbered: boolean, measured?: Size): Size {
|
|
133
|
+
let size: Size;
|
|
134
|
+
if (numbered) {
|
|
135
|
+
const counted = numberedSize(meta);
|
|
136
|
+
size = { tokens: Math.ceil(counted.tokens), bytes: Math.ceil(counted.bytes) + 200 };
|
|
137
|
+
} else {
|
|
138
|
+
size = { tokens: meta.estimatedTokens, bytes: (meta.jsonBytes ?? Math.ceil(meta.textBytes * 1.08)) + 200 };
|
|
139
|
+
}
|
|
140
|
+
return measured ? { tokens: Math.max(size.tokens, measured.tokens), bytes: Math.max(size.bytes, measured.bytes) } : size;
|
|
36
141
|
}
|
|
37
142
|
|
|
38
143
|
/** The digits of the numbers 1 to `count`, written out: what the line numbers of a text take. */
|
|
@@ -42,18 +147,34 @@ function digitsUpTo(count: number): number {
|
|
|
42
147
|
return digits;
|
|
43
148
|
}
|
|
44
149
|
|
|
150
|
+
/**
|
|
151
|
+
* The size of a document's text with its lines numbered (`12345| `), as the tools show it and as
|
|
152
|
+
* `numberInline` sends it, from its metadata alone: about 1.2 tokens a digit and one for the bar,
|
|
153
|
+
* and half a token more for each line's estimate, which is rounded up; in bytes, the digits and
|
|
154
|
+
* four more a line. About 8% to 16% more tokens than the text alone: 15.5% for a CSV of short
|
|
155
|
+
* rows, 9.4% for a service log, 8.4% for Hebrew prose. It can count short: a line that starts with
|
|
156
|
+
* 16 spaces costs about 2 tokens more with its number (the bar, the space, and a token for the run
|
|
157
|
+
* of 17 spaces). So `prepare` measures the numbered text it reads, and plans again when it is
|
|
158
|
+
* larger (`PlanOptions.measured`). New in 0.10.0.
|
|
159
|
+
*/
|
|
160
|
+
export function numberedSize(meta: Pick<DocumentMeta, "estimatedTokens" | "lines" | "textBytes" | "jsonBytes">): { tokens: number; bytes: number } {
|
|
161
|
+
const lines = Math.max(1, meta.lines);
|
|
162
|
+
const digits = digitsUpTo(lines);
|
|
163
|
+
return {
|
|
164
|
+
tokens: meta.estimatedTokens + 1.2 * digits + 1.5 * lines,
|
|
165
|
+
bytes: (meta.jsonBytes ?? meta.textBytes * 1.08) + digits + 4 * lines,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
45
169
|
/**
|
|
46
170
|
* About how many parts a whole-document read of a document takes, from its metadata alone:
|
|
47
171
|
* counting them exactly means reading the whole text. In the prompt every line carries its number
|
|
48
|
-
* (`
|
|
49
|
-
*
|
|
50
|
-
* On logs, prose, tables and blank-heavy text this lands within a few percent of the count.
|
|
172
|
+
* (`numberedSize`). A part ends at the end of a line, so it is short of full by half a line on
|
|
173
|
+
* average. On logs, prose, tables and blank-heavy text this lands within a few percent of the count.
|
|
51
174
|
*/
|
|
52
175
|
export function estimateParts(meta: Pick<DocumentMeta, "estimatedTokens" | "lines" | "textBytes" | "jsonBytes">, budget: Budget): number {
|
|
53
176
|
const lines = Math.max(1, meta.lines);
|
|
54
|
-
const
|
|
55
|
-
const tokens = meta.estimatedTokens + 1.2 * digits + 1.5 * lines;
|
|
56
|
-
const bytes = (meta.jsonBytes ?? meta.textBytes * 1.08) + digits + 4 * lines;
|
|
177
|
+
const { tokens, bytes } = numberedSize(meta);
|
|
57
178
|
const room = (limit: number, size: number) => Math.max(1, limit - size / lines / 2);
|
|
58
179
|
const maxBytes = Math.floor(budget.maxRequestBytes * 0.8);
|
|
59
180
|
return Math.max(1, Math.ceil(Math.max(tokens / room(budget.mapChunkTokens, tokens), bytes / room(maxBytes, bytes))));
|
|
@@ -70,14 +191,22 @@ export function canBeReadWhole(meta: Pick<DocumentMeta, "estimatedTokens" | "lin
|
|
|
70
191
|
return !Number.isFinite(parts) || parts <= budget.maxMapChunks * 1.05;
|
|
71
192
|
}
|
|
72
193
|
|
|
73
|
-
|
|
74
|
-
|
|
194
|
+
/**
|
|
195
|
+
* A count of tokens as a card shows it: "9,999", "10K", "1.0M". A count that rounds to 1,000K is
|
|
196
|
+
* written in millions (since 0.10.0: "1000K" before).
|
|
197
|
+
*/
|
|
198
|
+
export function formatCount(value: number): string {
|
|
199
|
+
if (value >= 1_000_000 || Math.round(value / 1_000) >= 1_000) return `${(value / 1_000_000).toFixed(1)}M`;
|
|
75
200
|
if (value >= 10_000) return `${Math.round(value / 1_000)}K`;
|
|
76
201
|
return value.toLocaleString("en-US");
|
|
77
202
|
}
|
|
78
203
|
|
|
204
|
+
/**
|
|
205
|
+
* A size in bytes: "512 B", "12 KB", "1.5 MB". A size that rounds to 1,024 KB is written in MB
|
|
206
|
+
* (since 0.10.0: "1024 KB" before).
|
|
207
|
+
*/
|
|
79
208
|
export function formatBytes(bytes: number): string {
|
|
80
|
-
if (bytes >= 1024 * 1024) return `${Number((bytes / 1024 / 1024).toFixed(1))} MB`;
|
|
209
|
+
if (bytes >= 1024 * 1024 || Math.round(bytes / 1024) >= 1024) return `${Number((bytes / 1024 / 1024).toFixed(1))} MB`;
|
|
81
210
|
if (bytes >= 1024) return `${Math.round(bytes / 1024)} KB`;
|
|
82
211
|
return `${bytes} B`;
|
|
83
212
|
}
|
|
@@ -126,11 +255,61 @@ export function frameMark(id: string): string {
|
|
|
126
255
|
* "--- End attached file: report.txt ---", in whatever letters, cannot end it early and start a
|
|
127
256
|
* fake one. The uploader chooses the name with the text, so the mark comes before the name, the
|
|
128
257
|
* name is quoted, and the last line holds the mark alone: a name cannot name a mark of its own.
|
|
258
|
+
*
|
|
259
|
+
* `withId` puts the document_id in the first line, for a file the tools read too (a table whose
|
|
260
|
+
* rows they count, `PrepareOptions.inlineTables: "tools"`): the tools take it, and a file sent whole
|
|
261
|
+
* has no card to give it. New in 0.10.0; without it, the frame of 0.9.
|
|
129
262
|
*/
|
|
130
|
-
export function renderInline(meta: DocumentMeta, text: string): string {
|
|
263
|
+
export function renderInline(meta: DocumentMeta, text: string, withId = false): string {
|
|
131
264
|
const mark = frameMark(meta.id);
|
|
132
265
|
const note = readingNote(meta, true);
|
|
133
|
-
return `--- Attached file [mark ${mark}]: ${JSON.stringify(meta.name)} (${meta.format}, ${meta.lines.toLocaleString("en-US")} ${plural(meta.lines, "line")}${note ? `, ${note}` : ""}; it ends only at the line with mark ${mark}) ---\n${text}\n--- End attached file [mark ${mark}] ---`;
|
|
266
|
+
return `--- Attached file [mark ${mark}]: ${JSON.stringify(meta.name)} (${meta.format}, ${meta.lines.toLocaleString("en-US")} ${plural(meta.lines, "line")}${note ? `, ${note}` : ""}${withId ? `; document_id ${meta.id}` : ""}; it ends only at the line with mark ${mark}) ---\n${text}\n--- End attached file [mark ${mark}] ---`;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* A text with its lines numbered as the tools number them ("12| text", by `numberLines`): a line
|
|
271
|
+
* ends at "\n", and a newline at the very end does not start another line. What `numberInline`
|
|
272
|
+
* puts between the frame lines of a file sent whole. New in 0.10.0.
|
|
273
|
+
*/
|
|
274
|
+
export function numberedText(text: string): string {
|
|
275
|
+
if (text.length === 0) return "";
|
|
276
|
+
return numberLines((text.endsWith("\n") ? text.slice(0, -1) : text).split("\n"), 1);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** A Markdown separator row, `| --- | :---: |`, as `aggregate_table` skips it. */
|
|
280
|
+
const SEPARATOR_ROW = /^\|(?:\s*:?-{3,}:?\s*\|)+\s*$/;
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Whether a text has a `| cell | cell |` table of at least `rows` rows, by the rule
|
|
284
|
+
* `aggregate_table` reads tables with: a run of lines that start and end with "|", which any other
|
|
285
|
+
* line ends, not counting the separator rows of Markdown. Rows of different tables are not added up:
|
|
286
|
+
* three one-cell lines in three paragraphs are three tables of one row. It stops at the row that
|
|
287
|
+
* makes the count.
|
|
288
|
+
*/
|
|
289
|
+
export function hasPipeRows(text: string, rows = 3): boolean {
|
|
290
|
+
let count = 0;
|
|
291
|
+
for (let start = 0; start < text.length;) {
|
|
292
|
+
const end = text.indexOf("\n", start);
|
|
293
|
+
const line = text.slice(start, end === -1 ? text.length : end).trim();
|
|
294
|
+
if (!(line.length > 1 && line.startsWith("|") && line.endsWith("|"))) count = 0;
|
|
295
|
+
else if (!SEPARATOR_ROW.test(line) && ++count >= rows) return true;
|
|
296
|
+
if (end === -1) break;
|
|
297
|
+
start = end + 1;
|
|
298
|
+
}
|
|
299
|
+
return false;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** How many `| cell |` rows of one table make a document sent whole one whose tables the tools count (`toolable`). */
|
|
303
|
+
export const TOOLABLE_PIPE_ROWS = 3;
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Whether the tools can count the tables of a document sent whole (`PrepareOptions.inlineTables:
|
|
307
|
+
* "tools"`): a CSV or a workbook always; a document of another format that `aggregate_table` reads
|
|
308
|
+
* when its text has a `| cell |` table of at least `TOOLABLE_PIPE_ROWS` rows. New in 0.10.0.
|
|
309
|
+
*/
|
|
310
|
+
export function isToolable(format: DocumentFormat, text: string): boolean {
|
|
311
|
+
if (format === "csv" || format === "xlsx") return true;
|
|
312
|
+
return TABLE_FORMATS.has(format) && hasPipeRows(text, TOOLABLE_PIPE_ROWS);
|
|
134
313
|
}
|
|
135
314
|
|
|
136
315
|
/** How many lines of a file its card shows. */
|
|
@@ -195,6 +374,24 @@ function qualityLines(meta: DocumentMeta, viewable: boolean): string[] {
|
|
|
195
374
|
return out;
|
|
196
375
|
}
|
|
197
376
|
|
|
377
|
+
/** What the tool guide (`documentToolsInstruction`) says of each tool. */
|
|
378
|
+
const SEARCH_LINES = [
|
|
379
|
+
"- search_document finds lines (exact or regex) or the most relevant passages (keywords).",
|
|
380
|
+
"- To count or list what can be matched as text (a word, an ID, an error code, a log level, a pattern), use search_document in exact or regex mode: its total_matching_lines is exact.",
|
|
381
|
+
"- To count per group (per hour or day, per error code or ID with a regex group, per message shape), pass group_by: one call gives every count. For more matches than a result shows, search again from its next_from_line, or with order \"last\" for the last ones.",
|
|
382
|
+
"- Search for the bare form of a word: a search matches inside longer words, so \"timeout\" also finds \"timeouts\", and a Hebrew word without its prefix letters (חוזה, not בחוזה) finds every form of it.",
|
|
383
|
+
];
|
|
384
|
+
const AGGREGATE_LINE = "- To add up, average, count or group the rows of a table (a CSV, an Excel sheet, a | cell | table), use aggregate_table: it reads every row, and its numbers are exact. Do not add numbers up from rows you read.";
|
|
385
|
+
const READ_LINE = "- read_document reads a line range. Read around search hits before you rely on them.";
|
|
386
|
+
const OVERVIEW_LINE = "- get_document_overview returns the outline, log profile, and the start and end of a file.";
|
|
387
|
+
const ANALYZE_LINE = "- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of the file and cannot be done by matching text: a full summary, a timeline, or items that must be judged by meaning. It is slow and costly, and it can miss items of a long list.";
|
|
388
|
+
const EVIDENCE_LINE = "Base your answer on text you actually read. Cite line numbers like (app.log L1203). If the tools did not find something, say so rather than guessing.";
|
|
389
|
+
const VIEW_LINES = [
|
|
390
|
+
"- Use view_pages when the answer depends on a picture, photo, chart, diagram, map, handwriting, a stamp or signature, or on how a page is laid out. A page is worth a look when its text says it has a picture or has no text, or mentions a figure.",
|
|
391
|
+
"- Page numbers are the N of the \"--- Page N ---\" lines in the text. Ask only for the pages you need: you have a limited number of tool turns.",
|
|
392
|
+
"- Do not use view_pages to read text, and do not describe a picture you have not looked at. If you could not look at a page, say so.",
|
|
393
|
+
];
|
|
394
|
+
|
|
198
395
|
/**
|
|
199
396
|
* The tool guide for the system prompt. `searchable` are the files the model reads through the
|
|
200
397
|
* text tools. `viewable` are the PDFs whose pages it can look at with `view_pages`: some of them
|
|
@@ -210,25 +407,79 @@ export function documentToolsInstruction(searchable: DocumentMeta[], viewable: D
|
|
|
210
407
|
guide.push(
|
|
211
408
|
`Some attached files are too large for your context: ${searchable.map((meta) => named(meta)).join("; ")}.`,
|
|
212
409
|
"You see only a summary card for each. Read them through the tools:",
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
...(
|
|
218
|
-
"- read_document reads a line range. Read around search hits before you rely on them.",
|
|
219
|
-
"- get_document_overview returns the outline, log profile, and the start and end of a file.",
|
|
220
|
-
...(wholeReads ? ["- analyze_whole_document reads the entire file in parts. Use it only when the task needs all of the file and cannot be done by matching text: a full summary, a timeline, or items that must be judged by meaning. It is slow and costly, and it can miss items of a long list."] : []),
|
|
410
|
+
...SEARCH_LINES,
|
|
411
|
+
...(searchable.some((meta) => TABLE_FORMATS.has(meta.format)) ? [AGGREGATE_LINE] : []),
|
|
412
|
+
READ_LINE,
|
|
413
|
+
OVERVIEW_LINE,
|
|
414
|
+
...(wholeReads ? [ANALYZE_LINE] : []),
|
|
221
415
|
"You have a limited number of tool turns. Call several tools in the same turn when the searches do not depend on each other, and answer as soon as you have enough evidence.",
|
|
222
|
-
|
|
416
|
+
EVIDENCE_LINE,
|
|
223
417
|
);
|
|
224
418
|
}
|
|
225
419
|
if (viewable.length > 0) {
|
|
226
420
|
guide.push(
|
|
227
421
|
`The text of a PDF does not show its pictures, charts or diagrams. You can look at the real pages of these PDFs with view_pages: ${viewable.map((meta) => named(meta, meta.pages ? `, ${meta.pages} ${meta.pages === 1 ? "page" : "pages"}` : "")).join("; ")}.`,
|
|
228
|
-
|
|
229
|
-
"- Page numbers are the N of the \"--- Page N ---\" lines in the text. Ask only for the pages you need: you have a limited number of tool turns.",
|
|
230
|
-
"- Do not use view_pages to read text, and do not describe a picture you have not looked at. If you could not look at a page, say so.",
|
|
422
|
+
...VIEW_LINES,
|
|
231
423
|
);
|
|
232
424
|
}
|
|
233
425
|
return guide.join("\n");
|
|
234
426
|
}
|
|
427
|
+
|
|
428
|
+
/** The tools in the order a tool set declares them: search, read, overview, aggregate, analyze, view. New in 0.10.0. */
|
|
429
|
+
export const TOOL_ORDER: readonly ToolName[] = ["search_document", "read_document", "get_document_overview", "aggregate_table", "analyze_whole_document", "view_pages"];
|
|
430
|
+
|
|
431
|
+
/** `names` once each, in `TOOL_ORDER`; names that are not tools are left out. New in 0.10.0. */
|
|
432
|
+
export function toolsInOrder(names: Iterable<string>): ToolName[] {
|
|
433
|
+
const given = new Set(names);
|
|
434
|
+
return TOOL_ORDER.filter((name) => given.has(name));
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* The tools a question needs, in `TOOL_ORDER`, as `files.tools` declares them for its documents:
|
|
439
|
+
* for searched documents, search_document, read_document and get_document_overview, with
|
|
440
|
+
* aggregate_table when one may hold a table, and analyze_whole_document when `wholeReads`; for
|
|
441
|
+
* documents sent whole whose tables the tools count (`toolable`), search_document, read_document
|
|
442
|
+
* and aggregate_table; and view_pages for PDFs whose pages can be shown. None when there is
|
|
443
|
+
* nothing to search, count or look at. New in 0.10.0.
|
|
444
|
+
*/
|
|
445
|
+
export function questionTools(documents: { searchable: readonly DocumentMeta[]; toolable?: readonly DocumentMeta[]; viewable?: readonly DocumentMeta[] }, wholeReads: boolean): ToolName[] {
|
|
446
|
+
const { searchable, toolable = [], viewable = [] } = documents;
|
|
447
|
+
const names: ToolName[] = [];
|
|
448
|
+
if (searchable.length > 0 || toolable.length > 0) names.push("search_document", "read_document");
|
|
449
|
+
if (searchable.length > 0) names.push("get_document_overview");
|
|
450
|
+
if (toolable.length > 0 || searchable.some((meta) => TABLE_FORMATS.has(meta.format))) names.push("aggregate_table");
|
|
451
|
+
if (wholeReads && searchable.length > 0) names.push("analyze_whole_document");
|
|
452
|
+
if (viewable.length > 0) names.push("view_pages");
|
|
453
|
+
return toolsInOrder(names);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* The line of the system text, with tools, for the files sent whole whose tables the tools can
|
|
458
|
+
* count (`PrepareOptions.inlineTables: "tools"`). New in 0.10.0.
|
|
459
|
+
*/
|
|
460
|
+
export const INLINE_TABLES_LINE = "Files shown in full can still be counted exactly: use aggregate_table for counts, sums and groups over their tables, and search_document exact for matching lines. In a spreadsheet, give the Row number when asked which row.";
|
|
461
|
+
|
|
462
|
+
/** The file name in `INLINE_CITATION_LINE`: an example, never the name of a real file. New in 0.10.0. */
|
|
463
|
+
export const CITATION_EXAMPLE_NAME = "report.docx";
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* The line of the system text that asks to cite the numbered lines of the files sent whole
|
|
467
|
+
* (`numberInline`) when no other line asks for citations: in a question that searches no file,
|
|
468
|
+
* with or without tools. Its file name is always `CITATION_EXAMPLE_NAME`, so that the line is the
|
|
469
|
+
* same in every question. New in 0.10.0.
|
|
470
|
+
*/
|
|
471
|
+
export const INLINE_CITATION_LINE = `Cite line numbers like (${CITATION_EXAMPLE_NAME} L12).`;
|
|
472
|
+
|
|
473
|
+
/**
|
|
474
|
+
* The fixed lines a loop that sends `instruction` adds after it, for the files sent whole (P1):
|
|
475
|
+
* `INLINE_TABLES_LINE` when the tools can count their tables (`toolable`), and
|
|
476
|
+
* `INLINE_CITATION_LINE` when their lines are numbered and no file is searched, since only the
|
|
477
|
+
* guide to searched files asks for citations: a question without tools, one over tables shown in
|
|
478
|
+
* full, one whose PDF pages can be looked at. `""` when there is neither. New in 0.10.0.
|
|
479
|
+
*/
|
|
480
|
+
export function inlineInstruction(prepared: Pick<PreparedContext, "plan" | "toolable">, numbered: boolean): string {
|
|
481
|
+
const lines: string[] = [];
|
|
482
|
+
if ((prepared.toolable?.length ?? 0) > 0) lines.push(INLINE_TABLES_LINE);
|
|
483
|
+
if (numbered && prepared.plan.inline.length > 0 && prepared.plan.searchable.length === 0) lines.push(INLINE_CITATION_LINE);
|
|
484
|
+
return lines.join("\n");
|
|
485
|
+
}
|
package/src/prepare.ts
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
// Planning one model request: which documents go into it whole, which become cards that the
|
|
2
|
+
// tools read, and the text of each. `files.prepare()` runs it. Moved out of library.ts in 0.10.0:
|
|
3
|
+
// the library hands it what it needs of the store and of the documents kept in memory
|
|
4
|
+
// (`PrepareContext`), and the options of the call as they were given. With no option new in 0.10.0,
|
|
5
|
+
// its blocks and its instruction are those of 0.9.
|
|
6
|
+
import type { AccessRules, Caller } from "./access.js";
|
|
7
|
+
import type { AccessOptions, PrepareOptions } from "./library.js";
|
|
8
|
+
import {
|
|
9
|
+
canBeReadWhole,
|
|
10
|
+
CARD_LINES,
|
|
11
|
+
documentToolsInstruction,
|
|
12
|
+
inlineSize,
|
|
13
|
+
isToolable,
|
|
14
|
+
numberedText,
|
|
15
|
+
planDocuments,
|
|
16
|
+
REQUEST_BYTES_MARGIN,
|
|
17
|
+
renderCard,
|
|
18
|
+
renderInline,
|
|
19
|
+
type WholeRead,
|
|
20
|
+
} from "./plan.js";
|
|
21
|
+
import { DocumentGoneError } from "./ranged.js";
|
|
22
|
+
import { numberLines, type DocumentSource } from "./search.js";
|
|
23
|
+
import { estimateTokens, jsonBytes } from "./text.js";
|
|
24
|
+
import type { Budget, DocumentMeta, PreparedContext } from "./types.js";
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The mark of a `PreparedContext` that this package's `prepare` made (since 0.10.0): its blocks
|
|
28
|
+
* have numbered lines when `numberInline` asks for them. `askWithFiles` numbers the citations of
|
|
29
|
+
* the files sent whole only for a context with the mark. A `LargeFiles` of your own that returns
|
|
30
|
+
* the result of this package's `prepare`, or a copy of it made with spread, keeps it; one of 0.9
|
|
31
|
+
* has none, and its blocks are sent as they are. A registered symbol, so that another copy of the
|
|
32
|
+
* package knows it too. It is not part of the public types.
|
|
33
|
+
*/
|
|
34
|
+
export const PREPARED_HERE = Symbol.for("llm-large-files.prepared");
|
|
35
|
+
|
|
36
|
+
/** Whether `prepared` was made by this package's `prepare` (`PREPARED_HERE`). */
|
|
37
|
+
export const preparedHere = (prepared: PreparedContext): boolean => (prepared as Marked)[PREPARED_HERE] === true;
|
|
38
|
+
|
|
39
|
+
/** A `PreparedContext` with the mark of this package's `prepare`. */
|
|
40
|
+
type Marked = PreparedContext & { [PREPARED_HERE]?: true };
|
|
41
|
+
|
|
42
|
+
/** What planning a request needs of the library that asks for it. */
|
|
43
|
+
export type PrepareContext = {
|
|
44
|
+
/**
|
|
45
|
+
* The caller of this call, from the options it was given: its owner and scope, checked against
|
|
46
|
+
* `rules`. Throws a TypeError for options the library does not accept.
|
|
47
|
+
*/
|
|
48
|
+
callerOf(access: AccessOptions | undefined): Caller;
|
|
49
|
+
/** The document, when `caller` may use it: one of another owner or scope is missing, not forbidden. */
|
|
50
|
+
metaFor(id: string, caller: Caller): Promise<DocumentMeta | undefined>;
|
|
51
|
+
/** A document ready to read and search, for `caller`. `known` is metadata just read from the store and checked. */
|
|
52
|
+
load(id: string, caller: Caller, known?: DocumentMeta): Promise<DocumentSource | undefined>;
|
|
53
|
+
/** Whether `document`, which a call of `caller` has just read, is still the one the store describes. */
|
|
54
|
+
stillOpened(document: DocumentSource, caller: Caller): Promise<boolean>;
|
|
55
|
+
/** The budget of one request: the library's, with `overrides` in place of its fields. */
|
|
56
|
+
budgetFor(overrides?: Partial<Budget>): Budget;
|
|
57
|
+
/** Whether `view_pages` can show the pages of a document: a PDF whose original is kept, and can be read. */
|
|
58
|
+
viewableMeta(meta: DocumentMeta): boolean;
|
|
59
|
+
/** What the library requires of every call (`requireOwner`, `requireScope`). */
|
|
60
|
+
rules: AccessRules;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
type Size = { tokens: number; bytes: number };
|
|
64
|
+
|
|
65
|
+
/** How the text of a document sent whole is given (`numberInline`, `inlineTables`). */
|
|
66
|
+
type Shape = { numbered: boolean; tables: boolean };
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The prompt text of a document, and, for one sent whole, whether the tools can count its tables,
|
|
70
|
+
* and the size of its numbered text with 200 bytes for its frame (`numberInline`).
|
|
71
|
+
*/
|
|
72
|
+
type Rendered = { text: string; toolable: boolean; size?: Size };
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* What a document contributes to the prompt: its text, or its card. Undefined when it is gone
|
|
76
|
+
* by now. A copy found to disagree with the store is opened again once.
|
|
77
|
+
*/
|
|
78
|
+
async function block(context: PrepareContext, id: string, meta: DocumentMeta, caller: Caller, whole: boolean, viewable: boolean, wholeRead: WholeRead, shape: Shape): Promise<Rendered | undefined> {
|
|
79
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
80
|
+
const document = await context.load(id, caller, attempt === 0 ? meta : undefined);
|
|
81
|
+
if (!document) return undefined;
|
|
82
|
+
let rendered: Rendered;
|
|
83
|
+
try {
|
|
84
|
+
if (whole) {
|
|
85
|
+
const text = await document.readText();
|
|
86
|
+
const numbered = shape.numbered ? numberedText(text) : undefined;
|
|
87
|
+
// A table the tools count has its document_id in its frame: the tools take it.
|
|
88
|
+
const toolable = shape.tables && isToolable(document.meta.format, text);
|
|
89
|
+
rendered = {
|
|
90
|
+
text: renderInline(document.meta, numbered ?? text, toolable),
|
|
91
|
+
toolable,
|
|
92
|
+
...(numbered !== undefined ? { size: { tokens: estimateTokens(numbered), bytes: jsonBytes(numbered) + 200 } } : {}),
|
|
93
|
+
};
|
|
94
|
+
} else {
|
|
95
|
+
rendered = { text: renderCard(document.meta, numberLines(await document.readLines(1, CARD_LINES), 1), viewable, wholeRead), toolable: false };
|
|
96
|
+
}
|
|
97
|
+
} catch (error) {
|
|
98
|
+
// The text is gone while its metadata is still there (removed outside the library): the
|
|
99
|
+
// same as missing. It was a plain Error, which failed the whole question.
|
|
100
|
+
if (error instanceof DocumentGoneError) return undefined;
|
|
101
|
+
if (document.broken) continue;
|
|
102
|
+
// Deleted between the look-up and the read: the same as missing.
|
|
103
|
+
if (!await context.metaFor(id, caller)) return undefined;
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
return await context.stillOpened(document, caller) ? rendered : undefined;
|
|
107
|
+
}
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The options of 0.10.0 that shape the text, checked. */
|
|
112
|
+
function shapeOf(options: PrepareOptions | undefined): Shape {
|
|
113
|
+
const numbered: unknown = options?.numberInline;
|
|
114
|
+
if (numbered !== undefined && typeof numbered !== "boolean") throw new TypeError(`PrepareOptions.numberInline must be true or false (got ${typeof numbered}).`);
|
|
115
|
+
const tables: unknown = options?.inlineTables;
|
|
116
|
+
if (tables !== undefined && tables !== "tools" && tables !== "text") throw new TypeError(`PrepareOptions.inlineTables must be "tools" or "text" (got ${JSON.stringify(tables) ?? String(tables)}).`);
|
|
117
|
+
return { numbered: numbered === true, tables: tables === "tools" };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const sum = (sizes: Iterable<Size>): Size => {
|
|
121
|
+
const total = { tokens: 0, bytes: 0 };
|
|
122
|
+
for (const size of sizes) {
|
|
123
|
+
total.tokens += size.tokens;
|
|
124
|
+
total.bytes += size.bytes;
|
|
125
|
+
}
|
|
126
|
+
return total;
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
/** How many times planning is made again when the request it planned does not fit. */
|
|
130
|
+
const MOST_EXTRA_PLANS = 6;
|
|
131
|
+
|
|
132
|
+
/** A plan and what goes with it. */
|
|
133
|
+
type Planned = Omit<PreparedContext, "missing">;
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Plans one model request (`LargeFiles.prepare`): which documents go in whole and which become
|
|
137
|
+
* searchable cards. `base` is the size of everything else in the request. `options` is what the
|
|
138
|
+
* caller gave `prepare`, passed on whole.
|
|
139
|
+
*
|
|
140
|
+
* The options new in 0.10.0: `numberInline` numbers the lines of the documents sent whole, and
|
|
141
|
+
* plans them by that size; `inlineTables: "tools"` lists in `toolable` those whose tables the tools
|
|
142
|
+
* can count. Without them, the blocks, the instruction and the plan are those of 0.9. The result
|
|
143
|
+
* always has the mark of this package (`PREPARED_HERE`).
|
|
144
|
+
*/
|
|
145
|
+
export async function prepareDocuments(context: PrepareContext, ids: string[], base: { tokens: number; bytes: number }, options?: PrepareOptions): Promise<PreparedContext> {
|
|
146
|
+
const caller = context.callerOf(options);
|
|
147
|
+
const budget = context.budgetFor(options?.budget);
|
|
148
|
+
const analysis = options?.wholeDocumentAnalysis !== false;
|
|
149
|
+
const shape = shapeOf(options);
|
|
150
|
+
const unique = [...new Set(ids)];
|
|
151
|
+
let documents: DocumentMeta[] = [];
|
|
152
|
+
const missing: string[] = [];
|
|
153
|
+
for (const id of unique) {
|
|
154
|
+
// A document of another owner or scope is reported as missing, not as forbidden, and is
|
|
155
|
+
// not read at all.
|
|
156
|
+
const meta = await context.metaFor(id, caller);
|
|
157
|
+
if (meta) documents.push(meta);
|
|
158
|
+
else missing.push(id);
|
|
159
|
+
}
|
|
160
|
+
// Pages can be shown for a PDF whose file is kept, whether its text is in the prompt or searched.
|
|
161
|
+
const viewableOf = () => (options?.viewPages ? documents.filter((meta) => context.viewableMeta(meta)) : []);
|
|
162
|
+
// With `numberInline`, the blocks read so far, by kind and ID: a plan made again reads each
|
|
163
|
+
// block once. Without it, the reads of 0.9.
|
|
164
|
+
const read = shape.numbered ? new Map<string, Rendered>() : undefined;
|
|
165
|
+
const render = async (meta: DocumentMeta, whole: boolean, viewable: boolean): Promise<Rendered | undefined> => {
|
|
166
|
+
const key = `${whole ? "whole" : "card"} ${meta.id}`;
|
|
167
|
+
const known = read?.get(key);
|
|
168
|
+
if (known) return known;
|
|
169
|
+
const wholeRead = !analysis ? "not_offered" : canBeReadWhole(meta, budget) ? "offered" : "too_large";
|
|
170
|
+
const rendered = await block(context, meta.id, meta, caller, whole, viewable, wholeRead, shape);
|
|
171
|
+
if (rendered) read?.set(key, rendered);
|
|
172
|
+
return rendered;
|
|
173
|
+
};
|
|
174
|
+
// What the request may hold of the documents.
|
|
175
|
+
const limit: Size = {
|
|
176
|
+
tokens: budget.contextTokens - budget.reservedTokens - base.tokens,
|
|
177
|
+
bytes: budget.maxRequestBytes - REQUEST_BYTES_MARGIN - base.bytes,
|
|
178
|
+
};
|
|
179
|
+
// With `numberInline`, the size of the numbered text of each document read whole so far.
|
|
180
|
+
const measured = new Map<string, Size>();
|
|
181
|
+
/** How far a plan is over the room it has: 0 when it fits. */
|
|
182
|
+
const excessOf = (planned: Planned): number => {
|
|
183
|
+
const whole = { tokens: planned.plan.inlineTokens, bytes: planned.plan.inlineBytes };
|
|
184
|
+
const tokens = Math.max(0, whole.tokens - limit.tokens, whole.tokens - budget.inlineTokens);
|
|
185
|
+
const bytes = Math.max(0, whole.bytes - limit.bytes);
|
|
186
|
+
return tokens / Math.max(1, budget.contextTokens) + bytes / Math.max(1, budget.maxRequestBytes);
|
|
187
|
+
};
|
|
188
|
+
const finish = ({ plan, blocks, instruction, viewable, toolable }: Planned): Marked => ({
|
|
189
|
+
plan,
|
|
190
|
+
blocks,
|
|
191
|
+
instruction,
|
|
192
|
+
missing,
|
|
193
|
+
viewable,
|
|
194
|
+
...(toolable ? { toolable } : {}),
|
|
195
|
+
[PREPARED_HERE]: true,
|
|
196
|
+
});
|
|
197
|
+
let extraPlans = 0;
|
|
198
|
+
let best: { planned: Planned; excess: number } | undefined;
|
|
199
|
+
// Planning needs only the metadata. The text is read for the documents sent whole, and the
|
|
200
|
+
// first lines for the others. One that is gone by then is missing, and the plan is made again.
|
|
201
|
+
for (;;) {
|
|
202
|
+
const plan = planDocuments(documents, budget, base, {
|
|
203
|
+
numbered: shape.numbered,
|
|
204
|
+
...(measured.size > 0 ? { measured } : {}),
|
|
205
|
+
});
|
|
206
|
+
const inline = new Set(plan.inline.map((meta) => meta.id));
|
|
207
|
+
const viewable = viewableOf();
|
|
208
|
+
const shown = new Set(viewable.map((meta) => meta.id));
|
|
209
|
+
const blocks = new Map<string, string>();
|
|
210
|
+
const toolableIds = new Set<string>();
|
|
211
|
+
const gone: string[] = [];
|
|
212
|
+
for (const meta of documents) {
|
|
213
|
+
const whole = inline.has(meta.id);
|
|
214
|
+
const rendered = await render(meta, whole, shown.has(meta.id));
|
|
215
|
+
if (rendered === undefined) {
|
|
216
|
+
gone.push(meta.id);
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
blocks.set(meta.id, rendered.text);
|
|
220
|
+
if (whole && rendered.toolable) toolableIds.add(meta.id);
|
|
221
|
+
if (whole && rendered.size) measured.set(meta.id, rendered.size);
|
|
222
|
+
}
|
|
223
|
+
if (gone.length > 0) {
|
|
224
|
+
missing.push(...gone);
|
|
225
|
+
documents = documents.filter((meta) => !gone.includes(meta.id));
|
|
226
|
+
best = undefined;
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
// A whole-document read is named only when the tools have it, and one of the files is
|
|
230
|
+
// small enough for it.
|
|
231
|
+
const wholeReads = analysis && plan.searchable.some((meta) => canBeReadWhole(meta, budget));
|
|
232
|
+
const toolable = shape.tables ? plan.inline.filter((meta) => toolableIds.has(meta.id)) : undefined;
|
|
233
|
+
// The numbered text is counted as it was measured, where that is larger than its estimate.
|
|
234
|
+
const counted = shape.numbered ? sum(plan.inline.map((meta) => inlineSize(meta, true, measured.get(meta.id)))) : undefined;
|
|
235
|
+
const planned: Planned = {
|
|
236
|
+
plan: counted ? { ...plan, inlineTokens: counted.tokens, inlineBytes: counted.bytes } : plan,
|
|
237
|
+
blocks,
|
|
238
|
+
instruction: documentToolsInstruction(plan.searchable, viewable, wholeReads),
|
|
239
|
+
viewable,
|
|
240
|
+
...(toolable ? { toolable } : {}),
|
|
241
|
+
};
|
|
242
|
+
// Without `numberInline`, the plan of 0.9: the cards are the caller's to count.
|
|
243
|
+
if (!shape.numbered) return finish(planned);
|
|
244
|
+
// A plan that does not fit is made again with the numbered text as measured. A plan made
|
|
245
|
+
// again that is no nearer to fitting is not used, and the nearest is.
|
|
246
|
+
const excess = excessOf(planned);
|
|
247
|
+
if (excess === 0) return finish(planned);
|
|
248
|
+
if (best && excess >= best.excess) return finish(best.planned);
|
|
249
|
+
best = { planned, excess };
|
|
250
|
+
if (extraPlans >= MOST_EXTRA_PLANS) return finish(planned);
|
|
251
|
+
extraPlans++;
|
|
252
|
+
}
|
|
253
|
+
}
|