Brain Docs

Reference

Integrations

Frameworks

Next.jsFastAPILangChainOpenAI

Protocol

Brain over MCP
Brain/Docs
✦ ASKBrain on GitHubDashboard
IntegrationsLangChain

LangChain

Where Brain fits in LangChain's memory model — the checkpointer it does not replace, the long-term store it does, three wiring options with working code, and the write policy no framework will give you.

PURPOSE

LangChain splits memory into two layers that are easy to conflate, and Brain only belongs in one of them. This page draws that line first, then gives three ways to wire Brain into the long-term half — a store, a retriever, or agent tools — with the trade-offs between them, the identity model, and the write policy that decides whether any of it is worth having.

◇Prerequisites

A LangChain or LangGraph app, a Brain API key, and a backend to point at. If encode and recall are new, read Your first memory first.

Brain replaces one of LangChain's two memory layers

This is the whole integration, and getting it wrong produces an app that duplicates conversation state in two places and recalls poorly from both.

Short-term — the checkpointer
Long-term — the store
Holds
The current thread's messages and graph state
Facts that outlive the thread
Keyed by
`thread_id`
A namespace you choose
Lifetime
One conversation
The user's relationship with your product
Backed by
`InMemorySaver`, Postgres, SQLite
**This is where Brain goes**
Read as
Exact replay, in order
A question — what do we know about this?

Do not put the checkpointer in Brain

A checkpointer needs exact, ordered replay of graph state. Brain ranks memories by resemblance to a cue and returns a membership verdict — it is a question-answerer, not a transcript. Backing a checkpointer with it gives you a conversation that silently loses turns and reorders the ones it keeps.

Keep the checkpointer on Postgres or SQLite. Brain is the layer above it.

The legacy memory classes are gone

If the integration you are porting uses ConversationChain with a BaseChatMemory subclass, that is the pre-0.3 API. It is deprecated in favour of managing memory outside the chain, and on 1.x it has moved into langchain-classic — so an import that worked on 0.2 raises on a current install.

What replaced it

Short-term is a LangGraph checkpointer keyed by thread_id. Long-term is a BaseStore, agent tools, or a retriever — the three options below. Nothing replaces BaseChatMemory one-for-one, because it conflated the two layers, which is the problem the split exists to fix.

Option A — Brain as a long-term store

The closest fit. LangGraph's store interface is put / get / search over namespaced items, which maps onto encode / recall with one honest caveat.

brain_store.py
from typing import Any, Iterable

from brain_db_sdk.http import BrainHttpClient
from langgraph.store.base import BaseStore, Item, SearchItem


class BrainStore(BaseStore):
    """Long-term memory, backed by Brain.

    Namespaces are advisory here, not a boundary: Brain's isolation is the
    credential's `(namespace, space)`, which this client was constructed
    with. Two BrainStore instances sharing a key share a space no matter what
    namespace tuple they are handed — see "Identity" below.
    """

    def __init__(self, brain: BrainHttpClient) -> None:
        self.brain = brain

    def put(self, namespace: tuple[str, ...], key: str, value: dict[str, Any]) -> None:
        text = value.get("text")
        if not text:
            return
        self.brain.encode(text, occurred_at=value.get("occurred_at"))

    def search(
        self, namespace_prefix: tuple[str, ...], *, query: str | None = None, limit: int = 10
    ) -> list[SearchItem]:
        if not query:
            return []
        answer = self.brain.recall(query, max_results=limit)
        if answer.answer_kind == "none":
            return []
        return [
            SearchItem(
                namespace=namespace_prefix,
                key=m.memory_id,
                value={"text": m.text},
                score=m.similarity_score,
            )
            for m in answer.memories
        ]

    def get(self, namespace: tuple[str, ...], key: str) -> Item | None:
        detail = self.brain.memory_inspect(key)
        return Item(namespace=namespace, key=key, value={"text": detail.text})
`put` is not an upsert, and `search` throws away the verdict

Two places this adapter is lying slightly, and you should know where.

put(namespace, key, value) implies you control the key. You do not — encode mints the memory id. Writing "the same key" twice writes two memories unless the text is byte-identical, in which case content dedup collapses them and reports was_deduplicated. If your graph relies on overwriting a store key, that behaviour does not exist here; corrections supersede instead.

search flattens single / many / none into a list. The interface has nowhere to put a membership verdict, so none becomes [] — which is the one distinction worth having. If the difference between "we know nothing" and "we found nothing good" matters in your prompt, reach past the store and call recall directly at that call site.

Option B — Brain as a retriever

For chains that are RAG-shaped, where you want memories to arrive as Documents alongside other sources.

from brain_db_sdk.http import BrainHttpClient
from langchain_core.documents import Document
from langchain_core.retrievers import BaseRetriever


class BrainRetriever(BaseRetriever):
    brain: BrainHttpClient
    max_results: int = 6

    def _get_relevant_documents(self, query: str, *, run_manager=None) -> list[Document]:
        answer = self.brain.recall(query, max_results=self.max_results)
        if answer.answer_kind == "none":
            return []
        return [
            Document(
                page_content=m.text,
                metadata={"memory_id": m.memory_id, "confidence": m.confidence},
            )
            for m in answer.memories
        ]
import { BrainHttpClient } from "@brain-db/sdk/http";
import { BaseRetriever } from "@langchain/core/retrievers";
import { Document } from "@langchain/core/documents";

export class BrainRetriever extends BaseRetriever {
  lc_namespace = ["brain", "retrievers"];

  constructor(
    private readonly brain: BrainHttpClient,
    private readonly maxResults = 6,
  ) {
    super();
  }

  async _getRelevantDocuments(query: string): Promise<Document[]> {
    const answer = await this.brain.recall({ query, maxResults: this.maxResults });
    if (answer.answerKind === "none") return [];
    return answer.memories.map(
      (m) =>
        new Document({
          pageContent: m.text,
          metadata: { memoryId: m.memoryId, confidence: m.confidence },
        }),
    );
  }
}

Do not put `similarityScore` in a threshold

The instinct with a retriever is to filter on score. Brain has already decided which memories answer the cue — the verdict encodes that judgement — and re-thresholding on top of it is how a chain discards the one memory that answered the question. If you are reaching for a threshold, what you want is a smaller max_results.

Option C — Brain as agent tools

Hand the model the verbs and let it decide when to use them. This is the LangChain analogue of the MCP shape, with the same trade-off.

from langchain_core.tools import tool


@tool
def recall_memory(query: str) -> str:
    """Look up what is known about the user. Returns nothing when unknown."""
    answer = brain.recall(query, max_results=6)
    if answer.answer_kind == "none":
        # Say so explicitly. An empty string invites the model to fill the gap.
        return "Nothing stored answers that."
    return "\n".join(f"- {m.text}" for m in answer.memories)


@tool
def remember(claim: str) -> str:
    """Store a durable fact about the user. Not for conversation turns."""
    result = brain.encode(claim)
    return f"stored {result.memory_id}"

Registering the write tool is a decision, not a default

An agent that can call remember decides for itself what is worth remembering — and the failure mode is silent. A memory that never gets written looks exactly like a conversation where there was nothing to write; no error, no log, nothing to alert on.

A common production shape is to register only recall_memory and write from your own code after the turn, where a policy can be tested. See the integrations index for the same trade in general.

Choosing between the three

OptionTypeDefault / Env
StoreLangGraph agents

Memory arrives through the framework's own interface, so the graph does not know Brain is there. Costs you the verdict.

RetrieverRAG-shaped chains

Composes with other retrievers and rerankers. Also costs you the verdict, and invites score-thresholding.

Toolsagentic loops

Keeps the verdict, because you format the tool's return value. Costs context on every call, and hands the write decision to the model.

A direct callanywhere it matters

Not a LangChain integration at all — just brain.recall(...) at the call site. Keeps everything, composes with nothing. Mix freely with the above.

Nothing stops you doing several. A production shape that works well: the store for the agent's background knowledge, a direct call on the one path where none has to change the prompt, and no write tool at all.

Putting it together

A LangGraph agent with both layers wired correctly — the checkpointer on Postgres for the thread, Brain for everything that outlives it.

agent.py
from langchain.agents import create_agent
from langchain_core.tools import tool
from langgraph.checkpoint.postgres import PostgresSaver

from brain_db_sdk.http import BrainHttpClient, BrainHttpError


def build_agent(user) -> object:
    # One client per caller. The credential IS the scope.
    brain = BrainHttpClient(key_for(user), base_url=BASE_URL, timeout=10.0)

    @tool
    def recall_memory(query: str) -> str:
        """Look up what is known about the user. Returns nothing when unknown."""
        try:
            answer = brain.recall(query, max_results=6)
        except BrainHttpError as err:
            # The agent should know it could not check, rather than
            # concluding the user has no history.
            return f"Memory is unavailable right now ({err.code}); answer without it."
        if answer.answer_kind == "none":
            return "Nothing stored answers that."
        return "\n".join(f"- {m.text}" for m in answer.memories)

    # Only the READ verb is registered. Writes happen below, under a policy.
    return create_agent(
        model="claude-opus-5",
        tools=[recall_memory],
        checkpointer=PostgresSaver.from_conn_string(PG_URL),
    )


def turn(user, thread_id: str, message: str) -> str:
    agent = build_agent(user)
    result = agent.invoke(
        {"messages": [{"role": "user", "content": message}]},
        config={"configurable": {"thread_id": thread_id}},
    )
    reply = result["messages"][-1].content

    # The write policy lives here, in code you can test — not in a tool the
    # model decides to call.
    if is_durable(message):
        BrainHttpClient(key_for(user), base_url=BASE_URL).encode(restate(message))

    return reply

Three things are load-bearing.

The checkpointer is Postgres, not Brain. thread_id replays the conversation exactly; Brain answers questions about the user. Different jobs, different stores.

Only the read tool is registered. The model can ask what is known whenever it likes; what gets remembered is decided by is_durable, which is a function with tests rather than a judgement the model makes silently.

The error path returns a sentence, not an exception. A tool that raises aborts the run; a tool that says "memory is unavailable" lets the agent tell the user it could not check.

Tuning the read

recall takes four options beyond the cue, and the defaults are right often enough that reaching past them signals a specific problem.

ParameterTypeRequired
max_resultsintoptional

1..=1000, server-enforced. What it bounds is prompt budget, not quality — Brain has already decided which memories answer the cue. Six to ten for a chat turn; more makes the prompt longer, not better.

subjectstroptional

Narrow to a known entity, when the chain already knows what it is about rather than hoping the cue carries it. Anchors the graph retriever.

scope"space" | "namespace"optional

"space" by default. "namespace" fans out across every space in the namespace and merges the hits — a deliberate cross-user read, and almost never what a per-user chain wants.

include_tracebooloptional

The read pipeline, as a JSON string. Free when off, and large when on — a three-hit recall over ~700 memories measured 121 KB, because it reports every candidate each lane considered. Switch it on for one request when chasing a bad answer; never for a chain in production.

Identity

LangChain's thread_id is not a Brain scope, and conflating them is the expensive mistake here.

A thread_id identifies a conversation to the checkpointer. Brain's scope is the (namespace, space) its credential resolves to — there is no user_id argument on any verb and no HTTP route accepts a selector. So the adapters above are already scoped by the client they were constructed with.

# The client carries the identity. Build it where you resolve the session,
# not once at import.
def store_for(user) -> BrainStore:
    return BrainStore(BrainHttpClient(key_for(user), base_url=BASE_URL))
One module-level client serves one tenant

The natural LangChain shape is a module-level brain = BrainHttpClient(...) closed over by every tool. In a single-tenant app that is correct. In a multi-tenant one it means every user's memories land in one space, and the app works — it just has no isolation. Nothing errors, and search returns other tenants' facts as perfectly good answers.

Resolve the credential per request. whoami reports what the server resolved, so it cannot agree with a mistake.

For pooled-key multi-tenancy — one credential, the space selected per request — you need act_as, which is wire-tier only. The HTTP client cannot do it. See Identity from a JWT.

The write policy is the whole game

No framework will give you this, and it decides whether the integration is worth having in six months.

Never write the model's output back

# WRONG — and it is the default shape of every memory adapter.
def save_turn(user_msg: str, ai_msg: str) -> None:
    brain.encode(user_msg)
    brain.encode(ai_msg)        # ← poisons the next recall

A model's reply is not an observation about the user. Store it and the next recall feeds the model its own words, so a wrong answer becomes a "fact" the next turn retrieves and repeats — with the confidence of something that came out of memory rather than out of a guess. The legacy saveContext hook took both turns, which is why this is worth stating plainly.

Do not write on every turn

saveContext fired every turn, and the modern equivalents invite the same thing. Porting that unchanged fills the space with conversation-shaped text that has no clean subject — which extraction cannot type and recall then has to rank around.

def after_turn(user_msg: str) -> None:
    if not is_durable(user_msg):
        return
    brain.encode(restate(user_msg))     # third person, standalone

is_durable can be a classifier, an explicit user signal, or a rule as crude as "contains a preference verb". Anything is better than "always". See What to write.

Recall before you write, not after

answer = brain.recall(user_msg)     # 1. read the state BEFORE this turn
reply = chain.invoke(...)           # 2. answer
if is_durable(user_msg):            # 3. then write
    brain.encode(restate(user_msg))

Encoding first and recalling with the same text returns the sentence you just stored as the top hit. It looks exactly like retrieval working perfectly, which is what makes it hard to notice.

Errors and degradation

The SDK raises one error type, and most memory calls are an enhancement rather than a precondition.

from brain_db_sdk.http import BrainHttpError

def _get_relevant_documents(self, query: str, *, run_manager=None) -> list[Document]:
    try:
        answer = self.brain.recall(query, max_results=self.max_results)
    except BrainHttpError as err:
        # A chain that answers without memory beats a chain that 500s.
        logger.warning("brain recall failed: %s %s", err.status, err.code)
        return []
    ...
Returning `[]` on an error is not the same as returning `[]` on `none`

Both produce an empty document list, and your prompt cannot tell them apart — so a degraded Brain silently becomes "the user has no history". If that distinction matters, surface it: a sentinel document, a flag on the state, or a direct recall at that call site instead of the retriever.

The client already retries transport failures, 429 and 503 three times with backoff. Do not wrap it in another retry loop — that gives you nine attempts and a worst case in the tens of seconds, inside a chain that is probably behind a request timeout.

Testing

Stub at the client, not at the HTTP layer:

from unittest.mock import MagicMock
from brain_db_sdk.http.types import RecallResult

def test_retriever_returns_nothing_when_brain_knows_nothing():
    brain = MagicMock()
    brain.recall.return_value = RecallResult(answer_kind="none", memories=[])
    assert BrainRetriever(brain=brain).invoke("anything") == []

Build the real RecallResult rather than a bare MagicMock for the return value — a mock answers .answer_kind with another mock, which is truthy, so a test of the empty path passes without exercising it. And use the lowercase "none": that is what the HTTP tier returns, and a test written against the wire tier's "None" asserts a string your code will never see.

What the framework shape gives up

Not reachable through a store or retrieverWhere it lives
The membership verdict, beyond "empty or not"recall directly
Corrections and supersessionHandling corrections
The typed graph — entities, statements, relationsThe typed graph
Evidence for an answerFaithfulness checking
The retrieval traceinclude_trace on a direct call

None of that is a reason to avoid the adapters. It is a reason to keep the SDK client reachable from the rest of your code — they are the same client, and they coexist happily.

01
What to write

The decision no framework makes for you.

02
Chat memory

The same loop without a framework, in detail.

03
Brain over MCP

The tools option, as a protocol rather than a library.

See also
recall() referenceEvery option, and the verdict in full.Identity by keyWhy thread_id is not a scope.Support bot recipeThe same encode/recall loop, framework-free.

Was this page helpful?

FastAPI

Brain in a FastAPI service — choosing the sync HTTP tier or the async wire tier, why the sync client blocks the event loop, lifespan and dependency wiring, per-tenant identity with act_as, streaming, and error mapping.

OpenAI

Brain as the long-term memory layer behind the Responses API — the flat tool shape, the dispatch loop, where Conversations end and memory begins, and why identity must never come from a tool argument.

On this page

Brain replaces one of LangChain's two memory layersThe legacy memory classes are goneOption A — Brain as a long-term storeOption B — Brain as a retrieverOption C — Brain as agent toolsChoosing between the threePutting it togetherTuning the readIdentityThe write policy is the whole gameNever write the model's output backDo not write on every turnRecall before you write, not afterErrors and degradationTestingWhat the framework shape gives up
Suggest an editOpen in Playground