llm-large-files 0.5.0 → 0.8.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.
- package/CHANGELOG.md +1719 -466
- package/README.md +190 -60
- package/dist/analyze.d.ts +8 -1
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +198 -54
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts +14 -3
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +194 -40
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +63 -7
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +1131 -214
- package/dist/ask.js.map +1 -1
- package/dist/decode.d.ts +19 -0
- package/dist/decode.d.ts.map +1 -0
- package/dist/decode.js +97 -0
- package/dist/decode.js.map +1 -0
- package/dist/encoding.d.ts +17 -0
- package/dist/encoding.d.ts.map +1 -0
- package/dist/encoding.js +852 -0
- package/dist/encoding.js.map +1 -0
- package/dist/errors.d.ts +59 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +80 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +339 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +163 -0
- package/dist/events.js.map +1 -0
- package/dist/evidence.d.ts +2 -0
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +9 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +26 -7
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +180 -314
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +17 -8
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +117 -66
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +23 -3
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +6 -2
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +5 -1
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +11 -2
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/errors.d.ts +9 -4
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +32 -0
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +10 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +33 -10
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -2
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -1
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -1
- package/dist/gemini/sse.js.map +1 -1
- package/dist/groups.d.ts +54 -0
- package/dist/groups.d.ts.map +1 -0
- package/dist/groups.js +136 -0
- package/dist/groups.js.map +1 -0
- package/dist/html.d.ts +11 -0
- package/dist/html.d.ts.map +1 -0
- package/dist/html.js +1112 -0
- package/dist/html.js.map +1 -0
- package/dist/http.d.ts +116 -0
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +347 -1
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +13 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -5
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +67 -5
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +449 -93
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +2 -1
- package/dist/limiter.d.ts.map +1 -1
- package/dist/limiter.js +3 -2
- package/dist/limiter.js.map +1 -1
- package/dist/map-reduce.d.ts +28 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +240 -52
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +84 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +190 -2
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +20 -4
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +184 -28
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +4 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +38 -0
- package/dist/node/ingest-child.d.ts.map +1 -0
- package/dist/node/ingest-child.js +42 -0
- package/dist/node/ingest-child.js.map +1 -0
- package/dist/node/isolated.d.ts +88 -0
- package/dist/node/isolated.d.ts.map +1 -0
- package/dist/node/isolated.js +381 -0
- package/dist/node/isolated.js.map +1 -0
- package/dist/node/sse.d.ts +59 -0
- package/dist/node/sse.d.ts.map +1 -0
- package/dist/node/sse.js +174 -0
- package/dist/node/sse.js.map +1 -0
- package/dist/office.d.ts +105 -0
- package/dist/office.d.ts.map +1 -0
- package/dist/office.js +1092 -0
- package/dist/office.js.map +1 -0
- package/dist/openai/adapter.d.ts +29 -5
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +325 -37
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +14 -2
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +39 -10
- package/dist/output-limit.js.map +1 -1
- package/dist/pause.d.ts +24 -0
- package/dist/pause.d.ts.map +1 -0
- package/dist/pause.js +38 -0
- package/dist/pause.js.map +1 -0
- package/dist/pdf-pages.d.ts +32 -2
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +277 -20
- package/dist/pdf-pages.js.map +1 -1
- package/dist/pdf-pictures.d.ts +30 -3
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +50 -8
- package/dist/pdf-pictures.js.map +1 -1
- package/dist/pdf-work.d.ts +40 -0
- package/dist/pdf-work.d.ts.map +1 -0
- package/dist/pdf-work.js +734 -0
- package/dist/pdf-work.js.map +1 -0
- package/dist/peers.d.ts +8 -0
- package/dist/peers.d.ts.map +1 -0
- package/dist/peers.js +32 -0
- package/dist/peers.js.map +1 -0
- package/dist/plan.d.ts +22 -4
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +61 -12
- package/dist/plan.js.map +1 -1
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +4 -2
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +23 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +33 -3
- package/dist/retry.js.map +1 -1
- package/dist/search.d.ts +107 -24
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +803 -149
- package/dist/search.js.map +1 -1
- package/dist/sse.d.ts +35 -2
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +145 -31
- package/dist/sse.js.map +1 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +5 -2
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +9 -1
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +28 -9
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +87 -3
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +526 -24
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +61 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +461 -46
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +103 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/word-styles.d.ts +102 -0
- package/dist/word-styles.d.ts.map +1 -0
- package/dist/word-styles.js +419 -0
- package/dist/word-styles.js.map +1 -0
- package/dist/xlsx.d.ts +23 -0
- package/dist/xlsx.d.ts.map +1 -0
- package/dist/xlsx.js +511 -0
- package/dist/xlsx.js.map +1 -0
- package/dist/xml-stream.d.ts +55 -0
- package/dist/xml-stream.d.ts.map +1 -0
- package/dist/xml-stream.js +235 -0
- package/dist/xml-stream.js.map +1 -0
- package/dist/zip-directory.d.ts +43 -0
- package/dist/zip-directory.d.ts.map +1 -0
- package/dist/zip-directory.js +130 -0
- package/dist/zip-directory.js.map +1 -0
- package/docs/README.md +288 -0
- package/docs/api.md +37 -381
- package/docs/configuration.md +28 -558
- package/docs/getting-started.md +407 -223
- package/docs/guides/anthropic.md +590 -0
- package/docs/guides/conversations.md +629 -0
- package/docs/guides/costs-and-limits.md +728 -0
- package/docs/guides/deployment.md +720 -0
- package/docs/guides/errors-and-reliability.md +748 -0
- package/docs/guides/explorer-model.md +399 -0
- package/docs/guides/openai-compatible.md +602 -0
- package/docs/guides/own-adapter-and-loop.md +1169 -0
- package/docs/guides/pdfs.md +1024 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1203 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1590 -0
- package/docs/how-it-works.md +1035 -164
- package/docs/measurements.md +881 -0
- package/docs/publishing.md +274 -46
- package/docs/reference/anthropic.md +427 -0
- package/docs/reference/ask.md +910 -0
- package/docs/reference/errors-and-retries.md +760 -0
- package/docs/reference/events.md +1001 -0
- package/docs/reference/gemini.md +827 -0
- package/docs/reference/library.md +1598 -0
- package/docs/reference/node.md +706 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +1031 -0
- package/docs/security.md +940 -101
- package/docs/troubleshooting.md +1410 -0
- package/package.json +7 -3
- package/src/analyze.ts +204 -49
- package/src/anthropic/adapter.ts +200 -40
- package/src/ask.ts +1151 -210
- package/src/decode.ts +89 -0
- package/src/encoding.ts +850 -0
- package/src/errors.ts +125 -0
- package/src/events.ts +451 -0
- package/src/evidence.ts +11 -2
- package/src/extract.ts +191 -308
- package/src/gemini/adapter.ts +127 -70
- package/src/gemini/chat.ts +28 -4
- package/src/gemini/endpoints.ts +12 -2
- package/src/gemini/errors.ts +34 -1
- package/src/gemini/generate.ts +42 -13
- package/src/gemini/index.ts +3 -3
- package/src/gemini/sse.ts +1 -1
- package/src/groups.ts +162 -0
- package/src/html.ts +1071 -0
- package/src/http.ts +376 -1
- package/src/index.ts +29 -6
- package/src/library.ts +498 -93
- package/src/limiter.ts +6 -1
- package/src/map-reduce.ts +252 -51
- package/src/model.ts +244 -4
- package/src/node/handlers.ts +196 -31
- package/src/node/index.ts +4 -0
- package/src/node/ingest-child.ts +61 -0
- package/src/node/isolated.ts +464 -0
- package/src/node/sse.ts +198 -0
- package/src/office.ts +1047 -0
- package/src/openai/adapter.ts +319 -38
- package/src/output-limit.ts +44 -8
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +270 -20
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/peers.ts +29 -0
- package/src/plan.ts +70 -12
- package/src/ranged.ts +4 -2
- package/src/retry.ts +49 -5
- package/src/search.ts +800 -155
- package/src/sse.ts +153 -28
- package/src/stores.ts +5 -2
- package/src/text-index.ts +30 -9
- package/src/text.ts +524 -23
- package/src/tools.ts +445 -46
- package/src/types.ts +108 -5
- package/src/word-styles.ts +420 -0
- package/src/xlsx.ts +478 -0
- package/src/xml-stream.ts +224 -0
- package/src/zip-directory.ts +136 -0
|
@@ -0,0 +1,1203 @@
|
|
|
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. …`. Since 0.8.0 both
|
|
444
|
+
notes end `To see the ones in between, search again with from_line N, or count them with group_by.`,
|
|
445
|
+
where N is the line after the last of the first ones (below line 15269 in the first note, and
|
|
446
|
+
below line 1000 in the second), and the result has `next_from_line` with that line
|
|
447
|
+
([`search_document`](../reference/tools.md#search_document)).
|
|
448
|
+
- **Steps with a count of one** are singular: ` — 1 matching line`, ` — 1 passage`,
|
|
449
|
+
` — 1 part, 1 relevant`, and `1 more tool call in this turn was not run (at most 8 a turn)`.
|
|
450
|
+
- **A call to a tool that does not exist** has the step `Call “do_magic” — failed: Unknown tool “do_magic”.`,
|
|
451
|
+
and the model gets `Unknown tool “do_magic”.`, as `files.tools().execute()` returns it.
|
|
452
|
+
- **The answer's second try** ([above](#replies-that-depend-on-the-request)): one more request when
|
|
453
|
+
the answer comes back without text. To cap the requests of a question exactly, set
|
|
454
|
+
`limits.requests`.
|
|
455
|
+
- **A whole-file read that fails** says why by the kind and status of the error, never by its
|
|
456
|
+
words: `Could not read any part of app.log: The model was busy (HTTP 429).` A fake `generateText`
|
|
457
|
+
that throws a plain `Error` gives `The model request failed.`, and one that throws
|
|
458
|
+
`new ModelRequestError("…", 401)` gives `The model refused the key or token it was sent (HTTP 401).`
|
|
459
|
+
- **A reply of HTTP 200 that is not JSON** is a `ModelRequestError` of kind `invalid` and status
|
|
460
|
+
200, with the `SyntaxError` as its `cause`: test `error.cause instanceof SyntaxError`. Kind
|
|
461
|
+
`invalid` alone also covers every other request the provider refused.
|
|
462
|
+
- **A fake `fetch` whose reply of HTTP 200 is empty** gets the request again: the reply is kind
|
|
463
|
+
`unreachable`, status 0. A streamed reply that is not of type `text/event-stream` is read by what
|
|
464
|
+
it holds: as events when it starts like them, as JSON when it starts with `{` or `[`.
|
|
465
|
+
- **An error inside a stream** has the status and the kind of its type: on an OpenAI-compatible
|
|
466
|
+
endpoint, `context_length_exceeded` is 400, kind `context_overflow`; on Claude,
|
|
467
|
+
`authentication_error` is 401, kind `auth`. Both kept the stream's HTTP 200 in 0.5.0.
|
|
468
|
+
- **A question stopped while its adapter is called** throws the signal's reason, even when the
|
|
469
|
+
adapter then fails with its own error (a fake that throws a 503, say).
|
|
470
|
+
- **A Gemini part read** sends `generationConfig: { maxOutputTokens }`, without `temperature`.
|
|
471
|
+
- **The card of a text file that is not valid UTF-8** has one more line, and its frame a note
|
|
472
|
+
after the count of lines, such as `, read as windows-1255`
|
|
473
|
+
([Text encodings](./pdfs.md#text-encodings)).
|
|
474
|
+
- **The stored text** of a file with characters that show nothing, with text that Word hides, or
|
|
475
|
+
with a hidden slide differs from what 0.5.0 stored
|
|
476
|
+
([Characters that show nothing](../security.md#characters-that-show-nothing)).
|
|
477
|
+
- **Steps** quote the model's words on one line, without the characters that show nothing. The
|
|
478
|
+
steps of a request too large are new, such as
|
|
479
|
+
`The request was larger than the model takes: older tool results were shortened, and it was sent again`
|
|
480
|
+
and `The first request was larger than the model's window of 60,000 tokens: the files were planned again to fit it`,
|
|
481
|
+
and the same for the tokens a minute the provider allows. So is `, notes only` at the end of the
|
|
482
|
+
step of a whole-file read that returned only its notes.
|
|
483
|
+
- **`anthropic().capabilities`** has `clearsToolResults: true` when `body.context_management`
|
|
484
|
+
clears tool uses or compacts the conversation.
|
|
485
|
+
- **`geminiToolTurns`, `openAiToolTurns` and `anthropicToolTurns`** leave `tool_turns_left` out of
|
|
486
|
+
each result, so their output no longer equals the stored result.
|
|
487
|
+
- **`MemoryDocumentStore`** returns a new copy of the metadata from each call: compare with
|
|
488
|
+
`toEqual`, not `toBe`.
|
|
489
|
+
- **`files.ingest` with `owner: ""`** throws a `TypeError`
|
|
490
|
+
([Storage](./storage.md#how-ownership-works)).
|
|
491
|
+
- **The descriptions of `search_document` and `analyze_whole_document`** changed: the first now
|
|
492
|
+
says that exact and regex results show the first `max_results` matching lines and the last one,
|
|
493
|
+
and the second sends counting and listing to `search_document`. A test that compares the tool
|
|
494
|
+
declarations, or the `tools` of a request, with a stored copy fails.
|
|
495
|
+
|
|
496
|
+
## Errors
|
|
497
|
+
|
|
498
|
+
A fake throws what a real adapter throws: a
|
|
499
|
+
[`ModelRequestError`](../reference/errors-and-retries.md#modelrequesterror) with an HTTP `status`
|
|
500
|
+
and a `kind`. The kind is told from the status, the message and the provider's `code` (and a
|
|
501
|
+
Gemini error's `details`), unless you pass `kind`:
|
|
502
|
+
|
|
503
|
+
| Kind | A fake throws | The loop sends it again |
|
|
504
|
+
| --- | --- | --- |
|
|
505
|
+
| `rate_limit` | `new ModelRequestError("Too many requests.", 429)` | Yes, up to `retry.retries` times (3) |
|
|
506
|
+
| `quota` | `new ModelRequestError("You exceeded your current quota.", 429, { code: "insufficient_quota" })` | No |
|
|
507
|
+
| `server` | `new ModelRequestError("The model is overloaded.", 503)` | Yes |
|
|
508
|
+
| `timeout` | `new ModelRequestError("The model sent nothing for 600 s.", 0, { kind: "timeout" })` | Once |
|
|
509
|
+
| `unreachable` | `new ModelRequestError("The model could not be reached.", 0)` | Yes |
|
|
510
|
+
| `auth` | `new ModelRequestError("Token expired.", 401)` | No |
|
|
511
|
+
| `invalid` | `new ModelRequestError("Bad request.", 400)` | No (HTTP 409 is `invalid` too, and is sent again) |
|
|
512
|
+
| `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 |
|
|
513
|
+
|
|
514
|
+
An `Error` without a `status` is not sent again, and reaches your code as it is. What each kind
|
|
515
|
+
means for a user is in [Errors and reliability](./errors-and-reliability.md).
|
|
516
|
+
|
|
517
|
+
```ts
|
|
518
|
+
// test/errors.test.ts
|
|
519
|
+
import { describe, expect, it } from "vitest";
|
|
520
|
+
import { askWithFiles, createLargeFiles, DocumentsNotFoundError, errorKindOf, MemoryDocumentStore, ModelRequestError, partialResultOf } from "llm-large-files";
|
|
521
|
+
import { appLog, bytes, calls, fakeModel, says } from "./fake-model.js";
|
|
522
|
+
|
|
523
|
+
/** Your application's own words for a question that failed: the code under test. */
|
|
524
|
+
function userMessage(error: unknown): string {
|
|
525
|
+
if (error instanceof DocumentsNotFoundError) return "A file is no longer available. Upload it again.";
|
|
526
|
+
switch (errorKindOf(error)) {
|
|
527
|
+
case "rate_limit":
|
|
528
|
+
case "server":
|
|
529
|
+
case "timeout":
|
|
530
|
+
case "unreachable":
|
|
531
|
+
return "The assistant is busy. Try again in a minute.";
|
|
532
|
+
case "context_overflow":
|
|
533
|
+
return "This chat is too long for the model. Start a new one.";
|
|
534
|
+
default:
|
|
535
|
+
return "Something went wrong.";
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
const question = [{ role: "user" as const, text: "How many payments failed?" }];
|
|
540
|
+
|
|
541
|
+
async function largeLog() {
|
|
542
|
+
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" });
|
|
544
|
+
const search = { name: "search_document", args: { document_id: meta.id, query: "ERROR", mode: "exact" } };
|
|
545
|
+
return { files, meta, search };
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
describe("a question that fails", () => {
|
|
549
|
+
it("shows a busy message when the model is overloaded", async () => {
|
|
550
|
+
const { files, meta } = await largeLog();
|
|
551
|
+
const model = fakeModel([new ModelRequestError("The model is overloaded.", 503)]);
|
|
552
|
+
|
|
553
|
+
// retries: 0, so the error comes back at once, not after three more tries and their waits.
|
|
554
|
+
const error = await askWithFiles({ files, model, documentIds: [meta.id], owner: "alice", messages: question, retry: { retries: 0 } })
|
|
555
|
+
.catch((caught: unknown) => caught);
|
|
556
|
+
|
|
557
|
+
expect(error).toMatchObject({ status: 503, kind: "server" });
|
|
558
|
+
expect(userMessage(error)).toBe("The assistant is busy. Try again in a minute.");
|
|
559
|
+
});
|
|
560
|
+
|
|
561
|
+
it("is sent again after a busy reply, without waiting in the test", async () => {
|
|
562
|
+
const { files, meta } = await largeLog();
|
|
563
|
+
const model = fakeModel([new ModelRequestError("Too many requests.", 429), says("8 payments failed.")]);
|
|
564
|
+
const waits: number[] = [];
|
|
565
|
+
|
|
566
|
+
const result = await askWithFiles({
|
|
567
|
+
files, model, documentIds: [meta.id], owner: "alice", messages: question,
|
|
568
|
+
// The wait is recorded instead of slept; random: () => 1 takes the jitter out of it.
|
|
569
|
+
retry: { sleep: async (ms) => { waits.push(ms); }, random: () => 1 },
|
|
570
|
+
});
|
|
571
|
+
|
|
572
|
+
expect(result.text).toBe("8 payments failed.");
|
|
573
|
+
expect(model.requests).toHaveLength(2);
|
|
574
|
+
expect(waits).toEqual([500]);
|
|
575
|
+
// A request that failed and was sent again counts once.
|
|
576
|
+
expect(result.usage.requests).toBe(1);
|
|
577
|
+
});
|
|
578
|
+
|
|
579
|
+
it("keeps what was found before the failure", async () => {
|
|
580
|
+
const { files, meta, search } = await largeLog();
|
|
581
|
+
const model = fakeModel([calls([search]), new ModelRequestError("Token expired.", 401)]);
|
|
582
|
+
|
|
583
|
+
const error = await askWithFiles({ files, model, documentIds: [meta.id], owner: "alice", messages: question })
|
|
584
|
+
.catch((caught: unknown) => caught);
|
|
585
|
+
|
|
586
|
+
expect(errorKindOf(error)).toBe("auth");
|
|
587
|
+
expect(model.requests).toHaveLength(2); // a refused token is not sent again
|
|
588
|
+
const partial = partialResultOf(error);
|
|
589
|
+
expect(partial).toMatchObject({ answered: false, steps: ["Search app.log (exact) for “ERROR” — 8 matching lines"] });
|
|
590
|
+
expect(partial!.toolTurns).toHaveLength(1);
|
|
591
|
+
});
|
|
592
|
+
|
|
593
|
+
it("refuses a document of another user before any model request", async () => {
|
|
594
|
+
const { files, meta } = await largeLog();
|
|
595
|
+
const model = fakeModel([says("never sent")]);
|
|
596
|
+
|
|
597
|
+
const error = await askWithFiles({ files, model, documentIds: [meta.id], owner: "bob", messages: question })
|
|
598
|
+
.catch((caught: unknown) => caught);
|
|
599
|
+
|
|
600
|
+
expect(error).toBeInstanceOf(DocumentsNotFoundError);
|
|
601
|
+
expect((error as DocumentsNotFoundError).ids).toEqual([meta.id]);
|
|
602
|
+
expect(userMessage(error)).toBe("A file is no longer available. Upload it again.");
|
|
603
|
+
expect(model.requests).toHaveLength(0);
|
|
604
|
+
});
|
|
605
|
+
});
|
|
606
|
+
```
|
|
607
|
+
|
|
608
|
+
Notes on these tests:
|
|
609
|
+
|
|
610
|
+
- **Waits.** The loop sends a failed request again after a real wait: up to 500 ms the first
|
|
611
|
+
time, then twice as long each time, with jitter that takes up to half off each wait. With
|
|
612
|
+
`random: () => 1` the waits are exactly 500, 1,000 and 2,000 ms. In tests, pass
|
|
613
|
+
`retry: { retries: 0 }` to get the error at once, or a `sleep` that records the waits and
|
|
614
|
+
returns at once, as above. Both are fields of
|
|
615
|
+
[`RetryOptions`](../reference/errors-and-retries.md#retryoptions).
|
|
616
|
+
- **`partialResultOf(error)`** gives what the question found and used before it failed: its steps,
|
|
617
|
+
evidence, tool rounds and usage, with `answered: false`. Test that your application keeps them.
|
|
618
|
+
Its `usage` is a copy taken when the question failed: a request of a fake that was still running
|
|
619
|
+
then, and answers later, is not counted.
|
|
620
|
+
- **`DocumentsNotFoundError`** comes before any model request, for a document that is missing,
|
|
621
|
+
expired or owned by someone else. Its `ids` are the ones not found.
|
|
622
|
+
- **A request too large** (`context_overflow`) is mended inside the loop when it can be. A fake that
|
|
623
|
+
repeats the error lets you see what your application does when it cannot be mended.
|
|
624
|
+
|
|
625
|
+
## The real adapters with a fake fetch
|
|
626
|
+
|
|
627
|
+
A fake model tests your code; it does not test that you set up the provider right. For that, run
|
|
628
|
+
the real adapter and fake the network. Every adapter takes a `fetch` option, and sends every request
|
|
629
|
+
through it, the part reads of a whole-file read included:
|
|
630
|
+
|
|
631
|
+
| Adapter | Where `fetch` goes |
|
|
632
|
+
| --- | --- |
|
|
633
|
+
| Gemini API and Vertex AI | `gemini(endpoint, { fetch })`, or `askGemini({ ..., fetch })` |
|
|
634
|
+
| OpenAI-compatible | `openAiCompatible({ ..., fetch })` |
|
|
635
|
+
| Claude | `anthropic({ ..., fetch })` |
|
|
636
|
+
|
|
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`:
|
|
639
|
+
|
|
640
|
+
```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
|
+
}
|
|
665
|
+
|
|
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
|
+
);
|
|
671
|
+
```
|
|
672
|
+
|
|
673
|
+
### Gemini on Vertex AI
|
|
674
|
+
|
|
675
|
+
`vertexAi()` with a fixed `accessToken` string makes no call to get a token, so the test needs no
|
|
676
|
+
credentials. The replies are in Gemini's own JSON:
|
|
677
|
+
|
|
678
|
+
```ts
|
|
679
|
+
// test/vertex.test.ts
|
|
680
|
+
import { describe, expect, it } from "vitest";
|
|
681
|
+
import { askWithFiles, createLargeFiles, MemoryDocumentStore } from "llm-large-files";
|
|
682
|
+
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";
|
|
685
|
+
|
|
686
|
+
// Replies as Gemini writes them.
|
|
687
|
+
const geminiText = (text: string) => ({
|
|
688
|
+
candidates: [{ content: { role: "model", parts: [{ text }] }, finishReason: "STOP" }],
|
|
689
|
+
usageMetadata: { promptTokenCount: 1_200, candidatesTokenCount: 20, totalTokenCount: 1_220 },
|
|
690
|
+
});
|
|
691
|
+
const geminiCall = (name: string, args: Record<string, unknown>) => ({
|
|
692
|
+
candidates: [{ content: { role: "model", parts: [{ functionCall: { name, args } }] }, finishReason: "STOP" }],
|
|
693
|
+
usageMetadata: { promptTokenCount: 900, candidatesTokenCount: 15, totalTokenCount: 915 },
|
|
694
|
+
});
|
|
695
|
+
|
|
696
|
+
// A fixed token: vertexAi() calls nothing to get it.
|
|
697
|
+
const endpoint = vertexAi({ project: "test-project", location: "europe-west4", model: "gemini-test", accessToken: "test-token" });
|
|
698
|
+
const question = [{ role: "user" as const, text: "How many payments failed?" }];
|
|
699
|
+
|
|
700
|
+
async function largeLog() {
|
|
701
|
+
const files = createLargeFiles({ store: new MemoryDocumentStore(), budget: { inlineTokens: 1_000 } });
|
|
702
|
+
const meta = await files.ingest({ name: "app.log", bytes: bytes(appLog(400)) });
|
|
703
|
+
return { files, meta };
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
describe("Gemini on Vertex AI, without the network", () => {
|
|
707
|
+
it("sends the token, runs the tool loop and counts the usage", async () => {
|
|
708
|
+
const { files, meta } = await largeLog();
|
|
709
|
+
const api = fakeFetch([
|
|
710
|
+
Response.json(geminiCall("search_document", { document_id: meta.id, query: "ERROR", mode: "exact" })),
|
|
711
|
+
Response.json(geminiText("8 payments failed (app.log L50).")),
|
|
712
|
+
]);
|
|
713
|
+
const model = gemini(endpoint, { fetch: api.fetch });
|
|
714
|
+
|
|
715
|
+
const result = await askWithFiles({ files, model, documentIds: [meta.id], messages: question });
|
|
716
|
+
|
|
717
|
+
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");
|
|
718
|
+
expect(api.sent[0]!.headers.Authorization).toBe("Bearer test-token");
|
|
719
|
+
expect(api.sent[1]!.body.contents.at(-1).parts[0].functionResponse.response).toMatchObject({ total_matching_lines: 8 });
|
|
720
|
+
expect(result).toMatchObject({ text: "8 payments failed (app.log L50).", answered: true, turns: 2, finishReason: "STOP" });
|
|
721
|
+
expect(result.usage.byModel["gemini-test"]).toMatchObject({ requests: 2, inputTokens: 2_100, outputTokens: 35 });
|
|
722
|
+
});
|
|
723
|
+
|
|
724
|
+
it("streams the answer through askGemini", async () => {
|
|
725
|
+
const files = createLargeFiles({ store: new MemoryDocumentStore() });
|
|
726
|
+
const meta = await files.ingest({ name: "notes.md", bytes: bytes("# Notes\n\nThe code word is heron.") });
|
|
727
|
+
// A streamed Gemini reply ends with a chunk that says why it ended.
|
|
728
|
+
const api = fakeFetch([sse([
|
|
729
|
+
{ candidates: [{ content: { role: "model", parts: [{ text: "The code word " }] } }] },
|
|
730
|
+
{ candidates: [{ content: { role: "model", parts: [{ text: "is heron." }] }, finishReason: "STOP" }] },
|
|
731
|
+
])]);
|
|
732
|
+
const deltas: string[] = [];
|
|
733
|
+
|
|
734
|
+
const result = await askGemini({
|
|
735
|
+
files, endpoint, fetch: api.fetch, documentIds: [meta.id],
|
|
736
|
+
messages: [{ role: "user", text: "What is the code word?" }],
|
|
737
|
+
onText: (delta) => deltas.push(delta),
|
|
738
|
+
});
|
|
739
|
+
|
|
740
|
+
expect(api.sent[0]!.url).toMatch(/:streamGenerateContent\?alt=sse$/);
|
|
741
|
+
expect(deltas).toEqual(["The code word ", "is heron."]);
|
|
742
|
+
expect(result.text).toBe("The code word is heron.");
|
|
743
|
+
});
|
|
744
|
+
|
|
745
|
+
it("reports an HTTP error with its kind", async () => {
|
|
746
|
+
const { files, meta } = await largeLog();
|
|
747
|
+
const busy = { error: { code: 429, message: "Resource exhausted. Please try again later.", status: "RESOURCE_EXHAUSTED" } };
|
|
748
|
+
const api = fakeFetch([Response.json(busy, { status: 429 })]);
|
|
749
|
+
|
|
750
|
+
const error = await askGemini({ files, endpoint, fetch: api.fetch, documentIds: [meta.id], messages: question, retry: { retries: 0 } })
|
|
751
|
+
.catch((caught: unknown) => caught);
|
|
752
|
+
|
|
753
|
+
expect(error).toBeInstanceOf(GeminiRequestError);
|
|
754
|
+
expect(error).toMatchObject({ status: 429, kind: "rate_limit", message: "Resource exhausted. Please try again later." });
|
|
755
|
+
});
|
|
756
|
+
|
|
757
|
+
it("reports a model that sends nothing as a timeout", async () => {
|
|
758
|
+
const { files, meta } = await largeLog();
|
|
759
|
+
// A fetch that never answers: it ends only when the adapter aborts it, as the real fetch does.
|
|
760
|
+
const silent = (async (_input: string | URL | Request, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
|
|
761
|
+
init?.signal?.addEventListener("abort", () => reject(init.signal!.reason), { once: true });
|
|
762
|
+
})) as typeof fetch;
|
|
763
|
+
const model = gemini(endpoint, { fetch: silent, firstByteTimeoutMs: 20 });
|
|
764
|
+
|
|
765
|
+
const error = await askWithFiles({ files, model, documentIds: [meta.id], messages: question, retry: { retries: 0 } })
|
|
766
|
+
.catch((caught: unknown) => caught);
|
|
767
|
+
|
|
768
|
+
expect(error).toMatchObject({ status: 0, kind: "timeout" });
|
|
769
|
+
});
|
|
770
|
+
});
|
|
771
|
+
```
|
|
772
|
+
|
|
773
|
+
A `fetch` that throws (`throw new TypeError("fetch failed")`) is a model that cannot be reached: a
|
|
774
|
+
`GeminiRequestError` with `status` 0, kind `"unreachable"` and the message
|
|
775
|
+
"Gemini could not be reached (fetch failed)." The setup itself is in
|
|
776
|
+
[Gemini and Vertex AI](./vertex-and-gemini.md).
|
|
777
|
+
|
|
778
|
+
### OpenAI-compatible endpoints and Claude
|
|
779
|
+
|
|
780
|
+
```ts
|
|
781
|
+
// test/providers.test.ts
|
|
782
|
+
import { describe, expect, it } from "vitest";
|
|
783
|
+
import { askWithFiles, createLargeFiles, MemoryDocumentStore } from "llm-large-files";
|
|
784
|
+
import { openAiCompatible } from "llm-large-files/openai";
|
|
785
|
+
import { anthropic } from "llm-large-files/anthropic";
|
|
786
|
+
import { appLog, bytes } from "./fake-model.js";
|
|
787
|
+
import { fakeFetch, sse } from "./fake-fetch.js";
|
|
788
|
+
|
|
789
|
+
const question = [{ role: "user" as const, text: "How many payments failed?" }];
|
|
790
|
+
|
|
791
|
+
async function largeLog() {
|
|
792
|
+
const files = createLargeFiles({ store: new MemoryDocumentStore(), budget: { inlineTokens: 1_000 } });
|
|
793
|
+
const meta = await files.ingest({ name: "app.log", bytes: bytes(appLog(400)) });
|
|
794
|
+
const args = { document_id: meta.id, query: "ERROR", mode: "exact" };
|
|
795
|
+
return { files, meta, args };
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
describe("other providers, without the network", () => {
|
|
799
|
+
it("runs the loop on an OpenAI-compatible endpoint, and streams its answer", async () => {
|
|
800
|
+
const { files, meta, args } = await largeLog();
|
|
801
|
+
const api = fakeFetch([
|
|
802
|
+
// Asked for a stream, answered in one piece: a reply that is not text/event-stream is read by
|
|
803
|
+
// its first characters, here as JSON.
|
|
804
|
+
Response.json({
|
|
805
|
+
choices: [{ index: 0, finish_reason: "tool_calls", message: { role: "assistant", content: null, tool_calls: [
|
|
806
|
+
{ id: "call_1", type: "function", function: { name: "search_document", arguments: JSON.stringify(args) } },
|
|
807
|
+
] } }],
|
|
808
|
+
usage: { prompt_tokens: 900, completion_tokens: 15 },
|
|
809
|
+
}),
|
|
810
|
+
// A stream ends with a finish_reason, or with [DONE].
|
|
811
|
+
sse([
|
|
812
|
+
{ choices: [{ index: 0, delta: { content: "8 payments " } }] },
|
|
813
|
+
{ choices: [{ index: 0, delta: { content: "failed." }, finish_reason: "stop" }] },
|
|
814
|
+
{ choices: [], usage: { prompt_tokens: 1_300, completion_tokens: 6 } },
|
|
815
|
+
"[DONE]",
|
|
816
|
+
]),
|
|
817
|
+
]);
|
|
818
|
+
const model = openAiCompatible({ model: "test-model", baseUrl: "https://llm.test/v1", apiKey: "test-key", fetch: api.fetch });
|
|
819
|
+
const deltas: string[] = [];
|
|
820
|
+
|
|
821
|
+
const result = await askWithFiles({ files, model, documentIds: [meta.id], messages: question, onText: (delta) => deltas.push(delta) });
|
|
822
|
+
|
|
823
|
+
expect(api.sent[0]!.url).toBe("https://llm.test/v1/chat/completions");
|
|
824
|
+
expect(api.sent[0]!.headers.Authorization).toBe("Bearer test-key");
|
|
825
|
+
expect(api.sent[0]!.body.stream).toBe(true);
|
|
826
|
+
expect(deltas).toEqual(["8 payments ", "failed."]);
|
|
827
|
+
expect(result).toMatchObject({ text: "8 payments failed.", answered: true, turns: 2 });
|
|
828
|
+
expect(result.usage).toMatchObject({ requests: 2, inputTokens: 2_200, outputTokens: 21 });
|
|
829
|
+
});
|
|
830
|
+
|
|
831
|
+
it("runs the loop on Claude, and reads its stream of events", async () => {
|
|
832
|
+
const { files, meta, args } = await largeLog();
|
|
833
|
+
const api = fakeFetch([
|
|
834
|
+
Response.json({
|
|
835
|
+
type: "message", role: "assistant", stop_reason: "tool_use",
|
|
836
|
+
content: [{ type: "tool_use", id: "toolu_1", name: "search_document", input: args }],
|
|
837
|
+
usage: { input_tokens: 900, output_tokens: 15 },
|
|
838
|
+
}),
|
|
839
|
+
// A stream ends with a message_delta that carries the stop_reason.
|
|
840
|
+
sse([
|
|
841
|
+
{ type: "message_start", message: { usage: { input_tokens: 1_300, output_tokens: 1 } } },
|
|
842
|
+
{ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } },
|
|
843
|
+
{ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "8 payments " } },
|
|
844
|
+
{ type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "failed." } },
|
|
845
|
+
{ type: "content_block_stop", index: 0 },
|
|
846
|
+
{ type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 6 } },
|
|
847
|
+
{ type: "message_stop" },
|
|
848
|
+
]),
|
|
849
|
+
]);
|
|
850
|
+
const model = anthropic({ model: "claude-test", apiKey: "test-key", fetch: api.fetch });
|
|
851
|
+
|
|
852
|
+
const result = await askWithFiles({ files, model, documentIds: [meta.id], messages: question });
|
|
853
|
+
|
|
854
|
+
expect(api.sent[0]!.url).toBe("https://api.anthropic.com/v1/messages");
|
|
855
|
+
expect(api.sent[0]!.headers["x-api-key"]).toBe("test-key");
|
|
856
|
+
expect(result).toMatchObject({ text: "8 payments failed.", answered: true, turns: 2, finishReason: "end_turn" });
|
|
857
|
+
});
|
|
858
|
+
});
|
|
859
|
+
```
|
|
860
|
+
|
|
861
|
+
### What each adapter expects of a fake reply
|
|
862
|
+
|
|
863
|
+
The adapters differ in when they stream and in how they read a reply. A fake reply must match, or
|
|
864
|
+
the adapter takes it for a broken one:
|
|
865
|
+
|
|
866
|
+
| | Gemini (`gemini()`, `askGemini`) | OpenAI-compatible | Claude |
|
|
867
|
+
| --- | --- | --- | --- |
|
|
868
|
+
| A reply in text | `candidates[0].content.parts: [{ text }]` | `choices[0].message.content` | `content: [{ type: "text", text }]` |
|
|
869
|
+
| A tool call | `parts: [{ functionCall: { name, args } }]` | `message.tool_calls`, with `arguments` as a JSON string | `content: [{ type: "tool_use", id, name, input }]` |
|
|
870
|
+
| Usage | `usageMetadata.promptTokenCount`, `candidatesTokenCount` | `usage.prompt_tokens`, `completion_tokens` | `usage.input_tokens`, `output_tokens` |
|
|
871
|
+
| 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` |
|
|
872
|
+
| 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 |
|
|
873
|
+
| A stream ends with | A chunk with `finishReason` | A chunk with `finish_reason`, or `data: [DONE]` | A `message_delta` event with `stop_reason` |
|
|
874
|
+
| An HTTP error body | `{ error: { code, message, status, details } }` | `{ error: { message, type, code, param } }` | `{ type: "error", error: { type, message } }` |
|
|
875
|
+
| Error class | `GeminiRequestError` | `OpenAiRequestError` | `AnthropicRequestError` |
|
|
876
|
+
|
|
877
|
+
A stream that closes without its end is taken for a reply cut off on its way, with `status` 0:
|
|
878
|
+
"Gemini's reply ended before it was complete.", "The model's reply ended before it was complete."
|
|
879
|
+
(OpenAI-compatible) or "Claude's reply ended before it was complete." The loop then sends the
|
|
880
|
+
request again, unless text of it was shown, and `onActivity` gets "The model's reply was cut off
|
|
881
|
+
on its way. Trying again…". When a fake stream seems to be sent twice, check that it ends as the
|
|
882
|
+
table above says: for Claude, a `message_delta` event with `stop_reason`, not only `message_stop`.
|
|
883
|
+
A stream that said it is whole (`[DONE]`, `message_stop`) and then stays open is read for one more
|
|
884
|
+
second, then left, and its reply is returned.
|
|
885
|
+
|
|
886
|
+
Other fake replies, and what each adapter makes of them:
|
|
887
|
+
|
|
888
|
+
- A body of HTTP 200 that is not JSON, such as `new Response("<html>…", { headers: { "Content-Type": "text/html" } })`:
|
|
889
|
+
a `ModelRequestError` with kind `invalid`, status 200 and the `SyntaxError` as `cause`, not sent
|
|
890
|
+
again. Its message is "Gemini's reply could not be read: it was not JSON (text/html). A proxy or
|
|
891
|
+
gateway may have answered in its place.", or the same with "The model's" or "Claude's". A body
|
|
892
|
+
under another type that starts with more than 65,536 characters of white space is read as JSON,
|
|
893
|
+
whatever follows.
|
|
894
|
+
- An empty body of HTTP 200, `new Response("")`: kind `unreachable`, status 0, "Gemini could not
|
|
895
|
+
be reached (the reply was empty)." (or "The model could not…", "Claude could not…"), sent again
|
|
896
|
+
as a reply cut off on its way.
|
|
897
|
+
- A stream with one event longer than 64,000,000 characters: kind `invalid`, status 200, "The
|
|
898
|
+
model's reply could not be read: an event of its stream held more than 64,000,000 characters.",
|
|
899
|
+
not sent again.
|
|
900
|
+
|
|
901
|
+
All three error classes extend `ModelRequestError`, with the same `status` and `kind`. A
|
|
902
|
+
`Retry-After` header on an error reply is the wait the loop takes before it sends the request
|
|
903
|
+
again; a wait longer than `retry.maxDelayMs` (60,000 ms by default) is not taken, and the error is
|
|
904
|
+
thrown.
|
|
905
|
+
|
|
906
|
+
All three adapters can read a whole file in parts, so `analyze_whole_document` is offered, and its
|
|
907
|
+
part reads go through the same `fetch`. Pass `wholeDocumentAnalysis: false` to `askWithFiles` or
|
|
908
|
+
`askGemini` when a test is not about it. A part read that fails is told to the model by the kind
|
|
909
|
+
and status of its error (`The model was busy (HTTP 429).`), never by the words of the fake's error
|
|
910
|
+
body; a part read whose reply has no text gives `The model returned no text (SAFETY).`, with the
|
|
911
|
+
provider's reason when it is a plain word. The adapters' options are in the reference:
|
|
912
|
+
[gemini](../reference/gemini.md), [openai](../reference/openai.md),
|
|
913
|
+
[anthropic](../reference/anthropic.md).
|
|
914
|
+
|
|
915
|
+
### Recorded replies
|
|
916
|
+
|
|
917
|
+
Writing a provider's JSON by hand is fine for a few replies. For the real shapes (thought
|
|
918
|
+
signatures, finish reasons, usage), record what a real model sends once, and replay it. Save this as
|
|
919
|
+
`test/record.ts`:
|
|
920
|
+
|
|
921
|
+
```ts
|
|
922
|
+
// test/record.ts: save the replies of a real model once, and replay them in tests.
|
|
923
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
924
|
+
import { dirname } from "node:path";
|
|
925
|
+
|
|
926
|
+
type Recording = { status: number; contentType: string; body: string };
|
|
927
|
+
|
|
928
|
+
/** A fetch that calls the real one and saves each reply to `${prefix}-1.json`, `${prefix}-2.json`, … */
|
|
929
|
+
export function recordingFetch(prefix: string, real: typeof fetch = fetch): typeof fetch {
|
|
930
|
+
let count = 0;
|
|
931
|
+
return (async (input: string | URL | Request, init?: RequestInit) => {
|
|
932
|
+
const response = await real(input, init);
|
|
933
|
+
const file = `${prefix}-${++count}.json`;
|
|
934
|
+
// Waits for the whole body: a stream is recorded whole, and passed on once it is.
|
|
935
|
+
const recording: Recording = { status: response.status, contentType: response.headers.get("content-type") ?? "", body: await response.clone().text() };
|
|
936
|
+
// An error thrown here would reach the adapter as a failed connection, and the request would be
|
|
937
|
+
// sent again: make the folder first.
|
|
938
|
+
await mkdir(dirname(file), { recursive: true });
|
|
939
|
+
await writeFile(file, JSON.stringify(recording, null, 2));
|
|
940
|
+
return response;
|
|
941
|
+
}) as typeof fetch;
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
/**
|
|
945
|
+
* A recorded reply as a Response for `fakeFetch`. Document IDs are new on every ingest, so the
|
|
946
|
+
* IDs in a recorded tool call are replaced with `documentId`, the one the test ingested.
|
|
947
|
+
*/
|
|
948
|
+
export async function replay(file: string, documentId?: string): Promise<Response> {
|
|
949
|
+
const recording = JSON.parse(await readFile(file, "utf8")) as Recording;
|
|
950
|
+
const body = documentId ? recording.body.replace(/doc_[a-f0-9]{32}/g, documentId) : recording.body;
|
|
951
|
+
return new Response(body, { status: recording.status, headers: { "Content-Type": recording.contentType } });
|
|
952
|
+
}
|
|
953
|
+
```
|
|
954
|
+
|
|
955
|
+
Record in a live run, then replay in the test:
|
|
956
|
+
|
|
957
|
+
```ts
|
|
958
|
+
import { askWithFiles } from "llm-large-files";
|
|
959
|
+
import { gemini, vertexAi } from "llm-large-files/gemini";
|
|
960
|
+
import { fakeFetch } from "./fake-fetch.js";
|
|
961
|
+
import { recordingFetch, replay } from "./record.js";
|
|
962
|
+
|
|
963
|
+
// Assumes `files` and `meta` (a test document, as in largeLog()), and a real `endpoint`
|
|
964
|
+
// (vertexAi() with your credentials) for the live run.
|
|
965
|
+
const question = [{ role: "user" as const, text: "How many payments failed?" }];
|
|
966
|
+
|
|
967
|
+
// Once, in a live run: the real model, with each reply saved.
|
|
968
|
+
const live = gemini(endpoint, { fetch: recordingFetch("test/recordings/payments") });
|
|
969
|
+
await askWithFiles({ files, model: live, documentIds: [meta.id], messages: question, wholeDocumentAnalysis: false });
|
|
970
|
+
|
|
971
|
+
// In the test: the same replies from the files, with the document ID of this run.
|
|
972
|
+
const api = fakeFetch([
|
|
973
|
+
await replay("test/recordings/payments-1.json", meta.id),
|
|
974
|
+
await replay("test/recordings/payments-2.json", meta.id),
|
|
975
|
+
]);
|
|
976
|
+
// A fixed token, so the test needs no credentials. Use the live run's model name, so that
|
|
977
|
+
// usage.byModel keeps its key.
|
|
978
|
+
const testEndpoint = vertexAi({ project: "test-project", model: "gemini-3.5-flash-lite", accessToken: "test-token" });
|
|
979
|
+
const model = gemini(testEndpoint, { fetch: api.fetch });
|
|
980
|
+
const result = await askWithFiles({ files, model, documentIds: [meta.id], messages: question, wholeDocumentAnalysis: false });
|
|
981
|
+
```
|
|
982
|
+
|
|
983
|
+
- Give `fakeFetch` one `replay` for each file the live run wrote (`payments-1.json`,
|
|
984
|
+
`payments-2.json`, …), in order: a request that was sent again is a file too. With fewer, the
|
|
985
|
+
last reply repeats for the rest, and the run differs from the recorded one without an error.
|
|
986
|
+
- Replay with the same options you recorded with. With `onText`, a Gemini request goes to the
|
|
987
|
+
stream URL and needs a recorded stream; with whole-file reads on, their part reads take replies
|
|
988
|
+
of their own, in an order that is not fixed.
|
|
989
|
+
- The replay swaps every document ID in the recording for the one ID given: it suits a test of one
|
|
990
|
+
document.
|
|
991
|
+
- A recording holds what the model wrote, and only the replies: no request, no token. Record with
|
|
992
|
+
test documents, not your users' files.
|
|
993
|
+
|
|
994
|
+
### Timers
|
|
995
|
+
|
|
996
|
+
With fake timers (`vi.useFakeTimers()`), the library's waits are timers too. A retry waits with
|
|
997
|
+
`setTimeout` unless you pass `retry.sleep`. A real adapter starts a timer of `firstByteTimeoutMs`
|
|
998
|
+
(600,000 ms by default) for each request, and one of `idleTimeoutMs` (300,000 ms) between the pieces
|
|
999
|
+
of a reply: a test that moves the clock that far aborts the request as a model that went silent.
|
|
1000
|
+
Pass `firstByteTimeoutMs: 0` and `idleTimeoutMs: 0` to such an adapter, or to `askGemini`: 0 waits
|
|
1001
|
+
without end. The waits themselves are in [Errors and reliability](./errors-and-reliability.md).
|
|
1002
|
+
|
|
1003
|
+
## Expiry, owners and the clock
|
|
1004
|
+
|
|
1005
|
+
`createLargeFiles` takes a `now` option, a clock for its expiry checks and `sweep`. Give the store
|
|
1006
|
+
the same clock: `MemoryDocumentStore` and `FileDocumentStore` take `now` too, and check expiry by
|
|
1007
|
+
their own clock when they read a document. A library clock set in the past, next to a store on the
|
|
1008
|
+
real clock, loses its documents at the first read: the store finds them expired by its own clock
|
|
1009
|
+
and deletes them.
|
|
1010
|
+
|
|
1011
|
+
```ts
|
|
1012
|
+
// test/expiry.test.ts
|
|
1013
|
+
import { describe, expect, it } from "vitest";
|
|
1014
|
+
import { askWithFiles, createLargeFiles, DocumentsNotFoundError, MemoryDocumentStore } from "llm-large-files";
|
|
1015
|
+
import { bytes, fakeModel, says } from "./fake-model.js";
|
|
1016
|
+
|
|
1017
|
+
describe("documents that expire", () => {
|
|
1018
|
+
it("are gone after their time to live, and swept from the store", async () => {
|
|
1019
|
+
let clock = new Date("2026-01-01T09:00:00Z");
|
|
1020
|
+
const now = () => clock;
|
|
1021
|
+
// One clock for both: the library checks expiry by its clock, and the store by its own when it reads.
|
|
1022
|
+
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" });
|
|
1024
|
+
expect(meta.expiresAt).toBe("2026-01-01T10:00:00.000Z");
|
|
1025
|
+
// Another user cannot delete it.
|
|
1026
|
+
expect(await files.delete(meta.id, { owner: "bob" })).toBe(false);
|
|
1027
|
+
|
|
1028
|
+
clock = new Date("2026-01-01T09:59:00Z");
|
|
1029
|
+
expect(await files.getMeta(meta.id, { owner: "alice" })).toBeDefined();
|
|
1030
|
+
|
|
1031
|
+
clock = new Date("2026-01-01T10:00:00Z");
|
|
1032
|
+
expect(await files.sweep()).toBe(1);
|
|
1033
|
+
const model = fakeModel([says("never sent")]);
|
|
1034
|
+
await expect(askWithFiles({ files, model, documentIds: [meta.id], owner: "alice", messages: [{ role: "user", text: "?" }] }))
|
|
1035
|
+
.rejects.toBeInstanceOf(DocumentsNotFoundError);
|
|
1036
|
+
expect(model.requests).toHaveLength(0);
|
|
1037
|
+
});
|
|
1038
|
+
});
|
|
1039
|
+
```
|
|
1040
|
+
|
|
1041
|
+
- A document expires at `expiresAt` exactly: at 10:00 it is gone.
|
|
1042
|
+
- `files.sweep()` passes the library's clock to the store's `sweep`, and returns how many documents
|
|
1043
|
+
it removed.
|
|
1044
|
+
- Owners need no clock: ingest with `owner`, then ask with another one, as in
|
|
1045
|
+
[Errors](#errors). The question fails with `DocumentsNotFoundError` before any model request, the
|
|
1046
|
+
same error as for a document that expired.
|
|
1047
|
+
- `files.delete(id, { owner })` returns `false`, and deletes nothing, for a document of another
|
|
1048
|
+
owner; for the document's own owner it returns `true`.
|
|
1049
|
+
|
|
1050
|
+
To test your own `DocumentStore`, run the same tests against it. The contract is in
|
|
1051
|
+
[Storage](./storage.md).
|
|
1052
|
+
|
|
1053
|
+
## Your routes
|
|
1054
|
+
|
|
1055
|
+
The handlers of `llm-large-files/node` take Node's own request and response, so a test can run them
|
|
1056
|
+
on a real HTTP server, on a free port, and call them with `fetch`. Mount them as your server does;
|
|
1057
|
+
this one routes `POST /api/documents` to `upload`, and `GET` and `DELETE /api/documents/:id` to
|
|
1058
|
+
`get` and `remove`:
|
|
1059
|
+
|
|
1060
|
+
```ts
|
|
1061
|
+
// test/routes.test.ts
|
|
1062
|
+
import { createServer, type Server } from "node:http";
|
|
1063
|
+
import type { AddressInfo } from "node:net";
|
|
1064
|
+
import { afterEach, describe, expect, it } from "vitest";
|
|
1065
|
+
import { createLargeFiles, MemoryDocumentStore } from "llm-large-files";
|
|
1066
|
+
import { createDocumentHandlers } from "llm-large-files/node";
|
|
1067
|
+
|
|
1068
|
+
let server: Server | undefined;
|
|
1069
|
+
afterEach(() => new Promise<void>((resolve) => (server ? server.close(() => resolve()) : resolve())));
|
|
1070
|
+
|
|
1071
|
+
/** Starts the routes on a free port, and returns their base URL. */
|
|
1072
|
+
async function start(): Promise<string> {
|
|
1073
|
+
const files = createLargeFiles({ store: new MemoryDocumentStore() });
|
|
1074
|
+
// In the test, the user is a header. Your server takes it from its session.
|
|
1075
|
+
const documents = createDocumentHandlers(files, {
|
|
1076
|
+
getOwner: (request) => (request.headers["x-user"] as string | undefined) || undefined,
|
|
1077
|
+
});
|
|
1078
|
+
server = createServer((request, response) => {
|
|
1079
|
+
const url = new URL(request.url ?? "/", "http://localhost");
|
|
1080
|
+
const id = url.pathname.split("/")[3] ?? "";
|
|
1081
|
+
if (request.method === "POST" && url.pathname === "/api/documents") return void documents.upload(request, response);
|
|
1082
|
+
if (request.method === "GET" && id) return void documents.get(request, response, id);
|
|
1083
|
+
if (request.method === "DELETE" && id) return void documents.remove(request, response, id);
|
|
1084
|
+
response.statusCode = 404;
|
|
1085
|
+
response.end();
|
|
1086
|
+
});
|
|
1087
|
+
// Port 0: the system picks a free port, so test files can run side by side.
|
|
1088
|
+
await new Promise<void>((resolve) => server!.listen(0, "127.0.0.1", resolve));
|
|
1089
|
+
return `http://127.0.0.1:${(server!.address() as AddressInfo).port}/api/documents`;
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
describe("the upload routes", () => {
|
|
1093
|
+
it("keeps an upload to its owner", async () => {
|
|
1094
|
+
const base = await start();
|
|
1095
|
+
const upload = await fetch(base, {
|
|
1096
|
+
method: "POST",
|
|
1097
|
+
headers: { "X-File-Name": "notes.md", "X-User": "alice" },
|
|
1098
|
+
body: "# Notes\n\nThe code word is heron.",
|
|
1099
|
+
});
|
|
1100
|
+
expect(upload.status).toBe(201);
|
|
1101
|
+
const { id } = (await upload.json()) as { id: string };
|
|
1102
|
+
|
|
1103
|
+
const asBob = await fetch(`${base}/${id}`, { headers: { "X-User": "bob" } });
|
|
1104
|
+
expect(asBob.status).toBe(404);
|
|
1105
|
+
expect(await asBob.json()).toEqual({ error: "This file is no longer available." });
|
|
1106
|
+
expect((await fetch(`${base}/${id}`, { headers: { "X-User": "alice" } })).status).toBe(200);
|
|
1107
|
+
const deleted = await fetch(`${base}/${id}`, { method: "DELETE", headers: { "X-User": "bob" } });
|
|
1108
|
+
expect(await deleted.json()).toEqual({ deleted: false });
|
|
1109
|
+
});
|
|
1110
|
+
});
|
|
1111
|
+
```
|
|
1112
|
+
|
|
1113
|
+
The other statuses (400 for a file without a name, 413 for one over `maxUploadBytes`, 422 for one
|
|
1114
|
+
that cannot be read) are in the [`llm-large-files/node` reference](../reference/node.md).
|
|
1115
|
+
|
|
1116
|
+
The `|| undefined` in `getOwner` matters. With it, a header that arrives empty (`"X-User": ""`)
|
|
1117
|
+
makes the upload anonymous: it is answered `201`, and anyone who has its ID can read it. With
|
|
1118
|
+
`?? ""` in its place, the same upload is answered 500
|
|
1119
|
+
`{ "error": "Upload failed (empty owner)." }` before its body is read. Test what your sign-in
|
|
1120
|
+
hands `getOwner` when there is no user, and throw an error with `status: 401` there if every
|
|
1121
|
+
upload needs a user ([A web app](./web-app.md#who-owns-an-upload-getowner)).
|
|
1122
|
+
|
|
1123
|
+
An answer route is tested the same way: give it `fakeModel()` where it would take the real model,
|
|
1124
|
+
and read what it sends back with `fetch`. How such a route streams the answer is in
|
|
1125
|
+
[A web app](./web-app.md).
|
|
1126
|
+
|
|
1127
|
+
## Live tests, few and cheap
|
|
1128
|
+
|
|
1129
|
+
Fakes test your code. Only a real model tells you whether it picks the right tool and finds the
|
|
1130
|
+
answer in your files, and every run costs money and time and gives a slightly different answer.
|
|
1131
|
+
Keep live tests few:
|
|
1132
|
+
|
|
1133
|
+
- **Out of the default run.** Skip them unless a variable is set, and run them on demand, before a
|
|
1134
|
+
release, or on a schedule.
|
|
1135
|
+
- **Cheap.** One small model, one small document, `wholeDocumentAnalysis: false`, and ceilings in
|
|
1136
|
+
`limits`: once a question has used `inputTokens` input tokens, or is one request short of
|
|
1137
|
+
`requests`, no more tools run and the next request is the answer. See
|
|
1138
|
+
[Costs and limits](./costs-and-limits.md).
|
|
1139
|
+
- **Loose.** Check that there is an answer and that it holds the fact, not its wording.
|
|
1140
|
+
- **Measured.** Log `result.usage`, so you see what a run costs.
|
|
1141
|
+
- **Useful twice.** Record the replies of a run that went well, and replay them in a fast test
|
|
1142
|
+
([Recorded replies](#recorded-replies)).
|
|
1143
|
+
|
|
1144
|
+
```ts
|
|
1145
|
+
// test/vertex.live.test.ts
|
|
1146
|
+
import { describe, expect, it } from "vitest";
|
|
1147
|
+
import { GoogleAuth } from "google-auth-library";
|
|
1148
|
+
import { askWithFiles, createLargeFiles, MemoryDocumentStore } from "llm-large-files";
|
|
1149
|
+
import { gemini, vertexAi } from "llm-large-files/gemini";
|
|
1150
|
+
import { appLog, bytes } from "./fake-model.js";
|
|
1151
|
+
|
|
1152
|
+
// Skipped unless LIVE_TESTS=1 is set: the default test run never calls a model.
|
|
1153
|
+
describe.skipIf(process.env.LIVE_TESTS !== "1")("live: Gemini on Vertex AI", () => {
|
|
1154
|
+
it("finds the failed payments in a log", async () => {
|
|
1155
|
+
const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
|
|
1156
|
+
const model = gemini(vertexAi({
|
|
1157
|
+
project: process.env.GOOGLE_CLOUD_PROJECT!,
|
|
1158
|
+
location: "global",
|
|
1159
|
+
model: process.env.LIVE_MODEL ?? "gemini-3.5-flash-lite",
|
|
1160
|
+
accessToken: async () => {
|
|
1161
|
+
const token = await auth.getAccessToken();
|
|
1162
|
+
if (!token) throw new Error("No access token from the application default credentials.");
|
|
1163
|
+
return token;
|
|
1164
|
+
},
|
|
1165
|
+
}));
|
|
1166
|
+
const files = createLargeFiles({ store: new MemoryDocumentStore(), budget: { inlineTokens: 1_000 } });
|
|
1167
|
+
const meta = await files.ingest({ name: "app.log", bytes: bytes(appLog(400)) });
|
|
1168
|
+
|
|
1169
|
+
const result = await askWithFiles({
|
|
1170
|
+
files, model, documentIds: [meta.id],
|
|
1171
|
+
messages: [{ role: "user", text: "How many payments failed? Answer with the number." }],
|
|
1172
|
+
wholeDocumentAnalysis: false,
|
|
1173
|
+
// Ceilings: a model that keeps calling tools cannot run up a bill.
|
|
1174
|
+
limits: { toolTurns: 4, requests: 5, inputTokens: 50_000 },
|
|
1175
|
+
});
|
|
1176
|
+
|
|
1177
|
+
// Loose checks: a real model words its answer its own way.
|
|
1178
|
+
expect(result.answered).toBe(true);
|
|
1179
|
+
expect(result.text).toMatch(/\b8\b/);
|
|
1180
|
+
expect(result.steps.length).toBeGreaterThan(0);
|
|
1181
|
+
console.log("live usage", result.usage);
|
|
1182
|
+
}, 120_000);
|
|
1183
|
+
});
|
|
1184
|
+
```
|
|
1185
|
+
|
|
1186
|
+
The credentials are the application default credentials, as on your servers: see
|
|
1187
|
+
[Gemini and Vertex AI](./vertex-and-gemini.md). For another provider, swap the adapter:
|
|
1188
|
+
[OpenAI-compatible endpoints](./openai-compatible.md), [Claude](./anthropic.md).
|
|
1189
|
+
|
|
1190
|
+
## Reference
|
|
1191
|
+
|
|
1192
|
+
- [`ModelAdapter`](../reference/ask.md#modeladapter), [`ModelRequest`](../reference/ask.md#modelrequest),
|
|
1193
|
+
[`AskResult`](../reference/ask.md#askresult), [`AskLimits`](../reference/ask.md#asklimits) and
|
|
1194
|
+
`partialResultOf`: [the tool loop and the adapter contract](../reference/ask.md).
|
|
1195
|
+
- [`ModelRequestError`](../reference/errors-and-retries.md#modelrequesterror),
|
|
1196
|
+
[`RetryOptions`](../reference/errors-and-retries.md#retryoptions) and `errorKindOf`:
|
|
1197
|
+
[errors, retries, streams](../reference/errors-and-retries.md).
|
|
1198
|
+
- [`MemoryDocumentStore`](../reference/library.md#memorydocumentstore) and the `now` option of
|
|
1199
|
+
[`LargeFilesOptions`](../reference/library.md#largefilesoptions):
|
|
1200
|
+
[the library and its documents](../reference/library.md).
|
|
1201
|
+
- The tools a script can call, with their arguments and results: [tools](../reference/tools.md).
|
|
1202
|
+
- The upload routes, their requests and statuses: [`llm-large-files/node`](../reference/node.md).
|
|
1203
|
+
- Streaming answers to a browser: [A web app](./web-app.md).
|