llm-large-files 0.4.1 → 0.5.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 +127 -0
- package/README.md +48 -8
- package/dist/anthropic/adapter.d.ts +106 -0
- package/dist/anthropic/adapter.d.ts.map +1 -0
- package/dist/anthropic/adapter.js +391 -0
- package/dist/anthropic/adapter.js.map +1 -0
- package/dist/anthropic/index.d.ts +3 -0
- package/dist/anthropic/index.d.ts.map +1 -0
- package/dist/anthropic/index.js +2 -0
- package/dist/anthropic/index.js.map +1 -0
- package/dist/ask.d.ts +144 -0
- package/dist/ask.d.ts.map +1 -0
- package/dist/ask.js +540 -0
- package/dist/ask.js.map +1 -0
- package/dist/budget.d.ts +23 -0
- package/dist/budget.d.ts.map +1 -0
- package/dist/budget.js +64 -0
- package/dist/budget.js.map +1 -0
- package/dist/evidence.d.ts +40 -0
- package/dist/evidence.d.ts.map +1 -0
- package/dist/evidence.js +137 -0
- package/dist/evidence.js.map +1 -0
- package/dist/gemini/adapter.d.ts +50 -0
- package/dist/gemini/adapter.d.ts.map +1 -0
- package/dist/gemini/adapter.js +179 -0
- package/dist/gemini/adapter.js.map +1 -0
- package/dist/gemini/chat.d.ts +31 -75
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +38 -300
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +11 -0
- package/dist/gemini/errors.d.ts.map +1 -0
- package/dist/gemini/errors.js +14 -0
- package/dist/gemini/errors.js.map +1 -0
- package/dist/gemini/generate.d.ts +9 -20
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +43 -92
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -1
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -1
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -2
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -38
- package/dist/gemini/sse.js.map +1 -1
- package/dist/http.d.ts +20 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +55 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +13 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +29 -3
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +10 -12
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +9 -0
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +25 -19
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +196 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/model.js +41 -0
- package/dist/model.js.map +1 -0
- package/dist/openai/adapter.d.ts +85 -0
- package/dist/openai/adapter.d.ts.map +1 -0
- package/dist/openai/adapter.js +293 -0
- package/dist/openai/adapter.js.map +1 -0
- package/dist/openai/index.d.ts +3 -0
- package/dist/openai/index.d.ts.map +1 -0
- package/dist/openai/index.js +2 -0
- package/dist/openai/index.js.map +1 -0
- package/dist/output-limit.d.ts +30 -0
- package/dist/output-limit.d.ts.map +1 -0
- package/dist/output-limit.js +92 -0
- package/dist/output-limit.js.map +1 -0
- package/dist/retry.d.ts +54 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +111 -0
- package/dist/retry.js.map +1 -0
- package/dist/sse.d.ts +3 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +39 -0
- package/dist/sse.js.map +1 -0
- package/dist/tools.d.ts +11 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +85 -31
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +28 -3
- package/dist/types.d.ts.map +1 -1
- package/docs/api.md +245 -27
- package/docs/configuration.md +83 -9
- package/docs/getting-started.md +67 -16
- package/docs/how-it-works.md +38 -2
- package/docs/security.md +18 -0
- package/package.json +21 -3
- package/src/anthropic/adapter.ts +454 -0
- package/src/anthropic/index.ts +2 -0
- package/src/ask.ts +675 -0
- package/src/budget.ts +71 -0
- package/src/evidence.ts +162 -0
- package/src/gemini/adapter.ts +218 -0
- package/src/gemini/chat.ts +61 -353
- package/src/gemini/errors.ts +15 -0
- package/src/gemini/generate.ts +50 -90
- package/src/gemini/index.ts +3 -1
- package/src/gemini/sse.ts +1 -34
- package/src/http.ts +59 -0
- package/src/index.ts +33 -4
- package/src/library.ts +39 -13
- package/src/map-reduce.ts +22 -16
- package/src/model.ts +200 -0
- package/src/openai/adapter.ts +345 -0
- package/src/openai/index.ts +2 -0
- package/src/output-limit.ts +99 -0
- package/src/retry.ts +132 -0
- package/src/sse.ts +34 -0
- package/src/tools.ts +91 -34
- package/src/types.ts +24 -3
package/docs/api.md
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
# API reference
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Five entry points:
|
|
4
4
|
|
|
5
5
|
| Import | Contents |
|
|
6
6
|
|---|---|
|
|
7
|
-
| `llm-large-files` | Core: `createLargeFiles`, stores, types, helpers. Provider-neutral. |
|
|
8
|
-
| `llm-large-files/gemini` | `askGemini`, endpoints, Gemini
|
|
7
|
+
| `llm-large-files` | Core: `createLargeFiles`, `askWithFiles`, stores, types, helpers. Provider-neutral. |
|
|
8
|
+
| `llm-large-files/gemini` | `gemini()`, `askGemini`, endpoints, Gemini helpers. |
|
|
9
|
+
| `llm-large-files/openai` | `openAiCompatible()` for any Chat Completions endpoint. |
|
|
10
|
+
| `llm-large-files/anthropic` | `anthropic()` for Claude. |
|
|
9
11
|
| `llm-large-files/node` | `createDocumentHandlers` for Node HTTP servers. |
|
|
10
12
|
|
|
11
13
|
## `llm-large-files`
|
|
@@ -15,7 +17,7 @@ Three entry points:
|
|
|
15
17
|
| Option | Type | Default |
|
|
16
18
|
|---|---|---|
|
|
17
19
|
| `store` | `DocumentStore` | required |
|
|
18
|
-
| `budget` | `Partial<Budget>` | see [configuration](configuration.md#budget) |
|
|
20
|
+
| `budget` | `Partial<Budget>` | see [configuration](configuration.md#budget). What is left out follows `contextTokens`; values that cannot work together throw |
|
|
19
21
|
| `ttlMs` | `number` | 72 hours. `Infinity` keeps documents until they are deleted (`expiresAt` is then `NEVER_EXPIRES`) |
|
|
20
22
|
| `maxUploadBytes` | `number` | 100 MB |
|
|
21
23
|
| `extractors` | `Partial<Record<DocumentFormat, Extractor>>` | built-ins |
|
|
@@ -36,8 +38,9 @@ Three entry points:
|
|
|
36
38
|
| `getOriginal(id, { owner }?)` | The uploaded file as a `Uint8Array`, when it was kept. `undefined` otherwise, and for another owner. |
|
|
37
39
|
| `delete(id, { owner }?)` | `true` if deleted. |
|
|
38
40
|
| `sweep()` | Removes expired documents; returns the count. |
|
|
39
|
-
| `prepare(ids, base, { owner?, viewPages? }?)` | Plans one request. `base` is `{ tokens, bytes }` for everything else in the request. Returns `PreparedContext`. `viewPages: true` says that your loop can pass files to the model. |
|
|
40
|
-
| `tools(documents, { generate?, onProgress?, signal?, viewPages?, regexBudgetMs? })` | A `ToolSet` scoped to these documents. `generate` enables `analyze_whole_document`, for documents small enough for it. `viewPages` (`true`, or a list of documents such as `prepared.viewable`) enables `view_pages`. `regexBudgetMs` (default 6,000) is the time the regex searches of the tool set may take together. |
|
|
41
|
+
| `prepare(ids, base, { owner?, viewPages?, budget? }?)` | Plans one request. `base` is `{ tokens, bytes }` for everything else in the request. Returns `PreparedContext`. `viewPages: true` says that your loop can pass files to the model. `budget` changes budget fields for this request. |
|
|
42
|
+
| `tools(documents, { generate?, onProgress?, signal?, viewPages?, regexBudgetMs?, maxWholeDocumentReads?, retry?, budget? })` | A `ToolSet` scoped to these documents: make one for each question. `generate` enables `analyze_whole_document`, for documents small enough for it. `viewPages` (`true`, or a list of documents such as `prepared.viewable`) enables `view_pages`. `regexBudgetMs` (default 6,000) is the time the regex searches of the tool set may take together. `maxWholeDocumentReads` (default 1) is how often each document may be read whole. `retry` is how a part read that failed is sent again. |
|
|
43
|
+
| `budgetFor(overrides?, limits?)` | The budget for one request: the library's, with `overrides` in place of its fields, made to fit `limits` (`{ contextTokens?, maxRequestBytes? }` of a model). |
|
|
41
44
|
|
|
42
45
|
`getMeta`, `getOriginal`, `delete`, `prepare` and the tools read the store. When it cannot be read
|
|
43
46
|
(a volume that does not answer, a database that is down) they throw `DocumentStoreError`, and a
|
|
@@ -64,13 +67,19 @@ no path and no host; `error.cause` is what the store threw, for your log.
|
|
|
64
67
|
declarations: ToolDeclaration[]; // { name, description, parameters: JSON Schema }
|
|
65
68
|
has(name): boolean;
|
|
66
69
|
execute(name, args): Promise<ToolResult>; // errors come back as { error } for the model to read
|
|
67
|
-
executeWithFiles(name, args, { maxFileBytes?, maxPages? }?): Promise<{ result: ToolResult; files: ToolFile[] }>;
|
|
70
|
+
executeWithFiles(name, args, { maxFileBytes?, maxPages?, maxResultCharacters? }?): Promise<{ result: ToolResult; files: ToolFile[] }>;
|
|
68
71
|
describe(name, args): string; // "Search app.log (exact) for “timeout”"
|
|
72
|
+
resultCharacters(name): number; // the most characters a result of this tool can have
|
|
69
73
|
}
|
|
70
74
|
```
|
|
71
75
|
|
|
72
76
|
`executeWithFiles` runs any tool. Its `files` (`{ name, mimeType, bytes }`) are empty for all but
|
|
73
77
|
`view_pages`. `execute("view_pages", …)` returns an error, because it has no place for the file.
|
|
78
|
+
`maxResultCharacters` is the room your request has left for this result, when that is less than
|
|
79
|
+
the tool's own cap: the result is cut to it and says where to go on.
|
|
80
|
+
|
|
81
|
+
A second `analyze_whole_document` of the same document by one tool set answers with an error that
|
|
82
|
+
tells the model to use the first answer (`maxWholeDocumentReads`).
|
|
74
83
|
|
|
75
84
|
| Tool | Arguments | Returns |
|
|
76
85
|
|---|---|---|
|
|
@@ -101,7 +110,15 @@ carry page numbers: `page` on each matching line, `pages` on a passage and on a
|
|
|
101
110
|
- `isDocumentId(value)`, `DOCUMENT_ID_PATTERN`.
|
|
102
111
|
- `estimateTokens(text)`, `utf8Bytes(text)`, `jsonBytes(text)`.
|
|
103
112
|
- `detectFormat(name, mimeType)`, `defaultExtractors`, `TOOL_NAMES`, `DEFAULT_BUDGET`,
|
|
104
|
-
`MAX_VIEW_PAGES` (5).
|
|
113
|
+
`MAX_VIEW_PAGES` (5), `MAX_WHOLE_DOCUMENT_READS` (1).
|
|
114
|
+
- `resolveBudget(partial?, limits?)`: a whole `Budget` from the fields you give
|
|
115
|
+
(see [configuration](configuration.md#budget)).
|
|
116
|
+
- `evidenceOf(call, result)`, `stubResult(call, result)`, `mergeRanges(ranges)`: what a tool call
|
|
117
|
+
showed, the short stand-in for a result that is dropped, and line ranges made one. For a loop of
|
|
118
|
+
your own.
|
|
119
|
+
- `withRetry(run, { retry?, signal?, canRetry?, onRetry? })`, `isRetryableStatus(status)`,
|
|
120
|
+
`retryAfterMs(headers, body?)`: the retry rule of the loop, for an adapter or a loop of your own.
|
|
121
|
+
- `parseSseJson(stream)`: async iterator over the JSON events of a `text/event-stream` body.
|
|
105
122
|
- `createPdfExtractor({ tables?: boolean, pictures?: boolean })`: the built-in PDF extractor with
|
|
106
123
|
an option changed. `tables: false` gives the text in pdf.js order, without rebuilt tables
|
|
107
124
|
(see [PDF tables](configuration.md#pdf-tables)). `pictures: false` leaves out the line that marks
|
|
@@ -126,6 +143,8 @@ type DocumentMeta = {
|
|
|
126
143
|
type GenerateText = (request: {
|
|
127
144
|
system: string; prompt: string; maxOutputTokens: number; signal?: AbortSignal;
|
|
128
145
|
onTruncated?: () => void; // call it when the model stopped at maxOutputTokens
|
|
146
|
+
onUsage?: (usage: { inputTokens?: number; cachedInputTokens?: number; outputTokens?: number; thoughtTokens?: number }) => void;
|
|
147
|
+
// call it once for every request that was answered
|
|
129
148
|
}) => Promise<string>;
|
|
130
149
|
type Extractor = (bytes: Uint8Array, input: { name: string; mimeType: string; format: DocumentFormat; scannedPages?: number }) => Promise<{ text: string; pages?: number }>;
|
|
131
150
|
// scannedPages: set when a PDF without any text is welcome, with the most pages it may have.
|
|
@@ -133,10 +152,155 @@ type Extractor = (bytes: Uint8Array, input: { name: string; mimeType: string; fo
|
|
|
133
152
|
type ToolFile = { name: string; mimeType: string; bytes: Uint8Array };
|
|
134
153
|
```
|
|
135
154
|
|
|
155
|
+
## `askWithFiles(options): Promise<AskResult>`
|
|
156
|
+
|
|
157
|
+
The tool loop, for any model. It plans the documents, offers the tools, runs the calls within the
|
|
158
|
+
limits of the request, and ends with a request that must be answered in text.
|
|
159
|
+
|
|
160
|
+
| Option | Description |
|
|
161
|
+
|---|---|
|
|
162
|
+
| `files`, `model`, `documentIds`, `messages` | Required. `model` is an adapter: `gemini()`, `openAiCompatible()`, `anthropic()`, or [your own](#your-own-adapter). |
|
|
163
|
+
| `explorer` | A second adapter, of any provider. It makes the tool calls and reads whole files in parts, and `model` writes the answer from what the tools returned. See [An explorer model](configuration.md#an-explorer-model). |
|
|
164
|
+
| `messages` | The conversation; the last must be the user's. Plain turns `{ role: "user" \| "assistant", text }`, the `toolTurns` an earlier question returned, and turns with parts in the provider's own form: `{ role, parts: [{ text }, { native: anImagePart }] }`. |
|
|
165
|
+
| `system` | System instruction; the tool guide is appended when needed. |
|
|
166
|
+
| `owner` | Only documents with this owner (or no owner) are used. |
|
|
167
|
+
| `documentPlacement` | `"first"` (default): document text and cards go at the start of the first user turn and stay there, so follow-up questions reuse the provider's prompt cache. `"last"`: appended to the latest user turn. |
|
|
168
|
+
| `limits` | `toolTurns` (12): the most chat requests for one question, counting the answer. `callsPerTurn` (8): the most tool calls of one turn that are run. `wholeDocumentReads` (1): how often each document may be read whole. `inputTokens`, `requests` (none): ceilings for the whole question, part reads included. |
|
|
169
|
+
| `retry` | `{ retries = 3, baseDelayMs = 500, maxDelayMs = 60_000 }`. See [Limits and retries](configuration.md#limits-and-retries). |
|
|
170
|
+
| `budget` | Budget fields for this question, in place of the library's. |
|
|
171
|
+
| `wholeDocumentAnalysis` | Default `true`. Set `false` to withhold the costly whole-file tool. |
|
|
172
|
+
| `viewPages` | Default `true`. Offers `view_pages` for PDFs whose original is kept, when every model of the question can be sent a file. |
|
|
173
|
+
| `onText`, `onActivity`, `onStep` | Answer text as it arrives, transient status, completed steps. |
|
|
174
|
+
| `signal` | Stops the question. |
|
|
175
|
+
|
|
176
|
+
Returns:
|
|
177
|
+
|
|
178
|
+
```ts
|
|
179
|
+
{
|
|
180
|
+
text: string; // everything the answering model wrote
|
|
181
|
+
answered: boolean; // false when its last turn had no text, or the prompt was refused
|
|
182
|
+
blockReason?: string;
|
|
183
|
+
steps: string[]; // "Search app.log (exact) for “timeout” — 12 matching lines"
|
|
184
|
+
evidence: Evidence[]; // per tool call: { tool, documentId, document, lines?, pages?, query?, mode?, totalMatchingLines?, whole? }
|
|
185
|
+
toolTurns: ToolTurn[]; // the tool rounds as plain JSON, to keep with the conversation
|
|
186
|
+
plan: DocumentPlan; // which documents went in whole and which were searched
|
|
187
|
+
budget: Budget; // the budget the question ran with
|
|
188
|
+
turns: number; // chat requests, an explorer's among them; part reads are not counted
|
|
189
|
+
finishReason?: string;
|
|
190
|
+
usage: { // every request that was answered, part reads included
|
|
191
|
+
requests: number; inputTokens: number; cachedInputTokens: number; outputTokens: number; thoughtTokens: number;
|
|
192
|
+
byModel: Record<string, { requests; inputTokens; cachedInputTokens; outputTokens; thoughtTokens }>;
|
|
193
|
+
};
|
|
194
|
+
lastUsage?: Record<string, unknown>; // the provider's own usage object of the last chat response
|
|
195
|
+
}
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
`inputTokens` counts every token of the prompts, those read from a cache included, and
|
|
199
|
+
`cachedInputTokens` is the part that was. `outputTokens` includes thoughts.
|
|
200
|
+
|
|
201
|
+
`answered` is `false` when the model's last turn had no text: the prompt was blocked
|
|
202
|
+
(`blockReason` says why), the reply was cut off before any text, or the model produced a malformed
|
|
203
|
+
tool call and the request for the answer came back empty too. `text` is then empty or holds only a
|
|
204
|
+
remark the model made before a tool call, so show your own message:
|
|
205
|
+
|
|
206
|
+
```ts
|
|
207
|
+
const result = await askWithFiles({ ... });
|
|
208
|
+
if (!result.answered) show(result.blockReason ? "The request was blocked." : "No answer this time. Try again.");
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
It throws `DocumentsNotFoundError` (`.ids`) before calling the model, `DocumentStoreError` when the
|
|
212
|
+
store could not be read (retry: the documents are not gone), `ModelRequestError` (`.status`, and
|
|
213
|
+
`.retryAfterMs` when the provider named a wait) for an HTTP error that another try did not mend,
|
|
214
|
+
and `Error` when the last message isn't the user's. `status` is 0 for a connection that failed.
|
|
215
|
+
Each adapter throws its own subclass: `GeminiRequestError`, `OpenAiRequestError`,
|
|
216
|
+
`AnthropicRequestError`.
|
|
217
|
+
|
|
218
|
+
### Keeping what a question read
|
|
219
|
+
|
|
220
|
+
`toolTurns` are the tool rounds of the question, with each result as the model had it. Store them
|
|
221
|
+
between the question and its answer, and pass them back:
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
const first = await askWithFiles({ files, model, documentIds, messages: [{ role: "user", text: question }] });
|
|
225
|
+
await saveTurn(sessionId, { question, toolTurns: first.toolTurns, answer: first.text });
|
|
226
|
+
|
|
227
|
+
// The next question of the conversation:
|
|
228
|
+
const messages = [
|
|
229
|
+
{ role: "user", text: question }, ...first.toolTurns, { role: "assistant", text: first.text },
|
|
230
|
+
{ role: "user", text: "And how long did recovery take?" },
|
|
231
|
+
];
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
The model then sees what it read before, and a follow-up is often answered without a new search.
|
|
235
|
+
The rounds are plain JSON and belong to no provider. The pages of a PDF are not in them: a stored
|
|
236
|
+
round says that they were shown. They count against the budget like any other part of the
|
|
237
|
+
conversation, and late in a long question the oldest are shortened first.
|
|
238
|
+
|
|
239
|
+
### Your own adapter
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
import type { ModelAdapter } from "llm-large-files";
|
|
243
|
+
|
|
244
|
+
const model: ModelAdapter = {
|
|
245
|
+
id: "my-model", // names the model in usage totals
|
|
246
|
+
capabilities: { toolFiles: "none", pageTokens: 0 }, // and, when you know them: contextTokens, maxRequestBytes, outputTokens, tokenScale, appendOnly
|
|
247
|
+
async send(request, hooks) {
|
|
248
|
+
// request: { system, messages, tools?, toolChoice? }
|
|
249
|
+
// messages: { role: "user" | "assistant", parts: [{ text } | { native }] }
|
|
250
|
+
// | { role: "tools", calls, answers: [{ call, result, files? }], raw? }
|
|
251
|
+
// Turn them into your provider's request, post it with hooks.signal, and call hooks.onText
|
|
252
|
+
// with the text as it arrives.
|
|
253
|
+
return { text, calls: [{ id, name, args }], raw: theTurnAsYourProviderSentIt, finishReason, usage: { inputTokens, outputTokens } };
|
|
254
|
+
},
|
|
255
|
+
generateText: async ({ system, prompt, maxOutputTokens, signal, onUsage, onTruncated }) => "…", // optional: enables whole-file reads
|
|
256
|
+
};
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
- A `tools` message is one round: the model's calls and the results, in call order. `raw` is the
|
|
260
|
+
turn as your `send` returned it, given back only to the adapter that produced it. Without `raw`
|
|
261
|
+
(an explorer of another provider made the calls, or the round was stored), build the turn from
|
|
262
|
+
`calls`.
|
|
263
|
+
- `toolChoice: "none"` means the model must answer in text. The tools are still in `tools`, for a
|
|
264
|
+
provider that wants them declared next to earlier calls.
|
|
265
|
+
- Throw `ModelRequestError(message, status, { retryAfterMs })` for an HTTP error, with status 0
|
|
266
|
+
for a connection that failed. The loop retries the ones worth retrying.
|
|
267
|
+
- Give a call whose arguments did not parse a `problem`: the loop answers it with that message and
|
|
268
|
+
does not run it.
|
|
269
|
+
- `capabilities.toolFiles` says where a file from a tool goes (`"inside"` the result, `"beside"`
|
|
270
|
+
it, or `"none"`: `view_pages` is then not offered). `appendOnly: true` tells the loop never to
|
|
271
|
+
rewrite an earlier turn of the conversation.
|
|
272
|
+
|
|
136
273
|
## `llm-large-files/gemini`
|
|
137
274
|
|
|
275
|
+
### `gemini(endpoint, options?): ModelAdapter`
|
|
276
|
+
|
|
277
|
+
A Gemini model for `askWithFiles`. `endpoint` is `geminiApi()`, `vertexAi()`, or your own
|
|
278
|
+
`{ url, streamUrl?, headers }`; its `explorerUrl` is not used here, because an explorer is an
|
|
279
|
+
adapter of its own.
|
|
280
|
+
|
|
281
|
+
| Option | Description |
|
|
282
|
+
|---|---|
|
|
283
|
+
| `generationConfig` | Sent with every chat request. |
|
|
284
|
+
| `toolFilePlacement` | `"inside"` (default) or `"beside"`: see [Where the pages go](configuration.md#where-the-pages-go-toolfileplacement). |
|
|
285
|
+
| `analysisConfig` | `(maxOutputTokens) => generationConfig` for whole-file part reads. |
|
|
286
|
+
| `contextTokens`, `maxRequestBytes` | The model's window and the largest request, when the budget of a question should follow them. |
|
|
287
|
+
| `pageTokens` | Tokens billed for one PDF page. Default 530. |
|
|
288
|
+
| `id`, `fetch` | The name in usage totals (default: the model in the URL), and a custom fetch. |
|
|
289
|
+
|
|
290
|
+
```ts
|
|
291
|
+
const model = gemini(geminiApi({ apiKey, model: "gemini-3.8-flash" }), { generationConfig: { temperature: 0.3 } });
|
|
292
|
+
const explorer = gemini(geminiApi({ apiKey, model: "gemini-3.5-flash-lite" }));
|
|
293
|
+
await askWithFiles({ files, model, explorer, documentIds, messages });
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
`fromGeminiContents(contents)` turns Gemini `contents` into `messages`, and
|
|
297
|
+
`geminiToolTurns(toolTurns)` gives stored tool rounds as `contents`.
|
|
298
|
+
|
|
138
299
|
### `askGemini(options): Promise<AskGeminiResult>`
|
|
139
300
|
|
|
301
|
+
`askWithFiles` with a `gemini()` model for the endpoint, and a second one for its explorer model
|
|
302
|
+
when it names one. It takes Gemini `contents` as well as `messages`.
|
|
303
|
+
|
|
140
304
|
| Option | Description |
|
|
141
305
|
|---|---|
|
|
142
306
|
| `files`, `endpoint`, `documentIds` | Required. |
|
|
@@ -147,8 +311,9 @@ type ToolFile = { name: string; mimeType: string; bytes: Uint8Array };
|
|
|
147
311
|
| `explorerGenerationConfig` | The same, for the requests of an [explorer model](configuration.md#an-explorer-model). Defaults to `generationConfig`. Not used without an explorer. |
|
|
148
312
|
| `owner` | Only documents with this owner (or no owner) are used. |
|
|
149
313
|
| `documentPlacement` | `"first"` (default): document text and cards go at the start of the first user turn and stay there, so follow-up questions reuse Gemini's prompt cache. `"last"`: appended to the latest user turn, as in 0.1.0. |
|
|
150
|
-
| `
|
|
151
|
-
| `
|
|
314
|
+
| `limits`, `retry`, `budget` | As in `askWithFiles`. |
|
|
315
|
+
| `maxToolTurns` | `limits.toolTurns` under its older name. Default 12. The most requests for one question, counting the answer. If the model is still calling tools on the last one, it is sent with no tools so the model must answer. With an explorer model the answer is always the last request, so the explorer has one less. |
|
|
316
|
+
| `maxToolCallsPerTurn` | `limits.callsPerTurn` under its older name. Default 8. The most tool calls of one model turn that are run. The others are answered with an error that tells the model to send them again if it still needs them. |
|
|
152
317
|
| `wholeDocumentAnalysis` | Default `true`. Set `false` to withhold the costly whole-file tool. |
|
|
153
318
|
| `viewPages` | Default `true`. Offers `view_pages` for PDFs whose original is kept. It changes nothing for a library that keeps no originals. |
|
|
154
319
|
| `toolFilePlacement` | `"inside"` (default): the pages go in the function response itself, which Gemini 3 models read. `"beside"`: in a user turn of their own after the function responses, for Gemini 2.5, which does not see a file inside a function response. See [Where the pages go](configuration.md#where-the-pages-go-toolfileplacement). |
|
|
@@ -156,25 +321,16 @@ type ToolFile = { name: string; mimeType: string; bytes: Uint8Array };
|
|
|
156
321
|
| `onText`, `onActivity`, `onStep` | Streaming answer text, transient status, completed steps. |
|
|
157
322
|
| `fetch`, `signal` | Custom fetch (proxies, tests) and cancellation. |
|
|
158
323
|
|
|
159
|
-
Returns `
|
|
160
|
-
|
|
161
|
-
`answered` is `false` when the model's last turn had no text: the prompt was blocked
|
|
162
|
-
(`blockReason` says why), the reply was cut off before any text, or the model produced a malformed
|
|
163
|
-
tool call and the tool-free retry came back empty too. `text` is then empty or holds only a remark
|
|
164
|
-
the model made before a tool call, so show your own message:
|
|
165
|
-
|
|
166
|
-
```ts
|
|
167
|
-
const result = await askGemini({ ... });
|
|
168
|
-
if (!result.answered) show(result.blockReason ? "The request was blocked." : "No answer this time. Try again.");
|
|
169
|
-
```
|
|
324
|
+
Returns what `askWithFiles` returns. **`usage` is the total of the question since 0.5.0**; Gemini's
|
|
325
|
+
own `usageMetadata` of the last response, which `usage` was before, is `lastUsage`.
|
|
170
326
|
|
|
171
|
-
It throws `
|
|
172
|
-
|
|
173
|
-
HTTP errors, and `Error` when the last message isn't the user's.
|
|
327
|
+
It throws what `askWithFiles` throws; the model's errors are `GeminiRequestError` (`.status`, 0
|
|
328
|
+
for a connection that failed).
|
|
174
329
|
|
|
175
330
|
With an [explorer model](configuration.md#an-explorer-model), `text` and `onText` carry only what
|
|
176
|
-
the answering model wrote, `turns` counts the requests of both models,
|
|
177
|
-
`finishReason` are those of the answer. An explorer that
|
|
331
|
+
the answering model wrote, `turns` counts the requests of both models, `usage.byModel` has an
|
|
332
|
+
entry for each, and `finishReason` and `lastUsage` are those of the answer. An explorer that
|
|
333
|
+
fails throws `GeminiRequestError` too.
|
|
178
334
|
|
|
179
335
|
### Endpoints
|
|
180
336
|
|
|
@@ -191,7 +347,7 @@ reads whole files in parts, so that `model` only writes the answer. Left out, em
|
|
|
191
347
|
|
|
192
348
|
### Lower-level helpers
|
|
193
349
|
|
|
194
|
-
- `createGeminiGenerateText({ url, headers, fetchImpl?, generationConfig?, timeoutMs? })`: a `GenerateText` for your own loop.
|
|
350
|
+
- `createGeminiGenerateText({ url, headers, fetchImpl?, generationConfig?, timeoutMs? })`: a `GenerateText` for your own loop. `headers` can be a function, called for every request.
|
|
195
351
|
- `toGeminiTools(declarations)`: `{ functionDeclarations }`.
|
|
196
352
|
- `geminiFunctionResponses([{ call, result, files? }])`: the `user` turn answering function
|
|
197
353
|
calls. Files from `executeWithFiles` go inside their function response, as base64.
|
|
@@ -205,6 +361,68 @@ reads whole files in parts, so that `model` only writes the answer. Left out, em
|
|
|
205
361
|
tool. The second is the line in the explorer's system instruction that says what its part is.
|
|
206
362
|
- `parseSseJson(stream)`: async iterator over a Generate Content SSE stream.
|
|
207
363
|
|
|
364
|
+
## `llm-large-files/openai`
|
|
365
|
+
|
|
366
|
+
### `openAiCompatible(options): ModelAdapter`
|
|
367
|
+
|
|
368
|
+
Any Chat Completions endpoint: OpenAI, Azure OpenAI, DeepSeek, LiteLLM, vLLM, Ollama, OpenRouter,
|
|
369
|
+
Gemini's OpenAI layer.
|
|
370
|
+
|
|
371
|
+
| Option | Description |
|
|
372
|
+
|---|---|
|
|
373
|
+
| `model` | Required: the model name the endpoint knows. |
|
|
374
|
+
| `baseUrl` | `/chat/completions` is added to it. Default `https://api.openai.com/v1`. |
|
|
375
|
+
| `url` | The whole URL, when it is not `baseUrl` + `/chat/completions` (Azure, a gateway). |
|
|
376
|
+
| `apiKey`, `headers` | `Authorization: Bearer …`, and more headers. A function is called for each request. |
|
|
377
|
+
| `body` | More fields for every chat request: `temperature`, `reasoning_effort`, `max_completion_tokens`. |
|
|
378
|
+
| `analysisBody` | `(maxOutputTokens) => fields` for whole-file part reads. |
|
|
379
|
+
| `maxTokensField` | The name of the output limit in a part read. Default `max_completion_tokens` for api.openai.com and Azure OpenAI, `max_tokens` elsewhere. |
|
|
380
|
+
| `answerWithoutTools` | `"tool_choice"` (default): the request for the answer keeps the tools and sends `tool_choice: "none"`. `"omit"`: it leaves them out, for a server that does not know `tool_choice`. |
|
|
381
|
+
| `pdfInput` | Default `false`. Send the pages of `view_pages` as a `file` part in a user message after the tool results. For a model that reads PDF input: many servers behind this API do not (Gemini's layer answers HTTP 400). Not run against OpenAI itself. |
|
|
382
|
+
| `stream`, `systemRole` | `false` for a server without streaming; `"developer"` for one that wants the newer role name. |
|
|
383
|
+
| `contextTokens`, `maxRequestBytes`, `tokenScale`, `pageTokens` | What the model takes, when the budget should follow it. |
|
|
384
|
+
| `id`, `timeoutMs`, `fetch` | The name in usage totals, the time a part read may take (180 s), a custom fetch. |
|
|
385
|
+
|
|
386
|
+
The model's own message goes back to it as it came (a server may want its `reasoning_content` or a
|
|
387
|
+
signature again). `fromOpenAiMessages(history)` returns `{ system, messages }` for a history kept
|
|
388
|
+
as Chat Completions messages, and `openAiToolTurns(toolTurns)` gives stored rounds in that form.
|
|
389
|
+
|
|
390
|
+
## `llm-large-files/anthropic`
|
|
391
|
+
|
|
392
|
+
### `anthropic(options): ModelAdapter`
|
|
393
|
+
|
|
394
|
+
Claude through the Messages API. Not run against the API for this release: it is tested against
|
|
395
|
+
the request and response shapes of its documentation.
|
|
396
|
+
|
|
397
|
+
| Option | Description |
|
|
398
|
+
|---|---|
|
|
399
|
+
| `model` | Required: `"claude-opus-5-5"`. |
|
|
400
|
+
| `apiKey`, `authToken` | `x-api-key`, or `Authorization: Bearer …`. A function is called for each request. |
|
|
401
|
+
| `baseUrl`, `url`, `headers`, `version`, `betas` | For a gateway that speaks the same API: `/v1/messages` is added to `baseUrl`. `version` is the `anthropic-version` header (default `2026-10-21`). |
|
|
402
|
+
| `maxTokens` | `max_tokens` of a chat request. Default 64,000. It comes out of the context window, so the budget of a question keeps it free. |
|
|
403
|
+
| `body` | More fields for every chat request: `thinking`, `output_config`, `context_management`. |
|
|
404
|
+
| `analysisBody` | `(maxOutputTokens) => fields` for whole-file part reads, such as `{ output_config: { effort: "low" } }`. |
|
|
405
|
+
| `fallbacks` | `"default"`, or a list of `{ model }`: another model answers when a safety classifier declines the request. Off unless set: it adds a beta header that Bedrock, Vertex AI and Foundry do not take. |
|
|
406
|
+
| `cache` | Prompt caching. `true` (default) for five minutes, `"1h"`, or `false`. A cache write costs a quarter more than plain input, and a read a tenth. |
|
|
407
|
+
| `toolFilePlacement` | `"inside"` (default): pages go into the tool result as a document block. `"beside"`: after the tool results. `"none"`: `view_pages` is not offered. |
|
|
408
|
+
| `stream` | Default `true`: chat requests are streamed, which keeps a long reply from timing out. |
|
|
409
|
+
| `contextTokens`, `maxRequestBytes`, `pageTokens`, `tokenScale` | Defaults: none, 32 MB, 3,500, and 1.35 (a guess for the current tokenizer, corrected during a question by the count the API reports). |
|
|
410
|
+
| `id`, `timeoutMs`, `fetch` | As above. |
|
|
411
|
+
|
|
412
|
+
What the adapter takes care of:
|
|
413
|
+
|
|
414
|
+
- The model's turn goes back exactly as it came, thinking blocks included, and the conversation is
|
|
415
|
+
never rewritten: Claude checks its thinking blocks against the conversation they were written
|
|
416
|
+
in. So old tool results are not shortened for Claude. When the room runs out, the next request is
|
|
417
|
+
the answer. For long conversations, turn on the API's own clearing of old tool results with
|
|
418
|
+
`body: { context_management: … }` and its beta in `betas`.
|
|
419
|
+
- The request for the answer keeps the tools and sends `tool_choice: { type: "none" }`.
|
|
420
|
+
- A refusal (`stop_reason: "refusal"`) is `blockReason: "refusal: <category>"`.
|
|
421
|
+
- No sampling settings are sent: the API of this version refuses `temperature`.
|
|
422
|
+
|
|
423
|
+
`fromAnthropicMessages(history)` and `anthropicToolTurns(toolTurns)` convert a history kept as
|
|
424
|
+
Messages API messages.
|
|
425
|
+
|
|
208
426
|
## `llm-large-files/node`
|
|
209
427
|
|
|
210
428
|
### `createDocumentHandlers(files, { getOwner? })`
|
package/docs/configuration.md
CHANGED
|
@@ -9,19 +9,89 @@ planner uses them to decide what goes into a request whole.
|
|
|
9
9
|
|---|---|---|
|
|
10
10
|
| `contextTokens` | 1,000,000 | The model's context window. |
|
|
11
11
|
| `maxRequestBytes` | 10,000,000 | The largest request body your connector accepts. Checked separately from tokens: non-English text and JSON escaping make bytes run ahead of tokens. |
|
|
12
|
-
| `inlineTokens` | 200,000 | The most document text sent whole in one request. Lower it to cut cost and latency; raise it to rely on the long context more. |
|
|
13
|
-
| `reservedTokens` | 64,000 | Kept free for the answer, tool results, and growing history. |
|
|
14
|
-
| `mapChunkTokens` | 100,000 | Part size when a whole file is read in parts. Smaller parts give more detailed notes but more model calls. |
|
|
12
|
+
| `inlineTokens` | half the window, 200,000 at most | The most document text sent whole in one request. Lower it to cut cost and latency; raise it to rely on the long context more. |
|
|
13
|
+
| `reservedTokens` | a quarter of the window, 64,000 at most | Kept free for the answer, tool results, and growing history. |
|
|
14
|
+
| `mapChunkTokens` | half the window, 100,000 at most | Part size when a whole file is read in parts. Smaller parts give more detailed notes but more model calls. |
|
|
15
15
|
| `maxMapChunks` | 30 | Refuse whole-file reads needing more model calls than this. 30 parts × 100K tokens = 3M tokens of input. |
|
|
16
|
-
| `toolResultCharacters` | 24,000 | Cap on one tool result, in characters. For a log that can be
|
|
16
|
+
| `toolResultCharacters` | 12% of the window, 24,000 at most | Cap on one tool result, in characters. For a log that can be 12,000 tokens. |
|
|
17
|
+
|
|
18
|
+
For a model with a smaller window, setting the window is enough: the rest follows it.
|
|
17
19
|
|
|
18
20
|
```ts
|
|
19
|
-
createLargeFiles({
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
createLargeFiles({ store, budget: { contextTokens: 128_000, maxRequestBytes: 4_000_000 } });
|
|
22
|
+
// → inlineTokens 64,000 · reservedTokens 32,000 · mapChunkTokens 64,000 · toolResultCharacters 15,360
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
A field you set stays as you set it. Values that cannot work together are an error when the
|
|
26
|
+
library is created: `reservedTokens` or `mapChunkTokens` at or above `contextTokens`.
|
|
27
|
+
`resolveBudget(partial)` gives the whole budget for any set of fields.
|
|
28
|
+
|
|
29
|
+
### One library, several models
|
|
30
|
+
|
|
31
|
+
The budget of a question is the library's, made to fit the model that is asked. An adapter can say
|
|
32
|
+
what its model takes:
|
|
33
|
+
|
|
34
|
+
```ts
|
|
35
|
+
const small = openAiCompatible({ baseUrl, apiKey, model: "small-model", contextTokens: 128_000 });
|
|
36
|
+
const result = await askWithFiles({ files, model: small, documentIds, messages });
|
|
37
|
+
result.budget; // the library's budget, fitted to a window of 128,000 tokens
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
- The smaller window holds: the library's `contextTokens`, or the model's. With an explorer, the
|
|
41
|
+
smallest of the three. The same for `maxRequestBytes`.
|
|
42
|
+
- Fields the library left open follow that window. Fields it set are kept, and lowered if they are
|
|
43
|
+
too large for it.
|
|
44
|
+
- `outputTokens` of a model is kept free on top: Claude counts `max_tokens` against the window.
|
|
45
|
+
- `tokenScale` is how many of the model's tokens one token of the library's estimate comes to. The
|
|
46
|
+
estimate is fitted to Gemini, so that is 1 there. For a tokenizer that counts more (the Claude
|
|
47
|
+
adapter says 1.35), the window is that much smaller in the library's terms.
|
|
48
|
+
- `budget` in `askWithFiles` (and in `prepare` and `tools`) changes fields for one question:
|
|
49
|
+
`budget: { inlineTokens: 20_000 }`.
|
|
50
|
+
|
|
51
|
+
### Limits and retries
|
|
52
|
+
|
|
53
|
+
What one question may do, in `limits` of `askWithFiles` and `askGemini`:
|
|
54
|
+
|
|
55
|
+
| Limit | Default | |
|
|
56
|
+
|---|---|---|
|
|
57
|
+
| `toolTurns` | 12 | Chat requests for one question, counting the answer. |
|
|
58
|
+
| `callsPerTurn` | 8 | Tool calls of one model turn that are run. The others are answered "send it again if you still need it". |
|
|
59
|
+
| `wholeDocumentReads` | 1 | How often each document may be read whole. One read is up to `maxMapChunks` requests. 0 refuses them all. |
|
|
60
|
+
| `inputTokens` | none | Once the question has used this many input tokens, over all its requests, the next request is the answer. A whole-file read that would pass it is refused with the numbers. |
|
|
61
|
+
| `requests` | none | The same, for the number of requests: the chat's and the part reads' together. |
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
await askWithFiles({ files, model, documentIds, messages, limits: { toolTurns: 8, inputTokens: 2_000_000 } });
|
|
23
65
|
```
|
|
24
66
|
|
|
67
|
+
A request that failed is sent again when another try can help: HTTP 408, 409, 429 and 5xx, and a
|
|
68
|
+
connection that failed. It waits 0.25 to 0.5 seconds, then twice and four times that, or as long as
|
|
69
|
+
the provider asks (`Retry-After`, or the `retryDelay` of Gemini's `RetryInfo`). It is not sent
|
|
70
|
+
again once text of the reply was shown, after you stopped the question, or when the provider asks
|
|
71
|
+
for a longer wait than `maxDelayMs`. The part reads of a whole-file read follow the same rule.
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
retry: { retries: 3, baseDelayMs: 500, maxDelayMs: 60_000 } // the defaults; retries: 0 turns it off
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### Room in the request
|
|
78
|
+
|
|
79
|
+
Every tool result stays in the conversation until the question is answered, and is sent again with
|
|
80
|
+
each later request. The loop counts the request as it grows, by the library's estimate and, once
|
|
81
|
+
the provider has answered, by the provider's own count:
|
|
82
|
+
|
|
83
|
+
- Before the calls of a turn run, each is given the room that is left, up to
|
|
84
|
+
`toolResultCharacters`. A result is cut to its room and says where to go on.
|
|
85
|
+
- When the room runs short, the results of all but the last three tool rounds are replaced by
|
|
86
|
+
stand-ins: `{ document, dropped: true, lines: "1-212", note: "… Read them again with
|
|
87
|
+
read_document if you need them." }`. `steps` then holds "Older tool results were shortened to
|
|
88
|
+
make room in the request". Claude's conversation is never rewritten, so this step is skipped for
|
|
89
|
+
it.
|
|
90
|
+
- A call that still finds no room is answered "no room left, answer now", and the next request is
|
|
91
|
+
the answer.
|
|
92
|
+
|
|
93
|
+
Text tools may fill the window up to half of `reservedTokens`; the other half is the answer's.
|
|
94
|
+
|
|
25
95
|
### How the plan is made
|
|
26
96
|
|
|
27
97
|
For each request, `prepare(ids, base)` takes the size of everything else (`base.tokens`,
|
|
@@ -119,7 +189,11 @@ tokens, and its answer is dropped.
|
|
|
119
189
|
- **`text` and `onText` carry only the answer.** Without an explorer, a remark that the model makes
|
|
120
190
|
before a tool call ("Let me search…") is part of `text`. The explorer's words are not shown.
|
|
121
191
|
`onActivity` and `onStep` report its tool calls as before, and `turns` counts its requests too.
|
|
122
|
-
`usage`
|
|
192
|
+
`usage` is the total of both models, with an entry for each in `usage.byModel`; `finishReason`
|
|
193
|
+
and `lastUsage` are those of the answer.
|
|
194
|
+
- **The explorer need not be a Gemini model.** With `askWithFiles`, `explorer` is any adapter:
|
|
195
|
+
`askWithFiles({ model: gemini(…), explorer: openAiCompatible(…) })`. The answering model gets
|
|
196
|
+
the explorer's calls and results in its own provider's form.
|
|
123
197
|
- **The explorer's requests are not streamed.** Nothing it writes is shown, so each goes to
|
|
124
198
|
`explorerUrl` in one piece. The answer streams as before.
|
|
125
199
|
- **Settings are per model.** `explorerGenerationConfig` is the explorer's `generationConfig`, and
|
package/docs/getting-started.md
CHANGED
|
@@ -138,9 +138,15 @@ What `askGemini` does each turn:
|
|
|
138
138
|
3. Adds each document's text or card at the start of the first user message, where it stays for
|
|
139
139
|
the whole conversation (so follow-up questions reuse Gemini's prompt cache), and a short tool
|
|
140
140
|
guide to the system prompt.
|
|
141
|
-
4. Runs the tool loop if needed (up to `
|
|
141
|
+
4. Runs the tool loop if needed (up to `limits.toolTurns` requests, default 12). If the model keeps
|
|
142
142
|
searching, the last request is sent without tools so it has to answer. `result.answered` is
|
|
143
143
|
`false` in the rare case that there is still no answer (a blocked prompt, or an empty reply).
|
|
144
|
+
5. Sends a request again when the model was busy or could not be reached, keeps the request
|
|
145
|
+
inside the model's window as tool results add up, and returns what the question used
|
|
146
|
+
(`result.usage`) and what it read (`result.evidence`).
|
|
147
|
+
|
|
148
|
+
`askGemini` is `askWithFiles` with a Gemini model. Everything it does, it does for
|
|
149
|
+
[any other model](#with-another-model-askwithfiles) too.
|
|
144
150
|
|
|
145
151
|
**Vertex AI:**
|
|
146
152
|
|
|
@@ -212,27 +218,57 @@ Kept files take disk space until they expire, which is why this is off by defaul
|
|
|
212
218
|
costs and the measurements are in [Pictures in PDFs](configuration.md#pictures-in-pdfs), and what
|
|
213
219
|
to think about before turning it on in [Security](security.md#original-files).
|
|
214
220
|
|
|
215
|
-
### With another model:
|
|
221
|
+
### With another model: `askWithFiles`
|
|
222
|
+
|
|
223
|
+
The loop is not Gemini's. `askWithFiles` takes the model as an adapter, and two adapters come with
|
|
224
|
+
the package next to Gemini's:
|
|
225
|
+
|
|
226
|
+
```ts
|
|
227
|
+
import { askWithFiles, DocumentsNotFoundError, ModelRequestError } from "llm-large-files";
|
|
228
|
+
import { openAiCompatible } from "llm-large-files/openai";
|
|
229
|
+
import { anthropic } from "llm-large-files/anthropic";
|
|
230
|
+
|
|
231
|
+
// Any Chat Completions endpoint: OpenAI, Azure OpenAI, DeepSeek, LiteLLM, vLLM, Ollama, OpenRouter.
|
|
232
|
+
const model = openAiCompatible({
|
|
233
|
+
baseUrl: "https://api.deepseek.com/v1",
|
|
234
|
+
apiKey: process.env.DEEPSEEK_API_KEY!,
|
|
235
|
+
model: "deepseek-v4-pro",
|
|
236
|
+
contextTokens: 1_000_000, // the budget of a question follows it
|
|
237
|
+
body: { temperature: 0.3 },
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
// Or Claude:
|
|
241
|
+
const claude = anthropic({ apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-opus-5-5", fallbacks: "default" });
|
|
242
|
+
|
|
243
|
+
const result = await askWithFiles({
|
|
244
|
+
files, model, documentIds, messages,
|
|
245
|
+
owner: req.user?.id,
|
|
246
|
+
system: "You are our support assistant.",
|
|
247
|
+
signal: abort.signal,
|
|
248
|
+
onText: (text) => send("text", text),
|
|
249
|
+
onActivity: (text) => send("activity", text),
|
|
250
|
+
onStep: (text) => send("step", text),
|
|
251
|
+
});
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
`messages` are `{ role: "user" | "assistant", text }`. A turn that holds more than text takes
|
|
255
|
+
parts, with anything but text in the provider's own form:
|
|
256
|
+
`{ role: "user", parts: [{ text: "What is in this picture?" }, { native: { type: "image_url", image_url: { url } } }] }`.
|
|
216
257
|
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
(`{ name, description, input_schema: parameters }`) also accept.
|
|
258
|
+
**Two models, of two providers.** `explorer` is a second adapter. It makes the tool calls and
|
|
259
|
+
reads whole files in parts, and `model` writes the answer from what the tools returned:
|
|
220
260
|
|
|
221
261
|
```ts
|
|
222
|
-
|
|
223
|
-
// 1. Add prepared.blocks.get(id) for each document to the user's message.
|
|
224
|
-
// 2. Add prepared.instruction to the system prompt.
|
|
225
|
-
// 3. If prepared.plan.searchable is not empty, give the model tools:
|
|
226
|
-
const tools = files.tools(prepared.plan.searchable, { generate: myTextCompletion /* optional: enables analyze-all */ });
|
|
227
|
-
// tools.declarations → your SDK's tool format
|
|
228
|
-
// for each tool call: const result = await tools.execute(call.name, call.args)
|
|
229
|
-
// return result to the model; repeat until it answers.
|
|
262
|
+
await askWithFiles({ files, model: claude, explorer: model, documentIds, messages });
|
|
230
263
|
```
|
|
231
264
|
|
|
232
|
-
|
|
233
|
-
|
|
265
|
+
**Errors.** A model's HTTP error is a `ModelRequestError` with a `status` (0 when the model could
|
|
266
|
+
not be reached). It reaches you after the request was tried again, when another try could have
|
|
267
|
+
helped.
|
|
234
268
|
|
|
235
|
-
|
|
269
|
+
**A model without an adapter** needs one object with a `send` method:
|
|
270
|
+
[your own adapter](api.md#your-own-adapter). `files.prepare()` and `files.tools()` are still there
|
|
271
|
+
for a loop that is all your own; `view_pages` in such a loop is described in
|
|
236
272
|
[Your own loop](configuration.md#your-own-loop).
|
|
237
273
|
|
|
238
274
|
## Keeping the conversation working
|
|
@@ -241,6 +277,21 @@ To offer `view_pages` in your own loop, it has to send a file to the model with
|
|
|
241
277
|
because the history grows. Stateful APIs that keep history server-side (such as Gemini
|
|
242
278
|
Interactions with `previous_interaction_id`) don't mix with per-turn planning.
|
|
243
279
|
- Keep the document IDs with the conversation, not with one message. Pass all of them on every turn.
|
|
280
|
+
- Keep **what a question read** with the conversation too. `result.toolTurns` is plain JSON: store
|
|
281
|
+
it between the question and its answer, and pass it back in `messages` in that place. The model
|
|
282
|
+
then sees its earlier searches and reads, and a follow-up question often needs no new one. In a
|
|
283
|
+
live check a follow-up took one request instead of three.
|
|
284
|
+
|
|
285
|
+
```ts
|
|
286
|
+
const messages = history.flatMap((turn) => [
|
|
287
|
+
{ role: "user", text: turn.question }, ...turn.toolTurns, { role: "assistant", text: turn.answer },
|
|
288
|
+
]).concat({ role: "user", text: newQuestion });
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
If your history is Gemini `contents`, `geminiToolTurns(result.toolTurns)` gives the rounds in
|
|
292
|
+
that form.
|
|
293
|
+
- `result.evidence` lists, for each tool call, the document and the lines or pages the model was
|
|
294
|
+
shown. Store it with the answer if you want to show sources, or to check a citation later.
|
|
244
295
|
- Expired documents raise `DocumentsNotFoundError` (with `.ids`). Ask the user to attach them again.
|
|
245
296
|
A store that could not be read raises `DocumentStoreError` instead: the documents are still
|
|
246
297
|
there, so retry the request. With `ttlMs: Infinity` documents do not expire at all.
|
package/docs/how-it-works.md
CHANGED
|
@@ -112,7 +112,42 @@ tool: it reports `total_matching_lines`.
|
|
|
112
112
|
|
|
113
113
|
Jobs needing more than `maxMapChunks` parts are refused, with advice to narrow the question first.
|
|
114
114
|
|
|
115
|
-
## The
|
|
115
|
+
## The loop (`askWithFiles`)
|
|
116
|
+
|
|
117
|
+
One loop serves every model. A provider is an adapter that turns the loop's request into its own
|
|
118
|
+
and reads the reply back; everything else happens once, in the core:
|
|
119
|
+
|
|
120
|
+
- **Retries.** A request that failed with HTTP 408, 409, 429 or 5xx, or that got no answer, is sent
|
|
121
|
+
again after a wait that doubles, or after the wait the provider asks for. Not after text of the
|
|
122
|
+
reply was shown, and not after a refusal such as 400 or 401. The part reads of a whole-file read
|
|
123
|
+
follow the same rule.
|
|
124
|
+
- **Calls of one turn run together**, four at a time, and are answered in the order they were made.
|
|
125
|
+
Looks at pages run one after another, because each is given the room the one before it left.
|
|
126
|
+
Regex searches do too: they share the time of the tool set. At most eight calls of a turn run.
|
|
127
|
+
- **Room.** The loop counts the request as it grows. Each call gets the room that is left, old
|
|
128
|
+
results are shortened to stand-ins when it runs short, and a call that finds none ends the tools:
|
|
129
|
+
the next request is the answer. See [Room in the request](configuration.md#room-in-the-request).
|
|
130
|
+
- **One whole-file read** of each document for a question. A model that asks again, with the task
|
|
131
|
+
put another way, is told to use the answer it has.
|
|
132
|
+
- **Usage** is summed over every request, the part reads included, for each model.
|
|
133
|
+
- **Evidence** is read from the tool calls: for each, the document and the lines or pages shown.
|
|
134
|
+
- **A call that did not arrive whole** (arguments that are not JSON, or cut off at the output
|
|
135
|
+
limit) is answered with what was wrong, and not run.
|
|
136
|
+
- **The end.** When the turns or the room run out, or the model's last turn has no text, one more
|
|
137
|
+
request must be answered in text. For Gemini it declares no tools; for an OpenAI-compatible
|
|
138
|
+
endpoint and for Claude it keeps them and sets the tool choice to none.
|
|
139
|
+
|
|
140
|
+
What differs between providers is in the adapters:
|
|
141
|
+
|
|
142
|
+
| | Gemini | OpenAI-compatible | Claude |
|
|
143
|
+
|---|---|---|---|
|
|
144
|
+
| The model's turn goes back | unchanged: thought signatures | unchanged: `reasoning_content`, signatures | unchanged: thinking blocks |
|
|
145
|
+
| The request for the answer | no tools declared | `tool_choice: "none"`, tools kept | `tool_choice: none`, tools kept |
|
|
146
|
+
| Pages of `view_pages` | inside the function response | a `file` part after the results, opt-in | a document block in the tool result |
|
|
147
|
+
| Old results shortened for room | yes | yes | no: the conversation may only grow |
|
|
148
|
+
| Prompt cache | the provider's own | the provider's own | `cache_control` on each request |
|
|
149
|
+
|
|
150
|
+
## Gemini (`askGemini`, `gemini()`)
|
|
116
151
|
|
|
117
152
|
- Document text and cards go at the **start of the first user turn** and stay there as the
|
|
118
153
|
conversation grows. Gemini's prompt cache works on a matching prefix, so a follow-up question
|
|
@@ -136,7 +171,8 @@ Jobs needing more than `maxMapChunks` parts are refused, with advice to narrow t
|
|
|
136
171
|
responses, because Vertex AI refuses a turn in which anything follows one. Both forms work with
|
|
137
172
|
Gemini 3.5 on the Gemini API and on Vertex AI.
|
|
138
173
|
- Tool results, pages included, live inside one call of `askGemini`. They are not sent again with
|
|
139
|
-
the next question.
|
|
174
|
+
the next question unless you pass `result.toolTurns` back with the conversation. Pages are not
|
|
175
|
+
in those: a stored round says that they were shown.
|
|
140
176
|
|
|
141
177
|
### With an explorer model
|
|
142
178
|
|