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
|
@@ -0,0 +1,1467 @@
|
|
|
1
|
+
# `llm-large-files`: the library and its documents
|
|
2
|
+
|
|
3
|
+
This is the reference for the part of the main entry point that ingests, stores and plans
|
|
4
|
+
documents: `createLargeFiles` and the `LargeFiles` object it returns, the budget, the stores, the
|
|
5
|
+
extractors, and the types that describe a document. It is for developers who wire the library into
|
|
6
|
+
an application or write a store, an extractor or a loop of their own.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
import {
|
|
10
|
+
createLargeFiles, DEFAULT_CACHE_BYTES, DEFAULT_WHOLE_DOCUMENT_BYTES, DEFAULT_MAX_PDF_PAGES, DEFAULT_MAX_TEXT_BYTES,
|
|
11
|
+
DEFAULT_INGEST_TIMEOUT_MS, NEVER_EXPIRES, isDocumentId, toDocumentSummary,
|
|
12
|
+
DEFAULT_BUDGET, resolveBudget,
|
|
13
|
+
MemoryDocumentStore, FileDocumentStore, DOCUMENT_ID_PATTERN, DocumentStoreError,
|
|
14
|
+
createPdfExtractor, defaultExtractors, detectFormat,
|
|
15
|
+
estimateTokens, utf8Bytes, jsonBytes,
|
|
16
|
+
} from "llm-large-files";
|
|
17
|
+
import type {
|
|
18
|
+
LargeFilesOptions, LargeFiles, AccessOptions, IngestInput, PrepareOptions, ToolOptions, PreparedContext, DocumentPlan,
|
|
19
|
+
Budget, ModelLimits, DocumentStore, StoredDocument, PdfExtractorOptions, Extractor, ExtractInput, ExtractProgress,
|
|
20
|
+
ExtractedText, DocumentMeta, DocumentSummary, DocumentFormat, OutlineEntry, LogIssue, LogProfile, ProgressEvent,
|
|
21
|
+
ProgressListener, ToolCallHooks, ToolRequestHandle, ToolRequestStart, ToolRequestEnd, IngestEvent,
|
|
22
|
+
} from "llm-large-files";
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
The signature blocks below assume these imports, and `ToolSet`, `GenerateText` and `RetryOptions`
|
|
26
|
+
from the same entry point.
|
|
27
|
+
|
|
28
|
+
Contents:
|
|
29
|
+
|
|
30
|
+
- [The library](#the-library): [`createLargeFiles(options)`](#createlargefilesoptions),
|
|
31
|
+
[`LargeFilesOptions`](#largefilesoptions), [`LargeFiles`](#largefiles), [`IngestInput`](#ingestinput),
|
|
32
|
+
[`AccessOptions`](#accessoptions), [`PrepareOptions`](#prepareoptions), [`ToolOptions`](#tooloptions),
|
|
33
|
+
[`PreparedContext`](#preparedcontext), [`DocumentPlan`](#documentplan),
|
|
34
|
+
[`DEFAULT_CACHE_BYTES`](#default_cache_bytes), [`DEFAULT_WHOLE_DOCUMENT_BYTES`](#default_whole_document_bytes),
|
|
35
|
+
[`DEFAULT_MAX_PDF_PAGES`](#default_max_pdf_pages), [`DEFAULT_MAX_TEXT_BYTES`](#default_max_text_bytes),
|
|
36
|
+
[`DEFAULT_INGEST_TIMEOUT_MS`](#default_ingest_timeout_ms),
|
|
37
|
+
[`NEVER_EXPIRES`](#never_expires), [`isDocumentId(value)`](#isdocumentidvalue),
|
|
38
|
+
[`toDocumentSummary(meta)`](#todocumentsummarymeta)
|
|
39
|
+
- [The budget](#the-budget): [`Budget`](#budget), [`DEFAULT_BUDGET`](#default_budget),
|
|
40
|
+
[`resolveBudget(budget?, limits?)`](#resolvebudgetbudget-limits), [`ModelLimits`](#modellimits)
|
|
41
|
+
- [Stores](#stores): [`DocumentStore`](#documentstore), [`StoredDocument`](#storeddocument),
|
|
42
|
+
[`MemoryDocumentStore`](#memorydocumentstore), [`FileDocumentStore`](#filedocumentstore),
|
|
43
|
+
[`DOCUMENT_ID_PATTERN`](#document_id_pattern), [`DocumentStoreError`](#documentstoreerror)
|
|
44
|
+
- [Extraction](#extraction): [`Extractor`](#extractor), [`ExtractInput`](#extractinput),
|
|
45
|
+
[`ExtractProgress`](#extractprogress), [`ExtractedText`](#extractedtext), [`defaultExtractors`](#defaultextractors),
|
|
46
|
+
[`createPdfExtractor(options?)`](#createpdfextractoroptions), [`PdfExtractorOptions`](#pdfextractoroptions),
|
|
47
|
+
[`detectFormat(name, mimeType)`](#detectformatname-mimetype)
|
|
48
|
+
- [Text sizes](#text-sizes): [`estimateTokens(text)`](#estimatetokenstext), [`utf8Bytes(text)`](#utf8bytestext),
|
|
49
|
+
[`jsonBytes(text)`](#jsonbytestext)
|
|
50
|
+
- [Document types](#document-types): [`DocumentMeta`](#documentmeta), [`DocumentSummary`](#documentsummary),
|
|
51
|
+
[`DocumentFormat`](#documentformat), [`OutlineEntry`](#outlineentry), [`LogIssue`](#logissue),
|
|
52
|
+
[`LogProfile`](#logprofile)
|
|
53
|
+
- [Progress of whole-document reads](#progress-of-whole-document-reads): [`ProgressEvent`](#progressevent),
|
|
54
|
+
[`ProgressListener`](#progresslistener), [`ToolCallHooks`](#toolcallhooks),
|
|
55
|
+
[`ToolRequestHandle`](#toolrequesthandle), [`ToolRequestStart`](#toolrequeststart),
|
|
56
|
+
[`ToolRequestEnd`](#toolrequestend)
|
|
57
|
+
|
|
58
|
+
The same entry point also exports the tool loop and the adapter contract ([ask.md](./ask.md)),
|
|
59
|
+
errors, retries and streams ([errors-and-retries.md](./errors-and-retries.md)), the tools the
|
|
60
|
+
model sees ([tools.md](./tools.md)), and the events of a question and of an ingest
|
|
61
|
+
([events.md](./events.md)).
|
|
62
|
+
|
|
63
|
+
## The library
|
|
64
|
+
|
|
65
|
+
### createLargeFiles(options)
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
declare function createLargeFiles(options: LargeFilesOptions): LargeFiles;
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Creates the library over one store. Create it once per process and share it: it keeps the cache of
|
|
72
|
+
documents ready to search and the queue of scans. Everything else lives in the store, so several
|
|
73
|
+
servers can share one store.
|
|
74
|
+
|
|
75
|
+
It throws an `Error` when `options.budget` holds a value that is not a finite number above 0, or
|
|
76
|
+
values that cannot work together (see [`resolveBudget`](#resolvebudgetbudget-limits)). It does not
|
|
77
|
+
call the store.
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
import { createLargeFiles, FileDocumentStore } from "llm-large-files";
|
|
81
|
+
|
|
82
|
+
const files = createLargeFiles({
|
|
83
|
+
store: new FileDocumentStore(process.env.DOCUMENTS_DIR ?? "./documents"),
|
|
84
|
+
budget: { contextTokens: 1_000_000, maxRequestBytes: 10_000_000 },
|
|
85
|
+
ttlMs: 24 * 60 * 60 * 1000,
|
|
86
|
+
keepOriginals: ["pdf"],
|
|
87
|
+
});
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### `LargeFilesOptions`
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
type LargeFilesOptions = {
|
|
94
|
+
store: DocumentStore;
|
|
95
|
+
budget?: Partial<Budget>;
|
|
96
|
+
ttlMs?: number;
|
|
97
|
+
maxUploadBytes?: number;
|
|
98
|
+
maxTextBytes?: number;
|
|
99
|
+
maxPdfPages?: number;
|
|
100
|
+
ingestTimeoutMs?: number;
|
|
101
|
+
extractors?: Partial<Record<DocumentFormat, Extractor>>;
|
|
102
|
+
keepOriginals?: DocumentFormat[];
|
|
103
|
+
scannedPdfPages?: number;
|
|
104
|
+
cacheBytes?: number;
|
|
105
|
+
cacheSize?: number;
|
|
106
|
+
wholeDocumentBytes?: number;
|
|
107
|
+
scanChunkBytes?: number;
|
|
108
|
+
maxConcurrentScans?: number;
|
|
109
|
+
now?: () => Date;
|
|
110
|
+
};
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
| Option | Type | Default | What it does |
|
|
114
|
+
|---|---|---|---|
|
|
115
|
+
| `store` | [`DocumentStore`](#documentstore) | required | Where the text, the metadata, kept originals and line indexes live: `new FileDocumentStore(dir)`, `new MemoryDocumentStore()`, or your own. |
|
|
116
|
+
| `budget` | `Partial<Budget>` | [`DEFAULT_BUDGET`](#default_budget) | The limits of your model connection. Fields you leave out follow `contextTokens` (see [`Budget`](#budget)): for a model with a smaller window, setting `contextTokens` is enough. |
|
|
117
|
+
| `ttlMs` | `number` | 72 hours (259,200,000) | How long a document is kept after it is ingested. `expiresAt` is set at ingest, and the library never extends it. `Infinity`, or any time that would end at or after the end of year 9999, keeps documents until they are deleted: `expiresAt` is then [`NEVER_EXPIRES`](#never_expires). |
|
|
118
|
+
| `maxUploadBytes` | `number` | 100 MB (104,857,600) | The largest file `ingest` accepts. The upload handler of [`llm-large-files/node`](./node.md) reads no more than this. |
|
|
119
|
+
| `maxTextBytes` | `number` | [`DEFAULT_MAX_TEXT_BYTES`](#default_max_text_bytes), 100 MB, or `maxUploadBytes` when that is larger | The most text kept from one file, in UTF-8 bytes. A file's text can be larger than the file: a PDF of 3 KB built for it drew 107 MB. The PDF, DOCX and PPTX extractors refuse a file as soon as its text passes this (a PDF page by page, and also past 100 times its size after the first 16 MB; a DOCX or PPTX also past 32 million characters, whatever this allows), and `ingest` refuses a larger text from any other extractor, the text extractor and yours included. Your extractor receives it as `ExtractInput.maxTextBytes`. At least 1. |
|
|
120
|
+
| `maxPdfPages` | `number` | [`DEFAULT_MAX_PDF_PAGES`](#default_max_pdf_pages), 5,000 | The most pages read from one PDF. A PDF with more is refused before any page is read. Your PDF extractor receives it as `ExtractInput.maxPages`. At least 1. |
|
|
121
|
+
| `ingestTimeoutMs` | `number` | [`DEFAULT_INGEST_TIMEOUT_MS`](#default_ingest_timeout_ms), 120,000 (2 minutes) | The most time one `ingest` may take to extract the text, build its line index and profile it, in milliseconds. The store's writes are not counted. Past it, `ingest` throws `<name> took too long to read (more than 2 min). Split it, or save it as plain text, and attach that.`, and stores nothing. 0 sets no limit, and so does a value past what a timer can wait (2,147,483,647 ms, 24.8 days). Your extractor receives the limit as `ExtractInput.signal`. Within one page of a PDF the limit is not looked at: see [security](../security.md#uploads). |
|
|
122
|
+
| `extractors` | `Partial<Record<DocumentFormat, Extractor>>` | the built-ins, [`defaultExtractors`](#defaultextractors) | An [`Extractor`](#extractor) per format, used in place of the built-in one. The formats are fixed ([`DocumentFormat`](#documentformat)): you can replace the extractor of a format, not add a format. |
|
|
123
|
+
| `keepOriginals` | `DocumentFormat[]` | `[]` | Formats whose uploaded file is kept in the store next to its text, for example `["pdf"]`, which `view_pages` needs. Takes effect only with a store that has `putOriginal`. A kept file takes as much space as the upload until its document expires or is deleted. |
|
|
124
|
+
| `scannedPdfPages` | `number` | 30 | The most pages a PDF without any text (a scan) may have and still be accepted, so that its pages can be shown to the model. It applies only when `"pdf"` is in `keepOriginals` and the store has `putOriginal`. Otherwise, and with 0, such a PDF is refused. Your own PDF extractor receives it as `ExtractInput.scannedPages`. |
|
|
125
|
+
| `cacheBytes` | `number` | [`DEFAULT_CACHE_BYTES`](#default_cache_bytes), 256 MB | The most memory that documents kept ready between tool calls may take, together with the decoded pieces of documents read by range. The least recently used go first. A document that would take more than this is not kept and is read again for each call. A document whose decoded text would take more than a quarter of it keeps no pieces. 0 keeps nothing. Each use of a kept document asks the store first, so a document deleted or expired on another server is never served from memory. |
|
|
126
|
+
| `cacheSize` | `number` | no limit | Also caps the number of documents kept. The pieces of a document read by range are not counted, and leave with their document. 0 keeps nothing. |
|
|
127
|
+
| `wholeDocumentBytes` | `number` | [`DEFAULT_WHOLE_DOCUMENT_BYTES`](#default_whole_document_bytes), 2 MB | Documents whose text (`textBytes`) is at most this size are loaded whole into memory. Larger ones are read by range when the store has `readTextRange`, as `FileDocumentStore` does: a tool call reads only the lines it needs, and a search reads the text a piece at a time. `Infinity` loads every document whole; 0 reads every one by range. |
|
|
128
|
+
| `scanChunkBytes` | `number` | 1 MB (1,048,576) | Reading by range: about how many bytes of text are read and searched at a time. At least 1. |
|
|
129
|
+
| `maxConcurrentScans` | `number` | 4 | Reading by range: how many scans of whole documents (searches, counting the parts of a file) run at once in this library (each `createLargeFiles` call has its own queue). The others wait their turn. At least 1. |
|
|
130
|
+
| `now` | `() => Date` | `() => new Date()` | The clock, for tests. It dates `createdAt` and `expiresAt`, decides whether a document has expired, and is passed to the store's `sweep`. |
|
|
131
|
+
|
|
132
|
+
Guides: [storage](../guides/storage.md) for the store, owners and retention,
|
|
133
|
+
[costs and limits](../guides/costs-and-limits.md) for the budget, [PDFs](../guides/pdfs.md) for
|
|
134
|
+
`keepOriginals`, `scannedPdfPages`, `extractors` and the files the limits refuse,
|
|
135
|
+
[security](../security.md#uploads) for `maxTextBytes`, `maxPdfPages` and `ingestTimeoutMs`, and
|
|
136
|
+
[deployment](../guides/deployment.md) for the memory settings.
|
|
137
|
+
|
|
138
|
+
### `LargeFiles`
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
interface LargeFiles {
|
|
142
|
+
readonly budget: Budget;
|
|
143
|
+
budgetFor(overrides?: Partial<Budget>, limits?: ModelLimits): Budget;
|
|
144
|
+
readonly maxUploadBytes: number;
|
|
145
|
+
ingest(input: IngestInput): Promise<DocumentMeta>;
|
|
146
|
+
getMeta(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>;
|
|
147
|
+
getOriginal(id: string, access?: AccessOptions): Promise<Uint8Array | undefined>;
|
|
148
|
+
delete(id: string, access?: AccessOptions): Promise<boolean>;
|
|
149
|
+
sweep(): Promise<number>;
|
|
150
|
+
prepare(ids: string[], base: { tokens: number; bytes: number }, options?: PrepareOptions): Promise<PreparedContext>;
|
|
151
|
+
tools(documents: DocumentMeta[], options?: ToolOptions): ToolSet;
|
|
152
|
+
}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
The object `createLargeFiles` returns. Below, its members are shown on a `LargeFiles` named `files`.
|
|
156
|
+
|
|
157
|
+
The members that read the store (`getMeta`, `getOriginal`, `delete` and `prepare`) throw
|
|
158
|
+
[`DocumentStoreError`](#documentstoreerror) when the store cannot be read: retry, the document is
|
|
159
|
+
not gone. A tool call that meets it answers the model with its message instead. What the store
|
|
160
|
+
throws while writing (in `ingest`, the removal in `delete`, `sweep`) is passed on unchanged: log it,
|
|
161
|
+
and do not show it to a user, since its message may name a path or a host.
|
|
162
|
+
|
|
163
|
+
#### `files.ingest(input)`
|
|
164
|
+
|
|
165
|
+
`ingest(input: IngestInput): Promise<DocumentMeta>`
|
|
166
|
+
|
|
167
|
+
Extracts the text of a file, normalizes it, profiles it, and stores it under a new ID. Returns the
|
|
168
|
+
new document's [`DocumentMeta`](#documentmeta).
|
|
169
|
+
|
|
170
|
+
1. The owner is checked (see [`IngestInput`](#ingestinput)), the name is cleaned, and the format
|
|
171
|
+
is picked by [`detectFormat(name, mimeType)`](#detectformatname-mimetype).
|
|
172
|
+
2. The extractor of that format turns the bytes into text. It receives the limits `maxTextBytes`
|
|
173
|
+
and `maxPdfPages`, the ingest's signal, and, when someone listens to the ingest's events, an
|
|
174
|
+
`onProgress` to report how far it is ([`ExtractInput`](#extractinput)). A text longer
|
|
175
|
+
than `maxTextBytes` is refused, whichever extractor made it. The extractor may say how the text
|
|
176
|
+
was read ([`ExtractedText`](#extractedtext)): the built-in one reads a text file that is not
|
|
177
|
+
valid UTF-8 in the older encoding its lines fit, when one does, and `encoding` and
|
|
178
|
+
`replacedCharacters` of the metadata record how it was read
|
|
179
|
+
([Text encodings](../guides/pdfs.md#text-encodings)).
|
|
180
|
+
3. The text is normalized: a byte-order mark is removed, line endings become `\n`, and terminal
|
|
181
|
+
escape sequences and control characters other than tab and newline are removed, C1 controls
|
|
182
|
+
(U+0080-U+009F) included. So are most characters that show nothing: Unicode tag characters
|
|
183
|
+
(the flags of England, Scotland and Wales are kept), the text-direction embeddings, overrides
|
|
184
|
+
and isolates (U+202A-U+202E, U+2066-U+2069), the zero-width space, the word joiner and the
|
|
185
|
+
invisible operators (U+200B, U+2060-U+2064), the deprecated format characters
|
|
186
|
+
(U+206A-U+206F), a byte-order mark inside the text, and a soft hyphen that is not at the end of
|
|
187
|
+
a line. The characters that scripts and emoji need are kept: LRM, RLM and ALM, zero-width
|
|
188
|
+
joiners and non-joiners, variation selectors. In a text with no other line break, U+0085 (next
|
|
189
|
+
line) ends a line, except right after U+0080-U+00FF; elsewhere it is removed. No other line
|
|
190
|
+
moves. Lines longer than 2,000 characters are split, so every line can be read by number
|
|
191
|
+
(`wrappedLines` counts them).
|
|
192
|
+
4. A `text` document becomes a `log`, and gets a `logProfile`, when it has at least 5 non-blank
|
|
193
|
+
lines and at least 40% of its first 200 non-blank lines start with a timestamp or a log level
|
|
194
|
+
(`ERROR`, `WARN`, `INFO`...).
|
|
195
|
+
5. The store is written: the original file (when it is kept), then the line index (when the store
|
|
196
|
+
has `putIndex`), then `put` last.
|
|
197
|
+
|
|
198
|
+
Steps 2 to 4 work in slices of about 12 ms, with a pause for other requests between two slices:
|
|
199
|
+
between the pages of a PDF, as a DOCX or PPTX is unpacked, and while the text is normalized,
|
|
200
|
+
measured, outlined, profiled and indexed. Ingests that run at once take turns, one slice each.
|
|
201
|
+
They run under one signal, aborted by `IngestInput.signal` or after `ingestTimeoutMs` (2 minutes
|
|
202
|
+
by default). When it aborts, `ingest` stops waiting for the extractor, throws, and writes nothing
|
|
203
|
+
to the store. The writes of step 5 are not under the signal. One page of a PDF is read without a
|
|
204
|
+
pause, and the signal is looked at only between pages.
|
|
205
|
+
|
|
206
|
+
**Events.** New in 0.7.0. With `IngestInput.onEvent`, the ingest tells what it does as typed
|
|
207
|
+
[`IngestEvent`](./events.md#ingestevent)s, in order: `ingest.start` first (the cleaned name, the
|
|
208
|
+
format the name and type say, the size), even for a file that is then refused; `ingest.progress` for each stage
|
|
209
|
+
that reports; and last `ingest.finish`, with the document's
|
|
210
|
+
[`DocumentSummary`](#documentsummary), or `ingest.error`. The stages, in the order they run:
|
|
211
|
+
`decode` (a text file that is not UTF-8, once, when it is decoded), `check` (the pages of a PDF
|
|
212
|
+
checked before they are read, with `@cantoo/pdf-lib`), `extract` (the pages of a PDF, the parts of
|
|
213
|
+
a DOCX or PPTX), `pictures` (the pages of a PDF looked at for pictures, with `@cantoo/pdf-lib`),
|
|
214
|
+
`prepare` and `index` (characters of the text), and `store` (each write)
|
|
215
|
+
([stages and units](./events.md#stages-and-units)). A stage sends at
|
|
216
|
+
most one `ingest.progress` about every 12 ms, and its last one when it ends. An extractor of your
|
|
217
|
+
own reports only what it passes to `onProgress`. The error of `ingest.error` is told in words for
|
|
218
|
+
users: a store that failed to write is "The document could not be stored. Try again later.",
|
|
219
|
+
whatever it threw, and the store's own error is the one `ingest` throws. A listener that throws
|
|
220
|
+
ends the ingest with that error, and nothing is stored; a throw on `ingest.finish` removes the
|
|
221
|
+
document that was just stored. `createDocumentHandlers` sends these events to a client that
|
|
222
|
+
asks for them with `Accept: text/event-stream`
|
|
223
|
+
([upload with progress](./node.md#upload-with-progress-accept-textevent-stream)).
|
|
224
|
+
|
|
225
|
+
| It throws | When |
|
|
226
|
+
|---|---|
|
|
227
|
+
| `TypeError("owner must be a string that is not empty or only spaces, such as the signed-in user's ID. To let anyone with the document's ID use it, leave owner out.")` | `owner` is `""`, spaces only or `null`, or, from JavaScript, neither a string nor a finite number (an object, `true`, `NaN`). Before anything is read. New in 0.6.0: 0.5.0 accepted them. |
|
|
228
|
+
| `Error("<name> is empty.")` | The file has no bytes. |
|
|
229
|
+
| `Error("<name> is larger than the 100 MB upload limit.")` | The file is larger than `maxUploadBytes`. The message gives your limit. |
|
|
230
|
+
| The extractor's `Error` | The extractor refused the file: a binary or compressed file, a PDF without text, a missing optional dependency or an `unpdf` that cannot run on this Node, a possible zip bomb, a file past `maxTextBytes` or `maxPdfPages`, a file built to exhaust the server. A text file is never refused for its encoding. The built-in messages, listed under [`defaultExtractors`](#defaultextractors), are written for a user. |
|
|
231
|
+
| `Error("<name> holds more than 100 MB of text, more than is kept from one file. Split it, and attach the part you need.")` | The text an extractor returned is larger than `maxTextBytes`. The message gives your limit. |
|
|
232
|
+
| `Error("<name> took too long to read (more than 2 min). Split it, or save it as plain text, and attach that.")` | The ingest took longer than `ingestTimeoutMs`. The message gives your limit: "500 ms" below a second, "45 s" below 2 minutes, "2 min" from there. |
|
|
233
|
+
| `signal.reason` | `IngestInput.signal` was aborted, before or during the ingest. |
|
|
234
|
+
| `Error("<name> did not contain any text.")` | The extracted text is blank. |
|
|
235
|
+
| The store's own error | A write failed. `ingest` first calls `store.delete(id)` to remove what was written (an error of that call is ignored), then throws the store's error unchanged. It is not a `DocumentStoreError`. |
|
|
236
|
+
|
|
237
|
+
The `TypeError` of an owner is a mistake of the server's code, not of the file: the upload handler
|
|
238
|
+
of [`llm-large-files/node`](./node.md) checks the owner itself, and answers `500` before it reads
|
|
239
|
+
the body. The errors of the file and the store's error are all plain `Error`s, with no class to
|
|
240
|
+
tell them apart. The upload handler of [`llm-large-files/node`](./node.md) takes an error that carries an
|
|
241
|
+
HTTP `status` or `statusCode` (400 to 599), or a Node system error (`code` and `syscall`), for the
|
|
242
|
+
store's: it answers with that status, or with 500 and the code. `ingest` also keeps a mark of each
|
|
243
|
+
error a store throws while it writes. The handler answers a marked error without a status or a
|
|
244
|
+
code, and a thrown value that is not an `Error`, with 500 `{ "error": "Upload failed." }`, without
|
|
245
|
+
its message. It answers any other `Error` with 422 and its message, as a file that cannot be read.
|
|
246
|
+
The package does not export the mark: behind an `ingest` of your own that throws a new error, or in
|
|
247
|
+
a route of your own, a store's error is answered as a file that cannot be read (see
|
|
248
|
+
[the upload handler](./node.md#uploadrequest-response)). Give your store's write errors a `status`
|
|
249
|
+
and a message of your own. See [errors and reliability](../guides/errors-and-reliability.md).
|
|
250
|
+
|
|
251
|
+
Guides: [web app](../guides/web-app.md) for uploads, [PDFs](../guides/pdfs.md) for what PDF
|
|
252
|
+
extraction writes.
|
|
253
|
+
|
|
254
|
+
#### `files.getMeta(id, access?)`
|
|
255
|
+
|
|
256
|
+
`getMeta(id: string, access?: AccessOptions): Promise<DocumentMeta | undefined>`
|
|
257
|
+
|
|
258
|
+
The document's metadata, or `undefined` when the ID does not match
|
|
259
|
+
[`DOCUMENT_ID_PATTERN`](#document_id_pattern), the document was never there, was deleted, has
|
|
260
|
+
expired (the library compares `expiresAt` with its clock itself, whatever the store returns), or
|
|
261
|
+
belongs to another owner ([`AccessOptions`](#accessoptions)). Throws `DocumentStoreError` when the
|
|
262
|
+
store cannot be read. A name that 0.5.0 or earlier stored cut inside an emoji comes back with a
|
|
263
|
+
replacement character (U+FFFD) in place of the half, as the model and the steps get it; the stored
|
|
264
|
+
metadata is not changed.
|
|
265
|
+
|
|
266
|
+
#### `files.getOriginal(id, access?)`
|
|
267
|
+
|
|
268
|
+
`getOriginal(id: string, access?: AccessOptions): Promise<Uint8Array | undefined>`
|
|
269
|
+
|
|
270
|
+
The uploaded file, when it was kept (`keepOriginals`). `undefined` in every case where `getMeta`
|
|
271
|
+
gives `undefined`, and when the document has no `originalKept`, the store has no `getOriginal`, or
|
|
272
|
+
the store returns none. Treat the bytes as read-only: `MemoryDocumentStore` returns the very bytes
|
|
273
|
+
it keeps, not a copy, so changing them changes the stored file.
|
|
274
|
+
Throws `DocumentStoreError` when the store cannot be read.
|
|
275
|
+
|
|
276
|
+
#### `files.delete(id, access?)`
|
|
277
|
+
|
|
278
|
+
`delete(id: string, access?: AccessOptions): Promise<boolean>`
|
|
279
|
+
|
|
280
|
+
Removes a document, with its original and its index. It looks the document up as `getMeta` does,
|
|
281
|
+
and returns `false` when it is not there for this caller: another owner's document is never
|
|
282
|
+
deleted. Otherwise it drops what this process keeps of the document in memory and returns what
|
|
283
|
+
`store.delete(id)` returns. Throws `DocumentStoreError` when the look-up cannot read the store; an
|
|
284
|
+
error of `store.delete` itself is passed on unchanged.
|
|
285
|
+
|
|
286
|
+
#### `files.sweep()`
|
|
287
|
+
|
|
288
|
+
`sweep(): Promise<number>`
|
|
289
|
+
|
|
290
|
+
Calls the store's `sweep` with the library's clock and returns how many expired documents it
|
|
291
|
+
removed: 0 when the store has no `sweep`. Errors of the store are passed on unchanged. The library
|
|
292
|
+
never sweeps on its own: run it on a schedule, from one place (see [deployment](../guides/deployment.md)).
|
|
293
|
+
|
|
294
|
+
#### `files.prepare(ids, base, options?)`
|
|
295
|
+
|
|
296
|
+
`prepare(ids: string[], base: { tokens: number; bytes: number }, options?: PrepareOptions): Promise<PreparedContext>`
|
|
297
|
+
|
|
298
|
+
Plans one model request: which documents go into the prompt whole, and which become cards that the
|
|
299
|
+
model reads through the tools.
|
|
300
|
+
|
|
301
|
+
| Argument | Type | What it is |
|
|
302
|
+
|---|---|---|
|
|
303
|
+
| `ids` | `string[]` | The document IDs of the request. A repeated ID counts once. |
|
|
304
|
+
| `base` | `{ tokens: number; bytes: number }` | The size of everything else in the request: messages, system prompt, other files. `estimateTokens` and `jsonBytes` measure text the way the plan does. |
|
|
305
|
+
| `options` | [`PrepareOptions`](#prepareoptions) | The owner, a budget for this request, whether your loop can show pages, and whether your tools have `analyze_whole_document`. |
|
|
306
|
+
|
|
307
|
+
Documents are taken smallest first, by `estimatedTokens`. Each one goes in whole when, with the
|
|
308
|
+
ones already taken, it still fits both the token room,
|
|
309
|
+
`min(inlineTokens, contextTokens − reservedTokens − base.tokens)`, and the byte room,
|
|
310
|
+
`maxRequestBytes − 256 KB − base.bytes`. Otherwise it is searchable. See
|
|
311
|
+
[how it works](../how-it-works.md) for the details.
|
|
312
|
+
|
|
313
|
+
Returns a [`PreparedContext`](#preparedcontext). A document that cannot be used is not an error
|
|
314
|
+
here: its ID is listed in `missing`, and a document that disappears while the plan is made is moved
|
|
315
|
+
there and the plan is made again. ([`askWithFiles`](./ask.md#askwithfilesoptions) throws
|
|
316
|
+
[`DocumentsNotFoundError`](./ask.md#documentsnotfounderror) for them instead.) Throws
|
|
317
|
+
`DocumentStoreError` when the store cannot be read, and an `Error` for a `budget` that cannot work.
|
|
318
|
+
|
|
319
|
+
```ts
|
|
320
|
+
import { estimateTokens, jsonBytes, type GenerateText, type LargeFiles } from "llm-large-files";
|
|
321
|
+
|
|
322
|
+
// One question in a loop of your own. `generate` is a plain text completion of your model.
|
|
323
|
+
async function planQuestion(files: LargeFiles, generate: GenerateText, documentIds: string[], userId: string, question: string) {
|
|
324
|
+
const instructions = "Answer questions about the attached files. Cite line numbers.";
|
|
325
|
+
const base = {
|
|
326
|
+
tokens: estimateTokens(instructions) + estimateTokens(question),
|
|
327
|
+
bytes: jsonBytes(instructions) + jsonBytes(question),
|
|
328
|
+
};
|
|
329
|
+
// viewPages: true only when your loop runs tools with executeWithFiles and sends their files to the model.
|
|
330
|
+
const prepared = await files.prepare(documentIds, base, { owner: userId, viewPages: true });
|
|
331
|
+
if (prepared.missing.length > 0) throw new Error(`Not found: ${prepared.missing.join(", ")}`);
|
|
332
|
+
|
|
333
|
+
const tools = files.tools(prepared.plan.searchable, { generate, viewPages: prepared.viewable });
|
|
334
|
+
const system = [instructions, prepared.instruction].filter(Boolean).join("\n\n");
|
|
335
|
+
const user = [...prepared.blocks.values(), question].join("\n\n");
|
|
336
|
+
return { system, user, tools };
|
|
337
|
+
}
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
Guide: [your own adapter and loop](../guides/own-adapter-and-loop.md).
|
|
341
|
+
|
|
342
|
+
#### `files.tools(documents, options?)`
|
|
343
|
+
|
|
344
|
+
`tools(documents: DocumentMeta[], options?: ToolOptions): ToolSet`
|
|
345
|
+
|
|
346
|
+
A [`ToolSet`](./tools.md#toolset) scoped to `documents`: a call that names any other `document_id`
|
|
347
|
+
answers with an error that lists the IDs it may use. Pass `prepared.plan.searchable`. Make one tool
|
|
348
|
+
set for each question: the time budget of regex searches and the count of whole-document reads
|
|
349
|
+
belong to the tool set.
|
|
350
|
+
|
|
351
|
+
It takes the owner from the metadata it is handed. Each call that reads a document's text or the
|
|
352
|
+
pages of its PDF compares the owner stored with the document with the `owner` of the
|
|
353
|
+
`DocumentMeta` given for that ID, and answers a document whose owners differ as it answers one
|
|
354
|
+
that is gone: `doc_… is no longer available on the server. Ask the user to attach the file again.`
|
|
355
|
+
So metadata built from an ID alone, or with another owner, reads nothing of a document that has an
|
|
356
|
+
owner. A document stored without an owner is read whatever the metadata says. Pass documents that
|
|
357
|
+
you got from `prepare` or `getMeta` with the caller's owner: they carry the stored owner.
|
|
358
|
+
|
|
359
|
+
It declares `search_document`, `read_document` and `get_document_overview`;
|
|
360
|
+
`analyze_whole_document` when `generate` is given and at least one document is small enough to be
|
|
361
|
+
read whole; and `view_pages` when `viewPages` names at least one PDF whose original is kept and the
|
|
362
|
+
store has `getOriginal`. With no `documents` and pages to show, it declares only `view_pages`. The
|
|
363
|
+
tools, their arguments and their results are in [tools.md](./tools.md).
|
|
364
|
+
|
|
365
|
+
Throws an `Error` for a `budget` that cannot work.
|
|
366
|
+
|
|
367
|
+
#### `files.budget`
|
|
368
|
+
|
|
369
|
+
`readonly budget: Budget`
|
|
370
|
+
|
|
371
|
+
The library's own budget: [`resolveBudget(options.budget)`](#resolvebudgetbudget-limits). The fields
|
|
372
|
+
you set stay as set, and the others follow your `contextTokens` (see [`Budget`](#budget)). With no
|
|
373
|
+
`budget`, it equals [`DEFAULT_BUDGET`](#default_budget). It is not fitted to any model.
|
|
374
|
+
|
|
375
|
+
#### `files.budgetFor(overrides?, limits?)`
|
|
376
|
+
|
|
377
|
+
`budgetFor(overrides?: Partial<Budget>, limits?: ModelLimits): Budget`
|
|
378
|
+
|
|
379
|
+
The budget of one request: the fields the library was given, with `overrides` in their place, made
|
|
380
|
+
to fit `limits` (a model's context window and request size, when they are smaller). Fields that
|
|
381
|
+
neither sets follow the window that results. Without either argument it returns `files.budget`.
|
|
382
|
+
Throws as `resolveBudget` does. `askWithFiles` calls it with the limits its models declare.
|
|
383
|
+
|
|
384
|
+
Guide: [costs and limits](../guides/costs-and-limits.md).
|
|
385
|
+
|
|
386
|
+
#### `files.maxUploadBytes`
|
|
387
|
+
|
|
388
|
+
`readonly maxUploadBytes: number`
|
|
389
|
+
|
|
390
|
+
The upload limit in effect: `options.maxUploadBytes`, or 104,857,600 (100 MB).
|
|
391
|
+
|
|
392
|
+
### `IngestInput`
|
|
393
|
+
|
|
394
|
+
```ts
|
|
395
|
+
type IngestInput = {
|
|
396
|
+
name: string;
|
|
397
|
+
mimeType?: string;
|
|
398
|
+
bytes: Uint8Array;
|
|
399
|
+
owner?: string;
|
|
400
|
+
signal?: AbortSignal;
|
|
401
|
+
onEvent?: (event: IngestEvent) => void;
|
|
402
|
+
runId?: string;
|
|
403
|
+
};
|
|
404
|
+
```
|
|
405
|
+
|
|
406
|
+
The argument of [`files.ingest`](#filesingestinput).
|
|
407
|
+
|
|
408
|
+
| Field | Type | Default | What it does |
|
|
409
|
+
|---|---|---|---|
|
|
410
|
+
| `name` | `string` | required | The file name. It is cleaned to one printable line: the last segment of a path, with control characters, line breaks and text-direction controls replaced by spaces, the characters that show nothing removed as from the text (tag characters, zero-width spaces, word joiners, soft hyphens, a byte-order mark), runs of spaces made one, trimmed, and cut to 255 characters, never in the middle of a character (`"file"` when nothing is left; an emoji of several characters, such as a flag, can lose its end). With the MIME type it picks the format. |
|
|
411
|
+
| `mimeType` | `string` | `"application/octet-stream"` | The MIME type, trimmed. Blank counts as absent. Used when the extension names no format. |
|
|
412
|
+
| `bytes` | `Uint8Array` | required | The file. A Node `Buffer` is one. Empty, or larger than `maxUploadBytes`, is refused. |
|
|
413
|
+
| `owner` | `string` | none | The user or tenant the document belongs to. Every later call must pass the same owner. Without one, anyone who has the ID can use the document. It must be a string that is not empty or only spaces: `""`, spaces only and `null` throw a `TypeError` (see [`files.ingest`](#filesingestinput)), since each would be one owner shared by every caller without a user. A number from JavaScript is taken, as before. Reads with the owner `""` work as before. |
|
|
414
|
+
| `signal` | `AbortSignal` | none | Stops the ingest when it aborts, for example when the uploader goes away: `ingest` throws `signal.reason` and stores nothing. The PDF, DOCX and PPTX extractors stop between pages and pieces; `ingest` stops waiting for an extractor of your own at once. A signal that aborts once the store is being written changes nothing. `createDocumentHandlers` passes one that aborts when the client closes the connection before the answer. |
|
|
415
|
+
| `onEvent` | `(event: IngestEvent) => void` | none | What the ingest does as it goes: `ingest.start`, `ingest.progress` for each stage, then `ingest.finish` or `ingest.error` (see [`files.ingest`](#filesingestinput) and [events](./events.md)). Progress is worked out only when it is given. New in 0.7.0. |
|
|
416
|
+
| `runId` | `string` | `"ing_"` and 16 hex digits | The `runId` of those events. New in 0.7.0. |
|
|
417
|
+
|
|
418
|
+
Guide: [web app](../guides/web-app.md).
|
|
419
|
+
|
|
420
|
+
### `AccessOptions`
|
|
421
|
+
|
|
422
|
+
```ts
|
|
423
|
+
type AccessOptions = { owner?: string };
|
|
424
|
+
```
|
|
425
|
+
|
|
426
|
+
Who is asking. `getMeta`, `getOriginal`, `delete` and `prepare` (through
|
|
427
|
+
[`PrepareOptions`](#prepareoptions)) take it, and so does `askWithFiles`.
|
|
428
|
+
|
|
429
|
+
| Field | Type | Default | What it does |
|
|
430
|
+
|---|---|---|---|
|
|
431
|
+
| `owner` | `string` | none | Compared with the document's `owner` with `===`. A document that has an owner can be used only with that exact owner. A document without one can be used by anyone. Another owner's document looks exactly like a missing one. |
|
|
432
|
+
|
|
433
|
+
The library has no notion of a session and cannot list documents by owner: record the IDs in your
|
|
434
|
+
own data. See [storage](../guides/storage.md) and [security](../security.md).
|
|
435
|
+
|
|
436
|
+
### `PrepareOptions`
|
|
437
|
+
|
|
438
|
+
```ts
|
|
439
|
+
type PrepareOptions = AccessOptions & {
|
|
440
|
+
budget?: Partial<Budget>;
|
|
441
|
+
viewPages?: boolean;
|
|
442
|
+
wholeDocumentAnalysis?: boolean;
|
|
443
|
+
};
|
|
444
|
+
```
|
|
445
|
+
|
|
446
|
+
The options of [`files.prepare`](#filesprepareids-base-options).
|
|
447
|
+
|
|
448
|
+
| Option | Type | Default | What it does |
|
|
449
|
+
|---|---|---|---|
|
|
450
|
+
| `owner` | `string` | none | As in [`AccessOptions`](#accessoptions). Another owner's documents are listed in `missing` and are not read. |
|
|
451
|
+
| `budget` | `Partial<Budget>` | the library's | The budget fields to change for this request, as in `LargeFilesOptions.budget`. `askWithFiles` passes the budget fitted to its model. |
|
|
452
|
+
| `viewPages` | `boolean` | `false` | Says that your loop can pass files to the model. `viewable` then lists the PDFs whose original is kept (with a store that has `getOriginal`), and the instruction and the cards tell the model about `view_pages`. Without it, `viewable` is empty and nothing mentions `view_pages`. |
|
|
453
|
+
| `wholeDocumentAnalysis` | `boolean` | `true` | Says whether your tool set has `analyze_whole_document`. Pass `false` when you call `tools` without `generate`: the instruction then does not name it, and the cards do not offer a whole-file read or say that a file is too large for one. Each says `This file is NOT in your context. Use the document tools to search it and to read line ranges.` `askWithFiles` passes `false` when the model that explores has no `generateText`, and when its own `wholeDocumentAnalysis` is `false`. |
|
|
454
|
+
|
|
455
|
+
Guide: [your own adapter and loop](../guides/own-adapter-and-loop.md).
|
|
456
|
+
|
|
457
|
+
### `ToolOptions`
|
|
458
|
+
|
|
459
|
+
```ts
|
|
460
|
+
type ToolOptions = {
|
|
461
|
+
generate?: GenerateText;
|
|
462
|
+
onProgress?: ProgressListener;
|
|
463
|
+
signal?: AbortSignal;
|
|
464
|
+
regexBudgetMs?: number;
|
|
465
|
+
maxWholeDocumentReads?: number;
|
|
466
|
+
retry?: RetryOptions;
|
|
467
|
+
budget?: Partial<Budget>;
|
|
468
|
+
viewPages?: boolean | DocumentMeta[];
|
|
469
|
+
};
|
|
470
|
+
```
|
|
471
|
+
|
|
472
|
+
The options of [`files.tools`](#filestoolsdocuments-options).
|
|
473
|
+
|
|
474
|
+
| Option | Type | Default | What it does |
|
|
475
|
+
|---|---|---|---|
|
|
476
|
+
| `generate` | [`GenerateText`](./ask.md#generatetext) | none | A plain text completion. It enables `analyze_whole_document`, which reads a whole file in parts. The tool is declared only when at least one of the documents is small enough: about `maxMapChunks` parts or fewer. Without `generate`, pass `wholeDocumentAnalysis: false` to `prepare`, so that the instruction does not name the tool and the cards do not offer a whole-file read. |
|
|
477
|
+
| `onProgress` | [`ProgressListener`](#progresslistener) | none | Progress of whole-document reads, for status messages. |
|
|
478
|
+
| `signal` | `AbortSignal` | none | Stops searches and whole-document reads. Once it has aborted, a call that fails throws instead of answering `{ error }`. |
|
|
479
|
+
| `regexBudgetMs` | `number` | [`REGEX_BUDGET_MS`](./tools.md#regex_budget_ms), 6,000 | The most time, in milliseconds, that the regex searches of this tool set may take together. Past it, a regex search answers with an error that tells the model to search another way. One search stops after 3,000 ms on its own. |
|
|
480
|
+
| `maxWholeDocumentReads` | `number` | [`MAX_WHOLE_DOCUMENT_READS`](./tools.md#max_whole_document_reads), 1 | How many times each document may be read whole by this tool set. A call past it answers with an error that tells the model to use what it has. 0 turns whole reads off. |
|
|
481
|
+
| `retry` | [`RetryOptions`](./errors-and-retries.md#retryoptions) | 3 retries, a first wait of 250 to 500 ms (500 ms before the jitter) that doubles, 60 s at most | How a failed model request of a whole-document read is sent again. An error without an HTTP status is sent again once, at once. |
|
|
482
|
+
| `budget` | `Partial<Budget>` | the library's | The budget fields to change for these tools: their result cap and part size. Use the budget you planned the request with. |
|
|
483
|
+
| `viewPages` | `boolean \| DocumentMeta[]` | none | Offers `view_pages`, which hands the model real pages of a PDF as a file. `true` offers it for the PDFs among `documents`; a list offers it for exactly those, which may include PDFs whose text is already in the prompt: pass `prepared.viewable`. Only PDFs with `originalKept` count, and only with a store that has `getOriginal`. Turn it on only when your loop runs tools with `executeWithFiles` and sends the files to the model. |
|
|
484
|
+
|
|
485
|
+
Guide: [your own adapter and loop](../guides/own-adapter-and-loop.md).
|
|
486
|
+
|
|
487
|
+
### `PreparedContext`
|
|
488
|
+
|
|
489
|
+
```ts
|
|
490
|
+
type PreparedContext = {
|
|
491
|
+
plan: DocumentPlan;
|
|
492
|
+
blocks: Map<string, string>;
|
|
493
|
+
instruction: string;
|
|
494
|
+
missing: string[];
|
|
495
|
+
viewable: DocumentMeta[];
|
|
496
|
+
};
|
|
497
|
+
```
|
|
498
|
+
|
|
499
|
+
What [`files.prepare`](#filesprepareids-base-options) returns.
|
|
500
|
+
|
|
501
|
+
| Field | Type | What it holds |
|
|
502
|
+
|---|---|---|
|
|
503
|
+
| `plan` | [`DocumentPlan`](#documentplan) | Which documents go in whole and which are searched. |
|
|
504
|
+
| `blocks` | `Map<string, string>` | The prompt text of each document, by ID. For a document sent whole, its text between two frame lines (see below). For a searchable one, a card: its `document_id`, size, log profile, outline (up to 40 headings) and first 25 lines, and a line that says how a text file that was not valid UTF-8 was read. |
|
|
505
|
+
| `instruction` | `string` | The guide to the tools, for the system prompt, when a document is searchable or viewable; `""` otherwise. It names `analyze_whole_document` when a searchable file is small enough for it and `prepare` was not given `wholeDocumentAnalysis: false`. Then give `generate` to `tools`, or a call of it is answered as an unknown tool. |
|
|
506
|
+
| `missing` | `string[]` | The IDs that were not found: never uploaded, not a document ID, deleted, expired, or another owner's. |
|
|
507
|
+
| `viewable` | `DocumentMeta[]` | The PDFs whose pages `view_pages` can show, whether their text is in the prompt or searched. Empty unless `prepare` was called with `viewPages: true`. Pass it to `tools(..., { viewPages })`. |
|
|
508
|
+
|
|
509
|
+
A document sent whole sits between these two lines (new in 0.6.0, for every document):
|
|
510
|
+
|
|
511
|
+
```text
|
|
512
|
+
--- Attached file [mark <mark>]: <name> (<format>, <lines> lines<reading>; it ends only at the line with mark <mark>) ---
|
|
513
|
+
<the text>
|
|
514
|
+
--- End attached file [mark <mark>] ---
|
|
515
|
+
```
|
|
516
|
+
|
|
517
|
+
- `<mark>` is eight hex digits made from the document ID, the same in every request, so a
|
|
518
|
+
provider's prompt cache reuses the file. After an upgrade from 0.5.0, the first request of each
|
|
519
|
+
conversation reads nothing of the file from the cache, since the frame lines changed. The
|
|
520
|
+
file's own text cannot hold its mark: a line that
|
|
521
|
+
copies the end of the frame has no mark or a wrong one, and the first line tells the model that
|
|
522
|
+
only the line with the mark ends the file. This does not make the model obey, and the mark is
|
|
523
|
+
not a secret (see [Security](../security.md#the-frame-around-a-file)).
|
|
524
|
+
- `<name>` is the name as a JSON string (`"report.txt"`): a quote in it is escaped.
|
|
525
|
+
It comes after the mark, and the last line holds the mark alone, since the uploader chooses the
|
|
526
|
+
name along with the text.
|
|
527
|
+
- `<lines>` has commas in the en-US way (`3,000 lines`), and a file of one line says `1 line`.
|
|
528
|
+
- `<reading>`, for a text file that was not valid UTF-8, is `, read as windows-1255`, then, when
|
|
529
|
+
some characters were not valid in that encoding, `, 1 character not valid in it, shown as �`; or,
|
|
530
|
+
for a file read as UTF-8, `, 3 characters not valid UTF-8, shown as �`. It is empty for any other
|
|
531
|
+
file.
|
|
532
|
+
|
|
533
|
+
For example `--- Attached file [mark 1f0c3a9e]: "app.log" (log, 3,000 lines; it ends only at the line with mark 1f0c3a9e) ---`.
|
|
534
|
+
In 0.5.0 the lines were `--- Attached file: app.log (log, 3,000 lines) ---` and
|
|
535
|
+
`--- End attached file: app.log ---`. Code or tests that look for one file in `blocks` or in a
|
|
536
|
+
request can look for `]: `, then `JSON.stringify(name)`, then ` (`; `--- Attached file [mark `
|
|
537
|
+
starts every frame.
|
|
538
|
+
|
|
539
|
+
A card starts with `--- Large attached file: <name> ---`, as before. Its third line is
|
|
540
|
+
`<format> · <size> · <lines> lines · <pages> pages · about <tokens> tokens`, with `1 line` and
|
|
541
|
+
`1 page` for one. For a text file that was not valid UTF-8, a line after the way to read it says
|
|
542
|
+
`This file is not in UTF-8. Its text was read as windows-1255: if its letters look wrong, ask the user to save it as UTF-8.`,
|
|
543
|
+
followed, when some characters were not valid in it, by
|
|
544
|
+
` 3 characters of it were not valid in windows-1255, and show as �.`; or, for a file read as UTF-8,
|
|
545
|
+
`3 characters of this file were not valid UTF-8, and show as �.` For one character:
|
|
546
|
+
`1 character of it was not valid in windows-1255, and shows as �.` and
|
|
547
|
+
`1 character of this file was not valid UTF-8, and shows as �.`
|
|
548
|
+
|
|
549
|
+
Guide: [your own adapter and loop](../guides/own-adapter-and-loop.md).
|
|
550
|
+
|
|
551
|
+
### `DocumentPlan`
|
|
552
|
+
|
|
553
|
+
```ts
|
|
554
|
+
type DocumentPlan = { inline: DocumentMeta[]; searchable: DocumentMeta[]; inlineTokens: number; inlineBytes: number };
|
|
555
|
+
```
|
|
556
|
+
|
|
557
|
+
| Field | Type | What it holds |
|
|
558
|
+
|---|---|---|
|
|
559
|
+
| `inline` | `DocumentMeta[]` | The documents whose full text goes into the prompt, smallest first. |
|
|
560
|
+
| `searchable` | `DocumentMeta[]` | The documents the model reaches only through the tools. |
|
|
561
|
+
| `inlineTokens` | `number` | The `estimatedTokens` of the inline documents, added up. |
|
|
562
|
+
| `inlineBytes` | `number` | What the inline documents take in a JSON request body: for each, its `jsonBytes` (or `textBytes` × 1.08 when that is absent) plus 200. |
|
|
563
|
+
|
|
564
|
+
Guide: [your own adapter and loop](../guides/own-adapter-and-loop.md).
|
|
565
|
+
|
|
566
|
+
### `DEFAULT_CACHE_BYTES`
|
|
567
|
+
|
|
568
|
+
```ts
|
|
569
|
+
declare const DEFAULT_CACHE_BYTES: number; // 268_435_456 (256 MB)
|
|
570
|
+
```
|
|
571
|
+
|
|
572
|
+
The default of `LargeFilesOptions.cacheBytes`.
|
|
573
|
+
|
|
574
|
+
### `DEFAULT_WHOLE_DOCUMENT_BYTES`
|
|
575
|
+
|
|
576
|
+
```ts
|
|
577
|
+
declare const DEFAULT_WHOLE_DOCUMENT_BYTES: number; // 2_097_152 (2 MB)
|
|
578
|
+
```
|
|
579
|
+
|
|
580
|
+
The default of `LargeFilesOptions.wholeDocumentBytes`.
|
|
581
|
+
|
|
582
|
+
### `DEFAULT_MAX_PDF_PAGES`
|
|
583
|
+
|
|
584
|
+
```ts
|
|
585
|
+
declare const DEFAULT_MAX_PDF_PAGES = 5000;
|
|
586
|
+
```
|
|
587
|
+
|
|
588
|
+
The default of `LargeFilesOptions.maxPdfPages`. New in 0.6.0.
|
|
589
|
+
|
|
590
|
+
### `DEFAULT_MAX_TEXT_BYTES`
|
|
591
|
+
|
|
592
|
+
```ts
|
|
593
|
+
declare const DEFAULT_MAX_TEXT_BYTES: number; // 104_857_600 (100 MB)
|
|
594
|
+
```
|
|
595
|
+
|
|
596
|
+
The default of `LargeFilesOptions.maxTextBytes`, when `maxUploadBytes` is not larger. New in
|
|
597
|
+
0.6.0.
|
|
598
|
+
|
|
599
|
+
### `DEFAULT_INGEST_TIMEOUT_MS`
|
|
600
|
+
|
|
601
|
+
```ts
|
|
602
|
+
declare const DEFAULT_INGEST_TIMEOUT_MS = 120000; // 2 minutes
|
|
603
|
+
```
|
|
604
|
+
|
|
605
|
+
The default of `LargeFilesOptions.ingestTimeoutMs`. New in 0.6.0.
|
|
606
|
+
|
|
607
|
+
### `NEVER_EXPIRES`
|
|
608
|
+
|
|
609
|
+
```ts
|
|
610
|
+
declare const NEVER_EXPIRES = "9999-12-31T23:59:59.999Z";
|
|
611
|
+
```
|
|
612
|
+
|
|
613
|
+
The `expiresAt` of a document ingested with `ttlMs: Infinity`, or with any time to live that would
|
|
614
|
+
end at or after this instant. It is a date, so that every comparison, and a server of an older version,
|
|
615
|
+
reads it as any other.
|
|
616
|
+
|
|
617
|
+
### isDocumentId(value)
|
|
618
|
+
|
|
619
|
+
```ts
|
|
620
|
+
declare function isDocumentId(value: unknown): value is string;
|
|
621
|
+
```
|
|
622
|
+
|
|
623
|
+
`true` for a string that matches [`DOCUMENT_ID_PATTERN`](#document_id_pattern). Use it to check IDs
|
|
624
|
+
that come from a browser. The library's own methods already treat any other string as a missing
|
|
625
|
+
document.
|
|
626
|
+
|
|
627
|
+
### toDocumentSummary(meta)
|
|
628
|
+
|
|
629
|
+
```ts
|
|
630
|
+
declare function toDocumentSummary(meta: DocumentMeta): DocumentSummary;
|
|
631
|
+
```
|
|
632
|
+
|
|
633
|
+
The fields of a document that are safe to send to a browser (see
|
|
634
|
+
[`DocumentSummary`](#documentsummary)). `pages` is included only when the document has pages, and
|
|
635
|
+
`encoding` and `replacedCharacters` only when they are set. The handlers of
|
|
636
|
+
[`llm-large-files/node`](./node.md) answer with it.
|
|
637
|
+
|
|
638
|
+
## The budget
|
|
639
|
+
|
|
640
|
+
### `Budget`
|
|
641
|
+
|
|
642
|
+
```ts
|
|
643
|
+
type Budget = {
|
|
644
|
+
contextTokens: number;
|
|
645
|
+
maxRequestBytes: number;
|
|
646
|
+
inlineTokens: number;
|
|
647
|
+
reservedTokens: number;
|
|
648
|
+
mapChunkTokens: number;
|
|
649
|
+
maxMapChunks: number;
|
|
650
|
+
toolResultCharacters: number;
|
|
651
|
+
};
|
|
652
|
+
```
|
|
653
|
+
|
|
654
|
+
The limits of the model connection that the documents must fit through. A field you leave out
|
|
655
|
+
follows the context window, so for a model with a smaller window, setting `contextTokens` is enough.
|
|
656
|
+
|
|
657
|
+
| Field | Default | Left out, it is | What it does |
|
|
658
|
+
|---|---|---|---|
|
|
659
|
+
| `contextTokens` | 1,000,000 | 1,000,000, or a model's smaller window | The model's context window, in tokens. |
|
|
660
|
+
| `maxRequestBytes` | 10,000,000 | 10,000,000, or a model's smaller limit | The largest request body your model connection accepts, in bytes. It is checked apart from tokens: non-English text and JSON escapes make bytes grow faster than tokens. |
|
|
661
|
+
| `inlineTokens` | 200,000 | half the window, 200,000 at most | The most document text sent whole in one request, in tokens. |
|
|
662
|
+
| `reservedTokens` | 64,000 | a quarter of the window, 64,000 at most | Tokens kept free for the answer, tool results and the growing conversation. Must be smaller than `contextTokens`. |
|
|
663
|
+
| `mapChunkTokens` | 100,000 | half the window, 100,000 at most | The size of each part when a whole document is read in parts. Must be smaller than `contextTokens`. |
|
|
664
|
+
| `maxMapChunks` | 30 | 30 | A whole-document read that needs more parts than this is refused. It counts parts: combining the notes and writing the answer are further model requests. `analyze_whole_document` is offered only for files whose estimate is within it, with 5% to spare. |
|
|
665
|
+
| `toolResultCharacters` | 24,000 | 12% of the window, between 1,000 and 24,000 | The cap on the characters of one tool result sent back to the model. The answer of `analyze_whole_document` may take up to 40,000 when this is lower. |
|
|
666
|
+
|
|
667
|
+
A field you set stays as you set it, except against a model's own limits
|
|
668
|
+
([`ModelLimits`](#modellimits)). `maxRequestBytes` drops to a model's smaller request size. When a
|
|
669
|
+
model's window is smaller than the one the values were given for, `contextTokens` drops to it and
|
|
670
|
+
the other values are lowered to fit it: `inlineTokens` to at most the window, `reservedTokens` and `mapChunkTokens` to at
|
|
671
|
+
most half of it, and `toolResultCharacters` to at most the window (at least 1,000). `maxMapChunks`
|
|
672
|
+
never changes.
|
|
673
|
+
|
|
674
|
+
Guide: [costs and limits](../guides/costs-and-limits.md).
|
|
675
|
+
|
|
676
|
+
### `DEFAULT_BUDGET`
|
|
677
|
+
|
|
678
|
+
```ts
|
|
679
|
+
declare const DEFAULT_BUDGET: Budget;
|
|
680
|
+
// { contextTokens: 1_000_000, maxRequestBytes: 10_000_000, inlineTokens: 200_000, reservedTokens: 64_000,
|
|
681
|
+
// mapChunkTokens: 100_000, maxMapChunks: 30, toolResultCharacters: 24_000 }
|
|
682
|
+
```
|
|
683
|
+
|
|
684
|
+
The budget when nothing is set: a model with a 1M-token window behind a 10 MB request limit. It is
|
|
685
|
+
what `resolveBudget()` returns.
|
|
686
|
+
|
|
687
|
+
### resolveBudget(budget?, limits?)
|
|
688
|
+
|
|
689
|
+
```ts
|
|
690
|
+
declare function resolveBudget(budget?: Partial<Budget>, limits?: ModelLimits): Budget;
|
|
691
|
+
```
|
|
692
|
+
|
|
693
|
+
A whole [`Budget`](#budget) from the fields that are given, by the rules in its table. A field set to
|
|
694
|
+
`undefined` counts as not given. With `limits`, the smaller window and the smaller request size
|
|
695
|
+
hold, the fields left out follow that window, and the given ones are lowered to fit it.
|
|
696
|
+
|
|
697
|
+
| It throws | When |
|
|
698
|
+
|---|---|
|
|
699
|
+
| `Error("budget.<field> must be a number above 0, and is <value>.")` | A given field is not a finite number above 0: 0, a negative number, `NaN`, `Infinity`, a string. |
|
|
700
|
+
| `Error("budget.reservedTokens (<n>) must be smaller than budget.contextTokens (<n>): nothing would be left for the conversation.")` | `reservedTokens` is at or above `contextTokens`. |
|
|
701
|
+
| `Error("budget.mapChunkTokens (<n>) must be smaller than budget.contextTokens (<n>): a part of a whole-file read would not fit the model.")` | `mapChunkTokens` is at or above `contextTokens`. |
|
|
702
|
+
|
|
703
|
+
```ts
|
|
704
|
+
import { resolveBudget } from "llm-large-files";
|
|
705
|
+
|
|
706
|
+
resolveBudget({ contextTokens: 128_000 });
|
|
707
|
+
// { contextTokens: 128000, maxRequestBytes: 10000000, inlineTokens: 64000, reservedTokens: 32000,
|
|
708
|
+
// mapChunkTokens: 64000, maxMapChunks: 30, toolResultCharacters: 15360 }
|
|
709
|
+
|
|
710
|
+
resolveBudget({ inlineTokens: 150_000 }, { contextTokens: 100_000, maxRequestBytes: 4_000_000 });
|
|
711
|
+
// { contextTokens: 100000, maxRequestBytes: 4000000, inlineTokens: 100000, reservedTokens: 25000,
|
|
712
|
+
// mapChunkTokens: 50000, maxMapChunks: 30, toolResultCharacters: 12000 }
|
|
713
|
+
```
|
|
714
|
+
|
|
715
|
+
### `ModelLimits`
|
|
716
|
+
|
|
717
|
+
```ts
|
|
718
|
+
type ModelLimits = { contextTokens?: number | undefined; maxRequestBytes?: number | undefined };
|
|
719
|
+
```
|
|
720
|
+
|
|
721
|
+
A model's own limits, which a budget must stay within. `resolveBudget` and `files.budgetFor` take
|
|
722
|
+
it. `askWithFiles` builds it from what its adapters declare in
|
|
723
|
+
[`ModelCapabilities`](./ask.md#modelcapabilities).
|
|
724
|
+
|
|
725
|
+
| Field | Type | Default | What it does |
|
|
726
|
+
|---|---|---|---|
|
|
727
|
+
| `contextTokens` | `number \| undefined` | none | The model's context window. When it is smaller than the budget's, it holds: the fields left out follow it, and the given ones are lowered to fit it. Ignored unless it is a finite number above 0. |
|
|
728
|
+
| `maxRequestBytes` | `number \| undefined` | none | The largest request the model takes. The smaller of this and the budget's holds. Ignored unless it is a finite number above 0. |
|
|
729
|
+
|
|
730
|
+
## Stores
|
|
731
|
+
|
|
732
|
+
### `DocumentStore`
|
|
733
|
+
|
|
734
|
+
```ts
|
|
735
|
+
interface DocumentStore {
|
|
736
|
+
put(document: StoredDocument): Promise<void>;
|
|
737
|
+
get(id: string): Promise<StoredDocument | undefined>;
|
|
738
|
+
getMeta(id: string): Promise<DocumentMeta | undefined>;
|
|
739
|
+
delete(id: string): Promise<boolean>;
|
|
740
|
+
sweep?(now?: Date): Promise<number>;
|
|
741
|
+
putOriginal?(id: string, bytes: Uint8Array): Promise<void>;
|
|
742
|
+
getOriginal?(id: string): Promise<Uint8Array | undefined>;
|
|
743
|
+
readTextRange?(id: string, start: number, end: number): Promise<Uint8Array | undefined>;
|
|
744
|
+
putIndex?(id: string, index: Uint8Array): Promise<void>;
|
|
745
|
+
getIndex?(id: string): Promise<Uint8Array | undefined>;
|
|
746
|
+
}
|
|
747
|
+
```
|
|
748
|
+
|
|
749
|
+
Where the extracted text lives, with its metadata, and optionally the uploaded file and a line
|
|
750
|
+
index. Use [`MemoryDocumentStore`](#memorydocumentstore) or [`FileDocumentStore`](#filedocumentstore),
|
|
751
|
+
or implement it over a database, Redis or S3.
|
|
752
|
+
|
|
753
|
+
| Method | Required | What it must do, and when the library calls it |
|
|
754
|
+
|---|---|---|
|
|
755
|
+
| `put(document)` | yes | Store the text and the metadata. Called last at ingest. A document should exist once its metadata does: `FileDocumentStore` writes the metadata last. Keep every field of `meta`, the optional ones too, and those a later version adds (0.6.0 added `encoding` and `replacedCharacters`): a store that keeps a fixed list of fields loses them, and one that checks `meta` against a fixed schema refuses the ingest of every file that has them. |
|
|
756
|
+
| `get(id)` | yes | The whole document, or `undefined` when there is no such document. It may return an expired one: the library checks `expiresAt` itself. Called to load a document whole: its text is at most `wholeDocumentBytes`, or the store has no `readTextRange`. |
|
|
757
|
+
| `getMeta(id)` | yes | The metadata, or `undefined` when there is no such document (an expired one may be returned; the library checks `expiresAt`). Called by every `prepare`, `getMeta`, `getOriginal` and `delete`, and by every tool call: keep it cheap, apart from the text. |
|
|
758
|
+
| `delete(id)` | yes | Remove the document, its original and its index, and return whether it existed. Also called by `ingest` after a failed write, so it must cope with a document that was written only in part. |
|
|
759
|
+
| `sweep(now?)` | no | Remove the documents expired at `now` (with their originals and indexes) and return how many. Without it, `files.sweep()` returns 0; expire the data another way, such as a TTL index of your database. |
|
|
760
|
+
| `putOriginal(id, bytes)` | no | Keep the uploaded file. Called at ingest, before `putIndex` and `put`, for the formats in `keepOriginals`. Without it, no original is kept, whatever `keepOriginals` says. |
|
|
761
|
+
| `getOriginal(id)` | no | The kept file, or `undefined` when none was kept or there is no such document. Without it, `view_pages` is never offered. |
|
|
762
|
+
| `readTextRange(id, start, end)` | no | Bytes `start` (inclusive) to `end` (exclusive) of the text exactly as given to `put`, as UTF-8: the line index is built from those bytes. Return fewer bytes at the end of the text, and `undefined` when the document is gone. Called only after `getMeta` found the document. Without it, every document is loaded whole. |
|
|
763
|
+
| `putIndex(id, index)` | no | Keep the line index of a document (a few bytes a line). Called at ingest before `put`, and when a document ingested without an index is first read by range (an error then is ignored). Without it, the index is built from the text each time a large document is opened. |
|
|
764
|
+
| `getIndex(id)` | no | The index kept by `putIndex`, or `undefined`. A damaged one is noticed and built again. An error is taken as no index. |
|
|
765
|
+
|
|
766
|
+
Errors:
|
|
767
|
+
|
|
768
|
+
- Return `undefined` (or `false` from `delete`) only when the document is not there. Throw for
|
|
769
|
+
anything else: a volume that does not answer, a database that is down. What `get`, `getMeta`,
|
|
770
|
+
`readTextRange` and `getOriginal` throw reaches the caller as
|
|
771
|
+
[`DocumentStoreError`](#documentstoreerror), so that it retries instead of telling a user that the
|
|
772
|
+
file is gone. A `DocumentStoreError` you throw yourself is passed on as it is.
|
|
773
|
+
- What `put`, `putOriginal` and `putIndex` throw at ingest is thrown by `ingest` unchanged, after it
|
|
774
|
+
calls `delete(id)`. What `delete` and `sweep` throw is passed on unchanged.
|
|
775
|
+
- The library compares `expiresAt` with its clock itself, so an expired document is never used. The
|
|
776
|
+
store must still remove it, in `sweep` or by its own expiry.
|
|
777
|
+
|
|
778
|
+
The library makes the IDs (see [`DOCUMENT_ID_PATTERN`](#document_id_pattern)), and every method
|
|
779
|
+
except `put` receives only the ID: no owner, no metadata. A store that lays documents out per user
|
|
780
|
+
or per chat session needs its own way from an ID to a place.
|
|
781
|
+
|
|
782
|
+
Guide: [storage](../guides/storage.md), which also shows a store of your own.
|
|
783
|
+
|
|
784
|
+
### `StoredDocument`
|
|
785
|
+
|
|
786
|
+
```ts
|
|
787
|
+
type StoredDocument = { meta: DocumentMeta; text: string };
|
|
788
|
+
```
|
|
789
|
+
|
|
790
|
+
What a store keeps for a document, and what `put` receives and `get` returns.
|
|
791
|
+
|
|
792
|
+
| Field | Type | What it holds |
|
|
793
|
+
|---|---|---|
|
|
794
|
+
| `meta` | [`DocumentMeta`](#documentmeta) | The metadata. |
|
|
795
|
+
| `text` | `string` | The extracted, normalized text. Keep it byte for byte: `readTextRange` must return ranges of exactly this text as UTF-8. |
|
|
796
|
+
|
|
797
|
+
### `MemoryDocumentStore`
|
|
798
|
+
|
|
799
|
+
```ts
|
|
800
|
+
declare class MemoryDocumentStore implements DocumentStore {
|
|
801
|
+
constructor(options?: { now?: () => Date });
|
|
802
|
+
put(document: StoredDocument): Promise<void>;
|
|
803
|
+
get(id: string): Promise<StoredDocument | undefined>;
|
|
804
|
+
getMeta(id: string): Promise<DocumentMeta | undefined>;
|
|
805
|
+
delete(id: string): Promise<boolean>;
|
|
806
|
+
sweep(now?: Date): Promise<number>;
|
|
807
|
+
putOriginal(id: string, bytes: Uint8Array): Promise<void>;
|
|
808
|
+
getOriginal(id: string): Promise<Uint8Array | undefined>;
|
|
809
|
+
}
|
|
810
|
+
```
|
|
811
|
+
|
|
812
|
+
Keeps documents, and kept originals, in the memory of the process: for tests, scripts and
|
|
813
|
+
one-process demos. They are lost on restart and not shared between processes. It has no
|
|
814
|
+
`readTextRange`, so every document is loaded whole, whatever `wholeDocumentBytes` says. `get` and
|
|
815
|
+
`getMeta` remove an expired document and return `undefined`. `putOriginal` keeps a copy of the
|
|
816
|
+
bytes, so the caller may reuse its buffer. The metadata is copied too, on the way in (`put`) and
|
|
817
|
+
on the way out (`get`, `getMeta`), as a store that writes it somewhere does: changing the metadata
|
|
818
|
+
that `ingest` or `getMeta` returned (deleting its `owner` before it goes to a browser, say) changes
|
|
819
|
+
nothing stored. Until 0.6.0 it handed out its own object. `getOriginal` returns the kept bytes
|
|
820
|
+
themselves: treat them as read-only.
|
|
821
|
+
|
|
822
|
+
| Option | Type | Default | What it does |
|
|
823
|
+
|---|---|---|---|
|
|
824
|
+
| `now` | `() => Date` | `() => new Date()` | The clock that decides expiry, and the default `now` of `sweep`. |
|
|
825
|
+
|
|
826
|
+
Guide: [testing](../guides/testing.md).
|
|
827
|
+
|
|
828
|
+
### `FileDocumentStore`
|
|
829
|
+
|
|
830
|
+
```ts
|
|
831
|
+
declare class FileDocumentStore implements DocumentStore {
|
|
832
|
+
constructor(directory: string, options?: { now?: () => Date; orphanAgeMs?: number });
|
|
833
|
+
put(document: StoredDocument): Promise<void>;
|
|
834
|
+
get(id: string): Promise<StoredDocument | undefined>;
|
|
835
|
+
getMeta(id: string): Promise<DocumentMeta | undefined>;
|
|
836
|
+
delete(id: string): Promise<boolean>;
|
|
837
|
+
sweep(now?: Date): Promise<number>;
|
|
838
|
+
putOriginal(id: string, bytes: Uint8Array): Promise<void>;
|
|
839
|
+
getOriginal(id: string): Promise<Uint8Array | undefined>;
|
|
840
|
+
readTextRange(id: string, start: number, end: number): Promise<Uint8Array | undefined>;
|
|
841
|
+
putIndex(id: string, index: Uint8Array): Promise<void>;
|
|
842
|
+
getIndex(id: string): Promise<Uint8Array | undefined>;
|
|
843
|
+
}
|
|
844
|
+
```
|
|
845
|
+
|
|
846
|
+
Keeps each document as files in one directory, so documents survive a restart, and several servers
|
|
847
|
+
can share the directory on a network volume. It has every method, `readTextRange`, `putIndex` and
|
|
848
|
+
`getIndex` included, so large documents are read by range.
|
|
849
|
+
|
|
850
|
+
| File | What it holds |
|
|
851
|
+
|---|---|
|
|
852
|
+
| `<id>.json` | The metadata. A document exists while this file does. |
|
|
853
|
+
| `<id>.txt` | The text, as UTF-8. |
|
|
854
|
+
| `<id>.idx` | The line index. |
|
|
855
|
+
| `<id>.bin` | The uploaded file, when it is kept. |
|
|
856
|
+
|
|
857
|
+
- The directory is created at the first write.
|
|
858
|
+
- Every file is written under a temporary name (`<file>.<8 hex digits>.tmp`) and then renamed, so
|
|
859
|
+
no server reads half a file. A rename that meets `EPERM`, `EACCES` or `EBUSY` (on Windows, another
|
|
860
|
+
process has the file open for a moment) is tried again, for about 2.6 seconds in all.
|
|
861
|
+
- `put` writes the text, then the metadata. `put`, `putOriginal` and `putIndex` throw
|
|
862
|
+
`Error("Invalid document ID.")` for an ID that does not match `DOCUMENT_ID_PATTERN`; for such an
|
|
863
|
+
ID the reads return `undefined` and `delete` returns `false`. Only matching IDs reach the file system.
|
|
864
|
+
- `getMeta` returns `undefined` when the metadata file is missing or cannot be parsed (damaged, or
|
|
865
|
+
being written by a server of 0.3.x), and removes an expired document and returns `undefined`.
|
|
866
|
+
`get`, `readTextRange` and `getOriginal` return `undefined` for a missing file. Any other failure
|
|
867
|
+
of a read is thrown. `getIndex` returns `undefined` for any failure.
|
|
868
|
+
- `delete` removes the metadata first, then the text, the index and the original, and returns
|
|
869
|
+
whether the metadata existed. When the metadata cannot be removed, nothing else is, and the
|
|
870
|
+
document stays whole.
|
|
871
|
+
- `sweep(now?)` removes expired documents and returns how many, counting a document whose metadata
|
|
872
|
+
is not valid and is older than `orphanAgeMs`. It also removes files that belong to no document,
|
|
873
|
+
and temporary files, once they are older than `orphanAgeMs` (these are not counted). A document
|
|
874
|
+
whose metadata could not be read at all, or that could not be removed, is left for the next
|
|
875
|
+
sweep. When the directory cannot be read, it returns 0.
|
|
876
|
+
|
|
877
|
+
| Option | Type | Default | What it does |
|
|
878
|
+
|---|---|---|---|
|
|
879
|
+
| `now` | `() => Date` | `() => new Date()` | The clock that decides expiry, and the default `now` of `sweep`. |
|
|
880
|
+
| `orphanAgeMs` | `number` | 3,600,000 (1 hour) | `sweep` removes files that belong to no document (an upload that failed, a server that stopped while writing) and temporary files only once they are this old. Younger ones may be an upload in progress, on this server or another one. |
|
|
881
|
+
|
|
882
|
+
Guides: [storage](../guides/storage.md), [deployment](../guides/deployment.md).
|
|
883
|
+
|
|
884
|
+
### `DOCUMENT_ID_PATTERN`
|
|
885
|
+
|
|
886
|
+
```ts
|
|
887
|
+
declare const DOCUMENT_ID_PATTERN: RegExp; // /^doc_[a-f0-9]{32}$/
|
|
888
|
+
```
|
|
889
|
+
|
|
890
|
+
The shape of every document ID that `ingest` makes: `doc_` and 32 lowercase hexadecimal digits
|
|
891
|
+
(a random UUID without its dashes). [`isDocumentId`](#isdocumentidvalue) tests a value against it.
|
|
892
|
+
|
|
893
|
+
### `DocumentStoreError`
|
|
894
|
+
|
|
895
|
+
```ts
|
|
896
|
+
declare class DocumentStoreError extends Error {
|
|
897
|
+
readonly code?: string;
|
|
898
|
+
readonly syscall?: string;
|
|
899
|
+
constructor(cause: unknown);
|
|
900
|
+
}
|
|
901
|
+
```
|
|
902
|
+
|
|
903
|
+
The store could not be read just now: a volume that did not answer, too many open files, a database
|
|
904
|
+
that is down. It does not mean that the document is gone, and the same call may work a moment
|
|
905
|
+
later: retry it, rather than ask the user to upload the file again.
|
|
906
|
+
|
|
907
|
+
| Field | Type | What it holds |
|
|
908
|
+
|---|---|---|
|
|
909
|
+
| `name` | `string` | `"DocumentStoreError"`. |
|
|
910
|
+
| `message` | `string` | `The document store could not be read (<code>). Try again.`, or without the code when there is none. It names no path and no host: it is safe to show to a user or a model. |
|
|
911
|
+
| `code` | `string \| undefined` | The code of the system error behind it (`EIO`, `EMFILE`, `ETIMEDOUT`), when there is one. |
|
|
912
|
+
| `syscall` | `string \| undefined` | The system call that failed (`open`, `read`), when there is one. |
|
|
913
|
+
| `cause` | `unknown` | What the store threw. Log it on the server; it may name a path or a host. |
|
|
914
|
+
|
|
915
|
+
`files.getMeta`, `files.getOriginal`, `files.delete` (its look-up) and `files.prepare` throw it,
|
|
916
|
+
and so does `askWithFiles`. A tool call that meets it answers the model with its message instead of
|
|
917
|
+
throwing. Errors of writes are never wrapped in it (see [`DocumentStore`](#documentstore)).
|
|
918
|
+
|
|
919
|
+
```ts
|
|
920
|
+
import { DocumentStoreError, toDocumentSummary, type LargeFiles } from "llm-large-files";
|
|
921
|
+
|
|
922
|
+
// `files` is your library.
|
|
923
|
+
async function documentSummary(files: LargeFiles, id: string, owner: string) {
|
|
924
|
+
try {
|
|
925
|
+
const meta = await files.getMeta(id, { owner });
|
|
926
|
+
return meta ? { status: 200, body: toDocumentSummary(meta) } : { status: 404, body: { error: "Not found." } };
|
|
927
|
+
} catch (error) {
|
|
928
|
+
if (!(error instanceof DocumentStoreError)) throw error;
|
|
929
|
+
console.error(error.cause); // what the store threw: for your log only
|
|
930
|
+
return { status: 503, body: { error: error.message } };
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
```
|
|
934
|
+
|
|
935
|
+
Guide: [errors and reliability](../guides/errors-and-reliability.md).
|
|
936
|
+
|
|
937
|
+
## Extraction
|
|
938
|
+
|
|
939
|
+
### `Extractor`
|
|
940
|
+
|
|
941
|
+
```ts
|
|
942
|
+
type Extractor = (bytes: Uint8Array, input: ExtractInput) => Promise<ExtractedText>;
|
|
943
|
+
```
|
|
944
|
+
|
|
945
|
+
Turns the bytes of an uploaded file into text, for one format. To refuse a file, throw an `Error`
|
|
946
|
+
whose message a user can read: `ingest` passes it on unchanged. The library then normalizes the
|
|
947
|
+
text, splits long lines and refuses blank text, as described under
|
|
948
|
+
[`files.ingest`](#filesingestinput). For a PDF, write a line `--- Page N ---` before the text of
|
|
949
|
+
each page, counting from 1, as the built-in one does: the page numbers in tool results and
|
|
950
|
+
`view_pages` are read from those lines.
|
|
951
|
+
|
|
952
|
+
```ts
|
|
953
|
+
import { createLargeFiles, defaultExtractors, MemoryDocumentStore, type Extractor } from "llm-large-files";
|
|
954
|
+
|
|
955
|
+
// An .html file is detected as "text". This extractor drops its tags before the text is stored.
|
|
956
|
+
const text: Extractor = async (bytes, input) => {
|
|
957
|
+
const extracted = await defaultExtractors.text(bytes, input);
|
|
958
|
+
if (!input.name.toLowerCase().endsWith(".html")) return extracted;
|
|
959
|
+
return { text: extracted.text.replace(/<script[\s\S]*?<\/script>|<style[\s\S]*?<\/style>|<[^>]+>/gi, " ") };
|
|
960
|
+
};
|
|
961
|
+
|
|
962
|
+
const files = createLargeFiles({ store: new MemoryDocumentStore(), extractors: { text } });
|
|
963
|
+
```
|
|
964
|
+
|
|
965
|
+
Guide: [PDFs](../guides/pdfs.md), for OCR and other PDF extractors.
|
|
966
|
+
|
|
967
|
+
### `ExtractInput`
|
|
968
|
+
|
|
969
|
+
```ts
|
|
970
|
+
type ExtractInput = {
|
|
971
|
+
name: string;
|
|
972
|
+
mimeType: string;
|
|
973
|
+
format: DocumentFormat;
|
|
974
|
+
scannedPages?: number;
|
|
975
|
+
signal?: AbortSignal;
|
|
976
|
+
maxTextBytes?: number;
|
|
977
|
+
maxPages?: number;
|
|
978
|
+
onProgress?: (progress: ExtractProgress) => void;
|
|
979
|
+
};
|
|
980
|
+
```
|
|
981
|
+
|
|
982
|
+
| Field | Type | What it holds |
|
|
983
|
+
|---|---|---|
|
|
984
|
+
| `name` | `string` | The cleaned file name (see [`IngestInput`](#ingestinput)). |
|
|
985
|
+
| `mimeType` | `string` | The MIME type, `"application/octet-stream"` when none was given. |
|
|
986
|
+
| `format` | [`DocumentFormat`](#documentformat) | The format from `detectFormat`. A text file that turns out to be a log is still `"text"` here: logs are recognized after extraction. |
|
|
987
|
+
| `scannedPages` | `number \| undefined` | Set for a PDF when one without any text may be accepted: `"pdf"` is in `keepOriginals`, the store has `putOriginal`, and `scannedPdfPages` is above 0. It is the most pages such a PDF may have. Unset, a PDF without text is to be refused. An extractor of your own may ignore it. |
|
|
988
|
+
| `signal` | `AbortSignal \| undefined` | The signal of the ingest: aborted after `ingestTimeoutMs`, or when `IngestInput.signal` aborts. Its `reason` is the error to throw. The PDF, DOCX and PPTX extractors stop between pages and pieces. The text extractor decodes valid UTF-8 and UTF-16 in one step, and a file that is not valid UTF-8 a step at a time, whatever it is read in, stopping between two steps. `ingest` sets it, and stops waiting for your extractor when it aborts, but cannot stop the work your extractor does: pass it on (to `fetch`, for example), or check it between steps with `signal.throwIfAborted()`. |
|
|
989
|
+
| `maxTextBytes` | `number \| undefined` | `LargeFilesOptions.maxTextBytes`: the most text to keep, in UTF-8 bytes. `ingest` sets it, and refuses a larger text from any extractor once it returns. An extractor that refuses as soon as its text grows past it spares the memory. |
|
|
990
|
+
| `maxPages` | `number \| undefined` | `LargeFilesOptions.maxPdfPages`: the most pages to read from one PDF. `ingest` sets it for every format; only the built-in PDF extractor uses it. `ingest` does not check it for you. |
|
|
991
|
+
| `onProgress` | `((progress: ExtractProgress) => void) \| undefined` | Call it as the extraction goes on, so that `ingest` can report progress ([`ExtractProgress`](#extractprogress)). Set only when someone listens to the ingest's events (`IngestInput.onEvent`). The built-in extractors call it for each page of a PDF and each part of a DOCX or PPTX. An extractor of your own may ignore it: the ingest then sends no `extract` progress. What it reports after it returned is dropped. It can throw, when the listener of the events throws: let that error end the extraction. New in 0.7.0. |
|
|
992
|
+
|
|
993
|
+
### `ExtractProgress`
|
|
994
|
+
|
|
995
|
+
```ts
|
|
996
|
+
type ExtractProgress = {
|
|
997
|
+
stage?: "extract" | "check" | "pictures" | "decode";
|
|
998
|
+
done: number;
|
|
999
|
+
total?: number;
|
|
1000
|
+
unit: "pages" | "parts" | "bytes";
|
|
1001
|
+
};
|
|
1002
|
+
```
|
|
1003
|
+
|
|
1004
|
+
New in 0.7.0. How far an extraction is, for `ExtractInput.onProgress`. Each call becomes an
|
|
1005
|
+
`ingest.progress` event of that stage, at most one about every 12 ms for each stage, and the last
|
|
1006
|
+
one when the stage ends. A call whose `stage` or `unit` is not one of these, or whose `done` is not
|
|
1007
|
+
a number of 0 or more, is left out.
|
|
1008
|
+
|
|
1009
|
+
| Field | Type | What it holds |
|
|
1010
|
+
|---|---|---|
|
|
1011
|
+
| `stage` | `"extract" \| "check" \| "pictures" \| "decode"`, optional | `"extract"` (the default): text read. `"check"`: pages checked before they are read. `"pictures"`: pages looked at for pictures. `"decode"`: bytes of a text file decoded. |
|
|
1012
|
+
| `done` | `number` | How many are done. |
|
|
1013
|
+
| `total` | `number`, optional | How many there are, when it is known. |
|
|
1014
|
+
| `unit` | `"pages" \| "parts" \| "bytes"` | What `done` and `total` count. |
|
|
1015
|
+
|
|
1016
|
+
```ts
|
|
1017
|
+
import { createLargeFiles, MemoryDocumentStore, type Extractor } from "llm-large-files";
|
|
1018
|
+
|
|
1019
|
+
// readPage is your own: the text of one page of a PDF, from an OCR service.
|
|
1020
|
+
declare function readPage(bytes: Uint8Array, page: number, signal?: AbortSignal): Promise<string>;
|
|
1021
|
+
declare function pageCount(bytes: Uint8Array): Promise<number>;
|
|
1022
|
+
|
|
1023
|
+
const pdf: Extractor = async (bytes, input) => {
|
|
1024
|
+
const pages = await pageCount(bytes);
|
|
1025
|
+
const texts: string[] = [];
|
|
1026
|
+
for (let page = 1; page <= pages; page++) {
|
|
1027
|
+
input.signal?.throwIfAborted();
|
|
1028
|
+
texts.push(`--- Page ${page} ---\n${await readPage(bytes, page, input.signal)}`);
|
|
1029
|
+
input.onProgress?.({ done: page, total: pages, unit: "pages" }); // an ingest.progress of stage "extract"
|
|
1030
|
+
}
|
|
1031
|
+
return { text: texts.join("\n\n"), pages };
|
|
1032
|
+
};
|
|
1033
|
+
|
|
1034
|
+
const files = createLargeFiles({ store: new MemoryDocumentStore(), extractors: { pdf } });
|
|
1035
|
+
```
|
|
1036
|
+
|
|
1037
|
+
### `ExtractedText`
|
|
1038
|
+
|
|
1039
|
+
```ts
|
|
1040
|
+
type ExtractedText = { text: string; pages?: number; encoding?: string; replacedCharacters?: number };
|
|
1041
|
+
```
|
|
1042
|
+
|
|
1043
|
+
| Field | Type | What it holds |
|
|
1044
|
+
|---|---|---|
|
|
1045
|
+
| `text` | `string` | The text of the file. |
|
|
1046
|
+
| `pages` | `number \| undefined` | The number of pages (or slides), stored as `DocumentMeta.pages`. |
|
|
1047
|
+
| `encoding` | `string \| undefined` | The older encoding the file was read in, when it is not UTF-8, such as `"windows-1255"`. Stored as `DocumentMeta.encoding` when it is a name (letters, digits, `.`, `_`, `:` and `-`, up to 40 characters) and not a name of UTF-8 or UTF-16 (`utf-8`, `utf8`, `unicode`, `utf-16be`…): a name `TextDecoder` does not know is kept. New in 0.6.0. |
|
|
1048
|
+
| `replacedCharacters` | `number \| undefined` | The characters that were not valid in the encoding the file was read in, each now U+FFFD (�). Stored as `DocumentMeta.replacedCharacters` when it is a whole number above 0. New in 0.6.0. |
|
|
1049
|
+
|
|
1050
|
+
The model is told of both, on the card and in the frame of a file sent whole (see
|
|
1051
|
+
[`PreparedContext`](#preparedcontext)).
|
|
1052
|
+
|
|
1053
|
+
### `defaultExtractors`
|
|
1054
|
+
|
|
1055
|
+
```ts
|
|
1056
|
+
declare const defaultExtractors: Record<DocumentFormat, Extractor>;
|
|
1057
|
+
```
|
|
1058
|
+
|
|
1059
|
+
The built-in extractor of each format, used for every format you do not replace in
|
|
1060
|
+
`LargeFilesOptions.extractors`. Call one from an extractor of your own to wrap it.
|
|
1061
|
+
|
|
1062
|
+
| Format | What the extractor does |
|
|
1063
|
+
|---|---|
|
|
1064
|
+
| `text`, `markdown`, `log`, `json`, `csv` | Decodes the bytes as UTF-8, or as UTF-16 when they start with a byte-order mark or look like little-endian UTF-16 without one. A file that is not valid UTF-8 is read as UTF-8 when it starts with a UTF-8 byte-order mark, when at least as many of its lines count as UTF-8 as count as not (a line counts as UTF-8 when it holds at least as many characters of more than one byte as characters that are not valid), or when at most one line in 200 is not UTF-8. Otherwise it is read in windows-1255, windows-1256, windows-1251, Shift_JIS or windows-1252 when its lines with letters fit one, its lines that are valid UTF-8 as UTF-8; and when none fits, as UTF-8, as 0.5.0 read it. Each character that is not valid in the encoding it is read in becomes U+FFFD. It returns `encoding` and `replacedCharacters` ([`ExtractedText`](#extractedtext)), and reads such a file a step at a time, with pauses for other requests. It never refuses a file for its encoding. It refuses gzip, ZIP and other binary files. See [Text encodings](../guides/pdfs.md#text-encodings). |
|
|
1065
|
+
| `pdf` | [`createPdfExtractor()`](#createpdfextractoroptions). Needs the optional dependency `unpdf`, in a version that runs on this Node, and `@cantoo/pdf-lib` to mark pages with pictures and to refuse a page that would hold the server. |
|
|
1066
|
+
| `docx` | The paragraphs of the main document first, then those of its endnotes, footers, footnotes and headers (in the order of their part names), one line each, with a blank line between parts. A text box is read once. The text of a run that Word hides (`<w:vanish/>`) comes after the text of its paragraph that shows, each of its lines starting with `[Hidden text, not shown in the document]`: a carriage return, a U+0085 or a line separator in it starts a new marked line, a line of more than about 1,950 characters is cut into marked pieces, and the text of a run inside a hidden run (the reading of a ruby) is marked too. The marks count toward the limits of text. Text hidden through a style is read as ordinary text. Needs the optional dependency `jszip`. |
|
|
1067
|
+
| `pptx` | One `## Slide N` section per slide, in order, with `[No text on this slide]` for a slide without text. A slide that the slide show skips (`show="0"`) keeps its text, under `## Slide N (hidden, not shown in the slide show)`. `pages` is the number of slides. Needs `jszip`. |
|
|
1068
|
+
|
|
1069
|
+
The messages they refuse a file with, which `ingest` throws:
|
|
1070
|
+
|
|
1071
|
+
- `This file looks binary, not text. Attach a text, log, PDF, DOCX, or PPTX file.`
|
|
1072
|
+
- `This file is gzip-compressed. Decompress it, then attach the text file inside.`
|
|
1073
|
+
- `This file is a ZIP archive. Extract it, then attach the text file you need.`
|
|
1074
|
+
- `Reading PDF files needs the optional dependency "unpdf".`
|
|
1075
|
+
- `The unpdf installed would stop the whole server at the first PDF file on Node <n>, so PDF files are not read.`, followed by what to install: before Node 22 `Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 24 or later.`, on Node 22 and 23 `Install unpdf 1.6.1 or later, or run Node 24 or later.`, on a later Node `Install unpdf 1.6.1 or later.` (an `unpdf` from 1.5.0 to 1.6.0, which loads a pdf.js that calls `Promise.try` where Node does not have it; new in 0.6.0)
|
|
1076
|
+
- `The unpdf installed cannot read PDF files on Node <n> (<unpdf's message>). Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 22 or later.` (before Node 22, an `unpdf` that cannot load its pdf.js: 1.9 and later, 2.x included; new in 0.6.0. From Node 22 on, unpdf's own error is thrown as it is.)
|
|
1077
|
+
- `This PDF has no text layer (it may be scanned). It needs OCR before it can be searched.`
|
|
1078
|
+
- `This PDF has no text layer (it may be scanned) and <n> pages. Without text it can only be read by looking at its pages, which works for up to <m> pages. It needs OCR first.`
|
|
1079
|
+
- `Reading DOCX and PPTX files needs the optional dependency "jszip".`
|
|
1080
|
+
- `This DOCX does not contain word/document.xml.` and `This PPTX does not contain any slides.`
|
|
1081
|
+
- `This DOCX unpacks to more than <n> MB, over 100 times its size. A file that grows that much is not read: it may be a zip bomb. Save it as text or PDF, and attach that.` (past the first 16 MB; `PPTX` for a presentation)
|
|
1082
|
+
- `This DOCX unpacks to more than 128 MB of XML, more than is read from one file. Save it as text or PDF, and attach that.`
|
|
1083
|
+
- `This PDF has <n> pages, more than the <m> read from one file. Split it, and attach the part you need.` (`maxPdfPages`, before any page is read)
|
|
1084
|
+
- `This PDF holds more than <n> MB of text, more than is kept from one file. Split it, and attach the part you need.` (`maxTextBytes`, counted page by page; `KB` below 1 MB, `B` below 1 KB)
|
|
1085
|
+
- `This PDF draws more than <n> MB of text, over 100 times its size. A file that grows that much is not read: it may be built to exhaust the server.` (text past 100 times the size of the file, after the first 16 MB, when that comes before `maxTextBytes`)
|
|
1086
|
+
- `This PDF lists the same page more than once. A file built that way can hold far more text than its size, so it is not read. Print it to a new PDF, and attach that.`
|
|
1087
|
+
- `This DOCX holds more than 32 million characters of text, more than is read from one file. Split it, and attach the part you need.` (from one Office file, whatever `maxTextBytes` allows; the marks of hidden text count)
|
|
1088
|
+
- `This DOCX holds more than <n> MB of text, more than is kept from one file. Split it, and attach the part you need.` (when `maxTextBytes` is below 32 million)
|
|
1089
|
+
- `This DOCX has more than 1,000,000 paragraphs, more than a document holds. It may be built to exhaust the server, so it is not read.` (paragraphs with text)
|
|
1090
|
+
- `This DOCX nests paragraphs more than 32 deep, which no document does. It may be built to exhaust the server, so it is not read.`
|
|
1091
|
+
- `This DOCX has more than 20,000 parts, more than an Office document has. It may be built to exhaust the server, so it is not read.` (before JSZip reads the file: its ZIP directory is read the way JSZip will read it, record by record, whatever count of parts the file gives)
|
|
1092
|
+
- `This DOCX lists its parts in a way that no Office program does: reading the list would take far more memory or time than an Office document needs. It may be built to exhaust the server, so it is not read.` (more than 80,000 extra fields, or more than 8 MB of names, comments and extra-field data that JSZip would turn into text or go through byte by byte: a name is counted once for each part that points to it, and a field for all the data it says it has, even past its record)
|
|
1093
|
+
- `This DOCX ends with a ZIP64 record that cannot be read, and reading it could hold the server without end. It may be built to exhaust the server, so it is not read.` (a ZIP64 end record that says it is longer than its fields, which JSZip reads in a loop that does not move on)
|
|
1094
|
+
|
|
1095
|
+
The Office messages say `PPTX` for a presentation. A PDF or an Office file that is damaged fails
|
|
1096
|
+
with the error of pdf.js or JSZip.
|
|
1097
|
+
|
|
1098
|
+
### createPdfExtractor(options?)
|
|
1099
|
+
|
|
1100
|
+
```ts
|
|
1101
|
+
declare function createPdfExtractor(options?: PdfExtractorOptions): Extractor;
|
|
1102
|
+
```
|
|
1103
|
+
|
|
1104
|
+
The built-in PDF extractor, with an option changed. It needs the optional dependency `unpdf`. It
|
|
1105
|
+
writes each page as a line `--- Page N ---` followed by the page's text, and
|
|
1106
|
+
`[No text on this page. It may be a scan, a photo, or a chart.]` for a page without text. With
|
|
1107
|
+
`pictures`, a page that shows a picture or a drawing gets the line
|
|
1108
|
+
`[Picture on this page. This text cannot show it.]` under its page line. It returns the number of
|
|
1109
|
+
pages. It throws the PDF messages listed under [`defaultExtractors`](#defaultextractors).
|
|
1110
|
+
|
|
1111
|
+
```ts
|
|
1112
|
+
import { createLargeFiles, createPdfExtractor, MemoryDocumentStore } from "llm-large-files";
|
|
1113
|
+
|
|
1114
|
+
// The text in pdf.js order, without rebuilt tables, as in version 0.1.0.
|
|
1115
|
+
const files = createLargeFiles({
|
|
1116
|
+
store: new MemoryDocumentStore(),
|
|
1117
|
+
extractors: { pdf: createPdfExtractor({ tables: false }) },
|
|
1118
|
+
});
|
|
1119
|
+
```
|
|
1120
|
+
|
|
1121
|
+
Guide: [PDFs](../guides/pdfs.md).
|
|
1122
|
+
|
|
1123
|
+
### `PdfExtractorOptions`
|
|
1124
|
+
|
|
1125
|
+
```ts
|
|
1126
|
+
type PdfExtractorOptions = { tables?: boolean; pictures?: boolean; checkPages?: boolean };
|
|
1127
|
+
```
|
|
1128
|
+
|
|
1129
|
+
| Option | Type | Default | What it does |
|
|
1130
|
+
|---|---|---|---|
|
|
1131
|
+
| `tables` | `boolean` | `true` | Rebuilds tables from the position of the text, and writes each row as `\| cell \| cell \| \|`, so an empty cell stays an empty cell. `false` gives the text in pdf.js order, as in version 0.1.0. |
|
|
1132
|
+
| `pictures` | `boolean` | `true` | Writes `[Picture on this page. This text cannot show it.]` under the page line of every page that shows a picture or a drawing, so the model knows that the text does not tell all of that page. Needs the optional dependency `@cantoo/pdf-lib`; without it, and with `false`, no page is marked. |
|
|
1133
|
+
| `checkPages` | `boolean` | `true` | Before pdf.js reads any page, adds up what each page would make it run, and refuses a file with a page that would hold the server for a long time ([Pages that would hold the server](../guides/pdfs.md#pages-that-would-hold-the-server)). Needs the optional dependency `@cantoo/pdf-lib`; without it, and with `false`, every page is read however long it takes. With `false` and `pictures: false`, the file is not read with `@cantoo/pdf-lib` at ingest. New in 0.6.0. |
|
|
1134
|
+
|
|
1135
|
+
### detectFormat(name, mimeType)
|
|
1136
|
+
|
|
1137
|
+
```ts
|
|
1138
|
+
declare function detectFormat(name: string, mimeType: string): DocumentFormat;
|
|
1139
|
+
```
|
|
1140
|
+
|
|
1141
|
+
The format of a file: from the extension after the last dot (in any case), then from the MIME type,
|
|
1142
|
+
else `"text"`. The MIME type is lowercased and compared whole, so `text/csv; charset=utf-8` names no
|
|
1143
|
+
format. A name without a dot is looked up whole, so a file named `log` is a `log`. `ingest` uses it,
|
|
1144
|
+
then turns a `"text"` document that reads like a log into `"log"`.
|
|
1145
|
+
|
|
1146
|
+
| Format | Extensions | MIME types |
|
|
1147
|
+
|---|---|---|
|
|
1148
|
+
| `log` | `.log`, `.out`, `.err` | none (also text recognized as a log at ingest) |
|
|
1149
|
+
| `markdown` | `.md`, `.markdown` | `text/markdown` |
|
|
1150
|
+
| `json` | `.json`, `.jsonl`, `.ndjson` | `application/json` |
|
|
1151
|
+
| `csv` | `.csv`, `.tsv` | `text/csv` |
|
|
1152
|
+
| `pdf` | `.pdf` | `application/pdf` |
|
|
1153
|
+
| `docx` | `.docx` | `application/vnd.openxmlformats-officedocument.wordprocessingml.document` |
|
|
1154
|
+
| `pptx` | `.pptx` | `application/vnd.openxmlformats-officedocument.presentationml.presentation` |
|
|
1155
|
+
| `text` | any other | any other |
|
|
1156
|
+
|
|
1157
|
+
Guide: [PDFs](../guides/pdfs.md).
|
|
1158
|
+
|
|
1159
|
+
## Text sizes
|
|
1160
|
+
|
|
1161
|
+
### estimateTokens(text)
|
|
1162
|
+
|
|
1163
|
+
```ts
|
|
1164
|
+
declare function estimateTokens(text: string): number;
|
|
1165
|
+
```
|
|
1166
|
+
|
|
1167
|
+
Estimates how many tokens a model counts for `text`, without calling it. It prices each kind of
|
|
1168
|
+
character (runs of letters, digits at about one token each, punctuation, line breaks, and each
|
|
1169
|
+
script), because characters per token vary from about 4.5 for English prose to 1 or 2 for logs and
|
|
1170
|
+
CSV. It was fitted to Gemini's `countTokens` on 60 texts and lands between 0.98 and 1.7 times that
|
|
1171
|
+
count: it leans high, which only makes a file searchable sooner. The one kind of text it counts low,
|
|
1172
|
+
at about 70%, is a long run of random letters in one case with no digits. `ingest` stores it as
|
|
1173
|
+
`estimatedTokens`. See [how it works](../how-it-works.md).
|
|
1174
|
+
|
|
1175
|
+
### utf8Bytes(text)
|
|
1176
|
+
|
|
1177
|
+
```ts
|
|
1178
|
+
declare function utf8Bytes(text: string): number;
|
|
1179
|
+
```
|
|
1180
|
+
|
|
1181
|
+
The size of `text` in UTF-8, in bytes, without encoding a copy. `utf8Bytes("héllo")` is 6.
|
|
1182
|
+
|
|
1183
|
+
### jsonBytes(text)
|
|
1184
|
+
|
|
1185
|
+
```ts
|
|
1186
|
+
declare function jsonBytes(text: string): number;
|
|
1187
|
+
```
|
|
1188
|
+
|
|
1189
|
+
The bytes `text` takes as a string in a JSON request body, which is what a request limit counts: its
|
|
1190
|
+
UTF-8 bytes, one more for each quote, backslash, line break, tab, carriage return, backspace and
|
|
1191
|
+
form feed, five more for any other control character, three more for half of a surrogate pair on
|
|
1192
|
+
its own, and the two quotes around it.
|
|
1193
|
+
`jsonBytes('say "hi"\n')` is 14.
|
|
1194
|
+
|
|
1195
|
+
## Document types
|
|
1196
|
+
|
|
1197
|
+
### `DocumentMeta`
|
|
1198
|
+
|
|
1199
|
+
```ts
|
|
1200
|
+
type DocumentMeta = {
|
|
1201
|
+
id: string;
|
|
1202
|
+
owner?: string;
|
|
1203
|
+
name: string;
|
|
1204
|
+
mimeType: string;
|
|
1205
|
+
format: DocumentFormat;
|
|
1206
|
+
bytes: number;
|
|
1207
|
+
textBytes: number;
|
|
1208
|
+
jsonBytes?: number;
|
|
1209
|
+
characters: number;
|
|
1210
|
+
lines: number;
|
|
1211
|
+
estimatedTokens: number;
|
|
1212
|
+
wrappedLines: number;
|
|
1213
|
+
pages?: number;
|
|
1214
|
+
encoding?: string;
|
|
1215
|
+
replacedCharacters?: number;
|
|
1216
|
+
originalKept?: boolean;
|
|
1217
|
+
outline: OutlineEntry[];
|
|
1218
|
+
logProfile?: LogProfile;
|
|
1219
|
+
createdAt: string;
|
|
1220
|
+
expiresAt: string;
|
|
1221
|
+
};
|
|
1222
|
+
```
|
|
1223
|
+
|
|
1224
|
+
The metadata of a stored document, made by `ingest`. It holds the owner and text from the file
|
|
1225
|
+
(the outline, the log profile): send [`toDocumentSummary(meta)`](#todocumentsummarymeta) to a
|
|
1226
|
+
browser instead.
|
|
1227
|
+
|
|
1228
|
+
| Field | Type | What it holds |
|
|
1229
|
+
|---|---|---|
|
|
1230
|
+
| `id` | `string` | `doc_` and 32 hexadecimal digits ([`DOCUMENT_ID_PATTERN`](#document_id_pattern)). |
|
|
1231
|
+
| `owner` | `string \| undefined` | The owner given at ingest. Absent when none was given. |
|
|
1232
|
+
| `name` | `string` | The cleaned file name (see [`IngestInput`](#ingestinput)). |
|
|
1233
|
+
| `mimeType` | `string` | The MIME type given, trimmed, or `"application/octet-stream"`. |
|
|
1234
|
+
| `format` | [`DocumentFormat`](#documentformat) | The format. |
|
|
1235
|
+
| `bytes` | `number` | The size of the uploaded file. |
|
|
1236
|
+
| `textBytes` | `number` | The size of the extracted text in UTF-8. |
|
|
1237
|
+
| `jsonBytes` | `number \| undefined` | The bytes the text takes inside a JSON request body, with the escapes JSON adds. Absent on a document ingested before 0.4.1: planning then assumes `textBytes` × 1.08. |
|
|
1238
|
+
| `characters` | `number` | The length of the text, in UTF-16 code units (a JavaScript string's `length`). |
|
|
1239
|
+
| `lines` | `number` | The number of lines of the text. A final line break does not start another line. |
|
|
1240
|
+
| `estimatedTokens` | `number` | [`estimateTokens`](#estimatetokenstext) of the text. |
|
|
1241
|
+
| `wrappedLines` | `number` | How many lines longer than 2,000 characters were split into several, so that every line can be read by number. |
|
|
1242
|
+
| `pages` | `number \| undefined` | The pages of a PDF, the slides of a PPTX, or what your extractor returned. |
|
|
1243
|
+
| `encoding` | `string \| undefined` | The older encoding a text file was read in, because it is not UTF-8, as `TextDecoder` names it: `"windows-1255"` for a Hebrew CSV that Excel saved, or `"windows-1256"`, `"windows-1251"`, `"shift_jis"`, `"windows-1252"`. Lines of it that are valid UTF-8 are read as UTF-8 all the same. Absent for valid UTF-8, for a file read as UTF-8 with characters that are not valid (see `replacedCharacters`), for UTF-16, for PDF, DOCX and PPTX, and on documents from before 0.6.0. An extractor of your own may set another name ([`ExtractedText`](#extractedtext)). How the encoding is chosen: [Text encodings](../guides/pdfs.md#text-encodings). New in 0.6.0. |
|
|
1244
|
+
| `replacedCharacters` | `number \| undefined` | The characters of a text file that were not valid in the encoding it was read in (UTF-8, or `encoding`), such as a character cut in two at the end of a UTF-8 log, or a byte that `encoding` does not have: each is stored as U+FFFD (�). Absent when there were none, and on documents from before 0.6.0. New in 0.6.0. |
|
|
1245
|
+
| `originalKept` | `boolean \| undefined` | `true` when the uploaded file is kept in the store (`keepOriginals`). Absent otherwise. Documents ingested before you turned `keepOriginals` on have no original. |
|
|
1246
|
+
| `outline` | [`OutlineEntry[]`](#outlineentry) | The headings found in the text, at most 400. Empty for `log`, `json` and `csv`. |
|
|
1247
|
+
| `logProfile` | [`LogProfile`](#logprofile) or `undefined` | The log profile, for a `log` document only. |
|
|
1248
|
+
| `createdAt` | `string` | When it was ingested, as an ISO 8601 date. |
|
|
1249
|
+
| `expiresAt` | `string` | When it expires, as an ISO 8601 date: `createdAt` plus `ttlMs`, or [`NEVER_EXPIRES`](#never_expires). |
|
|
1250
|
+
|
|
1251
|
+
### `DocumentSummary`
|
|
1252
|
+
|
|
1253
|
+
```ts
|
|
1254
|
+
type DocumentSummary = {
|
|
1255
|
+
id: string;
|
|
1256
|
+
name: string;
|
|
1257
|
+
mimeType: string;
|
|
1258
|
+
format: DocumentFormat;
|
|
1259
|
+
bytes: number;
|
|
1260
|
+
lines: number;
|
|
1261
|
+
estimatedTokens: number;
|
|
1262
|
+
pages?: number;
|
|
1263
|
+
encoding?: string;
|
|
1264
|
+
replacedCharacters?: number;
|
|
1265
|
+
expiresAt: string;
|
|
1266
|
+
};
|
|
1267
|
+
```
|
|
1268
|
+
|
|
1269
|
+
A JSON-safe summary of a document for API responses and browser state, made by
|
|
1270
|
+
[`toDocumentSummary`](#todocumentsummarymeta). Its fields mean what they mean in
|
|
1271
|
+
[`DocumentMeta`](#documentmeta); `pages` is there only when the document has pages, and `encoding`
|
|
1272
|
+
and `replacedCharacters` only for a text file that was not valid UTF-8 (new in 0.6.0): a UI can say
|
|
1273
|
+
"read as windows-1255", or that some characters could not be read. A client that checks the
|
|
1274
|
+
answer against a fixed list of fields must allow the two. It leaves out `owner`, `textBytes`,
|
|
1275
|
+
`jsonBytes`, `characters`, `wrappedLines`, `originalKept`, `outline`, `logProfile` and
|
|
1276
|
+
`createdAt`.
|
|
1277
|
+
|
|
1278
|
+
Guide: [web app](../guides/web-app.md).
|
|
1279
|
+
|
|
1280
|
+
### `DocumentFormat`
|
|
1281
|
+
|
|
1282
|
+
```ts
|
|
1283
|
+
type DocumentFormat = "text" | "markdown" | "log" | "json" | "csv" | "pdf" | "docx" | "pptx";
|
|
1284
|
+
```
|
|
1285
|
+
|
|
1286
|
+
The format of a document. It picks the extractor and decides whether a document gets an outline (not
|
|
1287
|
+
`log`, `json` or `csv`) and a log profile (`log` only). See [`detectFormat`](#detectformatname-mimetype).
|
|
1288
|
+
|
|
1289
|
+
### `OutlineEntry`
|
|
1290
|
+
|
|
1291
|
+
```ts
|
|
1292
|
+
type OutlineEntry = { line: number; level: number; title: string };
|
|
1293
|
+
```
|
|
1294
|
+
|
|
1295
|
+
One heading of a document's outline. The headings are found in the text: Markdown headings (the
|
|
1296
|
+
slides of a PPTX are `## Slide N`), lines that start with "Chapter", "Part", "Book", "Section" or
|
|
1297
|
+
"Appendix" (or the Hebrew words for chapter, part and appendix), numbered headings such as `2.1 Results`, and short lines in capitals; all but the
|
|
1298
|
+
Markdown ones only after a blank line. When there are more than 400, the outline keeps only the
|
|
1299
|
+
top-level headings (of the shallowest level found) when there are at least 20 of them, and all the
|
|
1300
|
+
headings otherwise. With 20 to 400 top-level headings, each one is kept once, in order. Otherwise
|
|
1301
|
+
(more than 400 top-level headings, or fewer than 20) the outline has 400 entries, in order, taken
|
|
1302
|
+
at even steps across the document from the top-level headings or from all of them.
|
|
1303
|
+
|
|
1304
|
+
| Field | Type | What it holds |
|
|
1305
|
+
|---|---|---|
|
|
1306
|
+
| `line` | `number` | The line of the heading in the extracted text, from 1. |
|
|
1307
|
+
| `level` | `number` | Its level: 1 is the top. |
|
|
1308
|
+
| `title` | `string` | The heading. |
|
|
1309
|
+
|
|
1310
|
+
### `LogIssue`
|
|
1311
|
+
|
|
1312
|
+
```ts
|
|
1313
|
+
type LogIssue = { template: string; level: string; count: number; firstLine: number };
|
|
1314
|
+
```
|
|
1315
|
+
|
|
1316
|
+
One frequent message shape of a log, at level `FATAL`, `ERROR` or `WARN`.
|
|
1317
|
+
|
|
1318
|
+
| Field | Type | What it holds |
|
|
1319
|
+
|---|---|---|
|
|
1320
|
+
| `template` | `string` | The message with timestamps removed, and IDs, IP addresses, hexadecimal numbers, quoted values and numbers replaced by `<id>`, `<ip>`, `<hex>`, `<s>` and `<n>`. At most 180 characters. |
|
|
1321
|
+
| `level` | `string` | `"FATAL"`, `"ERROR"` or `"WARN"`. |
|
|
1322
|
+
| `count` | `number` | How many lines have this shape. |
|
|
1323
|
+
| `firstLine` | `number` | The line of the first of them, from 1. |
|
|
1324
|
+
|
|
1325
|
+
### `LogProfile`
|
|
1326
|
+
|
|
1327
|
+
```ts
|
|
1328
|
+
type LogProfile = { levels: Record<string, number>; firstTimestamp?: string; lastTimestamp?: string; topIssues: LogIssue[] };
|
|
1329
|
+
```
|
|
1330
|
+
|
|
1331
|
+
What a log contains, found at ingest. It is on every card of a log and in the overview tool.
|
|
1332
|
+
|
|
1333
|
+
| Field | Type | What it holds |
|
|
1334
|
+
|---|---|---|
|
|
1335
|
+
| `levels` | `Record<string, number>` | Lines per level: `FATAL`, `ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`. `ERR` counts as `ERROR`, `WARNING` as `WARN`, `CRITICAL` as `FATAL`. |
|
|
1336
|
+
| `firstTimestamp` | `string \| undefined` | The first date and time (`2026-11-19 08:00:01` or ISO 8601) in the log, as written. |
|
|
1337
|
+
| `lastTimestamp` | `string \| undefined` | The last one. |
|
|
1338
|
+
| `topIssues` | [`LogIssue[]`](#logissue) | Up to 15 message shapes: `FATAL` first, then `ERROR`, then `WARN`, and the most frequent first within each level. |
|
|
1339
|
+
|
|
1340
|
+
## Progress of whole-document reads
|
|
1341
|
+
|
|
1342
|
+
### `ProgressEvent`
|
|
1343
|
+
|
|
1344
|
+
```ts
|
|
1345
|
+
type ProgressEvent = { kind: "map" | "reduce"; message: string; done: number; total: number };
|
|
1346
|
+
```
|
|
1347
|
+
|
|
1348
|
+
One step of a whole-document read (`analyze_whole_document`), for a status display.
|
|
1349
|
+
|
|
1350
|
+
| Field | Type | What it holds |
|
|
1351
|
+
|---|---|---|
|
|
1352
|
+
| `kind` | `"map" \| "reduce"` | `"map"`: a part of the file was read. `"reduce"`: notes were combined, or the answer is being written. |
|
|
1353
|
+
| `message` | `string` | A line to show: `Reading app.log: part 3 of 12`, `Combining notes on app.log (round 1): 2 of 4`, `Writing the answer from 9 relevant parts of app.log`. |
|
|
1354
|
+
| `done` | `number` | The steps of this kind done so far (0 for the step that writes the answer). |
|
|
1355
|
+
| `total` | `number` | The steps of this kind (1 for the step that writes the answer). |
|
|
1356
|
+
|
|
1357
|
+
It is not one of the events of `onEvent` ([events](./events.md)). In `askWithFiles`, each
|
|
1358
|
+
`ProgressEvent` of a whole-file read is also a `tool.progress` event, with the `callId` of its call
|
|
1359
|
+
and the same `done`, `total` and `message`, and `kind` as `stage`.
|
|
1360
|
+
|
|
1361
|
+
### `ProgressListener`
|
|
1362
|
+
|
|
1363
|
+
```ts
|
|
1364
|
+
type ProgressListener = (event: ProgressEvent) => void;
|
|
1365
|
+
```
|
|
1366
|
+
|
|
1367
|
+
The type of `ToolOptions.onProgress` and of `ToolCallHooks.onProgress`.
|
|
1368
|
+
[`askWithFiles`](./ask.md#askwithfilesoptions) passes each event's message, followed by "…", to its
|
|
1369
|
+
own `onActivity` instead.
|
|
1370
|
+
|
|
1371
|
+
### `ToolCallHooks`
|
|
1372
|
+
|
|
1373
|
+
```ts
|
|
1374
|
+
type ToolCallHooks = {
|
|
1375
|
+
onProgress?: ProgressListener;
|
|
1376
|
+
onRequest?: (request: ToolRequestStart) => ToolRequestHandle;
|
|
1377
|
+
};
|
|
1378
|
+
```
|
|
1379
|
+
|
|
1380
|
+
New in 0.7.0. Listeners for one tool call: the fourth argument of
|
|
1381
|
+
[`executeWithFiles`](./tools.md#toolset), next to its limits. With them, the progress and the model
|
|
1382
|
+
requests of two whole-file reads that run at once can be told apart. Only `analyze_whole_document`
|
|
1383
|
+
calls them; the other tools ignore them. `askWithFiles` passes its own for each call, and turns
|
|
1384
|
+
them into `tool.progress`, `request.start`, `retry` and `request.end` events
|
|
1385
|
+
([events in your own loop](./events.md#toolcallhooks)).
|
|
1386
|
+
|
|
1387
|
+
| Field | Type | What it does |
|
|
1388
|
+
|---|---|---|
|
|
1389
|
+
| `onProgress` | [`ProgressListener`](#progresslistener), optional | Progress of this call, in place of `ToolOptions.onProgress` for it. Without it, the tool set's own listener is called. |
|
|
1390
|
+
| `onRequest` | `(request: ToolRequestStart) => ToolRequestHandle`, optional | Called as each model request of this call starts ([`ToolRequestStart`](#toolrequeststart)). Return a [`ToolRequestHandle`](#toolrequesthandle): the read tells it of each retry of that request, and once when the request ends. |
|
|
1391
|
+
|
|
1392
|
+
Do not let them throw. The read takes a throw from `onRequest` or from a handle for a failure of
|
|
1393
|
+
that request: the part is reported as not read, and a merge or the answer falls back to the notes.
|
|
1394
|
+
A throw from `onProgress` ends the read, and `executeWithFiles` returns it as the tool's
|
|
1395
|
+
`{ error }`. To end your question on an error of your listener, as `askWithFiles` does, catch it in
|
|
1396
|
+
the listener, keep it, and abort the tool set's `signal`.
|
|
1397
|
+
|
|
1398
|
+
```ts
|
|
1399
|
+
import type { LargeFiles, ToolCall, ToolCallHooks } from "llm-large-files";
|
|
1400
|
+
|
|
1401
|
+
// files is your createLargeFiles(); prepared comes from files.prepare(); generate is your GenerateText.
|
|
1402
|
+
declare const files: LargeFiles;
|
|
1403
|
+
declare const prepared: Awaited<ReturnType<LargeFiles["prepare"]>>;
|
|
1404
|
+
declare const generate: NonNullable<Parameters<LargeFiles["tools"]>[1]>["generate"];
|
|
1405
|
+
|
|
1406
|
+
const tools = files.tools(prepared.plan.searchable, { ...(generate ? { generate } : {}) });
|
|
1407
|
+
|
|
1408
|
+
// Each call reports apart: "call 2: Reading app.log: part 3 of 12".
|
|
1409
|
+
async function run(call: ToolCall, index: number) {
|
|
1410
|
+
const hooks: ToolCallHooks = {
|
|
1411
|
+
onProgress: (event) => console.log(`call ${index}: ${event.message}`),
|
|
1412
|
+
onRequest: (start) => {
|
|
1413
|
+
const began = Date.now();
|
|
1414
|
+
return {
|
|
1415
|
+
retry: ({ attempt, delayMs }) => console.log(`call ${index}: ${start.detail}, retry ${attempt} in ${delayMs} ms`),
|
|
1416
|
+
end: ({ outcome, usage }) => console.log(`call ${index}: ${start.detail} ${outcome} in ${Date.now() - began} ms`, usage),
|
|
1417
|
+
};
|
|
1418
|
+
},
|
|
1419
|
+
};
|
|
1420
|
+
return tools.executeWithFiles(call.name, call.args, {}, hooks);
|
|
1421
|
+
}
|
|
1422
|
+
```
|
|
1423
|
+
|
|
1424
|
+
### `ToolRequestHandle`
|
|
1425
|
+
|
|
1426
|
+
```ts
|
|
1427
|
+
type ToolRequestHandle = {
|
|
1428
|
+
retry(notice: { attempt: number; delayMs: number; error: unknown }): void;
|
|
1429
|
+
end(end: ToolRequestEnd): void;
|
|
1430
|
+
};
|
|
1431
|
+
```
|
|
1432
|
+
|
|
1433
|
+
New in 0.7.0. One model request of a tool call, as `ToolCallHooks.onRequest` returns it.
|
|
1434
|
+
|
|
1435
|
+
| Member | What it is told |
|
|
1436
|
+
|---|---|
|
|
1437
|
+
| `retry(notice)` | The request failed and is sent again after `delayMs`, as a [`RetryNotice`](./errors-and-retries.md#retrynotice): `attempt` is 1 for the first retry, and `error` is the error as it was thrown. The retry of an error without a status, which has no wait, is not told. |
|
|
1438
|
+
| `end(end)` | The request ended, after any retries ([`ToolRequestEnd`](#toolrequestend)). Called once. |
|
|
1439
|
+
|
|
1440
|
+
### `ToolRequestStart`
|
|
1441
|
+
|
|
1442
|
+
```ts
|
|
1443
|
+
type ToolRequestStart = { purpose: "part" | "merge" | "final"; detail: string };
|
|
1444
|
+
```
|
|
1445
|
+
|
|
1446
|
+
New in 0.7.0. A model request of a whole-file read, as it starts.
|
|
1447
|
+
|
|
1448
|
+
| Field | Type | What it holds |
|
|
1449
|
+
|---|---|---|
|
|
1450
|
+
| `purpose` | `"part" \| "merge" \| "final"` | `"part"`: a part of the file is read. `"merge"`: notes are combined. `"final"`: the answer of the read is written. |
|
|
1451
|
+
| `detail` | `string` | Which one: `"part 3 of 12"`, `"first half of part 3 of 12"` (a part read again in halves), `"round 2: 1 of 4"`, `"the answer"`. |
|
|
1452
|
+
|
|
1453
|
+
### `ToolRequestEnd`
|
|
1454
|
+
|
|
1455
|
+
```ts
|
|
1456
|
+
type ToolRequestEnd = { outcome: "ok" | "error"; usage?: GenerateUsage; error?: unknown };
|
|
1457
|
+
```
|
|
1458
|
+
|
|
1459
|
+
New in 0.7.0. A model request of a tool call, as it ends.
|
|
1460
|
+
|
|
1461
|
+
| Field | Type | What it holds |
|
|
1462
|
+
|---|---|---|
|
|
1463
|
+
| `outcome` | `"ok" \| "error"` | `"error"` when the request failed in the end. A part that failed does not end the read: it is reported to the model. |
|
|
1464
|
+
| `usage` | [`GenerateUsage`](./ask.md#generateusage), optional | The tokens of the request, summed over what its part reader passed to `onUsage`. Absent when it passed nothing. |
|
|
1465
|
+
| `error` | `unknown`, optional | With `"error"`: the error as it was thrown. It can hold the provider's own words: keep it for your logs. |
|
|
1466
|
+
|
|
1467
|
+
Guide: [web app](../guides/web-app.md).
|