如何為網上課程導師建構快取感知檢索,優先確保內容新鮮度
How to Build Cache-Aware Retrieval for an Online Course Tutor — Freshness First
文章提出為網上課程導師建構快取感知檢索的方法,透過文件修訂版本核對及明確的失效政策,避免過時證據進入導師回答。文中提供 TypeScript 範例,分開快取查詢對應的證據 ID,以及取回的區塊文字或嵌入向量,並在使用證據前核對當前修訂版本。範例快取有效期設為 120 秒,作者指出應按查詢重複情況及編輯流程調整;亦建議以失效事件更新版本,並測試倒序事件及大量匯入後的熱門查詢。
Short answer: cache the expensive, stable parts of retrieval, but keep freshness decisions in a small policy layer that can reject a stale result before it reaches the tutor. For an online course tutor, that usually means versioned lesson chunks, a short-lived query-result cache, and an explicit invalidation event when an instructor edits an explanation.
I use the same shape for an internal property-management knowledge bot. Lease clauses and maintenance procedures change at different rates, so one global time-to-live is a trap. The cache is an optimization; the source-of-truth version is the contract.
Start with a freshness contract
Write down what “fresh” means for each document class before choosing a cache. A published lecture transcript might tolerate fifteen minutes of staleness. A changed grading rubric may not tolerate one request. In a property-management bot, an emergency contact list should invalidate immediately, while a general appliance manual can wait for a scheduled refresh.
Give every chunk a stable document ID and a revision number. Include the revision in the retrieval record, and keep the current revision in a metadata store. This avoids trying to infer freshness from wall-clock time alone. Clock skew and delayed workers make timestamp-only rules surprisingly fragile.
Freshness is a product requirement.
Consider a course called “Residential Wiring 101.” The instructor corrects a diagram in lesson 3, then republishes the transcript and quiz explanation as one editorial action. The importer may process those files on separate workers, and the vector index may lag behind the catalog by a few seconds. A query cache keyed only by the learner's words can therefore return the old transcript beside the new quiz explanation. Versioning makes the mismatch visible: each evidence item carries its document revision, and the catalog says which revision is current. During that short indexing window, the retrieval function can return the current items it has and wait for the missing revision, or deliberately return no evidence and let the tutor ask the learner to try again. That decision belongs in a policy you can test. It should not be an accidental side effect of whichever cache client happened to answer first. The property-management equivalent is a lease addendum replacing a paragraph while an older PDF remains searchable; the bot must prefer the current addendum even if the old file is more popular.
The retrieval path can then be described plainly: normalize the learner query, check a bounded answer cache, run hybrid retrieval on a miss, filter candidates against current revisions, rerank, and cache the resulting evidence IDs with a short expiry. The model response itself can have a separate cache policy because personalization and conversation context make it less reusable.
How should caching shape retrieval for an online course tutor?
Start with two caches, not one. The first stores query-to-evidence IDs; the second stores fetched chunk text or embeddings. Evidence IDs are cheap to validate against revisions, while a generated answer can silently preserve an outdated misconception. I keep answer caching opt-in for deterministic prompts and disable it for requests that mention “latest,” “today,” an assessment deadline, or a live policy.
Here is a minimal TypeScript sketch. It uses generic interfaces so the same logic can sit over an in-memory cache, Redis, or a database-backed implementation.
type Revision = { documentId: string; revision: number };
type Evidence = Revision & { text: string; score: number };
interface Cache<T> {
get(key: string): Promise<T | undefined>;
set(key: string, value: T, ttlSeconds: number): Promise<void>;
delete(key: string): Promise<void>;
}
interface Index {
search(query: string, limit: number): Promise<Evidence[]>;
}
interface Catalog {
current(documentId: string): Promise<number>;
}
const normalize = (query: string) =>
query.trim().toLowerCase().replace(/\\s+/g, " ");
async function retrieve(
rawQuery: string,
evidenceCache: Cache<Evidence[]>,
index: Index,
catalog: Catalog,
): Promise<Evidence[]> {
const query = normalize(rawQuery);
const key = `evidence:v2:${query}`;
const cached = await evidenceCache.get(key);
if (cached) {
const fresh = await Promise.all(
cached.map(async (item) =>
(await catalog.current(item.documentId)) === item.revision ? item : undefined,
),
);
const valid = fresh.filter((item): item is Evidence => item !== undefined);
if (valid.length === cached.length) return valid;
await evidenceCache.delete(key);
}
const found = await index.search(query, 8);
const current = await Promise.all(
found.map(async (item) =>
(await catalog.current(item.documentId)) === item.revision ? item : undefined,
),
);
const valid = current.filter((item): item is Evidence => item !== undefined);
await evidenceCache.set(key, valid, 120);
return valid;
}
The important decision is the validation step, not the two-minute number. Set that TTL from observed query repetition and your editing workflow. A cache hit that contains one old chunk is not a partial success; it is a miss that should be rebuilt.
Make invalidation an event, not a hope
When an instructor publishes revision 42 of a lesson, emit an event containing the document ID and revision. Consumers update the catalog first, then remove or mark affected evidence entries. A worker can delete exact keys if it maintains a reverse index from document ID to query keys; otherwise, revision validation gives you a bounded safety net while old entries expire. Cache misses hurt when a whole cohort asks the same exam question after a content import, so keep the invalidation event small and let the next request rebuild one key at a time.
Do not invalidate every query whenever any lesson changes. That creates a thundering herd during a content import. Partition keys by course and locale, and warm only the handful of canonical questions used in smoke tests. For the property-management bot, a building-specific policy update should touch that building's namespace, not the entire portfolio.
One awkward case deserves a test: two edits arrive out of order. Reject a catalog update if its revision is lower than the stored revision. I once assumed queue order was enough and spent an afternoon tracing a “random” old answer that was really a late worker.
Measure the misses that matter
Track cache hit rate by course, query shape, and revision age. A single global hit-rate number hides the expensive tail. Also record retrieval latency, embedding or reranking calls, stale-entry rejections, and the percentage of answers whose cited chunks were revised within the session. I don't treat a high hit rate as success if stale-entry rejections are climbing; that usually means the content workflow is publishing faster than the cache policy expects.
Use traces with a request ID that follows normalization, cache lookup, index search, and generation. Sample the query text carefully; student questions can contain personal data. Hashing the normalized key is often enough for aggregation, while retaining a short allowlist of synthetic test queries for debugging.
Test freshness as a property, not a demo. Publish a fixture, retrieve it, publish a new revision, and assert that the next retrieval contains the new revision. Add a negative test for an out-of-order event and a load test for a popular exam question after a bulk import. These tests catch more than tuning another similarity threshold.
The catch is operational complexity. If course material changes hourly, reviewers cannot tolerate eventual invalidation, or every answer is deeply personalized, a query cache may add little value; direct retrieval with aggressive indexing can be easier to reason about. Stick with a simpler uncached path when traffic is low and latency is not a user complaint.
Conversely, a cache-first design suits repeated study questions and read-heavy policy lookup, provided the freshness contract is explicit. It does not replace access control: include tenant, course, role, and locale in the cache key, and enforce authorization again when evidence is fetched. Your mileage may vary with multilingual tokenization and provider-specific embedding behavior, so measure those dimensions before selecting a TTL.
The practical rule is small: cache evidence, version the source, validate on use, and make invalidation observable. That keeps a tutor quick without teaching yesterday's lesson as today's answer.
References
來源:DEV Community · dev.to