Sessions represent individual conversations or interactions with a user. Each session contains a sequence of messages and can be processed to extract memories. Sessions maintain state (pending, processing, processed) and support retrieving relevant context for personalization.
Add messages to a session as the conversation progresses.
Copy
from recallrai import MessageRole# Add user messagesession.add_message(MessageRole.USER, "I love Italian food")# Add assistant responsesession.add_message( MessageRole.ASSISTANT, "That's great! I'll remember your preference for Italian cuisine.")# Continue the conversationsession.add_message(MessageRole.USER, "I'm also vegetarian")session.add_message( MessageRole.ASSISTANT, "Noted! You're vegetarian and enjoy Italian food.")
Messages can only be added to sessions in pending status. Attempting to add messages to a processed or processing session will raise an InvalidSessionStateError.
Retrieve relevant memories and context for personalizing AI responses.
Copy
from recallrai import RecallStrategy# Get context with defaultscontext = session.get_context()print(context.context)# Customize recall parameterscontext = session.get_context( recall_strategy=RecallStrategy.RECENT, min_top_k=10, max_top_k=30, memories_threshold=0.7, summaries_threshold=0.6, last_n_messages=5, last_n_summaries=3, timezone="America/New_York")# Use context in your LLM promptprompt = f"""Context about the user:{context.context}User: What restaurant should I try tonight?Assistant:"""
Timezone for formatting timestamps (e.g., ‘America/New_York’, ‘Europe/London’). Default: UTC.
Copy
{ "context": "User preferences and background:\n- Loves Italian cuisine\n- Vegetarian diet\n- Lives in New York\n- Premium plan subscriber since Jan 2024\n\nRecent conversations:\n- Last week: Asked about pasta recipes\n- Yesterday: Inquired about local farmers markets"}
Recall Strategies:
Use recent for time-sensitive contexts (e.g., ongoing support tickets)
Use relevant for knowledge-based queries (e.g., technical troubleshooting)
Use balanced for general conversational AI (default, recommended)
Process a session to extract memories from the conversation.
Copy
# Process the sessionsession.process()print(f"Session {session.session_id} is being processed")# Check statussession.refresh()print(f"Current status: {session.status}")
Copy
{ "message": "Session processing started"}
Processing is asynchronous. The session status changes from pending → processing → processed. Use refresh() to check the current status.
Sessions can only be processed when in pending status. Attempting to process an already processed or processing session will raise an InvalidSessionStateError.
from recallrai import RecallrAI, MessageRoledef handle_conversation(user_id: str, messages: list): """Complete flow: create session, add messages, process, get context""" client = RecallrAI(api_key="...", project_id="...") # Get or create user try: user = client.get_user(user_id) except: user = client.create_user(user_id) # Create session session = user.create_session() # Add all messages for msg in messages: session.add_message(msg["role"], msg["content"]) # Process to extract memories session.process() # Wait for processing (in production, use webhooks or polling) import time time.sleep(5) session.refresh() if session.status == "processed": # Get context for next conversation new_session = user.create_session() context = new_session.get_context() return context.context return None
from recallrai import RecallStrategy# For a technical support conversationcontext = session.get_context( recall_strategy=RecallStrategy.RELEVANT, # Prioritize relevant info max_top_k=100, # Get more context memories_threshold=0.5, # Lower threshold for broader matches last_n_messages=10 # Include recent conversation)# For a time-sensitive conversationcontext = session.get_context( recall_strategy=RecallStrategy.RECENT, # Prioritize recent max_top_k=30, last_n_summaries=5 # Focus on recent sessions)
# Short conversation (auto-process after 10 minutes of inactivity)session = user.create_session(auto_process_after_seconds=600)# Long conversation (auto-process after 1 hour)session = user.create_session(auto_process_after_seconds=3600)# Support ticket (auto-process after 4 hours)session = user.create_session(auto_process_after_seconds=14400)
Raised when trying to access a session that doesn’t exist.
Copy
from recallrai.exceptions import SessionNotFoundErrortry: session = user.get_session("nonexistent_session")except SessionNotFoundError as e: print(f"Session not found: {e.message}")
InvalidSessionStateError (400)
Raised when trying to perform an invalid operation for the session’s current state.
Copy
from recallrai.exceptions import InvalidSessionStateErrortry: # Try to add message to processed session session.add_message(MessageRole.USER, "Hello")except InvalidSessionStateError as e: print(f"Invalid operation: {e.message}") # Create a new session instead new_session = user.create_session()
Use auto-processing wisely: Set auto_process_after_seconds based on your conversation patterns. Shorter times for quick chats, longer for support sessions.
Get context early: Retrieve context at the start of each conversation to personalize responses from the first message.
Process regularly: Process sessions promptly after conversations end to keep memories fresh and accurate.
Don’t retrieve context unnecessarily: Context retrieval uses API calls. Cache context when appropriate within a single conversation.
Monitor session status: Always check session status before operations like adding messages or processing.