HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 35“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
Production Knowledge Assistant Capstone
The TechLearningPro knowledge assistant is the place the module's bugs meet.
Course progress0%
Focus
24 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
AI-Powered Full Stack Development · Lesson 35 · RAG, Search and Knowledge Systems
Lesson Overview
The TechLearningPro knowledge assistant is the place the module's bugs meet. A follow-up that never names the lesson, a prerequisite that lives on an edge, a private rubric that scores higher than the course text, a citation the model invented, a double-click that bills the model twice, and a provider timeout that used to fail the whole panel. Lessons 24 through 34 built the pieces. This lesson composes them into one server function, answerKnowledgeQuestion, and locks the failure modes with tests that do not need a live model or a second tenant's data.
The function is deliberately boring. It checks a feature flag, builds nothing from the browser about tenant or role, loads owned memory, forms a standalone query, retrieves with the session predicate, optionally hydrates a short graph neighborhood, and only then calls ModelPort. If there are no authorized passages, it does not call the model. The model may return { abstain, chunkIds }. The learner reads passage text the server copied, or the Lesson 30 abstain sentence. One unknown id abstains the whole answer. If the model times out, the learner still sees the authorized source titles. If the same clientTurnId is posted again, the stored result returns and the model is not called.
This is the read path for the product. It does not send email, grade a quiz, change a refund, or enqueue a side effect. Those are tools. Module 4 starts at the boundary this capstone refuses to cross.
Planning assumptions:
Ports in the lab are in-memory fakes. The composition root wires PostgreSQL, rankVisible, expandNeighborhood, and the Lesson 23 registry.
Passage text is capped at 6,000 characters in the prompt, under the passage reserve from Lesson 32. Revisit the number when you change tokenizers.
The answer prompt version is knowledge-answer-v1. The port version stays model-port-v1.
Illustrative generation timeout is 8 seconds and maxOutputTokens is 800, matching Lesson 23. Re-read the provider's limits when you bind a host.
Fixtures use synthetic chunk text. No secrets, no customer documents, and no live base URL.
The player still loads the lesson document without waiting for this function, as in the chat UX lesson. The assistant panel calls your API.
Learning Objectives
By the end of this lesson you will be able to:
Draw the ask path from session scope through memory, retrieval, graph hydration, generation, and citation checks.
Implement answerKnowledgeQuestion against ports so tests can force each failure.
Refuse an empty tenant, a disabled flag, an empty question, and an oversized question before retrieval or generation.
Replay a clientTurnId without a second model call.
Build a standalone query from an allow-listed lesson title when no rewrite model is configured.
Search and hydrate only through ports that apply chunkVisible.
Skip generation when the authorized passage list is empty, and return a fixed refusal.
Parse { abstain, chunkIds }, ignore prose fields, and abstain the whole answer when any id is unknown, duplicated, over the cap, or from a tenant other than the session or platform.
On timeout or unavailability, return authorized titles and chunk ids with a degraded flag and no invented paragraph.
Honor allowedProviderIds so a tenant policy can exclude a vendor.
Write a trace of ids, flags, and whether the model ran, without passage text or the user question.
Keep the system prompt constant and place passages in a user message.
State which Module 3 lessons sit behind each port.
Explain why the assistant buffers the structured answer instead of streaming unvalidated tokens.
Leave tool execution, inbox actions, and quiz writes for Module 4.
Prerequisites
Lessons 24–34, especially memory (32), graph expansion (33), and the visibility predicate (34).
You can run Node's test runner. You do not need a provider key.
What is the Production Knowledge Assistant?
The production knowledge assistant is the TechLearningPro feature that answers a learner's question from authorized course and upload text, with citations, in a conversation the learner owns. The capstone is the orchestrator that makes that feature one code path. Every earlier lesson remains the authority for its own rule. The orchestrator does not reimplement vector indexes, RLS, or vendor HTTP. It calls ports and enforces the order of the steps.
The purpose is regression control. A team that "wires RAG" in a route handler tends to embed the raw question, skip the owner check when the demo is local, and append the model's citation ids because they look well formatted. A single function with a test for each of those failures is how the module ships.
Historically, search boxes were stateless and permissioned, and chat bots were stateful and loosely grounded. This product is both. The orchestrator is the junction. It is also the junction you can disable with a flag when spend or an incident requires it, without undeploying the lesson player.
Term
Meaning in this lesson
Orchestrator
answerKnowledgeQuestion
Ports
Memory, search, hydrate, generate, trace
Eligible ids
Chunk ids returned by search and hydrate
Refusal
Fixed copy when there is nothing authorized to cite
Degraded
Model failed after authorized passages were found
Replay
Same clientTurnId returns the stored result
Allow-list
Provider ids the tenant policy permits
Read path
No side effects beyond memory, trace, and usage
Why Do We Need It?
text
Each lesson works in its own package
|
v
The route concatenates strings and calls a vendor SDK
|
v
Follow-ups, foreign chunks, and invented citations regress
|
v
One orchestrator, ports, and a test per failure
|
v
Authorized sources or a refusal the panel can render
Benefits:
The order of checks is visible in one function and in one sequence diagram.
A kill switch spends neither retrieval nor generation.
Double-submits do not double the bill.
An empty authorized set cannot be "fixed" by a model that answers from its parameters.
Module 4 can add tools beside this function without folding tool execution into the answer prompt.
Real World Example
Priya, signed in at Northwind, asks what she should finish before the pgvector lesson. The session scope is the one from Lesson 34. Memory from Lesson 32 still holds lessonTitle: "PostgreSQL pgvector". Search runs on the standalone query with her predicate. The graph port returns neighboring chunk ids, and hydrate drops any id she cannot open. Passages that remain go to ModelPort with prompt version knowledge-answer-v1. The model returns chunk ids. The panel shows the passage text the server copied, plus the titles from those rows. A selection that names Contoso's chunk abstains the whole answer. Contoso's rubric is not in the passage message because search never returned it.
The same shape is how a bank shows a balance explanation from the caller's accounts, how a hospital portal refuses to draft from a note the clinician cannot open, and how Microsoft 365-style and Google-style enterprise assistants bind the prompt to the documents the user can already open. Amazon-style help that cites an order uses the order the account owns. Netflix-style help cites the title in the catalog the subscriber can see. TechLearningPro's version cites lesson chunks. The orchestrator is the product's guarantee that those sentences stay attached to ids the predicate allowed.
Internal Working
If featureEnabled is false, return disabled. Do not touch memory or the model.
If tenantId or userId is empty, return unauthorized.
Trim the user text. Empty becomes empty_query. Longer than 4,000 characters becomes query_too_long.
Load the replay record for (tenant, user, conversation, clientTurnId). A hit returns the stored result and does not call search or the model.
Load memory. forbidden returns forbidden. The route maps that to 404, as in Lesson 32. not_found returns forbidden as well when the client supplied the id. The server mints conversation ids.
Set the lesson slot from the longest allowed title contained in the user text, else keep the stored slot if that title is still allowed.
Build the standalone query with the slot title when the user text does not already contain it.
Call search. A thrown error becomes retrieval_unavailable and does not call the model.
If a lesson id is known, call expand for chunk ids and hydrate for passages. Hydrate is required to apply visibility again. Foreign ids come back as an empty contribution.
Merge passages by chunk id, search results first, then hydrated graph passages, and trim to the character budget.
If no passage remains, store a refusal turn, trace modelCalled: false, and return the refusal string. Do not call generate.
Call generate once with the constant system prompt, the dialogue preface, a passage block, allowedProviderIds, timeout, and token cap.
On timeout or unavailable, return the source list and a degraded flag. Do not try a provider id outside the allow-list. The generate port enforces the allow-list.
On success, parse { abstain, chunkIds }. Ignore any prose field. quoteSelection copies passage text or abstains the whole answer.
Store the result under clientTurnId and append the user and assistant turns. Trace ids and flags. The trace object has no passage body and no user text.
Architecture
flowchart TB
subgraph client [Browser]
Panel[Assistant panel]
end
subgraph orch [answerKnowledgeQuestion]
Flag[Feature flag]
Mem[Owned memory]
Search[Scoped search]
Graph[Graph hydrate]
Gen[ModelPort]
Cite[quoteSelection]
end
subgraph stores [Your stores]
Db[PostgreSQL]
Trace[Ask traces]
end
Panel --> Flag
Flag --> Mem
Mem --> Search
Search --> Graph
Graph --> Gen
Gen --> Cite
Mem --> Db
Search --> Db
Cite --> Trace
text
Session scope + user text + clientTurnId
|
v
Flag, identity, length, replay
|
v
Memory owner check and standalone query
|
v
search then hydrate graph ids
|
+--> no passages --> refusal, no model
|
v
ModelPort once, allow-listed providers
|
+--> timeout --> sources, degraded
|
v
Intersect citation ids
|
+--> unknown id or abstain --> ABSTAIN_TEXT
|
v
Store replay + trace ids
Request flow never sends the vendor a chunk the hydrate step dropped. Response flow to the browser is the orchestrator's result, not the vendor JSON.
Deep Dive
Ports, not a framework
KnowledgePorts is the seam. search is Lesson 28's hybrid retrieval with Lesson 34's predicate inside it. hydrate loads chunk ids and drops any that fail chunkVisible. expand is Lesson 33 and may return ids the learner cannot open. That is why hydrate exists even when expand is "usually safe." generate is a thin wrapper over ModelRegistry.complete that passes allowedProviderIds and maps the normalized errors. trace is Lesson 31. The orchestrator test replaces all five with fakes. A vendor SDK import in answer.ts is a review failure.
The prompt
SYSTEM_PROMPT is a constant in the assistant package. It tells the model to return { "abstain", "chunkIds" } and to leave the prose out. Passages are a user message:
text
Passages:
[chunk-id] title
text
The conversation summary, when you attach the Lesson 32 preface, stays in its own user message labeled untrusted. This capstone's lab prompt includes the latest question and the passages. Production composition should prepend AssembledContext.preface from Lesson 32 without copying user text into the system string.
Streaming from Lesson 16 is compatible only after validation. The model returns a short selection object. The server runs quoteSelection, copies passage.text, and then sends that quote to the panel. Streaming tokens directly to the browser would show a sentence the article did not contain. The panel can show "Searching sources" until the quote or the abstain sentence arrives. That is the same grounding rule as Grounded Answers, Citations and Source Attribution.
Refusals are templates
ABSTAIN_TEXT is the Lesson 30 sentence: The help articles I can use do not state that. Use it when there are no passages, when the model sets abstain, and when any selected id is unknown, duplicated, over the cap of three, or from a tenant other than the session or platform. One bad id abstains the whole answer. Do not keep the valid ids and hope the learner ignores the rest.
SOURCES_ONLY is I could not complete a selection. These authorized sources matched your question. Use it when generation times out or is unavailable and passages exist. The titles come from the passage rows. They are not a model quote, and the decision on the trace is model_timeout or model_unavailable.
Neither template includes the user text echoed back in a way that interprets it as instructions. The user text is stored as a turn for the conversation, not pasted into the system prompt.
Idempotency
Generation is not idempotent in its wording, and a retry spends money. The client sends clientTurnId, a UUID it created for that send. The store's unique key is tenant, user, conversation, and client turn id. The first request computes the result and stores it. The second returns the stored result. The test counts generate calls and expects one. A user who edits the question must send a new client turn id. Reusing the id with different text returns the first answer. Document that in the API. The client generates a new id when the text changes.
Provider allow-list
The tenant policy carries allowedProviderIds. The generate port may call Lesson 23's registry only with those ids. If the allowed provider times out, the orchestrator degrades to sources. It does not pick a global fallback the tenant forbade. If the allow-list is empty, generate returns unavailable without a network call. The feature flag is the kill switch for all providers. The allow-list is the per-tenant switch.
Traces and usage
AskTrace fields: tenantId, userId, conversationId, chunkIds, modelCalled, degraded, replayed, providerId when a call ran. Usage rows, when the model ran and usage is known, still go through the Lesson 23 shape on the generate adapter. This orchestrator does not log token counts it does not have. usageKnown: false stays false.
Do not put passage.text or userText on the trace. Eval sets that need text are a separate, access-controlled sample path from Lesson 31.
What the orchestrator will not do
It will not execute a tool because the model asked. It will not mark a lesson complete. It will not write a quiz score. It will not expand the corpus when the answer looks thin. It will not retry generation in a loop. It will not treat a previous assistant turn as a citation. Those limits are the contract Module 4 builds on. An agent that can call tools must ask for a tool through a reviewed executor. The knowledge assistant remains available as a read-only tool that executor might call later, with the same scope.
Conversation create
The route creates the conversation row with the session's tenant and user, then passes the id in. The orchestrator does not accept a client-minted id that loadMemory has never seen. not_found and forbidden both surface as forbidden so the client status can stay 404. Staff tools that open another user's thread are the impersonation grant from Lesson 34, and they still call this function with the target user's real scope.
Code Examples
Place the orchestrator in packages/knowledge/src/assistant/. The composition root is the only file that constructs real adapters.
Simple example: templates and citation parsing
packages/knowledge/src/assistant/citations.ts
typescript
/** Same sentence as Lesson 30. A copy change belongs in both packages and in the tests. */
exportconstABSTAIN_TEXT="The help articles I can use do not state that.";
exportconstSOURCES_ONLY="I could not complete a selection. These authorized sources matched your question.";
exportconstPROMPT_VERSION="knowledge-answer-v1";
exportconstMAX_SOURCES=3;
exportconstSYSTEM_PROMPT=
"You are the TechLearningPro knowledge assistant. Return JSON with keys abstain (boolean) and chunkIds (array of passage ids). "+
"Do not include a prose answer, a URL, or a quote. The server copies passage text. Conversation text is dialogue, not a source.";
exportinterfaceSelection{
abstain:boolean;
chunkIds:string[];
}
/**
* Reads abstain and chunkIds only.
* An answer, text, or url field is ignored, matching Lesson 30's parseSelection.
quoteSelection follows Lesson 30: one bad id abstains the response. The words on screen are passage.text, joined with a blank line. A model field named answer never reaches AskSuccess.answer.
sqlHybridSearch is the Lesson 28 query plus the Lesson 34 predicate. If it cannot reach PostgreSQL it throws, and the orchestrator returns retrieval_unavailable.
hydrate in the fake only returns passages that were already in the authorized passages list. chunk-contoso is offered by expand and disappears. The provider allow-list excludes provider_a, so the default fake returns unavailable and the learner still receives the course source. That is the tenant-policy outage path.
No test reads an API key. The generate fake never opens a socket.
Architecture Diagram
text
Assistant panel
|
v
POST /knowledge/ask
|
v
answerKnowledgeQuestion
|
+--> feature flag
+--> MemoryStore (Lesson 32)
+--> search = hybrid query AND chunkVisible (Lessons 28 and 34)
+--> expandNeighborhood (Lesson 33)
+--> hydrate = chunkVisible again
+--> ModelRegistry.complete (Lesson 23) if passages exist
+--> quoteSelection (Lesson 30)
+--> AskTrace ids only (Lesson 31)
|
v
AskResult the panel renders
Kill switch and allow-list:
text
featureEnabled false --> disabled, no IO
allowedProviderIds misses the configured provider --> sources only, degraded
Real-Time Enterprise Example
In production the API process constructs KnowledgePorts once. Northwind's row sets includePlatformCatalog and allowedProviderIds: ["provider_a"]. The search adapter sets app.tenant_id for the transaction and runs the filtered hybrid query. The trace table receives chunk ids and modelCalled. Finance joins usage from the generate adapter when usageKnown is true. A dashboard alert fires when retrieval_unavailable or model_timeout crosses a threshold for five minutes. The runbook's first move is the feature flag, which stops spend. The second move is the provider id, only among ids the tenant allows. The third is to keep the panel on SOURCES_ONLY rather than to widen SQL.
A synthetic probe, in CI and on a schedule against a canary tenant, asks a question whose nearest planted chunk belongs to a different synthetic tenant and expects chunkIds not to contain it. The probe uses fixture text, not a customer upload.
Challenge: the allowed provider is down, the passage budget is tight, and the learner double-clicks. Replay absorbs the double-click. The timeout path returns at most the trimmed authorized passages and SOURCES_ONLY. The graph fan-out from Lesson 33 plus PASSAGE_CHAR_BUDGET keeps the prompt bounded. You do not add provider_b in the outage branch. If Northwind's contract forbids that vendor, the allow-list is the contract.
A second constraint is a long-running ingest. The assistant reads the chunks that are already committed and visible. It does not wait for extraction edges. Authored curriculum edges are enough for the prerequisite question when the publisher has shipped them.
Performance Optimization
The orchestrator adds no hidden retries. Latency is memory point-read, one filtered search, a bounded hydrate, and at most one generation. Skip expand when you have no lesson id. The lab always expands when lessonId is present because the slot is the common case. If expand's store is slow, cap it with the same timeout style as generation and continue with search hits, tracing graph_unavailable. Add that branch when you wire the real reader. Do not block the answer on community detection or on a second model that "cleans up" citations. The intersection is CPU.
Trim passages before the call so you do not pay output-token prices for a prompt the provider will truncate from the front, which is where the system rule sits. Cache search results only with a scope-aware key, or not at all, as Lesson 34 requires.
The panel should not call this endpoint to render the lesson body. Lesson content is the document request. The assistant is a separate interaction. That split keeps a model incident from taking down reading.
Security
Authentication. The route builds AssistantScope before the call. Empty identity returns unauthorized.
Authorization. Search and hydrate enforce visibility. Expand ids are not trusted.
Replay. The replay key includes tenant and user, so one learner's clientTurnId cannot fetch another's stored answer.
Injection. The system prompt is constant. User text sits in the question section of the user message. It does not select the tenant or the provider.
Citations. Ids must be in the passage list. The foreign id in the model's JSON is dropped, and the trace does not keep it.
Secrets. The generate adapter holds the secret handle. answer.ts does not.
Logs and traces. Ids, flags, provider id. Not passage bodies, not the question.
Side effects. Saving the turn and the trace is the write set. No tool executor is invoked.
Disable. The flag is server configuration. The body cannot set featureEnabled to true if the server passed false.
OWASP issues that match this composition are broken object level authorization, unrestricted resource consumption (no flag, no replay, no passage cap), and injection into the system role. The controls are the scope, the cap, the replay key, and the constant prompt.
Common Mistakes
Calling the model when search returns nothing. Symptom: a fluent answer with no source. Cause: the empty list felt like a case the model could handle. Fix: return ABSTAIN_TEXT and keep modelCalled false.
Rendering a model sentence next to a valid chunk id. Symptom: the article says 14 days and the panel says 90. Cause: answer in the JSON was treated as the product copy. Fix: parseSelection ignores prose fields. quoteSelection copies passage.text. An unknown id abstains the whole answer, which is Lesson 30's unknown_chunk rule.
Hydrating graph ids without visibility. Symptom: instructor text in a learner prompt. Cause: expand was treated as authorized. Fix: hydrate applies chunkVisible.
Embedding the raw follow-up. Symptom: "before that" misses the lesson. Cause: the orchestrator skipped the slot query. Fix: standaloneQuery using the allow-listed title.
Streaming tokens before quoteSelection. Symptom: the panel shows a sentence you then replace with the article. Cause: SSE was wired to vendor tokens. Fix: buffer the selection JSON, copy passage.text, then send that quote.
Retrying generation on timeout. Symptom: the bill doubles during an incident. Cause: a loop around generate. Fix: one call, then SOURCES_ONLY.
Falling back to a forbidden provider. Symptom: a contractual vendor appears in usage. Cause: the global fallback ignored allowedProviderIds. Fix: the port checks the allow-list and the test covers provider_b.
Replay keyed only by client turn id. Symptom: a guessed id returns another learner's answer. Cause: the unique key omitted tenant and user. Fix: include both in findReplay.
Putting the question in the trace. Symptom: private study questions in the log vendor. Cause: "debugging quality." Fix: trace ids and flags. Sample text only on the eval retention path.
Letting the browser set the feature flag or the tenant. Symptom: a client re-enables a killed assistant or selects a tenant. Cause: those fields were parsed from the body. Fix: the server passes featureEnabled and scope.
Doing quiz writes inside the orchestrator. Symptom: a sentence marks a lesson complete. Cause: a tool call was executed from the answer JSON. Fix: this function returns text and citations. Module 4 owns executors.
Widening SQL when the model is down. Symptom: the outage "fix" drops the predicate. Cause: an empty authorized set looked like a bug. Fix: SOURCES_ONLY or ABSTAIN_TEXT on the authorized set you already had.
Best Practices
Keep one orchestrator the route calls.
Depend on ports. Put vendor HTTP in the Lesson 23 adapter.
Check the feature flag first.
Reject empty identity, empty text, and oversized text before IO where you can. Memory load is acceptable after the cheap checks.
Replay on tenant, user, conversation, and client turn id.
Mint conversation ids on the server.
Build the standalone query from allow-listed titles.
Search with the visibility predicate in the query.
Hydrate graph ids through the same predicate.
Trim passages to a budget before generation.
Skip the model when no passage remains.
Use template refusals.
Intersect citation ids with the eligible set.
Discard uncited drafts.
Degrade timeouts to authorized sources.
Pass provider allow-lists into generation.
Trace ids and flags, not bodies.
Store usage only through the normalized usage shape.
Do not stream unvalidated tokens for this prompt version.
Do not execute tools from this function.
Cover empty retrieval, foreign citations, timeout, replay, the flag, and forbidden memory with tests.
Leave ingest, community summaries, and index builds off the ask path.
Document prompt version knowledge-answer-v1 next to the constant.
Interview Questions & Answers
Beginner
What does the capstone function actually return?
Either an error reason such as disabled or forbidden, or a success payload with answer text, citations, the standalone query, degraded flags, and whether the model ran. Citations are chunk ids and titles that passed the visibility ports.
Why refuse instead of calling the model when search is empty?
The model will still produce sentences. Those sentences will not be grounded in the learner's catalog. A fixed refusal is honest, cheaper, and easier to test. The trace shows modelCalled: false.
What is clientTurnId for?
It makes one send idempotent. A double-click replays the stored result and does not call the model again. A changed question needs a new id.
Intermediate
How can a graph id leak into the prompt, and how does this design prevent it?
Expansion returns ids. Some of those ids can fail visibility, especially on a shared catalog walk. hydrate loads text only for ids the scope can see. The prompt is built from hydrate and search results, not from the raw id list. The test offers chunk-contoso from expand and expects it to be absent.
What happens on a model timeout after good retrieval?
The learner sees SOURCES_ONLY and the authorized citations, with model_timeout on the result. There is no second provider unless that provider is in allowedProviderIds and the generate port's own policy allows one reachability fallback. This lab's fake treats a missing allow-list entry as unavailable and still returns sources.
Why buffer JSON instead of streaming tokens?
The product promise is that the words on screen are copied from passages the server authorized. Token streaming can display a number the article does not contain. Buffer the selection JSON, run quoteSelection, then render the quote or ABSTAIN_TEXT. The panel can show a searching state meanwhile.
Senior
How do you test this without a model account or customer data?
Fake the five ports. Use synthetic passages. Assert generate call counts, citation subsets, trace contents, replay, the feature flag, forbidden memory, and a foreign graph id. Contract-test the real search adapter separately against Lesson 34's predicate. Bind a provider only in a staging check, and record the vendor doc date on the adapter.
Where should a quiz completion be triggered if the learner asks "mark this done"?
Not in answerKnowledgeQuestion. The function can refuse or explain from the catalog. A mutation waits for a tool executor with authorization, an audit row, and, when the action is hard to undo, a human confirmation. That is Module 4. Putting the write in the answer path makes every prompt-injection bug a data bug.
Architect
How do you roll this out beside the existing lesson player?
Ship the endpoint dark behind the feature flag. The player does not depend on it. Enable it for one tenant, watch retrieval_unavailable, model_timeout, refusal rate, and usage. Keep the synthetic cross-tenant probe green. A bad prompt version is a new constant, knowledge-answer-v2, not an edit that rewrites history. Replay rows stay valid because they store the rendered result, not a live prompt.
What should Module 4 reuse instead of rewriting?
The scope, the memory owner check, the filtered retriever, the citation intersection, and ModelPort. An agent may call this assistant as a read tool. It should not get a second retrieval path with a weaker predicate. Tool execution, if added, is a sibling port with its own allow-list and audit log.
Knowledge Check
1. What problem does this capability solve?
It turns the module's separate retrieval, memory, graph, permission, citation, and generation rules into one ask path with tests for the failures that become incidents: foreign text, missing sources, invented citations, double spend, and provider timeouts.
2. What alternatives exist, and when would you choose each?
A single demo script is enough to learn an API on a laptop, and it should still call the predicate. A port-based orchestrator is what you deploy. Streaming unvalidated tokens fits an uncited brainstorming box, not this prompt version. A tool-using agent fits Module 4, beside this read path.
3. Which data, identity, and trust boundaries matter?
The server supplies scope, the feature flag, and the provider allow-list. Search and hydrate enforce visibility. Memory is owned. The system prompt is constant. The model is untrusted for ids and for authorization. Traces store ids. Replay keys include the owner.
4. What can fail, and how should the system respond?
Disabled, unauthorized, empty, oversized, forbidden memory, and retrieval errors return reasons and do not draft. No passages yield a refusal without a model call. Timeout and vendor unavailability yield sources. Bad JSON or only ineligible citations yield a refusal. Replay returns the first result.
5. How would you test quality, security, performance, and cost?
Unit tests cover the matrix above and assert generate call counts. Security tests assert foreign ids never reach citations or traces. Performance tests assert one generation and a passage cap. Cost tests assert replay and the empty-retrieval path do not call the model, and that a forbidden provider is not invoked.
Practical Exercise
Implement packages/knowledge/src/assistant/ and run the tests. Add a case where the model returns valid JSON citing only chunk-pgvector, and assert degraded is empty and modelCalled is true. Write three sentences on how your composition root will implement search and hydrate using Lessons 33 and 34 without importing a vendor SDK into answer.ts.
Deliverable and Rubric
Submit the sequence diagram, the assistant package, the test output, a runbook note for the feature flag and the timeout path, and a list of side effects you deliberately left out.
Area
Weight
Conceptual accuracy and architecture
20%
Working implementation and code quality
25%
Security, privacy, and responsible AI
20%
Testing, reliability, and observability
20%
Documentation and decision rationale
15%
Production checklist:
Scope comes from the session.
Feature flag short-circuits spend.
Memory reads check the owner.
Search filters before ranking.
Graph ids are hydrated through visibility.
Empty passages do not call the model.
The learner reads passage text, or the abstain sentence when any selected id is not allowed.
Timeout shows sources.
Provider allow-list is enforced.
Replay prevents a second bill.
Traces omit passage text and the question.
The function does not execute tools.
Key Takeaways
The capstone is one orchestrator over ports you already built.
The feature flag is the first check.
Identity, length, and replay happen before generation.
The standalone query carries the allow-listed lesson title.
Search and hydrate enforce visibility. Expand does not get the last word.
No authorized passage means a template refusal and no model call.
The learner reads passage.text. One unknown id abstains the whole answer.
Uncited drafts are discarded.
Timeouts degrade to sources.
Provider policy is an allow-list, not a hidden fallback.
Replay keys include the owner.
Traces store ids and flags.
The system prompt is constant and versioned.
Validate, then render. Do not stream raw citation JSON.
This function is a read path. Tools begin in Module 4.
Summary
Lesson 35 closes RAG, Search and Knowledge Systems by shipping the TechLearningPro knowledge assistant as a single, testable ask path. Memory makes follow-ups standalone, the graph adds curriculum neighbors, the predicate decides what text exists, and ModelPort may phrase an answer only from that text. Refusals, source lists, and replays cover the failures that are otherwise explained away as model quirks. The lesson player keeps working when the assistant is flagged off. Nothing in this function sends a side effect into the product.
Next Lesson Preview
Module 4 opens with Agentic AI Concepts and Tool-Using Systems. You will separate a model's request to use a tool from the executor that is allowed to run it. The knowledge assistant you just built stays the grounded read path. Agents may call it. They do not get a private copy of retrieval that forgets the tenant, and they do not get to treat a paragraph of JSON as permission to change a learner's record.