The States primitive represents the agent’s persistent memory and context management system. While sessions provide the container for conversations, states determine what information persists and how agents maintain context across interactions. This enables sophisticated workflows where agents can:
Remember Context: Maintain conversation history and relevant information across requests
Build Incrementally: Continue work from previous steps without starting over
Track Progress: Keep track of multi-step workflows and their current state
Share Knowledge: Make information available across different parts of a workflow
Maintain Variables: Store and retrieve data throughout the agent’s execution
Automatic Persistence
Message history persists automatically at no cost for all conversations
Environment State
Files, installed packages, and system state persist within session sandboxes
Session-Scoped
Each session maintains its own isolated state and context
Incremental Building
Agents build upon previous work without repeating completed steps
import { Agentbase } from '@agentbase/sdk';const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY});// First request - creates stateconst step1 = await agentbase.runAgent({ message: "Create a file called data.json with some sample data"});console.log('Session ID:', step1.session);// Output: Session ID: agent_session_abc123...// Second request - uses existing stateconst step2 = await agentbase.runAgent({ message: "Read the data.json file and summarize its contents", session: step1.session // Reuse session = reuse state});// The file still exists! Agent can read it.
// Step 1: Setup environmentconst setup = await agentbase.runAgent({ message: "Install pandas and numpy"});// Step 2: Process data (packages still installed)const process = await agentbase.runAgent({ message: "Create a Python script to process sales.csv", session: setup.session});// Step 3: Analyze (script and packages still available)const analyze = await agentbase.runAgent({ message: "Run the script and show the analysis", session: setup.session});// Step 4: Visualize (all previous work available)const visualize = await agentbase.runAgent({ message: "Create a chart from the analysis results", session: setup.session});// Each step builds on previous state
// Agent remembers conversation historyconst result1 = await agentbase.runAgent({ message: "My name is Alice and I work at TechCorp"});const result2 = await agentbase.runAgent({ message: "What's my name?", session: result1.session});// Agent responds: "Your name is Alice"const result3 = await agentbase.runAgent({ message: "Where do I work?", session: result1.session});// Agent responds: "You work at TechCorp"// All previous messages are in context
// Create a complete development workflow with persistent stateasync function developmentWorkflow() { // Initialize project const init = await agentbase.runAgent({ message: "Create a new Node.js project with package.json" }); const sessionId = init.session; // Install dependencies await agentbase.runAgent({ message: "Install express, dotenv, and nodemon", session: sessionId }); // Create application await agentbase.runAgent({ message: "Create a basic Express server in src/index.js", session: sessionId }); // Add features await agentbase.runAgent({ message: "Add a /health endpoint to the server", session: sessionId }); // Test const test = await agentbase.runAgent({ message: "Start the server and test the health endpoint", session: sessionId }); return test;}
State is created automatically on the first request in a session:
Copy
// No session ID = new session = new stateconst result = await agentbase.runAgent({ message: "Start a new project"});// Fresh state:// - Empty message history// - Clean file system// - No installed packages// - Default environment
// Same session = same stateconst continued = await agentbase.runAgent({ message: "Continue from where we left off", session: existingSessionId});// Preserved state:// - All previous messages// - All created files// - All installed packages// - Environment variables// - Working directory
async function iterativeDevelopment() { // Session for the entire development process const session = (await agentbase.runAgent({ message: "Create a Python web scraper project structure" })).session; // Each step builds on the previous await agentbase.runAgent({ message: "Install beautifulsoup4 and requests", session }); await agentbase.runAgent({ message: "Create scraper.py with basic scraping logic", session }); await agentbase.runAgent({ message: "Add error handling to the scraper", session }); await agentbase.runAgent({ message: "Create tests for the scraper", session }); const final = await agentbase.runAgent({ message: "Run the tests and fix any issues", session }); return final;}
async function researchProject(topic: string) { // Start research const init = await agentbase.runAgent({ message: `Research ${topic} and create a document with findings` }); const sessionId = init.session; // Add more information await agentbase.runAgent({ message: "Search for recent developments in 2024", session: sessionId // Adds to existing document }); await agentbase.runAgent({ message: "Find case studies and real-world examples", session: sessionId // Appends to document }); await agentbase.runAgent({ message: "Add statistics and data points", session: sessionId // Enhances existing content }); const final = await agentbase.runAgent({ message: "Organize all findings into a structured report", session: sessionId // Works with all accumulated information }); return final;}
async function debugWorkflow() { // Create buggy code const code = await agentbase.runAgent({ message: "Create a Python script that processes user data" }); const sessionId = code.session; // Test it const test1 = await agentbase.runAgent({ message: "Run the script with test data", session: sessionId }); // Fix issues found await agentbase.runAgent({ message: "Fix the KeyError in the script", session: sessionId // Script still exists, just modify it }); // Test again const test2 = await agentbase.runAgent({ message: "Run the script again", session: sessionId }); // Add more test cases const final = await agentbase.runAgent({ message: "Test edge cases: empty input, large dataset", session: sessionId }); return final;}
// Store session ID in your databaseasync function startWorkflow(userId: string, workflowType: string) { const result = await agentbase.runAgent({ message: "Initialize workflow" }); // Save for later use await db.workflows.create({ userId, workflowType, sessionId: result.session, status: 'in_progress', createdAt: new Date() }); return result.session;}// Resume laterasync function continueWorkflow(workflowId: string, message: string) { const workflow = await db.workflows.findById(workflowId); return await agentbase.runAgent({ message, session: workflow.sessionId });}
Use Separate Sessions for Independent Tasks
Copy
// Good: Separate sessions for unrelated tasksconst customerAnalysis = await agentbase.runAgent({ message: "Analyze customer churn data" // New session, clean state});const contentGeneration = await agentbase.runAgent({ message: "Generate marketing content" // Different session, different state});// Avoid: Mixing unrelated work in one sessionconst mixed = await agentbase.runAgent({ message: "Analyze customer data"});await agentbase.runAgent({ message: "Now write marketing content", session: mixed.session // Confusing context with unrelated previous work});
Clean Up Temporary State
Copy
// Clean up large files to manage disk usageconst analysis = await agentbase.runAgent({ message: "Process large_dataset.csv and analyze"});const sessionId = analysis.session;// Continue with analysis resultsawait agentbase.runAgent({ message: "Create summary report", session: sessionId});// Clean up large files no longer neededawait agentbase.runAgent({ message: "Delete large_dataset.csv and any temporary files", session: sessionId});
async function safeResume(sessionId: string, message: string) { try { return await agentbase.runAgent({ message, session: sessionId }); } catch (error) { if (error.code === 'SESSION_NOT_FOUND') { console.warn('Session expired, starting fresh'); // Either start new session or restore from checkpoint return await agentbase.runAgent({ message: `Resume workflow: ${message}`, system: "Previous session expired, recreate necessary state" }); } throw error; }}
Create State Checkpoints
Copy
// Save important state externally for recoveryasync function workflowWithCheckpoints() { const result = await agentbase.runAgent({ message: "Process data and create report" }); const sessionId = result.session; // Create checkpoint - extract important state const checkpoint = await agentbase.runAgent({ message: "List all created files and their purposes", session: sessionId }); // Store checkpoint externally await saveCheckpoint({ sessionId, timestamp: new Date(), files: checkpoint.message, context: "Data processing workflow" }); return result;}
// Session = container, State = contentsconst session1 = await agentbase.runAgent({ message: "Task A"});// Session 1 has its own stateconst session2 = await agentbase.runAgent({ message: "Task B"});// Session 2 has completely separate state
// Each sandbox has isolated stateconst result = await agentbase.runAgent({ message: "Create sensitive_data.txt"});// File exists only in this sandbox/session// Other sessions cannot access it
// Create files that persistconst files = await agentbase.runAgent({ message: "Create config.json, data.csv, and script.py"});// All files still existconst modify = await agentbase.runAgent({ message: "Update config.json with new settings", session: files.session});// Read any file from the sessionconst read = await agentbase.runAgent({ message: "Show contents of all three files", session: files.session});
Message History: Unlimited messages, but very long histories may impact performance
File Storage: 10GB per session limit
Memory Usage: 2-4GB depending on mode
Copy
// Check disk usageconst check = await agentbase.runAgent({ message: "Show disk usage with du -sh", session: existingSession});// Clean up if neededif (usageHigh) { await agentbase.runAgent({ message: "Delete files in /tmp and other temporary directories", session: existingSession });}
Very long message histories may need summarization:
Copy
// For very long sessions, periodically summarizeconst summary = await agentbase.runAgent({ message: "Summarize our conversation so far and key decisions made", session: longSession});// Store summary externally, potentially start new session// with summary as context
Problem: Hit 10GB storage limitSolution: Clean up large files regularly
Copy
// Monitor disk usageconst usage = await agentbase.runAgent({ message: "Check disk usage and list large files", session: existingSession});// Clean upawait agentbase.runAgent({ message: "Delete temporary files and large downloads", session: existingSession});
Conflicting State
Problem: Previous state interfering with new tasksSolution: Start new session for unrelated work
Copy
// Don't mix unrelated tasks// Instead of:const mixed = await agentbase.runAgent({ message: "Different task", session: existingSession // May have conflicting state});// Do this:const clean = await agentbase.runAgent({ message: "Different task" // New session, clean state});
async function createSnapshot(sessionId: string) { // List all important state const state = await agentbase.runAgent({ message: `Create a snapshot: 1. List all files in project directory 2. Export environment variables 3. List installed packages 4. Summarize current progress`, session: sessionId }); // Store snapshot externally return { sessionId, timestamp: new Date(), snapshot: state.message };}// Restore from snapshotasync function restoreFromSnapshot(snapshot: any) { return await agentbase.runAgent({ message: `Restore state: ${snapshot.snapshot}`, system: "Recreate the described environment and files" });}
async function migrateState(oldSession: string, newSession: string) { // Export state from old session const exported = await agentbase.runAgent({ message: "Create export.tar.gz with all project files", session: oldSession }); // Import to new session await agentbase.runAgent({ message: "Extract and restore from export.tar.gz", session: newSession });}
Remember: State management is automatic in Agentbase. Focus on organizing your workflows logically, and the platform handles persistence, isolation, and cleanup.