narrarium-engine 0.1.16 → 0.1.20
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 +35 -4
- package/dist/ai/config.d.ts +91 -0
- package/dist/ai/config.d.ts.map +1 -1
- package/dist/ai/config.js +150 -0
- package/dist/ai/config.js.map +1 -1
- package/dist/ai/fetch-client.d.ts +39 -4
- package/dist/ai/fetch-client.d.ts.map +1 -1
- package/dist/ai/fetch-client.js +276 -123
- package/dist/ai/fetch-client.js.map +1 -1
- package/dist/ai/memory.d.ts +34 -0
- package/dist/ai/memory.d.ts.map +1 -0
- package/dist/ai/memory.js +27 -0
- package/dist/ai/memory.js.map +1 -0
- package/dist/ai/provider-error.d.ts +50 -0
- package/dist/ai/provider-error.d.ts.map +1 -0
- package/dist/ai/provider-error.js +197 -0
- package/dist/ai/provider-error.js.map +1 -0
- package/dist/ai/redact.js +1 -1
- package/dist/ai/redact.js.map +1 -1
- package/dist/ai/request.d.ts +98 -9
- package/dist/ai/request.d.ts.map +1 -1
- package/dist/ai/request.js +153 -23
- package/dist/ai/request.js.map +1 -1
- package/dist/ai/responses.d.ts +106 -0
- package/dist/ai/responses.d.ts.map +1 -0
- package/dist/ai/responses.js +226 -0
- package/dist/ai/responses.js.map +1 -0
- package/dist/ai/router.d.ts +28 -4
- package/dist/ai/router.d.ts.map +1 -1
- package/dist/ai/router.js +57 -23
- package/dist/ai/router.js.map +1 -1
- package/dist/ai/routing.d.ts +14 -4
- package/dist/ai/routing.d.ts.map +1 -1
- package/dist/ai/routing.js +88 -16
- package/dist/ai/routing.js.map +1 -1
- package/dist/ai/types.d.ts +77 -2
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/types.js +6 -2
- package/dist/ai/types.js.map +1 -1
- package/dist/autopilot/attempt.d.ts +11 -0
- package/dist/autopilot/attempt.d.ts.map +1 -0
- package/dist/autopilot/attempt.js +53 -0
- package/dist/autopilot/attempt.js.map +1 -0
- package/dist/autopilot/calls/recorder.d.ts +1 -0
- package/dist/autopilot/calls/recorder.d.ts.map +1 -1
- package/dist/autopilot/calls/recorder.js +16 -1
- package/dist/autopilot/calls/recorder.js.map +1 -1
- package/dist/autopilot/calls/run-calls.d.ts +8 -0
- package/dist/autopilot/calls/run-calls.d.ts.map +1 -1
- package/dist/autopilot/calls/run-calls.js +56 -4
- package/dist/autopilot/calls/run-calls.js.map +1 -1
- package/dist/autopilot/calls/types.d.ts +29 -6
- package/dist/autopilot/calls/types.d.ts.map +1 -1
- package/dist/autopilot/calls/types.js +2 -2
- package/dist/autopilot/calls/types.js.map +1 -1
- package/dist/autopilot/errors.d.ts.map +1 -1
- package/dist/autopilot/errors.js +111 -1
- package/dist/autopilot/errors.js.map +1 -1
- package/dist/autopilot/live.d.ts +11 -1
- package/dist/autopilot/live.d.ts.map +1 -1
- package/dist/autopilot/live.js +17 -2
- package/dist/autopilot/live.js.map +1 -1
- package/dist/autopilot/runner.d.ts +5 -0
- package/dist/autopilot/runner.d.ts.map +1 -1
- package/dist/autopilot/runner.js +40 -1
- package/dist/autopilot/runner.js.map +1 -1
- package/dist/autopilot/session.d.ts +8 -0
- package/dist/autopilot/session.d.ts.map +1 -1
- package/dist/autopilot/session.js +10 -2
- package/dist/autopilot/session.js.map +1 -1
- package/dist/autopilot/types.d.ts +94 -7
- package/dist/autopilot/types.d.ts.map +1 -1
- package/dist/autopilot/types.js +2 -0
- package/dist/autopilot/types.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.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
|
@@ -4,8 +4,10 @@ import { discardBody, release } from "./body.js";
|
|
|
4
4
|
import { likelyTextTokens } from "./budget.js";
|
|
5
5
|
import { resolveDeadlines, startClock, timeoutMessage } from "./deadlines.js";
|
|
6
6
|
import { redactSecrets } from "./redact.js";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
7
|
+
import { describeErrorBody, errorBodyOfObject, parseErrorBody, refusesThinkingWithTools, suggestsResponsesApi } from "./provider-error.js";
|
|
8
|
+
import { ResponsesStreamReader, responseAsChat } from "./responses.js";
|
|
9
|
+
import { attemptThinking, buildChatRequest, candidateDestination, candidateEndpoint, canSendNone } from "./request.js";
|
|
10
|
+
import { candidateBoundary, leftOutStep, planAttempts, sortedRoute } from "./routing.js";
|
|
9
11
|
import { isEmptyToolArguments, splitReasoningBlock, structuredFromReply } from "./structured.js";
|
|
10
12
|
import { AiFallbackBlockedError, AiProviderError, AiReplyRejectedError, AiStreamInterruptedError, MAX_PARTIAL_CHARACTERS, TRANSPORT_TAIL_CHARACTERS } from "./types.js";
|
|
11
13
|
// 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.
|
|
@@ -25,7 +27,7 @@ const MAX_RETRY_AFTER_MS = 300_000;
|
|
|
25
27
|
* a word of what is sent). An attempt that could not be built reports what the request would have sent.
|
|
26
28
|
*/
|
|
27
29
|
function reportedMessages(built, request) {
|
|
28
|
-
const wire = built?.
|
|
30
|
+
const wire = built?.messages;
|
|
29
31
|
if (wire) {
|
|
30
32
|
return wire.map((message) => ({
|
|
31
33
|
role: message.role,
|
|
@@ -63,6 +65,9 @@ export function createFetchAi(config, options = {}) {
|
|
|
63
65
|
async complete(request) {
|
|
64
66
|
let startedAt = Date.now();
|
|
65
67
|
const secrets = config.aiIntegrations.map((integration) => integration.apiKey);
|
|
68
|
+
// What the client's host remembers of its models applies to every call it makes, unless the call brings its own memory.
|
|
69
|
+
if (options.memory && !request.memory)
|
|
70
|
+
request = { ...request, memory: options.memory };
|
|
66
71
|
const plan = planAttempts(config, request, options.githubModelsBaseUrl);
|
|
67
72
|
const skipped = plan.skipped.map((entry) => ({ model: entry.candidate.model, reason: entry.reason }));
|
|
68
73
|
const decisions = new Map();
|
|
@@ -73,93 +78,158 @@ export function createFetchAi(config, options = {}) {
|
|
|
73
78
|
let lastSent = plan.primary;
|
|
74
79
|
let tried = 0;
|
|
75
80
|
let outOfTime = false;
|
|
76
|
-
|
|
81
|
+
/** What became of every candidate of the route, as far as this call has gone: what the plan left out, and each attempt as it ends. */
|
|
82
|
+
const steps = [...plan.leftOut];
|
|
83
|
+
/** The candidates asked so far: a candidate that is asked again (without a thinking level) is still one. */
|
|
84
|
+
let askedCandidates = 0;
|
|
85
|
+
for (const [at, planned] of plan.attempts.entries()) {
|
|
77
86
|
request.signal?.throwIfAborted();
|
|
78
|
-
|
|
79
|
-
const integration = candidate.integration;
|
|
87
|
+
let attempt = planned;
|
|
88
|
+
const integration = planned.candidate.integration;
|
|
80
89
|
const maxTotal = plan.limits.maxTotalDurationMs;
|
|
81
90
|
// The first candidate runs for its own timeout whatever the total; the others start only while time remains.
|
|
82
|
-
if (
|
|
91
|
+
if (askedCandidates > 0 && maxTotal !== undefined && maxTotal - (Date.now() - startedAt) <= 0) {
|
|
83
92
|
outOfTime = true;
|
|
93
|
+
for (const rest of plan.attempts.slice(at))
|
|
94
|
+
steps.push(leftOutStep(rest.candidate, rest.index, "out-of-time", secrets, options.githubModelsBaseUrl));
|
|
84
95
|
break;
|
|
85
96
|
}
|
|
86
|
-
if (config.fallbackDisclosure?.requireAcknowledgement && candidateBoundary(candidate) !== candidateBoundary(lastSent)) {
|
|
87
|
-
const pair = `${candidateBoundary(lastSent)}>${candidateBoundary(candidate)}`;
|
|
97
|
+
if (config.fallbackDisclosure?.requireAcknowledgement && candidateBoundary(planned.candidate) !== candidateBoundary(lastSent)) {
|
|
98
|
+
const pair = `${candidateBoundary(lastSent)}>${candidateBoundary(planned.candidate)}`;
|
|
88
99
|
let accepted = decisions.get(pair);
|
|
89
100
|
if (accepted === undefined) {
|
|
90
101
|
const asking = Date.now();
|
|
91
|
-
accepted = options.acknowledgeFallback ? (await options.acknowledgeFallback(fallbackTarget(lastSent), fallbackTarget(candidate), { capability: request.capability, label: request.label })) === true : false;
|
|
102
|
+
accepted = options.acknowledgeFallback ? (await options.acknowledgeFallback(fallbackTarget(lastSent), fallbackTarget(planned.candidate), { capability: request.capability, label: request.label })) === true : false;
|
|
92
103
|
// The time a person takes to decide is not the call's time.
|
|
93
104
|
startedAt += Date.now() - asking;
|
|
94
105
|
decisions.set(pair, accepted);
|
|
95
106
|
}
|
|
96
107
|
if (!accepted) {
|
|
97
|
-
blocked.push({ candidate, from: lastSent, asked: Boolean(options.acknowledgeFallback) });
|
|
108
|
+
blocked.push({ candidate: planned.candidate, from: lastSent, asked: Boolean(options.acknowledgeFallback) });
|
|
109
|
+
steps.push(leftOutStep(planned.candidate, planned.index, "not-acknowledged", secrets, options.githubModelsBaseUrl));
|
|
98
110
|
continue;
|
|
99
111
|
}
|
|
100
112
|
}
|
|
101
|
-
// The first candidate runs for its own deadlines whatever the total; a later one runs for the routing time that is left.
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
toolsOnly: config.toolsOnly !== false,
|
|
116
|
-
...(attempt.built?.thinking ? { thinking: attempt.built.thinking } : {}),
|
|
117
|
-
...(attempt.built?.reasoningParameter ? { reasoningParameter: attempt.built.reasoningParameter } : {}),
|
|
118
|
-
...(skipped.length ? { skipped: skipped.map((entry) => ({ ...entry })) } : {}),
|
|
119
|
-
...(attempt.built?.notes?.length ? { notes: [...attempt.built.notes] } : {}),
|
|
120
|
-
};
|
|
121
|
-
notify(options.onAttempt, attemptReport);
|
|
122
|
-
notify(request.onAttempt, attemptReport);
|
|
123
|
-
const attemptStarted = Date.now();
|
|
124
|
-
const trace = { startedAt: attemptStarted, streamed: false, toolSeen: false };
|
|
125
|
-
lastSent = candidate;
|
|
126
|
-
tried += 1;
|
|
127
|
-
try {
|
|
128
|
-
if (!attempt.built)
|
|
129
|
-
throw attempt.buildError;
|
|
130
|
-
const response = await callCandidate(config, attempt, attempt.built, request, options, deadlines, secrets, trace, refusals);
|
|
131
|
-
const endReport = {
|
|
113
|
+
// The first candidate runs for its own deadlines whatever the total; a later one runs for the routing time that is left (and the same candidate asked again runs for what its first request had).
|
|
114
|
+
const routingLeft = askedCandidates > 0 && maxTotal !== undefined ? () => maxTotal - (Date.now() - startedAt) : undefined;
|
|
115
|
+
/** The ways this candidate was asked without thinking, in order, because the provider refuses a level when the request carries function tools (see `nextWithoutThinking`). */
|
|
116
|
+
const withoutThinking = [];
|
|
117
|
+
/** What its requests carried of the thinking, so far: the level (`level`), none of it (`omit`) or `none`: a way is never asked twice. */
|
|
118
|
+
const sent = new Set();
|
|
119
|
+
/** What the provider said the first time it refused: what a model that then answers is learned from. */
|
|
120
|
+
let refusedWith;
|
|
121
|
+
for (;;) {
|
|
122
|
+
const { candidate } = attempt;
|
|
123
|
+
const deadlines = resolveDeadlines(integration, options, routingLeft?.());
|
|
124
|
+
const destination = candidateDestination(candidate, options.githubModelsBaseUrl);
|
|
125
|
+
const identity = { attemptId: randomId("attempt"), label: request.label, capability: request.capability, provider: integration.provider, model: candidate.model, integrationId: integration.id, index: attempt.index };
|
|
126
|
+
const attemptReport = {
|
|
132
127
|
...identity,
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
...
|
|
141
|
-
...(
|
|
142
|
-
|
|
128
|
+
integrationName: redactSecrets(integration.name, secrets),
|
|
129
|
+
candidates: plan.attempts.length + plan.leftOut.length,
|
|
130
|
+
attempt: tried + 1,
|
|
131
|
+
attempts: plan.attempts.length,
|
|
132
|
+
// Copies: a listener can never change what is sent.
|
|
133
|
+
messages: reportedMessages(attempt.built, request),
|
|
134
|
+
...(attempt.built?.outputLimit ? { maxOutputTokens: attempt.built.outputLimit } : {}),
|
|
135
|
+
...(attempt.built?.apiVersion ? { apiVersion: attempt.built.apiVersion } : {}),
|
|
136
|
+
...(destination.protocol ? { protocol: destination.protocol } : {}),
|
|
137
|
+
stream: attempt.built?.stream ?? false,
|
|
138
|
+
tools: attempt.built?.useTools ?? false,
|
|
139
|
+
endpoint: candidateEndpoint(candidate, options.githubModelsBaseUrl),
|
|
140
|
+
timeoutMs: deadlines.startMs,
|
|
141
|
+
timeouts: { startMs: deadlines.startMs, idleMs: deadlines.idleMs, capMs: deadlines.capMs, ...(deadlines.raisedFrom !== undefined ? { raised: { from: deadlines.raisedFrom } } : {}) },
|
|
142
|
+
streamMode: integration.streamMode === "off" ? "off" : "auto",
|
|
143
|
+
toolsOnly: config.toolsOnly !== false,
|
|
144
|
+
...(attempt.built?.thinking ? { thinking: attempt.built.thinking } : {}),
|
|
145
|
+
thinkingMode: attemptThinking(candidate, attempt.built?.useTools ?? false),
|
|
146
|
+
...(attempt.built?.thinkingWhy ? { thinkingWhy: attempt.built.thinkingWhy } : {}),
|
|
147
|
+
...(attempt.built?.reasoningParameter ? { reasoningParameter: attempt.built.reasoningParameter } : {}),
|
|
148
|
+
...(skipped.length ? { skipped: skipped.map((entry) => ({ ...entry })) } : {}),
|
|
149
|
+
...(steps.some((step) => step.outcome === "left-out") ? { leftOut: sortedRoute(steps.filter((step) => step.outcome === "left-out")).map((step) => ({ ...step })) } : {}),
|
|
150
|
+
...(attempt.built?.notes?.length ? { notes: [...attempt.built.notes] } : {}),
|
|
143
151
|
};
|
|
144
|
-
notify(options.
|
|
145
|
-
notify(request.
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
const
|
|
157
|
-
|
|
152
|
+
notify(options.onAttempt, attemptReport);
|
|
153
|
+
notify(request.onAttempt, attemptReport);
|
|
154
|
+
const attemptStarted = Date.now();
|
|
155
|
+
const trace = { startedAt: attemptStarted, streamed: false, toolSeen: false };
|
|
156
|
+
lastSent = candidate;
|
|
157
|
+
tried += 1;
|
|
158
|
+
if (withoutThinking.length === 0)
|
|
159
|
+
askedCandidates += 1;
|
|
160
|
+
sent.add(attempt.built?.thinking === "none" ? "none" : attempt.built?.thinking ? "level" : "omit");
|
|
161
|
+
try {
|
|
162
|
+
if (!attempt.built)
|
|
163
|
+
throw attempt.buildError;
|
|
164
|
+
const response = await callCandidate(config, attempt, attempt.built, request, options, deadlines, secrets, trace, refusals);
|
|
165
|
+
const endReport = {
|
|
166
|
+
...identity,
|
|
167
|
+
outcome: "ok",
|
|
168
|
+
usage: response.usage,
|
|
169
|
+
usageKnown: response.usageKnown ?? false,
|
|
170
|
+
cost: response.cost,
|
|
171
|
+
costKnown: response.costKnown ?? false,
|
|
172
|
+
currency: response.currency,
|
|
173
|
+
text: response.text,
|
|
174
|
+
...replyTrace(trace, Boolean(request.json)),
|
|
175
|
+
...(trace.transport ? { transport: trace.transport } : {}),
|
|
176
|
+
durationMs: Date.now() - attemptStarted,
|
|
177
|
+
};
|
|
178
|
+
notify(options.onAttemptEnd, endReport);
|
|
179
|
+
notify(request.onAttemptEnd, endReport);
|
|
180
|
+
// The model answered when it was asked without thinking: that is what is learned of it, once. A model that no way answered is learned nothing of.
|
|
181
|
+
if (refusedWith && withoutThinking.length) {
|
|
182
|
+
const learning = { kind: "no-thinking-with-tools", integrationId: integration.id, integrationName: redactSecrets(integration.name, secrets), model: candidate.model, off: withoutThinking[withoutThinking.length - 1], body: refusedWith };
|
|
183
|
+
try {
|
|
184
|
+
request.memory?.learn(learning);
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
// A host's memory must never break a call.
|
|
188
|
+
}
|
|
189
|
+
notify(request.onLearned, learning);
|
|
190
|
+
notify(options.onLearned, learning);
|
|
191
|
+
}
|
|
192
|
+
return withSpent(response, spent);
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
// A host that is ending (a page that is reloaded) cancelled the request as much as the author did: its failure is not the provider's, and the prompt goes to no other candidate.
|
|
196
|
+
const interrupted = options.interrupted?.() === true;
|
|
197
|
+
const cancelled = (Boolean(request.signal?.aborted) && isAbortError(error)) || interrupted;
|
|
198
|
+
const failedReport = failedAttempt(identity, error, cancelled, deadlines.startMs, Date.now() - attemptStarted, secrets, replyTrace(trace, Boolean(request.json)));
|
|
199
|
+
notify(options.onAttemptEnd, failedReport);
|
|
200
|
+
notify(request.onAttemptEnd, failedReport);
|
|
201
|
+
if (cancelled)
|
|
202
|
+
throw error;
|
|
203
|
+
if (error instanceof AiProviderError && !error.target) {
|
|
204
|
+
error.target = { provider: integration.provider, model: candidate.model, integrationId: integration.id, ...(destination.endpoint ? { endpoint: destination.endpoint } : {}), ...(attempt.built?.apiVersion ? { apiVersion: attempt.built.apiVersion } : {}), ...(destination.protocol ? { protocol: destination.protocol } : {}), ...(destination.path ? { path: redactSecrets(destination.path, secrets) } : {}) };
|
|
205
|
+
}
|
|
206
|
+
steps.push(triedStep(attempt, failedReport, error, destination, secrets));
|
|
207
|
+
addSpent(spent, error);
|
|
208
|
+
lastError = error;
|
|
209
|
+
notify(request.onText, "");
|
|
210
|
+
notify(request.onStructuredText, "");
|
|
211
|
+
// A provider that refuses a thinking level because the request carries function tools is asked again without it, and if that is refused too, with `none` (the GPT-6 models take no request with
|
|
212
|
+
// tools that leaves the level out): each way once. The model is remembered by the way that answers, so that every later request with tools is asked that way (a request without tools keeps its
|
|
213
|
+
// level). Every request stays in the trail as the failed attempt it was, with the provider's words.
|
|
214
|
+
const next = nextWithoutThinking(candidate, attempt.built, error, sent);
|
|
215
|
+
if (next) {
|
|
216
|
+
const asked = { ...candidate, noThinkingWithTools: next === "none" ? "none" : true };
|
|
217
|
+
try {
|
|
218
|
+
attempt = { ...attempt, candidate: asked, built: buildChatRequest(asked, request, { githubModelsBaseUrl: options.githubModelsBaseUrl }) };
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
withoutThinking.push(next);
|
|
224
|
+
if (!refusedWith)
|
|
225
|
+
refusedWith = error.body;
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
// Asked every way, and refused every time: the provider's last words are the error, with what was tried, and where the provider says function tools are taken.
|
|
229
|
+
if (withoutThinking.length && error instanceof AiProviderError)
|
|
230
|
+
error.message = redactSecrets(`${error.message}${/[.!?]$/.test(error.message) ? "" : "."} ${refusedEveryWay(withoutThinking, refusedWith, integration.provider)}`, secrets);
|
|
231
|
+
break;
|
|
158
232
|
}
|
|
159
|
-
addSpent(spent, error);
|
|
160
|
-
lastError = error;
|
|
161
|
-
notify(request.onText, "");
|
|
162
|
-
notify(request.onStructuredText, "");
|
|
163
233
|
}
|
|
164
234
|
}
|
|
165
235
|
const notes = [];
|
|
@@ -167,6 +237,14 @@ export function createFetchAi(config, options = {}) {
|
|
|
167
237
|
notes.push(`Fallbacks in other accounts were not tried because "Never send fallback content outside the primary account" (fallbackDisclosure.sameBoundaryOnly) is on.`);
|
|
168
238
|
for (const entry of plan.skipped)
|
|
169
239
|
notes.push(redactSecrets(`Skipped "${entry.candidate.model}" in "${entry.candidate.integration.name}": it is marked as without tool calls and "Tools only" is on.`, secrets));
|
|
240
|
+
for (const step of plan.leftOut) {
|
|
241
|
+
if (step.leftOut === "context-window")
|
|
242
|
+
notes.push(`Skipped "${step.model}" in "${step.integrationName}": the prompt (about ${step.promptTokens} tokens) does not fit its context window (${step.windowTokens} tokens are left for the prompt).`);
|
|
243
|
+
else if (step.leftOut === "budget")
|
|
244
|
+
notes.push(`Not tried: "${step.model}" in "${step.integrationName}": the routing limits of tokens or cost (maxTokenAttempts, maxEstimatedCost) were reached.`);
|
|
245
|
+
else if (step.leftOut === "unusable")
|
|
246
|
+
notes.push(`Not tried: "${step.model}" in "${step.integrationName}" cannot be called (${UNUSABLE_WORDS[step.why ?? "model-missing"]}).`);
|
|
247
|
+
}
|
|
170
248
|
if (blocked.length) {
|
|
171
249
|
const names = [...new Set(blocked.map((entry) => `"${entry.candidate.integration.name}"`))].join(", ");
|
|
172
250
|
const from = `"${blocked[0].from.integration.name}"`;
|
|
@@ -176,6 +254,7 @@ export function createFetchAi(config, options = {}) {
|
|
|
176
254
|
}
|
|
177
255
|
if (outOfTime)
|
|
178
256
|
notes.push(`Fallbacks were not tried: the total routing time (maxTotalDurationMs, ${Math.round((plan.limits.maxTotalDurationMs ?? 0) / 1000)} s) was used up.`);
|
|
257
|
+
const route = sortedRoute(steps);
|
|
179
258
|
if (lastError instanceof AiProviderError) {
|
|
180
259
|
lastError.usage = spent.usage ?? lastError.usage;
|
|
181
260
|
lastError.cost = spent.cost ?? lastError.cost;
|
|
@@ -187,14 +266,72 @@ export function createFetchAi(config, options = {}) {
|
|
|
187
266
|
lastError.retryAfterMs = Math.max(lastError.retryAfterMs ?? 0, spent.retryAfterMs);
|
|
188
267
|
if (notes.length)
|
|
189
268
|
lastError.message = `${lastError.message}${/[.!?]$/.test(lastError.message) ? "" : "."} ${notes.join(" ")}`;
|
|
269
|
+
lastError.route = route;
|
|
190
270
|
throw lastError;
|
|
191
271
|
}
|
|
192
272
|
if (lastError instanceof Error)
|
|
193
|
-
throw lastError;
|
|
194
|
-
|
|
273
|
+
throw Object.assign(lastError, { route });
|
|
274
|
+
const none = notes.length ? new AiFallbackBlockedError(notes.join(" ")) : new AiProviderError("All AI candidates failed.");
|
|
275
|
+
none.route = route;
|
|
276
|
+
throw none;
|
|
195
277
|
},
|
|
196
278
|
};
|
|
197
279
|
}
|
|
280
|
+
/** What a target of the route that cannot be called says of itself, in the words of the notes of a failed call. */
|
|
281
|
+
const UNUSABLE_WORDS = {
|
|
282
|
+
"integration-missing": "its integration is no longer there",
|
|
283
|
+
"provider-unsupported": "its provider cannot run chat tasks here",
|
|
284
|
+
"model-missing": "the model is not in the integration",
|
|
285
|
+
"task-not-allowed": "the model is not allowed for this task",
|
|
286
|
+
};
|
|
287
|
+
/** The most characters of what a provider said that a step of a route keeps. */
|
|
288
|
+
const MAX_STEP_MESSAGE_CHARACTERS = 240;
|
|
289
|
+
/** The step that says how an attempt ended, from the report of its end (whose words are already cleaned of credentials). */
|
|
290
|
+
/**
|
|
291
|
+
* How a candidate is asked next, when its provider refused the request because it carries function tools together with a thinking level («Function tools with reasoning_effort are not supported…»), or
|
|
292
|
+
* `undefined` when there is no way left: without a level first (a model of the GPT-5.6 family still reasons then), then with `none` (the GPT-6 models refuse a request with tools that leaves the level out,
|
|
293
|
+
* and take `none`), each way once (`sent` says which were put on the wire, the first request included), and `none` only for a model that takes its level in `reasoning_effort`. A refusal of the value of the
|
|
294
|
+
* level («does not support 'none' with this model») is not this: that model takes function tools on the Responses API only.
|
|
295
|
+
*/
|
|
296
|
+
function nextWithoutThinking(candidate, built, error, sent) {
|
|
297
|
+
// The Responses API takes function tools with a thinking level: a refusal there is no refusal of this kind, and asking again without the level would be the same request.
|
|
298
|
+
if (!(error instanceof AiProviderError) || !built?.useTools || built.protocol === "responses" || !refusesThinkingWithTools(error.body))
|
|
299
|
+
return undefined;
|
|
300
|
+
return ["omit", "none"].find((way) => !sent.has(way) && (way !== "none" || canSendNone(candidate)));
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* What an error says after a model was asked every way without thinking and refused function tools each time: what was tried, and, when the provider says it, where the tools are taken, and what to set so that
|
|
304
|
+
* they are (the model's API protocol, for a provider that has the Responses API).
|
|
305
|
+
*/
|
|
306
|
+
function refusedEveryWay(tried, first, provider) {
|
|
307
|
+
const how = tried.includes("none") ? "without a thinking level and with \"none\"" : "without a thinking level";
|
|
308
|
+
const responses = suggestsResponsesApi(first);
|
|
309
|
+
return `Narrarium asked again ${how}, and the model still refuses function tools on this endpoint${responses ? ": the provider says to use /v1/responses for them" : ""}.${responses && provider !== "github_models" ? ' Set the "API protocol" of the model to "Responses API" in AI Integrations to use them.' : ""}`;
|
|
310
|
+
}
|
|
311
|
+
function triedStep(attempt, end, error, destination, secrets) {
|
|
312
|
+
const integration = attempt.candidate.integration;
|
|
313
|
+
const timeout = error instanceof AiProviderError ? error.timeout : undefined;
|
|
314
|
+
const message = (end.error ?? "").replace(/\s+/g, " ").trim();
|
|
315
|
+
return {
|
|
316
|
+
position: attempt.index,
|
|
317
|
+
integrationId: redactSecrets(integration.id, secrets),
|
|
318
|
+
integrationName: redactSecrets(integration.name, secrets),
|
|
319
|
+
provider: integration.provider,
|
|
320
|
+
model: redactSecrets(attempt.candidate.model, secrets),
|
|
321
|
+
outcome: end.outcome === "cancelled" ? "cancelled" : end.failureKind === "timeout" ? "timeout" : "failed",
|
|
322
|
+
...(destination.endpoint ? { endpoint: destination.endpoint } : {}),
|
|
323
|
+
...(destination.path ? { path: redactSecrets(destination.path, secrets) } : {}),
|
|
324
|
+
...(attempt.built?.apiVersion ? { apiVersion: attempt.built.apiVersion } : {}),
|
|
325
|
+
...(destination.protocol ? { protocol: destination.protocol } : {}),
|
|
326
|
+
...(end.status !== undefined ? { status: end.status } : {}),
|
|
327
|
+
...(end.errorBody ? { body: end.errorBody } : {}),
|
|
328
|
+
durationMs: end.durationMs,
|
|
329
|
+
...(message ? { message: message.length > MAX_STEP_MESSAGE_CHARACTERS ? `${message.slice(0, MAX_STEP_MESSAGE_CHARACTERS - 1)}…` : message } : {}),
|
|
330
|
+
...(end.failureKind === "timeout" && end.timeoutPhase ? { timeoutPhase: end.timeoutPhase } : {}),
|
|
331
|
+
...(end.failureKind === "timeout" && end.timeoutMs !== undefined ? { timeoutMs: end.timeoutMs } : {}),
|
|
332
|
+
...(timeout?.routing ? { routing: true } : {}),
|
|
333
|
+
};
|
|
334
|
+
}
|
|
198
335
|
function sumUsage(left, right) {
|
|
199
336
|
if (!left)
|
|
200
337
|
return right;
|
|
@@ -253,6 +390,7 @@ function failedAttempt(identity, error, cancelled, timeoutMs, durationMs, secret
|
|
|
253
390
|
failureKind: cancelled ? "cancelled" : timedOut ? "timeout" : "provider",
|
|
254
391
|
...(provider?.status !== undefined ? { status: provider.status } : {}),
|
|
255
392
|
...(provider?.retryAfterMs !== undefined ? { retryAfterMs: provider.retryAfterMs } : {}),
|
|
393
|
+
...(provider?.body ? { errorBody: provider.body } : {}),
|
|
256
394
|
...(timedOut ? { timeoutMs: provider?.timeout?.ms ?? timeoutMs } : {}),
|
|
257
395
|
...(timedOut && provider?.timeout ? { timeoutPhase: provider.timeout.phase } : {}),
|
|
258
396
|
...reply,
|
|
@@ -309,52 +447,43 @@ function parseRetryAfter(value) {
|
|
|
309
447
|
const TRANSIENT_STATUSES = new Set([408, 429, 502, 503, 504, 520, 521, 522, 523, 524]);
|
|
310
448
|
/**
|
|
311
449
|
* What a refusal of the thinking parameter says: the name of the one that the level travels in, in the provider's message or in the `param` of its error
|
|
312
|
-
* object (some providers say only `"param": "reasoning_effort"`): the OpenAI field, or the chat-template argument (`chat_template_kwargs`, `reasoning_strength`).
|
|
450
|
+
* object (some providers say only `"param": "reasoning_effort"`): the OpenAI field (`reasoning.effort` in the Responses API), or the chat-template argument (`chat_template_kwargs`, `reasoning_strength`).
|
|
313
451
|
* Either name is a refusal of the level, whichever of the two was sent: a gateway may answer with the name of the one it translated it into, and the remedy is
|
|
314
452
|
* the same setting.
|
|
315
453
|
*/
|
|
316
|
-
const THINKING_PARAMETER = /reasoning[\
|
|
317
|
-
/** What to change when a model refuses its level: the "Thinking parameter" of the model (to the other of the two, or to none), or the thinking of the task or of the integration. */
|
|
454
|
+
const THINKING_PARAMETER = /reasoning[\s._-]?effort|reasoning[\s_-]?strength|chat[\s_-]?template[\s_-]?kwargs/i;
|
|
455
|
+
/** What to change when a model refuses its level: the "Thinking parameter" of the model (to the other of the two, or to none), or the thinking of the task or of the integration. The Responses API has one field for the level, so there is no other to offer. */
|
|
318
456
|
function thinkingRemedy(model, sent) {
|
|
319
457
|
const other = sent.parameter === "reasoning_effort"
|
|
320
458
|
? `"chat_template_kwargs.reasoning_strength" (the level as an argument of the chat template, as Muse Glimmer takes it)`
|
|
321
459
|
: `"reasoning_effort" (the OpenAI field)`;
|
|
322
|
-
|
|
460
|
+
const choices = sent.parameter === "reasoning.effort" ? `"none" (no level is sent)` : `${other} or to "none" (no level is sent)`;
|
|
461
|
+
return `Set "Thinking parameter" of the model "${model}" in AI Integrations to ${choices}, or set thinking to "Automatic" for this task in the AI Router, or for the integration "${sent.integration}" in AI Integrations.`;
|
|
323
462
|
}
|
|
324
|
-
/**
|
|
463
|
+
/**
|
|
464
|
+
* The error of a response that is not OK: what the provider answered, read as its words (`AiErrorBody`: the status, the message, the type, the parameter and the code of its error, or its text when it is no
|
|
465
|
+
* known shape, or only the status when it said nothing), whole, and never cut but with an ellipsis. `sent` says where the level went when the request carried a thinking level: a refusal of that parameter is
|
|
466
|
+
* then said in the author's words too.
|
|
467
|
+
*/
|
|
325
468
|
async function providerError(response, provider, model, redact, sent) {
|
|
326
|
-
let
|
|
327
|
-
/** The parameter the provider says it refuses, when its error object names one. */
|
|
328
|
-
let param = "";
|
|
469
|
+
let text = "";
|
|
329
470
|
try {
|
|
330
|
-
|
|
331
|
-
const raw = redact(text.length > 50_000 ? text.slice(0, 50_000) : text).slice(0, 2000);
|
|
332
|
-
try {
|
|
333
|
-
const parsed = JSON.parse(raw);
|
|
334
|
-
const message = typeof parsed.error === "string" ? parsed.error : parsed.error?.message ?? parsed.message;
|
|
335
|
-
const refused = typeof parsed.error === "object" && parsed.error ? parsed.error.param : parsed.param;
|
|
336
|
-
if (typeof refused === "string")
|
|
337
|
-
param = refused;
|
|
338
|
-
detail = typeof message === "string" ? message : raw;
|
|
339
|
-
}
|
|
340
|
-
catch {
|
|
341
|
-
// A gateway in front of the provider answers with a page of its own (Cloudflare's 524, an nginx 502): its title says what it is, its markup says nothing.
|
|
342
|
-
const page = /^\s*<(?:!doctype\s+html|html)\b/i.test(raw) ? /<title[^>]*>([^<]{1,200})<\/title>/i.exec(raw)?.[1]?.replace(/\s+/g, " ").trim() : undefined;
|
|
343
|
-
detail = /^\s*<(?:!doctype\s+html|html)\b/i.test(raw) ? `an HTML page from a gateway or a proxy${page ? ` ("${page}")` : ""}, not an answer of the provider` : raw;
|
|
344
|
-
}
|
|
471
|
+
text = await response.text();
|
|
345
472
|
}
|
|
346
473
|
catch {
|
|
347
|
-
|
|
474
|
+
text = response.statusText ?? "";
|
|
348
475
|
}
|
|
349
476
|
const status = response.status;
|
|
477
|
+
const body = parseErrorBody(status, text, redact);
|
|
478
|
+
const said = describeErrorBody(body);
|
|
350
479
|
const retryable = status === 408 || status === 409 || status === 429 || status >= 500;
|
|
351
480
|
const retryAfterMs = status === 429 || status === 503 ? parseRetryAfter(response.headers?.get?.("retry-after")) : undefined;
|
|
352
|
-
|
|
353
|
-
//
|
|
354
|
-
if (sent !== undefined && (status === 400 || status === 422) && THINKING_PARAMETER.test(`${
|
|
355
|
-
return new AiProviderError(redact(`${provider} ${model}: the model does not accept a thinking level (${said}). Nothing was applied. ${thinkingRemedy(model, sent)}`), status, false);
|
|
481
|
+
// A level was sent and the provider refuses the parameter: the same request would be refused again, so it is no use to repeat it. (A level refused only because the request carries function tools is not
|
|
482
|
+
// this: that request is asked again without it, and the provider's own words are all there is to say.)
|
|
483
|
+
if (sent !== undefined && (status === 400 || status === 422) && THINKING_PARAMETER.test(`${body.message ?? body.raw ?? ""} ${body.param ?? ""}`) && !refusesThinkingWithTools(body)) {
|
|
484
|
+
return new AiProviderError(redact(`${provider} ${model}: the model does not accept a thinking level (${said}). Nothing was applied. ${thinkingRemedy(model, sent)}`), status, false, { body });
|
|
356
485
|
}
|
|
357
|
-
return new AiProviderError(redact(`${provider} ${model}: ${said}`), status, retryable, { ...(TRANSIENT_STATUSES.has(status) ? { transient: true } : {}), ...(retryAfterMs !== undefined ? { retryAfterMs } : {}) });
|
|
486
|
+
return new AiProviderError(redact(`${provider} ${model}: ${said}`), status, retryable, { body, ...(TRANSIENT_STATUSES.has(status) ? { transient: true } : {}), ...(retryAfterMs !== undefined ? { retryAfterMs } : {}) });
|
|
358
487
|
}
|
|
359
488
|
/** 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). */
|
|
360
489
|
class StreamReadError extends Error {
|
|
@@ -547,8 +676,8 @@ async function readJsonBody(response, clock, onChunk) {
|
|
|
547
676
|
}
|
|
548
677
|
const COMPLETE_REASONS = new Set(["stop", "tool_calls", "function_call", "end_turn", "stop_sequence", "tool_use", "eos"]);
|
|
549
678
|
const TRUNCATED_REASONS = new Set(["length", "max_tokens", "max_output_tokens", "model_length", "context_length_exceeded"]);
|
|
550
|
-
const FILTERED_REASONS = new Set(["content_filter", "safety", "blocked", "recitation", "prohibited_content"]);
|
|
551
|
-
const FAILED_REASONS = new Set(["error", "failed", "abort", "aborted", "cancelled", "canceled"]);
|
|
679
|
+
const FILTERED_REASONS = new Set(["content_filter", "safety", "blocked", "recitation", "prohibited_content", "refusal"]);
|
|
680
|
+
const FAILED_REASONS = new Set(["error", "failed", "abort", "aborted", "cancelled", "canceled", "incomplete"]);
|
|
552
681
|
/**
|
|
553
682
|
* What a provider's `finish_reason` says about a reply. A known reason decides by itself. A reason this client does
|
|
554
683
|
* not know is trusted only when the response also ended properly (`ended`: the `[DONE]` marker of a stream); with no
|
|
@@ -568,8 +697,8 @@ export function classifyFinishReason(reason, ended) {
|
|
|
568
697
|
return "failed";
|
|
569
698
|
return ended ? "complete" : "unexpected";
|
|
570
699
|
}
|
|
571
|
-
const PERMANENT_STREAM_ERROR = /authenticat|unauthori[sz]ed|forbidden|permission|invalid[_ -]?(?:request|api[_ -]?key|argument|parameter)|bad[_ -]?request/i;
|
|
572
|
-
const TRANSIENT_STREAM_ERROR = /overload|rate[_ -]?limit|too many requests|temporar|unavailable|busy|try again|time[ds]? ?out|capacity/i;
|
|
700
|
+
const PERMANENT_STREAM_ERROR = /authenticat|unauthori[sz]ed|forbidden|permission|invalid[_ -]?(?:request|api[_ -]?key|argument|parameter)|bad[_ -]?request|user[_ -]?error/i;
|
|
701
|
+
const TRANSIENT_STREAM_ERROR = /overload|rate[_ -]?limit|too[_ ]many[_ ]requests|temporar|unavailable|busy|try again|time[ds]? ?out|capacity/i;
|
|
573
702
|
/**
|
|
574
703
|
* A failure the provider reported inside the stream (`{"error": {...}}`, `{"error": "..."}`, or an `event: error`), or `null` when the
|
|
575
704
|
* chunk carries none. It is retried unless its status or code says authentication or an invalid request. `started`: the model had already written something, so the provider was answering
|
|
@@ -588,11 +717,12 @@ function streamError(value, label, details, redact, started) {
|
|
|
588
717
|
const words = [source?.type, source?.code, source?.status].filter((entry) => typeof entry === "string").join(" ");
|
|
589
718
|
const permanent = (status !== undefined && status >= 400 && status < 500 && status !== 408 && status !== 409 && status !== 429) || PERMANENT_STREAM_ERROR.test(words);
|
|
590
719
|
const transient = !permanent && ((status !== undefined && TRANSIENT_STATUSES.has(status)) || TRANSIENT_STREAM_ERROR.test(`${message} ${words}`));
|
|
591
|
-
const
|
|
720
|
+
const body = errorBodyOfObject(value, status ?? 200, redact);
|
|
721
|
+
const detail = body ? describeErrorBody(body).replace(/^HTTP \d+(?:, no body| — )?/, "") || "no details" : "no details";
|
|
592
722
|
const said = redact(`${label}: the provider reported an error during the reply — ${detail}`);
|
|
593
723
|
if (started && !permanent)
|
|
594
|
-
return new AiStreamInterruptedError(said, "provider-error", status, details);
|
|
595
|
-
return new AiProviderError(said, status, !permanent, { ...details, ...(transient ? { transient: true } : {}) });
|
|
724
|
+
return new AiStreamInterruptedError(said, "provider-error", status, { ...details, ...(body ? { body } : {}) });
|
|
725
|
+
return new AiProviderError(said, status, !permanent, { ...details, ...(body ? { body } : {}), ...(transient ? { transient: true } : {}) });
|
|
596
726
|
}
|
|
597
727
|
/**
|
|
598
728
|
* Characters of reasoning a reply carried. Only the count is kept, never the reasoning itself. The reasoning is in `reasoning_content` (llama.cpp, DeepSeek, older vLLM) or in `reasoning`
|
|
@@ -640,6 +770,8 @@ function chosenArguments(calls, wanted) {
|
|
|
640
770
|
}
|
|
641
771
|
/** What of the end of a stream is kept to cut the reported tail from: longer than the tail, so that a credential that the cut would divide has been replaced whole before it is. */
|
|
642
772
|
const TAIL_WINDOW_CHARACTERS = TRANSPORT_TAIL_CHARACTERS * 3;
|
|
773
|
+
/** The most characters of what a model refused with that an error shows. */
|
|
774
|
+
const MAX_REFUSAL_CHARACTERS = 300;
|
|
643
775
|
/** The headers in which a provider or its gateway puts the id of a request: it is what they look a call up by in their logs. */
|
|
644
776
|
const REQUEST_ID_HEADERS = ["x-llmproxy-request-id", "x-request-id", "request-id", "x-ms-request-id", "apim-request-id"];
|
|
645
777
|
/** The most addresses a set of refusals of `stream_options` keeps. */
|
|
@@ -711,6 +843,12 @@ async function callCandidate(config, attempt, built, request, options, deadlines
|
|
|
711
843
|
let usage;
|
|
712
844
|
let finishReason = "";
|
|
713
845
|
let reasoningCharacters = 0;
|
|
846
|
+
/** The tokens the provider says the model spent reasoning, for a reasoning that is not shown (the Responses API): the characters of it that were seen are none. */
|
|
847
|
+
let reasoningTokens = 0;
|
|
848
|
+
/** What the model said when it refused to answer (the Responses API). */
|
|
849
|
+
let refusal = "";
|
|
850
|
+
/** The reply is read as the Responses API tells it: one reader per attempt, whose events become the chunks that Chat Completions has. */
|
|
851
|
+
const responsesReader = built.protocol === "responses" ? new ResponsesStreamReader() : undefined;
|
|
714
852
|
/** The function calls of a streamed reply by their index, in the order they came. */
|
|
715
853
|
const calls = new Map();
|
|
716
854
|
/** The arguments of a call that came whole: in the message of a JSON reply, or in the last piece of a stream. */
|
|
@@ -728,8 +866,8 @@ async function callCandidate(config, attempt, built, request, options, deadlines
|
|
|
728
866
|
let tailCharacters = 0;
|
|
729
867
|
let status;
|
|
730
868
|
let requestId;
|
|
731
|
-
/** The request that is answered asks the provider for the tokens of the stream (`stream_options.include_usage
|
|
732
|
-
let usageRequested = Boolean(built.body.stream_options);
|
|
869
|
+
/** The request that is answered asks the provider for the tokens of the stream (`stream_options.include_usage`; the Responses API always ends its stream with them). */
|
|
870
|
+
let usageRequested = Boolean(responsesReader) || Boolean(built.body.stream_options);
|
|
733
871
|
let lastProgressAt;
|
|
734
872
|
let response;
|
|
735
873
|
/** Where the call is, to say what went wrong when something does. */
|
|
@@ -803,7 +941,7 @@ async function callCandidate(config, attempt, built, request, options, deadlines
|
|
|
803
941
|
...(answering ? details({}, "timeout") : {}),
|
|
804
942
|
transient: true,
|
|
805
943
|
timedOut: true,
|
|
806
|
-
timeout: { phase: expired.phase, ms: expired.ms, ...(expired.phase === "start" && deadlines.raisedFrom !== undefined ? { raisedFrom: deadlines.raisedFrom } : {}) },
|
|
944
|
+
timeout: { phase: expired.phase, ms: expired.ms, ...(expired.phase === "start" && deadlines.raisedFrom !== undefined ? { raisedFrom: deadlines.raisedFrom } : {}), ...(deadlines.routingMs !== undefined && expired.ms === deadlines.routingMs ? { routing: true } : {}) },
|
|
807
945
|
});
|
|
808
946
|
const reportProgress = () => {
|
|
809
947
|
if (!request.onProgress)
|
|
@@ -854,7 +992,11 @@ async function callCandidate(config, attempt, built, request, options, deadlines
|
|
|
854
992
|
else {
|
|
855
993
|
if (parsed === undefined)
|
|
856
994
|
return;
|
|
857
|
-
|
|
995
|
+
// The Responses API tells its events by name, and a few of them are the reply: they become the chunks that the rest of this reads.
|
|
996
|
+
const read = responsesReader ? responsesReader.read(parsed, event) : parsed;
|
|
997
|
+
if (!read)
|
|
998
|
+
return;
|
|
999
|
+
chunk = read;
|
|
858
1000
|
}
|
|
859
1001
|
if (!chunk || typeof chunk !== "object")
|
|
860
1002
|
return;
|
|
@@ -866,7 +1008,11 @@ async function callCandidate(config, attempt, built, request, options, deadlines
|
|
|
866
1008
|
const choices = Array.isArray(chunk.choices) ? chunk.choices : [];
|
|
867
1009
|
const first = choices[0];
|
|
868
1010
|
const delta = first?.delta;
|
|
869
|
-
reasoningCharacters += reasoningLength(delta);
|
|
1011
|
+
reasoningCharacters += reasoningLength(delta) + (chunk.reasoningCharacters ?? 0);
|
|
1012
|
+
if (typeof chunk.reasoningTokens === "number")
|
|
1013
|
+
reasoningTokens = chunk.reasoningTokens;
|
|
1014
|
+
if (chunk.refusal)
|
|
1015
|
+
refusal = chunk.refusal;
|
|
870
1016
|
if (reasoningCharacters > MAX_STREAM_REASONING_CHARACTERS)
|
|
871
1017
|
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)`);
|
|
872
1018
|
if (delta?.content) {
|
|
@@ -916,7 +1062,7 @@ async function callCandidate(config, attempt, built, request, options, deadlines
|
|
|
916
1062
|
};
|
|
917
1063
|
// What is sent: an address that refused `stream_options` before is not asked it again.
|
|
918
1064
|
let body = built.body;
|
|
919
|
-
if (usageRequested && refusals.has(built.url)) {
|
|
1065
|
+
if (usageRequested && !responsesReader && refusals.has(built.url)) {
|
|
920
1066
|
body = withoutUsageOption(body);
|
|
921
1067
|
usageRequested = false;
|
|
922
1068
|
}
|
|
@@ -950,10 +1096,10 @@ async function callCandidate(config, attempt, built, request, options, deadlines
|
|
|
950
1096
|
if (response.ok)
|
|
951
1097
|
break;
|
|
952
1098
|
trace.firstByteMs ??= elapsed();
|
|
953
|
-
const failure = await clock.guard(providerError(response, integration.provider, model, redact, built.thinking ? { integration: integration.name, parameter: built.reasoningParameter ?? "reasoning_effort" } : undefined));
|
|
1099
|
+
const failure = await clock.guard(providerError(response, integration.provider, model, redact, built.thinking && built.thinkingWhy !== "tools" ? { integration: integration.name, parameter: built.protocol === "responses" ? "reasoning.effort" : built.reasoningParameter ?? "reasoning_effort" } : undefined));
|
|
954
1100
|
failure.transport = transport();
|
|
955
1101
|
// A provider that refuses `stream_options` is asked again, at once, without it, and is not asked it again: its replies carry no token count, which is then an estimate.
|
|
956
|
-
if (usageRequested && refusesUsageOption(failure, label)) {
|
|
1102
|
+
if (usageRequested && !responsesReader && refusesUsageOption(failure, label)) {
|
|
957
1103
|
if (refusals.size >= MAX_REMEMBERED_REFUSALS)
|
|
958
1104
|
refusals.delete(refusals.values().next().value);
|
|
959
1105
|
refusals.add(built.url);
|
|
@@ -985,13 +1131,15 @@ async function callCandidate(config, attempt, built, request, options, deadlines
|
|
|
985
1131
|
trace.streamed = streamed;
|
|
986
1132
|
if (streamed) {
|
|
987
1133
|
stage = "stream";
|
|
988
|
-
|
|
1134
|
+
// A stream of Chat Completions ends with `[DONE]`; the Responses API has no such marker: its last event (`response.completed`, `response.incomplete` or `response.failed`) is the end.
|
|
1135
|
+
ended = (await readEventStream(response, clock, hooks)) || Boolean(responsesReader?.finished);
|
|
989
1136
|
streamEnd = ended ? "done" : "closed";
|
|
990
1137
|
}
|
|
991
1138
|
else {
|
|
992
1139
|
stage = "json";
|
|
993
1140
|
trace.firstByteMs ??= elapsed();
|
|
994
|
-
const
|
|
1141
|
+
const raw = await readJsonBody(response, clock, (count, decoded) => chunkArrived(count, decoded, "reply"));
|
|
1142
|
+
const payload = (responsesReader ? responseAsChat(raw) : raw);
|
|
995
1143
|
if (payload?.error) {
|
|
996
1144
|
const failure = streamError(payload.error, label, details(), redact, false);
|
|
997
1145
|
if (failure)
|
|
@@ -1003,7 +1151,9 @@ async function callCandidate(config, attempt, built, request, options, deadlines
|
|
|
1003
1151
|
if (Array.isArray(choice?.message?.tool_calls) && choice.message.tool_calls.length)
|
|
1004
1152
|
trace.toolSeen = true;
|
|
1005
1153
|
finishReason = typeof choice?.finish_reason === "string" ? choice.finish_reason : "";
|
|
1006
|
-
reasoningCharacters = reasoningLength(choice?.message);
|
|
1154
|
+
reasoningCharacters = reasoningLength(choice?.message) + (payload?.reasoningCharacters ?? 0);
|
|
1155
|
+
reasoningTokens = payload?.reasoningTokens ?? 0;
|
|
1156
|
+
refusal = payload?.refusal ?? "";
|
|
1007
1157
|
usage = normalizeUsage(payload?.usage);
|
|
1008
1158
|
// A plain reply that came whole still reaches the listener of the text, once.
|
|
1009
1159
|
if (!structured && text)
|
|
@@ -1029,8 +1179,11 @@ async function callCandidate(config, attempt, built, request, options, deadlines
|
|
|
1029
1179
|
throw new AiStreamInterruptedError(`${label}: unexpected finish reason "${shown}" and the stream did not end with [DONE]: the reply may be incomplete.`, "ended", undefined, details());
|
|
1030
1180
|
if (outcome === "failed")
|
|
1031
1181
|
throw new AiStreamInterruptedError(`${label}: the provider ended the reply with the finish reason "${shown}".`, /abort|cancel/i.test(shown) ? "provider-abort" : "provider-error", undefined, details({}, "error"));
|
|
1032
|
-
if (outcome === "filtered")
|
|
1033
|
-
|
|
1182
|
+
if (outcome === "filtered") {
|
|
1183
|
+
// A model that refuses says so in words of its own (the Responses API gives them apart from the text); they are shown as they are, cut short.
|
|
1184
|
+
const said = redact(refusal).replace(/\s+/g, " ").trim();
|
|
1185
|
+
throw new AiProviderError(shown === "refusal" ? `${label}: the model refused to answer${said ? `: "${said.length > MAX_REFUSAL_CHARACTERS ? `${said.slice(0, MAX_REFUSAL_CHARACTERS)}…` : said}"` : ""}.` : `${label}: the provider filtered the reply content (${shown}).`, undefined, false, details());
|
|
1186
|
+
}
|
|
1034
1187
|
// Some local servers leave the reasoning in the content as a leading <think> block: it is not the reply.
|
|
1035
1188
|
const inline = splitReasoningBlock(text);
|
|
1036
1189
|
text = inline.reply;
|
|
@@ -1038,14 +1191,14 @@ async function callCandidate(config, attempt, built, request, options, deadlines
|
|
|
1038
1191
|
const toolArguments = callArguments();
|
|
1039
1192
|
const answered = Boolean(text.trim() || toolArguments.trim());
|
|
1040
1193
|
if (outcome === "truncated") {
|
|
1041
|
-
const seen = !answered && reasoningCharacters > 0;
|
|
1194
|
+
const seen = !answered && (reasoningCharacters > 0 || reasoningTokens > 0);
|
|
1042
1195
|
// A model that is declared as reasoning and wrote nothing spent its limit on a reasoning that it does not show: the reply is cut the same way.
|
|
1043
1196
|
const declared = !answered && !seen && candidate.supportsReasoning === true;
|
|
1044
1197
|
const reasoned = seen || declared;
|
|
1045
1198
|
throw new AiProviderError(`${label}: ${seen ? "the model used its output limit while reasoning, before writing the reply" : declared ? "the model, which is declared as reasoning, used its output limit before writing the reply (its reasoning counts in the limit)" : "the reply was cut by the output token limit"}. Nothing was applied.`, undefined, false, details({ truncated: true, ...(reasoned ? { reasoningOnly: true, ...(candidate.maxOutputTokens && (built.outputLimit ?? 0) >= candidate.maxOutputTokens ? { limitReached: true } : {}) } : {}) }));
|
|
1046
1199
|
}
|
|
1047
1200
|
if (!answered)
|
|
1048
|
-
throw new AiProviderError(`${label}: ${reasoningCharacters > 0 ? "the model finished after reasoning without a reply" : "the provider returned an empty reply"}.`, undefined, true, details());
|
|
1201
|
+
throw new AiProviderError(`${label}: ${reasoningCharacters > 0 || reasoningTokens > 0 ? "the model finished after reasoning without a reply" : "the provider returned an empty reply"}.`, undefined, true, details());
|
|
1049
1202
|
// Measured before the arguments of a function become the text of the reply: they are counted once.
|
|
1050
1203
|
const measured = measure();
|
|
1051
1204
|
let json;
|