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:

let agents = VisionAgents(apiKey: "your_api_key")
agents.setUser(User(id: "jlahey")) { try await yourBackend.agentToken() }
let agent = agents.agent("myagent")

let session = try await agent.sessions.create()
await session.start()

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.

let events = session.events()
_ = try await session.responses.create("Where is order 1042?")

for await event in events {
    if event.kind == .responseDelta { print(event.text, terminator: "") }
    if event.kind == .responded { break }
}

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() returns a ChatChannelController for the channel. It opens on the ChatClient you handed over with agents.use(_:), 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

var options = SessionOptions()
options.title = "Order 1042"
options.custom = ["ticket": "4721"]
let session = try await agent.sessions.create(options)
await session.start()

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.

var options = SessionOptions()
options.id = "order-1042"
options.title = "Order 1042"
let session = try await agent.sessions.create(options)

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.

var options = SessionOptions()
options.modelOverwrites = ModelOverwrites(llm: "llm-thinking", thinking: .high)
options.tags = ["customer_id": "123", "plan": "pro"]
options.incognito = true
let session = try await agent.sessions.create(options)

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:

let updated = try await 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.

await session.close()
try await session.delete()
// A session you only have the id of: agents.close(sessionID:)

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.

try await session.startVoice()

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

// When you are done talking. Leaving a call you attached to keeps the session.
await voice.leave()
try await 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(agents:agent:) opens a session with voice on.
    • VoiceSession.attach(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, for example when the user denies the microphone, the error is in voice.failure.
    • join(camera: true) also turns the camera on, on the back lens where there is one.
  • During the call: setMuted(_:) and setCameraEnabled(_:).
  • Leaving: leave() leaves the call, and closes the session only if start opened it. end() always closes it.
  • State: VoiceSession is an ObservableObject that publishes call, isMuted, isCameraEnabled and failure. session is the conversation.

To use the ChatClient and StreamVideo your app already holds, hand them over first with agents.use(_:), so the session does not open second connections. An app with a StreamVideo of its own must hand it over: another one would become the instance Stream's call views and CallKit read. The quickstart builds a voice UI on VoiceSession.

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: show session.chat()'s channel with AIConversationView from StreamChatAI, through the AgentChat of the quickstart's chat UI. It streams the agent's replies in with markdown and shows the agent thinking.
  • Status: AIVoiceGlowView and AIVoiceWaveView from StreamChatAI take an AIVoiceAgentState. Work it out from the call, which says who is speaking, and from session.state. Read session.events() for latency timings, not for the status or the transcript.
VoiceScreen.swift
import StreamChatAI
import StreamVideo
import SwiftUI
import VisionAgentsCore

// `agents` has your apiKey and a user from setUser, and `openChat(for:)` and `AgentChat`
// are the chat UI's, as in the quickstart.
struct VoiceScreen: View {
    let agents: VisionAgents
    @State private var started: (voice: VoiceSession, chat: AgentChat)?

    var body: some View {
        if let started {
            VoiceConversation(voice: started.voice, chat: started.chat)
        } else {
            Button("Start") {
                Task { started = try? await start() }
            }
        }
    }

    private func start() async throws -> (voice: VoiceSession, chat: AgentChat) {
        // The agent joins the session's call right away.
        let voice = try await VoiceSession.start(agents: agents, agent: "my-agent")
        // The session's socket, which follows what the agent is doing.
        await voice.session.start()
        return (voice, try await openChat(for: voice.session))
    }
}

struct VoiceConversation: View {
    @ObservedObject var voice: VoiceSession
    @ObservedObject var chat: AgentChat

    var body: some View {
        VStack(spacing: 16) {
            if let call = voice.call {
                VoiceStatus(voice: voice, call: call.state)
            } else {
                AIVoiceGlowView(state: .connecting)
                    .frame(width: 240, height: 240)
            }
            // The transcript, with each reply streaming in as it is generated.
            // No composer while voice is on: a typed turn on a call is not marked
            // finished, and the next responses.create is refused.
            AIConversationView(messages: chat.messages)
            // Leaves the call and ends the session start() opened.
            Button("Hang up", role: .destructive) {
                Task { await voice.leave() }
            }
        }
        // Joins from this device, with the microphone on and the agent on the speaker.
        .task { await voice.join() }
    }
}

/// What the agent is doing, in the states the glow takes.
struct VoiceStatus: View {
    @ObservedObject var voice: VoiceSession
    // The call's participants, and which of them is speaking.
    @ObservedObject var call: CallState

    var body: some View {
        AIVoiceGlowView(state: state)
            .frame(width: 240, height: 240)
    }

    private var state: AIVoiceAgentState {
        // Speaking comes from the call: a reply is written before it is spoken.
        if call.remoteParticipants.contains(where: \.isSpeaking) { return .speaking }
        if call.localParticipant?.isSpeaking == true { return .listening }
        switch voice.session.state {
        case .listening: return .listening
        case .responding, .working: return .thinking
        case .idle, .ended: return .idle
        }
    }
}

AIConversationView leaves out a reply with nothing to show, such as one the caller cut off whose text was cleared. To style spoken turns, interrupted replies or a reply still being generated, read those custom fields from the message's extraData in your AIMessage, as AgentMessage reads generating, and pass AIConversationView a view factory. 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(agents:sessionID:) and call session.stopVoice() after leave(). Add a microphone usage description to your Info.plist.

AgentSession is an ObservableObject, so a view observing the session 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.

let session = try await agent.sessions.get(id)
print(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:

var query = SessionQuery(limit: 20)
query.projectID = "support"
query.state = .ended
query.createdSince = try Date("2026-10-01T00:00:00Z", strategy: .iso8601)
query.createdBefore = try Date("2026-11-01T00:00:00Z", strategy: .iso8601)
let page = try await agent.sessions.query(query)
let 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:

var query = SessionQuery(limit: 5)
query.state = .ended
let found = try await agent.sessions.search("order 1042", query)
let one = try await agent.sessions.get(found.items[0].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:

var query = SessionQuery(limit: 50)
query.projectID = "support"

let page1 = try await agent.sessions.query(query)

if page1.hasMore, let cursor = page1.nextCursor {
    query.cursor = cursor
    let page2 = try await agent.sessions.query(query)
}

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.

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

let fromThere = try await session.fork(ForkOptions(responseID: turns[0].id))

var fromNothing = ForkOptions()
fromNothing.withoutHistory = true
let fresh = try await session.fork(fromNothing)

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.

try await session.responses.rewind(to: turns[0].id)

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
let events = session.events()
// say(_:interrupt: true) stops the reply in progress first.
try await session.say("Hi, I can help with your order.")
_ = try await session.responses.create("Where is order 1042?")

for await event in events {
    if event.kind == .responseDelta { print(event.text, terminator: "") }
    if event.kind == .responded { break }
}

// interrupt(requestID:) stops only the reply answering that request, the request_id on its events.
try await 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.