Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.ag-kit.dev/llms.txt

Use this file to discover all available pages before exploring further.

Session management allows you to handle multiple concurrent conversations by using the sessionId parameter in memory operations. This is an application-level pattern built on top of AG-Kit’s memory APIs.

Core Concept

A session is simply a unique identifier (string) that isolates conversation contexts. All memory operations accept an optional sessionId parameter to separate data between different users or conversations.

Quick Start

Basic Session Management

import { InMemoryMemory } from '@ag-kit/agents';

// Create memory instance
const memory = new InMemoryMemory();

// Create session for user A
const sessionA = 'user-alice-session-1';
await memory.add(
  {
    message: {
      id: 'msg-1',
      role: 'user',
      content: 'Hello, I\'m Alice',
      timestamp: new Date()
    },
    state: { userId: 'alice' }
  },
  { sessionId: sessionA }
);

// Create session for user B
const sessionB = 'user-bob-session-1';
await memory.add(
  {
    message: {
      id: 'msg-1',
      role: 'user',
      content: 'Hi, I\'m Bob',
      timestamp: new Date()
    },
    state: { userId: 'bob' }
  },
  { sessionId: sessionB }
);

// Retrieve session-specific history
const aliceHistory = await memory.list({ sessionId: sessionA });
const bobHistory = await memory.list({ sessionId: sessionB });

console.log('Alice:', aliceHistory[0].message.content); // "Hello, I'm Alice"
console.log('Bob:', bobHistory[0].message.content); // "Hi, I'm Bob"

Common Session ID Patterns

You can design session IDs based on your application needs:
// User-based: one session per user
const sessionId = `user-${userId}`;

// Conversation-based: multiple sessions per user
const sessionId = `user-${userId}-conv-${conversationId}`;

// Time-based: sessions with timestamps
const sessionId = `user-${userId}-${Date.now()}`;

// Hierarchical: complex organization structure
const sessionId = `org-${orgId}/team-${teamId}/user-${userId}`;

Using Sessions with Agents

Sessions enable isolated conversations for different users or contexts.
import { InMemoryMemory } from '@ag-kit/agents';

const memory = new InMemoryMemory();

// Agent handles request with session isolation
async function handleUserMessage(userId: string, message: string) {
  const sessionId = `user-${userId}`;
  
  // Add user message to session
  await memory.add(
    {
      message: {
        id: crypto.randomUUID(),
        role: 'user',
        content: message,
        timestamp: new Date()
      }
    },
    { sessionId }
  );
  
  // Get session history for agent
  const history = await memory.list({ sessionId });
  
  // Process with agent...
  const response = await agent.run({
    messages: history.map(m => m.message),
    sessionId
  });
  
  return response;
}
Learn more: Complete Agent Integration Guide

Best Practices

  1. Use meaningful session IDs - Include user/conversation identifiers for debugging
  2. Implement session cleanup - Remove old sessions to prevent memory leaks
  3. Handle session expiration - Implement timeout logic in your application
  4. Store session metadata separately - Track creation time, last activity, etc.
  5. Consider privacy - Clear sensitive session data when no longer needed

Next Steps

Short-Term Memory

Learn about conversation history management

Long-Term Memory

Explore persistent memory storage