Spaces:
Running
Running
File size: 10,826 Bytes
ae7d3b8 e23b66d ae7d3b8 |
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 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 |
/**
*
* Copyright 2023-2025 InspectorRAGet Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**/
import { isEmpty, intersectionWith, unionWith, isEqual } from 'lodash';
import { Metric, TaskEvaluation } from '@/src/types';
import { castToNumber } from '@/src/utilities/metrics';
// ===================================================================================
// CONSTANTS
// ===================================================================================
export const PLACHOLDER_EXPRESSION_TEXT = '{}';
export enum EXPRESSION_OPERATORS {
// Logical operators
AND = '$and',
OR = '$or',
// Comparison operators
EQ = '$eq',
NEQ = '$neq',
GT = '$gt',
GTE = '$gte',
LT = '$lt',
LTE = '$lte',
}
export function validate(
expression: object,
modelIds?: string[],
values?: (string | number)[],
parent?: string,
): string | null {
// Step 1: Identify all the keys
const keys = Object.keys(expression);
// Step 2: In case of operator presence
const operators = keys.filter((key) => key.startsWith('$'));
if (operators.length > 1) {
return `More than one operator [${operators.join(', ')}] on the same level in the expression`;
}
if (operators.length === 1 && keys.length > 1) {
return `Additional keys on the same level in the expression`;
}
if (operators.length === 1) {
const operator = operators[0];
// Logical operator condition
if (
operator === EXPRESSION_OPERATORS.AND ||
operator === EXPRESSION_OPERATORS.OR
) {
if (parent && modelIds && modelIds.includes(parent)) {
return `Logical operator ("${operator}") must not preceed with model ID`;
}
if (
!Array.isArray(expression[operator]) ||
expression[operator].some((value) => typeof value !== 'object')
) {
return `Logical operator ("${operator}") must follow with array of expressions`;
}
if (
isEmpty(expression[operator]) ||
expression[operator].some((entry) => isEmpty(entry))
) {
return `Logical operator ("${operator}") cannot have empty expression value`;
}
for (let index = 0; index < expression[operator].length; index++) {
const nestedErrorMessage = validate(
expression[operator][index],
modelIds,
);
if (nestedErrorMessage) {
return nestedErrorMessage;
}
}
}
// Comparison operators condition
else if (
operator === EXPRESSION_OPERATORS.EQ ||
operator === EXPRESSION_OPERATORS.NEQ ||
operator === EXPRESSION_OPERATORS.LT ||
operator === EXPRESSION_OPERATORS.LTE ||
operator === EXPRESSION_OPERATORS.GT ||
operator === EXPRESSION_OPERATORS.GTE
) {
if (parent === undefined || parent.startsWith('$')) {
return `Comparison operator ("${operator}") must preceed with model ID`;
}
if (
typeof expression[operator] !== 'string' &&
typeof expression[operator] !== 'number'
) {
return `Comparison operator ("${operator}") must follow primitive data types ("string" or "number")`;
}
}
} else {
// Step 3: In case of operator less expression
for (let idx = 0; idx < keys.length; idx++) {
// Step 3.a: If model IDs are provided, make sure key is one of those model IDs
if (modelIds && !modelIds.includes(keys[idx])) {
return `Model ("${keys[idx]}") does not exists. Please use one for the following models: ${modelIds.join(', ')}`;
}
const value = expression[keys[idx]];
if (
typeof value !== 'object' &&
typeof value !== 'string' &&
typeof value !== 'number'
) {
return `Model ("${keys[idx]}") must follow either expression or primitive data types ("string" or "number")`;
}
if (typeof value === 'object') {
const nestedErrorMessage = validate(
expression[keys[idx]],
modelIds,
values,
keys[idx],
);
if (nestedErrorMessage) {
return nestedErrorMessage;
}
} else {
if (values && !values.includes(value)) {
return `"${value}" is not a valid value option. Please use one of the following: ${values.join(', ')}`;
}
}
}
}
return null;
}
export function evaluate(
evaluationsPerTaskPerModel: {
[key: string]: { [key: string]: TaskEvaluation };
},
expression: object,
metric: Metric,
annotator?: string,
): TaskEvaluation[] {
// Step 1: Initialize necessary variables
const eligibleEvaluations: TaskEvaluation[] = [];
// Step 2: Identify all the keys
const keys = Object.keys(expression);
// Step 3: In case of operator presence
const operators = keys.filter((key) => key.startsWith('$'));
if (operators.length === 1) {
const operator = operators[0];
// Step 3.a: In case of a logical operator
if (
operator === EXPRESSION_OPERATORS.AND ||
operator === EXPRESSION_OPERATORS.OR
) {
// Step 3.a.i: Initialize necessary variables
const results: TaskEvaluation[][] = [];
// Step 3.a.ii: Identify evaluations meeting nested expression
expression[operator].forEach((condition) => {
results.push(
evaluate(evaluationsPerTaskPerModel, condition, metric, annotator),
);
});
// Step 3.a.iii: Apply intersection ('$and') or union ('$or') logic based on the logical operator
if (operator === EXPRESSION_OPERATORS.AND) {
return intersectionWith(...results, isEqual);
} else {
return unionWith(...results, isEqual);
}
}
} else {
// Step 3: In case of expression without logical operators
// Step 3.a: Iterate over evaluations for each task
Object.values(evaluationsPerTaskPerModel).forEach((evaluationPerModel) => {
// Step 3.a.i: Initialize necessary variables
let satisfy: boolean = true;
// Step 3.a.ii: Iterate over conditions for each model in the expression
for (let idx = 0; idx < keys.length; idx++) {
// Step 3.a.ii.*: Check if evaluation exists
if (!evaluationPerModel.hasOwnProperty(keys[idx])) {
satisfy = false;
break;
}
// Step 3.a.ii.**: Fetch evaluation, value and expected value condition
const evaluation = evaluationPerModel[keys[idx]];
// Step 3.a.ii.***: Calculate value
/**
* annotator specific value if annotator is specified
* OR
* aggregate value
*/
let value: string | number;
if (annotator) {
if (!evaluation[metric.name].hasOwnProperty(annotator)) {
satisfy = false;
break;
}
value = castToNumber(
evaluation[metric.name][annotator].value,
metric.values,
);
} else {
value = castToNumber(
evaluation[`${metric.name}_agg`].value,
metric.values,
);
}
// Step 3.a.ii.*****: Extract expection from expression
const expectation = expression[keys[idx]];
// Step 3.a.ii.******: In case of expectation is an expression
if (typeof expectation === 'object') {
// Extract comparison operator from expectation expression
const operator = Object.keys(expectation).filter((key) =>
key.startsWith('$'),
)[0];
// If comparison operator is "$gt" OR "$gte"
if (
(operator === EXPRESSION_OPERATORS.GTE ||
operator === EXPRESSION_OPERATORS.GT) &&
(isNaN(value) ||
value <
castToNumber(
expectation[operator],
metric.values,
typeof expectation[operator] === 'string'
? 'displayValue'
: 'value',
))
) {
satisfy = false;
break;
}
// If comparison operator is "$lt" OR "$lte"
if (
(operator === EXPRESSION_OPERATORS.LTE ||
operator === EXPRESSION_OPERATORS.LT) &&
(isNaN(value) ||
value >
castToNumber(
expectation[operator],
metric.values,
typeof expectation[operator] === 'string'
? 'displayValue'
: 'value',
))
) {
satisfy = false;
break;
}
// If comparison operator is "$eq"
if (
operator === EXPRESSION_OPERATORS.EQ &&
(isNaN(value) ||
value !==
castToNumber(
expectation[operator],
metric.values,
typeof expectation[operator] === 'string'
? 'displayValue'
: 'value',
))
) {
satisfy = false;
break;
}
// If comparison operator is "$neq"
if (
operator === EXPRESSION_OPERATORS.NEQ &&
(isNaN(value) ||
value ===
castToNumber(
expectation[operator],
metric.values,
typeof expectation[operator] === 'string'
? 'displayValue'
: 'value',
))
) {
satisfy = false;
break;
}
} else {
// 3.a.ii.******: In case of expectation is a primitive type ("string"/"number") value
if (
isNaN(value) ||
value !==
castToNumber(
expectation,
metric.values,
typeof expectation === 'string' ? 'displayValue' : 'value',
)
) {
satisfy = false;
break;
}
}
}
// Step 3.a.iii: If satisfy expression requirments, add all evaluations for the current task to eligible evaluations list
if (satisfy) {
eligibleEvaluations.push(...Object.values(evaluationPerModel));
}
});
}
// Step 4: Return
return eligibleEvaluations;
}
|