llm-large-files 0.5.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (285) hide show
  1. package/CHANGELOG.md +1719 -466
  2. package/README.md +190 -60
  3. package/dist/analyze.d.ts +8 -1
  4. package/dist/analyze.d.ts.map +1 -1
  5. package/dist/analyze.js +198 -54
  6. package/dist/analyze.js.map +1 -1
  7. package/dist/anthropic/adapter.d.ts +14 -3
  8. package/dist/anthropic/adapter.d.ts.map +1 -1
  9. package/dist/anthropic/adapter.js +194 -40
  10. package/dist/anthropic/adapter.js.map +1 -1
  11. package/dist/ask.d.ts +63 -7
  12. package/dist/ask.d.ts.map +1 -1
  13. package/dist/ask.js +1131 -214
  14. package/dist/ask.js.map +1 -1
  15. package/dist/decode.d.ts +19 -0
  16. package/dist/decode.d.ts.map +1 -0
  17. package/dist/decode.js +97 -0
  18. package/dist/decode.js.map +1 -0
  19. package/dist/encoding.d.ts +17 -0
  20. package/dist/encoding.d.ts.map +1 -0
  21. package/dist/encoding.js +852 -0
  22. package/dist/encoding.js.map +1 -0
  23. package/dist/errors.d.ts +59 -0
  24. package/dist/errors.d.ts.map +1 -1
  25. package/dist/errors.js +80 -0
  26. package/dist/errors.js.map +1 -1
  27. package/dist/events.d.ts +339 -0
  28. package/dist/events.d.ts.map +1 -0
  29. package/dist/events.js +163 -0
  30. package/dist/events.js.map +1 -0
  31. package/dist/evidence.d.ts +2 -0
  32. package/dist/evidence.d.ts.map +1 -1
  33. package/dist/evidence.js +9 -2
  34. package/dist/evidence.js.map +1 -1
  35. package/dist/extract.d.ts +26 -7
  36. package/dist/extract.d.ts.map +1 -1
  37. package/dist/extract.js +180 -314
  38. package/dist/extract.js.map +1 -1
  39. package/dist/gemini/adapter.d.ts +17 -8
  40. package/dist/gemini/adapter.d.ts.map +1 -1
  41. package/dist/gemini/adapter.js +117 -66
  42. package/dist/gemini/adapter.js.map +1 -1
  43. package/dist/gemini/chat.d.ts +23 -3
  44. package/dist/gemini/chat.d.ts.map +1 -1
  45. package/dist/gemini/chat.js +6 -2
  46. package/dist/gemini/chat.js.map +1 -1
  47. package/dist/gemini/endpoints.d.ts +5 -1
  48. package/dist/gemini/endpoints.d.ts.map +1 -1
  49. package/dist/gemini/endpoints.js +11 -2
  50. package/dist/gemini/endpoints.js.map +1 -1
  51. package/dist/gemini/errors.d.ts +9 -4
  52. package/dist/gemini/errors.d.ts.map +1 -1
  53. package/dist/gemini/errors.js +32 -0
  54. package/dist/gemini/errors.js.map +1 -1
  55. package/dist/gemini/generate.d.ts +10 -2
  56. package/dist/gemini/generate.d.ts.map +1 -1
  57. package/dist/gemini/generate.js +33 -10
  58. package/dist/gemini/generate.js.map +1 -1
  59. package/dist/gemini/index.d.ts +3 -3
  60. package/dist/gemini/index.d.ts.map +1 -1
  61. package/dist/gemini/index.js +2 -2
  62. package/dist/gemini/index.js.map +1 -1
  63. package/dist/gemini/sse.d.ts +1 -1
  64. package/dist/gemini/sse.d.ts.map +1 -1
  65. package/dist/gemini/sse.js +1 -1
  66. package/dist/gemini/sse.js.map +1 -1
  67. package/dist/groups.d.ts +54 -0
  68. package/dist/groups.d.ts.map +1 -0
  69. package/dist/groups.js +136 -0
  70. package/dist/groups.js.map +1 -0
  71. package/dist/html.d.ts +11 -0
  72. package/dist/html.d.ts.map +1 -0
  73. package/dist/html.js +1112 -0
  74. package/dist/html.js.map +1 -0
  75. package/dist/http.d.ts +116 -0
  76. package/dist/http.d.ts.map +1 -1
  77. package/dist/http.js +347 -1
  78. package/dist/http.js.map +1 -1
  79. package/dist/index.d.ts +13 -7
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +7 -5
  82. package/dist/index.js.map +1 -1
  83. package/dist/library.d.ts +67 -5
  84. package/dist/library.d.ts.map +1 -1
  85. package/dist/library.js +449 -93
  86. package/dist/library.js.map +1 -1
  87. package/dist/limiter.d.ts +2 -1
  88. package/dist/limiter.d.ts.map +1 -1
  89. package/dist/limiter.js +3 -2
  90. package/dist/limiter.js.map +1 -1
  91. package/dist/map-reduce.d.ts +28 -1
  92. package/dist/map-reduce.d.ts.map +1 -1
  93. package/dist/map-reduce.js +240 -52
  94. package/dist/map-reduce.js.map +1 -1
  95. package/dist/model.d.ts +84 -2
  96. package/dist/model.d.ts.map +1 -1
  97. package/dist/model.js +190 -2
  98. package/dist/model.js.map +1 -1
  99. package/dist/node/handlers.d.ts +20 -4
  100. package/dist/node/handlers.d.ts.map +1 -1
  101. package/dist/node/handlers.js +184 -28
  102. package/dist/node/handlers.js.map +1 -1
  103. package/dist/node/index.d.ts +4 -0
  104. package/dist/node/index.d.ts.map +1 -1
  105. package/dist/node/index.js +2 -0
  106. package/dist/node/index.js.map +1 -1
  107. package/dist/node/ingest-child.d.ts +38 -0
  108. package/dist/node/ingest-child.d.ts.map +1 -0
  109. package/dist/node/ingest-child.js +42 -0
  110. package/dist/node/ingest-child.js.map +1 -0
  111. package/dist/node/isolated.d.ts +88 -0
  112. package/dist/node/isolated.d.ts.map +1 -0
  113. package/dist/node/isolated.js +381 -0
  114. package/dist/node/isolated.js.map +1 -0
  115. package/dist/node/sse.d.ts +59 -0
  116. package/dist/node/sse.d.ts.map +1 -0
  117. package/dist/node/sse.js +174 -0
  118. package/dist/node/sse.js.map +1 -0
  119. package/dist/office.d.ts +105 -0
  120. package/dist/office.d.ts.map +1 -0
  121. package/dist/office.js +1092 -0
  122. package/dist/office.js.map +1 -0
  123. package/dist/openai/adapter.d.ts +29 -5
  124. package/dist/openai/adapter.d.ts.map +1 -1
  125. package/dist/openai/adapter.js +325 -37
  126. package/dist/openai/adapter.js.map +1 -1
  127. package/dist/output-limit.d.ts +14 -2
  128. package/dist/output-limit.d.ts.map +1 -1
  129. package/dist/output-limit.js +39 -10
  130. package/dist/output-limit.js.map +1 -1
  131. package/dist/pause.d.ts +24 -0
  132. package/dist/pause.d.ts.map +1 -0
  133. package/dist/pause.js +38 -0
  134. package/dist/pause.js.map +1 -0
  135. package/dist/pdf-pages.d.ts +32 -2
  136. package/dist/pdf-pages.d.ts.map +1 -1
  137. package/dist/pdf-pages.js +277 -20
  138. package/dist/pdf-pages.js.map +1 -1
  139. package/dist/pdf-pictures.d.ts +30 -3
  140. package/dist/pdf-pictures.d.ts.map +1 -1
  141. package/dist/pdf-pictures.js +50 -8
  142. package/dist/pdf-pictures.js.map +1 -1
  143. package/dist/pdf-work.d.ts +40 -0
  144. package/dist/pdf-work.d.ts.map +1 -0
  145. package/dist/pdf-work.js +734 -0
  146. package/dist/pdf-work.js.map +1 -0
  147. package/dist/peers.d.ts +8 -0
  148. package/dist/peers.d.ts.map +1 -0
  149. package/dist/peers.js +32 -0
  150. package/dist/peers.js.map +1 -0
  151. package/dist/plan.d.ts +22 -4
  152. package/dist/plan.d.ts.map +1 -1
  153. package/dist/plan.js +61 -12
  154. package/dist/plan.js.map +1 -1
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +4 -2
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +23 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +33 -3
  161. package/dist/retry.js.map +1 -1
  162. package/dist/search.d.ts +107 -24
  163. package/dist/search.d.ts.map +1 -1
  164. package/dist/search.js +803 -149
  165. package/dist/search.js.map +1 -1
  166. package/dist/sse.d.ts +35 -2
  167. package/dist/sse.d.ts.map +1 -1
  168. package/dist/sse.js +145 -31
  169. package/dist/sse.js.map +1 -1
  170. package/dist/stores.d.ts.map +1 -1
  171. package/dist/stores.js +5 -2
  172. package/dist/stores.js.map +1 -1
  173. package/dist/text-index.d.ts +9 -1
  174. package/dist/text-index.d.ts.map +1 -1
  175. package/dist/text-index.js +28 -9
  176. package/dist/text-index.js.map +1 -1
  177. package/dist/text.d.ts +87 -3
  178. package/dist/text.d.ts.map +1 -1
  179. package/dist/text.js +526 -24
  180. package/dist/text.js.map +1 -1
  181. package/dist/tools.d.ts +61 -1
  182. package/dist/tools.d.ts.map +1 -1
  183. package/dist/tools.js +461 -46
  184. package/dist/tools.js.map +1 -1
  185. package/dist/types.d.ts +103 -4
  186. package/dist/types.d.ts.map +1 -1
  187. package/dist/word-styles.d.ts +102 -0
  188. package/dist/word-styles.d.ts.map +1 -0
  189. package/dist/word-styles.js +419 -0
  190. package/dist/word-styles.js.map +1 -0
  191. package/dist/xlsx.d.ts +23 -0
  192. package/dist/xlsx.d.ts.map +1 -0
  193. package/dist/xlsx.js +511 -0
  194. package/dist/xlsx.js.map +1 -0
  195. package/dist/xml-stream.d.ts +55 -0
  196. package/dist/xml-stream.d.ts.map +1 -0
  197. package/dist/xml-stream.js +235 -0
  198. package/dist/xml-stream.js.map +1 -0
  199. package/dist/zip-directory.d.ts +43 -0
  200. package/dist/zip-directory.d.ts.map +1 -0
  201. package/dist/zip-directory.js +130 -0
  202. package/dist/zip-directory.js.map +1 -0
  203. package/docs/README.md +288 -0
  204. package/docs/api.md +37 -381
  205. package/docs/configuration.md +28 -558
  206. package/docs/getting-started.md +407 -223
  207. package/docs/guides/anthropic.md +590 -0
  208. package/docs/guides/conversations.md +629 -0
  209. package/docs/guides/costs-and-limits.md +728 -0
  210. package/docs/guides/deployment.md +720 -0
  211. package/docs/guides/errors-and-reliability.md +748 -0
  212. package/docs/guides/explorer-model.md +399 -0
  213. package/docs/guides/openai-compatible.md +602 -0
  214. package/docs/guides/own-adapter-and-loop.md +1169 -0
  215. package/docs/guides/pdfs.md +1024 -0
  216. package/docs/guides/storage.md +731 -0
  217. package/docs/guides/testing.md +1203 -0
  218. package/docs/guides/vertex-and-gemini.md +717 -0
  219. package/docs/guides/web-app.md +1590 -0
  220. package/docs/how-it-works.md +1035 -164
  221. package/docs/measurements.md +881 -0
  222. package/docs/publishing.md +274 -46
  223. package/docs/reference/anthropic.md +427 -0
  224. package/docs/reference/ask.md +910 -0
  225. package/docs/reference/errors-and-retries.md +760 -0
  226. package/docs/reference/events.md +1001 -0
  227. package/docs/reference/gemini.md +827 -0
  228. package/docs/reference/library.md +1598 -0
  229. package/docs/reference/node.md +706 -0
  230. package/docs/reference/openai.md +385 -0
  231. package/docs/reference/tools.md +1031 -0
  232. package/docs/security.md +940 -101
  233. package/docs/troubleshooting.md +1410 -0
  234. package/package.json +7 -3
  235. package/src/analyze.ts +204 -49
  236. package/src/anthropic/adapter.ts +200 -40
  237. package/src/ask.ts +1151 -210
  238. package/src/decode.ts +89 -0
  239. package/src/encoding.ts +850 -0
  240. package/src/errors.ts +125 -0
  241. package/src/events.ts +451 -0
  242. package/src/evidence.ts +11 -2
  243. package/src/extract.ts +191 -308
  244. package/src/gemini/adapter.ts +127 -70
  245. package/src/gemini/chat.ts +28 -4
  246. package/src/gemini/endpoints.ts +12 -2
  247. package/src/gemini/errors.ts +34 -1
  248. package/src/gemini/generate.ts +42 -13
  249. package/src/gemini/index.ts +3 -3
  250. package/src/gemini/sse.ts +1 -1
  251. package/src/groups.ts +162 -0
  252. package/src/html.ts +1071 -0
  253. package/src/http.ts +376 -1
  254. package/src/index.ts +29 -6
  255. package/src/library.ts +498 -93
  256. package/src/limiter.ts +6 -1
  257. package/src/map-reduce.ts +252 -51
  258. package/src/model.ts +244 -4
  259. package/src/node/handlers.ts +196 -31
  260. package/src/node/index.ts +4 -0
  261. package/src/node/ingest-child.ts +61 -0
  262. package/src/node/isolated.ts +464 -0
  263. package/src/node/sse.ts +198 -0
  264. package/src/office.ts +1047 -0
  265. package/src/openai/adapter.ts +319 -38
  266. package/src/output-limit.ts +44 -8
  267. package/src/pause.ts +41 -0
  268. package/src/pdf-pages.ts +270 -20
  269. package/src/pdf-pictures.ts +56 -9
  270. package/src/pdf-work.ts +722 -0
  271. package/src/peers.ts +29 -0
  272. package/src/plan.ts +70 -12
  273. package/src/ranged.ts +4 -2
  274. package/src/retry.ts +49 -5
  275. package/src/search.ts +800 -155
  276. package/src/sse.ts +153 -28
  277. package/src/stores.ts +5 -2
  278. package/src/text-index.ts +30 -9
  279. package/src/text.ts +524 -23
  280. package/src/tools.ts +445 -46
  281. package/src/types.ts +108 -5
  282. package/src/word-styles.ts +420 -0
  283. package/src/xlsx.ts +478 -0
  284. package/src/xml-stream.ts +224 -0
  285. package/src/zip-directory.ts +136 -0
@@ -1,17 +1,24 @@
1
1
  // Any Chat Completions endpoint as a model of `askWithFiles`: OpenAI, Azure OpenAI, DeepSeek,
2
2
  // LiteLLM, vLLM, Ollama, OpenRouter, Gemini's OpenAI layer. No SDK: the caller gives the URL.
3
- import { base64, parseArguments, readArguments, resolveHeaderSource, resolveSecret, unreachableReason, type HeaderSource, type SecretSource } from "../http.js";
4
- import { ModelRequestError, type ChatMessage, type ModelAdapter, type ModelMessage, type ModelReply, type ModelRequest, type ModelTextMessage, type ModelToolRound, type SendHooks, type ToolCall, type ToolTurn } from "../model.js";
3
+ import { randomUUID } from "node:crypto";
4
+ import { base64, idleWatch, noteCutReply, notJsonMessage, parseArguments, readArguments, readJson, replyEnd, resolveHeaderSource, resolveSecret, streamedReply, unreachableReason, type HeaderSource, type IdleWatch, type SecretSource } from "../http.js";
5
+ import { laterResult, ModelRequestError, type ChatMessage, type ModelAdapter, type ModelMessage, type ModelReply, type ModelRequest, type ModelTextMessage, type ModelToolRound, type SendHooks, type ToolCall, type ToolTurn } from "../model.js";
5
6
  import { completeWithinLimit, type LimitedReply } from "../output-limit.js";
6
7
  import { retryAfterMs } from "../retry.js";
7
- import { parseSseJson } from "../sse.js";
8
+ import { eventTooLongMessage, parseSseJson, SseEventTooLongError } from "../sse.js";
8
9
  import type { GenerateText, GenerateUsage, ToolDeclaration, ToolResult } from "../types.js";
9
10
 
10
11
  /** The endpoint answered with an HTTP error, or could not be reached (`status` 0). */
11
12
  export class OpenAiRequestError extends ModelRequestError {
12
- constructor(message: string, status: number, options: { retryAfterMs?: number; cause?: unknown } = {}) {
13
+ /** The request field the error is about, when the server named it (`error.param`): "max_tokens". */
14
+ readonly param?: string;
15
+ /** The server's own word for the error (`error.code`): "unsupported_parameter". */
16
+ readonly code?: string;
17
+ constructor(message: string, status: number, options: ConstructorParameters<typeof ModelRequestError>[2] & { param?: string } = {}) {
13
18
  super(message, status, options);
14
19
  this.name = "OpenAiRequestError";
20
+ if (options.param) this.param = options.param;
21
+ if (options.code) this.code = options.code;
15
22
  }
16
23
  }
17
24
 
@@ -38,8 +45,10 @@ export type OpenAiCompatibleOptions = {
38
45
  analysisBody?: ((maxOutputTokens: number) => Record<string, unknown>) | undefined;
39
46
  /**
40
47
  * The name of the output limit in a part read. `max_completion_tokens` for api.openai.com and
41
- * Azure OpenAI, whose newer models refuse the other; `max_tokens` anywhere else, where it is the
42
- * one every server knows.
48
+ * Azure OpenAI (`*.openai.azure.com`, and the `/openai/` paths of `*.cognitiveservices.azure.com`
49
+ * and `*.services.ai.azure.com`), whose newer models refuse the other; `max_tokens` anywhere
50
+ * else, where it is the one every server knows. Left out, a server that refuses the one sent
51
+ * (HTTP 400 naming it) is sent the other, which is then kept for this adapter.
43
52
  */
44
53
  maxTokensField?: "max_tokens" | "max_completion_tokens" | undefined;
45
54
  /** "system" (the default), or "developer" for an endpoint that wants the newer name. */
@@ -68,6 +77,19 @@ export type OpenAiCompatibleOptions = {
68
77
  tokenScale?: number | undefined;
69
78
  /** Milliseconds a part read may take. Defaults to 180,000. */
70
79
  timeoutMs?: number | undefined;
80
+ /**
81
+ * The longest wait, in milliseconds, for the first piece of a chat reply. Headers do not count:
82
+ * a model that thinks sends nothing until it has thought, and a reply that is not streamed comes
83
+ * whole at the end. A request that gets nothing for that long is aborted and sent again, once.
84
+ * Defaults to 600,000. 0 waits without end.
85
+ */
86
+ firstByteTimeoutMs?: number | undefined;
87
+ /**
88
+ * The longest wait, in milliseconds, between two pieces of a chat reply once it has started to
89
+ * arrive (keep-alives count). A request that gets nothing for that long is aborted and sent
90
+ * again, once, unless text of it was shown. Defaults to 300,000. 0 waits without end.
91
+ */
92
+ idleTimeoutMs?: number | undefined;
71
93
  /** Names the model in usage totals. Defaults to `model`. */
72
94
  id?: string | undefined;
73
95
  fetch?: typeof fetch | undefined;
@@ -93,13 +115,113 @@ function usageOf(usage: Json | undefined): GenerateUsage {
93
115
  };
94
116
  }
95
117
 
96
- /** The error of a response that is not OK. Gemini's layer wraps its error in an array. */
118
+ /** The status of an error event in a stream that began with 200: from its code, or from its type. */
119
+ const STATUS_OF_ERROR: Record<string, number> = {
120
+ server_error: 500, api_error: 500, internal_error: 500, internal_server_error: 500, service_unavailable: 503,
121
+ rate_limit_exceeded: 429, rate_limit_error: 429, tokens_exceeded: 429, timeout: 408, invalid_request_error: 400,
122
+ context_length_exceeded: 400, insufficient_quota: 429,
123
+ };
124
+
125
+ /**
126
+ * The HTTP status of an error that arrived inside a stream. The response itself was 200, which says
127
+ * nothing of the error: OpenAI's own is `{ type: "server_error", code: null }`. A failure the server
128
+ * did not name is its own, 500, and is sent again like one (when no text of it was shown).
129
+ */
130
+ export function streamErrorStatus(failed: unknown): number {
131
+ if (failed && typeof failed === "object") {
132
+ const { code, type } = failed as { code?: unknown; type?: unknown };
133
+ const numeric = typeof code === "number" ? code : typeof code === "string" && /^\d{3}$/.test(code) ? Number(code) : Number.NaN;
134
+ if (numeric >= 400 && numeric <= 599) return numeric;
135
+ for (const word of [type, code]) if (typeof word === "string" && STATUS_OF_ERROR[word] !== undefined) return STATUS_OF_ERROR[word]!;
136
+ }
137
+ return 500;
138
+ }
139
+
140
+ /**
141
+ * Whether a server refused the name of the output limit (`max_tokens` or `max_completion_tokens`),
142
+ * rather than its number: "Unsupported parameter: 'max_tokens' ... Use 'max_completion_tokens'
143
+ * instead", "Unrecognized request argument supplied: max_completion_tokens". Not "max_tokens is
144
+ * too large", which can name the other field too.
145
+ */
146
+ function refusesField(error: unknown, field: string): boolean {
147
+ if (!(error instanceof OpenAiRequestError) || error.status !== 400) return false;
148
+ // A server that names the field it refuses says it plainly.
149
+ if (error.param !== undefined) return error.param === field && (error.code === "unsupported_parameter" || REFUSED.test(error.message));
150
+ const message = error.message;
151
+ if (/too large|too many|maximum|at most|exceed|must be (less|at most|<)/i.test(message) || !REFUSED.test(message)) return false;
152
+ // "Unsupported parameter: 'max_tokens' ... Use 'max_completion_tokens' instead" names both: the
153
+ // one it refuses comes first. Azure's "Could not finish the message because max_tokens or model
154
+ // output limit was reached" refuses nothing.
155
+ const named = /max_completion_tokens|max_tokens/.exec(message)?.[0];
156
+ return named === field;
157
+ }
158
+
159
+ /** Words of a server that refuses a field of the request, rather than its value. */
160
+ const REFUSED = /unsupported|unrecognized|not supported|unknown (parameter|field|argument)|not permitted|not allowed|extra (inputs|fields)/i;
161
+
162
+ /**
163
+ * Adds a piece of OpenRouter's streamed `reasoning_details` to those of the turn. Pieces of one
164
+ * detail share its `index` and type: their text is joined, and their other fields (a signature, an
165
+ * ID, the encrypted data) are kept. The details stay in the order they came, and are not changed
166
+ * otherwise: they go back to the model as they were written.
167
+ */
168
+ function addReasoningDetail(details: Json[], detail: unknown): void {
169
+ if (!detail || typeof detail !== "object") return;
170
+ const piece = detail as Json;
171
+ const same = typeof piece.index === "number" ? details.find((known) => known.index === piece.index && known.type === piece.type) : undefined;
172
+ if (!same) {
173
+ details.push({ ...piece });
174
+ return;
175
+ }
176
+ for (const [key, value] of Object.entries(piece)) {
177
+ if (value === null || value === undefined) continue;
178
+ if ((key === "text" || key === "summary") && typeof value === "string" && typeof same[key] === "string") same[key] += value;
179
+ else same[key] = value;
180
+ }
181
+ }
182
+
183
+ /**
184
+ * The error of a response that is not OK. Gemini's layer wraps its error in an array. Most servers
185
+ * put it in `error`; vLLM before its OpenAI-shaped errors, SGLang and FastChat put `message`, and
186
+ * servers built on FastAPI `detail`, at the top of the body.
187
+ */
97
188
  async function failure(response: Response): Promise<OpenAiRequestError> {
98
189
  const data = await response.json().catch(() => null) as Json | Json[] | null;
99
190
  const body = Array.isArray(data) ? data[0] : data;
100
- const message = typeof body?.error === "string" ? body.error : body?.error?.message;
191
+ const nested = body?.error && typeof body.error === "object" ? body.error as Json : undefined;
192
+ const message = [typeof body?.error === "string" ? body.error : nested?.message, body?.message, detailText(body?.detail)]
193
+ .find((text): text is string => typeof text === "string" && text.length > 0);
101
194
  const wait = retryAfterMs(response.headers, body);
102
- return new OpenAiRequestError(typeof message === "string" && message ? message : `The model returned HTTP ${response.status}.`, response.status, wait === undefined ? {} : { retryAfterMs: wait });
195
+ const own = nested ?? (body && typeof body === "object" ? body : undefined);
196
+ const param = typeof own?.param === "string" ? own.param as string : undefined;
197
+ const code = typeof own?.code === "string" ? own.code as string : undefined;
198
+ return new OpenAiRequestError(message ?? `The model returned HTTP ${response.status}.`, response.status, {
199
+ ...(wait === undefined ? {} : { retryAfterMs: wait }),
200
+ ...(param ? { param } : {}),
201
+ ...(code ? { code } : {}),
202
+ });
203
+ }
204
+
205
+ /** FastAPI's `detail`: a message, or a list of problems, each with its own `msg`. */
206
+ function detailText(detail: unknown): string | undefined {
207
+ if (typeof detail === "string") return detail;
208
+ if (!Array.isArray(detail)) return undefined;
209
+ return detail.map((problem) => (typeof (problem as Json | null)?.msg === "string" ? (problem as Json).msg as string : "")).filter(Boolean).join("; ") || undefined;
210
+ }
211
+
212
+ /** The error a reply that came with 200 holds instead of choices, when it holds one. */
213
+ function bodyError(data: unknown): unknown {
214
+ const body = (Array.isArray(data) ? data[0] : data) as Json | null | undefined;
215
+ return body && typeof body === "object" && body.error ? body.error : undefined;
216
+ }
217
+
218
+ /** An error event inside a stream, or a body, that began with 200, with the server's own word for it. */
219
+ function streamFailure(failed: unknown): OpenAiRequestError {
220
+ const named = failed && typeof failed === "object" ? failed as Json : {};
221
+ return new OpenAiRequestError(typeof failed === "string" ? failed : String(named.message ?? "The model reported an error."), streamErrorStatus(failed), {
222
+ ...(typeof named.code === "string" && named.code ? { code: named.code } : {}),
223
+ ...(typeof named.param === "string" && named.param ? { param: named.param } : {}),
224
+ });
103
225
  }
104
226
 
105
227
  const textOf = (message: ModelTextMessage): string => message.parts.map((part) => part.text ?? "").filter(Boolean).join("\n\n");
@@ -110,6 +232,30 @@ function textMessage(message: ModelTextMessage): OpenAiMessage {
110
232
  return { role: message.role, content: message.parts.map((part) => (part.native !== undefined ? part.native : { type: "text", text: part.text })) };
111
233
  }
112
234
 
235
+ /**
236
+ * Turns of the user that follow each other, made one. The loop can send the question and the
237
+ * request for an answer after it with no turn between them, and some servers (DeepSeek's reasoner,
238
+ * the chat templates of Mistral and Gemma models) refuse two user turns in a row.
239
+ */
240
+ function joinUserTurns(messages: OpenAiMessage[]): OpenAiMessage[] {
241
+ const parts = (content: unknown): unknown[] => (typeof content === "string" ? (content ? [{ type: "text", text: content }] : []) : Array.isArray(content) ? content : []);
242
+ const out: OpenAiMessage[] = [];
243
+ for (const message of messages) {
244
+ const last = out.at(-1);
245
+ if (last?.role !== "user" || message.role !== "user") {
246
+ out.push(message);
247
+ continue;
248
+ }
249
+ out[out.length - 1] = {
250
+ role: "user",
251
+ content: typeof last.content === "string" && typeof message.content === "string"
252
+ ? [last.content, message.content].filter(Boolean).join("\n\n")
253
+ : [...parts(last.content), ...parts(message.content)],
254
+ };
255
+ }
256
+ return out;
257
+ }
258
+
113
259
  /** The messages of one tool round. `number` makes the IDs of calls that came without one. */
114
260
  function roundMessages(round: ModelToolRound, number: number, pdfInput: boolean): OpenAiMessage[] {
115
261
  const idOf = (call: ToolCall, index: number) => call.id ?? `call_${number}_${index + 1}`;
@@ -172,7 +318,9 @@ export function fromOpenAiMessages(history: OpenAiMessage[]): { system: string;
172
318
  */
173
319
  export function openAiToolTurns(turns: ToolTurn[]): OpenAiMessage[] {
174
320
  return turns.flatMap((turn, index) => {
175
- const answers = turn.calls.map(({ result, ...call }) => ({ call, result }));
321
+ // A call that came without an ID is given one that no round of another question has: these
322
+ // messages are kept, and sent again next to those of later questions.
323
+ const answers = turn.calls.map(({ result, ...call }) => ({ call: call.id ? call : { ...call, id: `call_${randomUUID().replaceAll("-", "").slice(0, 24)}` }, result: laterResult(result) }));
176
324
  return roundMessages({ role: "tools", calls: answers.map((answer) => answer.call), answers }, index + 1, false);
177
325
  });
178
326
  }
@@ -181,14 +329,18 @@ export function openAiToolTurns(turns: ToolTurn[]): OpenAiMessage[] {
181
329
  export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter {
182
330
  const fetchImpl = options.fetch ?? fetch;
183
331
  const url = options.url ?? `${(options.baseUrl ?? "https://api.openai.com/v1").replace(/\/+$/, "")}/chat/completions`;
184
- const official = /(^|\.)openai\.com$|\.openai\.azure\.com$/.test((() => {
332
+ const { hostname, pathname } = (() => {
185
333
  try {
186
- return new URL(url).hostname;
334
+ return new URL(url);
187
335
  } catch {
188
- return "";
336
+ return { hostname: "", pathname: "" };
189
337
  }
190
- })());
191
- const maxTokensField = options.maxTokensField ?? (official ? "max_completion_tokens" : "max_tokens");
338
+ })();
339
+ // Azure OpenAI answers on three kinds of host. On the two it shares with other models, only its `/openai/` paths are OpenAI's.
340
+ const official = /(^|\.)openai\.com$|\.openai\.azure\.com$/.test(hostname)
341
+ || (/\.(cognitiveservices\.azure\.com|services\.ai\.azure\.com)$/.test(hostname) && pathname.includes("/openai/"));
342
+ /** The name of the output limit in a part read: changed once when the server refuses it and no name was given. */
343
+ let maxTokensField = options.maxTokensField ?? (official ? "max_completion_tokens" : "max_tokens");
192
344
  const systemRole = options.systemRole ?? "system";
193
345
  const pdfInput = options.pdfInput === true;
194
346
 
@@ -200,7 +352,7 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
200
352
  const built = new WeakMap<ModelToolRound, { number: number; messages: OpenAiMessage[] }>();
201
353
  const toMessages = (messages: ModelMessage[]): OpenAiMessage[] => {
202
354
  let rounds = 0;
203
- return messages.flatMap((message) => {
355
+ return joinUserTurns(messages.flatMap((message) => {
204
356
  if (message.role !== "tools") return [textMessage(message)];
205
357
  const number = ++rounds;
206
358
  let known = built.get(message);
@@ -209,7 +361,7 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
209
361
  built.set(message, known);
210
362
  }
211
363
  return known.messages;
212
- });
364
+ }));
213
365
  };
214
366
  const bodyOf = (request: ModelRequest, stream: boolean): Json => {
215
367
  const mustAnswer = request.toolChoice === "none";
@@ -223,13 +375,13 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
223
375
  };
224
376
  };
225
377
 
226
- const post = async (body: Json, signal: AbortSignal | undefined, stopped: () => boolean): Promise<Response> => {
378
+ const post = async (body: Json, signal: AbortSignal | undefined, stopped: () => boolean, lost: (error: unknown) => OpenAiRequestError = unreachable, headers?: Record<string, string>): Promise<Response> => {
227
379
  let response: Response;
228
380
  try {
229
- response = await fetchImpl(url, { method: "POST", headers: await headersNow(), body: JSON.stringify(body), ...(signal ? { signal } : {}) });
381
+ response = await fetchImpl(url, { method: "POST", headers: headers ?? await headersNow(), body: JSON.stringify(body), ...(signal ? { signal } : {}) });
230
382
  } catch (error) {
231
383
  if (stopped()) throw error;
232
- throw new OpenAiRequestError(`The model could not be reached${unreachableReason(error)}.`, 0, { cause: error });
384
+ throw lost(error);
233
385
  }
234
386
  if (!response.ok) throw await failure(response);
235
387
  return response;
@@ -238,19 +390,40 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
238
390
  const generateText: GenerateText = ({ system, prompt, maxOutputTokens, signal, onTruncated, onUsage }) => {
239
391
  const send = async (limit: number): Promise<LimitedReply> => {
240
392
  const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
241
- const response = await post({
393
+ const stopped = () => Boolean(signal?.aborted) || timeout.aborted;
394
+ const body = (field: string): Json => ({
242
395
  model: options.model,
243
396
  messages: [{ role: systemRole, content: system }, { role: "user", content: prompt }],
244
- [maxTokensField]: limit,
397
+ [field]: limit,
245
398
  ...options.analysisBody?.(limit),
246
- }, signal ? AbortSignal.any([signal, timeout]) : timeout, () => Boolean(signal?.aborted) || timeout.aborted);
247
- const data = await response.json() as Json;
399
+ });
400
+ let response: Response;
401
+ // The name this request is sent with: part reads run together, and another may learn the other name meanwhile.
402
+ const sent = maxTokensField;
403
+ try {
404
+ response = await post(body(sent), signal ? AbortSignal.any([signal, timeout]) : timeout, stopped);
405
+ } catch (error) {
406
+ // A server that knows only the other name of the output limit: it is sent that one, now and from now on.
407
+ if (options.maxTokensField !== undefined || !refusesField(error, sent)) throw error;
408
+ const other = sent === "max_tokens" ? "max_completion_tokens" : "max_tokens";
409
+ if (maxTokensField === sent) maxTokensField = other;
410
+ response = await post(body(other), signal ? AbortSignal.any([signal, timeout]) : timeout, stopped);
411
+ }
412
+ const data = await readJson<Json>(response, stopped, unreachable, undefined, (error) => new OpenAiRequestError(notJsonMessage("The model's", response), response.status, { kind: "invalid", cause: error }));
413
+ // An error in a body that came with 200 (OpenRouter, once generation has started): thrown as
414
+ // a stream's error is, with its status, so that a 502 is sent again rather than read as no text.
415
+ const failed = bodyError(data);
416
+ if (failed) throw streamFailure(failed);
248
417
  const used = usageOf(data.usage);
249
418
  onUsage?.(used);
250
419
  const choice = data.choices?.[0];
420
+ // DeepSeek stops a reply when its servers run short: that is the server's failure, sent again.
421
+ if (choice?.finish_reason === "insufficient_system_resource") throw interrupted();
251
422
  return {
252
423
  text: contentText(choice?.message?.content),
253
424
  cutOff: choice?.finish_reason === "length",
425
+ // Stopped by the content filter before its end: what it wrote is not all there is.
426
+ stopped: choice?.finish_reason === "content_filter",
254
427
  ...(typeof choice?.finish_reason === "string" ? { reason: choice.finish_reason } : {}),
255
428
  thoughts: used.thoughtTokens ?? 0,
256
429
  };
@@ -272,18 +445,53 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
272
445
 
273
446
  async send(request: ModelRequest, hooks: SendHooks = {}): Promise<ModelReply> {
274
447
  const stream = Boolean(hooks.onText) && options.stream !== false;
275
- const response = await post(bodyOf(request, stream), hooks.signal, () => Boolean(hooks.signal?.aborted));
448
+ // A key or token is fetched before the watch starts: the time that takes is not the model's.
449
+ const headers = await headersNow();
450
+ const watch = idleWatch(hooks.signal, { firstByteTimeoutMs: options.firstByteTimeoutMs, idleTimeoutMs: options.idleTimeoutMs });
451
+ // A request the watch aborted got nothing back for the whole wait: that is no failed connection.
452
+ const lost = (error: unknown) => (watch.expired ? silent(watch.waitedMs) : unreachable(error));
453
+ try {
454
+ // The headers are no piece of the reply: a server may send them at once and then think.
455
+ const response = await post(bodyOf(request, stream), watch.signal, () => Boolean(hooks.signal?.aborted), lost, headers);
456
+ return await readReply(response, stream, hooks, watch, lost);
457
+ } finally {
458
+ watch.stop();
459
+ }
460
+ },
461
+ };
462
+
463
+ /** The reply of a request that was answered: streamed, or in one piece. */
464
+ async function readReply(answer: Response, stream: boolean, hooks: SendHooks, watch: IdleWatch, lost: (error: unknown) => OpenAiRequestError): Promise<ModelReply> {
465
+ {
276
466
  let message: Json;
277
467
  let finish: unknown;
278
468
  let usage: Json | undefined;
279
469
  let text = "";
280
- if (stream && response.body && (response.headers.get("content-type") ?? "").includes("text/event-stream")) {
470
+ // A body that is no JSON (a gateway's page) is not the model's reply, and is not sent again.
471
+ const notJson = (error: unknown) => new OpenAiRequestError(notJsonMessage("The model's", answer), answer.status, { kind: "invalid", cause: error });
472
+ let response = answer;
473
+ let events = false;
474
+ if (stream && answer.body) {
475
+ try {
476
+ ({ events, response } = await streamedReply(answer, watch));
477
+ } catch (error) {
478
+ if (hooks.signal?.aborted) throw error;
479
+ throw noteCutReply(lost(error));
480
+ }
481
+ }
482
+ if (events && response.body) {
281
483
  let reasoning = "";
484
+ let reasoningText = "";
485
+ let refusal = "";
486
+ const details: Json[] = [];
282
487
  const toolCalls: Json[] = [];
488
+ let ended = false;
489
+ // "[DONE]" ends the reply: a server that leaves the connection open after it is not waited for.
490
+ const end = replyEnd(watch);
283
491
  try {
284
- for await (const chunk of parseSseJson<Json>(response.body)) {
492
+ for await (const chunk of parseSseJson<Json>(response.body, { onData: watch.pulse, onDone: () => { ended = true; end.reached(); }, signal: end.signal })) {
285
493
  const failed = (Array.isArray(chunk) ? chunk[0] : chunk)?.error;
286
- if (failed) throw new OpenAiRequestError(typeof failed === "string" ? failed : String(failed.message ?? "The model reported an error."), typeof failed.code === "number" ? failed.code : response.status);
494
+ if (failed) throw streamFailure(failed);
287
495
  if (chunk.usage) usage = chunk.usage as Json;
288
496
  const choice = chunk.choices?.[0] as Json | undefined;
289
497
  if (!choice) continue;
@@ -294,6 +502,11 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
294
502
  hooks.onText?.(piece);
295
503
  }
296
504
  if (typeof delta.reasoning_content === "string") reasoning += delta.reasoning_content;
505
+ // What a non-streamed reply holds in fields of its own: a refusal, and the reasoning of
506
+ // OpenRouter, whose details (a thought signature among them) must go back with the turn.
507
+ if (typeof delta.refusal === "string") refusal += delta.refusal;
508
+ if (typeof delta.reasoning === "string") reasoningText += delta.reasoning;
509
+ if (Array.isArray(delta.reasoning_details)) for (const detail of delta.reasoning_details as unknown[]) addReasoningDetail(details, detail);
297
510
  for (const part of (Array.isArray(delta.tool_calls) ? delta.tool_calls : []) as Json[]) {
298
511
  // A call arrives in pieces under its index: first its ID and name, then its arguments, a few characters at a time.
299
512
  const at = typeof part.index === "number" ? part.index : part.id || toolCalls.length === 0 ? toolCalls.length : toolCalls.length - 1;
@@ -301,45 +514,113 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
301
514
  for (const [key, value] of Object.entries(part)) {
302
515
  if (key !== "index" && key !== "function" && value !== undefined && value !== null && !(key === "id" && call.id)) call[key] = value;
303
516
  }
304
- if (typeof part.function?.name === "string") call.function.name += part.function.name;
517
+ // The name comes whole in the first piece of a call. A server that sends it again with
518
+ // each piece does not make it longer; one that sends it in pieces does.
519
+ const name = part.function?.name;
520
+ if (typeof name === "string" && name !== call.function.name) call.function.name += name;
305
521
  if (typeof part.function?.arguments === "string") call.function.arguments += part.function.arguments;
306
522
  }
307
523
  finish = choice.finish_reason ?? finish;
308
524
  }
309
525
  } catch (error) {
310
- if (hooks.signal?.aborted || error instanceof OpenAiRequestError) throw error;
311
- // The connection went while the answer was on its way.
312
- throw new OpenAiRequestError(`The model could not be reached${unreachableReason(error)}.`, 0, { cause: error });
526
+ // The reply ended with "[DONE]", and the connection then stayed open, or broke rather than
527
+ // end: what came before it is whole.
528
+ const whole = end.left(error) || (end.whole && !hooks.signal?.aborted && !(error instanceof OpenAiRequestError));
529
+ if (!whole) {
530
+ if (hooks.signal?.aborted || error instanceof OpenAiRequestError) throw error;
531
+ // An event too long to read would come again: it is not sent again, like a page in the reply's place.
532
+ if (error instanceof SseEventTooLongError) throw new OpenAiRequestError(eventTooLongMessage("The model's", error), answer.status, { kind: "invalid", cause: error });
533
+ // The connection went while the answer was on its way, or nothing came for the whole wait.
534
+ throw noteCutReply(lost(error));
535
+ }
536
+ } finally {
537
+ end.dispose();
313
538
  }
539
+ // A stream ends with a reason for its end, and with "[DONE]". One that closed with neither
540
+ // was cut off on its way (a proxy, a dropped connection): it is not a whole reply, and is
541
+ // sent again like a connection that failed, unless text of it was shown.
542
+ if (finish === undefined && !ended) throw noteCutReply(new OpenAiRequestError("The model's reply ended before it was complete.", 0));
314
543
  const calls = toolCalls.filter(Boolean);
315
- message = { role: "assistant", content: text || null, ...(reasoning ? { reasoning_content: reasoning } : {}), ...(calls.length > 0 ? { tool_calls: calls } : {}) };
544
+ message = {
545
+ role: "assistant",
546
+ content: text || null,
547
+ ...(refusal ? { refusal } : {}),
548
+ ...(reasoning ? { reasoning_content: reasoning } : {}),
549
+ ...(reasoningText ? { reasoning: reasoningText } : {}),
550
+ ...(details.length > 0 ? { reasoning_details: details } : {}),
551
+ ...(calls.length > 0 ? { tool_calls: calls } : {}),
552
+ };
553
+ // A refusal is what the model has to say to the user, as it is without streaming.
554
+ if (!text && refusal) {
555
+ text = refusal;
556
+ hooks.onText?.(refusal);
557
+ }
316
558
  } else {
317
559
  // In one piece: no streaming was asked for, or the server answered without it.
318
- const data = await response.json() as Json;
560
+ const data = await readJson<Json>(response, () => Boolean(hooks.signal?.aborted), lost, watch, notJson);
561
+ // An error in a body that came with 200, as a stream may send one: not an empty reply.
562
+ const failed = bodyError(data);
563
+ if (failed) throw streamFailure(failed);
319
564
  const choice = data.choices?.[0] as Json | undefined;
320
565
  message = (choice?.message ?? { role: "assistant", content: null }) as Json;
321
566
  finish = choice?.finish_reason;
322
567
  usage = data.usage as Json | undefined;
568
+ // The whole reply is in hand: one that the server stopped is sent again before any of it is shown.
569
+ if (finish === "insufficient_system_resource") throw interrupted();
323
570
  // A refusal is what the model has to say to the user, in a field of its own.
324
571
  text = contentText(message.content) || (typeof message.refusal === "string" ? message.refusal : "");
325
572
  if (text) hooks.onText?.(text);
326
573
  }
574
+ // DeepSeek stops a reply when its servers run short: what came of it is not the model's whole
575
+ // turn. That is the server's failure, sent again unless text of it was shown.
576
+ if (finish === "insufficient_system_resource") throw interrupted();
327
577
  // Cut off at the output limit with a call half-written: the call is answered, not run.
328
578
  const cutOff = finish === "length" ? "This call was cut off at the output limit before its arguments were complete, and was not run. Send it again." : undefined;
329
579
  const calls: ToolCall[] = (Array.isArray(message.tool_calls) ? message.tool_calls as Json[] : [])
330
580
  .filter((call) => typeof call?.function?.name === "string" && call.function.name)
331
581
  .map((call) => {
332
- const { args, problem = cutOff } = readArguments(call.function.arguments);
333
- return { ...(typeof call.id === "string" && call.id ? { id: call.id } : {}), name: call.function.name as string, args, ...(problem ? { problem } : {}) };
582
+ const read = readArguments(call.function.arguments);
583
+ // Arguments that are not a JSON object go back as none, and so do arguments that are
584
+ // empty: a server that reads every call of the conversation (vLLM before 0.29) refuses
585
+ // the next request when one is not JSON.
586
+ const written = call.function.arguments;
587
+ if (read.problem || typeof written !== "string" || !written.trim()) call.function = { ...call.function, arguments: read.problem ? "{}" : JSON.stringify(read.args) };
588
+ const problem = read.problem ?? cutOff;
589
+ return { ...(typeof call.id === "string" && call.id ? { id: call.id } : {}), name: call.function.name as string, args: read.args, ...(problem ? { problem } : {}) };
334
590
  });
591
+ const kind = finishOfOpenAi(finish);
335
592
  return {
336
593
  text,
337
594
  calls,
338
595
  raw: message,
339
596
  ...(typeof finish === "string" ? { finishReason: finish } : {}),
597
+ ...(kind ? { finish: kind } : {}),
340
598
  ...(finish === "content_filter" && !text && calls.length === 0 ? { blockReason: "content_filter" } : {}),
341
599
  ...(usage ? { usage: usageOf(usage), providerUsage: usage } : {}),
342
600
  };
343
- },
344
- };
601
+ }
602
+ }
603
+ }
604
+
605
+ /** A request that got no answer: the reason, without the stack of the HTTP client. */
606
+ function unreachable(error: unknown): OpenAiRequestError {
607
+ return new OpenAiRequestError(`The model could not be reached${unreachableReason(error)}.`, 0, { cause: error });
608
+ }
609
+
610
+ /** A request that got nothing back for the whole wait of its `IdleWatch`. */
611
+ function silent(waitMs: number): OpenAiRequestError {
612
+ return new OpenAiRequestError(`The model sent nothing for ${Math.round(waitMs / 1_000)} s.`, 0, { kind: "timeout" });
613
+ }
614
+
615
+ /** A reply the server stopped because it ran short (DeepSeek's `insufficient_system_resource`). */
616
+ function interrupted(): OpenAiRequestError {
617
+ return new OpenAiRequestError("The model's server stopped the reply: it ran short of resources.", 503);
618
+ }
619
+
620
+ /** `finish_reason` in the terms of `ModelReply.finish`. Undefined for a reason it does not know. */
621
+ function finishOfOpenAi(reason: unknown): ModelReply["finish"] {
622
+ if (reason === "stop" || reason === "tool_calls" || reason === "function_call") return "complete";
623
+ if (reason === "length") return "cut";
624
+ if (reason === "content_filter") return "filtered";
625
+ return undefined;
345
626
  }
@@ -26,11 +26,31 @@ function remember(model: string, limit: number): void {
26
26
  learnedLimits.set(model, limit);
27
27
  }
28
28
 
29
+ /**
30
+ * The errors `completeWithinLimit` threw for a reply with no text, with why the reply stopped, in
31
+ * the provider's word ("" when it did not say).
32
+ */
33
+ const noTextErrors = new WeakMap<object, string>();
34
+
35
+ /**
36
+ * Why a reply had no text, when this error is the one `completeWithinLimit` throws for it: the
37
+ * provider's word for why it stopped ("SAFETY", "refusal"), or "" when it did not say. Undefined
38
+ * for any other error. The message of that error is the package's own.
39
+ */
40
+ export function noTextReason(error: unknown): string | undefined {
41
+ return typeof error === "object" && error !== null ? noTextErrors.get(error) : undefined;
42
+ }
43
+
29
44
  /** A reply to a plain completion. */
30
45
  export type LimitedReply = {
31
46
  text: string;
32
47
  /** True when the model stopped because it reached the output limit. */
33
48
  cutOff: boolean;
49
+ /**
50
+ * True when the provider stopped the reply before its end for another reason (its safety
51
+ * filters): what it wrote is kept, and said to be incomplete, as a reply cut off at the limit is.
52
+ */
53
+ stopped?: boolean;
34
54
  /** Why it stopped, in the provider's word, for the message when there is no text. */
35
55
  reason?: string;
36
56
  /** Tokens the model spent thinking, when the provider says. */
@@ -41,8 +61,9 @@ export type LimitedReply = {
41
61
  * Sends a completion with an output limit, and once more with `THINKING_OUTPUT_TOKENS` when the
42
62
  * reply was cut off with nothing written, or with half the limit or more gone on thoughts. What
43
63
  * was learned is kept under `model` (a URL, or a URL and a model name): later requests start with
44
- * the larger limit, and a model that refused it (HTTP 400) is not asked for it again. Requests
45
- * that arrive while the first one to a model is on its way wait for it.
64
+ * the larger limit, and a model that refused it (HTTP 400, but not for a request too large for the
65
+ * window with it) is not asked for it again, nor is one whose window, or allowance a minute, is no
66
+ * larger than that limit. Requests that arrive while the first one to a model is on its way wait for it.
46
67
  */
47
68
  export async function completeWithinLimit(model: string, maxOutputTokens: number, send: (limit: number) => Promise<LimitedReply>, options: {
48
69
  signal?: AbortSignal | undefined;
@@ -83,15 +104,30 @@ export async function completeWithinLimit(model: string, maxOutputTokens: number
83
104
  } catch (error) {
84
105
  if (signal?.aborted) throw error;
85
106
  // A model or a gateway that refuses the larger limit (HTTP 400) is not asked for it again.
86
- // Any other failure says nothing about the limit: the next request starts with it. What
87
- // the first reply had is kept; with nothing in it, this error is the one to report.
88
- if ((error as { status?: unknown } | null)?.status === 400) remember(model, 0);
107
+ // A refusal of this request as too large for the window with that limit is no such refusal,
108
+ // unless the window is no larger than the limit itself: a smaller part may fit. Nothing is
109
+ // learned from it, and the next request starts as this one did. A request too large for
110
+ // what the provider allows in a minute (OpenAI's or Groq's TPM, HTTP 429 or 413) is too
111
+ // large the same way, with that allowance as the window. Any other failure says nothing
112
+ // about the limit: the next request starts with it. What the first reply had is kept; with
113
+ // nothing in it, this error is the one to report.
114
+ const { status, kind, limitTokens } = (error ?? {}) as { status?: unknown; kind?: unknown; limitTokens?: unknown };
115
+ if (status === 400 || kind === "context_overflow") {
116
+ const tooLarge = kind === "context_overflow" && !(typeof limitTokens === "number" && limitTokens <= THINKING_OUTPUT_TOKENS);
117
+ if (!tooLarge) remember(model, 0);
118
+ else if (learnedLimits.get(model) === THINKING_OUTPUT_TOKENS) learnedLimits.delete(model);
119
+ }
89
120
  if (!reply.text.trim()) throw error;
90
121
  }
91
122
  }
92
- if (!reply.text.trim()) throw new Error(`The model returned no text${reply.reason ? ` (${reply.reason})` : ""}.`);
93
- // The text stops mid-list when the output limit is reached. Say so instead of passing it off as complete.
94
- if (reply.cutOff) options.onTruncated?.();
123
+ if (!reply.text.trim()) {
124
+ const error = new Error(`The model returned no text${reply.reason ? ` (${reply.reason})` : ""}.`);
125
+ noTextErrors.set(error, reply.reason ?? "");
126
+ throw error;
127
+ }
128
+ // The text stops mid-list when the output limit is reached, or when a filter stopped it. Say so
129
+ // instead of passing it off as complete.
130
+ if (reply.cutOff || reply.stopped) options.onTruncated?.();
95
131
  return reply.text;
96
132
  } finally {
97
133
  learned();
package/src/pause.ts ADDED
@@ -0,0 +1,41 @@
1
+ /** Lets other work on the server run (an answer streaming to another user) before going on. */
2
+ export const pause = () => new Promise<void>((resolve) => setImmediate(resolve));
3
+
4
+ let turn: Promise<void> = Promise.resolve();
5
+
6
+ /**
7
+ * `pause`, taken in turns: each caller waits for the pause before it, so one slice of work runs in
8
+ * a turn of the event loop. Ten uploads that pause at once then hold the server for one slice
9
+ * between two turns, not ten.
10
+ */
11
+ export const fairPause = (): Promise<void> => (turn = turn.then(pause));
12
+
13
+ /** Work done between two pauses of a long loop, in milliseconds: short enough that nobody waits. */
14
+ const SLICE_MS = 12;
15
+
16
+ /**
17
+ * Splits a long piece of synchronous work into slices, so that one upload does not hold the whole
18
+ * server: call `maybePause()` now and then (every few thousand items), and it pauses once the
19
+ * current slice has run for about 12 ms. It also stops the work when `signal` is aborted.
20
+ */
21
+ export class TimeSlicer {
22
+ private sliceStart = performance.now();
23
+
24
+ constructor(private readonly signal?: AbortSignal) {}
25
+
26
+ /** Whether the current slice has run its time: `maybePause` would pause now. */
27
+ get due(): boolean {
28
+ return performance.now() - this.sliceStart >= SLICE_MS;
29
+ }
30
+
31
+ async maybePause(): Promise<void> {
32
+ if (this.due) await this.pauseNow();
33
+ }
34
+
35
+ /** Pauses, then starts a new slice. Throws the reason of `signal` when it was aborted meanwhile. */
36
+ async pauseNow(): Promise<void> {
37
+ await fairPause();
38
+ this.signal?.throwIfAborted();
39
+ this.sliceStart = performance.now();
40
+ }
41
+ }