@outputai/core 0.17.1-next.78fc808.0 → 0.18.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.
@@ -66,12 +66,10 @@ export interface GroundTruth {
66
66
  }
67
67
  export interface LastOutput {
68
68
  output: unknown;
69
- executionTimeMs?: number;
70
69
  date: string;
71
70
  }
72
71
  export interface LastEval {
73
72
  output: EvalCase;
74
- executionTimeMs?: number;
75
73
  date: string;
76
74
  }
77
75
  export declare const LastOutputSchema: z.ZodType<LastOutput>;
@@ -41,12 +41,10 @@ export const EvalOutputSchema = z.object({
41
41
  });
42
42
  export const LastOutputSchema = z.object({
43
43
  output: z.any(),
44
- executionTimeMs: z.number().optional(),
45
44
  date: z.string()
46
45
  });
47
46
  export const LastEvalSchema = z.object({
48
47
  output: EvalCaseSchema,
49
- executionTimeMs: z.number().optional(),
50
48
  date: z.string()
51
49
  });
52
50
  export const DatasetSchema = z.object({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@outputai/core",
3
- "version": "0.17.1-next.78fc808.0",
3
+ "version": "0.18.0",
4
4
  "description": "The core module of the output framework",
5
5
  "type": "module",
6
6
  "engines": {
@@ -121,6 +121,11 @@
121
121
  "@ai-sdk/perplexity": "4.0.49"
122
122
  },
123
123
  "license": "Apache-2.0",
124
+ "repository": {
125
+ "type": "git",
126
+ "url": "https://github.com/growthxai/output",
127
+ "directory": "projects/core"
128
+ },
124
129
  "publishConfig": {
125
130
  "access": "public"
126
131
  },
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Abortable one-shot or looping task.
3
+ * Subclasses implement {@link CancelableRunner#run}.
4
+ */
5
+ export class CancelableRunner {
6
+ #abortCtrl = new AbortController();
7
+ #running = false;
8
+ #execution = null;
9
+ #signal = null;
10
+
11
+ /**
12
+ * @param {object} options
13
+ * @param {AbortSignal} options.signal - stops the runner when aborted
14
+ */
15
+ constructor( { signal } ) {
16
+ this.#signal = signal;
17
+ }
18
+
19
+ /** Whether start() has an in-flight execution */
20
+ get running() {
21
+ return this.#running;
22
+ }
23
+
24
+ /**
25
+ * Starts the runner. Idempotent: later calls return the same promise.
26
+ * @returns {Promise<*>} settles when run() finishes; rejects if run() rejects
27
+ */
28
+ start() {
29
+ if ( this.#execution ) {
30
+ return this.#execution;
31
+ }
32
+
33
+ const signal = AbortSignal.any( [ this.#signal, this.#abortCtrl.signal ] );
34
+
35
+ if ( signal.aborted ) {
36
+ return Promise.resolve();
37
+ }
38
+
39
+ this.#running = true;
40
+ this.#execution = this.run( signal ).finally( () => {
41
+ this.#running = false;
42
+ } );
43
+
44
+ return this.#execution;
45
+ }
46
+
47
+ /**
48
+ * Stops the runner and waits for the in-flight execution to settle.
49
+ * @returns {Promise<*>}
50
+ */
51
+ stop() {
52
+ this.abort();
53
+ return this.#execution ?? Promise.resolve();
54
+ }
55
+
56
+ /** Abort without waiting. Safe to call from run(). */
57
+ abort() {
58
+ this.#abortCtrl.abort();
59
+ }
60
+
61
+ /**
62
+ * Work body. Receives a signal that aborts on stop() or the external signal.
63
+ * @param {AbortSignal} _signal
64
+ * @returns {Promise<*>}
65
+ */
66
+ async run( _signal ) {
67
+ throw new Error( `${this.constructor.name} must implement run()` );
68
+ }
69
+ }
@@ -66,7 +66,10 @@ const providerInitializers = Object.fromEntries(
66
66
  /** Providers already initialized due usage */
67
67
  const initializedProviders = {};
68
68
 
69
- /** Providers registered by the user */
69
+ /**
70
+ * Providers registered by the user.
71
+ * @type {Record<string, { providerFn: Function, extractStepCost: Function|null }>}
72
+ */
70
73
  const registeredProviders = {};
71
74
 
72
75
  /**
@@ -76,19 +79,31 @@ const registeredProviders = {};
76
79
  export const getProviderNames = () =>
77
80
  new Set( Object.keys( providerInitializers ).concat( Object.keys( registeredProviders ) ) ).values().toArray();
78
81
 
82
+ /**
83
+ * Returns the step cost extractor registered for a provider, if any.
84
+ * @param {string} name
85
+ * @returns {((providerMetadata: object|undefined) => number|null)|null}
86
+ */
87
+ export const getStepCostExtractorForProvider = name => registeredProviders[name]?.extractStepCost ?? null;
88
+
79
89
  const registerProviderSchema = z.object( {
80
90
  name: z.string().min( 1, 'Provider name must be a non-empty string' ),
81
- providerFn: z.function()
91
+ providerFn: z.function(),
92
+ extractStepCost: z.function().optional()
82
93
  } );
83
94
 
84
95
  /**
85
96
  * Register or override an AI SDK provider factory by name.
86
97
  * @param {string} name - Provider name used in prompt frontmatter
87
98
  * @param {Function} providerFn - Factory function that receives a model id
99
+ * @param {object} [options]
100
+ * @param {(providerMetadata: object|undefined) => number|null} [options.extractStepCost] -
101
+ * when set, metering bills from this extractor only and never from models.dev;
102
+ * with no steps, falls back to `finalStep` then top-level response `providerMetadata`
88
103
  * @returns {void}
89
104
  */
90
- export const registerProvider = ( name, providerFn ) => {
91
- const result = registerProviderSchema.safeParse( { name, providerFn } );
105
+ export const registerProvider = ( name, providerFn, options = {} ) => {
106
+ const result = registerProviderSchema.safeParse( { name, providerFn, ...options } );
92
107
  if ( !result.success ) {
93
108
  throw new ValidationError( `Invalid provider registration: ${z.prettifyError( result.error )}` );
94
109
  }
@@ -98,7 +113,10 @@ export const registerProvider = ( name, providerFn ) => {
98
113
  `Cannot register provider "${name}": that name is a deprecated alias for "${canonical}". Register "${canonical}" instead.`
99
114
  );
100
115
  }
101
- registeredProviders[name] = providerFn;
116
+ registeredProviders[name] = {
117
+ providerFn,
118
+ extractStepCost: typeof options.extractStepCost === 'function' ? options.extractStepCost : null
119
+ };
102
120
  };
103
121
 
104
122
  /**
@@ -111,7 +129,7 @@ export const registerProvider = ( name, providerFn ) => {
111
129
  * @returns {object} provider
112
130
  */
113
131
  export const getProvider = name => {
114
- const provider = registeredProviders[name] ?? initializedProviders[name];
132
+ const provider = registeredProviders[name]?.providerFn ?? initializedProviders[name];
115
133
 
116
134
  if ( provider ) {
117
135
  return provider;
package/src/llm/consts.js CHANGED
@@ -4,3 +4,16 @@ export const Role = {
4
4
  USER: 'user',
5
5
  ASSISTANT: 'assistant'
6
6
  };
7
+
8
+ export const CacheFreshness = Object.freeze( {
9
+ CACHED: 'cached',
10
+ STALE: 'stale',
11
+ SNAPSHOT: 'snapshot'
12
+ } );
13
+
14
+ /** Where an LLM generation cost total came from */
15
+ export const PricingSource = Object.freeze( {
16
+ MODELS_DEV: 'models.dev',
17
+ PROVIDER: 'provider'
18
+ } );
19
+
@@ -412,7 +412,8 @@ export interface LLMUsageEvent {
412
412
 
413
413
  export type LLMGenerationCostItemStatus = 'ok' | 'fallback' | 'uncertain' | 'missing';
414
414
  export type LLMGenerationCostStatus = 'precise' | 'imprecise' | 'incomplete';
415
- export type LLMGenerationCostPricingFreshness = 'live' | 'cached' | 'stale' | 'snapshot';
415
+ export type LLMGenerationCostPricingFreshness = 'cached' | 'stale' | 'snapshot';
416
+ export type LLMGenerationCostPricingSource = 'models.dev' | 'provider';
416
417
 
417
418
  /** Context-based pricing tier applied to a normalized cost item. */
418
419
  export interface LLMGenerationCostTier {
@@ -445,8 +446,10 @@ export interface LLMGenerationCost extends BaseAttribute {
445
446
  tools: number | null;
446
447
  total: number | null;
447
448
  status: LLMGenerationCostStatus;
448
- /** How current the rate table was. Absent on costs recorded before this field existed. */
449
+ /** How current the models.dev rate table was. Null when `pricingSource` is `provider`. */
449
450
  pricingFreshness?: LLMGenerationCostPricingFreshness | null;
451
+ /** Where `total` came from. Absent on costs recorded before this field existed. */
452
+ pricingSource?: LLMGenerationCostPricingSource;
450
453
  items: LLMGenerationCostItem[];
451
454
  }
452
455
 
@@ -515,23 +518,42 @@ export function loadPrompt(
515
518
  promptDir?: string
516
519
  ): Prompt;
517
520
 
521
+ /** Options for {@link registerProvider}. */
522
+ export type RegisterProviderOptions = {
523
+ /**
524
+ * Function called once per AI SDK step at bill time. Receives that step's `providerMetadata`
525
+ * (or `undefined`) and returns the dollar amount charged for the step, or `null` when missing.
526
+ * With no steps, metering falls back to `finalStep`, then top-level response `providerMetadata`.
527
+ * When set, metering bills only from this function and never from models.dev; legacy
528
+ * `cost:llm:request` is not emitted.
529
+ */
530
+ extractStepCost?: ( providerMetadata: Record<string, any> | undefined ) => number | null; // eslint-disable-line @typescript-eslint/no-explicit-any
531
+ };
532
+
518
533
  /**
519
534
  * Register a custom LLM provider for use in prompt files.
520
535
  *
521
536
  * @param name - Provider name (used in prompt config `provider` field)
522
537
  * @param providerFn - Factory function that creates a model from a model name string
538
+ * @param options - Optional `extractStepCost` function and other registration options
523
539
  *
524
540
  * @example
525
541
  * ```ts
526
- * import { createDeepSeek } from '@ai-sdk/deepseek';
542
+ * import { createOpenRouter } from '@openrouter/ai-sdk-provider';
527
543
  * import { registerProvider } from '@outputai/core/llm';
528
544
  *
529
- * registerProvider('deepseek', createDeepSeek({ apiKey: '...' }));
545
+ * registerProvider('openrouter', createOpenRouter({ apiKey: '...' }), {
546
+ * extractStepCost: ( providerMetadata ) => {
547
+ * const cost = providerMetadata?.openrouter?.usage?.cost;
548
+ * return typeof cost === 'number' ? cost : null;
549
+ * }
550
+ * });
530
551
  * ```
531
552
  */
532
553
  export function registerProvider(
533
554
  name: string,
534
- providerFn: ( modelName: string ) => unknown
555
+ providerFn: ( modelName: string ) => unknown,
556
+ options?: RegisterProviderOptions
535
557
  ): void;
536
558
 
537
559
  /**
@@ -0,0 +1,28 @@
1
+ import modelsPricingSnapshot from './models_pricing_snapshot.json' with { type: 'json' };
2
+ import { parseModelsDevData } from './parser.js';
3
+ import { CacheFreshness } from '../consts.js';
4
+
5
+ const snapshot = parseModelsDevData( modelsPricingSnapshot );
6
+
7
+ const CACHE_TTL = 1000 * 60 * 60 * 24; // 1 day
8
+
9
+ const cache = {
10
+ content: null,
11
+ expiresAt: 0
12
+ };
13
+
14
+ export const update = content => {
15
+ Object.assign( cache, {
16
+ content,
17
+ expiresAt: Date.now() + CACHE_TTL
18
+ } );
19
+ };
20
+
21
+ export const getPricing = () => {
22
+ if ( cache.content ) {
23
+ const freshness = cache.expiresAt > Date.now() ? CacheFreshness.CACHED : CacheFreshness.STALE;
24
+ return { models: cache.content, freshness };
25
+ }
26
+
27
+ return { models: snapshot, freshness: CacheFreshness.SNAPSHOT };
28
+ };
@@ -0,0 +1,83 @@
1
+ import { CancelableRunner } from '#helpers/cancelable_runner';
2
+ import { update as updateCache } from './cache.js';
3
+ import { Logger } from '#runtime_logger';
4
+ import { EnvHttpProxyAgent, fetch } from 'undici';
5
+ import { parseModelsDevData } from './parser.js';
6
+ import { sleepCancellable } from '#helpers/promise';
7
+
8
+ const log = Logger.createLogger( 'LLM Pricing Retriever' );
9
+
10
+ /* Ignore HTTP/2. Check: https://github.com/growthxai/output/issues/299 */
11
+ const dispatcher = new EnvHttpProxyAgent( { allowH2: false } );
12
+
13
+ const DATA_SOURCE_URL = 'https://models.dev/api.json';
14
+ const INTERVAL_AFTER_SUCCESS = 6 * 60 * 60 * 1000; // 6 hours
15
+ const INTERVAL_AFTER_ERROR = 5 * 60 * 1000; // 5 minutes
16
+
17
+ const fetchData = async signal => {
18
+ try {
19
+ const response = await fetch( DATA_SOURCE_URL, { dispatcher, signal } );
20
+ if ( !response.ok ) {
21
+ log.warn( 'Request error', { status: response.status } );
22
+ return null;
23
+ }
24
+
25
+ return await response.json();
26
+
27
+ } catch ( error ) {
28
+ if ( !signal.aborted ) {
29
+ log.warn( 'Request failure', { error: error.message, code: error.code } );
30
+ }
31
+ return null;
32
+ }
33
+ };
34
+
35
+ const refreshCache = async signal => {
36
+ const rawJson = await fetchData( signal );
37
+ if ( !rawJson ) {
38
+ return false;
39
+ }
40
+
41
+ try {
42
+ updateCache( parseModelsDevData( rawJson ) );
43
+ log.info( 'Data acquired' );
44
+ return true;
45
+ } catch ( error ) {
46
+ log.warn( 'Parsing failure', { error: error.message } );
47
+ return false;
48
+ }
49
+ };
50
+
51
+ /**
52
+ * Periodically fetches models pricing from models.dev, parses it and saves to the cache.
53
+ */
54
+ export class LLMPricingRetriever extends CancelableRunner {
55
+ #intervalAfterSuccess = INTERVAL_AFTER_SUCCESS;
56
+ #intervalAfterError = INTERVAL_AFTER_ERROR;
57
+
58
+ /**
59
+ * @param {object} options
60
+ * @param {AbortSignal} options.signal - stops the retriever when aborted
61
+ * @param {object} [options.overrides] - interval tuning, mostly for tests
62
+ */
63
+ constructor( { signal, overrides = {} } ) {
64
+ super( { signal } );
65
+ if ( Number.isFinite( overrides?.intervalAfterSuccess ) ) {
66
+ this.#intervalAfterSuccess = overrides.intervalAfterSuccess;
67
+ }
68
+ if ( Number.isFinite( overrides?.intervalAfterError ) ) {
69
+ this.#intervalAfterError = overrides.intervalAfterError;
70
+ }
71
+ }
72
+
73
+ /**
74
+ * @inheritdoc
75
+ * @param {AbortSignal} signal
76
+ */
77
+ async run( signal ) {
78
+ while ( !signal.aborted ) {
79
+ const success = await refreshCache( signal );
80
+ await sleepCancellable( success ? this.#intervalAfterSuccess : this.#intervalAfterError, signal );
81
+ }
82
+ }
83
+ };