Sessions API

Sessions store a conversation with AI. Every frontier model handles the storage of messages differently. That's why we standardize message persistence and makes it easy for you to change the underlying model.

Sessions have a title, description and custom fields. You can do the following with sessions:

Let's get started and create your first session:

val agents = VisionAgents(apiKey = "your_api_key")
agents.setUser(User(id = "jlahey")) { yourBackend.agentToken() }
val agent = agents.agent("myagent")

val session = agent.chat()

Server side auth requires a STREAM_API_KEY and a STREAM_API_SECRET, client side you need the API key, user id and token. Auth explains how this works in detail.

Now that you have a session open, you can use responses.create to interact with the agent.

val answer = launch {
    session.events()
        .takeWhile { it.type != "responded" }
        .collect { if (it.type == "response_delta") print(it.text) }
}
session.responses.create("Where is order 1042?")
answer.join()

A session keeps its conversation in a Stream Chat channel, which session.chat() opens. The channel is a transcript, for text and voice sessions alike: the agent does not answer a message sent to it, so write to the agent with responses.create, which also stores your message in the channel.

session.chat(context) returns a ChannelClient for the channel. It opens on the ChatClient you handed over with agents.use(client), or else connects one as the user setUser named.

If you've used OpenAI before the responses.create API will seem familiar. Creating responses API explains how to interact with the agent.

A few fields on the session are updated automatically:

  • Title
  • Description
  • Usage

Creating or Updating a session

sessions.create creates a conversation

val session = agent.chat(
    SessionOptions(
        title = "Order 1042",
        custom = buildJsonObject { put("ticket", "4721") },
    ),
)

Passing your own id gives you control over uniqueness. This is convenient when you want to create a session for an object in your database. For instance opening a session for a specific order in your shop etc.

val session = agent.chat(SessionOptions(id = "order-1042", title = "Order 1042"))

An id is any string of up to 64 letters, digits, - and _. A UUID works too.

Everything is optional:

Option What it does
id The id to hold the session by, such as your own record's id. Left out, the router generates a UUIDv7
title, description What a person finds the conversation by later. Both are searched
project_id Groups conversations, and is recorded as the project cost tag
custom Your own labels, handed back untouched
tags Cost tags for this conversation, merged with the agent's own tags
model_overwrites Change the models for this conversation, such as { llm: "llm-thinking", thinking: "high" }
incognito Keep nothing: no Stream Chat channel, no session row, no turns. It cannot be listed, searched or forked afterwards
start_voice Start voice as the session opens. Left out, the conversation is held in writing until voice is started

Models, cost tags and incognito

It's common to want to overwrite the thinking level, cost tracking or incognito mode.

model_overwrites changes the models for one conversation, tags adds cost tags to it. incognito mode disables permanent storage.

val session = agent.chat(
    SessionOptions(
        modelOverwrites = ModelOverwrites(llm = "llm-thinking", thinking = ModelOverwrites.Thinking.High),
        tags = mapOf("customer_id" to "123", "plan" to "pro"),
        incognito = true,
    ),
)

model_overwrites takes llm, stt, tts, sts, search, thinking, temperature, max_output_tokens and verbosity. thinking is how hard the model reasons before answering: none, minimal, low, medium or high. A model that does not reason ignores it.

tags are cost labels. This helps you easily see costs by user, use case, or any other tag you provide.

Update a running session

update changes a session's title, description, custom data, models or voice. New models take over from the next turn, and one that doesn't route is refused. A user's device can only change the title, description and custom data:

val updated = session.update(title = "Pricing")

Fields you leave out stay as they are. Setting sts switches the session to speech-to-speech, and an empty sts switches it back. A session you only have the id of is changed with sessions.update(id, changes), from a device too.

Title, description and review

The router writes some fields for you:

Field Written By
title, description After the first answer, then after every third answer A fast model reading the start of the conversation
review_score, review_notes Once, a few seconds after the session ends A quality model reading the whole conversation
usage When the session ends The router, from every model it called

The title is up to eight words, such as "Add push notifications to an Android app", and the description is one sentence, both in the user's language. A title passed to create is replaced after the first answer; once you set one with update, the router stops renaming the session.

An incognito session gets none of these, and a session nobody spoke in gets no review. Read them with Getting a session.

Delete or Close a session

close ends the conversation and keeps it. delete removes it.

session.close()
session.delete()
// A session you only have the id of: sessions.close(id)

close ends the conversation: with voice on, the agent leaves the call. It is safe to call on a session that has already ended, and keeps what the session recorded and remembered. A session you only have the id of is closed by its id, as the JavaScript, Kotlin, Swift and Dart samples show.

A text session also ends when the last client watching it disconnects. To continue it, resume it by its session id: watching it again (attach in Kotlin and Swift, Sessions.Resume in Go) or asking it something with agent.sessions.responses(id).create(text) reopens it with everything that was said.

delete stops the session if it is running, and deletes its turns and what it remembered. The user's other memories are kept. A session you only hold the id of is deleted with sessions.delete(id). To keep the session and forget only what it remembered, see Memory and persistence.

Voice

voice.start() starts the realtime communication and voice.stop() stops it. The agent talks on a call of the agent call type, which is built into every Stream app.

session.startVoice()

// Joins the call "agent:" + session.id with Stream Video, as the user setUser named.
val voice = VoiceSession.attach(context, agents, session.id)
voice.join()

// When you are done talking. Leaving a call you attached to keeps the session.
voice.leave()
session.stopVoice()

VoiceSession is this device on the session's call. A session created with start_voice: true has voice on from the start.

VoiceSession joins the call with Stream Video, signed in as the user you passed to setUser.

  • Joining:
    • VoiceSession.start(context, agents, options) opens a session with voice on.
    • VoiceSession.attach(context, agents, sessionId) joins one whose voice is already on.
    • join() turns the microphone on, joins, and plays the agent on the speaker. It doesn't throw: if joining fails, the error is in voice.failure. Ask for RECORD_AUDIO before you call it.
    • join(camera = true) also turns the camera on, on the back lens. It needs CAMERA too.
  • During the call: setMuted(muted) and setCameraEnabled(enabled).
  • Leaving: leave() leaves the call, and closes the session only if start opened it. end() always closes it.
  • State: call, isMuted, isCameraEnabled and failure are StateFlows. session is the conversation.

To use the ChatClient and StreamVideo your app already holds, hand them over first with agents.use(client) and agents.use(video), so the session does not open second connections. Stream Video keeps one client per process: one of your own that is signed in as another user makes joining fail.

A phone call is a session too. Each person who rings one of your numbers gets a new session. See accepting calls and making calls.

Voice UI: transcript, captions and status

A voice UI is three pieces: the agent's audio, the transcript with live captions, and a status that says whether the agent is listening, thinking or speaking.

The agent's status is one of these, the states the glow and wave views take:

State When
connecting Until this device has joined.
speaking While the call hears the agent.
listening While the caller is heard or transcribed.
thinking While the agent answers or its skills work, and until its reply is heard.
idle Otherwise, and after leave().

Speaking comes from the call and not from the events. spoke fires when a piece of the reply has been synthesized and sent to the call, not when its audio starts, and responded means the model finished, not that the reply was spoken.

Without the call, session.state says what the agent is doing on any session, typed or spoken: idle, listening, responding, working (with the skills at work) or ended. The state follows the session's socket beside session.events(), so a loop reading events elsewhere is unaffected.

For latency timings, read session.events(): turn carries the turn's timings and spoke its time_to_first_byte_ms.

  • Audio: VoiceSession joins the call and plays the agent on the speaker, so it needs no view of yours.
  • Transcript and captions: session.conversation holds the turns, each reply growing as it is generated. To show the channel instead, open it with session.chat(context) and render it with MessageList from the Compose UI components, as in the quickstart's chat UI.
  • Status: AIVoiceGlow and AIVoiceWave from stream-chat-android-ai-compose take an AIVoiceAgentState. Work it out from the call, which says who is speaking, and from the conversation's state. Read session.events() for latency timings, not for the status or the transcript.
VoiceScreen.kt
import io.getstream.chat.android.ai.compose.ui.component.AIVoiceAgentState
import io.getstream.chat.android.ai.compose.ui.component.AIVoiceGlow
import io.getstream.visionagents.android.core.Conversation
import io.getstream.visionagents.android.core.SessionOptions
import io.getstream.visionagents.android.core.VisionAgents
import io.getstream.visionagents.android.core.VoiceSession

// `agents` has your apiKey and a user from setUser, as in the quickstart.
// Ask for RECORD_AUDIO before the user taps Start.
@Composable
fun VoiceScreen(agents: VisionAgents) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    var voice by remember { mutableStateOf<VoiceSession?>(null) }

    val started = voice
    if (started != null) {
        VoiceConversation(started)
    } else {
        Button(onClick = {
            scope.launch {
                // The agent joins the session's call right away.
                voice = VoiceSession.start(context, agents, SessionOptions(agent = "my-agent"))
            }
        }) { Text("Start") }
    }
}

@Composable
fun VoiceConversation(voice: VoiceSession) {
    val scope = rememberCoroutineScope()
    val conversation by voice.session.conversation.collectAsStateWithLifecycle()

    // Joins from this device, with the microphone on and the agent on the speaker.
    LaunchedEffect(voice) { voice.join() }

    Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(16.dp)) {
        VoiceStatus(voice, conversation.state)
        // The transcript, with each reply growing as it is generated.
        LazyColumn(Modifier.weight(1f)) {
            items(conversation.turns) { turn -> Text(turn.text) }
        }
        // Leaves the call and ends the session start() opened.
        Button(onClick = { scope.launch { voice.leave() } }) { Text("Hang up") }
    }
}

/** What the agent is doing, in the states the glow takes. */
@Composable
fun VoiceStatus(voice: VoiceSession, session: Conversation.State) {
    val call by voice.call.collectAsStateWithLifecycle()
    // The call's participants that are speaking, this device's user included.
    val speakers by remember(call) { call?.state?.activeSpeakers ?: MutableStateFlow(emptyList()) }
        .collectAsStateWithLifecycle()

    val state = when {
        call == null -> AIVoiceAgentState.Connecting
        // Speaking comes from the call: a reply is written before it is spoken.
        speakers.any { !it.isLocal } -> AIVoiceAgentState.Speaking
        speakers.any { it.isLocal } -> AIVoiceAgentState.Listening
        else -> when (session) {
            Conversation.State.Listening -> AIVoiceAgentState.Listening
            Conversation.State.Responding, is Conversation.State.Working -> AIVoiceAgentState.Thinking
            Conversation.State.Idle, Conversation.State.Ended -> AIVoiceAgentState.Idle
        }
    }
    AIVoiceGlow(state = state, modifier = Modifier.size(240.dp))
}

To let the caller cut the agent off, call session.interrupt(). voice.leave() ends the session start opened. To keep the conversation going in writing instead, join with VoiceSession.attach(context, agents, sessionId) and call session.stopVoice() after leave().

AgentSession exposes conversation as a StateFlow, so a composable collecting it redraws as its state changes. Read latency timings from event.fields.

Listing & Searching sessions

sessions.query lists an agent's sessions, including ended ones. It works like other Stream queries, with a filter, sort, limit and cursor. sessions.get reads one session by id.

Getting a session

sessions.get reads one session, running or ended. Once it has ended, your backend is also told how it went: a review and what it cost.

val session = agent.sessions.get(id)
println("${session.title} ${session.state} ${session.modality}")
// The review and usage are only given to your backend.
Field What it says
title, description, custom, project_id Your labels, or the ones the router wrote for you
state live while the agent holds it, ended after
modality text, voice, or video once the agent has seen the user's video
llm, stt, tts, voice The models and voice routing picked, while it is running
created_at, last_response_at, closed_at When it began, last answered and ended
review_score, review_notes How well the agent handled it, from 1 to 5, and why
usage input_tokens (with cached_input_tokens), output_tokens, requests and cost_micros, in millionths of a dollar, over every model it called, typed and spoken

usage is filled in once the session has ended, and the review a few seconds later. A session nobody spoke in has no review. These three fields are only given to your backend, so a user's device asks your backend for them.

Querying

For example, the ended sessions of the support project in October:

val page = agent.sessions.query(
    SessionQuery(
        projectId = "support",
        state = Session.State.Ended,
        createdSince = Instant.parse("2026-10-01T00:00:00Z"),
        createdBefore = Instant.parse("2026-11-01T00:00:00Z"),
        sort = SessionQuery.Sort.UpdatedAt,
        limit = 20,
    ),
)
val sessions = page.items

Every condition in the filter has to match:

Field Matches
project_id The project the session belongs to
agent_id, config_id The agent id or config the session ran under
user_id Whose session it is (backend only)
modality text, voice or video
state live or ended
custom Sessions with all of these labels, such as { ticket: "4721" }
created_at A time range, with $gte and $lt
text A search, with $q

Sessions come back most recently active first (updated_at). A text search comes back best match first (relevance).

Searching

Search with a text condition. It matches the title, description, project and agent name, not what was said, and can't be combined with project_id:

val found = agent.sessions.search(
    "order 1042",
    SessionQuery(state = Session.State.Ended, limit = 5),
)
val one = agent.sessions.get(found.items.first().id)

sessions.search("order 1042") is a shortcut for the same query. Incognito sessions are never searchable.

What comes back are records, not live sessions: most of them are over. Read their turns with sessions.responses(id) (see Reading Responses and History), or continue one with a fork or by resuming it by its id.

Pagination

Results come back a page at a time as { items, has_more, next_cursor }: 25 by default, up to 200 with limit. When has_more is true, pass next_cursor back as cursor with the same filter and sort:

val query = SessionQuery(projectId = "support", limit = 50)

val page1 = agent.sessions.query(query)

val cursor = page1.nextCursor
if (page1.hasMore && cursor != null) {
    val page2 = agent.sessions.query(query.copy(cursor = cursor))
}

A session's turns page the same way, with limit and cursor on responses.list and on the items; items.all() and items.unwind() follow the cursor for you.

Info:

Filter field names are the same in every SDK. The page fields follow each SDK's casing, such as nextCursor in Kotlin and Swift and NextCursor in Go.

Fork, Rewind & Interrupt

Fork

fork continues a conversation as a new session, with the parent's history carried across. The usual reason is to ask the same question of a different model or a different agent without losing the original answer. The parent is untouched and keeps running if it was.

val forked = session.fork(
    ForkOptions(
        modelOverwrites = ModelOverwrites(llm = "llm-thinking"),
        title = "Order 1042, thinking harder",
    ),
)
// A fork comes back as a record: attach opens it as a live session, as it does any session by id.
val harder = agents.attach(forked.id)

val fromThere = session.fork(ForkOptions(responseId = turns.first().id))
val fresh = session.fork(ForkOptions(withoutHistory = true))

Anything you name overrides what the parent was opened with: agent, title, description, project_id, custom, model_overwrites and incognito. response_id carries the history only up to the end of that response, and messages: false starts the same configuration over with no history. A fork writes its own transcript, so the two conversations never interleave.

A fork is always held in writing, even of a session with voice on: talking to two agents at once is not a conversation. Start voice on the fork to talk to it. An incognito session cannot be forked, because nothing was recorded to fork from.

Rewind

responses.rewind goes back to a response and carries on from there, as though nothing after it was said. It takes the response, any item of it, or its id.

session.responses.rewind(turns.first())

Rewinding abandons the reply being spoken and marks every later response rewound, so they drop out of the list and the items. It needs a recorded history it can cut, so it is refused for an incognito session, a native speech-to-speech one, and a session that keeps its conversation in Stream Chat, whose channel would bring the later turns back. Fork that session at the response instead.

Interrupt

interrupt() abandons the reply being spoken. It goes over the socket a watched session holds open to the backend, alongside the other live calls: what the conversation does arrives on it as events, and you can send it text.

Method What it does
responses.create(text) Answer the text through the model, as though it had been said
say(text) Speak or write the text as it is, without the model. For a greeting you already know
interrupt() Abandon the reply being spoken
events() Everything the conversation does, until it ends
val answer = launch {
    session.events()
        .dropWhile { it.type != "responding" }
        .takeWhile { it.type != "responded" }
        .collect { if (it.type == "response_delta") print(it.text) }
}
session.say("Hi, I can help with your order.")
session.responses.create("Where is order 1042?")
answer.join()

session.interrupt()

By default, what say sends waits for the reply in progress to finish.

The events you will use most are response_delta (a fragment of the answer), responded (the answer is complete; pending_work stays true while tools or delegated work are outstanding), heard (what the caller said, on a call), tool_call and tool_ran, error and left (the session ended). Your SDK answers tool_call for you by running the tool you registered.

responses.create returns the turn's id, so you can follow one particular question.

Backend vs Client side

Client side you can only read sessions for the authenticated user. On the backend you can search and query all sessions, so you can build your admin screens. To filter for a specific user on the backend, simply pass the user_id param on query sessions.