Skip to content

feat(python/agent): hide base functions, compact prompts, filter examples - #4534

Open
jacobsimionato wants to merge 1 commit into
macros/6b-default-catalog-simplifierfrom
macros/7-hiding-prompts-examples
Open

jacobsimionato wants to merge 1 commit into
macros/6b-default-catalog-simplifierfrom
macros/7-hiding-prompts-examples

Conversation

@jacobsimionato

@jacobsimionato jacobsimionato commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Developers can hide base catalog components behind their own macros (Python functions that expand into A2UI components on the server) with MacroExpander(passthrough_components=[]). The base catalog's helper functions (formatString, required, and so on) still reached the model, so a macro-only agent kept an empty base catalog in its prompt. The prompt generators also always emitted every A2UI Express grammar rule (Express is the compact text syntax the model writes) and empty component or function headings, even when no active catalog could use them. Finally, few-shot examples that span several catalogs made A2uiGenerator.create_processor() fail for any client that supports only some of those catalogs.

Fixes #4414
Fixes #2895

Stack: 10/11 (overview) · previous: #4551 · next: #4535

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

Summary

  1. MacroExpander gains passthrough_functions, which prunes base catalog functions the same way passthrough_components prunes components. In v1.0, a base catalog left with no components and no functions is dropped from the inference catalogs (the catalogs the model sees). The catalog IDs the client advertised (the transport catalogs) are still echoed on the wire unchanged. In v0.9, the macros are merged into the single base catalog, so it is pruned but never dropped.
  2. The Express prompt now includes only the grammar rules that the active catalog schemas can use (data bindings, checks, actions, nested function calls, child templates). test_express_prompt_rules_adapt_to_active_catalog_features checks that a macro-only Express prompt is under a third the size of the full Basic Catalog prompt.
  3. All inference formats (Express, Direct JSON, Elemental, Atom) and SkillGenerator (the agent skill file generator) skip empty component or function sections, drop component-focused catalog instructions when a catalog has no components, and skip catalogs that have nothing left to describe. SkillGenerator labels functions-only catalogs "Helper function signatures".
  4. A2uiGenerator gains an opt-in filter_examples_to_active_catalogs flag. When it is on, examples are checked once in __init__ against all registered catalogs. Each session (one create_processor() call per client) then keeps only the example turns that are valid for that client's inference catalogs, instead of raising.

Breaking changes: One minor break: passing a bare str or bytes to passthrough_components now raises TypeError (a string was previously split into single characters). Lists, tuples, and other iterables still work. Both new parameters are optional, and the defaults keep the old behavior, including strict example validation.

New public API

from a2ui.core.basic_catalog import BasicCatalog
from a2ui.core.schema import ProtocolVersion
from a2ui.processor import A2uiGenerator, CatalogConfig
from a2ui.transformers.macros import MacroExpander

# music_catalog is your own catalog and AlbumCard is a @macro. album_example
# uses AlbumCard; music_example uses music_catalog components.
basic = BasicCatalog(ProtocolVersion.V1_0)
generator = A2uiGenerator(
    catalogs=[CatalogConfig(basic), CatalogConfig(music_catalog)],
    examples=[album_example, music_example],
    transformers=[
        MacroExpander([AlbumCard], passthrough_components=[], passthrough_functions=[]),
    ],
    filter_examples_to_active_catalogs=True,
)
# The emptied base catalog is dropped from the inference catalogs. A client
# missing a catalog that an example needs gets that example dropped, not an error.

Where to review

Category Files Diff (+/-)
Production 9 +557 / -125
Tests 1 +1014 / -0
Docs and changelog 2 +20 / -5
Total 12 +1591 / -130

Start here:

  1. python/a2ui_agent/src/a2ui/transformers/macros/expander.py: passthrough_functions and the v1.0 empty-catalog drop. The v0.9 path now reuses the existing pruning transformers.
  2. python/a2ui_agent/src/a2ui/inference_formats/express/prompt_generator.py: _detect_catalog_features() and the rule selection in _filter_express_rules(), which maps hard-coded rule indexes to features. This is fragile if the rule list changes.
  3. python/a2ui_agent/src/a2ui/processor/generator.py and processor.py: eager validation grouped by protocol version, and per-session filtering.
Implementation details
  1. MacroExpander now stores passthrough_components and passthrough_functions as frozenset (previously set for components) and rejects str or bytes for either.
  2. The v0.9 transform_to_inference_catalog() replaces its hand-written component deletion with the two pruning transformers, which also drop $defs used only by pruned entries.
  3. _detect_catalog_features() scans component property schemas and function args schemas. It recognizes common-type $refs (dynamic values, child lists, actions, check rules) and recurses through combinators, properties, items, and additionalProperties. The nested function rule is also kept when templates are present and system functions exist. Remaining rules are renumbered without gaps.
  4. A2uiGenerator._validate_all_examples() groups registered catalogs by protocol version, applies the static transformers (all v1.0 catalogs together, v0.9 catalogs one at a time), and validates each turn against the group matching its version. _example_turn_release_line() reads the message version, or detects v0.8 envelope keys.
  5. With transformer_factory, __init__ only checks that each turn targets a registered protocol version; catalog validation waits until the session.
  6. Per-session filtering lives in A2uiRequestProcessor behind a private keyword argument, _filter_invalid_examples, which A2uiGenerator.create_processor() sets. Dropped turns are logged at debug level; if every turn is dropped, the session has no examples.
  7. SkillGenerator.generate_skillset() skips catalogs whose instructions are empty and describes functions-only catalogs as "Helper function signatures".
  8. python/a2ui_agent/src/a2ui/transformers/macros/README.md and python/a2ui_agent/CHANGELOG.md document the new options.
Verification
  1. New test file: python/a2ui_agent/tests/test_hiding_prompts_and_examples.py (macro hiding in v1.0 and v0.9, Express feature detection, compaction across all generators and SkillGenerator, eager validation and per-session filtering across protocol versions).
  2. At the stack tip (all 11 commits applied): the full Python suite passes (6027 passed), mypy is clean (283 source files), and the 56 conformance goldens are valid.
  3. Prettier and pyink are clean on every commit, and every commit has a DCO sign-off.

@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 several enhancements to the prompt generation and catalog handling pipeline. Key changes include adding passthrough_functions to MacroExpander to prune unused functions, compacting Express grammar rules and prompt/skill generators to omit unused features and empty sections, and introducing an opt-in filter_examples_to_active_catalogs option on A2uiGenerator for eager validation and per-session multi-catalog example filtering. Feedback on these changes suggests caching the filtered examples on A2uiGenerator to prevent CPU-intensive validation overhead during create_processor calls, and optimizing _detect_catalog_features by exiting early once all features are detected.

Comment on lines +292 to +293
filtered = _filter_valid_examples(self.examples, inference_catalogs)
processor_examples = filtered or None

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.

high

When filter_examples_to_active_catalogs is enabled, _filter_valid_examples runs validate_payload on every example turn for every create_processor call. Since validate_payload is CPU-intensive and the set of active/inference catalogs is typically static or has very few variations per renderer, this can become a severe performance bottleneck under high request concurrency.

Consider caching the filtered examples on the A2uiGenerator instance using a cache key derived from the inference catalog IDs (e.g., tuple(c.catalog_id for c in inference_catalogs)).

            cache_key = tuple(c.catalog_id for c in inference_catalogs)
            if not hasattr(self, "_filtered_examples_cache"):
                self._filtered_examples_cache = {}
            if cache_key not in self._filtered_examples_cache:
                self._filtered_examples_cache[cache_key] = _filter_valid_examples(self.examples, inference_catalogs)
            filtered = self._filtered_examples_cache[cache_key]
            processor_examples = filtered or None
References
  1. Enforce strict ordering (e.g., compare as lists or tuples rather than sets) when comparing catalogs or catalog states, because catalog order represents a priority order.

Comment on lines +657 to +681
def _detect_catalog_features(
helpers: Mapping[str, CatalogSchemaHelper],
) -> _ExpressCatalogFeatures:
"""Derives which optional Express grammar rules the active catalogs can actually use."""
found = {
"data_bindings": False,
"checks": False,
"actions": False,
"functions": False,
"templates": False,
}
for helper in helpers.values():
if helper.functions:
found["functions"] = True
for comp_name in helper.component_properties:
if helper.is_checkable(comp_name):
found["checks"] = True
for prop_name in helper.get_component_properties(comp_name):
p_schema = helper.get_property_schema(comp_name, prop_name)
_scan_property_schema_features(
p_schema,
path_key=helper.path_key,
visited=set(),
found=found,
)

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

Recursively scanning every property schema of every component in every active catalog can be highly CPU-intensive, especially for large catalogs. Since we only need to detect if any of the 5 optional Express grammar features are present, we can optimize this process by exiting early as soon as all features are found (all(found.values()) is True).

def _detect_catalog_features(
    helpers: Mapping[str, CatalogSchemaHelper],
) -> _ExpressCatalogFeatures:
    """Derives which optional Express grammar rules the active catalogs can actually use."""
    found = {
        "data_bindings": False,
        "checks": False,
        "actions": False,
        "functions": False,
        "templates": False,
    }
    for helper in helpers.values():
        if all(found.values()):
            break
        if helper.functions:
            found["functions"] = True
        for comp_name in helper.component_properties:
            if all(found.values()):
                break
            if helper.is_checkable(comp_name):
                found["checks"] = True
            for prop_name in helper.get_component_properties(comp_name):
                if all(found.values()):
                    break
                p_schema = helper.get_property_schema(comp_name, prop_name)
                _scan_property_schema_features(
                    p_schema,
                    path_key=helper.path_key,
                    visited=set(),
                    found=found,
                )

@jacobsimionato jacobsimionato changed the title feat(python/agent): add exclusive hiding mode, prompt compaction (#4414), and example filtering (#2895) feat(python/agent): add macro hiding, prompt compaction, example filtering Dec 2, 2026
@jacobsimionato
jacobsimionato force-pushed the macros/7-hiding-prompts-examples branch from 8f1cbb7 to 47b192c 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/6-transformer-pipeline to macros/6b-default-catalog-simplifier December 2, 2026 23:18
@jacobsimionato
jacobsimionato removed this pull request from stack #4552 December 3, 2026 12:03
@jacobsimionato
jacobsimionato force-pushed the macros/7-hiding-prompts-examples branch from 47b192c to 8cdda8f Compare 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
@jacobsimionato jacobsimionato changed the title feat(python/agent): add macro hiding, prompt compaction, example filtering feat(python/agent): hide base functions, compact prompts, filter examples Dec 3, 2026
…), and example filtering (#2895)

Signed-off-by: Jacob Simionato <jsimionato@google.com>
@jacobsimionato
jacobsimionato force-pushed the macros/7-hiding-prompts-examples branch from 8cdda8f to c15fbc0 Compare December 3, 2026 12:24

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.

[FEATURE]: Express promptSnippet only teaches the syntax the active catalogs use agent_sdk: Ergonomic way to support multi-catalog examples

1 participant