@dooor-ai/toolkit
Version:
Guards, Evals & Observability for AI applications - works seamlessly with LangChain/LangGraph
161 lines (138 loc) • 4.49 kB
text/typescript
import { Eval } from "./base";
import { EvalResult, EvalConfig } from "../core/types";
import { getCortexDBClient, getGlobalProviderName } from "../observability/cortexdb-client";
export interface ContextualPrecisionConfig extends EvalConfig {
/** Retrieved context/documents */
context?: string;
}
/**
* ContextualPrecisionEval - Measures if the retrieved context is relevant (no noise)
*
* Evaluates whether the retrieved documents are actually useful for answering
* the question. High precision means low noise, no irrelevant docs.
*
* Example:
* ```typescript
* const eval = new ContextualPrecisionEval({
* threshold: 0.8,
* context: "Paris is the capital of France. The weather is sunny today."
* });
* const result = await eval.evaluate(
* "What is the capital of France?",
* "Paris"
* );
* // result.score = 0.75 (50% relevant, 50% noise), result.passed = false
* ```
*/
export class ContextualPrecisionEval extends Eval {
private context?: string;
constructor(config: ContextualPrecisionConfig = {}) {
super(config);
this.context = config.context;
}
get name(): string {
return "ContextualPrecisionEval";
}
/**
* Set context dynamically
*/
setContext(context: string): void {
this.context = context;
}
async evaluate(
input: string,
output: string,
metadata?: Record<string, any>
): Promise<EvalResult> {
const startTime = Date.now();
const context = this.context || metadata?.context || metadata?.retrievedDocs;
if (!context) {
return {
name: this.name,
score: 0.5,
passed: false,
details: "No context provided for precision evaluation. Pass 'context' via config or metadata.",
metadata: {
latency: Date.now() - startTime,
},
timestamp: new Date(),
};
}
try {
const cortexClient = getCortexDBClient();
const providerName = getGlobalProviderName();
const prompt = this.buildPrompt(input, context);
const response = await cortexClient.invokeAI({
prompt,
usage: "evaluation",
providerName: providerName || undefined,
temperature: 0.0,
maxTokens: 300,
});
const score = this.parseScore(response.text);
const passed = score >= this.getThreshold();
return {
name: this.name,
score,
passed,
details: `Contextual precision score: ${score.toFixed(2)}. ${passed ? "PASSED" : "FAILED"} (threshold: ${this.getThreshold()})`,
metadata: {
latency: Date.now() - startTime,
judgeResponse: response.text,
contextLength: context.length,
},
timestamp: new Date(),
};
} catch (error) {
console.error("ContextualPrecisionEval failed:", error);
return {
name: this.name,
score: 0.5,
passed: false,
details: `Eval failed: ${error instanceof Error ? error.message : "Unknown error"}`,
metadata: {
error: String(error),
latency: Date.now() - startTime,
},
timestamp: new Date(),
};
}
}
private buildPrompt(question: string, context: string): string {
return `You are an expert evaluator. Your task is to measure PRECISION: how much of the retrieved context is actually relevant to the question?
Question: "${question}"
Retrieved Context: """
${context}
"""
Evaluate precision (relevance ratio):
- 1.0 = 100% of context is relevant, zero noise
- 0.7-0.9 = Most context is relevant, minor irrelevant parts
- 0.4-0.6 = Mixed, significant irrelevant content
- 0.0-0.3 = Mostly irrelevant, high noise
Output ONLY a JSON object in this exact format:
{
"score": 0.85,
"reasoning": "What percentage is relevant vs irrelevant"
}`;
}
private parseScore(response: string): number {
try {
const jsonMatch = response.match(/\{[\s\S]*\}/);
if (jsonMatch) {
const parsed = JSON.parse(jsonMatch[0]);
if (typeof parsed.score === "number") {
return Math.max(0, Math.min(1, parsed.score));
}
}
const numberMatch = response.match(/\b0?\.\d+\b|\b1\.0\b|\b[01]\b/);
if (numberMatch) {
return Math.max(0, Math.min(1, parseFloat(numberMatch[0])));
}
console.warn("Could not parse score from response:", response);
return 0.5;
} catch (error) {
console.error("Error parsing score:", error);
return 0.5;
}
}
}