llm-large-files 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1402 -467
- package/README.md +188 -60
- package/dist/analyze.d.ts +5 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +96 -47
- 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 +190 -39
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +60 -4
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +1068 -206
- package/dist/ask.js.map +1 -1
- 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 +4 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +15 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +333 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +159 -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 +3 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +35 -3
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +626 -58
- 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 +108 -61
- 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/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 +13 -7
- 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/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 +11 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -4
- 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 +405 -85
- package/dist/library.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 +182 -1
- 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 +122 -20
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -0
- package/dist/node/index.js.map +1 -1
- 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/openai/adapter.d.ts +29 -5
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +311 -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 +275 -14
- 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/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/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 +8 -2
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +60 -10
- 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 +6 -0
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +25 -8
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +62 -2
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +314 -14
- 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 +269 -42
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +102 -3
- package/dist/types.d.ts.map +1 -1
- 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 +726 -0
- package/docs/guides/deployment.md +654 -0
- package/docs/guides/errors-and-reliability.md +735 -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 +971 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1199 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1589 -0
- package/docs/how-it-works.md +1012 -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 +892 -0
- package/docs/reference/errors-and-retries.md +758 -0
- package/docs/reference/events.md +993 -0
- package/docs/reference/gemini.md +823 -0
- package/docs/reference/library.md +1467 -0
- package/docs/reference/node.md +528 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +883 -0
- package/docs/security.md +897 -103
- package/docs/troubleshooting.md +1390 -0
- package/package.json +2 -2
- package/src/analyze.ts +93 -42
- package/src/anthropic/adapter.ts +196 -39
- package/src/ask.ts +1087 -202
- package/src/encoding.ts +850 -0
- package/src/errors.ts +17 -0
- package/src/events.ts +442 -0
- package/src/evidence.ts +5 -2
- package/src/extract.ts +602 -62
- package/src/gemini/adapter.ts +118 -65
- package/src/gemini/chat.ts +28 -4
- package/src/gemini/errors.ts +34 -1
- package/src/gemini/generate.ts +23 -10
- package/src/gemini/index.ts +3 -3
- package/src/gemini/sse.ts +1 -1
- package/src/http.ts +376 -1
- package/src/index.ts +27 -5
- package/src/library.ts +459 -85
- package/src/map-reduce.ts +252 -51
- package/src/model.ts +236 -3
- package/src/node/handlers.ts +137 -22
- package/src/node/index.ts +2 -0
- package/src/node/sse.ts +198 -0
- package/src/openai/adapter.ts +306 -38
- package/src/output-limit.ts +44 -8
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +268 -15
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/plan.ts +68 -12
- package/src/retry.ts +49 -5
- package/src/search.ts +63 -10
- package/src/sse.ts +153 -28
- package/src/stores.ts +5 -2
- package/src/text-index.ts +26 -7
- package/src/text.ts +323 -13
- package/src/tools.ts +261 -42
- package/src/types.ts +107 -4
- package/src/zip-directory.ts +136 -0
|
@@ -0,0 +1,726 @@
|
|
|
1
|
+
# Costs and limits
|
|
2
|
+
|
|
3
|
+
This guide is for you if you need to bound what one question may spend, or to count what it did
|
|
4
|
+
spend. It covers the limits of a question, the budget that decides what goes into each request, the
|
|
5
|
+
usage a question reports, cost per user or per chat session, and the features that cost most. Every
|
|
6
|
+
field and default is in the reference: [`AskLimits`](../reference/ask.md#asklimits),
|
|
7
|
+
[`AskResult`](../reference/ask.md#askresult) and [`Budget`](../reference/library.md#budget).
|
|
8
|
+
|
|
9
|
+
## Where the tokens go
|
|
10
|
+
|
|
11
|
+
One question is a chain of model requests:
|
|
12
|
+
|
|
13
|
+
- **Chat requests.** Each one carries your system instruction and the tool guide, the conversation,
|
|
14
|
+
the documents sent whole (or a card for each document that is searched), the tool declarations,
|
|
15
|
+
and every tool result of the question so far. So each request of the tool loop is larger than the
|
|
16
|
+
one before, and the documents sent whole are read again by every request.
|
|
17
|
+
- **Part reads.** A whole-file read (`analyze_whole_document`) sends the file to the model in parts,
|
|
18
|
+
one request each, then writes an answer from their notes. When the notes together are larger
|
|
19
|
+
than one part, it merges them first.
|
|
20
|
+
- **Pages.** A page that `view_pages` showed stays in every later request of the question.
|
|
21
|
+
|
|
22
|
+
The last request writes the answer. A question about documents that are sent whole, with no pages to
|
|
23
|
+
look at, is a single request. [How it works](../how-it-works.md) has the details.
|
|
24
|
+
|
|
25
|
+
## The limits of a question
|
|
26
|
+
|
|
27
|
+
`limits` of `askWithFiles` and `askGemini` bounds one question, whatever the model decides to do:
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
import { GoogleAuth } from "google-auth-library";
|
|
31
|
+
import { createLargeFiles, FileDocumentStore } from "llm-large-files";
|
|
32
|
+
import { askGemini, vertexAi } from "llm-large-files/gemini";
|
|
33
|
+
|
|
34
|
+
const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
|
|
35
|
+
const endpoint = vertexAi({
|
|
36
|
+
project: process.env.GOOGLE_CLOUD_PROJECT!,
|
|
37
|
+
location: process.env.GOOGLE_CLOUD_LOCATION ?? "global",
|
|
38
|
+
model: "gemini-3.8-flash",
|
|
39
|
+
explorerModel: process.env.GEMINI_EXPLORER_MODEL, // optional: a cheaper model searches and reads
|
|
40
|
+
accessToken: async () => (await auth.getAccessToken())!,
|
|
41
|
+
});
|
|
42
|
+
const files = createLargeFiles({ store: new FileDocumentStore("./data/large-files") });
|
|
43
|
+
|
|
44
|
+
export async function ask(userId: string, documentIds: string[], question: string) {
|
|
45
|
+
const result = await askGemini({
|
|
46
|
+
files,
|
|
47
|
+
endpoint,
|
|
48
|
+
owner: userId,
|
|
49
|
+
documentIds,
|
|
50
|
+
messages: [{ role: "user", text: question }],
|
|
51
|
+
limits: {
|
|
52
|
+
toolTurns: 8, // at most 8 chat requests, the answer included, plus one when the answer comes back without text
|
|
53
|
+
callsPerTurn: 6, // at most 6 tool calls run in one turn
|
|
54
|
+
wholeDocumentReads: 1, // each document is read whole once at most (the default)
|
|
55
|
+
inputTokens: 1_500_000, // no more tools once the question has used this many input tokens
|
|
56
|
+
requests: 30, // chat requests and part reads together
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
console.log(result.turns, result.usage);
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
| Limit | Default | What it counts | When it is reached |
|
|
65
|
+
|---|---|---|---|
|
|
66
|
+
| `toolTurns` | 12 | Chat requests of the question: the answer and the second tries after an empty or broken turn included. The second try of the answer itself, when it came back without text, can be one request past it. | The last request must be answered in text (`toolChoice: "none"`; Gemini gets no tools declared, the other adapters keep them listed). |
|
|
67
|
+
| `callsPerTurn` | 8 | Tool calls of one model turn that are run. | Each call past it is answered "Not run: one turn runs at most 8 tool calls. Send this call again if you still need it." |
|
|
68
|
+
| `wholeDocumentReads` | 1 | Whole-file reads of each document. | A read past it is answered with an error that tells the model to use the answer it already has. 0 refuses every read. |
|
|
69
|
+
| `inputTokens` | none | Input tokens of the question: every chat request and part read, of every model. | No more tools run: the next request is the answer. A whole-file read that would pass it is refused before it starts. |
|
|
70
|
+
| `requests` | none | Answered requests of the question: chat requests and part reads together. | Once one request is left, no more tools run, and that request is the answer. A whole-file read that would pass it is refused before it starts. |
|
|
71
|
+
|
|
72
|
+
**No limit throws.** A question that reaches a limit ends with a request for the answer, written
|
|
73
|
+
from what the tools returned so far. That request usually ends with `FINAL_ANSWER_REQUEST`: "Stop
|
|
74
|
+
using tools now. Answer my question using only what the tools returned above, with line citations.
|
|
75
|
+
Say plainly what you could not find." When no tool ran (for example with `toolTurns: 1` or
|
|
76
|
+
`requests: 1`), it ends with `FINAL_ANSWER_WITHOUT_TOOLS` instead. When pages were the only thing
|
|
77
|
+
to look at, it ends with `FINAL_ANSWER_AFTER_PAGES`. `answered` is true when the reply has text and
|
|
78
|
+
was not refused.
|
|
79
|
+
|
|
80
|
+
- **The answer is asked for once more when it comes back without text**: empty, or with a tool call
|
|
81
|
+
the model was told not to make. The note "Your last reply had no text. No tool can be called in
|
|
82
|
+
this reply: write the answer now, in text, from what is above." goes at the end of that one
|
|
83
|
+
request. It is one of the two second tries a question may make, and it can be one request past
|
|
84
|
+
`toolTurns`. It is not made after a refusal, a filter or a reply cut off at the output limit with
|
|
85
|
+
nothing in it, nor once `requests` or `inputTokens` is reached: those two are never passed by
|
|
86
|
+
it. With `toolTurns: 8`, a question makes at most 9 answered chat requests; to cap them exactly,
|
|
87
|
+
set `requests`.
|
|
88
|
+
- Each tool result carries `tool_turns_left`, so the model can see its turns run out and stop
|
|
89
|
+
searching in time. The results of an earlier question, passed back in `messages`, are sent
|
|
90
|
+
without it ([Conversations](./conversations.md#what-toolturns-holds)).
|
|
91
|
+
- A model that answers in text before a limit is reached ends the question there.
|
|
92
|
+
- The result does not say that a limit ended the question, and `steps` has no line for it. When
|
|
93
|
+
`result.turns` reaches `toolTurns`, the model was most likely still calling tools when its turns
|
|
94
|
+
ran out. `result.usage` shows how close the question came to `inputTokens` and `requests`.
|
|
95
|
+
- With an explorer model, the limits count the work of both models together. The answer is always
|
|
96
|
+
a request of its own, so the explorer has at most `toolTurns − 1` requests
|
|
97
|
+
([explorer model](./explorer-model.md)).
|
|
98
|
+
- `maxToolTurns` and `maxToolCallsPerTurn` of `askGemini` are `toolTurns` and `callsPerTurn` under
|
|
99
|
+
their names from before 0.5.0. When both are given, `limits` wins.
|
|
100
|
+
|
|
101
|
+
### `inputTokens` and `requests` are checked between turns
|
|
102
|
+
|
|
103
|
+
- **They are checked before each tool turn**, against what the question has used so far. The
|
|
104
|
+
request that crosses `inputTokens` has already been sent: its tool calls run, and then the answer
|
|
105
|
+
is asked for. So a question can pass `inputTokens` by about two requests: the one that crossed
|
|
106
|
+
it, and the answer, which reads everything the tools returned. Set the ceiling that far below
|
|
107
|
+
what must not be passed.
|
|
108
|
+
- **`requests` keeps one request for the answer**, so the answer stays within it.
|
|
109
|
+
- **A whole-file read is reckoned before it starts.** In input tokens, it is the size of the file
|
|
110
|
+
in the tokens of the model that reads it. In requests, it is its parts, one merge of their notes,
|
|
111
|
+
its answer, and the answer of the question. A read that does not fit what is left is not run, and
|
|
112
|
+
costs nothing. The model gets the reason, for example: "Not run: reading all of app.log takes
|
|
113
|
+
about 2,400,000 input tokens, and 900,000 are left of the 1,500,000 this question may use. Use
|
|
114
|
+
search_document and read_document." Reads let through in the same turn share what is left. A read
|
|
115
|
+
whose notes need more than one merge can pass `requests` by those merges.
|
|
116
|
+
- **A request that failed and was sent again counts once**, as it does in `usage`.
|
|
117
|
+
|
|
118
|
+
### Tools you can leave out
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
import { askGemini } from "llm-large-files/gemini";
|
|
122
|
+
|
|
123
|
+
// files and endpoint as in the first sample. documentIds and question are yours.
|
|
124
|
+
const result = await askGemini({
|
|
125
|
+
files,
|
|
126
|
+
endpoint,
|
|
127
|
+
documentIds,
|
|
128
|
+
messages: [{ role: "user", text: question }],
|
|
129
|
+
wholeDocumentAnalysis: false, // no analyze_whole_document: no part reads
|
|
130
|
+
viewPages: false, // no view_pages: no pages in the requests
|
|
131
|
+
});
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
- **`wholeDocumentAnalysis: false`** leaves `analyze_whole_document` out of the tools of every
|
|
135
|
+
request: the question makes no part reads. A model that explores without `generateText` (the
|
|
136
|
+
explorer when there is one, otherwise `model`) has no whole-file reads either. In both cases the
|
|
137
|
+
tool guide and the cards do not mention whole-file reads.
|
|
138
|
+
- **`limits.wholeDocumentReads: 0`** keeps the tool and refuses every call of it: "Whole-file reads
|
|
139
|
+
are turned off for this question. Use search_document and read_document on app.log." Each refused
|
|
140
|
+
call still takes a place in a turn. Prefer `wholeDocumentAnalysis: false`.
|
|
141
|
+
- **`viewPages: false`** leaves `view_pages` out, and the tool guide does not mention it.
|
|
142
|
+
|
|
143
|
+
Neither changes which documents are sent whole: that is the budget's work.
|
|
144
|
+
|
|
145
|
+
## The budget
|
|
146
|
+
|
|
147
|
+
The budget describes your model connection: how large one request may be, and how it is shared
|
|
148
|
+
between documents, tool results, pages and the answer. The library plans every request with it.
|
|
149
|
+
|
|
150
|
+
### What each field decides
|
|
151
|
+
|
|
152
|
+
| Field | Default | What it decides |
|
|
153
|
+
|---|---|---|
|
|
154
|
+
| `contextTokens` | 1,000,000 | The window a question is planned for. |
|
|
155
|
+
| `maxRequestBytes` | 10,000,000 | The largest request body. It is checked apart from tokens: non-English text and JSON escaping make bytes run ahead of tokens. |
|
|
156
|
+
| `inlineTokens` | half the window, 200,000 at most | The most document text sent whole in one request. Lower it to send fewer documents whole; raise it to rely on the long context more. |
|
|
157
|
+
| `reservedTokens` | a quarter of the window, 64,000 at most | Kept free of documents: for the answer, tool results and a growing history. Text tool results may fill the window up to `contextTokens − reservedTokens / 2`. Pages may take up to half of it. |
|
|
158
|
+
| `mapChunkTokens` | half the window, 100,000 at most | The size of one part of a whole-file read. |
|
|
159
|
+
| `maxMapChunks` | 30 | The most parts of a whole-file read. A file that needs more is not read whole. |
|
|
160
|
+
| `toolResultCharacters` | 12% of the window, from 1,000 to 24,000 | The most characters of one tool result. The answer of a whole-file read may have 40,000, or this many when it is more. |
|
|
161
|
+
|
|
162
|
+
The defaults fit a model with a window of 1M tokens behind a request limit of 10 MB. For a model
|
|
163
|
+
with a smaller window, set `contextTokens`: the fields you leave out follow it.
|
|
164
|
+
|
|
165
|
+
| `contextTokens` | `inlineTokens` | `reservedTokens` | `mapChunkTokens` | `toolResultCharacters` |
|
|
166
|
+
|---|---|---|---|---|
|
|
167
|
+
| 1,000,000 | 200,000 | 64,000 | 100,000 | 24,000 |
|
|
168
|
+
| 200,000 | 100,000 | 50,000 | 100,000 | 24,000 |
|
|
169
|
+
| 128,000 | 64,000 | 32,000 | 64,000 | 15,360 |
|
|
170
|
+
| 32,768 | 16,384 | 8,192 | 16,384 | 3,932 |
|
|
171
|
+
|
|
172
|
+
`maxRequestBytes` and `maxMapChunks` do not follow the window.
|
|
173
|
+
|
|
174
|
+
```ts
|
|
175
|
+
import { createLargeFiles, FileDocumentStore } from "llm-large-files";
|
|
176
|
+
|
|
177
|
+
const files = createLargeFiles({
|
|
178
|
+
store: new FileDocumentStore("./data/large-files"),
|
|
179
|
+
budget: { contextTokens: 128_000, maxRequestBytes: 4_000_000 },
|
|
180
|
+
});
|
|
181
|
+
console.log(files.budget);
|
|
182
|
+
// { contextTokens: 128000, maxRequestBytes: 4000000, inlineTokens: 64000, reservedTokens: 32000,
|
|
183
|
+
// mapChunkTokens: 64000, maxMapChunks: 30, toolResultCharacters: 15360 }
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
- **A field you set stays as you set it**, unless a model's window is smaller than the budget's
|
|
187
|
+
([below](#one-library-several-models)). Then a value too large for that window is lowered:
|
|
188
|
+
`inlineTokens` to the window, `reservedTokens` and `mapChunkTokens` to half of it,
|
|
189
|
+
`toolResultCharacters` to the window (1,000 at least). `maxMapChunks` is never lowered.
|
|
190
|
+
- **Values that cannot work are an error.** A field that is not a number above 0 throws
|
|
191
|
+
"budget.inlineTokens must be a number above 0, and is 0." A `reservedTokens` or `mapChunkTokens`
|
|
192
|
+
at or above `contextTokens` throws, for example, "budget.reservedTokens (200,000) must be smaller
|
|
193
|
+
than budget.contextTokens (128,000): nothing would be left for the conversation."
|
|
194
|
+
`createLargeFiles` throws for the library's budget. `askWithFiles` and `askGemini` throw for the
|
|
195
|
+
`budget` of a question, before any request.
|
|
196
|
+
- **`budget` of `askWithFiles` and `askGemini`** changes fields for one question, such as
|
|
197
|
+
`budget: { inlineTokens: 20_000 }`. The other fields stay the library's.
|
|
198
|
+
|
|
199
|
+
`resolveBudget(partial, limits)` gives the whole budget for any set of fields.
|
|
200
|
+
`files.budgetFor(overrides, limits)` gives the library's budget with `overrides` in place of its
|
|
201
|
+
fields. Both fit the budget to `limits` ([`ModelLimits`](../reference/library.md#modellimits): a
|
|
202
|
+
model's `contextTokens` and `maxRequestBytes`) when those are smaller:
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
import { resolveBudget } from "llm-large-files";
|
|
206
|
+
|
|
207
|
+
resolveBudget({ contextTokens: 200_000 });
|
|
208
|
+
// inlineTokens 100,000 · reservedTokens 50,000 · mapChunkTokens 100,000 · toolResultCharacters 24,000
|
|
209
|
+
|
|
210
|
+
// A value you set that is too large for a model's smaller window is lowered to fit it.
|
|
211
|
+
resolveBudget({ inlineTokens: 300_000 }, { contextTokens: 128_000 });
|
|
212
|
+
// contextTokens 128,000 · inlineTokens 128,000 · reservedTokens 32,000 · mapChunkTokens 64,000
|
|
213
|
+
|
|
214
|
+
// files as in the sample above: the library's budget with fewer parts for a whole-file read.
|
|
215
|
+
files.budgetFor({ maxMapChunks: 10 });
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
### Whole or searched
|
|
219
|
+
|
|
220
|
+
For each question the budget decides which documents go into the prompt whole, and which the model
|
|
221
|
+
reads through the tools. The library takes the size of everything else in the request (your system
|
|
222
|
+
instruction, the conversation and its stored tool rounds, and a margin of 2,000 tokens and 8,000
|
|
223
|
+
bytes), then fills the room that is left, smallest document first:
|
|
224
|
+
|
|
225
|
+
- token room: `min(inlineTokens, contextTokens − reservedTokens − the rest)`
|
|
226
|
+
- byte room: `maxRequestBytes − 256 KB − the rest`
|
|
227
|
+
|
|
228
|
+
A document goes whole when it fits both, after the smaller ones. The others get a card and the
|
|
229
|
+
tools. With the default budget and a short conversation, a log of 150,000 tokens goes whole. Add a
|
|
230
|
+
second log of 80,000 tokens, and the 80,000 go whole while the 150,000 are searched: the two
|
|
231
|
+
together are more than 200,000.
|
|
232
|
+
|
|
233
|
+
The sizes are the library's estimate of tokens (`estimatedTokens` of each document) and the text's
|
|
234
|
+
size in JSON. As the conversation grows, the room for documents shrinks, so a document that went
|
|
235
|
+
whole in the first question of a chat can be searched in a later one. `result.plan` says what
|
|
236
|
+
happened:
|
|
237
|
+
|
|
238
|
+
```ts
|
|
239
|
+
// result: what askWithFiles or askGemini returned.
|
|
240
|
+
console.log("whole:", result.plan.inline.map((meta) => meta.name), result.plan.inlineTokens);
|
|
241
|
+
console.log("searched:", result.plan.searchable.map((meta) => meta.name));
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
### One library, several models
|
|
245
|
+
|
|
246
|
+
The budget of a question is the library's, with the question's `budget` in place of its fields,
|
|
247
|
+
made to fit the models of the question. An adapter says what its model takes in its
|
|
248
|
+
`capabilities` ([`ModelCapabilities`](../reference/ask.md#modelcapabilities)):
|
|
249
|
+
|
|
250
|
+
1. **The window** is the smallest of the budget's `contextTokens` and the `contextTokens` of each
|
|
251
|
+
model. The same goes for `maxRequestBytes`.
|
|
252
|
+
2. **The largest `tokenScale`** of the models divides it. The budget is counted in the library's
|
|
253
|
+
estimate of tokens, which is fitted to Gemini's count. A model whose tokenizer counts more tokens
|
|
254
|
+
for the same text has, in those terms, a smaller window.
|
|
255
|
+
3. **The largest `outputTokens`**, divided the same way, is kept free. A model that counts its reply
|
|
256
|
+
against the window (Claude's `max_tokens`) leaves that much less for the prompt. At least a
|
|
257
|
+
quarter of the window is left.
|
|
258
|
+
4. **The other fields** follow the window that results: those the library left out are worked out
|
|
259
|
+
from it, and those it set are lowered when they are too large for it.
|
|
260
|
+
|
|
261
|
+
What the adapters declare unless you set it:
|
|
262
|
+
|
|
263
|
+
| Adapter | `contextTokens` | `maxRequestBytes` | `tokenScale` | `outputTokens` | `pageTokens` |
|
|
264
|
+
|---|---|---|---|---|---|
|
|
265
|
+
| `gemini()` | only when set | only when set | 1 | none | 530 |
|
|
266
|
+
| `openAiCompatible()` | only when set | only when set | 1, or the option | none | 1,000 (pages need `pdfInput`) |
|
|
267
|
+
| `anthropic()` | only when set | 32,000,000 | 1.35, or the option | `maxTokens`: 64,000 | 3,500 |
|
|
268
|
+
|
|
269
|
+
A model that declares no window gets the library's: 1,000,000 tokens unless you set another. So
|
|
270
|
+
declare the window of every model whose window is smaller.
|
|
271
|
+
|
|
272
|
+
**With `askWithFiles`**, give each adapter its `contextTokens` (and `maxRequestBytes`), and every
|
|
273
|
+
question is planned for the smallest. Here a model on your own server explores for Gemini on
|
|
274
|
+
Vertex AI:
|
|
275
|
+
|
|
276
|
+
```ts
|
|
277
|
+
import { GoogleAuth } from "google-auth-library";
|
|
278
|
+
import { askWithFiles, createLargeFiles, FileDocumentStore } from "llm-large-files";
|
|
279
|
+
import { gemini, vertexAi } from "llm-large-files/gemini";
|
|
280
|
+
import { openAiCompatible } from "llm-large-files/openai";
|
|
281
|
+
|
|
282
|
+
const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
|
|
283
|
+
const files = createLargeFiles({ store: new FileDocumentStore("./data/large-files") });
|
|
284
|
+
|
|
285
|
+
// Writes the answers. Its window: 1,048,576 tokens.
|
|
286
|
+
const flash = gemini(vertexAi({
|
|
287
|
+
project: process.env.GOOGLE_CLOUD_PROJECT!,
|
|
288
|
+
model: "gemini-3.8-flash",
|
|
289
|
+
accessToken: async () => (await auth.getAccessToken())!,
|
|
290
|
+
}), { contextTokens: 1_048_576 });
|
|
291
|
+
|
|
292
|
+
// Searches and reads. Its window: 131,072 tokens, and a tokenizer that counts a fifth more.
|
|
293
|
+
const local = openAiCompatible({
|
|
294
|
+
baseUrl: process.env.LOCAL_LLM_URL!,
|
|
295
|
+
model: process.env.LOCAL_LLM_MODEL!,
|
|
296
|
+
contextTokens: 131_072,
|
|
297
|
+
tokenScale: 1.2,
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
export async function ask(documentIds: string[], question: string) {
|
|
301
|
+
const result = await askWithFiles({ files, model: flash, explorer: local, documentIds, messages: [{ role: "user", text: question }] });
|
|
302
|
+
console.log(result.budget.contextTokens); // 109226: the library's 1,000,000, then 131,072, then / 1.2
|
|
303
|
+
return result;
|
|
304
|
+
}
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
**With `askGemini`**, which makes its models without these numbers, put the window in the
|
|
308
|
+
library's `budget`, or in the `budget` of a question. With an explorer, use the smaller of the two
|
|
309
|
+
windows. [Vertex AI and Gemini](./vertex-and-gemini.md) has the setup.
|
|
310
|
+
|
|
311
|
+
`result.budget` is the budget a question ran with. `files.budgetFor(undefined, { contextTokens })`
|
|
312
|
+
gives the same in advance for a model that declares only a window. With a `tokenScale` or
|
|
313
|
+
`outputTokens`, only `result.budget` has it.
|
|
314
|
+
|
|
315
|
+
A window left too large is often recovered. The first request the provider refuses as too large
|
|
316
|
+
teaches the loop the window it names. Older tool results are shortened, or, when no tool has run
|
|
317
|
+
yet, the documents are planned again ([errors and reliability](./errors-and-reliability.md)). With
|
|
318
|
+
Claude, whose conversation may only grow, only the second works: a refusal after a tool ran is
|
|
319
|
+
thrown, with `kind: "context_overflow"`. So is one that shortening cannot fix. Even a recovery
|
|
320
|
+
costs a refused request and a step the user sees: declare the window instead.
|
|
321
|
+
|
|
322
|
+
### Setting `tokenScale`
|
|
323
|
+
|
|
324
|
+
The documents are planned before the first request, with the scale the adapters declare. During a
|
|
325
|
+
question, the input tokens each provider reports raise the loop's estimate of each request's size,
|
|
326
|
+
and so leave less room, when they are higher than the scale says (up to twice the estimate). The
|
|
327
|
+
latest report counts: a lower one brings the estimate back down, but never below what the scale
|
|
328
|
+
says. A scale set too low makes requests that the provider can refuse as too large. A scale set too
|
|
329
|
+
high leaves part of the window unused.
|
|
330
|
+
|
|
331
|
+
To find the scale of an OpenAI-compatible model, compare its count of a sample of a file like the
|
|
332
|
+
ones your users upload, well inside the model's window (a few thousand lines), with the library's
|
|
333
|
+
estimate. It costs one request, whose reply you do not need:
|
|
334
|
+
|
|
335
|
+
```ts
|
|
336
|
+
import { readFile } from "node:fs/promises";
|
|
337
|
+
import { estimateTokens } from "llm-large-files";
|
|
338
|
+
import { openAiCompatible } from "llm-large-files/openai";
|
|
339
|
+
|
|
340
|
+
const local = openAiCompatible({ baseUrl: process.env.LOCAL_LLM_URL!, model: process.env.LOCAL_LLM_MODEL! });
|
|
341
|
+
const text = (await readFile("sample.log", "utf8")).split("\n").slice(0, 5_000).join("\n");
|
|
342
|
+
const reply = await local.send({ system: "", messages: [{ role: "user", parts: [{ text }] }] });
|
|
343
|
+
console.log((reply.usage?.inputTokens ?? 0) / estimateTokens(text)); // about the tokenScale to set
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
`gemini()` needs no scale. `anthropic()` defaults to 1.35, a cautious guess for Claude's tokenizer
|
|
347
|
+
([Claude](./anthropic.md)).
|
|
348
|
+
|
|
349
|
+
## Usage: what a question used
|
|
350
|
+
|
|
351
|
+
`result.usage` ([`UsageTotals`](../reference/ask.md#usagetotals)) sums every request of the
|
|
352
|
+
question that was answered, part reads included, in all and for each model:
|
|
353
|
+
|
|
354
|
+
| Field | What it counts |
|
|
355
|
+
|---|---|
|
|
356
|
+
| `requests` | Answered requests: chat requests and part reads. A request that failed and was sent again counts once. |
|
|
357
|
+
| `inputTokens` | Every token of the prompts, those read from a cache included. |
|
|
358
|
+
| `cachedInputTokens` | The part of `inputTokens` that was read from the provider's prompt cache. |
|
|
359
|
+
| `outputTokens` | Every token the models wrote, thoughts included. |
|
|
360
|
+
| `thoughtTokens` | The part of `outputTokens` spent thinking, where the provider says. |
|
|
361
|
+
| `byModel` | The same five counts for each model, keyed by the adapter's `id`. |
|
|
362
|
+
|
|
363
|
+
What each provider's numbers become:
|
|
364
|
+
|
|
365
|
+
| | Gemini | OpenAI-compatible | Claude |
|
|
366
|
+
|---|---|---|---|
|
|
367
|
+
| `inputTokens` | `promptTokenCount` + `toolUsePromptTokenCount` | `prompt_tokens` | `input_tokens` + `cache_creation_input_tokens` + `cache_read_input_tokens` |
|
|
368
|
+
| `cachedInputTokens` | `cachedContentTokenCount` | `prompt_tokens_details.cached_tokens`, or DeepSeek's `prompt_cache_hit_tokens` | `cache_read_input_tokens` |
|
|
369
|
+
| `outputTokens` | `candidatesTokenCount` + `thoughtsTokenCount` | `completion_tokens` | `output_tokens` |
|
|
370
|
+
| `thoughtTokens` | `thoughtsTokenCount` | `completion_tokens_details.reasoning_tokens` | 0: not reported |
|
|
371
|
+
|
|
372
|
+
- **Only answered requests are counted.** A request that failed is not, though the provider may
|
|
373
|
+
have billed it: a stream cut off half-way, or a wait on a silent model that ran out. Your
|
|
374
|
+
provider's bill is the record; `usage` is a close account of it.
|
|
375
|
+
- **A request without usage counts with 0 tokens**: an OpenAI-compatible server that sends no
|
|
376
|
+
usage, or a part reader of your own that does not call `onUsage`.
|
|
377
|
+
- **`byModel` is keyed by the adapter's `id`.** For `gemini()` that is the model named in the URL
|
|
378
|
+
(`"gemini-3.8-flash"`); for `openAiCompatible()` and `anthropic()`, the `model` option; for any of
|
|
379
|
+
them, the `id` option when you set it. A part read counts under the model that read it: the
|
|
380
|
+
explorer, when there is one. Two adapters with the same `id` share an entry, so give them their
|
|
381
|
+
own. `askGemini` names its models from their URLs and has no `id` option.
|
|
382
|
+
- **`turns` is not `usage.requests`.** `result.turns` counts the chat requests the question made,
|
|
383
|
+
part reads not included. `usage.requests` counts every answered request.
|
|
384
|
+
- **`lastUsage`** is the provider's own usage object of the last chat request, as it came.
|
|
385
|
+
- **A question that failed** throws. `partialResultOf(error)` gives what it had used until then.
|
|
386
|
+
- **A question planned again**, after the provider refused its first request as too large, counts
|
|
387
|
+
what its first try used.
|
|
388
|
+
|
|
389
|
+
## Cost per user or per session
|
|
390
|
+
|
|
391
|
+
Add `result.usage` to the record of the chat session (or of the user) after each question, and
|
|
392
|
+
multiply by your prices. The library knows no prices: keep a price list for each model `id`, with
|
|
393
|
+
three rates: input not read from the cache, input read from the cache, and output. Thoughts are
|
|
394
|
+
part of `outputTokens`, so do not add `thoughtTokens` on top.
|
|
395
|
+
|
|
396
|
+
This module is the arithmetic. Save it as `usage.ts`:
|
|
397
|
+
|
|
398
|
+
```ts
|
|
399
|
+
import type { ModelUsage, UsageTotals } from "llm-large-files";
|
|
400
|
+
|
|
401
|
+
/** One model's prices per million tokens, from your provider's price list. */
|
|
402
|
+
export type Price = { input: number; cachedInput: number; output: number };
|
|
403
|
+
|
|
404
|
+
/** One model's usage in a session. The model ID is a value, not a field name: IDs hold dots. */
|
|
405
|
+
export type ModelSpend = ModelUsage & { model: string; requests: number };
|
|
406
|
+
|
|
407
|
+
/** The usage part of your session record. */
|
|
408
|
+
export type SessionUsage = { questions: number; failed: number; cost: number; unpriced: string[]; models: ModelSpend[] };
|
|
409
|
+
|
|
410
|
+
export const noUsage = (): SessionUsage => ({ questions: 0, failed: 0, cost: 0, unpriced: [], models: [] });
|
|
411
|
+
|
|
412
|
+
/** What one question cost by your prices, and the models that have no price. */
|
|
413
|
+
export function costOf(usage: UsageTotals, prices: Record<string, Price>): { cost: number; unpriced: string[] } {
|
|
414
|
+
let cost = 0;
|
|
415
|
+
const unpriced: string[] = [];
|
|
416
|
+
for (const [model, used] of Object.entries(usage.byModel)) {
|
|
417
|
+
const price = prices[model];
|
|
418
|
+
if (!price) {
|
|
419
|
+
unpriced.push(model);
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
// inputTokens holds the cached tokens; outputTokens holds the thoughts.
|
|
423
|
+
const fresh = used.inputTokens - used.cachedInputTokens;
|
|
424
|
+
cost += (fresh * price.input + used.cachedInputTokens * price.cachedInput + used.outputTokens * price.output) / 1_000_000;
|
|
425
|
+
}
|
|
426
|
+
return { cost, unpriced };
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** A session's usage with one more question added. */
|
|
430
|
+
export function addUsage(session: SessionUsage, usage: UsageTotals, prices: Record<string, Price>, failed = false): SessionUsage {
|
|
431
|
+
const { cost, unpriced } = costOf(usage, prices);
|
|
432
|
+
const models = session.models.map((spend) => ({ ...spend }));
|
|
433
|
+
for (const [model, used] of Object.entries(usage.byModel)) {
|
|
434
|
+
let spend = models.find((known) => known.model === model);
|
|
435
|
+
if (!spend) {
|
|
436
|
+
spend = { model, requests: 0, inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, thoughtTokens: 0 };
|
|
437
|
+
models.push(spend);
|
|
438
|
+
}
|
|
439
|
+
spend.requests += used.requests;
|
|
440
|
+
spend.inputTokens += used.inputTokens;
|
|
441
|
+
spend.cachedInputTokens += used.cachedInputTokens;
|
|
442
|
+
spend.outputTokens += used.outputTokens;
|
|
443
|
+
spend.thoughtTokens += used.thoughtTokens;
|
|
444
|
+
}
|
|
445
|
+
return {
|
|
446
|
+
questions: session.questions + 1,
|
|
447
|
+
failed: session.failed + (failed ? 1 : 0),
|
|
448
|
+
cost: session.cost + cost,
|
|
449
|
+
unpriced: [...new Set([...session.unpriced, ...unpriced])],
|
|
450
|
+
models,
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
```
|
|
454
|
+
|
|
455
|
+
Then the chat route records what each question used, the failed ones too:
|
|
456
|
+
|
|
457
|
+
```ts
|
|
458
|
+
import { readFile } from "node:fs/promises";
|
|
459
|
+
import { partialResultOf, type ChatTurn, type ToolTurn, type UsageTotals } from "llm-large-files";
|
|
460
|
+
import { askGemini } from "llm-large-files/gemini";
|
|
461
|
+
import { addUsage, noUsage, type Price, type SessionUsage } from "./usage.js";
|
|
462
|
+
|
|
463
|
+
/** Your storage of chat sessions (MongoDB, SQL…): the usage is a field of the session record. */
|
|
464
|
+
export interface Sessions {
|
|
465
|
+
usage(userId: string, sessionId: string): Promise<SessionUsage | undefined>;
|
|
466
|
+
saveUsage(userId: string, sessionId: string, usage: SessionUsage): Promise<void>;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// Your price list, per million tokens: { "gemini-3.8-flash": { "input": …, "cachedInput": …, "output": … }, … }
|
|
470
|
+
const prices = JSON.parse(await readFile("./prices.json", "utf8")) as Record<string, Price>;
|
|
471
|
+
|
|
472
|
+
// files and endpoint as in the first sample. messages: the chat so far, ending with the question.
|
|
473
|
+
export async function answer(sessions: Sessions, userId: string, sessionId: string, documentIds: string[], messages: Array<ChatTurn | ToolTurn>) {
|
|
474
|
+
const record = async (usage: UsageTotals, failed: boolean) => {
|
|
475
|
+
const before = (await sessions.usage(userId, sessionId)) ?? noUsage();
|
|
476
|
+
await sessions.saveUsage(userId, sessionId, addUsage(before, usage, prices, failed));
|
|
477
|
+
};
|
|
478
|
+
try {
|
|
479
|
+
const result = await askGemini({ files, endpoint, owner: userId, documentIds, messages });
|
|
480
|
+
await record(result.usage, false);
|
|
481
|
+
return result;
|
|
482
|
+
} catch (error) {
|
|
483
|
+
// What the question paid for before it failed. Undefined when it failed before its first request.
|
|
484
|
+
const partial = partialResultOf(error);
|
|
485
|
+
if (partial) await record(partial.usage, true);
|
|
486
|
+
throw error;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
- **Failed questions cost too.** `partialResultOf(error)` holds the usage of a question that failed
|
|
492
|
+
once it was under way: a model error (its first request included, which then shows 0 requests),
|
|
493
|
+
or a question you cancelled. It is undefined for a question that failed before its first request
|
|
494
|
+
(a document that is gone, a budget that does not work), which used nothing.
|
|
495
|
+
- **Several servers.** Two questions of one session can end on two servers at the same moment, and
|
|
496
|
+
a read, an addition and a write lose one of them. Add with an atomic update of your database
|
|
497
|
+
(MongoDB's `$inc`, SQL's `UPDATE … SET n = n + ?`), or store one record per question and sum the
|
|
498
|
+
records when you need the total. Model IDs hold dots (`gemini-3.8-flash`), which MongoDB reads as
|
|
499
|
+
a path in an update, so keep them as values, as `models` does above, not as field names.
|
|
500
|
+
- **Claude's cache writes** are inside `inputTokens`, so the sample prices them at the plain input
|
|
501
|
+
rate, and Anthropic bills them at another. [Claude](./anthropic.md) shows how to read Claude's own
|
|
502
|
+
usage of each reply, which has them apart.
|
|
503
|
+
- **A price that depends on the size of each request** (a higher rate for a long prompt) cannot be
|
|
504
|
+
worked out from the totals of a question. Price each reply as it comes
|
|
505
|
+
([below](#each-reply-as-it-comes)).
|
|
506
|
+
|
|
507
|
+
### An allowance per user
|
|
508
|
+
|
|
509
|
+
To keep a user within an allowance, turn what the user has left into `limits.inputTokens` of the
|
|
510
|
+
next question. Keep a margin: a question can pass its ceiling by about two requests.
|
|
511
|
+
|
|
512
|
+
```ts
|
|
513
|
+
import { askGemini } from "llm-large-files/gemini";
|
|
514
|
+
|
|
515
|
+
// files and endpoint as in the first sample. spentThisMonth: the user's input tokens this month,
|
|
516
|
+
// from your records. userId, documentIds and messages are yours.
|
|
517
|
+
const allowance = 50_000_000; // input tokens a month: your own figure
|
|
518
|
+
const margin = 2_000_000; // about two requests of a 1M-token window
|
|
519
|
+
const left = allowance - spentThisMonth;
|
|
520
|
+
if (left <= margin) throw new Error("You have used this month's allowance.");
|
|
521
|
+
|
|
522
|
+
const result = await askGemini({
|
|
523
|
+
files,
|
|
524
|
+
endpoint,
|
|
525
|
+
owner: userId,
|
|
526
|
+
documentIds,
|
|
527
|
+
messages,
|
|
528
|
+
limits: { inputTokens: Math.min(5_000_000, left - margin) },
|
|
529
|
+
});
|
|
530
|
+
```
|
|
531
|
+
|
|
532
|
+
There is no limit across questions: each question runs up to four tool calls at a time, and each
|
|
533
|
+
whole-file read up to four parts at a time, whatever the other questions do. To bound how fast a
|
|
534
|
+
user or a tenant spends, wrap the adapters (below) and make them wait for your own limiter.
|
|
535
|
+
|
|
536
|
+
### Each reply as it comes
|
|
537
|
+
|
|
538
|
+
With `askWithFiles`, an adapter you wrap sees the usage of every request it answers: its chat
|
|
539
|
+
requests and its part reads. Make the wrapped adapter for each question, so that what it reports
|
|
540
|
+
belongs to that question:
|
|
541
|
+
|
|
542
|
+
```ts
|
|
543
|
+
import type { GenerateUsage, ModelAdapter } from "llm-large-files";
|
|
544
|
+
|
|
545
|
+
/** The adapter, with `onReply` called for every answered request: chat requests and part reads. */
|
|
546
|
+
export function metered(base: ModelAdapter, onReply: (model: string, usage: GenerateUsage) => void): ModelAdapter {
|
|
547
|
+
const { generateText } = base;
|
|
548
|
+
return {
|
|
549
|
+
...base,
|
|
550
|
+
async send(request, hooks) {
|
|
551
|
+
const reply = await base.send(request, hooks);
|
|
552
|
+
onReply(base.id, reply.usage ?? {});
|
|
553
|
+
return reply;
|
|
554
|
+
},
|
|
555
|
+
...(generateText ? {
|
|
556
|
+
generateText: (part) => generateText({
|
|
557
|
+
...part,
|
|
558
|
+
onUsage: (used) => {
|
|
559
|
+
onReply(base.id, used);
|
|
560
|
+
part.onUsage?.(used); // the question's own count
|
|
561
|
+
},
|
|
562
|
+
}),
|
|
563
|
+
} : {}),
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
```
|
|
567
|
+
|
|
568
|
+
`reply.providerUsage` of each chat request is the provider's own usage object, for the fields the
|
|
569
|
+
totals do not have. More on wrapping an adapter: [your own adapter and loop](./own-adapter-and-loop.md).
|
|
570
|
+
|
|
571
|
+
## What costs most
|
|
572
|
+
|
|
573
|
+
### Whole-file reads
|
|
574
|
+
|
|
575
|
+
- **A read sends the whole file once**, in parts of up to `mapChunkTokens` (and 80% of
|
|
576
|
+
`maxRequestBytes`), each line with its number. When the notes of the parts together are larger
|
|
577
|
+
than one part, it first merges them, in up to 8 rounds of merge requests. Then it writes an
|
|
578
|
+
answer. Its input is about the size of the file, and more for a file of many short lines. The
|
|
579
|
+
notes of a part may be up to 4,096 output tokens and the answer up to 8,192. For a model that
|
|
580
|
+
spends such a limit thinking, both are raised to 32,768.
|
|
581
|
+
- **With the defaults, one read can cost about 3,000,000 input tokens**: a file of up to 30 parts
|
|
582
|
+
of 100,000 tokens may be read whole. A file that needs more parts is not: its card says that it is
|
|
583
|
+
too large to be analyzed whole, and the tool is not offered when no file of the question can be
|
|
584
|
+
read whole.
|
|
585
|
+
- **Parts are read four at a time**, by the explorer model when there is one.
|
|
586
|
+
|
|
587
|
+
What bounds it:
|
|
588
|
+
|
|
589
|
+
- `limits.wholeDocumentReads` (1 per document by default), `wholeDocumentAnalysis: false`, and
|
|
590
|
+
`limits.inputTokens` and `limits.requests`, which refuse a read that would pass them.
|
|
591
|
+
- With your own loop, the same cap is `maxWholeDocumentReads` of `files.tools()`
|
|
592
|
+
(`MAX_WHOLE_DOCUMENT_READS`, 1, by default), counted per tool set: make one for each question
|
|
593
|
+
([your own adapter and loop](./own-adapter-and-loop.md)).
|
|
594
|
+
- `budget.maxMapChunks`: with 10, only files of up to about 1,000,000 tokens are read whole at the
|
|
595
|
+
default part size.
|
|
596
|
+
- `budget.mapChunkTokens`: smaller parts give more detailed notes, and more requests, notes and
|
|
597
|
+
merges. The input of the parts is the file either way. With `maxMapChunks` it also sets the
|
|
598
|
+
largest file that is read whole.
|
|
599
|
+
- For a model that thinks, less thinking in the part reads: `analysisConfig` of `gemini()` and
|
|
600
|
+
`askGemini`, `analysisBody` of `openAiCompatible()` and `anthropic()`. See
|
|
601
|
+
[Vertex AI and Gemini](./vertex-and-gemini.md).
|
|
602
|
+
|
|
603
|
+
### Long tool loops
|
|
604
|
+
|
|
605
|
+
Each chat request sends everything before it. One tool result may be up to `toolResultCharacters`
|
|
606
|
+
(24,000 characters, about 12,000 tokens of a log), up to 8 run in a turn, and every result stays in
|
|
607
|
+
the requests until the answer. Text tool results may fill the window up to
|
|
608
|
+
`contextTokens − reservedTokens / 2`: 968,000 tokens with the default budget. So the bound with the
|
|
609
|
+
defaults is 12 requests of up to about 968,000 tokens each, about 11.6 million input tokens, plus a
|
|
610
|
+
whole-file read of each document searched. A question of a few searches and reads is far from that
|
|
611
|
+
bound: [measurements](../measurements.md) has live numbers.
|
|
612
|
+
|
|
613
|
+
What bounds it: `limits.toolTurns` and `limits.callsPerTurn`; `limits.inputTokens`;
|
|
614
|
+
`budget.toolResultCharacters` (smaller results, though the model may then need more reads); and an
|
|
615
|
+
explorer model, which makes these requests at its own price.
|
|
616
|
+
|
|
617
|
+
### Pages of PDFs
|
|
618
|
+
|
|
619
|
+
- **One `view_pages` call shows up to five pages** (`MAX_VIEW_PAGES`). A page costs about 530
|
|
620
|
+
tokens on Gemini, 1,000 on an OpenAI-compatible model and 3,500 on Claude by default (the
|
|
621
|
+
adapter's `pageTokens`). An OpenAI-compatible model is shown pages only with `pdfInput: true`.
|
|
622
|
+
Without it, `openAiCompatible()` declares `toolFiles: "none"`, and `view_pages` is offered to no
|
|
623
|
+
model of the question.
|
|
624
|
+
- **Pages stay in every later request of the question**, so a page shown early is paid for again
|
|
625
|
+
by each request after it. They are not kept in `toolTurns`, so a later question does not pay for
|
|
626
|
+
them again.
|
|
627
|
+
- **A question shows pages up to half of `reservedTokens`**, counted with the largest `pageTokens`
|
|
628
|
+
of its models: 60 pages on Gemini with the default budget, 32 on an OpenAI-compatible model with
|
|
629
|
+
`pdfInput`, 12 on Claude with the library's default window. The size of the request in bytes
|
|
630
|
+
bounds them too.
|
|
631
|
+
|
|
632
|
+
What bounds it: `viewPages: false`; `keepOriginals` only for the formats that need it (no kept
|
|
633
|
+
original, no pages); a smaller `reservedTokens`, which also keeps less of the window free for the
|
|
634
|
+
answer (text tool results may then grow the request further). See [PDFs](./pdfs.md).
|
|
635
|
+
|
|
636
|
+
### Documents sent whole
|
|
637
|
+
|
|
638
|
+
Up to `inlineTokens` (200,000 by default) of document text goes into every chat request of the
|
|
639
|
+
question, and into every later question that names the same documents. Prompt caching makes the
|
|
640
|
+
repeats cheaper ([below](#prompt-caching)).
|
|
641
|
+
|
|
642
|
+
- A lower `inlineTokens` sends fewer documents whole. Each request is then smaller, but the model
|
|
643
|
+
needs tool turns to read what is searched: a question that one request answers from a document
|
|
644
|
+
sent whole can take several when the document is searched.
|
|
645
|
+
- Name in `documentIds` only the documents a question is about. Each one named is planned: sent
|
|
646
|
+
whole, or given a card.
|
|
647
|
+
|
|
648
|
+
### An explorer model
|
|
649
|
+
|
|
650
|
+
With an explorer, the requests of the tool loop and the part reads go to a cheaper model, and the
|
|
651
|
+
model you chose for its answers is called once, with what the tools returned. A question that uses
|
|
652
|
+
the tools takes one request more. When that pays off: [explorer model](./explorer-model.md).
|
|
653
|
+
|
|
654
|
+
## Prompt caching
|
|
655
|
+
|
|
656
|
+
A provider's prompt cache bills the start of a request it has seen recently at a lower rate, and
|
|
657
|
+
reports it in `cachedInputTokens`. The library keeps the start of the requests of a chat the same:
|
|
658
|
+
|
|
659
|
+
- **`documentPlacement: "first"`** (the default) puts the documents and cards at the start of the
|
|
660
|
+
first user turn, where they stay as the conversation grows, so every later request and every
|
|
661
|
+
follow-up question can read them from the cache. `"last"` appends them to the latest user turn:
|
|
662
|
+
they move with every question and are billed in full each time. In a live test with Gemini, 96%
|
|
663
|
+
of the input of a follow-up question was cached with `"first"`, against 0% with `"last"`
|
|
664
|
+
([measurements](../measurements.md)).
|
|
665
|
+
- **Notes are not kept.** The note sent after an empty or broken turn, which asks the model to try
|
|
666
|
+
again, is in that one request only, and so is the note of the answer's second try. (When the
|
|
667
|
+
model that makes the tool calls has a conversation that may only grow, such as Claude, it keeps
|
|
668
|
+
the note of a broken tool turn.)
|
|
669
|
+
- **The request for the answer adds its line at the end.**
|
|
670
|
+
|
|
671
|
+
What you keep the same:
|
|
672
|
+
|
|
673
|
+
- **Your system instruction.** It comes first in every request, before the tool guide. A date, a
|
|
674
|
+
time or the user's question in it changes the start of every request, and nothing is read from
|
|
675
|
+
the cache. Put such things in the user's turn instead.
|
|
676
|
+
- **The documents, in the same order.** Their text and cards are in the order of `documentIds`.
|
|
677
|
+
Pass the same IDs in the same order. A document added to the chat changes the first user turn,
|
|
678
|
+
and the cache misses from there, once.
|
|
679
|
+
- **The history.** A turn you change or drop changes the request from that turn on
|
|
680
|
+
([conversations](./conversations.md)).
|
|
681
|
+
|
|
682
|
+
What the library changes:
|
|
683
|
+
|
|
684
|
+
- A document that went whole can become a card as the history grows (above). The tool guide, which
|
|
685
|
+
names the files that are searched, changes with it.
|
|
686
|
+
- Within a question, when room runs short, older tool results are replaced by short stand-ins. The
|
|
687
|
+
request changes from the first round replaced. A model whose conversation may only grow (Claude)
|
|
688
|
+
has nothing replaced.
|
|
689
|
+
- The tool rounds of an earlier question are sent without their `tool_turns_left`. So the first
|
|
690
|
+
request of a follow-up question differs from the requests of the question before it from that
|
|
691
|
+
question's first tool round on, and the cache misses from there, once in each follow-up
|
|
692
|
+
question: those rounds are billed at the full price in that request (with Claude's
|
|
693
|
+
`cache_control`, as a cache write). The rounds of older questions were already sent without it,
|
|
694
|
+
and still match. The documents and cards before them are still read from the cache.
|
|
695
|
+
- An upgrade that changes the library's prompts misses the cache once in each conversation. 0.6.0
|
|
696
|
+
changed the tool guide, the descriptions of `search_document` and `analyze_whole_document`, and
|
|
697
|
+
the frame lines of a file sent whole. The first request after the upgrade shares with what 0.5.0
|
|
698
|
+
sent at most what comes before the first text that changed. For a question with files to
|
|
699
|
+
search, that is nothing on Claude and OpenAI-compatible endpoints, where the tools come first,
|
|
700
|
+
and at most your own system text on Gemini, where the tool guide follows it in the system
|
|
701
|
+
instruction. For a question whose files are all sent whole, it is your own system text, and
|
|
702
|
+
`view_pages` with its guide when the pages of a PDF can be looked at. From then on the frame of a
|
|
703
|
+
document is the same in every request
|
|
704
|
+
([Deployment](./deployment.md#servers-of-two-versions)).
|
|
705
|
+
|
|
706
|
+
The adapters:
|
|
707
|
+
|
|
708
|
+
- `anthropic()` asks for caching: `cache` is `true` by default (five minutes), `"1h"` for an hour,
|
|
709
|
+
`false` for none. See [Claude](./anthropic.md).
|
|
710
|
+
- `gemini()` and `openAiCompatible()` send no cache settings. What the provider caches on its own
|
|
711
|
+
is reported in `cachedInputTokens`.
|
|
712
|
+
|
|
713
|
+
## Related pages
|
|
714
|
+
|
|
715
|
+
- [`llm-large-files` reference: the tool loop](../reference/ask.md): `AskLimits`, `AskResult`,
|
|
716
|
+
`UsageTotals`, `ModelCapabilities`.
|
|
717
|
+
- [`llm-large-files` reference: the library](../reference/library.md): `Budget`, `DEFAULT_BUDGET`,
|
|
718
|
+
`resolveBudget`, `ModelLimits`, `budgetFor`.
|
|
719
|
+
- [Tools reference](../reference/tools.md): what each tool returns, `MAX_VIEW_PAGES`,
|
|
720
|
+
`MAX_WHOLE_DOCUMENT_READS`.
|
|
721
|
+
- [An explorer model](./explorer-model.md), [Vertex AI and Gemini](./vertex-and-gemini.md),
|
|
722
|
+
[OpenAI-compatible endpoints](./openai-compatible.md), [Claude](./anthropic.md).
|
|
723
|
+
- [Errors and reliability](./errors-and-reliability.md): requests too large, retries,
|
|
724
|
+
`partialResultOf`.
|
|
725
|
+
- [Conversations](./conversations.md): history, `toolTurns`, keeping the window.
|
|
726
|
+
- [How it works](../how-it-works.md): the room in the request and how the plan is made.
|