llm-large-files 0.8.2 → 0.10.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 (288) hide show
  1. package/CHANGELOG.md +981 -0
  2. package/README.md +22 -17
  3. package/dist/access.d.ts +128 -0
  4. package/dist/access.d.ts.map +1 -0
  5. package/dist/access.js +234 -0
  6. package/dist/access.js.map +1 -0
  7. package/dist/aggregate.d.ts +6 -0
  8. package/dist/aggregate.d.ts.map +1 -1
  9. package/dist/aggregate.js +86 -13
  10. package/dist/aggregate.js.map +1 -1
  11. package/dist/analyze.d.ts +4 -0
  12. package/dist/analyze.d.ts.map +1 -1
  13. package/dist/analyze.js +2 -2
  14. package/dist/analyze.js.map +1 -1
  15. package/dist/answer-info.d.ts +26 -0
  16. package/dist/answer-info.d.ts.map +1 -0
  17. package/dist/answer-info.js +32 -0
  18. package/dist/answer-info.js.map +1 -0
  19. package/dist/anthropic/adapter.d.ts +5 -1
  20. package/dist/anthropic/adapter.d.ts.map +1 -1
  21. package/dist/anthropic/adapter.js +35 -10
  22. package/dist/anthropic/adapter.js.map +1 -1
  23. package/dist/ask.d.ts +159 -14
  24. package/dist/ask.d.ts.map +1 -1
  25. package/dist/ask.js +743 -113
  26. package/dist/ask.js.map +1 -1
  27. package/dist/cache.d.ts +12 -3
  28. package/dist/cache.d.ts.map +1 -1
  29. package/dist/cache.js +18 -5
  30. package/dist/cache.js.map +1 -1
  31. package/dist/citations.d.ts +36 -0
  32. package/dist/citations.d.ts.map +1 -0
  33. package/dist/citations.js +291 -0
  34. package/dist/citations.js.map +1 -0
  35. package/dist/encoding.js +5 -3
  36. package/dist/encoding.js.map +1 -1
  37. package/dist/error-info.d.ts +70 -0
  38. package/dist/error-info.d.ts.map +1 -0
  39. package/dist/error-info.js +253 -0
  40. package/dist/error-info.js.map +1 -0
  41. package/dist/errors.d.ts +74 -8
  42. package/dist/errors.d.ts.map +1 -1
  43. package/dist/errors.js +104 -15
  44. package/dist/errors.js.map +1 -1
  45. package/dist/events.d.ts +57 -13
  46. package/dist/events.d.ts.map +1 -1
  47. package/dist/events.js +42 -11
  48. package/dist/events.js.map +1 -1
  49. package/dist/evidence.d.ts +4 -2
  50. package/dist/evidence.d.ts.map +1 -1
  51. package/dist/evidence.js +35 -5
  52. package/dist/evidence.js.map +1 -1
  53. package/dist/extract.d.ts +32 -8
  54. package/dist/extract.d.ts.map +1 -1
  55. package/dist/extract.js +52 -36
  56. package/dist/extract.js.map +1 -1
  57. package/dist/gemini/adapter.d.ts +54 -7
  58. package/dist/gemini/adapter.d.ts.map +1 -1
  59. package/dist/gemini/adapter.js +152 -41
  60. package/dist/gemini/adapter.js.map +1 -1
  61. package/dist/gemini/chat.d.ts +38 -53
  62. package/dist/gemini/chat.d.ts.map +1 -1
  63. package/dist/gemini/chat.js +20 -25
  64. package/dist/gemini/chat.js.map +1 -1
  65. package/dist/gemini/endpoints.d.ts +59 -11
  66. package/dist/gemini/endpoints.d.ts.map +1 -1
  67. package/dist/gemini/endpoints.js +33 -7
  68. package/dist/gemini/endpoints.js.map +1 -1
  69. package/dist/gemini/errors.d.ts +39 -5
  70. package/dist/gemini/errors.d.ts.map +1 -1
  71. package/dist/gemini/errors.js +70 -9
  72. package/dist/gemini/errors.js.map +1 -1
  73. package/dist/gemini/generate.d.ts +53 -2
  74. package/dist/gemini/generate.d.ts.map +1 -1
  75. package/dist/gemini/generate.js +100 -50
  76. package/dist/gemini/generate.js.map +1 -1
  77. package/dist/gemini/index.d.ts +4 -4
  78. package/dist/gemini/index.d.ts.map +1 -1
  79. package/dist/http.d.ts +41 -3
  80. package/dist/http.d.ts.map +1 -1
  81. package/dist/http.js +40 -2
  82. package/dist/http.js.map +1 -1
  83. package/dist/index.d.ts +13 -8
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +8 -5
  86. package/dist/index.js.map +1 -1
  87. package/dist/ingest.d.ts +78 -0
  88. package/dist/ingest.d.ts.map +1 -0
  89. package/dist/ingest.js +893 -0
  90. package/dist/ingest.js.map +1 -0
  91. package/dist/library.d.ts +295 -33
  92. package/dist/library.d.ts.map +1 -1
  93. package/dist/library.js +458 -650
  94. package/dist/library.js.map +1 -1
  95. package/dist/map-reduce.d.ts +176 -10
  96. package/dist/map-reduce.d.ts.map +1 -1
  97. package/dist/map-reduce.js +807 -61
  98. package/dist/map-reduce.js.map +1 -1
  99. package/dist/model.d.ts +79 -6
  100. package/dist/model.d.ts.map +1 -1
  101. package/dist/model.js +80 -4
  102. package/dist/model.js.map +1 -1
  103. package/dist/node/handlers.d.ts +247 -14
  104. package/dist/node/handlers.d.ts.map +1 -1
  105. package/dist/node/handlers.js +491 -227
  106. package/dist/node/handlers.js.map +1 -1
  107. package/dist/node/index.d.ts +3 -2
  108. package/dist/node/index.d.ts.map +1 -1
  109. package/dist/node/index.js +2 -1
  110. package/dist/node/index.js.map +1 -1
  111. package/dist/node/ingest-child.d.ts +7 -1
  112. package/dist/node/ingest-child.d.ts.map +1 -1
  113. package/dist/node/ingest-child.js +19 -4
  114. package/dist/node/ingest-child.js.map +1 -1
  115. package/dist/node/isolated.d.ts +3 -1
  116. package/dist/node/isolated.d.ts.map +1 -1
  117. package/dist/node/isolated.js +11 -4
  118. package/dist/node/isolated.js.map +1 -1
  119. package/dist/node/originals.d.ts +19 -0
  120. package/dist/node/originals.d.ts.map +1 -0
  121. package/dist/node/originals.js +82 -0
  122. package/dist/node/originals.js.map +1 -0
  123. package/dist/node/spool.d.ts +106 -0
  124. package/dist/node/spool.d.ts.map +1 -0
  125. package/dist/node/spool.js +378 -0
  126. package/dist/node/spool.js.map +1 -0
  127. package/dist/node/sse.d.ts +6 -4
  128. package/dist/node/sse.d.ts.map +1 -1
  129. package/dist/node/sse.js +9 -7
  130. package/dist/node/sse.js.map +1 -1
  131. package/dist/openai/adapter.d.ts +5 -1
  132. package/dist/openai/adapter.d.ts.map +1 -1
  133. package/dist/openai/adapter.js +53 -12
  134. package/dist/openai/adapter.js.map +1 -1
  135. package/dist/output-limit.d.ts +2 -1
  136. package/dist/output-limit.d.ts.map +1 -1
  137. package/dist/output-limit.js +5 -2
  138. package/dist/output-limit.js.map +1 -1
  139. package/dist/pdf-layout.d.ts.map +1 -1
  140. package/dist/pdf-layout.js +71 -12
  141. package/dist/pdf-layout.js.map +1 -1
  142. package/dist/pdf-outline.d.ts +71 -0
  143. package/dist/pdf-outline.d.ts.map +1 -0
  144. package/dist/pdf-outline.js +414 -0
  145. package/dist/pdf-outline.js.map +1 -0
  146. package/dist/plan.d.ts +137 -7
  147. package/dist/plan.d.ts.map +1 -1
  148. package/dist/plan.js +248 -26
  149. package/dist/plan.js.map +1 -1
  150. package/dist/prepare.d.ts +50 -0
  151. package/dist/prepare.d.ts.map +1 -0
  152. package/dist/prepare.js +207 -0
  153. package/dist/prepare.js.map +1 -0
  154. package/dist/ranged.d.ts +16 -11
  155. package/dist/ranged.d.ts.map +1 -1
  156. package/dist/ranged.js +56 -12
  157. package/dist/ranged.js.map +1 -1
  158. package/dist/retry.d.ts +3 -1
  159. package/dist/retry.d.ts.map +1 -1
  160. package/dist/retry.js +6 -2
  161. package/dist/retry.js.map +1 -1
  162. package/dist/scope.d.ts +25 -0
  163. package/dist/scope.d.ts.map +1 -0
  164. package/dist/scope.js +60 -0
  165. package/dist/scope.js.map +1 -0
  166. package/dist/search.d.ts +7 -0
  167. package/dist/search.d.ts.map +1 -1
  168. package/dist/search.js +72 -10
  169. package/dist/search.js.map +1 -1
  170. package/dist/source.d.ts +60 -0
  171. package/dist/source.d.ts.map +1 -0
  172. package/dist/source.js +170 -0
  173. package/dist/source.js.map +1 -0
  174. package/dist/stores.d.ts +126 -31
  175. package/dist/stores.d.ts.map +1 -1
  176. package/dist/stores.js +655 -141
  177. package/dist/stores.js.map +1 -1
  178. package/dist/testing/fake-fetch.d.ts +31 -0
  179. package/dist/testing/fake-fetch.d.ts.map +1 -0
  180. package/dist/testing/fake-fetch.js +66 -0
  181. package/dist/testing/fake-fetch.js.map +1 -0
  182. package/dist/testing/fake-model.d.ts +38 -0
  183. package/dist/testing/fake-model.d.ts.map +1 -0
  184. package/dist/testing/fake-model.js +62 -0
  185. package/dist/testing/fake-model.js.map +1 -0
  186. package/dist/testing/index.d.ts +7 -0
  187. package/dist/testing/index.d.ts.map +1 -0
  188. package/dist/testing/index.js +9 -0
  189. package/dist/testing/index.js.map +1 -0
  190. package/dist/testing/store-checks.d.ts +72 -0
  191. package/dist/testing/store-checks.d.ts.map +1 -0
  192. package/dist/testing/store-checks.js +619 -0
  193. package/dist/testing/store-checks.js.map +1 -0
  194. package/dist/tools.d.ts +47 -2
  195. package/dist/tools.d.ts.map +1 -1
  196. package/dist/tools.js +440 -71
  197. package/dist/tools.js.map +1 -1
  198. package/dist/types.d.ts +165 -14
  199. package/dist/types.d.ts.map +1 -1
  200. package/dist/whole-cost.d.ts +37 -0
  201. package/dist/whole-cost.d.ts.map +1 -0
  202. package/dist/whole-cost.js +46 -0
  203. package/dist/whole-cost.js.map +1 -0
  204. package/docs/README.md +21 -8
  205. package/docs/getting-started.md +18 -13
  206. package/docs/guides/anthropic.md +17 -10
  207. package/docs/guides/conversations.md +112 -47
  208. package/docs/guides/costs-and-limits.md +147 -42
  209. package/docs/guides/deployment.md +380 -86
  210. package/docs/guides/errors-and-reliability.md +317 -67
  211. package/docs/guides/explorer-model.md +4 -1
  212. package/docs/guides/openai-compatible.md +47 -7
  213. package/docs/guides/own-adapter-and-loop.md +60 -16
  214. package/docs/guides/pdfs.md +219 -36
  215. package/docs/guides/storage.md +676 -145
  216. package/docs/guides/testing.md +149 -129
  217. package/docs/guides/vertex-and-gemini.md +169 -57
  218. package/docs/guides/web-app.md +318 -80
  219. package/docs/how-it-works.md +155 -30
  220. package/docs/measurements.md +215 -13
  221. package/docs/publishing.md +185 -37
  222. package/docs/reference/anthropic.md +12 -7
  223. package/docs/reference/ask.md +415 -47
  224. package/docs/reference/errors-and-retries.md +194 -14
  225. package/docs/reference/events.md +77 -27
  226. package/docs/reference/gemini.md +252 -87
  227. package/docs/reference/library.md +886 -178
  228. package/docs/reference/node.md +659 -111
  229. package/docs/reference/openai.md +21 -10
  230. package/docs/reference/testing.md +311 -0
  231. package/docs/reference/tools.md +285 -30
  232. package/docs/security.md +404 -78
  233. package/docs/troubleshooting.md +151 -70
  234. package/docs/upgrading-0.10.md +472 -0
  235. package/docs/upgrading-0.9.md +890 -0
  236. package/package.json +16 -3
  237. package/src/access.ts +267 -0
  238. package/src/aggregate.ts +92 -14
  239. package/src/analyze.ts +2 -2
  240. package/src/answer-info.ts +45 -0
  241. package/src/anthropic/adapter.ts +40 -11
  242. package/src/ask.ts +866 -115
  243. package/src/cache.ts +20 -5
  244. package/src/citations.ts +294 -0
  245. package/src/encoding.ts +6 -4
  246. package/src/error-info.ts +290 -0
  247. package/src/errors.ts +131 -15
  248. package/src/events.ts +112 -24
  249. package/src/evidence.ts +35 -5
  250. package/src/extract.ts +56 -34
  251. package/src/gemini/adapter.ts +196 -43
  252. package/src/gemini/chat.ts +63 -78
  253. package/src/gemini/endpoints.ts +89 -16
  254. package/src/gemini/errors.ts +74 -11
  255. package/src/gemini/generate.ts +147 -57
  256. package/src/gemini/index.ts +4 -4
  257. package/src/http.ts +65 -4
  258. package/src/index.ts +13 -8
  259. package/src/ingest.ts +958 -0
  260. package/src/library.ts +711 -651
  261. package/src/map-reduce.ts +858 -70
  262. package/src/model.ts +113 -9
  263. package/src/node/handlers.ts +709 -221
  264. package/src/node/index.ts +14 -2
  265. package/src/node/ingest-child.ts +24 -6
  266. package/src/node/isolated.ts +11 -4
  267. package/src/node/originals.ts +78 -0
  268. package/src/node/spool.ts +379 -0
  269. package/src/node/sse.ts +9 -7
  270. package/src/openai/adapter.ts +56 -13
  271. package/src/output-limit.ts +5 -2
  272. package/src/pdf-layout.ts +69 -11
  273. package/src/pdf-outline.ts +400 -0
  274. package/src/plan.ts +287 -36
  275. package/src/prepare.ts +253 -0
  276. package/src/ranged.ts +48 -14
  277. package/src/retry.ts +6 -2
  278. package/src/scope.ts +63 -0
  279. package/src/search.ts +69 -13
  280. package/src/source.ts +178 -0
  281. package/src/stores.ts +702 -142
  282. package/src/testing/fake-fetch.ts +80 -0
  283. package/src/testing/fake-model.ts +78 -0
  284. package/src/testing/index.ts +11 -0
  285. package/src/testing/store-checks.ts +660 -0
  286. package/src/tools.ts +461 -73
  287. package/src/types.ts +151 -14
  288. package/src/whole-cost.ts +64 -0
@@ -1,7 +1,7 @@
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
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";
4
+ import { base64, idleWatch, noteCutReply, notJsonMessage, parseArguments, partTimer, readArguments, readJson, replyEnd, resolveHeaderSource, resolveSecret, streamedReply, unreachableReason, until, waitText, type HeaderSource, type IdleWatch, type PartTimer, type SecretSource } from "../http.js";
5
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";
6
6
  import { completeWithinLimit, type LimitedReply } from "../output-limit.js";
7
7
  import { retryAfterMs } from "../retry.js";
@@ -75,7 +75,11 @@ export type OpenAiCompatibleOptions = {
75
75
  pageTokens?: number | undefined;
76
76
  /** This model's tokens for one token of the library's estimate. Defaults to 1. */
77
77
  tokenScale?: number | undefined;
78
- /** Milliseconds a part read may take. Defaults to 180,000. */
78
+ /**
79
+ * Milliseconds a part read may take, its whole reply included. Defaults to 180,000; 0 sets none
80
+ * (since 0.10.0). A part past it is an `OpenAiRequestError` of kind "timeout" and status 0 (since
81
+ * 0.10.0; before, the abort of the timer), which a whole-file read sends again once.
82
+ */
79
83
  timeoutMs?: number | undefined;
80
84
  /**
81
85
  * The longest wait, in milliseconds, for the first piece of a chat reply. Headers do not count:
@@ -312,6 +316,9 @@ export function fromOpenAiMessages(history: OpenAiMessage[]): { system: string;
312
316
  return { system: system.join("\n\n"), messages };
313
317
  }
314
318
 
319
+ /** An ID for a call that came without one: no round of another question has it. */
320
+ const newCallId = (): string => `call_${randomUUID().replaceAll("-", "").slice(0, 24)}`;
321
+
315
322
  /**
316
323
  * The tool rounds a question returned (`AskResult.toolTurns`) as Chat Completions messages, for an
317
324
  * application that keeps its history in that form: put them between the question and its answer.
@@ -320,7 +327,7 @@ export function openAiToolTurns(turns: ToolTurn[]): OpenAiMessage[] {
320
327
  return turns.flatMap((turn, index) => {
321
328
  // A call that came without an ID is given one that no round of another question has: these
322
329
  // 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) }));
330
+ const answers = turn.calls.map(({ result, ...call }) => ({ call: call.id ? call : { ...call, id: newCallId() }, result: laterResult(result) }));
324
331
  return roundMessages({ role: "tools", calls: answers.map((answer) => answer.call), answers }, index + 1, false);
325
332
  });
326
333
  }
@@ -375,10 +382,15 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
375
382
  };
376
383
  };
377
384
 
378
- const post = async (body: Json, signal: AbortSignal | undefined, stopped: () => boolean, lost: (error: unknown) => OpenAiRequestError = unreachable, headers?: Record<string, string>): Promise<Response> => {
385
+ /**
386
+ * Sends a request. A `bounded` one (a part read, whose time limit is its signal) stops waiting
387
+ * when the signal aborts, even for a fetch that does not stop then itself.
388
+ */
389
+ const post = async (body: Json, signal: AbortSignal | undefined, stopped: () => boolean, lost: (error: unknown) => OpenAiRequestError = unreachable, headers?: Record<string, string>, bounded = false): Promise<Response> => {
379
390
  let response: Response;
380
391
  try {
381
- response = await fetchImpl(url, { method: "POST", headers: headers ?? await headersNow(), body: JSON.stringify(body), ...(signal ? { signal } : {}) });
392
+ const sent = fetchImpl(url, { method: "POST", headers: headers ?? await headersNow(), body: JSON.stringify(body), ...(signal ? { signal } : {}) });
393
+ response = await (bounded ? until(sent, signal) : sent);
382
394
  } catch (error) {
383
395
  if (stopped()) throw error;
384
396
  throw lost(error);
@@ -389,8 +401,17 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
389
401
 
390
402
  const generateText: GenerateText = ({ system, prompt, maxOutputTokens, signal, onTruncated, onUsage }) => {
391
403
  const send = async (limit: number): Promise<LimitedReply> => {
392
- const timeout = AbortSignal.timeout(options.timeoutMs ?? 180_000);
393
- const stopped = () => Boolean(signal?.aborted) || timeout.aborted;
404
+ const timer = partTimer(signal, options.timeoutMs);
405
+ try {
406
+ return await read(limit, timer);
407
+ } finally {
408
+ timer.stop();
409
+ }
410
+ };
411
+ /** One part read, within its time limit: past it, a timeout. A stop of the caller's is reported as it is. */
412
+ const read = async (limit: number, timer: PartTimer): Promise<LimitedReply> => {
413
+ const stopped = () => Boolean(signal?.aborted);
414
+ const lost = (error: unknown) => (timer.expired && !signal?.aborted ? tooSlow(timer.limitMs) : unreachable(error));
394
415
  const body = (field: string): Json => ({
395
416
  model: options.model,
396
417
  messages: [{ role: systemRole, content: system }, { role: "user", content: prompt }],
@@ -401,15 +422,15 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
401
422
  // The name this request is sent with: part reads run together, and another may learn the other name meanwhile.
402
423
  const sent = maxTokensField;
403
424
  try {
404
- response = await post(body(sent), signal ? AbortSignal.any([signal, timeout]) : timeout, stopped);
425
+ response = await post(body(sent), timer.signal, stopped, lost, undefined, true);
405
426
  } catch (error) {
406
427
  // A server that knows only the other name of the output limit: it is sent that one, now and from now on.
407
428
  if (options.maxTokensField !== undefined || !refusesField(error, sent)) throw error;
408
429
  const other = sent === "max_tokens" ? "max_completion_tokens" : "max_tokens";
409
430
  if (maxTokensField === sent) maxTokensField = other;
410
- response = await post(body(other), signal ? AbortSignal.any([signal, timeout]) : timeout, stopped);
431
+ response = await post(body(other), timer.signal, stopped, lost, undefined, true);
411
432
  }
412
- const data = await readJson<Json>(response, stopped, unreachable, undefined, (error) => new OpenAiRequestError(notJsonMessage("The model's", response), response.status, { kind: "invalid", cause: error }));
433
+ const data = await readJson<Json>(response, stopped, lost, timer.signal ? { pulse: () => undefined, signal: timer.signal } : undefined, (error) => new OpenAiRequestError(notJsonMessage("The model's", response), response.status, { kind: "invalid", cause: error }));
413
434
  // An error in a body that came with 200 (OpenRouter, once generation has started): thrown as
414
435
  // a stream's error is, with its status, so that a 502 is sent again rather than read as no text.
415
436
  const failed = bodyError(data);
@@ -467,6 +488,13 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
467
488
  let finish: unknown;
468
489
  let usage: Json | undefined;
469
490
  let text = "";
491
+ /** The provider's ID of the response and the model that wrote it, when it names them. */
492
+ let responseId: string | undefined;
493
+ let responseModel: string | undefined;
494
+ const named = (data: Json | undefined) => {
495
+ if (typeof data?.id === "string" && data.id) responseId = data.id;
496
+ if (typeof data?.model === "string" && data.model) responseModel = data.model;
497
+ };
470
498
  // A body that is no JSON (a gateway's page) is not the model's reply, and is not sent again.
471
499
  const notJson = (error: unknown) => new OpenAiRequestError(notJsonMessage("The model's", answer), answer.status, { kind: "invalid", cause: error });
472
500
  let response = answer;
@@ -492,6 +520,7 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
492
520
  for await (const chunk of parseSseJson<Json>(response.body, { onData: watch.pulse, onDone: () => { ended = true; end.reached(); }, signal: end.signal })) {
493
521
  const failed = (Array.isArray(chunk) ? chunk[0] : chunk)?.error;
494
522
  if (failed) throw streamFailure(failed);
523
+ named(chunk);
495
524
  if (chunk.usage) usage = chunk.usage as Json;
496
525
  const choice = chunk.choices?.[0] as Json | undefined;
497
526
  if (!choice) continue;
@@ -508,8 +537,11 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
508
537
  if (typeof delta.reasoning === "string") reasoningText += delta.reasoning;
509
538
  if (Array.isArray(delta.reasoning_details)) for (const detail of delta.reasoning_details as unknown[]) addReasoningDetail(details, detail);
510
539
  for (const part of (Array.isArray(delta.tool_calls) ? delta.tool_calls : []) as Json[]) {
511
- // A call arrives in pieces under its index: first its ID and name, then its arguments, a few characters at a time.
512
- const at = typeof part.index === "number" ? part.index : part.id || toolCalls.length === 0 ? toolCalls.length : toolCalls.length - 1;
540
+ // A call arrives in pieces under its index: first its ID and name, then its arguments, a
541
+ // few characters at a time. A server that sends no index starts a new call with an ID
542
+ // that is not the last call's: one that sends the ID with every piece adds to that call.
543
+ const last = toolCalls[toolCalls.length - 1] as Json | undefined;
544
+ const at = typeof part.index === "number" ? part.index : toolCalls.length === 0 || (part.id && part.id !== last?.id) ? toolCalls.length : toolCalls.length - 1;
513
545
  const call = (toolCalls[at] ??= { type: "function", function: { name: "", arguments: "" } });
514
546
  for (const [key, value] of Object.entries(part)) {
515
547
  if (key !== "index" && key !== "function" && value !== undefined && value !== null && !(key === "id" && call.id)) call[key] = value;
@@ -565,6 +597,7 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
565
597
  message = (choice?.message ?? { role: "assistant", content: null }) as Json;
566
598
  finish = choice?.finish_reason;
567
599
  usage = data.usage as Json | undefined;
600
+ named(data);
568
601
  // The whole reply is in hand: one that the server stopped is sent again before any of it is shown.
569
602
  if (finish === "insufficient_system_resource") throw interrupted();
570
603
  // A refusal is what the model has to say to the user, in a field of its own.
@@ -579,6 +612,9 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
579
612
  const calls: ToolCall[] = (Array.isArray(message.tool_calls) ? message.tool_calls as Json[] : [])
580
613
  .filter((call) => typeof call?.function?.name === "string" && call.function.name)
581
614
  .map((call) => {
615
+ // A call that came without an ID is given one, once, in the turn that goes back too: its
616
+ // tool message must name the same ID as the call does.
617
+ if (typeof call.id !== "string" || !call.id) call.id = newCallId();
582
618
  const read = readArguments(call.function.arguments);
583
619
  // Arguments that are not a JSON object go back as none, and so do arguments that are
584
620
  // empty: a server that reads every call of the conversation (vLLM before 0.29) refuses
@@ -586,7 +622,7 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
586
622
  const written = call.function.arguments;
587
623
  if (read.problem || typeof written !== "string" || !written.trim()) call.function = { ...call.function, arguments: read.problem ? "{}" : JSON.stringify(read.args) };
588
624
  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 } : {}) };
625
+ return { id: call.id as string, name: call.function.name as string, args: read.args, ...(problem ? { problem } : {}) };
590
626
  });
591
627
  const kind = finishOfOpenAi(finish);
592
628
  return {
@@ -596,6 +632,8 @@ export function openAiCompatible(options: OpenAiCompatibleOptions): ModelAdapter
596
632
  ...(typeof finish === "string" ? { finishReason: finish } : {}),
597
633
  ...(kind ? { finish: kind } : {}),
598
634
  ...(finish === "content_filter" && !text && calls.length === 0 ? { blockReason: "content_filter" } : {}),
635
+ ...(responseId ? { responseId } : {}),
636
+ ...(responseModel ? { responseModel } : {}),
599
637
  ...(usage ? { usage: usageOf(usage), providerUsage: usage } : {}),
600
638
  };
601
639
  }
@@ -612,6 +650,11 @@ function silent(waitMs: number): OpenAiRequestError {
612
650
  return new OpenAiRequestError(`The model sent nothing for ${Math.round(waitMs / 1_000)} s.`, 0, { kind: "timeout" });
613
651
  }
614
652
 
653
+ /** A part read whose whole reply did not come within its time limit (`timeoutMs`). */
654
+ function tooSlow(limitMs: number): OpenAiRequestError {
655
+ return new OpenAiRequestError(`The model took longer than ${waitText(limitMs)} to answer.`, 0, { kind: "timeout" });
656
+ }
657
+
615
658
  /** A reply the server stopped because it ran short (DeepSeek's `insufficient_system_resource`). */
616
659
  function interrupted(): OpenAiRequestError {
617
660
  return new OpenAiRequestError("The model's server stopped the reply: it ran short of resources.", 503);
@@ -1,5 +1,6 @@
1
1
  // A plain completion on a model that may think its output limit away: shared by the part readers
2
2
  // of every adapter.
3
+ import { until } from "./http.js";
3
4
 
4
5
  /**
5
6
  * A model that thinks counts its thoughts in its output limit. Asked for 4,096 tokens of notes on
@@ -63,7 +64,8 @@ export type LimitedReply = {
63
64
  * was learned is kept under `model` (a URL, or a URL and a model name): later requests start with
64
65
  * the larger limit, and a model that refused it (HTTP 400, but not for a request too large for the
65
66
  * 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.
67
+ * larger than that limit. Requests that arrive while the first one to a model is on its way wait for it,
68
+ * until their own signal aborts.
67
69
  */
68
70
  export async function completeWithinLimit(model: string, maxOutputTokens: number, send: (limit: number) => Promise<LimitedReply>, options: {
69
71
  signal?: AbortSignal | undefined;
@@ -77,7 +79,8 @@ export async function completeWithinLimit(model: string, maxOutputTokens: number
77
79
  if (!answered.has(model)) {
78
80
  const first = firstRequests.get(model);
79
81
  if (first) {
80
- await first;
82
+ // The first request may be another question's: this one's abort ends the wait at once.
83
+ await until(first, signal);
81
84
  signal?.throwIfAborted();
82
85
  } else {
83
86
  firstRequests.set(model, new Promise<void>((resolve) => {
package/src/pdf-layout.ts CHANGED
@@ -476,19 +476,77 @@ function isNumeric(text: string): boolean {
476
476
  return digits > 0 && letters * 2 <= digits;
477
477
  }
478
478
 
479
- /** The text of one line's pieces in one cell, in reading order. */
480
- function joinPieces(pieces: Piece[], rightToLeft: boolean): string {
481
- const ordered = [...pieces].sort((left, right) => (rightToLeft ? right.x0 - left.x0 : left.x0 - right.x0));
482
- let text = "";
483
- ordered.forEach((piece, index) => {
484
- if (index > 0) {
485
- const previous = ordered[index - 1]!;
486
- const gap = rightToLeft ? previous.x0 - piece.x1 : piece.x0 - previous.x1;
487
- if (gap > VISIBLE_GAP * Math.max(piece.size, previous.size)) text += " ";
479
+ type Direction = "ltr" | "rtl";
480
+
481
+ /** Arabic-Indic and Persian digits and the Arabic separators: in the right-to-left block, but numbers. */
482
+ const ARABIC_DIGITS = /[\u0660-\u0669\u066b\u066c\u06f0-\u06f9]/g;
483
+
484
+ /** The direction of the letters of a piece; none for a piece without letters, or with as many of each. */
485
+ function letterDirection(text: string): Direction | undefined {
486
+ const rightToLeft = (text.match(RIGHT_TO_LEFT)?.length ?? 0) - (text.match(ARABIC_DIGITS)?.length ?? 0);
487
+ const leftToRight = text.match(LEFT_TO_RIGHT)?.length ?? 0;
488
+ return rightToLeft === leftToRight ? undefined : rightToLeft > leftToRight ? "rtl" : "ltr";
489
+ }
490
+
491
+ /** The directions of the nearest pieces before and after `index` that have one. */
492
+ function around(directions: Array<Direction | undefined>, index: number): [Direction | undefined, Direction | undefined] {
493
+ let before: Direction | undefined;
494
+ for (let other = index - 1; other >= 0 && !before; other--) before = directions[other];
495
+ let after: Direction | undefined;
496
+ for (let other = index + 1; other < directions.length && !after; other++) after = directions[other];
497
+ return [before, after];
498
+ }
499
+
500
+ /**
501
+ * The direction each piece is read in, for pieces from left to right; `spaced[i]` says whether a
502
+ * gap shows between pieces i and i + 1. A number reads left to right when it touches, with no gap
503
+ * and through pieces without letters only, a left-to-right word ("AB" + "-12") or another number
504
+ * ("8,300" + ",000"). Any other piece without letters takes the direction of the pieces on both
505
+ * sides when they agree, else the region's: in a right-to-left cell, "09:00 - 17:00" is laid out
506
+ * with the first time on the right, and "16 GB" with the number on the right, as two items.
507
+ */
508
+ function pieceDirections(pieces: Piece[], spaced: boolean[], rightToLeft: boolean): Direction[] {
509
+ const letters = pieces.map((piece) => letterDirection(piece.text));
510
+ const isNumber = pieces.map((piece, index) => !letters[index] && /[\d\u0660-\u0669\u06f0-\u06f9]/.test(piece.text));
511
+ /** Whether the piece at `index` touches a left-to-right word or a number, walking by `step` through pieces without letters. */
512
+ const touches = (index: number, step: 1 | -1): boolean => {
513
+ for (let other = index + step; other >= 0 && other < pieces.length && !spaced[Math.min(other, other - step)]; other += step) {
514
+ if (letters[other] === "ltr" || isNumber[other]) return true;
515
+ if (letters[other]) return false;
488
516
  }
489
- text += piece.text;
517
+ return false;
518
+ };
519
+ const numbers = letters.map((direction, index) => {
520
+ if (direction || !isNumber[index]) return direction;
521
+ return touches(index, -1) || touches(index, 1) ? "ltr" : undefined;
490
522
  });
491
- return text;
523
+ return numbers.map((direction, index) => {
524
+ const [before, after] = around(numbers, index);
525
+ return direction ?? (before && before === after ? before : rightToLeft ? "rtl" : "ltr");
526
+ });
527
+ }
528
+
529
+ /**
530
+ * The text of one line's pieces in one cell, in reading order. Pieces of the other direction next
531
+ * to each other (a Latin name in a Hebrew cell, a Hebrew phrase in an English one) are a run that
532
+ * reads in its own direction; the runs follow each other in the direction of the region.
533
+ */
534
+ function joinPieces(pieces: Piece[], rightToLeft: boolean): string {
535
+ const byX = [...pieces].sort((left, right) => left.x0 - right.x0);
536
+ const spaced = byX.slice(1).map((piece, index) => piece.x0 - byX[index]!.x1 > VISIBLE_GAP * Math.max(piece.size, byX[index]!.size));
537
+ const directions = pieceDirections(byX, spaced, rightToLeft);
538
+ // From left to right: each piece, then a space where the gap to the next piece on the page shows.
539
+ const parts = byX.flatMap((piece, index) => (index < spaced.length ? [piece.text, spaced[index] ? " " : ""] : [piece.text]));
540
+ // Turn each run of the other direction around, then the whole cell when it is right to left: a
541
+ // run keeps its order, and each space stays between the two pieces it was between on the page.
542
+ let start = 0;
543
+ directions.forEach((direction, index) => {
544
+ if (directions[index + 1] === direction) return;
545
+ if (direction !== (rightToLeft ? "rtl" : "ltr")) parts.splice(2 * start, 2 * (index - start) + 1, ...parts.slice(2 * start, 2 * index + 1).reverse());
546
+ start = index + 1;
547
+ });
548
+ if (rightToLeft) parts.reverse();
549
+ return parts.join("");
492
550
  }
493
551
 
494
552
  /** Columns that are their own run of whole sentences in file order: page columns, not table columns. */