Memory and Recall
Choose what agents remember, how they recall it, and when it expires.
#Memory and Recall
Memory retrieves relevant context and can save reusable skills, resources and insights for later use. It does not guarantee that every earlier message will remain in the model's context. Automatic memory is private to the customer a run acts for, so set a user_id before you expect recall. See Customer-scoped memory.
The current hosted invocation path retrieves memory before execution and can index new memory asynchronously after the response. Conversation compaction is an opt-in deployment setting and is off by default.
Requests with an optional cost cap skip background memory enrichment, including post-response indexing and extraction, until the budget ledger covers those costs. Capped requests also refuse paid hosted web search and sandbox execution. See System Tools.
#History and run limits
With compaction off, automatic thread continuity uses a bounded recent-history tail. The invocation contract allows at most 128 messages, not 128 conversation turns. The runtime reserves four message slots for server context and fills the remaining space with incoming messages and the newest stored history that fits. Older messages can fall outside that tail. A stable thread_id does not guarantee full-history replay. Retrieval may supply relevant older information when it is available, but it is not a substitute for a complete transcript.
Deployments with a configured model cascade, PostgreSQL session storage, and durable task-budget control use automatic compaction. The model keeps system instructions, the current user request, and recent complete tool exchanges. A derived summary can cover older settled exchanges. The complete original conversation remains in canonical history. Summary generation uses the ordinary model usage and billing path and counts against the request's cost cap.
Operators can set MAIVN_DATA_PLANE_CONVERSATION_COMPACTION_ENABLED=false to disable compaction. Explicit true keeps the earlier opt-in policy, which retains every user message verbatim and summarizes older assistant and tool evidence.
If that view cannot be built and the history is also too long to replay unchanged (more than 124 messages, which is the 128-message cap minus the four reserved slots), the run stops with conversation_context_unavailable instead of dropping constraints. The session result uses HTTP 409 with context.reason and context.retryable. The terminal error event carries the same reason and retry flag. Only failed (a failed or invalid summary) is retryable. no_fit means pinned constraints and recent complete exchanges cannot fit, and unsupported means the replay records cannot be compacted safely. uncontrolled, missing_model, and missing_scope are configuration or scope limits. unavailable means the scoped summary attempt could not be admitted. Local runs without project scope may receive missing_scope for long conversations, while hosted requests have project scope. Full stored history and observed usage remain available after refusal. Keep essential facts explicit, or start a new thread with an application-provided summary that preserves the constraints you need.
Message count and model context size are separate limits. A small number of long messages can still exceed the selected model's token limit. Keep essential instructions and current facts explicit, split large tasks into bounded runs, and save results your application needs to retain.
The extended hosted-job profile supports a total duration up to two hours with a durable idle deadline. Account and deployment policy, provider limits, and client timeouts also apply. See Hosted jobs and Timeouts, Retries & Reliability before retrying work after a disconnection. A timeout does not prove that remote work stopped.
#Thread recall and scope-shared assets
Memory is intentionally split into two layers:
- Conversation recall: the recent-history tail belongs to the current
thread_id. Facts recalled from earlier conversations (vector hits, keyword hits and graph neighbors) are scoped by owner, project, agent and swarm, not by thread, so they cross threads for the same user. - Scope-shared assets: skills, bound resources, and promoted insights are reusable across future threads within their sharing scope (
agent,swarm,project, ororg).
This means future threads already benefit from scoped skills and resources, and from what the same user said in other threads. Use a different user_id for each customer (see Customer-scoped memory) to keep their memory apart. AI-generated insights are narrower by default: auto extraction only supports agent or swarm, and broader reuse happens through portal promotion to project or org.
Every run saves memory back after it answers, unless you turn persistence off with MemoryConfig(persistence_mode='persist_none') (recall still works) or turn memory off with MemoryConfig(enabled=False) or level='none'. A run that saves memory can also create AI-generated (learned) skills; see Skills.
#Delete everything about one user
client.memory.delete_user(user_id) (async: adelete_user) permanently deletes everything the platform remembers about one end user in your project: their insights, conversational facts (graph assertions), skills learned from their runs and post-run extraction receipts. Other users' memory and shared records are not touched. Uploaded resources are kept; delete those with client.resources.
erased = client.memory.delete_user("dana-4821")
print(erased.insights_deleted, erased.graph_assertions_deleted)It returns MemoryUserDeleteResponse with user_id, insights_deleted, graph_assertions_deleted, skills_deleted and enrichment_receipts_deleted (DELETE /v1/memory/users/{user_id}). The deletion cannot be undone. The platform keeps an audit record of who asked (the API key), when, the user ID and the counts, never the content.
- Your project API key may delete any user in its project. A client bound with
client.memory.for_user(user_id)may delete only that same user (HTTP 403memory_erase_forbiddenotherwise). - The default
'sdk-user'owns no memory and cannot be deleted (HTTP 422invalid_memory_user). - A legal hold on your team refuses the deletion with HTTP 409
deletion_unavailable. Retrying will not change that, so contact support.
To delete single insights instead, use client.memory.insights.delete(memory_id) (DELETE /v1/memory/insights/{memory_id}), or client.memory.for_user(user_id).insights for a customer's records.
#Memory levels
MemoryConfig.level controls recall context size. It does not by itself select retrieval-only or vector-only persistence:
focus and clarity are available on plans that include deeper memory levels. On other plans, a run that asks for them uses glimpse, and the run's memory details report the level that was used.
Use persistence_mode="persist_none" for retrieval without new persistence, "vector_only" to exclude graph extraction, or "vector_plus_graph" to permit it. When you pass a MemoryConfig, omitted fields default to enabled, clarity and vector_plus_graph. The runtime and tenant policy can further restrict behavior. Explicit bound-resource access for a schema-bearing request has separate handling. See Structured Output.
#Customer-scoped memory
Automatic memory and run attachments are private to the exact user_id a run acts for, within your project. Take the ID from your trusted backend's authenticated customer session. The platform authenticates your API key, but it does not verify the end user, so never trust an ID sent by a browser.
- An ID is opaque and case-sensitive, at most 256 characters, with no control characters and no surrounding whitespace.
- The default
user_id('sdk-user') and a blank one own no private memory. Private recall, extraction and attachment persistence are off for those runs. Generation, the current prompt's attachments and explicitly shared authored knowledge still work, and the SDK emits aUserWarningwhen memory is enabled with the default. - Set the ID per call with
RunOptions(user_id=...). A backend that acts for one customer can set it once withClient(default_user_id=...)or theMAIVN_DEFAULT_USER_IDenvironment variable. An explicit per-calluser_idalways wins. - Manage a customer's records with
client.memory.for_user(user_id),client.skills.for_user(user_id)andclient.resources.for_user(user_id). Creating a record without eitherscope.shared=Trueor afor_userfacade fails with HTTP 422memory_classification_required.
#Team memory policy
An organization (a team, in the Portal) can set a memory policy in its settings. The platform enforces it on every run for that team, whatever your MemoryConfig asks for. See Portal Memory Management for the controls.
- Memory switch off. Runs stop recalling and storing memory.
- Persistence ceiling. Your
persistence_modeis lowered to the ceiling and never raised:nonestores nothing,vector_onlystores no graph assertions, andvector_plus_graphallows both. - Retention windows. Recall never returns a vector record or graph assertion past its window, and an hourly cleanup deletes expired records. A legal hold stops that deletion.
- No policy saved. The Portal shows Not configured, the policy API returns
configured: false, and runs use their own memory settings.
A run still starts when the policy blocks storage. It just stores less, so a missing memory_indexed event can come from the policy rather than from your config.
Explicit writes are checked too. Creating a skill or insight, promoting an insight and uploading a resource are refused with HTTP 403 memory_persistence_disabled when the switch is off or the ceiling is No storage. HTTP 503 memory_policy_unavailable means the platform could not read the policy, and the write was not stored; retry it. See Errors and exceptions.
#Quick start
Use a stable thread_id, a customer user_id and scope defaults:
from maivn import (
Agent,
MemoryConfig,
MemoryInsightExtractionConfig,
MemoryRetrievalConfig,
MemorySkillExtractionConfig,
RunOptions,
)
from maivn.messages import HumanMessage
agent = Agent(
name="memory_demo",
system_prompt="Use prior context when relevant.",
api_key="your-api-key",
memory_config=MemoryConfig(
enabled=True,
level="clarity", # none | glimpse | focus | clarity
persistence_mode="vector_plus_graph",
retrieval=MemoryRetrievalConfig(
top_k=4,
skills_enabled=True,
insights_enabled=True,
resources_enabled=True,
),
skill_extraction=MemorySkillExtractionConfig(
enabled=True,
),
insight_extraction=MemoryInsightExtractionConfig(
enabled=True,
),
),
)
thread_id = "customer-success-q1"
options = RunOptions(user_id="customer-123") # from your authenticated session
agent.invoke(
messages=[HumanMessage(content="Store this rollout plan and owners.")],
thread_id=thread_id,
options=options,
)
result = agent.invoke(
messages=[HumanMessage(content="Who owns the rollout milestones?")],
thread_id=thread_id,
options=options,
)#Scope memory assets
Agent and Swarm can define memory assets directly:
skills: reusable skills (see Skills)resources: bound resource payloads (inline content, file, URL or document reference)
Constructor skills declarations are only stored locally in this SDK. Constructor resources are uploaded before the first invocation. Set binding_type to bind them to the scope.
agent = Agent(
name="deploy_agent",
api_key="your-api-key",
memory_config=MemoryConfig(
level="clarity",
),
resources=[
{
"name": "deploy-runbook.txt",
"mime_type": "text/plain",
"text_content": "Rollback immediately if canary validation fails.",
"binding_type": "agent",
"sharing_scope": "agent",
"tags": ["deploy", "rollback"],
}
],
)Swarm has no memory_config constructor argument. Pass memory_config= on each Swarm.invoke call instead.
#Bound resource versioning
Scope resource declarations are uploaded once per scope instance. Content hashes support server-side deduplication, but the upload still sends the bytes. Changing a file after registration does not make that same scope upload again.
For an explicit replacement version, use client.resources.upload with ResourceUploadOptions(resource_id=existing_id). The constructor path does not forward resource_id as a replacement request. See SDK Resource Configuration.
#Skills
A skill is a named, ordered procedure the agent can follow: a description plus one to eight steps. Agent and Swarm register skills through the API and reuse them on later runs.
add_skill and add_skill_set make network calls when you call them, not when the agent next runs. They author shared knowledge for that agent or swarm, so they reject a Skill that is private (scope.owner_user_id set) or AI-generated. Create a new authored skill with your own content instead.
from maivn import Skill, SkillStep
agent.add_skill(
name="deploy_with_health_checks",
description="Deploy, run health checks, then cut over traffic.",
steps=["Deploy the service.", "Check service health before switching traffic."],
)
# The same skill with full control over each step:
agent.add_skill(Skill(
name="rollback_release",
description="Roll back a bad release.",
steps=(
SkillStep(index=1, action="Freeze new deploys."),
SkillStep(index=2, action="Roll back to the last healthy release."),
),
))
agent.use_skills("release and rollback procedures", limit=5)A Skill needs a name (up to 160 characters), a description (up to 4,000) and 1 to 8 steps. A SkillStep has a one-based index, an action (up to 240 characters) and optional tool, parameters and expected_output.
#Skill sets and markdown
A SkillSet groups skills and nested sets. parse_skill_markdown(path) reads a markdown file or a directory into a Skill or SkillSet, and add_skill_set accepts the same path directly. A file starts with frontmatter. kind is skill or set, skill is the name, and description is required. A set lists children as relative paths. A skill lists its steps as a numbered list under a ## Steps heading:
---
kind: skill
skill: rollback-release
description: Roll back a bad release safely.
---
Use when a canary fails.
## Steps
1. Freeze new deploys.
2. Roll back to the last healthy release.
3. Confirm health checks pass.A directory is a set when it holds SET.md or _set.md with kind: set. Other .md files in the directory join the set as children.
from maivn import parse_skill_markdown
tree = parse_skill_markdown("skills/incident-response") # SkillSet
agent.add_skill_set("skills/incident-response") # parse and register in one callThe parser raises SkillFrontmatterError for bad frontmatter, SkillChildNotFoundError for a missing child path and SkillCycleError for a cycle. All three subclass SkillMarkdownError, which is a ValueError. add_skill_set raises ValueError if the path resolves to a single skill.
#Skill scope
SkillScopeRequest says where a skill lives: project_id, organization_id, agent_id, swarm_id, sharing_scope (agent, swarm, project or org, default project) and shared (default False). Set it on Skill.scope or SkillSet.scope. add_skill and add_skill_set replace the scope with the agent's or swarm's own (sharing_scope='agent' or 'swarm', shared=True). RunOptions(attached_skill_ids=..., auto_skills=True) injects skills for one call.
#Memory records
client.memory reads and manages stored records. The SDK exports the models it uses. SDK Resource Configuration covers the client methods.
client.skills (with Skill) and client.memory.skills (with MemorySkillCreate) are separate clients with separate request models. Agent.add_skill is the usual way to author a skill for an agent. Delete an authored skill with client.skills.delete(skill.memory_id), which returns SkillDeleteResponse. client.memory.skills.delete accepts only IDs from memory.skills.create or memory.skills.list: the learned-skill store, which also holds the AI-generated skills that runs create when they save memory. See Manage skills and memory.
#Message attachments
HumanMessage and RedactedMessage support attachments. Attachment payloads are normalized and sent as document candidates for registration.
from maivn.messages import HumanMessage
message = HumanMessage(
content="Use the attached runbook for this request.",
attachments=[
{
"name": "runbook.txt",
"mime_type": "text/plain",
"text_content": "Escalate if error rate exceeds 2%.",
}
],
)An attachment dictionary needs name (or filename) and one payload key: content_base64 (or inline_base64), content_bytes or text_content. A prepared attachment can instead carry storage_ref, size_bytes and content_hash. Other keys such as sharing_scope and tags are ignored, and file is not supported: a dictionary with none of the payload keys is rejected. To store a file with a scope, bind a resource on the scope or use client.resources.upload.
#Per-invocation overrides
Override scope defaults per call with memory_config:
from maivn import MemoryConfig, MemoryRetrievalConfig
result = agent.invoke(
messages=[HumanMessage(content="Use retrieval only for this turn.")],
thread_id=thread_id,
memory_config=MemoryConfig(
level="glimpse",
retrieval=MemoryRetrievalConfig(
skills_enabled=True,
insights_enabled=True,
resources_enabled=True,
skill_injection_max_count=3,
insight_injection_max_count=2,
resource_injection_max_count=2,
),
),
)#Observe memory and resource events
Use event streaming to inspect enrichment phases:
events = []
def on_event(event: dict) -> None:
if event.get("event") != "enrichment":
return
payload = event.get("payload") or {}
phase = payload.get("phase")
if isinstance(phase, str) and (
phase.startswith("memory_") or phase.startswith("document_")
):
events.append(
{
"phase": phase,
"message": payload.get("message"),
"memory": payload.get("memory"),
}
)
agent.events(include="enrichment", on_event=on_event).invoke(
messages=[HumanMessage(content="Recall the project constraints.")],
thread_id=thread_id,
)Common memory phases:
memory_retrievingmemory_retrievedmemory_indexingmemory_graph_extractingmemory_indexedmemory_skill_extractingmemory_insight_extracting
Common resource phases:
resource_registeringresource_registeredresource_dedup_reusedresource_version_supersededresource_extractingresource_extracted
payload.memory can include hit counts, per-signal counts (skill_hits, insight_hits, resource_hits), latency, and effective memory level.
On the memory_retrieved event, payload.memory.requested_level is the level the run asked for and payload.memory.level is the level the run used. level_cap_reason appears only when the level was lowered: its value is plan when your plan does not include deeper memory levels, or plan_unavailable when the plan could not be read.
A memory configuration with no level asks for clarity by default, so on a plan without deeper memory levels the event shows a requested level of clarity and a used level of glimpse.
#Async post-finalize behavior
Memory extraction can finish after the response stream closes. An extraction-start event or a non-zero retrieval count does not prove that the latest invocation's assets were saved.
Use client.memory.enrichments.list(session_id) or its async alist counterpart to read persisted outcomes. Each MemoryEnrichmentReceipt has session_id, invocation_id, owner_user_id, status (completed or failed), skill_count, insight_count, graph_edge_count and created_at. Completed can legitimately mean zero assets. An empty receipt list does not imply completion. If you poll, use a bounded retry policy and keep a pending state when no receipt arrives.
#Configuration reference
SDK controls are enabled, level, persistence_mode, the retrieval signal toggles (skills_enabled, insights_enabled, resources_enabled, graph_enabled) and injection counts, retrieval.insight_relevance_floor, and extraction enabled and max_count. Graph controls are retrieval.graph_enabled, retrieval.graph_injection_max_count (1 to 16) and graph_extraction (enabled, max_count up to 16). When you omit them, each injection count falls back to retrieval.top_k, then to 3, and skill and insight extraction default to 2 per run.
Nested per-call configuration replaces the corresponding nested scope configuration rather than merging each nested field.
#Recall similarity floor
retrieval.insight_relevance_floor (0.0 to 1.0) sets a similarity floor over recalled memory. Recalled skills, insights and resources that are not bound to the scope must score at or above it to be injected. A floor you set also applies to keyword recall, so a fact the similarity floor dropped is not added back by a keyword match. Resources you bind explicitly stay available whatever the floor. When you leave it unset, the SDK sends nothing and the platform default of 0.6 applies. This differs slightly from v1, where the value was a relevance score on each insight.
MemoryConfig(
level='clarity',
retrieval=MemoryRetrievalConfig(insight_relevance_floor=0.7),
)The option requires a platform release that supports it. Against an older platform, setting it makes the request fail with a validation error, and leaving it unset works everywhere.
See Session Config Models for exact fields and request behavior.