Skip to main content
DELETE
/
v1
/
sessions
/
{session_id}
Delete Session
curl --request DELETE \
  --url https://api.example.com/v1/sessions/{session_id} \
  --header 'Authorization: <authorization>'
{
  "success": true,
  "deleted": true,
  "message": "Session deleted successfully"
}

Overview

Clean up individual sessions when you’re done using them. This frees up resources and prevents unnecessary charges.

Request

session_id
string
required
The UUID of the session to delete
Authorization
string
required
Bearer token for authentication
save_snapshot_mode
string
Snapshot mode when deleting the sessionOptions:
  • none - No snapshot is saved (default)
  • memory - Creates a memory snapshot (fastest restoration, but may be less reliable)
  • filesystem - Creates a filesystem snapshot (more reliable, preserves all browser data including authentication)
See Session Snapshots guide for details on snapshot modes and authentication preservation.
save_as_default
boolean
Set the snapshot as the user’s default environment
  • true - Save snapshot and set as default environment
  • false - Save snapshot without setting as default (default)
When true, future sessions can automatically restore from this snapshot using restore_default_environment_from_user_id.Requires save_snapshot_mode to be set to memory or filesystem.

Response

success
boolean
Whether the operation completed successfully
deleted
boolean
Whether the session was actually deleted (false if not found)
message
string
Result message
{
  "success": true,
  "deleted": true,
  "message": "Session deleted successfully"
}

Example

curl -X DELETE https://api.agi.tech/v1/sessions/<session_id> \
  -H "Authorization: Bearer $AGI_API_KEY"

Use Cases

Cleanup After Task

# Standard pattern: always cleanup
session_id = create_session()

try:
    # Do work
    send_message(session_id, "Find product prices")
    results = wait_for_completion(session_id)
    process_results(results)
finally:
    # Always cleanup
    delete_session(session_id)

Context Manager Pattern

from contextlib import contextmanager

@contextmanager
def agent_session(agent_name="agi-0"):
    """Context manager for automatic cleanup"""
    session_id = create_session(agent_name)
    try:
        yield session_id
    finally:
        delete_session(session_id)

# Usage
with agent_session() as session_id:
    send_message(session_id, "Research AI companies")
    results = poll_until_complete(session_id)
# Session automatically deleted here

Batch Cleanup

# Clean up old completed sessions
def cleanup_completed_sessions():
    sessions = get_sessions()

    for session in sessions:
        if session["status"] in ["completed", "error"]:
            print(f"Deleting session {session['session_id']}")
            delete_session(session["session_id"])

Selective Cleanup

# Delete only sessions older than 1 hour
from datetime import datetime, timedelta

def cleanup_old_sessions(max_age_hours=1):
    sessions = get_sessions()
    now = datetime.now()

    for session in sessions:
        created_at = datetime.fromisoformat(
            session["created_at"].replace("Z", "+00:00")
        )

        age = now - created_at

        if age > timedelta(hours=max_age_hours):
            print(f"Deleting old session: {session['session_id']}")
            delete_session(session["session_id"])

Resource Monitoring

# Monitor and limit concurrent sessions
MAX_SESSIONS = 5

def create_managed_session():
    sessions = get_sessions()

    # Delete oldest if at limit
    if len(sessions) >= MAX_SESSIONS:
        oldest = min(sessions, key=lambda s: s["created_at"])
        print(f"At session limit, deleting oldest: {oldest['session_id']}")
        delete_session(oldest["session_id"])

    return create_session()

Error Handling

def safe_delete(session_id):
    """Delete with error handling"""
    try:
        result = delete_session(session_id)

        if result["deleted"]:
            print(f"Session {session_id} deleted")
        else:
            print(f"Session {session_id} not found (already deleted?)")

        return result["success"]

    except requests.HTTPError as e:
        if e.response.status_code == 404:
            print("Session doesn't exist")
            return True  # Already gone, that's fine
        else:
            print(f"Error deleting session: {e}")
            return False

Deletion Behavior

ScenarioResult
Active sessionImmediately terminated and deleted
Running taskTask cancelled, session deleted
Paused sessionSession deleted
Completed taskSession deleted
Non-existent IDReturns deleted: false, no error
Deletion is immediate and cannot be undone. Ensure you’ve retrieved any results before deleting.

Lifecycle Management

class SessionManager:
    def __init__(self):
        self.active_sessions = []

    def create(self, agent_name="agi-0"):
        session_id = create_session(agent_name)
        self.active_sessions.append(session_id)
        return session_id

    def delete(self, session_id):
        if session_id in self.active_sessions:
            delete_session(session_id)
            self.active_sessions.remove(session_id)

    def cleanup_all(self):
        for session_id in self.active_sessions:
            try:
                delete_session(session_id)
            except Exception as e:
                print(f"Error deleting {session_id}: {e}")
        self.active_sessions.clear()

# Usage
manager = SessionManager()

# Register cleanup on exit
import atexit
atexit.register(manager.cleanup_all)

# Use manager
session = manager.create()
# ... do work ...
manager.delete(session)

Saving Snapshots

Save Snapshot on Deletion

To preserve session state (including authentication) for future use:
# Save filesystem snapshot (recommended for authentication)
response = requests.delete(
    f"https://api.agi.tech/v1/sessions/{session_id}",
    headers={"Authorization": f"Bearer {API_KEY}"},
    params={"save_snapshot_mode": "filesystem"}
)

Save and Set as Default

Save a snapshot and set it as your default environment:
# Save snapshot and set as default
response = requests.delete(
    f"https://api.agi.tech/v1/sessions/{session_id}",
    headers={"Authorization": f"Bearer {API_KEY}"},
    params={
        "save_snapshot_mode": "filesystem",
        "save_as_default": "true"
    }
)
Future sessions can then automatically restore from this snapshot using restore_default_environment_from_user_id. See Session Snapshots guide for complete details on managing snapshots and authentication state.

Best Practices

Always delete sessions when done. Orphaned sessions consume resources and may incur charges.
Use try/finally blocks or context managers to ensure cleanup even if errors occur.
Save snapshots with save_snapshot_mode=filesystem after logging into services to preserve authentication state.
Deleting a session immediately terminates any running tasks and closes the browser.