@outputai/core 0.15.1-next.fd6bb62.0 → 0.16.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/dist/credentials/index.d.ts +1 -1
- package/dist/credentials/types.d.ts +4 -4
- package/dist/evals/aggregate.d.ts +2 -0
- package/dist/evals/aggregate.js +11 -0
- package/dist/evals/eval_workflow.d.ts +20 -0
- package/dist/evals/eval_workflow.js +98 -0
- package/dist/evals/index.d.ts +7 -0
- package/dist/evals/index.js +4 -0
- package/dist/evals/interpret.d.ts +3 -0
- package/dist/evals/interpret.js +40 -0
- package/dist/evals/schemas.d.ts +96 -0
- package/dist/evals/schemas.js +60 -0
- package/dist/evals/verdict.d.ts +27 -0
- package/dist/evals/verdict.js +109 -0
- package/dist/evals/verify.d.ts +42 -0
- package/dist/evals/verify.js +19 -0
- package/package.json +57 -15
- package/src/consts.d.ts +2 -0
- package/src/helpers/path.js +34 -0
- package/src/http/fetch/index.d.ts +3 -5
- package/src/http/index.d.ts +1 -0
- package/src/interface/index.d.ts +1 -0
- package/src/llm/agent.js +147 -0
- package/src/llm/ai_provider.js +131 -0
- package/src/llm/ai_sdk_options.js +126 -0
- package/src/llm/consts.js +6 -0
- package/src/llm/deprecated_provider_aliases.js +8 -0
- package/src/llm/generate.js +98 -0
- package/src/llm/index.d.ts +697 -0
- package/src/llm/index.js +6 -0
- package/src/llm/judge.js +48 -0
- package/src/llm/prompt/content.js +70 -0
- package/src/llm/prompt/interpolations.js +58 -0
- package/src/llm/prompt/loader.js +67 -0
- package/src/llm/prompt/markup/attributes.js +52 -0
- package/src/llm/prompt/markup/nodes.js +71 -0
- package/src/llm/prompt/markup/tokenizer.js +3 -0
- package/src/llm/prompt/markup/tokens.js +26 -0
- package/src/llm/prompt/validations.js +129 -0
- package/src/llm/utils/cost.js +267 -0
- package/src/llm/utils/error_handler.js +53 -0
- package/src/llm/utils/file.js +42 -0
- package/src/llm/utils/google_vertex_auth.js +31 -0
- package/src/llm/utils/image.js +37 -0
- package/src/llm/utils/legacy_cost_attribute.js +75 -0
- package/src/llm/utils/metering.js +139 -0
- package/src/llm/utils/models.js +15 -0
- package/src/llm/utils/models_pricing.js +96 -0
- package/src/llm/utils/models_pricing_snapshot.json +4711 -0
- package/src/llm/utils/skills.js +74 -0
- package/src/llm/utils/sources.js +73 -0
- package/src/llm/utils/stream.js +75 -0
- package/src/llm/utils/tools.js +62 -0
- package/src/llm/utils/usage.js +155 -0
- package/src/llm/utils/usage_tools.js +23 -0
- package/src/llm/utils/web_search.js +155 -0
- package/src/llm/utils/wrap.js +279 -0
- package/src/llm/validations.js +234 -0
- package/src/worker/bundler_options.js +1 -9
- package/src/worker/interceptors/activity.js +0 -1
- package/src/worker/interceptors/workflow.js +0 -1
- package/src/worker/loader/workflows.js +16 -2
- package/src/worker/webpack_loaders/workflow_rewriter/index.mjs +3 -7
- package/src/worker/webpack_loaders/workflow_rewriter/rewrite_activity_calls.js +27 -7
- package/src/worker/webpack_loaders/workflow_validator/npm_workflow_export_resolve.js +5 -6
- package/src/sdk/README.md +0 -47
- package/src/sdk/helpers/component_metadata.d.ts +0 -17
- package/src/sdk/helpers/component_metadata.js +0 -6
- package/src/sdk/helpers/index.d.ts +0 -12
- package/src/sdk/helpers/index.js +0 -3
- package/src/sdk/helpers/objects.d.ts +0 -56
- package/src/sdk/helpers/objects.js +0 -8
- package/src/sdk/helpers/path.d.ts +0 -11
- package/src/sdk/helpers/path.js +0 -32
- package/src/sdk/runtime/context.d.ts +0 -30
- package/src/sdk/runtime/context.js +0 -15
- package/src/sdk/runtime/events.d.ts +0 -13
- package/src/sdk/runtime/events.js +0 -5
- package/src/sdk/runtime/index.d.ts +0 -12
- package/src/sdk/runtime/index.js +0 -3
- package/src/sdk/runtime/tracing.d.ts +0 -48
- package/src/sdk/runtime/tracing.js +0 -11
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import { fetchModelsPricing, Freshness } from './models_pricing.js';
|
|
2
|
+
import { BaseAttribute } from '#trace_attribute';
|
|
3
|
+
import { LLMGenerationUsage, LLMGenerationUsageItem } from './usage.js';
|
|
4
|
+
import { resolveWebSearchPpm } from './web_search.js';
|
|
5
|
+
import { Logger } from '#runtime_logger';
|
|
6
|
+
import Decimal from 'decimal.js';
|
|
7
|
+
|
|
8
|
+
// Checks whether a pricing value can be used in cost calculations.
|
|
9
|
+
const isValidNumber = v => Number.isFinite( v ) && v >= 0;
|
|
10
|
+
|
|
11
|
+
export class LLMGenerationCostItem {
|
|
12
|
+
static Status = Object.freeze( {
|
|
13
|
+
OK: 'ok',
|
|
14
|
+
FALLBACK: 'fallback',
|
|
15
|
+
UNCERTAIN: 'uncertain',
|
|
16
|
+
MISSING: 'missing'
|
|
17
|
+
} );
|
|
18
|
+
|
|
19
|
+
group;
|
|
20
|
+
label;
|
|
21
|
+
amount;
|
|
22
|
+
ppm;
|
|
23
|
+
total;
|
|
24
|
+
status;
|
|
25
|
+
|
|
26
|
+
constructor( group, label, amount, ppm, total, status, tier = undefined ) {
|
|
27
|
+
this.group = group;
|
|
28
|
+
this.label = label;
|
|
29
|
+
this.amount = amount;
|
|
30
|
+
this.ppm = ppm;
|
|
31
|
+
this.total = total;
|
|
32
|
+
this.status = status;
|
|
33
|
+
if ( tier ) {
|
|
34
|
+
this.tier = { type: tier.type, size: tier.size };
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
get key() {
|
|
39
|
+
return JSON.stringify( [ this.group, this.label, this.ppm, this.status, this.tier?.type, this.tier?.size ] );
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export class LLMGenerationCost extends BaseAttribute {
|
|
44
|
+
static TYPE = 'llm:generation:cost';
|
|
45
|
+
static Status = Object.freeze( {
|
|
46
|
+
PRECISE: 'precise',
|
|
47
|
+
IMPRECISE: 'imprecise',
|
|
48
|
+
INCOMPLETE: 'incomplete'
|
|
49
|
+
} );
|
|
50
|
+
providerId;
|
|
51
|
+
modelId;
|
|
52
|
+
input = null;
|
|
53
|
+
output = null;
|
|
54
|
+
tools = null;
|
|
55
|
+
total = null;
|
|
56
|
+
status = LLMGenerationCost.Status.INCOMPLETE;
|
|
57
|
+
pricingFreshness = null;
|
|
58
|
+
items = [];
|
|
59
|
+
|
|
60
|
+
constructor( modelId, providerId, items, usageStatus, pricingFreshness ) {
|
|
61
|
+
super( LLMGenerationCost.TYPE );
|
|
62
|
+
this.modelId = modelId;
|
|
63
|
+
this.providerId = providerId;
|
|
64
|
+
|
|
65
|
+
// group items with the same key, summing amount
|
|
66
|
+
this.items = Map.groupBy( items, e => e.key )
|
|
67
|
+
.values()
|
|
68
|
+
.toArray()
|
|
69
|
+
.map( items => {
|
|
70
|
+
if ( items.length === 1 ) {
|
|
71
|
+
return items[0];
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const { group, label, ppm, status, tier } = items[0];
|
|
75
|
+
const amount = items.reduce( ( sum, item ) => sum + item.amount, 0 );
|
|
76
|
+
const total = isValidNumber( ppm ) ? Decimal( amount ).div( 1_000_000 ).mul( ppm ).toNumber() : null;
|
|
77
|
+
return new LLMGenerationCostItem( group, label, amount, ppm, total, status, tier );
|
|
78
|
+
} );
|
|
79
|
+
|
|
80
|
+
this.pricingFreshness = pricingFreshness;
|
|
81
|
+
|
|
82
|
+
const meaningfulItems = this.items.filter( v => v.amount > 0 );
|
|
83
|
+
const hasMissingItems = meaningfulItems.some( v => v.status === LLMGenerationCostItem.Status.MISSING );
|
|
84
|
+
const hasFallbackItems = meaningfulItems.some( v => v.status === LLMGenerationCostItem.Status.FALLBACK );
|
|
85
|
+
const hasUncertainItems = meaningfulItems.some( v => v.status === LLMGenerationCostItem.Status.UNCERTAIN );
|
|
86
|
+
|
|
87
|
+
if ( hasMissingItems || usageStatus === LLMGenerationUsage.Status.INCOMPLETE ) {
|
|
88
|
+
this.status = LLMGenerationCost.Status.INCOMPLETE;
|
|
89
|
+
} else if ( hasFallbackItems || pricingFreshness === Freshness.SNAPSHOT || hasUncertainItems ) {
|
|
90
|
+
this.status = LLMGenerationCost.Status.IMPRECISE;
|
|
91
|
+
} else {
|
|
92
|
+
this.status = LLMGenerationCost.Status.PRECISE;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const sumGroup = group => {
|
|
96
|
+
const groupItems = this.items.filter( p => p.group === group && isValidNumber( p.total ) );
|
|
97
|
+
return groupItems.length > 0 ? groupItems.reduce( ( s, p ) => s.add( p.total ), Decimal( 0 ) ).toNumber() : null;
|
|
98
|
+
};
|
|
99
|
+
this.input = sumGroup( LLMGenerationUsageItem.Group.INPUT );
|
|
100
|
+
this.output = sumGroup( LLMGenerationUsageItem.Group.OUTPUT );
|
|
101
|
+
this.tools = sumGroup( LLMGenerationUsageItem.Group.TOOLS );
|
|
102
|
+
if ( isValidNumber( this.input ) || isValidNumber( this.output ) || isValidNumber( this.tools ) ) {
|
|
103
|
+
this.total = Decimal( this.input ?? 0 ).add( this.output ?? 0 ).add( this.tools ?? 0 ).toNumber();
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Selects the exact rate, then the first available fallback rate.
|
|
109
|
+
const resolveValue = values => {
|
|
110
|
+
if ( isValidNumber( values[0] ) ) {
|
|
111
|
+
return { ppm: values[0], status: LLMGenerationCostItem.Status.OK };
|
|
112
|
+
}
|
|
113
|
+
const fallback = values.slice( 1 ).find( isValidNumber );
|
|
114
|
+
if ( isValidNumber( fallback ) ) {
|
|
115
|
+
return { ppm: fallback, status: LLMGenerationCostItem.Status.FALLBACK };
|
|
116
|
+
}
|
|
117
|
+
return { ppm: null, status: LLMGenerationCostItem.Status.MISSING };
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
// Resolves the applicable token or provider-tool rate for one usage item.
|
|
121
|
+
const resolvePrice = ( { providerId, group, label, pricing, isReasoning } ) => {
|
|
122
|
+
// Tool charges are never token-priced: models.dev has no rate for them.
|
|
123
|
+
if ( group === LLMGenerationUsageItem.Group.TOOLS ) {
|
|
124
|
+
return resolveValue( [ resolveWebSearchPpm( providerId, label, isReasoning ) ] );
|
|
125
|
+
}
|
|
126
|
+
if ( !pricing ) {
|
|
127
|
+
return resolveValue( [] );
|
|
128
|
+
}
|
|
129
|
+
if ( group === LLMGenerationUsageItem.Group.OUTPUT ) {
|
|
130
|
+
const values = [ pricing.output ];
|
|
131
|
+
if ( label === 'reasoning' ) {
|
|
132
|
+
values.unshift( pricing.reasoning );
|
|
133
|
+
}
|
|
134
|
+
return resolveValue( values );
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const values = [ pricing.input ];
|
|
138
|
+
if ( label === 'cache_read' ) {
|
|
139
|
+
values.unshift( pricing.cache_read );
|
|
140
|
+
} else if ( label === 'cache_write' ) {
|
|
141
|
+
values.unshift( pricing.cache_write );
|
|
142
|
+
}
|
|
143
|
+
return resolveValue( values );
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
// Finds the highest context threshold crossed by this request's input.
|
|
147
|
+
const resolvePricingTier = ( modelPricing, input ) => {
|
|
148
|
+
// DESC sort by size
|
|
149
|
+
const supportedTiers = modelPricing.cost.tiers.filter( t => t?.tier?.type === 'context' && isValidNumber( t.tier.size ) );
|
|
150
|
+
const hasUnsupported = supportedTiers.length !== modelPricing.cost.tiers.length;
|
|
151
|
+
|
|
152
|
+
const sortedTiers = supportedTiers.toSorted( ( t1, t2 ) => t2.tier.size - t1.tier.size );
|
|
153
|
+
const tier = sortedTiers.find( tier => input > tier.tier.size );
|
|
154
|
+
|
|
155
|
+
return { tier, hasUnsupported };
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
// Calculates the price of each usage item
|
|
159
|
+
const calculateCostItems = ( { usage, pricing, isReasoning, uncertain } ) => {
|
|
160
|
+
const { providerId } = usage;
|
|
161
|
+
return usage.items.map( ( { group, label, amount } ) => {
|
|
162
|
+
const { ppm, status } = resolvePrice( { providerId, isReasoning, group, label, pricing } );
|
|
163
|
+
const total = isValidNumber( ppm ) ? Decimal( amount ).div( 1_000_000 ).mul( ppm ).toNumber() : null;
|
|
164
|
+
|
|
165
|
+
const isTool = group === LLMGenerationUsageItem.Group.TOOLS;
|
|
166
|
+
const isCostOk = status === LLMGenerationCostItem.Status.OK;
|
|
167
|
+
|
|
168
|
+
const finalStatus = !isTool && isCostOk && uncertain ? LLMGenerationCostItem.Status.UNCERTAIN : status;
|
|
169
|
+
|
|
170
|
+
const tier = !isTool && pricing?.tier?.type ? pricing.tier : null;
|
|
171
|
+
return new LLMGenerationCostItem( group, label, amount, ppm, total, finalStatus, tier );
|
|
172
|
+
} );
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
// Prices the total usage
|
|
176
|
+
const calculateStandardUsage = ( usage, modelPricing ) => {
|
|
177
|
+
const { reasoning: isReasoning, cost: pricing } = modelPricing ?? {};
|
|
178
|
+
return calculateCostItems( { usage, pricing, isReasoning } );
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
/* Prices the tiered usage:
|
|
182
|
+
- Multi-step + any incomplete step: base pricing, uncertain.
|
|
183
|
+
- Known request + no tier + no unsupported tiers: base, precise.
|
|
184
|
+
- Known request + no tier + unsupported tiers: base, uncertain.
|
|
185
|
+
- Known request + tier + no unsupported tiers: tier, precise.
|
|
186
|
+
- Known request + tier + unsupported tiers: tier, uncertain.
|
|
187
|
+
*/
|
|
188
|
+
const calculateTieredUsage = ( totalUsage, stepsUsage, modelPricing ) => {
|
|
189
|
+
const { cost: pricing, reasoning: isReasoning } = modelPricing;
|
|
190
|
+
|
|
191
|
+
const isMultiStep = stepsUsage.length > 1;
|
|
192
|
+
const hasIncompleteSteps = stepsUsage.some( u => u?.status !== LLMGenerationUsage.Status.COMPLETE );
|
|
193
|
+
|
|
194
|
+
// incomplete multi-steps fallback to calculate total usage with NO tiers, since token counts are unreliable
|
|
195
|
+
if ( isMultiStep && hasIncompleteSteps ) {
|
|
196
|
+
return calculateCostItems( { usage: totalUsage, pricing, isReasoning, uncertain: true } );
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
return ( isMultiStep ? stepsUsage : [ totalUsage ] ).flatMap( usage => {
|
|
200
|
+
// output usage can't have tier billing
|
|
201
|
+
if ( !isValidNumber( usage.input ) ) {
|
|
202
|
+
return calculateCostItems( { usage, pricing, isReasoning } );
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const pricingTier = resolvePricingTier( modelPricing, usage.input );
|
|
206
|
+
|
|
207
|
+
// if there is a matching tier used, otherwise use base pricing
|
|
208
|
+
const finalPricing = pricingTier.tier ?? pricing;
|
|
209
|
+
|
|
210
|
+
// it will be uncertain if unsupported tiers exists
|
|
211
|
+
return calculateCostItems( { usage, pricing: finalPricing, isReasoning, uncertain: pricingTier.hasUnsupported } );
|
|
212
|
+
} );
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
// Returns whether model pricing has tier info or not
|
|
216
|
+
const hasTiers = modelPricing => Array.isArray( modelPricing?.cost?.tiers ) && modelPricing.cost.tiers.length > 0;
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Calculates the cost of an LLM call based on the LLMGenerationUsage.
|
|
220
|
+
*
|
|
221
|
+
* @param {LLMGenerationUsage} usage - Normalized LLM generation usage
|
|
222
|
+
* @param {LLMGenerationUsage[]} stepsUsage - Per-request usage for multi-step calls
|
|
223
|
+
* @returns {Promise<LLMGenerationCost | null>} LLM generation cost with input, output, total and breakdown
|
|
224
|
+
*/
|
|
225
|
+
export const calculateCosts = async ( usage, stepsUsage ) => {
|
|
226
|
+
const { models, freshness: pricingFreshness } = await fetchModelsPricing();
|
|
227
|
+
|
|
228
|
+
if ( !models ) {
|
|
229
|
+
Logger.warn( 'Failed to fetch models pricing', { namespace: 'LLM' } );
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const { providerId, modelId } = usage;
|
|
234
|
+
|
|
235
|
+
const modelPricing = models.get( `${providerId}/${modelId}` );
|
|
236
|
+
if ( !modelPricing ) {
|
|
237
|
+
Logger.warn( 'Missing pricing reference for model', { namespace: 'LLM', modelId, providerId } );
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const items = hasTiers( modelPricing ) ? calculateTieredUsage( usage, stepsUsage, modelPricing ) : calculateStandardUsage( usage, modelPricing );
|
|
241
|
+
|
|
242
|
+
const unrated = items.find( v => v.group === LLMGenerationUsageItem.Group.TOOLS && v.status === LLMGenerationCostItem.Status.MISSING );
|
|
243
|
+
if ( unrated ) {
|
|
244
|
+
Logger.warn( 'Tool call with no rate for model', { namespace: 'LLM', modelId, providerId, type: unrated.label } );
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
return new LLMGenerationCost( modelId, providerId, items, usage.status, pricingFreshness );
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Calculates a cost using the legacy aggregate pricing behavior.
|
|
252
|
+
*
|
|
253
|
+
* @param {LLMGenerationUsage} usage - Normalized aggregate LLM generation usage
|
|
254
|
+
* @returns {Promise<LLMGenerationCost | null>} Cost compatible with the legacy conversion
|
|
255
|
+
*/
|
|
256
|
+
export const calculateLegacyCosts = async usage => {
|
|
257
|
+
const { models, freshness: pricingFreshness } = await fetchModelsPricing();
|
|
258
|
+
if ( !models ) {
|
|
259
|
+
return null;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const { providerId, modelId } = usage;
|
|
263
|
+
const modelPricing = models.get( `${providerId}/${modelId}` );
|
|
264
|
+
const items = calculateStandardUsage( usage, modelPricing );
|
|
265
|
+
|
|
266
|
+
return new LLMGenerationCost( modelId, providerId, items, usage.status, pricingFreshness );
|
|
267
|
+
};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import * as ai from 'ai';
|
|
2
|
+
import { FatalError, TransparentFatalError } from '#errors';
|
|
3
|
+
|
|
4
|
+
const nonRetryableAiSdkErrorTypes = [
|
|
5
|
+
ai.InvalidArgumentError, // Invalid call settings are deterministic caller bugs, so retrying the same activity cannot fix them.
|
|
6
|
+
ai.InvalidDataContentError, // Invalid media content has the wrong local shape/encoding and will fail again with the same input.
|
|
7
|
+
ai.InvalidPromptError, // Invalid prompt structure is a deterministic request-construction error.
|
|
8
|
+
ai.LoadAPIKeyError, // Missing or invalid API key configuration will not change during an activity retry.
|
|
9
|
+
ai.LoadSettingError, // Missing or invalid provider settings are deployment/configuration problems.
|
|
10
|
+
ai.NoImageGeneratedError, // Image generation completed provider calls but collected zero images; repeating identical input is not useful.
|
|
11
|
+
ai.NoSuchProviderError, // A missing provider id is a deterministic provider registry/configuration error.
|
|
12
|
+
ai.NoSuchModelError, // A missing model id is a deterministic provider/model configuration error.
|
|
13
|
+
ai.UnsupportedFunctionalityError // The selected model/output mode does not support the requested feature.
|
|
14
|
+
];
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Maps an AI SDK error to a framework error:
|
|
18
|
+
* - AI SDK Unrecoverable error types become TransparentFatalErrors;
|
|
19
|
+
* - AI SDK API error with isRetryable=false become TransparentFatalErrors;
|
|
20
|
+
* Some errors are not mapped:
|
|
21
|
+
* - Grammar which technically are isRetryable=false, will be rethrown, because they are actually transient;
|
|
22
|
+
* - Other errors are rethrown as well;
|
|
23
|
+
*
|
|
24
|
+
* @param {object} error - Original Error
|
|
25
|
+
* @returns {object} A new Error
|
|
26
|
+
*/
|
|
27
|
+
export const mapAiError = error => {
|
|
28
|
+
if ( !( error instanceof Error ) ) {
|
|
29
|
+
return error;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if ( error instanceof FatalError ) {
|
|
33
|
+
return error;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const isApiError = ai.APICallError.isInstance( error );
|
|
37
|
+
const isGrammarCompilationError = error.message === 'Grammar compilation timed out.';
|
|
38
|
+
|
|
39
|
+
// This error is actually transient, so instead of FatalError, return it
|
|
40
|
+
if ( isApiError && error.statusCode === 400 && isGrammarCompilationError ) {
|
|
41
|
+
return error;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Non-retryable API failures are already classified by AI SDK as permanent provider failures.
|
|
45
|
+
if ( isApiError && !error.isRetryable ) {
|
|
46
|
+
return new TransparentFatalError( error );
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if ( nonRetryableAiSdkErrorTypes.some( E => E.isInstance( error ) ) ) {
|
|
50
|
+
return new TransparentFatalError( error );
|
|
51
|
+
}
|
|
52
|
+
return error;
|
|
53
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { join } from 'path';
|
|
2
|
+
import { readdirSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { FatalError } from '#errors';
|
|
4
|
+
|
|
5
|
+
const scanDir = dir => {
|
|
6
|
+
try {
|
|
7
|
+
return readdirSync( dir, { withFileTypes: true } );
|
|
8
|
+
} catch ( error ) {
|
|
9
|
+
throw new FatalError( `Error scanning directory "${dir}"`, { cause: error } );
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
const readFile = path => {
|
|
14
|
+
try {
|
|
15
|
+
return readFileSync( path, 'utf-8' );
|
|
16
|
+
} catch ( error ) {
|
|
17
|
+
throw new FatalError( `Error reading file "${path}"`, { cause: error } );
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Recursively search for a file by name and return both its content and containing directory.
|
|
23
|
+
*
|
|
24
|
+
* @param {string} dir - Directory to search
|
|
25
|
+
* @param {string} name - File name to find
|
|
26
|
+
* @returns {{ content: string, dir: string } | null}
|
|
27
|
+
*/
|
|
28
|
+
export const searchAndReadFile = ( dir, name ) => {
|
|
29
|
+
for ( const entry of scanDir( dir ) ) {
|
|
30
|
+
const path = join( dir, entry.name );
|
|
31
|
+
if ( entry.name === name ) {
|
|
32
|
+
return { dir, content: readFile( path ) };
|
|
33
|
+
}
|
|
34
|
+
if ( entry.isDirectory() && !entry.isSymbolicLink() ) {
|
|
35
|
+
const result = searchAndReadFile( path, name );
|
|
36
|
+
if ( result ) {
|
|
37
|
+
return result;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return null;
|
|
42
|
+
};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { ValidationError } from '#errors';
|
|
2
|
+
|
|
3
|
+
const envVar = 'GCP_CREDENTIALS_JSON';
|
|
4
|
+
|
|
5
|
+
const unescapeLinebreaks = v => v.replaceAll( '\\n', '\n' );
|
|
6
|
+
|
|
7
|
+
const decodeBase64 = v => Buffer.from( v, 'base64' ).toString( 'utf8' );
|
|
8
|
+
|
|
9
|
+
const parseJson = v => {
|
|
10
|
+
try {
|
|
11
|
+
return JSON.parse( v );
|
|
12
|
+
} catch ( cause ) {
|
|
13
|
+
throw new ValidationError( `Invalid ${envVar}: value is neither JSON nor base64 encoded JSON`, { cause } );
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export const resolveGoogleVertexAuthOptions = () => {
|
|
18
|
+
const value = process.env[envVar]?.trim();
|
|
19
|
+
|
|
20
|
+
if ( !value ) {
|
|
21
|
+
return {};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const credentials = parseJson( value.startsWith( '{' ) ? value : decodeBase64( value ) );
|
|
25
|
+
|
|
26
|
+
if ( credentials.private_key ) {
|
|
27
|
+
credentials.private_key = unescapeLinebreaks( credentials.private_key );
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
return { googleAuthOptions: { credentials } };
|
|
31
|
+
};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { Logger } from '#runtime_logger';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Get the approximate file size from a base64 string.
|
|
5
|
+
* @param {string} b64data
|
|
6
|
+
* @returns {number} Size in bytes
|
|
7
|
+
*/
|
|
8
|
+
export const calculateBase64FileSize = b64data => {
|
|
9
|
+
if ( typeof b64data !== 'string' ) {
|
|
10
|
+
return null;
|
|
11
|
+
}
|
|
12
|
+
const baseSize = b64data.length * ( 3 / 4 );
|
|
13
|
+
const paddingSize = [ b64data.at( -2 ), b64data.at( -1 ) ].filter( v => v === '=' ).length;
|
|
14
|
+
return baseSize - paddingSize;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Return a serialized version of the images from the AI SDK response.
|
|
19
|
+
* It contains only the file size and the media-type
|
|
20
|
+
*
|
|
21
|
+
* @param {object} response
|
|
22
|
+
* @returns {Array<{size: number, mediaType: string}>}
|
|
23
|
+
*/
|
|
24
|
+
export const serializeImagesFromResponse = response => {
|
|
25
|
+
try {
|
|
26
|
+
if ( !Array.isArray( response?.images ) ) {
|
|
27
|
+
return [];
|
|
28
|
+
}
|
|
29
|
+
return response.images
|
|
30
|
+
.filter( image => image !== null && typeof image === 'object' )
|
|
31
|
+
.map( ( { base64, mediaType } ) => ( { size: calculateBase64FileSize( base64 ), mediaType } ) );
|
|
32
|
+
|
|
33
|
+
} catch ( error ) {
|
|
34
|
+
Logger.error( 'Image serialization failed', { namespace: 'LLM', error: error?.message || String( error ) } );
|
|
35
|
+
return [];
|
|
36
|
+
}
|
|
37
|
+
};
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { BaseAttribute } from '#trace_attribute';
|
|
2
|
+
import Decimal from 'decimal.js';
|
|
3
|
+
|
|
4
|
+
const exists = v => Number.isFinite( v );
|
|
5
|
+
|
|
6
|
+
/** Legacy priced usage attribute retained for trace compatibility. */
|
|
7
|
+
export class LLMUsageLegacy extends BaseAttribute {
|
|
8
|
+
static TYPE = 'llm:usage';
|
|
9
|
+
modelId;
|
|
10
|
+
usage = [];
|
|
11
|
+
total;
|
|
12
|
+
tokensUsed;
|
|
13
|
+
|
|
14
|
+
constructor( modelId, usage ) {
|
|
15
|
+
super( LLMUsageLegacy.TYPE );
|
|
16
|
+
this.modelId = modelId;
|
|
17
|
+
this.usage = usage;
|
|
18
|
+
this.total = Decimal( 0 );
|
|
19
|
+
this.tokensUsed = Decimal( 0 );
|
|
20
|
+
|
|
21
|
+
for ( const item of usage ) {
|
|
22
|
+
item.total = Decimal( item.amount ).div( 1_000_000 ).mul( item.ppm ).toNumber();
|
|
23
|
+
this.total = this.total.add( item.total );
|
|
24
|
+
this.tokensUsed = this.tokensUsed.add( item.amount );
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
this.total = this.total.toNumber();
|
|
28
|
+
this.tokensUsed = this.tokensUsed.toNumber();
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const convertCostToLegacy = cost => {
|
|
33
|
+
if ( !cost || cost.items.every( v => v.status === 'missing' ) ) {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const usage = [];
|
|
38
|
+
|
|
39
|
+
// items
|
|
40
|
+
const inputItem = cost.items.find( ( { group, label, total } ) => group === 'input' && !label && exists( total ) );
|
|
41
|
+
const noCacheItem = cost.items.find( ( { label, total } ) => label === 'no_cache' && exists( total ) );
|
|
42
|
+
const cacheReadItem = cost.items.find( ( { label } ) => label === 'cache_read' ); // even when it doesn't have total
|
|
43
|
+
const cacheWriteItem = cost.items.find( ( { label, total } ) => label === 'cache_write' && exists( total ) );
|
|
44
|
+
const outputItem = cost.items.find( ( { group, label, total } ) => group === 'output' && !label && exists( total ) );
|
|
45
|
+
const textItem = cost.items.find( ( { label, total } ) => label === 'text' && exists( total ) );
|
|
46
|
+
const reasoningItem = cost.items.find( ( { label, total } ) => label === 'reasoning' && exists( total ) );
|
|
47
|
+
|
|
48
|
+
if ( inputItem ) {
|
|
49
|
+
usage.push( { type: 'input', ppm: inputItem.ppm, amount: inputItem.amount } );
|
|
50
|
+
} else {
|
|
51
|
+
if ( noCacheItem || cacheWriteItem ) {
|
|
52
|
+
const totalInput = ( noCacheItem?.amount ?? 0 ) + ( cacheWriteItem?.amount ?? 0 );
|
|
53
|
+
const ppm = noCacheItem?.ppm ?? cacheWriteItem?.ppm;
|
|
54
|
+
usage.push( { type: 'input', ppm, amount: totalInput } );
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if ( cacheReadItem ) {
|
|
58
|
+
const ppm = [ 'fallback', 'missing' ].includes( cacheReadItem.status ) ? 0 : cacheReadItem.ppm;
|
|
59
|
+
usage.push( { type: 'input_cached', ppm, amount: cacheReadItem.amount } );
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if ( outputItem ) {
|
|
64
|
+
usage.push( { type: 'output', ppm: outputItem.ppm, amount: outputItem.amount } );
|
|
65
|
+
} else {
|
|
66
|
+
if ( textItem ) {
|
|
67
|
+
usage.push( { type: 'output', ppm: textItem.ppm, amount: textItem.amount } );
|
|
68
|
+
}
|
|
69
|
+
if ( reasoningItem ) {
|
|
70
|
+
usage.push( { type: 'reasoning', ppm: reasoningItem.ppm, amount: reasoningItem.amount } );
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return new LLMUsageLegacy( cost.modelId, usage );
|
|
75
|
+
};
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { parseLLMUsage } from './usage.js';
|
|
2
|
+
import { calculateCosts, calculateLegacyCosts } from './cost.js';
|
|
3
|
+
import { stepEventBus } from '#bus';
|
|
4
|
+
import { addEventActionWithContext, EventAction } from '#tracing';
|
|
5
|
+
import { Logger } from '#runtime_logger';
|
|
6
|
+
import { convertCostToLegacy } from './legacy_cost_attribute.js';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Collects the usage of a single LLM call and bills it once.
|
|
10
|
+
*
|
|
11
|
+
* Steps are recorded as the SDK lifecycle reports them, and the response is handed to `bill()` by
|
|
12
|
+
* the paths that have one, so a call that throws after the model ran is still billed for what it
|
|
13
|
+
* spent. `bill()` parses the usage, costs it, attaches both as trace attributes and emits the
|
|
14
|
+
* metering events; it never throws.
|
|
15
|
+
*/
|
|
16
|
+
export class Metering {
|
|
17
|
+
#recordedSteps = [];
|
|
18
|
+
#billed = false;
|
|
19
|
+
#prompt;
|
|
20
|
+
#traceId;
|
|
21
|
+
#toolIdsByName;
|
|
22
|
+
#attributes = {
|
|
23
|
+
usage: null,
|
|
24
|
+
cost: null,
|
|
25
|
+
legacy: null
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
async #createAttributes( { usage, steps } ) {
|
|
29
|
+
const totalUsage = parseLLMUsage( { prompt: this.#prompt, usage, steps, toolIdsByName: this.#toolIdsByName } );
|
|
30
|
+
const stepsUsage = steps.map( step => parseLLMUsage( {
|
|
31
|
+
prompt: this.#prompt,
|
|
32
|
+
usage: step.usage,
|
|
33
|
+
steps: [ step ],
|
|
34
|
+
toolIdsByName: this.#toolIdsByName
|
|
35
|
+
} ) );
|
|
36
|
+
|
|
37
|
+
this.#attributes.usage = totalUsage;
|
|
38
|
+
if ( this.#attributes.usage ) {
|
|
39
|
+
this.#attributes.cost = await calculateCosts( this.#attributes.usage, stepsUsage );
|
|
40
|
+
|
|
41
|
+
if ( this.#attributes.cost ) {
|
|
42
|
+
// @TEMP Preserve the deprecated event and trace attribute for legacy consumers.
|
|
43
|
+
const legacyCost = await calculateLegacyCosts( this.#attributes.usage );
|
|
44
|
+
this.#attributes.legacy = convertCostToLegacy( legacyCost );
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
#attachAttributes() {
|
|
50
|
+
if ( this.#attributes.usage ) {
|
|
51
|
+
addEventActionWithContext( EventAction.ADD_ATTR, { id: this.#traceId, details: this.#attributes.usage } );
|
|
52
|
+
}
|
|
53
|
+
if ( this.#attributes.cost ) {
|
|
54
|
+
addEventActionWithContext( EventAction.ADD_ATTR, { id: this.#traceId, details: this.#attributes.cost } );
|
|
55
|
+
}
|
|
56
|
+
if ( this.#attributes.legacy ) {
|
|
57
|
+
addEventActionWithContext( EventAction.ADD_ATTR, { id: this.#traceId, details: this.#attributes.legacy } );
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
#emitEvents() {
|
|
62
|
+
if ( this.#attributes.usage ) {
|
|
63
|
+
stepEventBus.emit( 'sdk:llm:generation:metering', structuredClone( { cost: this.#attributes.cost, usage: this.#attributes.usage } ) );
|
|
64
|
+
}
|
|
65
|
+
if ( this.#attributes.legacy ) {
|
|
66
|
+
stepEventBus.emit( 'sdk:cost:llm:request', structuredClone( this.#attributes.legacy ) );
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* @param {object} args
|
|
72
|
+
* @param {string} args.traceId - Trace event the usage and cost attributes are attached to
|
|
73
|
+
* @param {object} args.prompt - Loaded prompt (`config.provider` / `config.model` used for cost)
|
|
74
|
+
* @param {Record<string, string>} [args.toolIdsByName] - Provider tool ids keyed by configured name
|
|
75
|
+
*/
|
|
76
|
+
constructor( { traceId, prompt, toolIdsByName } ) {
|
|
77
|
+
this.#traceId = traceId;
|
|
78
|
+
this.#prompt = prompt;
|
|
79
|
+
this.#toolIdsByName = toolIdsByName;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Records a completed step, used as the usage source when the call ends without a response.
|
|
84
|
+
*
|
|
85
|
+
* @param {object} step - AI SDK step
|
|
86
|
+
*/
|
|
87
|
+
recordStep = step => {
|
|
88
|
+
if ( !this.#billed ) {
|
|
89
|
+
this.#recordedSteps.push( step );
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Bills the recorded usage: parses it, costs it, attaches the trace attributes and emits the
|
|
95
|
+
* metering events. Later calls and later records are ignored, so it is safe to call from every
|
|
96
|
+
* path that can end the call. Read the result from `attributes`.
|
|
97
|
+
*
|
|
98
|
+
* An empty collector is not a final answer: the SDK reports a stream error before the steps that
|
|
99
|
+
* preceded it, so billing stays open until there is usage or a step to report.
|
|
100
|
+
*
|
|
101
|
+
* @param {object} [response] - AI SDK response, whose aggregate usage and steps take precedence
|
|
102
|
+
* over the recorded steps; omitted by the paths that end without one
|
|
103
|
+
* @returns {Promise<void>}
|
|
104
|
+
*/
|
|
105
|
+
bill = async ( response = null ) => {
|
|
106
|
+
if ( this.#billed ) {
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
try {
|
|
111
|
+
const responseSteps = response?.steps;
|
|
112
|
+
const steps = Array.isArray( responseSteps ) && responseSteps.length > 0 ? responseSteps : this.#recordedSteps;
|
|
113
|
+
const usage = response?.usage;
|
|
114
|
+
|
|
115
|
+
if ( !usage && steps.length === 0 ) {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
this.#billed = true;
|
|
120
|
+
|
|
121
|
+
await this.#createAttributes( { usage, steps } );
|
|
122
|
+
this.#attachAttributes();
|
|
123
|
+
this.#emitEvents();
|
|
124
|
+
|
|
125
|
+
} catch ( error ) {
|
|
126
|
+
Logger.error( 'Metering failed', { namespace: 'LLM', error: error?.message || String( error ) } );
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Attributes produced by `bill()`; each one is null until billed, and stays null when there is
|
|
132
|
+
* nothing to report.
|
|
133
|
+
*
|
|
134
|
+
* @returns {{ usage: object|null, cost: object|null, legacy: object|null }}
|
|
135
|
+
*/
|
|
136
|
+
get attributes() {
|
|
137
|
+
return this.#attributes;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { ValidationError } from '#errors';
|
|
2
|
+
import { getProvider } from '../ai_provider.js';
|
|
3
|
+
|
|
4
|
+
/** Load a model from a prompt */
|
|
5
|
+
export const loadTextModel = prompt => getProvider( prompt.config.provider )( prompt.config.model );
|
|
6
|
+
|
|
7
|
+
/** Load an image model from a prompt. */
|
|
8
|
+
export const loadImageModel = prompt => {
|
|
9
|
+
const provider = getProvider( prompt.config.provider );
|
|
10
|
+
const imageModelFactory = provider.image ?? provider.imageModel;
|
|
11
|
+
if ( typeof imageModelFactory !== 'function' ) {
|
|
12
|
+
throw new ValidationError( `Provider "${prompt.config.provider}" used by prompt "${prompt.name}" does not support image models.` );
|
|
13
|
+
}
|
|
14
|
+
return imageModelFactory( prompt.config.model );
|
|
15
|
+
};
|