Generative UI (A2UI)
A2UI (“Agent to UI”) is an open, transport-agnostic, JSON-based streaming UI protocol designed for agentic applications.
In standard conversational AI, agents communicate with users strictly through text or Markdown prose. With A2UI, an agent can stream rich, interactive UI surfaces—such as cards, lists, input forms, and buttons—that client applications render incrementally in real time as the model generates them.
How a surface travels
Section titled “How a surface travels”A surface rides on its own data part channel within the Genkit streaming response:
- The server middleware emits Genkit data parts carrying the MIME type
application/a2ui+json. - The part’s
datapayload is an object{"envelopes": [...]}wrapping an array of A2UI v0.9 envelope messages, such ascreateSurface,updateComponents, andupdateDataModel. - This follows the A2A binding of the A2UI specification, so emitted envelopes are byte-compatible across the JavaScript, Go, and Python packages, and can be consumed by standard
@a2ui/*web renderers.
Because the wire protocol is decoupled from the server language, an agent written in Go, JavaScript/TypeScript, or Python can stream to the same web frontend.
- The server middleware emits Genkit data parts carrying the MIME type
application/a2ui+json, following the A2UI extension spec. - The part’s
datapayload is an object{"messages": [...]}wrapping a list of A2UI messages, such ascreateSurface,updateComponents, andupdateDataModel. By default these are A2UI v1.0 messages. - The part’s
metadata.a2uiExpressholds the compact source the model wrote for that surface. It’s what the model sees of the surface on later turns, so clients that manage history must send parts back with their metadata intact.
{ "data": { "messages": [ { "version": "1.0", "deleteSurface": { "surfaceId": "tokyo-weather" } }, { "version": "1.0", "createSurface": { "surfaceId": "tokyo-weather", "catalogId": "https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json", "components": [{ "id": "root", "component": "Text", "text": "Sunny, 18C" }] } } ] }, "metadata": { "mimeType": "application/a2ui+json", "a2uiExpress": "surface(\"tokyo-weather\")\nroot = Text(\"Sunny, 18C\")" }}Server: Add the middleware
Section titled “Server: Add the middleware”To give an agent generative UI capabilities, attach the A2UI middleware to your agent or model pipeline. The middleware injects the active catalog’s capabilities into the prompt, intercepts streamed model outputs, extracts a2ui fenced code blocks, validates them against the catalog, and rewrites them into canonical A2UI data parts. Outside these blocks, standard prose passes through untouched.
To give an agent generative UI capabilities, attach the A2UI middleware to your agent or model pipeline. The middleware injects the active catalog and the A2UI Express contract into the prompt, intercepts streamed model outputs, extracts the <a2ui> blocks the model writes, compiles and validates them against the catalog, and rewrites them into canonical A2UI data parts. Outside these blocks, standard prose passes through untouched.
Install the server plugin
Section titled “Install the server plugin”Install @genkit-ai/a2ui along with your core Genkit packages:
npm install @genkit-ai/a2ui genkit @genkit-ai/google-genai @genkit-ai/expresspnpm add @genkit-ai/a2ui genkit @genkit-ai/google-genai @genkit-ai/expressyarn add @genkit-ai/a2ui genkit @genkit-ai/google-genai @genkit-ai/expressbun add @genkit-ai/a2ui genkit @genkit-ai/google-genai @genkit-ai/expressConfigure the agent
Section titled “Configure the agent”Pass a2ui() in the agent’s use array. When configured without options, the agent defaults to the bundled basic catalog, exposing 12 core layout, content, and interactive components.
import { genkit, z, InMemorySessionStore } from 'genkit/beta';import { googleAI } from '@genkit-ai/google-genai';import { a2ui } from '@genkit-ai/a2ui';import { expressHandler } from '@genkit-ai/express';import express from 'express';
const ai = genkit({ plugins: [googleAI()],});
// A sample tool the model can call to fetch data before generating UIconst getWeather = ai.defineTool( { name: 'getWeather', description: 'Gets current weather conditions for a city.', inputSchema: z.object({ city: z.string() }), outputSchema: z.object({ city: z.string(), tempC: z.number(), condition: z.string(), humidity: z.number(), }), }, async ({ city }) => { return { city, tempC: 22, condition: 'Partly cloudy', humidity: 55, }; },);
export const uiAgent = ai.defineAgent({ name: 'uiAgent', model: googleAI.model('gemini-flash-latest'), system: `You are an interactive assistant that can render rich UI surfaces.Prefer rendering an A2UI surface whenever a visual display is clearer than plain prose,such as weather forecasts, comparisons, lists, forms, or interactive cards. Keep prosebrief and place the primary information in the UI components.`, tools: [getWeather], use: [a2ui()], store: new InMemorySessionStore(),});
// Serve the agent over HTTPconst app = express();app.use(express.json());app.post('/api/uiAgent', expressHandler(uiAgent));app.listen(8080, () => { console.log('Server running on http://localhost:8080');});The middleware also works with one-shot ai.generate() calls:
const response = await ai.generate({ model: googleAI.model('gemini-flash-latest'), prompt: 'Show me the current weather in Tokyo', use: [a2ui()],});Options
Section titled “Options”The a2ui() middleware accepts the following options:
| Option | Default | Description |
|---|---|---|
catalog | 'basic' | Catalog ID resolved from the Genkit registry. |
instructions | 'system' | Where to inject catalog capabilities. Set to 'system' to append to the system prompt, or 'none' to omit. |
validate | 'warn' | Envelope validation strategy. 'warn' logs invalid envelopes and drops them; 'strict' throws errors on validation failure; 'off' disables envelope checking. |
surfaceId | undefined | Surface ID assignment policy. Defaults to generating a fresh UUID per surface. Provide a fixed string to reuse a single surface. |
version | 'v0.9' | The A2UI protocol version stamped on emitted envelopes. |
Install the Go package
Section titled “Install the Go package”Add the A2UI plugin to your Go module:
go get github.com/firebase/genkit/go/plugins/a2ui/expThe package declares itself exp, so these examples import it as a2uix, the same convention as aix and genkitx.
Configure the agent
Section titled “Configure the agent”Attach &a2uix.Surfaces{} with ai.WithUse to an agent’s prompt or a generate call. When called without options, it defaults to the bundled basic catalog.
The basic-middleware/a2ui sample serves an agent configured with the middleware:
package main
import ( "context" "log" "net/http"
"github.com/firebase/genkit/go/ai" aix "github.com/firebase/genkit/go/ai/exp" "github.com/firebase/genkit/go/ai/exp/localstore" "github.com/firebase/genkit/go/genkit" genkitx "github.com/firebase/genkit/go/genkit/exp" a2uix "github.com/firebase/genkit/go/plugins/a2ui/exp" "github.com/firebase/genkit/go/plugins/googlegenai" "github.com/firebase/genkit/go/plugins/middleware")
func main() { ctx := context.Background() g := genkit.Init(ctx, genkit.WithExperimental(), genkit.WithPlugins(&googlegenai.GoogleAI{}), )
type WeatherInput struct { City string `json:"city"` }
type WeatherOutput struct { City string `json:"city"` TempC float64 `json:"tempC"` Condition string `json:"condition"` Humidity int `json:"humidity"` }
getWeather := genkit.DefineTool(g, "getWeather", "Gets current weather conditions for a city.", func(ctx *ai.ToolContext, in WeatherInput) (WeatherOutput, error) { return WeatherOutput{ City: in.City, TempC: 22, Condition: "Partly cloudy", Humidity: 55, }, nil }, )
uiAgent := genkitx.DefineAgent(g, "uiAgent", aix.InlinePrompt{ ai.WithModelName("googleai/gemini-flash-latest"), ai.WithSystem("You are a helpful assistant that can render rich UI. Prefer a surface whenever a result is clearer shown than told."), ai.WithTools(getWeather), ai.WithUse(&middleware.Retry{MaxRetries: 5}, &a2uix.Surfaces{}), }, aix.WithSessionStore(localstore.NewInMemorySessionStore[any]()), )
mux := http.NewServeMux() mux.Handle("/api/uiAgent", genkit.Handler(uiAgent)) mux.Handle("/api/uiAgent/getSnapshot", genkit.Handler(uiAgent.GetSnapshotAction())) mux.Handle("/api/uiAgent/abort", genkit.Handler(uiAgent.AbortAction()))
log.Println("Server running on http://localhost:8080") http.ListenAndServe(":8080", mux)}POST /api/uiAgent is the standard endpoint expected by client applications, with getSnapshot and abort at the sub-paths derived by the client. See Serve agents over HTTP for endpoint routing and CORS setup.
You can also attach the middleware to a standalone genkit.Generate call:
resp, err := genkit.Generate(ctx, g, ai.WithModelName("googleai/gemini-flash-latest"), ai.WithSystem("You help users. Render UI when it is clearer than prose."), ai.WithPrompt("Show me the weather in Tokyo."), ai.WithUse(&a2uix.Surfaces{}),)if err != nil { return err}
for _, envelope := range a2uix.EnvelopesFromParts(resp.Message.Content) { log.Println(envelope)}The middleware maintains streaming turn state. When pairing with middleware that re-invokes the model (such as Retry or Fallback), place them outside Surfaces: ai.WithUse(&middleware.Retry{}, &a2uix.Surfaces{}) ensures each retry attempt gets a fresh A2UI turn.
a2uix.EnvelopesFromParts extracts envelopes from any message or chunk content, while a2uix.IsPart reports whether a given part carries A2UI data.
Options
Section titled “Options”Every field of a2uix.Surfaces is per-call configuration:
| Field | Default | Description |
|---|---|---|
Catalog | nil | An inline catalog for code-defined use. Overrides CatalogID when set. Not serialized for JSON-dispatched calls; prefer CatalogID. |
CatalogID | "basic" | The ID of a catalog registered with LoadCatalog, resolved from the registry on each call. |
Instructions | "system" | Where the catalog’s capabilities are injected. Set to "none" to omit prompt injection when managing instructions manually. |
Validate | "warn" | How malformed envelopes are handled: "warn" logs and drops the block; "strict" fails the call; "off" passes everything through. See The trust boundary and security. |
SurfaceID | a fresh UUID | A fixed surface ID to reuse for every surface, for a client that maintains a single live surface. |
Version | "v0.9" | The protocol version stamped on envelopes. Must be one of a2uix.SupportedVersions. |
Register as a plugin
Section titled “Register as a plugin”Passing &a2uix.Surfaces{} directly to ai.WithUse does not require registering a plugin. However, registering &a2uix.A2UI{} makes the middleware discoverable by name in the Developer UI and in .prompt files (use: [a2ui]):
g := genkit.Init(ctx, genkit.WithExperimental(), genkit.WithPlugins(&googlegenai.GoogleAI{}, &a2uix.A2UI{}),)Install the server package
Section titled “Install the server package”Add genkit_a2ui alongside your core Genkit packages:
dart pub add genkit genkit_a2ui genkit_google_genaigenkit_a2ui is server-side only. Clients don’t depend on it (see Client: Render surfaces).
Configure the agent
Section titled “Configure the agent”In Genkit Dart, middleware is resolved from the registry, so you must register A2uiPlugin() in Genkit(plugins: [...]) before referencing a2ui(). Add a2ui() to the agent’s use list to enable generative UI with the default basic catalog (A2UI v1.0):
import 'package:genkit/experimental.dart';import 'package:genkit/experimental_io.dart';import 'package:genkit/genkit.dart';import 'package:genkit/io.dart';import 'package:genkit_a2ui/a2ui.dart';import 'package:genkit_google_genai/genkit_google_genai.dart';
// Register A2uiPlugin so `use: [a2ui()]` resolves from the registryfinal ai = Genkit(plugins: [googleAI(), A2uiPlugin()]);
final uiAgent = ai.defineAgent( name: 'uiAgent', model: googleAI.gemini('gemini-flash-latest'), system: 'You help users. Render UI when it is clearer than prose.', use: [a2ui()], // defaults to the bundled 'basic' catalog store: InMemorySessionStore(),);
// Serve the agent over HTTP: /api/uiAgent plus /getSnapshot and /abortvoid main() async { final genkit = GenkitRouter()..addAgent(uiAgent, path: '/api/uiAgent'); await genkit.serve( port: 8080, // Flutter web and other browser clients run on another origin. cors: const CorsOptions(), );}The middleware also works with one-shot ai.generate() calls. a2uiEnvelopesFromParts reads the A2UI messages out of the response:
final res = await ai.generate( model: googleAI.gemini('gemini-flash-latest'), prompt: 'Show me the weather in Tokyo', use: [a2ui()],);
for (final message in a2uiEnvelopesFromParts(res.message?.content)) { print(message);}Options
Section titled “Options”Pass configuration options to a2ui(...):
| Option | Default | Description |
|---|---|---|
catalog | 'basic' | Catalog ID resolved from the Genkit registry. 'basic' is the A2UI v1.0 basic catalog; 'basic-v0.9' keeps v0.9. |
instructions | 'system' | Where to inject catalog capabilities. Set to 'system' to append to the system prompt, or 'none' to omit (start your own prompt from renderCatalogInstructions(catalog)). |
validate | 'warn' | What to do with a block that fails to compile or validate. 'warn' logs and drops it; 'strict' fails the turn; 'off' checks only that the block compiles, not the component tree. See The trust boundary and security. |
repair | true | Ask the model once to fix a block that failed to compile. Costs an extra model call on the failure path only. See Self-repair. |
version | from catalog | Optional assertion ('1.0' or 'v0.9'). The catalog decides which protocol version a turn emits; passing version fails the turn if the resolved catalog targets another one. |
When the model renders
Section titled “When the model renders”The injected instructions ask for a surface when the answer is data the user will look at or act on (structured tool results, comparisons, choices, forms), and for plain prose otherwise. They yield to your system prompt, so steer from there:
ai.defineAgent( name: 'dashboard', // More surfaces: system: 'Answer with an A2UI surface whenever you can, explanations included.', // Or fewer: 'Only render a surface when the user asks for one.' use: [a2ui()],);Surfaces: create, replace, and update
Section titled “Surfaces: create, replace, and update”The model writes each surface in A2UI Express, a compact positional notation that costs far fewer tokens than the equivalent JSON:
surface("tokyo-weather")root = Card(Column([title, refresh]))title = Text("## Weather in Tokyo")refresh = Button(Text("Refresh"), "primary", Event("refresh", {city: "Tokyo"}))The model names each surface, and the ID reaches the client unchanged:
-
Rendering an ID again replaces that surface. The middleware puts a
deleteSurfacein front of everycreateSurface, since renderers reject a secondcreateSurfacefor a live ID. For a new surface the delete is a no-op. Custom renderers must treat adeleteSurfacefor an unknown ID as a no-op too. -
A block without
rootupdates a live surface. It carries only what changed, asupdateComponentsorupdateDataModelmessages. For example, this updates whatever the surface bound to$/temp:surface("tokyo-weather")$/temp = "21C"
Because a part can carry only updates for a surface an earlier part or turn created, clients must feed every message from every part, in order, into one renderer per conversation, and render each surface once, keyed by its ID.
Unless validate is 'off', every block is checked against the surfaces the conversation’s history left on the client, so an update must target a live surface and leave its component tree valid. remoteAgent and session stores send A2UI parts back with the history, which is what makes this work.
Self-repair
Section titled “Self-repair”Models occasionally emit a block that doesn’t compile, most often by putting a label where a component ID belongs (Button("Refresh", ...) instead of Button(Text("Refresh"), ...)). When that happens, the middleware sends a follow-up call with the error, the Express contract, and the failed block, then compiles the reply. If the repair works, the surface renders; if not, the block is dropped (or 'strict' fails the turn). That is at most one call per distinct broken block, 3 per model call, and 30 seconds in total.
Repair runs once the model’s response is complete, so a repaired surface arrives as the last chunk of the stream rather than where the model wrote it. Its token usage is added to the turn’s usage, and cancelling the turn cancels a repair in flight.
To see the model’s own mistakes while developing, turn repair off:
use: [a2ui(validate: 'strict', repair: false)]Install the server package
Section titled “Install the server package”Add genkit-a2ui alongside your core Genkit packages:
uv add genkit genkit-a2ui genkit-google-genai genkit-fastapi genkit-middlewareConfigure the agent
Section titled “Configure the agent”Pass Surfaces() from genkit_a2ui in the agent’s use list. When configured without arguments, Surfaces() defaults to the bundled 'basic' catalog.
from fastapi import FastAPIfrom pydantic import BaseModel
from genkit.exp import Genkitfrom genkit.exp.agent import InMemorySessionStorefrom genkit_a2ui import Surfacesfrom genkit_fastapi.exp import serve_agentfrom genkit_google_genai import GoogleAIfrom genkit_middleware import Retry
ai = Genkit(plugins=[GoogleAI()])
class WeatherInput(BaseModel): city: str
class WeatherOutput(BaseModel): city: str temp_c: float condition: str humidity: int
@ai.tool()async def get_weather(input: WeatherInput) -> WeatherOutput: """Gets current weather conditions for a city.""" return WeatherOutput( city=input.city, temp_c=22.0, condition='Partly cloudy', humidity=55, )
ui_agent = ai.define_agent( name='uiAgent', model=GoogleAI.gemini('gemini-flash-latest'), system=( 'You are an interactive assistant that can render rich UI surfaces. ' 'Prefer rendering an A2UI surface whenever a visual display is clearer than plain prose, ' 'such as weather forecasts, comparisons, lists, forms, or interactive cards. ' 'Keep prose brief and place the primary information in the UI components.' ), tools=[get_weather], use=[Retry(max_retries=3), Surfaces()], store=InMemorySessionStore(),)
app = FastAPI()app.include_router(serve_agent(ui_agent), prefix='/api')# Routes: /api/uiAgent, /api/uiAgent/getSnapshot, /api/uiAgent/abortSurfaces() also works with standalone ai.generate() calls. Use envelopes_from_parts() to extract emitted A2UI envelopes from message or stream chunk parts, and is_a2ui_part() to test individual parts:
from genkit_a2ui import Surfaces, envelopes_from_parts
response = await ai.generate( model=GoogleAI.gemini('gemini-flash-latest'), system='You help users. Render UI when it is clearer than prose.', prompt='Show me the current weather in Tokyo.', use=[Surfaces()],)
for envelope in envelopes_from_parts(response.message.content if response.message else None): print(envelope)Surfaces keeps per-turn streaming parser state. When pairing with middleware that re-runs the model (such as Retry or Fallback from genkit_middleware), place that middleware ahead of Surfaces (use=[Retry(max_retries=3), Surfaces()]) so each attempt starts with a fresh parser.
Options
Section titled “Options”Pass configuration keyword arguments directly to Surfaces(...) (validated by SurfacesConfig):
catalog(default'basic'): Catalog ID resolved from the Genkit registry on each call.instructions(default'system'): Where catalog capabilities are injected. Set to'system'to append to the system message, or'none'to omit prompt injection.validation(aliasvalidate, default'warn'): Envelope validation policy.'warn'logs malformed fences and drops them;'strict'fails the turn, so the response comes back withfinish_reason == 'failed'and nomessage;'off'passes parsed JSON objects through unchecked. See The trust boundary and security.surface_id(default fresh UUID): Surface ID assignment policy. Defaults to minting a UUID per surface; pass a fixed string to reuse a single live surface.version(default'v0.9'): Protocol version stamped on emitted envelopes ('v0.9'or'v0.9.1').
Register by name
Section titled “Register by name”Passing Surfaces() directly in use requires no registration. To list the middleware and the bundled catalog in the Developer UI, register both at startup. define_middleware() registers Surfaces as surfaces; pass name='a2ui' to match the name the JavaScript and Go plugins use.
from genkit_a2ui import Surfaces, register_basic_catalog
ai.define_middleware(Surfaces, name='a2ui')register_basic_catalog(ai)Client: Render surfaces
Section titled “Client: Render surfaces”Because A2UI emits standardized JSON envelopes over HTTP, client-side rendering is completely decoupled from your backend language. A web frontend can interact directly with a backend written in TypeScript, Go, or Python.
Web clients use @a2ui/web_core and an A2UI renderer. A2UI provides official renderers for Web Components/Lit (@a2ui/lit), React (@a2ui/react), and Angular (@a2ui/angular).
The examples below use the Lit renderer.
1. Install client packages
Section titled “1. Install client packages”Install the client dependencies along with the @genkit-ai/a2ui client helper:
npm install @a2ui/lit @a2ui/web_core @a2ui/markdown-it lit @lit/context @genkit-ai/a2ui genkitpnpm add @a2ui/lit @a2ui/web_core @a2ui/markdown-it lit @lit/context @genkit-ai/a2ui genkityarn add @a2ui/lit @a2ui/web_core @a2ui/markdown-it lit @lit/context @genkit-ai/a2ui genkitbun add @a2ui/lit @a2ui/web_core @a2ui/markdown-it lit @lit/context @genkit-ai/a2ui genkit2. Add client font styles
Section titled “2. Add client font styles”The basic catalog’s Icon component renders icon names as ligatures using the Material Symbols Outlined font. Include the stylesheet in your web app’s HTML <head> so icons render visually:
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,0..1,0"/>3. Initialize client styles and markdown rendering
Section titled “3. Initialize client styles and markdown rendering”Initialize @a2ui/web_core styles and provide the Markdown renderer context on the document body so all <a2ui-surface> elements inherit formatting:
import { Context, basicCatalog } from '@a2ui/lit/v0_9';import '@a2ui/lit/v0_9'; // Registers <a2ui-surface> and basic catalog custom elementsimport { renderMarkdown } from '@a2ui/markdown-it';import { MessageProcessor } from '@a2ui/web_core/v0_9';import { injectBasicCatalogStyles } from '@a2ui/web_core/v0_9/basic_catalog';import { ContextProvider } from '@lit/context';
// Inject catalog stylinginjectBasicCatalogStyles();
// Provide the markdown renderer to surface elementsnew ContextProvider(document.body as any, { context: Context.markdown, initialValue: renderMarkdown,});4. Stream and process agent turns
Section titled “4. Stream and process agent turns”Connect to your backend endpoint using remoteAgent() from genkit/beta/client. Iterate over turn.stream, appending prose deltas to your chat view and feeding extracted A2UI envelopes into the MessageProcessor:
import { MessageProcessor } from '@a2ui/web_core/v0_9';import { basicCatalog } from '@a2ui/lit/v0_9';import { remoteAgent } from 'genkit/beta/client';import { a2uiEnvelopesFromParts, actionToMessage, type A2uiClientAction,} from '@genkit-ai/a2ui/client';
const agent = remoteAgent({ url: '/api/uiAgent' });const chat = agent.chat();
// Set up the message processor with the basic catalogconst processor = new MessageProcessor([basicCatalog], (action) => { handleAction(action as unknown as A2uiClientAction);});
// Mount new surfaces when createdprocessor.onSurfaceCreated((surface) => { const container = document.getElementById('chat-log')!; const surfaceEl = document.createElement('a2ui-surface') as any; surfaceEl.surface = surface; container.appendChild(surfaceEl);});
// Stream a user messageasync function sendMessage(text: string) { const turn = chat.sendStream(text);
for await (const chunk of turn.stream) { // 1. Render prose text deltas if (chunk.text) { appendProseText(chunk.text); }
// 2. Extract and process A2UI envelopes from raw data parts const envelopes = a2uiEnvelopesFromParts(chunk.raw.modelChunk?.content); if (envelopes.length > 0) { processor.processMessages(envelopes); } }
await turn.response;}Stream using the lightweight helper
Section titled “Stream using the lightweight helper”If you do not require full session management with remoteAgent, @genkit-ai/a2ui/client also provides the streamA2uiAgent async generator:
import { streamA2uiAgent } from '@genkit-ai/a2ui/client';
for await (const event of streamA2uiAgent({ url: '/api/uiAgent', message: 'What is the weather in Tokyo?',})) { if (event.type === 'text') { appendProseText(event.text); } else if (event.type === 'envelopes') { processor.processMessages(event.envelopes); }}streamA2uiAgent accepts sessionId, headers, and abortSignal in its configuration object.
Clients don’t depend on genkit_a2ui. A2UI arrives as plain, spec-shaped data parts, so a Flutter client needs only package:genkit and a renderer: a2ui_flutter renders surfaces, and a2ui_core processes messages and holds each surface’s state.
1. Install client packages
Section titled “1. Install client packages”Add the client packages to your Flutter app:
flutter pub add genkit a2ui_flutter a2ui_core url_launcherurl_launcher backs the basic catalog’s openUrl function, which a2ui_core doesn’t bundle.
An app that hosts the agent in-process can depend on both genkit_a2ui and a2ui_flutter, since both build on a2ui_core 0.7. a2ui_core is pre-1.0 and still makes breaking releases, so running the agent in a server package of its own (as the sample does) keeps it from holding back the renderer version.
2. Copy the A2UI helpers
Section titled “2. Copy the A2UI helpers”Copy these two helpers into your app. a2uiMessagesFrom reads A2UI messages out of a chunk’s or message’s parts, and a2uiActionToMessage wraps a surface action as the next agent input:
import 'package:a2ui_core/a2ui_core.dart' show ActionMessage, RendererToAgentMessagePayload;import 'package:genkit/client.dart';
const a2uiMimeType = 'application/a2ui+json';
const _envelopeKeys = {'checks', 'accessibility', 'catalogId', 'metadata'};
/// The A2UI messages carried by a chunk's or message's parts.Iterable<Map<String, dynamic>> a2uiMessagesFrom(List<Part>? parts) sync* { for (final part in parts ?? const <Part>[]) { if (part.metadata?['mimeType'] != a2uiMimeType) continue; // `envelopes` is the pre-spec key, still written by older agents. Malformed // payloads are skipped rather than throwing mid-stream. final data = part.data; if ((data?['messages'] ?? data?['envelopes']) case final List messages) { yield* messages.whereType<Map>().map( (m) => _normalizeEnvelopeKeys( m is Map<String, dynamic> ? m : m.cast<String, dynamic>(), ), ); } }}
bool _hasAtEnvelopeKey(Object? c) => c is Map && c.keys.any( (k) => k is String && k.startsWith('@') && _envelopeKeys.contains(k.substring(1)) && !c.containsKey(k.substring(1)), );
/// Rewrites `@checks`, `@accessibility`, `@catalogId` and `@metadata` on v1.0/// components to the bare names that `a2ui_core` 0.7 expects, so this client/// keeps rendering if the agent moves to a newer SDK first. Delete it once your/// `a2ui_core` reads the `@` keys itself.Map<String, dynamic> _normalizeEnvelopeKeys(Map<String, dynamic> message) { if (message['version'] != '1.0') return message; for (final kind in const ['createSurface', 'updateComponents']) { if (message[kind] case final Map body) { if (body['components'] case final List components when components.any(_hasAtEnvelopeKey)) { return <String, dynamic>{ ...message, kind: <String, dynamic>{ ...body.cast<String, dynamic>(), 'components': <Object?>[ for (final c in components) if (c is Map) <String, dynamic>{ for (final MapEntry(:key, :value) in c.entries) if (key is String && key.startsWith('@') && _envelopeKeys.contains(key.substring(1)) && !c.containsKey(key.substring(1))) key.substring(1): value else '$key': value, } else c, ], }, }; } } } return message;}
/// Wraps a surface action (e.g. a button press) as the next agent input.////// `a2ui_core` writes the `{messages: [...]}` wrapper the agent reads, with/// the action in a spec-shaped `{version, action}` message, so it is forwarded/// as is.Message a2uiActionToMessage(ActionMessage action) => Message( role: .user, content: [ DataPart( data: RendererToAgentMessagePayload.of(action).toJson(), metadata: {'mimeType': a2uiMimeType}, ), ],);3. Set up the message processor and stream turns
Section titled “3. Set up the message processor and stream turns”Connect with remoteAgent and feed every A2UI message, in order, into one a2ui_core MessageProcessor per conversation:
import 'package:a2ui_core/a2ui_core.dart';import 'package:a2ui_flutter/a2ui_flutter.dart';import 'package:a2ui_flutter/basic_catalog.dart';import 'package:genkit/experimental_client.dart';import 'package:url_launcher/url_launcher.dart';
final agent = remoteAgent( url: 'http://localhost:8080/api/uiAgent', getSnapshotUrl: 'http://localhost:8080/api/uiAgent/getSnapshot', abortUrl: 'http://localhost:8080/api/uiAgent/abort',);final chat = agent.chat();
// True while a turn streams. A button press mid-stream would otherwise start// a second turn, interleaving both streams into the same processor.var busy = false;
// The renderer rejects a surface whose catalog ID it doesn't hold, so the ID// must match the catalog the agent uses. `basicCatalog()` has the same ID as// the plugin's bundled basic catalog.final processor = MessageProcessor<ComponentImplementation>( catalogs: [basicCatalog(openUrl: (uri) => launchUrl(uri))], // Deliver actions to `outboundListener` as typed, versioned messages. unifiedOutbound: true, // A surface action (e.g. a button press) becomes the next turn. outboundListener: (message) { if (message is ActionMessage && !busy) { runTurn(chat.sendStream(message: a2uiActionToMessage(message))); } }, onError: (error) => print('A2UI renderer error: ${error.message}'),);
Future<void> runTurn(AgentTurn turn) async { busy = true; try { await for (final chunk in turn.stream) { if (chunk.text.isNotEmpty) appendProse(chunk.text); for (final m in a2uiMessagesFrom(chunk.raw.modelChunk?.content)) { // One message the renderer can't take (a newer protocol version, say) // must not stop the rest of the turn. try { processor.processMessages([m]); } on Object catch (e) { print('Skipping an A2UI message: $e'); } } } await turn.response; } finally { busy = false; }}
// Apply the same `busy` check to your text input before starting a turn.await runTurn(chat.sendStream(text: 'What is the weather in Tokyo?'));4. Mount the surfaces
Section titled “4. Mount the surfaces”Listen to processor.model.onSurfaceCreated and onSurfaceDeleted, and render each surface with an A2uiSurface widget. Key the chat log by surface ID, so a replaced surface re-renders where it first appeared and an updated one changes in place:
final surfaceIds = <String>[];
// In initState:processor.model.onSurfaceCreated.subscribe((surface) { setState(() { if (!surfaceIds.contains(surface.id)) surfaceIds.add(surface.id); });});processor.model.onSurfaceDeleted.subscribe((_) => setState(() {}));
// In build, for each ID in surfaceIds:Widget buildSurface(String surfaceId) { final surface = processor.model.getSurface(surfaceId); // Deleted: keep the slot in case the agent renders the ID again. if (surface == null) return const SizedBox.shrink(); // A replaced surface is a new model, so key by it to start fresh. return A2uiSurface(key: ObjectKey(surface), surface: surface);}Handle user actions and forms
Section titled “Handle user actions and forms”When users interact with components (such as clicking a Button), the surface triggers an action that is sent back to the agent as the next conversational turn.
Use actionToMessage() to wrap the client action into an AgentInput message and send it as the next conversational turn:
import { actionToMessage, a2uiEnvelopesFromParts, type A2uiClientAction,} from '@genkit-ai/a2ui/client';
async function handleAction(action: A2uiClientAction) { // Send the action payload as the next turn in the conversation const turn = chat.sendStream({ message: actionToMessage(action), });
for await (const chunk of turn.stream) { if (chunk.text) appendProseText(chunk.text); const envelopes = a2uiEnvelopesFromParts(chunk.raw.modelChunk?.content); if (envelopes.length > 0) processor.processMessages(envelopes); }
await turn.response;}actionToMessage puts the action’s name in the user message text so models without custom prompt handling understand the action, and attaches the complete structured action data (including bound form context) as an A2UI data part. The server middleware sanitizes inbound action parts into concise text summaries for the model.
Form inputs and data binding
Section titled “Form inputs and data binding”Input components (TextField, CheckBox, and Slider) do not broadcast values on every keystroke. To capture input upon submission:
- The input component binds its
valueto a data-model path (for example,{ "path": "/email" }). - The submit
Buttonspecifies those same data-model paths in itsaction.event.context.
The instructions injected by the A2UI middleware guide the model to configure these bindings. When the user clicks submit, the client renderer resolves the bound paths from the surface data model and passes the values in action.context.
The outboundListener from the previous section already does this: a2uiActionToMessage sends the action back as an A2UI data part carrying an action message. The middleware turns it into a line the model can read, so no accompanying text is needed:
[UI action "refresh" from refreshBtn on surface tokyo-weather context={"city":"Tokyo"}]Form inputs and data binding
Section titled “Form inputs and data binding”Input components (TextField, CheckBox, Slider, ChoicePicker, and DateTimeInput) don’t send their values automatically. To capture what the user entered, the model must:
- Bind each input’s value to a data-model path:
email = TextField("Email", $/email). - Echo those same paths in the submit button’s event context:
Event("submit", {email: $/email}).
The instructions injected by the A2UI middleware already tell the model to do this. When the user clicks submit, the renderer resolves the bound paths from the surface’s data model and passes the values in the action’s context. Without both steps, the action arrives with an empty context.
The basic component catalog
Section titled “The basic component catalog”The built-in basic catalog provides 12 core components across layout, content, and interactive categories:
Layout components
Section titled “Layout components”Row: Lays out child components horizontally.- Props:
children: string[](required IDs),justify?: start|center|end|spaceAround|spaceBetween|spaceEvenly|stretch,align?: start|center|end|stretch.
- Props:
Column: Lays out child components vertically.- Props:
children: string[](required IDs),justify?: start|center|end|spaceBetween|spaceAround|spaceEvenly|stretch,align?: start|center|end|stretch.
- Props:
List: Displays a scrollable or sequential list of items.- Props:
children: string[](required IDs),direction?: vertical|horizontal,listStyle?: ordered|unordered|none.
- Props:
Card: A styled card container with elevation and borders wrapping a single child.- Props:
child: string(required ID of the child component; use aColumnorRowto group multiple elements).
- Props:
Divider: A visual separator line.- Props:
axis?: horizontal|vertical.
- Props:
Content components
Section titled “Content components”Text: Displays plain text or inline Markdown.- Props:
text: string(required),variant?: h1|h2|h3|h4|h5|caption|body.
- Props:
Image: Displays a remote image.- Props:
url: string(required),description?: string,fit?: contain|cover|fill|none|scaleDown,variant?: icon|avatar|smallFeature|mediumFeature|largeFeature|header.
- Props:
Icon: Displays a standard Material symbol ligature.- Props:
name: string(required). Must be one of the supported names, such ascheck,close,refresh,star,info,warning,error,search,home, orfavorite.
- Props:
Interactive components
Section titled “Interactive components”Button: A clickable button that fires an action back to the agent.- Props:
child: string(required child ID, typically aText),variant?: default|primary|borderless,action: { event: { name: string, context?: object } }(required).
- Props:
TextField: A single- or multi-line text input field.- Props:
label: string(required),value?: string or { path } binding,variant?: shortText|longText|number|obscured.
- Props:
CheckBox: A toggleable checkbox.- Props:
label: string(required),value: boolean or { path } binding(required).
- Props:
Slider: A numeric range slider.- Props:
max: number(required),value: number or { path } binding(required),min?: number,step?: number,label?: string.
- Props:
The bundled basicCatalog is the A2UI v1.0 basic catalog: 18 components across layout, content, and interactive categories. A2UI Express is positional, so the order of a component’s properties is the order of its arguments (Button(Text("Go"), "primary", Event("go"))). Optional properties are marked with ?.
Layout components
Section titled “Layout components”| Component | Arguments |
|---|---|
Row | children, justify? (start, center, end, spaceAround, spaceBetween, spaceEvenly, stretch), align? (start, center, end, stretch) |
Column | children, justify?, align? (same values as Row) |
List | children, direction? (vertical, horizontal), align? |
Card | child (use a Column or Row to group several elements) |
Tabs | tabs (a list of {title, child}) |
Modal | trigger (the component that opens it), content |
Divider | axis? (horizontal, vertical) |
Content components
Section titled “Content components”| Component | Arguments |
|---|---|
Text | text (inline Markdown; use heading lines such as "## Title" for headings), variant? (caption, body) |
Image | url, description?, fit? (contain, cover, fill, none, scaleDown), variant? (icon, avatar, smallFeature, mediumFeature, largeFeature, header) |
Icon | name: one of the names in basicIconNames, such as check, close, refresh, star, info, warning, error, search, or home |
Video | url, posterUrl? |
AudioPlayer | url, description? |
Interactive components
Section titled “Interactive components”| Component | Arguments |
|---|---|
Button | child (a component ID, typically a Text), variant? (default, primary, borderless), action (Event(name, context?)) |
TextField | label, value, placeholder?, variant? (shortText, longText, number, obscured) |
CheckBox | label, value |
ChoicePicker | label?, variant? (multipleSelection, mutuallyExclusive), options (a list of {label, value}), value, displayStyle? (checkbox, chips), filterable? |
Slider | label?, min?, max, value, steps? |
DateTimeInput | value, enableDate?, enableTime?, min?, max?, label? |
Text-like and value arguments accept either a literal or a data binding ($/path).
To keep emitting A2UI v0.9 (for example, while some clients still render v0.9 only), pass a2ui(catalog: 'basic-v0.9') or extend basicCatalogV09. It has the 12 v0.9 components, without Tabs, Modal, Video, AudioPlayer, ChoicePicker, and DateTimeInput.
Custom catalogs
Section titled “Custom catalogs”When you want agents to render custom UI widgets or components tailored to your design system, you can register a custom catalog. A catalog defines:
id: A globally unique URI for the catalog (matching the client-side renderer).components: An array of component definitions withname,description, and compactpropsdocumentation.propsis model-facing guidance rather than strict JSON Schema, keeping injected prompt tokens minimal.
Catalog JSON definition
Section titled “Catalog JSON definition”Define your catalog in a JSON file (such as ./catalogs/dashboard.json):
{ "id": "https://example.com/catalogs/dashboard.json", "components": [ { "name": "MetricCard", "description": "Displays a key metric with a title, numeric value, and change indicator.", "props": "title: string (required); value: string|number (required); trend?: up|down|neutral; percentage?: number." }, { "name": "Text", "description": "Displays plain or inline-markdown text.", "props": "text: string (required); variant?: body|caption." } ]}Register the catalog on the server
Section titled “Register the catalog on the server”When you want agents to render custom UI widgets or components tailored to your design system, define a custom catalog, register it with loadCatalog, and reference it by ID.
Catalog format
Section titled “Catalog format”Catalogs use the A2UI specification’s catalog.json format, so a published catalog loads unmodified:
catalogId: A globally unique URI identifying the catalog. It’s sent ascatalogIdoncreateSurface, and the client must register a catalog under the same ID.protocolVersion:"1.0"for A2UI v1.0 catalogs (omitted on v0.9 catalogs). The catalog’s protocol version decides what the middleware emits.components: An object keyed by component name, where each value is the component’s JSON Schema. The schema’sdescriptionand property descriptions are what the model sees.functions(optional): Client functions (validation checks, formatters), keyed by name.
Property order matters: A2UI Express is positional, so the model writes MetricCard("Revenue", "$1.2M", "up"), and the order of a component’s properties decides which argument is which.
Option A: Load from a JSON file
Section titled “Option A: Load from a JSON file”Define the catalog in a JSON file (such as ./catalogs/dashboard.json):
{ "catalogId": "https://example.com/catalogs/dashboard.json", "protocolVersion": "1.0", "components": { "MetricCard": { "type": "object", "description": "Displays a key metric with a title, value, and trend indicator.", "properties": { "component": { "const": "MetricCard" }, "title": { "$ref": "common_types.json#/$defs/DynamicString" }, "value": { "$ref": "common_types.json#/$defs/DynamicString" }, "trend": { "type": "string", "enum": ["up", "down", "neutral"] } }, "required": ["component", "title", "value"] } }}Then register it under a lookup ID at startup, before the agent handles a turn:
import 'package:genkit_a2ui/a2ui.dart';
await loadCatalog(ai, id: 'dashboard', file: './catalogs/dashboard.json');Option B: Define it in code
Section titled “Option B: Define it in code”A2uiCatalogComponent.simple builds the same schema from a parameter list, so you don’t have to write JSON Schema by hand. Extend the bundled basic catalog to keep its standard components:
import 'package:genkit_a2ui/a2ui.dart';
final dashboardCatalog = basicCatalog.extend( id: 'https://example.com/catalogs/dashboard.json', components: [ A2uiCatalogComponent.simple( name: 'MetricCard', description: 'Displays a key metric with a title, value, and trend indicator.', params: [ // A literal or a data binding (`$/path`). const A2uiParam.dynamicValue('title', required: true), const A2uiParam.dynamicValue('value', required: true), // A literal only, restricted to these values. const A2uiParam.string('trend', enumValues: ['up', 'down', 'neutral']), ], ), ],);
await loadCatalog(ai, id: 'dashboard', catalog: dashboardCatalog);A2uiParam.dynamicValue takes a string unless you set its type (A2uiDynamicType.number, .boolean, .stringList, or .value). The other parameter kinds are A2uiParam.number, A2uiParam.boolean, A2uiParam.child (one child component ID), A2uiParam.children (a list of child IDs), A2uiParam.action (an event fired on interaction), and A2uiParam.schema (a hand-written JSON Schema). For inputs that accept validation checks, pass checkable: true to A2uiCatalogComponent.simple.
basicCatalog.extend keeps the basic catalog’s protocol version (v1.0). Extend basicCatalogV09 instead to build a v0.9 catalog.
Use the registered catalog
Section titled “Use the registered catalog”Reference the lookup ID in the a2ui() options:
final dashboardAgent = ai.defineAgent( name: 'dashboardAgent', model: googleAI.gemini('gemini-flash-latest'), system: 'You generate executive dashboards using MetricCards and structured layouts.', use: [a2ui(catalog: 'dashboard', validate: 'strict')], store: InMemorySessionStore(),);Catalogs live in the Genkit registry (value type a2ui-catalog), so the middleware resolves them by lookup ID on each call. The lookup ID is separate from the catalog’s catalogId URI, which is what the client matches.
Load the catalog file using loadCatalog:
import { loadCatalog } from '@genkit-ai/a2ui';
await loadCatalog(ai, { id: 'dashboard', file: './catalogs/dashboard.json',});You can also define catalogs directly in memory, extending basicCatalog:
import { loadCatalog, basicCatalog, type A2uiCatalog } from '@genkit-ai/a2ui';
const dashboardCatalog: A2uiCatalog = { id: 'https://example.com/catalogs/dashboard.json', components: [ ...basicCatalog.components, { name: 'MetricCard', description: 'Displays a key metric with a title, numeric value, and trend indicator.', props: 'title: string (required); value: string|number (required); trend?: up|down|neutral.', }, ],};
await loadCatalog(ai, { id: 'dashboard', catalog: dashboardCatalog,});To use it, pass the registered catalog ID to a2ui():
export const dashboardAgent = ai.defineAgent({ name: 'dashboardAgent', model: googleAI.model('gemini-flash-latest'), system: 'You generate executive dashboards using MetricCards and structured layouts.', use: [ a2ui({ catalog: 'dashboard', validate: 'strict', }), ],});Load a catalog from a JSON file with LoadCatalogFile, or construct a Catalog struct in memory and register it with LoadCatalog:
myCatalog := &a2uix.Catalog{ ID: "https://example.com/catalogs/dashboard.json", Components: []a2uix.CatalogComponent{ { Name: "MetricCard", Description: "Displays a key metric with a title, numeric value, and trend indicator.", Props: "title: string (required); value: string|number (required); trend?: up|down|neutral.", }, },}if err := a2uix.LoadCatalog(g, myCatalog); err != nil { return err}Or from a file:
catalog, err := a2uix.LoadCatalogFile(g, "./catalogs/dashboard.json")if err != nil { return err}LoadCatalogFile returns the parsed catalog, so catalog.ID is the key to reference it by.
Reference the registered catalog by ID in a2uix.Surfaces:
resp, err := genkit.Generate(ctx, g, ai.WithModelName("googleai/gemini-flash-latest"), ai.WithPrompt("Show dashboard metrics."), ai.WithUse(&a2uix.Surfaces{CatalogID: "https://example.com/catalogs/dashboard.json"}),)Catalogs live in the Genkit registry under a2ui-catalog. The Go plugin keys registrations by the catalog’s own ID, while JavaScript keys by a user-specified lookup key. The underlying wire protocol and catalog JSON schemas are identical.
Load a catalog from a JSON file with load_catalog_file(), or construct an A2uiCatalog in memory and register it with load_catalog():
from genkit_a2ui import ( A2uiCatalog, A2uiCatalogComponent, load_catalog, load_catalog_file, register_basic_catalog,)
# Option 1: Load from a JSON file (returns the parsed A2uiCatalog)file_catalog = load_catalog_file(ai, './catalogs/dashboard.json')
# Option 2: Build in memory (optionally extending the bundled basic catalog)basic_catalog = register_basic_catalog(ai)dashboard_catalog = A2uiCatalog( id='https://example.com/catalogs/dashboard.json', components=( *basic_catalog.components, A2uiCatalogComponent( name='MetricCard', description='Displays a key metric with a title, numeric value, and trend indicator.', props='title: string (required); value: string|number (required); trend?: up|down|neutral.', ), ),)load_catalog(ai, dashboard_catalog)genkit_a2ui keys registered catalogs in the Genkit registry by catalog.id. Pass that ID to Surfaces():
dashboard_agent = ai.define_agent( name='dashboardAgent', model=GoogleAI.gemini('gemini-flash-latest'), system='You generate executive dashboards using MetricCards and structured layouts.', use=[ Surfaces( catalog=dashboard_catalog.id, validation='strict', ), ], store=InMemorySessionStore(),)Register matching widgets on the client
Section titled “Register matching widgets on the client”The client application must register a matching catalog renderer under the exact same catalog ID and support the corresponding component names:
Create a custom component renderer and supply it alongside basicCatalog to the MessageProcessor:
import { MessageProcessor } from '@a2ui/web_core/v0_9';import { basicCatalog } from '@a2ui/lit/v0_9';
const customCatalog = { id: 'https://example.com/catalogs/dashboard.json', components: { // Custom web component renderers mapped to component names MetricCard: metricCardRenderer, },};
const processor = new MessageProcessor([basicCatalog, customCatalog], (action) => { handleAction(action);});In Flutter, implement each custom component as an a2ui_flutter ComponentImplementation (a name, a schema, and a builder), and build a CatalogImplementation that holds the basic components plus yours under the server’s catalogId:
import 'package:a2ui_core/a2ui_core.dart' show A2uiProtocolVersion, BasicCatalog, CommonSchemasV1, MessageProcessor;import 'package:a2ui_flutter/a2ui_flutter.dart';import 'package:a2ui_flutter/basic_catalog.dart';import 'package:json_schema_builder/json_schema_builder.dart';import 'package:url_launcher/url_launcher.dart';
final metricCard = ComponentImplementation( name: 'MetricCard', // Must match the server component name schema: Schema.object( properties: { // A literal or a `{"@path": "/..."}` data binding. 'title': CommonSchemasV1.dynamicString, 'value': CommonSchemasV1.dynamicString, 'trend': Schema.string(enumValues: ['up', 'down', 'neutral']), }, required: ['title', 'value'], ), // `props` holds resolved values; the builder reruns when bound data changes. builder: (context, node, props, buildChild) => MetricCardWidget( title: props.string('title') ?? '', value: props.string('value') ?? '', trend: props.string('trend'), ),);
final dashboardCatalog = CatalogImplementation( id: 'https://example.com/catalogs/dashboard.json', // Must match the server catalogId protocolVersion: A2uiProtocolVersion.v1_0, components: [...BasicComponents.all, metricCard], functions: BasicCatalog.v1_0( openUrl: (uri) => launchUrl(uri), ).functions.values.toList(), definitions: BasicComponents.api.definitions,);
final processor = MessageProcessor<ComponentImplementation>( catalogs: [dashboardCatalog], // ...);The renderer rejects a createSurface whose catalogId it doesn’t hold (an A2uiCatalogError from processMessages), so that surface never appears. json_schema_builder provides Schema; add it with flutter pub add json_schema_builder.
The trust boundary and security
Section titled “The trust boundary and security”Because generative UI renders model-generated structures in the client DOM or Flutter widget tree, treat every emitted surface as untrusted output:
- Validation checks structure, not values: The
validateoption (strictorwarn) checks that surfaces are well-formed against the active catalog (component names, structure, and references). It does not sanitize property values (such asImage.urlor Markdown text withinText). - Sanitize in the client renderer: The client renderer is responsible for sanitizing property values before mounting them into the DOM or widget tree. Markdown parsers must escape raw HTML tags unless intentionally permitted and sanitized.
- Enforce Content Security Policy (CSP): For web applications, configure a strong CSP restricting
img-srcand fetch destinations to trusted domains to prevent remote code execution or data exfiltration. - Protect secrets: Do not place confidential tokens or sensitive IDs in the surface data model, as any bound data may be returned to the server in user action payloads.
If you need server-side control over props (for example, allow-listing image hosts), add your own model middleware before a2ui() in use. Middleware listed first wraps the ones after it, so it sees the parts a2ui() emits and can rewrite them. If you change a part’s data.messages, also update or remove its metadata.a2uiExpress, since that source is what the model is shown on later turns.
Under the hood
Section titled “Under the hood”A2UI operates as a specialized data channel within the Genkit runtime:
- Prompt capability injection: The middleware augments the system prompt with the active catalog’s components and prop descriptions.
- Stream interception: As the model generates text, the middleware intercepts and parses
a2uifenced code blocks. - Envelope translation: Emitted envelopes are validated against the catalog and packaged into Genkit
dataparts with MIME typeapplication/a2ui+json. - Action translation: Inbound user actions sent via
actionToMessage()are converted into concise summaries for the model while preserving full structured payloads in conversation history.
- Prompt capability injection: Unless
instructionsis'none', the middleware adds the catalog’s component signatures and the A2UI Express contract to the system prompt. - Stream interception: The middleware intercepts both the streamed chunks and the final aggregated message, and extracts the
<a2ui>Express blocks from the model’s text. - Compilation: Each block is compiled into A2UI messages (v1.0 by default) with
a2ui_agentand checked against the catalog and the conversation’s live surfaces. A block that fails to compile goes through self-repair. - Part rewriting: Each block becomes a canonical A2UI data part with MIME type
application/a2ui+json, with the Express source inmetadata.a2uiExpress. - History replay: Inbound A2UI parts are turned back into text before the model sees them. A surface the model rendered is replayed as its original Express block, and a user action becomes a line such as
[UI action "refresh" from refreshBtn on surface tokyo-weather]. A model that doesn’t understand the A2UI MIME type can still reason about prior surfaces and actions.
Upgrade from earlier versions
Section titled “Upgrade from earlier versions”genkit_a2ui is in preview, and 0.5 and 0.6 are both breaking releases. See the package changelog and README for the full migration notes.
From 0.5 (A2UI v0.9) to 0.6 (A2UI v1.0):
basicCatalogandA2uiCatalog(...)now target A2UI v1.0. Messages carry"version": "1.0", new surfaces inline their components and data model oncreateSurface, data bindings use{"@path": ...}, andText.variantdropsh1..h5in favor of Markdown heading lines.- To stay on v0.9 (for example, while clients still render v0.9 only), use
a2ui(catalog: 'basic-v0.9'), extendbasicCatalogV09, or passprotocolVersion: 'v0.9'toA2uiCatalog(...). a2ui(version:)no longer picks the version; it asserts the catalog’s version.a2uiVersionis removed in favor ofcatalog.protocolVersion.genuiis discontinued. Replace it witha2ui_flutteranda2ui_core0.7, and copy the client helpers again (a2uiSubmitToMessagebecamea2uiActionToMessage).a2ui_flutterships both a v1.0 basic catalog (package:a2ui_flutter/basic_catalog.dart) and a v0.9 one (package:a2ui_flutter/v0_9/basic_catalog.dart). Their IDs differ, so a client that registers both renders surfaces from either server version. Both libraries export a top-levelbasicCatalog(...), so prefix one import (import 'package:a2ui_flutter/v0_9/basic_catalog.dart' as v09;).
From 0.4 to 0.5:
- The model writes A2UI Express in
<a2ui>blocks instead of fenceda2uiJSON. Withinstructions: 'none', rewrite your prompt starting fromrenderCatalogInstructions(catalog). - The A2UI part’s payload key changed from
data.envelopestodata.messages. The agent still readsenvelopeswhen replaying history. Upgrade the agent and its clients together. package:genkit_a2ui/client.dartis removed. Clients no longer depend ongenkit_a2ui.- Surface IDs belong to the model, and the
surfaceIdoption is removed. - Catalogs use the spec’s
catalog.jsonshape (componentskeyed by name, each a JSON Schema). Extend the basic catalog withbasicCatalog.extend(...)instead of spreading its components, and useA2uiCatalogComponent.simpleinstead ofpropsstrings.
Next steps
Section titled “Next steps”- Serve agents over HTTP covers Express setup and client connectivity in detail.
- Sessions and state explains session stores, history, and client state.
- Define agents covers agent definitions, tools, and configurations.
- Explore the
a2uitestapp for a complete runnable sample with Express and Lit.
- Serve agents over HTTP covers endpoint routing and the browser client.
- Middleware covers composition order and built-in middleware to pair with
Surfaces. - Run and stream agents covers reading a turn’s chunks, where A2UI data parts arrive alongside text.
- Explore the
basic-middleware/a2uisample for a complete Go backend.
- Serve agents over HTTP covers server endpoints and client connectivity.
- Sessions and state covers Dart session stores and history.
- Define agents covers agent definitions and tools in Dart.
- Explore the
a2uitestapp for a complete runnable sample: adart:ioserver hosting the agent with a custom catalog, plus a Flutter client that renders surfaces witha2ui_flutter.
- Serve agents over HTTP covers FastAPI route mounting with
serve_agent()and client connectivity. - Middleware covers composition order and built-in middleware such as
RetryandFallback. - Run and stream agents covers reading streamed chunks and responses.
- Define agents covers agent definitions, tools, and session stores in Python.
- A2UI specification provides the full protocol and catalog specification.