UNPKG

@dooor-ai/toolkit

Version:

Guards, Evals & Observability for AI applications - works seamlessly with LangChain/LangGraph

141 lines (136 loc) 4.89 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FaithfulnessEval = void 0; const base_1 = require("./base"); const cortexdb_client_1 = require("../observability/cortexdb-client"); /** * 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 * ``` */ class FaithfulnessEval extends base_1.Eval { constructor(config = {}) { super(config); this.context = config.context; } get name() { return "FaithfulnessEval"; } /** * Set context dynamically (useful for RAG pipelines) */ setContext(context) { this.context = context; } async evaluate(input, output, metadata) { 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 = (0, cortexdb_client_1.getCortexDBClient)(); const providerName = (0, cortexdb_client_1.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(), }; } } buildPrompt(question, answer, context) { 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" }`; } parseScore(response) { 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; } } } exports.FaithfulnessEval = FaithfulnessEval;