Skip to content

Type to search the docs, or jump to:

Using Macros

Macros let you define composite UI components on the server that can programmatically inject server-side data and expand into the flexible, reusable catalog components your client supports (from the Basic Catalog, your own custom catalogs, or both) before any messages reach the renderer. Because the renderer only receives components the client already implements, you can add or change macros on the server without shipping new client code.

How macros work

When a language model builds UI from low-level primitives on every turn, repeated patterns like flight summaries or product cards take many lines of nested components. With a macro, you write a function once on the server to assemble that pattern.

Macros are useful when you want to:

  1. Reduce output tokens and latency by letting the model write one call instead of a nested component tree.
  2. Keep layouts consistent across turns because your server code constructs the component hierarchy.
  3. Look up data from server-side databases and APIs, accepting an identifier from the model and populating the components on the server.
  4. Ship new domain components with a server deployment alone, using catalog components the client already renders.

In the sequence below, MacroExpander works on both sides of the model call. Before inference, it adds each macro’s component schema to the catalog in the system prompt. After inference, it intercepts each macro call, runs your macro function, and outputs flat catalog components for the renderer.

sequenceDiagram
participant Model
participant Agent as Agent server
participant Expander as MacroExpander
participant Renderer
Agent->>Expander: Add macro schemas to catalog
Expander-->>Agent: Inference catalog
Agent->>Model: System prompt with FlightCard(...) signature
Model-->>Agent: root = FlightCard("OS 87", ...)
Agent->>Expander: Expand macro calls in messages
Expander-->>Agent: Expanded catalog components
Agent->>Renderer: createSurface with catalog components

Example: macro, model call, and expanded output

Here is a FlightCard macro. The flight and route parameters take static strings, while status uses DynamicString so it can bind to the data model:

flight_macros.py
from a2ui.builder.v1_0 import Card, Column, DynamicString, Text
from a2ui.transformers.macros import macro
@macro
def FlightCard(flight: str, route: str, status: DynamicString) -> Card:
"""Summary card for a flight with a live status line.
Args:
flight: Flight number, such as "OS 87".
route: Departure and arrival cities, such as "Vienna to New York".
status: Current status text or data binding.
"""
return Card(
child=Column(
children=[
Text(text=f"### {flight}"),
Text(text=route, variant="caption"),
Text(text=status),
]
)
)

Using the Express inference format, the model calls FlightCard in a single line:

Model output
Your flight is boarding.
<a2ui>
$/flight/status = "Boarding"
root = FlightCard("OS 87", "Vienna to New York", $/flight/status)
</a2ui>

MacroExpander runs FlightCard on the server and sends the expanded components over the wire, with static arguments baked in and the /flight/status data binding preserved. In v1.0, each expanded component names its catalog with @catalogId, so the surface needs no default catalog:

[
{
"version": "1.0",
"createSurface": {
"surfaceId": "main",
"components": [
{
"component": "Text",
"id": "root__text_1",
"@catalogId": "https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json",
"text": "### OS 87"
},
{
"component": "Text",
"id": "root__text_2",
"@catalogId": "https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json",
"text": "Vienna to New York",
"variant": "caption"
},
{
"component": "Text",
"id": "root__text_3",
"@catalogId": "https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json",
"text": {"@path": "/flight/status"}
},
{
"component": "Column",
"id": "root__column_1",
"@catalogId": "https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json",
"children": ["root__text_1", "root__text_2", "root__text_3"]
},
{
"component": "Card",
"id": "root",
"@catalogId": "https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json",
"child": "root__column_1"
}
],
"dataModel": {
"flight": {"status": "Boarding"}
}
}
}
]

Configure a macro

The steps below integrate a macro into a Python agent using BasicCatalog("1.0"). You do not need to use the Basic Catalog: the same workflow applies to your own custom catalogs, as shown in Macros with custom catalogs.

Step 1: Install the Python agent SDK

Install a2ui-agent-sdk with pip (or uv add a2ui-agent-sdk):

Terminal window
pip install a2ui-agent-sdk

Step 2: Define a macro

Decorate a Python function with @macro and return a single root builder component. @macro inspects the parameter type hints and the Args: block in the docstring to generate the component schema that the model sees:

flight_macros.py
from a2ui.builder.v1_0 import (
Action,
Button,
Card,
Column,
DynamicString,
Text,
)
from a2ui.transformers.macros import macro
@macro
def FlightCard(
flight: str,
route: str,
status: DynamicString,
on_rebook: Action,
) -> Card:
"""Summary card for a flight with a live status line and rebook button.
Args:
flight: Flight number, such as "OS 87".
route: Departure and arrival cities, such as "Vienna to New York".
status: Current status text or data binding.
on_rebook: Action sent when the user clicks Rebook.
"""
return Card(
child=Column(
children=[
Text(text=f"### {flight}"),
Text(text=route, variant="caption"),
Text(text=status),
Button(child=Text(text="Rebook"), action=on_rebook),
]
)
)

Because a macro is regular Python running on your server, it can also take an identifier (such as flight_id: str), look up the record in a database or service, and populate the returned components directly.

Step 3: Set up the expander and request processor

Create a MacroExpander with your macro list and pass it to A2uiRequestProcessor as a transformer. The processor adds the macro schemas to the catalogs the model sees and expands macro calls before it validates the messages for the client:

agent.py
from a2ui.core.basic_catalog import BasicCatalog
from a2ui.processor import A2uiRequestProcessor
from a2ui.transformers.macros import MacroExpander
from flight_macros import FlightCard
expander = MacroExpander([FlightCard])
processor = A2uiRequestProcessor(
catalogs=[BasicCatalog("1.0")],
transformers=[expander],
)
system_prompt = processor.prompt_snippet # Append to your model's system instruction.

MacroExpander is a transformer rather than a CatalogConfig.transformers entry because it acts both before inference (exposing macros in a dedicated inference-only catalog) and after parsing (expanding macro calls in outgoing messages); CatalogConfig rejects it. MacroExpander is pure and stateless, so a single instance can be safely shared across concurrent sessions. To negotiate catalogs per renderer, pass the same transformers=[expander] to A2uiGenerator. A2uiRequestProcessor uses the Express inference format by default, and works with any format factory you pass via format_factory.

Step 4: Parse model output and expand macros

After your model responds, parse the response with await processor.aparse_response(...). Macros may be async def, so a processor with macros parses asynchronously; it expands every macro and validates the expanded messages before returning them:

agent.py (continued)
from a2ui.parser import A2uiPart, TextPart, to_message_dicts
# llm_output = call_your_model(system_prompt, user_message)
parts = await processor.aparse_response(llm_output)
text_reply = [part.text for part in parts if isinstance(part, TextPart)]
wire_payload = [
message
for part in parts
if isinstance(part, A2uiPart)
for message in to_message_dicts(part.a2ui)
]

Send wire_payload over your transport to the renderer alongside any conversational text in text_reply. To stream, use processor.aopen_stream(), which holds back each macro call until it is complete and then expands it. In ADK agents, SendA2uiToClientToolset runs the processor for you.

Macros with custom catalogs

Macros build component trees using typed Python builder classes. Builder classes for the Basic Catalog ship in a2ui.builder.v1_0 and a2ui.builder.v0_9. When you define a custom catalog, the A2UI CLI (a2ui) generates those Python builder classes directly from your catalog JSON file.

Step 1: Install the A2UI CLI

Install the standalone a2ui binary using the release installer script. Both scripts verify the SHA-256 checksum of the downloaded archive and do not require administrator privileges:

Terminal window
curl -fsSL https://raw.githubusercontent.com/a2ui-project/a2ui/main/scripts/public/install_cli.sh | sh

Installs a2ui into ${XDG_BIN_HOME:-$HOME/.local/bin}. Make sure that directory is on your PATH, or pass A2UI_INSTALL_DIR (and optionally A2UI_VERSION) to sh, as in curl -fsSL ... | A2UI_INSTALL_DIR="$HOME/bin" sh.

Step 2: Generate builder classes for your catalog

Suppose you have a travel_catalog.json file that defines a BoardingPass component (and your client renderer registers the matching BoardingPass widget).

Example travel_catalog.json
travel_catalog.json
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"catalogId": "https://example.com/catalogs/travel/v1/catalog.json",
"protocolVersion": "1.0",
"components": {
"BoardingPass": {
"type": "object",
"description": "A boarding pass with a scannable code.",
"properties": {
"component": {"const": "BoardingPass"},
"passenger": {"type": "string"},
"seat": {"type": "string"},
"gate": {"$ref": "common_types.json#/$defs/DynamicString"}
},
"required": ["component", "passenger", "seat", "gate"]
}
},
"$defs": {
"anyComponent": {
"oneOf": [{"$ref": "#/components/BoardingPass"}],
"discriminator": {"propertyName": "component"}
},
"anyFunction": {"not": {}}
}
}

Run a2ui codegen with --lang python to generate a Python builder module from your catalog schema:

Terminal window
a2ui codegen --lang python --catalog travel_catalog.json --out travel_builders.py --catalog-name travel

The generated travel_builders.py file contains a typed ComponentBuilderNode subclass for every component in your catalog:

travel_builders.py (excerpt)
class BoardingPass(ComponentBuilderNode, catalog_id=CATALOG_ID):
r"""A boarding pass with a scannable code."""
component: Literal["BoardingPass"] = "BoardingPass"
passenger: str
seat: str
gate: DynamicString

Re-run a2ui codegen whenever travel_catalog.json changes rather than editing the generated file by hand.

Step 3: Write a macro with the generated builders

Import your generated builder classes into a macro. In A2UI v1.0, a single surface can combine components from multiple catalogs, so a macro can mix your custom BoardingPass with layout components from BasicCatalog("1.0"):

trip_macros.py
from a2ui.builder.v1_0 import Card, Column, DynamicString, Text
from a2ui.transformers.macros import macro
from travel_builders import BoardingPass
@macro
def TripSummary(passenger: str, seat: str, gate: DynamicString) -> Card:
"""Trip summary card containing a boarding pass.
Args:
passenger: Passenger full name.
seat: Assigned seat number.
gate: Departure gate text or data binding.
"""
return Card(
child=Column(
children=[
Text(text=f"### Have a good trip, {passenger}"),
BoardingPass(passenger=passenger, seat=seat, gate=gate),
]
)
)

Load your custom catalog with Catalog.from_json and pass all transport catalogs to A2uiRequestProcessor together with the expander. If your agent uses only your custom catalog without the Basic Catalog, pass [travel_catalog] instead:

agent.py
import json
from pathlib import Path
from a2ui.core import Catalog
from a2ui.core.basic_catalog import BasicCatalog
from a2ui.parser import A2uiPart
from a2ui.processor import A2uiRequestProcessor
from a2ui.transformers.macros import MacroExpander
from trip_macros import TripSummary
travel_catalog = Catalog.from_json(
json.loads(Path("travel_catalog.json").read_text())
)
basic_catalog = BasicCatalog("1.0")
expander = MacroExpander([TripSummary])
processor = A2uiRequestProcessor(
catalogs=[basic_catalog, travel_catalog],
transformers=[expander],
)
system_prompt = processor.prompt_snippet
# After receiving llm_output from the model:
parts = await processor.aparse_response(llm_output)
transport_messages = [
msg for part in parts if isinstance(part, A2uiPart) for msg in part.a2ui
]

In v1.0, the processor’s inference catalogs are your catalogs plus an inference-only catalog for your macros (expander.transform_catalogs(...) computes them); the renderer only ever sees your catalogs. Because generated v1.0 builders self-stamp their own CATALOG_ID, expanding TripSummary emits Card, Column, Text, and BoardingPass components already tagged with their owning @catalogId and strips any macro-sidecar createSurface.catalogId to produce a defaultless v1.0 surface.

Reference

Supported parameter types

Parameter annotations control both the JSON Schema shown to the model and whether a value is static or reactive:

  • Plain Python types (str, int, float, bool) accept only static literal values, which are baked into the expanded components when the macro runs. Passing a data binding to a plain str parameter fails validation.
  • Reactive A2UI types (DynamicString, DynamicNumber, DynamicBoolean, DynamicStringList) accept either a literal value or a @path / @call binding. When you pass that parameter to a child component property, the binding remains live on the renderer.

Always treat macro arguments as untrusted model output, and validate identifiers against your backend data rather than trusting arbitrary strings.

The table below lists the most common parameter annotations (showing v1.0 schema definitions):

Python annotationSchema exposed to the modelValue passed to your macro
str, int, float, boolstring, integer, number, booleanStatic literal value (data bindings rejected).
Literal[...] or Enum (str, int, float, or bool values)enum (with inferred JSON Schema type)Static literal value (Enum and Literal[EnumMember, ...] parameters are coerced into Enum members; invalid values fail validation).
Sequence[V], dict[str, V]array, objectList or dict with elements converted to V.
DynamicString, DynamicNumber, DynamicBoolean, DynamicStringListDynamicString and related typesLiteral value, DataBinding, or FunctionCall.
ActionActionAction built from an event object or function call.
Child or component classChild (ComponentId in v0.9.1)ComponentRef pointing to another component ID.
ChildList or Sequence[Child]ChildListList of ComponentRef items; ChildList (not Sequence[Child]) also accepts DynamicChildList bindings.
CheckRule or Sequence[CheckRule]CheckRule (or array of CheckRule)CheckRule instance(s) for input validation.
AccessibilityAttributesAccessibilityAttributesAccessibilityAttributes model.

@macro reads parameter descriptions from Google-style (Args:) docstrings, Sphinx-style (:param name:) docstrings, or typing.Annotated[T, Field(description="...")]. For additional annotations, including DynamicValue, Extensions, catalog sub-models (TabItem, ChoicePickerOption), and union types, see the parameter type mapping table in the macros README.

Protocol versions

To target A2UI v0.9.1 instead of v1.0, import builders from a2ui.builder.v0_9 and pass a single catalog (such as BasicCatalog("0.9.1")) to A2uiRequestProcessor(catalogs=[...], transformers=[expander]). Do not mix v1_0 and v0_9 builders or catalogs on the same MacroExpander.

Additional configuration options

Custom macro names and descriptions

Override the inferred PascalCase component name or docstring description by passing arguments to @macro, such as @macro("CustomCard") or @macro(name="CustomCard", description="...").

Error handling (on_error)

With the default on_error="raise", a macro that fails argument coercion or raises a runtime exception during expansion raises A2uiValidationError on the server so an agent retry loop can send the error back to the model. Pass on_error="passthrough" to MacroExpander to log the error and leave the component unexpanded so sibling components still expand (note that client renderers do not implement unexpanded macro components). Structural errors (A2uiRecursionError, A2uiCatalogError, and protocol-version mismatches) always raise regardless of on_error.

Filtering base components (passthrough_components)

By default, all components from your base catalogs remain visible to the model alongside your macros. Pass passthrough_components=["Button"] to MacroExpander to expose only specific base components plus your macros, or passthrough_components=[] to expose only your macros.

Explicit protocol_version

MacroExpander normally infers the protocol version from your macro parameter and return annotations or the catalogs passed to transform_catalogs. If a v1.0 macro uses only version-neutral annotations (such as str, int, or Child, with no v1.0 return type) and you export a standalone macro catalog with expander.to_catalog(), pass protocol_version="1.0" to MacroExpander(...).

Overriding component catalog IDs (catalog_id)

Generated v1.0 builders bind their catalog’s CATALOG_ID automatically. Pass catalog_id=... when instantiating a builder to override it, or catalog_id=None to omit @catalogId on a component.