Skip to main content

Overview

The Session class represents a conversation session. It provides methods for adding messages, retrieving context, and processing sessions to update user memories.

Properties

session_id
string
Unique identifier for the session.
user_id
string
ID of the user this session belongs to.
status
SessionStatus
Current session status: PENDING, PROCESSING, PROCESSED, or FAILED
metadata
dict
Session metadata as a dictionary.
created_at
datetime
UTC timestamp when the session was created.
processed_at
datetime | None
UTC timestamp when the session was processed, or None if not yet processed.
auto_process_after_seconds
integer | None
Seconds of inactivity before auto-processing, or None if disabled.

Session Management Methods

update()

Update the session metadata.
from recallrai.exceptions import SessionNotFoundError

try:
    user = client.get_user("user123")
    session = user.get_session("session-uuid")
    session.update(new_metadata={"type": "support_chat", "priority": "high"})
    print(f"Updated metadata: {session.metadata}")
except SessionNotFoundError as e:
    print(f"Error: {e}")
new_metadata
dict
required
New metadata to replace the existing metadata. Completely replaces the old metadata.
Returns: None (mutates the instance in place) Raises: UserNotFoundError, SessionNotFoundError

refresh()

Refresh the session instance with the latest data from the server.
session = user.get_session("session-uuid")
session.refresh()
print(f"Current status: {session.status}")
print(f"Processed at: {session.processed_at}")
Returns: None (updates the instance in place) Raises: UserNotFoundError, SessionNotFoundError

Message Methods

add_message()

Add a message to the session.
from recallrai.models import MessageRole
from recallrai.exceptions import InvalidSessionStateError

try:
    session = user.get_session("session-uuid")
    
    # Add a user message
    session.add_message(
        role=MessageRole.USER,
        content="Hello! How are you?"
    )
    
    # Add an assistant message
    session.add_message(
        role=MessageRole.ASSISTANT,
        content="I'm doing well, thank you! How can I help you today?"
    )
    
except InvalidSessionStateError as e:
    print(f"Cannot add messages to a processed session: {e}")
role
MessageRole
required
Message role: MessageRole.USER or MessageRole.ASSISTANT
content
string
required
The message content text.
MessageRole.USER: Messages from the user/human
MessageRole.ASSISTANT: Messages from the AI assistant
Returns: None Raises: UserNotFoundError, SessionNotFoundError, InvalidSessionStateError
You cannot add messages to a session that has already been processed.

get_messages()

Retrieve messages from the session with pagination.
session = user.get_session("session-uuid")
messages = session.get_messages(offset=0, limit=50)

print(f"Total messages: {messages.total}")
print(f"Has more: {messages.has_more}")

for msg in messages.messages:
    print(f"{msg.role.value.upper()} (at {msg.timestamp}): {msg.content}")
offset
integer
Number of messages to skip. Default: 0
limit
integer
Maximum number of messages to return. Default: 50
Returns: MessageList object with:
  • messages: List of message objects with role, content, and timestamp fields
  • total: Total number of messages in the session
  • has_more: Boolean indicating if more messages are available
Raises: UserNotFoundError, SessionNotFoundError

Context Retrieval

get_context()

Retrieve contextual information for the session based on user memories and conversation history.
from recallrai.models import RecallStrategy

# Get context with default parameters
context = session.get_context()
print(f"Context: {context.context}")

# Get context with specific recall strategy
context = session.get_context(recall_strategy=RecallStrategy.LOW_LATENCY)

# Get context with custom parameters
context = session.get_context(
    recall_strategy=RecallStrategy.BALANCED,
    min_top_k=10,
    max_top_k=100,
    memories_threshold=0.6,
    summaries_threshold=0.5,
    last_n_messages=20,
    last_n_summaries=5,
    timezone="America/Los_Angeles",
    include_system_prompt=True
)
recall_strategy
RecallStrategy
Strategy for memory retrieval:
  • LOW_LATENCY: Fast retrieval with basic relevance
  • BALANCED: Good balance of speed and quality (default)
  • DEEP: More thorough but slower memory search
min_top_k
integer
Minimum number of memories to return. Range: 5-50. Default: 15
max_top_k
integer
Maximum number of memories to return. Range: 10-100. Default: 50
memories_threshold
float
Similarity threshold for memories. Range: 0.2-0.8. Default: 0.6
summaries_threshold
float
Similarity threshold for summaries. Range: 0.2-0.8. Default: 0.5
last_n_messages
integer
Number of last messages to include in context. Range: 1-100. Optional.
last_n_summaries
integer
Number of last summaries to include in context. Range: 1-20. Optional.
timezone
string
Timezone for formatting timestamps (e.g., America/New_York). Use None for UTC. Optional.
include_system_prompt
boolean
Whether to include the default RecallrAI system prompt. Default: True
Returns: Context object with context field containing the formatted context string Raises: UserNotFoundError, SessionNotFoundError
Use the context string as part of your system prompt when calling your LLM. This provides the AI with relevant memories and conversation history.

Processing

process()

Process the session to update user memories.
from recallrai.exceptions import InvalidSessionStateError

try:
    session = user.get_session("session-uuid")
    session.process()
    print("Session processing started")
    
    # Check status later
    session.refresh()
    print(f"Status: {session.status}")
    
except InvalidSessionStateError as e:
    print(f"Cannot process session: {e}")
Processing extracts memories from the conversation and updates the user’s memory store. This is an asynchronous operation - the session status will change to PROCESSING and then PROCESSED when complete.
Returns: None Raises: UserNotFoundError, SessionNotFoundError, InvalidSessionStateError
You can only process a session once. After processing, you cannot add more messages to the session.

Usage Example with LLM

Here’s how to use sessions with an LLM like OpenAI:
import openai
from recallrai import RecallrAI
from recallrai.models import MessageRole

# Initialize clients
rai_client = RecallrAI(api_key="rai_yourapikey", project_id="project-uuid")
oai_client = openai.OpenAI(api_key="your-openai-api-key")

# Get user and create session
user = rai_client.get_user("user123")
session = user.create_session(auto_process_after_seconds=1800)

# Get user input
user_message = input("You: ")

# Add to RecallrAI
session.add_message(role=MessageRole.USER, content=user_message)

# Get context from RecallrAI
context = session.get_context()

# Create system prompt with context
system_prompt = "You are a helpful assistant" + context.context

# Get conversation history
messages = session.get_messages(limit=50)
previous_messages = [
    {"role": msg.role, "content": msg.content}
    for msg in messages.messages
]

# Call LLM
response = oai_client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": system_prompt},
        *previous_messages,
    ]
)

assistant_message = response.choices[0].message.content
print(f"Assistant: {assistant_message}")

# Add assistant response to RecallrAI
session.add_message(role=MessageRole.ASSISTANT, content=assistant_message)

# Process session when conversation ends
session.process()

Async Session

For async applications, use AsyncSession:
from recallrai import AsyncRecallrAI
from recallrai.models import MessageRole

client = AsyncRecallrAI(api_key="rai_yourapikey", project_id="project-uuid")
user = await client.get_user("user123")
session = await user.create_session()

# All methods are the same, just use await
await session.add_message(role=MessageRole.USER, content="Hello")
context = await session.get_context()
messages = await session.get_messages(limit=10)
await session.process()