llm-large-files 0.8.2 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (288) hide show
  1. package/CHANGELOG.md +981 -0
  2. package/README.md +22 -17
  3. package/dist/access.d.ts +128 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +234 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/aggregate.d.ts +6 -0
  8. package/dist/aggregate.d.ts.map +1 -1
  9. package/dist/aggregate.js +86 -13
  10. package/dist/aggregate.js.map +1 -1
  11. package/dist/analyze.d.ts +4 -0
  12. package/dist/analyze.d.ts.map +1 -1
  13. package/dist/analyze.js +2 -2
  14. package/dist/analyze.js.map +1 -1
  15. package/dist/answer-info.d.ts +26 -0
  16. package/dist/answer-info.d.ts.map +1 -0
  17. package/dist/answer-info.js +32 -0
  18. package/dist/answer-info.js.map +1 -0
  19. package/dist/anthropic/adapter.d.ts +5 -1
  20. package/dist/anthropic/adapter.d.ts.map +1 -1
  21. package/dist/anthropic/adapter.js +35 -10
  22. package/dist/anthropic/adapter.js.map +1 -1
  23. package/dist/ask.d.ts +159 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +743 -113
  26. package/dist/ask.js.map +1 -1
  27. package/dist/cache.d.ts +12 -3
  28. package/dist/cache.d.ts.map +1 -1
  29. package/dist/cache.js +18 -5
  30. package/dist/cache.js.map +1 -1
  31. package/dist/citations.d.ts +36 -0
  32. package/dist/citations.d.ts.map +1 -0
  33. package/dist/citations.js +291 -0
  34. package/dist/citations.js.map +1 -0
  35. package/dist/encoding.js +5 -3
  36. package/dist/encoding.js.map +1 -1
  37. package/dist/error-info.d.ts +70 -0
  38. package/dist/error-info.d.ts.map +1 -0
  39. package/dist/error-info.js +253 -0
  40. package/dist/error-info.js.map +1 -0
  41. package/dist/errors.d.ts +74 -8
  42. package/dist/errors.d.ts.map +1 -1
  43. package/dist/errors.js +104 -15
  44. package/dist/errors.js.map +1 -1
  45. package/dist/events.d.ts +57 -13
  46. package/dist/events.d.ts.map +1 -1
  47. package/dist/events.js +42 -11
  48. package/dist/events.js.map +1 -1
  49. package/dist/evidence.d.ts +4 -2
  50. package/dist/evidence.d.ts.map +1 -1
  51. package/dist/evidence.js +35 -5
  52. package/dist/evidence.js.map +1 -1
  53. package/dist/extract.d.ts +32 -8
  54. package/dist/extract.d.ts.map +1 -1
  55. package/dist/extract.js +52 -36
  56. package/dist/extract.js.map +1 -1
  57. package/dist/gemini/adapter.d.ts +54 -7
  58. package/dist/gemini/adapter.d.ts.map +1 -1
  59. package/dist/gemini/adapter.js +152 -41
  60. package/dist/gemini/adapter.js.map +1 -1
  61. package/dist/gemini/chat.d.ts +38 -53
  62. package/dist/gemini/chat.d.ts.map +1 -1
  63. package/dist/gemini/chat.js +20 -25
  64. package/dist/gemini/chat.js.map +1 -1
  65. package/dist/gemini/endpoints.d.ts +59 -11
  66. package/dist/gemini/endpoints.d.ts.map +1 -1
  67. package/dist/gemini/endpoints.js +33 -7
  68. package/dist/gemini/endpoints.js.map +1 -1
  69. package/dist/gemini/errors.d.ts +39 -5
  70. package/dist/gemini/errors.d.ts.map +1 -1
  71. package/dist/gemini/errors.js +70 -9
  72. package/dist/gemini/errors.js.map +1 -1
  73. package/dist/gemini/generate.d.ts +53 -2
  74. package/dist/gemini/generate.d.ts.map +1 -1
  75. package/dist/gemini/generate.js +100 -50
  76. package/dist/gemini/generate.js.map +1 -1
  77. package/dist/gemini/index.d.ts +4 -4
  78. package/dist/gemini/index.d.ts.map +1 -1
  79. package/dist/http.d.ts +41 -3
  80. package/dist/http.d.ts.map +1 -1
  81. package/dist/http.js +40 -2
  82. package/dist/http.js.map +1 -1
  83. package/dist/index.d.ts +13 -8
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +8 -5
  86. package/dist/index.js.map +1 -1
  87. package/dist/ingest.d.ts +78 -0
  88. package/dist/ingest.d.ts.map +1 -0
  89. package/dist/ingest.js +893 -0
  90. package/dist/ingest.js.map +1 -0
  91. package/dist/library.d.ts +295 -33
  92. package/dist/library.d.ts.map +1 -1
  93. package/dist/library.js +458 -650
  94. package/dist/library.js.map +1 -1
  95. package/dist/map-reduce.d.ts +176 -10
  96. package/dist/map-reduce.d.ts.map +1 -1
  97. package/dist/map-reduce.js +807 -61
  98. package/dist/map-reduce.js.map +1 -1
  99. package/dist/model.d.ts +79 -6
  100. package/dist/model.d.ts.map +1 -1
  101. package/dist/model.js +80 -4
  102. package/dist/model.js.map +1 -1
  103. package/dist/node/handlers.d.ts +247 -14
  104. package/dist/node/handlers.d.ts.map +1 -1
  105. package/dist/node/handlers.js +491 -227
  106. package/dist/node/handlers.js.map +1 -1
  107. package/dist/node/index.d.ts +3 -2
  108. package/dist/node/index.d.ts.map +1 -1
  109. package/dist/node/index.js +2 -1
  110. package/dist/node/index.js.map +1 -1
  111. package/dist/node/ingest-child.d.ts +7 -1
  112. package/dist/node/ingest-child.d.ts.map +1 -1
  113. package/dist/node/ingest-child.js +19 -4
  114. package/dist/node/ingest-child.js.map +1 -1
  115. package/dist/node/isolated.d.ts +3 -1
  116. package/dist/node/isolated.d.ts.map +1 -1
  117. package/dist/node/isolated.js +11 -4
  118. package/dist/node/isolated.js.map +1 -1
  119. package/dist/node/originals.d.ts +19 -0
  120. package/dist/node/originals.d.ts.map +1 -0
  121. package/dist/node/originals.js +82 -0
  122. package/dist/node/originals.js.map +1 -0
  123. package/dist/node/spool.d.ts +106 -0
  124. package/dist/node/spool.d.ts.map +1 -0
  125. package/dist/node/spool.js +378 -0
  126. package/dist/node/spool.js.map +1 -0
  127. package/dist/node/sse.d.ts +6 -4
  128. package/dist/node/sse.d.ts.map +1 -1
  129. package/dist/node/sse.js +9 -7
  130. package/dist/node/sse.js.map +1 -1
  131. package/dist/openai/adapter.d.ts +5 -1
  132. package/dist/openai/adapter.d.ts.map +1 -1
  133. package/dist/openai/adapter.js +53 -12
  134. package/dist/openai/adapter.js.map +1 -1
  135. package/dist/output-limit.d.ts +2 -1
  136. package/dist/output-limit.d.ts.map +1 -1
  137. package/dist/output-limit.js +5 -2
  138. package/dist/output-limit.js.map +1 -1
  139. package/dist/pdf-layout.d.ts.map +1 -1
  140. package/dist/pdf-layout.js +71 -12
  141. package/dist/pdf-layout.js.map +1 -1
  142. package/dist/pdf-outline.d.ts +71 -0
  143. package/dist/pdf-outline.d.ts.map +1 -0
  144. package/dist/pdf-outline.js +414 -0
  145. package/dist/pdf-outline.js.map +1 -0
  146. package/dist/plan.d.ts +137 -7
  147. package/dist/plan.d.ts.map +1 -1
  148. package/dist/plan.js +248 -26
  149. package/dist/plan.js.map +1 -1
  150. package/dist/prepare.d.ts +50 -0
  151. package/dist/prepare.d.ts.map +1 -0
  152. package/dist/prepare.js +207 -0
  153. package/dist/prepare.js.map +1 -0
  154. package/dist/ranged.d.ts +16 -11
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +56 -12
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +3 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +6 -2
  161. package/dist/retry.js.map +1 -1
  162. package/dist/scope.d.ts +25 -0
  163. package/dist/scope.d.ts.map +1 -0
  164. package/dist/scope.js +60 -0
  165. package/dist/scope.js.map +1 -0
  166. package/dist/search.d.ts +7 -0
  167. package/dist/search.d.ts.map +1 -1
  168. package/dist/search.js +72 -10
  169. package/dist/search.js.map +1 -1
  170. package/dist/source.d.ts +60 -0
  171. package/dist/source.d.ts.map +1 -0
  172. package/dist/source.js +170 -0
  173. package/dist/source.js.map +1 -0
  174. package/dist/stores.d.ts +126 -31
  175. package/dist/stores.d.ts.map +1 -1
  176. package/dist/stores.js +655 -141
  177. package/dist/stores.js.map +1 -1
  178. package/dist/testing/fake-fetch.d.ts +31 -0
  179. package/dist/testing/fake-fetch.d.ts.map +1 -0
  180. package/dist/testing/fake-fetch.js +66 -0
  181. package/dist/testing/fake-fetch.js.map +1 -0
  182. package/dist/testing/fake-model.d.ts +38 -0
  183. package/dist/testing/fake-model.d.ts.map +1 -0
  184. package/dist/testing/fake-model.js +62 -0
  185. package/dist/testing/fake-model.js.map +1 -0
  186. package/dist/testing/index.d.ts +7 -0
  187. package/dist/testing/index.d.ts.map +1 -0
  188. package/dist/testing/index.js +9 -0
  189. package/dist/testing/index.js.map +1 -0
  190. package/dist/testing/store-checks.d.ts +72 -0
  191. package/dist/testing/store-checks.d.ts.map +1 -0
  192. package/dist/testing/store-checks.js +619 -0
  193. package/dist/testing/store-checks.js.map +1 -0
  194. package/dist/tools.d.ts +47 -2
  195. package/dist/tools.d.ts.map +1 -1
  196. package/dist/tools.js +440 -71
  197. package/dist/tools.js.map +1 -1
  198. package/dist/types.d.ts +165 -14
  199. package/dist/types.d.ts.map +1 -1
  200. package/dist/whole-cost.d.ts +37 -0
  201. package/dist/whole-cost.d.ts.map +1 -0
  202. package/dist/whole-cost.js +46 -0
  203. package/dist/whole-cost.js.map +1 -0
  204. package/docs/README.md +21 -8
  205. package/docs/getting-started.md +18 -13
  206. package/docs/guides/anthropic.md +17 -10
  207. package/docs/guides/conversations.md +112 -47
  208. package/docs/guides/costs-and-limits.md +147 -42
  209. package/docs/guides/deployment.md +380 -86
  210. package/docs/guides/errors-and-reliability.md +317 -67
  211. package/docs/guides/explorer-model.md +4 -1
  212. package/docs/guides/openai-compatible.md +47 -7
  213. package/docs/guides/own-adapter-and-loop.md +60 -16
  214. package/docs/guides/pdfs.md +219 -36
  215. package/docs/guides/storage.md +676 -145
  216. package/docs/guides/testing.md +149 -129
  217. package/docs/guides/vertex-and-gemini.md +169 -57
  218. package/docs/guides/web-app.md +318 -80
  219. package/docs/how-it-works.md +155 -30
  220. package/docs/measurements.md +215 -13
  221. package/docs/publishing.md +185 -37
  222. package/docs/reference/anthropic.md +12 -7
  223. package/docs/reference/ask.md +415 -47
  224. package/docs/reference/errors-and-retries.md +194 -14
  225. package/docs/reference/events.md +77 -27
  226. package/docs/reference/gemini.md +252 -87
  227. package/docs/reference/library.md +886 -178
  228. package/docs/reference/node.md +659 -111
  229. package/docs/reference/openai.md +21 -10
  230. package/docs/reference/testing.md +311 -0
  231. package/docs/reference/tools.md +285 -30
  232. package/docs/security.md +404 -78
  233. package/docs/troubleshooting.md +151 -70
  234. package/docs/upgrading-0.10.md +472 -0
  235. package/docs/upgrading-0.9.md +890 -0
  236. package/package.json +16 -3
  237. package/src/access.ts +267 -0
  238. package/src/aggregate.ts +92 -14
  239. package/src/analyze.ts +2 -2
  240. package/src/answer-info.ts +45 -0
  241. package/src/anthropic/adapter.ts +40 -11
  242. package/src/ask.ts +866 -115
  243. package/src/cache.ts +20 -5
  244. package/src/citations.ts +294 -0
  245. package/src/encoding.ts +6 -4
  246. package/src/error-info.ts +290 -0
  247. package/src/errors.ts +131 -15
  248. package/src/events.ts +112 -24
  249. package/src/evidence.ts +35 -5
  250. package/src/extract.ts +56 -34
  251. package/src/gemini/adapter.ts +196 -43
  252. package/src/gemini/chat.ts +63 -78
  253. package/src/gemini/endpoints.ts +89 -16
  254. package/src/gemini/errors.ts +74 -11
  255. package/src/gemini/generate.ts +147 -57
  256. package/src/gemini/index.ts +4 -4
  257. package/src/http.ts +65 -4
  258. package/src/index.ts +13 -8
  259. package/src/ingest.ts +958 -0
  260. package/src/library.ts +711 -651
  261. package/src/map-reduce.ts +858 -70
  262. package/src/model.ts +113 -9
  263. package/src/node/handlers.ts +709 -221
  264. package/src/node/index.ts +14 -2
  265. package/src/node/ingest-child.ts +24 -6
  266. package/src/node/isolated.ts +11 -4
  267. package/src/node/originals.ts +78 -0
  268. package/src/node/spool.ts +379 -0
  269. package/src/node/sse.ts +9 -7
  270. package/src/openai/adapter.ts +56 -13
  271. package/src/output-limit.ts +5 -2
  272. package/src/pdf-layout.ts +69 -11
  273. package/src/pdf-outline.ts +400 -0
  274. package/src/plan.ts +287 -36
  275. package/src/prepare.ts +253 -0
  276. package/src/ranged.ts +48 -14
  277. package/src/retry.ts +6 -2
  278. package/src/scope.ts +63 -0
  279. package/src/search.ts +69 -13
  280. package/src/source.ts +178 -0
  281. package/src/stores.ts +702 -142
  282. package/src/testing/fake-fetch.ts +80 -0
  283. package/src/testing/fake-model.ts +78 -0
  284. package/src/testing/index.ts +11 -0
  285. package/src/testing/store-checks.ts +660 -0
  286. package/src/tools.ts +461 -73
  287. package/src/types.ts +151 -14
  288. package/src/whole-cost.ts +64 -0
@@ -2,8 +2,8 @@
2
2
 
3
3
  This guide shows how to test code that uses llm-large-files without calling a real model: tests
4
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.
5
+ developers. The samples use [Vitest](https://vitest.dev); the fakes they import from
6
+ [`llm-large-files/testing`](../reference/testing.md) do not depend on it.
7
7
 
8
8
  ## What to fake
9
9
 
@@ -16,10 +16,10 @@ Fake the layer below the code you test, and nothing above it.
16
16
  | Expiry, owners, deleting | The clock: `now`, with `MemoryDocumentStore` | [Expiry, owners and the clock](#expiry-owners-and-the-clock) |
17
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
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
+ | A `DocumentStore` of your own | Nothing: `documentStoreChecks` runs the store against the contract | [Checking your store](./storage.md#checking-your-store) |
19
20
 
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.
21
+ The library's own tests work the same way, with the same fakes. Since 0.9.0 they ship in the
22
+ package as `llm-large-files/testing`: import them instead of copying them.
23
23
 
24
24
  ## Test documents
25
25
 
@@ -36,73 +36,12 @@ becomes a card that the model reaches through the tools, as a 50 MB log would. S
36
36
  `createLargeFiles`, or for one question with `budget` in `askWithFiles`. How the plan is made is in
37
37
  [How it works](../how-it-works.md).
38
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`:
39
+ The samples encode text with `utf8()` from `llm-large-files/testing`, and use `appLog(count)`, a
40
+ log of `count` lines with a failed payment on every 50th, from the file below. From 19 lines on it
41
+ is over 1,000 estimated tokens. The samples use 400 lines, which hold 8 failed payments.
48
42
 
49
43
  ```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
-
44
+ // test/documents.ts: test documents for code that calls askWithFiles.
106
45
  /** A service log of `count` lines, with a failed payment on every 50th line. */
107
46
  export function appLog(count: number): string {
108
47
  const lines: string[] = [];
@@ -116,6 +55,26 @@ export function appLog(count: number): string {
116
55
  }
117
56
  ```
118
57
 
58
+ `serviceLog(lines)` from `llm-large-files/testing` is another: a log with an `ERROR` line every 97
59
+ lines, the one the library's own tests use.
60
+
61
+ ## A scripted model
62
+
63
+ `askWithFiles` talks to a model only through a [`ModelAdapter`](../reference/ask.md#modeladapter):
64
+ an object with an `id`, its `capabilities` and a `send` method. `fakeModel` is one that answers
65
+ each request from a script and records what it was sent:
66
+
67
+ ```ts
68
+ import { calls, fakeModel, says } from "llm-large-files/testing";
69
+
70
+ // Assumes `meta`, a log ingested as in the tests below.
71
+ const model = fakeModel([
72
+ calls([{ name: "search_document", args: { document_id: meta.id, query: "ERROR", mode: "exact" } }]),
73
+ says("8 payments failed."),
74
+ ]);
75
+ // After the question, model.requests holds each request the loop sent, in order.
76
+ ```
77
+
119
78
  What the parts do:
120
79
 
121
80
  - **The script.** One entry for each request, in order. The last entry repeats, so a model that
@@ -129,13 +88,19 @@ What the parts do:
129
88
  `text` event, once the reply is in.
130
89
  - **The options.** `id` names the model in `usage.byModel`; give two fakes different ones. A
131
90
  `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).
91
+ that tool is not offered. The capabilities make the fake look like a given model. Unless you
92
+ say otherwise they are `toolFiles: "inside"`, as Gemini's, so the loop offers `view_pages` for
93
+ PDFs whose original is kept (see [PDFs](./pdfs.md)), and `pageTokens: 500`. `toolFiles: "none"`
94
+ makes a model that takes no files, `contextTokens` and `maxRequestBytes` make the budget of a
95
+ question fit a model, and `appendOnly: true` makes the loop treat it as Claude (a conversation
96
+ that may only grow).
97
+ - **The replies.** `says(text, more?)` is a reply of text, and `calls(list, more?)` a reply that
98
+ calls tools. `more` adds fields, such as `usage`. The `raw` of a `calls` reply is
99
+ `{ own: [the tool names] }`, a stand-in for the provider's own form of the turn.
100
+
101
+ Every export, with its defaults, is in the [reference](../reference/testing.md). The source of
102
+ `fakeModel` is in the package, in `src/testing/fake-model.ts`. A fake adapter is also the starting
103
+ point for one of your own: see [Your own adapter and loop](./own-adapter-and-loop.md).
139
104
 
140
105
  ## A first test
141
106
 
@@ -145,14 +110,15 @@ Two tests: a short document that goes in whole, and a log that the model must se
145
110
  // test/ask.test.ts
146
111
  import { describe, expect, it } from "vitest";
147
112
  import { askWithFiles, createLargeFiles, MemoryDocumentStore } from "llm-large-files";
148
- import { appLog, bytes, calls, fakeModel, says } from "./fake-model.js";
113
+ import { calls, fakeModel, says, utf8 } from "llm-large-files/testing";
114
+ import { appLog } from "./documents.js";
149
115
 
150
116
  const question = (text: string) => [{ role: "user" as const, text }];
151
117
 
152
118
  describe("questions about documents", () => {
153
119
  it("sends a short document whole, in one request without tools", async () => {
154
120
  const files = createLargeFiles({ store: new MemoryDocumentStore() });
155
- const meta = await files.ingest({ name: "notes.md", bytes: bytes("# Notes\n\nThe code word is heron.") });
121
+ const meta = await files.ingest({ name: "notes.md", bytes: utf8("# Notes\n\nThe code word is heron.") });
156
122
  const model = fakeModel([says("Heron.", { usage: { inputTokens: 40, outputTokens: 3 } })]);
157
123
 
158
124
  const result = await askWithFiles({ files, model, documentIds: [meta.id], messages: question("What is the code word?") });
@@ -167,7 +133,7 @@ describe("questions about documents", () => {
167
133
  // Any document over about 1,000 tokens becomes a card with tools: a small test file takes
168
134
  // the path that a real 50 MB log takes.
169
135
  const files = createLargeFiles({ store: new MemoryDocumentStore(), budget: { inlineTokens: 1_000 } });
170
- const meta = await files.ingest({ name: "app.log", bytes: bytes(appLog(400)) });
136
+ const meta = await files.ingest({ name: "app.log", bytes: utf8(appLog(400)) });
171
137
  const search = { id: "call_1", name: "search_document", args: { document_id: meta.id, query: "ERROR", mode: "exact" } };
172
138
  const model = fakeModel([calls([search]), says("8 payments failed, the first on line 50 (app.log L50).")]);
173
139
 
@@ -213,13 +179,14 @@ text, a blocked prompt and an explorer model:
213
179
  // test/loop.test.ts
214
180
  import { describe, expect, it } from "vitest";
215
181
  import { askWithFiles, createLargeFiles, MemoryDocumentStore } from "llm-large-files";
216
- import { appLog, bytes, calls, fakeModel, says } from "./fake-model.js";
182
+ import { calls, fakeModel, says, utf8 } from "llm-large-files/testing";
183
+ import { appLog } from "./documents.js";
217
184
 
218
185
  const question = (text: string) => [{ role: "user" as const, text }];
219
186
 
220
187
  async function largeLog() {
221
188
  const files = createLargeFiles({ store: new MemoryDocumentStore(), budget: { inlineTokens: 1_000 } });
222
- const meta = await files.ingest({ name: "app.log", bytes: bytes(appLog(400)) });
189
+ const meta = await files.ingest({ name: "app.log", bytes: utf8(appLog(400)) });
223
190
  return { files, meta };
224
191
  }
225
192
 
@@ -353,11 +320,12 @@ the wording of a label or a notice is the library's.
353
320
  // test/events.test.ts
354
321
  import { expect, it } from "vitest";
355
322
  import { askStream, createLargeFiles, MemoryDocumentStore, type AskEvent } from "llm-large-files";
356
- import { appLog, bytes, calls, fakeModel, says } from "./fake-model.js";
323
+ import { calls, fakeModel, says, utf8 } from "llm-large-files/testing";
324
+ import { appLog } from "./documents.js";
357
325
 
358
326
  it("shows the search, then the answer, in order", async () => {
359
327
  const files = createLargeFiles({ store: new MemoryDocumentStore(), budget: { inlineTokens: 1_000 } });
360
- const meta = await files.ingest({ name: "app.log", bytes: bytes(appLog(400)) });
328
+ const meta = await files.ingest({ name: "app.log", bytes: utf8(appLog(400)) });
361
329
  const search = { id: "s1", name: "search_document", args: { document_id: meta.id, query: "ERROR", mode: "exact" } };
362
330
  const model = fakeModel([calls([search]), says("8 payments failed.")]);
363
331
 
@@ -518,7 +486,8 @@ means for a user is in [Errors and reliability](./errors-and-reliability.md).
518
486
  // test/errors.test.ts
519
487
  import { describe, expect, it } from "vitest";
520
488
  import { askWithFiles, createLargeFiles, DocumentsNotFoundError, errorKindOf, MemoryDocumentStore, ModelRequestError, partialResultOf } from "llm-large-files";
521
- import { appLog, bytes, calls, fakeModel, says } from "./fake-model.js";
489
+ import { calls, fakeModel, says, utf8 } from "llm-large-files/testing";
490
+ import { appLog } from "./documents.js";
522
491
 
523
492
  /** Your application's own words for a question that failed: the code under test. */
524
493
  function userMessage(error: unknown): string {
@@ -540,7 +509,7 @@ const question = [{ role: "user" as const, text: "How many payments failed?" }];
540
509
 
541
510
  async function largeLog() {
542
511
  const files = createLargeFiles({ store: new MemoryDocumentStore(), budget: { inlineTokens: 1_000 } });
543
- const meta = await files.ingest({ name: "app.log", bytes: bytes(appLog(400)), owner: "alice" });
512
+ const meta = await files.ingest({ name: "app.log", bytes: utf8(appLog(400)), owner: "alice" });
544
513
  const search = { name: "search_document", args: { document_id: meta.id, query: "ERROR", mode: "exact" } };
545
514
  return { files, meta, search };
546
515
  }
@@ -634,40 +603,17 @@ through it, the part reads of a whole-file read included:
634
603
  | OpenAI-compatible | `openAiCompatible({ ..., fetch })` |
635
604
  | Claude | `anthropic({ ..., fetch })` |
636
605
 
637
- A fake `fetch` answers from a script, as the fake model does, and records each request with its
638
- parsed JSON body. Save this as `test/fake-fetch.ts`:
606
+ `fakeFetch` from `llm-large-files/testing` answers from a script, as the fake model does. Each
607
+ request gets the next reply, and the last one repeats. A reply is a `Response`, answered with a
608
+ copy each time, or a function of the request and its number. `sent` records every request: its
609
+ `url`, `method` and `headers`, and its `body` parsed as JSON. `sse(events)` makes a streamed reply:
610
+ one `data:` line for each event, an object as JSON, a string such as `"[DONE]"` as it is.
639
611
 
640
612
  ```ts
641
- // test/fake-fetch.ts: a fetch for the real adapters that answers from a script, without the network.
642
- type Json = Record<string, any>;
643
-
644
- /** A request as the adapter sent it. */
645
- export type Sent = { url: string; headers: Record<string, string>; body: Json };
646
-
647
- type Reply = Response | ((sent: Sent, call: number) => Response | Promise<Response>);
648
-
649
- /** Answers each request with the next reply of the script; the last one repeats. Records every request. */
650
- export function fakeFetch(replies: Reply[]) {
651
- const sent: Sent[] = [];
652
- const fetch = async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {
653
- const request: Sent = {
654
- url: String(input),
655
- headers: { ...(init?.headers as Record<string, string>) },
656
- body: JSON.parse(String(init?.body)) as Json,
657
- };
658
- sent.push(request);
659
- const reply = replies[Math.min(sent.length - 1, replies.length - 1)]!;
660
- // A body can be read only once: each request gets a copy.
661
- return typeof reply === "function" ? reply(request, sent.length) : reply.clone();
662
- };
663
- return { fetch: fetch as typeof globalThis.fetch, sent };
664
- }
613
+ import { fakeFetch } from "llm-large-files/testing";
665
614
 
666
- /** A streamed reply: Server-Sent Events, one `data:` line for each event. A string is sent as it is ("[DONE]"). */
667
- export const sse = (events: unknown[]): Response => new Response(
668
- events.map((event) => `data: ${typeof event === "string" ? event : JSON.stringify(event)}\n\n`).join(""),
669
- { headers: { "Content-Type": "text/event-stream" } },
670
- );
615
+ const api = fakeFetch([Response.json({ candidates: [] })]);
616
+ // Give api.fetch to the adapter; after the question, api.sent holds each request it made.
671
617
  ```
672
618
 
673
619
  ### Gemini on Vertex AI
@@ -680,8 +626,8 @@ credentials. The replies are in Gemini's own JSON:
680
626
  import { describe, expect, it } from "vitest";
681
627
  import { askWithFiles, createLargeFiles, MemoryDocumentStore } from "llm-large-files";
682
628
  import { askGemini, gemini, GeminiRequestError, vertexAi } from "llm-large-files/gemini";
683
- import { appLog, bytes } from "./fake-model.js";
684
- import { fakeFetch, sse } from "./fake-fetch.js";
629
+ import { fakeFetch, sse, utf8 } from "llm-large-files/testing";
630
+ import { appLog } from "./documents.js";
685
631
 
686
632
  // Replies as Gemini writes them.
687
633
  const geminiText = (text: string) => ({
@@ -699,7 +645,7 @@ const question = [{ role: "user" as const, text: "How many payments failed?" }];
699
645
 
700
646
  async function largeLog() {
701
647
  const files = createLargeFiles({ store: new MemoryDocumentStore(), budget: { inlineTokens: 1_000 } });
702
- const meta = await files.ingest({ name: "app.log", bytes: bytes(appLog(400)) });
648
+ const meta = await files.ingest({ name: "app.log", bytes: utf8(appLog(400)) });
703
649
  return { files, meta };
704
650
  }
705
651
 
@@ -723,7 +669,7 @@ describe("Gemini on Vertex AI, without the network", () => {
723
669
 
724
670
  it("streams the answer through askGemini", async () => {
725
671
  const files = createLargeFiles({ store: new MemoryDocumentStore() });
726
- const meta = await files.ingest({ name: "notes.md", bytes: bytes("# Notes\n\nThe code word is heron.") });
672
+ const meta = await files.ingest({ name: "notes.md", bytes: utf8("# Notes\n\nThe code word is heron.") });
727
673
  // A streamed Gemini reply ends with a chunk that says why it ended.
728
674
  const api = fakeFetch([sse([
729
675
  { candidates: [{ content: { role: "model", parts: [{ text: "The code word " }] } }] },
@@ -783,14 +729,14 @@ import { describe, expect, it } from "vitest";
783
729
  import { askWithFiles, createLargeFiles, MemoryDocumentStore } from "llm-large-files";
784
730
  import { openAiCompatible } from "llm-large-files/openai";
785
731
  import { anthropic } from "llm-large-files/anthropic";
786
- import { appLog, bytes } from "./fake-model.js";
787
- import { fakeFetch, sse } from "./fake-fetch.js";
732
+ import { fakeFetch, sse, utf8 } from "llm-large-files/testing";
733
+ import { appLog } from "./documents.js";
788
734
 
789
735
  const question = [{ role: "user" as const, text: "How many payments failed?" }];
790
736
 
791
737
  async function largeLog() {
792
738
  const files = createLargeFiles({ store: new MemoryDocumentStore(), budget: { inlineTokens: 1_000 } });
793
- const meta = await files.ingest({ name: "app.log", bytes: bytes(appLog(400)) });
739
+ const meta = await files.ingest({ name: "app.log", bytes: utf8(appLog(400)) });
794
740
  const args = { document_id: meta.id, query: "ERROR", mode: "exact" };
795
741
  return { files, meta, args };
796
742
  }
@@ -957,7 +903,7 @@ Record in a live run, then replay in the test:
957
903
  ```ts
958
904
  import { askWithFiles } from "llm-large-files";
959
905
  import { gemini, vertexAi } from "llm-large-files/gemini";
960
- import { fakeFetch } from "./fake-fetch.js";
906
+ import { fakeFetch } from "llm-large-files/testing";
961
907
  import { recordingFetch, replay } from "./record.js";
962
908
 
963
909
  // Assumes `files` and `meta` (a test document, as in largeLog()), and a real `endpoint`
@@ -1012,7 +958,7 @@ and deletes them.
1012
958
  // test/expiry.test.ts
1013
959
  import { describe, expect, it } from "vitest";
1014
960
  import { askWithFiles, createLargeFiles, DocumentsNotFoundError, MemoryDocumentStore } from "llm-large-files";
1015
- import { bytes, fakeModel, says } from "./fake-model.js";
961
+ import { fakeModel, says, utf8 } from "llm-large-files/testing";
1016
962
 
1017
963
  describe("documents that expire", () => {
1018
964
  it("are gone after their time to live, and swept from the store", async () => {
@@ -1020,7 +966,7 @@ describe("documents that expire", () => {
1020
966
  const now = () => clock;
1021
967
  // One clock for both: the library checks expiry by its clock, and the store by its own when it reads.
1022
968
  const files = createLargeFiles({ store: new MemoryDocumentStore({ now }), now, ttlMs: 60 * 60_000 });
1023
- const meta = await files.ingest({ name: "notes.md", bytes: bytes("The code word is heron."), owner: "alice" });
969
+ const meta = await files.ingest({ name: "notes.md", bytes: utf8("The code word is heron."), owner: "alice" });
1024
970
  expect(meta.expiresAt).toBe("2026-01-01T10:00:00.000Z");
1025
971
  // Another user cannot delete it.
1026
972
  expect(await files.delete(meta.id, { owner: "bob" })).toBe(false);
@@ -1147,7 +1093,8 @@ import { describe, expect, it } from "vitest";
1147
1093
  import { GoogleAuth } from "google-auth-library";
1148
1094
  import { askWithFiles, createLargeFiles, MemoryDocumentStore } from "llm-large-files";
1149
1095
  import { gemini, vertexAi } from "llm-large-files/gemini";
1150
- import { appLog, bytes } from "./fake-model.js";
1096
+ import { utf8 } from "llm-large-files/testing";
1097
+ import { appLog } from "./documents.js";
1151
1098
 
1152
1099
  // Skipped unless LIVE_TESTS=1 is set: the default test run never calls a model.
1153
1100
  describe.skipIf(process.env.LIVE_TESTS !== "1")("live: Gemini on Vertex AI", () => {
@@ -1164,7 +1111,7 @@ describe.skipIf(process.env.LIVE_TESTS !== "1")("live: Gemini on Vertex AI", ()
1164
1111
  },
1165
1112
  }));
1166
1113
  const files = createLargeFiles({ store: new MemoryDocumentStore(), budget: { inlineTokens: 1_000 } });
1167
- const meta = await files.ingest({ name: "app.log", bytes: bytes(appLog(400)) });
1114
+ const meta = await files.ingest({ name: "app.log", bytes: utf8(appLog(400)) });
1168
1115
 
1169
1116
  const result = await askWithFiles({
1170
1117
  files, model, documentIds: [meta.id],
@@ -1187,8 +1134,81 @@ The credentials are the application default credentials, as on your servers: see
1187
1134
  [Gemini and Vertex AI](./vertex-and-gemini.md). For another provider, swap the adapter:
1188
1135
  [OpenAI-compatible endpoints](./openai-compatible.md), [Claude](./anthropic.md).
1189
1136
 
1137
+ ## The library's own evals
1138
+
1139
+ The repository has an eval suite in `evals/`: about 50 Hebrew and English questions over synthetic
1140
+ files (a Hebrew policy in Word, a budget workbook with two header rows, a windows-1255 CSV of 3,000
1141
+ rows, a deck, a 3 MB service log, a shift diary, Hebrew PDFs, a contract), each with the facts its
1142
+ answer must hold. It is how the library checks that a change to what it sends a model keeps the
1143
+ answers right. It is not part of the package. To run it, clone the repository and `npm install`:
1144
+
1145
+ ```bash
1146
+ npm run eval:replay # every case from its recording: no network, no key
1147
+ npm run eval:recheck # the facts checked again on the recorded answers
1148
+ GEMINI_API_KEY=… npm run eval:record # each case once against the Gemini API, recorded
1149
+ GEMINI_API_KEY=… npm run eval:live -- --k 3
1150
+ ```
1151
+
1152
+ - **Replay** answers each request from `evals/cassettes`, and checks the facts again on the
1153
+ recorded answers. CI runs it on every pull request. A request that changed fails with
1154
+ "prompt changed: re-record", with the case, the request and the first field that differs (the
1155
+ method, the URL, or a field of the body). A fact that held when recorded must hold again. A case
1156
+ that asks for a whole-file read must have made one when it was recorded, so its part, merge and
1157
+ final requests are in its cassette and a change to those prompts fails too.
1158
+ - **Recheck** is a replay that writes each case's facts, checked on its recorded answer, to the
1159
+ cassette. Run it after you change a fact and no request: a replay whose facts changed since the
1160
+ recording fails with "facts changed" until you do.
1161
+ - **Record** runs each case once on each model (Gemini 3.5 Flash-Lite and 3.8 Flash by default), and
1162
+ writes its cassette: each request as a hash with an outline of its fields, and the response. A
1163
+ cassette holds no request text and no project ID. Request headers are written from a short list
1164
+ (content-type, accept, anthropic-version, anthropic-beta); every other header value, and every
1165
+ URL parameter but `alt` and `api-version`, is written as `<redacted>`.
1166
+ - **Live** runs each case k times. A case passes only when every run passes (pass^k): a real model
1167
+ answers a little differently each time. A workflow of the repository runs it every week and on
1168
+ demand, once the repository has the `GEMINI_API_KEY` secret; until then it skips with a notice.
1169
+
1170
+ Record and live fail a case when a question ends with an error (a refused key, a quota), when a case
1171
+ not known to fail on 0.9.0 misses pass^k, or when a fact that held in every run of the baseline
1172
+ fails now. Each writes a report, `evals/results/<mode>.md`, with the runs as JSON beside it
1173
+ (`<mode>.json`, answers included). A replay or a recheck writes one only when given `--results`.
1174
+ The report gives, for each case and model, whether it passed, the requests (mean and median), the
1175
+ share of questions answered in one request, reads and whole reads per question, input tokens, the
1176
+ cached share, latency, whether the question's input-token ceiling was reached, and the line
1177
+ citations checked per answer. For each model it figures the release gates: counts right, Hebrew
1178
+ lookups right, Hebrew answered in Hebrew, citations inside what the tools showed, the requests of
1179
+ inline-table questions, and the facts lost against the baseline, which it lists. The baseline is
1180
+ the report of 0.9.0, `evals/baseline/0.9.0.md` (runs in `0.9.0.json`). Its answers are kept, so its
1181
+ facts are checked again as the cases say now.
1182
+
1183
+ | Option | What it does |
1184
+ | --- | --- |
1185
+ | `--k 3` | Runs of each case, live. |
1186
+ | `--models a,b` | The Gemini models. |
1187
+ | `--cases id,id` | Only these cases (their IDs are in `evals/cases.ts`). |
1188
+ | `--results file.json` | Adds the runs to this file, and writes its report beside it. |
1189
+ | `--title "…"` | The title of the report. |
1190
+ | `--notes notes.md` | Markdown put under the report's title. |
1191
+ | `--baseline file.json` | The results to compare facts with (`evals/baseline/0.9.0.json` by default; `none` for no comparison). |
1192
+ | `--max-input-tokens N` | No question starts once the run has used this many input tokens. |
1193
+ | `--question-input-tokens N` | A question that uses more is stopped (1,500,000 by default). |
1194
+ | `--concurrency N` | Cases run at once (4 against the API, 1 in a replay, by default: a replay runs the cases in the order they were recorded, as a model's part reads learn its output limit once in a process). |
1195
+
1196
+ `node evals/cli.mjs report --results file.json` writes the report of a results file again.
1197
+
1198
+ A fact is a number (to a tolerance, and next to its label when the value belongs to one row), a
1199
+ text the answer must say or must not say, a line the answer must cite, or the language: a Hebrew
1200
+ question is answered with at least 60% Hebrew letters, once citations, file names, numbers, code,
1201
+ identifiers, names and Latin glosses are left out. Facts read the answer without its markdown
1202
+ emphasis.
1203
+
1204
+ The record and replay under it is internal to `evals/` for now. It becomes public in
1205
+ `llm-large-files/testing` in 0.10.x, for recording the questions of your own app the same way;
1206
+ until then, [Recorded replies](#recorded-replies) shows a small version to copy.
1207
+
1190
1208
  ## Reference
1191
1209
 
1210
+ - `fakeModel`, `says`, `calls`, `httpError`, `fakeFetch`, `sse`, `utf8`, `serviceLog` and
1211
+ `documentStoreChecks`: [`llm-large-files/testing`](../reference/testing.md).
1192
1212
  - [`ModelAdapter`](../reference/ask.md#modeladapter), [`ModelRequest`](../reference/ask.md#modelrequest),
1193
1213
  [`AskResult`](../reference/ask.md#askresult), [`AskLimits`](../reference/ask.md#asklimits) and
1194
1214
  `partialResultOf`: [the tool loop and the adapter contract](../reference/ask.md).