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.
Installation
Section titled “Installation”pip install xmemory-aiRequires Python 3.12+ and pydantic>=2.0.
Quick start
Section titled “Quick start”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 rememberschema = mem.generate_schema( "Track contacts with name, email, company, and notes.")
# Create a memory instance from that schemaresp = 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 informationmem.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 backresult = 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")Configuration
Section titled “Configuration”| Parameter | Env var | Default | Description |
|---|---|---|---|
token | XMEM_AUTH_TOKEN | None | Bearer token for authentication |
url | XMEM_API_URL | https://api.xmemory.ai | API base URL |
instance_id | — | None | Instance to read/write against |
timeout | — | 60 | Default request timeout in seconds |
All parameters are keyword-only. Token and URL fall back to their environment variables when not passed.
Writing
Section titled “Writing”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 storedprint(resp.diff_plan) # what was inserted, updated, or deletedExtraction logic
Section titled “Extraction logic”Control the speed/accuracy tradeoff:
from xmemory import ExtractionLogic
resp = mem.write("...", extraction_logic=ExtractionLogic.FAST)| Value | When to use |
|---|---|
DEEP | Important or complex information (default) |
REGULAR | Balanced speed and accuracy |
FAST | High-volume, low-stakes writes |
Reading
Section titled “Reading”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)Read modes
Section titled “Read modes”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 relationsresp = mem.read("Show all contacts", read_mode=ReadMode.XRESPONSE)# → {"objects": [...], "relations": [...]}
# Raw SQL result setsresp = mem.read("List all contacts", read_mode=ReadMode.RAW_TABLES)# → {"tables": [...]}Extracting (without writing)
Section titled “Extracting (without writing)”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.
Schemas
Section titled “Schemas”Generating
Section titled “Generating”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.
Updating
Section titled “Updating”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.
Error handling
Section titled “Error handling”All errors raise XmemoryAPIError. The exception carries an optional .status attribute with the HTTP status code.
from xmemory import XmemoryAPIError, XmemoryHealthCheckError
# Check connectivitytry: mem.check_health()except XmemoryHealthCheckError as e: print(f"API unreachable: {e}")
# Handle operation errorstry: mem.write("...")except XmemoryAPIError as e: print(f"Error (HTTP {e.status}): {e}")XmemoryHealthCheckError is a subclass of XmemoryAPIError, so catching XmemoryAPIError covers both.
Reference
Section titled “Reference”Methods
Section titled “Methods”| Method | Returns | Description |
|---|---|---|
check_health() | — | Raises XmemoryHealthCheckError if the API is unreachable |
generate_schema(description, *, old_schema_yml, timeout) | GenerateSchemaResponse | Generate a schema from a plain-language description |
create_instance(schema_text, schema_type, *, timeout) | CreateInstanceResponse | Create a new instance; auto-saves instance_id on success |
update_schema(schema_text, schema_type, *, timeout) | bool | Update the current instance’s schema |
write(text, *, extraction_logic, timeout) | WriteResponse | Extract and persist objects from text |
read(query, *, read_mode, timeout) | ReadResponse | Query the instance in natural language |
extract(text, *, extraction_logic, timeout) | ExtractionResponse | Extract objects without writing them |
| Enum | Values |
|---|---|
SchemaType | YML, JSON |
ExtractionLogic | FAST, REGULAR, DEEP |
ReadMode | SINGLE_ANSWER, RAW_TABLES, XRESPONSE |
Exceptions
Section titled “Exceptions”| Exception | Parent | .status |
|---|---|---|
XmemoryAPIError | Exception | HTTP status code or None |
XmemoryHealthCheckError | XmemoryAPIError | HTTP status code or None |