Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 23x 23x 21x 21x 21x 18x 13x 13x 11x 10x 10x 7x 7x 21x 2x 2x 46x 46x 46x 46x 46x 46x 46x 6x 2x 46x 46x 46x 46x 10x 10x 10x 10x 2x 2x 8x 8x 10x 8x 8x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 48x 48x 4x 4x 2x 2x 4x 46x 6x 6x 6x 6x 6x 6x 40x 48x 48x 48x 48x 48x 48x 48x 48x 39x 34x 1x 1x 1x 1x 1x 1x 33x 33x 33x 33x 33x 33x 33x 33x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 48x 26x 48x 3x 3x 48x 2x 2x 2x 2x 2x 2x 20x 46x 26x 26x 15x 15x 15x 15x 15x 15x 15x 26x 11x 11x 26x 48x 26x 26x 26x 26x 22x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 6x 6x 9x 3x 3x 6x 6x 6x 9x 6x 6x 6x 9x 1x 1x 5x 5x 2x 2x 2x 2x 2x 2x 34x 39x 39x 39x 39x 39x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 4x 8x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x | import { isAPIKeyRequiredForProvider } from '@api/ai-providers';
import { getApiUrl } from '@api/constants';
import {
evaluationCriteria,
scoringGuidelinesText,
} from '@api/evaluations/generic-judge-defaults';
import {
type EvaluationInput,
type LLMJudge,
type LLMJudgeConfig,
LLMJudgeResult,
} from '@api/types/evaluations/llm-judge';
import type { AppContext } from '@api/types/hono';
import { error, warn } from '@shared/console-logging';
import {
type AIProvider,
AIProvider as AIProviderEnum,
} from '@shared/types/constants';
import { CacheMode } from '@shared/types/middleware/cache';
import OpenAI from 'openai';
import { z } from 'zod';
// Constants for retry logic
const LLM_JUDGE_MAX_RETRIES = 3;
const LLM_JUDGE_RETRY_DELAY_BASE = 1000; // 1 second base delay
/**
* Check if an error is retryable for LLM judge requests
*/
function isRetryableLLMJudgeError(error: unknown): boolean {
if (error instanceof Error) {
const message = error.message.toLowerCase();
return (
message.includes('timeout') ||
message.includes('network') ||
message.includes('connection') ||
message.includes('rate limit') ||
message.includes('too many requests') ||
message.includes('temporary') ||
message.includes('server error') ||
message.includes('gateway') ||
message.includes('service unavailable')
);
}
return false;
}
/**
* Check if input text appears to be a pre-formatted template prompt
*/
function isTemplateBasedInput(text: string): boolean {
// Generic template detection criteria:
const templateIndicators = [
text.includes('You are an expert evaluator'),
text.includes('You are a quality evaluator'),
text.includes('Provide your evaluation as a JSON object'),
text.includes('Return your response as a JSON object'),
text.includes('You are') &&
text.includes('evaluate') &&
text.includes('\n\n'),
];
// Must have at least one strong indicator AND contain double newlines (separator)
return (
templateIndicators.some((indicator) => indicator) && text.includes('\n\n')
);
}
/**
* Parse a template-based prompt into system and user components
*/
function parseTemplatePrompt(text: string): {
systemPrompt: string;
userPrompt: string;
} {
// Split on first occurrence of double newline
const doubleLnIndex = text.indexOf('\n\n');
if (doubleLnIndex === -1) {
return { systemPrompt: '', userPrompt: text };
}
const systemPrompt = text.substring(0, doubleLnIndex).trim();
const userPrompt = text.substring(doubleLnIndex + 2).trim();
// Validate that we have meaningful content in both parts
if (systemPrompt.length < 10 || userPrompt.length < 10) {
return { systemPrompt: '', userPrompt: text };
}
return { systemPrompt, userPrompt };
}
/**
* Check if the prompt expects structured JSON output
*/
function expectsStructuredOutput(systemPrompt: string): boolean {
return (
systemPrompt.includes('JSON object') ||
systemPrompt.includes('JSON structure') ||
systemPrompt.includes('Return your response as') ||
systemPrompt.includes('as a JSON object')
);
}
/**
* Zod schema for evaluation results
*/
const EvaluationResultSchema = z.object({
score: z.number().min(0).max(1).describe('Evaluation score between 0 and 1'),
reasoning: z.string().describe('Detailed reasoning for the evaluation'),
});
/**
* Model configuration for LLM judge
*/
export interface LLMJudgeModelConfig {
model: string;
provider: AIProvider;
/** The provider's API key, where it needs one. */
apiKey?: string;
/** The provider's configured base URL, where it has one. */
customHost?: string;
}
export function createLLMJudge(
c: AppContext,
config: Partial<LLMJudgeConfig> = {},
modelConfig?: LLMJudgeModelConfig,
openaiClient?: OpenAI,
): LLMJudge {
const judgeConfig = {
model: modelConfig?.model || config.model || 'gpt-5-mini',
temperature: config.temperature || 0.1,
max_tokens: config.max_tokens || 1000,
timeout: config.timeout || 30000,
};
// Provider and API key from model config or defaults
const provider = modelConfig?.provider || AIProviderEnum.OPENAI;
const apiKey = modelConfig?.apiKey || '';
const customHost = modelConfig?.customHost;
// Create OpenAI client once (or use injected client for testing)
const client =
openaiClient ||
new OpenAI({
apiKey: '',
baseURL: `${getApiUrl(c)}/v1`,
dangerouslyAllowBrowser: true, // Safe in server-side Node.js context
});
/**
* Generate evaluation prompt for text evaluation
*/
function generateEvaluationPrompt(input: EvaluationInput): {
systemPrompt: string;
userPrompt: string;
useStructuredOutput: boolean;
} {
// If outputFormat is explicitly specified (always 'json' now), use structured output
if (input.outputFormat === 'json') {
const { systemPrompt, userPrompt } = parseTemplatePrompt(input.text);
if (systemPrompt && userPrompt) {
return { systemPrompt, userPrompt, useStructuredOutput: true };
}
}
// Template-based evaluation: More robust detection of pre-formatted prompts
if (isTemplateBasedInput(input.text)) {
const { systemPrompt, userPrompt } = parseTemplatePrompt(input.text);
if (systemPrompt && userPrompt) {
const useStructuredOutput = expectsStructuredOutput(systemPrompt);
return { systemPrompt, userPrompt, useStructuredOutput };
}
}
// Criteria-based evaluation (generic judge fallback)
const criteria =
input.evaluationCriteria?.criteria || evaluationCriteria.general;
const systemPrompt = `You are a quality evaluator. Evaluate the given text based on these criteria:
${criteria.map((criterion: string) => `- ${criterion}`).join('\n')}
Scoring Guidelines:
${scoringGuidelinesText}
Provide a score between 0 and 1 where:
- 1.0 means excellent quality, exceeds expectations
- 0.5 means adequate quality, partially meets expectations
- 0.0 means very poor quality, fails to meet expectations`;
const userPrompt = `Please evaluate the following text:
${input.text}
Provide a score between 0 and 1 with detailed reasoning for your evaluation.`;
return { systemPrompt, userPrompt, useStructuredOutput: false };
}
/**
* Core evaluation method using OpenAI library
*/
async function evaluate(input: EvaluationInput): Promise<LLMJudgeResult> {
// Self-hosted providers such as Ollama are called without a key, so only
// the providers that need one are held to it.
if (apiKey.trim() === '' && isAPIKeyRequiredForProvider(provider)) {
warn('[LLM_JUDGE] API key not configured for evaluation model');
return getFallbackResult('no_api_key', undefined, {
retryCount: 0,
maxRetries: LLM_JUDGE_MAX_RETRIES,
});
}
const saConfig = {
targets: [
{
provider: provider,
model: judgeConfig.model,
cache: {
mode: CacheMode.SIMPLE,
},
...(apiKey ? { api_key: apiKey } : {}),
...(customHost ? { custom_host: customHost } : {}),
},
],
agent_name: 'super-agents',
skill_name: 'judge',
};
let lastError: unknown;
let retryCount = 0;
for (let i = 0; i < LLM_JUDGE_MAX_RETRIES; i++) {
try {
const prompt = generateEvaluationPrompt(input);
const clientWithHeaders = client.withOptions({
defaultHeaders: {
'sa-config': JSON.stringify(saConfig),
},
});
let parsed: unknown;
const response = await clientWithHeaders.chat.completions.parse({
model: judgeConfig.model,
messages: [
{ role: 'system', content: prompt.systemPrompt },
{ role: 'user', content: prompt.userPrompt },
],
response_format: {
type: 'json_schema',
json_schema: {
name: 'evaluation_result',
strict: true,
schema: z.toJSONSchema(EvaluationResultSchema),
},
},
});
parsed = response.choices[0].message.parsed;
if (!parsed) {
throw new Error('No parsed response from AI provider');
}
// For structured output (like task/outcome extraction), return as metadata
if (prompt.useStructuredOutput) {
return {
score: 1.0, // Default score for successful extraction
reasoning: 'Structured data extracted successfully',
metadata: parsed as Record<string, unknown>,
};
}
// For regular evaluation, validate and return
return LLMJudgeResult.parse(parsed);
} catch (err) {
lastError = err;
if (i < LLM_JUDGE_MAX_RETRIES - 1 && isRetryableLLMJudgeError(err)) {
const delay = LLM_JUDGE_RETRY_DELAY_BASE * 2 ** i;
warn(
`[LLM_JUDGE] Retrying evaluation (${i + 1}/${LLM_JUDGE_MAX_RETRIES}) after ${delay}ms:`,
err instanceof Error ? err.message : String(err),
);
await new Promise((resolve) => setTimeout(resolve, delay));
retryCount++;
} else {
break;
}
}
}
// Categorize error type for better fallback messaging
const retryInfo = {
retryCount,
maxRetries: LLM_JUDGE_MAX_RETRIES,
};
if (lastError instanceof Error) {
error('[LLM_JUDGE] Evaluation failed:', {
errorMessage: lastError.message,
errorStack: lastError.stack,
retryCount,
model: judgeConfig.model,
});
if (
lastError.message.includes('fetch') ||
lastError.message.includes('network')
) {
return getFallbackResult('network_error', lastError.message, retryInfo);
}
if (
lastError.message.includes('JSON') ||
lastError.message.includes('parse') ||
lastError.message.includes('No valid message output') ||
lastError.message.includes('No valid text content')
) {
return getFallbackResult('parse_error', lastError.message, retryInfo);
}
if (
lastError.message.includes('timeout') ||
lastError.message.includes('abort')
) {
return getFallbackResult('timeout_error', lastError.message, retryInfo);
}
if (
lastError.message.includes('unknown') ||
lastError.message.includes('Unknown')
) {
return getFallbackResult('unknown_error', lastError.message, retryInfo);
}
return getFallbackResult('api_error', lastError.message, retryInfo);
}
error('[LLM_JUDGE] Evaluation failed with unknown error:', {
error: String(lastError),
retryCount,
model: judgeConfig.model,
});
return getFallbackResult('unknown_error', String(lastError), retryInfo);
}
return {
evaluate,
config: judgeConfig,
};
}
/**
* Get fallback result with specific error type and optional details
*/
function getFallbackResult(
errorType:
| 'no_api_key'
| 'network_error'
| 'parse_error'
| 'timeout_error'
| 'api_error'
| 'unknown_error',
errorDetails?: string,
retryInfo?: {
retryCount: number;
maxRetries: number;
},
): LLMJudgeResult {
const errorMessages = {
no_api_key: 'Evaluation skipped - OpenAI API key not configured',
network_error: 'Evaluation failed - network connection error',
parse_error: 'Evaluation failed - response parsing error',
timeout_error: 'Evaluation failed - request timeout',
api_error: 'Evaluation failed - OpenAI API error',
unknown_error: 'Evaluation failed - unknown error occurred',
};
const reasoning =
retryInfo && retryInfo.retryCount > 0
? `${errorMessages[errorType]} (retried ${retryInfo.retryCount}/${retryInfo.maxRetries} times)`
: errorMessages[errorType];
return {
score: 0.5,
reasoning,
metadata: {
fallback: true,
errorType,
...(errorDetails && { errorDetails }),
...(retryInfo && retryInfo.retryCount > 0 && { retryInfo }),
},
};
}
|