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
Section titled “MemAgent”MemAgent
Section titled “MemAgent”MemAgent( model: Optional[Any] = None, llm_config: Optional[Dict[str, Any]] = None, tools: Union[List, Any, None] = None, persona: Optional[Any] = None, instruction: Optional[str] = None, application_mode: Optional[str] = None, memory_types: Optional[List[Union[str, Any]]] = None, max_steps: int = 20, memory_provider: Optional[Any] = None, memory_ids: Union[str, List[str], None] = None, agent_id: Optional[str] = None, tool_access: Optional[str] = 'private', delegates: Optional[List[MemAgent]] = None, verbose: bool = None, embedding_provider: Optional[str] = None, embedding_config: Optional[Dict[str, Any]] = None, semantic_cache: bool = False, semantic_cache_config: Union[Any, Dict[str, Any], None] = None, context_window_tokens: Optional[int] = None, internet_access_provider: Optional[InternetAccessProvider] = None, skills_marketplace_provider: Union[str, Dict[str, Any], None] = None, skills_marketplace_config: Optional[Dict[str, Any]] = None, sandbox_provider: Union[str, Dict[str, Any], SandboxProvider, None] = None, browser_control: Union[str, Dict[str, Any], BrowserControlProvider, None] = None, meta_harness: Optional[Any] = None, meta_harness_mode: Optional[str] = None, default_harness: str = 'auto', harness_config: Optional[Dict[str, Any]] = None, skill_paths: Optional[List[str]] = None, mcp_servers: Optional[List[Dict[str, Any]]] = None, connectors: Optional[List[Union[str, Dict[str, Any]]]] = None, automations_enabled: bool = True, default_timezone: Optional[str] = None, self_aware: bool = False, self_aware_config: Optional[Dict[str, Any]] = None, continual_learning: bool = False, continual_learning_config: Optional[Dict[str, Any]] = None, learning_control_plane: Union[bool, Dict[str, Any], Any, None] = None, workflow_outcome_evaluator: Optional[Callable[[Any], Any]] = None, toolbox: Optional[Any] = None, skillbox: Optional[Any] = None, authored_skills: Optional[List[Any]] = None, skill_retrieval: bool = False, skill_retrieval_config: Optional[Dict[str, Any]] = None, tool_result_policy: Union[memorizz.tooling.ToolResultPolicy, Dict[str, Any], None] = None, tool_cache: Union[bool, Dict[str, Any], ToolCacheConfig, None] = None, context_policy: Union[memorizz.tooling.ContextPolicy, Dict[str, Any], None] = None, completion_policy: Union[memorizz.completion.CompletionPolicy, Dict[str, Any], bool, None] = None, retrieval_policy: Union[Any, Dict[str, Any], str, bool, None] = None, approval_store: Optional[memorizz.approval.ApprovalStore] = None, delegation: Optional[Dict[str, Any]] = None, semantic_layer: Optional[Any] = None, name: Optional[str] = None, application_id: Optional[str] = None, auto_register: bool = True, is_favorite: bool = False, streaming: bool = True, capture_context_snapshots: bool = False, capture_memory_history: bool = False, background_model: Optional[Any] = None, background_llm_config: Optional[Dict[str, Any]] = None, memory_consolidation: Union[bool, Dict[str, Any], None] = None, persona_learning: Union[bool, Dict[str, Any], None] = None, prospection: Any = False, proactive: Any = None, memory_routing: Union[bool, str, Dict[str, Any], None] = None, reranker: Any = None, entity_policy: Union[Any, Dict[str, Any], None] = None, multi_tenant: bool = False, raise_errors: bool = False, decision_model: Any = None, refine_cycle: Optional[bool] = None, refine_interval_hours: Optional[float] = None, voice: bool = False, voice_config: Union[str, Dict[str, Any], Any, None] = None, observability: Union[Any, Dict[str, Any], str, bool, None] = None, observability_provider: Union[str, Dict[str, Any], Any, None] = None,)memorizz.memagent.core.MemAgent · Source
MemAgent class that orchestrates manager components.
run( query: str, memory_id: Optional[str] = None, thread_id: Optional[str] = None, user_id: Optional[str] = None, context: Optional[Dict[str, Any]] = None, tool_context: Optional[Dict[str, Any]] = None, observability_context: Optional[Dict[str, Any]] = None, retrieval_policy: Any = None, trace_tags: Optional[Dict[str, str]] = None, memory_capture: Optional[bool] = None, raise_errors: Optional[bool] = None, also_recall_from: Optional[Iterable[str]] = None,) -> strRun the agent with the given query using the new manager architecture.
Arguments
query: The user’s querymemory_id: 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 firstmemory_idsentry on a first run. To read more than one memory, seealso_recall_from.also_recall_from: 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 forRetrievalPolicy(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.thread_id: Optional thread ID to use (if not provided, reuses current or creates new)user_id: Optional end-user identifier for multi-tenant apps. When provided, every memory unit written during this turn is tagged withuser_idand every read is restricted to rows matching the same scope.Nonemeans anonymous/legacy scope — reads return only rows with nouser_idset.context: 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 toconversation_memory(only the originalqueryis 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.
tool_context: Optional per-call dict made available to tool functions viamemorizz.get_tool_context()(M4). Unlikecontextabove, this is NOT sent to the LLM at all — it’s stored in acontextvars.ContextVarset 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).observability_context: 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.retrieval_policy: 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); aRetrievalPolicyor dict replaces the agent’s policy for the call. The agent’s own policy, and whatsave()writes, stay unchanged, and other calls running at the same time keep theirs.trace_tags: 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; seememorizz.observability.normalize_trace_tagsfor the rules. Invalid tags raiseValueErrorbefore the turn runs.memory_capture:Falsemakes 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’sentity_memory_upsertandremembercalls are refused with a short explanation. The turn is still recorded in its conversation.raise_errors:Trueraises a failure (a model provider error, a bug) instead of returning “I encountered an error: …” as the answer.Nonefollowsagent.raise_errors(off by default). Running out of steps is an answer, not an error.
Returns
- The agent’s response
run_stream_events
Section titled “run_stream_events”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
Section titled “arun_stream_events”arun_stream_events(query, **kwargs)Async event iterator backed by one owned execution context/worker.
validate_configuration
Section titled “validate_configuration”validate_configuration() -> Dict[str, Any]Validate configured optional subsystems and return a stable report.
capability_report
Section titled “capability_report”capability_report(*, preflight: bool = False) -> Dict[str, Any]Return package and configured-agent feature/provider states.
semantic_cache_stats
Section titled “semantic_cache_stats”semantic_cache_stats() -> Dict[str, Any]Return real hit/miss/bypass/write/eviction counters and provenance.
inspect_semantic_cache
Section titled “inspect_semantic_cache”inspect_semantic_cache( query: str, *, thread_id: Optional[str] = None, user_id: Optional[str] = None, context: Optional[Dict[str, Any]] = None, metadata: Optional[Dict[str, Any]] = None, bypass_reason: Optional[str] = None,) -> SemanticCacheInspectionInspect cache provenance/freshness without returning cached content.
invalidate_semantic_cache
Section titled “invalidate_semantic_cache”invalidate_semantic_cache( *, domains: Optional[List[str]] = None, tags: Optional[List[str]] = None, data_version: Optional[str] = None,) -> intInvalidate semantic cache entries by operational domain or tag.
tool_cache_stats
Section titled “tool_cache_stats”tool_cache_stats() -> Dict[str, Any]Hits, misses, stored results, bypasses and the tool time saved.
enable_tool_cache
Section titled “enable_tool_cache”enable_tool_cache(**config: Any) -> ToolCacheTurn the tool-call cache on (ToolCacheConfig fields as keywords).
disable_tool_cache
Section titled “disable_tool_cache”disable_tool_cache() -> NoneTurn the tool-call cache off; stored results expire on their own.
invalidate_tool_cache
Section titled “invalidate_tool_cache”invalidate_tool_cache( tool_name: Optional[str] = None, *, user_id: Optional[str] = None,) -> intDrop cached tool results (all, one tool’s, and/or one user’s).
generate_summaries
Section titled “generate_summaries”generate_summaries( days_back: int = 7, max_memories_per_summary: int = 50, *, memory_id: Optional[str] = None, user_id: Optional[str] = None, thread_id: Optional[str] = None, keep_recent: int = 0, summary_type: str = 'automatic',) -> List[str]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.
Arguments
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.Noneselects 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
Section titled “with_background_model”with_background_model(model: Any = 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
Section titled “wait_for_memory_upkeep”wait_for_memory_upkeep(timeout: Optional[float] = None) -> boolWait for background memory upkeep (thread compaction, reflection, consolidation) to finish. True when nothing is still running.
describe_memory
Section titled “describe_memory”describe_memory() -> Dict[str, Any]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
Section titled “with_memory_consolidation”with_memory_consolidation(enabled: bool = True, **settings: Any)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
Section titled “with_persona_learning”with_persona_learning(enabled: bool = True, **settings: Any)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
Section titled “with_voice”with_voice(enabled: bool = True, config: Any = None) -> MemAgentTurn the agent’s voice on or off, optionally changing its settings.
with_observability
Section titled “with_observability”with_observability(enabled: bool = True, provider: Any = None) -> MemAgentTurn 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
Section titled “observability_status”observability_status() -> Dict[str, Any]Whether traces are recorded, where they go and whether that
provider is ready (missing names what it still needs).
observability_url
Section titled “observability_url”observability_url() -> Optional[str]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
Section titled “flush_observability”flush_observability(timeout: float = 2.0) -> NoneWait up to timeout seconds for traces queued for the provider
to be sent (before a short script exits, for example).
voice_status
Section titled “voice_status”voice_status() -> Dict[str, Any]Whether the agent can speak now: provider, readiness, what is missing.
speak(text: str) -> AnySay text aloud: returns a VoiceAudio (bytes and MIME type).
listen
Section titled “listen”listen(audio: bytes, mime_type: str = 'audio/webm') -> strTranscribe a recording of someone speaking to the agent.
run_voice
Section titled “run_voice”run_voice( audio: bytes, mime_type: str = 'audio/webm', **run_kwargs: Any,) -> Dict[str, Any]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
Section titled “start_voice_session”start_voice_session(greeting: Optional[str] = None, **run_kwargs: Any) -> Dict[str, Any]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
Section titled “end_voice_session”end_voice_session(session_id: str) -> NoneEnd a live call started by :meth:start_voice_session.
enter_environment
Section titled “enter_environment”enter_environment(name: str, tools: List[Callable[..., Any]]) -> List[str]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
Section titled “leave_environment”leave_environment(name: str) -> List[str]Take back the tools :meth:enter_environment lent; return their names.
review_persona
Section titled “review_persona”review_persona( memory_id: Optional[str] = None, *, user_id: Optional[str] = None, force: bool = False, dry_run: bool = False,) -> AnyReview 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
Section titled “apply_persona_proposal”apply_persona_proposal(approved_by: str, proposal: Any = None) -> AnyApply the waiting persona change. Undo it with :meth:undo_persona_change.
dismiss_persona_proposal
Section titled “dismiss_persona_proposal”dismiss_persona_proposal(approved_by: str) -> NoneTurn down the waiting persona change; it won’t be proposed again.
undo_persona_change
Section titled “undo_persona_change”undo_persona_change(approved_by: str, version: Optional[int] = None) -> AnyUndo the latest background persona change, or the one making version.
persona_learning_status
Section titled “persona_learning_status”persona_learning_status() -> Dict[str, Any]Reviews so far, a change waiting for review, and past changes.
with_also_recall_from
Section titled “with_also_recall_from”with_also_recall_from(memories: Optional[Iterable[str]]) -> MemAgentName 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
Section titled “with_prospection”with_prospection(level: Any = True, **settings: Any)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
Section titled “prospect”prospect( activity: Any = None, *, memory_id: Optional[str] = None, thread_id: Optional[str] = None, user_id: Optional[str] = None, trigger: str = 'event', force: bool = False,) -> List[Any]Run one prospection pass and return the resulting :class:~memorizz.prospection.Prospect list.
prospects
Section titled “prospects”prospects( *, status: Optional[str] = None, memory_id: Optional[str] = None, include_expired: bool = True, limit: int = 20, user_id: Optional[str] = None,) -> List[Any]List stored prospects for this agent, newest first.
accept_prospect
Section titled “accept_prospect”accept_prospect( prospect_id: str, *, run: bool = True, user_id: Optional[str] = None, memory_id: Optional[str] = None, thread_id: Optional[str] = None,) -> AnyAccept a prospect; with run=True the agent carries it out.
dismiss_prospect
Section titled “dismiss_prospect”dismiss_prospect(prospect_id: str, user_id: Optional[str] = None) -> AnyReject a prospect so it is not proposed again.
defer_prospect
Section titled “defer_prospect”defer_prospect( prospect_id: str, *, hours: Optional[int] = None, user_id: Optional[str] = None,) -> AnyDefer a prospect for later, optionally extending its expiry.
record_prospect_outcome
Section titled “record_prospect_outcome”record_prospect_outcome( prospect_id: str, outcome: str, *, user_id: Optional[str] = None,) -> AnyRecord useful, not_useful, or situation_did_not_occur on a prospect.
snooze_prospection
Section titled “snooze_prospection”snooze_prospection( seconds: Optional[int] = None, user_id: Optional[str] = None,) -> Dict[str, Any]Pause prospection passes for seconds (0 wakes immediately).
on_prospect
Section titled “on_prospect”on_prospect(callback: Callable[[Any], None]) -> Callable[[], None]Call callback whenever a prospect is created or updated.
prospection_status
Section titled “prospection_status”prospection_status(user_id: Optional[str] = None) -> Dict[str, Any]Prospection settings, token budget usage, cooldown, snooze, and worker state.
prospection_metrics
Section titled “prospection_metrics”prospection_metrics(user_id: Optional[str] = None) -> Dict[str, Any]Outcome trace metrics, acceptance/usefulness rates, and adapted seed weights.
prospection_tick
Section titled “prospection_tick”prospection_tick( *, memory_id: Optional[str] = None, user_id: Optional[str] = None, force: bool = False,) -> Dict[str, Any]Run one scheduled prospection tick.
start_prospection
Section titled “start_prospection”start_prospection( *, interval: Optional[float] = None, memory_id: Optional[str] = None, user_id: Optional[str] = None,) -> NoneStart the background prospection worker (clock or async mode).
stop_prospection
Section titled “stop_prospection”stop_prospection() -> NoneStop any background prospection worker started on this agent.
note_prospection_event
Section titled “note_prospection_event”note_prospection_event( trigger: str, *, memory_id: Optional[str] = None, thread_id: Optional[str] = None, user_id: Optional[str] = None, synchronous: bool = False,) -> boolTrigger an event-driven prospection pass (e.g. session_end, turn_end).
with_memory_routing
Section titled “with_memory_routing”with_memory_routing(router: Any = 'auto', *, enabled: bool = True, **settings: Any)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
Section titled “with_reranker”with_reranker(reranker: Any)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
Section titled “remember”remember( text: str, *, memory_id: Optional[str] = None, user_id: Optional[str] = None, thread_id: Optional[str] = None, source: str = 'api',) -> Dict[str, Any]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
Section titled “add_knowledge”add_knowledge( source: Union[str, os.PathLike[str]], *, namespace: Optional[str] = None, user_id: Optional[str] = None, chunking_strategy: Any = 'fixed', chunk_size: Optional[int] = None, chunk_overlap: Optional[int] = None, metadata: Optional[Dict[str, Any]] = None, embeddings: str = 'required',) -> strPut 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
Section titled “plan_memory_consolidation”plan_memory_consolidation( memory_id: Optional[str] = None, *, user_id: Optional[str] = None, thread_ids: Optional[Sequence[str]] = None, since: Optional[float] = None, knowledge_base: bool = False,) -> AnyDry-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
Section titled “apply_memory_consolidation”apply_memory_consolidation( plan: Any, approved_by: str, reason: Optional[str] = None,) -> AnyMake a consolidation plan’s changes (a plan, its dict, or its id).
Nothing is deleted; :meth:restore_memory_consolidation undoes it.
restore_memory_consolidation
Section titled “restore_memory_consolidation”restore_memory_consolidation( plan_id: str, *, approved_by: str, memory_id: Optional[str] = None, user_id: Optional[str] = None,) -> Dict[str, int]Undo an applied consolidation plan in one memory and user.
pending_memory_consolidations
Section titled “pending_memory_consolidations”pending_memory_consolidations() -> List[Any]Plans made in this process that are waiting to be applied.
observability_summary
Section titled “observability_summary”observability_summary( memory_id: str, user_id: Optional[str], *, thread_id: Optional[str] = None, limit: int = 1000,) -> Dict[str, Any]Return tenant-scoped operational counts without exposing row bodies.
get_trace_context
Section titled “get_trace_context”get_trace_context() -> Dict[str, Any]Return identifiers for linking application outcomes to the last turn.
trace_url
Section titled “trace_url”trace_url( base_url: str = 'http://127.0.0.1:8765', *, turn_id: Optional[str] = None,) -> Optional[str]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
Section titled “build_personalization_context”build_personalization_context( query: str, *, memory_id: Optional[str] = None, user_id: Optional[str] = None, preferences: Optional[Dict[str, Any]] = None, writing_samples: Optional[List[Dict[str, Any]]] = None, additional_memories: Optional[List[Dict[str, Any]]] = None, policy: Optional[Any] = None, exclude_thread_id: Optional[str] = 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
Section titled “last_memory_context_evidence”last_memory_context_evidence(*, include_ids: bool = False) -> Dict[str, Any]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.
last_tool_outcomes
Section titled “last_tool_outcomes”Property. Structured outcomes from the most recent turn, in execution order.
last_turn_limits
Section titled “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.
record_feedback
Section titled “record_feedback”record_feedback( rating: float, *, verified: bool = True, source: str = 'user', label: Optional[str] = None, comment: Optional[str] = None, include_comment: bool = False, trace_context: Optional[Dict[str, Any]] = None, external_id: Optional[str] = None,) -> Dict[str, Any]Join verified application feedback to a concrete agent trace.
record_task_outcome
Section titled “record_task_outcome”record_task_outcome( status: Optional[str] = None, *, verdict: Optional[str] = None, turn_id: Optional[str] = None, verified: bool = True, source: Optional[str] = None, score: Optional[float] = None, grader: Optional[str] = None, reason_code: Optional[str] = None, metrics: Optional[Dict[str, Any]] = None, trace_context: Optional[Dict[str, Any]] = None, external_id: Optional[str] = None,) -> Dict[str, Any]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
Section titled “has_automations”has_automations() -> boolReturn True when automation storage + tools are available for this agent.
create_automation
Section titled “create_automation”create_automation( name: str, schedule_type: str, *, query_template: str, cron_expr: Optional[str] = None, interval_seconds: Optional[int] = None, timezone: Optional[str] = None, memory_id: Optional[str] = None, whatsapp_to: Optional[List[str]] = None, max_run_seconds: int = 900, retry_max_attempts: int = 1, retry_backoff_seconds: int = 60, misfire_policy: str = 'skip',) -> AutomationJobCreate a scheduled automation job for this agent.
Arguments
name: Human-readable job name (e.g. “Daily briefing”).schedule_type: One of “cron”, “interval”, or “one_shot”. A one_shot runs once, after interval_seconds if given.query_template: The prompt template to run. Supports placeholders: {today_iso}, {scheduled_for_iso}, {now_utc_iso}, {timezone}.cron_expr: 5-field cron expression (required when schedule_type=“cron”).interval_seconds: Seconds between runs (required when schedule_type=“interval”).timezone: 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.memory_id: Memory ID for the automation’s conversation thread. Auto-generated if not provided.whatsapp_to: List of WhatsApp recipient numbers. When provided, results are delivered via WhatsApp/Twilio.max_run_seconds: Maximum execution time per run (default 900).retry_max_attempts: Number of retry attempts on failure (default 1).retry_backoff_seconds: Backoff between retries (default 60).misfire_policy: What to do on missed runs: “skip” or “run”.
Returns
- The created AutomationJob instance.
Raises
- 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
Section titled “list_automations”list_automations(*, enabled: Optional[bool] = None) -> List[AutomationJob]List automation jobs belonging to this agent.
Arguments
enabled: Filter by enabled state. None returns all jobs.
Returns
- List of AutomationJob instances.
get_automation
Section titled “get_automation”get_automation(job_id: str) -> Optional[AutomationJob]Get a single automation job by ID.
Arguments
job_id: The job identifier.
Returns
- AutomationJob if found, None otherwise.
pause_automation
Section titled “pause_automation”pause_automation(job_id: str) -> AutomationJobPause a running automation job.
Arguments
job_id: The job identifier to pause.
Returns
- The updated AutomationJob with enabled=False.
resume_automation
Section titled “resume_automation”resume_automation(job_id: str) -> AutomationJobResume a paused automation job.
Arguments
job_id: The job identifier to resume.
Returns
- The updated AutomationJob with enabled=True.
trigger_automation
Section titled “trigger_automation”trigger_automation(job_id: str) -> AutomationJobTrigger 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.
Arguments
job_id: The job identifier to trigger.
Returns
- The updated AutomationJob.
list_automation_runs
Section titled “list_automation_runs”list_automation_runs(job_id: str, *, limit: int = 50) -> List[AutomationRun]List execution history for a specific automation job.
Arguments
job_id: The job identifier.limit: Maximum number of runs to return (default 50).
Returns
- List of AutomationRun instances, most recent first.
delete_automation
Section titled “delete_automation”delete_automation(job_id: str) -> boolPermanently delete an automation job.
Arguments
job_id: The job identifier to delete.
Returns
- True if the job was deleted, False if not found.
list_approval_proposals
Section titled “list_approval_proposals”list_approval_proposals( *, status: Union[memorizz.approval.ApprovalStatus, str, None] = None, limit: int = 100,) -> List[Dict[str, Any]]List durable approval proposals owned by this agent.
approve
Section titled “approve”approve( proposal_id: str, *, approver_id: str, reason: Optional[str] = None,) -> Dict[str, Any]Record a host-side approval decision without executing the tool.
reject
Section titled “reject”reject( proposal_id: str, *, approver_id: str, reason: Optional[str] = None,) -> Dict[str, Any]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
Section titled “cancel_approval”cancel_approval( proposal_id: str, *, approver_id: str, reason: Optional[str] = None,) -> Dict[str, Any]Cancel a pending proposal (host-friendly alias for rejection).
resume_approval
Section titled “resume_approval”resume_approval( proposal_id: str, *, continue_model: bool = True,) -> memorizz.approval.ApprovalResumeResultExecute 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
Section titled “resume_rejection”resume_rejection( proposal_id: str, *, continue_model: bool = True,) -> memorizz.approval.ApprovalResumeResultHand 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
Section titled “discover_mcp_tools”discover_mcp_tools( server_name: Optional[str] = None, *, only_direct_tools: bool = False,) -> Dict[str, Any]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.
Arguments
server_name: One configured server; every enabled one when omitted.only_direct_tools: 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.
Returns
{"ok": bool, "tools": {server: [names]}, "errors": {server: text}}.okis False when any server could not be listed.
close( *, cleanup_scope: Optional[Dict[str, Any]] = None, close_memory_provider: bool = True, close_model_provider: bool = False,) -> Dict[str, Any]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
Section titled “lifecycle”lifecycle( *, cleanup_scope: Optional[Dict[str, Any]] = None, close_memory_provider: bool = True, close_model_provider: bool = False,)Manage the agent lifecycle with optional exact-scope cleanup.
Persistence
Section titled “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
Section titled “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
Section titled “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
Section titled “MemAgentBuilder”MemAgentBuilder
Section titled “MemAgentBuilder”MemAgentBuilder()memorizz.memagent.builders.agent_builder.MemAgentBuilder · Source
Builder pattern for constructing MemAgent instances.
This provides a fluent interface for complex MemAgent configurations, making them more readable and maintainable.
with_name
Section titled “with_name”with_name(name: str) -> MemAgentBuilderSet a display name for the agent.
with_instruction
Section titled “with_instruction”with_instruction(instruction: str) -> MemAgentBuilderSet the agent instruction.
with_model
Section titled “with_model”with_model(model: Any) -> MemAgentBuilderSet the LLM model.
with_llm_config
Section titled “with_llm_config”with_llm_config(config: Dict[str, Any]) -> MemAgentBuilderSet the LLM configuration.
with_persona
Section titled “with_persona”with_persona( persona: Any = None, name: str = None, expertise: List[str] = None,) -> MemAgentBuilderSet the agent persona.
with_favorite
Section titled “with_favorite”with_favorite(is_favorite: bool = True) -> MemAgentBuilderMark the built agent as favorite or non-favorite.
with_memory_provider
Section titled “with_memory_provider”with_memory_provider(provider: Any) -> MemAgentBuilderSet the memory provider.
with_memory_ids
Section titled “with_memory_ids”with_memory_ids(memory_ids: Union[str, List[str]]) -> MemAgentBuilderSet memory IDs.
with_application_mode
Section titled “with_application_mode”with_application_mode(mode: str) -> MemAgentBuilderSet the application mode.
with_tools
Section titled “with_tools”with_tools(tools: Union[List, Any]) -> MemAgentBuilderAdd tools to the agent.
with_tool
Section titled “with_tool”with_tool(tool: Any) -> MemAgentBuilderAdd a single tool to the agent.
with_toolbox
Section titled “with_toolbox”with_toolbox(toolbox: Any) -> MemAgentBuilderAttach a progressively retrieved Toolbox and its callable bindings.
with_mcp_servers
Section titled “with_mcp_servers”with_mcp_servers( mcp_servers: Union[Dict[str, Any], List[Dict[str, Any]]],) -> MemAgentBuilderAttach MCP server configurations to the agent.
with_internet_access_provider
Section titled “with_internet_access_provider”with_internet_access_provider(provider: Any) -> MemAgentBuilderAttach an internet access provider.
with_skills_marketplace
Section titled “with_skills_marketplace”with_skills_marketplace( provider: Any, config: Optional[Dict[str, Any]] = None,) -> MemAgentBuilderConfigure a skills marketplace without post-build mutation.
with_skill_paths
Section titled “with_skill_paths”with_skill_paths(skill_paths: Union[str, List[str]]) -> MemAgentBuilderAttach skill markdown file paths to the agent.
with_sandbox
Section titled “with_sandbox”with_sandbox(provider: Any) -> MemAgentBuilderAttach a sandbox provider instance, name, or provider config.
with_sandbox_provider
Section titled “with_sandbox_provider”with_sandbox_provider(provider: Any) -> MemAgentBuilderBackward-compatible alias for :meth:with_sandbox.
with_browser_control
Section titled “with_browser_control”with_browser_control(provider: Any) -> MemAgentBuilderAttach a browser-control provider instance, name, or config.
with_browser_control_provider
Section titled “with_browser_control_provider”with_browser_control_provider(provider: Any) -> MemAgentBuilderCompatibility alias for :meth:with_browser_control.
with_meta_harness
Section titled “with_meta_harness”with_meta_harness( meta_harness: Any = None, *, mode: str = 'delegate', default_harness: str = 'auto', config: Optional[Dict[str, Any]] = None,) -> MemAgentBuilderAttach 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
Section titled “with_execution_harness”with_execution_harness( harness: str, *, meta_harness: Any = None, config: Optional[Dict[str, Any]] = None,) -> MemAgentBuilderConvenience alias for full-runtime meta-harness execution.
with_semantic_cache
Section titled “with_semantic_cache”with_semantic_cache( enabled: bool = True, threshold: float = 0.85, scope: str = 'session',) -> MemAgentBuilderConfigure semantic caching (isolated to a session by default).
with_tool_cache
Section titled “with_tool_cache”with_tool_cache( enabled: bool = True, *, ttl_seconds: float = 300.0, scope: str = 'agent', mcp: str = 'annotated',) -> MemAgentBuilderReuse 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
Section titled “with_embedding_provider”with_embedding_provider(provider: str, config: Dict[str, Any] = None) -> MemAgentBuilderSet the embedding provider.
with_retrieval_policy
Section titled “with_retrieval_policy”with_retrieval_policy(policy: Any) -> MemAgentBuilderSet automatic memory-retrieval scope independently of storage.
with_also_recall_from
Section titled “with_also_recall_from”with_also_recall_from(memories: Any) -> MemAgentBuilderName 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
Section titled “with_background_model”with_background_model(model: Any) -> MemAgentBuilderRun memory upkeep (summaries, reflection, consolidation) on a
second model: an llm_config dict or a model instance.
with_memory_consolidation
Section titled “with_memory_consolidation”with_memory_consolidation(enabled: bool = True, **settings: Any) -> MemAgentBuilderConsolidate memory in the background; see ConsolidationConfig.
with_memory_routing
Section titled “with_memory_routing”with_memory_routing(router: Any = 'auto', **settings: Any) -> MemAgentBuilderFile 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
Section titled “with_reranker”with_reranker(reranker: Any) -> MemAgentBuilderRerank 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
Section titled “with_context_policy”with_context_policy(policy: Any) -> MemAgentBuilderwith_tool_result_policy
Section titled “with_tool_result_policy”with_tool_result_policy(policy: Any) -> MemAgentBuilderwith_approval_store
Section titled “with_approval_store”with_approval_store(store: Any) -> MemAgentBuilderwith_skills
Section titled “with_skills”with_skills( skills: Union[List[Any], Any], *, persistence: str = 'skillbox',) -> MemAgentBuilderAttach authored procedural skills without enabling continual learning.
with_skill_retrieval
Section titled “with_skill_retrieval”with_skill_retrieval( enabled: bool = True, top_k: int = 2, min_similarity: float = 0.7,) -> MemAgentBuilderConfigure progressive Skillbox retrieval independently of learning.
with_skillbox
Section titled “with_skillbox”with_skillbox(skillbox: Any) -> MemAgentBuilderAttach an authored/learned Skillbox independently of learning.
with_continual_learning
Section titled “with_continual_learning”with_continual_learning( enabled: bool = True, config: Dict[str, Any] = None,) -> MemAgentBuilderEnable/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
Section titled “with_learning_control_plane”with_learning_control_plane( enabled: bool = True, config: Optional[Dict[str, Any]] = None, **settings: Any,) -> MemAgentBuilderEnable bounded evidence, event compilation, and governed forgetting.
with_workflow_outcome_evaluator
Section titled “with_workflow_outcome_evaluator”with_workflow_outcome_evaluator(evaluator: Any) -> MemAgentBuilderSet a runtime business-success rubric for captured workflows.
with_delegation
Section titled “with_delegation”with_delegation( delegates: Union[List[Any], Any] = None, **config: Any,) -> MemAgentBuilderMake delegates operational and configure orchestration behavior.
with_delegates
Section titled “with_delegates”with_delegates(delegates: List[Any]) -> MemAgentBuilderSet delegates and enable model-generated orchestration by default.
with_semantic_layer
Section titled “with_semantic_layer”with_semantic_layer(catalog: Any) -> MemAgentBuilderAttach a governed semantic catalog and query planner.
with_completion_policy
Section titled “with_completion_policy”with_completion_policy(policy: Any) -> MemAgentBuilderAttach a host-enforced final-response acceptance policy.
with_automations_enabled
Section titled “with_automations_enabled”with_automations_enabled(enabled: bool = True) -> MemAgentBuilderEnable/disable durable automations tooling (when supported by provider).
with_default_timezone
Section titled “with_default_timezone”with_default_timezone(tz: str) -> MemAgentBuilderSet a default IANA timezone used by automation tools when omitted.
with_self_aware
Section titled “with_self_aware”with_self_aware(enabled: bool = True, config: Dict[str, Any] = None) -> MemAgentBuilderEnable/disable self-awareness host codebase tooling.
with_prospection
Section titled “with_prospection”with_prospection(level: Any = True, **settings: Any) -> MemAgentBuilderEnable 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
Section titled “with_entity_memory”with_entity_memory( enabled: bool = True, *, capture: Any = 'keep', policy: Any = 'keep',) -> MemAgentBuilderExplicitly 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
Section titled “with_tool_access”with_tool_access(access: str) -> MemAgentBuilderSet tool access level.
with_max_steps
Section titled “with_max_steps”with_max_steps(steps: int) -> MemAgentBuilderSet maximum execution steps.
with_verbose
Section titled “with_verbose”with_verbose(verbose: bool = True) -> MemAgentBuilderEnable verbose logging.
with_oracle_from_env
Section titled “with_oracle_from_env”with_oracle_from_env( *, ensure_ready: bool = True, provision_if_missing: Optional[bool] = None, preflight: bool = True, require_preflight_ok: bool = True, **provider_overrides: Any,) -> MemAgentBuilderAttach 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
Section titled “with_e2b_from_env”with_e2b_from_env(*, validate: bool = True, **provider_config: Any) -> MemAgentBuilderAttach a stateful E2B provider using E2B_API_KEY by default.
build(validate: bool = True, persist: bool = False) -> MemAgentBuild the MemAgent instance.
Returns
- Configured MemAgent instance.
build_and_save
Section titled “build_and_save”build_and_save(validate: bool = True) -> MemAgentBuild, validate, and persist the configured agent.
Prospection loop
Section titled “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.
ProspectionPolicy
Section titled “ProspectionPolicy”ProspectionPolicy( enabled: bool = False, level: str = 'low', tick_mode: str = 'event', clock_interval_minutes: int = 15, event_triggers: Tuple[str, ...] = ('turn_end', 'memory_write_important', 'compaction', 'session_end'), token_budget_per_day: int = 50000, adaptive_budget: bool = True, daily_evaluations: int = 24, daily_actions: int = 10, cooldown_seconds: int = 120, scan_interval_seconds: int = 900, max_seeds_per_pass: int = 5, top_k_to_main_thread: int = 3, min_score: float = 0.4, auto_run_max_risk_tier: int = -1, default_expiry_hours: int = 72, shadow: bool = False, surface_to_main_thread: bool = True, predict: bool = False, auto_after: int = 3, scan_tools: Tuple[str, ...] = (), allow_external_actions: bool = False, min_context_chars: int = 40, max_steps: int = 10, pending_minutes: int = 15, snooze_seconds: int = 3600, seed_weights: Tuple[Tuple[str, float], ...] = (),)memorizz.prospection.ProspectionPolicy · Source
Settings governing an agent’s prospection loop.
| Field | Type | Default |
|---|---|---|
enabled |
bool |
False |
level |
str |
'low' |
tick_mode |
str |
'event' |
clock_interval_minutes |
int |
15 |
event_triggers |
Tuple[str, ...] |
('turn_end', 'memory_write_important', 'compaction', 'ses… |
token_budget_per_day |
int |
50000 |
adaptive_budget |
bool |
True |
daily_evaluations |
int |
24 |
daily_actions |
int |
10 |
cooldown_seconds |
int |
120 |
scan_interval_seconds |
int |
900 |
max_seeds_per_pass |
int |
5 |
top_k_to_main_thread |
int |
3 |
min_score |
float |
0.4 |
auto_run_max_risk_tier |
int |
-1 |
default_expiry_hours |
int |
72 |
shadow |
bool |
False |
surface_to_main_thread |
bool |
True |
predict |
bool |
False |
auto_after |
int |
3 |
scan_tools |
Tuple[str, ...] |
() |
allow_external_actions |
bool |
False |
min_context_chars |
int |
40 |
max_steps |
int |
10 |
pending_minutes |
int |
15 |
snooze_seconds |
int |
3600 |
seed_weights |
Tuple[Tuple[str, float], ...] |
() |
Prospect
Section titled “Prospect”Prospect( prospect_id: str, agent_id: str, created_at: str, predicted_situation: str, proposed_action: Dict[str, Any], source_memory_ids: List[str] = <factory>, seed: Dict[str, Any] = <factory>, title: str = '', message: str = '', evidence: List[Dict[str, Any]] = <factory>, confidence: float = 0.5, score: float = 0.0, risk_tier: int = 1, status: str = 'proposed', outcome: Optional[str] = None, decision: str = 'ask', reason: str = '', by: Optional[str] = None, origin: str = 'grounded', routine: str = '', external: bool = False, dedup_key: str = '', memory_id: Optional[str] = None, thread_id: Optional[str] = None, user_id: Optional[str] = None, proposal_id: Optional[str] = None, result: Optional[str] = None, error: Optional[str] = None, trigger: str = 'event', about: Dict[str, Any] = <factory>, expires_at: Optional[str] = None, updated_at: Optional[str] = None, refreshed_count: int = 0,)memorizz.prospection.Prospect · Source
A first-class prospect memory unit stored in MemoryType.PROSPECTS.
| Field | Type | Default |
|---|---|---|
prospect_id |
str |
required |
agent_id |
str |
required |
created_at |
str |
required |
predicted_situation |
str |
required |
proposed_action |
Dict[str, Any] |
required |
source_memory_ids |
List[str] |
[] |
seed |
Dict[str, Any] |
{} |
title |
str |
'' |
message |
str |
'' |
evidence |
List[Dict[str, Any]] |
[] |
confidence |
float |
0.5 |
score |
float |
0.0 |
risk_tier |
int |
1 |
status |
str |
'proposed' |
outcome |
Optional[str] |
None |
decision |
str |
'ask' |
reason |
str |
'' |
by |
Optional[str] |
None |
origin |
str |
'grounded' |
routine |
str |
'' |
external |
bool |
False |
dedup_key |
str |
'' |
memory_id |
Optional[str] |
None |
thread_id |
Optional[str] |
None |
user_id |
Optional[str] |
None |
proposal_id |
Optional[str] |
None |
result |
Optional[str] |
None |
error |
Optional[str] |
None |
trigger |
str |
'event' |
about |
Dict[str, Any] |
{} |
expires_at |
Optional[str] |
None |
updated_at |
Optional[str] |
None |
refreshed_count |
int |
0 |
Publishing to a Simuground
Section titled “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.
connect
Section titled “connect”connect(url: Optional[str] = None, key: Optional[str] = None) -> Dict[str, str]memorizz.cloud.connect · Source
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).
publish
Section titled “publish”publish( agent: Any, *, linkedin: Optional[str] = None, url: Optional[str] = None, key: Optional[str] = None, timeout: float = 30.0, quiet: bool = False,) -> Dict[str, Any]memorizz.cloud.publish · Source
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.
status
Section titled “status”status( *, url: Optional[str] = None, key: Optional[str] = None, timeout: float = 15.0,) -> Dict[str, Any]memorizz.cloud.status · Source
Check the status of the agent bound to your workshop key.
meetings
Section titled “meetings”meetings( *, url: Optional[str] = None, key: Optional[str] = None, limit: int = 200, timeout: float = 15.0,) -> Dict[str, Any]memorizz.cloud.meetings · Source
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.
chat( text: str, *, url: Optional[str] = None, key: Optional[str] = None, timeout: float = 120.0,) -> strmemorizz.cloud.chat · Source
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.
meetings_tool
Section titled “meetings_tool”meetings_tool( *, url: Optional[str] = None, key: Optional[str] = None, timeout: float = 15.0,) -> Anymemorizz.cloud.meetings_tool · Source
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.
CloudError
Section titled “CloudError”CloudError( message: str, *, code: str = 'cloud_error', status_code: Optional[int] = None,)memorizz.cloud.CloudError · Source
Actionable failure when connecting to or publishing to MemoRizz Cloud.
Meta-harness
Section titled “Meta-harness”MetaHarness
Section titled “MetaHarness”MetaHarness( *, memory_provider: Any = None, adapters: Optional[Iterable[AgentHarness]] = None, run_store: Optional[HarnessRunStore] = None, approval_store: Optional[ApprovalStore] = None, router: Optional[HarnessRouter] = None, context_max_chars: int = 24000, allowed_workspace_roots: Optional[Iterable[str]] = None, recover_interrupted: bool = False, agent: Any = None, learning_control_plane: Any = None, context_cache_entries: int = 128, scratch_root: Optional[str | Path] = None,)memorizz.metaharness.service.MetaHarness · Source
Route, govern, execute, remember, and evaluate agent harness runs.
from_env
Section titled “from_env”from_env( *, memory_provider: Any = None, agent: Any = None, run_store: Optional[HarnessRunStore] = None, approval_store: Optional[ApprovalStore] = None, allowed_workspace_roots: Optional[Iterable[str]] = None,) -> MetaHarnessregister
Section titled “register”register(adapter: AgentHarness) -> MetaHarnesslist_harnesses
Section titled “list_harnesses”list_harnesses(*, probe: bool = True) -> List[Dict[str, Any]]probe(name: str) -> Dict[str, Any]run(task: HarnessTask | Dict[str, Any]) -> HarnessResultstart(task: HarnessTask | Dict[str, Any]) -> HarnessRunstream
Section titled “stream”stream( run_id: str, *, after: int = 0, poll_seconds: float = 0.1,) -> Generator[Dict[str, Any], None, None]approve
Section titled “approve”approve( proposal_id: str, *, approver_id: str, reason: Optional[str] = None,) -> Dict[str, Any]reject
Section titled “reject”reject( proposal_id: str, *, approver_id: str, reason: Optional[str] = None,) -> Dict[str, Any]resume_approval
Section titled “resume_approval”resume_approval(proposal_id: str) -> HarnessResultConsume and synchronously execute one approved exact checkpoint.
resume_approval_start
Section titled “resume_approval_start”resume_approval_start(proposal_id: str) -> HarnessRunConsume an approval and resume its checkpoint in a background worker.
cancel
Section titled “cancel”cancel(run_id: str, *, before_start: bool = False) -> Dict[str, Any]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: str) -> HarnessResultRun a finished run’s exact task again and wait for the result.
run_plan
Section titled “run_plan”run_plan(task: HarnessTask | Dict[str, Any], plan: HarnessPlan) -> List[HarnessResult]Run a bounded serial planner/implementer/reviewer composition.
compare
Section titled “compare”compare(task: HarnessTask | Dict[str, Any], harnesses: Iterable[str]) -> Dict[str, Any]Run an explicit comparison; callers must provide isolated workspaces for writes.
continue_conversation
Section titled “continue_conversation”continue_conversation( conversation_id: str, task: HarnessTask | Dict[str, Any],) -> HarnessRunStart 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
Section titled “refine_memory”refine_memory( memory_id: str, *, user_id: Optional[str] = None, dry_run: bool = False, model: Any = None,) -> Dict[str, Any]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
Section titled “recover_interrupted_runs”recover_interrupted_runs() -> intMark orphaned queued/running rows interrupted when a worker starts.
close() -> NoneHarnessTask
Section titled “HarnessTask”HarnessTask( task: str, workspace: str, harness: str = 'auto', memory_id: Optional[str] = None, user_id: Optional[str] = None, thread_id: Optional[str] = None, agent_id: Optional[str] = None, model: Optional[str] = None, mode: str = 'runtime', permissions: HarnessPermissions = <factory>, budget: HarnessBudget = <factory>, verification: VerificationSpec = <factory>, output_schema: Optional[Dict[str, Any]] = None, context: Dict[str, Any] = <factory>, metadata: Dict[str, Any] = <factory>, run_id: str = <factory>,)memorizz.metaharness.models.HarnessTask · Source
HarnessTask(task: ‘str’, workspace: ‘str’, harness: ‘str’ = ‘auto’, memory_id: ‘Optional[str]’ = None, user_id: ‘Optional[str]’ = None, thread_id: ‘Optional[str]’ = None, agent_id: ‘Optional[str]’ = None, model: ‘Optional[str]’ = None, mode: ‘str’ = ‘runtime’, permissions: ‘HarnessPermissions’ = <factory>, budget: ‘HarnessBudget’ = <factory>, verification: ‘VerificationSpec’ = <factory>, output_schema: ‘Optional[Dict[str, Any]]’ = None, context: ‘Dict[str, Any]’ = <factory>, metadata: ‘Dict[str, Any]’ = <factory>, run_id: ‘str’ = <factory>)
| Field | Type | Default |
|---|---|---|
task |
str |
required |
workspace |
str |
required |
harness |
str |
'auto' |
memory_id |
Optional[str] |
None |
user_id |
Optional[str] |
None |
thread_id |
Optional[str] |
None |
agent_id |
Optional[str] |
None |
model |
Optional[str] |
None |
mode |
str |
'runtime' |
permissions |
HarnessPermissions |
HarnessPermissions(workspace_mode='read_only', allowed_ro… |
budget |
HarnessBudget |
HarnessBudget(max_wall_time_seconds=900.0, max_steps=80, … |
verification |
VerificationSpec |
VerificationSpec(command=None, cwd=None, timeout_seconds=… |
output_schema |
Optional[Dict[str, Any]] |
None |
context |
Dict[str, Any] |
{} |
metadata |
Dict[str, Any] |
{} |
run_id |
str |
a new UUID |
HarnessPermissions
Section titled “HarnessPermissions”HarnessPermissions( workspace_mode: str = 'read_only', allowed_roots: List[str] = <factory>, allow_dirty_workspace: bool = False, network: str = 'none', allowed_tools: List[str] = <factory>, denied_tools: List[str] = <factory>, allowed_env: List[str] = <factory>, mcp_access: str = 'read_only', mcp_memory_scope: str = 'run', mcp_read_memory_ids: List[str] = <factory>, require_approval: Optional[bool] = None, allow_subagents: bool = False,)memorizz.metaharness.models.HarnessPermissions · Source
HarnessPermissions(workspace_mode: ‘str’ = ‘read_only’, allowed_roots: ‘List[str]’ = <factory>, allow_dirty_workspace: ‘bool’ = False, network: ‘str’ = ‘none’, allowed_tools: ‘List[str]’ = <factory>, denied_tools: ‘List[str]’ = <factory>, allowed_env: ‘List[str]’ = <factory>, mcp_access: ‘str’ = ‘read_only’, mcp_memory_scope: ‘str’ = ‘run’, mcp_read_memory_ids: ‘List[str]’ = <factory>, require_approval: ‘Optional[bool]’ = None, allow_subagents: ‘bool’ = False)
| Field | Type | Default |
|---|---|---|
workspace_mode |
str |
'read_only' |
allowed_roots |
List[str] |
[] |
allow_dirty_workspace |
bool |
False |
network |
str |
'none' |
allowed_tools |
List[str] |
[] |
denied_tools |
List[str] |
[] |
allowed_env |
List[str] |
[] |
mcp_access |
str |
'read_only' |
mcp_memory_scope |
str |
'run' |
mcp_read_memory_ids |
List[str] |
[] |
require_approval |
Optional[bool] |
None |
allow_subagents |
bool |
False |
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.
HarnessMemoryRefine
Section titled “HarnessMemoryRefine”HarnessMemoryRefine( provider: Any, *, settings: Optional[RefineSettings] = None, model_factory: Callable[[Mapping[str, Any]], Any] = <function _default_model at 0x108b3b740>, task_of: Optional[Callable[[str], str]] = None,)memorizz.metaharness.memory_refine.HarnessMemoryRefine · Source
Plan and run refine cycles over the memories harnesses share.
answers
Section titled “answers”answers( memory_id: str, user_id: Optional[str] = None, *, only_new: bool = False,) -> List[Dict[str, Any]]The raw answers harness runs saved to this memory, oldest first.
findings
Section titled “findings”findings( memory_id: str, user_id: Optional[str] = None, *, include_replaced: bool = False,) -> List[Dict[str, Any]]What the memory knows: its findings, most confirmed first.
plan( memory_id: str, user_id: Optional[str] = None, *, model: Any = None,) -> Dict[str, Any]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: str, user_id: Optional[str] = None, *, dry_run: bool = False, trigger: str = 'manual', model: Any = None,) -> Dict[str, Any]Run one cycle over this memory and return its report.
list_runs
Section titled “list_runs”list_runs(memory_id: str, limit: int = 10) -> List[Dict[str, Any]]Stored cycles of this memory, newest first.
maybe_start
Section titled “maybe_start”maybe_start(memory_id: str, user_id: Optional[str] = None) -> boolStart 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.
RefineSettings
Section titled “RefineSettings”RefineSettings(path: Optional[Path] = None)memorizz.metaharness.memory_refine.RefineSettings · Source
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.
AgentHarness
Section titled “AgentHarness”AgentHarness(*args, **kwargs)memorizz.metaharness.base.AgentHarness · Source
Helper class that provides a standard way to create an ABC using inheritance.
See the memory-first meta-harness guide for the adapter security matrix and complete SDK, CLI, UI, and MCP workflows.
Runtime policies
Section titled “Runtime policies”governed_tool
Section titled “governed_tool”governed_tool( *, deterministic: bool = True, side_effects: bool = False, requires_approval: Optional[bool] = None, approval_reason: Optional[str] = None, domains: Sequence[str] = (), aliases: Sequence[str] = (), deprecated_arguments: Optional[Mapping[str, str]] = None, cacheable: bool = False, cache_ttl_seconds: Optional[float] = None,) -> Callable[[Callable[..., Any]], Callable[..., Any]]memorizz.tooling.governed_tool · Source
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.
ToolPolicy
Section titled “ToolPolicy”ToolPolicy( deterministic: bool = True, side_effects: bool = False, requires_approval: bool = False, approval_reason: Optional[str] = None, domains: tuple[str, ...] = (), aliases: tuple[str, ...] = (), deprecated_arguments: Mapping[str, str] = <factory>, cacheable: bool = False, cache_ttl_seconds: Optional[float] = None,)memorizz.tooling.ToolPolicy · Source
Runtime governance metadata attached to a trusted callable.
| Field | Type | Default |
|---|---|---|
deterministic |
bool |
True |
side_effects |
bool |
False |
requires_approval |
bool |
False |
approval_reason |
Optional[str] |
None |
domains |
tuple[str, ...] |
() |
aliases |
tuple[str, ...] |
() |
deprecated_arguments |
Mapping[str, str] |
{} |
cacheable |
bool |
False |
cache_ttl_seconds |
Optional[float] |
None |
ToolCacheConfig
Section titled “ToolCacheConfig”ToolCacheConfig( enabled: bool = True, ttl_seconds: float = 300.0, scope: str = 'agent', mcp: str = 'annotated', max_result_chars: int = 200000, freshness_by_domain: Dict[str, float] = <factory>,)memorizz.tool_cache.ToolCacheConfig · Source
How a MemAgent reuses tool results.
| Field | Type | Default |
|---|---|---|
enabled |
bool |
True |
ttl_seconds |
float |
300.0 |
scope |
str |
'agent' |
mcp |
str |
'annotated' |
max_result_chars |
int |
200000 |
freshness_by_domain |
Dict[str, float] |
{'mcp': 300.0, 'inventory': 60.0, 'calendar': 60.0} |
ToolResultPolicy
Section titled “ToolResultPolicy”ToolResultPolicy( offload_above_chars: int = 8000, offload_above_tokens: Optional[int] = None, expansion_tool_names: frozenset[str] = <factory>, digest_chars: int = 360, persist_all_results: bool = False,)memorizz.tooling.ToolResultPolicy · Source
Control when full tool output is replaced by an auditable pointer.
| Field | Type | Default |
|---|---|---|
offload_above_chars |
int |
8000 |
offload_above_tokens |
Optional[int] |
None |
expansion_tool_names |
frozenset[str] |
frozenset({'expand_tool_result', 'retrieve_tool_log_entry'}) |
digest_chars |
int |
360 |
persist_all_results |
bool |
False |
ToolOutcome
Section titled “ToolOutcome”ToolOutcome( status: ToolOutcomeStatus = <ToolOutcomeStatus.SUCCESS: success>, reason_code: Optional[str] = None, provider: Optional[str] = None, primary_provider: Optional[str] = None, fallback_provider: Optional[str] = None, retryable: Optional[bool] = None, result_count: Optional[int] = None, fallback_used: bool = False, degraded: bool = False,)memorizz.tool_outcomes.ToolOutcome · Source
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.
| Field | Type | Default |
|---|---|---|
status |
ToolOutcomeStatus |
<ToolOutcomeStatus.SUCCESS: 'success'> |
reason_code |
Optional[str] |
None |
provider |
Optional[str] |
None |
primary_provider |
Optional[str] |
None |
fallback_provider |
Optional[str] |
None |
retryable |
Optional[bool] |
None |
result_count |
Optional[int] |
None |
fallback_used |
bool |
False |
degraded |
bool |
False |
ToolOutcomeStatus
Section titled “ToolOutcomeStatus”memorizz.tool_outcomes.ToolOutcomeStatus (enum) · Source
Terminal state for one tool execution.
| Value | |
|---|---|
SUCCESS |
'success' |
EMPTY |
'empty' |
DEGRADED |
'degraded' |
FALLBACK |
'fallback' |
PROVIDER_ERROR |
'provider_error' |
ERROR |
'error' |
ToolResult
Section titled “ToolResult”ToolResult(value: Any, outcome: ToolOutcome, display: Optional[Dict[str, Any]] = None)memorizz.tool_outcomes.ToolResult · Source
A tool payload with an explicit outcome.
MemAgent unwraps value before model serialization, preserving the
tool’s established result schema.
| Field | Type | Default |
|---|---|---|
value |
Any |
required |
outcome |
ToolOutcome |
required |
display |
Optional[Dict[str, Any]] |
None |
ContextPolicy
Section titled “ContextPolicy”ContextPolicy( progressive_tool_disclosure: bool = True, tool_top_k: int = 5, sticky_tool_limit: int = 15, stable_tool_list_tokens: int = 6000, approval_ttl_seconds: int = 900, max_tool_invocations_per_turn: int = 20, max_tool_attempts_per_call: int = 2, compact_at: int = 80, keep_recent_messages: int = 6, always_visible_tools: Tuple[str, ...] = (), tool_min_similarity: Optional[float] = None, tool_selection: Any = None, tool_selection_margin: float = 0.15,)memorizz.tooling.ContextPolicy · Source
Bounded context and progressive-disclosure defaults for an agent.
| Field | Type | Default |
|---|---|---|
progressive_tool_disclosure |
bool |
True |
tool_top_k |
int |
5 |
sticky_tool_limit |
int |
15 |
stable_tool_list_tokens |
int |
6000 |
approval_ttl_seconds |
int |
900 |
max_tool_invocations_per_turn |
int |
20 |
max_tool_attempts_per_call |
int |
2 |
compact_at |
int |
80 |
keep_recent_messages |
int |
6 |
always_visible_tools |
Tuple[str, ...] |
() |
tool_min_similarity |
Optional[float] |
None |
tool_selection |
Any |
None |
tool_selection_margin |
float |
0.15 |
RetrievalPolicy
Section titled “RetrievalPolicy”RetrievalPolicy( conversation_scope: str = 'memory', knowledge_base_scope: str = 'memory', knowledge_base_namespaces: Tuple[str, ...] = (), entity_scope: str = 'memory', candidate_limit: int = 5, max_items: int = 4, query_expansion: bool = False, max_query_variants: int = 2, dedupe_parent_sources: bool = False, scoring: Optional[Dict[str, Any]] = None, retention: Optional[Dict[str, Any]] = None, max_chars_per_item: Optional[int] = 600, max_recall_chars: Optional[int] = None, workflow_scope: str = 'disabled', read_routing: Any = None, read_threshold: float = 0.5, also_recall_from: Tuple[str, ...] = (),)memorizz.retrieval.RetrievalPolicy · Source
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.
| Field | Type | Default |
|---|---|---|
conversation_scope |
str |
'memory' |
knowledge_base_scope |
str |
'memory' |
knowledge_base_namespaces |
Tuple[str, ...] |
() |
entity_scope |
str |
'memory' |
candidate_limit |
int |
5 |
max_items |
int |
4 |
query_expansion |
bool |
False |
max_query_variants |
int |
2 |
dedupe_parent_sources |
bool |
False |
scoring |
Optional[Dict[str, Any]] |
None |
retention |
Optional[Dict[str, Any]] |
None |
max_chars_per_item |
Optional[int] |
600 |
max_recall_chars |
Optional[int] |
None |
workflow_scope |
str |
'disabled' |
read_routing |
Any |
None |
read_threshold |
float |
0.5 |
also_recall_from |
Tuple[str, ...] |
() |
ConsolidationConfig
Section titled “ConsolidationConfig”ConsolidationConfig( enabled: bool = False, every_n_turns: int = 20, every_hours: float = 24.0, auto_apply: bool = True, review_attributes: bool = True, extract_facts: bool = True, max_entities: int = 40, max_threads: int = 5, max_messages_per_thread: int = 40, relations: Any = None, relation_min_similarity: float = 0.5, relation_threshold: float = 0.5, max_relation_pairs: int = 60, refine_cycle: bool = False, refine_interval_hours: float = 24.0, refine_verify: bool = True, refine_verify_model_checks: int = 3, refine_tool_review: str = 'propose', refine_compact: bool = True, refine_drop_suppressed_vectors: bool = False,)memorizz.learning.consolidation.ConsolidationConfig · Source
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.
| Field | Type | Default |
|---|---|---|
enabled |
bool |
False |
every_n_turns |
int |
20 |
every_hours |
float |
24.0 |
auto_apply |
bool |
True |
review_attributes |
bool |
True |
extract_facts |
bool |
True |
max_entities |
int |
40 |
max_threads |
int |
5 |
max_messages_per_thread |
int |
40 |
relations |
Any |
None |
relation_min_similarity |
float |
0.5 |
relation_threshold |
float |
0.5 |
max_relation_pairs |
int |
60 |
refine_cycle |
bool |
False |
refine_interval_hours |
float |
24.0 |
refine_verify |
bool |
True |
refine_verify_model_checks |
int |
3 |
refine_tool_review |
str |
'propose' |
refine_compact |
bool |
True |
refine_drop_suppressed_vectors |
bool |
False |
MemoryRoutingConfig
Section titled “MemoryRoutingConfig”MemoryRoutingConfig( enabled: bool = False, router: str = 'auto', model: Optional[str] = None, run_id: Optional[str] = None, capture_turns: bool = True, min_confidence: float = 0.5, entity_capture: Optional[bool] = None, extraction_gate: Any = None, gate_threshold: float = 0.5, dedupe_writes: Any = None, extra: Dict[str, Any] = <factory>,)memorizz.memagent.memory_routing.MemoryRoutingConfig · Source
How an agent routes its own memory writes. Off by default.
| Field | Type | Default |
|---|---|---|
enabled |
bool |
False |
router |
str |
'auto' |
model |
Optional[str] |
None |
run_id |
Optional[str] |
None |
capture_turns |
bool |
True |
min_confidence |
float |
0.5 |
entity_capture |
Optional[bool] |
None |
extraction_gate |
Any |
None |
gate_threshold |
float |
0.5 |
dedupe_writes |
Any |
None |
extra |
Dict[str, Any] |
{} |
RerankerConfig
Section titled “RerankerConfig”RerankerConfig( provider: str, model: Optional[str] = None, run_id: Optional[str] = None, function: Optional[Callable[..., Any]] = None,)memorizz.reranking.RerankerConfig · Source
An agent’s own reranker; from_value(None) is None (follow the store).
| Field | Type | Default |
|---|---|---|
provider |
str |
required |
model |
Optional[str] |
None |
run_id |
Optional[str] |
None |
function |
Optional[Callable[..., Any]] |
None |
ConsolidationPlan
Section titled “ConsolidationPlan”ConsolidationPlan( plan_id: str, memory_id: str, user_id: Optional[str], ops: Tuple[ConsolidationOp, ...], model: Optional[str] = None, created_at: str = <factory>, warnings: Tuple[str, ...] = (),)memorizz.learning.consolidation.ConsolidationPlan · Source
A dry run: what a consolidation pass would change, and why.
| Field | Type | Default |
|---|---|---|
plan_id |
str |
required |
memory_id |
str |
required |
user_id |
Optional[str] |
required |
ops |
Tuple[ConsolidationOp, ...] |
required |
model |
Optional[str] |
None |
created_at |
str |
'2026-12-05T09:21:43.195427+00:00' |
warnings |
Tuple[str, ...] |
() |
CompletionPolicy
Section titled “CompletionPolicy”CompletionPolicy( enabled: bool = False, max_rejections: int = 2, fail_closed: bool = True, require_tool_calls: bool = False, forbidden_response_patterns: Sequence[str] = <factory>, validator: Optional[CompletionValidator] = None, validator_name: Optional[str] = None, validator_required: bool = False, delivery_mode: str = 'buffered', retry_instruction: str = 'The host rejected that proposed final response: {reason} Continue working from the current state, use the available tools, and propose a new final response only after the acceptance criteria pass.',)memorizz.completion.CompletionPolicy · Source
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.
| Field | Type | Default |
|---|---|---|
enabled |
bool |
False |
max_rejections |
int |
2 |
fail_closed |
bool |
True |
require_tool_calls |
bool |
False |
forbidden_response_patterns |
Sequence[str] |
() |
validator |
Optional[CompletionValidator] |
None |
validator_name |
Optional[str] |
None |
validator_required |
bool |
False |
delivery_mode |
str |
'buffered' |
retry_instruction |
str |
'The host rejected that proposed final response: {reason}… |
Model providers
Section titled “Model providers”LLMProvider
Section titled “LLMProvider”LLMProvider(*args, **kwargs)memorizz.llms.llm_provider.LLMProvider · Source
A generic protocol that defines the contract for any LLM provider to be compatible with both the OpenAI and AzureOpenAI classes.
generate
Section titled “generate”generate( messages: List[Dict[str, str]], tools: Optional[List[Dict[str, Any]]] = None, tool_choice: str = 'auto',) -> AnyGenerate a response from a list of messages (chat format), optionally with tool calling.
generate_stream
Section titled “generate_stream”generate_stream( messages: List[Dict[str, str]], tools: Optional[List[Dict[str, Any]]] = None, tool_choice: str = 'auto',) -> Generator[Dict[str, Any], None, None]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”: <full response object>} when tool calls are detected
- {“type”: “done”, “content”: “<full accumulated text>”} 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
Section titled “get_config”get_config() -> Dict[str, Any]Returns a serializable dictionary of the provider’s configuration. This is used for saving and reconstructing the agent.
get_last_usage
Section titled “get_last_usage”get_last_usage() -> Optional[Dict[str, int]]Return token usage details (prompt/completion/total) from the most recent call.
get_context_window_tokens
Section titled “get_context_window_tokens”get_context_window_tokens() -> Optional[int]Return the provider’s context window size in tokens, when known.
Memory providers
Section titled “Memory providers”MemoryProvider
Section titled “MemoryProvider”MemoryProvider(config: Dict[str, Any])memorizz.memory_provider.base.MemoryProvider · Source
Abstract base class for memory providers.
store( data: Dict[str, Any] = None, memory_store_type: str = None, memory_id: str = None, memory_unit: Any = None,) -> strStore data in the memory provider.
Arguments
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
Section titled “retrieve_by_query”retrieve_by_query( query: Dict[str, Any], memory_store_type: str = None, limit: int = 1, memory_id: str = None, memory_type: str = None, **kwargs,) -> Optional[Dict[str, Any]]Retrieve a document from the memory provider.
Arguments
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_idlimit(int): Maximum number of results to return- **kwargs Additional provider-specific parameters. Includes
user_idfor multi-tenant scoping. Omitting it is an administrative/unscoped read, explicitly passingNoneselects anonymous/legacy rows, and a string selects that exact tenant.
retrieve_by_id
Section titled “retrieve_by_id”retrieve_by_id(id: str, memory_store_type: str) -> Optional[Dict[str, Any]]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
Section titled “list_all”list_all(memory_store_type: str, user_id: Any = <not set>) -> List[Dict[str, Any]]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
Section titled “retrieve_conversation_history_ordered_by_timestamp”retrieve_conversation_history_ordered_by_timestamp( memory_id: str, memory_type: str = None, limit: int = None, user_id: Any = <not set>, thread_id: Optional[str] = None,) -> List[Dict[str, Any]]Retrieve the conversation history ordered by timestamp.
Arguments
memory_id(str): The memory ID to retrieve history formemory_type(str or MemoryType, optional): Type of memory (typically CONVERSATION_MEMORY)limit(int, optional): Maximum number of entries to returnuser_id(str, optional (keyword)): Multi-tenant scope. Omitting it is an administrative/unscoped read, explicitly passingNoneselects 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
Section titled “query_observability_records”query_observability_records( memory_store_type: Any, *, agent_ids: Optional[List[str]] = None, memory_ids: Optional[List[str]] = None, thread_id: Optional[str] = None, user_id: Any = <not set>, application_id: Optional[str] = None, record_type: Optional[str] = None, tool_name: Optional[str] = None, success: Optional[bool] = None, event_filters: Optional[Dict[str, Any]] = None, start_time: Any = None, end_time: Any = None, limit: int = 250, cursor: Optional[str] = None,) -> Dict[str, Any]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
Section titled “invalidate_semantic_cache”invalidate_semantic_cache( *, agent_id: Optional[str] = None, memory_id: Optional[str] = None, domains: Optional[List[str]] = None, tags: Optional[List[str]] = None, data_version: Optional[str] = None,) -> intDelete 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
Section titled “store_memagent”store_memagent(memagent: MemAgent) -> strStore a memagent in the memory provider.
delete_memagent
Section titled “delete_memagent”delete_memagent(agent_id: str, cascade: bool = False) -> boolDelete a memagent from the memory provider.
list_memagents
Section titled “list_memagents”list_memagents() -> List[Dict[str, Any]]List all memagents in the memory provider.
delete_scope
Section titled “delete_scope”delete_scope( *, memory_id: Optional[str] = None, user_id: Any = <not set>, agent_ids: Optional[List[str]] = None, keep_traces: bool = False,) -> Dict[str, Any]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() -> NoneClose 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
Section titled “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.