@dooor-ai/toolkit
Version:
Guards, Evals & Observability for AI applications - works seamlessly with LangChain/LangGraph
163 lines (140 loc) • 4.55 kB
text/typescript
import { Eval } from "./base";
import { EvalResult, EvalConfig } from "../core/types";
import { getCortexDBClient, getGlobalProviderName } from "../observability/cortexdb-client";
export interface FaithfulnessConfig extends EvalConfig {
/** Context/retrieved documents to check against */
context?: string;
}
/**
* FaithfulnessEval - Measures if the LLM's answer is grounded in the provided context
*
* Critical for RAG systems to prevent hallucination. Checks if claims in the answer
* are supported by the retrieved context.
*
* Example:
* ```typescript
* const eval = new FaithfulnessEval({
* threshold: 0.8,
* context: "The Eiffel Tower is 330 meters tall."
* });
* const result = await eval.evaluate(
* "How tall is the Eiffel Tower?",
* "The Eiffel Tower is 330 meters tall."
* );
* // result.score = 1.0, result.passed = true
* ```
*/
export class FaithfulnessEval extends Eval {
private context?: string;
constructor(config: FaithfulnessConfig = {}) {
super(config);
this.context = config.context;
}
get name(): string {
return "FaithfulnessEval";
}
/**
* Set context dynamically (useful for RAG pipelines)
*/
setContext(context: string): void {
this.context = context;
}
async evaluate(
input: string,
output: string,
metadata?: Record<string, any>
): Promise<EvalResult> {
const startTime = Date.now();
// Get context from metadata if not set directly
const context = this.context || metadata?.context || metadata?.retrievedDocs;
if (!context) {
return {
name: this.name,
score: 0.5,
passed: false,
details: "No context provided for faithfulness 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, output, 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: `Faithfulness 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("FaithfulnessEval 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, answer: string, context: string): string {
return `You are an expert evaluator. Your task is to assess if the answer is faithful to (grounded in) the provided context.
Context: """
${context}
"""
Question: "${question}"
Answer: "${answer}"
Evaluate faithfulness:
- 1.0 = All claims in answer are directly supported by context
- 0.7-0.9 = Most claims supported, minor unsupported details
- 0.4-0.6 = Some claims supported, some not found in context
- 0.0-0.3 = Answer contains hallucinations or unsupported claims
Output ONLY a JSON object in this exact format:
{
"score": 0.9,
"reasoning": "Brief explanation of what's supported and what's not"
}`;
}
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;
}
}
}