Python SDK API¶
This page covers the stable, high-value Python surface. Import public types from
memorizz unless a guide documents a provider-specific module.
MemAgent¶
memorizz.memagent.core.MemAgent
¶
MemAgent class that orchestrates manager components.
Attributes¶
last_tool_outcomes
property
¶
Structured outcomes from the most recent turn, in execution order.
Methods:¶
run(query, memory_id=None, thread_id=None, user_id=None, context=None, tool_context=None, observability_context=None, retrieval_policy=None)
¶
Run the agent with the given query using the new manager architecture.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
The user's query |
required |
memory_id
|
Optional[str]
|
Optional memory ID to use (if not provided, uses stored or default) |
None
|
thread_id
|
Optional[str]
|
Optional thread ID to use (if not provided, reuses current or creates new) |
None
|
user_id
|
Optional[str]
|
Optional end-user identifier for multi-tenant apps. When
provided, every memory unit written during this turn is tagged
with |
None
|
context
|
Optional[Dict[str, Any]]
|
Optional per-call ephemeral context (M2). When provided,
the dict is rendered as a structured system-role message
between the main system prompt and conversation history, so
the agent sees it for this turn only. It is intentionally
NOT persisted to Callers may pass any JSON-serialisable dict; unknown keys are included verbatim. |
None
|
tool_context
|
Optional[Dict[str, Any]]
|
Optional per-call dict made available to tool
functions via |
None
|
observability_context
|
Optional[Dict[str, Any]]
|
Optional content-free host provenance for the private trace bundle. Only a strict allowlist of routing, ownership, grounding, and fingerprint fields is retained; this dict is never sent to the LLM or conversation history. |
None
|
retrieval_policy
|
Any
|
A policy for this call only. A scope string
such as |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The agent's response |
run_stream_events(query, *, delivery_mode=None, cancellation=None, queue_size=64, **kwargs)
¶
Return a closeable, ordered v1 event stream (no private reasoning).
arun_stream_events(query, **kwargs)
async
¶
Async event iterator backed by one owned execution context/worker.
validate_configuration()
¶
Validate configured optional subsystems and return a stable report.
capability_report(*, preflight=False)
¶
Return package and configured-agent feature/provider states.
semantic_cache_stats()
¶
Return real hit/miss/bypass/write/eviction counters and provenance.
inspect_semantic_cache(query, *, thread_id=None, user_id=None, context=None, metadata=None, bypass_reason=None)
¶
Inspect cache provenance/freshness without returning cached content.
invalidate_semantic_cache(*, domains=None, tags=None, data_version=None)
¶
Invalidate semantic cache entries by operational domain or tag.
tool_cache_stats()
¶
Hits, misses, stored results, bypasses and the tool time saved.
enable_tool_cache(**config)
¶
Turn the tool-call cache on (ToolCacheConfig fields as keywords).
disable_tool_cache()
¶
Turn the tool-call cache off; stored results expire on their own.
invalidate_tool_cache(tool_name=None, *, user_id=None)
¶
Drop cached tool results (all, one tool's, and/or one user's).
generate_summaries(days_back=7, max_memories_per_summary=50, *, memory_id=None, user_id=None, thread_id=None, keep_recent=0, summary_type='automatic')
¶
Generate summaries by compressing memory units from a specified time period.
This method collects memory units from the specified time period, uses an LLM to compress them into emotionally and situationally relevant summaries, and stores them in the summaries collection.
Parameters:¶
days_back : int, optional
Number of days back to include in the summary (default: 7)
max_memories_per_summary : int, optional
Maximum number of memory units to include in each summary (default: 50)
memory_id : str, optional
Exact memory scope. When omitted, the configured/current memory
IDs are considered for backward compatibility.
user_id : str, optional
Exact tenant scope. None selects only anonymous/legacy rows;
this method never inherits a user from the most recent run.
thread_id : str, optional
Exact conversation thread. When omitted, all threads in the
selected memory/tenant scope may be compacted independently.
Returns:¶
List[str] List of summary IDs that were created
with_background_model(model=None)
¶
Run memory upkeep on a second, usually cheaper, model.
Pass an llm_config dict (saved with the agent, secrets left out),
a model instance from create_llm_provider, or None to go back
to the agent's own model. The user's turns keep the agent's model.
Returns the agent, for chaining.
wait_for_memory_upkeep(timeout=None)
¶
Wait for background memory upkeep (thread compaction, reflection, consolidation) to finish. True when nothing is still running.
describe_memory()
¶
What this agent remembers and how it recalls it.
The active memory types, whether entity facts are on, the memory tools the model can call, the retrieval policy, the background model and the consolidation schedule.
with_memory_consolidation(enabled=True, **settings)
¶
Consolidate memory in the background every so many turns or hours.
Settings are those of :class:ConsolidationConfig: every_n_turns
(20), every_hours (24), auto_apply (True), review_attributes,
extract_facts, max_entities, max_threads and
max_messages_per_thread. Passes run on the background model.
Returns the agent, for chaining.
with_memory_routing(router='auto', *, enabled=True, **settings)
¶
Route the agent's own memory writes to the store each belongs in.
router is "auto" (a fine-tuned router if there is one, else
OpenAI Decisions with an OpenAI key, else the background model),
"openai_decisions", "llm" or "finetuned"; settings are
those of :class:MemoryRoutingConfig (model, run_id,
capture_turns, min_confidence). Returns the agent.
with_reranker(reranker)
¶
Rerank what the agent recalls: "voyage", "cohere",
"openai_decisions" (optionally "voyage:rerank-2.5-lite"),
"finetuned:<run id>", "off", or None to follow the store.
Returns the agent.
remember(text, *, memory_id=None, user_id=None, thread_id=None, source='api')
¶
Keep text, filed in the store the memory router picks.
A durable fact or policy goes to the knowledge base, facts about the
user or a named person or thing to entity memory, working notes to
short-term memory; nothing is kept when the router judges it not
worth keeping. When the router is unsure or names a store the agent
does not file directly, the text goes to the knowledge base. Uses the
agent's router (memory_routing), or the automatic one when routing
is off. Returns a receipt: stored, memory_type, the ids
written and the router's answer with its reason.
plan_memory_consolidation(memory_id=None, *, user_id=None, thread_ids=None, since=None, knowledge_base=False)
¶
Dry-run consolidation of one memory and user; nothing changes.
Merges duplicate entities, suppresses duplicate summaries (and, with
knowledge_base=True, duplicate knowledge-base chunks), and, on the
background model, retires facts stored twice or contradicted by a
newer one and finds facts the user stated in thread_ids that were
never stored. Without thread_ids it reads the threads this agent
served since the last pass. user_id=None is the anonymous scope.
apply_memory_consolidation(plan, approved_by, reason=None)
¶
Make a consolidation plan's changes (a plan, its dict, or its id).
Nothing is deleted; :meth:restore_memory_consolidation undoes it.
restore_memory_consolidation(plan_id, *, approved_by, memory_id=None, user_id=None)
¶
Undo an applied consolidation plan in one memory and user.
pending_memory_consolidations()
¶
Plans made in this process that are waiting to be applied.
observability_summary(memory_id, user_id, *, thread_id=None, limit=1000)
¶
Return tenant-scoped operational counts without exposing row bodies.
get_trace_context()
¶
Return identifiers for linking application outcomes to the last turn.
build_personalization_context(query, *, memory_id=None, user_id=None, preferences=None, writing_samples=None, additional_memories=None, policy=None, exclude_thread_id=None)
¶
Build explicit, tenant-scoped personalization without running an LLM.
Cross-thread conversation recall occurs only when the supplied
:class:~memorizz.personalization.PersonalizationPolicy enables it and
both memory_id and user_id are bound. Host preferences and
writing samples are accepted as already-authorized application data.
last_memory_context_evidence()
¶
Return the content-free memory supply snapshot for the latest turn.
record_feedback(rating, *, verified=True, source='user', label=None, comment=None, include_comment=False, trace_context=None, external_id=None)
¶
Join verified application feedback to a concrete agent trace.
record_task_outcome(status, *, verified=True, source='application', score=None, metrics=None, trace_context=None, external_id=None)
¶
Join a business/task outcome to a concrete agent trace.
has_automations()
¶
Return True when automation storage + tools are available for this agent.
create_automation(name, schedule_type, *, query_template, cron_expr=None, interval_seconds=None, timezone=None, memory_id=None, whatsapp_to=None, max_run_seconds=900, retry_max_attempts=1, retry_backoff_seconds=60, misfire_policy='skip')
¶
Create a scheduled automation job for this agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Human-readable job name (e.g. "Daily briefing"). |
required |
schedule_type
|
str
|
One of "cron", "interval", or "one_shot". |
required |
query_template
|
str
|
The prompt template to run. Supports placeholders: {today_iso}, {scheduled_for_iso}, {now_utc_iso}, {timezone}. |
required |
cron_expr
|
Optional[str]
|
5-field cron expression (required when schedule_type="cron"). |
None
|
interval_seconds
|
Optional[int]
|
Seconds between runs (required when schedule_type="interval"). |
None
|
timezone
|
Optional[str]
|
IANA timezone name. Falls back to agent's default_timezone or MEMORIZZ_DEFAULT_TIMEZONE env var. |
None
|
memory_id
|
Optional[str]
|
Memory ID for the automation's conversation thread. Auto-generated if not provided. |
None
|
whatsapp_to
|
Optional[List[str]]
|
List of WhatsApp recipient numbers. When provided, results are delivered via WhatsApp/Twilio. |
None
|
max_run_seconds
|
int
|
Maximum execution time per run (default 900). |
900
|
retry_max_attempts
|
int
|
Number of retry attempts on failure (default 1). |
1
|
retry_backoff_seconds
|
int
|
Backoff between retries (default 60). |
60
|
misfire_policy
|
str
|
What to do on missed runs: "skip" or "run". |
'skip'
|
Returns:
| Type | Description |
|---|---|
AutomationJob
|
The created AutomationJob instance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If automations are unavailable, timezone is invalid, or required parameters are missing. |
Example::
job = agent.create_automation(
name="Morning News Digest",
schedule_type="cron",
cron_expr="0 8 * * *",
timezone="America/New_York",
query_template="Give me today's top 5 tech news for {today_iso}",
)
print(f"Created job {job.job_id}, next run: {job.next_run_at}")
list_automations(*, enabled=None)
¶
List automation jobs belonging to this agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
enabled
|
Optional[bool]
|
Filter by enabled state. None returns all jobs. |
None
|
Returns:
| Type | Description |
|---|---|
List[AutomationJob]
|
List of AutomationJob instances. |
get_automation(job_id)
¶
Get a single automation job by ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
The job identifier. |
required |
Returns:
| Type | Description |
|---|---|
Optional[AutomationJob]
|
AutomationJob if found, None otherwise. |
pause_automation(job_id)
¶
Pause a running automation job.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
The job identifier to pause. |
required |
Returns:
| Type | Description |
|---|---|
AutomationJob
|
The updated AutomationJob with enabled=False. |
resume_automation(job_id)
¶
Resume a paused automation job.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
The job identifier to resume. |
required |
Returns:
| Type | Description |
|---|---|
AutomationJob
|
The updated AutomationJob with enabled=True. |
trigger_automation(job_id)
¶
Trigger an immediate run of an automation job.
Sets next_run_at to now and enables the job so the worker picks it up on its next poll cycle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
The job identifier to trigger. |
required |
Returns:
| Type | Description |
|---|---|
AutomationJob
|
The updated AutomationJob. |
list_automation_runs(job_id, *, limit=50)
¶
List execution history for a specific automation job.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
The job identifier. |
required |
limit
|
int
|
Maximum number of runs to return (default 50). |
50
|
Returns:
| Type | Description |
|---|---|
List[AutomationRun]
|
List of AutomationRun instances, most recent first. |
delete_automation(job_id)
¶
Permanently delete an automation job.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
The job identifier to delete. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the job was deleted, False if not found. |
list_approval_proposals(*, status=None, limit=100)
¶
List durable approval proposals owned by this agent.
approve(proposal_id, *, approver_id, reason=None)
¶
Record a host-side approval decision without executing the tool.
reject(proposal_id, *, approver_id, reason=None)
¶
Record a host-side rejection decision.
cancel_approval(proposal_id, *, approver_id, reason=None)
¶
Cancel a pending proposal (host-friendly alias for rejection).
resume_approval(proposal_id, *, continue_model=True)
¶
Execute an approved checkpoint once and return structured evidence.
Set continue_model=False for deterministic host workflows that need
the exact tool result without asking an LLM to comment on it.
close(*, cleanup_scope=None, close_memory_provider=True, close_model_provider=False)
¶
Close agent-owned runtime resources and optionally delete a scope.
cleanup_scope is forwarded to a provider's delete_scope before
connections are closed. It must contain an exact memory_id,
user_id, and/or agent_ids boundary; providers retain their own
fail-closed validation.
lifecycle(*, cleanup_scope=None, close_memory_provider=True, close_model_provider=False)
¶
Manage the agent lifecycle with optional exact-scope cleanup.
Persistence¶
agent.save() stores the current definition in its configured memory provider.
MemAgent.load(agent_id, memory_provider=provider, **overrides) restores it;
omit memory_provider only when the definition lives in the default filesystem
provider. Tool code is not stored: pass the functions back with
tools=[...], which also restores their governed_tool policies.
MemAgentBuilder.with_knowledge_base(ids) attaches knowledge bases by the ids
ingest_knowledge returns. Their chunks are recalled automatically whenever
knowledge_base is one of the agent's memory types (the assistant,
workflow and deep_research modes include it), whatever memory_id they
were ingested under. Rebuilding a named agent keeps its stored knowledge bases
unless with_knowledge_base is called.
Personalization context¶
PersonalizationContext is the provider-neutral boundary between durable
memory and a host application's generation prompt. Cross-thread conversation
recall is disabled by default and becomes available only when the host opts in
with an exact memory_id and authenticated user_id.
from memorizz import PersonalizationPolicy
personalization = agent.build_personalization_context(
"Draft a LinkedIn post about memory observability",
memory_id="workspace-7",
user_id="user-42",
exclude_thread_id="current-thread",
preferences={"preferred_tone": "concise and technical"},
policy=PersonalizationPolicy(
conversation_recall=True,
min_relevance_score=0.70,
max_conversation_memories=2,
),
)
response = agent.run(
"Draft the post.",
memory_id="workspace-7",
user_id="user-42",
context={"personalization_context": personalization.to_dict()},
)
The rendered prompt tells the model to use memories only when they naturally
improve the current answer. personalization.trace_summary() and
agent.last_memory_context_evidence() contain counts, scores, attribute names,
and hashed references, not the underlying profile values or conversation text.
With continual learning on, recall arrives as one evidence pack: its items are
counted in source_counts["evidence_items"], by source in
evidence_source_counts, and referenced in evidence_refs.
learning_control_plane.explain_last_retrieval() explains each choice.
Canonical user entities and duplicate cleanup¶
Use a stable application-owned identity_key for profile writes. Name changes
then update one deterministic entity instead of creating a second profile.
This field is deliberately absent from the model-facing entity_memory_upsert
tool: only a trusted host or application may bind a canonical identity.
Existing cross-name duplicates are never merged heuristically: preview an exact
selection first, inspect conflicts, and only then apply a reversible soft
supersession.
from memorizz.long_term.semantic.entity_memory import EntityMemory
entities = EntityMemory(provider)
preview = entities.consolidate_duplicate_entities(
memory_id="workspace-7",
user_id="user-42",
entity_ids=["reviewed-id-1", "reviewed-id-2"],
canonical_identity_key="authenticated_user",
)
# After operator review of preview["groups"]:
applied = entities.consolidate_duplicate_entities(
memory_id="workspace-7",
user_id="user-42",
entity_ids=["reviewed-id-1", "reviewed-id-2"],
canonical_identity_key="authenticated_user",
apply=True,
)
The apply path writes and verifies the merged canonical row before setting
metadata.superseded_by on aliases. It does not delete records. Anonymous
legacy rows require the separate explicit migrate_legacy_scope operator step;
authenticated runtime reads never adopt them automatically.
MemAgentBuilder¶
memorizz.memagent.builders.agent_builder.MemAgentBuilder
¶
Builder pattern for constructing MemAgent instances.
This provides a fluent interface for complex MemAgent configurations, making them more readable and maintainable.
Methods:¶
with_name(name)
¶
Set a display name for the agent.
with_instruction(instruction)
¶
Set the agent instruction.
with_model(model)
¶
Set the LLM model.
with_llm_config(config)
¶
Set the LLM configuration.
with_persona(persona=None, name=None, expertise=None)
¶
Set the agent persona.
with_favorite(is_favorite=True)
¶
Mark the built agent as favorite or non-favorite.
with_memory_provider(provider)
¶
Set the memory provider.
with_memory_ids(memory_ids)
¶
Set memory IDs.
with_application_mode(mode)
¶
Set the application mode.
with_tools(tools)
¶
Add tools to the agent.
with_tool(tool)
¶
Add a single tool to the agent.
with_toolbox(toolbox)
¶
Attach a progressively retrieved Toolbox and its callable bindings.
with_mcp_servers(mcp_servers)
¶
Attach MCP server configurations to the agent.
with_internet_access_provider(provider)
¶
Attach an internet access provider.
with_skills_marketplace(provider, config=None)
¶
Configure a skills marketplace without post-build mutation.
with_skill_paths(skill_paths)
¶
Attach skill markdown file paths to the agent.
with_sandbox(provider)
¶
Attach a sandbox provider instance, name, or provider config.
with_sandbox_provider(provider)
¶
Backward-compatible alias for :meth:with_sandbox.
with_browser_control(provider)
¶
Attach a browser-control provider instance, name, or config.
with_browser_control_provider(provider)
¶
Compatibility alias for :meth:with_browser_control.
with_meta_harness(meta_harness=None, *, mode='delegate', default_harness='auto', config=None)
¶
Attach the memory-first external-harness control plane.
delegate exposes bounded harness invocation tools to the native
MemAgent loop. runtime makes the selected harness execute the
complete turn while MemoRizz retains memory, approval, and trace
ownership. Passing None lazily builds the standard Codex, Claude
Code, and OpenHands registry from the local configuration.
with_execution_harness(harness, *, meta_harness=None, config=None)
¶
Convenience alias for full-runtime meta-harness execution.
with_semantic_cache(enabled=True, threshold=0.85, scope='session')
¶
Configure semantic caching (isolated to a session by default).
with_tool_cache(enabled=True, *, ttl_seconds=300.0, scope='agent', mcp='annotated')
¶
Reuse results of repeated calls to cacheable tools.
Python tools opt in with @governed_tool(cacheable=True); MCP tools
are cached when their server marks them read-only and idempotent
(mcp="off" to never cache MCP results).
with_embedding_provider(provider, config=None)
¶
Set the embedding provider.
with_retrieval_policy(policy)
¶
Set automatic memory-retrieval scope independently of storage.
with_background_model(model)
¶
Run memory upkeep (summaries, reflection, consolidation) on a
second model: an llm_config dict or a model instance.
with_memory_consolidation(enabled=True, **settings)
¶
Consolidate memory in the background; see ConsolidationConfig.
with_memory_routing(router='auto', **settings)
¶
File what the agent remembers in the store each memory belongs in.
router is "auto" (a fine-tuned router if there is one, else
OpenAI Decisions with an OpenAI key, else the background model),
"openai_decisions", "llm" or "finetuned". Settings are
those of MemoryRoutingConfig: model, run_id,
capture_turns (route each user message after its turn, default
True) and min_confidence (0.5). Pass router=False to turn it off.
with_reranker(reranker)
¶
Rerank what the agent recalls: "voyage", "cohere",
"openai_decisions" (or "voyage:rerank-2.5-lite"),
"finetuned:<run id>" or "off". Without it the agent follows
the store's reranker, if any.
with_context_policy(policy)
¶
with_tool_result_policy(policy)
¶
with_approval_store(store)
¶
with_skills(skills, *, persistence='skillbox')
¶
Attach authored procedural skills without enabling continual learning.
with_skill_retrieval(enabled=True, top_k=2, min_similarity=0.7)
¶
Configure progressive Skillbox retrieval independently of learning.
with_skillbox(skillbox)
¶
Attach an authored/learned Skillbox independently of learning.
with_continual_learning(enabled=True, config=None)
¶
Enable/disable the workflow→skill continual learning loop.
config keys follow PromotionConfig (e.g. min_executions,
require_shadow, shadow_evaluation_enabled,
promotion_every_n_runs).
with_learning_control_plane(enabled=True, config=None, **settings)
¶
Enable bounded evidence, event compilation, and governed forgetting.
with_workflow_outcome_evaluator(evaluator)
¶
Set a runtime business-success rubric for captured workflows.
with_delegation(delegates=None, **config)
¶
Make delegates operational and configure orchestration behavior.
with_delegates(delegates)
¶
Set delegates and enable model-generated orchestration by default.
with_semantic_layer(catalog)
¶
Attach a governed semantic catalog and query planner.
with_completion_policy(policy)
¶
Attach a host-enforced final-response acceptance policy.
with_automations_enabled(enabled=True)
¶
Enable/disable durable automations tooling (when supported by provider).
with_default_timezone(tz)
¶
Set a default IANA timezone used by automation tools when omitted.
with_self_aware(enabled=True, config=None)
¶
Enable/disable self-awareness host codebase tooling.
with_entity_memory(enabled=True)
¶
Explicitly enable or disable entity memory for the agent.
with_tool_access(access)
¶
Set tool access level.
with_max_steps(steps)
¶
Set maximum execution steps.
with_verbose(verbose=True)
¶
Enable verbose logging.
with_oracle_from_env(*, ensure_ready=True, provision_if_missing=None, preflight=True, require_preflight_ok=True, **provider_overrides)
¶
Attach an Oracle provider using the documented environment.
By default the local Docker runtime is started/readied first and a
provider preflight is retained on the built agent in
environment_reports["oracle"].
with_e2b_from_env(*, validate=True, **provider_config)
¶
Attach a stateful E2B provider using E2B_API_KEY by default.
build(validate=True, persist=False)
¶
build_and_save(validate=True)
¶
Build, validate, and persist the configured agent.
Meta-harness¶
memorizz.metaharness.service.MetaHarness
¶
Route, govern, execute, remember, and evaluate agent harness runs.
Methods:¶
from_env(*, memory_provider=None, agent=None, run_store=None, approval_store=None, allowed_workspace_roots=None)
classmethod
¶
register(adapter)
¶
list_harnesses(*, probe=True)
¶
probe(name)
¶
run(task)
¶
start(task)
¶
stream(run_id, *, after=0, poll_seconds=0.1)
¶
approve(proposal_id, *, approver_id, reason=None)
¶
reject(proposal_id, *, approver_id, reason=None)
¶
resume_approval(proposal_id)
¶
Consume and synchronously execute one approved exact checkpoint.
resume_approval_start(proposal_id)
¶
Consume an approval and resume its checkpoint in a background worker.
cancel(run_id, *, before_start=False)
¶
Cancel a run. With before_start, a run this process has not
created yet (a delegate's, being prepared) starts already canceled
instead of raising KeyError.
retry(run_id)
¶
Run a finished run's exact task again and wait for the result.
run_plan(task, plan)
¶
Run a bounded serial planner/implementer/reviewer composition.
compare(task, harnesses)
¶
Run an explicit comparison; callers must provide isolated workspaces for writes.
recover_interrupted_runs()
¶
Mark orphaned queued/running rows interrupted when a worker starts.
close()
¶
memorizz.metaharness.models.HarnessTask
dataclass
¶
memorizz.metaharness.base.AgentHarness
¶
See the memory-first meta-harness guide for the adapter security matrix and complete SDK, CLI, UI, and MCP workflows.
Runtime policies¶
memorizz.tooling.governed_tool(*, deterministic=True, side_effects=False, requires_approval=None, approval_reason=None, domains=(), aliases=(), deprecated_arguments=None, cacheable=False, cache_ttl_seconds=None)
¶
Decorate a callable with explicit tool and cache governance metadata.
cacheable=True lets a MemAgent with a tool cache reuse this tool's
result for a repeated call with the same arguments, for
cache_ttl_seconds (else the cache's default). Only a deterministic tool
without side effects can be cacheable.
memorizz.tooling.ToolPolicy
dataclass
¶
Runtime governance metadata attached to a trusted callable.
memorizz.tool_cache.ToolCacheConfig
dataclass
¶
memorizz.tooling.ToolResultPolicy
dataclass
¶
memorizz.tool_outcomes.ToolOutcome
dataclass
¶
Content-free evidence about a tool result.
status drives the primary UI label. fallback_used and degraded
remain orthogonal because a fallback can itself offer reduced capability.
memorizz.tool_outcomes.ToolOutcomeStatus
¶
Bases: str, Enum
Terminal state for one tool execution.
memorizz.tool_outcomes.ToolResult
dataclass
¶
A tool payload with an explicit outcome.
MemAgent unwraps value before model serialization, preserving the
tool's established result schema.
memorizz.tooling.ContextPolicy
dataclass
¶
Bounded context and progressive-disclosure defaults for an agent.
memorizz.retrieval.RetrievalPolicy
dataclass
¶
Configure automatic semantic recall without changing storage.
The defaults preserve the pre-0.5.2 behaviour for compatibility. Safer
conversational applications can use RetrievalPolicy.disabled(),
select conversation_scope="thread" and explicit KB namespaces, or seal
each thread with RetrievalPolicy.sealed().
entity_scope decides where entity facts live: "memory" shares
them across the threads of a memory and user, "thread" keeps the
facts a thread writes, and the facts it recalls, inside that thread, and
"disabled" stops recalling them automatically (the entity tools still
work).
Methods:¶
sealed(**overrides)
classmethod
¶
Nothing a user said in one thread reaches another.
Conversation recall and entity facts stay inside the current thread, the semantic cache only answers from the same thread, and the agent's persona is read-only. The knowledge base is shared reference material and stays on.
memorizz.learning.consolidation.ConsolidationConfig
dataclass
¶
When and how a background consolidation pass runs.
every_n_turns and every_hours schedule a pass after a turn: the
first one reached wins. auto_apply applies a scheduled plan as
memorizz:consolidation; otherwise the plan waits for review.
memorizz.memagent.memory_routing.MemoryRoutingConfig
dataclass
¶
memorizz.reranking.RerankerConfig
dataclass
¶
An agent's own reranker; from_value(None) is None (follow the store).
memorizz.learning.consolidation.ConsolidationPlan
dataclass
¶
A dry run: what a consolidation pass would change, and why.
memorizz.completion.CompletionPolicy
dataclass
¶
Bounded, auditable final-response acceptance policy.
validator is deliberately runtime-only: serializing arbitrary code is
unsafe. When validator_required is persisted, a reloaded agent rejects
completion until the trusted host rebinds a validator.
Model providers¶
memorizz.llms.llm_provider.LLMProvider
¶
Bases: Protocol
A generic protocol that defines the contract for any LLM provider to be compatible with both the OpenAI and AzureOpenAI classes.
Methods:¶
generate(messages, tools=None, tool_choice='auto')
¶
Generate a response from a list of messages (chat format), optionally with tool calling.
generate_stream(messages, tools=None, tool_choice='auto')
¶
Stream a response from a list of messages (chat format), optionally with tool calling.
Yields dictionaries with one of these shapes
- {"type": "content", "content": "..."} for text chunks
- {"type": "tool_calls", "response":
} when tool calls are detected - {"type": "done", "content": "
"} at the end of the stream - {"type": "usage", "usage": {...}} for known token accounting
Content deltas concatenate exactly to done.content, including whitespace. Exactly one done or completed tool_calls event ends a successful request; an incomplete/refused request raises, it must not invent success at EOF. Reasoning is diagnostic only. Tool response objects are internal and never serialized into public SDK events. Consumers close this generator; adapters must close their raw provider stream and cooperate with the current cancellation token. See llms.streaming.streaming_capabilities for reliable detection (an inherited Protocol stub is not an iterator).
get_config()
¶
Returns a serializable dictionary of the provider's configuration. This is used for saving and reconstructing the agent.
get_last_usage()
¶
Return token usage details (prompt/completion/total) from the most recent call.
get_context_window_tokens()
¶
Return the provider's context window size in tokens, when known.
Memory providers¶
memorizz.memory_provider.base.MemoryProvider
¶
Bases: ABC
Abstract base class for memory providers.
Methods:¶
store(data=None, memory_store_type=None, memory_id=None, memory_unit=None)
abstractmethod
¶
Store data in the memory provider.
Parameters:¶
data : Dict[str, Any], optional Data dictionary to store (legacy parameter) memory_store_type : str, optional Type of memory store (legacy parameter) memory_id : str, optional Memory ID to associate with (new parameter) memory_unit : MemoryUnit, optional Memory unit object to store (new parameter)
retrieve_by_query(query, memory_store_type=None, limit=1, memory_id=None, memory_type=None, **kwargs)
abstractmethod
¶
Retrieve a document from the memory provider.
Parameters:¶
query : Dict[str, Any] or str
Search query (dict for filter queries, str for semantic search)
memory_store_type : str, optional
Type of memory store (legacy parameter name)
memory_type : str or MemoryType, optional
Type of memory store (new parameter name, takes precedence over memory_store_type)
memory_id : str, optional
Filter results to specific memory_id
limit : int
Maximum number of results to return
**kwargs
Additional provider-specific parameters. Includes user_id for
multi-tenant scoping. Omitting it is an administrative/unscoped
read, explicitly passing None selects anonymous/legacy rows,
and a string selects that exact tenant.
retrieve_by_id(id, memory_store_type)
abstractmethod
¶
Retrieve a document from the memory provider by id.
When a provider supports multi-tenant scoping via user_id it may
accept a user_id keyword argument; callers that need strict
isolation should check the returned row's user_id against their
expected scope before acting on it.
list_all(memory_store_type, user_id=_UNSET)
abstractmethod
¶
List all documents within a memory store type in the memory provider.
user_id follows the shared sentinel contract: omitting it performs
an administrative/unscoped read, explicitly passing None selects
only anonymous/legacy rows, and a string selects that exact tenant.
retrieve_conversation_history_ordered_by_timestamp(memory_id, memory_type=None, limit=None, user_id=_UNSET, thread_id=None)
abstractmethod
¶
Retrieve the conversation history ordered by timestamp.
Parameters:¶
memory_id : str
The memory ID to retrieve history for
memory_type : str or MemoryType, optional
Type of memory (typically CONVERSATION_MEMORY)
limit : int, optional
Maximum number of entries to return
user_id : str, optional (keyword)
Multi-tenant scope. Omitting it is an administrative/unscoped
read, explicitly passing None selects anonymous/legacy rows,
and a string selects that exact tenant.
thread_id : str, optional
When provided, return only rows from that exact conversation
thread. When omitted, return all threads in the memory scope.
query_observability_records(memory_store_type, *, agent_ids=None, memory_ids=None, thread_id=None, user_id=_UNSET, application_id=None, record_type=None, tool_name=None, success=None, event_filters=None, start_time=None, end_time=None, limit=250, cursor=None)
¶
Return one bounded observability page with portable metadata.
First-party database providers should override this with indexed predicates. This compatibility path intentionally remains available to third-party and filesystem providers, but it never returns an unbounded page to the caller.
invalidate_semantic_cache(*, agent_id=None, memory_id=None, domains=None, tags=None, data_version=None)
¶
Delete persistent cache entries matching governance metadata.
This provider-neutral fallback keeps domain/tag/data-version invalidation operational on filesystem, MongoDB, Oracle, and custom providers. Native providers may override it with a bulk predicate.
store_memagent(memagent)
abstractmethod
¶
Store a memagent in the memory provider.
delete_memagent(agent_id, cascade=False)
abstractmethod
¶
Delete a memagent from the memory provider.
list_memagents()
abstractmethod
¶
List all memagents in the memory provider.
close()
abstractmethod
¶
Close the connection to the memory provider.
See the custom provider contract before
implementing this interface, particularly the three-state user_id filter.
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.