Skip to main content

Python SDK: Memories

Create, search, update, and delete memories with the Python SDK.

Overview

The memories resource handles creating, reading, updating, and deleting memory objects. Memories are the core data type in Trix.

All memory operations support both synchronous and asynchronous clients. See Advanced for async examples.

Create Memory

create_memory.py
from trix import MemoryType

memory = client.memories.create(
    content="Python is great for data science and machine learning",
    type=MemoryType.TEXT,
    tags=["python", "programming"],
    metadata={
        "source": "documentation",
        "author": "team"
    },
    priority=5,
    space_id="space_abc123"
)

print(memory.id)
print(memory.content)

Memory Types

TypeDescription
TEXTPlain text content
MARKDOWNMarkdown-formatted content
URLURL to be fetched and processed
AUDIOAudio file for transcription
IMAGEImage for visual embedding + OCR

List and Search Memories

list_memories.py
from trix import SearchMode

result = client.memories.list(limit=20, offset=0)
for memory in result.data:
    print(memory.content)

result = client.memories.list(
    q="how does Python handle memory?",
    mode=SearchMode.SEMANTIC,
    limit=10
)

result = client.memories.list(
    tags=["python", "ml"],
    space_id="space_dev"
)

Search Modes

ModeDescriptionBest For
SEMANTICVector similarity searchConceptual queries, finding related content
KEYWORDTraditional keyword searchExact matches, known keywords
HYBRIDCombines semantic and keywordGeneral purpose (recommended)

Iterate Through All Memories

Stream through all memories with automatic pagination:

iterate_memories.py
for memory in client.memories.iter(page_size=100):
    print(memory.content)

for memory in client.memories.iter(
    tags=["important"],
    page_size=50,
    max_items=1000
):
    process_memory(memory)

The iter() method handles pagination automatically, making it easy to process large datasets without managing offsets manually.

Get Single Memory

get_memory.py
memory = client.memories.get("mem_xyz789")
print(memory.content)
print(memory.tags)
print(memory.metadata)

Update Memory

update_memory.py
updated = client.memories.update(
    "mem_xyz789",
    content="Updated content here",
    tags=["python", "updated"],
    metadata={"last_reviewed": "2024-01-15"},
    priority=8
)

Updating content will trigger re-embedding. If you only want to update metadata without re-embedding, use the embed=False option.

Delete Memory

delete_memory.py
client.memories.delete("mem_xyz789")

Bulk Operations

Efficiently create, update, or delete multiple memories at once:

Bulk Create

bulk_create.py
from trix import MemoryCreate

result = client.memories.bulk_create([
    MemoryCreate(content="First memory", tags=["batch"]),
    MemoryCreate(content="Second memory", tags=["batch"]),
    MemoryCreate(content="Third memory", tags=["batch"])
])
print(f"Created: {len(result)}")

Bulk Update

bulk_update.py
client.memories.bulk_update([
    {"id": "mem_1", "tags": ["reviewed"]},
    {"id": "mem_2", "content": "Updated content"}
])

Bulk Delete

bulk_delete.py
client.memories.bulk_delete(["mem_1", "mem_2", "mem_3"])

Audio Memories

Store and transcribe audio files:

Create from Audio File

create_audio.py
with open("recording.mp3", "rb") as audio_file:
    memory = client.memories.create_with_audio(
        audio_file=audio_file,
        filename="recording.mp3",
        content_type="audio/mpeg",
        tags=["meeting", "q4"],
        transcribe=True,
        language="en"
    )

Stream Audio Content

stream_audio.py
audio_bytes = client.memories.stream_audio("mem_audio123")

for chunk in client.memories.stream_audio_chunks("mem_audio123", chunk_size=8192):
    process_chunk(chunk)

Transcription

transcription.py
job = client.memories.transcribe("mem_audio123", language="en")

transcript = client.memories.get_transcript("mem_audio123")
print(transcript.text)
print(transcript.segments)

Highlights

Create and manage text highlights within memories.

highlights.py
from trix import ExtractionType

highlight = client.highlights.create(
    memory_id="mem_xyz",
    text="important concept here",
    note="Key takeaway from this section",
    importance=5,
    tags=["key-point"],
    color="#FFFF00"
)

highlights = client.highlights.list("mem_xyz", limit=20)
for h in highlights.data:
    print(f'"{h.text}" - {h.note}')

extractions = client.highlights.extract(
    memory_id="mem_xyz",
    extraction_types=[
        ExtractionType.KEY_POINTS,
        ExtractionType.ENTITIES,
        ExtractionType.QUOTES
    ],
    limit=10
)

for extraction in extractions:
    print(f"Type: {extraction.extraction_type}")
    for h in extraction.highlights:
        print(f"  - {h.text}")

client.highlights.update("hlt_abc", color="#00FF00", note="Updated note")
client.highlights.delete("hlt_abc")

Memory Pinning

Pin important memories to prevent them from being affected by decay or automatic cleanup. Pinned memories are always prioritized in search results.

pinning.py
client.memories.pin("mem_xyz789")
client.memories.unpin("mem_xyz789")

memory = client.memories.get("mem_xyz789")
print(f"Pinned: {memory.is_pinned}")

memory = client.memories.create(
    content="Critical business rule: always validate input",
    is_pinned=True,
    tags=["rules", "validation"]
)

pinned = client.memories.list(pinned=True)
for m in pinned.data:
    print(f"Pinned: {m.content[:50]}...")

Use pinning for critical information that should never be forgotten, such as core business rules, important contacts, or key procedures.

Protection Levels

Set protection levels on memories to control how they can be modified or deleted. This provides an extra layer of safety for important data.

protection.py
from trix import ProtectionLevel

client.memories.set_protection_level("mem_xyz789", "hard")

memory = client.memories.create(
    content="Legal compliance requirement: retain for 7 years",
    protection_level="hard",
    tags=["legal", "compliance"]
)

memory = client.memories.get("mem_xyz789")
print(f"Protection: {memory.protection_level}")

client.memories.set_protection_level("mem_xyz789", "none")
client.memories.delete("mem_xyz789")

Protection Level Reference

LevelDescriptionUse Case
noneNo protection, can be freely modified or deletedRegular memories
softDeletion requires explicit confirmationImportant but occasionally updated data
hardCannot be deleted without first removing protectionCritical data, compliance requirements

Soft Delete & Restore

Soft delete moves memories to a recoverable state instead of permanently deleting them. This allows you to restore accidentally deleted memories.

soft_delete.py
client.memories.soft_delete("mem_xyz789")
client.memories.restore("mem_xyz789")

memory = client.memories.get("mem_xyz789")
print(f"Status: active")

deleted = client.memories.list(include_deleted=True)
for m in deleted.data:
    print(f"{m.content[:50]}...")

client.memories.delete("mem_xyz789")

Soft-deleted memories are automatically purged after 30 days by default. Configure the retention period in your space settings.

Topic Extraction

Extract and search by topics to organize and discover related memories. Topics are automatically extracted or can be manually assigned.

topics.py
topics = client.memories.get_topics("mem_xyz789")
for topic in topics:
    print(f"Topic: {topic.name} (confidence: {topic.confidence:.2f})")

results = client.search.by_topic("machine learning")
for result in results.data:
    print(f"{result.score:.2f}: {result.memory.content[:50]}...")

results = client.search.by_topic(
    topics=["python", "data science"],
    match_all=True,
    limit=20
)

Quality Scores & Enrichment

Assess memory quality and enrich memories with additional metadata, summaries, and extracted information.

Quality Scores

quality.py
score = client.memories.get_quality_score("mem_xyz789")
print(f"Quality score: {score:.2f}")

high_quality = client.memories.list(min_quality=0.7, limit=50)
for m in high_quality.data:
    print(f"High quality: {m.content[:50]}...")

Memory Enrichment

enrichment.py
from trix import EnrichmentOperation

result = client.enrichments.enrich(
    "mem_xyz789",
    operations=["topics", "summary", "entities"]
)

print(f"Summary: {result.summary}")
print(f"Topics: {result.topics}")
print(f"Entities: {result.entities}")

batch_result = client.enrichments.batch_enrich(
    memory_ids=["mem_1", "mem_2", "mem_3"],
    operations=[
        EnrichmentOperation.TOPICS,
        EnrichmentOperation.SUMMARY,
        EnrichmentOperation.KEY_POINTS
    ]
)

for enrichment in batch_result.results:
    print(f"{enrichment.memory_id}: {enrichment.summary[:100]}...")

Enrichment Operations

OperationDescription
topicsExtract topic labels from content
summaryGenerate a concise summary
entitiesExtract named entities (people, places, organizations)
key_pointsExtract key points and takeaways
sentimentAnalyze sentiment and tone
keywordsExtract important keywords

Multi-scale Clusters

Access memory clusters at different granularity levels to understand how memories are organized and find related content.

clusters.py
from trix import ClusterScale

fine_clusters = client.clusters.list(scale="fine")
medium_clusters = client.clusters.list(scale="medium")
coarse_clusters = client.clusters.list(scale="coarse")

print(f"Fine clusters: {len(fine_clusters.data)}")
print(f"Medium clusters: {len(medium_clusters.data)}")
print(f"Coarse clusters: {len(coarse_clusters.data)}")

for cluster in fine_clusters.data[:5]:
    print(f"Cluster: {cluster.label}")
    print(f"  Memories: {cluster.memory_count}")
    print(f"  Topics: {cluster.topics}")

results = client.search.query("artificial intelligence", cluster_scale="coarse")
cluster_memories = client.clusters.get_memories("cluster_abc123", limit=50)
cluster = client.clusters.get("cluster_abc123")
print(f"Cluster: {cluster.label}")

Cluster Scales

ScaleDescriptionTypical Use
fineMany small, tightly related clustersFinding very similar memories
mediumBalanced clusteringGeneral organization (default)
coarseFew large, broadly related clustersHigh-level categorization

Advanced List & Create Options

The list and create methods support additional parameters for fine-grained control over memory management.

Advanced List Options

advanced_list.py
memories = client.memories.list(
    q="search query",
    mode=SearchMode.HYBRID,
    tags=["important"],
    space_id="space_abc123",
    pinned=True,
    protected=True,
    min_quality=0.7,
    include_deleted=False,
    session_id="sess_abc123",
    limit=50,
    offset=0
)

for memory in client.memories.iter(
    tags=["important"],
    space_id="space_abc123",
    page_size=100
):
    print(f"Memory: {memory.content[:50]}...")

Advanced Create Options

advanced_create.py
memory = client.memories.create(
    content="Important business rule documentation",
    type=MemoryType.MARKDOWN,
    tags=["rules", "documentation"],
    metadata={
        "author": "admin",
        "department": "engineering"
    },
    space_id="space_abc123",
    priority=9,
    is_pinned=True,
    protection_level="soft",
    session_id="sess_abc123"
)

print(f"Created: {memory.id}")
print(f"Pinned: {memory.is_pinned}")
print(f"Protection: {memory.protection_level}")

Feedback

Collect user feedback on memories to improve relevance and quality.

feedback.py
from trix import FeedbackResult

response = client.feedback.submit(
    query_context="machine learning basics",
    results=[
        FeedbackResult(memory_id="mem_1", score=0.9, rank=1),
        FeedbackResult(memory_id="mem_2", score=0.8, rank=2),
        FeedbackResult(memory_id="mem_3", score=0.6, rank=3)
    ],
    boost_amount=0.5,
    create_relationships=True
)

print(f"Boosted {response.memories_boosted} memories")
print(f"Created {response.relationships_created} relationships")

client.feedback.quick(
    memory_id="mem_xyz",
    useful=True,
    source_memory_id="mem_query"
)

client.feedback.batch(
    useful_ids=["mem_1", "mem_2"],
    not_useful_ids=["mem_3"],
    source_memory_id="mem_query"
)