@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 +21 -0
- package/README.md +202 -2
- package/package.json +61 -5
- package/src/capabilities.ts +144 -0
- package/src/classifier.ts +126 -0
- package/src/config.ts +38 -0
- package/src/main.ts +25 -0
- package/src/operations/decisions.ts +14 -0
- package/src/operations/embeddings.ts +11 -0
- package/src/operations/files.ts +38 -0
- package/src/operations/moderation.ts +13 -0
- package/src/operations/responses.helpers.ts +424 -0
- package/src/operations/responses.transport.ts +17 -0
- package/src/operations/responses.ts +186 -0
- package/src/operations/transcription.ts +14 -0
- package/src/policy/models.ts +83 -0
- package/src/policy/reasoning.ts +196 -0
- package/src/policy/tasks.ts +32 -0
- package/src/providers/_provider.helpers.ts +37 -0
- package/src/providers/_provider.ts +19 -0
- package/src/providers/anthropic.helpers.ts +346 -0
- package/src/providers/anthropic.reasoning.helpers.ts +75 -0
- package/src/providers/anthropic.stream.ts +299 -0
- package/src/providers/anthropic.ts +63 -0
- package/src/providers/deepseek.ts +98 -0
- package/src/providers/openai.ts +20 -0
- package/src/registry.helpers.ts +117 -0
- package/src/registry.ts +56 -0
- package/src/router.helpers.ts +269 -0
- package/src/router.ts +204 -0
- package/src/trace.ts +17 -0
- package/src/types.ts +291 -0
- package/src/utils/errors.ts +164 -0
- package/src/utils/promptCache.ts +144 -0
- package/src/utils/responseFormat.ts +8 -0
- package/src/utils/responseItems.ts +1 -0
- package/src/zod.ts +1 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { getLLMProviderClient, getLLMRouterConfig } from '../registry.ts';
|
|
2
|
+
|
|
3
|
+
/* Transcribe an audio buffer in memory (raw provider result with text and usage). */
|
|
4
|
+
export function createTranscription(buffer: Uint8Array, fileName: string, contentType: string, language?: string | null) {
|
|
5
|
+
return getLLMProviderClient('openai').audio.transcriptions.create({
|
|
6
|
+
// @ts-ignore - new File() typing
|
|
7
|
+
file: new File([buffer], fileName, {
|
|
8
|
+
type: contentType,
|
|
9
|
+
}),
|
|
10
|
+
model: getLLMRouterConfig().defaults.transcriptionModel,
|
|
11
|
+
response_format: 'json',
|
|
12
|
+
...(language ? { languages: [language] } : {}),
|
|
13
|
+
});
|
|
14
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { getLLMRouterConfig, getOptionalLLMRouterConfig } from '../config.ts';
|
|
2
|
+
import type { LLMEffort, LLMProviderName, LLMTier } from '../types.ts';
|
|
3
|
+
import { getModelReasoningPolicy, type LLMReasoningPolicy, resolveReasoningEffort } from './reasoning.ts';
|
|
4
|
+
|
|
5
|
+
export type LLMModelId = string;
|
|
6
|
+
|
|
7
|
+
// USD per 1M tokens
|
|
8
|
+
export interface LLMModelPrice {
|
|
9
|
+
input: number;
|
|
10
|
+
cachedInput: number;
|
|
11
|
+
output: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface LLMModelEntry {
|
|
15
|
+
provider: LLMProviderName;
|
|
16
|
+
strength: number; // Orders routes for the pin upgrade and never-downgrade rules; higher is stronger
|
|
17
|
+
cacheLifetimeMS: number; // The application's expected cache lifetime for pin freshness
|
|
18
|
+
imageInput: boolean; // Whether a non-OpenAI model takes input_image parts; OpenAI models are fully capable by provider
|
|
19
|
+
prices: (LLMModelPrice & { cacheWriteMultiplier: number }) | null; // null: price not verified
|
|
20
|
+
reasoning?: LLMReasoningPolicy; // Overrides built-in capabilities; required for reasoning requests to unknown models.
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/* Resolve an application-defined tier; unknown tiers are configuration errors. */
|
|
24
|
+
export function getModelForTier(tier: LLMTier): string {
|
|
25
|
+
const tiers = getLLMRouterConfig().routing.tiers;
|
|
26
|
+
if (!Object.hasOwn(tiers, tier)) throw new Error(`Unknown LLM tier "${tier}".`);
|
|
27
|
+
return tiers[tier];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/* Look up a registered model's capabilities, ranking and pricing. */
|
|
31
|
+
export function getLLMModelEntry(model: string): LLMModelEntry | null {
|
|
32
|
+
const models = getLLMRouterConfig().routing.models;
|
|
33
|
+
return Object.hasOwn(models, model) ? models[model] : null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/* Resolve the application's fallback; returning null disables model fallback. */
|
|
37
|
+
export function getDefaultFallbackModel(model: string): string | null {
|
|
38
|
+
return getLLMRouterConfig().routing.fallbackModel(model);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/* Resolve registered capability overrides while allowing built-in lookups before router configuration. */
|
|
42
|
+
export function getResolvedModelReasoningPolicy(model: string, provider?: LLMProviderName): LLMReasoningPolicy | null {
|
|
43
|
+
const models = getOptionalLLMRouterConfig()?.routing.models;
|
|
44
|
+
const entry = models && Object.hasOwn(models, model) ? models[model] : undefined;
|
|
45
|
+
return getModelReasoningPolicy(model, provider || entry?.provider, entry?.reasoning);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/* Map the requested effort through the selected model's registered or built-in capabilities. */
|
|
49
|
+
export function mapCompatibleReasoningEffort(model: string, effort: LLMEffort, provider?: LLMProviderName): LLMEffort {
|
|
50
|
+
const policy = getResolvedModelReasoningPolicy(model, provider);
|
|
51
|
+
if (!policy) {
|
|
52
|
+
throw new Error(`No reasoning policy for model "${model}". Declare routing.models[model].reasoning with its supported efforts.`);
|
|
53
|
+
}
|
|
54
|
+
return resolveReasoningEffort(model, effort, provider, policy);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/*
|
|
58
|
+
* Estimate the USD cost of one usage aggregate from the policy prices; null when the model has no verified price.
|
|
59
|
+
* Responses: uncached input, cached input, cache writes (input price x cacheWriteMultiplier) and output, times 2 for
|
|
60
|
+
* the priority/fast service tiers. OpenAI input_tokens include cached and cache-write tokens. Decisions: input only.
|
|
61
|
+
*/
|
|
62
|
+
export function estimateLLMCostUSD(
|
|
63
|
+
input: {
|
|
64
|
+
model: string;
|
|
65
|
+
endpoint: 'responses' | 'decisions';
|
|
66
|
+
serviceTier: string | null;
|
|
67
|
+
tokens: { input: number; cached: number; cacheWrite: number; output: number };
|
|
68
|
+
},
|
|
69
|
+
models: Readonly<Record<string, LLMModelEntry>> = getLLMRouterConfig().routing.models,
|
|
70
|
+
): number | null {
|
|
71
|
+
const prices = Object.hasOwn(models, input.model) ? models[input.model]?.prices : null;
|
|
72
|
+
if (!prices) return null;
|
|
73
|
+
const { tokens } = input;
|
|
74
|
+
if (input.endpoint === 'decisions') return (tokens.input * prices.input) / 1e6;
|
|
75
|
+
const uncached = Math.max(0, tokens.input - tokens.cached - tokens.cacheWrite);
|
|
76
|
+
const cost =
|
|
77
|
+
(uncached * prices.input +
|
|
78
|
+
tokens.cached * prices.cachedInput +
|
|
79
|
+
tokens.cacheWrite * prices.input * prices.cacheWriteMultiplier +
|
|
80
|
+
tokens.output * prices.output) /
|
|
81
|
+
1e6;
|
|
82
|
+
return input.serviceTier && ['priority', 'fast'].includes(input.serviceTier) ? cost * 2 : cost;
|
|
83
|
+
}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import type { LLMEffort, LLMProviderName } from '../types.ts';
|
|
2
|
+
|
|
3
|
+
export const LLM_REASONING_EFFORTS: readonly LLMEffort[] = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
|
|
4
|
+
|
|
5
|
+
export interface LLMReasoningPolicy {
|
|
6
|
+
readonly supportedEfforts: readonly LLMEffort[];
|
|
7
|
+
readonly mappings?: Readonly<Partial<Record<LLMEffort, LLMEffort>>>;
|
|
8
|
+
readonly omitReasoning?: boolean; // Models without a reasoning parameter resolve to none and omit that parameter.
|
|
9
|
+
readonly anthropic?: {
|
|
10
|
+
readonly mode: 'adaptive' | 'budget';
|
|
11
|
+
readonly effort?: boolean; // False for legacy models without output_config.effort; otherwise true.
|
|
12
|
+
readonly budgets?: Readonly<Partial<Record<LLMEffort, number>>>;
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/*
|
|
17
|
+
* Verified provider capabilities, independent of the application's routing catalog.
|
|
18
|
+
* OpenAI: https://developers.openai.com/api/docs/guides/reasoning and each listed model page.
|
|
19
|
+
* Claude: https://platform.claude.com/docs/en/build-with-claude/effort and /thinking.
|
|
20
|
+
* DeepSeek: https://api-docs.deepseek.com/guides/thinking_mode/.
|
|
21
|
+
* Legacy Claude budgets below are router presets, not native named effort levels.
|
|
22
|
+
*/
|
|
23
|
+
const FILE_CONSTANTS: {
|
|
24
|
+
profiles: { provider: LLMProviderName; models: readonly string[]; policy: LLMReasoningPolicy }[];
|
|
25
|
+
} = {
|
|
26
|
+
profiles: [
|
|
27
|
+
{
|
|
28
|
+
provider: 'openai',
|
|
29
|
+
models: ['gpt-6.2-astra', 'gpt-6.2-sol', 'gpt-6-astra', 'gpt-6.1-sol'],
|
|
30
|
+
policy: { supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'] },
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
provider: 'openai',
|
|
34
|
+
models: ['gpt-6-sol', 'gpt-6.1-terra', 'gpt-6-luna', 'gpt-5.6-luna'],
|
|
35
|
+
policy: { supportedEfforts: ['none', 'low', 'medium', 'high', 'xhigh', 'max'] },
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
provider: 'openai',
|
|
39
|
+
models: ['gpt-5', 'gpt-5-mini', 'gpt-5-nano'],
|
|
40
|
+
policy: { supportedEfforts: ['minimal', 'low', 'medium', 'high'] },
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
provider: 'openai',
|
|
44
|
+
models: ['gpt-4.1'],
|
|
45
|
+
policy: { supportedEfforts: ['none'], omitReasoning: true },
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
provider: 'deepseek',
|
|
49
|
+
models: ['deepseek-v4-pro', 'deepseek-flash'],
|
|
50
|
+
policy: { supportedEfforts: ['none', 'low', 'high', 'max'], mappings: { minimal: 'low', medium: 'high', xhigh: 'high' } },
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
provider: 'anthropic',
|
|
54
|
+
models: [
|
|
55
|
+
'claude-fable-5-2',
|
|
56
|
+
'claude-mythos-5-2',
|
|
57
|
+
'claude-fable-5-1',
|
|
58
|
+
'claude-mythos-5-1',
|
|
59
|
+
'claude-fable-5',
|
|
60
|
+
'claude-mythos-5',
|
|
61
|
+
'claude-opus-5-5',
|
|
62
|
+
'claude-sonnet-5-5',
|
|
63
|
+
],
|
|
64
|
+
policy: { supportedEfforts: ['low', 'medium', 'high', 'xhigh', 'max'], anthropic: { mode: 'adaptive' } },
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
provider: 'anthropic',
|
|
68
|
+
models: ['claude-opus-5', 'claude-sonnet-5', 'claude-haiku-5-5', 'claude-opus-4-8', 'claude-opus-4-7'],
|
|
69
|
+
policy: { supportedEfforts: ['none', 'low', 'medium', 'high', 'xhigh', 'max'], anthropic: { mode: 'adaptive' } },
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
provider: 'anthropic',
|
|
73
|
+
models: ['claude-mythos-preview'],
|
|
74
|
+
policy: { supportedEfforts: ['low', 'medium', 'high', 'max'], anthropic: { mode: 'adaptive' } },
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
provider: 'anthropic',
|
|
78
|
+
models: ['claude-opus-4-6', 'claude-sonnet-4-6'],
|
|
79
|
+
policy: { supportedEfforts: ['none', 'low', 'medium', 'high', 'max'], anthropic: { mode: 'adaptive' } },
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
provider: 'anthropic',
|
|
83
|
+
models: ['claude-opus-4-5'],
|
|
84
|
+
policy: {
|
|
85
|
+
supportedEfforts: ['none', 'low', 'medium', 'high'],
|
|
86
|
+
anthropic: { mode: 'budget', budgets: { low: 1024, medium: 4096, high: 8192 } },
|
|
87
|
+
},
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
provider: 'anthropic',
|
|
91
|
+
models: ['claude-sonnet-4-5', 'claude-haiku-4-5'],
|
|
92
|
+
policy: {
|
|
93
|
+
supportedEfforts: ['none', 'low', 'medium', 'high'],
|
|
94
|
+
anthropic: { mode: 'budget', effort: false, budgets: { low: 1024, medium: 4096, high: 8192 } },
|
|
95
|
+
},
|
|
96
|
+
},
|
|
97
|
+
],
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
/* Validate configured capabilities before they can produce an invalid mapping or native parameter. */
|
|
101
|
+
export function validateLLMReasoningPolicy(policy: LLMReasoningPolicy, provider?: LLMProviderName, model = 'custom model'): void {
|
|
102
|
+
const prefix = `Invalid reasoning policy for "${model}":`;
|
|
103
|
+
if (
|
|
104
|
+
!policy || !Array.isArray(policy.supportedEfforts) || !policy.supportedEfforts.length ||
|
|
105
|
+
policy.supportedEfforts.some((effort) => !LLM_REASONING_EFFORTS.includes(effort))
|
|
106
|
+
) {
|
|
107
|
+
throw new Error(`${prefix} supportedEfforts must contain canonical reasoning efforts.`);
|
|
108
|
+
}
|
|
109
|
+
if (new Set(policy.supportedEfforts).size !== policy.supportedEfforts.length) {
|
|
110
|
+
throw new Error(`${prefix} supportedEfforts cannot contain duplicates.`);
|
|
111
|
+
}
|
|
112
|
+
for (const [requested, effective] of Object.entries(policy.mappings || {})) {
|
|
113
|
+
if (!LLM_REASONING_EFFORTS.includes(requested as LLMEffort) || !policy.supportedEfforts.includes(effective as LLMEffort)) {
|
|
114
|
+
throw new Error(`${prefix} mappings must map canonical efforts to supported efforts.`);
|
|
115
|
+
}
|
|
116
|
+
if (policy.supportedEfforts.includes(requested as LLMEffort) && requested !== effective) {
|
|
117
|
+
throw new Error(`${prefix} mappings cannot change an already supported effort.`);
|
|
118
|
+
}
|
|
119
|
+
if (requested !== 'none' && effective === 'none' && policy.supportedEfforts.some((effort) => effort !== 'none')) {
|
|
120
|
+
throw new Error(`${prefix} mappings cannot disable an available reasoning mode.`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (policy.omitReasoning !== undefined && typeof policy.omitReasoning !== 'boolean') {
|
|
124
|
+
throw new Error(`${prefix} omitReasoning must be boolean.`);
|
|
125
|
+
}
|
|
126
|
+
if (
|
|
127
|
+
policy.omitReasoning &&
|
|
128
|
+
(policy.supportedEfforts.length !== 1 || policy.supportedEfforts[0] !== 'none' || provider === 'anthropic' || policy.anthropic)
|
|
129
|
+
) throw new Error(`${prefix} omitReasoning requires only none and a non-Anthropic model.`);
|
|
130
|
+
if (provider === 'anthropic' && !policy.anthropic) {
|
|
131
|
+
throw new Error(`${prefix} Anthropic models must declare their native thinking configuration.`);
|
|
132
|
+
}
|
|
133
|
+
if (!policy.anthropic) return;
|
|
134
|
+
if (provider && provider !== 'anthropic') {
|
|
135
|
+
throw new Error(`${prefix} Anthropic thinking configuration requires the anthropic provider.`);
|
|
136
|
+
}
|
|
137
|
+
const { mode, effort, budgets } = policy.anthropic;
|
|
138
|
+
if (mode !== 'adaptive' && mode !== 'budget') throw new Error(`${prefix} Anthropic mode must be adaptive or budget.`);
|
|
139
|
+
if (effort !== undefined && typeof effort !== 'boolean') throw new Error(`${prefix} Anthropic effort support must be boolean.`);
|
|
140
|
+
if (effort !== false && policy.supportedEfforts.includes('minimal')) {
|
|
141
|
+
throw new Error(`${prefix} Anthropic native effort does not support minimal.`);
|
|
142
|
+
}
|
|
143
|
+
if (mode !== 'budget' && budgets) throw new Error(`${prefix} thinking budgets require budget mode.`);
|
|
144
|
+
for (const [level, budget] of Object.entries(budgets || {})) {
|
|
145
|
+
if (level === 'none' || !policy.supportedEfforts.includes(level as LLMEffort) || !Number.isSafeInteger(budget) || budget < 1024) {
|
|
146
|
+
throw new Error(`${prefix} thinking budgets must be integers of at least 1024 for supported positive efforts.`);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (mode === 'budget' && policy.supportedEfforts.some((level: LLMEffort) => level !== 'none' && !budgets?.[level])) {
|
|
150
|
+
throw new Error(`${prefix} budget mode requires a thinking budget for every supported positive effort.`);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/* Resolve an explicit policy or a documented model profile; unknown model names require configuration. */
|
|
155
|
+
export function getModelReasoningPolicy(
|
|
156
|
+
model: string,
|
|
157
|
+
provider?: LLMProviderName,
|
|
158
|
+
explicitPolicy?: LLMReasoningPolicy,
|
|
159
|
+
): LLMReasoningPolicy | null {
|
|
160
|
+
if (explicitPolicy) {
|
|
161
|
+
validateLLMReasoningPolicy(explicitPolicy, provider, model);
|
|
162
|
+
return explicitPolicy;
|
|
163
|
+
}
|
|
164
|
+
// Only recognize dated snapshots of known IDs, never arbitrary future model families or suffixes.
|
|
165
|
+
const baseModel = model.replace(/-(?:\d{4}-\d{2}-\d{2}|\d{8})$/, '');
|
|
166
|
+
return FILE_CONSTANTS.profiles.find((profile) => (!provider || provider === profile.provider) && profile.models.includes(baseModel))
|
|
167
|
+
?.policy || null;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/* Preserve exact efforts, then provider aliases, then the nearest level; ties prefer stronger reasoning. */
|
|
171
|
+
export function resolveReasoningEffort(
|
|
172
|
+
model: string,
|
|
173
|
+
requested: LLMEffort,
|
|
174
|
+
provider?: LLMProviderName,
|
|
175
|
+
explicitPolicy?: LLMReasoningPolicy,
|
|
176
|
+
): LLMEffort {
|
|
177
|
+
if (!LLM_REASONING_EFFORTS.includes(requested)) throw new Error(`Unknown reasoning effort "${requested}".`);
|
|
178
|
+
const policy = getModelReasoningPolicy(model, provider, explicitPolicy);
|
|
179
|
+
if (!policy) {
|
|
180
|
+
throw new Error(`No reasoning policy for model "${model}". Declare routing.models[model].reasoning with its supported efforts.`);
|
|
181
|
+
}
|
|
182
|
+
if (policy.supportedEfforts.includes(requested)) return requested;
|
|
183
|
+
const mapped = policy.mappings?.[requested];
|
|
184
|
+
if (mapped) return mapped;
|
|
185
|
+
const positive = policy.supportedEfforts.filter((effort) => effort !== 'none');
|
|
186
|
+
const candidates = requested !== 'none' && positive.length ? positive : policy.supportedEfforts;
|
|
187
|
+
const requestedRank = LLM_REASONING_EFFORTS.indexOf(requested);
|
|
188
|
+
let closest = candidates[0];
|
|
189
|
+
for (const candidate of candidates) {
|
|
190
|
+
const candidateRank = LLM_REASONING_EFFORTS.indexOf(candidate);
|
|
191
|
+
const closestRank = LLM_REASONING_EFFORTS.indexOf(closest);
|
|
192
|
+
const difference = Math.abs(candidateRank - requestedRank) - Math.abs(closestRank - requestedRank);
|
|
193
|
+
if (difference < 0 || (difference === 0 && candidateRank > closestRank)) closest = candidate;
|
|
194
|
+
}
|
|
195
|
+
return closest;
|
|
196
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { LLMClassifierConfig } from '../classifier.ts';
|
|
2
|
+
import type { LLMProviderName, LLMRouteSpec } from '../types.ts';
|
|
3
|
+
|
|
4
|
+
// Applications own their task vocabulary and signal types.
|
|
5
|
+
export type LLMResponseTask = string;
|
|
6
|
+
export type LLMDecisionTask = string;
|
|
7
|
+
|
|
8
|
+
export interface LLMTaskCall<S = unknown> {
|
|
9
|
+
task: string;
|
|
10
|
+
signals?: S;
|
|
11
|
+
decision?: undefined;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export type LLMRouteRule<S> = (signals: S) => { route: LLMRouteSpec; rule: string };
|
|
15
|
+
|
|
16
|
+
export interface LLMTaskTrial {
|
|
17
|
+
organizationIds: readonly string[];
|
|
18
|
+
route: LLMRouteSpec;
|
|
19
|
+
note?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface LLMTaskPolicy<S = unknown> {
|
|
23
|
+
route: LLMRouteSpec | LLMRouteRule<S>;
|
|
24
|
+
providers?: readonly LLMProviderName[];
|
|
25
|
+
trial?: LLMTaskTrial;
|
|
26
|
+
fallback?: LLMRouteSpec | null;
|
|
27
|
+
locked?: string;
|
|
28
|
+
classifier?: LLMClassifierConfig;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Signal types are checked by the application's task map before registration.
|
|
32
|
+
export type LLMTaskPolicyMap = Readonly<Record<string, LLMTaskPolicy<any>>>;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { LLM } from '../types.ts';
|
|
2
|
+
|
|
3
|
+
export const ANTHROPIC_REASONING_PREFIX = 'anthropic:thinking:v1:';
|
|
4
|
+
|
|
5
|
+
/* Identify only the router's provider-tagged Anthropic replay state. */
|
|
6
|
+
export function isAnthropicReasoningItem(item: unknown): boolean {
|
|
7
|
+
const entry = item as { type?: unknown; encrypted_content?: unknown } | null;
|
|
8
|
+
return entry?.type === 'reasoning' && typeof entry.encrypted_content === 'string' &&
|
|
9
|
+
entry.encrypted_content.startsWith(ANTHROPIC_REASONING_PREFIX);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const FILE_CONSTANTS = {
|
|
13
|
+
anthropicItemPrefix: 'anthropic_',
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/* Give normalized Anthropic output a local identity that cannot be mistaken for an OpenAI stored item. */
|
|
17
|
+
export function makeAnthropicResponseItemId(messageId: string, index: number): string {
|
|
18
|
+
return `${FILE_CONSTANTS.anthropicItemPrefix}${messageId}_${index}`;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/* Remove local Anthropic item IDs only at a Responses transport boundary, preserving receipts and tool correlation IDs. */
|
|
22
|
+
export function stripAnthropicResponseItemIds(params: LLM.RequestParams): { params: LLM.RequestParams; mappedParams: string[] } {
|
|
23
|
+
const mappedParams: string[] = [];
|
|
24
|
+
if (!Array.isArray(params.input)) return { params, mappedParams };
|
|
25
|
+
const input = params.input.flatMap((item, index) => {
|
|
26
|
+
if (isAnthropicReasoningItem(item)) {
|
|
27
|
+
mappedParams.push(`input[${index}]:anthropic_reasoning->omitted`);
|
|
28
|
+
return [];
|
|
29
|
+
}
|
|
30
|
+
if (item.type !== 'message' && item.type !== 'function_call') return item;
|
|
31
|
+
if (!('id' in item) || typeof item.id !== 'string' || !item.id.startsWith(FILE_CONSTANTS.anthropicItemPrefix)) return item;
|
|
32
|
+
const { id: _id, ...rest } = item;
|
|
33
|
+
mappedParams.push(`input[${index}].id:anthropic->omitted`);
|
|
34
|
+
return rest;
|
|
35
|
+
});
|
|
36
|
+
return { params: mappedParams.length ? { ...params, input: input as LLM.Input } : params, mappedParams };
|
|
37
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { LLM, LLMProviderClientOptions, LLMProviderClients, LLMProviderName } from '../types.ts';
|
|
2
|
+
|
|
3
|
+
// Router params mapped to what one provider honors, with the names of what the mapping removed or rewrote
|
|
4
|
+
export interface LLMPreparedProviderParams {
|
|
5
|
+
params: LLM.RequestParams;
|
|
6
|
+
strippedParams: string[];
|
|
7
|
+
mappedParams: string[];
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/* What one provider contributes: its name, how to build its SDK client, its param mapping and its usage normalization. */
|
|
11
|
+
export interface LLMProviderAdapter<P extends LLMProviderName = LLMProviderName> {
|
|
12
|
+
name: P;
|
|
13
|
+
/* Build the provider's SDK client from the configured options. */
|
|
14
|
+
createClient(options: LLMProviderClientOptions): LLMProviderClients[P];
|
|
15
|
+
/* Map complete router params without mutation; native OpenAI requests retain object identity. */
|
|
16
|
+
prepareParams(params: LLM.RequestParams): LLMPreparedProviderParams;
|
|
17
|
+
/* Return the response with usage in the Responses shape; OpenAI returns the same object. */
|
|
18
|
+
normalizeUsage(response: LLM.Response): LLM.Response;
|
|
19
|
+
}
|