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,1199 @@
1
+ # Testing an integration
2
+
3
+ This guide shows how to test code that uses llm-large-files without calling a real model: tests
4
+ that run in milliseconds, cost nothing and give the same result every time. It is for application
5
+ developers. The samples use [Vitest](https://vitest.dev); the helper files they build do not
6
+ depend on it.
7
+
8
+ ## What to fake
9
+
10
+ Fake the layer below the code you test, and nothing above it.
11
+
12
+ | What you test | What to fake | Section |
13
+ | --- | --- | --- |
14
+ | Your code around a question: what it stores, shows and streams, and what it does with each error | The model: a scripted `ModelAdapter` | [A scripted model](#a-scripted-model) |
15
+ | Your provider setup: the URL, the token, the body fields, how a reply or a stream is read | The network: the `fetch` of a real adapter | [The real adapters with a fake fetch](#the-real-adapters-with-a-fake-fetch) |
16
+ | Expiry, owners, deleting | The clock: `now`, with `MemoryDocumentStore` | [Expiry, owners and the clock](#expiry-owners-and-the-clock) |
17
+ | Your upload and answer routes | Nothing for uploads, the model for answers: a real server on a free port, called with `fetch` | [Your routes](#your-routes) |
18
+ | Whether a real model finds the answer in a real file | Nothing: a few live tests | [Live tests, few and cheap](#live-tests-few-and-cheap) |
19
+
20
+ The library's own tests work the same way, with a fake model and fake `fetch` functions. Their
21
+ helper (`test/fake-model.ts` in the repository) is not part of the package, so the helper below is
22
+ one you copy into your own tests.
23
+
24
+ ## Test documents
25
+
26
+ Use a new `MemoryDocumentStore` in each test: it keeps documents in process memory, so tests do not
27
+ share them and leave nothing behind. `ingest` takes the bytes of a file; for text, encode a string
28
+ with `TextEncoder`, which writes UTF-8. To test a file in an older encoding, such as a CSV that
29
+ Excel saved in windows-1255, give `ingest` the bytes of a real file: `meta.encoding` then says how
30
+ it was read ([Text encodings](./pdfs.md#text-encodings)).
31
+
32
+ A document that fits goes into the prompt whole (by default up to 200,000 estimated tokens of
33
+ documents), and the question is then one model request without tools. To test the tool loop with a
34
+ small file, lower `budget.inlineTokens`: with 1,000, a document whose estimate is over 1,000 tokens
35
+ becomes a card that the model reaches through the tools, as a 50 MB log would. Set it on
36
+ `createLargeFiles`, or for one question with `budget` in `askWithFiles`. How the plan is made is in
37
+ [How it works](../how-it-works.md).
38
+
39
+ The helper file below has `bytes()` and `appLog(count)`, a log of `count` lines with a failed
40
+ payment on every 50th. From 19 lines on it is over 1,000 estimated tokens. The samples use 400
41
+ lines, which hold 8 failed payments.
42
+
43
+ ## A scripted model
44
+
45
+ `askWithFiles` talks to a model only through a [`ModelAdapter`](../reference/ask.md#modeladapter):
46
+ an object with an `id`, its `capabilities` and a `send` method. A fake one answers each request from
47
+ a script and records what it was sent. Save this as `test/fake-model.ts`:
48
+
49
+ ```ts
50
+ // test/fake-model.ts: a scripted model, and test documents, for code that calls askWithFiles.
51
+ import type { GenerateText, ModelAdapter, ModelCapabilities, ModelReply, ModelRequest, SendHooks, ToolCall } from "llm-large-files";
52
+
53
+ /** One entry of a script: a reply, an error to throw, or a function that picks one from the request. */
54
+ export type Scripted =
55
+ | Partial<ModelReply>
56
+ | Error
57
+ | ((request: ModelRequest, call: number, hooks: SendHooks) => Partial<ModelReply> | Error | Promise<Partial<ModelReply> | Error>);
58
+
59
+ export type FakeModel = ModelAdapter & {
60
+ /** Every request the loop sent, in order, failed ones included. */
61
+ readonly requests: ModelRequest[];
62
+ };
63
+
64
+ /** A reply in text. */
65
+ export const says = (text: string, more: Partial<ModelReply> = {}): Partial<ModelReply> => ({ text, ...more });
66
+
67
+ /** A reply that calls tools. */
68
+ export const calls = (list: ToolCall[], more: Partial<ModelReply> = {}): Partial<ModelReply> => ({ calls: list, ...more });
69
+
70
+ /**
71
+ * A model that answers each request with the next entry of its script; the last entry repeats.
72
+ * An entry that is an Error is thrown, as an adapter throws a request that failed.
73
+ */
74
+ export function fakeModel(
75
+ script: Scripted[],
76
+ options: Partial<ModelCapabilities> & { id?: string; generateText?: GenerateText } = {},
77
+ ): FakeModel {
78
+ const { id = "fake-model", generateText, ...capabilities } = options;
79
+ const requests: ModelRequest[] = [];
80
+ return {
81
+ id,
82
+ // "none": this model takes no files, so view_pages is not offered. Pass toolFiles: "inside" to test it.
83
+ capabilities: { toolFiles: "none", pageTokens: 500, ...capabilities },
84
+ requests,
85
+ ...(generateText ? { generateText } : {}),
86
+ async send(request, hooks = {}) {
87
+ // A copy of the list, so that what was recorded cannot change later.
88
+ requests.push({ ...request, messages: [...request.messages] });
89
+ const entry = script[Math.min(requests.length - 1, script.length - 1)]!;
90
+ const reply = typeof entry === "function" ? await entry(request, requests.length, hooks) : entry;
91
+ if (reply instanceof Error) throw reply;
92
+ const text = reply.text ?? "";
93
+ // When the loop listens for text, pass it on in two pieces, as a streaming adapter would.
94
+ if (text && hooks.onText) {
95
+ const half = Math.ceil(text.length / 2);
96
+ hooks.onText(text.slice(0, half));
97
+ if (half < text.length) hooks.onText(text.slice(half));
98
+ }
99
+ return { calls: [], ...reply, text };
100
+ },
101
+ };
102
+ }
103
+
104
+ export const bytes = (text: string): Uint8Array => new TextEncoder().encode(text);
105
+
106
+ /** A service log of `count` lines, with a failed payment on every 50th line. */
107
+ export function appLog(count: number): string {
108
+ const lines: string[] = [];
109
+ for (let n = 1; n <= count; n++) {
110
+ const time = new Date(Date.UTC(2026, 0, 1, 8, 0, n)).toISOString();
111
+ lines.push(n % 50 === 0
112
+ ? `${time} ERROR [worker-${n % 4}] payment ${n} failed: card declined`
113
+ : `${time} INFO [worker-${n % 4}] GET /api/orders/${n} 200 in ${(n * 37) % 900} ms`);
114
+ }
115
+ return lines.join("\n");
116
+ }
117
+ ```
118
+
119
+ What the parts do:
120
+
121
+ - **The script.** One entry for each request, in order. The last entry repeats, so a model that
122
+ always says the same thing is a script of one. An `Error` entry is thrown from `send`, as a real
123
+ adapter throws a request that failed. A function entry gets the request, its number (1 for the
124
+ first) and the hooks, and returns the reply: use it when the reply depends on what was asked.
125
+ - **`requests`.** A copy of each request as it was sent, failed attempts included.
126
+ - **`onText`.** When your code passes `onText` to `askWithFiles` (or `streamText: true`, or uses
127
+ `askStream`), the loop passes a hook to the adapter, and the fake calls it with the text in two
128
+ pieces, as a stream would arrive. With `onEvent` alone, it does not: the text then comes in one
129
+ `text` event, once the reply is in.
130
+ - **The options.** `id` names the model in `usage.byModel`; give two fakes different ones. A
131
+ `generateText` function offers `analyze_whole_document`, the whole-file read in parts; without it
132
+ that tool is not offered. The capabilities make the fake look like a given model:
133
+ `contextTokens` and `maxRequestBytes` make the budget of a question fit them, `appendOnly: true`
134
+ makes the loop treat it as Claude (a conversation that may only grow), and `toolFiles: "inside"`
135
+ lets the loop offer `view_pages` for PDFs whose original is kept (see [PDFs](./pdfs.md)).
136
+
137
+ A fake adapter is also the starting point for one of your own: see
138
+ [Your own adapter and loop](./own-adapter-and-loop.md).
139
+
140
+ ## A first test
141
+
142
+ Two tests: a short document that goes in whole, and a log that the model must search.
143
+
144
+ ```ts
145
+ // test/ask.test.ts
146
+ import { describe, expect, it } from "vitest";
147
+ import { askWithFiles, createLargeFiles, MemoryDocumentStore } from "llm-large-files";
148
+ import { appLog, bytes, calls, fakeModel, says } from "./fake-model.js";
149
+
150
+ const question = (text: string) => [{ role: "user" as const, text }];
151
+
152
+ describe("questions about documents", () => {
153
+ it("sends a short document whole, in one request without tools", async () => {
154
+ const files = createLargeFiles({ store: new MemoryDocumentStore() });
155
+ const meta = await files.ingest({ name: "notes.md", bytes: bytes("# Notes\n\nThe code word is heron.") });
156
+ const model = fakeModel([says("Heron.", { usage: { inputTokens: 40, outputTokens: 3 } })]);
157
+
158
+ const result = await askWithFiles({ files, model, documentIds: [meta.id], messages: question("What is the code word?") });
159
+
160
+ expect(result).toMatchObject({ text: "Heron.", answered: true, steps: [], evidence: [], toolTurns: [], turns: 1 });
161
+ expect(result.usage).toMatchObject({ requests: 1, inputTokens: 40, outputTokens: 3 });
162
+ expect(model.requests).toHaveLength(1);
163
+ expect(model.requests[0]!.tools).toBeUndefined();
164
+ });
165
+
166
+ it("searches a log too large to send whole, then answers", async () => {
167
+ // Any document over about 1,000 tokens becomes a card with tools: a small test file takes
168
+ // the path that a real 50 MB log takes.
169
+ const files = createLargeFiles({ store: new MemoryDocumentStore(), budget: { inlineTokens: 1_000 } });
170
+ const meta = await files.ingest({ name: "app.log", bytes: bytes(appLog(400)) });
171
+ const search = { id: "call_1", name: "search_document", args: { document_id: meta.id, query: "ERROR", mode: "exact" } };
172
+ const model = fakeModel([calls([search]), says("8 payments failed, the first on line 50 (app.log L50).")]);
173
+
174
+ const result = await askWithFiles({ files, model, documentIds: [meta.id], messages: question("How many payments failed?") });
175
+
176
+ // The first request offers the tools; the second carries the call and what the tool returned.
177
+ expect(model.requests[0]!.tools!.map((tool) => tool.name)).toEqual(["search_document", "read_document", "get_document_overview"]);
178
+ const round = model.requests[1]!.messages.find((message) => message.role === "tools");
179
+ expect(round).toMatchObject({ calls: [search], answers: [{ result: { document: "app.log", total_matching_lines: 8 } }] });
180
+
181
+ expect(result).toMatchObject({ answered: true, turns: 2 });
182
+ expect(result.plan.searchable.map((document) => document.name)).toEqual(["app.log"]);
183
+ expect(result.steps).toEqual(["Search app.log (exact) for “ERROR” — 8 matching lines"]);
184
+ expect(result.evidence).toEqual([expect.objectContaining({ tool: "search_document", documentId: meta.id, query: "ERROR", totalMatchingLines: 8 })]);
185
+ expect(result.toolTurns[0]!.calls[0]).toMatchObject({ name: "search_document", result: { total_matching_lines: 8 } });
186
+ });
187
+ });
188
+ ```
189
+
190
+ The tool calls of a script are what a model would send: a tool name and its arguments, as the
191
+ [tools reference](../reference/tools.md) lists them. The tools run for real, against the document in
192
+ the store, so the test checks what your file holds. A call names its document by ID, and the ID is
193
+ new on every ingest: write the script after the ingest, as here, or in a function entry.
194
+
195
+ Each recorded `ModelRequest` holds what the model was given:
196
+
197
+ - `system`: your `system` text, then the library's guide to the tools when there are any, and in
198
+ an explorer's requests `EXPLORER_INSTRUCTION` after them.
199
+ - `messages`: the conversation. A text turn is `{ role: "user" | "assistant", parts }`; a tool round
200
+ is `{ role: "tools", calls, answers }`, where each answer's `result` is the JSON the model sees.
201
+ - `tools`: the declarations on offer, left out when the question needs none.
202
+ - `toolChoice`: `"auto"` while tools may run, `"none"` for the request that must be answered in
203
+ text. Left out, with `tools`, when the question needs no tools.
204
+
205
+ The [`ModelRequest` reference](../reference/ask.md#modelrequest) has every field.
206
+
207
+ ### Replies that depend on the request
208
+
209
+ A function entry decides from the request. These tests cover the end of the tool loop, streamed
210
+ text, a blocked prompt and an explorer model:
211
+
212
+ ```ts
213
+ // test/loop.test.ts
214
+ import { describe, expect, it } from "vitest";
215
+ import { askWithFiles, createLargeFiles, MemoryDocumentStore } from "llm-large-files";
216
+ import { appLog, bytes, calls, fakeModel, says } from "./fake-model.js";
217
+
218
+ const question = (text: string) => [{ role: "user" as const, text }];
219
+
220
+ async function largeLog() {
221
+ const files = createLargeFiles({ store: new MemoryDocumentStore(), budget: { inlineTokens: 1_000 } });
222
+ const meta = await files.ingest({ name: "app.log", bytes: bytes(appLog(400)) });
223
+ return { files, meta };
224
+ }
225
+
226
+ describe("the tool loop", () => {
227
+ it("asks for the answer in text when the tool turns run out", async () => {
228
+ const { files, meta } = await largeLog();
229
+ // A model that never stops reading, until it is told to answer (toolChoice "none").
230
+ const model = fakeModel([(request, call) => request.toolChoice === "none"
231
+ ? says("No failure in the first 30 lines.")
232
+ : calls([{ name: "read_document", args: { document_id: meta.id, start_line: call * 10, end_line: call * 10 + 9 } }])]);
233
+
234
+ const result = await askWithFiles({ files, model, documentIds: [meta.id], messages: question("Any failures early on?"), limits: { toolTurns: 3 } });
235
+
236
+ expect(model.requests.map((request) => request.toolChoice)).toEqual(["auto", "auto", "none"]);
237
+ expect(result.steps).toEqual(["Read app.log lines 10-19", "Read app.log lines 20-29"]);
238
+ expect(result).toMatchObject({ text: "No failure in the first 30 lines.", answered: true, turns: 3 });
239
+ });
240
+
241
+ it("streams the text, and reports each step as it is taken", async () => {
242
+ const { files, meta } = await largeLog();
243
+ const search = { name: "search_document", args: { document_id: meta.id, query: "ERROR", mode: "exact" } };
244
+ const model = fakeModel([calls([search], { text: "Checking the log." }), says("8 payments failed.")]);
245
+ const deltas: string[] = [];
246
+ const steps: string[] = [];
247
+
248
+ const result = await askWithFiles({
249
+ files, model, documentIds: [meta.id], messages: question("How many payments failed?"),
250
+ onText: (delta) => deltas.push(delta),
251
+ onStep: (step) => steps.push(step),
252
+ });
253
+
254
+ // The loop puts a blank line between the text of two model turns.
255
+ expect(result.text).toBe("Checking the log.\n\n8 payments failed.");
256
+ expect(deltas.join("")).toBe(result.text);
257
+ expect(steps).toEqual(result.steps);
258
+ });
259
+
260
+ it("returns answered: false when the provider blocks the prompt", async () => {
261
+ const { files, meta } = await largeLog();
262
+ const model = fakeModel([says("", { blockReason: "SAFETY" })]);
263
+
264
+ const result = await askWithFiles({ files, model, documentIds: [meta.id], messages: question("?") });
265
+
266
+ expect(result).toMatchObject({ answered: false, blockReason: "SAFETY", text: "" });
267
+ });
268
+
269
+ it("lets an explorer search while the main model answers", async () => {
270
+ const { files, meta } = await largeLog();
271
+ const search = { name: "search_document", args: { document_id: meta.id, query: "ERROR", mode: "exact" } };
272
+ // The explorer calls the tools, then replies DONE; the other model writes the answer.
273
+ const explorer = fakeModel([calls([search]), says("DONE")], { id: "explorer" });
274
+ const model = fakeModel([says("8 payments failed.")], { id: "answerer" });
275
+
276
+ const result = await askWithFiles({ files, model, explorer, documentIds: [meta.id], messages: question("How many payments failed?") });
277
+
278
+ expect(explorer.requests).toHaveLength(2);
279
+ expect(model.requests[0]!.toolChoice).toBe("none");
280
+ expect(result).toMatchObject({ text: "8 payments failed.", answered: true, turns: 3 });
281
+ expect(result.usage.byModel.explorer!.requests).toBe(2);
282
+ expect(result.usage.byModel.answerer!.requests).toBe(1);
283
+ });
284
+ });
285
+ ```
286
+
287
+ What these show of the loop:
288
+
289
+ - `limits.toolTurns` counts the answer: with 3, tools run in the first two requests, and the third
290
+ has `toolChoice: "none"`. The tools are still listed in it, and the last user turn asks for the
291
+ answer (`FINAL_ANSWER_REQUEST`). See [`AskLimits`](../reference/ask.md#asklimits).
292
+ - The same search or read twice is not run twice: the second gets a pointer to the first result
293
+ (in a later turn, it runs again when that result failed or was cut). That is why the reads above
294
+ move on by ten lines a request.
295
+ - Text the model writes before a tool call is part of `text`, and of what `onText` receives, with
296
+ `"\n\n"` before the next turn's text.
297
+ - In the tool loop (not for a document sent whole), a reply with no text and no tool call before
298
+ any tool ran, or a tool call that could not be read (`finish: "malformed_call"`), is asked for
299
+ once more. An empty reply that was cut off (`finish: "cut"`), filtered or blocked is not. This
300
+ happens at most twice a question, and only while a tool turn is left: the second try is a
301
+ request of its own and takes a tool turn. It adds a step to `steps` and `onStep`: "The model's
302
+ first reply was empty: it was asked again", or "The model's tool call could not be read: it was
303
+ asked to send it again". Script that reply too, or the fake repeats its last entry.
304
+ - The request for the answer (`toolChoice: "none"`) is asked for once more when its reply has no
305
+ text, or holds a tool call, with a note at its end that is not kept: "Your last reply had no
306
+ text. No tool can be called in this reply: write the answer now, in text, from what is above."
307
+ Its step is "The model's answer was empty: it was asked again", or "The model called a tool
308
+ instead of answering: it was asked again for the answer". It is one of the two second tries, and
309
+ can be one request past `limits.toolTurns`; it is not made after a refusal, a filter, a reply
310
+ cut off at the output limit with nothing in it, or once `limits.requests` or
311
+ `limits.inputTokens` is reached. So a fake that answers the answer's request
312
+ with nothing gets one more request, with `toolChoice: "none"`. The fake above repeats its last
313
+ entry; a fake that throws when its queue of replies runs out fails there.
314
+ - With an `explorer`, the explorer gets the tool requests and what it writes is not shown. The
315
+ answering model gets one request, with `toolChoice: "none"`. `turns` counts the chat requests of
316
+ both. See [An explorer model](./explorer-model.md).
317
+
318
+ ## What to assert
319
+
320
+ Assert what your application does with the result. These are the fields of
321
+ [`AskResult`](../reference/ask.md#askresult) worth checking, and what a fake makes them:
322
+
323
+ | Field | What it holds in a test |
324
+ | --- | --- |
325
+ | `text` | What the script wrote: the answer, after any remark made before a tool call. |
326
+ | `answered` | `false` when the last turn had no text: a blocked prompt (`blockReason`), a reply cut off before any text, an answer with no text after its second try. Test that your application then shows its own message. |
327
+ | `steps` | The steps `onStep` received, in order. They are sentences for people, written by the library, one line of plain text each. |
328
+ | `evidence` | One entry per tool call that showed something: `tool`, `documentId`, `document`, `lines`, `pages`, `query`, `mode`, `totalMatchingLines`, `whole`. |
329
+ | `toolTurns` | The tool rounds as plain JSON. Test that your application stores them, and passes them back between the question and its answer (see [Conversations](./conversations.md)). |
330
+ | `turns` | Chat requests made, an explorer's included: 1 for a document sent whole. |
331
+ | `usage` | The sum of the `usage` your fake returned: `requests`, `inputTokens`, `cachedInputTokens`, `outputTokens`, `thoughtTokens`, and the same per model `id` in `byModel`. A request that failed and was sent again counts once. |
332
+ | `plan` | `plan.inline` and `plan.searchable`: which documents went in whole and which were searched. |
333
+ | `finishReason`, `lastUsage` | The `finishReason` and `providerUsage` of the last reply, as the fake gave them. |
334
+
335
+ Some advice:
336
+
337
+ - Compare `steps` and `evidence` to the tools that ran, not to the model's wording. A test that
338
+ compares whole step sentences checks the library's wording too, and needs an update when it
339
+ changes; `toHaveLength` or `toContain` is often enough.
340
+ - Do not compare the `system` text or the document cards in a request whole: they are the
341
+ library's prompts, not your application's. Check that your own `system` text is in it.
342
+ - To test what your application does with `usage` (a cost per user, a ceiling), give the fake's
343
+ replies round numbers of tokens, as above. See [Costs and limits](./costs-and-limits.md).
344
+
345
+ ### Events
346
+
347
+ New in 0.7.0. To test what your application shows while a question runs, collect the events of a
348
+ scripted question with `onEvent` (or read `askStream`), and assert their order and the fields your
349
+ page reads. Compare `type`s, ids and outcomes, not whole events: `time` changes on every run, and
350
+ the wording of a label or a notice is the library's.
351
+
352
+ ```ts
353
+ // test/events.test.ts
354
+ import { expect, it } from "vitest";
355
+ import { askStream, createLargeFiles, MemoryDocumentStore, type AskEvent } from "llm-large-files";
356
+ import { appLog, bytes, calls, fakeModel, says } from "./fake-model.js";
357
+
358
+ it("shows the search, then the answer, in order", async () => {
359
+ const files = createLargeFiles({ store: new MemoryDocumentStore(), budget: { inlineTokens: 1_000 } });
360
+ const meta = await files.ingest({ name: "app.log", bytes: bytes(appLog(400)) });
361
+ const search = { id: "s1", name: "search_document", args: { document_id: meta.id, query: "ERROR", mode: "exact" } };
362
+ const model = fakeModel([calls([search]), says("8 payments failed.")]);
363
+
364
+ const events: AskEvent[] = [];
365
+ const stream = askStream({ files, model, documentIds: [meta.id], messages: [{ role: "user", text: "How many failed?" }], runId: "run_test" });
366
+ for await (const event of stream) events.push(event);
367
+
368
+ // seq counts from 1 without gaps, every event names the run, and the run ends once, last.
369
+ expect(events.map((event) => event.seq)).toEqual(events.map((_, index) => index + 1));
370
+ expect(events.every((event) => event.runId === "run_test")).toBe(true);
371
+ expect(events.map((event) => event.type).filter((type) => type !== "text" && type !== "notice")).toEqual([
372
+ "run.start", "plan",
373
+ "request.start", "request.end", // the turn that calls the tool
374
+ "tool.start", "tool.end",
375
+ "request.start", "request.end", // the answer
376
+ "run.finish",
377
+ ]);
378
+ expect(events.find((event) => event.type === "tool.end")).toMatchObject({ callId: "call_1", outcome: "ok" });
379
+ // askStream streams by default: the fake passes the answer in two pieces, which join to the text.
380
+ const text = events.flatMap((event) => (event.type === "text" ? [event.delta] : []));
381
+ expect(text.join("")).toBe((await stream.result).text);
382
+ });
383
+ ```
384
+
385
+ To test a failure, script an `Error` entry, as in [Errors](#errors): the run ends with `run.error`,
386
+ whose `error.message` is told in words for users, while `stream.result` rejects with the error as
387
+ the fake threw it. The library's own tests check the same rules for every run: each
388
+ `request.start` and `tool.start` has its end, and each `retry`, `text` and `tool.progress` falls
389
+ between them.
390
+
391
+ ### Output that 0.6.0 changed
392
+
393
+ A test that pins the library's exact output breaks when that output changes. These changed in
394
+ 0.6.0, for a test written for 0.5.0:
395
+
396
+ - **A stream must say that it ended.** A fake stream without Gemini's `finishReason`, an
397
+ OpenAI-compatible `finish_reason` or `[DONE]`, or Claude's `stop_reason`, is no longer a whole
398
+ reply: it throws "Gemini's reply ended before it was complete." (or "The model's …",
399
+ "Claude's …"), status 0, kind `unreachable`, and is sent again when none of its text was shown.
400
+ Give the last piece of a fake stream its end marker.
401
+ - **A repeated call is not run.** The same search, read or overview, or a read of lines inside a
402
+ read shown in full, gets a pointer to the earlier result: `already_shown: true` and a note, a
403
+ step that ends ` — already shown above`, and no entry in `evidence`. Script calls that differ.
404
+ - **An empty first reply, or a tool call that could not be read, is asked for once more**: one
405
+ more request, and the step `The model's first reply was empty: it was asked again`. Script that
406
+ reply too.
407
+ - **Tool results have new fields**: `already_shown`, `text_cut`, and on a whole-file read
408
+ `notes_only` and `answer_shortened`. Compare with `toMatchObject`, not `toEqual`.
409
+ - **Model errors have a `kind`**, and some are not sent again as they were. A quota (a Gemini
410
+ quota per day, OpenAI's `insufficient_quota`, HTTP 402, Claude's credit and spending limits) is
411
+ thrown at once. A request too large, OpenAI's HTTP 429 for the tokens a minute among them, is
412
+ never sent again as it was: the loop makes it smaller first, when it can. 0.5.0 sent every error
413
+ of status 0, 408, 409, 429 or 500 and more again, up to three times.
414
+ - **Calls without an ID** get a random one from `anthropicToolTurns` and `openAiToolTurns`:
415
+ `toolu_` or `call_` and 24 hex digits, a new one each time, where 0.5.0 gave `toolu_1_1` or
416
+ `call_1_1`.
417
+ - **An upload whose store fails** while it writes, with an error that has no status, is answered
418
+ `500` `{ "error": "Upload failed." }`, not `422` with the store's message.
419
+ - **A model that sends nothing fails after a wait.** A real adapter aborts a request that gets
420
+ nothing for `firstByteTimeoutMs` (600,000 ms), or for `idleTimeoutMs` (300,000 ms) between
421
+ pieces: a test with fake timers that moves the clock that far now aborts it
422
+ ([Timers](#timers)). 0.5.0 waited without end.
423
+ - **Two searches in a row that fail in the same mode** get a hint at the end of their error:
424
+ `Two regex searches in a row failed. Try mode "exact" with a plain word or ID from the file, or mode "keywords".`
425
+ or `This search failed twice in a row. Check the arguments against the tool's description, or answer from what you have.`
426
+ - **An unknown `document_id`** is answered `Unknown document_id nope. Use one of: <id> ("app.log").`,
427
+ where 0.5.0 said `Unknown document_id nope. Use an ID from a file card.`
428
+ - **Part reads of a fake `generateText` that does not call `onUsage`** count in `usage.requests`
429
+ and toward `limits.requests`.
430
+ - **The frame of a file sent whole** carries a mark made from the document ID, before the quoted
431
+ name: `--- Attached file [mark 1f0c3a9e]: "report.txt" (text, 6 lines; it ends only at the line with mark 1f0c3a9e) ---`
432
+ and `--- End attached file [mark 1f0c3a9e] ---`. It was `--- Attached file: report.txt (text, 6 lines) ---`.
433
+ The ID is new on every ingest, so the mark is too: match the start, `--- Attached file [mark `,
434
+ or find one file by `]: ` and its name as a JSON string (`JSON.stringify(name)`), then ` (`. A
435
+ file of one line says `1 line`, and the card of a PDF of one page `1 page`.
436
+ - **An exact or regex search** with more matching lines than `max_results` returns one more entry
437
+ in `matches`: the first `max_results`, then the last matching line of the file, with the note
438
+ `21 of the 442 matching lines are shown: the first 20 and the last (line 15269). To see the ones in between, narrow the search.`
439
+ Its `evidence` lists the lines of the last match too. With no more matches than `max_results`,
440
+ nothing changed, unless the result is cut to the room it has: the last match then stays, matches
441
+ are dropped from the end of the first ones, and the note is new,
442
+ `Showing 4 of the 10 matching lines to stay within the size limit: the first 3 and the last (line 1000). Narrow the query or read specific lines.`
443
+ where 0.5.0 said `Showing 4 of 10 results to stay within the size limit. …`.
444
+ - **Steps with a count of one** are singular: ` — 1 matching line`, ` — 1 passage`,
445
+ ` — 1 part, 1 relevant`, and `1 more tool call in this turn was not run (at most 8 a turn)`.
446
+ - **A call to a tool that does not exist** has the step `Call “do_magic” — failed: Unknown tool “do_magic”.`,
447
+ and the model gets `Unknown tool “do_magic”.`, as `files.tools().execute()` returns it.
448
+ - **The answer's second try** ([above](#replies-that-depend-on-the-request)): one more request when
449
+ the answer comes back without text. To cap the requests of a question exactly, set
450
+ `limits.requests`.
451
+ - **A whole-file read that fails** says why by the kind and status of the error, never by its
452
+ words: `Could not read any part of app.log: The model was busy (HTTP 429).` A fake `generateText`
453
+ that throws a plain `Error` gives `The model request failed.`, and one that throws
454
+ `new ModelRequestError("…", 401)` gives `The model refused the key or token it was sent (HTTP 401).`
455
+ - **A reply of HTTP 200 that is not JSON** is a `ModelRequestError` of kind `invalid` and status
456
+ 200, with the `SyntaxError` as its `cause`: test `error.cause instanceof SyntaxError`. Kind
457
+ `invalid` alone also covers every other request the provider refused.
458
+ - **A fake `fetch` whose reply of HTTP 200 is empty** gets the request again: the reply is kind
459
+ `unreachable`, status 0. A streamed reply that is not of type `text/event-stream` is read by what
460
+ it holds: as events when it starts like them, as JSON when it starts with `{` or `[`.
461
+ - **An error inside a stream** has the status and the kind of its type: on an OpenAI-compatible
462
+ endpoint, `context_length_exceeded` is 400, kind `context_overflow`; on Claude,
463
+ `authentication_error` is 401, kind `auth`. Both kept the stream's HTTP 200 in 0.5.0.
464
+ - **A question stopped while its adapter is called** throws the signal's reason, even when the
465
+ adapter then fails with its own error (a fake that throws a 503, say).
466
+ - **A Gemini part read** sends `generationConfig: { maxOutputTokens }`, without `temperature`.
467
+ - **The card of a text file that is not valid UTF-8** has one more line, and its frame a note
468
+ after the count of lines, such as `, read as windows-1255`
469
+ ([Text encodings](./pdfs.md#text-encodings)).
470
+ - **The stored text** of a file with characters that show nothing, with text that Word hides, or
471
+ with a hidden slide differs from what 0.5.0 stored
472
+ ([Characters that show nothing](../security.md#characters-that-show-nothing)).
473
+ - **Steps** quote the model's words on one line, without the characters that show nothing. The
474
+ steps of a request too large are new, such as
475
+ `The request was larger than the model takes: older tool results were shortened, and it was sent again`
476
+ and `The first request was larger than the model's window of 60,000 tokens: the files were planned again to fit it`,
477
+ and the same for the tokens a minute the provider allows. So is `, notes only` at the end of the
478
+ step of a whole-file read that returned only its notes.
479
+ - **`anthropic().capabilities`** has `clearsToolResults: true` when `body.context_management`
480
+ clears tool uses or compacts the conversation.
481
+ - **`geminiToolTurns`, `openAiToolTurns` and `anthropicToolTurns`** leave `tool_turns_left` out of
482
+ each result, so their output no longer equals the stored result.
483
+ - **`MemoryDocumentStore`** returns a new copy of the metadata from each call: compare with
484
+ `toEqual`, not `toBe`.
485
+ - **`files.ingest` with `owner: ""`** throws a `TypeError`
486
+ ([Storage](./storage.md#how-ownership-works)).
487
+ - **The descriptions of `search_document` and `analyze_whole_document`** changed: the first now
488
+ says that exact and regex results show the first `max_results` matching lines and the last one,
489
+ and the second sends counting and listing to `search_document`. A test that compares the tool
490
+ declarations, or the `tools` of a request, with a stored copy fails.
491
+
492
+ ## Errors
493
+
494
+ A fake throws what a real adapter throws: a
495
+ [`ModelRequestError`](../reference/errors-and-retries.md#modelrequesterror) with an HTTP `status`
496
+ and a `kind`. The kind is told from the status, the message and the provider's `code` (and a
497
+ Gemini error's `details`), unless you pass `kind`:
498
+
499
+ | Kind | A fake throws | The loop sends it again |
500
+ | --- | --- | --- |
501
+ | `rate_limit` | `new ModelRequestError("Too many requests.", 429)` | Yes, up to `retry.retries` times (3) |
502
+ | `quota` | `new ModelRequestError("You exceeded your current quota.", 429, { code: "insufficient_quota" })` | No |
503
+ | `server` | `new ModelRequestError("The model is overloaded.", 503)` | Yes |
504
+ | `timeout` | `new ModelRequestError("The model sent nothing for 600 s.", 0, { kind: "timeout" })` | Once |
505
+ | `unreachable` | `new ModelRequestError("The model could not be reached.", 0)` | Yes |
506
+ | `auth` | `new ModelRequestError("Token expired.", 401)` | No |
507
+ | `invalid` | `new ModelRequestError("Bad request.", 400)` | No (HTTP 409 is `invalid` too, and is sent again) |
508
+ | `context_overflow` | `new ModelRequestError("prompt is too long: 210417 tokens > 200000 maximum", 400)` | Not as it was: the loop makes the request smaller, or plans the documents again for a smaller window |
509
+
510
+ An `Error` without a `status` is not sent again, and reaches your code as it is. What each kind
511
+ means for a user is in [Errors and reliability](./errors-and-reliability.md).
512
+
513
+ ```ts
514
+ // test/errors.test.ts
515
+ import { describe, expect, it } from "vitest";
516
+ import { askWithFiles, createLargeFiles, DocumentsNotFoundError, errorKindOf, MemoryDocumentStore, ModelRequestError, partialResultOf } from "llm-large-files";
517
+ import { appLog, bytes, calls, fakeModel, says } from "./fake-model.js";
518
+
519
+ /** Your application's own words for a question that failed: the code under test. */
520
+ function userMessage(error: unknown): string {
521
+ if (error instanceof DocumentsNotFoundError) return "A file is no longer available. Upload it again.";
522
+ switch (errorKindOf(error)) {
523
+ case "rate_limit":
524
+ case "server":
525
+ case "timeout":
526
+ case "unreachable":
527
+ return "The assistant is busy. Try again in a minute.";
528
+ case "context_overflow":
529
+ return "This chat is too long for the model. Start a new one.";
530
+ default:
531
+ return "Something went wrong.";
532
+ }
533
+ }
534
+
535
+ const question = [{ role: "user" as const, text: "How many payments failed?" }];
536
+
537
+ async function largeLog() {
538
+ const files = createLargeFiles({ store: new MemoryDocumentStore(), budget: { inlineTokens: 1_000 } });
539
+ const meta = await files.ingest({ name: "app.log", bytes: bytes(appLog(400)), owner: "alice" });
540
+ const search = { name: "search_document", args: { document_id: meta.id, query: "ERROR", mode: "exact" } };
541
+ return { files, meta, search };
542
+ }
543
+
544
+ describe("a question that fails", () => {
545
+ it("shows a busy message when the model is overloaded", async () => {
546
+ const { files, meta } = await largeLog();
547
+ const model = fakeModel([new ModelRequestError("The model is overloaded.", 503)]);
548
+
549
+ // retries: 0, so the error comes back at once, not after three more tries and their waits.
550
+ const error = await askWithFiles({ files, model, documentIds: [meta.id], owner: "alice", messages: question, retry: { retries: 0 } })
551
+ .catch((caught: unknown) => caught);
552
+
553
+ expect(error).toMatchObject({ status: 503, kind: "server" });
554
+ expect(userMessage(error)).toBe("The assistant is busy. Try again in a minute.");
555
+ });
556
+
557
+ it("is sent again after a busy reply, without waiting in the test", async () => {
558
+ const { files, meta } = await largeLog();
559
+ const model = fakeModel([new ModelRequestError("Too many requests.", 429), says("8 payments failed.")]);
560
+ const waits: number[] = [];
561
+
562
+ const result = await askWithFiles({
563
+ files, model, documentIds: [meta.id], owner: "alice", messages: question,
564
+ // The wait is recorded instead of slept; random: () => 1 takes the jitter out of it.
565
+ retry: { sleep: async (ms) => { waits.push(ms); }, random: () => 1 },
566
+ });
567
+
568
+ expect(result.text).toBe("8 payments failed.");
569
+ expect(model.requests).toHaveLength(2);
570
+ expect(waits).toEqual([500]);
571
+ // A request that failed and was sent again counts once.
572
+ expect(result.usage.requests).toBe(1);
573
+ });
574
+
575
+ it("keeps what was found before the failure", async () => {
576
+ const { files, meta, search } = await largeLog();
577
+ const model = fakeModel([calls([search]), new ModelRequestError("Token expired.", 401)]);
578
+
579
+ const error = await askWithFiles({ files, model, documentIds: [meta.id], owner: "alice", messages: question })
580
+ .catch((caught: unknown) => caught);
581
+
582
+ expect(errorKindOf(error)).toBe("auth");
583
+ expect(model.requests).toHaveLength(2); // a refused token is not sent again
584
+ const partial = partialResultOf(error);
585
+ expect(partial).toMatchObject({ answered: false, steps: ["Search app.log (exact) for “ERROR” — 8 matching lines"] });
586
+ expect(partial!.toolTurns).toHaveLength(1);
587
+ });
588
+
589
+ it("refuses a document of another user before any model request", async () => {
590
+ const { files, meta } = await largeLog();
591
+ const model = fakeModel([says("never sent")]);
592
+
593
+ const error = await askWithFiles({ files, model, documentIds: [meta.id], owner: "bob", messages: question })
594
+ .catch((caught: unknown) => caught);
595
+
596
+ expect(error).toBeInstanceOf(DocumentsNotFoundError);
597
+ expect((error as DocumentsNotFoundError).ids).toEqual([meta.id]);
598
+ expect(userMessage(error)).toBe("A file is no longer available. Upload it again.");
599
+ expect(model.requests).toHaveLength(0);
600
+ });
601
+ });
602
+ ```
603
+
604
+ Notes on these tests:
605
+
606
+ - **Waits.** The loop sends a failed request again after a real wait: up to 500 ms the first
607
+ time, then twice as long each time, with jitter that takes up to half off each wait. With
608
+ `random: () => 1` the waits are exactly 500, 1,000 and 2,000 ms. In tests, pass
609
+ `retry: { retries: 0 }` to get the error at once, or a `sleep` that records the waits and
610
+ returns at once, as above. Both are fields of
611
+ [`RetryOptions`](../reference/errors-and-retries.md#retryoptions).
612
+ - **`partialResultOf(error)`** gives what the question found and used before it failed: its steps,
613
+ evidence, tool rounds and usage, with `answered: false`. Test that your application keeps them.
614
+ Its `usage` is a copy taken when the question failed: a request of a fake that was still running
615
+ then, and answers later, is not counted.
616
+ - **`DocumentsNotFoundError`** comes before any model request, for a document that is missing,
617
+ expired or owned by someone else. Its `ids` are the ones not found.
618
+ - **A request too large** (`context_overflow`) is mended inside the loop when it can be. A fake that
619
+ repeats the error lets you see what your application does when it cannot be mended.
620
+
621
+ ## The real adapters with a fake fetch
622
+
623
+ A fake model tests your code; it does not test that you set up the provider right. For that, run
624
+ the real adapter and fake the network. Every adapter takes a `fetch` option, and sends every request
625
+ through it, the part reads of a whole-file read included:
626
+
627
+ | Adapter | Where `fetch` goes |
628
+ | --- | --- |
629
+ | Gemini API and Vertex AI | `gemini(endpoint, { fetch })`, or `askGemini({ ..., fetch })` |
630
+ | OpenAI-compatible | `openAiCompatible({ ..., fetch })` |
631
+ | Claude | `anthropic({ ..., fetch })` |
632
+
633
+ A fake `fetch` answers from a script, as the fake model does, and records each request with its
634
+ parsed JSON body. Save this as `test/fake-fetch.ts`:
635
+
636
+ ```ts
637
+ // test/fake-fetch.ts: a fetch for the real adapters that answers from a script, without the network.
638
+ type Json = Record<string, any>;
639
+
640
+ /** A request as the adapter sent it. */
641
+ export type Sent = { url: string; headers: Record<string, string>; body: Json };
642
+
643
+ type Reply = Response | ((sent: Sent, call: number) => Response | Promise<Response>);
644
+
645
+ /** Answers each request with the next reply of the script; the last one repeats. Records every request. */
646
+ export function fakeFetch(replies: Reply[]) {
647
+ const sent: Sent[] = [];
648
+ const fetch = async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {
649
+ const request: Sent = {
650
+ url: String(input),
651
+ headers: { ...(init?.headers as Record<string, string>) },
652
+ body: JSON.parse(String(init?.body)) as Json,
653
+ };
654
+ sent.push(request);
655
+ const reply = replies[Math.min(sent.length - 1, replies.length - 1)]!;
656
+ // A body can be read only once: each request gets a copy.
657
+ return typeof reply === "function" ? reply(request, sent.length) : reply.clone();
658
+ };
659
+ return { fetch: fetch as typeof globalThis.fetch, sent };
660
+ }
661
+
662
+ /** A streamed reply: Server-Sent Events, one `data:` line for each event. A string is sent as it is ("[DONE]"). */
663
+ export const sse = (events: unknown[]): Response => new Response(
664
+ events.map((event) => `data: ${typeof event === "string" ? event : JSON.stringify(event)}\n\n`).join(""),
665
+ { headers: { "Content-Type": "text/event-stream" } },
666
+ );
667
+ ```
668
+
669
+ ### Gemini on Vertex AI
670
+
671
+ `vertexAi()` with a fixed `accessToken` string makes no call to get a token, so the test needs no
672
+ credentials. The replies are in Gemini's own JSON:
673
+
674
+ ```ts
675
+ // test/vertex.test.ts
676
+ import { describe, expect, it } from "vitest";
677
+ import { askWithFiles, createLargeFiles, MemoryDocumentStore } from "llm-large-files";
678
+ import { askGemini, gemini, GeminiRequestError, vertexAi } from "llm-large-files/gemini";
679
+ import { appLog, bytes } from "./fake-model.js";
680
+ import { fakeFetch, sse } from "./fake-fetch.js";
681
+
682
+ // Replies as Gemini writes them.
683
+ const geminiText = (text: string) => ({
684
+ candidates: [{ content: { role: "model", parts: [{ text }] }, finishReason: "STOP" }],
685
+ usageMetadata: { promptTokenCount: 1_200, candidatesTokenCount: 20, totalTokenCount: 1_220 },
686
+ });
687
+ const geminiCall = (name: string, args: Record<string, unknown>) => ({
688
+ candidates: [{ content: { role: "model", parts: [{ functionCall: { name, args } }] }, finishReason: "STOP" }],
689
+ usageMetadata: { promptTokenCount: 900, candidatesTokenCount: 15, totalTokenCount: 915 },
690
+ });
691
+
692
+ // A fixed token: vertexAi() calls nothing to get it.
693
+ const endpoint = vertexAi({ project: "test-project", location: "europe-west4", model: "gemini-test", accessToken: "test-token" });
694
+ const question = [{ role: "user" as const, text: "How many payments failed?" }];
695
+
696
+ async function largeLog() {
697
+ const files = createLargeFiles({ store: new MemoryDocumentStore(), budget: { inlineTokens: 1_000 } });
698
+ const meta = await files.ingest({ name: "app.log", bytes: bytes(appLog(400)) });
699
+ return { files, meta };
700
+ }
701
+
702
+ describe("Gemini on Vertex AI, without the network", () => {
703
+ it("sends the token, runs the tool loop and counts the usage", async () => {
704
+ const { files, meta } = await largeLog();
705
+ const api = fakeFetch([
706
+ Response.json(geminiCall("search_document", { document_id: meta.id, query: "ERROR", mode: "exact" })),
707
+ Response.json(geminiText("8 payments failed (app.log L50).")),
708
+ ]);
709
+ const model = gemini(endpoint, { fetch: api.fetch });
710
+
711
+ const result = await askWithFiles({ files, model, documentIds: [meta.id], messages: question });
712
+
713
+ expect(api.sent[0]!.url).toBe("https://europe-west4-aiplatform.googleapis.com/v1/projects/test-project/locations/europe-west4/publishers/google/models/gemini-test:generateContent");
714
+ expect(api.sent[0]!.headers.Authorization).toBe("Bearer test-token");
715
+ expect(api.sent[1]!.body.contents.at(-1).parts[0].functionResponse.response).toMatchObject({ total_matching_lines: 8 });
716
+ expect(result).toMatchObject({ text: "8 payments failed (app.log L50).", answered: true, turns: 2, finishReason: "STOP" });
717
+ expect(result.usage.byModel["gemini-test"]).toMatchObject({ requests: 2, inputTokens: 2_100, outputTokens: 35 });
718
+ });
719
+
720
+ it("streams the answer through askGemini", async () => {
721
+ const files = createLargeFiles({ store: new MemoryDocumentStore() });
722
+ const meta = await files.ingest({ name: "notes.md", bytes: bytes("# Notes\n\nThe code word is heron.") });
723
+ // A streamed Gemini reply ends with a chunk that says why it ended.
724
+ const api = fakeFetch([sse([
725
+ { candidates: [{ content: { role: "model", parts: [{ text: "The code word " }] } }] },
726
+ { candidates: [{ content: { role: "model", parts: [{ text: "is heron." }] }, finishReason: "STOP" }] },
727
+ ])]);
728
+ const deltas: string[] = [];
729
+
730
+ const result = await askGemini({
731
+ files, endpoint, fetch: api.fetch, documentIds: [meta.id],
732
+ messages: [{ role: "user", text: "What is the code word?" }],
733
+ onText: (delta) => deltas.push(delta),
734
+ });
735
+
736
+ expect(api.sent[0]!.url).toMatch(/:streamGenerateContent\?alt=sse$/);
737
+ expect(deltas).toEqual(["The code word ", "is heron."]);
738
+ expect(result.text).toBe("The code word is heron.");
739
+ });
740
+
741
+ it("reports an HTTP error with its kind", async () => {
742
+ const { files, meta } = await largeLog();
743
+ const busy = { error: { code: 429, message: "Resource exhausted. Please try again later.", status: "RESOURCE_EXHAUSTED" } };
744
+ const api = fakeFetch([Response.json(busy, { status: 429 })]);
745
+
746
+ const error = await askGemini({ files, endpoint, fetch: api.fetch, documentIds: [meta.id], messages: question, retry: { retries: 0 } })
747
+ .catch((caught: unknown) => caught);
748
+
749
+ expect(error).toBeInstanceOf(GeminiRequestError);
750
+ expect(error).toMatchObject({ status: 429, kind: "rate_limit", message: "Resource exhausted. Please try again later." });
751
+ });
752
+
753
+ it("reports a model that sends nothing as a timeout", async () => {
754
+ const { files, meta } = await largeLog();
755
+ // A fetch that never answers: it ends only when the adapter aborts it, as the real fetch does.
756
+ const silent = (async (_input: string | URL | Request, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
757
+ init?.signal?.addEventListener("abort", () => reject(init.signal!.reason), { once: true });
758
+ })) as typeof fetch;
759
+ const model = gemini(endpoint, { fetch: silent, firstByteTimeoutMs: 20 });
760
+
761
+ const error = await askWithFiles({ files, model, documentIds: [meta.id], messages: question, retry: { retries: 0 } })
762
+ .catch((caught: unknown) => caught);
763
+
764
+ expect(error).toMatchObject({ status: 0, kind: "timeout" });
765
+ });
766
+ });
767
+ ```
768
+
769
+ A `fetch` that throws (`throw new TypeError("fetch failed")`) is a model that cannot be reached: a
770
+ `GeminiRequestError` with `status` 0, kind `"unreachable"` and the message
771
+ "Gemini could not be reached (fetch failed)." The setup itself is in
772
+ [Gemini and Vertex AI](./vertex-and-gemini.md).
773
+
774
+ ### OpenAI-compatible endpoints and Claude
775
+
776
+ ```ts
777
+ // test/providers.test.ts
778
+ import { describe, expect, it } from "vitest";
779
+ import { askWithFiles, createLargeFiles, MemoryDocumentStore } from "llm-large-files";
780
+ import { openAiCompatible } from "llm-large-files/openai";
781
+ import { anthropic } from "llm-large-files/anthropic";
782
+ import { appLog, bytes } from "./fake-model.js";
783
+ import { fakeFetch, sse } from "./fake-fetch.js";
784
+
785
+ const question = [{ role: "user" as const, text: "How many payments failed?" }];
786
+
787
+ async function largeLog() {
788
+ const files = createLargeFiles({ store: new MemoryDocumentStore(), budget: { inlineTokens: 1_000 } });
789
+ const meta = await files.ingest({ name: "app.log", bytes: bytes(appLog(400)) });
790
+ const args = { document_id: meta.id, query: "ERROR", mode: "exact" };
791
+ return { files, meta, args };
792
+ }
793
+
794
+ describe("other providers, without the network", () => {
795
+ it("runs the loop on an OpenAI-compatible endpoint, and streams its answer", async () => {
796
+ const { files, meta, args } = await largeLog();
797
+ const api = fakeFetch([
798
+ // Asked for a stream, answered in one piece: a reply that is not text/event-stream is read by
799
+ // its first characters, here as JSON.
800
+ Response.json({
801
+ choices: [{ index: 0, finish_reason: "tool_calls", message: { role: "assistant", content: null, tool_calls: [
802
+ { id: "call_1", type: "function", function: { name: "search_document", arguments: JSON.stringify(args) } },
803
+ ] } }],
804
+ usage: { prompt_tokens: 900, completion_tokens: 15 },
805
+ }),
806
+ // A stream ends with a finish_reason, or with [DONE].
807
+ sse([
808
+ { choices: [{ index: 0, delta: { content: "8 payments " } }] },
809
+ { choices: [{ index: 0, delta: { content: "failed." }, finish_reason: "stop" }] },
810
+ { choices: [], usage: { prompt_tokens: 1_300, completion_tokens: 6 } },
811
+ "[DONE]",
812
+ ]),
813
+ ]);
814
+ const model = openAiCompatible({ model: "test-model", baseUrl: "https://llm.test/v1", apiKey: "test-key", fetch: api.fetch });
815
+ const deltas: string[] = [];
816
+
817
+ const result = await askWithFiles({ files, model, documentIds: [meta.id], messages: question, onText: (delta) => deltas.push(delta) });
818
+
819
+ expect(api.sent[0]!.url).toBe("https://llm.test/v1/chat/completions");
820
+ expect(api.sent[0]!.headers.Authorization).toBe("Bearer test-key");
821
+ expect(api.sent[0]!.body.stream).toBe(true);
822
+ expect(deltas).toEqual(["8 payments ", "failed."]);
823
+ expect(result).toMatchObject({ text: "8 payments failed.", answered: true, turns: 2 });
824
+ expect(result.usage).toMatchObject({ requests: 2, inputTokens: 2_200, outputTokens: 21 });
825
+ });
826
+
827
+ it("runs the loop on Claude, and reads its stream of events", async () => {
828
+ const { files, meta, args } = await largeLog();
829
+ const api = fakeFetch([
830
+ Response.json({
831
+ type: "message", role: "assistant", stop_reason: "tool_use",
832
+ content: [{ type: "tool_use", id: "toolu_1", name: "search_document", input: args }],
833
+ usage: { input_tokens: 900, output_tokens: 15 },
834
+ }),
835
+ // A stream ends with a message_delta that carries the stop_reason.
836
+ sse([
837
+ { type: "message_start", message: { usage: { input_tokens: 1_300, output_tokens: 1 } } },
838
+ { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
839
+ { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "8 payments " } },
840
+ { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "failed." } },
841
+ { type: "content_block_stop", index: 0 },
842
+ { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 6 } },
843
+ { type: "message_stop" },
844
+ ]),
845
+ ]);
846
+ const model = anthropic({ model: "claude-test", apiKey: "test-key", fetch: api.fetch });
847
+
848
+ const result = await askWithFiles({ files, model, documentIds: [meta.id], messages: question });
849
+
850
+ expect(api.sent[0]!.url).toBe("https://api.anthropic.com/v1/messages");
851
+ expect(api.sent[0]!.headers["x-api-key"]).toBe("test-key");
852
+ expect(result).toMatchObject({ text: "8 payments failed.", answered: true, turns: 2, finishReason: "end_turn" });
853
+ });
854
+ });
855
+ ```
856
+
857
+ ### What each adapter expects of a fake reply
858
+
859
+ The adapters differ in when they stream and in how they read a reply. A fake reply must match, or
860
+ the adapter takes it for a broken one:
861
+
862
+ | | Gemini (`gemini()`, `askGemini`) | OpenAI-compatible | Claude |
863
+ | --- | --- | --- | --- |
864
+ | A reply in text | `candidates[0].content.parts: [{ text }]` | `choices[0].message.content` | `content: [{ type: "text", text }]` |
865
+ | A tool call | `parts: [{ functionCall: { name, args } }]` | `message.tool_calls`, with `arguments` as a JSON string | `content: [{ type: "tool_use", id, name, input }]` |
866
+ | Usage | `usageMetadata.promptTokenCount`, `candidatesTokenCount` | `usage.prompt_tokens`, `completion_tokens` | `usage.input_tokens`, `output_tokens` |
867
+ | Streams when | `onText` is set and the endpoint has a `streamUrl` (`geminiApi()` and `vertexAi()` set one); the request goes to that URL | `onText` is set and the `stream` option is not `false` | Always, unless the `stream` option is `false` |
868
+ | A streamed request's reply | A stream when the content type is `text/event-stream`. Of any other type, by its first characters: events when it starts with `data:` or a comment, JSON when it starts with `{` or `[` (one chunk, or a list of chunks) | The same: a stream for `text/event-stream`, and by its first characters otherwise | The same |
869
+ | A stream ends with | A chunk with `finishReason` | A chunk with `finish_reason`, or `data: [DONE]` | A `message_delta` event with `stop_reason` |
870
+ | An HTTP error body | `{ error: { code, message, status, details } }` | `{ error: { message, type, code, param } }` | `{ type: "error", error: { type, message } }` |
871
+ | Error class | `GeminiRequestError` | `OpenAiRequestError` | `AnthropicRequestError` |
872
+
873
+ A stream that closes without its end is taken for a reply cut off on its way, with `status` 0:
874
+ "Gemini's reply ended before it was complete.", "The model's reply ended before it was complete."
875
+ (OpenAI-compatible) or "Claude's reply ended before it was complete." The loop then sends the
876
+ request again, unless text of it was shown, and `onActivity` gets "The model's reply was cut off
877
+ on its way. Trying again…". When a fake stream seems to be sent twice, check that it ends as the
878
+ table above says: for Claude, a `message_delta` event with `stop_reason`, not only `message_stop`.
879
+ A stream that said it is whole (`[DONE]`, `message_stop`) and then stays open is read for one more
880
+ second, then left, and its reply is returned.
881
+
882
+ Other fake replies, and what each adapter makes of them:
883
+
884
+ - A body of HTTP 200 that is not JSON, such as `new Response("<html>…", { headers: { "Content-Type": "text/html" } })`:
885
+ a `ModelRequestError` with kind `invalid`, status 200 and the `SyntaxError` as `cause`, not sent
886
+ again. Its message is "Gemini's reply could not be read: it was not JSON (text/html). A proxy or
887
+ gateway may have answered in its place.", or the same with "The model's" or "Claude's". A body
888
+ under another type that starts with more than 65,536 characters of white space is read as JSON,
889
+ whatever follows.
890
+ - An empty body of HTTP 200, `new Response("")`: kind `unreachable`, status 0, "Gemini could not
891
+ be reached (the reply was empty)." (or "The model could not…", "Claude could not…"), sent again
892
+ as a reply cut off on its way.
893
+ - A stream with one event longer than 64,000,000 characters: kind `invalid`, status 200, "The
894
+ model's reply could not be read: an event of its stream held more than 64,000,000 characters.",
895
+ not sent again.
896
+
897
+ All three error classes extend `ModelRequestError`, with the same `status` and `kind`. A
898
+ `Retry-After` header on an error reply is the wait the loop takes before it sends the request
899
+ again; a wait longer than `retry.maxDelayMs` (60,000 ms by default) is not taken, and the error is
900
+ thrown.
901
+
902
+ All three adapters can read a whole file in parts, so `analyze_whole_document` is offered, and its
903
+ part reads go through the same `fetch`. Pass `wholeDocumentAnalysis: false` to `askWithFiles` or
904
+ `askGemini` when a test is not about it. A part read that fails is told to the model by the kind
905
+ and status of its error (`The model was busy (HTTP 429).`), never by the words of the fake's error
906
+ body; a part read whose reply has no text gives `The model returned no text (SAFETY).`, with the
907
+ provider's reason when it is a plain word. The adapters' options are in the reference:
908
+ [gemini](../reference/gemini.md), [openai](../reference/openai.md),
909
+ [anthropic](../reference/anthropic.md).
910
+
911
+ ### Recorded replies
912
+
913
+ Writing a provider's JSON by hand is fine for a few replies. For the real shapes (thought
914
+ signatures, finish reasons, usage), record what a real model sends once, and replay it. Save this as
915
+ `test/record.ts`:
916
+
917
+ ```ts
918
+ // test/record.ts: save the replies of a real model once, and replay them in tests.
919
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
920
+ import { dirname } from "node:path";
921
+
922
+ type Recording = { status: number; contentType: string; body: string };
923
+
924
+ /** A fetch that calls the real one and saves each reply to `${prefix}-1.json`, `${prefix}-2.json`, … */
925
+ export function recordingFetch(prefix: string, real: typeof fetch = fetch): typeof fetch {
926
+ let count = 0;
927
+ return (async (input: string | URL | Request, init?: RequestInit) => {
928
+ const response = await real(input, init);
929
+ const file = `${prefix}-${++count}.json`;
930
+ // Waits for the whole body: a stream is recorded whole, and passed on once it is.
931
+ const recording: Recording = { status: response.status, contentType: response.headers.get("content-type") ?? "", body: await response.clone().text() };
932
+ // An error thrown here would reach the adapter as a failed connection, and the request would be
933
+ // sent again: make the folder first.
934
+ await mkdir(dirname(file), { recursive: true });
935
+ await writeFile(file, JSON.stringify(recording, null, 2));
936
+ return response;
937
+ }) as typeof fetch;
938
+ }
939
+
940
+ /**
941
+ * A recorded reply as a Response for `fakeFetch`. Document IDs are new on every ingest, so the
942
+ * IDs in a recorded tool call are replaced with `documentId`, the one the test ingested.
943
+ */
944
+ export async function replay(file: string, documentId?: string): Promise<Response> {
945
+ const recording = JSON.parse(await readFile(file, "utf8")) as Recording;
946
+ const body = documentId ? recording.body.replace(/doc_[a-f0-9]{32}/g, documentId) : recording.body;
947
+ return new Response(body, { status: recording.status, headers: { "Content-Type": recording.contentType } });
948
+ }
949
+ ```
950
+
951
+ Record in a live run, then replay in the test:
952
+
953
+ ```ts
954
+ import { askWithFiles } from "llm-large-files";
955
+ import { gemini, vertexAi } from "llm-large-files/gemini";
956
+ import { fakeFetch } from "./fake-fetch.js";
957
+ import { recordingFetch, replay } from "./record.js";
958
+
959
+ // Assumes `files` and `meta` (a test document, as in largeLog()), and a real `endpoint`
960
+ // (vertexAi() with your credentials) for the live run.
961
+ const question = [{ role: "user" as const, text: "How many payments failed?" }];
962
+
963
+ // Once, in a live run: the real model, with each reply saved.
964
+ const live = gemini(endpoint, { fetch: recordingFetch("test/recordings/payments") });
965
+ await askWithFiles({ files, model: live, documentIds: [meta.id], messages: question, wholeDocumentAnalysis: false });
966
+
967
+ // In the test: the same replies from the files, with the document ID of this run.
968
+ const api = fakeFetch([
969
+ await replay("test/recordings/payments-1.json", meta.id),
970
+ await replay("test/recordings/payments-2.json", meta.id),
971
+ ]);
972
+ // A fixed token, so the test needs no credentials. Use the live run's model name, so that
973
+ // usage.byModel keeps its key.
974
+ const testEndpoint = vertexAi({ project: "test-project", model: "gemini-3.5-flash-lite", accessToken: "test-token" });
975
+ const model = gemini(testEndpoint, { fetch: api.fetch });
976
+ const result = await askWithFiles({ files, model, documentIds: [meta.id], messages: question, wholeDocumentAnalysis: false });
977
+ ```
978
+
979
+ - Give `fakeFetch` one `replay` for each file the live run wrote (`payments-1.json`,
980
+ `payments-2.json`, …), in order: a request that was sent again is a file too. With fewer, the
981
+ last reply repeats for the rest, and the run differs from the recorded one without an error.
982
+ - Replay with the same options you recorded with. With `onText`, a Gemini request goes to the
983
+ stream URL and needs a recorded stream; with whole-file reads on, their part reads take replies
984
+ of their own, in an order that is not fixed.
985
+ - The replay swaps every document ID in the recording for the one ID given: it suits a test of one
986
+ document.
987
+ - A recording holds what the model wrote, and only the replies: no request, no token. Record with
988
+ test documents, not your users' files.
989
+
990
+ ### Timers
991
+
992
+ With fake timers (`vi.useFakeTimers()`), the library's waits are timers too. A retry waits with
993
+ `setTimeout` unless you pass `retry.sleep`. A real adapter starts a timer of `firstByteTimeoutMs`
994
+ (600,000 ms by default) for each request, and one of `idleTimeoutMs` (300,000 ms) between the pieces
995
+ of a reply: a test that moves the clock that far aborts the request as a model that went silent.
996
+ Pass `firstByteTimeoutMs: 0` and `idleTimeoutMs: 0` to such an adapter, or to `askGemini`: 0 waits
997
+ without end. The waits themselves are in [Errors and reliability](./errors-and-reliability.md).
998
+
999
+ ## Expiry, owners and the clock
1000
+
1001
+ `createLargeFiles` takes a `now` option, a clock for its expiry checks and `sweep`. Give the store
1002
+ the same clock: `MemoryDocumentStore` and `FileDocumentStore` take `now` too, and check expiry by
1003
+ their own clock when they read a document. A library clock set in the past, next to a store on the
1004
+ real clock, loses its documents at the first read: the store finds them expired by its own clock
1005
+ and deletes them.
1006
+
1007
+ ```ts
1008
+ // test/expiry.test.ts
1009
+ import { describe, expect, it } from "vitest";
1010
+ import { askWithFiles, createLargeFiles, DocumentsNotFoundError, MemoryDocumentStore } from "llm-large-files";
1011
+ import { bytes, fakeModel, says } from "./fake-model.js";
1012
+
1013
+ describe("documents that expire", () => {
1014
+ it("are gone after their time to live, and swept from the store", async () => {
1015
+ let clock = new Date("2026-01-01T09:00:00Z");
1016
+ const now = () => clock;
1017
+ // One clock for both: the library checks expiry by its clock, and the store by its own when it reads.
1018
+ const files = createLargeFiles({ store: new MemoryDocumentStore({ now }), now, ttlMs: 60 * 60_000 });
1019
+ const meta = await files.ingest({ name: "notes.md", bytes: bytes("The code word is heron."), owner: "alice" });
1020
+ expect(meta.expiresAt).toBe("2026-01-01T10:00:00.000Z");
1021
+ // Another user cannot delete it.
1022
+ expect(await files.delete(meta.id, { owner: "bob" })).toBe(false);
1023
+
1024
+ clock = new Date("2026-01-01T09:59:00Z");
1025
+ expect(await files.getMeta(meta.id, { owner: "alice" })).toBeDefined();
1026
+
1027
+ clock = new Date("2026-01-01T10:00:00Z");
1028
+ expect(await files.sweep()).toBe(1);
1029
+ const model = fakeModel([says("never sent")]);
1030
+ await expect(askWithFiles({ files, model, documentIds: [meta.id], owner: "alice", messages: [{ role: "user", text: "?" }] }))
1031
+ .rejects.toBeInstanceOf(DocumentsNotFoundError);
1032
+ expect(model.requests).toHaveLength(0);
1033
+ });
1034
+ });
1035
+ ```
1036
+
1037
+ - A document expires at `expiresAt` exactly: at 10:00 it is gone.
1038
+ - `files.sweep()` passes the library's clock to the store's `sweep`, and returns how many documents
1039
+ it removed.
1040
+ - Owners need no clock: ingest with `owner`, then ask with another one, as in
1041
+ [Errors](#errors). The question fails with `DocumentsNotFoundError` before any model request, the
1042
+ same error as for a document that expired.
1043
+ - `files.delete(id, { owner })` returns `false`, and deletes nothing, for a document of another
1044
+ owner; for the document's own owner it returns `true`.
1045
+
1046
+ To test your own `DocumentStore`, run the same tests against it. The contract is in
1047
+ [Storage](./storage.md).
1048
+
1049
+ ## Your routes
1050
+
1051
+ The handlers of `llm-large-files/node` take Node's own request and response, so a test can run them
1052
+ on a real HTTP server, on a free port, and call them with `fetch`. Mount them as your server does;
1053
+ this one routes `POST /api/documents` to `upload`, and `GET` and `DELETE /api/documents/:id` to
1054
+ `get` and `remove`:
1055
+
1056
+ ```ts
1057
+ // test/routes.test.ts
1058
+ import { createServer, type Server } from "node:http";
1059
+ import type { AddressInfo } from "node:net";
1060
+ import { afterEach, describe, expect, it } from "vitest";
1061
+ import { createLargeFiles, MemoryDocumentStore } from "llm-large-files";
1062
+ import { createDocumentHandlers } from "llm-large-files/node";
1063
+
1064
+ let server: Server | undefined;
1065
+ afterEach(() => new Promise<void>((resolve) => (server ? server.close(() => resolve()) : resolve())));
1066
+
1067
+ /** Starts the routes on a free port, and returns their base URL. */
1068
+ async function start(): Promise<string> {
1069
+ const files = createLargeFiles({ store: new MemoryDocumentStore() });
1070
+ // In the test, the user is a header. Your server takes it from its session.
1071
+ const documents = createDocumentHandlers(files, {
1072
+ getOwner: (request) => (request.headers["x-user"] as string | undefined) || undefined,
1073
+ });
1074
+ server = createServer((request, response) => {
1075
+ const url = new URL(request.url ?? "/", "http://localhost");
1076
+ const id = url.pathname.split("/")[3] ?? "";
1077
+ if (request.method === "POST" && url.pathname === "/api/documents") return void documents.upload(request, response);
1078
+ if (request.method === "GET" && id) return void documents.get(request, response, id);
1079
+ if (request.method === "DELETE" && id) return void documents.remove(request, response, id);
1080
+ response.statusCode = 404;
1081
+ response.end();
1082
+ });
1083
+ // Port 0: the system picks a free port, so test files can run side by side.
1084
+ await new Promise<void>((resolve) => server!.listen(0, "127.0.0.1", resolve));
1085
+ return `http://127.0.0.1:${(server!.address() as AddressInfo).port}/api/documents`;
1086
+ }
1087
+
1088
+ describe("the upload routes", () => {
1089
+ it("keeps an upload to its owner", async () => {
1090
+ const base = await start();
1091
+ const upload = await fetch(base, {
1092
+ method: "POST",
1093
+ headers: { "X-File-Name": "notes.md", "X-User": "alice" },
1094
+ body: "# Notes\n\nThe code word is heron.",
1095
+ });
1096
+ expect(upload.status).toBe(201);
1097
+ const { id } = (await upload.json()) as { id: string };
1098
+
1099
+ const asBob = await fetch(`${base}/${id}`, { headers: { "X-User": "bob" } });
1100
+ expect(asBob.status).toBe(404);
1101
+ expect(await asBob.json()).toEqual({ error: "This file is no longer available." });
1102
+ expect((await fetch(`${base}/${id}`, { headers: { "X-User": "alice" } })).status).toBe(200);
1103
+ const deleted = await fetch(`${base}/${id}`, { method: "DELETE", headers: { "X-User": "bob" } });
1104
+ expect(await deleted.json()).toEqual({ deleted: false });
1105
+ });
1106
+ });
1107
+ ```
1108
+
1109
+ The other statuses (400 for a file without a name, 413 for one over `maxUploadBytes`, 422 for one
1110
+ that cannot be read) are in the [`llm-large-files/node` reference](../reference/node.md).
1111
+
1112
+ The `|| undefined` in `getOwner` matters. With it, a header that arrives empty (`"X-User": ""`)
1113
+ makes the upload anonymous: it is answered `201`, and anyone who has its ID can read it. With
1114
+ `?? ""` in its place, the same upload is answered 500
1115
+ `{ "error": "Upload failed (empty owner)." }` before its body is read. Test what your sign-in
1116
+ hands `getOwner` when there is no user, and throw an error with `status: 401` there if every
1117
+ upload needs a user ([A web app](./web-app.md#who-owns-an-upload-getowner)).
1118
+
1119
+ An answer route is tested the same way: give it `fakeModel()` where it would take the real model,
1120
+ and read what it sends back with `fetch`. How such a route streams the answer is in
1121
+ [A web app](./web-app.md).
1122
+
1123
+ ## Live tests, few and cheap
1124
+
1125
+ Fakes test your code. Only a real model tells you whether it picks the right tool and finds the
1126
+ answer in your files, and every run costs money and time and gives a slightly different answer.
1127
+ Keep live tests few:
1128
+
1129
+ - **Out of the default run.** Skip them unless a variable is set, and run them on demand, before a
1130
+ release, or on a schedule.
1131
+ - **Cheap.** One small model, one small document, `wholeDocumentAnalysis: false`, and ceilings in
1132
+ `limits`: once a question has used `inputTokens` input tokens, or is one request short of
1133
+ `requests`, no more tools run and the next request is the answer. See
1134
+ [Costs and limits](./costs-and-limits.md).
1135
+ - **Loose.** Check that there is an answer and that it holds the fact, not its wording.
1136
+ - **Measured.** Log `result.usage`, so you see what a run costs.
1137
+ - **Useful twice.** Record the replies of a run that went well, and replay them in a fast test
1138
+ ([Recorded replies](#recorded-replies)).
1139
+
1140
+ ```ts
1141
+ // test/vertex.live.test.ts
1142
+ import { describe, expect, it } from "vitest";
1143
+ import { GoogleAuth } from "google-auth-library";
1144
+ import { askWithFiles, createLargeFiles, MemoryDocumentStore } from "llm-large-files";
1145
+ import { gemini, vertexAi } from "llm-large-files/gemini";
1146
+ import { appLog, bytes } from "./fake-model.js";
1147
+
1148
+ // Skipped unless LIVE_TESTS=1 is set: the default test run never calls a model.
1149
+ describe.skipIf(process.env.LIVE_TESTS !== "1")("live: Gemini on Vertex AI", () => {
1150
+ it("finds the failed payments in a log", async () => {
1151
+ const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
1152
+ const model = gemini(vertexAi({
1153
+ project: process.env.GOOGLE_CLOUD_PROJECT!,
1154
+ location: "global",
1155
+ model: process.env.LIVE_MODEL ?? "gemini-3.5-flash-lite",
1156
+ accessToken: async () => {
1157
+ const token = await auth.getAccessToken();
1158
+ if (!token) throw new Error("No access token from the application default credentials.");
1159
+ return token;
1160
+ },
1161
+ }));
1162
+ const files = createLargeFiles({ store: new MemoryDocumentStore(), budget: { inlineTokens: 1_000 } });
1163
+ const meta = await files.ingest({ name: "app.log", bytes: bytes(appLog(400)) });
1164
+
1165
+ const result = await askWithFiles({
1166
+ files, model, documentIds: [meta.id],
1167
+ messages: [{ role: "user", text: "How many payments failed? Answer with the number." }],
1168
+ wholeDocumentAnalysis: false,
1169
+ // Ceilings: a model that keeps calling tools cannot run up a bill.
1170
+ limits: { toolTurns: 4, requests: 5, inputTokens: 50_000 },
1171
+ });
1172
+
1173
+ // Loose checks: a real model words its answer its own way.
1174
+ expect(result.answered).toBe(true);
1175
+ expect(result.text).toMatch(/\b8\b/);
1176
+ expect(result.steps.length).toBeGreaterThan(0);
1177
+ console.log("live usage", result.usage);
1178
+ }, 120_000);
1179
+ });
1180
+ ```
1181
+
1182
+ The credentials are the application default credentials, as on your servers: see
1183
+ [Gemini and Vertex AI](./vertex-and-gemini.md). For another provider, swap the adapter:
1184
+ [OpenAI-compatible endpoints](./openai-compatible.md), [Claude](./anthropic.md).
1185
+
1186
+ ## Reference
1187
+
1188
+ - [`ModelAdapter`](../reference/ask.md#modeladapter), [`ModelRequest`](../reference/ask.md#modelrequest),
1189
+ [`AskResult`](../reference/ask.md#askresult), [`AskLimits`](../reference/ask.md#asklimits) and
1190
+ `partialResultOf`: [the tool loop and the adapter contract](../reference/ask.md).
1191
+ - [`ModelRequestError`](../reference/errors-and-retries.md#modelrequesterror),
1192
+ [`RetryOptions`](../reference/errors-and-retries.md#retryoptions) and `errorKindOf`:
1193
+ [errors, retries, streams](../reference/errors-and-retries.md).
1194
+ - [`MemoryDocumentStore`](../reference/library.md#memorydocumentstore) and the `now` option of
1195
+ [`LargeFilesOptions`](../reference/library.md#largefilesoptions):
1196
+ [the library and its documents](../reference/library.md).
1197
+ - The tools a script can call, with their arguments and results: [tools](../reference/tools.md).
1198
+ - The upload routes, their requests and statuses: [`llm-large-files/node`](../reference/node.md).
1199
+ - Streaming answers to a browser: [A web app](./web-app.md).