@outputai/core 0.15.1-next.5db73d3.0 → 0.15.1-next.606278c.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@outputai/core",
3
- "version": "0.15.1-next.5db73d3.0",
3
+ "version": "0.15.1-next.606278c.0",
4
4
  "description": "The core module of the output framework",
5
5
  "type": "module",
6
6
  "engines": {
@@ -15,14 +15,6 @@
15
15
  "types": "./src/hooks/index.d.ts",
16
16
  "import": "./src/hooks/index.js"
17
17
  },
18
- "./sdk/helpers": {
19
- "types": "./src/sdk/helpers/index.d.ts",
20
- "import": "./src/sdk/helpers/index.js"
21
- },
22
- "./sdk/runtime": {
23
- "types": "./src/sdk/runtime/index.d.ts",
24
- "import": "./src/sdk/runtime/index.js"
25
- },
26
18
  "./temporal": {
27
19
  "types": "./src/temporal/index.d.ts",
28
20
  "import": "./src/temporal/index.js"
@@ -84,9 +76,9 @@
84
76
  "winston": "3.19.0"
85
77
  },
86
78
  "peerDependencies": {
87
- "zod": ">=4.3 <5",
79
+ "zod": ">=4.6.6 <5",
88
80
  "ky": ">=2 <3",
89
- "undici": ">=8 <9",
81
+ "undici": ">=8.12.2 <9",
90
82
  "ai": ">=7 <8",
91
83
  "@ai-sdk/amazon-bedrock": ">=5 <6",
92
84
  "@ai-sdk/anthropic": ">=4 <5",
@@ -117,9 +109,9 @@
117
109
  },
118
110
  "devDependencies": {
119
111
  "@types/js-yaml": "4.0.9",
120
- "zod": "4.6.5",
112
+ "zod": "4.6.6",
121
113
  "ky": "2.0.2",
122
- "undici": "8.10.2",
114
+ "undici": "8.12.3",
123
115
  "ai": "7.0.112",
124
116
  "@ai-sdk/amazon-bedrock": "5.0.92",
125
117
  "@ai-sdk/anthropic": "4.0.61",
package/src/llm/agent.js CHANGED
@@ -5,6 +5,7 @@ import { Role } from './consts.js';
5
5
  import { drainStream } from './utils/stream.js';
6
6
  import { loadPrompt } from './prompt/loader.js';
7
7
  import { loadSkills } from './utils/skills.js';
8
+ import { extractProviderToolIds } from './utils/tools.js';
8
9
  import * as Validator from './validations.js';
9
10
  import { Logger } from '#runtime_logger';
10
11
 
@@ -13,6 +14,7 @@ export class Agent {
13
14
  #prompt;
14
15
  #initialMessages;
15
16
  #store;
17
+ #toolIdsByName;
16
18
 
17
19
  constructor( args ) {
18
20
  const { promptFile, promptObject, promptDir, variables, tools, output, stopWhen, messageStore } = Validator.parseAgentArgs( args );
@@ -32,6 +34,7 @@ export class Agent {
32
34
  // seed only <user> turns into each generate()/stream() call.
33
35
  this.#initialMessages = messages.filter( m => m.role === Role.USER );
34
36
  this.#store = messageStore ?? null;
37
+ this.#toolIdsByName = extractProviderToolIds( aiOptions.tools );
35
38
  }
36
39
 
37
40
  async #combineWithPreviousMessages( messages ) {
@@ -51,6 +54,7 @@ export class Agent {
51
54
  return wrapTextGeneration( {
52
55
  name: 'Agent.generate',
53
56
  prompt: this.#prompt,
57
+ toolIdsByName: this.#toolIdsByName,
54
58
  fn: async ( { onStepEndHook } ) => {
55
59
  const response = await this.#agent.generate( {
56
60
  messages: combinedMessages,
@@ -77,6 +81,7 @@ export class Agent {
77
81
  return wrapTextGeneration( {
78
82
  name: 'Agent.generateWithStreaming',
79
83
  prompt: this.#prompt,
84
+ toolIdsByName: this.#toolIdsByName,
80
85
  fn: async ( { onStepEndHook } ) => {
81
86
  const state = { response: null };
82
87
  const stream = await this.#agent.stream( {
@@ -115,6 +120,7 @@ export class Agent {
115
120
  return wrapStream( {
116
121
  name: 'Agent.stream',
117
122
  prompt: this.#prompt,
123
+ toolIdsByName: this.#toolIdsByName,
118
124
  abortSignal,
119
125
  fn: ( { onEndHook, onErrorHook, onStepEndHook, onAbortHook } ) => this.#agent.stream( {
120
126
  messages: combinedMessages,
@@ -4,18 +4,22 @@ import { wrapImageGeneration, wrapStream, wrapTextGeneration } from './utils/wra
4
4
  import { loadAiSdkTextOptions, loadAiSdkImageOptions } from './ai_sdk_options.js';
5
5
  import { drainStream } from './utils/stream.js';
6
6
  import { loadSkills } from './utils/skills.js';
7
+ import { extractProviderToolIds } from './utils/tools.js';
7
8
  import * as Validator from './validations.js';
8
9
 
9
10
  export const generateText = async args => {
10
11
  const { promptFile, promptObject, variables, promptDir, ...aiOptions } = Validator.parseGenerateTextArgs( args );
11
12
  const prompt = promptObject ?? loadPrompt( promptFile, variables, promptDir );
12
13
  const skills = loadSkills( prompt );
14
+ const options = loadAiSdkTextOptions( { prompt, skills, ...aiOptions } );
15
+ const toolIdsByName = extractProviderToolIds( options.tools );
13
16
 
14
17
  return wrapTextGeneration( {
15
18
  name: 'generateText',
16
19
  prompt,
20
+ toolIdsByName,
17
21
  fn: ( { onStepEndHook } ) => AI.generateText( {
18
- ...loadAiSdkTextOptions( { prompt, skills, ...aiOptions } ),
22
+ ...options,
19
23
  onStepEnd: onStepEndHook
20
24
  } )
21
25
  } );
@@ -25,13 +29,16 @@ export const streamText = args => {
25
29
  const { promptFile, promptObject, variables, promptDir, onEnd, onError, onChunk, ...aiOptions } = Validator.parseStreamTextArgs( args );
26
30
  const prompt = promptObject ?? loadPrompt( promptFile, variables, promptDir );
27
31
  const skills = loadSkills( prompt );
32
+ const options = loadAiSdkTextOptions( { prompt, skills, ...aiOptions } );
33
+ const toolIdsByName = extractProviderToolIds( options.tools );
28
34
 
29
35
  return wrapStream( {
30
36
  name: 'streamText',
31
37
  prompt,
38
+ toolIdsByName,
32
39
  abortSignal: aiOptions.abortSignal,
33
40
  fn: ( { onEndHook, onErrorHook, onStepEndHook, onAbortHook } ) => AI.streamText( {
34
- ...loadAiSdkTextOptions( { prompt, skills, ...aiOptions } ),
41
+ ...options,
35
42
  ...( onChunk && { onChunk } ),
36
43
  onStepEnd: onStepEndHook,
37
44
  onAbort: onAbortHook,
@@ -48,14 +55,17 @@ export const generateTextWithStreaming = async args => {
48
55
  const { promptFile, promptObject, variables, promptDir, onChunk, ...aiOptions } = Validator.parseGenerateTextWithStreamingArgs( args );
49
56
  const prompt = promptObject ?? loadPrompt( promptFile, variables, promptDir );
50
57
  const skills = loadSkills( prompt );
58
+ const options = loadAiSdkTextOptions( { prompt, skills, ...aiOptions } );
59
+ const toolIdsByName = extractProviderToolIds( options.tools );
51
60
 
52
61
  return wrapTextGeneration( {
53
62
  name: 'generateTextWithStreaming',
54
63
  prompt,
64
+ toolIdsByName,
55
65
  fn: async ( { onStepEndHook } ) => {
56
66
  const state = { response: null };
57
67
  const stream = AI.streamText( {
58
- ...loadAiSdkTextOptions( { prompt, skills, ...aiOptions } ),
68
+ ...options,
59
69
  ...( onChunk && { onChunk } ),
60
70
  onStepEnd: onStepEndHook,
61
71
  onEnd: res => {
@@ -390,11 +390,17 @@ export interface LLMUsageEvent {
390
390
  readonly tokensUsed: number;
391
391
  }
392
392
 
393
- export type LLMGenerationCostItemStatus = 'ok' | 'fallback' | 'missing';
393
+ export type LLMGenerationCostItemStatus = 'ok' | 'fallback' | 'uncertain' | 'missing';
394
394
  export type LLMGenerationCostStatus = 'precise' | 'imprecise' | 'incomplete';
395
395
  export type LLMGenerationCostPricingFreshness = 'live' | 'cached' | 'stale' | 'snapshot';
396
396
 
397
- /** Cost calculated for one normalized LLM usage item. */
397
+ /** Context-based pricing tier applied to a normalized cost item. */
398
+ export interface LLMGenerationCostTier {
399
+ type: 'context';
400
+ size: number;
401
+ }
402
+
403
+ /** Cost calculated for one normalized LLM usage pricing segment. */
398
404
  export interface LLMGenerationCostItem {
399
405
  group: 'input' | 'output' | 'tools';
400
406
  label: string | null;
@@ -402,6 +408,7 @@ export interface LLMGenerationCostItem {
402
408
  ppm: number | null;
403
409
  total: number | null;
404
410
  status: LLMGenerationCostItemStatus;
411
+ tier?: LLMGenerationCostTier;
405
412
  }
406
413
 
407
414
  /** Normalized LLM generation cost trace attribute. */
@@ -1,16 +1,18 @@
1
1
  import { fetchModelsPricing, Freshness } from './models_pricing.js';
2
2
  import { BaseAttribute } from '#trace_attribute';
3
3
  import { LLMGenerationUsage, LLMGenerationUsageItem } from './usage.js';
4
- import { GroundingPpmMap } from './grounding.js';
4
+ import { resolveWebSearchPpm } from './web_search.js';
5
5
  import { Logger } from '#runtime_logger';
6
6
  import Decimal from 'decimal.js';
7
7
 
8
- const exists = v => Number.isFinite( v );
8
+ // Checks whether a pricing value can be used in cost calculations.
9
+ const isValidNumber = v => Number.isFinite( v ) && v >= 0;
9
10
 
10
11
  export class LLMGenerationCostItem {
11
12
  static Status = Object.freeze( {
12
13
  OK: 'ok',
13
14
  FALLBACK: 'fallback',
15
+ UNCERTAIN: 'uncertain',
14
16
  MISSING: 'missing'
15
17
  } );
16
18
 
@@ -21,13 +23,20 @@ export class LLMGenerationCostItem {
21
23
  total;
22
24
  status;
23
25
 
24
- constructor( group, label, amount, ppm, total, status ) {
26
+ constructor( group, label, amount, ppm, total, status, tier = undefined ) {
25
27
  this.group = group;
26
28
  this.label = label;
27
29
  this.amount = amount;
28
30
  this.ppm = ppm;
29
31
  this.total = total;
30
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 ] );
31
40
  }
32
41
  }
33
42
 
@@ -52,46 +61,67 @@ export class LLMGenerationCost extends BaseAttribute {
52
61
  super( LLMGenerationCost.TYPE );
53
62
  this.modelId = modelId;
54
63
  this.providerId = providerId;
55
- this.items = items;
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
+
56
80
  this.pricingFreshness = pricingFreshness;
57
81
 
58
- const meaningfulItems = items.filter( v => v.amount > 0 );
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 );
59
86
 
60
- if ( meaningfulItems.some( v => v.status === LLMGenerationCostItem.Status.MISSING ) || usageStatus === LLMGenerationUsage.Status.INCOMPLETE ) {
87
+ if ( hasMissingItems || usageStatus === LLMGenerationUsage.Status.INCOMPLETE ) {
61
88
  this.status = LLMGenerationCost.Status.INCOMPLETE;
62
- } else if ( meaningfulItems.some( v => v.status === LLMGenerationCostItem.Status.FALLBACK ) || pricingFreshness === Freshness.SNAPSHOT ) {
89
+ } else if ( hasFallbackItems || pricingFreshness === Freshness.SNAPSHOT || hasUncertainItems ) {
63
90
  this.status = LLMGenerationCost.Status.IMPRECISE;
64
91
  } else {
65
92
  this.status = LLMGenerationCost.Status.PRECISE;
66
93
  }
94
+
67
95
  const sumGroup = group => {
68
- const groupItems = items.filter( p => p.group === group && exists( p.total ) );
96
+ const groupItems = this.items.filter( p => p.group === group && isValidNumber( p.total ) );
69
97
  return groupItems.length > 0 ? groupItems.reduce( ( s, p ) => s.add( p.total ), Decimal( 0 ) ).toNumber() : null;
70
98
  };
71
99
  this.input = sumGroup( LLMGenerationUsageItem.Group.INPUT );
72
100
  this.output = sumGroup( LLMGenerationUsageItem.Group.OUTPUT );
73
101
  this.tools = sumGroup( LLMGenerationUsageItem.Group.TOOLS );
74
- if ( exists( this.input ) || exists( this.output ) || exists( this.tools ) ) {
102
+ if ( isValidNumber( this.input ) || isValidNumber( this.output ) || isValidNumber( this.tools ) ) {
75
103
  this.total = Decimal( this.input ?? 0 ).add( this.output ?? 0 ).add( this.tools ?? 0 ).toNumber();
76
104
  }
77
105
  }
78
106
  }
79
107
 
108
+ // Selects the exact rate, then the first available fallback rate.
80
109
  const resolveValue = values => {
81
- if ( exists( values[0] ) ) {
110
+ if ( isValidNumber( values[0] ) ) {
82
111
  return { ppm: values[0], status: LLMGenerationCostItem.Status.OK };
83
112
  }
84
- const fallback = values.slice( 1 ).find( exists );
85
- if ( exists( fallback ) ) {
113
+ const fallback = values.slice( 1 ).find( isValidNumber );
114
+ if ( isValidNumber( fallback ) ) {
86
115
  return { ppm: fallback, status: LLMGenerationCostItem.Status.FALLBACK };
87
116
  }
88
117
  return { ppm: null, status: LLMGenerationCostItem.Status.MISSING };
89
118
  };
90
119
 
91
- const resolvePrice = ( { group, label, pricing } ) => {
120
+ // Resolves the applicable token or provider-tool rate for one usage item.
121
+ const resolvePrice = ( { providerId, group, label, pricing, isReasoning } ) => {
92
122
  // Tool charges are never token-priced: models.dev has no rate for them.
93
123
  if ( group === LLMGenerationUsageItem.Group.TOOLS ) {
94
- return resolveValue( [ GroundingPpmMap.get( label ) ] );
124
+ return resolveValue( [ resolveWebSearchPpm( providerId, label, isReasoning ) ] );
95
125
  }
96
126
  if ( !pricing ) {
97
127
  return resolveValue( [] );
@@ -113,13 +143,86 @@ const resolvePrice = ( { group, label, pricing } ) => {
113
143
  return resolveValue( values );
114
144
  };
115
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
+
116
218
  /**
117
219
  * Calculates the cost of an LLM call based on the LLMGenerationUsage.
118
220
  *
119
221
  * @param {LLMGenerationUsage} usage - Normalized LLM generation usage
222
+ * @param {LLMGenerationUsage[]} stepsUsage - Per-request usage for multi-step calls
120
223
  * @returns {Promise<LLMGenerationCost | null>} LLM generation cost with input, output, total and breakdown
121
224
  */
122
- export const calculateCosts = async usage => {
225
+ export const calculateCosts = async ( usage, stepsUsage ) => {
123
226
  const { models, freshness: pricingFreshness } = await fetchModelsPricing();
124
227
 
125
228
  if ( !models ) {
@@ -129,22 +232,36 @@ export const calculateCosts = async usage => {
129
232
 
130
233
  const { providerId, modelId } = usage;
131
234
 
132
- const pricing = models.get( `${providerId}/${modelId}` );
133
- if ( !pricing ) {
235
+ const modelPricing = models.get( `${providerId}/${modelId}` );
236
+ if ( !modelPricing ) {
134
237
  Logger.warn( 'Missing pricing reference for model', { namespace: 'LLM', modelId, providerId } );
135
238
  }
136
239
 
137
- const items = usage.items.map( ( { group, label, amount } ) => {
138
- const { ppm, status } = resolvePrice( { pricing, group, label } );
139
- const total = exists( ppm ) ? Decimal( amount ).div( 1_000_000 ).mul( ppm ).toNumber() : null;
140
- return new LLMGenerationCostItem( group, label, amount, ppm, total, status );
141
- } );
240
+ const items = hasTiers( modelPricing ) ? calculateTieredUsage( usage, stepsUsage, modelPricing ) : calculateStandardUsage( usage, modelPricing );
142
241
 
143
- const unrated = items.find( v =>
144
- v.group === LLMGenerationUsageItem.Group.TOOLS && v.status === LLMGenerationCostItem.Status.MISSING );
242
+ const unrated = items.find( v => v.group === LLMGenerationUsageItem.Group.TOOLS && v.status === LLMGenerationCostItem.Status.MISSING );
145
243
  if ( unrated ) {
146
244
  Logger.warn( 'Tool call with no rate for model', { namespace: 'LLM', modelId, providerId, type: unrated.label } );
147
245
  }
148
246
 
149
247
  return new LLMGenerationCost( modelId, providerId, items, usage.status, pricingFreshness );
150
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
+ };
@@ -1,5 +1,5 @@
1
1
  import { parseLLMUsage } from './usage.js';
2
- import { calculateCosts } from './cost.js';
2
+ import { calculateCosts, calculateLegacyCosts } from './cost.js';
3
3
  import { stepEventBus } from '#bus';
4
4
  import { addEventActionWithContext, EventAction } from '#tracing';
5
5
  import { Logger } from '#runtime_logger';
@@ -18,6 +18,7 @@ export class Metering {
18
18
  #billed = false;
19
19
  #prompt;
20
20
  #traceId;
21
+ #toolIdsByName;
21
22
  #attributes = {
22
23
  usage: null,
23
24
  cost: null,
@@ -25,12 +26,22 @@ export class Metering {
25
26
  };
26
27
 
27
28
  async #createAttributes( { usage, steps } ) {
28
- this.#attributes.usage = parseLLMUsage( { prompt: this.#prompt, 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;
29
38
  if ( this.#attributes.usage ) {
30
- this.#attributes.cost = await calculateCosts( this.#attributes.usage );
39
+ this.#attributes.cost = await calculateCosts( this.#attributes.usage, stepsUsage );
40
+
31
41
  if ( this.#attributes.cost ) {
32
42
  // @TEMP Preserve the deprecated event and trace attribute for legacy consumers.
33
- this.#attributes.legacy = convertCostToLegacy( this.#attributes.cost );
43
+ const legacyCost = await calculateLegacyCosts( this.#attributes.usage );
44
+ this.#attributes.legacy = convertCostToLegacy( legacyCost );
34
45
  }
35
46
  }
36
47
  }
@@ -60,10 +71,12 @@ export class Metering {
60
71
  * @param {object} args
61
72
  * @param {string} args.traceId - Trace event the usage and cost attributes are attached to
62
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
63
75
  */
64
- constructor( { traceId, prompt } ) {
76
+ constructor( { traceId, prompt, toolIdsByName } ) {
65
77
  this.#traceId = traceId;
66
78
  this.#prompt = prompt;
79
+ this.#toolIdsByName = toolIdsByName;
67
80
  }
68
81
 
69
82
  /**
@@ -33,9 +33,12 @@ const parseData = data => {
33
33
  if ( providerId === '_meta' ) {
34
34
  continue;
35
35
  }
36
- for ( const [ modelName, { cost } ] of Object.entries( provider.models ?? {} ) ) {
36
+ for ( const [ modelName, { cost, reasoning } ] of Object.entries( provider.models ?? {} ) ) {
37
37
  if ( cost ) { // some models don't have cost
38
- map.set( `${providerId}/${modelName}`, cost );
38
+ map.set( `${providerId}/${modelName}`, {
39
+ cost,
40
+ reasoning: reasoning === true
41
+ } );
39
42
  }
40
43
  }
41
44
  }