llm-large-files 0.5.0 → 0.8.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.
Files changed (285) hide show
  1. package/CHANGELOG.md +1719 -466
  2. package/README.md +190 -60
  3. package/dist/analyze.d.ts +8 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +198 -54
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +194 -40
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +63 -7
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1131 -214
  14. package/dist/ask.js.map +1 -1
  15. package/dist/decode.d.ts +19 -0
  16. package/dist/decode.d.ts.map +1 -0
  17. package/dist/decode.js +97 -0
  18. package/dist/decode.js.map +1 -0
  19. package/dist/encoding.d.ts +17 -0
  20. package/dist/encoding.d.ts.map +1 -0
  21. package/dist/encoding.js +852 -0
  22. package/dist/encoding.js.map +1 -0
  23. package/dist/errors.d.ts +59 -0
  24. package/dist/errors.d.ts.map +1 -1
  25. package/dist/errors.js +80 -0
  26. package/dist/errors.js.map +1 -1
  27. package/dist/events.d.ts +339 -0
  28. package/dist/events.d.ts.map +1 -0
  29. package/dist/events.js +163 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/evidence.d.ts +2 -0
  32. package/dist/evidence.d.ts.map +1 -1
  33. package/dist/evidence.js +9 -2
  34. package/dist/evidence.js.map +1 -1
  35. package/dist/extract.d.ts +26 -7
  36. package/dist/extract.d.ts.map +1 -1
  37. package/dist/extract.js +180 -314
  38. package/dist/extract.js.map +1 -1
  39. package/dist/gemini/adapter.d.ts +17 -8
  40. package/dist/gemini/adapter.d.ts.map +1 -1
  41. package/dist/gemini/adapter.js +117 -66
  42. package/dist/gemini/adapter.js.map +1 -1
  43. package/dist/gemini/chat.d.ts +23 -3
  44. package/dist/gemini/chat.d.ts.map +1 -1
  45. package/dist/gemini/chat.js +6 -2
  46. package/dist/gemini/chat.js.map +1 -1
  47. package/dist/gemini/endpoints.d.ts +5 -1
  48. package/dist/gemini/endpoints.d.ts.map +1 -1
  49. package/dist/gemini/endpoints.js +11 -2
  50. package/dist/gemini/endpoints.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +9 -4
  52. package/dist/gemini/errors.d.ts.map +1 -1
  53. package/dist/gemini/errors.js +32 -0
  54. package/dist/gemini/errors.js.map +1 -1
  55. package/dist/gemini/generate.d.ts +10 -2
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +33 -10
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +3 -3
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +2 -2
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -1
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -1
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/groups.d.ts +54 -0
  68. package/dist/groups.d.ts.map +1 -0
  69. package/dist/groups.js +136 -0
  70. package/dist/groups.js.map +1 -0
  71. package/dist/html.d.ts +11 -0
  72. package/dist/html.d.ts.map +1 -0
  73. package/dist/html.js +1112 -0
  74. package/dist/html.js.map +1 -0
  75. package/dist/http.d.ts +116 -0
  76. package/dist/http.d.ts.map +1 -1
  77. package/dist/http.js +347 -1
  78. package/dist/http.js.map +1 -1
  79. package/dist/index.d.ts +13 -7
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +7 -5
  82. package/dist/index.js.map +1 -1
  83. package/dist/library.d.ts +67 -5
  84. package/dist/library.d.ts.map +1 -1
  85. package/dist/library.js +449 -93
  86. package/dist/library.js.map +1 -1
  87. package/dist/limiter.d.ts +2 -1
  88. package/dist/limiter.d.ts.map +1 -1
  89. package/dist/limiter.js +3 -2
  90. package/dist/limiter.js.map +1 -1
  91. package/dist/map-reduce.d.ts +28 -1
  92. package/dist/map-reduce.d.ts.map +1 -1
  93. package/dist/map-reduce.js +240 -52
  94. package/dist/map-reduce.js.map +1 -1
  95. package/dist/model.d.ts +84 -2
  96. package/dist/model.d.ts.map +1 -1
  97. package/dist/model.js +190 -2
  98. package/dist/model.js.map +1 -1
  99. package/dist/node/handlers.d.ts +20 -4
  100. package/dist/node/handlers.d.ts.map +1 -1
  101. package/dist/node/handlers.js +184 -28
  102. package/dist/node/handlers.js.map +1 -1
  103. package/dist/node/index.d.ts +4 -0
  104. package/dist/node/index.d.ts.map +1 -1
  105. package/dist/node/index.js +2 -0
  106. package/dist/node/index.js.map +1 -1
  107. package/dist/node/ingest-child.d.ts +38 -0
  108. package/dist/node/ingest-child.d.ts.map +1 -0
  109. package/dist/node/ingest-child.js +42 -0
  110. package/dist/node/ingest-child.js.map +1 -0
  111. package/dist/node/isolated.d.ts +88 -0
  112. package/dist/node/isolated.d.ts.map +1 -0
  113. package/dist/node/isolated.js +381 -0
  114. package/dist/node/isolated.js.map +1 -0
  115. package/dist/node/sse.d.ts +59 -0
  116. package/dist/node/sse.d.ts.map +1 -0
  117. package/dist/node/sse.js +174 -0
  118. package/dist/node/sse.js.map +1 -0
  119. package/dist/office.d.ts +105 -0
  120. package/dist/office.d.ts.map +1 -0
  121. package/dist/office.js +1092 -0
  122. package/dist/office.js.map +1 -0
  123. package/dist/openai/adapter.d.ts +29 -5
  124. package/dist/openai/adapter.d.ts.map +1 -1
  125. package/dist/openai/adapter.js +325 -37
  126. package/dist/openai/adapter.js.map +1 -1
  127. package/dist/output-limit.d.ts +14 -2
  128. package/dist/output-limit.d.ts.map +1 -1
  129. package/dist/output-limit.js +39 -10
  130. package/dist/output-limit.js.map +1 -1
  131. package/dist/pause.d.ts +24 -0
  132. package/dist/pause.d.ts.map +1 -0
  133. package/dist/pause.js +38 -0
  134. package/dist/pause.js.map +1 -0
  135. package/dist/pdf-pages.d.ts +32 -2
  136. package/dist/pdf-pages.d.ts.map +1 -1
  137. package/dist/pdf-pages.js +277 -20
  138. package/dist/pdf-pages.js.map +1 -1
  139. package/dist/pdf-pictures.d.ts +30 -3
  140. package/dist/pdf-pictures.d.ts.map +1 -1
  141. package/dist/pdf-pictures.js +50 -8
  142. package/dist/pdf-pictures.js.map +1 -1
  143. package/dist/pdf-work.d.ts +40 -0
  144. package/dist/pdf-work.d.ts.map +1 -0
  145. package/dist/pdf-work.js +734 -0
  146. package/dist/pdf-work.js.map +1 -0
  147. package/dist/peers.d.ts +8 -0
  148. package/dist/peers.d.ts.map +1 -0
  149. package/dist/peers.js +32 -0
  150. package/dist/peers.js.map +1 -0
  151. package/dist/plan.d.ts +22 -4
  152. package/dist/plan.d.ts.map +1 -1
  153. package/dist/plan.js +61 -12
  154. package/dist/plan.js.map +1 -1
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +4 -2
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +23 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +33 -3
  161. package/dist/retry.js.map +1 -1
  162. package/dist/search.d.ts +107 -24
  163. package/dist/search.d.ts.map +1 -1
  164. package/dist/search.js +803 -149
  165. package/dist/search.js.map +1 -1
  166. package/dist/sse.d.ts +35 -2
  167. package/dist/sse.d.ts.map +1 -1
  168. package/dist/sse.js +145 -31
  169. package/dist/sse.js.map +1 -1
  170. package/dist/stores.d.ts.map +1 -1
  171. package/dist/stores.js +5 -2
  172. package/dist/stores.js.map +1 -1
  173. package/dist/text-index.d.ts +9 -1
  174. package/dist/text-index.d.ts.map +1 -1
  175. package/dist/text-index.js +28 -9
  176. package/dist/text-index.js.map +1 -1
  177. package/dist/text.d.ts +87 -3
  178. package/dist/text.d.ts.map +1 -1
  179. package/dist/text.js +526 -24
  180. package/dist/text.js.map +1 -1
  181. package/dist/tools.d.ts +61 -1
  182. package/dist/tools.d.ts.map +1 -1
  183. package/dist/tools.js +461 -46
  184. package/dist/tools.js.map +1 -1
  185. package/dist/types.d.ts +103 -4
  186. package/dist/types.d.ts.map +1 -1
  187. package/dist/word-styles.d.ts +102 -0
  188. package/dist/word-styles.d.ts.map +1 -0
  189. package/dist/word-styles.js +419 -0
  190. package/dist/word-styles.js.map +1 -0
  191. package/dist/xlsx.d.ts +23 -0
  192. package/dist/xlsx.d.ts.map +1 -0
  193. package/dist/xlsx.js +511 -0
  194. package/dist/xlsx.js.map +1 -0
  195. package/dist/xml-stream.d.ts +55 -0
  196. package/dist/xml-stream.d.ts.map +1 -0
  197. package/dist/xml-stream.js +235 -0
  198. package/dist/xml-stream.js.map +1 -0
  199. package/dist/zip-directory.d.ts +43 -0
  200. package/dist/zip-directory.d.ts.map +1 -0
  201. package/dist/zip-directory.js +130 -0
  202. package/dist/zip-directory.js.map +1 -0
  203. package/docs/README.md +288 -0
  204. package/docs/api.md +37 -381
  205. package/docs/configuration.md +28 -558
  206. package/docs/getting-started.md +407 -223
  207. package/docs/guides/anthropic.md +590 -0
  208. package/docs/guides/conversations.md +629 -0
  209. package/docs/guides/costs-and-limits.md +728 -0
  210. package/docs/guides/deployment.md +720 -0
  211. package/docs/guides/errors-and-reliability.md +748 -0
  212. package/docs/guides/explorer-model.md +399 -0
  213. package/docs/guides/openai-compatible.md +602 -0
  214. package/docs/guides/own-adapter-and-loop.md +1169 -0
  215. package/docs/guides/pdfs.md +1024 -0
  216. package/docs/guides/storage.md +731 -0
  217. package/docs/guides/testing.md +1203 -0
  218. package/docs/guides/vertex-and-gemini.md +717 -0
  219. package/docs/guides/web-app.md +1590 -0
  220. package/docs/how-it-works.md +1035 -164
  221. package/docs/measurements.md +881 -0
  222. package/docs/publishing.md +274 -46
  223. package/docs/reference/anthropic.md +427 -0
  224. package/docs/reference/ask.md +910 -0
  225. package/docs/reference/errors-and-retries.md +760 -0
  226. package/docs/reference/events.md +1001 -0
  227. package/docs/reference/gemini.md +827 -0
  228. package/docs/reference/library.md +1598 -0
  229. package/docs/reference/node.md +706 -0
  230. package/docs/reference/openai.md +385 -0
  231. package/docs/reference/tools.md +1031 -0
  232. package/docs/security.md +940 -101
  233. package/docs/troubleshooting.md +1410 -0
  234. package/package.json +7 -3
  235. package/src/analyze.ts +204 -49
  236. package/src/anthropic/adapter.ts +200 -40
  237. package/src/ask.ts +1151 -210
  238. package/src/decode.ts +89 -0
  239. package/src/encoding.ts +850 -0
  240. package/src/errors.ts +125 -0
  241. package/src/events.ts +451 -0
  242. package/src/evidence.ts +11 -2
  243. package/src/extract.ts +191 -308
  244. package/src/gemini/adapter.ts +127 -70
  245. package/src/gemini/chat.ts +28 -4
  246. package/src/gemini/endpoints.ts +12 -2
  247. package/src/gemini/errors.ts +34 -1
  248. package/src/gemini/generate.ts +42 -13
  249. package/src/gemini/index.ts +3 -3
  250. package/src/gemini/sse.ts +1 -1
  251. package/src/groups.ts +162 -0
  252. package/src/html.ts +1071 -0
  253. package/src/http.ts +376 -1
  254. package/src/index.ts +29 -6
  255. package/src/library.ts +498 -93
  256. package/src/limiter.ts +6 -1
  257. package/src/map-reduce.ts +252 -51
  258. package/src/model.ts +244 -4
  259. package/src/node/handlers.ts +196 -31
  260. package/src/node/index.ts +4 -0
  261. package/src/node/ingest-child.ts +61 -0
  262. package/src/node/isolated.ts +464 -0
  263. package/src/node/sse.ts +198 -0
  264. package/src/office.ts +1047 -0
  265. package/src/openai/adapter.ts +319 -38
  266. package/src/output-limit.ts +44 -8
  267. package/src/pause.ts +41 -0
  268. package/src/pdf-pages.ts +270 -20
  269. package/src/pdf-pictures.ts +56 -9
  270. package/src/pdf-work.ts +722 -0
  271. package/src/peers.ts +29 -0
  272. package/src/plan.ts +70 -12
  273. package/src/ranged.ts +4 -2
  274. package/src/retry.ts +49 -5
  275. package/src/search.ts +800 -155
  276. package/src/sse.ts +153 -28
  277. package/src/stores.ts +5 -2
  278. package/src/text-index.ts +30 -9
  279. package/src/text.ts +524 -23
  280. package/src/tools.ts +445 -46
  281. package/src/types.ts +108 -5
  282. package/src/word-styles.ts +420 -0
  283. package/src/xlsx.ts +478 -0
  284. package/src/xml-stream.ts +224 -0
  285. package/src/zip-directory.ts +136 -0
@@ -1,308 +1,492 @@
1
- # Integration guide
1
+ # Getting started
2
2
 
3
- This guide adds large-file support to an existing chatbot backend in four steps. The examples use
4
- Express and Gemini, with notes for other setups.
3
+ This page takes you from `npm install` to a first answer about a file, then through the steps of
4
+ adding the library to an app. Each step is short and links to the guide that explains it.
5
5
 
6
- ## 1. Install
6
+ ## Install
7
7
 
8
8
  ```bash
9
9
  npm install llm-large-files
10
- npm install jszip unpdf # optional: DOCX/PPTX and PDF support
11
- npm install @cantoo/pdf-lib # optional: let the model look at pages of a PDF (pictures, charts)
12
10
  ```
13
11
 
14
- ## 2. Create the library once
12
+ The library needs Node.js 20.19 or later. It is an ES module, and its TypeScript types come with
13
+ it. From CommonJS code, `require("llm-large-files")` works on the Node versions that load ES
14
+ modules with `require()` by default: 20.19 and later in Node 20, 22.12 and later, and 23 and later.
15
+ On Node 21 and on 22.0 to 22.11, load it with `import("llm-large-files")`.
15
16
 
16
- ```ts
17
- // large-files.ts
18
- import { createLargeFiles, FileDocumentStore } from "llm-large-files";
17
+ Text, Markdown, logs, JSON and CSV need nothing more. Three optional packages add the rest:
19
18
 
20
- export const files = createLargeFiles({
21
- store: new FileDocumentStore(process.env.LARGE_FILES_DIR ?? "./data/large-files"),
22
- // Your connector's real limits. Anything left out uses the defaults in docs/configuration.md.
23
- budget: { contextTokens: 1_000_000, maxRequestBytes: 10_000_000 },
24
- ttlMs: 72 * 60 * 60 * 1000, // keep uploads for 3 days
25
- maxUploadBytes: 100 * 1024 * 1024,
26
- // Optional: keep uploaded PDFs, so the model can look at their pages (see "Pictures" below).
27
- // keepOriginals: ["pdf"],
28
- });
19
+ ```bash
20
+ npm install jszip unpdf @cantoo/pdf-lib # Node 24 and later
21
+ npm install jszip unpdf@1 @cantoo/pdf-lib # Node 22
22
+ npm install jszip unpdf@1.7.0 @cantoo/pdf-lib # Node 20
23
+ ```
29
24
 
30
- // Reclaim disk space from expired uploads (expired files are already ignored on read).
31
- setInterval(() => void files.sweep(), 60 * 60 * 1000).unref();
25
+ | Package | What it enables |
26
+ | --- | --- |
27
+ | `jszip` | DOCX, PPTX and XLSX files. |
28
+ | `unpdf` | PDF files: their text, with tables rebuilt as rows. |
29
+ | `@cantoo/pdf-lib` | The model can look at the pages of a PDF (`view_pages`, with `keepOriginals`). The text of a PDF also marks the pages that show a picture. |
30
+
31
+ Without the package a format needs, its upload fails with an error that names the package, such
32
+ as `Reading PDF files needs the optional dependency "unpdf".` Install `@cantoo/pdf-lib` before you
33
+ turn on `keepOriginals`: without it, every look at a page fails. The details are in
34
+ [PDFs](./guides/pdfs.md).
35
+
36
+ On Node 24 and later, `npm install unpdf` installs unpdf 2, which asks for Node 24. On Node 22,
37
+ install `unpdf@1`, and on Node 20, `unpdf@1.7.0`. An unpdf that cannot read PDFs on your version
38
+ of Node is refused at the first PDF, with a message that says what to install, such as
39
+ `The unpdf installed cannot read PDF files on Node 20 (…). Install unpdf 1.7.0 (npm install unpdf@1.7.0), or run Node 22 or later.`
40
+
41
+ The Vertex AI samples on this page also use Google's auth library, which is not a dependency of
42
+ this package:
43
+
44
+ ```bash
45
+ npm install google-auth-library
32
46
  ```
33
47
 
34
- Running several server instances? Give them a shared store. Use a shared disk, or implement
35
- `DocumentStore` over Redis, S3, or your database (see [configuration](configuration.md#stores)).
48
+ ## Quickstart
36
49
 
37
- ## 3. Accept uploads
50
+ This script ingests one file and asks one question about it, with Gemini on Vertex AI. You need a
51
+ Google Cloud project with Vertex AI turned on, and Application Default Credentials (on your own
52
+ machine, `gcloud auth application-default login`).
38
53
 
39
54
  ```ts
40
- import express from "express";
41
- import { createDocumentHandlers } from "llm-large-files/node";
55
+ // quickstart.mts
56
+ import { readFile } from "node:fs/promises";
57
+ import { basename } from "node:path";
58
+ import { GoogleAuth } from "google-auth-library";
59
+ import { createLargeFiles, MemoryDocumentStore } from "llm-large-files";
60
+ import { askGemini, vertexAi } from "llm-large-files/gemini";
42
61
 
43
- const app = express();
44
- const documents = createDocumentHandlers(files, {
45
- // Uploads become private to this user. Return undefined to allow anonymous use.
46
- getOwner: (req) => (req as any).user?.id,
62
+ const [path, question] = process.argv.slice(2);
63
+ if (!path || !question) throw new Error('Usage: node quickstart.mts <file> "<question>"');
64
+
65
+ // 1. The library. This one keeps documents in memory, for as long as the process runs.
66
+ const files = createLargeFiles({ store: new MemoryDocumentStore() });
67
+
68
+ // 2. Ingest the file: its text is extracted, measured and stored.
69
+ const doc = await files.ingest({ name: basename(path), bytes: await readFile(path) });
70
+ console.log(`${doc.name}: ${doc.format}, ${doc.lines} lines, about ${doc.estimatedTokens} tokens\n`);
71
+
72
+ // 3. Ask. The access token comes from Application Default Credentials.
73
+ const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
74
+ const endpoint = vertexAi({
75
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
76
+ location: "global", // the default; or "us", "eu", or a region such as "europe-west4"
77
+ model: "gemini-3.8-flash",
78
+ accessToken: async () => (await auth.getAccessToken())!,
47
79
  });
48
80
 
49
- // Mount before express.json(): the body is the raw file, not JSON.
50
- app.post("/api/documents", documents.upload);
51
- app.get("/api/documents/:id", (req, res) => documents.get(req, res, req.params.id));
52
- app.delete("/api/documents/:id", (req, res) => documents.remove(req, res, req.params.id));
53
- app.use(express.json());
81
+ const result = await askGemini({
82
+ files,
83
+ endpoint,
84
+ documentIds: [doc.id],
85
+ messages: [{ role: "user", text: question }],
86
+ onText: (delta) => process.stdout.write(delta), // the answer, as it streams
87
+ });
88
+
89
+ console.log(`\n\n${result.plan.inline.length > 0 ? "Read whole" : "Searched with tools"}, ${result.turns} chat request(s)`);
90
+ for (const step of result.steps) console.log(`- ${step}`);
54
91
  ```
55
92
 
56
- The response is a `DocumentSummary`:
93
+ Node 22.18 and later in Node 22, and Node 23.6 and later, run TypeScript files directly:
57
94
 
58
- ```json
59
- { "id": "doc_3f9c…", "name": "app.log", "mimeType": "text/plain", "format": "log",
60
- "bytes": 5082044, "lines": 60000, "estimatedTokens": 1270511, "expiresAt": "2026-11-09T07:43:14.435Z" }
95
+ ```bash
96
+ GOOGLE_CLOUD_PROJECT=your-project-id node quickstart.mts ./app.log "What failed first, and when?"
61
97
  ```
62
98
 
63
- Errors are JSON `{ "error": "…" }`: 400 when there's no file name, 413 when the file is too large,
64
- 422 for an unreadable file (binary, empty, a zip bomb, or a scanned PDF that cannot be shown page by
65
- page), and 500 when the server fails, as when the store's disk is full. `getOwner` can refuse a
66
- request by throwing an error with a `status`, such as 401 (see the [API reference](api.md)).
99
+ In PowerShell, set the variable with `$env:GOOGLE_CLOUD_PROJECT = "your-project-id"`, then run
100
+ `node quickstart.mts ./app.log "What failed first, and when?"`. On older versions of Node, compile
101
+ the file first, with `typescript` and `@types/node` installed:
102
+ `npx tsc --module nodenext --target es2022 quickstart.mts`. Then run `node quickstart.mjs` with
103
+ the same arguments.
104
+
105
+ What happened:
106
+
107
+ - `ingest` extracted the text of the file, counted its lines and estimated its tokens, and stored
108
+ it. The `doc.id` it returned is how you name the document from then on.
109
+ - `askGemini` planned the request. A document that fits the budget goes into the prompt whole: by
110
+ default up to 200,000 tokens of document text, in a window of 1,000,000 tokens and a request of
111
+ 10 MB. A larger one becomes a short card, and the model gets tools to search it, read lines of
112
+ it, get an overview of it, and read it whole in parts.
113
+ - When the model used tools, the loop ran its calls and sent it what they returned, until it
114
+ answered: at most 12 chat requests by default, the last of which must be answered in text, and
115
+ one more when that answer comes back without text. `result.steps` lists what it did, for example
116
+ `Search app.log (exact) for “timeout” — 12 matching lines`.
67
117
 
68
- **Other servers.** The handlers take Node's `IncomingMessage` / `ServerResponse`, so they work with
69
- `node:http`, Express, Koa (`ctx.req`, `ctx.res`), Fastify (`request.raw`, `reply.raw`), and Next.js
70
- API routes on the Node runtime. Not using Node HTTP? Call `files.ingest({ name, mimeType, bytes, owner })`
71
- yourself and return `toDocumentSummary(meta)`.
118
+ The details of the plan and the loop are in [How it works](./how-it-works.md).
72
119
 
73
- ### Browser
120
+ The quickstart works the same with other providers. Each sample below replaces its step 3, from
121
+ `const auth` to the end of the `askGemini` call. Put the sample's imports in place of the two
122
+ Vertex AI imports, those of `google-auth-library` and `llm-large-files/gemini`.
123
+
124
+ ### With a Gemini API key
125
+
126
+ `askGemini` takes the Gemini Developer API with an API key:
74
127
 
75
128
  ```ts
76
- async function uploadLargeFile(file: File) {
77
- const response = await fetch("/api/documents", {
78
- method: "POST",
79
- headers: {
80
- "Content-Type": "application/octet-stream",
81
- "X-File-Name": encodeURIComponent(file.name),
82
- "X-File-Type": file.type,
83
- },
84
- body: file,
85
- });
86
- const result = await response.json();
87
- if (!response.ok) throw new Error(result.error);
88
- return result; // keep result.id with the conversation
89
- }
129
+ import { askGemini, geminiApi } from "llm-large-files/gemini";
130
+
131
+ const result = await askGemini({
132
+ files,
133
+ endpoint: geminiApi({ apiKey: process.env.GEMINI_API_KEY!, model: "gemini-3.8-flash" }),
134
+ documentIds: [doc.id],
135
+ messages: [{ role: "user", text: question }],
136
+ onText: (delta) => process.stdout.write(delta),
137
+ });
90
138
  ```
91
139
 
92
- **Which files should go to the server?** Anything your current inline path can't handle. A
93
- practical rule is text over about 512 KB and PDFs over about 7 MB (base64 makes them about a
94
- third bigger). Smaller files can keep your existing path. PDFs under your payload limit are better
95
- sent inline, because Gemini then reads every page with its layout and images. For larger PDFs,
96
- turn on `keepOriginals` (below) so the model can ask for the pages it needs.
140
+ ### With an OpenAI-compatible model
141
+
142
+ `askGemini` is `askWithFiles` with a Gemini model. With any other model, call `askWithFiles` and
143
+ pass the model as an adapter. `openAiCompatible()` speaks Chat Completions: OpenAI, Azure OpenAI,
144
+ DeepSeek, OpenRouter, vLLM, Ollama, LiteLLM, llama.cpp.
97
145
 
98
- ## 4. Answer questions
146
+ ```ts
147
+ import { askWithFiles } from "llm-large-files";
148
+ import { openAiCompatible } from "llm-large-files/openai";
99
149
 
100
- ### With Gemini or Vertex AI: `askGemini`
150
+ const model = openAiCompatible({
151
+ baseUrl: "https://api.openai.com/v1", // the default; DeepSeek, OpenRouter, vLLM, Ollama: their own
152
+ apiKey: process.env.OPENAI_API_KEY!,
153
+ model: "gpt-5.5",
154
+ contextTokens: 400_000, // your model's context window: the plan follows it
155
+ });
156
+
157
+ const result = await askWithFiles({
158
+ files,
159
+ model,
160
+ documentIds: [doc.id],
161
+ messages: [{ role: "user", text: question }],
162
+ onText: (delta) => process.stdout.write(delta),
163
+ });
164
+ ```
165
+
166
+ Set `contextTokens` to the window of your model. Without it, the plan assumes the library's
167
+ window, 1,000,000 tokens unless you set another. The recipe for each server is in
168
+ [OpenAI-compatible endpoints](./guides/openai-compatible.md).
169
+
170
+ ### With Claude
101
171
 
102
172
  ```ts
103
- import { askGemini, DocumentsNotFoundError, geminiApi } from "llm-large-files/gemini";
104
-
105
- const endpoint = geminiApi({ apiKey: process.env.GEMINI_API_KEY!, model: "gemini-3.8-flash" });
106
-
107
- app.post("/api/chat", async (req, res) => {
108
- const { messages, documentIds } = req.body; // messages: [{ role: "user" | "model", text }]
109
- res.writeHead(200, { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" });
110
- const send = (event: string, data: unknown) => res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
111
- const abort = new AbortController();
112
- res.on("close", () => abort.abort());
113
- try {
114
- await askGemini({
115
- files, endpoint, messages, documentIds,
116
- owner: (req as any).user?.id,
117
- system: "You are our support assistant.",
118
- generationConfig: { temperature: 0.3, maxOutputTokens: 8192 },
119
- signal: abort.signal,
120
- onText: (text) => send("text", text), // answer, streamed
121
- onActivity: (text) => send("activity", text), // "Searching app.log for “timeout”…"
122
- onStep: (text) => send("step", text), // "Search app.log … — 12 matching lines"
123
- });
124
- send("done", {});
125
- } catch (error) {
126
- send("error", error instanceof DocumentsNotFoundError
127
- ? "A file has expired. Please attach it again."
128
- : String((error as Error).message));
129
- }
130
- res.end();
173
+ import { askWithFiles } from "llm-large-files";
174
+ import { anthropic } from "llm-large-files/anthropic";
175
+
176
+ const model = anthropic({
177
+ apiKey: process.env.ANTHROPIC_API_KEY!,
178
+ model: "claude-opus-5-5",
179
+ contextTokens: 1_000_000, // your model's context window: the plan follows it
180
+ });
181
+
182
+ const result = await askWithFiles({
183
+ files,
184
+ model,
185
+ documentIds: [doc.id],
186
+ messages: [{ role: "user", text: question }],
187
+ onText: (delta) => process.stdout.write(delta),
131
188
  });
132
189
  ```
133
190
 
134
- What `askGemini` does each turn:
191
+ Thinking, streaming and gateways for Claude are in [Claude](./guides/anthropic.md).
192
+
193
+ ## Integrate it into your app
135
194
 
136
- 1. Measures the rest of the request (history, system prompt, other files).
137
- 2. Plans the documents against your budget. Each one goes in whole, or becomes a card plus tools.
138
- 3. Adds each document's text or card at the start of the first user message, where it stays for
139
- the whole conversation (so follow-up questions reuse Gemini's prompt cache), and a short tool
140
- guide to the system prompt.
141
- 4. Runs the tool loop if needed (up to `limits.toolTurns` requests, default 12). If the model keeps
142
- searching, the last request is sent without tools so it has to answer. `result.answered` is
143
- `false` in the rare case that there is still no answer (a blocked prompt, or an empty reply).
144
- 5. Sends a request again when the model was busy or could not be reached, keeps the request
145
- inside the model's window as tool results add up, and returns what the question used
146
- (`result.usage`) and what it read (`result.evidence`).
195
+ The quickstart holds everything in one process for one question. An app creates the library once,
196
+ takes uploads in one request and questions in others, and keeps the conversation between them.
197
+ The samples below use Gemini on Vertex AI. With another provider, use `askWithFiles` as above:
198
+ the options these samples use are the same, with `model` in place of `endpoint`. Model settings
199
+ that `askGemini` takes (`generationConfig`, `toolFilePlacement`, the waits) are options of the
200
+ adapter there.
147
201
 
148
- `askGemini` is `askWithFiles` with a Gemini model. Everything it does, it does for
149
- [any other model](#with-another-model-askwithfiles) too.
202
+ ### 1. Create the library once
150
203
 
151
- **Vertex AI:**
204
+ Create the library and the endpoint when the server starts, and share them between requests.
152
205
 
153
206
  ```ts
207
+ // large-files.ts: created once, when the server starts, and shared by every request.
154
208
  import { GoogleAuth } from "google-auth-library";
209
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
155
210
  import { vertexAi } from "llm-large-files/gemini";
156
211
 
212
+ export const files = createLargeFiles({
213
+ // Text extracted from uploads is kept here. Several servers need one shared store.
214
+ store: new FileDocumentStore(process.env.LARGE_FILES_DIR ?? "./data/large-files"),
215
+ // The context window of the model that answers (1,000,000 is the default). The rest follows it.
216
+ budget: { contextTokens: 1_000_000 },
217
+ });
218
+
157
219
  const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
158
- const endpoint = vertexAi({
159
- project: "my-project",
160
- location: "global", // or "us", "eu", "europe-west4", …
220
+ export const endpoint = vertexAi({
221
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
161
222
  model: "gemini-3.8-flash",
162
223
  accessToken: async () => (await auth.getAccessToken())!,
163
224
  });
164
- ```
165
-
166
- **An enterprise gateway** that proxies Generate Content:
167
225
 
168
- ```ts
169
- const endpoint = {
170
- url: "https://llm-gateway.corp.example/gemini/models/gemini-3.8-flash:generateContent",
171
- streamUrl: "https://llm-gateway.corp.example/gemini/models/gemini-3.8-flash:streamGenerateContent?alt=sse", // optional
172
- headers: { Authorization: `Bearer ${process.env.GATEWAY_TOKEN}`, "Content-Type": "application/json" },
173
- };
226
+ // An expired document is ignored at once. This frees the space it took.
227
+ setInterval(() => {
228
+ files.sweep().catch((error) => console.error("sweep failed", error));
229
+ }, 60 * 60 * 1000).unref();
174
230
  ```
175
231
 
176
- Without `streamUrl`, answers arrive in one piece (and `onText` fires once).
232
+ Documents are kept for 72 hours (`ttlMs`), and uploads are taken up to 100 MB
233
+ (`maxUploadBytes`). To let the model look at the pages of a PDF, add `keepOriginals: ["pdf"]`
234
+ ([PDFs](./guides/pdfs.md)). Every option is in the
235
+ [library reference](./reference/library.md#largefilesoptions).
177
236
 
178
- **Existing Gemini history.** If your chat already stores Gemini `contents` (with images or inline
179
- PDFs), pass `contents` instead of `messages`; document text is added at the start of the first user turn.
237
+ Where the documents live is up to your app: a shared volume for `FileDocumentStore`, or a store of
238
+ your own over your database or object storage, laid out per user and per chat session. See
239
+ [Storage](./guides/storage.md), and [Deployment](./guides/deployment.md) for several servers.
240
+ Vertex AI settings for production (credentials, location, quotas) are in
241
+ [Gemini and Vertex AI](./guides/vertex-and-gemini.md).
180
242
 
181
- **A second model for the searching (optional).** The model you name does both halves of the work:
182
- it searches and reads a large file, and it answers. `explorerModel` gives the first half to another
183
- model, for example a cheaper one, and `model` then only writes the answer:
243
+ ### 2. Accept uploads
244
+
245
+ `createDocumentHandlers` gives you upload, get and delete handlers for any Node HTTP server:
246
+ `node:http`, Express, Fastify (`request.raw`, `reply.raw`), and Next.js API routes on the Node
247
+ runtime (Fastify and Next.js need a step first: see
248
+ [Web app](./guides/web-app.md#mount-them-in-plain-nodehttp)).
184
249
 
185
250
  ```ts
186
- const endpoint = geminiApi({
187
- apiKey: process.env.GEMINI_API_KEY!,
188
- model: "gemini-3.8-flash",
189
- explorerModel: process.env.GEMINI_EXPLORER_MODEL, // unset or empty: one model does both
251
+ import express from "express";
252
+ import { createDocumentHandlers } from "llm-large-files/node";
253
+ import { files } from "./large-files.js";
254
+
255
+ const app = express();
256
+ const documents = createDocumentHandlers(files, {
257
+ // Uploads become private to this user. undefined: anonymous. currentUserId is your auth.
258
+ getOwner: (request) => currentUserId(request),
190
259
  });
260
+
261
+ // Before any body parser: the body of an upload is the raw file.
262
+ app.post("/api/documents", documents.upload);
263
+ app.get("/api/documents/:id", (req, res) => documents.get(req, res, req.params.id));
264
+ app.delete("/api/documents/:id", (req, res) => documents.remove(req, res, req.params.id));
265
+ app.use(express.json());
191
266
  ```
192
267
 
193
- `vertexAi()` takes it the same way, and an endpoint of your own takes the explorer's URL as
194
- `explorerUrl`. What each model gets, and what it costs, is in
195
- [An explorer model](configuration.md#an-explorer-model).
268
+ The browser posts the raw file, with its name in an `X-File-Name` header (URI-encoded). The
269
+ response is a `201` with a `DocumentSummary`: `id`, `name`, `format`, `lines`, `estimatedTokens`,
270
+ `expiresAt` and more. A text file that was not valid UTF-8 also has `encoding`, the older encoding
271
+ it was read in (`"windows-1255"`), or `replacedCharacters`, the characters stored as �, or both.
272
+ Keep the `id` with the chat session. Not on a Node HTTP server, or taking multipart forms? Call
273
+ `files.ingest({ name, mimeType, bytes, owner })` yourself and return `toDocumentSummary(meta)`.
274
+
275
+ `getOwner` returns the signed-in user's ID, or `undefined` for an anonymous upload. An empty
276
+ string, a string of spaces or `null` would be one owner shared by every caller without a user, so
277
+ the upload is refused: `500` with `{ "error": "Upload failed (empty owner)." }`. Return the ID
278
+ itself, not the user object (`{ "error": "Upload failed (owner is not a string)." }`). Both come
279
+ before the body is read.
196
280
 
197
- ### Pictures, charts and scans in PDFs
281
+ The browser side, every status and other servers are in [Web app](./guides/web-app.md); the
282
+ routes in full are in the [node reference](./reference/node.md).
198
283
 
199
- The text of a PDF does not hold its pictures. To let the model look at a page when the text is not
200
- enough, install `@cantoo/pdf-lib` and keep the uploaded PDFs:
284
+ ### 3. Ask with the user's history, and stream the answer
285
+
286
+ Send the whole conversation on every turn, with all the documents of the session. The plan is made
287
+ again for each question, because the history grows.
201
288
 
202
289
  ```ts
203
- export const files = createLargeFiles({
204
- store: new FileDocumentStore("./data/large-files"),
205
- keepOriginals: ["pdf"],
206
- });
290
+ // chat.ts
291
+ import type { ChatTurn, ToolTurn } from "llm-large-files";
292
+ import { askGemini } from "llm-large-files/gemini";
293
+ import { endpoint, files } from "./large-files.js";
294
+
295
+ // A chat session as your app stores it: who owns it, its documents, and its turns.
296
+ export type Session = { userId: string; documentIds: string[]; turns: StoredTurn[] };
297
+ export type StoredTurn = { question: string; toolTurns: ToolTurn[]; answer: string };
298
+
299
+ export async function ask(session: Session, question: string, send: (event: string, data: unknown) => void, signal: AbortSignal) {
300
+ // The whole history, on every turn, with the tool rounds of each earlier question in its place.
301
+ const messages: Array<ChatTurn | ToolTurn> = session.turns.flatMap((turn): Array<ChatTurn | ToolTurn> => [
302
+ { role: "user", text: turn.question },
303
+ ...turn.toolTurns,
304
+ { role: "assistant", text: turn.answer },
305
+ ]);
306
+ messages.push({ role: "user", text: question });
307
+
308
+ const result = await askGemini({
309
+ files,
310
+ endpoint,
311
+ messages,
312
+ documentIds: session.documentIds, // every document of the session, on every turn
313
+ owner: session.userId,
314
+ signal,
315
+ onText: (delta) => send("text", delta), // the answer, as it streams
316
+ onActivity: (text) => send("activity", text), // short-lived: "Search app.log (keywords) for “timeout”…"
317
+ onStep: (text) => send("step", text), // done: "Search app.log (exact) for “timeout” — 12 matching lines"
318
+ });
319
+
320
+ if (!result.answered) {
321
+ send("error", "No answer came back. Please ask again.");
322
+ return;
323
+ }
324
+ // Keep what the question read with its answer: the next question starts from it.
325
+ session.turns.push({ question, toolTurns: result.toolTurns, answer: result.text });
326
+ send("done", {});
327
+ }
207
328
  ```
208
329
 
209
- `askGemini` needs no change. It offers the model a tool, `view_pages`, and sends the pages it asks
210
- for (up to five a call) as a small PDF. A look shows up among the steps:
330
+ - The last message must be the user's question. `"model"` is accepted for `"assistant"`.
331
+ - `owner` must be the owner the documents were uploaded with. A document of another owner is
332
+ treated as missing.
333
+ - `send` stands for your transport: in a web app, a Server-Sent Event. The answer streams when
334
+ `onText` is set and the endpoint has a stream URL, as `vertexAi()` and `geminiApi()` do.
335
+ - Show the steps and activity lines as plain text, never as markdown or HTML: they quote what the
336
+ model sent, which a file can steer ([Security](./security.md#what-the-library-logs)).
337
+ - Abort `signal` when the client goes away, so the question stops.
338
+ - `answered` is `false` when the model's last turn had no text: a blocked prompt, a reply cut off,
339
+ or a tool call that could not be read. An answer that comes back empty, or with a tool call in
340
+ place of the text, is asked for once more first. Show your own message then.
211
341
 
212
- ```
213
- ✓ Look at report.pdf pages 12-14
214
- ```
342
+ The route, the browser side and cancelling are in [Web app](./guides/web-app.md). To have a
343
+ second, cheaper model search the files while this one writes the answer, add `explorerModel` to
344
+ `vertexAi()`: see [An explorer model](./guides/explorer-model.md).
215
345
 
216
- With originals kept, a scanned PDF of up to 30 pages is accepted too, and read page by page.
217
- Kept files take disk space until they expire, which is why this is off by default. The limits, the
218
- costs and the measurements are in [Pictures in PDFs](configuration.md#pictures-in-pdfs), and what
219
- to think about before turning it on in [Security](security.md#original-files).
346
+ ### 4. Keep `toolTurns` with the answer
220
347
 
221
- ### With another model: `askWithFiles`
348
+ `result.toolTurns` holds the tool calls of the question and what they returned, as plain JSON.
349
+ Store it with the answer, and put it back between the question and the answer, as `ask()` does
350
+ above. The model then sees what it found before, and a follow-up question often needs no new
351
+ search. A call whose result is still in the conversation in full is not run again: the model gets
352
+ a pointer to it, and the step ends with `— already shown above`.
222
353
 
223
- The loop is not Gemini's. `askWithFiles` takes the model as an adapter, and two adapters come with
224
- the package next to Gemini's:
354
+ Storing history across servers, keeping it inside the window, and converting history that is in a
355
+ provider's own form are in [Conversations](./guides/conversations.md).
225
356
 
226
- ```ts
227
- import { askWithFiles, DocumentsNotFoundError, ModelRequestError } from "llm-large-files";
228
- import { openAiCompatible } from "llm-large-files/openai";
229
- import { anthropic } from "llm-large-files/anthropic";
357
+ ### 5. Handle errors
230
358
 
231
- // Any Chat Completions endpoint: OpenAI, Azure OpenAI, DeepSeek, LiteLLM, vLLM, Ollama, OpenRouter.
232
- const model = openAiCompatible({
233
- baseUrl: "https://api.deepseek.com/v1",
234
- apiKey: process.env.DEEPSEEK_API_KEY!,
235
- model: "deepseek-v4-pro",
236
- contextTokens: 1_000_000, // the budget of a question follows it
237
- body: { temperature: 0.3 },
238
- });
359
+ Before a question fails, the loop sends a failed request again when a wait can mend it, recovers
360
+ from a request too large, and asks once more after an empty or unreadable turn
361
+ ([Errors and reliability](./guides/errors-and-reliability.md)). What still fails is thrown:
239
362
 
240
- // Or Claude:
241
- const claude = anthropic({ apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-opus-5-5", fallbacks: "default" });
363
+ ```ts
364
+ import { DocumentsNotFoundError, DocumentStoreError, errorKindOf, partialResultOf } from "llm-large-files";
365
+ import { ask } from "./chat.js";
366
+
367
+ // session, question, send and signal: as in step 3.
368
+ try {
369
+ await ask(session, question, send, signal);
370
+ } catch (error) {
371
+ if (!signal.aborted) send("error", messageFor(error)); // after an abort, no one is listening
372
+ // What a failed question had found and used, or undefined.
373
+ const partial = partialResultOf(error);
374
+ if (partial) console.warn(`The failed question used ${partial.usage.inputTokens} input tokens`);
375
+ }
242
376
 
243
- const result = await askWithFiles({
244
- files, model, documentIds, messages,
245
- owner: req.user?.id,
246
- system: "You are our support assistant.",
247
- signal: abort.signal,
248
- onText: (text) => send("text", text),
249
- onActivity: (text) => send("activity", text),
250
- onStep: (text) => send("step", text),
251
- });
377
+ function messageFor(error: unknown): string {
378
+ if (error instanceof DocumentsNotFoundError) return "A file is no longer available. Please attach it again.";
379
+ if (error instanceof DocumentStoreError) return "Your files could not be read just now. Please try again.";
380
+ switch (errorKindOf(error)) {
381
+ case "quota":
382
+ return "The assistant is not available right now. Please tell support.";
383
+ case "rate_limit":
384
+ return "The assistant is busy. Please try again in a minute.";
385
+ case "auth":
386
+ case "invalid":
387
+ return "The assistant is not set up correctly. Please tell support.";
388
+ case "context_overflow":
389
+ return "This conversation is too long for the model. Please start a new chat.";
390
+ case undefined:
391
+ return "Something went wrong. Please try again.";
392
+ default:
393
+ return "The model did not answer. Please try again.";
394
+ }
395
+ }
252
396
  ```
253
397
 
254
- `messages` are `{ role: "user" | "assistant", text }`. A turn that holds more than text takes
255
- parts, with anything but text in the provider's own form:
256
- `{ role: "user", parts: [{ text: "What is in this picture?" }, { native: { type: "image_url", image_url: { url } } }] }`.
398
+ - `DocumentsNotFoundError` (`.ids`): a document expired, was deleted, was never uploaded, or
399
+ belongs to another owner. It is thrown before any model request.
400
+ - `DocumentStoreError`: the store could not be read just now. It does not mean the documents are
401
+ gone: the same request may work a moment later.
402
+ - `ModelRequestError`: the model failed. `.kind` says how (`quota`, `rate_limit`, `timeout`,
403
+ `unreachable`, `server`, `auth`, `invalid`, `context_overflow`), and `.status` is the HTTP
404
+ status, or 0 when no answer came. `errorKindOf(error)` reads the kind of any error that has one.
405
+ - `partialResultOf(error)` gives the steps, `toolTurns` and `usage` of a question that failed
406
+ under way, so you can still keep and count them.
407
+
408
+ What to tell the user for each case, and how to change the retries and the waits, are in
409
+ [Errors and reliability](./guides/errors-and-reliability.md).
410
+
411
+ ### 6. Set limits
257
412
 
258
- **Two models, of two providers.** `explorer` is a second adapter. It makes the tool calls and
259
- reads whole files in parts, and `model` writes the answer from what the tools returned:
413
+ A question costs what its requests take in. These options bound it:
260
414
 
261
415
  ```ts
262
- await askWithFiles({ files, model: claude, explorer: model, documentIds, messages });
416
+ import { askGemini } from "llm-large-files/gemini";
417
+
418
+ // files, endpoint, messages and session: as in step 3.
419
+ const result = await askGemini({
420
+ files,
421
+ endpoint,
422
+ messages,
423
+ documentIds: session.documentIds,
424
+ owner: session.userId,
425
+ limits: {
426
+ toolTurns: 8, // chat requests for one question, the answer included; part reads not counted (default 12)
427
+ inputTokens: 400_000, // input tokens for one question, over all its requests (default: none)
428
+ },
429
+ });
430
+ console.log(result.usage.inputTokens, result.usage.outputTokens, result.usage.requests);
263
431
  ```
264
432
 
265
- **Errors.** A model's HTTP error is a `ModelRequestError` with a `status` (0 when the model could
266
- not be reached). It reaches you after the request was tried again, when another try could have
267
- helped.
268
-
269
- **A model without an adapter** needs one object with a `send` method:
270
- [your own adapter](api.md#your-own-adapter). `files.prepare()` and `files.tools()` are still there
271
- for a loop that is all your own; `view_pages` in such a loop is described in
272
- [Your own loop](configuration.md#your-own-loop).
273
-
274
- ## Keeping the conversation working
275
-
276
- - Send the **full history** each turn when files are attached. The plan is recomputed each time,
277
- because the history grows. Stateful APIs that keep history server-side (such as Gemini
278
- Interactions with `previous_interaction_id`) don't mix with per-turn planning.
279
- - Keep the document IDs with the conversation, not with one message. Pass all of them on every turn.
280
- - Keep **what a question read** with the conversation too. `result.toolTurns` is plain JSON: store
281
- it between the question and its answer, and pass it back in `messages` in that place. The model
282
- then sees its earlier searches and reads, and a follow-up question often needs no new one. In a
283
- live check a follow-up took one request instead of three.
284
-
285
- ```ts
286
- const messages = history.flatMap((turn) => [
287
- { role: "user", text: turn.question }, ...turn.toolTurns, { role: "assistant", text: turn.answer },
288
- ]).concat({ role: "user", text: newQuestion });
289
- ```
290
-
291
- If your history is Gemini `contents`, `geminiToolTurns(result.toolTurns)` gives the rounds in
292
- that form.
293
- - `result.evidence` lists, for each tool call, the document and the lines or pages the model was
294
- shown. Store it with the answer if you want to show sources, or to check a citation later.
295
- - Expired documents raise `DocumentsNotFoundError` (with `.ids`). Ask the user to attach them again.
296
- A store that could not be read raises `DocumentStoreError` instead: the documents are still
297
- there, so retry the request. With `ttlMs: Infinity` documents do not expire at all.
433
+ - `budget.contextTokens` in `createLargeFiles` is the window the plan fits the request into. With
434
+ `askWithFiles`, an adapter's `contextTokens` applies too, and the smaller wins.
435
+ - `limits` also takes `callsPerTurn` (default 8), `wholeDocumentReads` (default 1 per document)
436
+ and `requests` (default: none). See [`AskLimits`](./reference/ask.md#asklimits). An answer that
437
+ comes back without text is asked for once more, which can be one request past `toolTurns`; it is
438
+ not made once `requests` or `inputTokens` is reached.
439
+ - `result.usage` is what the question used, in all and for each model: input, cached input, output
440
+ and thought tokens, and requests. Store it per user or per session to count costs.
441
+
442
+ What costs most, and how to set the budget for each model, are in
443
+ [Costs and limits](./guides/costs-and-limits.md).
298
444
 
299
445
  ## Run the demo
300
446
 
447
+ The repository has two examples that run as they are, with a Gemini API key:
448
+
301
449
  ```bash
302
- git clone https://github.com/renanbazinin/llm-large-files && cd llm-large-files
303
- npm install && npm run build
304
- GEMINI_API_KEY=... node examples/server.ts # http://localhost:3000
305
- GEMINI_API_KEY=... node examples/ask-cli.ts big.log "What failed first?"
450
+ git clone https://github.com/renanbazinin/llm-large-files
451
+ cd llm-large-files
452
+ npm install
453
+ npm run build
454
+ GEMINI_API_KEY=... node examples/server.ts # then open http://localhost:3000
455
+ GEMINI_API_KEY=... node examples/ask-cli.ts ./big.log "What failed first, and when?"
306
456
  ```
307
457
 
308
- The examples need Node 22.18+ or 24 to run TypeScript directly.
458
+ - `examples/server.ts` is a chat server in one file, on `node:http`: an upload route
459
+ (`createDocumentHandlers`), answers streamed as Server-Sent Events, and a small web page. It
460
+ stores uploads in `.data/large-files` and keeps PDFs, so the model can look at their pages.
461
+ `GEMINI_MODEL` picks the model (default `gemini-3.8-flash`), and `GEMINI_EXPLORER_MODEL` adds an
462
+ explorer model. Every upload is anonymous.
463
+ - `examples/ask-cli.ts` asks one question about one file from the command line. Two more
464
+ arguments are optional: the model, and an explorer model.
465
+
466
+ Both need a Node that runs TypeScript directly: 22.18 and later in Node 22, or 23.6 and later.
467
+ Build first: the examples import
468
+ the package by name, which resolves to the repository's own `dist/`. `npm install` in the
469
+ repository also installs the optional packages, so every format works. In PowerShell, set the key
470
+ with `$env:GEMINI_API_KEY = "..."` and then run `node examples/server.ts`.
471
+
472
+ ## Next steps
473
+
474
+ - [Gemini and Vertex AI](./guides/vertex-and-gemini.md): endpoints, access tokens, thinking,
475
+ gateways, Vertex quotas and errors.
476
+ - [OpenAI-compatible endpoints](./guides/openai-compatible.md) and [Claude](./guides/anthropic.md):
477
+ the other adapters.
478
+ - [An explorer model](./guides/explorer-model.md): a cheaper model that searches while another
479
+ answers.
480
+ - [Web app](./guides/web-app.md): uploads, streaming over SSE, cancelling.
481
+ - [Conversations](./guides/conversations.md): history, `toolTurns`, converters.
482
+ - [Storage](./guides/storage.md): your own store, per user and per session.
483
+ - [Deployment](./guides/deployment.md): several servers, memory, proxies and timeouts.
484
+ - [Errors and reliability](./guides/errors-and-reliability.md) and
485
+ [Costs and limits](./guides/costs-and-limits.md).
486
+ - [PDFs](./guides/pdfs.md): tables, pictures, scans and page views.
487
+ - [Your own adapter and loop](./guides/own-adapter-and-loop.md) and
488
+ [Testing](./guides/testing.md).
489
+ - [How it works](./how-it-works.md), [Security](./security.md) and
490
+ [Troubleshooting](./troubleshooting.md).
491
+ - [The documentation index](./README.md), with the reference for every export, and the
492
+ [changelog](../CHANGELOG.md).