@outputai/core 0.15.1-next.8ef04e2.0 → 0.15.1-next.91027b1.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 (58) 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 +11 -13
  18. package/src/consts.d.ts +2 -0
  19. package/src/helpers/path.js +0 -2
  20. package/src/http/fetch/index.d.ts +3 -5
  21. package/src/http/index.d.ts +1 -0
  22. package/src/interface/index.d.ts +1 -0
  23. package/src/llm/agent.js +6 -0
  24. package/src/llm/generate.js +13 -3
  25. package/src/llm/index.d.ts +88 -22
  26. package/src/llm/index.js +1 -0
  27. package/src/llm/judge.js +48 -0
  28. package/src/llm/utils/cost.js +141 -24
  29. package/src/llm/utils/metering.js +18 -5
  30. package/src/llm/utils/models_pricing.js +5 -2
  31. package/src/llm/utils/models_pricing_snapshot.json +1010 -465
  32. package/src/llm/utils/tools.js +14 -0
  33. package/src/llm/utils/usage.js +23 -24
  34. package/src/llm/utils/web_search.js +155 -0
  35. package/src/llm/utils/wrap.js +6 -4
  36. package/src/worker/bundler_options.js +1 -9
  37. package/src/worker/loader/workflows.js +16 -2
  38. package/src/worker/webpack_loaders/workflow_rewriter/index.mjs +3 -7
  39. package/src/worker/webpack_loaders/workflow_rewriter/rewrite_activity_calls.js +27 -7
  40. package/src/worker/webpack_loaders/workflow_validator/npm_workflow_export_resolve.js +5 -6
  41. package/src/llm/utils/grounding.js +0 -49
  42. package/src/sdk/README.md +0 -47
  43. package/src/sdk/helpers/component_metadata.d.ts +0 -17
  44. package/src/sdk/helpers/component_metadata.js +0 -6
  45. package/src/sdk/helpers/index.d.ts +0 -12
  46. package/src/sdk/helpers/index.js +0 -3
  47. package/src/sdk/helpers/objects.d.ts +0 -56
  48. package/src/sdk/helpers/objects.js +0 -8
  49. package/src/sdk/helpers/path.d.ts +0 -13
  50. package/src/sdk/helpers/path.js +0 -33
  51. package/src/sdk/runtime/context.d.ts +0 -30
  52. package/src/sdk/runtime/context.js +0 -15
  53. package/src/sdk/runtime/events.d.ts +0 -13
  54. package/src/sdk/runtime/events.js +0 -5
  55. package/src/sdk/runtime/index.d.ts +0 -12
  56. package/src/sdk/runtime/index.js +0 -3
  57. package/src/sdk/runtime/tracing.d.ts +0 -48
  58. package/src/sdk/runtime/tracing.js +0 -11
@@ -1,10 +1,8 @@
1
1
  import type * as undici from 'undici';
2
2
 
3
- type NodeRequestInfo = string | URL | globalThis.Request;
4
- type NodeRequestInit = globalThis.RequestInit & Pick<undici.RequestInit, 'dispatcher'>;
5
-
6
- type OutputFetch = {
7
- ( input: NodeRequestInfo, init?: NodeRequestInit ): Promise<Response>;
3
+ /** Fetch function supporting Node and Undici request types. */
4
+ export type OutputFetch = {
5
+ ( input: string | URL | globalThis.Request, init?: globalThis.RequestInit & Pick<undici.RequestInit, 'dispatcher'> ): Promise<Response>;
8
6
  ( input: undici.RequestInfo, init?: undici.RequestInit ): Promise<Response>;
9
7
  };
10
8
 
@@ -17,6 +17,7 @@ export type HttpRequestCostEvent = {
17
17
  };
18
18
 
19
19
  export { outputFetch } from './fetch/index.js';
20
+ export type { OutputFetch } from './fetch/index.js';
20
21
  export { HTTPRequestCount } from './fetch/logger.js';
21
22
  export { createKyClient } from './ky/index.js';
22
23
 
@@ -8,3 +8,4 @@ export * from './evaluator.js';
8
8
  export * from './workflow.js';
9
9
  export * from './evaluation_result.js';
10
10
  export * from './logger.js';
11
+ export type { AnyZodSchema, DeepPartial, TemporalActivityOptions } from './types.js';
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 => {
@@ -11,7 +11,14 @@ import type {
11
11
  StreamTextOnErrorCallback
12
12
  } from 'ai';
13
13
  import type { Output as AIOutputNamespace } from 'ai';
14
+ import type { z } from 'zod';
14
15
  import type { Attribute } from '#trace_attribute';
16
+ import type {
17
+ EvaluationBooleanResult,
18
+ EvaluationNumberResult,
19
+ EvaluationStringResult,
20
+ EvaluationVerdictResult
21
+ } from '#interface/evaluation_result';
15
22
 
16
23
  type BaseAttribute = Attribute.BaseAttribute;
17
24
 
@@ -186,12 +193,8 @@ export type Prompt = {
186
193
  instructions: string | null;
187
194
  };
188
195
 
189
- type AnyAiOutput = AIOutputNamespace.Output<unknown, unknown, unknown>;
190
- type DefaultRuntimeContext = Record<string, unknown>;
191
- type CompatibleToolSchemaKey = 'inputSchema' | 'outputSchema' | 'contextSchema';
192
- type WithoutToolSchemaBrands<T> = T extends unknown ? {
193
- [K in keyof T]: K extends CompatibleToolSchemaKey ? unknown : T[K];
194
- } : never;
196
+ /** Any AI SDK structured output specification. */
197
+ export type AnyAiOutput = AIOutputNamespace.Output<unknown, unknown, unknown>;
195
198
 
196
199
  /**
197
200
  * Structurally-compatible AI SDK 7 tool shape.
@@ -199,12 +202,17 @@ type WithoutToolSchemaBrands<T> = T extends unknown ? {
199
202
  * This derives from AI SDK's `ToolSet` and widens only schema fields so tools from packages
200
203
  * resolved with a different Zod peer instance remain assignable.
201
204
  */
202
- export type CompatibleTool = WithoutToolSchemaBrands<ToolSet[string]>;
205
+ export type CompatibleTool = ToolSet[string] extends infer Tool ?
206
+ Tool extends unknown ? {
207
+ [K in keyof Tool]: K extends 'inputSchema' | 'outputSchema' | 'contextSchema' ? unknown : Tool[K];
208
+ } : never :
209
+ never;
203
210
 
204
211
  /** AI SDK tools accepted by Output APIs without requiring one exact Zod peer instance. */
205
212
  export type CompatibleToolSet = Record<string, CompatibleTool>;
206
213
 
207
- type PromptFileCallOptions = {
214
+ /** Options for an LLM call using a prompt file. */
215
+ export type PromptFileCallOptions = {
208
216
  /** Prompt file name (e.g. 'summary@v1') */
209
217
  prompt: string;
210
218
  /** Variables to interpolate into the prompt file */
@@ -213,7 +221,8 @@ type PromptFileCallOptions = {
213
221
  promptDir?: string;
214
222
  };
215
223
 
216
- type PromptObjectCallOptions = {
224
+ /** Options for an LLM call using a loaded or custom prompt. */
225
+ export type PromptObjectCallOptions = {
217
226
  /** Loaded or custom prompt object. */
218
227
  prompt: Prompt;
219
228
  /** Prompt objects are already rendered and cannot receive interpolation variables. */
@@ -222,13 +231,16 @@ type PromptObjectCallOptions = {
222
231
  promptDir?: never;
223
232
  };
224
233
 
225
- type PromptCallOptions = PromptFileCallOptions | PromptObjectCallOptions;
234
+ /** Prompt file or loaded prompt options accepted by LLM calls. */
235
+ export type PromptCallOptions = PromptFileCallOptions | PromptObjectCallOptions;
226
236
 
227
- type StopWhen<Tools extends ToolSet = ToolSet> =
228
- StopCondition<NoInfer<Tools>, DefaultRuntimeContext> |
229
- Array<StopCondition<NoInfer<Tools>, DefaultRuntimeContext>>;
237
+ /** Stop conditions accepted by text generation calls. */
238
+ export type StopWhen<Tools extends ToolSet = ToolSet> =
239
+ StopCondition<NoInfer<Tools>, Record<string, unknown>> |
240
+ Array<StopCondition<NoInfer<Tools>, Record<string, unknown>>>;
230
241
 
231
- type TextCallOptions<
242
+ /** Shared options accepted by text generation calls. */
243
+ export type TextCallOptions<
232
244
  Tools extends ToolSet = ToolSet,
233
245
  OutputSpec extends AnyAiOutput = AnyAiOutput
234
246
  > = PromptCallOptions & {
@@ -283,7 +295,8 @@ export type GenerateImageInput =
283
295
  mediaType?: string;
284
296
  };
285
297
 
286
- type GenerateImageInputs =
298
+ /** Image and mask inputs accepted by image generation calls. */
299
+ export type GenerateImageInputs =
287
300
  | {
288
301
  /** Runtime image inputs for image-to-image generation */
289
302
  images: GenerateImageInput[];
@@ -339,7 +352,7 @@ export type OutputAgentStreamParameters = OutputAgentGenerateWithStreamingParame
339
352
  * `ai` does not export a named `Source` type.
340
353
  */
341
354
  export type ExtractedSource =
342
- AIGenerateTextResult<ToolSet, DefaultRuntimeContext, AnyAiOutput>['sources'][number];
355
+ AIGenerateTextResult<ToolSet, Record<string, unknown>, AnyAiOutput>['sources'][number];
343
356
 
344
357
  export type LLMGenerationUsageStatus = 'complete' | 'incomplete';
345
358
 
@@ -383,11 +396,17 @@ export interface LLMUsageEvent {
383
396
  readonly tokensUsed: number;
384
397
  }
385
398
 
386
- export type LLMGenerationCostItemStatus = 'ok' | 'fallback' | 'missing';
399
+ export type LLMGenerationCostItemStatus = 'ok' | 'fallback' | 'uncertain' | 'missing';
387
400
  export type LLMGenerationCostStatus = 'precise' | 'imprecise' | 'incomplete';
388
401
  export type LLMGenerationCostPricingFreshness = 'live' | 'cached' | 'stale' | 'snapshot';
389
402
 
390
- /** Cost calculated for one normalized LLM usage item. */
403
+ /** Context-based pricing tier applied to a normalized cost item. */
404
+ export interface LLMGenerationCostTier {
405
+ type: 'context';
406
+ size: number;
407
+ }
408
+
409
+ /** Cost calculated for one normalized LLM usage pricing segment. */
391
410
  export interface LLMGenerationCostItem {
392
411
  group: 'input' | 'output' | 'tools';
393
412
  label: string | null;
@@ -395,6 +414,7 @@ export interface LLMGenerationCostItem {
395
414
  ppm: number | null;
396
415
  total: number | null;
397
416
  status: LLMGenerationCostItemStatus;
417
+ tier?: LLMGenerationCostTier;
398
418
  }
399
419
 
400
420
  /** Normalized LLM generation cost trace attribute. */
@@ -423,7 +443,7 @@ export interface LLMGenerationMeteringEvent {
423
443
  * `onEnd` payload plus `result`, `cost`, and merged `sources`.
424
444
  */
425
445
  export type WrappedStreamTextOnEndEvent<Tools extends ToolSet = ToolSet> =
426
- Parameters<GenerateTextOnEndCallback<Tools, DefaultRuntimeContext>>[0] & {
446
+ Parameters<GenerateTextOnEndCallback<Tools, Record<string, unknown>>>[0] & {
427
447
  result: string;
428
448
  cost: LLMGenerationCost | null;
429
449
  sources: ExtractedSource[];
@@ -441,7 +461,7 @@ export type WrappedStreamTextOnEndCallback<Tools extends ToolSet = ToolSet> = (
441
461
  export type GenerateTextResult<
442
462
  Tools extends ToolSet = ToolSet,
443
463
  OutputSpec extends AnyAiOutput = AnyAiOutput
444
- > = AIGenerateTextResult<Tools, DefaultRuntimeContext, OutputSpec> & {
464
+ > = AIGenerateTextResult<Tools, Record<string, unknown>, OutputSpec> & {
445
465
  /** Unified field name alias for 'text' */
446
466
  result: string;
447
467
  /** Calculated cost for the LLM call; `null` when pricing data is not available */
@@ -503,6 +523,52 @@ export function registerProvider(
503
523
  */
504
524
  export function getProviderNames(): string[];
505
525
 
526
+ /**
527
+ * Arguments accepted by the LLM judge functions.
528
+ *
529
+ * The prompt file is resolved from the directory of the file calling the judge.
530
+ */
531
+ export type JudgeArgs = {
532
+ /** Prompt filename (without `.prompt` extension). */
533
+ prompt: string;
534
+ /** Variables to interpolate into the prompt. */
535
+ variables?: PromptVariables;
536
+ /** Output schema replacing the default one. It must keep the judged field and `reasoning`. */
537
+ schema?: z.ZodType;
538
+ };
539
+
540
+ /**
541
+ * Ask an LLM judge for a verdict. The default schema is `{ verdict: 'pass' | 'partial' | 'fail', reasoning: string }`.
542
+ *
543
+ * @param args - Judge arguments. See {@link JudgeArgs}.
544
+ * @returns Verdict result with the judge reasoning.
545
+ */
546
+ export function judgeVerdict( args: JudgeArgs ): Promise<EvaluationVerdictResult>;
547
+
548
+ /**
549
+ * Ask an LLM judge for a numeric score. The default schema is `{ score: number, reasoning: string }`.
550
+ *
551
+ * @param args - Judge arguments. See {@link JudgeArgs}.
552
+ * @returns Number result with the judge reasoning.
553
+ */
554
+ export function judgeScore( args: JudgeArgs ): Promise<EvaluationNumberResult>;
555
+
556
+ /**
557
+ * Ask an LLM judge for a true or false answer. The default schema is `{ result: boolean, reasoning: string }`.
558
+ *
559
+ * @param args - Judge arguments. See {@link JudgeArgs}.
560
+ * @returns Boolean result with the judge reasoning.
561
+ */
562
+ export function judgeBoolean( args: JudgeArgs ): Promise<EvaluationBooleanResult>;
563
+
564
+ /**
565
+ * Ask an LLM judge for a label. The default schema is `{ label: string, reasoning: string }`.
566
+ *
567
+ * @param args - Judge arguments. See {@link JudgeArgs}.
568
+ * @returns String result with the judge reasoning.
569
+ */
570
+ export function judgeLabel( args: JudgeArgs ): Promise<EvaluationStringResult>;
571
+
506
572
  /**
507
573
  * Use an LLM model to generate text.
508
574
  *
@@ -557,7 +623,7 @@ export function streamText<
557
623
  OutputSpec extends AnyAiOutput = AnyAiOutput
558
624
  >(
559
625
  args: StreamTextParameters<Tools, OutputSpec>
560
- ): AIStreamTextResult<Tools, DefaultRuntimeContext, OutputSpec>;
626
+ ): AIStreamTextResult<Tools, Record<string, unknown>, OutputSpec>;
561
627
 
562
628
  /**
563
629
  * Use an image model to generate images from a prompt filename or object.
@@ -626,6 +692,6 @@ export declare class Agent<
626
692
  * `onEnd` receives {@link WrappedStreamTextOnEndEvent} (`result`, `cost`, `sources`), matching {@link streamText}.
627
693
  */
628
694
  stream( options?: OutputAgentStreamParameters ): Promise<
629
- AIStreamTextResult<ToolSet, DefaultRuntimeContext, OutputSpec>
695
+ AIStreamTextResult<ToolSet, Record<string, unknown>, OutputSpec>
630
696
  >;
631
697
  }
package/src/llm/index.js CHANGED
@@ -2,4 +2,5 @@ export { generateText, generateTextWithStreaming, streamText, generateImage } fr
2
2
  export { Agent } from './agent.js';
3
3
  export { loadPrompt } from './prompt/loader.js';
4
4
  export { registerProvider, getProviderNames } from './ai_provider.js';
5
+ export { judgeVerdict, judgeScore, judgeBoolean, judgeLabel } from './judge.js';
5
6
  export * as aiSdk from 'ai';
@@ -0,0 +1,48 @@
1
+ import { Output } from 'ai';
2
+ import { z } from 'zod';
3
+ import { EvaluationBooleanResult, EvaluationNumberResult, EvaluationStringResult, EvaluationVerdictResult } from '#interface/evaluation_result';
4
+ import { generateText } from './generate.js';
5
+
6
+ const CONFIDENCE = 0.9;
7
+
8
+ const verdictSchema = z.object( { verdict: z.enum( [ 'pass', 'partial', 'fail' ] ), reasoning: z.string() } );
9
+ const scoreSchema = z.object( { score: z.number(), reasoning: z.string() } );
10
+ const booleanSchema = z.object( { result: z.boolean(), reasoning: z.string() } );
11
+ const labelSchema = z.object( { label: z.string(), reasoning: z.string() } );
12
+
13
+ const judge = async ( { prompt, variables, schema } ) => {
14
+ const { output } = await generateText( { prompt, variables, output: Output.object( { schema } ) } );
15
+ return output;
16
+ };
17
+
18
+ /**
19
+ * Ask an LLM judge for a pass, partial, or fail verdict.
20
+ */
21
+ export const judgeVerdict = async ( { prompt, variables, schema = verdictSchema } ) => {
22
+ const { verdict, reasoning } = await judge( { prompt, variables, schema } );
23
+ return new EvaluationVerdictResult( { value: verdict, confidence: CONFIDENCE, reasoning } );
24
+ };
25
+
26
+ /**
27
+ * Ask an LLM judge for a numeric score.
28
+ */
29
+ export const judgeScore = async ( { prompt, variables, schema = scoreSchema } ) => {
30
+ const { score, reasoning } = await judge( { prompt, variables, schema } );
31
+ return new EvaluationNumberResult( { value: score, confidence: CONFIDENCE, reasoning } );
32
+ };
33
+
34
+ /**
35
+ * Ask an LLM judge for a true or false answer.
36
+ */
37
+ export const judgeBoolean = async ( { prompt, variables, schema = booleanSchema } ) => {
38
+ const { result, reasoning } = await judge( { prompt, variables, schema } );
39
+ return new EvaluationBooleanResult( { value: result, confidence: CONFIDENCE, reasoning } );
40
+ };
41
+
42
+ /**
43
+ * Ask an LLM judge for a label.
44
+ */
45
+ export const judgeLabel = async ( { prompt, variables, schema = labelSchema } ) => {
46
+ const { label, reasoning } = await judge( { prompt, variables, schema } );
47
+ return new EvaluationStringResult( { value: label, confidence: CONFIDENCE, reasoning } );
48
+ };
@@ -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
+ };