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
@@ -0,0 +1,717 @@
1
+ # Gemini API and Vertex AI
2
+
3
+ This guide sets up Gemini for production, on Vertex AI or on the Gemini API: endpoints and access
4
+ tokens, `askGemini` or `askWithFiles` with `gemini()`, the waits on a model that thinks, thinking,
5
+ the budget, an explorer model, whole-file reads, pages of PDFs, an enterprise gateway, quotas and
6
+ errors. It is for developers who call Gemini from a server. Every export and option of
7
+ `llm-large-files/gemini` is listed in the [reference](../reference/gemini.md).
8
+
9
+ ## Vertex AI or the Gemini API
10
+
11
+ `vertexAi()` and `geminiApi()` each return a `GeminiEndpoint`: the URLs of one model and the
12
+ headers to send. The adapter, the tools and the loop are the same for both. Only the URL and the
13
+ headers differ.
14
+
15
+ | | `vertexAi()` | `geminiApi()` |
16
+ |---|---|---|
17
+ | Sign-in | An OAuth access token, sent as `Authorization: Bearer …` | An API key, sent as the `x-goog-api-key` header |
18
+ | Host | The host of the `location` you pick, `"global"` by default | `https://generativelanguage.googleapis.com` (`baseUrl`) |
19
+ | API version | `"v1"` (`apiVersion`) | `"v1beta"` (`apiVersion`) |
20
+ | Streaming | `streamUrl` is set (`:streamGenerateContent?alt=sse`) | The same |
21
+ | A second model that explores | `explorerModel` | `explorerModel` |
22
+
23
+ Use Vertex AI when your servers run in a Google Cloud project: access goes through IAM and service
24
+ accounts, so there is no long-lived key to keep secret, you choose the location that processes the
25
+ requests, and quotas and billing are the project's. Use the Gemini API for a setup with an API key,
26
+ for prototypes and for tests.
27
+
28
+ ### Vertex AI
29
+
30
+ `vertexAi({ project, model, accessToken, location?, apiVersion?, explorerModel? })` builds the URL
31
+ `{host}/{apiVersion}/projects/{project}/locations/{location}/publishers/google/models/{model}:generateContent`,
32
+ and the same with `:streamGenerateContent?alt=sse` for streaming. `location` defaults to
33
+ `"global"`. The host follows the location: see [`vertexHost()`](../reference/gemini.md#vertexhostlocation).
34
+
35
+ With `"global"`, Google may serve a request from any region. Pick `"us"`, `"eu"` or a region when
36
+ your data must be processed there. Which models a location offers is Google's to say: a model name
37
+ the location does not have is refused, and the error has `kind` `"invalid"`. Set `apiVersion` only
38
+ when you need another version of the API than `"v1"`. The library was checked live on Vertex AI in
39
+ the `global` and `eu` locations: see [Measurements](../measurements.md).
40
+
41
+ ### Access tokens for Vertex AI
42
+
43
+ `accessToken` is a string, or a function that returns one. Give a function: the adapter calls it
44
+ before every request, the part reads of a whole-file read included, so a token that was renewed is
45
+ used, and a question that outlasts a token keeps working. A string is sent as it is for as long as
46
+ the endpoint lives, and an access token expires (after an hour, by default): use one only in a
47
+ script.
48
+
49
+ The usual source is `google-auth-library` with application default credentials (ADC). It is not a
50
+ dependency of this package:
51
+
52
+ ```bash
53
+ npm install google-auth-library
54
+ ```
55
+
56
+ ```ts
57
+ import { GoogleAuth } from "google-auth-library";
58
+ import { vertexAi } from "llm-large-files/gemini";
59
+
60
+ // Application default credentials: on Google Cloud (Cloud Run, GKE with Workload Identity, Compute
61
+ // Engine), the service account the server runs as; elsewhere, the key file that
62
+ // GOOGLE_APPLICATION_CREDENTIALS names; on a laptop, `gcloud auth application-default login`.
63
+ const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
64
+
65
+ // Called before every request. GoogleAuth keeps the token and fetches a new one when it is about
66
+ // to expire, so the call is cheap.
67
+ async function accessToken(): Promise<string> {
68
+ const token = await auth.getAccessToken();
69
+ if (!token) throw new Error("No access token from the application default credentials.");
70
+ return token;
71
+ }
72
+
73
+ const endpoint = vertexAi({
74
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
75
+ location: "global",
76
+ model: "gemini-3.8-flash",
77
+ accessToken,
78
+ });
79
+ ```
80
+
81
+ - **A service account.** Prefer the account the server runs as (attached to Cloud Run or Compute
82
+ Engine, or mapped to a Kubernetes service account with Workload Identity): there is no key file
83
+ to store. Off Google Cloud, point `GOOGLE_APPLICATION_CREDENTIALS` at its key file, or pass
84
+ `keyFilename` to `GoogleAuth`. The account needs a role that may call the model, such as Vertex AI
85
+ User (`roles/aiplatform.user`).
86
+ - **An error thrown by your function** has no HTTP status and no `kind`. In a chat request it ends
87
+ the question with that error: the request is not sent again. In a part read it is tried once
88
+ more, and the part is then reported as one that could not be read.
89
+ - **A token that is refused** (HTTP 401 or 403: expired, a missing role, the Vertex AI API not
90
+ enabled in the project) is a `GeminiRequestError` with `kind` `"auth"`. It is not sent again.
91
+
92
+ ### The Gemini API
93
+
94
+ ```ts
95
+ import { geminiApi } from "llm-large-files/gemini";
96
+
97
+ const endpoint = geminiApi({
98
+ apiKey: process.env.GEMINI_API_KEY!,
99
+ model: "gemini-3.8-flash",
100
+ });
101
+ // endpoint.url: https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent
102
+ // endpoint.streamUrl: https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse
103
+ ```
104
+
105
+ The key goes in a header, not in the URL, so it stays out of URL logs. `baseUrl` points the endpoint
106
+ at a proxy that keeps the Gemini API's paths. The samples below that take an `endpoint` use the
107
+ Vertex AI one of [Access tokens for Vertex AI](#access-tokens-for-vertex-ai); a `geminiApi()`
108
+ endpoint can take its place.
109
+
110
+ ## `askGemini` or `askWithFiles` with `gemini()`
111
+
112
+ `askGemini` is [`askWithFiles`](../reference/ask.md#askwithfilesoptions) with Gemini models made for
113
+ you. It builds `gemini(endpoint, …)` for the model that answers and, when the endpoint names an
114
+ explorer (`explorerUrl`, which `explorerModel` sets), a second `gemini()` for it, with the same
115
+ headers.
116
+
117
+ ```ts
118
+ import { readFile } from "node:fs/promises";
119
+ import { createLargeFiles, FileDocumentStore, type ChatTurn } from "llm-large-files";
120
+ import { askGemini } from "llm-large-files/gemini";
121
+
122
+ // endpoint as in Access tokens for Vertex AI.
123
+ const files = createLargeFiles({ store: new FileDocumentStore("./data/large-files") });
124
+ const meta = await files.ingest({ name: "import.log", bytes: await readFile("./import.log") });
125
+
126
+ const documentIds = [meta.id];
127
+ const messages: ChatTurn[] = [{ role: "user", text: "Why did the import fail at 02:00?" }];
128
+
129
+ const result = await askGemini({
130
+ files, endpoint, documentIds, messages,
131
+ onText: (delta) => process.stdout.write(delta), // streamed: the endpoint has a streamUrl
132
+ });
133
+ console.log(result.answered, result.usage.byModel);
134
+ ```
135
+
136
+ On top of `askWithFiles`, `askGemini` adds:
137
+
138
+ - `contents`: the history as Gemini `contents`, with images or inline PDFs, in place of `messages`
139
+ ([below](#gemini-history-stored-as-contents)).
140
+ - `generationConfig` for the model that answers and `explorerGenerationConfig` for the explorer.
141
+ - One value of `toolFilePlacement`, `analysisConfig`, `firstByteTimeoutMs`, `idleTimeoutMs` and
142
+ `fetch`, given to both models.
143
+ - `maxToolTurns` and `maxToolCallsPerTurn`, the names that `limits.toolTurns` and
144
+ `limits.callsPerTurn` had before 0.5.0. `limits` wins when both are set.
145
+
146
+ Every other option goes to `askWithFiles` as it is. What `askGemini` cannot do:
147
+
148
+ | You need | `askGemini` | `askWithFiles` with `gemini()` |
149
+ |---|---|---|
150
+ | A smaller window or request size for the model, so the budget follows it down | No: set them in the budget ([below](#the-window-and-the-budget)) | `contextTokens`, `maxRequestBytes` |
151
+ | The cost of a page, the name in `usage.byModel` | No: 530 tokens, the model in the URL | `pageTokens`, `id` |
152
+ | An explorer with other headers, or of another provider | No: the same headers (with `vertexAi()` or `geminiApi()`, the same project, location and key too) | `explorer`: any adapter |
153
+ | Different waits, `fetch` or `toolFilePlacement` for each model | No: one value for both | Each adapter its own |
154
+ | A part reader of your own ([below](#whole-file-reads-in-parts)) | No | Yes |
155
+ | Turns with native parts in `messages` | Use `contents` | `{ role, parts: [{ text }, { native }] }` |
156
+
157
+ Start with `askGemini`. Move to `askWithFiles` when you need a row of this table:
158
+
159
+ ```ts
160
+ import { askWithFiles } from "llm-large-files";
161
+ import { gemini, vertexAi } from "llm-large-files/gemini";
162
+
163
+ // files, documentIds and messages as in the sample above; accessToken as in Access tokens for Vertex AI.
164
+ const model = gemini(
165
+ vertexAi({ project: process.env.GOOGLE_CLOUD_PROJECT!, model: "gemini-3.8-flash", accessToken }),
166
+ { generationConfig: { temperature: 0.3 } },
167
+ );
168
+
169
+ const result = await askWithFiles({
170
+ files, model, documentIds, messages,
171
+ onText: (delta) => process.stdout.write(delta),
172
+ });
173
+ ```
174
+
175
+ What the Gemini adapter does in either case:
176
+
177
+ - **It streams** a reply when `onText` is given and the endpoint has a `streamUrl`. Otherwise each
178
+ reply arrives whole, and `onText` gets its text once the reply is in: one call for each text part.
179
+ - **It sends its own model turns back unchanged** in the later requests of the question, because
180
+ Gemini 3 wants its thought signatures back. Another model gets them rebuilt from their function
181
+ calls, without signatures, as stored `toolTurns` always are. With an explorer, that is the
182
+ answering model.
183
+ - **It never shows thoughts.** Parts that Gemini marks `"thought": true` are not in `text` and not
184
+ passed to `onText`.
185
+ - **The request that must be answered in text declares no tools.** Gemini can ignore
186
+ `functionCallingConfig` mode `NONE` and go on calling them.
187
+ - **A stream that ends without a `finishReason` was cut off** on its way (a proxy, a dropped
188
+ connection). It is sent again when none of its text was shown, and is an error otherwise.
189
+ - **A turn with `MALFORMED_FUNCTION_CALL` or `UNEXPECTED_TOOL_CALL`** is asked for once more, the
190
+ request for the answer included: there the note says that no tool can be called, and asks for
191
+ the answer in text.
192
+ `SAFETY`, `RECITATION`, `BLOCKLIST`, `PROHIBITED_CONTENT`, `SPII` and `IMAGE_SAFETY` mark a reply
193
+ that a filter stopped; `MAX_TOKENS`, one cut off at the output limit.
194
+
195
+ **Usage.** `usage.byModel` is keyed by the model name in the URL (`"gemini-3.8-flash"`). Input
196
+ tokens are `promptTokenCount` plus `toolUsePromptTokenCount`, cached tokens `cachedContentTokenCount`,
197
+ and output tokens `candidatesTokenCount` plus `thoughtsTokenCount` (the thoughts are also
198
+ `thoughtTokens`). `lastUsage` is Gemini's own `usageMetadata` of the last response. Turning that into
199
+ a cost: [Costs and limits](./costs-and-limits.md).
200
+
201
+ ## Waits: a model that thinks sends nothing
202
+
203
+ A chat request has two waits. `firstByteTimeoutMs` (600,000 ms, ten minutes) is the longest wait for
204
+ the first piece of the reply, and `idleTimeoutMs` (300,000 ms) the longest gap between two pieces
205
+ once it has started. A request that gets nothing for that long is aborted with a
206
+ `GeminiRequestError` ("Gemini sent nothing for 600 s.", `status` 0, `kind` `"timeout"`) and sent
207
+ again, once.
208
+
209
+ The first wait is long because of how Gemini answers:
210
+
211
+ - **Headers do not count.** A server may send them at once and then think.
212
+ - **A model that thinks sends nothing while it thinks** (unless you ask it for its thoughts). The
213
+ first piece comes when it starts to write, which on a large request with a high thinking level
214
+ can take minutes.
215
+ - **A reply that is not streamed arrives whole, at the end.** The explorer's requests are never
216
+ streamed, and neither is any request made without `onText` or to an endpoint without a
217
+ `streamUrl`. For those, this wait covers the whole reply.
218
+
219
+ Any bytes count as a piece, keep-alives included, and a reply that keeps arriving has no limit.
220
+ Set the waits on `gemini()` or `askGemini` (which gives both models the same); 0 waits without end:
221
+
222
+ ```ts
223
+ import { askGemini, gemini } from "llm-large-files/gemini";
224
+
225
+ // files, endpoint, documentIds and messages as in the askGemini sample above.
226
+ await askGemini({ files, endpoint, documentIds, messages, firstByteTimeoutMs: 900_000, idleTimeoutMs: 120_000 });
227
+
228
+ // With askWithFiles, each adapter has its own.
229
+ const patient = gemini(endpoint, { firstByteTimeoutMs: 900_000 });
230
+ ```
231
+
232
+ What this means for your server:
233
+
234
+ - **A question has no deadline of its own.** Each chat request may wait the whole
235
+ `firstByteTimeoutMs`, twice. Give `signal` a deadline:
236
+ `AbortSignal.any([clientGone, AbortSignal.timeout(15 * 60_000)])`. A request that already showed
237
+ text is not sent again, and `retry: { retries: 0 }` turns the second try off.
238
+ - **Keep the waits below the request timeout of what stands in front of your server**, or raise
239
+ that timeout: a load balancer, a proxy, Cloud Run. Keep the stream to the browser alive while the
240
+ model is silent: [Web app](./web-app.md) and [Deployment](./deployment.md).
241
+ - **Part reads have a limit of their own**, 180 s a request: [below](#whole-file-reads-in-parts).
242
+
243
+ ## Thinking
244
+
245
+ Thinking is set in `generationConfig.thinkingConfig`, which the adapter sends as it is: the library
246
+ does not check it. A model that does not take a setting refuses the request with HTTP 400, `kind`
247
+ `"invalid"`, and the error is thrown. Given a `thinkingLevel`, `gemini-2.5-flash-lite` on Vertex AI
248
+ answered "thinking_level is not supported by this model".
249
+
250
+ - `generationConfig` goes with every chat request of its model. With `askGemini`,
251
+ `explorerGenerationConfig` is the explorer's, and defaults to `generationConfig`: set it when the
252
+ two models do not take the same settings.
253
+ - The part reads of a whole-file read do not get `generationConfig`. They get `analysisConfig`, or
254
+ `{ maxOutputTokens }` without it, with no temperature: Gemini 3.6 and later ignore it, and
255
+ Google says later models will refuse it. Until 0.6.0 the default was
256
+ `{ maxOutputTokens, temperature: 0.2 }`; to keep it for an older model, pass
257
+ `analysisConfig: (maxOutputTokens) => ({ maxOutputTokens, temperature: 0.2 })`. With an explorer,
258
+ the explorer reads the parts, so write `analysisConfig` for it.
259
+ - A model that thinks counts its thoughts in `maxOutputTokens`. Leave the limit out, or leave room
260
+ for the thoughts in it.
261
+
262
+ **Part reads and `THINKING_OUTPUT_TOKENS`.** A part of a whole-file read is asked for 4,096 tokens
263
+ of notes, and the answer of the read for 8,192. A thinking model can spend that on thoughts: asked
264
+ for 4,096 tokens of notes on a part of a log, Gemini 3.8 Flash spent 3,931 of them thinking and
265
+ wrote two lines, and Gemini 4 wrote nothing (November 2026). When a reply stops at the limit with
266
+ nothing written, or with half the limit or more gone on thoughts, it is asked for once more with
267
+ `THINKING_OUTPUT_TOKENS` (32,768), and later requests to that URL start there, for the life of the
268
+ process. A model or a gateway that refuses 32,768 (HTTP 400) is not asked for it again, unless the
269
+ 400 says the request was too large for the model's window with that limit, and the window is
270
+ larger than 32,768: a later part may still get it. `analysisConfig` receives the limit: put it in
271
+ `maxOutputTokens`, or the second request is the same as the first.
272
+
273
+ ```ts
274
+ import { askGemini } from "llm-large-files/gemini";
275
+
276
+ // files, endpoint, documentIds and messages as in the askGemini sample above.
277
+ await askGemini({
278
+ files, endpoint, documentIds, messages,
279
+ generationConfig: { temperature: 0.3, thinkingConfig: { thinkingLevel: "high" } }, // the answering model
280
+ explorerGenerationConfig: { thinkingConfig: { thinkingBudget: 0 } }, // a Gemini 2.5 explorer
281
+ // The part reads go to the Gemini 2.5 explorer, which takes a temperature.
282
+ analysisConfig: (maxOutputTokens) => ({ maxOutputTokens, temperature: 0.2, thinkingConfig: { thinkingBudget: 0 } }),
283
+ toolFilePlacement: "beside", // one of the two is Gemini 2.5: see Pages of PDFs below
284
+ });
285
+ ```
286
+
287
+ ## The window and the budget
288
+
289
+ The library plans every question against a budget: what goes in whole, what is searched, how large
290
+ a tool result may be. By default it assumes a window of 1,000,000 tokens and requests of at most
291
+ 10,000,000 bytes. Its token estimate is fitted to Gemini's own count, so a Gemini model needs no
292
+ `tokenScale`. Vertex AI names a window of 1,048,576 tokens in its errors for
293
+ `gemini-3.1-flash-lite` (November 2026), and the default fits such a model.
294
+
295
+ Tell the library when your model, or the connection to it, takes less. A window or request size
296
+ that `gemini()` declares only lowers the budget: the smaller of it and the library's
297
+ `budget.contextTokens` (or `budget.maxRequestBytes`) holds. For a model that takes more than
298
+ 1,000,000 tokens, raise the library's budget: `createLargeFiles({ budget: { contextTokens: 2_000_000 } })`.
299
+
300
+ ```ts
301
+ import { createLargeFiles, FileDocumentStore } from "llm-large-files";
302
+ import { askGemini, gemini } from "llm-large-files/gemini";
303
+
304
+ // endpoint, documentIds and messages as in the askGemini sample above.
305
+
306
+ // askWithFiles: the adapter says what its model takes, and the budget of each question follows it down.
307
+ const small = gemini(endpoint, { contextTokens: 128_000, maxRequestBytes: 4_000_000 });
308
+
309
+ // askGemini cannot say it for its models: put it in the library's budget...
310
+ const files = createLargeFiles({
311
+ store: new FileDocumentStore("./data/large-files"),
312
+ budget: { contextTokens: 128_000, maxRequestBytes: 4_000_000 },
313
+ });
314
+ // ...or in the budget of one question.
315
+ await askGemini({ files, endpoint, documentIds, messages, budget: { contextTokens: 128_000 } });
316
+ ```
317
+
318
+ With an explorer, the budget must fit both models: `askWithFiles` takes the smaller of what the two
319
+ adapters declare; with `askGemini`, set the smaller one yourself.
320
+
321
+ A window left too large is not fatal. The first request that Gemini refuses as too large teaches
322
+ the loop the window it names; it shortens older tool results and sends the request again, or plans
323
+ the documents again when no tool has run yet
324
+ ([A request too large](#a-request-too-large)). That costs a refused request and a step the user
325
+ sees: declare the window instead. How the budget is worked out, and what each field does:
326
+ [Costs and limits](./costs-and-limits.md).
327
+
328
+ ## An explorer model
329
+
330
+ An explorer is a second, cheaper or faster model that makes the tool calls (search, read, look at
331
+ pages) and reads whole files in parts, while the model you named only writes the answer from what
332
+ the tools returned. With `askGemini`, name it in the endpoint: `explorerModel` in `vertexAi()` or
333
+ `geminiApi()` (left out, empty, or the same as `model`, one model does both), or `explorerUrl` in an
334
+ endpoint of your own. It is called with the endpoint's headers (with `vertexAi()`, in the same
335
+ project and location), never streamed, with `explorerGenerationConfig`, and it reads the parts, so
336
+ `analysisConfig` is for it. If either model is Gemini 2.5, use `toolFilePlacement: "beside"`. To
337
+ give the two models other headers or their own limits, or to pair Gemini with another provider,
338
+ use `askWithFiles` with two adapters. Who does what, what changes in the result, and the cost:
339
+ [An explorer model](./explorer-model.md).
340
+
341
+ ```ts
342
+ import { askWithFiles } from "llm-large-files";
343
+ import { askGemini, gemini, vertexAi } from "llm-large-files/gemini";
344
+
345
+ // files, documentIds and messages as in the askGemini sample above; accessToken as in Access
346
+ // tokens for Vertex AI.
347
+ const project = process.env.GOOGLE_CLOUD_PROJECT!;
348
+
349
+ // askGemini: one endpoint names both models.
350
+ await askGemini({
351
+ files, documentIds, messages,
352
+ endpoint: vertexAi({ project, accessToken, model: "gemini-3.8-flash", explorerModel: "gemini-3.5-flash-lite" }),
353
+ });
354
+
355
+ // askWithFiles: two adapters, each with its own endpoint and settings.
356
+ await askWithFiles({
357
+ files, documentIds, messages,
358
+ model: gemini(vertexAi({ project, accessToken, model: "gemini-3.8-flash" })),
359
+ explorer: gemini(vertexAi({ project, accessToken, model: "gemini-3.5-flash-lite", location: "europe-west4" })),
360
+ });
361
+ ```
362
+
363
+ ## Whole-file reads in parts
364
+
365
+ `analyze_whole_document` reads a file in parts, four at a time, and writes one answer from the
366
+ notes. `gemini()` reads the parts with `createGeminiGenerateText`: on the endpoint's `url` (not
367
+ streamed), with its headers (asked for before each request), the adapter's `fetch` and
368
+ `analysisConfig`. The parts follow the question's `retry`, as chat requests do.
369
+
370
+ Each part read may take 180 s. That is a limit of its own, not the waits above, and `gemini()` and
371
+ `askGemini` cannot change it. A part that runs out of time is tried once more at once, and is then
372
+ reported in the answer of the read as a part that could not be read. To give the parts more time,
373
+ replace the adapter's part reader with your own (with `askWithFiles` only):
374
+
375
+ ```ts
376
+ import type { ModelAdapter } from "llm-large-files";
377
+ import { createGeminiGenerateText, gemini, vertexAi } from "llm-large-files/gemini";
378
+
379
+ // accessToken as in Access tokens for Vertex AI.
380
+ const readerEndpoint = vertexAi({ project: process.env.GOOGLE_CLOUD_PROJECT!, model: "gemini-3.5-flash-lite", accessToken });
381
+ const reader: ModelAdapter = {
382
+ ...gemini(readerEndpoint),
383
+ generateText: createGeminiGenerateText({
384
+ url: readerEndpoint.url,
385
+ headers: readerEndpoint.headers,
386
+ timeoutMs: 300_000, // five minutes for each part read
387
+ generationConfig: (maxOutputTokens) => ({ maxOutputTokens }), // the default: no temperature
388
+ }),
389
+ };
390
+ // Give it as `explorer` (it reads the parts when there is one), or as `model` when it works alone.
391
+ ```
392
+
393
+ A part that Gemini refuses as larger than it takes is read as two halves, while `maxMapChunks` and
394
+ the requests the question has left allow it. A part that cannot be read is reported to the model
395
+ by the kind and status of its error ("The model was busy (HTTP 429).", "The model's quota has run
396
+ out (HTTP 429)."), never by Google's message, which can name your project. How the parts are cut
397
+ and merged: [How it works](../how-it-works.md).
398
+
399
+ ## Pages of PDFs
400
+
401
+ When the library keeps the uploaded PDFs (`keepOriginals: ["pdf"]`), the model gets `view_pages`,
402
+ which hands it up to five pages at a time as one PDF. The Gemini adapter needs no setup for it. Two
403
+ settings matter:
404
+
405
+ - **`toolFilePlacement`.** `"inside"` (the default) puts the PDF in the `parts` of its function
406
+ response, which names it as `{ "$ref": "pages-12-14.pdf" }`. Gemini 3 models read it there.
407
+ Gemini 2.5 accepts that form, bills it, and does not see the pages: use `"beside"`, which sends the
408
+ PDFs in a user turn of their own after the function responses. `askGemini` gives both models one
409
+ value, so use `"beside"` when either is Gemini 2.5.
410
+ - **`pageTokens`.** What Gemini bills for one page: 530 by default (`GEMINI_PAGE_TOKENS`; 520 to 532
411
+ were measured). A question may look at `reservedTokens / 2 / pageTokens` pages, 60 with the default
412
+ budget. It is an option of `gemini()`; `askGemini` uses 530.
413
+
414
+ ```ts
415
+ import { askGemini } from "llm-large-files/gemini";
416
+
417
+ // files, endpoint, documentIds and messages as in the askGemini sample above.
418
+ await askGemini({ files, endpoint, documentIds, messages, toolFilePlacement: "beside" }); // for Gemini 2.5
419
+ ```
420
+
421
+ The optional dependency, the limits, scanned PDFs and the live results: [PDFs](./pdfs.md).
422
+
423
+ ## An enterprise gateway
424
+
425
+ A gateway that proxies Generate Content takes an endpoint of your own: `{ url, streamUrl?, headers,
426
+ explorerUrl? }`. It must accept Gemini's request body and answer with Gemini's JSON, and its
427
+ `streamUrl` with server-sent events, as `:streamGenerateContent?alt=sse` does.
428
+
429
+ ```ts
430
+ import type { GeminiEndpoint } from "llm-large-files/gemini";
431
+
432
+ const gateway = "https://llm-gateway.corp.example/gemini/models";
433
+
434
+ // Your gateway's token: called before every request, so keep it cached and renew it before it expires.
435
+ async function gatewayToken(): Promise<string> {
436
+ return process.env.GATEWAY_TOKEN!;
437
+ }
438
+
439
+ const endpoint: GeminiEndpoint = {
440
+ url: `${gateway}/gemini-3.8-flash:generateContent`,
441
+ streamUrl: `${gateway}/gemini-3.8-flash:streamGenerateContent?alt=sse`, // optional
442
+ explorerUrl: `${gateway}/gemini-3.5-flash-lite:generateContent`, // optional, askGemini only
443
+ headers: async () => ({
444
+ "Content-Type": "application/json",
445
+ Authorization: `Bearer ${await gatewayToken()}`,
446
+ }),
447
+ };
448
+ ```
449
+
450
+ - **`headers` are sent exactly as given.** The adapter adds no `Content-Type`: include
451
+ `"Content-Type": "application/json"` yourself.
452
+ - **`headers` as a function** is called before every request, part reads included. A plain object
453
+ is sent as it is.
454
+ - **Without `streamUrl`** each reply arrives whole: nothing streams to the user.
455
+ - **`explorerUrl`** is the explorer's `...:generateContent` URL, on any host. `askGemini` calls it
456
+ with the same headers. `gemini()` ignores it: an explorer is an adapter of its own.
457
+ - **The name in `usage.byModel`** is read from `/models/{name}` in the URL, or is the host when the
458
+ URL has none. With `askWithFiles`, name it with `gemini(endpoint, { id })`.
459
+ - **A body limit** of the gateway goes in `maxRequestBytes` ([above](#the-window-and-the-budget)).
460
+
461
+ The same form reaches Vertex AI on a host that `vertexAi()` does not build, such as a private
462
+ endpoint of your network:
463
+
464
+ ```ts
465
+ import type { GeminiEndpoint } from "llm-large-files/gemini";
466
+
467
+ // accessToken as in Access tokens for Vertex AI.
468
+ const host = process.env.VERTEX_HOST!; // where your network reaches Vertex AI
469
+ const path = `/v1/projects/${process.env.GOOGLE_CLOUD_PROJECT}/locations/europe-west4/publishers/google/models/gemini-3.8-flash`;
470
+ const privateEndpoint: GeminiEndpoint = {
471
+ url: `${host}${path}:generateContent`,
472
+ streamUrl: `${host}${path}:streamGenerateContent?alt=sse`,
473
+ headers: async () => ({ "Content-Type": "application/json", Authorization: `Bearer ${await accessToken()}` }),
474
+ };
475
+ ```
476
+
477
+ ## Quotas, retries and errors on Vertex AI
478
+
479
+ A request that Gemini refused, or that got no whole answer, throws a `GeminiRequestError`: a
480
+ `ModelRequestError` with `status` (0 when no answer came), `kind`, and `retryAfterMs` when the error
481
+ names a wait. The loop sends a request again when another try can help, and throws the error when
482
+ it cannot. What each kind means for the user:
483
+ [Errors and reliability](./errors-and-reliability.md).
484
+
485
+ Two failures are not a `GeminiRequestError`, and have no `kind`:
486
+
487
+ - an error thrown by your `accessToken` or `headers` function;
488
+ - the abort of your own `signal`, thrown as it came.
489
+
490
+ A reply of HTTP 200 whose body is not JSON, such as a gateway's HTML page, is a
491
+ `GeminiRequestError` of kind `"invalid"`, status 200, with the `SyntaxError` as `cause`: "Gemini's
492
+ reply could not be read: it was not JSON (text/html). A proxy or gateway may have answered in its
493
+ place." It is not sent again, streamed or not; until 0.6.0 it was the `SyntaxError` itself, and a
494
+ streamed request that got such a page came back as an empty reply. An empty body
495
+ of HTTP 200 is "Gemini could not be reached (the reply was empty).", status 0, and is sent again.
496
+ A reply asked for as a stream that comes under another content type than `text/event-stream` is
497
+ read by what it starts with: events, or one chunk or a list of chunks in JSON, as Gemini sends them
498
+ without `alt=sse`.
499
+
500
+ ### Quotas
501
+
502
+ | What Gemini or Vertex AI answers | `kind` | What the library does |
503
+ |---|---|---|
504
+ | HTTP 429 whose `details` hold a `google.rpc.QuotaFailure` with a quota per day (`PerDay` in its `quotaId` or `quotaMetric`) | `"quota"` | Throws at once: a wait does not mend it. |
505
+ | HTTP 429 whose message alone names a quota per day ("Quota exceeded for … requests_per_day_per_project …") | `"quota"` | The same. |
506
+ | Any other HTTP 429, a quota per minute among them | `"rate_limit"` | Sends it again, up to `retry.retries` times (3): after the wait the error names, or after a wait that doubles. |
507
+
508
+ The wait an error names is its `Retry-After` or `retry-after-ms` header, or the `retryDelay` of a
509
+ `google.rpc.RetryInfo` in its body. One longer than `retry.maxDelayMs` (60 s) is not waited for: the
510
+ error is thrown. Without a named wait, the defaults wait 0.25 to 0.5 s, then 0.5 to 1 s, then 1 to
511
+ 2 s: three and a half seconds at most, which a quota per minute can outlast. `onActivity` reports
512
+ each wait of a chat request ("The model did not answer (HTTP 429). Trying again in 2 s…"). The
513
+ waits of part reads are not told to `onActivity`; since 0.7.0, `onEvent` and `askStream` give every
514
+ wait, theirs included, as a `retry` event ([events](../reference/events.md#retry)).
515
+
516
+ A whole-file read is what reaches a quota per minute first: up to 30 part reads, four at a time,
517
+ each with the same rule. If your project hits its quota under load, wait longer:
518
+
519
+ ```ts
520
+ import { askGemini } from "llm-large-files/gemini";
521
+
522
+ // files, endpoint, documentIds and messages as in the askGemini sample above.
523
+ await askGemini({
524
+ files, endpoint, documentIds, messages,
525
+ retry: { retries: 5, baseDelayMs: 2_000 }, // about 1-2, 2-4, 4-8, 8-16 and 16-32 s
526
+ });
527
+ ```
528
+
529
+ When Vertex AI names a wait longer than 60 s (`Retry-After`, or `retryDelay` in its body), the
530
+ error is thrown at once. If your users can wait that long, raise `retry.maxDelayMs`, for example
531
+ `retry: { retries: 5, baseDelayMs: 2_000, maxDelayMs: 120_000 }`.
532
+
533
+ Longer waits also delay the error the user sees when the model is down. Raising the quota, or
534
+ moving the searching to an [explorer](#an-explorer-model) on another model, removes the cause.
535
+
536
+ ### A request too large
537
+
538
+ Vertex AI refuses a request larger than the model's window with HTTP 400 and its own words: "The
539
+ input token count exceeds the maximum number of tokens allowed 1048576." The Gemini API puts the
540
+ numbers in parentheses, and another Vertex AI wording reads "the input token count is N but model
541
+ only supports up to M". Each is `kind` `"context_overflow"`, with `limitTokens` (1,048,576 here) and,
542
+ when the message gives it, `requestedTokens`.
543
+
544
+ The loop then makes the request smaller, or plans the documents again, before it throws:
545
+ [Errors and reliability](./errors-and-reliability.md#a-request-too-large-for-the-model). Vertex
546
+ AI's message gives no count, so a plan made again is for 1,048,576 divided by 1.25: 838,860 tokens.
547
+ That holds while the budget assumes a larger window, as its default of 1,000,000 does; a window
548
+ that comes to no less than the one the budget assumed becomes 7/10 of that one. A refused output
549
+ limit ("…has a maxOutputTokens value of 5000000 but the maximum supported value is…") is `"invalid"`,
550
+ not an overflow.
551
+
552
+ ### Other errors
553
+
554
+ | What happened | `status` | `kind` | Sent again |
555
+ |---|---|---|---|
556
+ | The token was refused: expired, a missing role, the API not enabled | 401, 403 | `"auth"` | No |
557
+ | An API key of the Gemini API that is not valid (`API_KEY_INVALID`) | 400 | `"auth"` | No |
558
+ | A setting the model does not take, a model the location does not have, another refusal | 400, 404, and any other 4xx not in this table | `"invalid"` | No |
559
+ | The provider or a gateway timed out | 408 | `"timeout"` | Yes |
560
+ | A conflict | 409 | `"invalid"` | Yes |
561
+ | A gateway refused the body as too large | 413 | `"context_overflow"` | Made smaller, as in [A request too large](#a-request-too-large) |
562
+ | Gemini failed on its side | 5xx | `"server"` | Yes |
563
+ | Nothing came for `firstByteTimeoutMs` or `idleTimeoutMs` | 0 | `"timeout"` | Once |
564
+ | The connection failed, or a stream ended before its `finishReason` | 0 | `"unreachable"` | Yes, unless text was shown |
565
+ | A reply of HTTP 200 whose body is empty | 0 | `"unreachable"` | Yes |
566
+ | A reply of HTTP 200 whose body is not JSON (a gateway's page) | 200 | `"invalid"` | No |
567
+ | An event of a stream longer than 64,000,000 characters | 200 | `"invalid"` | No |
568
+
569
+ The message of the error is Google's own text, and can name your project, model and quotas. Log
570
+ it; show the user a message of your own, chosen by `kind`, as the [sample below](#a-production-setup)
571
+ does.
572
+
573
+ ## Gemini history stored as contents
574
+
575
+ `askGemini` takes plain turns and stored tool rounds in `messages`, or your own Gemini `contents`
576
+ (with images and inline PDFs) in `contents`; given both, `contents` is used. The last turn must be
577
+ the user's. Document text and cards are added at the start of the first user turn, and your array
578
+ is not changed. `fromGeminiContents(contents)` turns `contents` into `messages` for `askWithFiles`,
579
+ and `geminiToolTurns(result.toolTurns)` gives the tool rounds of a question as `contents`, to store
580
+ between the question and its answer:
581
+
582
+ ```ts
583
+ import { askGemini, geminiToolTurns, type GeminiContent } from "llm-large-files/gemini";
584
+
585
+ // files, endpoint and documentIds as in the askGemini sample above.
586
+ // The conversation as your application keeps it, with the new question as its last user turn.
587
+ const history: GeminiContent[] = [{ role: "user", parts: [{ text: "Why did the import fail at 02:00?" }] }];
588
+
589
+ const result = await askGemini({ files, endpoint, documentIds, contents: history });
590
+ history.push(...geminiToolTurns(result.toolTurns), ...(result.answered ? [{ role: "model" as const, parts: [{ text: result.text }] }] : []));
591
+ ```
592
+
593
+ Store no model turn for a question that was not answered
594
+ ([Conversations](./conversations.md#storing-a-conversation-and-asking-the-next-question)).
595
+
596
+ Rounds kept this way are sent as they are. Passed as `toolTurns` in `messages` instead, they stay
597
+ rounds the loop knows: a repeated call is answered with a pointer to its earlier result, and old
598
+ results can be shortened when room runs short. What to store and how to keep a conversation inside
599
+ the window: [Conversations](./conversations.md).
600
+
601
+ ## A production setup
602
+
603
+ Vertex AI with application default credentials, an explorer, the answer streamed, limits on the
604
+ question, and errors told apart by `kind`. `answer()` is called by your HTTP route, with a `send`
605
+ that writes events to the browser ([Web app](./web-app.md)).
606
+
607
+ ```ts
608
+ import { GoogleAuth } from "google-auth-library";
609
+ import {
610
+ createLargeFiles,
611
+ DocumentsNotFoundError,
612
+ errorKindOf,
613
+ FileDocumentStore,
614
+ partialResultOf,
615
+ type AskResult,
616
+ type ChatTurn,
617
+ type ToolTurn,
618
+ } from "llm-large-files";
619
+ import { askGemini, vertexAi } from "llm-large-files/gemini";
620
+
621
+ const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
622
+
623
+ async function accessToken(): Promise<string> {
624
+ const token = await auth.getAccessToken();
625
+ if (!token) throw new Error("No access token from the application default credentials.");
626
+ return token;
627
+ }
628
+
629
+ export const files = createLargeFiles({
630
+ store: new FileDocumentStore(process.env.DOCUMENTS_DIR ?? "./data/large-files"),
631
+ // askGemini cannot declare a model's window: the budget does. The default (1,000,000 tokens,
632
+ // 10 MB a request) fits a model of 1,048,576 tokens; set it for a smaller one.
633
+ });
634
+
635
+ const endpoint = vertexAi({
636
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
637
+ location: process.env.VERTEX_LOCATION ?? "global",
638
+ model: process.env.GEMINI_MODEL ?? "gemini-3.8-flash", // writes the answer
639
+ explorerModel: process.env.GEMINI_EXPLORER_MODEL, // searches and reads; unset: one model does both
640
+ accessToken, // called before every request
641
+ });
642
+
643
+ export type Send = (event: "text" | "activity" | "step" | "done" | "error", data: unknown) => void;
644
+
645
+ export async function answer(question: {
646
+ userId: string;
647
+ documentIds: string[];
648
+ /** The conversation, with stored tool rounds, and the new question last. */
649
+ messages: Array<ChatTurn | ToolTurn>;
650
+ send: Send;
651
+ /** Aborted when the browser goes away. */
652
+ signal: AbortSignal;
653
+ }): Promise<AskResult | undefined> {
654
+ // A question has no deadline of its own: keep this above firstByteTimeoutMs (10 minutes).
655
+ const signal = AbortSignal.any([question.signal, AbortSignal.timeout(15 * 60_000)]);
656
+ try {
657
+ const result = await askGemini({
658
+ files,
659
+ endpoint,
660
+ documentIds: question.documentIds,
661
+ messages: question.messages,
662
+ owner: question.userId,
663
+ system: "You are our support assistant. Cite the lines you used.",
664
+ generationConfig: { temperature: 0.3, thinkingConfig: { thinkingLevel: "high" } }, // the answering model
665
+ explorerGenerationConfig: { temperature: 0.2 }, // the explorer
666
+ limits: { toolTurns: 12, inputTokens: 2_000_000, requests: 40 },
667
+ retry: { retries: 5, baseDelayMs: 2_000 },
668
+ signal,
669
+ onText: (delta) => question.send("text", delta),
670
+ onActivity: (text) => question.send("activity", text),
671
+ onStep: (text) => question.send("step", text),
672
+ });
673
+ question.send("done", { answered: result.answered });
674
+ return result; // store result.toolTurns and result.usage with the conversation
675
+ } catch (error) {
676
+ // What the question found and paid for before it failed: store its toolTurns and usage too.
677
+ const partial = partialResultOf(error);
678
+ console.error("question failed", errorKindOf(error), error);
679
+ if (!question.signal.aborted) {
680
+ question.send("error", signal.aborted ? "The answer took too long. Please try again." : messageFor(error));
681
+ }
682
+ return partial;
683
+ }
684
+ }
685
+
686
+ function messageFor(error: unknown): string {
687
+ if (error instanceof DocumentsNotFoundError) return "A file has expired or was removed. Please attach it again.";
688
+ switch (errorKindOf(error)) {
689
+ case "rate_limit":
690
+ return "The assistant is busy. Please try again in a minute.";
691
+ case "quota":
692
+ return "The assistant has reached its limit for today. Please try again tomorrow.";
693
+ case "context_overflow":
694
+ return "This conversation is too long for the model. Please start a new chat.";
695
+ case "timeout":
696
+ case "unreachable":
697
+ case "server":
698
+ return "The model did not answer. Please try again.";
699
+ default: // "auth", "invalid", and errors without a kind: a setup problem, in your logs
700
+ return "Something went wrong on our side. Please try again later.";
701
+ }
702
+ }
703
+ ```
704
+
705
+ - `result.answered` is `false` when the last turn had no text (a blocked prompt, a reply stopped by
706
+ the output limit or a filter before it wrote anything, or an answer with no text, empty or a
707
+ tool call such as `UNEXPECTED_TOOL_CALL`, even after it was asked for once more): show your own
708
+ message then. A reply cut off after some text is `answered: true`, with `finishReason`
709
+ `"MAX_TOKENS"`. With an explorer, `text` and `onText` carry only the answering model's words.
710
+ - Steps and activity lines are one line of plain text each, and still quote the model's words:
711
+ show them as text in the browser, never as HTML or markdown.
712
+ - `limits.inputTokens` and `limits.requests` are ceilings on the whole question, part reads
713
+ included: once one is reached no more tools run and the next request is the answer.
714
+ - `owner` scopes the documents to the user: a document of another owner is reported missing
715
+ ([Security](../security.md)).
716
+ - For tests, pass `fetch` to `askGemini` or `gemini()`, or use a fake adapter:
717
+ [Testing](./testing.md).