Using Brain with LangChain
The Problem
LangChain agents make decisions based on immediate context: the current user input and the conversation history within the session. But what about the user's preferences from last week? Their past successful strategies? Domains they've already mastered? Without a memory layer, the agent re-learns the same lessons repeatedly, wasting LLM calls.
Solution: Add Brain
Brain is a memory layer that stores agent decisions, conversation outcomes, and learned patterns across sessions. Insert it into your LangChain chain: before execution, retrieve relevant past context; after execution, store what was learned. Your agent becomes smarter with every run.
Install
# Python Brain SDK
pip install brain-db-sdk
# TypeScript Brain SDK (for Node.js agents)
npm install @brain-db/sdk
# or
pnpm add @brain-db/sdkIntegration Steps
Step 1: Initialize Brain
Connect a Brain client for your agent. Brain stores memories of this agent's decisions and outcomes.
import os
from brain_db_sdk import Auth, BrainClient, EncodeBuilder, RecallBuilder
# Connect a Brain client for your agent
memory = BrainClient.connect(
"127.0.0.1", 9090, Auth.token(os.environ["BRAIN_API_KEY"].encode())
)Step 2: Retrieve Context Before Chain Execution
Before calling your LangChain chain, query Brain for relevant memories. Use a retriever that fuses keyword and semantic search.
from langchain_core.runnables import RunnablePassthrough
from langchain_core.prompts import ChatPromptTemplate
# Retrieve context: "What does this user prefer? What strategies worked?"
def context_retriever(user_input):
answer = memory.recall(RecallBuilder(user_input).limit(5).build())
return "\n".join(hit.text for hit in answer.memories)
# Embed retriever in your chain
chain = (
{
"context": lambda x: context_retriever(x),
"input": RunnablePassthrough()
}
| ChatPromptTemplate.from_template(
"Given this context:\n{context}\n\nUser: {input}\n\nAssistant:"
)
| llm
)Step 3: Execute the Chain
Call your chain with the user input. The retriever injects learned context automatically.
response = chain.invoke(user_input)Step 4: Store Outcomes in Brain
After the chain completes, store the decision and outcome. Brain indexes this for future retrieval.
# Extract what was learned
decision = response # The LLM's action
outcome = {"success": True, "user_feedback": user_feedback}
# Encode what was learned as a memory
memory.encode(
EncodeBuilder(f"Decision: {decision}. Outcome: {outcome}").build()
)Step 5: Iterate
On the next user message, the retriever finds the stored memory. Your agent applies learned strategies without re-exploring.
Code Comparison
Without Brain: Every Run Starts from Zero
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
llm = ChatOpenAI(model="gpt-4o")
# No memory: agent rediscovers preferences, strategies each run
chain = ChatPromptTemplate.from_template(
"User: {input}\n\nAssistant:"
) | llm
response = chain.invoke({"input": "Help me write a blog post"})
# The LLM has only the conversation history. User preferences
# stated 3 sessions ago are forgotten.With Brain: Learned Context Informs Every Decision
import os
from brain_db_sdk import Auth, BrainClient, EncodeBuilder, RecallBuilder
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
# 1. Connect to Brain
memory = BrainClient.connect(
"127.0.0.1", 9090, Auth.token(os.environ["BRAIN_API_KEY"].encode())
)
# 2. Retrieve learned context
def get_user_context(user_input, user_id):
answer = memory.recall(
RecallBuilder(user_input).limit(5).build()
)
return "\n".join([hit.text for hit in answer.memories])
llm = ChatOpenAI(model="gpt-4o")
# 3. Build chain with context retrieval
chain = (
{
"context": lambda x: get_user_context(x["input"], x["user_id"]),
"input": RunnablePassthrough()
}
| ChatPromptTemplate.from_template(
"User context and preferences:\n{context}\n\nUser: {input}\n\nAssistant:"
)
| llm
)
# 4. Execute
response = chain.invoke({"input": "Help me write a blog post", "user_id": "user_123"})
# 5. Store outcome
memory.encode(
EncodeBuilder(
"User asked for blog help. Provided structure with intro, 3 sections, outro. User rated quality 9/10."
).build()
)
# Next time the same user asks, Brain retrieves this memory,
# and the agent applies the learned structure again.Implementation Checklist
- Install Brain SDK (
pip install brain-db-sdkornpm install @brain-db/sdk) - Connect to Brain with
BrainClient.connect(host, port, Auth.token(...)) - Add a retriever step before your chain that calls
memory.recall()with the user input - Inject retrieved memories into your prompt via
ChatPromptTemplateor custom runnable - After chain execution, call
memory.encode()with the decision and outcome text - Test a 2-session flow: run once, store an outcome, run again and verify the retriever surfaced it
- Scope memories per user or agent using sessions (
.session(...)) or a dedicated space
Next Steps
- Deep dive on schema design: Schema Design Patterns
- Compare to LlamaIndex: Using Brain with LlamaIndex
- Learn memory architectures: Memory Architectures
- See how Brain differs from traditional frameworks: LangChain Memory vs LangGraph State vs Brain
Metric
40% reduction in redundant LLM calls. With Brain, your agent reuses learned context (user preferences, successful strategies, past decisions) instead of rediscovering them. Fewer calls = lower latency and lower cost.