@valerypopoff/rivet2-core 2.1.10 → 2.3.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 (86) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/bundle.cjs +2101 -867
  3. package/dist/cjs/bundle.cjs.map +4 -4
  4. package/dist/cjs/webAppRuntime.cjs +37 -3
  5. package/dist/cjs/webAppRuntime.cjs.map +2 -2
  6. package/dist/esm/api/createProcessor.js +2 -0
  7. package/dist/esm/integrations/CodeRunner.js +2 -7
  8. package/dist/esm/integrations/CodeRunnerOptions.js +7 -0
  9. package/dist/esm/model/AgentResponseTrace.js +121 -11
  10. package/dist/esm/model/GraphProcessor.js +14 -0
  11. package/dist/esm/model/RecordingPlayer.js +50 -5
  12. package/dist/esm/model/SubprocessorBridge.js +1 -0
  13. package/dist/esm/model/UiGraphActionProtocol.js +1 -0
  14. package/dist/esm/model/chat-v2/aiSdkBridge.js +146 -14
  15. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -0
  16. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +93 -0
  17. package/dist/esm/model/chat-v2/chatV2EditorCache.js +6 -5
  18. package/dist/esm/model/chat-v2/chatV2Pipeline.js +41 -4
  19. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +31 -2
  20. package/dist/esm/model/chat-v2/chatV2ResponseBodyCapture.js +10 -2
  21. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +6 -11
  22. package/dist/esm/model/chat-v2/chatV2Shared.js +1 -1
  23. package/dist/esm/model/chat-v2/chatV2Types.js +16 -0
  24. package/dist/esm/model/chat-v2/customProviderApi.js +0 -2
  25. package/dist/esm/model/chat-v2/index.js +3 -0
  26. package/dist/esm/model/chat-v2/llmChatV2Body.js +9 -1
  27. package/dist/esm/model/chat-v2/llmChatV2CachePolicy.js +5 -0
  28. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +7 -0
  29. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +95 -14
  30. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +32 -9
  31. package/dist/esm/model/chat-v2/llmModelCandidate.js +5 -1
  32. package/dist/esm/model/chat-v2/llmProfile.js +42 -0
  33. package/dist/esm/model/chat-v2/llmProfileBody.js +10 -0
  34. package/dist/esm/model/chat-v2/llmProfileFallback.js +390 -4
  35. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +7 -0
  36. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +326 -0
  37. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +53 -34
  38. package/dist/esm/model/chat-v2/providerOptions.js +33 -7
  39. package/dist/esm/model/nodes/CodeNewNode.js +5 -47
  40. package/dist/esm/model/nodes/CodeNode.js +4 -46
  41. package/dist/esm/model/nodes/ExpressionNode.js +5 -8
  42. package/dist/esm/model/nodes/LLMChatV2Node.js +10 -1
  43. package/dist/esm/model/nodes/MatchNode.js +86 -41
  44. package/dist/esm/plugins/gentrace/gentraceSdk.js +0 -1
  45. package/dist/esm/plugins/gentrace/index.js +0 -1
  46. package/dist/esm/plugins/gentrace/plugin.js +61 -179
  47. package/dist/esm/plugins.js +1 -2
  48. package/dist/esm/recording/ExecutionRecorder.js +49 -8
  49. package/dist/types/api/createProcessor.d.ts +3 -0
  50. package/dist/types/integrations/CodeRunner.d.ts +10 -7
  51. package/dist/types/integrations/CodeRunnerOptions.d.ts +15 -0
  52. package/dist/types/model/AgentResponseTrace.d.ts +14 -1
  53. package/dist/types/model/EditorDefinition.d.ts +16 -0
  54. package/dist/types/model/ExecutorProtocol.d.ts +9 -6
  55. package/dist/types/model/GraphProcessor.d.ts +15 -5
  56. package/dist/types/model/NodeBase.d.ts +0 -10
  57. package/dist/types/model/Nodes.d.ts +2 -2
  58. package/dist/types/model/ProcessContext.d.ts +52 -0
  59. package/dist/types/model/UiGraphActionProtocol.d.ts +1 -0
  60. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +30 -0
  61. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +1 -0
  62. package/dist/types/model/chat-v2/chatV2ProviderProfile.d.ts +3 -0
  63. package/dist/types/model/chat-v2/chatV2ResponseBodyCapture.d.ts +8 -2
  64. package/dist/types/model/chat-v2/chatV2RuntimeOptions.d.ts +3 -8
  65. package/dist/types/model/chat-v2/chatV2Types.d.ts +24 -0
  66. package/dist/types/model/chat-v2/customProviderApi.d.ts +0 -1
  67. package/dist/types/model/chat-v2/index.d.ts +3 -0
  68. package/dist/types/model/chat-v2/llmChatV2CachePolicy.d.ts +1 -1
  69. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +10 -1
  70. package/dist/types/model/chat-v2/llmModelCandidate.d.ts +2 -0
  71. package/dist/types/model/chat-v2/llmProfile.d.ts +14 -0
  72. package/dist/types/model/chat-v2/llmProfileBody.d.ts +1 -1
  73. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +21 -2
  74. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +26 -6
  75. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +111 -0
  76. package/dist/types/model/chat-v2/llmProfileNodeRuntime.d.ts +1 -1
  77. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +3 -0
  78. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -0
  79. package/dist/types/model/nodes/CodeNewNode.d.ts +0 -5
  80. package/dist/types/model/nodes/CodeNode.d.ts +0 -5
  81. package/dist/types/model/nodes/MatchNode.d.ts +6 -0
  82. package/dist/types/plugins/gentrace/gentraceSdk.d.ts +0 -1
  83. package/dist/types/plugins/gentrace/plugin.d.ts +55 -9
  84. package/dist/types/plugins.d.ts +1 -1
  85. package/dist/types/recording/ExecutionRecorder.d.ts +7 -1
  86. package/package.json +2 -2
@@ -5,6 +5,8 @@ import {} from '../../index.js';
5
5
  import { dedent } from 'ts-dedent';
6
6
  import { nodeDefinition } from '../NodeDefinition.js';
7
7
  import { buildJsValueInterpolatedSource, buildJsValueInputsInitializer, buildJsValuePreview, getJsValueInterpolationInputDefinitions, getJsValueInterpolationRuntimeContext, interpolateJsValuePreviewSource, sanitizeGeneratedJsValueError, } from './jsValueInterpolation.js';
8
+ import { ALL_CODE_RUNNER_OPTIONS } from '../../integrations/CodeRunnerOptions.js';
9
+ const CODE_RUNTIME_HELPER_MESSAGE = 'Node execution also provides "require" and "process". Browser execution provides "fetch", "console", and "Rivet".';
8
10
  const DEFAULT_EXPRESSION = '{{a}} == "123" ? {{b}} : {{c}}';
9
11
  const MAX_BODY_PREVIEW_LINES = 15;
10
12
  const EXPRESSION_INPUTS_IDENTIFIER = '__expressionInputs';
@@ -77,7 +79,8 @@ export class ExpressionNodeImpl extends NodeImpl {
77
79
  {
78
80
  type: 'code',
79
81
  label: 'Expression',
80
- helperMessage: 'Use {{var}} to create input ports. Interpolated variables evaluate as the connected values.',
82
+ helperMessage: 'Use {{var}} to create input ports. Interpolated variables evaluate as the connected values. ' +
83
+ CODE_RUNTIME_HELPER_MESSAGE,
81
84
  dataKey: 'expression',
82
85
  language: 'javascript',
83
86
  interpolationSyntax: 'js-value',
@@ -111,13 +114,7 @@ export class ExpressionNodeImpl extends NodeImpl {
111
114
  const { inputNames, inputsIdentifier } = interpolationContext;
112
115
  const source = buildExpressionWrapper(this.data.expression, interpolationContext);
113
116
  try {
114
- return await context.codeRunner.runCode(source, inputs, {
115
- includeFetch: false,
116
- includeRequire: false,
117
- includeRivet: false,
118
- includeProcess: false,
119
- includeConsole: false,
120
- }, context.graphInputNodeValues, context.contextValues);
117
+ return await context.codeRunner.runCode(source, inputs, ALL_CODE_RUNNER_OPTIONS, context.graphInputNodeValues, context.contextValues);
121
118
  }
122
119
  catch (error) {
123
120
  throw sanitizeExpressionError(error, inputNames, inputsIdentifier);
@@ -262,6 +262,7 @@ export class LLMChatV2NodeImpl extends NodeImpl {
262
262
  }
263
263
  async process(inputs, context) {
264
264
  const invocationJournal = new LLMInvocationJournal();
265
+ let profileAttemptSequence = 0;
265
266
  // Retries, fallback profiles, and tool continuation produce several
266
267
  // physical provider calls underneath one node invocation. Always observe
267
268
  // them locally so every later output projection shares one truthful
@@ -283,7 +284,15 @@ export class LLMChatV2NodeImpl extends NodeImpl {
283
284
  nodeId: this.chartNode.id,
284
285
  inputs,
285
286
  context: usageTrackingContext,
286
- onLLMAttempt: (attempt) => invocationJournal.recordLLMAttempt(attempt),
287
+ onLLMAttempt: (attempt) => {
288
+ invocationJournal.recordLLMAttempt(attempt);
289
+ context.onLLMProfileAttempt?.({
290
+ ...attempt,
291
+ eventId: `${context.processId}:llm-profile-attempt:${profileAttemptSequence++}`,
292
+ nodeId: context.node.id,
293
+ processId: context.processId,
294
+ });
295
+ },
287
296
  });
288
297
  const toolCallContinuation = context.toolCallContinuation;
289
298
  const cacheHit = projectLLMChatV2EditorCacheHit(runtime);
@@ -21,6 +21,7 @@ export class MatchNodeImpl extends NodeImpl {
21
21
  data: {
22
22
  cases: ['YES', 'NO'],
23
23
  casePortIds: [nanoid(), nanoid()],
24
+ valueInputMode: 'shared',
24
25
  },
25
26
  };
26
27
  return chartNode;
@@ -34,57 +35,86 @@ export class MatchNodeImpl extends NodeImpl {
34
35
  required: true,
35
36
  description: 'The value that will be tested against each of the cases.',
36
37
  },
37
- {
38
+ ];
39
+ if (this.getValueInputMode() === 'shared') {
40
+ inputs.push({
38
41
  id: 'value',
39
- title: 'Value',
42
+ title: 'Custom value',
40
43
  dataType: 'any',
41
- description: 'The value passed through to the output port that matches. If unconnected, the test value will be passed through.',
42
- },
43
- ];
44
+ description: 'The optional value passed through to every matching output. If unconnected, the Test value is passed through.',
45
+ });
46
+ }
47
+ else {
48
+ const portIds = this.getCasePortIds();
49
+ this.data.cases.forEach((caseValue, index) => {
50
+ inputs.push({
51
+ id: this.getCaseValueInputId(portIds[index]),
52
+ title: this.getCaseTitle(caseValue, index),
53
+ dataType: 'any',
54
+ description: `The optional custom value emitted when /${caseValue}/ matches the Test value. If unconnected, Test is passed through.`,
55
+ });
56
+ });
57
+ inputs.push({
58
+ id: 'value-unmatched',
59
+ title: 'Unmatched',
60
+ dataType: 'any',
61
+ description: 'The optional custom value emitted when no regular expression matches the Test value. If unconnected, Test is passed through.',
62
+ });
63
+ }
44
64
  return inputs;
45
65
  }
46
66
  getOutputDefinitions() {
47
67
  const outputs = [];
48
- const portIds = resolveStoredOrderedPortIds(this.data.cases.length, this.data.casePortIds, {
49
- kind: 'prefix',
50
- prefix: 'case',
51
- startIndex: 1,
52
- });
68
+ const portIds = this.getCasePortIds();
53
69
  for (let i = 0; i < this.data.cases.length; i++) {
54
70
  outputs.push({
55
71
  id: portIds[i],
56
- title: this.data.cases[i]?.trim() ? this.data.cases[i] : `Case ${i + 1}`,
57
- dataType: 'string',
58
- description: `The 'value' (or 'test' if value is unconnected) passed through if the test value matches this regex: /${this
59
- .data.cases[i]}/`,
72
+ title: this.getCaseTitle(this.data.cases[i], i),
73
+ dataType: 'any',
74
+ description: this.getValueInputMode() === 'shared'
75
+ ? `The shared Custom value (or Test if Custom value is unconnected) passed through if the test value matches /${this.data.cases[i]}/.`
76
+ : `The corresponding ${this.getCaseTitle(this.data.cases[i], i)} custom value (or Test if it is unconnected) passed through if the test value matches /${this.data.cases[i]}/.`,
60
77
  });
61
78
  }
62
79
  outputs.push({
63
80
  id: 'unmatched',
64
81
  title: 'Unmatched',
65
- dataType: 'string',
66
- description: 'The value (or test if value is unconnected) passed through if no regexes match.',
82
+ dataType: 'any',
83
+ description: this.getValueInputMode() === 'shared'
84
+ ? 'The shared Custom value (or Test if Custom value is unconnected) passed through if no regexes match.'
85
+ : 'The Unmatched custom value (or Test if it is unconnected) passed through if no regexes match.',
67
86
  });
68
87
  return outputs;
69
88
  }
70
89
  getBody() {
71
- return dedent `
72
- ${this.data.exclusive ? 'First Matching Case' : 'All Matching Cases'}
73
- ${this.data.cases.length} Cases
74
- `;
90
+ return this.data.exclusive ? 'Trigger the first matching case only' : 'Trigger all matching cases';
75
91
  }
76
92
  getEditors() {
77
93
  return [
78
94
  {
79
- type: 'toggle',
95
+ type: 'segmented',
96
+ label: 'Matching cases to trigger',
80
97
  dataKey: 'exclusive',
81
- label: 'Exclusive',
82
- helperMessage: 'If enabled, only the first matching branch will be ran.',
98
+ defaultValue: false,
99
+ options: [
100
+ { value: false, label: 'Trigger all matching cases' },
101
+ { value: true, label: 'Trigger first only' },
102
+ ],
103
+ },
104
+ {
105
+ type: 'segmented',
106
+ label: 'Custom case values',
107
+ dataKey: 'valueInputMode',
108
+ defaultValue: 'shared',
109
+ options: [
110
+ { value: 'shared', label: 'One shared custom value' },
111
+ { value: 'per-output', label: 'Custom values per case' },
112
+ ],
83
113
  },
84
114
  {
85
115
  type: 'stringList',
86
116
  dataKey: 'cases',
87
- label: 'Cases',
117
+ label: 'Cases (regular expressions)',
88
118
  placeholder: 'Case (regular expression)',
89
119
  reorderable: true,
90
120
  portBinding: {
@@ -96,15 +126,15 @@ export class MatchNodeImpl extends NodeImpl {
96
126
  prefix: 'case',
97
127
  startIndex: 1,
98
128
  },
129
+ companionBindings: [{ side: 'input', prefix: 'value-' }],
99
130
  },
100
- helperMessage: '(Regular expressions)',
101
131
  },
102
132
  ];
103
133
  }
104
134
  static getUIData() {
105
135
  return {
106
136
  infoBoxBody: dedent `
107
- Any number of regular expressions can be configured, each corresponding to an output of the node. The output port of the first matching regex will be ran, and all other output ports will not be ran.
137
+ Configure any number of regular expressions, each corresponding to an output. Trigger all matched outputs by default, or choose Trigger first matching case. One shared custom value passes one optional value to every active output, while Custom values per case gives each case and Unmatched output its own optional custom value input.
108
138
  `,
109
139
  infoBoxTitle: 'Regex Match Node',
110
140
  contextMenuTitle: 'Regex Match',
@@ -114,14 +144,19 @@ export class MatchNodeImpl extends NodeImpl {
114
144
  async process(inputs) {
115
145
  const inputValue = inputs['input'];
116
146
  const inputString = inputValue?.value == null ? undefined : coerceType(inputValue, 'string');
117
- const value = inputs['value'];
118
- const portIds = resolveStoredOrderedPortIds(this.data.cases.length, this.data.casePortIds, {
119
- kind: 'prefix',
120
- prefix: 'case',
121
- startIndex: 1,
147
+ const portIds = this.getCasePortIds();
148
+ const sharedValue = inputs['value'];
149
+ const getTestOutputValue = () => ({
150
+ type: 'string',
151
+ value: inputString,
122
152
  });
123
- const outputType = value === undefined ? 'string' : value.type;
124
- const outputValue = value === undefined ? inputString : value.value;
153
+ const getSharedOutputValue = () => sharedValue ?? getTestOutputValue();
154
+ const getOutputValue = (portId) => this.getValueInputMode() === 'shared'
155
+ ? getSharedOutputValue()
156
+ : inputs[this.getCaseValueInputId(portId)] ?? getTestOutputValue();
157
+ const getUnmatchedOutputValue = () => this.getValueInputMode() === 'shared'
158
+ ? getSharedOutputValue()
159
+ : inputs['value-unmatched'] ?? getTestOutputValue();
125
160
  const cases = this.data.cases;
126
161
  let matched = false;
127
162
  const output = {};
@@ -130,10 +165,7 @@ export class MatchNodeImpl extends NodeImpl {
130
165
  const canMatch = !this.data.exclusive || !matched;
131
166
  if (match && canMatch) {
132
167
  matched = true;
133
- output[portIds[i]] = {
134
- type: outputType,
135
- value: outputValue,
136
- };
168
+ output[portIds[i]] = getOutputValue(portIds[i]);
137
169
  }
138
170
  else {
139
171
  output[portIds[i]] = {
@@ -143,10 +175,7 @@ export class MatchNodeImpl extends NodeImpl {
143
175
  }
144
176
  }
145
177
  if (!matched) {
146
- output['unmatched'] = {
147
- type: outputType,
148
- value: outputValue,
149
- };
178
+ output['unmatched'] = getUnmatchedOutputValue();
150
179
  }
151
180
  else {
152
181
  output['unmatched'] = {
@@ -156,5 +185,21 @@ export class MatchNodeImpl extends NodeImpl {
156
185
  }
157
186
  return output;
158
187
  }
188
+ getValueInputMode() {
189
+ return this.data.valueInputMode === 'per-output' ? 'per-output' : 'shared';
190
+ }
191
+ getCasePortIds() {
192
+ return resolveStoredOrderedPortIds(this.data.cases.length, this.data.casePortIds, {
193
+ kind: 'prefix',
194
+ prefix: 'case',
195
+ startIndex: 1,
196
+ });
197
+ }
198
+ getCaseTitle(caseValue, index) {
199
+ return caseValue?.trim() ? caseValue : `Case ${index + 1}`;
200
+ }
201
+ getCaseValueInputId(portId) {
202
+ return `value-${portId}`;
203
+ }
159
204
  }
160
205
  export const matchNode = nodeDefinition(MatchNodeImpl, 'Regex Match');
@@ -4,5 +4,4 @@
4
4
  export { init } from '@gentrace/core/dist/providers/init.mjs';
5
5
  export { getPipelines } from '@gentrace/core/dist/providers/pipeline-methods.mjs';
6
6
  export { Pipeline } from '@gentrace/core/dist/providers/pipeline.mjs';
7
- export { runTest } from '@gentrace/core/dist/providers/run-test.mjs';
8
7
  export { StepRun } from '@gentrace/core/dist/providers/step-run.mjs';
@@ -1,3 +1,2 @@
1
- // eslint-disable-next-line import/no-cycle -- The plugin implementation uses GraphProcessor to execute local Gentrace tests.
2
1
  import { gentracePlugin } from './plugin.js';
3
2
  export default gentracePlugin;
@@ -1,12 +1,4 @@
1
- import { Pipeline, StepRun, init, runTest, getPipelines } from './gentraceSdk.js';
2
- import { globalRivetNodeRegistry } from '../../model/Nodes.js';
3
- import { cloneDeep, mapValues } from 'lodash-es';
4
- import { GptTokenizerTokenizer } from '../../integrations/GptTokenizerTokenizer.js';
5
- import { ExecutionRecorder } from '../../recording/ExecutionRecorder.js';
6
- import { inferType } from '../../utils/coerceType.js';
7
- // eslint-disable-next-line import/no-cycle -- Local Gentrace execution intentionally depends on GraphProcessor.
8
- import { GraphProcessor } from '../../model/GraphProcessor.js';
9
- import { resolveProcessSettings } from '../../api/processSettings.js';
1
+ import { Pipeline, StepRun, getPipelines, init } from './gentraceSdk.js';
10
2
  const apiKeyConfigSpec = {
11
3
  type: 'secret',
12
4
  label: 'Gentrace API Key',
@@ -15,183 +7,73 @@ const apiKeyConfigSpec = {
15
7
  helperText: 'Create at https://gentrace.ai/settings/api-keys',
16
8
  };
17
9
  function initializeGentrace(gentraceApiKey) {
18
- init({
19
- apiKey: gentraceApiKey,
20
- });
21
- }
22
- export const runGentraceTests = async (gentracePipelineSlug, settings, project, graph, nativeApi, contextValues = {}) => {
23
- const gentraceApiKey = settings.pluginSettings?.gentrace?.gentraceApiKey;
24
- if (!gentraceApiKey) {
10
+ if (!gentraceApiKey)
25
11
  throw new Error('Gentrace API key not set.');
12
+ init({ apiKey: gentraceApiKey });
13
+ }
14
+ function timestampForTrial(run, durationMs, index) {
15
+ const runStart = Date.parse(run.startedAt);
16
+ const safeStart = Number.isFinite(runStart) ? runStart + index : Date.now();
17
+ const safeDuration = Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : 0;
18
+ return {
19
+ start: new Date(safeStart).toISOString(),
20
+ end: new Date(safeStart + safeDuration).toISOString(),
21
+ };
22
+ }
23
+ /**
24
+ * Exports an already completed Rivet Evaluation as one Gentrace pipeline run.
25
+ * It never fetches Gentrace test cases and never executes a Rivet graph: the
26
+ * generic Evaluations runner remains the sole execution engine.
27
+ */
28
+ export async function exportGentraceEvaluationRun(input) {
29
+ initializeGentrace(input.gentraceApiKey);
30
+ if (!input.pipelineSlug)
31
+ throw new Error('Gentrace pipeline slug is required.');
32
+ if (input.run.executionStatus !== 'completed') {
33
+ throw new Error('Only completed Rivet Evaluation runs can be exported to Gentrace.');
26
34
  }
27
- const graphId = graph.metadata?.id;
28
- if (!graphId) {
29
- throw new Error('Graph ID not set.');
30
- }
31
- initializeGentrace(gentraceApiKey);
32
- const response = await runTest(gentracePipelineSlug, async (testCase) => {
33
- const pipeline = new Pipeline({
34
- slug: gentracePipelineSlug,
35
- });
36
- const runner = pipeline.start();
37
- const rivetFormattedInputs = mapValues(testCase.inputs, inferType);
38
- const tempProject = {
39
- ...project,
40
- graphs: {
41
- ...project.graphs,
42
- [graph.metadata.id]: graph,
43
- },
44
- };
45
- const recorder = new ExecutionRecorder();
46
- const processor = new GraphProcessor(tempProject, graphId, globalRivetNodeRegistry);
47
- processor.executor = 'browser';
48
- recorder.record(processor);
49
- const runContextValues = cloneDeep(contextValues);
50
- await processor.processGraph({
51
- settings: resolveProcessSettings(settings),
52
- nativeApi,
53
- tokenizer: new GptTokenizerTokenizer(),
54
- }, rivetFormattedInputs, runContextValues);
55
- const fullRecording = recorder.getRecording();
56
- const stepRuns = convertRecordingToStepRuns(fullRecording, project, graphId);
57
- for (const stepRun of stepRuns) {
58
- await runner.addStepRunNode(stepRun);
59
- }
60
- if (stepRuns.length === 0) {
61
- throw new Error('No Rivet steps found. You need operations which are not Graph Input or Graph Output nodes.');
62
- }
63
- return ['', runner];
64
- });
65
- return response;
66
- };
67
- export const runRemoteGentraceTests = async (gentracePipelineSlug, settings, project, graph, runAndRecord) => {
68
- const gentraceApiKey = settings.pluginSettings?.gentrace?.gentraceApiKey;
69
- if (!gentraceApiKey) {
70
- throw new Error('Gentrace API key not set.');
71
- }
72
- const graphId = graph.metadata?.id;
73
- if (!graphId) {
74
- throw new Error('Graph ID not set.');
75
- }
76
- initializeGentrace(gentraceApiKey);
77
- const response = await runTest(gentracePipelineSlug, async (testCase) => {
78
- const pipeline = new Pipeline({
79
- slug: gentracePipelineSlug,
80
- });
81
- const runner = pipeline.start();
82
- const rivetFormattedInputs = mapValues(testCase.inputs, inferType);
83
- const fullRecording = await runAndRecord(rivetFormattedInputs);
84
- const stepRuns = convertRecordingToStepRuns(fullRecording, project, graphId);
85
- for (const stepRun of stepRuns) {
86
- await runner.addStepRunNode(stepRun);
87
- }
88
- if (stepRuns.length === 0) {
89
- throw new Error('No Rivet steps found. You need operations which are not Graph Input or Graph Output nodes.');
90
- }
91
- return ['', runner];
92
- });
93
- return response;
94
- };
95
- function convertRecordingToStepRuns(recording, project, graphId) {
96
- const partialProcessStartEndPairs = {};
97
- recording.events.forEach((event) => {
98
- const eventType = event?.type;
99
- if (!eventType) {
100
- return;
101
- }
102
- if (eventType === 'nodeStart' || eventType === 'nodeFinish') {
103
- const processId = event?.data?.processId;
104
- const nodeId = event?.data?.nodeId;
105
- if (!processId) {
106
- return;
107
- }
108
- let existingPair = partialProcessStartEndPairs[processId];
109
- if (!existingPair) {
110
- existingPair = {};
111
- partialProcessStartEndPairs[processId] = existingPair;
112
- }
113
- existingPair.nodeId = nodeId;
114
- if (eventType === 'nodeStart') {
115
- existingPair.start = event.ts;
116
- existingPair.inputs = event.data.inputs;
117
- }
118
- else {
119
- existingPair.end = event.ts;
120
- existingPair.outputs = event.data.outputs;
121
- }
122
- }
35
+ const pipeline = new Pipeline({ slug: input.pipelineSlug });
36
+ const runner = pipeline.start({
37
+ metadata: {
38
+ source: { type: 'string', value: 'rivet-evaluations' },
39
+ evaluationRunId: { type: 'string', value: input.run.id },
40
+ suiteName: { type: 'string', value: input.run.suiteName },
41
+ purpose: { type: 'string', value: input.run.purpose },
42
+ qualityStatus: { type: 'string', value: input.run.qualityStatus },
43
+ qualityReason: { type: 'string', value: input.run.qualityReason.message },
44
+ accountingStatus: { type: 'string', value: input.run.accountingStatus },
45
+ executionStatus: { type: 'string', value: input.run.executionStatus },
46
+ },
123
47
  });
124
- const processStartEndPairs = partialProcessStartEndPairs;
125
- const selectedGraph = project.graphs[graphId];
126
- if (!selectedGraph) {
127
- return [];
128
- }
129
- // Convert to step runs
130
- const stepRuns = [];
131
- for (const [, pair] of Object.entries(processStartEndPairs)) {
132
- const { nodeId } = pair;
133
- const relatedNode = selectedGraph.nodes.find((node) => node.id === nodeId);
134
- const nodeType = relatedNode?.type;
135
- if (!nodeType || !relatedNode.data || nodeType === 'graphInput' || nodeType === 'graphOutput') {
136
- continue;
137
- }
138
- const nodeData = relatedNode.data;
139
- if (relatedNode) {
140
- pair.modelParams = { ...nodeData, ...{ type: nodeType } };
141
- }
142
- if (nodeType === 'chat') {
143
- const modelName = nodeData.model ? nodeData.model : '';
144
- if (modelName.startsWith('gpt')) {
145
- // Convert to OpenAI Gentrace node
146
- const gentraceOpenAIInputs = { ...pair.inputs };
147
- gentraceOpenAIInputs.messages = [
148
- {
149
- content: pair.inputs.prompt.value,
150
- role: 'user',
151
- },
152
- ];
153
- const gentraceOpenAIModelParams = { ...pair.modelParams };
154
- gentraceOpenAIModelParams.model = modelName;
155
- gentraceOpenAIModelParams.frequency_penalty = pair.modelParams.frequencyPenalty || null;
156
- gentraceOpenAIModelParams.max_tokens = pair.modelParams.maxTokens || undefined;
157
- gentraceOpenAIModelParams.presence_penalty = pair.modelParams.presencePenalty || null;
158
- gentraceOpenAIModelParams.stop = pair.modelParams.stop || null;
159
- gentraceOpenAIModelParams.temperature = pair.modelParams.temperature || null;
160
- gentraceOpenAIModelParams.top_p = pair.modelParams.top_p || null;
161
- const gentraceOpenAIOutputs = { ...pair.outputs };
162
- const outputValues = Array.isArray(pair.outputs.response.value)
163
- ? pair.outputs.response.value
164
- : [pair.outputs.response.value];
165
- gentraceOpenAIOutputs.choices = outputValues.map((outputValue, index) => {
166
- return {
167
- index,
168
- message: {
169
- content: outputValue,
170
- role: 'assistant',
171
- },
172
- usage: {
173
- completion_tokens: pair.outputs.responseTokens.value,
174
- prompt_tokens: pair.outputs.requestTokens.value,
175
- total_tokens: pair.outputs.responseTokens.value + pair.outputs.requestTokens.value,
176
- },
177
- };
178
- });
179
- stepRuns.push(new StepRun('openai', 'openai_createChatCompletion', pair.end - pair.start, new Date(pair.start).toISOString(), new Date(pair.end).toISOString(), gentraceOpenAIInputs, gentraceOpenAIModelParams, gentraceOpenAIOutputs, {}, undefined));
180
- continue;
181
- }
182
- }
183
- stepRuns.push(new StepRun('rivet', nodeType ? `rivet_operation_${nodeType}` : 'rivet_operation', pair.end - pair.start, new Date(pair.start).toISOString(), new Date(pair.end).toISOString(), pair.inputs, pair.modelParams, pair.outputs, {}, undefined));
48
+ for (const [index, trial] of input.run.trials.entries()) {
49
+ const durationMs = typeof trial.totalMetrics.durationMs === 'number' ? trial.totalMetrics.durationMs : 0;
50
+ const { start, end } = timestampForTrial(input.run, durationMs, index);
51
+ await runner.addStepRunNode(new StepRun('rivet', 'rivet_evaluation_trial', durationMs, start, end, {
52
+ caseId: trial.caseId,
53
+ caseName: trial.caseName,
54
+ trialIndex: trial.trialIndex,
55
+ inputs: trial.inputs,
56
+ expected: trial.expected,
57
+ }, {
58
+ source: 'rivet-evaluations',
59
+ purpose: input.run.purpose,
60
+ }, {
61
+ executionStatus: trial.executionStatus,
62
+ qualityStatus: trial.qualityStatus,
63
+ qualityReason: trial.qualityReason,
64
+ outputs: trial.outputs,
65
+ observations: trial.observations,
66
+ metrics: trial.totalMetrics,
67
+ }, {}, trial.error));
184
68
  }
185
- return stepRuns;
69
+ return (await runner.submit({ waitForServer: true }));
186
70
  }
187
- export const getGentracePipelines = async (gentraceApiKey) => {
71
+ export async function getGentracePipelines(gentraceApiKey) {
188
72
  initializeGentrace(gentraceApiKey);
189
- return await getPipelines();
190
- };
73
+ return getPipelines();
74
+ }
191
75
  export const gentracePlugin = {
192
76
  id: 'gentrace',
193
77
  name: 'Gentrace',
194
- configSpec: {
195
- gentraceApiKey: apiKeyConfigSpec,
196
- },
78
+ configSpec: { gentraceApiKey: apiKeyConfigSpec },
197
79
  };
@@ -3,9 +3,8 @@ import autoevalsPlugin from './plugins/autoevals/index.js';
3
3
  import assemblyAiPlugin from './plugins/assemblyAi/index.js';
4
4
  import { huggingFacePlugin } from './plugins/huggingface/plugin.js';
5
5
  import pineconePlugin from './plugins/pinecone/index.js';
6
- // eslint-disable-next-line import/no-cycle -- Gentrace depends on GraphProcessor for local test execution.
7
6
  import gentracePlugin from './plugins/gentrace/index.js';
8
- export { getGentracePipelines, runGentraceTests, runRemoteGentraceTests } from './plugins/gentrace/plugin.js';
7
+ export { exportGentraceEvaluationRun, getGentracePipelines } from './plugins/gentrace/plugin.js';
9
8
  import { openAIPlugin } from './plugins/openai/plugin.js';
10
9
  import { googlePlugin } from './plugins/google/plugin.js';
11
10
  export { anthropicPlugin, autoevalsPlugin, assemblyAiPlugin, pineconePlugin, huggingFacePlugin, gentracePlugin, googlePlugin, };
@@ -78,6 +78,7 @@ const toRecordedEventMap = {
78
78
  progress,
79
79
  }, execution),
80
80
  llmCallFinished: ({ execution, ...event }) => ({ ...event, execution }),
81
+ llmProfileAttempt: ({ execution, ...event }) => ({ ...event, execution }),
81
82
  toolCallFinished: ({ execution, ...event }) => ({ ...event, execution }),
82
83
  nodeOutputsCleared: ({ node, processId, execution }) => withExecution({
83
84
  nodeId: node.id,
@@ -116,13 +117,28 @@ function toRecordedEvent(event, data) {
116
117
  ts: Date.now(),
117
118
  };
118
119
  }
120
+ const recordableData = omitReplayRecordedAt(data);
119
121
  const recordedEvent = {
120
122
  type: event,
121
- data: toRecordedEventMap[event](data),
123
+ data: toRecordedEventMap[event](recordableData),
122
124
  ts: Date.now(),
123
125
  };
124
126
  return recordedEvent;
125
127
  }
128
+ /**
129
+ * Replay provenance belongs to the current delivery, not the historical event
130
+ * itself. If a replay is recorded again, the recorder's own `ts` is the one
131
+ * authoritative timestamp to persist.
132
+ */
133
+ function omitReplayRecordedAt(data) {
134
+ if (data == null || typeof data !== 'object')
135
+ return data;
136
+ const { replayRecordedAt: _replayRecordedAt, ...recordableData } = data;
137
+ return recordableData;
138
+ }
139
+ function isRecordableProcessEvent(message) {
140
+ return message in toRecordedEventMap || isPrefix(message, 'globalSet:') || isPrefix(message, 'userEvent:');
141
+ }
126
142
  function mapValuesDeep(obj, fn) {
127
143
  if (Array.isArray(obj)) {
128
144
  return obj.map((value) => {
@@ -212,18 +228,39 @@ export class ExecutionRecorder {
212
228
  on = undefined;
213
229
  off = undefined;
214
230
  once = undefined;
215
- recordSocket(channel) {
231
+ recordSocket(channel, options = {}) {
216
232
  return new Promise((resolve) => {
217
233
  this.recordingId = nanoid();
234
+ let settled = false;
235
+ const finish = () => {
236
+ if (settled)
237
+ return;
238
+ settled = true;
239
+ channel.removeEventListener('message', listener);
240
+ options.signal?.removeEventListener('abort', finish);
241
+ resolve();
242
+ };
218
243
  const listener = (event) => {
219
- const { message, data } = JSON.parse(event.data);
220
- if (this.#includePartialOutputs === false && message === 'partialOutput') {
244
+ let payload;
245
+ try {
246
+ payload = JSON.parse(event.data);
247
+ }
248
+ catch {
249
+ // A debugger socket can carry control-plane payloads alongside graph
250
+ // events. They are not part of a replayable graph recording.
221
251
  return;
222
252
  }
223
- if (this.#includeTrace === false && message === 'trace') {
253
+ const { message, data, requestId } = payload;
254
+ if (typeof message !== 'string' || !isRecordableProcessEvent(message)) {
224
255
  return;
225
256
  }
226
- if (message === 'codeConsole') {
257
+ if (options.requestId !== undefined && requestId !== options.requestId) {
258
+ return;
259
+ }
260
+ if (this.#includePartialOutputs === false && message === 'partialOutput') {
261
+ return;
262
+ }
263
+ if (this.#includeTrace === false && message === 'trace') {
227
264
  return;
228
265
  }
229
266
  this.#events.push(toRecordedEvent(message, data));
@@ -231,11 +268,15 @@ export class ExecutionRecorder {
231
268
  emitDetached(this.#emitter, 'finish', {
232
269
  recording: this.getRecording(),
233
270
  });
234
- channel.removeEventListener('message', listener);
235
- resolve();
271
+ finish();
236
272
  }
237
273
  };
274
+ if (options.signal?.aborted) {
275
+ finish();
276
+ return;
277
+ }
238
278
  channel.addEventListener('message', listener);
279
+ options.signal?.addEventListener('abort', finish, { once: true });
239
280
  });
240
281
  }
241
282
  record(processor) {