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,892 @@
1
+ # The tool loop and the adapter contract
2
+
3
+ This is the reference for the part of `llm-large-files` that asks the questions: `askWithFiles`
4
+ and `askStream`, their options, limits and result, the conversation they take, the contract a model
5
+ adapter implements, usage totals and evidence. It is for you if you call `askWithFiles`, write or
6
+ wrap an adapter, or run a tool loop of your own. Sections link to the guide that explains the
7
+ task, where there is one.
8
+
9
+ ```ts
10
+ import {
11
+ askWithFiles, askStream, partialResultOf, DocumentsNotFoundError, UsageMeter,
12
+ evidenceOf, mergeRanges, stubResult,
13
+ EXPLORER_INSTRUCTION, FINAL_ANSWER_REQUEST, FINAL_ANSWER_AFTER_PAGES, FINAL_ANSWER_WITHOUT_TOOLS,
14
+ } from "llm-large-files";
15
+ import type {
16
+ AskOptions, AskLimits, AskResult,
17
+ ChatMessage, ChatTurn, ToolTurn,
18
+ ModelAdapter, ModelCapabilities, ModelRequest, ModelMessage, ModelTextMessage, ModelToolRound,
19
+ ModelPart, ToolCall, ToolAnswer, SendHooks, ModelReply, GenerateText, GenerateUsage,
20
+ ModelUsage, UsageTotals, Evidence, NumberRange, AskEvent, EventStream,
21
+ } from "llm-large-files";
22
+ ```
23
+
24
+ `llm-large-files/gemini` re-exports `DocumentsNotFoundError`, `partialResultOf`, `ChatTurn` and the
25
+ four message constants. They are the same values, documented here.
26
+
27
+ Contents:
28
+
29
+ - **The question:** [`askWithFiles(options)`](#askwithfilesoptions),
30
+ [`askStream(options)`](#askstreamoptions), [`AskOptions`](#askoptions),
31
+ [`AskLimits`](#asklimits), [`AskResult`](#askresult),
32
+ [`partialResultOf(error)`](#partialresultoferror),
33
+ [`DocumentsNotFoundError`](#documentsnotfounderror)
34
+ - **What the loop adds to its requests:** [`EXPLORER_INSTRUCTION`](#explorer_instruction),
35
+ [`FINAL_ANSWER_REQUEST`](#final_answer_request),
36
+ [`FINAL_ANSWER_AFTER_PAGES`](#final_answer_after_pages),
37
+ [`FINAL_ANSWER_WITHOUT_TOOLS`](#final_answer_without_tools)
38
+ - **The conversation:** [`ChatMessage`](#chatmessage), [`ChatTurn`](#chatturn),
39
+ [`ToolTurn`](#toolturn)
40
+ - **The adapter contract:** [`ModelAdapter`](#modeladapter),
41
+ [`ModelCapabilities`](#modelcapabilities), [`ModelRequest`](#modelrequest),
42
+ [`ModelMessage`](#modelmessage), [`ModelTextMessage`](#modeltextmessage),
43
+ [`ModelToolRound`](#modeltoolround), [`ModelPart`](#modelpart), [`ToolCall`](#toolcall),
44
+ [`ToolAnswer`](#toolanswer), [`SendHooks`](#sendhooks), [`ModelReply`](#modelreply),
45
+ [`GenerateText`](#generatetext), [`GenerateUsage`](#generateusage)
46
+ - **Usage:** [`ModelUsage`](#modelusage), [`UsageTotals`](#usagetotals),
47
+ [`UsageMeter`](#usagemeter)
48
+ - **Evidence and ranges:** [`Evidence`](#evidence), [`NumberRange`](#numberrange),
49
+ [`evidenceOf(call, result)`](#evidenceofcall-result), [`mergeRanges(ranges)`](#mergerangesranges),
50
+ [`stubResult(call, result, hadFiles?)`](#stubresultcall-result-hadfiles)
51
+
52
+ The rest of the main entry is on three other pages: [library and documents](./library.md)
53
+ (`createLargeFiles`, the budget, stores, extractors, document types), [errors and
54
+ retries](./errors-and-retries.md) (`ModelRequestError` and its kinds, `withRetry`, timeouts,
55
+ `parseSseJson`) and [tools](./tools.md) (each tool the model sees, `TOOL_NAMES`, `ToolResult`,
56
+ `ToolFile`, `ToolDeclaration`). The events of a question and of an ingest (`AskEvent`,
57
+ `IngestEvent`, `EventError`, `eventStream`) are on [events](./events.md).
58
+
59
+ ## The question
60
+
61
+ ### askWithFiles(options)
62
+
63
+ ```ts
64
+ declare function askWithFiles(options: AskOptions): Promise<AskResult>;
65
+ ```
66
+
67
+ Answers the last user message of `options.messages` from the documents `options.documentIds`,
68
+ with any model that has an adapter. Documents that fit go into the prompt whole; the others are
69
+ shown as a card, and the model reaches them through tools. The loop runs the model's tool calls
70
+ within `limits` and ends with a request that must be answered in text, so a question ends with an
71
+ answer or with `answered: false`.
72
+
73
+ What it does, in order:
74
+
75
+ 1. **Fits the budget to the models.** It takes the library's budget, with the fields of
76
+ `options.budget` in place of its own, and fits it to what the adapters declare:
77
+ `contextTokens`, `maxRequestBytes`, `tokenScale`, `outputTokens` (see
78
+ [`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
+ 3. **Sends one request without tools** to `model` when every document went in whole and no PDF
82
+ can be looked at, and returns its reply.
83
+ 4. **Otherwise runs tool rounds.** The model that explores (`explorer`, or `model` without one)
84
+ gets the tools. Of each turn's calls, the loop runs at most `limits.callsPerTurn`, up to four
85
+ at a time, each result fitted to the room left in the request, and sends the results back.
86
+ Tools run in at most `limits.toolTurns - 1` model turns.
87
+ 5. **Ends with the answer.** A reply with text and no tool call is the answer, when there is no
88
+ explorer. Otherwise (out of turns, room or `limits`, a reply with no text, an explorer that is
89
+ done) `model` gets one more request: the tools listed, `toolChoice: "none"`, and one of the
90
+ [`FINAL_ANSWER_*`](#final_answer_request) lines as a user turn at the end. When its reply has
91
+ no text (it is empty, or holds a tool call the model was told not to make), that request is
92
+ sent once more with a note after the line, which is not kept: "Your last reply had no text. No
93
+ tool can be called in this reply: write the answer now, in text, from what is above." Not after
94
+ a refusal (`blockReason`), a reply `"filtered"`, or one `"cut"` with nothing in it; not once
95
+ `limits.requests` or `limits.inputTokens` is reached; and not when the question already made its
96
+ two second tries (see [`ModelReply`](#modelreply)). New in 0.6.0.
97
+
98
+ A request that fails is sent again by the rule of `retry` (see
99
+ [`withRetry`](./errors-and-retries.md#withretryrun-options)), but never once text of its reply was
100
+ shown. A request the provider refuses as too large (`kind: "context_overflow"`) is never sent again
101
+ as it was: it is made smaller. Older tool results are shortened, at most twice a question, and
102
+ never when a model of the question is `appendOnly`. When that does not mend it, and no tool call
103
+ was answered and no text was shown yet, the documents are planned again, once, for a smaller window
104
+ worked out from the provider's numbers. A request larger than the tokens a minute (or a day) that
105
+ the provider allows (OpenAI's and Groq's TPM, HTTP 429 or 413) is this kind too, with that
106
+ allowance as the window, and its steps say so.
107
+ [How it works](../how-it-works.md#a-request-too-large-for-the-model) explains each step.
108
+
109
+ **Returns** an [`AskResult`](#askresult).
110
+
111
+ **Throws:**
112
+
113
+ | Error | When | [`partialResultOf`](#partialresultoferror) |
114
+ |---|---|---|
115
+ | `Error`: "budget.… must be a number above 0, and is …", or "budget.reservedTokens (…) must be smaller than budget.contextTokens (…)…" (the same for `mapChunkTokens`) | A field of `options.budget` is not a number above 0, or the fields cannot work together. Before any request. See [`resolveBudget`](./library.md#resolvebudgetbudget-limits). | undefined |
116
+ | `Error`: "The last message must be the user's." | `messages` is empty, or its last message is not a user turn. | undefined |
117
+ | [`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 |
118
+ | [`DocumentsNotFoundError`](#documentsnotfounderror) | A document of `documentIds` was never stored, has expired or been deleted, or belongs to another `owner`. Before any request. | undefined |
119
+ | [`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 |
120
+ | 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 |
121
+ | 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 |
122
+ | The signal's reason | `signal` aborted. Nothing is sent or retried after that, no part of a whole-file read either. It is thrown at once, also while an adapter (or a part reader) that does not look at the signal is still at work, and also when the adapter then fails with its own error. Text that such an adapter sends later is not shown. | What the question had done, when the reason is an object |
123
+
124
+ When the documents were planned again after an overflow and the second plan fails before it sends
125
+ anything, the first overflow error is thrown, with what the first try had done. A whole-file part
126
+ read that fails does not end the question: the tool reports it to the model.
127
+
128
+ ```ts
129
+ import { GoogleAuth } from "google-auth-library";
130
+ import { askWithFiles, DocumentsNotFoundError, partialResultOf, type AskResult, type ChatMessage, type LargeFiles } from "llm-large-files";
131
+ import { gemini, vertexAi } from "llm-large-files/gemini";
132
+
133
+ const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
134
+ const accessToken = async () => (await auth.getAccessToken())!;
135
+ const project = process.env.GOOGLE_CLOUD_PROJECT!;
136
+
137
+ const model = gemini(vertexAi({ project, model: "gemini-3.8-flash", accessToken })); // writes the answer
138
+ const explorer = gemini(vertexAi({ project, model: "gemini-3.5-flash-lite", accessToken })); // searches and reads
139
+
140
+ // files is your createLargeFiles(); userId, documentIds and messages are the chat being answered.
141
+ export async function answer(files: LargeFiles, userId: string, documentIds: string[], messages: ChatMessage[], signal: AbortSignal): Promise<AskResult> {
142
+ try {
143
+ const result = await askWithFiles({
144
+ files, model, explorer, documentIds, messages, signal,
145
+ owner: userId,
146
+ limits: { toolTurns: 12, inputTokens: 2_000_000 },
147
+ onText: (delta) => process.stdout.write(delta),
148
+ onActivity: (status) => console.error(status),
149
+ onStep: (line) => console.error(`Done: ${line}`),
150
+ });
151
+ if (!result.answered) console.error(result.blockReason ? `Declined: ${result.blockReason}` : "No answer: show your own message.");
152
+ return result;
153
+ } catch (error) {
154
+ if (error instanceof DocumentsNotFoundError) console.error("Upload again:", error.ids);
155
+ const partial = partialResultOf(error); // what the question found and paid for before it failed
156
+ if (partial) console.error(`${partial.usage.requests} requests were answered before it failed`);
157
+ throw error;
158
+ }
159
+ }
160
+ ```
161
+
162
+ `askGemini` (in [`llm-large-files/gemini`](./gemini.md)) is this function with Gemini models made
163
+ for you. Guides: [web app](../guides/web-app.md) (streaming, progress, cancelling),
164
+ [conversations](../guides/conversations.md), [explorer model](../guides/explorer-model.md),
165
+ [errors and reliability](../guides/errors-and-reliability.md).
166
+
167
+ ### askStream(options)
168
+
169
+ ```ts
170
+ declare function askStream(options: AskOptions): EventStream<AskEvent, AskResult>;
171
+ ```
172
+
173
+ New in 0.7.0. [`askWithFiles`](#askwithfilesoptions) as a stream of its events, for a page that
174
+ shows the question as it goes. It starts the question at once and returns an async iterable of
175
+ [`AskEvent`](./events.md#askevent)s, in order: `run.start` first, then the plan, the requests, the tool
176
+ calls, the text and the notices, and last `run.finish` or `run.error`. Each event is also the one
177
+ `onEvent` would get.
178
+
179
+ | Member | What it is |
180
+ |---|---|
181
+ | `[Symbol.asyncIterator]()` | The events, read with `for await`. They wait in memory until they are read. The loop ends after the last event. It does not throw when the question fails: read the `run.error` event, or await `result`. Leaving the loop early (`break`, `return`, a throw) stops the question. It can be read once: a second `for await` throws `TypeError("These events can be read once.")`. |
182
+ | `result` | `Promise<AskResult>`: what `askWithFiles` returns, `toolTurns` included. It rejects with the question's error, and [`partialResultOf`](#partialresultoferror) works on that error. Awaiting it is optional: it never goes unhandled. |
183
+ | `abort(reason?)` | Stops the question. The stream ends after its last event, `run.error`. Without a reason, the question throws a `DOMException` named `"AbortError"`. |
184
+
185
+ The options are those of `askWithFiles`, with three differences:
186
+
187
+ - `streamText` defaults to `true`: the model is asked for the answer as it is written, and `text`
188
+ events come as it arrives. Pass `streamText: false` to ask for each reply whole.
189
+ - `signal` still stops the question, as does `abort()` or leaving the loop.
190
+ - `onEvent`, when given, gets each event too, after the stream. A throw from it ends the question
191
+ with that error, and the stream still ends with the `run.error`; a throw on `run.finish` leaves
192
+ the stream ending with `run.finish`, and `result` rejects with it.
193
+
194
+ ```ts
195
+ import { askStream, partialResultOf, type AskOptions, type ToolTurn } from "llm-large-files";
196
+
197
+ // options are those of askWithFiles. Returns the tool rounds to keep with the conversation.
198
+ export async function showQuestion(options: AskOptions): Promise<ToolTurn[]> {
199
+ const stream = askStream(options);
200
+ for await (const event of stream) {
201
+ if (event.type === "tool.start") console.error(`${event.label}…`);
202
+ if (event.type === "tool.progress") console.error(`${event.message}…`);
203
+ if (event.type === "text") process.stdout.write(event.delta);
204
+ if (event.type === "run.error") console.error(`\nFailed: ${event.error.message}`); // safe to show
205
+ }
206
+ try {
207
+ return (await stream.result).toolTurns;
208
+ } catch (error) {
209
+ console.error(error); // the provider's own words, for your logs
210
+ return partialResultOf(error)?.toolTurns ?? [];
211
+ }
212
+ }
213
+ ```
214
+
215
+ To send the events to a browser as Server-Sent Events, pass the stream itself to
216
+ [`writeSseEvents`](./node.md#writesseeventsresponse-events-options): it stops the question when the
217
+ client goes away. An async
218
+ generator that wraps the stream stops it only when it next yields; change what is sent with the
219
+ `map` option instead. What each event holds, and what goes over the wire: [events](./events.md).
220
+ [`eventStream`](./events.md#eventstreamrun-options) makes the same kind of stream around any
221
+ function that takes an `onEvent` and a `signal`.
222
+
223
+ ### `AskOptions`
224
+
225
+ The options of `askWithFiles`.
226
+
227
+ | Option | Type | Default | What it does |
228
+ |---|---|---|---|
229
+ | `files` | [`LargeFiles`](./library.md#largefiles) | required | The library that holds the documents, plans them and makes the tools. |
230
+ | `model` | [`ModelAdapter`](#modeladapter) | required | The model that answers. Without `explorer`, it also makes the tool calls and reads whole files in parts. |
231
+ | `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. |
232
+ | `documentIds` | `string[]` | required | The documents this question may use. Duplicates count once. One that is missing throws [`DocumentsNotFoundError`](#documentsnotfounderror). |
233
+ | `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. |
234
+ | `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. |
235
+ | `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. |
236
+ | `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. |
237
+ | `limits` | [`AskLimits`](#asklimits) | `{}` | The limits of this question: tool turns, calls per turn, whole-file reads, ceilings on tokens and requests. |
238
+ | `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. |
239
+ | `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. |
240
+ | `wholeDocumentAnalysis` | `boolean` | `true` | Offer `analyze_whole_document`, which reads a whole file in many model requests. It is offered only when the model that explores has `generateText` and a document reached through tools is small enough to be read in about `budget.maxMapChunks` parts or fewer. `false` withholds it. The tool guide names it only when it is offered, and a card offers it only for a file that is small enough. With `false`, or a model that explores without `generateText`, a card says that its file can be searched and read by line ranges, not that it can be analyzed whole or is too large for that. |
241
+ | `viewPages` | `boolean` | `true` | Offer `view_pages` for PDFs whose original file is kept (`keepOriginals`). It is offered only when no model of the question has `capabilities.toolFiles: "none"`. It changes nothing for a library that keeps no originals. |
242
+ | `onText` | `(delta: string) => void` | none | The answer's text as it arrives. With it, `streamText` defaults to `true`, and the adapter streams when it can; otherwise the text of each reply comes once the reply is in: in one piece, or from `gemini()`, one piece for each text part. A remark the model wrote before a tool call comes too, and the text of a later reply then starts with `"\n\n"`. With an explorer, only the answering model's text comes. |
243
+ | `streamText` | `boolean` | `true` with `onText`, and in [`askStream`](#askstreamoptions); `false` otherwise | Whether to ask the model for the answer as it is written: the loop then passes `onText` to the adapter's `send` ([`SendHooks`](#sendhooks)), and an adapter that can stream does. A reply that fails after its first piece of text is not sent again: that text was shown. With `false`, the text of each reply comes once the reply is in, to `onText` and as `text` events, and a reply that fails can be sent again. A listener of the events alone (`onEvent` without `onText`) does not change how the model is asked. New in 0.7.0. |
244
+ | `onActivity` | `(text: string) => void` | none | Short-lived status in English: each tool call as it starts ("Search app.log (exact) for “timeout”…"), "Too large to read at once: app.log. Searching instead…", the progress of a whole-file read, a retry of a chat request ("The model did not answer (HTTP 503). Trying again in 2 s…", "The model could not be reached. Trying again…", or, for a reply that began and was cut off on its way, "The model's reply was cut off on its way. Trying again…"), and "Writing the answer…" before the request for the answer. Show it as plain text: a tool call's line can quote the model's words. The retries of a whole-file read's requests are not told here: they come only as `retry` events. |
245
+ | `onStep` | `(text: string) => void` | none | Each finished step, the same lines as `result.steps`, as they happen. |
246
+ | `onEvent` | `(event: AskEvent) => void` | none | Everything the question does, as typed events in order: `run.start`, the `plan`, each model request (`request.start`, `retry`, `request.end`), each tool call (`tool.start`, `tool.progress`, `tool.end`), the text, the notices, and last `run.finish` or `run.error`. See [events](./events.md). `onText`, `onActivity` and `onStep` still get the same strings, at the same moments. A model error in an event is told by its kind and status, never in the provider's words ([`EventError`](./errors-and-retries.md#errors-in-events-eventerror)). Tool results are left out unless `eventResults` is set. A throw from it ends the question with that error ([a listener that throws](./events.md#a-listener-that-throws)). New in 0.7.0. |
247
+ | `runId` | `string` | `"run_"` and 16 hex digits | The `runId` of every event of the question. Pass your own to find the events in your logs. New in 0.7.0. |
248
+ | `eventResults` | `boolean` | `false` | Put each tool result in its `tool.end` event (`result`), and `toolTurns` in the result that `run.finish` and `run.error` carry. Off by default: results hold the text of the documents, and events are often sent on to a browser. The result `askWithFiles` returns always has `toolTurns`. New in 0.7.0. |
249
+ | `signal` | `AbortSignal` | none | Stops the question: the request under way is aborted through the adapter, tool calls stop, and nothing is sent again. `askWithFiles` then throws the signal's reason, at once: the loop does not wait for an adapter, or a part reader, that does not look at the signal. A request left running that way may be billed by the provider, and is not counted in the usage. |
250
+
251
+ Guides: [conversations](../guides/conversations.md) (`messages`, `documentPlacement`),
252
+ [storage](../guides/storage.md) (`owner`), [web app](../guides/web-app.md) (`onText`,
253
+ `onActivity`, `onStep`, `signal`), [PDFs](../guides/pdfs.md) (`viewPages`),
254
+ [costs and limits](../guides/costs-and-limits.md) (`limits`, `budget`). Reference:
255
+ [events](./events.md) (`onEvent`, `runId`, `eventResults`).
256
+
257
+ ### `AskLimits`
258
+
259
+ The limits of one question: `AskOptions.limits`. Every field is optional.
260
+
261
+ | Field | Type | Default | What it does |
262
+ |---|---|---|---|
263
+ | `toolTurns` | `number` | 12 | The most model turns of the chat for one question, counting the answer and a second try after an empty or broken reply. Tools run in all but the last: if the model is still calling tools then, the last turn must be answered in text. With an explorer, the explorer has up to `toolTurns - 1` turns and `model` the last. A request the provider refused as too large takes no turn of its own: what is sent again after it is the same turn, so `result.turns` can be a little higher. When the answer comes back without text, it is asked for once more, and that request can be one past `toolTurns`; it is not made once `requests` or `inputTokens` is reached. Truncated to a whole number; below 1 counts as 1. With 1, no tool runs and the only request is the answer. |
264
+ | `callsPerTurn` | `number` | 8 | The most tool calls of one model turn that are run. Each call beyond it is answered with an error ("Not run: one turn runs at most 8 tool calls. Send this call again if you still need it."), and `steps` says how many were not run. Truncated to a whole number; below 1 counts as 1. |
265
+ | `wholeDocumentReads` | `number` | 1 ([`MAX_WHOLE_DOCUMENT_READS`](./tools.md#max_whole_document_reads)) | How many times each document may be read whole (`analyze_whole_document`) in one question. One read of a large file is up to `budget.maxMapChunks` part requests and a few more. 0 refuses every whole-file read but still lists the tool: to withhold it, set `wholeDocumentAnalysis: false`. |
266
+ | `inputTokens` | `number` | none | A ceiling on the input tokens of the question, over all its requests, part reads included, as the adapters report them (`usage.inputTokens`, cached tokens included). Checked before each tool request: once it is reached, no further tool request is made and the next request is the answer. The calls of the reply that reached it still run, and their results and the answer come on top. A whole-file read that would pass it is refused, with the numbers, before it starts. |
267
+ | `requests` | `number` | none | The same ceiling on model requests, chat requests and part reads together, as `usage.requests` counts them. Once `requests - 1` are used, no further tool request is made: the last request is kept for the answer. The calls of the reply that used it still run, but a whole-file read that needs more requests than are left is refused, and the reads of one turn share what is left. |
268
+
269
+ `askGemini` also takes `maxToolTurns` and `maxToolCallsPerTurn`, the names these had before 0.5.0
270
+ (see [gemini](./gemini.md)). Guide: [costs and limits](../guides/costs-and-limits.md).
271
+
272
+ ### `AskResult`
273
+
274
+ What `askWithFiles` returns, and what [`partialResultOf`](#partialresultoferror) gives for a
275
+ question that failed.
276
+
277
+ | Field | Type | What it holds |
278
+ |---|---|---|
279
+ | `text` | `string` | Everything the answering model wrote, as `onText` got it: a remark made before a tool call, then `"\n\n"` and the answer. With an explorer, only what `model` wrote. `""` when nothing was written. |
280
+ | `answered` | `boolean` | True when the last reply had text that is not blank, and the provider did not refuse the prompt. False when the prompt was refused (`blockReason`), or the last reply had no text: it was cut off before any text, or the request for the answer came back without text, and so did its second try. `text` may then be empty, or hold a remark made before a tool call, or the start of a reply that was refused: show your own message. |
281
+ | `blockReason` | `string`, optional | Why the provider refused the prompt, in the adapter's words. Set only then. Nothing more is asked after a refusal. |
282
+ | `steps` | `string[]` | Each finished step, in order: a line for each tool call, run or refused ("Search app.log (exact) for “timeout” — 12 matching lines", or "… — already shown above"), one for the calls of a turn over `callsPerTurn`, and one when the loop shortened older results, asked again after an empty or broken reply, or planned the documents again. The second try of the answer says "The model's answer was empty: it was asked again" or "The model called a tool instead of answering: it was asked again for the answer". The lines `onStep` got. Each is one line of plain text: a line break, a tab or another control character in what the model sent becomes one space with the blanks around it; the invisible characters that file text loses are dropped (text-direction overrides and isolates, zero-width spaces, word joiners, soft hyphens, tag characters); `](` becomes `] (`, so that a markdown link or picture stays text. A query is cut at 80 characters and a task at 100, never in the middle of a character. Steps still quote the model's words, HTML tags and web addresses included: show them as plain text, never as markdown or HTML. |
283
+ | `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). |
284
+ | `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. |
285
+ | `plan` | [`DocumentPlan`](./library.md#documentplan) | Which documents went in whole (`inline`) and which were reached through tools (`searchable`). |
286
+ | `budget` | [`Budget`](./library.md#budget) | The budget the question ran with: the library's (with `options.budget`), fitted to the models. |
287
+ | `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. |
288
+ | `finishReason` | `string`, optional | The provider's own word for why the last reply that gave one ended (`"STOP"`, `"length"`, `"end_turn"`). |
289
+ | `usage` | [`UsageTotals`](#usagetotals) | Tokens and requests of the whole question, whole-file part reads included, in all and for each model by its `id`. |
290
+ | `lastUsage` | `Record<string, unknown>`, optional | The provider's own usage object of the last chat reply that had one, as it came. |
291
+
292
+ Guides: [conversations](../guides/conversations.md) (`toolTurns`),
293
+ [costs and limits](../guides/costs-and-limits.md) (`usage`),
294
+ [errors and reliability](../guides/errors-and-reliability.md) (`answered`, `blockReason`).
295
+
296
+ ### partialResultOf(error)
297
+
298
+ ```ts
299
+ declare function partialResultOf(error: unknown): AskResult | undefined;
300
+ ```
301
+
302
+ New in 0.6.0, from `llm-large-files` and `llm-large-files/gemini`.
303
+
304
+ What a question that failed had done before it failed. `askWithFiles` throws the error as it came;
305
+ this gives, for that error object, an [`AskResult`](#askresult) with `answered: false` and the
306
+ `steps`, `evidence`, `toolTurns`, `usage`, `turns`, `plan` and `budget` of the question until
307
+ then. Keep its `toolTurns` with the conversation and count its `usage`: those requests were paid
308
+ for. `usage` is a copy taken when the question failed: a request still running then (an adapter
309
+ or a part reader that did not stop at the signal) may be billed by the provider, and is not
310
+ counted. It returns `undefined` for an error that did not come from a question under way (a missing
311
+ document, a budget that cannot work, a store that could not be read while planning) and for a
312
+ value that is not an object. The sample under [`askWithFiles`](#askwithfilesoptions) uses it.
313
+
314
+ The `run.error` event carries the same result as `partial`, as an `EventResult`: without
315
+ `toolTurns`, and with a plan that names the documents only (both hold text of the documents),
316
+ unless `eventResults` is set; and
317
+ `sseMessageOf` sends only its `steps`, `evidence` and `usage`. Keep the tool rounds from
318
+ `partialResultOf(error)` on the server: with `askStream`, `error` is what `stream.result` rejects
319
+ with.
320
+
321
+ Guide: [errors and reliability](../guides/errors-and-reliability.md).
322
+
323
+ ### `DocumentsNotFoundError`
324
+
325
+ ```ts
326
+ declare class DocumentsNotFoundError extends Error {
327
+ constructor(ids: string[]);
328
+ readonly ids: string[];
329
+ }
330
+ ```
331
+
332
+ Thrown by `askWithFiles` (and `askGemini`) before any model request, when documents of
333
+ `documentIds` were never stored, have expired or been deleted, or belong to another owner. `ids`
334
+ lists them. `name` is `"DocumentsNotFoundError"`. The message names the IDs, not the files: "A
335
+ document is no longer available: ‹id›. Upload it again.", or for several "3 documents are no longer
336
+ available: ‹id›, ‹id›, ‹id›. Upload them again."
337
+
338
+ Guide: [errors and reliability](../guides/errors-and-reliability.md).
339
+
340
+ ## What the loop adds to its requests
341
+
342
+ Each is a `string`. The loop adds them itself. They are exported so that you can recognise them in
343
+ a request, or use them in a loop of your own.
344
+
345
+ ### `EXPLORER_INSTRUCTION`
346
+
347
+ Added after the system instruction of every request of an explorer model:
348
+
349
+ > You only gather material in this conversation: another model writes the answer. It sees this
350
+ > conversation and what your tool calls returned, not what you thought or wrote. So call the tools
351
+ > until their results hold everything the answer needs from the files. Then, or at once if no tool
352
+ > is needed, reply with the single word DONE instead of an answer.
353
+
354
+ Guide: [explorer model](../guides/explorer-model.md).
355
+
356
+ ### `FINAL_ANSWER_REQUEST`
357
+
358
+ The user turn at the end of the request for the answer, when a document is reached through tools
359
+ and tool calls were answered:
360
+
361
+ > Stop using tools now. Answer my question using only what the tools returned above, with line
362
+ > citations. Say plainly what you could not find.
363
+
364
+ ### `FINAL_ANSWER_AFTER_PAGES`
365
+
366
+ The same, when every document went in whole and the only tool was `view_pages`:
367
+
368
+ > Stop using tools now. Answer my question from the text of the files and the pages you looked at.
369
+ > Say plainly what you could not see or find.
370
+
371
+ ### `FINAL_ANSWER_WITHOUT_TOOLS`
372
+
373
+ The same, when no tool call was answered in the question (an explorer called none, the first reply
374
+ was empty, or no turn was left for tools), so there is no tool result to answer from:
375
+
376
+ > Answer my question now, from what is in this conversation. No tools are available for this reply:
377
+ > if the answer needs a part of a file that is not shown here, say so plainly.
378
+
379
+ None of the three is kept in the conversation or in `toolTurns`. Nor is the note of the answer's
380
+ second try, which is not exported (new in 0.6.0): "Your last reply had no text. No tool can be
381
+ called in this reply: write the answer now, in text, from what is above."
382
+
383
+ ## The conversation
384
+
385
+ ### `ChatMessage`
386
+
387
+ ```ts
388
+ type ChatMessage = ChatTurn | ToolTurn | ModelTextMessage;
389
+ ```
390
+
391
+ What `askWithFiles` takes as `messages`: plain turns ([`ChatTurn`](#chatturn)), the tool rounds an
392
+ earlier question returned ([`ToolTurn`](#toolturn), from `result.toolTurns`), and turns with parts
393
+ in a provider's own form ([`ModelTextMessage`](#modeltextmessage), such as
394
+ `{ role: "user", parts: [{ text }, { native: anImagePart }] }`). The last must be a user turn.
395
+ Declare the array as `ChatMessage[]`: without it, TypeScript widens `role` to `string`.
396
+
397
+ ```ts
398
+ import type { ChatMessage } from "llm-large-files";
399
+
400
+ // first is the AskResult of the first question of this chat.
401
+ const messages: ChatMessage[] = [
402
+ { role: "user", text: "Why did the nightly import fail?" },
403
+ ...first.toolTurns, // between the question and its answer
404
+ { role: "assistant", text: first.text },
405
+ { role: "user", text: "And how long did recovery take?" },
406
+ ];
407
+ ```
408
+
409
+ The adapter entries convert histories kept in a provider's form: `fromGeminiContents`
410
+ ([gemini](./gemini.md)), `fromOpenAiMessages` ([openai](./openai.md), which also returns the
411
+ system message) and `fromAnthropicMessages` ([anthropic](./anthropic.md)).
412
+ Guide: [conversations](../guides/conversations.md).
413
+
414
+ ### `ChatTurn`
415
+
416
+ ```ts
417
+ type ChatTurn = { role: "user" | "assistant" | "model"; text: string };
418
+ ```
419
+
420
+ A plain turn of the user or of the model. `"model"` is taken as `"assistant"`.
421
+
422
+ ### `ToolTurn`
423
+
424
+ ```ts
425
+ type ToolTurn = { role: "tools"; calls: Array<ToolCall & { result: ToolResult }> };
426
+ ```
427
+
428
+ One round of tool use as an application stores it: the calls of one model turn, each with what the
429
+ tool returned ([`ToolResult`](./tools.md#toolresult)), in call order. Plain JSON that belongs to no
430
+ provider. `askWithFiles` returns them in `result.toolTurns`; passed back in `messages`, the model
431
+ sees in a later question what its tools returned in an earlier one. Their results are sent without
432
+ `tool_turns_left`, which counted the turns of their own question (since 0.6.0; what `toolTurns`
433
+ holds is unchanged). A call whose result is still in the conversation in full is then not run
434
+ again: it is answered with a pointer (`already_shown: true`). Not with a model that declares
435
+ `clearsToolResults`, and not for a read of one line made in an earlier question, or an exact or
436
+ regex search that 0.5.0 stored without its last match: those run again (see
437
+ [tools](./tools.md#what-askwithfiles-adds-to-results)). Guide:
438
+ [conversations](../guides/conversations.md).
439
+
440
+ ## The adapter contract
441
+
442
+ An adapter turns the loop's neutral request into a provider's, sends it, and reads the reply back.
443
+ Everything else (planning, tools, limits, retries, usage, the request for the answer) is the
444
+ loop's, once, for every provider. The built-in adapters are `gemini()` ([gemini](./gemini.md)),
445
+ `openAiCompatible()` ([openai](./openai.md)) and `anthropic()` ([anthropic](./anthropic.md)).
446
+
447
+ ### `ModelAdapter`
448
+
449
+ ```ts
450
+ interface ModelAdapter {
451
+ readonly id: string;
452
+ readonly capabilities: ModelCapabilities;
453
+ /** @deprecated Never called: set capabilities.tokenScale. */
454
+ estimateTokens?(text: string): number;
455
+ send(request: ModelRequest, hooks?: SendHooks): Promise<ModelReply>;
456
+ requestBytes?(request: ModelRequest): number;
457
+ generateText?: GenerateText;
458
+ }
459
+ ```
460
+
461
+ A model provider, as the tool loop sees it.
462
+
463
+ | Member | Required | What it is |
464
+ |---|---|---|
465
+ | `id` | yes | Names the model in `usage.byModel`, such as `"gemini-3.8-flash"`. Give the two models of a question different IDs to tell them apart there: requests of the same `id` are summed together. |
466
+ | `capabilities` | yes | What the model can take: see [`ModelCapabilities`](#modelcapabilities). |
467
+ | `send(request, hooks?)` | yes | One chat request. Returns a [`ModelReply`](#modelreply). Throw a [`ModelRequestError`](./errors-and-retries.md#modelrequesterror) for an HTTP error, with status 0 for a connection that failed. The loop reads `status`, `kind`, `retryAfterMs`, `limitTokens` and `requestedTokens` from the error, and sends again the ones worth it. |
468
+ | `requestBytes?(request)` | no | The size in bytes of the body `send` would post for `request`. The loop calls it before it shows the pages of a PDF in a turn, with the turn whose calls are being run as a round with no `answers` yet. With it the room for the pages is exact; without it, it is estimated. |
469
+ | `generateText` | no | A plain completion for the parts of a whole-file read: see [`GenerateText`](#generatetext). The one of the model that explores is used. Without it, `analyze_whole_document` is not offered. |
470
+ | `estimateTokens?(text)` | no | Deprecated, and never called: `askWithFiles` sizes every request with the library's `estimateTokens`, scaled by `tokenScale`. Set `capabilities.tokenScale` for a model that counts differently. It is kept so that adapters that set it still compile, and a later version may remove it. |
471
+
472
+ What `send` must do with the request:
473
+
474
+ - **A tool round with `raw`** is sent back as `raw`, unchanged: the loop sets it only on rounds
475
+ that this adapter returned. **Without `raw`** (a stored round, or one an explorer of another
476
+ adapter made), build the model turn from `calls`.
477
+ - **The results** of a round go in call order, each with its call's `id`. The files of an answer
478
+ (the pages of `view_pages`) go where `capabilities.toolFiles` says.
479
+ - **`toolChoice: "none"`** means the model must answer in text. The tools are still in `tools`.
480
+ - **Text:** call `hooks.onText` as text arrives when it is given; return the whole text in
481
+ `reply.text` either way, starting with what was streamed. Pass `hooks.signal` to the request: the
482
+ loop stops waiting for `send` when the signal aborts, and drops what it returns later, but a
483
+ request that goes on holds a connection and may be billed.
484
+ - **A call whose arguments could not be read** is returned with `problem`: the loop answers it with
485
+ that message and does not run it.
486
+
487
+ ```ts
488
+ import { ModelRequestError, retryAfterMs, type ModelAdapter, type ModelReply, type ModelRequest } from "llm-large-files";
489
+
490
+ // toProviderBody and fromProviderBody are your own: the neutral request in your provider's form,
491
+ // and your provider's response as a ModelReply.
492
+ declare function toProviderBody(request: ModelRequest): unknown;
493
+ declare function fromProviderBody(body: unknown): ModelReply;
494
+
495
+ const model: ModelAdapter = {
496
+ id: "my-model",
497
+ capabilities: { contextTokens: 128_000, toolFiles: "none", pageTokens: 0 },
498
+ async send(request, hooks = {}) {
499
+ let response: Response;
500
+ try {
501
+ response = await fetch(process.env.MODEL_URL!, {
502
+ method: "POST",
503
+ headers: { "content-type": "application/json", authorization: `Bearer ${process.env.MODEL_API_KEY}` },
504
+ body: JSON.stringify(toProviderBody(request)),
505
+ signal: hooks.signal ?? null,
506
+ });
507
+ } catch (cause) {
508
+ if (hooks.signal?.aborted) throw cause;
509
+ throw new ModelRequestError("The model could not be reached.", 0, { cause });
510
+ }
511
+ if (!response.ok) {
512
+ const message = (await response.text()) || `The model returned HTTP ${response.status}.`;
513
+ throw new ModelRequestError(message, response.status, { retryAfterMs: retryAfterMs(response.headers) });
514
+ }
515
+ const reply = fromProviderBody(await response.json());
516
+ if (reply.text) hooks.onText?.(reply.text); // no streaming here: the whole text at once
517
+ return reply;
518
+ },
519
+ };
520
+ ```
521
+
522
+ Guide: [your own adapter and loop](../guides/own-adapter-and-loop.md), and
523
+ [testing](../guides/testing.md) for an adapter that answers from a script.
524
+
525
+ ### `ModelCapabilities`
526
+
527
+ What a model can take, as far as its adapter knows. What each built-in adapter declares is on its
528
+ reference page.
529
+
530
+ | Field | Type | Default | What it does |
531
+ |---|---|---|---|
532
+ | `contextTokens` | `number` | none | The context window, in the model's tokens. The window of a question is the smallest of the library's `budget.contextTokens` and those its models declare. |
533
+ | `maxRequestBytes` | `number` | none | The largest request body, in bytes. A question's `budget.maxRequestBytes` is the smallest of the library's and those its models declare. |
534
+ | `toolFiles` | `"inside" \| "beside" \| "none"` | required | Where `send` puts a file that a tool returned (the pages of `view_pages`): `"inside"` the tool result, `"beside"` it in a user turn of its own, or `"none"` for a model that cannot be sent one. When any model of the question says `"none"`, `view_pages` is not offered. |
535
+ | `pageTokens` | `number` | required | About what the model bills for one PDF page it is shown, in its tokens. The question counts the largest of its models': the pages of a question may take up to half of `budget.reservedTokens`. |
536
+ | `tokenScale` | `number` | 1 | How many of this model's tokens one token of the library's estimate (`estimateTokens`, fitted to Gemini) comes to. A model that counts a third more for the same text says 1.33, and its window is that much smaller in the library's tokens. The question uses the largest of its models'. A value that is not above 0 counts as 1. |
537
+ | `outputTokens` | `number` | none | Tokens set aside for the reply, when they come out of the same window as the prompt (Claude's `max_tokens`). The largest of the models' is kept free, but at least a quarter of the window is left for the prompt. |
538
+ | `appendOnly` | `boolean` | `false` | True for a model whose earlier turns may not be rewritten (Claude ties its thinking blocks to the turns they were written in). When any model of the question says so, old tool results are not shortened to make room: when the room runs out, the question is answered with what it has, and an overflow is mended only by planning the documents again. When the model that explores is append-only, a note the loop adds after an empty or broken reply stays in its conversation for the rest of the question. |
539
+ | `clearsToolResults` | `boolean` | `false` | True for a model whose provider may clear old tool results from the conversation on its side, before the model reads it: Claude's context editing with `clear_tool_uses`, or compaction. When any model of the question says so, no call is answered with a pointer to an earlier result: each call made again runs again, the same call twice in one turn runs twice, and pointers in stored rounds are sent as the stand-in that says to call again. The loop still counts every result as sent, so its room runs out where it would without it. `anthropic()` sets it from its `body`; set it in an adapter of your own whose provider does this. New in 0.6.0. |
540
+
541
+ With an explorer, every field counts for the pair: the budget is planned for the smaller window
542
+ and the larger scale, because both models get the same conversation. Guides:
543
+ [explorer model](../guides/explorer-model.md), [costs and limits](../guides/costs-and-limits.md).
544
+
545
+ ### `ModelRequest`
546
+
547
+ ```ts
548
+ type ModelRequest = {
549
+ system: string;
550
+ messages: ModelMessage[];
551
+ tools?: ToolDeclaration[];
552
+ toolChoice?: "auto" | "none";
553
+ };
554
+ ```
555
+
556
+ | Field | What it holds |
557
+ |---|---|
558
+ | `system` | The system instruction: `options.system`, then the guide to the document tools, and for an explorer [`EXPLORER_INSTRUCTION`](#explorer_instruction) after them. May be empty. |
559
+ | `messages` | The conversation, oldest first. The last message is a user turn or a tool round. |
560
+ | `tools` | The tools on offer ([`ToolDeclaration`](./tools.md#tooldeclaration)). Left out of a request that needs none: every document went in whole and no page can be looked at. |
561
+ | `toolChoice` | `"auto"` for the requests that may call tools. `"none"` for the request for the answer: the model must answer in text, and the tools are still listed, for a provider that wants them declared next to the calls already in the conversation. Left out when `tools` is. |
562
+
563
+ ### `ModelMessage`
564
+
565
+ ```ts
566
+ type ModelMessage = ModelTextMessage | ModelToolRound;
567
+ ```
568
+
569
+ One message of a [`ModelRequest`](#modelrequest): a turn of text, or a round of tool use.
570
+
571
+ ### `ModelTextMessage`
572
+
573
+ ```ts
574
+ type ModelTextMessage = { role: "user" | "assistant"; parts: ModelPart[] };
575
+ ```
576
+
577
+ A turn of the user or of the model, as text and native parts. It is also a
578
+ [`ChatMessage`](#chatmessage): pass one in `messages` to send parts in the provider's own form.
579
+
580
+ ### `ModelToolRound`
581
+
582
+ ```ts
583
+ type ModelToolRound = { role: "tools"; calls: ToolCall[]; answers: ToolAnswer[]; raw?: unknown };
584
+ ```
585
+
586
+ | Field | What it holds |
587
+ |---|---|
588
+ | `role` | `"tools"`. |
589
+ | `calls` | The calls of one model turn, in order ([`ToolCall`](#toolcall)). |
590
+ | `answers` | Each call with what the tool returned, in call order ([`ToolAnswer`](#toolanswer)). Empty for a model turn that has not been answered yet, as `requestBytes` may get it. |
591
+ | `raw` | That model turn in its provider's own form. Set only for the adapter that returned it, which sends it back unchanged (Gemini wants its thought signatures, Claude its thinking blocks). Without it, the turn is built from `calls`. |
592
+
593
+ ### `ModelPart`
594
+
595
+ ```ts
596
+ type ModelPart = { text: string; native?: undefined } | { native: unknown; text?: string };
597
+ ```
598
+
599
+ One piece of a message: plain text, or something in the provider's own form (an image, an inline
600
+ PDF) that only its adapter reads. A native part may carry the text it holds in `text`: the loop
601
+ then sizes it by that text; otherwise by the size of its JSON. Each built-in adapter passes a native
602
+ part on to its provider as it is, and the loop sends it to every model of the question, so with an
603
+ explorer of another provider, that model gets it too.
604
+
605
+ ### `ToolCall`
606
+
607
+ ```ts
608
+ type ToolCall = { id?: string; name: string; args: Record<string, unknown>; problem?: string };
609
+ ```
610
+
611
+ | Field | What it holds |
612
+ |---|---|
613
+ | `id` | The provider's own ID of the call, where it gives one. |
614
+ | `name` | The tool's name: see [tools](./tools.md). |
615
+ | `args` | The arguments, as an object. |
616
+ | `problem` | Why the call cannot be run as it came: its arguments were not JSON, or it was cut off. The loop answers it with `{ error: problem }`, does not run it, and the model can send it again. |
617
+
618
+ ### `ToolAnswer`
619
+
620
+ ```ts
621
+ type ToolAnswer = { call: ToolCall; result: ToolResult; files?: ToolFile[] };
622
+ ```
623
+
624
+ A tool call with what the tool returned for it: its JSON result
625
+ ([`ToolResult`](./tools.md#toolresult)) and the files that belong to it
626
+ ([`ToolFile`](./tools.md#toolfile)), such as the pages of `view_pages`. Each result the loop adds in
627
+ a question has `tool_turns_left`, the tool turns left at that point. A stand-in that later replaces
628
+ it (`dropped: true`) does not, and a result of a stored round is sent in a later question without
629
+ it.
630
+
631
+ ### `SendHooks`
632
+
633
+ ```ts
634
+ type SendHooks = { onText?: (delta: string) => void; signal?: AbortSignal };
635
+ ```
636
+
637
+ | Field | What it holds |
638
+ |---|---|
639
+ | `onText` | Called with the reply's text as it arrives. The loop gives it only for a reply that is shown (never an explorer's) and only when the text is asked for as it is written: `streamText`, on by default with `onText` and in `askStream` (until 0.7.0, whenever the application gave `onText`). An adapter streams when it is given and it can; one that does not stream calls it once the reply is in: `openAiCompatible()` and `anthropic()` once with the whole text, `gemini()` once for each text part. The text is in `reply.text` either way, and the loop passes on what the adapter did not. The deltas must add up to the start of `reply.text`: the loop passes on the rest of `reply.text` only when it starts with what was streamed, and `result.text` is what was passed on. |
640
+ | `signal` | The question's signal. Pass it to the request. |
641
+
642
+ ### `ModelReply`
643
+
644
+ ```ts
645
+ type ModelReply = {
646
+ text: string;
647
+ calls: ToolCall[];
648
+ raw?: unknown;
649
+ finishReason?: string;
650
+ finish?: "complete" | "cut" | "filtered" | "malformed_call";
651
+ blockReason?: string;
652
+ usage?: Partial<ModelUsage>;
653
+ providerUsage?: Record<string, unknown>;
654
+ };
655
+ ```
656
+
657
+ | Field | What it holds |
658
+ |---|---|
659
+ | `text` | What the model wrote for the user in this reply. Thoughts are not part of it. |
660
+ | `calls` | The tool calls of this reply, in order. `[]` when there are none. |
661
+ | `raw` | This turn in the provider's own form, to be sent back unchanged with the tool results. The loop gives it back only to this adapter. |
662
+ | `finishReason` | Why the reply ended, in the provider's own word (`"STOP"`, `"length"`, `"end_turn"`). It becomes `result.finishReason`. |
663
+ | `finish` | How the reply ended, in terms every adapter maps its own to: `"complete"`; `"cut"` at the output limit; `"filtered"` by the provider's safety filters; `"malformed_call"`, a tool call the model tried to make that could not be read (Gemini's `MALFORMED_FUNCTION_CALL`). Unset when the adapter does not know. The loop asks once more, with a note, after a reply with no calls that is `"malformed_call"`, or that is empty before any tool ran and is neither `"cut"` nor `"filtered"`, while a tool turn is left before the answer. It also asks once more for the answer when its reply has no text and is not `"filtered"`: empty and not `"cut"`, or with calls, or `"malformed_call"`. At most two such second tries a question, the answer's included, and none for a reply with `blockReason` or once `limits.inputTokens` or `limits.requests` is reached. |
664
+ | `blockReason` | Why the provider refused the prompt, when it did. A reply with `blockReason` and no calls ends the question: no request for the answer follows, and the result has `answered: false` and this `blockReason`. |
665
+ | `usage` | The tokens of this request ([`ModelUsage`](#modelusage)), as far as the provider says. `inputTokens` must count every token of the prompt, cached ones included, and `outputTokens` the thoughts. The loop adds it to `result.usage`, and uses `inputTokens` to correct its own estimate of the request's size. |
666
+ | `providerUsage` | The provider's own usage object, as it came. It becomes `result.lastUsage`. |
667
+
668
+ ### `GenerateText`
669
+
670
+ ```ts
671
+ type GenerateText = (request: {
672
+ system: string;
673
+ prompt: string;
674
+ maxOutputTokens: number;
675
+ signal?: AbortSignal;
676
+ onTruncated?: () => void;
677
+ onUsage?: (usage: GenerateUsage) => void;
678
+ }) => Promise<string>;
679
+ ```
680
+
681
+ A plain text completion, for the parts of a whole-file read (`analyze_whole_document`). The
682
+ library stays provider-neutral by taking it as a function: `ModelAdapter.generateText`, or the
683
+ `generate` option of `files.tools()` in a loop of your own. It returns the text of the reply.
684
+
685
+ | Field | What it holds |
686
+ |---|---|
687
+ | `system` | The system instruction of the part read. |
688
+ | `prompt` | The part of the file and the task. |
689
+ | `maxOutputTokens` | The most tokens the reply may have. Send it as the provider's output limit. |
690
+ | `signal` | Stops the read. Pass it to the request. |
691
+ | `onTruncated` | Optional to call. Call it when the model stopped because it reached `maxOutputTokens`, so the read can say its result is incomplete. |
692
+ | `onUsage` | Optional to call. Call it once for every request that was answered, with the tokens it used. In `askWithFiles`, a call of `generateText` that never calls it is counted as one request with no tokens. |
693
+
694
+ Throw a `ModelRequestError` for a request that failed, as `send` does: the part is sent again by
695
+ the rule of `retry`, and an error without a status is tried once more. The model that asked for the
696
+ read, the step and `toolTurns` are told why a part failed by the error's `kind`, its HTTP status
697
+ (`status`, `statusCode` or `response.status`), or the code of a connection that failed, never by
698
+ its message: a plain `Error` is told as "The model request failed." (see
699
+ [`analyze_whole_document`](./tools.md#analyze_whole_document)). The loop stops waiting for
700
+ `generateText` when the signal aborts. Guide:
701
+ [your own adapter and loop](../guides/own-adapter-and-loop.md).
702
+
703
+ ### `GenerateUsage`
704
+
705
+ ```ts
706
+ type GenerateUsage = { inputTokens?: number; cachedInputTokens?: number; outputTokens?: number; thoughtTokens?: number };
707
+ ```
708
+
709
+ The tokens one part-read request used, as far as the provider said, for `onUsage`. The fields mean
710
+ what they mean in [`ModelUsage`](#modelusage).
711
+
712
+ ## Usage
713
+
714
+ ### `ModelUsage`
715
+
716
+ ```ts
717
+ type ModelUsage = { inputTokens: number; cachedInputTokens: number; outputTokens: number; thoughtTokens: number };
718
+ ```
719
+
720
+ Tokens of one request, or summed over several.
721
+
722
+ | Field | What it holds |
723
+ |---|---|
724
+ | `inputTokens` | Every token of the prompt, those read from a cache included. |
725
+ | `cachedInputTokens` | The part of `inputTokens` that was read from the provider's prompt cache. |
726
+ | `outputTokens` | Every token the model produced, thoughts included. |
727
+ | `thoughtTokens` | The part of `outputTokens` that went on thinking, where the provider says. |
728
+
729
+ ### `UsageTotals`
730
+
731
+ ```ts
732
+ type UsageTotals = ModelUsage & {
733
+ requests: number;
734
+ byModel: Record<string, ModelUsage & { requests: number }>;
735
+ };
736
+ ```
737
+
738
+ The usage of one question (`result.usage`): every request it made, whole-file part reads included,
739
+ in all and by model.
740
+
741
+ | Field | What it holds |
742
+ |---|---|
743
+ | `inputTokens`, `cachedInputTokens`, `outputTokens`, `thoughtTokens` | The sums over every request, as in [`ModelUsage`](#modelusage). |
744
+ | `requests` | Requests that were answered. One that failed and was sent again counts once; one that failed in the end does not count. |
745
+ | `byModel` | The same totals for each model, keyed by the adapter's `id`. |
746
+
747
+ Guide: [costs and limits](../guides/costs-and-limits.md).
748
+
749
+ ### `UsageMeter`
750
+
751
+ ```ts
752
+ declare class UsageMeter {
753
+ readonly totals: UsageTotals;
754
+ add(model: string, usage: Partial<ModelUsage> | undefined): void;
755
+ }
756
+ ```
757
+
758
+ Sums the usage of the requests of one question: `askWithFiles` uses one, and you can use one in a
759
+ loop of your own. `totals` starts at zero, with an empty `byModel`. `add` counts one request in
760
+ `totals` and in `totals.byModel[model]`, and adds each field of `usage` that is a finite number
761
+ above 0. With `usage` undefined it counts the request and no tokens.
762
+
763
+ ```ts
764
+ import { UsageMeter } from "llm-large-files";
765
+
766
+ const meter = new UsageMeter();
767
+ meter.add("gemini-3.8-flash", { inputTokens: 12_000, cachedInputTokens: 8_000, outputTokens: 450 });
768
+ meter.add("gemini-3.5-flash-lite", undefined); // a request that reported no usage still counts
769
+ console.log(meter.totals);
770
+ // { requests: 2, inputTokens: 12000, cachedInputTokens: 8000, outputTokens: 450, thoughtTokens: 0,
771
+ // byModel: { "gemini-3.8-flash": { requests: 1, … }, "gemini-3.5-flash-lite": { requests: 1, inputTokens: 0, … } } }
772
+ ```
773
+
774
+ Guide: [your own adapter and loop](../guides/own-adapter-and-loop.md).
775
+
776
+ ## Evidence and ranges
777
+
778
+ ### `Evidence`
779
+
780
+ ```ts
781
+ type Evidence = {
782
+ tool: string;
783
+ documentId: string;
784
+ document?: string;
785
+ lines?: NumberRange[];
786
+ pages?: NumberRange[];
787
+ query?: string;
788
+ mode?: string;
789
+ totalMatchingLines?: number;
790
+ whole?: boolean;
791
+ callId?: string;
792
+ };
793
+ ```
794
+
795
+ What one tool call showed the model of one document: `result.evidence` holds one for each call
796
+ that showed something.
797
+
798
+ | Field | What it holds |
799
+ |---|---|
800
+ | `tool` | The tool that was called: `"search_document"`, `"read_document"`, `"get_document_overview"`, `"analyze_whole_document"`, `"view_pages"`. |
801
+ | `documentId` | The document's ID. |
802
+ | `document` | The file's name, when the result gave it. |
803
+ | `lines` | The lines the model was shown, merged and in order. A read: its lines. A search: its passages, or each matching line with the lines of context around it, the last matching line of the file included when the search showed it. An overview: the first 30 and the last 20 lines (all of them in a file of 30 lines or fewer). |
804
+ | `pages` | The pages it looked at (`view_pages`), or the pages those lines are on, where the tool said. |
805
+ | `query` | What was searched for, or the task of a whole-file read. |
806
+ | `mode` | `"keywords"`, `"exact"` or `"regex"`, for a search. |
807
+ | `totalMatchingLines` | For an exact or regex search: how many lines match in the whole file, often more than were shown. |
808
+ | `whole` | True for a whole-file read: other model requests read every line, and the model saw their answer. It has no `lines`. |
809
+ | `callId` | The tool call it came from, as its events name it (`"call_3"`): the `callId` of its `tool.start` and `tool.end`, whose `evidence` is this entry. `askWithFiles` always sets it; [`evidenceOf`](#evidenceofcall-result) does not. New in 0.7.0. |
810
+
811
+ ```ts
812
+ import { mergeRanges, type AskResult, type NumberRange } from "llm-large-files";
813
+
814
+ // The lines each document showed in a question: a "Sources" list under the answer.
815
+ function sources(result: AskResult): string[] {
816
+ const shown = new Map<string, { name: string; lines: NumberRange[] }>();
817
+ for (const entry of result.evidence) {
818
+ const document = shown.get(entry.documentId) ?? { name: entry.document ?? entry.documentId, lines: [] };
819
+ document.lines.push(...(entry.lines ?? []));
820
+ shown.set(entry.documentId, document);
821
+ }
822
+ return [...shown.values()]
823
+ .filter(({ lines }) => lines.length > 0)
824
+ .map(({ name, lines }) => `${name}: lines ${mergeRanges(lines).map(([from, to]) => (to > from ? `${from}-${to}` : `${from}`)).join(", ")}`);
825
+ }
826
+ ```
827
+
828
+ ### `NumberRange`
829
+
830
+ ```ts
831
+ type NumberRange = [from: number, to: number];
832
+ ```
833
+
834
+ A range of lines or pages, 1-based, both ends included: `[12, 14]` is 12, 13 and 14.
835
+
836
+ ### evidenceOf(call, result)
837
+
838
+ ```ts
839
+ declare function evidenceOf(call: ToolCall, result: ToolResult): Evidence | undefined;
840
+ ```
841
+
842
+ What a tool call showed of a document, read from the call and its result, as `askWithFiles` builds
843
+ `result.evidence`. Use it in a loop of your own. It returns `undefined` when the call's
844
+ `document_id` is missing, empty or not a string, the result is an error (`error`), or the result is
845
+ a stand-in for a dropped one (`dropped: true`).
846
+
847
+ ```ts
848
+ import { evidenceOf, mergeRanges } from "llm-large-files";
849
+
850
+ evidenceOf(
851
+ { name: "read_document", args: { document_id: "d1", start_line: 120, end_line: 180 } },
852
+ { document: "app.log", lines: "120-180", total_lines: 50_000, text: "…" },
853
+ );
854
+ // { tool: "read_document", documentId: "d1", document: "app.log", lines: [[120, 180]] }
855
+
856
+ mergeRanges([[40, 52], [1, 30], [31, 35], [50, 60]]);
857
+ // [[1, 35], [40, 60]]
858
+ ```
859
+
860
+ ### mergeRanges(ranges)
861
+
862
+ ```ts
863
+ declare function mergeRanges(ranges: NumberRange[]): NumberRange[];
864
+ ```
865
+
866
+ The ranges in order, with those that overlap or touch made one: `[1, 30]` and `[31, 35]` become
867
+ `[1, 35]`. It returns a new array and leaves `ranges` as it was. The sample above shows it.
868
+
869
+ ### stubResult(call, result, hadFiles?)
870
+
871
+ ```ts
872
+ declare function stubResult(call: ToolCall, result: ToolResult, hadFiles?: boolean): ToolResult | undefined;
873
+ ```
874
+
875
+ A short stand-in for a tool result that is dropped from the request to make room. It keeps the
876
+ document's name, says which lines or pages the result showed so that the model can get them again,
877
+ and has `dropped: true` and a `note` that says it is a stand-in. `askWithFiles` uses it to shorten
878
+ older tool results, and for the pages in `result.toolTurns`. Set `hadFiles` (default `false`) for a
879
+ result whose files (pages) are dropped with it, however small its JSON is.
880
+
881
+ It returns `undefined` when there is nothing to gain: the result is an error, is already a
882
+ stand-in, or (without `hadFiles`) its JSON is under 700 characters. Otherwise, by tool:
883
+
884
+ | Tool | The stand-in keeps |
885
+ |---|---|
886
+ | `read_document` | `lines`, `total_lines` |
887
+ | `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) |
888
+ | `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 |
889
+ | `view_pages` | `pages`, `total_pages` |
890
+ | `get_document_overview`, any other | nothing more than `document` and the note |
891
+
892
+ Guide: [your own adapter and loop](../guides/own-adapter-and-loop.md).