llm-large-files 0.5.0 → 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 (221) hide show
  1. package/CHANGELOG.md +1402 -467
  2. package/README.md +188 -60
  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 +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +190 -39
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +60 -4
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1068 -206
  14. package/dist/ask.js.map +1 -1
  15. package/dist/encoding.d.ts +17 -0
  16. package/dist/encoding.d.ts.map +1 -0
  17. package/dist/encoding.js +852 -0
  18. package/dist/encoding.js.map +1 -0
  19. package/dist/errors.d.ts +4 -0
  20. package/dist/errors.d.ts.map +1 -1
  21. package/dist/errors.js +15 -0
  22. package/dist/errors.js.map +1 -1
  23. package/dist/events.d.ts +333 -0
  24. package/dist/events.d.ts.map +1 -0
  25. package/dist/events.js +159 -0
  26. package/dist/events.js.map +1 -0
  27. package/dist/evidence.d.ts +2 -0
  28. package/dist/evidence.d.ts.map +1 -1
  29. package/dist/evidence.js +3 -2
  30. package/dist/evidence.js.map +1 -1
  31. package/dist/extract.d.ts +35 -3
  32. package/dist/extract.d.ts.map +1 -1
  33. package/dist/extract.js +626 -58
  34. package/dist/extract.js.map +1 -1
  35. package/dist/gemini/adapter.d.ts +17 -8
  36. package/dist/gemini/adapter.d.ts.map +1 -1
  37. package/dist/gemini/adapter.js +108 -61
  38. package/dist/gemini/adapter.js.map +1 -1
  39. package/dist/gemini/chat.d.ts +23 -3
  40. package/dist/gemini/chat.d.ts.map +1 -1
  41. package/dist/gemini/chat.js +6 -2
  42. package/dist/gemini/chat.js.map +1 -1
  43. package/dist/gemini/errors.d.ts +9 -4
  44. package/dist/gemini/errors.d.ts.map +1 -1
  45. package/dist/gemini/errors.js +32 -0
  46. package/dist/gemini/errors.js.map +1 -1
  47. package/dist/gemini/generate.d.ts +10 -2
  48. package/dist/gemini/generate.d.ts.map +1 -1
  49. package/dist/gemini/generate.js +13 -7
  50. package/dist/gemini/generate.js.map +1 -1
  51. package/dist/gemini/index.d.ts +3 -3
  52. package/dist/gemini/index.d.ts.map +1 -1
  53. package/dist/gemini/index.js +2 -2
  54. package/dist/gemini/index.js.map +1 -1
  55. package/dist/gemini/sse.d.ts +1 -1
  56. package/dist/gemini/sse.d.ts.map +1 -1
  57. package/dist/gemini/sse.js +1 -1
  58. package/dist/gemini/sse.js.map +1 -1
  59. package/dist/http.d.ts +116 -0
  60. package/dist/http.d.ts.map +1 -1
  61. package/dist/http.js +347 -1
  62. package/dist/http.js.map +1 -1
  63. package/dist/index.d.ts +11 -6
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +6 -4
  66. package/dist/index.js.map +1 -1
  67. package/dist/library.d.ts +67 -5
  68. package/dist/library.d.ts.map +1 -1
  69. package/dist/library.js +405 -85
  70. package/dist/library.js.map +1 -1
  71. package/dist/map-reduce.d.ts +28 -1
  72. package/dist/map-reduce.d.ts.map +1 -1
  73. package/dist/map-reduce.js +240 -52
  74. package/dist/map-reduce.js.map +1 -1
  75. package/dist/model.d.ts +84 -2
  76. package/dist/model.d.ts.map +1 -1
  77. package/dist/model.js +182 -1
  78. package/dist/model.js.map +1 -1
  79. package/dist/node/handlers.d.ts +20 -4
  80. package/dist/node/handlers.d.ts.map +1 -1
  81. package/dist/node/handlers.js +122 -20
  82. package/dist/node/handlers.js.map +1 -1
  83. package/dist/node/index.d.ts +2 -0
  84. package/dist/node/index.d.ts.map +1 -1
  85. package/dist/node/index.js +1 -0
  86. package/dist/node/index.js.map +1 -1
  87. package/dist/node/sse.d.ts +59 -0
  88. package/dist/node/sse.d.ts.map +1 -0
  89. package/dist/node/sse.js +174 -0
  90. package/dist/node/sse.js.map +1 -0
  91. package/dist/openai/adapter.d.ts +29 -5
  92. package/dist/openai/adapter.d.ts.map +1 -1
  93. package/dist/openai/adapter.js +311 -37
  94. package/dist/openai/adapter.js.map +1 -1
  95. package/dist/output-limit.d.ts +14 -2
  96. package/dist/output-limit.d.ts.map +1 -1
  97. package/dist/output-limit.js +39 -10
  98. package/dist/output-limit.js.map +1 -1
  99. package/dist/pause.d.ts +24 -0
  100. package/dist/pause.d.ts.map +1 -0
  101. package/dist/pause.js +38 -0
  102. package/dist/pause.js.map +1 -0
  103. package/dist/pdf-pages.d.ts +32 -2
  104. package/dist/pdf-pages.d.ts.map +1 -1
  105. package/dist/pdf-pages.js +275 -14
  106. package/dist/pdf-pages.js.map +1 -1
  107. package/dist/pdf-pictures.d.ts +30 -3
  108. package/dist/pdf-pictures.d.ts.map +1 -1
  109. package/dist/pdf-pictures.js +50 -8
  110. package/dist/pdf-pictures.js.map +1 -1
  111. package/dist/pdf-work.d.ts +40 -0
  112. package/dist/pdf-work.d.ts.map +1 -0
  113. package/dist/pdf-work.js +734 -0
  114. package/dist/pdf-work.js.map +1 -0
  115. package/dist/plan.d.ts +22 -4
  116. package/dist/plan.d.ts.map +1 -1
  117. package/dist/plan.js +61 -12
  118. package/dist/plan.js.map +1 -1
  119. package/dist/retry.d.ts +23 -1
  120. package/dist/retry.d.ts.map +1 -1
  121. package/dist/retry.js +33 -3
  122. package/dist/retry.js.map +1 -1
  123. package/dist/search.d.ts +8 -2
  124. package/dist/search.d.ts.map +1 -1
  125. package/dist/search.js +60 -10
  126. package/dist/search.js.map +1 -1
  127. package/dist/sse.d.ts +35 -2
  128. package/dist/sse.d.ts.map +1 -1
  129. package/dist/sse.js +145 -31
  130. package/dist/sse.js.map +1 -1
  131. package/dist/stores.d.ts.map +1 -1
  132. package/dist/stores.js +5 -2
  133. package/dist/stores.js.map +1 -1
  134. package/dist/text-index.d.ts +6 -0
  135. package/dist/text-index.d.ts.map +1 -1
  136. package/dist/text-index.js +25 -8
  137. package/dist/text-index.js.map +1 -1
  138. package/dist/text.d.ts +62 -2
  139. package/dist/text.d.ts.map +1 -1
  140. package/dist/text.js +314 -14
  141. package/dist/text.js.map +1 -1
  142. package/dist/tools.d.ts +61 -1
  143. package/dist/tools.d.ts.map +1 -1
  144. package/dist/tools.js +269 -42
  145. package/dist/tools.js.map +1 -1
  146. package/dist/types.d.ts +102 -3
  147. package/dist/types.d.ts.map +1 -1
  148. package/dist/zip-directory.d.ts +43 -0
  149. package/dist/zip-directory.d.ts.map +1 -0
  150. package/dist/zip-directory.js +130 -0
  151. package/dist/zip-directory.js.map +1 -0
  152. package/docs/README.md +288 -0
  153. package/docs/api.md +37 -381
  154. package/docs/configuration.md +28 -558
  155. package/docs/getting-started.md +407 -223
  156. package/docs/guides/anthropic.md +590 -0
  157. package/docs/guides/conversations.md +629 -0
  158. package/docs/guides/costs-and-limits.md +726 -0
  159. package/docs/guides/deployment.md +654 -0
  160. package/docs/guides/errors-and-reliability.md +735 -0
  161. package/docs/guides/explorer-model.md +399 -0
  162. package/docs/guides/openai-compatible.md +602 -0
  163. package/docs/guides/own-adapter-and-loop.md +1169 -0
  164. package/docs/guides/pdfs.md +971 -0
  165. package/docs/guides/storage.md +731 -0
  166. package/docs/guides/testing.md +1199 -0
  167. package/docs/guides/vertex-and-gemini.md +717 -0
  168. package/docs/guides/web-app.md +1589 -0
  169. package/docs/how-it-works.md +1012 -164
  170. package/docs/measurements.md +881 -0
  171. package/docs/publishing.md +274 -46
  172. package/docs/reference/anthropic.md +427 -0
  173. package/docs/reference/ask.md +892 -0
  174. package/docs/reference/errors-and-retries.md +758 -0
  175. package/docs/reference/events.md +993 -0
  176. package/docs/reference/gemini.md +823 -0
  177. package/docs/reference/library.md +1467 -0
  178. package/docs/reference/node.md +528 -0
  179. package/docs/reference/openai.md +385 -0
  180. package/docs/reference/tools.md +883 -0
  181. package/docs/security.md +897 -103
  182. package/docs/troubleshooting.md +1390 -0
  183. package/package.json +2 -2
  184. package/src/analyze.ts +93 -42
  185. package/src/anthropic/adapter.ts +196 -39
  186. package/src/ask.ts +1087 -202
  187. package/src/encoding.ts +850 -0
  188. package/src/errors.ts +17 -0
  189. package/src/events.ts +442 -0
  190. package/src/evidence.ts +5 -2
  191. package/src/extract.ts +602 -62
  192. package/src/gemini/adapter.ts +118 -65
  193. package/src/gemini/chat.ts +28 -4
  194. package/src/gemini/errors.ts +34 -1
  195. package/src/gemini/generate.ts +23 -10
  196. package/src/gemini/index.ts +3 -3
  197. package/src/gemini/sse.ts +1 -1
  198. package/src/http.ts +376 -1
  199. package/src/index.ts +27 -5
  200. package/src/library.ts +459 -85
  201. package/src/map-reduce.ts +252 -51
  202. package/src/model.ts +236 -3
  203. package/src/node/handlers.ts +137 -22
  204. package/src/node/index.ts +2 -0
  205. package/src/node/sse.ts +198 -0
  206. package/src/openai/adapter.ts +306 -38
  207. package/src/output-limit.ts +44 -8
  208. package/src/pause.ts +41 -0
  209. package/src/pdf-pages.ts +268 -15
  210. package/src/pdf-pictures.ts +56 -9
  211. package/src/pdf-work.ts +722 -0
  212. package/src/plan.ts +68 -12
  213. package/src/retry.ts +49 -5
  214. package/src/search.ts +63 -10
  215. package/src/sse.ts +153 -28
  216. package/src/stores.ts +5 -2
  217. package/src/text-index.ts +26 -7
  218. package/src/text.ts +323 -13
  219. package/src/tools.ts +261 -42
  220. package/src/types.ts +107 -4
  221. package/src/zip-directory.ts +136 -0
@@ -0,0 +1,823 @@
1
+ # `llm-large-files/gemini`
2
+
3
+ This page lists every export of `llm-large-files/gemini` with its options, defaults, return values
4
+ and errors. The entry point covers Gemini on the Gemini API and on Vertex AI: the endpoints,
5
+ `askGemini`, the `gemini()` adapter for `askWithFiles`, converters for Gemini `contents`, and the
6
+ helpers for a tool loop of your own. How to set Gemini up for production is in the guide
7
+ [Gemini API and Vertex AI](../guides/vertex-and-gemini.md).
8
+
9
+ ```ts
10
+ import { askGemini, gemini, geminiApi, vertexAi } from "llm-large-files/gemini";
11
+ import type { AskGeminiOptions, GeminiContent, GeminiEndpoint, GeminiModelOptions } from "llm-large-files/gemini";
12
+ ```
13
+
14
+ The entry point needs no Google SDK: it posts to the Generate Content REST API with `fetch`.
15
+
16
+ ## Contents
17
+
18
+ - [Endpoints](#endpoints): [`geminiApi()`](#geminiapioptions), [`vertexAi()`](#vertexaioptions),
19
+ [`vertexHost()`](#vertexhostlocation), [`GeminiEndpoint`](#geminiendpoint)
20
+ - [Asking a question](#asking-a-question): [`askGemini()`](#askgeminioptions),
21
+ [`AskGeminiOptions`](#askgeminioptions-1), [`AskGeminiResult`](#askgeminiresult)
22
+ - [The model adapter](#the-model-adapter): [`gemini()`](#geminiendpoint-options),
23
+ [`GeminiModelOptions`](#geminimodeloptions), [`GEMINI_PAGE_TOKENS`](#gemini_page_tokens)
24
+ - [Gemini contents](#gemini-contents): [`fromGeminiContents()`](#fromgeminicontentscontents),
25
+ [`geminiToolTurns()`](#geminitoolturnsturns), [`GeminiContent`](#geminicontent),
26
+ [`GeminiPart`](#geminipart)
27
+ - [Helpers for your own loop](#helpers-for-your-own-loop):
28
+ [`createGeminiGenerateText()`](#creategeminigeneratetextoptions),
29
+ [`THINKING_OUTPUT_TOKENS`](#thinking_output_tokens), [`toGeminiTools()`](#togeminitoolsdeclarations),
30
+ [`geminiFunctionResponses()`](#geminifunctionresponsescalls),
31
+ [`geminiFunctionResponseTurns()`](#geminifunctionresponseturnscalls-options),
32
+ [`GeminiFunctionCall`](#geminifunctioncall), [`GeminiToolAnswer`](#geminitoolanswer),
33
+ [`GeminiToolFilePlacement`](#geminitoolfileplacement), [`usageOfGemini()`](#usageofgeminiusage)
34
+ - [Errors](#errors): [`GeminiRequestError`](#geminirequesterror)
35
+ - [Re-exports of the main entry](#re-exports-of-the-main-entry): `DocumentsNotFoundError`,
36
+ `partialResultOf`, `EXPLORER_INSTRUCTION`, `FINAL_ANSWER_REQUEST`, `FINAL_ANSWER_AFTER_PAGES`,
37
+ `FINAL_ANSWER_WITHOUT_TOOLS`, `parseSseJson`, `ChatTurn`, `AskEvent`
38
+
39
+ ## Endpoints
40
+
41
+ A `GeminiEndpoint` says where a Gemini model is and how to sign in to it. `geminiApi()` and
42
+ `vertexAi()` build one. For an enterprise gateway, write one yourself.
43
+
44
+ ### geminiApi(options)
45
+
46
+ ```ts
47
+ declare function geminiApi(options: {
48
+ apiKey: string;
49
+ model: string;
50
+ explorerModel?: string | undefined;
51
+ apiVersion?: string;
52
+ baseUrl?: string;
53
+ }): GeminiEndpoint;
54
+ ```
55
+
56
+ The endpoint of a model on the Gemini Developer API, signed in with an API key.
57
+
58
+ | Option | Type | Default | What it does |
59
+ |---|---|---|---|
60
+ | `apiKey` | `string` | required | Sent in the `x-goog-api-key` header of every request, not in the URL. |
61
+ | `model` | `string` | required | The model that answers, such as `"gemini-3.8-flash"`. Without an explorer it also makes the tool calls. URL-encoded into the path. |
62
+ | `explorerModel` | `string \| undefined` | none | A second model that explores the documents: it makes the tool calls and reads whole files in parts, and `model` writes the answer. The name is trimmed. `undefined`, an empty string, only spaces, or the name of `model` mean no explorer, so an unset environment variable can be passed as it is. |
63
+ | `apiVersion` | `string` | `"v1beta"` | The version segment of the path. |
64
+ | `baseUrl` | `string` | `"https://generativelanguage.googleapis.com"` | The host, for a proxy that keeps the Gemini API's paths. Trailing slashes are removed. |
65
+
66
+ It returns:
67
+
68
+ | Field | Value |
69
+ |---|---|
70
+ | `url` | `{baseUrl}/{apiVersion}/models/{model}:generateContent` |
71
+ | `streamUrl` | `{baseUrl}/{apiVersion}/models/{model}:streamGenerateContent?alt=sse` |
72
+ | `headers` | The object `{ "Content-Type": "application/json", "x-goog-api-key": apiKey }` |
73
+ | `explorerUrl` | `{baseUrl}/{apiVersion}/models/{explorerModel}:generateContent`, only when an explorer is named. Otherwise the field is absent. |
74
+
75
+ It makes no request and throws nothing.
76
+
77
+ ```ts
78
+ import { geminiApi } from "llm-large-files/gemini";
79
+
80
+ const endpoint = geminiApi({
81
+ apiKey: process.env.GEMINI_API_KEY!,
82
+ model: "gemini-3.8-flash",
83
+ explorerModel: process.env.GEMINI_EXPLORER_MODEL, // unset or empty: one model does both
84
+ });
85
+ // endpoint.url: https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent
86
+ // endpoint.streamUrl: https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse
87
+ ```
88
+
89
+ Guides: [Gemini API and Vertex AI](../guides/vertex-and-gemini.md),
90
+ [an explorer model](../guides/explorer-model.md).
91
+
92
+ ### vertexAi(options)
93
+
94
+ ```ts
95
+ declare function vertexAi(options: {
96
+ project: string;
97
+ model: string;
98
+ explorerModel?: string | undefined;
99
+ location?: string;
100
+ accessToken: string | (() => string | Promise<string>);
101
+ apiVersion?: string;
102
+ }): GeminiEndpoint;
103
+ ```
104
+
105
+ The endpoint of a Gemini model on Vertex AI, signed in with an OAuth access token.
106
+
107
+ | Option | Type | Default | What it does |
108
+ |---|---|---|---|
109
+ | `project` | `string` | required | The Google Cloud project ID. URL-encoded into the path. |
110
+ | `model` | `string` | required | The model that answers, under `publishers/google/models/`. Without an explorer it also makes the tool calls. |
111
+ | `explorerModel` | `string \| undefined` | none | A second model that explores the documents, with the same rules as in [`geminiApi()`](#geminiapioptions). It is in the same project and location. |
112
+ | `location` | `string` | `"global"` | Where the requests are served. It picks the host ([`vertexHost()`](#vertexhostlocation)) and is the `locations/{location}` segment of the path, as given. |
113
+ | `accessToken` | `string \| (() => string \| Promise<string>)` | required | Sent as `Authorization: Bearer {token}`. A function is called before every request, chat requests and part reads of both models alike, so it can return a renewed token. |
114
+ | `apiVersion` | `string` | `"v1"` | The version segment of the path. |
115
+
116
+ It returns:
117
+
118
+ | Field | Value |
119
+ |---|---|
120
+ | `url` | `{vertexHost(location)}/{apiVersion}/projects/{project}/locations/{location}/publishers/google/models/{model}:generateContent` |
121
+ | `streamUrl` | The same, ending in `:streamGenerateContent?alt=sse` |
122
+ | `headers` | An async function that returns `{ "Content-Type": "application/json", Authorization: "Bearer {token}" }` |
123
+ | `explorerUrl` | The `:generateContent` URL of `explorerModel`, only when an explorer is named. Otherwise the field is absent. |
124
+
125
+ It makes no request and does not call `accessToken`. An error that the token function throws comes
126
+ out of the request that needed the token, as it was thrown: it is not a `GeminiRequestError`. It
127
+ has no status, so a chat request is not sent again: `askGemini`, or `askWithFiles` with `gemini()`,
128
+ throws it. A part read is tried once more, and then counts as unread.
129
+
130
+ ```ts
131
+ import { GoogleAuth } from "google-auth-library";
132
+ import { vertexAi } from "llm-large-files/gemini";
133
+
134
+ const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
135
+
136
+ const endpoint = vertexAi({
137
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
138
+ location: "global",
139
+ model: "gemini-3.8-flash",
140
+ explorerModel: "gemini-3.5-flash-lite",
141
+ accessToken: async () => (await auth.getAccessToken()) ?? "",
142
+ });
143
+ ```
144
+
145
+ Guide: [Gemini API and Vertex AI](../guides/vertex-and-gemini.md), which covers access tokens.
146
+
147
+ ### vertexHost(location)
148
+
149
+ ```ts
150
+ declare function vertexHost(location: string): string;
151
+ ```
152
+
153
+ The Vertex AI host of a location, as `vertexAi()` uses it. The location is not checked.
154
+
155
+ | `location` | Host |
156
+ |---|---|
157
+ | `"global"` | `https://aiplatform.googleapis.com` |
158
+ | `"us"`, `"eu"` | `https://aiplatform.us.rep.googleapis.com`, `https://aiplatform.eu.rep.googleapis.com` |
159
+ | Any other, such as `"europe-west4"` | `https://europe-west4-aiplatform.googleapis.com` |
160
+
161
+ Use it to build the URLs of a [`GeminiEndpoint`](#geminiendpoint) of your own on Vertex AI.
162
+
163
+ ### `GeminiEndpoint`
164
+
165
+ ```ts
166
+ type GeminiEndpoint = {
167
+ url: string;
168
+ streamUrl?: string;
169
+ headers: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
170
+ explorerUrl?: string | undefined;
171
+ };
172
+ ```
173
+
174
+ Where a Gemini model is and how to call it.
175
+
176
+ | Field | Type | Default | What it does |
177
+ |---|---|---|---|
178
+ | `url` | `string` | required | The non-streaming `...:generateContent` URL. Chat requests made without `onText`, and the part reads of a whole-file read when there is no explorer, go here. |
179
+ | `streamUrl` | `string` | none | The streaming `...:streamGenerateContent?alt=sse` URL, used for a chat request when `onText` is given. Without it each reply arrives whole, and `onText` gets its text once it has arrived. |
180
+ | `headers` | `Record<string, string>` or a function that returns them | required | Sent with every request as they are. A function is called before every request, so a renewed token is used. `gemini()` adds no header of its own: give `"Content-Type": "application/json"`, as `geminiApi()` and `vertexAi()` do. |
181
+ | `explorerUrl` | `string \| undefined` | none | The `...:generateContent` URL of an explorer model, called with the same `headers` and never streamed. Only `askGemini` reads it, and only when it differs from `url`. With `askGemini` it receives the explorer's chat requests and the part reads of whole-file reads. `gemini()` ignores it. |
182
+
183
+ An endpoint for a gateway that proxies Generate Content:
184
+
185
+ ```ts
186
+ import type { GeminiEndpoint } from "llm-large-files/gemini";
187
+
188
+ const models = "https://llm-gateway.example.com/gemini/models";
189
+
190
+ const gateway: GeminiEndpoint = {
191
+ url: `${models}/gemini-3.8-flash:generateContent`,
192
+ streamUrl: `${models}/gemini-3.8-flash:streamGenerateContent?alt=sse`,
193
+ headers: async () => ({
194
+ "Content-Type": "application/json",
195
+ Authorization: `Bearer ${process.env.GATEWAY_TOKEN}`,
196
+ }),
197
+ explorerUrl: `${models}/gemini-3.5-flash-lite:generateContent`, // optional
198
+ };
199
+ ```
200
+
201
+ Guide: [Gemini API and Vertex AI](../guides/vertex-and-gemini.md), which has a section on gateways.
202
+
203
+ ## Asking a question
204
+
205
+ ### askGemini(options)
206
+
207
+ ```ts
208
+ declare function askGemini(options: AskGeminiOptions): Promise<AskGeminiResult>;
209
+ ```
210
+
211
+ [`askWithFiles`](./ask.md#askwithfilesoptions) with Gemini models built for you. It makes
212
+ `gemini(endpoint, …)` the model that answers. When `endpoint.explorerUrl` is set and differs from
213
+ `endpoint.url`, it makes a second `gemini()` on that URL the explorer, with the same headers and no
214
+ stream. Documents that fit go into the prompt whole. A document too large for that, or a PDF whose
215
+ pages can be looked at, is reached through tools. When the tool loop ends without an answer in text
216
+ (out of turns or of room, a reply with no text, or always with an explorer), a last request without
217
+ tools asks for it. When that reply has no text (it is empty, or ends with `UNEXPECTED_TOOL_CALL` or
218
+ `MALFORMED_FUNCTION_CALL`), it is asked for once more. `answered` is false when there is still no
219
+ text: a blocked prompt, which gets no last request, or an empty or cut-off reply.
220
+
221
+ `askGemini` cannot set `contextTokens`, `maxRequestBytes`, `pageTokens` or `id` on its models. Put
222
+ the model's window in the library's budget, or use `askWithFiles` with
223
+ [`gemini()`](#geminiendpoint-options), which also takes an explorer of another provider or on
224
+ another endpoint.
225
+
226
+ **Returns** an [`AskGeminiResult`](#askgeminiresult).
227
+
228
+ **Throws** what `askWithFiles` throws ([ask reference](./ask.md)). Among them:
229
+
230
+ - `DocumentsNotFoundError`, before any model request, when a document ID was never uploaded, has
231
+ expired, or belongs to another `owner`.
232
+ - `Error("The last message must be the user's.")`, when the last turn of `messages` or `contents`
233
+ is not the user's, or when both are left out.
234
+ - `DocumentStoreError`, when the store could not be read.
235
+ - [`GeminiRequestError`](#geminirequesterror), for a chat request that Gemini did not answer, after
236
+ the retries. An explorer that fails throws it too. `partialResultOf(error)` gives what the
237
+ question found until then. A part read of a whole-file read that fails is not thrown: the tool
238
+ reports it to the model.
239
+ - The error of an `accessToken` function, as it was thrown, when a chat request needed the token
240
+ ([`vertexAi()`](#vertexaioptions)).
241
+ - The reason of `signal`, when it aborts.
242
+
243
+ ```ts
244
+ import { askGemini } from "llm-large-files/gemini";
245
+
246
+ // files (from createLargeFiles), endpoint (from vertexAi() above), userId and documentId
247
+ // come from your application.
248
+ const result = await askGemini({
249
+ files,
250
+ endpoint,
251
+ owner: userId,
252
+ documentIds: [documentId],
253
+ messages: [{ role: "user", text: "Why did the nightly import fail?" }],
254
+ onText: (delta) => process.stdout.write(delta),
255
+ });
256
+ if (!result.answered) console.log("No answer this time.");
257
+ console.log(result.usage.byModel); // one entry for each model, keyed by the model name in its URL
258
+ ```
259
+
260
+ Guide: [Gemini API and Vertex AI](../guides/vertex-and-gemini.md).
261
+
262
+ ### `AskGeminiOptions`
263
+
264
+ The options of `askGemini`. `AskOptions.model` and `AskOptions.explorer` are not here: `endpoint`
265
+ takes their place.
266
+
267
+ Shared with [`AskOptions`](./ask.md#askoptions), with the same meaning and defaults: `files`,
268
+ `documentIds`, `documentPlacement`, `system`, `owner`, `limits`, `retry`, `budget`,
269
+ `wholeDocumentAnalysis`, `viewPages`, `onText`, `onActivity`, `onStep`, `signal`, and, new in 0.7.0,
270
+ `streamText`, `onEvent`, `runId` and `eventResults` (see [events](./events.md)). With Gemini:
271
+
272
+ - `messages` is optional and typed `Array<ChatTurn | ToolTurn>`: plain turns and the `toolTurns`
273
+ of earlier questions. Turns with native parts (images, inline PDFs, thought signatures) go in
274
+ `contents` instead. Give `messages` or `contents`: with neither, the question throws "The last
275
+ message must be the user's."
276
+ - `onText` streams only when the endpoint has a `streamUrl`. Without one, it gets the text of each
277
+ reply once the reply has arrived. The same holds for `streamText` (on by default with `onText`):
278
+ it asks for the answer as it is written only from an endpoint with a `streamUrl`.
279
+ - `limits` is merged with `maxToolTurns` and `maxToolCallsPerTurn` (below). A field of `limits`
280
+ wins.
281
+
282
+ Fields `askGemini` adds:
283
+
284
+ | Field | Type | Default | What it does |
285
+ |---|---|---|---|
286
+ | `endpoint` | [`GeminiEndpoint`](#geminiendpoint) | required | The model that answers, and the explorer when `explorerUrl` is set and differs from `url`. |
287
+ | `contents` | [`GeminiContent[]`](#geminicontent) | none | The conversation as Gemini `contents`, with images, inline PDFs or function calls. Converted with [`fromGeminiContents()`](#fromgeminicontentscontents). It wins over `messages` when both are given. The array is not changed. The last turn must be the user's. |
288
+ | `generationConfig` | `Record<string, unknown>` | none | Sent as `generationConfig` with every chat request of the answering model, and of the explorer unless `explorerGenerationConfig` is set: `temperature`, `maxOutputTokens`, `thinkingConfig` and so on. Not used for part reads. |
289
+ | `explorerGenerationConfig` | `Record<string, unknown>` | `generationConfig` | The same, for the explorer's chat requests, when the two models do not take the same settings. Not used without an explorer. |
290
+ | `toolFilePlacement` | [`GeminiToolFilePlacement`](#geminitoolfileplacement) | `"inside"` | Where the pages of `view_pages` go, for both models. `"beside"` for Gemini 2.5. |
291
+ | `analysisConfig` | `(maxOutputTokens: number) => Record<string, unknown>` | `{ maxOutputTokens }` | The `generationConfig` of the part reads of a whole-file read, for both models. The explorer reads the parts when there is one, so write it for that model. Put the limit it is given in `maxOutputTokens`: a second try raises it to [`THINKING_OUTPUT_TOKENS`](#thinking_output_tokens). The default sends no temperature since 0.6.0 (it was `temperature: 0.2`): Gemini 3.6 and later ignore it, and Google says later models will refuse it. For an older model that should keep it: `(maxOutputTokens) => ({ maxOutputTokens, temperature: 0.2 })`. |
292
+ | `firstByteTimeoutMs` | `number` | `600_000` | The longest wait for the first piece of a chat reply, for both models. See [`GeminiModelOptions`](#geminimodeloptions). 0 waits without end. |
293
+ | `idleTimeoutMs` | `number` | `300_000` | The longest wait between two pieces of a chat reply, for both models. 0 waits without end. |
294
+ | `maxToolTurns` | `number` | 12 | `limits.toolTurns`, under the name it had before 0.5.0. `limits.toolTurns` wins when both are set. |
295
+ | `maxToolCallsPerTurn` | `number` | 8 | `limits.callsPerTurn`, under the name it had before 0.5.0. `limits.callsPerTurn` wins when both are set. |
296
+ | `fetch` | `typeof fetch` | the global `fetch` | Used for every request of both models, part reads included: a proxy, logging, tests. |
297
+
298
+ `askGemini` has no stream form of its own. To read its events with `for await`, as
299
+ [`askStream`](./ask.md#askstreamoptions) gives them for `askWithFiles`, wrap it in
300
+ [`eventStream`](./events.md#eventstreamrun-options) from `llm-large-files`: it passes the listener
301
+ and a signal, and leaving the loop early stops the question.
302
+
303
+ ```ts
304
+ import { eventStream } from "llm-large-files";
305
+ import { askGemini, type AskEvent, type AskGeminiOptions, type AskGeminiResult } from "llm-large-files/gemini";
306
+
307
+ // options are those of askGemini, with your endpoint, files and messages.
308
+ export async function showGeminiQuestion(options: AskGeminiOptions): Promise<AskGeminiResult | undefined> {
309
+ const stream = eventStream<AskEvent, AskGeminiResult>(
310
+ (onEvent, signal) => askGemini({ ...options, onEvent, signal, streamText: options.streamText !== false }),
311
+ { signal: options.signal },
312
+ );
313
+ for await (const event of stream) {
314
+ if (event.type === "request.start") console.error(`${event.role} request ${event.requestId} to ${event.model}`);
315
+ if (event.type === "tool.end") console.error(event.step ?? `${event.callId}: ${event.outcome}`);
316
+ if (event.type === "text") process.stdout.write(event.delta);
317
+ if (event.type === "run.error") console.error(event.error.message);
318
+ }
319
+ return stream.result.catch(() => undefined);
320
+ }
321
+ ```
322
+
323
+ With an explorer, `run.start` names both models (`models.explorer`), and the explorer's requests
324
+ have `role: "explorer"`.
325
+
326
+ Guide: [Gemini API and Vertex AI](../guides/vertex-and-gemini.md).
327
+
328
+ ### `AskGeminiResult`
329
+
330
+ ```ts
331
+ type AskGeminiResult = AskResult;
332
+ ```
333
+
334
+ What `askGemini` returns: an [`AskResult`](./ask.md#askresult). With Gemini:
335
+
336
+ - `usage` is the total of the whole question, part reads included. `usage.byModel` has an entry
337
+ for each model, keyed by the model name in its URL (`"gemini-3.8-flash"`).
338
+ - `lastUsage` is Gemini's own `usageMetadata`, as it came, and `finishReason` Gemini's own
339
+ `finishReason`, such as `"STOP"` or `"MAX_TOKENS"`. Each is that of the last chat response that
340
+ gave one, of either model: the answer's, unless the prompt was blocked before it.
341
+ - With an explorer, `text` holds only what the answering model wrote, and `turns` counts the chat
342
+ requests of both models.
343
+
344
+ Guide: [errors and reliability](../guides/errors-and-reliability.md).
345
+
346
+ ## The model adapter
347
+
348
+ ### gemini(endpoint, options?)
349
+
350
+ ```ts
351
+ declare function gemini(
352
+ endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "headers">,
353
+ options?: GeminiModelOptions,
354
+ ): ModelAdapter;
355
+ ```
356
+
357
+ A Gemini model for [`askWithFiles`](./ask.md#askwithfilesoptions), as a
358
+ [`ModelAdapter`](./ask.md#modeladapter). Use it instead of `askGemini` to set the model's window,
359
+ the cost of a page or the name in usage totals, to pair Gemini with a model of another provider,
360
+ or to give each model its own settings. `endpoint.explorerUrl` is ignored: an explorer is an
361
+ adapter of its own, passed as `explorer`.
362
+
363
+ The adapter it returns:
364
+
365
+ | Member | Value |
366
+ |---|---|
367
+ | `id` | `options.id`. Without it, the model name in the URL (`/models/{name}`, decoded); for a URL without one, its host; else `"gemini"`. |
368
+ | `capabilities` | `toolFiles` from `toolFilePlacement` (`"inside"`), `pageTokens` (530), and `contextTokens` and `maxRequestBytes` when they are set. No `tokenScale` (so 1), no `outputTokens`, not `appendOnly`. |
369
+ | `send(request, hooks?)` | One chat request: to `streamUrl` when `hooks.onText` is given and the endpoint has one, otherwise to `url`. |
370
+ | `requestBytes(request)` | The size in bytes of the JSON body that `send` would post. |
371
+ | `generateText` | The part reader of whole-file reads: [`createGeminiGenerateText()`](#creategeminigeneratetextoptions) on `endpoint.url`, with `analysisConfig` and `fetch`. `askWithFiles` uses it when this model is the one that explores. Each of its requests may take 180 s, and `gemini()` has no option to change that. |
372
+
373
+ What `send` does:
374
+
375
+ - It asks for the headers before every request.
376
+ - The body holds `contents`; `systemInstruction` when the system instruction is not empty;
377
+ `generationConfig` when it is set; and, when tools are offered, `tools: [{ functionDeclarations }]`
378
+ with `toolConfig: { functionCallingConfig: { mode: "AUTO" } }`. A request that must be answered in
379
+ text declares no tools at all, because Gemini can ignore mode `NONE` and go on calling them.
380
+ - A model turn of the question goes back unchanged, thought signatures included, in the later
381
+ requests to the same adapter. Another model of the question gets it rebuilt from its calls, as a
382
+ stored tool round (`toolTurns`) is.
383
+ - A reply to `streamUrl` is read as a stream when its content type is `text/event-stream`, or when
384
+ it starts like events (`data:`, `event:`, `id:`, `retry:` or a comment). Otherwise it is read in
385
+ one piece, as one chunk or a list of chunks, as Gemini answers without `?alt=sse`: a gateway that
386
+ drops `?alt=sse`, or does not stream, is read whole (since 0.6.0; 0.5.0 read it as an empty
387
+ reply). A body that starts with more than 65,536 characters of white space is read in one piece.
388
+ - Parts marked `"thought": true` are not in the reply's `text` and are not passed to `onText`.
389
+ - Gemini's `finishReason` becomes the reply's `finish`: `STOP` is `"complete"`; `MAX_TOKENS` is
390
+ `"cut"`; `SAFETY`, `RECITATION`, `BLOCKLIST`, `PROHIBITED_CONTENT`, `SPII` and `IMAGE_SAFETY` are
391
+ `"filtered"`; `MALFORMED_FUNCTION_CALL` and `UNEXPECTED_TOOL_CALL` are `"malformed_call"`.
392
+ `promptFeedback.blockReason` becomes `blockReason`, and `usageMetadata` becomes `usage`
393
+ ([`usageOfGemini()`](#usageofgeminiusage)) and `providerUsage`.
394
+
395
+ `send` throws, and sends nothing again itself: `askWithFiles` decides what is retried.
396
+
397
+ | Case | Error | `status` | `kind` |
398
+ |---|---|---|---|
399
+ | Gemini answered with an HTTP error | `GeminiRequestError` with Gemini's `error.message`, or "Gemini returned HTTP 503." | The HTTP status | Told from the status, Gemini's `error.status` and `details` |
400
+ | An error object inside the stream | `GeminiRequestError` with its message | Its `code` when that is a number, else the response's | As above |
401
+ | The connection failed, before or while the reply arrived, or an event of the stream was not JSON | `GeminiRequestError`: "Gemini could not be reached (fetch failed)." | 0 | `"unreachable"` |
402
+ | A reply of HTTP 200 whose body is empty | `GeminiRequestError`: "Gemini could not be reached (the reply was empty).", new in 0.6.0. When the reply's type is `text/event-stream`, "Gemini's reply ended before it was complete." Either is sent again as a reply cut off on its way. | 0 | `"unreachable"` |
403
+ | Nothing arrived for a whole wait | `GeminiRequestError`: "Gemini sent nothing for 600 s." | 0 | `"timeout"` |
404
+ | A stream that closed with no `finishReason` and no `blockReason` | `GeminiRequestError`: "Gemini's reply ended before it was complete." | 0 | `"unreachable"` |
405
+ | A streamed response without a body | `GeminiRequestError`: "Gemini returned an empty stream." | The response's, a 2xx | `"invalid"` (the status is a 2xx); not sent again |
406
+ | A reply whose body is not JSON (a gateway's HTML page), streamed or not | `GeminiRequestError`: "Gemini's reply could not be read: it was not JSON (text/html). A proxy or gateway may have answered in its place.", the brackets holding the response's media type (left out when it has none), with the `SyntaxError` as `cause`. Not sent again. Until 0.6.0, the `SyntaxError` itself, and for a streamed request an empty reply. | The response's, 200 | `"invalid"` |
407
+ | An event of the stream longer than 64,000,000 characters | `GeminiRequestError`: "Gemini's reply could not be read: an event of its stream held more than 64,000,000 characters." Not sent again. New in 0.6.0. | The response's, 200 | `"invalid"` |
408
+ | `hooks.signal` aborted | The signal's reason, as it is | none | none |
409
+
410
+ For an HTTP error, `retryAfterMs` is the wait Gemini asked for: the `retry-after-ms` or
411
+ `Retry-After` header, or the `retryDelay` of a `google.rpc.RetryInfo` in the error's `details`. An
412
+ error inside a stream, or in the body of a response that was OK, has none.
413
+
414
+ ```ts
415
+ import { askWithFiles } from "llm-large-files";
416
+ import { gemini, geminiApi } from "llm-large-files/gemini";
417
+
418
+ // files, documentIds and messages come from your application.
419
+ const apiKey = process.env.GEMINI_API_KEY!;
420
+
421
+ const model = gemini(geminiApi({ apiKey, model: "gemini-3.8-flash" }), {
422
+ contextTokens: 1_048_576, // the model's window: it can only lower the budget, and the library's 1,000,000 is smaller here
423
+ generationConfig: { temperature: 0.3 },
424
+ });
425
+ const explorer = gemini(geminiApi({ apiKey, model: "gemini-3.5-flash-lite" }), { id: "explorer" });
426
+
427
+ const result = await askWithFiles({ files, model, explorer, documentIds, messages });
428
+ console.log(result.usage.byModel); // keyed "gemini-3.8-flash" and, when the explorer ran, "explorer"
429
+ ```
430
+
431
+ Guides: [Gemini API and Vertex AI](../guides/vertex-and-gemini.md),
432
+ [an explorer model](../guides/explorer-model.md).
433
+
434
+ ### `GeminiModelOptions`
435
+
436
+ The options of `gemini()`.
437
+
438
+ | Option | Type | Default | What it does |
439
+ |---|---|---|---|
440
+ | `generationConfig` | `Record<string, unknown> \| undefined` | none: the field is left out of the body | Sent as `generationConfig` with every chat request: `temperature`, `maxOutputTokens`, `thinkingConfig` and so on. It is sent as it is, not checked. Not used for part reads. |
441
+ | `toolFilePlacement` | [`GeminiToolFilePlacement`](#geminitoolfileplacement) `\| undefined` | `"inside"` | Where the pages of `view_pages` go. `"inside"` puts the PDF in the function response itself, which Gemini 3 models read. `"beside"` sends it in a user turn of its own after the function responses: use it for Gemini 2.5, which does not see a file inside a function response. It is also `capabilities.toolFiles`. |
442
+ | `analysisConfig` | `((maxOutputTokens: number) => Record<string, unknown>) \| undefined` | `{ maxOutputTokens }` | The `generationConfig` of the part reads of a whole-file read. Put the limit it is given in `maxOutputTokens`: a second try raises it to [`THINKING_OUTPUT_TOKENS`](#thinking_output_tokens). No temperature by default since 0.6.0 (see `analysisConfig` of [`AskGeminiOptions`](#askgeminioptions)). |
443
+ | `contextTokens` | `number \| undefined` | none | The model's context window in tokens. Set as `capabilities.contextTokens`, it keeps the budget of a question within it. Without it the library's budget holds: 1,000,000 tokens unless you set another. |
444
+ | `maxRequestBytes` | `number \| undefined` | none | The largest request body the model or your gateway takes, in bytes. Set as `capabilities.maxRequestBytes`, it keeps the budget within it. |
445
+ | `pageTokens` | `number \| undefined` | `530` ([`GEMINI_PAGE_TOKENS`](#gemini_page_tokens)) | Tokens billed for one PDF page shown by `view_pages`. |
446
+ | `id` | `string \| undefined` | the model name in the URL | The name of the model in `usage.byModel` and in messages. See `id` under [`gemini()`](#geminiendpoint-options). |
447
+ | `firstByteTimeoutMs` | `number \| undefined` | `600_000` | The longest wait, in milliseconds, for the first piece of a chat reply. Headers do not count: a model that thinks sends nothing until it has thought, and a reply that is not streamed comes whole at the end. A request that gets nothing for that long is aborted with a `GeminiRequestError` (`status` 0, `kind` `"timeout"`), which `askWithFiles` sends again once. 0, a negative or a non-finite number waits without end. Not used for part reads. |
448
+ | `idleTimeoutMs` | `number \| undefined` | `300_000` | The longest wait, in milliseconds, between two pieces of a chat reply once it has started to arrive. Any bytes count, keep-alives included. The same error; `askWithFiles` sends the request again once, unless text of it was shown. 0 waits without end. |
449
+ | `fetch` | `typeof fetch \| undefined` | the global `fetch` | Used for chat requests and part reads. |
450
+
451
+ The two waits default to `DEFAULT_FIRST_BYTE_TIMEOUT_MS` and `DEFAULT_IDLE_TIMEOUT_MS`
452
+ ([errors and retries](./errors-and-retries.md)). What to set them to, and why the first one is
453
+ long: [Gemini API and Vertex AI](../guides/vertex-and-gemini.md) and
454
+ [errors and reliability](../guides/errors-and-reliability.md).
455
+
456
+ ### `GEMINI_PAGE_TOKENS`
457
+
458
+ ```ts
459
+ const GEMINI_PAGE_TOKENS = 530;
460
+ ```
461
+
462
+ What Gemini bills for one PDF page it is shown, in tokens (measured: 520 to 532). It is the default
463
+ of `pageTokens` in `gemini()`, and the value `askGemini` always uses. Guide: [PDFs](../guides/pdfs.md).
464
+
465
+ ## Gemini contents
466
+
467
+ For an application that keeps its conversations as Gemini `contents`.
468
+
469
+ ### fromGeminiContents(contents)
470
+
471
+ ```ts
472
+ declare function fromGeminiContents(contents: GeminiContent[]): ChatMessage[];
473
+ ```
474
+
475
+ Gemini `contents` as the `messages` of `askWithFiles` ([`ChatMessage`](./ask.md#chatmessage)).
476
+ The role `"user"` stays `"user"`, and `"model"` becomes `"assistant"`. A part that holds only
477
+ `text` becomes `{ text }`. A part with `text` and other fields (a thought signature) becomes
478
+ `{ native: part, text }`. Every other part (an image, an inline PDF, a function call) is kept as
479
+ `{ native: part }`, which `gemini()` sends back as it is. The array and its parts are not changed.
480
+ `askGemini` uses it for `contents`.
481
+
482
+ Guide: [conversations](../guides/conversations.md).
483
+
484
+ ### geminiToolTurns(turns)
485
+
486
+ ```ts
487
+ declare function geminiToolTurns(turns: ToolTurn[]): GeminiContent[];
488
+ ```
489
+
490
+ The tool rounds of a question ([`AskResult.toolTurns`](./ask.md#askresult)) as Gemini `contents`:
491
+ for each round, a `model` turn of `functionCall` parts (`{ name, args, id? }`), then a `user` turn
492
+ of `functionResponse` parts, in call order. Put them between the question and its answer, and the
493
+ model sees in a later question what its tools returned in this one. The results leave out
494
+ `tool_turns_left`, which counted the turns of their own question, as `askWithFiles` does with
495
+ stored rounds (since 0.6.0): a history kept as `contents` gives the same request as one kept as
496
+ `toolTurns`. Contents that 0.5.0 converted keep the field.
497
+
498
+ ```ts
499
+ import { askGemini, geminiToolTurns, type GeminiContent } from "llm-large-files/gemini";
500
+
501
+ // files, endpoint and documentId as above. history is what your application keeps for the chat.
502
+ const history: GeminiContent[] = [];
503
+
504
+ async function ask(question: string): Promise<string> {
505
+ const turn: GeminiContent = { role: "user", parts: [{ text: question }] };
506
+ const result = await askGemini({ files, endpoint, documentIds: [documentId], contents: [...history, turn] });
507
+ history.push(turn, ...geminiToolTurns(result.toolTurns));
508
+ if (result.answered) history.push({ role: "model", parts: [{ text: result.text }] });
509
+ return result.text;
510
+ }
511
+ ```
512
+
513
+ Guide: [conversations](../guides/conversations.md).
514
+
515
+ ### `GeminiContent`
516
+
517
+ ```ts
518
+ type GeminiContent = { role: "user" | "model"; parts: GeminiPart[] };
519
+ ```
520
+
521
+ One entry of Gemini's `contents`.
522
+
523
+ ### `GeminiPart`
524
+
525
+ ```ts
526
+ type GeminiPart = Record<string, unknown>;
527
+ ```
528
+
529
+ One part of a turn, in Gemini's own form: `{ text }`, `{ inlineData }`, `{ functionCall }`,
530
+ `{ functionResponse }` and so on. The library reads `text`, `thought` and `functionCall`, and
531
+ passes every part on as it is.
532
+
533
+ ## Helpers for your own loop
534
+
535
+ These build Gemini requests in a tool loop of your own, made with `files.prepare()` and
536
+ `files.tools()`. Guide: [your own adapter and loop](../guides/own-adapter-and-loop.md).
537
+
538
+ ### createGeminiGenerateText(options)
539
+
540
+ ```ts
541
+ declare function createGeminiGenerateText(options: {
542
+ url: string;
543
+ headers: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
544
+ fetchImpl?: typeof fetch;
545
+ generationConfig?: (maxOutputTokens: number) => Record<string, unknown>;
546
+ timeoutMs?: number;
547
+ }): GenerateText;
548
+ ```
549
+
550
+ A [`GenerateText`](./ask.md#generatetext) on a non-streaming `...:generateContent` URL: the plain
551
+ completion a whole-file read uses for each part. `gemini()` builds one on its endpoint's `url`.
552
+
553
+ | Option | Type | Default | What it does |
554
+ |---|---|---|---|
555
+ | `url` | `string` | required | The `...:generateContent` URL. What is learned about the model's output limit is kept under it. |
556
+ | `headers` | `Record<string, string>` or a function that returns them | required | A function is called before every request: a whole-file read can outlast an access token. |
557
+ | `fetchImpl` | `typeof fetch` | the global `fetch` | Your own `fetch`. |
558
+ | `generationConfig` | `(maxOutputTokens: number) => Record<string, unknown>` | `{ maxOutputTokens }` | The `generationConfig` of each request, from its output limit. Until 0.6.0 the default also sent `temperature: 0.2`. |
559
+ | `timeoutMs` | `number` | `180_000` | The longest time one request may take, its whole body included. A second try at a larger limit gets its own. |
560
+
561
+ Each request posts `contents: [{ role: "user", parts: [{ text: prompt }] }]`, the system
562
+ instruction and the `generationConfig`. The text it returns is the reply's text parts without the
563
+ thoughts, joined. `onUsage` gets the usage of every request that was answered
564
+ ([`usageOfGemini()`](#usageofgeminiusage)). `onTruncated` is called when the reply stopped at
565
+ `MAX_TOKENS`, or a safety filter stopped it.
566
+
567
+ When a reply stops at `MAX_TOKENS` with no text, or with half the limit or more spent on thoughts,
568
+ and the limit was below [`THINKING_OUTPUT_TOKENS`](#thinking_output_tokens), the request is sent
569
+ once more with that limit, and later requests to the same `url` start there. If that second request
570
+ fails, the first reply's text is kept when it had some, and the error is thrown when it had none. A
571
+ model or gateway that refused the larger limit with HTTP 400 is not asked for it again. A refusal
572
+ of the request as too large (kind `"context_overflow"`: for the model's window at HTTP 400, or for
573
+ the tokens a minute the provider allows at HTTP 429 or 413) is not taken for that since 0.6.0: it
574
+ turns the larger limit off only when the window or allowance it names is 32,768 tokens or less.
575
+ Otherwise what was learned is forgotten, and a later part may still get the larger limit. The
576
+ first request to a `url` goes alone: requests to it that arrive meanwhile wait for what it learns.
577
+
578
+ | Case | Error |
579
+ |---|---|
580
+ | An HTTP error | `GeminiRequestError` with Gemini's `error.message`, or "The model returned HTTP 503.", with `status`, `kind` and `retryAfterMs` |
581
+ | The connection failed, or the body could not be read | `GeminiRequestError`: "Gemini could not be reached (…).", `status` 0 |
582
+ | A body of HTTP 200 that is empty | `GeminiRequestError`: "Gemini could not be reached (the reply was empty).", `status` 0 |
583
+ | A body that is not JSON | `GeminiRequestError`: "Gemini's reply could not be read: it was not JSON (text/html). A proxy or gateway may have answered in its place.", the response's `status`, kind `"invalid"`, the `SyntaxError` as `cause`. Until 0.6.0, the `SyntaxError` itself. |
584
+ | `timeoutMs` passed, or `signal` aborted | The abort error, as it is, with no status |
585
+ | A reply with no text | `Error`: "The model returned no text." or, with its `finishReason`, "The model returned no text (SAFETY)." |
586
+
587
+ A whole-file read tries a part once more after an error with no status. It tells the model why a
588
+ part failed by the error's kind and status, never by Gemini's message: "The model took too long to
589
+ answer." for a request past `timeoutMs`, "The model returned no text (SAFETY)." for a reply with no
590
+ text, the reason only when it is a plain word (see
591
+ [`analyze_whole_document`](./tools.md#analyze_whole_document)).
592
+
593
+ `gemini()` gives its part reads no way to change the 180 s. To change it, replace the adapter's
594
+ `generateText`:
595
+
596
+ ```ts
597
+ import type { ModelAdapter } from "llm-large-files";
598
+ import { createGeminiGenerateText, gemini } from "llm-large-files/gemini";
599
+
600
+ // endpoint as in the vertexAi() sample.
601
+ const base = gemini(endpoint);
602
+ const model: ModelAdapter = {
603
+ ...base,
604
+ // Part reads that may take up to five minutes each.
605
+ generateText: createGeminiGenerateText({ url: endpoint.url, headers: endpoint.headers, timeoutMs: 300_000 }),
606
+ };
607
+ ```
608
+
609
+ Guides: [Gemini API and Vertex AI](../guides/vertex-and-gemini.md),
610
+ [errors and reliability](../guides/errors-and-reliability.md).
611
+
612
+ ### `THINKING_OUTPUT_TOKENS`
613
+
614
+ ```ts
615
+ const THINKING_OUTPUT_TOKENS = 32_768;
616
+ ```
617
+
618
+ The output limit that a part read is asked for again with when the model spent its limit on
619
+ thoughts. A model that thinks counts its thoughts in its output limit: asked for 4,096 tokens of
620
+ notes on a part of a log, Gemini 3.8 Flash spent 3,931 of them thinking and wrote two lines, and
621
+ Gemini 4 wrote nothing (November 2026). The part reads of `gemini()`, `openAiCompatible()` and
622
+ `anthropic()` all follow this rule; the constant is exported only from this entry point.
623
+
624
+ Guides: [Gemini API and Vertex AI](../guides/vertex-and-gemini.md); the rule for every adapter's
625
+ part reads: [How it works](../how-it-works.md#map-reduce).
626
+
627
+ ### toGeminiTools(declarations)
628
+
629
+ ```ts
630
+ declare function toGeminiTools(declarations: ToolDeclaration[]): { functionDeclarations: ToolDeclaration[] };
631
+ ```
632
+
633
+ The tool declarations of a [`ToolSet`](./tools.md#toolset) as an entry of Gemini's `tools`.
634
+ Gemini takes the library's JSON Schema subset as it is, so the declarations are not changed.
635
+
636
+ ### geminiFunctionResponses(calls)
637
+
638
+ ```ts
639
+ declare function geminiFunctionResponses(calls: GeminiToolAnswer[]): GeminiContent & { role: "user" };
640
+ ```
641
+
642
+ The `user` turn that answers a model turn's function calls: one part
643
+ `{ functionResponse: { name, id?, response, parts? } }` for each call, in the order given, where
644
+ `response` is what the tool returned. A file a tool returned (`files`, from
645
+ `executeWithFiles`) goes inside its function response, as
646
+ `{ inlineData: { mimeType, displayName, data } }` with the bytes in base64. The field of the result
647
+ whose value is the file's name becomes `{ "$ref": name }`; a file that no field names is listed in
648
+ `response.files` as `{ "$ref": name }`. The results you pass are not changed. To put files beside
649
+ the function responses, use `geminiFunctionResponseTurns()`.
650
+
651
+ ### geminiFunctionResponseTurns(calls, options?)
652
+
653
+ ```ts
654
+ declare function geminiFunctionResponseTurns(
655
+ calls: GeminiToolAnswer[],
656
+ options?: { files?: GeminiToolFilePlacement },
657
+ ): Array<GeminiContent & { role: "user" }>;
658
+ ```
659
+
660
+ The turns that answer a model turn's function calls. Add them all to `contents`, in order.
661
+
662
+ | Option | Type | Default | What it does |
663
+ |---|---|---|---|
664
+ | `files` | [`GeminiToolFilePlacement`](#geminitoolfileplacement) | `"inside"` | `"inside"`, or any value but `"beside"`: one turn, that of `geminiFunctionResponses()`. `"beside"`: the function responses, without files, in one `user` turn; then, when a call returned files, a second `user` turn in which each file follows a text part "pages-2-3.pdf (returned by view_pages):", as `{ inlineData: { mimeType, data } }`. |
665
+
666
+ The files get a turn of their own because Vertex AI refuses a turn in which anything follows a
667
+ function response (HTTP 400 for Gemini 3 models, November 2026). Each turn is a `GeminiContent` with
668
+ the role `"user"`, so the turns go into a `GeminiContent[]` as they are.
669
+
670
+ One tool round of your own loop:
671
+
672
+ ```ts
673
+ import type { ToolSet } from "llm-large-files";
674
+ import { geminiFunctionResponseTurns, type GeminiContent, type GeminiToolAnswer } from "llm-large-files/gemini";
675
+
676
+ // tools is the ToolSet of files.tools(); contents is the conversation of your request, and
677
+ // modelTurn is the model turn of Gemini's last reply, which called functions.
678
+ async function answerCalls(tools: ToolSet, contents: GeminiContent[], modelTurn: GeminiContent): Promise<void> {
679
+ const answers: GeminiToolAnswer[] = [];
680
+ for (const part of modelTurn.parts) {
681
+ const call = part.functionCall as { name: string; args?: Record<string, unknown>; id?: string } | undefined;
682
+ if (!call) continue;
683
+ const args = call.args ?? {};
684
+ const { result, files } = await tools.executeWithFiles(call.name, args);
685
+ answers.push({ call: { name: call.name, args, ...(call.id ? { id: call.id } : {}) }, result, files });
686
+ }
687
+ // The model turn goes back unchanged: Gemini 3 wants its thought signatures.
688
+ contents.push(modelTurn, ...geminiFunctionResponseTurns(answers, { files: "beside" }));
689
+ }
690
+ ```
691
+
692
+ ### `GeminiFunctionCall`
693
+
694
+ ```ts
695
+ type GeminiFunctionCall = ToolCall; // { id?: string; name: string; args: Record<string, unknown>; problem?: string }
696
+ ```
697
+
698
+ A function call of the model: [`ToolCall`](./ask.md#toolcall) under a Gemini name.
699
+
700
+ ### `GeminiToolAnswer`
701
+
702
+ ```ts
703
+ type GeminiToolAnswer = ToolAnswer; // { call: ToolCall; result: ToolResult; files?: ToolFile[] }
704
+ ```
705
+
706
+ A function call with what the tool returned for it, and the files it returned:
707
+ [`ToolAnswer`](./ask.md#toolanswer) under a Gemini name.
708
+
709
+ ### `GeminiToolFilePlacement`
710
+
711
+ ```ts
712
+ type GeminiToolFilePlacement = "inside" | "beside";
713
+ ```
714
+
715
+ Where a file that a tool returned (the pages of `view_pages`) goes in the request:
716
+
717
+ | Value | Where the file goes |
718
+ |---|---|
719
+ | `"inside"` | In the `parts` of its function response, which names it with `{ "$ref": name }`. Gemini 3 models read it there. Gemini 2.5 accepts that form and does not see the file. |
720
+ | `"beside"` | In a `user` turn of its own, after the turn of function responses, for a model that does not read a file inside a function response. |
721
+
722
+ Guide: [PDFs](../guides/pdfs.md), which has the live results for each model.
723
+
724
+ ### usageOfGemini(usage)
725
+
726
+ ```ts
727
+ declare function usageOfGemini(usage: Record<string, unknown> | undefined): GenerateUsage;
728
+ ```
729
+
730
+ Gemini's `usageMetadata` in the terms every adapter reports ([`GenerateUsage`](./ask.md#generateusage)):
731
+ thoughts are output, and cached tokens are part of the input.
732
+
733
+ | Field | From `usageMetadata` |
734
+ |---|---|
735
+ | `inputTokens` | `promptTokenCount` + `toolUsePromptTokenCount` |
736
+ | `cachedInputTokens` | `cachedContentTokenCount` |
737
+ | `outputTokens` | `candidatesTokenCount` + `thoughtsTokenCount` |
738
+ | `thoughtTokens` | `thoughtsTokenCount` |
739
+
740
+ A field that is missing or not a number counts as 0, and `undefined` gives four zeros. Guide:
741
+ [costs and limits](../guides/costs-and-limits.md).
742
+
743
+ ## Errors
744
+
745
+ ### `GeminiRequestError`
746
+
747
+ ```ts
748
+ declare class GeminiRequestError extends ModelRequestError {
749
+ constructor(message: string, status: number, options?: {
750
+ retryAfterMs?: number;
751
+ cause?: unknown;
752
+ kind?: ModelErrorKind;
753
+ code?: string | undefined;
754
+ details?: unknown;
755
+ });
756
+ }
757
+ ```
758
+
759
+ A Gemini request that failed: Gemini answered with an HTTP error, or `status` is 0 because Gemini
760
+ could not be reached, sent nothing for a whole wait, or ended a stream before it was complete. A
761
+ reply of HTTP 200 that could not be read (not JSON, or an event too long) keeps its 200, with kind
762
+ `"invalid"`.
763
+ `gemini()` throws it for chat requests, and its part reader (`generateText`) for part reads.
764
+ `askGemini` and `askWithFiles` throw it for a chat request that failed and was not worth another
765
+ try, or still failed after the retries. A part read that fails is not thrown: the part counts as
766
+ unread, and when no part could be read the tool call returns
767
+ `{ error: "Could not read any part of app.log: …" }` to the model, with the kind and status of the
768
+ failure, not Gemini's message ("The model was busy (HTTP 429)."). Its `name` is
769
+ `"GeminiRequestError"`.
770
+
771
+ Its fields are those of [`ModelRequestError`](./errors-and-retries.md#modelrequesterror): `status`,
772
+ `kind`, `retryAfterMs`, and for a request too large, `limitTokens` and `requestedTokens` when the
773
+ message gives them (`kind`, `limitTokens` and `requestedTokens` are new in 0.6.0). Gemini's `error.status` (such as `"RESOURCE_EXHAUSTED"`) and `details` are
774
+ passed in as `code` and `details` to tell the `kind`, and are not kept on the error:
775
+
776
+ - HTTP 429 whose `details` name a quota per day (`google.rpc.QuotaFailure`) is `"quota"`, which is
777
+ not retried. So is a 429 whose message alone names a quota per day, as Vertex AI's
778
+ "Quota exceeded for aiplatform.googleapis.com/generate_content_requests_per_day_per_project_per_base_model …"
779
+ does. Another 429 is `"rate_limit"`.
780
+ - HTTP 400 whose `details` give the reason `API_KEY_INVALID` is `"auth"`.
781
+ - A message such as Vertex AI's "Unable to submit request because the input token count is N but
782
+ model only supports up to M." is `"context_overflow"`, with `requestedTokens` N and
783
+ `limitTokens` M.
784
+
785
+ ```ts
786
+ import { askGemini, DocumentsNotFoundError, GeminiRequestError, partialResultOf } from "llm-large-files/gemini";
787
+
788
+ // files and endpoint as above; documentIds: string[];
789
+ // messages: Array<ChatTurn | ToolTurn> (plain turns and stored toolTurns).
790
+ try {
791
+ const result = await askGemini({ files, endpoint, documentIds, messages });
792
+ console.log(result.text);
793
+ } catch (error) {
794
+ if (error instanceof DocumentsNotFoundError) {
795
+ console.error("Upload again:", error.ids);
796
+ } else if (error instanceof GeminiRequestError) {
797
+ // For your logs, not for your users: the message is Gemini's own.
798
+ console.error(error.status, error.kind, error.retryAfterMs, error.message);
799
+ }
800
+ const partial = partialResultOf(error); // what the question found and paid for before it failed
801
+ if (partial) console.error(`${partial.usage.requests} requests were answered before it failed`);
802
+ throw error;
803
+ }
804
+ ```
805
+
806
+ What to show your users for each `kind`: [errors and reliability](../guides/errors-and-reliability.md).
807
+
808
+ ## Re-exports of the main entry
809
+
810
+ These are the same values and types as the exports of `llm-large-files`, so `instanceof` works
811
+ whichever entry point you import them from. Each is described on its own page.
812
+
813
+ | Export | What it is | Page |
814
+ |---|---|---|
815
+ | `DocumentsNotFoundError` | The error for document IDs that were never uploaded, have expired, or belong to another owner; `.ids` lists them. | [ask](./ask.md#documentsnotfounderror) |
816
+ | `partialResultOf(error)` | What a question that threw had found and used until then, or `undefined`. | [ask](./ask.md#partialresultoferror) |
817
+ | `EXPLORER_INSTRUCTION` | The line added to an explorer model's system instruction. | [ask](./ask.md#explorer_instruction) |
818
+ | `FINAL_ANSWER_REQUEST` | The message that asks for the answer after tools ran. | [ask](./ask.md#final_answer_request) |
819
+ | `FINAL_ANSWER_AFTER_PAGES` | The same, when `view_pages` was the only tool. | [ask](./ask.md#final_answer_after_pages) |
820
+ | `FINAL_ANSWER_WITHOUT_TOOLS` | The message that asks for the answer when no tool ran. | [ask](./ask.md#final_answer_without_tools) |
821
+ | `parseSseJson(stream, hooks?)` | The `text/event-stream` parser: JSON objects, one per `data:` event. | [errors and retries](./errors-and-retries.md#parsessejsonstream-hooks) |
822
+ | `ChatTurn` | The type `{ role: "user" \| "assistant" \| "model"; text: string }`. | [ask](./ask.md#chatturn) |
823
+ | `AskEvent` | The type of the events `onEvent` gets. New in 0.7.0. | [events](./events.md) |