llm-large-files 0.4.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/CHANGELOG.md +1400 -338
  2. package/README.md +217 -49
  3. package/dist/analyze.d.ts +5 -0
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +96 -47
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +117 -0
  8. package/dist/anthropic/adapter.d.ts.map +1 -0
  9. package/dist/anthropic/adapter.js +542 -0
  10. package/dist/anthropic/adapter.js.map +1 -0
  11. package/dist/anthropic/index.d.ts +3 -0
  12. package/dist/anthropic/index.d.ts.map +1 -0
  13. package/dist/anthropic/index.js +2 -0
  14. package/dist/anthropic/index.js.map +1 -0
  15. package/dist/ask.d.ts +200 -0
  16. package/dist/ask.d.ts.map +1 -0
  17. package/dist/ask.js +1402 -0
  18. package/dist/ask.js.map +1 -0
  19. package/dist/budget.d.ts +23 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +64 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/encoding.d.ts +17 -0
  24. package/dist/encoding.d.ts.map +1 -0
  25. package/dist/encoding.js +852 -0
  26. package/dist/encoding.js.map +1 -0
  27. package/dist/errors.d.ts +4 -0
  28. package/dist/errors.d.ts.map +1 -1
  29. package/dist/errors.js +15 -0
  30. package/dist/errors.js.map +1 -1
  31. package/dist/events.d.ts +333 -0
  32. package/dist/events.d.ts.map +1 -0
  33. package/dist/events.js +159 -0
  34. package/dist/events.js.map +1 -0
  35. package/dist/evidence.d.ts +42 -0
  36. package/dist/evidence.d.ts.map +1 -0
  37. package/dist/evidence.js +138 -0
  38. package/dist/evidence.js.map +1 -0
  39. package/dist/extract.d.ts +35 -3
  40. package/dist/extract.d.ts.map +1 -1
  41. package/dist/extract.js +626 -58
  42. package/dist/extract.js.map +1 -1
  43. package/dist/gemini/adapter.d.ts +59 -0
  44. package/dist/gemini/adapter.d.ts.map +1 -0
  45. package/dist/gemini/adapter.js +226 -0
  46. package/dist/gemini/adapter.js.map +1 -0
  47. package/dist/gemini/chat.d.ts +53 -77
  48. package/dist/gemini/chat.d.ts.map +1 -1
  49. package/dist/gemini/chat.js +42 -300
  50. package/dist/gemini/chat.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +16 -0
  52. package/dist/gemini/errors.d.ts.map +1 -0
  53. package/dist/gemini/errors.js +46 -0
  54. package/dist/gemini/errors.js.map +1 -0
  55. package/dist/gemini/generate.d.ts +18 -21
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +49 -92
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +6 -4
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +4 -3
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -2
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -38
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/http.d.ts +136 -0
  68. package/dist/http.d.ts.map +1 -0
  69. package/dist/http.js +401 -0
  70. package/dist/http.js.map +1 -0
  71. package/dist/index.d.ts +18 -2
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +13 -4
  74. package/dist/index.js.map +1 -1
  75. package/dist/library.d.ts +96 -8
  76. package/dist/library.d.ts.map +1 -1
  77. package/dist/library.js +414 -96
  78. package/dist/library.js.map +1 -1
  79. package/dist/map-reduce.d.ts +37 -1
  80. package/dist/map-reduce.d.ts.map +1 -1
  81. package/dist/map-reduce.js +255 -61
  82. package/dist/map-reduce.js.map +1 -1
  83. package/dist/model.d.ts +278 -0
  84. package/dist/model.d.ts.map +1 -0
  85. package/dist/model.js +222 -0
  86. package/dist/model.js.map +1 -0
  87. package/dist/node/handlers.d.ts +20 -4
  88. package/dist/node/handlers.d.ts.map +1 -1
  89. package/dist/node/handlers.js +122 -20
  90. package/dist/node/handlers.js.map +1 -1
  91. package/dist/node/index.d.ts +2 -0
  92. package/dist/node/index.d.ts.map +1 -1
  93. package/dist/node/index.js +1 -0
  94. package/dist/node/index.js.map +1 -1
  95. package/dist/node/sse.d.ts +59 -0
  96. package/dist/node/sse.d.ts.map +1 -0
  97. package/dist/node/sse.js +174 -0
  98. package/dist/node/sse.js.map +1 -0
  99. package/dist/openai/adapter.d.ts +109 -0
  100. package/dist/openai/adapter.d.ts.map +1 -0
  101. package/dist/openai/adapter.js +567 -0
  102. package/dist/openai/adapter.js.map +1 -0
  103. package/dist/openai/index.d.ts +3 -0
  104. package/dist/openai/index.d.ts.map +1 -0
  105. package/dist/openai/index.js +2 -0
  106. package/dist/openai/index.js.map +1 -0
  107. package/dist/output-limit.d.ts +42 -0
  108. package/dist/output-limit.d.ts.map +1 -0
  109. package/dist/output-limit.js +121 -0
  110. package/dist/output-limit.js.map +1 -0
  111. package/dist/pause.d.ts +24 -0
  112. package/dist/pause.d.ts.map +1 -0
  113. package/dist/pause.js +38 -0
  114. package/dist/pause.js.map +1 -0
  115. package/dist/pdf-pages.d.ts +32 -2
  116. package/dist/pdf-pages.d.ts.map +1 -1
  117. package/dist/pdf-pages.js +275 -14
  118. package/dist/pdf-pages.js.map +1 -1
  119. package/dist/pdf-pictures.d.ts +30 -3
  120. package/dist/pdf-pictures.d.ts.map +1 -1
  121. package/dist/pdf-pictures.js +50 -8
  122. package/dist/pdf-pictures.js.map +1 -1
  123. package/dist/pdf-work.d.ts +40 -0
  124. package/dist/pdf-work.d.ts.map +1 -0
  125. package/dist/pdf-work.js +734 -0
  126. package/dist/pdf-work.js.map +1 -0
  127. package/dist/plan.d.ts +22 -4
  128. package/dist/plan.d.ts.map +1 -1
  129. package/dist/plan.js +61 -12
  130. package/dist/plan.js.map +1 -1
  131. package/dist/retry.d.ts +76 -0
  132. package/dist/retry.d.ts.map +1 -0
  133. package/dist/retry.js +141 -0
  134. package/dist/retry.js.map +1 -0
  135. package/dist/search.d.ts +8 -2
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +60 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/sse.d.ts +36 -0
  140. package/dist/sse.d.ts.map +1 -0
  141. package/dist/sse.js +153 -0
  142. package/dist/sse.js.map +1 -0
  143. package/dist/stores.d.ts.map +1 -1
  144. package/dist/stores.js +5 -2
  145. package/dist/stores.js.map +1 -1
  146. package/dist/text-index.d.ts +6 -0
  147. package/dist/text-index.d.ts.map +1 -1
  148. package/dist/text-index.js +25 -8
  149. package/dist/text-index.js.map +1 -1
  150. package/dist/text.d.ts +62 -2
  151. package/dist/text.d.ts.map +1 -1
  152. package/dist/text.js +314 -14
  153. package/dist/text.js.map +1 -1
  154. package/dist/tools.d.ts +72 -1
  155. package/dist/tools.d.ts.map +1 -1
  156. package/dist/tools.js +341 -60
  157. package/dist/tools.js.map +1 -1
  158. package/dist/types.d.ts +128 -4
  159. package/dist/types.d.ts.map +1 -1
  160. package/dist/zip-directory.d.ts +43 -0
  161. package/dist/zip-directory.d.ts.map +1 -0
  162. package/dist/zip-directory.js +130 -0
  163. package/dist/zip-directory.js.map +1 -0
  164. package/docs/README.md +288 -0
  165. package/docs/api.md +58 -184
  166. package/docs/configuration.md +34 -490
  167. package/docs/getting-started.md +412 -177
  168. package/docs/guides/anthropic.md +590 -0
  169. package/docs/guides/conversations.md +629 -0
  170. package/docs/guides/costs-and-limits.md +726 -0
  171. package/docs/guides/deployment.md +654 -0
  172. package/docs/guides/errors-and-reliability.md +735 -0
  173. package/docs/guides/explorer-model.md +399 -0
  174. package/docs/guides/openai-compatible.md +602 -0
  175. package/docs/guides/own-adapter-and-loop.md +1169 -0
  176. package/docs/guides/pdfs.md +971 -0
  177. package/docs/guides/storage.md +731 -0
  178. package/docs/guides/testing.md +1199 -0
  179. package/docs/guides/vertex-and-gemini.md +717 -0
  180. package/docs/guides/web-app.md +1589 -0
  181. package/docs/how-it-works.md +1022 -138
  182. package/docs/measurements.md +881 -0
  183. package/docs/publishing.md +274 -46
  184. package/docs/reference/anthropic.md +427 -0
  185. package/docs/reference/ask.md +892 -0
  186. package/docs/reference/errors-and-retries.md +758 -0
  187. package/docs/reference/events.md +993 -0
  188. package/docs/reference/gemini.md +823 -0
  189. package/docs/reference/library.md +1467 -0
  190. package/docs/reference/node.md +528 -0
  191. package/docs/reference/openai.md +385 -0
  192. package/docs/reference/tools.md +883 -0
  193. package/docs/security.md +902 -90
  194. package/docs/troubleshooting.md +1390 -0
  195. package/package.json +22 -4
  196. package/src/analyze.ts +93 -42
  197. package/src/anthropic/adapter.ts +611 -0
  198. package/src/anthropic/index.ts +2 -0
  199. package/src/ask.ts +1560 -0
  200. package/src/budget.ts +71 -0
  201. package/src/encoding.ts +850 -0
  202. package/src/errors.ts +17 -0
  203. package/src/events.ts +442 -0
  204. package/src/evidence.ts +165 -0
  205. package/src/extract.ts +602 -62
  206. package/src/gemini/adapter.ts +271 -0
  207. package/src/gemini/chat.ts +87 -355
  208. package/src/gemini/errors.ts +48 -0
  209. package/src/gemini/generate.ts +67 -94
  210. package/src/gemini/index.ts +6 -4
  211. package/src/gemini/sse.ts +1 -34
  212. package/src/http.ts +434 -0
  213. package/src/index.ts +55 -4
  214. package/src/library.ts +497 -97
  215. package/src/map-reduce.ts +266 -59
  216. package/src/model.ts +433 -0
  217. package/src/node/handlers.ts +137 -22
  218. package/src/node/index.ts +2 -0
  219. package/src/node/sse.ts +198 -0
  220. package/src/openai/adapter.ts +613 -0
  221. package/src/openai/index.ts +2 -0
  222. package/src/output-limit.ts +135 -0
  223. package/src/pause.ts +41 -0
  224. package/src/pdf-pages.ts +268 -15
  225. package/src/pdf-pictures.ts +56 -9
  226. package/src/pdf-work.ts +722 -0
  227. package/src/plan.ts +68 -12
  228. package/src/retry.ts +176 -0
  229. package/src/search.ts +63 -10
  230. package/src/sse.ts +159 -0
  231. package/src/stores.ts +5 -2
  232. package/src/text-index.ts +26 -7
  233. package/src/text.ts +323 -13
  234. package/src/tools.ts +338 -62
  235. package/src/types.ts +129 -5
  236. package/src/zip-directory.ts +136 -0
package/docs/README.md ADDED
@@ -0,0 +1,288 @@
1
+ # llm-large-files documentation
2
+
3
+ `llm-large-files` lets a language model answer questions about files larger than its context window
4
+ or its request size limit: logs, books and other text, CSV, JSON, Word, PowerPoint and PDF files. A
5
+ file that fits goes into the prompt whole; a larger one becomes a short card, and the model
6
+ searches it, reads line ranges, reads all of it in parts or looks at the pages of a PDF, in one
7
+ tool loop that works with Gemini and Vertex AI, OpenAI-compatible endpoints, Claude or a model of
8
+ your own. This page is the map: where to start, which entry point to use, the words the other pages
9
+ use, and every page in one line.
10
+
11
+ ## Start here
12
+
13
+ ### A chatbot on Gemini or Vertex AI
14
+
15
+ For an application where users upload files into a chat, ask about them and watch the answer
16
+ stream in, with Gemini on Vertex AI or the Gemini API. Read in this order:
17
+
18
+ 1. [Getting started](./getting-started.md): install, a quickstart that runs, and the integration
19
+ in short steps.
20
+ 2. [Gemini API and Vertex AI](./guides/vertex-and-gemini.md): endpoints and access tokens,
21
+ `askGemini`, thinking, whole-file reads, pages, gateways, Vertex quotas and errors.
22
+ 3. [Web app](./guides/web-app.md): uploads, answers and progress streamed to the browser,
23
+ cancelling.
24
+ 4. [Conversations](./guides/conversations.md): the history you keep, tool turns included, across
25
+ requests and servers.
26
+ 5. [Storage](./guides/storage.md): where documents live, owners, a layout per user and per chat
27
+ session, retention.
28
+ 6. [Errors and reliability](./guides/errors-and-reliability.md): what each failure means and what
29
+ to show the user.
30
+ 7. [Costs and limits](./guides/costs-and-limits.md): what one question may spend, and its usage per
31
+ user or session.
32
+ 8. [An explorer model](./guides/explorer-model.md): a cheaper model that searches the files while
33
+ yours writes the answer.
34
+ 9. [Deployment](./guides/deployment.md): several servers, memory, sweeps, proxies, upgrades.
35
+
36
+ ### Another model
37
+
38
+ For OpenAI, Azure OpenAI, DeepSeek, a local server, Claude, or a model that has no adapter yet:
39
+
40
+ 1. [Getting started](./getting-started.md).
41
+ 2. [OpenAI-compatible endpoints](./guides/openai-compatible.md) or [Claude](./guides/anthropic.md):
42
+ the adapter and its settings for your provider.
43
+ 3. [Your own adapter and loop](./guides/own-adapter-and-loop.md): when your model has no adapter,
44
+ or you already run a tool loop of your own.
45
+
46
+ Then go on with steps 3 to 9 of the first path. Those guides are not tied to a provider.
47
+
48
+ ## Which entry point
49
+
50
+ There are three ways to ask a question. All three use the same `LargeFiles` object from
51
+ `createLargeFiles()`, so your documents, store and owners stay as they are when you move from one
52
+ to another.
53
+
54
+ | Entry point | Pick it when | What you do yourself |
55
+ |---|---|---|
56
+ | `askGemini`, from `llm-large-files/gemini` | Your model is Gemini, on the Gemini API or Vertex AI. One endpoint (`vertexAi()`, `geminiApi()`, or your gateway's URL and headers) says where the model is and can name an explorer model, and you may pass the history as Gemini `contents`. | Keep the history and show the answer; the loop does the rest. The explorer can only be another Gemini model, called with the same headers. |
57
+ | `askWithFiles` with an adapter, from `llm-large-files` | Any other model (`openAiCompatible()`, `anthropic()`, an adapter of your own), an explorer of another provider than the answering model, or an adapter you wrap for logging, quotas or a gateway. With `gemini()`, it also lets you declare the model's `contextTokens`, `maxRequestBytes` and `id` on the adapter. | The same as with `askGemini`. |
58
+ | Your own loop, with `files.prepare()` and `files.tools()` | You already run a tool loop, such as an agent framework, and want only the documents in it. `prepare()` gives the plan, the text or card of each document and the system instruction; `tools()` gives the tool declarations and runs the calls. | The loop: sending requests, retries, keeping the request inside the window, limits, usage, evidence and history. `withRetry`, `parseSseJson`, `evidenceOf`, `stubResult` and `UsageMeter` help with parts of it. |
59
+
60
+ `askGemini` is `askWithFiles` with a `gemini()` adapter for the endpoint, and a second one for its
61
+ explorer model when the endpoint names one. Both return the same `AskResult`. Here are the three
62
+ ways in; the third stops where your own loop takes over:
63
+
64
+ ```ts
65
+ import { askWithFiles, createLargeFiles, FileDocumentStore } from "llm-large-files";
66
+ import { askGemini, gemini, vertexAi } from "llm-large-files/gemini";
67
+
68
+ // Assumed: getAccessToken() returns an OAuth access token for Vertex AI (see the Vertex guide),
69
+ // and documentId is the `id` that files.ingest() returned for an upload.
70
+ const files = createLargeFiles({ store: new FileDocumentStore("./data/large-files") });
71
+ const endpoint = vertexAi({
72
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
73
+ location: "global",
74
+ model: "gemini-3.8-flash",
75
+ accessToken: getAccessToken,
76
+ });
77
+ const documentIds = [documentId];
78
+ const messages = [{ role: "user" as const, text: "What caused the outage, and when? Cite lines." }];
79
+
80
+ // 1. askGemini: the endpoint says where the model is.
81
+ const first = await askGemini({ files, endpoint, documentIds, messages });
82
+
83
+ // 2. askWithFiles: the same loop, with the model as an adapter you can swap or wrap.
84
+ const model = gemini(endpoint);
85
+ const second = await askWithFiles({ files, model, documentIds, messages });
86
+ console.log(first.text, second.steps, second.usage);
87
+
88
+ // 3. Your own loop: the plan, the cards and the tools, for a loop you already have.
89
+ // The second argument is the size of the rest of your request: system prompt and messages.
90
+ const context = await files.prepare(documentIds, { tokens: 1_000, bytes: 4_000 });
91
+ // By default, the instruction and the cards offer analyze_whole_document for a file that can be
92
+ // read whole. The tool exists only when you pass `generate` (here the Gemini adapter's own).
93
+ // Without it, pass { wholeDocumentAnalysis: false } as prepare's third argument, so that the
94
+ // instruction and the cards do not offer the tool.
95
+ const tools = files.tools(context.plan.searchable, { generate: model.generateText });
96
+ // Put context.instruction in your system prompt and context.blocks (a text for each document) in
97
+ // the user turn, offer tools.declarations to your model, and run each call with tools.execute().
98
+ ```
99
+
100
+ [Getting started](./getting-started.md) has a quickstart that runs. The third way is explained in
101
+ [your own adapter and loop](./guides/own-adapter-and-loop.md).
102
+
103
+ ## Glossary
104
+
105
+ Each term links to the page that explains it. The defaults and limits are on those pages.
106
+
107
+ - **Adapter**: a `ModelAdapter`, the object through which the loop talks to one model: an `id`,
108
+ its `capabilities` (at least `toolFiles` and `pageTokens`) and `send()`, plus `generateText()`
109
+ when it can do whole-file reads. Built in: `gemini()`, `openAiCompatible()` and `anthropic()`.
110
+ See [`ModelAdapter`](./reference/ask.md#modeladapter) and
111
+ [your own adapter and loop](./guides/own-adapter-and-loop.md).
112
+ - **Budget**: the sizes one request must fit (`Budget`): the model's context window
113
+ (`contextTokens`), the largest request body (`maxRequestBytes`), and the shares inside them:
114
+ document text sent whole, tokens kept free, the part size of a whole-file read, one tool result.
115
+ `askWithFiles` fits the budget to the window and body size each adapter declares, and the
116
+ built-in adapters declare a window only when you give them `contextTokens`. See
117
+ [`Budget`](./reference/library.md#budget) and [costs and limits](./guides/costs-and-limits.md).
118
+ - **Card**: what the model sees of a document that is not inline: its name and `document_id`, its
119
+ format and size, for a text file that was not valid UTF-8 the encoding it was read in or how
120
+ many of its characters were not valid, for a log its levels, time range and most frequent
121
+ problems, the start of its outline, and its first lines, numbered. It tells the model to use the
122
+ tools for the rest. See [how it works](./how-it-works.md).
123
+ - **Document**: a file after `files.ingest()`: its extracted text, which the tools read by line
124
+ number, and its metadata (`DocumentMeta`), kept in the store under an ID the library makes
125
+ (`doc_` and 32 hex characters). It expires after `ttlMs`. The uploaded file itself is kept only
126
+ for the formats in `keepOriginals`. See [storage](./guides/storage.md).
127
+ - **Evidence**: `AskResult.evidence`, one entry for each tool call that showed the model part of a
128
+ document: which document, and which lines or pages, as ranges (`Evidence`). A whole-file read is
129
+ marked `whole: true`. Keep it with the answer for citations or an audit trail. See
130
+ [`AskResult`](./reference/ask.md#askresult).
131
+ - **Events**: what a question or an ingest does as it runs, as typed data in order (`AskEvent`,
132
+ `IngestEvent`): each model request, tool call, piece of text and notice, numbered by `seq`, and
133
+ last `run.finish` or `run.error` (`ingest.finish` or `ingest.error`). Get them with `onEvent`,
134
+ or with `askStream` as an async iterable, and send them to a browser with `writeSseEvents`. New
135
+ in 0.7.0. See [events](./reference/events.md).
136
+ - **Explorer model**: an optional second model (`explorer` in `askWithFiles`, `explorerModel` in
137
+ `vertexAi()` and `geminiApi()`) that makes the tool calls and does the whole-file reads. The
138
+ answering model then gets what the tools returned, not what the explorer wrote, and writes the
139
+ answer in a request of its own. Without one, one model does both. See
140
+ [an explorer model](./guides/explorer-model.md).
141
+ - **Inline**: a document whose whole text goes into the prompt because it fits the budget, between
142
+ two frame lines that carry a mark made from its ID, which the file's own lines cannot copy. By
143
+ default (`documentPlacement: "first"`) it goes at the start of the first user turn, where a
144
+ provider's prompt cache can reuse it on follow-up questions. See [how it works](./how-it-works.md).
145
+ - **Limits**: `AskLimits`, how much work one question may do: chat requests (`toolTurns`), tool
146
+ calls in one turn (`callsPerTurn`), whole-file reads of each document (`wholeDocumentReads`),
147
+ and optional ceilings on input tokens (`inputTokens`) and requests (`requests`). The budget is
148
+ about size; the limits are about work, and so about cost. See
149
+ [`AskLimits`](./reference/ask.md#asklimits) and [costs and limits](./guides/costs-and-limits.md).
150
+ - **Owner**: a string you set at ingest, usually the ID of the user or tenant. It must not be
151
+ empty: `ingest` refuses `""`, a string of spaces and `null`. Every later call for the document
152
+ must pass the same string; with another one, the document is treated as missing and
153
+ `askWithFiles` throws `DocumentsNotFoundError`. A document without an owner can be used by anyone
154
+ who has its ID. The library only compares the strings: chat sessions, and which documents
155
+ belong to one, are your application's to keep. See [storage](./guides/storage.md) and
156
+ [security](./security.md).
157
+ - **Plan**: the split of a question's documents into inline and searchable (`DocumentPlan`, also in
158
+ `AskResult.plan`). The smallest documents go in whole first, while they fit the budget's room for
159
+ document text and the request size; the others get a card and the tools. `files.prepare()` makes
160
+ it for each question. See [`DocumentPlan`](./reference/library.md#documentplan) and
161
+ [how it works](./how-it-works.md).
162
+ - **Pointer**: a short result (`already_shown: true`) given in place of running a tool call again,
163
+ when an earlier result still in the conversation holds in full what the call would return. The
164
+ earlier result may be from this question or from an earlier one passed back as tool turns. It
165
+ saves room in the request. See [conversations](./guides/conversations.md).
166
+ - **Question**: one call of `askGemini` or `askWithFiles`: the user's latest message and every
167
+ model request made to answer it. Limits, usage and whole-file reads count per question. See
168
+ [`askWithFiles`](./reference/ask.md#askwithfilesoptions).
169
+ - **Stand-in**: a short result put in place of an older tool result when the request runs out of
170
+ room (`dropped: true`). It names the document and the lines or pages that were shown, so the
171
+ model can read them again. When a model of the question may only grow its conversation
172
+ (`appendOnly`, as Claude's), no older result is replaced to make room: when the room runs out,
173
+ the question is answered with what it has. A look at pages kept in `toolTurns`, and a pointer
174
+ whose result is gone, are still stand-ins. See
175
+ [conversations](./guides/conversations.md) and [how it works](./how-it-works.md).
176
+ - **Steps**: one short line for each tool call, in order, such as
177
+ `Search app.log (exact) for “timeout” — 12 matching lines`, and lines for what the loop itself
178
+ did, such as `Older tool results were shortened to make room in the request`. They arrive live
179
+ through `onStep`, and all together in `AskResult.steps`. Each is one line of plain text that can
180
+ quote the model's words: show it as plain text, never as markdown or HTML. See
181
+ [`AskResult`](./reference/ask.md#askresult) and [web app](./guides/web-app.md).
182
+ - **Store**: a `DocumentStore`, where the text and metadata of documents live and, when the store
183
+ supports it, their original files and line indexes. Built in: `MemoryDocumentStore` and
184
+ `FileDocumentStore`; write your own for a database or object storage. Servers that share a store
185
+ share the documents. See [storage](./guides/storage.md) and
186
+ [`DocumentStore`](./reference/library.md#documentstore).
187
+ - **Tool turns**: `AskResult.toolTurns`, the tool rounds of a question as plain JSON (`ToolTurn`),
188
+ each call with its result. Store them with the chat and pass them back in `messages`, between
189
+ that question and its answer: a later question then sees what was found and need not search
190
+ again. Pages that were shown are not in them. See [conversations](./guides/conversations.md) and
191
+ [`ToolTurn`](./reference/ask.md#toolturn). Not the same as `limits.toolTurns` and the
192
+ `tool_turns_left` field of each result, which count the chat requests of a question (see
193
+ **Limits**).
194
+ - **Tools**: what the model calls to reach the documents: `search_document`, `read_document`,
195
+ `get_document_overview`, `analyze_whole_document` (a whole-file read) and `view_pages` (the pages
196
+ of a PDF whose original is kept). A tool set reaches only the documents it was made for. See
197
+ [tools](./reference/tools.md).
198
+ - **Usage**: `AskResult.usage` (`UsageTotals`), the requests and tokens of a whole question (input,
199
+ cached input, output, thinking), whole-file part reads included, in total and for each model
200
+ (`byModel`). Multiply by your prices for the cost of a question. See
201
+ [costs and limits](./guides/costs-and-limits.md) and
202
+ [`UsageTotals`](./reference/ask.md#usagetotals).
203
+ - **Whole-file read (map-reduce)**: the `analyze_whole_document` tool. The file is cut into parts
204
+ of up to `mapChunkTokens`, each part is read by a model request of its own, several at a time,
205
+ and their notes are merged into one answer. A file that would need more than `maxMapChunks` parts
206
+ is refused. `askWithFiles` offers it only when the adapter that makes the tool calls has
207
+ `generateText` and `wholeDocumentAnalysis` is not `false`; in your own loop, only when you pass
208
+ `generate` to `files.tools()`. Without `generate`, pass `wholeDocumentAnalysis: false` to
209
+ `files.prepare()`, so that the instruction does not name it and the cards do not offer it. See
210
+ [tools](./reference/tools.md) and [how it works](./how-it-works.md).
211
+
212
+ ## Guides
213
+
214
+ One task each, with samples:
215
+
216
+ - [Gemini API and Vertex AI](./guides/vertex-and-gemini.md): the Gemini API and Vertex AI in
217
+ production: endpoints, access tokens, `gemini()` and `askGemini` setup, thinking, whole-file
218
+ reads, pages, gateways, Vertex quotas and errors.
219
+ - [OpenAI-compatible endpoints](./guides/openai-compatible.md): recipes for OpenAI, Azure OpenAI,
220
+ DeepSeek, OpenRouter, vLLM, Ollama, LiteLLM and llama.cpp.
221
+ - [Claude](./guides/anthropic.md): setup, thinking, streaming, conversations that may only grow,
222
+ gateways.
223
+ - [An explorer model](./guides/explorer-model.md): a second, cheaper model that explores the
224
+ documents while another answers: who does what, what changes for your app, cost, any pair of
225
+ providers.
226
+ - [Web app](./guides/web-app.md): uploads (`createDocumentHandlers`, direct `ingest`, the
227
+ browser), answers and progress streamed over server-sent events, cancelling.
228
+ - [Conversations](./guides/conversations.md): the message format, keeping tool turns, history
229
+ across requests and servers, staying inside the window, converters, pointers for repeated calls,
230
+ mixing providers.
231
+ - [Storage](./guides/storage.md): the `DocumentStore` contract and writing your own, the built-in
232
+ stores, owners and a layout per user and per session, retention, original files, the cache.
233
+ - [Deployment](./guides/deployment.md): several servers, memory sizing, sweeps, proxies and
234
+ timeouts for streams, rolling upgrades, Node.js and ESM.
235
+ - [Errors and reliability](./guides/errors-and-reliability.md): every error and its kind and what
236
+ to show a user, retries, waits on a silent model, deadlines, requests too large, empty or broken
237
+ turns, `partialResultOf`.
238
+ - [Costs and limits](./guides/costs-and-limits.md): `AskLimits`, the budget for each model, usage
239
+ totals, cost per user or session, what costs most.
240
+ - [PDFs and other formats](./guides/pdfs.md): formats and their optional dependencies, PDF tables,
241
+ pictures, the page marker, `view_pages`, scanned PDFs, `toolFilePlacement`, your own extractors
242
+ and OCR.
243
+ - [Your own adapter and loop](./guides/own-adapter-and-loop.md): writing or wrapping a
244
+ `ModelAdapter`, your own loop with `prepare()` and `tools()`, `parseSseJson`, `withRetry`.
245
+ - [Testing an integration](./guides/testing.md): tests without a real model: a scripted model, the
246
+ real adapters with a fake `fetch`, errors, expiry and owners, and a few cheap live tests.
247
+
248
+ ## Reference by module
249
+
250
+ Every export and option, one page per part of the package. The first column is the name you
251
+ import from.
252
+
253
+ | Import from | Reference | What is there |
254
+ |---|---|---|
255
+ | `llm-large-files` | [The library and its documents](./reference/library.md) | `createLargeFiles`, `LargeFiles` and its options, the budget, stores, extractors, document types, text helpers |
256
+ | | [The tool loop and the adapter contract](./reference/ask.md) | `askWithFiles`, its options, limits and result, conversation types, the `ModelAdapter` contract, usage, evidence |
257
+ | | [Errors, retries and streams](./reference/errors-and-retries.md) | `ModelRequestError` and error kinds, `withRetry`, timeouts, `parseSseJson` |
258
+ | | [Tools](./reference/tools.md) | each tool the model sees: name, arguments, results, limits; `ToolSet` and its types |
259
+ | | [Events](./reference/events.md) | `askStream`, `eventStream`, the events of a question (`AskEvent`) and of an ingest (`IngestEvent`), `EventError` |
260
+ | `llm-large-files/gemini` | [Gemini](./reference/gemini.md) | `askGemini`, `gemini()`, `geminiApi()`, `vertexAi()` and the other Gemini exports |
261
+ | `llm-large-files/openai` | [OpenAI-compatible](./reference/openai.md) | `openAiCompatible()` and the other OpenAI exports |
262
+ | `llm-large-files/anthropic` | [Claude](./reference/anthropic.md) | `anthropic()` and the other Anthropic exports |
263
+ | `llm-large-files/node` | [Node HTTP handlers](./reference/node.md) | `createDocumentHandlers`: routes, requests, responses and statuses; `writeSseEvents` and `sseMessageOf`, events as Server-Sent Events |
264
+
265
+ ## Internals and measurements
266
+
267
+ - [How it works](./how-it-works.md): the internals end to end: ingest, text encodings, the plan,
268
+ the frame and the cards, room in the request, token estimates, the tools, whole-file reads, the
269
+ loop.
270
+ - [Security](./security.md): owners and scoping, prompt injection (the frame around a file,
271
+ characters that show nothing, hidden text, older encodings), retention, original files, PDFs,
272
+ uploads, regular expressions, cost, storage errors, what the library logs.
273
+ - [Measurements](./measurements.md): every live result and measurement, with its date.
274
+ - [Troubleshooting](./troubleshooting.md): symptom, cause, fix.
275
+
276
+ Older links: [api.md](./api.md) and [configuration.md](./configuration.md) keep their old
277
+ headings, each pointing to its new home.
278
+
279
+ ## Maintainers
280
+
281
+ - [Publishing](./publishing.md): releasing a version to npm.
282
+ - [Contributing](https://github.com/renanbazinin/llm-large-files/blob/main/CONTRIBUTING.md): how to work on the code and its tests.
283
+
284
+ ## Changelog
285
+
286
+ [CHANGELOG.md](../CHANGELOG.md) says what changed in each version. From 0.6.0 on, each version
287
+ starts with what you must change when you upgrade, then what you can add, what works differently
288
+ and what was fixed.
package/docs/api.md CHANGED
@@ -1,228 +1,102 @@
1
1
  # API reference
2
2
 
3
- Three entry points:
3
+ The API reference is no longer one page. It is split by module of the package: one page for each
4
+ of the four other entry points, and four for the main entry, `llm-large-files`. This page keeps the headings of the old
5
+ page, so that links to them still work, and each one points to its new home. The guides that
6
+ explain each task are listed in the [documentation index](./README.md).
4
7
 
5
- | Import | Contents |
8
+ | Entry point | Reference |
6
9
  |---|---|
7
- | `llm-large-files` | Core: `createLargeFiles`, stores, types, helpers. Provider-neutral. |
8
- | `llm-large-files/gemini` | `askGemini`, endpoints, Gemini adapters. |
9
- | `llm-large-files/node` | `createDocumentHandlers` for Node HTTP servers. |
10
+ | `llm-large-files` | [The library and its documents](./reference/library.md), [the tool loop and the adapter contract](./reference/ask.md), [errors, retries and streams](./reference/errors-and-retries.md), [the tools the model sees](./reference/tools.md) |
11
+ | `llm-large-files/gemini` | [Gemini API and Vertex AI: `gemini()`, `askGemini`, the endpoints](./reference/gemini.md) |
12
+ | `llm-large-files/openai` | [OpenAI-compatible endpoints: `openAiCompatible()`](./reference/openai.md) |
13
+ | `llm-large-files/anthropic` | [Claude: `anthropic()`](./reference/anthropic.md) |
14
+ | `llm-large-files/node` | [Node HTTP handlers: `createDocumentHandlers`](./reference/node.md) |
10
15
 
11
16
  ## `llm-large-files`
12
17
 
18
+ Now four pages: [the library and its documents](./reference/library.md), [the tool loop and the adapter contract](./reference/ask.md), [errors, retries and streams](./reference/errors-and-retries.md), and [the tools the model sees](./reference/tools.md).
19
+
13
20
  ### `createLargeFiles(options): LargeFiles`
14
21
 
15
- | Option | Type | Default |
16
- |---|---|---|
17
- | `store` | `DocumentStore` | required |
18
- | `budget` | `Partial<Budget>` | see [configuration](configuration.md#budget) |
19
- | `ttlMs` | `number` | 72 hours. `Infinity` keeps documents until they are deleted (`expiresAt` is then `NEVER_EXPIRES`) |
20
- | `maxUploadBytes` | `number` | 100 MB |
21
- | `extractors` | `Partial<Record<DocumentFormat, Extractor>>` | built-ins |
22
- | `cacheBytes` | `number` | 256 MB: memory that documents kept ready between tool calls may take. Each use checks the store first. 0 keeps none |
23
- | `cacheSize` | `number` | no limit: also caps the number of documents kept. The pieces kept of a document read by range are not counted |
24
- | `wholeDocumentBytes` | `number` | 2 MB: larger documents are read by range when the store can ([details](configuration.md#large-files-many-users-several-servers)). `Infinity` loads all whole |
25
- | `scanChunkBytes` | `number` | 1 MB: text read and searched at a time, reading by range |
26
- | `maxConcurrentScans` | `number` | 4: searches of a document read by range that run at once; the others wait |
27
- | `keepOriginals` | `DocumentFormat[]` | `[]`: only text is kept. `["pdf"]` keeps uploaded PDFs, which `view_pages` needs ([details](configuration.md#keeping-the-uploaded-file)) |
28
- | `scannedPdfPages` | `number` | 30: the longest PDF without any text that is accepted when its original is kept. 0 refuses them all |
22
+ Now [`createLargeFiles`](./reference/library.md#createlargefilesoptions) in the library reference, with every option in [`LargeFilesOptions`](./reference/library.md#largefilesoptions).
29
23
 
30
24
  ### `LargeFiles`
31
25
 
32
- | Member | Description |
33
- |---|---|
34
- | `ingest({ name, mimeType?, bytes, owner? })` | Extracts, normalizes, profiles, and stores a file. Returns `DocumentMeta`. Throws an `Error` with a user-readable message for empty, oversized, binary, or text-less files. |
35
- | `getMeta(id, { owner }?)` | `DocumentMeta`, or `undefined` if unknown, expired, or owned by someone else. |
36
- | `getOriginal(id, { owner }?)` | The uploaded file as a `Uint8Array`, when it was kept. `undefined` otherwise, and for another owner. |
37
- | `delete(id, { owner }?)` | `true` if deleted. |
38
- | `sweep()` | Removes expired documents; returns the count. |
39
- | `prepare(ids, base, { owner?, viewPages? }?)` | Plans one request. `base` is `{ tokens, bytes }` for everything else in the request. Returns `PreparedContext`. `viewPages: true` says that your loop can pass files to the model. |
40
- | `tools(documents, { generate?, onProgress?, signal?, viewPages?, regexBudgetMs? })` | A `ToolSet` scoped to these documents. `generate` enables `analyze_whole_document`, for documents small enough for it. `viewPages` (`true`, or a list of documents such as `prepared.viewable`) enables `view_pages`. `regexBudgetMs` (default 6,000) is the time the regex searches of the tool set may take together. |
41
-
42
- `getMeta`, `getOriginal`, `delete`, `prepare` and the tools read the store. When it cannot be read
43
- (a volume that does not answer, a database that is down) they throw `DocumentStoreError`, and a
44
- tool call answers with its message. That is not "the document is gone": retry. The message names
45
- no path and no host; `error.cause` is what the store threw, for your log.
46
- | `budget`, `maxUploadBytes` | The effective settings. |
26
+ Now [`LargeFiles`](./reference/library.md#largefiles) in the library reference, with the options of its methods and [`DocumentStoreError`](./reference/library.md#documentstoreerror).
47
27
 
48
28
  ### `PreparedContext`
49
29
 
50
- ```ts
51
- {
52
- plan: { inline: DocumentMeta[]; searchable: DocumentMeta[]; inlineTokens: number; inlineBytes: number };
53
- blocks: Map<string, string>; // per document ID: full text (inline) or a summary card (searchable)
54
- instruction: string; // add to the system prompt; empty when there is nothing to search or to look at
55
- missing: string[]; // IDs not found (never uploaded, expired, or another owner's)
56
- viewable: DocumentMeta[]; // PDFs whose pages view_pages can show; empty without viewPages: true
57
- }
58
- ```
30
+ Now [`PreparedContext`](./reference/library.md#preparedcontext) and [`DocumentPlan`](./reference/library.md#documentplan) in the library reference.
59
31
 
60
32
  ### `ToolSet`
61
33
 
62
- ```ts
63
- {
64
- declarations: ToolDeclaration[]; // { name, description, parameters: JSON Schema }
65
- has(name): boolean;
66
- execute(name, args): Promise<ToolResult>; // errors come back as { error } for the model to read
67
- executeWithFiles(name, args, { maxFileBytes?, maxPages? }?): Promise<{ result: ToolResult; files: ToolFile[] }>;
68
- describe(name, args): string; // "Search app.log (exact) for “timeout”"
69
- }
70
- ```
71
-
72
- `executeWithFiles` runs any tool. Its `files` (`{ name, mimeType, bytes }`) are empty for all but
73
- `view_pages`. `execute("view_pages", …)` returns an error, because it has no place for the file.
74
-
75
- | Tool | Arguments | Returns |
76
- |---|---|---|
77
- | `search_document` | `document_id`, `query`, `mode`: `keywords` (default) \| `exact` \| `regex`, `max_results`, `context_lines`, `case_sensitive` | `keywords`: ranked passages with numbered lines. `exact`/`regex`: matching lines and `total_matching_lines`. |
78
- | `read_document` | `document_id`, `start_line`, `end_line?` | Up to 600 numbered lines, and `next_start_line` if there's more |
79
- | `get_document_overview` | `document_id` | Format, size, outline, log profile, first and last lines |
80
- | `analyze_whole_document` | `document_id`, `task` | `answer` from a map-reduce read, plus part counts |
81
- | `view_pages` | `document_id`, `from_page`, `to_page?` | Up to 5 pages of a PDF as one PDF file, with `pages` ("12-14"), `total_pages`, `file` (its name), and `next_page` when fewer pages were given than asked. Declared only with `viewPages`, for PDFs whose original is kept. |
82
-
83
- For a PDF that `view_pages` can show, the results of `search_document` and `read_document` also
84
- carry page numbers: `page` on each matching line, `pages` on a passage and on a range that was read.
34
+ Now [`ToolSet`](./reference/tools.md#toolset); each tool's arguments, results and limits are in [Tools](./reference/tools.md).
85
35
 
86
36
  ### Stores
87
37
 
88
- - `new MemoryDocumentStore({ now? })`: in-process, for tests and single-instance demos.
89
- - `new FileDocumentStore(directory, { now?, orphanAgeMs? })`: `<id>.txt`, `<id>.json` and the line
90
- index `<id>.idx` per document, and `<id>.bin` for a kept original. Safe for several servers on one
91
- volume: files are written whole, large documents are read by range, and `sweep` leaves files
92
- younger than `orphanAgeMs` (1 hour) that belong to no document yet.
93
- - Implement `DocumentStore` (`put`, `get`, `getMeta`, `delete`, `sweep?`, `putOriginal?` with
94
- `getOriginal?` to keep originals, and `readTextRange?` with `putIndex?` and `getIndex?` to read
95
- large documents by range) for anything else.
38
+ Now [`DocumentStore`](./reference/library.md#documentstore), [`MemoryDocumentStore`](./reference/library.md#memorydocumentstore) and [`FileDocumentStore`](./reference/library.md#filedocumentstore) in the library reference; choosing a store and writing your own are in [Storage](./guides/storage.md).
96
39
 
97
40
  ### Helpers
98
41
 
99
- - `toDocumentSummary(meta)`: the browser-safe fields (`DocumentSummary`).
100
- - `toolResultSummary(label, result)`: `" — 12 matching lines"`, for step lists.
101
- - `isDocumentId(value)`, `DOCUMENT_ID_PATTERN`.
102
- - `estimateTokens(text)`, `utf8Bytes(text)`, `jsonBytes(text)`.
103
- - `detectFormat(name, mimeType)`, `defaultExtractors`, `TOOL_NAMES`, `DEFAULT_BUDGET`,
104
- `MAX_VIEW_PAGES` (5).
105
- - `createPdfExtractor({ tables?: boolean, pictures?: boolean })`: the built-in PDF extractor with
106
- an option changed. `tables: false` gives the text in pdf.js order, without rebuilt tables
107
- (see [PDF tables](configuration.md#pdf-tables)). `pictures: false` leaves out the line that marks
108
- a page with a picture (see [Pictures in PDFs](configuration.md#pictures-in-pdfs)).
42
+ Each helper is now on the page of its module: text sizes, formats, extractors, budgets, document IDs and `toDocumentSummary` in [the library reference](./reference/library.md); `toolResultSummary` and the tool constants in [Tools](./reference/tools.md); `evidenceOf`, `stubResult`, `mergeRanges` and `partialResultOf` in [the tool loop reference](./reference/ask.md); retries, error kinds, `parseSseJson` and the waits of the adapters in [Errors, retries and streams](./reference/errors-and-retries.md).
109
43
 
110
44
  ### Key types
111
45
 
112
- ```ts
113
- type DocumentFormat = "text" | "markdown" | "log" | "json" | "csv" | "pdf" | "docx" | "pptx";
114
-
115
- type DocumentMeta = {
116
- id: string; owner?: string; name: string; mimeType: string; format: DocumentFormat;
117
- bytes: number; textBytes: number; characters: number; lines: number; estimatedTokens: number;
118
- wrappedLines: number; pages?: number;
119
- originalKept?: boolean; // the uploaded file is in the store next to the text
120
- outline: { line: number; level: number; title: string }[];
121
- logProfile?: { levels: Record<string, number>; firstTimestamp?: string; lastTimestamp?: string;
122
- topIssues: { template: string; level: string; count: number; firstLine: number }[] };
123
- createdAt: string; expiresAt: string;
124
- };
125
-
126
- type GenerateText = (request: {
127
- system: string; prompt: string; maxOutputTokens: number; signal?: AbortSignal;
128
- onTruncated?: () => void; // call it when the model stopped at maxOutputTokens
129
- }) => Promise<string>;
130
- type Extractor = (bytes: Uint8Array, input: { name: string; mimeType: string; format: DocumentFormat; scannedPages?: number }) => Promise<{ text: string; pages?: number }>;
131
- // scannedPages: set when a PDF without any text is welcome, with the most pages it may have.
132
-
133
- type ToolFile = { name: string; mimeType: string; bytes: Uint8Array };
134
- ```
46
+ Now [`DocumentMeta`](./reference/library.md#documentmeta), [`DocumentSummary`](./reference/library.md#documentsummary), [`DocumentFormat`](./reference/library.md#documentformat), [`Extractor`](./reference/library.md#extractor) and [`ExtractedText`](./reference/library.md#extractedtext) in the library reference, [`GenerateText`](./reference/ask.md#generatetext) and [`ModelCapabilities`](./reference/ask.md#modelcapabilities) in the tool loop reference, and [`ToolFile`](./reference/tools.md#toolfile) in Tools.
47
+
48
+ ## `askWithFiles(options): Promise<AskResult>`
49
+
50
+ Now [`askWithFiles`](./reference/ask.md#askwithfilesoptions), [`AskOptions`](./reference/ask.md#askoptions), [`AskLimits`](./reference/ask.md#asklimits) and [`AskResult`](./reference/ask.md#askresult). What it throws ([`DocumentsNotFoundError`](./reference/ask.md#documentsnotfounderror), [`DocumentStoreError`](./reference/library.md#documentstoreerror), and [`ModelRequestError`](./reference/errors-and-retries.md#modelrequesterror) with its [`ModelErrorKind`](./reference/errors-and-retries.md#modelerrorkind)) and [`partialResultOf`](./reference/ask.md#partialresultoferror) are on those pages; what to show a user is in [Errors and reliability](./guides/errors-and-reliability.md).
51
+
52
+ ### Keeping what a question read
53
+
54
+ Now in [Conversations](./guides/conversations.md); the type is [`ToolTurn`](./reference/ask.md#toolturn).
55
+
56
+ ### Your own adapter
57
+
58
+ Now in [Your own adapter and loop](./guides/own-adapter-and-loop.md); the contract is [`ModelAdapter`](./reference/ask.md#modeladapter).
135
59
 
136
60
  ## `llm-large-files/gemini`
137
61
 
62
+ Now [the `llm-large-files/gemini` reference](./reference/gemini.md); setting up the Gemini API or Vertex AI is in [Gemini API and Vertex AI](./guides/vertex-and-gemini.md).
63
+
64
+ ### `gemini(endpoint, options?): ModelAdapter`
65
+
66
+ Now in [the `llm-large-files/gemini` reference](./reference/gemini.md), with its options.
67
+
138
68
  ### `askGemini(options): Promise<AskGeminiResult>`
139
69
 
140
- | Option | Description |
141
- |---|---|
142
- | `files`, `endpoint`, `documentIds` | Required. |
143
- | `messages` | `{ role: "user" \| "model" \| "assistant", text }[]`; the last must be the user's. |
144
- | `contents` | Instead of `messages`: raw Gemini `contents` (images, inline PDFs…). Not mutated. |
145
- | `system` | System instruction; the tool guide is appended when needed. |
146
- | `generationConfig` | Sent with every chat request. |
147
- | `explorerGenerationConfig` | The same, for the requests of an [explorer model](configuration.md#an-explorer-model). Defaults to `generationConfig`. Not used without an explorer. |
148
- | `owner` | Only documents with this owner (or no owner) are used. |
149
- | `documentPlacement` | `"first"` (default): document text and cards go at the start of the first user turn and stay there, so follow-up questions reuse Gemini's prompt cache. `"last"`: appended to the latest user turn, as in 0.1.0. |
150
- | `maxToolTurns` | Default 12. The most requests for one question, counting the answer. If the model is still calling tools on the last one, it is sent with no tools so the model must answer. With an explorer model the answer is always the last request, so the explorer has one less. |
151
- | `maxToolCallsPerTurn` | Default 8. The most tool calls of one model turn that are run. The others are answered with an error that tells the model to send them again if it still needs them. |
152
- | `wholeDocumentAnalysis` | Default `true`. Set `false` to withhold the costly whole-file tool. |
153
- | `viewPages` | Default `true`. Offers `view_pages` for PDFs whose original is kept. It changes nothing for a library that keeps no originals. |
154
- | `toolFilePlacement` | `"inside"` (default): the pages go in the function response itself, which Gemini 3 models read. `"beside"`: in a user turn of their own after the function responses, for Gemini 2.5, which does not see a file inside a function response. See [Where the pages go](configuration.md#where-the-pages-go-toolfileplacement). |
155
- | `analysisConfig` | `(maxOutputTokens) => generationConfig` for whole-file part reads. The explorer model reads the parts when there is one, so write it for that model. Without it a part is asked for with `{ maxOutputTokens, temperature: 0.2 }`. A model that thinks counts its thoughts in that limit: a reply that it cut off that way is asked for again with 32,768, and later parts start there. |
156
- | `onText`, `onActivity`, `onStep` | Streaming answer text, transient status, completed steps. |
157
- | `fetch`, `signal` | Custom fetch (proxies, tests) and cancellation. |
158
-
159
- Returns `{ text, answered, blockReason?, steps, plan, turns, finishReason?, usage? }`.
160
-
161
- `answered` is `false` when the model's last turn had no text: the prompt was blocked
162
- (`blockReason` says why), the reply was cut off before any text, or the model produced a malformed
163
- tool call and the tool-free retry came back empty too. `text` is then empty or holds only a remark
164
- the model made before a tool call, so show your own message:
165
-
166
- ```ts
167
- const result = await askGemini({ ... });
168
- if (!result.answered) show(result.blockReason ? "The request was blocked." : "No answer this time. Try again.");
169
- ```
170
-
171
- It throws `DocumentsNotFoundError` (`.ids`) before calling the model, `DocumentStoreError` when the
172
- store could not be read (retry: the documents are not gone), `GeminiRequestError` (`.status`) for
173
- HTTP errors, and `Error` when the last message isn't the user's.
174
-
175
- With an [explorer model](configuration.md#an-explorer-model), `text` and `onText` carry only what
176
- the answering model wrote, `turns` counts the requests of both models, and `usage` and
177
- `finishReason` are those of the answer. An explorer that fails throws `GeminiRequestError` too.
70
+ Now in [the `llm-large-files/gemini` reference](./reference/gemini.md), with its options and its result.
178
71
 
179
72
  ### Endpoints
180
73
 
181
- - `geminiApi({ apiKey, model, explorerModel?, apiVersion = "v1beta", baseUrl? })`
182
- - `vertexAi({ project, model, explorerModel?, location = "global", accessToken, apiVersion = "v1" })`,
183
- where `accessToken` can be a string or `() => string | Promise<string>`.
184
- - Or any `{ url, streamUrl?, headers, explorerUrl? }` (`headers` can be a function).
185
-
186
- `model` is the model that answers. `explorerModel` names a second one that makes the tool calls and
187
- reads whole files in parts, so that `model` only writes the answer. Left out, empty, or the same as
188
- `model`, one model does both, as before. In an endpoint of your own it is `explorerUrl`: the
189
- `...:generateContent` URL of the explorer, called with the same headers. See
190
- [An explorer model](configuration.md#an-explorer-model).
74
+ `geminiApi`, `vertexAi`, `vertexHost` and the `GeminiEndpoint` type (an endpoint of your own) are now in [the `llm-large-files/gemini` reference](./reference/gemini.md); access tokens and gateways are in [Gemini API and Vertex AI](./guides/vertex-and-gemini.md).
191
75
 
192
76
  ### Lower-level helpers
193
77
 
194
- - `createGeminiGenerateText({ url, headers, fetchImpl?, generationConfig?, timeoutMs? })`: a `GenerateText` for your own loop.
195
- - `toGeminiTools(declarations)`: `{ functionDeclarations }`.
196
- - `geminiFunctionResponses([{ call, result, files? }])`: the `user` turn answering function
197
- calls. Files from `executeWithFiles` go inside their function response, as base64.
198
- - `geminiFunctionResponseTurns([{ call, result, files? }], { files?: "inside" | "beside" })`: the
199
- turns to add to `contents`. That is the one turn above, or with `"beside"` the function
200
- responses followed by a `user` turn that holds the files.
201
- - `FINAL_ANSWER_REQUEST`, `FINAL_ANSWER_AFTER_PAGES`: the messages `askGemini` adds when the model
202
- must stop using tools. The second is used when `view_pages` was the only tool.
203
- - `FINAL_ANSWER_WITHOUT_TOOLS`, `EXPLORER_INSTRUCTION`: the two texts `askGemini` adds for an
204
- explorer model. The first asks the answering model for the answer when the explorer called no
205
- tool. The second is the line in the explorer's system instruction that says what its part is.
206
- - `parseSseJson(stream)`: async iterator over a Generate Content SSE stream.
78
+ `createGeminiGenerateText`, `toGeminiTools`, `geminiFunctionResponses` and `geminiFunctionResponseTurns` are now in [the `llm-large-files/gemini` reference](./reference/gemini.md); `FINAL_ANSWER_REQUEST`, `FINAL_ANSWER_AFTER_PAGES`, `FINAL_ANSWER_WITHOUT_TOOLS` and `EXPLORER_INSTRUCTION` in [the tool loop reference](./reference/ask.md); `parseSseJson` in [Errors, retries and streams](./reference/errors-and-retries.md); `llm-large-files/gemini` still exports them all, as [its reference](./reference/gemini.md) lists.
207
79
 
208
- ## `llm-large-files/node`
80
+ ## `llm-large-files/openai`
209
81
 
210
- ### `createDocumentHandlers(files, { getOwner? })`
82
+ Now [the `llm-large-files/openai` reference](./reference/openai.md); recipes for OpenAI, Azure OpenAI, DeepSeek, OpenRouter, vLLM, Ollama, LiteLLM and llama.cpp are in [OpenAI-compatible endpoints](./guides/openai-compatible.md).
83
+
84
+ ### `openAiCompatible(options): ModelAdapter`
85
+
86
+ Now in [the `llm-large-files/openai` reference](./reference/openai.md), with its options.
87
+
88
+ ## `llm-large-files/anthropic`
211
89
 
212
- Returns `{ upload(req, res), get(req, res, id), remove(req, res, id) }`.
90
+ Now [the `llm-large-files/anthropic` reference](./reference/anthropic.md); setting up Claude is in [Claude](./guides/anthropic.md).
213
91
 
214
- - **upload**: the body is the raw file. Name it with an `X-File-Name` header (URI-encoded) or a
215
- `?name=` query parameter, and optionally set `X-File-Type`. Responds 201 with a `DocumentSummary`,
216
- or 400/413/422/500 with `{ error }`. If a framework already parsed the body into a `Buffer`
217
- (`express.raw()`), that buffer is used.
218
- - **get**: 200 with a `DocumentSummary`, or 404.
219
- - **remove**: `{ deleted: boolean }`.
92
+ ### `anthropic(options): ModelAdapter`
220
93
 
221
- Each handler answers its errors itself and never rejects, so it needs no `catch`. 422 is a file
222
- that cannot be read. 500 is the server's trouble, such as a store that fails: the message says
223
- what failed and gives a system error's code (`Upload failed (ENOSPC).`), never a path or a host.
94
+ Now in [the `llm-large-files/anthropic` reference](./reference/anthropic.md), with its options.
95
+
96
+ ## `llm-large-files/node`
97
+
98
+ Now [the `llm-large-files/node` reference](./reference/node.md); uploads and streamed answers are in [Web app](./guides/web-app.md).
99
+
100
+ ### `createDocumentHandlers(files, { getOwner? })`
224
101
 
225
- `getOwner` runs before the upload is read. To refuse a request, throw an error with a `status`
226
- (or `statusCode`) between 400 and 599, as the `http-errors` package makes:
227
- `throw Object.assign(new Error("Sign in first."), { status: 401 })`. The handler answers with that
228
- status and message. Any other error from `getOwner` is a 500 that does not repeat its message.
102
+ Now in [the `llm-large-files/node` reference](./reference/node.md), with its options, routes and statuses.