Agent Memory Retrieval Upgrade: From Vector Search to Inverted Index
This article explains how to upgrade an AI agent's memory retrieval by combining message search and event search. It covers why a 3-gram inverted index suits literal matching, how hybrid lexical and semantic retrieval work, and how retrieval works alongside explicit long-term notes. It also outlines key implementation concerns such as permissions, privacy, context budget, and evaluation.
Agent Memory Retrieval Upgrade: From Vector Search to Inverted Index
1. The Starting Point: Why “Being Able to Search” Matters More Than “Remembering More”
In instant messaging products, chat history search is almost a default feature. Users instinctively expect to search for a sentence, a link, or a keyword and instantly jump back to the context around it. But treating search merely as a convenience for users underestimates its value.
The real dividing line is whether you design the agent as a first-class citizen. Once you accept that premise, retrieval can no longer serve humans alone; it must also serve the agent’s need to look back. Instead of relying only on the small slice of the current context window that has not yet been flushed out, the agent can actively revisit history.
This is a structural shift: memory no longer depends on the model “happening to remember,” but on the system “being able to retrieve.” The former is probabilistic; the latter is an engineering concern.
2. Two Types of Retrieval Targets: Messages and Events
2.1 Message Retrieval
Messages are the most surface-level carrier of memory. A user vaguely remembers a sentence, a link, a promise, or a decision that was made, and retrieval lets them land directly on that moment instead of scrolling back endlessly. This is a basic capability any serious chat product should have.
2.2 Event Retrieval
The message layer alone is not enough. The core abstraction of agent memory is usually the “event,” which is far broader than a single message. An event can be:
- Something the user said;
- Something the agent said;
- An information source the agent encountered in a browser;
- An intermediate step observed by the system within a workflow.
The value of the event layer is that the agent is no longer looking only for an exact quote, but for “what happened last week,” “what happened last month,” “how you once discussed a certain topic,” “which sources I saw while searching,” and “what I myself did before.” The past therefore becomes traceable, and traceability is the key step that turns memory from a decoration into a usable capability.
3. Technology Choice: Why a 3-gram Inverted Index Fits
Using a 3-gram-based inverted index for event retrieval is a pragmatic choice, for three reasons.
First, literal-match recall is a rigid requirement. Links, IDs, proper nouns, code snippets, and configuration items are often “averaged out” in a semantic vector space, where their similarity does not score well, yet these are exactly what users and agents rely on most. An inverted index matches such exact tokens deterministically.
Second, 3-grams are friendly to Chinese and mixed text. Chinese lacks natural whitespace tokenization: splitting by character causes index bloat and noise, while splitting by word depends on tokenizer quality. Taking three consecutive characters as the index unit balances index size against matching tolerance and naturally supports substring-style recall.
Third, it is explainable and debuggable. A hit is a hit; you do not have to guess at a similarity threshold to explain “why nothing was found.”
Illustrative index-building logic (pseudocode):
def build_index(events):index = defaultdict(set) # gram -> set of event IDsfor e in events:text = normalize(e.content) # unify case, full-width/half-widthfor i in range(len(text) - 2):index[text[i:i+3]].add(e.id)return indexdef search(index, query, top_k=20):grams = [query[i:i+3] for i in range(len(query) - 2)]if not grams:return []counter = Counter()for g in grams:for eid in index.get(g, ()): # intersect and count posting listscounter[eid] += 1return [eid for eid, _ in counter.most_common(top_k)]
Engineering-wise, you also need to cap high-frequency grams to avoid long-tail noise events drowning out results; add fallbacks for stop words and extremely short queries; and decouple index updates from writes so that incremental events can be retrieved promptly.
4. Hybrid Retrieval: Letting Literal and Semantic Signals Each Do Their Job
Production systems rarely choose one over the other; instead, they let the two signals complement each other:
- The literal path (inverted index) handles exact matches and entity recall;
- The semantic path (vector similarity) handles paraphrasing and fuzzy intent;
- A fusion layer performs normalized scoring and weighting, then hands results to a reranking model or simply truncates them.
A simplified fusion example:
def hybrid_search(lexical_ids, dense_ids, alpha=0.6):scores = defaultdict(float)for i, eid in enumerate(lexical_ids):scores[eid] += alpha * (1.0 / (i + 1))for i, eid in enumerate(dense_ids):scores[eid] += (1 - alpha) * (1.0 / (i + 1))return sorted(scores, key=scores.get, reverse=True)
The key principle is to bring retrieval results back into the context with their “provenance,” including time, participants, and source type, so the agent can judge how fresh and trustworthy the evidence is.
5. Working with Explicit Memory: Teaching to Fish
On top of this, there is a mechanism for actively distilling memory: carrying long-term memory in structured text such as Markdown and persisting important conclusions through file-writing tools, the digital equivalent of “a weak memory beats a written note.”
The two are complementary: explicit notes are compressed conclusions, while retrieval is the traceable raw trail. The former saves tokens; the latter preserves fidelity. The ideal strategy is for the agent to retrieve first, then decide whether it needs to read the full event, and write conclusions back to long-term memory when necessary, forming a “retrieve-verify-distill” loop.
6. Implementation Points and Common Pitfalls
- Permissions and visibility: Retrieval in group chats and private chats must follow the original visibility scope; the index layer must not become a channel for privilege escalation.
- Privacy and lifecycle: Set retention periods and deletion capability for events, and deletion must also clean up the index.
- Context budget: Limit retrieval results and rank them by relevance and time decay to avoid crowding out the window.
- Evaluation: Measure literal hit rate, semantic recall, and final task completion rate separately, rather than looking at a single metric.
7. Conclusion
Giving retrieval to both users and agents is essentially returning the right to use memory to the system itself. When messages and events can be retrieved and traced, and work alongside explicit notes, memory truly becomes a verifiable, reusable production capability rather than a temporary decoration in the context, which is exactly the engineering meaning of “teaching to fish.”
