@ultimat3/ai 31.24.0 → 31.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +6 -7
- package/README.md +5 -3
- package/package.json +11 -11
- package/src/agent-compact-request.ts +2 -1
- package/src/agent-compact.ts +3 -1
- package/src/agent-def.ts +9 -0
- package/src/agent-usage.ts +8 -0
- package/src/agent.ts +11 -4
- package/src/anthropic-provider.ts +5 -1
- package/src/errors.ts +13 -0
- package/src/gateway-providers.ts +49 -9
- package/src/gateway-settle.ts +79 -0
- package/src/gateway.ts +62 -76
- package/src/index.ts +8 -0
- package/src/llm-answer.ts +3 -3
- package/src/llm-def.ts +9 -0
- package/src/llm-instrument.ts +6 -4
- package/src/llm.ts +7 -1
- package/src/model-fallback.ts +255 -0
- package/src/models.ts +10 -0
- package/src/openai-body.ts +6 -2
- package/src/provider-options.ts +181 -0
- package/src/provider.ts +16 -0
- package/src/run-meter.ts +34 -8
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// Single responsibility: `providerOptions` — the typed bag of wire parameters the framework does not
|
|
2
|
+
// model itself, one sub-bag per wire format, screened key by key before any request leaves.
|
|
3
|
+
//
|
|
4
|
+
// The keys are the WIRE's own names (`top_p`, `service_tier`), never a translated set: a body builder
|
|
5
|
+
// spreads a screened bag as it stands, the way it passes a content block through.
|
|
6
|
+
|
|
7
|
+
import { renderCauseValue } from '@ultimat3/core';
|
|
8
|
+
import { AiRequestInvalidError } from './errors';
|
|
9
|
+
import type { SamplingWire } from './sampling';
|
|
10
|
+
|
|
11
|
+
/** The Messages API's parameters a request may pass through (`anthropicProvider()`). */
|
|
12
|
+
export interface AnthropicProviderOptions {
|
|
13
|
+
/** `metadata.user_id`: an opaque per-user id the provider uses for abuse detection. */
|
|
14
|
+
readonly metadata?: { readonly user_id?: string };
|
|
15
|
+
readonly service_tier?: 'auto' | 'standard_only';
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** The chat-completions parameters a request may pass through (`openAiProvider()`, any host). */
|
|
19
|
+
export interface OpenAiProviderOptions {
|
|
20
|
+
/** 0 to 1. Asked for explicitly: a reasoning model in this family may answer it with a 400. */
|
|
21
|
+
readonly top_p?: number;
|
|
22
|
+
/** -2 to 2. */
|
|
23
|
+
readonly frequency_penalty?: number;
|
|
24
|
+
/** -2 to 2. */
|
|
25
|
+
readonly presence_penalty?: number;
|
|
26
|
+
readonly user?: string;
|
|
27
|
+
readonly parallel_tool_calls?: boolean;
|
|
28
|
+
readonly service_tier?: 'auto' | 'default' | 'flex' | 'priority';
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* One bag per wire format; each provider reads its own wire's and never another's, so one request
|
|
33
|
+
* carries both when its `fallbackModels` cross formats.
|
|
34
|
+
*/
|
|
35
|
+
export interface ProviderOptions {
|
|
36
|
+
readonly anthropic?: AnthropicProviderOptions;
|
|
37
|
+
readonly openai?: OpenAiProviderOptions;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
type Rule =
|
|
41
|
+
| { readonly kind: 'number'; readonly min: number; readonly max: number }
|
|
42
|
+
| { readonly kind: 'string' }
|
|
43
|
+
| { readonly kind: 'boolean' }
|
|
44
|
+
| { readonly kind: 'enum'; readonly values: readonly string[] }
|
|
45
|
+
| { readonly kind: 'object'; readonly fields: Readonly<Record<string, Rule>> };
|
|
46
|
+
|
|
47
|
+
type RulesOf<T> = { readonly [K in keyof Required<T>]-?: Rule };
|
|
48
|
+
|
|
49
|
+
// Typed against the interfaces: a key one adds without the other is a type error, both ways.
|
|
50
|
+
const RULES: { readonly [W in SamplingWire]-?: RulesOf<Required<ProviderOptions>[W]> } = {
|
|
51
|
+
anthropic: {
|
|
52
|
+
metadata: { kind: 'object', fields: { user_id: { kind: 'string' } } },
|
|
53
|
+
service_tier: { kind: 'enum', values: ['auto', 'standard_only'] },
|
|
54
|
+
},
|
|
55
|
+
openai: {
|
|
56
|
+
frequency_penalty: { kind: 'number', min: -2, max: 2 },
|
|
57
|
+
parallel_tool_calls: { kind: 'boolean' },
|
|
58
|
+
presence_penalty: { kind: 'number', min: -2, max: 2 },
|
|
59
|
+
service_tier: { kind: 'enum', values: ['auto', 'default', 'flex', 'priority'] },
|
|
60
|
+
top_p: { kind: 'number', min: 0, max: 1 },
|
|
61
|
+
user: { kind: 'string' },
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const WIRES = Object.keys(RULES) as SamplingWire[];
|
|
66
|
+
|
|
67
|
+
/** Every key each wire takes, sorted — what the README's table and a refusal list. */
|
|
68
|
+
export const PROVIDER_OPTION_KEYS: { readonly [W in SamplingWire]: readonly string[] } = {
|
|
69
|
+
anthropic: Object.keys(RULES.anthropic).sort(),
|
|
70
|
+
openai: Object.keys(RULES.openai).sort(),
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
74
|
+
typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
75
|
+
|
|
76
|
+
const refuse = (detail: string, fix: string): never => {
|
|
77
|
+
throw new AiRequestInvalidError({ detail, fix });
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const FIX = (wire: string, key: string): string =>
|
|
81
|
+
`providerOptions: { ${wire}: { ${key}: <value> } } # one of: ${PROVIDER_OPTION_KEYS[wire as SamplingWire]?.join(', ') ?? WIRES.join(', ')} — or drop the key`;
|
|
82
|
+
|
|
83
|
+
function screenValue(path: string, wire: string, key: string, rule: Rule, value: unknown): void {
|
|
84
|
+
const shown = renderCauseValue(value);
|
|
85
|
+
switch (rule.kind) {
|
|
86
|
+
case 'number':
|
|
87
|
+
if (typeof value !== 'number' || !(value >= rule.min && value <= rule.max)) {
|
|
88
|
+
refuse(
|
|
89
|
+
`providerOptions.${path} is ${shown}; it must be a number from ${rule.min} to ${rule.max}`,
|
|
90
|
+
FIX(wire, key),
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
return;
|
|
94
|
+
case 'string':
|
|
95
|
+
case 'boolean':
|
|
96
|
+
if (typeof value !== rule.kind) {
|
|
97
|
+
refuse(`providerOptions.${path} is ${shown}; it must be a ${rule.kind}`, FIX(wire, key));
|
|
98
|
+
}
|
|
99
|
+
return;
|
|
100
|
+
case 'enum':
|
|
101
|
+
if (typeof value !== 'string' || !rule.values.includes(value)) {
|
|
102
|
+
refuse(
|
|
103
|
+
`providerOptions.${path} is ${shown}; it must be one of ${rule.values.join(', ')}`,
|
|
104
|
+
FIX(wire, key),
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
return;
|
|
108
|
+
case 'object':
|
|
109
|
+
screenFields(path, wire, key, rule.fields, value);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function screenFields(
|
|
114
|
+
path: string,
|
|
115
|
+
wire: string,
|
|
116
|
+
key: string,
|
|
117
|
+
fields: Readonly<Record<string, Rule>>,
|
|
118
|
+
bag: unknown,
|
|
119
|
+
): void {
|
|
120
|
+
if (!isRecord(bag)) {
|
|
121
|
+
refuse(
|
|
122
|
+
`providerOptions.${path} is ${renderCauseValue(bag)}; it must be an object`,
|
|
123
|
+
FIX(wire, key),
|
|
124
|
+
);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const known = Object.keys(fields);
|
|
128
|
+
for (const [name, value] of Object.entries(bag)) {
|
|
129
|
+
if (value === undefined) continue;
|
|
130
|
+
const rule = Object.hasOwn(fields, name) ? fields[name] : undefined;
|
|
131
|
+
if (rule === undefined) {
|
|
132
|
+
refuse(
|
|
133
|
+
`providerOptions.${path}.${name} is not a parameter here; it takes ${known.join(', ')}`,
|
|
134
|
+
FIX(wire, key),
|
|
135
|
+
);
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
// A top-level key names itself in the fix; a nested one names the key that holds it.
|
|
139
|
+
screenValue(`${path}.${name}`, wire, path === wire ? name : key, rule, value);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* The whole bag, screened: an unknown wire, an unknown key for its wire, a wrong type or an
|
|
145
|
+
* out-of-range number is `X_AI_REQUEST_INVALID` — before a reservation, before a socket. A bag for a
|
|
146
|
+
* wire no configured provider speaks is NOT refused: a `fallbackModels` chain may cross formats.
|
|
147
|
+
*/
|
|
148
|
+
export function screenProviderOptions(options: unknown): void {
|
|
149
|
+
if (options === undefined) return;
|
|
150
|
+
if (!isRecord(options)) {
|
|
151
|
+
refuse(
|
|
152
|
+
`providerOptions is ${renderCauseValue(options)}; it must be an object keyed by wire format`,
|
|
153
|
+
`providerOptions: { openai: { top_p: 0.9 } } # keyed by ${WIRES.join(', ')}`,
|
|
154
|
+
);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
for (const [wire, bag] of Object.entries(options)) {
|
|
158
|
+
if (bag === undefined) continue;
|
|
159
|
+
if (!(WIRES as string[]).includes(wire)) {
|
|
160
|
+
refuse(
|
|
161
|
+
`providerOptions.${wire} names no wire format; the wires are ${WIRES.join(', ')}`,
|
|
162
|
+
`providerOptions: { openai: { top_p: 0.9 } } # keyed by ${WIRES.join(', ')}`,
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
screenFields(wire, wire, wire, RULES[wire as SamplingWire], bag);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* The body fields one wire's bag adds — screened here too, so a provider called directly (no
|
|
171
|
+
* gateway) refuses exactly what the gateway would. The other wires' bags are ignored.
|
|
172
|
+
*/
|
|
173
|
+
export function providerOptionsBody(
|
|
174
|
+
wire: SamplingWire,
|
|
175
|
+
options: ProviderOptions | undefined,
|
|
176
|
+
): Record<string, unknown> {
|
|
177
|
+
const bag = options?.[wire];
|
|
178
|
+
if (bag === undefined) return {};
|
|
179
|
+
screenFields(wire, wire, wire, RULES[wire], bag);
|
|
180
|
+
return Object.fromEntries(Object.entries(bag).filter(([, value]) => value !== undefined));
|
|
181
|
+
}
|
package/src/provider.ts
CHANGED
|
@@ -7,11 +7,13 @@ import type { Money } from '@ultimat3/money';
|
|
|
7
7
|
import type { AiMediaBlock } from './content-blocks';
|
|
8
8
|
import { blockText, mediaTokenEstimate } from './content-blocks';
|
|
9
9
|
import { costOf } from './cost';
|
|
10
|
+
import type { ModelFallback } from './model-fallback';
|
|
10
11
|
import { resolveModel } from './model-resolve';
|
|
11
12
|
import type { Effort, ModelId, ThinkingMode } from './models';
|
|
12
13
|
import { modelSpec } from './models';
|
|
13
14
|
import type { PromptCacheHint, SystemPrompt } from './prompt-cache';
|
|
14
15
|
import { systemText } from './prompt-cache';
|
|
16
|
+
import type { ProviderOptions } from './provider-options';
|
|
15
17
|
import type { SamplingWire } from './sampling';
|
|
16
18
|
import type { LlmTool, LlmToolCall } from './tools';
|
|
17
19
|
|
|
@@ -57,6 +59,15 @@ export function messageText(message: AiMessage): string {
|
|
|
57
59
|
|
|
58
60
|
export interface GenerateRequest {
|
|
59
61
|
readonly model?: ModelId;
|
|
62
|
+
/**
|
|
63
|
+
* Tried in order, by the gateway alone, when `model` fails with a declared class
|
|
64
|
+
* (`MODEL_FALLBACK_ON`: rate limited, overloaded, unavailable, timed out) — never on a 400, a
|
|
65
|
+
* refusal or a budget. Each attempt is reserved and billed on its own. Not in `promptCacheKey`:
|
|
66
|
+
* each model's answer is cached under its own model.
|
|
67
|
+
*/
|
|
68
|
+
readonly fallbackModels?: readonly ModelId[];
|
|
69
|
+
/** Wire parameters the framework does not model, one bag per wire (`./provider-options`). */
|
|
70
|
+
readonly providerOptions?: ProviderOptions;
|
|
60
71
|
/** One string, or a stable part and a per-run part (`./prompt-cache`) — two blocks on the wire. */
|
|
61
72
|
readonly system?: SystemPrompt;
|
|
62
73
|
/**
|
|
@@ -148,6 +159,11 @@ export interface GenerateResult {
|
|
|
148
159
|
* an app wrote may not state it, and its `cost` is summed in its place.
|
|
149
160
|
*/
|
|
150
161
|
readonly costExact?: Money;
|
|
162
|
+
/**
|
|
163
|
+
* The models of a `fallbackModels` chain that failed before this one answered, in order — stamped
|
|
164
|
+
* by the gateway. Each was reserved and settled on the ledger; the run meter counts each one.
|
|
165
|
+
*/
|
|
166
|
+
readonly fallbacks?: readonly ModelFallback[];
|
|
151
167
|
}
|
|
152
168
|
|
|
153
169
|
/** One streamed increment. `done` carries the assembled result. */
|
package/src/run-meter.ts
CHANGED
|
@@ -10,21 +10,26 @@ import { addUsage } from './agent-usage';
|
|
|
10
10
|
import type { Billed } from './billed';
|
|
11
11
|
import { BILLED_META, billedCall, billedOf } from './billed';
|
|
12
12
|
import { addMoney } from './cost';
|
|
13
|
+
import type { ModelFallback } from './model-fallback';
|
|
14
|
+
import { withAttemptSink } from './model-fallback';
|
|
13
15
|
import type { GenerateResult } from './provider';
|
|
14
16
|
import { ZERO_USAGE } from './wire';
|
|
15
17
|
|
|
16
18
|
export interface RunMeter {
|
|
17
19
|
/**
|
|
18
|
-
*
|
|
19
|
-
* transport failure leaves it that way, and its bill cannot be known from here.
|
|
20
|
+
* Run and await one provider call. Until it reports usage it is UNSETTLED: an abort, a deadline
|
|
21
|
+
* or a transport failure leaves it that way, and its bill cannot be known from here. A thunk, so
|
|
22
|
+
* the call STARTS inside this meter: a `fallbackModels` chain in it reports each model it falls
|
|
23
|
+
* over from to this meter alone (`withAttemptSink`), however many calls share a thrown object.
|
|
20
24
|
*/
|
|
21
|
-
call(work: Promise<GenerateResult>): Promise<GenerateResult>;
|
|
25
|
+
call(work: () => Promise<GenerateResult>): Promise<GenerateResult>;
|
|
22
26
|
/** The run so far, re-priced from the summed usage — `undefined` before the first answer. */
|
|
23
27
|
total(): AgentRunUsage | undefined;
|
|
24
28
|
/** The run's bill, or `undefined` when no provider call was ever started. */
|
|
25
29
|
billed(): Billed | undefined;
|
|
26
30
|
/**
|
|
27
|
-
* What
|
|
31
|
+
* What was billed at ANOTHER model's price, added and never re-priced: runs underneath this one —
|
|
32
|
+
* a tool that itself calls `llm()` or an `agent()` — and answers a `fallbackModels` model gave.
|
|
28
33
|
* Their failures are read by the model as tool results and never thrown here, so this is the
|
|
29
34
|
* only way that spend reaches the run that caused it.
|
|
30
35
|
*/
|
|
@@ -60,6 +65,18 @@ export function runMeter(): RunMeter {
|
|
|
60
65
|
let carried: Billed | undefined;
|
|
61
66
|
const counted = new WeakSet<object>();
|
|
62
67
|
|
|
68
|
+
/**
|
|
69
|
+
* A model a chain fell over from, as it happens — an attempt too, never free: its bill when its
|
|
70
|
+
* failure carried one, else one unsettled call. The model that ends the walk is the call's own
|
|
71
|
+
* answer or throw, counted below.
|
|
72
|
+
*/
|
|
73
|
+
const fellOver = (attempt: ModelFallback): void => {
|
|
74
|
+
const bill = attempt.billed ?? UNSETTLED_CALL;
|
|
75
|
+
if (attempt.billed === undefined) unsettled += 1;
|
|
76
|
+
else carried = carried === undefined ? bill : sum(carried, bill);
|
|
77
|
+
parent?.report(bill);
|
|
78
|
+
};
|
|
79
|
+
|
|
63
80
|
const absorb = (error: unknown): void => {
|
|
64
81
|
const billed = billedOf(error);
|
|
65
82
|
if (billed === undefined || typeof error !== 'object' || error === null) return;
|
|
@@ -91,11 +108,17 @@ export function runMeter(): RunMeter {
|
|
|
91
108
|
async call(work) {
|
|
92
109
|
unsettled += 1;
|
|
93
110
|
try {
|
|
94
|
-
const result = await work;
|
|
111
|
+
const result = await withAttemptSink(fellOver, work);
|
|
95
112
|
unsettled -= 1;
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
113
|
+
if (fellOverTo(result)) {
|
|
114
|
+
// Answered by a `fallbackModels` model: billed at ITS price, apart — `own` is re-priced
|
|
115
|
+
// as one model, and summing a fallback's tokens into it charged them at the primary's.
|
|
116
|
+
report(billedCall(result.usage, result.costExact ?? result.cost));
|
|
117
|
+
} else {
|
|
118
|
+
calls += 1;
|
|
119
|
+
own = addUsage(own, result);
|
|
120
|
+
parent?.report(billedCall(result.usage, result.costExact ?? result.cost));
|
|
121
|
+
}
|
|
99
122
|
return result;
|
|
100
123
|
} catch (error) {
|
|
101
124
|
// The provider answered and billed, then the answer could not be used: settled after all.
|
|
@@ -153,6 +176,9 @@ export async function meteredRun<T>(
|
|
|
153
176
|
}
|
|
154
177
|
}
|
|
155
178
|
|
|
179
|
+
/** Answered on a fallback, not the model asked for. */
|
|
180
|
+
const fellOverTo = (result: GenerateResult): boolean => (result.fallbacks?.length ?? 0) > 0;
|
|
181
|
+
|
|
156
182
|
/** One started call that never reported usage: counted, never priced. */
|
|
157
183
|
const UNSETTLED_CALL: Billed = {
|
|
158
184
|
usage: ZERO_USAGE,
|