Context Retrieval & RAG
Describes how an agent retrieves context from memory layers and injects it into LLM prompts with citation markers.
What this file does
Describes how an agent retrieves context from memory layers and injects it into LLM prompts with citation markers.
When to use it
- Building an LLM agent that needs persistent memory across conversations
- Implementing RAG with multiple memory stores (notes, knowledge graph)
- Adding citation verification to LLM outputs
- Designing a context injection pipeline for system prompts
Assumes this stack
Context Retrieval & RAG
Before each response, the ContextRetrievalAgent assembles relevant context from all memory layers and injects it into the system prompt with [N] citation markers.
Retrieval Flow
Defined in src/qq/context/retrieval_agent.py:102-286.
prepare_context() (retrieval_agent.py:102-166)
- Core notes (always included) --
core_manager.get_all_items()returns Identity, Projects, Relationships, System - Working notes (vector search) -- top 3 most relevant via embedding similarity
- Knowledge graph entities (embedding search) -- top 5 most relevant entities from Neo4j
- Format everything into a context block with
[N]indices
Core Notes Retrieval (retrieval_agent.py:128-132)
- Always loaded, no filtering
- Provides stable identity and context across all conversations
- Categories: Identity, Projects, Relationships, System
Working Notes Retrieval (retrieval_agent.py:135-144)
notes_agent.get_relevant_notes(query, limit=3)- Embedding-based vector similarity search against MongoDB
- Access tracking via
increment_access()(feeds importance decay) - Falls back to recent notes if embeddings are unavailable
Entity Retrieval (retrieval_agent.py:147-154)
knowledge_agent.get_relevant_entities(query, limit=5)- Embedding similarity search on Neo4j entity nodes
- Returns entities with similarity scores
Context Formatting
_format_context() (retrieval_agent.py:186-286)
Builds a structured text block:
## Retrieved Context
### Core Memory (User Profile)
[1] Identity: ...
[2] Projects: ...
### Relevant Memory Notes
[3] note content (importance: 0.7)
[4] note content (importance: 0.5)
### Related Knowledge
[5] Entity: Person - description
[6] Entity: Concept - description
Each item gets a [N] index via source_registry.add(type, label, detail).
Items below CITE_THRESHOLD (0.3) are filtered out.
System Prompt Injection (retrieval_agent.py:288-324)
- Prepends
## Retrieved Contextsection to system prompt - Includes explanation of
[N]indices for the LLM - Separated from main prompt with
---
Notes Agent (Summarization & Search)
Defined in src/qq/memory/notes_agent.py:52-316.
process_messages() (notes_agent.py:154-219)
- Load current
notes.mdcontent - Format last 20 messages
- LLM analyzes via
NOTES_EXTRACTION_PROMPT - Returns JSON:
{"additions": [...], "removals": [...], "summary": "..."}
_apply_updates() (notes_agent.py:221-288)
- Update
notes.mdfile viaapply_diff() - Generate embeddings for new items
- Store in MongoDB with source provenance
- Note IDs:
SHA256(content)[:16]
Vector Search (notes_agent.py:290-312)
get_relevant_notes(): Query embedding --> MongoDB similarity search --> top-k with scores. Falls back to recent notes if embeddings are unavailable.
Alignment Agent (Post-Answer Citation Verification)
Defined in src/qq/services/alignment.py.
After the LLM generates a response:
- Silent review of
[N]citations against actual source content - Flags unsupported claims
- Runs only when
QQ_ALIGNMENT_ENABLED=true
What's inside
4 retrieval stages, 2 formatting steps, 1 alignment agent, code references with line numbers.
Change this for your project
- Replace
src/qq/context/retrieval_agent.pywith your own module path - Replace
src/qq/memory/notes_agent.pywith your own module path - Replace
src/qq/services/alignment.pywith your own module path - Replace
QQ_ALIGNMENT_ENABLEDwith your own environment variable name
Where it goes
Reference documentation for a retrieval pipeline. Keep with the ingestion or retrieval code it describes.
Worth borrowing
- Using
[N]citation markers to let the LLM reference retrieved context in its output - Post-answer alignment agent that silently verifies citations against source content
Related Documents
SUMMARY
Proposes three on-prem AI architectures, modular, hybrid, and fully local RAG, with hardware specs and vendor lists.
Retrieval & Prompts
Explains how CharMemory's extraction prompt and Vector Storage settings determine memory retrieval quality in SillyTavern.
App Review Support Guide — Switch2Go
Explains an AAC app's accessibility permissions, hardware needs, and reviewer walkthrough to pass App Store review.
RFC-BLite: High-Performance Embedded Document Database for .NET
Specifies an embedded document database for.NET with zero-allocation I/O, C-BSON format, and ACID transactions.