Repository navigation
feat(python/agent): hide base functions, compact prompts, filter examples - #4534
jacobsimionato wants to merge 1 commit into
Conversation
There was a problem hiding this comment.
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.
| filtered = _filter_valid_examples(self.examples, inference_catalogs) | ||
| processor_examples = filtered or None |
There was a problem hiding this comment.
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 NoneReferences
- 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.
| 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, | ||
| ) |
There was a problem hiding this comment.
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,
)8f1cbb7 to
47b192c
Compare
47b192c to
8cdda8f
Compare
…), and example filtering (#2895) Signed-off-by: Jacob Simionato <jsimionato@google.com>
8cdda8f to
c15fbc0
Compare
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 madeA2uiGenerator.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
MacroExpandergainspassthrough_functions, which prunes base catalog functions the same waypassthrough_componentsprunes 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.test_express_prompt_rules_adapt_to_active_catalog_featureschecks that a macro-only Express prompt is under a third the size of the full Basic Catalog prompt.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.SkillGeneratorlabels functions-only catalogs "Helper function signatures".A2uiGeneratorgains an opt-infilter_examples_to_active_catalogsflag. When it is on, examples are checked once in__init__against all registered catalogs. Each session (onecreate_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
strorbytestopassthrough_componentsnow raisesTypeError(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
Where to review
Start here:
python/a2ui_agent/src/a2ui/transformers/macros/expander.py:passthrough_functionsand the v1.0 empty-catalog drop. The v0.9 path now reuses the existing pruning transformers.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.python/a2ui_agent/src/a2ui/processor/generator.pyandprocessor.py: eager validation grouped by protocol version, and per-session filtering.Implementation details
MacroExpandernow storespassthrough_componentsandpassthrough_functionsasfrozenset(previouslysetfor components) and rejectsstrorbytesfor either.transform_to_inference_catalog()replaces its hand-written component deletion with the two pruning transformers, which also drop$defsused only by pruned entries._detect_catalog_features()scans component property schemas and functionargsschemas. It recognizes common-type$refs (dynamic values, child lists, actions, check rules) and recurses through combinators,properties,items, andadditionalProperties. The nested function rule is also kept when templates are present and system functions exist. Remaining rules are renumbered without gaps.A2uiGenerator._validate_all_examples()groups registered catalogs by protocol version, applies the statictransformers(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 messageversion, or detects v0.8 envelope keys.transformer_factory,__init__only checks that each turn targets a registered protocol version; catalog validation waits until the session.A2uiRequestProcessorbehind a private keyword argument,_filter_invalid_examples, whichA2uiGenerator.create_processor()sets. Dropped turns are logged at debug level; if every turn is dropped, the session has no examples.SkillGenerator.generate_skillset()skips catalogs whose instructions are empty and describes functions-only catalogs as "Helper function signatures".python/a2ui_agent/src/a2ui/transformers/macros/README.mdandpython/a2ui_agent/CHANGELOG.mddocument the new options.Verification
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 andSkillGenerator, eager validation and per-session filtering across protocol versions).