@jsb188/llm-router 1.1.12 → 1.1.13
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/LICENSE +21 -0
- package/README.md +203 -0
- package/package.json +43 -6
- package/src/capabilities.ts +144 -0
- package/src/classifier.ts +126 -0
- package/src/config.ts +38 -0
- package/src/main.ts +25 -1
- package/src/operations/decisions.ts +14 -0
- package/src/operations/embeddings.ts +11 -0
- package/src/operations/files.ts +38 -0
- package/src/operations/moderation.ts +13 -0
- package/src/operations/responses.helpers.ts +424 -0
- package/src/operations/responses.transport.ts +17 -0
- package/src/operations/responses.ts +186 -0
- package/src/operations/transcription.ts +14 -0
- package/src/policy/models.ts +83 -0
- package/src/policy/reasoning.ts +196 -0
- package/src/policy/tasks.ts +32 -0
- package/src/providers/_provider.helpers.ts +37 -0
- package/src/providers/_provider.ts +19 -0
- package/src/providers/anthropic.helpers.ts +346 -0
- package/src/providers/anthropic.reasoning.helpers.ts +75 -0
- package/src/providers/anthropic.stream.ts +299 -0
- package/src/providers/anthropic.ts +63 -0
- package/src/providers/deepseek.ts +98 -0
- package/src/providers/openai.ts +20 -0
- package/src/registry.helpers.ts +117 -0
- package/src/registry.ts +56 -0
- package/src/router.helpers.ts +269 -0
- package/src/router.ts +204 -0
- package/src/trace.ts +17 -0
- package/src/types.ts +291 -0
- package/src/utils/errors.ts +164 -0
- package/src/utils/promptCache.ts +144 -0
- package/src/utils/responseFormat.ts +8 -0
- package/src/utils/responseItems.ts +1 -0
- package/src/zod.ts +1 -0
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { getLLMProviderClient } from '../registry.ts';
|
|
2
|
+
|
|
3
|
+
export const files = {
|
|
4
|
+
/* Upload one prompt file that expires after the given number of seconds. */
|
|
5
|
+
upload(
|
|
6
|
+
buffer: Uint8Array,
|
|
7
|
+
fileName: string,
|
|
8
|
+
contentType: string,
|
|
9
|
+
purpose: 'vision' | 'user_data',
|
|
10
|
+
expiresAfterSeconds: number,
|
|
11
|
+
requestOptions?: { timeout?: number; maxRetries?: number; signal?: AbortSignal },
|
|
12
|
+
) {
|
|
13
|
+
return getLLMProviderClient('openai').files.create(
|
|
14
|
+
{
|
|
15
|
+
// @ts-ignore - new File() typing
|
|
16
|
+
file: new File([buffer], fileName, {
|
|
17
|
+
type: contentType,
|
|
18
|
+
}),
|
|
19
|
+
purpose,
|
|
20
|
+
expires_after: {
|
|
21
|
+
anchor: 'created_at',
|
|
22
|
+
seconds: expiresAfterSeconds,
|
|
23
|
+
},
|
|
24
|
+
},
|
|
25
|
+
requestOptions,
|
|
26
|
+
);
|
|
27
|
+
},
|
|
28
|
+
|
|
29
|
+
/* Validate a cached prompt file with the credentials used to submit model requests. */
|
|
30
|
+
retrieve(fileId: string, requestOptions?: { timeout?: number; maxRetries?: number; signal?: AbortSignal }) {
|
|
31
|
+
return getLLMProviderClient('openai').files.retrieve(fileId, { timeout: 15_000, maxRetries: 1, ...requestOptions });
|
|
32
|
+
},
|
|
33
|
+
|
|
34
|
+
/* Delete one uploaded file. */
|
|
35
|
+
delete(fileId: string) {
|
|
36
|
+
return getLLMProviderClient('openai').files.delete(fileId);
|
|
37
|
+
},
|
|
38
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { getLLMProviderClient, getLLMRouterConfig } from '../registry.ts';
|
|
2
|
+
import type { LLM } from '../types.ts';
|
|
3
|
+
|
|
4
|
+
/* Classify text and/or images with the moderation model (raw provider result). */
|
|
5
|
+
export function createModeration(input: LLM.ModerationCreateParams['input'], requestOptions?: LLM.RequestOptions) {
|
|
6
|
+
return getLLMProviderClient('openai').moderations.create(
|
|
7
|
+
{
|
|
8
|
+
model: getLLMRouterConfig().defaults.moderationModel,
|
|
9
|
+
input,
|
|
10
|
+
},
|
|
11
|
+
requestOptions,
|
|
12
|
+
);
|
|
13
|
+
}
|
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
import type { ParsedResponse } from 'openai/resources/responses/responses';
|
|
2
|
+
import { getLLMRequestPortability } from '../capabilities.ts';
|
|
3
|
+
import { getResolvedModelReasoningPolicy, mapCompatibleReasoningEffort } from '../policy/models.ts';
|
|
4
|
+
import type { LLMProviderAdapter } from '../providers/_provider.ts';
|
|
5
|
+
import { getLLMProviderAdapter, getLLMRetryConfig } from '../registry.ts';
|
|
6
|
+
import { getUsableLLMRouteDecision, resolveLLMTaskRoute } from '../router.ts';
|
|
7
|
+
import { emitLLMTrace } from '../trace.ts';
|
|
8
|
+
import type { LLM, LLMAttempt, LLMProviderName, LLMRequestObserver, LLMRoute, LLMRouteDecision, LLMRouterRequest } from '../types.ts';
|
|
9
|
+
import {
|
|
10
|
+
chatProviderRetryDelay,
|
|
11
|
+
getLLMErrorDetails,
|
|
12
|
+
isLLMConnectionError,
|
|
13
|
+
isLLMTimeoutError,
|
|
14
|
+
LLMRequestError,
|
|
15
|
+
LLMSchemaError,
|
|
16
|
+
} from '../utils/errors.ts';
|
|
17
|
+
import {
|
|
18
|
+
getPromptCacheRejection,
|
|
19
|
+
hasPromptCacheParams,
|
|
20
|
+
type PromptCacheRejection,
|
|
21
|
+
stripPromptCacheComparison,
|
|
22
|
+
stripPromptCacheParams,
|
|
23
|
+
} from '../utils/promptCache.ts';
|
|
24
|
+
import { parseStructuredResponse } from '../utils/responseFormat.ts';
|
|
25
|
+
|
|
26
|
+
// Per-process memory of rejected request features; never reset, no reset API
|
|
27
|
+
const FILE_CONSTANTS = {
|
|
28
|
+
// Remember whether a model rejects modern controls only or also the cache key.
|
|
29
|
+
promptCacheRejectedModels: new Map<string, 'controls' | 'all'>(),
|
|
30
|
+
// (model, param) pairs already traced as unsupported, so the warning is written once per process
|
|
31
|
+
reportedRequestFeatureRejections: new Set<string>(),
|
|
32
|
+
// Provider names in console warnings
|
|
33
|
+
providerLabels: { openai: 'OpenAI', deepseek: 'DeepSeek', anthropic: 'Anthropic' } as Record<LLMProviderName, string>,
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export interface PreparedResponsesParams {
|
|
37
|
+
params: LLM.RequestParams; // Adapted router request; native Messages translation happens at the transport boundary.
|
|
38
|
+
// Removed up front because the model is remembered as not supporting them
|
|
39
|
+
promptCacheStripped: boolean;
|
|
40
|
+
strippedParams: string[]; // What the provider adapter removed
|
|
41
|
+
mappedParams: string[]; // Model effort mappings and provider request rewrites
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/* What one attempt runs with; a retry replaces it, never mutates it. */
|
|
45
|
+
export interface ResponsesAttemptState {
|
|
46
|
+
request: LLMRouterRequest;
|
|
47
|
+
decision: LLMRouteDecision; // Resolved once per call
|
|
48
|
+
route: LLMRoute; // This attempt's route: decision.route, or decision.fallback after a fallback
|
|
49
|
+
params: Partial<LLM.RequestParams>; // Caller params, possibly stripped by a cache-parameter retry
|
|
50
|
+
fallbackAttempt: boolean;
|
|
51
|
+
transportAttempt: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface ResponsesRetryPlan {
|
|
55
|
+
state: ResponsesAttemptState;
|
|
56
|
+
delayMS: number | null; // Set only for a recorded transport retry
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/*
|
|
60
|
+
* The decision one call starts on. A task call resolves now; the request's portability is computed only if a candidate
|
|
61
|
+
* is not OpenAI. A passed decision must be allowed and able to serve the request, else the call fails before sending.
|
|
62
|
+
*/
|
|
63
|
+
export function getResponsesCallDecision(
|
|
64
|
+
request: LLMRouterRequest,
|
|
65
|
+
params: Partial<LLM.RequestParams>,
|
|
66
|
+
method: 'create' | 'parse',
|
|
67
|
+
observer: LLMRequestObserver | null,
|
|
68
|
+
): LLMRouteDecision {
|
|
69
|
+
// Caller plus context params (the durable include counts); getContextParams is synchronous and deterministic for a call.
|
|
70
|
+
// The router calls it only for a non-OpenAI candidate, at most once (it keeps the result)
|
|
71
|
+
const getPortability = () =>
|
|
72
|
+
getLLMRequestPortability({ ...params, ...(observer?.getContextParams?.(request, params) ?? {}) }, method);
|
|
73
|
+
if (!request.decision) return resolveLLMTaskRoute({ ...request, portability: getPortability });
|
|
74
|
+
return getUsableLLMRouteDecision(request.decision, getPortability);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/*
|
|
78
|
+
* Complete caller params with the route: its model, its effort mapped to the model, its verbosity. Context params from
|
|
79
|
+
* the observer sit between the caller's params and reasoning/text/model (the durable-run store/include position).
|
|
80
|
+
*/
|
|
81
|
+
export function makeResponsesParams(
|
|
82
|
+
route: LLMRoute,
|
|
83
|
+
params: Partial<LLM.RequestParams>,
|
|
84
|
+
contextParams: Partial<LLM.RequestParams>,
|
|
85
|
+
): LLM.RequestParams {
|
|
86
|
+
const reasoning = {
|
|
87
|
+
...(params.reasoning || {}),
|
|
88
|
+
effort: mapCompatibleReasoningEffort(route.model, route.effort, route.provider),
|
|
89
|
+
} as unknown as LLM.RequestParams['reasoning'];
|
|
90
|
+
|
|
91
|
+
// Spreads the caller's text, so the format object keeps its reference ($parseRaw is non-enumerable)
|
|
92
|
+
const text = {
|
|
93
|
+
...(params.text || {}),
|
|
94
|
+
verbosity: route.verbosity,
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const result: LLM.RequestParams = {
|
|
98
|
+
...params,
|
|
99
|
+
...contextParams,
|
|
100
|
+
reasoning,
|
|
101
|
+
text,
|
|
102
|
+
model: route.model,
|
|
103
|
+
};
|
|
104
|
+
if (getResolvedModelReasoningPolicy(route.model, route.provider)?.omitReasoning) delete result.reasoning;
|
|
105
|
+
return result;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/*
|
|
109
|
+
* Build the exact provider params of one attempt: remove request features the chosen model is already known to reject
|
|
110
|
+
* in this process (prompt cache params), then map them through the route's provider adapter (OpenAI: the same object).
|
|
111
|
+
* Synchronous; runs on every attempt.
|
|
112
|
+
*/
|
|
113
|
+
export function prepareResponsesParams(state: ResponsesAttemptState, observer: LLMRequestObserver | null): PreparedResponsesParams {
|
|
114
|
+
const { request, params } = state;
|
|
115
|
+
let requestParams = makeResponsesParams(state.route, params, observer?.getContextParams?.(request, params) ?? {});
|
|
116
|
+
const model = state.route.model;
|
|
117
|
+
const promptCacheStripped = FILE_CONSTANTS.promptCacheRejectedModels.has(model) && hasPromptCacheParams(requestParams);
|
|
118
|
+
if (promptCacheStripped) {
|
|
119
|
+
requestParams = stripPromptCacheParams(requestParams, FILE_CONSTANTS.promptCacheRejectedModels.get(model) !== 'all');
|
|
120
|
+
}
|
|
121
|
+
const adapted = getLLMProviderAdapter(state.route.provider).prepareParams(requestParams);
|
|
122
|
+
const effectiveEffort = requestParams.reasoning?.effort ?? 'omitted';
|
|
123
|
+
const effortMappings = effectiveEffort === state.route.effort ? [] : [`reasoning.effort:${state.route.effort}->${effectiveEffort}`];
|
|
124
|
+
return {
|
|
125
|
+
params: adapted.params,
|
|
126
|
+
promptCacheStripped,
|
|
127
|
+
strippedParams: adapted.strippedParams,
|
|
128
|
+
mappedParams: [...effortMappings, ...adapted.mappedParams],
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/* Describe one attempt for observers. */
|
|
133
|
+
export function makeResponsesAttempt(
|
|
134
|
+
method: LLMAttempt['method'],
|
|
135
|
+
state: ResponsesAttemptState,
|
|
136
|
+
prepared: PreparedResponsesParams,
|
|
137
|
+
): LLMAttempt {
|
|
138
|
+
const { request } = state;
|
|
139
|
+
return {
|
|
140
|
+
method,
|
|
141
|
+
params: prepared.params,
|
|
142
|
+
strippedParams: prepared.strippedParams,
|
|
143
|
+
mappedParams: prepared.mappedParams,
|
|
144
|
+
decision: state.decision,
|
|
145
|
+
route: state.route,
|
|
146
|
+
fallbackAttempt: state.fallbackAttempt,
|
|
147
|
+
transportAttempt: state.transportAttempt,
|
|
148
|
+
singleAttempt: !!request.singleAttempt,
|
|
149
|
+
timeoutMS: request.timeoutMS,
|
|
150
|
+
promptCacheStripped: !!request.promptCacheStripped || prepared.promptCacheStripped,
|
|
151
|
+
promptCacheComparisonStripped: !!request.promptCacheComparisonStripped,
|
|
152
|
+
meta: request.meta,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/* SDK retries of one attempt: none when the caller or a durable run owns the retries. */
|
|
157
|
+
export function getResponseSDKRetries(singleAttempt: boolean | undefined, durable: boolean): number {
|
|
158
|
+
return singleAttempt || durable ? 0 : getLLMRetryConfig().sdkRetries ?? 2;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/*
|
|
162
|
+
* Decide whether a failed responses() call may switch to the decision's
|
|
163
|
+
* fallback route, and why. It triggers when the model is unavailable (an
|
|
164
|
+
* explicit model/invalid-prompt request error, or "model_not_found") or when
|
|
165
|
+
* the provider is having a transient outage (5xx). The OpenAI SDK already
|
|
166
|
+
* retries the same model a few times on 5xx before surfacing it here, so
|
|
167
|
+
* switching models is a last resort. A fallback on another provider
|
|
168
|
+
* (crossProvider) also takes that provider's own account, quota, server and
|
|
169
|
+
* connection failures; a timeout never switches, so a caller's time budget is
|
|
170
|
+
* not doubled. Returns null when the error is not one of these.
|
|
171
|
+
*/
|
|
172
|
+
export function getResponsesFallbackReason(err: any, crossProvider: boolean): 'unavailable' | 'outage' | 'provider' | null {
|
|
173
|
+
const details = getLLMErrorDetails(err);
|
|
174
|
+
if (details.status === 404 && details.type === 'not_found_error' && /\bmodel\b/i.test(details.message)) return 'unavailable';
|
|
175
|
+
const isModelUnavailable = err.error?.type === 'invalid_request_error' &&
|
|
176
|
+
(err.error?.param === 'model' || // OpenAI model outage error
|
|
177
|
+
err.error?.code === 'model_not_found' || // Model unavailable or removed
|
|
178
|
+
err.error?.code === 'invalid_prompt'); // OpenAI "violating prompt" error
|
|
179
|
+
if (isModelUnavailable) return 'unavailable';
|
|
180
|
+
|
|
181
|
+
// 503 means the model's serving capacity is overloaded, which a different
|
|
182
|
+
// model can dodge; other 5xx codes are usually provider-wide (a fallback
|
|
183
|
+
// model on the same provider hits the same failure), so they are left to
|
|
184
|
+
// propagate unless the fallback is on another provider.
|
|
185
|
+
if (err.status === 503) return 'outage';
|
|
186
|
+
if (!crossProvider) return null;
|
|
187
|
+
const providerFailure = [401, 402, 429].includes(err.status) || err.status >= 500 ||
|
|
188
|
+
(isLLMConnectionError(err) && !isLLMTimeoutError(err));
|
|
189
|
+
return providerFailure ? 'provider' : null;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/*
|
|
193
|
+
* Trace a prompt cache parameter rejection. An unsupported model is remembered
|
|
194
|
+
* (later requests are pre-stripped) and warned once per (model, param); any
|
|
195
|
+
* other shape is our own bug and is error-logged on every occurrence.
|
|
196
|
+
*/
|
|
197
|
+
function notePromptCacheRejection(
|
|
198
|
+
model: string,
|
|
199
|
+
provider: string,
|
|
200
|
+
rejection: PromptCacheRejection,
|
|
201
|
+
err: any,
|
|
202
|
+
observer: LLMRequestObserver | null,
|
|
203
|
+
) {
|
|
204
|
+
const fields = { model, param: rejection.param, code: rejection.code, httpStatus: err?.status ?? null, stripped: true, provider };
|
|
205
|
+
if (!rejection.unsupportedModel) {
|
|
206
|
+
emitLLMTrace('error', 'ai.cache.params_rejected', { ...fields, memoized: false });
|
|
207
|
+
observer?.onRequestFeatureError?.('OpenAI prompt cache parameters invalid', fields);
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
FILE_CONSTANTS.promptCacheRejectedModels.set(
|
|
211
|
+
model,
|
|
212
|
+
rejection.param.includes('prompt_cache_key') || FILE_CONSTANTS.promptCacheRejectedModels.get(model) === 'all' ? 'all' : 'controls',
|
|
213
|
+
);
|
|
214
|
+
const reportKey = `prompt_cache|${model}|${rejection.param}`;
|
|
215
|
+
if (FILE_CONSTANTS.reportedRequestFeatureRejections.has(reportKey)) return;
|
|
216
|
+
FILE_CONSTANTS.reportedRequestFeatureRejections.add(reportKey);
|
|
217
|
+
emitLLMTrace('warn', 'ai.cache.params_rejected', { ...fields, memoized: true });
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/*
|
|
221
|
+
* Downgrade rejected cache features once per category. A retained key may
|
|
222
|
+
* require a second downgrade after modern controls; removed features cannot
|
|
223
|
+
* trigger another retry.
|
|
224
|
+
*/
|
|
225
|
+
export function getRejectedRequestFeatureRetry(
|
|
226
|
+
err: any,
|
|
227
|
+
request: LLMRouterRequest,
|
|
228
|
+
params: Partial<LLM.RequestParams>,
|
|
229
|
+
attempt: Pick<LLMAttempt, 'params' | 'route'>,
|
|
230
|
+
observer: LLMRequestObserver | null,
|
|
231
|
+
): Pick<ResponsesAttemptState, 'request' | 'params'> | null {
|
|
232
|
+
const requestParams = attempt.params;
|
|
233
|
+
const model = String(requestParams.model);
|
|
234
|
+
const promptCacheRejection = hasPromptCacheParams(requestParams) ? getPromptCacheRejection(err) : null;
|
|
235
|
+
// A provider may reject modern controls first, then the retained legacy key.
|
|
236
|
+
// Permit that second downgrade only while the rejected key is still present.
|
|
237
|
+
if (
|
|
238
|
+
request.promptCacheStripped &&
|
|
239
|
+
!(promptCacheRejection?.param.includes('prompt_cache_key') && requestParams.prompt_cache_key !== undefined)
|
|
240
|
+
) {
|
|
241
|
+
return null;
|
|
242
|
+
}
|
|
243
|
+
if (promptCacheRejection) {
|
|
244
|
+
if (promptCacheRejection.param.includes('comparison_response_id')) {
|
|
245
|
+
return request.promptCacheComparisonStripped
|
|
246
|
+
? null
|
|
247
|
+
: { request: { ...request, promptCacheComparisonStripped: true }, params: stripPromptCacheComparison(params) };
|
|
248
|
+
}
|
|
249
|
+
notePromptCacheRejection(model, attempt.route.provider, promptCacheRejection, err, observer);
|
|
250
|
+
return {
|
|
251
|
+
request: { ...request, promptCacheStripped: true },
|
|
252
|
+
params: stripPromptCacheParams(params, !promptCacheRejection.param.includes('prompt_cache_key')),
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
return null;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/*
|
|
259
|
+
* Trace a switch to the fallback route after an outage, a model or provider error, or a failed structured-output
|
|
260
|
+
* validation (err null: httpStatus, code and param are null). A guaranteed cache miss.
|
|
261
|
+
*/
|
|
262
|
+
function traceResponsesModelFallback(
|
|
263
|
+
err: any,
|
|
264
|
+
attempt: LLMAttempt,
|
|
265
|
+
fallback: LLMRoute,
|
|
266
|
+
reason: 'unavailable' | 'outage' | 'provider' | 'schema',
|
|
267
|
+
) {
|
|
268
|
+
emitLLMTrace('warn', 'ai.model.fallback', {
|
|
269
|
+
fromModel: String(attempt.params.model),
|
|
270
|
+
toModel: fallback.model,
|
|
271
|
+
httpStatus: err?.status ?? null,
|
|
272
|
+
code: err?.error?.code ?? err?.code ?? null,
|
|
273
|
+
param: err?.error?.param ?? err?.param ?? null,
|
|
274
|
+
task: attempt.decision.task,
|
|
275
|
+
provider: attempt.route.provider,
|
|
276
|
+
toProvider: fallback.provider,
|
|
277
|
+
reason,
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/* The state of the one fallback attempt: the decision's fallback route, a fresh transport count. */
|
|
282
|
+
function makeResponsesFallbackState(state: ResponsesAttemptState, fallback: LLMRoute): ResponsesAttemptState {
|
|
283
|
+
return { ...state, route: fallback, fallbackAttempt: true, transportAttempt: 0 };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/* Warn, trace and plan the one retry on the fallback route after a model, outage or provider error. */
|
|
287
|
+
function planResponsesFallback(
|
|
288
|
+
err: any,
|
|
289
|
+
state: ResponsesAttemptState,
|
|
290
|
+
attempt: LLMAttempt,
|
|
291
|
+
fallback: LLMRoute,
|
|
292
|
+
reason: 'unavailable' | 'outage' | 'provider',
|
|
293
|
+
): ResponsesRetryPlan {
|
|
294
|
+
console.warn(
|
|
295
|
+
`(!1) ${FILE_CONSTANTS.providerLabels[attempt.route.provider]} model "${attempt.params.model}" is not available, retrying ${
|
|
296
|
+
attempt.method === 'parse' ? 'responsesJSON' : 'responsesCreate'
|
|
297
|
+
}() with "${fallback.model}"...`,
|
|
298
|
+
);
|
|
299
|
+
traceResponsesModelFallback(err, attempt, fallback, reason);
|
|
300
|
+
return { state: makeResponsesFallbackState(state, fallback), delayMS: null };
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/*
|
|
304
|
+
* Decide what follows a failed attempt, in order: cache-parameter retry, the fallback on another provider (once, also
|
|
305
|
+
* under singleAttempt), single-attempt stop, recorded transport retry, the decision's same-provider fallback route
|
|
306
|
+
* (once). Synchronous; throws LLMRequestError when nothing follows.
|
|
307
|
+
*/
|
|
308
|
+
export function planResponsesRetry(
|
|
309
|
+
err: any,
|
|
310
|
+
state: ResponsesAttemptState,
|
|
311
|
+
attempt: LLMAttempt,
|
|
312
|
+
durable: boolean,
|
|
313
|
+
observer: LLMRequestObserver | null,
|
|
314
|
+
): ResponsesRetryPlan {
|
|
315
|
+
const { request } = state;
|
|
316
|
+
// Evaluated before the singleAttempt check: the rejection is remembered and traced even when no retry follows
|
|
317
|
+
const featureRetry = getRejectedRequestFeatureRetry(err, request, state.params, attempt, observer);
|
|
318
|
+
if (featureRetry && !request.singleAttempt) return { state: { ...state, ...featureRetry }, delayMS: null };
|
|
319
|
+
// Another provider shares none of this provider's failures: at most one attempt more, a timeout excluded
|
|
320
|
+
const crossFallback = state.decision.fallback;
|
|
321
|
+
if (
|
|
322
|
+
(!request.singleAttempt || getLLMRetryConfig().crossProviderFallbackOnSingleAttempt !== false) && !state.fallbackAttempt &&
|
|
323
|
+
crossFallback && crossFallback.provider !== state.decision.route.provider
|
|
324
|
+
) {
|
|
325
|
+
const crossReason = getResponsesFallbackReason(err, true);
|
|
326
|
+
if (crossReason) return planResponsesFallback(err, state, attempt, crossFallback, crossReason);
|
|
327
|
+
}
|
|
328
|
+
if (request.singleAttempt) throw new LLMRequestError(err, attempt.params, attempt.route);
|
|
329
|
+
const retryDelay = durable ? chatProviderRetryDelay(err, state.transportAttempt, getLLMRetryConfig()) : null;
|
|
330
|
+
if (retryDelay !== null) return { state: { ...state, transportAttempt: state.transportAttempt + 1 }, delayMS: retryDelay };
|
|
331
|
+
const reason = state.fallbackAttempt ? null : getResponsesFallbackReason(err, false);
|
|
332
|
+
const fallback = reason ? state.decision.fallback : null;
|
|
333
|
+
if (!fallback) throw new LLMRequestError(err, attempt.params, attempt.route);
|
|
334
|
+
|
|
335
|
+
// Model error / outage; retry once on the fallback route
|
|
336
|
+
return planResponsesFallback(err, state, attempt, fallback, reason!);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/*
|
|
340
|
+
* The state after a structured response of a non-OpenAI route failed validation: the decision's fallback route, once,
|
|
341
|
+
* even under singleAttempt (a provider-correctness guard, not a transient retry; at most one attempt more). Traced as
|
|
342
|
+
* ai.model.fallback with reason 'schema'. Throws LLMRequestError on a fallback attempt or without a fallback.
|
|
343
|
+
*/
|
|
344
|
+
export function planSchemaFallback(err: LLMSchemaError, state: ResponsesAttemptState, attempt: LLMAttempt): ResponsesAttemptState {
|
|
345
|
+
const fallback =
|
|
346
|
+
state.fallbackAttempt || (state.request.singleAttempt && getLLMRetryConfig().crossProviderFallbackOnSingleAttempt === false)
|
|
347
|
+
? null
|
|
348
|
+
: state.decision.fallback;
|
|
349
|
+
if (!fallback) throw new LLMRequestError(err.cause, err.params, state.route);
|
|
350
|
+
traceResponsesModelFallback(null, attempt, fallback, 'schema');
|
|
351
|
+
return makeResponsesFallbackState(state, fallback);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/* Whether a response's output carries a refusal part (the model declined; OpenAI's parse returns parsed null for it). */
|
|
355
|
+
function hasResponseRefusal(response: LLM.Response): boolean {
|
|
356
|
+
return (response.output || []).some((item) => item.type === 'message' && item.content.some((part) => part.type === 'refusal'));
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/*
|
|
360
|
+
* Validate a completed structured response of a non-OpenAI route as responses.parse would. A parse failure (invalid
|
|
361
|
+
* JSON or a schema mismatch) is an LLMSchemaError, and so is a response with no parsed output and no refusal part
|
|
362
|
+
* (no output_text to parse), for which OpenAI's path returns parsed null without a throw.
|
|
363
|
+
*/
|
|
364
|
+
export function parseGuardedStructuredResponse(
|
|
365
|
+
response: LLM.Response,
|
|
366
|
+
params: LLM.RequestParams,
|
|
367
|
+
requestId: string | null,
|
|
368
|
+
): ParsedResponse<unknown> {
|
|
369
|
+
let parsed: ParsedResponse<unknown>;
|
|
370
|
+
try {
|
|
371
|
+
parsed = parseStructuredResponse(response, params);
|
|
372
|
+
} catch (cause) {
|
|
373
|
+
throw new LLMSchemaError(cause, response, params, requestId);
|
|
374
|
+
}
|
|
375
|
+
if (parsed.output_parsed === null && !hasResponseRefusal(response)) {
|
|
376
|
+
throw new LLMSchemaError(new Error('Structured response has no output text to parse'), response, params, requestId);
|
|
377
|
+
}
|
|
378
|
+
return parsed;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/*
|
|
382
|
+
* Iterate a Responses API stream and report usage from its terminal response (usage normalized by the provider
|
|
383
|
+
* adapter) before yielding it. The terminal event is yielded with the normalized response only when the adapter
|
|
384
|
+
* returned a different object.
|
|
385
|
+
*/
|
|
386
|
+
async function* iterateTrackedResponsesStream(
|
|
387
|
+
stream: AsyncIterable<LLM.StreamEvent>,
|
|
388
|
+
observer: LLMRequestObserver | null,
|
|
389
|
+
attempt: LLMAttempt,
|
|
390
|
+
adapter: LLMProviderAdapter,
|
|
391
|
+
) {
|
|
392
|
+
for await (const event of stream) {
|
|
393
|
+
if (event.type === 'response.completed' || event.type === 'response.incomplete' || event.type === 'response.failed') {
|
|
394
|
+
const response = adapter.normalizeUsage(event.response);
|
|
395
|
+
await observer?.onUsage?.(response, attempt);
|
|
396
|
+
yield response === event.response ? event : { ...event, response };
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
yield event;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/*
|
|
405
|
+
* Preserve the provider stream surface while intercepting iteration for usage tracking.
|
|
406
|
+
*/
|
|
407
|
+
export function trackResponsesStream(
|
|
408
|
+
stream: AsyncIterable<LLM.StreamEvent>,
|
|
409
|
+
observer: LLMRequestObserver | null,
|
|
410
|
+
attempt: LLMAttempt,
|
|
411
|
+
adapter: LLMProviderAdapter,
|
|
412
|
+
): AsyncIterable<LLM.StreamEvent> {
|
|
413
|
+
return new Proxy(stream as object, {
|
|
414
|
+
/* Replace the async iterator with the tracked one; every other member comes from the stream itself. */
|
|
415
|
+
get(target, property) {
|
|
416
|
+
if (property === Symbol.asyncIterator) {
|
|
417
|
+
return () => iterateTrackedResponsesStream(stream, observer, attempt, adapter);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
const value = Reflect.get(target, property, target);
|
|
421
|
+
return typeof value === 'function' ? value.bind(target) : value;
|
|
422
|
+
},
|
|
423
|
+
}) as AsyncIterable<LLM.StreamEvent>;
|
|
424
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { createAnthropicRequest } from '../providers/anthropic.ts';
|
|
2
|
+
import { getLLMProviderClient } from '../registry.ts';
|
|
3
|
+
import type { LLM, LLMProviderName } from '../types.ts';
|
|
4
|
+
|
|
5
|
+
/* Select the native transport while keeping retries, recording and schema validation shared. */
|
|
6
|
+
export function createProviderResponseRequest(
|
|
7
|
+
provider: LLMProviderName,
|
|
8
|
+
params: LLM.RequestParams,
|
|
9
|
+
options: Pick<LLM.RequestOptions, 'maxRetries' | 'timeout'>,
|
|
10
|
+
method: 'create' | 'parse',
|
|
11
|
+
) {
|
|
12
|
+
if (provider === 'anthropic') return createAnthropicRequest(getLLMProviderClient(provider), params, options);
|
|
13
|
+
const client = getLLMProviderClient(provider);
|
|
14
|
+
return method === 'parse' && provider === 'openai'
|
|
15
|
+
? client.responses.parse(params, options)
|
|
16
|
+
: client.responses.create(params, options);
|
|
17
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import type { ParsedResponse } from 'openai/resources/responses/responses';
|
|
2
|
+
import { getLLMProviderAdapter, getLLMRequestObserver } from '../registry.ts';
|
|
3
|
+
import { createProviderResponseRequest } from './responses.transport.ts';
|
|
4
|
+
import type { LLM, LLMAttempt, LLMJSONResult, LLMRequestObserver, LLMRouterRequest } from '../types.ts';
|
|
5
|
+
import { LLMIncompleteResponseError, LLMSchemaError } from '../utils/errors.ts';
|
|
6
|
+
import {
|
|
7
|
+
getResponsesCallDecision,
|
|
8
|
+
getResponseSDKRetries,
|
|
9
|
+
makeResponsesAttempt,
|
|
10
|
+
parseGuardedStructuredResponse,
|
|
11
|
+
planResponsesRetry,
|
|
12
|
+
planSchemaFallback,
|
|
13
|
+
prepareResponsesParams,
|
|
14
|
+
type ResponsesAttemptState,
|
|
15
|
+
trackResponsesStream,
|
|
16
|
+
} from './responses.helpers.ts';
|
|
17
|
+
|
|
18
|
+
// Resolved once per call, before the first attempt; each attempt reads its own provider's client and adapter
|
|
19
|
+
interface ResponsesCallContext {
|
|
20
|
+
observer: LLMRequestObserver | null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/* Resolve the observer of one call. */
|
|
24
|
+
function getResponsesCallContext(): ResponsesCallContext {
|
|
25
|
+
return { observer: getLLMRequestObserver() };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/* SDK options of one attempt: no SDK retries when the caller or a durable run owns them; timeout only when set. */
|
|
29
|
+
function getResponsesSDKOptions(request: LLMRouterRequest, durable: boolean) {
|
|
30
|
+
return {
|
|
31
|
+
maxRetries: getResponseSDKRetries(request.singleAttempt, durable),
|
|
32
|
+
...(request.timeoutMS ? { timeout: request.timeoutMS } : {}),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/* Send one Responses attempt (streaming or not); on failure continue with the planned next attempt. */
|
|
37
|
+
async function attemptCreateResponse(
|
|
38
|
+
state: ResponsesAttemptState,
|
|
39
|
+
context: ResponsesCallContext,
|
|
40
|
+
): Promise<AsyncIterable<LLM.StreamEvent> | LLM.Response> {
|
|
41
|
+
const adapter = getLLMProviderAdapter(state.route.provider);
|
|
42
|
+
const prepared = prepareResponsesParams(state, context.observer);
|
|
43
|
+
const requestParams = prepared.params;
|
|
44
|
+
const attempt = makeResponsesAttempt('create', state, prepared);
|
|
45
|
+
const handle = (await context.observer?.onAttemptStart?.(attempt)) ?? null;
|
|
46
|
+
const durable = !!handle?.durable;
|
|
47
|
+
|
|
48
|
+
try {
|
|
49
|
+
const { data: createResult, request_id } = await createProviderResponseRequest(
|
|
50
|
+
state.route.provider,
|
|
51
|
+
requestParams,
|
|
52
|
+
getResponsesSDKOptions(state.request, durable),
|
|
53
|
+
'create',
|
|
54
|
+
)
|
|
55
|
+
.withResponse();
|
|
56
|
+
handle?.setRequestId(request_id);
|
|
57
|
+
if (requestParams.stream && typeof (createResult as any)?.[Symbol.asyncIterator] === 'function') {
|
|
58
|
+
const stream = createResult as AsyncIterable<LLM.StreamEvent>;
|
|
59
|
+
return trackResponsesStream(handle ? handle.wrapStream(stream, request_id) : stream, context.observer, attempt, adapter);
|
|
60
|
+
}
|
|
61
|
+
// OpenAI's identity adapter returns the same object
|
|
62
|
+
const response = adapter.normalizeUsage(createResult as LLM.Response);
|
|
63
|
+
await handle?.onResponse(response, request_id);
|
|
64
|
+
await context.observer?.onUsage?.(response, attempt);
|
|
65
|
+
await handle?.finish(response);
|
|
66
|
+
return response;
|
|
67
|
+
} catch (err: any) {
|
|
68
|
+
await handle?.fail(err, null);
|
|
69
|
+
const plan = planResponsesRetry(err, state, attempt, durable, context.observer);
|
|
70
|
+
if (plan.delayMS !== null) {
|
|
71
|
+
await new Promise((resolve) => setTimeout(resolve, plan.delayMS!));
|
|
72
|
+
await context.observer?.beforeTransportRetry?.(attempt);
|
|
73
|
+
}
|
|
74
|
+
// Returned, not awaited: the next attempt starts in this tick, as the old recursion did
|
|
75
|
+
return attemptCreateResponse(plan.state, context);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/*
|
|
80
|
+
* Send one structured-output attempt; on failure continue with the planned next attempt. OpenAI parses with its strict
|
|
81
|
+
* schema (responses.parse). Another provider is guarded: create, meter, then validate; a failed validation falls back once.
|
|
82
|
+
*/
|
|
83
|
+
async function attemptParseResponse(state: ResponsesAttemptState, context: ResponsesCallContext): Promise<LLMJSONResult> {
|
|
84
|
+
const adapter = getLLMProviderAdapter(state.route.provider);
|
|
85
|
+
const prepared = prepareResponsesParams(state, context.observer);
|
|
86
|
+
const requestParams = prepared.params;
|
|
87
|
+
const attempt: LLMAttempt = makeResponsesAttempt('parse', state, prepared);
|
|
88
|
+
const handle = (await context.observer?.onAttemptStart?.(attempt)) ?? null;
|
|
89
|
+
const durable = !!handle?.durable;
|
|
90
|
+
const guarded = state.route.provider !== 'openai';
|
|
91
|
+
let rawResponse: Response | null = null; // fetch Response, not LLM.Response
|
|
92
|
+
|
|
93
|
+
try {
|
|
94
|
+
const sdkOptions = getResponsesSDKOptions(state.request, durable);
|
|
95
|
+
const providerRequest = createProviderResponseRequest(state.route.provider, requestParams, sdkOptions, 'parse');
|
|
96
|
+
if (handle?.captureRawResponse) {
|
|
97
|
+
const httpResponse = await providerRequest.asResponse();
|
|
98
|
+
try {
|
|
99
|
+
// The SDK types its fetch Response with undici's declarations; at runtime it is the global Response
|
|
100
|
+
rawResponse = httpResponse.clone() as unknown as Response;
|
|
101
|
+
} catch {
|
|
102
|
+
// A diagnostic clone failure must not prevent normal SDK parsing.
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const { data, request_id } = await providerRequest.withResponse();
|
|
106
|
+
// OpenAI's identity adapter returns the same parsed response
|
|
107
|
+
const parseResult = adapter.normalizeUsage(data as LLM.Response);
|
|
108
|
+
handle?.setRequestId(request_id);
|
|
109
|
+
await handle?.onResponse(parseResult, request_id);
|
|
110
|
+
if (rawResponse?.body) void rawResponse.body.cancel().catch(() => {});
|
|
111
|
+
rawResponse = null;
|
|
112
|
+
await context.observer?.onUsage?.(parseResult, attempt);
|
|
113
|
+
await handle?.finish(parseResult);
|
|
114
|
+
// Described inside the try, as before the move: a throw while describing it takes the failure path below
|
|
115
|
+
if (parseResult.status !== 'completed') {
|
|
116
|
+
throw new LLMIncompleteResponseError(
|
|
117
|
+
parseResult,
|
|
118
|
+
requestParams,
|
|
119
|
+
request_id,
|
|
120
|
+
handle?.describeIncomplete(parseResult, request_id) ?? null,
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Metered before it is validated: a billed response is recorded even when it fails the guard
|
|
125
|
+
const parsed = guarded
|
|
126
|
+
? parseGuardedStructuredResponse(parseResult, requestParams, request_id)
|
|
127
|
+
: (parseResult as ParsedResponse<unknown>);
|
|
128
|
+
return {
|
|
129
|
+
id: parsed.id,
|
|
130
|
+
model: parsed.model,
|
|
131
|
+
usage: parsed.usage,
|
|
132
|
+
content: parsed.output,
|
|
133
|
+
parsed: parsed.output_parsed,
|
|
134
|
+
};
|
|
135
|
+
} catch (err: any) {
|
|
136
|
+
// The provider response and usage were already recorded; keep its diagnostics and INCOMPLETE status intact.
|
|
137
|
+
if (err instanceof LLMIncompleteResponseError) throw err;
|
|
138
|
+
// Settled too: fall back once without failing the attempt (planSchemaFallback throws when no fallback is left)
|
|
139
|
+
if (err instanceof LLMSchemaError) return attemptParseResponse(planSchemaFallback(err, state, attempt), context);
|
|
140
|
+
await handle?.fail(err, rawResponse);
|
|
141
|
+
const plan = planResponsesRetry(err, state, attempt, durable, context.observer);
|
|
142
|
+
if (plan.delayMS !== null) {
|
|
143
|
+
await new Promise((resolve) => setTimeout(resolve, plan.delayMS!));
|
|
144
|
+
await context.observer?.beforeTransportRetry?.(attempt);
|
|
145
|
+
}
|
|
146
|
+
// Returned, not awaited: the finally below runs at the same point as in the old recursion
|
|
147
|
+
return attemptParseResponse(plan.state, context);
|
|
148
|
+
} finally {
|
|
149
|
+
if (rawResponse?.body && !rawResponse.body.locked) void rawResponse.body.cancel().catch(() => {});
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/* The first attempt's state of one call: the call's decision, resolved once, and its primary route. */
|
|
154
|
+
function makeInitialResponsesState(
|
|
155
|
+
request: LLMRouterRequest,
|
|
156
|
+
params: Partial<LLM.RequestParams>,
|
|
157
|
+
method: 'create' | 'parse',
|
|
158
|
+
observer: LLMRequestObserver | null,
|
|
159
|
+
): ResponsesAttemptState {
|
|
160
|
+
const decision = getResponsesCallDecision(request, params, method, observer);
|
|
161
|
+
return { request, decision, route: decision.route, params, fallbackAttempt: false, transportAttempt: 0 };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/*
|
|
165
|
+
* Build the exact provider params of one request as createResponse would send them now (a task call resolves as a
|
|
166
|
+
* create call; the method matters only to a non-OpenAI candidate's portability check).
|
|
167
|
+
*/
|
|
168
|
+
export function buildResponseParams(request: LLMRouterRequest, params: Partial<LLM.RequestParams>): LLM.RequestParams {
|
|
169
|
+
const observer = getLLMRequestObserver();
|
|
170
|
+
return prepareResponsesParams(makeInitialResponsesState(request, params, 'create', observer), observer).params;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/* Send a Responses request (streaming or not) with cache-parameter, transport and model-fallback retries. */
|
|
174
|
+
export async function createResponse(
|
|
175
|
+
request: LLMRouterRequest,
|
|
176
|
+
params: Partial<LLM.RequestParams>,
|
|
177
|
+
): Promise<AsyncIterable<LLM.StreamEvent> | LLM.Response> {
|
|
178
|
+
const context = getResponsesCallContext();
|
|
179
|
+
return attemptCreateResponse(makeInitialResponsesState(request, params, 'create', context.observer), context);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/* Send a structured-output Responses request and return its parsed result. */
|
|
183
|
+
export async function createJSONResponse(request: LLMRouterRequest, params: Partial<LLM.RequestParams>): Promise<LLMJSONResult> {
|
|
184
|
+
const context = getResponsesCallContext();
|
|
185
|
+
return attemptParseResponse(makeInitialResponsesState(request, params, 'parse', context.observer), context);
|
|
186
|
+
}
|