@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.
@@ -0,0 +1,269 @@
1
+ import { getLLMRouterConfig } from './registry.ts';
2
+ import { getLLMModelEntry } from './policy/models.ts';
3
+ import type { LLMResponseTask } from './policy/tasks.ts';
4
+ import { getLLMDefaultFallbackRoute, getLLMTaskPolicy, toLLMRoute } from './router.ts';
5
+ import type {
6
+ LLMEffort,
7
+ LLMPin,
8
+ LLMPinnedRouteChoice,
9
+ LLMProviderName,
10
+ LLMRoute,
11
+ LLMRouteDecision,
12
+ LLMRouteSource,
13
+ LLMRouteSwitch,
14
+ LLMRouteSwitchReason,
15
+ LLMStoredRoute,
16
+ LLMVerbosity,
17
+ } from './types.ts';
18
+
19
+ // Whether a route may carry a task's content (the router's isLLMRouteAllowed, or a test's own check)
20
+ type LLMRouteAllowedCheck = (task: LLMResponseTask, route: LLMRoute) => boolean;
21
+
22
+ const FILE_CONSTANTS = {
23
+ // Canonical effort order, also used to validate saved routes and pins.
24
+ effortRank: { none: 0, minimal: 1, low: 2, medium: 3, high: 4, xhigh: 5, max: 6 } satisfies Record<LLMEffort, number>,
25
+ // The values a stored route or pin may hold; `satisfies` keeps each set complete
26
+ providers: { openai: true, deepseek: true, anthropic: true } satisfies Record<LLMProviderName, true>,
27
+ verbosities: { low: true, medium: true, high: true } satisfies Record<LLMVerbosity, true>,
28
+ sources: { policy: true, trial: true, pin: true, recovered: true, caller: true } satisfies Record<LLMRouteSource, true>,
29
+ maxClockSkewMS: 60_000, // A stored time may sit this far in the future and still count
30
+ };
31
+
32
+ /* Whether a value is a plain object whose keys can be read. */
33
+ function isLLMRecord(value: unknown): value is Record<string, unknown> {
34
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
35
+ }
36
+
37
+ /* Whether a value is one of the keys of a value set. */
38
+ function isLLMValueOf<K extends string>(values: Record<K, unknown>, value: unknown): value is K {
39
+ return typeof value === 'string' && Object.hasOwn(values, value);
40
+ }
41
+
42
+ /* Whether a value is an ISO time exactly as toISOString writes it. */
43
+ function isLLMISOTime(value: unknown): value is string {
44
+ if (typeof value !== 'string') return false;
45
+ const time = Date.parse(value);
46
+ return Number.isFinite(time) && new Date(time).toISOString() === value;
47
+ }
48
+
49
+ /*
50
+ * Parse a stored route: a known provider, effort and verbosity and a model with a catalog entry; null for any other
51
+ * shape, so a route naming a removed model is never reused.
52
+ */
53
+ function parseLLMRoute(value: unknown): LLMRoute | null {
54
+ if (!isLLMRecord(value)) return null;
55
+ const { provider, model, effort, verbosity } = value;
56
+ if (
57
+ !isLLMValueOf(FILE_CONSTANTS.providers, provider) || typeof model !== 'string' || getLLMModelEntry(model)?.provider !== provider
58
+ ) return null;
59
+ if (!isLLMValueOf(FILE_CONSTANTS.effortRank, effort) || !isLLMValueOf(FILE_CONSTANTS.verbosities, verbosity)) return null;
60
+ return { provider, model, effort, verbosity };
61
+ }
62
+
63
+ /* Whether two routes are the same provider, model, effort and verbosity. */
64
+ function isSameLLMRoute(a: LLMRoute, b: LLMRoute): boolean {
65
+ return a.provider === b.provider && a.model === b.model && a.effort === b.effort && a.verbosity === b.verbosity;
66
+ }
67
+
68
+ /* A model's strength from its entry; 0 for an unknown model. */
69
+ function getLLMModelStrength(model: string): number {
70
+ return getLLMModelEntry(model)?.strength ?? 0;
71
+ }
72
+
73
+ /* The cache lifetime of a pin's model; 0 for an unknown model, so its pin is never warm. */
74
+ function getLLMPinLifetimeMS(pin: LLMPin): number {
75
+ return getLLMModelEntry(pin.route.model)?.cacheLifetimeMS ?? 0;
76
+ }
77
+
78
+ /* Whether a stored time is less than one lifetime before now and at most the allowed clock skew after it. */
79
+ function isWithinLLMLifetime(time: string, now: number, lifetimeMS: number): boolean {
80
+ const elapsed = now - Date.parse(time);
81
+ return lifetimeMS > 0 && elapsed >= -(getLLMRouterConfig().routing.pinning?.maxClockSkewMS ?? FILE_CONSTANTS.maxClockSkewMS) &&
82
+ elapsed < lifetimeMS;
83
+ }
84
+
85
+ /* The tier-table fallback of a route when the task may use it, else null. */
86
+ function getAllowedLLMFallbackRoute(task: LLMResponseTask, route: LLMRoute, isAllowed: LLMRouteAllowedCheck): LLMRoute | null {
87
+ const policy = getLLMTaskPolicy(task);
88
+ const fallback = policy.fallback === undefined
89
+ ? getLLMDefaultFallbackRoute(route)
90
+ : policy.fallback
91
+ ? toLLMRoute(policy.fallback)
92
+ : null;
93
+ return fallback && isAllowed(task, fallback) ? fallback : null;
94
+ }
95
+
96
+ /*
97
+ * A decision moved onto a kept route (a held or recovered pin, or a checkpoint's route): that route and rule, the
98
+ * route's allowed default fallback, and the given source.
99
+ */
100
+ function keepLLMRoute(
101
+ decision: LLMRouteDecision,
102
+ kept: LLMStoredRoute,
103
+ source: LLMRouteSource,
104
+ isAllowed: LLMRouteAllowedCheck,
105
+ ): LLMRouteDecision {
106
+ return {
107
+ ...decision,
108
+ route: kept.route,
109
+ fallback: isSameLLMRoute(decision.route, kept.route)
110
+ ? decision.fallback
111
+ : getAllowedLLMFallbackRoute(decision.task, kept.route, isAllowed),
112
+ source,
113
+ rule: kept.rule,
114
+ };
115
+ }
116
+
117
+ /* The switch from one route to another, or null when both are the same route. */
118
+ function getLLMRouteSwitch(
119
+ task: LLMResponseTask,
120
+ from: LLMRoute,
121
+ to: LLMRoute,
122
+ reason: LLMRouteSwitchReason,
123
+ warm: boolean | null,
124
+ ): LLMRouteSwitch | null {
125
+ return isSameLLMRoute(from, to) ? null : { task, from, to, reason, warm };
126
+ }
127
+
128
+ /* Order two routes by model strength, then the requested effort's canonical seven-level rank; unknown models rank 0. */
129
+ export function compareLLMRouteStrength(a: LLMRoute, b: LLMRoute): number {
130
+ const byModel = getLLMModelStrength(a.model) - getLLMModelStrength(b.model);
131
+ return byModel || FILE_CONSTANTS.effortRank[a.effort] - FILE_CONSTANTS.effortRank[b.effort];
132
+ }
133
+
134
+ /*
135
+ * Parse a stored pin; null for any other shape or version, an unknown provider, model, effort or verbosity, or a
136
+ * non-ISO time (a corrupt pin, or one on a removed model, is a cold start).
137
+ */
138
+ export function parseLLMPin(value: unknown): LLMPin | null {
139
+ if (!isLLMRecord(value) || value.v !== 1) return null;
140
+ const { organizationId, runId, source, rule, chosenAt, lastRequestAt, epoch } = value;
141
+ const route = parseLLMRoute(value.route);
142
+ if (!route || typeof organizationId !== 'string' || !organizationId || (runId !== null && typeof runId !== 'string')) return null;
143
+ if (!isLLMValueOf(FILE_CONSTANTS.sources, source) || typeof rule !== 'string' || !rule) return null;
144
+ if (!isLLMISOTime(chosenAt) || !isLLMISOTime(lastRequestAt)) return null;
145
+ if (typeof epoch !== 'number' || !Number.isSafeInteger(epoch) || epoch < 0) return null;
146
+ return { v: 1, organizationId, runId, route, source, rule, chosenAt, lastRequestAt, epoch };
147
+ }
148
+
149
+ /* Parse a checkpointed route; null for any other shape, provider, model, effort or verbosity. */
150
+ export function parseLLMStoredRoute(value: unknown): LLMStoredRoute | null {
151
+ if (!isLLMRecord(value)) return null;
152
+ const { rule } = value;
153
+ const route = parseLLMRoute(value.route);
154
+ return route && typeof rule === 'string' && rule ? { route, rule } : null;
155
+ }
156
+
157
+ /*
158
+ * Whether the pin's last request is within its model's cache lifetime (unknown model: 0) and at most 60 s in the future
159
+ * (clock skew).
160
+ */
161
+ export function isLLMPinFresh(pin: LLMPin, now: number): boolean {
162
+ return isWithinLLMLifetime(pin.lastRequestAt, now, getLLMPinLifetimeMS(pin));
163
+ }
164
+
165
+ /* Fresh, and its route was chosen less than one cache lifetime ago (same clock-skew bound): the never-downgrade hold. */
166
+ export function isLLMPinHeld(pin: LLMPin, now: number): boolean {
167
+ return isLLMPinFresh(pin, now) &&
168
+ isWithinLLMLifetime(pin.chosenAt, now, getLLMRouterConfig().routing.pinning?.holdMS ?? getLLMPinLifetimeMS(pin));
169
+ }
170
+
171
+ /*
172
+ * Apply the cache rules to this run's candidate decision, in order: no pin (NONE); this run's own pin on a recovered
173
+ * attempt (RECOVERED, kept without a warmth check, whatever organization wrote it: a run id is unique, and the run may
174
+ * have switched organization since); another organization's pin (NONE); a pin route the task may not use, or a cold pin
175
+ * (COLD, candidate); a stronger candidate (WARM, upgrade); a held pin (WARM, kept, never downgraded); a warm pin whose
176
+ * hold is over (WARM, candidate). Warmth is time-only; the context epoch is not read. A switch is reported only when the
177
+ * route changes.
178
+ */
179
+ export function chooseLLMPinnedRoute(input: {
180
+ candidate: LLMRouteDecision;
181
+ pin: LLMPin | null;
182
+ now: number;
183
+ organizationId: string;
184
+ runId: string | null;
185
+ isAllowed: LLMRouteAllowedCheck;
186
+ }): LLMPinnedRouteChoice {
187
+ const { candidate, pin, now, isAllowed } = input;
188
+ const task = candidate.task;
189
+ if (!pin) return { decision: candidate, pinState: 'NONE', switched: null, held: null };
190
+ const allowed = isAllowed(task, pin.route);
191
+ if (getLLMRouterConfig().routing.pinning?.reuseRecovered !== false && input.runId !== null && pin.runId === input.runId && allowed) {
192
+ const switched = getLLMRouteSwitch(task, candidate.route, pin.route, 'recovered', null);
193
+ return { decision: keepLLMRoute(candidate, pin, 'recovered', isAllowed), pinState: 'RECOVERED', switched, held: pin };
194
+ }
195
+ if (pin.organizationId !== input.organizationId) return { decision: candidate, pinState: 'NONE', switched: null, held: null };
196
+ const fresh = isLLMPinFresh(pin, now);
197
+ if (!allowed) {
198
+ return {
199
+ decision: candidate,
200
+ pinState: 'COLD',
201
+ switched: getLLMRouteSwitch(task, pin.route, candidate.route, 'capability', fresh),
202
+ held: null,
203
+ };
204
+ }
205
+ if (!fresh) {
206
+ return {
207
+ decision: candidate,
208
+ pinState: 'COLD',
209
+ switched: getLLMRouteSwitch(task, pin.route, candidate.route, 'cold', false),
210
+ held: null,
211
+ };
212
+ }
213
+ if (getLLMRouterConfig().routing.pinning?.upgradeImmediately !== false && compareLLMRouteStrength(candidate.route, pin.route) > 0) {
214
+ return {
215
+ decision: candidate,
216
+ pinState: 'WARM',
217
+ switched: getLLMRouteSwitch(task, pin.route, candidate.route, 'upgrade', true),
218
+ held: null,
219
+ };
220
+ }
221
+ if (isLLMPinHeld(pin, now)) {
222
+ return { decision: keepLLMRoute(candidate, pin, 'pin', isAllowed), pinState: 'WARM', switched: null, held: pin };
223
+ }
224
+ return {
225
+ decision: candidate,
226
+ pinState: 'WARM',
227
+ switched: getLLMRouteSwitch(task, pin.route, candidate.route, 'hold_expired', true),
228
+ held: null,
229
+ };
230
+ }
231
+
232
+ /*
233
+ * The pin one compiled request writes: the held pin's route, source, rule and chosenAt when the run kept one, else the
234
+ * decision's route, source and rule, chosen now. Organization, run, epoch and lastRequestAt always come from this request.
235
+ */
236
+ export function makeLLMPin(input: {
237
+ decision: LLMRouteDecision;
238
+ held: LLMPin | null;
239
+ organizationId: string;
240
+ runId: string | null;
241
+ epoch: number;
242
+ now: number;
243
+ }): LLMPin {
244
+ const { organizationId, runId, epoch } = input;
245
+ const lastRequestAt = new Date(input.now).toISOString();
246
+ if (input.held) return { ...input.held, organizationId, runId, epoch, lastRequestAt };
247
+ const { route, source, rule } = input.decision;
248
+ return { v: 1, organizationId, runId, route, source, rule, chosenAt: lastRequestAt, lastRequestAt, epoch };
249
+ }
250
+
251
+ /*
252
+ * Reuse a recovered run's stored route when its rule equals the resolved rule (same signals) and the task may use it;
253
+ * else keep the resolved decision. A reused route that differs from the resolved one is reported as a recovered switch.
254
+ */
255
+ export function reuseRecoveredLLMRoute(input: {
256
+ stored: LLMStoredRoute | null;
257
+ resolved: LLMRouteDecision;
258
+ isAllowed: LLMRouteAllowedCheck;
259
+ }): { decision: LLMRouteDecision; switched: LLMRouteSwitch | null } {
260
+ const { stored, resolved, isAllowed } = input;
261
+ if (
262
+ getLLMRouterConfig().routing.pinning?.reuseRecovered === false || !stored || stored.rule !== resolved.rule ||
263
+ !isAllowed(resolved.task, stored.route)
264
+ ) {
265
+ return { decision: resolved, switched: null };
266
+ }
267
+ const switched = getLLMRouteSwitch(resolved.task, resolved.route, stored.route, 'recovered', null);
268
+ return { decision: switched ? keepLLMRoute(resolved, stored, 'recovered', isAllowed) : resolved, switched };
269
+ }
package/src/router.ts ADDED
@@ -0,0 +1,204 @@
1
+ import { getLLMRouteOffending, type LLMRequestPortability, routeServesRequest } from './capabilities.ts';
2
+ import { getDefaultFallbackModel, getLLMModelEntry, getModelForTier } from './policy/models.ts';
3
+ import type { LLMResponseTask, LLMTaskCall, LLMTaskPolicy, LLMTaskPolicyMap } from './policy/tasks.ts';
4
+ import { getLLMRouterConfig, isLLMProviderConfigured } from './registry.ts';
5
+ import { validateLLMRouteSpec } from './registry.helpers.ts';
6
+ import { emitLLMTrace } from './trace.ts';
7
+ import type { LLMProviderName, LLMRoute, LLMRouteDecision, LLMRouteSpec } from './types.ts';
8
+ import { LLMRouteError } from './utils/errors.ts';
9
+
10
+ export interface LLMRouteOptions {
11
+ policies?: LLMTaskPolicyMap; // defaults to the registered policies
12
+ isConfigured?: (provider: LLMProviderName) => boolean; // defaults to the registry's isLLMProviderConfigured
13
+ }
14
+
15
+ // One route a resolution may choose, in candidate order: the trial, the rule, the rule's fallback
16
+ type LLMRouteCandidate = Omit<LLMRouteDecision, 'task'>;
17
+
18
+ // Why a candidate is not usable: its provider, an unknown request (resolved before the call), or the request's labels it cannot serve
19
+ type LLMRouteExclusion = 'provider_not_allowed' | 'provider_unconfigured' | 'portability_unknown' | string[];
20
+
21
+ /* Resolve a registered model's provider; unknown models are configuration errors. */
22
+ function getLLMModelProvider(model: string): LLMProviderName {
23
+ const entry = getLLMModelEntry(model);
24
+ if (!entry) throw new Error(`Unknown LLM model "${model}".`);
25
+ return entry.provider;
26
+ }
27
+
28
+ /* Turn a policy spec into a route: the tier through the tier table, the provider from the model entry (unknown models are rejected). */
29
+ export function toLLMRoute(spec: LLMRouteSpec): LLMRoute {
30
+ validateLLMRouteSpec(spec, getLLMRouterConfig().routing);
31
+ const model = spec.model === undefined ? getModelForTier(spec.tier) : spec.model;
32
+ return { provider: getLLMModelProvider(model), model, effort: spec.effort, verbosity: spec.verbosity };
33
+ }
34
+
35
+ /* The tier-table fallback of a route: getDefaultFallbackModel, the provider of that model, same effort and verbosity. */
36
+ export function getLLMDefaultFallbackRoute(route: LLMRoute): LLMRoute | null {
37
+ const model = getDefaultFallbackModel(route.model);
38
+ if (!model || model === route.model) return null;
39
+ return { provider: getLLMModelProvider(model), model, effort: route.effort, verbosity: route.verbosity };
40
+ }
41
+
42
+ /* Read a registered task policy, reporting missing tasks before a provider request is made. */
43
+ export function getLLMTaskPolicy(task: LLMResponseTask, options: LLMRouteOptions = {}): LLMTaskPolicy<any> {
44
+ const policies = options.policies ?? getLLMRouterConfig().routing.policies;
45
+ if (!Object.hasOwn(policies, task)) throw new LLMRouteError(task, [], [{ model: '', reason: 'task_not_registered' }]);
46
+ return policies[task];
47
+ }
48
+
49
+ /* Why a route's provider may not carry the task's content: not in the allow-list (default ['openai']), or not configured; null when it may. */
50
+ function getLLMRouteProviderExclusion(
51
+ task: LLMResponseTask,
52
+ route: LLMRoute,
53
+ options: LLMRouteOptions,
54
+ ): 'provider_not_allowed' | 'provider_unconfigured' | null {
55
+ const providers = getLLMTaskPolicy(task, options).providers ?? getLLMRouterConfig().routing.defaultProviders ?? ['openai'];
56
+ const entry = getLLMModelEntry(route.model);
57
+ if (entry && entry.provider !== route.provider) return 'provider_not_allowed';
58
+ if (!providers.includes(route.provider)) return 'provider_not_allowed';
59
+ if ((options.isConfigured ?? isLLMProviderConfigured)(route.provider)) return null;
60
+ return 'provider_unconfigured';
61
+ }
62
+
63
+ /*
64
+ * Whether a route may carry this task's content: its provider is in the task's allow-list (default ['openai']) and
65
+ * configured. The pin and recovery rules take it as their isAllowed check.
66
+ */
67
+ export function isLLMRouteAllowed(task: LLMResponseTask, route: LLMRoute, options: LLMRouteOptions = {}): boolean {
68
+ return !getLLMRouteProviderExclusion(task, route, options);
69
+ }
70
+
71
+ /*
72
+ * Why a route cannot carry one request, or null when it can: its provider first, then (non-OpenAI only) whether the
73
+ * request is portable to it. The portability is read only here, so an OpenAI-only resolution never computes it.
74
+ */
75
+ function getLLMRouteExclusion(
76
+ task: LLMResponseTask,
77
+ route: LLMRoute,
78
+ options: LLMRouteOptions,
79
+ getPortability: (() => LLMRequestPortability) | undefined,
80
+ ): LLMRouteExclusion | null {
81
+ const providerExclusion = getLLMRouteProviderExclusion(task, route, options);
82
+ if (providerExclusion || route.provider === 'openai') return providerExclusion;
83
+ if (!getPortability) return 'portability_unknown';
84
+ const portability = getPortability();
85
+ if (routeServesRequest(route, portability)) return null;
86
+ const offending = getLLMRouteOffending(route, portability);
87
+ return offending.length ? offending : ['input_image'];
88
+ }
89
+
90
+ /* The candidates of one task call in order: the trial (only for a listed organization), the rule, the rule's fallback. */
91
+ function getLLMRouteCandidates(
92
+ policy: LLMTaskPolicy<unknown>,
93
+ chosen: { route: LLMRouteSpec; rule: string },
94
+ organizationId: string | null | undefined,
95
+ ): LLMRouteCandidate[] {
96
+ const ruleRoute = toLLMRoute(chosen.route);
97
+ const ruleFallback = policy.fallback === undefined
98
+ ? getLLMDefaultFallbackRoute(ruleRoute)
99
+ : policy.fallback
100
+ ? toLLMRoute(policy.fallback)
101
+ : null;
102
+ const trial = policy.trial && organizationId && policy.trial.organizationIds.includes(organizationId) ? policy.trial : null;
103
+ return [
104
+ // A failed trial falls back to the task's normal route
105
+ ...(trial ? [{ route: toLLMRoute(trial.route), fallback: ruleRoute, source: 'trial' as const, rule: 'trial' }] : []),
106
+ { route: ruleRoute, fallback: ruleFallback, source: 'policy', rule: chosen.rule },
107
+ ...(ruleFallback ? [{ route: ruleFallback, fallback: null, source: 'policy' as const, rule: 'capability' }] : []),
108
+ ];
109
+ }
110
+
111
+ /* Trace one skipped candidate (ai.route.switched; no cache state applies): info for a skipped trial, warn for a skipped rule route. */
112
+ function traceLLMRouteSkip(task: LLMResponseTask, skipped: LLMRouteCandidate, chosen: LLMRoute, exclusion: LLMRouteExclusion): void {
113
+ emitLLMTrace(skipped.source === 'trial' ? 'info' : 'warn', 'ai.route.switched', {
114
+ task,
115
+ from: skipped.route,
116
+ to: chosen,
117
+ reason: 'capability',
118
+ warm: null,
119
+ rereadTokens: null,
120
+ excluded: exclusion,
121
+ });
122
+ }
123
+
124
+ /*
125
+ * Apply the task's trial and rule; keep the first allowed candidate that can serve the request. Its fallback is kept
126
+ * only when it is usable by the same test. Every skipped candidate is traced; nothing usable throws LLMRouteError.
127
+ * Without portability (a resolution before the call) a non-OpenAI candidate is not usable. Source 'policy' or 'trial'.
128
+ */
129
+ export function resolveLLMTaskRoute(
130
+ input: LLMTaskCall & { organizationId?: string | null; portability?: () => LLMRequestPortability },
131
+ options: LLMRouteOptions = {},
132
+ ): LLMRouteDecision {
133
+ const policy = getLLMTaskPolicy(input.task, options);
134
+ const chosen = typeof policy.route === 'function' ? policy.route(input.signals) : { route: policy.route, rule: 'fixed' };
135
+ let portability: LLMRequestPortability | undefined;
136
+ const getPortability = input.portability && (() => (portability ??= input.portability!()));
137
+ const skipped: Array<{ candidate: LLMRouteCandidate; exclusion: LLMRouteExclusion }> = [];
138
+ for (const candidate of getLLMRouteCandidates(policy, chosen, input.organizationId)) {
139
+ const exclusion = getLLMRouteExclusion(input.task, candidate.route, options, getPortability);
140
+ if (exclusion) {
141
+ skipped.push({ candidate, exclusion });
142
+ continue;
143
+ }
144
+ const fallbackUsable = !!candidate.fallback && !getLLMRouteExclusion(input.task, candidate.fallback, options, getPortability);
145
+ for (const skip of skipped) traceLLMRouteSkip(input.task, skip.candidate, candidate.route, skip.exclusion);
146
+ return {
147
+ task: input.task,
148
+ route: candidate.route,
149
+ fallback: fallbackUsable ? candidate.fallback : null,
150
+ source: candidate.source,
151
+ rule: candidate.rule,
152
+ };
153
+ }
154
+ throw makeLLMRouteError(
155
+ input.task,
156
+ portability,
157
+ skipped.map(({ candidate, exclusion }) => ({ route: candidate.route, exclusion })),
158
+ );
159
+ }
160
+
161
+ /* The error of a request no route can carry: the request's offending labels (when computed) and every excluded route with its reason. */
162
+ function makeLLMRouteError(
163
+ task: LLMResponseTask,
164
+ portability: LLMRequestPortability | undefined,
165
+ excluded: Array<{ route: LLMRoute; exclusion: LLMRouteExclusion }>,
166
+ ): LLMRouteError {
167
+ return new LLMRouteError(
168
+ task,
169
+ portability?.offending ?? [],
170
+ excluded.map(({ route, exclusion }) => ({
171
+ model: route.model,
172
+ reason: Array.isArray(exclusion) ? exclusion.join(',') : exclusion,
173
+ })),
174
+ );
175
+ }
176
+
177
+ /*
178
+ * Check a decision resolved before the call against the request: its route must be allowed and able to serve it, else
179
+ * LLMRouteError (nothing is sent). Its fallback is kept only when usable by the same test. Returns the same decision
180
+ * object when nothing changes, as for every OpenAI route and fallback of a task that allows OpenAI (the default).
181
+ */
182
+ export function getUsableLLMRouteDecision(
183
+ decision: LLMRouteDecision,
184
+ getRequestPortability: () => LLMRequestPortability,
185
+ ): LLMRouteDecision {
186
+ if (decision.source !== 'caller' && !getLLMModelEntry(decision.route.model)) {
187
+ throw new LLMRouteError(decision.task, [], [{ model: decision.route.model, reason: 'model_not_registered' }]);
188
+ }
189
+ let portability: LLMRequestPortability | undefined;
190
+ const getPortability = () => (portability ??= getRequestPortability());
191
+ const exclusion = getLLMRouteExclusion(decision.task, decision.route, {}, getPortability);
192
+ if (exclusion) throw makeLLMRouteError(decision.task, portability, [{ route: decision.route, exclusion }]);
193
+ if (decision.source !== 'caller' && decision.fallback && !getLLMModelEntry(decision.fallback.model)) {
194
+ return { ...decision, fallback: null };
195
+ }
196
+ if (!decision.fallback || !getLLMRouteExclusion(decision.task, decision.fallback, {}, getPortability)) return decision;
197
+ return { ...decision, fallback: null };
198
+ }
199
+
200
+ /* A caller-made decision for tests, evals and probes (source and rule 'caller'); fallback defaults to the tier-table rule. */
201
+ export function makeLLMRouteDecision(input: { task: LLMResponseTask; route: LLMRoute; fallback?: LLMRoute | null }): LLMRouteDecision {
202
+ const fallback = input.fallback === undefined ? getLLMDefaultFallbackRoute(input.route) : input.fallback;
203
+ return { task: input.task, route: input.route, fallback, source: 'caller', rule: 'caller' };
204
+ }
package/src/trace.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { getLLMTraceLogger } from './registry.ts';
2
+ import type { LLMTraceLevel } from './types.ts';
3
+
4
+ /* Send one event to the registered logger; before registration only warn on the console. */
5
+ export function emitLLMTrace(
6
+ level: LLMTraceLevel,
7
+ name: string,
8
+ fields: Record<string, unknown>,
9
+ options?: { detail?: boolean },
10
+ ): void {
11
+ const logger = getLLMTraceLogger();
12
+ if (!logger) {
13
+ console.warn(name, fields);
14
+ return;
15
+ }
16
+ logger(level, name, fields, options);
17
+ }