Skip to content

Python

The xmemory-ai package gives your Python code persistent, structured memory. Write free-form text, have it automatically extracted into typed objects, and query it back in natural language.

For MCP-based integration (no SDK needed), see the MCP guide.

API key: To use xmemory APIs or integrations, you need an API key. Please register your interest at https://xmemory.ai and we will reach out to give access. Copy and securely store the key. Never share your API key publicly.


Terminal window
pip install xmemory-ai

Requires Python 3.12+ and pydantic>=2.0.


This is the full flow — from schema to stored knowledge to answers — in a single script:

from xmemory import xmemory_instance, SchemaType
# Connect (reads XMEM_AUTH_TOKEN from env if token is not passed)
mem = xmemory_instance(token="your-token")
# Describe what you want to remember
schema = mem.generate_schema(
"Track contacts with name, email, company, and notes."
)
# Create a memory instance from that schema
resp = mem.create_instance(schema.generated_schema, SchemaType.YML)
print(f"Instance created: {resp.instance_id}")
# The instance_id is saved on the client automatically —
# all subsequent calls use it.
# Write some information
mem.write("Alice Johnson works at Acme Corp. Her email is alice@acme.com.")
mem.write("Bob Lee is a designer at Globex. He joined last Monday.")
# Read it back
result = mem.read("What is Alice's email?")
print(result.reader_result) # {"answer": "alice@acme.com"}
result = mem.read("Who joined recently?")
print(result.reader_result) # {"answer": "Bob Lee joined last Monday."}

Once you have an instance_id, you can skip the schema step on subsequent runs:

mem = xmemory_instance(token="your-token", instance_id="your-saved-instance-id")

ParameterEnv varDefaultDescription
tokenXMEM_AUTH_TOKENNoneBearer token for authentication
urlXMEM_API_URLhttps://api.xmemory.aiAPI base URL
instance_idNoneInstance to read/write against
timeout60Default request timeout in seconds

All parameters are keyword-only. Token and URL fall back to their environment variables when not passed.


Send free-form text — xmemory extracts structured objects according to your schema and merges them into the knowledge graph.

resp = mem.write("Carol is a senior engineer at Initech. Her email is carol@initech.com.")
print(resp.cleaned_objects) # the objects that were stored
print(resp.diff_plan) # what was inserted, updated, or deleted

Control the speed/accuracy tradeoff:

from xmemory import ExtractionLogic
resp = mem.write("...", extraction_logic=ExtractionLogic.FAST)
ValueWhen to use
DEEPImportant or complex information (default)
REGULARBalanced speed and accuracy
FASTHigh-volume, low-stakes writes

Ask questions in natural language. xmemory translates them into SQL against the knowledge graph and returns a formatted answer.

resp = mem.read("Who works at Acme Corp?")
print(resp.reader_result)
from xmemory import ReadMode
# Plain-text answer (default)
resp = mem.read("What is Alice's email?", read_mode=ReadMode.SINGLE_ANSWER)
# → {"answer": "alice@acme.com"}
# Structured objects and relations
resp = mem.read("Show all contacts", read_mode=ReadMode.XRESPONSE)
# → {"objects": [...], "relations": [...]}
# Raw SQL result sets
resp = mem.read("List all contacts", read_mode=ReadMode.RAW_TABLES)
# → {"tables": [...]}

Preview what xmemory would extract from a piece of text, without storing anything:

resp = mem.extract("Dave manages the London office.")
print(resp.objects_extracted)

Accepts the same extraction_logic parameter as write.


Describe what you want to track in plain language:

schema = mem.generate_schema(
"Track user preferences, open tasks with priorities, and conversation history."
)
print(schema.generated_schema)

Object names use CamelCase (UserPreferences, OpenTask). The generation endpoint handles naming conventions automatically.

When your needs change, pass the existing schema so changes are incremental:

schema = mem.generate_schema(
"Add an assignee field to tasks.",
old_schema_yml=current_schema,
)
mem.update_schema(schema.generated_schema, SchemaType.YML)

Existing objects and fields are preserved — only the described changes are applied.


All errors raise XmemoryAPIError. The exception carries an optional .status attribute with the HTTP status code.

from xmemory import XmemoryAPIError, XmemoryHealthCheckError
# Check connectivity
try:
mem.check_health()
except XmemoryHealthCheckError as e:
print(f"API unreachable: {e}")
# Handle operation errors
try:
mem.write("...")
except XmemoryAPIError as e:
print(f"Error (HTTP {e.status}): {e}")

XmemoryHealthCheckError is a subclass of XmemoryAPIError, so catching XmemoryAPIError covers both.


MethodReturnsDescription
check_health()Raises XmemoryHealthCheckError if the API is unreachable
generate_schema(description, *, old_schema_yml, timeout)GenerateSchemaResponseGenerate a schema from a plain-language description
create_instance(schema_text, schema_type, *, timeout)CreateInstanceResponseCreate a new instance; auto-saves instance_id on success
update_schema(schema_text, schema_type, *, timeout)boolUpdate the current instance’s schema
write(text, *, extraction_logic, timeout)WriteResponseExtract and persist objects from text
read(query, *, read_mode, timeout)ReadResponseQuery the instance in natural language
extract(text, *, extraction_logic, timeout)ExtractionResponseExtract objects without writing them
EnumValues
SchemaTypeYML, JSON
ExtractionLogicFAST, REGULAR, DEEP
ReadModeSINGLE_ANSWER, RAW_TABLES, XRESPONSE
ExceptionParent.status
XmemoryAPIErrorExceptionHTTP status code or None
XmemoryHealthCheckErrorXmemoryAPIErrorHTTP status code or None