llm-large-files 0.4.1 → 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.
Files changed (236) hide show
  1. package/CHANGELOG.md +1400 -338
  2. package/README.md +217 -49
  3. package/dist/analyze.d.ts +5 -0
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +96 -47
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +117 -0
  8. package/dist/anthropic/adapter.d.ts.map +1 -0
  9. package/dist/anthropic/adapter.js +542 -0
  10. package/dist/anthropic/adapter.js.map +1 -0
  11. package/dist/anthropic/index.d.ts +3 -0
  12. package/dist/anthropic/index.d.ts.map +1 -0
  13. package/dist/anthropic/index.js +2 -0
  14. package/dist/anthropic/index.js.map +1 -0
  15. package/dist/ask.d.ts +200 -0
  16. package/dist/ask.d.ts.map +1 -0
  17. package/dist/ask.js +1402 -0
  18. package/dist/ask.js.map +1 -0
  19. package/dist/budget.d.ts +23 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +64 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/encoding.d.ts +17 -0
  24. package/dist/encoding.d.ts.map +1 -0
  25. package/dist/encoding.js +852 -0
  26. package/dist/encoding.js.map +1 -0
  27. package/dist/errors.d.ts +4 -0
  28. package/dist/errors.d.ts.map +1 -1
  29. package/dist/errors.js +15 -0
  30. package/dist/errors.js.map +1 -1
  31. package/dist/events.d.ts +333 -0
  32. package/dist/events.d.ts.map +1 -0
  33. package/dist/events.js +159 -0
  34. package/dist/events.js.map +1 -0
  35. package/dist/evidence.d.ts +42 -0
  36. package/dist/evidence.d.ts.map +1 -0
  37. package/dist/evidence.js +138 -0
  38. package/dist/evidence.js.map +1 -0
  39. package/dist/extract.d.ts +35 -3
  40. package/dist/extract.d.ts.map +1 -1
  41. package/dist/extract.js +626 -58
  42. package/dist/extract.js.map +1 -1
  43. package/dist/gemini/adapter.d.ts +59 -0
  44. package/dist/gemini/adapter.d.ts.map +1 -0
  45. package/dist/gemini/adapter.js +226 -0
  46. package/dist/gemini/adapter.js.map +1 -0
  47. package/dist/gemini/chat.d.ts +53 -77
  48. package/dist/gemini/chat.d.ts.map +1 -1
  49. package/dist/gemini/chat.js +42 -300
  50. package/dist/gemini/chat.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +16 -0
  52. package/dist/gemini/errors.d.ts.map +1 -0
  53. package/dist/gemini/errors.js +46 -0
  54. package/dist/gemini/errors.js.map +1 -0
  55. package/dist/gemini/generate.d.ts +18 -21
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +49 -92
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +6 -4
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +4 -3
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -2
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -38
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/http.d.ts +136 -0
  68. package/dist/http.d.ts.map +1 -0
  69. package/dist/http.js +401 -0
  70. package/dist/http.js.map +1 -0
  71. package/dist/index.d.ts +18 -2
  72. package/dist/index.d.ts.map +1 -1
  73. package/dist/index.js +13 -4
  74. package/dist/index.js.map +1 -1
  75. package/dist/library.d.ts +96 -8
  76. package/dist/library.d.ts.map +1 -1
  77. package/dist/library.js +414 -96
  78. package/dist/library.js.map +1 -1
  79. package/dist/map-reduce.d.ts +37 -1
  80. package/dist/map-reduce.d.ts.map +1 -1
  81. package/dist/map-reduce.js +255 -61
  82. package/dist/map-reduce.js.map +1 -1
  83. package/dist/model.d.ts +278 -0
  84. package/dist/model.d.ts.map +1 -0
  85. package/dist/model.js +222 -0
  86. package/dist/model.js.map +1 -0
  87. package/dist/node/handlers.d.ts +20 -4
  88. package/dist/node/handlers.d.ts.map +1 -1
  89. package/dist/node/handlers.js +122 -20
  90. package/dist/node/handlers.js.map +1 -1
  91. package/dist/node/index.d.ts +2 -0
  92. package/dist/node/index.d.ts.map +1 -1
  93. package/dist/node/index.js +1 -0
  94. package/dist/node/index.js.map +1 -1
  95. package/dist/node/sse.d.ts +59 -0
  96. package/dist/node/sse.d.ts.map +1 -0
  97. package/dist/node/sse.js +174 -0
  98. package/dist/node/sse.js.map +1 -0
  99. package/dist/openai/adapter.d.ts +109 -0
  100. package/dist/openai/adapter.d.ts.map +1 -0
  101. package/dist/openai/adapter.js +567 -0
  102. package/dist/openai/adapter.js.map +1 -0
  103. package/dist/openai/index.d.ts +3 -0
  104. package/dist/openai/index.d.ts.map +1 -0
  105. package/dist/openai/index.js +2 -0
  106. package/dist/openai/index.js.map +1 -0
  107. package/dist/output-limit.d.ts +42 -0
  108. package/dist/output-limit.d.ts.map +1 -0
  109. package/dist/output-limit.js +121 -0
  110. package/dist/output-limit.js.map +1 -0
  111. package/dist/pause.d.ts +24 -0
  112. package/dist/pause.d.ts.map +1 -0
  113. package/dist/pause.js +38 -0
  114. package/dist/pause.js.map +1 -0
  115. package/dist/pdf-pages.d.ts +32 -2
  116. package/dist/pdf-pages.d.ts.map +1 -1
  117. package/dist/pdf-pages.js +275 -14
  118. package/dist/pdf-pages.js.map +1 -1
  119. package/dist/pdf-pictures.d.ts +30 -3
  120. package/dist/pdf-pictures.d.ts.map +1 -1
  121. package/dist/pdf-pictures.js +50 -8
  122. package/dist/pdf-pictures.js.map +1 -1
  123. package/dist/pdf-work.d.ts +40 -0
  124. package/dist/pdf-work.d.ts.map +1 -0
  125. package/dist/pdf-work.js +734 -0
  126. package/dist/pdf-work.js.map +1 -0
  127. package/dist/plan.d.ts +22 -4
  128. package/dist/plan.d.ts.map +1 -1
  129. package/dist/plan.js +61 -12
  130. package/dist/plan.js.map +1 -1
  131. package/dist/retry.d.ts +76 -0
  132. package/dist/retry.d.ts.map +1 -0
  133. package/dist/retry.js +141 -0
  134. package/dist/retry.js.map +1 -0
  135. package/dist/search.d.ts +8 -2
  136. package/dist/search.d.ts.map +1 -1
  137. package/dist/search.js +60 -10
  138. package/dist/search.js.map +1 -1
  139. package/dist/sse.d.ts +36 -0
  140. package/dist/sse.d.ts.map +1 -0
  141. package/dist/sse.js +153 -0
  142. package/dist/sse.js.map +1 -0
  143. package/dist/stores.d.ts.map +1 -1
  144. package/dist/stores.js +5 -2
  145. package/dist/stores.js.map +1 -1
  146. package/dist/text-index.d.ts +6 -0
  147. package/dist/text-index.d.ts.map +1 -1
  148. package/dist/text-index.js +25 -8
  149. package/dist/text-index.js.map +1 -1
  150. package/dist/text.d.ts +62 -2
  151. package/dist/text.d.ts.map +1 -1
  152. package/dist/text.js +314 -14
  153. package/dist/text.js.map +1 -1
  154. package/dist/tools.d.ts +72 -1
  155. package/dist/tools.d.ts.map +1 -1
  156. package/dist/tools.js +341 -60
  157. package/dist/tools.js.map +1 -1
  158. package/dist/types.d.ts +128 -4
  159. package/dist/types.d.ts.map +1 -1
  160. package/dist/zip-directory.d.ts +43 -0
  161. package/dist/zip-directory.d.ts.map +1 -0
  162. package/dist/zip-directory.js +130 -0
  163. package/dist/zip-directory.js.map +1 -0
  164. package/docs/README.md +288 -0
  165. package/docs/api.md +58 -184
  166. package/docs/configuration.md +34 -490
  167. package/docs/getting-started.md +412 -177
  168. package/docs/guides/anthropic.md +590 -0
  169. package/docs/guides/conversations.md +629 -0
  170. package/docs/guides/costs-and-limits.md +726 -0
  171. package/docs/guides/deployment.md +654 -0
  172. package/docs/guides/errors-and-reliability.md +735 -0
  173. package/docs/guides/explorer-model.md +399 -0
  174. package/docs/guides/openai-compatible.md +602 -0
  175. package/docs/guides/own-adapter-and-loop.md +1169 -0
  176. package/docs/guides/pdfs.md +971 -0
  177. package/docs/guides/storage.md +731 -0
  178. package/docs/guides/testing.md +1199 -0
  179. package/docs/guides/vertex-and-gemini.md +717 -0
  180. package/docs/guides/web-app.md +1589 -0
  181. package/docs/how-it-works.md +1022 -138
  182. package/docs/measurements.md +881 -0
  183. package/docs/publishing.md +274 -46
  184. package/docs/reference/anthropic.md +427 -0
  185. package/docs/reference/ask.md +892 -0
  186. package/docs/reference/errors-and-retries.md +758 -0
  187. package/docs/reference/events.md +993 -0
  188. package/docs/reference/gemini.md +823 -0
  189. package/docs/reference/library.md +1467 -0
  190. package/docs/reference/node.md +528 -0
  191. package/docs/reference/openai.md +385 -0
  192. package/docs/reference/tools.md +883 -0
  193. package/docs/security.md +902 -90
  194. package/docs/troubleshooting.md +1390 -0
  195. package/package.json +22 -4
  196. package/src/analyze.ts +93 -42
  197. package/src/anthropic/adapter.ts +611 -0
  198. package/src/anthropic/index.ts +2 -0
  199. package/src/ask.ts +1560 -0
  200. package/src/budget.ts +71 -0
  201. package/src/encoding.ts +850 -0
  202. package/src/errors.ts +17 -0
  203. package/src/events.ts +442 -0
  204. package/src/evidence.ts +165 -0
  205. package/src/extract.ts +602 -62
  206. package/src/gemini/adapter.ts +271 -0
  207. package/src/gemini/chat.ts +87 -355
  208. package/src/gemini/errors.ts +48 -0
  209. package/src/gemini/generate.ts +67 -94
  210. package/src/gemini/index.ts +6 -4
  211. package/src/gemini/sse.ts +1 -34
  212. package/src/http.ts +434 -0
  213. package/src/index.ts +55 -4
  214. package/src/library.ts +497 -97
  215. package/src/map-reduce.ts +266 -59
  216. package/src/model.ts +433 -0
  217. package/src/node/handlers.ts +137 -22
  218. package/src/node/index.ts +2 -0
  219. package/src/node/sse.ts +198 -0
  220. package/src/openai/adapter.ts +613 -0
  221. package/src/openai/index.ts +2 -0
  222. package/src/output-limit.ts +135 -0
  223. package/src/pause.ts +41 -0
  224. package/src/pdf-pages.ts +268 -15
  225. package/src/pdf-pictures.ts +56 -9
  226. package/src/pdf-work.ts +722 -0
  227. package/src/plan.ts +68 -12
  228. package/src/retry.ts +176 -0
  229. package/src/search.ts +63 -10
  230. package/src/sse.ts +159 -0
  231. package/src/stores.ts +5 -2
  232. package/src/text-index.ts +26 -7
  233. package/src/text.ts +323 -13
  234. package/src/tools.ts +338 -62
  235. package/src/types.ts +129 -5
  236. package/src/zip-directory.ts +136 -0
@@ -0,0 +1,883 @@
1
+ # Tools
2
+
3
+ This page lists the tools the model gets for documents too large for its prompt and for the
4
+ pages of PDFs: their names, arguments, results and limits, and the tool exports of `llm-large-files`. Read it when you write a
5
+ loop of your own, show `steps` to users, keep `toolTurns`, or want to know exactly what the model
6
+ was told and what it read.
7
+
8
+ ```ts
9
+ import { MAX_VIEW_PAGES, MAX_WHOLE_DOCUMENT_READS, REGEX_BUDGET_MS, TOOL_NAMES, toolResultSummary } from "llm-large-files";
10
+ import type { JsonSchema, ToolCallLimits, ToolDeclaration, ToolFile, ToolFileLimits, ToolOutput, ToolResult, ToolSet } from "llm-large-files";
11
+ ```
12
+
13
+ Contents:
14
+
15
+ - [The tools](#the-tools) and [which tools are offered](#which-tools-are-offered)
16
+ - [Rules for every tool](#rules-for-every-tool)
17
+ - [`search_document`](#search_document), [`read_document`](#read_document),
18
+ [`get_document_overview`](#get_document_overview),
19
+ [`analyze_whole_document`](#analyze_whole_document), [`view_pages`](#view_pages)
20
+ - [The tool guide](#the-tool-guide)
21
+ - [What `askWithFiles` adds to results](#what-askwithfiles-adds-to-results)
22
+ - Exports: [`TOOL_NAMES`](#tool_names), [`MAX_VIEW_PAGES`](#max_view_pages),
23
+ [`MAX_WHOLE_DOCUMENT_READS`](#max_whole_document_reads), [`REGEX_BUDGET_MS`](#regex_budget_ms),
24
+ [toolResultSummary(label, result)](#toolresultsummarylabel-result), [`ToolSet`](#toolset),
25
+ [`ToolCallLimits`](#toolcalllimits), [`ToolFileLimits`](#toolfilelimits),
26
+ [`ToolOutput`](#tooloutput), [`ToolFile`](#toolfile), [`ToolResult`](#toolresult),
27
+ [`ToolDeclaration`](#tooldeclaration), [`JsonSchema`](#jsonschema)
28
+ - [Stability](#stability)
29
+
30
+ Related exports on other pages: [`LargeFiles`](./library.md#largefiles) (its `tools()` method),
31
+ [`ToolOptions`](./library.md#tooloptions), [`ToolCallHooks`](./library.md#toolcallhooks) (the
32
+ fourth argument of `executeWithFiles`), [`PreparedContext`](./library.md#preparedcontext) and
33
+ [`Budget`](./library.md#budget) are in the [library reference](./library.md). `ToolCall`,
34
+ `ToolAnswer`, `ToolTurn`, `evidenceOf`, `stubResult` and [`AskLimits`](./ask.md#asklimits) are in
35
+ the [loop reference](./ask.md).
36
+
37
+ ## The tools
38
+
39
+ | Tool | What it does |
40
+ |---|---|
41
+ | `search_document` | Finds lines that contain a text or match a regex, with an exact count, the first of them and the last one; or the passages that match keywords best. |
42
+ | `read_document` | Reads a range of lines, numbered, up to 600 a call. |
43
+ | `get_document_overview` | The outline, the log profile, the first 30 and last 20 lines, and what a whole-file read would take. |
44
+ | `analyze_whole_document` | Reads the whole file in parts with other model calls (map-reduce) and answers a task that needs all of it. |
45
+ | `view_pages` | Up to 5 pages of a PDF, cut out of the uploaded file, as one small PDF the model looks at. |
46
+
47
+ The model finds a document's `document_id` on its card in the prompt, or in the
48
+ [tool guide](#the-tool-guide) for a PDF whose text is in the prompt. How the card, the tools and
49
+ the loop work together is in [How it works](../how-it-works.md).
50
+
51
+ ### Which tools are offered
52
+
53
+ In [askWithFiles(options)](./ask.md#askwithfilesoptions) (and `askGemini`, which runs it):
54
+
55
+ - No tool is offered when every document fits in the prompt and none has pages to look at. The
56
+ question is then one request.
57
+ - `search_document`, `read_document` and `get_document_overview` are offered when at least one
58
+ document is too large for the prompt (`plan.searchable`). They reach only those documents: a
59
+ document whose text is in the prompt is not searched.
60
+ - `analyze_whole_document` is offered with them when all of these hold: the model that explores
61
+ (the explorer, or else the model) has `generateText`, `wholeDocumentAnalysis` is not `false`, and
62
+ at least one searchable document is estimated, from its metadata, to need no more than
63
+ `maxMapChunks` parts (5% leeway).
64
+ - `view_pages` is offered for each PDF whose uploaded file is kept (`keepOriginals` includes
65
+ `"pdf"` and the store keeps originals), when `viewPages` is not `false` and every model of the
66
+ question can be sent a file (`capabilities.toolFiles` is not `"none"`). An OpenAI-compatible
67
+ model needs `pdfInput: true`; Claude with `toolFilePlacement: "none"` turns it off. It is also
68
+ offered for a PDF whose text is in the prompt; when no document is searchable, it is the only
69
+ tool. See [PDFs](../guides/pdfs.md).
70
+
71
+ With an [explorer model](../guides/explorer-model.md), the explorer gets the tools and makes the
72
+ calls; the answering model gets what they returned.
73
+
74
+ Through `files.tools(documents, options)` (a loop of your own, see [`ToolSet`](#toolset)):
75
+
76
+ - The three text tools are declared unless `documents` is empty and there are PDFs to look at.
77
+ With no documents and no PDFs they are still declared, and every call answers that no attached
78
+ file is read with this tool.
79
+ - `analyze_whole_document` is declared when `options.generate` is given and at least one of
80
+ `documents` is estimated within `maxMapChunks` parts (5% leeway). With `generate` and no such
81
+ document it is not declared, but a call of it is still answered, with the reason. Without
82
+ `generate`, pass `wholeDocumentAnalysis: false` to `prepare`: the tool guide then does not name
83
+ it, and the cards do not offer a whole-file read.
84
+ - `view_pages` is declared when `options.viewPages` names at least one PDF whose `originalKept` is
85
+ true and the store has `getOriginal`: `true` means every PDF in `documents`, and a list (such as
86
+ `prepared.viewable`) means exactly those.
87
+
88
+ ## Rules for every tool
89
+
90
+ **Arguments.** Integers may arrive as numbers or as numeric strings (`"12"`); fractions are cut to
91
+ whole numbers; a value that is neither a number nor a numeric string takes the default (an empty or
92
+ blank string counts as 0, so it is clamped to the minimum); line numbers and counts out of range
93
+ are clamped, not refused. Page numbers are the exception: `view_pages` refuses a page that is not a
94
+ number of 1 or more. A `mode` other than `"exact"` or `"regex"` is `"keywords"`, and
95
+ `case_sensitive` is on only when it is `true`.
96
+
97
+ **Scope.** A call reaches only the documents its tool set was made for. A `document_id` outside
98
+ them is refused with the IDs the model may use, so that the next call is right (`view_pages`
99
+ refuses it with the reason instead, see [its errors](#view_pages)). The tool set does not know who
100
+ asks: it compares the owner stored with each document with the `owner` of the metadata it was
101
+ given, and answers a document whose stored owner is set and differs as one that is gone. A
102
+ document stored without an owner is read whatever the metadata holds: as everywhere, it is open to
103
+ anyone who has its ID. Make it from documents you looked up with the user's `owner`, as `prepare`
104
+ and `askWithFiles` do (see [Security](../security.md#tool-scoping)).
105
+
106
+ **Errors.** A call that fails returns `{ "error": "..." }` for the model to read, and the loop goes
107
+ on. It never names a server path: a Node system error becomes "The file could not be read from
108
+ storage (EIO). Try the call again.", and a store that could not be read gives the message of
109
+ [`DocumentStoreError`](./library.md#documentstoreerror), "The document store could not be read
110
+ (CODE). Try again." Errors every tool can return, unless a row names the tools:
111
+
112
+ | Error | When |
113
+ |---|---|
114
+ | `document_id is required.` | `document_id` is missing or blank. |
115
+ | `Unknown document_id ID. Use one of: doc_… ("app.log"), ….` | `search_document`, `read_document`, `get_document_overview`, `analyze_whole_document`: the ID is not one of the tool set's documents. Up to 20 usable IDs are listed, each with its file name, and `…` when there are more. |
116
+ | `Unknown document_id ID. No attached file is read with this tool in this conversation.` | `search_document`, `read_document`, `get_document_overview`, `analyze_whole_document`: the tool set has no document for these tools. |
117
+ | `ID is no longer available on the server. Ask the user to attach the file again.` | The document was deleted or expired after the request was planned. |
118
+ | `Unknown tool “NAME”.` | The name is not a tool of this tool set. The name is cut at 64 characters, never in the middle of a character. Until 0.6.0: `Unknown tool NAME.`, with the whole name. |
119
+
120
+ **Size.** One result is at most `toolResultCharacters` characters of JSON (a field of
121
+ [`Budget`](./library.md#budget): 24,000 with the default budget, less for a model with a small
122
+ window). The answer of `analyze_whole_document` may have up to the larger of that and 40,000.
123
+ `view_pages` returns a short JSON result and is limited in pages and bytes instead. A loop can
124
+ lower the cap of one call with [`ToolCallLimits.maxResultCharacters`](#toolcalllimits), never below
125
+ 600 characters. A result that is too large is cut, and says so:
126
+
127
+ - A list (the matches or passages of a search, the outline of an overview) loses entries from its
128
+ end, keeping at least one, and its `note` becomes "Showing K of N results to stay within the size
129
+ limit. Narrow the query or read specific lines." The note of a search that stopped early is kept
130
+ before it: "The scan stopped early; the total is a lower bound, and the last match in the file is
131
+ not known. Showing K of N results to stay within the size limit. Narrow the query or read
132
+ specific lines."
133
+ - An exact or regex search that read the whole file and has 2 matches or more is cut its own way:
134
+ it loses matches from the end of the first ones, and keeps the last one (see
135
+ [`search_document`](#search_document)).
136
+ - When even one entry is too large, the result becomes
137
+ `{ "truncated": true, "partial": "<the start of the result as JSON text>", "note": "Result cut to the size limit. Ask for a smaller range." }`.
138
+ - `read_document` shortens its range instead, and `analyze_whole_document` cuts the end of its
139
+ answer. See their sections.
140
+
141
+ **Page numbers.** For a PDF whose pages `view_pages` can show in this tool set, search and read
142
+ results also carry page numbers, since a page number is what `view_pages` takes: `page` on a
143
+ matching line, `pages` (`"12"` or `"12-14"`) on a passage and on a read. They come from the
144
+ `--- Page N ---` lines the PDF extractor writes, counting up from 1. Other documents get no page
145
+ fields.
146
+
147
+ ## `search_document`
148
+
149
+ The description the model sees:
150
+
151
+ > Search a large attached file. mode "keywords" returns the most relevant passages for a question;
152
+ > "exact" finds the lines that contain the text; "regex" finds the lines that match a JavaScript
153
+ > regular expression. For exact and regex, total_matching_lines counts every matching line, and the
154
+ > result shows the first max_results of them and the last one. Results include line numbers to read
155
+ > further with read_document.
156
+
157
+ Until 0.6.0 it said that `exact` "returns every line containing the text", while the result showed
158
+ the first lines only: a model asked when something last happened named the last line it was shown.
159
+
160
+ | Argument | Type | Required | Default and limits | Meaning |
161
+ |---|---|---|---|---|
162
+ | `document_id` | string | yes | | The `document_id` from the file's card. |
163
+ | `query` | string | yes | Not blank (`query is required.`) | Keywords, exact text, or a regex, by `mode`. |
164
+ | `mode` | `"keywords"` \| `"exact"` \| `"regex"` | no | `"keywords"` | How to search. |
165
+ | `max_results` | integer | no | keywords: 5, from 1 to 10. exact and regex: 20, from 1 to 50 | Passages, or matching lines, returned. It does not limit the count. exact and regex also show the last matching line after them, when it is not among them. |
166
+ | `context_lines` | integer | no | 0, from 0 to 5 | exact and regex: lines shown before and after each match. |
167
+ | `case_sensitive` | boolean | no | `false` | exact and regex: match case. Keywords never do. |
168
+
169
+ **`keywords`** ranks passages with BM25, computed at query time from substring hits: no index, any
170
+ language.
171
+
172
+ - The query is lowercased and split at anything that is not a letter, a digit or `_`. Terms of
173
+ fewer than 2 characters and common English and Hebrew words are dropped; at most 12 distinct
174
+ terms are kept. A term also matches inside longer words: "timeout" matches "timeouts".
175
+ - A passage is a run of whole lines of about 1,500 characters, or 40 lines at most. A passage that
176
+ contains the whole query as a phrase (more than one term, up to 200 characters) is ranked higher.
177
+ - Passages come best first. `score` is rounded to two decimals and only orders the results.
178
+ - A query with no usable term, or with no hit, returns no passage and the note "No passage contains
179
+ these keywords. Try other words, synonyms, or exact mode."
180
+
181
+ **`exact`** finds every line that contains the text. A line counts once, however many times it
182
+ contains the text. A text with a line break matches across lines and counts on the line where it
183
+ starts. The scan stops after 1,000,000 matching lines.
184
+
185
+ **`regex`** tests a JavaScript regular expression against each line on its own, so a match cannot
186
+ span lines. It runs with the `i` flag unless `case_sensitive` is `true`, and with the `u` flag when
187
+ the pattern is valid with it (so `\p{L}` means a letter); a pattern valid only without it, such as
188
+ `[\w-.]`, runs without it. Limits:
189
+
190
+ | Limit | Value | When it is reached |
191
+ |---|---|---|
192
+ | Pattern length | 300 characters | Refused: `Regex is longer than 300 characters.` |
193
+ | Nested quantifier, such as `(a+)+` | Refused up front | `Regex has a nested quantifier like (a+)+, which can hang on large files. Simplify it.` |
194
+ | Invalid pattern | | `Invalid regex: ` and the engine's message. |
195
+ | One search | 3,000 ms of matching, or what is left of the tool set's time when that is less | The scan stops; the result has the lines found so far and the note below. |
196
+ | A line the pattern cannot get past | Two whole slices of 250 ms on the same line | The scan stops there, the same way. |
197
+ | All regex searches of one tool set | [`REGEX_BUDGET_MS`](#regex_budget_ms), 6,000 ms | Each later regex search fails: `The time for regex searches is used up for this answer. Search with mode "exact" or "keywords" instead.` |
198
+
199
+ A regex scan runs in slices of 250 ms with other work of the server in between, and the regex
200
+ searches of one tool set run one after another, even when the calls of a turn run together. See
201
+ [Security](../security.md) for why.
202
+
203
+ Results of `exact` and `regex`:
204
+
205
+ | Field | Type | Meaning |
206
+ |---|---|---|
207
+ | `document` | string | The file name. |
208
+ | `mode` | `"exact"` \| `"regex"` | The mode that ran. |
209
+ | `total_matching_lines` | number | Every matching line in the file, not only those shown. This is the number to count with. |
210
+ | `note` | string, optional | When more lines match than are shown: "N of the M matching lines are shown: the first K and the last (line L). To see the ones in between, narrow the search." ("the first and the last" when K is 1). When the scan stopped (1,000,000 lines, or a regex limit): "The scan stopped early; the total is a lower bound, and the last match in the file is not known." Or a size-limit note (below). Absent when every match is shown. |
211
+ | `matches` | array | The first `max_results` matching lines, in file order, then the last matching line of the file when it is not among them. A scan that stopped early shows no last line, since it did not reach the end. |
212
+ | `matches[].line` | number | The line number. |
213
+ | `matches[].page` | number, optional | The page of the line, for a PDF whose pages can be shown. |
214
+ | `matches[].text` | string | The line. A line longer than 400 characters is cut to 400 around the match, with `…` where it was cut. |
215
+ | `matches[].before`, `matches[].after` | string[], optional | With `context_lines` above 0: the lines around the match, as `"1202\| text"`, each cut to 400 characters. |
216
+
217
+ A search with `max_results: 1` and `context_lines: 1`:
218
+
219
+ ```json
220
+ {
221
+ "document": "app.log",
222
+ "mode": "exact",
223
+ "total_matching_lines": 51,
224
+ "note": "2 of the 51 matching lines are shown: the first and the last (line 4987). To see the ones in between, narrow the search.",
225
+ "matches": [
226
+ {
227
+ "line": 1203,
228
+ "text": "2026-05-01 12:00:03 ERROR payment-service: timeout after 1203ms calling ledger",
229
+ "before": ["1202| 2026-05-01 12:00:02 INFO request 1202 ok"],
230
+ "after": ["1204| 2026-05-01 12:00:04 INFO request 1204 ok"]
231
+ },
232
+ {
233
+ "line": 4987,
234
+ "text": "2026-05-01 13:22:47 ERROR payment-service: timeout after 4987ms calling ledger",
235
+ "before": ["4986| 2026-05-01 13:22:46 INFO request 4986 ok"],
236
+ "after": ["4988| 2026-05-01 13:22:48 INFO request 4988 ok"]
237
+ }
238
+ ]
239
+ }
240
+ ```
241
+
242
+ When the result is too large for its room, an exact or regex search that read the whole file and
243
+ has 2 matches or more loses matches from the end of the first ones, and keeps the last one. Its
244
+ note is then one of:
245
+
246
+ - "Showing N of the M matching lines to stay within the size limit: the first K and the last (line
247
+ L). Narrow the query or read specific lines." (N is K + 1; "the first and the last" when K is 1);
248
+ - "Showing 1 of the M matching lines to stay within the size limit: the last (line L). Narrow the
249
+ query or read specific lines.", when only the last one fits;
250
+ - "Showing 1 of the M matching lines: the last (line L). Narrow the search.", when the last one
251
+ fits only with this shorter note.
252
+
253
+ When not even that fits, the result is cut as text, as any other (see
254
+ [Size](#rules-for-every-tool)), and its `partial` holds the note before the match. A note that starts with
255
+ "Showing " marks a result that was cut: a call made again runs again. A result with the note "N of
256
+ the M matching lines are shown" is whole, and a call made again gets a pointer to it.
257
+
258
+ Results of `keywords`:
259
+
260
+ | Field | Type | Meaning |
261
+ |---|---|---|
262
+ | `document` | string | The file name. |
263
+ | `mode` | `"keywords"` | |
264
+ | `passages` | array | The best passages, best first. |
265
+ | `passages[].lines` | string | `"412-436"`: the passage's first and last line. |
266
+ | `passages[].pages` | string, optional | `"37"` or `"37-38"`, for a PDF whose pages can be shown. |
267
+ | `passages[].score` | number | The BM25 score, rounded to two decimals. |
268
+ | `passages[].text` | string | The passage's lines, numbered (`"412\| text"`), one a line. |
269
+ | `note` | string, optional | The no-passage note, or the size-limit note. |
270
+
271
+ ## `read_document`
272
+
273
+ The description the model sees:
274
+
275
+ > Read a range of lines from a large attached file, with line numbers. Up to 600 lines per call;
276
+ > long results are cut and tell you where to continue.
277
+
278
+ | Argument | Type | Required | Default and limits | Meaning |
279
+ |---|---|---|---|---|
280
+ | `document_id` | string | yes | | The document to read. |
281
+ | `start_line` | integer | yes | Clamped to 1 through the last line; 1 when it is missing | First line to read, 1-based. |
282
+ | `end_line` | integer | no | `start_line + 199`; clamped to `start_line` through `start_line + 599` and the last line | Last line to read. |
283
+
284
+ The numbered text must fit in the cap less 500 characters, as JSON. When it does not, the range is
285
+ shortened (to 70% of its length, step by step) until it fits, and `next_start_line` says where to
286
+ go on. When one line alone is longer than that, its text is cut to half of that room and
287
+ `text_cut` is `true`.
288
+
289
+ | Field | Type | Meaning |
290
+ |---|---|---|
291
+ | `document` | string | The file name. |
292
+ | `lines` | string | `"1200-1399"`: the lines shown, which may be fewer than asked. |
293
+ | `pages` | string, optional | The pages those lines are on, for a PDF whose pages can be shown. |
294
+ | `total_lines` | number | The lines of the whole file. |
295
+ | `text` | string | The lines, numbered (`"1200\| text"`), one a line. |
296
+ | `text_cut` | `true`, optional | The one line shown was cut: its end is missing. |
297
+ | `next_start_line` | number, optional | The first line not shown, when the file goes on. |
298
+ | `note` | `"End of file."`, optional | Instead of `next_start_line`, when the last line shown is the file's last. |
299
+
300
+ ```json
301
+ { "document": "app.log", "lines": "1200-1399", "total_lines": 5000, "text": "1200| ...\n1201| ...", "next_start_line": 1400 }
302
+ ```
303
+
304
+ ## `get_document_overview`
305
+
306
+ The description the model sees:
307
+
308
+ > Get the full outline (headings with line numbers), log profile (levels, time range, most
309
+ > frequent errors), and the first and last lines of a large attached file.
310
+
311
+ | Argument | Type | Required | Meaning |
312
+ |---|---|---|---|
313
+ | `document_id` | string | yes | The document. |
314
+
315
+ | Field | Type | Meaning |
316
+ |---|---|---|
317
+ | `document` | string | The file name. |
318
+ | `format` | string | The [`DocumentFormat`](./library.md#documentformat): `"log"`, `"pdf"`, `"csv"`, and so on. |
319
+ | `size` | string | The size of the uploaded file: `"512 B"`, `"340 KB"`, `"61.2 MB"`. |
320
+ | `lines` | number | The lines of the extracted text. |
321
+ | `estimated_tokens` | number | The library's token estimate of the text. |
322
+ | `pages` | number, optional | The page count of a PDF, or the slide count of a PPTX. |
323
+ | `parts_for_whole_document_analysis` | number | About how many parts a whole-file read would take, estimated from the metadata, to within a part or two. The read itself counts them. |
324
+ | `whole_document_analysis` | string, optional | "Not available for this file: it would take about N parts, and the limit is M. Use search_document and read_document." when the estimate is above `maxMapChunks`. |
325
+ | `log_profile` | [`LogProfile`](./library.md#logprofile), optional | For a log: the count of each level, the first and last timestamps, and up to 15 problems (WARN, ERROR and FATAL message shapes: `template`, `level`, `count`, `firstLine`), FATAL first, then ERROR, then WARN, the most frequent first within each. |
326
+ | `first_lines` | string | The first 30 lines, numbered. |
327
+ | `last_lines` | string | The last 20 lines, numbered; `""` when the file has 30 lines or fewer. |
328
+ | `outline` | string[] | One entry a heading: `"L12 Title"`, with two more spaces before the title for each level below the shallowest heading (`"L40 Install"`). It is the outline stored at ingest: at most 400 headings. When a file has more, the outline keeps its top-level headings alone if there are 20 or more of them, and all its headings otherwise. With 20 to 400 top-level headings, each one is kept once, in order. More than 400 are cut to 400, taken at even steps across the file (see [`OutlineEntry`](./library.md#outlineentry)). Cut from its end to fit the cap. |
329
+
330
+ ## `analyze_whole_document`
331
+
332
+ The description the model sees:
333
+
334
+ > Read an entire large file in parts and answer a task that needs all of it, such as a full
335
+ > summary, a timeline, or items that must be judged by meaning. To count or list lines that
336
+ > contain a word, an ID or a pattern, use search_document in exact or regex mode instead: its
337
+ > count is exact, and this can miss items. Slow and costly: prefer search_document and
338
+ > read_document for specific questions.
339
+
340
+ | Argument | Type | Required | Meaning |
341
+ |---|---|---|---|
342
+ | `document_id` | string | yes | The document. |
343
+ | `task` | string | yes | What to find or produce from the whole file, stated completely. Not blank (`task is required.`). |
344
+
345
+ The file is split into parts of up to `mapChunkTokens` tokens (and 80% of `maxRequestBytes`), 4 are
346
+ read at a time with the `generate` function of the tool set, their notes are merged, and one answer
347
+ is written from them. A part the model refuses as too large is read as two halves, while
348
+ `maxMapChunks` and [`ToolCallLimits.maxRequests`](#toolcalllimits) allow it. The steps, output
349
+ limits and retries are in [How it works](../how-it-works.md); what a read costs is in
350
+ [Costs and limits](../guides/costs-and-limits.md).
351
+
352
+ Each document may be read whole [`MAX_WHOLE_DOCUMENT_READS`](#max_whole_document_reads) times (1)
353
+ by one tool set, which is one question in `askWithFiles`. Set it with `limits.wholeDocumentReads`
354
+ in [`AskLimits`](./ask.md#asklimits), or `maxWholeDocumentReads` in
355
+ [`ToolOptions`](./library.md#tooloptions). A read is counted when it starts, so two calls in one
356
+ turn do not both pass.
357
+
358
+ | Field | Type | Meaning |
359
+ |---|---|---|
360
+ | `document` | string | The file name. |
361
+ | `parts_read` | number | The parts the file was read in, those that could not be read included; a part read as two halves counts as two. |
362
+ | `parts_with_relevant_content` | number | The parts that were read and held something for the task. |
363
+ | `parts_that_failed` | number, optional | Parts that could not be read. The notes name each one: "[This part could not be read: reason]". |
364
+ | `notes_cut_short` | number, optional | Notes of parts, and merges of notes, that stopped at the output limit or were cut off by the provider. |
365
+ | `answer_cut_short` | `true`, optional | The final answer stopped at its output limit. |
366
+ | `notes_only` | `true`, optional | The last step, which writes one answer from the notes, failed: `answer` is the notes of the parts, with their line citations. |
367
+ | `note` | string, optional | With `notes_only`: "The last step of this read, which writes one answer from the notes of the parts, failed (REASON). The answer is those notes: answer from them.", plus "Some of them were cut off at the output limit, so they are incomplete: tell the user." when some were. Otherwise, when notes or the answer were cut short: "Incomplete: the model's output limit was reached, so some relevant items are missing from this answer. Tell the user it is incomplete. For a complete list or an exact count, use search_document in exact or regex mode (it returns total_matching_lines), or ask about a narrower part of the file." |
368
+ | `answer` | string | The answer. When no part held anything relevant: "No part of NAME contained anything relevant to: TASK", with the count of parts that could not be read, if any. |
369
+ | `answer_shortened` | string, optional | "The rest of this answer did not fit in the room left in this conversation." The answer was cut at its end, which then reads `…`. |
370
+
371
+ ```json
372
+ { "document": "novel.txt", "parts_read": 4, "parts_with_relevant_content": 3, "answer": "Ada appears first in chapter 2 (L412) ..." }
373
+ ```
374
+
375
+ Errors:
376
+
377
+ | Error | When | Counted as a read |
378
+ |---|---|---|
379
+ | `NAME was already read whole for this question, and is not read whole again. Use the answer of that read, or search_document and read_document for the details.` | The document was read whole as often as it may be (" N times" is added when that is more than 1). | no |
380
+ | `Whole-file reads are turned off for this question. Use search_document and read_document on NAME.` | `maxWholeDocumentReads` (or `limits.wholeDocumentReads`) is 0. | no |
381
+ | `The whole-file read of NAME failed earlier in this question (REASON), and is not tried again. Use search_document and read_document.` | An earlier read of it could read no part. | no |
382
+ | `Reading all of NAME needs N model calls, over the limit of M. Use search_document to narrow the question first.` | The read counted more parts than `maxMapChunks`. Nothing was sent. | no |
383
+ | `Could not read any part of NAME: REASON` | Every part failed at the model. | yes |
384
+ | The store's error | No part could be read from the store. Nothing was sent. | no |
385
+
386
+ REASON, in these errors, in the notes of a part that could not be read, and in the note of
387
+ `notes_only`, says why a model request failed. Since 0.6.0 it is built from the error's kind, its
388
+ HTTP status or its connection code, never from its message, which can name a project, a host, a
389
+ key or a URL. It is one of:
390
+
391
+ | REASON | For an error |
392
+ |---|---|
393
+ | `The request was larger than the model takes (HTTP 400).` | of kind `context_overflow` |
394
+ | `The model's quota has run out (HTTP 429).` | of kind `quota` |
395
+ | `The model was busy (HTTP 429).` | of kind `rate_limit` |
396
+ | `The model took too long to answer.` | of kind `timeout`; named `TimeoutError`, on the error or its cause (an `AbortSignal.timeout`, or a built-in part reader past its `timeoutMs`); or with undici's code `UND_ERR_HEADERS_TIMEOUT` or `UND_ERR_BODY_TIMEOUT` |
397
+ | `The model could not be reached.` | of kind `unreachable`; or whose code, or that of a cause up to 3 levels down, is that of a connection that failed: `ECONNREFUSED`, `ECONNRESET`, `ECONNABORTED`, `ENOTFOUND`, `EAI_AGAIN`, `ETIMEDOUT`, `EHOSTUNREACH`, `ENETUNREACH`, `ENETDOWN`, `EPIPE`, `UND_ERR_CONNECT_TIMEOUT`, `UND_ERR_SOCKET`, `UND_ERR_CLOSED`, `UND_ERR_DESTROYED` |
398
+ | `The model failed on its side (HTTP 503).` | of kind `server` |
399
+ | `The model refused the key or token it was sent (HTTP 401).` | of kind `auth` |
400
+ | `The model refused the request (HTTP 400).` | of kind `invalid` |
401
+ | `The model's reply could not be read (HTTP 200).` | of kind `invalid` with a status from 200 to 299: a reply that was not JSON, or a streamed event too long |
402
+ | `The model returned no text (SAFETY).` or `The model returned no text.` | the error a built-in part reader throws for a reply with no text. The provider's reason is given only when it is a plain word (letters and `_`, up to 40). |
403
+ | `The model request failed.` | any other: a plain `Error` or a string thrown by a `generate` of your own, an error whose fields throw when read. `The model request failed (HTTP 302).` for a status from 100 to 399. |
404
+
405
+ The status in brackets is there when the error has one: its `status`, else `statusCode`, else
406
+ `response.status`, as the errors of provider SDKs, got and axios carry it, when that is a whole
407
+ number from 100 to 599, or 0 (which is not shown). An error with a status and no `kind` has its kind
408
+ told from the status and its message, as [`classifyModelError`](./errors-and-retries.md#classifymodelerrorstatus-message-signals)
409
+ does. A failure to read a part's lines from the store is told as every tool tells a store's error
410
+ ([Rules for every tool](#rules-for-every-tool)):
411
+ `[This part could not be read: The document store could not be read (EIO). Try again.]`. Until
412
+ 0.6.0, REASON was the error's own message.
413
+
414
+ ## `view_pages`
415
+
416
+ The description the model sees:
417
+
418
+ > Look at pages of an attached PDF as they are printed. Use it when the answer depends on
419
+ > something the text of the file cannot show: a picture, photo, chart, diagram, map, handwriting,
420
+ > a stamp or signature, or how a page is laid out. It is not for reading text. Up to 5 pages per
421
+ > call.
422
+
423
+ | Argument | Type | Required | Default and limits | Meaning |
424
+ |---|---|---|---|---|
425
+ | `document_id` | string | yes | | The `document_id` of the PDF. |
426
+ | `from_page` | integer | yes | 1 or more; not clamped | First page, 1-based: the N of the `--- Page N ---` lines in the text. |
427
+ | `to_page` | integer | no | `from_page`. A page past the end is taken as the last page | Last page. One call shows at most [`MAX_VIEW_PAGES`](#max_view_pages) (5) pages, fewer when the call's `maxPages` is lower. |
428
+
429
+ The pages are cut out of the kept original into one small PDF, and returned as a file next to a
430
+ short JSON result. Only [`ToolSet.executeWithFiles`](#toolset) returns the file; `execute` answers
431
+ with an error. Pages are left off the end until the file fits the call's `maxFileBytes`. Cutting
432
+ needs the optional dependency `@cantoo/pdf-lib`. How pages are cut and counted, and what they cost,
433
+ is in [PDFs](../guides/pdfs.md).
434
+
435
+ | Field | Type | Meaning |
436
+ |---|---|---|
437
+ | `document` | string | The file name. |
438
+ | `pages` | string | The pages shown: `"12"` or `"12-14"`. |
439
+ | `total_pages` | number | The pages of the PDF. |
440
+ | `file` | string | The name of the file returned with the result: `"pages-12-14.pdf"`. |
441
+ | `next_page` | number, optional | The first page asked for and not shown, when it can still be looked at. |
442
+ | `note` | string, optional | Why fewer pages were shown than asked (see below). |
443
+
444
+ When fewer pages were shown than asked, the note is one of:
445
+
446
+ - "Showing S of the W pages asked for: the others did not fit in this request. Call view_pages from
447
+ page N if you need them." (with `next_page`)
448
+ - "Showing S of the W pages asked for: one call shows at most 5. Call view_pages from page N if you
449
+ need them." (with `next_page`)
450
+ - "Showing S of the W pages asked for: no more pages can be looked at for this question." (no
451
+ `next_page`: the call's `maxPages` was the limit)
452
+
453
+ The file is `{ name: "pages-12-14.pdf", mimeType: "application/pdf", bytes }` (a
454
+ [`ToolFile`](#toolfile)).
455
+
456
+ ```json
457
+ { "document": "report.pdf", "pages": "2-3", "total_pages": 6, "file": "pages-2-3.pdf" }
458
+ ```
459
+
460
+ Errors, besides those of [every tool](#rules-for-every-tool):
461
+
462
+ | Error | When |
463
+ |---|---|
464
+ | `Unknown document_id ID. Use the document_id of an attached PDF.` | The ID is not a PDF this tool set can show. |
465
+ | `The pages of NAME cannot be shown: only its text was kept. Answer from the text.` | A document the text tools can read whose pages cannot be shown: not a PDF, or its original is not kept. |
466
+ | `from_page must be a page number: 1 or higher.` (or `to_page`) | Not a number, or below 1. |
467
+ | `to_page (T) is before from_page (F).` | |
468
+ | `NAME has N pages. There is no page F.` | `from_page` is past the last page. |
469
+ | `No more pages can be looked at for this question. Answer from the pages and the text you already have.` | The call's `maxPages` is below 1. |
470
+ | `There is no room left in this request to show more pages. Answer from the pages and the text you already have.` | The call's `maxFileBytes` is below 1,024. |
471
+ | `The original file of NAME is no longer on the server, so its pages cannot be shown. Answer from the text.` | The store no longer has the original. |
472
+ | `NAME: Page F is 2.1 MB as a file, more than the 1.5 MB that fit in this request.` | The first page alone does not fit `maxFileBytes`. |
473
+ | `NAME: ` and the reason | The file cannot be cut: it needs a password, is damaged, declares too many objects to cut in memory, has another page count than its text, has no page `from_page` (when its page count was not recorded), or `@cantoo/pdf-lib` is not installed. |
474
+ | `The pages could not be shown: this application does not pass files from tools to the model. Answer from the text.` | The call was run with `execute`, which has no place for a file. |
475
+
476
+ ## The tool guide
477
+
478
+ When any document is searchable or has pages to look at, the planned request carries a tool guide
479
+ for the system instruction (`PreparedContext.instruction`; `askWithFiles` adds it, and a loop of
480
+ your own adds it to its system prompt). In short, it tells the model:
481
+
482
+ - which files are too large for its context, by name (quoted, so a name cannot read as an
483
+ instruction) and `document_id`, and that it sees only a card of each;
484
+ - what each text tool is for, and this rule: "To count or list what can be matched as text (a word,
485
+ an ID, an error code, a log level, a pattern), use search_document in exact or regex mode: its
486
+ total_matching_lines is exact.";
487
+ - to read around search hits before relying on them;
488
+ - to use `analyze_whole_document` only when the task needs all of the file and cannot be done by
489
+ matching text (a full summary, a timeline, items judged by meaning), and that it is slow, costly,
490
+ and can miss items of a long list. This line is left out when `prepare` gets
491
+ `wholeDocumentAnalysis: false` (`askWithFiles` passes it when its own `wholeDocumentAnalysis` is
492
+ `false` or the model that explores has no `generateText`), or when no searchable file can be read
493
+ whole;
494
+ - that its tool turns are limited: call several tools in one turn when they do not depend on each
495
+ other, and answer as soon as it has enough evidence;
496
+ - to base the answer on text it read, cite line numbers like `(app.log L1203)`, and say so when the
497
+ tools did not find something.
498
+
499
+ For PDFs whose pages can be shown, it names each one with its `document_id` and page count, and
500
+ says to use `view_pages` when the answer depends on a picture, chart, diagram, map, handwriting, a
501
+ stamp or signature, or the layout of a page; that a page is worth a look when its text says it has
502
+ a picture, has no text, or mentions a figure; that page numbers are the N of the `--- Page N ---`
503
+ lines; not to read text with it; and not to describe a picture it has not looked at.
504
+
505
+ The counting rule is also in the description of `analyze_whole_document`, and in the note of a
506
+ whole-file read that came out incomplete.
507
+
508
+ ## What `askWithFiles` adds to results
509
+
510
+ The tools above answer one call. The loop of [askWithFiles(options)](./ask.md#askwithfilesoptions)
511
+ adds to their results, and answers some calls without running them. A loop of your own does none
512
+ of this unless you write it.
513
+
514
+ - **`tool_turns_left`.** Every result the loop sends has this field when it is first sent: the tool
515
+ turns left after this one, or 0 when the request has no room left. A stand-in that later
516
+ replaces the result, and the stand-in kept in `toolTurns` for a look at pages, do not have it.
517
+ `toolTurns` keep it, but the rounds of an earlier question passed back in `messages` are sent
518
+ without it, since it counted the turns of their own question (since 0.6.0). `geminiToolTurns`,
519
+ `openAiToolTurns` and `anthropicToolTurns` leave it out too.
520
+ - **A call made again.** A call whose result is still in the conversation in full (the same
521
+ search with the same arguments as the tool reads them, the same overview, the same read, or a
522
+ read of lines inside a read shown in full), in this question or in the tool rounds of an earlier
523
+ one passed back in `messages`, is not run (new in 0.6.0). Its result is a pointer, and its step
524
+ ends " — already shown above":
525
+ - `{ "document": "app.log", "already_shown": true, "note": "Not run: this exact call was answered earlier in this conversation, and its result is still shown above in full. The file has not changed, so it would return the same. Use that result. For more, read other lines, or search with other words or another mode." }`
526
+ - For a read inside an earlier read: `{ "document": "app.log", "lines": "150-200", "already_shown": true, "note": "Not run: lines 150-200 are already shown above in full, in the result that has lines 100-299 of this file, and the file has not changed. Use them. To see more, read other lines." }`
527
+ - For the same call twice in one turn: `{ "already_shown": true, "note": "Not run: call 1 of this turn is the same call, and its result is next to this one. Use it." }`
528
+
529
+ A result of an earlier turn that failed, was cut (`truncated`, `text_cut`, a note that starts
530
+ "Showing "), came from a search that stopped early, or is itself a pointer or a stand-in is never
531
+ pointed to: the call runs, and may get more. A search whose note only says how many of its
532
+ matches are shown ("21 of the 442 matching lines are shown: …") was not cut, and is pointed to.
533
+ The same call made twice in one turn gets the pointer to the first whatever the first returns (an
534
+ error, a cut result, a pointer); only when the first is refused for lack of room is the second
535
+ refused the same way. Whole-file reads and looks at pages are never pointed to.
536
+
537
+ Some calls run again all the same:
538
+ - every call, with a model that declares
539
+ [`clearsToolResults`](./ask.md#modelcapabilities) (Claude with `clear_tool_uses` or compaction
540
+ in its `body`), which may no longer have the earlier result; the same call twice in one turn
541
+ runs twice too;
542
+ - a read of one line from the tool rounds of an earlier question: 0.5.0 cut the text of such a
543
+ read without saying so (no `text_cut`), and the stored rounds do not tell which version wrote
544
+ them;
545
+ - an exact or regex search that 0.5.0 stored: fewer `matches` than `total_matching_lines`, and
546
+ no note. Run now, it shows the last match too.
547
+ - **Stand-ins.** When the request runs short of room, the results of older tool rounds are replaced
548
+ by the short stand-ins of [`stubResult`](./ask.md#stubresultcall-result-hadfiles), with
549
+ `"dropped": true`; when and how is in [How it works](../how-it-works.md), and nothing is replaced
550
+ when any model of the question is append-only (Claude). A pointer whose result was replaced
551
+ becomes
552
+ `{ "document": "app.log", "dropped": true, "note": "Not run then: it repeated an earlier call whose result was later dropped from the conversation to make room. Call it again if you need it." }`.
553
+ So does every pointer of a stored round when a model of the question declares
554
+ `clearsToolResults`. In `toolTurns`, the result of a look at pages is kept as its stand-in,
555
+ since the file is not kept.
556
+ - **A hint after two failed searches.** When two `search_document` calls in a row fail in the
557
+ same mode, the error of the second (and of any after it) ends with a hint. For `regex`: "Two
558
+ regex searches in a row failed. Try mode "exact" with a plain word or ID from the file, or mode
559
+ "keywords"." For the other modes: "This search failed twice in a row. Check the arguments against
560
+ the tool's description, or answer from what you have." A call of another tool, or a search that
561
+ works, starts the count again.
562
+ - **A share of the room.** Before the calls of a turn run, the room left in the request is shared
563
+ among those that run and return text, and each gets its share as `maxResultCharacters`. A
564
+ whole-file read is the exception: its answer is not cut up front; once the other results of the
565
+ turn are in, it is cut to the room they left. A look at pages is not in the share: it gets
566
+ `maxFileBytes` and `maxPages` instead (see [`ToolCallLimits`](#toolcalllimits)). How the room
567
+ is shared is in [How it works](../how-it-works.md#room-in-the-request).
568
+ - **Calls that are not run**, each answered with an `error`:
569
+ - past `limits.callsPerTurn` (8): "Not run: one turn runs at most 8 tool calls. Send this call
570
+ again if you still need it.";
571
+ - when there is not enough room left for the call: "Not run: there is no room left in this
572
+ conversation for another tool result. Answer now, from what the tools returned so far.";
573
+ - a call whose arguments did not arrive whole (`ToolCall.problem`, set by the adapter), such as
574
+ "The arguments of this call were not valid JSON, and it was not run: … Send the call again.",
575
+ which quotes up to 300 characters of the arguments, never cut in the middle of a character;
576
+ - a whole-file read that would pass `limits.inputTokens` or `limits.requests`: "Not run: reading
577
+ all of NAME takes about N input tokens, and M are left of the L this question may use. Use
578
+ search_document and read_document." (or "model requests ... this question may make").
579
+ - **Steps.** Each call that runs starts an `onActivity` line, its `describe()` label and `…`.
580
+ Each call up to `callsPerTurn` ends with a step, in `onStep` and `steps`: the label and
581
+ [toolResultSummary(label, result)](#toolresultsummarylabel-result), or the label and
582
+ " — already shown above" for a pointer. The calls past it share one step: "N more tool calls in
583
+ this turn were not run (at most 8 a turn)", or "1 more tool call in this turn was not run (at
584
+ most 8 a turn)" for one. A call of a tool that does not exist has the label `Call “NAME”`, the
585
+ name cut at 64 characters, and the step `Call “do_magic” — failed: Unknown tool “do_magic”.`;
586
+ until 0.6.0 the label was the name itself. Labels and steps are one line of plain text: a line
587
+ break or a control character the model sent becomes a space, the invisible characters that file
588
+ text loses are dropped, and `](` becomes `] (` (see [`AskResult`](./ask.md#askresult)). See
589
+ [Web app](../guides/web-app.md) for showing them.
590
+
591
+ The regex time of a question is always [`REGEX_BUDGET_MS`](#regex_budget_ms) in `askWithFiles`: it
592
+ has no option for it.
593
+
594
+ ## Exports
595
+
596
+ ### `TOOL_NAMES`
597
+
598
+ The names of the five tools, as constants.
599
+
600
+ ```ts
601
+ const TOOL_NAMES = {
602
+ search: "search_document",
603
+ read: "read_document",
604
+ overview: "get_document_overview",
605
+ analyze: "analyze_whole_document",
606
+ view: "view_pages",
607
+ } as const;
608
+ ```
609
+
610
+ Compare a `ToolCall.name` with these rather than with string literals. See
611
+ [Your own adapter and loop](../guides/own-adapter-and-loop.md).
612
+
613
+ ### `MAX_VIEW_PAGES`
614
+
615
+ `5`. The most pages one `view_pages` call shows. [`ToolCallLimits.maxPages`](#toolcalllimits)
616
+ can only lower it. See [PDFs](../guides/pdfs.md).
617
+
618
+ ### `MAX_WHOLE_DOCUMENT_READS`
619
+
620
+ `1`. How many times one tool set reads each document whole, unless `maxWholeDocumentReads` in
621
+ [`ToolOptions`](./library.md#tooloptions) (or `limits.wholeDocumentReads` in
622
+ [`AskLimits`](./ask.md#asklimits)) says otherwise. One read of a large file is up to
623
+ `maxMapChunks` part requests, plus the requests that merge their notes and the one that writes its
624
+ answer. See [Costs and limits](../guides/costs-and-limits.md).
625
+
626
+ ### `REGEX_BUDGET_MS`
627
+
628
+ `6_000`. The milliseconds the regex searches of one tool set may take together, unless
629
+ `regexBudgetMs` in [`ToolOptions`](./library.md#tooloptions) says otherwise. One search still stops
630
+ after 3,000 ms of matching, and after two 250 ms slices that cannot get past the same line (see
631
+ [the regex limits](#search_document)). See [Security](../security.md).
632
+
633
+ ### toolResultSummary(label, result)
634
+
635
+ `toolResultSummary(label: string, result: ToolResult): string`
636
+
637
+ What a finished call found, as a suffix for its `describe()` label in a list of steps. It never
638
+ throws.
639
+
640
+ | The result has | The suffix |
641
+ |---|---|
642
+ | `error` | ` — failed:` and the error, as in ` — failed: Unknown tool “do_magic”.` |
643
+ | `total_matching_lines` (exact, regex) | ` — 1,203 matching lines` (numbers in en-US form), ` — 1 matching line` for one |
644
+ | `passages` (keywords) | ` — 5 passages`, ` — 1 passage` for one |
645
+ | `parts_read` (whole-file read) | ` — 9 parts, 3 relevant` (` — 1 part, 1 relevant` for one), then `, notes only` with `notes_only`, or `, incomplete` with `notes_cut_short` or `answer_cut_short` |
646
+ | `lines` and `total_lines` (read) | ` — got 1200-1342` when the label does not end with the lines shown, else `""` |
647
+ | `pages` and `total_pages` (view_pages) | ` — got page 2` or ` — got pages 2-3` when the label does not end with the pages shown, else `""` |
648
+ | anything else (an overview, a cut result) | `""` |
649
+
650
+ ```ts
651
+ import { toolResultSummary } from "llm-large-files";
652
+
653
+ const label = "Search app.log (exact) for “timeout”";
654
+ const step = label + toolResultSummary(label, { document: "app.log", mode: "exact", total_matching_lines: 1203, matches: [] });
655
+ // "Search app.log (exact) for “timeout” — 1,203 matching lines"
656
+ ```
657
+
658
+ Until 0.6.0 a count of one was plural too (` — 1 matching lines`). `askWithFiles` makes its steps
659
+ this way, and then makes each one line of plain text. See [Web app](../guides/web-app.md).
660
+
661
+ ### `ToolSet`
662
+
663
+ The tools of one question, scoped to a set of documents. You get one from `files.tools(documents,
664
+ options)` (see [`LargeFiles`](./library.md#largefiles) and [`ToolOptions`](./library.md#tooloptions));
665
+ `askWithFiles` makes one per question. Make one per question in your own loop too: the regex time
666
+ and the whole-file reads are counted per tool set.
667
+
668
+ ```ts
669
+ type ToolSet = {
670
+ declarations: ToolDeclaration[];
671
+ has(name: string): boolean;
672
+ execute(name: string, args: Record<string, unknown>): Promise<ToolResult>;
673
+ executeWithFiles(name: string, args: Record<string, unknown>, limits?: ToolCallLimits, hooks?: ToolCallHooks): Promise<ToolOutput>;
674
+ describe(name: string, args: Record<string, unknown>): string;
675
+ resultCharacters(name: string): number;
676
+ };
677
+ ```
678
+
679
+ | Member | What it does |
680
+ |---|---|
681
+ | `declarations` | The tools to declare to the model, in this order: `search_document`, `read_document`, `get_document_overview`, `analyze_whole_document`, `view_pages`, those that are [offered](#which-tools-are-offered). |
682
+ | `has(name)` | `true` for each declared tool. Also `true` for `analyze_whole_document` when `generate` was given and the text tools are declared, even if it is not declared because no document is small enough: a call then gets the reason. Use it to tell the calls of this tool set from others. |
683
+ | `execute(name, args)` | Runs a call and returns its JSON result, within the tool's own cap. Failures come back as `{ error }`, as listed above. `view_pages` answers with an error here: it returns a file. |
684
+ | `executeWithFiles(name, args, limits?, hooks?)` | Runs any call with [`ToolCallLimits`](#toolcalllimits), and returns the result with the files it produced (`files` is empty for every tool but `view_pages`). Use it in a loop that can send files to the model. `hooks` ([`ToolCallHooks`](./library.md#toolcallhooks), new in 0.7.0) are listeners for this call alone: the progress of a whole-file read, in place of `ToolOptions.onProgress`, and each of its model requests with their retries. Only `analyze_whole_document` calls them. |
685
+ | `describe(name, args)` | A short line for a progress UI, read from the arguments the way the tool reads them: `Search app.log (exact) for “timeout”` (the query cut to 80 characters), `Read app.log lines 1200-1260` (`-1260` only when `end_line` is a number not below `start_line`), `Overview of app.log`, `Read all of novel.txt for “list every character”` (the task cut to 100 characters), `Look at report.pdf pages 2-3`. A cut never splits an emoji. A file not yet known is "the file"; an unknown tool is its name, as it came (`askWithFiles` labels it `Call “NAME”` instead). The line quotes the model's words as they are: show it as plain text, or clean it as `askWithFiles` does its steps. In `askWithFiles`, this line, made one line of plain text, is the `label` of the call's `tool.start` event, the line `onActivity` gets with "…", and the start of its step. |
686
+ | `resultCharacters(name)` | The most characters of a result of this tool: the larger of `toolResultCharacters` and 40,000 for `analyze_whole_document`, 600 for `view_pages` (its file is counted in bytes), and `toolResultCharacters` for any other name. What a loop sets aside in its request before it runs a call. |
687
+
688
+ `execute` and `executeWithFiles` throw only when the tool set's `signal` was aborted: the error
689
+ that ended the call is thrown again instead of being returned to the model.
690
+
691
+ A turn of your own loop, run with the tool set. `files` is your
692
+ [`LargeFiles`](./library.md#largefiles), created once with
693
+ [createLargeFiles(options)](./library.md#createlargefilesoptions):
694
+
695
+ ```ts
696
+ import { DocumentsNotFoundError, toolResultSummary } from "llm-large-files";
697
+ import type { ToolAnswer, ToolCall } from "llm-large-files";
698
+
699
+ const documentIds = ["doc_0123456789abcdef0123456789abcdef"];
700
+ // The size of everything else in the request: system prompt, messages.
701
+ const base = { tokens: 2_000, bytes: 8_000 };
702
+ const prepared = await files.prepare(documentIds, base, {
703
+ owner: "user-42",
704
+ viewPages: true,
705
+ // The tool set below has no generate. This keeps the instruction from naming
706
+ // analyze_whole_document, and the cards from offering a whole-file read.
707
+ wholeDocumentAnalysis: false,
708
+ });
709
+ // A document that is gone (expired, or another owner's) is left out of the plan: say so, as askWithFiles does.
710
+ if (prepared.missing.length > 0) throw new DocumentsNotFoundError(prepared.missing);
711
+ const tools = files.tools(prepared.plan.searchable, { viewPages: prepared.viewable });
712
+ // Send prepared.instruction with your system prompt, and tools.declarations as the tools.
713
+
714
+ async function runCalls(calls: ToolCall[], roomCharacters: number, roomBytes: number): Promise<ToolAnswer[]> {
715
+ const answers: ToolAnswer[] = [];
716
+ for (const call of calls) {
717
+ // Arguments that did not arrive whole: tell the model, and do not run the call.
718
+ if (call.problem) {
719
+ answers.push({ call, result: { error: call.problem } });
720
+ continue;
721
+ }
722
+ const label = tools.has(call.name) ? tools.describe(call.name, call.args) : call.name;
723
+ const { result, files: pages } = await tools.executeWithFiles(call.name, call.args, {
724
+ maxResultCharacters: roomCharacters,
725
+ maxFileBytes: Math.floor(roomBytes * 3 / 4), // base64 turns three bytes into four
726
+ });
727
+ console.log(`${label}${toolResultSummary(label, result)}`);
728
+ answers.push({ call, result, files: pages });
729
+ }
730
+ return answers;
731
+ }
732
+ ```
733
+
734
+ Send each answer back in your provider's form, its files with it. The whole loop, with sizing,
735
+ limits and each provider's converters, is in
736
+ [Your own adapter and loop](../guides/own-adapter-and-loop.md).
737
+
738
+ ### `ToolCallLimits`
739
+
740
+ What one call may use of the request its result will be sent in: the third argument of
741
+ `executeWithFiles`. Every field is optional.
742
+
743
+ ```ts
744
+ type ToolCallLimits = {
745
+ maxFileBytes?: number;
746
+ maxPages?: number;
747
+ maxResultCharacters?: number;
748
+ maxRequests?: number;
749
+ };
750
+ ```
751
+
752
+ | Field | Type | Default | What it does |
753
+ |---|---|---|---|
754
+ | `maxFileBytes` | number | 3/8 of (`maxRequestBytes` − 262,144): 3,651,696 bytes with the default budget | `view_pages`: the most bytes its file may have. Pages are left off the end until the cut fits. Below 1,024 the call fails. Give the room left in your request, times 3/4 when you send files as base64. |
755
+ | `maxPages` | number | [`MAX_VIEW_PAGES`](#max_view_pages) (5) | `view_pages`: the most pages this call may show, never more than 5. Below 1 the call fails. Lower it as the pages already shown use up your token budget. |
756
+ | `maxResultCharacters` | number | The tool's own cap ([`resultCharacters`](#toolset)) | The most characters of the JSON result, when that is less than the tool's cap: the room left in the request. The result is cut to it and says where to go on. Never below 600. `view_pages` ignores it. |
757
+ | `maxRequests` | number | No limit | `analyze_whole_document`: the most model requests the read may make. It does not stop the read: a part the model refuses as too large is read as two halves only while this and `maxMapChunks` allow it (the parts, a merge and the answer must fit). New in 0.6.0. |
758
+
759
+ In `askWithFiles`, `maxFileBytes` is what is left of `maxRequestBytes` after the request so far
760
+ and a tenth kept free (256 KiB at least), times 3/4; `maxPages` is what is left of
761
+ `reservedTokens / 2 / pageTokens` pages for the question (60 with a `reservedTokens` of 64,000 and
762
+ Gemini's 530 tokens a page); `maxRequests`, when `limits.requests` is set, is the read's own
763
+ requests and a share of what the question has left of it. See
764
+ [Your own adapter and loop](../guides/own-adapter-and-loop.md).
765
+
766
+ ### `ToolFileLimits`
767
+
768
+ ```ts
769
+ type ToolFileLimits = ToolCallLimits;
770
+ ```
771
+
772
+ The name of [`ToolCallLimits`](#toolcalllimits) before 0.5.0, kept so that older code compiles.
773
+ Use `ToolCallLimits`.
774
+
775
+ ### `ToolOutput`
776
+
777
+ ```ts
778
+ type ToolOutput = { result: ToolResult; files: ToolFile[] };
779
+ ```
780
+
781
+ What `executeWithFiles` returns: a call's JSON result and the files that belong to it.
782
+
783
+ | Field | Type | Meaning |
784
+ |---|---|---|
785
+ | `result` | [`ToolResult`](#toolresult) | The JSON result, or `{ error }` for a call that failed. |
786
+ | `files` | [`ToolFile`](#toolfile)`[]` | The files of the result. Empty for every tool but `view_pages`, and for a `view_pages` call that failed. |
787
+
788
+ See [Your own adapter and loop](../guides/own-adapter-and-loop.md).
789
+
790
+ ### `ToolFile`
791
+
792
+ ```ts
793
+ type ToolFile = {
794
+ name: string;
795
+ mimeType: string;
796
+ bytes: Uint8Array;
797
+ };
798
+ ```
799
+
800
+ | Field | Type | Meaning |
801
+ |---|---|---|
802
+ | `name` | string | A short ASCII name, unique among the files of one result: `"pages-12-14.pdf"`. The result's `file` field names it. |
803
+ | `mimeType` | string | `"application/pdf"` for `view_pages`. |
804
+ | `bytes` | `Uint8Array` | The file. Send it to the model in your provider's form; it is not kept in `toolTurns`. |
805
+
806
+ See [PDFs](../guides/pdfs.md).
807
+
808
+ ### `ToolResult`
809
+
810
+ ```ts
811
+ type ToolResult = Record<string, unknown>;
812
+ ```
813
+
814
+ A tool's JSON result: an object whose fields are listed for each tool above, or `{ error: string }`
815
+ for a call that failed. Send it to the model as it is. To read one in code, test for the fields
816
+ (`error`, `already_shown`, `dropped`, `truncated`, `total_matching_lines`) rather than the wording
817
+ of notes. See [Your own adapter and loop](../guides/own-adapter-and-loop.md).
818
+
819
+ ### `ToolDeclaration`
820
+
821
+ ```ts
822
+ type ToolDeclaration = {
823
+ name: string;
824
+ description: string;
825
+ parameters: JsonSchema & { type: "object" };
826
+ };
827
+ ```
828
+
829
+ A tool as it is declared to the model. Every provider takes this form, or one made from it by its
830
+ adapter (`toGeminiTools` in the [Gemini reference](./gemini.md)).
831
+
832
+ | Field | Type | Meaning |
833
+ |---|---|---|
834
+ | `name` | string | The tool's name: for the tools of a tool set, one of [`TOOL_NAMES`](#tool_names). |
835
+ | `description` | string | The description the model sees, quoted in the tool's section above. |
836
+ | `parameters` | [`JsonSchema`](#jsonschema) with `type: "object"` | The arguments: `properties` and `required`, as in the tool's argument table. |
837
+
838
+ See [Your own adapter and loop](../guides/own-adapter-and-loop.md).
839
+
840
+ ### `JsonSchema`
841
+
842
+ ```ts
843
+ type JsonSchema = {
844
+ type: "string" | "integer" | "number" | "boolean" | "object" | "array";
845
+ description?: string;
846
+ enum?: string[];
847
+ properties?: Record<string, JsonSchema>;
848
+ required?: string[];
849
+ items?: JsonSchema;
850
+ };
851
+ ```
852
+
853
+ The subset of JSON Schema that Gemini, OpenAI and Anthropic function declarations all accept, and
854
+ the only one the tools use.
855
+
856
+ | Field | Type | Meaning |
857
+ |---|---|---|
858
+ | `type` | `"string"` \| `"integer"` \| `"number"` \| `"boolean"` \| `"object"` \| `"array"` | The JSON type of the value. |
859
+ | `description` | string, optional | What the value is, for the model. |
860
+ | `enum` | string[], optional | The values allowed, such as `mode`'s `"keywords"`, `"exact"` and `"regex"`. |
861
+ | `properties` | `Record<string, JsonSchema>`, optional | For an object: its fields. |
862
+ | `required` | string[], optional | For an object: the fields that must be given. |
863
+ | `items` | `JsonSchema`, optional | For an array: the schema of each item. |
864
+
865
+ See [Your own adapter and loop](../guides/own-adapter-and-loop.md).
866
+
867
+ ## Stability
868
+
869
+ [Publishing](../publishing.md) counts the tool names, their arguments and their result fields as
870
+ public API, like the documented exports and the HTTP responses of `llm-large-files/node`: changing them is
871
+ a breaking change, and the [changelog](../../CHANGELOG.md) names it. While the version is `0.x`, a
872
+ minor version (0.7.0) may make breaking changes. Descriptions, notes, error texts and the tool
873
+ guide are written for the model and have changed between versions: do not parse them; test for
874
+ result fields instead.
875
+
876
+ 0.6.0 changed the guide, the descriptions of `search_document` and `analyze_whole_document`, and
877
+ the frame of every file sent whole ([`PreparedContext`](./library.md#preparedcontext)), so the
878
+ provider's prompt cache misses once after upgrading to it: the first request of each conversation
879
+ after the upgrade reads from the cache at most what comes before the first text that changed. For
880
+ a question with files to search, that is nothing where the tools come first (Claude,
881
+ OpenAI-compatible endpoints), and at most your own system text on Gemini, where the guide follows
882
+ it in the system instruction. For a question whose files are all sent whole, it is your own system
883
+ text, and `view_pages` with its guide when the pages of a PDF can be looked at.