llm-large-files 0.9.0 → 0.10.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 (222) hide show
  1. package/CHANGELOG.md +446 -0
  2. package/README.md +13 -7
  3. package/dist/access.d.ts +45 -3
  4. package/dist/access.d.ts.map +1 -1
  5. package/dist/access.js +106 -3
  6. package/dist/access.js.map +1 -1
  7. package/dist/aggregate.d.ts +6 -0
  8. package/dist/aggregate.d.ts.map +1 -1
  9. package/dist/aggregate.js +86 -13
  10. package/dist/aggregate.js.map +1 -1
  11. package/dist/analyze.d.ts +4 -0
  12. package/dist/analyze.d.ts.map +1 -1
  13. package/dist/analyze.js +2 -2
  14. package/dist/analyze.js.map +1 -1
  15. package/dist/answer-info.d.ts +26 -0
  16. package/dist/answer-info.d.ts.map +1 -0
  17. package/dist/answer-info.js +32 -0
  18. package/dist/answer-info.js.map +1 -0
  19. package/dist/anthropic/adapter.d.ts +5 -1
  20. package/dist/anthropic/adapter.d.ts.map +1 -1
  21. package/dist/anthropic/adapter.js +35 -10
  22. package/dist/anthropic/adapter.js.map +1 -1
  23. package/dist/ask.d.ts +115 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +572 -103
  26. package/dist/ask.js.map +1 -1
  27. package/dist/citations.d.ts +36 -0
  28. package/dist/citations.d.ts.map +1 -0
  29. package/dist/citations.js +291 -0
  30. package/dist/citations.js.map +1 -0
  31. package/dist/error-info.d.ts +13 -0
  32. package/dist/error-info.d.ts.map +1 -1
  33. package/dist/error-info.js +37 -1
  34. package/dist/error-info.js.map +1 -1
  35. package/dist/errors.d.ts +3 -1
  36. package/dist/errors.d.ts.map +1 -1
  37. package/dist/errors.js +3 -1
  38. package/dist/errors.js.map +1 -1
  39. package/dist/events.d.ts +25 -7
  40. package/dist/events.d.ts.map +1 -1
  41. package/dist/events.js.map +1 -1
  42. package/dist/evidence.d.ts.map +1 -1
  43. package/dist/evidence.js +21 -2
  44. package/dist/evidence.js.map +1 -1
  45. package/dist/extract.d.ts.map +1 -1
  46. package/dist/extract.js +6 -1
  47. package/dist/extract.js.map +1 -1
  48. package/dist/gemini/adapter.d.ts +35 -4
  49. package/dist/gemini/adapter.d.ts.map +1 -1
  50. package/dist/gemini/adapter.js +68 -29
  51. package/dist/gemini/adapter.js.map +1 -1
  52. package/dist/gemini/chat.d.ts +28 -55
  53. package/dist/gemini/chat.d.ts.map +1 -1
  54. package/dist/gemini/chat.js +20 -27
  55. package/dist/gemini/chat.js.map +1 -1
  56. package/dist/gemini/endpoints.d.ts +59 -11
  57. package/dist/gemini/endpoints.d.ts.map +1 -1
  58. package/dist/gemini/endpoints.js +33 -7
  59. package/dist/gemini/endpoints.js.map +1 -1
  60. package/dist/gemini/errors.d.ts +39 -5
  61. package/dist/gemini/errors.d.ts.map +1 -1
  62. package/dist/gemini/errors.js +70 -9
  63. package/dist/gemini/errors.js.map +1 -1
  64. package/dist/gemini/generate.d.ts +53 -2
  65. package/dist/gemini/generate.d.ts.map +1 -1
  66. package/dist/gemini/generate.js +100 -50
  67. package/dist/gemini/generate.js.map +1 -1
  68. package/dist/gemini/index.d.ts +3 -3
  69. package/dist/gemini/index.d.ts.map +1 -1
  70. package/dist/http.d.ts +41 -3
  71. package/dist/http.d.ts.map +1 -1
  72. package/dist/http.js +40 -2
  73. package/dist/http.js.map +1 -1
  74. package/dist/index.d.ts +6 -4
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +4 -2
  77. package/dist/index.js.map +1 -1
  78. package/dist/ingest.d.ts +9 -1
  79. package/dist/ingest.d.ts.map +1 -1
  80. package/dist/ingest.js +50 -25
  81. package/dist/ingest.js.map +1 -1
  82. package/dist/library.d.ts +129 -2
  83. package/dist/library.d.ts.map +1 -1
  84. package/dist/library.js +224 -149
  85. package/dist/library.js.map +1 -1
  86. package/dist/map-reduce.d.ts +176 -10
  87. package/dist/map-reduce.d.ts.map +1 -1
  88. package/dist/map-reduce.js +804 -58
  89. package/dist/map-reduce.js.map +1 -1
  90. package/dist/model.d.ts +36 -4
  91. package/dist/model.d.ts.map +1 -1
  92. package/dist/model.js +17 -1
  93. package/dist/model.js.map +1 -1
  94. package/dist/node/handlers.d.ts +29 -8
  95. package/dist/node/handlers.d.ts.map +1 -1
  96. package/dist/node/handlers.js +148 -126
  97. package/dist/node/handlers.js.map +1 -1
  98. package/dist/node/index.d.ts +1 -1
  99. package/dist/node/index.d.ts.map +1 -1
  100. package/dist/node/index.js.map +1 -1
  101. package/dist/node/ingest-child.js +2 -2
  102. package/dist/node/ingest-child.js.map +1 -1
  103. package/dist/node/spool.d.ts +9 -5
  104. package/dist/node/spool.d.ts.map +1 -1
  105. package/dist/node/spool.js +28 -15
  106. package/dist/node/spool.js.map +1 -1
  107. package/dist/node/sse.d.ts +6 -5
  108. package/dist/node/sse.d.ts.map +1 -1
  109. package/dist/node/sse.js +8 -7
  110. package/dist/node/sse.js.map +1 -1
  111. package/dist/openai/adapter.d.ts +5 -1
  112. package/dist/openai/adapter.d.ts.map +1 -1
  113. package/dist/openai/adapter.js +53 -12
  114. package/dist/openai/adapter.js.map +1 -1
  115. package/dist/output-limit.d.ts +2 -1
  116. package/dist/output-limit.d.ts.map +1 -1
  117. package/dist/output-limit.js +5 -2
  118. package/dist/output-limit.js.map +1 -1
  119. package/dist/pdf-outline.d.ts +71 -0
  120. package/dist/pdf-outline.d.ts.map +1 -0
  121. package/dist/pdf-outline.js +414 -0
  122. package/dist/pdf-outline.js.map +1 -0
  123. package/dist/plan.d.ts +137 -7
  124. package/dist/plan.d.ts.map +1 -1
  125. package/dist/plan.js +248 -26
  126. package/dist/plan.js.map +1 -1
  127. package/dist/prepare.d.ts +50 -0
  128. package/dist/prepare.d.ts.map +1 -0
  129. package/dist/prepare.js +207 -0
  130. package/dist/prepare.js.map +1 -0
  131. package/dist/ranged.d.ts +2 -1
  132. package/dist/ranged.d.ts.map +1 -1
  133. package/dist/ranged.js +16 -3
  134. package/dist/ranged.js.map +1 -1
  135. package/dist/search.d.ts +7 -0
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +72 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/stores.d.ts +6 -0
  140. package/dist/stores.d.ts.map +1 -1
  141. package/dist/stores.js +82 -11
  142. package/dist/stores.js.map +1 -1
  143. package/dist/tools.d.ts +22 -2
  144. package/dist/tools.d.ts.map +1 -1
  145. package/dist/tools.js +323 -76
  146. package/dist/tools.js.map +1 -1
  147. package/dist/types.d.ts +49 -1
  148. package/dist/types.d.ts.map +1 -1
  149. package/dist/whole-cost.d.ts +37 -0
  150. package/dist/whole-cost.d.ts.map +1 -0
  151. package/dist/whole-cost.js +46 -0
  152. package/dist/whole-cost.js.map +1 -0
  153. package/docs/README.md +4 -0
  154. package/docs/guides/anthropic.md +5 -2
  155. package/docs/guides/conversations.md +1 -1
  156. package/docs/guides/costs-and-limits.md +132 -36
  157. package/docs/guides/deployment.md +106 -13
  158. package/docs/guides/errors-and-reliability.md +157 -45
  159. package/docs/guides/explorer-model.md +4 -1
  160. package/docs/guides/openai-compatible.md +47 -7
  161. package/docs/guides/own-adapter-and-loop.md +33 -6
  162. package/docs/guides/pdfs.md +96 -7
  163. package/docs/guides/storage.md +46 -3
  164. package/docs/guides/testing.md +71 -0
  165. package/docs/guides/vertex-and-gemini.md +159 -50
  166. package/docs/guides/web-app.md +10 -6
  167. package/docs/how-it-works.md +120 -22
  168. package/docs/measurements.md +172 -5
  169. package/docs/publishing.md +76 -4
  170. package/docs/reference/anthropic.md +12 -7
  171. package/docs/reference/ask.md +262 -35
  172. package/docs/reference/errors-and-retries.md +30 -2
  173. package/docs/reference/events.md +27 -10
  174. package/docs/reference/gemini.md +184 -68
  175. package/docs/reference/library.md +190 -23
  176. package/docs/reference/node.md +51 -17
  177. package/docs/reference/openai.md +21 -10
  178. package/docs/reference/tools.md +271 -26
  179. package/docs/security.md +101 -12
  180. package/docs/troubleshooting.md +14 -12
  181. package/docs/upgrading-0.10.md +472 -0
  182. package/package.json +5 -1
  183. package/src/access.ts +127 -4
  184. package/src/aggregate.ts +92 -14
  185. package/src/analyze.ts +2 -2
  186. package/src/answer-info.ts +45 -0
  187. package/src/anthropic/adapter.ts +40 -11
  188. package/src/ask.ts +646 -106
  189. package/src/citations.ts +294 -0
  190. package/src/error-info.ts +36 -1
  191. package/src/errors.ts +3 -1
  192. package/src/events.ts +29 -6
  193. package/src/evidence.ts +21 -2
  194. package/src/extract.ts +6 -1
  195. package/src/gemini/adapter.ts +99 -32
  196. package/src/gemini/chat.ts +53 -82
  197. package/src/gemini/endpoints.ts +89 -16
  198. package/src/gemini/errors.ts +74 -11
  199. package/src/gemini/generate.ts +147 -57
  200. package/src/gemini/index.ts +3 -3
  201. package/src/http.ts +65 -4
  202. package/src/index.ts +6 -4
  203. package/src/ingest.ts +58 -27
  204. package/src/library.ts +336 -142
  205. package/src/map-reduce.ts +855 -67
  206. package/src/model.ts +44 -4
  207. package/src/node/handlers.ts +159 -118
  208. package/src/node/index.ts +1 -0
  209. package/src/node/ingest-child.ts +2 -2
  210. package/src/node/spool.ts +28 -14
  211. package/src/node/sse.ts +8 -7
  212. package/src/openai/adapter.ts +56 -13
  213. package/src/output-limit.ts +5 -2
  214. package/src/pdf-outline.ts +400 -0
  215. package/src/plan.ts +287 -36
  216. package/src/prepare.ts +253 -0
  217. package/src/ranged.ts +16 -3
  218. package/src/search.ts +69 -13
  219. package/src/stores.ts +76 -11
  220. package/src/tools.ts +327 -75
  221. package/src/types.ts +45 -1
  222. package/src/whole-cost.ts +64 -0
@@ -242,9 +242,11 @@ for `onText`.
242
242
  | `ms` | `number` | From `request.start` to now, retries and their waits included. |
243
243
  | `outcome` | `"ok" \| "error"` | How it ended. |
244
244
  | `usage` | `Partial<ModelUsage>`, optional | What the provider said this request used. For a `"reader"` request, the sum of all its sends. |
245
- | `finish` | `"complete" \| "cut" \| "filtered" \| "malformed_call"`, optional | How the reply ended, in the library's words. Chat requests only. |
245
+ | `finish` | `"complete" \| "cut" \| "filtered" \| "malformed_call" \| "other"`, optional | How the reply ended, in the library's words. Chat requests only. `"other"` is new in 0.10.0: `gemini()` gives it for Gemini's `OTHER`, `LANGUAGE` and four more reasons. |
246
246
  | `finishReason` | `string`, optional | How the reply ended, in the provider's words. Chat requests only. |
247
247
  | `toolCalls` | `number`, optional | How many tool calls the reply asked for. Chat requests with outcome `"ok"`. |
248
+ | `responseId` | `string`, optional | The provider's ID of the response (`ModelReply.responseId`), when the adapter gives one: to find the request in the provider's logs. Chat requests only. New in 0.10.0. |
249
+ | `responseModel` | `string`, optional | The model that wrote the response, as the provider names it (`ModelReply.responseModel`), when the adapter gives one: the exact version behind an alias. Chat requests only. New in 0.10.0. |
248
250
  | `error` | [`EventError`](#errors-eventerror), optional | With outcome `"error"`: why. |
249
251
 
250
252
  A request that failed does not always end the question. An overflow is made smaller and sent
@@ -284,7 +286,7 @@ outcome that says so.
284
286
  | `outcome` | [`ToolOutcome`](#tooloutcome) | How it ended. |
285
287
  | `ms` | `number` | From `tool.start` to now. Ends come in call order, so this includes the wait for the calls before it in the turn. |
286
288
  | `step` | `string`, optional | The finished step, as `onStep` got it. Absent for `"not_run"` (one `calls_not_run` notice says it for all of them), and for a call ended because its turn failed. |
287
- | `evidence` | [`Evidence`](./ask.md#evidence), optional | What the call showed the model, with this `callId`. Each entry of `AskResult.evidence` has its `callId` too, so you can find the call it came from. |
289
+ | `evidence` | [`Evidence`](./ask.md#evidence), optional | What the call showed the model, with this `callId`. Each entry of `AskResult.evidence` that a call made has its `callId` too, so you can find the call it came from. The entries of the files sent whole (`tool: "inline"`, new in 0.10.0) have none: no call made them. |
288
290
  | `resultCharacters` | `number`, optional | The characters of the JSON result the model was sent. 0 for a call ended because its turn failed. |
289
291
  | `error` | `string`, optional | When the result the model was sent is an error (outcomes `"error"`, `"refused"`, `"not_run"`): its message. For a call ended because its turn failed: why, as in `EventError.message`. |
290
292
  | `result` | [`ToolResult`](./tools.md#toolresult), optional | The result the model was sent. Only with `eventResults: true`: it holds document text. |
@@ -297,6 +299,7 @@ outcome that says so.
297
299
  | `message` | `string` | One line of plain text, word for word what the callback got when there was one. |
298
300
  | `display` | [`NoticeDisplay`](#noticecode-and-noticedisplay) | Where it went in the callbacks: `"activity"`, `"step"` or `"none"`. |
299
301
  | `documentIds` | `string[]`, optional | The documents the notice is about: those left out (`"documents_missing"`), the one found gone (`"document_gone"`), the one whose pages were not looked at (`"page_looks_busy"`). New in 0.9.0. |
302
+ | `discardText` | `true`, optional | With `"answer_filtered"` under `AskOptions.filteredAnswer: "drop"`: text of the question was already sent (`text` events, `onText`), and the answer is dropped. The page takes away the text it showed for the question, and shows its own message. Absent when no text was sent. See [filtered and cut answers](../guides/errors-and-reliability.md#filtered-and-cut-answers). New in 0.10.0. |
300
303
 
301
304
  #### `run.finish`
302
305
 
@@ -352,7 +355,9 @@ These hold for every run.
352
355
  from being asked for again. `no_room` and `results_shortened` come while a turn is planned,
353
356
  before its `tool.start` events. `room_made`, `nudged` and `answer_again` come after the
354
357
  `request.end` of the request they are about, before the next `request.start`. `blocked` comes
355
- right after the `request.end` of the reply the provider refused.
358
+ right after the `request.end` of the reply the provider refused. `answer_filtered` and
359
+ `answer_cut` come last, right before `run.finish`, after every `text` event of the question
360
+ (new in 0.10.0).
356
361
 
357
362
  ### `RequestRole` and `RequestPurpose`
358
363
 
@@ -386,9 +391,10 @@ How a tool call ended (`tool.end.outcome`):
386
391
  |---|---|
387
392
  | `"ok"` | Ran and returned a result. |
388
393
  | `"error"` | Ran, or was checked, and returned `{ error }`: bad arguments, a document it cannot read, a regex that took too long, a call that did not arrive whole. Or it was ended because its turn failed (the question was stopped, or a listener threw): then the model was sent nothing. |
389
- | `"refused"` | Was not run, for a limit of the question: its cost, the room left in the conversation, the reads of a whole file. |
394
+ | `"refused"` | Was not run, for a limit of the question: its cost, the room left in the conversation, the reads of a whole file. Since 0.10.0 also a call of a tool the question does not have, and a result that `AskOptions.onToolResult` rejected (`{ reject }`): the model was sent the error. |
390
395
  | `"already_shown"` | Repeated a call whose result is still in the conversation, and was answered with a pointer to it. |
391
396
  | `"not_run"` | Was over `limits.callsPerTurn` for its turn. |
397
+ | `"redacted"` | Ran, and `AskOptions.onToolResult` replaced its result: the model was sent the replacement, with `redacted: true`. `evidence`, `step`, `resultCharacters` and `result` tell the replacement. New in 0.10.0. |
392
398
 
393
399
  ### `NoticeCode` and `NoticeDisplay`
394
400
 
@@ -405,19 +411,21 @@ to `onStep` and `AskResult.steps`, `"none"` to neither. The `"none"` notices are
405
411
  | `"results_shortened"` | step | Older tool results were shortened to make room. | "Older tool results were shortened to make room in the request" |
406
412
  | `"answer_again"` | step | The answer came back without text and was asked for again. | "The model's answer was empty: it was asked again", "The model called a tool instead of answering: it was asked again for the answer" |
407
413
  | `"calls_not_run"` | step | A turn had more calls than `limits.callsPerTurn`. | "2 more tool calls in this turn were not run (at most 8 a turn)" |
408
- | `"budget_reached"` | none | `limits.inputTokens` or `limits.requests` was reached, so no more tools run, or the answer is not asked for again. Once a question. | "No more tools: the question reached its limit of input tokens or requests." |
414
+ | `"budget_reached"` | none | The ceiling of input tokens (`limits.inputTokens`, or the default since 0.10.0: the next tool request and the answer would pass it) or `limits.requests` was reached, so no more tools run, or the answer is not asked for again. Once a question. | "No more tools: the question reached its limit of input tokens or requests." |
409
415
  | `"no_room"` | none | There is no room left in the conversation for another tool result. Once a question. | "There is no room left in this conversation for another tool result." |
410
416
  | `"blocked"` | none | The provider refused the prompt (`AskResult.blockReason`). | "The provider refused the prompt: SAFETY." |
411
417
  | `"documents_missing"` | none | Documents of `documentIds` were missing, and the question is answered without them (`onMissingDocuments: "drop"`, see [missing documents](./ask.md#missing-documents)). Before the `plan` event, once a question. `documentIds` names them; `AskResult.missing` lists them too. New in 0.9.0. | "1 of the attached files is no longer available: the question is answered without it." |
412
418
  | `"document_gone"` | none | A tool call found a document gone during the question: deleted or expired since it was planned. The model was told so in the call's result ("‹id› is no longer available on the server. Ask the user to attach the file again."). Once for each document. `documentIds` names it. New in 0.9.0. | "app.log is no longer available on the server." |
413
419
  | `"page_looks_busy"` | none | A look at pages waited longer than `pageLookWaitMs` for its turn (`maxConcurrentPageLooks`, [library](./library.md#largefilesoptions)) and was not run. The model was told the server is busy. `documentIds` names the PDF. New in 0.9.0. | "The pages of report.pdf were not looked at: the server was busy with other looks at pages." |
420
+ | `"answer_filtered"` | none | A filter of the provider stopped the answer, with or without text (`AskResult.finish` `"filtered"`). Right before `run.finish`. With `filteredAnswer: "drop"`, `discardText` says when text was already sent. New in 0.10.0. | "A filter of the provider stopped the answer before it was finished.", "… before any text came.", or under `"drop"` "… before it was finished: its text was dropped." |
421
+ | `"answer_cut"` | none | The answer stopped at the output limit (`AskResult.finish` `"cut"`). Right before `run.finish`. The answer is kept. New in 0.10.0. | "The answer stopped at the model's output limit, so it is incomplete.", or "… before any text came." |
414
422
 
415
423
  The messages are written for people and may change between versions. Test `code`, not `message`.
416
424
 
417
425
  New codes come with new versions: 0.9.0 added `"documents_missing"`, `"document_gone"` and
418
- `"page_looks_busy"`. In TypeScript, a `switch` over `NoticeCode` that must handle every code (one
419
- with a `never` check in its `default`) no longer compiles until it handles them. Give such a switch
420
- a `default` that shows nothing, or the message.
426
+ `"page_looks_busy"`, and 0.10.0 `"answer_filtered"` and `"answer_cut"`. In TypeScript, a `switch`
427
+ over `NoticeCode` that must handle every code (one with a `never` check in its `default`) no longer
428
+ compiles until it handles them. Give such a switch a `default` that shows nothing, or the message.
421
429
 
422
430
  ### How the callbacks map to events
423
431
 
@@ -504,13 +512,20 @@ text of the documents:
504
512
  ```ts
505
513
  type EventResult = Omit<AskResult, "toolTurns" | "plan"> & {
506
514
  toolTurns?: ToolTurn[];
507
- plan: { inline: Array<DocumentRef | DocumentMeta>; searchable: Array<DocumentRef | DocumentMeta> };
515
+ // Since 0.10.0 the full metadata here has no owner, scope, sha256, original or metaVersion, in its
516
+ // type (DocumentMeta before) and at run time.
517
+ plan: {
518
+ inline: Array<DocumentRef | Omit<DocumentMeta, "owner" | "scope" | "sha256" | "original" | "metaVersion">>;
519
+ searchable: Array<DocumentRef | Omit<DocumentMeta, "owner" | "scope" | "sha256" | "original" | "metaVersion">>;
520
+ };
508
521
  };
509
522
  ```
510
523
 
511
524
  With `eventResults: true`, `tool.end.result` is the result the model was sent, and
512
525
  `run.finish.result` and `run.error.partial` have `toolTurns` and the full plan. Use it for a log or an
513
- audit trail on your server, not for a browser. The result `askWithFiles` returns, `askStream`'s
526
+ audit trail on your server, not for a browser. Since 0.10.0 even that plan has no `owner`, `scope`,
527
+ `sha256`, `original` or `metaVersion`: they stay on the server. Read them from `AskResult.plan`,
528
+ which keeps the full metadata. The result `askWithFiles` returns, `askStream`'s
514
529
  `result`, and `partialResultOf(error)` always have `toolTurns`: keep them from there, with the
515
530
  conversation.
516
531
 
@@ -970,6 +985,7 @@ type ToolCallHooks = {
970
985
  onRequest?: (request: ToolRequestStart) => ToolRequestHandle;
971
986
  onDocumentGone?: (documentId: string) => void; // new in 0.9.0
972
987
  onPagesBusy?: (documentId: string) => void; // new in 0.9.0
988
+ signal?: AbortSignal; // new in 0.10.0
973
989
  };
974
990
  type ToolRequestStart = { purpose: "part" | "merge" | "final"; detail: string };
975
991
  type ToolRequestHandle = {
@@ -985,6 +1001,7 @@ type ToolRequestEnd = { outcome: "ok" | "error"; usage?: GenerateUsage; error?:
985
1001
  | `onRequest` | `(request: ToolRequestStart) => ToolRequestHandle` | Called as each model request of this call starts, with its `purpose` and `detail` (`"part 3 of 12"`, `"first half of part 3 of 12"`, `"round 2: 1 of 4"`, `"the answer"`). The handle you return is told of each retry of that request, and once of its end, with the usage its part reader reported (summed over its sends) and, on an error, the error. |
986
1002
  | `onDocumentGone` | `(documentId: string) => void` | Called when the document the call names is no longer in the store: deleted or expired since it was planned, or not the caller's. The call's result is the error the model is told. `askWithFiles` makes it a `"document_gone"` notice. New in 0.9.0. |
987
1003
  | `onPagesBusy` | `(documentId: string) => void` | Called when a look at pages (`view_pages`) waited longer than `pageLookWaitMs` for its turn and was not run. The call's result is the error the model is told. `askWithFiles` makes it a `"page_looks_busy"` notice. New in 0.9.0. |
1004
+ | `signal` | `AbortSignal` | Ends this call alone: its scans, regex searches, whole-file read, look at pages and loads. Joined with `ToolOptions.signal`. New in 0.10.0. |
988
1005
 
989
1006
  `onProgress` and `onRequest` are used only by `analyze_whole_document`; the other tools ignore
990
1007
  them, and `view_pages` too. `onDocumentGone` is called by every tool, and `onPagesBusy` by
@@ -8,7 +8,7 @@ helpers for a tool loop of your own. How to set Gemini up for production is in t
8
8
 
9
9
  ```ts
10
10
  import { askGemini, gemini, geminiApi, vertexAi } from "llm-large-files/gemini";
11
- import type { AskGeminiOptions, GeminiContent, GeminiEndpoint, GeminiModelOptions } from "llm-large-files/gemini";
11
+ import type { AskGeminiOptions, GeminiContent, GeminiEndpoint, GeminiModelOptions, GeminiRequestFields } from "llm-large-files/gemini";
12
12
  ```
13
13
 
14
14
  The entry point needs no Google SDK: it posts to the Generate Content REST API with `fetch`.
@@ -16,11 +16,14 @@ The entry point needs no Google SDK: it posts to the Generate Content REST API w
16
16
  ## Contents
17
17
 
18
18
  - [Endpoints](#endpoints): [`geminiApi()`](#geminiapioptions), [`vertexAi()`](#vertexaioptions),
19
- [`vertexHost()`](#vertexhostlocation), [`GeminiEndpoint`](#geminiendpoint)
19
+ [`VertexAiOptions`](#vertexaioptions-1), [`vertexHost()`](#vertexhostlocation),
20
+ [`GeminiEndpoint`](#geminiendpoint)
20
21
  - [Asking a question](#asking-a-question): [`askGemini()`](#askgeminioptions),
21
- [`AskGeminiOptions`](#askgeminioptions-1), [`AskGeminiResult`](#askgeminiresult)
22
+ [`AskGeminiOptions`](#askgeminioptions-1), [`GeminiOwnOptions`](#geminiownoptions),
23
+ [`AskGeminiResult`](#askgeminiresult)
22
24
  - [The model adapter](#the-model-adapter): [`gemini()`](#geminiendpoint-options),
23
- [`GeminiModelOptions`](#geminimodeloptions), [`GEMINI_PAGE_TOKENS`](#gemini_page_tokens)
25
+ [`GeminiModelOptions`](#geminimodeloptions), [`GeminiRequestFields`](#geminirequestfields),
26
+ [`GEMINI_PAGE_TOKENS`](#gemini_page_tokens)
24
27
  - [Gemini contents](#gemini-contents): [`fromGeminiContents()`](#fromgeminicontentscontents-options),
25
28
  [`FromGeminiContentsOptions`](#fromgeminicontentsoptions),
26
29
  [`geminiToolTurns()`](#geminitoolturnsturns), [`GeminiContent`](#geminicontent),
@@ -93,40 +96,40 @@ Guides: [Gemini API and Vertex AI](../guides/vertex-and-gemini.md),
93
96
  ### vertexAi(options)
94
97
 
95
98
  ```ts
96
- declare function vertexAi(options: {
97
- project: string;
98
- model: string;
99
- explorerModel?: string | undefined;
100
- location?: string;
101
- accessToken: string | (() => string | Promise<string>);
102
- apiVersion?: string;
103
- }): GeminiEndpoint;
99
+ declare function vertexAi(options: VertexAiOptions): GeminiEndpoint;
104
100
  ```
105
101
 
106
- The endpoint of a Gemini model on Vertex AI, signed in with an OAuth access token.
102
+ The endpoint of a Gemini model on Vertex AI, signed in with an OAuth access token, or, since
103
+ 0.10.0, with an API key of Vertex AI express mode.
107
104
 
108
105
  | Option | Type | Default | What it does |
109
106
  |---|---|---|---|
110
- | `project` | `string` | required | The Google Cloud project ID. URL-encoded into the path. |
107
+ | `project` | `string` | required with `accessToken` | The Google Cloud project ID. URL-encoded into the path. Not with `apiKey`. |
111
108
  | `model` | `string` | required | The model that answers, under `publishers/google/models/`. Without an explorer it also makes the tool calls. |
112
109
  | `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. |
113
- | `location` | `string` | `"global"` | Where the requests are served. It picks the host ([`vertexHost()`](#vertexhostlocation)) and is the `locations/{location}` segment of the path. It must be lowercase letters, digits and single hyphens (`"global"`, `"us"`, `"europe-west4"`): anything else throws a `TypeError`, since 0.7.1. |
114
- | `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. |
110
+ | `location` | `string` | `"global"` | Where the requests are served. It picks the host ([`vertexHost()`](#vertexhostlocation)) and is the `locations/{location}` segment of the path. It must be lowercase letters, digits and single hyphens (`"global"`, `"us"`, `"europe-west4"`): anything else throws a `TypeError`, since 0.7.1. Not with `apiKey`. |
111
+ | `accessToken` | `string \| ((context: { refresh: boolean }) => string \| Promise<string>)` | required without `apiKey` | 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. Since 0.10.0 it is called with `{ refresh: true }` when the token it gave was refused with HTTP 401: return a new token then, not the one kept in a cache. A function of no arguments still fits. |
112
+ | `apiKey` | `string` | none | The API key of Vertex AI express mode, sent as the `x-goog-api-key` header. The URL then names no project or location: `{host}/{apiVersion}/publishers/google/models/{model}:generateContent`. Give `apiKey` or `project` and `accessToken`, not both. New in 0.10.0. |
113
+ | `headers` | `Record<string, string>` or a function that returns them | none | More headers, merged after the library's: a name you give replaces the library's. A function is called before every request with the context the endpoint's `headers` get (`{ refresh: true }` after a 401). New in 0.10.0. |
114
+ | `host` | `string` | the host of `location` | The https origin to send the requests to: a Private Service Connect endpoint, or a proxy that keeps Vertex AI's paths. `"https://host"` or `"https://host:port"`, with a slash at the end or none, and nothing more: a path, a query, a fragment, an `@` or another scheme throws a `TypeError`, as a bad `location` does, since the token would go to another host. New in 0.10.0. |
115
115
  | `apiVersion` | `string` | `"v1"` | The version segment of the path. |
116
116
 
117
117
  It returns:
118
118
 
119
119
  | Field | Value |
120
120
  |---|---|
121
- | `url` | `{vertexHost(location)}/{apiVersion}/projects/{project}/locations/{location}/publishers/google/models/{model}:generateContent` |
121
+ | `url` | `{host}/{apiVersion}/projects/{project}/locations/{location}/publishers/google/models/{model}:generateContent`, where `host` is `vertexHost(location)` unless given; with `apiKey`, `{host}/{apiVersion}/publishers/google/models/{model}:generateContent` |
122
122
  | `streamUrl` | The same, ending in `:streamGenerateContent?alt=sse` |
123
- | `headers` | An async function that returns `{ "Content-Type": "application/json", Authorization: "Bearer {token}" }` |
123
+ | `headers` | An async function that returns `{ "Content-Type": "application/json", Authorization: "Bearer {token}" }` (with `apiKey`, `"x-goog-api-key": apiKey` in place of `Authorization`), then the fields of `headers` |
124
124
  | `explorerUrl` | The `:generateContent` URL of `explorerModel`, only when an explorer is named. Otherwise the field is absent. |
125
+ | `refreshable` | `true` when `accessToken` is a function, new in 0.10.0: a request refused with HTTP 401 is sent once more with a new token. Absent for a token given as a string, and for `apiKey`. |
125
126
 
126
127
  It makes no request and does not call `accessToken`. An error that the token function throws comes
127
128
  out of the request that needed the token, as it was thrown: it is not a `GeminiRequestError`. It
128
129
  has no status, so a chat request is not sent again: `askGemini`, or `askWithFiles` with `gemini()`,
129
- throws it. A part read is tried once more, and then counts as unread.
130
+ throws it. A part read is tried once more, and then counts as unread. One exception: when the
131
+ function throws as it is called with `{ refresh: true }` after a 401, the request's error is that
132
+ 401 (a `GeminiRequestError` of kind `"auth"`), with what the function threw as its `cause`.
130
133
 
131
134
  ```ts
132
135
  import { GoogleAuth } from "google-auth-library";
@@ -139,12 +142,49 @@ const endpoint = vertexAi({
139
142
  location: "global",
140
143
  model: "gemini-3.8-flash",
141
144
  explorerModel: "gemini-3.5-flash-lite",
142
- accessToken: async () => (await auth.getAccessToken()) ?? "",
145
+ accessToken: async ({ refresh }) => {
146
+ const client = await auth.getClient();
147
+ // The cached token was refused: mark it expired, so that the client fetches a new one.
148
+ if (refresh) client.setCredentials({ ...client.credentials, expiry_date: 1 });
149
+ return (await client.getAccessToken()).token ?? "";
150
+ },
143
151
  });
152
+
153
+ // Express mode: an API key, and no project.
154
+ const express = vertexAi({ apiKey: process.env.VERTEX_API_KEY!, model: "gemini-3.8-flash" });
144
155
  ```
145
156
 
146
157
  Guide: [Gemini API and Vertex AI](../guides/vertex-and-gemini.md), which covers access tokens.
147
158
 
159
+ ### `VertexAiOptions`
160
+
161
+ ```ts
162
+ type VertexAiOptions =
163
+ | {
164
+ project: string;
165
+ location?: string;
166
+ accessToken: string | ((context: { refresh: boolean }) => string | Promise<string>);
167
+ model: string;
168
+ explorerModel?: string | undefined;
169
+ headers?: HeaderSource | undefined;
170
+ host?: string | undefined;
171
+ apiVersion?: string;
172
+ }
173
+ | {
174
+ apiKey: string;
175
+ model: string;
176
+ explorerModel?: string | undefined;
177
+ headers?: HeaderSource | undefined;
178
+ host?: string | undefined;
179
+ apiVersion?: string;
180
+ };
181
+ // HeaderSource = Record<string, string> | ((context?: { refresh?: boolean }) => Record<string, string> | Promise<Record<string, string>>)
182
+ ```
183
+
184
+ The options of [`vertexAi()`](#vertexaioptions): a project with a token, or an API key of express
185
+ mode. The type refuses a project with an API key, and a project without a token. New as a type of
186
+ its own in 0.10.0.
187
+
148
188
  ### vertexHost(location)
149
189
 
150
190
  ```ts
@@ -170,8 +210,9 @@ Use it to build the URLs of a [`GeminiEndpoint`](#geminiendpoint) of your own on
170
210
  type GeminiEndpoint = {
171
211
  url: string;
172
212
  streamUrl?: string;
173
- headers: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
213
+ headers: Record<string, string> | ((context?: { refresh?: boolean }) => Record<string, string> | Promise<Record<string, string>>);
174
214
  explorerUrl?: string | undefined;
215
+ refreshable?: true | undefined;
175
216
  };
176
217
  ```
177
218
 
@@ -181,8 +222,9 @@ Where a Gemini model is and how to call it.
181
222
  |---|---|---|---|
182
223
  | `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. |
183
224
  | `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. |
184
- | `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. |
225
+ | `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. Since 0.10.0 it may take a context: it is called with `{ refresh: true }` when a request of a `refreshable` endpoint is sent again after a 401, and with nothing otherwise. `gemini()` adds no header of its own: give `"Content-Type": "application/json"`, as `geminiApi()` and `vertexAi()` do. |
185
226
  | `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. |
227
+ | `refreshable` | `true \| undefined` | none | `headers({ refresh: true })` gives a token that is new, not the one it keeps in a cache: a request refused with HTTP 401 is sent once more with those headers, in chat requests, part reads and askGemini's explorer alike. A second 401 is the error: there is no third try. `vertexAi()` sets it when `accessToken` is a function. New in 0.10.0. |
186
228
 
187
229
  An endpoint for a gateway that proxies Generate Content:
188
230
 
@@ -222,6 +264,10 @@ tools asks for it. When that reply has no text (it is empty, or ends with `UNEXP
222
264
  `MALFORMED_FUNCTION_CALL`), it is asked for once more. `answered` is false when there is still no
223
265
  text: a blocked prompt, which gets no last request, or an empty or cut-off reply.
224
266
 
267
+ Since 0.10.0 `askGemini` takes every option of `askWithFiles` by its type, and gives the ones it does
268
+ not use itself to `askWithFiles` as they are: an option new in `askWithFiles` reaches the loop with no
269
+ change to `askGemini`.
270
+
225
271
  `askGemini` cannot set `contextTokens`, `maxRequestBytes`, `pageTokens` or `id` on its models. Put
226
272
  the model's window in the library's budget, or use `askWithFiles` with
227
273
  [`gemini()`](#geminiendpoint-options), which also takes an explorer of another provider or on
@@ -265,14 +311,19 @@ Guide: [Gemini API and Vertex AI](../guides/vertex-and-gemini.md).
265
311
 
266
312
  ### `AskGeminiOptions`
267
313
 
314
+ ```ts
315
+ type AskGeminiOptions = Omit<AskOptions, "model" | "explorer" | "messages"> & GeminiOwnOptions;
316
+ ```
317
+
268
318
  The options of `askGemini`. `AskOptions.model` and `AskOptions.explorer` are not here: `endpoint`
269
319
  takes their place.
270
320
 
271
- Shared with [`AskOptions`](./ask.md#askoptions), with the same meaning and defaults: `files`,
272
- `documentIds`, `documentPlacement`, `system`, `owner`, `limits`, `retry`, `budget`,
273
- `wholeDocumentAnalysis`, `viewPages`, `onText`, `onActivity`, `onStep`, `signal`, and, new in 0.7.0,
274
- `streamText`, `onEvent`, `runId` and `eventResults` (see [events](./events.md)), and, new in 0.9.0,
275
- `scope` and `onMissingDocuments` ([missing documents](./ask.md#missing-documents)). With Gemini:
321
+ Every other option of [`AskOptions`](./ask.md#askoptions) is one of `askGemini`, with the same
322
+ meaning and default, and goes to `askWithFiles` as it is. Since 0.10.0 the type says so itself
323
+ (before, `askGemini` listed each option by hand); no option was removed. Among them: `files`,
324
+ `documentIds`, `documentPlacement`, `system`, `owner`, `scope`, `onMissingDocuments`, `limits`,
325
+ `retry`, `budget`, `wholeDocumentAnalysis`, `viewPages`, `onText`, `streamText`, `onActivity`,
326
+ `onStep`, `onEvent`, `runId`, `eventResults`, `signal`, and those new in 0.10.0. With Gemini:
276
327
 
277
328
  - `messages` is optional and typed [`ChatMessage[]`](./ask.md#chatmessage), as in `askWithFiles`:
278
329
  plain turns, the `toolTurns` of earlier questions, and turns with parts, such as
@@ -286,7 +337,7 @@ Shared with [`AskOptions`](./ask.md#askoptions), with the same meaning and defau
286
337
  - `limits` is merged with `maxToolTurns` and `maxToolCallsPerTurn` (below). A field of `limits`
287
338
  wins.
288
339
 
289
- Fields `askGemini` adds:
340
+ Fields `askGemini` adds, its own (`GeminiOwnOptions`):
290
341
 
291
342
  | Field | Type | Default | What it does |
292
343
  |---|---|---|---|
@@ -301,6 +352,20 @@ Fields `askGemini` adds:
301
352
  | `maxToolTurns` | `number` | 12 | `limits.toolTurns`, under the name it had before 0.5.0. `limits.toolTurns` wins when both are set. |
302
353
  | `maxToolCallsPerTurn` | `number` | 8 | `limits.callsPerTurn`, under the name it had before 0.5.0. `limits.callsPerTurn` wins when both are set. |
303
354
  | `fetch` | `typeof fetch` | the global `fetch` | Used for every request of both models, part reads included: a proxy, logging, tests. |
355
+ | `body` | [`GeminiRequestFields`](#geminirequestfields) | none | More fields for the body of every chat request of the answering model, and of the explorer unless `explorerBody` is set: `safetySettings`, `labels`, `serviceTier`, `cachedContent`. Merged last. Not used for part reads. New in 0.10.0. |
356
+ | `explorerBody` | [`GeminiRequestFields`](#geminirequestfields) | `body` | The same, for the explorer's chat requests. Not used without an explorer. New in 0.10.0. |
357
+ | `analysisBody` | `(maxOutputTokens: number) => GeminiRequestFields` | none | More fields for the body of each part read of a whole-file read, for both models. New in 0.10.0. |
358
+ | `functionCallingMode` | `"AUTO" \| "VALIDATED"` | `"AUTO"` | The `functionCallingConfig` mode of the requests that offer tools, for both models. New in 0.10.0. |
359
+ | `answerWithoutTools` | `"omit" \| "mode_none"` | `"omit"` | How the request for the answer in text says so, for both models ([`GeminiModelOptions`](#geminimodeloptions)). New in 0.10.0. |
360
+ | `timeoutMs` | `number` | `180_000` | The longest time of one part read of a whole-file read, for both models. 0 sets none. New in 0.10.0. |
361
+
362
+ ### `GeminiOwnOptions`
363
+
364
+ The options of `askGemini` that are not `askWithFiles`'s: `endpoint`, `messages` (optional here),
365
+ `contents`, `generationConfig`, `explorerGenerationConfig`, `body`, `explorerBody`, `analysisBody`,
366
+ `functionCallingMode`, `answerWithoutTools`, `timeoutMs`, `maxToolTurns`, `maxToolCallsPerTurn`,
367
+ `toolFilePlacement`, `analysisConfig`, `firstByteTimeoutMs`, `idleTimeoutMs` and `fetch`, as
368
+ described above. New as a type of its own in 0.10.0.
304
369
 
305
370
  `askGemini` has no stream form of its own. To read its events with `for await`, as
306
371
  [`askStream`](./ask.md#askstreamoptions) gives them for `askWithFiles`, wrap it in
@@ -356,7 +421,7 @@ Guide: [errors and reliability](../guides/errors-and-reliability.md).
356
421
 
357
422
  ```ts
358
423
  declare function gemini(
359
- endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "headers">,
424
+ endpoint: Pick<GeminiEndpoint, "url" | "streamUrl" | "headers" | "refreshable">,
360
425
  options?: GeminiModelOptions,
361
426
  ): ModelAdapter;
362
427
  ```
@@ -375,15 +440,19 @@ The adapter it returns:
375
440
  | `capabilities` | `toolFiles` from `toolFilePlacement` (`"inside"`), `pageTokens` (530), and `contextTokens` and `maxRequestBytes` when they are set. No `tokenScale` (so 1), no `outputTokens`, not `appendOnly`. |
376
441
  | `send(request, hooks?)` | One chat request: to `streamUrl` when `hooks.onText` is given and the endpoint has one, otherwise to `url`. |
377
442
  | `requestBytes(request)` | The size in bytes of the JSON body that `send` would post. |
378
- | `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. |
443
+ | `generateText` | The part reader of whole-file reads: [`createGeminiGenerateText()`](#creategeminigeneratetextoptions) on `endpoint.url`, with `analysisConfig`, `analysisBody`, `timeoutMs`, `fetch` and the endpoint's `refreshable`. `askWithFiles` uses it when this model is the one that explores. Each of its requests may take `timeoutMs` (180 s); before 0.10.0, `gemini()` had no option to change that. |
379
444
 
380
445
  What `send` does:
381
446
 
382
447
  - It asks for the headers before every request.
383
448
  - The body holds `contents`; `systemInstruction` when the system instruction is not empty;
384
- `generationConfig` when it is set; and, when tools are offered, `tools: [{ functionDeclarations }]`
385
- with `toolConfig: { functionCallingConfig: { mode: "AUTO" } }`. A request that must be answered in
386
- text declares no tools at all, because Gemini can ignore mode `NONE` and go on calling them.
449
+ `generationConfig` when it is set; when tools are offered, `tools: [{ functionDeclarations }]`
450
+ with `toolConfig: { functionCallingConfig: { mode } }`, the mode being `functionCallingMode`
451
+ (`"AUTO"`); and last, the fields of `body`. A request that must be answered in text declares no
452
+ tools at all by default, because Gemini can ignore mode `NONE` and go on calling them; with
453
+ `answerWithoutTools: "mode_none"` it keeps them, with mode `NONE`.
454
+ - A request refused with HTTP 401 by a `refreshable` endpoint is sent once more, with the headers of
455
+ `headers({ refresh: true })`. A second 401 is the error. New in 0.10.0.
387
456
  - A model turn of the question goes back unchanged, thought signatures included, in the later
388
457
  requests to the same adapter. Another model of the question gets it rebuilt from its calls, as a
389
458
  stored tool round (`toolTurns`) is.
@@ -393,18 +462,29 @@ What `send` does:
393
462
  drops `?alt=sse`, or does not stream, is read whole (since 0.6.0; 0.5.0 read it as an empty
394
463
  reply). A body that starts with more than 65,536 characters of white space is read in one piece.
395
464
  - Parts marked `"thought": true` are not in the reply's `text` and are not passed to `onText`.
396
- - Gemini's `finishReason` becomes the reply's `finish`: `STOP` is `"complete"`; `MAX_TOKENS` is
397
- `"cut"`; `SAFETY`, `RECITATION`, `BLOCKLIST`, `PROHIBITED_CONTENT`, `SPII` and `IMAGE_SAFETY` are
398
- `"filtered"`; `MALFORMED_FUNCTION_CALL` and `UNEXPECTED_TOOL_CALL` are `"malformed_call"`.
399
- `promptFeedback.blockReason` becomes `blockReason`, and `usageMetadata` becomes `usage`
400
- ([`usageOfGemini()`](#usageofgeminiusage)) and `providerUsage`.
465
+ - Gemini's `finishReason` becomes the reply's `finish`, and stays as it came in `finishReason`:
466
+
467
+ | `finishReason` | `finish` |
468
+ |---|---|
469
+ | `STOP` | `"complete"` |
470
+ | `MAX_TOKENS` | `"cut"` |
471
+ | `SAFETY`, `RECITATION`, `BLOCKLIST`, `PROHIBITED_CONTENT`, `SPII`, `IMAGE_SAFETY`; since 0.10.0 `MODEL_ARMOR`, `IMAGE_PROHIBITED_CONTENT`, `IMAGE_RECITATION`, `IMAGE_OTHER` | `"filtered"` |
472
+ | `MALFORMED_FUNCTION_CALL`, `UNEXPECTED_TOOL_CALL`; since 0.10.0 `MALFORMED_RESPONSE` | `"malformed_call"` |
473
+ | Since 0.10.0: `OTHER`, `FINISH_REASON_UNSPECIFIED`, `NO_IMAGE`, `TOO_MANY_TOOL_CALLS`, `MISSING_THOUGHT_SIGNATURE`, `LANGUAGE` | `"other"` |
474
+ | Any other | none |
475
+
476
+ `LANGUAGE` (a language the model does not take) is `"other"`, not `"filtered"`: it is no safety
477
+ filter. Before 0.10.0 the reasons new to the table gave no `finish`.
478
+ `promptFeedback.blockReason` becomes `blockReason`, `usageMetadata` becomes `usage`
479
+ ([`usageOfGemini()`](#usageofgeminiusage)) and `providerUsage`, and, since 0.10.0, `responseId`
480
+ and `modelVersion` become `responseId` and `responseModel`.
401
481
 
402
482
  `send` throws, and sends nothing again itself: `askWithFiles` decides what is retried.
403
483
 
404
484
  | Case | Error | `status` | `kind` |
405
485
  |---|---|---|---|
406
486
  | 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` |
407
- | An error object inside the stream | `GeminiRequestError` with its message | Its `code` when that is a number, else the response's | As above |
487
+ | An error object inside the stream, or in a reply of HTTP 200 that is not streamed | `GeminiRequestError` with its message, or "Gemini reported an error." | Its `code` when that is a number; else, since 0.10.0, the status of its `google.rpc` name (`"UNAVAILABLE"` 503, `"RESOURCE_EXHAUSTED"` 429, `"DEADLINE_EXCEEDED"` 504, `"INVALID_ARGUMENT"` 400 …); else 500. Before 0.10.0, the response's 200, so it was not sent again. | As above |
408
488
  | 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"` |
409
489
  | 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"` |
410
490
  | Nothing arrived for a whole wait | `GeminiRequestError`: "Gemini sent nothing for 600 s." | 0 | `"timeout"` |
@@ -416,7 +496,9 @@ What `send` does:
416
496
 
417
497
  For an HTTP error, `retryAfterMs` is the wait Gemini asked for: the `retry-after-ms` or
418
498
  `Retry-After` header, or the `retryDelay` of a `google.rpc.RetryInfo` in the error's `details`. An
419
- error inside a stream, or in the body of a response that was OK, has none.
499
+ error inside a stream, or in the body of a response that was OK, has the `retryDelay` of its
500
+ `details` when it has one (since 0.10.0). An error body that is a list (`[{ "error": … }]`) is read
501
+ by its first entry, its message and `details` included (since 0.10.0).
420
502
 
421
503
  ```ts
422
504
  import { askWithFiles } from "llm-large-files";
@@ -454,12 +536,46 @@ The options of `gemini()`.
454
536
  | `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. |
455
537
  | `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. |
456
538
  | `fetch` | `typeof fetch \| undefined` | the global `fetch` | Used for chat requests and part reads. |
539
+ | `body` | [`GeminiRequestFields`](#geminirequestfields) `\| undefined` | none | More fields for the body of every chat request, the request for the answer included, merged last. Counted in `requestBytes`. Not used for part reads. New in 0.10.0. |
540
+ | `analysisBody` | `((maxOutputTokens: number) => GeminiRequestFields) \| undefined` | none | More fields for the body of each part read, given its output limit, merged last. The part reads' `generationConfig` is `analysisConfig`. New in 0.10.0. |
541
+ | `functionCallingMode` | `"AUTO" \| "VALIDATED" \| undefined` | `"AUTO"` | The `functionCallingConfig` mode of a request that offers tools. With `"VALIDATED"`, Gemini checks each call against the declaration of its tool. Sent only with tools. New in 0.10.0. |
542
+ | `answerWithoutTools` | `"omit" \| "mode_none" \| undefined` | `"omit"` | How the request that must be answered in text says so. `"omit"` declares no tools, as before. `"mode_none"` keeps the tools and sends mode `NONE`, so the request starts as the ones before it did; a tool call that still comes back is asked for again once (the loop's `answer_again`). New in 0.10.0. |
543
+ | `timeoutMs` | `number \| undefined` | `180_000` | The longest time, in milliseconds, of one part read, its whole reply included. A part past it is a `GeminiRequestError` of kind `"timeout"` and status 0, sent again once, and then reported as "The model took too long to answer." 0 sets none. New in 0.10.0. |
457
544
 
458
545
  The two waits default to `DEFAULT_FIRST_BYTE_TIMEOUT_MS` and `DEFAULT_IDLE_TIMEOUT_MS`
459
546
  ([errors and retries](./errors-and-retries.md)). What to set them to, and why the first one is
460
547
  long: [Gemini API and Vertex AI](../guides/vertex-and-gemini.md) and
461
548
  [errors and reliability](../guides/errors-and-reliability.md).
462
549
 
550
+ ### `GeminiRequestFields`
551
+
552
+ ```ts
553
+ type GeminiRequestFields = {
554
+ safetySettings?: Array<{ category: string; threshold: string; method?: string }>;
555
+ labels?: Record<string, string>;
556
+ serviceTier?: string;
557
+ cachedContent?: string;
558
+ contents?: never;
559
+ systemInstruction?: never;
560
+ tools?: never;
561
+ toolConfig?: never;
562
+ generationConfig?: never;
563
+ [key: string]: unknown;
564
+ };
565
+ ```
566
+
567
+ What `body`, `explorerBody` and `analysisBody` add to a request body: fields of the Generate
568
+ Content API that the library does not write. They are merged last. The fields the library writes
569
+ are typed `never`, so setting one fails to compile; set `generationConfig` and `analysisConfig` for
570
+ those. Nothing is refused at run time: a field given anyway replaces the library's. New in 0.10.0.
571
+
572
+ | Field | What it is |
573
+ |---|---|
574
+ | `safetySettings` | The thresholds of Gemini's safety filters. A reply a filter stops has `finish` `"filtered"`. |
575
+ | `labels` | Vertex AI only: labels for the billing export, keys and values in lower case, at most 63 characters each. They reach everyone who reads the billing data: never put a user ID, an email or other personal data in them. |
576
+ | `serviceTier` | The service tier of the request, where the API offers one. |
577
+ | `cachedContent` | The name of an explicit context cache (`cachedContents/…`). The library keeps no cache of its own: Gemini 3 caches the start of a request by itself. A request that uses a cache may not set `systemInstruction`, `tools` or `toolConfig` (they must be in the cache), and the library's requests send the system text (part reads included), and tools when they offer them: it fits only requests that send neither ([the guide](../guides/vertex-and-gemini.md#fields-of-your-own-safety-settings-labels-and-more)). |
578
+
463
579
  ### `GEMINI_PAGE_TOKENS`
464
580
 
465
581
  ```ts
@@ -592,10 +708,12 @@ These build Gemini requests in a tool loop of your own, made with `files.prepare
592
708
  ```ts
593
709
  declare function createGeminiGenerateText(options: {
594
710
  url: string;
595
- headers: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
711
+ headers: Record<string, string> | ((context?: { refresh?: boolean }) => Record<string, string> | Promise<Record<string, string>>);
596
712
  fetchImpl?: typeof fetch;
597
713
  generationConfig?: (maxOutputTokens: number) => Record<string, unknown>;
714
+ body?: (maxOutputTokens: number) => GeminiRequestFields;
598
715
  timeoutMs?: number;
716
+ refreshable?: boolean | undefined;
599
717
  }): GenerateText;
600
718
  ```
601
719
 
@@ -608,13 +726,21 @@ completion a whole-file read uses for each part. `gemini()` builds one on its en
608
726
  | `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. |
609
727
  | `fetchImpl` | `typeof fetch` | the global `fetch` | Your own `fetch`. |
610
728
  | `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`. |
611
- | `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. |
729
+ | `body` | `(maxOutputTokens: number) => GeminiRequestFields` | none | More fields for the body of each request, given its output limit, merged last (`gemini({ analysisBody })`). New in 0.10.0. |
730
+ | `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. 0 sets none (since 0.10.0; before, 0 aborted every request at once). |
731
+ | `refreshable` | `boolean` | `false` | A request refused with HTTP 401 is sent once more with the headers of `headers({ refresh: true })`. A second 401 is the error. New in 0.10.0. |
612
732
 
613
733
  Each request posts `contents: [{ role: "user", parts: [{ text: prompt }] }]`, the system
614
- instruction and the `generationConfig`. The text it returns is the reply's text parts without the
734
+ instruction, the `generationConfig` and the fields of `body`. The text it returns is the reply's text parts without the
615
735
  thoughts, joined. `onUsage` gets the usage of every request that was answered
616
736
  ([`usageOfGemini()`](#usageofgeminiusage)). `onTruncated` is called when the reply stopped at
617
- `MAX_TOKENS`, or a safety filter stopped it.
737
+ `MAX_TOKENS`, a filter stopped it, or, since 0.10.0, it ended for a reason whose `finish` is
738
+ `"other"` ([`gemini()`](#geminiendpoint-options)).
739
+
740
+ A reply of HTTP 200 that is a list of chunks, as Gemini answers without `?alt=sse` (a gateway that
741
+ passes such a reply on), is read chunk by chunk, as a chat reply is: its text is that of every
742
+ chunk, and its finish reason and usage are the last ones it has (since 0.10.0; before, the read
743
+ threw "The model returned no text.").
618
744
 
619
745
  When a reply stops at `MAX_TOKENS` with no text, or with half the limit or more spent on thoughts,
620
746
  and the limit was below [`THINKING_OUTPUT_TOKENS`](#thinking_output_tokens), the request is sent
@@ -629,35 +755,24 @@ first request to a `url` goes alone: requests to it that arrive meanwhile wait f
629
755
 
630
756
  | Case | Error |
631
757
  |---|---|
632
- | An HTTP error | `GeminiRequestError` with Gemini's `error.message`, or "The model returned HTTP 503.", with `status`, `kind` and `retryAfterMs` |
758
+ | An HTTP error | `GeminiRequestError` with Gemini's `error.message`, or "The model returned HTTP 503.", with `status`, `kind` and `retryAfterMs`. A body that is a list is read by its first entry (since 0.10.0). |
759
+ | An error in a body of HTTP 200 (a gateway, or Vertex AI), or in any chunk of a list | `GeminiRequestError` with its message, or "Gemini reported an error.", whose `status` is its `code`, else that of its `google.rpc` name, else 500. New in 0.10.0: before, the reply had no text, and the error was "The model returned no text." |
633
760
  | The connection failed, or the body could not be read | `GeminiRequestError`: "Gemini could not be reached (…).", `status` 0 |
634
761
  | A body of HTTP 200 that is empty | `GeminiRequestError`: "Gemini could not be reached (the reply was empty).", `status` 0 |
635
762
  | 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. |
636
- | `timeoutMs` passed, or `signal` aborted | The abort error, as it is, with no status |
763
+ | `timeoutMs` passed | `GeminiRequestError`: "Gemini took longer than 180 s to answer.", `status` 0, kind `"timeout"`, which a whole-file read sends again once. New in 0.10.0: before, the abort error of the timer, with no status. |
764
+ | `signal` aborted | The signal's reason, as it is |
637
765
  | A reply with no text | `Error`: "The model returned no text." or, with its `finishReason`, "The model returned no text (SAFETY)." |
638
766
  | A prompt Gemini blocked: HTTP 200 with `promptFeedback.blockReason` and no candidate | `Error`: "The model returned no text (PROHIBITED_CONTENT).", with the block reason. It is not sent again: it would be blocked again. Before 0.7.1 it had no reason, and a whole-file read sent it once more. |
639
767
 
640
- A whole-file read tries a part once more after an error with no status. It tells the model why a
641
- part failed by the error's kind and status, never by Gemini's message: "The model took too long to
642
- answer." for a request past `timeoutMs`, "The model returned no text (SAFETY)." for a reply with no
643
- text, the reason only when it is a plain word (see
768
+ A whole-file read tries a part once more after an error with no status, and after a timeout. It
769
+ tells the model why a part failed by the error's kind and status, never by Gemini's message: "The
770
+ model took too long to answer." for a request past `timeoutMs`, "The model returned no text
771
+ (SAFETY)." for a reply with no text, the reason only when it is a plain word (see
644
772
  [`analyze_whole_document`](./tools.md#analyze_whole_document)).
645
773
 
646
- `gemini()` gives its part reads no way to change the 180 s. To change it, replace the adapter's
647
- `generateText`:
648
-
649
- ```ts
650
- import type { ModelAdapter } from "llm-large-files";
651
- import { createGeminiGenerateText, gemini } from "llm-large-files/gemini";
652
-
653
- // endpoint as in the vertexAi() sample.
654
- const base = gemini(endpoint);
655
- const model: ModelAdapter = {
656
- ...base,
657
- // Part reads that may take up to five minutes each.
658
- generateText: createGeminiGenerateText({ url: endpoint.url, headers: endpoint.headers, timeoutMs: 300_000 }),
659
- };
660
- ```
774
+ Since 0.10.0 `gemini(endpoint, { timeoutMs })` and `askGemini({ timeoutMs })` set the time of each
775
+ part read: there is no need to replace the adapter's `generateText` for it.
661
776
 
662
777
  Guides: [Gemini API and Vertex AI](../guides/vertex-and-gemini.md),
663
778
  [errors and reliability](../guides/errors-and-reliability.md).
@@ -810,9 +925,10 @@ declare class GeminiRequestError extends ModelRequestError {
810
925
  ```
811
926
 
812
927
  A Gemini request that failed: Gemini answered with an HTTP error, or `status` is 0 because Gemini
813
- could not be reached, sent nothing for a whole wait, or ended a stream before it was complete. A
814
- reply of HTTP 200 that could not be read (not JSON, or an event too long) keeps its 200, with kind
815
- `"invalid"`.
928
+ could not be reached, sent nothing for a whole wait, ended a stream before it was complete, or did
929
+ not answer a part read within `timeoutMs`. A reply of HTTP 200 that could not be read (not JSON, or
930
+ an event too long) keeps its 200, with kind `"invalid"`. An error that came inside a reply of HTTP
931
+ 200 has the status of its code or of its `google.rpc` name (since 0.10.0).
816
932
  `gemini()` throws it for chat requests, and its part reader (`generateText`) for part reads.
817
933
  `askGemini` and `askWithFiles` throw it for a chat request that failed and was not worth another
818
934
  try, or still failed after the retries. A part read that fails is not thrown: the part counts as