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
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
| Type | Description |
|---|---|
TEXT | Plain text content |
MARKDOWN | Markdown-formatted content |
URL | URL to be fetched and processed |
AUDIO | Audio file for transcription |
IMAGE | Image for visual embedding + OCR |
List and Search Memories
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
| Mode | Description | Best For |
|---|---|---|
SEMANTIC | Vector similarity search | Conceptual queries, finding related content |
KEYWORD | Traditional keyword search | Exact matches, known keywords |
HYBRID | Combines semantic and keyword | General purpose (recommended) |
Iterate Through All Memories
Stream through all memories with automatic pagination:
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
memory = client.memories.get("mem_xyz789")
print(memory.content)
print(memory.tags)
print(memory.metadata)Update Memory
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
client.memories.delete("mem_xyz789")Bulk Operations
Efficiently create, update, or delete multiple memories at once:
Bulk Create
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
client.memories.bulk_update([
{"id": "mem_1", "tags": ["reviewed"]},
{"id": "mem_2", "content": "Updated content"}
])Bulk Delete
client.memories.bulk_delete(["mem_1", "mem_2", "mem_3"])Audio Memories
Store and transcribe audio files:
Create from Audio File
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
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
job = client.memories.transcribe("mem_audio123", language="en")
transcript = client.memories.get_transcript("mem_audio123")
print(transcript.text)
print(transcript.segments)Search
The search resource provides semantic search and embedding operations.
Find Similar Memories
results = client.search.similar(
memory_id="mem_xyz",
limit=10,
threshold=0.6
)
for result in results:
print(f"{result.score:.2f}: {result.memory.content[:50]}...")Generate Embeddings
response = client.search.embed(["mem_1", "mem_2", "mem_3"])
for memory_id, embedding in zip(response.memory_ids, response.embeddings):
print(f"{memory_id}: {len(embedding)} dimensions")
batch = client.search.embed_all(batch_size=100)
print(f"Processed {batch.total_processed} memories")Search Configuration
config = client.search.get_config()
print(f"Default limit: {config.default_limit}")
print(f"Max limit: {config.max_limit}")
print(f"Min similarity: {config.min_similarity_threshold}")Highlights
Create and manage text highlights within memories.
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.
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.
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
| Level | Description | Use Case |
|---|---|---|
none | No protection, can be freely modified or deleted | Regular memories |
soft | Deletion requires explicit confirmation | Important but occasionally updated data |
hard | Cannot be deleted without first removing protection | Critical 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.
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 = 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
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
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
| Operation | Description |
|---|---|
topics | Extract topic labels from content |
summary | Generate a concise summary |
entities | Extract named entities (people, places, organizations) |
key_points | Extract key points and takeaways |
sentiment | Analyze sentiment and tone |
keywords | Extract important keywords |
Multi-scale Clusters
Access memory clusters at different granularity levels to understand how memories are organized and find related content.
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
| Scale | Description | Typical Use |
|---|---|---|
fine | Many small, tightly related clusters | Finding very similar memories |
medium | Balanced clustering | General organization (default) |
coarse | Few large, broadly related clusters | High-level categorization |
Advanced List & Create Options
The list and create methods support additional parameters for fine-grained control over memory management.
Advanced List Options
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
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.
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"
)