用 100 行 Python 檢查,在客服聊天機械人回答前找出過期及互相矛盾的支援文件
Catch stale and conflicting support docs before your chatbot does: a 100-line Python check
作者提供一個僅用 Python 標準庫的檢查腳本,可在 CI 檢查支援知識庫的文件新鮮度、退役文件替代關係及檢索回歸。示例涵蓋文件缺少 owner 或 review_by、審核日期逾期,以及舊政策文件被檢索器選中的情況;示例使用簡單 TF-IDF,並可替換成項目實際使用的檢索器。腳本不會識別兩份有效文件正文中的矛盾。
If you've wired a support assistant to a knowledge base, you've probably tested whether it retrieves something. The harder question is whether it retrieves the current thing.
A real example of the stakes: in Moffatt v. Air Canada (2024 BCCRT 149), a British Columbia tribunal found the airline responsible after its website chatbot told a customer they could claim a bereavement fare after travel, while the airline's own bereavement page said they couldn't. The tribunal wrote that "it makes no difference whether the information comes from a static page or a chatbot." The decision doesn't say how that chatbot worked, so I'm not claiming it was a retrieval bug. But "two docs disagree and the bot picks the wrong one" is a failure mode every RAG builder should test for.
This post builds a small, dependency-free check you can run in CI:
- Freshness: every live doc has an owner, an effective date and a review-by date, and none is overdue.
- Retirement: retired docs are explicitly superseded by a live doc.
- Retrieval regression: a set of "golden questions" must retrieve the doc you expect.
The knowledge base format
Plain markdown with front matter. The convention is the point; the parser is trivial.
---
title: Refund policy
owner: billing-ops
effective: 2026-03-01
review_by: 2026-09-01
supersedes: refunds-2025
---
Refunds are available within 30 days of purchase. Refund requests must be submitted before the service is used.
The old version stays in the repo for history but is marked retired:
---
title: Refund policy (2025)
owner: billing-ops
effective: 2025-01-01
review_by: 2026-01-01
status: retired
---
Refunds are available within 60 days of purchase, including after the service has been used.
And one doc somebody forgot to give metadata:
---
title: Shipping times
effective: 2026-02-01
---
Standard shipping takes 3 to 5 business days within Canada.
Golden questions
Write these the way customers actually phrase things. Transcripts and ticket subjects are the best source.
question,expected_doc
How many days do I have to ask for a refund?,refunds
Can I get my money back after I already used the service?,refunds
When is phone support open?,hours
How long does standard shipping take?,shipping
The checker
The retriever here is a tiny TF-IDF scorer so the example runs anywhere. In your project, replace Index.search with a call to your real retriever (vector store, hybrid search, whatever you use) and keep the rest.
"""kbcheck.py - freshness and retrieval regression checks for a support knowledge base.
Stdlib only. Usage: python kbcheck.py kb/ golden.csv --today 2026-11-09
"""
import argparse, csv, datetime as dt, math, pathlib, re, sys
from collections import Counter
REQUIRED = ("title", "owner", "effective", "review_by")
def parse(path):
text = path.read_text(encoding="utf-8")
meta, body = {}, text
m = re.match(r"^---\n(.*?)\n---\n(.*)$", text, re.S)
if m:
for line in m.group(1).splitlines():
if ":" in line:
k, v = line.split(":", 1)
meta[k.strip()] = v.strip()
body = m.group(2)
return {"id": path.stem, "meta": meta, "body": body.strip()}
def load(kb_dir):
return [parse(p) for p in sorted(pathlib.Path(kb_dir).glob("*.md"))]
def freshness(docs, today):
problems = []
for d in docs:
meta = d["meta"]
if meta.get("status") == "retired":
continue
missing = [k for k in REQUIRED if not meta.get(k)]
if missing:
problems.append((d["id"], "missing metadata: " + ", ".join(missing)))
rb = meta.get("review_by")
if rb and dt.date.fromisoformat(rb) < today:
problems.append((d["id"], f"review overdue since {rb} (owner: {meta.get('owner', '?')})"))
return problems
TOKEN = re.compile(r"[a-z0-9]+")
STOP = set("a an the to of and or is are do i my can how when what for in on be by after before with".split())
def tokens(s):
return [t for t in TOKEN.findall(s.lower()) if t not in STOP]
class Index:
"""Tiny TF-IDF retriever over live (non-retired) docs. Swap in your real retriever."""
def __init__(self, docs):
self.docs = [d for d in docs if d["meta"].get("status") != "retired"]
self.tf = [Counter(tokens(d["meta"].get("title", "") + " " + d["body"])) for d in self.docs]
df = Counter(t for tf in self.tf for t in tf)
n = len(self.docs)
self.idf = {t: math.log((n + 1) / (c + 1)) + 1 for t, c in df.items()}
def search(self, q, k=1):
qt = tokens(q)
scores = [sum(tf[t] * self.idf.get(t, 0) for t in qt) for tf in self.tf]
ranked = sorted(zip(scores, (d["id"] for d in self.docs)), reverse=True)
return [doc_id for s, doc_id in ranked[:k] if s > 0]
def regression(index, golden_csv, k):
failures = []
with open(golden_csv, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
hits = index.search(row["question"], k)
if row["expected_doc"] not in hits:
failures.append((row["question"], row["expected_doc"], hits))
return failures
def retired_leaks(docs):
"""Flag retired docs that a live doc does not explicitly supersede."""
live_supersedes = {d["meta"].get("supersedes") for d in docs if d["meta"].get("status") != "retired"}
return [d["id"] for d in docs if d["meta"].get("status") == "retired" and d["id"] not in live_supersedes]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("kb_dir"); ap.add_argument("golden")
ap.add_argument("--today", default=dt.date.today().isoformat())
ap.add_argument("-k", type=int, default=1)
a = ap.parse_args()
docs = load(a.kb_dir)
today = dt.date.fromisoformat(a.today)
fresh = freshness(docs, today)
fails = regression(Index(docs), a.golden, a.k)
leaks = retired_leaks(docs)
for doc_id, msg in fresh:
print(f"FRESHNESS {doc_id}: {msg}")
for doc_id in leaks:
print(f"RETIRED {doc_id}: retired but no live doc declares 'supersedes: {doc_id}'")
for q, exp, hits in fails:
print(f"RETRIEVAL '{q}' expected {exp}, got {hits or 'nothing'}")
print(f"{len(docs)} docs, {len(fresh)} freshness issues, {len(fails)} retrieval failures")
sys.exit(1 if (fresh or fails or leaks) else 0)
if __name__ == "__main__":
main()
Running it
$ python kbcheck.py kb golden.csv --today 2026-11-09
FRESHNESS refunds: review overdue since 2026-09-01 (owner: billing-ops)
FRESHNESS shipping: missing metadata: owner, review_by
4 docs, 2 freshness issues, 0 retrieval failures
Exit code is 1, so CI fails and the owners get a nudge.
Now the interesting case. Remove the status: retired line from refunds-2025.md, as if someone restored an old article, and rerun:
FRESHNESS refunds-2025: review overdue since 2026-01-01 (owner: billing-ops)
FRESHNESS refunds: review overdue since 2026-09-01 (owner: billing-ops)
FRESHNESS shipping: missing metadata: owner, review_by
RETRIEVAL 'Can I get my money back after I already used the service?' expected refunds, got ['refunds-2025']
4 docs, 3 freshness issues, 1 retrieval failures
The old 60-day "even after use" policy wins retrieval for exactly the question where the answer changed. That's the bug you want caught in CI, not in a customer conversation.
Design notes
- Filter retired docs before retrieval, not after. If retired docs are in the index at all, a ranking change can surface them.
- Make the expected doc, not the expected text, the assertion. Answer wording changes; the source of truth shouldn't. If you also check generated answers, assert on a few must-contain facts (like "30 days").
-
Use
-kto match your real context window. If your assistant receives the top 3 chunks, test with-k 3, and consider also failing when a retired or conflicting doc appears anywhere in those 3. -
Freshness is a people problem with a machine reminder. The script can tell you a review is overdue. It can't decide the policy. Route failures to the
ownerfield. - Grow the golden set from production. Every time a human corrects the assistant, add that question.
Limitations
The TF-IDF retriever is deliberately naive and exists only to make the example self-contained. The front-matter parser handles simple key: value lines only; use a YAML library if your docs need more. Nothing here detects two live docs that contradict each other in free text. For that, the practical first step is the supersedes convention plus a rule that each policy has exactly one owner.
This article was created with the help of AI and reviewed by a human; the code was run and its output pasted unedited. Source for the case: the official decision text, Moffatt v. Air Canada, 2024 BCCRT 149 (decisions.civilresolutionbc.ca).
來源:DEV Community · dev.to