Skip to content

feat(python/agent): add TransformerPipeline, macro-safe streaming (#2865) - #4533

Open
jacobsimionato wants to merge 1 commit into
macros/5c-async-parallel-macrosfrom
macros/6-transformer-pipeline
Open

jacobsimionato wants to merge 1 commit into
macros/5c-async-parallel-macrosfrom
macros/6-transformer-pipeline

Conversation

@jacobsimionato

@jacobsimionato jacobsimionato commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Macros are Python functions that expand into A2UI components on the server. To use them, an agent had to wire MacroExpander around A2uiRequestProcessor by hand. It called expander.transform_catalogs(...) to build the catalogs the model sees, passed those to the processor, and then awaited expander.transform_to_transport(...) on every parsed block. The processor validated against the macro-augmented catalogs, not the catalogs the client renders, and streaming did not work because a half-written macro call cannot be expanded or validated.

This PR lets the processor own that wiring. Two terms used below: the transport side is what the client renders (its catalogs, and the messages it receives, tracked on the server in a RendererState). The inference side is what the model sees and writes: the transport catalogs after transformers such as macros or pruning (removing components the model should not use) have changed them.

Closes #2865

Stack: 8/11 (overview) · previous: #4562 · next: #4551

Reviewer guide: A2UI Python macros: reviewer guide explains how the whole stack fits together.

This PR connects macros to the request processor and builds on the async macros from #4562.

Summary

  1. Adds MessageTransformer (async transform_to_transport and transform_to_inference), CatalogMessageTransformer (both a MessageTransformer and a CatalogTransformer, the existing catalog-only base class), and TransformerPipeline, all in a2ui.catalog_transformers. The pipeline runs catalog stages in order (transport to inference) and message stages in reverse (model output back to client messages). MacroExpander stays in a2ui.transformers.macros and now subclasses CatalogMessageTransformer.
  2. A2uiGenerator and A2uiRequestProcessor accept transformers=. Instead, A2uiGenerator can take transformer_factory=, a callable that receives the catalogs chosen for a session and returns that session's transformers. The processor exposes inference_catalogs and pipeline, and builds its prompt and parser from the inference catalogs.
  3. Adds aparse_response() and aopen_stream() (returning the new AsyncResponseStream). Model output is parsed against the inference catalogs, converted back to client messages by the pipeline, then checked against and applied to the transport state in one transaction, so a failed turn leaves the state unchanged.
  4. Streams hold back macro calls until they are complete. Of the four inference formats (the syntaxes the model writes A2UI in), only Express and Direct JSON emit components before a block ends, so only they needed this. Sync parse_response() and open_stream() still work for catalog-only pipelines and raise RuntimeError when a stage transforms messages.
  5. Two options the pipeline needs in multi-catalog and stateless setups. ComponentPruningTransformer and FunctionPruningTransformer take catalog_id=, because a pipeline stage sees every catalog, not just one. parse_response() and aparse_response() take assume_unknown_surfaces=, so a processor without saved state accepts updates to surfaces created in earlier turns.

Breaking changes: None for supported use. Processors without transformers behave as before. CatalogConfig now raises TypeError up front for entries that are not CatalogTransformer subclasses (already its annotated type) or that transform messages. Before this PR MacroExpander had no transform(), so a CatalogConfig holding one already failed when it built its catalog. Pass it to transformers= instead.

New public API

from a2ui.catalog_transformers import ComponentPruningTransformer
from a2ui.core.basic_catalog import BasicCatalog
from a2ui.processor import A2uiGenerator, CatalogConfig
from a2ui.transformers.macros import MacroExpander

basic = BasicCatalog("1.0")  # v1.0: MacroExpander adds a separate macro catalog
generator = A2uiGenerator(
    catalogs=[CatalogConfig(basic)],
    transformers=[  # or: transformer_factory=lambda catalogs: [...]
        ComponentPruningTransformer(["Card", "Text"], catalog_id=basic.catalog_id),
        MacroExpander([FlightsTable]),  # FlightsTable: a user-defined @macro
    ],
)
processor = generator.create_processor(renderer_capabilities)  # sent by the client
parts = await processor.aparse_response(llm_text)

stream = processor.aopen_stream()
for chunk in chunks:
    send(await stream.afeed(chunk))  # only the parts this chunk made ready
send(await stream.aclose())

Where to review

Category Files Diff (+/-)
Production 16 +1570 / -53
Tests (test_transformer_pipeline.py) 1 +1183 / -0
Docs and changelog 4 +71 / -34
Total 21 +2824 / -87

Start here:

  1. python/a2ui_agent/src/a2ui/catalog_transformers/base.py and pipeline.py: do catalog stages run transport to inference and message stages run the other way, and does the pipeline combine every stage's held-back component names?
  2. python/a2ui_agent/src/a2ui/processor/processor.py: is output validated against the client's catalogs, and does a failed turn leave the transport state unchanged?
  3. python/a2ui_agent/src/a2ui/processor/_streaming.py: is each block committed or rolled back before the next is parsed, and are unchanged components not sent twice? Known risk: these wrappers call private members of the inner Express and Direct JSON streams through getattr, since those streams have no public hooks for this. A rename there would fail quietly.
  4. python/a2ui_agent/src/a2ui/inference_formats/express/response_stream.py and compiler.py: can a partial macro call, or one that refers to a component not streamed yet, ever be emitted?
Implementation details
  1. TransformerPipeline flattens nested pipelines and rejects stages that are neither CatalogTransformer nor MessageTransformer with TypeError. transform() raises A2uiCatalogError unless the pipeline maps one catalog to exactly one. Message stages whose has_message_transforms is False are skipped.
  2. MacroExpander.has_message_transforms is True only when macros are registered, and streaming_held_components is the set of macro names. The new MacroExpander.transform() works for v0.9 and raises for v1.0, where macros live in their own catalog; use transform_catalogs() there.
  3. CatalogTransformer.transform_catalogs() is a new default method that applies transform() to each catalog.
  4. The inference-side state comes from a private _create_stateless_state() in utils/renderer_state.py. It assumes unknown surfaces exist, inherits known surface catalog bindings from the transport state, and skips topology checks, because a transformer may still reshape the tree. Only the transport state checks topology, after conversion.
  5. Streaming lives in TransformingResponseStream (sync, catalog-only pipelines), AsyncTransformingResponseStream, and SyncToAsyncResponseStream (used when no pipeline is set) in processor/_streaming.py. Chunks are split after each closing block tag, so each block is committed or rolled back before the next is parsed. A per-block cache drops components whose canonical JSON did not change since the last healed batch.
  6. Express takes non_progressive_components and initial_surfaces. The compiler takes hold_unresolved_components and speculative_vars to defer macro nodes whose variable references are not resolved yet. Direct JSON takes force_buffer_components, which buffers every component until it is complete whenever the pipeline transforms messages.
  7. The private members read through getattr are _sync_inference_state, _reject_open_block, _block_close_indices, and _superseded_by_part.
  8. The macros guide (docs/site/src/content/docs/guides/macros.mdx) and the macros README now show transformers=[expander] with aparse_response. The README also notes that a scoped MacroExpander(catalog_id=...) that relies on createSurface.catalogId can miss macros in later streamed batches.
Verification

Measured at the stack tip (all 11 commits applied), not on this commit alone:

  1. Full Python suite passes (6027 passed).
  2. mypy is clean (283 source files).
  3. 56 conformance goldens are valid.
  4. Prettier and pyink are clean on every commit, and every commit has a DCO sign-off.

This PR adds python/a2ui_agent/tests/test_transformer_pipeline.py (17 tests). It covers pipeline ordering, catalog_id pruning, the generator factory, shared expanders across concurrent sessions, multi-turn rollback, async macros in all four formats, and streaming edge cases (forward references, rejected blocks, several blocks in one chunk, and supersede, delete, and recreate).

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a robust transformer pipeline architecture to support bidirectional catalog and message transformations between inference and transport layers. Key additions include TransformerPipeline, MessageTransformer, CatalogMessageTransformer, BoundCatalogMessageTransformer, and AsyncResponseStream, which are integrated into A2uiGenerator and A2uiRequestProcessor to support features like async macro expansion and session-bound transformer execution. Additionally, MacroExpander has been refactored to plug cleanly into this pipeline, and transactional tracking of inference surface catalogs has been added to RendererState. Feedback on the changes suggests a performance optimization in _StreamLoweringState.filter_uncached_messages to avoid calling to_message_dicts inside a loop, preventing O(N^2) complexity during message filtering.

Comment on lines +185 to +192
def filter_uncached_messages(
self, messages: Sequence[AgentToRendererMessage]
) -> tuple[list[AgentToRendererMessage], list[tuple[tuple[str | None, str], str]]]:
"""Filters out unchanged components from cumulative stream re-emissions."""
filtered: list[AgentToRendererMessage] = []
pending_cache: list[tuple[tuple[str | None, str], str]] = []
for msg in messages:
msg_dict = to_message_dicts(msg)[0]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Performance Optimization: Avoid Repeated Message Serialization in Loops

In _StreamLoweringState.filter_uncached_messages, calling recursive payload traversal functions like to_message_dicts(msg) inside a loop over messages results in redundant traversals and $O(N^2)$ complexity as the list of messages grows with each chunk.

To prevent this, avoid calling the traversal function inside the loop over messages. Instead, run the traversal once per payload (e.g., on the entire collection of messages at once) to optimize performance and reduce complexity to $O(N)$.

Suggested change
def filter_uncached_messages(
self, messages: Sequence[AgentToRendererMessage]
) -> tuple[list[AgentToRendererMessage], list[tuple[tuple[str | None, str], str]]]:
"""Filters out unchanged components from cumulative stream re-emissions."""
filtered: list[AgentToRendererMessage] = []
pending_cache: list[tuple[tuple[str | None, str], str]] = []
for msg in messages:
msg_dict = to_message_dicts(msg)[0]
def filter_uncached_messages(
self, messages: Sequence[AgentToRendererMessage]
) -> tuple[list[AgentToRendererMessage], list[tuple[tuple[str | None, str], str]]]:
"""Filters out unchanged components from cumulative stream re-emissions."""
filtered: list[AgentToRendererMessage] = []
pending_cache: list[tuple[tuple[str | None, str], str]] = []
msg_dicts = to_message_dicts(messages)
for msg, msg_dict in zip(messages, msg_dicts):
References
  1. Avoid calling recursive payload traversal functions inside loops over messages to prevent redundant traversals and O(N^2) complexity. Run the traversal once per payload instead.

@jacobsimionato jacobsimionato changed the title feat(python/agent): add TransformerPipeline, processor integration, and macro-safe streaming (#2865) feat(python/agent): add TransformerPipeline and macro-safe streaming Dec 2, 2026
gspencergoog added a commit to gspencergoog/A2UI that referenced this pull request Dec 2, 2026
… TransformerPipeline

Signed-off-by: Greg Spencer <gspencer@google.com>
@jacobsimionato
jacobsimionato force-pushed the macros/6-transformer-pipeline branch from 318ac3f to 2226477 Compare December 2, 2026 23:17
@jacobsimionato
jacobsimionato removed this pull request from stack #4536 December 2, 2026 23:18
@jacobsimionato
jacobsimionato changed the base branch from macros/5-omit-builder-defaults to macros/5b-stateless-v10-macros December 2, 2026 23:18
@jacobsimionato jacobsimionato changed the title feat(python/agent): add TransformerPipeline and macro-safe streaming feat(python/agent): stateless TransformerPipeline & streaming (#2865) Dec 2, 2026
@jacobsimionato
jacobsimionato removed this pull request from stack #4552 December 3, 2026 12:03
@jacobsimionato
jacobsimionato force-pushed the macros/6-transformer-pipeline branch from 2226477 to 6c93760 Compare December 3, 2026 12:04
Base automatically changed from macros/5b-stateless-v10-macros to macros/2-checks-a11y-params December 3, 2026 12:04
@jacobsimionato
jacobsimionato changed the base branch from macros/2-checks-a11y-params to macros/5c-async-parallel-macros December 3, 2026 12:04
@jacobsimionato
jacobsimionato marked this pull request as ready for review December 3, 2026 12:04
@jacobsimionato
jacobsimionato removed this pull request from stack #4563 December 3, 2026 12:06
github-actions Bot added a commit that referenced this pull request Dec 3, 2026
@github-actions

github-actions Bot commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

📖 Docs Site Preview Deployed

Preview URL: https://a2ui.org/pr-preview/pr-4533/

Modified pages in this PR:

Built from commit 53e4459 · Workflow run · GitHub Pages may take ~30–60s to propagate updates. This preview is removed automatically when the PR closes.

@jacobsimionato jacobsimionato changed the title feat(python/agent): stateless TransformerPipeline & streaming (#2865) feat(python/agent): add TransformerPipeline, macro-safe streaming (#2865) Dec 3, 2026
…-safe streaming (#2865)

Signed-off-by: Jacob Simionato <jsimionato@google.com>
@jacobsimionato
jacobsimionato force-pushed the macros/6-transformer-pipeline branch from 6c93760 to 53e4459 Compare December 3, 2026 12:24
github-actions Bot added a commit that referenced this pull request Dec 3, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RFC] Unifying Catalog Transformations and Message Translation via CatalogMessageTransformer & TransformerPipeline

1 participant