Brain Docs

Reference

Integrations

Frameworks

Next.jsFastAPILangChainOpenAI

Protocol

Brain over MCP
Brain/Docs
✦ ASKBrain on GitHubDashboard
IntegrationsOpenAI

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.

PURPOSE

OpenAI's Conversations hold a thread. Brain holds what should outlive one. This page wires them together on the Responses API: the function-tool shape, the dispatch loop, pre-fetching versus tool-driven recall, and the identity rule that is the only genuinely dangerous part of this integration.

◇Prerequisites

An OpenAI API key, a Brain API key, and a backend to point at. If encode and recall are new, read Your first memory first.

The Assistants API is gone — this page used to describe it

OpenAI deprecated the Assistants API on 26 August 2025 and sunset it on 26 August 2026. It is no longer available, and there is no provider-level rollback: an app still calling client.beta.assistants is broken rather than deprecated.

The replacements are the Responses API and the Conversations API, and the mapping is:

AssistantsNow
An Assistant (model, tools, instructions)A Prompt — versioned configuration
A RunA Response
A ThreadA Conversation
submit_tool_outputs on a runA function_call_output item on the next response

OpenAI ships no automated Thread → Conversation migration; the guidance is to start new threads as conversations and backfill only what you need.

Where the line falls

A Conversation is the transcript of one thread. Brain is everything that should still be true next month, in a different thread, possibly in a different product surface.

STORES02 STAGESTOOLS02 STAGESreadwriteConversation (one thread)Brain memories (durable)brain_recall → recall()brain_encode → encode()
Conversations hold the current thread; Brain holds what outlives it. The dispatch loop bridges them through function tools that call the SDK's encode and recall verbs.

Do not put the transcript in Brain

A Conversation needs exact, ordered replay. Brain ranks by resemblance to a cue and returns a membership verdict — it answers questions, it does not reproduce transcripts. Writing every turn into it gives you a space full of dialogue with no clean subject, which extraction cannot type and recall then has to rank around.

Tool definitions

The Responses API uses a flat function shape. This is the single most common porting error from Chat Completions, which nests the definition under a function key.

tools = [
    {
        "type": "function",
        "name": "brain_recall",
        "description": (
            "Answer a question from the user's long-term memory. Returns the "
            "memories that answer the cue, or an explicit 'nothing stored' "
            "when the answer is not known."
        ),
        "parameters": {
            "type": "object",
            "properties": {
                "query": {"type": "string", "description": "What you want to know."},
                "max_results": {"type": "integer", "minimum": 1, "maximum": 20},
            },
            "required": ["query"],
            "additionalProperties": False,
        },
    },
]
The Chat Completions shape is silently wrong here
# Chat Completions — NESTED. Rejected by Responses.
{"type": "function", "function": {"name": "brain_recall", "parameters": {...}}}

# Responses — FLAT.
{"type": "function", "name": "brain_recall", "parameters": {...}}

Copying a tool array across from an older integration produces a schema error, not a silently ignored tool — which is the good outcome. The bad one is copying the dispatch half, where role: "tool" messages are replaced by function_call_output items and nothing errors; the model simply never sees the result.

There is no user_id argument, and there must not be one

Notice what the schema above does not contain. The identity is the Brain credential your dispatcher holds, resolved server-side. See Identity below for why adding one would be a vulnerability rather than a convenience.

The dispatch loop

import json
import os

import openai
from brain_db_sdk.http import BrainHttpClient, BrainHttpError

oai = openai.OpenAI()


def answer(user, conversation_id: str, message: str) -> str:
    # The credential carries the scope. Resolve it per caller, never once at
    # import, and never from anything the model produced.
    brain = BrainHttpClient(key_for(user), base_url=os.environ["BRAIN_BASE_URL"], timeout=10.0)

    response = oai.responses.create(
        model="gpt-5",
        conversation=conversation_id,
        input=[{"role": "user", "content": message}],
        tools=tools,
        instructions=(
            "You have long-term memory through brain_recall. Call it before "
            "answering anything about the user. If it reports nothing stored, "
            "say you do not know rather than guessing."
        ),
    )

    while True:
        calls = [item for item in response.output if item.type == "function_call"]
        if not calls:
            return response.output_text

        outputs = [
            {
                "type": "function_call_output",
                "call_id": call.call_id,
                "output": dispatch(brain, call),
            }
            for call in calls
        ]

        response = oai.responses.create(
            model="gpt-5",
            conversation=conversation_id,
            previous_response_id=response.id,
            input=outputs,
            tools=tools,
        )


def dispatch(brain: BrainHttpClient, call) -> str:
    args = json.loads(call.arguments)
    try:
        if call.name == "brain_recall":
            answer = brain.recall(args["query"], max_results=min(args.get("max_results", 6), 20))
            if answer.answer_kind == "none":
                # An explicit sentence, not an empty string. See below.
                return "Nothing stored answers that."
            return "\n".join(f"- {m.text}" for m in answer.memories)
        return f"error: no such tool {call.name}"
    except BrainHttpError as err:
        # A tool failure is not a run failure.
        return f"Memory is unavailable right now ({err.code}); answer without it."

Three details the happy path leaves out.

call_id, not id. The output item must carry the call_id from the model's function_call, or the model cannot pair a result with the call that asked for it. With parallel tool calls that pairing is the only thing keeping two results apart.

A none verdict is an answer — return it as one. Submitting an empty string invites the model to fill the gap from its own weights. Submitting "Nothing stored answers that." tells it what actually happened, which is what makes "I don't know" reachable.

A tool error is not a run failure. Brain being briefly unavailable should submit an output saying so, not raise out of the loop. The model can then tell the user it could not check, rather than answering confidently without memory.

Tool-driven or pre-fetched

Two ways to get memory into a response, and most deployments want both.

Tool-driven
Pre-fetched
Who decides
The model, when it judges it needs context
Your code, before the call
Round trips
At least two per turn that uses memory
One
Follow-up
Can refine the cue and ask again
One shot; the cue is whatever you chose
Failure mode
The model does not call it, and nobody notices
You fetched the wrong thing, visibly
Context cost
Tool definitions plus every result
Only what you injected
# Pre-fetched: one call, the cue is yours.
answer = brain.recall(message, max_results=6)
context = (
    "No stored memories are relevant."
    if answer.answer_kind == "none"
    else "\n".join(f"- {m.text}" for m in answer.memories)
)

response = oai.responses.create(
    model="gpt-5",
    conversation=conversation_id,
    input=[{"role": "user", "content": message}],
    instructions=f"What is known about this user:\n{context}",
    tools=tools,            # still registered, for follow-up
)

A shape that works well: pre-fetch a default block and keep brain_recall registered for the model to dig further. You get a deterministic baseline and the agent keeps the ability to ask a better question than you guessed.

In TypeScript

The same loop. The one difference worth noting is that output_text is a convenience getter in both SDKs, and the tool items are discriminated on type rather than duck-typed.

import OpenAI from "openai";
import { BrainHttpClient, BrainHttpError } from "@brain-db/sdk/http";

const oai = new OpenAI();

export async function answer(user: User, conversationId: string, message: string) {
  const brain = new BrainHttpClient({
    apiKey: await keyForUser(user),
    baseUrl: process.env.BRAIN_BASE_URL,
    timeoutMs: 10_000,
  });

  let response = await oai.responses.create({
    model: "gpt-5",
    conversation: conversationId,
    input: [{ role: "user", content: message }],
    tools,
  });

  for (;;) {
    const calls = response.output.filter((item) => item.type === "function_call");
    if (calls.length === 0) return response.output_text;

    const outputs = await Promise.all(
      calls.map(async (call) => ({
        type: "function_call_output" as const,
        call_id: call.call_id,
        output: await dispatch(brain, call),
      })),
    );

    response = await oai.responses.create({
      model: "gpt-5",
      conversation: conversationId,
      previous_response_id: response.id,
      input: outputs,
      tools,
    });
  }
}
A MemoryHit carries bigints

createdAtUnixNanos is a bigint — nanosecond timestamps exceed Number.MAX_SAFE_INTEGER, so the SDK parses them as bigints rather than rounding. JSON.stringify throws TypeError: Do not know how to serialize a BigInt on one, which means returning a raw MemoryHit as a tool output fails at runtime, not at compile time. Format to a string as the dispatcher above does, and you never meet it.

Errors

The SDK raises one error type, and the question that matters for a tool loop is whether to retry, tell the user, or tell an operator.

CodeStatusRetry
transport0fatal

No answer at all — DNS, connection refused, or the client timeout fired. Usually a wrong or unset BRAIN_BASE_URL. Already retried by the SDK.

unauthorized401fatal

The Brain key is missing, malformed or rejected. Your configuration, not the user's request — do not surface it to the end user.

llm_credential.missing409fatal

No provider credential registered for the namespace, so the extraction pipeline's LLM tier cannot run. A 409 rather than a 503 precisely because retrying will never fix it: a human registers a key.

quota.exceeded429retriable

A plan ceiling at the edge. Honour Retry-After.

engine.unavailable503retriable

Brain is restarting, overloaded or rate-limiting. The SDK retries this for you on idempotent verbs.

Return the condition, do not raise it

Every one of these should become a function_call_output the model can read. Raising aborts the response and the user gets nothing; returning "Memory is unavailable right now (engine.unavailable); answer without it." gets them an answer plus an honest caveat. Branch on code, never on message.

Do not add your own retry loop

The client already retries — three attempts, 100 ms base backoff doubling to a 2 s cap, on transport failures, 429 and 503. Wrapping a tool call in another three-attempt loop gives you nine attempts and a worst case measured in tens of seconds, inside a turn the user is waiting on. Tune the policy instead: retry={"max_attempts": 2} on the client.

Migrating an Assistants integration

If you are arriving from a broken Assistants app, the Brain half barely changes — it was always encode and recall behind two function tools. What changes is everything around it.

{"type": "function", "function": {…}} becomes {"type": "function", "name": …, "parameters": …}. This one errors loudly, which is the easy case.

There is no run to submit against. You create a new response whose input is a list of function_call_output items, each carrying the call_id from the model's call. This is the one that does not error — a role: "tool" message is accepted and simply never seen as a tool result.

No queued / in_progress / requires_action state machine. A response either comes back with tool calls in its output or it does not, and the loop above is the whole thing.

OpenAI ships no automated migration. Start new threads as conversations and backfill only what a user would notice losing.

It did not change and it is still the dangerous part: the Brain credential comes from the authenticated request, never from a tool argument.

Identity

This is the part that is genuinely dangerous, and it is a Brain scoping question rather than an OpenAI one.

A Prompt is a shared definition; a Conversation is per user. Your dispatcher has to attach the right Brain identity to each tool call, and there are two honest ways:

OptionTypeDefault / Env
A client per userone key each

Construct a BrainHttpClient with that user's key when you handle their turn. Isolation is structural — a key cannot address another user's space — and you are running key lifecycle for every signup.

One principal, act_aswire tier only

One pooled credential with the space selected per request. The production shape at scale, and act_as does not exist on the HTTP API — it needs the wire client, and therefore a long-lived process.

Never take the identity from the tool call

The model produces the arguments. If your dispatcher reads a user id, tenant slug or workspace name out of them, then a model that hallucinates one reads another tenant's memory — and reports it as a confident answer, because from the model's side the tool succeeded.

This is not hypothetical prompt-injection paranoia: it is the ordinary failure mode of a model filling in a plausible-looking required field. Take the identity from the request's authenticated context, which you already resolved before you called OpenAI, and nowhere else. The tool schema should not have a field for it, so there is nothing to read.

Brain's side of this is structural rather than conventional: there is no scope argument on any HTTP route, so even a dispatcher that wanted to forward a model-supplied tenant id has nowhere to put it. whoami reports what the server resolved, so it cannot agree with a mistake.

Context cost

Every tool output lands in the conversation and is re-sent on each subsequent turn of that thread. Three rules:

  • Keep max_results small. Six hits is usually plenty. The server caps it at 1000, which is not an invitation — max_results bounds prompt budget, not answer quality, because Brain has already decided which memories answer the cue.
  • Clamp what the model asks for. The schema says maximum: 20; the dispatcher above also applies min(..., 20), because a schema is a suggestion to a model and a clamp is not.
  • Never enable the retrieval trace on this path. include_trace returns the whole read pipeline — a three-hit recall over ~700 memories measured 121 KB. Useful in a debug endpoint, ruinous in a conversation that replays on every turn.

What to register, and what not to

Registering the write verb at all is a choice. An agent that can call brain_encode 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.

# The read tool, registered. The write, deliberately not.
if is_durable(message):
    brain.encode(restate(message))      # after the turn, under a policy you can test

A common production shape is read tool only, with writes from your own code after the response completes. You keep the useful autonomy — the model can ask what is known whenever it likes — and remove the one failure nothing alerts on.

And never write the model's reply back

Whichever shape you pick, store what the user said, not what the model answered. A reply is not an observation about the user; store it and the next recall is fed the model's own words, so a wrong answer becomes a "fact" the next turn retrieves and repeats — now with the authority of memory. See What to write.

Streaming

responses.create(stream=True) emits the function call as it is produced, so the dispatch loop can start before the model finishes. Two things to know:

  • Accumulate the arguments. They arrive as deltas; call.arguments is only complete at the response.completed event. Parsing early gives you truncated JSON.
  • The tool round trip is a second request. Streaming does not remove it — you still submit function_call_output items and create another response. Budget two round trips for any turn that touches memory, which is the real argument for pre-fetching on latency-sensitive paths.

Compressing a thread when it ends

When a Conversation is finished, the turns are still raw dialogue. One durable memory is usually worth more than fifty fragments: recall the thread's material, summarise it with your model, and encode the summary as a single standalone claim. The Session summary recipe is the whole pattern.

01
What to write

The decision the write tool hands to the model, and why to take it back.

02
Session summary

Compressing a finished thread into one memory.

03
Brain over MCP

The same tool shape as a protocol, for clients you do not control.

See also
Identity by keyWhy there is no scope argument for a model to fill in.recall() referenceEvery option, and the verdict in full.Multi-tenancyOne space per customer, and the act_as tier.

Was this page helpful?

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.

Brain over MCP

@brain-db/mcp exposes Brain's tenant surface as 49 Model Context Protocol tools over stdio or remote Streamable HTTP — the transports, the tool surface, the four-line error contract, and the identity model that makes one public deployment safe.

On this page

Where the line fallsTool definitionsThere is no user_id argument, and there must not be oneThe dispatch loopTool-driven or pre-fetchedIn TypeScriptErrorsMigrating an Assistants integrationIdentityContext costWhat to register, and what not toStreamingCompressing a thread when it ends
Suggest an editOpen in Playground