llm-large-files 0.5.0 → 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 +1402 -467
- package/README.md +188 -60
- 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 +14 -3
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +190 -39
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +60 -4
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +1068 -206
- package/dist/ask.js.map +1 -1
- 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 +2 -0
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +3 -2
- package/dist/evidence.js.map +1 -1
- 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 +17 -8
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +108 -61
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +23 -3
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +6 -2
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +9 -4
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +32 -0
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +10 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +13 -7
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -2
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -1
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -1
- package/dist/gemini/sse.js.map +1 -1
- package/dist/http.d.ts +116 -0
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +347 -1
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +11 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +67 -5
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +405 -85
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +28 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +240 -52
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +84 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +182 -1
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +20 -4
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +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 +29 -5
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +311 -37
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +14 -2
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +39 -10
- package/dist/output-limit.js.map +1 -1
- package/dist/pause.d.ts +24 -0
- package/dist/pause.d.ts.map +1 -0
- package/dist/pause.js +38 -0
- package/dist/pause.js.map +1 -0
- package/dist/pdf-pages.d.ts +32 -2
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +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 +23 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +33 -3
- package/dist/retry.js.map +1 -1
- package/dist/search.d.ts +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 +35 -2
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +145 -31
- package/dist/sse.js.map +1 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +5 -2
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +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 +61 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +269 -42
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +102 -3
- 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 +37 -381
- package/docs/configuration.md +28 -558
- package/docs/getting-started.md +407 -223
- package/docs/guides/anthropic.md +590 -0
- package/docs/guides/conversations.md +629 -0
- package/docs/guides/costs-and-limits.md +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 +1012 -164
- package/docs/measurements.md +881 -0
- package/docs/publishing.md +274 -46
- package/docs/reference/anthropic.md +427 -0
- package/docs/reference/ask.md +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 +897 -103
- package/docs/troubleshooting.md +1390 -0
- package/package.json +2 -2
- package/src/analyze.ts +93 -42
- package/src/anthropic/adapter.ts +196 -39
- package/src/ask.ts +1087 -202
- package/src/encoding.ts +850 -0
- package/src/errors.ts +17 -0
- package/src/events.ts +442 -0
- package/src/evidence.ts +5 -2
- package/src/extract.ts +602 -62
- package/src/gemini/adapter.ts +118 -65
- package/src/gemini/chat.ts +28 -4
- package/src/gemini/errors.ts +34 -1
- package/src/gemini/generate.ts +23 -10
- package/src/gemini/index.ts +3 -3
- package/src/gemini/sse.ts +1 -1
- package/src/http.ts +376 -1
- package/src/index.ts +27 -5
- package/src/library.ts +459 -85
- package/src/map-reduce.ts +252 -51
- package/src/model.ts +236 -3
- 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 +306 -38
- package/src/output-limit.ts +44 -8
- 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 +49 -5
- package/src/search.ts +63 -10
- package/src/sse.ts +153 -28
- package/src/stores.ts +5 -2
- package/src/text-index.ts +26 -7
- package/src/text.ts +323 -13
- package/src/tools.ts +261 -42
- package/src/types.ts +107 -4
- package/src/zip-directory.ts +136 -0
package/src/text.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { TimeSlicer } from "./pause.js";
|
|
2
|
+
|
|
1
3
|
/** Lines longer than this are split so line-based tools always return bounded output. */
|
|
2
4
|
export const MAX_LINE_CHARACTERS = 2_000;
|
|
3
5
|
|
|
@@ -7,20 +9,176 @@ export const MAX_LINE_CHARACTERS = 2_000;
|
|
|
7
9
|
* ("ESC 7", "ESC c"). Coloured logs are full of them. An "ESC ]" whose end is not on its line is
|
|
8
10
|
* not a sequence: only those two characters go. Otherwise one stray "ESC ]", a cut-off window title
|
|
9
11
|
* or two bytes in a logged user agent, would take every line after it.
|
|
12
|
+
* U+009B, the one-character form of "ESC [", starts a sequence only with a parameter ("\x9b31m"),
|
|
13
|
+
* and not right after U+0080-U+00FF: there it is the end of a letter of UTF-8 read as Latin-1
|
|
14
|
+
* ("ś" is C5 9B, so "Coś? Tak" holds "\xc5\x9b? Tak"), and what follows it is text. `INVISIBLE`
|
|
15
|
+
* removes the U+009B alone then.
|
|
16
|
+
*/
|
|
17
|
+
// eslint-disable-next-line no-control-regex
|
|
18
|
+
const ANSI_ESCAPE = /\x1b(?:\[[0-?]*[ -\/]*[@-~]|\][^\x07\x1b\n]*(?:\x07|\x1b\\)|[ -\/]+[0-~]|[0-~])|(?<![\x80-\xff])\x9b[0-?]+[ -\/]*[@-~]/g;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Characters that show nothing, that no script needs, and that can hide text from a person who
|
|
22
|
+
* reads the file while a model reads it:
|
|
23
|
+
* - control characters other than tab and line breaks: C0 (U+0000-U+001F, U+007F) and C1
|
|
24
|
+
* (U+0080-U+009F);
|
|
25
|
+
* - Unicode tag characters (U+E0000-U+E007F). Each spells out one ASCII character, which a model
|
|
26
|
+
* reads and a person does not see. The three flags written with them (England, Scotland,
|
|
27
|
+
* Wales) are kept;
|
|
28
|
+
* - the text-direction controls that change the order a person sees: embeddings and overrides
|
|
29
|
+
* (U+202A-U+202E) and isolates (U+2066-U+2069). The marks that right-to-left text needs
|
|
30
|
+
* (U+200E, U+200F, U+061C) are kept;
|
|
31
|
+
* - the zero-width space (U+200B), the word joiner and invisible operators (U+2060-U+2064), the
|
|
32
|
+
* deprecated format characters (U+206A-U+206F), a byte order mark inside the text (U+FEFF), and
|
|
33
|
+
* the soft hyphen (U+00AD), but not one before a line break: there it shows, as a hyphen.
|
|
34
|
+
* Zero-width joiners and non-joiners (U+200C, U+200D) are kept: emoji and some scripts need them.
|
|
35
|
+
* Tab, "\n" and "\r" are not among them, so removing them moves no line. U+0085 goes with the other
|
|
36
|
+
* C1 characters, except where it ends lines (see `NEXT_LINE`).
|
|
10
37
|
*/
|
|
11
38
|
// eslint-disable-next-line no-control-regex
|
|
12
|
-
const
|
|
39
|
+
const INVISIBLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\u200B\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF]+|\xAD(?!\n)|\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|(?:\uDB40[\uDC00-\uDC7F])+/g;
|
|
40
|
+
/** A flag written with tag characters starts with U+1F3F4, whose first half is this. */
|
|
41
|
+
const FLAG_START = 0xd83c;
|
|
42
|
+
/**
|
|
43
|
+
* U+0085 (next line) ends each record of a mainframe file converted to UTF-8, which has no other
|
|
44
|
+
* line break: in such a text it becomes a line break (see `breaksAtNextLine`). Not one right after
|
|
45
|
+
* U+0080-U+00FF: there it is the last byte of a UTF-8 letter read as Latin-1 ("ą" is C4 85), and a
|
|
46
|
+
* line break would split the word. `INVISIBLE` removes that one, and those of other texts.
|
|
47
|
+
*/
|
|
48
|
+
const NEXT_LINE = /(?<![\x80-\xFF])\x85/g;
|
|
49
|
+
/** A run of U+0085, to go past it in one step. */
|
|
50
|
+
const NEXT_LINE_RUN = /\x85+/y;
|
|
51
|
+
|
|
52
|
+
/** `text` without the characters of `INVISIBLE`. */
|
|
53
|
+
export function removeInvisible(text: string): string {
|
|
54
|
+
return text.replace(INVISIBLE, (found) => (found.charCodeAt(0) === FLAG_START ? found : ""));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A word for a count: "line" for 1, "lines" for any other. */
|
|
58
|
+
export const plural = (count: number, word: string): string => (count === 1 ? word : `${word}s`);
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Whether the U+0085 of `text` end lines: only when it has no other line break, one at its very end
|
|
62
|
+
* aside. A mainframe file converted to UTF-8 has none. In a text that has them, a U+0085 is more
|
|
63
|
+
* often in a JSON string or a CSV field, or a windows-1252 "…" read as Latin-1, and a line break
|
|
64
|
+
* there would split a record and move every line after it.
|
|
65
|
+
*/
|
|
66
|
+
export function breaksAtNextLine(text: string): boolean {
|
|
67
|
+
let end = text.length;
|
|
68
|
+
if (text.charCodeAt(end - 1) === 10) end--;
|
|
69
|
+
if (text.charCodeAt(end - 1) === 13) end--;
|
|
70
|
+
const lineFeed = text.indexOf("\n");
|
|
71
|
+
if (lineFeed !== -1 && lineFeed < end) return false;
|
|
72
|
+
const carriageReturn = text.indexOf("\r");
|
|
73
|
+
return carriageReturn === -1 || carriageReturn >= end;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** `removeInvisible`, after each U+0085 that ends a line is made a line break, when `nextLines`. */
|
|
77
|
+
function cleanLines(text: string, nextLines: boolean): string {
|
|
78
|
+
return removeInvisible(nextLines && text.includes("\x85") ? text.replace(NEXT_LINE, "\n") : text);
|
|
79
|
+
}
|
|
13
80
|
|
|
14
81
|
/**
|
|
15
|
-
* Strips a BOM, unifies line endings, and removes terminal escape sequences
|
|
16
|
-
* other than tab and newline
|
|
82
|
+
* Strips a BOM, unifies line endings, and removes terminal escape sequences, control characters
|
|
83
|
+
* other than tab and newline, and the invisible characters of `INVISIBLE`. In a text with no other
|
|
84
|
+
* line break, a U+0085 becomes one (see `NEXT_LINE`).
|
|
17
85
|
*/
|
|
18
86
|
export function normalizeText(raw: string): string {
|
|
19
|
-
|
|
87
|
+
const text = raw.replace(/^/, "");
|
|
88
|
+
return normalizeLines(text, breaksAtNextLine(text));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* `normalizeText` without the BOM: the same on a whole text as on pieces of it cut after line
|
|
93
|
+
* breaks, given `breaksAtNextLine` of the whole text as `nextLines`.
|
|
94
|
+
*/
|
|
95
|
+
function normalizeLines(raw: string, nextLines: boolean): string {
|
|
96
|
+
return cleanLines(withoutEscapes(raw.replace(/\r\n?/g, "\n")), nextLines);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** `text` without terminal escape sequences. */
|
|
100
|
+
function withoutEscapes(text: string): string {
|
|
20
101
|
// Remove whole sequences first. Dropping only the ESC byte would leave "[31mERROR[0m" behind.
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
102
|
+
// U+009B is the one-character form of "ESC [".
|
|
103
|
+
return text.includes("\x1b") || text.includes("\x9b") ? text.replace(ANSI_ESCAPE, "") : text;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* `withoutEscapes`, with a pause after each `piece` characters or so. The sequences are found one
|
|
108
|
+
* after the other, as `replace` finds them, so the result is the same.
|
|
109
|
+
*/
|
|
110
|
+
async function withoutEscapesInPieces(text: string, slicer: TimeSlicer, piece: number): Promise<string> {
|
|
111
|
+
if (!text.includes("\x1b") && !text.includes("\x9b")) return text;
|
|
112
|
+
// A copy of its own: during a pause, another ingest may use `ANSI_ESCAPE`, which moves its lastIndex.
|
|
113
|
+
const escape = new RegExp(ANSI_ESCAPE.source, "g");
|
|
114
|
+
const done: string[] = [];
|
|
115
|
+
let parts: string[] = [];
|
|
116
|
+
// Where the text after the last sequence starts, and where the last pause was.
|
|
117
|
+
let kept = 0;
|
|
118
|
+
let paused = 0;
|
|
119
|
+
for (let found = escape.exec(text); found !== null; found = escape.exec(text)) {
|
|
120
|
+
parts.push(text.slice(kept, found.index));
|
|
121
|
+
kept = escape.lastIndex;
|
|
122
|
+
if (kept - paused >= piece) {
|
|
123
|
+
done.push(parts.join(""));
|
|
124
|
+
parts = [];
|
|
125
|
+
paused = kept;
|
|
126
|
+
await slicer.maybePause();
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
parts.push(text.slice(kept));
|
|
130
|
+
done.push(parts.join(""));
|
|
131
|
+
return done.length === 1 ? done[0]! : done.join("");
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* `normalizeLines`, a piece of about `piece` characters at a time, with a pause between pieces. A
|
|
136
|
+
* line with no break for megabytes can hold millions of characters or escape sequences to remove,
|
|
137
|
+
* which take seconds in one go. The escape sequences are found in order, as in one go, and the
|
|
138
|
+
* pieces of the last step (`cleanLines`) end where `cutsCleanly` says, so the result is the same.
|
|
139
|
+
*/
|
|
140
|
+
export async function normalizeInPieces(raw: string, slicer: TimeSlicer, nextLines: boolean, piece = SLICE_CHARACTERS): Promise<string> {
|
|
141
|
+
const text = await withoutEscapesInPieces(raw.replace(/\r\n?/g, "\n"), slicer, piece);
|
|
142
|
+
const parts: string[] = [];
|
|
143
|
+
for (let from = 0; from < text.length;) {
|
|
144
|
+
let to = Math.min(text.length, from + piece);
|
|
145
|
+
// Where the next piece starts.
|
|
146
|
+
let next = to;
|
|
147
|
+
while (to < text.length && !cutsCleanly(text, to)) {
|
|
148
|
+
if (text.charCodeAt(to) === 0x85) {
|
|
149
|
+
// A run of U+0085 after U+0080-U+00FF, which no place may cut. `cleanLines` removes all of
|
|
150
|
+
// it, and gives the same on the text before it and after it alone: the run is left out.
|
|
151
|
+
NEXT_LINE_RUN.lastIndex = to;
|
|
152
|
+
NEXT_LINE_RUN.test(text);
|
|
153
|
+
next = NEXT_LINE_RUN.lastIndex;
|
|
154
|
+
break;
|
|
155
|
+
}
|
|
156
|
+
next = ++to;
|
|
157
|
+
}
|
|
158
|
+
parts.push(cleanLines(text.slice(from, to), nextLines));
|
|
159
|
+
from = next;
|
|
160
|
+
await slicer.maybePause();
|
|
161
|
+
}
|
|
162
|
+
return parts.length === 1 ? parts[0]! : parts.join("");
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Whether `cleanLines` gives the same result on `text` cut before `at` as on it whole. It does
|
|
167
|
+
* unless the cut is between the two halves of a character outside the basic plane, inside a flag,
|
|
168
|
+
* between a soft hyphen and a line break, or before a U+0085 right after U+0080-U+00FF. Only
|
|
169
|
+
* these places are kept whole: a rule that never cut after a soft hyphen or half of a pair would
|
|
170
|
+
* never cut a line of soft hyphens, or of tag characters and emoji in turn, and such a line
|
|
171
|
+
* would be cleaned in one go again.
|
|
172
|
+
*/
|
|
173
|
+
function cutsCleanly(text: string, at: number): boolean {
|
|
174
|
+
const before = text.charCodeAt(at - 1);
|
|
175
|
+
const after = text.charCodeAt(at);
|
|
176
|
+
if (isHighSurrogate(before) && isLowSurrogate(after)) return false;
|
|
177
|
+
if (before === 0xad && after === 0x0a) return false;
|
|
178
|
+
if (after === 0x85 && before >= 0x80 && before <= 0xff) return false;
|
|
179
|
+
// A flag is 14 units: U+1F3F4, then tag characters, each a pair that starts with U+DB40.
|
|
180
|
+
if (after === 0xdb40 && text.slice(Math.max(0, at - 12), at).includes("\uD83C\uDFF4")) return false;
|
|
181
|
+
return true;
|
|
24
182
|
}
|
|
25
183
|
|
|
26
184
|
/**
|
|
@@ -45,11 +203,72 @@ export function foldCase(text: string): string {
|
|
|
45
203
|
const isHighSurrogate = (code: number) => code >= 0xd800 && code <= 0xdbff;
|
|
46
204
|
const isLowSurrogate = (code: number) => code >= 0xdc00 && code <= 0xdfff;
|
|
47
205
|
|
|
206
|
+
/**
|
|
207
|
+
* The first `end` UTF-16 units of `text`, one fewer when the last of them would be the first half
|
|
208
|
+
* of a character outside the basic plane (an emoji). Half of one is not text: JSON writes it as
|
|
209
|
+
* `\ud83d`, and an API that checks its input (Claude's) refuses the request.
|
|
210
|
+
*/
|
|
211
|
+
export function sliceWhole(text: string, end: number): string {
|
|
212
|
+
const at = Math.max(0, Math.min(text.length, Math.trunc(end)));
|
|
213
|
+
return at > 0 && at < text.length && isHighSurrogate(text.charCodeAt(at - 1)) ? text.slice(0, at - 1) : text.slice(0, at);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Half of a character outside the basic plane, on its own. */
|
|
217
|
+
const LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* `text` with each half of a character that is on its own (an emoji cut in two) made a replacement
|
|
221
|
+
* character, as `String.prototype.toWellFormed` does. 0.5.0 cut some strings that way, and kept them:
|
|
222
|
+
* log templates in the metadata, and search windows in tool rounds. Claude's API refuses a request
|
|
223
|
+
* that holds one. Text that is whole comes back as it is.
|
|
224
|
+
*/
|
|
225
|
+
export function wellFormed(text: string): string {
|
|
226
|
+
return /[\ud800-\udfff]/.test(text) ? text.replace(LONE_SURROGATE, "\ufffd") : text;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* A JSON value with `wellFormed` applied to every string in it, keys included. The same value, not
|
|
231
|
+
* a copy, when nothing in it needed that.
|
|
232
|
+
*/
|
|
233
|
+
export function wellFormedJson<T>(value: T): T {
|
|
234
|
+
if (typeof value === "string") return wellFormed(value) as T;
|
|
235
|
+
if (Array.isArray(value)) {
|
|
236
|
+
let changed = false;
|
|
237
|
+
const items = value.map((item: unknown) => {
|
|
238
|
+
const fixed = wellFormedJson(item);
|
|
239
|
+
if (fixed !== item) changed = true;
|
|
240
|
+
return fixed;
|
|
241
|
+
});
|
|
242
|
+
return (changed ? items : value) as T;
|
|
243
|
+
}
|
|
244
|
+
if (value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
|
|
245
|
+
let changed = false;
|
|
246
|
+
const entries = Object.entries(value).map(([key, item]): [string, unknown] => {
|
|
247
|
+
const fixedKey = wellFormed(key);
|
|
248
|
+
const fixed = wellFormedJson(item);
|
|
249
|
+
if (fixedKey !== key || fixed !== item) changed = true;
|
|
250
|
+
return [fixedKey, fixed];
|
|
251
|
+
});
|
|
252
|
+
return (changed ? Object.fromEntries(entries) : value) as T;
|
|
253
|
+
}
|
|
254
|
+
return value;
|
|
255
|
+
}
|
|
256
|
+
|
|
48
257
|
/**
|
|
49
258
|
* Splits lines longer than `limit`, preferring a break after whitespace or punctuation near the
|
|
50
259
|
* end of each piece. Minified JSON or a PDF paragraph becomes many addressable lines.
|
|
51
260
|
*/
|
|
52
261
|
export function wrapLongLines(text: string, limit = MAX_LINE_CHARACTERS): { text: string; wrapped: number } {
|
|
262
|
+
// Most files have no long line: then the text is used as it is, without splitting and joining it.
|
|
263
|
+
let longest = 0;
|
|
264
|
+
let start = 0;
|
|
265
|
+
for (let end = text.indexOf("\n"); ; end = text.indexOf("\n", start)) {
|
|
266
|
+
const stop = end === -1 ? text.length : end;
|
|
267
|
+
if (stop - start > longest) longest = stop - start;
|
|
268
|
+
if (end === -1 || longest > limit) break;
|
|
269
|
+
start = end + 1;
|
|
270
|
+
}
|
|
271
|
+
if (longest <= limit) return { text, wrapped: 0 };
|
|
53
272
|
let wrapped = 0;
|
|
54
273
|
const lines = text.split("\n");
|
|
55
274
|
const out: string[] = [];
|
|
@@ -113,13 +332,20 @@ const SYMBOL = 1; // Dashes, quotes, arrows, box drawing, and anything unclassif
|
|
|
113
332
|
* of random letters in a single case with no digits (about 70% of the real count).
|
|
114
333
|
*/
|
|
115
334
|
export function estimateTokens(text: string): number {
|
|
116
|
-
|
|
335
|
+
return Math.ceil(tokensIn(text, 0, text.length, 0));
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* The tokens of `text` from `from` to `to`, added to `tokens`. Every count starts again after a line
|
|
340
|
+
* break, so a text cut after line breaks gives, piece by piece, the sum it gives whole.
|
|
341
|
+
*/
|
|
342
|
+
function tokensIn(text: string, from: number, to: number, tokens: number): number {
|
|
117
343
|
// The current run of ASCII letters: its length since the last case change, and its casing.
|
|
118
344
|
let piece = 0;
|
|
119
345
|
let capitalsInARow = 0;
|
|
120
346
|
let previousWasLower = false;
|
|
121
347
|
let previous = 0; // 1 = space, 2 = ASCII punctuation, 0 = anything else
|
|
122
|
-
for (let index =
|
|
348
|
+
for (let index = from; index < to; index++) {
|
|
123
349
|
const code = text.charCodeAt(index);
|
|
124
350
|
if ((code >= 97 && code <= 122) || (code >= 65 && code <= 90)) {
|
|
125
351
|
const capital = code <= 90;
|
|
@@ -176,7 +402,7 @@ export function estimateTokens(text: string): number {
|
|
|
176
402
|
else if (code < 0xff00) tokens += OTHER_SCRIPT;
|
|
177
403
|
else tokens += KANA;
|
|
178
404
|
}
|
|
179
|
-
return
|
|
405
|
+
return tokens;
|
|
180
406
|
}
|
|
181
407
|
|
|
182
408
|
/**
|
|
@@ -187,9 +413,15 @@ export function estimateTokens(text: string): number {
|
|
|
187
413
|
* quarter or more, a novel by a hundredth.
|
|
188
414
|
*/
|
|
189
415
|
export function textSizes(text: string): { utf8: number; json: number } {
|
|
416
|
+
const { utf8, escapes } = sizesIn(text, 0, text.length);
|
|
417
|
+
return { utf8, json: utf8 + escapes + 2 };
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** UTF-8 bytes and JSON escapes of `text` from `from` to `to`, which must not split a surrogate pair. */
|
|
421
|
+
function sizesIn(text: string, from: number, to: number): { utf8: number; escapes: number } {
|
|
190
422
|
let utf8 = 0;
|
|
191
423
|
let escapes = 0;
|
|
192
|
-
for (let index =
|
|
424
|
+
for (let index = from; index < to; index++) {
|
|
193
425
|
const code = text.charCodeAt(index);
|
|
194
426
|
if (code < 0x80) {
|
|
195
427
|
utf8 += 1;
|
|
@@ -197,7 +429,7 @@ export function textSizes(text: string): { utf8: number; json: number } {
|
|
|
197
429
|
else if (code < 0x20) escapes += code === 0x0a || code === 0x09 || code === 0x0d || code === 0x08 || code === 0x0c ? 1 : 5;
|
|
198
430
|
} else if (code < 0x800) {
|
|
199
431
|
utf8 += 2;
|
|
200
|
-
} else if (isHighSurrogate(code) && isLowSurrogate(text.charCodeAt(index + 1))) {
|
|
432
|
+
} else if (isHighSurrogate(code) && index + 1 < to && isLowSurrogate(text.charCodeAt(index + 1))) {
|
|
201
433
|
utf8 += 4;
|
|
202
434
|
index++;
|
|
203
435
|
} else {
|
|
@@ -206,7 +438,85 @@ export function textSizes(text: string): { utf8: number; json: number } {
|
|
|
206
438
|
if (code >= 0xd800 && code <= 0xdfff) escapes += 3;
|
|
207
439
|
}
|
|
208
440
|
}
|
|
209
|
-
return { utf8,
|
|
441
|
+
return { utf8, escapes };
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** Characters worked on between two looks at the clock while ingesting. */
|
|
445
|
+
const SLICE_CHARACTERS = 1 << 18;
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* The text cut into slices of about 256K characters, each ending after a line break (the last
|
|
449
|
+
* one at the end of the text), as `[from, to)` offsets.
|
|
450
|
+
*/
|
|
451
|
+
function* lineSlices(text: string): Generator<[number, number]> {
|
|
452
|
+
for (let from = 0; from < text.length;) {
|
|
453
|
+
let to = Math.min(text.length, from + SLICE_CHARACTERS);
|
|
454
|
+
if (to < text.length) {
|
|
455
|
+
const newline = text.indexOf("\n", to - 1);
|
|
456
|
+
to = newline === -1 ? text.length : newline + 1;
|
|
457
|
+
}
|
|
458
|
+
yield [from, to];
|
|
459
|
+
from = to;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* `estimateTokens` and `textSizes` of a text, the same numbers, worked out a slice at a time so
|
|
465
|
+
* that other requests get a turn while a large upload is measured. Slices end after a line break.
|
|
466
|
+
*/
|
|
467
|
+
export async function measureText(text: string, slicer: TimeSlicer): Promise<{ tokens: number; utf8: number; json: number }> {
|
|
468
|
+
let tokens = 0;
|
|
469
|
+
let utf8 = 0;
|
|
470
|
+
let escapes = 0;
|
|
471
|
+
for (const [from, to] of lineSlices(text)) {
|
|
472
|
+
tokens = tokensIn(text, from, to, tokens);
|
|
473
|
+
const sizes = sizesIn(text, from, to);
|
|
474
|
+
utf8 += sizes.utf8;
|
|
475
|
+
escapes += sizes.escapes;
|
|
476
|
+
await slicer.maybePause();
|
|
477
|
+
}
|
|
478
|
+
return { tokens: Math.ceil(tokens), utf8, json: utf8 + escapes + 2 };
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* What ingest makes of extracted text, a slice at a time: `normalizeText`, then `wrapLongLines`,
|
|
483
|
+
* then the lines (a line break at the very end does not start another line). The same results as
|
|
484
|
+
* doing each in one go: no step of `normalizeText` reaches across a line break, and whether a U+0085
|
|
485
|
+
* ends lines is decided once, for the whole text. A slice that runs far past its size holds a long
|
|
486
|
+
* line: it is cleaned in pieces too. `onProgress` is told the characters of `raw` cleaned so far,
|
|
487
|
+
* after each slice; splitting the lines after that is quick, and is not counted.
|
|
488
|
+
*/
|
|
489
|
+
export async function prepareText(
|
|
490
|
+
raw: string,
|
|
491
|
+
slicer: TimeSlicer,
|
|
492
|
+
onProgress?: (done: number, total: number) => void,
|
|
493
|
+
): Promise<{ text: string; wrapped: number; lines: string[] }> {
|
|
494
|
+
const start = raw.charCodeAt(0) === 0xfeff ? 1 : 0;
|
|
495
|
+
const body = start === 1 ? raw.slice(1) : raw;
|
|
496
|
+
const nextLines = breaksAtNextLine(body);
|
|
497
|
+
const parts: string[] = [];
|
|
498
|
+
// A clean text (most logs) comes back as it is: joining its slices would copy all of it.
|
|
499
|
+
let changed = false;
|
|
500
|
+
for (const [from, to] of lineSlices(body)) {
|
|
501
|
+
const slice = body.slice(from, to);
|
|
502
|
+
const normalized = slice.length > 2 * SLICE_CHARACTERS ? await normalizeInPieces(slice, slicer, nextLines) : normalizeLines(slice, nextLines);
|
|
503
|
+
if (normalized !== slice) changed = true;
|
|
504
|
+
parts.push(normalized);
|
|
505
|
+
onProgress?.(start + to, raw.length);
|
|
506
|
+
await slicer.maybePause();
|
|
507
|
+
}
|
|
508
|
+
const { text, wrapped } = wrapLongLines(!changed ? body : parts.length === 1 ? parts[0]! : parts.join(""));
|
|
509
|
+
parts.length = 0;
|
|
510
|
+
await slicer.maybePause();
|
|
511
|
+
const lines: string[] = [];
|
|
512
|
+
for (const [from, to] of lineSlices(text)) {
|
|
513
|
+
const piece = text.slice(from, to).split("\n");
|
|
514
|
+
// A slice that ends with a line break splits into one empty string too many.
|
|
515
|
+
if (text.charCodeAt(to - 1) === 10) piece.pop();
|
|
516
|
+
for (const line of piece) lines.push(line);
|
|
517
|
+
await slicer.maybePause();
|
|
518
|
+
}
|
|
519
|
+
return { text, wrapped, lines };
|
|
210
520
|
}
|
|
211
521
|
|
|
212
522
|
/** UTF-8 byte length without allocating an encoded copy. */
|