Skip to main content

Overview

The BaseSessionService abstract class provides a set of methods for managing sessions and events. Implementations include in-memory storage, database persistence, and cloud-based solutions.

Available Implementations

  • InMemorySessionService - Simple in-memory storage for development
  • DatabaseSessionService - PostgreSQL/SQLite persistence with Drizzle ORM
  • VertexAiSessionService - Google Vertex AI backed sessions

Methods

createSession

Creates a new session.
appName
string
required
The name of the app.
userId
string
required
The id of the user.
state
Record<string, any>
The initial state of the session. Defaults to an empty object.
sessionId
string
The client-provided id of the session. If not provided, a generated ID will be used.
returns
Promise<Session>
The newly created session instance.
const session = await sessionService.createSession(
  'my-app',
  'user-123',
  { initialKey: 'value' },
  'custom-session-id'
);

getSession

Gets a session with optional filtering of events.
appName
string
required
The name of the app.
userId
string
required
The id of the user.
sessionId
string
required
The id of the session.
config
GetSessionConfig
Optional configuration for getting the session.
returns
Promise<Session | undefined>
The session or undefined if not found.
// Get full session
const session = await sessionService.getSession(
  'my-app',
  'user-123',
  'session-id'
);

// Get session with only recent events
const recentSession = await sessionService.getSession(
  'my-app',
  'user-123',
  'session-id',
  { numRecentEvents: 10 }
);

listSessions

Lists all sessions for a user.
appName
string
required
The name of the app.
userId
string
required
The id of the user.
returns
Promise<ListSessionsResponse>
The response containing the list of sessions.
const response = await sessionService.listSessions('my-app', 'user-123');
console.log(`Found ${response.sessions.length} sessions`);

deleteSession

Deletes a session permanently.
appName
string
required
The name of the app.
userId
string
required
The id of the user.
sessionId
string
required
The id of the session.
returns
Promise<void>
Resolves when the session is deleted.
await sessionService.deleteSession('my-app', 'user-123', 'session-id');

endSession

Ends a session and returns its final state. This is typically called when a session is complete and should be stored in long-term memory before potential cleanup.
appName
string
required
The name of the app.
userId
string
required
The id of the user.
sessionId
string
required
The id of the session.
returns
Promise<Session | undefined>
The session with its final state, or undefined if not found.
const finalSession = await sessionService.endSession(
  'my-app',
  'user-123',
  'session-id'
);

if (finalSession) {
  // Store in long-term memory
  await memoryService.addSessionToMemory(finalSession);
}

appendEvent

Appends an event to a session object and updates the session state based on the event’s state delta.
session
Session
required
The session to append the event to.
event
Event
required
The event to append. If the event is marked as partial, it will not be appended or update state.
returns
Promise<Event>
The appended event.
const event: Event = {
  author: 'user',
  text: 'Hello!',
  timestamp: Date.now(),
  actions: {
    stateDelta: {
      lastMessage: 'Hello!'
    }
  }
};

await sessionService.appendEvent(session, event);

State Management

The session service automatically manages state updates through events:
  1. When an event is appended with actions.stateDelta, those state changes are applied to the session
  2. Keys starting with temp_ are ignored and won’t be persisted
  3. Setting a value to null or undefined removes that key from state
// This event will update session.state
const event = {
  actions: {
    stateDelta: {
      userName: 'Alice',        // Sets userName
      temp_processing: true,    // Ignored (temp_ prefix)
      oldKey: null             // Removes oldKey from state
    }
  }
};

Usage with Agents

import { AgentBuilder, InMemorySessionService } from '@iqai/adk';

const sessionService = new InMemorySessionService();

const agent = new AgentBuilder()
  .withModel('gpt-4')
  .withSessionConfig({
    appName: 'my-app',
    userId: 'user-123',
    sessionService: sessionService,
    // Optionally provide existing sessionId to continue conversation
    sessionId: 'existing-session-id'
  })
  .buildLlm();

const response = await agent.ask('What's the weather?');

// Session is automatically managed
console.log('Session ID:', agent.session?.id);

Build docs developers (and LLMs) love