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.
- package/CHANGELOG.md +981 -0
- package/README.md +22 -17
- package/dist/access.d.ts +128 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +234 -0
- package/dist/access.js.map +1 -0
- package/dist/aggregate.d.ts +6 -0
- package/dist/aggregate.d.ts.map +1 -1
- package/dist/aggregate.js +86 -13
- package/dist/aggregate.js.map +1 -1
- package/dist/analyze.d.ts +4 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +2 -2
- package/dist/analyze.js.map +1 -1
- package/dist/answer-info.d.ts +26 -0
- package/dist/answer-info.d.ts.map +1 -0
- package/dist/answer-info.js +32 -0
- package/dist/answer-info.js.map +1 -0
- package/dist/anthropic/adapter.d.ts +5 -1
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +35 -10
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +159 -14
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +743 -113
- package/dist/ask.js.map +1 -1
- package/dist/cache.d.ts +12 -3
- package/dist/cache.d.ts.map +1 -1
- package/dist/cache.js +18 -5
- package/dist/cache.js.map +1 -1
- package/dist/citations.d.ts +36 -0
- package/dist/citations.d.ts.map +1 -0
- package/dist/citations.js +291 -0
- package/dist/citations.js.map +1 -0
- package/dist/encoding.js +5 -3
- package/dist/encoding.js.map +1 -1
- package/dist/error-info.d.ts +70 -0
- package/dist/error-info.d.ts.map +1 -0
- package/dist/error-info.js +253 -0
- package/dist/error-info.js.map +1 -0
- package/dist/errors.d.ts +74 -8
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +104 -15
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +57 -13
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js +42 -11
- package/dist/events.js.map +1 -1
- package/dist/evidence.d.ts +4 -2
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +35 -5
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +32 -8
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +52 -36
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +54 -7
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +152 -41
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +38 -53
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +20 -25
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/endpoints.d.ts +59 -11
- package/dist/gemini/endpoints.d.ts.map +1 -1
- package/dist/gemini/endpoints.js +33 -7
- package/dist/gemini/endpoints.js.map +1 -1
- package/dist/gemini/errors.d.ts +39 -5
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +70 -9
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +53 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +100 -50
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +4 -4
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/http.d.ts +41 -3
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +40 -2
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +13 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -5
- package/dist/index.js.map +1 -1
- package/dist/ingest.d.ts +78 -0
- package/dist/ingest.d.ts.map +1 -0
- package/dist/ingest.js +893 -0
- package/dist/ingest.js.map +1 -0
- package/dist/library.d.ts +295 -33
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +458 -650
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +176 -10
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +807 -61
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +79 -6
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +80 -4
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +247 -14
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +491 -227
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +3 -2
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +2 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/ingest-child.d.ts +7 -1
- package/dist/node/ingest-child.d.ts.map +1 -1
- package/dist/node/ingest-child.js +19 -4
- package/dist/node/ingest-child.js.map +1 -1
- package/dist/node/isolated.d.ts +3 -1
- package/dist/node/isolated.d.ts.map +1 -1
- package/dist/node/isolated.js +11 -4
- package/dist/node/isolated.js.map +1 -1
- package/dist/node/originals.d.ts +19 -0
- package/dist/node/originals.d.ts.map +1 -0
- package/dist/node/originals.js +82 -0
- package/dist/node/originals.js.map +1 -0
- package/dist/node/spool.d.ts +106 -0
- package/dist/node/spool.d.ts.map +1 -0
- package/dist/node/spool.js +378 -0
- package/dist/node/spool.js.map +1 -0
- package/dist/node/sse.d.ts +6 -4
- package/dist/node/sse.d.ts.map +1 -1
- package/dist/node/sse.js +9 -7
- package/dist/node/sse.js.map +1 -1
- package/dist/openai/adapter.d.ts +5 -1
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +53 -12
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +2 -1
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +5 -2
- package/dist/output-limit.js.map +1 -1
- package/dist/pdf-layout.d.ts.map +1 -1
- package/dist/pdf-layout.js +71 -12
- package/dist/pdf-layout.js.map +1 -1
- package/dist/pdf-outline.d.ts +71 -0
- package/dist/pdf-outline.d.ts.map +1 -0
- package/dist/pdf-outline.js +414 -0
- package/dist/pdf-outline.js.map +1 -0
- package/dist/plan.d.ts +137 -7
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +248 -26
- package/dist/plan.js.map +1 -1
- package/dist/prepare.d.ts +50 -0
- package/dist/prepare.d.ts.map +1 -0
- package/dist/prepare.js +207 -0
- package/dist/prepare.js.map +1 -0
- package/dist/ranged.d.ts +16 -11
- package/dist/ranged.d.ts.map +1 -1
- package/dist/ranged.js +56 -12
- package/dist/ranged.js.map +1 -1
- package/dist/retry.d.ts +3 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +6 -2
- package/dist/retry.js.map +1 -1
- package/dist/scope.d.ts +25 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +60 -0
- package/dist/scope.js.map +1 -0
- package/dist/search.d.ts +7 -0
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +72 -10
- package/dist/search.js.map +1 -1
- package/dist/source.d.ts +60 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +170 -0
- package/dist/source.js.map +1 -0
- package/dist/stores.d.ts +126 -31
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +655 -141
- package/dist/stores.js.map +1 -1
- package/dist/testing/fake-fetch.d.ts +31 -0
- package/dist/testing/fake-fetch.d.ts.map +1 -0
- package/dist/testing/fake-fetch.js +66 -0
- package/dist/testing/fake-fetch.js.map +1 -0
- package/dist/testing/fake-model.d.ts +38 -0
- package/dist/testing/fake-model.d.ts.map +1 -0
- package/dist/testing/fake-model.js +62 -0
- package/dist/testing/fake-model.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +9 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/store-checks.d.ts +72 -0
- package/dist/testing/store-checks.d.ts.map +1 -0
- package/dist/testing/store-checks.js +619 -0
- package/dist/testing/store-checks.js.map +1 -0
- package/dist/tools.d.ts +47 -2
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +440 -71
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +165 -14
- package/dist/types.d.ts.map +1 -1
- package/dist/whole-cost.d.ts +37 -0
- package/dist/whole-cost.d.ts.map +1 -0
- package/dist/whole-cost.js +46 -0
- package/dist/whole-cost.js.map +1 -0
- package/docs/README.md +21 -8
- package/docs/getting-started.md +18 -13
- package/docs/guides/anthropic.md +17 -10
- package/docs/guides/conversations.md +112 -47
- package/docs/guides/costs-and-limits.md +147 -42
- package/docs/guides/deployment.md +380 -86
- package/docs/guides/errors-and-reliability.md +317 -67
- package/docs/guides/explorer-model.md +4 -1
- package/docs/guides/openai-compatible.md +47 -7
- package/docs/guides/own-adapter-and-loop.md +60 -16
- package/docs/guides/pdfs.md +219 -36
- package/docs/guides/storage.md +676 -145
- package/docs/guides/testing.md +149 -129
- package/docs/guides/vertex-and-gemini.md +169 -57
- package/docs/guides/web-app.md +318 -80
- package/docs/how-it-works.md +155 -30
- package/docs/measurements.md +215 -13
- package/docs/publishing.md +185 -37
- package/docs/reference/anthropic.md +12 -7
- package/docs/reference/ask.md +415 -47
- package/docs/reference/errors-and-retries.md +194 -14
- package/docs/reference/events.md +77 -27
- package/docs/reference/gemini.md +252 -87
- package/docs/reference/library.md +886 -178
- package/docs/reference/node.md +659 -111
- package/docs/reference/openai.md +21 -10
- package/docs/reference/testing.md +311 -0
- package/docs/reference/tools.md +285 -30
- package/docs/security.md +404 -78
- package/docs/troubleshooting.md +151 -70
- package/docs/upgrading-0.10.md +472 -0
- package/docs/upgrading-0.9.md +890 -0
- package/package.json +16 -3
- package/src/access.ts +267 -0
- package/src/aggregate.ts +92 -14
- package/src/analyze.ts +2 -2
- package/src/answer-info.ts +45 -0
- package/src/anthropic/adapter.ts +40 -11
- package/src/ask.ts +866 -115
- package/src/cache.ts +20 -5
- package/src/citations.ts +294 -0
- package/src/encoding.ts +6 -4
- package/src/error-info.ts +290 -0
- package/src/errors.ts +131 -15
- package/src/events.ts +112 -24
- package/src/evidence.ts +35 -5
- package/src/extract.ts +56 -34
- package/src/gemini/adapter.ts +196 -43
- package/src/gemini/chat.ts +63 -78
- package/src/gemini/endpoints.ts +89 -16
- package/src/gemini/errors.ts +74 -11
- package/src/gemini/generate.ts +147 -57
- package/src/gemini/index.ts +4 -4
- package/src/http.ts +65 -4
- package/src/index.ts +13 -8
- package/src/ingest.ts +958 -0
- package/src/library.ts +711 -651
- package/src/map-reduce.ts +858 -70
- package/src/model.ts +113 -9
- package/src/node/handlers.ts +709 -221
- package/src/node/index.ts +14 -2
- package/src/node/ingest-child.ts +24 -6
- package/src/node/isolated.ts +11 -4
- package/src/node/originals.ts +78 -0
- package/src/node/spool.ts +379 -0
- package/src/node/sse.ts +9 -7
- package/src/openai/adapter.ts +56 -13
- package/src/output-limit.ts +5 -2
- package/src/pdf-layout.ts +69 -11
- package/src/pdf-outline.ts +400 -0
- package/src/plan.ts +287 -36
- package/src/prepare.ts +253 -0
- package/src/ranged.ts +48 -14
- package/src/retry.ts +6 -2
- package/src/scope.ts +63 -0
- package/src/search.ts +69 -13
- package/src/source.ts +178 -0
- package/src/stores.ts +702 -142
- package/src/testing/fake-fetch.ts +80 -0
- package/src/testing/fake-model.ts +78 -0
- package/src/testing/index.ts +11 -0
- package/src/testing/store-checks.ts +660 -0
- package/src/tools.ts +461 -73
- package/src/types.ts +151 -14
- package/src/whole-cost.ts +64 -0
package/src/openai/adapter.ts
CHANGED
|
@@ -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
|
-
/**
|
|
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:
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
393
|
-
|
|
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),
|
|
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),
|
|
431
|
+
response = await post(body(other), timer.signal, stopped, lost, undefined, true);
|
|
411
432
|
}
|
|
412
|
-
const data = await readJson<Json>(response, stopped,
|
|
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
|
|
512
|
-
|
|
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 {
|
|
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);
|
package/src/output-limit.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
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
|
-
|
|
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
|
|
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. */
|