-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathevaluator.ts
More file actions
311 lines (289 loc) · 9.61 KB
/
Copy pathevaluator.ts
File metadata and controls
311 lines (289 loc) · 9.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
import { createLogger } from '@sim/logger'
import { ChartBarIcon } from '@/components/icons'
import type { BlockConfig, ParamType } from '@/blocks/types'
import {
getModelOptions,
getProviderCredentialSubBlocks,
PROVIDER_CREDENTIAL_INPUTS,
} from '@/blocks/utils'
import { getBaseModelProviders } from '@/providers/models'
import type { ProviderId } from '@/providers/types'
import type { ToolResponse } from '@/tools/types'
const logger = createLogger('EvaluatorBlock')
interface Metric {
name: string
description: string
range: {
min: number
max: number
}
}
interface EvaluatorResponse extends ToolResponse {
output: {
content: string
model: string
tokens?: {
prompt?: number
completion?: number
total?: number
}
cost?: {
input: number
output: number
total: number
}
[metricName: string]: any // Allow dynamic metric fields
}
}
export const generateEvaluatorPrompt = (metrics: Metric[], content: string): string => {
// Filter out invalid/incomplete metrics first
const validMetrics = metrics.filter((m) => m?.name && m.range)
// Create a clear metrics description with name, range, and description
const metricsDescription = validMetrics
.map(
(metric) =>
`"${metric.name}" (${metric.range.min}-${metric.range.max}): ${metric.description || ''}` // Handle potentially missing description
)
.join('\n')
// Format the content properly - try to detect and format JSON
let formattedContent = content
try {
// If content looks like JSON (starts with { or [)
if (
typeof content === 'string' &&
(content.trim().startsWith('{') || content.trim().startsWith('['))
) {
// Try to parse and pretty-print
const parsedContent = JSON.parse(content)
formattedContent = JSON.stringify(parsedContent, null, 2)
}
// If it's already an object (shouldn't happen here but just in case)
else if (typeof content === 'object') {
formattedContent = JSON.stringify(content, null, 2)
}
} catch (e) {
logger.warn('Warning: Content may not be valid JSON, using as-is', { e })
formattedContent = content
}
// Generate an example of the expected output format using only valid metrics
const exampleOutput = validMetrics.reduce(
(acc, metric) => {
// Ensure metric and name are valid before using them
if (metric?.name) {
acc[metric.name.toLowerCase()] = Math.floor((metric.range.min + metric.range.max) / 2) // Use middle of range as example
} else {
logger.warn('Skipping invalid metric during example generation:', metric)
}
return acc
},
{} as Record<string, number>
)
return `You are an objective evaluation agent. Analyze the content against the provided metrics and provide detailed scoring.
Evaluation Instructions:
- You MUST evaluate the content against each metric
- For each metric, provide a numeric score within the specified range
- Your response MUST be a valid JSON object with each metric name as a key and a numeric score as the value
- IMPORTANT: Use lowercase versions of the metric names as keys in your JSON response
- Follow the exact schema of the response format provided to you
- Do not include explanations in the JSON - only numeric scores
- Do not add any additional fields not specified in the schema
- Do not include ANY text before or after the JSON object
Metrics to evaluate:
${metricsDescription}
Content to evaluate:
${formattedContent}
Example of expected response format (with different scores):
${JSON.stringify(exampleOutput, null, 2)}
Remember: Your response MUST be a valid JSON object containing only the lowercase metric names as keys with their numeric scores as values. No text explanations.`
}
// Simplified response format generator that matches the agent block schema structure
const generateResponseFormat = (metrics: Metric[]) => {
// Filter out invalid/incomplete metrics first
const validMetrics = metrics.filter((m) => m?.name)
// Create properties for each metric
const properties: Record<string, any> = {}
// Add each metric as a property
validMetrics.forEach((metric) => {
// We've already filtered, but double-check just in case
if (metric?.name) {
properties[metric.name.toLowerCase()] = {
type: 'number',
description: `${metric.description || ''} (Score between ${metric.range?.min ?? 0}-${metric.range?.max ?? 'N/A'})`, // Safely access range
}
} else {
logger.warn('Skipping invalid metric during response format property generation:', metric)
}
})
// Return a proper JSON Schema format
return {
name: 'evaluation_response',
schema: {
type: 'object',
properties,
// Use only valid, lowercase metric names for the required array
required: validMetrics
.filter((metric) => metric?.name)
.map((metric) => metric.name.toLowerCase()),
additionalProperties: false,
},
strict: true,
}
}
export const EvaluatorBlock: BlockConfig<EvaluatorResponse> = {
type: 'evaluator',
name: 'Evaluator',
description: 'Evaluate content',
longDescription:
'This is a core workflow block. Assess content quality using customizable evaluation metrics and scoring criteria. Create objective evaluation frameworks with numeric scoring to measure performance across multiple dimensions.',
docsLink: 'https://docs.sim.ai/workflows/blocks/evaluator',
category: 'blocks',
bgColor: '#4D5FFF',
icon: ChartBarIcon,
subBlocks: [
{
id: 'metrics',
title: 'Evaluation Metrics',
type: 'eval-input',
required: true,
},
{
id: 'content',
title: 'Content',
type: 'long-input',
placeholder: 'Enter the content to evaluate',
required: true,
},
{
id: 'model',
title: 'Model',
type: 'combobox',
placeholder: 'Type or select a model...',
required: true,
defaultValue: 'claude-sonnet-5',
options: getModelOptions,
},
...getProviderCredentialSubBlocks(),
{
id: 'temperature',
title: 'Temperature',
type: 'slider',
min: 0,
max: 2,
hidden: true,
},
{
id: 'systemPrompt',
title: 'System Prompt',
type: 'code',
hidden: true,
value: (params: Record<string, any>) => {
try {
const metrics = params.metrics || []
// Process content safely
let processedContent = ''
if (typeof params.content === 'object') {
processedContent = JSON.stringify(params.content, null, 2)
} else {
processedContent = String(params.content || '')
}
// Generate prompt and response format directly
const promptText = generateEvaluatorPrompt(metrics, processedContent)
const responseFormatObj = generateResponseFormat(metrics)
// Create a clean, simple JSON object
const result = {
systemPrompt: promptText,
responseFormat: responseFormatObj,
}
return JSON.stringify(result)
} catch (e) {
logger.error('Error in systemPrompt value function:', { e })
// Return a minimal valid JSON as fallback
return JSON.stringify({
systemPrompt: 'Evaluate the content and return a JSON with metric scores.',
responseFormat: {
schema: {
type: 'object',
properties: {},
additionalProperties: true,
},
},
})
}
},
},
],
tools: {
access: [
'openai_chat',
'anthropic_chat',
'google_chat',
'xai_chat',
'deepseek_chat',
'deepseek_reasoner',
],
config: {
tool: (params: Record<string, any>) => {
const model = params.model || 'gpt-4o'
if (!model) {
throw new Error('No model selected')
}
const tool = getBaseModelProviders()[model as ProviderId]
if (!tool) {
throw new Error(`Invalid model selected: ${model}`)
}
return tool
},
},
},
inputs: {
metrics: {
type: 'json' as ParamType,
description: 'Evaluation metrics configuration',
schema: {
type: 'array',
properties: {},
items: {
type: 'object',
properties: {
name: {
type: 'string',
description: 'Name of the metric',
},
description: {
type: 'string',
description: 'Description of what this metric measures',
},
range: {
type: 'object',
properties: {
min: {
type: 'number',
description: 'Minimum possible score',
},
max: {
type: 'number',
description: 'Maximum possible score',
},
},
required: ['min', 'max'],
},
},
required: ['name', 'description', 'range'],
},
},
},
model: { type: 'string' as ParamType, description: 'AI model to use' },
...PROVIDER_CREDENTIAL_INPUTS,
temperature: {
type: 'number' as ParamType,
description: 'Response randomness level (low for consistent evaluation)',
},
content: { type: 'string' as ParamType, description: 'Content to evaluate' },
},
outputs: {
content: { type: 'string', description: 'Evaluation results' },
model: { type: 'string', description: 'Model used' },
tokens: { type: 'json', description: 'Token usage' },
cost: { type: 'json', description: 'Cost information' },
} as any,
}