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
package/README.md CHANGED
@@ -20,38 +20,56 @@ AI**, **any OpenAI-compatible endpoint** and **Claude** are included, and so are
20
20
  npm install llm-large-files
21
21
  ```
22
22
 
23
- ## Quickstart (Gemini, 10 lines)
23
+ ## Quickstart
24
+
25
+ With Gemini on Vertex AI, and an access token from Application Default Credentials
26
+ (`npm install google-auth-library`; on your own machine, `gcloud auth application-default login`):
24
27
 
25
28
  ```ts
29
+ import { readFile } from "node:fs/promises";
30
+ import { GoogleAuth } from "google-auth-library";
26
31
  import { createLargeFiles, FileDocumentStore } from "llm-large-files";
27
- import { askGemini, geminiApi } from "llm-large-files/gemini";
32
+ import { askGemini, vertexAi } from "llm-large-files/gemini";
28
33
 
29
34
  const files = createLargeFiles({ store: new FileDocumentStore("./data/large-files") });
30
35
 
31
36
  // When a user uploads a file:
32
- const doc = await files.ingest({ name: "app.log", bytes: fileBytes });
37
+ const doc = await files.ingest({ name: "app.log", bytes: await readFile("./app.log") });
33
38
 
34
39
  // When they ask about it:
35
- const { text, steps } = await askGemini({
40
+ const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
41
+ const endpoint = vertexAi({
42
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
43
+ model: "gemini-3.8-flash",
44
+ accessToken: async () => (await auth.getAccessToken())!, // asked for on each request
45
+ });
46
+ const result = await askGemini({
36
47
  files,
37
- endpoint: geminiApi({ apiKey: process.env.GEMINI_API_KEY!, model: "gemini-3.8-flash" }),
48
+ endpoint,
38
49
  documentIds: [doc.id],
39
50
  messages: [{ role: "user", text: "What caused the outage, and when? Cite lines." }],
40
- onText: (delta) => process.stdout.write(delta), // optional streaming
51
+ onText: (delta) => process.stdout.write(delta), // optional: the answer as it streams
41
52
  });
42
53
  ```
43
54
 
44
- `steps` lists what the model did, for example
45
- `Search app.log (exact) for “failover” — 1 matching lines`. Show it under the answer so users can
46
- see where the answer came from.
55
+ `result.steps` lists the tool calls in order, such as
56
+ `Search app.log (exact) for “failover” — 12 matching lines`, with the loop's own notices among
57
+ them (`Older tool results were shortened to make room in the request`). Show it under the answer so
58
+ users can see where the answer came from, as plain text: the steps quote what the model sent.
47
59
 
48
- Using **Vertex AI** or an **enterprise gateway**? Swap the endpoint:
60
+ Using the **Gemini API** with a key, or an **enterprise gateway**? Swap the endpoint:
49
61
 
50
62
  ```ts
51
- import { vertexAi } from "llm-large-files/gemini";
52
- const endpoint = vertexAi({ project: "my-project", model: "gemini-3.8-flash", accessToken: getToken });
53
- // or your own proxy:
54
- const endpoint = { url: "https://llm-gw.corp/v1/gemini:generateContent", headers: { Authorization: `Bearer ${key}` } };
63
+ import { geminiApi, type GeminiEndpoint } from "llm-large-files/gemini";
64
+
65
+ const withKey = geminiApi({ apiKey: process.env.GEMINI_API_KEY!, model: "gemini-3.8-flash" });
66
+
67
+ // Your own proxy of Generate Content. Its headers are sent exactly as given.
68
+ const viaGateway: GeminiEndpoint = {
69
+ url: "https://llm-gateway.example.com/v1/gemini:generateContent",
70
+ streamUrl: "https://llm-gateway.example.com/v1/gemini:streamGenerateContent?alt=sse", // without it, no streaming
71
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.GATEWAY_KEY}` },
72
+ };
55
73
  ```
56
74
 
57
75
  ## Any model
@@ -68,28 +86,42 @@ const deepseek = openAiCompatible({ baseUrl: "https://api.deepseek.com/v1", apiK
68
86
  // Claude. `fallbacks` lets another model answer when a safety classifier declines the request.
69
87
  const claude = anthropic({ apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-opus-5-5", fallbacks: "default" });
70
88
 
71
- const result = await askWithFiles({
72
- files,
89
+ const withClaude = await askWithFiles({
90
+ files, // `files` and `doc` are those of the quickstart
73
91
  model: claude, // writes the answer
74
92
  explorer: deepseek, // optional: a second model, of any provider, that searches and reads
75
93
  documentIds: [doc.id],
76
94
  messages: [{ role: "user", text: "What caused the outage, and when? Cite lines." }],
77
95
  onText: (delta) => process.stdout.write(delta),
78
96
  });
97
+
98
+ withClaude.answered; // false when the last reply had no text (a blocked prompt, a reply cut off before any text, a tool call that could not be read): show your own message
99
+ withClaude.usage; // { requests: 5, inputTokens: 32662, cachedInputTokens: 6086, outputTokens: 750, thoughtTokens: 0, byModel: { … } }
100
+ withClaude.evidence; // [{ tool: "read_document", documentId, document: "app.log", lines: [[34100, 34110]] }, …]
101
+ withClaude.toolTurns; // pass these back in `messages`, between this question and its answer: a follow-up then needs no new search
79
102
  ```
80
103
 
81
- Every model gets the same loop: a request that failed is sent again, the request is kept inside
82
- the model's window, and one question cannot read a file whole twice. The result says what it cost
83
- and what it read:
104
+ How to keep a chat's history, tool turns included, across requests and servers:
105
+ [Conversations](docs/guides/conversations.md).
84
106
 
85
- ```ts
86
- result.usage; // { requests: 5, inputTokens: 32662, cachedInputTokens: 6086, outputTokens: 750, byModel: { … } }
87
- result.evidence; // [{ tool: "read_document", documentId, document: "prod.log", lines: [[34100, 34110]] }, …]
88
- result.toolTurns; // keep these with the conversation: a follow-up question then needs no new search
89
- ```
107
+ Every model gets the same loop. A failed request is sent again when another try can help (a lost
108
+ connection, HTTP 408, 409, 429 or 5xx), never for a quota that ran out or once text was shown. With
109
+ the built-in adapters, a model silent for 10 minutes before its reply (`firstByteTimeoutMs`) or 5
110
+ minutes inside it (`idleTimeoutMs`) is cut off and asked once more. A request the provider refuses
111
+ as too large is made smaller, or the files are planned again for a window a little smaller than the
112
+ one it names. An empty first reply, an unreadable tool call, or an answer that comes back without
113
+ text is asked for again, a repeated call gets a pointer to the result already shown, and by default
114
+ each file is read whole at most once a question.
90
115
 
91
- A model that has no adapter needs one object with a `send` method:
92
- [your own adapter](docs/api.md#your-own-adapter).
116
+ A question that fails throws `DocumentsNotFoundError` for a file that expired, was deleted, or
117
+ belongs to another `owner`, `DocumentStoreError` when the store cannot be read, or a
118
+ `ModelRequestError` whose `kind` (`"rate_limit"`, `"quota"`, `"timeout"`, `"context_overflow"`, …)
119
+ tells you what to show the user. `partialResultOf(error)` gives what it found and paid for:
120
+ [Errors and reliability](docs/guides/errors-and-reliability.md).
121
+
122
+ A model that has no adapter needs one object with an `id`, its `capabilities` (at least `toolFiles`
123
+ and `pageTokens`) and a `send` method, plus `generateText` to read whole files in parts:
124
+ [your own adapter](docs/guides/own-adapter-and-loop.md).
93
125
 
94
126
  ## Add it to a web app
95
127
 
@@ -97,23 +129,75 @@ A model that has no adapter needs one object with a `send` method:
97
129
  import express from "express";
98
130
  import { createDocumentHandlers } from "llm-large-files/node";
99
131
 
100
- const documents = createDocumentHandlers(files, { getOwner: (req) => req.user?.id });
101
- app.post("/api/documents", documents.upload); // mount before express.json()
132
+ const app = express();
133
+ // `files` is the quickstart's. getOwner names the signed-in user (here, set on req.user by your
134
+ // auth middleware): each upload is then theirs alone.
135
+ const documents = createDocumentHandlers(files, {
136
+ getOwner: (req) => (req as typeof req & { user?: { id: string } }).user?.id,
137
+ });
138
+ app.post("/api/documents", documents.upload); // mount before express.json(): the body is the raw file
139
+ app.get("/api/documents/:id", (req, res) => documents.get(req, res, req.params.id));
102
140
  app.delete("/api/documents/:id", (req, res) => documents.remove(req, res, req.params.id));
103
141
  ```
104
142
 
105
- The browser uploads the raw file:
143
+ The browser uploads the raw file (`file` comes from an `<input type="file">`):
106
144
 
107
145
  ```ts
108
- await fetch("/api/documents", {
146
+ const response = await fetch("/api/documents", {
109
147
  method: "POST",
110
148
  headers: { "Content-Type": "application/octet-stream", "X-File-Name": encodeURIComponent(file.name) },
111
149
  body: file,
112
- }); // → { id, name, format, lines, estimatedTokens, expiresAt, ... }
150
+ });
151
+ const summary = await response.json(); // 201: { id, name, format, lines, estimatedTokens, expiresAt, … }; otherwise { error }
113
152
  ```
114
153
 
115
- The full walkthrough, with streaming to the browser, is in the [integration guide](docs/getting-started.md).
116
- There's also a [one-file demo server](examples/server.ts).
154
+ When the user asks, stream the question to the page with `askStream` (new in 0.7.0): typed events
155
+ in order, from `run.start` through each tool call, its progress and the text as it is written, to
156
+ `run.finish` or `run.error`. Errors in events are told in words for users, and no text of the
157
+ documents is in them:
158
+
159
+ ```ts
160
+ import { askStream } from "llm-large-files";
161
+ import { writeSseEvents } from "llm-large-files/node";
162
+
163
+ app.post("/api/chat", express.json(), async (req, res) => {
164
+ const stream = askStream({
165
+ files, model: claude, // `claude` is the adapter of "Any model"
166
+ owner: (req as typeof req & { user?: { id: string } }).user?.id,
167
+ documentIds: [String(req.body.documentId)],
168
+ messages: [{ role: "user", text: String(req.body.question) }],
169
+ });
170
+ await writeSseEvents(res, stream); // one SSE message per event; stops the question if the page leaves
171
+ });
172
+ ```
173
+
174
+ Pass the upload's `id` in `documentIds` and the same user as `owner`: a document
175
+ that has an owner is missing for anyone else. This `getOwner` returns `undefined` for an anonymous
176
+ upload. Never return an empty string: it would be one owner shared by every caller without a user,
177
+ and the upload is answered 500. Reading the events in the browser, the upload's own progress, and
178
+ cancelling are in the [web app guide](docs/guides/web-app.md); every event is in
179
+ [Events](docs/reference/events.md). There's also a
180
+ [one-file demo server](https://github.com/renanbazinin/llm-large-files/blob/main/examples/server.ts) and a [command-line script](https://github.com/renanbazinin/llm-large-files/blob/main/examples/ask-cli.ts): from a
181
+ clone of this repository, run `npm install` and `npm run build`, then run them with Node 22.18 or a
182
+ later 22.x, or Node 23.6 or later.
183
+
184
+ **Uploads you do not trust.** These handlers read each upload in your server's process. Ingest
185
+ limits the text, the pages and the time of one file, refuses the zip bombs and the PDFs built to
186
+ hold a server that its checks recognize, and pauses for other requests between pages and slices of
187
+ its work. It does not refuse every file built to hurt a server. While a file is read, it takes
188
+ memory from your server's heap. Some steps run in one block, and no other request is answered
189
+ meanwhile. pdf.js reads one page of a PDF in one block: up to about 1.5 s for a page of a small
190
+ file that passes the page check, longer in a large file. `@cantoo/pdf-lib` reads one object of a
191
+ PDF in one block, about 0.1 to 0.35 s for each MB of it. Neither it nor pdf.js checks the memory
192
+ an object takes before building it: a crafted PDF of 732 bytes, whose object stream unpacks to
193
+ 4 MB of empty dictionaries, ran a heap of 512 MB out of memory at ingest. What a stream unpacks to
194
+ is outside the heap: one of 1.6 KB took 1.6 GB of memory with 20 MB of heap. If your users can
195
+ upload files you do not trust, read them in child processes with a heap limit and a kill timer:
196
+ pass `createIsolatedExtractors().extractors`, from `llm-large-files/node`, to `createLargeFiles`
197
+ ([isolated ingest](docs/reference/node.md#createisolatedextractorsoptions)). Give the server a
198
+ memory limit too, as [Deployment](docs/guides/deployment.md#uploads-and-ingest) shows, and do not
199
+ offer `view_pages` on their documents. What is refused, and what still holds the server:
200
+ [Security](docs/security.md#uploads).
117
201
 
118
202
  ## Pictures, charts and scans in PDFs
119
203
 
@@ -121,21 +205,28 @@ A large PDF goes to the model as text, and text cannot show a chart. Keep the up
121
205
  the model gets a tool, `view_pages`, that hands it the pages it asks for as a small PDF:
122
206
 
123
207
  ```bash
124
- npm install @cantoo/pdf-lib
208
+ npm install unpdf @cantoo/pdf-lib # Node 24; for Node 20 and 22, see Requirements
125
209
  ```
126
210
 
127
211
  ```ts
212
+ // In place of the quickstart's files:
128
213
  const files = createLargeFiles({
129
214
  store: new FileDocumentStore("./data/large-files"),
130
- keepOriginals: ["pdf"], // off by default: a kept file takes disk space until it expires
215
+ keepOriginals: ["pdf"], // off by default: a kept file takes disk space until it expires and is swept
131
216
  });
217
+ setInterval(() => files.sweep().catch(console.error), 60 * 60 * 1000).unref(); // removes expired documents and their files
132
218
  // askGemini needs no change. A step then reads: Look at report.pdf pages 12-14
133
219
  ```
134
220
 
221
+ `unpdf` reads the text of a PDF, and `@cantoo/pdf-lib` cuts its pages. With `askWithFiles`,
222
+ `view_pages` is offered only when every model of the question can be sent a file: `gemini()` and
223
+ `anthropic()` can by default, `openAiCompatible()` only with `pdfInput: true`. So the question
224
+ above, with DeepSeek exploring, is not offered `view_pages` at all.
225
+
135
226
  Asked which bar of a chart is tallest, `gemini-3.5-flash-lite` said from the text that it could
136
227
  not see the chart; with `view_pages` it looked at the page and answered correctly. It did not look
137
- at a page for any of ten questions that the text answers. A page costs about 530 tokens.
138
- Details, limits and measurements: [Pictures in PDFs](docs/configuration.md#pictures-in-pdfs).
228
+ at a page for any of ten questions that the text answers. On Gemini a page costs about 530 tokens;
229
+ `anthropic()` counts 3,500 for Claude by default. Scans, tables, limits: [PDFs](docs/guides/pdfs.md).
139
230
 
140
231
  ## One model to explore, another to answer
141
232
 
@@ -144,10 +235,12 @@ default. That model does both halves of the work on a large file. It explores th
144
235
  reads, looks at pages), and then it answers. You can name a second model for the first half:
145
236
 
146
237
  ```ts
147
- const endpoint = geminiApi({
148
- apiKey: process.env.GEMINI_API_KEY!,
238
+ // In place of the quickstart's endpoint:
239
+ const endpoint = vertexAi({
240
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
149
241
  model: "gemini-3.8-flash", // writes the answer
150
242
  explorerModel: process.env.GEMINI_EXPLORER_MODEL, // optional: searches and reads
243
+ accessToken: async () => (await auth.getAccessToken())!, // `auth` is the quickstart's
151
244
  });
152
245
  ```
153
246
 
@@ -155,50 +248,87 @@ Left out or empty, nothing changes: one model does both. With an explorer, the m
155
248
  search through a large file go to that model, which can be a cheaper or faster one, and `model`
156
249
  gets what the tools returned and writes the answer in one request. In eleven live checks with
157
250
  `gemini-3.5-flash-lite` exploring, the other model answered every one correctly from what it found.
158
- What each model gets, and what it costs: [An explorer model](docs/configuration.md#an-explorer-model).
251
+ What each model gets, and what it costs: [An explorer model](docs/guides/explorer-model.md).
159
252
 
160
253
  ## What it handles
161
254
 
162
255
  | | |
163
256
  |---|---|
164
- | **Formats** | Text, Markdown, logs (UTF-8 and UTF-16), JSON/JSONL, CSV/TSV, DOCX, PPTX, PDF (text layer, with tables rebuilt so empty cells stay empty; pages with a picture are marked, and the model can look at the pages themselves; scans of up to 30 pages) |
257
+ | **Formats** | Text, Markdown, logs (UTF-8 and UTF-16, and Hebrew, Arabic, Cyrillic, Japanese and Western European text in its older encoding), JSON/JSONL, CSV/TSV, HTML (the text a browser shows), DOCX (headings, clause numbers, tables, notes and comments), PPTX (slides in show order, tables, speaker notes), XLSX (every sheet, a line per row, with its row number), PDF (text layer, with tables rebuilt so empty cells stay empty; pages with a picture are marked, and the model can look at the pages themselves; scans of up to 30 pages when PDFs are kept) |
165
258
  | **Logs** | Detected automatically; the card shows level counts, the time range, and the most frequent errors grouped by shape (`timeout after <n>ms to <ip>`) |
166
259
  | **Books and documents** | An outline of headings with line numbers, including Markdown, "Chapter 12", numbered sections, and Hebrew chapter titles |
167
- | **Limits** | One budget covers tokens *and* request bytes, so files fit both your context window and your connector's payload limit. It follows the model: set `contextTokens`, or let the adapter say it |
260
+ | **Limits** | One budget covers tokens *and* request bytes, so files fit both your context window and your connector's payload limit. It assumes 1M tokens and 10 MB: set `budget.contextTokens` for your model's window (an adapter's `contextTokens` can only make it smaller) |
261
+ | **Reliability** | Retries, waits on a silent model, recovery from a request too large, error kinds: see [Errors and reliability](docs/guides/errors-and-reliability.md) |
168
262
  | **Models** | Gemini and Vertex AI, any OpenAI-compatible endpoint, Claude, or an adapter of your own. Two models of different providers can share a question |
169
- | **Cost** | Usage summed over every request of a question, for each model, with ceilings on whole-file reads, requests and tokens |
263
+ | **Cost** | Usage summed over every request of a question, for each model, with ceilings on whole-file reads, requests and input tokens |
170
264
  | **Privacy** | Documents can belong to an `owner`; other users can't plan, read, or delete them |
265
+ | **Hostile uploads** | Limits on the text, pages and time of one file; zip bombs and PDFs built to exhaust a server are refused when the checks recognize them, with a code (`"hostile"`); ingest pauses for other requests between pages and slices. Not every hostile file is refused, and some steps hold the server for a while: read untrusted uploads in child processes with `createIsolatedExtractors`, which refuses a file that runs out of memory or time while the server goes on ([Security](docs/security.md#uploads)) |
171
266
  | **Storage** | In memory, on disk with expiry, or your own store (Redis, S3, a database) |
172
267
 
173
268
  ## Live results
174
269
 
175
- With `gemini-3.8-flash` on the Gemini API:
176
-
177
- | File | Question | Result |
178
- |---|---|---|
179
- | 5 MB log, about 1.27M tokens (over the 1M limit) | "What caused the outage?" | Correct root cause, citing the right lines, in about 60 s over 11 tool calls |
180
- | 467 KB novel, about 117K tokens | "Where was the ledger hidden?" | Sent whole; correct. Estimated 116,840 tokens; Gemini billed 116,842 |
181
- | Same novel, map-reduce | "Read all of it…" | 4 parts read in parallel; correct, cited answer in 32 s |
182
- | PDF with a chart and photos (`gemini-3.5-flash-lite`) | "Which bar is tallest, and what number is on the sign?" | Looked at 2 pages unasked; all five facts right, in 3 s. From the text alone: "cannot see the chart" |
270
+ With `gemini-3.8-flash` on the Gemini API, a 5 MB log of about 1.27M tokens, over the 1M window,
271
+ got the right root cause of an outage, citing the right lines, in about 60 s over 11 tool calls.
272
+ Every live result with its date, model and setup, and what has not been run live, such as the
273
+ Claude adapter: [Measurements](docs/measurements.md).
183
274
 
184
275
  ## Documentation
185
276
 
186
- - [Integration guide](docs/getting-started.md): Express, plain Node, browser upload, streaming, Vertex AI, gateways, other models, existing chat history
187
- - [API reference](docs/api.md): `askWithFiles`, the three adapters, and what an adapter of your own must do
188
- - [Configuration](docs/configuration.md): budget, limits and retries, an explorer model, stores, formats, extractors, pictures in PDFs
189
- - [How it works](docs/how-it-works.md): planner, cards, tools, map-reduce, looking at pages, the loop, and the provider quirks it handles
190
- - [Security](docs/security.md): owners, tool scoping, retention, original files, regex safety, what a question can cost
277
+ - [Documentation index](docs/README.md): where to start, which entry point to use, a glossary, and every page in one line.
278
+ - [Getting started](docs/getting-started.md): install, a quickstart that runs, and the integration in short steps.
279
+
280
+ Guides, one task each:
281
+
282
+ - [Gemini and Vertex AI](docs/guides/vertex-and-gemini.md): endpoints, access tokens, thinking, whole-file reads, pages, gateways, Vertex quotas and errors.
283
+ - [OpenAI-compatible endpoints](docs/guides/openai-compatible.md): OpenAI, Azure OpenAI, DeepSeek, OpenRouter, vLLM, Ollama, LiteLLM, llama.cpp.
284
+ - [Claude](docs/guides/anthropic.md): setup, thinking, streaming, conversations that may only grow, gateways.
285
+ - [An explorer model](docs/guides/explorer-model.md): a cheaper model that explores the files while another answers.
286
+ - [Web app](docs/guides/web-app.md): uploads, answers and progress streamed over Server-Sent Events, cancelling.
287
+ - [Conversations](docs/guides/conversations.md): the history you keep, tool turns included, across requests and servers.
288
+ - [Storage](docs/guides/storage.md): the store contract, owners, a layout per user and per chat session, retention.
289
+ - [Deployment](docs/guides/deployment.md): several servers, memory, sweeps, proxies and timeouts for streams, upgrades.
290
+ - [Errors and reliability](docs/guides/errors-and-reliability.md): every error and what to show the user, retries, waits, deadlines.
291
+ - [Costs and limits](docs/guides/costs-and-limits.md): the limits of a question, the budget per model, usage per user or session.
292
+ - [PDFs](docs/guides/pdfs.md): formats and optional packages, tables, pictures, `view_pages`, scans, extractors and OCR.
293
+ - [Your own adapter or loop](docs/guides/own-adapter-and-loop.md): a model without an adapter, or a tool loop of your own.
294
+ - [Testing](docs/guides/testing.md): testing your integration without a real model.
295
+
296
+ Reference, one page per module:
297
+
298
+ - [`llm-large-files`: the library and its documents](docs/reference/library.md): `createLargeFiles`, stores, budget, extractors.
299
+ - [`llm-large-files`: the tool loop](docs/reference/ask.md): `askWithFiles`, its options and result, the adapter contract.
300
+ - [`llm-large-files`: errors, retries, streams](docs/reference/errors-and-retries.md): `ModelRequestError` and its kinds, `withRetry`, `parseSseJson`.
301
+ - [`llm-large-files`: the tools](docs/reference/tools.md): every tool the model sees, its arguments, results and limits.
302
+ - [`llm-large-files`: events](docs/reference/events.md): `askStream`, the events of a question and of an ingest, `eventStream`.
303
+ - [`llm-large-files/gemini`](docs/reference/gemini.md): `askGemini`, `gemini()`, `geminiApi()`, `vertexAi()`.
304
+ - [`llm-large-files/openai`](docs/reference/openai.md): `openAiCompatible()` and its options.
305
+ - [`llm-large-files/anthropic`](docs/reference/anthropic.md): `anthropic()` and its options.
306
+ - [`llm-large-files/node`](docs/reference/node.md): `createDocumentHandlers`, its routes and responses, `createIsolatedExtractors`.
307
+
308
+ [Changelog](CHANGELOG.md): what each version changed, and what to change in your code when you upgrade.
309
+
310
+ Also: [How it works](docs/how-it-works.md), [Security](docs/security.md),
311
+ [Troubleshooting](docs/troubleshooting.md) and [Measurements](docs/measurements.md). For
312
+ maintainers: [Contributing](https://github.com/renanbazinin/llm-large-files/blob/main/CONTRIBUTING.md) and [Publishing](docs/publishing.md).
191
313
 
192
314
  ## Requirements
193
315
 
194
- Node.js 20.19 or newer. The package is ESM; CommonJS projects can `require()` it on Node 20.19+ and 22.12+.
195
- For DOCX/PPTX install `jszip`, for PDF install `unpdf`, and to mark and show the pages of a PDF
196
- install `@cantoo/pdf-lib`. All three are optional:
316
+ Node.js 20.19 or newer. The package is ESM; CommonJS code can `require()` it on Node 20.19+ and
317
+ 22.12+. For DOCX, PPTX and XLSX install `jszip`, for PDF install `unpdf`, and to mark and show the
318
+ pages of a PDF, and refuse a page built to hold the server before it is read, install
319
+ `@cantoo/pdf-lib`. All three are optional:
197
320
 
198
321
  ```bash
199
- npm install jszip unpdf @cantoo/pdf-lib
322
+ npm install jszip unpdf @cantoo/pdf-lib # Node 24 and later
323
+ npm install jszip unpdf@1 @cantoo/pdf-lib # Node 22
324
+ npm install jszip unpdf@1.7.0 @cantoo/pdf-lib # Node 20
200
325
  ```
201
326
 
327
+ On Node 24 and later, `npm install unpdf` installs unpdf 2, which asks for Node 24. On Node 20,
328
+ unpdf 1.9 and later cannot load pdf.js, and on Node 20 and 22 the pdf.js of unpdf 1.5.0 to 1.6.0
329
+ would stop the whole process. Such an unpdf is refused at the first PDF, with a message that says
330
+ what to install.
331
+
202
332
  ## License
203
333
 
204
334
  [MIT](LICENSE)
package/dist/analyze.d.ts CHANGED
@@ -1,9 +1,16 @@
1
+ import type { TimeSlicer } from "./pause.js";
1
2
  import type { DocumentFormat, LogProfile, OutlineEntry } from "./types.js";
2
- /** Treats text as a log when most early lines start with a timestamp or a level. */
3
+ /** The level of a log line, in upper case ("ERROR", "WARN"), or undefined. */
4
+ export declare function levelOf(line: string): string | undefined;
5
+ /** Treats text as a log when most early lines start with a timestamp or a level, or have the shape of a log line. */
3
6
  export declare function looksLikeLog(lines: string[]): boolean;
4
7
  /** Headings with line numbers: Markdown, slide/page markers, and common book and report patterns. */
5
8
  export declare function buildOutline(lines: string[], format: DocumentFormat): OutlineEntry[];
9
+ /** `buildOutline`, the same result, with pauses for other requests while a large file is read. */
10
+ export declare function buildOutlineInSlices(lines: string[], format: DocumentFormat, slicer: TimeSlicer): Promise<OutlineEntry[]>;
6
11
  /** Replaces the variable parts of a log message so repeated failures group together. */
7
12
  export declare function logTemplate(line: string): string;
8
13
  export declare function buildLogProfile(lines: string[]): LogProfile;
14
+ /** `buildLogProfile`, the same result, with pauses for other requests while a large log is read. */
15
+ export declare function buildLogProfileInSlices(lines: string[], slicer: TimeSlicer): Promise<LogProfile>;
9
16
  //# sourceMappingURL=analyze.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"analyze.d.ts","sourceRoot":"","sources":["../src/analyze.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAY,UAAU,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AASrF,oFAAoF;AACpF,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAKrD;AAED,qGAAqG;AACrG,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,cAAc,GAAG,YAAY,EAAE,CA6BpF;AAED,wFAAwF;AACxF,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAYhD;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,UAAU,CAgC3D"}
1
+ {"version":3,"file":"analyze.d.ts","sourceRoot":"","sources":["../src/analyze.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C,OAAO,KAAK,EAAE,cAAc,EAAY,UAAU,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AA4BrF,8EAA8E;AAC9E,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAMxD;AAED,qHAAqH;AACrH,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CASrD;AA2BD,qGAAqG;AACrG,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,cAAc,GAAG,YAAY,EAAE,CAWpF;AAED,kGAAkG;AAClG,wBAAsB,oBAAoB,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC,CAY/H;AAiFD,wFAAwF;AACxF,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAYhD;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,UAAU,CAI3D;AAED,oGAAoG;AACpG,wBAAsB,uBAAuB,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAOtG"}