Persistent conversation containers that maintain context, state, and memory across requests
Sessions are the foundational container for agent conversations, providing persistent context, state management, and continuity across multiple requests.
The Sessions primitive represents a persistent conversation thread between you and an agent. Each session is a unique, isolated container that maintains:
Conversation History: All messages and responses in chronological order
Computational State: Files, installed packages, and environment configuration
Context Memory: Agent’s understanding of ongoing tasks and user preferences
Tool State: Results from previous tool executions and data gathered
Session Identity: Unique identifier for tracking and resuming conversations
Sessions enable sophisticated multi-turn interactions where agents can remember context, build on previous work, and maintain continuity across hours, days, or even weeks.
Automatic Creation
Every agent request creates a new session or continues an existing one
Persistent by Default
Message history and state persist automatically at no extra cost
Isolated Containers
Each session is completely isolated from others for security and privacy
Long-Lived
Sessions can span multiple requests over extended time periods
import { Agentbase } from '@agentbase/sdk';const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY});// Omit session parameter to create new sessionconst result = await agentbase.runAgent({ message: "Hello, I'm starting a new project"});console.log('Session ID:', result.session);// Output: Session ID: agent_session_abc123xyz789...// Save this session ID for continuing the conversationconst sessionId = result.session;
// Continue existing sessionconst continuation = await agentbase.runAgent({ message: "Let's continue working on that project", session: sessionId // Reuse the session ID from above});// Agent has full context from previous conversation// All files, packages, and state are preserved
// Turn 1: Start conversationconst turn1 = await agentbase.runAgent({ message: "My name is Alice and I need help building a website"});const sessionId = turn1.session;// Turn 2: Agent remembers your nameconst turn2 = await agentbase.runAgent({ message: "What technologies should I use?", session: sessionId});// Agent response will reference Alice and the website project// Turn 3: Continue with contextconst turn3 = await agentbase.runAgent({ message: "Can you create the project structure?", session: sessionId});// Agent knows what project we're talking about// Turn 4: Build on previous workconst turn4 = await agentbase.runAgent({ message: "Add a homepage and contact form", session: sessionId});// Project structure from turn 3 still exists
// Session pauses automatically// - Computational environment suspended// - All state preserved (files, packages)// - Message history intact// - Next request will auto-resume (~1-2 seconds)// After 10 minutes of no activity...const resumed = await agentbase.runAgent({ message: "Resume work", session: pausedSessionId});// Automatically resumes, all state intact
// Eventually sessions expire// Attempting to use expired session:try { const result = await agentbase.runAgent({ message: "Use old session", session: expiredSessionId });} catch (error) { if (error.code === 'SESSION_NOT_FOUND') { // Session no longer exists // Start new session or restore from backup }}
async function collaborativeProject(projectId: string, userId: string) { // Each user gets their own session for the same project const userSession = await getUserSession(projectId, userId); if (!userSession) { // Create new session for this user const result = await agentbase.runAgent({ message: `Load project ${projectId} for user ${userId}`, system: "You are assisting with a collaborative project." }); await saveUserSession({ projectId, userId, sessionId: result.session, role: 'contributor' }); return result.session; } // User continues their work in their session return userSession.sessionId;}// User A works in their sessionconst userA = await collaborativeProject('proj_123', 'user_alice');await agentbase.runAgent({ message: "Work on feature A", session: userA});// User B works in separate sessionconst userB = await collaborativeProject('proj_123', 'user_bob');await agentbase.runAgent({ message: "Work on feature B", session: userB});// Sessions are isolated but can be coordinated
async function testingWorkflow() { // Create test scenarios in separate sessions const scenarios = [ 'test happy path with valid data', 'test error handling with invalid data', 'test edge cases with boundary values' ]; const sessions = await Promise.all( scenarios.map(async (scenario) => { const result = await agentbase.runAgent({ message: `Set up test environment and ${scenario}`, system: "You are a QA engineer running test scenarios." }); return { scenario, sessionId: result.session, result: result.message }; }) ); // Each test runs in isolated session // Continue specific tests as needed await agentbase.runAgent({ message: "Run additional edge case tests", session: sessions[2].sessionId // Edge case session });}
Session Isolation: Each session is completely isolated. Never share session IDs between different users or security contexts.
Copy
// Good: User-specific sessionsasync function getUserSession(userId: string, workflowId: string) { const session = await db.sessions.findOne({ userId, workflowId }); if (!session) { throw new Error('Session not found or unauthorized'); } // Verify user owns this session if (session.userId !== userId) { throw new Error('Unauthorized access to session'); } return session.sessionId;}// Avoid: Sharing sessions between usersconst sharedSession = 'agent_session_123'; // Don't do this!
// Session 1: Data analystconst analyst = await agentbase.runAgent({ message: "Analyze this data", system: "You are a data analyst"});// Session 2: Content writer (different session, different role)const writer = await agentbase.runAgent({ message: "Write a blog post", system: "You are a content writer"});// Each session maintains its role throughout
// Main session coordinates multiple agentsconst support = await agentbase.runAgent({ message: "I need help", system: "You are a routing agent", agents: [ { name: "Technical Support", description: "Handles technical issues" }, { name: "Billing Support", description: "Handles billing questions" } ]});// All agent transfers happen within the same session
Short sessions (<10 messages): Optimal performance
Medium sessions (10-50 messages): Good performance
Long sessions (50+ messages): Consider periodic summarization
Copy
// For very long sessions, periodically summarizeif (messageCount > 50) { const summary = await agentbase.runAgent({ message: "Summarize our conversation and key decisions so far", session: longSession }); // Store summary, potentially start new session with summary as context}
Remember: Sessions are the foundation of continuity in Agentbase. Save session IDs, reuse them for related work, and use separate sessions for independent workflows.