AI Development

AD-02

Design retrieval and memory

What you'll produce: Retrieval design doc

Definition

Retrieval is how a system fetches information it was not given up front. Memory is what it keeps from earlier runs. A retrieval design doc records, for each kind of question, the source of truth, the search method, what is returned to the model, what is written back, and who owns freshness and access.

TL;DR

Why retrieval decides what the model can get right

A model answers from its training and from its window. Anything specific to your business, such as today's price list or last week's ticket, has to be fetched. Eugene Yan's survey of LLM patterns gives the practical case for retrieval. An index is cheaper to keep current than a model, and when a document has to be corrected or removed, you change the index instead of retraining anything.

The same survey reports a finding from early retrieval research that still guides design: when retrieval gets more precise, end-to-end answer accuracy rises with it. The reverse holds too. LangChain's retrieval guide names three ways an agent's search goes wrong. It searches clumsily and fills its window with failed attempts. One search returns far too much. Or it pulls in stale or off-topic material, which looks just as convincing to the model as the right answer and gets built on in every later step.

That last point is why a design doc is worth the time. Retrieval errors do not announce themselves. The answer reads well and cites something.

Start from questions, then pick the cheapest search that works

Collect real questions before choosing any technology. Group them into types and name one source of truth for each. This step often finds the real problem: two documents that disagree, or a question type with no source at all.

Then pick a search method per source.

Method Good at Weak at
Name and keyword search Exact terms such as codes, identifiers, file names Synonyms and paraphrase
Semantic search Questions worded differently from the source Exact identifiers, and cost at large scale
Structured query Numbers and records in a database Anything not in a table
External search API Fresh public information Private data, and trust in what comes back

Chip Huyen's platform overview notes that keyword-style retrieval costs far less and runs far quicker than the embedding-based kind, which makes it a strong baseline to start from. A typical production system then combines methods: a cheap first pass fetches candidates and a more precise step reranks them. Eugene Yan reports from his own project that a classical index plus embeddings worked better than either alone.

For agents, add one more choice: whether the system searches once and answers, or the model decides when to search again. A fixed single search suits a question-and-answer tool. An agent doing research will find things mid-task that it could not have known to look for. Give it tools that look before they read, such as listing file names and matching lines, so it can narrow down before loading whole documents.

Decide what the system remembers

Memory is information the system writes for its own later use. LangChain's overview borrows three types from cognitive science, and they map well to engineering decisions.

  • Instructions it follows. Rules and preferences that shape behaviour, often kept in a file the agent reads at the start of each run.
  • Facts it knows. Things learned about a user, a customer, or a domain, retrieved when relevant.
  • Records of past runs. Earlier examples of the task done well, used as worked examples.

The same overview stresses that memory is specific to the application. A coding assistant and a research assistant should remember different things, so there is no general-purpose setting to copy.

For each type, the design doc answers four questions. Who may write it? Is it written during the run or by a background job? Who may read it? When does it expire? LangChain's account of its own agent builder describes storing memory as files the agent can read and edit, backed by a database. The format matters less than the rules around it.

One limit needs stating plainly. Our own post on memory failures argues that a similarity search is a lookup, and an agent in the middle of a long task needs state: the goal, the decisions already made, the step it is on. Keep that in an explicit record that is written at each step, not in a store you hope will return the right fragment.

Worked example: a field-service assistant

This example is fictional. A company that services commercial heating equipment wants an assistant for its technicians.

The team collects 45 real questions from the dispatch log and finds four types.

  1. Error codes, such as what a given code means on a given boiler model. The source is the manufacturer manuals. Codes are exact strings, so keyword search over manuals, filtered by model, is the method.
  2. Symptoms described in plain words, such as a unit that short-cycles after a filter change. The source is past resolved tickets. Wording varies, so semantic search is used here, with a keyword pass for model numbers.
  3. Part availability. The source is the inventory database, queried directly.
  4. Site history, such as what was done at this address before. This is memory: a short note per site, written by a background job after each closed ticket and reviewed by the dispatcher weekly.

The return contract caps each result at 400 tokens and five results per search, and every result carries its manual section or ticket number. Site notes expire after 24 months unless renewed.

The retrieval eval uses 20 of the questions, each labelled with the manual section or ticket a correct answer must cite. On the first run, 14 return the expected source. Five of the six misses are error-code questions where semantic search had been tried first and returned a similar code from the wrong model. Switching those to keyword search with a model filter brings the result to 19 of 20. The last miss is a manual that was never indexed.

Common failure modes

  • One method for everything. A vector index used for error codes and inventory counts will return something plausible and wrong.
  • No owner for freshness. An index nobody refreshes becomes a source of confident, outdated answers.
  • Memory without expiry or review. Entries the agent wrote from a bad run get retrieved into good runs.
  • Access rules checked too late. If the index ignores who is asking, retrieval can surface a document the user should not see. Store the access level with every entry and filter before results reach the model.
  • Testing only the final answer. Without a retrieval eval, every wrong answer looks like a model problem.
  • Using search to hold run state. The step counter and the list of decisions belong in a record, not in an index.

How it connects to the other pillars

On the product side, the question set and the labelled sources come from the work of defining quality before building. If the product team has a golden set of cases, the retrieval eval is a slice of it with one extra column: which source a correct answer must cite.

On the factory side, shared memory between agent workers is the same design problem with more writers. Each work order should name what a worker may read and what it may write back, so that one worker's mistake does not become another's context. The rules in this doc, covering owner, writer, reader, and expiry, are the ones a factory needs once many agents share one store.

Run it yourself

Time: ~half a day for a first version

  1. List the questions and where each answer lives — You need: 30 to 50 real questions from logs or from the people who do the work today. You get: A table of question types, each mapped to one source of truth and its owner. If two sources can answer the same question, decide which one wins before you build anything.
  2. Choose a search method per source — You need: The table and a sample of each source. You get: One method per source, chosen from name and keyword search, semantic search, structured query, or an external search API. Try keyword search first. It is fast, cheap, and a strong baseline. Add semantic search where wording varies.
  3. Decide how content is prepared and kept fresh — You need: Document sizes, update frequency, and access rules for each source. You get: A chunking rule, the metadata stored with each chunk, a refresh schedule, and an expiry rule.
  4. Decide what is remembered — You need: Examples of facts, preferences, and past runs the system would benefit from recalling. You get: A memory table listing each type, who may write it, whether it is written during the run or afterwards, who may read it, and how long it lives.
  5. Define what goes back to the model — You need: The token ceiling for retrieved content from the context map. You get: A result limit, a size cap per result, a required citation format, and a rule for writing oversized results to a file.
  6. Build the retrieval eval — You need: The question set, with the source a correct answer must cite. You get: A test that reports, per question, whether the expected source was returned and how many tokens came with it.

Do it with AI

You are helping me write a retrieval design doc for one AI system. Use only what I provide. Where information is missing, list it as an open question instead of guessing.

System and task: [ONE SENTENCE]
Sample questions the system must answer: [PASTE 30 TO 50 REAL QUESTIONS]
Available sources: [FOR EACH: NAME, FORMAT, SIZE, HOW OFTEN IT CHANGES, OWNER, WHO MAY ACCESS IT]
Token ceiling for retrieved content per call: [NUMBER]
Things the system should remember between runs, if any: [LIST OR "NONE YET"]

Produce the following sections.

1. Question map. Group the questions into types. For each type name the single source of truth. Flag any type with no source or with two competing sources.

2. Search method. For each source recommend keyword search, semantic search, structured query, or a combination, with one sentence of reasoning tied to the sample questions. Prefer the simplest method that would find the answer.

3. Preparation and freshness. For each source give a chunking rule, the metadata to store (at least source, section, date, and access level), a refresh schedule, and an expiry rule.

4. Memory. For each thing to remember state the type (instructions the system follows, facts it knows, or records of past runs), who may write it, whether it is written during the run or by a background job, who may read it, and the retention period.

5. Return contract. State how many results are returned, the size cap per result, the citation format, and what happens to results over the cap.

6. Retrieval eval. Pick 20 of the sample questions and for each one name the source and section a correct answer must cite.

End with open questions and the three risks most likely to cause a wrong answer.

Chain it

  1. Question mapper — Groups real questions into types and proposes a source of truth for each; Question logs and a catalogue of available sources → A question map with gaps and conflicts marked; gate: Each source owner confirms their source is the right one for its question types
  2. Index builder — Prepares each source according to the chunking and metadata rules and builds the search indexes; The approved question map and the preparation rules → Indexes with source, section, date, and access level on every entry
  3. Retrieval evaluator — Runs the question set against the indexes and checks whether the expected source came back; The indexes and the labelled question set → A per-question pass or fail with the returned sources and token counts
  4. Memory curator — Proposes new memory entries from finished runs and flags entries that are stale or contradicted; Run records and the current memory store → A list of proposed additions, edits, and deletions; gate: A named owner approves changes to shared memory before they take effect

How AI changes this

Automate

Keep human

Stage

FAQ

Do I need a vector database?

Not always. If the questions use the same words as the documents, such as error codes, product names, or file names, keyword search is cheaper and often enough. Add semantic search when people describe things in words the source does not use. Many systems run both and rerank the combined results.

What is the difference between retrieval and memory?

Retrieval reads from sources the system does not own, such as documents, databases, or the web. Memory is what the system itself writes and reads back later. They can share the same search machinery, but memory needs extra rules because the system is the author. Decide who may write, who reviews, and when entries expire.

Should memory be written during the run or afterwards?

Writing during the run makes the memory available immediately, but adds latency and mixes memory logic into the agent. Writing afterwards in a background job keeps the run fast and the logic separate, but the memory arrives late and you need a trigger. Pick per memory type, based on how soon the next run needs it.

How do I know retrieval is the problem and not the model?

Check whether the expected source was in the window when the model answered. If it was missing, fix retrieval. If it was present and the answer is still wrong, look at the prompt, the amount of surrounding material, or the model. The retrieval eval exists to make that check quick.

Sources

Related