narrarium-engine 0.1.6 → 0.1.7
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/README.md +45 -9
- package/dist/ai/config.d.ts +22 -0
- package/dist/ai/config.d.ts.map +1 -1
- package/dist/ai/config.js +19 -0
- package/dist/ai/config.js.map +1 -1
- package/dist/ai/deadlines.d.ts +79 -0
- package/dist/ai/deadlines.d.ts.map +1 -0
- package/dist/ai/deadlines.js +151 -0
- package/dist/ai/deadlines.js.map +1 -0
- package/dist/ai/fetch-client.d.ts +41 -5
- package/dist/ai/fetch-client.d.ts.map +1 -1
- package/dist/ai/fetch-client.js +369 -125
- package/dist/ai/fetch-client.js.map +1 -1
- package/dist/ai/request.d.ts +3 -1
- package/dist/ai/request.d.ts.map +1 -1
- package/dist/ai/request.js +3 -1
- package/dist/ai/request.js.map +1 -1
- package/dist/ai/types.d.ts +32 -1
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/types.js +1 -0
- package/dist/ai/types.js.map +1 -1
- package/dist/autopilot/errors.d.ts +2 -1
- package/dist/autopilot/errors.d.ts.map +1 -1
- package/dist/autopilot/errors.js +25 -1
- package/dist/autopilot/errors.js.map +1 -1
- package/dist/autopilot/types.d.ts +8 -1
- package/dist/autopilot/types.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/ai/fetch-client.js
CHANGED
|
@@ -1,13 +1,23 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { abortError, isAbortError } from "../util/abort.js";
|
|
2
2
|
import { randomId } from "../util/hash.js";
|
|
3
3
|
import { likelyTextTokens } from "./budget.js";
|
|
4
|
+
import { resolveDeadlines, startClock, timeoutMessage } from "./deadlines.js";
|
|
4
5
|
import { redactSecrets } from "./redact.js";
|
|
5
6
|
import { effectiveAiBase, endpointOrigin } from "./request.js";
|
|
6
7
|
import { candidateBoundary, planAttempts } from "./routing.js";
|
|
7
8
|
import { splitReasoningBlock, structuredFromReply } from "./structured.js";
|
|
8
9
|
import { AiFallbackBlockedError, AiProviderError, AiReplyRejectedError } from "./types.js";
|
|
9
|
-
|
|
10
|
-
export
|
|
10
|
+
// The deadlines of a call: how long a provider has to begin answering, the least it is given, and the most a call may take.
|
|
11
|
+
export { DEFAULT_REQUEST_TIMEOUT_MS, MIN_REQUEST_TIMEOUT_MS, TOTAL_REQUEST_CAP_MS } from "./deadlines.js";
|
|
12
|
+
/**
|
|
13
|
+
* Raw bytes of a stream include the JSON envelope of every piece (a few hundred bytes for a few characters), so a long reasoning phase is
|
|
14
|
+
* far larger than its text. A stream over this many bytes is a model that loops, and is stopped.
|
|
15
|
+
*/
|
|
16
|
+
export const MAX_STREAM_TRANSPORT_BYTES = 256_000_000;
|
|
17
|
+
/** The characters of reasoning a stream may carry before it is taken for a loop and stopped. */
|
|
18
|
+
export const MAX_STREAM_REASONING_CHARACTERS = 16_000_000;
|
|
19
|
+
/** A host's progress listener is called at most this often. */
|
|
20
|
+
const PROGRESS_INTERVAL_MS = 250;
|
|
11
21
|
const MAX_RETRY_AFTER_MS = 300_000;
|
|
12
22
|
function notify(hook, value) {
|
|
13
23
|
try {
|
|
@@ -68,9 +78,8 @@ export function createFetchAi(config, options = {}) {
|
|
|
68
78
|
continue;
|
|
69
79
|
}
|
|
70
80
|
}
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
timeoutMs = Math.max(1, Math.min(timeoutMs, Math.ceil(maxTotal - (Date.now() - startedAt))));
|
|
81
|
+
// The first candidate runs for its own deadlines whatever the total; a later one runs for the routing time that is left.
|
|
82
|
+
const deadlines = resolveDeadlines(integration, options, tried > 0 && maxTotal !== undefined ? maxTotal - (Date.now() - startedAt) : undefined);
|
|
74
83
|
const identity = { attemptId: randomId("attempt"), label: request.label, capability: request.capability, provider: integration.provider, model: candidate.model, integrationId: integration.id, index: attempt.index };
|
|
75
84
|
const sent = attempt.built?.body.messages ?? [{ role: "system", content: request.system }, { role: "user", content: request.user }];
|
|
76
85
|
notify(options.onAttempt, {
|
|
@@ -81,15 +90,18 @@ export function createFetchAi(config, options = {}) {
|
|
|
81
90
|
stream: attempt.built?.stream ?? false,
|
|
82
91
|
tools: attempt.built?.useTools ?? false,
|
|
83
92
|
endpoint: effectiveAiBase(integration, options.githubModelsBaseUrl),
|
|
84
|
-
timeoutMs,
|
|
93
|
+
timeoutMs: deadlines.startMs,
|
|
94
|
+
timeouts: { startMs: deadlines.startMs, idleMs: deadlines.idleMs, capMs: deadlines.capMs, ...(deadlines.raisedFrom !== undefined ? { raised: { from: deadlines.raisedFrom } } : {}) },
|
|
95
|
+
streamMode: integration.streamMode === "off" ? "off" : "auto",
|
|
85
96
|
});
|
|
86
97
|
const attemptStarted = Date.now();
|
|
98
|
+
const trace = { startedAt: attemptStarted, streamed: false, toolSeen: false };
|
|
87
99
|
lastSent = candidate;
|
|
88
100
|
tried += 1;
|
|
89
101
|
try {
|
|
90
102
|
if (!attempt.built)
|
|
91
103
|
throw attempt.buildError;
|
|
92
|
-
const response = await callCandidate(config, attempt, attempt.built, request, options,
|
|
104
|
+
const response = await callCandidate(config, attempt, attempt.built, request, options, deadlines, secrets, trace);
|
|
93
105
|
notify(options.onAttemptEnd, {
|
|
94
106
|
...identity,
|
|
95
107
|
outcome: "ok",
|
|
@@ -99,13 +111,14 @@ export function createFetchAi(config, options = {}) {
|
|
|
99
111
|
costKnown: response.costKnown ?? false,
|
|
100
112
|
currency: response.currency,
|
|
101
113
|
text: response.text,
|
|
114
|
+
...replyTrace(trace, Boolean(request.json)),
|
|
102
115
|
durationMs: Date.now() - attemptStarted,
|
|
103
116
|
});
|
|
104
117
|
return withSpent(response, spent);
|
|
105
118
|
}
|
|
106
119
|
catch (error) {
|
|
107
120
|
const cancelled = Boolean(request.signal?.aborted) && isAbortError(error);
|
|
108
|
-
notify(options.onAttemptEnd, failedAttempt(identity, error, cancelled,
|
|
121
|
+
notify(options.onAttemptEnd, failedAttempt(identity, error, cancelled, deadlines.startMs, Date.now() - attemptStarted, secrets, replyTrace(trace, Boolean(request.json))));
|
|
109
122
|
if (cancelled)
|
|
110
123
|
throw error;
|
|
111
124
|
if (error instanceof AiProviderError && !error.target) {
|
|
@@ -183,7 +196,14 @@ function withSpent(response, spent) {
|
|
|
183
196
|
...(spent.costKnown === false ? { costKnown: false } : {}),
|
|
184
197
|
};
|
|
185
198
|
}
|
|
186
|
-
function
|
|
199
|
+
function replyTrace(trace, structured) {
|
|
200
|
+
return {
|
|
201
|
+
streamed: trace.streamed,
|
|
202
|
+
...(trace.firstByteMs !== undefined ? { firstByteMs: trace.firstByteMs } : {}),
|
|
203
|
+
...(structured && trace.firstByteMs !== undefined ? { toolCalled: trace.toolSeen } : {}),
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
function failedAttempt(identity, error, cancelled, timeoutMs, durationMs, secrets, reply) {
|
|
187
207
|
const provider = error instanceof AiProviderError ? error : undefined;
|
|
188
208
|
const timedOut = provider?.timedOut === true;
|
|
189
209
|
return {
|
|
@@ -198,7 +218,9 @@ function failedAttempt(identity, error, cancelled, timeoutMs, durationMs, secret
|
|
|
198
218
|
failureKind: cancelled ? "cancelled" : timedOut ? "timeout" : "provider",
|
|
199
219
|
...(provider?.status !== undefined ? { status: provider.status } : {}),
|
|
200
220
|
...(provider?.retryAfterMs !== undefined ? { retryAfterMs: provider.retryAfterMs } : {}),
|
|
201
|
-
...(timedOut ? { timeoutMs } : {}),
|
|
221
|
+
...(timedOut ? { timeoutMs: provider?.timeout?.ms ?? timeoutMs } : {}),
|
|
222
|
+
...(timedOut && provider?.timeout ? { timeoutPhase: provider.timeout.phase } : {}),
|
|
223
|
+
...reply,
|
|
202
224
|
durationMs,
|
|
203
225
|
};
|
|
204
226
|
}
|
|
@@ -260,18 +282,48 @@ async function providerError(response, provider, model, redact) {
|
|
|
260
282
|
const retryAfterMs = status === 429 || status === 503 ? parseRetryAfter(response.headers?.get?.("retry-after")) : undefined;
|
|
261
283
|
return new AiProviderError(redact(`${provider} ${model}: HTTP ${status}${detail ? ` — ${detail.replace(/\s+/g, " ").slice(0, 400)}` : ""}`), status, retryable, { ...(TRANSIENT_STATUSES.has(status) ? { transient: true } : {}), ...(retryAfterMs !== undefined ? { retryAfterMs } : {}) });
|
|
262
284
|
}
|
|
285
|
+
/** The connection failed while a stream was being read (as opposed to a deadline, the author's cancel, or what the engine itself found wrong). */
|
|
286
|
+
class StreamReadError extends Error {
|
|
287
|
+
reason;
|
|
288
|
+
constructor(reason) {
|
|
289
|
+
super("The stream could not be read.");
|
|
290
|
+
this.reason = reason;
|
|
291
|
+
this.name = "StreamReadError";
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
/** Stops reading without waiting for the other side: whatever it does with the cancel, the call must not hang on it. */
|
|
295
|
+
function release(reader) {
|
|
296
|
+
try {
|
|
297
|
+
void reader.cancel().catch(() => undefined);
|
|
298
|
+
}
|
|
299
|
+
catch {
|
|
300
|
+
// A reader that cannot be cancelled is of no use any more.
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
/** Lets a body go that nobody is going to read (a reply that arrived too late, or that the call gave up). */
|
|
304
|
+
function discardBody(response) {
|
|
305
|
+
try {
|
|
306
|
+
void response.body?.cancel().catch(() => undefined);
|
|
307
|
+
}
|
|
308
|
+
catch {
|
|
309
|
+
// A body that is locked or already read has nothing left to discard.
|
|
310
|
+
}
|
|
311
|
+
}
|
|
263
312
|
/**
|
|
264
313
|
* Reads server-sent events; resolves `true` when the provider closed the stream with `[DONE]`. An event is its `data:`
|
|
265
314
|
* lines joined with a newline, ended by a blank line; a value that is complete as it stands (one JSON object, or
|
|
266
315
|
* `[DONE]`) is delivered at once, so servers that leave out the blank lines still stream.
|
|
316
|
+
* Every piece that arrives starts the idle deadline again, a comment (`: keep-alive`) too, and no read can hold the call past
|
|
317
|
+
* a deadline or the author's cancel. However it ends, but by the end of the stream, the reader is released.
|
|
267
318
|
*/
|
|
268
|
-
async function readEventStream(response,
|
|
319
|
+
async function readEventStream(response, clock, hooks) {
|
|
269
320
|
if (!response.body)
|
|
270
321
|
throw new AiProviderError("The provider returned an empty stream.", undefined, true, { transient: true });
|
|
271
322
|
const reader = response.body.getReader();
|
|
272
323
|
const decoder = new TextDecoder();
|
|
273
324
|
let buffer = "";
|
|
274
325
|
let pending = [];
|
|
326
|
+
let exhausted = false;
|
|
275
327
|
const complete = (value) => {
|
|
276
328
|
const text = value.trim();
|
|
277
329
|
if (text === "[DONE]")
|
|
@@ -301,12 +353,12 @@ async function readEventStream(response, onData) {
|
|
|
301
353
|
if (single === "[DONE]")
|
|
302
354
|
return true;
|
|
303
355
|
if (single)
|
|
304
|
-
onData(single);
|
|
356
|
+
hooks.onData(single);
|
|
305
357
|
}
|
|
306
358
|
return false;
|
|
307
359
|
}
|
|
308
360
|
if (joined)
|
|
309
|
-
onData(joined);
|
|
361
|
+
hooks.onData(joined);
|
|
310
362
|
return false;
|
|
311
363
|
};
|
|
312
364
|
const takeLine = (line) => {
|
|
@@ -320,30 +372,76 @@ async function readEventStream(response, onData) {
|
|
|
320
372
|
};
|
|
321
373
|
try {
|
|
322
374
|
for (;;) {
|
|
323
|
-
|
|
324
|
-
|
|
375
|
+
let piece;
|
|
376
|
+
try {
|
|
377
|
+
piece = await clock.guard(reader.read());
|
|
378
|
+
}
|
|
379
|
+
catch (error) {
|
|
380
|
+
// A deadline or the author's cancel is told by the call; anything else here is the connection.
|
|
381
|
+
throw clock.interrupted() ? error : new StreamReadError(error);
|
|
382
|
+
}
|
|
383
|
+
if (piece.done) {
|
|
384
|
+
exhausted = true;
|
|
325
385
|
break;
|
|
326
|
-
|
|
386
|
+
}
|
|
387
|
+
clock.activity();
|
|
388
|
+
hooks.onBytes(piece.value.byteLength);
|
|
389
|
+
buffer += decoder.decode(piece.value, { stream: true });
|
|
327
390
|
let newline = buffer.indexOf("\n");
|
|
328
391
|
while (newline >= 0) {
|
|
329
392
|
const line = buffer.slice(0, newline);
|
|
330
393
|
buffer = buffer.slice(newline + 1);
|
|
331
|
-
if (takeLine(line))
|
|
332
|
-
await reader.cancel().catch(() => undefined);
|
|
394
|
+
if (takeLine(line))
|
|
333
395
|
return true;
|
|
334
|
-
}
|
|
335
396
|
newline = buffer.indexOf("\n");
|
|
336
397
|
}
|
|
398
|
+
hooks.onPiece();
|
|
337
399
|
}
|
|
338
400
|
buffer += decoder.decode();
|
|
339
401
|
if (buffer.trim() && takeLine(buffer))
|
|
340
402
|
return true;
|
|
341
403
|
return flush();
|
|
342
404
|
}
|
|
343
|
-
|
|
344
|
-
// The reply
|
|
345
|
-
|
|
346
|
-
|
|
405
|
+
finally {
|
|
406
|
+
// The provider closed the stream, or the reply is given up (the end marker, an error chunk, a deadline, the author): let the connection go.
|
|
407
|
+
if (!exhausted)
|
|
408
|
+
release(reader);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Reads the whole body of a reply that is one JSON value. Like the stream reader it starts the idle deadline again at every piece, cannot
|
|
413
|
+
* be held past a deadline or the author's cancel, and releases the body however it ends (`response.json()` would keep it locked).
|
|
414
|
+
*/
|
|
415
|
+
async function readJsonBody(response, clock, onBytes) {
|
|
416
|
+
if (!response.body)
|
|
417
|
+
return clock.guard(response.json());
|
|
418
|
+
const reader = response.body.getReader();
|
|
419
|
+
const decoder = new TextDecoder();
|
|
420
|
+
let body = "";
|
|
421
|
+
let exhausted = false;
|
|
422
|
+
try {
|
|
423
|
+
for (;;) {
|
|
424
|
+
let piece;
|
|
425
|
+
try {
|
|
426
|
+
piece = await clock.guard(reader.read());
|
|
427
|
+
}
|
|
428
|
+
catch (error) {
|
|
429
|
+
throw clock.interrupted() ? error : new StreamReadError(error);
|
|
430
|
+
}
|
|
431
|
+
if (piece.done) {
|
|
432
|
+
exhausted = true;
|
|
433
|
+
break;
|
|
434
|
+
}
|
|
435
|
+
clock.activity();
|
|
436
|
+
onBytes(piece.value.byteLength);
|
|
437
|
+
body += decoder.decode(piece.value, { stream: true });
|
|
438
|
+
}
|
|
439
|
+
body += decoder.decode();
|
|
440
|
+
return JSON.parse(body);
|
|
441
|
+
}
|
|
442
|
+
finally {
|
|
443
|
+
if (!exhausted)
|
|
444
|
+
release(reader);
|
|
347
445
|
}
|
|
348
446
|
}
|
|
349
447
|
const COMPLETE_REASONS = new Set(["stop", "tool_calls", "function_call", "end_turn", "stop_sequence", "tool_use", "eos"]);
|
|
@@ -396,117 +494,241 @@ function reasoningLength(source) {
|
|
|
396
494
|
const { reasoning_content: content, reasoning } = source;
|
|
397
495
|
return (typeof content === "string" ? content.length : 0) + (typeof reasoning === "string" ? reasoning.length : 0);
|
|
398
496
|
}
|
|
399
|
-
|
|
497
|
+
/** The function calls of a message (`tool_calls`) whose arguments are text, in their order. */
|
|
498
|
+
function callsOf(value) {
|
|
499
|
+
if (!Array.isArray(value))
|
|
500
|
+
return [];
|
|
501
|
+
const calls = [];
|
|
502
|
+
for (const entry of value) {
|
|
503
|
+
const fn = entry && typeof entry === "object" ? entry.function : undefined;
|
|
504
|
+
if (!fn || typeof fn !== "object")
|
|
505
|
+
continue;
|
|
506
|
+
const { name, arguments: args } = fn;
|
|
507
|
+
if (typeof args === "string")
|
|
508
|
+
calls.push({ name: typeof name === "string" ? name : "", arguments: args });
|
|
509
|
+
}
|
|
510
|
+
return calls;
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* The arguments of the call that is the reply: the first call to the function that was asked for that carries arguments, else the first
|
|
514
|
+
* that carries any, else the first. The other calls are ignored, never joined to it.
|
|
515
|
+
*/
|
|
516
|
+
function chosenArguments(calls, wanted) {
|
|
517
|
+
let first;
|
|
518
|
+
let firstWithArguments;
|
|
519
|
+
for (const call of calls) {
|
|
520
|
+
first ??= call.arguments;
|
|
521
|
+
if (!call.arguments.trim())
|
|
522
|
+
continue;
|
|
523
|
+
if (wanted && call.name === wanted)
|
|
524
|
+
return call.arguments;
|
|
525
|
+
firstWithArguments ??= call.arguments;
|
|
526
|
+
}
|
|
527
|
+
return firstWithArguments ?? first ?? "";
|
|
528
|
+
}
|
|
529
|
+
async function callCandidate(config, attempt, built, request, options, deadlines, secrets, trace) {
|
|
400
530
|
const { candidate } = attempt;
|
|
401
531
|
const { integration, model } = candidate;
|
|
402
532
|
const label = `${integration.provider} ${model}`;
|
|
403
533
|
const redact = (text) => redactSecrets(text, secrets);
|
|
404
534
|
const fetchImpl = options.fetch ?? fetch;
|
|
405
|
-
const
|
|
406
|
-
|
|
407
|
-
|
|
535
|
+
const clock = startClock(request.signal, deadlines);
|
|
536
|
+
const structured = Boolean(request.json);
|
|
537
|
+
const wanted = request.json?.name;
|
|
538
|
+
const elapsed = () => Date.now() - trace.startedAt;
|
|
539
|
+
let text = "";
|
|
540
|
+
let usage;
|
|
541
|
+
let finishReason = "";
|
|
542
|
+
let reasoningCharacters = 0;
|
|
543
|
+
/** The function calls of a streamed reply by their index, in the order they came. */
|
|
544
|
+
const calls = new Map();
|
|
545
|
+
/** The arguments of a call that came whole: in the message of a JSON reply, or in the last piece of a stream. */
|
|
546
|
+
let wholeArguments = "";
|
|
547
|
+
/** The response ended properly: a stream that closed with `[DONE]`, or a complete JSON body. */
|
|
548
|
+
let ended = true;
|
|
549
|
+
let bytes = 0;
|
|
550
|
+
let events = 0;
|
|
551
|
+
let lastProgressAt;
|
|
552
|
+
let response;
|
|
553
|
+
/** Where the call is, to say what went wrong when something does. */
|
|
554
|
+
let stage = "send";
|
|
555
|
+
const callArguments = () => wholeArguments || chosenArguments(calls.values(), wanted);
|
|
556
|
+
/** What the attempt used: the provider's count, else an estimate once the model has started to answer. */
|
|
557
|
+
const measure = () => {
|
|
558
|
+
if (usage && usage.inputTokens + usage.outputTokens > 0)
|
|
559
|
+
return { usage, usageKnown: true };
|
|
560
|
+
const args = callArguments();
|
|
561
|
+
if (!text && !args && !reasoningCharacters)
|
|
562
|
+
return {};
|
|
563
|
+
return {
|
|
564
|
+
usage: { inputTokens: attempt.inputTokens, outputTokens: likelyTextTokens(text) + likelyTextTokens(args) + Math.ceil(reasoningCharacters / 4), cachedInputTokens: 0 },
|
|
565
|
+
usageKnown: false,
|
|
566
|
+
};
|
|
567
|
+
};
|
|
568
|
+
const details = (extra = {}) => {
|
|
569
|
+
const measured = measure();
|
|
570
|
+
return {
|
|
571
|
+
usage: measured.usage,
|
|
572
|
+
cost: estimateCost(measured.usage, candidate.pricing),
|
|
573
|
+
...(measured.usageKnown === undefined ? {} : { usageKnown: measured.usageKnown, costKnown: measured.usageKnown && Boolean(candidate.pricing) }),
|
|
574
|
+
currency: config.costCurrency,
|
|
575
|
+
model,
|
|
576
|
+
provider: integration.provider,
|
|
577
|
+
integrationId: integration.id,
|
|
578
|
+
...extra,
|
|
579
|
+
};
|
|
580
|
+
};
|
|
581
|
+
/** A stream that no model's answer explains: stopped, with what it used and what to do. */
|
|
582
|
+
const runaway = (what) => new AiProviderError(redact(`${label}: ${what}. Nothing was applied: the provider may have used tokens. Lower the thinking effort of the model or choose another one.`), undefined, false, details());
|
|
583
|
+
const timeoutError = (expired, answering) => new AiProviderError(redact(timeoutMessage(label, expired, deadlines, integration.name)), undefined, true, {
|
|
584
|
+
...(answering ? details() : {}),
|
|
585
|
+
transient: true,
|
|
586
|
+
timedOut: true,
|
|
587
|
+
timeout: { phase: expired.phase, ms: expired.ms, ...(expired.phase === "start" && deadlines.raisedFrom !== undefined ? { raisedFrom: deadlines.raisedFrom } : {}) },
|
|
588
|
+
});
|
|
589
|
+
const reportProgress = () => {
|
|
590
|
+
if (!request.onProgress)
|
|
591
|
+
return;
|
|
592
|
+
const now = Date.now();
|
|
593
|
+
if (lastProgressAt !== undefined && now - lastProgressAt < PROGRESS_INTERVAL_MS)
|
|
594
|
+
return;
|
|
595
|
+
lastProgressAt = now;
|
|
596
|
+
notify(request.onProgress, { bytes, events, characters: text.length + callArguments().length });
|
|
597
|
+
};
|
|
598
|
+
const addCalls = (value) => {
|
|
599
|
+
if (!Array.isArray(value))
|
|
600
|
+
return;
|
|
601
|
+
for (const entry of value) {
|
|
602
|
+
if (!entry || typeof entry !== "object")
|
|
603
|
+
continue;
|
|
604
|
+
const { index, function: fn } = entry;
|
|
605
|
+
if (!fn || typeof fn !== "object")
|
|
606
|
+
continue;
|
|
607
|
+
trace.toolSeen = true;
|
|
608
|
+
// A piece without an index belongs to the only call there is.
|
|
609
|
+
const key = typeof index === "number" && Number.isInteger(index) && index >= 0 ? index : 0;
|
|
610
|
+
let call = calls.get(key);
|
|
611
|
+
if (!call) {
|
|
612
|
+
call = { name: "", arguments: "" };
|
|
613
|
+
calls.set(key, call);
|
|
614
|
+
}
|
|
615
|
+
if (typeof fn.name === "string" && fn.name)
|
|
616
|
+
call.name = fn.name;
|
|
617
|
+
if (typeof fn.arguments === "string")
|
|
618
|
+
call.arguments += fn.arguments;
|
|
619
|
+
}
|
|
620
|
+
};
|
|
621
|
+
const take = (data) => {
|
|
622
|
+
let chunk;
|
|
408
623
|
try {
|
|
409
|
-
|
|
410
|
-
method: "POST",
|
|
411
|
-
headers: built.headers,
|
|
412
|
-
body: JSON.stringify(built.body),
|
|
413
|
-
signal: timer.signal,
|
|
414
|
-
});
|
|
624
|
+
chunk = JSON.parse(data);
|
|
415
625
|
}
|
|
416
|
-
catch
|
|
417
|
-
|
|
418
|
-
throw error;
|
|
419
|
-
const timedOut = timer.timedOut();
|
|
420
|
-
throw new AiProviderError(redact(`${label}: ${timedOut ? "request timed out" : error instanceof Error ? error.message : String(error)}`), undefined, true, { transient: true, ...(timedOut ? { timedOut: true } : {}) });
|
|
626
|
+
catch {
|
|
627
|
+
return;
|
|
421
628
|
}
|
|
422
|
-
if (!
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
629
|
+
if (!chunk || typeof chunk !== "object")
|
|
630
|
+
return;
|
|
631
|
+
if (chunk.error) {
|
|
632
|
+
const failure = streamError(chunk.error, label, details(), redact);
|
|
633
|
+
if (failure)
|
|
634
|
+
throw failure;
|
|
635
|
+
}
|
|
636
|
+
const choices = Array.isArray(chunk.choices) ? chunk.choices : [];
|
|
637
|
+
const first = choices[0];
|
|
638
|
+
const delta = first?.delta;
|
|
639
|
+
reasoningCharacters += reasoningLength(delta);
|
|
640
|
+
if (reasoningCharacters > MAX_STREAM_REASONING_CHARACTERS)
|
|
641
|
+
throw runaway(`the model's reasoning passed the safety limit of ${MAX_STREAM_REASONING_CHARACTERS / 1_000_000} million characters (a reasoning loop is likely)`);
|
|
642
|
+
if (delta?.content) {
|
|
643
|
+
text += delta.content;
|
|
644
|
+
// The text of a structured reply is no prose for the listener: its progress is `onProgress`.
|
|
645
|
+
if (!structured)
|
|
646
|
+
request.onText?.(text);
|
|
647
|
+
}
|
|
648
|
+
addCalls(delta?.tool_calls);
|
|
649
|
+
// Some providers end the stream with the whole message instead of (or after) the pieces.
|
|
650
|
+
const whole = callsOf(first?.message?.tool_calls);
|
|
651
|
+
if (whole.length) {
|
|
652
|
+
trace.toolSeen = true;
|
|
653
|
+
const args = chosenArguments(whole, wanted);
|
|
654
|
+
if (args.trim())
|
|
655
|
+
wholeArguments = args;
|
|
656
|
+
}
|
|
657
|
+
const reason = choices.find((choice) => typeof choice?.finish_reason === "string" && choice.finish_reason)?.finish_reason;
|
|
658
|
+
if (reason)
|
|
659
|
+
finishReason = reason;
|
|
660
|
+
if (chunk.usage)
|
|
661
|
+
usage = normalizeUsage(chunk.usage);
|
|
662
|
+
};
|
|
663
|
+
const countBytes = (count, what) => {
|
|
664
|
+
bytes += count;
|
|
665
|
+
trace.firstByteMs ??= elapsed();
|
|
666
|
+
if (bytes > MAX_STREAM_TRANSPORT_BYTES)
|
|
667
|
+
throw runaway(`the ${what} passed the safety limit of ${MAX_STREAM_TRANSPORT_BYTES / 1_000_000} MB (a model that loops while reasoning looks like this)`);
|
|
668
|
+
};
|
|
669
|
+
const hooks = {
|
|
670
|
+
onData: (data) => {
|
|
671
|
+
events += 1;
|
|
672
|
+
take(data);
|
|
673
|
+
},
|
|
674
|
+
onBytes: (count) => countBytes(count, "stream"),
|
|
675
|
+
onPiece: reportProgress,
|
|
676
|
+
};
|
|
677
|
+
try {
|
|
678
|
+
const sent = Promise.resolve(fetchImpl(built.url, {
|
|
679
|
+
method: "POST",
|
|
680
|
+
headers: built.headers,
|
|
681
|
+
body: JSON.stringify(built.body),
|
|
682
|
+
signal: clock.signal,
|
|
683
|
+
}));
|
|
684
|
+
// A reply that comes after the call was given up is dropped, and its body let go.
|
|
685
|
+
sent.then((late) => {
|
|
686
|
+
if (clock.interrupted())
|
|
687
|
+
discardBody(late);
|
|
688
|
+
}, () => undefined);
|
|
689
|
+
response = await clock.guard(sent);
|
|
690
|
+
stage = "other";
|
|
691
|
+
if (!response.ok) {
|
|
692
|
+
trace.firstByteMs ??= elapsed();
|
|
693
|
+
const failure = await clock.guard(providerError(response, integration.provider, model, redact));
|
|
694
|
+
// A provider that cannot stream says so with a 400: tell where to switch streaming off.
|
|
695
|
+
if (built.stream && (failure.status === 400 || failure.status === 422) && /stream/i.test(failure.message.replace(label, ""))) {
|
|
696
|
+
failure.message = redact(`${failure.message}${/[.!?]$/.test(failure.message) ? "" : "."} If this provider cannot stream its replies, set "Streaming" of the integration "${integration.name}" to "off".`);
|
|
697
|
+
}
|
|
698
|
+
throw failure;
|
|
699
|
+
}
|
|
700
|
+
// A streamed request: the start deadline is over, the silence between two pieces is what is watched now.
|
|
701
|
+
if (built.stream)
|
|
702
|
+
clock.streaming();
|
|
455
703
|
// A JSON body to a streaming request means the server ignored `stream`: its reply is read as a whole.
|
|
456
704
|
const streamed = built.stream && !/\bjson\b/i.test(response.headers?.get?.("content-type") ?? "");
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
try {
|
|
462
|
-
chunk = JSON.parse(data);
|
|
463
|
-
}
|
|
464
|
-
catch {
|
|
465
|
-
return;
|
|
466
|
-
}
|
|
467
|
-
if (!chunk || typeof chunk !== "object")
|
|
468
|
-
return;
|
|
469
|
-
if (chunk.error) {
|
|
470
|
-
const failure = streamError(chunk.error, label, details(), redact);
|
|
471
|
-
if (failure)
|
|
472
|
-
throw failure;
|
|
473
|
-
}
|
|
474
|
-
const delta = chunk.choices?.[0]?.delta;
|
|
475
|
-
reasoningCharacters += reasoningLength(delta);
|
|
476
|
-
if (delta?.content) {
|
|
477
|
-
text += delta.content;
|
|
478
|
-
request.onText?.(text);
|
|
479
|
-
}
|
|
480
|
-
const reason = chunk.choices?.find((choice) => typeof choice?.finish_reason === "string" && choice.finish_reason)?.finish_reason;
|
|
481
|
-
if (reason)
|
|
482
|
-
finishReason = reason;
|
|
483
|
-
if (chunk.usage)
|
|
484
|
-
usage = normalizeUsage(chunk.usage);
|
|
485
|
-
});
|
|
486
|
-
}
|
|
487
|
-
else {
|
|
488
|
-
const payload = await response.json();
|
|
489
|
-
if (payload?.error) {
|
|
490
|
-
const failure = streamError(payload.error, label, details(), redact);
|
|
491
|
-
if (failure)
|
|
492
|
-
throw failure;
|
|
493
|
-
}
|
|
494
|
-
const choice = payload?.choices?.[0];
|
|
495
|
-
text = typeof choice?.message?.content === "string" ? choice.message.content : "";
|
|
496
|
-
toolArguments = choice?.message?.tool_calls?.find((call) => typeof call.function?.arguments === "string")?.function?.arguments ?? "";
|
|
497
|
-
finishReason = typeof choice?.finish_reason === "string" ? choice.finish_reason : "";
|
|
498
|
-
reasoningCharacters = reasoningLength(choice?.message);
|
|
499
|
-
usage = normalizeUsage(payload?.usage);
|
|
500
|
-
if (built.stream && text)
|
|
501
|
-
request.onText?.(text);
|
|
502
|
-
}
|
|
705
|
+
trace.streamed = streamed;
|
|
706
|
+
if (streamed) {
|
|
707
|
+
stage = "stream";
|
|
708
|
+
ended = await readEventStream(response, clock, hooks);
|
|
503
709
|
}
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
const
|
|
508
|
-
|
|
710
|
+
else {
|
|
711
|
+
stage = "json";
|
|
712
|
+
trace.firstByteMs ??= elapsed();
|
|
713
|
+
const payload = await readJsonBody(response, clock, (count) => countBytes(count, "reply"));
|
|
714
|
+
if (payload?.error) {
|
|
715
|
+
const failure = streamError(payload.error, label, details(), redact);
|
|
716
|
+
if (failure)
|
|
717
|
+
throw failure;
|
|
718
|
+
}
|
|
719
|
+
const choice = payload?.choices?.[0];
|
|
720
|
+
text = typeof choice?.message?.content === "string" ? choice.message.content : "";
|
|
721
|
+
wholeArguments = choice?.message?.tool_calls?.find((call) => typeof call.function?.arguments === "string")?.function?.arguments ?? "";
|
|
722
|
+
if (Array.isArray(choice?.message?.tool_calls) && choice.message.tool_calls.length)
|
|
723
|
+
trace.toolSeen = true;
|
|
724
|
+
finishReason = typeof choice?.finish_reason === "string" ? choice.finish_reason : "";
|
|
725
|
+
reasoningCharacters = reasoningLength(choice?.message);
|
|
726
|
+
usage = normalizeUsage(payload?.usage);
|
|
727
|
+
// A plain reply that came whole still reaches the listener of the text, once.
|
|
728
|
+
if (!structured && text)
|
|
729
|
+
request.onText?.(text);
|
|
509
730
|
}
|
|
731
|
+
stage = "other";
|
|
510
732
|
const outcome = classifyFinishReason(finishReason, ended);
|
|
511
733
|
const shown = redact(finishReason).replace(/\s+/g, " ").trim().slice(0, 60);
|
|
512
734
|
if (outcome === "incomplete")
|
|
@@ -521,6 +743,7 @@ async function callCandidate(config, attempt, built, request, options, timeoutMs
|
|
|
521
743
|
const inline = splitReasoningBlock(text);
|
|
522
744
|
text = inline.reply;
|
|
523
745
|
reasoningCharacters += inline.reasoningCharacters;
|
|
746
|
+
const toolArguments = callArguments();
|
|
524
747
|
const answered = Boolean(text.trim() || toolArguments.trim());
|
|
525
748
|
if (outcome === "truncated") {
|
|
526
749
|
const reasoned = !answered && reasoningCharacters > 0;
|
|
@@ -528,6 +751,8 @@ async function callCandidate(config, attempt, built, request, options, timeoutMs
|
|
|
528
751
|
}
|
|
529
752
|
if (!answered)
|
|
530
753
|
throw new AiProviderError(`${label}: ${reasoningCharacters > 0 ? "the model finished after reasoning without a reply" : "the provider returned an empty reply"}.`, undefined, true, details());
|
|
754
|
+
// Measured before the arguments of a function become the text of the reply: they are counted once.
|
|
755
|
+
const measured = measure();
|
|
531
756
|
let json;
|
|
532
757
|
if (request.json) {
|
|
533
758
|
try {
|
|
@@ -539,7 +764,6 @@ async function callCandidate(config, attempt, built, request, options, timeoutMs
|
|
|
539
764
|
if (!text)
|
|
540
765
|
text = toolArguments;
|
|
541
766
|
}
|
|
542
|
-
const measured = measure();
|
|
543
767
|
return {
|
|
544
768
|
text,
|
|
545
769
|
json,
|
|
@@ -553,8 +777,28 @@ async function callCandidate(config, attempt, built, request, options, timeoutMs
|
|
|
553
777
|
currency: config.costCurrency,
|
|
554
778
|
};
|
|
555
779
|
}
|
|
780
|
+
catch (error) {
|
|
781
|
+
if (response && clock.interrupted())
|
|
782
|
+
discardBody(response);
|
|
783
|
+
// The author's cancel wins over everything, and is never a timeout.
|
|
784
|
+
if (request.signal?.aborted)
|
|
785
|
+
throw request.signal.reason instanceof Error ? request.signal.reason : abortError();
|
|
786
|
+
const expired = clock.expired();
|
|
787
|
+
if (expired)
|
|
788
|
+
throw timeoutError(expired, stage === "stream" || stage === "json");
|
|
789
|
+
if (error instanceof AiProviderError)
|
|
790
|
+
throw error;
|
|
791
|
+
if (stage === "send")
|
|
792
|
+
throw new AiProviderError(redact(`${label}: ${error instanceof Error ? error.message : String(error)}`), undefined, true, { transient: true });
|
|
793
|
+
if (stage === "stream" && error instanceof StreamReadError) {
|
|
794
|
+
throw new AiProviderError(redact(`${label}: the connection with the provider was lost while it was answering, so the reply could not be read. Nothing was applied. If this happens every time, check the proxy or the tunnel between this app and the provider.`), undefined, true, details({ transient: true }));
|
|
795
|
+
}
|
|
796
|
+
if (stage === "stream" || stage === "json")
|
|
797
|
+
throw new AiProviderError(redact(`${label}: the reply could not be read.`), undefined, true, details({ transient: true }));
|
|
798
|
+
throw error;
|
|
799
|
+
}
|
|
556
800
|
finally {
|
|
557
|
-
|
|
801
|
+
clock.dispose();
|
|
558
802
|
}
|
|
559
803
|
}
|
|
560
804
|
//# sourceMappingURL=fetch-client.js.map
|