Overview
The sessions resource provides complete lifecycle management for CLI sessions. Sessions organize memories into trackable contexts with states (active, paused, completed) and automatic memory counting.
Sessions were added in SDK v1.5.0. Ensure you're using the latest version to access this functionality. Both sync and async clients are supported.
Create Session
from trix import Trix, SessionType, RetentionPolicy
client = Trix.from_env()
session = client.sessions.create(
name="Customer Support Chat",
type=SessionType.CONVERSATION
)
print(f"Created session: {session.id}")
print(f"Status: {session.status}")
project = client.sessions.create(
name="Q4 Feature Development",
type=SessionType.PROJECT,
description="New analytics dashboard features",
tags=["q4", "analytics", "frontend"],
space_id="spc_abc123",
retention_policy=RetentionPolicy.PERMANENT,
is_private=False,
metadata={
"team": "engineering",
"priority": "high"
}
)
client.close()Async Support
from trix import AsyncTrix, SessionType
async def create_session():
async with AsyncTrix.from_env() as client:
session = await client.sessions.create(
name="Async Session",
type=SessionType.CONVERSATION
)
print(f"Created: {session.id}")
import asyncio
asyncio.run(create_session())Create Parameters
| Parameter | Type | Description |
|---|---|---|
name | str | Session name (required, max 200 chars) |
type | SessionType | CONVERSATION, PROJECT, TASK, or TEMPORARY |
description | str | Detailed description (max 1000 chars) |
tags | List[str] | Tags for organization (max 10 tags) |
space_id | str | Associate session with a space |
retention_policy | RetentionPolicy | PERMANENT, TEMPORARY, AUTO_DELETE, ON_COMPLETION |
retention_days | int | Days before auto-deletion |
is_private | bool | Private sessions visible only to creator |
metadata | Dict | Custom key-value metadata |
List and Filter Sessions
response = client.sessions.list()
print(f"Found {len(response.data)} sessions")
active_sessions = client.sessions.list(
status=SessionStatus.ACTIVE,
type=SessionType.PROJECT,
limit=20
)
found = client.sessions.list(
search="customer support",
tags=["q4", "frontend"]
)List Parameters
| Parameter | Type | Description |
|---|---|---|
status | SessionStatus | Filter by ACTIVE, PAUSED, COMPLETED, ARCHIVED |
type | SessionType | Filter by session type |
space_id | str | Filter by space |
tags | List[str] | Filter by tags |
search | str | Search name and description |
limit | int | Results per page (default: 20, max: 100) |
Get Session
session = client.sessions.get("sess_abc123")
print(session.name)
print(f"Status: {session.status}")
print(f"Memories: {session.memory_count}")
print(f"Messages: {session.message_count}")
print(f"Created: {session.created_at}")
print(f"Last active: {session.last_active_at}")Update Session
updated = client.sessions.update(
"sess_abc123",
description="Updated project description",
tags=["q4", "analytics", "frontend", "high-priority"],
metadata={
"status": "in-progress",
"assignee": "engineering-team"
}
)
print(f"Session updated: {updated.name}")Only provided fields are updated. Omitted fields remain unchanged.
Lifecycle Management
Manage session state transitions: active → paused → active → completed
Pause Session
paused = client.sessions.pause("sess_abc123")
print(paused.status)
print(paused.paused_at)Paused sessions cannot accept new memories. Pause sessions when taking a break to prevent accidental additions.
Resume Session
resumed = client.sessions.resume("sess_abc123")
print(resumed.status)
print(resumed.paused_at)Complete Session
completed = client.sessions.complete(
"sess_abc123",
summary="Successfully launched Q4 campaigns with 15% increase in engagement"
)
print(completed.status)
print(completed.completed_at)
print(completed.summary)
done = client.sessions.complete("sess_def456")Completed sessions are read-only. They cannot be reopened or modified.
Delete Session
client.sessions.delete("sess_abc123")
print("Session deleted")Deleting a session permanently removes it and all associated memories. Consider completing or archiving instead.
Get Active Sessions
response = client.sessions.get_active()
print(f"{len(response.data)} active sessions")
for session in response.data:
print(f"{session.name}: {session.memory_count} memories")Session Memories
response = client.sessions.get_memories("sess_abc123", limit=50)
print(f"Found {len(response.data)} memories")
for memory in response.data:
print(f"[{memory.created_at}] {memory.content}")Creating Memories in Sessions
client.memories.create(
content="Design system uses Material 3",
session_id="sess_abc123"
)
session = client.sessions.get("sess_abc123")
print(f"Memory count: {session.memory_count}")Complete Workflow Example
from trix import Trix, SessionType
def manage_project():
client = Trix.from_env()
session = client.sessions.create(
name="Mobile App Redesign",
type=SessionType.PROJECT,
description="Redesign iOS and Android apps",
tags=["mobile", "ui", "q1-2024"],
space_id="spc_engineering"
)
print(f"Created session: {session.id}")
client.memories.create(content="Design system uses Material 3", session_id=session.id)
client.memories.create(content="Target: iOS 15+ and Android 12+", session_id=session.id)
client.sessions.pause(session.id)
print("Session paused")
client.sessions.resume(session.id)
print("Session resumed")
client.memories.create(content="Added dark mode support", session_id=session.id)
completed = client.sessions.complete(
session.id,
summary="Successfully launched redesigned apps with 95% positive feedback"
)
print(f"Project completed with {completed.memory_count} memories")
client.close()
manage_project()Pydantic Models
from trix.types import (
Session,
SessionType,
SessionStatus,
RetentionPolicy,
CreateSessionParams,
UpdateSessionParams,
CompleteSessionParams,
SessionsResponse,
SessionStats
)
class SessionType(str, Enum):
CONVERSATION = "conversation"
PROJECT = "project"
TASK = "task"
TEMPORARY = "temporary"
class SessionStatus(str, Enum):
ACTIVE = "active"
PAUSED = "paused"
COMPLETED = "completed"
ARCHIVED = "archived"
class RetentionPolicy(str, Enum):
PERMANENT = "permanent"
TEMPORARY = "temporary"
AUTO_DELETE = "auto_delete"
ON_COMPLETION = "on_completion"
class Session(BaseModel):
id: str
account_id: str
user_id: str
created_by: str
name: str
description: Optional[str]
type: SessionType
status: SessionStatus
space_id: Optional[str]
origin_type: Optional[str]
tags: Optional[List[str]]
retention_policy: RetentionPolicy
retention_days: Optional[int]
summary: Optional[str]
is_private: bool
message_count: int
memory_count: int
metadata: Optional[Dict[str, Any]]
created_at: str
updated_at: str
last_active_at: str
paused_at: Optional[str]
completed_at: Optional[str]
archived_at: Optional[str]Error Handling
from trix import TrixError
try:
client.sessions.pause("sess_abc123")
except TrixError as error:
if error.status_code == 409:
print("Invalid state transition")
print("Session may already be paused or completed")
elif error.status_code == 404:
print("Session not found")
else:
print(f"Error: {error.message}")Best Practices
- Use context managers: Always use
withorasync withfor automatic resource cleanup - Descriptive names: Use clear, searchable session names
- Use appropriate types: Choose the session type that matches your use case
- Tag consistently: Establish tagging conventions for your team
- Pause inactive sessions: Prevent accidental memory additions
- Add summaries: Include completion summaries for future reference
- Set retention policies: Use temporary sessions for ephemeral work
- Type hints: Use Pydantic models for type safety
Next Steps
- Advanced Features - Error handling, retries, and pagination
- Memories - Creating session-scoped memories
- Spaces - Organizing sessions with spaces
- Sessions API Reference - Complete REST API documentation