@outputai/core 0.15.1-next.ff9e1ab.0 → 0.16.1-next.219890f.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.
Files changed (114) hide show
  1. package/dist/credentials/index.d.ts +1 -1
  2. package/dist/credentials/types.d.ts +4 -4
  3. package/dist/evals/aggregate.d.ts +2 -0
  4. package/dist/evals/aggregate.js +11 -0
  5. package/dist/evals/eval_workflow.d.ts +20 -0
  6. package/dist/evals/eval_workflow.js +98 -0
  7. package/dist/evals/index.d.ts +7 -0
  8. package/dist/evals/index.js +4 -0
  9. package/dist/evals/interpret.d.ts +3 -0
  10. package/dist/evals/interpret.js +40 -0
  11. package/dist/evals/schemas.d.ts +96 -0
  12. package/dist/evals/schemas.js +60 -0
  13. package/dist/evals/verdict.d.ts +27 -0
  14. package/dist/evals/verdict.js +109 -0
  15. package/dist/evals/verify.d.ts +42 -0
  16. package/dist/evals/verify.js +19 -0
  17. package/package.json +64 -14
  18. package/src/consts.d.ts +2 -0
  19. package/src/consts.js +4 -3
  20. package/src/helpers/error_serializer.js +26 -5
  21. package/src/helpers/fetch.js +21 -9
  22. package/src/helpers/number.js +20 -0
  23. package/src/helpers/path.js +34 -0
  24. package/src/helpers/redact.js +2 -1
  25. package/src/hooks/index.js +1 -1
  26. package/src/http/config.js +10 -0
  27. package/src/http/cost.d.ts +20 -0
  28. package/src/http/cost.js +41 -0
  29. package/src/http/fetch/events.js +10 -0
  30. package/src/http/fetch/index.d.ts +24 -0
  31. package/src/http/fetch/index.js +78 -0
  32. package/src/http/fetch/logger.d.ts +10 -0
  33. package/src/http/fetch/logger.js +56 -0
  34. package/src/http/index.d.ts +28 -0
  35. package/src/http/index.js +9 -0
  36. package/src/http/ky/index.d.ts +25 -0
  37. package/src/http/ky/index.js +10 -0
  38. package/src/http/request_tag.js +30 -0
  39. package/src/interface/index.d.ts +1 -0
  40. package/src/interface/logger.js +4 -4
  41. package/src/llm/agent.js +147 -0
  42. package/src/llm/ai_provider.js +131 -0
  43. package/src/llm/ai_sdk_options.js +126 -0
  44. package/src/llm/consts.js +6 -0
  45. package/src/llm/deprecated_provider_aliases.js +8 -0
  46. package/src/llm/generate.js +98 -0
  47. package/src/llm/index.d.ts +715 -0
  48. package/src/llm/index.js +6 -0
  49. package/src/llm/judge.js +48 -0
  50. package/src/llm/prompt/content.js +70 -0
  51. package/src/llm/prompt/interpolations.js +58 -0
  52. package/src/llm/prompt/loader.js +67 -0
  53. package/src/llm/prompt/markup/attributes.js +52 -0
  54. package/src/llm/prompt/markup/nodes.js +71 -0
  55. package/src/llm/prompt/markup/tokenizer.js +3 -0
  56. package/src/llm/prompt/markup/tokens.js +26 -0
  57. package/src/llm/prompt/validations.js +129 -0
  58. package/src/llm/utils/attributes/llm_generation.js +28 -0
  59. package/src/llm/utils/attributes/llm_generation_cost.js +99 -0
  60. package/src/llm/utils/attributes/llm_generation_usage.js +51 -0
  61. package/src/llm/utils/cost.js +168 -0
  62. package/src/llm/utils/error_handler.js +53 -0
  63. package/src/llm/utils/file.js +42 -0
  64. package/src/llm/utils/google_vertex_auth.js +31 -0
  65. package/src/llm/utils/image.js +37 -0
  66. package/src/llm/utils/legacy_cost_attribute.js +75 -0
  67. package/src/llm/utils/metering.js +148 -0
  68. package/src/llm/utils/models.js +15 -0
  69. package/src/llm/utils/models_pricing.js +96 -0
  70. package/src/llm/utils/models_pricing_snapshot.json +4711 -0
  71. package/src/llm/utils/request_details.js +7 -0
  72. package/src/llm/utils/skills.js +74 -0
  73. package/src/llm/utils/sources.js +73 -0
  74. package/src/llm/utils/stream.js +75 -0
  75. package/src/llm/utils/tools.js +62 -0
  76. package/src/llm/utils/usage.js +101 -0
  77. package/src/llm/utils/usage_tools.js +23 -0
  78. package/src/llm/utils/web_search.js +155 -0
  79. package/src/llm/utils/wrap.js +279 -0
  80. package/src/llm/validations.js +234 -0
  81. package/src/tracing/trace_attribute.d.ts +0 -17
  82. package/src/tracing/trace_attribute.js +1 -29
  83. package/src/worker/bundler_options.js +1 -9
  84. package/src/worker/configs.js +63 -15
  85. package/src/worker/global_functions.js +11 -6
  86. package/src/worker/index.js +42 -55
  87. package/src/worker/interceptors/activity.js +0 -1
  88. package/src/worker/interceptors/workflow.js +0 -1
  89. package/src/worker/loader/workflows.js +16 -2
  90. package/src/worker/log_hooks.js +8 -0
  91. package/src/worker/shutdown.js +5 -11
  92. package/src/worker/telemetry.js +122 -2
  93. package/src/worker/temporal_logger.js +45 -12
  94. package/src/worker/webpack_loaders/workflow_rewriter/index.mjs +3 -7
  95. package/src/worker/webpack_loaders/workflow_rewriter/rewrite_activity_calls.js +27 -7
  96. package/src/worker/webpack_loaders/workflow_validator/npm_workflow_export_resolve.js +5 -6
  97. package/src/worker/worker_options.js +43 -0
  98. package/src/sdk/README.md +0 -47
  99. package/src/sdk/helpers/component_metadata.d.ts +0 -17
  100. package/src/sdk/helpers/component_metadata.js +0 -6
  101. package/src/sdk/helpers/index.d.ts +0 -12
  102. package/src/sdk/helpers/index.js +0 -3
  103. package/src/sdk/helpers/objects.d.ts +0 -56
  104. package/src/sdk/helpers/objects.js +0 -8
  105. package/src/sdk/helpers/path.d.ts +0 -11
  106. package/src/sdk/helpers/path.js +0 -32
  107. package/src/sdk/runtime/context.d.ts +0 -30
  108. package/src/sdk/runtime/context.js +0 -15
  109. package/src/sdk/runtime/events.d.ts +0 -13
  110. package/src/sdk/runtime/events.js +0 -5
  111. package/src/sdk/runtime/index.d.ts +0 -12
  112. package/src/sdk/runtime/index.js +0 -3
  113. package/src/sdk/runtime/tracing.d.ts +0 -48
  114. package/src/sdk/runtime/tracing.js +0 -11
@@ -0,0 +1,51 @@
1
+ import Decimal from 'decimal.js';
2
+ import { isNonNegativeInteger } from '#helpers/number';
3
+ import { LLMGeneration } from './llm_generation.js';
4
+
5
+ export class LLMGenerationUsageItem {
6
+ static Group = { INPUT: 'input', OUTPUT: 'output', TOOLS: 'tools' };
7
+
8
+ group;
9
+ label;
10
+ amount;
11
+
12
+ constructor( group, label, amount ) {
13
+ this.group = group;
14
+ this.label = label;
15
+ this.amount = amount;
16
+ }
17
+ }
18
+
19
+ export class LLMGenerationUsage extends LLMGeneration {
20
+ static TYPE = 'llm:generation:usage';
21
+
22
+ static Status = Object.freeze( {
23
+ COMPLETE: 'complete',
24
+ INCOMPLETE: 'incomplete'
25
+ } );
26
+
27
+ status = LLMGenerationUsage.Status.INCOMPLETE;
28
+ input = null;
29
+ output = null;
30
+ total = null;
31
+ items = [];
32
+
33
+ constructor( modelId, providerId, promptName, requestDetails, items ) {
34
+ super( LLMGenerationUsage.TYPE, modelId, providerId, promptName, requestDetails );
35
+
36
+ this.items = items;
37
+ const inputItems = items.filter( p => p.group === LLMGenerationUsageItem.Group.INPUT );
38
+ if ( inputItems.length > 0 ) {
39
+ this.input = inputItems.reduce( ( s, p ) => s.add( p.amount ), Decimal( 0 ) ).toNumber();
40
+ }
41
+ const outputItems = items.filter( p => p.group === LLMGenerationUsageItem.Group.OUTPUT );
42
+ if ( outputItems.length > 0 ) {
43
+ this.output = outputItems.reduce( ( s, p ) => s.add( p.amount ), Decimal( 0 ) ).toNumber();
44
+ }
45
+
46
+ if ( isNonNegativeInteger( this.input ) || isNonNegativeInteger( this.output ) ) {
47
+ this.total = ( this.input ?? 0 ) + ( this.output ?? 0 );
48
+ }
49
+ this.status = LLMGenerationUsage.Status[isNonNegativeInteger( this.input ) && isNonNegativeInteger( this.output ) ? 'COMPLETE' : 'INCOMPLETE'];
50
+ }
51
+ }
@@ -0,0 +1,168 @@
1
+ import { fetchModelsPricing } from './models_pricing.js';
2
+ import { LLMGenerationUsage, LLMGenerationUsageItem } from './attributes/llm_generation_usage.js';
3
+ import { resolveWebSearchPpm } from './web_search.js';
4
+ import { Logger } from '#runtime_logger';
5
+ import { LLMGenerationCost, LLMGenerationCostItem } from './attributes/llm_generation_cost.js';
6
+ import Decimal from 'decimal.js';
7
+ import { isNonNegativeNumber } from '#helpers/number';
8
+
9
+ // Selects the exact rate, then the first available fallback rate.
10
+ const resolveValue = values => {
11
+ if ( isNonNegativeNumber( values[0] ) ) {
12
+ return { ppm: values[0], status: LLMGenerationCostItem.Status.OK };
13
+ }
14
+ const fallback = values.slice( 1 ).find( isNonNegativeNumber );
15
+ if ( isNonNegativeNumber( fallback ) ) {
16
+ return { ppm: fallback, status: LLMGenerationCostItem.Status.FALLBACK };
17
+ }
18
+ return { ppm: null, status: LLMGenerationCostItem.Status.MISSING };
19
+ };
20
+
21
+ // Resolves the applicable token or provider-tool rate for one usage item.
22
+ const resolvePrice = ( { providerId, group, label, pricing, isReasoning } ) => {
23
+ // Tool charges are never token-priced: models.dev has no rate for them.
24
+ if ( group === LLMGenerationUsageItem.Group.TOOLS ) {
25
+ return resolveValue( [ resolveWebSearchPpm( providerId, label, isReasoning ) ] );
26
+ }
27
+ if ( !pricing ) {
28
+ return resolveValue( [] );
29
+ }
30
+ if ( group === LLMGenerationUsageItem.Group.OUTPUT ) {
31
+ const values = [ pricing.output ];
32
+ if ( label === 'reasoning' ) {
33
+ values.unshift( pricing.reasoning );
34
+ }
35
+ return resolveValue( values );
36
+ }
37
+
38
+ const values = [ pricing.input ];
39
+ if ( label === 'cache_read' ) {
40
+ values.unshift( pricing.cache_read );
41
+ } else if ( label === 'cache_write' ) {
42
+ values.unshift( pricing.cache_write );
43
+ }
44
+ return resolveValue( values );
45
+ };
46
+
47
+ // Finds the highest context threshold crossed by this request's input.
48
+ const resolvePricingTier = ( modelPricing, input ) => {
49
+ // DESC sort by size
50
+ const supportedTiers = modelPricing.cost.tiers.filter( t => t?.tier?.type === 'context' && isNonNegativeNumber( t.tier.size ) );
51
+ const hasUnsupported = supportedTiers.length !== modelPricing.cost.tiers.length;
52
+
53
+ const sortedTiers = supportedTiers.toSorted( ( t1, t2 ) => t2.tier.size - t1.tier.size );
54
+ const tier = sortedTiers.find( tier => input > tier.tier.size );
55
+
56
+ return { tier, hasUnsupported };
57
+ };
58
+
59
+ // Calculates the price of each usage item
60
+ const calculateCostItems = ( { usage, pricing, isReasoning, uncertain } ) => {
61
+ const { providerId } = usage;
62
+ return usage.items.map( ( { group, label, amount } ) => {
63
+ const { ppm, status } = resolvePrice( { providerId, isReasoning, group, label, pricing } );
64
+ const total = isNonNegativeNumber( ppm ) ? Decimal( amount ).div( 1_000_000 ).mul( ppm ).toNumber() : null;
65
+
66
+ const isTool = group === LLMGenerationUsageItem.Group.TOOLS;
67
+ const isCostOk = status === LLMGenerationCostItem.Status.OK;
68
+
69
+ const finalStatus = !isTool && isCostOk && uncertain ? LLMGenerationCostItem.Status.UNCERTAIN : status;
70
+
71
+ const tier = !isTool && pricing?.tier?.type ? pricing.tier : null;
72
+ return new LLMGenerationCostItem( group, label, amount, ppm, total, finalStatus, tier );
73
+ } );
74
+ };
75
+
76
+ // Prices the total usage
77
+ const calculateStandardUsage = ( usage, modelPricing ) => {
78
+ const { reasoning: isReasoning, cost: pricing } = modelPricing ?? {};
79
+ return calculateCostItems( { usage, pricing, isReasoning } );
80
+ };
81
+
82
+ /* Prices the tiered usage:
83
+ - Multi-step + any incomplete step: base pricing, uncertain.
84
+ - Known request + no tier + no unsupported tiers: base, precise.
85
+ - Known request + no tier + unsupported tiers: base, uncertain.
86
+ - Known request + tier + no unsupported tiers: tier, precise.
87
+ - Known request + tier + unsupported tiers: tier, uncertain.
88
+ */
89
+ const calculateTieredUsage = ( totalUsage, stepsUsage, modelPricing ) => {
90
+ const { cost: pricing, reasoning: isReasoning } = modelPricing;
91
+
92
+ const isMultiStep = stepsUsage.length > 1;
93
+ const hasIncompleteSteps = stepsUsage.some( u => u?.status !== LLMGenerationUsage.Status.COMPLETE );
94
+
95
+ // incomplete multi-steps fallback to calculate total usage with NO tiers, since token counts are unreliable
96
+ if ( isMultiStep && hasIncompleteSteps ) {
97
+ return calculateCostItems( { usage: totalUsage, pricing, isReasoning, uncertain: true } );
98
+ }
99
+
100
+ return ( isMultiStep ? stepsUsage : [ totalUsage ] ).flatMap( usage => {
101
+ // output usage can't have tier billing
102
+ if ( !isNonNegativeNumber( usage.input ) ) {
103
+ return calculateCostItems( { usage, pricing, isReasoning } );
104
+ }
105
+
106
+ const pricingTier = resolvePricingTier( modelPricing, usage.input );
107
+
108
+ // if there is a matching tier used, otherwise use base pricing
109
+ const finalPricing = pricingTier.tier ?? pricing;
110
+
111
+ // it will be uncertain if unsupported tiers exists
112
+ return calculateCostItems( { usage, pricing: finalPricing, isReasoning, uncertain: pricingTier.hasUnsupported } );
113
+ } );
114
+ };
115
+
116
+ // Returns whether model pricing has tier info or not
117
+ const hasTiers = modelPricing => Array.isArray( modelPricing?.cost?.tiers ) && modelPricing.cost.tiers.length > 0;
118
+
119
+ /**
120
+ * Calculates the cost of an LLM call based on the LLMGenerationUsage.
121
+ *
122
+ * @param {LLMGenerationUsage} usage - Normalized LLM generation usage
123
+ * @param {LLMGenerationUsage[]} stepsUsage - Per-request usage for multi-step calls
124
+ * @returns {Promise<LLMGenerationCost | null>} LLM generation cost with input, output, total and breakdown
125
+ */
126
+ export const calculateCosts = async ( usage, stepsUsage ) => {
127
+ const { models, freshness: pricingFreshness } = await fetchModelsPricing();
128
+
129
+ if ( !models ) {
130
+ Logger.warn( 'Failed to fetch models pricing', { namespace: 'LLM' } );
131
+ return null;
132
+ }
133
+
134
+ const { providerId, modelId } = usage;
135
+
136
+ const modelPricing = models.get( `${providerId}/${modelId}` );
137
+ if ( !modelPricing ) {
138
+ Logger.warn( 'Missing pricing reference for model', { namespace: 'LLM', modelId, providerId } );
139
+ }
140
+
141
+ const items = hasTiers( modelPricing ) ? calculateTieredUsage( usage, stepsUsage, modelPricing ) : calculateStandardUsage( usage, modelPricing );
142
+
143
+ const unrated = items.find( v => v.group === LLMGenerationUsageItem.Group.TOOLS && v.status === LLMGenerationCostItem.Status.MISSING );
144
+ if ( unrated ) {
145
+ Logger.warn( 'Tool call with no rate for model', { namespace: 'LLM', modelId, providerId, type: unrated.label } );
146
+ }
147
+
148
+ return new LLMGenerationCost( modelId, providerId, usage.promptName, usage.requestDetails, items, usage.status, pricingFreshness );
149
+ };
150
+
151
+ /**
152
+ * Calculates a cost using the legacy aggregate pricing behavior.
153
+ *
154
+ * @param {LLMGenerationUsage} usage - Normalized aggregate LLM generation usage
155
+ * @returns {Promise<LLMGenerationCost | null>} Cost compatible with the legacy conversion
156
+ */
157
+ export const calculateLegacyCosts = async usage => {
158
+ const { models, freshness: pricingFreshness } = await fetchModelsPricing();
159
+ if ( !models ) {
160
+ return null;
161
+ }
162
+
163
+ const { providerId, modelId } = usage;
164
+ const modelPricing = models.get( `${providerId}/${modelId}` );
165
+ const items = calculateStandardUsage( usage, modelPricing );
166
+
167
+ return new LLMGenerationCost( modelId, providerId, null, null, items, usage.status, pricingFreshness );
168
+ };
@@ -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,148 @@
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
+ import { parseRequestDetails } from './request_details.js';
8
+
9
+ /**
10
+ * Collects the usage of a single LLM call and bills it once.
11
+ *
12
+ * Steps are recorded as the SDK lifecycle reports them, and the response is handed to `bill()` by
13
+ * the paths that have one, so a call that throws after the model ran is still billed for what it
14
+ * spent. `bill()` parses the usage, costs it, attaches both as trace attributes and emits the
15
+ * metering events; it never throws.
16
+ */
17
+ export class Metering {
18
+ #recordedSteps = [];
19
+ #billed = false;
20
+ #startedAt;
21
+ #prompt;
22
+ #traceId;
23
+ #toolIdsByName;
24
+ #attributes = {
25
+ usage: null,
26
+ cost: null,
27
+ legacy: null
28
+ };
29
+
30
+ async #createAttributes( { usage, steps, requestDetails } ) {
31
+ const baseUsageArgs = {
32
+ prompt: this.#prompt,
33
+ toolIdsByName: this.#toolIdsByName
34
+ };
35
+ // Only the call-level usage carries the request details; the per-step usages feed the tiered cost items only
36
+ const totalUsage = parseLLMUsage( { ...baseUsageArgs, usage, steps, requestDetails } );
37
+ const stepsUsage = steps.map( step => parseLLMUsage( { ...baseUsageArgs, usage: step.usage, steps: [ step ] } ) );
38
+
39
+ this.#attributes.usage = totalUsage;
40
+ if ( this.#attributes.usage ) {
41
+ this.#attributes.cost = await calculateCosts( this.#attributes.usage, stepsUsage );
42
+
43
+ if ( this.#attributes.cost ) {
44
+ // @TEMP Preserve the deprecated event and trace attribute for legacy consumers.
45
+ const legacyCost = await calculateLegacyCosts( this.#attributes.usage );
46
+ this.#attributes.legacy = convertCostToLegacy( legacyCost );
47
+ }
48
+ }
49
+ }
50
+
51
+ #attachAttributes() {
52
+ if ( this.#attributes.usage ) {
53
+ addEventActionWithContext( EventAction.ADD_ATTR, { id: this.#traceId, details: this.#attributes.usage } );
54
+ }
55
+ if ( this.#attributes.cost ) {
56
+ addEventActionWithContext( EventAction.ADD_ATTR, { id: this.#traceId, details: this.#attributes.cost } );
57
+ }
58
+ if ( this.#attributes.legacy ) {
59
+ addEventActionWithContext( EventAction.ADD_ATTR, { id: this.#traceId, details: this.#attributes.legacy } );
60
+ }
61
+ }
62
+
63
+ #emitEvents() {
64
+ if ( this.#attributes.usage ) {
65
+ stepEventBus.emit( 'sdk:llm:generation:metering', structuredClone( { cost: this.#attributes.cost, usage: this.#attributes.usage } ) );
66
+ }
67
+ if ( this.#attributes.legacy ) {
68
+ stepEventBus.emit( 'sdk:cost:llm:request', structuredClone( this.#attributes.legacy ) );
69
+ }
70
+ }
71
+
72
+ /**
73
+ * @param {object} args
74
+ * @param {string} args.traceId - Trace event the usage and cost attributes are attached to
75
+ * @param {object} args.prompt - Loaded prompt (`config.provider` / `config.model` used for cost)
76
+ * @param {Record<string, string>} [args.toolIdsByName] - Provider tool ids keyed by configured name
77
+ */
78
+ constructor( { traceId, prompt, toolIdsByName } ) {
79
+ this.#traceId = traceId;
80
+ this.#prompt = prompt;
81
+ this.#toolIdsByName = toolIdsByName;
82
+ this.#startedAt = performance.now();
83
+ }
84
+
85
+ /**
86
+ * Records a completed step, used as the usage source when the call ends without a response.
87
+ *
88
+ * @param {object} step - AI SDK step
89
+ */
90
+ recordStep = step => {
91
+ if ( !this.#billed ) {
92
+ this.#recordedSteps.push( step );
93
+ }
94
+ };
95
+
96
+ /**
97
+ * Bills the recorded usage: parses it, costs it, attaches the trace attributes and emits the
98
+ * metering events. Later calls and later records are ignored, so it is safe to call from every
99
+ * path that can end the call. Read the result from `attributes`.
100
+ *
101
+ * An empty collector is not a final answer: the SDK reports a stream error before the steps that
102
+ * preceded it, so billing stays open until there is usage or a step to report.
103
+ *
104
+ * @param {object} [response] - AI SDK response, whose aggregate usage and steps take precedence
105
+ * over the recorded steps; omitted by the paths that end without one
106
+ * @returns {Promise<void>}
107
+ */
108
+ bill = async ( response = null ) => {
109
+ if ( this.#billed ) {
110
+ return;
111
+ }
112
+
113
+ try {
114
+ const duration = Math.ceil( performance.now() - this.#startedAt );
115
+ const responseSteps = response?.steps;
116
+ const steps = Array.isArray( responseSteps ) && responseSteps.length > 0 ? responseSteps : this.#recordedSteps;
117
+ const usage = response?.usage;
118
+
119
+ if ( !usage && steps.length === 0 ) {
120
+ return;
121
+ }
122
+
123
+ const requestsHeaders = steps.length > 0 ?
124
+ steps.map( step => step?.response?.headers ) :
125
+ ( response?.responses ?? [] ).map( r => r?.headers );
126
+ const requestDetails = parseRequestDetails( { requestsHeaders, duration } );
127
+
128
+ this.#billed = true;
129
+
130
+ await this.#createAttributes( { usage, steps, requestDetails } );
131
+ this.#attachAttributes();
132
+ this.#emitEvents();
133
+
134
+ } catch ( error ) {
135
+ Logger.error( 'Metering failed', { namespace: 'LLM', error: error?.message || String( error ) } );
136
+ }
137
+ };
138
+
139
+ /**
140
+ * Attributes produced by `bill()`; each one is null until billed, and stays null when there is
141
+ * nothing to report.
142
+ *
143
+ * @returns {{ usage: object|null, cost: object|null, legacy: object|null }}
144
+ */
145
+ get attributes() {
146
+ return this.#attributes;
147
+ }
148
+ }
@@ -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
+ };