Continuous GenAI Evaluation and Hallucination Regression Gate with DeepEval
Automated LLM evaluation and hallucination regression testing with DeepEval, quality gates, and Slack alerts.
Catch Fabricated Citations with an Answer Grounding Guard
id: ai-answer-grounding-guard
namespace: company.team
description: |
Check that AI answers actually rest on the sources they cite. The guard loads a question
and answer evaluation set (or generates one with the bundled stub sets), then verifies
every answer: does it cite anything at all, do the cited sources exist, do the quoted
spans really appear in those sources, are numeric claims backed by a citation, and are
the cited sources still fresh. Every check feeds one grounding scorecard with
per-category pass rates and a trend against the previous run, and a failed gate opens a
GitHub issue and pages Slack, so fabricated citations get caught in review, not by users.
triggers:
- id: daily_grounding_guard
type: io.kestra.plugin.core.trigger.Schedule
description: Daily 07:30 UTC grounding run over the previous day's sampled
production answers; run it on demand from the UI or API right after a
model, prompt, or corpus change.
cron: 30 7 * * *
inputs:
- id: eval_set_url
type: STRING
defaults: ''
description: URL (http, https, or file) of a JSON evaluation set to check
instead of the bundled stub set. The set carries sources (id, text,
updated date) and items (question, answer, citations, quotes).
- id: eval_set_json
type: STRING
defaults: ''
description: Inline JSON evaluation set, taking precedence over eval_set_url.
Leave empty in production; this is the seam for pointing the guard at a
generated set.
- id: stub_mode
type: STRING
defaults: grounded
description: Behaviour of the bundled stub set when no set is supplied.
"grounded" is fully cited with exact quotes; "fabricated" cites a missing
source, alters a quote, and makes an uncited numeric claim; "mixed" is
half clean, half flawed.
- id: max_source_age_days
type: INT
defaults: 400
description: A cited source older than this many days (from the set's checked_at
date) counts as stale. Twice this age is a high severity finding.
- id: min_grounding_score
type: INT
defaults: 80
description: Minimum overall grounding score (0-100) for the run to pass.
- id: min_category_rate
type: INT
defaults: 70
description: Minimum per-category pass rate (percent). A category below this
floor fails the run even when the overall score passes, and any critical
failure fails the run outright.
- id: previous_scorecard_url
type: STRING
defaults: ''
description: URL (http, https, or file) of the previous run's scorecard.json,
used for the trend comparison. Empty marks this run as the baseline.
- id: github_repository
type: STRING
defaults: acme/ai-platform
description: Repository that receives the tracking issue when the grounding gate fails.
tasks:
- id: guard_workspace
type: io.kestra.plugin.core.flow.WorkingDirectory
description: One shared directory so the evaluation set, the findings, and the
scorecard are the same files every stage reads.
tasks:
- id: load_eval_set
type: io.kestra.plugin.scripts.python.Script
description: Resolve the evaluation set (inline JSON, then URL, then the bundled
stub set), validate sources and items, and write eval_set.json plus
set_meta.json with the set's totals.
taskRunner:
type: io.kestra.plugin.core.runner.Process
env:
EVAL_SET_URL: '{{ inputs.eval_set_url }}'
EVAL_SET_JSON: '{{ inputs.eval_set_json }}'
STUB_MODE: '{{ inputs.stub_mode }}'
script: |
import json
import os
import urllib.request
def stub_set(mode):
sources = {
"s1": {"text": "The refund window is 30 days from delivery. Refunds "
"land back on the original payment method within 5 days.",
"updated": "2026-09-01"},
"s2": {"text": "Premium support answers within 4 business hours. "
"Standard support answers within 2 business days.",
"updated": "2026-08-15"},
"s3": {"text": "Data is stored in the EU region by default for all "
"accounts created after March 2024.",
"updated": "2025-01-10"},
}
good = [
{"question": "How long do I have to ask for a refund?",
"answer": "You have 30 days from delivery to ask for a refund.",
"citations": ["s1"],
"quotes": [{"source": "s1",
"text": "The refund window is 30 days from delivery."}]},
{"question": "How fast is premium support?",
"answer": "Premium support answers within 4 business hours.",
"citations": ["s2"],
"quotes": [{"source": "s2",
"text": "Premium support answers within 4 business hours."}]},
{"question": "When does the refund money arrive?",
"answer": "Refunds land back on the original payment method within "
"5 days of approval.",
"citations": ["s1"],
"quotes": [{"source": "s1",
"text": "within 5 days"}]},
{"question": "What about standard support?",
"answer": "Standard support answers within 2 business days.",
"citations": ["s2"],
"quotes": [{"source": "s2",
"text": "Standard support answers within 2 business days."}]},
]
flawed = [
{"question": "Can I get a refund after two months?",
"answer": "Yes, the refund window is 60 days from delivery.",
"citations": ["s9"],
"quotes": [{"source": "s9",
"text": "The refund window is 60 days from delivery."}]},
{"question": "How long do I have to ask for a refund?",
"answer": "You have 90 days from delivery to ask for a refund.",
"citations": ["s1"],
"quotes": [{"source": "s1",
"text": "The refund window is 90 days from delivery."}]},
{"question": "What discount do annual plans get?",
"answer": "Annual plans get a 25 percent discount on every seat, "
"applied automatically at checkout.",
"citations": [],
"quotes": []},
{"question": "Where is my data stored?",
"answer": "Data is stored in the EU region by default.",
"citations": ["s3"],
"quotes": [{"source": "s3",
"text": "Data is stored in the EU region by default"}]},
]
if mode == "fabricated":
items = flawed
elif mode == "mixed":
items = good[:2] + flawed[1:3]
else:
items = good
return {"checked_at": "2026-10-23", "sources": sources, "items": items}
def load_set():
inline = os.environ.get("EVAL_SET_JSON", "").strip()
if inline:
return json.loads(inline), "inline"
url = os.environ.get("EVAL_SET_URL", "").strip()
if url:
if url.startswith("file://"):
with open(url[7:], encoding="utf-8") as handle:
return json.load(handle), "file"
with urllib.request.urlopen(url, timeout=30) as response:
return json.loads(response.read().decode("utf-8")), "url"
mode = os.environ.get("STUB_MODE", "grounded").strip() or "grounded"
return stub_set(mode), "stub:" + mode
raw, source = load_set()
if not isinstance(raw, dict) or "sources" not in raw or "items" not in raw:
raise ValueError("evaluation set must carry sources and items")
sources = raw["sources"]
items = raw["items"]
if not isinstance(sources, dict) or not sources:
raise ValueError("sources must be a non-empty object keyed by source id")
if not isinstance(items, list) or not items:
raise ValueError("items must be a non-empty list")
for index, item in enumerate(items):
for field in ("question", "answer"):
if field not in item:
raise ValueError("item %d is missing the %s field" % (index + 1, field))
item.setdefault("citations", [])
item.setdefault("quotes", [])
checked_at = str(raw.get("checked_at", "2026-10-23"))
normalised = {"checked_at": checked_at, "sources": sources, "items": items}
meta = {"source": source, "checked_at": checked_at,
"items": len(items), "sources": len(sources)}
with open("eval_set.json", "w", encoding="utf-8") as handle:
json.dump(normalised, handle, indent=2)
with open("set_meta.json", "w", encoding="utf-8") as handle:
json.dump(meta, handle, indent=2)
print("loaded %d items and %d sources from %s (checked_at %s)"
% (meta["items"], meta["sources"], source, checked_at))
- id: analyse_set
type: io.kestra.plugin.scripts.python.Script
description: Run the grounding batteries over eval_set.json. Citation coverage
and validity, quote fidelity against the source text, numeric claims
without a citation, answer to source overlap, and cited source
freshness. Writes findings.json with one record per check.
taskRunner:
type: io.kestra.plugin.core.runner.Process
env:
MAX_SOURCE_AGE_DAYS: '{{ inputs.max_source_age_days }}'
script: |
import datetime
import json
import os
import re
def normalise(text):
return re.sub(r"\s+", " ", str(text).lower()).strip()
def words(text):
return set(re.findall(r"[a-z0-9]+", str(text).lower()))
with open("eval_set.json", encoding="utf-8") as handle:
data = json.load(handle)
sources = data["sources"]
items = data["items"]
checked_at = datetime.date.fromisoformat(data["checked_at"])
max_age = int(os.environ.get("MAX_SOURCE_AGE_DAYS", "400"))
findings = []
def record(check, category, passed, severity, detail):
findings.append({"id": check, "category": category, "passed": passed,
"severity": severity, "detail": detail})
uncited = [i for i, item in enumerate(items) if not item["citations"]]
record("citation_coverage", "grounding", not uncited, "high",
"%d of %d answers carry no citation (items %s)"
% (len(uncited), len(items), [i + 1 for i in uncited]))
missing = sorted({c for item in items for c in item["citations"]
if c not in sources})
record("citation_validity", "citation_integrity", not missing, "critical",
"cited sources that do not exist: %s" % (missing or "none"))
bad_quotes = []
for index, item in enumerate(items):
for quote in item["quotes"]:
source_text = sources.get(quote.get("source", ""), {}).get("text", "")
if normalise(quote.get("text", "")) not in normalise(source_text):
bad_quotes.append(index + 1)
record("quote_fidelity", "citation_integrity", not bad_quotes, "critical",
"quotes that do not appear in their source, on items %s" % bad_quotes)
numeric_uncited = []
for index, item in enumerate(items):
if re.search(r"\d", item["answer"]) and not item["citations"]:
numeric_uncited.append(index + 1)
record("numeric_claims_cited", "grounding", not numeric_uncited, "high",
"answers with numbers but no citation, items %s" % numeric_uncited)
low_overlap = []
for index, item in enumerate(items):
cited_text = " ".join(sources[c]["text"] for c in item["citations"]
if c in sources)
answer_words = words(item["answer"]) - {"the", "a", "an", "is", "to", "of",
"for", "you", "your", "do", "does"}
if not answer_words:
continue
overlap = len(answer_words & words(cited_text)) / len(answer_words)
if overlap < 0.35:
low_overlap.append(index + 1)
record("answer_source_overlap", "grounding", not low_overlap, "medium",
"answers sharing under 35 percent of content words with their cited "
"sources, items %s" % low_overlap)
stale, ancient = [], []
for index, item in enumerate(items):
for citation in item["citations"]:
updated = sources.get(citation, {}).get("updated")
if not updated:
continue
age = (checked_at - datetime.date.fromisoformat(updated)).days
if age > 2 * max_age:
ancient.append(index + 1)
elif age > max_age:
stale.append(index + 1)
record("source_freshness", "freshness", not stale and not ancient,
"high" if ancient else "medium",
"answers citing stale sources: %s; citing sources over twice the age "
"limit: %s" % (sorted(set(stale)), sorted(set(ancient))))
with open("findings.json", "w", encoding="utf-8") as handle:
json.dump(findings, handle, indent=2)
failed = [f for f in findings if not f["passed"]]
print("analysis complete: %d checks, %d failed; missing sources %s; "
"bad quotes on items %s"
% (len(findings), len(failed), missing, bad_quotes))
- id: build_scorecard
type: io.kestra.plugin.scripts.python.Script
description: Turn findings.json into the grounding scorecard. Per-category pass
rates, one overall score, the gate verdict (score floor, category
floor, no critical failures), and a trend against the previous
scorecard when one is supplied. Writes scorecard.json and scorecard.md
and emits the gate outputs the triage branch reads.
taskRunner:
type: io.kestra.plugin.core.runner.Process
env:
MIN_GROUNDING_SCORE: '{{ inputs.min_grounding_score }}'
MIN_CATEGORY_RATE: '{{ inputs.min_category_rate }}'
PREVIOUS_SCORECARD_URL: '{{ inputs.previous_scorecard_url }}'
script: |
import json
import os
import urllib.request
from kestra import Kestra
with open("findings.json", encoding="utf-8") as handle:
findings = json.load(handle)
with open("set_meta.json", encoding="utf-8") as handle:
meta = json.load(handle)
min_score = float(os.environ.get("MIN_GROUNDING_SCORE", "80"))
min_rate = float(os.environ.get("MIN_CATEGORY_RATE", "70"))
categories = {}
for finding in findings:
bucket = categories.setdefault(finding["category"], {"passed": 0, "total": 0})
bucket["total"] += 1
bucket["passed"] += 1 if finding["passed"] else 0
for bucket in categories.values():
bucket["rate"] = round(100.0 * bucket["passed"] / bucket["total"], 1)
total = len(findings)
passed_count = sum(1 for f in findings if f["passed"])
overall = round(100.0 * passed_count / total, 1) if total else 0.0
failures = [f for f in findings if not f["passed"]]
critical_failures = [f for f in failures if f["severity"] == "critical"]
weak = [name for name, data in categories.items() if data["rate"] < min_rate]
gate_passed = overall >= min_score and not weak and not critical_failures
trend = {"verdict": "baseline", "note": "no previous scorecard; this run is the baseline"}
previous_url = os.environ.get("PREVIOUS_SCORECARD_URL", "").strip()
if previous_url:
try:
if previous_url.startswith("file://"):
with open(previous_url[7:], encoding="utf-8") as handle:
previous = json.load(handle)
else:
with urllib.request.urlopen(previous_url, timeout=30) as response:
previous = json.loads(response.read().decode("utf-8"))
before = float(previous["overall"]["grounding_score"])
delta = round(overall - before, 1)
if delta <= -10:
trend = {"verdict": "regressed",
"note": "grounding score fell %.1f points (%.1f to %.1f)"
% (abs(delta), before, overall)}
elif delta >= 10:
trend = {"verdict": "improved",
"note": "grounding score rose %.1f points (%.1f to %.1f)"
% (delta, before, overall)}
else:
trend = {"verdict": "steady",
"note": "grounding score steady (%.1f to %.1f)" % (before, overall)}
except Exception as error:
trend = {"verdict": "unknown",
"note": "previous scorecard unreadable: %s" % error}
scorecard = {
"set": meta,
"categories": categories,
"overall": {"grounding_score": overall, "gate_passed": gate_passed,
"critical_failures": len(critical_failures),
"checks_passed": passed_count, "checks_total": total},
"failures": failures,
"trend": trend,
}
with open("scorecard.json", "w", encoding="utf-8") as handle:
json.dump(scorecard, handle, indent=2)
lines = ["# AI answer grounding guard scorecard", "",
"Set source `%s`: %d answers checked against %d sources."
% (meta["source"], meta["items"], meta["sources"]), "",
"**Grounding score: %.1f/100** (gate %.0f). Gate %s. Trend: %s."
% (overall, min_score, "PASSED" if gate_passed else "FAILED",
trend["note"]), "", "## Categories", ""]
for name, data in categories.items():
lines.append("- %s: %.1f%% (%d/%d checks)"
% (name, data["rate"], data["passed"], data["total"]))
if failures:
lines += ["", "## Failures", ""]
for failure in failures:
lines.append("- **%s** (%s, %s): %s"
% (failure["id"], failure["category"],
failure["severity"], failure["detail"]))
with open("scorecard.md", "w", encoding="utf-8") as handle:
handle.write("\n".join(lines) + "\n")
print("grounding score %.1f/100 across %d checks; gate %s; critical failures %d; "
"weak categories: %s; trend: %s"
% (overall, total, "PASSED" if gate_passed else "FAILED",
len(critical_failures), ", ".join(weak) or "none", trend["note"]))
Kestra.outputs({"grounding_score": overall, "passed": gate_passed,
"critical_failures": len(critical_failures),
"critical_count": len(critical_failures),
"weak_categories": weak,
"weak_summary": ", ".join(weak) if weak else "none",
"trend_note": trend["note"],
"trend_verdict": trend["verdict"]})
- id: write_trend_record
type: io.kestra.plugin.scripts.python.Script
description: Append this run to trend.jsonl (source, score, per-category rates,
gate verdict, trend verdict) so answer grounding is auditable over
time, and emit the record as a task output.
taskRunner:
type: io.kestra.plugin.core.runner.Process
script: |
import datetime
import json
from kestra import Kestra
with open("scorecard.json", encoding="utf-8") as handle:
scorecard = json.load(handle)
entry = {
"date": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"source": scorecard["set"]["source"],
"grounding_score": scorecard["overall"]["grounding_score"],
"gate_passed": scorecard["overall"]["gate_passed"],
"critical_failures": scorecard["overall"]["critical_failures"],
"items": scorecard["set"]["items"],
"categories": {name: data["rate"]
for name, data in scorecard["categories"].items()},
"trend": scorecard["trend"]["note"],
}
with open("trend.jsonl", "a", encoding="utf-8") as handle:
handle.write(json.dumps(entry) + "\n")
print("trend record appended:", json.dumps(entry))
Kestra.outputs({"trend_record": entry})
- id: triage
type: io.kestra.plugin.core.flow.If
description: Branch on the gate. A passing run just records itself; a failing
run gets the full escalation.
condition: '{{ outputs.build_scorecard.vars.passed == false }}'
then:
- id: escalate
type: io.kestra.plugin.core.flow.Parallel
description: Open the tracking issue and alert Slack at the same time; the
scorecard is attached to the execution for review.
tasks:
- id: raise_issue
type: io.kestra.plugin.github.issues.Create
description: Open a labeled GitHub issue with the grounding score, the weak
categories, and the critical failure count, so fabricated or stale
citations land in the engineering backlog.
jwtToken: '{{ secret(''GITHUB_TOKEN'') }}'
repository: '{{ inputs.github_repository }}'
title: 'AI answer grounding guard: score {{
outputs.build_scorecard.vars.grounding_score }}/100, gate failed'
body: '## AI answer grounding results
**Grounding score: {{ outputs.build_scorecard.vars.grounding_score
}}/100** (gate `{{ inputs.min_grounding_score }}`, per-category
floor `{{ inputs.min_category_rate }}`).
Weak categories: {{ outputs.build_scorecard.vars.weak_summary }}.
Critical failures: {{ outputs.build_scorecard.vars.critical_count
}}. Trend: {{ outputs.build_scorecard.vars.trend_note }}.
The full scorecard is in `scorecard.json` and `scorecard.md` on
the execution''s file outputs. Find the failing answers in
`findings.json`, fix the retrieval, prompt, or corpus entry behind
them, then re-run the guard before the answers ship again.
'
- id: notify_slack
type: io.kestra.plugin.slack.notifications.SlackIncomingWebhook
description: Page the team channel with the score and the weak categories so a
grounding failure is seen within minutes.
url: '{{ secret(''SLACK_WEBHOOK_URL'') }}'
messageText: ':rotating_light: AI answer grounding guard: score {{
outputs.build_scorecard.vars.grounding_score }}/100, gate failed.
Weak categories: {{ outputs.build_scorecard.vars.weak_summary }}.
Critical failures: {{ outputs.build_scorecard.vars.critical_count
}}. Tracking issue opened in {{ inputs.github_repository }}.
'
else:
- id: record_passing_run
type: io.kestra.plugin.scripts.python.Script
description: Record the passing run (score and trend) so the team has an
auditable trail of answers staying grounded over time.
taskRunner:
type: io.kestra.plugin.core.runner.Process
env:
SCORE: '{{ outputs.build_scorecard.vars.grounding_score }}'
TREND_NOTE: '{{ outputs.build_scorecard.vars.trend_note }}'
script: |
import json
import os
from kestra import Kestra
print("passing run: AI answer grounding score %s/100, no critical failures. Trend: %s"
% (os.environ.get("SCORE", "?"), os.environ.get("TREND_NOTE", "n/a")))
Kestra.outputs({"verdict": "passing"})
AI answers sound confident even when the citations under them are invented. This blueprint checks a set of questions and answers against the sources they cite and proves the link is real: the sources exist, the quotes appear in them word for word, the numbers in the answer carry a citation, and the sources are not years out of date. Every check feeds one grounding scorecard with per-category pass rates and a trend against the last run. A failed gate opens a GitHub issue and pages Slack.
Run it as-is first: switch stub_mode to "fabricated" and the set cites a source that does not exist, alters a 30 day refund window into 90 days inside a quote, makes a numeric claim with no citation at all, and leans on a source from January 2025. The gate fails with critical findings and you see the full escalation path.
Grounding: every answer carries at least one citation, numeric claims are cited, and the answer's own words overlap the cited sources, so an answer cannot drift away from what it claims to rest on.
Citation integrity: cited source IDs must exist in the corpus, and every quoted span must appear in its source after normalising case and whitespace. An altered quote is a critical failure, because that is how fabricated evidence ships.
Freshness: cited sources older than max_source_age_days are flagged, and sources past twice that age raise the severity, so answers stop resting on retired documentation.
daily_grounding_guard (Schedule trigger) runs the guard daily at 07:30 UTC. Run it on demand after any model, prompt, or corpus change.
load_eval_set (Python) resolves the evaluation set from inline JSON, a URL, or the bundled stub sets, validates sources and items, and normalises the fields the checks need.
analyse_set (Python) runs the six checks: citation coverage, citation validity, quote fidelity, numeric claims cited, answer to source overlap, and source freshness.
build_scorecard (Python) turns the findings into per-category pass rates and one grounding score, applies the gate, compares with the previous scorecard for the trend, and writes scorecard.json, scorecard.md, and the trend record.
triage (flow tasks) branches on the gate: passing runs are recorded; failing runs open the GitHub issue and post the Slack alert in parallel.
An evaluation set as JSON: sources keyed by ID with text and an updated date, plus items with question, answer, citations, and quotes. Sample production answers into it, or use the bundled stub sets.
A GitHub token with issue-write scope on the tracking repository.
A Slack incoming webhook URL for the team channel.
GITHUB_TOKEN: token used to open the tracking issue (required).
SLACK_WEBHOOK_URL: incoming webhook for the team-channel alert (required).
Add the two secrets above to your Kestra namespace.
Import this blueprint and run it with the default "grounded" stub: the gate passes and the scorecard records a clean run.
Run it again with stub_mode set to "fabricated" and then "mixed" to see both failure shapes and the escalation.
Point eval_set_url at your own sampled answers, set max_source_age_days to your documentation's real shelf life, and leave the daily schedule enabled.
Sample live traffic: replace the stub load with a subflow that pulls yesterday's answers from your serving logs and builds the set automatically.
Add an LLM judge stage for the answers that pass the mechanical checks but still read as unsupported, and feed its verdicts into the same scorecard.
Write the scorecard to a warehouse table for a grounding quality dashboard.
Gate releases: fail the deployment pipeline when the grounding score drops below threshold or the trend verdict is regressed.
Automated LLM evaluation and hallucination regression testing with DeepEval, quality gates, and Slack alerts.
Find new images for running Docker Compose services, summarize their release notes with AI, update only what a person approves, and roll back automatically when the new version isn't healthy.
Track mentions of your project on Hacker News, Stack Overflow, GitHub and dev.to, triage them with an LLM and post an urgency-grouped Slack digest.
Ingest dynamic URLs, run Crawl4AI with headless Chromium stealth, extract token-optimized Markdown, and sink clean text to storage.
Upload a lecture video and get course content (title, summary, chapters and quiz) generated with Amazon Transcribe and Bedrock, then sent for human approval.
Build dbt marts on DuckDB, check row-volume drift and metric reconciliation against a KV baseline, and sync/warm Apache Superset exposures or triage breaches.
