@jsb188/llm-router 0.0.0-stage → 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jsb188
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,203 @@
1
- # Temporary Holding Version
1
+ # LLM router
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The application owns task names, business rules, model choices and classification instructions. This package executes routes, adapts
4
+ provider requests, checks capabilities, handles retries, and exposes recording/usage hooks.
5
+
6
+ ## Register once at startup
7
+
8
+ ```ts
9
+ import { configureLLMRouter } from '@jsb188/llm-router/main.ts';
10
+ import { models, policies, tiers } from './llmPolicies.ts';
11
+
12
+ configureLLMRouter({
13
+ providers: { openai: { apiKey: environment.openaiKey } },
14
+ routing: {
15
+ models,
16
+ policies,
17
+ tiers,
18
+ defaultProviders: ['openai'],
19
+ fallbackModel: (model) => model === tiers.standard ? tiers.advanced : tiers.standard,
20
+ pinning: { holdMS: 30 * 60_000, upgradeImmediately: true, reuseRecovered: true },
21
+ },
22
+ defaults: {
23
+ decisionsModel: 'your-decisions-model',
24
+ embedding: { model: 'your-embedding-model', dimensions: 1536 },
25
+ moderationModel: 'your-moderation-model',
26
+ transcriptionModel: 'your-transcription-model',
27
+ },
28
+ retries: { sdkRetries: 2, transportRetries: 2, initialDelayMS: 500, maxDelayMS: 30_000 },
29
+ observer: requestObserver,
30
+ traceLogger,
31
+ });
32
+ ```
33
+
34
+ Registration validates static routes, model/tier references, fallbacks, classifier definitions, and operation defaults before replacing
35
+ the active router. Providers and hooks are installed together. A failed registration leaves the previous registration intact. Static
36
+ configuration is copied and frozen; callback closures and observer hooks remain application-owned. Reconfigure with a complete
37
+ configuration to update settings. `getLLMRouterConfig()` exposes the current registration for controlled updates and tests.
38
+
39
+ A model entry supplies provider, image capability, strength ranking, cache lifetime, and optional prices. The application chooses
40
+ rankings and tier names. Unknown policy models and tiers fail clearly. A missing task fails before a provider request. Provider keys
41
+ alone do not authorize a task to send data to that provider: its provider allow-list must also permit it.
42
+
43
+ ## Model-specific reasoning effort
44
+
45
+ Every route accepts `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, and `max`. Before each attempt, including a fallback to
46
+ another model, the router resolves the requested effort against that model's capabilities:
47
+
48
+ 1. Keep an effort the model supports.
49
+ 2. Apply a documented provider mapping when present, such as DeepSeek's `medium` and `xhigh` to `high`.
50
+ 3. Otherwise choose the nearest level in the seven-level order, preferring the stronger level on a tie. A positive request never
51
+ disables thinking when the model has a positive reasoning level. If `none` is unavailable, use the lowest supported level.
52
+
53
+ These are compatibility choices, not a promise that equal labels consume equal tokens across models. For example, `minimal` becomes
54
+ `low` on Claude, `xhigh` becomes `max` on Claude Opus 4.6, and `none` becomes `low` on an always-thinking model. Non-reasoning models
55
+ such as GPT-4.1 resolve to `none` and omit the unsupported reasoning parameter.
56
+
57
+ Known models have built-in profiles in `src/policy/reasoning.ts`. A model entry can override them with `reasoning`; unrecognized models
58
+ require an explicit profile before a response request can run. Registration validates supplied profiles. For example, a custom
59
+ OpenAI-compatible model entry can declare:
60
+
61
+ ```ts
62
+ reasoning: {
63
+ supportedEfforts: ['none', 'low', 'high'],
64
+ mappings: { medium: 'high' },
65
+ }
66
+ ```
67
+
68
+ Anthropic profiles also declare `anthropic: { mode: 'adaptive' }`, or `mode: 'budget'` with a token budget for each positive supported
69
+ level. Legacy Claude defaults use router-defined budgets of 1024 / 4096 / 8192 tokens for low / medium / high; these are not native
70
+ named thinking levels. Use `effort: false` inside the Anthropic configuration for budget-only models without native effort support. An
71
+ explicit `max_output_tokens` must exceed the selected legacy thinking budget; otherwise the request fails before transport. When
72
+ omitted, the output limit defaults to the selected budget plus 4096 tokens.
73
+
74
+ `mapCompatibleReasoningEffort(model, effort, provider?)` uses registered overrides; `resolveReasoningEffort` can resolve a standalone
75
+ profile. Both are exported from the package root. Observers retain the requested route effort, receive the effective request effort,
76
+ and see any conversion in `mappedParams`, for example `reasoning.effort:xhigh->high`.
77
+
78
+ ## Optional Anthropic provider
79
+
80
+ The package includes the native `@anthropic-ai/sdk`. Anthropic is opt-in: register its explicit API key, add the chosen Claude model to
81
+ the application's catalog, and allow `anthropic` on the intended task. Installing this package does not change existing routes, tiers,
82
+ defaults, or provider allow-lists. For example, extend an existing complete registration:
83
+
84
+ ```ts
85
+ configureLLMRouter({
86
+ ...config,
87
+ providers: { ...config.providers, anthropic: { apiKey: environment.anthropicKey } },
88
+ routing: {
89
+ ...config.routing,
90
+ models: {
91
+ ...config.routing.models,
92
+ 'claude-sonnet-4-6': { provider: 'anthropic', strength: 30, imageInput: true, cacheLifetimeMS: 0, prices: null },
93
+ },
94
+ policies: {
95
+ ...config.routing.policies,
96
+ 'anthropic.example': {
97
+ providers: ['anthropic'],
98
+ route: { model: 'claude-sonnet-4-6', effort: 'medium', verbosity: 'medium' },
99
+ fallback: null,
100
+ },
101
+ },
102
+ },
103
+ });
104
+
105
+ await createResponse({ task: 'anthropic.example' }, { input: 'Hello', max_output_tokens: 1024 });
106
+ ```
107
+
108
+ Use an actual Claude model identifier available to your account. Catalog entries and prices remain application-owned. Calling
109
+ `createLLMProviderClient('anthropic', ...)` returns the native Anthropic client; OpenAI and DeepSeek clients retain their existing
110
+ types and behavior. Low-level clients bypass routing and recording.
111
+
112
+ The shared request/response API retains its Responses shape. The adapter translates text, leading system/developer instructions,
113
+ function schemas, parallel calls and results, HTTP(S)/base64 images, explicit tool choice, and JSON schema output into Messages API
114
+ requests. `max_output_tokens` maps to `max_tokens`, defaulting to 4096. Structured results are validated by the existing Zod parser;
115
+ raw JSON schema is supported through `createResponse`, while `createJSONResponse` requires `zodTextFormat`. Streaming emits the
116
+ existing Responses events, preserves cancellation, and rejects interrupted streams. Refusals remain refusals and token-limit stops
117
+ remain incomplete. Retries, explicit fallbacks, pins, and observer hooks use the same router policies as other providers.
118
+
119
+ This initial adapter supports eager, unnamespaced custom function tools. Capability checks reject hosted tools, tool search,
120
+ namespaces/deferred tools, provider file IDs/files, foreign-provider reasoning history, stateful response references, assistant
121
+ prefilling, and system/developer messages inserted after conversation history. Supply complete stateless tool histories with all
122
+ parallel results immediately following their calls. Applications using those unsupported features need a separate integration before
123
+ choosing an Anthropic route. A task with a compatible permitted fallback may use that route instead; an explicit incompatible decision
124
+ fails.
125
+
126
+ Native thinking follows the resolved model-specific effort. Signed thinking and redacted blocks are carried in opaque
127
+ `reasoning.encrypted_content` values and restored unchanged for tool continuations; keep these response items in conversation history.
128
+ Thinking text is omitted by default; requesting a reasoning summary enables summarized display. Active thinking requires automatic or
129
+ disabled tool choice; forcing a specific tool or requiring a tool fails capability checks. Text verbosity, OpenAI prompt-cache
130
+ controls, storage, service-tier, and safety-identifier settings are stripped and recorded in attempt metadata. Anthropic prompt caching
131
+ is not enabled by these OpenAI controls. Usage normalizes total input (fresh + cache read + cache write), cached tokens, cache-write
132
+ tokens, and output tokens. `buildResponseParams` and observer `attempt.params` expose the adapted router request; the native Messages
133
+ payload is generated at the transport boundary. Raw HTTP capture remains available to structured-response observers.
134
+
135
+ Credentials must be supplied explicitly. `ANTHROPIC_CUSTOM_HEADERS` must be unset so environment headers cannot override the registered
136
+ credential. Anthropic-only reasoning replay and local response-item IDs are removed from outbound OpenAI/DeepSeek history while
137
+ tool-call IDs and the application's original receipt objects remain intact.
138
+
139
+ Decisions, embeddings, moderation, transcription, and file operations continue using their existing OpenAI integration. Application
140
+ usage ledgers must support Anthropic before activating it. Run `yarn workspace @jsb188/llm-router test` on Node 24+ for offline mocked
141
+ transport tests, and `yarn workspace @jsb188/llm-router typecheck` for package validation.
142
+
143
+ ## Route a task
144
+
145
+ ```ts
146
+ const policies = {
147
+ 'assistant.reply': {
148
+ route: { tier: 'standard', effort: 'medium', verbosity: 'medium' },
149
+ },
150
+ 'document.process': {
151
+ route: ({ escalated }: { escalated: boolean }) => ({
152
+ route: { tier: escalated ? 'advanced' : 'standard', effort: 'high', verbosity: 'low' },
153
+ rule: escalated ? 'escalated' : 'primary',
154
+ }),
155
+ fallback: null,
156
+ },
157
+ };
158
+ ```
159
+
160
+ Call `createResponse({ task, signals, meta }, params)` or `createJSONResponse(...)`. Alternatively, resolve once with
161
+ `resolveLLMTaskRoute({ task, signals })`, persist the result, and pass `{ decision, meta }`. Use an application wrapper with its own
162
+ task/signal union for compile-time business validation. The package's task vocabulary is intentionally open.
163
+
164
+ A policy's `fallback` overrides the global fallback; `null` disables it. An organization trial can select another route and falls back
165
+ to the task's regular route. Capability checks run before requests. `makeLLMRouteDecision` supports explicit callers such as probes;
166
+ such callers may name uncatalogued models with an explicit provider and a built-in reasoning profile, but still obey the task's
167
+ provider allow-list and capability checks. Stored pins require a catalogued model with a matching provider.
168
+
169
+ ## Optional classification
170
+
171
+ A task can register `classifier: { instructions, choices, fallback, minProbability?, select? }`. Each choice names a value, optional
172
+ description, and complete route. Classification is explicit so the app controls context selection, timing, billing and retry ownership:
173
+
174
+ ```ts
175
+ const policy = getLLMTaskPolicy('document.process');
176
+ const classification = await classifyLLMRoute(
177
+ policy.classifier!,
178
+ inputText,
179
+ (params) => trackedDecisionsRequest(params),
180
+ );
181
+ const decision = makeLLMRouteDecision({
182
+ task: 'document.process',
183
+ route: classification.route,
184
+ fallback: null,
185
+ });
186
+ await trackedJSONRequest({ decision }, responseParams);
187
+ ```
188
+
189
+ The classifier executor is not called when every candidate has the same provider/model/effort/verbosity. Multiple routes cause one
190
+ Decisions call; by default the highest qualifying probability wins. The app may register another selection strategy. The classifier's
191
+ uncertainty fallback is distinct from a provider-error fallback. There is no shadow mode or automatic background classification.
192
+ Registering a classifier does not itself invoke it.
193
+
194
+ ## Operational behavior
195
+
196
+ - Defaults for Decisions, embeddings, moderation and transcription are read by their operation wrappers. The registered Decisions model
197
+ is authoritative; apps should use the same setting when capturing request parameters.
198
+ - Request observers receive opaque application metadata and own recording, usage persistence, and durable-run ownership checks.
199
+ - `singleAttempt` disables SDK, transport and cache-feature retries. By default one cross-provider failure/schema fallback remains
200
+ allowed; set `retries.crossProviderFallbackOnSingleAttempt: false` for a strict single-request budget.
201
+ - Pins compare app-provided model strength, then reasoning effort. Cache freshness uses the registered model lifetime. The hold period
202
+ can be configured independently. The application persists pins and checkpoints.
203
+ - Pricing estimation accepts an optional explicit model catalog for reports that do not configure provider clients.
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
- "name": "@jsb188/llm-router",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@jsb188/llm-router",
3
+ "version": "1.1.13",
4
+ "description": "Shared LLM routing utilities.",
5
+ "license": "MIT",
6
+ "author": "jsb188",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": "./src/main.ts",
10
+ "./main.ts": "./src/main.ts",
11
+ "./types.ts": "./src/types.ts",
12
+ "./registry.ts": "./src/registry.ts",
13
+ "./trace.ts": "./src/trace.ts",
14
+ "./zod.ts": "./src/zod.ts",
15
+ "./router.ts": "./src/router.ts",
16
+ "./router.helpers.ts": "./src/router.helpers.ts",
17
+ "./capabilities.ts": "./src/capabilities.ts",
18
+ "./classifier.ts": "./src/classifier.ts",
19
+ "./policy/models.ts": "./src/policy/models.ts",
20
+ "./policy/reasoning.ts": "./src/policy/reasoning.ts",
21
+ "./policy/tasks.ts": "./src/policy/tasks.ts",
22
+ "./providers/_provider.ts": "./src/providers/_provider.ts",
23
+ "./providers/openai.ts": "./src/providers/openai.ts",
24
+ "./providers/deepseek.ts": "./src/providers/deepseek.ts",
25
+ "./providers/anthropic.ts": "./src/providers/anthropic.ts",
26
+ "./operations/responses.ts": "./src/operations/responses.ts",
27
+ "./operations/responses.helpers.ts": "./src/operations/responses.helpers.ts",
28
+ "./operations/decisions.ts": "./src/operations/decisions.ts",
29
+ "./operations/embeddings.ts": "./src/operations/embeddings.ts",
30
+ "./operations/moderation.ts": "./src/operations/moderation.ts",
31
+ "./operations/transcription.ts": "./src/operations/transcription.ts",
32
+ "./operations/files.ts": "./src/operations/files.ts",
33
+ "./utils/errors.ts": "./src/utils/errors.ts",
34
+ "./utils/promptCache.ts": "./src/utils/promptCache.ts",
35
+ "./utils/responseFormat.ts": "./src/utils/responseFormat.ts",
36
+ "./utils/responseItems.ts": "./src/utils/responseItems.ts"
37
+ },
38
+ "peerDependencies": {
39
+ "openai": "7.59.0",
40
+ "zod": "^3.25 || ^4.0"
41
+ },
42
+ "scripts": {
43
+ "typecheck": "tsc --project ./tsconfig.json",
44
+ "test": "node --test tests/*.test.ts"
45
+ },
46
+ "devDependencies": {
47
+ "openai": "7.59.0",
48
+ "typescript": "^7.0.2",
49
+ "zod": "^4.0"
50
+ },
51
+ "files": [
52
+ "src/**/*.ts",
53
+ "!**/*.test.*",
54
+ "!**/*.spec.*",
55
+ "!**/tests/**",
56
+ "!**/*.md",
57
+ "!**/.DS_Store"
58
+ ],
59
+ "dependencies": {
60
+ "@anthropic-ai/sdk": "^1.10.0"
61
+ }
62
+ }
@@ -0,0 +1,144 @@
1
+ import { getLLMModelEntry, mapCompatibleReasoningEffort } from './policy/models.ts';
2
+ import { getAnthropicRequestErrors } from './providers/anthropic.helpers.ts';
3
+ import { isAnthropicReasoningItem } from './providers/_provider.helpers.ts';
4
+ import type { LLM, LLMRoute } from './types.ts';
5
+
6
+ // The portable Responses core: anything not listed here is offending (the adapter strips the cache, store, service-tier
7
+ // and safety-identifier keys, text.verbosity and reasoning.summary, so they count as portable)
8
+ const FILE_CONSTANTS = {
9
+ portableKeys: new Set([
10
+ 'model',
11
+ 'input',
12
+ 'instructions',
13
+ 'stream',
14
+ 'max_output_tokens',
15
+ 'tools',
16
+ 'tool_choice',
17
+ 'text',
18
+ 'reasoning',
19
+ 'parallel_tool_calls',
20
+ 'prompt_cache_key',
21
+ 'prompt_cache_options',
22
+ 'store',
23
+ 'service_tier',
24
+ 'safety_identifier',
25
+ ]),
26
+ portableToolChoices: new Set(['none', 'auto', 'required']),
27
+ portableItemTypes: new Set(['message', 'function_call', 'function_call_output']),
28
+ portablePartTypes: new Set(['input_text', 'output_text', 'input_image', 'input_file']),
29
+ };
30
+
31
+ /* What one request uses beyond the portable Responses core; model-independent; computed from caller plus context params. */
32
+ export interface LLMRequestPortability {
33
+ imageInput: boolean; // an input_image part: the one extra a non-OpenAI model may serve
34
+ offending: string[]; // every other non-portable key, item or part, as a path ('include', 'input[3]:reasoning', 'tools[0]:namespace', ...)
35
+ anthropicOffending?: string[]; // Native Messages has a different supported subset than DeepSeek Responses.
36
+ anthropicForRoute?: (route: LLMRoute) => string[]; // Check model-specific thinking/tool constraints after choosing a route.
37
+ }
38
+
39
+ /* The offending label of a structured-output format: a raw json_schema (or one sent through create) cannot be guarded with zod. */
40
+ function getTextFormatLabel(format: unknown, method: 'create' | 'parse'): string | null {
41
+ const textFormat = format as { type?: unknown; $parseRaw?: unknown } | null | undefined;
42
+ if (!textFormat || textFormat.type === 'text') return null;
43
+ if (textFormat.type !== 'json_schema') return `text.format:${String(textFormat.type)}`;
44
+ return method === 'parse' && typeof textFormat.$parseRaw === 'function' ? null : 'text.format:json_schema';
45
+ }
46
+
47
+ /* The offending label of a tool_choice: anything but none, auto, required or one named function. */
48
+ function getToolChoiceLabel(toolChoice: unknown): string | null {
49
+ if (toolChoice === undefined || toolChoice === null) return null;
50
+ if (typeof toolChoice === 'string') return FILE_CONSTANTS.portableToolChoices.has(toolChoice) ? null : `tool_choice:${toolChoice}`;
51
+ const choice = toolChoice as { type?: unknown; name?: unknown };
52
+ return choice.type === 'function' && typeof choice.name === 'string' ? null : `tool_choice:${String(choice.type)}`;
53
+ }
54
+
55
+ /* The offending labels of the top-level keys: keys outside the portable core, parallel_tool_calls false, the text format and the tool choice. */
56
+ function getTopLevelOffending(params: Partial<LLM.RequestParams>, method: 'create' | 'parse'): string[] {
57
+ const offending = Object.entries(params)
58
+ .filter(([key, value]) => value !== undefined && !FILE_CONSTANTS.portableKeys.has(key))
59
+ .map(([key]) => key);
60
+ // DeepSeek always runs tool calls in parallel
61
+ if (params.parallel_tool_calls === false) offending.push('parallel_tool_calls:false');
62
+ const formatLabel = getTextFormatLabel(params.text?.format, method);
63
+ if (formatLabel) offending.push(formatLabel);
64
+ const toolChoiceLabel = getToolChoiceLabel(params.tool_choice);
65
+ if (toolChoiceLabel) offending.push(toolChoiceLabel);
66
+ return offending;
67
+ }
68
+
69
+ /* The offending labels of the tools: every tool that is not a function, and every function with defer_loading. */
70
+ function getToolsOffending(tools: unknown): string[] {
71
+ if (!Array.isArray(tools)) return [];
72
+ return tools.flatMap((tool, index) => {
73
+ const entry = tool as { type?: unknown; defer_loading?: unknown } | null;
74
+ if (entry?.type !== 'function') return [`tools[${index}]:${String(entry?.type)}`];
75
+ return entry.defer_loading ? [`tools[${index}]:defer_loading`] : [];
76
+ });
77
+ }
78
+
79
+ /* Walk one content-part array (message content or function_call_output output) into the portability result; strings are skipped. */
80
+ function addContentPartsPortability(parts: unknown, path: string, result: LLMRequestPortability): void {
81
+ if (!Array.isArray(parts)) return;
82
+ parts.forEach((part, index) => {
83
+ const entry = part as { type?: unknown; file_id?: unknown } | null;
84
+ if (entry?.file_id != null) result.offending.push(`${path}[${index}]:file_id`);
85
+ if (entry?.type === 'input_image') result.imageInput = true;
86
+ else if (entry?.type === 'input_file') result.offending.push(`${path}[${index}]:input_file`);
87
+ else if (!FILE_CONSTANTS.portablePartTypes.has(entry?.type as string)) {
88
+ result.offending.push(`${path}[${index}]:${String(entry?.type)}`);
89
+ }
90
+ });
91
+ }
92
+
93
+ /* Walk the input items into the portability result: only messages, function calls and their outputs are portable. */
94
+ function addInputPortability(input: unknown, result: LLMRequestPortability): void {
95
+ if (!Array.isArray(input)) return;
96
+ input.forEach((item, index) => {
97
+ if (isAnthropicReasoningItem(item)) return; // Other provider adapters remove this opaque replay state.
98
+ const entry = item as { type?: unknown; role?: unknown; content?: unknown; output?: unknown } | null;
99
+ // An easy message carries a role and no type
100
+ const type = entry?.type ?? (entry?.role !== undefined ? 'message' : undefined);
101
+ if (!FILE_CONSTANTS.portableItemTypes.has(type as string)) {
102
+ result.offending.push(`input[${index}]:${String(type)}`);
103
+ return;
104
+ }
105
+ if (type === 'message') addContentPartsPortability(entry!.content, `input[${index}].content`, result);
106
+ if (type === 'function_call_output') addContentPartsPortability(entry!.output, `input[${index}].output`, result);
107
+ });
108
+ }
109
+
110
+ /* Whether one request is portable, and what it uses beyond the portable core (an allow-list: anything unknown is offending). */
111
+ export function getLLMRequestPortability(params: Partial<LLM.RequestParams>, method: 'create' | 'parse'): LLMRequestPortability {
112
+ const result: LLMRequestPortability = {
113
+ imageInput: false,
114
+ offending: [...getTopLevelOffending(params, method), ...getToolsOffending(params.tools)],
115
+ };
116
+ addInputPortability(params.input, result);
117
+ // Keep the original enumerable portability report stable for existing diagnostics and snapshots.
118
+ Object.defineProperty(result, 'anthropicOffending', { value: getAnthropicRequestErrors(params, method) });
119
+ Object.defineProperty(result, 'anthropicForRoute', {
120
+ value: (route: LLMRoute) => {
121
+ try {
122
+ const effort = mapCompatibleReasoningEffort(route.model, route.effort, route.provider);
123
+ return getAnthropicRequestErrors({ ...params, model: route.model, reasoning: { ...params.reasoning, effort } }, method);
124
+ } catch (error) {
125
+ return [error instanceof Error ? error.message : String(error)];
126
+ }
127
+ },
128
+ });
129
+ return result;
130
+ }
131
+
132
+ /* Return the unsupported features for a specific provider; old reports retain their conservative defaults. */
133
+ export function getLLMRouteOffending(route: LLMRoute, portability: LLMRequestPortability): string[] {
134
+ return route.provider === 'anthropic'
135
+ ? portability.anthropicForRoute?.(route) ?? portability.anthropicOffending ?? portability.offending
136
+ : portability.offending;
137
+ }
138
+
139
+ /* Whether a route can serve a request: any OpenAI model; another provider's model only when nothing is offending and, for images, its entry has imageInput (unknown models: no). */
140
+ export function routeServesRequest(route: LLMRoute, portability: LLMRequestPortability): boolean {
141
+ if (route.provider === 'openai') return true;
142
+ if (getLLMRouteOffending(route, portability).length) return false;
143
+ return !portability.imageInput || !!getLLMModelEntry(route.model)?.imageInput;
144
+ }
@@ -0,0 +1,126 @@
1
+ import type { LLM, LLMRoute } from './types.ts';
2
+
3
+ // A single choice answer from the provider's Decisions endpoint.
4
+ type LLMChoiceAnswer = Extract<LLM.Decision['answers'][number], { type: 'choice' }>;
5
+
6
+ export interface LLMClassifierChoice {
7
+ value: string;
8
+ description?: string;
9
+ route: LLMRoute;
10
+ }
11
+
12
+ export interface LLMClassifierCandidate extends LLMClassifierChoice {
13
+ probability: number;
14
+ }
15
+
16
+ // The application owns the vocabulary, uncertainty fallback and selection strategy.
17
+ export interface LLMClassifierConfig {
18
+ instructions: string;
19
+ choices: readonly LLMClassifierChoice[];
20
+ fallback: LLMRoute;
21
+ minProbability?: number;
22
+ // Receives only configured choices with valid probabilities at or above the threshold.
23
+ select?: (candidates: readonly LLMClassifierCandidate[]) => string | null;
24
+ }
25
+
26
+ export interface LLMClassification {
27
+ route: LLMRoute;
28
+ category: string | null;
29
+ probabilities: Readonly<Record<string, number>>;
30
+ reason: 'single_route' | 'classified' | 'refusal' | 'no_answer' | 'no_match';
31
+ }
32
+
33
+ // The app supplies its tracked executor, including model, billing attribution, deadline and retries.
34
+ export type LLMClassifierExecutor = (params: LLM.DecisionInputParams) => Promise<Pick<LLM.Decision, 'answers'> | null>;
35
+
36
+ /* Read valid choice probabilities; duplicate entries are ignored rather than selecting arbitrary values. */
37
+ export function getChoiceAnswerProbabilities(answer: LLMChoiceAnswer): Map<string, number> {
38
+ const probabilities = new Map<string, number>();
39
+ const duplicates = new Set<string>();
40
+ for (const item of Array.isArray(answer.probabilities) ? answer.probabilities : []) {
41
+ if (typeof item?.value !== 'string' || !Number.isFinite(item.probability) || item.probability < 0 || item.probability > 1) {
42
+ continue;
43
+ }
44
+ if (probabilities.has(item.value)) duplicates.add(item.value);
45
+ probabilities.set(item.value, item.probability);
46
+ }
47
+ for (const value of duplicates) probabilities.delete(value);
48
+ return probabilities;
49
+ }
50
+
51
+ /* Reject unusable classifier definitions before any provider request is made. */
52
+ export function validateLLMClassifierConfig(config: LLMClassifierConfig): void {
53
+ if (!config.instructions.trim()) throw new Error('LLM classifier instructions must not be empty.');
54
+ if (!config.choices.length) throw new Error('LLM classifier must define at least one choice.');
55
+ const threshold = config.minProbability ?? 0;
56
+ if (!Number.isFinite(threshold) || threshold < 0 || threshold > 1) {
57
+ throw new Error('LLM classifier minProbability must be between 0 and 1.');
58
+ }
59
+ const values = new Set<string>();
60
+ for (const choice of config.choices) {
61
+ if (!choice.value.trim() || values.has(choice.value)) throw new Error('LLM classifier choice values must be nonempty and unique.');
62
+ values.add(choice.value);
63
+ }
64
+ }
65
+
66
+ /* Compare the full execution route, so effort or verbosity differences still require classification. */
67
+ function isSameClassifierRoute(a: LLMRoute, b: LLMRoute): boolean {
68
+ return a.provider === b.provider && a.model === b.model && a.effort === b.effort && a.verbosity === b.verbosity;
69
+ }
70
+
71
+ /* Select the highest-probability candidate; configuration order breaks ties. */
72
+ function selectMostLikelyCandidate(candidates: readonly LLMClassifierCandidate[]): string | null {
73
+ let selected: LLMClassifierCandidate | undefined;
74
+ for (const candidate of candidates) {
75
+ if (!selected || candidate.probability > selected.probability) selected = candidate;
76
+ }
77
+ return selected?.value ?? null;
78
+ }
79
+
80
+ /* Interpret one named answer, accepting only configured choices and retaining the explicit uncertainty fallback. */
81
+ function readLLMClassification(config: LLMClassifierConfig, decision: Pick<LLM.Decision, 'answers'> | null): LLMClassification {
82
+ const answers = (Array.isArray(decision?.answers) ? decision.answers : []).filter((answer) => answer?.name === 'route');
83
+ const answer = answers.length === 1 ? answers[0] : null;
84
+ const fallback: LLMClassification = { route: config.fallback, category: null, probabilities: {}, reason: 'no_answer' };
85
+ if (answer?.type === 'refusal') return { ...fallback, reason: 'refusal' };
86
+ if (answer?.type !== 'choice') return fallback;
87
+ const listed = getChoiceAnswerProbabilities(answer);
88
+ const candidates = config.choices.flatMap((choice) => {
89
+ const probability = listed.get(choice.value);
90
+ return probability === undefined ? [] : [{ ...choice, probability }];
91
+ });
92
+ const probabilities = Object.fromEntries(candidates.map(({ value, probability }) => [value, probability]));
93
+ const eligible = candidates.filter(({ probability }) => probability >= (config.minProbability ?? 0));
94
+ const value = (config.select ?? selectMostLikelyCandidate)(eligible);
95
+ const selected = eligible.find((candidate) => candidate.value === value);
96
+ return selected
97
+ ? { route: selected.route, category: selected.value, probabilities, reason: 'classified' }
98
+ : { ...fallback, probabilities, reason: 'no_match' };
99
+ }
100
+
101
+ /*
102
+ * Classify application-supplied input once. Identical candidate routes skip the provider entirely. Transport errors
103
+ * propagate to the application; refusals or unusable answers select its configured fallback. This helper never
104
+ * persists results or starts background requests.
105
+ */
106
+ export async function classifyLLMRoute(
107
+ config: LLMClassifierConfig,
108
+ input: LLM.DecisionInputParams['input'],
109
+ execute: LLMClassifierExecutor,
110
+ ): Promise<LLMClassification> {
111
+ validateLLMClassifierConfig(config);
112
+ const route = config.choices[0].route;
113
+ if (config.choices.every((choice) => isSameClassifierRoute(route, choice.route))) {
114
+ return { route, category: null, probabilities: {}, reason: 'single_route' };
115
+ }
116
+ const decision = await execute({
117
+ input,
118
+ questions: [{
119
+ type: 'choice',
120
+ name: 'route',
121
+ instructions: config.instructions,
122
+ choices: config.choices.map(({ value, description }) => ({ value, ...(description ? { description } : {}) })),
123
+ }],
124
+ });
125
+ return readLLMClassification(config, decision);
126
+ }
package/src/config.ts ADDED
@@ -0,0 +1,38 @@
1
+ import type { LLMRequestObserver, LLMRetryConfig, LLMRouterConfig, LLMTraceLogger } from './types.ts';
2
+
3
+ let activeConfig: LLMRouterConfig | null = null;
4
+
5
+ /*
6
+ * Publish the validated configuration after all provider clients are ready.
7
+ */
8
+ export function setLLMRouterConfig(config: LLMRouterConfig): void {
9
+ activeConfig = config;
10
+ }
11
+
12
+ /*
13
+ * Read the configuration when built-in model policies can be used before setup.
14
+ */
15
+ export function getOptionalLLMRouterConfig(): LLMRouterConfig | null {
16
+ return activeConfig;
17
+ }
18
+
19
+ /* Return the application's registration, failing clearly before startup configuration. */
20
+ export function getLLMRouterConfig(): LLMRouterConfig {
21
+ if (!activeConfig) throw new Error('LLM router is not configured. Call configureLLMRouter at startup.');
22
+ return activeConfig;
23
+ }
24
+
25
+ /* Return the registered request observer, or null before configuration. */
26
+ export function getLLMRequestObserver(): LLMRequestObserver | null {
27
+ return activeConfig?.observer ?? null;
28
+ }
29
+
30
+ /* Return the registered trace logger, or null before configuration. */
31
+ export function getLLMTraceLogger(): LLMTraceLogger | null {
32
+ return activeConfig?.traceLogger ?? null;
33
+ }
34
+
35
+ /* Retry settings are optional; transport helpers can use their defaults before registration. */
36
+ export function getLLMRetryConfig(): LLMRetryConfig {
37
+ return activeConfig?.retries ?? {};
38
+ }
package/src/main.ts ADDED
@@ -0,0 +1,25 @@
1
+ export { configureLLMRouter, createLLMProviderClient, getLLMRouterConfig } from './registry.ts';
2
+ export { buildResponseParams, createJSONResponse, createResponse } from './operations/responses.ts';
3
+ export { getResponseSDKRetries } from './operations/responses.helpers.ts';
4
+ export { createDecision } from './operations/decisions.ts';
5
+ export { createEmbeddings } from './operations/embeddings.ts';
6
+ export { createModeration } from './operations/moderation.ts';
7
+ export { createTranscription } from './operations/transcription.ts';
8
+ export { files } from './operations/files.ts';
9
+ export { getLLMTaskPolicy, isLLMRouteAllowed, makeLLMRouteDecision, resolveLLMTaskRoute } from './router.ts';
10
+ export {
11
+ chooseLLMPinnedRoute,
12
+ compareLLMRouteStrength,
13
+ isLLMPinFresh,
14
+ isLLMPinHeld,
15
+ makeLLMPin,
16
+ parseLLMPin,
17
+ parseLLMStoredRoute,
18
+ reuseRecoveredLLMRoute,
19
+ } from './router.helpers.ts';
20
+ export { classifyLLMRoute, getChoiceAnswerProbabilities, validateLLMClassifierConfig } from './classifier.ts';
21
+ export type { LLMClassification, LLMClassifierChoice, LLMClassifierConfig, LLMClassifierExecutor } from './classifier.ts';
22
+ export type { LLMOperationDefaults, LLMRouterConfig, LLMRoutingConfig } from './types.ts';
23
+ export { getResolvedModelReasoningPolicy, mapCompatibleReasoningEffort } from './policy/models.ts';
24
+ export { getModelReasoningPolicy, LLM_REASONING_EFFORTS, resolveReasoningEffort } from './policy/reasoning.ts';
25
+ export type { LLMReasoningPolicy } from './policy/reasoning.ts';
@@ -0,0 +1,14 @@
1
+ import { getLLMProviderClient, getLLMRouterConfig } from '../registry.ts';
2
+ import type { LLM, LLMDecisionResult } from '../types.ts';
3
+
4
+ /* Evaluate questions on the registered Decisions model and retain the provider request id. */
5
+ export async function createDecision(
6
+ params: LLM.DecisionInputParams,
7
+ requestOptions?: LLM.RequestOptions,
8
+ ): Promise<LLMDecisionResult> {
9
+ const request = { model: getLLMRouterConfig().defaults.decisionsModel, ...params };
10
+ // Registration is authoritative even when an untyped caller supplies a model.
11
+ request.model = getLLMRouterConfig().defaults.decisionsModel;
12
+ const { data, request_id } = await getLLMProviderClient('openai').decisions.create(request, requestOptions).withResponse();
13
+ return { data, requestId: request_id };
14
+ }
@@ -0,0 +1,11 @@
1
+ import { getLLMProviderClient, getLLMRouterConfig } from '../registry.ts';
2
+
3
+ /* Create embeddings for one text or a batch of texts (raw provider result; items carry their input index). */
4
+ export function createEmbeddings(text: string | string[]) {
5
+ return getLLMProviderClient('openai').embeddings.create({
6
+ model: getLLMRouterConfig().defaults.embedding.model,
7
+ encoding_format: 'float',
8
+ dimensions: getLLMRouterConfig().defaults.embedding.dimensions,
9
+ input: Array.isArray(text) ? text : [text],
10
+ });
11
+ }