llm-large-files 0.5.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1719 -466
- package/README.md +190 -60
- package/dist/analyze.d.ts +8 -1
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +198 -54
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts +14 -3
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +194 -40
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +63 -7
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +1131 -214
- package/dist/ask.js.map +1 -1
- package/dist/decode.d.ts +19 -0
- package/dist/decode.d.ts.map +1 -0
- package/dist/decode.js +97 -0
- package/dist/decode.js.map +1 -0
- package/dist/encoding.d.ts +17 -0
- package/dist/encoding.d.ts.map +1 -0
- package/dist/encoding.js +852 -0
- package/dist/encoding.js.map +1 -0
- package/dist/errors.d.ts +59 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +80 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +339 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +163 -0
- package/dist/events.js.map +1 -0
- package/dist/evidence.d.ts +2 -0
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +9 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +26 -7
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +180 -314
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +17 -8
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +117 -66
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +23 -3
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +6 -2
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +5 -1
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +11 -2
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/errors.d.ts +9 -4
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +32 -0
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +10 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +33 -10
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -2
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -1
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -1
- package/dist/gemini/sse.js.map +1 -1
- package/dist/groups.d.ts +54 -0
- package/dist/groups.d.ts.map +1 -0
- package/dist/groups.js +136 -0
- package/dist/groups.js.map +1 -0
- package/dist/html.d.ts +11 -0
- package/dist/html.d.ts.map +1 -0
- package/dist/html.js +1112 -0
- package/dist/html.js.map +1 -0
- package/dist/http.d.ts +116 -0
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +347 -1
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +13 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -5
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +67 -5
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +449 -93
- package/dist/library.js.map +1 -1
- package/dist/limiter.d.ts +2 -1
- package/dist/limiter.d.ts.map +1 -1
- package/dist/limiter.js +3 -2
- package/dist/limiter.js.map +1 -1
- package/dist/map-reduce.d.ts +28 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +240 -52
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +84 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +190 -2
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +20 -4
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +184 -28
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +4 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +38 -0
- package/dist/node/ingest-child.d.ts.map +1 -0
- package/dist/node/ingest-child.js +42 -0
- package/dist/node/ingest-child.js.map +1 -0
- package/dist/node/isolated.d.ts +88 -0
- package/dist/node/isolated.d.ts.map +1 -0
- package/dist/node/isolated.js +381 -0
- package/dist/node/isolated.js.map +1 -0
- package/dist/node/sse.d.ts +59 -0
- package/dist/node/sse.d.ts.map +1 -0
- package/dist/node/sse.js +174 -0
- package/dist/node/sse.js.map +1 -0
- package/dist/office.d.ts +105 -0
- package/dist/office.d.ts.map +1 -0
- package/dist/office.js +1092 -0
- package/dist/office.js.map +1 -0
- package/dist/openai/adapter.d.ts +29 -5
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +325 -37
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +14 -2
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +39 -10
- package/dist/output-limit.js.map +1 -1
- package/dist/pause.d.ts +24 -0
- package/dist/pause.d.ts.map +1 -0
- package/dist/pause.js +38 -0
- package/dist/pause.js.map +1 -0
- package/dist/pdf-pages.d.ts +32 -2
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +277 -20
- package/dist/pdf-pages.js.map +1 -1
- package/dist/pdf-pictures.d.ts +30 -3
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +50 -8
- package/dist/pdf-pictures.js.map +1 -1
- package/dist/pdf-work.d.ts +40 -0
- package/dist/pdf-work.d.ts.map +1 -0
- package/dist/pdf-work.js +734 -0
- package/dist/pdf-work.js.map +1 -0
- package/dist/peers.d.ts +8 -0
- package/dist/peers.d.ts.map +1 -0
- package/dist/peers.js +32 -0
- package/dist/peers.js.map +1 -0
- package/dist/plan.d.ts +22 -4
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +61 -12
- package/dist/plan.js.map +1 -1
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +4 -2
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +23 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +33 -3
- package/dist/retry.js.map +1 -1
- package/dist/search.d.ts +107 -24
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +803 -149
- package/dist/search.js.map +1 -1
- package/dist/sse.d.ts +35 -2
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +145 -31
- package/dist/sse.js.map +1 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +5 -2
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +9 -1
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +28 -9
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +87 -3
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +526 -24
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +61 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +461 -46
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +103 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/word-styles.d.ts +102 -0
- package/dist/word-styles.d.ts.map +1 -0
- package/dist/word-styles.js +419 -0
- package/dist/word-styles.js.map +1 -0
- package/dist/xlsx.d.ts +23 -0
- package/dist/xlsx.d.ts.map +1 -0
- package/dist/xlsx.js +511 -0
- package/dist/xlsx.js.map +1 -0
- package/dist/xml-stream.d.ts +55 -0
- package/dist/xml-stream.d.ts.map +1 -0
- package/dist/xml-stream.js +235 -0
- package/dist/xml-stream.js.map +1 -0
- package/dist/zip-directory.d.ts +43 -0
- package/dist/zip-directory.d.ts.map +1 -0
- package/dist/zip-directory.js +130 -0
- package/dist/zip-directory.js.map +1 -0
- package/docs/README.md +288 -0
- package/docs/api.md +37 -381
- package/docs/configuration.md +28 -558
- package/docs/getting-started.md +407 -223
- package/docs/guides/anthropic.md +590 -0
- package/docs/guides/conversations.md +629 -0
- package/docs/guides/costs-and-limits.md +728 -0
- package/docs/guides/deployment.md +720 -0
- package/docs/guides/errors-and-reliability.md +748 -0
- package/docs/guides/explorer-model.md +399 -0
- package/docs/guides/openai-compatible.md +602 -0
- package/docs/guides/own-adapter-and-loop.md +1169 -0
- package/docs/guides/pdfs.md +1024 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1203 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1590 -0
- package/docs/how-it-works.md +1035 -164
- package/docs/measurements.md +881 -0
- package/docs/publishing.md +274 -46
- package/docs/reference/anthropic.md +427 -0
- package/docs/reference/ask.md +910 -0
- package/docs/reference/errors-and-retries.md +760 -0
- package/docs/reference/events.md +1001 -0
- package/docs/reference/gemini.md +827 -0
- package/docs/reference/library.md +1598 -0
- package/docs/reference/node.md +706 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +1031 -0
- package/docs/security.md +940 -101
- package/docs/troubleshooting.md +1410 -0
- package/package.json +7 -3
- package/src/analyze.ts +204 -49
- package/src/anthropic/adapter.ts +200 -40
- package/src/ask.ts +1151 -210
- package/src/decode.ts +89 -0
- package/src/encoding.ts +850 -0
- package/src/errors.ts +125 -0
- package/src/events.ts +451 -0
- package/src/evidence.ts +11 -2
- package/src/extract.ts +191 -308
- package/src/gemini/adapter.ts +127 -70
- package/src/gemini/chat.ts +28 -4
- package/src/gemini/endpoints.ts +12 -2
- package/src/gemini/errors.ts +34 -1
- package/src/gemini/generate.ts +42 -13
- package/src/gemini/index.ts +3 -3
- package/src/gemini/sse.ts +1 -1
- package/src/groups.ts +162 -0
- package/src/html.ts +1071 -0
- package/src/http.ts +376 -1
- package/src/index.ts +29 -6
- package/src/library.ts +498 -93
- package/src/limiter.ts +6 -1
- package/src/map-reduce.ts +252 -51
- package/src/model.ts +244 -4
- package/src/node/handlers.ts +196 -31
- package/src/node/index.ts +4 -0
- package/src/node/ingest-child.ts +61 -0
- package/src/node/isolated.ts +464 -0
- package/src/node/sse.ts +198 -0
- package/src/office.ts +1047 -0
- package/src/openai/adapter.ts +319 -38
- package/src/output-limit.ts +44 -8
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +270 -20
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/peers.ts +29 -0
- package/src/plan.ts +70 -12
- package/src/ranged.ts +4 -2
- package/src/retry.ts +49 -5
- package/src/search.ts +800 -155
- package/src/sse.ts +153 -28
- package/src/stores.ts +5 -2
- package/src/text-index.ts +30 -9
- package/src/text.ts +524 -23
- package/src/tools.ts +445 -46
- package/src/types.ts +108 -5
- package/src/word-styles.ts +420 -0
- package/src/xlsx.ts +478 -0
- package/src/xml-stream.ts +224 -0
- package/src/zip-directory.ts +136 -0
|
@@ -0,0 +1,629 @@
|
|
|
1
|
+
# Conversations
|
|
2
|
+
|
|
3
|
+
This guide is for applications that ask more than one question in a chat. It covers the format of
|
|
4
|
+
`messages`, what to keep after each answer and how to send it back, how to keep a long history
|
|
5
|
+
inside the model's window, and how to work with a history kept in a provider's own format. It
|
|
6
|
+
applies to `askWithFiles` and to `askGemini`, which runs it.
|
|
7
|
+
|
|
8
|
+
## The message format
|
|
9
|
+
|
|
10
|
+
`askWithFiles` takes the conversation as `messages: ChatMessage[]`, oldest first. A `ChatMessage`
|
|
11
|
+
is one of three kinds:
|
|
12
|
+
|
|
13
|
+
| Kind | Shape | What it is |
|
|
14
|
+
|---|---|---|
|
|
15
|
+
| `ChatTurn` | `{ role: "user" \| "assistant" \| "model", text }` | A plain turn. `"model"` is the same as `"assistant"`. |
|
|
16
|
+
| `ToolTurn` | `{ role: "tools", calls: [{ id?, name, args, result }] }` | One tool round of an earlier question, as `AskResult.toolTurns` returned it. |
|
|
17
|
+
| `ModelTextMessage` | `{ role: "user" \| "assistant", parts: [{ text } \| { native, text? }] }` | A turn with parts in the provider's own form: an image, an inline PDF. |
|
|
18
|
+
|
|
19
|
+
The rules:
|
|
20
|
+
|
|
21
|
+
- **The last message is the user's question.** Otherwise `askWithFiles` throws
|
|
22
|
+
`Error("The last message must be the user's.")` before it sends anything.
|
|
23
|
+
- **Send the whole conversation with every question.** The library keeps nothing between
|
|
24
|
+
questions. The plan of the documents, the tools on offer and the room in the request are worked
|
|
25
|
+
out again each time, from the conversation you pass. Any server can answer the next question
|
|
26
|
+
([Deployment](./deployment.md)). An API that keeps the history on the provider's side does not
|
|
27
|
+
fit this.
|
|
28
|
+
- **Send the question as the user wrote it.** The loop adds the document text and cards on each
|
|
29
|
+
request: at the start of the first user turn (`documentPlacement: "first"`, the default), or at
|
|
30
|
+
the end of the last (`"last"`). Never store them in your history.
|
|
31
|
+
- **What you pass is not changed.** The loop works on copies.
|
|
32
|
+
- **A `native` part goes unchanged to every model of the question**: a Gemini part to `gemini()`, a
|
|
33
|
+
Chat Completions content part to `openAiCompatible()`, a Messages API block to `anthropic()`.
|
|
34
|
+
With an [explorer model](./explorer-model.md) of another provider, both models get it, so both
|
|
35
|
+
must read it. A native part that also has `text` is sized by that text; one without is sized by
|
|
36
|
+
the length of its JSON, as media.
|
|
37
|
+
|
|
38
|
+
Annotate the array as `ChatMessage[]`. Without the annotation TypeScript widens `role` to
|
|
39
|
+
`string`, and the array is not accepted as `messages`.
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
import { readFile } from "node:fs/promises";
|
|
43
|
+
import { GoogleAuth } from "google-auth-library";
|
|
44
|
+
import { askWithFiles, type ChatMessage } from "llm-large-files";
|
|
45
|
+
import { gemini, vertexAi } from "llm-large-files/gemini";
|
|
46
|
+
|
|
47
|
+
// `files` is your library and `documentIds` the documents of this chat (see Getting started).
|
|
48
|
+
const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
|
|
49
|
+
const model = gemini(vertexAi({
|
|
50
|
+
project: process.env.GOOGLE_CLOUD_PROJECT!,
|
|
51
|
+
model: "gemini-3.8-flash",
|
|
52
|
+
accessToken: async () => (await auth.getAccessToken())!,
|
|
53
|
+
}));
|
|
54
|
+
|
|
55
|
+
const question = "Where is the first error in app.log?";
|
|
56
|
+
const first = await askWithFiles({ files, model, documentIds, messages: [{ role: "user", text: question }] });
|
|
57
|
+
|
|
58
|
+
const chart = (await readFile("chart.png")).toString("base64");
|
|
59
|
+
const messages: ChatMessage[] = [
|
|
60
|
+
{ role: "user", text: question },
|
|
61
|
+
...first.toolTurns, // what the tools returned, between the question and its answer
|
|
62
|
+
...(first.answered ? [{ role: "assistant" as const, text: first.text }] : []), // only an answer
|
|
63
|
+
// A turn with a part in Gemini's own form.
|
|
64
|
+
{ role: "user", parts: [{ text: "Does this chart show the same outage?" }, { native: { inlineData: { mimeType: "image/png", data: chart } } }] },
|
|
65
|
+
];
|
|
66
|
+
const second = await askWithFiles({ files, model, documentIds, messages });
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`askGemini` takes the conversation in one of two options. `messages` takes plain turns and stored
|
|
70
|
+
tool rounds (`Array<ChatTurn | ToolTurn>`), and no native parts. `contents` takes Gemini
|
|
71
|
+
`contents`, native parts included, and converts them with `fromGeminiContents`
|
|
72
|
+
([below](#gemini-contents)). When both are given, `contents` is used. For native parts and stored
|
|
73
|
+
tool rounds in one history, call `askWithFiles` with `gemini(endpoint)`, as above; an explorer
|
|
74
|
+
model is then passed as `explorer` ([Explorer model](./explorer-model.md)).
|
|
75
|
+
|
|
76
|
+
Every field of these types is in the reference: [`askWithFiles(options)`](../reference/ask.md#askwithfilesoptions)
|
|
77
|
+
and the rest of [ask.md](../reference/ask.md).
|
|
78
|
+
|
|
79
|
+
## What `toolTurns` holds
|
|
80
|
+
|
|
81
|
+
`AskResult.toolTurns` is the tool rounds of the question, in order, as plain JSON. A round is the
|
|
82
|
+
tool calls of one model turn, each with what its tool returned:
|
|
83
|
+
|
|
84
|
+
```json
|
|
85
|
+
{
|
|
86
|
+
"role": "tools",
|
|
87
|
+
"calls": [
|
|
88
|
+
{
|
|
89
|
+
"id": "c1",
|
|
90
|
+
"name": "read_document",
|
|
91
|
+
"args": { "document_id": "doc_3f2a…", "start_line": 96, "end_line": 98 },
|
|
92
|
+
"result": { "document": "app.log", "lines": "96-98", "total_lines": 5000, "text": "96| …", "next_start_line": 99, "tool_turns_left": 10 }
|
|
93
|
+
}
|
|
94
|
+
]
|
|
95
|
+
}
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
- `id` is the provider's own ID of the call, when it gave one. `args` and `result` are what the
|
|
99
|
+
model sent and what it was given back. The tools and their results are in
|
|
100
|
+
[Tools](../reference/tools.md).
|
|
101
|
+
- Each result is **as the model last had it**. One that was shortened during the question to make
|
|
102
|
+
room is stored as its stand-in (`dropped: true`). Every result, pointer and refusal carries
|
|
103
|
+
`tool_turns_left`, the tool turns the question had left then. A stand-in does not.
|
|
104
|
+
- **`tool_turns_left` is stored, and not sent again.** When you pass the rounds back in a later
|
|
105
|
+
question, the results go to the model without it: its count was of the turns their own question
|
|
106
|
+
had left, and a model could take a 0 there for its own. So the first request of a follow-up
|
|
107
|
+
differs from the requests of the question before it, from that question's first tool round on.
|
|
108
|
+
The provider's prompt cache misses from there, once in each follow-up question, in its first
|
|
109
|
+
request; the rounds of older questions were already sent without the count and still match, and
|
|
110
|
+
the documents and cards before the rounds are still read from the cache
|
|
111
|
+
([Costs and limits](./costs-and-limits.md#prompt-caching)).
|
|
112
|
+
- Calls that were not run are there too, with an `error`: for example refused for lack of room,
|
|
113
|
+
past `limits.callsPerTurn`, or whose arguments could not be read. So are pointers to results already
|
|
114
|
+
shown ([Repeated calls](#repeated-calls-in-a-follow-up)).
|
|
115
|
+
- **Pages are not in them.** A `view_pages` result is stored as a stand-in that says which pages
|
|
116
|
+
were shown: `{ document, pages: "2-3", total_pages, dropped: true, note: "These pages were shown
|
|
117
|
+
to you earlier and are no longer attached. Look at them again with view_pages if you need
|
|
118
|
+
them." }`.
|
|
119
|
+
- **No provider's own form.** A stored round has no thought signatures, thinking blocks or other
|
|
120
|
+
raw parts of the model turn. Any adapter can be given it, and builds the turn from the calls.
|
|
121
|
+
- Only the rounds of this question. The stored rounds you passed in `messages` are not repeated.
|
|
122
|
+
- With an explorer model they are the explorer's rounds. Its words are not kept.
|
|
123
|
+
- They are there when `answered` is false, and in `partialResultOf(error)` when the question failed.
|
|
124
|
+
|
|
125
|
+
`limits.toolTurns` is something else: the most chat requests of one question, the answer included,
|
|
126
|
+
plus one more when the answer comes back without text. Whole-file part reads do not count toward
|
|
127
|
+
it ([Costs and limits](./costs-and-limits.md)).
|
|
128
|
+
|
|
129
|
+
**Why keep them.** Passed back between their question and its answer, the rounds show the model
|
|
130
|
+
what it searched and read before. A follow-up is then often answered without a new search, and a
|
|
131
|
+
call that repeats one of them is answered from the stored result
|
|
132
|
+
([below](#repeated-calls-in-a-follow-up)). In a live check of 0.5.0 a follow-up took one request
|
|
133
|
+
and no search; in a live check of the pointers on Vertex AI, during the work on 0.6.0, a follow-up
|
|
134
|
+
that repeated its first search got a pointer and answered from the stored result
|
|
135
|
+
([Measurements](../measurements.md)).
|
|
136
|
+
|
|
137
|
+
## Storing a conversation and asking the next question
|
|
138
|
+
|
|
139
|
+
What to keep for each question:
|
|
140
|
+
|
|
141
|
+
| Keep | From | Why |
|
|
142
|
+
|---|---|---|
|
|
143
|
+
| The question | What the user typed | The user turn of the history. Not the document text: the loop adds it. |
|
|
144
|
+
| The tool rounds | `result.toolTurns` | Sent back between the question and its answer. |
|
|
145
|
+
| The answer | `result.text`, when `result.answered` is true | The assistant turn. |
|
|
146
|
+
| The documents | Your session record | Passed as `documentIds` on every question ([below](#owners-and-documents-across-turns)). |
|
|
147
|
+
| `evidence` | `result.evidence` | Optional: the document and the lines or pages each call showed, to show sources or check a citation. |
|
|
148
|
+
| `usage` | `result.usage` | Optional: tokens and requests of the question, to count cost per user or session ([Costs and limits](./costs-and-limits.md)). |
|
|
149
|
+
|
|
150
|
+
An answer that is not one (`answered: false`) is not stored as the assistant's turn: the model
|
|
151
|
+
would read your error message as its own words. Keep the question and its tool rounds, so a second
|
|
152
|
+
try can use what was found.
|
|
153
|
+
|
|
154
|
+
**Keep the tool rounds apart from the session record.** One question's `toolTurns` can be large: a
|
|
155
|
+
result is up to `toolResultCharacters` (24,000 characters by default; the answer of a whole-file
|
|
156
|
+
read up to 40,000), a turn runs up to 8 calls, and tools run in up to 11 requests of a question. With the default limits that is up to about
|
|
157
|
+
2 million characters, less when the request runs out of room first. A session record that embeds
|
|
158
|
+
every turn reaches a database's limit on one record (16 MB in MongoDB) after a handful of such
|
|
159
|
+
questions.
|
|
160
|
+
|
|
161
|
+
This sample keeps sessions in one MongoDB collection and one record per question in another, and
|
|
162
|
+
asks with Gemini on Vertex AI. `files` is your library ([Getting started](../getting-started.md)).
|
|
163
|
+
|
|
164
|
+
```ts
|
|
165
|
+
import { GoogleAuth } from "google-auth-library";
|
|
166
|
+
import { MongoClient } from "mongodb";
|
|
167
|
+
import { partialResultOf, type AskResult, type ChatTurn, type Evidence, type ToolTurn, type UsageTotals } from "llm-large-files";
|
|
168
|
+
import { askGemini, vertexAi } from "llm-large-files/gemini";
|
|
169
|
+
|
|
170
|
+
/** One chat. Its questions are kept apart, one record each. */
|
|
171
|
+
type SessionRecord = { _id: string; userId: string; documentIds: string[] };
|
|
172
|
+
|
|
173
|
+
/** One question of a chat and what came of it. */
|
|
174
|
+
type TurnRecord = {
|
|
175
|
+
sessionId: string;
|
|
176
|
+
index: number;
|
|
177
|
+
question: string;
|
|
178
|
+
toolTurns: ToolTurn[];
|
|
179
|
+
answer?: string; // only when the question was answered
|
|
180
|
+
evidence: Evidence[];
|
|
181
|
+
usage: UsageTotals;
|
|
182
|
+
createdAt: Date;
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
const mongo = new MongoClient(process.env.MONGODB_URI!);
|
|
186
|
+
const sessions = mongo.db("chat").collection<SessionRecord>("sessions");
|
|
187
|
+
const turns = mongo.db("chat").collection<TurnRecord>("turns");
|
|
188
|
+
|
|
189
|
+
const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
|
|
190
|
+
const endpoint = vertexAi({
|
|
191
|
+
project: process.env.GOOGLE_CLOUD_PROJECT!,
|
|
192
|
+
model: "gemini-3.8-flash",
|
|
193
|
+
accessToken: async () => (await auth.getAccessToken())!,
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
/** The messages of the next question: each earlier question, its tool rounds, its answer. */
|
|
197
|
+
function historyOf(earlier: TurnRecord[], question: string): Array<ChatTurn | ToolTurn> {
|
|
198
|
+
return [
|
|
199
|
+
...earlier.flatMap((turn): Array<ChatTurn | ToolTurn> => [
|
|
200
|
+
{ role: "user", text: turn.question },
|
|
201
|
+
...turn.toolTurns,
|
|
202
|
+
...(turn.answer !== undefined ? [{ role: "assistant" as const, text: turn.answer }] : []),
|
|
203
|
+
]),
|
|
204
|
+
{ role: "user", text: question },
|
|
205
|
+
];
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export async function ask(sessionId: string, userId: string, question: string, onText: (delta: string) => void, signal: AbortSignal): Promise<AskResult> {
|
|
209
|
+
const session = await sessions.findOne({ _id: sessionId, userId });
|
|
210
|
+
if (!session) throw new Error("No such chat.");
|
|
211
|
+
const earlier = await turns.find({ sessionId }).sort({ index: 1 }).toArray();
|
|
212
|
+
const asked = { sessionId, index: earlier.length, question, createdAt: new Date() };
|
|
213
|
+
try {
|
|
214
|
+
const result = await askGemini({
|
|
215
|
+
files,
|
|
216
|
+
endpoint,
|
|
217
|
+
owner: userId,
|
|
218
|
+
documentIds: session.documentIds,
|
|
219
|
+
messages: historyOf(earlier, question),
|
|
220
|
+
onText,
|
|
221
|
+
signal,
|
|
222
|
+
});
|
|
223
|
+
await turns.insertOne({
|
|
224
|
+
...asked,
|
|
225
|
+
toolTurns: result.toolTurns,
|
|
226
|
+
...(result.answered ? { answer: result.text } : {}),
|
|
227
|
+
evidence: result.evidence,
|
|
228
|
+
usage: result.usage,
|
|
229
|
+
});
|
|
230
|
+
return result;
|
|
231
|
+
} catch (error) {
|
|
232
|
+
// A question that failed keeps what it read and what it cost.
|
|
233
|
+
const partial = partialResultOf(error);
|
|
234
|
+
if (partial) await turns.insertOne({ ...asked, toolTurns: partial.toolTurns, evidence: partial.evidence, usage: partial.usage });
|
|
235
|
+
throw error;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
- `historyOf` puts each question's rounds right after it, in the order they came, and the answer
|
|
241
|
+
after them. Keep that order: the rounds are what the model did between the question and its
|
|
242
|
+
answer.
|
|
243
|
+
- `askWithFiles` takes the same array: `Array<ChatTurn | ToolTurn>` is a `ChatMessage[]`.
|
|
244
|
+
- `partialResultOf(error)` is undefined for an error raised before the question was under way:
|
|
245
|
+
documents that are missing, a budget that does not work, a last message that is not the user's.
|
|
246
|
+
Nothing was asked, so there is nothing to keep. What each error means and what to show the user
|
|
247
|
+
is in [Errors and reliability](./errors-and-reliability.md).
|
|
248
|
+
- Streaming `onText` to a browser, and what to send when the answer ends, is in
|
|
249
|
+
[Web app](./web-app.md).
|
|
250
|
+
|
|
251
|
+
## Keeping the history inside the window
|
|
252
|
+
|
|
253
|
+
A history grows with every question, and stored tool rounds grow it fast. The loop makes room on
|
|
254
|
+
its own in some ways, and not in others.
|
|
255
|
+
|
|
256
|
+
### What the loop does on its own
|
|
257
|
+
|
|
258
|
+
- **It plans the documents for the room the history leaves.** The text turns and the stored rounds
|
|
259
|
+
are counted before any document goes in whole. As the history grows, a document that went in
|
|
260
|
+
whole may be searched instead. `result.plan.searchable` lists the documents that did not go in
|
|
261
|
+
whole, which the model reaches only through the tools.
|
|
262
|
+
- **It shortens old tool results.** When the results of a new turn do not fit, the results of all
|
|
263
|
+
but the last three tool rounds are replaced by short stand-ins, then all but the last two, then
|
|
264
|
+
all but the last one. Stored rounds of earlier questions are the oldest, so they go first. A
|
|
265
|
+
stand-in keeps the document and the lines or pages that were shown, and tells the model to read
|
|
266
|
+
them again if it needs them:
|
|
267
|
+
|
|
268
|
+
```json
|
|
269
|
+
{ "document": "app.log", "dropped": true, "lines": "1-212", "total_lines": 5000, "note": "These lines were shown to you earlier and were dropped from the conversation to make room. Read them again with read_document if you need them." }
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
Errors and results under 700 characters are left as they are, except a `view_pages` result
|
|
273
|
+
that showed pages: it is always replaced, and its pages go with it. A whole-file read keeps the
|
|
274
|
+
first 6,000 characters of its answer. `steps` then holds "Older tool results were shortened to
|
|
275
|
+
make room in the request".
|
|
276
|
+
- **It stops running tools when nothing fits.** A call that cannot get 1,500 characters of room is
|
|
277
|
+
not run. The model is told to answer from what it has, and the next request is the answer.
|
|
278
|
+
- **It recovers when the provider refuses a request as too large**, for the model's window or for
|
|
279
|
+
the tokens the provider allows in a minute. It shortens older results,
|
|
280
|
+
down to the latest round if needed, and sends the request again, at most twice a question. When
|
|
281
|
+
nothing can be shortened, or the request sent again is still too large, and no tool call has
|
|
282
|
+
been answered and no text shown yet, it plans the documents again for a smaller window, once a
|
|
283
|
+
question. Details are in [Errors and reliability](./errors-and-reliability.md).
|
|
284
|
+
|
|
285
|
+
What it does not do:
|
|
286
|
+
|
|
287
|
+
- **It never shortens a text turn**, a question or an answer, and never touches native parts.
|
|
288
|
+
- **It never shortens anything for an append-only model.** When a model of the question declares
|
|
289
|
+
`appendOnly` (Claude does: [Claude](./anthropic.md)), no turn is rewritten during the question, and
|
|
290
|
+
old results are not replaced by stand-ins. The check of stored pointers at the start of a
|
|
291
|
+
question ([below](#repeated-calls-in-a-follow-up)) still runs.
|
|
292
|
+
- **It does not change your stored rounds.** Stand-ins exist in the requests of one question. The
|
|
293
|
+
`toolTurns` it returns are the new rounds as the model last had them.
|
|
294
|
+
|
|
295
|
+
### What your application does
|
|
296
|
+
|
|
297
|
+
A long conversation passes the window in the end, whatever the loop does. Then the question fails,
|
|
298
|
+
most often with a `ModelRequestError` whose `kind` is `"context_overflow"`. Keep the history under a limit
|
|
299
|
+
you choose:
|
|
300
|
+
|
|
301
|
+
- Measure stored turns with `estimateTokens`, the library's own estimate, which the budget is
|
|
302
|
+
counted in. You can store the size of each turn when you save it.
|
|
303
|
+
- Before each question, send the newest turns that fit. Drop the tool rounds of old turns before
|
|
304
|
+
their text, then drop the oldest turns.
|
|
305
|
+
- Take the limit from `result.budget.contextTokens` of the latest answer, kept with the session:
|
|
306
|
+
the window the question ran with, in the library's tokens, fitted to the models (for Claude, its
|
|
307
|
+
`tokenScale` and `maxTokens` included). Before the first answer, `files.budgetFor().contextTokens`
|
|
308
|
+
gives the library's own. A quarter of it is a reasonable start: the rest is left for the
|
|
309
|
+
documents sent whole (up to `inlineTokens`), the part kept free (`reservedTokens`), and the
|
|
310
|
+
tool results of the new question. This is a starting point, not a rule of the library.
|
|
311
|
+
- With Claude, or any append-only model, this is the only thing that keeps the history inside the
|
|
312
|
+
window.
|
|
313
|
+
- Instead of dropping old turns, you can replace them with a summary that your application writes
|
|
314
|
+
with a model call of its own. The library does not do this.
|
|
315
|
+
|
|
316
|
+
The types and `historyOf` are those of the sample above.
|
|
317
|
+
|
|
318
|
+
```ts
|
|
319
|
+
import { estimateTokens, type ChatTurn, type ToolTurn } from "llm-large-files";
|
|
320
|
+
|
|
321
|
+
/** About how many tokens a stored question takes in a request, in the library's estimate. */
|
|
322
|
+
function tokensOf(turn: TurnRecord): number {
|
|
323
|
+
return estimateTokens(turn.question) + estimateTokens(turn.answer ?? "") + estimateTokens(JSON.stringify(turn.toolTurns));
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* The newest turns that fit in `limit` tokens. Once a turn does not fit whole, it and every older
|
|
328
|
+
* turn are sent without their tool rounds. The oldest turns are left out first.
|
|
329
|
+
*/
|
|
330
|
+
function fitHistory(earlier: TurnRecord[], limit: number): TurnRecord[] {
|
|
331
|
+
const kept: TurnRecord[] = [];
|
|
332
|
+
let used = 0;
|
|
333
|
+
let withRounds = true;
|
|
334
|
+
for (const turn of [...earlier].reverse()) {
|
|
335
|
+
if (withRounds && used + tokensOf(turn) > limit) withRounds = false;
|
|
336
|
+
const sent = withRounds ? turn : { ...turn, toolTurns: [] };
|
|
337
|
+
const size = tokensOf(sent);
|
|
338
|
+
if (used + size > limit) break;
|
|
339
|
+
kept.unshift(sent);
|
|
340
|
+
used += size;
|
|
341
|
+
}
|
|
342
|
+
return kept;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** The messages of the next question, the history cut to a quarter of the window. */
|
|
346
|
+
export function messagesFor(earlier: TurnRecord[], question: string, contextTokens: number): Array<ChatTurn | ToolTurn> {
|
|
347
|
+
return historyOf(fitHistory(earlier, Math.floor(contextTokens / 4)), question);
|
|
348
|
+
}
|
|
349
|
+
```
|
|
350
|
+
|
|
351
|
+
To use it in the session sample:
|
|
352
|
+
|
|
353
|
+
- Add `contextTokens?: number` to `SessionRecord`.
|
|
354
|
+
- In `ask`, pass
|
|
355
|
+
`messages: messagesFor(earlier, question, session.contextTokens ?? files.budgetFor().contextTokens)`
|
|
356
|
+
in place of `historyOf(earlier, question)`.
|
|
357
|
+
- After `insertOne`, keep the window the question ran with:
|
|
358
|
+
`await sessions.updateOne({ _id: sessionId, userId }, { $set: { contextTokens: result.budget.contextTokens } });`.
|
|
359
|
+
|
|
360
|
+
Dropping a round is safe for the rounds after it: a pointer to a result that is no longer sent is
|
|
361
|
+
turned into a stand-in at the start of the question ([below](#repeated-calls-in-a-follow-up)).
|
|
362
|
+
|
|
363
|
+
## Repeated calls in a follow-up
|
|
364
|
+
|
|
365
|
+
A call whose result is still in the conversation in full is not run again. That holds within a
|
|
366
|
+
question, and across questions for the stored rounds you pass back. The files do not change, so the
|
|
367
|
+
same call would return the same.
|
|
368
|
+
|
|
369
|
+
The model gets a pointer in place of a result. The step of a pointer ends in "— already shown
|
|
370
|
+
above", for example "Search app.log (exact) for “ERROR” — already shown above". A pointer runs
|
|
371
|
+
nothing and has no entry in `evidence`. It is stored in `toolTurns` like any result.
|
|
372
|
+
|
|
373
|
+
Which calls count as the same and which results are never pointed to:
|
|
374
|
+
[How it works](../how-it-works.md#pointers-to-repeated-calls). The exact pointer and stand-in
|
|
375
|
+
results: [Tools](../reference/tools.md#what-askwithfiles-adds-to-results).
|
|
376
|
+
|
|
377
|
+
Some stored results are run again rather than pointed to:
|
|
378
|
+
|
|
379
|
+
- **A read of one line in the rounds of an earlier question.** 0.5.0 cut a long line to the room
|
|
380
|
+
it had without saying so, and a stored read cannot be told apart from such a one. Reads of more
|
|
381
|
+
lines, and reads of the same question, are pointed to.
|
|
382
|
+
- **An exact or regex search that 0.5.0 stored** with more matching lines than it showed. It holds
|
|
383
|
+
only the first matches; run again, it shows the last one too.
|
|
384
|
+
- **Any call, with a model whose provider may clear old tool results on its side**
|
|
385
|
+
(`capabilities.clearsToolResults`: Claude with context editing that clears tool uses, or
|
|
386
|
+
compaction). No call is pointed to then, and the same call twice in one turn runs twice.
|
|
387
|
+
|
|
388
|
+
With a model that clears tool results, every stored pointer is sent as the stand-in that says to
|
|
389
|
+
call again: "Not run then: it repeated an earlier call whose result was later dropped from the
|
|
390
|
+
conversation to make room. Call it again if you need it."
|
|
391
|
+
|
|
392
|
+
**When the result is no longer there.** When a result is later shortened to make room, the pointers
|
|
393
|
+
to it become stand-ins (`dropped: true`) that say the call was not run then and can be made again.
|
|
394
|
+
The same check runs at the start of every question, on the rounds you pass. A pointer whose result
|
|
395
|
+
you left out of the history, or whose result was stored as a stand-in, becomes such a stand-in, so
|
|
396
|
+
the model is never told to use what it no longer has. Pointers work only when the stored rounds
|
|
397
|
+
come back as they were stored, in their place.
|
|
398
|
+
|
|
399
|
+
## Histories in a provider's own form
|
|
400
|
+
|
|
401
|
+
When your application already keeps its history in a provider's format, convert it at the edges:
|
|
402
|
+
into `messages` before the question, and the new tool rounds back into that format after it.
|
|
403
|
+
|
|
404
|
+
| History kept as | Into `messages` | New rounds back into it | Entry point |
|
|
405
|
+
|---|---|---|---|
|
|
406
|
+
| Gemini `contents` | `fromGeminiContents(contents)`, or `askGemini({ contents })` | `geminiToolTurns(result.toolTurns)` | `llm-large-files/gemini` |
|
|
407
|
+
| Chat Completions messages | `fromOpenAiMessages(history)`, which returns `{ system, messages }` | `openAiToolTurns(result.toolTurns)` | `llm-large-files/openai` |
|
|
408
|
+
| Messages API messages (Claude) | `fromAnthropicMessages(history)` | `anthropicToolTurns(result.toolTurns)` | `llm-large-files/anthropic` |
|
|
409
|
+
|
|
410
|
+
Put the converted rounds between the question and its answer, as with `ToolTurn`s. The three
|
|
411
|
+
converters leave `tool_turns_left` out of each result, so a request built from them is the same as
|
|
412
|
+
one built from the stored `ToolTurn`s; a test that compares a converted result with the stored one
|
|
413
|
+
must leave that field out. The full signatures are in [gemini.md](../reference/gemini.md),
|
|
414
|
+
[openai.md](../reference/openai.md) and [anthropic.md](../reference/anthropic.md).
|
|
415
|
+
|
|
416
|
+
### Gemini `contents`
|
|
417
|
+
|
|
418
|
+
```ts
|
|
419
|
+
import type { LargeFiles } from "llm-large-files";
|
|
420
|
+
import { askGemini, geminiToolTurns, type GeminiContent, type GeminiEndpoint } from "llm-large-files/gemini";
|
|
421
|
+
|
|
422
|
+
/** Asks the next question of a history kept as Gemini `contents`, and returns the history with it. */
|
|
423
|
+
export async function next(files: LargeFiles, endpoint: GeminiEndpoint, documentIds: string[], history: GeminiContent[], question: string): Promise<GeminiContent[]> {
|
|
424
|
+
const asked: GeminiContent = { role: "user", parts: [{ text: question }] };
|
|
425
|
+
const result = await askGemini({ files, endpoint, documentIds, contents: [...history, asked] });
|
|
426
|
+
return [
|
|
427
|
+
...history,
|
|
428
|
+
asked,
|
|
429
|
+
...geminiToolTurns(result.toolTurns),
|
|
430
|
+
...(result.answered ? [{ role: "model" as const, parts: [{ text: result.text }] }] : []),
|
|
431
|
+
];
|
|
432
|
+
}
|
|
433
|
+
```
|
|
434
|
+
|
|
435
|
+
- `geminiToolTurns` gives, for each round, a `model` turn of `functionCall` parts and a `user` turn
|
|
436
|
+
of `functionResponse` parts. A call's `id` is in both when it has one. Each result is given
|
|
437
|
+
without its `tool_turns_left`, as the loop sends the rounds of an earlier question. `contents`
|
|
438
|
+
that 0.5.0 converted keep it, and are sent as they are.
|
|
439
|
+
- `fromGeminiContents` makes a `"user"` turn a user turn and a `"model"` turn an assistant turn. A
|
|
440
|
+
text part is text. A text part with more fields (a `thoughtSignature`) is kept whole as a native
|
|
441
|
+
part, sized by its text. Every other part is a native part, as it is: an image, an inline PDF,
|
|
442
|
+
and the `functionCall` and `functionResponse` parts of earlier questions.
|
|
443
|
+
|
|
444
|
+
So stored rounds in `contents` reach Gemini unchanged: the request is the same as with `messages`
|
|
445
|
+
and `ToolTurn`s. The loop does not see them as tool rounds, though. It cannot shorten them to make
|
|
446
|
+
room, does not point a repeated call to them, and sizes them only roughly, as media. No helper
|
|
447
|
+
turns Gemini function calls back into `ToolTurn`s. Where you can, keep `toolTurns` as the JSON they
|
|
448
|
+
are, and pass them in `messages`.
|
|
449
|
+
|
|
450
|
+
### Chat Completions messages
|
|
451
|
+
|
|
452
|
+
```ts
|
|
453
|
+
import { askWithFiles, type LargeFiles } from "llm-large-files";
|
|
454
|
+
import { fromOpenAiMessages, openAiCompatible, openAiToolTurns, type OpenAiMessage } from "llm-large-files/openai";
|
|
455
|
+
|
|
456
|
+
const model = openAiCompatible({ apiKey: process.env.OPENAI_API_KEY!, model: "gpt-5.5" });
|
|
457
|
+
|
|
458
|
+
/** Asks the next question of a history kept as Chat Completions messages, and returns the history with it. */
|
|
459
|
+
export async function next(files: LargeFiles, documentIds: string[], history: OpenAiMessage[], question: string): Promise<OpenAiMessage[]> {
|
|
460
|
+
const asked: OpenAiMessage = { role: "user", content: question };
|
|
461
|
+
const { system, messages } = fromOpenAiMessages([...history, asked]);
|
|
462
|
+
const result = await askWithFiles({ files, model, documentIds, system, messages });
|
|
463
|
+
return [
|
|
464
|
+
...history,
|
|
465
|
+
asked,
|
|
466
|
+
...openAiToolTurns(result.toolTurns), // convert once: a call without an ID gets a new random one each time
|
|
467
|
+
...(result.answered ? [{ role: "assistant", content: result.text }] : []),
|
|
468
|
+
];
|
|
469
|
+
}
|
|
470
|
+
```
|
|
471
|
+
|
|
472
|
+
- `fromOpenAiMessages` joins the `system` and `developer` messages into `system`, with a blank line
|
|
473
|
+
between them; pass it as `system`. An `assistant` message with `tool_calls`, and the `tool`
|
|
474
|
+
messages that answer it, become one `ToolTurn`. Text that an assistant message carries next to
|
|
475
|
+
its `tool_calls` is not kept.
|
|
476
|
+
- A `tool` message's content is read as a JSON object, or kept as `{ text }`. A call that no `tool`
|
|
477
|
+
message answers gets `{ error: "No result was kept for this call." }`. A call without an `id`
|
|
478
|
+
gets `call_<n>_<i>`.
|
|
479
|
+
- In a `user` or `assistant` message, content parts other than text are native parts. Messages of
|
|
480
|
+
any other role are skipped.
|
|
481
|
+
- `openAiToolTurns` gives, for each round, an `assistant` message with `content: null` and
|
|
482
|
+
`tool_calls`, then one `tool` message per call with the result as JSON text, without its
|
|
483
|
+
`tool_turns_left`. A call without an ID gets a random one: `call_` and 24 hex characters.
|
|
484
|
+
|
|
485
|
+
### Messages API messages (Claude)
|
|
486
|
+
|
|
487
|
+
```ts
|
|
488
|
+
import { askWithFiles, type LargeFiles } from "llm-large-files";
|
|
489
|
+
import { anthropic, anthropicToolTurns, fromAnthropicMessages, type AnthropicMessage } from "llm-large-files/anthropic";
|
|
490
|
+
|
|
491
|
+
const claude = anthropic({
|
|
492
|
+
apiKey: process.env.ANTHROPIC_API_KEY!,
|
|
493
|
+
model: "claude-opus-5-5",
|
|
494
|
+
contextTokens: 1_000_000, // your model's window
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
/** Asks the next question of a history kept as Messages API messages, and returns the history with it. */
|
|
498
|
+
export async function next(files: LargeFiles, documentIds: string[], system: string, history: AnthropicMessage[], question: string): Promise<AnthropicMessage[]> {
|
|
499
|
+
const asked: AnthropicMessage = { role: "user", content: question };
|
|
500
|
+
const result = await askWithFiles({ files, model: claude, documentIds, system, messages: fromAnthropicMessages([...history, asked]) });
|
|
501
|
+
return [
|
|
502
|
+
...history,
|
|
503
|
+
asked,
|
|
504
|
+
...anthropicToolTurns(result.toolTurns), // convert once: a call without an ID gets a new random one each time
|
|
505
|
+
...(result.answered ? [{ role: "assistant" as const, content: result.text }] : []),
|
|
506
|
+
];
|
|
507
|
+
}
|
|
508
|
+
```
|
|
509
|
+
|
|
510
|
+
- The Messages API keeps the system prompt apart from the messages, so pass it as `system`
|
|
511
|
+
yourself.
|
|
512
|
+
- `fromAnthropicMessages` makes text blocks text, and leaves out empty ones. The `tool_use` blocks
|
|
513
|
+
of an assistant message, and the `tool_result` blocks that answer them, become one `ToolTurn`. A
|
|
514
|
+
result's content is read as a JSON object, or kept as `{ text }`; a call that no `tool_result`
|
|
515
|
+
answers gets `{ error: "No result was kept for this call." }`. Thinking blocks (`thinking`,
|
|
516
|
+
`redacted_thinking`) are left out: they belong to the conversation they were written in. Every
|
|
517
|
+
other block, an image or a document, is a native part.
|
|
518
|
+
- `anthropicToolTurns` gives, for each round, an `assistant` message of `tool_use` blocks and a
|
|
519
|
+
`user` message of `tool_result` blocks, each result without its `tool_turns_left`. A result with
|
|
520
|
+
an `error` gets `is_error: true`. A call
|
|
521
|
+
without an ID gets a random one, `toolu_` and 24 hex characters, and every ID is made to fit the
|
|
522
|
+
API (`[A-Za-z0-9_-]`) and to appear once in the output.
|
|
523
|
+
- Set `contextTokens` on `anthropic()` to the model's window, and trim the history yourself: the
|
|
524
|
+
loop shortens nothing for Claude ([Claude](./anthropic.md)).
|
|
525
|
+
|
|
526
|
+
## Mixing providers in one history
|
|
527
|
+
|
|
528
|
+
`ToolTurn`s belong to no provider. Store them once, and any adapter can be given them: a
|
|
529
|
+
conversation can start on Gemini and go on with Claude or an OpenAI-compatible model.
|
|
530
|
+
|
|
531
|
+
```ts
|
|
532
|
+
import { askWithFiles, type AskResult } from "llm-large-files";
|
|
533
|
+
import { anthropic } from "llm-large-files/anthropic";
|
|
534
|
+
|
|
535
|
+
// SessionRecord, TurnRecord and files are those of the session sample above, messagesFor that of
|
|
536
|
+
// the trimming sample.
|
|
537
|
+
const claude = anthropic({
|
|
538
|
+
apiKey: process.env.ANTHROPIC_API_KEY!,
|
|
539
|
+
model: "claude-opus-5-5",
|
|
540
|
+
contextTokens: 1_000_000, // your model's window
|
|
541
|
+
});
|
|
542
|
+
|
|
543
|
+
/** `contextTokens` is the window to trim the history to, in the library's tokens: Claude's, not the earlier model's. */
|
|
544
|
+
export function askClaude(session: SessionRecord, earlier: TurnRecord[], question: string, contextTokens: number): Promise<AskResult> {
|
|
545
|
+
return askWithFiles({
|
|
546
|
+
files,
|
|
547
|
+
model: claude,
|
|
548
|
+
owner: session.userId,
|
|
549
|
+
documentIds: session.documentIds,
|
|
550
|
+
messages: messagesFor(earlier, question, contextTokens),
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
```
|
|
554
|
+
|
|
555
|
+
What each adapter does with stored rounds:
|
|
556
|
+
|
|
557
|
+
- **Call IDs are made valid for its API, in each request.** `anthropic()` turns a character outside
|
|
558
|
+
`[A-Za-z0-9_-]` into `_` (Kimi's `functions.read_document:0` is sent as
|
|
559
|
+
`functions_read_document_0`), gives a call without an ID `toolu_<round>_<n>`, and adds `_2`,
|
|
560
|
+
`_3` to an ID already used in the request. `openAiCompatible()` gives a call without an ID
|
|
561
|
+
`call_<round>_<n>`, the same in the call and in its result, and sends other IDs as they are.
|
|
562
|
+
`gemini()` sends a call's `id` in its `functionCall` and `functionResponse` when it has one, and
|
|
563
|
+
none otherwise.
|
|
564
|
+
- **The provider's own form of a turn stays with that provider.** Gemini's thought signatures,
|
|
565
|
+
Claude's thinking blocks and OpenRouter's reasoning details go back only to the adapter that
|
|
566
|
+
produced them, within one question. They are never in `toolTurns`: a stored round is rebuilt
|
|
567
|
+
from its calls by whichever adapter gets it.
|
|
568
|
+
- **Native parts are not converted.** A Gemini image part goes to Claude as it is, in Gemini's
|
|
569
|
+
form. Convert native parts yourself, or keep only their text, before another provider gets the
|
|
570
|
+
history.
|
|
571
|
+
- **Windows differ.** The budget of a question follows its models (`contextTokens` of the adapter).
|
|
572
|
+
A history that fit a 1M-token window may not fit a smaller one: trim it for the new model
|
|
573
|
+
([above](#what-your-application-does)). The window kept with the session is the earlier
|
|
574
|
+
model's until the new one has answered; what Claude's window comes to in the library's tokens
|
|
575
|
+
is in [Claude](./anthropic.md).
|
|
576
|
+
|
|
577
|
+
Within one question, an explorer of another provider works the same way: the answering model gets
|
|
578
|
+
the explorer's calls and results, built in its own form ([Explorer model](./explorer-model.md)).
|
|
579
|
+
|
|
580
|
+
## Owners and documents across turns
|
|
581
|
+
|
|
582
|
+
- **Pass the same `owner` with every question.** A document ingested with another owner is treated
|
|
583
|
+
as missing. The owner is a string that is not empty: `ingest` refuses `""`, which
|
|
584
|
+
`user?.id ?? ""` gives a caller who is not signed in. How to choose the owner (a user, or a user
|
|
585
|
+
and a session) is in [Storage](./storage.md#how-ownership-works).
|
|
586
|
+
- **Keep the documents with the conversation, not with one message.** Pass all of them in
|
|
587
|
+
`documentIds` on every question. They are planned again each time.
|
|
588
|
+
- **A document that is gone stops the question before any model request.** One that expired, was
|
|
589
|
+
deleted, or belongs to another owner raises `DocumentsNotFoundError`, with the IDs in `.ids` and
|
|
590
|
+
the message "A document is no longer available: doc_…. Upload it again." `partialResultOf` gives
|
|
591
|
+
undefined for it: nothing was asked.
|
|
592
|
+
- **A document you take out of `documentIds` is no longer planned or offered.** Its card is not
|
|
593
|
+
sent, and a tool call that names it is answered "Unknown document_id …". The stored rounds that
|
|
594
|
+
hold its lines still go to the model, which can use what they show. To take a document out of
|
|
595
|
+
the conversation completely, drop those rounds from the history too.
|
|
596
|
+
- **Stored rounds hold the text of the files, word for word**, up to `toolResultCharacters` per
|
|
597
|
+
result, and the answers of whole-file reads (up to 40,000 characters). They outlive the
|
|
598
|
+
document: its expiry (`ttlMs` of `createLargeFiles`) and `files.delete`. Your rules for keeping and
|
|
599
|
+
deleting data must cover them ([Security](../security.md), [Storage](./storage.md)).
|
|
600
|
+
|
|
601
|
+
With the session sample above, documents that are gone can be taken off the session, and the user
|
|
602
|
+
asked for them again:
|
|
603
|
+
|
|
604
|
+
```ts
|
|
605
|
+
import { DocumentsNotFoundError } from "llm-large-files";
|
|
606
|
+
|
|
607
|
+
// `ask` and `sessions` are those of the session sample above.
|
|
608
|
+
/** Asks the question, or says which files must be attached again. */
|
|
609
|
+
export async function askOrExplain(sessionId: string, userId: string, question: string, onText: (delta: string) => void, signal: AbortSignal): Promise<string | undefined> {
|
|
610
|
+
try {
|
|
611
|
+
await ask(sessionId, userId, question, onText, signal);
|
|
612
|
+
return undefined;
|
|
613
|
+
} catch (error) {
|
|
614
|
+
if (!(error instanceof DocumentsNotFoundError)) throw error;
|
|
615
|
+
await sessions.updateOne({ _id: sessionId, userId }, { $pull: { documentIds: { $in: error.ids } } });
|
|
616
|
+
return error.ids.length === 1 ? "A file of this chat is no longer available. Please attach it again." : `${error.ids.length} files of this chat are no longer available. Please attach them again.`;
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
```
|
|
620
|
+
|
|
621
|
+
## Related pages
|
|
622
|
+
|
|
623
|
+
- [Web app](./web-app.md): uploads, streaming the answer, cancelling.
|
|
624
|
+
- [Storage](./storage.md): owners, a per-user or per-session layout, retention.
|
|
625
|
+
- [Errors and reliability](./errors-and-reliability.md): every error, and what to show the user.
|
|
626
|
+
- [Costs and limits](./costs-and-limits.md): `limits`, the budget, usage per user or session.
|
|
627
|
+
- [Explorer model](./explorer-model.md): a second model that searches while another answers.
|
|
628
|
+
- [How it works](../how-it-works.md): the loop, the plan and the room in the request.
|
|
629
|
+
- [ask.md](../reference/ask.md): `ChatMessage`, `ToolTurn`, `AskResult` and the rest of the loop's types.
|