Knowledge and retrieval
Step 6 of 14. Store Assist should answer from approved manuals, not from memory. This step covers how retrieval works, how to build and refresh the index, how to delete from it, and when to skip it for live data.
Knowledge and retrieval in 60 seconds
- What: retrieval finds approved passages for each question and hands them to the model as evidence, so answers rest on current documents.
- Build: split documents into chunks, attach metadata and access rules, embed them, and search with meaning and keywords together.
- Keep fresh: drive the index from change events, make every update safe to repeat, and run a reconciliation job for what the events missed.
- Delete properly: a withdrawn document must leave chunks, derived data and caches, and you should be able to prove it did.
- Right tool: use the index for knowledge, live services for facts that change by the minute, and both together when a question needs each.
The problem it solves
A language model knows nothing about Acme Retail's current procedures. It has never read the scanner sync guide or this week's till software notes. Left alone, it fills the gaps with plausible text, and for a colleague with a queue at the till, plausible is not good enough.
Retrieval-augmented generation, usually shortened to RAG, closes that gap. The application looks up evidence from a trusted knowledge source at question time and puts it in front of the model. The model is asked to answer from that evidence and to say so when the evidence does not cover the question.
How a retrieval request flows
Take the question "Why won't my handheld scanner sync since this morning's update?" The pipeline has eight stages, and each one can fail on its own.
- Read the question. Work out what is being asked, and pull in only the earlier turns that matter to it.
- Shape the query. Tidy the wording or rewrite it so that it matches how the manuals are written. A colleague says "won't sync"; the guide says "device registration failure".
- Find candidates. Search the index of approved scanner guides, store procedures and help articles for a generous shortlist, perhaps 20 passages.
- Apply access rules. Drop anything this colleague's role and store may not read. A regional store closure plan can be a perfect semantic match and still be off limits.
- Rank. Reorder the shortlist so that passages which are relevant, current and suited to the device type come first.
- Assemble the context. Keep a small set of excerpts, say three, each carrying an identifier and a link back to its source.
- Generate. Ask the model to answer only from those excerpts and to admit when they are not enough.
- Return with sources. Show where the answer came from so the colleague can check the steps against the original guide.
Retrieval improves the odds but guarantees nothing: the wrong guide can come back, the right guide can be stale, and the model can misread a good passage. Evaluate the whole pipeline. See simple RAG for the basic shape and corrective RAG for patterns that check what came back.
Building the index
Manuals and procedures are too long and too uneven to search as single blobs. The usual remedy is to cut them into chunks. Each chunk is stored with its text plus metadata that you will rely on later for filtering, citation and cleanup.
- Origin: the source document and the section the chunk came from.
- Version: which revision of the document the text belongs to.
- Updated at: when the source last changed.
- Owner: the team accountable for the content.
- Access rules: who may read it, expressed in the same terms your identity layer uses. See Step 4: Identity, access and limits.
- Language and type: for example quick card, full procedure or policy.
An embedding model turns each chunk into a list of numbers, called a vector, positioned so that passages with similar meaning sit close together. A vector search service stores those vectors. At question time the query is embedded the same way and the nearest chunks are returned. This is semantic search, and it finds the right guide even when the colleague uses different words from the author.
Search by meaning and by exact term
Meaning alone misses things that must match exactly. A question that quotes SKU 448812, the error code SYNC-31 or incident INC-5521 depends on those tokens appearing in the result. Embeddings blur them. Keyword search, which matches literal terms, handles them well but stumbles on paraphrase.
Production systems therefore run both and merge the two result lists, then pass the merged list to a ranking stage. A common merge is reciprocal rank fusion, which rewards passages that appear high in either list without needing the two scores to be comparable. A reranker model can then read the query with each candidate and reorder them more carefully. More detail sits in vector search and chunking and advanced RAG.
Chunk size is a decision to test
Tiny chunks lose the surrounding steps, so "restart the device" arrives without the warning before it. Huge chunks waste the prompt budget and bury useful lines. The right size follows the shape of the material.
- Numbered procedures such as scanner sync steps: keep each one whole, at around 150 tokens, with its title attached.
- Long policies: split by section and prefix each chunk with its heading path.
- Tables of codes: one chunk per row group, with the header row repeated.
- Supplier manuals: section chunks flagged as third-party, since they are untrusted.
Start with a sensible default, then test with real questions. Check whether the right source appears in the top results, whether the passage has enough context to be understood, and whether the final answer reflects it faithfully.
Keeping the index in step with the source
Freshness is where retrieval most often fails in production. The scanner sync procedure changed on Monday. If Tuesday's answers still give the old steps, the assistant is fluent, confident and wrong, and nothing in the logs looks broken.
Rebuilding the whole index on a timer is fine for a few hundred documents. It is wasteful for thousands and always leaves a window in which the index is stale. The approach that scales is to update only what changed, triggered by notifications from the source.
- An editor publishes a revised sync guide in the content system.
- The source announces the edit with a notification, or the edit is spotted in its change log.
- A worker process picks the message up.
- It reads the newest revision of the document from the source.
- It swaps in the new chunks and creates fresh embeddings only for passages whose text differs.
- The index stamps the document with its new version and update time.
- A monitor confirms that the update landed and measures how long it took.
The trigger may be change data capture, a webhook, an event stream or a scheduled scan, whichever the source supports. See change data capture and pub/sub. Whichever you use, events can arrive twice, arrive out of order or never arrive. Three habits keep the index trustworthy.
- Make updates idempotent. Applying the same event twice must leave the same result. Key each write on document identifier plus version, and ignore any event whose version is not newer than what is stored. See idempotency.
- Reconcile on a schedule. A nightly job lists every document with its version in the source and in the index, then repairs differences. It is the safety net for lost events.
- Watch lag. Track the gap between a source edit and its appearance in the index, and alert when it exceeds the target.
Deleting is part of the design
Withdrawing a document from the content system does not remove it from everywhere it has travelled. Suppose a product-recall notice is withdrawn because it was issued in error. Its chunks may sit in the index, its text may live in derived data such as summaries or evaluation sets, and answers built from it may sit in caches. Any of those can put the withdrawn text back in front of a colleague.
A deletion workflow should therefore cover three places: the indexed chunks, any derived data, and every cache that could hold an answer built from the document. It should follow the organisation's retention and deletion policy, and it should produce a record showing each place was cleared. Step 7: Semantic caching explains how cached answers are tied to their sources so that this last part can be done.
Knowledge or live data?
An index is a copy, and copies lag. It suits explanatory material: manuals, policies, how-to guides. It does not suit facts that change by the minute. When a colleague asks "How many units of SKU 448812 are in the stockroom?" or "What is the status of incident INC-5521?", the right move is to call the authoritative inventory or ticketing service, not to search an index that may be minutes behind.
- Use retrieval for documentation, procedures and policies.
- Use live service calls for stock, incident status, order state and any other fact with an authoritative system behind it.
- Use both when a question needs background and a current fact.
Scanner help is the combined case: the guide comes from retrieval, this scanner's registration state from a device-management lookup, and permissions are checked separately on each source.
Store Assist, worked through
Acme's knowledge base holds roughly 6,000 documents. Cut into chunks of about 150 to 400 tokens, that is around 60,000 chunks. A full reindex is cheap in money but slow, so keep it for planned changes. Daily edits touch perhaps 40 documents, which is why incremental indexing wins.
- Request volume: 36,000 requests a day, of which about 60 percent are procedure questions that need retrieval, so roughly 21,600 searches a day, or 0.6 a second on average and 6 a second at the 10x peak.
- Context budget: about 500 of the 1,000 input tokens are retrieved excerpts, three chunks of roughly 160 tokens.
- Shortlist and rerank: 20 candidates from the combined search, reranked to 3.
- Freshness target: an edited procedure is searchable within 15 minutes at the 95th percentile, and a withdrawn recall notice is gone from the index within 5 minutes.
- Live data: SKU 448812 stock and INC-5521 status come from the inventory and ticketing services, called with the colleague's own identity, never from the index.
from dataclasses import dataclass
MAX_CHUNK_TOKENS = 400 # hard cap on a single chunk
MAX_BATCH_EMBED = 64 # embeddings requested per call
MAX_ATTEMPTS = 5 # redeliveries before the event goes to a dead-letter queue
@dataclass
class ChangeEvent:
doc_id: str
version: int
kind: str # "upsert" or "delete"
def handle(event: ChangeEvent, index, source, embedder, log):
stored = index.get_version(event.doc_id) # None if never indexed
# Idempotency: an old or repeated event changes nothing.
if stored is not None and event.version <= stored.version:
log.info("skip", doc=event.doc_id, version=event.version)
return
if event.kind == "delete":
# A tombstone keeps the id and version so a late, older upsert cannot resurrect it.
index.delete_chunks(event.doc_id)
index.write_tombstone(event.doc_id, event.version)
caches.invalidate_by_source(event.doc_id) # placeholder: purge dependent answers
return
doc = source.fetch(event.doc_id, event.version) # always read the named version
chunks = split_into_chunks(doc, max_tokens=MAX_CHUNK_TOKENS)
attach_metadata(chunks, doc) # version, updated_at, owner, access rules
# Embed only chunks whose text hash changed; reuse the rest.
changed = [c for c in chunks if index.text_hash(c.id) != c.hash]
for start in range(0, len(changed), MAX_BATCH_EMBED):
batch = changed[start:start + MAX_BATCH_EMBED]
for chunk, vector in zip(batch, embedder.embed([c.text for c in batch])):
chunk.vector = vector
# One atomic swap, so a reader never sees half old and half new.
index.replace_document(event.doc_id, chunks, version=event.version)
metrics.record_lag(doc.updated_at) # placeholder: freshness monitor
The helpers and the index, source and embedder objects are placeholders. Copy the version check, tombstone, hash-based re-embedding and atomic replacement.
Design decisions
- Filter placement: apply access rules inside the search as a pre-filter. Post-filtering can leave the top results empty when the best passages are off limits.
- Index versioning: build a new index alongside the live one, check it against the golden questions, then switch traffic with a pointer change. Keep the old one for a day so you can switch back.
- Embedding model upgrades: vectors from different models are not comparable, so an upgrade means a full blue-green reindex.
- Freshness objective: set it per content class, from minutes for recall notices to a day for archived policy.
- Citations: return document identifier, section and version with every excerpt in a fixed format, so colleagues can open the source and audits can name the exact text used.
- Untrusted sources: mark third-party content, such as supplier manuals, and pass it to the model as data with provenance, never as instructions. See Step 5: Guardrails and privacy.
Measuring it
- Recall at k: for each labelled question, whether the correct passage is among the top k results. Track k of 5 and 20. Low recall at 20 means search is failing, low recall at 5 means ranking is.
- Mean reciprocal rank (MRR): the average of one over the position of the first correct passage.
- Groundedness: the share of answer claims supported by the supplied excerpts. The target for Store Assist is at least 95 percent.
- Freshness lag: time from source edit to searchable, at the median and 95th percentile.
- Deletion latency: time from withdrawal to absence from index and caches, checked by a probe query.
When to use it, and how much of it
| Question type | Source | Notes |
|---|---|---|
| How do I fix scanner sync? | Retrieval over approved guides | The main use case. Cite the guide and its version. |
| How many units of SKU 448812 are in the stockroom? | Live inventory service | Authoritative and current. Do not index stock levels. |
| Why is my scanner failing to sync, and is it registered? | Both | Guide from the index, device state from a live lookup. |
| Fewer than a hundred short, stable documents | Paste into the prompt | A full index adds moving parts without a gain. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Quality | Grounded answers cite real documents. Bad chunking or stale content still produces wrong ones. | Evaluate retrieval separately from generation so you know which half to fix. |
| Latency | Search, access filtering and reranking add roughly 100 to 400 ms before the model starts. | Run searches in parallel, cap the shortlist, and cache retrieval results where safe. |
| Cost | Retrieved text adds about 500 input tokens per request. Embedding and reindexing add smaller recurring costs. | Keep to a few excerpts. |
| Operations | An index is a second data system to run. | Assign an owner and rehearse a rebuild. |
What this means for your role
Common mistakes
Step checklist
- Every chunk carries origin, version, updated time, owner, access rules and type.
- Search combines meaning and keyword matching, with a ranking stage that has been tested against labelled questions.
- Access rules are applied as a pre-filter, and a test proves that a restricted document never reaches an unauthorised colleague.
- Chunk size has been tested per source type, with recall and MRR recorded.
- Index updates are event driven, idempotent and version checked, with a dead-letter path for failures.
- A nightly reconciliation job runs and reports drift.
- Freshness lag is measured, with an alert at the agreed objective.
- A deletion drill removes a test document from the index, derived data and caches within the target time.
- Live facts come from authoritative services, and a routing test shows that stock and incident questions skip the index.
- Blue-green reindexing has been rehearsed, including rollback.
Further reading
- Simple RAG: the basic retrieve-then-generate pattern.
- Advanced RAG: query rewriting, fusion and reranking in more depth.
- Corrective RAG: checking retrieved evidence before using it.
- Vector search and chunking: how indexes and chunk strategies behave.
- Retrieval cache: reusing search results safely.
- Change data capture and pub/sub: event sources for incremental indexing.
Retrieval gives Store Assist current, citable knowledge, and live lookups give it current facts. Together they keep answers tied to what Acme actually says and actually holds. With that in place, repeated questions become the next cost to tackle. Next: Step 7: Semantic caching.