Repository navigation
feat(python,docs): add a2ui.agent facade, inference_formats re-exports, and extending-the-sdk guide - #4543
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces a unified a2ui.agent public facade for the Python Agent SDK, adds composable A2uiTransformer support to A2uiRequestProcessor and A2uiGenerator, and updates MacroExpander to subclass the new transformer. It also includes comprehensive documentation and tests for extending the SDK. The review feedback highlights critical issues to address: copying transport_state.surface_catalogs before mutating it to avoid runtime errors or side effects, resolving error handling and type mismatches in _TransformingResponseStream.close(), and properly importing and exporting to_message_models in a2ui/inference_formats/__init__.py to prevent an ImportError.
…s, and extending-the-sdk guide Signed-off-by: Greg Spencer <gspencer@google.com>
2dfff42 to
bc5a623
Compare
aee32d9 to
2cbb544
Compare
| return 'Wrap UI payloads inside <my-ui>...</my-ui>.'; | ||
| } | ||
| protected renderCatalogInstructions(catalog: CatalogApi): string { | ||
| return `Catalog: ${catalog.catalogId}`; |
There was a problem hiding this comment.
The TypeScript and Dart custom PromptGenerator snippets fail to compile because CatalogApi exposes id (not catalogId) in both SDKs, and the Dart override adds a bool includeSchema = true parameter that Dart's base PromptGenerator.generateCatalogInstructions does not define or pass. All three tabs also reference undefined CustomParser, CustomFormat (Dart), and catalogs (TypeScript/Python) without stubs, and TypeScript imports RawResponsePart unused.
Additional details
- TypeScript (
typescript/core/web_core/src/catalog/types.tsdeclaresreadonly id: string):- Line 100:
catalog.catalogId->catalog.id - Line 89: remove unused
type RawResponsePart(unless used in aCustomParserstub) - Lines 114 & 119: define
catalogsand add a minimalCustomParserstub or comment
- Line 100:
- Dart (
dart/a2ui_core/lib/src/core/catalog.dartdeclaresfinal String id, anddart/a2ui_agent/lib/src/prompt/generator.dartdeclaresgenerateCatalogInstructions({CatalogApi? catalog})):@override - String generateCatalogInstructions({ - bool includeSchema = true, - CatalogApi? catalog, - }) { + String generateCatalogInstructions({CatalogApi? catalog}) { final targets = catalog != null ? [catalog] : catalogs; - return targets.map((c) => 'Catalog: ${c.catalogId}').join('\n'); + return targets.map((c) => 'Catalog: ${c.id}').join('\n'); }
- Line 218: add a minimal
CustomFormatstub or placeholder comment (and show passing the factory toA2uiRequestProcessor).
- Line 218: add a minimal
- Python (lines 169 & 182): define
catalogsand either provide a minimalCustomParserstub or comment notingParser's six abstract members (catalogs,has_format_content,wrap,unwrap,compile,decompile).
🤖 Agent-generated
| version = "0.1.0" | ||
| dependencies = [ | ||
| "a2ui-core>=0.7.0", | ||
| "a2ui-agent-sdk>0.12.1", |
There was a problem hiding this comment.
Pinning a2ui-agent-sdk>0.12.1 resolves to the already-tagged 0.13.0 release, which does not include a2ui.agent, RendererState.commit, or a2ui.utils.experimental, so extensions copying this manifest will fail at import time with ModuleNotFoundError. In addition, a2ui-core>=0.7.0 on the previous line is looser than a2ui-agent-sdk's own a2ui-core>=0.8.0,<0.9.0 requirement.
Additional details
Tag python/a2ui-agent-sdk/v0.13.0 (90f4a8cc2c) predates a2ui/agent.py, and python/a2ui_agent/pyproject.toml already sets fallback-version = "0.13.0" and requires "a2ui-core>=0.8.0,<0.9.0".
Update both constraints to match the first release that ships a2ui.agent:
dependencies = [
- "a2ui-core>=0.7.0",
- "a2ui-agent-sdk>0.12.1",
+ "a2ui-core>=0.8.0,<0.9.0",
+ "a2ui-agent-sdk>=0.14.0,<0.15.0",
]🤖 Agent-generated
| @@ -0,0 +1,323 @@ | |||
| --- | |||
| title: 'How to Extend the A2UI SDK' | |||
There was a problem hiding this comment.
Because A2UI has separate Core, Agent, and Renderer SDKs—and this guide covers only the Agent SDK—calling it "How to Extend the A2UI SDK" (with slug guides/extending-the-sdk) can mislead client or renderer developers looking for Core or Renderer extension points. Let's scope the title and slug to How to Extend the A2UI Agent SDK (guides/extending-the-agent-sdk) before merge, add it to docs/site/llms.txt, and remove the stale "composable transformers" wording in the agent-integration.mdx link.
Additional details
Details to update together:
- Title & slug: Rename
titleto'How to Extend the A2UI Agent SDK'and slug toguides/extending-the-agent-sdkindocs/site/astro.config.mjs(lines 252–253), matching sibling guides (How to Integrate A2UI into a Client, How to Integrate A2UI into an Agent), and update the links indocs/site/src/content/docs/concepts/inference-formats.mdx:288anddocs/site/src/content/docs/guides/agent-integration.mdx:1703. - Stale link copy (
agent-integration.mdx:1703): Replacecomposable transformers(dropped when converging on feat(python/agent): add TransformerPipeline, macro-safe streaming (#2865) #4533) withcatalog transformers, catalog providers. - Agent discovery (
docs/site/llms.txt): All 10 existing guides are listed under## Integration Guides(lines 48–57); add- [How to Extend the A2UI Agent SDK](https://a2ui.org/guides/extending-the-agent-sdk/) ([Markdown](https://a2ui.org/guides/extending-the-agent-sdk.md))afterUsing Macros.
| title: 'How to Extend the A2UI SDK' | |
| title: 'How to Extend the A2UI Agent SDK' |
🤖 Agent-generated
| </Tabs> | ||
|
|
||
| <Aside type="note" title="Do not override PromptGenerator.generate()"> | ||
| `PromptGenerator.generate()` is final in Python and shared with `SkillGenerator`. Override |
There was a problem hiding this comment.
This shared callout below the three-language tabs mentions only Python's @final and snake_case hooks, which contradicts the TypeScript tab right above it (where subclasses implement renderCatalogInstructions and renderExamples and overriding generate() silently diverges from SkillGenerator) and omits Dart's @nonVirtual. Similarly, line 75 says SkillGenerator picks up prompt hooks automatically when passing the factory to A2uiGenerator or A2uiRequestProcessor, whereas callers pass the InferenceFormat created by the factory directly to SkillGenerator.
Additional details
Actual contracts across the three SDKs:
- TypeScript (
typescript/agents/a2ui_agent/src/prompt/generator.ts,skill/generator.ts):generate()is concrete (not final), whileSkillGeneratorcallsgenerateBaseRules(),generateCatalogInstructions(c), andgenerateExamples(c)—so overridinggenerate()silently diverges from generated skills. Subclasses implementgenerateBaseRules(),renderCatalogInstructions(catalog), andrenderExamples(catalog). - Python (
python/a2ui_agent/src/a2ui/prompt/generator.py):generate()is@final; hooks aregenerate_base_rules(),generate_catalog_instructions(), andgenerate_examples(). - Dart (
dart/a2ui_agent/lib/src/prompt/generator.dart):generate()is@nonVirtual; hooks aregenerateBaseRules(),generateCatalogInstructions(), andgenerateExamples(). SkillGeneratorwiring (line 75): Across all three SDKs,SkillGeneratortakes anInferenceFormatinstance directly (A2uiRequestProcessor._formatis private in TS and Dart), so rephrase line 75 to:Pass your factory to A2uiGenerator or A2uiRequestProcessor, or pass the InferenceFormat your factory creates to SkillGenerator so generated skills reuse the same prompt hooks.
🤖 Agent-generated
|
|
||
| ## Transform catalogs and define macros | ||
|
|
||
| Use `CatalogTransformer` on `CatalogConfig` when you need a static per-catalog rewrite before prompting (such as `ComponentPruningTransformer` or `FunctionPruningTransformer`). |
There was a problem hiding this comment.
Calling this a "static" rewrite is misleading because CatalogConfig runs CatalogTransformer.transform() at runtime (lazily on first use and cached on the config), not at build or compile time. Describing it as a per-catalog rewrite applied before prompting and validation avoids making readers think it is an offline/build-time step (same for "statically" in the overview table on line 15).
Additional details
In python/a2ui_agent/src/a2ui/processor/catalog_config.py, CatalogConfig.transformed_catalog is a @cached_property that executes each configured CatalogTransformer sequentially at runtime on first use and reuses the result across requests.
| Use `CatalogTransformer` on `CatalogConfig` when you need a static per-catalog rewrite before prompting (such as `ComponentPruningTransformer` or `FunctionPruningTransformer`). | |
| Use `CatalogTransformer` on `CatalogConfig` when you need to rewrite or prune a catalog at runtime before prompting and validation (such as `ComponentPruningTransformer` or `FunctionPruningTransformer`). The transformed catalog is computed once per `CatalogConfig` and reused across requests. |
Also consider updating line 15 in the overview table from Prune or rewrite a single catalog statically to Prune or rewrite a catalog before prompting and validation.
🤖 Agent-generated
| To ship a reusable third-party extension package (following the same architecture as `a2ui-agent-experimental`): | ||
|
|
||
| 1. Depend only on `a2ui-core` and `a2ui-agent-sdk` in `pyproject.toml`, keeping core logic free of agent framework, transport, and LLM client dependencies. | ||
| 2. Import only from top-level public facade modules (`a2ui.agent`, `a2ui.core`, `a2ui.core.basic_catalog`, `a2ui.core.schema`, `a2ui.builder.v1_0`). Never deep-import internal submodules, even those without a leading underscore. |
There was a problem hiding this comment.
This packaging checklist contradicts the guide itself and cites a nonexistent package: step 2's allowlist omits a2ui.utils.experimental even though line 295 right above imports from it (so step 3's custom ast test fails on the guide's own code), and lines 242 and 309 cite a2ui-agent-experimental and DecisionModel, which do not exist in the repo or on PyPI.
Additional details
- Allowlist mismatch (line 312): Include
a2ui.utils.experimental(for optional experimental schema inspection) anda2ui.constants(zero-dependency leaf constants), or simplify once internals are hidden behind_-prefixed subpackages undera2ui.agent. - Enforcing without custom
astscripts (line 313): Until internals are_-prefixed, a few lines of Ruff[tool.ruff.lint.flake8-tidy-imports.banned-api]is lighter for extension authors than maintaining a customasttest. - Nonexistent package/symbol (lines 242 & 309):
git grepfinds zero matches fora2ui-agent-experimentalorDecisionModeloutside this file—keep both lines generic (e.g. "custom planner or decision-model packages" on line 242, and "To ship a reusable third-party extension package:" on line 309).
🤖 Agent-generated
| ## Unreleased | ||
|
|
||
| - Added the unified `a2ui.agent` public facade and re-exported `InferenceFormat` | ||
| and `InferenceFormatFactory` from `a2ui.inference_formats`. |
There was a problem hiding this comment.
This changelog entry is missing the PR link ([#4543](...)), breaking traceability in generated release notes and diverging from the other entries under ## Unreleased.
Additional details
Per .agents/skills/update-changelog/SKILL.md (Core Rule 6), every changelog entry should conclude with a clickable PR link.
| and `InferenceFormatFactory` from `a2ui.inference_formats`. | |
| and `InferenceFormatFactory` from `a2ui.inference_formats` | |
| ([#4543](https://github.com/a2ui-project/a2ui/pull/4543)). |
🤖 Agent-generated
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| """Unified public facade for the A2UI Python Agent SDK. |
There was a problem hiding this comment.
Let's aim for one canonical way to import everything from a2ui-agent-sdk instead of maintaining parallel top-level paths alongside a2ui.agent. Structuring this as a package (a2ui/agent/__init__.py, matching a2ui.core, a2ui.a2a, and a2ui.adk) lets us move internals behind _-prefixed subpackages (with one-release DeprecationWarning shims on the legacy paths) so Pyright/Pylance, Ruff, and IDE auto-import enforce the single entry point automatically instead of asking every downstream author to write a custom ast test. Along the same lines, let's skip adding new exports to a2ui.inference_formats and fill the missing public exports on a2ui.agent so extensions don't have to reach past it.
Additional details
Concrete pieces to align around a single public surface:
- Use a package (
src/a2ui/agent/__init__.py) + plan to hide internals behind_: Matchesa2ui/core/,a2ui/a2a/, anda2ui/adk/. Moving implementations undera2ui/agent/_...in a follow-up (withDeprecationWarningshims likea2ui.core._compat/a2ui.inference_strategy) makesreportPrivateImportUsage/ RuffPLC2701enforce the boundary for all users automatically. Separate intentional sub-facades stay explicit:a2ui.constants(zero-dependency leaf),a2ui.builder.v0_9/v1_0(protocol-versioned), and opt-in experimental APIs (e.g.a2ui.agent.experimental). - Don't widen
a2ui.inference_formats/__init__.py: Avoid adding new public re-exports (InferenceFormat,InferenceFormatFactory) to a legacy path we want to consolidate away from—callers already havea2ui.inference_formatfor backwards compatibility anda2ui.agentgoing forward. - Export the missing public Agent SDK symbols on
a2ui.agent: CustomParser.compileimplementations and format extensions currently have to deep-importA2uiCompilationError,A2uiCompilationParseError,A2uiCompilationValidationError(a2ui.parser),DirectJsonResponseStream,DirectJsonDecompiler(a2ui.inference_formats.direct_json), andExpressDecompiler(a2ui.inference_formats.express)—all of which are exported by@a2ui/agent(andExpressResponseStreamis already here). Also,to_message_dicts/to_message_modelscan be imported directly froma2ui.parserrather than througha2ui.inference_formats.
(Note: DirectJsonPromptGenerator/ExpressPromptGenerator were intentionally unexported in #3568, so keeping those out makes sense; sibling a2ui-a2a also currently imports BlockLexer, JSON_PAYLOAD_START_RE, read_json, and to_version_number, which is worth auditing before deprecating the legacy paths.)
🤖 Agent-generated
| "to_message_models", | ||
| } | ||
| exported = set(agent.__all__) | ||
| assert expected.issubset(exported) |
There was a problem hiding this comment.
This test checks only hasattr on a 20-symbol subset (omitting validate_payload, which the guide highlights) and deduplicates agent.__all__ via set(...), so duplicate or unsorted __all__ entries, leaked private (_-prefixed) names, or accidental a2ui.core pass-through re-exports would pass unnoticed.
Additional details
Strengthening the invariants catches facade regressions automatically:
assert agent.__all__ == sorted(set(agent.__all__))
assert all(not name.startswith("_") for name in agent.__all__)
public_attrs = {
name for name in vars(agent) if not name.startswith("_") and name != "annotations"
}
assert public_attrs == set(agent.__all__)You can also add "validate_payload" to expected and assert identity (is) against the defining submodules plus not getattr(getattr(agent, name), "__module__", "").startswith("a2ui.core") to guard against cross-package re-export leaks.
🤖 Agent-generated
Summary
Add the unified
a2ui.agentfacade anda2ui.inference_formatsABC re-exports (InferenceFormat,InferenceFormatFactory) toa2ui-agent-sdk. Also adddocs/site/src/content/docs/guides/extending-the-sdk.mdxshowing how to extend the Agent SDK through public interfaces.Reviewer Focus
python/a2ui_agent/src/a2ui/agent.py: Single top-level facade for agent coordination, formats, transformers, macros, validation, skills, and RPC. Matches@a2ui/agentin TypeScript andpackage:a2ui_agent/a2ui_agent.dartin Dart.python/a2ui_agent/src/a2ui/inference_formats/__init__.py: Re-exportsInferenceFormatandInferenceFormatFactoryalongside the built-in format implementations.docs/site/src/content/docs/guides/extending-the-sdk.mdx: Developer guide covering custom inference formats,CatalogTransformer,@macro/MacroExpander,RendererState.commit/validate_payload,CatalogSchemaInspector, and standalone extension packaging.Changes
python/a2ui_agent/src/a2ui/agent.pyexporting 44 public SDK contracts in__all__.InferenceFormatandInferenceFormatFactoryfrompython/a2ui_agent/src/a2ui/inference_formats/__init__.py.docs/site/src/content/docs/guides/extending-the-sdk.mdx, registered it indocs/site/astro.config.mjs, and linked to it fromdocs/site/src/content/docs/guides/agent-integration.mdxanddocs/site/src/content/docs/concepts/inference-formats.mdx.python/a2ui_agent/tests/test_agent_facade.pyand updatedpython/a2ui_agent/CHANGELOG.md.Impact & Risks
TransformerPipelineandCatalogMessageTransformerfrom feat(python/agent): add TransformerPipeline, macro-safe streaming (#2865) #4533.Testing
uv run pytest python/a2ui_agent/tests/test_agent_facade.py python/a2ui_agent/tests/test_macro_lowering.py python/a2ui_agent/tests/processor/uv run mypy python/a2ui_agent/src/a2ui/agent.py python/a2ui_agent/src/a2ui/inference_formats/__init__.pyuv run pyink --check python/a2ui_agent/src/a2ui/agent.py python/a2ui_agent/tests/test_agent_facade.pyandprettier --check docs/site/src/content/docs/guides/extending-the-sdk.mdx