Skip to main content

Python SDK: Sessions

Manage CLI sessions with full lifecycle control using the Python SDK.

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

create_session.py
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

create_session_async.py
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

ParameterTypeDescription
namestrSession name (required, max 200 chars)
typeSessionTypeCONVERSATION, PROJECT, TASK, or TEMPORARY
descriptionstrDetailed description (max 1000 chars)
tagsList[str]Tags for organization (max 10 tags)
space_idstrAssociate session with a space
retention_policyRetentionPolicyPERMANENT, TEMPORARY, AUTO_DELETE, ON_COMPLETION
retention_daysintDays before auto-deletion
is_privateboolPrivate sessions visible only to creator
metadataDictCustom key-value metadata

List and Filter Sessions

list_sessions.py
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

ParameterTypeDescription
statusSessionStatusFilter by ACTIVE, PAUSED, COMPLETED, ARCHIVED
typeSessionTypeFilter by session type
space_idstrFilter by space
tagsList[str]Filter by tags
searchstrSearch name and description
limitintResults per page (default: 20, max: 100)

Get Session

get_session.py
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

update_session.py
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

pause_session.py
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

resume_session.py
resumed = client.sessions.resume("sess_abc123")

print(resumed.status)
print(resumed.paused_at)

Complete Session

complete_session.py
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

delete_session.py
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

get_active_sessions.py
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

get_session_memories.py
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

create_memory_in_session.py
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

complete_workflow.py
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

types.py
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

error_handling.py
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 with or async with for 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