Knowledge Management and Document Agents
An assistant is only as dependable as the pages it reads and the checks on what it extracts.
Knowledge agents answer from an organization's content; document agents turn files into checked data and actions. Both need owned, current sources, permissions that follow the user, citations or traceable fields, validation in code, a review queue for doubt and a feedback loop that repairs the content itself.
What you will learn: how to organize knowledge for agents, keep access rights, extract document data with validation, set review thresholds from evidence and maintain quality over time.
Prerequisites: RAG Explained and Agentic RAG and Document Ingestion, Parsing and Chunking.
The example runs in November 2026 with Python 3.13 and only the standard library. The invoices, confidence values and thresholds are invented; the program does not read real files or call a model.
Knowledge and documents
| Aspect | Knowledge agent | Document agent |
|---|---|---|
| Input | A question | A file or stream of files |
| Output | Answer with sources | Structured fields, classification, next step |
| Main risk | Wrong, outdated or unauthorized answer | Silently wrong data |
| Main check | Support in cited passages | Validation rules and review |
| Typical use | Policy, product and engineering questions | Invoices, forms, claims, contracts |
Build a RAG Knowledge Assistant builds a small assistant. This page looks at running both kinds across an organization.
Content comes first
If three pages describe three leave policies, retrieval will find one of them. Before adding an agent, establish basics.
- Owner for each collection and important page.
- Status: draft, approved, superseded.
- Dates: effective, reviewed, expiry.
- Scope: region, product, audience, version.
- Authority: which source wins when they conflict.
- Retention: what must be kept or removed.
Search logs showing unanswered questions are a useful list of content to write.
The document pipeline
| Stage | Watch for |
|---|---|
| Receive | Malware, duplicates, wrong channel, missing pages |
| Read | Rotated scans, handwriting, tables, hidden text |
| Classify | Mixed bundles, unknown types |
| Extract | Values from the wrong column or party |
| Validate | Totals, formats, dates, master data |
| Route | Clear reasons and no lost items |
Count every document in and out. A file that fails quietly is worse than one that reaches a reviewer.
Validation beats confidence
A confidence score says how sure an extraction component is, in its own terms. It may be badly calibrated, and a confidently misread digit passes a threshold. Rules that use independent facts catch more.
| Check type | Example |
|---|---|
| Arithmetic | Lines plus tax equal total |
| Format | Identifier matches expected pattern |
| Plausibility | Date not in the future; amount within range |
| Cross-reference | Supplier and order exist and agree |
| Consistency | Same name and number across pages |
| Duplicate | Same supplier, number or amount seen before |
Accept or review
The program combines field confidence thresholds with rules and states why each item needs review.
"""Validate extracted document fields and route uncertain ones to people."""
import re
from datetime import date
from decimal import Decimal, InvalidOperation
THRESHOLD = {"invoice_no": 0.90, "date": 0.90, "net": 0.95, "tax": 0.95, "total": 0.95}
def money(text):
return Decimal(text.replace(",", ""))
def check(doc):
problems = []
for field, minimum in THRESHOLD.items():
if field not in doc:
problems.append(f"{field} missing")
elif doc[field][1] < minimum:
problems.append(f"{field} low confidence {doc[field][1]:.2f}")
if problems and any("missing" in p for p in problems):
return problems
try:
net, tax, total = (money(doc[f][0]) for f in ("net", "tax", "total"))
if net + tax != total:
problems.append(f"totals do not add up: {net} + {tax} != {total}")
except InvalidOperation:
problems.append("amount is not a number")
try:
if date.fromisoformat(doc["date"][0]) > date(2026, 11, 28):
problems.append("date is in the future")
except ValueError:
problems.append("date not understood")
if not re.fullmatch(r"[A-Z]{2}-\d{4}", doc["invoice_no"][0]):
problems.append("invoice number has unexpected form")
return problems
def doc(no, day, net, tax, total, confidence=None):
confidence = confidence or {}
values = dict(invoice_no=no, date=day, net=net, tax=tax, total=total)
return {k: (v, confidence.get(k, 0.99)) for k, v in values.items()}
documents = {
"scan-1": doc("AB-1001", "2026-11-02", "1,000.00", "80.00", "1,080.00"),
"scan-2": doc("AB-1002", "2026-11-03", "500.00", "40.00", "590.00"),
"scan-3": doc("AB-1003", "2026-11-04", "75.00", "6.00", "81.00", {"total": 0.62}),
"scan-4": doc("A8-I004", "2027-11-05", "20.00", "1.60", "21.60"),
}
accepted = 0
for name, d in documents.items():
problems = check(d)
accepted += not problems
print(name, "accept" if not problems else "review: " + "; ".join(problems))
print(f"straight through: {accepted} of {len(documents)}")
Output:
scan-1 accept
scan-2 review: totals do not add up: 500.00 + 40.00 != 590.00
scan-3 review: total low confidence 0.62
scan-4 review: date is in the future; invoice number has unexpected form
straight through: 1 of 4
One of four passes. The second invoice has confident fields that fail arithmetic, which a confidence threshold alone would have accepted. The third is arithmetically fine but the total was read uncertainly. The fourth fails on date and number format. Passing these checks does not prove correctness: two matching misreadings, a forged document or a rule that is too loose can slip through. Sample accepted items and compare them with the source.
Setting thresholds from evidence
- Label a representative set, including poor scans and rare layouts.
- For each field, measure accuracy at different confidence levels.
- Choose thresholds by the cost of an error against the cost of review.
- Use stricter values for amounts, bank details, identifiers and dates with legal effect.
- Recheck when document sources, models or reading software change.
Do not copy thresholds from an example, including this one.
A review queue people can use
Show the page image beside the field, highlight its location, state the failed check, order by deadline and value and record the correction. Avoid pre-ticked approval. Insert known test errors occasionally, with staff awareness, to check that review works. Feed corrections back into rules, examples and supplier guidance (LLM Judges, Human Review and Ratings).
Permissions follow the user
An assistant must not become a way around access control. Carry source permissions into the index, filter before retrieval, apply current group membership, remove deleted content promptly and keep caches and memory within the same boundaries. Test with accounts that should see nothing. Making content searchable often reveals files shared far too widely, so review sharing before launch (RAG Security, Freshness and Cost).
Trustworthy answers
- Cite the specific passage and version, with a link the user can open.
- Say when sources conflict and name both.
- Abstain when support is missing, and offer a person or owner.
- Quote exactly where wording matters, and verify quotations in code.
- Show effective dates for rules and prices.
A citation proves that something was retrieved, not that it supports the sentence. Evaluate support separately (RAG Evaluation, Grounding and Debugging).
When search is not enough
Questions that cross many records, such as which contracts depend on a given supplier, need structured data or relationships. Extract key facts into tables or a knowledge graph with provenance for each fact, and let the agent query them (Knowledge Graphs and Ontologies, GraphRAG and Hybrid Graph Retrieval). Keep inferred links labeled and reviewable.
Capturing knowledge
Agents can draft articles from resolved cases or meetings. Unreviewed drafts that enter the index create a loop in which generated text becomes evidence for later answers. Keep drafts out of authoritative collections until an owner approves, mark origin and date and avoid recording private remarks or personal details that people did not expect to be published.
Hostile and sensitive documents
Any incoming file can carry malicious code or instructions for a model, including invisible text. Scan files, process them in isolation, treat extracted text as data and never allow it to change tools, recipients or payment details (Supply Chain and Retrieval Poisoning). Detect sensitive categories, restrict them, redact where appropriate and verify that redaction removes underlying text and metadata, not only the visible layer.
Records and retention
Indexes, extracted fields, previews, logs and evaluation sets are all copies. Give each a retention rule, honor legal holds, handle deletion requests across all of them and keep the original with a checksum so that later questions can be answered. Record which software and model version produced each extracted value (Data Contracts, Access and Retention).
Measures
| Measure | Meaning |
|---|---|
| Field accuracy | Correct values, by field and document type |
| False acceptance | Wrong items that passed without review |
| Straight-through rate | Share needing no review, read beside false acceptance |
| Review time and age | Cost and backlog |
| Answer support | Claims backed by cited text |
| Correct abstention | Declines when it should |
| Stale content | Pages past review date that are still retrieved |
| Access violations | Target is none; investigate every one |
Rolling out
- Choose one collection or document type with an owner.
- Clean content and fix permissions.
- Build a labeled test set and baseline.
- Review every item at first and measure.
- Allow straight-through processing only for proven cases with sampling.
- Add collections one at a time and rerun tests.
- Keep a manual route and a reprocessing method for found errors.
A supplier changes its invoice layout, and the net amount is now read as the total. Confidence stays high. A check that net plus tax equals total flags every case on the first day, and a per-supplier error chart shows where to look. This scenario is invented.
Preparing documents for retrieval
How content is split affects what can be found. Keep headings with their text, keep table rows with column names, attach the document title, version and effective date to every piece and avoid separating a rule from its exceptions. Index a parent section alongside small passages so the agent can read around a hit. When a page changes, replace all its pieces together; mixed old and new fragments produce answers that never existed in any version.
Matching method to document type
| Document type | Practical method |
|---|---|
| Structured electronic invoice | Parse the data directly; no model needed for the fields |
| Fixed form | Layout template or form extraction with validation |
| Varied business documents | Model extraction against a schema with source locations |
| Long contracts and reports | Section-aware retrieval and clause-level extraction |
| Handwriting and poor scans | Specialist reading plus a higher review rate |
| Mixed bundles | Split and classify first; check page order and completeness |
Where a trading partner can send structured data, asking for it often beats improving extraction.
A schema for extraction
Define each field with a type, meaning, allowed values and what to return when absent. Ask for the page and the supporting text for each value, and confirm in code that the text appears there. Distinguish "not present", "unreadable" and "zero". Version the schema, and when it changes, decide whether earlier documents need reprocessing (Message Roles, Structured Output and Function Calling).
Keeping knowledge alive
Launch is the easy part. Give each collection a review rhythm and a report its owner will read: unanswered questions, answers rated wrong, conflicting pages, expired pages still retrieved and documents never used. Allow users to flag a source from inside an answer. Archive rather than hoard, because every outdated page is a candidate for a confident wrong answer. Recognize content work as real work in plans and budgets (Metadata, Indexing, Quality and Lineage).
Cost and capacity
Large files, repeated reprocessing and long contexts drive cost. Process each version once and cache results by checksum, send only the relevant pages to a model, use ordinary parsers where they suffice and plan for month-end peaks. Track cost per accepted document, including review time, and compare it with the previous process.
When wrong data has spread
Sooner or later a rule is too loose or a layout changes and wrong values reach other systems. Stop straight-through processing for the affected type, identify every item handled under the same release, reprocess from the stored originals, correct downstream records through their normal processes and tell the owners what changed. Add the failing documents to the test set. This depends on keeping originals, versions and the link from each posted value to its source.
Designing the answer screen
People judge an answer by what sits around it. Put the direct answer first, then the source title, effective date and a link to the exact passage. Mark where sources disagree. Offer a visible way to say the answer is wrong, and to reach the content owner. Avoid decorative confidence meters that users cannot interpret. When the system declines, say what it searched and suggest where else to look, so the person is not left at a dead end (Agent UX, Trust and Onboarding).
Controlling intake
Define who may submit which documents and through which channel. A shared mailbox that accepts anything from anyone will receive spam, duplicates, personal messages and attacks. Acknowledge receipt, reject unsupported types with a clear reason and watch for sudden changes in volume or sender. Keep the original message with the file, since it often explains what the sender intended.
Common mistakes
| Mistake | Consequence | Instead |
|---|---|---|
| Indexing everything at once | Conflicts, leaks and noise | Owned collections, step by step |
| Trusting confidence scores alone | Confident errors pass | Add independent checks |
| Permissions applied after generation | Information leaks | Filter before retrieval |
| No document counts | Silent loss | Reconcile in and out |
| Generated drafts treated as truth | Errors reinforce themselves | Approve before indexing |
| Reporting only straight-through rate | Quality problems hidden | Report false acceptance too |
Checklist
- Sources have owners, status, dates and scope.
- Permissions and deletions propagate to every copy.
- Answers cite passages and can abstain.
- Extracted values pass independent validation.
- Thresholds come from labeled evidence.
- Reviewers see source and reason side by side.
- Documents are counted through the whole pipeline.
- Accepted items are sampled and errors can be reprocessed.
Frequently asked questions
Can a long-context model replace the index?
Sometimes for small, stable sets. You still need permissions, current versions, citations and cost control, which retrieval often handles better.
Is optical character recognition still needed?
Some models read page images directly, while many pipelines still use dedicated text and layout extraction. Compare both on your own documents.
What straight-through rate should we expect?
It depends on document variety, quality and tolerance for error. Measure on your own labeled set rather than relying on a general figure.
Who fixes a wrong answer?
Route it to the content owner when the source is wrong, and to the builder when retrieval or generation failed. Track both to closure.
References
- W3C SKOS reference for knowledge organization
- W3C PROV overview on provenance
- OWASP GenAI Security Project
Where to go next
Knowledge Ingestion and Real-Time Pipelines
Keep content flowing and fresh.
Multimodal, Vision, Video and Document Agents
Read page images.
Data Agents and AI Data Analysts
Move on to data agents.