Creating responses API

responses.create asks the agent something in writing. It works on any running session, a chat or a call, and the agent answers as though the text had been said. On a call the answer is spoken; in a chat it is written.

It returns as soon as the agent has started answering, with the id of the turn. Follow the answer on the session's events, or read the turn back from its items once it is done.

The router gives the turn no id in three cases: an incognito session, which records nothing; a speech-to-speech session, whose model decides what a turn is; and the retry of a request id it already took. A turn with no id has no items of its own, so follow it on the session's events, or read the whole session's with responses.items.

Send a text message

ReactReact Native
await session.responses.create("Where is order 1042?");

for await (const event of session.events()) {
  if (event.kind === "response_delta") console.log(event.text);
  if (event.kind === "responded") break;
}
Kotlin
// Polled over HTTP, so it needs no socket.
val session = agents.agent("my-agent").sessions.create(SessionOptions(watch = false))
val responses = agents.sessions.responses(session.id)

val turn = responses.create("Where is order 1042?")
var status = turn.status
while (status == AgentResponse.Status.Running) {
    delay(500)
    status = responses.list().items.find { it.id == turn.id }?.status ?: status
}

val answer = responses.items(turn.id).items
    .filter { it.kind == ResponseItem.Kind.Answer }
    .joinToString("") { it.text }
Swift
let session = try await agents.agent("my-agent").sessions.create()
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 }
}
Dart
// Polled over HTTP, so it needs no socket.
final session = await agents
    .agent('my-agent')
    .sessions
    .create(const SessionOptions(watch: false));
final responses = agents.sessions.responses(session.id);

final turn = await responses.create('Where is order 1042?');
var status = turn.status;
while (status == ResponseStatus.running) {
  await Future<void>.delayed(const Duration(milliseconds: 500));
  final turns = await responses.list();
  status = turns.items.firstWhere((each) => each.id == turn.id, orElse: () => turn).status;
}

final answer = (await responses.items(responseId: turn.id)).items
    .where((item) => item.kind == ItemKind.answer)
    .map((item) => item.text)
    .join();

A browser or phone that opens its own session, as in the quickstart, watches it too, so events() works there. A session opened with watch: false is not watched: it reads the turn back with responses.items instead.

Incognito sessions

An incognito session records nothing, so its answers exist only on the session's events. POST /v1/agents/sessions/{id}/responses on one answers 202 with an empty id, and the turn has no items to read back. Read the answer from events(), as in the samples above, never from the turn's items.

In Go, turn.Items.All and turn.Items.List fail with ErrUnnamedTurn when the turn has no id. The Python SDK doesn't check yet: there, a turn's items come back empty for an incognito session, so read session.events(). The same empty id comes back for a turn on a speech-to-speech session, and for a retried request_id; those sessions still record their turns, which responses.items reads.

Send an image

Info:

A session kept in Stream Chat, which is every session that isn't incognito, takes images as base64 data URIs only. The router uploads them to the conversation's channel and shows them on the user's message, and refuses a URL. An incognito session also takes an http(s) URL.

Pass images next to the text, at most 8. Each image is a base64 data URI such as data:image/jpeg;base64,... for a picture you hold in memory or on disk, or, in an incognito session, an http(s) URL the backend can fetch. JPEG, PNG, WebP and GIF are accepted. detail is optional and one of auto, low or high; high costs more and reads small print better.

React Native
import * as ImagePicker from "expo-image-picker";

// A photo the user picked, as a data URI. A session kept in Stream Chat takes data URIs only:
// the router shows them on the user's message.
const picked = await ImagePicker.launchImageLibraryAsync({
  base64: true,
  mediaTypes: ["images"],
  quality: 0.7,
});
const asset = picked.assets?.[0];
if (asset?.base64) {
  const photo = `data:${asset.mimeType ?? "image/jpeg"};base64,${asset.base64}`;
  await session.responses.create("Which order is this receipt for?", {
    images: [{ url: photo, detail: "high" }],
  });
}
React
// A photo the user picked in an <input type="file">, as a data URI. A session kept in
// Stream Chat takes data URIs only: the router shows them on the user's message.
const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
const file = input.files![0]!;
const photo = await new Promise<string>((resolve, reject) => {
  const reader = new FileReader();
  reader.onload = () => resolve(reader.result as string);
  reader.onerror = () => reject(reader.error);
  reader.readAsDataURL(file);
});

await session.responses.create("Which order is this receipt for?", {
  images: [{ url: photo, detail: "high" }],
});
Kotlin
// Two receipts the user photographed, as JPEG data URIs. A session kept in Stream Chat takes
// data URIs only: the router shows them on the user's message, and refuses a URL.
val receipts = listOf("receipt-1041.jpg", "receipt-1042.jpg").map { file ->
    "data:image/jpeg;base64," + Base64.encodeToString(File(file).readBytes(), Base64.NO_WRAP)
}

responses.create(
    "Which of these two receipts is for order 1042?",
    images = listOf(
        ImageSource(receipts[0]),
        ImageSource(receipts[1], ImageSource.Detail.High),
    ),
)
Swift
// Two receipts the user photographed (UIImages), as JPEG data URIs. A session kept in
// Stream Chat, which is every text session a phone opens unless it's incognito, takes
// data URIs only: the router shows them on the user's message, and refuses a URL.
let receipts = [receipt1041, receipt1042].map { photo in
    "data:image/jpeg;base64," + photo.jpegData(compressionQuality: 0.8)!.base64EncodedString()
}

_ = try await session.responses.create(
    "Which of these two receipts is for order 1042?",
    images: [
        ImageSource(url: receipts[0]),
        ImageSource(url: receipts[1], detail: .high),
    ]
)
Dart
import 'dart:convert';
import 'dart:io';

// Two receipts the user photographed, as JPEG data URIs. A session kept in Stream Chat takes
// data URIs only: the router shows them on the user's message, and refuses a URL.
final receipts = [
  for (final path in ['receipt-1041.jpg', 'receipt-1042.jpg'])
    'data:image/jpeg;base64,${base64Encode(await File(path).readAsBytes())}',
];

await session.responses.create('Which of these two receipts is for order 1042?', images: [
  AgentImage(receipts[0]),
  AgentImage(receipts[1], detail: 'high'),
]);
Node.js only

From your server, a session not kept in Stream Chat also takes an image by URL:

import { readFile } from "node:fs/promises";

const photo = (await readFile("receipt.jpg")).toString("base64");

await session.responses.create(
  "Which of these two receipts is for order 1042?",
  {
    images: [
      { url: "https://example.com/receipts/1041.png" },
      { url: `data:image/jpeg;base64,${photo}`, detail: "high" },
    ],
  },
);

The pictures go to the agent's subagent, which needs a model that can see, such as the vlm route. The conversation model gets the question and, once the subagent has looked, its findings; it never sees the pixels. So the turn takes a little longer than a text-only one. In a conversation kept in Stream Chat, the router also uploads the pictures to the channel and shows them on the person's message.

Send a video

Pass recorded clips next to the text, such as a customer's video of a parcel that arrived damaged. A response takes at most two clips. Each clip is either an http(s) URL the backend can fetch, or a base64 data URI such as data:video/mp4;base64,... for a file on disk. MP4, MOV, 3GP, MKV and WebM are accepted, up to 50 MB each. The agent sees 8 frames spread evenly across each clip; set max_frames up to 32 for a longer one.

$STREAM_ACCELERATION_URL is your router's URL, $SERVER_TOKEN is a server token, and $SESSION_ID is the ID of the session that answers.

Not in the Node.js SDK yet. Showing cURL.

Not in the Python SDK yet. Showing cURL.

Not in the Ruby SDK yet. Showing cURL.

Not in the PHP SDK yet. Showing cURL.

Not in the .NET SDK yet. Showing cURL.

Go
clip, err := client.ClipFile("unboxing.mp4")
if err != nil {
	log.Fatal(err)
}

_, err = session.Responses.Create(ctx, "Which of these clips shows order 1042 arriving damaged?",
	client.Clip{URL: "https://example.com/returns/1042.mp4", MaxFrames: 16},
	clip,
)
Rust
use base64::{Engine, engine::general_purpose::STANDARD};
use vision_agents::types::{CreateResponseRequest, VideoSource};

let clip = STANDARD.encode(std::fs::read("unboxing.mp4")?);

session
    .responses
    .create_with(&CreateResponseRequest {
        text: "Which of these clips shows order 1042 arriving damaged?".into(),
        videos: Some(vec![
            VideoSource { url: "https://example.com/returns/1042.mp4".into(), max_frames: Some(16) },
            VideoSource { url: format!("data:video/mp4;base64,{clip}"), max_frames: None },
        ]),
        ..Default::default()
    })
    .await?;
cURL
curl -X POST "$STREAM_ACCELERATION_URL/v1/agents/sessions/$SESSION_ID/responses" \
  -H "api_key: $STREAM_API_KEY" -H "stream-auth-type: jwt" \
  -H "Authorization: Bearer $SERVER_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"text": "Which of these clips shows order 1042 arriving damaged?", "videos": [{"url": "https://example.com/returns/1042.mp4", "max_frames": 16}]}'
Info:

The Go and Rust SDKs take videos. From the others, send videos in the body of POST /v1/agents/sessions/{id}/responses, as in the cURL sample.

The backend samples each clip into frames, each with the moment it was taken. It shows the frames to the agent's subagent when the agent has one, and otherwise to its conversation model. That model needs to see images, such as gemini/gemini-3.8-flash.

Send a voice note

Pass a recording of what the person asked, such as a voice message they held the mic button for, as audio. The router transcribes it before the turn starts, and the agent answers what was said, after any text sent with it, so the text may be empty. A response takes one voice note. It is either an http(s) URL the backend can fetch, or a base64 data URI such as data:audio/mp4;base64,... for a recording in memory or on disk, at most 8 MiB either way. The usual recording formats are accepted, such as M4A, WebM, Ogg, MP3 and WAV. The router reads the kind from the bytes, so a WebM or MP4 recording counts as audio even when it is labelled as video.

This is the body of POST /v1/agents/sessions/{id}/responses with a voice note as a data URI:

{
  "text": "",
  "audio": {
    "url": "data:audio/mp4;base64,AAAAIGZ0eXBNNEEgAAAAAE00QSBtcDQyaXNvbQ..."
  },
  "request_id": "9b2f6c1e-4d7a-4b8e-a5f3-2c1d0e9f8a7b"
}
  • text is required, and may be the empty string when the voice note carries the whole question.
  • audio is one object with a single url, not an array.
  • request_id is one fresh id per question, of letters, digits, - and _. A conversation kept in Stream Chat needs it, and with it the router uploads the voice note to the channel and shows it on the person's message. A session not kept in Stream Chat ignores it. The SDKs send one for you.

Not in the Node.js SDK yet. Showing cURL.

Not in the Python SDK yet. Showing cURL.

Not in the Ruby SDK yet. Showing cURL.

Not in the PHP SDK yet. Showing cURL.

Not in the .NET SDK yet. Showing cURL.

Go
note, err := os.ReadFile("question.m4a")
if err != nil {
	log.Fatal(err)
}

_, err = session.Responses.Create(ctx, "",
	client.VoiceNote{URL: "data:audio/mp4;base64," + base64.StdEncoding.EncodeToString(note)},
)
Rust
use base64::{Engine, engine::general_purpose::STANDARD};
use vision_agents::types::{AudioSource, CreateResponseRequest};

let note = STANDARD.encode(std::fs::read("question.m4a")?);

session
    .responses
    .create_with(&CreateResponseRequest {
        text: String::new(),
        audio: Some(AudioSource { url: format!("data:audio/mp4;base64,{note}") }),
        ..Default::default()
    })
    .await?;
cURL
printf '{"text": "", "audio": {"url": "data:audio/mp4;base64,%s"}, "request_id": "%s"}' \
  "$(base64 < question.m4a | tr -d '\n')" "$(uuidgen)" > voice-note.json

curl -X POST "$STREAM_ACCELERATION_URL/v1/agents/sessions/$SESSION_ID/responses" \
  -H "api_key: $STREAM_API_KEY" -H "stream-auth-type: jwt" \
  -H "Authorization: Bearer $SERVER_TOKEN" \
  -H "Content-Type: application/json" \
  --data-binary @voice-note.json

The cURL sample writes the body to a file first, because a recording of a minute or more is too long to pass on the command line. $STREAM_ACCELERATION_URL, $SERVER_TOKEN and $SESSION_ID are as in Send a video.

Info:

The Go and Rust SDKs take a voice note. The JavaScript SDK's responses.create doesn't take one yet. From JavaScript and the other SDKs, send audio in the body of POST /v1/agents/sessions/{id}/responses, as in the cURL sample.

The note is transcribed in the agent's languages, and the question the agent answers is the typed text, then what was said. In a conversation kept in Stream Chat, the person's message carries the transcript and shows the voice note. A note that isn't audio, is over 8 MiB or has no words in it is a 400, and no turn starts. So is a voice note to an agent in a region where the deployment transcribes nothing.

Send a PDF or Word document

Pass a file with the question, such as a contract the person wants explained, and the agent answers from it. A response takes one file: a PDF or a Word document (DOCX or DOC). It is either an http(s) URL the backend can fetch, at most 20 MiB, or a base64 data URI such as data:application/pdf;base64,..., at most 8 MiB. The router tells the format from the bytes, so the type in the data URI doesn't matter. name is what the file is called, shown on the person's message and to the model. Left out, it's the last part of the URL, or document for a data URI.

This is the body of POST /v1/agents/sessions/{id}/responses with a PDF as a data URI:

{
  "text": "What is the notice period in this contract?",
  "files": [
    {
      "url": "data:application/pdf;base64,JVBERi0xLjcKCjEgMCBvYmoKPDwvVHlwZS9DYXRhbG9n...",
      "name": "lease.pdf"
    }
  ],
  "request_id": "4c8e2a7d-1f3b-4e9a-b6d5-8a0c7e2f1b3d"
}

Not in the Node.js SDK yet. Showing cURL.

Not in the Python SDK yet. Showing cURL.

Not in the Ruby SDK yet. Showing cURL.

Not in the PHP SDK yet. Showing cURL.

Not in the .NET SDK yet. Showing cURL.

Go
lease, err := client.DocumentFile("lease.pdf")
if err != nil {
	log.Fatal(err)
}

_, err = session.Responses.Create(ctx, "What is the notice period in this contract?", lease)
if err != nil {
	log.Fatal(err)
}

// Or by URL, which the router fetches itself.
_, err = session.Responses.Create(ctx, "And what does the handbook say about notice?",
	client.Document{URL: "https://example.com/policies/handbook.docx", Name: "handbook.docx"},
)
Rust
use base64::{Engine, engine::general_purpose::STANDARD};
use vision_agents::types::{CreateResponseRequest, FileSource};

let lease = STANDARD.encode(std::fs::read("lease.pdf")?);

session
    .responses
    .create_with(&CreateResponseRequest {
        text: "What is the notice period in this contract?".into(),
        files: Some(vec![FileSource {
            url: format!("data:application/pdf;base64,{lease}"),
            name: Some("lease.pdf".into()),
        }]),
        ..Default::default()
    })
    .await?;
cURL
printf '{"text": "What is the notice period in this contract?", "files": [{"url": "data:application/pdf;base64,%s", "name": "lease.pdf"}], "request_id": "%s"}' \
  "$(base64 < lease.pdf | tr -d '\n')" "$(uuidgen)" > question.json

curl -X POST "$STREAM_ACCELERATION_URL/v1/agents/sessions/$SESSION_ID/responses" \
  -H "api_key: $STREAM_API_KEY" -H "stream-auth-type: jwt" \
  -H "Authorization: Bearer $SERVER_TOKEN" \
  -H "Content-Type: application/json" \
  --data-binary @question.json
Info:

The Go SDK takes a file as client.Document, or client.DocumentFile for one on disk, and the Rust SDK as files on create_with. The JavaScript SDK's responses.create doesn't take one yet. From JavaScript and the other SDKs, send files in the body of POST /v1/agents/sessions/{id}/responses, as in the cURL sample.

The router reads the file as text before the turn starts. The agent answers from it on this turn and on every later turn of the conversation: the text goes ahead of the conversation on every reply, so summarising a long chat never drops it. In a conversation kept in Stream Chat, the person's message shows the file.

Who can read it. The file belongs to the person who sent it, in that conversation. The agent reads it again when the same person carries the conversation on or forks it. A conversation opened by anybody else, your server included, never reads it. A file can only be sent in a person's own conversation: it is refused in a thread, in a channel others write in, and in a session a dispatch worker opened for a channel's message. A rewind or an edit to before the turn that brought the file leaves the file out from then on, and bringing that branch back brings the file back.

Scanned pages and pictures. A page that is only a picture, such as a scan, and the charts and pictures in a file, are read with OCR and billed as OCR, at most 10 of them a file. A file with more than 10 scanned pages is refused: send a copy with a text layer. Pages that weren't read are named to the model, so it says it can't see them rather than guessing.

Prompt injection. When your organization's policy sets prompt_injection, the file is screened once, before the turn. A file that reads as an injection is refused with a 400 prompt_injection, and one that can't be screened right now with a 503. Neither is read.

Refusals. Everything that can refuse a file does so before the turn starts, so no turn is answered or billed:

Status Code When
413 document_too_large Over 8 MiB as a data URI or 20 MiB by URL, over 100 pages, more than 10 scanned pages, more text than the conversation has room for (see below), or longer than 20 seconds to read.
400 document_unreadable The file needs a password, is damaged, or has no text in it.
415 unsupported_media_type The file is not a PDF or a Word document.
400 invalid_request A URL that can't be fetched, a data URI that isn't base64 with a type, a file and a voice note in the same response, a file in a thread or a shared conversation, or a file sent to a speech-to-speech session.
402 spend_limit_reached, insufficient_credits Reading scanned pages or screening the file would go over a spend limit, or the organization has no credit left.

The files of one conversation hold at most 120,000 characters of text together, or a quarter of the conversation model's context window, counted at 3 characters a token, when that is smaller, because every reply is sent all of them. A file that doesn't fit in what is left is refused with document_too_large.

Send what the person did in a reply's UI

A reply can be UI the agent writes, such as a plan with a map and a form to change it. When the person does something in it that's for the agent, such as tapping a place or submitting the form, ask with their next message, in their words, and pass what they did as uiAction. It names the reply it came from (message_id, the id of the reply's Stream Chat message), the UI's format and the action (name), with what it carries (payload), in at most 8 KB as JSON.

The client SDKs make it for you: in React, aiUIActionJSON(action) from stream-chat-react/ai-components turns the AIUIAction the person's tap made into it, as the same function from stream-chat-expo/ai-components does in React Native, and on iOS, StreamChatAI's AIUIAction has it as json, as does the AIUIAction of stream-chat-android-ai-compose on Android, and in Flutter the AIUIAction of stream_chat_flutter_ai has it as toJson(). Use the action's label as the text.

React Native
import { aiUIActionJSON } from "stream-chat-expo/ai-components";

// In the AIUIHost's send, with the AIUIAction of the person's tap.
await session.responses.create(action.label, {
  uiAction: aiUIActionJSON(action),
});
React
import { aiUIActionJSON } from "stream-chat-react/ai-components";

// In the AIUIHost's send, with the AIUIAction of the person's tap.
await session.responses.create(action.label, {
  uiAction: aiUIActionJSON(action),
});
Kotlin
// In a coroutine launched from the AIUIHost's send, with the AIUIAction of the person's tap.
session.responses.create(action.label, uiAction = action.json)
Swift
// In the AIUIHost's send, with the AIUIAction of the person's tap.
_ = try await session.responses.create(action.label, uiAction: action.json)
Dart
// In the AIUIHost's send, with the AIUIAction of the person's tap.
await session.responses.create(action.label, uiAction: action.toJson());
Info:

The JavaScript SDK takes uiAction in every version of @stream-io/stream-agents. The Swift, Go and Rust SDKs take it from tag 0.2.0 of the Agents repository, the Flutter SDK from stream_agents 0.7.0, and the Kotlin SDK from io.getstream:stream-agents-android-core 0.2.0. From the others, send ui_action in the body of POST /v1/agents/sessions/{id}/responses.

React (v14) only

aiUIActionJSON comes with stream-chat-react 14.16.0 or later, and works the same in 14 and 15. In stream-chat 9, a message's custom data sits on the message itself, so the person's message below carries the action as message.ai_ui_action.

React Native (v9) only

aiUIActionJSON comes with stream-chat-expo 9.13.0 or later, and works the same in 9 and 10. In stream-chat 9, a message's custom data sits on the message itself, so the person's message below carries the action as message.ai_ui_action.

The model is told what the person did after their words. In a conversation kept in Stream Chat, the person's message carries the action as custom.ai_ui_action, and the model is also told the opening words of the reply it was in, so the agent knows which reply they acted on when it showed the same UI more than once. An action without a message_id, format or name, or over 8 KB, is a 400, and the question isn't asked. The JavaScript, Flutter, Go and Rust SDKs leave out an empty action, so the question is asked without one.

Set the length and reasoning

Cap one answer with max_output_tokens, or change how long the model thinks before it with reasoning_effort. Both apply to this answer alone, including the replies that finish it after its tools, and the session's own settings come back for the next question.

ReactReact Native
await session.responses.create("Plan my week around these meetings", {
  maxOutputTokens: 800,
  reasoningEffort: "high",
});
Kotlin
session.responses.create(
    "Plan my week around these meetings",
    maxOutputTokens = 800,
    reasoningEffort = "high",
)
Swift
_ = try await session.responses.create(
    "Plan my week around these meetings",
    maxOutputTokens: 800,
    reasoningEffort: "high"
)
Dart
await session.responses.create(
  'Plan my week around these meetings',
  maxOutputTokens: 800,
  reasoningEffort: 'high',
);
Info:

The JavaScript, Kotlin, Swift, Flutter and Go SDKs take these. From the others, send max_output_tokens and reasoning_effort in the body of POST /v1/agents/sessions/{id}/responses.

max_output_tokens counts reasoning too, so leave room for it when you raise the effort. The efforts depend on the model, such as none, low, medium, high or max. One the session's model doesn't take is a 400, and the question isn't asked.

Reading responses and history

A session keeps a record of each turn, called a response, and what happened inside it, called its items. These are read over HTTP, so they work during the conversation, after it has ended, and for a session your process is not holding.

Method What it returns
responses.create(text) Asks something and returns the turn as soon as it has started. See Send a text message
responses.list() The turns, oldest first, a page at a time as { items, has_more, next_cursor }: what was asked, the status (running, completed, ...) and how long it took
responses.items What happened, turn by turn: said, thought, answer, blocked, error and tool calls
responses.rewind(response) Carries on from the end of that response, as though nothing after it was said. See Rewind
ReactReact Native
const { items: turns } = await session.responses.list({ limit: 50 });

for (const item of await session.responses.items.all()) {
  console.log(item.kind, item.text);
}

const old = agent.sessions.responses("96f20176bfc7b3c051b759abf0bcae94");
const lastWeek = (await old.list()).items;
Kotlin
val turns = responses.list(limit = 50).items

responses.unwind().collect { println("${it.kind} ${it.text}") }

val old = agent.sessions.responses("96f20176bfc7b3c051b759abf0bcae94")
val lastWeek = old.list().items
Swift
let turns = try await session.responses.list(limit: 50).items

for try await item in session.responses.unwind() {
    print(item.kind, item.text)
}

let old = agent.sessions.responses("96f20176bfc7b3c051b759abf0bcae94")
let lastWeek = try await old.list().items
Dart
final turns = (await session.responses.list(limit: 50)).items;

await for (final item in session.responses.unwind()) {
  print('${item.kind} ${item.text}');
}

final old = agent.sessions.responses('96f20176bfc7b3c051b759abf0bcae94');
final lastWeek = (await old.list()).items;

Items leave out the answer's fragments, which are on the events; they are the shape of the conversation rather than its keystrokes. An incognito session has no items, because it records nothing. A turn that responses.create returned with no id, on a speech-to-speech session or for a retried request, has none of its own either: responses.items reads the whole session's.

Regenerate and edit

In a conversation kept in Stream Chat, a person can ask for a reply again, or change a question they asked earlier, without leaving the conversation. The earlier versions are kept as branches of the same session, which the person pages through as ‹ 1/2 ›, the way ChatGPT shows them. A branch never shows up as a new conversation.

Method What it does
responses.regenerate(response) Answers that response's question again, as a new reply beside the old one. The old reply and everything after it are hidden and kept as a branch.
responses.edit(response, text) Asks text in place of that response's question, as a new question beside it. The old question and everything after it are hidden and kept as a branch.
responses.siblings(response) The alternatives to a response, oldest first, for a ‹ i/n › control: its regenerations, or with of: "question" the edits of its question.
responses.branch(response) The messages of a hidden branch, shaped as Stream Chat messages, to show in place of the conversation's. Nothing is written to Chat.
responses.activate(response) Makes a hidden branch the conversation again. Call it before asking anything while a hidden branch is shown.
responses.rewind(response) Carries on from the end of that response, and keeps the later turns as a branch. See Rewind.

Not in the Kotlin SDK yet. Showing cURL.

Not in the Swift SDK yet. Showing cURL.

Not in the Flutter SDK yet. Showing cURL.

ReactReact Native
// Answer the question again: the old reply stays as ‹ 1/2 ›.
const again = await session.responses.regenerate(turn.id);
console.log(again.created.branch); // { of: "reply", index: 2, count: 2 }

// Ask something else in place of the question.
await session.responses.edit(turn.id, "Where is order 1043?");

// Page through the alternatives, and show one without changing the conversation.
const { items: replies } = await session.responses.siblings(turn.id);
const shown = await session.responses.branch(replies[0]!.id);

// Bring the one shown back before asking anything else.
await session.responses.activate(replies[0]!.id);
cURL
AUTH=(-H "api_key: $STREAM_API_KEY" -H "stream-auth-type: jwt" -H "Authorization: Bearer $USER_TOKEN")
RESPONSES="$STREAM_ACCELERATION_URL/v1/agents/sessions/$SESSION_ID/responses"

# Regenerate: replaces names the response, and empty text answers its question again.
curl -X POST "$RESPONSES" "${AUTH[@]}" -H "Content-Type: application/json" \
  -d "{\"text\": \"\", \"replaces\": \"$RESPONSE_ID\", \"request_id\": \"$(uuidgen)\"}"

# The alternatives, a hidden branch's messages, and bringing a branch back.
curl "$RESPONSES/$RESPONSE_ID/siblings?of=reply" "${AUTH[@]}"
curl "$RESPONSES/$RESPONSE_ID/branch" "${AUTH[@]}"
curl -X POST "$RESPONSES/$RESPONSE_ID/activate" "${AUTH[@]}"
Info:

The JavaScript and Go SDKs have these methods. From the others, send replaces in the body of POST /v1/agents/sessions/{id}/responses, and call the siblings, branch and activate endpoints, as in the cURL sample.

A regenerate is responses.create with replaces, an earlier response's id, and empty text. Over HTTP, send text as "": the field is required, and a body without it is refused with a 400. An edit is the same with the new question as text. A request_id is required, and images, audio, videos, files and uiAction can't go with replaces.

The response a regenerate or an edit returns has three more fields:

  • branch: where it stands among its alternatives, as { of, index, count }. of is reply for a regenerate and question for an edit, and index counts from 1, oldest first. It is absent when the response is the only one.
  • parent_response_id: the response it was answered after.
  • rewound_to: { message_id, inclusive }, where the channel was rewound to. Drop every message after message_id from what you show, and message_id itself when inclusive is true, so the old and the new answer are never shown together. The JavaScript SDK does this for the session's channel.

siblings lists each alternative with its index, the i of ‹ i/n ›, and active, whether the conversation goes through it now. branch answers active: true and no messages for a response that's already on the conversation, because the channel shows it. activate answers already_active when nothing changed, so a retry is safe.

In the JavaScript SDK, agentChatTransport does all of this for the AI components' AIConversationController: it regenerates and edits. With the React Native controller, it also pages ‹ i/n › with switchBranch and brings the branch shown back before the next question, and the controller offers regenerate and edit on every message that has a branch mark. stream-chat-react has no version switcher yet: its controller offers regenerate on the latest reply and edit on the user's latest message. A regenerate or an edit of a message without a mark is refused with an AgentBranchError whose code is not_branchable. To hide both actions, pass actions: { edit: false, regenerate: false } to the controller.

Rewind

responses.rewind(response) goes back to a response and carries on from there, as though nothing after it was said. In a conversation kept in Stream Chat, it is an edit of the turn after that response, without a new question: that turn and everything after it are hidden in Stream Chat and kept as a branch, which siblings, branch and activate read and bring back. It counts toward the 100 edit and regenerate points, and it is refused in the same cases as an edit. Rewinding to the newest response hides nothing.

A session that recorded nothing can't be rewound: an incognito session, and a session on a speech-to-speech model, which keeps its own context.

Limits and caveats

  • At most 100 edit and regenerate points per conversation. Stream Chat keeps at most 100 separate hidden stretches per channel. Regenerating the same reply again doesn't add one, and editing or regenerating an earlier turn swallows the points after it. Each turn where the person regenerated or edited and then kept chatting adds one, so a normal conversation stays in single digits. Past the limit, a regenerate, an edit, a rewind or an activate is refused with a 409 branch_limit_reached: continue in a new conversation. The conversation keeps working otherwise. Sending and reading are unaffected, and paging through branches never counts.
  • Bringing a branch back sends its messages again. activate sends the branch's messages to Stream Chat again, as new messages with new ids and new created_at values. They fire message.new again, reach webhooks and moderation as new messages, and count as messages. They are sent with skip_push, and each carries custom.resent_from, the id of the message it copies, so your backend can tell them apart. A branch of more than 100 messages can't be brought back: 409 branch_too_long.
  • Memories from abandoned branches are kept. The agent learns from every turn, and nothing it learned is forgotten when a turn is regenerated, edited or switched away from. After an edit, something said on the old branch can still be recalled.
  • Switching branches doesn't retitle the conversation. A title the person set is never changed.
  • Hidden branches still count. They appear, unmarked, in a Stream Chat channel export, and they still count in the channel's message_count. The router's record of the branches is the full transcript.
  • Other devices. A device that didn't make the change receives channel.rewound. In JavaScript, the channel session.chat() opens, and AgentChat, drop the hidden messages and read the channel again when it arrives. A plain stream-chat client doesn't handle it yet: reload the channel's messages yourself when it arrives, as Agent channel rewind describes.
  • Briefly stale reads. For a moment after a rewind, a read of the channel can still return the messages it just hid.
  • Not every turn can be branched. A turn whose messages carry no branch mark, such as one spoken on a call, can't be regenerated or edited, and a rewind that would hide it is refused. Turns sent with responses.create are marked. A response on a hidden branch must be brought back with activate before it is regenerated, edited or rewound to: until then it is a 409. A conversation in a thread, one shared with the members of its channel, one a dispatch worker answers, a session while it is on a call, and a session on a speech-to-speech model can't be branched at all.
  • One change at a time. While an earlier regenerate, edit or switch is unfinished, the next is refused with a 409 switch_unfinished. Try again shortly.
  • Deleting branches. The router's copies of hidden branches are deleted with the session, and when the person's memories are truncated. A branch whose copies were deleted answers 410 branch_unavailable.

Limits

  • An image, video, voice note or file URL must be public: the backend fetches it without credentials, and refuses one that resolves to a private or loopback address.
  • A video URL points at one file. A stream playlist, such as HLS (.m3u8), is refused.