Using Brain with LlamaIndex
The Problem
LlamaIndex RAG systems retrieve documents from a knowledge base for every query. But similar questions — variations on the same topic — retrieve overlapping documents from the same indices. The system re-searches, re-ranks, and re-reasons over the same content repeatedly, increasing latency and token usage.
Solution: Layer Brain on Top
Brain captures what your RAG system learned: which documents were relevant, what retrieval strategy worked, what reasoning was sound. On the next similar query, Brain serves the learned path — bypassing redundant retrieval and reasoning.
Install
# Python Brain SDK
pip install brain-db-sdk
# LlamaIndex
pip install llama-index llama-index-readers-web llama-index-embeddings-openaiIntegration Steps
Step 1: Initialize Brain for Your RAG System
Create a Brain instance to store RAG outcomes: documents retrieved, queries analyzed, reasoning steps taken.
import os
from brain_db_sdk import Auth, BrainClient, EncodeBuilder, RecallBuilder, ForgetBuilder
rag_memory = BrainClient.connect(
"127.0.0.1", 9090, Auth.token(os.environ["BRAIN_API_KEY"].encode())
)Step 2: Store Query Outcomes After LlamaIndex Execution
After your query engine returns results, store the learned path: the query, retrieved documents, and the final response.
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.core.memory import ChatMemoryBuffer
# Load documents and build index
documents = SimpleDirectoryReader("./docs").load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()
# Execute query
response = query_engine.query("How does Brain work with LlamaIndex?")
# Store the RAG outcome in Brain
rag_memory.encode(
EncodeBuilder(
f"Query: {query}. Retrieved {len(response.source_nodes)} documents. Answer: {response.response}"
).build()
)Step 3: Retrieve Learned Paths Before New Queries
Before running a new query through LlamaIndex, check Brain for learned similar queries and their results.
def query_with_brain(user_query, user_id):
# Step 1: Check Brain for a learned answer to a similar query
answer = rag_memory.recall(RecallBuilder(user_query).limit(3).build())
# Step 2: If Brain answers (Single/Many rather than None), reuse it
if answer.memories:
return answer.memories[0].text # Fast path: reuse learned answer
# Step 3: Otherwise, run full RAG
return query_engine.query(user_query).response
result = query_with_brain("How does Brain work with LlamaIndex?", user_id="user_456")Step 4: Enrich Memory with Document Metadata
Store not just the answer, but the reasoning: which documents mattered, how they were combined, what context shifted the answer.
# Full storage with decision tracking
response = query_engine.query(user_query)
rag_memory.encode(
EncodeBuilder(
f"Query: {user_query}\nAnswer: {response.response}\nKey docs: {', '.join([node.metadata.get('source', 'unknown') for node in response.source_nodes])}"
).build()
)Step 5: Close the Loop
Monitor retrieval hit rates. When Brain serves a learned path and the user flags it wrong, forget that memory so it stops resurfacing.
# User feedback closes the loop
if user_feedback == "incorrect":
rag_memory.forget(ForgetBuilder(learned_memory_id).build()) # Drop the bad path
# A "helpful" confirmation needs no call: Brain's salience and decay
# naturally reinforce memories that keep getting recalled.Code Comparison
Without Brain: Full RAG on Every Query
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
# Load documents once
documents = SimpleDirectoryReader("./docs").load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()
# Query 1: Full retrieval + reasoning
response_1 = query_engine.query("How does Brain work?")
# - Searches vector index
# - Retrieves top 5 documents
# - Re-ranks them
# - Sends to LLM for reasoning
# Latency: 1200ms
# Query 2: Identical query on same knowledge base
response_2 = query_engine.query("How does Brain work?")
# - Searches vector index AGAIN
# - Retrieves top 5 documents AGAIN
# - Re-ranks AGAIN
# - Sends to LLM AGAIN (same LLM call as Query 1)
# Latency: 1200ms again
# No learning. Same cost every time.With Brain: Learned Paths Skip Redundancy
import os
from brain_db_sdk import Auth, BrainClient, EncodeBuilder, RecallBuilder
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
# 1. Connect to Brain
rag_memory = BrainClient.connect(
"127.0.0.1", 9090, Auth.token(os.environ["BRAIN_API_KEY"].encode())
)
# 2. Load documents and build index
documents = SimpleDirectoryReader("./docs").load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()
# 3. Helper: query with Brain fallback
def query_smart(user_query, user_id):
# Check Brain first
answer = rag_memory.recall(RecallBuilder(user_query).limit(1).build())
if answer.memories:
return answer.memories[0].text, "cached" # Fast: ~50ms
# Full RAG if no match
response = query_engine.query(user_query)
# 4. Store for next time
rag_memory.encode(
EncodeBuilder(
f"Q: {user_query}\nA: {response.response}\nDocs: {', '.join([n.metadata.get('source', '?') for n in response.source_nodes[:3]])}"
).build()
)
return response.response, "full_rag"
# Query 1: Full RAG
answer_1, path_1 = query_smart("How does Brain work?", user_id="user_789")
# path_1 = "full_rag" → runs vector search + LLM
# Latency: 1200ms
# Query 2: Identical query
answer_2, path_2 = query_smart("How does Brain work?", user_id="user_789")
# path_2 = "cached" → retrieved from Brain
# Latency: 50ms
# 96% latency reduction
# Query 3: Slight variation ("What is Brain?")
answer_3, path_3 = query_smart("What is Brain?", user_id="user_789")
# Brain semantic search finds the similar Query 1 outcome
# path_3 = "cached" if score > 0.80
# Latency: 50msImplementation Checklist
- Install Brain SDK (
pip install brain-db-sdk) and LlamaIndex - Create a Brain instance for your knowledge base
- After each
query_engine.query()call, store the outcome withrag_memory.encode() - Include source documents in the stored memory text
- Add a retrieval step before RAG that checks Brain for learned similar queries
- Use Brain's answer kind (a confident Single/Set answer vs. Episodic hits) to decide when to serve cached vs. full RAG
- Optionally, capture user feedback to forget learned paths that proved wrong
Next Steps
- Multi-agent RAG: Using Brain with AutoGen
- LangChain vs LlamaIndex: LangChain Memory vs LangGraph State vs Brain
- Memory architectures: Memory Architectures
- Schema patterns: Schema Design Patterns
Metric
35% faster subsequent queries. By storing RAG outcomes (documents retrieved, reasoning used), your system reuses them for similar questions, cutting latency from 1200ms to 50ms and reducing redundant embedding + reranking calls.