Skip to content

Python SDK API

This page covers the stable, high-value Python surface. Import public types from memorizz unless a guide documents a provider-specific module.

MemAgent

memorizz.memagent.core.MemAgent

MemAgent class that orchestrates manager components.

Attributes

last_tool_outcomes property

Structured outcomes from the most recent turn, in execution order.

last_turn_limits property

Per-turn limits the most recent turn ran into.

tool_budget_exhausted is True when tool calls were refused because the turn had used ContextPolicy.max_tool_invocations_per_turn (tool_call_limit). refused_tool_calls counts the calls that did not run and refused_tools counts them by tool name.

Methods:

run(query, memory_id=None, thread_id=None, user_id=None, context=None, tool_context=None, observability_context=None, retrieval_policy=None, trace_tags=None, memory_capture=None, raise_errors=None, also_recall_from=None)

Run the agent with the given query using the new manager architecture.

Parameters:

Name Type Description Default
query str

The user's query

required
memory_id Optional[str]

The one memory this turn reads and writes: a single ID, never a list. Without it the turn stays in the memory the agent last ran in, or its first memory_ids entry on a first run. To read more than one memory, see also_recall_from.

None
also_recall_from Optional[Iterable[str]]

Other memories this turn may also read, such as a team's shared memory while working in a private one: their conversations and their entity records are recalled beside this memory's, each marked with the memory it came from. Nothing is ever written to them. Shorthand for RetrievalPolicy(also_recall_from=[...]) on this call; [] reads no other memory this turn. A sealed or thread-scoped policy, and a delegate's task, read none.

None
thread_id Optional[str]

Optional thread ID to use (if not provided, reuses current or creates new)

None
user_id Optional[str]

Optional end-user identifier for multi-tenant apps. When provided, every memory unit written during this turn is tagged with user_id and every read is restricted to rows matching the same scope. None means anonymous/legacy scope — reads return only rows with no user_id set.

None
context Optional[Dict[str, Any]]

Optional per-call ephemeral context (M2). When provided, the dict is rendered as a structured system-role message between the main system prompt and conversation history, so the agent sees it for this turn only. It is intentionally NOT persisted to conversation_memory (only the original query is recorded). Recommended shape for SDK consumers::

{
  "current_page": {"type": "analysis"|"group"|...,
                   "id": "<id>", "title": "<title>"},
  "quoted_text": "<optional highlighted snippet>",
  "highlights": [...],          # optional
  "notes": [...],               # optional
  "internet_search_allowed": True|False,
  "open_threads": [...],        # optional
}

Callers may pass any JSON-serialisable dict; unknown keys are included verbatim.

None
tool_context Optional[Dict[str, Any]]

Optional per-call dict made available to tool functions via memorizz.get_tool_context() (M4). Unlike context above, this is NOT sent to the LLM at all — it's stored in a contextvars.ContextVar set before the tool loop and reset when the call returns. Use it for per-request facts the LLM should not see or be required to pass (e.g. {"user_id": "..."} for tenant-scoped tool queries).

None
observability_context Optional[Dict[str, Any]]

Optional content-free host provenance for the private trace bundle. Only a strict allowlist of routing, ownership, grounding, and fingerprint fields is retained; this dict is never sent to the LLM or conversation history.

None
retrieval_policy Any

A policy for this call only. A scope string such as "sealed" or "thread" changes just those scopes and keeps the agent's other settings (scoring, retention, namespaces); a RetrievalPolicy or dict replaces the agent's policy for the call. The agent's own policy, and what save() writes, stay unchanged, and other calls running at the same time keep theirs.

None
trace_tags Optional[Dict[str, str]]

Optional run labels for this turn's trace, such as {"experiment": "lme-v2", "question": "q17"}. They are recorded on the turn's start and result events, never sent to the model, and the Traces page filters by them. At most 16 string tags; see memorizz.observability.normalize_trace_tags for the rules. Invalid tags raise ValueError before the turn runs.

None
memory_capture Optional[bool]

False makes the turn teach memory nothing, for text the user did not write themselves (another agent's request, a system prompt): no entity capture or routing after it, and the model's entity_memory_upsert and remember calls are refused with a short explanation. The turn is still recorded in its conversation.

None
raise_errors Optional[bool]

True raises a failure (a model provider error, a bug) instead of returning "I encountered an error: ..." as the answer. None follows agent.raise_errors (off by default). Running out of steps is an answer, not an error.

None

Returns:

Type Description
str

The agent's response

run_stream_events(query, *, delivery_mode=None, cancellation=None, queue_size=64, **kwargs)

Return a closeable, ordered v1 event stream (no private reasoning).

Accepts run()'s keyword arguments, including trace_tags.

arun_stream_events(query, **kwargs) async

Async event iterator backed by one owned execution context/worker.

validate_configuration()

Validate configured optional subsystems and return a stable report.

capability_report(*, preflight=False)

Return package and configured-agent feature/provider states.

semantic_cache_stats()

Return real hit/miss/bypass/write/eviction counters and provenance.

inspect_semantic_cache(query, *, thread_id=None, user_id=None, context=None, metadata=None, bypass_reason=None)

Inspect cache provenance/freshness without returning cached content.

invalidate_semantic_cache(*, domains=None, tags=None, data_version=None)

Invalidate semantic cache entries by operational domain or tag.

tool_cache_stats()

Hits, misses, stored results, bypasses and the tool time saved.

enable_tool_cache(**config)

Turn the tool-call cache on (ToolCacheConfig fields as keywords).

disable_tool_cache()

Turn the tool-call cache off; stored results expire on their own.

invalidate_tool_cache(tool_name=None, *, user_id=None)

Drop cached tool results (all, one tool's, and/or one user's).

generate_summaries(days_back=7, max_memories_per_summary=50, *, memory_id=None, user_id=None, thread_id=None, keep_recent=0, summary_type='automatic')

Generate summaries by compressing memory units from a specified time period.

This method collects memory units from the specified time period, uses an LLM to compress them into emotionally and situationally relevant summaries, and stores them in the summaries collection.

Parameters:

days_back : int, optional Number of days back to include in the summary (default: 7) max_memories_per_summary : int, optional Maximum number of memory units to include in each summary (default: 50) memory_id : str, optional Exact memory scope. When omitted, the configured/current memory IDs are considered for backward compatibility. user_id : str, optional Exact tenant scope. None selects only anonymous/legacy rows; this method never inherits a user from the most recent run. thread_id : str, optional Exact conversation thread. When omitted, all threads in the selected memory/tenant scope may be compacted independently.

Returns:

List[str] List of summary IDs that were created

with_background_model(model=None)

Run memory upkeep on a second, usually cheaper, model.

Pass an llm_config dict (saved with the agent, secrets left out), a model instance from create_llm_provider, or None to go back to the agent's own model. The user's turns keep the agent's model. Returns the agent, for chaining.

wait_for_memory_upkeep(timeout=None)

Wait for background memory upkeep (thread compaction, reflection, consolidation) to finish. True when nothing is still running.

describe_memory()

What this agent remembers and how it recalls it.

The active memory types, whether entity facts are on, the memory tools the model can call, the retrieval policy, the background model and the consolidation schedule.

with_memory_consolidation(enabled=True, **settings)

Consolidate memory in the background every so many turns or hours.

Settings are those of :class:ConsolidationConfig: every_n_turns (20), every_hours (24), auto_apply (True), review_attributes, extract_facts, max_entities, max_threads and max_messages_per_thread. Passes run on the background model. Returns the agent, for chaining.

with_persona_learning(enabled=True, **settings)

Grow the persona from conversations and memories, off the turn.

Settings are those of :class:PersonaLearningConfig: every_n_turns (20), every_hours (24), auto_apply (True), min_conversations (3), max_threads and max_messages_per_thread; across_users (False) with min_users (2) to learn from several people; and standing_rules (False) with min_corrections (2) and rule_owners to have corrections proposed as rules a named owner approves. Reviews run on the background model. Returns the agent, for chaining.

with_voice(enabled=True, config=None)

Turn the agent's voice on or off, optionally changing its settings.

with_observability(enabled=True, provider=None)

Turn the agent's traces on or off, optionally changing where they go. provider is a name ("sentry", "memorizz"), a dict, an ObservabilityConfig or a provider instance; left as None it keeps the provider the agent has.

observability_status()

Whether traces are recorded, where they go and whether that provider is ready (missing names what it still needs).

observability_url()

Where a person opens this agent's traces at its provider. For the built-in provider it is a path in the MemoRizz UI.

flush_observability(timeout=2.0)

Wait up to timeout seconds for traces queued for the provider to be sent (before a short script exits, for example).

voice_status()

Whether the agent can speak now: provider, readiness, what is missing.

speak(text)

Say text aloud: returns a VoiceAudio (bytes and MIME type).

listen(audio, mime_type='audio/webm')

Transcribe a recording of someone speaking to the agent.

run_voice(audio, mime_type='audio/webm', **run_kwargs)

One spoken turn: transcribe, answer with :meth:run, speak the answer.

Returns {"heard", "text", "audio"}; audio is None when nothing was heard or the answer is empty. run_kwargs go to :meth:run.

start_voice_session(greeting=None, **run_kwargs)

Start a live call with the agent (LiveKit or Vapi).

Returns what a browser needs to join: for LiveKit server_url and participant_token, for Vapi public_key and assistant_id. Each thing the caller says is answered with :meth:run (run_kwargs are passed to it). End it with :meth:end_voice_session.

end_voice_session(session_id)

End a live call started by :meth:start_voice_session.

enter_environment(name, tools)

Lend the agent an environment's tools for as long as it is there.

The tools join the agent's current tool list and are offered on every turn, but they belong to the environment: they are never written to the saved agent or to toolbox memory, and :meth:leave_environment takes them away again. Entering the same environment twice replaces its tools. Raises ValueError when a tool's name is already one of the agent's own tools.

leave_environment(name)

Take back the tools :meth:enter_environment lent; return their names.

review_persona(memory_id=None, *, user_id=None, force=False, dry_run=False)

Review recent conversations for a lasting pattern, now.

Returns a :class:PersonaReview. The persona doesn't change: a proposal waits for :meth:apply_persona_proposal or :meth:dismiss_persona_proposal, on the stored agent, so it survives a restart. force reviews even with nothing new since the last one. dry_run returns the review and stores nothing.

apply_persona_proposal(approved_by, proposal=None)

Apply the waiting persona change. Undo it with :meth:undo_persona_change.

dismiss_persona_proposal(approved_by)

Turn down the waiting persona change; it won't be proposed again.

undo_persona_change(approved_by, version=None)

Undo the latest background persona change, or the one making version.

persona_learning_status()

Reviews so far, a change waiting for review, and past changes.

with_also_recall_from(memories)

Name other memories every turn of this agent may also read: a team's shared memory, say, for an agent that also works in private ones. Their conversations and entity records are recalled beside the turn's own memory, marked with where they came from, and nothing is written to them. None or [] reads no other memory. Saved with the agent; run(also_recall_from=...) overrides it for one call.

with_prospection(level=True, **settings)

Configure the agent's prospection loop; see :class:~memorizz.prospection.ProspectionPolicy.

level is True or "low" (propose only), "medium" (also auto-run Tier 0 read-only preparation), "high" (Tier 0/1 reversible actions; Tier 2 always waits for user confirmation), "ultra" (high plus habit prediction), or False to disable. settings are any other :class:ProspectionPolicy fields (tick_mode, shadow, token_budget_per_day, scan, scan_tools, etc.). Returns the agent.

prospect(activity=None, *, memory_id=None, thread_id=None, user_id=None, trigger='event', force=False)

Run one prospection pass and return the resulting :class:~memorizz.prospection.Prospect list.

prospects(*, status=None, memory_id=None, include_expired=True, limit=20, user_id=None)

List stored prospects for this agent, newest first.

accept_prospect(prospect_id, *, run=True, user_id=None, memory_id=None, thread_id=None)

Accept a prospect; with run=True the agent carries it out.

dismiss_prospect(prospect_id, user_id=None)

Reject a prospect so it is not proposed again.

defer_prospect(prospect_id, *, hours=None, user_id=None)

Defer a prospect for later, optionally extending its expiry.

record_prospect_outcome(prospect_id, outcome, *, user_id=None)

Record useful, not_useful, or situation_did_not_occur on a prospect.

snooze_prospection(seconds=None, user_id=None)

Pause prospection passes for seconds (0 wakes immediately).

on_prospect(callback)

Call callback whenever a prospect is created or updated.

prospection_status(user_id=None)

Prospection settings, token budget usage, cooldown, snooze, and worker state.

prospection_metrics(user_id=None)

Outcome trace metrics, acceptance/usefulness rates, and adapted seed weights.

prospection_tick(*, memory_id=None, user_id=None, force=False)

Run one scheduled prospection tick.

start_prospection(*, interval=None, memory_id=None, user_id=None)

Start the background prospection worker (clock or async mode).

stop_prospection()

Stop any background prospection worker started on this agent.

note_prospection_event(trigger, *, memory_id=None, thread_id=None, user_id=None, synchronous=False)

Trigger an event-driven prospection pass (e.g. session_end, turn_end).

with_memory_routing(router='auto', *, enabled=True, **settings)

Route the agent's own memory writes to the store each belongs in.

router is "auto" (a fine-tuned router if there is one, else OpenAI Decisions with an OpenAI key, else the background model), "openai_decisions", "llm" or "finetuned"; settings are those of :class:MemoryRoutingConfig (model, run_id, capture_turns, min_confidence). Returns the agent.

with_reranker(reranker)

Rerank what the agent recalls and what knowledge_base_lookup returns: "voyage", "cohere", "openai_decisions", "huggingface" (optionally with a model, as in "huggingface:cross-encoder/ms-marco-MiniLM-L6-v2"), "finetuned:<run id>", "off", your own reranker (a function (query, texts) -> scores or a CrossEncoder), or None to follow the store. Returns the agent.

remember(text, *, memory_id=None, user_id=None, thread_id=None, source='api')

Keep text, filed in the store the memory router picks.

A durable fact or policy goes to the knowledge base, facts about the user or a named person or thing to entity memory, working notes to short-term memory; nothing is kept when the router judges it not worth keeping. When the router is unsure or names a store the agent does not file directly, the text goes to the knowledge base. Uses the agent's router (memory_routing), or the automatic one when routing is off. Returns a receipt: stored, memory_type, the ids written and the router's answer with its reason.

add_knowledge(source, *, namespace=None, user_id=None, chunking_strategy='fixed', chunk_size=None, chunk_overlap=None, metadata=None, embeddings='required')

Put a document in this agent's knowledge base and keep it there.

source is the text itself, or a path to a file (a Path, or a string naming a file that exists: PDFs, Markdown, text, CSV, JSON, HTML and code). It is chunked and embedded, attached to the agent and the agent saved, so knowledge_base_lookup and recall find it from the next turn on. Unlike remember, no router decides where it goes. Knowledge-base recall is turned on for the agent if it was off. namespace defaults to the file name ("notes" for text). embeddings is passed to the knowledge base as given ("required": a chunk that cannot be embedded fails the call). Returns the knowledge_base_id; KnowledgeBase.detach_from_agent takes it off again.

plan_memory_consolidation(memory_id=None, *, user_id=None, thread_ids=None, since=None, knowledge_base=False)

Dry-run consolidation of one memory and user; nothing changes.

Merges duplicate entities, suppresses duplicate summaries (and, with knowledge_base=True, duplicate knowledge-base chunks), and, on the background model, retires facts stored twice or contradicted by a newer one and finds facts the user stated in thread_ids that were never stored. Without thread_ids it reads the threads this agent served since the last pass. user_id=None is the anonymous scope.

apply_memory_consolidation(plan, approved_by, reason=None)

Make a consolidation plan's changes (a plan, its dict, or its id).

Nothing is deleted; :meth:restore_memory_consolidation undoes it.

restore_memory_consolidation(plan_id, *, approved_by, memory_id=None, user_id=None)

Undo an applied consolidation plan in one memory and user.

pending_memory_consolidations()

Plans made in this process that are waiting to be applied.

observability_summary(memory_id, user_id, *, thread_id=None, limit=1000)

Return tenant-scoped operational counts without exposing row bodies.

get_trace_context()

Return identifiers for linking application outcomes to the last turn.

trace_url(base_url=trace_links.DEFAULT_UI_URL, *, turn_id=None)

The Traces page link for the last turn's trace, or None when no turn has run.

The last turn is the newest one this agent object finished, in any thread or stream (run_stream_events included). Pass turn_id to link another of its turns. The link names the agent, thread, root trace and turn, and opens at #trace-timeline.

build_personalization_context(query, *, memory_id=None, user_id=None, preferences=None, writing_samples=None, additional_memories=None, policy=None, exclude_thread_id=None)

Build explicit, tenant-scoped personalization without running an LLM.

Cross-thread conversation recall occurs only when the supplied :class:~memorizz.personalization.PersonalizationPolicy enables it and both memory_id and user_id are bound. Host preferences and writing samples are accepted as already-authorized application data.

last_memory_context_evidence(*, include_ids=False)

Return the content-free memory supply snapshot for the latest turn.

include_ids=True adds retrieved: one entry per recalled record with its ref fingerprint, memory_type, plain record_id, thread_id and score, for retrieval evaluation. The ids are held apart from the snapshot, so traces, the UI and the default return value never carry them; only code that holds this agent can ask for them, and only for its own execution context.

record_feedback(rating, *, verified=True, source='user', label=None, comment=None, include_comment=False, trace_context=None, external_id=None)

Join verified application feedback to a concrete agent trace.

record_task_outcome(status=None, *, verdict=None, turn_id=None, verified=True, source=None, score=None, grader=None, reason_code=None, metrics=None, trace_context=None, external_id=None)

Join a task outcome, or a grader's verdict, to a turn's trace.

Give the outcome as status (success, failure, partial, unknown) or as a grader verdict (pass, fail, partial, unknown). The turn is turn_id, trace_context, or else the last turn in this context. grader names who judged it and reason_code says why; both are short labels. source defaults to "grader" when a grader is named, else "application". Failing verdicts appear on the turn in Traces and under the Overview's Needs attention.

has_automations()

Return True when automation storage + tools are available for this agent.

create_automation(name, schedule_type, *, query_template, cron_expr=None, interval_seconds=None, timezone=None, memory_id=None, whatsapp_to=None, max_run_seconds=900, retry_max_attempts=1, retry_backoff_seconds=60, misfire_policy='skip')

Create a scheduled automation job for this agent.

Parameters:

Name Type Description Default
name str

Human-readable job name (e.g. "Daily briefing").

required
schedule_type str

One of "cron", "interval", or "one_shot". A one_shot runs once, after interval_seconds if given.

required
query_template str

The prompt template to run. Supports placeholders: {today_iso}, {scheduled_for_iso}, {now_utc_iso}, {timezone}.

required
cron_expr Optional[str]

5-field cron expression (required when schedule_type="cron").

None
interval_seconds Optional[int]

Seconds between runs (required when schedule_type="interval").

None
timezone Optional[str]

IANA timezone name. Falls back to agent's default_timezone, then the MEMORIZZ_DEFAULT_TIMEZONE env var. Required for cron; other schedules can use this machine's timezone.

None
memory_id Optional[str]

Memory ID for the automation's conversation thread. Auto-generated if not provided.

None
whatsapp_to Optional[List[str]]

List of WhatsApp recipient numbers. When provided, results are delivered via WhatsApp/Twilio.

None
max_run_seconds int

Maximum execution time per run (default 900).

900
retry_max_attempts int

Number of retry attempts on failure (default 1).

1
retry_backoff_seconds int

Backoff between retries (default 60).

60
misfire_policy str

What to do on missed runs: "skip" or "run".

'skip'

Returns:

Type Description
AutomationJob

The created AutomationJob instance.

Raises:

Type Description
ValueError

If automations are unavailable, timezone is invalid, or required parameters are missing.

Example::

job = agent.create_automation(
    name="Morning News Digest",
    schedule_type="cron",
    cron_expr="0 8 * * *",
    timezone="America/New_York",
    query_template="Give me today's top 5 tech news for {today_iso}",
)
print(f"Created job {job.job_id}, next run: {job.next_run_at}")

list_automations(*, enabled=None)

List automation jobs belonging to this agent.

Parameters:

Name Type Description Default
enabled Optional[bool]

Filter by enabled state. None returns all jobs.

None

Returns:

Type Description
List[AutomationJob]

List of AutomationJob instances.

get_automation(job_id)

Get a single automation job by ID.

Parameters:

Name Type Description Default
job_id str

The job identifier.

required

Returns:

Type Description
Optional[AutomationJob]

AutomationJob if found, None otherwise.

pause_automation(job_id)

Pause a running automation job.

Parameters:

Name Type Description Default
job_id str

The job identifier to pause.

required

Returns:

Type Description
AutomationJob

The updated AutomationJob with enabled=False.

resume_automation(job_id)

Resume a paused automation job.

Parameters:

Name Type Description Default
job_id str

The job identifier to resume.

required

Returns:

Type Description
AutomationJob

The updated AutomationJob with enabled=True.

trigger_automation(job_id)

Trigger an immediate run of an automation job.

Sets next_run_at to now and enables the job so the worker picks it up on its next poll cycle.

Parameters:

Name Type Description Default
job_id str

The job identifier to trigger.

required

Returns:

Type Description
AutomationJob

The updated AutomationJob.

list_automation_runs(job_id, *, limit=50)

List execution history for a specific automation job.

Parameters:

Name Type Description Default
job_id str

The job identifier.

required
limit int

Maximum number of runs to return (default 50).

50

Returns:

Type Description
List[AutomationRun]

List of AutomationRun instances, most recent first.

delete_automation(job_id)

Permanently delete an automation job.

Parameters:

Name Type Description Default
job_id str

The job identifier to delete.

required

Returns:

Type Description
bool

True if the job was deleted, False if not found.

list_approval_proposals(*, status=None, limit=100)

List durable approval proposals owned by this agent.

approve(proposal_id, *, approver_id, reason=None)

Record a host-side approval decision without executing the tool.

reject(proposal_id, *, approver_id, reason=None)

Record a host-side rejection decision.

The paused turn's thread is told the call was rejected. To let the model react in the same run, follow with :meth:resume_rejection.

cancel_approval(proposal_id, *, approver_id, reason=None)

Cancel a pending proposal (host-friendly alias for rejection).

resume_approval(proposal_id, *, continue_model=True)

Execute an approved checkpoint once and return structured evidence.

Set continue_model=False for deterministic host workflows that need the exact tool result without asking an LLM to comment on it.

resume_rejection(proposal_id, *, continue_model=True)

Hand a rejected proposal back to the model as the call's result.

The paused tool call is answered with a refusal that carries the approver's reason, and the model continues the run from there: it can say so, or do something else, without the host writing a message for it. Nothing is executed. One rejection is handed back once; with continue_model=False the refusal is only stored in the thread.

discover_mcp_tools(server_name=None, *, only_direct_tools=False)

List MCP servers now and register each tool as server__tool.

A server that has never been listed gives the model only the general tools (mcp_list_tools, mcp_call_tool) on its first turn, and the model spends steps finding out what the server offers. Call this once after building the agent and the first turn already has every allowed tool under its own name and schema.

Parameters:

Name Type Description Default
server_name Optional[str]

One configured server; every enabled one when omitted.

None
only_direct_tools bool

Also remove the general MCP tools, so each MCP tool has exactly one name. Leave it off when the model should still read resources or prompts, or list a server again.

False

Returns:

Type Description
Dict[str, Any]

{"ok": bool, "tools": {server: [names]}, "errors": {server: text}}.

Dict[str, Any]

ok is False when any server could not be listed.

close(*, cleanup_scope=None, close_memory_provider=True, close_model_provider=False)

Close agent-owned runtime resources and optionally delete a scope.

cleanup_scope is forwarded to a provider's delete_scope before connections are closed. It must contain an exact memory_id, user_id, and/or agent_ids boundary, and may set keep_traces=True to keep the scope's trace records; providers retain their own fail-closed validation.

lifecycle(*, cleanup_scope=None, close_memory_provider=True, close_model_provider=False)

Manage the agent lifecycle with optional exact-scope cleanup.

Persistence

agent.save() stores the current definition in its configured memory provider. MemAgent.load(agent_id, memory_provider=provider, **overrides) restores it; omit memory_provider only when the definition lives in the default filesystem provider. Tool code is not stored: pass the functions back with tools=[...], which also restores their governed_tool policies.

MemAgentBuilder.with_knowledge_base(ids) attaches knowledge bases by the ids ingest_knowledge returns. Their chunks are recalled automatically whenever knowledge_base is one of the agent's memory types (the assistant, workflow and deep_research modes include it), whatever memory_id they were ingested under. Rebuilding a named agent keeps its stored knowledge bases unless with_knowledge_base is called.

Personalization context

PersonalizationContext is the provider-neutral boundary between durable memory and a host application's generation prompt. Cross-thread conversation recall is disabled by default and becomes available only when the host opts in with an exact memory_id and authenticated user_id.

from memorizz import PersonalizationPolicy

personalization = agent.build_personalization_context(
    "Draft a LinkedIn post about memory observability",
    memory_id="workspace-7",
    user_id="user-42",
    exclude_thread_id="current-thread",
    preferences={"preferred_tone": "concise and technical"},
    policy=PersonalizationPolicy(
        conversation_recall=True,
        min_relevance_score=0.70,
        max_conversation_memories=2,
    ),
)

response = agent.run(
    "Draft the post.",
    memory_id="workspace-7",
    user_id="user-42",
    context={"personalization_context": personalization.to_dict()},
)

The rendered prompt tells the model to use memories only when they naturally improve the current answer. personalization.trace_summary() and agent.last_memory_context_evidence() contain counts, scores, attribute names, and hashed references, not the underlying profile values or conversation text. With continual learning on, recall arrives as one evidence pack: its items are counted in source_counts["evidence_items"], by source in evidence_source_counts, and referenced in evidence_refs. learning_control_plane.explain_last_retrieval() explains each choice. For retrieval evaluation, agent.last_memory_context_evidence(include_ids=True) also returns the plain record ids behind those references (see retrieved record ids).

Canonical user entities and duplicate cleanup

Use a stable application-owned identity_key for profile writes. Name changes then update one deterministic entity instead of creating a second profile. This field is deliberately absent from the model-facing entity_memory_upsert tool: only a trusted host or application may bind a canonical identity. Existing cross-name duplicates are never merged heuristically: preview an exact selection first, inspect conflicts, and only then apply a reversible soft supersession.

from memorizz.long_term.semantic.entity_memory import EntityMemory

entities = EntityMemory(provider)
preview = entities.consolidate_duplicate_entities(
    memory_id="workspace-7",
    user_id="user-42",
    entity_ids=["reviewed-id-1", "reviewed-id-2"],
    canonical_identity_key="authenticated_user",
)

# After operator review of preview["groups"]:
applied = entities.consolidate_duplicate_entities(
    memory_id="workspace-7",
    user_id="user-42",
    entity_ids=["reviewed-id-1", "reviewed-id-2"],
    canonical_identity_key="authenticated_user",
    apply=True,
)

The apply path writes and verifies the merged canonical row before setting metadata.superseded_by on aliases. It does not delete records. Anonymous legacy rows require the separate explicit migrate_legacy_scope operator step; authenticated runtime reads never adopt them automatically.

MemAgentBuilder

memorizz.memagent.builders.agent_builder.MemAgentBuilder

Builder pattern for constructing MemAgent instances.

This provides a fluent interface for complex MemAgent configurations, making them more readable and maintainable.

Methods:

with_name(name)

Set a display name for the agent.

with_instruction(instruction)

Set the agent instruction.

with_model(model)

Set the LLM model.

with_llm_config(config)

Set the LLM configuration.

with_persona(persona=None, name=None, expertise=None)

Set the agent persona.

with_favorite(is_favorite=True)

Mark the built agent as favorite or non-favorite.

with_memory_provider(provider)

Set the memory provider.

with_memory_ids(memory_ids)

Set memory IDs.

with_application_mode(mode)

Set the application mode.

with_tools(tools)

Add tools to the agent.

with_tool(tool)

Add a single tool to the agent.

with_toolbox(toolbox)

Attach a progressively retrieved Toolbox and its callable bindings.

with_mcp_servers(mcp_servers)

Attach MCP server configurations to the agent.

with_internet_access_provider(provider)

Attach an internet access provider.

with_skills_marketplace(provider, config=None)

Configure a skills marketplace without post-build mutation.

with_skill_paths(skill_paths)

Attach skill markdown file paths to the agent.

with_sandbox(provider)

Attach a sandbox provider instance, name, or provider config.

with_sandbox_provider(provider)

Backward-compatible alias for :meth:with_sandbox.

with_browser_control(provider)

Attach a browser-control provider instance, name, or config.

with_browser_control_provider(provider)

Compatibility alias for :meth:with_browser_control.

with_meta_harness(meta_harness=None, *, mode='delegate', default_harness='auto', config=None)

Attach the memory-first external-harness control plane.

delegate exposes bounded harness invocation tools to the native MemAgent loop. runtime makes the selected harness execute the complete turn while MemoRizz retains memory, approval, and trace ownership. Passing None lazily builds the standard Codex, Claude Code, and OpenHands registry from the local configuration.

with_execution_harness(harness, *, meta_harness=None, config=None)

Convenience alias for full-runtime meta-harness execution.

with_semantic_cache(enabled=True, threshold=0.85, scope='session')

Configure semantic caching (isolated to a session by default).

with_tool_cache(enabled=True, *, ttl_seconds=300.0, scope='agent', mcp='annotated')

Reuse results of repeated calls to cacheable tools.

Python tools opt in with @governed_tool(cacheable=True); MCP tools are cached when their server marks them read-only and idempotent (mcp="off" to never cache MCP results).

with_embedding_provider(provider, config=None)

Set the embedding provider.

with_retrieval_policy(policy)

Set automatic memory-retrieval scope independently of storage.

with_also_recall_from(memories)

Name other memories every turn may also read, such as a team's shared memory for an agent that also works in private ones. Their conversations and entity records are recalled, marked with where they came from; nothing is written to them. Applied on top of with_retrieval_policy; see MemAgent.with_also_recall_from.

with_background_model(model)

Run memory upkeep (summaries, reflection, consolidation) on a second model: an llm_config dict or a model instance.

with_memory_consolidation(enabled=True, **settings)

Consolidate memory in the background; see ConsolidationConfig.

with_memory_routing(router='auto', **settings)

File what the agent remembers in the store each memory belongs in.

router is "auto" (a fine-tuned router if there is one, else OpenAI Decisions with an OpenAI key, else the background model), "openai_decisions", "llm" or "finetuned". Settings are those of MemoryRoutingConfig: model, run_id, capture_turns (route each user message after its turn, default True) and min_confidence (0.5). Pass router=False to turn it off.

with_reranker(reranker)

Rerank what the agent recalls and what knowledge_base_lookup returns: "voyage", "cohere", "openai_decisions", "huggingface" (or "huggingface:<model id>"), "finetuned:<run id>", "off", or your own reranker (a function (query, texts) -> scores or a CrossEncoder). Without it the agent follows the store's reranker, if any.

with_context_policy(policy)

with_tool_result_policy(policy)

with_approval_store(store)

with_skills(skills, *, persistence='skillbox')

Attach authored procedural skills without enabling continual learning.

with_skill_retrieval(enabled=True, top_k=2, min_similarity=0.7)

Configure progressive Skillbox retrieval independently of learning.

with_skillbox(skillbox)

Attach an authored/learned Skillbox independently of learning.

with_continual_learning(enabled=True, config=None)

Enable/disable the workflow→skill continual learning loop.

config keys follow PromotionConfig (e.g. min_executions, require_shadow, shadow_evaluation_enabled, promotion_every_n_runs).

with_learning_control_plane(enabled=True, config=None, **settings)

Enable bounded evidence, event compilation, and governed forgetting.

with_workflow_outcome_evaluator(evaluator)

Set a runtime business-success rubric for captured workflows.

with_delegation(delegates=None, **config)

Make delegates operational and configure orchestration behavior.

with_delegates(delegates)

Set delegates and enable model-generated orchestration by default.

with_semantic_layer(catalog)

Attach a governed semantic catalog and query planner.

with_completion_policy(policy)

Attach a host-enforced final-response acceptance policy.

with_automations_enabled(enabled=True)

Enable/disable durable automations tooling (when supported by provider).

with_default_timezone(tz)

Set a default IANA timezone used by automation tools when omitted.

with_self_aware(enabled=True, config=None)

Enable/disable self-awareness host codebase tooling.

with_prospection(level=True, **settings)

Enable the background prospection loop on the agent.

level is True/"low", "medium", "high", "ultra", or False; settings are any :class:~memorizz.prospection.ProspectionPolicy fields (tick_mode, token_budget_per_day, shadow, scan, etc.).

with_entity_memory(enabled=True, *, capture='keep', policy='keep')

Explicitly enable or disable entity memory for the agent.

capture=False stops the background model filing the entity facts of each user message (on by default when the agent has a background model). policy (self_identity_key, subjects) binds the user's facts to one record; see MemAgent.with_entity_memory.

with_tool_access(access)

Set tool access level.

with_max_steps(steps)

Set maximum execution steps.

with_verbose(verbose=True)

Enable verbose logging.

with_oracle_from_env(*, ensure_ready=True, provision_if_missing=None, preflight=True, require_preflight_ok=True, **provider_overrides)

Attach an Oracle provider using the documented environment.

By default the local Docker runtime is started/readied first and a provider preflight is retained on the built agent in environment_reports["oracle"].

with_e2b_from_env(*, validate=True, **provider_config)

Attach a stateful E2B provider using E2B_API_KEY by default.

build(validate=True, persist=False)

Build the MemAgent instance.

Returns:

Type Description
MemAgent

Configured MemAgent instance.

build_and_save(validate=True)

Build, validate, and persist the configured agent.

Prospection loop

MemAgent(prospection=...) (off by default: prospection=False) and with_prospection(...) take True, a level name ("low", "medium", "high", "ultra"), a dict of settings, or a ProspectionPolicy. agent.prospect() writes and returns Prospect memory units persisted in MemoryType.PROSPECTS. See the prospection loop guide.

memorizz.prospection.ProspectionPolicy dataclass

Settings governing an agent's prospection loop.

Attributes

acts property

Whether autonomous execution is permitted (non-shadow, tier >= 0).

Methods:

from_value(value) classmethod

Normalize False/None/True/level/dict/policy.

memorizz.prospection.Prospect dataclass

A first-class prospect memory unit stored in MemoryType.PROSPECTS.

Attributes

id property

Alias for prospect_id.

prompt property

Actionable follow-up prompt derived from proposed_action.

Methods:

from_event(event) classmethod

Backwards-compatible alias for :meth:from_dict.

to_context_block()

Render as a clearly labeled suggestion for main-thread context.

Publishing to a Simuground

memorizz.cloud publishes an agent's definition (name, instruction and persona) to a hosted Simuground with a workshop key, and, if you add one, your LinkedIn profile link (publish(agent, linkedin=...)), which goes only to the owners of the agents yours meets. The copy's memory stays on the server; meetings() and chat() read it back, and open only the agent that key published. meetings_tool() gives a local agent a read-only simuground_meetings tool, so prospection can scan who its copy met.

memorizz.cloud.connect(url=None, key=None)

Configure the MemoRizz server URL and workshop key for agent.publish().

Falls back to MEMORIZZ_CLOUD_URL and MEMORIZZ_CLOUD_KEY when either argument is omitted. Returns {"url": ...} (never the key).

memorizz.cloud.publish(agent, *, linkedin=None, url=None, key=None, timeout=30.0, quiet=False)

Publish agent's definition to the configured MemoRizz Simuground.

Publishing a second time with the same workshop key updates your existing agent in place rather than adding a duplicate.

linkedin is your own LinkedIn profile link. Owners of the agents yours meets see it in :func:meetings, so their agents can suggest connecting with you. It is not shown on the public watch page. Each publish replaces the last: publish without it to stop sharing it.

memorizz.cloud.status(*, url=None, key=None, timeout=15.0)

Check the status of the agent bound to your workshop key.

memorizz.cloud.meetings(*, url=None, key=None, limit=200, timeout=15.0)

Who your published agent met in the Simuground, and what was said.

Reads only the open conversations your agent took part in, newest first under met and in order under lines. Your workshop key decides which agent: it can only ever be the one it published.

memorizz.cloud.chat(text, *, url=None, key=None, timeout=120.0)

Talk to your published agent in private and return its answer.

It answers from what it saw and remembers in the Simuground. Nobody else hears this conversation.

memorizz.cloud.meetings_tool(*, url=None, key=None, timeout=15.0)

A read-only tool, simuground_meetings, that tells an agent who its published copy met in the Simuground and what was said.

Give it to the agent you published from and let prospection scan it, so the agent suggests who to follow up with::

agent.add_tool(cloud.meetings_tool())
agent.with_prospection("low", scan_tools=("simuground_meetings",))

It changes nothing, so it runs at every prospection level without asking.

memorizz.cloud.CloudError

Bases: RuntimeError

Actionable failure when connecting to or publishing to MemoRizz Cloud.

Meta-harness

memorizz.metaharness.service.MetaHarness

Route, govern, execute, remember, and evaluate agent harness runs.

Methods:

from_env(*, memory_provider=None, agent=None, run_store=None, approval_store=None, allowed_workspace_roots=None) classmethod

register(adapter)

list_harnesses(*, probe=True)

probe(name)

run(task)

start(task)

stream(run_id, *, after=0, poll_seconds=0.1)

approve(proposal_id, *, approver_id, reason=None)

reject(proposal_id, *, approver_id, reason=None)

resume_approval(proposal_id)

Consume and synchronously execute one approved exact checkpoint.

resume_approval_start(proposal_id)

Consume an approval and resume its checkpoint in a background worker.

cancel(run_id, *, before_start=False)

Cancel a run. With before_start, a run this process has not created yet (a delegate's, being prepared) starts already canceled instead of raising KeyError.

retry(run_id)

Run a finished run's exact task again and wait for the result.

run_plan(task, plan)

Run a bounded serial planner/implementer/reviewer composition.

compare(task, harnesses)

Run an explicit comparison; callers must provide isolated workspaces for writes.

continue_conversation(conversation_id, task)

Start the next turn of a conversation in the background.

Works with every harness: earlier turns (each request, answer, changed files and commands) reach the new run as bounded context, and the turn is recorded in the same conversation and thread.

refine_memory(memory_id, *, user_id=None, dry_run=False, model=None)

Distil the raw answers harnesses saved to memory_id into findings: quoted from the answer, confirmed when a run agrees, replaced when one corrects them. Every raw answer is kept. dry_run plans and changes nothing.

recover_interrupted_runs()

Mark orphaned queued/running rows interrupted when a worker starts.

close()

memorizz.metaharness.models.HarnessTask dataclass

memorizz.metaharness.models.HarnessPermissions dataclass

A run reads and writes one memory, its task's memory_id. Two fields of HarnessPermissions change that: mcp_read_memory_ids names up to 5 other memories the run may read and never write, and mcp_memory_scope="all" opens it to every memory of the user ("run" is the default). A run with no memory_id is private: it starts with nothing from memory and its answer is not saved.

memorizz.metaharness.memory_refine.HarnessMemoryRefine

Plan and run refine cycles over the memories harnesses share.

Methods:

answers(memory_id, user_id=None, *, only_new=False)

The raw answers harness runs saved to this memory, oldest first.

findings(memory_id, user_id=None, *, include_replaced=False)

What the memory knows: its findings, most confirmed first.

plan(memory_id, user_id=None, *, model=None)

What a cycle would change. Nothing is written.

ops are the changes that passed their checks; dropped the ones that did not, each with why.

run(memory_id, user_id=None, *, dry_run=False, trigger='manual', model=None)

Run one cycle over this memory and return its report.

list_runs(memory_id, limit=10)

Stored cycles of this memory, newest first.

maybe_start(memory_id, user_id=None)

Start a cycle in the background when enough new answers wait.

Called after a run's answer is saved. It never blocks the run and never raises into it.

memorizz.metaharness.memory_refine.RefineSettings

Which model distils, and whether cycles start by themselves.

Kept on this machine (<MEMORIZZ_HOME>/harness-memory-refine.json), like the judge's: the model and its key are this machine's.

meta.memory_refine is the HarnessMemoryRefine of a MetaHarness, and meta.refine_memory(memory_id) runs one cycle. Both classes are exported from memorizz.metaharness.

memorizz.metaharness.base.AgentHarness

Bases: ABC

Methods:

probe() abstractmethod

Return secret-free runtime capability and health information.

run(task, *, workspace, context_pack, emit, cancel_event) abstractmethod

Execute one bounded task and emit normalized events.

See the memory-first meta-harness guide for the adapter security matrix and complete SDK, CLI, UI, and MCP workflows.

Runtime policies

memorizz.tooling.governed_tool(*, deterministic=True, side_effects=False, requires_approval=None, approval_reason=None, domains=(), aliases=(), deprecated_arguments=None, cacheable=False, cache_ttl_seconds=None)

Decorate a callable with explicit tool and cache governance metadata.

cacheable=True lets a MemAgent with a tool cache reuse this tool's result for a repeated call with the same arguments, for cache_ttl_seconds (else the cache's default). Only a deterministic tool without side effects can be cacheable.

memorizz.tooling.ToolPolicy dataclass

Runtime governance metadata attached to a trusted callable.

memorizz.tool_cache.ToolCacheConfig dataclass

How a MemAgent reuses tool results.

Methods:

from_value(value) classmethod

True/a dict/a config -> config; None/False/disabled -> None.

memorizz.tooling.ToolResultPolicy dataclass

Control when full tool output is replaced by an auditable pointer.

Methods:

to_dict()

Return a stable JSON representation for agent persistence.

memorizz.tool_outcomes.ToolOutcome dataclass

Content-free evidence about a tool result.

status drives the primary UI label. fallback_used and degraded remain orthogonal because a fallback can itself offer reduced capability.

Attributes

ok property

Whether execution produced a usable result.

Methods:

from_value(value) classmethod

Build an outcome from a status string or outcome mapping.

to_dict()

Return a stable JSON-safe representation.

memorizz.tool_outcomes.ToolOutcomeStatus

Bases: str, Enum

Terminal state for one tool execution.

memorizz.tool_outcomes.ToolResult dataclass

A tool payload with an explicit outcome.

MemAgent unwraps value before model serialization, preserving the tool's established result schema.

memorizz.tooling.ContextPolicy dataclass

Bounded context and progressive-disclosure defaults for an agent.

memorizz.retrieval.RetrievalPolicy dataclass

Configure automatic semantic recall without changing storage.

The defaults preserve the pre-0.5.2 behaviour for compatibility. Safer conversational applications can use RetrievalPolicy.disabled(), select conversation_scope="thread" and explicit KB namespaces, or seal each thread with RetrievalPolicy.sealed().

entity_scope decides where entity facts live: "memory" shares them across the threads of a memory and user, "thread" keeps the facts a thread writes, and the facts it recalls, inside that thread, and "disabled" stops recalling them automatically (the entity tools still work).

max_chars_per_item cuts each recalled item to that many characters (600 by default; None keeps items whole). max_recall_chars caps the recalled text of a turn as a whole (None, the default, sets no total cap). The most relevant items get their share first, so raising the per-item cap with a total cap cannot flood the prompt.

workflow_scope recalls past workflows (a request, the tools it called and whether each worked) among the memories, for an agent with workflow memory: "memory" from every thread of the memory and user, "thread" from the current thread only, "disabled" (the default) none. A thread-scoped or sealed policy keeps it to the current thread.

also_recall_from names other memories a turn may read beside the one it runs in: a team's shared memory while working in a private one, or a person's other conversations on a chat surface that keeps a memory per conversation (the console's playground). Their conversations and their entity records are recalled, each marked with the memory it came from, and the agent's own conversations there are listed as its other recent ones. It only reads: nothing is written to those memories, a record of theirs cannot be changed through the turn, and recalling a row there does not count as a use of it. A turn's user_id applies to them as it does to its own memory; never list a memory the turn's user may not see. agent.run(also_recall_from=[...]) sets it for one call.

read_routing asks a decision model, before recall, which kinds of memory a request needs: episodic (past conversations), semantic (the knowledge base and entity facts) and procedural (workflows, skills and stated procedures), one yes or no each in one request. Stores whose kind gets less than read_threshold are not searched that turn; the conversation itself is always loaded. True uses the agent's decision model; a name ("d1", "openai_decisions", ...) picks one. When the model cannot answer, every store is searched as usual.

Attributes

workflows_in_thread_only property

Workflow recall stays in the current thread: asked for, or the policy keeps conversations per thread.

Methods:

sealed(**overrides) classmethod

Nothing a user said in one thread reaches another.

Conversation recall and entity facts stay inside the current thread, the semantic cache only answers from the same thread, and the agent's persona is read-only. The knowledge base is shared reference material and stays on.

memorizz.learning.consolidation.ConsolidationConfig dataclass

When and how a background consolidation pass runs.

every_n_turns and every_hours schedule a pass after a turn: the first one reached wins. auto_apply applies a scheduled plan as memorizz:consolidation; otherwise the plan waits for review.

memorizz.memagent.memory_routing.MemoryRoutingConfig dataclass

How an agent routes its own memory writes. Off by default.

Attributes

worth_saving property

Routing is on, or entity capture, the gate or write dedupe was set by hand.

Methods:

from_value(value) classmethod

None/False is off; True routes automatically; a router name ("openai_decisions", or "openai_decisions:gpt-6-luna", "finetuned:<run id>") or a mapping of these fields turns it on.

memorizz.reranking.RerankerConfig dataclass

An agent's own reranker; from_value(None) is None (follow the store).

memorizz.learning.consolidation.ConsolidationPlan dataclass

A dry run: what a consolidation pass would change, and why.

memorizz.completion.CompletionPolicy dataclass

Bounded, auditable final-response acceptance policy.

validator is deliberately runtime-only: serializing arbitrary code is unsafe. When validator_required is persisted, a reloaded agent rejects completion until the trusted host rebinds a validator.

Methods:

evaluate(candidate)

Evaluate one candidate without mutating agent or host state.

to_dict()

Serialize configuration without serializing executable validator code.

Model providers

memorizz.llms.llm_provider.LLMProvider

Bases: Protocol

A generic protocol that defines the contract for any LLM provider to be compatible with both the OpenAI and AzureOpenAI classes.

Methods:

generate(messages, tools=None, tool_choice='auto')

Generate a response from a list of messages (chat format), optionally with tool calling.

generate_stream(messages, tools=None, tool_choice='auto')

Stream a response from a list of messages (chat format), optionally with tool calling.

Yields dictionaries with one of these shapes
  • {"type": "content", "content": "..."} for text chunks
  • {"type": "tool_calls", "response": } when tool calls are detected
  • {"type": "done", "content": ""} at the end of the stream
  • {"type": "usage", "usage": {...}} for known token accounting

Content deltas concatenate exactly to done.content, including whitespace. Exactly one done or completed tool_calls event ends a successful request; an incomplete/refused request raises, it must not invent success at EOF. Reasoning is diagnostic only. Tool response objects are internal and never serialized into public SDK events. Consumers close this generator; adapters must close their raw provider stream and cooperate with the current cancellation token. See llms.streaming.streaming_capabilities for reliable detection (an inherited Protocol stub is not an iterator).

get_config()

Returns a serializable dictionary of the provider's configuration. This is used for saving and reconstructing the agent.

get_last_usage()

Return token usage details (prompt/completion/total) from the most recent call.

get_context_window_tokens()

Return the provider's context window size in tokens, when known.

Memory providers

memorizz.memory_provider.base.MemoryProvider

Bases: ABC

Abstract base class for memory providers.

Methods:

store(data=None, memory_store_type=None, memory_id=None, memory_unit=None) abstractmethod

Store data in the memory provider.

Parameters:

data : Dict[str, Any], optional Data dictionary to store (legacy parameter) memory_store_type : str, optional Type of memory store (legacy parameter) memory_id : str, optional Memory ID to associate with (new parameter) memory_unit : MemoryUnit, optional Memory unit object to store (new parameter)

retrieve_by_query(query, memory_store_type=None, limit=1, memory_id=None, memory_type=None, **kwargs) abstractmethod

Retrieve a document from the memory provider.

Parameters:

query : Dict[str, Any] or str Search query (dict for filter queries, str for semantic search) memory_store_type : str, optional Type of memory store (legacy parameter name) memory_type : str or MemoryType, optional Type of memory store (new parameter name, takes precedence over memory_store_type) memory_id : str, optional Filter results to specific memory_id limit : int Maximum number of results to return **kwargs Additional provider-specific parameters. Includes user_id for multi-tenant scoping. Omitting it is an administrative/unscoped read, explicitly passing None selects anonymous/legacy rows, and a string selects that exact tenant.

retrieve_by_id(id, memory_store_type) abstractmethod

Retrieve a document from the memory provider by id.

When a provider supports multi-tenant scoping via user_id it may accept a user_id keyword argument; callers that need strict isolation should check the returned row's user_id against their expected scope before acting on it.

list_all(memory_store_type, user_id=_UNSET) abstractmethod

List all documents within a memory store type in the memory provider.

user_id follows the shared sentinel contract: omitting it performs an administrative/unscoped read, explicitly passing None selects only anonymous/legacy rows, and a string selects that exact tenant.

retrieve_conversation_history_ordered_by_timestamp(memory_id, memory_type=None, limit=None, user_id=_UNSET, thread_id=None) abstractmethod

Retrieve the conversation history ordered by timestamp.

Parameters:

memory_id : str The memory ID to retrieve history for memory_type : str or MemoryType, optional Type of memory (typically CONVERSATION_MEMORY) limit : int, optional Maximum number of entries to return user_id : str, optional (keyword) Multi-tenant scope. Omitting it is an administrative/unscoped read, explicitly passing None selects anonymous/legacy rows, and a string selects that exact tenant. thread_id : str, optional When provided, return only rows from that exact conversation thread. When omitted, return all threads in the memory scope.

query_observability_records(memory_store_type, *, agent_ids=None, memory_ids=None, thread_id=None, user_id=_UNSET, application_id=None, record_type=None, tool_name=None, success=None, event_filters=None, start_time=None, end_time=None, limit=250, cursor=None)

Return one bounded observability page with portable metadata.

First-party database providers should override this with indexed predicates. This compatibility path intentionally remains available to third-party and filesystem providers, but it never returns an unbounded page to the caller.

invalidate_semantic_cache(*, agent_id=None, memory_id=None, domains=None, tags=None, data_version=None)

Delete persistent cache entries matching governance metadata.

This provider-neutral fallback keeps domain/tag/data-version invalidation operational on filesystem, MongoDB, Oracle, and custom providers. Native providers may override it with a bulk predicate.

store_memagent(memagent) abstractmethod

Store a memagent in the memory provider.

delete_memagent(agent_id, cascade=False) abstractmethod

Delete a memagent from the memory provider.

list_memagents() abstractmethod

List all memagents in the memory provider.

delete_scope(*, memory_id=None, user_id=_UNSET, agent_ids=None, keep_traces=False)

Delete every package-owned row inside one exact scope.

Give at least one of memory_id, user_id (None selects rows without a user) and agent_ids; a row is deleted when every given part its store records matches. agent_ids also deletes those agents' records and automation jobs, and memory_id drops the memory from every agent's memory list. keep_traces=True keeps trace records: observability records in shared memory (trace bundles, outcomes, verdicts, feedback) and legacy trace bundles in conversation memory. Returns per-store counts and total_deleted.

This portable sweep (filesystem, Notion, custom providers) reads each store and deletes store by store, so a failure part-way leaves the earlier stores deleted; run it again to finish. Oracle deletes in one transaction and MongoDB with native filters.

close() abstractmethod

Close the connection to the memory provider.

See the custom provider contract before implementing this interface, particularly the three-state user_id filter. Delete a scope describes what delete_scope removes, and keeps with keep_traces=True, on each provider.

Memory evaluation

The normalized memory-suite SDK keeps diagnostic runs separate from exact paper reproduction. Use get_protocol_manifest() before a run and inspect the returned report's comparison_label, paper_comparable, and comparability_reasons fields before publishing a comparison.

from memorizz.benchmarks.memory_suite import (
    get_protocol_manifest,
    run_memory_suite,
    verify_dataset,
)

readiness = verify_dataset("longmemeval-v2", data_path="./datasets/lme-v2")
protocol = get_protocol_manifest("longmemeval-v2")

report = run_memory_suite(
    "longmemeval-v2",
    "./datasets/lme-v2",
    variant="standard-100",
    profile="smoke",
    workspace="./.memorizz-eval",
    memory_backend="filesystem",  # use "oracle" for Oracle AI Database
    candidate_pool_size=256,
    lexical_ratio=0.35,
    oracle_reader=True,
)

MemorySuiteRunner additionally accepts injected model, judge, embedding, and memory-provider objects for deterministic tests. See the evaluation-suite guide for official-source sync, strict comparability, CLI equivalents, and result interpretation.