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,427 @@
1
+ # `llm-large-files/anthropic`
2
+
3
+ This page lists every export of `llm-large-files/anthropic` with its options, defaults, return
4
+ values and errors: the `anthropic()` adapter for Claude through the Messages API, the API version
5
+ it is written for, its error class, and the converters for a history kept as Messages API
6
+ messages. How to set Claude up, and what its append-only conversation means for your application,
7
+ is in the guide [Claude](../guides/anthropic.md).
8
+
9
+ ```ts
10
+ import { anthropic, ANTHROPIC_VERSION, anthropicToolTurns, AnthropicRequestError, fromAnthropicMessages } from "llm-large-files/anthropic";
11
+ import type { AnthropicMessage, AnthropicOptions } from "llm-large-files/anthropic";
12
+ // What the signatures below use from the main entry:
13
+ import { ModelRequestError } from "llm-large-files";
14
+ import type { ChatMessage, ModelAdapter, ModelErrorKind, ToolTurn } from "llm-large-files";
15
+ ```
16
+
17
+ The entry point needs no Anthropic SDK: it posts JSON to the Messages URL with `fetch`, signed in
18
+ with a key or a token, or through a gateway that speaks the same API.
19
+
20
+ ## Contents
21
+
22
+ - [The model adapter](#the-model-adapter): [`anthropic()`](#anthropicoptions),
23
+ [`AnthropicOptions`](#anthropicoptions-1), [`ANTHROPIC_VERSION`](#anthropic_version)
24
+ - [Errors](#errors): [`AnthropicRequestError`](#anthropicrequesterror)
25
+ - [Messages API messages](#messages-api-messages): [`AnthropicMessage`](#anthropicmessage),
26
+ [`fromAnthropicMessages()`](#fromanthropicmessageshistory),
27
+ [`anthropicToolTurns()`](#anthropictoolturnsturns)
28
+
29
+ ## The model adapter
30
+
31
+ ### anthropic(options)
32
+
33
+ ```ts
34
+ declare function anthropic(options: AnthropicOptions): ModelAdapter;
35
+ ```
36
+
37
+ A Claude model, as a [`ModelAdapter`](./ask.md#modeladapter) for
38
+ [`askWithFiles`](./ask.md#askwithfilesoptions): the model that answers, or the `explorer`. It makes
39
+ no request when it is created and throws nothing. The options are in
40
+ [`AnthropicOptions`](#anthropicoptions-1).
41
+
42
+ The adapter it returns:
43
+
44
+ | Member | Value |
45
+ |---|---|
46
+ | `id` | `options.id`, else `options.model`. It names the model in `usage.byModel` and in messages. |
47
+ | `capabilities` | `maxRequestBytes` 32,000,000; `toolFiles` from `toolFilePlacement` (`"inside"`); `pageTokens` 3,500; `tokenScale` 1.35; `outputTokens` equal to `maxTokens` (64,000); `appendOnly: true`; `contextTokens` only when you set it; `clearsToolResults: true` only when `body.context_management.edits` holds an edit whose `type` starts with `clear_tool_uses` or `compact` (new in 0.6.0). Each value but `appendOnly` comes from an option: `toolFiles` from `toolFilePlacement`, `outputTokens` from `maxTokens`, `clearsToolResults` from `body`, the others from the option of the same name. See [`ModelCapabilities`](./ask.md#modelcapabilities). |
48
+ | `send(request, hooks?)` | One chat request, described below. |
49
+ | `requestBytes(request)` | The size in bytes of the JSON body that `send` would post. |
50
+ | `generateText` | The part reader of whole-file reads, described below. With it, `analyze_whole_document` can be offered when this adapter is the model that uses the tools (the explorer, when there is one), unless `wholeDocumentAnalysis` is `false`. |
51
+
52
+ `appendOnly: true` tells the loop that Claude's conversation may only grow: Claude checks its
53
+ thinking blocks against the conversation they were written in, so an earlier turn that is rewritten
54
+ makes the request invalid. The loop then never shortens old tool results to make room; when the
55
+ room runs out, the question is answered with what it has.
56
+
57
+ `clearsToolResults: true` tells the loop that Claude may clear old tool results on its side, with
58
+ context editing (`clear_tool_uses`) or compaction, before it reads the request. The loop then
59
+ answers no call made again with a pointer to an earlier result: each runs again. `clear_thinking`
60
+ alone changes nothing.
61
+
62
+ **Where it posts.** Every request goes to `url`, or to `baseUrl` (default
63
+ `https://api.anthropic.com`, trailing slashes removed) followed by `/v1/messages`. Its headers are:
64
+
65
+ - `Content-Type: application/json`;
66
+ - `anthropic-version`: `version`, default [`ANTHROPIC_VERSION`](#anthropic_version);
67
+ - `anthropic-beta`, when there is any: the values of `betas`, and `server-side-fallback-2026-07-01`
68
+ when `fallbacks` is set, each once, joined by commas;
69
+ - `x-api-key` when `apiKey` gives a non-empty string, and `Authorization: Bearer {authToken}` when
70
+ `authToken` does;
71
+ - then `headers`, which can replace any of them.
72
+
73
+ `apiKey`, `authToken` and `headers` are resolved before every request, chat requests and part
74
+ reads alike, so a function can return a renewed key or token.
75
+
76
+ **The body of a chat request**, in this order, a later field replacing an earlier one:
77
+
78
+ - `model` and `max_tokens` (`maxTokens`).
79
+ - `system`, when the system instruction is not empty.
80
+ - `messages`.
81
+ - `tools`, each as `{ name, description, input_schema }`, when the request offers tools, with
82
+ `eager_input_streaming: true` on each when the request is streamed and `eagerInputStreaming` is
83
+ on. A request that must be answered in text keeps the tools and adds
84
+ `tool_choice: { type: "none" }`: Claude ties its thinking to the tools of the conversation.
85
+ - `stream: true`, when the request is streamed.
86
+ - `cache_control: { type: "ephemeral" }`, with `ttl: "1h"` for `cache: "1h"`, unless
87
+ `cache: false`.
88
+ - `fallbacks`, when set.
89
+ - Every field of `body`.
90
+
91
+ No `temperature` or other sampling field is sent. `body` would send one, but the API version in
92
+ `ANTHROPIC_VERSION` refuses `temperature`: see [Claude](../guides/anthropic.md).
93
+
94
+ **The conversation in the request.**
95
+
96
+ - A turn of text becomes content blocks: `{ type: "text", text }` for each text part that is not
97
+ empty (the API refuses an empty text block), and each native part as it is. Turns of the same role
98
+ that follow each other are made one message, and a turn left with no blocks is dropped.
99
+ - A model turn of this question goes back as it came, thinking blocks and their signatures
100
+ included. Two kinds of block are left out of it: an empty text block (one a stream opened and
101
+ closed with nothing in it, which the API refuses) that no thinking block follows, and, in a reply
102
+ that has a `fallback` block, the thinking and tool-use blocks before the last `fallback` (those of
103
+ the model that declined).
104
+ - A stored tool round (the `toolTurns` of an earlier question, or a round of another adapter)
105
+ becomes an assistant turn of `{ type: "tool_use", id, name, input }` blocks. Its call IDs are made
106
+ to fit the API: each character other than `A-Z`, `a-z`, `0-9`, `_` and `-` becomes `_`; a call
107
+ without an ID is given `toolu_{round}_{n}`; an ID already used earlier in the request gets `_2`,
108
+ `_3` and so on. The IDs of Claude's own turns are kept as they are.
109
+ - The results follow in one user turn of `{ type: "tool_result", tool_use_id, content }` blocks,
110
+ `content` being the result as JSON, with `is_error: true` when the result is an error. With
111
+ `toolFilePlacement` `"inside"`, the pages of `view_pages` are `document` blocks inside the
112
+ `tool_result`, after its JSON. With `"beside"`, they come after all the results of the turn, each
113
+ after a text block `"{file name} (returned by view_pages):"`.
114
+
115
+ **Streaming.** Every chat request is streamed unless `stream` is `false`, whether `onText` is given
116
+ or not: the explorer's requests too. Each piece of text goes to `onText` as it arrives.
117
+
118
+ - A response of type `text/event-stream` is read as events. A response of another type, or of none,
119
+ is read by its first characters (since 0.6.0): as events when it starts like them (`data:`,
120
+ `event:`, `id:`, `retry:` or a comment), whole otherwise, as a gateway that answered without
121
+ streaming sends it. `onText` then gets its text at once. A body that starts with more than 65,536
122
+ characters of white space is read whole.
123
+ - `message_stop` ends the reply. A gateway that then leaves the connection open is read for one
124
+ more second at most, and the body is cancelled, which closes the connection; a connection that
125
+ breaks after `message_stop` keeps the reply too. 0.5.0 waited for such a connection to close,
126
+ and failed a request whose connection broke after `message_stop` with status 0, with the whole
127
+ answer already shown.
128
+
129
+ **The reply** ([`ModelReply`](./ask.md#modelreply)):
130
+
131
+ - `text` is the text of the `text` blocks. Thinking is not part of it.
132
+ - `calls` are the `tool_use` blocks, those after the last `fallback` block when there is one, with
133
+ their `input` as `args` (`{}` when it is not an object). In a stream, input whose pieces do not
134
+ make a JSON object gives the call a `problem` (the loop answers it with that message instead of
135
+ running it, and the model can send it again), and a tool-use block whose stream never closed gets
136
+ "This call did not arrive whole, and was not run. Send it again.". When
137
+ `stop_reason` is `"max_tokens"`, every call gets a `problem` that says it was cut off at the output
138
+ limit. A reply with `stop_reason` `"refusal"` has no calls.
139
+ - `raw` is the content as it goes back (see above). Thinking, signatures and citations are kept.
140
+ - `finishReason` is `stop_reason`. `finish` is `"complete"` for `end_turn`, `tool_use` and
141
+ `stop_sequence`; `"cut"` for `max_tokens` and `model_context_window_exceeded`; `"filtered"` for
142
+ `refusal`.
143
+ - `blockReason` is `"refusal"` for a refusal, followed by `": {category}"` when the API gives
144
+ `stop_details.category`. A question whose reply was refused ends with `answered: false`, even when
145
+ some text had streamed.
146
+ - `usage`: `inputTokens` is `input_tokens` + `cache_creation_input_tokens` +
147
+ `cache_read_input_tokens`, the whole prompt; `cachedInputTokens` is `cache_read_input_tokens`;
148
+ `outputTokens` is `output_tokens`; `thoughtTokens` stays 0, as the adapter reads no count of
149
+ thinking apart. With fallbacks, the attempts in `usage.iterations` are added up. `providerUsage`
150
+ is the API's `usage` as it came; in a stream, that of `message_start` updated by `message_delta`.
151
+
152
+ **Part reads** (`generateText`, for `analyze_whole_document`) go to the same URL with the same
153
+ headers and are never streamed. The body is `model`, `max_tokens` (the limit of that read),
154
+ `system`, one user message, then the fields of `analysisBody(limit)`: no `body`, no
155
+ `cache_control`, no `fallbacks`, no tools. Each request may take `timeoutMs` (180 s). A reply that
156
+ stopped for `refusal` or `model_context_window_exceeded` is kept and marked incomplete, as one cut
157
+ off at its limit is. A reply cut off with nothing written, or with half its limit or more spent
158
+ thinking, while the limit was below 32,768, is asked again with 32,768 output tokens
159
+ ([`THINKING_OUTPUT_TOKENS`](./gemini.md#thinking_output_tokens)), and later part reads to the same
160
+ URL and model start there. Claude does not count its thoughts apart: when the reply has thinking
161
+ blocks, its thoughts are taken as its `output_tokens` less its text, estimated with `tokenScale`
162
+ (new in 0.6.0: 0.5.0 counted none, so a part that thought most of its limit away came back cut,
163
+ with the little text it wrote). A model that refuses that limit with HTTP 400 is not asked for it again. A
164
+ refusal of the request as too large for the model's window is not taken for that (since 0.6.0): it
165
+ turns the larger limit off only when the window it names is 32,768 tokens or less.
166
+
167
+ **Errors.** `send` throws, and does not send anything again itself:
168
+ [`askWithFiles`](./ask.md#askwithfilesoptions) decides what is retried
169
+ ([`RetryOptions`](./errors-and-retries.md#retryoptions)).
170
+
171
+ | Case | Error | `status` | `kind` |
172
+ |---|---|---|---|
173
+ | The API answered with an HTTP error | [`AnthropicRequestError`](#anthropicrequesterror) with the body's `error.message`, else "Claude returned HTTP {status}." (for example "Claude returned HTTP 529."). With `type` (the body's `error.type`) and `retryAfterMs` when the API gave them. A spending cap of the organization (HTTP 429 with `error.details.error_code` `enforced_spend_limit_reached`) has kind `"quota"` (since 0.6.0; it was sent again three times). A response with the header `x-should-retry: false` is not sent again, whatever its status, as Anthropic's own SDKs do (since 0.6.0). | The HTTP status | Told from the status, the message and `type` |
174
+ | An `error` event inside the stream | `AnthropicRequestError` with its message, else "Claude reported an error.", and its `type` | From its `type`: `overloaded_error` 529, `rate_limit_error` 429, `api_error` 500, `timeout_error` 408, and since 0.6.0 `invalid_request_error` 400, `authentication_error` 401, `billing_error` 402, `permission_error` 403, `not_found_error` 404, `request_too_large` 413. Any other type, or none: 500, sent again when none of the reply was shown (in 0.5.0, the response's 200, not sent again) | Told from the status, the message and `type` |
175
+ | The connection failed, before or while the reply arrived, or an event of the stream was not JSON | `AnthropicRequestError`: "Claude could not be reached (fetch failed).", the reason being the HTTP client's message | 0 | `"unreachable"` |
176
+ | A reply of HTTP 200 whose body is empty | `AnthropicRequestError`: "Claude could not be reached (the reply was empty).", new in 0.6.0. When the reply's type is `text/event-stream`, "Claude's reply ended before it was complete." Either is sent again as a reply cut off on its way. | 0 | `"unreachable"` |
177
+ | Nothing arrived for a whole wait (`firstByteTimeoutMs`, `idleTimeoutMs`) | `AnthropicRequestError`: "Claude sent nothing for {seconds} s.", the wait that ran out (600 s or 300 s by default) | 0 | `"timeout"` |
178
+ | A stream that closed with no `stop_reason` | `AnthropicRequestError`: "Claude's reply ended before it was complete." | 0 | `"unreachable"` |
179
+ | A reply whose body is not JSON (a gateway's HTML page) | `AnthropicRequestError`: "Claude's reply could not be read: it was not JSON (text/html). A proxy or gateway may have answered in its place.", the brackets holding the response's media type (left out when it has none), with the `SyntaxError` as `cause`. Not sent again. Until 0.6.0, the `SyntaxError` itself. | The response's, 200 | `"invalid"` |
180
+ | An event of the stream longer than 64,000,000 characters | `AnthropicRequestError`: "Claude's reply could not be read: an event of its stream held more than 64,000,000 characters." Not sent again. New in 0.6.0. | The response's, 200 | `"invalid"` |
181
+ | `hooks.signal` aborted | The signal's reason, as it is | none | none |
182
+
183
+ A part read throws as `send` does for an HTTP error, a connection that failed, an empty body, an
184
+ abort and a body that is not JSON. It has no waits of `firstByteTimeoutMs` and `idleTimeoutMs`;
185
+ instead, a request that ran past `timeoutMs` throws the error of its abort (a `TimeoutError`). A
186
+ reply with no text throws `Error("The model returned no text (refusal).")`, the reason in brackets
187
+ being `stop_reason`. These two have no `status`. In a whole-file read, the model is told why a part
188
+ failed by the error's kind and status, never by the API's message: "The model took too long to
189
+ answer." for the `TimeoutError`, "The model returned no text (refusal)." for a reply with no text
190
+ (see [`analyze_whole_document`](./tools.md#analyze_whole_document)).
191
+
192
+ ```ts
193
+ import { askWithFiles } from "llm-large-files";
194
+ import { anthropic } from "llm-large-files/anthropic";
195
+
196
+ // files, documentIds and messages come from your application.
197
+ const model = anthropic({
198
+ model: "claude-opus-5-5",
199
+ apiKey: process.env.ANTHROPIC_API_KEY!,
200
+ contextTokens: 1_000_000, // set this to your model's context window
201
+ cache: "1h", // follow-up questions within the hour read the cached prompt
202
+ });
203
+
204
+ const result = await askWithFiles({
205
+ files,
206
+ model,
207
+ documentIds,
208
+ messages,
209
+ onText: (delta) => process.stdout.write(delta),
210
+ });
211
+ if (result.blockReason) console.log(`Refused: ${result.blockReason}`);
212
+ ```
213
+
214
+ Guide: [Claude](../guides/anthropic.md): the window, thinking and effort, caching, fallbacks,
215
+ gateways and hosts other than the Claude API, and Claude next to Gemini. A second model that
216
+ explores while Claude answers: [explorer model](../guides/explorer-model.md).
217
+
218
+ ### `AnthropicOptions`
219
+
220
+ ```ts
221
+ type AnthropicOptions = {
222
+ model: string;
223
+ apiKey?: string | (() => string | Promise<string>) | undefined;
224
+ authToken?: string | (() => string | Promise<string>) | undefined;
225
+ baseUrl?: string | undefined;
226
+ url?: string | undefined;
227
+ headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>) | undefined;
228
+ version?: string | undefined;
229
+ betas?: string[] | undefined;
230
+ maxTokens?: number | undefined;
231
+ body?: Record<string, unknown> | undefined;
232
+ analysisBody?: ((maxOutputTokens: number) => Record<string, unknown>) | undefined;
233
+ fallbacks?: "default" | Array<Record<string, unknown> & { model: string }> | undefined;
234
+ cache?: boolean | "5m" | "1h" | undefined;
235
+ toolFilePlacement?: "inside" | "beside" | "none" | undefined;
236
+ stream?: boolean | undefined;
237
+ eagerInputStreaming?: boolean | undefined;
238
+ contextTokens?: number | undefined;
239
+ maxRequestBytes?: number | undefined;
240
+ pageTokens?: number | undefined;
241
+ tokenScale?: number | undefined;
242
+ timeoutMs?: number | undefined;
243
+ firstByteTimeoutMs?: number | undefined;
244
+ idleTimeoutMs?: number | undefined;
245
+ id?: string | undefined;
246
+ fetch?: typeof fetch | undefined;
247
+ };
248
+ ```
249
+
250
+ The options of [`anthropic()`](#anthropicoptions).
251
+
252
+ | Option | Type | Default | What it does |
253
+ |---|---|---|---|
254
+ | `model` | `string` | required | The model ID, sent as `model` in every chat request and part read: `"claude-opus-5-5"`. |
255
+ | `apiKey` | `string \| (() => string \| Promise<string>)` | none | Sent as `x-api-key`. A function is called before every request. An empty string sends no header. |
256
+ | `authToken` | `string \| (() => string \| Promise<string>)` | none | Sent as `Authorization: Bearer {token}`, for an OAuth token or a gateway. A function is called before every request. |
257
+ | `baseUrl` | `string` | `"https://api.anthropic.com"` | The base of the API. Trailing slashes are removed and `/v1/messages` is added. Not used when `url` is set. |
258
+ | `url` | `string` | `baseUrl` + `/v1/messages` | The whole Messages URL, used as it is. Its host also sets the default of `eagerInputStreaming`. |
259
+ | `headers` | `Record<string, string> \| (() => Record<string, string> \| Promise<Record<string, string>>)` | none | More headers, merged last: they can replace any header the adapter writes. A function is called before every request. |
260
+ | `version` | `string` | [`ANTHROPIC_VERSION`](#anthropic_version), `"2026-10-21"` | The `anthropic-version` header. |
261
+ | `betas` | `string[]` | none | Values for the `anthropic-beta` header, such as the beta that a `context_management` field in `body` needs. |
262
+ | `maxTokens` | `number` | `64_000` | `max_tokens` of every chat request: the most Claude may write, thinking included. Cut to a whole number, at least 1. It is also `capabilities.outputTokens`: it comes out of the context window, so the budget of a question keeps it free. Part reads send their own limit instead. |
263
+ | `body` | `Record<string, unknown>` | none | More fields for the body of every chat request: `thinking`, `output_config`, `context_management`, `metadata`. Spread last, so a field here replaces the adapter's own; a field set to `undefined` is left out of the JSON. Not sent with part reads. |
264
+ | `analysisBody` | `(maxOutputTokens: number) => Record<string, unknown>` | none | More fields for the body of each part read, given the `max_tokens` that request is sent with. Spread last. |
265
+ | `fallbacks` | `"default" \| Array<Record<string, unknown> & { model: string }>` | none | Have another model answer when this one's safety classifiers decline a request: `"default"`, or a list of `{ model }`. It adds the `fallbacks` field and the beta `server-side-fallback-2026-07-01`. Off unless set: it is offered on the Claude API, not on Amazon Bedrock, Vertex AI or Microsoft Foundry, and not for every model. |
266
+ | `cache` | `boolean \| "5m" \| "1h"` | `true` | Prompt caching: a top-level `cache_control`, which caches the request up to its last block, so each request of the tool loop, and a follow-up question, reads what the one before wrote. `true` and `"5m"` send `{ type: "ephemeral" }`, which the API keeps five minutes; `"1h"` adds `ttl: "1h"`; `false` sends none. Part reads are not cached. |
267
+ | `toolFilePlacement` | `"inside" \| "beside" \| "none"` | `"inside"` | Where the pages of `view_pages` go: `"inside"` the tool result as `document` blocks; `"beside"` it, after the tool results of the turn; `"none"` sends no file, and `view_pages` is then not offered to any model of the question. It is `capabilities.toolFiles`. |
268
+ | `stream` | `boolean` | `true` | Stream every chat request, which keeps a long reply from timing out. `false` for a gateway without streaming. Part reads are never streamed. |
269
+ | `eagerInputStreaming` | `boolean` | `true` when the host of the URL is `api.anthropic.com`, else `false` | Set `eager_input_streaming: true` on each tool of a streamed request, so that tool input arrives as it is written. Off by default for any other URL, which may refuse the field. Never sent when `stream` is `false`. |
270
+ | `contextTokens` | `number` | none | The model's context window in tokens. Set as `capabilities.contextTokens`, it keeps the budget of a question within it. Without it the library's budget holds: 1,000,000 tokens unless you set another. |
271
+ | `maxRequestBytes` | `number` | `32_000_000` | The largest request body in bytes, the limit of the Claude API (32 MB). It keeps the budget within it. |
272
+ | `pageTokens` | `number` | `3_500` | Tokens billed for one PDF page shown by `view_pages`: its text and its picture. The loop sizes the pages a question may look at from it. |
273
+ | `tokenScale` | `number` | `1.35` | Claude's tokens for one token of the library's estimate, which is fitted to Gemini: documents are planned for a window that much smaller. 1.35 is a cautious guess for the tokenizer of the current models; during a question, the token count the API reports with each reply corrects the estimate. |
274
+ | `timeoutMs` | `number` | `180_000` | The longest a part read's request may take, in milliseconds, each try counted apart. A request that runs longer is aborted. Not used for chat requests. |
275
+ | `firstByteTimeoutMs` | `number` | `600_000` | The longest wait, in milliseconds, for the first piece of a chat reply. Headers do not count: a model that thinks sends nothing until it has thought, and a reply that is not streamed comes whole at the end. A request that gets nothing for that long is aborted with an `AnthropicRequestError` (`status` 0, `kind` `"timeout"`), which `askWithFiles` sends again once. 0, a negative or a non-finite number waits without end. The key, token and headers are resolved before the wait starts. Not used for part reads. |
276
+ | `idleTimeoutMs` | `number` | `300_000` | The longest wait, in milliseconds, between two pieces of a chat reply once it has started to arrive. Any bytes count, Claude's `ping` events included. The same error; `askWithFiles` sends the request again once, unless text of it was shown. 0 waits without end. Not used for part reads. |
277
+ | `id` | `string` | `model` | The name of the model in `usage.byModel` and in messages. |
278
+ | `fetch` | `typeof fetch` | the global `fetch` | Used for chat requests and part reads: a proxy, logging, tests. |
279
+
280
+ The two waits default to [`DEFAULT_FIRST_BYTE_TIMEOUT_MS`](./errors-and-retries.md#default_first_byte_timeout_ms)
281
+ and [`DEFAULT_IDLE_TIMEOUT_MS`](./errors-and-retries.md#default_idle_timeout_ms). What to set
282
+ them to: [errors and reliability](../guides/errors-and-reliability.md). How `contextTokens`,
283
+ `maxTokens` and `tokenScale` shape the room of a question: [Claude](../guides/anthropic.md) and
284
+ [costs and limits](../guides/costs-and-limits.md). Pages: [PDFs](../guides/pdfs.md).
285
+
286
+ ### `ANTHROPIC_VERSION`
287
+
288
+ ```ts
289
+ const ANTHROPIC_VERSION = "2026-10-21";
290
+ ```
291
+
292
+ The version of the Messages API that the adapter's requests and its reading of replies are written
293
+ for. It is the default of `version`, sent as the `anthropic-version` header.
294
+
295
+ ## Errors
296
+
297
+ ### `AnthropicRequestError`
298
+
299
+ ```ts
300
+ declare class AnthropicRequestError extends ModelRequestError {
301
+ readonly type?: string;
302
+ constructor(message: string, status: number, options?: {
303
+ retryAfterMs?: number;
304
+ cause?: unknown;
305
+ kind?: ModelErrorKind;
306
+ code?: string | undefined;
307
+ details?: unknown;
308
+ type?: string;
309
+ });
310
+ }
311
+ ```
312
+
313
+ A request to Claude that failed: the API answered with an HTTP error, or could not be reached
314
+ (`status` 0). It is a [`ModelRequestError`](./errors-and-retries.md#modelrequesterror), so code
315
+ that handles every provider through `ModelRequestError` and `kind` needs no case of its own for it.
316
+ The table under [`anthropic()`](#anthropicoptions) lists when the adapter throws one.
317
+
318
+ | Field | Type | What it holds |
319
+ |---|---|---|
320
+ | `name` | `string` | `"AnthropicRequestError"`. |
321
+ | `message` | `string` | The API's own message, or one of the adapter's (see the table above). It is the provider's text: log it, and do not show it to your users as it is. |
322
+ | `status` | `number` | The HTTP status, or the status of an `error` event in the stream; 0 when no answer came; 200 for a reply that came and could not be read. |
323
+ | `kind` | [`ModelErrorKind`](./errors-and-retries.md#modelerrorkind) | What went wrong, told from `status`, the message and `type`: `type` `"request_too_large"` with a 4xx status makes it `"context_overflow"`, an `overloaded_error` (529) `"server"`, a `rate_limit_error` (429) `"rate_limit"`. "Your credit balance is too low" (HTTP 400) and the spending limits ("You have reached your API usage limits", HTTP 400, or HTTP 429 with `enforced_spend_limit_reached`) make it `"quota"`. The adapter sets `"timeout"` itself for a wait that ran out, and `"invalid"` for a reply of HTTP 200 it could not read. New in 0.6.0. |
324
+ | `retryAfterMs` | `number \| undefined` | The wait the API asked for: its `retry-after-ms` or `Retry-After` header, or the `retryDelay` of a `google.rpc.RetryInfo` in the error body. |
325
+ | `limitTokens`, `requestedTokens` | `number \| undefined` | For `kind` `"context_overflow"`: the model's limit and the tokens of the request, when the message gives them. New in 0.6.0. |
326
+ | `type` | `string \| undefined` | The API's own word for the error, its `error.type`: `"rate_limit_error"`, `"overloaded_error"`, `"request_too_large"`. |
327
+ | `cause` | `unknown` | The HTTP client's error, for a request that could not be reached. |
328
+
329
+ The constructor takes the options of `ModelRequestError` and `type`. `type` sets the field and is
330
+ used to tell the kind, in place of any `code` given; `kind` given wins over what the status and
331
+ message say. You build one yourself only in a test or in a wrapper around the adapter.
332
+
333
+ ```ts
334
+ import { askWithFiles } from "llm-large-files";
335
+ import { AnthropicRequestError } from "llm-large-files/anthropic";
336
+
337
+ // files, model, documentIds and messages as above.
338
+ try {
339
+ await askWithFiles({ files, model, documentIds, messages });
340
+ } catch (error) {
341
+ if (error instanceof AnthropicRequestError && error.type === "overloaded_error") {
342
+ console.error(`Claude is overloaded (HTTP ${error.status}); retries ran out.`);
343
+ }
344
+ throw error;
345
+ }
346
+ ```
347
+
348
+ Guide: [errors and reliability](../guides/errors-and-reliability.md), with what to show your users
349
+ for each `kind`.
350
+
351
+ ## Messages API messages
352
+
353
+ ### `AnthropicMessage`
354
+
355
+ ```ts
356
+ type AnthropicMessage = { role: "user" | "assistant"; content: string | Array<Record<string, unknown>> };
357
+ ```
358
+
359
+ A message of the Messages API as it takes and returns it: a string, or a list of content blocks
360
+ (`text`, `image`, `document`, `tool_use`, `tool_result`, `thinking`, and any other). There is no
361
+ system role: the system prompt goes in `askWithFiles`'s `system` option.
362
+
363
+ ### fromAnthropicMessages(history)
364
+
365
+ ```ts
366
+ declare function fromAnthropicMessages(history: AnthropicMessage[]): ChatMessage[];
367
+ ```
368
+
369
+ A conversation kept as Messages API messages, as `askWithFiles` takes it in `messages`
370
+ ([`ChatMessage[]`](./ask.md#chatmessage)). It does not change `history`, and throws nothing.
371
+
372
+ | Block in a message | What it becomes |
373
+ |---|---|
374
+ | A string `content` | Read as one `text` block. |
375
+ | `text` | A text part. An empty one is left out. |
376
+ | `thinking`, `redacted_thinking` | Left out: they belong to the conversation they were written in. |
377
+ | `tool_use`, in an assistant message | A call of a stored tool round ([`ToolTurn`](./ask.md#toolturn)): its `id`, `name`, and `input` (`{}` when it is not an object). |
378
+ | `tool_result`, in a user message | The result of the call with the same `tool_use_id` in an earlier message: its text (a string `content`, or the `text` blocks of a list, joined) parsed as a JSON object, else `{ text }`. One that answers no known call is left out. |
379
+ | Any other block (an `image`, a `document`) | A native part, as it is. |
380
+
381
+ The parts of a message become one turn of its role, when it has any, and its `tool_use` blocks
382
+ become one tool round after that turn. A call that no `tool_result` answers keeps the result
383
+ `{ error: "No result was kept for this call." }`.
384
+
385
+ Native parts reach every model of the question as they are. With a model of another provider (an
386
+ explorer on Gemini, say), both models must read blocks in the Messages API's form.
387
+
388
+ ### anthropicToolTurns(turns)
389
+
390
+ ```ts
391
+ declare function anthropicToolTurns(turns: ToolTurn[]): AnthropicMessage[];
392
+ ```
393
+
394
+ The tool rounds a question returned ([`AskResult.toolTurns`](./ask.md#askresult)) as Messages API
395
+ messages, for an application that keeps its history in that form. Put them between the question and
396
+ its answer. It throws nothing.
397
+
398
+ Each round becomes two messages: an assistant message of `{ type: "tool_use", id, name, input }`
399
+ blocks, and a user message of `{ type: "tool_result", tool_use_id, content }` blocks, `content`
400
+ being the result as JSON, without `tool_turns_left`, which counted the turns of its own question
401
+ (since 0.6.0, as `askWithFiles` sends stored rounds), with `is_error: true` when the result is an
402
+ error. No document blocks: `toolTurns` keep no files.
403
+
404
+ A call with an ID keeps it. A call without one is given a new random ID, `toolu_` and 24 hex
405
+ digits, a different one each time the function runs, so that the rounds of two questions kept in
406
+ one history never share an ID. (Before 0.6.0 such calls were numbered from 1.) The IDs are then
407
+ made to fit the API: each character other than `A-Z`, `a-z`, `0-9`, `_` and `-` becomes `_` (a
408
+ call from another provider, such as `functions.search:0`, becomes `functions_search_0`), and an ID
409
+ already used earlier in the returned list gets `_2`, `_3` and so on.
410
+
411
+ ```ts
412
+ import { askWithFiles } from "llm-large-files";
413
+ import { anthropicToolTurns, fromAnthropicMessages, type AnthropicMessage } from "llm-large-files/anthropic";
414
+
415
+ // files, model and documentIds as above; system is your system prompt. history is the chat so
416
+ // far, kept by your application as Messages API messages, ending with the user's question.
417
+ async function answer(history: AnthropicMessage[]): Promise<string> {
418
+ const result = await askWithFiles({ files, model, system, documentIds, messages: fromAnthropicMessages(history) });
419
+ // Keep what the tools returned between the question and the answer: a follow-up question
420
+ // then finds it without searching again.
421
+ history.push(...anthropicToolTurns(result.toolTurns), { role: "assistant", content: result.text });
422
+ return result.text;
423
+ }
424
+ ```
425
+
426
+ Guides: [conversations](../guides/conversations.md), which covers keeping `toolTurns` and the
427
+ history across requests, and [Claude](../guides/anthropic.md), on a conversation that may only grow.