Skip to main content
{
  "session_id": "sess_abc123xyz",
  "status": "pending",
  "created_at": "2024-01-15T10:30:00Z",
  "metadata": {
    "channel": "web_chat",
    "language": "en",
    "context": "customer_support"
  },
  "auto_process_after_seconds": 1800
}

Overview

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.

Session Object

session_id
string
required
Unique identifier for the session.
status
string
required
Current status of the session: pending, processing, or processed.
created_at
timestamp
ISO 8601 timestamp of when the session was created.
metadata
object
Custom metadata object for storing additional information about the session.
auto_process_after_seconds
integer
Seconds of inactivity before the session is automatically processed (minimum 600).

Session Lifecycle

Sessions follow a specific lifecycle:
  1. pending - Session is active, messages can be added
  2. processing - Session is being analyzed to extract memories
  3. processed - Session analysis complete, memories extracted

Creating a Session

Create a new session for a user to start tracking a conversation.
from recallrai import RecallrAI

client = RecallrAI(
    api_key="rai_your_api_key",
    project_id="your_project_id"
)

user = client.get_user("alice_123")

# Create a session with defaults
session = user.create_session()

# Create with custom auto-process time and metadata
session = user.create_session(
    auto_process_after_seconds=1800,  # 30 minutes
    metadata={
        "channel": "web_chat",
        "language": "en",
        "context": "customer_support"
    }
)

print(f"Session ID: {session.session_id}")
print(f"Status: {session.status}")
auto_process_after_seconds
integer
default:"600"
Seconds of inactivity before automatically processing the session (minimum 600 = 10 minutes).
metadata
object
default:"{}"
Custom metadata to associate with the session.
{
  "session_id": "sess_abc123xyz",
  "status": "pending",
  "created_at": "2024-01-15T10:30:00Z",
  "metadata": {
    "channel": "web_chat",
    "language": "en",
    "context": "customer_support"
  },
  "auto_process_after_seconds": 1800
}

Retrieving a Session

Get an existing session by its ID.
user = client.get_user("alice_123")
session = user.get_session("sess_abc123xyz")

print(f"Session: {session.session_id}")
print(f"Status: {session.status}")
print(f"Created: {session.created_at}")

Listing Sessions

List all sessions for a user with pagination and filtering.
# List with defaults
sessions = user.list_sessions()

print(f"Total sessions: {sessions.total}")
for session in sessions.sessions:
    print(f"- {session.session_id} ({session.status})")

# List with pagination
sessions = user.list_sessions(offset=0, limit=20)

# Filter by session metadata
sessions = user.list_sessions(
    metadata_filter={"channel": "web_chat"}
)

# Filter by user metadata
sessions = user.list_sessions(
    user_metadata_filter={"plan": "premium"}
)

# Pagination
if sessions.has_more():
    next_sessions = user.list_sessions(
        offset=sessions.next_offset(),
        limit=20
    )
offset
integer
default:"0"
Number of sessions to skip (for pagination).
limit
integer
default:"10"
Maximum number of sessions to return (1-100).
metadata_filter
object
Filter sessions by session metadata (exact match).
user_metadata_filter
object
Filter sessions by user metadata (exact match).

Adding Messages

Add messages to a session as the conversation progresses.
from recallrai import MessageRole

# Add user message
session.add_message(MessageRole.USER, "I love Italian food")

# Add assistant response
session.add_message(
    MessageRole.ASSISTANT,
    "That's great! I'll remember your preference for Italian cuisine."
)

# Continue the conversation
session.add_message(MessageRole.USER, "I'm also vegetarian")
session.add_message(
    MessageRole.ASSISTANT,
    "Noted! You're vegetarian and enjoy Italian food."
)
role
string
required
Role of the message sender: user or assistant.
message
string
required
Content of the message.
Messages can only be added to sessions in pending status. Attempting to add messages to a processed or processing session will raise an InvalidSessionStateError.

Getting Context

Retrieve relevant memories and context for personalizing AI responses.
from recallrai import RecallStrategy

# Get context with defaults
context = session.get_context()
print(context.context)

# Customize recall parameters
context = 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 prompt
prompt = f"""Context about the user:
{context.context}

User: What restaurant should I try tonight?
Assistant:"""

Context Parameters

recall_strategy
string
default:"balanced"
Strategy for retrieving memories:
  • recent - Prioritize recent memories
  • relevant - Prioritize semantic relevance
  • balanced - Balance recency and relevance
min_top_k
integer
default:"15"
Minimum number of memories to retrieve.
max_top_k
integer
default:"50"
Maximum number of memories to retrieve.
memories_threshold
float
default:"0.6"
Similarity threshold for memories (0.0-1.0). Higher values = more relevant matches required.
summaries_threshold
float
default:"0.5"
Similarity threshold for session summaries (0.0-1.0).
last_n_messages
integer
Number of recent messages to include in context (overrides thresholds).
last_n_summaries
integer
Number of recent summaries to include in context (overrides thresholds).
timezone
string
Timezone for formatting timestamps (e.g., ‘America/New_York’, ‘Europe/London’). Default: UTC.
{
  "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)

Processing a Session

Process a session to extract memories from the conversation.
# Process the session
session.process()

print(f"Session {session.session_id} is being processed")

# Check status
session.refresh()
print(f"Current status: {session.status}")
{
  "message": "Session processing started"
}
Processing is asynchronous. The session status changes from pendingprocessingprocessed. 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.

Retrieving Messages

Get all messages in a session with pagination.
# Get messages with defaults
messages = session.get_messages()

print(f"Total messages: {messages.total}")
for msg in messages.messages:
    print(f"[{msg.role}] {msg.message}")
    print(f"  Created: {msg.created_at}")

# Get with pagination
messages = session.get_messages(offset=0, limit=20)

# Pagination
if messages.has_more():
    next_messages = session.get_messages(
        offset=messages.next_offset(),
        limit=20
    )
offset
integer
default:"0"
Number of messages to skip (for pagination).
limit
integer
default:"50"
Maximum number of messages to return (1-100).
{
  "messages": [
    {
      "message_id": "msg_abc123",
      "role": "user",
      "message": "I love Italian food",
      "created_at": "2024-01-15T10:31:00Z"
    },
    {
      "message_id": "msg_def456",
      "role": "assistant",
      "message": "That's great! I'll remember your preference.",
      "created_at": "2024-01-15T10:31:05Z"
    }
  ],
  "total": 8,
  "offset": 0,
  "limit": 50
}

Updating Session Metadata

Update the metadata associated with a session.
# Update metadata
session.update(new_metadata={
    "channel": "mobile_app",
    "language": "es",
    "resolved": True
})

print(f"Updated metadata: {session.metadata}")
Metadata is completely replaced, not merged. Include all fields you want to keep.

Refreshing Session Data

Refresh a session object to get the latest data from the server.
# Refresh session
session.refresh()

print(f"Current status: {session.status}")
print(f"Metadata: {session.metadata}")
Use refresh() to check if an asynchronously processed session has completed: status changed from processing to processed.

Common Patterns

Complete Conversation Flow

from recallrai import RecallrAI, MessageRole

def 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

Session with Custom Recall

from recallrai import RecallStrategy

# For a technical support conversation
context = 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 conversation
context = session.get_context(
    recall_strategy=RecallStrategy.RECENT,  # Prioritize recent
    max_top_k=30,
    last_n_summaries=5  # Focus on recent sessions
)

Auto-Processing 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)

Error Handling

Raised when trying to access a session that doesn’t exist.
from recallrai.exceptions import SessionNotFoundError

try:
    session = user.get_session("nonexistent_session")
except SessionNotFoundError as e:
    print(f"Session not found: {e.message}")
Raised when trying to perform an invalid operation for the session’s current state.
from recallrai.exceptions import InvalidSessionStateError

try:
    # 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()

Best Practices

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.

Next Steps

I