Repository navigation
feat(python/agent): add TransformerPipeline, macro-safe streaming (#2865) - #4533
jacobsimionato wants to merge 1 commit into
Conversation
There was a problem hiding this comment.
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.
| 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] |
There was a problem hiding this comment.
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
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
| 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
- 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.
… TransformerPipeline Signed-off-by: Greg Spencer <gspencer@google.com>
318ac3f to
2226477
Compare
2226477 to
6c93760
Compare
📖 Docs Site Preview DeployedPreview URL: https://a2ui.org/pr-preview/pr-4533/ Modified pages in this PR: Built from commit |
…-safe streaming (#2865) Signed-off-by: Jacob Simionato <jsimionato@google.com>
6c93760 to
53e4459
Compare
Problem
Macros are Python functions that expand into A2UI components on the server. To use them, an agent had to wire
MacroExpanderaroundA2uiRequestProcessorby hand. It calledexpander.transform_catalogs(...)to build the catalogs the model sees, passed those to the processor, and then awaitedexpander.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
MessageTransformer(asynctransform_to_transportandtransform_to_inference),CatalogMessageTransformer(both aMessageTransformerand aCatalogTransformer, the existing catalog-only base class), andTransformerPipeline, all ina2ui.catalog_transformers. The pipeline runs catalog stages in order (transport to inference) and message stages in reverse (model output back to client messages).MacroExpanderstays ina2ui.transformers.macrosand now subclassesCatalogMessageTransformer.A2uiGeneratorandA2uiRequestProcessoraccepttransformers=. Instead,A2uiGeneratorcan taketransformer_factory=, a callable that receives the catalogs chosen for a session and returns that session's transformers. The processor exposesinference_catalogsandpipeline, and builds its prompt and parser from the inference catalogs.aparse_response()andaopen_stream()(returning the newAsyncResponseStream). 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.parse_response()andopen_stream()still work for catalog-only pipelines and raiseRuntimeErrorwhen a stage transforms messages.ComponentPruningTransformerandFunctionPruningTransformertakecatalog_id=, because a pipeline stage sees every catalog, not just one.parse_response()andaparse_response()takeassume_unknown_surfaces=, so a processor without saved state accepts updates to surfaces created in earlier turns.Breaking changes: None for supported use. Processors without
transformersbehave as before.CatalogConfignow raisesTypeErrorup front for entries that are notCatalogTransformersubclasses (already its annotated type) or that transform messages. Before this PRMacroExpanderhad notransform(), so aCatalogConfigholding one already failed when it built its catalog. Pass it totransformers=instead.New public API
Where to review
test_transformer_pipeline.py)Start here:
python/a2ui_agent/src/a2ui/catalog_transformers/base.pyandpipeline.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?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?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 throughgetattr, since those streams have no public hooks for this. A rename there would fail quietly.python/a2ui_agent/src/a2ui/inference_formats/express/response_stream.pyandcompiler.py: can a partial macro call, or one that refers to a component not streamed yet, ever be emitted?Implementation details
TransformerPipelineflattens nested pipelines and rejects stages that are neitherCatalogTransformernorMessageTransformerwithTypeError.transform()raisesA2uiCatalogErrorunless the pipeline maps one catalog to exactly one. Message stages whosehas_message_transformsis False are skipped.MacroExpander.has_message_transformsis True only when macros are registered, andstreaming_held_componentsis the set of macro names. The newMacroExpander.transform()works for v0.9 and raises for v1.0, where macros live in their own catalog; usetransform_catalogs()there.CatalogTransformer.transform_catalogs()is a new default method that appliestransform()to each catalog._create_stateless_state()inutils/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.TransformingResponseStream(sync, catalog-only pipelines),AsyncTransformingResponseStream, andSyncToAsyncResponseStream(used when no pipeline is set) inprocessor/_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.non_progressive_componentsandinitial_surfaces. The compiler takeshold_unresolved_componentsandspeculative_varsto defer macro nodes whose variable references are not resolved yet. Direct JSON takesforce_buffer_components, which buffers every component until it is complete whenever the pipeline transforms messages.getattrare_sync_inference_state,_reject_open_block,_block_close_indices, and_superseded_by_part.docs/site/src/content/docs/guides/macros.mdx) and the macros README now showtransformers=[expander]withaparse_response. The README also notes that a scopedMacroExpander(catalog_id=...)that relies oncreateSurface.catalogIdcan miss macros in later streamed batches.Verification
Measured at the stack tip (all 11 commits applied), not on this commit alone:
This PR adds
python/a2ui_agent/tests/test_transformer_pipeline.py(17 tests). It covers pipeline ordering,catalog_idpruning, 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).