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,278 @@
1
+ import type { GenerateText, ToolDeclaration, ToolFile, ToolResult } from "./types.js";
2
+ /**
3
+ * A tool call a model made. `id` is the provider's own, where it gives one. `problem` says why
4
+ * the call cannot be run as it came (its arguments were not JSON, or it was cut off): the loop
5
+ * then answers it with that message, and the model can send it again.
6
+ */
7
+ export type ToolCall = {
8
+ id?: string;
9
+ name: string;
10
+ args: Record<string, unknown>;
11
+ problem?: string;
12
+ };
13
+ /** A tool call with what the tool returned for it. */
14
+ export type ToolAnswer = {
15
+ call: ToolCall;
16
+ result: ToolResult;
17
+ files?: ToolFile[];
18
+ };
19
+ /**
20
+ * One piece of a message: plain text, or something in the provider's own form (an image, an inline
21
+ * PDF) that only its adapter reads. A native part may carry the text it holds, to be sized by.
22
+ */
23
+ export type ModelPart = {
24
+ text: string;
25
+ native?: undefined;
26
+ } | {
27
+ native: unknown;
28
+ text?: string;
29
+ };
30
+ /** A turn of the user or of the model, as text and native parts. */
31
+ export type ModelTextMessage = {
32
+ role: "user" | "assistant";
33
+ parts: ModelPart[];
34
+ };
35
+ /**
36
+ * One round of tool use: the calls of a model turn, and what the tools returned for them, in call
37
+ * order. `raw` is that model turn in its provider's own form. The loop sets it only for the
38
+ * adapter that received it, which sends it back unchanged (Gemini wants its thought signatures,
39
+ * Claude its thinking blocks). Without `raw` the turn is built from `calls`. A round whose
40
+ * `answers` is empty is a model turn that has not been answered yet.
41
+ */
42
+ export type ModelToolRound = {
43
+ role: "tools";
44
+ calls: ToolCall[];
45
+ answers: ToolAnswer[];
46
+ raw?: unknown;
47
+ };
48
+ export type ModelMessage = ModelTextMessage | ModelToolRound;
49
+ /** A plain chat turn. "model" is accepted as an alias for "assistant". */
50
+ export type ChatTurn = {
51
+ role: "user" | "assistant" | "model";
52
+ text: string;
53
+ };
54
+ /**
55
+ * A round of tool use as an application stores it between a question and its answer
56
+ * (`AskResult.toolTurns`): plain JSON. Passed back in `messages`, the model sees in a later
57
+ * question what its tools returned in an earlier one, and does not have to search again.
58
+ */
59
+ export type ToolTurn = {
60
+ role: "tools";
61
+ calls: Array<ToolCall & {
62
+ result: ToolResult;
63
+ }>;
64
+ };
65
+ /**
66
+ * A result of a stored tool round, as it is sent again in a later question: without
67
+ * `tool_turns_left`, which counted the tool turns its own question had left, not those of the
68
+ * later one. The same result when it has none.
69
+ */
70
+ export declare function laterResult(result: ToolResult): ToolResult;
71
+ /** What `askWithFiles` takes as conversation: plain turns, stored tool rounds, and turns with native parts. */
72
+ export type ChatMessage = ChatTurn | ToolTurn | ModelTextMessage;
73
+ export type ModelRequest = {
74
+ /** The system instruction: the application's, then the guide to the document tools. May be empty. */
75
+ system: string;
76
+ /** The conversation, oldest first. The last message is the user's, or a tool round. */
77
+ messages: ModelMessage[];
78
+ /** The tools on offer. Left out when the conversation needs none. */
79
+ tools?: ToolDeclaration[];
80
+ /**
81
+ * "none": the model must answer in text. The tools are still listed, for a provider that wants
82
+ * them declared next to the tool calls already in the conversation.
83
+ */
84
+ toolChoice?: "auto" | "none";
85
+ };
86
+ /** Tokens of one request, or summed over several. */
87
+ export type ModelUsage = {
88
+ /** Every token of the prompt, those read from a cache included. */
89
+ inputTokens: number;
90
+ /** The part of `inputTokens` that was read from the provider's prompt cache. */
91
+ cachedInputTokens: number;
92
+ /** Every token the model produced, thoughts included. */
93
+ outputTokens: number;
94
+ /** The part of `outputTokens` that went on thinking, where the provider says. */
95
+ thoughtTokens: number;
96
+ };
97
+ export type ModelReply = {
98
+ /** What the model wrote for the user in this reply. Thoughts are not part of it. */
99
+ text: string;
100
+ calls: ToolCall[];
101
+ /** This turn in the provider's own form, to send back unchanged with the tool results. */
102
+ raw?: unknown;
103
+ /** Why the reply ended, in the provider's own word ("STOP", "length", "end_turn"). */
104
+ finishReason?: string;
105
+ /**
106
+ * How the reply ended, in terms every adapter maps its own to: "complete"; "cut" at the output
107
+ * limit; "filtered" by the provider's safety filters; "malformed_call", a tool call the model
108
+ * tried to make that could not be read (Gemini's MALFORMED_FUNCTION_CALL). Unset when the
109
+ * adapter does not know the reason.
110
+ */
111
+ finish?: "complete" | "cut" | "filtered" | "malformed_call";
112
+ /** Why the provider refused the prompt, when it did. Nothing more is asked after it. */
113
+ blockReason?: string;
114
+ usage?: Partial<ModelUsage>;
115
+ /** The provider's own usage object, as it came. */
116
+ providerUsage?: Record<string, unknown>;
117
+ };
118
+ export type SendHooks = {
119
+ /**
120
+ * Called with the answer text as it arrives. When it is given the adapter streams if it can; one
121
+ * that cannot calls it once with the whole text. The text is in the reply either way.
122
+ */
123
+ onText?: (delta: string) => void;
124
+ signal?: AbortSignal;
125
+ };
126
+ /** What a model can take, as far as its adapter knows. */
127
+ export type ModelCapabilities = {
128
+ /** The context window in tokens. When set, the budget of a question is no larger than this. */
129
+ contextTokens?: number;
130
+ /** The largest request body in bytes. When set, the budget of a question is no larger than this. */
131
+ maxRequestBytes?: number;
132
+ /**
133
+ * Where a file that a tool returned (the pages of `view_pages`) goes: "inside" the tool result,
134
+ * "beside" it in a user turn of its own, or "none" for a model that cannot be sent one. With
135
+ * "none", `view_pages` is not offered.
136
+ */
137
+ toolFiles: "inside" | "beside" | "none";
138
+ /** About what the model bills for one PDF page it is shown, in tokens. */
139
+ pageTokens: number;
140
+ /**
141
+ * How many of this model's tokens one token of the library's estimate comes to. The estimate
142
+ * (`estimateTokens`) is fitted to Gemini, so that is 1, the default. A model whose tokenizer
143
+ * counts a third more for the same text says 1.33, and its documents are planned for a window
144
+ * that much smaller.
145
+ */
146
+ tokenScale?: number;
147
+ /**
148
+ * Tokens set aside for the model's reply, when they come out of the same window as the prompt
149
+ * (Claude's `max_tokens`). The budget of a question leaves them free.
150
+ */
151
+ outputTokens?: number;
152
+ /**
153
+ * True for a model whose conversation may only grow: an earlier turn that is rewritten makes
154
+ * the request invalid (Claude ties its thinking blocks to the conversation they were written
155
+ * in). Old tool results are then not shortened to make room: when the room runs out, the
156
+ * question is answered with what it has.
157
+ */
158
+ appendOnly?: boolean;
159
+ /**
160
+ * True for a model whose provider may clear old tool results from the conversation on its side,
161
+ * before the model reads it (Claude's context editing with `clear_tool_uses`, or compaction). A
162
+ * call made again is then run again, instead of being answered with a pointer to an earlier
163
+ * result that the model may no longer have.
164
+ */
165
+ clearsToolResults?: boolean;
166
+ };
167
+ /** A model provider, as the tool loop sees it. */
168
+ export interface ModelAdapter {
169
+ /** Names the model in usage totals and messages: "gemini-3.8-flash". */
170
+ readonly id: string;
171
+ readonly capabilities: ModelCapabilities;
172
+ /**
173
+ * @deprecated Never called. The loop counts every request in the library's estimate
174
+ * (`estimateTokens`), as the documents were counted when they were uploaded, and turns that into
175
+ * this model's tokens with `capabilities.tokenScale`: set `tokenScale` instead. Kept so that
176
+ * adapters that declare it still compile; it may be removed in a later version.
177
+ */
178
+ estimateTokens?(text: string): number;
179
+ /**
180
+ * One chat request. Throw a `ModelRequestError` for an HTTP error or a connection that failed:
181
+ * the loop retries the ones worth retrying.
182
+ */
183
+ send(request: ModelRequest, hooks?: SendHooks): Promise<ModelReply>;
184
+ /**
185
+ * The size in bytes of the body `send` would post. With it, the room left for the pages of a PDF
186
+ * is exact; without it, it is estimated.
187
+ */
188
+ requestBytes?(request: ModelRequest): number;
189
+ /** A plain completion, for whole-file reads. Without it `analyze_whole_document` is not offered. */
190
+ generateText?: GenerateText;
191
+ }
192
+ /**
193
+ * What went wrong with a model request, as far as the error says:
194
+ * - "context_overflow": the request was larger than the model takes (its context window, or the
195
+ * size of the body). A smaller request can work.
196
+ * - "quota": a quota that does not come back soon (a daily cap, no credit left). Sending again
197
+ * does not help.
198
+ * - "rate_limit": too many requests or tokens for now (HTTP 429). Sending again later helps.
199
+ * - "timeout": nothing came from the model for longer than the adapter waits (`firstByteTimeoutMs`,
200
+ * `idleTimeoutMs`; status 0), or the provider or a gateway said the request timed out (HTTP 408).
201
+ * - "unreachable": no answer at all: the connection failed.
202
+ * - "server": the provider failed on its side (HTTP 5xx).
203
+ * - "auth": the key or token was refused (HTTP 401, 403).
204
+ * - "invalid": the provider refused the request as it was (another HTTP 4xx).
205
+ */
206
+ export type ModelErrorKind = "context_overflow" | "quota" | "rate_limit" | "timeout" | "unreachable" | "server" | "auth" | "invalid";
207
+ /** How an error was told apart, with the numbers of an overflow when the message gives them. */
208
+ export type ModelErrorClass = {
209
+ kind: ModelErrorKind;
210
+ /** The most input tokens the model takes, as the provider counts them. */
211
+ limitTokens?: number;
212
+ /**
213
+ * The tokens of the refused request that the provider counted against the window: its input,
214
+ * and for some providers (OpenRouter, vLLM) the output it would have taken too.
215
+ */
216
+ requestedTokens?: number;
217
+ };
218
+ /**
219
+ * Tells what kind of failure an HTTP status and an error message are (see `ModelErrorKind`).
220
+ * `code` is the provider's own word, when it gives one (OpenAI's `error.code`, Claude's
221
+ * `error.type`, Gemini's `error.status`); `details` is a Gemini error's `details`. A quota is told
222
+ * from those, from HTTP 402 (payment required), and from words that only a quota uses (no credit
223
+ * left, a spending cap, a quota per day): Gemini says "You exceeded your current quota" of a limit
224
+ * per minute too, which a wait mends.
225
+ */
226
+ export declare function classifyModelError(status: number, message: string, signals?: {
227
+ code?: string | undefined;
228
+ details?: unknown;
229
+ }): ModelErrorClass;
230
+ /**
231
+ * A model request that failed: the provider answered with an HTTP error, or could not be reached
232
+ * (`status` 0). `retryAfterMs` is the wait the provider asked for, when it named one. `kind` says
233
+ * what went wrong (see `ModelErrorKind`); for a request larger than the model takes,
234
+ * `limitTokens` and `requestedTokens` are the provider's numbers, when its message gives them.
235
+ */
236
+ export declare class ModelRequestError extends Error {
237
+ readonly status: number;
238
+ readonly retryAfterMs?: number;
239
+ readonly kind: ModelErrorKind;
240
+ readonly limitTokens?: number;
241
+ readonly requestedTokens?: number;
242
+ constructor(message: string, status: number, options?: {
243
+ retryAfterMs?: number;
244
+ cause?: unknown;
245
+ /** The kind, when the adapter knows it (a timeout). Otherwise it is told from the status and the message. */
246
+ kind?: ModelErrorKind;
247
+ /** The provider's own word for the error, used to tell its kind. */
248
+ code?: string | undefined;
249
+ /** The `details` of a Gemini error, used to tell its kind. */
250
+ details?: unknown;
251
+ });
252
+ }
253
+ /** The kind of a model error, when it has one: a `ModelRequestError`'s, or that of an error with the same field. */
254
+ export declare function errorKindOf(error: unknown): ModelErrorKind | undefined;
255
+ /**
256
+ * For a request refused as larger than the tokens a minute (or a day) of the provider allows, not
257
+ * than the model's window: that period. Undefined for any other error.
258
+ */
259
+ export declare function rateAllowanceOf(error: unknown): "minute" | "day" | undefined;
260
+ /** Some document IDs were never uploaded, have expired, or belong to another owner. */
261
+ export declare class DocumentsNotFoundError extends Error {
262
+ readonly ids: string[];
263
+ constructor(ids: string[]);
264
+ }
265
+ /** Usage of one question: every request it made, whole-file part reads included, in all and by model. */
266
+ export type UsageTotals = ModelUsage & {
267
+ /** Requests that were answered. One that failed and was sent again counts once. */
268
+ requests: number;
269
+ byModel: Record<string, ModelUsage & {
270
+ requests: number;
271
+ }>;
272
+ };
273
+ /** Sums the usage of the requests of one question. */
274
+ export declare class UsageMeter {
275
+ readonly totals: UsageTotals;
276
+ add(model: string, usage: Partial<ModelUsage> | undefined): void;
277
+ }
278
+ //# sourceMappingURL=model.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../src/model.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAEtF;;;;GAIG;AACH,MAAM,MAAM,QAAQ,GAAG;IAAE,EAAE,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAEtG,sDAAsD;AACtD,MAAM,MAAM,UAAU,GAAG;IAAE,IAAI,EAAE,Q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U,GAAG;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CAC5D,CAAC;AAEF,sDAAsD;AACtD,qBAAa,UAAU;IACrB,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAgD;IAE5E,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,UAAU,CAAC,GAAG,SAAS,GAAG,IAAI;CAUjE"}
package/dist/model.js ADDED
@@ -0,0 +1,222 @@
1
+ /**
2
+ * A result of a stored tool round, as it is sent again in a later question: without
3
+ * `tool_turns_left`, which counted the tool turns its own question had left, not those of the
4
+ * later one. The same result when it has none.
5
+ */
6
+ export function laterResult(result) {
7
+ if (result === null || typeof result !== "object" || !("tool_turns_left" in result))
8
+ return result;
9
+ const { tool_turns_left: _left, ...rest } = result;
10
+ return rest;
11
+ }
12
+ /** Wording of a request larger than the model takes, across providers. */
13
+ const OVERFLOW_WORDING = [
14
+ /context[_ ]length[_ ]exceeded/i,
15
+ /maximum context length/i,
16
+ /prompt is too long/i,
17
+ /input token count\b.{0,40}\bexceeds/i,
18
+ // Vertex AI: "Unable to submit request because the input token count is N but model only supports up to M."
19
+ /input token count is [\d,]+ but/i,
20
+ /model only supports up to/i,
21
+ /exceeds? the maximum number of tokens/i,
22
+ /maximum context (?:size|window)/i,
23
+ /too large for (?:the )?model with [\d,]+ maximum context/i,
24
+ /exceeds? (?:the )?(?:available |model'?s? )?context (?:size|window|length)/i,
25
+ /request payload size exceeds/i,
26
+ /reduce the length of the messages/i,
27
+ /input tokens? exceeds?/i,
28
+ /request_too_large/i,
29
+ // Claude 3.7 to 4.1: "input length and `max_tokens` exceed context limit: 188240 + 21333 > 200000".
30
+ /exceed context limit/i,
31
+ // Text Generation Inference (Hugging Face, Together): "Input validation error: `inputs` tokens +
32
+ // `max_new_tokens` must be <= 32769. Given: 40000 `inputs` tokens and 1024 `max_new_tokens`".
33
+ /`?inputs`? tokens \+ `?max_new_tokens`? must be <=/i,
34
+ /`?inputs`? must have less than [\d,]+ tokens/i,
35
+ // LM Studio: "Trying to keep the first 9000 tokens when context the overflows. However, the model
36
+ // is loaded with context length of only 4096 tokens, which is not enough."
37
+ /loaded with context length of only/i,
38
+ /tokens to keep from the initial prompt is greater than the context length/i,
39
+ // Amazon Bedrock: "Input is too long for requested model."
40
+ /input is too long for (?:the )?(?:requested )?model/i,
41
+ ];
42
+ /**
43
+ * A request larger than the tokens a whole minute (or day) allows. OpenAI: "Request too large for
44
+ * gpt-4o in organization org-… on tokens per min (TPM): Limit 30000, Requested 45237.", as HTTP 429.
45
+ * Groq says "tokens per minute", as HTTP 413. No wait lets it pass: only a smaller request can.
46
+ */
47
+ const RATE_TOO_SMALL = /request too large for .{0,200}\bon tokens per (min(?:ute)?|day)\b/i;
48
+ /** Wording of throttling, which can share words with an overflow ("too many tokens, please wait"). */
49
+ const THROTTLE_WORDING = /rate.?limit|too many requests|please (?:wait|try again later)|per (?:minute|second|day)\b|\b[TR]PM\b|throttl/i;
50
+ const LIMIT_WORDING = [
51
+ /maximum context length is ([\d,]+)/i,
52
+ // The Gemini API puts the number in parentheses; Vertex AI (November 2026) does not:
53
+ // "The input token count exceeds the maximum number of tokens allowed 1048576."
54
+ /maximum number of tokens allowed \(?([\d,]+)/i,
55
+ /> ?([\d,]+) maximum/i,
56
+ /with ([\d,]+) maximum context/i,
57
+ /configured limit of ([\d,]+) tokens/i,
58
+ /supports up to ([\d,]+)/i,
59
+ /context limit: [\d,]+ \+ [\d,]+ > ([\d,]+)/i,
60
+ /must be <= ?([\d,]+)/i,
61
+ /must have less than ([\d,]+) tokens/i,
62
+ /context length of only ([\d,]+) tokens/i,
63
+ /\bLimit:? ([\d,]+), Requested\b/i,
64
+ ];
65
+ const REQUESTED_WORDING = [
66
+ /input token count \(([\d,]+)\)/i,
67
+ /input token count is ([\d,]+)/i,
68
+ /context limit: ([\d,]+) \+/i,
69
+ /\(([\d,]+) in the messages/i,
70
+ /resulted in ([\d,]+) tokens/i,
71
+ /too long: ([\d,]+) tokens/i,
72
+ /prompt contains ([\d,]+) tokens/i,
73
+ /requested (?:about )?([\d,]+) tokens/i,
74
+ // vLLM since its errors changed: "However, your request has 40000 input tokens."
75
+ /your request has ([\d,]+) input tokens/i,
76
+ /\bGiven: ([\d,]+)/i,
77
+ /\bRequested:? ([\d,]+)/i,
78
+ ];
79
+ /**
80
+ * Wording of a quota that does not come back soon: no credit left (DeepSeek's "Insufficient
81
+ * Balance", OpenRouter's "Insufficient credits", Claude's "Your credit balance is too low"), or a
82
+ * spending cap that was reached (Claude's "You have reached your API usage limits").
83
+ */
84
+ const QUOTA_WORDING = /credit balance is too low|insufficient (?:balance|credits?|funds)|reached your (?:specified )?API usage limits/i;
85
+ /** A quota per day named in the message alone: Vertex AI's "Quota exceeded for …requests_per_day_per_project…". */
86
+ const DAILY_QUOTA_WORDING = /quota.{0,200}(?:per[_ -]?day|PerDay)/i;
87
+ function firstNumber(message, patterns) {
88
+ for (const pattern of patterns) {
89
+ const found = pattern.exec(message)?.[1];
90
+ if (!found)
91
+ continue;
92
+ const value = Number(found.replace(/,/g, ""));
93
+ if (Number.isFinite(value) && value > 0)
94
+ return value;
95
+ }
96
+ return undefined;
97
+ }
98
+ /** True when a Gemini error says a quota per day ran out: `google.rpc.QuotaFailure` with a "PerDay" quota. */
99
+ function dailyQuota(details) {
100
+ if (!Array.isArray(details))
101
+ return false;
102
+ return details.some((detail) => {
103
+ const violations = detail?.violations;
104
+ return Array.isArray(violations) && violations.some((violation) => {
105
+ const id = violation;
106
+ return /per.?day/i.test(`${String(id?.quotaId ?? "")} ${String(id?.quotaMetric ?? "")}`);
107
+ });
108
+ });
109
+ }
110
+ /** A request larger than the model takes, with the numbers its message gives. */
111
+ function overflowOf(message) {
112
+ const limitTokens = firstNumber(message, LIMIT_WORDING);
113
+ const requestedTokens = firstNumber(message, REQUESTED_WORDING);
114
+ return { kind: "context_overflow", ...(limitTokens ? { limitTokens } : {}), ...(requestedTokens ? { requestedTokens } : {}) };
115
+ }
116
+ /** True when a Gemini error names an API key that is not valid (it comes as HTTP 400). */
117
+ const keyRefused = (details) => Array.isArray(details) && details.some((detail) => detail?.reason === "API_KEY_INVALID");
118
+ /**
119
+ * Tells what kind of failure an HTTP status and an error message are (see `ModelErrorKind`).
120
+ * `code` is the provider's own word, when it gives one (OpenAI's `error.code`, Claude's
121
+ * `error.type`, Gemini's `error.status`); `details` is a Gemini error's `details`. A quota is told
122
+ * from those, from HTTP 402 (payment required), and from words that only a quota uses (no credit
123
+ * left, a spending cap, a quota per day): Gemini says "You exceeded your current quota" of a limit
124
+ * per minute too, which a wait mends.
125
+ */
126
+ export function classifyModelError(status, message, signals = {}) {
127
+ const { code, details } = signals;
128
+ if (status === 0)
129
+ return { kind: "unreachable" };
130
+ if (code === "insufficient_quota" || status === 402 || (status === 429 && (dailyQuota(details) || DAILY_QUOTA_WORDING.test(message))))
131
+ return { kind: "quota" };
132
+ if (status < 500 && QUOTA_WORDING.test(message))
133
+ return { kind: "quota" };
134
+ // Larger than the provider lets through in a minute: a context overflow, though it comes as 429,
135
+ // and though its words are those of a rate limit.
136
+ if ((status === 429 || status === 413) && RATE_TOO_SMALL.test(message))
137
+ return overflowOf(message);
138
+ const throttled = THROTTLE_WORDING.test(message);
139
+ const overflow = !throttled && status !== 429 && status < 500 && (status === 413 || code === "context_length_exceeded" || code === "request_too_large" || OVERFLOW_WORDING.some((pattern) => pattern.test(message)));
140
+ if (overflow)
141
+ return overflowOf(message);
142
+ if (status === 429)
143
+ return { kind: "rate_limit" };
144
+ if (status === 408)
145
+ return { kind: "timeout" };
146
+ if (status >= 500)
147
+ return { kind: "server" };
148
+ if (status === 401 || status === 403 || keyRefused(details))
149
+ return { kind: "auth" };
150
+ return { kind: "invalid" };
151
+ }
152
+ /**
153
+ * A model request that failed: the provider answered with an HTTP error, or could not be reached
154
+ * (`status` 0). `retryAfterMs` is the wait the provider asked for, when it named one. `kind` says
155
+ * what went wrong (see `ModelErrorKind`); for a request larger than the model takes,
156
+ * `limitTokens` and `requestedTokens` are the provider's numbers, when its message gives them.
157
+ */
158
+ export class ModelRequestError extends Error {
159
+ status;
160
+ retryAfterMs;
161
+ kind;
162
+ limitTokens;
163
+ requestedTokens;
164
+ constructor(message, status, options = {}) {
165
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
166
+ this.name = "ModelRequestError";
167
+ this.status = status;
168
+ if (options.retryAfterMs !== undefined)
169
+ this.retryAfterMs = options.retryAfterMs;
170
+ const found = classifyModelError(status, message, { code: options.code, details: options.details });
171
+ this.kind = options.kind ?? found.kind;
172
+ if (this.kind === "context_overflow") {
173
+ if (found.limitTokens)
174
+ this.limitTokens = found.limitTokens;
175
+ if (found.requestedTokens)
176
+ this.requestedTokens = found.requestedTokens;
177
+ }
178
+ }
179
+ }
180
+ /** The kind of a model error, when it has one: a `ModelRequestError`'s, or that of an error with the same field. */
181
+ export function errorKindOf(error) {
182
+ const kind = error?.kind;
183
+ return typeof kind === "string" ? kind : undefined;
184
+ }
185
+ /**
186
+ * For a request refused as larger than the tokens a minute (or a day) of the provider allows, not
187
+ * than the model's window: that period. Undefined for any other error.
188
+ */
189
+ export function rateAllowanceOf(error) {
190
+ if (errorKindOf(error) !== "context_overflow" || !(error instanceof Error))
191
+ return undefined;
192
+ const period = RATE_TOO_SMALL.exec(error.message)?.[1];
193
+ if (period === undefined)
194
+ return undefined;
195
+ return period.toLowerCase() === "day" ? "day" : "minute";
196
+ }
197
+ /** Some document IDs were never uploaded, have expired, or belong to another owner. */
198
+ export class DocumentsNotFoundError extends Error {
199
+ ids;
200
+ constructor(ids) {
201
+ super(`${ids.length === 1 ? "A document is" : `${ids.length} documents are`} no longer available: ${ids.join(", ")}. Upload ${ids.length === 1 ? "it" : "them"} again.`);
202
+ this.ids = ids;
203
+ this.name = "DocumentsNotFoundError";
204
+ }
205
+ }
206
+ const EMPTY_USAGE = { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, thoughtTokens: 0 };
207
+ /** Sums the usage of the requests of one question. */
208
+ export class UsageMeter {
209
+ totals = { requests: 0, ...EMPTY_USAGE, byModel: {} };
210
+ add(model, usage) {
211
+ const of = (this.totals.byModel[model] ??= { requests: 0, ...EMPTY_USAGE });
212
+ for (const sum of [this.totals, of]) {
213
+ sum.requests++;
214
+ for (const key of Object.keys(EMPTY_USAGE)) {
215
+ const value = usage?.[key];
216
+ if (typeof value === "number" && Number.isFinite(value) && value > 0)
217
+ sum[key] += value;
218
+ }
219
+ }
220
+ }
221
+ }
222
+ //# sourceMappingURL=model.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.js","sourceRoot":"","sources":["../src/model.ts"],"names":[],"mappings":"AA6CA;;;;GAIG;AACH,MAAM,UAAU,WAAW,CAAC,MAAkB;IAC5C,IAAI,MAAM,KAAK,IAAI,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC,CAAC,iBAAiB,IAAI,MAAM,CAAC;QAAE,OAAO,MAAM,CAAC;IACnG,MAAM,EAAE,eAAe,EAAE,KAAK,EAAE,GAAG,IAAI,EAAE,GAAG,MAAM,CAAC;IACnD,OAAO,IAAI,CAAC;AACd,CAAC;AA8JD,0EAA0E;AAC1E,MAAM,gBAAgB,GAAG;IACvB,gCAAgC;IAChC,yBAAyB;IACzB,qBAAqB;IACrB,sCAAsC;IACtC,4GAA4G;IAC5G,kCAAkC;IAClC,4BAA4B;IAC5B,wCAAwC;IACxC,kCAAkC;IAClC,2DAA2D;IAC3D,6EAA6E;IAC7E,+BAA+B;IAC/B,oCAAoC;IACpC,yBAAyB;IACzB,oBAAoB;IACpB,oGAAoG;IACpG,uBAAuB;IACvB,iGAAiG;IACjG,8FAA8F;IAC9F,qDAAqD;IACrD,+CAA+C;IAC/C,kGAAkG;IAClG,2EAA2E;IAC3E,qCAAqC;IACrC,4EAA4E;IAC5E,2DAA2D;IAC3D,sDAAsD;CACvD,CAAC;AACF;;;;GAIG;AACH,MAAM,cAAc,GAAG,oEAAoE,CAAC;AAC5F,sGA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AACtD,MAAM,OAAO,UAAU;IACZ,MAAM,GAAgB,EAAE,QAAQ,EAAE,CAAC,EAAE,GAAG,WAAW,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;IAE5E,GAAG,CAAC,KAAa,EAAE,KAAsC;QACvD,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,EAAE,QAAQ,EAAE,CAAC,EAAE,GAAG,WAAW,EAAE,CAAC,CAAC;QAC5E,KAAK,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE,CAAC;YACpC,GAAG,CAAC,QAAQ,EAAE,CAAC;YACf,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,WAAW,CAA4B,EAAE,CAAC;gBACtE,MAAM,KAAK,GAAG,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC;gBAC3B,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC;oBAAE,GAAG,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC;YAC1F,CAAC;QACH,CAAC;IACH,CAAC;CACF"}
@@ -3,7 +3,11 @@ import { type LargeFiles } from "../library.js";
3
3
  export type DocumentHandlerOptions = {
4
4
  /**
5
5
  * The signed-in user for this request. When set, uploads are owned by that user and other
6
- * users cannot read or delete them. Return undefined to allow anonymous access.
6
+ * users cannot read or delete them. Return undefined to allow anonymous access. An empty owner
7
+ * ("", spaces only, or null from JavaScript) is the server's mistake: the upload is answered with a 500
8
+ * `{"error":"Upload failed (empty owner)."}`, before its body is read. So is an owner from
9
+ * JavaScript that is neither a string nor a finite number (`req.user` in place of `req.user.id`,
10
+ * say): `{"error":"Upload failed (owner is not a string)."}`.
7
11
  *
8
12
  * To refuse a request, throw an error with a `status` (or `statusCode`) between 400 and 599, as
9
13
  * the `http-errors` package makes: the handler answers with that status and the error's message.
@@ -14,10 +18,21 @@ export type DocumentHandlerOptions = {
14
18
  };
15
19
  /**
16
20
  * The handlers answer every request themselves, errors included, and never reject: they can be
17
- * called without a `catch`, from `node:http` or from Express 4.
21
+ * called without a `catch`, from `node:http`, from Express 4 (which does not catch a rejected
22
+ * promise) or from Express 5.
18
23
  */
19
24
  export type DocumentHandlers = {
20
- /** POST: the body is the raw file. Name it with an `X-File-Name` header (URI-encoded) or `?name=`. */
25
+ /**
26
+ * POST: the body is the raw file. Name it with an `X-File-Name` header (URI-encoded) or `?name=`.
27
+ * A file that cannot be read is answered with a 422 and the reason. A store that fails while it
28
+ * writes is answered with a 500 that does not repeat its message, unless its error has a status.
29
+ *
30
+ * When the request's `Accept` header names `text/event-stream` (not with `q=0`, nor only through a
31
+ * wildcard), a file that passes the checks of the name, the owner and the size (which still
32
+ * answer with an HTTP error) is answered with a 200 and Server-Sent Events: the ingest's events (`ingest.start`, `ingest.progress`…), ending
33
+ * with `ingest.finish`, whose data is the summary a 201 would hold, or `ingest.error`, whose data
34
+ * is `{ error: { message, status } }` with the message and status a JSON answer would have.
35
+ */
21
36
  upload(request: IncomingMessage, response: ServerResponse): Promise<void>;
22
37
  /** GET: the document's summary, or 404. */
23
38
  get(request: IncomingMessage, response: ServerResponse, id: string): Promise<void>;
@@ -26,7 +41,8 @@ export type DocumentHandlers = {
26
41
  };
27
42
  /**
28
43
  * Upload, get, and delete handlers for any Node HTTP server (node:http, Express, Fastify via
29
- * `request.raw`/`reply.raw`, Next.js API routes on the Node runtime). Responses are JSON.
44
+ * `request.raw`/`reply.raw`, Next.js API routes on the Node runtime). Responses are JSON, except an upload that asks for
45
+ * `text/event-stream`: it is answered with its ingest events.
30
46
  */
31
47
  export declare function createDocumentHandlers(files: LargeFiles, options?: DocumentHandlerOptions): DocumentHandlers;
32
48
  //# sourceMappingURL=handlers.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"handlers.d.ts","sourceRoot":"","sources":["../../src/node/handlers.ts"],"names":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