Skip to main content

TotalRecall Python SDK

Build AI that remembers. The official Python SDK for TotalRecall — production-grade memory infrastructure for AI applications.

Python Version License: MIT

Features

  • 🧠 Persistent Memory — Store memories forever with semantic embeddings
  • 🔍 Semantic Search — Find memories by meaning, not keywords
  • 🤖 Auto Extraction — AI automatically extracts memories from conversations
  • 🔄 Intelligent Forgetting — Qwen decides what to keep, archive, or delete
  • 📊 Quality Scoring — Monitor memory health with composite scores
  • 🔗 Conflict Detection — Automatically detect contradictory information
  • 📝 Memory Versioning — Track how knowledge evolves over time

Installation

pip install totalrecall-sdk

Quick Start

import asyncio
from totalrecall import TotalRecall

async def main():
    client = TotalRecall(
        api_key="tr_your_api_key",
        project_id="my-project-id",
    )

    # Store a memory
    await client.create_memory(
        content="User prefers dark mode and Vim editor",
        category="preference",
        importance=0.8,
    )

    # Search memories
    results = await client.search_memories(
        query="What editor does the user prefer?",
    )
    print(results)
    # [SearchResult(content='User prefers dark mode and Vim editor', score=0.95, ...)]

    # Get formatted context for your LLM
    context = await client.search_as_context(
        "Tell me about the user's preferences"
    )
    # "- [preference] User prefers dark mode and Vim editor (relevance: 95%)"

    await client.close()

asyncio.run(main())

API Reference

Configuration

client = TotalRecall(
    api_key="tr_your_api_key",        # Required: Your API key
    project_id="proj_123",            # Required: Project ID
    base_url="https://totalrecall.theatomicshift.com/api",  # Optional: API base URL
    max_retries=3,                     # Optional: Retry attempts (default: 3)
    timeout=30.0,                      # Optional: Timeout in seconds (default: 30)
)

Context Manager

async with TotalRecall(api_key="...", project_id="...") as client:
    results = await client.search_memories(query="test")
# Client automatically closed

Memory Operations

create_memory(content, ...)

Create a new memory.

memory = await client.create_memory(
    content="User is allergic to peanuts",
    category="health",
    label="allergy",
    importance=0.95,
    metadata={"source": "conversation", "conversation_id": "conv_123"},
)

get_memory(memory_id)

Retrieve a memory by ID.

memory = await client.get_memory("mem_abc123")
print(memory.content, memory.importance, memory.version)

list_memories(limit, offset, category)

List all memories for the project.

memories = await client.list_memories(limit=50, category="preference")

update_memory(memory_id, ...)

Update an existing memory.

updated = await client.update_memory(
    "mem_abc123",
    content="User now prefers VS Code",
    importance=0.9,
)

delete_memory(memory_id)

Delete a memory (soft delete — sets is_active: False).

await client.delete_memory("mem_abc123")

Search Operations

search_memories(query, ...)

Search memories by semantic similarity.

results = await client.search_memories(
    query="What are the user's coding preferences?",
    category="preference",
    limit=10,
    threshold=0.7,
)

for result in results:
    print(f"{result.content} (score: {result.score})")

search_as_context(query, limit, max_tokens)

Search and format results as context for LLM injection. Automatically handles token budgeting.

context = await client.search_as_context(
    "Tell me about this user",
    limit=10,
    max_tokens=2000,
)

# Use in your LLM prompt:
prompt = f"""
You are a helpful assistant. Here's what you know about the user:

{context}

User asks: {user_question}
"""

Stats & Versions

get_stats()

Get memory statistics for the project.

stats = await client.get_stats()
print(f"Total: {stats.total}, Active: {stats.active}")
print(f"Avg importance: {stats.avg_importance}")

get_versions(memory_id)

Get version history for a memory.

versions = await client.get_versions("mem_abc123")
for v in versions:
    print(f"v{v.version}: {v.content} ({v.created_at})")

AI Memory Intelligence

detect_conflicts(content, category)

Detect contradictions between new content and existing memories.

conflicts = await client.detect_conflicts(
    content="User hates React",
    category="opinion",
)

if conflicts:
    print(f"Found {len(conflicts)} conflicts:")
    for c in conflicts:
        print(f"  - {c.conflict_type}: '{c.existing_content}' vs '{c.new_content}'")

merge_memories(memory_ids, content)

Merge multiple memories into one.

merged = await client.merge_memories(
    memory_ids=["mem_abc", "mem_def"],
    content="User prefers dark mode, Vim, and TypeScript",
)

Intelligent Forgetting

run_forgetting_cycle(dry_run, max_api_calls)

Run the forgetting cycle to evaluate and clean up memories.

result = await client.run_forgetting_cycle(dry_run=False, max_api_calls=10)

print(f"Evaluated {result.total_evaluated} memories")
print(f"Kept: {result.kept}, Archived: {result.archived}, Deleted: {result.deleted}")

preview_forgetting_cycle(max_api_calls)

Preview what the forgetting cycle would do without making changes.

preview = await client.preview_forgetting_cycle(max_api_calls=5)
print("Dry run results:")
for a in preview.actions:
    print(f"  {a.action}: '{a.content}' ({a.reason})")

Quality & Summary

get_quality_score()

Get the memory health score for the project.

quality = await client.get_quality_score()
print(f"Health: {quality.overall_score}/100")
print(f"Freshness: {quality.freshness}, Diversity: {quality.diversity}")
print(f"Categories: {quality.category_distribution}")

get_summary()

Get an AI-generated summary of all project memories.

summary = await client.get_summary()
print(summary)
# "This project tracks a software developer who prefers dark mode..."

Webhooks

create_webhook(name, url, events)

Register a webhook for memory events.

webhook = await client.create_webhook(
    name="Slack Notifications",
    url="https://hooks.slack.com/xxx",
    events=["memory.created", "memory.updated"],
)
print(f"Secret: {webhook.secret}")  # Only shown on creation!

list_webhooks()

List all webhooks for the project.

webhooks = await client.list_webhooks()
for w in webhooks:
    print(f"{w.name}: {'active' if w.is_active else 'inactive'}")

delete_webhook(webhook_id)

Delete a webhook.

await client.delete_webhook("wh_abc123")

toggle_webhook(webhook_id)

Toggle a webhook's active state.

toggled = await client.toggle_webhook("wh_abc123")
print(f"{'active' if toggled.is_active else 'inactive'}")

test_webhook(webhook_id)

Send a test event to a webhook.

result = await client.test_webhook("wh_abc123")
print(f"Delivered to {result.triggered}/{result.total} webhooks")

Audit Logs

get_audit_logs(limit, offset, action, resource)

Get audit logs for the project.

logs = await client.get_audit_logs(limit=50, action="memory.create")
for log in logs:
    print(f"{log.action} on {log.resource} at {log.created_at}")

get_audit_log_stats()

Get audit log statistics.

stats = await client.get_audit_log_stats()
print(f"Total events: {stats.total}")
print(f"Action breakdown: {stats.action_breakdown}")

Batch Operations

create_memories_batch(inputs)

Create multiple memories at once.

memories = await client.create_memories_batch([
    {"content": "User likes TypeScript", "category": "preference"},
    {"content": "User works at Acme Corp", "category": "work"},
    {"content": "User prefers dark mode", "category": "preference"},
])

search_batch(queries, limit)

Search multiple queries at once.

results = await client.search_batch(
    ["What does the user do for work?", "What are their preferences?"],
    limit=5,
)
work_results, pref_results = results

Error Handling

The SDK raises TotalRecallError with descriptive messages. Client errors (4xx) are raised immediately, while server errors (5xx) are retried with exponential backoff.

from totalrecall import TotalRecall
from totalrecall.client import TotalRecallError

try:
    memory = await client.get_memory("nonexistent")
except TotalRecallError as e:
    print(f"Error ({e.status_code}): {e}")
    # Error (404): Memory not found

Type Hints

The SDK is fully typed with dataclasses and type hints for excellent IDE support.

from totalrecall import TotalRecall, Memory, SearchResult

client: TotalRecall = TotalRecall(
    api_key="tr_...",
    project_id="my-project",
)

results: list[SearchResult] = await client.search_memories(query="test")

License

MIT © 2026 TotalRecall

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

totalrecall_sdk-0.1.2.tar.gz (23.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

totalrecall_sdk-0.1.2-py3-none-any.whl (20.5 kB view details)

Uploaded Python 3

File details

Details for the file totalrecall_sdk-0.1.2.tar.gz.

File metadata

  • Download URL: totalrecall_sdk-0.1.2.tar.gz
  • Upload date:
  • Size: 23.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.3

File hashes

Hashes for totalrecall_sdk-0.1.2.tar.gz
Algorithm Hash digest
SHA256 c69ea04fe65f39668d020a7bfd702e2cc9316dceca370e60f4ce23ec4301425d
MD5 5c95b21b860e68e129f5466e4cba9e22
BLAKE2b-256 4d82bf64129aaccc57b25df5b91a8f6a2dbc7ef82bdba45d28295a990ba87510

See more details on using hashes here.

File details

Details for the file totalrecall_sdk-0.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for totalrecall_sdk-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 43412c76a881adba9fdc018185bb5e2abd3e639013ee65f74a769532e07b6c8b
MD5 a45352eb81a51c30c74ffa506e212260
BLAKE2b-256 1b6ff8e5f42cffad7043ab12233da280565bba65e117421c612e735c0b7a8c17

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page