llm-large-files 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +1402 -467
- package/README.md +188 -60
- package/dist/analyze.d.ts +5 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +96 -47
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts +14 -3
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +190 -39
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +60 -4
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +1068 -206
- package/dist/ask.js.map +1 -1
- package/dist/encoding.d.ts +17 -0
- package/dist/encoding.d.ts.map +1 -0
- package/dist/encoding.js +852 -0
- package/dist/encoding.js.map +1 -0
- package/dist/errors.d.ts +4 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +15 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +333 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +159 -0
- package/dist/events.js.map +1 -0
- package/dist/evidence.d.ts +2 -0
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +3 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +35 -3
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +626 -58
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +17 -8
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +108 -61
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +23 -3
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +6 -2
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +9 -4
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +32 -0
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +10 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +13 -7
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -2
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -1
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -1
- package/dist/gemini/sse.js.map +1 -1
- package/dist/http.d.ts +116 -0
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +347 -1
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +11 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +67 -5
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +405 -85
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +28 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +240 -52
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +84 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +182 -1
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +20 -4
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +122 -20
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/sse.d.ts +59 -0
- package/dist/node/sse.d.ts.map +1 -0
- package/dist/node/sse.js +174 -0
- package/dist/node/sse.js.map +1 -0
- package/dist/openai/adapter.d.ts +29 -5
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +311 -37
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +14 -2
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +39 -10
- package/dist/output-limit.js.map +1 -1
- package/dist/pause.d.ts +24 -0
- package/dist/pause.d.ts.map +1 -0
- package/dist/pause.js +38 -0
- package/dist/pause.js.map +1 -0
- package/dist/pdf-pages.d.ts +32 -2
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +275 -14
- package/dist/pdf-pages.js.map +1 -1
- package/dist/pdf-pictures.d.ts +30 -3
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +50 -8
- package/dist/pdf-pictures.js.map +1 -1
- package/dist/pdf-work.d.ts +40 -0
- package/dist/pdf-work.d.ts.map +1 -0
- package/dist/pdf-work.js +734 -0
- package/dist/pdf-work.js.map +1 -0
- package/dist/plan.d.ts +22 -4
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +61 -12
- package/dist/plan.js.map +1 -1
- package/dist/retry.d.ts +23 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +33 -3
- package/dist/retry.js.map +1 -1
- package/dist/search.d.ts +8 -2
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +60 -10
- package/dist/search.js.map +1 -1
- package/dist/sse.d.ts +35 -2
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +145 -31
- package/dist/sse.js.map +1 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +5 -2
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +6 -0
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +25 -8
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +62 -2
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +314 -14
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +61 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +269 -42
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +102 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/zip-directory.d.ts +43 -0
- package/dist/zip-directory.d.ts.map +1 -0
- package/dist/zip-directory.js +130 -0
- package/dist/zip-directory.js.map +1 -0
- package/docs/README.md +288 -0
- package/docs/api.md +37 -381
- package/docs/configuration.md +28 -558
- package/docs/getting-started.md +407 -223
- package/docs/guides/anthropic.md +590 -0
- package/docs/guides/conversations.md +629 -0
- package/docs/guides/costs-and-limits.md +726 -0
- package/docs/guides/deployment.md +654 -0
- package/docs/guides/errors-and-reliability.md +735 -0
- package/docs/guides/explorer-model.md +399 -0
- package/docs/guides/openai-compatible.md +602 -0
- package/docs/guides/own-adapter-and-loop.md +1169 -0
- package/docs/guides/pdfs.md +971 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1199 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1589 -0
- package/docs/how-it-works.md +1012 -164
- package/docs/measurements.md +881 -0
- package/docs/publishing.md +274 -46
- package/docs/reference/anthropic.md +427 -0
- package/docs/reference/ask.md +892 -0
- package/docs/reference/errors-and-retries.md +758 -0
- package/docs/reference/events.md +993 -0
- package/docs/reference/gemini.md +823 -0
- package/docs/reference/library.md +1467 -0
- package/docs/reference/node.md +528 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +883 -0
- package/docs/security.md +897 -103
- package/docs/troubleshooting.md +1390 -0
- package/package.json +2 -2
- package/src/analyze.ts +93 -42
- package/src/anthropic/adapter.ts +196 -39
- package/src/ask.ts +1087 -202
- package/src/encoding.ts +850 -0
- package/src/errors.ts +17 -0
- package/src/events.ts +442 -0
- package/src/evidence.ts +5 -2
- package/src/extract.ts +602 -62
- package/src/gemini/adapter.ts +118 -65
- package/src/gemini/chat.ts +28 -4
- package/src/gemini/errors.ts +34 -1
- package/src/gemini/generate.ts +23 -10
- package/src/gemini/index.ts +3 -3
- package/src/gemini/sse.ts +1 -1
- package/src/http.ts +376 -1
- package/src/index.ts +27 -5
- package/src/library.ts +459 -85
- package/src/map-reduce.ts +252 -51
- package/src/model.ts +236 -3
- package/src/node/handlers.ts +137 -22
- package/src/node/index.ts +2 -0
- package/src/node/sse.ts +198 -0
- package/src/openai/adapter.ts +306 -38
- package/src/output-limit.ts +44 -8
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +268 -15
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/plan.ts +68 -12
- package/src/retry.ts +49 -5
- package/src/search.ts +63 -10
- package/src/sse.ts +153 -28
- package/src/stores.ts +5 -2
- package/src/text-index.ts +26 -7
- package/src/text.ts +323 -13
- package/src/tools.ts +261 -42
- package/src/types.ts +107 -4
- package/src/zip-directory.ts +136 -0
package/docs/how-it-works.md
CHANGED
|
@@ -1,209 +1,1057 @@
|
|
|
1
1
|
# How it works
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
3
|
+
This page follows a file from upload to answer: what ingest stores, how a request is planned, what
|
|
4
|
+
the model sees, what each tool does, and how the tool loop keeps every request inside the model's
|
|
5
|
+
limits. It is for developers who want to know why the library behaves as it does; the
|
|
6
|
+
[guides](./README.md) show how to use each part.
|
|
7
|
+
|
|
8
|
+
```text
|
|
9
|
+
upload ─► ingest ─► store extract · normalize · profile · line index
|
|
10
|
+
(and the uploaded file, for formats in keepOriginals)
|
|
11
|
+
|
|
12
|
+
question ─► plan the documents for the room left in the request, smallest first
|
|
13
|
+
├─ fits ─────► its whole text in the first user turn
|
|
14
|
+
└─ too big ──► its card in the first user turn
|
|
15
|
+
+ the tool guide in the system instruction
|
|
16
|
+
+ tools: search · read · overview
|
|
17
|
+
· analyze-all (when the exploring model can read parts
|
|
18
|
+
and a file is within maxMapChunks)
|
|
19
|
+
a kept PDF, in either branch, when every model can be sent a file
|
|
20
|
+
─► + tool: view_pages (the real pages, as a small PDF),
|
|
21
|
+
and its lines in the tool guide
|
|
22
|
+
|
|
23
|
+
─► tool loop: run the calls of a turn, fit their results to the room left, repeat
|
|
24
|
+
─► the answer: the model's last turn, or one more request that must be answered in text
|
|
13
25
|
```
|
|
14
26
|
|
|
15
27
|
## Ingest
|
|
16
28
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
29
|
+
`files.ingest({ name, bytes, mimeType?, owner?, signal? })` does five things, in order.
|
|
30
|
+
|
|
31
|
+
1. **Check.** An owner that is empty, spaces only or `null` is refused
|
|
32
|
+
([Security](./security.md#ownership)). The name is cleaned to one printable line: the last path
|
|
33
|
+
segment, without control characters, line breaks, text-direction controls or most other
|
|
34
|
+
characters that show nothing (variation selectors, joiners and Hangul fillers are kept), 255
|
|
35
|
+
characters at most, never cut in the middle of a character. An empty file, or one over
|
|
36
|
+
`maxUploadBytes` (100 MB by default), is refused.
|
|
37
|
+
2. **Extract** text by format, with the built-in extractors or your own (`extractors`). The format
|
|
38
|
+
comes from the extension, then the MIME type, and is `text` otherwise.
|
|
39
|
+
- **PDF** (needs the optional `unpdf`). Each page starts with a `--- Page N ---` line. Tables
|
|
40
|
+
are rebuilt from the position of their text and written as `| cell | cell | |` rows, so an
|
|
41
|
+
empty cell stays an empty cell. A page that shows a picture or a drawing gets the line
|
|
42
|
+
`[Picture on this page. This text cannot show it.]`. Those pages are found from the structure
|
|
43
|
+
of the file: a small interpreter follows each page's drawing instructions and notes where
|
|
44
|
+
images are painted and which shapes are filled, without decoding any image. That needs the
|
|
45
|
+
optional `@cantoo/pdf-lib`; without it, and for a file of over 150,000 objects or one that
|
|
46
|
+
takes over 5 seconds to go through, no page is marked. A page without text says
|
|
47
|
+
`[No text on this page. It may be a scan, a photo, or a chart.]`.
|
|
48
|
+
- **A PDF without any text** (a scan) is refused, unless its original is kept: then one of up
|
|
49
|
+
to `scannedPdfPages` (30) pages is stored, to be read by looking at its pages.
|
|
50
|
+
- **PPTX**: a `## Slide N` heading for each slide, and the slide count as the document's
|
|
51
|
+
`pages`. A slide that the slide show skips is headed
|
|
52
|
+
`## Slide N (hidden, not shown in the slide show)`, and its text is kept. **DOCX**: the body,
|
|
53
|
+
then the endnotes, footers, footnotes and headers (the other parts in the order of their
|
|
54
|
+
names). The text of a run that Word hides comes after the text of its paragraph that shows,
|
|
55
|
+
each of its lines starting with `[Hidden text, not shown in the document]`, and a long line is
|
|
56
|
+
cut into pieces, each marked. Text hidden through a style is not told apart
|
|
57
|
+
([Security](./security.md#hidden-text-in-word-and-powerpoint)).
|
|
58
|
+
- **Text, logs, Markdown, JSON and CSV** are read as UTF-8, or as UTF-16 when they start with a
|
|
59
|
+
byte-order mark or about half of their first bytes are zeros. A file that is not valid UTF-8
|
|
60
|
+
is read in the older encoding it was saved in, or as UTF-8 with its characters that are not
|
|
61
|
+
valid counted ([Text encodings](#text-encodings)). A compressed or other binary file is
|
|
62
|
+
refused.
|
|
63
|
+
- **Limits.** A PDF of more than `maxPdfPages` (5,000) pages is refused before its pages are
|
|
64
|
+
read, and one whose page tree lists a page twice as soon as it does. With `@cantoo/pdf-lib`,
|
|
65
|
+
the same reading of the file that finds the pictures first adds up what each page would make
|
|
66
|
+
pdf.js run (its content, each form every time it is painted, the glyph programs of its Type3
|
|
67
|
+
fonts), and refuses a page that would hold the server for more than about 1.5 s, or 32
|
|
68
|
+
times the size of the file in content when that is more, before pdf.js reads any page
|
|
69
|
+
([Pages that would hold the server](./guides/pdfs.md#pages-that-would-hold-the-server)). The text is counted as
|
|
70
|
+
it is read, a PDF page by page and a DOCX or PPTX paragraph by paragraph, and the file is
|
|
71
|
+
refused once it passes `maxTextBytes` (100 MB by default, or `maxUploadBytes` when that is
|
|
72
|
+
larger); a PDF also past 100 times its size in text (after the first 16 MB); a DOCX or PPTX
|
|
73
|
+
also past 32 million
|
|
74
|
+
characters of text, 1,000,000 paragraphs with text, paragraphs nested 32 deep, or 20,000
|
|
75
|
+
parts. The text of any other extractor, yours included, is checked when it returns.
|
|
76
|
+
|
|
77
|
+
Formats, tables, the picture line, the refusals and your own extractors:
|
|
78
|
+
[PDFs and other formats](./guides/pdfs.md).
|
|
79
|
+
3. **Normalize.** Strip a BOM, turn every line ending into `\n`, and remove most of what a person
|
|
80
|
+
does not see in the file:
|
|
81
|
+
- terminal escape sequences (colour codes, window titles, character-set selection), and control
|
|
82
|
+
characters other than tab and newline, C1 (U+0080-U+009F) included;
|
|
83
|
+
- characters that show nothing and that no script needs: tag characters, the zero-width space,
|
|
84
|
+
the word joiner, the text-direction controls that reorder what a person sees, a byte order
|
|
85
|
+
mark inside the text, and a soft hyphen that is not at the end of a line. What scripts and
|
|
86
|
+
emoji need is kept: the marks of right-to-left text, zero-width joiners and non-joiners,
|
|
87
|
+
variation selectors ([Security](./security.md#characters-that-show-nothing) lists both);
|
|
88
|
+
- U+0085 (next line), which becomes a line break in a text that has no other one, such as a
|
|
89
|
+
mainframe file converted to UTF-8, and is removed in any other text. Right after
|
|
90
|
+
U+0080-U+00FF it is part of a UTF-8 letter read as Latin-1, and is removed there too.
|
|
91
|
+
|
|
92
|
+
No line break is added or removed, but for U+0085 in a text with no line feed. A text without
|
|
93
|
+
these characters is kept as it is, and a line of megabytes is cleaned in pieces of 256K
|
|
94
|
+
characters. Then lines over 2,000 characters are split, after a space or one of `,;}` near the
|
|
95
|
+
end of a piece when there is one. A line that lost characters can be split into fewer pieces
|
|
96
|
+
than 0.5.0 split it, which moves the lines after it. Every line-based tool then returns bounded
|
|
97
|
+
output. A file with no text left is refused:
|
|
98
|
+
"app.log did not contain any text."
|
|
99
|
+
4. **Profile.**
|
|
100
|
+
- Count lines and characters, [estimate tokens](#token-estimates), and measure two sizes: the
|
|
101
|
+
UTF-8 bytes, and the bytes the text takes as a string in a JSON request body (`jsonBytes`),
|
|
102
|
+
which is what a request limit counts. Quotes, backslashes, tabs and line breaks take two bytes
|
|
103
|
+
there; the planner uses this size.
|
|
104
|
+
- A file detected as plain text becomes a **log** when it has at least 5 non-empty lines and at
|
|
105
|
+
least 40% of the first 200 of them start with a timestamp or a level.
|
|
106
|
+
- Build an **outline**: headings with their line numbers. Markdown headings; after a blank
|
|
107
|
+
line, lines that start with Chapter, Part, Book, Section or Appendix, or the Hebrew words for
|
|
108
|
+
chapter, part and appendix, numbered headings such as `2.1 Scope`, and short lines in
|
|
109
|
+
capitals. At most 400 entries: past that, the top-level headings alone when there are 20
|
|
110
|
+
to 400 of them, each once and in order; otherwise 400 taken at even steps over the file,
|
|
111
|
+
from the top-level headings when there are more than 400 of them, or from all the headings
|
|
112
|
+
when there are fewer than 20 (see [`OutlineEntry`](./reference/library.md#outlineentry)).
|
|
113
|
+
Logs, JSON and CSV get no outline.
|
|
114
|
+
- For a log, build a **profile**: lines by level (ERR counts as ERROR, WARNING as WARN,
|
|
115
|
+
CRITICAL as FATAL), the first and last timestamp, and the ERROR, FATAL and WARN lines grouped
|
|
116
|
+
by shape. Timestamps are removed, and UUIDs, IP addresses, hex, quoted values and numbers
|
|
117
|
+
become `<id>`, `<ip>`, `<hex>`, `<s>` and `<n>`. So 81 timeouts to three hosts become one
|
|
118
|
+
entry, `[ERROR ×81, L6] ERROR Connection timeout after <n>ms to <ip>`: the level, the count,
|
|
119
|
+
the first line, and the template, which keeps the level word. The profile keeps 15 entries,
|
|
120
|
+
FATAL first, then ERROR, then WARN, each by count.
|
|
121
|
+
5. **Store**, in this order: the uploaded file (when its format is in `keepOriginals` and the store
|
|
122
|
+
has `putOriginal`), the line index (when the store has `putIndex`), then the text and its
|
|
123
|
+
metadata (`put`). A document exists once its metadata does; if a write fails, what was written
|
|
124
|
+
is deleted. The ID is `doc_` and 32 hex characters, and `expiresAt` is `ttlMs` (72 hours) later.
|
|
125
|
+
|
|
126
|
+
Steps 2 to 4 share the server with other requests. Each works in slices of about 12 ms, with a
|
|
127
|
+
pause between two slices: the PDF extractor and the picture marks between pages, the DOCX and PPTX
|
|
128
|
+
extractors as they unpack, the text extractor as it decodes a file that is not UTF-8, and then the
|
|
129
|
+
normalizing, the measures, the outline, the log profile and the line index. Ingests that run at
|
|
130
|
+
once take turns, one slice each. They run under one signal, aborted by the caller's `signal` or
|
|
131
|
+
after `ingestTimeoutMs` (2 minutes): `ingest` then throws, and nothing is stored. A step under way
|
|
132
|
+
when it aborts, such as one page of pdf.js, runs to its end in the background, and holds the
|
|
133
|
+
server while it runs: pdf.js reads a page without a pause. [Security](./security.md#uploads) has
|
|
134
|
+
the limits and the stalls measured.
|
|
135
|
+
|
|
136
|
+
The **line index** holds, for each line, where it starts in the UTF-8 bytes and in the string, which
|
|
137
|
+
lines start a passage for keyword search (about 1,500 characters or 40 lines), and which lines are
|
|
138
|
+
`--- Page N ---` markers. That is a few bytes a line. It is written by any store that keeps one, even
|
|
139
|
+
one the library then loads whole. No term index is built: keyword search counts its terms when it
|
|
140
|
+
runs.
|
|
141
|
+
|
|
142
|
+
### Text encodings
|
|
143
|
+
|
|
144
|
+
A text file whose bytes are not all valid UTF-8 is one of two things. It is UTF-8 with a few
|
|
145
|
+
characters that are not valid: a log cut at a byte count, a stray byte, a binary body in a log
|
|
146
|
+
line. Or it was saved in an older encoding: Excel saves a Hebrew CSV in windows-1255. The text
|
|
147
|
+
extractor looks at each line, about a megabyte at a time with a pause in between, and decides:
|
|
148
|
+
|
|
149
|
+
1. **CESU-8.** When every fault is half of a surrogate pair, as an Oracle export or Java's modified
|
|
150
|
+
UTF-8 writes an emoji, the pairs are joined and the file is read as UTF-8, emoji included.
|
|
151
|
+
2. **UTF-8, with a count.** A line counts as UTF-8 when it holds at least as many characters of
|
|
152
|
+
more than one byte as characters that are not valid, as not UTF-8 when it holds more that are
|
|
153
|
+
not valid, and as ASCII when it holds neither. When at least as many lines count as UTF-8 as
|
|
154
|
+
count as not, or when at most one line in 200 is not UTF-8 (ASCII lines counted), the file is
|
|
155
|
+
read as UTF-8. Each character that is not valid becomes U+FFFD, and
|
|
156
|
+
`meta.replacedCharacters` counts them. A character cut in two by the start or the end of the
|
|
157
|
+
file counts as UTF-8, and a byte-order mark always means UTF-8.
|
|
158
|
+
3. **An older encoding.** Otherwise the lines that are not UTF-8 and hold letters (a byte of 0xC0 or
|
|
159
|
+
more), wherever they are in the file, up to 64 KB of them, choose the encoding. It is the first
|
|
160
|
+
of these in which they read as the words of one script: windows-1255 (Hebrew; ISO-8859-8 too),
|
|
161
|
+
windows-1256 (Arabic), windows-1251 (Cyrillic), Shift_JIS (Japanese, half-width katakana
|
|
162
|
+
included) and windows-1252 (Western European; ISO-8859-1 too). Lines of signs alone (– ’ € °)
|
|
163
|
+
choose only when no line has letters, and Shift_JIS is tried on the first 64 KB of the lines
|
|
164
|
+
that are not UTF-8. When no line is UTF-8, the whole file is read in that encoding; otherwise
|
|
165
|
+
each line that is valid UTF-8 is read as UTF-8, and the others in that encoding. A byte that the
|
|
166
|
+
encoding does not have becomes U+FFFD and is counted. `meta.encoding` names the encoding.
|
|
167
|
+
4. **UTF-8 again.** When no encoding fits, the file is read as UTF-8 with the count, as 0.5.0 read
|
|
168
|
+
it. No text file is refused for its encoding.
|
|
169
|
+
|
|
170
|
+
The model is told. The frame of a file sent whole adds `read as windows-1255`, or
|
|
171
|
+
`3 characters not valid UTF-8, shown as �`, after its line count ([The card](#the-card)), and the
|
|
172
|
+
card of a larger one has a line such as
|
|
173
|
+
`This file is not in UTF-8. Its text was read as windows-1255: if its letters look wrong, ask the user to save it as UTF-8.`
|
|
174
|
+
A file that is valid UTF-8, or UTF-16, is read as before, byte for byte.
|
|
175
|
+
|
|
176
|
+
What it gets wrong, as a rule:
|
|
177
|
+
|
|
178
|
+
- **Encodings it does not recognize** are read as UTF-8, with U+FFFD and the count: Greek, Turkish,
|
|
179
|
+
Central European (windows-1250), Icelandic, KOI8-R and KOI8-U, the DOS code pages (437, 850,
|
|
180
|
+
866), ISO-8859-5 and -6, EUC-JP, Chinese, Korean and Thai. So is a Japanese file of kanji with few
|
|
181
|
+
or no kana.
|
|
182
|
+
- **A wrong encoding** is chosen for a file of a line or two (Greek capitals as windows-1251,
|
|
183
|
+
"Dzień dobry." as windows-1252), and for a file of fewer than 200 lines, or of one long line such
|
|
184
|
+
as minified JSON, whose few stray bytes happen to fit one. Hungarian in windows-1250 is read as
|
|
185
|
+
windows-1252, with õ and û in place of ő and ű. ISO-8859-15 is read as windows-1252 when it has
|
|
186
|
+
no œ, with ¤ in place of €; a file with œ in its words (cœur, sœur) is most often read as UTF-8
|
|
187
|
+
with U+FFFD instead, since its œ would be ½, which does not fit between two letters.
|
|
188
|
+
- **Lines in two encodings.** In a file where at most one line in 200 is not UTF-8, those lines
|
|
189
|
+
become U+FFFD even when they are in an older encoding. In a file in an older encoding, a line
|
|
190
|
+
that happens to be valid UTF-8 is read as UTF-8; this is rare, and most likely in a file of
|
|
191
|
+
half-width katakana alone. A few such lines can make a short file of half-width katakana in
|
|
192
|
+
Shift_JIS count as UTF-8, and it is then read as UTF-8 with U+FFFD.
|
|
193
|
+
|
|
194
|
+
What it costs: [Measurements](./measurements.md#the-server). What to tell users who upload such
|
|
195
|
+
files: [PDFs and other formats](./guides/pdfs.md#text-encodings). An editor that opens such a file
|
|
196
|
+
as UTF-8 does not show what the model reads:
|
|
197
|
+
[Security](./security.md#text-files-that-were-not-utf-8).
|
|
198
|
+
|
|
199
|
+
### Reading a stored document
|
|
200
|
+
|
|
201
|
+
Every use of a document first asks the store for its metadata, so a document deleted or expired on
|
|
202
|
+
another server that shares the store is never served from memory. Then:
|
|
203
|
+
|
|
204
|
+
- A text of up to `wholeDocumentBytes` (2 MB) is loaded whole and kept in a memory cache of
|
|
205
|
+
`cacheBytes` (256 MB). So is every text, with a store that cannot read by range.
|
|
206
|
+
- A larger text, with a store that has `readTextRange` (`FileDocumentStore` has), is read by
|
|
207
|
+
range. A tool call reads the lines it needs through the index, and a search reads the text about
|
|
208
|
+
`scanChunkBytes` (1 MB) at a time, with at most `maxConcurrentScans` (4) scans of whole documents
|
|
209
|
+
at once in the library (each `createLargeFiles` call has its own queue and its own cache; one per
|
|
210
|
+
process when you create it once). Decoded pieces go in the same cache, at most a quarter of it
|
|
211
|
+
for one document.
|
|
212
|
+
- A document stored without an index gets one built the first time it is read by range, and saved.
|
|
213
|
+
|
|
214
|
+
Sizing this for many users and servers: [Storage](./guides/storage.md) and
|
|
215
|
+
[Deployment](./guides/deployment.md).
|
|
34
216
|
|
|
35
217
|
## The card
|
|
36
218
|
|
|
37
|
-
A
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
219
|
+
A file that is sent whole sits between two frame lines:
|
|
220
|
+
|
|
221
|
+
```text
|
|
222
|
+
--- Attached file [mark 1f0c3a9e]: "app.log" (log, 3,000 lines; it ends only at the line with mark 1f0c3a9e) ---
|
|
223
|
+
2026-11-19T08:00:01.370Z INFO request id=0 handled in 0ms
|
|
224
|
+
…
|
|
225
|
+
--- End attached file [mark 1f0c3a9e] ---
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
The mark is eight hex digits made from the document ID, which is made after the file's text, so a
|
|
229
|
+
line of the file cannot hold it: a line that copies the end of the frame has no mark or a wrong
|
|
230
|
+
one, and the first frame line tells the model that only the line with the mark ends the file. This
|
|
231
|
+
does not make the model obey, and the mark is not a secret. The name, which the uploader chooses
|
|
232
|
+
with the text, comes after the mark, quoted as JSON, and the closing line holds the mark alone.
|
|
233
|
+
The mark is the same in every request, so a provider's prompt cache can reuse the file from one
|
|
234
|
+
request to the next; after an upgrade from 0.5.0, the first request of each conversation misses
|
|
235
|
+
it once, since the frame lines changed. A file of one line says `1 line`. A text file that was not
|
|
236
|
+
valid UTF-8 adds a note after the line count ([Text encodings](#text-encodings)):
|
|
237
|
+
`, read as windows-1255`, `, read as windows-1255, 1 character not valid in it, shown as �`, or
|
|
238
|
+
`, 3 characters not valid UTF-8, shown as �`. What the mark guards against, and what it does not:
|
|
239
|
+
[Security](./security.md#the-frame-around-a-file).
|
|
240
|
+
|
|
241
|
+
A file too large to send whole is replaced by its card, a few kilobytes. This is the card of a
|
|
242
|
+
3,000-line log, with its first lines shortened here:
|
|
243
|
+
|
|
244
|
+
```text
|
|
245
|
+
--- Large attached file: app.log ---
|
|
246
|
+
document_id: doc_5db4a21d03f043d3bb156a2fab2dc15d
|
|
247
|
+
log · 189 KB · 3,000 lines · about 139K tokens
|
|
248
|
+
This file is NOT in your context. Use the document tools to search it, read line ranges, or analyze all of it.
|
|
249
|
+
Log levels: INFO 2,889, ERROR 81, WARN 29, FATAL 1
|
|
250
|
+
Time range: 2026-11-19T08:00:01.370Z → 2026-11-19T09:08:30.000Z
|
|
251
|
+
Most frequent problems (count, first line):
|
|
252
|
+
[FATAL ×1, L2901] FATAL Primary database unreachable, failing over to replica <ip>
|
|
253
|
+
[ERROR ×81, L6] ERROR Connection timeout after <n>ms to <ip>
|
|
254
|
+
[WARN ×29, L8] WARN Slow query took <n>ms on table <s>
|
|
255
|
+
First lines:
|
|
256
|
+
1| 2026-11-19T08:00:01.370Z INFO request id=0 handled in 0ms
|
|
257
|
+
2| 2026-11-19T08:00:02.740Z INFO request id=1eef handled in 1ms
|
|
258
|
+
…
|
|
259
|
+
25| 2026-11-19T08:00:34.250Z INFO request id=2e668 handled in 24ms
|
|
260
|
+
--- End large attached file: app.log ---
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
A card holds:
|
|
264
|
+
|
|
265
|
+
- The name and `document_id`.
|
|
266
|
+
- The format, size, line count, page count (a PDF's pages, a PPTX's slides) and estimated tokens.
|
|
267
|
+
- A line that says the file is not in the model's context. When a whole-file read would be refused
|
|
268
|
+
(the file is estimated at more than `maxMapChunks` parts, with 5% leeway), it says instead that
|
|
269
|
+
the file can be searched and read by line ranges, and is too large to be analyzed whole. When
|
|
270
|
+
`prepare` gets `wholeDocumentAnalysis: false` ([The plan](#how-the-plan-is-made)), it says only
|
|
271
|
+
that the file can be searched and read by line ranges, whatever its size.
|
|
272
|
+
- For a PDF whose pages can be looked at, a line that sends the model to `view_pages` for pictures,
|
|
273
|
+
charts and layout.
|
|
274
|
+
- For a text file that was not valid UTF-8, a line that says so: the encoding it was read in, how
|
|
275
|
+
many characters were not valid, or both
|
|
276
|
+
(`3 characters of this file were not valid UTF-8, and show as �.`).
|
|
277
|
+
- For a log: the levels, the time range, and the first 8 of the 15 problems the profile keeps
|
|
278
|
+
(FATAL first, then ERROR, then WARN, each by count).
|
|
279
|
+
- The first 40 headings of the outline, and how many there are.
|
|
280
|
+
- The first 25 lines, numbered, each cut to 300 characters.
|
|
281
|
+
|
|
282
|
+
A model can often aim its first call from the card alone: a FATAL line with its line number, or a
|
|
283
|
+
heading of the outline. The rest of the profile and the whole outline are in
|
|
284
|
+
`get_document_overview`.
|
|
285
|
+
|
|
286
|
+
When any file is searchable or its pages can be looked at, the **tool guide** goes into the system
|
|
287
|
+
instruction, after yours. It names those files (quoted, so a file name that reads like an
|
|
288
|
+
instruction stays a name), says which tool does what, sends counting and listing to exact or regex
|
|
289
|
+
search, keeps the whole-file read for tasks that need meaning (a summary, a timeline, items judged
|
|
290
|
+
one by one), asks the model to call independent tools in the same turn, and to cite line numbers
|
|
291
|
+
like `(app.log L1203)`. The line on `analyze_whole_document` is left out when `prepare` gets
|
|
292
|
+
`wholeDocumentAnalysis: false` ([The plan](#how-the-plan-is-made)), or when every searchable file
|
|
293
|
+
is too large for it. For PDFs whose pages can be looked at, it adds when to use `view_pages`, what
|
|
294
|
+
its page numbers are, and not to describe a picture the model has not looked at.
|
|
295
|
+
|
|
296
|
+
## The plan
|
|
297
|
+
|
|
298
|
+
The plan decides which documents go into the request whole and which become cards.
|
|
299
|
+
[`askWithFiles`](./reference/ask.md#askwithfilesoptions) makes it once for each question, for the
|
|
300
|
+
budget fitted to its models, and once more after a request too large for the model
|
|
301
|
+
([below](#a-request-too-large-for-the-model)). In your own loop you make it with
|
|
302
|
+
`files.prepare(ids, base, options)` ([Your own adapter and loop](./guides/own-adapter-and-loop.md)).
|
|
303
|
+
|
|
304
|
+
### The budget of a question
|
|
305
|
+
|
|
306
|
+
The library's budget describes one model connection: `contextTokens`, `maxRequestBytes`, and the
|
|
307
|
+
fields that follow from them ([Costs and limits](./guides/costs-and-limits.md)). `askWithFiles`
|
|
308
|
+
fits it to the models of the question, the answering model and the explorer:
|
|
309
|
+
|
|
310
|
+
- **The window** is the smallest of the budget's `contextTokens` and every model's
|
|
311
|
+
`capabilities.contextTokens`. It is then divided by the largest `tokenScale` of the models: the
|
|
312
|
+
budget counts in the library's estimate, which is fitted to Gemini, and a tokenizer that counts
|
|
313
|
+
1.35 times as many tokens (Claude's default) leaves a window that much smaller in those terms.
|
|
314
|
+
- **The reply.** The largest `capabilities.outputTokens` (Claude's `maxTokens`, 64,000 by default)
|
|
315
|
+
comes out of that window, which never goes below a quarter of itself.
|
|
316
|
+
- **The request size** is the smallest of the budget's `maxRequestBytes` and every model's
|
|
317
|
+
`capabilities.maxRequestBytes`.
|
|
318
|
+
- **Fields you set** with `budget` (on the library, or on the question) are kept, and lowered when
|
|
319
|
+
they are too large for a smaller window. Fields you left out follow the window: a quarter kept
|
|
320
|
+
free (`reservedTokens`, 64,000 at most), half of it for document text (`inlineTokens`, 200,000 at
|
|
321
|
+
most) and for one part of a whole-file read (`mapChunkTokens`, 100,000 at most), and 12% of it,
|
|
322
|
+
in characters, for one tool result (`toolResultCharacters`, from 1,000 to 24,000).
|
|
323
|
+
|
|
324
|
+
`result.budget` is the budget the question ran with. `files.budgetFor(overrides, limits)` gives the
|
|
325
|
+
library's budget fitted to any window and request size, as in the sample below.
|
|
326
|
+
|
|
327
|
+
### How the plan is made
|
|
328
|
+
|
|
329
|
+
For each question (in your own loop, each request you plan), `prepare(ids, base)` takes the size of
|
|
330
|
+
everything else in the request (`base.tokens`, `base.bytes`). `askWithFiles` passes the system
|
|
331
|
+
instruction, the conversation as it was asked, and the tool rounds of earlier questions in it, with
|
|
332
|
+
a margin of 2,000 tokens and 8,000 bytes. The plan needs only the metadata. It fills the room left,
|
|
333
|
+
smallest documents first, by estimated tokens:
|
|
334
|
+
|
|
335
|
+
- token room = `min(inlineTokens, contextTokens − reservedTokens − base.tokens)`
|
|
336
|
+
- byte room = `maxRequestBytes − 256 KB − base.bytes`
|
|
337
|
+
|
|
338
|
+
A document is sent whole if, with the ones chosen before it, it fits both. Its bytes are its JSON
|
|
339
|
+
size and 200 more. Otherwise it becomes searchable. The 256 KB are kept for the cards, the tool
|
|
340
|
+
declarations and the JSON around them.
|
|
341
|
+
|
|
342
|
+
- An ID given twice counts once. A document that was never there, was deleted, has expired or
|
|
343
|
+
belongs to another owner is in `missing`, and `askWithFiles` throws `DocumentsNotFoundError` for
|
|
344
|
+
it. One that disappears while its text or card is read is moved to `missing`, and the plan is
|
|
345
|
+
made again.
|
|
346
|
+
- With `viewPages`, `viewable` lists the PDFs whose original is kept (and a store that can give it
|
|
347
|
+
back), whether their text is sent whole or searched.
|
|
348
|
+
- Whether a whole-file read is offered for a file is decided from its metadata: about how many parts
|
|
349
|
+
it takes, counting the `12345| ` prefix of every line, at most `maxMapChunks` with 5% leeway.
|
|
350
|
+
`prepare` with `wholeDocumentAnalysis: false` offers it for no file: the tool guide does not name
|
|
351
|
+
it, and no card offers it. Pass that when you call `files.tools()` without `generate`, its part
|
|
352
|
+
reader ([Your own adapter and loop](./guides/own-adapter-and-loop.md)). `askWithFiles` passes it
|
|
353
|
+
when you set `wholeDocumentAnalysis: false`, and when its exploring model has no `generateText`.
|
|
354
|
+
|
|
355
|
+
`askWithFiles` puts the texts and cards, in the order of `documentIds`, at the start of the first
|
|
356
|
+
user turn (`documentPlacement: "first"`, the default). They stay there as the conversation grows,
|
|
357
|
+
so a provider's prompt cache, which matches the start of a request, can reuse them on every
|
|
358
|
+
follow-up question: Gemini's own cache, and Claude's `cache_control`. `"last"` appends them to the
|
|
359
|
+
latest user turn instead, where they move with every turn and are billed in full each time. A
|
|
360
|
+
question with no searchable file and no viewable PDF is then one request, without tools.
|
|
361
|
+
|
|
362
|
+
To see a plan and a budget without asking a model:
|
|
363
|
+
|
|
364
|
+
```ts
|
|
365
|
+
import { readFile } from "node:fs/promises";
|
|
366
|
+
import { createLargeFiles, MemoryDocumentStore } from "llm-large-files";
|
|
367
|
+
|
|
368
|
+
const files = createLargeFiles({ store: new MemoryDocumentStore() });
|
|
369
|
+
const meta = await files.ingest({ name: "app.log", bytes: await readFile("app.log") });
|
|
370
|
+
|
|
371
|
+
// The budget of a question on a model with a window of 128,000 tokens:
|
|
372
|
+
// inlineTokens 64,000 · reservedTokens 32,000 · mapChunkTokens 64,000 · toolResultCharacters 15,360
|
|
373
|
+
const budget = files.budgetFor(undefined, { contextTokens: 128_000 });
|
|
374
|
+
|
|
375
|
+
// The plan of a request whose other parts take about 3,000 tokens and 12,000 bytes.
|
|
376
|
+
const prepared = await files.prepare([meta.id], { tokens: 3_000, bytes: 12_000 }, { budget });
|
|
377
|
+
console.log(prepared.plan.inline.map((document) => document.name)); // sent whole
|
|
378
|
+
console.log(prepared.plan.searchable.map((document) => document.name)); // cards and tools
|
|
379
|
+
console.log(prepared.blocks.get(meta.id)); // the text or the card
|
|
380
|
+
console.log(prepared.instruction); // the tool guide, or ""
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
## Token estimates
|
|
384
|
+
|
|
385
|
+
`estimateTokens(text)` walks the text once and prices each kind of character, because the number
|
|
386
|
+
of characters in a token depends on the kind of text. Digits cost about a token each, so a flat 4
|
|
387
|
+
characters per token is right for a novel and three times too low for a log. The weights:
|
|
388
|
+
|
|
389
|
+
| Character | Tokens |
|
|
390
|
+
|---|---|
|
|
391
|
+
| A run of ASCII letters | 1.1 for the run, 1.3 more at each change of case inside it (`camelCase`, base64), 0.18 for each letter past the 6th (the 3rd for capitals), 0.5 for each past the 20th |
|
|
392
|
+
| A digit | 1.2 |
|
|
393
|
+
| A run of ASCII punctuation | 0.85, for its first character only |
|
|
394
|
+
| A line break | 2.2 |
|
|
395
|
+
| A tab | 1 |
|
|
396
|
+
| A space | 0 before a letter, 0.2 before anything else |
|
|
397
|
+
| Latin letters with accents (é, ü, ß) | 0.6 |
|
|
398
|
+
| Greek, Cyrillic | 0.4, 0.3 |
|
|
399
|
+
| Hebrew, Arabic | 0.52, 0.41 |
|
|
400
|
+
| Han, kana, Hangul | 0.7, 0.56, 0.7 |
|
|
401
|
+
| Other alphabets and syllabaries (Devanagari, Thai, Georgian) | 0.45 |
|
|
402
|
+
| Half of an emoji or another character outside the basic plane | 0.5 |
|
|
403
|
+
| Dashes, quotes, arrows, box drawing, anything else | 1 |
|
|
404
|
+
|
|
405
|
+
The sum is rounded up. The weights were fitted to Gemini's `countTokens` on 60 texts: prose in
|
|
406
|
+
eleven languages, source code, JSON, CSV and eight log formats (Gemini 2.5, 3.5 and 3.8 count
|
|
407
|
+
identically). On them the estimate lands between 0.98 and 1.7 times Gemini's count. It leans high
|
|
408
|
+
on purpose: overestimating only makes a file searchable a little sooner. The one kind of text it
|
|
409
|
+
counts low, at about 70%, is a long run of random letters in one case with no digits. The counts
|
|
410
|
+
by kind of text are in [Measurements](./measurements.md).
|
|
411
|
+
|
|
412
|
+
```ts
|
|
413
|
+
import { estimateTokens, jsonBytes } from "llm-large-files";
|
|
414
|
+
|
|
415
|
+
estimateTokens("2026-11-19T08:14:03.512Z ERROR payment-gateway timeout after 30000ms to 10.4.2.17"); // 53: 81 characters
|
|
416
|
+
estimateTokens("It was a bright cold day in April, and the clocks were striking thirteen."); // 18: 73 characters
|
|
417
|
+
jsonBytes('He said "no".\n'); // 19: the 14 characters, an escape for each quote and the line break, and two quotes
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
Tokenizers differ between providers. An adapter's `tokenScale` says how many of its model's tokens
|
|
421
|
+
one estimated token comes to: 1 for Gemini, and by default 1 for an OpenAI-compatible model and 1.35
|
|
422
|
+
for Claude. A tokenizer that groups digits counts fewer tokens than this estimate on logs and data, the
|
|
423
|
+
safe direction.
|
|
424
|
+
|
|
425
|
+
During a question the provider's own count corrects the estimate. After each reply the loop compares
|
|
426
|
+
the input tokens the provider counted (divided by that model's `tokenScale`) with its estimate of
|
|
427
|
+
the request, and multiplies its later estimates by the ratio, kept between 1 and 2. A provider that
|
|
428
|
+
refuses a request as too large can raise it to 8 ([below](#a-request-too-large-for-the-model)).
|
|
41
429
|
|
|
42
430
|
## Tools
|
|
43
431
|
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
(
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
432
|
+
A model reaches a searchable file only through tools, and only the documents of the question: an
|
|
433
|
+
unknown `document_id` is answered with the IDs it may use. This section says what each tool does and
|
|
434
|
+
why it is built that way. Each tool's arguments, results, defaults, limits and error texts, and the
|
|
435
|
+
rules every tool follows, are in the [tools reference](./reference/tools.md).
|
|
436
|
+
|
|
437
|
+
- **`search_document`** finds lines. In `keywords` mode (the default) it ranks the passages of the
|
|
438
|
+
line index by BM25, computed when the search runs from substring hits: there is no term index to
|
|
439
|
+
build or keep up to date, it works in any language, and "timeout" also matches "timeouts". In
|
|
440
|
+
`exact` and `regex` modes it returns the first `max_results` matching lines and the last one in
|
|
441
|
+
the file (with the lines around each when `context_lines` asks for them; none by default), and
|
|
442
|
+
`total_matching_lines` counts every matching line in the file, not only those shown; a line with
|
|
443
|
+
several matches counts once. When not all are shown, a note says how many of how many:
|
|
444
|
+
`21 of the 442 matching lines are shown: the first 20 and the last (line 15269). To see the ones in between, narrow the search.`
|
|
445
|
+
The last match is there for a question about when something last happened: shown only the first
|
|
446
|
+
ones and the count, a model named a wrong line as the last
|
|
447
|
+
([Measurements](./measurements.md#reading-a-whole-file)). The count is exact unless the scan
|
|
448
|
+
stopped early, which the result says; then the last match is not known, and not shown. A regex
|
|
449
|
+
scan runs in short time slices with other work in between, under a time limit of its own and a
|
|
450
|
+
budget the regex searches of a question share, so a pattern that backtracks without end returns
|
|
451
|
+
partial results instead of holding the process.
|
|
452
|
+
- **`read_document`** returns a numbered line range, read through the line index, and says where to
|
|
453
|
+
go on.
|
|
454
|
+
- **`get_document_overview`** returns more than the card: the whole log profile, the whole outline,
|
|
455
|
+
the first and last lines, and about how many parts a whole-file read would take. That count is
|
|
456
|
+
estimated from the metadata, without reading the text, and the overview says when it is over
|
|
457
|
+
`maxMapChunks`.
|
|
458
|
+
- **`analyze_whole_document`** reads a whole file in parts ([Map-reduce](#map-reduce)). It is
|
|
459
|
+
declared when the exploring model has a part reader (`generateText`), `wholeDocumentAnalysis` is
|
|
460
|
+
not `false`, and at least one searchable file is estimated within `maxMapChunks`.
|
|
461
|
+
- **`view_pages`** returns pages of a PDF as a file ([Looking at pages](#looking-at-pages)). It is
|
|
462
|
+
declared when a kept PDF can be shown to every model of the question. The text tools are left out
|
|
463
|
+
only when no file is searchable and there are pages to look at.
|
|
464
|
+
|
|
465
|
+
A tool that fails returns `{ error }`, with a message that names no path on the server, so the model
|
|
466
|
+
can try another way. What the scope means for prompt injection and owners:
|
|
467
|
+
[Security](./security.md).
|
|
468
|
+
|
|
469
|
+
Every result is capped at `toolResultCharacters` (the answer of a whole-file read at the larger of
|
|
470
|
+
that and 40,000 characters). In the loop it is cut further, never below 600 characters: to its
|
|
471
|
+
share of the room left in the request or, for the answer of a whole-file read, to the room the
|
|
472
|
+
other results of its turn left ([Room in the request](#room-in-the-request)). A list loses
|
|
473
|
+
entries from its end (an exact or regex search loses them from the end of its first matches, and
|
|
474
|
+
keeps the last one), a read loses lines, and the result says what was cut and where to go on.
|
|
63
475
|
|
|
64
476
|
## Looking at pages
|
|
65
477
|
|
|
66
478
|
Text cannot show a chart. `view_pages(document_id, from_page, to_page)` gives the model the pages
|
|
67
|
-
themselves: up to five a call,
|
|
479
|
+
themselves: up to five a call (`MAX_VIEW_PAGES`), cut out of the kept original into one PDF of their
|
|
480
|
+
own. The adapter hands that PDF to the model: inside the function response for Gemini, as a
|
|
481
|
+
document block for Claude, as a `file` part after the tool results for an OpenAI-compatible model
|
|
482
|
+
with `pdfInput: true` ([the table below](#what-differs-between-providers)).
|
|
483
|
+
|
|
484
|
+
It is offered for a PDF whose original is kept (`keepOriginals: ["pdf"]`, and a store with
|
|
485
|
+
`putOriginal` and `getOriginal`), unless `viewPages` is `false`, and only when every model of the
|
|
486
|
+
question can be sent a file. An OpenAI-compatible model without `pdfInput`, or Claude with
|
|
487
|
+
`toolFilePlacement: "none"`, rules it out. A PDF whose text fits in the prompt gets `view_pages`
|
|
488
|
+
too, and only that: such a file is often a slide deck, with little text and a picture on every
|
|
489
|
+
page. Page numbers are the N of the `--- Page N ---` lines.
|
|
68
490
|
|
|
69
491
|
Cutting pages out of a PDF sounds like copying them. Copied the way PDF libraries offer it, a page
|
|
70
492
|
brings along everything it refers to:
|
|
71
493
|
|
|
72
494
|
- **Links.** A contents page links to every section. Each link holds a reference to its target
|
|
73
|
-
page, so
|
|
74
|
-
|
|
75
|
-
a
|
|
495
|
+
page, so a copy took those pages too, with their pictures: the contents page of a report came out
|
|
496
|
+
at 89% of the size of its file. Before copying, every page that is not wanted is replaced by null,
|
|
497
|
+
so a link to it copies a few bytes and not the page. (Not an empty page: the cut must hold no
|
|
498
|
+
objects that call themselves pages and are not among its pages.)
|
|
76
499
|
- **Shared resources.** FPDF, TCPDF, jsPDF and others write one list of all images of the file and
|
|
77
500
|
give it to every page. A copy of one page carried all of them. The content of each wanted page is
|
|
78
|
-
read to see which images it paints
|
|
79
|
-
|
|
501
|
+
read to see which images it paints (with its forms, patterns, Type 3 fonts and the appearances of
|
|
502
|
+
its annotations), and the page gets a list of only those. Nothing is dropped unless all content
|
|
503
|
+
that could name an image was read.
|
|
80
504
|
- **Layers.** A file can hide a layer. The settings that say so are copied with the pages, or the
|
|
81
505
|
hidden layer would show.
|
|
506
|
+
- **Page extras** that can hold a lot and are not needed to show the page (editor data, article
|
|
507
|
+
threads, actions, a thumbnail) are dropped.
|
|
508
|
+
|
|
509
|
+
The cut needs `@cantoo/pdf-lib`. A file that declares over a million objects, or more objects than
|
|
510
|
+
60% of the free heap can hold at 1,700 bytes an object, is refused before it is read. An empty
|
|
511
|
+
password is tried, which opens the many files encrypted only against printing or copying. When the
|
|
512
|
+
library counts other pages than the text extractor did, the pages are not shown: a wrong page is
|
|
513
|
+
worse than none. Pages are left off the end until the cut fits; the result then says how many were
|
|
514
|
+
shown and where to go on.
|
|
82
515
|
|
|
83
|
-
The pages are counted against the request twice. As bytes
|
|
516
|
+
The pages are counted against the request twice. As **bytes**: base64 makes them a third larger, and
|
|
84
517
|
they stay in the request until the question is answered, so the room for the next look shrinks.
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
(
|
|
518
|
+
The loop keeps a tenth of `maxRequestBytes` free (256 KB at least) and gives each look what is left
|
|
519
|
+
of the request, which the adapter measures as it would send it. As **tokens**: what the model bills
|
|
520
|
+
for a page (`pageTokens`: by default 530 for Gemini, 1,000 for an OpenAI-compatible model and 3,500
|
|
521
|
+
for Claude; the largest of the question's models, divided by the largest `tokenScale` of those
|
|
522
|
+
models), against half of
|
|
523
|
+
`reservedTokens`. With the default budget and Gemini that is 60 pages a question. When either runs
|
|
524
|
+
out, the tool says so and the model answers from what it has. The looks of one turn run one after
|
|
525
|
+
another, each with the room the one before it left.
|
|
88
526
|
|
|
89
|
-
|
|
90
|
-
|
|
527
|
+
Pages are not kept in `toolTurns`: the stored round says that they were shown. Setting this up,
|
|
528
|
+
scanned PDFs and `toolFilePlacement`: [PDFs and other formats](./guides/pdfs.md).
|
|
91
529
|
|
|
92
530
|
## Map-reduce
|
|
93
531
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
2. Read the parts four at a time. Each part either takes notes with line citations or replies
|
|
97
|
-
`NOTHING RELEVANT`. A failed part is retried once; if it fails again, it's reported in the answer
|
|
98
|
-
rather than failing the whole read.
|
|
99
|
-
3. If the notes are still too large, merge them in batches (or pairs) for up to 8 rounds.
|
|
100
|
-
4. Write one answer from the notes, flagging contradictions and parts that couldn't be read.
|
|
532
|
+
`analyze_whole_document(document_id, task)` reads a whole file with many model requests, through
|
|
533
|
+
the part reader (`generateText`) of the model that explores.
|
|
101
534
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
535
|
+
1. **Split** on line boundaries into parts that fit both `mapChunkTokens` and 80% of
|
|
536
|
+
`maxRequestBytes`, counting the line-number prefix of every line. A file of more than
|
|
537
|
+
`maxMapChunks` parts (30) is refused before any request: "Reading all of app.log needs 41 model
|
|
538
|
+
calls, over the limit of 30. Use search_document to narrow the question first." Such a file is
|
|
539
|
+
most often not offered the read at all: its card, the tool guide and the overview say so
|
|
540
|
+
([The plan](#how-the-plan-is-made)).
|
|
541
|
+
2. **Map.** Read the parts four at a time. Each part either takes notes with line citations
|
|
542
|
+
(`(L123)`) or replies `NOTHING RELEVANT`. A part that fails is sent again by the loop's rule
|
|
543
|
+
([Retries and waits](#retries-and-waits)), and an error with no status once more at once.
|
|
544
|
+
- A part the model refuses as larger than it takes (an error of kind `context_overflow`: its
|
|
545
|
+
window is smaller than the budget says) is read as two halves, once, while `maxMapChunks` and
|
|
546
|
+
the requests the question has left allow it. A half that is still too large is a part that
|
|
547
|
+
could not be read.
|
|
548
|
+
- A part that still fails is reported in the answer (`parts_that_failed`) rather than failing
|
|
549
|
+
the whole read. When no part could be read, the read fails with the reason and is not tried
|
|
550
|
+
again in the question. When none could even be read from the store, no model request was
|
|
551
|
+
made, and the store's error is the result.
|
|
552
|
+
- The reason of a model request that failed is told by its kind, its HTTP status, the code of a
|
|
553
|
+
connection that failed or a timeout, never by the error's words, which can name a host or a
|
|
554
|
+
key: `Could not read any part of app.log: The model refused the key or token it was sent (HTTP 401).`
|
|
555
|
+
An error with none of these is `The model request failed.`
|
|
556
|
+
([Security](./security.md#what-the-library-logs)).
|
|
557
|
+
3. **Reduce.** While the notes of the relevant parts together are larger than `mapChunkTokens`,
|
|
558
|
+
merge them in batches of up to `mapChunkTokens` (in pairs when no two notes fit one batch), four
|
|
559
|
+
at a time, for at most 8 rounds. A merge that fails keeps its notes as they were, and the rounds
|
|
560
|
+
stop there.
|
|
561
|
+
4. **Answer.** Write one answer from the notes, flagging contradictions, gaps and parts that could
|
|
562
|
+
not be read. When this last step fails, the notes are the answer, with `notes_only: true`: they
|
|
563
|
+
were paid for.
|
|
105
564
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
tool: it reports `total_matching_lines`.
|
|
565
|
+
The result holds `parts_read`, `parts_with_relevant_content`, `parts_that_failed`,
|
|
566
|
+
`notes_cut_short`, `answer_cut_short`, `notes_only` and the `answer`. While it runs, the progress goes
|
|
567
|
+
to `onActivity`: "Reading app.log: part 3 of 12…", and, with `onEvent`, comes as `tool.progress`
|
|
568
|
+
events with the `callId` of the read, each part a `request.start` and `request.end` of role
|
|
569
|
+
`"reader"`.
|
|
112
570
|
|
|
113
|
-
|
|
571
|
+
**Output limits.** Part notes and merged notes start at 4,096 output tokens, the answer at 8,192.
|
|
572
|
+
When a reply reaches its limit, or a provider's filter stops it (Gemini `SAFETY` and the like,
|
|
573
|
+
`content_filter`, Claude's `refusal` or `model_context_window_exceeded`), the result says the answer
|
|
574
|
+
is incomplete and points the model to exact search.
|
|
575
|
+
|
|
576
|
+
A model that thinks counts its thoughts in that limit. When a reply stops at the limit with nothing
|
|
577
|
+
written, or with half of the limit or more spent on thoughts, each adapter's part reader asks once
|
|
578
|
+
more with 32,768 (`THINKING_OUTPUT_TOKENS`, exported by `llm-large-files/gemini`), and starts there for later requests to that model in
|
|
579
|
+
the process. The first request to a model finds this out while the others wait, so one request is
|
|
580
|
+
wasted, not four. A model that refuses the larger limit (HTTP 400) is not asked for it again, but a
|
|
581
|
+
refusal of the request as too large for the model's window with that limit is no such refusal,
|
|
582
|
+
unless the window is 32,768 tokens or less. A request refused as larger than the tokens a minute
|
|
583
|
+
that the provider allows counts the same way, with that allowance for the window. Claude does not
|
|
584
|
+
count its thoughts apart: when a reply has thinking blocks, its part reader takes for thoughts the
|
|
585
|
+
output tokens it billed besides its text.
|
|
586
|
+
|
|
587
|
+
**Counting is search's job.** Even within its limits a model can skip items of a long list, so for
|
|
588
|
+
a complete list or an exact count, `search_document` in exact or regex mode is the reliable tool: it
|
|
589
|
+
reports `total_matching_lines`. The tool guide says so, and keeps the whole-file read for what
|
|
590
|
+
needs meaning: a summary, a timeline, items that must be judged one by one. A search shows the
|
|
591
|
+
first `max_results` matching lines (50 at most) and the last one, so a list longer than that
|
|
592
|
+
needs narrower searches; a way to page through the rest is planned. The live checks are in
|
|
593
|
+
[Measurements](./measurements.md).
|
|
114
594
|
|
|
115
595
|
## The loop (`askWithFiles`)
|
|
116
596
|
|
|
117
|
-
One loop serves every model. A provider is an adapter that turns the loop's request into its own
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
597
|
+
One loop serves every model. A provider is an adapter that turns the loop's request into its own and
|
|
598
|
+
reads the reply back. Planning, tools, limits, room, retries, usage and the forced answer happen
|
|
599
|
+
once, in the core. `askGemini` is this loop with Gemini adapters ([below](#gemini-askgemini-gemini)).
|
|
600
|
+
|
|
601
|
+
A question goes like this:
|
|
602
|
+
|
|
603
|
+
1. Fit the budget to the models, and [plan the documents](#how-the-plan-is-made).
|
|
604
|
+
2. Send a request with the tools (`toolChoice: "auto"`) to the model that explores.
|
|
605
|
+
3. A reply without tool calls ends the tool requests. Its text is the answer, unless it is empty,
|
|
606
|
+
the prompt was blocked, or it comes from an explorer. A reply with calls is a turn: its calls run, each result gets
|
|
607
|
+
`tool_turns_left`, and the round of calls and results joins the conversation, sent again with
|
|
608
|
+
every later request until the question is answered. The rounds come back in
|
|
609
|
+
`result.toolTurns`; passed back in `messages` with the conversation, they let a later question
|
|
610
|
+
use what this one found ([Conversations](./guides/conversations.md)). They are sent then
|
|
611
|
+
without `tool_turns_left`, which counted the turns of their own question.
|
|
612
|
+
4. Repeat from 2 until the model answers, or until the tool turns, the room or the question's
|
|
613
|
+
ceilings run out. Then one more request [must be answered in text](#the-request-for-the-answer).
|
|
614
|
+
|
|
615
|
+
### The calls of a turn
|
|
616
|
+
|
|
617
|
+
- **At most `limits.callsPerTurn` calls run** (8 by default; every limit is in
|
|
618
|
+
[`AskLimits`](./reference/ask.md#asklimits)). The others are answered "Not run: one turn runs at
|
|
619
|
+
most 8 tool calls. Send this call again if you still need it.", and a step says how many.
|
|
620
|
+
- **Before anything runs**, each call is looked at in order. A call that did not arrive whole is
|
|
621
|
+
answered with what was wrong ([below](#empty-or-broken-turns)). A call made twice in the turn, or
|
|
622
|
+
whose result is already in the conversation, is answered with a pointer
|
|
623
|
+
([below](#pointers-to-repeated-calls)). A whole-file read that would pass a ceiling of the
|
|
624
|
+
question is refused with the numbers. The others run.
|
|
625
|
+
- **They run together**, four at a time, and are answered in the order they were made. Looks at
|
|
626
|
+
pages run one after another, because each is given the room the one before it left. Regex
|
|
627
|
+
searches do too: they share the time of the tool set.
|
|
628
|
+
- **Two searches in a row that failed in the same mode** get a hint with the second error: after
|
|
629
|
+
two failed regex searches, to try exact or keywords mode; after two other failures, to check the
|
|
630
|
+
arguments against the tool's description or answer from what it has.
|
|
631
|
+
- **Whole-file reads.** By default (`limits.wholeDocumentReads: 1`) each document may be read whole
|
|
632
|
+
once a question; 0 refuses every read. A model that asks again, with the task put another way, is
|
|
633
|
+
told to use the answer it has. A read that could read no part is not tried again either, and a
|
|
634
|
+
model that asks again is told that it failed and why. A read refused before any model request
|
|
635
|
+
(too many parts, a store that could not be read) is not counted. A read is priced before it
|
|
636
|
+
starts, at its estimated parts and 3 more requests, and its file's estimated tokens in the
|
|
637
|
+
exploring model's terms; one that would pass `limits.inputTokens` or `limits.requests` is
|
|
638
|
+
refused with the numbers. The reads of one turn are counted together, and each may make its own
|
|
639
|
+
requests and an even share of what the question has left.
|
|
640
|
+
- **`tool_turns_left`** in every result tells the model how many tool turns are left after this
|
|
641
|
+
one: 0 when the room ran out. The tool guide asks it to call independent tools in one turn and to
|
|
642
|
+
answer as soon as it has enough. The results of an earlier question, passed back in `messages`,
|
|
643
|
+
are sent without it, so a model cannot take their 0 for its own. The first request of each
|
|
644
|
+
follow-up question then differs from the requests of the question before it from that
|
|
645
|
+
question's first tool round on, and a provider's prompt cache misses from there, once in each
|
|
646
|
+
follow-up question.
|
|
647
|
+
|
|
648
|
+
### Room in the request
|
|
649
|
+
|
|
650
|
+
Every tool result stays in the conversation until the question is answered, and is sent again with
|
|
651
|
+
each later request. The loop counts the request as it grows, by the library's estimate and, once the
|
|
652
|
+
provider has answered, by the provider's own count ([Token estimates](#token-estimates)).
|
|
653
|
+
|
|
654
|
+
- **The limits.** Tool results may grow the request until half of `reservedTokens` is left free in
|
|
655
|
+
the window; that half is kept for the answer. In bytes, the request may grow to
|
|
656
|
+
`maxRequestBytes` less 2% (32 KB at least). The room left is counted in characters: two for each
|
|
657
|
+
token left, and a third of each byte left, whichever is less.
|
|
658
|
+
- **Shared among the calls of a turn.** Before the calls of a turn run, the room that is left is
|
|
659
|
+
shared among those that return text: each gets an even share, up to its cap
|
|
660
|
+
(`toolResultCharacters`), and what a call with a smaller cap does not need goes to the others. A
|
|
661
|
+
result is cut to its share and says where to go on. A call that is refused, or answered with a
|
|
662
|
+
pointer, takes no room, and looks at pages have [room of their own](#looking-at-pages).
|
|
663
|
+
- **The answer of a whole-file read**, which cannot be asked for again, is not cut to a share: once
|
|
664
|
+
the other results of the turn are in, it gets all the room they left (up to the larger of
|
|
665
|
+
`toolResultCharacters` and 40,000 characters, and never below 600). An answer that does not fit
|
|
666
|
+
is cut at its end, and says so in `answer_shortened`; the other fields stay.
|
|
667
|
+
- **Making room.** When the room is less than the calls of the turn could return together, older
|
|
668
|
+
results are replaced by [stand-ins](#stand-ins): those of all but the last three tool rounds, then
|
|
669
|
+
all but the last two, then all but the last one, as far as needed. `steps` then holds "Older tool
|
|
670
|
+
results were shortened to make room in the request". When any model of the question, the
|
|
671
|
+
answering model or the explorer, may only grow its conversation (`capabilities.appendOnly`:
|
|
672
|
+
Claude), nothing is replaced, for either model.
|
|
673
|
+
- **No room left.** Calls that still cannot each get 1,500 characters (or their cap, when it is
|
|
674
|
+
smaller) are answered "Not run: there is no room left in this conversation for another tool
|
|
675
|
+
result. Answer now, from what the tools returned so far.", the last calls of the turn first, and
|
|
676
|
+
the next request is the answer.
|
|
677
|
+
|
|
678
|
+
### Stand-ins
|
|
679
|
+
|
|
680
|
+
A stand-in is a short result in place of one that was dropped to make room. It keeps which document
|
|
681
|
+
it was about and what it showed, says `dropped: true`, and tells the model how to get it back. What
|
|
682
|
+
each tool's stand-in keeps, and which results are too small to replace, is in
|
|
683
|
+
[`stubResult`](./reference/ask.md#stubresultcall-result-hadfiles). The tool rounds a question
|
|
684
|
+
returns in `toolTurns` hold stand-ins for pages, since a file cannot be kept as JSON
|
|
685
|
+
([Conversations](./guides/conversations.md)).
|
|
686
|
+
|
|
687
|
+
### Pointers to repeated calls
|
|
688
|
+
|
|
689
|
+
A call whose result is still in the conversation in full is not run again: the files do not change,
|
|
690
|
+
so it would return the same and only take room. It is answered with a pointer, and its step says
|
|
691
|
+
"already shown above". That covers:
|
|
692
|
+
|
|
693
|
+
- the same search (same document, query and mode, and the same number of results, context and
|
|
694
|
+
case, the defaults filled in) or the same overview: "Not run: this exact call was answered
|
|
695
|
+
earlier in this conversation, and its result is still shown above in full…";
|
|
696
|
+
- a read of lines inside a read that is shown in full: "Not run: lines 40-60 are already shown above
|
|
697
|
+
in full, in the result that has lines 1-200 of this file…";
|
|
698
|
+
- the same search, read or overview made twice in one turn: "Not run: call 2 of this turn is the
|
|
699
|
+
same call, and its result is next to this one. Use it.";
|
|
700
|
+
- results in the tool rounds of earlier questions, passed back in `messages`.
|
|
701
|
+
|
|
702
|
+
A result of an earlier turn that was cut to its room (a list that says "Showing…", a read with
|
|
703
|
+
`text_cut`), replaced by a stand-in, that failed, or from a search that stopped early is not
|
|
704
|
+
pointed to: the call runs, and may get more. When a call is made twice in one turn, the second gets
|
|
705
|
+
the pointer whatever the first returns, even an error or a cut result. Only when the first is
|
|
706
|
+
refused for lack of room is the second refused the same way. Whole-file reads and looks at pages
|
|
707
|
+
are never pointed to. When a result is later replaced by a stand-in, the pointers to it become
|
|
708
|
+
stand-ins too, which say that the call was not run then and can be made again; a call of the
|
|
709
|
+
current turn that would have pointed to it runs instead.
|
|
710
|
+
|
|
711
|
+
Three more cases run the call again:
|
|
712
|
+
|
|
713
|
+
- **A read of one line in the rounds of an earlier question.** 0.5.0 cut a long line to its room
|
|
714
|
+
without saying so, and stored reads cannot be told apart. Reads of more lines, and reads of the
|
|
715
|
+
same question, are pointed to.
|
|
716
|
+
- **An exact or regex search that 0.5.0 stored**, with fewer matches than `total_matching_lines`
|
|
717
|
+
and no note: it holds only the first matches, and a search made now shows the last one too.
|
|
718
|
+
- **Any call, with a model whose provider may clear old tool results on its side**
|
|
719
|
+
(`capabilities.clearsToolResults`: Claude with `clear_tool_uses` or compaction in
|
|
720
|
+
`body.context_management`). The model may no longer have the result a pointer names, so no call
|
|
721
|
+
is answered with a pointer, every stored pointer is sent as the stand-in above, and the same call
|
|
722
|
+
made twice in one turn runs twice.
|
|
723
|
+
|
|
724
|
+
### Empty or broken turns
|
|
725
|
+
|
|
726
|
+
- **A call that did not arrive whole** is answered with what was wrong, and not run: arguments that
|
|
727
|
+
are not a JSON object, a call cut off at the output limit, or a Claude tool block that was never
|
|
728
|
+
closed. The answer asks the model to send the call again.
|
|
729
|
+
- **A turn whose call could not be read at all** (Gemini's `MALFORMED_FUNCTION_CALL` or
|
|
730
|
+
`UNEXPECTED_TOOL_CALL`), **or an empty reply** while no call of the question has been answered
|
|
731
|
+
yet, is asked for once more, with a short note that says what was wrong. Without it the answer
|
|
732
|
+
would be written from the cards alone, and look like any other. An empty reply that was cut off
|
|
733
|
+
at the output limit or stopped by a filter is not asked for again.
|
|
734
|
+
- That second try happens at most twice a question, only when a turn is left besides the answer's,
|
|
735
|
+
and not after a blocked prompt or once the question's ceilings are reached. It takes a tool turn.
|
|
736
|
+
`steps` says "The model's tool call could not be read: it was asked to send it again" or "The
|
|
737
|
+
model's first reply was empty: it was asked again". An explorer's note tells it to reply DONE.
|
|
738
|
+
- **The note is not kept in the conversation**, so the start of later requests stays the one the
|
|
739
|
+
provider's cache holds. The exception is an exploring model whose conversation may only grow
|
|
740
|
+
(`appendOnly`: Claude), which keeps it, because what it thinks next follows the note; when that
|
|
741
|
+
model also answers, its later requests, the answer's included, have the note. An answering model
|
|
742
|
+
other than the explorer never gets the explorer's notes.
|
|
743
|
+
- **An answer that comes back without text** (empty, or with a tool call the model was told not to
|
|
744
|
+
make, such as Gemini's `UNEXPECTED_TOOL_CALL`) is asked for once more, with a note at its end
|
|
745
|
+
that is not kept: "Your last reply had no text. No tool can be called in this reply: write the
|
|
746
|
+
answer now, in text, from what is above." It is one of the two second tries of the question, and
|
|
747
|
+
can be one request past `limits.toolTurns`, but it is not made after a refusal, a filter or a
|
|
748
|
+
reply cut off at the output limit with nothing in it, nor once `limits.requests` or
|
|
749
|
+
`limits.inputTokens` is reached. `steps` says "The model's answer was empty: it was asked again"
|
|
750
|
+
or "The model called a tool instead of answering: it was asked again for the answer". With an
|
|
751
|
+
explorer, this note goes to the answering model.
|
|
752
|
+
|
|
753
|
+
Gemini is the one adapter that reports a broken call as a turn of its own (`finish:
|
|
754
|
+
"malformed_call"`). The OpenAI-compatible and Claude adapters mark the call itself, which the
|
|
755
|
+
first point covers.
|
|
756
|
+
|
|
757
|
+
### A request too large for the model
|
|
758
|
+
|
|
759
|
+
The budget can assume a larger window than the model has, or the estimate can run low. A provider
|
|
760
|
+
that refuses a request as larger than the model takes (an error of kind `context_overflow`) does not
|
|
761
|
+
end the question:
|
|
762
|
+
|
|
763
|
+
- **Shorten and send again.** The loop takes the provider's numbers for the rest of the question:
|
|
764
|
+
its count of the request raises the estimate (up to 8 times), and the window it names lowers the
|
|
765
|
+
limit of the room. It then replaces older results with stand-ins, the latest round too if needed,
|
|
766
|
+
and sends the request again. `steps` says "The request was larger than the model takes: older tool
|
|
767
|
+
results were shortened, and it was sent again". That happens at most twice a question, and once
|
|
768
|
+
for any one request. When any model of the question may only grow its conversation (Claude),
|
|
769
|
+
nothing is shortened.
|
|
770
|
+
- **Plan again.** When it happens to the first requests of a question, before any tool call was
|
|
771
|
+
answered or any text shown, the documents are planned again for a smaller window, once, as for a
|
|
772
|
+
model that declares it. The window is the one the provider named, or seven tenths of the window
|
|
773
|
+
the budget assumed when it named none, divided by how much more than the estimate the provider
|
|
774
|
+
counted (by 1.25 when it named a window but gave no count). A result that is not smaller than the
|
|
775
|
+
assumed window becomes seven tenths of it. This applies to any model, Claude included. What the first try paid
|
|
776
|
+
for, the tool turns it took and its steps are carried over, and `steps` says why.
|
|
777
|
+
- **Otherwise** the error is thrown, with `kind: "context_overflow"` and the provider's
|
|
778
|
+
`limitTokens` and `requestedTokens` when its message gives them.
|
|
779
|
+
|
|
780
|
+
A request larger than the tokens a minute that the provider allows (OpenAI's "Request too large …
|
|
781
|
+
on tokens per min (TPM)", HTTP 429, or Groq's, HTTP 413 or 429) is of the same kind, with that
|
|
782
|
+
allowance for the window: only a smaller request can pass it. Its steps name the allowance, as
|
|
783
|
+
"The first request was larger than the 30,000 tokens a minute that the provider allows: the files
|
|
784
|
+
were planned again to fit it".
|
|
785
|
+
|
|
786
|
+
### Retries and waits
|
|
787
|
+
|
|
788
|
+
- **Retries.** A chat request that failed with HTTP 408, 409, 429 or 5xx, or got no answer (status
|
|
789
|
+
0), is sent again up to `retry.retries` (3) more times. The wait doubles from `baseDelayMs`
|
|
790
|
+
(500 ms) with jitter, so it is 0.25 to 0.5 s, then 0.5 to 1 s, then 1 to 2 s, up to `maxDelayMs`
|
|
791
|
+
(60 s), or it is the wait the provider asks for (`retry-after-ms`, `Retry-After`, or the
|
|
792
|
+
`retryDelay` of Gemini's `RetryInfo`). A provider that asks for more than `maxDelayMs` is not
|
|
793
|
+
waited for: the error is reported. Meanwhile `onActivity` says "The model did not answer (HTTP
|
|
794
|
+
503). Trying again in 1 s…", and a `retry` event says the same, with the error's kind and status.
|
|
795
|
+
- **Not sent again**: a refusal such as 400, 401, 403 or 404; a quota that does not come back soon
|
|
796
|
+
(kind `quota`: OpenAI's `insufficient_quota`, HTTP 402, Claude's credit balance and spending
|
|
797
|
+
limits, a Gemini quota per day); an error of kind `context_overflow`, whatever its status, which
|
|
798
|
+
only a smaller request can pass; one that Claude's API marks `x-should-retry: false`; a reply of
|
|
799
|
+
HTTP 200 that is not JSON, such as a gateway's sign-in page (kind `invalid`); a request whose
|
|
800
|
+
reply already showed text; a request after you stopped the question; and, in a chat request, an
|
|
801
|
+
error with no status.
|
|
802
|
+
- **Silence.** Each adapter watches a chat request. One that gets nothing for `firstByteTimeoutMs`
|
|
803
|
+
(600 s) before the first piece of its reply, or for `idleTimeoutMs` (300 s) between two pieces, is
|
|
804
|
+
aborted (kind `timeout`, status 0) and sent again once, unless text of it was shown. Headers do
|
|
805
|
+
not count as a piece: a model that thinks sends nothing until it has thought. Keep-alives do. A
|
|
806
|
+
reply that keeps arriving has no limit. 0 turns a wait off.
|
|
807
|
+
- **A stream that closes without saying why it ended** was cut off on its way, by a proxy or a
|
|
808
|
+
dropped connection. It is not taken for a whole reply: it is sent again when none of it was shown,
|
|
809
|
+
and is an error otherwise. So is a reply of HTTP 200 whose body is empty. `onActivity` then says
|
|
810
|
+
"The model's reply was cut off on its way. Trying again…".
|
|
811
|
+
- **A stream that said it is whole** (`[DONE]`, Claude's `message_stop`) returns its reply, though
|
|
812
|
+
the server then leaves the connection open, or the connection breaks: its body is read for at
|
|
813
|
+
most one more second, then cancelled. One event of a stream holds at most 64,000,000 characters;
|
|
814
|
+
a longer one ends the reply with kind `invalid`, and it is not sent again. A reply asked for as a
|
|
815
|
+
stream that comes under another content type is read as events or as JSON, as its first
|
|
816
|
+
characters show; one that starts with more than 65,536 characters of white space is read as
|
|
817
|
+
JSON, whatever follows.
|
|
818
|
+
- **Part reads** of a whole-file read follow the same rule, and an error with no status is tried once
|
|
819
|
+
more at once. Their retries are not told to `onActivity`; since 0.7.0 they are `retry` events.
|
|
820
|
+
They have no silence waits: each request has a limit of 180 s instead (`timeoutMs`
|
|
821
|
+
of `openAiCompatible()` and `anthropic()`; fixed for `gemini()`). An error your token or header
|
|
822
|
+
function throws in a part read has no status with `gemini()`; with `openAiCompatible()` and
|
|
823
|
+
`anthropic()` it is a failed connection (status 0), sent again like one.
|
|
824
|
+
- **An HTTP error or a failed connection** is a `ModelRequestError` (`GeminiRequestError`,
|
|
825
|
+
`OpenAiRequestError`, `AnthropicRequestError`) with a `status` and a `kind`:
|
|
826
|
+
`context_overflow`, `quota`, `rate_limit`, `timeout`, `unreachable`, `server`, `auth` or
|
|
827
|
+
`invalid` ([`ModelErrorKind`](./reference/errors-and-retries.md#modelerrorkind)). So is a reply
|
|
828
|
+
of HTTP 200 whose body is not JSON: kind `invalid`, status 200, and the `SyntaxError` as its
|
|
829
|
+
`cause`. Other errors have no kind: `DocumentsNotFoundError`, `DocumentStoreError`, an error your
|
|
830
|
+
own token or header function throws in a chat request, an abort.
|
|
831
|
+
- **Stopping.** When the question's `signal` aborts, the question stops at once and throws the
|
|
832
|
+
signal's reason, even when an adapter or a part reader does not look at the signal. Nothing is
|
|
833
|
+
sent after that, and text that such an adapter sends later is not shown. A request still running
|
|
834
|
+
then may be billed by the provider; it is not counted in the usage.
|
|
835
|
+
- **What a failed question found.** A question that fails once under way leaves its steps,
|
|
836
|
+
evidence, tool rounds and usage to `partialResultOf(error)`, with `answered: false`. It is
|
|
837
|
+
undefined for an error raised before the question was under way: a missing document, a budget
|
|
838
|
+
that cannot work, a store that failed while the documents were planned.
|
|
839
|
+
|
|
840
|
+
What to show a user for each error: [Errors and reliability](./guides/errors-and-reliability.md).
|
|
841
|
+
The retry rule and the waits as exports:
|
|
842
|
+
[Errors, retries and streams](./reference/errors-and-retries.md).
|
|
843
|
+
|
|
844
|
+
### The request for the answer
|
|
845
|
+
|
|
846
|
+
When the model's last turn has text and no calls, that text is the answer. Otherwise one more request
|
|
847
|
+
is sent to the answering model, and it must be answered in text:
|
|
848
|
+
|
|
849
|
+
- **When.** The tool turns ran out (`limits.toolTurns`, 12 by default: tools run in at most 11
|
|
850
|
+
requests, so no request is made whose calls would be thrown away), the room ran out, the question
|
|
851
|
+
reached `limits.inputTokens` or all but one of `limits.requests`, or the model's last turn had no
|
|
852
|
+
text (cut off, stopped by a filter, or a broken call). With an explorer it is always made. It is
|
|
853
|
+
not made after a blocked prompt, which would only be blocked again.
|
|
854
|
+
- **What.** The conversation, then a user message: `FINAL_ANSWER_REQUEST` after text tools,
|
|
855
|
+
`FINAL_ANSWER_AFTER_PAGES` when the only tool offered was `view_pages` (every text was in the
|
|
856
|
+
prompt), or `FINAL_ANSWER_WITHOUT_TOOLS` when no call was answered at all. For Gemini the request
|
|
857
|
+
declares no tools; for an OpenAI-compatible endpoint and for Claude it keeps them and sets the
|
|
858
|
+
tool choice to none.
|
|
859
|
+
- **Its result.** `answered` is true when the reply has text and the prompt was not blocked. A
|
|
860
|
+
reply with no text is asked for once more ([Empty or broken turns](#empty-or-broken-turns)). When
|
|
861
|
+
even that has no text, or the provider blocked the prompt, `answered` is `false` (with
|
|
862
|
+
`blockReason`), so your application can show its own message instead of an empty answer.
|
|
863
|
+
|
|
864
|
+
### An explorer model
|
|
865
|
+
|
|
866
|
+
One model does all of the above unless the question has an explorer: `askWithFiles({ model,
|
|
867
|
+
explorer })`, where the two may be of different providers, or an `askGemini` endpoint that names one
|
|
868
|
+
([An explorer model](./guides/explorer-model.md)). Then the loop is split in two:
|
|
869
|
+
|
|
870
|
+
- **The requests with tools go to the explorer.** It gets the same conversation, the same tool guide
|
|
871
|
+
and `EXPLORER_INSTRUCTION`: gather what the answer needs, then reply `DONE`. Its turns go back to
|
|
872
|
+
it unchanged, thought signatures included. Reading a whole file in parts is its work too, with its
|
|
873
|
+
own part reader. Its words are not shown, and nothing it writes is the answer.
|
|
874
|
+
- **The request for the answer goes to the answering model**, and with an explorer it is always
|
|
875
|
+
made. It holds the conversation, the explorer's tool calls and their results, pages included,
|
|
876
|
+
and the closing user message. It does not hold the explorer's thoughts, its thought signatures,
|
|
877
|
+
its remarks or its notes: the answer is written from what the files say.
|
|
878
|
+
- **The budget fits both models**: the smaller window, the larger `tokenScale`, and pages at the
|
|
879
|
+
larger `pageTokens`. `view_pages` needs both to take a file. `limits.toolTurns` counts the
|
|
880
|
+
explorer's requests and the answer's, so the explorer has one less.
|
|
881
|
+
|
|
882
|
+
### Usage and evidence
|
|
883
|
+
|
|
884
|
+
- **Usage** is summed over every request of the question that was answered: the chat's, the
|
|
885
|
+
explorer's and the part reads, in all and for each model (`usage.byModel`, by adapter `id`). A
|
|
886
|
+
request that failed and was sent again counts once. A part reader that does not report its tokens
|
|
887
|
+
still counts its requests. `turns` counts the chat requests alone, and `lastUsage` is the
|
|
888
|
+
provider's own usage object of the last chat response. Turning it into a cost:
|
|
889
|
+
[Costs and limits](./guides/costs-and-limits.md).
|
|
890
|
+
- **Evidence** is read from the tool calls, in call order: for each call that ran, the document and
|
|
891
|
+
the lines or pages it showed (merged into ranges). A search adds its query and mode, and an exact
|
|
892
|
+
or regex search its `totalMatchingLines`. An overview shows the first 30 and last 20 lines. A
|
|
893
|
+
whole-file read is marked `whole: true`, with its task as the query. Calls that failed or were
|
|
894
|
+
refused, pointers and stand-ins add nothing.
|
|
895
|
+
|
|
896
|
+
### What your application sees
|
|
897
|
+
|
|
898
|
+
- `onText`: the answer as it arrives. Without an explorer, a remark the model makes before a tool
|
|
899
|
+
call is shown too, separated by a blank line, and is part of `text`; `answered` is about the last
|
|
900
|
+
turn.
|
|
901
|
+
- `onActivity`: short-lived status. "Too large to read at once: app.log. Searching instead…", each
|
|
902
|
+
call as it runs ("Search app.log (exact) for “timeout”…"), the parts of a whole-file read,
|
|
903
|
+
retries, and "Writing the answer…".
|
|
904
|
+
- `onStep` and `steps`: each finished call with what it found ("Search app.log (exact) for
|
|
905
|
+
“timeout” — 12 matching lines"), and what the loop did to the conversation.
|
|
906
|
+
- `onEvent`, or `askStream` (new in 0.7.0): all of the above and more, as typed events in order,
|
|
907
|
+
each with a `seq` from 1, from `run.start` to `run.finish` or `run.error`. The three callbacks
|
|
908
|
+
get the same strings, at the same moments, with or without it. See
|
|
909
|
+
[Events](./reference/events.md).
|
|
910
|
+
|
|
911
|
+
Where the events of a question come from:
|
|
912
|
+
|
|
913
|
+
| Event | Sent by | When |
|
|
914
|
+
|---|---|---|
|
|
915
|
+
| `run.start` | `askWithFiles` | First, before the options are checked or the documents planned. |
|
|
916
|
+
| `plan` | the plan | Once the documents are planned; again after a question planned again (a `replanned` notice comes first). |
|
|
917
|
+
| `request.start`, `request.end` | each chat request (`role` `"tools"`, `"explorer"` or `"answer"`) and each request of a whole-file read (`"reader"`, with its `callId`) | Around the request, its retries included. An overflow made smaller is a new request. |
|
|
918
|
+
| `retry` | the retry rule ([Retries and waits](#retries-and-waits)) | Before each wait, between the request's start and end. |
|
|
919
|
+
| `text` | the answering model's replies | As the text arrives with `streamText`; otherwise once each reply is in. The same text as `onText`. |
|
|
920
|
+
| `tool.start`, `tool.progress`, `tool.end` | the calls of a turn ([The calls of a turn](#the-calls-of-a-turn)) | A call starts when it runs, so starts and ends of one turn interleave; ends come in call order. `tool.progress` is the progress of a whole-file read. |
|
|
921
|
+
| `notice` | the loop | What it did that is not a request or a call: `searching_instead`, `writing_answer`, `replanned`, `room_made`, `nudged`, `results_shortened`, `answer_again`, `calls_not_run`, and three that the callbacks never got: `budget_reached`, `no_room`, `blocked`. |
|
|
922
|
+
| `run.finish`, `run.error` | `askWithFiles` | Last, once. Nothing comes after them, not even a part read still running. |
|
|
923
|
+
|
|
924
|
+
The events tell a model error by its kind and status, never in the provider's words, and carry no
|
|
925
|
+
text of the documents unless the question is asked with `eventResults: true`. An ingest has its own events, from `ingest.start` to
|
|
926
|
+
`ingest.finish` or `ingest.error` ([`files.ingest`](./reference/library.md#filesingestinput)).
|
|
927
|
+
|
|
928
|
+
Activity lines and steps are each one line of plain text, cleaned of what file text drops, and a
|
|
929
|
+
call to a tool that does not exist is shown as `Call “<name>”`. They quote the model's words: show
|
|
930
|
+
them as plain text ([Security](./security.md#what-the-library-logs)).
|
|
931
|
+
|
|
932
|
+
In this sample, `files` and `meta` come from the sample in
|
|
933
|
+
[How the plan is made](#how-the-plan-is-made), and `accessToken` is the function shown in
|
|
934
|
+
[Gemini API and Vertex AI](./guides/vertex-and-gemini.md), which returns a Vertex AI access token.
|
|
935
|
+
|
|
936
|
+
```ts
|
|
937
|
+
import { askWithFiles, partialResultOf } from "llm-large-files";
|
|
938
|
+
import { gemini, vertexAi } from "llm-large-files/gemini";
|
|
939
|
+
|
|
940
|
+
// files and meta: from the sample in "How the plan is made".
|
|
941
|
+
// accessToken: the function of the Gemini API and Vertex AI guide.
|
|
942
|
+
const model = gemini(vertexAi({ project: process.env.GOOGLE_CLOUD_PROJECT!, model: "gemini-3.8-flash", accessToken }));
|
|
943
|
+
|
|
944
|
+
try {
|
|
945
|
+
const result = await askWithFiles({
|
|
946
|
+
files,
|
|
947
|
+
model,
|
|
948
|
+
documentIds: [meta.id],
|
|
949
|
+
messages: [{ role: "user", text: "Why did the database fail over?" }],
|
|
950
|
+
onActivity: (text) => console.log(`[now] ${text}`),
|
|
951
|
+
onStep: (text) => console.log(`[step] ${text}`),
|
|
952
|
+
});
|
|
953
|
+
console.log(result.answered, result.text);
|
|
954
|
+
console.log(result.plan.searchable.length, result.budget.contextTokens); // the plan and the fitted budget
|
|
955
|
+
console.log(result.evidence, result.usage.requests, result.turns);
|
|
956
|
+
} catch (error) {
|
|
957
|
+
// What the question found and paid for before it failed, when it was under way.
|
|
958
|
+
console.log(partialResultOf(error)?.steps);
|
|
959
|
+
throw error;
|
|
960
|
+
}
|
|
961
|
+
```
|
|
962
|
+
|
|
963
|
+
### What differs between providers
|
|
964
|
+
|
|
965
|
+
What differs is in the adapters:
|
|
966
|
+
|
|
967
|
+
| | Gemini (`gemini()`) | OpenAI-compatible (`openAiCompatible()`) | Claude (`anthropic()`) |
|
|
143
968
|
|---|---|---|---|
|
|
144
|
-
| The model's turn goes back | unchanged: thought signatures | unchanged
|
|
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,
|
|
147
|
-
|
|
|
148
|
-
|
|
|
969
|
+
| The model's turn goes back | unchanged: thought signatures | unchanged (`reasoning_content`, OpenRouter's `reasoning_details`), but arguments that are not a JSON object, or are empty, go back as JSON (`"{}"`) | unchanged (thinking blocks), but an empty text block after the last thinking block is left out |
|
|
970
|
+
| The request for the answer | no tools declared | `tool_choice: "none"`, tools kept; `answerWithoutTools: "omit"` leaves them out | `tool_choice: { type: "none" }`, tools kept |
|
|
971
|
+
| Pages of `view_pages` | inside the function response, or in a user turn of their own with `toolFilePlacement: "beside"` | a `file` part in a user message after the results, only with `pdfInput: true`; otherwise not offered | a document block in the tool result; after the results with `toolFilePlacement: "beside"`; not offered with `"none"` |
|
|
972
|
+
| A page costs (`pageTokens`) | 530 by default | 1,000 by default | 3,500 by default |
|
|
973
|
+
| `tokenScale` | 1 | 1 by default (`tokenScale`) | 1.35 by default (`tokenScale`) |
|
|
974
|
+
| Kept free in the window for the reply | nothing | nothing | `maxTokens`, 64,000 by default |
|
|
975
|
+
| Request size declared | none, unless you set `maxRequestBytes` | none, unless you set `maxRequestBytes` | 32,000,000 bytes by default (`maxRequestBytes`) |
|
|
976
|
+
| Old results shortened for room | yes, unless Claude is the other model of the question | yes, unless Claude is the other model of the question | no: the conversation may only grow (`appendOnly`); with Claude as the answering model or the explorer, nothing is shortened for either |
|
|
977
|
+
| Prompt cache | the provider's own | the provider's own | `cache_control` on each request: 5 minutes, `cache: "1h"`, or `false` for none |
|
|
978
|
+
| Streams the chat | when the loop asks for the text as it is written (`streamText`: with `onText`, or in `askStream`) and the endpoint has a `streamUrl` | when the loop asks for the text as it is written, unless `stream: false` | always, unless `stream: false` |
|
|
979
|
+
| A whole stream ends with | a chunk with a `finishReason` | a `finish_reason`, or `[DONE]` | a stop reason |
|
|
980
|
+
|
|
981
|
+
The adapters also handle what their providers do differently:
|
|
982
|
+
|
|
983
|
+
- **OpenAI-compatible.** Two user turns in a row are sent as one, since some servers refuse them.
|
|
984
|
+
The output limit of a part read is `max_completion_tokens` on OpenAI and Azure OpenAI hosts and
|
|
985
|
+
`max_tokens` elsewhere, and a server that refuses the name it got is sent the other, which is
|
|
986
|
+
kept. An error inside a stream that began with 200 gets the status its code or type names, or
|
|
987
|
+
500, and keeps its code (`context_length_exceeded`, `insufficient_quota`). An error whose message
|
|
988
|
+
is at the top of the body (vLLM before its OpenAI-shaped errors, SGLang, FastChat) or in FastAPI's
|
|
989
|
+
`detail` is read. DeepSeek's `insufficient_system_resource` is a 503, sent again. A tool name sent
|
|
990
|
+
again with each piece of a stream is taken once. A refusal is kept as the reply's text.
|
|
991
|
+
[OpenAI-compatible endpoints](./guides/openai-compatible.md).
|
|
992
|
+
- **Claude.** Call IDs of other providers and of stored rounds are rewritten to what the API takes,
|
|
993
|
+
each once in a request. After a server-side fallback, the thinking and tool-use blocks written
|
|
994
|
+
before the switch are left out of the turn that goes back, and the tool calls among them are not
|
|
995
|
+
run. A refusal is reported as `blockReason` (`refusal`, with its category). A failed tool result
|
|
996
|
+
is marked `is_error`. An error inside a stream gets the status of its type
|
|
997
|
+
(`invalid_request_error` 400, `authentication_error` 401, `billing_error` 402,
|
|
998
|
+
`permission_error` 403, `not_found_error` 404, `request_too_large` 413), and a type it does not
|
|
999
|
+
know is 500, sent again when none of the reply was shown. With `clear_tool_uses` or compaction in
|
|
1000
|
+
`body.context_management`, the adapter declares `clearsToolResults`
|
|
1001
|
+
([Pointers to repeated calls](#pointers-to-repeated-calls)). [Claude](./guides/anthropic.md).
|
|
149
1002
|
|
|
150
1003
|
## Gemini (`askGemini`, `gemini()`)
|
|
151
1004
|
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
independent searches and stop when it has enough. This keeps it from searching one thing per turn.
|
|
160
|
-
- **Gemini can ignore `functionCallingConfig: { mode: "NONE" }`.** Live testing showed it kept
|
|
161
|
-
calling tools on the turn meant to force an answer. So when the turns run out, or the model's
|
|
162
|
-
last turn has no text, the final request **declares no tools at all** and adds a short "answer
|
|
163
|
-
now" message. That request is the last of the `maxToolTurns`; no request is made whose tool
|
|
164
|
-
calls would be thrown away.
|
|
165
|
-
- If even that request has no text, or Gemini blocks the prompt, the result has `answered: false`
|
|
166
|
-
(and `blockReason`), so the caller can show its own message instead of an empty answer.
|
|
167
|
-
- Pages from `view_pages` go **inside the function response** (`functionResponse.parts`, with the
|
|
168
|
-
result naming the file as `{ "$ref": "pages-12-14.pdf" }`). `toolFilePlacement: "beside"` sends
|
|
169
|
-
them in a `user` turn of their own, right after the turn of function responses: Gemini 2.5 does
|
|
170
|
-
not see a file inside a function response. The files do not share a turn with the function
|
|
171
|
-
responses, because Vertex AI refuses a turn in which anything follows one. Both forms work with
|
|
172
|
-
Gemini 3.5 on the Gemini API and on Vertex AI.
|
|
173
|
-
- Tool results, pages included, live inside one call of `askGemini`. They are not sent again with
|
|
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.
|
|
176
|
-
|
|
177
|
-
### With an explorer model
|
|
178
|
-
|
|
179
|
-
One model does all of the above unless the endpoint names an explorer
|
|
180
|
-
([configuration](configuration.md#an-explorer-model)). Then the loop is split in two:
|
|
181
|
-
|
|
182
|
-
- **The requests with tools go to the explorer.** It gets the same conversation, the same tool
|
|
183
|
-
guide and a line that says what its part is: gather what the answer needs, then reply `DONE`.
|
|
184
|
-
Its turns go back to it unchanged, thought signatures included. Reading a whole file in parts is
|
|
185
|
-
its work too.
|
|
186
|
-
- **The request without tools goes to the answering model**, and with an explorer it is always
|
|
187
|
-
made. It holds the conversation, the explorer's function calls, and the function responses, pages
|
|
188
|
-
included. It does not hold the explorer's thoughts, its thought signatures, or anything it
|
|
189
|
-
wrote: the answer is written from what the files say.
|
|
190
|
-
- **That request ends with a user message.** A Gemini 3 model refuses a request that ends with
|
|
191
|
-
the result of a function call it did not sign (HTTP 400, "Function call is missing a
|
|
192
|
-
thought_signature"), and a signature belongs to the model that made the call. With a user message
|
|
193
|
-
after the results, the calls belong to an earlier turn, and the request is accepted without
|
|
194
|
-
signatures. The message is the "answer now" one from above.
|
|
195
|
-
- An explorer that calls no tool leaves nothing to answer from but the conversation, so the
|
|
196
|
-
message then says that instead (`FINAL_ANSWER_WITHOUT_TOOLS`).
|
|
1005
|
+
`askGemini` is `askWithFiles` with a `gemini()` model for the endpoint. When the endpoint names an
|
|
1006
|
+
explorer (`explorerUrl`, which `explorerModel` of `geminiApi()` and `vertexAi()` sets), it makes a
|
|
1007
|
+
second `gemini()` for it, called with the same headers, without streaming, with
|
|
1008
|
+
`explorerGenerationConfig` or else `generationConfig`. `maxToolTurns` and `maxToolCallsPerTurn` are
|
|
1009
|
+
the names that `limits.toolTurns` and `limits.callsPerTurn` had before 0.5.0; `limits` wins.
|
|
1010
|
+
`contents` are converted to messages with `fromGeminiContents`. Everything above applies; what is
|
|
1011
|
+
Gemini's own:
|
|
197
1012
|
|
|
198
|
-
|
|
1013
|
+
- **The model's turns go back unchanged**, so Gemini 3 thought signatures stay intact. A signature
|
|
1014
|
+
belongs to the model that wrote it: with an explorer, the answering model gets the explorer's
|
|
1015
|
+
function calls without them, and its request ends with the closing user message after the
|
|
1016
|
+
function responses.
|
|
1017
|
+
- **The request for the answer declares no tools at all.** Gemini can ignore
|
|
1018
|
+
`functionCallingConfig: { mode: "NONE" }` and keep calling tools on the turn meant to force an
|
|
1019
|
+
answer. The tool requests use mode `AUTO`.
|
|
1020
|
+
- **Finish reasons.** `MAX_TOKENS` is a reply cut off at the output limit. `SAFETY`, `RECITATION`,
|
|
1021
|
+
`BLOCKLIST`, `PROHIBITED_CONTENT`, `SPII` and `IMAGE_SAFETY` mark a reply a filter stopped.
|
|
1022
|
+
`MALFORMED_FUNCTION_CALL` and `UNEXPECTED_TOOL_CALL` are a broken call, asked for once more. A
|
|
1023
|
+
prompt Gemini blocks (`promptFeedback.blockReason`) ends the question with `answered: false` and
|
|
1024
|
+
`blockReason`.
|
|
1025
|
+
- **Pages** go inside the function response: `functionResponse.parts` holds the PDF, and the result
|
|
1026
|
+
names it as `{ "$ref": "pages-12-14.pdf" }`. Gemini 2.5 does not see a file there, so
|
|
1027
|
+
`toolFilePlacement: "beside"` sends the pages in a user turn of their own, right after the turn of
|
|
1028
|
+
function responses. They do not share that turn, because Vertex AI refuses a turn in which
|
|
1029
|
+
anything follows a function response.
|
|
1030
|
+
- **Errors.** `error.status` and `details` tell the kind: a 429 whose `QuotaFailure` names a quota
|
|
1031
|
+
per day, or whose message alone does, is `quota`, not sent again, while a quota per minute is
|
|
1032
|
+
waited for; `API_KEY_INVALID` is `auth`. The `retryDelay` of `RetryInfo` is the wait. A streamed
|
|
1033
|
+
reply that comes as one JSON chunk, or a list of them, is read.
|
|
1034
|
+
- **Usage.** Input is `promptTokenCount` plus `toolUsePromptTokenCount`, cached input
|
|
1035
|
+
`cachedContentTokenCount`, output `candidatesTokenCount` plus `thoughtsTokenCount`.
|
|
1036
|
+
- **Part reads** go to the non-streaming URL of the model that explores, with
|
|
1037
|
+
`{ maxOutputTokens }`, with no temperature (Gemini 3.6 and later ignore one), unless
|
|
1038
|
+
`analysisConfig` says otherwise, and a limit of 180 s per request. Headers are asked for with
|
|
1039
|
+
every request, chat or part, so an access token renewed meanwhile is used.
|
|
199
1040
|
|
|
200
|
-
|
|
1041
|
+
Setting up Gemini and Vertex AI, thinking, quotas and gateways:
|
|
1042
|
+
[Gemini API and Vertex AI](./guides/vertex-and-gemini.md).
|
|
201
1043
|
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
| Map-reduce on the novel, 40K-token parts | 4 parts, 1 relevant. Correct answer citing L2036. 32 s. |
|
|
1044
|
+
## Live results
|
|
1045
|
+
|
|
1046
|
+
The live checks of the loop, the token estimate, map-reduce and `view_pages` are in
|
|
1047
|
+
[Measurements](./measurements.md).
|
|
207
1048
|
|
|
208
|
-
The
|
|
209
|
-
|
|
1049
|
+
The events of 0.7.0 were checked live on the Gemini API in November 2026, with
|
|
1050
|
+
`gemini-3.1-flash-lite` answering and `gemini-3.5-flash-lite` exploring, on a log of 60,000 lines
|
|
1051
|
+
(7.2 MB) and a smaller one read whole. In each question the events ran in order from `run.start`
|
|
1052
|
+
to `run.finish`, every request and call that started ended, the `text` events joined to the
|
|
1053
|
+
answer, and `onStep` got the same steps as before. The explorer's requests were marked `role: "explorer"` and the answer's
|
|
1054
|
+
`role: "answer"`. A whole-file read made 7 part requests, each with the `callId` of its call and a
|
|
1055
|
+
`tool.progress` for each part, and its 21 retries came as `retry` events. `writeSseEvents` sent a
|
|
1056
|
+
question to a client over HTTP, one message per event, ending with `run.finish` without
|
|
1057
|
+
`toolTurns`.
|