@ultimat3/ai 31.25.0 → 31.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/gateway.ts CHANGED
@@ -5,10 +5,8 @@
5
5
  // goes through here, so budgets and accounting cannot be bypassed by a stray fetch.
6
6
 
7
7
  import type { Breaker, Random, RetryPolicy } from '@ultimat3/core';
8
- import { fingerprint, finiteCount, finiteOption, logger, renderThrowable } from '@ultimat3/core';
8
+ import { finiteCount, finiteOption, logger, renderThrowable, systemClock } from '@ultimat3/core';
9
9
  import type { Money } from '@ultimat3/money';
10
- import type { Billed } from './billed';
11
- import { billedOf } from './billed';
12
10
  import type { BudgetKeys, BudgetLimits, BudgetReservation, BudgetStore } from './budget';
13
11
  import {
14
12
  assertFiniteLimits,
@@ -24,12 +22,14 @@ import {
24
22
  providerBreakers,
25
23
  streamVerdict,
26
24
  } from './gateway-providers';
25
+ import { abortedBy, ceilingOf, freeOf, promptCacheKey, settleFailure } from './gateway-settle';
26
+ import { generateOverModels, modelChain, streamOverModels } from './model-fallback';
27
27
  import { resolveModel } from './model-resolve';
28
28
  import type { ModelId } from './models';
29
29
  import type { GenerateRequest, GenerateResult, Provider, StreamChunk } from './provider';
30
+ import { screenProviderOptions } from './provider-options';
30
31
  import type { SamplingWire } from './sampling';
31
32
  import { sentBillOf, streamBillOf } from './stream-bill';
32
- import { ZERO_USAGE } from './wire';
33
33
 
34
34
  /**
35
35
  * Response cache. Structurally satisfied by `@ultimat3/cache`'s memo/LRU tiers; declared as
@@ -54,6 +54,7 @@ export const DEFAULT_GATEWAY_RETRY: RetryPolicy = {
54
54
 
55
55
  export type { GatewayBreakerOption } from './gateway-providers';
56
56
  export { backoffMs, DEFAULT_GATEWAY_BREAKER, isRetryable } from './gateway-providers';
57
+ export { promptCacheKey } from './gateway-settle';
57
58
 
58
59
  export interface ProviderGatewayInput {
59
60
  /** Tried in order for a given model. First provider that lists the model wins. */
@@ -82,6 +83,12 @@ export interface ProviderGatewayInput {
82
83
  * after the cooldown answers. Per process. `(provider) => breaker({ … })` to choose your own, `'off'` declines.
83
84
  */
84
85
  readonly breaker?: GatewayBreakerOption | undefined;
86
+ /**
87
+ * The clock `retry.timeBudgetMs` is read from. Injectable for the reason `sleep` and `random`
88
+ * are: a budget that only real time can spend is a rule no unit test can hold. Production
89
+ * passes none (`systemClock`).
90
+ */
91
+ readonly clock?: { monotonic(): number } | undefined;
85
92
  }
86
93
 
87
94
  export interface Gateway {
@@ -126,6 +133,7 @@ class GatewayImpl implements Gateway {
126
133
  /** Left `undefined` rather than defaulted, so `backoffDelay` owns the one fallback to `Math.random`. */
127
134
  private readonly random: Random | undefined;
128
135
  private readonly gateOf: (provider: Provider) => Breaker | undefined;
136
+ private readonly monotonic: () => number;
129
137
 
130
138
  get defaultModel(): ModelId | undefined {
131
139
  return this.config.defaultModel;
@@ -153,6 +161,8 @@ class GatewayImpl implements Gateway {
153
161
  this.sleep = config.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
154
162
  this.random = config.random;
155
163
  this.gateOf = providerBreakers(config.breaker);
164
+ const clock = config.clock;
165
+ this.monotonic = clock === undefined ? () => systemClock.monotonic() : () => clock.monotonic();
156
166
  }
157
167
 
158
168
  /**
@@ -179,10 +189,39 @@ class GatewayImpl implements Gateway {
179
189
  return (await ledger.report()).cost;
180
190
  }
181
191
 
182
- async generate(request: GenerateRequest): Promise<GenerateResult> {
192
+ /**
193
+ * The request, screened before a reservation or a socket — the ceiling, the wire bag, every model
194
+ * of the chain registered — with the primary model resolved, and the chain to walk.
195
+ */
196
+ private prepared(request: GenerateRequest): {
197
+ readonly resolved: GenerateRequest;
198
+ readonly chain: readonly ModelId[];
199
+ } {
183
200
  const model = resolveModel('gateway', request.model, this.config.defaultModel);
184
- const resolved: GenerateRequest = { ...request, model, maxTokens: ceilingOf(request) };
201
+ const maxTokens = ceilingOf(request);
202
+ screenProviderOptions(request.providerOptions);
203
+ return {
204
+ resolved: { ...request, model, maxTokens },
205
+ chain: modelChain(model, request.fallbackModels),
206
+ };
207
+ }
208
+
209
+ async generate(request: GenerateRequest): Promise<GenerateResult> {
210
+ const { resolved, chain } = this.prepared(request);
211
+ // One clock for the chain: `retry.timeBudgetMs` bounds the call, every model included.
212
+ const startedAt = this.monotonic();
213
+ return generateOverModels(chain, (model, index) =>
214
+ this.generateModel({ ...resolved, model }, startedAt, index > 0),
215
+ );
216
+ }
185
217
 
218
+ /** One model of the chain: cache, reservation, the provider loop, the record. */
219
+ private async generateModel(
220
+ resolved: GenerateRequest,
221
+ startedAt: number,
222
+ continuing: boolean,
223
+ ): Promise<GenerateResult> {
224
+ const model = resolveModel('gateway', resolved.model);
186
225
  const cacheKey = promptCacheKey(resolved);
187
226
  const cached = await this.config.cache?.get(cacheKey);
188
227
  if (cached !== undefined) {
@@ -212,6 +251,9 @@ class GatewayImpl implements Gateway {
212
251
  random: this.random,
213
252
  gateOf: this.gateOf,
214
253
  call: (provider) => provider.generate(resolved),
254
+ startedAt,
255
+ monotonic: this.monotonic,
256
+ continuing,
215
257
  });
216
258
  } catch (error) {
217
259
  // A call that never landed must not go on holding its reservation — and one that DID land
@@ -252,8 +294,17 @@ class GatewayImpl implements Gateway {
252
294
  }
253
295
 
254
296
  async *stream(request: GenerateRequest): AsyncIterable<StreamChunk> {
255
- const model = resolveModel('gateway', request.model, this.config.defaultModel);
256
- const resolved: GenerateRequest = { ...request, model, maxTokens: ceilingOf(request) };
297
+ const { resolved, chain } = this.prepared(request);
298
+ // A chain falls over only before the first chunk (`streamOverModels`); after it, never — nor
299
+ // once `retry.timeBudgetMs` is spent: one clock for the call, as `generate` keeps it.
300
+ const startedAt = this.monotonic();
301
+ const budget = this.retry.timeBudgetMs;
302
+ const spent = (): boolean => budget !== undefined && this.monotonic() - startedAt > budget;
303
+ yield* streamOverModels(chain, (model) => this.streamModel({ ...resolved, model }), spent);
304
+ }
305
+
306
+ private async *streamModel(resolved: GenerateRequest): AsyncIterable<StreamChunk> {
307
+ const model = resolveModel('gateway', resolved.model);
257
308
 
258
309
  // Routed BEFORE the reservation, not after it. `providerFor` throws for a registered model no
259
310
  // configured provider serves — an ordinary boot misconfiguration — and a debit taken first has
@@ -268,7 +319,9 @@ class GatewayImpl implements Gateway {
268
319
  // open and no chunk has been delivered for a retry to hide behind. So `providerFor` picks the
269
320
  // single provider serving this model and that call stands or throws; `attempt`'s backoff and
270
321
  // its fallback across providers belong to `generate` alone. A caller that wants either uses
271
- // `generate`, or reconnects itself and knows what it has already shown.
322
+ // `generate`, or reconnects itself and knows what it has already shown. A declared
323
+ // `fallbackModels` chain is the one exception, and only before the first chunk is delivered
324
+ // (`streamOverModels`): a throw from the first pull handed the consumer nothing to duplicate.
272
325
  const { provider, ticket } = admittedProvider(model, this.config.providers, this.gateOf);
273
326
  const gate = this.gateOf(provider);
274
327
  let answered = false;
@@ -352,70 +405,3 @@ class GatewayImpl implements Gateway {
352
405
  );
353
406
  }
354
407
  }
355
-
356
- /**
357
- * A failed call's reservation: reconciled against its bill when the failure carries one — else
358
- * against `running`, what a stream's wire reported before it stopped — else given back.
359
- */
360
- async function settleFailure(
361
- ledger: BudgetLedger | undefined,
362
- reservation: BudgetReservation | undefined,
363
- error: unknown,
364
- running?: Billed,
365
- ): Promise<void> {
366
- const billed = billedOf(error) ?? running;
367
- if (billed === undefined) return ledger?.release(reservation);
368
- await ledger?.record(billed.usage, billed.cost, reservation);
369
- }
370
-
371
- /** The caller's abort — its signal, or the `AbortError` a fetch raises for it. */
372
- function abortedBy(request: GenerateRequest, error: unknown): boolean {
373
- if (request.signal?.aborted === true) return true;
374
- return error instanceof Error && error.name === 'AbortError';
375
- }
376
-
377
- /** The stored answer as a hit delivers it: no token spent, no money, in the currency it named. */
378
- const freeOf = (stored: GenerateResult): GenerateResult => ({
379
- ...stored,
380
- usage: ZERO_USAGE,
381
- cost: { ...stored.cost, minor: 0 },
382
- ...(stored.costExact === undefined ? {} : { costExact: { ...stored.costExact, minor: 0 } }),
383
- });
384
-
385
- /**
386
- * The request's completion ceiling, screened at the one seam every model call in an app passes
387
- * through — `llm()`, `agent()`, an eval, a judge and a hand-built `generate()` alike.
388
- *
389
- * It is not the request that a `NaN` here breaks, and that is why it is refused before anything
390
- * else happens: `maxTokens` IS the pre-flight estimate, `want > remaining` is false for a `NaN`
391
- * want, and `BudgetLedger.debit` then writes it onto the ambient ledger and the per-process
392
- * `BudgetStore`. Both counters are `NaN` from then on, so every later comparison against them is
393
- * false too — one unscreened declaration turns off every actor and org ceiling in the process,
394
- * permanently, and reports nothing. Screened before the reservation, so the ledger never sees it.
395
- */
396
- function ceilingOf(request: GenerateRequest): number {
397
- return finiteCount('the AI gateway', 'maxTokens', request.maxTokens, 1);
398
- }
399
-
400
- /**
401
- * Cache key. Every field that changes the answer is in it — a key that ignores `effort` or
402
- * `system` would serve one prompt's answer for another — and each tool WHOLE: every `llm()` tool
403
- * is named `respond`, so a key over names alone served an answer shaped for an old `output` schema
404
- * after the schema changed. Core's `fingerprint`, so key order never splits one request in two and
405
- * the width is the one every other sharing key in the framework has.
406
- */
407
- export function promptCacheKey(request: GenerateRequest): string {
408
- return fingerprint({
409
- model: request.model,
410
- system: request.system ?? '',
411
- messages: request.messages,
412
- maxTokens: request.maxTokens,
413
- effort: request.effort ?? 'high',
414
- thinking: request.thinking ?? 'adaptive',
415
- tools: request.tools ?? [],
416
- stop: request.stopSequences ?? [],
417
- // Only when asked for: an absent knob must leave every key written before it existed as it was.
418
- ...(request.temperature === undefined ? {} : { temperature: request.temperature }),
419
- ...(request.seed === undefined ? {} : { seed: request.seed }),
420
- });
421
- }
package/src/index.ts CHANGED
@@ -142,6 +142,8 @@ export type { LlmAction, LlmBudget, LlmCall, LlmDef, LlmVarsArgs } from './llm';
142
142
  export { LlmTextChunk, llm } from './llm';
143
143
  export type { LlmCache, LlmScopeArgs, LlmSemanticCache } from './llm-cache';
144
144
  export type { LlmStreamChunk } from './llm-stream';
145
+ export type { ModelFallback, ModelFallbackClass } from './model-fallback';
146
+ export { MODEL_FALLBACK_ON } from './model-fallback';
145
147
  export type { ModelSource } from './model-resolve';
146
148
  export type {
147
149
  ContentKind,
@@ -215,6 +217,12 @@ export {
215
217
  parseMessage,
216
218
  STREAM_ONLY_MAX_TOKENS,
217
219
  } from './provider';
220
+ export type {
221
+ AnthropicProviderOptions,
222
+ OpenAiProviderOptions,
223
+ ProviderOptions,
224
+ } from './provider-options';
225
+ export { PROVIDER_OPTION_KEYS } from './provider-options';
218
226
  export type {
219
227
  AssembledContext,
220
228
  Chunk,
package/src/llm-answer.ts CHANGED
@@ -6,7 +6,7 @@ import type { Span, SpanAttributes } from '@ultimat3/core';
6
6
  import { SEMCONV } from '@ultimat3/core';
7
7
  import type { InferOutput, StandardSchemaV1 } from '@ultimat3/schema';
8
8
  import { formatIssues, validateAsync } from '@ultimat3/schema';
9
- import { runTotal } from './agent-usage';
9
+ import { pricedOn, runTotal } from './agent-usage';
10
10
  import { LlmTruncatedError } from './answer-errors';
11
11
  import { LlmRefusedError, LlmStreamInvalidError } from './errors';
12
12
  import type { Gateway } from './gateway';
@@ -60,7 +60,7 @@ export async function streamedAnswer<
60
60
  meter: RunMeter,
61
61
  ): Promise<InferOutput<TOutput>> {
62
62
  const { output } = def;
63
- const result = await meter.call(streamOneTurn(gateway, request, sink));
63
+ const result = await meter.call(() => streamOneTurn(gateway, request, sink));
64
64
  span.setAttributes({ 'ultimate.llm.attempts': 1, ...answerAttributes(result) });
65
65
  await observeCall(def, meter, result, 1, undefined);
66
66
  if (result.stopReason === 'refusal') {
@@ -110,7 +110,7 @@ export async function observeCall<
110
110
  cost: result.cost,
111
111
  ...(result.costExact === undefined ? {} : { costExact: result.costExact }),
112
112
  ...(repairOf === undefined ? {} : { repairOf }),
113
- run: runTotal(result.model, undefined, meter.total()),
113
+ run: runTotal(pricedOn(result), undefined, meter.total(), meter.below()),
114
114
  });
115
115
  }
116
116
 
package/src/llm-def.ts CHANGED
@@ -11,6 +11,7 @@ import type { ModelId } from './models';
11
11
  import type { Prompt, PromptVars } from './prompt';
12
12
  import type { PromptCacheOption } from './prompt-cache';
13
13
  import type { StopReason, TokenUsage } from './provider';
14
+ import type { ProviderOptions } from './provider-options';
14
15
 
15
16
  /** Per-call ceilings, checked before the provider is reached. Never truncates — refuses. */
16
17
  export interface LlmBudget {
@@ -35,6 +36,14 @@ export interface LlmDef<
35
36
  * travels with it; this one is the deployment decision, so it wins.
36
37
  */
37
38
  readonly model?: ModelId;
39
+ /**
40
+ * Tried in order when the model fails with a declared class (`MODEL_FALLBACK_ON`: rate limited,
41
+ * overloaded, timed out, unavailable) — never on a 400, a refusal or a budget. Each attempt is
42
+ * reserved and billed; a streamed call falls over only before its first chunk.
43
+ */
44
+ readonly fallbackModels?: readonly ModelId[];
45
+ /** Wire parameters the framework does not model, one bag per wire, screened at declaration. */
46
+ readonly providerOptions?: ProviderOptions;
38
47
  readonly input: TInput;
39
48
  readonly output: TOutput;
40
49
  readonly prompt: Prompt<V>;
@@ -25,7 +25,7 @@ export function llmReport(span: Span, model: string, meter: RunMeter): LlmReport
25
25
  let answeredBy = model;
26
26
  const watched: RunMeter = {
27
27
  ...meter,
28
- call: async (work: Promise<GenerateResult>): Promise<GenerateResult> => {
28
+ call: async (work: () => Promise<GenerateResult>): Promise<GenerateResult> => {
29
29
  const result = await meter.call(work);
30
30
  provider = result.provider ?? NO_PROVIDER;
31
31
  answeredBy = result.model;
@@ -35,10 +35,12 @@ export function llmReport(span: Span, model: string, meter: RunMeter): LlmReport
35
35
  return {
36
36
  meter: watched,
37
37
  settle({ cacheHit, error }) {
38
- // The RUN's usage — every attempt, repair turns included — not the last answer's.
38
+ // The RUN's usage — every attempt, repair turns and fallback answers included — not the last
39
+ // answer's. `below` is a fallback model's answers: an `llm()` runs nothing underneath it.
39
40
  const usage = meter.total()?.usage;
40
- const inputTokens = usage?.inputTokens ?? 0;
41
- const outputTokens = usage?.outputTokens ?? 0;
41
+ const apart = meter.below()?.usage;
42
+ const inputTokens = (usage?.inputTokens ?? 0) + (apart?.inputTokens ?? 0);
43
+ const outputTokens = (usage?.outputTokens ?? 0) + (apart?.outputTokens ?? 0);
42
44
  span.setAttributes({
43
45
  [SEMCONV.genAiProviderName]: provider,
44
46
  [SEMCONV.genAiResponseModel]: answeredBy,
package/src/llm.ts CHANGED
@@ -37,12 +37,14 @@ import type { LlmBudget, LlmDef } from './llm-def';
37
37
  import { llmReport } from './llm-instrument';
38
38
  import type { LlmStreamChunk } from './llm-stream';
39
39
  import { currentLlmSink, llmStream, withLlmSink } from './llm-stream';
40
+ import { declaredFallbacks } from './model-fallback';
40
41
  import { modelForCall } from './model-resolve';
41
42
  import { moreCapableThan } from './models';
42
43
  import type { PromptVars } from './prompt';
43
44
  import { promptCacheHint } from './prompt-cache';
44
45
  import type { AiMessage, GenerateRequest, GenerateResult } from './provider';
45
46
  import { isTruncated } from './provider';
47
+ import { screenProviderOptions } from './provider-options';
46
48
  import { assertNoSecrets } from './redaction';
47
49
  import type { Respond } from './respond';
48
50
  import { RESPOND, respondFor } from './respond';
@@ -113,6 +115,8 @@ export function llm<
113
115
  // a call that cannot answer.
114
116
  finiteCount('llm', 'maxTokens', def.maxTokens ?? DEFAULT_MAX_TOKENS, 1);
115
117
  const sampling = screenSampling('llm', def);
118
+ // Screened here too, so a bag the wire would refuse fails the boot, not the first request.
119
+ screenProviderOptions(def.providerOptions);
116
120
  const built = action<TInput, TOutput, typeof LlmTextChunk>({
117
121
  input: def.input,
118
122
  output: def.output,
@@ -255,6 +259,8 @@ async function generate<
255
259
  ...(prompt.effort === undefined ? {} : { effort: prompt.effort }),
256
260
  ...(prompt.thinking === undefined ? {} : { thinking: prompt.thinking }),
257
261
  ...sampling,
262
+ ...declaredFallbacks(model, def.fallbackModels),
263
+ ...(def.providerOptions === undefined ? {} : { providerOptions: def.providerOptions }),
258
264
  // The caller's own signal, forwarded to the transport exactly as `agent()` does — and
259
265
  // inherited by `streamedAnswer` from this same `base`. Without it a disconnected caller left
260
266
  // the provider call in flight, billed and unread, and the repair turn bought a SECOND one.
@@ -285,7 +291,7 @@ async function generate<
285
291
  let issues = 'no output';
286
292
  let rejected: readonly string[] | undefined;
287
293
  for (let attempt = 1; attempt <= ATTEMPTS; attempt += 1) {
288
- const result = await meter.call(gateway.generate({ ...request, messages }));
294
+ const result = await meter.call(() => gateway.generate({ ...request, messages }));
289
295
  span.setAttributes({ 'ultimate.llm.attempts': attempt, ...answerAttributes(result) });
290
296
  await observeCall(def, meter, result, attempt, rejected);
291
297
  // Branch on the stop reason BEFORE reading the answer. A refusal carries empty or partial
@@ -0,0 +1,255 @@
1
+ // Single responsibility: `fallbackModels` — which failures a model chain falls over on (the declared
2
+ // class), the chain's screen, and the loop that walks it for one `generate` or one stream: an attempt
3
+ // span per model under the caller's one span, and every failed attempt stamped onto the answer.
4
+
5
+ import type { Span } from '@ultimat3/core';
6
+ import {
7
+ asyncContext,
8
+ isUltimateError,
9
+ renderThrowable,
10
+ SEMCONV,
11
+ startSpan,
12
+ stringField,
13
+ withSpan,
14
+ } from '@ultimat3/core';
15
+ import type { Billed } from './billed';
16
+ import { billedOf } from './billed';
17
+ import { AiProviderUnavailableError, AiRequestInvalidError } from './errors';
18
+ import type { ModelId } from './models';
19
+ import { modelSpec } from './models';
20
+ import type { GenerateResult, StreamChunk } from './provider';
21
+
22
+ /**
23
+ * The DECLARED classes a chain falls over on — every one a fact about the model's hosts at this
24
+ * moment, never about the request: the same request has a real chance on the next model.
25
+ *
26
+ * | Class | Read from |
27
+ * |---|---|
28
+ * | `rate_limited` | 429 |
29
+ * | `overloaded` | 529 |
30
+ * | `timeout` | 408, 504, `ETIMEDOUT` |
31
+ * | `unavailable` | any other 5xx, a refused/dropped/unopenable socket, every breaker open |
32
+ *
33
+ * Never: a 4xx (the request), a refusal or truncation (an answer), a budget, an abort, a model no
34
+ * provider lists (`app.config.ts`) — each would fail, or be wrong, the same way on every model.
35
+ */
36
+ export const MODEL_FALLBACK_ON = ['rate_limited', 'overloaded', 'timeout', 'unavailable'] as const;
37
+
38
+ export type ModelFallbackClass = (typeof MODEL_FALLBACK_ON)[number];
39
+
40
+ /** One model of a chain that failed before the next was asked. */
41
+ export interface ModelFallback {
42
+ readonly model: ModelId;
43
+ readonly reason: ModelFallbackClass;
44
+ /** The failure, rendered (`renderThrowable`): bounded, and never a provider's whole body. */
45
+ readonly cause: string;
46
+ /** What it was billed, when its failure carried a bill; absent means unsettled, never free. */
47
+ readonly billed?: Billed;
48
+ }
49
+
50
+ const PROVIDER_UNAVAILABLE = 'X_AI_PROVIDER_UNAVAILABLE';
51
+ const UNAVAILABLE_CODES: ReadonlySet<string> = new Set([
52
+ 'ECONNRESET',
53
+ 'ConnectionRefused',
54
+ 'ConnectionClosed',
55
+ 'FailedToOpenSocket',
56
+ ]);
57
+
58
+ /**
59
+ * The class of ONE transport failure, read off `status` / `code` — total: the value came from an
60
+ * app's `Provider`, and a property read on it can trap. 409 and 425 are retryable on the same
61
+ * host but say nothing about the model, so they are no class.
62
+ */
63
+ export function transportFallbackClass(error: unknown): ModelFallbackClass | undefined {
64
+ if (typeof error !== 'object' || error === null) return undefined;
65
+ try {
66
+ const { status, code } = error as { status?: unknown; code?: unknown };
67
+ if (typeof status === 'number') {
68
+ if (status === 429) return 'rate_limited';
69
+ if (status === 529) return 'overloaded';
70
+ if (status === 408 || status === 504) return 'timeout';
71
+ return status >= 500 ? 'unavailable' : undefined;
72
+ }
73
+ if (code === 'ETIMEDOUT') return 'timeout';
74
+ return typeof code === 'string' && UNAVAILABLE_CODES.has(code) ? 'unavailable' : undefined;
75
+ } catch {
76
+ return undefined;
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Whether a model's failure falls over, and as what. The gateway's own exhausted error carries the
82
+ * verdict its retry loop reached (`fallback`); any other coded refusal never falls over; a raw
83
+ * provider throw (a stream's first pull) is classed by its transport fields.
84
+ */
85
+ export function fallbackClassOf(error: unknown): ModelFallbackClass | undefined {
86
+ if (error instanceof AiProviderUnavailableError) return error.fallback;
87
+ if (isUltimateError(error) && stringField(error, 'code') !== PROVIDER_UNAVAILABLE) {
88
+ return undefined;
89
+ }
90
+ return transportFallbackClass(error);
91
+ }
92
+
93
+ /**
94
+ * The chain, screened before a reservation or a socket: every id registered (`X_AI_MODEL_UNKNOWN`)
95
+ * and none twice — a repeated model is a second bill for the answer that just failed.
96
+ */
97
+ export function modelChain(
98
+ model: ModelId,
99
+ fallbackModels: readonly ModelId[] | undefined,
100
+ ): readonly ModelId[] {
101
+ const chain = [model, ...(fallbackModels ?? [])];
102
+ for (const [index, id] of chain.entries()) {
103
+ modelSpec(id);
104
+ if (chain.indexOf(id) !== index) {
105
+ throw new AiRequestInvalidError({
106
+ detail: `fallbackModels names "${id}" twice in the chain ${chain.join(' → ')}; a repeat asks a model that just failed`,
107
+ fix: `fallbackModels: [${chain
108
+ .filter((one, at) => chain.indexOf(one) === at && one !== model)
109
+ .map((one) => `'${one}'`)
110
+ .join(', ')}] # each model once, the primary not among them`,
111
+ });
112
+ }
113
+ }
114
+ return chain;
115
+ }
116
+
117
+ /**
118
+ * What a DECLARATION's chain adds to a request on `model`: the chain without `model` itself — a
119
+ * run's own pick (`agent()`'s `model()`, `llm()`'s resolution) may be one of its fallbacks, and is
120
+ * then simply not asked twice. Nothing when no fallback is left.
121
+ */
122
+ export function declaredFallbacks(
123
+ model: ModelId,
124
+ fallbackModels: readonly ModelId[] | undefined,
125
+ ): { readonly fallbackModels?: readonly ModelId[] } {
126
+ const rest = (fallbackModels ?? []).filter((one) => one !== model);
127
+ return rest.length === 0 ? {} : { fallbackModels: rest };
128
+ }
129
+
130
+ const fellOverAs = (model: ModelId, reason: ModelFallbackClass, error: unknown): ModelFallback => {
131
+ const billed = billedOf(error);
132
+ return {
133
+ model,
134
+ reason,
135
+ cause: renderThrowable(error),
136
+ ...(billed === undefined ? {} : { billed }),
137
+ };
138
+ };
139
+
140
+ /** Every model failed on a declared class: one coded error naming each, for the meter to count. */
141
+ const exhausted = (chain: readonly ModelId[], fellOver: readonly ModelFallback[]): unknown =>
142
+ new AiProviderUnavailableError({
143
+ model: chain.join(' → '),
144
+ attempts: fellOver.map((one) => `${one.model}: ${one.reason}`),
145
+ fellOver,
146
+ });
147
+
148
+ const attemptAttributes = (model: ModelId, index: number) => ({
149
+ [SEMCONV.genAiRequestModel]: model,
150
+ 'ultimate.llm.fallback.index': index,
151
+ });
152
+
153
+ /**
154
+ * Where a chain reports each model it falls over FROM, the moment it moves on: the run meter of the
155
+ * call in flight (`RunMeter.call` opens one around the call). Ambient per CALL, never keyed on a
156
+ * thrown value — one object can reject two calls at once (`signal.reason`), and an attempt read off
157
+ * it was credited to whichever meter caught it first. The model that ends the walk is the call's
158
+ * own throw or answer, which the meter counts already.
159
+ */
160
+ const attemptSinks = asyncContext<(attempt: ModelFallback) => void>(
161
+ 'a model-fallback attempt sink',
162
+ );
163
+
164
+ /** Run `work` with `sink` hearing every model a chain inside it falls over from. */
165
+ export function withAttemptSink<T>(sink: (attempt: ModelFallback) => void, work: () => T): T {
166
+ return attemptSinks.run(sink, work);
167
+ }
168
+
169
+ /** The model failed declared: kept for the answer, reported unless it was the chain's last. */
170
+ function fallOver(
171
+ fellOver: ModelFallback[],
172
+ attempt: ModelFallback,
173
+ last: boolean,
174
+ chain: readonly ModelId[],
175
+ ): void {
176
+ fellOver.push(attempt);
177
+ if (last) throw exhausted(chain, fellOver);
178
+ attemptSinks.get()?.(attempt);
179
+ }
180
+
181
+ /**
182
+ * One `generate` over the chain. A single-model chain is the call itself — no span, nothing stamped.
183
+ * Otherwise each model runs in its own `ai.model.attempt` span; a failure outside the declared
184
+ * class, or the last model's, ends the walk.
185
+ */
186
+ export async function generateOverModels(
187
+ chain: readonly ModelId[],
188
+ run: (model: ModelId, index: number) => Promise<GenerateResult>,
189
+ ): Promise<GenerateResult> {
190
+ const [only] = chain;
191
+ if (chain.length === 1 && only !== undefined) return run(only, 0);
192
+ const fellOver: ModelFallback[] = [];
193
+ for (const [index, model] of chain.entries()) {
194
+ try {
195
+ const result = await withSpan('ai.model.attempt', (span) => {
196
+ span.setAttributes(attemptAttributes(model, index));
197
+ return run(model, index).catch((error: unknown) => {
198
+ markReason(span, error);
199
+ throw error;
200
+ });
201
+ });
202
+ return fellOver.length === 0 ? result : { ...result, fallbacks: fellOver };
203
+ } catch (error) {
204
+ const reason = fallbackClassOf(error);
205
+ if (reason === undefined) throw error;
206
+ fallOver(fellOver, fellOverAs(model, reason, error), index === chain.length - 1, chain);
207
+ }
208
+ }
209
+ throw exhausted(chain, fellOver);
210
+ }
211
+
212
+ const markReason = (span: Span, error: unknown): void => {
213
+ const reason = fallbackClassOf(error);
214
+ if (reason !== undefined) span.setAttribute('ultimate.llm.fallback.reason', reason);
215
+ };
216
+
217
+ /**
218
+ * One stream over the chain. Falls over ONLY before the first chunk reaches the consumer: from then
219
+ * on a replay would duplicate what it already read, so a later failure is thrown as it stands. Nor
220
+ * once `spent()` says the call's time budget is gone — the same rule `generate`'s retry loop keeps.
221
+ */
222
+ export async function* streamOverModels(
223
+ chain: readonly ModelId[],
224
+ run: (model: ModelId) => AsyncIterable<StreamChunk>,
225
+ spent: () => boolean = () => false,
226
+ ): AsyncIterable<StreamChunk> {
227
+ const [only] = chain;
228
+ if (chain.length === 1 && only !== undefined) {
229
+ yield* run(only);
230
+ return;
231
+ }
232
+ const fellOver: ModelFallback[] = [];
233
+ for (const [index, model] of chain.entries()) {
234
+ const span = startSpan('ai.model.attempt', { attributes: attemptAttributes(model, index) });
235
+ let delivered = false;
236
+ try {
237
+ for await (const chunk of run(model)) {
238
+ delivered = true;
239
+ yield chunk.type === 'done' && fellOver.length > 0
240
+ ? { type: 'done', result: { ...chunk.result, fallbacks: [...fellOver] } }
241
+ : chunk;
242
+ }
243
+ return;
244
+ } catch (error) {
245
+ span.recordError(error);
246
+ const last = index === chain.length - 1;
247
+ const reason = delivered || (!last && spent()) ? undefined : fallbackClassOf(error);
248
+ if (reason === undefined) throw error;
249
+ span.setAttribute('ultimate.llm.fallback.reason', reason);
250
+ fallOver(fellOver, fellOverAs(model, reason, error), last, chain);
251
+ } finally {
252
+ span.end();
253
+ }
254
+ }
255
+ }
package/src/models.ts CHANGED
@@ -262,6 +262,16 @@ export function resetModels(): void {
262
262
  registry.clear();
263
263
  }
264
264
 
265
+ /**
266
+ * Test-only: exactly `specs` again, in their order — what `registeredModels()` answered earlier.
267
+ * A REPLACE, never a reset: an app's `models.ts` registers once per process. Rows were screened
268
+ * when first registered. `@ultimat3/testing`'s file boundary is the caller.
269
+ */
270
+ export function restoreModels(specs: readonly ModelSpec[]): void {
271
+ registry.clear();
272
+ for (const spec of specs) registry.set(spec.id, spec);
273
+ }
274
+
265
275
  const rankOf = (effort: Effort): number => EFFORTS.indexOf(effort);
266
276
 
267
277
  /**
@@ -12,6 +12,7 @@ import { toOpenAiMessages, toOpenAiTools, toolChoiceFor } from './openai-message
12
12
  import type { PromptCacheRule, ProviderCacheRow } from './prompt-cache';
13
13
  import { OPENAI_CACHE_KEY_MAX, promptCacheRule, SESSION_KEY_MAX } from './prompt-cache';
14
14
  import type { GenerateRequest } from './provider';
15
+ import { providerOptionsBody } from './provider-options';
15
16
  import { samplingBody } from './sampling';
16
17
 
17
18
  type CacheRule = Pick<PromptCacheRule, 'marks' | 'session'>;
@@ -31,8 +32,9 @@ export interface ChatCompletionBodyInput {
31
32
 
32
33
  /**
33
34
  * The body. What is deliberately absent is as load-bearing as what is present:
34
- * - no `top_p` / `presence_penalty`, and `temperature` / `seed` only for a model whose row takes
35
- * them (`ModelSpec.sampling`): a sampling knob on a reasoning model in this family is a 400.
35
+ * - no `top_p` / `presence_penalty` of the framework's choosing, and `temperature` / `seed` only
36
+ * for a model whose row takes them (`ModelSpec.sampling`): a sampling knob on a reasoning model
37
+ * in this family is a 400. `providerOptions.openai` sends them when the APP asks, screened.
36
38
  * - no `response_format`. The output schema is projected into the `respond` tool by `llm()`, and
37
39
  * that projection is the framework's ONE structured-output path — see the README.
38
40
  * - `max_completion_tokens`, never the deprecated `max_tokens`, which current reasoning models
@@ -51,6 +53,8 @@ export function chatCompletionBody(input: ChatCompletionBodyInput): Record<strin
51
53
  max_completion_tokens: Math.min(request.maxTokens, spec.maxOutput),
52
54
  ...reasoningFields(model, request.effort, request.thinking),
53
55
  ...samplingBody('openai', model, request),
56
+ // The app's explicit wire parameters, screened; no key collides with a field set above.
57
+ ...providerOptionsBody('openai', request.providerOptions),
54
58
  };
55
59
  if (request.tools !== undefined && request.tools.length > 0) {
56
60
  body['tools'] = toOpenAiTools(request.tools);