@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.
@@ -0,0 +1,299 @@
1
+ import type Anthropic from '@anthropic-ai/sdk';
2
+ import { APIUserAbortError } from '@anthropic-ai/sdk';
3
+ import type { LLM } from '../types.ts';
4
+ import { fromAnthropicContentBlock, fromAnthropicMessage } from './anthropic.helpers.ts';
5
+ import { makeAnthropicResponseItemId } from './_provider.helpers.ts';
6
+
7
+ type SupportedBlock = Anthropic.TextBlock | Anthropic.ToolUseBlock | Anthropic.ThinkingBlock | Anthropic.RedactedThinkingBlock;
8
+ type UnsequencedEvent<T = LLM.StreamEvent> = T extends LLM.StreamEvent ? Omit<T, 'sequence_number'> : never;
9
+
10
+ interface StreamBlock {
11
+ block: SupportedBlock;
12
+ arguments: string;
13
+ stopped: boolean;
14
+ }
15
+
16
+ interface StreamState {
17
+ message: Anthropic.Message | null;
18
+ blocks: StreamBlock[];
19
+ sequence: number;
20
+ createdAt: number;
21
+ }
22
+
23
+ /* Add a monotonic sequence number to one normalized stream event. */
24
+ function sequenceEvent(state: StreamState, event: UnsequencedEvent): LLM.StreamEvent {
25
+ return { ...event, sequence_number: state.sequence++ } as LLM.StreamEvent;
26
+ }
27
+
28
+ /* Require the message header before any content or usage update is accepted. */
29
+ function requireMessage(state: StreamState): Anthropic.Message {
30
+ if (!state.message) throw new Error('Anthropic stream received content before message_start.');
31
+ return state.message;
32
+ }
33
+
34
+ /* Require an existing, unfinished content block for its next update. */
35
+ function requireBlock(state: StreamState, index: number): StreamBlock {
36
+ requireMessage(state);
37
+ const block = state.blocks[index];
38
+ if (!block || block.stopped) throw new Error(`Anthropic stream received an invalid content block index: ${index}.`);
39
+ return block;
40
+ }
41
+
42
+ /* Build a normalized snapshot without sharing mutable content with yielded events. */
43
+ function responseSnapshot(state: StreamState, params: LLM.RequestParams, inProgress: boolean): LLM.Response {
44
+ const response = fromAnthropicMessage(requireMessage(state), params);
45
+ return {
46
+ ...response,
47
+ created_at: state.createdAt,
48
+ ...(inProgress ? { status: 'in_progress' as const, incomplete_details: null, error: null } : {}),
49
+ output: response.output.map((item, index) => {
50
+ const status = inProgress ? 'in_progress' : response.status === 'completed' ? 'completed' : 'incomplete';
51
+ if (item.type === 'function_call') {
52
+ const block = state.blocks[index];
53
+ return { ...item, status, arguments: block?.arguments || item.arguments };
54
+ }
55
+ return item.type === 'message' || item.type === 'reasoning' ? { ...item, status } : item;
56
+ }),
57
+ };
58
+ }
59
+
60
+ /* Start text, reasoning or function output while retaining its provider block identity and original order. */
61
+ function startBlock(state: StreamState, event: Anthropic.RawContentBlockStartEvent): UnsequencedEvent[] {
62
+ const message = requireMessage(state);
63
+ if (event.index !== state.blocks.length || state.blocks.some((entry) => !entry.stopped)) {
64
+ throw new Error('Anthropic stream started an out-of-order content block.');
65
+ }
66
+ if (
67
+ event.content_block.type !== 'text' && event.content_block.type !== 'tool_use' &&
68
+ event.content_block.type !== 'thinking' && event.content_block.type !== 'redacted_thinking'
69
+ ) {
70
+ throw new Error(`Unsupported Anthropic stream content: ${event.content_block.type}.`);
71
+ }
72
+ const block = structuredClone(event.content_block);
73
+ state.blocks.push({ block, arguments: '', stopped: false });
74
+ message.content.push(block);
75
+ const item = fromAnthropicContentBlock(block, message.id, event.index);
76
+ if (item.type === 'function_call') {
77
+ return [{
78
+ type: 'response.output_item.added',
79
+ output_index: event.index,
80
+ item: { ...item, status: 'in_progress', arguments: '' },
81
+ }];
82
+ }
83
+ if (item.type === 'reasoning') {
84
+ const events: UnsequencedEvent[] = [{
85
+ type: 'response.output_item.added',
86
+ output_index: event.index,
87
+ item: { ...item, status: 'in_progress', summary: [], encrypted_content: null },
88
+ }];
89
+ if (block.type === 'thinking') {
90
+ events.push({
91
+ type: 'response.reasoning_summary_part.added',
92
+ output_index: event.index,
93
+ item_id: item.id,
94
+ summary_index: 0,
95
+ part: { type: 'summary_text', text: '' },
96
+ });
97
+ if (block.thinking) {
98
+ events.push({
99
+ type: 'response.reasoning_summary_text.delta',
100
+ output_index: event.index,
101
+ item_id: item.id,
102
+ summary_index: 0,
103
+ delta: block.thinking,
104
+ });
105
+ }
106
+ }
107
+ return events;
108
+ }
109
+ if (item.type !== 'message') throw new Error('Unexpected normalized Anthropic content block.');
110
+ const events: UnsequencedEvent[] = [
111
+ { type: 'response.output_item.added', output_index: event.index, item: { ...item, status: 'in_progress', content: [] } },
112
+ {
113
+ type: 'response.content_part.added',
114
+ output_index: event.index,
115
+ item_id: item.id,
116
+ content_index: 0,
117
+ part: { type: 'output_text', text: '', annotations: [] },
118
+ },
119
+ ];
120
+ if (block.type === 'text' && block.text) {
121
+ events.push({
122
+ type: 'response.output_text.delta',
123
+ output_index: event.index,
124
+ item_id: item.id,
125
+ content_index: 0,
126
+ delta: block.text,
127
+ logprobs: [],
128
+ });
129
+ }
130
+ return events;
131
+ }
132
+
133
+ /* Accumulate text, JSON and signed thinking fragments, exposing only public summary text in reasoning events. */
134
+ function updateBlock(state: StreamState, event: Anthropic.RawContentBlockDeltaEvent): UnsequencedEvent | null {
135
+ const entry = requireBlock(state, event.index);
136
+ const itemId = makeAnthropicResponseItemId(requireMessage(state).id, event.index);
137
+ if (event.delta.type === 'text_delta' && entry.block.type === 'text') {
138
+ entry.block.text += event.delta.text;
139
+ return {
140
+ type: 'response.output_text.delta',
141
+ item_id: itemId,
142
+ output_index: event.index,
143
+ content_index: 0,
144
+ delta: event.delta.text,
145
+ logprobs: [],
146
+ };
147
+ }
148
+ if (event.delta.type === 'input_json_delta' && entry.block.type === 'tool_use') {
149
+ entry.arguments += event.delta.partial_json;
150
+ return {
151
+ type: 'response.function_call_arguments.delta',
152
+ item_id: itemId,
153
+ output_index: event.index,
154
+ delta: event.delta.partial_json,
155
+ };
156
+ }
157
+ if (event.delta.type === 'thinking_delta' && entry.block.type === 'thinking') {
158
+ if (entry.block.signature) throw new Error('Anthropic thinking text arrived after its signature.');
159
+ entry.block.thinking += event.delta.thinking;
160
+ return {
161
+ type: 'response.reasoning_summary_text.delta',
162
+ item_id: itemId,
163
+ output_index: event.index,
164
+ summary_index: 0,
165
+ delta: event.delta.thinking,
166
+ };
167
+ }
168
+ if (event.delta.type === 'signature_delta' && entry.block.type === 'thinking') {
169
+ entry.block.signature += event.delta.signature;
170
+ return null;
171
+ }
172
+ throw new Error(`Unsupported Anthropic stream delta: ${event.delta.type}.`);
173
+ }
174
+
175
+ /* Validate completed tool JSON before exposing callable output items. */
176
+ function completeMessage(state: StreamState, params: LLM.RequestParams): LLM.Response {
177
+ const message = requireMessage(state);
178
+ if (!message.stop_reason || state.blocks.some((entry) => !entry.stopped)) {
179
+ throw new Error('Anthropic stream ended before its content and stop reason were complete.');
180
+ }
181
+ const complete = message.stop_reason === 'end_turn' || message.stop_reason === 'tool_use' || message.stop_reason === 'stop_sequence';
182
+ for (const entry of state.blocks) {
183
+ if (entry.block.type !== 'tool_use' || !entry.arguments) continue;
184
+ try {
185
+ const input: unknown = JSON.parse(entry.arguments);
186
+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error('Expected a tool argument object.');
187
+ entry.block.input = input;
188
+ } catch (error) {
189
+ // Truncated tool JSON remains visible on an incomplete response, never as an executable completed call.
190
+ if (complete) throw new Error('Anthropic stream returned invalid tool arguments.', { cause: error });
191
+ }
192
+ }
193
+ return responseSnapshot(state, params, false);
194
+ }
195
+
196
+ /* Finish output events only after the provider confirms message completion. */
197
+ function finishOutput(response: LLM.Response): UnsequencedEvent[] {
198
+ return response.output.flatMap((item, output_index): UnsequencedEvent[] => {
199
+ const events: UnsequencedEvent[] = [];
200
+ if (item.type === 'message') {
201
+ item.content.forEach((part, content_index) => {
202
+ if (part.type === 'output_text') {
203
+ events.push({
204
+ type: 'response.output_text.done',
205
+ output_index,
206
+ item_id: item.id,
207
+ content_index,
208
+ text: part.text,
209
+ logprobs: [],
210
+ });
211
+ } else {
212
+ events.push({ type: 'response.refusal.done', output_index, item_id: item.id, content_index, refusal: part.refusal });
213
+ }
214
+ events.push({ type: 'response.content_part.done', output_index, item_id: item.id, content_index, part });
215
+ });
216
+ } else if (item.type === 'function_call') {
217
+ events.push({ type: 'response.function_call_arguments.done', output_index, item_id: item.id!, arguments: item.arguments });
218
+ } else if (item.type === 'reasoning') {
219
+ item.summary.forEach((part, summary_index) => {
220
+ events.push({
221
+ type: 'response.reasoning_summary_text.done',
222
+ output_index,
223
+ item_id: item.id,
224
+ summary_index,
225
+ text: part.text,
226
+ });
227
+ events.push({
228
+ type: 'response.reasoning_summary_part.done',
229
+ output_index,
230
+ item_id: item.id,
231
+ summary_index,
232
+ part,
233
+ ...(item.status === 'incomplete' ? { status: 'incomplete' } : {}),
234
+ });
235
+ });
236
+ }
237
+ events.push({ type: 'response.output_item.done', output_index, item });
238
+ return events;
239
+ });
240
+ }
241
+
242
+ /* Translate native Messages SSE events and reject interrupted or unsupported streams. */
243
+ async function* iterateAnthropicStream(
244
+ stream: AsyncIterable<Anthropic.RawMessageStreamEvent>,
245
+ params: LLM.RequestParams,
246
+ ): AsyncGenerator<LLM.StreamEvent> {
247
+ const state: StreamState = { message: null, blocks: [], sequence: 0, createdAt: Math.floor(Date.now() / 1000) };
248
+ for await (const event of stream) {
249
+ if (event.type === 'message_start') {
250
+ if (state.message || event.message.content.length) throw new Error('Anthropic stream returned an invalid message_start.');
251
+ state.message = structuredClone(event.message);
252
+ const response = responseSnapshot(state, params, true);
253
+ yield sequenceEvent(state, { type: 'response.created', response });
254
+ yield sequenceEvent(state, { type: 'response.in_progress', response });
255
+ } else if (event.type === 'content_block_start') {
256
+ for (const normalized of startBlock(state, event)) yield sequenceEvent(state, normalized);
257
+ } else if (event.type === 'content_block_delta') {
258
+ const normalized = updateBlock(state, event);
259
+ if (normalized) yield sequenceEvent(state, normalized);
260
+ } else if (event.type === 'content_block_stop') {
261
+ requireBlock(state, event.index).stopped = true;
262
+ } else if (event.type === 'message_delta') {
263
+ const message = requireMessage(state);
264
+ message.stop_reason = event.delta.stop_reason;
265
+ message.stop_sequence = event.delta.stop_sequence;
266
+ // Usage deltas are cumulative; retain initial input/cache counts when a later delta omits them.
267
+ message.usage = { ...message.usage, ...Object.fromEntries(Object.entries(event.usage).filter(([, value]) => value != null)) };
268
+ } else if (event.type === 'message_stop') {
269
+ const response = completeMessage(state, params);
270
+ for (const normalized of finishOutput(response)) yield sequenceEvent(state, normalized);
271
+ const type = response.status === 'completed'
272
+ ? 'response.completed'
273
+ : response.status === 'failed'
274
+ ? 'response.failed'
275
+ : 'response.incomplete';
276
+ yield sequenceEvent(state, { type, response });
277
+ return;
278
+ } else {
279
+ throw new Error(`Unsupported Anthropic stream event: ${(event as { type: string }).type}.`);
280
+ }
281
+ }
282
+ if ((stream as { controller?: AbortController }).controller?.signal.aborted) throw new APIUserAbortError();
283
+ throw new Error('Anthropic stream ended without message_stop.');
284
+ }
285
+
286
+ /* Preserve SDK cancellation while exposing only the router's normalized stream events. */
287
+ export function normalizeAnthropicStream(
288
+ stream: AsyncIterable<Anthropic.RawMessageStreamEvent>,
289
+ params: LLM.RequestParams,
290
+ ): AsyncIterable<LLM.StreamEvent> {
291
+ const controller = (stream as { controller?: AbortController }).controller;
292
+ return {
293
+ ...(controller ? { controller } : {}),
294
+ /* Iteration owns cleanup through the native SDK iterator's return method. */
295
+ [Symbol.asyncIterator]() {
296
+ return iterateAnthropicStream(stream, params);
297
+ },
298
+ };
299
+ }
@@ -0,0 +1,63 @@
1
+ import Anthropic from '@anthropic-ai/sdk';
2
+ import process from 'node:process';
3
+ import type { LLM } from '../types.ts';
4
+ import { getPromptCacheParamNames, stripPromptCacheParams } from '../utils/promptCache.ts';
5
+ import type { LLMProviderAdapter } from './_provider.ts';
6
+ import { fromAnthropicMessage, toAnthropicParams } from './anthropic.helpers.ts';
7
+ import { normalizeAnthropicStream } from './anthropic.stream.ts';
8
+
9
+ export const anthropicProvider: LLMProviderAdapter<'anthropic'> = {
10
+ name: 'anthropic',
11
+ /* Build a native client only with the explicitly registered Anthropic credential. */
12
+ createClient(options) {
13
+ if (!options.apiKey) throw new Error('Anthropic API key is not set.');
14
+ if (process.env.ANTHROPIC_CUSTOM_HEADERS) throw new Error('ANTHROPIC_CUSTOM_HEADERS must be unset when using the LLM router.');
15
+ return new Anthropic({ ...options, baseURL: 'https://api.anthropic.com', authToken: null });
16
+ },
17
+ /* Remove OpenAI controls that have no equivalent in this adapter and record every omission. */
18
+ prepareParams(params) {
19
+ const strippedParams = getPromptCacheParamNames(params);
20
+ const next = { ...stripPromptCacheParams(params) };
21
+ for (const key of ['store', 'service_tier', 'safety_identifier'] as const) {
22
+ if (next[key] !== undefined) {
23
+ delete next[key];
24
+ strippedParams.push(key);
25
+ }
26
+ }
27
+ if (next.text?.verbosity !== undefined) {
28
+ const { verbosity: _verbosity, ...text } = next.text;
29
+ next.text = text;
30
+ strippedParams.push('text.verbosity');
31
+ }
32
+ return { params: next, strippedParams, mappedParams: ['responses->messages'] };
33
+ },
34
+ /* Native response conversion already supplies normalized input, cache and output usage. */
35
+ normalizeUsage(response) {
36
+ return response;
37
+ },
38
+ };
39
+
40
+ /* Translate one router request and preserve raw HTTP access for structured-response diagnostics. */
41
+ export function createAnthropicRequest(
42
+ client: Anthropic,
43
+ params: LLM.RequestParams,
44
+ options: Pick<LLM.RequestOptions, 'maxRetries' | 'timeout'>,
45
+ ) {
46
+ const request = client.messages.create(toAnthropicParams(params), options);
47
+ return {
48
+ /* Expose the native HTTP response before parsing so observers can capture malformed output. */
49
+ asResponse() {
50
+ return request.asResponse();
51
+ },
52
+ /* Normalize a native message or stream into the router's existing Responses contract. */
53
+ async withResponse() {
54
+ const { data, request_id } = await request.withResponse();
55
+ return {
56
+ request_id: request_id ?? null,
57
+ data: params.stream
58
+ ? normalizeAnthropicStream(data as AsyncIterable<Anthropic.RawMessageStreamEvent>, params)
59
+ : fromAnthropicMessage(data as Anthropic.Message, params),
60
+ };
61
+ },
62
+ };
63
+ }
@@ -0,0 +1,98 @@
1
+ import OpenAI from 'openai';
2
+ import type { LLM, LLMEffort } from '../types.ts';
3
+ import { getResolvedModelReasoningPolicy, mapCompatibleReasoningEffort } from '../policy/models.ts';
4
+ import { LLM_REASONING_EFFORTS } from '../policy/reasoning.ts';
5
+ import { getPromptCacheParamNames, stripPromptCacheParams } from '../utils/promptCache.ts';
6
+ import type { LLMProviderAdapter } from './_provider.ts';
7
+ import { stripAnthropicResponseItemIds } from './_provider.helpers.ts';
8
+
9
+ const FILE_CONSTANTS = {
10
+ baseURL: 'https://api.deepseek.com', // the probe confirms the /responses path; switch to .../v1 only if its base_path check fails
11
+ strippedKeys: ['store', 'include', 'service_tier', 'safety_identifier'] as const,
12
+ };
13
+
14
+ /* The DeepSeek effort of a router effort; an unset or unknown effort is high, so the effort sent is always explicit. */
15
+ function getDeepSeekEffort(model: string, effort: string | null | undefined): LLMEffort {
16
+ const requested = effort && LLM_REASONING_EFFORTS.includes(effort as LLMEffort) ? effort as LLMEffort : 'high';
17
+ return mapCompatibleReasoningEffort(model, requested, 'deepseek');
18
+ }
19
+
20
+ /* Whether an input item is a developer message (an easy message or type 'message'). */
21
+ function isDeveloperMessage(item: unknown): boolean {
22
+ const message = item as { role?: unknown; type?: unknown } | null;
23
+ return !!message && message.role === 'developer' && (message.type === undefined || message.type === 'message');
24
+ }
25
+
26
+ export const deepseekProvider: LLMProviderAdapter<'deepseek'> = {
27
+ name: 'deepseek',
28
+ /* Build an OpenAI SDK client on DeepSeek's base URL; never without an explicit key, never with the environment's OpenAI key, org, project or admin key. */
29
+ createClient(options) {
30
+ // The SDK falls back to OPENAI_API_KEY / OPENAI_ORG_ID / OPENAI_PROJECT_ID (and OPENAI_ADMIN_KEY) from the environment. It
31
+ // also sends the headers of OPENAI_CUSTOM_HEADERS, which this package cannot read: its callers (the server, the probe)
32
+ // refuse to build this client while that variable is set.
33
+ if (!options.apiKey) throw new Error('DeepSeek API key is not set.');
34
+ return new OpenAI({ ...options, baseURL: FILE_CONSTANTS.baseURL, organization: null, project: null, adminAPIKey: null });
35
+ },
36
+ /*
37
+ * Map complete router params to what DeepSeek honors, on shallow copies (the input is never mutated): drop the
38
+ * prompt cache params, store / include / service_tier / safety_identifier, text.verbosity and reasoning.summary; send
39
+ * the effort through the DeepSeek effort table, always explicit; send developer messages as system messages.
40
+ */
41
+ prepareParams(params) {
42
+ const strippedParams: string[] = [];
43
+ const mappedParams: string[] = [];
44
+ let base = params;
45
+ const promptCacheParams = getPromptCacheParamNames(params);
46
+ if (promptCacheParams.length) {
47
+ strippedParams.push(...promptCacheParams);
48
+ base = stripPromptCacheParams(params);
49
+ }
50
+ const next = { ...base } as LLM.RequestParams;
51
+ for (const key of FILE_CONSTANTS.strippedKeys) {
52
+ if (next[key] === undefined) continue;
53
+ delete next[key];
54
+ strippedParams.push(key);
55
+ }
56
+ if (next.text?.verbosity !== undefined) {
57
+ // The rest spread keeps the same text.format object reference ($parseRaw is non-enumerable on it)
58
+ const { verbosity: _verbosity, ...text } = next.text;
59
+ if (Object.keys(text).length) next.text = text;
60
+ else delete next.text;
61
+ strippedParams.push('text.verbosity');
62
+ }
63
+ if (next.reasoning?.summary !== undefined) strippedParams.push('reasoning.summary');
64
+ const fromEffort = next.reasoning?.effort ?? null;
65
+ if (!params.model) throw new Error('DeepSeek requests require a model to resolve reasoning capabilities.');
66
+ if (getResolvedModelReasoningPolicy(params.model, 'deepseek')?.omitReasoning) {
67
+ if (next.reasoning !== undefined) strippedParams.push('reasoning');
68
+ delete next.reasoning;
69
+ } else {
70
+ const toEffort = getDeepSeekEffort(params.model, fromEffort);
71
+ next.reasoning = { effort: toEffort };
72
+ if (fromEffort !== toEffort) mappedParams.push(`reasoning.effort:${fromEffort ?? 'unset'}->${toEffort}`);
73
+ }
74
+ if (Array.isArray(next.input) && next.input.some(isDeveloperMessage)) {
75
+ next.input = next.input.map((item) => (isDeveloperMessage(item) ? { ...item, role: 'system' } : item)) as LLM.Input;
76
+ mappedParams.push('role:developer->system');
77
+ }
78
+ const history = stripAnthropicResponseItemIds(next);
79
+ return { params: history.params, strippedParams, mappedParams: [...mappedParams, ...history.mappedParams] };
80
+ },
81
+ /* Fill the usage fields DeepSeek may omit (cached and reasoning tokens 0, total = input + output); the same response when none is missing. */
82
+ normalizeUsage(response) {
83
+ const usage = response.usage;
84
+ if (!usage) return response;
85
+ const cachedTokens = usage.input_tokens_details?.cached_tokens;
86
+ const reasoningTokens = usage.output_tokens_details?.reasoning_tokens;
87
+ if (cachedTokens != null && reasoningTokens != null && usage.total_tokens != null) return response;
88
+ return {
89
+ ...response,
90
+ usage: {
91
+ ...usage,
92
+ input_tokens_details: { ...usage.input_tokens_details, cached_tokens: cachedTokens ?? 0 },
93
+ output_tokens_details: { ...usage.output_tokens_details, reasoning_tokens: reasoningTokens ?? 0 },
94
+ total_tokens: usage.total_tokens ?? (Number(usage.input_tokens) || 0) + (Number(usage.output_tokens) || 0),
95
+ },
96
+ };
97
+ },
98
+ };
@@ -0,0 +1,20 @@
1
+ import OpenAI from 'openai';
2
+ import type { LLMProviderAdapter } from './_provider.ts';
3
+ import { stripAnthropicResponseItemIds } from './_provider.helpers.ts';
4
+
5
+ // Native OpenAI requests pass through unchanged; foreign local item IDs are removed from mixed history.
6
+ export const openaiProvider: LLMProviderAdapter<'openai'> = {
7
+ name: 'openai',
8
+ /* Build an OpenAI SDK client; the options object is passed through unchanged. */
9
+ createClient(options) {
10
+ return new OpenAI(options);
11
+ },
12
+ /* Preserve native request identity while omitting Anthropic's local receipt IDs from outbound history. */
13
+ prepareParams(params) {
14
+ return { ...stripAnthropicResponseItemIds(params), strippedParams: [] };
15
+ },
16
+ /* Return the same response: OpenAI usage is already in the Responses shape. */
17
+ normalizeUsage(response) {
18
+ return response;
19
+ },
20
+ };
@@ -0,0 +1,117 @@
1
+ import { validateLLMClassifierConfig } from './classifier.ts';
2
+ import { LLM_REASONING_EFFORTS, validateLLMReasoningPolicy } from './policy/reasoning.ts';
3
+ import type { LLMRouterConfig, LLMRouteSpec, LLMRoutingConfig } from './types.ts';
4
+
5
+ const FILE_CONSTANTS = {
6
+ providers: new Set(['openai', 'deepseek', 'anthropic']),
7
+ efforts: new Set(LLM_REASONING_EFFORTS),
8
+ verbosities: new Set(['low', 'medium', 'high']),
9
+ };
10
+
11
+ /* Reject malformed static routes before a configuration becomes active. */
12
+ export function validateLLMRouteSpec(route: LLMRouteSpec, routing: LLMRoutingConfig): void {
13
+ if (!route || typeof route !== 'object') throw new Error('An LLM route must be an object.');
14
+ if ((route.model === undefined) === (route.tier === undefined)) throw new Error('An LLM route must name exactly one model or tier.');
15
+ const model = route.model ?? (Object.hasOwn(routing.tiers, route.tier!) ? routing.tiers[route.tier!] : undefined);
16
+ if (!model || !Object.hasOwn(routing.models, model)) {
17
+ throw new Error(`Unknown LLM route model or tier: ${route.model ?? route.tier}.`);
18
+ }
19
+ if (!FILE_CONSTANTS.efforts.has(route.effort) || !FILE_CONSTANTS.verbosities.has(route.verbosity)) {
20
+ throw new Error('Invalid LLM route effort or verbosity.');
21
+ }
22
+ }
23
+
24
+ /* Validate a provider allow-list without requiring every permitted provider to be configured. */
25
+ function validateProviders(providers: readonly string[]): void {
26
+ if (!providers.length || providers.some((provider) => !FILE_CONSTANTS.providers.has(provider))) {
27
+ throw new Error('Invalid LLM provider allow-list.');
28
+ }
29
+ }
30
+
31
+ /* Validate the application's model catalog, tier references, fallbacks and operation defaults. */
32
+ function validateModels(config: LLMRouterConfig): void {
33
+ const { models, tiers, fallbackModel, pinning } = config.routing;
34
+ if (!models || !Object.keys(models).length) throw new Error('Register at least one LLM model.');
35
+ for (const [model, entry] of Object.entries(models)) {
36
+ if (
37
+ !model || !FILE_CONSTANTS.providers.has(entry.provider) || !Number.isFinite(entry.strength) ||
38
+ !Number.isFinite(entry.cacheLifetimeMS) || entry.cacheLifetimeMS < 0 || typeof entry.imageInput !== 'boolean'
39
+ ) throw new Error(`Invalid LLM model entry: ${model}.`);
40
+ if (entry.reasoning !== undefined) validateLLMReasoningPolicy(entry.reasoning, entry.provider, model);
41
+ const fallback = fallbackModel(model);
42
+ if (fallback !== null && (!Object.hasOwn(models, fallback) || fallback === model)) {
43
+ throw new Error(`Invalid LLM fallback for ${model}.`);
44
+ }
45
+ }
46
+ for (const [tier, model] of Object.entries(tiers)) {
47
+ if (!tier || !Object.hasOwn(models, model)) throw new Error(`Invalid LLM tier: ${tier}.`);
48
+ }
49
+ if (
50
+ pinning && [pinning.holdMS, pinning.maxClockSkewMS].some((value) => value !== undefined && (!Number.isFinite(value) || value < 0))
51
+ ) throw new Error('Invalid LLM pinning duration.');
52
+ const defaults = config.defaults;
53
+ if (
54
+ !defaults?.decisionsModel || !defaults.embedding?.model || !defaults.moderationModel || !defaults.transcriptionModel ||
55
+ !Number.isSafeInteger(defaults.embedding.dimensions) || defaults.embedding.dimensions <= 0
56
+ ) throw new Error('Invalid LLM operation defaults.');
57
+ }
58
+
59
+ /* Validate registration before creating clients or replacing the active configuration. */
60
+ export function validateLLMRouterConfig(config: LLMRouterConfig): void {
61
+ if (!config.routing || !config.routing.policies || typeof config.routing.fallbackModel !== 'function') {
62
+ throw new Error('LLM routing configuration is required.');
63
+ }
64
+ validateModels(config);
65
+ for (const [key, value] of Object.entries(config.retries ?? {})) {
66
+ if (key === 'crossProviderFallbackOnSingleAttempt') {
67
+ if (typeof value !== 'boolean') throw new Error('Invalid LLM retry fallback setting.');
68
+ } else if (!Number.isSafeInteger(value) || Number(value) < 0) throw new Error(`Invalid LLM retry setting: ${key}.`);
69
+ }
70
+ validateProviders(config.routing.defaultProviders ?? ['openai']);
71
+ for (const provider of Object.keys(config.providers)) {
72
+ if (!FILE_CONSTANTS.providers.has(provider)) throw new Error(`Unknown LLM provider: ${provider}.`);
73
+ }
74
+ for (const [task, policy] of Object.entries(config.routing.policies)) {
75
+ if (!task || !policy || !policy.route) throw new Error(`Invalid LLM task policy: ${task}.`);
76
+ validateProviders(policy.providers ?? config.routing.defaultProviders ?? ['openai']);
77
+ if (typeof policy.route !== 'function') validateLLMRouteSpec(policy.route, config.routing);
78
+ if (policy.fallback) validateLLMRouteSpec(policy.fallback, config.routing);
79
+ if (policy.classifier) {
80
+ validateLLMClassifierConfig(policy.classifier);
81
+ for (const route of [policy.classifier.fallback, ...policy.classifier.choices.map((choice) => choice.route)]) {
82
+ validateLLMRouteSpec({ model: route.model, effort: route.effort, verbosity: route.verbosity }, config.routing);
83
+ if (config.routing.models[route.model].provider !== route.provider) {
84
+ throw new Error(`Classifier route provider mismatch: ${task}.`);
85
+ }
86
+ }
87
+ }
88
+ if (policy.trial) {
89
+ validateLLMRouteSpec(policy.trial.route, config.routing);
90
+ if (!Array.isArray(policy.trial.organizationIds) || policy.trial.organizationIds.some((id) => typeof id !== 'string' || !id)) {
91
+ throw new Error(`Invalid LLM trial organizations: ${task}.`);
92
+ }
93
+ }
94
+ }
95
+ }
96
+
97
+ /* Copy and freeze declarative configuration while preserving executable policy callbacks. */
98
+ function freezeLLMConfigurationValue<T>(value: T): T {
99
+ if (Array.isArray(value)) return Object.freeze(value.map((item) => freezeLLMConfigurationValue(item))) as T;
100
+ if (value && typeof value === 'object') {
101
+ return Object.freeze(
102
+ Object.fromEntries(Object.entries(value).map(([key, item]) => [key, freezeLLMConfigurationValue(item)])),
103
+ ) as T;
104
+ }
105
+ return value;
106
+ }
107
+
108
+ /* Snapshot static registration; observer hooks retain their identity so application instrumentation stays live. */
109
+ export function snapshotLLMRouterConfig(config: LLMRouterConfig): LLMRouterConfig {
110
+ return Object.freeze({
111
+ ...config,
112
+ providers: freezeLLMConfigurationValue(config.providers),
113
+ routing: freezeLLMConfigurationValue(config.routing),
114
+ defaults: freezeLLMConfigurationValue(config.defaults),
115
+ retries: freezeLLMConfigurationValue(config.retries),
116
+ });
117
+ }
@@ -0,0 +1,56 @@
1
+ import { setLLMRouterConfig } from './config.ts';
2
+ import { snapshotLLMRouterConfig, validateLLMRouterConfig } from './registry.helpers.ts';
3
+ import type { LLMProviderAdapter } from './providers/_provider.ts';
4
+ import { deepseekProvider } from './providers/deepseek.ts';
5
+ import { openaiProvider } from './providers/openai.ts';
6
+ import { anthropicProvider } from './providers/anthropic.ts';
7
+ import type { LLMProviderClientOptions, LLMProviderClients, LLMProviderConfig, LLMProviderName, LLMRouterConfig } from './types.ts';
8
+
9
+ export { getLLMRouterConfig, getLLMRequestObserver, getLLMRetryConfig, getLLMTraceLogger } from './config.ts';
10
+
11
+ // Module state of the router: one instance per process
12
+ const FILE_CONSTANTS = {
13
+ adapters: { openai: openaiProvider, deepseek: deepseekProvider, anthropic: anthropicProvider } as {
14
+ [P in LLMProviderName]: LLMProviderAdapter<P>;
15
+ },
16
+ providers: {} as Partial<Record<LLMProviderName, LLMProviderConfig>>,
17
+ clients: {} as Partial<LLMProviderClients>,
18
+ };
19
+
20
+ /* Validate and install one complete registration; failures leave the previous router intact. */
21
+ export function configureLLMRouter(config: LLMRouterConfig): void {
22
+ const registered = snapshotLLMRouterConfig(config);
23
+ validateLLMRouterConfig(registered);
24
+ const clients: Partial<LLMProviderClients> = {};
25
+ for (const name of Object.keys(registered.providers) as LLMProviderName[]) {
26
+ Object.assign(clients, { [name]: FILE_CONSTANTS.adapters[name].createClient({ ...registered.providers[name] }) });
27
+ }
28
+ FILE_CONSTANTS.providers = { ...registered.providers };
29
+ FILE_CONSTANTS.clients = clients;
30
+ setLLMRouterConfig(registered);
31
+ }
32
+
33
+ /* Return the configured client of one provider. */
34
+ export function getLLMProviderClient<P extends LLMProviderName>(provider: P): LLMProviderClients[P] {
35
+ const client = FILE_CONSTANTS.clients[provider];
36
+ if (!client) throw new Error(`LLM provider "${provider}" is not configured.`);
37
+ return client;
38
+ }
39
+
40
+ /* Whether a provider has a configured client. */
41
+ export function isLLMProviderConfigured(provider: LLMProviderName): boolean {
42
+ return !!FILE_CONSTANTS.clients[provider];
43
+ }
44
+
45
+ /* The adapter of a provider. */
46
+ export function getLLMProviderAdapter<P extends LLMProviderName>(provider: P): LLMProviderAdapter<P> {
47
+ return FILE_CONSTANTS.adapters[provider];
48
+ }
49
+
50
+ /* Build a fresh raw client (configured provider config plus overrides) for probes and evals; no hooks, never cached. */
51
+ export function createLLMProviderClient<P extends LLMProviderName>(
52
+ provider: P,
53
+ overrides?: LLMProviderClientOptions,
54
+ ): LLMProviderClients[P] {
55
+ return FILE_CONSTANTS.adapters[provider].createClient({ ...FILE_CONSTANTS.providers[provider], ...overrides });
56
+ }