Custom Integration Guide
Learn how to build custom integrations with the Memory Scope API for your specific use case. This guide covers patterns, best practices, and common integration scenarios.
Integration Architecture
A typical integration follows this pattern:
- Read user memories with appropriate scopes and purposes
- Incorporate memories into your application context
- Use the context to personalize user experience
- Store new information from user interactions
- Handle policy denials gracefully
- Provide user control through revocation
Basic Integration Pattern
Here's a basic pattern for integrating the Memory Scope API into any application:
Basic Integration Pattern
from memory_scope import MemoryScopeClient
from memory_scope.exceptions import PolicyDeniedError
class MyApplication:
def __init__(self, memory_api_key: str):
self.memory_client = MemoryScopeClient(api_key=memory_api_key)
def get_user_context(self, user_id: str, purpose: str) -> dict:
"""Get user context from multiple scopes"""
context = {}
# Read preferences
try:
prefs = self.memory_client.read_memory(
user_id=user_id,
scope="preferences",
domain=None,
purpose=purpose
)
context["preferences"] = prefs.summary_struct
except PolicyDeniedError:
context["preferences"] = None
# Read constraints
try:
constraints = self.memory_client.read_memory(
user_id=user_id,
scope="constraints",
domain=None,
purpose=purpose
)
context["constraints"] = constraints.summary_struct
except PolicyDeniedError:
context["constraints"] = None
return context
def personalize_experience(self, user_id: str, action: str):
"""Use memories to personalize user experience"""
context = self.get_user_context(
user_id=user_id,
purpose=f"personalize {action} experience"
)
# Use context in your application logic
if context["preferences"]:
# Apply preferences
apply_preferences(context["preferences"])
if context["constraints"]:
# Respect constraints
apply_constraints(context["constraints"])
def store_user_feedback(self, user_id: str, feedback: dict):
"""Store user feedback as memories"""
if "preferences" in feedback:
self.memory_client.create_memory(
user_id=user_id,
scope="preferences",
domain=feedback.get("domain"),
source="user_feedback",
value_json=feedback["preferences"]
)Common Integration Scenarios
1. Recommendation Systems
Use preferences and constraints to filter and rank recommendations:
Recommendation System
def get_recommendations(user_id: str, items: list) -> list:
# Read preferences and constraints
prefs = memory_client.read_memory(
user_id=user_id,
scope="preferences",
domain="products",
purpose="generate product recommendations"
)
constraints = memory_client.read_memory(
user_id=user_id,
scope="constraints",
domain="budget",
purpose="filter recommendations by budget"
)
# Filter and score items
filtered = [
item for item in items
if item not in prefs.summary_struct.get("dislikes", [])
and meets_constraints(item, constraints.summary_struct)
]
# Score by preferences
scored = sorted(
filtered,
key=lambda x: score_item(x, prefs.summary_struct),
reverse=True
)
return scored[:10]2. Content Personalization
Personalize content based on user communication preferences:
Content Personalization
def personalize_content(user_id: str, content: str) -> str:
# Read communication preferences
comm = memory_client.read_memory(
user_id=user_id,
scope="communication",
domain=None,
purpose="personalize content display"
)
# Apply preferences
style = comm.summary_struct
if style.get("preferred_tone") == "casual":
content = make_casual(content)
if style.get("use_emojis"):
content = add_emojis(content)
return content3. Form Pre-filling
Pre-fill forms with stored user information:
Form Pre-filling
def get_form_data(user_id: str) -> dict:
# Read facts
facts = memory_client.read_memory(
user_id=user_id,
scope="facts",
domain="personal",
purpose="pre-fill user form"
)
return facts.summary_structError Handling Pattern
Always handle errors gracefully, especially policy denials:
Error Handling
from memory_scope.exceptions import (
PolicyDeniedError,
InvalidRequestError,
RateLimitError
)
def safe_read_memory(user_id: str, scope: str, purpose: str, default=None):
"""Safely read memory with fallback"""
try:
result = memory_client.read_memory(
user_id=user_id,
scope=scope,
domain=None,
purpose=purpose
)
return result.summary_struct
except PolicyDeniedError:
# Expected - use default
return default
except RateLimitError:
# Retry logic here
raise
except Exception as e:
# Log and use default
logger.error(f"Error reading memory: {e}")
return defaultBest Practices
- Use appropriate scopes for different types of data
- Write clear, descriptive purpose strings
- Handle PolicyDeniedError gracefully - it's not an error
- Store revocation tokens securely and associate with user sessions
- Cache memory reads when appropriate to reduce API calls
- Provide users with UI to revoke access to their data
- Use domains to organize memories within scopes
- Respect user constraints in all operations
- Store new information from user interactions
- Monitor API usage and implement rate limit handling
Integration Checklist
- Initialize MemoryScopeClient with API key
- Implement error handling for all memory operations
- Handle PolicyDeniedError with fallback behavior
- Store and manage revocation tokens
- Provide user revocation UI
- Use appropriate scopes and purposes
- Cache responses when appropriate
- Monitor API usage and rate limits