Skip to main content

xmemory

Python client library for the xmemory API.

Quick start

from xmemory import XmemoryClient, SchemaType

client = XmemoryClient(api_key="xmem_...")  # or set XMEM_API_KEY env var

# Create an instance and start using it immediately
schema = """\
objects:
  person:
    fields:
      name:
        type: str
        required: true
        description: full name of the person
      role:
        type: str
        required: false
        description: job title or role
      location:
        type: str
        required: false
        description: city or location
relations: {}
"""

inst = client.admin.create_instance(
    cluster_id="<your-cluster-id>",
    name="my-memory",
    schema_text=schema,
    schema_type=SchemaType.YML,
)

inst.write("Alice is a software engineer based in Berlin.")
result = inst.read("What does Alice do?")
print(result.reader_result)

Bind to an existing instance

inst = client.instance("<your-instance-id>")
inst.write("Bob joined the team as a designer.")
result = inst.read("Who is on the team?")

Async quick start

import asyncio
from xmemory import AsyncXmemoryClient, SchemaType

async def main():
    async with AsyncXmemoryClient(api_key="xmem_...") as client:
        inst = await client.admin.create_instance(
            cluster_id="<cluster-id>",
            name="my-memory",
            schema_text=schema,  # same schema as above
            schema_type=SchemaType.YML,
        )
        await inst.write("Alice is a software engineer based in Berlin.")
        result = await inst.read("What does Alice do?")
        print(result.reader_result)

asyncio.run(main())

Configuration

Parameter Env var Default Description
url XMEM_API_URL https://api.xmemory.ai Base URL of the xmemory API
api_key XMEM_API_KEY None API key for authentication
timeout — 60 Default request timeout in seconds

Deprecation: The legacy term token (argument token= and env var XMEM_AUTH_TOKEN) is still accepted for backwards compatibility but prints an orange-colored deprecation notice on use. Migrate to api_key / XMEM_API_KEY. The legacy names will be removed in a future release.

Client structure

The client is organized into two namespaces:

  • client.admin — cluster management, instance lifecycle, schema and metadata management
  • client.instance(id) — instance-bound data operations (read, write, extract)

Admin API (client.admin)

# Clusters
clusters = client.admin.list_clusters()
cluster = client.admin.get_cluster("<cluster-id>")

# Instance lifecycle
inst = client.admin.create_instance(cluster_id, "name", schema, SchemaType.YML)
instances = client.admin.list_instances()
info = client.admin.get_instance("<instance-id>")
client.admin.delete_instance("<instance-id>")

# Schema management
schema = client.admin.get_instance_schema("<instance-id>")
client.admin.update_instance_schema("<instance-id>", new_schema, SchemaType.YML)

# Metadata management
client.admin.update_instance_metadata("<instance-id>", "new-name", "new description")

# Change one field and leave the rest alone
client.admin.patch_instance_metadata("<instance-id>", description="a new description")

# Schema generation
result = client.admin.generate_schema(cluster_id, "People with name, role, and location.")
print(result.data_schema)

create_instance returns an InstanceAPI bound to the new instance, ready for data operations.

list_instances and get_instance return InstanceInfo metadata objects.

Agent-facing instance metadata

An instance can carry metadata that shapes how agents connect to it and what they do with it. patch_instance_metadata is the way to set the advisory hints: every argument is independent, omitting one leaves the stored value untouched, and passing None clears it.

from xmemory import AgentSurface, BindingTier

client.admin.patch_instance_metadata(
    "<instance-id>",
    # Advisory hints — they seed what a connect flow proposes, and grant nothing.
    agent_surfaces=[AgentSurface.CLAUDE_CODE, AgentSurface.CODEX],
    agent_default_binding_tier=BindingTier.AUTOLOAD,
    agent_engagement_hints=["a convention is learned or corrected"],
)

Concurrent edits to these three are last-writer-wins by design: they only seed what a connect flow proposes, so the loser of a race re-applies a suggestion. agent_owner_instructions is not like that — see below.

Reading it back:

info = client.admin.get_instance("<instance-id>")
info.agent_owner_instructions
info.agent_surfaces                    # e.g. ["claude_code", "codex"]
info.agent_default_binding_tier        # e.g. "autoload"
info.agent_engagement_hints

These read as plain strings rather than enums, so a value your server knows and this release does not is returned rather than rejected.

Setting the standing instructions. Use update_instance_metadata for agent_owner_instructions, not patch_instance_metadata. The field is rendered to agents verbatim, and a second writer edits it from the same screen, so a silently lost edit is a rule that stops being enforced. Only update_instance_metadata carries expected_owner_instructions_epoch: pass the epoch you read the value at and the server refuses the losing save instead of applying it.

patch_instance_metadata also accepts the field — it is the only way to set it without restating the name — but it can carry no guard, so an edit composed from stale data overwrites a newer one silently. Reach for it only when you are seeding a value nobody else is editing.

info = client.admin.get_instance("<instance-id>")
client.admin.update_instance_metadata(
    "<instance-id>", info.name, info.description,
    agent_owner_instructions=(info.agent_owner_instructions or "") + "\nAlso: never paraphrase a rule.",
    expected_owner_instructions_epoch=info.agent_owner_instructions_epoch,
)

Instance API (client.instance(id))

inst = client.instance("<instance-id>")

# Read
result = inst.read("Who is on the team?")
print(result.reader_result)
print(result.console_url)  # this read's trace in the console; None if none is configured

# Write (synchronous)
result = inst.write("Bob joined the team on Monday as a designer.")
print(result.changes)     # what the write created / updated / deleted
print(result.console_url)  # the same link for the write

# Write (async job)
job = inst.write_async("Bob joined the team on Monday as a designer.")
status = inst.write_status(job.write_id)
print(status.changes)     # the same summary, once the write completes

# Structured write: deterministic, LLM-free create/update/delete mutations
# (mutually exclusive with text; applied in list order)
from xmemory import ObjectCreate, ObjectMutation

result = inst.write(structured_mutations=[
    ObjectMutation(
        object_type="person",
        create=ObjectCreate(key={"name": "Bob"}, values={"role": "designer"}),
    ),
    # Plain dicts in the API wire form work too:
    {"object_mutation": {"object_type": "person", "update": {"key": {"name": "Bob"}, "values": {"role": None}}}},  # None clears
])

# A relation's own fields (see "Fields on a relation") go in its values. An update
# names one link by every endpoint, in a later write than the one that created it:
# a request that creates a link cannot also change it.
from xmemory import RelationCreate, RelationEndpoint, RelationMutation, RelationUpdate

bob_at_acme = [
    RelationEndpoint(object_name="person", key={"name": "Bob"}),
    RelationEndpoint(object_name="company", key={"name": "Acme"}),
]
inst.write(structured_mutations=[
    ObjectMutation(object_type="company", create=ObjectCreate(key={"name": "Acme"})),
    RelationMutation(relation_type="employment", create=RelationCreate(endpoints=bob_at_acme, values={"title": "designer"})),
])
inst.write(structured_mutations=[
    RelationMutation(relation_type="employment", update=RelationUpdate(endpoints=bob_at_acme, values={"title": "lead designer"})),
])

# Extract (without persisting)
result = inst.extract("Carol is a manager based in Berlin.")
print(result.objects_extracted)

# Describe: agent-facing tool docs, plus what this memory is for
described = inst.describe()
print(described.as_text())      # ready to inject into a system prompt
described.purpose               # what the memory is for (the instance description)
described.owner_instructions    # the standing preference set for it, verbatim
described.usage_brief           # generated from the schema; None until generated

as_text() includes purpose and owner_instructions when the instance has them. usage_brief is left out of it — it restates the schema summary that is already there — so read the attribute if you want it.

Both fields are free text set by anyone holding edit permission on the instance, so as_text() labels each with where it came from rather than presenting it as the library's own words. Those labels state provenance; they are not a security boundary. If you inject this into a system prompt you are still handling text you do not control.

Write ordering

Every write to an instance goes into one queue for that instance: write and write_async, text and structured_mutations alike. Queued writes are processed in parallel, but applied to the instance one at a time, in the order they were queued (FIFO). A write is never applied ahead of an older one, even when its own processing finished first.

  • write_async returns once the write is queued. write_status reports QUEUED until processing starts, and EXTRACTED while a processed write waits for older writes to be applied.
  • write waits in the same queue and returns once its own write is applied. It does not jump ahead of async writes queued before it.
  • The order is the order the server receives the writes. Two writes sent at the same time (from two threads, or asyncio.gather) have no defined order between them, so when one must apply after another, wait for the first call to return (write_async returning its write_id is enough) before sending the second.
  • Reads are not queued: a read sees only writes that have completed.
inst.write_async("Bob joined the team as a designer.")
inst.write_async("Bob moved to the London office.")
# Applied after both writes above, in order.
inst.write(structured_mutations=[
    {"object_mutation": {"object_type": "person", "update": {"key": {"name": "Bob"}, "values": {"role": "lead designer"}}}},
])

Read modes

from xmemory import ReadMode

result = inst.read("Show people and companies", read_mode=ReadMode.XRESPONSE)

What comes back

In single-answer mode reader_result is always the prose answer. In raw-tables and xresponse mode its value says which of five answers the read gave:

reader_result Meaning What to do
rows Answered. Use them.
exactly {"columns": [], "rows": []} / {"objects": [], "relations": []}, notice is None The query executed and matched nothing — every table and column it used exists, so the data is absent. Trust the empty result.
the same empty value, notice set The server could not run a query that answers the question as asked, so the empty value says nothing about what is stored. Rephrase the question, for example by naming the exact value to look up. Do not treat the data as absent.
None The schema provably cannot represent the concept. An answer, not a variant of the empty one. Try a better-matching instance; this memory cannot hold it.
(raises) Every sub-query's SQL failed, so nothing was answered. Catch XmemoryAPIError with .status 422 and .code INVALID_INPUT. It is the same answer for the same input, so do not retry it.
result = inst.read("Which invoices are overdue?", read_mode=ReadMode.RAW_TABLES)
if result.reader_result is None:
    ...  # not a concept this memory holds — try another instance
elif result.notice is not None:
    ...  # not answered as asked — rephrase; the data may well be stored
elif not result.reader_result["rows"]:
    ...  # the data is absent; the read did not fail

Composite queries

When a query bundles several independent questions, the server may decompose it into sub-queries and answer each one. reader_result is still the combined answer (for single-answer mode, a labelled multi-part string); reader_results holds one TaggedReaderResult (sub_query, reader_result, error, notice) per sub-query so you can read each answer unambiguously. A single-intent query yields one entry, and the list is empty against a server without question decomposition.

result = inst.read("Who leads sales, and where is HQ?")
for part in result.reader_results:
    print(part.sub_query, "->", part.error or part.reader_result)

Each part's reader_result uses the same five answers as above, with one more case: a sub-query whose SQL failed carries the empty result and a user-safe error, while the others are answered regardless. Its bytes then equal those of a sub-query that matched nothing, so read error before reader_result, as the loop above does. The combined reader_result folds the parts: rows if any sub-query answered; else the empty result if any executed and matched nothing, or could not be answered as asked; else None. The top-level notice is set when any part could not be answered as asked, even if another part answered, so check it before trusting an empty part. In the tabular modes a read where every sub-query failed raises the 422 above instead.

Scoped reads

By default a read may draw on any object in the instance. Pass a scope to restrict it to a specific set of concrete objects — each named by its type plus its user-defined primary key:

from xmemory import ReadScope, ScopeObject

result = inst.read(
    "What do these people do?",
    scope=ReadScope(
        objects=[
            ScopeObject(type="Person", key={"name": "Alice"}),
            ScopeObject(type="Person", key={"name": "Bob"}),
        ],
    ),
)

Only the listed objects are in scope. To also expose the relations among them, set relations_scope="all_relations" (the default is "no_relations"):

result = inst.read(
    "How are these people connected?",
    scope=ReadScope(
        objects=[
            ScopeObject(type="Person", key={"name": "Alice"}),
            ScopeObject(type="Company", key={"name": "Acme"}),
        ],
        relations_scope="all_relations",
    ),
)

Each ScopeObject names one object by its type plus its user-defined primary key, using the same field name(s) as your schema, with one entry per primary-key field. Only objects of a type that has a user-defined primary key can be scoped. Scoped reads compose with read_mode.

A read can also say what else the memory could answer about. Pass include_related_types=RelatedTypesMode.TYPES and related_types on the result names the object types the read touched, each with the fields it did not return and the object types a declared relation links it to (the relation, both roles, and its cardinality seen from the touched type), plus a catalog that describes every named type (description, primary key, field names) and relation once. It is derived from the instance schema and the statements the read executed — no extra rows, no model call — so an agent can ask a deliberate follow-up instead of guessing what the store holds.

from xmemory import RelatedTypesMode

result = inst.read(
    "Which courses require an English test?",
    include_related_types=RelatedTypesMode.TYPES,
)
for touched in result.related_types.touched:
    print(touched.object_type, "did not return", touched.fields_not_returned)
    for link in touched.related:
        neighbour = result.related_types.objects[link.object_type]
        print("  linked to", link.object_type, "via", link.relation, neighbour.fields)

related_types is None unless the read asked for it. A requested read that executed nothing arrives with touched == []. The server caps the payload; truncated says when it did, and omitted_touched and each entry's omitted_related count what was dropped.

To follow the relations further, add related_types_depth=2 (up to 3). Every entry under related_types.objects then carries its distance from the touched types (0 for a touched type) and, between the touched types and the last level, its own related edges, so the walk can be continued from the catalog:

result = inst.read(
    "Which courses require an English test?",
    include_related_types=RelatedTypesMode.TYPES,
    related_types_depth=2,
)
for name, entry in result.related_types.objects.items():
    print(name, "at distance", entry.distance)
    for link in entry.related:
        print("  linked to", link.object_type, "via", link.relation)

related_types.depth echoes the depth asked for. distance counts listed edges from the nearest touched type, and omitted_objects counts the types within that many relation levels that the server's budgets kept out of the catalog; truncated says something was cut. Left unset, nothing is sent and the server serves one level in the shape it always had: depth, omitted_objects and the catalog entries' distance, related and omitted_related are then absent and read as their defaults (distance is None). A value outside 1 to 3 is a 422 whose code is VALIDATION_ERROR. Asking for related types needs the instance.get permission on the API key, the same one the schema endpoints need, on top of data.read: a key without it gets a 403 whose message names the permission, and the plain read is unaffected.

Scoped writes

A write is normally free to touch anything in the instance: the extractor sees the text alone, and whatever it produces is reconciled against the whole instance. Pass a scope to anchor a text write to a set of concrete existing objects instead:

from xmemory import ScopeObject, WriteScope

result = inst.write(
    "After her promotion she is a surgeon, and her desk phone is +1-555-0100.",
    scope=WriteScope(
        objects=[ScopeObject(type="Person", key={"name": "Alice Johnson"})],
    ),
)

The write is confined to the scope: it may only modify or delete the scoped objects, and create new objects and relations anchored to them. That confinement is checked against the resulting plan, so it holds regardless of what the extractor produced. Extraction itself is unchanged by a scope — it runs on the text alone, so the text still names the objects it means.

What a change outside the confinement costs is the scope's mode. The default, "reject", fails the whole write with a validation error rather than applying partially. Pass mode="drop" and such a change — and any change that depended on one — is skipped and reported instead, while the rest of the write applies:

result = inst.write(
    "Alice Johnson is now a surgeon, and Bob Lee moved to Seattle.",
    scope=WriteScope(
        objects=[ScopeObject(type="Person", key={"name": "Alice Johnson"})],
        mode="drop",
    ),
)
for skipped in result.changes.get("skipped_out_of_scope", []):
    print(skipped["operation"], skipped["object_type_name"], skipped["fields"], skipped["count"])

A drop-mode write applies the plan it would have run unscoped minus those changes; it never adds one or re-targets one at a scoped record. Each entry in skipped_out_of_scope carries the operation (create, update, delete, merge, link or unlink), the object_type_name, the fields the skipped changes would have written and a count of the records it stands for. identity names the record (field='value') only when the scope itself named it, and is empty otherwise, so the report says that matching records exist without naming records the caller had not already asked about. The key is omitted entirely when nothing was skipped.

The report holds at most 100 entries. Past that, entries are kept as they are while there is room, those that name a record first, and the rest arrive folded: one entry per operation and object_type_name, marked "folded": True, with an empty identity, no fields and the summed count. When even those would be more than 100, none is kept as it was, and the last folded entries are folded once more, into one entry per operation whose object_type_name is empty too. Unnamed entries are folded before named ones, but a record the scope named can still end up inside a folded entry. Summing count per operation still gives the true totals, and only a folded entry has the folded key, so read it with skipped.get("folded", False).

Drop mode also changes what a scope entry means for creates. It creates only records whose primary key the scope names — and such a record need not be stored yet, where a reject-mode scope requires every scoped record to exist. That is what makes "create or update exactly this record, and nothing else" one call. A type declared without a primary key has nothing to name its records by, so drop mode never creates one.

WriteScope takes the same ScopeObjects as ReadScope, identified the same way. Unlike ReadScope there is no relations_scope: the relations among the scoped objects always accompany the extraction hint.

Things to know before reaching for it:

  • Scope applies to text writes only — combining it with structured_mutations raises a ValueError, since those bypass extraction entirely and there is nothing for a scope to anchor.
  • Only objects of a type with a user-defined primary key can be scoped. A scope names records by that key, so a type declared primary_key: [] has nothing to name its records by.
  • The server caps the number of scoped objects per write, and can have scoped writes disabled entirely. Both are server-side rules, so they surface as an XmemoryAPIError.
  • A scoped write additionally requires read permission on the instance: the response carries the previous value of every field the write changed, resolving a scope answers whether each named object is stored, and a drop-mode report says what the skipped changes would have written. An API key with write access alone is refused.
  • A server that predates mode never sees the key: it is sent only when it is not "reject", so an unscoped or reject-mode write is byte-identical to what this client sent before the option existed.
  • write_async accepts the same scope. Under "reject" a scope violation surfaces through write_status as a failed write; under "drop" the write completes and write_status().changes carries what it skipped.

What a delete reports

Deleting a record never deletes the records linked to it. The relation's on_delete removes or clears each link, and the write lists those links under changes["deleted"]["relations"]; a link the same write also states may be reported under relationship_outcomes as well, or instead. A record whose last link of a relation was the deleted one is listed in changes["orphaned_records"], so you can decide whether it still belongs. relation is the relation's class name: an XMD relation works_at comes back as WorksAt:

result = inst.write("Remove the Harbour Wall project.")
for r in (result.changes or {}).get("orphaned_records", []):
    who = f'{r["count"]} more' if r.get("folded") else r["identity"]
    print(r["object_type_name"], who, "has no", r["relation"], "link left")

The key is omitted when there is no such record and by a server that predates the report, so a missing key means none reported, and changes is None on a response from an older server. A record the write deleted, or that still has a link of that relation when the write completes, is not listed. identity names the record as the write's other entries do: by the write's own identifier when the write names it, otherwise by its key rendered field='value', a composite one comma-separated, or empty when it has none or part of it is unknown. Past 100 entries of one type and relation, the rest arrive as one entry marked "folded": True, with an empty identity and their count. Only a folded entry has the folded and count keys, so read folded with .get. deleted["relations"] folds a delete's links past 100 of one relation into one entry with that relation's name, empty endpoints and fields, "folded": True and their count.

Extraction logic

from xmemory import ExtractionLogic

result = inst.write("...", extraction_logic=ExtractionLogic.FAST)

Schema format

Schemas use the XMD (Xmemory Data Model) format with objects and relations:

objects:
  person:
    fields:
      name:
        type: str
        required: true
        description: full name of the person
      role:
        type: str
        required: false
        description: job title or role
    primary_key: [name]
  company:
    fields:
      name:
        type: str
        required: true
        description: company name
      industry:
        type: str
        required: false
        description: industry or sector
    primary_key: [name]
relations:
  employment:
    objects:
      person:
        type: person
        on_delete: cascade
      company:
        type: company
        on_delete: cascade
    description: person works at company

Field types: str, int, float and bool; string, integer and boolean are accepted as aliases. There is no date type: store dates and times in a str field, and say in its description how they are written.

Fields on a relation

A relation can declare fields of its own: values that belong to one link rather than to either record, such as a person's title at a company. Only structured writes set them; a text write does not, so a value that will arrive in text is best kept on an object. They are shaped like an object's fields:

relations:
  employment:
    objects:
      person:
        type: person
        on_delete: cascade
      company:
        type: company
        on_delete: cascade
    keys:
      one_link_per_pair: [person, company]
    fields:
      title:
        type: str
        description: the person's job title at this company
      started_on:
        type: str
        description: the day the person started at this company, as YYYY-MM-DD
    description: person works at company
  • A relation's field is never required, since a link is made before its values are known. It takes no merge, and it cannot share a name with one of the relation's roles or with a name the server reserves. A schema that breaks this is refused: an XmemoryAPIError with status 422, code INVALID_INPUT and details["error_code"] == "xmd_relation_field_invalid".
  • A relation's fields are declared when the relation is added, in the schema; a migration plan's AddRelation carries the same fields. On a relation that already exists, a schema update that adds or removes a field, or changes its type, enum or default, is refused; its description can change.
  • A relation create takes their values in values, and an update names one link by every endpoint and sets them (see the structured write example above). A key over the relation's roles, as above, keeps the same two records to one link, so an update by their endpoints never finds more than one.

Mergeable text fields

By default a write replaces a field's stored value. A str field that is not part of the primary key can instead declare a merge, so a later text write merges its value into the text already stored. A server from before field merges keeps the block but ignores it, and replaces the value as before:

objects:
  project:
    fields:
      name:
        type: str
        required: true
      next_steps:
        type: str
        description: what is still to be done on the project, one step per line
        merge:
          rules:
            - Keep every step that is still open.
            - Drop a step the text says is done.
          max_length: 400
    primary_key: [name]
  • max_length is required, a whole number from 1 to 20,000: the length the merge keeps the text within. rules is optional: up to 50 non-empty lines of at most 1,000 characters each. merge takes no other key, and a schema that breaks any of this is refused.
  • With rules, the server merges the new value into the stored one by those rules, within the cap.
  • Without rules, the new value is appended on its own line, leaving out lines whose facts are already stated; past the cap, the text is shortened, keeping every fact.
  • If a merge cannot be made, the new value is appended, even past the cap, and nothing stored is cut.
  • Only text writes merge, through the server's diff engine. structured_mutations replace the value as given.
  • Adding, changing or removing a merge is a metadata-only schema change.

Where a merge that changed the field found the new value contradicting the stored one, the write's result says what each said and which one it kept:

result = inst.write("The Harbour Wall survey moved to 10 March.")
for c in (result.changes or {}).get("merge_contradictions", []):
    print(c["object_type_name"], c["identity"], c["field"], c["stored"], "->", c["new"], "kept:", c["kept"])

The key is omitted when there is no such entry, and changes is None on a response from an older server. An absent key does not prove the texts agreed: a merge that failed, fell back to appending, or left the stored text unchanged reports none. identity is the record's key rendered field='value', a composite one comma-separated; it is empty when the record has no key or part of it is unknown.

Schema evolution

Schemas can change after creation. xmemory supports safe, data-preserving migrations (rename / remove / type change) driven by structured migration ops, plus a suggestion engine that proposes improvements from real read traffic. Both paths are purely additive to this library — existing callers are unaffected.

See the Schema evolution section of the API reference for the conceptual model, and the Python guide for full walkthroughs.

Suggestion-engine flow (review → decide → apply)

The engine surfaces a single rolling proposal per instance. The minimum flow is three calls — review, decide (in bulk), apply:

from xmemory import DecisionInput, XmemoryClient

client = XmemoryClient(api_key="xmem_...")
inst = client.instance("<instance-id>")

# 1. Review — get the consolidated proposal + its concurrency token.
review = inst.review_suggestions()
if review.status == "evolution_in_progress":
    print(f"A migration is in flight; retry in {review.retry_after_seconds}s")
else:
    proposal = review.proposal
    for item in proposal.items:
        print(item.item_fingerprint, item.rationale, item.op)

    # 2. Decide — accept / reject / defer per item, in one batch. Leave out
    #    items flagged apply_blocked: accepting one fails the whole apply.
    decisions = [
        DecisionInput(item_fingerprint=item.item_fingerprint, decision="accept")
        for item in proposal.items if not item.apply_blocked
    ]
    if decisions:
        decided = inst.decide_suggestions(proposal.proposal_version, decisions)

        # 3. Apply — commit accepted decisions as one migration.
        applied = inst.apply_pending_decisions(decided.next_proposal_version)
        print(applied.status, applied.summary)  # e.g. "ok" "added 1 field"

review_suggestions() returns a ReviewSuggestionsResult. When status == "evolution_in_progress", back off for retry_after_seconds and retry instead of blocking.

An item with apply_blocked == True cannot be applied as proposed — for example a field that another item in the same proposal already adds as part of a new object — and its rationale says why. Accepting it fails the whole apply, so a bulk accept should skip it; the remaining items apply together. When every item is flagged there is nothing to accept: skip the decide call, which refuses an empty batch with invalid_decision_input.

Direct migration flow (enhance → dry-run → update)

To drive a migration yourself (e.g. renaming a field), ask the server to enhance the current schema, preview the DDL, then apply it:

import yaml
from xmemory import SchemaType, XmemoryClient

client = XmemoryClient(api_key="xmem_...")
current = client.admin.get_instance_schema("<instance-id>").data_schema

# 1. Enhance — produce the new schema + an executor-ready migration plan.
enhanced = client.admin.enhance_instance_schema(
    instance_id="<instance-id>",
    schema_description="Rename Person.mail to Person.email.",
    current_yml_schema=yaml.safe_dump(current),
)
print(enhanced.summary)
for op in enhanced.migration_plan.ops:
    print(op)

new_yaml = yaml.safe_dump(enhanced.data_schema)

# 2. Dry-run — preview the DDL without applying anything.
preview = client.admin.dry_run_migration(
    "<instance-id>", new_yaml, SchemaType.YML,
    migration_plan=enhanced.migration_plan,
)
print(preview.statements)

# 3. Update — apply. confirm_destructive=True is required for ops that drop data.
info = client.admin.update_instance_schema(
    "<instance-id>", new_yaml, SchemaType.YML,
    migration_plan=enhanced.migration_plan,
    confirm_destructive=False,
)
print(info.migration_id, info.prior_version, "->", info.new_version)

enhance_instance_schema runs on the model the instance is configured to use. To enhance a schema not tied to an instance, call client.admin.enhance_schema("<cluster-id>", description, current_yaml), which runs on the cluster's model.

Migration history

page = client.admin.list_migrations("<instance-id>", limit=20)
for record in page.items:
    print(record.id, record.source, record.prior_version, "->", record.new_version)

detail = client.admin.get_migration("<instance-id>", "<migration-id>", include_yaml=True)
print(detail.yaml_before, detail.yaml_after)

Migration ops are exported as typed models (MigrationPlan, MigrationOp, AddField, RenameField, RemoveObject, …). ProposalItem.op and MigrationRecord.ops are kept as raw dicts for forward compatibility — call parse_migration_op(...) / parse_migration_plan(...) to validate them into typed ops.

Runnable end-to-end examples live in examples/.

Context managers

Both clients support the context manager protocol and close the underlying HTTP connection on exit.

# sync
with XmemoryClient(api_key="xmem_...") as client:
    inst = client.instance("abc")
    inst.write("...")

# async
async with AsyncXmemoryClient(api_key="xmem_...") as client:
    inst = client.instance("abc")
    await inst.write("...")

External HTTP client

You can pass your own httpx.Client (or httpx.AsyncClient). The client will not be closed when the Xmemory client is closed, giving you full control over its lifecycle.

import httpx
from xmemory import XmemoryClient

http = httpx.Client(base_url="https://api.xmemory.ai", timeout=30)
client = XmemoryClient(http_client=http, api_key="xmem_...")

The library never modifies a client you pass in — the object you built is the object you keep. It adds one header, X-Xmemory-Client, to the requests it issues through that client (xmemory-python/<version> (python <version>; <system>-<machine>), which the API uses to tell its own clients apart). The header is added per request rather than installed on your client, so a client you share with other traffic carries nothing of ours between calls.

Your User-Agent is never read and never written. Set it, clear it, leave it at httpx's default — attribution is unaffected either way, because it does not live in that field. That is the reason for a dedicated header: User-Agent belongs to whoever built the request, and a library claiming it has to decide whose choice to overrule.

Setting the header on a client you pass in is not how you get attributed, and not necessary: the library adds its own on every request it issues, and a per-request header wins over a client-level one in httpx, so yours would be replaced on each call. xmemory.client_identity() and xmemory.CLIENT_HEADER are exported for requests you send to the API outside this library:

import httpx
from xmemory import CLIENT_HEADER, client_identity

# A call this library does not make for you -- an endpoint it does not wrap, say.
httpx.get(
    "https://api.xmemory.ai/some/endpoint",
    headers={CLIENT_HEADER: client_identity(), "Authorization": "Bearer xmem_..."},
)

The API key travels on every API request, whichever client issues it. check_health() is the one exception, on both paths: it requests /healthz, which takes no key.

Health check

from xmemory import XmemoryHealthCheckError

try:
    client.check_health()
except XmemoryHealthCheckError as e:
    print(f"API is unreachable: {e}")

Error handling

All errors raise XmemoryAPIError (or its subclass XmemoryHealthCheckError for connectivity failures). XmemoryAPIError carries an optional .status (HTTP status code), .code (structured error code, when the server returned one), .details (structured error payload), and .retry_after (the Retry-After response header in seconds, when the server sent one).

from xmemory import XmemoryAPIError

try:
    result = client.instance("abc").read("something")
except XmemoryAPIError as e:
    print(f"API error (HTTP {e.status}): {e}")

Branch on .code, not on the HTTP status. A single status can carry more than one meaning, so the structured .code is the discriminator, never the bare status. Pattern match on .code rather than parsing the message string.

Account / billing & rate-limit codes

HTTP .code Meaning Retryable?
402 QUOTA_EXCEEDED Tenant exhausted its plan's daily/monthly token quota. No
429 RATE_LIMITED Genuine velocity/rate limit. Yes — back off and retry, honoring .retry_after.

For QUOTA_EXCEEDED, details carries {"kind": "daily_quota_exceeded" | "monthly_quota_exceeded", "retry_after_seconds": int | None}, and when the window is resettable the server also sends a Retry-After header (surfaced as .retry_after). The library never retries automatically — it only surfaces these values for you to act on.

import time

try:
    result = client.instance("abc").write("…")
except XmemoryAPIError as e:
    if e.code == "QUOTA_EXCEEDED":
        kind = (e.details or {}).get("kind")  # daily_quota_exceeded | monthly_quota_exceeded
        # Non-retryable: surface to the user; e.retry_after (seconds) hints when the window resets.
        raise
    elif e.code == "RATE_LIMITED":
        # Retryable: back off, honoring e.retry_after if set, then retry.
        time.sleep(e.retry_after or 1)
    else:
        raise

Read codes

HTTP .code Meaning Retryable?
422 INVALID_INPUT The read answered nothing: in raw-tables / xresponse mode every sub-query's SQL failed, or the model provider declined the input. See What comes back. No — the same input gives the same answer.
403 FORBIDDEN The API key lacks a permission the call needs — for a read with include_related_types=RelatedTypesMode.TYPES, instance.get (servers from before the permission rename call it instance.get_own); the message names it. See Related types. No — repeat without the option, or use a key that holds it.

Schema-evolution codes

The schema-evolution endpoints return structured error codes you can pattern match on via .code rather than parsing the message — for example stale_proposal_version, dependency_closure_failed, destructive_confirmation_required, non_additive_change_requires_plan, stale_schema_version, migration_not_found, instance_not_initialised:

try:
    inst.apply_pending_decisions(token)
except XmemoryAPIError as e:
    if e.code == "stale_proposal_version":
        review = inst.review_suggestions()  # re-review and retry

Response types

Method Returns
admin.list_clusters() list[ClusterInfo]
admin.get_cluster() ClusterInfo
admin.create_instance() InstanceAPI
admin.list_instances() list[InstanceInfo]
admin.get_instance() InstanceInfo
admin.get_setup_instructions() AgentSetupResult
admin.get_instance_schema() InstanceSchemaInfo
admin.update_instance_schema() InstanceInfo
admin.update_instance_metadata() InstanceInfo
admin.patch_instance_metadata() InstanceInfo
admin.delete_instance() list[str]
admin.generate_schema() GenerateSchemaResult
admin.enhance_schema() EnhanceSchemaResult
admin.enhance_instance_schema() EnhanceSchemaResult
admin.dry_run_migration() DryRunResult
admin.list_migrations() ListMigrationsResult
admin.get_migration() MigrationRecord
inst.read() ReadResult
inst.write() WriteResult
inst.write_async() AsyncWriteResult
inst.write_status() WriteStatusResult
inst.extract() ExtractResult
inst.get_schema() InstanceSchemaInfo
inst.describe() DescribeResult
inst.setup_instructions() AgentSetupResult
inst.review_suggestions() ReviewSuggestionsResult
inst.decide_suggestions() DecideSuggestionsResult
inst.apply_pending_decisions() ApplyPendingDecisionsResult

License

This client library is released under the MIT license. The MIT grant covers this library only — the xmemory service it talks to and the technology behind it are proprietary to xmemory Inc., and using the service is governed by the Terms & Conditions.

Package publishing to pip

python -m pip install --upgrade build twine
python -m build

# test with test.pypi.org (separate account and API key required)
python -m twine upload --repository testpypi dist/*

# publish the real version when ready
python -m twine upload dist/*

# test the package
pip install xmemory-ai

Connecting an instance elsewhere

admin.get_setup_instructions(instance_id) and inst.setup_instructions() both return an AgentSetupResult: how to reach the same memory from another agent surface, ordered most-likely-first. Available on either handle, because the MCP instance connection serves the same tool.

setup = inst.setup_instructions()
for surface in setup.surfaces:
    print(surface.label)
    for step in surface.steps:
        print(" ", step.description, step.command or "")

Two formats. The default, SetupFormat.AGENT, answers what do I run right now, here. SetupFormat.PROJECT also returns the files a team commits once, so nobody sets the instance up by hand:

setup = inst.setup_instructions(format=SetupFormat.PROJECT)
if setup.format == SetupFormat.PROJECT and setup.project:
    for fragment in setup.project.fragments:
        print(fragment.path, fragment.merge)   # a merge, never a file to overwrite

Check setup.format rather than assuming. A server older than that parameter ignores it and still answers 200, so asking for PROJECT is not the same as receiving it.

Nothing returned carries a credential: the steps tell a reader to sign in themselves, out of band, so an instance id stays an identifier rather than a key.

Advisory values — step.kind, fragment.merge, format — arrive as enum members when this release knows them and as plain strings when it does not, so a value added to the server later does not make the whole result unparseable. A step.kind you do not recognise is not something to execute.

Metadata

Release files for xmemory-ai 0.25.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for xmemory-ai 0.25.0
File Size Uploaded Provenance Actions
xmemory_ai-0.25.0.tar.gz 108.0 kB Without provenance Details for xmemory_ai-0.25.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for xmemory-ai 0.25.0
File Interpreter ABI Platform Actions
xmemory_ai-0.25.0-py3-none-any.whl Python 3 none any Details for xmemory_ai-0.25.0-py3-none-any.whl

Total release size: 164.9 kB

Release files / xmemory_ai-0.25.0.tar.gz

Download URL xmemory_ai-0.25.0.tar.gz
Size 108.0 kB
Tags Source
SHA-256 checksum
How to use checksums
83f6b749d76bf252053927d1c1cedddb90700183bb5cdc09942fa902f20cff35
BLAKE2b-256 checksum
How to use checksums
cde3f0321a80190de466e01496145557e9b1e82ca25454c62ef0d8d4b11a061b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / xmemory_ai-0.25.0-py3-none-any.whl

Download URL xmemory_ai-0.25.0-py3-none-any.whl
Size 56.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9c29c0f670b26be82fdcf4fc6085baa0b1fbaabe530979440482ff205cdf544f
BLAKE2b-256 checksum
How to use checksums
050c18685e5fd2060dc7bfc450011b8f215af087c028e366b2159d431d1fa3b0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for xmemory-ai 0.25.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.25.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page