@valerypopoff/rivet2-core 2.12.0 → 2.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/bundle.cjs +3188 -592
- package/dist/cjs/bundle.cjs.map +4 -4
- package/dist/esm/api/createProcessor.js +5 -0
- package/dist/esm/api/processSettings.js +1 -0
- package/dist/esm/exports.js +5 -0
- package/dist/esm/model/GraphInputStream.js +70 -0
- package/dist/esm/model/GraphProcessor.js +264 -29
- package/dist/esm/model/MarkdownSanitizationPolicy.js +2 -0
- package/dist/esm/model/NodeExecutionPlanner.js +4 -4
- package/dist/esm/model/NodeImpl.js +1 -1
- package/dist/esm/model/Nodes.js +9 -0
- package/dist/esm/model/ProcessContextBuilder.js +2 -1
- package/dist/esm/model/StreamingOutputWatch.js +5 -0
- package/dist/esm/model/StreamingWatchTopology.js +228 -0
- package/dist/esm/model/classifier/credentials.js +81 -0
- package/dist/esm/model/classifier/migration.js +97 -0
- package/dist/esm/model/classifier/providers.js +347 -0
- package/dist/esm/model/classifier/questionHelpers.js +125 -0
- package/dist/esm/model/classifier/types.js +1 -0
- package/dist/esm/model/nodeBodyMarkdown.js +37 -0
- package/dist/esm/model/nodes/AssembleMessageNode.js +2 -2
- package/dist/esm/model/nodes/AssemblePromptNode.js +46 -17
- package/dist/esm/model/nodes/ClassifierEvaluateNode.js +392 -0
- package/dist/esm/model/nodes/ClassifierQuestionNode.js +569 -0
- package/dist/esm/model/nodes/CodeNewNode.js +33 -9
- package/dist/esm/model/nodes/GraphInputNode.js +15 -19
- package/dist/esm/model/nodes/LLMChatV2Node.js +3 -12
- package/dist/esm/model/nodes/LLMProfileNode.js +6 -12
- package/dist/esm/model/nodes/MatchCaseNode.js +78 -3
- package/dist/esm/model/nodes/MatchCaseNodeBase.js +24 -2
- package/dist/esm/model/nodes/ObjectNode.js +48 -41
- package/dist/esm/model/nodes/PassthroughNode.js +1 -1
- package/dist/esm/model/nodes/ProjectNameNode.js +37 -0
- package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +1 -0
- package/dist/esm/model/nodes/SubGraphNode.js +1 -0
- package/dist/esm/model/nodes/codeOutputInference.js +292 -0
- package/dist/esm/model/nodes/variadicPortIndex.js +1 -1
- package/dist/esm/utils/serialization/serialization.js +4 -0
- package/dist/types/exports.d.ts +6 -0
- package/dist/types/model/EditorDefinition.d.ts +24 -0
- package/dist/types/model/GraphInputStream.d.ts +23 -0
- package/dist/types/model/GraphProcessor.d.ts +3 -0
- package/dist/types/model/MarkdownSanitizationPolicy.d.ts +1 -1
- package/dist/types/model/NodeExecutionPlanner.d.ts +1 -1
- package/dist/types/model/NodeImpl.d.ts +3 -1
- package/dist/types/model/Nodes.d.ts +7 -4
- package/dist/types/model/ProcessContext.d.ts +3 -0
- package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
- package/dist/types/model/Settings.d.ts +4 -0
- package/dist/types/model/StreamingOutputWatch.d.ts +2 -0
- package/dist/types/model/StreamingWatchTopology.d.ts +26 -0
- package/dist/types/model/classifier/credentials.d.ts +24 -0
- package/dist/types/model/classifier/migration.d.ts +18 -0
- package/dist/types/model/classifier/providers.d.ts +78 -0
- package/dist/types/model/classifier/questionHelpers.d.ts +31 -0
- package/dist/types/model/classifier/types.d.ts +58 -0
- package/dist/types/model/nodeBodyMarkdown.d.ts +19 -0
- package/dist/types/model/nodes/AssemblePromptNode.d.ts +4 -3
- package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +47 -0
- package/dist/types/model/nodes/ClassifierQuestionNode.d.ts +60 -0
- package/dist/types/model/nodes/CodeNewNode.d.ts +6 -0
- package/dist/types/model/nodes/GraphInputNode.d.ts +2 -0
- package/dist/types/model/nodes/MatchCaseNode.d.ts +9 -2
- package/dist/types/model/nodes/MatchCaseNodeBase.d.ts +13 -1
- package/dist/types/model/nodes/ObjectNode.d.ts +5 -0
- package/dist/types/model/nodes/ProjectNameNode.d.ts +12 -0
- package/dist/types/model/nodes/codeOutputInference.d.ts +31 -0
- package/dist/types/model/nodes/variadicPortIndex.d.ts +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
import { JEV_DEFAULT_CREDENTIAL_NAMES } from './credentials.js';
|
|
2
|
+
export const JEV_SYSTEM_ONE_ENDPOINT = 'https://api.typesafe.ai/v1/systemone';
|
|
3
|
+
/** Jev's published USD rates. Keep this Core-owned rather than graph-authored. */
|
|
4
|
+
export const JEV_TOKEN_PRICING = {
|
|
5
|
+
inputPerMillionTokens: 0.042,
|
|
6
|
+
outputPerMillionTokens: 0,
|
|
7
|
+
};
|
|
8
|
+
const TOKENS_PER_MILLION = 1_000_000;
|
|
9
|
+
const MAX_AUTOMATIC_ATTEMPTS = 3;
|
|
10
|
+
const RETRYABLE_STATUSES = new Set([429, 529]);
|
|
11
|
+
export const DEFAULT_CLASSIFIER_RETRY_ON_NON_200_REPEAT_TIMES = 1;
|
|
12
|
+
export const DEFAULT_CLASSIFIER_RETRY_ON_NON_200_COOLDOWN_MS = 0;
|
|
13
|
+
/**
|
|
14
|
+
* Builds a provider for the shared System One-compatible protocol. Provider
|
|
15
|
+
* descriptors remain static Core code, while the Evaluate node stays agnostic
|
|
16
|
+
* to which compatible provider is selected.
|
|
17
|
+
*/
|
|
18
|
+
export function createApiCompatibleClassifierProvider(config) {
|
|
19
|
+
return {
|
|
20
|
+
id: config.id,
|
|
21
|
+
label: config.label,
|
|
22
|
+
defaultModel: config.defaultModel,
|
|
23
|
+
credentialNames: config.credentialNames,
|
|
24
|
+
browserExecutionSupported: config.browserExecutionSupported ?? false,
|
|
25
|
+
pricing: config.pricing,
|
|
26
|
+
async evaluate({ apiKey, fetchImplementation = fetch, model, questions, retryOnNon200, retryOnNon200CooldownMs, retryOnNon200RepeatTimes, signal, state, timeoutMs, }) {
|
|
27
|
+
const request = {
|
|
28
|
+
state,
|
|
29
|
+
model,
|
|
30
|
+
questions: createQuestionMap(questions),
|
|
31
|
+
};
|
|
32
|
+
return await callApiCompatibleClassifier({
|
|
33
|
+
apiKey,
|
|
34
|
+
endpoint: config.endpoint,
|
|
35
|
+
fetchImplementation,
|
|
36
|
+
providerLabel: config.label,
|
|
37
|
+
questions,
|
|
38
|
+
request,
|
|
39
|
+
retryOnNon200,
|
|
40
|
+
retryOnNon200CooldownMs,
|
|
41
|
+
retryOnNon200RepeatTimes,
|
|
42
|
+
signal,
|
|
43
|
+
timeoutMs,
|
|
44
|
+
});
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
export const jevClassifierProvider = createApiCompatibleClassifierProvider({
|
|
49
|
+
id: 'jev',
|
|
50
|
+
label: 'Jev',
|
|
51
|
+
defaultModel: 'jev-latest',
|
|
52
|
+
credentialNames: JEV_DEFAULT_CREDENTIAL_NAMES,
|
|
53
|
+
endpoint: JEV_SYSTEM_ONE_ENDPOINT,
|
|
54
|
+
pricing: JEV_TOKEN_PRICING,
|
|
55
|
+
});
|
|
56
|
+
/** Ordered so adding later API-compatible providers does not alter authored provider IDs. */
|
|
57
|
+
export const classifierProviders = [jevClassifierProvider];
|
|
58
|
+
export function getClassifierProvider(id) {
|
|
59
|
+
const provider = classifierProviders.find((candidate) => candidate.id === (id || jevClassifierProvider.id));
|
|
60
|
+
if (!provider)
|
|
61
|
+
throw new Error(`Unknown classifier provider '${id}'.`);
|
|
62
|
+
return provider;
|
|
63
|
+
}
|
|
64
|
+
export function getClassifierProviderEnvironmentVariableNames() {
|
|
65
|
+
return [...new Set(classifierProviders.map((provider) => provider.credentialNames.environmentVariableName))];
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Returns a USD cost only when the selected provider has static pricing and
|
|
69
|
+
* the token counts are safe non-negative integers. Callers must not treat an
|
|
70
|
+
* unpriced provider as free.
|
|
71
|
+
*/
|
|
72
|
+
export function calculateClassifierUsageCost(provider, usage) {
|
|
73
|
+
const pricing = provider.pricing;
|
|
74
|
+
if (pricing == null ||
|
|
75
|
+
!Number.isFinite(pricing.inputPerMillionTokens) ||
|
|
76
|
+
pricing.inputPerMillionTokens < 0 ||
|
|
77
|
+
!Number.isFinite(pricing.outputPerMillionTokens) ||
|
|
78
|
+
pricing.outputPerMillionTokens < 0 ||
|
|
79
|
+
!Number.isSafeInteger(usage.input_tokens) ||
|
|
80
|
+
usage.input_tokens < 0 ||
|
|
81
|
+
!Number.isSafeInteger(usage.output_tokens) ||
|
|
82
|
+
usage.output_tokens < 0) {
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
const totalCost = (usage.input_tokens * pricing.inputPerMillionTokens + usage.output_tokens * pricing.outputPerMillionTokens) /
|
|
86
|
+
TOKENS_PER_MILLION;
|
|
87
|
+
return Number.isFinite(totalCost) && totalCost >= 0 ? totalCost : undefined;
|
|
88
|
+
}
|
|
89
|
+
function createQuestionMap(questions) {
|
|
90
|
+
const result = Object.create(null);
|
|
91
|
+
for (const question of questions) {
|
|
92
|
+
const providerQuestion = question.type === 'noul' && question.criteria === undefined
|
|
93
|
+
? { type: question.type, instructions: question.instructions }
|
|
94
|
+
: { type: question.type, instructions: question.instructions, criteria: question.criteria };
|
|
95
|
+
Object.defineProperty(result, question.questionId, { enumerable: true, value: providerQuestion });
|
|
96
|
+
}
|
|
97
|
+
return result;
|
|
98
|
+
}
|
|
99
|
+
async function callApiCompatibleClassifier({ apiKey, endpoint, fetchImplementation, providerLabel, questions, request, retryOnNon200, retryOnNon200CooldownMs, retryOnNon200RepeatTimes, signal, timeoutMs, }) {
|
|
100
|
+
const deadline = Date.now() + timeoutMs;
|
|
101
|
+
const configuredRetryCount = retryOnNon200
|
|
102
|
+
? normalizeClassifierNon200RetryCount(retryOnNon200RepeatTimes)
|
|
103
|
+
: 0;
|
|
104
|
+
const configuredCooldownMs = normalizeClassifierNon200RetryCooldownMs(retryOnNon200CooldownMs);
|
|
105
|
+
let automaticRetryCount = 0;
|
|
106
|
+
let configuredRetryCountUsed = 0;
|
|
107
|
+
// Serialize once before the first attempt. This is the exact body sent for
|
|
108
|
+
// every retry and a detached snapshot for the optional inspection output,
|
|
109
|
+
// so concurrent graph code cannot mutate a shared State object between
|
|
110
|
+
// retries and make the diagnostic disagree with the wire payload.
|
|
111
|
+
const requestJson = JSON.stringify(request);
|
|
112
|
+
const requestBody = JSON.parse(requestJson);
|
|
113
|
+
for (;;) {
|
|
114
|
+
throwIfAborted(signal, providerLabel);
|
|
115
|
+
const remainingMs = deadline - Date.now();
|
|
116
|
+
if (remainingMs <= 0)
|
|
117
|
+
throw new Error(`${providerLabel} request timed out after ${timeoutMs} ms.`);
|
|
118
|
+
const controller = new AbortController();
|
|
119
|
+
const onAbort = () => controller.abort(signal.reason);
|
|
120
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
121
|
+
const timer = setTimeout(() => controller.abort(new Error(`${providerLabel} request timeout`)), remainingMs);
|
|
122
|
+
const cleanupAttempt = () => {
|
|
123
|
+
clearTimeout(timer);
|
|
124
|
+
signal.removeEventListener('abort', onAbort);
|
|
125
|
+
};
|
|
126
|
+
let response;
|
|
127
|
+
try {
|
|
128
|
+
response = await fetchImplementation(endpoint, {
|
|
129
|
+
method: 'POST',
|
|
130
|
+
headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
|
|
131
|
+
body: requestJson,
|
|
132
|
+
signal: controller.signal,
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
cleanupAttempt();
|
|
137
|
+
if (signal.aborted)
|
|
138
|
+
throwAbort(signal, providerLabel);
|
|
139
|
+
if (Date.now() >= deadline || controller.signal.aborted) {
|
|
140
|
+
throw new Error(`${providerLabel} request timed out after ${timeoutMs} ms.`);
|
|
141
|
+
}
|
|
142
|
+
if (automaticRetryCount >= MAX_AUTOMATIC_ATTEMPTS - 1) {
|
|
143
|
+
throw new Error(`${providerLabel} request failed after ${MAX_AUTOMATIC_ATTEMPTS} attempts due to a transport error.`);
|
|
144
|
+
}
|
|
145
|
+
automaticRetryCount += 1;
|
|
146
|
+
await waitForRetry(Math.min(250 * 2 ** (automaticRetryCount - 1), deadline - Date.now()), signal, providerLabel);
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
if (!response.ok) {
|
|
150
|
+
cleanupAttempt();
|
|
151
|
+
if (RETRYABLE_STATUSES.has(response.status) && automaticRetryCount < MAX_AUTOMATIC_ATTEMPTS - 1) {
|
|
152
|
+
automaticRetryCount += 1;
|
|
153
|
+
const delayMs = getRetryDelayMs(response.headers.get('retry-after'), automaticRetryCount, deadline);
|
|
154
|
+
await response.body?.cancel().catch(() => undefined);
|
|
155
|
+
await waitForRetry(delayMs, signal, providerLabel);
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
if (response.status === 401 || response.status === 403) {
|
|
159
|
+
throw new Error(`${providerLabel} authentication failed. Check the ${providerLabel} API key.`);
|
|
160
|
+
}
|
|
161
|
+
if (response.status === 422 || response.status === 400) {
|
|
162
|
+
throw new Error(`${providerLabel} rejected the request (HTTP ${response.status}).`);
|
|
163
|
+
}
|
|
164
|
+
if (configuredRetryCountUsed < configuredRetryCount && !RETRYABLE_STATUSES.has(response.status)) {
|
|
165
|
+
configuredRetryCountUsed += 1;
|
|
166
|
+
await response.body?.cancel().catch(() => undefined);
|
|
167
|
+
await waitForRetry(Math.min(configuredCooldownMs, deadline - Date.now()), signal, providerLabel);
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
throw new Error(`${providerLabel} request failed (HTTP ${response.status}).`);
|
|
171
|
+
}
|
|
172
|
+
let body;
|
|
173
|
+
try {
|
|
174
|
+
body = await response.json();
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
if (signal.aborted)
|
|
178
|
+
throwAbort(signal, providerLabel);
|
|
179
|
+
if (controller.signal.aborted || Date.now() >= deadline) {
|
|
180
|
+
throw new Error(`${providerLabel} request timed out after ${timeoutMs} ms.`);
|
|
181
|
+
}
|
|
182
|
+
throw new Error(`${providerLabel} returned an invalid JSON response.`);
|
|
183
|
+
}
|
|
184
|
+
finally {
|
|
185
|
+
cleanupAttempt();
|
|
186
|
+
}
|
|
187
|
+
const validatedResponse = validateApiCompatibleClassifierResponse(body, questions, providerLabel);
|
|
188
|
+
return {
|
|
189
|
+
requestBody,
|
|
190
|
+
response: validatedResponse,
|
|
191
|
+
// The validator only accepts an object-shaped JSON response and returns
|
|
192
|
+
// that exact parsed value; do not project it through Rivet's aggregate
|
|
193
|
+
// answer contract before exposing the optional diagnostic output.
|
|
194
|
+
responseBody: validatedResponse,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
export function normalizeClassifierNon200RetryCount(value) {
|
|
199
|
+
const retryCount = typeof value === 'number' && Number.isFinite(value)
|
|
200
|
+
? value
|
|
201
|
+
: DEFAULT_CLASSIFIER_RETRY_ON_NON_200_REPEAT_TIMES;
|
|
202
|
+
return Math.max(1, Math.floor(retryCount));
|
|
203
|
+
}
|
|
204
|
+
export function normalizeClassifierNon200RetryCooldownMs(value) {
|
|
205
|
+
const cooldownMs = typeof value === 'number' && Number.isFinite(value) ? value : DEFAULT_CLASSIFIER_RETRY_ON_NON_200_COOLDOWN_MS;
|
|
206
|
+
return Math.max(0, Math.floor(cooldownMs));
|
|
207
|
+
}
|
|
208
|
+
function throwIfAborted(signal, providerLabel) {
|
|
209
|
+
if (signal.aborted)
|
|
210
|
+
throwAbort(signal, providerLabel);
|
|
211
|
+
}
|
|
212
|
+
function throwAbort(signal, providerLabel) {
|
|
213
|
+
throw signal.reason instanceof Error ? signal.reason : new Error(`${providerLabel} request aborted.`);
|
|
214
|
+
}
|
|
215
|
+
function waitForRetry(delayMs, signal, providerLabel) {
|
|
216
|
+
throwIfAborted(signal, providerLabel);
|
|
217
|
+
if (delayMs <= 0)
|
|
218
|
+
return Promise.resolve();
|
|
219
|
+
return new Promise((resolve, reject) => {
|
|
220
|
+
const onAbort = () => {
|
|
221
|
+
clearTimeout(timer);
|
|
222
|
+
signal.removeEventListener('abort', onAbort);
|
|
223
|
+
reject(signal.reason instanceof Error ? signal.reason : new Error(`${providerLabel} request aborted.`));
|
|
224
|
+
};
|
|
225
|
+
const timer = setTimeout(() => {
|
|
226
|
+
signal.removeEventListener('abort', onAbort);
|
|
227
|
+
resolve();
|
|
228
|
+
}, delayMs);
|
|
229
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
230
|
+
if (signal.aborted)
|
|
231
|
+
onAbort();
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
function getRetryDelayMs(retryAfter, attempt, deadline) {
|
|
235
|
+
let requestedMs;
|
|
236
|
+
if (retryAfter != null) {
|
|
237
|
+
const seconds = Number(retryAfter);
|
|
238
|
+
if (Number.isFinite(seconds) && seconds >= 0)
|
|
239
|
+
requestedMs = seconds * 1000;
|
|
240
|
+
else {
|
|
241
|
+
const date = Date.parse(retryAfter);
|
|
242
|
+
if (Number.isFinite(date))
|
|
243
|
+
requestedMs = Math.max(0, date - Date.now());
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return Math.max(0, Math.min(requestedMs ?? 250 * 2 ** (attempt - 1), deadline - Date.now()));
|
|
247
|
+
}
|
|
248
|
+
function isRecord(value) {
|
|
249
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
250
|
+
}
|
|
251
|
+
function requireFiniteUnit(value, label, providerLabel) {
|
|
252
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) {
|
|
253
|
+
throw new Error(`${providerLabel} response has invalid ${label}.`);
|
|
254
|
+
}
|
|
255
|
+
return value;
|
|
256
|
+
}
|
|
257
|
+
function requireProbabilityMap(value, expectedKeys, label, providerLabel) {
|
|
258
|
+
if (!isRecord(value))
|
|
259
|
+
throw new Error(`${providerLabel} response has invalid ${label}.`);
|
|
260
|
+
const actualKeys = Object.keys(value);
|
|
261
|
+
if (actualKeys.length !== expectedKeys.length ||
|
|
262
|
+
expectedKeys.some((key) => !Object.prototype.hasOwnProperty.call(value, key))) {
|
|
263
|
+
throw new Error(`${providerLabel} response has inconsistent ${label} keys.`);
|
|
264
|
+
}
|
|
265
|
+
let total = 0;
|
|
266
|
+
for (const key of expectedKeys)
|
|
267
|
+
total += requireFiniteUnit(value[key], `${label}.${key}`, providerLabel);
|
|
268
|
+
if (Math.abs(total - 1) > 0.001)
|
|
269
|
+
throw new Error(`${providerLabel} response ${label} must sum to 1.`);
|
|
270
|
+
return value;
|
|
271
|
+
}
|
|
272
|
+
function structurallyEqual(left, right) {
|
|
273
|
+
if (Object.is(left, right))
|
|
274
|
+
return true;
|
|
275
|
+
if (Array.isArray(left) || Array.isArray(right)) {
|
|
276
|
+
return Array.isArray(left) && Array.isArray(right) && left.length === right.length && left.every((item, index) => structurallyEqual(item, right[index]));
|
|
277
|
+
}
|
|
278
|
+
if (!isRecord(left) || !isRecord(right))
|
|
279
|
+
return false;
|
|
280
|
+
const leftKeys = Object.keys(left);
|
|
281
|
+
const rightKeys = Object.keys(right);
|
|
282
|
+
return leftKeys.length === rightKeys.length && leftKeys.every((key) => Object.prototype.hasOwnProperty.call(right, key) && structurallyEqual(left[key], right[key]));
|
|
283
|
+
}
|
|
284
|
+
export function validateApiCompatibleClassifierResponse(body, questions, providerLabel = 'Classifier provider') {
|
|
285
|
+
if (!isRecord(body) ||
|
|
286
|
+
typeof body.model !== 'string' ||
|
|
287
|
+
body.model.trim() === '' ||
|
|
288
|
+
!isRecord(body.answers) ||
|
|
289
|
+
!isRecord(body.usage)) {
|
|
290
|
+
throw new Error(`${providerLabel} returned an invalid response shape.`);
|
|
291
|
+
}
|
|
292
|
+
const expectedIds = questions.map((question) => question.questionId);
|
|
293
|
+
const answerIds = Object.keys(body.answers);
|
|
294
|
+
if (answerIds.length !== expectedIds.length ||
|
|
295
|
+
expectedIds.some((id) => !Object.prototype.hasOwnProperty.call(body.answers, id))) {
|
|
296
|
+
throw new Error(`${providerLabel} response does not match the submitted question IDs.`);
|
|
297
|
+
}
|
|
298
|
+
for (const question of questions) {
|
|
299
|
+
const answer = body.answers[question.questionId];
|
|
300
|
+
if (!isRecord(answer) || answer.type !== question.type) {
|
|
301
|
+
throw new Error(`${providerLabel} response type does not match question '${question.questionId}'.`);
|
|
302
|
+
}
|
|
303
|
+
if (question.type === 'choice') {
|
|
304
|
+
const choiceQuestion = question;
|
|
305
|
+
const keys = Object.keys(choiceQuestion.criteria);
|
|
306
|
+
if (typeof answer.choice !== 'string' ||
|
|
307
|
+
!Object.prototype.hasOwnProperty.call(choiceQuestion.criteria, answer.choice)) {
|
|
308
|
+
throw new Error(`${providerLabel} response chose an unknown option for '${question.questionId}'.`);
|
|
309
|
+
}
|
|
310
|
+
requireFiniteUnit(answer.confidence, `${question.questionId}.confidence`, providerLabel);
|
|
311
|
+
requireProbabilityMap(answer.probabilities, keys, `${question.questionId}.probabilities`, providerLabel);
|
|
312
|
+
}
|
|
313
|
+
else if (question.type === 'score') {
|
|
314
|
+
const scoreQuestion = question;
|
|
315
|
+
if (typeof answer.score !== 'number' ||
|
|
316
|
+
!Number.isFinite(answer.score) ||
|
|
317
|
+
answer.score < 0 ||
|
|
318
|
+
answer.score > scoreQuestion.criteria.length - 1) {
|
|
319
|
+
throw new Error(`${providerLabel} response has invalid score for '${question.questionId}'.`);
|
|
320
|
+
}
|
|
321
|
+
requireFiniteUnit(answer.confidence, `${question.questionId}.confidence`, providerLabel);
|
|
322
|
+
const keys = scoreQuestion.criteria.map((_, index) => String(index));
|
|
323
|
+
requireProbabilityMap(answer.probabilities, keys, `${question.questionId}.probabilities`, providerLabel);
|
|
324
|
+
const legend = answer.legend;
|
|
325
|
+
if (!isRecord(legend) ||
|
|
326
|
+
Object.keys(legend).length !== keys.length ||
|
|
327
|
+
keys.some((key, index) => !Object.prototype.hasOwnProperty.call(legend, key) ||
|
|
328
|
+
!structurallyEqual(legend[key], scoreQuestion.criteria[index]))) {
|
|
329
|
+
throw new Error(`${providerLabel} response has inconsistent legend for '${question.questionId}'.`);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
else {
|
|
333
|
+
requireFiniteUnit(answer.noul, `${question.questionId}.noul`, providerLabel);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
const inputTokens = body.usage.input_tokens;
|
|
337
|
+
const outputTokens = body.usage.output_tokens;
|
|
338
|
+
if (typeof inputTokens !== 'number' ||
|
|
339
|
+
!Number.isSafeInteger(inputTokens) ||
|
|
340
|
+
inputTokens < 0 ||
|
|
341
|
+
typeof outputTokens !== 'number' ||
|
|
342
|
+
!Number.isSafeInteger(outputTokens) ||
|
|
343
|
+
outputTokens < 0) {
|
|
344
|
+
throw new Error(`${providerLabel} response has invalid usage values.`);
|
|
345
|
+
}
|
|
346
|
+
return body;
|
|
347
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { createInterpolationInputDefinition } from '../interpolationInputDefinition.js';
|
|
2
|
+
import { extractInterpolationVariableReferences, getInterpolationGlobalValues, interpolate } from '../../utils/interpolation.js';
|
|
3
|
+
import { interpolateJsonTemplate } from '../nodes/ObjectNode.js';
|
|
4
|
+
const STRUCTURED_ENTRY_TYPES = ['string', 'object', 'object[]', 'any', 'any[]'];
|
|
5
|
+
export function getInstructionsInputDefinition() {
|
|
6
|
+
return {
|
|
7
|
+
id: 'instructions',
|
|
8
|
+
title: 'Instructions',
|
|
9
|
+
dataType: STRUCTURED_ENTRY_TYPES,
|
|
10
|
+
required: true,
|
|
11
|
+
splitRunBehavior: 'preserve-array',
|
|
12
|
+
description: 'String or JSON structure describing the independent question.',
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
export function getCriteriaInputDefinition(dataTypes) {
|
|
16
|
+
return {
|
|
17
|
+
id: 'criteria',
|
|
18
|
+
title: 'Criteria',
|
|
19
|
+
dataType: dataTypes,
|
|
20
|
+
required: true,
|
|
21
|
+
splitRunBehavior: 'preserve-array',
|
|
22
|
+
description: 'Complete criteria for this question.',
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
export function getInterpolationInputDefinitions(templates, reserved) {
|
|
26
|
+
const names = new Set();
|
|
27
|
+
for (const template of templates) {
|
|
28
|
+
for (const { baseName } of extractInterpolationVariableReferences(template)) {
|
|
29
|
+
if (!reserved.has(baseName))
|
|
30
|
+
names.add(baseName);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return [...names].map((interpolationName) => createInterpolationInputDefinition({
|
|
34
|
+
interpolationName,
|
|
35
|
+
dataType: 'any',
|
|
36
|
+
required: false,
|
|
37
|
+
description: `Interpolated value named '${interpolationName}'.`,
|
|
38
|
+
}));
|
|
39
|
+
}
|
|
40
|
+
function inputValues(inputs) {
|
|
41
|
+
const values = Object.create(null);
|
|
42
|
+
for (const [key, value] of Object.entries(inputs))
|
|
43
|
+
values[key] = value;
|
|
44
|
+
return values;
|
|
45
|
+
}
|
|
46
|
+
export function interpolateQuestionText(template, inputs, context) {
|
|
47
|
+
return interpolate(template, inputValues(inputs), context.graphInputNodeValues, context.contextValues, {
|
|
48
|
+
globalValues: getInterpolationGlobalValues(template, context.getGlobal),
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
export function resolveAuthoredClassifierEntry({ type, text, lines, objectTemplate, inputs, context, label, }) {
|
|
52
|
+
if (type === 'lines') {
|
|
53
|
+
const resolved = (lines ?? []).map((line) => interpolateQuestionText(line, inputs, context));
|
|
54
|
+
if (resolved.length === 0)
|
|
55
|
+
throw new Error(`${label} require at least one line.`);
|
|
56
|
+
return resolved;
|
|
57
|
+
}
|
|
58
|
+
if (type === 'object') {
|
|
59
|
+
const template = objectTemplate?.trim() ? objectTemplate : '{}';
|
|
60
|
+
let parsed;
|
|
61
|
+
try {
|
|
62
|
+
parsed = JSON.parse(interpolateJsonTemplate(template, Object.fromEntries(Object.entries(inputs).map(([key, value]) => [key, value?.value])), context.graphInputNodeValues, context.contextValues, getInterpolationGlobalValues(template, context.getGlobal)));
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
throw new Error(`${label} JSON template is invalid: ${error.message}`);
|
|
66
|
+
}
|
|
67
|
+
if (parsed === null || Array.isArray(parsed) || typeof parsed !== 'object') {
|
|
68
|
+
throw new Error(`${label} JSON template must produce an object.`);
|
|
69
|
+
}
|
|
70
|
+
assertClassifierEntry(parsed, label);
|
|
71
|
+
return parsed;
|
|
72
|
+
}
|
|
73
|
+
return interpolateQuestionText(text ?? '', inputs, context);
|
|
74
|
+
}
|
|
75
|
+
export function getStringInput(inputs, portId, label) {
|
|
76
|
+
const value = inputs[portId]?.value;
|
|
77
|
+
if (typeof value !== 'string')
|
|
78
|
+
throw new Error(`${label} input must be a string.`);
|
|
79
|
+
return value;
|
|
80
|
+
}
|
|
81
|
+
export function requireQuestionId(questionId) {
|
|
82
|
+
if (questionId.trim().length === 0)
|
|
83
|
+
throw new Error('Question ID is required.');
|
|
84
|
+
return questionId;
|
|
85
|
+
}
|
|
86
|
+
export function getStructuredInput(inputs, portId, label) {
|
|
87
|
+
const value = inputs[portId]?.value;
|
|
88
|
+
if (value === undefined)
|
|
89
|
+
throw new Error(`${label} input is required.`);
|
|
90
|
+
assertClassifierEntry(value, label);
|
|
91
|
+
return value;
|
|
92
|
+
}
|
|
93
|
+
export function assertClassifierEntry(value, label) {
|
|
94
|
+
assertClassifierEntryValue(value, label, new Set(), false);
|
|
95
|
+
}
|
|
96
|
+
export function assertClassifierInstructions(value, label = 'Instructions') {
|
|
97
|
+
assertClassifierEntry(value, label);
|
|
98
|
+
if (value === null || (typeof value === 'string' && value.trim() === '')) {
|
|
99
|
+
throw new Error(`${label} are required.`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function assertClassifierEntryValue(value, label, seen, nested) {
|
|
103
|
+
if (value === null || typeof value === 'string')
|
|
104
|
+
return;
|
|
105
|
+
if (nested && (typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value))))
|
|
106
|
+
return;
|
|
107
|
+
if (typeof value !== 'object')
|
|
108
|
+
throw new Error(`${label} must contain only strings, null, objects, and arrays.`);
|
|
109
|
+
if (seen.has(value))
|
|
110
|
+
throw new Error(`${label} must not contain circular references.`);
|
|
111
|
+
seen.add(value);
|
|
112
|
+
if (Array.isArray(value)) {
|
|
113
|
+
value.forEach((item, index) => assertClassifierEntryValue(item, `${label}[${index}]`, seen, true));
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
for (const [key, item] of Object.entries(value)) {
|
|
117
|
+
assertClassifierEntryValue(item, `${label}.${key}`, seen, true);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
seen.delete(value);
|
|
121
|
+
}
|
|
122
|
+
export function abbreviate(value, maximum = 72) {
|
|
123
|
+
const compact = value.replace(/\s+/g, ' ').trim();
|
|
124
|
+
return compact.length <= maximum ? compact : `${compact.slice(0, maximum - 3)}...`;
|
|
125
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export const NODE_BODY_FIELD_LABEL_CLASS = 'rivet-node-body-field-label';
|
|
2
|
+
export const NODE_BODY_FIELD_VALUE_CLASS = 'rivet-node-body-field-value';
|
|
3
|
+
export const NODE_BODY_FIELD_ROW_CLASS = 'rivet-node-body-field-row';
|
|
4
|
+
export const NODE_BODY_TEXT_ROW_CLASS = 'rivet-node-body-text-row';
|
|
5
|
+
export const NODE_BODY_SEPARATOR_CLASS = 'rivet-node-body-separator';
|
|
6
|
+
/**
|
|
7
|
+
* Renders a label/value pair for a Markdown node body without letting authored
|
|
8
|
+
* values become Markdown. Class-based styling is deliberately used instead of
|
|
9
|
+
* inline styles because node-body Markdown is sanitized before it reaches DOM.
|
|
10
|
+
*/
|
|
11
|
+
export function formatNodeBodyMarkdownField(label, value) {
|
|
12
|
+
return `<div class="${NODE_BODY_FIELD_ROW_CLASS}">${formatNodeBodyMarkdownLabel(label)} ${formatNodeBodyMarkdownValue(value)}</div>`;
|
|
13
|
+
}
|
|
14
|
+
/** Renders a sanitized, styled field label without adding an empty value node. */
|
|
15
|
+
export function formatNodeBodyMarkdownLabel(label) {
|
|
16
|
+
return `<span class="${NODE_BODY_FIELD_LABEL_CLASS}">${escapeNodeBodyMarkdownText(label)}:</span>`;
|
|
17
|
+
}
|
|
18
|
+
/** Wraps authored text in a raw HTML span so Markdown punctuation stays literal. */
|
|
19
|
+
export function formatNodeBodyMarkdownValue(value) {
|
|
20
|
+
return `<span class="${NODE_BODY_FIELD_VALUE_CLASS}">${escapeNodeBodyMarkdownText(value)}</span>`;
|
|
21
|
+
}
|
|
22
|
+
/** Renders unlabelled authored text as a standalone Markdown body row. */
|
|
23
|
+
export function formatNodeBodyMarkdownTextRow(value) {
|
|
24
|
+
return `<div class="${NODE_BODY_TEXT_ROW_CLASS}">${formatNodeBodyMarkdownValue(value)}</div>`;
|
|
25
|
+
}
|
|
26
|
+
/** A block separator that does not cause Markdown to create empty paragraphs. */
|
|
27
|
+
export function formatNodeBodyMarkdownSeparator() {
|
|
28
|
+
return `<div class="${NODE_BODY_SEPARATOR_CLASS}"></div>`;
|
|
29
|
+
}
|
|
30
|
+
function escapeNodeBodyMarkdownText(value) {
|
|
31
|
+
return String(value ?? '')
|
|
32
|
+
.replace(/&/g, '&')
|
|
33
|
+
.replace(/</g, '<')
|
|
34
|
+
.replace(/>/g, '>')
|
|
35
|
+
.replace(/"/g, '"')
|
|
36
|
+
.replace(/'/g, ''');
|
|
37
|
+
}
|
|
@@ -7,7 +7,7 @@ import { orderBy } from 'lodash-es';
|
|
|
7
7
|
import { coerceTypeOptional, dedent, getInputOrData } from '../../utils/index.js';
|
|
8
8
|
import { nodeDefinition } from '../NodeDefinition.js';
|
|
9
9
|
import { match } from 'ts-pattern';
|
|
10
|
-
import { getNextVariadicPortIndex } from './variadicPortIndex.js';
|
|
10
|
+
import { getNextVariadicPortIndex, parseVariadicPortIndex } from './variadicPortIndex.js';
|
|
11
11
|
const messageTypeToTitle = {
|
|
12
12
|
assistant: 'Assistant',
|
|
13
13
|
developer: 'Developer',
|
|
@@ -148,7 +148,7 @@ export class AssembleMessageNodeImpl extends NodeImpl {
|
|
|
148
148
|
.otherwise(() => {
|
|
149
149
|
throw new Error(`Invalid type: ${type}`);
|
|
150
150
|
});
|
|
151
|
-
const inputParts = orderBy(Object.entries(inputs).filter(([key]) => key.startsWith('part')), ([key]) => key, 'asc');
|
|
151
|
+
const inputParts = orderBy(Object.entries(inputs).filter(([key]) => key.startsWith('part')), ([key]) => parseVariadicPortIndex(key, 'part', 'legacy'), 'asc');
|
|
152
152
|
for (const [, inputPart] of inputParts) {
|
|
153
153
|
if (!inputPart || inputPart.type === 'control-flow-excluded' || !inputPart.value) {
|
|
154
154
|
continue;
|
|
@@ -8,7 +8,18 @@ import { orderBy } from 'lodash-es';
|
|
|
8
8
|
import { dedent } from 'ts-dedent';
|
|
9
9
|
import { nodeDefinition } from '../NodeDefinition.js';
|
|
10
10
|
import { getInputOrData } from '../../utils/inputs.js';
|
|
11
|
-
import { getNextVariadicPortIndex } from './variadicPortIndex.js';
|
|
11
|
+
import { getNextVariadicPortIndex, parseVariadicPortIndex } from './variadicPortIndex.js';
|
|
12
|
+
function isEmptyPromptMessage(message) {
|
|
13
|
+
// Tool protocol messages remain meaningful even when their textual content is empty.
|
|
14
|
+
if (message.type === 'function') {
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
if (message.type === 'assistant' && (message.function_call != null || (message.function_calls?.length ?? 0) > 0)) {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
const parts = Array.isArray(message.message) ? message.message : [message.message];
|
|
21
|
+
return !parts.some((part) => typeof part !== 'string' || part.trim().length > 0);
|
|
22
|
+
}
|
|
12
23
|
export class AssemblePromptNodeImpl extends NodeImpl {
|
|
13
24
|
static create() {
|
|
14
25
|
const chartNode = {
|
|
@@ -20,7 +31,9 @@ export class AssemblePromptNodeImpl extends NodeImpl {
|
|
|
20
31
|
y: 0,
|
|
21
32
|
width: 250,
|
|
22
33
|
},
|
|
23
|
-
data: {
|
|
34
|
+
data: {
|
|
35
|
+
filterEmptyPrompts: false,
|
|
36
|
+
},
|
|
24
37
|
};
|
|
25
38
|
return chartNode;
|
|
26
39
|
}
|
|
@@ -32,7 +45,7 @@ export class AssemblePromptNodeImpl extends NodeImpl {
|
|
|
32
45
|
dataType: 'boolean',
|
|
33
46
|
id: 'isLastMessageCacheBreakpoint',
|
|
34
47
|
title: 'Is Last Message Cache Breakpoint',
|
|
35
|
-
description: 'Whether the last message in
|
|
48
|
+
description: 'Whether the last message in a multi-message prompt should be a cache breakpoint.',
|
|
36
49
|
});
|
|
37
50
|
}
|
|
38
51
|
for (let i = 1; i <= messageCount; i++) {
|
|
@@ -78,48 +91,64 @@ export class AssemblePromptNodeImpl extends NodeImpl {
|
|
|
78
91
|
group: ['AI'],
|
|
79
92
|
};
|
|
80
93
|
}
|
|
81
|
-
getEditors(
|
|
94
|
+
getEditors() {
|
|
82
95
|
return [
|
|
83
96
|
{
|
|
84
97
|
type: 'toggle',
|
|
85
98
|
label: 'Compute Token Count',
|
|
86
99
|
dataKey: 'computeTokenCount',
|
|
87
100
|
},
|
|
101
|
+
{
|
|
102
|
+
type: 'toggle',
|
|
103
|
+
label: 'Filter empty prompts',
|
|
104
|
+
dataKey: 'filterEmptyPrompts',
|
|
105
|
+
defaultValue: false,
|
|
106
|
+
helperMessage: 'Removes text-only messages whose content is empty or whitespace. Rich-content and tool-protocol messages are preserved.',
|
|
107
|
+
},
|
|
88
108
|
{
|
|
89
109
|
type: 'toggle',
|
|
90
110
|
label: 'Is Last Message Cache Breakpoint',
|
|
91
111
|
dataKey: 'isLastMessageCacheBreakpoint',
|
|
92
|
-
|
|
112
|
+
useInputToggleDataKey: 'useIsLastMessageCacheBreakpointInput',
|
|
113
|
+
helperMessage: 'For Anthropic, marks the last message in a prompt containing at least two messages as a cache breakpoint. This message and every message before it will be cached using Prompt Caching.',
|
|
93
114
|
},
|
|
94
115
|
];
|
|
95
116
|
}
|
|
96
|
-
getBody(
|
|
97
|
-
return
|
|
117
|
+
getBody() {
|
|
118
|
+
return [
|
|
119
|
+
this.data.filterEmptyPrompts ? 'Filter empty prompts: Enabled' : '',
|
|
120
|
+
this.data.useIsLastMessageCacheBreakpointInput
|
|
121
|
+
? 'Last message cache breakpoint: From input'
|
|
122
|
+
: this.data.isLastMessageCacheBreakpoint
|
|
123
|
+
? 'Last message is cache breakpoint'
|
|
124
|
+
: '',
|
|
125
|
+
]
|
|
126
|
+
.filter(Boolean)
|
|
127
|
+
.join('\n');
|
|
98
128
|
}
|
|
99
129
|
async process(inputs, context) {
|
|
100
130
|
const output = {};
|
|
101
131
|
const isLastMessageCacheBreakpoint = getInputOrData(this.data, inputs, 'isLastMessageCacheBreakpoint', 'boolean');
|
|
102
132
|
const outMessages = [];
|
|
103
|
-
const inputMessages = orderBy(Object.entries(inputs).filter(([key]) => key.startsWith('message')), ([key]) => key, 'asc');
|
|
133
|
+
const inputMessages = orderBy(Object.entries(inputs).filter(([key]) => key.startsWith('message')), ([key]) => parseVariadicPortIndex(key, 'message', 'legacy'), 'asc');
|
|
104
134
|
for (const [, inputMessage] of inputMessages) {
|
|
105
135
|
if (!inputMessage || inputMessage.type === 'control-flow-excluded' || !inputMessage.value) {
|
|
106
136
|
continue;
|
|
107
137
|
}
|
|
108
138
|
const inMessages = arrayizeDataValue(unwrapDataValue(inputMessage));
|
|
109
139
|
for (const message of inMessages) {
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
else {
|
|
114
|
-
const coerced = coerceType(message, 'chat-message');
|
|
115
|
-
if (coerced) {
|
|
116
|
-
outMessages.push(coerced);
|
|
117
|
-
}
|
|
140
|
+
const outMessage = message.type === 'chat-message' ? message.value : coerceType(message, 'chat-message');
|
|
141
|
+
if (this.data.filterEmptyPrompts && isEmptyPromptMessage(outMessage)) {
|
|
142
|
+
continue;
|
|
118
143
|
}
|
|
144
|
+
outMessages.push(outMessage);
|
|
119
145
|
}
|
|
120
146
|
}
|
|
121
147
|
if (isLastMessageCacheBreakpoint && outMessages.length > 1) {
|
|
122
|
-
outMessages.
|
|
148
|
+
outMessages[outMessages.length - 1] = {
|
|
149
|
+
...outMessages[outMessages.length - 1],
|
|
150
|
+
isCacheBreakpoint: true,
|
|
151
|
+
};
|
|
123
152
|
}
|
|
124
153
|
output['prompt'] = {
|
|
125
154
|
type: 'chat-message[]',
|