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// TypeScriptnew RecallClient(options?: RecallClientOptions)interface RecallClientOptions {redisUrl?: string;mem0ApiKey?: string;environment?: string;cacheConfig?: CacheConfig;syncConfig?: SyncConfig;[key: string]: any;}
python# PythonRecallClient(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
| Parameter | Type | Default | Description |
|---|---|---|---|
redis_url | string | "redis://localhost:6379" | Redis connection URL |
mem0_api_key | string | None | Mem0 API key for cloud storage |
environment | string | "development" | Environment name (development, staging, production) |
cache_config | CacheConfig | None | Cache configuration options |
sync_config | SyncConfig | None | Synchronization configuration |
Example
pythonfrom recall import RecallClient# Basic initializationclient = RecallClient(redis_url="redis://localhost:6379",mem0_api_key="m0-xxxxxxxxxxxx")# With configurationclient = RecallClient(redis_url="redis://localhost:6379",mem0_api_key="m0-xxxxxxxxxxxx",environment="production",cache_config=CacheConfig(ttl=3600),sync_config=SyncConfig(mode="eager"))
typescriptimport { RecallClient } from "@recall/client";// Basic initializationconst client = new RecallClient({redisUrl: "redis://localhost:6379",mem0ApiKey: "m0-xxxxxxxxxxxx",});// With configurationconst 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.
pythonadd(content: str,user_id: str,priority: str = "medium",metadata: dict | None = None,async_mode: bool = False) -> dict
typescriptadd(options: AddMemoryOptions): Promise<Memory>interface AddMemoryOptions {content: string;userId: string;priority?: Priority;metadata?: Record<string, any>;asyncMode?: boolean;}
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
content | string | Yes | The memory content to store |
user_id | string | Yes | User identifier |
priority | string | No | Priority level: "critical", "high", "medium", "low" |
metadata | object | No | Additional metadata |
async_mode | boolean | No | If true, returns immediately without waiting for cloud sync |
Returns
A dictionary/object containing:
id: Unique memory identifiercontent: The stored contentuser_id: Associated user IDpriority: Assigned priority levelcreated_at: Creation timestampmetadata: Any additional metadata
Example
pythonmemory = 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
typescriptconst 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.
pythonsearch(query: str,user_id: str | None = None,limit: int = 10,filters: dict | None = None,threshold: float = 0.0) -> list[dict]
typescriptsearch(options: SearchOptions): Promise<Memory[]>interface SearchOptions {query: string;userId?: string;limit?: number;filters?: Record<string, any>;threshold?: number;}
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
query | string | Yes | Search query |
user_id | string | No | Filter by user ID |
limit | integer | No | Maximum results to return (default: 10) |
filters | object | No | Metadata filters |
threshold | float | No | Minimum 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
pythonresults = 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})")
typescriptconst 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.
pythonget(memory_id: str) -> dict | None
typescriptget(memoryId: string): Promise<Memory | null>
Example
pythonmemory = client.get("mem_abc123xyz")if memory:print(f"Content: {memory['content']}")else:print("Memory not found")
typescriptconst memory = await client.get("mem_abc123xyz");if (memory) {console.log(`Content: ${memory.content}`);} else {console.log("Memory not found");}
update()
Update an existing memory.
pythonupdate(memory_id: str,content: str | None = None,priority: str | None = None,metadata: dict | None = None) -> dict
typescriptupdate(options: UpdateOptions): Promise<Memory>interface UpdateOptions {memoryId: string;content?: string;priority?: Priority;metadata?: Record<string, any>;}
Example
pythonupdated = client.update(memory_id="mem_abc123xyz",priority="critical",metadata={"last_accessed": datetime.now().isoformat()})
typescriptconst updated = await client.update({memoryId: "mem_abc123xyz",priority: "critical",metadata: { lastAccessed: new Date().toISOString() },});
delete()
Delete a memory from both cache and cloud storage.
pythondelete(memory_id: str) -> bool
typescriptdelete(memoryId: string): Promise<boolean>
Example
pythonsuccess = client.delete("mem_abc123xyz")print(f"Deleted: {success}")
typescriptconst success = await client.delete("mem_abc123xyz");console.log(`Deleted: ${success}`);
get_all()
Retrieve all memories for a user.
pythonget_all(user_id: str,limit: int | None = None,offset: int = 0) -> list[dict]
typescriptgetAll(options: GetAllOptions): Promise<Memory[]>interface GetAllOptions {userId: string;limit?: number;offset?: number;}
Example
pythonmemories = client.get_all(user_id="user_123",limit=100,offset=0)print(f"Total memories: {len(memories)}")
typescriptconst 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.
pythonadd_batch(memories: list[dict]) -> list[dict]
typescriptaddBatch(memories: AddMemoryOptions[]): Promise<Memory[]>
Example
pythonmemories = [{"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")
typescriptconst 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.
pythondelete_batch(memory_ids: list[str]) -> dict
typescriptdeleteBatch(memoryIds: string[]): Promise<BatchDeleteResult>
Cache Management
cache_stats()
Get detailed cache statistics.
pythoncache_stats() -> dict
typescriptcacheStats(): 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}}
typescriptinterface 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.
pythonoptimize_cache(aggressive: bool = False) -> dict
typescriptoptimizeCache(options?: OptimizeOptions): Promise<OptimizeResult>
clear_cache()
Clear cache for specific user or entirely.
pythonclear_cache(user_id: str | None = None) -> bool
typescriptclearCache(userId?: string): Promise<boolean>
Synchronization
sync()
Manually trigger synchronization between cache and cloud.
pythonsync(direction: str = "bidirectional",force: bool = False) -> dict
typescriptsync(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.
pythonhealth_check() -> dict
typescripthealthCheck(): 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"}
typescriptinterface HealthStatus {status: "healthy" | "degraded" | "unhealthy";timestamp: string;components: {redis: ComponentHealth;mem0: ComponentHealth;cache: ComponentHealth;};version: string;}
Configuration Classes
CacheConfig
pythonclass CacheConfig:ttl: int | dict[str, int | None] = 3600max_memory: str = "512mb"eviction_policy: str = "allkeys-lru"compression: bool = Falsewarm_cache: bool = True
typescriptinterface CacheConfig {ttl?: number | Record<Priority, number | null>;maxMemory?: string;evictionPolicy?: string;compression?: boolean;warmCache?: boolean;}
SyncConfig
pythonclass SyncConfig:mode: str = "lazy" # lazy, eager, manualbatch_size: int = 100interval: int = 60retry_policy: str = "exponential"max_retries: int = 3
typescriptinterface SyncConfig {mode?: "lazy" | "eager" | "manual";batchSize?: number;interval?: number;retryPolicy?: string;maxRetries?: number;}
Error Handling
Exception Types
pythonfrom recall.exceptions import (RecallError, # Base exceptionConnectionError, # Redis/Mem0 connection issuesAuthenticationError, # Invalid API keyValidationError, # Invalid parametersCacheError, # Cache-specific errorsSyncError, # Synchronization errorsRateLimitError # 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}")
typescriptimport {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)
pythonfrom recall import AsyncRecallClientimport asyncioasync def main():client = AsyncRecallClient(redis_url="redis://localhost:6379",mem0_api_key="your-api-key")# Async methodsmemory = await client.add(content="Async memory",user_id="user_123")results = await client.search(query="async operations",user_id="user_123")# Concurrent operationstasks = [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
- Explore advanced features
- Learn about webhooks and events
- Review best practices
- Check SDK references for language-specific details