Import:
from gaia.agents.base.memory import MemoryMixin
Import: from gaia.agents.base.memory_store import MemoryStore
Import: from gaia.agents.base.discovery import SystemDiscoveryArchitecture
The memory system has three layers:MemoryMixin
The primary integration point. Add this mixin to any Agent subclass to give it persistent memory.Inheritance Order
MemoryMixin must come before Agent in the class declaration. This is required because MemoryMixin overrides process_query and _execute_tool, both of which call super() to reach the Agent base class. If Agent is listed first, both overrides are silently shadowed.
init_memory()
Initialize the memory subsystem. Call this beforesuper().__init__().
v2 startup sequence:
- Open/create DB, apply schema migrations (v1 → v2: adds
embedding BLOB,superseded_by TEXT,consolidated_at TEXT) - Validate Lemonade embedding service connectivity — raises
RuntimeErrorif unreachable - Backfill embeddings for items missing them (up to 100 per startup)
- Rebuild FAISS index from stored embeddings
apply_confidence_decay()— 30-day decayreconcile_memory()— Hindsight-inspired, max 20 pairsconsolidate_old_sessions()— max 5 sessions, windowed (see Consolidation)start_skill_synthesis()— distill repeated workflows into procedural memory, on a background threadprune()— 90-day hard delete. Runs after consolidation; queued sessions are held only until their turns reach 180 days- Generate session UUID
init_memory(). Pruning follows them there so eligible conversations get a chance to be distilled before deletion.
Skill synthesis is the one step that does not run inline: start_skill_synthesis() hands it to a background thread, because a distillation call is seconds of model time and would otherwise land in front of the user’s first answer. Each pass reads only the history no earlier pass consumed (a watermark in the meta table plus per-episode marks in synthesis_marks), and spends at most max_distill_calls_per_pass model calls — 2 by default — leaving the rest for the next session. wait_for_skill_synthesis(timeout) joins the pass; _synthesize_skills(force=True) or MemoryStore.reset_synthesis_progress() re-opens history it already consumed.
A stored procedure’s success_count is its lineage’s track record, not one pass’s. Each pass adds only the episodes the matched row was not built from, so a later batch can still supersede a stale procedure, and re-reading history — a forced pass, or the first pass after a reset — counts each session once.
After adoption the record keeps counting. In a turn that recalled a procedure, the person’s answers to prompts for the tools in its tools_required are its outcome: any decline adds a failed attempt, approvals with no decline add a successful one (MemoryStore.record_skill_outcome, which also counts provenance.outcomes and provenance.outcome_successes). Only a prompt the console reports as shown and answered (note_prompt_answered) counts, so auto-approval, Accept edits, standing grants, timeouts and unattended refusals count nothing. Once a procedure has MIN_OUTCOMES_TO_RETIRE (3) outcomes since it was learned, a failure that takes its rate in runs below min_success_rate disables it (MemoryStore.disable_skill), logged at WARNING; each session it was learned from counts as one success and each outcome as one attempt, so its birth tool-call counts cannot outweigh the declines. Outcomes a row counted before approvals were counted (provenance.unscored_outcomes) are left out of that rate and of the three. A supersede carries the outcomes to the new row, and a session where a step was declined is never clustered into a procedure.
get_memory_system_prompt()
Returns the stable memory section, frozen for the session. Always includes proactive usage instructions for the LLM, plus any stored preferences, facts, skills, and error patterns. Nothing time-sensitive. This method is called automatically byAgent._get_mixin_prompts(). It is in Agent.VOLATILE_PROMPT_FRAGMENTS, so it is sent in the session context at the start of the first user message, not in the system prompt (see Session context).
set_memory_context(), reset_memory_session(), and a forget or update_memory call on an item it shows — so a forgotten memory leaves the prompt at once. Always returns a non-empty string — even with zero stored memories, the instructions block is included so the LLM knows it has persistent memory tools. Example output (with stored memories):
- Includes items from every context when the active context is
global(the default), otherwiseglobal+ the active context - Excludes items where
sensitive=1 - Excludes items where
superseded_by IS NOT NULL(only current/active items) - Covers preferences, facts, skills, errors, reminders and notes; lessons have their own section, and session summaries (consolidation notes) are left out because their dated history would contradict newer facts — they stay recallable. A reminder whose due day has passed is left to the upcoming/overdue path, and a reminder shows its due date
- Most recently confirmed first (the store is read in that order, not by confidence), so a fact that changed outranks the one it replaced
- No per-category limit: the categories take turns, one item each, until the 4250-char cap (
STABLE_MEMORY_PROMPT_CHARS, instructions included) is full. An item too long for what is left is skipped whole, and a closing line says how many were left out so the model knows torecallthem - Confidence scores are not shown, so the model doesn’t discount a true fact that was extracted rather than stated
get_memory_dynamic_context()
Returns the per-turn dynamic context that is prepended to the user message each turn. Contains the current time, upcoming/overdue items, the stored memories most relevant to the user’s message, lessons learned this session, and any learned procedures recalled for this goal.process_query closes the block before the user’s text, so a short message is never read as the block’s last line (and refused as an instruction planted in memory). The model receives:
frame_user_message() in gaia.agents.base.history builds this shape and user_text_of() strips it back to the user’s text; stored history keeps only the user’s text.
Recalled procedures (procedural memory) ride here too, under a === RECALLED PROCEDURES (learned from past successful runs) === heading, whenever a stored procedure matches the goal. The matched set changes from turn to turn, so it never goes in the system prompt. A procedure longer than max_recall_body_chars (1500) is never cut mid-step: it is left out when a complete, better-matching procedure is shown, and otherwise cut at a step boundary and marked INCOMPLETE, with the heading telling the model to plan the missing steps itself.
Relevant memories come from a vector search on the user’s message: at most TURN_RECALL_TOP_K (3) items of category fact, preference, note, skill or error. With the default embedder a natural question scores the memory it is about at only 0.35-0.55 and unrelated ones at 0.25-0.40, so no fixed floor works. A match passes on a cosine of at least 0.5, or, once the store holds 8 or more memories, on clearing all three of 0.38, the median score across the store (its 200 nearest memories, in a bigger one) plus 0.08, and the best match minus 0.06. Up to two more memories (cosine 0.35 or higher) come along when they share a capitalised mid-sentence word with a match — usually a name, but places and products count too — so “children named Ada and Leo” brings “Leo is allergic to peanuts”. Sensitive items, items already in the stable memory section, and items from other contexts are skipped; a default global session is unscoped and reads every context. Lessons (domain='lesson') are skipped here whatever the scope — they are filed as notes but belong to one workspace, and their own path scopes them and frames their raw tool output against injection. Credential-shaped content is masked. Surfacing a memory here does not bump its confidence or use count. If the embedding call fails, the section is left out and a warning is logged. Returns an empty string only if init_memory() has not been called.
The upcoming/overdue section is rate-limited, not per-turn. It rides the first turn of a session and the first turn after REMINDER_PAUSE_SECONDS (30 min) of silence — a natural pause — so an [OVERDUE ...] block never lands on an unrelated turn.
Anything included is marked as raised immediately, by the agent loop:
reminded_atis written to the store, soget_upcoming()skips it in later sessions. An overdue item is therefore volunteered once. It stays fully recallable —recall(category='reminder')still returns it. An item due in the future gets one nudge per session, sincereminded_atis still earlier thandue_at.- The id is also held in memory for the session, so a store that cannot be written (incognito) still gets no repeats.
reminded_at and should not — prompt-based enforcement of this was unreliable, which is why it moved into code.
register_memory_tools()
Registers the 5 LLM-facing memory tools with the agent’s tool registry. Call this from your agent’s_register_tools() method.
remember, recall, update_memory, forget, forget_everything, search_past_conversations.
set_memory_context()
Switch the active context mid-session. Affects which memories the session context includes and the context newremember calls are stored under.
run_bootstrap_conversation()
Run the adaptive day-zero onboarding conversation and store the approved answers. This is the entry point for populating an empty memory — the CLI’sgaia memory bootstrap --chat-only runs the same engine.
[Y/n/q]) before it is written, with source="user" and confidence=0.8 — identity answers as profile/global, work answers as fact/work with an entity link (e.g. app:vscode). Only Y or a bare Enter stores an entry; an answer that is not Y, n, or q is re-asked rather than treated as approval. Each stored entry is embedded immediately on this path.
Returns a BootstrapResult:
Raises
RuntimeError if memory is disabled for the session (embedding service unreachable, or GAIA_MEMORY_DISABLED=1) — use gaia memory bootstrap --chat-only, which onboards without an embedder — or if an approved entry cannot be stored or embedded. A prompt_fn may raise BootstrapCancelled to abort; entries approved before the abort remain stored.
The engine lives in
gaia.agents.base.bootstrap as a pure function over an injected MemoryStore plus injected IO — no LLM, no console. run_bootstrap_conversation(store, prompt_fn=..., output_fn=..., on_stored=None) is how the CLI drives onboarding on a machine with no embedding backend.reset_memory_session()
Start a fresh memory session. Generates a new session ID and applies confidence decay to unused knowledge.Properties
Embedding Pipeline
These methods handle the vector embedding pipeline for hybrid search. All are internal (_-prefixed) — you do not call them directly.
LemonadeProvider for embedding. Cached for the process lifetime. Raises RuntimeError if Lemonade is unreachable.
user.embeddinggemma-300m-GGUF. Returns a normalized numpy array suitable for cosine similarity via FAISS IndexFlatIP.
The store records which embedder produced its vectors. When that differs from the active embedder — or is missing, as in memory written before v0.22.0 with the retired
nomic-embed-text-v2-moe-GGUF — the stored vectors are cleared and re-embedded on the next agent start (or dashboard rebuild), with a warning in the log. Vectors from two models are never mixed in one index.init_memory() startup. Returns the number of items backfilled.
Hybrid Search
- Embed query via Lemonade (
user.embeddinggemma-300m-GGUF, 768-dim) - FAISS cosine search: top-K × 4 candidates (oversample)
- FTS5 BM25 search: top-K × 4 candidates (oversample)
- Deduplicate by ID, apply RRF weights:
0.6 / (60 + rank_vector) + 0.4 / (60 + rank_bm25) - Return the top-K results by fused score
- Bump confidence +0.02 and increment
use_counton the results returned — not on every candidate, and not at all withcount_as_use=False, which extraction’s lookup of what is already known passes. A lookup nobody asked for must not make an old memory look more trusted every turn, or stale facts out-rank new ones in the session context
Complexity-Aware Recall Depth
top_k value — no LLM call needed, purely heuristic:
Mem0-Style LLM Extraction
tool_record is only checked against (see below).
The extraction fetches top-10 relevant existing items first via
_hybrid_search(), so the LLM can see what already exists and decide whether to add, update, delete, or do nothing. This replaces v1’s regex-based heuristic extraction.
A delete is kept only when the turn contradicts that memory, so a model that reads “forget X” cannot point it at another one. It is dropped when the user’s own forget or forget_everything removed something this turn (user_forgot; a forget that failed doesn’t count), when its id was not among the items the model was shown, or when the memory shares fewer than two content words with the user’s message (content_stems; one, if the memory has only one). A kept delete refuses system/profile/permission rows and goes through MemoryStore.delete(), not forget(): the memory was replaced, not forgotten, so older chats about it stay searchable. Each dropped or applied delete is logged by id, never by content. On a turn that asks to forget something, an add or update whose content words all come from that request (“forget that I am allergic to mango” → “Allergic to mango”) is dropped, whether or not the forget worked, so the turn never saves again what it asked to remove. The request ends its clause at “since”, “because”, or “as I…”, so “remove the peanut cookies since I’m allergic to peanuts” still saves the allergy. A “don’t”, “not”, or “never” anywhere before the verb in its clause (“Never, ever forget X”, “I don’t want you to forget X”) is a request to remember and is unaffected, and so is a question that isn’t a “can/could/would/will you” request (“Did you forget X?”).
Memory holds what is true about the user, not the subject of the conversation. grounded must be "user" (the user said it about themselves); an op grounded in anything else is dropped. A document’s contents, a search result, the weather, or the assistant’s answer are not facts about the user, and stored as one they are replayed in every later chat as if the user had said them (#5027).
Because the model labels lifted content "user" too, an add or update whose words come from the assistant’s answer or a tool’s arguments and result rather than the user’s message is dropped as well (_copied_from_material). An op that repeats something the user forgot after saying it is dropped (see Forgetting).
Error handling: Invalid JSON → logged warning carrying the reply’s length and opening characters, skip this turn. Timeout (EXTRACTION_TIMEOUT_S, 60s) → logged warning; the call is abandoned and whatever it eventually returns is discarded. Individual operation failure → logged, continue with remaining operations. No fallback to regex heuristics.
Background extraction
Extraction runs after the turn returns, not before it._after_process_query() schedules the job and returns immediately, so the answer is on screen while the model call is still in flight.
It yields to the user. A queued job does not start while a user turn is running, or until
EXTRACTION_IDLE_S has passed since the last one ended. A queue that reaches EXTRACTION_QUEUE_MAX starts at once instead, so holding never drops a turn. Extraction shares the local model with the conversation, so a job started the moment a turn ended made a quick follow-up queue behind it. A job already running when a user turn starts is stopped (#5022): its model call streams with AgentSDK.send_messages(cancel=...), the new turn sets the event, and the stream is closed (on the NPU it is read to its end instead, for up to 60 s, because FastFlowLM restarts when a reply is cut off). A job cancelled while it still waits for the model is never sent. Nothing partial is stored, and the job goes back to the front of the queue to rerun once the user is idle. A flush from wait_for_memory_extraction is never stopped. Its model call is kept out of the turn’s metrics (AgentSDK.side_request()), so a turn’s recorded stats are its own.
One extraction thread per agent. Each job freezes the turn’s text and context at turn end, so mutating the agent afterwards cannot change what gets extracted.
Waiting for it. Anything that exits right after a turn must drain first, or the last turn’s facts die with the process:
True when nothing is left in flight. Waiting also skips the idle window, so queued jobs run at once. A host that exits without calling either still gets the same drain from an atexit hook; only a hard kill (os._exit, SIGKILL) drops held jobs. drain_memory_extraction() is a no-op on an agent without memory, so it is safe to call unconditionally. The CLI chat paths call it from their cleanup block, which covers the one-shot, interactive, Ctrl-C and error exits alike; the Agent UI needs no change, because signal_done() follows process_query(), which no longer waits. The TUI’s agent drains when the TUI closes its stdin on quit, and the TUI gives it up to 20 s to exit (printing “Saving memories before exit…” after the first second) before killing it.
Consolidation
prune().
Returns: {"consolidated": int, "windows": int, "extracted_items": int} — consolidated counts sessions that made progress, windows the turn windows distilled across them.
Criteria for consolidation:
- All turns in the session are > 14 days old
- Session has ≥ 5 turns
- At least one turn has
consolidated_at IS NULL
- Take the oldest 20 turns with
consolidated_at IS NULL— one window (get_unconsolidated_turns()) - Call LLM with consolidation prompt → returns summary + extracted knowledge
- Store summary as
knowledge(category="note", source="consolidation", domain="session:{id[:8]}") - Store each extracted item via
store()(normal dedup applies;system/profile/permissionitems are dropped, and so is an item whose words come from the assistant’s lines rather than the user’s, one the user forgot after the window was said, one a current memory already says (is_current, whatever its entity tag), and one the user changed after the window (changed_since) — an old chat states what was true then) - Mark exactly that window’s turns with
consolidated_at = now— only after steps 2–4 succeed. A failed window stays unmarked and is retried next run - Repeat until complete or a budget is reached: ten windows per session, five model calls total, or ten seconds elapsed across the run. An in-flight call finishes; remaining windows resume next run
prune() holds its old turns until then, with an absolute ceiling of twice the retention window (180 days by default), including sessions whose model calls always fail or that stay active.
Forgetting
A forgotten memory is not learned again from old conversations (#4730). Theforget tool and the Memory page’s Forget call MemoryStore.forget(), which deletes the row and records its content and the time in the forgotten table, in one transaction. A sensitive row, or a copy of one, keeps only its word stems there, and is never named in a prompt. The conversation that stated the fact stays in the log, so consolidation could otherwise distil it again. Instead each consolidation window is told what the user forgot after the window began (get_forgotten(said_before=...)), so a forget later in the same chat counts and the model skips reworded copies and leaves them out of the session summary. Any item that is the same memory (is_forgotten), or summary that repeats one (mentions_forgotten), is dropped. Extraction applies the same check from the moment the turn started, so a forget made by that turn’s own tools counts.
Something the user says after forgetting it is the user telling GAIA again, and is learned as usual; storing it from a teaching source (user from the Memory page, tool from remember) also clears the forgotten record. A plain delete() — used when newer information replaces a memory — records nothing, and neither does deleting one of GAIA’s own records (a tool lesson or session summary) from the Memory page: DELETE /api/memory/knowledge/{id} forgets only rows is_about_user() accepts.
search_past_conversations applies the same rule to what it returns: a turn that repeats something forgotten after it was said (mentions_forgotten(content, said_before=timestamp)) is left out, and the result counts it as forgotten_hidden. A recall with no filter holds back sensitive rows, so it says how many it held back (sensitive_withheld); any filter lists them. forget_everything calls MemoryStore.clear_all() (every row, sensitive ones included, the conversation log and tool history) and is in TOOLS_REQUIRING_CONFIRMATION, so the user approves it first. Each erase raises a counter (MemoryStore.erase_count()). A turn, extraction job or consolidation window reads it when it begins, and once it has moved (erased_since(count)) nothing more from that work is stored: no conversation turn or tool-history row (store_turn and log_tool_call take erase_count), no extracted, consolidated or auto-learned memory. Every other agent on the same store drops its frozen memory prompt and vector index at the start of its next turn. Learned procedures, skill deltas and synthesis marks are kept, as is deleted_sessions; a synthesis mark loses its session goal text.
Reconciliation
system, profile, and permission rows are excluded before model classification; normal confidence bookkeeping during recall is unchanged. Detects and resolves contradictory, reinforcing, or weakening facts that were never co-retrieved during extraction. Called on startup after decay, before consolidation.
Returns: {"pairs_checked": int, "reinforced": int, "contradicted": int, "weakened": int, "neutral": int}
Process:
- For each context, compute pairwise embedding similarity among active items
- Flag pairs with cosine similarity > 0.85
- For each flagged pair, a single LLM call classifies the relationship:
Rate-limited to
max_pairs classifications per startup (~20s on local LLM). Highest-similarity pairs processed first.
Lifecycle Hooks
MemoryMixin hooks into the Agent lifecycle at 3 points. These are automatic — you do not call them directly. Hook 1:process_query() override
Prepends per-turn dynamic context (time + upcoming items) to the user message. Saves the original user input so _after_process_query can store the clean version without the context prefix.
Hook 2: _execute_tool() override
Wraps every non-memory tool call to auto-log it to tool_history. If a tool runs and fails, the error is automatically stored as knowledge (category="error") for future avoidance. Two kinds are skipped: an error that names no cause (“Unknown error”) or a missing table or column, since a later turn has nothing to act on. A tool-recorded error carries the GAIA version that saw it, and errors from any other version are dropped when memory opens; a real error is stored again the next time it happens. A call refused before it ran (executed: False on the result, in a dict or a JSON envelope, which includes a declined confirmation prompt and GAIA’s own per-turn limits such as the search_tools cap, the mail-reading budget and the loop guard) is neither stored nor treated as evidence the operation works — only a call that actually ran and succeeded clears errors stored for the same operation (the tool plus the program or path it acted on). Memory tools (remember, recall, etc.) are excluded from logging to avoid noise and recursion.
Hook 3: _after_process_query() callback
Called after process_query() completes. Stores both conversation turns (user + assistant) in the conversations table synchronously, so the transcript is durable the instant the turn ends, then schedules Mem0-style LLM extraction (ADD/UPDATE/DELETE/NOOP operations against existing memory) and returns without waiting for it.
For turns of at least MIN_EXTRACTION_WORDS (5) words, the scheduled job fetches top-10 relevant existing items via _hybrid_search(), then asks the LLM to decide what operations to perform — no regex heuristic fallback. See Background extraction for the timing, the queue, and how to wait for it before exiting.
KV-Cache Frozen Prefix Design
Memory reaches the model in two parts, and neither is in the system prompt:
The system prompt and tool list then stay byte-identical across fresh sessions of the same agent, so an inference engine (like Lemonade Server) reuses its cache for them even when memory changed since the last chat. Hybrid models such as Qwen3.6 can resume only from a checkpoint at a user-message start, never from inside the system prompt, so per-session text there would make every new chat re-read the whole prompt.
The session context holds every fragment named in
Agent.VOLATILE_PROMPT_FRAGMENTS — memory, loaded skills, the project map or working directory, and (for the chat agents) the session’s folders and scratch directory. Agent.session_context returns it; every request carries it, fenced, at the start of its first user message:
MemoryStore
The pure data layer. Agent-agnostic — no imports fromgaia.agents. Thread-safe via threading.Lock. Uses WAL mode for concurrent reads.
Constructor
Database Schema (v2)
Three tables in a single SQLite file. Schema version 2 adds vector embedding support and fact lineage tracking.conversations— every conversation turn, persistent across sessions, with FTS5 index. v2 addsconsolidated_at TEXTcolumn for tracking which turns have been distilled to knowledge.knowledge— persistent facts, preferences, errors, skills with FTS5 index, confidence scoring, context scoping, entity linking, temporal fields (due_at,reminded_at). v2 addsembedding BLOB(768-dim float32 vector) andsuperseded_by TEXT(fact lineage — ID of newer item that replaced this one).tool_history— every tool call the agent makes, auto-logged with success/failure, duration, error messages
MemoryStore.__init__(). v1 → v2 adds:
Knowledge Methods
store()
store(), update(), and delete() raise ValueError for system, profile, or permission unless the caller passes allow_privileged=True. Updates check both the existing and requested category, including content-only changes and recategorization out of a privileged category. Those rows lead every session context, so only onboarding, system-context collection, gaia memory, seed_bulk(), and the reviewed dashboard writes opt in. The LLM extractor, consolidation, and the remember/update_memory/forget tools cannot. The dashboard (POST /api/memory/knowledge, commit-discovery, commit-inference) validates against USER_REVIEWED_CATEGORIES — the chat-turn categories plus profile. Inference commits accept only profile. Both commit endpoints reject an invalid batch with HTTP 422 before mutation. commit-inference replaces the old inferred profile in one transaction (MemoryStore.replace_by_source), so a failed save keeps the previous profile; commit-discovery storage failures return HTTP 500 with a correlation ID and the number of items already stored, so callers must not assume atomic rollback there.
Deduplication: Only a restatement or a refinement of an existing entry in the same category + context + entity scope merges into it: one fact’s words, in order and ignoring filler like “the”, “is” and “my”, must start the other’s (”… is Elena” -> ”… is Elena Petrova”). The merged entry keeps the fuller wording and the higher confidence. A fact that swaps, inserts or reorders a word (“mother” -> “mother-in-law”, “React 18” -> “React 19”, “is” -> “is not”) is stored as a new entry, never written over the old one; extraction’s UPDATE and consolidation retire the old entry through superseded_by. The extractor files one statement as a fact or a preference interchangeably, so the same words (ignoring case and punctuation) in either of those two are one memory too: the existing row keeps its category (INTERCHANGEABLE_CATEGORIES).
Validation: content must be non-empty (raises ValueError otherwise). Content longer than 2000 characters is silently truncated. due_at, if provided, is normalized to timezone-aware ISO 8601.
Embedding: After storage, MemoryMixin immediately embeds the new item via _embed_text() and writes the embedding BLOB back via store_embedding(). The FAISS index is incrementally updated.
search()
count_as_use=False. Filters on superseded_by IS NULL to return only current/active items.
The time_from and time_to parameters add temporal filtering on created_at, narrowing results before BM25 ranking.
This is the keyword component of search. For full hybrid search (vector + BM25 fused by RRF), use
MemoryMixin._hybrid_search(), which calls this method internally as one of its two retrieval signals.get_by_category()
superseded_by IS NULL to return only current/active items.
get_by_entity()
superseded_by IS NULL to return only current/active items.
get_upcoming()
superseded_by IS NULL to return only current/active items.
update()
updated_at to the current time. When content is updated, the stored embedding is cleared (embedding = NULL) to force re-embedding. The superseded_by parameter is used by the LLM extraction pipeline to mark old items as replaced by newer versions while preserving fact lineage.
delete()
forget()
forget() deletes the entry and records that the user forgot it; see Forgetting. sensitive=True records it as sensitive even when the row isn’t flagged. copies_of() returns the ids of current rows that store the same fact: the same words bar filler and bracketed asides (“I am allergic to mango” and “User is allergic to mango (health info)”), or, when either row is sensitive, a looser rewording of it (“User has a mango allergy”) that does not negate it (“User is not allergic to mango” stays), about the same subject, in a chat-writable category, limited to contexts when given. forget_with_copies() forgets the entry and those copies and returns every erased id; if any of them is sensitive, all are recorded as sensitive, so an unflagged copy can’t leave the fact’s words in the forgotten table. The forget tool and the Memory page’s Forget go through it. get_forgotten() lists the text of what was forgotten, newest first, for a prompt (sensitive entries are left out). is_forgotten() says whether content is the same memory as one of them, and mentions_forgotten() whether a longer text, such as a session summary, repeats one. With said_before, each covers only what was forgotten after that moment.
get_all_knowledge(about_user=True) (and GET /api/memory/knowledge?about_user=true) returns only rows about the user, leaving out tool lessons, session summaries, errors and system facts.
replace_by_source()
apply_confidence_decay()
decay_factor for items not accessed in days_threshold days, at most once per days_threshold (tracked in decayed_at) and not within days_threshold of its last confirmation. It never moves updated_at, which the agent is shown as “last confirmed” and which orders memories newest first. Called once per session start via reset_memory_session().
update_confidence()
delta, clamped to [0.0, 1.0]. Used internally by reconciliation (+0.05 reinforce, +0.1 contradict newer, -0.1 weaken). updated_at moves only with confirmed=True — a lesson whose fix just worked again; a reconciliation nudge is not a confirmation.
delete_by_source()
"discovery"). Returns the number of entries deleted. Used by gaia memory bootstrap --reset to clear discovery items.
Conversation Methods
Tool History Methods
Dashboard Methods
Aggregate queries for the Memory Dashboard UI:Embedding & Vector Methods (v2)
Consolidation Methods (v2)
Reconciliation Methods (v2)
SystemDiscovery
Local system scanner for day-zero bootstrap. Returns lists of discovered facts for user review — nothing is stored directly.Methods
Discovery never reports an unsupported OS as “nothing found”. Every source run
through
scan_all(), the Agent UI’s discovery and inference streams, or
gaia memory bootstrap is checked against unsupported_reason(source) first;
when a source has no branch for the running platform it is named in a log line
(and an SSE log event) and mapped to [] without being called, so “GAIA
cannot look here” is never mistaken for “you have none”. A scanner called
directly applies the same gate itself and returns [] after logging — but call
unsupported_reason(source) yourself when you need the reason as a string to
show a user.Discovery never reads file contents, email content, or browser page content. It reads names, extensions, URLs, and metadata only. All browser history and email items are auto-flagged as sensitive.
Code Examples
Minimal Agent with Memory
Switching Contexts
Accessing the Store Directly
Custom DB Path
Memory Tools Reference
These 6 tools are registered byregister_memory_tools() and exposed to the LLM:
remember
Store a fact, preference, error, skill, note, or reminder. Supports
category, domain, due_at, sensitive, entity. An unknown category or a due_at that is not ISO 8601 does not fail the save: the fact is stored as a fact, or without a date, and the result lists the argument under ignored. A privileged category (system, profile, permission) is handled the same way: the fact is stored as a fact, never under the privileged category. Stored under the agent’s active context; the model does not pick one. Text that restates a file, web page or tool result this session read is refused (status: "skipped") unless the user’s message this turn asks to keep something, or answers yes after the agent asked about that same text; error memories, which describe tools rather than the user, are exempt. update_memory applies the same check.recall
Search memory by query (hybrid: vector + BM25), category, context, entity, or time range. Returns results with IDs for use with update/forget. An empty result carries a
message saying that text read from files, pages or tools is not saved memory.update_memory
Modify an existing entry by ID. Only non-empty fields change. Use
reminded_at="now" after mentioning time-sensitive items.forget
Delete one memory, by its ID from
recall or by the user’s words for it (“allergic to shellfish”). An id that isn’t stored (“allergy:mango”) is read as words too. Words erase only the one memory they clearly match: it holds every word that names something, as written or as a kin word: a plural (“allergy” meets “allergies”) or a listed adjective (“allergic”, “diabetic”, “asthmatic”). “historic” doesn’t meet “history”, and a cut-off word like “allerg” meets nothing. Copies of the same words, ignoring filler such as “User is”, are one memory saved twice, so all of them go, whether it was forgotten by ID or by words, and the result lists their IDs as knowledge_ids. A memory that is only close in meaning is never erased; it comes back as a candidate for the model to confirm and forget by ID. A forget by words also returns the erased text as erased. Anything less erases nothing and returns the candidate IDs, spelled out in the message as ready-to-call forget(knowledge_id=...) lines with each memory’s text (only memories in this session’s context that share a word with the description or clear the recall floor, so a miss returns none), and the Agent UI step says nothing was erased rather than quoting the message written for the model.forget_everything
Erase all memory, sensitive rows included, plus past conversations and tool history. Learned skills are kept. Asks the user first; nothing brings it back.
search_past_conversations
Search conversation history by keywords, time range, or both. Returns matching turns with timestamps and session IDs. An empty result carries
past_conversation_turns (turns stored by earlier sessions) and a message that says plainly when there are none to search.remember = create, recall = read, update_memory = update, forget = delete (forget_everything deletes all of it), plus search_past_conversations for history.
Knowledge Sources
v2 replaces the v1
heuristic source (regex-based) with llm_extract (Mem0-style LLM extraction). The LLM sees both the conversation and existing memory, then decides what operations to perform (ADD/UPDATE/DELETE/NOOP). This produces higher-quality extractions with proper deduplication and contradiction resolution.API Reference
MemoryMixin Methods
MemoryStore Methods
Related
- User Guide — What agent memory does, CLI commands, dashboard walkthrough
- Agent System — Base Agent class that MemoryMixin extends
- Tool Decorator — How the 6 memory tools are registered
- Agent UI — Desktop interface with Memory Dashboard
- Agent SDK — Chat SDK for building conversational agents