@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/src/types.ts ADDED
@@ -0,0 +1,291 @@
1
+ import type OpenAI from 'openai';
2
+ import type Anthropic from '@anthropic-ai/sdk';
3
+ import type { ParsedResponse } from 'openai/resources/responses/responses';
4
+ import type { LLMModelEntry, LLMModelId } from './policy/models.ts';
5
+ import type { LLMResponseTask, LLMTaskCall, LLMTaskPolicyMap } from './policy/tasks.ts';
6
+
7
+ /*
8
+ * Router-owned names for every SDK type the server uses. Type-only: always import it with `import type { LLM }`.
9
+ * Inside this namespace a bare `Response` means LLM.Response, never the fetch Response.
10
+ */
11
+ export declare namespace LLM {
12
+ // Shared
13
+ export type FunctionDefinition = OpenAI.FunctionDefinition;
14
+ export type RequestOptions = OpenAI.RequestOptions; // SDK per-call options (timeout, maxRetries, signal); not LLMCallOptions
15
+
16
+ // Responses: request
17
+ export type RequestParams = OpenAI.Responses.ResponseCreateParams;
18
+ export type RequestParamsNonStreaming = OpenAI.Responses.ResponseCreateParamsNonStreaming;
19
+ export type Input = OpenAI.Responses.ResponseInput;
20
+ export type InputItem = OpenAI.Responses.ResponseInputItem;
21
+ export namespace InputItem {
22
+ export type FunctionCallOutput = OpenAI.Responses.ResponseInputItem.FunctionCallOutput;
23
+ }
24
+ export type InputContent = OpenAI.Responses.ResponseInputContent;
25
+ export type InputContentList = OpenAI.Responses.ResponseInputMessageContentList;
26
+ export type InputImage = OpenAI.Responses.ResponseInputImage;
27
+ export type EasyInputMessage = OpenAI.Responses.EasyInputMessage;
28
+
29
+ // Responses: tools
30
+ export type Tool = OpenAI.Responses.Tool;
31
+ export type FunctionTool = OpenAI.Responses.FunctionTool;
32
+ export type ToolSearchTool = OpenAI.Responses.ToolSearchTool;
33
+ export type NamespaceTool = OpenAI.Responses.NamespaceTool;
34
+ export namespace NamespaceTool {
35
+ export type Function = OpenAI.Responses.NamespaceTool.Function;
36
+ }
37
+
38
+ // Responses: result
39
+ export type Response = OpenAI.Responses.Response;
40
+ export type Usage = OpenAI.Responses.ResponseUsage;
41
+ export type OutputItem = OpenAI.Responses.ResponseOutputItem;
42
+ export type OutputMessage = OpenAI.Responses.ResponseOutputMessage;
43
+ export type OutputText = OpenAI.Responses.ResponseOutputText;
44
+ export type ReasoningItem = OpenAI.Responses.ResponseReasoningItem;
45
+ export type FunctionCall = OpenAI.Responses.ResponseFunctionToolCall;
46
+ export type ToolSearchOutputItem = OpenAI.Responses.ResponseToolSearchOutputItem;
47
+
48
+ // Responses: stream
49
+ export type StreamEvent = OpenAI.Responses.ResponseStreamEvent;
50
+ export type ReasoningSummaryTextDeltaEvent = OpenAI.Responses.ResponseReasoningSummaryTextDeltaEvent;
51
+ export type ReasoningSummaryTextDoneEvent = OpenAI.Responses.ResponseReasoningSummaryTextDoneEvent;
52
+ export type ReasoningSummaryPartAddedEvent = OpenAI.Responses.ResponseReasoningSummaryPartAddedEvent;
53
+ export type ReasoningSummaryPartDoneEvent = OpenAI.Responses.ResponseReasoningSummaryPartDoneEvent;
54
+
55
+ // Decisions
56
+ export type Decision = OpenAI.Decisions.Decision;
57
+ export type DecisionParams = OpenAI.Decisions.DecisionCreateParams;
58
+ export type DecisionInputParams = Omit<OpenAI.Decisions.DecisionCreateParams, 'model'>; // The router adds the model
59
+ export type DecisionInputPart = OpenAI.Decisions.DecisionInputPart;
60
+
61
+ // Moderation
62
+ export type ModerationCreateParams = OpenAI.ModerationCreateParams;
63
+ export type ModerationCreateResponse = OpenAI.ModerationCreateResponse;
64
+ export type ModerationMultiModalInput = OpenAI.ModerationMultiModalInput;
65
+ }
66
+
67
+ export type LLMProviderName = 'openai' | 'deepseek' | 'anthropic';
68
+ export interface LLMProviderClients {
69
+ openai: OpenAI;
70
+ deepseek: OpenAI;
71
+ anthropic: Anthropic;
72
+ }
73
+ // Preserve the existing raw Responses client alias for callers of OpenAI-compatible providers.
74
+ export type LLMProviderClient = OpenAI;
75
+
76
+ export interface LLMProviderConfig {
77
+ apiKey?: string;
78
+ }
79
+
80
+ // Overrides supported by standalone provider clients.
81
+ export interface LLMProviderClientOptions {
82
+ apiKey?: string;
83
+ maxRetries?: number;
84
+ timeout?: number;
85
+ }
86
+
87
+ export interface LLMRoutingConfig {
88
+ policies: LLMTaskPolicyMap;
89
+ models: Readonly<Record<string, LLMModelEntry>>;
90
+ tiers: Readonly<Record<string, string>>;
91
+ fallbackModel: (model: string) => string | null;
92
+ defaultProviders?: readonly LLMProviderName[];
93
+ pinning?: { holdMS?: number; maxClockSkewMS?: number; upgradeImmediately?: boolean; reuseRecovered?: boolean };
94
+ }
95
+
96
+ export interface LLMOperationDefaults {
97
+ decisionsModel: string;
98
+ embedding: { model: string; dimensions: number };
99
+ moderationModel: string;
100
+ transcriptionModel: string;
101
+ }
102
+
103
+ export interface LLMRetryConfig {
104
+ sdkRetries?: number;
105
+ transportRetries?: number;
106
+ initialDelayMS?: number;
107
+ maxDelayMS?: number;
108
+ crossProviderFallbackOnSingleAttempt?: boolean;
109
+ }
110
+
111
+ export interface LLMRouterConfig {
112
+ providers: Partial<Record<LLMProviderName, LLMProviderConfig>>;
113
+ routing: LLMRoutingConfig;
114
+ defaults: LLMOperationDefaults;
115
+ retries?: LLMRetryConfig;
116
+ observer?: LLMRequestObserver;
117
+ traceLogger?: LLMTraceLogger;
118
+ }
119
+
120
+ export type LLMTier = string;
121
+ export type LLMEffort = 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
122
+ export type LLMVerbosity = 'low' | 'medium' | 'high';
123
+
124
+ // What chose a route: the task rule, an organization trial, a held pin, a recovered run's stored
125
+ // route or pin, or the caller (tests, evals, probes)
126
+ export type LLMRouteSource = 'policy' | 'trial' | 'pin' | 'recovered' | 'caller';
127
+
128
+ /* One model choice with every field explicit; effort is the requested value, mapped per model when params are built. */
129
+ export interface LLMRoute {
130
+ provider: LLMProviderName;
131
+ model: string;
132
+ effort: LLMEffort;
133
+ verbosity: LLMVerbosity;
134
+ }
135
+
136
+ // A policy route names either an application tier or a model.
137
+ export type LLMRouteSpec = ({ tier: LLMTier; model?: undefined } | { model: LLMModelId; tier?: undefined }) & {
138
+ effort: LLMEffort;
139
+ verbosity: LLMVerbosity;
140
+ };
141
+
142
+ /* What the router decided for one task; agent runs keep it for every step. */
143
+ export interface LLMRouteDecision {
144
+ task: LLMResponseTask;
145
+ route: LLMRoute;
146
+ fallback: LLMRoute | null; // The one-shot fallback (outage, unavailable model, schema or provider failure); null means none
147
+ source: LLMRouteSource;
148
+ // 'fixed', 'primary', 'escalated', 'default', 'category:<C>', 'role:<ROLE>', 'tier:<tier>[,effort:<e>][,verbosity:<v>]',
149
+ // 'trial', 'capability' (the rule's fallback route, taken because no earlier candidate could serve the request), 'caller'
150
+ rule: string;
151
+ }
152
+
153
+ /* A route pin persisted by the application alongside its execution state. */
154
+ export interface LLMPin {
155
+ v: 1;
156
+ organizationId: string; // The organization of the run that wrote it; another organization's pin is none unless this run wrote it
157
+ runId: string | null; // The run that wrote it; equals this run's id only on a recovered attempt (null outside a durable run)
158
+ route: LLMRoute;
159
+ source: LLMRouteSource; // What chose the route at chosenAt
160
+ rule: string; // The rule that chose the route at chosenAt
161
+ chosenAt: string; // ISO time the route was chosen; never-downgrade holds for one cache lifetime from here
162
+ lastRequestAt: string; // ISO time of the last compiled request on this pin; the cache is warm for one lifetime from here
163
+ epoch: number; // The context epoch of that request; telemetry only (an epoch change keeps most of the prefix cached)
164
+ }
165
+
166
+ /* A run's route as its checkpoint stores it for recovery. */
167
+ export interface LLMStoredRoute {
168
+ route: LLMRoute;
169
+ rule: string;
170
+ }
171
+
172
+ // How a run's route relates to the chat's pin: no usable pin, a warm pin, a cold pin, or this run's own pin (recovered attempt)
173
+ export type LLMPinState = 'NONE' | 'WARM' | 'COLD' | 'RECOVERED';
174
+ export type LLMRouteSwitchReason = 'cold' | 'upgrade' | 'hold_expired' | 'capability' | 'recovered';
175
+
176
+ /* One route change of a pinned or recovered run; warm is null when the cache state does not apply (recovery). */
177
+ export interface LLMRouteSwitch {
178
+ task: LLMResponseTask;
179
+ from: LLMRoute;
180
+ to: LLMRoute;
181
+ reason: LLMRouteSwitchReason;
182
+ warm: boolean | null;
183
+ }
184
+
185
+ /*
186
+ * What the pin rules chose for a run: its decision, the pin's state, the switch to trace, and the pin the run keeps
187
+ * (null: the run writes a new pin).
188
+ */
189
+ export interface LLMPinnedRouteChoice {
190
+ decision: LLMRouteDecision;
191
+ pinState: LLMPinState;
192
+ switched: LLMRouteSwitch | null;
193
+ held: LLMPin | null;
194
+ }
195
+
196
+ // A call whose route was already resolved (controllers, CSV records, tests and evals)
197
+ export interface LLMDecidedCall {
198
+ decision: LLMRouteDecision;
199
+ task?: undefined;
200
+ signals?: undefined;
201
+ }
202
+ export type LLMCallTarget = LLMTaskCall | LLMDecidedCall;
203
+
204
+ // Retry ownership and cache-strip state of one call
205
+ export interface LLMCallOptions {
206
+ timeoutMS?: number; // Per-request SDK timeout; SDK default when unset
207
+ singleAttempt?: boolean; // Let a durable caller reserve and own every retry/fallback
208
+ // Set on the one retry after a 400 named a prompt cache parameter; recorded on the step
209
+ promptCacheStripped?: boolean;
210
+ promptCacheComparisonStripped?: boolean;
211
+ }
212
+
213
+ // First argument of createResponse / createJSONResponse / buildResponseParams
214
+ export type LLMRouterRequest =
215
+ & LLMCallTarget
216
+ & LLMCallOptions
217
+ & {
218
+ organizationId?: string | null; // The organization a task's trial is looked up by; null or unset means none
219
+ meta?: unknown; // Opaque to the package; handed to observers unchanged
220
+ };
221
+
222
+ export interface LLMJSONResult {
223
+ id: string;
224
+ model: LLM.Response['model'];
225
+ usage: LLM.Response['usage'];
226
+ content: ParsedResponse<unknown>['output'];
227
+ parsed: unknown;
228
+ }
229
+
230
+ export interface LLMDecisionResult {
231
+ data: LLM.Decision;
232
+ requestId: string | null; // The raw x-request-id; never coerced
233
+ }
234
+
235
+ export type LLMTraceLevel = 'info' | 'warn' | 'error';
236
+ export type LLMTraceLogger = (
237
+ level: LLMTraceLevel,
238
+ name: string,
239
+ fields: Record<string, unknown>,
240
+ options?: { detail?: boolean },
241
+ ) => void;
242
+
243
+ /* One provider attempt of a Responses request, as observers see it. */
244
+ export interface LLMAttempt {
245
+ method: 'create' | 'parse';
246
+ params: LLM.RequestParams; // Adapted router params; native providers translate these at the transport boundary. Observers must not mutate it.
247
+ strippedParams: string[]; // Params the provider adapter removed, in its order; [] for OpenAI
248
+ mappedParams: string[]; // Model effort mappings and provider rewrites, such as 'reasoning.effort:medium->high'
249
+ decision: LLMRouteDecision; // Resolved once per call
250
+ route: LLMRoute; // This attempt's route: decision.route, or decision.fallback after a fallback
251
+ fallbackAttempt: boolean; // This attempt runs on the one-shot fallback route
252
+ transportAttempt: number; // Recorded transport retries already made on this model
253
+ singleAttempt: boolean;
254
+ timeoutMS: number | undefined;
255
+ promptCacheStripped: boolean; // Stripped by an earlier rejection in this call, or up front by the per-process memo
256
+ promptCacheComparisonStripped: boolean;
257
+ meta: unknown;
258
+ }
259
+
260
+ /* What an observer returns for one started attempt. */
261
+ export interface LLMAttemptHandle {
262
+ // True for a durable run: the router sends maxRetries 0 and makes recorded transport retries itself
263
+ durable: boolean;
264
+ // True when the raw HTTP response of a structured call must be kept for failure diagnostics
265
+ captureRawResponse: boolean;
266
+ /* Synchronous; called right after the provider answered. */
267
+ setRequestId(requestId: string | null): void;
268
+ /* Wrap a provider stream; the router wraps the result once more for usage tracking. */
269
+ wrapStream(stream: AsyncIterable<LLM.StreamEvent>, requestId: string | null): AsyncIterable<LLM.StreamEvent>;
270
+ /* Awaited with a non-streaming result, before usage. */
271
+ onResponse(response: LLM.Response, requestId: string | null): Promise<void>;
272
+ /* Awaited after usage; closes the attempt. */
273
+ finish(response: LLM.Response): Promise<void>;
274
+ /* Synchronous; describes a structured response that settled without completing. Runs inside the provider try (a throw is a failed attempt); the result travels as LLMIncompleteResponseError.details. */
275
+ describeIncomplete(response: LLM.Response, requestId: string | null): unknown;
276
+ /* Awaited first in the failure path; rawResponse is the kept fetch Response of a structured call, or null. */
277
+ fail(error: unknown, rawResponse: Response | null): Promise<void>;
278
+ }
279
+
280
+ export interface LLMRequestObserver {
281
+ /* Synchronous and deterministic for a call; runs on every attempt, inside buildResponseParams and in a call's portability check (non-OpenAI candidates only). The result is spread after the caller's params and before reasoning, text and model. */
282
+ getContextParams?(request: LLMRouterRequest, params: Partial<LLM.RequestParams>): Partial<LLM.RequestParams>;
283
+ /* Awaited once per attempt, after params are final and before the provider call. A throw ends the call with that error. */
284
+ onAttemptStart?(attempt: LLMAttempt): Promise<LLMAttemptHandle>;
285
+ /* Awaited after the delay of a recorded transport retry, before the next attempt is prepared. A throw ends the call with that error. */
286
+ beforeTransportRetry?(failedAttempt: LLMAttempt): Promise<unknown>;
287
+ /* Awaited with every settled response (a non-streaming result, or a stream's terminal event before it is yielded) and the attempt that produced it. */
288
+ onUsage?(response: LLM.Response, attempt: LLMAttempt): Promise<void>;
289
+ /* Synchronous. A rejected request feature that the model does support (our own request bug); called after its trace event. */
290
+ onRequestFeatureError?(message: string, data: Record<string, unknown>): void;
291
+ }
@@ -0,0 +1,164 @@
1
+ import { APIConnectionError, APIConnectionTimeoutError, APIError, APIUserAbortError } from 'openai';
2
+ import {
3
+ APIConnectionError as AnthropicConnectionError,
4
+ APIConnectionTimeoutError as AnthropicTimeoutError,
5
+ APIUserAbortError as AnthropicAbortError,
6
+ } from '@anthropic-ai/sdk';
7
+ import type { LLMResponseTask } from '../policy/tasks.ts';
8
+ import type { LLM, LLMRetryConfig, LLMRoute } from '../types.ts';
9
+
10
+ /* Extract bounded provider diagnostics from SDK or wrapped errors without logging headers or request bodies. */
11
+ export function getLLMErrorDetails(error: any) {
12
+ const provider = error?.error?.error || error?.error || error;
13
+ return {
14
+ status: error?.status ?? error?.data?.status ?? null,
15
+ requestId: error?.requestID || error?.request_id || error?.data?.requestId || error?.headers?.get?.('x-request-id') ||
16
+ error?.headers?.get?.('request-id') || null,
17
+ type: provider?.type ?? null,
18
+ code: provider?.code ?? error?.code ?? error?.data?.code ?? null,
19
+ param: provider?.param ?? null,
20
+ message: String(provider?.message || error?.message || error || '').slice(0, 2000),
21
+ };
22
+ }
23
+
24
+ export type LLMErrorReason = 'BROKEN_FUNCTION_CALL' | 'IMAGE_OR_FILE_NOT_FOUND' | 'INVALID_IMAGE_TYPE' | 'INVALID_FILE_TYPE';
25
+
26
+ export type PossibleStaleReason = LLMErrorReason | boolean | null;
27
+
28
+ /* Get reason for request error from OpenAI response error object */
29
+ export function getLLMErrorReason(err: any): LLMErrorReason | null {
30
+ const providerError = err?.error || err;
31
+ const errType = providerError?.type;
32
+ const errParam = providerError?.param;
33
+ const errMessage = providerError?.message || '';
34
+ const unavailableFile = /\bfiles?\b[\s\S]*\b(?:not found|does not exist|expired|deleted|not accessible)\b|\bno such file\b/i.test(
35
+ errMessage,
36
+ );
37
+ if ((errType === 'invalid_request_error' || err?.status === 404) && unavailableFile) {
38
+ return 'IMAGE_OR_FILE_NOT_FOUND';
39
+ }
40
+
41
+ if (errType === 'invalid_request_error') {
42
+ if (errParam === 'input' && /\b(?:fc|rs)_[a-z0-9]+\b/i.test(errMessage)) {
43
+ return 'BROKEN_FUNCTION_CALL';
44
+ } else if (/\bExpected image type to be\b/i.test(errMessage)) {
45
+ return 'INVALID_IMAGE_TYPE';
46
+ } else if (
47
+ /\bExpected file type to be\b/i.test(errMessage) ||
48
+ /\bExpected context stuffing file type to be\b/i.test(errMessage) ||
49
+ /\bInvalid file type\b/i.test(errMessage) ||
50
+ /\bUnsupported file type\b/i.test(errMessage)
51
+ ) {
52
+ return 'INVALID_FILE_TYPE';
53
+ }
54
+ }
55
+
56
+ return null;
57
+ }
58
+
59
+ /*
60
+ * Bound explicit retries for failures before a response stream is handed to
61
+ * its consumer. Each attempt can then have its own request ID and trace step.
62
+ * Transient means a retryable HTTP status, or an SDK connection failure or
63
+ * timeout (matched by class: the SDK's errors keep the name 'Error').
64
+ */
65
+ export function chatProviderRetryDelay(error: any, attempt: number, retry: LLMRetryConfig = {}): number | null {
66
+ if (attempt >= (retry.transportRetries ?? 2)) return null;
67
+ const transient = [408, 409, 429].includes(error.status) || error.status >= 500 || isLLMConnectionError(error);
68
+ if (!transient) return null;
69
+ const retryAfter = Number(error.headers?.get?.('retry-after'));
70
+ return Number.isFinite(retryAfter) && retryAfter > 0
71
+ ? Math.min(retryAfter * 1000, retry.maxDelayMS ?? 30_000)
72
+ : Math.min((retry.initialDelayMS ?? 500) * 2 ** attempt, retry.maxDelayMS ?? 30_000);
73
+ }
74
+
75
+ /* Whether an error is the SDK's connection failure (timeouts included). */
76
+ export function isLLMConnectionError(error: unknown): boolean {
77
+ return error instanceof APIConnectionError || error instanceof AnthropicConnectionError;
78
+ }
79
+
80
+ /* Whether an error is the SDK's request timeout (a connection error subclass). */
81
+ export function isLLMTimeoutError(error: unknown): boolean {
82
+ return error instanceof APIConnectionTimeoutError || error instanceof AnthropicTimeoutError;
83
+ }
84
+
85
+ /* Whether an error is the SDK's caller-abort error. */
86
+ export function isLLMAbortError(error: unknown): boolean {
87
+ return error instanceof APIUserAbortError || error instanceof AnthropicAbortError;
88
+ }
89
+
90
+ /* Test helper: build the SDK error a provider HTTP response would produce. */
91
+ export function makeLLMProviderError(status: number | undefined, body?: object, message?: string, headers?: Headers) {
92
+ return APIError.generate(status, body, message, headers);
93
+ }
94
+
95
+ /* Test helper: build an SDK transport error (connection failure, timeout or caller abort). */
96
+ export function makeLLMTransportError(kind: 'connection' | 'timeout' | 'abort', message?: string) {
97
+ if (kind === 'timeout') return new APIConnectionTimeoutError({ message });
98
+ if (kind === 'abort') return new APIUserAbortError({ message });
99
+ return new APIConnectionError({ message });
100
+ }
101
+
102
+ /* Final failure of a Responses call after every retry and fallback the request allows. */
103
+ export class LLMRequestError extends Error {
104
+ params: LLM.RequestParams; // Exact provider params of the attempt that failed
105
+ route: LLMRoute; // The route of the attempt that failed (names its provider)
106
+
107
+ /* Keep the provider error as the cause, with the params and route of the attempt that failed. */
108
+ constructor(cause: unknown, params: LLM.RequestParams, route: LLMRoute) {
109
+ super('LLM request failed', { cause });
110
+ this.name = 'LLMRequestError';
111
+ this.params = params;
112
+ this.route = route;
113
+ }
114
+ }
115
+
116
+ /* No route of a task may carry this request; thrown before anything is sent. */
117
+ export class LLMRouteError extends Error {
118
+ task: LLMResponseTask;
119
+ offending: string[]; // The request's non-portable labels (empty when the portability was not computed)
120
+ excluded: Array<{ model: string; reason: string }>; // Every candidate route and why it was not usable
121
+
122
+ /* Keep the task, the request's offending labels and every excluded candidate. */
123
+ constructor(task: LLMResponseTask, offending: string[], excluded: Array<{ model: string; reason: string }>) {
124
+ super(`No usable LLM route for ${task}`);
125
+ this.name = 'LLMRouteError';
126
+ this.task = task;
127
+ this.offending = offending;
128
+ this.excluded = excluded;
129
+ }
130
+ }
131
+
132
+ /* A structured response of a non-OpenAI route that failed validation; the response and its usage were already recorded. */
133
+ export class LLMSchemaError extends Error {
134
+ response: LLM.Response;
135
+ params: LLM.RequestParams;
136
+ requestId: string | null;
137
+
138
+ /* Keep the parse failure as the cause, with the settled response, the params that produced it and the provider request id. */
139
+ constructor(cause: unknown, response: LLM.Response, params: LLM.RequestParams, requestId: string | null) {
140
+ super('LLM structured response failed validation', { cause });
141
+ this.name = 'LLMSchemaError';
142
+ this.response = response;
143
+ this.params = params;
144
+ this.requestId = requestId;
145
+ }
146
+ }
147
+
148
+ /* A structured response that settled without completing; the response and its usage were already recorded. */
149
+ export class LLMIncompleteResponseError extends Error {
150
+ response: LLM.Response;
151
+ params: LLM.RequestParams;
152
+ requestId: string | null;
153
+ details: unknown; // What the attempt handle's describeIncomplete returned; null without a handle
154
+
155
+ /* Keep the settled response, the params that produced it, the provider request id and the handle's description. */
156
+ constructor(response: LLM.Response, params: LLM.RequestParams, requestId: string | null, details: unknown) {
157
+ super('LLM structured response not completed');
158
+ this.name = 'LLMIncompleteResponseError';
159
+ this.response = response;
160
+ this.params = params;
161
+ this.requestId = requestId;
162
+ this.details = details;
163
+ }
164
+ }
@@ -0,0 +1,144 @@
1
+ export interface PromptCacheRejection {
2
+ param: string;
3
+ code: string;
4
+ // The model does not support the parameter at all (remember and pre-strip); anything else is a bug in our request
5
+ unsupportedModel: boolean;
6
+ }
7
+
8
+ export interface ResponsesCacheUsageSummary {
9
+ inputTokens: number;
10
+ cachedTokens: number;
11
+ cacheWriteTokens: number;
12
+ outputTokens: number;
13
+ }
14
+
15
+ const FILE_CONSTANTS = {
16
+ promptCacheParamPattern: /(^|\.)prompt_cache_(key|options|breakpoint)/,
17
+ unsupportedPromptCacheParams: ['prompt_cache_key', 'prompt_cache_options', 'prompt_cache_breakpoint'],
18
+ promptCacheParamKeys: ['prompt_cache_key', 'prompt_cache_options'],
19
+ unsupportedFeatureCodes: ['invalid_parameter', 'unsupported_parameter'],
20
+ };
21
+
22
+ /*
23
+ * Read the provider's rejected parameter name from an SDK error (or its body).
24
+ */
25
+ function getProviderErrorParam(err: any): string {
26
+ return String(err?.error?.param ?? err?.param ?? '');
27
+ }
28
+
29
+ /*
30
+ * Classify a 400 that names a prompt cache parameter. Bare
31
+ * prompt_cache_key / prompt_cache_options / prompt_cache_breakpoint with an unsupported-feature code means
32
+ * the model does not support caching parameters; any other shape (for example
33
+ * invalid_value on prompt_cache_options.ttl or a breakpoint mode) is our bug.
34
+ */
35
+ export function getPromptCacheRejection(err: any): PromptCacheRejection | null {
36
+ if (err?.status !== 400) return null;
37
+ const param = getProviderErrorParam(err);
38
+ if (!FILE_CONSTANTS.promptCacheParamPattern.test(param)) return null;
39
+ const code = String(err?.error?.code ?? err?.code ?? '');
40
+ return {
41
+ param,
42
+ code,
43
+ unsupportedModel: FILE_CONSTANTS.unsupportedFeatureCodes.includes(code) &&
44
+ FILE_CONSTANTS.unsupportedPromptCacheParams.includes(param),
45
+ };
46
+ }
47
+
48
+ /*
49
+ * Return content parts without prompt_cache_breakpoint, or null when none had one.
50
+ */
51
+ function stripContentBreakpoints(content: unknown): unknown[] | null {
52
+ if (!Array.isArray(content) || !content.some((part) => part && typeof part === 'object' && 'prompt_cache_breakpoint' in part)) {
53
+ return null;
54
+ }
55
+ return content.map((part) => {
56
+ if (!part || typeof part !== 'object' || !('prompt_cache_breakpoint' in part)) return part;
57
+ const { prompt_cache_breakpoint: _breakpoint, ...rest } = part as Record<string, unknown>;
58
+ return rest;
59
+ });
60
+ }
61
+
62
+ /*
63
+ * Return an input without any content-part breakpoints. The same array is
64
+ * returned when nothing was marked, so unmarked requests keep their identity.
65
+ */
66
+ function stripInputBreakpoints(input: unknown): unknown {
67
+ if (!Array.isArray(input)) return input;
68
+ let changed = false;
69
+ const stripped = input.map((item) => {
70
+ const content = stripContentBreakpoints((item as { content?: unknown })?.content);
71
+ if (!content) return item;
72
+ changed = true;
73
+ return { ...item, content };
74
+ });
75
+ return changed ? stripped : input;
76
+ }
77
+
78
+ /*
79
+ * Return the prompt cache parameters present in request params, in the order key, options, content-part breakpoint.
80
+ */
81
+ export function getPromptCacheParamNames(params: unknown): string[] {
82
+ const request = params as Record<string, unknown> | null;
83
+ if (!request || typeof request !== 'object') return [];
84
+ const names = FILE_CONSTANTS.promptCacheParamKeys.filter((key) => request[key] !== undefined);
85
+ const hasBreakpoint = Array.isArray(request.input) &&
86
+ request.input.some(
87
+ (item) =>
88
+ Array.isArray(item?.content) &&
89
+ item.content.some((part: unknown) => part !== null && typeof part === 'object' && 'prompt_cache_breakpoint' in part),
90
+ );
91
+ return hasBreakpoint ? [...names, 'prompt_cache_breakpoint'] : names;
92
+ }
93
+
94
+ /*
95
+ * Return whether request params carry any prompt cache parameter or breakpoint.
96
+ */
97
+ export function hasPromptCacheParams(params: unknown): boolean {
98
+ return getPromptCacheParamNames(params).length > 0;
99
+ }
100
+
101
+ /*
102
+ * Drop prompt_cache_key, prompt_cache_options and every content-part
103
+ * breakpoint, optionally preserving a supported key. Never mutates; returns
104
+ * the same object when nothing was present.
105
+ */
106
+ export function stripPromptCacheParams<T>(params: T, preserveKey = false): T {
107
+ if (!hasPromptCacheParams(params)) return params;
108
+ const { prompt_cache_key: _key, prompt_cache_options: _options, ...rest } = params as Record<string, unknown>;
109
+ return {
110
+ ...rest,
111
+ ...(preserveKey && _key !== undefined ? { prompt_cache_key: _key } : {}),
112
+ ...('input' in rest ? { input: stripInputBreakpoints(rest.input) } : {}),
113
+ } as T;
114
+ }
115
+
116
+ /*
117
+ * Normalize a request input for the recorder's "is this the compiled input"
118
+ * comparison: breakpoints are stripped so a cache-parameter retry still
119
+ * matches the context that compiled it.
120
+ */
121
+ export function normalizeRecordedInput(input: unknown): unknown {
122
+ return stripInputBreakpoints(input);
123
+ }
124
+
125
+ /*
126
+ * Summarize input, cached, cache-write and output tokens of one provider usage object.
127
+ */
128
+ export function summarizeResponsesCacheUsage(usage: any): ResponsesCacheUsageSummary | null {
129
+ if (!usage || typeof usage !== 'object') return null;
130
+ return {
131
+ inputTokens: Number(usage.input_tokens) || 0,
132
+ cachedTokens: Number(usage.input_tokens_details?.cached_tokens) || 0,
133
+ cacheWriteTokens: Number(usage.input_tokens_details?.cache_write_tokens) || 0,
134
+ outputTokens: Number(usage.output_tokens) || 0,
135
+ };
136
+ }
137
+
138
+ /* Drop optional comparison diagnostics without discarding supported key, TTL or markers. */
139
+ export function stripPromptCacheComparison<T>(params: T): T {
140
+ const value = params as any;
141
+ if (!value.prompt_cache_options?.comparison_response_id) return params;
142
+ const { comparison_response_id: _comparison, ...options } = value.prompt_cache_options;
143
+ return { ...value, prompt_cache_options: options };
144
+ }
@@ -0,0 +1,8 @@
1
+ import { parseResponse } from 'openai/lib/ResponsesParser';
2
+ import type { ParsedResponse } from 'openai/resources/responses/responses';
3
+ import type { LLM } from '../types.ts';
4
+
5
+ /* Parse a response's structured output exactly as the SDK's responses.parse does (create, then parseResponse); throws on invalid JSON or a schema mismatch. */
6
+ export function parseStructuredResponse(response: LLM.Response, params: LLM.RequestParams): ParsedResponse<unknown> {
7
+ return parseResponse(response, params);
8
+ }
@@ -0,0 +1 @@
1
+ export { toResponseInputItems } from 'openai/lib/responses/ResponseInputItems';
package/src/zod.ts ADDED
@@ -0,0 +1 @@
1
+ export { zodTextFormat } from 'openai/helpers/zod';