llm-large-files 0.4.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/CHANGELOG.md +1400 -338
  2. package/README.md +217 -49
  3. package/dist/analyze.d.ts +5 -0
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +96 -47
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +117 -0
  8. package/dist/anthropic/adapter.d.ts.map +1 -0
  9. package/dist/anthropic/adapter.js +542 -0
  10. package/dist/anthropic/adapter.js.map +1 -0
  11. package/dist/anthropic/index.d.ts +3 -0
  12. package/dist/anthropic/index.d.ts.map +1 -0
  13. package/dist/anthropic/index.js +2 -0
  14. package/dist/anthropic/index.js.map +1 -0
  15. package/dist/ask.d.ts +200 -0
  16. package/dist/ask.d.ts.map +1 -0
  17. package/dist/ask.js +1402 -0
  18. package/dist/ask.js.map +1 -0
  19. package/dist/budget.d.ts +23 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +64 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/encoding.d.ts +17 -0
  24. package/dist/encoding.d.ts.map +1 -0
  25. package/dist/encoding.js +852 -0
  26. package/dist/encoding.js.map +1 -0
  27. package/dist/errors.d.ts +4 -0
  28. package/dist/errors.d.ts.map +1 -1
  29. package/dist/errors.js +15 -0
  30. package/dist/errors.js.map +1 -1
  31. package/dist/events.d.ts +333 -0
  32. package/dist/events.d.ts.map +1 -0
  33. package/dist/events.js +159 -0
  34. package/dist/events.js.map +1 -0
  35. package/dist/evidence.d.ts +42 -0
  36. package/dist/evidence.d.ts.map +1 -0
  37. package/dist/evidence.js +138 -0
  38. package/dist/evidence.js.map +1 -0
  39. package/dist/extract.d.ts +35 -3
  40. package/dist/extract.d.ts.map +1 -1
  41. package/dist/extract.js +626 -58
  42. package/dist/extract.js.map +1 -1
  43. package/dist/gemini/adapter.d.ts +59 -0
  44. package/dist/gemini/adapter.d.ts.map +1 -0
  45. package/dist/gemini/adapter.js +226 -0
  46. package/dist/gemini/adapter.js.map +1 -0
  47. package/dist/gemini/chat.d.ts +53 -77
  48. package/dist/gemini/chat.d.ts.map +1 -1
  49. package/dist/gemini/chat.js +42 -300
  50. package/dist/gemini/chat.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +16 -0
  52. package/dist/gemini/errors.d.ts.map +1 -0
  53. package/dist/gemini/errors.js +46 -0
  54. package/dist/gemini/errors.js.map +1 -0
  55. package/dist/gemini/generate.d.ts +18 -21
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +49 -92
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +6 -4
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +4 -3
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -2
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -38
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/http.d.ts +136 -0
  68. package/dist/http.d.ts.map +1 -0
  69. package/dist/http.js +401 -0
  70. package/dist/http.js.map +1 -0
  71. package/dist/index.d.ts +18 -2
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +13 -4
  74. package/dist/index.js.map +1 -1
  75. package/dist/library.d.ts +96 -8
  76. package/dist/library.d.ts.map +1 -1
  77. package/dist/library.js +414 -96
  78. package/dist/library.js.map +1 -1
  79. package/dist/map-reduce.d.ts +37 -1
  80. package/dist/map-reduce.d.ts.map +1 -1
  81. package/dist/map-reduce.js +255 -61
  82. package/dist/map-reduce.js.map +1 -1
  83. package/dist/model.d.ts +278 -0
  84. package/dist/model.d.ts.map +1 -0
  85. package/dist/model.js +222 -0
  86. package/dist/model.js.map +1 -0
  87. package/dist/node/handlers.d.ts +20 -4
  88. package/dist/node/handlers.d.ts.map +1 -1
  89. package/dist/node/handlers.js +122 -20
  90. package/dist/node/handlers.js.map +1 -1
  91. package/dist/node/index.d.ts +2 -0
  92. package/dist/node/index.d.ts.map +1 -1
  93. package/dist/node/index.js +1 -0
  94. package/dist/node/index.js.map +1 -1
  95. package/dist/node/sse.d.ts +59 -0
  96. package/dist/node/sse.d.ts.map +1 -0
  97. package/dist/node/sse.js +174 -0
  98. package/dist/node/sse.js.map +1 -0
  99. package/dist/openai/adapter.d.ts +109 -0
  100. package/dist/openai/adapter.d.ts.map +1 -0
  101. package/dist/openai/adapter.js +567 -0
  102. package/dist/openai/adapter.js.map +1 -0
  103. package/dist/openai/index.d.ts +3 -0
  104. package/dist/openai/index.d.ts.map +1 -0
  105. package/dist/openai/index.js +2 -0
  106. package/dist/openai/index.js.map +1 -0
  107. package/dist/output-limit.d.ts +42 -0
  108. package/dist/output-limit.d.ts.map +1 -0
  109. package/dist/output-limit.js +121 -0
  110. package/dist/output-limit.js.map +1 -0
  111. package/dist/pause.d.ts +24 -0
  112. package/dist/pause.d.ts.map +1 -0
  113. package/dist/pause.js +38 -0
  114. package/dist/pause.js.map +1 -0
  115. package/dist/pdf-pages.d.ts +32 -2
  116. package/dist/pdf-pages.d.ts.map +1 -1
  117. package/dist/pdf-pages.js +275 -14
  118. package/dist/pdf-pages.js.map +1 -1
  119. package/dist/pdf-pictures.d.ts +30 -3
  120. package/dist/pdf-pictures.d.ts.map +1 -1
  121. package/dist/pdf-pictures.js +50 -8
  122. package/dist/pdf-pictures.js.map +1 -1
  123. package/dist/pdf-work.d.ts +40 -0
  124. package/dist/pdf-work.d.ts.map +1 -0
  125. package/dist/pdf-work.js +734 -0
  126. package/dist/pdf-work.js.map +1 -0
  127. package/dist/plan.d.ts +22 -4
  128. package/dist/plan.d.ts.map +1 -1
  129. package/dist/plan.js +61 -12
  130. package/dist/plan.js.map +1 -1
  131. package/dist/retry.d.ts +76 -0
  132. package/dist/retry.d.ts.map +1 -0
  133. package/dist/retry.js +141 -0
  134. package/dist/retry.js.map +1 -0
  135. package/dist/search.d.ts +8 -2
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +60 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/sse.d.ts +36 -0
  140. package/dist/sse.d.ts.map +1 -0
  141. package/dist/sse.js +153 -0
  142. package/dist/sse.js.map +1 -0
  143. package/dist/stores.d.ts.map +1 -1
  144. package/dist/stores.js +5 -2
  145. package/dist/stores.js.map +1 -1
  146. package/dist/text-index.d.ts +6 -0
  147. package/dist/text-index.d.ts.map +1 -1
  148. package/dist/text-index.js +25 -8
  149. package/dist/text-index.js.map +1 -1
  150. package/dist/text.d.ts +62 -2
  151. package/dist/text.d.ts.map +1 -1
  152. package/dist/text.js +314 -14
  153. package/dist/text.js.map +1 -1
  154. package/dist/tools.d.ts +72 -1
  155. package/dist/tools.d.ts.map +1 -1
  156. package/dist/tools.js +341 -60
  157. package/dist/tools.js.map +1 -1
  158. package/dist/types.d.ts +128 -4
  159. package/dist/types.d.ts.map +1 -1
  160. package/dist/zip-directory.d.ts +43 -0
  161. package/dist/zip-directory.d.ts.map +1 -0
  162. package/dist/zip-directory.js +130 -0
  163. package/dist/zip-directory.js.map +1 -0
  164. package/docs/README.md +288 -0
  165. package/docs/api.md +58 -184
  166. package/docs/configuration.md +34 -490
  167. package/docs/getting-started.md +412 -177
  168. package/docs/guides/anthropic.md +590 -0
  169. package/docs/guides/conversations.md +629 -0
  170. package/docs/guides/costs-and-limits.md +726 -0
  171. package/docs/guides/deployment.md +654 -0
  172. package/docs/guides/errors-and-reliability.md +735 -0
  173. package/docs/guides/explorer-model.md +399 -0
  174. package/docs/guides/openai-compatible.md +602 -0
  175. package/docs/guides/own-adapter-and-loop.md +1169 -0
  176. package/docs/guides/pdfs.md +971 -0
  177. package/docs/guides/storage.md +731 -0
  178. package/docs/guides/testing.md +1199 -0
  179. package/docs/guides/vertex-and-gemini.md +717 -0
  180. package/docs/guides/web-app.md +1589 -0
  181. package/docs/how-it-works.md +1022 -138
  182. package/docs/measurements.md +881 -0
  183. package/docs/publishing.md +274 -46
  184. package/docs/reference/anthropic.md +427 -0
  185. package/docs/reference/ask.md +892 -0
  186. package/docs/reference/errors-and-retries.md +758 -0
  187. package/docs/reference/events.md +993 -0
  188. package/docs/reference/gemini.md +823 -0
  189. package/docs/reference/library.md +1467 -0
  190. package/docs/reference/node.md +528 -0
  191. package/docs/reference/openai.md +385 -0
  192. package/docs/reference/tools.md +883 -0
  193. package/docs/security.md +902 -90
  194. package/docs/troubleshooting.md +1390 -0
  195. package/package.json +22 -4
  196. package/src/analyze.ts +93 -42
  197. package/src/anthropic/adapter.ts +611 -0
  198. package/src/anthropic/index.ts +2 -0
  199. package/src/ask.ts +1560 -0
  200. package/src/budget.ts +71 -0
  201. package/src/encoding.ts +850 -0
  202. package/src/errors.ts +17 -0
  203. package/src/events.ts +442 -0
  204. package/src/evidence.ts +165 -0
  205. package/src/extract.ts +602 -62
  206. package/src/gemini/adapter.ts +271 -0
  207. package/src/gemini/chat.ts +87 -355
  208. package/src/gemini/errors.ts +48 -0
  209. package/src/gemini/generate.ts +67 -94
  210. package/src/gemini/index.ts +6 -4
  211. package/src/gemini/sse.ts +1 -34
  212. package/src/http.ts +434 -0
  213. package/src/index.ts +55 -4
  214. package/src/library.ts +497 -97
  215. package/src/map-reduce.ts +266 -59
  216. package/src/model.ts +433 -0
  217. package/src/node/handlers.ts +137 -22
  218. package/src/node/index.ts +2 -0
  219. package/src/node/sse.ts +198 -0
  220. package/src/openai/adapter.ts +613 -0
  221. package/src/openai/index.ts +2 -0
  222. package/src/output-limit.ts +135 -0
  223. package/src/pause.ts +41 -0
  224. package/src/pdf-pages.ts +268 -15
  225. package/src/pdf-pictures.ts +56 -9
  226. package/src/pdf-work.ts +722 -0
  227. package/src/plan.ts +68 -12
  228. package/src/retry.ts +176 -0
  229. package/src/search.ts +63 -10
  230. package/src/sse.ts +159 -0
  231. package/src/stores.ts +5 -2
  232. package/src/text-index.ts +26 -7
  233. package/src/text.ts +323 -13
  234. package/src/tools.ts +338 -62
  235. package/src/types.ts +129 -5
  236. package/src/zip-directory.ts +136 -0
@@ -0,0 +1,1169 @@
1
+ # Your own adapter and loop
2
+
3
+ This guide is for two cases: your model has no adapter in the package, or you already run a tool
4
+ loop and want only the documents and their tools. It shows the `ModelAdapter` contract as the loop
5
+ uses it, a complete adapter for a made-up provider, a wrapper around an existing adapter (logs,
6
+ quotas, a shared limit, a gateway's errors), and a loop of your own built on `files.prepare()` and `files.tools()`.
7
+ The exact types are in the [ask reference](../reference/ask.md#modeladapter) and the
8
+ [tools reference](../reference/tools.md#toolset).
9
+
10
+ ## Three ways in
11
+
12
+ | You have | Do this | The library still does | You do |
13
+ |---|---|---|---|
14
+ | A model the package has no adapter for | [Write an adapter](#a-complete-adapter) and call `askWithFiles` | The plan, the tools, limits, retries, usage, room in the request, the request for the answer | Turn the neutral request into your provider's, and its reply back |
15
+ | An adapter of the package, and a need for logs, metrics, quotas or a limit on requests at once | [Wrap it](#wrapping-an-adapter) | Everything | Your code around `send` and `generateText` |
16
+ | A tool loop of your own (an agent framework, a provider's SDK) | [Use `prepare()` and `tools()`](#your-own-loop) | The plan, the document text and cards, the tools and their limits | Turns, room, retries, usage, the request for the answer |
17
+
18
+ Check first whether you need an adapter at all. A server that speaks Chat Completions (vLLM,
19
+ Ollama, LiteLLM, a gateway) works with `openAiCompatible()` and its `url`, and a gateway that
20
+ proxies Generate Content works with `gemini()` given your own `{ url, streamUrl, headers }`. See
21
+ [OpenAI-compatible endpoints](./openai-compatible.md) and [Gemini and Vertex AI](./vertex-and-gemini.md).
22
+
23
+ ## The adapter contract
24
+
25
+ An adapter is one object. The loop uses these members:
26
+
27
+ | Member | Required | What the loop does with it |
28
+ |---|---|---|
29
+ | `id` | Yes | Names the model in `usage.byModel`. Two adapters with the same `id` add up in one entry. |
30
+ | `capabilities` | Yes | Sizes the question: see [Capabilities](#capabilities). |
31
+ | `send(request, hooks?)` | Yes | Every chat request: each tool turn, and the answer. |
32
+ | `generateText` | No | The part reads of `analyze_whole_document`. Without it on the model that explores, that tool is not offered. |
33
+ | `requestBytes(request)` | No | The size of a request body, so that the pages of `view_pages` get exactly the room that is left. Without it, the loop estimates. |
34
+ | `estimateTokens(text)` | No | Deprecated, and never called. Set `capabilities.tokenScale` instead: see [`requestBytes` and `estimateTokens`](#requestbytes-and-estimatetokens). |
35
+
36
+ One adapter object serves every question at once, so keep nothing of one request on it. The loop
37
+ tells models apart by object, not by `id`: `explorer` set to the same object as `model` is one
38
+ model, and two adapters of the same model are two (see [An explorer model](./explorer-model.md)).
39
+
40
+ ### Capabilities
41
+
42
+ `capabilities` is a [`ModelCapabilities`](../reference/ask.md#modelcapabilities): its fields, their
43
+ defaults and what each changes are there. For an adapter of your own:
44
+
45
+ - Declare `contextTokens`, and `maxRequestBytes` when the provider has a limit. Left unset, the
46
+ question is planned for the library's budget: 1,000,000 tokens and 10,000,000 bytes unless you
47
+ set `budget`.
48
+ - `toolFiles` and `pageTokens` are required. With `toolFiles: "none"`, `view_pages` is not offered
49
+ and any `pageTokens` will do. With `"inside"` or `"beside"`, the pages reach `send` in
50
+ `answers[].files`, and your `send` puts them where the provider reads them: the loop only tells
51
+ `"none"` from the other two.
52
+ - Set `appendOnly` only when the provider ties reasoning to earlier turns, as Claude ties its
53
+ thinking blocks. It costs room: in a question the model takes part in, old tool results are
54
+ never shortened to make room.
55
+ - Set `clearsToolResults` when your provider may clear old tool results from the conversation on
56
+ its side, before the model reads it, as Claude's context editing does. A call the model makes
57
+ again is then run again, instead of answered with a pointer to a result it may no longer have,
58
+ and the pointers in stored rounds become stand-ins that say to call again.
59
+
60
+ ### What `send` receives
61
+
62
+ `request` is a `ModelRequest`:
63
+
64
+ - `system`: your system prompt, then the guide to the document tools. On an explorer's requests,
65
+ `EXPLORER_INSTRUCTION` follows. It may be empty: leave it out of the body then.
66
+ - `messages`: the conversation, oldest first. Each message is one of two kinds.
67
+ - `{ role: "user" | "assistant", parts }`: a turn of text. A part is `{ text }`, or `{ native }`:
68
+ something in the provider's own form that your application put in `messages` (an image, say),
69
+ to pass through untouched. A native part may also carry `text`, which only sizes it. The text
70
+ and cards of the documents are one `{ text }` part at the start of the first user turn, or at
71
+ the end of the last with `documentPlacement: "last"`.
72
+ - `{ role: "tools", calls, answers, raw? }`: one round of tool use. `calls` are the model's calls
73
+ in order, and `answers` holds one `{ call, result, files? }` for each, in the same order. Send
74
+ each `result` as JSON text: it is a plain object, and the loop adds `tool_turns_left` to it.
75
+ The results of a round stored from an earlier question come without `tool_turns_left`.
76
+ `files` are the pages of a `view_pages` call, one PDF (`application/pdf`), and come only when
77
+ `toolFiles` is not `"none"`.
78
+ - `raw` on a round is the model's turn as your `send` returned it: send it back unchanged. The loop
79
+ sets it only on rounds this adapter object produced in this question. A round stored from an
80
+ earlier question (`toolTurns`) or made by another model has none: build the model's turn from
81
+ `calls`, and give a call without an `id` one that is the same for the call and its result.
82
+ - The last message is the user's, or a tool round. Two user turns can follow each other: the
83
+ question, then the request for the answer when no tool ran. In a provider whose tool results go
84
+ in a user turn (Gemini, Claude), a tool round followed by the request for the answer is two user
85
+ turns as well. Join them if your provider refuses that, as the OpenAI-compatible adapter does.
86
+ - `tools`: the declarations, `{ name, description, parameters }`, in a JSON Schema subset that
87
+ Gemini, OpenAI and Claude accept. Left out when the request needs no tools.
88
+ - `toolChoice`: `"auto"` on a request that may call tools, `"none"` on the request for the answer,
89
+ which must be answered in text. With `"none"` the tools are still listed, for a provider that
90
+ wants them declared next to the calls already in the conversation. Leave them out if your
91
+ provider ignores its own "none": the Gemini adapter does.
92
+
93
+ ### Streaming and cancelling: `hooks`
94
+
95
+ - `hooks.onText` is given when your application streams (`onText` of `askWithFiles`) and the text
96
+ of this request is shown: every chat request without an explorer, and the answering model's
97
+ request with one. An explorer's requests come without it. When it is given, stream if you can,
98
+ and pass each piece of the answer as it arrives. Pass text for the user only, never thoughts.
99
+ - The pieces must add up to the start of `reply.text`. What they did not cover is passed on by the
100
+ loop once `send` returns, so an adapter that cannot stream can leave `onText` alone.
101
+ - Once a piece was passed, a failure of this request is not sent again: the user has seen it. A
102
+ failure before the first piece is.
103
+ - `hooks.signal` aborts when the question is cancelled. Pass it to `fetch`, and when it has
104
+ aborted, throw what `fetch` threw as it is. Nothing is sent again after an abort. The loop does
105
+ not wait for `send` (or `generateText`) once the signal has aborted: the question throws the
106
+ signal's reason at once, and a reply that arrives later is dropped and not counted in `usage`.
107
+ Abort your own request all the same, so that the connection is freed and the provider stops
108
+ billing it.
109
+ - The loop always passes `hooks`, but the type says it may be left out: write
110
+ `send(request, hooks = {})`.
111
+
112
+ ### What `send` returns
113
+
114
+ `send` returns a [`ModelReply`](../reference/ask.md#modelreply): its fields and what the loop does
115
+ with each are there. For an adapter of your own:
116
+
117
+ - `text` is what the model wrote for the user, without thoughts. `calls` is `[]` when there are
118
+ none.
119
+ - Give a call that cannot be run as it came a `problem`: arguments that are not a JSON object, or a
120
+ call cut off at the output limit. The loop answers it with `{ error: problem }`, and the model can
121
+ send it again.
122
+ - Keep `raw` plain JSON: the loop measures it with `JSON.stringify`.
123
+ - Set `blockReason` when the provider refused the prompt, and return no calls with it.
124
+ - In `usage`, count the prompt and nothing else in `inputTokens`, cached tokens included; count the
125
+ thoughts in `outputTokens`. Leave out, or give 0 for, what the provider does not report. The loop
126
+ compares `inputTokens` with its own estimate of the request, and makes its later estimates up to
127
+ twice as large when the provider counted more.
128
+ - Set `finish` as the next section says.
129
+
130
+ ### How the reply ended: `finish`
131
+
132
+ | `finish` | Set it when | What the loop does |
133
+ |---|---|---|
134
+ | `"complete"` | The model ended its turn. | Nothing more. |
135
+ | `"cut"` | The reply stopped at the output limit. | A reply with text and no calls is still the answer; `finishReason` tells why it stopped. A first reply without text is not asked for again. |
136
+ | `"filtered"` | The provider's safety filters stopped the reply. | The same as `"cut"`. To end the question, set `blockReason` as well, and return no calls. |
137
+ | `"malformed_call"` | The model tried to call a tool, and the call could not be read (Gemini's `MALFORMED_FUNCTION_CALL`). | A reply without calls is asked for once more, with a note that says so. |
138
+ | Unset | You do not know why it ended. | The same as `"complete"`. |
139
+
140
+ Two kinds of reply are asked for once more, with a note that says what was wrong: a
141
+ `"malformed_call"` reply without calls, and a first reply with no text and no calls before any tool
142
+ ran, unless it was `"cut"` or `"filtered"`. A question makes at most two such second tries, each
143
+ takes a tool turn, and none is made when only the turn for the answer is left. Any other reply
144
+ without text, and the last tool turn, lead to one more request, with `toolChoice: "none"`, that
145
+ asks for the answer. When the reply to that request has no text either, or holds calls (which
146
+ `"none"` forbids), it is asked for once more, with a note that is not kept, unless it was
147
+ `"filtered"`, blocked, or `"cut"` with nothing in it. That try is one of the two, and may be one
148
+ request past `limits.toolTurns`.
149
+
150
+ ### Errors to throw
151
+
152
+ Throw a `ModelRequestError` for every request that failed:
153
+ `new ModelRequestError(message, status, options?)`. Its options are all optional.
154
+
155
+ | Argument | What to give |
156
+ |---|---|
157
+ | `message` | The provider's message. The kind is read from it, and so are `limitTokens` and `requestedTokens` for a request too large. It is the provider's wording: log it, and do not show it to users. |
158
+ | `status` | The HTTP status. `0` for a request that got no answer: the connection failed, or a stream closed before it said how it ended. |
159
+ | `retryAfterMs` | The wait the provider asked for. `retryAfterMs(response.headers, body)` reads `retry-after-ms`, `Retry-After`, and the `RetryInfo` of a Gemini error body. |
160
+ | `code` | The provider's own word for the error (OpenAI's `error.code`, Claude's `error.type`, Gemini's `error.status`). `"insufficient_quota"` makes it a `"quota"`, as do HTTP 402 and a message that only a quota writes (no credit left, a spending cap, a quota per day). `"context_length_exceeded"` and `"request_too_large"` make it a `"context_overflow"` for a status below 500 other than 429, whose message does not speak of rate limits. A 429 or 413 that says "Request too large for … on tokens per min" (OpenAI's and Groq's TPM) is a `"context_overflow"` too, with its numbers. With status 0 the code is not read: the kind is `"unreachable"` unless you give `kind`. |
161
+ | `details` | The `details` of a Gemini error: a daily quota and an API key that is not valid are told from them. |
162
+ | `kind` | The kind, when you know it better than the classifier: `"timeout"` with status 0 when your own wait for a silent model ran out, or `"context_overflow"` for a gateway's wording that the classifier does not know. Give that one with the 4xx status the gateway sent, such as 400 (a 413 is read as one without it), and see [Wrapping an adapter](#wrapping-an-adapter). |
163
+ | `cause` | The error underneath, for your logs. |
164
+
165
+ The kind is told from the status, the message, `code` and `details` by `classifyModelError`, which
166
+ you can call to see how a message is read. The kinds and what to show for each are in
167
+ [Errors and reliability](./errors-and-reliability.md). What the loop does with your error:
168
+
169
+ - **Sent again**, up to 3 times by default (`AskOptions.retry`): status 0, 408, 409, 429 and 5xx
170
+ (`isRetryableStatus`). The wait is 500 ms, doubled for each try, times a jitter between 0.5 and
171
+ 1, and never more than `maxDelayMs` (60 seconds). The wait in `retryAfterMs` is taken instead,
172
+ unless it is longer than `maxDelayMs`: the error is then thrown at once.
173
+ - **Sent again once**: kind `"timeout"` with status 0.
174
+ - **Not sent again**: kind `"quota"`, any other status, and an error without a status (a plain
175
+ `Error` ends the question). Nothing is sent again once text of the request was passed to
176
+ `onText`, or after the signal aborted.
177
+ - **Made smaller**: kind `"context_overflow"`. It is never sent again as it is, whatever its status:
178
+ only a smaller request can pass. Older tool results are shortened and the request is sent again,
179
+ at most twice in a question, and never for an `appendOnly` model. When nothing could be
180
+ shortened, or the shortened request was refused again, and no tool has run yet and no text was
181
+ shown, the documents are planned again, once, for the window the provider named (`limitTokens`)
182
+ or a smaller one. Otherwise the error is thrown. So set this kind only on an error that a wait
183
+ would not mend.
184
+
185
+ A body of HTTP 200 that is not JSON (a gateway's page in the model's place) is best thrown as
186
+ `new ModelRequestError(message, response.status, { kind: "invalid", cause })`, as the package's
187
+ adapters do: it is not sent again, and a whole-file read tells the model "The model's reply could
188
+ not be read (HTTP 200).". An empty body of HTTP 200 is a reply cut off on its way: the package's
189
+ adapters throw it with status 0, which is sent again.
190
+
191
+ The error that ends a question reaches your code as it is, and `partialResultOf(error)` gives what
192
+ the question found and paid for until then. The adapters of the package throw subclasses
193
+ (`GeminiRequestError`, `OpenAiRequestError`, `AnthropicRequestError`); a subclass of your own
194
+ works the same way.
195
+
196
+ ### Part reads: `generateText`
197
+
198
+ `analyze_whole_document` reads a file in parts, one plain completion each, through the
199
+ `generateText` of the model that explores: the explorer when there is one, otherwise `model`. A
200
+ `GenerateText` takes `{ system, prompt, maxOutputTokens, signal?, onTruncated?, onUsage? }` and
201
+ returns the text of the reply.
202
+
203
+ - One prompt, no tools, no conversation. `maxOutputTokens` is 4,096 for the notes on a part and
204
+ for a merge of notes, and 8,192 for the answer of the read. Send it as the provider's output
205
+ limit, and pass `signal` to the request.
206
+ - Call `onUsage` once for each request that was answered, with its tokens as in `usage` above. A
207
+ part read that returns without calling it is counted as a request with no tokens.
208
+ - Call `onTruncated` when the reply stopped at the output limit, or a filter stopped it: the read
209
+ then says that its answer is incomplete.
210
+ - Throw when the reply has no text. An empty string is taken as the notes on the part, and the
211
+ part is not reported as one that could not be read.
212
+ - Throw `ModelRequestError` as `send` does. Part reads are sent again by the same rules, and an
213
+ error without a status is tried once more at once. A part that still fails is reported as one
214
+ that could not be read; one refused as too large (`"context_overflow"`) may be read as two
215
+ halves. Up to four requests of one read run at once.
216
+ - The model is told why a part failed by the error's kind, its HTTP status (`status`,
217
+ `statusCode` or `response.status`, as a provider's SDK sets them) or the code of a connection
218
+ that failed, never by its message, which may name a host or a key. A plain `Error` without them
219
+ is told as "The model request failed.". So give your errors a `kind` or a `status`
220
+ ([Failures inside tools](./errors-and-reliability.md#failures-inside-tools)).
221
+ - A model that thinks counts its thoughts in `maxOutputTokens`, and can spend all of it on them.
222
+ The adapters of the package send such a request again with `THINKING_OUTPUT_TOKENS` (32,768,
223
+ exported by `llm-large-files/gemini`). For a model of yours that thinks, send at least that.
224
+ - Set a timeout of your own. The adapters of the package give a part read 180 seconds.
225
+
226
+ ### `requestBytes` and `estimateTokens`
227
+
228
+ `requestBytes(request)` returns the size in bytes of the body `send` would post for `request`. The
229
+ loop calls it on the model that explores, in a turn that looks at pages, with the model's turn
230
+ that is about to be answered as a last round whose `answers` is empty. The pages then get what is
231
+ left of `maxRequestBytes` after that request and a margin of a tenth of it (at least 256 KB),
232
+ times 3/4 for base64. Without `requestBytes`, the loop uses its estimate of the request. The size
233
+ of the body without streaming is close enough.
234
+
235
+ `estimateTokens(text)` is deprecated: the loop never calls it, and a later version may remove it.
236
+ Every size is the library's estimate (`estimateTokens` from `llm-large-files`) scaled by
237
+ `capabilities.tokenScale`: set that for a tokenizer that counts differently, and leave the
238
+ `estimateTokens` member out of your adapter. An adapter that still declares it compiles as before.
239
+
240
+ ## A complete adapter
241
+
242
+ Example AI is a made-up provider, so that the adapter shows the contract and nothing else. Its API
243
+ takes one `POST` to `{baseUrl}/chat` with `model`, `system`, `messages`, `tools`, `tool_choice` and
244
+ `stream`. A message is `{ role, content }`. A model turn may carry `tool_calls`
245
+ (`{ id, name, arguments }`, the arguments as JSON text), and a `tool` message answers one by its
246
+ `tool_call_id`. A reply is `{ message, stop_reason, usage }`. A stream sends `text`, `tool_call`,
247
+ `end` and `error` events. Errors are HTTP statuses with `{ error: { message, code } }`, and
248
+ `max_output_tokens` sets the output limit.
249
+
250
+ ```ts
251
+ // example-ai.ts: an adapter for Example AI, a made-up provider.
252
+ import {
253
+ ModelRequestError,
254
+ parseSseJson,
255
+ retryAfterMs,
256
+ SseEventTooLongError,
257
+ type GenerateText,
258
+ type ModelAdapter,
259
+ type ModelMessage,
260
+ type ModelReply,
261
+ type ModelRequest,
262
+ type ModelUsage,
263
+ type ToolCall,
264
+ } from "llm-large-files";
265
+
266
+ // The provider's own shapes.
267
+ type ExampleCall = { id: string; name: string; arguments: string };
268
+ type ExampleMessage = { role: "user" | "assistant" | "tool"; content: unknown; tool_calls?: ExampleCall[]; tool_call_id?: string };
269
+ type ExampleUsage = { input_tokens?: number; cached_input_tokens?: number; output_tokens?: number; reasoning_tokens?: number };
270
+ type ExampleReply = { message?: { content?: string; tool_calls?: ExampleCall[] }; stop_reason?: string; usage?: ExampleUsage };
271
+ type ExampleEvent =
272
+ | { type: "text"; text: string }
273
+ | { type: "tool_call"; call: ExampleCall }
274
+ | { type: "end"; stop_reason: string; usage?: ExampleUsage }
275
+ | { type: "error"; status?: number; message: string };
276
+
277
+ export type ExampleAiOptions = {
278
+ baseUrl: string;
279
+ apiKey: string;
280
+ model: string;
281
+ /** The model's context window, in tokens. */
282
+ contextTokens: number;
283
+ };
284
+
285
+ /** Every prompt token, cached ones included; every output token, reasoning included. */
286
+ const usageOf = (usage: ExampleUsage | undefined): Partial<ModelUsage> => ({
287
+ inputTokens: usage?.input_tokens ?? 0,
288
+ cachedInputTokens: usage?.cached_input_tokens ?? 0,
289
+ outputTokens: usage?.output_tokens ?? 0,
290
+ thoughtTokens: usage?.reasoning_tokens ?? 0,
291
+ });
292
+
293
+ const finishOf = (reason: string | undefined): ModelReply["finish"] => {
294
+ if (reason === "end" || reason === "tool_calls") return "complete";
295
+ if (reason === "max_tokens") return "cut";
296
+ if (reason === "safety") return "filtered";
297
+ if (reason === "malformed_tool_call") return "malformed_call";
298
+ return undefined;
299
+ };
300
+
301
+ /** A call whose arguments are not a JSON object is answered with `problem`, not run. */
302
+ function toCall(call: ExampleCall): ToolCall {
303
+ let args: unknown;
304
+ try {
305
+ args = JSON.parse(call.arguments);
306
+ } catch {
307
+ args = undefined;
308
+ }
309
+ if (args && typeof args === "object" && !Array.isArray(args)) return { id: call.id, name: call.name, args: args as Record<string, unknown> };
310
+ return { id: call.id, name: call.name, args: {}, problem: `The arguments were not a JSON object: ${call.arguments.slice(0, 200)}. Send the call again.` };
311
+ }
312
+
313
+ function replyOf(text: string, calls: ExampleCall[], reason: string | undefined, usage: ExampleUsage | undefined): ModelReply {
314
+ const finish = finishOf(reason);
315
+ return {
316
+ text,
317
+ calls: calls.map(toCall),
318
+ // This turn as the provider wrote it: it comes back in `raw` of the tool round, to be sent as it is.
319
+ raw: { role: "assistant", content: text, tool_calls: calls } satisfies ExampleMessage,
320
+ ...(reason ? { finishReason: reason } : {}),
321
+ ...(finish ? { finish } : {}),
322
+ // Refused before it wrote anything: the question ends here, with `blockReason`.
323
+ ...(reason === "safety" && !text && calls.length === 0 ? { blockReason: "safety" } : {}),
324
+ ...(usage ? { usage: usageOf(usage), providerUsage: usage } : {}),
325
+ };
326
+ }
327
+
328
+ /** The neutral conversation in Example AI's form. */
329
+ function toMessages(messages: ModelMessage[]): ExampleMessage[] {
330
+ return messages.flatMap((message, at): ExampleMessage[] => {
331
+ if (message.role !== "tools") {
332
+ // Text parts, and parts in the provider's own form that the application passed in `messages`.
333
+ return [{ role: message.role, content: message.parts.map((part) => (part.native !== undefined ? part.native : { type: "text", text: part.text })) }];
334
+ }
335
+ // A call without an ID (a stored round) gets one from its place: the same for the call and its result.
336
+ const idOf = (call: ToolCall, index: number) => call.id ?? `call_${at}_${index}`;
337
+ // This adapter's own turn goes back unchanged. Without `raw` (a stored round, or another model's), it is built from the calls.
338
+ const asked: ExampleMessage = message.raw !== undefined ? message.raw as ExampleMessage : {
339
+ role: "assistant",
340
+ content: "",
341
+ tool_calls: message.calls.map((call, index) => ({ id: idOf(call, index), name: call.name, arguments: JSON.stringify(call.args) })),
342
+ };
343
+ // One answer for each call, in call order.
344
+ const results = message.answers.map((answer, index): ExampleMessage => ({
345
+ role: "tool",
346
+ tool_call_id: idOf(answer.call, index),
347
+ content: JSON.stringify(answer.result),
348
+ }));
349
+ // Pages from view_pages go "beside" the results, in a user turn of their own.
350
+ const files = message.answers.flatMap((answer) => (answer.files ?? []).map((file) => ({
351
+ type: "file",
352
+ name: file.name,
353
+ mime_type: file.mimeType,
354
+ data: Buffer.from(file.bytes).toString("base64"),
355
+ })));
356
+ return [asked, ...results, ...(files.length > 0 ? [{ role: "user" as const, content: files }] : [])];
357
+ });
358
+ }
359
+
360
+ export function exampleAi(options: ExampleAiOptions): ModelAdapter {
361
+ const bodyOf = (request: ModelRequest, stream: boolean) => ({
362
+ model: options.model,
363
+ ...(request.system ? { system: request.system } : {}),
364
+ messages: toMessages(request.messages),
365
+ // `toolChoice: "none"`: the tools stay listed, and the model must answer in text.
366
+ ...(request.tools?.length ? { tools: request.tools, tool_choice: request.toolChoice ?? "auto" } : {}),
367
+ stream,
368
+ });
369
+
370
+ /** Posts a body. A failed connection is status 0; an HTTP error keeps its status, code and wait. */
371
+ const post = async (body: unknown, signal: AbortSignal | undefined): Promise<Response> => {
372
+ let response: Response;
373
+ try {
374
+ response = await fetch(`${options.baseUrl}/chat`, {
375
+ method: "POST",
376
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${options.apiKey}` },
377
+ body: JSON.stringify(body),
378
+ ...(signal ? { signal } : {}),
379
+ });
380
+ } catch (error) {
381
+ // Stopped by the caller (or by a timeout of ours): passed on as it is.
382
+ if (signal?.aborted) throw error;
383
+ throw new ModelRequestError("Example AI could not be reached.", 0, { cause: error });
384
+ }
385
+ if (!response.ok) {
386
+ const data = (await response.json().catch(() => null)) as { error?: { message?: string; code?: string } } | null;
387
+ const wait = retryAfterMs(response.headers, data);
388
+ throw new ModelRequestError(data?.error?.message ?? `Example AI returned HTTP ${response.status}.`, response.status, {
389
+ code: data?.error?.code,
390
+ ...(wait === undefined ? {} : { retryAfterMs: wait }),
391
+ });
392
+ }
393
+ return response;
394
+ };
395
+
396
+ /** Part reads of analyze_whole_document: one prompt, no tools, no streaming. */
397
+ const generateText: GenerateText = async ({ system, prompt, maxOutputTokens, signal, onTruncated, onUsage }) => {
398
+ const timeout = AbortSignal.timeout(180_000);
399
+ const response = await post({
400
+ model: options.model,
401
+ system,
402
+ messages: [{ role: "user", content: [{ type: "text", text: prompt }] }],
403
+ max_output_tokens: maxOutputTokens,
404
+ stream: false,
405
+ }, signal ? AbortSignal.any([signal, timeout]) : timeout);
406
+ const data = (await response.json()) as ExampleReply;
407
+ onUsage?.(usageOf(data.usage));
408
+ const text = data.message?.content ?? "";
409
+ if (!text.trim()) throw new Error(`Example AI returned no text (${data.stop_reason ?? "no reason given"}).`);
410
+ if (data.stop_reason === "max_tokens" || data.stop_reason === "safety") onTruncated?.();
411
+ return text;
412
+ };
413
+
414
+ return {
415
+ id: options.model,
416
+ capabilities: { contextTokens: options.contextTokens, toolFiles: "beside", pageTokens: 1_000 },
417
+ requestBytes: (request) => Buffer.byteLength(JSON.stringify(bodyOf(request, false))),
418
+ generateText,
419
+
420
+ async send(request, hooks = {}) {
421
+ const stream = Boolean(hooks.onText);
422
+ const response = await post(bodyOf(request, stream), hooks.signal);
423
+ if (!stream || !response.body) {
424
+ // In one piece. The loop passes the text on to onText itself.
425
+ const data = (await response.json()) as ExampleReply;
426
+ return replyOf(data.message?.content ?? "", data.message?.tool_calls ?? [], data.stop_reason, data.usage);
427
+ }
428
+ let text = "";
429
+ const calls: ExampleCall[] = [];
430
+ let end: { stop_reason: string; usage?: ExampleUsage } | undefined;
431
+ try {
432
+ for await (const event of parseSseJson<ExampleEvent>(response.body, { signal: hooks.signal })) {
433
+ if (event.type === "error") throw new ModelRequestError(event.message, event.status ?? 500);
434
+ if (event.type === "text") {
435
+ text += event.text;
436
+ hooks.onText?.(event.text);
437
+ } else if (event.type === "tool_call") {
438
+ calls.push(event.call);
439
+ } else {
440
+ end = event;
441
+ }
442
+ }
443
+ } catch (error) {
444
+ if (hooks.signal?.aborted || error instanceof ModelRequestError) throw error;
445
+ // An event too long to hold would come again: not sent again (status 200, kind "invalid").
446
+ if (error instanceof SseEventTooLongError) throw new ModelRequestError(error.message, response.status, { kind: "invalid", cause: error });
447
+ throw new ModelRequestError("The connection to Example AI failed during the reply.", 0, { cause: error });
448
+ }
449
+ // No end event: the stream was cut off on its way. Sent again like a lost connection, unless text was shown.
450
+ if (!end) throw new ModelRequestError("Example AI's reply ended before it was complete.", 0);
451
+ return replyOf(text, calls, end.stop_reason, end.usage);
452
+ },
453
+ };
454
+ }
455
+ ```
456
+
457
+ It is a model like any other:
458
+
459
+ ```ts
460
+ import { readFile } from "node:fs/promises";
461
+ import { askWithFiles, createLargeFiles, FileDocumentStore } from "llm-large-files";
462
+ import { exampleAi } from "./example-ai.js";
463
+
464
+ const files = createLargeFiles({ store: new FileDocumentStore("./data/large-files") });
465
+ const model = exampleAi({
466
+ baseUrl: process.env.EXAMPLE_AI_URL!,
467
+ apiKey: process.env.EXAMPLE_AI_KEY!,
468
+ model: "example-large",
469
+ contextTokens: 256_000,
470
+ });
471
+
472
+ const log = await files.ingest({ name: "app.log", bytes: await readFile("./app.log") });
473
+ const result = await askWithFiles({
474
+ files,
475
+ model,
476
+ documentIds: [log.id],
477
+ messages: [{ role: "user", text: "Why did the checkout service time out?" }],
478
+ onText: (delta) => process.stdout.write(delta),
479
+ });
480
+ console.log("\n", result.answered, result.usage.byModel["example-large"]);
481
+ ```
482
+
483
+ What this adapter leaves out, and the adapters of the package do:
484
+
485
+ - **A wait for a silent model.** A request here waits as long as `fetch` does. The adapters of the
486
+ package abort a request that sends nothing for `firstByteTimeoutMs` (600 seconds by default), or
487
+ nothing between two pieces for `idleTimeoutMs` (300 seconds), and throw kind `"timeout"` with
488
+ status 0. [`parseSseJson`](#parsessejson) below shows such a wait.
489
+ - **Two user turns in a row** are sent as they are. Join them if your provider refuses them.
490
+ - **A call cut off at the output limit** is run when its arguments still parse. The OpenAI-compatible
491
+ adapter gives every call of a reply that ended at the limit a `problem` instead.
492
+ - **A body that is not JSON** throws a `SyntaxError`, which has no status: a chat request is not
493
+ sent again, a part read is tried once more, and the model is told "The model request failed.".
494
+ The adapters of the package throw kind `"invalid"` with the response's status for it, which is
495
+ not sent again, and kind `"unreachable"` with status 0, which is, for an empty body.
496
+ - **A part read with no text** throws a plain `Error`, and the model is told "The model request
497
+ failed.", not its message. The package's part readers say "The model returned no text
498
+ (SAFETY).", with the provider's reason.
499
+ - **`pageTokens: 1_000`** is a placeholder: give what your provider bills for one PDF page.
500
+ - **A model that thinks**: `generateText` sends `maxOutputTokens` as it is.
501
+
502
+ ## Wrapping an adapter
503
+
504
+ A wrapper is an adapter that calls another. It sees every chat request (`send`) and every part read
505
+ (`generateText`) of the questions it is given, so it is the place for logs, metrics, a quota per
506
+ user, and a limit on requests at once: the loop runs up to four tool calls of a turn at once, and
507
+ up to four requests of a whole-file read, but sets no limit across questions.
508
+
509
+ Keep the inner adapter's `id` and `capabilities`, pass `hooks` through unchanged, and keep
510
+ `requestBytes` and `generateText` when the inner adapter has them. A wrapper without
511
+ `generateText` turns whole-file reads off.
512
+
513
+ ```ts
514
+ // controlled.ts: any adapter, with a quota per user, a shared limit and a record of every request.
515
+ import { ModelRequestError, type GenerateText, type ModelAdapter, type ModelRequest, type ModelUsage } from "llm-large-files";
516
+
517
+ /** Your own accounting: a database table, a metrics client. */
518
+ export type Accounting = {
519
+ /** How many model requests this user may still make today. */
520
+ requestsLeft(user: string): Promise<number>;
521
+ record(entry: { user: string; model: string; kind: "chat" | "part"; ms: number; usage: Partial<ModelUsage> | undefined }): void;
522
+ };
523
+
524
+ // At most 16 model requests at once in this process, over every question and every user.
525
+ const MOST_AT_ONCE = 16;
526
+ let running = 0;
527
+ const waiting: Array<() => void> = [];
528
+ async function inTurn<T>(run: () => Promise<T>): Promise<T> {
529
+ while (running >= MOST_AT_ONCE) await new Promise<void>((resolve) => waiting.push(resolve));
530
+ running++;
531
+ try {
532
+ return await run();
533
+ } finally {
534
+ running--;
535
+ waiting.shift()?.();
536
+ }
537
+ }
538
+
539
+ export function controlled(inner: ModelAdapter, user: string, accounting: Accounting): ModelAdapter {
540
+ const reader = inner.generateText;
541
+ const generateText: GenerateText | undefined = reader && ((request) => inTurn(() => {
542
+ const started = Date.now();
543
+ return reader({
544
+ ...request,
545
+ // Called once for each answered part read: record it, and pass it on to the loop's totals.
546
+ onUsage: (usage) => {
547
+ accounting.record({ user, model: inner.id, kind: "part", ms: Date.now() - started, usage });
548
+ request.onUsage?.(usage);
549
+ },
550
+ });
551
+ }));
552
+
553
+ return {
554
+ // The same id and capabilities: usage totals and the budget stay those of the model.
555
+ id: inner.id,
556
+ capabilities: inner.capabilities,
557
+ ...(inner.requestBytes ? { requestBytes: (request: ModelRequest) => inner.requestBytes!(request) } : {}),
558
+ ...(generateText ? { generateText } : {}),
559
+
560
+ async send(request, hooks) {
561
+ if (await accounting.requestsLeft(user) <= 0) {
562
+ // Kind "quota" is never sent again: the question ends with this error.
563
+ throw new ModelRequestError("This user has no model requests left today.", 429, { kind: "quota" });
564
+ }
565
+ return inTurn(async () => {
566
+ const started = Date.now();
567
+ // The hooks go through unchanged: onText streams the answer, signal cancels the request.
568
+ const reply = await inner.send(request, hooks);
569
+ accounting.record({ user, model: inner.id, kind: "chat", ms: Date.now() - started, usage: reply.usage });
570
+ return reply;
571
+ });
572
+ },
573
+ };
574
+ }
575
+ ```
576
+
577
+ Wrap the Vertex AI model, and handle the quota where the question is asked:
578
+
579
+ ```ts
580
+ import { GoogleAuth } from "google-auth-library";
581
+ import { askWithFiles, errorKindOf, partialResultOf } from "llm-large-files";
582
+ import { gemini, vertexAi } from "llm-large-files/gemini";
583
+ import { controlled } from "./controlled.js";
584
+
585
+ const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
586
+ const vertex = gemini(vertexAi({
587
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
588
+ location: "global",
589
+ model: "gemini-3.8-flash",
590
+ accessToken: async () => {
591
+ const token = await auth.getAccessToken();
592
+ if (!token) throw new Error("No access token from the application default credentials.");
593
+ return token;
594
+ },
595
+ }));
596
+
597
+ // files, documentIds, userId and accounting come from your application.
598
+ try {
599
+ const result = await askWithFiles({
600
+ files,
601
+ model: controlled(vertex, userId, accounting),
602
+ documentIds,
603
+ owner: userId,
604
+ messages: [{ role: "user", text: "Summarize the errors of the last hour." }],
605
+ });
606
+ console.log(result.text);
607
+ } catch (error) {
608
+ if (errorKindOf(error) !== "quota") throw error;
609
+ // What the question found and paid for before the allowance ran out.
610
+ console.log("Allowance used up.", partialResultOf(error)?.usage.requests ?? 0, "requests made");
611
+ }
612
+ ```
613
+
614
+ - **Retries go through the wrapper.** The loop sends a failed request again by calling `send`
615
+ again, so the quota is checked before every try, and a try that failed is not recorded.
616
+ - **The queue does not watch the signal.** A cancelled question waits for its turn, and then fails
617
+ at once.
618
+ - **One wrapper per model and question.** `controlled(vertex, ...)` called twice gives two
619
+ adapters: passed as `model` and `explorer`, they would be two models. Pass the same wrapper
620
+ object, or leave `explorer` out.
621
+ - **Headers are not the wrapper's.** `send` never sees the HTTP request. For a header per tenant,
622
+ use the adapter's own options: a `headers` function (on `openAiCompatible()` and `anthropic()`,
623
+ or the endpoint's `headers` for `gemini()`), or its `fetch` option. Both are called for every
624
+ request.
625
+
626
+ **Errors a gateway words its own way.** When a gateway refuses a request as too large in words the
627
+ classifier does not know, the error gets another kind, most often `"invalid"`, and the loop makes
628
+ no room for it. A wrapper can catch the inner adapter's error and throw a new one with the kind:
629
+ `kind` is read-only, so the error cannot be changed in place.
630
+
631
+ ```ts
632
+ // gateway-errors.ts: a gateway's own wording for a request too large, read as one.
633
+ import { ModelRequestError, type ModelAdapter } from "llm-large-files";
634
+
635
+ const TOO_LARGE = /prompt exceeds the gateway's token limit/i; // your gateway's wording
636
+
637
+ export function withGatewayErrors(inner: ModelAdapter): ModelAdapter {
638
+ return {
639
+ ...inner, // id, capabilities, requestBytes and generateText stay the inner adapter's
640
+ async send(request, hooks) {
641
+ try {
642
+ return await inner.send(request, hooks);
643
+ } catch (error) {
644
+ if (error instanceof ModelRequestError && error.kind === "invalid" && TOO_LARGE.test(error.message)) {
645
+ // Keep the gateway's status. With this kind the error is never sent again as it is: the loop makes room.
646
+ throw new ModelRequestError(error.message, error.status, { kind: "context_overflow", cause: error });
647
+ }
648
+ throw error;
649
+ }
650
+ },
651
+ };
652
+ }
653
+ ```
654
+
655
+ - The new error is a plain `ModelRequestError`: code that checks for a subclass, such as
656
+ `GeminiRequestError`, no longer sees one. The first error is its `cause`.
657
+ - It has no `limitTokens`: those are read only from wording the classifier knows. A plan made
658
+ again for it is for 7/10 of the window the budget assumed.
659
+ - Part reads do not go through `send`. Wrap `generateText` the same way when they pass the same
660
+ gateway: a part refused as too large can then be read as two halves.
661
+
662
+ For a scripted adapter in tests, see [Testing](./testing.md).
663
+
664
+ ## Your own loop
665
+
666
+ When you already run a tool loop, use the library for the documents only: `files.prepare()` plans
667
+ a request, and `files.tools()` gives the tools to offer and runs their calls. Nothing of
668
+ `askWithFiles` runs then.
669
+
670
+ ### What is yours to do
671
+
672
+ - **Turns, and a last request for the answer.** Limit the turns, and end with a request that must
673
+ be answered in text. The notes the loop sends for that are exported: `FINAL_ANSWER_REQUEST`
674
+ (after tool results), `FINAL_ANSWER_AFTER_PAGES` (when the only tool was `view_pages`) and
675
+ `FINAL_ANSWER_WITHOUT_TOOLS` (when no tool ran).
676
+ - **Room in the request.** One result is capped at `budget.toolResultCharacters` (24,000 by
677
+ default), but nothing stops a turn of many calls from filling the window. Limit the calls of a
678
+ turn, and pass the room that is left as `maxResultCharacters`. When the request runs short,
679
+ replace the results of older rounds with `stubResult(call, result, hadFiles)`: the short
680
+ stand-in `askWithFiles` uses, which keeps the document's name and the lines or pages the result
681
+ showed, so that the model can get them again. Pass `true` as `hadFiles` for a result that came
682
+ with pages, and drop the pages with it. It is `undefined` when it would save nothing: an error, a stand-in
683
+ already, or a result under 700 characters without pages. Leave the turns of a model whose
684
+ conversation may only grow, such as Claude, as they are ([Capabilities](#capabilities)).
685
+ - **Retries**, with [`withRetry`](#withretry) and errors that carry a status.
686
+ - **Usage.** `UsageMeter` sums it by model: `meter.add(modelId, usage)`, then `meter.totals`.
687
+ - **Steps and evidence.** `tools.describe(name, args)` labels a call ("Search app.log (exact) for
688
+ “timeout”"), `toolResultSummary(label, result)` adds what it found ("— 12 matching lines", "— 1
689
+ matching line"), and `evidenceOf(call, result)` gives the lines or pages it showed. A label
690
+ quotes the model's words: `askWithFiles` makes its steps one line of plain text (no line breaks,
691
+ no text-direction controls, `](` written `] (`), and a loop of your own should show them as plain
692
+ text too, never as markdown or HTML.
693
+ - **Rounds of an earlier question.** `askWithFiles` sends their results without
694
+ `tool_turns_left`, a count that was of their own question's turns. Leave it out too when you send
695
+ stored rounds again.
696
+
697
+ Some of what `askWithFiles` does has no public form, and is not there in a loop of your own: when
698
+ to shorten old tool results, recovering from a request too large, the second try after an empty
699
+ reply or a malformed call, a pointer in place of a call that repeats one already answered, and
700
+ refusing a whole-file read that would pass a ceiling of the question before it starts.
701
+
702
+ ### The steps
703
+
704
+ 1. **Plan.** `files.prepare(documentIds, base, { owner, viewPages, wholeDocumentAnalysis, budget })`.
705
+ `base` is the size of the rest of the request, `{ tokens, bytes }`: the system prompt and the
706
+ conversation, with a margin for what frames them (`askWithFiles` adds 2,000 tokens and 8,000
707
+ bytes). The documents are fitted into what the budget leaves. Pass `wholeDocumentAnalysis: false`
708
+ when your tools will have no `generate` (step 3): the instruction then leaves out
709
+ `analyze_whole_document`, and the cards do not offer a whole-file read. The result is a
710
+ `PreparedContext`:
711
+ - `missing`: IDs that were never uploaded, were deleted, have expired, or belong to another
712
+ owner. Stop and ask for them again. `askWithFiles` throws `DocumentsNotFoundError` here.
713
+ - `blocks`: for each document, its whole text or its card. Put them at the start of the first
714
+ user turn, in the order of your IDs.
715
+ - `instruction`: the guide to the tools, for the system prompt. Empty when there is nothing to
716
+ search or look at.
717
+ - `plan`: `inline` (sent whole), `searchable` (reached through the tools), and the tokens and
718
+ bytes of the inline text.
719
+ - `viewable`: the PDFs whose pages `view_pages` can show, because their uploaded file is kept
720
+ (`keepOriginals`). Empty unless you pass `viewPages: true` and the store keeps originals.
721
+ 2. **No tools needed?** When `plan.searchable` and `viewable` are both empty, every document is in
722
+ the prompt: send one request without tools.
723
+ 3. **Tools.** `files.tools(prepared.plan.searchable, options)` gives a `ToolSet`. The options that
724
+ matter here: `generate` (a `GenerateText`, which turns on `analyze_whole_document`; without it,
725
+ plan with `wholeDocumentAnalysis: false` in step 1), `viewPages` (pass `prepared.viewable`, and
726
+ only when your loop sends files to the model), `signal`, `onProgress` (progress of whole-file
727
+ reads, for every call; per call, see [`ToolCallHooks`](#progress-of-each-call-toolcallhooks)),
728
+ `maxWholeDocumentReads` (1 by default), `regexBudgetMs` (6,000), `retry` and `budget`.
729
+ Make one tool set for each question: the count of whole-file reads and the time for regex
730
+ searches belong to it. The full list is in the
731
+ [library reference](../reference/library.md#tooloptions).
732
+
733
+ Pass `tools()` only metadata that came back for this user: `prepared.plan.searchable` and
734
+ `prepared.viewable` from `prepare(ids, base, { owner })`, or `getMeta(id, { owner })`. The tool
735
+ set takes no owner option: the model can reach every document it is given, and each call
736
+ compares the owner stored with the document with the `owner` of the metadata it was handed.
737
+ Metadata built from IDs the client sent, without the stored owner, reads nothing of a document
738
+ that has one: each call answers `doc_… is no longer available on the server. …`.
739
+ 4. **Offer** `tools.declarations` in your provider's form. Gemini takes them as
740
+ `functionDeclarations` (`toGeminiTools`), the OpenAI-compatible adapter sends each as
741
+ `{ type: "function", function: declaration }`, and the Claude adapter as
742
+ `{ name, description, input_schema: parameters }`.
743
+ 5. **Run** each call with `tools.executeWithFiles(name, args, limits, hooks?)`, which returns
744
+ `{ result, files }`. It does not throw for a call that went wrong: an unknown tool, bad
745
+ arguments, a document outside this tool set, a store that failed, or a whole-file read that
746
+ failed all come back as `{ error }`, for the model to read. It throws only when your `signal`
747
+ aborted. `files` is empty for every tool but `view_pages`, whose pages come as one PDF
748
+ (`{ name, mimeType: "application/pdf", bytes }`): send it with the result, in your provider's
749
+ form. `tools.execute(name, args)` is the same without files and without limits, and answers
750
+ `view_pages` with an error, because it has nowhere to put the pages. An unknown tool is
751
+ answered `Unknown tool “do_magic”.`, its name quoted and cut at 64 characters. A whole-file read
752
+ whose model requests failed tells the model why by the kind and status of the error, never by
753
+ its words ([Failures inside tools](./errors-and-reliability.md#failures-inside-tools)).
754
+
755
+ To offer tools of your own as well, declare them next to `tools.declarations`, with names other
756
+ than the library's (`TOOL_NAMES`), and send a call to `tools.executeWithFiles` only when
757
+ `tools.has(call.name)`. Run the others yourself, and treat their arguments as untrusted input:
758
+ a file the model reads can ask it for anything. Check them, and ask the user before anything
759
+ that cannot be undone.
760
+ 6. **Loop** with the results, and end with a request for the answer.
761
+
762
+ Plan and run the tools with the same budget. The library's own fits a model with a 1M-token window
763
+ unless you set `budget.contextTokens` in `createLargeFiles`. For a budget of one request, pass
764
+ `budget` to both `prepare` and `tools`; `files.budgetFor(overrides, { contextTokens, maxRequestBytes })`
765
+ gives one that fits a model's limits.
766
+
767
+ ### A loop on Vertex AI
768
+
769
+ This loop answers one question with Gemini on Vertex AI, through the Generate Content REST API and
770
+ the helpers of `llm-large-files/gemini`: `toGeminiTools` for the declarations,
771
+ `geminiFunctionResponseTurns` for the results and their pages, `createGeminiGenerateText` for part
772
+ reads, and `usageOfGemini` for usage.
773
+
774
+ ```ts
775
+ import { GoogleAuth } from "google-auth-library";
776
+ import {
777
+ createLargeFiles,
778
+ estimateTokens,
779
+ evidenceOf,
780
+ FileDocumentStore,
781
+ FINAL_ANSWER_AFTER_PAGES,
782
+ FINAL_ANSWER_REQUEST,
783
+ jsonBytes,
784
+ retryAfterMs,
785
+ toolResultSummary,
786
+ UsageMeter,
787
+ withRetry,
788
+ type Evidence,
789
+ type ToolAnswer,
790
+ type ToolCall,
791
+ } from "llm-large-files";
792
+ import {
793
+ createGeminiGenerateText,
794
+ GEMINI_PAGE_TOKENS,
795
+ geminiFunctionResponseTurns,
796
+ GeminiRequestError,
797
+ toGeminiTools,
798
+ usageOfGemini,
799
+ vertexAi,
800
+ type GeminiContent,
801
+ } from "llm-large-files/gemini";
802
+
803
+ const MODEL = "gemini-3.8-flash";
804
+ const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
805
+ const endpoint = vertexAi({
806
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
807
+ location: "global",
808
+ model: MODEL,
809
+ accessToken: async () => {
810
+ const token = await auth.getAccessToken();
811
+ if (!token) throw new Error("No access token from the application default credentials.");
812
+ return token;
813
+ },
814
+ });
815
+
816
+ // Keep the uploaded PDFs, so that view_pages can show their pages.
817
+ const files = createLargeFiles({ store: new FileDocumentStore("./data/large-files"), keepOriginals: ["pdf"] });
818
+
819
+ const MAX_TURNS = 8; // model requests of the chat, the answer's included
820
+ const MAX_CALLS = 8; // tool calls run in one turn
821
+ const MAX_REQUESTS = 40; // every model request of the question, part reads included
822
+
823
+ type GenerateResponse = { candidates?: Array<{ content?: GeminiContent }>; usageMetadata?: Record<string, unknown> };
824
+
825
+ /** One generateContent request. Its errors carry the status and kind that withRetry reads. */
826
+ async function generateContent(body: unknown, signal: AbortSignal | undefined): Promise<GenerateResponse> {
827
+ const headers = typeof endpoint.headers === "function" ? await endpoint.headers() : endpoint.headers;
828
+ let response: Response;
829
+ try {
830
+ response = await fetch(endpoint.url, { method: "POST", headers, body: JSON.stringify(body), ...(signal ? { signal } : {}) });
831
+ } catch (error) {
832
+ if (signal?.aborted) throw error;
833
+ throw new GeminiRequestError("Vertex AI could not be reached.", 0, { cause: error });
834
+ }
835
+ const data = (await response.json().catch(() => null)) as (GenerateResponse & { error?: { message?: string; status?: string; details?: unknown } }) | null;
836
+ if (!response.ok) {
837
+ const wait = retryAfterMs(response.headers, data);
838
+ throw new GeminiRequestError(data?.error?.message ?? `Vertex AI returned HTTP ${response.status}.`, response.status, {
839
+ code: data?.error?.status,
840
+ details: data?.error?.details,
841
+ ...(wait === undefined ? {} : { retryAfterMs: wait }),
842
+ });
843
+ }
844
+ // A reply whose body could not be read: sent again, like a connection that failed.
845
+ if (!data) throw new GeminiRequestError("The reply of Vertex AI could not be read.", 0);
846
+ return data;
847
+ }
848
+
849
+ export async function ask(question: string, documentIds: string[], owner: string, signal?: AbortSignal) {
850
+ const system = "You answer questions about the user's files. Cite line numbers.";
851
+ const usage = new UsageMeter();
852
+ const evidence: Evidence[] = [];
853
+ const budget = files.budget;
854
+
855
+ // 1. The plan. `base` is the size of the rest of the request: the system prompt and the question, with a margin.
856
+ const base = { tokens: estimateTokens(system + question) + 2_000, bytes: jsonBytes(system + question) + 8_000 };
857
+ const prepared = await files.prepare(documentIds, base, { owner, viewPages: true });
858
+ if (prepared.missing.length > 0) throw new Error(`Attach these files again: ${prepared.missing.join(", ")}`);
859
+
860
+ // 2. Whole texts and cards at the start of the question, the guide to the tools in the system prompt.
861
+ const blocks = [...new Set(documentIds)].flatMap((id) => prepared.blocks.get(id) ?? []);
862
+ const contents: GeminiContent[] = [{ role: "user", parts: [...blocks.map((text) => ({ text })), { text: question }] }];
863
+ const systemInstruction = { parts: [{ text: [system, prepared.instruction].filter(Boolean).join("\n\n") }] };
864
+
865
+ // 3. One tool set for this question: the documents that are searched, and the PDFs whose pages can be shown.
866
+ const needsTools = prepared.plan.searchable.length > 0 || prepared.viewable.length > 0;
867
+ const readPart = createGeminiGenerateText({ url: endpoint.url, headers: endpoint.headers });
868
+ const tools = files.tools(prepared.plan.searchable, {
869
+ // Part reads of analyze_whole_document, counted with the chat's requests.
870
+ generate: (request) => readPart({ ...request, onUsage: (used) => usage.add(MODEL, used) }),
871
+ viewPages: prepared.viewable,
872
+ onProgress: (event) => console.log(event.message),
873
+ ...(signal ? { signal } : {}),
874
+ });
875
+
876
+ // Pages stay in the request: allow as many as half of what the budget keeps free can pay for.
877
+ let pagesLeft = Math.floor(budget.reservedTokens / 2 / GEMINI_PAGE_TOKENS);
878
+ let answerNow = !needsTools;
879
+ for (let turn = 1; ; turn++) {
880
+ const data = await withRetry(() => generateContent({
881
+ contents,
882
+ systemInstruction,
883
+ // The request for the answer declares no tools: the model must answer in text.
884
+ ...(answerNow ? {} : { tools: [toGeminiTools(tools.declarations)] }),
885
+ }, signal), { signal, onRetry: ({ delayMs }) => console.log(`Trying again in ${Math.round(delayMs / 1_000)} s`) });
886
+ const used = usageOfGemini(data.usageMetadata);
887
+ usage.add(MODEL, used);
888
+
889
+ const content: GeminiContent = data.candidates?.[0]?.content ?? { role: "model", parts: [] };
890
+ const text = content.parts.filter((part) => typeof part.text === "string" && part.thought !== true).map((part) => String(part.text)).join("");
891
+ const calls: ToolCall[] = content.parts.flatMap((part) => {
892
+ const call = part.functionCall as { name?: string; args?: Record<string, unknown>; id?: string } | undefined;
893
+ return call?.name ? [{ name: call.name, args: call.args ?? {}, ...(call.id ? { id: call.id } : {}) }] : [];
894
+ });
895
+ if (answerNow || calls.length === 0) return { text, usage: usage.totals, evidence };
896
+
897
+ // The model's turn goes back unchanged: Gemini 3 wants its thought signatures.
898
+ contents.push(content);
899
+ // The room this turn's results share: about two characters a token, up to half of what the budget keeps free.
900
+ const tokensLeft = budget.contextTokens - budget.reservedTokens / 2 - (used.inputTokens ?? 0);
901
+ let sentBytes = Buffer.byteLength(JSON.stringify(contents));
902
+ const answers: ToolAnswer[] = [];
903
+ for (const [index, call] of calls.entries()) {
904
+ if (index >= MAX_CALLS) {
905
+ answers.push({ call, result: { error: `Not run: one turn runs at most ${MAX_CALLS} calls. Send it again if you still need it.` } });
906
+ continue;
907
+ }
908
+ const label = tools.describe(call.name, call.args);
909
+ const output = await tools.executeWithFiles(call.name, call.args, {
910
+ maxResultCharacters: Math.floor((tokensLeft * 2) / Math.min(calls.length, MAX_CALLS)),
911
+ maxFileBytes: Math.floor(((budget.maxRequestBytes - sentBytes - 1_000_000) * 3) / 4), // base64: four bytes for three
912
+ maxPages: pagesLeft,
913
+ maxRequests: MAX_REQUESTS - usage.totals.requests - 1, // for a whole-file read; one is kept for the answer
914
+ });
915
+ console.log(`${label}${toolResultSummary(label, output.result)}`);
916
+ if (output.files.length > 0) {
917
+ // `pages` is "12" or "12-14". The next look at pages has that much less room.
918
+ const [from = 0, to = from] = String(output.result.pages ?? "").split("-").map(Number);
919
+ pagesLeft -= to - from + 1;
920
+ for (const file of output.files) sentBytes += Math.ceil(file.bytes.length / 3) * 4;
921
+ }
922
+ const shown = evidenceOf(call, output.result);
923
+ if (shown) evidence.push(shown);
924
+ answers.push({ call, result: output.result, files: output.files });
925
+ }
926
+ contents.push(...geminiFunctionResponseTurns(answers));
927
+ // Out of turns or of requests: the next request is the last, and asks for the answer.
928
+ answerNow = turn + 1 >= MAX_TURNS || usage.totals.requests >= MAX_REQUESTS - 1;
929
+ // With nothing to search, the only tool was view_pages: the text of every file is in the prompt.
930
+ const closing = prepared.plan.searchable.length > 0 ? FINAL_ANSWER_REQUEST : FINAL_ANSWER_AFTER_PAGES;
931
+ if (answerNow) contents.push({ role: "user", parts: [{ text: closing }] });
932
+ }
933
+ }
934
+ ```
935
+
936
+ - **Every call gets an answer.** A call past `MAX_CALLS` is answered with an error, not dropped:
937
+ the provider expects one response for each call of the turn.
938
+ - **The pages go inside the function responses.** For Gemini 2.5, which takes them there and does
939
+ not see them, pass `{ files: "beside" }` to `geminiFunctionResponseTurns` (see
940
+ [PDFs](./pdfs.md)).
941
+ - **The ceiling on requests is soft.** It is checked before each turn, and `maxRequests` keeps a
942
+ whole-file read within it only where the read has a choice (see the next section). To refuse a
943
+ costly read first, as `askWithFiles` does, run `get_document_overview` on the document: its
944
+ `parts_for_whole_document_analysis` is the number of parts, worked out from the document's size.
945
+ Or leave `generate` out, and pass `wholeDocumentAnalysis: false` to `prepare`.
946
+ - **To stream the answer**, post the last request to `endpoint.streamUrl` and read it with
947
+ [`parseSseJson`](#parsessejson).
948
+ - **For a conversation**, keep `contents` with the chat, and see [Conversations](./conversations.md)
949
+ for what to keep between questions.
950
+
951
+ ### `ToolCallLimits`
952
+
953
+ The third argument of `executeWithFiles` says what one call may use of the request its result goes
954
+ into. Fill it from your own request, as the sample above does:
955
+
956
+ - `maxResultCharacters`: the room left for this call's result, in characters. The result is cut to
957
+ it and says where to go on. `tools.resultCharacters(name)` is the most a result of that tool can
958
+ have before any limit: what to set aside in your request before you run a call.
959
+ - `maxFileBytes`: the room left in your request for the pages of this call, times 3/4 when files go
960
+ as base64.
961
+ - `maxPages`: the pages the question may still show. Lower it as the pages add up.
962
+ - `maxRequests`: what your ceiling on requests has left, for a whole-file read. It only limits how
963
+ many parts refused as too large are read again as two halves: a read that needs more parts than
964
+ this still makes all of them, the merges of their notes and an answer.
965
+
966
+ The defaults, the floors and the errors a call answers with are in the
967
+ [tools reference](../reference/tools.md#toolcalllimits).
968
+
969
+ ### Progress of each call: `ToolCallHooks`
970
+
971
+ New in 0.7.0. `ToolOptions.onProgress` hears every whole-file read of the tool set, and its events
972
+ do not say which call they belong to. When your loop runs calls at once and shows each one, pass
973
+ listeners for one call as the fourth argument of `executeWithFiles`
974
+ ([`ToolCallHooks`](../reference/library.md#toolcallhooks)):
975
+
976
+ - `onProgress`: the progress of this call's read, in place of the tool set's listener: "Reading
977
+ app.log: part 3 of 12", with `done` and `total`.
978
+ - `onRequest(start)`: each model request of the read as it starts, with its `purpose` (`"part"`,
979
+ `"merge"`, `"final"`) and a `detail` such as `"part 3 of 12"`. Return a handle: the read calls
980
+ its `retry(notice)` before each retry of that request, and its `end({ outcome, usage, error })`
981
+ once when it ends. `usage` is what the part reader passed to `onUsage` for that request, so you
982
+ can show or count the cost of each read.
983
+
984
+ Only `analyze_whole_document` calls them; the other tools ignore them.
985
+
986
+ ```ts
987
+ import type { ToolCall, ToolCallHooks, ToolCallLimits, ToolOutput, ToolSet } from "llm-large-files";
988
+
989
+ // show() is your own: it updates the line of one call on the page.
990
+ declare function show(callId: string, text: string): void;
991
+
992
+ /** Runs the calls of one turn at once, each with its own progress line. */
993
+ async function runTurn(tools: ToolSet, calls: Array<ToolCall & { id: string }>, limits: ToolCallLimits): Promise<ToolOutput[]> {
994
+ return Promise.all(calls.map((call) => {
995
+ const hooks: ToolCallHooks = {
996
+ onProgress: (event) => show(call.id, `${event.message}…`),
997
+ onRequest: (start) => ({
998
+ retry: ({ attempt }) => show(call.id, `${start.detail}: trying again (${attempt})…`),
999
+ end: ({ outcome }) => {
1000
+ if (outcome === "error") show(call.id, `${start.detail} could not be read`);
1001
+ },
1002
+ }),
1003
+ };
1004
+ return tools.executeWithFiles(call.name, call.args, limits, hooks);
1005
+ }));
1006
+ }
1007
+ ```
1008
+
1009
+ Do not let the listeners throw: the read takes a throw from `onRequest` or a handle for a failed
1010
+ request, and a throw from `onProgress` ends the read with `{ error }`. To stop the question on an
1011
+ error of your own, abort the tool set's `signal`. `askWithFiles` uses these hooks for its
1012
+ `tool.progress`, `request.start`, `retry` and `request.end` events ([events](../reference/events.md)).
1013
+
1014
+ ## Streams and retries in your own code
1015
+
1016
+ The loop's own stream reader and retry rule are exported, for an adapter or a loop of yours.
1017
+
1018
+ ### `parseSseJson`
1019
+
1020
+ `parseSseJson<T>(body, hooks?)` turns a `text/event-stream` body into one JSON value for each
1021
+ `data:` event. The body is a web stream (`response.body` of the global `fetch`), or an async
1022
+ iterable of bytes or strings (a Node stream, from node-fetch and the like). `event:` lines are
1023
+ passed over, so what tells events apart must be in the JSON. For an adapter, the hooks are what
1024
+ matter:
1025
+
1026
+ - `onData` is called for each piece of bytes that arrives, keep-alive comments included: restart
1027
+ your wait for a silent stream there.
1028
+ - `onDone` is called for `data: [DONE]`. A stream that ends with neither it nor the provider's own
1029
+ last event was cut off on its way: throw status 0, so that the request is sent again while none
1030
+ of its text was shown.
1031
+ - `signal`: when it aborts, the reader stops waiting and throws the signal's reason. Join the
1032
+ caller's signal and your own wait in it, as below.
1033
+ - `maxEventLength`: the most characters one event may hold, 64,000,000 by default (`Infinity`
1034
+ for no limit). A longer event ends the stream with an error named `SseEventTooLongError`, "An
1035
+ event of the stream held more than 64,000,000 characters.", rather than fill the server's
1036
+ memory. The class is exported, with the limit in its `limit`. The package's adapters throw it as
1037
+ kind `"invalid"` with the reply's status, which is not sent again, as the example above does: the
1038
+ same event would come again.
1039
+
1040
+ A line may end with a line feed, a CRLF or a CR alone. Leaving the loop early cancels a web
1041
+ stream's reader, or calls an async iterable's `return()`, without waiting for either to settle.
1042
+
1043
+ What it parses and what it throws are in the
1044
+ [reference](../reference/errors-and-retries.md#parsessejsonstream-hooks).
1045
+
1046
+ This reader passes the text of a streamed Chat Completions reply on as it arrives, and stops when
1047
+ nothing arrives for `idleMs`:
1048
+
1049
+ ```ts
1050
+ // read-stream.ts: the text of a streamed Chat Completions reply.
1051
+ import { ModelRequestError, parseSseJson } from "llm-large-files";
1052
+
1053
+ type Chunk = { choices?: Array<{ delta?: { content?: string } }> };
1054
+
1055
+ /**
1056
+ * Passes the text on as it arrives, and stops the stream when nothing arrives for `idleMs`
1057
+ * (keep-alive comments count as something).
1058
+ */
1059
+ export async function readStream(response: Response, onText: (delta: string) => void, caller?: AbortSignal, idleMs = 120_000): Promise<string> {
1060
+ if (!response.body) throw new ModelRequestError("The reply had no body.", 0);
1061
+ const silence = new AbortController();
1062
+ let timer = setTimeout(() => silence.abort(), idleMs);
1063
+ let text = "";
1064
+ let done = false;
1065
+ try {
1066
+ for await (const chunk of parseSseJson<Chunk>(response.body, {
1067
+ onData: () => {
1068
+ clearTimeout(timer);
1069
+ timer = setTimeout(() => silence.abort(), idleMs);
1070
+ },
1071
+ onDone: () => {
1072
+ done = true;
1073
+ },
1074
+ signal: caller ? AbortSignal.any([caller, silence.signal]) : silence.signal,
1075
+ })) {
1076
+ const delta = chunk.choices?.[0]?.delta?.content ?? "";
1077
+ if (delta) {
1078
+ text += delta;
1079
+ onText(delta);
1080
+ }
1081
+ }
1082
+ } catch (error) {
1083
+ // Our own wait ran out, not the caller's signal: a timeout, which is sent again once.
1084
+ if (silence.signal.aborted && !caller?.aborted) throw new ModelRequestError(`Nothing arrived for ${idleMs / 1_000} s.`, 0, { kind: "timeout" });
1085
+ throw error;
1086
+ } finally {
1087
+ clearTimeout(timer);
1088
+ }
1089
+ // No `data: [DONE]`: the stream was cut off on its way.
1090
+ if (!done) throw new ModelRequestError("The reply ended before it was complete.", 0);
1091
+ return text;
1092
+ }
1093
+ ```
1094
+
1095
+ ### `withRetry`
1096
+
1097
+ `withRetry(run, options?)` runs `run`, and runs it again by the rule the loop uses for every model
1098
+ request, described in [Errors to throw](#errors-to-throw). It reads `status`, `kind` and
1099
+ `retryAfterMs` of what `run` throws, so any error with those fields works, and calls `run` again as
1100
+ it is: build the request inside it. Two options matter most in code of your own:
1101
+
1102
+ - `canRetry`: return false once a try did something that must not happen twice, such as showing
1103
+ text. The loop does that for `onText`; in your own code, pass it as below.
1104
+ - `unknownErrors: "once"` tries an error without a status once more, at once. Part reads use it;
1105
+ chat requests do not.
1106
+
1107
+ `retry` sets the count and the waits, `signal` stops them, and `onRetry` is called before each
1108
+ wait. Every option is in the [reference](../reference/errors-and-retries.md#withretryrun-options).
1109
+
1110
+ With the reader above, a streamed request is sent again until the user has seen any of its text:
1111
+
1112
+ ```ts
1113
+ import { ModelRequestError, retryAfterMs, withRetry } from "llm-large-files";
1114
+ import { readStream } from "./read-stream.js";
1115
+
1116
+ /** One streamed request, sent again by the library's rules until any of its text was shown. */
1117
+ export async function streamAnswer(prompt: string, write: (delta: string) => void, signal?: AbortSignal): Promise<string> {
1118
+ let shown = false;
1119
+ return withRetry(async () => {
1120
+ let response: Response;
1121
+ try {
1122
+ response = await fetch(`${process.env.LLM_BASE_URL}/chat/completions`, {
1123
+ method: "POST",
1124
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.LLM_API_KEY}` },
1125
+ body: JSON.stringify({ model: process.env.LLM_MODEL, stream: true, messages: [{ role: "user", content: prompt }] }),
1126
+ ...(signal ? { signal } : {}),
1127
+ });
1128
+ } catch (error) {
1129
+ if (signal?.aborted) throw error;
1130
+ throw new ModelRequestError("The server could not be reached.", 0, { cause: error });
1131
+ }
1132
+ if (!response.ok) {
1133
+ const body = (await response.json().catch(() => null)) as { error?: { message?: string; code?: string } } | null;
1134
+ const wait = retryAfterMs(response.headers, body);
1135
+ throw new ModelRequestError(body?.error?.message ?? `HTTP ${response.status}`, response.status, {
1136
+ code: body?.error?.code,
1137
+ ...(wait === undefined ? {} : { retryAfterMs: wait }),
1138
+ });
1139
+ }
1140
+ return readStream(response, (delta) => {
1141
+ shown = true;
1142
+ write(delta);
1143
+ }, signal);
1144
+ }, {
1145
+ retry: { retries: 2, maxDelayMs: 20_000 },
1146
+ signal,
1147
+ // Text the user has seen is not written a second time: the error is thrown instead.
1148
+ canRetry: () => !shown,
1149
+ onRetry: ({ attempt, delayMs, error }) => console.warn(`Sending again (${attempt}) in ${Math.round(delayMs)} ms:`, error),
1150
+ });
1151
+ }
1152
+ ```
1153
+
1154
+ ## See also
1155
+
1156
+ - [How it works](../how-it-works.md): the loop of `askWithFiles` from end to end.
1157
+ - [Errors and reliability](./errors-and-reliability.md): every error and kind, and what to show.
1158
+ - [Costs and limits](./costs-and-limits.md): `AskLimits`, the budget for each model, usage.
1159
+ - [An explorer model](./explorer-model.md), [Conversations](./conversations.md),
1160
+ [PDFs](./pdfs.md), [Testing](./testing.md).
1161
+ - Reference: [`ModelAdapter`](../reference/ask.md#modeladapter),
1162
+ [`ModelCapabilities`](../reference/ask.md#modelcapabilities),
1163
+ [`ModelReply`](../reference/ask.md#modelreply), [`GenerateText`](../reference/ask.md#generatetext),
1164
+ [`ToolSet`](../reference/tools.md#toolset), [`ToolCallLimits`](../reference/tools.md#toolcalllimits),
1165
+ [`ToolCallHooks`](../reference/library.md#toolcallhooks),
1166
+ [`PreparedContext`](../reference/library.md#preparedcontext),
1167
+ [`ModelRequestError`](../reference/errors-and-retries.md#modelrequesterror),
1168
+ [retries and streams](../reference/errors-and-retries.md), and the
1169
+ [Gemini helpers](../reference/gemini.md).