@valerypopoff/rivet2-core 2.24.0 → 2.25.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 (43) hide show
  1. package/dist/cjs/bundle.cjs +273 -28
  2. package/dist/cjs/bundle.cjs.map +3 -3
  3. package/dist/cjs/interpolationRuntime.cjs +23 -0
  4. package/dist/cjs/interpolationRuntime.cjs.map +3 -3
  5. package/dist/cjs/serialization.cjs +1 -0
  6. package/dist/cjs/serialization.cjs.map +2 -2
  7. package/dist/esm/exports.js +3 -0
  8. package/dist/esm/model/DatasetOwnership.js +9 -0
  9. package/dist/esm/model/GraphExecutionState.js +3 -0
  10. package/dist/esm/model/GraphProcessor.js +62 -1
  11. package/dist/esm/model/RunCostLedger.js +58 -0
  12. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -2
  13. package/dist/esm/model/chat-v2/chatV2Outputs.js +1 -1
  14. package/dist/esm/model/chat-v2/chatV2Pipeline.js +5 -0
  15. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +3 -0
  16. package/dist/esm/model/chat-v2/llmModelCandidate.js +3 -0
  17. package/dist/esm/model/chat-v2/llmProfile.js +2 -0
  18. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -0
  19. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +2 -1
  20. package/dist/esm/model/chat-v2/modelRegistry.js +12 -3
  21. package/dist/esm/model/classifier/profile.js +11 -3
  22. package/dist/esm/model/classifier/profileExecution.js +2 -1
  23. package/dist/esm/model/classifier/providers.js +25 -14
  24. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +16 -5
  25. package/dist/esm/model/nodes/ClassifierProfileNode.js +2 -0
  26. package/dist/esm/model/tokenPricing.js +52 -0
  27. package/dist/esm/model/tokenPricingEditor.js +9 -0
  28. package/dist/types/exports.d.ts +3 -0
  29. package/dist/types/model/DatasetOwnership.d.ts +5 -0
  30. package/dist/types/model/GraphExecutionState.d.ts +2 -0
  31. package/dist/types/model/GraphProcessor.d.ts +3 -0
  32. package/dist/types/model/RunCostLedger.d.ts +19 -0
  33. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
  34. package/dist/types/model/chat-v2/chatV2Types.d.ts +2 -0
  35. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +3 -1
  36. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +7 -5
  37. package/dist/types/model/chat-v2/modelRegistry.d.ts +7 -1
  38. package/dist/types/model/classifier/profile.d.ts +3 -1
  39. package/dist/types/model/classifier/profileExecution.d.ts +1 -0
  40. package/dist/types/model/classifier/providers.d.ts +4 -1
  41. package/dist/types/model/tokenPricing.d.ts +18 -0
  42. package/dist/types/model/tokenPricingEditor.d.ts +4 -0
  43. package/package.json +1 -1
@@ -58,6 +58,8 @@ export * from './plugins.js';
58
58
  export * from './model/classifier/credentials.js';
59
59
  export * from './model/classifier/migration.js';
60
60
  export * from './model/classifier/providers.js';
61
+ export * from './model/tokenPricing.js';
62
+ export { getChatV2SystemTokenPricing } from './model/chat-v2/modelRegistry.js';
61
63
  export * from './model/classifier/types.js';
62
64
  export * from './model/NodeRegistration.js';
63
65
  export * from './model/RegistryAssembly.js';
@@ -66,6 +68,7 @@ export * from './model/NodeBodySpec.js';
66
68
  export * from './model/interpolationInputDefinition.js';
67
69
  export * from './integrations/DatasetProvider.js';
68
70
  export * from './model/Dataset.js';
71
+ export { remapOwnedDatasets } from './model/DatasetOwnership.js';
69
72
  export * from './api/streaming.js';
70
73
  export * from './api/createProcessor.js';
71
74
  export * from './api/processSettings.js';
@@ -0,0 +1,9 @@
1
+ /** Change only the owner of already validated sidecars. Reference/version
2
+ * rewiring is an operation-specific policy, not part of dataset ownership. */
3
+ export function remapOwnedDatasets(datasets, sourceId, targetId) {
4
+ return datasets.map((dataset) => {
5
+ if (dataset.meta.projectId !== sourceId)
6
+ throw new Error('Dataset ownership does not match the source project.');
7
+ return { ...dataset, meta: { ...dataset.meta, projectId: targetId } };
8
+ });
9
+ }
@@ -1,3 +1,4 @@
1
+ import { RunCostLedger } from './RunCostLedger.js';
1
2
  /** Invocation-owned fields; GraphProcessor resets them at the established initialization boundaries. */
2
3
  export class GraphInvocationState {
3
4
  rootRunId = undefined;
@@ -23,6 +24,7 @@ export class GraphInvocationState {
23
24
  successfulAbortTerminalProcessIds = undefined;
24
25
  totalCost = 0;
25
26
  costBreakdown;
27
+ costLedger = new RunCostLedger();
26
28
  ignoreNodes = undefined;
27
29
  hasPreloadedData = false;
28
30
  loadedProjects = undefined;
@@ -58,6 +60,7 @@ export class GraphInvocationState {
58
60
  this.successfulAbortTerminalProcessIds = new Set();
59
61
  this.totalCost = 0;
60
62
  this.costBreakdown = undefined;
63
+ this.costLedger = new RunCostLedger();
61
64
  this.nodeAbortControllers = new Map();
62
65
  this.loadedProjects = options.loadedProjects;
63
66
  this.graphInputNodeValues = options.sharedOverride?.graphInputNodeValues ?? {};
@@ -887,6 +887,8 @@ export class GraphProcessor {
887
887
  const hostChatV2Observer = this.getRootProcessor().#run.context.onChatV2CallFinished;
888
888
  const hostLLMChatOutputSnapshotObserver = this.getRootProcessor().#run.context.onLLMChatOutputSnapshot;
889
889
  const hostLLMProfileAttemptObserver = this.getRootProcessor().#run.context.onLLMProfileAttempt;
890
+ // Capture the invocation's ledger, not a later run that reuses this processor.
891
+ const costLedger = this.getRootProcessor().#run.costLedger;
890
892
  this.#run.nodeProcessContextBase = {
891
893
  ...this.#run.context,
892
894
  abortGraph: (error) => {
@@ -906,6 +908,12 @@ export class GraphProcessor {
906
908
  graphOutputs: this.#run.graphOutputs,
907
909
  graphCallPath: this.#graphCallPath,
908
910
  onChatV2CallFinished: (event) => {
911
+ try {
912
+ costLedger.observeChat(event);
913
+ }
914
+ catch {
915
+ costLedger.markUnobserved();
916
+ }
909
917
  try {
910
918
  const observerResult = hostChatV2Observer?.(event);
911
919
  if (observerResult != null && typeof observerResult.then === 'function') {
@@ -935,6 +943,12 @@ export class GraphProcessor {
935
943
  emitDetached(this.#emitter, 'llmChatOutputSnapshot', this.#withExecution(event));
936
944
  },
937
945
  onLLMProfileAttempt: (event) => {
946
+ try {
947
+ costLedger.observeClassifier(event);
948
+ }
949
+ catch {
950
+ costLedger.markUnobserved();
951
+ }
938
952
  try {
939
953
  const observerResult = hostLLMProfileAttemptObserver?.(event);
940
954
  if (observerResult != null && typeof observerResult.then === 'function') {
@@ -2107,6 +2121,11 @@ export class GraphProcessor {
2107
2121
  }
2108
2122
  return processor;
2109
2123
  }
2124
+ /** Snapshot the root execution's observed provider estimates after completion. */
2125
+ getRunCostSnapshot() {
2126
+ const root = this.getRootProcessor();
2127
+ return root.#run.costLedger.snapshot(root.isRunning);
2128
+ }
2110
2129
  #getEnclosingStreamingWatchInvocation() {
2111
2130
  let processor = this;
2112
2131
  while (processor) {
@@ -2204,11 +2223,22 @@ export class GraphProcessor {
2204
2223
  nodeAbortController.abort(getAbortSignalReason(this.#run.abortController.signal));
2205
2224
  }
2206
2225
  let continuationFinalized = false;
2226
+ const costLedger = this.getRootProcessor().#run.costLedger;
2227
+ const accountingKey = `${this.#run.graphRunId}:${processId}:${index}`;
2228
+ let accountingEntered = false;
2229
+ let observedPhysicalCall = false;
2230
+ let cacheHit = false;
2231
+ let accountingOutputs;
2207
2232
  try {
2208
2233
  const createContextProfileStart = this.#startRuntimeProfile();
2209
2234
  let context;
2210
2235
  try {
2211
- context = this.#createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput, undefined, markResultAsEditorCacheHit);
2236
+ context = this.#createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput, undefined, markResultAsEditorCacheHit
2237
+ ? () => {
2238
+ cacheHit = true;
2239
+ markResultAsEditorCacheHit();
2240
+ }
2241
+ : undefined);
2212
2242
  }
2213
2243
  finally {
2214
2244
  this.#finishRuntimeProfile('createNodeProcessContext', createContextProfileStart);
@@ -2217,10 +2247,27 @@ export class GraphProcessor {
2217
2247
  if (nodeAbortController.signal.aborted) {
2218
2248
  throw createGraphAbortErrorFromSignal(nodeAbortController.signal);
2219
2249
  }
2250
+ if (node.type === 'llmChatV2') {
2251
+ const observer = context.onChatV2CallFinished;
2252
+ context.onChatV2CallFinished = (event) => {
2253
+ observedPhysicalCall = true;
2254
+ observer?.(event);
2255
+ };
2256
+ }
2257
+ else if (node.type === 'classifierEvaluate') {
2258
+ const observer = context.onLLMProfileAttempt;
2259
+ context.onLLMProfileAttempt = (event) => {
2260
+ if (event.family === 'classifier' && event.attemptIndex !== undefined)
2261
+ observedPhysicalCall = true;
2262
+ observer?.(event);
2263
+ };
2264
+ }
2220
2265
  const implementationProfileStart = this.#startRuntimeProfile();
2221
2266
  let results;
2222
2267
  try {
2268
+ accountingEntered = true;
2223
2269
  results = await instance.process(inputValues, context);
2270
+ accountingOutputs = results;
2224
2271
  }
2225
2272
  finally {
2226
2273
  this.#finishRuntimeProfile('nodeImplementation', implementationProfileStart);
@@ -2242,6 +2289,20 @@ export class GraphProcessor {
2242
2289
  return results;
2243
2290
  }
2244
2291
  finally {
2292
+ if (accountingEntered && !cacheHit) {
2293
+ try {
2294
+ if (['chat', 'chatLoop', 'chatGoogle', 'chatAnthropic', 'chatHuggingFace', 'getEmbedding'].includes(node.type)) {
2295
+ const cost = accountingOutputs?.['cost'];
2296
+ costLedger.observeLegacy(accountingKey, cost?.type === 'number' ? cost.value : undefined);
2297
+ }
2298
+ else if ((node.type === 'llmChatV2' || node.type === 'classifierEvaluate') && !observedPhysicalCall) {
2299
+ costLedger.markUnobserved();
2300
+ }
2301
+ }
2302
+ catch {
2303
+ costLedger.markUnobserved();
2304
+ }
2305
+ }
2245
2306
  if (!continuationFinalized) {
2246
2307
  this.#discardToolCallContinuation(processId, index);
2247
2308
  }
@@ -0,0 +1,58 @@
1
+ /** Receives physical-call observations directly, before display/recording filters. */
2
+ export class RunCostLedger {
3
+ #calls = new Map();
4
+ #hasUnobservedWork = false;
5
+ observeChat(event) {
6
+ if (typeof event.callId !== 'string' || !event.callId) {
7
+ this.markUnobserved();
8
+ return;
9
+ }
10
+ this.#record(`llm:${event.callId}`, event.pricing.status === 'known' ? event.pricing.costUsd : undefined);
11
+ }
12
+ observeClassifier(event) {
13
+ if (event.family !== 'classifier' || event.attemptIndex === undefined)
14
+ return;
15
+ if (typeof event.eventId !== 'string' ||
16
+ !event.eventId ||
17
+ !Number.isSafeInteger(event.attemptIndex) ||
18
+ event.attemptIndex < 0) {
19
+ this.markUnobserved();
20
+ return;
21
+ }
22
+ this.#record(`decision:${event.eventId}`, event.classifierUsage?.estimatedCostUsd);
23
+ }
24
+ /** Legacy Chat does not expose complete per-attempt accounting. */
25
+ observeLegacy(key, value) {
26
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0)
27
+ this.#record(`legacy:${key}`, value);
28
+ this.markUnobserved();
29
+ }
30
+ markUnobserved() {
31
+ this.#hasUnobservedWork = true;
32
+ }
33
+ snapshot(executionPending = false) {
34
+ let known = 0;
35
+ let knownCount = 0;
36
+ let hasUnknownCost = this.#hasUnobservedWork || executionPending;
37
+ for (const cost of this.#calls.values()) {
38
+ if (cost === null)
39
+ hasUnknownCost = true;
40
+ else {
41
+ known += cost;
42
+ knownCount++;
43
+ }
44
+ }
45
+ if (!Number.isFinite(known))
46
+ return { status: 'unknown', knownCostUsd: null };
47
+ if (!hasUnknownCost)
48
+ return { status: 'complete', knownCostUsd: known };
49
+ if (knownCount === 0)
50
+ return { status: 'unknown', knownCostUsd: null };
51
+ return { status: 'partial', knownCostUsd: known };
52
+ }
53
+ #record(id, value) {
54
+ if (this.#calls.has(id))
55
+ return;
56
+ this.#calls.set(id, typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null);
57
+ }
58
+ }
@@ -109,9 +109,9 @@ export function notifyChatV2CallFinished(options, params) {
109
109
  const rawUsage = safelyRead(() => copyRawUsage(resultUsage ?? errorUsage));
110
110
  const normalizedUsage = safelyRead(() => normalizeObservedUsage(rawUsage));
111
111
  const modelInfo = safelyRead(() => getChatV2ModelInfo(options.provider, options.modelId));
112
- const calculatedCost = safelyRead(() => calculateChatV2UsageCost(options.provider, options.modelId, rawUsage, params.result?.providerMetadata));
112
+ const calculatedCost = safelyRead(() => calculateChatV2UsageCost(options.provider, options.modelId, resultUsage ?? errorUsage, params.result?.providerMetadata, options.tokenPricing));
113
113
  const costUsd = toUsageNumber(calculatedCost);
114
- const hasKnownPricing = modelInfo?.cost != null || (options.provider === 'openrouter' && costUsd != null);
114
+ const hasKnownPricing = options.tokenPricing != null || modelInfo?.cost != null || (options.provider === 'openrouter' && costUsd != null);
115
115
  const finishReason = safelyRead(() => params.result?.finishReason) ??
116
116
  getErrorProperty(params.error, 'finishReason', (value) => typeof value === 'string');
117
117
  const event = {
@@ -55,7 +55,7 @@ export function normalizeChatV2Usage(usage, options, providerMetadata) {
55
55
  totalTokens,
56
56
  cachedTokens,
57
57
  reasoningTokens,
58
- totalCost: calculateChatV2UsageCost(options.provider, options.modelId, usage, providerMetadata),
58
+ totalCost: calculateChatV2UsageCost(options.provider, options.modelId, usage, providerMetadata, options.tokenPricing),
59
59
  };
60
60
  }
61
61
  export function createChatV2ResponseOutput(response, structuredOutput, responseFormat) {
@@ -68,6 +68,7 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
68
68
  const callId = createObservedChatV2CallId(options);
69
69
  const callStartedAt = Date.now();
70
70
  let callWasObserved = false;
71
+ let completedResponse;
71
72
  // AI SDK accessors such as usage and reasoning may settle after a request
72
73
  // has otherwise failed. Their diagnostic callbacks belong only to this
73
74
  // physical request: never let a retired retry/fallback candidate overwrite
@@ -116,6 +117,9 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
116
117
  const result = transportMode === 'generate'
117
118
  ? await generateChatV2(attemptChatOptions)
118
119
  : await streamChatV2(attemptChatOptions);
120
+ // Cancellation during diagnostic finalization must not erase usage
121
+ // already returned by this physical attempt. It still wins the outcome.
122
+ completedResponse = result;
119
123
  signal.throwIfAborted();
120
124
  await options.responseBodyCapture?.flush();
121
125
  signal.throwIfAborted();
@@ -160,6 +164,7 @@ async function runChatV2WithRetry(options, chatOptions, retryPlan, signal, trans
160
164
  callId,
161
165
  attemptIndex: attempt,
162
166
  outcome: signal.aborted ? 'aborted' : 'provider-failure',
167
+ result: completedResponse,
163
168
  error,
164
169
  startedAt: callStartedAt,
165
170
  durationMs: Math.max(0, Date.now() - callStartedAt),
@@ -1,4 +1,5 @@
1
1
  import { profileSuspensionHints } from '../profileSuspensionHints.js';
2
+ import { getTokenPricingEditor } from '../tokenPricingEditor.js';
2
3
  import { STREAM_RESPONSE_HELPER_MESSAGE } from './chatV2Shared.js';
3
4
  import { DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS, DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES, } from './chatV2Retry.js';
4
5
  import { anthropicCacheControlTtlOptions, anthropicEffortOptions, anthropicThinkingModeOptions, chatV2ProviderOptions, customProviderApiOptions, getChatV2ModelOptions, googleThinkingLevelOptions, openAIReasoningEffortOptions, openAIWebSearchContextSizeOptions, } from './providerOptions.js';
@@ -624,6 +625,7 @@ export async function getLLMChatV2Editors(data, context) {
624
625
  ...(!usesProfile
625
626
  ? [
626
627
  getModelEditors(await getResolvedModelOptions(data, context)),
628
+ getTokenPricingEditor(),
627
629
  ...getProviderEditors(),
628
630
  getParameterEditors(),
629
631
  ...(data.provider === 'custom' ? [] : [getReasoningEditors()]),
@@ -640,6 +642,7 @@ export async function getLLMProfileEditors(data, context) {
640
642
  const profileData = data;
641
643
  return [
642
644
  getModelEditors(await getResolvedModelOptions(profileData, context)),
645
+ getTokenPricingEditor(),
643
646
  ...getProviderEditors(),
644
647
  getParameterEditors(),
645
648
  ...(profileData.provider === 'custom' ? [] : [getReasoningEditors()]),
@@ -8,9 +8,11 @@ import { createChatV2ResponseOutput, mergeCustomProviderResponseFormatOptions }
8
8
  import { parseCustomProviderApi } from './customProviderApi.js';
9
9
  import { parseChatV2Provider } from './providerOptions.js';
10
10
  import { restoreOpenAICompatibleInstructionRoles } from './developerMessageRoles.js';
11
+ import { validateTokenPricing } from '../tokenPricing.js';
11
12
  export async function resolveLLMModelCandidate(params) {
12
13
  const { plan, profile } = params;
13
14
  const effectiveData = profile ? applyLLMProfileToNodeData(plan.data, profile) : plan.data;
15
+ const tokenPricing = validateTokenPricing(effectiveData.tokenPricing);
14
16
  if (hasLLMChatV2ToolResponseFormatConflict(effectiveData)) {
15
17
  throw new Error(LLM_CHAT_V2_TOOL_RESPONSE_FORMAT_CONFLICT_COPY.paragraphs[0]);
16
18
  }
@@ -62,6 +64,7 @@ export async function resolveLLMModelCandidate(params) {
62
64
  requestBodyOverlay,
63
65
  runOptions: {
64
66
  ...baseRunOptions,
67
+ tokenPricing,
65
68
  provider,
66
69
  model: resolvedProvider.model,
67
70
  modelId,
@@ -5,6 +5,7 @@ import { LLM_PROFILE_VALUE_VERSION, pickLLMChatV2ProfileData } from './llmProfil
5
5
  import { createRivetLLMProfileHealthIdentity } from './llmProfileHealthStore.js';
6
6
  import { normalizeChatV2CredentialNamesByProvider } from './chatV2CredentialNames.js';
7
7
  import { normalizeTemperature } from './temperature.js';
8
+ import { validateTokenPricing } from '../tokenPricing.js';
8
9
  export { applyLLMProfileToNodeData, createDefaultLLMProfileValue, createLLMProfileNodeData, LLM_PROFILE_VALUE_VERSION, pickLLMChatV2ProfileData, } from './llmProfileTypes.js';
9
10
  const credentialSources = new Set([
10
11
  'input',
@@ -106,6 +107,7 @@ export function scopeLLMProfileHealthIdentity(profile, fallback) {
106
107
  };
107
108
  }
108
109
  function normalizeConfiguration(data) {
110
+ data = { ...data, tokenPricing: validateTokenPricing(data.tokenPricing) };
109
111
  for (const field of llmProfileStringDataKeys) {
110
112
  if (typeof data[field] !== 'string') {
111
113
  throw new Error(`LLM Profile ${field} must be a string.`);
@@ -1,4 +1,5 @@
1
1
  export const llmProfileFieldSpecs = [
2
+ { key: 'tokenPricing' },
2
3
  { key: 'model', inputId: 'model', valueKind: 'string' },
3
4
  { key: 'useModelInput', valueKind: 'boolean', resolvedInputToggle: true },
4
5
  { key: 'temperature', inputId: 'temperature', valueKind: 'optional-number' },
@@ -1,4 +1,5 @@
1
1
  import { coerceTypeOptional } from '../../utils/coerceType.js';
2
+ import { validateTokenPricing } from '../tokenPricing.js';
2
3
  import { getInputOrData } from '../../utils/inputs.js';
3
4
  import { resolveChatV2Credential } from './chatV2ProviderProfile.js';
4
5
  import { resolveLLMChatV2ExtraProviderOptions, resolveLLMChatV2GenerationParameters, resolveLLMChatV2Headers, } from './chatV2RuntimeOptions.js';
@@ -81,7 +82,7 @@ export function resolveLLMProfileNodeValue(params) {
81
82
  return {
82
83
  version: LLM_PROFILE_VALUE_VERSION,
83
84
  credential,
84
- configuration,
85
+ configuration: { ...configuration, tokenPricing: validateTokenPricing(configuration.tokenPricing) },
85
86
  ...(profileName === '' ? {} : { profileName }),
86
87
  ...(projectId == null
87
88
  ? {}
@@ -1,6 +1,7 @@
1
1
  import { anthropicModels } from '../../plugins/anthropic/anthropic.js';
2
2
  import { generativeAiGoogleModels } from '../../plugins/google/google.js';
3
3
  import { openaiModels } from '../../utils/openai.js';
4
+ import { calculateTokenUsageCost, isReportedTokenCount } from '../tokenPricing.js';
4
5
  const TOKENS_PER_THOUSAND = 1_000;
5
6
  function isFiniteNonNegative(value) {
6
7
  return typeof value === 'number' && Number.isFinite(value) && value >= 0;
@@ -55,9 +56,15 @@ export function getChatV2ModelInfo(provider, modelId) {
55
56
  const providerModels = chatV2ModelRegistry[provider];
56
57
  return providerModels[modelId];
57
58
  }
59
+ export function getChatV2SystemTokenPricing(provider, modelId) {
60
+ const cost = getChatV2ModelInfo(provider, modelId.trim())?.cost;
61
+ return cost == null
62
+ ? undefined
63
+ : { inputPerMillionTokens: cost.prompt * 1_000_000, outputPerMillionTokens: cost.completion * 1_000_000 };
64
+ }
58
65
  export function calculateChatV2Cost(provider, modelId, promptTokens, completionTokens) {
59
66
  const model = getChatV2ModelInfo(provider, modelId);
60
- if (model?.cost == null || !isFiniteNonNegative(promptTokens) || !isFiniteNonNegative(completionTokens)) {
67
+ if (model?.cost == null || !isReportedTokenCount(promptTokens) || !isReportedTokenCount(completionTokens)) {
61
68
  return undefined;
62
69
  }
63
70
  const cost = model.cost.prompt * promptTokens + model.cost.completion * completionTokens;
@@ -68,7 +75,9 @@ export function calculateChatV2Cost(provider, modelId, promptTokens, completionT
68
75
  * billable text-token counts are available. Cache discounts, long-context
69
76
  * premiums, and provider tool fees are not modeled in those estimates.
70
77
  */
71
- export function calculateChatV2UsageCost(provider, modelId, usage, providerMetadata) {
78
+ export function calculateChatV2UsageCost(provider, modelId, usage, providerMetadata, tokenPricing) {
79
+ if (tokenPricing !== undefined)
80
+ return calculateTokenUsageCost(tokenPricing, usage);
72
81
  if (provider === 'openrouter') {
73
82
  const reportedUsage = providerMetadata?.openrouter?.usage;
74
83
  const cost = reportedUsage != null && typeof reportedUsage === 'object'
@@ -76,7 +85,7 @@ export function calculateChatV2UsageCost(provider, modelId, usage, providerMetad
76
85
  : undefined;
77
86
  return isFiniteNonNegative(cost) ? cost : undefined;
78
87
  }
79
- if (!isFiniteNonNegative(usage?.inputTokens) || !isFiniteNonNegative(usage.outputTokens)) {
88
+ if (usage?.inputTokens == null || usage.outputTokens == null) {
80
89
  return undefined;
81
90
  }
82
91
  return calculateChatV2Cost(provider, modelId, usage.inputTokens, usage.outputTokens);
@@ -1,4 +1,5 @@
1
1
  import CryptoJS from 'crypto-js';
2
+ import { validateTokenPricing } from '../tokenPricing.js';
2
3
  import stableStringify from 'safe-stable-stringify';
3
4
  import { classifierInputDataValue, snapshotClassifierJson } from './json.js';
4
5
  import { ClassifierValueBudget } from './limits.js';
@@ -10,6 +11,7 @@ export const DEFAULT_CLASSIFIER_PROFILE_FAILURE_WINDOW_MS = 300_000;
10
11
  export const DEFAULT_CLASSIFIER_PROFILE_OPEN_DURATION_MS = 300_000;
11
12
  export const classifierProfileInputIds = ['model', 'apiKey'];
12
13
  export const classifierProfileDataKeys = [
14
+ 'tokenPricing',
13
15
  'provider',
14
16
  'model',
15
17
  'useModelInput',
@@ -77,11 +79,12 @@ function normalizeDetachedProfile(value) {
77
79
  throw new Error('Unknown Decision AI API key source.');
78
80
  classifierProfileResponseTimeout(configuration);
79
81
  classifierProfileHealthPolicy(configuration);
82
+ configuration.tokenPricing = validateTokenPricing(configuration.tokenPricing);
80
83
  return {
81
84
  version: 1,
82
- sourceNodeId: profile.sourceNodeId,
85
+ ...(profile.sourceNodeId === undefined ? {} : { sourceNodeId: profile.sourceNodeId }),
83
86
  // Blank names are absent, but authored whitespace must survive exact-default display aliases.
84
- profileName: profile.profileName?.trim() ? profile.profileName : undefined,
87
+ ...(profile.profileName?.trim() ? { profileName: profile.profileName } : {}),
85
88
  credential: credential.value === undefined ? {} : { value: credential.value.trim() },
86
89
  configuration: {
87
90
  ...pickClassifierProfileData(configuration),
@@ -125,7 +128,12 @@ export function resolveClassifierProfile(data, inputs, context) {
125
128
  }
126
129
  return normalizeClassifierProfileValue({
127
130
  version: 1,
128
- configuration: { ...pickClassifierProfileData(data), provider: provider.id, model, useModelInput: false },
131
+ configuration: {
132
+ ...pickClassifierProfileData({ ...data, tokenPricing: validateTokenPricing(data.tokenPricing) }),
133
+ provider: provider.id,
134
+ model,
135
+ useModelInput: false,
136
+ },
129
137
  credential: value === undefined ? {} : { value },
130
138
  profileName: context.node.title,
131
139
  sourceNodeId: context.node.id,
@@ -190,6 +190,7 @@ export async function runClassifierProfiles(input) {
190
190
  ...input.state,
191
191
  questions: input.questions,
192
192
  apiKey: profile.credential.value,
193
+ tokenPricing: profile.configuration.tokenPricing,
193
194
  model,
194
195
  ...(Number.isFinite(timeoutMs) ? { timeoutMs } : {}),
195
196
  deadline: input.deadline,
@@ -231,7 +232,7 @@ export async function runClassifierProfiles(input) {
231
232
  skipReason: 'unreached',
232
233
  });
233
234
  }
234
- return { result, provider, model };
235
+ return { result, provider, model, tokenPricing: profile.configuration.tokenPricing };
235
236
  }
236
237
  catch (error) {
237
238
  lastError = error;
@@ -1,3 +1,4 @@
1
+ import { calculateTokenUsageCost, isReportedTokenCount, validateTokenPricing, } from '../tokenPricing.js';
1
2
  import { JEV_DEFAULT_CREDENTIAL_NAMES, LIQUID_DEFAULT_CREDENTIAL_NAMES, OPENAI_DEFAULT_CREDENTIAL_NAMES, OPENROUTER_DEFAULT_CREDENTIAL_NAMES, PERPLEXITY_DEFAULT_CREDENTIAL_NAMES, SUBQ_DEFAULT_CREDENTIAL_NAMES, BASETEN_DEFAULT_CREDENTIAL_NAMES, } from './credentials.js';
2
3
  import { assertLiquidImageLimits } from './images.js';
3
4
  import { prepareClassifierState, inspectStateMessages, systemOneState, } from './state.js';
@@ -271,7 +272,11 @@ function createClassifierProvider(spec) {
271
272
  // discard non-enumerable/inherited content.
272
273
  if ('images' in input)
273
274
  throw new Error('Pass image evidence through State, not a separate images field.');
274
- const args = { ...input, fetchImplementation: input.fetchImplementation ?? fetch };
275
+ const args = {
276
+ ...input,
277
+ tokenPricing: validateTokenPricing(input.tokenPricing),
278
+ fetchImplementation: input.fetchImplementation ?? fetch,
279
+ };
275
280
  const operation = createOperation(args, provider.label);
276
281
  operation.check();
277
282
  if (typeof args.model !== 'string')
@@ -334,6 +339,11 @@ function normalizeModelPricing(provider) {
334
339
  return (provider.modelPricing ??
335
340
  (provider.pricing && provider.defaultModel ? [{ models: [provider.defaultModel], pricing: provider.pricing }] : []));
336
341
  }
342
+ export function getClassifierSystemTokenPricing(providerId, model) {
343
+ const provider = getClassifierProvider(providerId);
344
+ return normalizeModelPricing(provider).find((entry) => entry.models.includes(model?.trim() || provider.defaultModel))
345
+ ?.pricing;
346
+ }
337
347
  export function getClassifierProvider(id) {
338
348
  const provider = classifierProviders.find((candidate) => candidate.id === (id || jevClassifierProvider.id));
339
349
  if (!provider)
@@ -350,7 +360,12 @@ export function getClassifierProviderEnvironmentVariableNames() {
350
360
  * count or add image tokens again. Decisions has no separate cache charges.
351
361
  * Callers must not treat an unpriced provider as free.
352
362
  */
353
- export function calculateClassifierUsageCost(provider, usage, models) {
363
+ export function calculateClassifierUsageCost(provider, usage, models, tokenPricing) {
364
+ if (tokenPricing !== undefined)
365
+ return calculateTokenUsageCost(tokenPricing, {
366
+ inputTokens: usage.input_tokens,
367
+ outputTokens: usage.output_tokens,
368
+ });
354
369
  if (!models)
355
370
  return undefined;
356
371
  const entries = normalizeModelPricing(provider);
@@ -365,10 +380,8 @@ export function calculateClassifierUsageCost(provider, usage, models) {
365
380
  !validRates(base) ||
366
381
  (tier != null &&
367
382
  (!Number.isSafeInteger(tier.aboveInputTokens) || tier.aboveInputTokens < 0 || !validRates(tier))) ||
368
- !Number.isSafeInteger(usage.input_tokens) ||
369
- usage.input_tokens < 0 ||
370
- !Number.isSafeInteger(usage.output_tokens) ||
371
- usage.output_tokens < 0) {
383
+ !isReportedTokenCount(usage.input_tokens) ||
384
+ !isReportedTokenCount(usage.output_tokens)) {
372
385
  return undefined;
373
386
  }
374
387
  const pricing = tier && usage.input_tokens > tier.aboveInputTokens ? tier : base;
@@ -571,10 +584,10 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
571
584
  validatedResponse = validateResponse(body, prepared.questions, providerLabel);
572
585
  }
573
586
  catch (error) {
574
- report('failure', response.status, 'response-validation', classifierAttemptUsage(body, spec, args.model), error instanceof Error ? error.message : `${providerLabel} returned an invalid Decision AI response.`);
587
+ report('failure', response.status, 'response-validation', classifierAttemptUsage(body, spec, args.model, args.tokenPricing), error instanceof Error ? error.message : `${providerLabel} returned an invalid Decision AI response.`);
575
588
  throw new ClassifierProviderError(error instanceof Error ? error.message : `${providerLabel} returned an invalid Decision AI response.`, 'response-validation', undefined, { cause: error });
576
589
  }
577
- report('success', response.status, undefined, classifierAttemptUsage(body, spec, args.model));
590
+ report('success', response.status, undefined, classifierAttemptUsage(body, spec, args.model, args.tokenPricing));
578
591
  return {
579
592
  // Preserve the direct-provider result contract, but graph runs with the
580
593
  // diagnostic disabled never allocate this second representation.
@@ -592,7 +605,7 @@ async function callClassifierHttp(args, spec, prepared, buildRequest, operation)
592
605
  }
593
606
  }
594
607
  /** The bounded reader produced plain JSON; do not require valid answers to retain usable usage. */
595
- function classifierAttemptUsage(body, provider, requestedModel) {
608
+ function classifierAttemptUsage(body, provider, requestedModel, tokenPricing) {
596
609
  if (!body || typeof body !== 'object' || Array.isArray(body) || !Object.hasOwn(body, 'usage'))
597
610
  return;
598
611
  const { usage, model } = body;
@@ -601,13 +614,11 @@ function classifierAttemptUsage(body, provider, requestedModel) {
601
614
  Array.isArray(usage) ||
602
615
  !Object.hasOwn(usage, 'input_tokens') ||
603
616
  !Object.hasOwn(usage, 'output_tokens') ||
604
- !Number.isSafeInteger(usage.input_tokens) ||
605
- usage.input_tokens < 0 ||
606
- !Number.isSafeInteger(usage.output_tokens) ||
607
- usage.output_tokens < 0)
617
+ !isReportedTokenCount(usage.input_tokens) ||
618
+ !isReportedTokenCount(usage.output_tokens))
608
619
  return;
609
620
  const estimatedCostUsd = typeof model === 'string' && Object.hasOwn(body, 'model')
610
- ? calculateClassifierUsageCost(provider, usage, { requestedModel, responseModel: model })
621
+ ? calculateClassifierUsageCost(provider, usage, { requestedModel, responseModel: model }, tokenPricing)
611
622
  : undefined;
612
623
  return {
613
624
  inputTokens: usage.input_tokens,
@@ -8,6 +8,8 @@ import { getNextVariadicPortIndex } from './variadicPortIndex.js';
8
8
  import { resolveClassifierApiKey } from '../classifier/credentials.js';
9
9
  import { classifierArrayValues, classifierInputDataValue } from '../classifier/json.js';
10
10
  import { normalizeClassifierState } from '../classifier/state.js';
11
+ import { validateTokenPricing } from '../tokenPricing.js';
12
+ import { getTokenPricingEditor } from '../tokenPricingEditor.js';
11
13
  import { CLASSIFIER_LIMITS, ClassifierValueBudget } from '../classifier/limits.js';
12
14
  import { calculateClassifierUsageCost, classifierFailureKind, classifierProviders, DEFAULT_CLASSIFIER_RETRY_ON_NON_200_COOLDOWN_MS, DEFAULT_CLASSIFIER_RETRY_ON_NON_200_REPEAT_TIMES, getClassifierProvider, normalizeClassifierNon200RetryCooldownMs, normalizeClassifierNon200RetryCount, } from '../classifier/providers.js';
13
15
  import { normalizeClassifierProfiles } from '../classifier/profile.js';
@@ -112,6 +114,10 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
112
114
  return [
113
115
  { type: 'custom', label: 'Configuration', customEditorId: 'ClassifierConfiguration' },
114
116
  { ...getClassifierModelEditor(), hideIf: (data) => data.configurationMode === 'profile' },
117
+ {
118
+ ...getTokenPricingEditor(),
119
+ hideIf: (data) => data.configurationMode === 'profile',
120
+ },
115
121
  {
116
122
  type: 'group',
117
123
  label: 'Outputs',
@@ -120,7 +126,7 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
120
126
  type: 'toggle',
121
127
  label: 'Usage details',
122
128
  dataKey: 'outputUsage',
123
- helperMessage: 'Adds estimated totalCost to Usage only for recognized requested/returned models. Unknown pricing is omitted. Provider-specific premiums are not included.',
129
+ helperMessage: 'Adds estimated totalCost to Usage using explicit token prices or known model rates. Unknown pricing is omitted. Provider-specific premiums are not included.',
124
130
  },
125
131
  {
126
132
  type: 'toggle',
@@ -288,6 +294,7 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
288
294
  checkPreparation();
289
295
  if (this.data.configurationMode === 'profile')
290
296
  return this.processProfiles(inputs, context, checkPreparation, attempts, diagnostics);
297
+ const tokenPricing = validateTokenPricing(this.data.tokenPricing);
291
298
  const provider = getClassifierProvider(this.data.provider);
292
299
  if (!provider.browserExecutionSupported && context.executor === 'browser') {
293
300
  throw new Error(`${provider.label} cannot run in the Browser executor. Select the Node executor, or run through Studio Server or remote debugging.`);
@@ -337,6 +344,7 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
337
344
  throw new Error('Decision AI run requires at least one question.');
338
345
  const result = await (provider.evaluateInput ?? provider.evaluate).call(provider, {
339
346
  apiKey,
347
+ tokenPricing,
340
348
  model: modelValue,
341
349
  questions,
342
350
  retryOnNon200: this.data.retryOnNon200,
@@ -367,13 +375,16 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
367
375
  });
368
376
  // Custom providers own their transport; caller cancellation still wins.
369
377
  checkPreparation();
370
- return { ...this.projectResult(provider, modelValue, result, checkPreparation), ...this.profileEvidence(attempts) };
378
+ return {
379
+ ...this.projectResult(provider, modelValue, result, checkPreparation, tokenPricing),
380
+ ...this.profileEvidence(attempts),
381
+ };
371
382
  }
372
- projectResult(provider, modelValue, result, checkPreparation) {
383
+ projectResult(provider, modelValue, result, checkPreparation, tokenPricing) {
373
384
  const totalCost = calculateClassifierUsageCost(provider, result.response.usage, {
374
385
  requestedModel: modelValue,
375
386
  responseModel: result.response.model,
376
- });
387
+ }, tokenPricing);
377
388
  // The provider's parsed response may also be exposed verbatim through the
378
389
  // diagnostic output. Do not mutate its Usage object while adding Rivet's
379
390
  // calculated accounting detail.
@@ -457,7 +468,7 @@ export class ClassifierEvaluateNodeImpl extends NodeImpl {
457
468
  });
458
469
  check();
459
470
  return {
460
- ...this.projectResult(selected.provider, selected.model, selected.result, check),
471
+ ...this.projectResult(selected.provider, selected.model, selected.result, check, selected.tokenPricing),
461
472
  ...this.profileEvidence(attempts, classifierProfileSummary(profiles, attempts)),
462
473
  };
463
474
  }
@@ -5,6 +5,7 @@ import { resolveClassifierProfile, DEFAULT_CLASSIFIER_PROFILE_RESPONSE_TIMEOUT_M
5
5
  import { getClassifierModelEditor, getClassifierEvaluateBodySections } from './ClassifierEvaluateNode.js';
6
6
  import { formatNodeBodyMarkdownField } from '../nodeBodyMarkdown.js';
7
7
  import { profileSuspensionHints } from '../profileSuspensionHints.js';
8
+ import { getTokenPricingEditor } from '../tokenPricingEditor.js';
8
9
  export class ClassifierProfileNodeImpl extends NodeImpl {
9
10
  static create() {
10
11
  return {
@@ -38,6 +39,7 @@ export class ClassifierProfileNodeImpl extends NodeImpl {
38
39
  getEditors() {
39
40
  return [
40
41
  getClassifierModelEditor(),
42
+ getTokenPricingEditor(),
41
43
  {
42
44
  type: 'group',
43
45
  label: 'Decision AI profile suspension',