Client API Reference

Complete reference for the RecallClient class and all available methods.

RecallClient

The main client class for interacting with Recall's hybrid memory system.

Constructor

typescript
// TypeScript
new RecallClient(options?: RecallClientOptions)
interface RecallClientOptions {
redisUrl?: string;
mem0ApiKey?: string;
environment?: string;
cacheConfig?: CacheConfig;
syncConfig?: SyncConfig;
[key: string]: any;
}
python
# Python
RecallClient(
redis_url: str | None = None,
mem0_api_key: str | None = None,
environment: str = "development",
cache_config: CacheConfig | None = None,
sync_config: SyncConfig | None = None,
**kwargs
)

Parameters

ParameterTypeDefaultDescription
redis_urlstring"redis://localhost:6379"Redis connection URL
mem0_api_keystringNoneMem0 API key for cloud storage
environmentstring"development"Environment name (development, staging, production)
cache_configCacheConfigNoneCache configuration options
sync_configSyncConfigNoneSynchronization configuration

Example

python
from recall import RecallClient
# Basic initialization
client = RecallClient(
redis_url="redis://localhost:6379",
mem0_api_key="m0-xxxxxxxxxxxx"
)
# With configuration
client = RecallClient(
redis_url="redis://localhost:6379",
mem0_api_key="m0-xxxxxxxxxxxx",
environment="production",
cache_config=CacheConfig(ttl=3600),
sync_config=SyncConfig(mode="eager")
)
typescript
import { RecallClient } from "@recall/client";
// Basic initialization
const client = new RecallClient({
redisUrl: "redis://localhost:6379",
mem0ApiKey: "m0-xxxxxxxxxxxx",
});
// With configuration
const client = new RecallClient({
redisUrl: "redis://localhost:6379",
mem0ApiKey: "m0-xxxxxxxxxxxx",
environment: "production",
cacheConfig: { ttl: 3600 },
syncConfig: { mode: "eager" },
});

Core Methods

add()

Add a new memory to the system.

python
add(
content: str,
user_id: str,
priority: str = "medium",
metadata: dict | None = None,
async_mode: bool = False
) -> dict
typescript
add(options: AddMemoryOptions): Promise<Memory>
interface AddMemoryOptions {
content: string;
userId: string;
priority?: Priority;
metadata?: Record<string, any>;
asyncMode?: boolean;
}

Parameters

ParameterTypeRequiredDescription
contentstringYesThe memory content to store
user_idstringYesUser identifier
prioritystringNoPriority level: "critical", "high", "medium", "low"
metadataobjectNoAdditional metadata
async_modebooleanNoIf true, returns immediately without waiting for cloud sync

Returns

A dictionary/object containing:

  • id: Unique memory identifier
  • content: The stored content
  • user_id: Associated user ID
  • priority: Assigned priority level
  • created_at: Creation timestamp
  • metadata: Any additional metadata

Example

python
memory = client.add(
content="User prefers dark theme",
user_id="user_123",
priority="high",
metadata={
"category": "preferences",
"source": "settings_update"
}
)
print(f"Memory ID: {memory['id']}")
# Output: Memory ID: mem_abc123xyz
typescript
const memory = await client.add({
content: "User prefers dark theme",
userId: "user_123",
priority: "high",
metadata: {
category: "preferences",
source: "settings_update",
},
});
console.log(`Memory ID: ${memory.id}`);
// Output: Memory ID: mem_abc123xyz

search()

Search for relevant memories using semantic search.

python
search(
query: str,
user_id: str | None = None,
limit: int = 10,
filters: dict | None = None,
threshold: float = 0.0
) -> list[dict]
typescript
search(options: SearchOptions): Promise<Memory[]>
interface SearchOptions {
query: string;
userId?: string;
limit?: number;
filters?: Record<string, any>;
threshold?: number;
}

Parameters

ParameterTypeRequiredDescription
querystringYesSearch query
user_idstringNoFilter by user ID
limitintegerNoMaximum results to return (default: 10)
filtersobjectNoMetadata filters
thresholdfloatNoMinimum relevance score (0.0 to 1.0)

Returns

Array of memory objects, each containing:

  • All memory fields
  • score: Relevance score (0.0 to 1.0)
  • source: Whether from "cache" or "cloud"

Example

python
results = client.search(
query="user preferences for UI",
user_id="user_123",
limit=5,
filters={"category": "preferences"},
threshold=0.7
)
for memory in results:
print(f"{memory['content']} (score: {memory['score']:.2f})")
typescript
const results = await client.search({
query: "user preferences for UI",
userId: "user_123",
limit: 5,
filters: { category: "preferences" },
threshold: 0.7,
});
results.forEach((memory) => {
console.log(`${memory.content} (score: ${memory.score.toFixed(2)})`);
});

get()

Retrieve a specific memory by ID.

python
get(memory_id: str) -> dict | None
typescript
get(memoryId: string): Promise<Memory | null>

Example

python
memory = client.get("mem_abc123xyz")
if memory:
print(f"Content: {memory['content']}")
else:
print("Memory not found")
typescript
const memory = await client.get("mem_abc123xyz");
if (memory) {
console.log(`Content: ${memory.content}`);
} else {
console.log("Memory not found");
}

update()

Update an existing memory.

python
update(
memory_id: str,
content: str | None = None,
priority: str | None = None,
metadata: dict | None = None
) -> dict
typescript
update(options: UpdateOptions): Promise<Memory>
interface UpdateOptions {
memoryId: string;
content?: string;
priority?: Priority;
metadata?: Record<string, any>;
}

Example

python
updated = client.update(
memory_id="mem_abc123xyz",
priority="critical",
metadata={"last_accessed": datetime.now().isoformat()}
)
typescript
const updated = await client.update({
memoryId: "mem_abc123xyz",
priority: "critical",
metadata: { lastAccessed: new Date().toISOString() },
});

delete()

Delete a memory from both cache and cloud storage.

python
delete(memory_id: str) -> bool
typescript
delete(memoryId: string): Promise<boolean>

Example

python
success = client.delete("mem_abc123xyz")
print(f"Deleted: {success}")
typescript
const success = await client.delete("mem_abc123xyz");
console.log(`Deleted: ${success}`);

get_all()

Retrieve all memories for a user.

python
get_all(
user_id: str,
limit: int | None = None,
offset: int = 0
) -> list[dict]
typescript
getAll(options: GetAllOptions): Promise<Memory[]>
interface GetAllOptions {
userId: string;
limit?: number;
offset?: number;
}

Example

python
memories = client.get_all(
user_id="user_123",
limit=100,
offset=0
)
print(f"Total memories: {len(memories)}")
typescript
const memories = await client.getAll({
userId: "user_123",
limit: 100,
offset: 0,
});
console.log(`Total memories: ${memories.length}`);

Batch Operations

add_batch()

Add multiple memories in a single operation.

python
add_batch(memories: list[dict]) -> list[dict]
typescript
addBatch(memories: AddMemoryOptions[]): Promise<Memory[]>

Example

python
memories = [
{
"content": "Prefers email notifications",
"user_id": "user_123",
"priority": "high"
},
{
"content": "Works in tech industry",
"user_id": "user_123",
"priority": "medium"
}
]
results = client.add_batch(memories)
print(f"Added {len(results)} memories")
typescript
const memories = [
{
content: "Prefers email notifications",
userId: "user_123",
priority: "high",
},
{
content: "Works in tech industry",
userId: "user_123",
priority: "medium",
},
];
const results = await client.addBatch(memories);
console.log(`Added ${results.length} memories`);

delete_batch()

Delete multiple memories by ID.

python
delete_batch(memory_ids: list[str]) -> dict
typescript
deleteBatch(memoryIds: string[]): Promise<BatchDeleteResult>

Cache Management

cache_stats()

Get detailed cache statistics.

python
cache_stats() -> dict
typescript
cacheStats(): Promise<CacheStats>

Returns

python
{
"size": 1234, # Number of cached items
"memory_usage": "45.6MB", # Memory used
"hit_rate": 0.92, # Cache hit rate
"miss_rate": 0.08, # Cache miss rate
"evictions": 156, # Number of evictions
"avg_ttl": 3600, # Average TTL in seconds
"by_priority": {
"critical": 10,
"high": 234,
"medium": 567,
"low": 423
}
}
typescript
interface CacheStats {
size: number;
memoryUsage: string;
hitRate: number;
missRate: number;
evictions: number;
avgTtl: number;
byPriority: {
critical: number;
high: number;
medium: number;
low: number;
};
}

optimize_cache()

Optimize cache by removing stale entries and reorganizing based on access patterns.

python
optimize_cache(
aggressive: bool = False
) -> dict
typescript
optimizeCache(options?: OptimizeOptions): Promise<OptimizeResult>

clear_cache()

Clear cache for specific user or entirely.

python
clear_cache(user_id: str | None = None) -> bool
typescript
clearCache(userId?: string): Promise<boolean>

Synchronization

sync()

Manually trigger synchronization between cache and cloud.

python
sync(
direction: str = "bidirectional",
force: bool = False
) -> dict
typescript
sync(options?: SyncOptions): Promise<SyncResult>
interface SyncOptions {
direction?: "bidirectional" | "to_cloud" | "from_cloud";
force?: boolean;
}

Health & Monitoring

health_check()

Check the health status of all components.

python
health_check() -> dict
typescript
healthCheck(): Promise<HealthStatus>

Returns

python
{
"status": "healthy",
"timestamp": "2024-01-15T10:30:00Z",
"components": {
"redis": {
"status": "healthy",
"latency_ms": 1.2,
"version": "7.0.5"
},
"mem0": {
"status": "healthy",
"latency_ms": 45.3,
"quota_used": 0.23
},
"cache": {
"status": "healthy",
"size": 1234,
"memory_usage": "45.6MB"
}
},
"version": "1.0.0"
}
typescript
interface HealthStatus {
status: "healthy" | "degraded" | "unhealthy";
timestamp: string;
components: {
redis: ComponentHealth;
mem0: ComponentHealth;
cache: ComponentHealth;
};
version: string;
}

Configuration Classes

CacheConfig

python
class CacheConfig:
ttl: int | dict[str, int | None] = 3600
max_memory: str = "512mb"
eviction_policy: str = "allkeys-lru"
compression: bool = False
warm_cache: bool = True
typescript
interface CacheConfig {
ttl?: number | Record<Priority, number | null>;
maxMemory?: string;
evictionPolicy?: string;
compression?: boolean;
warmCache?: boolean;
}

SyncConfig

python
class SyncConfig:
mode: str = "lazy" # lazy, eager, manual
batch_size: int = 100
interval: int = 60
retry_policy: str = "exponential"
max_retries: int = 3
typescript
interface SyncConfig {
mode?: "lazy" | "eager" | "manual";
batchSize?: number;
interval?: number;
retryPolicy?: string;
maxRetries?: number;
}

Error Handling

Exception Types

python
from recall.exceptions import (
RecallError, # Base exception
ConnectionError, # Redis/Mem0 connection issues
AuthenticationError, # Invalid API key
ValidationError, # Invalid parameters
CacheError, # Cache-specific errors
SyncError, # Synchronization errors
RateLimitError # API rate limiting
)
try:
client.add(content="", user_id="")
except ValidationError as e:
print(f"Invalid input: {e}")
except RecallError as e:
print(f"Recall error: {e}")
typescript
import {
RecallError,
ConnectionError,
AuthenticationError,
ValidationError,
CacheError,
SyncError,
RateLimitError,
} from "@recall/client";
try {
await client.add({ content: "", userId: "" });
} catch (error) {
if (error instanceof ValidationError) {
console.log(`Invalid input: ${error.message}`);
} else if (error instanceof RecallError) {
console.log(`Recall error: ${error.message}`);
}
}

Async Support

Async Client (Python)

python
from recall import AsyncRecallClient
import asyncio
async def main():
client = AsyncRecallClient(
redis_url="redis://localhost:6379",
mem0_api_key="your-api-key"
)
# Async methods
memory = await client.add(
content="Async memory",
user_id="user_123"
)
results = await client.search(
query="async operations",
user_id="user_123"
)
# Concurrent operations
tasks = [
client.add(content=f"Memory {i}", user_id="user_123")
for i in range(10)
]
memories = await asyncio.gather(*tasks)
asyncio.run(main())

Next Steps