Generative UI

An agent can answer with UI rather than text: a weekend plan with a map of the places, a tab for each day and a form to change the pace. The agent writes the UI into its reply, the router carries it to Stream Chat beside the reply's words, and your app shows it in place of them. What the person does in it comes back to the agent with their next message.

The router knows no UI format. The model writes the UI in a format your app has a renderer for, such as A2UI or OpenUI, and the router passes it on as it is.

How the agent writes UI

The model writes the UI in a fenced block of its reply. The block's info string is ui:<format>, or ui:<format>@<version> to name the format's version, such as ui:a2ui@1.0. OpenUI's own fence, openui-lang, is read as the openui format, since that's the fence OpenUI's prompts ask models for:

Here's a weekend in Ohrid, with a map and a plan for each day.

```openui-lang
root = Card([title, map])
title = CardHeader("A weekend in Ohrid")
```

The first such block is the reply's UI, and any later one is left out of its text. Only the agent writes UI: a block in a person's message stays part of their words.

The router only treats a block as UI when its fence starts a line and uses one of these names. Anything else stays in the reply's text, so a sentence that mentions UI, or an ordinary code block, isn't mistaken for UI.

React

The model writes UI when the agent's instructions ask it to: add the format's own instructions, with the components of your app it may place, to the agent's instructions.md. stream-chat-react writes those instructions from the same components your app shows. The capabilities() of the app's AIUIHost hold, for each format it reads, the fence the model writes in and the instructions for the model:

// Each format the host reads, such as A2UI and OpenUI, with its `fence` and `instructions`.
const { renderers } = await ui.capabilities();
console.log(JSON.stringify(renderers, null, 2));

The page can't change the agent, so print them while you build the app and add them to instructions.md, or send them to your server and have it add them. Write them again when your components change. You can also write them on your server or at build time, from the same component definitions:

import { a2uiInstructions } from "stream-chat-react/a2ui";
import { openUIInstructions } from "stream-chat-react/openui";

const a2ui = await a2uiInstructions({ components: [placeCard] });
const openui = await openUIInstructions([placeCard]);
Warning:

OpenUI's own instructions, which openUIInstructions and the OpenUI renderer's capabilities() return, tell the model its entire reply must be openui-lang, with no Markdown or explanations. With OpenUI's chat library they're about 53 KB, sent on every turn. For an agent that answers in prose and adds a card only when it helps, describe the UI in agent.yaml instead.

See Tell the agent what the app shows in the React guide.

React (v14) only

The same code runs on stream-chat-react 14.16.0 or later, which brought generative UI and stream-chat-react/a2ui and stream-chat-react/openui. See Tell the agent what the app shows in the React v14 guide.

React Native

The model writes UI when the agent's instructions ask it to: add the format's own instructions, with the components of your app it may place, to the agent's instructions.md. The Chat SDK writes those instructions from the same components your app shows, for A2UI, the format it renders on React Native. The capabilities() of the app's AIUIHost hold the fence the model writes in and the instructions for the model:

// Each format the host reads, A2UI on React Native, with its `fence` and `instructions`.
const { renderers } = await ui.capabilities();
console.log(JSON.stringify(renderers, null, 2));

The app can't change the agent, so print them while you build the app and add them to instructions.md, or send them to your server and have it add them. Write them again when your components change. You can also write them at build time, from the same component definitions:

import { a2uiInstructions } from "stream-chat-expo/a2ui";

const a2ui = await a2uiInstructions({ components: [placeCard] });

See Tell the agent what the app shows in the React Native guide.

React Native (v9) only

The same code runs on stream-chat-expo 9.13.0 or later, which brought generative UI. See Tell the agent what the app shows in the v9 guide.

Swift

The model writes UI when the agent's instructions ask it to: add the format's own instructions, with the components of your app it may place, to the agent's instructions.md. StreamChatAI writes those instructions from the same components your app shows. The capabilities of the app's AIUIHost hold, for each format it reads, the fence the model writes in and the instructions for the model: what you gave the renderer as its instructions, then the format's own, written from its components, yours and the host's tools:

// The instructions of each format the host reads, such as A2UI's and OpenUI's.
let instructions = (ui.capabilities["renderers"]?.arrayValue ?? [])
    .compactMap { $0.dictionaryValue?["instructions"]?.stringValue }

The app can't change the agent, so write them into a file from a unit test of your app, add them to instructions.md and sync the agent, or send them to your server and have it add them. The test builds the same host as the app and runs on the simulator, which writes to your Mac, so the file lands in your repository. Write the instructions from a test in the iOS guide shows it. Write them again when your components change. A renderer's instructions parameter is where to say which answers to write as UI and when to use your components:

A2UIRenderer(instructions: "Write a trip plan as UI, with a place_card for each place. Answer everything else in Markdown.")

A2UI's capabilities also hold the catalog_id of the catalog with your components, getstream.io:app-catalog by default (the renderer's catalogId changes it). See Tell the agent what the app shows in the iOS guide.

Kotlin

The model writes UI when the agent's instructions ask it to: add the format's own instructions, with the components of your app it may place, to the agent's instructions.md. stream-chat-android-ai-compose writes those instructions from the same components your app shows. The capabilities of the app's AIUIHost hold, as plain Kotlin values, for each format it reads, the fence the model writes in and the instructions for the model: what you gave the renderer as its instructions, then the format's own, written from its components, yours and the host's tools:

// The instructions of each format the host reads, such as A2UI's and OpenUI's.
val instructions: List<String> = (ui.capabilities["renderers"] as? List<*>).orEmpty()
    .mapNotNull { renderer -> (renderer as? Map<*, *>)?.get("instructions") as? String }

The app can't change the agent, so print them while you build the app and add them to instructions.md, or send them to your server and have it add them. Write them again when your components change. A renderer's instructions parameter is where to say which answers to write as UI and when to use your components:

val renderer: A2UIRenderer = A2UIRenderer(
    instructions = "Write a trip plan as UI, with a place_card for each place. Answer everything else in Markdown.",
)

A2UI's capabilities also hold the catalog_id of the catalog with your components, getstream.io:app-catalog by default (the renderer's catalogId changes it). See Tell the agent what the app shows in the Android guide.

Dart

The model writes UI when the agent's instructions ask it to: add the format's own instructions, with the components of your app it may place, to the agent's instructions.md. stream_chat_flutter_ai writes those instructions from the same components your app shows. The capabilities of the app's AIUIHost hold, as plain Dart values, for each format it reads, the fence the model writes in and the instructions for the model: what you gave the renderer as its instructions, then the format's own, written from its components, yours and the host's tools:

// The instructions of each format the host reads, such as A2UI's and OpenUI's.
final instructions = [
  for (final renderer in ui.capabilities['renderers'] as List<Object?>? ?? const [])
    if (renderer case {'instructions': final String text}) text,
];

The app can't change the agent, so print them while you build the app and add them to instructions.md, or send them to your server and have it add them. Write them again when your components change. A renderer's instructions parameter is where to say which answers to write as UI and when to use your components:

final renderer = A2UIRenderer(
  instructions: 'Write a trip plan as UI, with a place_card for each place. Answer everything else in Markdown.',
);

A2UI's capabilities also hold the catalog_id of the catalog with your components, getstream.io:app-catalog by default (the renderer's catalogId changes it). See Tell the agent what the app shows in the Flutter guide.

Change a card with a patch

Say the agent showed a booking card, and the person changes the party size from 2 to 4. The agent doesn't have to write the whole card again. It can send just the lines that changed, in an openui-patch block (or ui:openui+patch):

The Harbor Window table seats four, and Kaneo is filling up.

```openui-patch
gauge = AvailabilityGauge(88, "20 min wait")
tables = SeatSelector([{id: "T4", zone: "Harbor Window", seats: 4, available: true}])
```

This is how a patch changes the card:

  • A line that sets a name the card already has replaces that line.
  • A line with a new name is added at the end.
  • name = null removes that component. A $variable set to null just becomes null.

The router applies the patch to the previous card before it saves the reply. So the message in Stream Chat always has the complete, updated card, and your app never applies patches itself. Patches work with OpenUI only.

The agent only sends patches if you ask it to. Either add a rule like this to the renderer's instructions, as the Swift assistant does:

When the person changes the card of your last reply, write only what changes, in one openui-patch fenced block.

Or set patch_mode: true in agent.yaml.

Describe the UI in agent.yaml

Instead of copying a renderer's instructions into instructions.md, you can describe the UI in agent.yaml. When the agent is synced, the SDK writes the instructions for you and the agent is told them after instructions.md. They ask for a short sentence and then a card only when a card helps, so the agent still answers everything else in prose. You pick the format, OpenUI or A2UI, choose which of its built-in components the agent can use, add your app's own components, and set a few rules. Here's an agent that writes OpenUI:

agents/concierge/agent.yaml
name: concierge
llm: llm-fast
ui:
  format: openui
  # Form brings FormControl, Buttons and Button.
  keep: [CardHeader, Form, Chips, FollowUpBlock]
  patch_mode: true
  voice_ui: true
  rules:
    - Always pair RestaurantCard with AvailabilityGauge when the wait is known.
Key What it does
format openui, the default, or a2ui. For A2UI, see below.
keep Which built-in components the agent can use. Leave it out to allow all of them. In OpenUI, components they need come along automatically (Form also brings FormControl, Buttons and Button), and Card is always included.
components A JSON file with your app's own components, ui/components.json by default. It uses the same component definitions as your apps. For example, restaurant_card shows up in the instructions as RestaurantCard(name, cuisine, rating, price_tier?).
blueprints A YAML file of layouts you want the agent to reuse, ui/blueprints.yaml by default. Each one says when to use it and which components go in which order, with an example in the agent's format. An example that wouldn't render is refused.
patch_mode OpenUI only. Set to true to have the agent update its last card with a patch.
voice_ui Set to true to let the agent show UI during calls too. See UI on a call.
rules Your own extra rules, such as "Write times as 24h".

To have the agent write A2UI 1.0 instead, set format: a2ui. It then writes its UI in a ui:a2ui@1.0 block, using the instructions the iOS SDK's A2UIRenderer writes for itself, so the Stream A2UI renderers in your apps can show it:

agents/concierge/agent.yaml
name: concierge
llm: llm-fast
ui:
  format: a2ui
  keep: [Text, Column, Row, Card, Button, ChoicePicker, formatString, required]
  voice_ui: true
  rules:
    - Write times as 24h, like 19:15, never 7:15 PM.

A few things work differently from OpenUI:

  • keep lists components and functions of A2UI's basic catalog by name, such as Column, Button or formatString. Nothing comes along automatically, so list everything the agent needs. Your own components are always offered.
  • The parameter names of your components must be plain identifiers: letters, digits and _, not starting with a digit.
  • A blueprint's example is written in A2UI, in a ui:a2ui@1.0 block. It's checked the way the renderer checks it, for things like unknown components or properties, missing required properties, and children that are never defined.
  • patch_mode isn't allowed. An A2UI reply always draws a new card instead of changing the last one.

Good to know:

  • The files have to be inside the agent's folder, and each can be up to 512 KB.
  • The same folder always produces the same instructions, so the model provider can cache them.
  • Make sure your apps can draw everything you allow here: the components in keep, and the ones in components.json.

Turn UI off for one session

A client that can't show cards, such as a voice-only app or a text-message bridge, can open a session without the UI instructions. The model isn't sent them, so the agent is expected to answer in prose:

Not in the Kotlin SDK yet. Showing React.

Not in the Flutter SDK yet. Showing React.

React
const session = await agent.sessions.create({ ui: false });
React Native
const session = await agent.sessions.create({ ui: false });
Swift
var options = SessionOptions()
options.ui = false
let session = try await agent.sessions.create(options)

The session keeps it when it's reopened or forked. It leaves out only the UI described in agent.yaml: instructions you copied into instructions.md yourself are always sent. It doesn't stop the model from writing a card on its own, and a card it writes still reaches the reply.

Info:

Sessions open with ui: false from JavaScript and Swift. The agent has to be synced with the Go or JavaScript SDK, which keep the UI apart from instructions.md, so ui: false can leave it out.

What reaches Stream Chat

As the reply streams, the router moves the block out of its text into the message's custom data, as custom.ai_ui, and keeps the words around it as the message's text:

{
  "v": 1,
  "format": "openui",
  "status": "streaming",
  "content": "root = Card([title, map])\ntitle = CardHeader(\"A weekend in Ohrid\")"
}
Field Description
v The version of the field, 1.
format The format from the block's info string, such as a2ui or openui.
version The format's version, such as 1.0, when the info string names one.
status streaming while the agent is still writing the block, then complete.
content The block as the model wrote it, such as an OpenUI program or A2UI messages.

If the agent sent a patch, content is still the complete card, with the patch already applied.

Tip:

The text is what people read wherever the UI can't show: in a push notification, in an external thread and in an app without a renderer for the format. So have the model write a sentence saying what the UI shows before the block.

Warning:

Stream Chat holds at most 50 KB of custom data on a message. When the UI would take the message's custom data over 48 KB as JSON, the router leaves it out, and the reply keeps only its words. A UI that was showing while the reply streamed is taken off again, rather than left cut off midway.

React (v14), React Native (v9) only

stream-chat 9 puts a message's custom data on the message itself, so the UI is message.ai_ui, where stream-chat 10 has message.custom.ai_ui. fromStreamMessage reads message.ai_ui.

When the conversation goes on, the model reads its earlier replies with their UI, written back as the blocks it wrote.

Stream Chat gets the UI in batches, a few times a second. To show cards faster, read them from the session's socket instead: see Show it as it streams. UI shown during a voice call is saved on the call's transcript too: see UI on a call.

Show it in your app

React

AIConversation from stream-chat-react shows a reply's UI in place of its text, brings it in as the agent writes it, and sends what the person does in it back to the agent. Its renderers of A2UI and OpenUI are in stream-chat-react/a2ui and stream-chat-react/openui. Each is built on its format's official packages. stream-chat-react lists them as optional, so npm install stream-chat-react doesn't add them. Install the packages for each format your agent writes:

# A2UI
npm install @a2ui/web_core@~0.15.0 @a2ui/react@~0.15.0

# OpenUI
npm install @openuidev/react-lang@~1.0.2 @openuidev/react-ui@~0.18.1 @openuidev/react-headless@~0.18.1 zustand@^4.5.5 zod@^4

A page that imports a renderer without its packages fails to build.

Keep an AIUIHost with the renderers of the formats your agent writes and your components for as long as the conversation shows, so each reply's UI keeps its state, such as what the person typed into a form. Its send asks the session, with what the person did as uiAction:

AgentConversation.tsx
"use client"; // Next.js App Router: these hooks run in the browser

import type { Session } from "@stream-io/stream-agents";
import { useMemo } from "react";
import type { LocalMessage } from "stream-chat";
import {
  AIConversation,
  AIUIHost,
  aiUIActionJSON,
  fromStreamMessage,
} from "stream-chat-react/ai-components";
import { createA2UIRenderer } from "stream-chat-react/a2ui";
import { createOpenUIRenderer } from "stream-chat-react/openui";
import "stream-chat-react/dist/css/index.css";
import "stream-chat-react/dist/css/ai-components.css";
import "@openuidev/react-ui/components.css";

import { placeCard } from "./placeCard";

// `messages` are the messages of the channel session.chat() opened, loaded with
// `channel.watch()`.
export const AgentConversation = ({
  session,
  messages,
}: {
  session: Session;
  messages: LocalMessage[];
}) => {
  const ui = useMemo(
    () =>
      new AIUIHost({
        components: [placeCard],
        renderers: [createA2UIRenderer(), createOpenUIRenderer()],
        // What the person did, in their words, with the action for the agent.
        send: (action) =>
          session.responses.create(action.label, {
            uiAction: aiUIActionJSON(action),
          }),
      }),
    [session],
  );

  return (
    <AIConversation
      messages={messages.map((message) => fromStreamMessage(message))}
      ui={ui}
    />
  );
};

With the quickstart's AgentChat and AIConversationController, give the same host to the quickstart's AIConversation as ui, and send the action through the controller as custom.uiAction. The transport passes it to the session as uiAction, and the question shows at once like any other:

// In the component that renders the quickstart's AIConversation.
const ui = useMemo(
  () =>
    new AIUIHost({
      components: [placeCard],
      renderers: [createA2UIRenderer(), createOpenUIRenderer()],
      send: (action) => {
        conversation.send({
          text: action.label,
          custom: { uiAction: aiUIActionJSON(action) },
        });
      },
    }),
  [conversation],
);

return <AIConversation conversation={conversation} ui={ui} />;

A reply shows its UI when one of the host's renderers reads its format and version, the first one listed asked first. Otherwise, it shows its text.

A component is a view of your app the agent can place, described once with the parameters the agent fills in and the events it reports. Every renderer places it by its name, so it works whichever format the agent writes:

placeCard.tsx
import {
  AIUIParameterType,
  defineAIUIComponent,
  requiredAIUIParameter,
} from "stream-chat-react/ai-components";

export const placeCard = defineAIUIComponent<{ title: string }>(
  {
    name: "place_card",
    description: "A photo and a short summary of a place.",
    parameters: [
      requiredAIUIParameter(
        "title",
        AIUIParameterType.string,
        "The place's Wikipedia title.",
      ),
    ],
    events: [
      {
        name: "ask_about",
        description: "The person asks about the place.",
        parameters: [],
      },
    ],
  },
  ({ args, context }) => (
    <PlaceCard
      title={args.title}
      onClick={() =>
        context.emit("ask_about", `Tell me more about ${args.title}`)
      }
    />
  ),
);

A component can load what it shows in the browser, such as a place's photo, which then never reaches the agent. The React generative UI guide covers the rest: the renderers' options, theming, running your app's tools from a reply's UI and handling errors. The iOS, Android and Flutter guides do the same in the apps.

React (v14) only

The same code and packages work with stream-chat-react 14.17.0 or later, which brought the quickstart's AIConversationController. The renderers take the same optional packages in both majors. Render AgentConversation inside <Chat> or a TranslationProvider, as the quickstart's src/main.tsx does: stream-chat-react 14 translates only inside one, and without it the AI components show their keys, such as Thinking… {{ duration }}. The React v14 generative UI guide covers the rest.

React Native

AIConversation from stream-chat-expo shows a reply's UI in place of its text, brings it in as the agent writes it, and sends what the person does in it back to the agent. Its A2UI renderer is in stream-chat-expo/a2ui and comes with the SDK, so there's nothing more to install. React Native renders A2UI only: tell the agent to write A2UI, as above.

Keep an AIUIHost with the renderer and your components for as long as the conversation shows, so each reply's UI keeps its state, such as what the person typed into a form. Its send asks the session, with what the person did as uiAction:

AgentConversation.tsx
import type { Session } from "@stream-io/stream-agents";
import { useMemo } from "react";
import type { LocalMessage } from "stream-chat";
import { createA2UIRenderer } from "stream-chat-expo/a2ui";
import {
  AIUIHost,
  aiUIActionJSON,
  fromStreamMessage,
} from "stream-chat-expo/ai-components";
import { AIConversation } from "stream-chat-expo/ai-components/conversation";

import { placeCard } from "./placeCard";

// `messages` are the messages of the channel session.chat() opened, loaded with
// `channel.watch()`.
export const AgentConversation = ({
  session,
  messages,
}: {
  session: Session;
  messages: LocalMessage[];
}) => {
  const ui = useMemo(
    () =>
      new AIUIHost({
        components: [placeCard],
        renderers: [createA2UIRenderer()],
        // What the person did, in their words, with the action for the agent.
        send: (action) =>
          session.responses.create(action.label, {
            uiAction: aiUIActionJSON(action),
          }),
      }),
    [session],
  );

  return (
    <AIConversation
      messages={messages.map((message) => fromStreamMessage(message))}
      ui={ui}
    />
  );
};

A reply shows its UI when the renderer reads its format and version. Otherwise, it shows its text.

A component is a view of your app the agent can place, described once with the parameters the agent fills in and the events it reports:

placeCard.tsx
import { Pressable, Text } from "react-native";
import {
  AIUIParameterType,
  defineAIUIComponent,
  requiredAIUIParameter,
} from "stream-chat-expo/ai-components";

export const placeCard = defineAIUIComponent<{ title: string }>(
  {
    name: "place_card",
    description: "A photo and a short summary of a place.",
    parameters: [
      requiredAIUIParameter(
        "title",
        AIUIParameterType.string,
        "The place's Wikipedia title.",
      ),
    ],
    events: [
      {
        name: "ask_about",
        description: "The person asks about the place.",
        parameters: [],
      },
    ],
  },
  ({ args, context }) => (
    <Pressable
      onPress={() =>
        context.emit("ask_about", `Tell me more about ${args.title}`)
      }
    >
      <Text>{args.title}</Text>
    </Pressable>
  ),
);

The React Native generative UI guide covers the rest: the renderer's options, theming, running your app's tools from a reply's UI and handling errors.

React Native (v9) only

The same code runs on stream-chat-expo 9.14.0 or later: generative UI came in 9.13.0, and the ai-components/conversation entry point it imports AIConversation from in 9.14.0. The v9 generative UI guide covers the rest.

Swift

StreamChatAI's AIConversationView shows a reply's UI in place of its text, brings it in as the agent writes it, and sends what the person does in it back to the agent. Its renderers of A2UI and OpenUI are the StreamChatA2UI and StreamChatOpenUI libraries, from version 5.16.0 of the Stream Chat Swift SDK. Add the library of each format your agent writes to your app target, next to StreamChatAI:

Library Renderer Format Requires
StreamChatA2UI A2UIRenderer A2UI 1.0 iOS 15
StreamChatOpenUI OpenUIRenderer OpenUI Lang 1.0 iOS 17

The quickstart's chat UI shows the session's channel with AgentTransport and AgentMessage. Give each message the UI the router moved out of its text, as its uiDocument:

struct AgentMessage: AIMessage {
    let message: ChatMessage

    // The id, role, text, isGenerating and parts, as in the quickstart.

    // The reply's UI, from the message's `custom.ai_ui`.
    var uiDocument: AIUIDocument? { AIUIDocument(customData: message.extraData) }
}

Keep an AIUIHost with the renderers of the formats your agent writes and your components in AgentTransport, so each reply's UI keeps its state, such as what the person typed into a form, for as long as the conversation shows. Its send asks the session, as the composer does:

import Combine
import StreamChat
import StreamChatA2UI
import StreamChatAI
import StreamChatOpenUI
import StreamAgents

@MainActor
final class AgentTransport: AIConversationTransport {
    let session: AgentSession
    /// The UI the agent writes for some replies, in A2UI or OpenUI, with the app's own views.
    let ui: AIUIHost<AIUIRendererPair<A2UIRenderer, OpenUIRenderer>>
    private let channel: ChatChannelController
    private var subscription: AnyCancellable?

    init(_ session: AgentSession) async throws {
        self.session = session
        ui = AIUIHost(components: [PlaceCardComponent()]) {
            A2UIRenderer()
            OpenUIRenderer()
        } send: { [session] action in
            // What the person did, in their words, with the action for the agent.
            _ = try await session.responses.create(action.label, uiAction: action.json)
        }
        channel = try await session.chat()
        await session.start()
    }

    // connect(_:), send(_:), stop() and approver as in the quickstart.
}

Then pass the host to the conversation, in the quickstart's AgentConversation:

struct AgentConversation: View {
    let ui: AIUIHost<AIUIRendererPair<A2UIRenderer, OpenUIRenderer>>
    @StateObject private var conversation: AIConversation<AgentMessage>

    init(transport: AgentTransport) {
        ui = transport.ui
        _conversation = StateObject(
            wrappedValue: AIConversation(transport: transport, approver: transport.approver, actions: [.rate])
        )
    }

    var body: some View {
        AIConversationView(conversation: conversation, ui: ui)
            .safeAreaInset(edge: .bottom) {
                AIComposerView(conversation: conversation)
            }
    }
}

A reply shows its UI when one of the host's renderers reads its format and version, the first one listed asked first. Otherwise, it shows its text. The UI comes in as the agent writes it: each part fades in, rising into place, after the parts before it. A reply loaded from the channel's history shows at once.

OpenUIRenderer needs iOS 17, so this AgentTransport builds only for a deployment target of iOS 17 or later. With an earlier one, such as the quickstart's iOS 15, make ui an AIUIHost<A2UIRenderer>, with A2UIRenderer() alone, in AgentTransport and AgentConversation.

A component is a view of your app the agent can place, described once with the parameters the agent fills in and the events it reports. Every renderer places it by its name, so it works whichever format the agent writes:

struct PlaceCardComponent: AIUIComponent {
    // Decoded off the main actor, also in an app whose code is on the main actor by default.
    nonisolated struct Arguments: Decodable {
        let title: String
    }

    let definition = AIUIComponentDefinition(
        name: "place_card",
        description: "A photo and a short summary of a place.",
        parameters: [.required("title", .string, description: "The place's Wikipedia title.")],
        events: [.init(name: "ask_about", description: "The person asks about the place.")]
    )

    func body(arguments: Arguments, context: AIUIComponentContext) -> some View {
        PlaceCard(title: arguments.title) {
            context.emit("ask_about", label: "Tell me more about \(arguments.title)")
        }
    }
}

A component can load what it shows on the device, such as a place's photo or the person's calendar, which then never reaches the agent. Its definition reads and writes JSON, so your apps and the agent's instructions can share one description of it, decoded with JSONDecoder as [AIUIComponentDefinition].

The renderers treat what the agent writes as untrusted: a reply's UI can't crash or freeze the app, and its links open through the host, which opens only web and email links by default. A reply's UI can also run your app's client side tools, passed to the host as tools, such as to load the person's calendar for the days of a plan. They are apart from the tools the agent calls, and the host runs one by itself only when its definition says it's read-only (readOnlyHint).

The iOS generative UI guide covers the rest: the renderers' options and theming, components, a renderer of your own for another format, and showing a reply's UI in your own views with AIUIView.

Kotlin

AIConversation, of the AI components in stream-chat-android-ai-compose, shows a reply's UI in place of its text, brings it in as the agent writes it, and sends what the person does in it back to the agent. Its renderers of A2UI and OpenUI are the stream-chat-android-ai-a2ui and stream-chat-android-ai-openui artifacts, from version 7.18.0 of the Stream Chat Android SDK. Add the artifact of each format your agent writes to your dependencies, next to stream-chat-android-ai-compose:

Artifact Renderer Format Requires
stream-chat-android-ai-a2ui A2UIRenderer A2UI 1.0 minSdk 23
stream-chat-android-ai-openui OpenUIRenderer OpenUI Lang 1.0 minSdk 23

The quickstart's chat UI shows the session's channel with AIConversation, through AgentTransport and AgentMessage. Give each message the UI the router moved out of its text, as its uiDocument:

/** A message of the session's channel, as the AI components show it. */
class AgentMessage(val message: Message) : AIMessage {
    override val id: String = message.id

    // The agent's replies carry `ai_generated: true`.
    override val role: AIMessageRole =
        if (message.extraData["ai_generated"] == true) AIMessageRole.Assistant else AIMessageRole.User
    override val text: String = message.text
    override val isGenerating: Boolean = message.extraData["generating"] == true

    // The reply's reasoning and tool calls, which the router writes as its attachments.
    // Stream Chat moves an attachment's `name` out of its extraData, and a tool call needs it back.
    override val parts: List<AIMessagePart> = AIMessagePart.parts(
        message.attachments.map { it.type.orEmpty() to it.extraData + ("name" to it.name) },
    )

    // The reply's UI, from the message's `custom.ai_ui`.
    override val uiDocument: AIUIDocument? = AIUIDocument.from(message.extraData)
}

The quickstart's AgentTransport asks the session with the person's words. To send what they did in a reply's UI too, give its send the request's uiAction:

override suspend fun send(request: AIConversationRequest<AgentMessage>) {
    // What the person did in a reply's UI, if anything, goes to the agent with their words.
    session.responses.create(request.text, uiAction = request.uiAction?.json)
}

Keep an AIUIHost with the renderers of the formats your agent writes and your components beside the conversation's AIConversationState, in the ViewModel behind your screen, so each reply's UI keeps its state, such as what the person typed into a form, for as long as the conversation shows. Its send is the state's, which sends what the person did as their next message:

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import io.getstream.chat.android.ai.a2ui.generativeui.A2UIRenderer
import io.getstream.chat.android.ai.compose.conversation.AIConversationState
import io.getstream.chat.android.ai.compose.generativeui.AIUIHost
import io.getstream.chat.android.ai.openui.generativeui.OpenUIRenderer
import io.getstream.agents.android.core.channelState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class AgentViewModel(application: Application) : AndroidViewModel(application) {
    private val _conversation = MutableStateFlow<AIConversationState<AgentMessage>?>(null)

    /** The conversation, once the session's channel is open. */
    val conversation: StateFlow<AIConversationState<AgentMessage>?> = _conversation.asStateFlow()

    /** The UI the agent writes for some replies, in A2UI or OpenUI, with the app's own views. */
    val ui: AIUIHost = AIUIHost(
        renderers = listOf(A2UIRenderer(), OpenUIRenderer()),
        components = listOf(placeCard),
    ) { action ->
        // What the person did goes to the agent as their next message.
        _conversation.value?.send(action)
    }

    init {
        viewModelScope.launch {
            val session = agents.agent("my-agent").sessions.create()
            val transport = AgentTransport(session, session.channelState(application, viewModelScope), viewModelScope)
            _conversation.value = AIConversationState(transport, viewModelScope)
        }
    }
}

channelState watches the session's channel on the client that chat(context) opens, and keeps its messages up to date, after a reconnect too. Then pass the host to the conversation:

val conversation by viewModel.conversation.collectAsStateWithLifecycle()
conversation?.let { AIConversation(state = it, ui = viewModel.ui) }

A reply shows its UI when one of the host's renderers reads its format and version, the first one listed asked first. Otherwise, it shows its text. The UI comes in as the agent writes it: each part fades in, rising into place, after the parts before it. A reply loaded from the channel's history shows at once. The host is confined to the main thread. Conversation View covers the rest of AIConversation, such as the agent thinking and a question while it's sent.

A component is a view of your app the agent can place, described once with the parameters the agent fills in and the events it reports. Every renderer places it by its name, so it works whichever format the agent writes:

val placeCard: AIUIComponent = AIUIComponent(
    AIUIComponentDefinition(
        name = "place_card",
        description = "A photo and a short summary of a place.",
        parameters = listOf(
            AIUIParameter.required("title", AIUIParameterType.String, description = "The place's Wikipedia title."),
        ),
        events = listOf(AIUIComponentDefinition.Event("ask_about", "The person asks about the place.")),
    ),
) { arguments, context ->
    val title = arguments["title"] as? String ?: return@AIUIComponent
    PlaceCard(title = title, onClick = { context.emit("ask_about", label = "Tell me more about $title") })
}

PlaceCard is a composable of your app. Its arguments are the JSON the agent wrote, as plain Kotlin values, so show nothing while they don't fit, such as while the agent is still writing them. A component can load what it shows on the device, such as a place's photo or the person's calendar, which then never reaches the agent. Its definition reads and writes JSON, so your apps and the agent's instructions can share one description of it, read with AIUIComponentDefinition.fromJsonString(text).

The renderers treat what the agent writes as untrusted: a reply's links open through the host, which opens only web and email links by default (linkSchemes), and its images load only from the web. A reply's UI can also run your app's client-side tools, passed to the host as tools, such as to load the person's calendar for the days of a plan. They are apart from the tools the agent calls, and the host runs one by itself only when it says it's read-only (isReadOnly).

The Android generative UI guide covers the rest: the renderers' options and theming, components, a renderer of your own for another format, and showing a reply's UI in your own views with AIUIView.

Dart

AIConversationView, of the AI components in stream_chat_flutter_ai, shows a reply's UI in place of its text, brings it in as the agent writes it, and sends what the person does in it back to the agent. Its renderers of A2UI and OpenUI are the stream_chat_flutter_ai_a2ui and stream_chat_flutter_ai_openui packages. Add the package of each format your agent writes to your dependencies, next to stream_chat_flutter_ai:

Package Renderer Format Requires
stream_chat_flutter_ai_a2ui A2UIRenderer A2UI 1.0 Flutter 3.44
stream_chat_flutter_ai_openui OpenUIRenderer OpenUI Lang 1.0 Flutter 3.44

The quickstart's chat UI shows the session's channel with AIConversationView, through AgentTransport and AgentMessage. Give each message the UI the router moved out of its text, as its uiDocument:

/// A message of the channel, as the AI components show it.
class AgentMessage with AIMessage {
  // The reply's reasoning and tool calls, which the router writes as its attachments, and
  // its UI, from the message's `custom.ai_ui`, decoded once here rather than on every rebuild.
  AgentMessage(this.message)
    : parts = AIMessagePart.parseAll([
        for (final attachment in message.attachments)
          if (attachment.rawType case final type?)
            (type: type, payload: {'id': attachment.id, ...attachment.extraData}),
      ]),
      uiDocument = AIUIDocument.fromCustomData(message.extraData);

  final stream.Message message;

  @override
  String get id => message.id;

  // The agent's replies carry `ai_generated: true`.
  @override
  AIMessageRole get role =>
      message.extraData['ai_generated'] == true ? AIMessageRole.assistant : AIMessageRole.user;

  @override
  String get text => message.text ?? '';

  @override
  bool get isGenerating => message.extraData['generating'] == true;

  @override
  final List<AIMessagePart> parts;

  @override
  final AIUIDocument? uiDocument;
}

Keep an AIUIHost with the renderers of the formats your agent writes and your components in AgentTransport, so each reply's UI keeps its state, such as what the person typed into a form, for as long as the conversation shows. Its send asks the session, as the composer does:

import 'dart:async';

import 'package:stream_chat/stream_chat.dart' as stream;
import 'package:stream_chat_flutter_ai/stream_chat_flutter_ai.dart';
import 'package:stream_chat_flutter_ai_a2ui/stream_chat_flutter_ai_a2ui.dart';
import 'package:stream_chat_flutter_ai_openui/stream_chat_flutter_ai_openui.dart';
import 'package:stream_agents/stream_agents.dart';

class AgentTransport with AIConversationTransport<AgentMessage> {
  AgentTransport._(this.session, this._channel);

  final AgentSession session;
  final stream.Channel _channel;
  final _subscriptions = <StreamSubscription<Object?>>[];

  /// The UI the agent writes for some replies, in A2UI or OpenUI, with the app's own views.
  late final ui = AIUIHost(
    renderers: [A2UIRenderer(), OpenUIRenderer()],
    components: const [PlaceCardComponent()],
    send: (action) async {
      // What the person did, in their words, with the action for the agent.
      await session.responses.create(action.label, uiAction: action.toJson());
    },
  );

  // open(), connect(), send(), stop(), approver(), _failed and _activityOf as in the quickstart.

  @override
  void disconnect() {
    for (final subscription in _subscriptions) {
      unawaited(subscription.cancel());
    }
    _subscriptions.clear();
    // Disposing the conversation disconnects it, and the replies' UI goes with it.
    ui.dispose();
  }
}

Then pass the host to the conversation, in the quickstart's AgentConversation:

AIConversationView.conversation(conversation: _conversation, ui: widget.transport.ui)

A reply shows its UI when one of the host's renderers reads its format and version, the first one listed asked first. Otherwise, it shows its text. The UI comes in as the agent writes it: each part fades in, rising into place, after the parts before it. A reply loaded from the channel's history shows at once.

A component is a view of your app the agent can place, described once with the parameters the agent fills in and the events it reports. Every renderer places it by its name, so it works whichever format the agent writes:

class PlaceCardComponent extends AIUIComponent<String> {
  const PlaceCardComponent();

  @override
  AIUIComponentDefinition get definition => const AIUIComponentDefinition(
    name: 'place_card',
    description: 'A photo and a short summary of a place.',
    parameters: [
      AIUIParameter.required('title', AIUIParameterType.string, description: "The place's Wikipedia title."),
    ],
    events: [AIUIComponentEvent(name: 'ask_about', description: 'The person asks about the place.')],
  );

  @override
  String readArguments(AIUIArguments arguments) => arguments.string('title');

  @override
  Widget build(BuildContext context, String title, AIUIComponentContext ui) =>
      PlaceCard(title: title, onTap: () => ui.emit('ask_about', label: 'Tell me more about $title'));
}

PlaceCard is a widget of your app. Its arguments are the JSON the agent wrote, which readArguments reads with the getters of AIUIArguments. A getter throws while they don't fit, such as while the agent is still writing them, and the component shows nothing. A component can load what it shows on the device, such as a place's photo or the person's calendar, which then never reaches the agent. Its definition reads and writes JSON, so your apps and the agent's instructions can share one description of it, read with AIUIComponentDefinition.fromJson(json).

The renderers treat what the agent writes as untrusted: a reply's links open through the host, which opens only web and email links by default (open), and its images load only from the web (mediaUrl). A reply's UI can also run your app's client-side tools, passed to the host as tools, such as to load the person's calendar for the days of a plan. They are apart from the tools the agent calls, and the host runs one by itself only when its definition says it's read-only (isReadOnly).

The Flutter generative UI guide covers the rest: the renderers' options and theming, components, a renderer of your own for another format, and showing a reply's UI in your own views with AIUIView.

Show it as it streams

Stream Chat updates a reply's UI a few times a second. The session's socket is faster: the router sends each piece of the UI the moment the model writes it. Use the socket if you want a card to build up smoothly while the agent is still writing it.

The socket sends two kinds of frames:

  • ui_delta: the next piece of the UI.
  • ui_completed: the whole UI, once the model has finished it. It has content instead of delta.
{
  "type": "ui_delta",
  "turn_id": "turn_7",
  "format": "openui",
  "delta": "gauge = AvailabilityGauge(86, \"12 min wait\")\n"
}

Frames also have version if the UI names one, and "mode": "patch" when it's a patch. For a patch, the pieces are just the patch, not the whole card.

You don't need to handle these frames yourself. The client SDKs collect them on the agent's turn as Turn.ui, with format, version, status and content, and they apply patches for you. There's one exception. If a patch arrives but the socket never saw the card before it, for example because the app just reopened an old conversation, Turn.ui stays empty. In that case the message in Stream Chat already has the full card, so show that.

To show the socket's UI on the right message in the chat, use LiveUI. While a reply is being written, it shows the socket's version of the card on it. Once Stream Chat has the finished card, it switches back to Chat's copy. It follows a few rules, so a new reply never shows the previous reply's card:

  • If the message has a turn id (support_runtime.turn_id), it shows the UI of that turn.
  • If the turn id isn't there yet, only the newest reply that's being written shows the UI of the agent's current turn. This is cleared as soon as the person asks something new, or the agent starts a new turn.
  • Once the reply is finished (generating is false), or its ai_ui is complete, it shows what Stream Chat saved. That can be no UI at all, for example if the reply was refused.
ReactReact Native

If you use AgentChat from @stream-io/stream-agents/chat, as the quickstart does, there's nothing to add: it already does this for every message it gives you. If you read messages from the channel yourself, as in Show it in your app, you get the UI at Stream Chat's slower pace. Each turn in session.conversation also has its ui.

Swift

Add a LiveUI to your AgentTransport, and pass it the session's conversation every time it changes. When observe(_:) returns true, publish the channel's messages again, with overlay(_:) swapping in the live UI:

@MainActor
final class AgentTransport: AIConversationTransport {
    let session: AgentSession
    let ui: AIUIHost<AIUIRendererPair<A2UIRenderer, OpenUIRenderer>>
    private let channel: ChatChannelController
    private var feed: AIConversationFeed<AgentMessage>?
    private var subscriptions: Set<AnyCancellable> = []
    /// Each reply's UI as the session's socket streams it, ahead of its message in the channel.
    private var liveUI = LiveUI()

    // init(_:), send(_:), stop() and approver as above.

    func connect(_ feed: AIConversationFeed<AgentMessage>) {
        self.feed = feed
        channel.messagesChangesPublisher
            .sink { [weak self] _ in MainActor.assumeIsolated { self?.publish() } }
            .store(in: &subscriptions)
        // The session's conversation, whose turns carry their UI.
        session.$conversation
            .sink { [weak self] conversation in MainActor.assumeIsolated { self?.sessionChanged(conversation) } }
            .store(in: &subscriptions)
        channel.synchronize { [weak self] _ in self?.publish() }
    }

    private func sessionChanged(_ conversation: Conversation) {
        if liveUI.observe(conversation) {
            publish()
        }
    }

    /// The channel's messages, oldest first, with the socket's UI on the reply being written.
    private func publish() {
        let messages = Array(channel.messages.reversed())
        let live = liveUI.overlay(messages)
        feed?.update(messages: messages.map { AgentMessage($0, customData: live[$0.id]) })
    }
}

struct AgentMessage: AIMessage {
    let message: ChatMessage
    /// The message's custom data, with the UI the socket streamed for it while it's written.
    private let customData: [String: RawJSON]

    init(_ message: ChatMessage, customData: [String: RawJSON]? = nil) {
        self.message = message
        self.customData = customData ?? message.extraData
    }

    // The id, role, text, isGenerating and parts, as in the quickstart.

    var uiDocument: AIUIDocument? { AIUIDocument(customData: customData) }
}

On Swift, an OpenUI card also builds up one finished line at a time: TurnUI.content leaves out a line until the model has finished writing it. That stops values from flickering, such as a gauge showing 8 before it gets to 86. To animate the change from the reply's text to its card, call publish() inside withAnimation, as the Swift assistant does.

Kotlin

Add a LiveUI to your AgentTransport, and pass it the session's conversation every time it changes. When observe returns true, show the channel's messages again, with overlay swapping in the live UI. overlay answers each reply's custom data by message id, so give it to AgentMessage, which reads its uiDocument from it:

class AgentTransport(
    val session: AgentSession,
    private val channel: StateFlow<ChannelState?>,
    private val scope: CoroutineScope,
) : AIConversationTransport<AgentMessage> {
    /** Each reply's UI as the session's socket streams it, ahead of its message in the channel. */
    private val liveUI = LiveUI()

    /** Moves each time the socket streams more UI, so the messages are shown again. */
    private val streamed = MutableStateFlow(0)

    override fun connect(feed: AIConversationFeed<AgentMessage>) {
        // The channel's messages, oldest first, with the socket's UI on the reply being written.
        scope.launch {
            channel.collectLatest { state ->
                val messages = state?.messages ?: return@collectLatest
                combine(messages, streamed) { messages, _ ->
                    val shown = messages.filter { it.deletedAt == null }
                    val live = liveUI.overlay(shown)
                    shown.map { AgentMessage(it, live[it.id]) }
                }.collect { feed.update(messages = it) }
            }
        }
        // The session's conversation, whose turns carry their UI.
        scope.launch {
            session.conversation.collect { conversation ->
                if (liveUI.observe(conversation)) streamed.update { it + 1 }
            }
        }
        // What the agent is doing, and a reply it couldn't write, as in the quickstart.
    }

    // send() and stop() as above.
}

/** A message of the session's channel, as the AI components show it. */
class AgentMessage(val message: Message, customData: Map<String, Any?>? = null) : AIMessage {
    /** The message's custom data, with the UI the socket streamed for it while it's written. */
    private val customData: Map<String, Any?> = customData ?: message.extraData

    // The id, role, text, isGenerating and parts, as above.

    // The reply's UI: the socket's while it's written, then the message's `custom.ai_ui`.
    override val uiDocument: AIUIDocument? = AIUIDocument.from(this.customData)
}

On Kotlin too, an OpenUI card builds up one finished line at a time: TurnUI.content leaves out a line until the model has finished writing it, so values don't flicker, such as a gauge showing 8 before it gets to 86.

LiveUI, its overlay and Turn.ui are in io.getstream.agents.android.core.

Info:

The Kotlin SDK has LiveUI and Turn.ui from io.getstream:stream-agents-android-core 0.7.0.

Dart

Add a LiveUI to your AgentTransport, and pass it the session's conversation every time it changes. When observe returns true, update the feed again, running the channel's messages through overlay first:

/// Each reply's UI as the session's socket streams it, ahead of its message in the channel.
final liveUI = LiveUI();

@override
void connect(AIConversationFeed<AgentMessage> feed) {
  // The channel's messages, oldest first, with the socket's UI on the reply being written.
  void publish() => feed.updateMessages([
    for (final message in liveUI.overlay(_channel.state!.messages))
      if (message.deletedAt == null) AgentMessage(message),
  ]);

  _subscriptions
    ..add(_channel.state!.messagesStream.listen((_) => publish()))
    ..add(
      session.conversation.stream.listen((conversation) {
        // The session's conversation, whose turns carry their UI.
        if (liveUI.observe(conversation)) publish();
        if (!_failed) feed.updateActivity(_activityOf(conversation.state));
      }),
    );
  // The session's events, as in the quickstart.
}

overlay puts the live UI into the reply's extraData, which is where AgentMessage already reads it from, so AgentMessage doesn't change.

LiveUI and Turn.ui are in the stream_agents package, which you import as package:stream_agents/stream_agents.dart.

UI on a call

The agent can show UI during a voice call too, such as a restaurant card while it talks about where to eat. The router makes sure the UI is never read out loud, and sends it over the session's socket, the same as in a chat.

The agent only does this if you allow it. Add a line to its instructions, such as "On a call, say one or two sentences out loud, then write the UI after them", or set voice_ui: true in agent.yaml.

There are two places to show it:

  • In the transcript. The UI is saved on the reply's message in the call's transcript, as custom.ai_ui. So it shows in the chat after the call, and in any view of the transcript during the call, such as the quickstart's voice screen once you pass the host to it as ui.
  • On your call screen. If your call screen doesn't show the transcript, show the UI of the agent's latest turn yourself:

Not documented for React Native yet. Showing React.

Not documented for React Native (v9) yet. Showing React.

ReactReact Native

On a call, each turn in session.conversation has its ui too. The React assistant's VoiceMode.tsx shows the latest one with AIUIView, using a separate AIUIHost from the chat's.

Swift
/// The UI of the agent's newest turn on the call, as the call's session streams it.
struct CallUI: View {
    @ObservedObject var voice: VoiceSession
    /// A host of its own, apart from the chat's, with the same renderers and components.
    let ui: AIUIHost<AIUIRendererPair<A2UIRenderer, OpenUIRenderer>>

    var body: some View {
        if let turn = voice.session.turns.last(where: { $0.speaker.isAgent && $0.ui?.content.isEmpty == false }),
           let turnUI = turn.ui,
           let document = AIUIDocument(customData: [AIUIDocument.customDataKey: turnUI.customData]) {
            // The renderers take the turn's UI before its view is asked for, as a conversation's do.
            let _ = ui.receive([CallTurn(turn: turn, uiDocument: document)])
            let view = AIUIView(host: ui, document: document, messageID: turn.id)
            if view.canShow {
                view
            }
        }
    }
}

/// One of the agent's turns on the call, as the renderers read a reply.
struct CallTurn: AIMessage {
    let turn: Turn
    let uiDocument: AIUIDocument?

    var id: String { turn.id }
    var role: AIMessageRole { .assistant }
    var text: String { turn.text }
    var isGenerating: Bool { turn.ui?.isStreaming == true }
}

When the person taps something in it, the host's send sends it to the agent, the same as in the chat.

Kotlin
/** The UI of the agent's newest turn on the call, as the call's session streams it. */
@Composable
fun CallUI(voice: VoiceSession, ui: AIUIHost, modifier: Modifier = Modifier) {
    val conversation by voice.session.conversation.collectAsStateWithLifecycle()
    val turn = conversation.turns.lastOrNull { it.isAgent && it.ui?.content?.isNotEmpty() == true } ?: return
    val document = remember(turn.ui) {
        turn.ui?.let { AIUIDocument.from(mapOf(AIUIDocument.CUSTOM_DATA_KEY to it.customData)) }
    } ?: return
    // The renderers take the turn's UI before its view is asked for, as a conversation's do.
    ui.receive(listOf(CallTurn(turn, document)))
    if (ui.canShow(document)) {
        AIUIView(ui, document, turn.id, modifier)
    }
}

/** One of the agent's turns on the call, as the renderers read a reply. */
private class CallTurn(turn: Turn, override val uiDocument: AIUIDocument) : AIMessage {
    override val id: String = turn.id
    override val role: AIMessageRole = AIMessageRole.Assistant
    override val text: String = turn.text
    override val isGenerating: Boolean = turn.ui?.isStreaming == true
}

Give it a host of its own, apart from the chat's, with the same renderers and components. When the person taps something in it, the host's send sends it to the agent, the same as in the chat.

Dart
/// The UI of the agent's newest turn on the call, as the call's session streams it.
class CallUI extends StatelessWidget {
  const CallUI({super.key, required this.session, required this.ui});

  /// The call's session.
  final AgentSession session;

  /// A host of its own, apart from the chat's, with the same renderers and components.
  final AIUIHost ui;

  @override
  Widget build(BuildContext context) => StreamBuilder(
    stream: session.conversation.stream,
    initialData: session.conversation.value,
    builder: (context, snapshot) {
      final turn = snapshot.requireData.turns.where((turn) => turn.speaker.isAgent && turn.ui != null).lastOrNull;
      final document = turn == null ? null : AIUIDocument.fromCustomData({'ai_ui': turn.ui!.toWireJson()});
      if (turn == null || document == null) return const SizedBox.shrink();
      // The renderers take the turn's UI before its view is asked for, as a conversation's do.
      ui.receive([CallTurn(turn, document)]);
      return AIUIView(host: ui, document: document, messageId: turn.id);
    },
  );
}

/// One of the agent's turns on the call, as the renderers read a reply.
class CallTurn with AIMessage {
  CallTurn(this.turn, this.uiDocument);

  final Turn turn;

  @override
  final AIUIDocument uiDocument;

  @override
  String get id => turn.id;

  @override
  AIMessageRole get role => AIMessageRole.assistant;

  @override
  String get text => turn.text;

  @override
  bool get isGenerating => turn.ui?.isStreaming ?? false;

  @override
  List<AIMessagePart> get parts => const [];
}

When the person taps something in it, the host's send sends it to the agent, the same as in the chat.

What the person does

Warning:

The agent doesn't answer a message sent to the session's channel. When the person does something in a reply's UI, ask the session instead: the router writes the person's message into the channel itself, with the action on it.

React

When the person does something in a reply's UI that's for the agent, such as tapping a place or submitting a form, the host calls its send with an AIUIAction. Ask the session with it, as AgentConversation does above: action.label is the question, in the person's words, such as "Tell me more about St. Naum", and aiUIActionJSON(action) is what they did, passed as uiAction to responses.create. See Send what the person did in a reply's UI.

The React guide does the same with Stream Agents, and sends the action to the channel as a message only for a backend of your own.

React Native

When the person does something in a reply's UI that's for the agent, such as tapping a place or submitting a form, the host calls its send with an AIUIAction. Ask the session with it, as AgentConversation does above: action.label is the question, in the person's words, such as "Tell me more about St. Naum", and aiUIActionJSON(action) is what they did, passed as uiAction to responses.create. See Send what the person did in a reply's UI.

The React Native guide sends the action to the channel as a message instead.

Swift

When the person does something in a reply's UI that's for the agent, such as tapping a place, choosing a follow-up or submitting a form, the host calls its send with an AIUIAction. Ask the session with it, as AgentTransport does above: action.label is the question, in the person's words, such as "Tell me more about St. Naum", and action.json is what they did, passed as uiAction to responses.create. See Send what the person did in a reply's UI.

Property Description
messageID The reply whose UI it came from.
format The format of that UI.
name What happened, such as a component's event (ask_about) or an action of the format, such as OpenUI's continue_conversation.
label What the person did, in their words. Use it as the question.
payload The details, in the format's own shape, such as what was chosen and a form's values.

The iOS guide sends the action to the channel instead, with action.customData as the message's extra data.

The host sends a reply's actions one after another, in the order they happened, and logs a send that throws. To show the person that asking failed, catch the error in send, as the Swift assistant does. The SDK's renderers label an action with the control the person tapped, never with text the agent wrote for it, so the conversation shows only what the person chose. OpenUI sends only the values of the form the action belongs to, and never a password field's value.

Info:

The Swift SDK takes uiAction from version 0.2.0.

Kotlin

When the person does something in a reply's UI that's for the agent, such as tapping a place, choosing a follow-up or submitting a form, the host calls its send with an AIUIAction. Pass it to the conversation's state, which sends it through the transport, as above: the request's text is action.label, the question in the person's words, such as "Tell me more about St. Naum", and request.uiAction?.json is what they did, passed as uiAction to responses.create. See Send what the person did in a reply's UI.

Property Description
messageId The reply whose UI it came from.
format The format of that UI.
name What happened, such as a component's event (ask_about) or an action of the format, such as OpenUI's continue_conversation.
label What the person did, in their words. Use it as the question.
payload The details, in the format's own shape, such as what was chosen and a form's values.

The Android guide sends the action to the channel, with action.json in the message's custom data under AIUIAction.CUSTOM_DATA_KEY. The agent doesn't answer a message sent to the session's channel, so ask the session instead: the router writes the person's message into the channel itself, with the action on it.

The host calls send on the main thread and doesn't wait for it. The state asks in its own scope, and when responses.create throws an AgentsException, it shows it as its error, as the Android assistant does. The SDK's renderers label an action with the control the person tapped, never with text the agent wrote for it, so the conversation shows only what the person chose. OpenUI sends only the values of the form the action belongs to, and never a password field's value. What the person types into an A2UI text field that's obscured is in none of the action's details.

Info:

The Kotlin SDK takes uiAction from io.getstream:stream-agents-android-core 0.2.0.

Dart

When the person does something in a reply's UI that's for the agent, such as tapping a place, choosing a follow-up or submitting a form, the host calls its send with an AIUIAction. Ask the session with it, as AgentTransport does above: action.label is the question, in the person's words, such as "Tell me more about St. Naum", and action.toJson() is what they did, passed as uiAction to responses.create. See Send what the person did in a reply's UI.

Property Description
messageId The reply whose UI it came from.
format The format of that UI.
name What happened, such as a component's event (ask_about) or an action of the format, such as OpenUI's continue_conversation.
label What the person did, in their words. Use it as the question.
payload The details, in the format's own shape, such as what was chosen and a form's values.

The Flutter guide sends the action to the channel, with action.toCustomData() in the message's extra data. The agent doesn't answer a message sent to the session's channel, so ask the session instead: the router writes the person's message into the channel itself, with the action on it.

The host sends a reply's actions one after another, in the order they happened, and reports a send that throws to FlutterError.onError. responses.create throws an AgentsException when asking fails: catch it to show the person, as the Flutter assistant does. The SDK's renderers label an action with the control the person tapped, never with text the agent wrote for it, so the conversation shows only what the person chose. OpenUI sends only the values of the form the action belongs to, and never a password field's value.

Info:

The Flutter SDK takes uiAction from stream_agents 0.7.0.

The action 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 router keeps it on the person's message as custom.ai_ui_action, and tells the model what they did after their words, with the opening words of the reply it was in. The model reads the action as data, not as instructions.

A card can also bring a tool of its own, for the agent to act on what the person chose in it, such as booking the table they tapped in a seat selector. Give the tool to the session when the card shows and take it back once the card has done its job. That way the agent can take the action only while the card offering it is on the screen.

Examples

React

The Swift assistant sample plans a trip as interactive UI. Its settings choose how the agent answers: in Markdown, or with UI in A2UI or OpenUI. Ask "Plan a weekend in Ohrid" and the reply is a map of the places, the person's own calendar for those days, a tab for each day and a form to change the plan. The map, the place cards and the calendar are the app's own views, described once in UIComponents.json and placed by both formats. The agent learns them from a2ui/instructions.md or openui/instructions.md, which are generated from that file with the renderers' own code. When the settings change, the sample's backend rewrites the agent's instructions: its instructions.md, followed by the chosen format's.

The React assistant sample shows the same replies in the browser. It has its own components for the map, the place cards and the calendar, and for booking a table: a restaurant card, a gauge of how busy it is and a seat picker. Tapping a place or sending the form asks the agent in the person's words, with what they did as its uiAction, and the agent answers with a new plan. You can also switch the brand from its menu, and its voice mode shows UI during calls.

The Android assistant sample shows them in a Compose app. Its Settings screen chooses how the agent answers: in Markdown, or with UI in A2UI or OpenUI.

React Native

The React Native assistant sample plans a trip as interactive UI in A2UI, in an Expo app. Ask "Plan a weekend in Ohrid" and the reply is a map of the places, a tab for each day and a form to change the plan, built from the app's own components. Tapping a place or sending the form asks the agent in the person's words, with what they did as its uiAction, and the agent answers with a new plan.

Swift

The Swift assistant sample plans a trip as interactive UI. Its settings choose how the agent answers: in Markdown, or with UI in A2UI or OpenUI. Ask "Plan a weekend in Ohrid" and the reply is a map of the places, the person's own calendar for those days, a tab for each day and a form to change the pace and the interests. Ask "Where should we eat in Ohrid tonight?" and you get a card for each restaurant, a gauge of how busy the first one is, and a picker for its tables.

Build your app on Stream's hosted router, as the iOS quickstart does: StreamAgents(apiKey:) connects with your app's API key, and the router runs the agent and its models, so you deploy nothing else. Read the sample for how its parts fit, and bring them into that app.

  • AgentChat.swift keeps one AIUIHost with both renderers for each conversation, so a reply shows whichever UI it carries, and its send asks the session with responses.create(_:uiAction:). It uses LiveUI, so cards build up as the socket streams them, with an animation as the reply's text turns into the card.
  • TripComponents.swift has the app's own views: the map, the place cards, the calendar and the booking views. They're described once in UIComponents.json, which the app decodes as [AIUIComponentDefinition], and both formats place them. The cards load their photos from Wikipedia and the calendar reads EventKit on the phone, so the agent never sees the person's calendar.
  • prompts/generate.sh writes a2ui/instructions.md and openui/instructions.md from that file with the renderers' own code, from a stream-chat-swift checkout. Each prompt.json picks the components the agent can use and says when to write UI. It also asks for an openui-patch when the person changes the last card, such as the party size, and lets the agent show UI on calls. Its examples have to render, or nothing is written. It builds the renderers' internal prompt code for that, so an app of yours that doesn't need it writes the instructions from a test instead.
  • When the settings change, the sample's backend rewrites the agent's instructions: its instructions.md, followed by the chosen format's. A conversation keeps the instructions it started with, so the next new one is the first to answer the new way.
  • VoiceMode.swift shows the agent's latest UI during a call, under the glow, using its own host.
  • Settings > Brand (Brand.swift) changes the UI's accent color and corner radius: Stream Default, Ember Hospitality or Nordic Mobility. The open conversation switches right away: it creates its host again with the brand's A2UITheme and OpenUITheme, and the app's own components read the brand from the environment.

Tapping a place, a pin on the map, a follow-up, a free table or the form's button asks the agent in the person's words, such as "Update the plan", with the form's values in the action, and the agent answers again. The React assistant and Android assistant samples show the same replies in the browser and in a Compose app.

Kotlin

The Android assistant sample shows the replies of the Swift assistant's agent in a Compose app. Its Settings screen chooses how the agent answers: in Markdown, or with UI in A2UI or OpenUI. Ask "Plan a weekend in Ohrid" and the reply shows its UI in place of its words.

  • ChatViewModel.kt keeps one AIUIHost with both renderers for the screen's life, whatever the format, so a reply shows whichever UI it carries, and earlier replies keep their UI and its state when the format changes.
  • AgentTransport.kt gives each message its uiDocument with AIUIDocument.from(message.extraData), and its send asks the session with responses.create(request.text, uiAction = request.uiAction?.json). It uses LiveUI, so cards build up as the socket streams them. The conversation's state shows the person why when asking fails.
  • components/ has the app's own views: the map, the place cards, the calendar and the booking views. They're described once in UIComponents.json, a copy of the Swift assistant's, which TripComponents.kt reads as AIUIComponentDefinitions. The place cards load their photos and the calendar reads the person's own days, which the agent never sees.
  • ChatScreen.kt passes the host to AIConversation as ui. VoiceMode.kt shows the agent's latest UI during a call, using its own host.
  • Settings > Brand (Brand.kt) changes the UI's accent color and corner radius: Stream Default, Ember Hospitality or Nordic Mobility. The open conversation switches right away.
  • The setting is kept by the Swift assistant's backend (GET and PUT /reply-format), which rewrites the agent's instructions: its instructions.md, followed by the chosen format's. So every app answers the same way, from the next new conversation on.

Tapping a place, a pin on the map, a follow-up, a free table or a form's button asks the agent in the person's words, with what they did as its uiAction, and the agent answers again.

Dart

The Flutter assistant sample shows the replies of the Swift assistant's agent in a Flutter app, on iOS and Android. Its Settings screen chooses how the agent answers: in Markdown, or with UI in A2UI or OpenUI. Ask "Plan a weekend in Ohrid" and the reply is a map of the places, the person's own calendar for those days, a tab for each day and a form to change the pace and the interests. Ask where to eat and you get a restaurant card, a gauge of how busy it is, and a table picker.

  • agent_chat.dart keeps one AIUIHost with both renderers for each conversation, so a reply shows whichever UI it carries. It reads each message's UI with AIUIDocument.fromCustomData(message.extraData), uses LiveUI to show the socket's UI while a reply is written, and sends what the person does with responses.create(action.label, uiAction: action.toJson()). If that fails, it tells the person why.
  • trip_components.dart has the app's own widgets: the map, the place cards, the calendar and the booking widgets. They're described once in assets/UIComponents.json, a copy of the Swift assistant's, which the app reads with AIUIComponentDefinition.fromJson. The cards load their photos from Wikipedia and the calendar reads the phone's own, so the agent never sees the person's calendar.
  • chat_screen.dart passes the host to AIConversationView as ui. voice_screen.dart shows the agent's latest UI during a call, using its own host.
  • Settings also lets you switch the brand (brand_theme.dart): Stream Default, Ember Hospitality or Nordic Mobility. The open conversation updates right away.
  • The reply format is kept by the Swift assistant's backend (GET and PUT /reply-format), which rewrites the agent's instructions: its instructions.md, followed by the chosen format's. So every app answers the same way, from the next new conversation on.

Tapping a place, a pin on the map, a follow-up, a free table or a form's button asks the agent in the person's words, with what they did as its uiAction, and the agent answers again.