llm-large-files 0.8.1 → 0.9.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 (204) hide show
  1. package/CHANGELOG.md +631 -0
  2. package/README.md +9 -10
  3. package/dist/access.d.ts +86 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +131 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/ask.d.ts +45 -1
  8. package/dist/ask.d.ts.map +1 -1
  9. package/dist/ask.js +181 -20
  10. package/dist/ask.js.map +1 -1
  11. package/dist/cache.d.ts +12 -3
  12. package/dist/cache.d.ts.map +1 -1
  13. package/dist/cache.js +18 -5
  14. package/dist/cache.js.map +1 -1
  15. package/dist/encoding.js +5 -3
  16. package/dist/encoding.js.map +1 -1
  17. package/dist/error-info.d.ts +57 -0
  18. package/dist/error-info.d.ts.map +1 -0
  19. package/dist/error-info.js +217 -0
  20. package/dist/error-info.js.map +1 -0
  21. package/dist/errors.d.ts +72 -8
  22. package/dist/errors.d.ts.map +1 -1
  23. package/dist/errors.js +102 -15
  24. package/dist/errors.js.map +1 -1
  25. package/dist/events.d.ts +35 -9
  26. package/dist/events.d.ts.map +1 -1
  27. package/dist/events.js +42 -11
  28. package/dist/events.js.map +1 -1
  29. package/dist/evidence.d.ts +4 -2
  30. package/dist/evidence.d.ts.map +1 -1
  31. package/dist/evidence.js +14 -3
  32. package/dist/evidence.js.map +1 -1
  33. package/dist/extract.d.ts +32 -8
  34. package/dist/extract.d.ts.map +1 -1
  35. package/dist/extract.js +46 -35
  36. package/dist/extract.js.map +1 -1
  37. package/dist/gemini/adapter.d.ts +19 -3
  38. package/dist/gemini/adapter.d.ts.map +1 -1
  39. package/dist/gemini/adapter.js +84 -12
  40. package/dist/gemini/adapter.js.map +1 -1
  41. package/dist/gemini/chat.d.ts +18 -6
  42. package/dist/gemini/chat.d.ts.map +1 -1
  43. package/dist/gemini/chat.js +2 -0
  44. package/dist/gemini/chat.js.map +1 -1
  45. package/dist/gemini/index.d.ts +1 -1
  46. package/dist/gemini/index.d.ts.map +1 -1
  47. package/dist/index.d.ts +9 -6
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +4 -3
  50. package/dist/index.js.map +1 -1
  51. package/dist/ingest.d.ts +70 -0
  52. package/dist/ingest.d.ts.map +1 -0
  53. package/dist/ingest.js +868 -0
  54. package/dist/ingest.js.map +1 -0
  55. package/dist/library.d.ts +176 -34
  56. package/dist/library.d.ts.map +1 -1
  57. package/dist/library.js +332 -512
  58. package/dist/library.js.map +1 -1
  59. package/dist/limiter.d.ts +2 -2
  60. package/dist/limiter.js +2 -2
  61. package/dist/map-reduce.js +3 -3
  62. package/dist/map-reduce.js.map +1 -1
  63. package/dist/model.d.ts +43 -2
  64. package/dist/model.d.ts.map +1 -1
  65. package/dist/model.js +63 -3
  66. package/dist/model.js.map +1 -1
  67. package/dist/node/handlers.d.ts +234 -7
  68. package/dist/node/handlers.d.ts.map +1 -1
  69. package/dist/node/handlers.js +482 -121
  70. package/dist/node/handlers.js.map +1 -1
  71. package/dist/node/index.d.ts +3 -2
  72. package/dist/node/index.d.ts.map +1 -1
  73. package/dist/node/index.js +2 -1
  74. package/dist/node/index.js.map +1 -1
  75. package/dist/node/ingest-child.d.ts +7 -1
  76. package/dist/node/ingest-child.d.ts.map +1 -1
  77. package/dist/node/ingest-child.js +18 -3
  78. package/dist/node/ingest-child.js.map +1 -1
  79. package/dist/node/isolated.d.ts +3 -1
  80. package/dist/node/isolated.d.ts.map +1 -1
  81. package/dist/node/isolated.js +11 -4
  82. package/dist/node/isolated.js.map +1 -1
  83. package/dist/node/originals.d.ts +19 -0
  84. package/dist/node/originals.d.ts.map +1 -0
  85. package/dist/node/originals.js +82 -0
  86. package/dist/node/originals.js.map +1 -0
  87. package/dist/node/spool.d.ts +102 -0
  88. package/dist/node/spool.d.ts.map +1 -0
  89. package/dist/node/spool.js +365 -0
  90. package/dist/node/spool.js.map +1 -0
  91. package/dist/node/sse.d.ts +4 -3
  92. package/dist/node/sse.d.ts.map +1 -1
  93. package/dist/node/sse.js +7 -6
  94. package/dist/node/sse.js.map +1 -1
  95. package/dist/pdf-layout.d.ts.map +1 -1
  96. package/dist/pdf-layout.js +71 -12
  97. package/dist/pdf-layout.js.map +1 -1
  98. package/dist/ranged.d.ts +22 -11
  99. package/dist/ranged.d.ts.map +1 -1
  100. package/dist/ranged.js +50 -12
  101. package/dist/ranged.js.map +1 -1
  102. package/dist/retry.d.ts +3 -1
  103. package/dist/retry.d.ts.map +1 -1
  104. package/dist/retry.js +6 -2
  105. package/dist/retry.js.map +1 -1
  106. package/dist/scope.d.ts +25 -0
  107. package/dist/scope.d.ts.map +1 -0
  108. package/dist/scope.js +60 -0
  109. package/dist/scope.js.map +1 -0
  110. package/dist/source.d.ts +60 -0
  111. package/dist/source.d.ts.map +1 -0
  112. package/dist/source.js +170 -0
  113. package/dist/source.js.map +1 -0
  114. package/dist/stores.d.ts +120 -31
  115. package/dist/stores.d.ts.map +1 -1
  116. package/dist/stores.js +582 -139
  117. package/dist/stores.js.map +1 -1
  118. package/dist/testing/fake-fetch.d.ts +31 -0
  119. package/dist/testing/fake-fetch.d.ts.map +1 -0
  120. package/dist/testing/fake-fetch.js +66 -0
  121. package/dist/testing/fake-fetch.js.map +1 -0
  122. package/dist/testing/fake-model.d.ts +38 -0
  123. package/dist/testing/fake-model.d.ts.map +1 -0
  124. package/dist/testing/fake-model.js +62 -0
  125. package/dist/testing/fake-model.js.map +1 -0
  126. package/dist/testing/index.d.ts +7 -0
  127. package/dist/testing/index.d.ts.map +1 -0
  128. package/dist/testing/index.js +9 -0
  129. package/dist/testing/index.js.map +1 -0
  130. package/dist/testing/store-checks.d.ts +72 -0
  131. package/dist/testing/store-checks.d.ts.map +1 -0
  132. package/dist/testing/store-checks.js +619 -0
  133. package/dist/testing/store-checks.js.map +1 -0
  134. package/dist/tools.d.ts +25 -0
  135. package/dist/tools.d.ts.map +1 -1
  136. package/dist/tools.js +135 -13
  137. package/dist/tools.js.map +1 -1
  138. package/dist/types.d.ts +116 -13
  139. package/dist/types.d.ts.map +1 -1
  140. package/docs/README.md +17 -8
  141. package/docs/getting-started.md +18 -13
  142. package/docs/guides/anthropic.md +12 -8
  143. package/docs/guides/conversations.md +112 -47
  144. package/docs/guides/costs-and-limits.md +16 -7
  145. package/docs/guides/deployment.md +309 -87
  146. package/docs/guides/errors-and-reliability.md +161 -23
  147. package/docs/guides/own-adapter-and-loop.md +27 -10
  148. package/docs/guides/pdfs.md +123 -29
  149. package/docs/guides/storage.md +634 -143
  150. package/docs/guides/testing.md +78 -129
  151. package/docs/guides/vertex-and-gemini.md +10 -7
  152. package/docs/guides/web-app.md +322 -77
  153. package/docs/how-it-works.md +35 -8
  154. package/docs/measurements.md +63 -8
  155. package/docs/publishing.md +112 -36
  156. package/docs/reference/ask.md +154 -13
  157. package/docs/reference/errors-and-retries.md +166 -14
  158. package/docs/reference/events.md +53 -20
  159. package/docs/reference/gemini.md +70 -21
  160. package/docs/reference/library.md +709 -165
  161. package/docs/reference/node.md +633 -104
  162. package/docs/reference/testing.md +311 -0
  163. package/docs/reference/tools.md +15 -5
  164. package/docs/security.md +316 -70
  165. package/docs/troubleshooting.md +165 -58
  166. package/docs/upgrading-0.9.md +890 -0
  167. package/package.json +12 -3
  168. package/src/access.ts +144 -0
  169. package/src/ask.ts +230 -19
  170. package/src/cache.ts +20 -5
  171. package/src/encoding.ts +6 -4
  172. package/src/error-info.ts +255 -0
  173. package/src/errors.ts +129 -15
  174. package/src/events.ts +86 -21
  175. package/src/evidence.ts +14 -3
  176. package/src/extract.ts +50 -33
  177. package/src/gemini/adapter.ts +97 -11
  178. package/src/gemini/chat.ts +20 -6
  179. package/src/gemini/index.ts +1 -1
  180. package/src/index.ts +9 -6
  181. package/src/ingest.ts +927 -0
  182. package/src/library.ts +482 -523
  183. package/src/limiter.ts +2 -2
  184. package/src/map-reduce.ts +3 -3
  185. package/src/model.ts +69 -5
  186. package/src/node/handlers.ts +691 -117
  187. package/src/node/index.ts +13 -2
  188. package/src/node/ingest-child.ts +23 -5
  189. package/src/node/isolated.ts +11 -4
  190. package/src/node/originals.ts +78 -0
  191. package/src/node/spool.ts +365 -0
  192. package/src/node/sse.ts +7 -6
  193. package/src/pdf-layout.ts +69 -11
  194. package/src/ranged.ts +42 -14
  195. package/src/retry.ts +6 -2
  196. package/src/scope.ts +63 -0
  197. package/src/source.ts +178 -0
  198. package/src/stores.ts +635 -140
  199. package/src/testing/fake-fetch.ts +80 -0
  200. package/src/testing/fake-model.ts +78 -0
  201. package/src/testing/index.ts +11 -0
  202. package/src/testing/store-checks.ts +660 -0
  203. package/src/tools.ts +150 -14
  204. package/src/types.ts +106 -13
@@ -8,12 +8,12 @@ task, where there is one.
8
8
 
9
9
  ```ts
10
10
  import {
11
- askWithFiles, askStream, partialResultOf, DocumentsNotFoundError, UsageMeter,
11
+ askWithFiles, askStream, partialResultOf, DocumentsNotFoundError, UsageMeter, TOOL_TURN_VERSION,
12
12
  evidenceOf, mergeRanges, stubResult,
13
13
  EXPLORER_INSTRUCTION, FINAL_ANSWER_REQUEST, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_WITHOUT_TOOLS,
14
14
  } from "llm-large-files";
15
15
  import type {
16
- AskOptions, AskLimits, AskResult,
16
+ AskOptions, AskLimits, AskResult, MissingDocumentsAction, MissingDocumentsContext,
17
17
  ChatMessage, ChatTurn, ToolTurn,
18
18
  ModelAdapter, ModelCapabilities, ModelRequest, ModelMessage, ModelTextMessage, ModelToolRound,
19
19
  ModelPart, ToolCall, ToolAnswer, SendHooks, ModelReply, GenerateText, GenerateUsage,
@@ -30,7 +30,9 @@ Contents:
30
30
  [`askStream(options)`](#askstreamoptions), [`AskOptions`](#askoptions),
31
31
  [`AskLimits`](#asklimits), [`AskResult`](#askresult),
32
32
  [`partialResultOf(error)`](#partialresultoferror),
33
- [`DocumentsNotFoundError`](#documentsnotfounderror)
33
+ [`DocumentsNotFoundError`](#documentsnotfounderror), [missing documents](#missing-documents),
34
+ [`MissingDocumentsAction`](#missingdocumentsaction),
35
+ [`MissingDocumentsContext`](#missingdocumentscontext)
34
36
  - **What the loop adds to its requests:** [`EXPLORER_INSTRUCTION`](#explorer_instruction),
35
37
  [`FINAL_ANSWER_REQUEST`](#final_answer_request),
36
38
  [`FINAL_ANSWER_AFTER_PAGES`](#final_answer_after_pages),
@@ -76,8 +78,9 @@ What it does, in order:
76
78
  `options.budget` in place of its own, and fits it to what the adapters declare:
77
79
  `contextTokens`, `maxRequestBytes`, `tokenScale`, `outputTokens` (see
78
80
  [`ModelCapabilities`](#modelcapabilities)). `result.budget` is the outcome.
79
- 2. **Plans the documents** with `files.prepare`, for the room the conversation leaves. A document
80
- that is missing throws `DocumentsNotFoundError` before any model request.
81
+ 2. **Plans the documents** with `files.prepare`, for the room the conversation leaves. Documents
82
+ that are missing are settled by `onMissingDocuments` before any model request: by default the
83
+ question throws `DocumentsNotFoundError` ([missing documents](#missing-documents)).
81
84
  3. **Sends one request without tools** to `model` when every document went in whole and no PDF
82
85
  can be looked at, and returns its reply.
83
86
  4. **Otherwise runs tool rounds.** The model that explores (`explorer`, or `model` without one)
@@ -106,6 +109,16 @@ the provider allows (OpenAI's and Groq's TPM, HTTP 429 or 413) is this kind too,
106
109
  allowance as the window, and its steps say so.
107
110
  [How it works](../how-it-works.md#a-request-too-large-for-the-model) explains each step.
108
111
 
112
+ New in 0.9.0: the first request of a question is not sent to be refused. When the stored rounds of
113
+ earlier questions make it larger than the room it has in tokens, by the loop's own estimate (the
114
+ window less half of `reservedTokens`), their results are shortened first, in the same steps, until
115
+ it fits. The request is then what 0.8.2 sent again after the provider refused it, without the
116
+ refused request before it. Only tokens are counted here, as in that recovery: a request is not
117
+ shortened for its bytes alone. This is done for an `appendOnly` model too: a stored round has no
118
+ thinking in it, and nothing of the question was sent yet. Before, such a question failed on Claude.
119
+ `steps` says "Older tool results were shortened to make room in the request", once: a question
120
+ planned again shortens them again without saying so twice.
121
+
109
122
  **Returns** an [`AskResult`](#askresult).
110
123
 
111
124
  **Throws:**
@@ -116,7 +129,11 @@ allowance as the window, and its steps say so.
116
129
  | `Error`: "The last message must be the user's." | `messages` is empty, or its last message is not a user turn. | undefined |
117
130
  | `RangeError`: "limits.… must be a number, and is NaN. Leave it out for the default.", or `TypeError`: "limits.… must be a number, and is …" | A field of `options.limits` is NaN, or not a number. Before any request. New in 0.7.1. | undefined |
118
131
  | [`DocumentStoreError`](./library.md#documentstoreerror) | The store could not be read while the documents were planned. The documents are not gone: try again. A store that fails during a tool call is not thrown: the model gets the message as the tool's `error`. | undefined |
119
- | [`DocumentsNotFoundError`](#documentsnotfounderror) | A document of `documentIds` was never stored, has expired or been deleted, or belongs to another `owner`. Before any request. | undefined |
132
+ | [`DocumentsNotFoundError`](#documentsnotfounderror) | A document of `documentIds` was never stored, has expired or been deleted, or belongs to another `owner` or `scope`, and `onMissingDocuments` is `"throw"` (the default) or returned it; or a retry or replace of `onMissingDocuments` did not bring it back. Before any request. | undefined |
133
+ | `TypeError`: "onMissingDocuments must be "throw", "drop" or a function, and is …", or "onMissingDocuments returned …: it must return …" | `onMissingDocuments` is something else, or its function returned something else. New in 0.9.0. | undefined |
134
+ | What the function of `onMissingDocuments` threw | It threw, or its promise rejected. Before any request. New in 0.9.0. | undefined |
135
+ | `TypeError("owner is required: requireOwner is on")`, `TypeError("scope is required: requireScope is on")` | The library requires an owner or a scope ([`LargeFilesOptions`](./library.md#largefilesoptions)), and the question has none. Before any request. New in 0.9.0. | undefined |
136
+ | [`DocumentScopeError`](./library.md#documentscopeerror) | `scope` is not a valid scope, or the store threw one. Before any request when the scope is not valid. New in 0.9.0. | undefined |
120
137
  | [`ModelRequestError`](./errors-and-retries.md#modelrequesterror), or the adapter's subclass (`GeminiRequestError`, `OpenAiRequestError`, `AnthropicRequestError`) | A chat request failed, and was not worth another try, still failed after `retry.retries` more, asked for a longer wait than `retry.maxDelayMs`, or had already shown text. A `context_overflow` that the recovery above did not mend. | What the question had done |
121
138
  | Any other error of an adapter | Thrown as it came. An error without a numeric `status` is not sent again. | What the question had done |
122
139
  | What a listener threw | `onEvent`, `onText`, `onActivity` or `onStep` threw. The question stops: the calls of the turn still running stop, and no request follows. New in 0.7.0 for a throw during a whole-file read (`onActivity` on its progress, `onEvent` on its events): 0.6.0 reported it to the model as the tool's error, and went on. | What the question had done, when the error is an object and the question was under way |
@@ -230,11 +247,13 @@ The options of `askWithFiles`.
230
247
  | `files` | [`LargeFiles`](./library.md#largefiles) | required | The library that holds the documents, plans them and makes the tools. |
231
248
  | `model` | [`ModelAdapter`](#modeladapter) | required | The model that answers. Without `explorer`, it also makes the tool calls and reads whole files in parts. |
232
249
  | `explorer` | `ModelAdapter \| undefined` | none | A second model, of any provider, that makes the tool calls (search, read, look at pages) and reads whole files in parts. `model` then writes the answer from what the tools returned. Its requests get [`EXPLORER_INSTRUCTION`](#explorer_instruction), and its text is not shown. Left out, or the same object as `model`: one model does both. |
233
- | `documentIds` | `string[]` | required | The documents this question may use. Duplicates count once. One that is missing throws [`DocumentsNotFoundError`](#documentsnotfounderror). |
250
+ | `documentIds` | `string[]` | required | The documents this question may use. Duplicates count once. One that is missing throws [`DocumentsNotFoundError`](#documentsnotfounderror), unless `onMissingDocuments` says otherwise. |
234
251
  | `messages` | [`ChatMessage[]`](#chatmessage) | required | The conversation, oldest first. The last message must be the user's question. The loop works on copies: your array is not changed. |
235
252
  | `documentPlacement` | `"first" \| "last"` | `"first"` | Where document text and cards go. `"first"`: at the start of the first user turn, where they stay as the conversation grows, so the provider's prompt cache can reuse them on every follow-up question. `"last"`: after the text of the latest user turn; they then move on every turn and are billed in full each time. |
236
253
  | `system` | `string` | none | Your system instruction. It is trimmed, and the guide to the document tools is added after it when a document is reached through tools or has pages to look at. |
237
254
  | `owner` | `string` | none | The user (or tenant) asking. A document ingested with another owner is treated as missing. Without `owner`, only documents ingested without one can be used. |
255
+ | `scope` | [`DocumentScope`](./library.md#documentscope) | none | The scope of the question, such as `[userId, chatId]`. Every store call of the question carries it, and a document ingested with another scope is treated as missing. The tools check the owner and scope the store holds against `owner` and `scope` (`ToolOptions.access`). New in 0.9.0. |
256
+ | `onMissingDocuments` | `"throw" \| "drop" \| ((missing: string[], context: MissingDocumentsContext) => MissingDocumentsAction \| Promise<MissingDocumentsAction>)` | `"throw"` | What to do when documents of `documentIds` are missing: expired, deleted, never stored, or of another owner or scope, which look the same. Settled before any request. `"throw"`: [`DocumentsNotFoundError`](#documentsnotfounderror), as before 0.9.0. `"drop"`: the question is answered without them. A function: it gets the missing IDs, and says what to do. See [missing documents](#missing-documents). New in 0.9.0. |
238
257
  | `limits` | [`AskLimits`](#asklimits) | `{}` | The limits of this question: tool turns, calls per turn, whole-file reads, ceilings on tokens and requests. |
239
258
  | `retry` | [`RetryOptions`](./errors-and-retries.md#retryoptions) | `{ retries: 3, baseDelayMs: 500, maxDelayMs: 60_000 }` | How a failed model request is sent again: chat requests and whole-file part reads. `{ retries: 0 }` turns it off. |
240
259
  | `budget` | `Partial<`[`Budget`](./library.md#budget)`>` | the library's | Budget fields for this question, in place of the library's. Fields given nowhere follow the context window. The budget is then fitted to the models either way: `result.budget` shows it. |
@@ -288,6 +307,7 @@ question that failed.
288
307
  | `evidence` | [`Evidence[]`](#evidence) | What each tool call showed the model: the document, and the lines or pages. In call order. A call that failed, was not run, or was answered with a pointer to an earlier result adds none. Each has the `callId` of its call's events (new in 0.7.0). |
289
308
  | `toolTurns` | [`ToolTurn[]`](#toolturn) | The tool rounds of this question, as plain JSON, as the model last had them. Pass them back in `messages`, between this question and its answer, and a later question sees what was found here. Each result of a call made in this question has `tool_turns_left`, except a stand-in (`dropped: true`, see [`stubResult`](#stubresultcall-result-hadfiles)): a result shortened to make room, a pointer whose result was shortened, and the result of a call that showed pages. The pages are not kept: their stand-in says which pages were shown. A call's `problem` is left out. |
290
309
  | `plan` | [`DocumentPlan`](./library.md#documentplan) | Which documents went in whole (`inline`) and which were reached through tools (`searchable`). |
310
+ | `missing` | `string[]`, optional | The documents of `documentIds` that were missing, and that the question was answered without (`onMissingDocuments` `"drop"`). Absent when none was. New in 0.9.0. |
291
311
  | `budget` | [`Budget`](./library.md#budget) | The budget the question ran with: the library's (with `options.budget`), fitted to the models. |
292
312
  | `turns` | `number` | Chat requests of the question, the explorer's among them; whole-file part reads are not counted. A request counts when it is sent, so one that failed counts too. One sent again after a failure counts once; one sent again smaller after an overflow counts again. |
293
313
  | `finishReason` | `string`, optional | The provider's own word for why the last reply that gave one ended (`"STOP"`, `"length"`, `"end_turn"`). |
@@ -339,17 +359,124 @@ Guide: [errors and reliability](../guides/errors-and-reliability.md).
339
359
  declare class DocumentsNotFoundError extends Error {
340
360
  constructor(ids: string[]);
341
361
  readonly ids: string[];
362
+ readonly code: "documents_missing"; // new in 0.9.0
363
+ readonly status: 404; // new in 0.9.0
364
+ static is(value: unknown): value is DocumentsNotFoundError; // new in 0.9.0
342
365
  }
343
366
  ```
344
367
 
345
368
  Thrown by `askWithFiles` (and `askGemini`) before any model request, when documents of
346
- `documentIds` were never stored, have expired or been deleted, or belong to another owner. `ids`
369
+ `documentIds` were never stored, have expired or been deleted, or belong to another owner or scope. `ids`
347
370
  lists them. `name` is `"DocumentsNotFoundError"`. The message names the IDs, not the files: "A
348
371
  document is no longer available: ‹id›. Upload it again.", or for several "3 documents are no longer
349
- available: ‹id›, ‹id›, ‹id›. Upload them again."
372
+ available: ‹id›, ‹id›, ‹id›. Upload them again." New in 0.9.0: `code` is `"documents_missing"`,
373
+ `status` is 404, and `DocumentsNotFoundError.is(error)` tells one apart also when another copy of
374
+ the package made it (see [errors](./errors-and-retries.md#telling-errors-apart-across-copies-of-the-package)).
375
+
376
+ Since 0.9.0 `onMissingDocuments` can answer without them, or bring them back, instead.
350
377
 
351
378
  Guide: [errors and reliability](../guides/errors-and-reliability.md).
352
379
 
380
+ ### Missing documents
381
+
382
+ New in 0.9.0. `AskOptions.onMissingDocuments` says what a question does with documents of
383
+ `documentIds` that are missing. A document that expired (`ttlMs`), was deleted, was never stored,
384
+ or belongs to another owner or scope is missing: the four look the same, so another user's ID tells
385
+ nothing. It is settled before any model request.
386
+
387
+ - **`"throw"`** (the default): the question throws [`DocumentsNotFoundError`](#documentsnotfounderror),
388
+ as before.
389
+ - **`"drop"`**: the question is answered without them.
390
+ - The system instruction gets one line at its end: "1 of the attached files is no longer
391
+ available; say so if the question needs it." (or "3 of the attached files are no longer
392
+ available; say so if the question needs them."). Only in this question.
393
+ - `AskResult.missing` lists their IDs, and a `"documents_missing"` notice names them
394
+ (`documentIds`), before the `plan` event.
395
+ - With no document left, the question is a plain chat: no tool guide, no tools. The model may
396
+ then answer from what it knows, without saying the files are gone. To refuse instead, give a
397
+ function that throws when none is left:
398
+ `(missing) => (missing.length === new Set(documentIds).size ? "throw" : "drop")`, with the
399
+ question's own `documentIds`.
400
+ - **A function** gets the missing IDs and a [`MissingDocumentsContext`](#missingdocumentscontext),
401
+ and returns a [`MissingDocumentsAction`](#missingdocumentsaction), or a promise of one.
402
+ - `"throw"` or `"drop"`, as above.
403
+ - `{ retry: true }`: you ingested them again under the same IDs (`IngestInput.id`). The documents
404
+ are planned again, once.
405
+ - `{ replace: { [oldId]: newId } }`: you ingested them under new IDs. The documents are planned
406
+ again, once, with each new ID in the place of its old one.
407
+ - After a retry or a replace, an ID still missing fails the question with
408
+ `DocumentsNotFoundError`. When you cannot bring them all back, return `"drop"`: those you
409
+ ingested again are used from the next question.
410
+ - What it throws fails the question, as it came. When `signal` aborts while it runs, the
411
+ question ends at once with the signal's reason, whether the function looks at the signal or not.
412
+
413
+ A question planned again for a smaller window (after the provider refused its first request) keeps
414
+ what was settled: the function is not asked again about the same documents.
415
+
416
+ ```ts
417
+ import { askWithFiles, IngestError, type AskResult, type LargeFiles, type MissingDocumentsAction, type ModelAdapter } from "llm-large-files";
418
+
419
+ declare const files: LargeFiles;
420
+ declare const model: ModelAdapter;
421
+ // The uploads you keep, by their ID, which is also the document's ID.
422
+ declare const uploads: { find(userId: string, id: string): Promise<{ name: string; bytes: Uint8Array } | undefined> };
423
+
424
+ export async function ask(userId: string, chatId: string, documentIds: string[], question: string): Promise<AskResult> {
425
+ return askWithFiles({
426
+ files,
427
+ model,
428
+ owner: userId,
429
+ scope: [userId, chatId],
430
+ documentIds,
431
+ messages: [{ role: "user", text: question }],
432
+ // Ingest again what was kept; answer without the files that are gone for good.
433
+ onMissingDocuments: async (missing, { owner, scope }): Promise<MissingDocumentsAction> => {
434
+ let back = 0;
435
+ for (const id of missing) {
436
+ const upload = await uploads.find(userId, id);
437
+ if (!upload) continue;
438
+ try {
439
+ await files.ingest({ name: upload.name, bytes: upload.bytes, id, owner, scope });
440
+ } catch (error) {
441
+ // Another question of the chat ingested it meanwhile.
442
+ if (!(IngestError.is(error) && error.code === "exists")) throw error;
443
+ }
444
+ back++;
445
+ }
446
+ return back === missing.length ? { retry: true } : "drop";
447
+ },
448
+ });
449
+ }
450
+ ```
451
+
452
+ - Two questions of one chat can find the same document missing at once: a second tab, or a
453
+ question sent again. The second ingest gets an [`IngestError`](./library.md#ingesterror) of code
454
+ `"exists"`, and the ID counts as back. If the first has not stored it yet, that question fails
455
+ with `DocumentsNotFoundError`, and can be asked again.
456
+
457
+ ### `MissingDocumentsAction`
458
+
459
+ ```ts
460
+ type MissingDocumentsAction = "throw" | "drop" | { retry: true } | { replace: Record<string, string> };
461
+ ```
462
+
463
+ New in 0.9.0. What a function of `onMissingDocuments` returns: see
464
+ [missing documents](#missing-documents). Anything else is a `TypeError`: "onMissingDocuments returned
465
+ …: it must return "throw", "drop", { retry: true } or { replace: { [oldId]: newId } }." The map of
466
+ a replace is a plain object (made as `{}`, or with `Object.create(null)`), not a `Map` or an
467
+ instance of a class, and its new IDs are strings that are not empty. An action with a key of
468
+ another name, such as `{ retry: true, why: "…" }`, is a `TypeError` too.
469
+
470
+ ### `MissingDocumentsContext`
471
+
472
+ ```ts
473
+ type MissingDocumentsContext = { owner?: string; scope?: DocumentScope; signal?: AbortSignal };
474
+ ```
475
+
476
+ New in 0.9.0. What a function of `onMissingDocuments` is told besides the IDs: the `owner`, `scope`
477
+ and `signal` of the question, when it has them. Ingest again with the same owner and scope, or the
478
+ documents are still missing for the question.
479
+
353
480
  ## What the loop adds to its requests
354
481
 
355
482
  Each is a `string`. The loop adds them itself. They are exported so that you can recognise them in
@@ -440,7 +567,9 @@ A plain turn of the user or of the model. `"model"` is taken as `"assistant"`.
440
567
  ### `ToolTurn`
441
568
 
442
569
  ```ts
443
- type ToolTurn = { role: "tools"; calls: Array<ToolCall & { result: ToolResult }> };
570
+ type ToolTurn = { role: "tools"; version?: number; calls: Array<ToolCall & { result: ToolResult }> };
571
+
572
+ declare const TOOL_TURN_VERSION: 1;
444
573
  ```
445
574
 
446
575
  One round of tool use as an application stores it: the calls of one model turn, each with what the
@@ -455,6 +584,13 @@ regex search that 0.5.0 stored without its last match: those run again (see
455
584
  [tools](./tools.md#what-askwithfiles-adds-to-results)). Guide:
456
585
  [conversations](../guides/conversations.md).
457
586
 
587
+ `version` is the version of this shape, new in 0.9.0: `TOOL_TURN_VERSION` (1) on the rounds
588
+ `askWithFiles` returns, absent on those of earlier versions, which are read as before. It is never
589
+ sent to the model: of a stored round, only its calls are. A round of a higher version, made by a
590
+ newer version of the package, is refused with a `TypeError` ("A stored tool round (toolTurns) has
591
+ version 2: …"), before any request. Catch it to ask again without the old rounds. A test that
592
+ compares the rounds whole must expect `version`.
593
+
458
594
  ## The adapter contract
459
595
 
460
596
  An adapter turns the loop's neutral request into a provider's, sends it, and reads the reply back.
@@ -616,7 +752,8 @@ type ModelPart = { text: string; native?: undefined } | { native: unknown; text?
616
752
 
617
753
  One piece of a message: plain text, or something in the provider's own form (an image, an inline
618
754
  PDF) that only its adapter reads. A native part may carry the text it holds in `text`: the loop
619
- then sizes it by that text; otherwise by the size of its JSON. Each built-in adapter passes a native
755
+ then counts its tokens from that text, and its bytes from the larger of the text and the part's
756
+ JSON (since 0.9.0; before, from the text alone); otherwise it sizes it by the size of its JSON. Each built-in adapter passes a native
620
757
  part on to its provider as it is, and the loop sends it to every model of the question, so with an
621
758
  explorer of another provider, that model gets it too.
622
759
 
@@ -897,12 +1034,16 @@ older tool results, and for the pages in `result.toolTurns`. Set `hadFiles` (def
897
1034
  result whose files (pages) are dropped with it, however small its JSON is.
898
1035
 
899
1036
  It returns `undefined` when there is nothing to gain: the result is an error, is already a
900
- stand-in, or (without `hadFiles`) its JSON is under 700 characters. Otherwise, by tool:
1037
+ stand-in, or (without `hadFiles`) its JSON is under 700 characters, or is no larger than its
1038
+ stand-in would be. That last rule is new in 0.9.0: a search counted by group, or an
1039
+ `aggregate_table` result, of a few short groups came out larger as a stand-in (845 characters grew
1040
+ to 1,073), and replaced the result it was meant to shorten. Otherwise, by tool:
901
1041
 
902
1042
  | Tool | The stand-in keeps |
903
1043
  |---|---|
904
1044
  | `read_document` | `lines`, `total_lines` |
905
- | `search_document` | `mode`, `query` (its first 200 characters), `total_matching_lines`, `lines_shown` (up to 60 ranges, such as `"120-180"`, the last match's among them when the search showed it) |
1045
+ | `search_document` | `mode`, `query` (its first 200 characters), `total_matching_lines`, `lines_shown` (up to 60 ranges, such as `"120-180"`, the last match's among them when the search showed it); with `group_by`, `group_by`, `total_groups` and the first 30 `groups` |
1046
+ | `aggregate_table` | `table`, `rows_matched`, `total_groups`, and the first 30 `groups` |
906
1047
  | `analyze_whole_document` | `parts_read`, and the first 6,000 characters of `answer`, followed by "…" when it was longer: the answer cannot be asked for again |
907
1048
  | `view_pages` | `pages`, `total_pages` |
908
1049
  | `get_document_overview`, any other | nothing more than `document` and the note |
@@ -11,6 +11,7 @@ import {
11
11
  classifyModelError,
12
12
  DEFAULT_FIRST_BYTE_TIMEOUT_MS,
13
13
  DEFAULT_IDLE_TIMEOUT_MS,
14
+ errorInfoOf,
14
15
  errorKindOf,
15
16
  isRetryableStatus,
16
17
  ModelRequestError,
@@ -18,7 +19,7 @@ import {
18
19
  retryAfterMs,
19
20
  withRetry,
20
21
  } from "llm-large-files";
21
- import type { EventError, IdleWaits, ModelErrorClass, ModelErrorKind, RetryNotice, RetryOptions, SseHooks } from "llm-large-files";
22
+ import type { ErrorCategory, ErrorInfo, EventError, IdleWaits, ModelErrorClass, ModelErrorKind, RetryNotice, RetryOptions, SseHooks } from "llm-large-files";
22
23
  ```
23
24
 
24
25
  Contents:
@@ -27,6 +28,7 @@ Contents:
27
28
  [`ModelErrorClass`](#modelerrorclass),
28
29
  [`classifyModelError`](#classifymodelerrorstatus-message-signals),
29
30
  [`errorKindOf`](#errorkindoferror), [other error classes](#other-error-classes),
31
+ [`errorInfoOf`](#errorinfooferror) and [`ErrorInfo`](#errorinfo),
30
32
  [errors in events: `EventError`](#errors-in-events-eventerror)
31
33
  - Retries: [`withRetry`](#withretryrun-options), [`RetryOptions`](#retryoptions),
32
34
  [`RetryNotice`](#retrynotice), [retries in events](#retries-in-events),
@@ -53,6 +55,7 @@ declare class ModelRequestError extends Error {
53
55
  readonly retryAfterMs?: number;
54
56
  readonly limitTokens?: number;
55
57
  readonly requestedTokens?: number;
58
+ static is(value: unknown): value is ModelRequestError; // new in 0.9.0
56
59
  }
57
60
  ```
58
61
 
@@ -308,21 +311,164 @@ errorKindOf({ kind: "quota" }); // "quota": any
308
311
  ### Other error classes
309
312
 
310
313
  The adapters' errors are `ModelRequestError`s, so `instanceof ModelRequestError` and
311
- `errorKindOf` work for all three. The three errors of the documents are not, and have no `kind`.
314
+ `errorKindOf` work for all three. The four errors of the documents are not, and have no `kind`.
312
315
 
313
316
  | Class | Exported from | Extends | Fields of its own | Reference |
314
317
  |---|---|---|---|---|
315
318
  | `GeminiRequestError` | `llm-large-files/gemini` | `ModelRequestError` | none | [gemini.md](./gemini.md) |
316
319
  | `OpenAiRequestError` | `llm-large-files/openai` | `ModelRequestError` | `param`, `code` | [openai.md](./openai.md) |
317
320
  | `AnthropicRequestError` | `llm-large-files/anthropic` | `ModelRequestError` | `type` | [anthropic.md](./anthropic.md) |
318
- | `DocumentsNotFoundError` | `llm-large-files`, `llm-large-files/gemini` | `Error` | `ids` | [ask.md](./ask.md#documentsnotfounderror) |
319
- | `DocumentStoreError` | `llm-large-files` | `Error` | `code`, `syscall`, and the caught error as `cause` | [library.md](./library.md#documentstoreerror) |
320
- | `IngestError` | `llm-large-files` | `Error` | `code`, `status`, `retryAfterMs`, and the extractor's error as `cause`. New in 0.8.0 | [library.md](./library.md#ingesterror) |
321
+ | `DocumentsNotFoundError` | `llm-large-files`, `llm-large-files/gemini` | `Error` | `ids`; `code` `"documents_missing"` and `status` 404, new in 0.9.0 | [ask.md](./ask.md#documentsnotfounderror) |
322
+ | `DocumentStoreError` | `llm-large-files` | `Error` | `code`, `syscall`, and the caught error as `cause`; `operation` (`"read"`, `"write"`, `"delete"`, `"sweep"`) and `status` 503, new in 0.9.0 | [library.md](./library.md#documentstoreerror) |
323
+ | `DocumentScopeError` | `llm-large-files` | `TypeError` | `code` (`"scope_required"`, `"scope_invalid"`, `"scope_missing"`). New in 0.9.0. The upload handlers answer `"scope_missing"` `404` "This chat no longer exists.", and the other two `500` | [library.md](./library.md#documentscopeerror) |
324
+ | `IngestError` | `llm-large-files` | `Error` | `code`, `status`, `retryAfterMs`, and the extractor's error as `cause`. New in 0.8.0. Code `"exists"` (status 409) is new in 0.9.0 | [library.md](./library.md#ingesterror) |
325
+
326
+ `DocumentStoreError` is the store failing: retry the call. `DocumentScopeError` is a scope the call
327
+ should not have given, or should have: the same call fails again. The message of
328
+ `DocumentStoreError` names its operation, never a path or a host:
329
+
330
+ | `operation` | Message |
331
+ |---|---|
332
+ | `"read"` | `The document store could not be read (EIO). Try again.` |
333
+ | `"write"` | `The document could not be stored (EIO). Try again.` |
334
+ | `"delete"` | `The document could not be deleted (EIO). Try again.` |
335
+ | `"sweep"` | `The document store could not be cleaned up (EIO). Try again.` |
336
+ | code `"NEWER_VERSION"` | `The document was stored by a newer version of llm-large-files. Try again.` |
337
+
338
+ The library throws `"read"` from every look-up, `"write"` from `files.ingest` (code `"ETIMEDOUT"`
339
+ for a write that did not end within `ingestTimeoutMs`), `"delete"` from `files.delete` and
340
+ `"sweep"` from `files.sweep`. Until 0.9.0 the errors of writes came out as the store threw them. A
341
+ `DocumentScopeError` the store throws is never wrapped.
342
+
343
+ #### Telling errors apart across copies of the package
344
+
345
+ New in 0.9.0. Each of `ModelRequestError`, `DocumentsNotFoundError`, `DocumentStoreError`,
346
+ `DocumentScopeError` and `IngestError` has a static `is(value)`. It is `true` for an error of that
347
+ class, or of a class that extends it (`GeminiRequestError` for `ModelRequestError.is`), also when
348
+ another copy of the package made it: two versions installed side by side, or one bundled into a
349
+ dependency. `instanceof` is `false` then. `is` reads a mark that every copy puts on its errors
350
+ (`Symbol.for`), so it never throws, and is `false` for an object that only has the same `name`.
351
+
352
+ ```ts
353
+ import { DocumentsNotFoundError, DocumentStoreError, IngestError } from "llm-large-files";
354
+
355
+ function statusOf(error: unknown): number {
356
+ if (IngestError.is(error) || DocumentStoreError.is(error) || DocumentsNotFoundError.is(error)) return error.status;
357
+ return 500;
358
+ }
359
+ ```
360
+
361
+ ### errorInfoOf(error)
362
+
363
+ ```ts
364
+ declare function errorInfoOf(error: unknown): ErrorInfo;
365
+ ```
366
+
367
+ New in 0.9.0. What any error of the library means, in one record: its category and code, the HTTP
368
+ status to answer with, whether to retry it, and an English message that is safe to show. Switch on
369
+ `category` and `code` to show your own words, in your users' language. It is built on the rules of
370
+ [`EventError`](#errors-in-events-eventerror): a model error is told by its kind, never in the
371
+ provider's words.
372
+
373
+ - It reads the errors of every copy of the package, by their brand (`IngestError.is` and the
374
+ others), like the [`is` methods](#telling-errors-apart-across-copies-of-the-package).
375
+ - It also reads an [`EventError`](#errors-in-events-eventerror), the plain data of `run.error` and
376
+ `ingest.error`, so that a `map` of `writeSseEvents` can word a failed question: an `IngestError`'s
377
+ by its `code`, a `DocumentStoreError`'s and a `DocumentsNotFoundError`'s by their `name` (keeping
378
+ their message, which the library wrote), a `DocumentScopeError`'s by its `name` and `code`, a
379
+ model's by its `kind`, an `AbortError`'s, a `TypeError`'s and a `RangeError`'s by their name (the
380
+ `ingest.error` of a call `ingest` refused is `"input"`, as the error), and a Node system error's by the code in
381
+ the library's words for it ("The file could not be read from storage (ELOOP).", "Upload failed
382
+ (ELOOP)."). The `ingest.error` of the
383
+ [upload handlers](./node.md#upload-with-progress-accept-textevent-stream) is read the same way.
384
+ - Plain data with none of these is `"unknown"`, never a model's error: a model's `EventError`
385
+ always has its `kind`, the kind its status, message and `code` give when the error had none of
386
+ its own (an error of an adapter of yours, or `httpError` of the testing helpers). Plain data
387
+ thrown, such as `{ status: 429, message }`, is not an adapter's error: it reads as
388
+ `"unknown"`, and so does its `EventError`, which has no `kind`. Its `status` is kept when it is
389
+ 400 to 599 (the `ingest.error` of a hook of yours that threw a `409`), else 500, and it is
390
+ `retryable` for 429, 502, 503 and 504. Before, such data with a status was read as a model's
391
+ error: a store that failed (503) and a deleted chat (404) were "The model failed on its side" and
392
+ "The model refused the request".
393
+ - The `message` of a model's `EventError` is kept when it is the library's own words for its kind
394
+ ("The model failed on its side (HTTP 503)."), whatever status they name: the upload handlers'
395
+ `ingest.error` names the provider's status in its message and the answer's (502) in `status`.
396
+ Any other words are replaced by the library's, from its kind and `status`.
397
+ - It never throws. A value it cannot read is `"unknown"`.
398
+ - `message` never holds a path, a host, a stack or a provider's words. Log the error itself, with
399
+ its `cause`, on the server.
400
+
401
+ | Error | `category` | `code` | `status` | `retryable` | `message` |
402
+ |---|---|---|---|---|---|
403
+ | [`IngestError`](./library.md#ingesterror) | `"ingest"` | its code: `"too_large"`, `"busy"`… | its status: 422, 413, 409, 503 | `true` for `"busy"` only, with its `retryAfterMs` | its message; for `"unreadable"`, "This file could not be read. It may be damaged, or not of the type its name says.", since its own is a parser's |
404
+ | [`DocumentStoreError`](./library.md#documentstoreerror) | `"store"` | its code, when it has one that reads as a code (capital letters, digits and `_`, as its message shows it): `"EIO"`, `"ETIMEDOUT"`, `"NEWER_VERSION"`. A driver may put a host in `code`: such a code is left out | 503 | `true`, `retryAfterMs` 5,000 | its message: "The document could not be stored (EIO). Try again." |
405
+ | [`DocumentsNotFoundError`](./ask.md#documentsnotfounderror) | `"missing"` | `"documents_missing"` | 404 | `false` | its message, which names the IDs |
406
+ | [`DocumentScopeError`](./library.md#documentscopeerror) `"scope_missing"` | `"missing"` | `"scope_missing"` | 404 | `false` | "This chat no longer exists." |
407
+ | [`ModelRequestError`](#modelrequesterror), or an error with a `kind`, or an `Error` with a `status` of 0 or 400 to 599 and no `kind` (an adapter of your own) | `"model"` | its [kind](#modelerrorkind), from its status, message and `code` (`"insufficient_quota"` is `quota`) when it has none of its own | by kind: `context_overflow` 413, `rate_limit` 429, `quota` 503, `timeout` 504, `unreachable` and `server` 502, `auth` and `invalid` 500 | `true` for `rate_limit`, `timeout`, `unreachable` and `server`, with the provider's `retryAfterMs` when it named one | by kind and status: "The model was busy (HTTP 429)." |
408
+ | An `AbortError` (a signal that aborted: the user left, the server stopped the question) | `"aborted"` | `"aborted"` | 503 | `true` | "It was stopped before it finished." |
409
+ | A `TimeoutError` (`AbortSignal.timeout`, a deadline) | `"aborted"` | `"timeout"` | 504 | `true` | "It took too long, and was stopped. Try again." |
410
+ | `DocumentScopeError` `"scope_invalid"` or `"scope_required"`, a `TypeError`, a `RangeError`, and their `EventError` | `"input"` | the scope error's code | 500 | `false` | "Something went wrong." It is a bug of the server, not something the user did. |
411
+ | A Node system error (a `code` and a `syscall`), such as a path `ingest` does not read (`ELOOP`, `EISDIR`, `EINVAL`, `ENOENT`, `ETIMEDOUT`), and its `EventError` | `"unknown"` | its code: `"ENOSPC"`, when it reads as one (capitals, digits and `_`). A code that does not, such as a host, is left out | 500 | `false` | "Something went wrong (ENOSPC).", or "Something went wrong." without a code |
412
+ | Plain data (an `EventError`) without a `kind`, and without a `code` or `name` of the rows above | `"unknown"` | none | its `status` when it is 400 to 599, else 500 | `true` for 429, 502, 503 and 504 | "Something went wrong." |
413
+ | Anything else | `"unknown"` | none | 500 | `false` | "Something went wrong." |
414
+
415
+ The statuses of model errors are those a server that asks a model for its user answers: the same as
416
+ `toUserError` in [Errors and reliability](../guides/errors-and-reliability.md#putting-it-together-a-chat-route).
417
+ The upload handlers answer with [`uploadAnswerOf`](./node.md#uploadansweroferror), which follows
418
+ the same rules for the library's errors and keeps the message of an error with a status.
419
+
420
+ #### Your own words, in one switch
421
+
422
+ Switch on `category`, and on `code` where you want more detail. This one answers a Hebrew-speaking
423
+ user; [Errors and reliability](../guides/errors-and-reliability.md#your-users-words-errorinfoof) has
424
+ one for every code:
425
+
426
+ ```ts
427
+ import { errorInfoOf } from "llm-large-files";
428
+
429
+ export function hebrewMessage(error: unknown): string {
430
+ const info = errorInfoOf(error);
431
+ switch (info.category) {
432
+ case "ingest": return info.code === "too_large" ? "הקובץ גדול מדי." : "לא ניתן לקרוא את הקובץ.";
433
+ case "store": return "לא ניתן לגשת לקבצים כרגע. נסו שוב בעוד רגע.";
434
+ case "missing": return info.code === "scope_missing" ? "השיחה הזו כבר לא קיימת." : "אחד הקבצים כבר לא זמין. צרפו אותו שוב.";
435
+ case "model": return info.retryable ? "העוזר עמוס כרגע. נסו שוב בעוד דקה." : "העוזר אינו זמין כרגע.";
436
+ case "aborted": return "השאלה נעצרה.";
437
+ default: return "משהו השתבש. נסו שוב מאוחר יותר."; // "input", "unknown", and later categories
438
+ }
439
+ }
440
+ ```
441
+
442
+ ### `ErrorInfo`
443
+
444
+ ```ts
445
+ type ErrorCategory = "ingest" | "store" | "missing" | "model" | "aborted" | "input" | "unknown";
446
+
447
+ type ErrorInfo = {
448
+ category: ErrorCategory;
449
+ code?: string;
450
+ status: number;
451
+ retryable: boolean;
452
+ retryAfterMs?: number;
453
+ message: string;
454
+ };
455
+ ```
456
+
457
+ New in 0.9.0. What [`errorInfoOf()`](#errorinfooferror) returns.
458
+
459
+ | Field | Type | What it holds |
460
+ |---|---|---|
461
+ | `category` | `ErrorCategory` | What kind of failure: a refused file, the store, documents or a chat that are gone, a model request, a stop, a mistake in the call, or anything else. A switch over every category must handle those a later version adds. |
462
+ | `code` | `string`, optional | More precise than the category: an `IngestErrorCode`, a `ModelErrorKind`, `"documents_missing"`, a `DocumentScopeErrorCode`, `"aborted"` or `"timeout"`, or a system error's code. |
463
+ | `status` | `number` | The HTTP status to answer with: 400 to 599. |
464
+ | `retryable` | `boolean` | Whether the same call may work when it is made again, later. |
465
+ | `retryAfterMs` | `number`, optional | How long to wait first, in milliseconds, when that is known. |
466
+ | `message` | `string` | English words a user may see. Never a path, a host, a stack or a provider's words. |
321
467
 
322
468
  ### Errors in events: `EventError`
323
469
 
324
470
  ```ts
325
- type EventError = { message: string; kind?: ModelErrorKind; status?: number; name?: string; code?: IngestErrorCode };
471
+ type EventError = { message: string; kind?: ModelErrorKind; status?: number; name?: string; code?: IngestErrorCode | DocumentScopeErrorCode };
326
472
  ```
327
473
 
328
474
  New in 0.7.0. An error as the events of a question or an ingest carry it ([events](./events.md)):
@@ -332,11 +478,11 @@ included: log that one.
332
478
 
333
479
  | Field | Type | What it holds |
334
480
  |---|---|---|
335
- | `message` | `string` | Words your users may see. A model error is told by its kind and status, never in the provider's words, which can name projects, hosts or keys: "The model was busy (HTTP 429).", "The model's quota has run out (HTTP 429).", "The model could not be reached.", "The model refused the key or token it was sent (HTTP 401)." A Node system error is told by its code ("The file could not be read from storage (ENOENT)."), a `DocumentStoreError` by its own message, which names only its code, and a store that failed to write in `ingest.error` as "The document could not be stored. Try again later.". The library's own errors (a refused file, `DocumentsNotFoundError`, an abort, the error a listener threw) keep their message, and so does any other `Error` without a `kind` or a numeric `status`, such as one an adapter or a token function of your own throws: give such errors a status, or words of your own. A value that is not an `Error` is "Something went wrong.". |
336
- | `kind` | [`ModelErrorKind`](#modelerrorkind), optional | For a model error: its kind, as [`errorKindOf`](#errorkindoferror) reads it. |
337
- | `status` | `number`, optional | For an HTTP error: its status. 0 when no answer came. |
338
- | `name` | `string`, optional | The error's class name: `"ModelRequestError"`, `"GeminiRequestError"`, `"AbortError"`, `"DocumentsNotFoundError"`, `"IngestError"`… |
339
- | `code` | [`IngestErrorCode`](./library.md#ingesterror), optional | For a file `ingest` could not read: why (`"too_large"`, `"no_text"`, `"busy"`…). New in 0.8.0. |
481
+ | `message` | `string` | Words your users may see. A model error is told by its kind and status, never in the provider's words, which can name projects, hosts or keys: "The model was busy (HTTP 429).", "The model's quota has run out (HTTP 429).", "The model could not be reached.", "The model refused the key or token it was sent (HTTP 401)." A Node system error is told by its code ("The file could not be read from storage (ENOENT)."), when the code reads as one (capitals, digits and `_`; since 0.9.0: a driver may put a host in `code`), a `DocumentStoreError` by its own message, which names only its code, and a store that failed to write in `ingest.error` as "The document could not be stored. Try again later." (with `name` `"DocumentStoreError"` and `status` 503 since 0.9.0). The library's own errors (a refused file, `DocumentsNotFoundError`, an abort, the error a listener threw) keep their message, and so does any other `Error` without a `kind` or a numeric `status`, such as one an adapter or a token function of your own throws: give such errors a status, or words of your own. A status that is not a model's (not 0 or 400 to 599), and plain data thrown with a status (`{ status: 429, message }`), are "Something went wrong.", as `errorInfoOf` reads them (since 0.9.0; before, a model's words). A value that is not an `Error` is "Something went wrong.". |
482
+ | `kind` | [`ModelErrorKind`](#modelerrorkind), optional | For a model error: its kind, as [`errorKindOf`](#errorkindoferror) reads it. Since 0.9.0 also for an `Error` with a `status` of 0 or 400 to 599 and no `kind` of its own (an adapter of yours, `httpError` of the testing helpers): the kind its status, message and `code` give ([`classifyModelError`](#classifymodelerrorstatus-message-signals)), as its message is told and as `errorInfoOf` reads the error. Not for plain data thrown (an object of no class), and never for the library's own errors (`DocumentStoreError`, `DocumentsNotFoundError`, `IngestError`, `DocumentScopeError`). |
483
+ | `status` | `number`, optional | For an HTTP error: its status. 0 when no answer came. Since 0.9.0 also the status of the library's own errors: 503 for `DocumentStoreError`, 404 for `DocumentsNotFoundError`, and for an `IngestError` the status of every code but those of 422 (413, 409, 503). |
484
+ | `name` | `string`, optional | The error's class name: `"ModelRequestError"`, `"GeminiRequestError"`, `"AbortError"`, `"DocumentsNotFoundError"`, `"DocumentStoreError"`, `"DocumentScopeError"`, `"IngestError"`, `"TypeError"`… Since 0.9.0 a store's own subclass of `DocumentStoreError` (one named `"BucketStoreError"`) is named `"DocumentStoreError"` here, and an extractor's own subclass of `IngestError` (one named `"OcrRefusal"`) `"IngestError"`, so that `errorInfoOf` reads them as a store's failure and a refused file. |
485
+ | `code` | [`IngestErrorCode`](./library.md#ingesterror) or [`DocumentScopeErrorCode`](./library.md#documentscopeerror), optional | For a file `ingest` could not read: why (`"too_large"`, `"no_text"`, `"busy"`, `"exists"`…). New in 0.8.0. Since 0.9.0 also, with `name` `"DocumentScopeError"`, why a scope could not be used: `"scope_missing"` (the chat was deleted), `"scope_invalid"` or `"scope_required"`. A table typed `Record<IngestErrorCode, string>` must check the code before it looks it up. |
340
486
 
341
487
  To show your own words, map the error by `kind`, `status` or `name`, as you would the thrown one
342
488
  (see [Errors and reliability](../guides/errors-and-reliability.md)).
@@ -358,8 +504,9 @@ declare function withRetry<T>(run: () => Promise<T>, options?: {
358
504
  Runs `run`, and runs it again when it failed in a way that another try can mend. It is the rule
359
505
  `askWithFiles` and `askGemini` use for each chat request, and the whole-file part reads use for
360
506
  each part. It reads three fields of what `run` throws, so any error with them works, not only a
361
- `ModelRequestError`: `status` (a finite number), `kind` and `retryAfterMs`. `run` is called again
362
- as it is: build the request inside it.
507
+ `ModelRequestError`: `status` (a finite number), `kind` and `retryAfterMs`. An error without a
508
+ `kind` also has its `message` and `code` read, for the kind they give. `run` is called again as it
509
+ is: build the request inside it.
363
510
 
364
511
  | Option | Type | Default | What it does |
365
512
  |---|---|---|---|
@@ -375,7 +522,12 @@ What happens to an error, checked in this order:
375
522
  2. Its `kind` is `"quota"` or `"context_overflow"`: it is thrown. A wait does not mend a daily cap
376
523
  or an empty balance, and only a smaller request passes a limit of size, whatever its status
377
524
  (OpenAI's request larger than the tokens a minute allows comes as 429). 0.5.0, which had no
378
- kinds, sent both again when their status was 0, 408, 409, 429 or 500 and more.
525
+ kinds, sent both again when their status was 0, 408, 409, 429 or 500 and more. An error without
526
+ a `kind` of its own that has a `status` of 0 or 400 to 599 (an adapter of yours, `httpError`)
527
+ has the kind [`classifyModelError`](#classifymodelerrorstatus-message-signals) gives its status,
528
+ message and `code`, as its events have it: a 429 of code `"insufficient_quota"` is a quota, and
529
+ is thrown. Plain data thrown (an object of no class) has no kind. New in 0.9.0: such an error
530
+ was sent again by its status, while its `retry` event and `errorInfoOf` called it not retryable.
379
531
  3. The provider said not to send it again: the adapter took note of Claude's
380
532
  `x-should-retry: false`. It is thrown, whatever its status. The note is internal: an error of
381
533
  your own cannot carry it.