TypeScriptADK-TS
Sessions

Session Management

Track and manage a single conversation thread with a simple, consistent lifecycle

Sessions represent one conversation thread. They keep the message history and scoped state needed to maintain context across turns—much like a chat thread in a messaging app.

The Session Object

When a user starts interacting with your agent, the SessionService creates a Session object (google.adk.sessions.Session). This object acts as the container holding everything related to that one specific chat thread. Here are its key properties:

  • Identification (id, appName, userId): Unique labels for the conversation.
    • id: A unique identifier for this specific conversation thread, essential for retrieving it later. A SessionService object can handle multiple Session(s). This field identifies which particular session object are we referring to. For example, "test_id_modification".
    • app_name: Identifies which agent application this conversation belongs to. For example, "id_modifier_workflow".
    • userId: Links the conversation to a particular user.
  • History (events): A chronological sequence of all interactions (Event objects – user messages, agent responses, tool actions) that have occurred within this specific thread.
  • Session State (state): A place to store temporary data relevant only to this specific, ongoing conversation. This acts as a scratchpad for the agent during the interaction. We will cover how to use and manage state in detail in the next section.
  • Activity Tracking (lastUpdateTime): A timestamp indicating the last time an event occurred in this conversation thread.

Managing Sessions with a SessionService

As seen above, you don't typically create or manage Session objects directly. Instead, you use a SessionService. This service acts as the central manager responsible for the entire lifecycle of your conversation sessions.

Its core responsibilities include:

  • Starting New Conversations: Creating fresh Session objects when a user begins an interaction.
  • Resuming Existing Conversations: Retrieving a specific Session (using its ID) so the agent can continue where it left off.
  • Saving Progress: Appending new interactions (Event objects) to a session's history. This is also the mechanism through which session state gets updated (more in the State section).
  • Listing Conversations: Finding the active session threads for a particular user and application.
  • Cleaning Up: Deleting Session objects and their associated data when conversations are finished or no longer needed.

Implementation Options

In-memory (development)

Fast and simple for development/testing.

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

const sessionService = new InMemorySessionService();

// Create session
const session = await sessionService.createSession(
  'my-app',
  'user123',
  {
    current_step: 'welcome',
    'user:theme': 'dark'
  }
);

Use when you don't need persistence between restarts.

Database (production-ready persistence)

Persistent storage using PostgreSQL, MySQL, or SQLite. Choose a specific factory or use the generic auto-detect helper.

PostgreSQL

import { createPostgresSessionService, createDatabaseSessionService } from '@iqai/adk';

// Direct (requires peer dep: pg)
const sessionService = createPostgresSessionService(
  'postgres://user:pass@host:5432/db'
);

// Or auto-detect
const sessionService = createDatabaseSessionService('postgres://user:pass@host:5432/db');

MySQL

import { createMysqlSessionService, createDatabaseSessionService } from '@iqai/adk';

// Direct (requires peer dep: mysql2)
const sessionService = createMysqlSessionService(
  'mysql://user:pass@host:3306/db'
);

// Or auto-detect
const sessionService = createDatabaseSessionService('mysql://user:pass@host:3306/db');

SQLite

import { createSqliteSessionService, createDatabaseSessionService } from '@iqai/adk';

// Direct (requires peer dep: better-sqlite3)
const sessionService = createSqliteSessionService('sessions.db');

// Or auto-detect (both forms are supported)
const sessionService = createDatabaseSessionService('sqlite://sessions.db');
const sessionService2 = createDatabaseSessionService('sessions.db');

Once you have a sessionService, use it the same way regardless of the database:

// Create a session
const session = await sessionService.createSession(
  'my-app',
  'user123',
  {
    current_step: 'welcome',
    'user:preferred_language': 'es',
    'app:version': '2.0'
  }
);

Notes:

  • Tables are created automatically by default
  • Prefixes are handled for you: app: → app_states, user: → user_states, unprefixed → sessions

Database peer dependencies

Install one of: better-sqlite3 (SQLite), pg (PostgreSQL), or mysql2 (MySQL), depending on your database.

Cloud (Vertex AI Agent Engine)

Scalable, managed storage on Google Cloud.

import { VertexAiSessionService } from '@iqai/adk';

const sessionService = new VertexAiSessionService({
  project: 'your-gcp-project',
  location: 'us-central1',
  agentEngineId: 'your-agent-engine-id' // Optional: can use appName as reasoning engine ID
});

// Create session (sessionId is auto-generated)
const session = await sessionService.createSession(
  'projects/your-project/locations/us-central1/reasoningEngines/12345',
  'user123',
  {
    current_step: 'welcome',
    'user:language': 'en'
  }
);

Use when you want fully managed persistence and scale.

Choosing an implementation

Pick in-memory for local dev, database for most production apps, and cloud for managed, enterprise scale.

Session Lifecycle

Here’s a simplified flow of how Session and SessionService work together during a conversation turn:

  1. Start or Resume: Your application needs to use the SessionService to either createSession (for a new chat) or use an existing session id.
  2. Context Provided: The Runner gets the appropriate Session object from the appropriate service method, providing the agent with access to the corresponding Session's state and events.
  3. Agent Processing: The user prompts the agent with a query. The agent analyzes the query and potentially the session state and events history to determine the response.
  4. Response & State Update: The agent generates a response (and potentially flags data to be updated in the state). The Runner packages this as an Event.
  5. Save Interaction: The Runner calls sessionService.appendEvent(session, event) with the session and the new event as the arguments. The service adds the Event to the history and updates the session's state in storage based on information within the event. The session's lastUpdateTime also get updated.
  6. Ready for Next: The agent's response goes to the user. The updated Session is now stored by the SessionService, ready for the next turn (which restarts the cycle at step 1, usually with the continuation of the conversation in the current session).
  7. End Conversation: When the conversation is over, your application calls sessionService.deleteSession(...) to clean up the stored session data if it is no longer required.

This cycle highlights how the SessionService ensures conversational continuity by managing the history and state associated with each Session object.

How is this guide?