From 3c4b43ecd5d29fe4e4d185033b7743d84252b5ba Mon Sep 17 00:00:00 2001 From: Greg Spencer Date: Wed, 2 Dec 2026 22:04:04 +0000 Subject: [PATCH 1/4] feat(python,docs): add a2ui.agent facade package and Agent SDK extension guide Signed-off-by: Greg Spencer --- docs/site/astro.config.mjs | 4 + docs/site/llms.txt | 1 + .../docs/concepts/inference-formats.mdx | 2 +- .../content/docs/guides/agent-integration.mdx | 2 +- .../docs/guides/extending-the-agent-sdk.mdx | 356 ++++++++++++++++++ python/a2ui_agent/CHANGELOG.md | 2 + python/a2ui_agent/src/a2ui/agent/__init__.py | 138 +++++++ python/a2ui_agent/tests/test_agent_facade.py | 108 ++++++ 8 files changed, 611 insertions(+), 2 deletions(-) create mode 100644 docs/site/src/content/docs/guides/extending-the-agent-sdk.mdx create mode 100644 python/a2ui_agent/src/a2ui/agent/__init__.py create mode 100644 python/a2ui_agent/tests/test_agent_facade.py diff --git a/docs/site/astro.config.mjs b/docs/site/astro.config.mjs index d6c3809f49..8d79c73a25 100644 --- a/docs/site/astro.config.mjs +++ b/docs/site/astro.config.mjs @@ -248,6 +248,10 @@ export default defineConfig({ label: 'Using Macros', slug: 'guides/macros', }, + { + label: 'How to Extend the A2UI Agent SDK', + slug: 'guides/extending-the-agent-sdk', + }, { label: 'Model Context Protocol (MCP)', collapsed: true, diff --git a/docs/site/llms.txt b/docs/site/llms.txt index 46f5d8aa2a..4d27d6f25d 100644 --- a/docs/site/llms.txt +++ b/docs/site/llms.txt @@ -49,6 +49,7 @@ Parallel Markdown editions of documentation pages are available by appending `.m - [How to Integrate A2UI into an Agent](https://a2ui.org/guides/agent-integration/) ([Markdown](https://a2ui.org/guides/agent-integration.md)) - [How to Define a Catalog](https://a2ui.org/guides/defining-a-catalog/) ([Markdown](https://a2ui.org/guides/defining-a-catalog.md)) - [Using Macros](https://a2ui.org/guides/macros/) ([Markdown](https://a2ui.org/guides/macros.md)) +- [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)) - [MCP Overview](https://a2ui.org/guides/mcp-overview/) ([Markdown](https://a2ui.org/guides/mcp-overview.md)) - [Call MCP Tools from A2UI](https://a2ui.org/guides/mcp-catalog/) ([Markdown](https://a2ui.org/guides/mcp-catalog.md)) - [Serve A2UI Layouts from an MCP Server](https://a2ui.org/guides/a2ui-over-mcp/) ([Markdown](https://a2ui.org/guides/a2ui-over-mcp.md)) diff --git a/docs/site/src/content/docs/concepts/inference-formats.mdx b/docs/site/src/content/docs/concepts/inference-formats.mdx index e3bf47e510..74db44b84b 100644 --- a/docs/site/src/content/docs/concepts/inference-formats.mdx +++ b/docs/site/src/content/docs/concepts/inference-formats.mdx @@ -285,7 +285,7 @@ void illustrateFormats( -Express covers v0.9, v0.9.1, and v1.0 generation with lower token cost, while Direct JSON remains useful when serving legacy v0.8 payloads in Python, debugging raw wire payloads, or calling a model fine-tuned directly on A2UI JSON schemas. Teams experimenting with alternative grammars (such as HTML-inspired or S-expression notations; see [`python/a2ui_agent/src/a2ui/inference_formats/experimental/`](https://github.com/a2ui-project/a2ui/tree/main/python/a2ui_agent/src/a2ui/inference_formats/experimental)) implement the same `InferenceFormatFactory`, `PromptGenerator`, and `Parser` interfaces. +Express covers v0.9, v0.9.1, and v1.0 generation with lower token cost, while Direct JSON remains useful when serving legacy v0.8 payloads in Python, debugging raw wire payloads, or calling a model fine-tuned directly on A2UI JSON schemas. Teams experimenting with alternative grammars implement the same `InferenceFormatFactory`, `PromptGenerator`, and `Parser` interfaces (see [How to Extend the A2UI Agent SDK](../../guides/extending-the-agent-sdk/) and [`python/a2ui_agent/src/a2ui/inference_formats/experimental/`](https://github.com/a2ui-project/a2ui/tree/main/python/a2ui_agent/src/a2ui/inference_formats/experimental)). ## Token and latency benchmarks diff --git a/docs/site/src/content/docs/guides/agent-integration.mdx b/docs/site/src/content/docs/guides/agent-integration.mdx index b44e55d72d..ab317a41c3 100644 --- a/docs/site/src/content/docs/guides/agent-integration.mdx +++ b/docs/site/src/content/docs/guides/agent-integration.mdx @@ -1700,7 +1700,7 @@ final prunedGenerator = A2uiGenerator( ## Connect to agent frameworks and transports -Plug the A2UI generator and message processors into standard agent frameworks and protocols instead of writing custom transport plumbing. +Plug the A2UI generator and message processors into standard agent frameworks and protocols instead of writing custom transport plumbing. To add custom inference formats, catalog transformers, catalog providers, or standalone extension packages, see [How to Extend the A2UI Agent SDK](../extending-the-agent-sdk/). ### Google ADK diff --git a/docs/site/src/content/docs/guides/extending-the-agent-sdk.mdx b/docs/site/src/content/docs/guides/extending-the-agent-sdk.mdx new file mode 100644 index 0000000000..55eb55737a --- /dev/null +++ b/docs/site/src/content/docs/guides/extending-the-agent-sdk.mdx @@ -0,0 +1,356 @@ +--- +title: 'How to Extend the A2UI Agent SDK' +description: 'Extend the A2UI Agent SDK with custom inference formats, catalog transformers, catalog providers, macros, RPC handlers, and standalone extension packages.' +--- + +import {Aside, Tabs, TabItem} from '@astrojs/starlight/components'; + +Extend the A2UI [Agent SDK](../../concepts/sdks/#agent-sdk) through public, framework-agnostic interfaces to add new [inference formats](../../concepts/inference-formats/), transform catalogs, load catalogs from custom backends, or publish standalone extension packages without importing private SDK internals. + +## Extension points at a glance + +| Goal | Public interface | Scope | +| :----------------------------------------------------- | :-------------------------------------------------------------------------------------------------- | :---------------------------------------------------------- | +| Add a new LLM syntax or wire notation | `InferenceFormatFactory`, `InferenceFormat`, `PromptGenerator`, `Parser`, `ResponseStream` | TypeScript, Python, Dart | +| Prune or rewrite a catalog before prompting/validation | `CatalogTransformer` on `CatalogConfig` | TypeScript, Python, Dart | +| Load catalogs from a database, service, or registry | `CatalogProvider` | TypeScript, Python, Dart | +| Define server-side composite components | `@macro`, `MacroExpander` | Python | +| Validate and commit messages from a custom loop | `RendererState.commit`, `validate_payload` | Python (`RendererState` + `validatePayload` in TS and Dart) | +| Inspect component properties dynamically | `a2ui.utils.experimental.CatalogSchemaInspector` (`@experimental`, transitioning to `CatalogModel`) | Python | +| Handle renderer-to-agent RPC and client actions | `RendererToAgentMessageProcessor`, `RendererFunctionCalls` | TypeScript, Python, Dart | + +## Import from the single SDK entry point + +Each Agent SDK exposes its core extension contracts from one public entry point so third-party packages avoid deep submodule imports. + + + + +```ts +import { + A2uiGenerator, + A2uiRequestProcessor, + type CatalogProvider, + type CatalogTransformer, + type InferenceFormat, + type InferenceFormatFactory, + Parser, + PromptGenerator, + RendererState, +} from '@a2ui/agent'; +``` + + + + +```python +from a2ui.agent import ( + A2uiGenerator, + A2uiRequestProcessor, + CatalogProvider, + CatalogTransformer, + InferenceFormat, + InferenceFormatFactory, + MacroExpander, + Parser, + PromptGenerator, + RendererState, + ResponseStream, + macro, +) +``` + + + + +```dart +import 'package:a2ui_agent/a2ui_agent.dart'; +``` + + + + +## Implement a custom inference format + +To teach an LLM a new syntax (for example, a domain-specific shorthand or structured DSL), implement `PromptGenerator`, `Parser`, `InferenceFormat`, and `InferenceFormatFactory`. Pass your factory to `A2uiGenerator` or `A2uiRequestProcessor`, or pass the `InferenceFormat` your factory creates to `SkillGenerator` so generated skills reuse the same prompt hooks. + + + + +```ts +import { + A2uiRequestProcessor, + type AgentToRendererMessage, + type CatalogApi, + type InferenceFormat, + type InferenceFormatFactory, + Parser, + PromptGenerator, +} from '@a2ui/agent'; + +// Implement Parser (compile, decompile, wrap, unwrap, etc.) for your syntax. +declare class CustomParser extends Parser {} +declare const catalogs: CatalogApi[]; + +class CustomPromptGenerator extends PromptGenerator { + constructor(catalogs: CatalogApi[]) { + super(catalogs); + } + generateBaseRules(): string { + return 'Wrap UI payloads inside ....'; + } + protected renderCatalogInstructions(catalog: CatalogApi): string { + return `Catalog: ${catalog.id}`; + } + protected renderExamples(_catalog: CatalogApi): string { + return ''; + } +} + +class CustomFormatFactory implements InferenceFormatFactory { + createFormat( + catalogs: CatalogApi[], + _examples?: Record, + ): InferenceFormat { + return { + promptGenerator: new CustomPromptGenerator(catalogs), + createParser: () => new CustomParser(catalogs), + }; + } +} + +const processor = new A2uiRequestProcessor(catalogs, undefined, new CustomFormatFactory()); +``` + + + + +```python +from collections.abc import Sequence + +from a2ui.agent import ( + A2uiRequestProcessor, + InferenceFormat, + InferenceFormatFactory, + Parser, + PromptGenerator, +) +from a2ui.core import CatalogApi +from a2ui.core.basic_catalog import BasicCatalog +from a2ui.core.schema import AgentToRendererMessage, ProtocolVersion + + +class CustomParser(Parser): + """Subclass Parser and implement its six abstract members: + catalogs, has_format_content, wrap, unwrap, compile, and decompile. + """ + + def __init__(self, catalogs: Sequence[CatalogApi]) -> None: + self._catalogs = list(catalogs) + + +class CustomPromptGenerator(PromptGenerator): + def __init__(self, catalogs: Sequence[CatalogApi]) -> None: + self._catalogs = list(catalogs) + + @property + def catalogs(self) -> list[CatalogApi]: + return list(self._catalogs) + + def generate_base_rules(self) -> str: + return "Wrap UI payloads inside ...." + + def generate_catalog_instructions( + self, + include_schema: bool = True, + catalog: CatalogApi | None = None, + ) -> str: + del include_schema + targets = [catalog] if catalog is not None else self._catalogs + return "\n".join(f"Catalog: {c.catalog_id}" for c in targets) + + +class CustomFormat(InferenceFormat): + def __init__(self, catalogs: Sequence[CatalogApi]) -> None: + self._catalogs = list(catalogs) + self._prompt = CustomPromptGenerator(self._catalogs) + + @property + def prompt_generator(self) -> PromptGenerator: + return self._prompt + + def create_parser(self) -> Parser: + return CustomParser(self._catalogs) + + +class CustomFormatFactory(InferenceFormatFactory): + def create_format( + self, + catalogs: Sequence[CatalogApi], + examples: Sequence[Sequence[AgentToRendererMessage]] | None = None, + ) -> InferenceFormat: + del examples + return CustomFormat(catalogs) + + +catalogs: list[CatalogApi] = [BasicCatalog(ProtocolVersion.V1_0)] +processor = A2uiRequestProcessor(catalogs, format_factory=CustomFormatFactory()) +``` + + + + +```dart +import 'package:a2ui_agent/a2ui_agent.dart'; +import 'package:a2ui_core/a2ui_core.dart'; + +class CustomPromptGenerator extends PromptGenerator { + CustomPromptGenerator(this.catalogs); + + @override + final List catalogs; + + @override + String generateBaseRules() => 'Wrap UI payloads inside ....'; + + @override + String generateCatalogInstructions({CatalogApi? catalog}) { + final targets = catalog != null ? [catalog] : catalogs; + return targets.map((c) => 'Catalog: ${c.id}').join('\n'); + } +} + +class CustomFormat implements InferenceFormat { + CustomFormat(this.catalogs) + : promptGenerator = CustomPromptGenerator(catalogs); + + final List catalogs; + + @override + final PromptGenerator promptGenerator; + + @override + Parser createParser() => throw UnimplementedError('Return your Parser'); +} + +class CustomFormatFactory implements InferenceFormatFactory { + const CustomFormatFactory(); + + @override + InferenceFormat createFormat( + List catalogs, { + List> examples = const [], + }) => CustomFormat(catalogs); +} + +// Wire the factory into A2uiRequestProcessor: +// final processor = A2uiRequestProcessor( +// catalogs, +// formatFactory: const CustomFormatFactory(), +// ); +``` + + + + + + +## Transform catalogs and define macros + +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. + +For server-side composite components authored with `@macro` and expanded with `MacroExpander`, see [Using Macros](../macros/). + +## Model providers and agent frameworks + +The A2UI Agent SDK stays intentionally agnostic to LLM client libraries, network transports, and credentials: + +- **Standard LLM providers** (Gemini, OpenAI, Anthropic, local models, or framework runtimes such as ADK and LangGraph) integrate outside `a2ui-agent-sdk` by feeding `processor.prompt_snippet` into your model call and passing streamed text chunks into `processor.open_stream()` or `processor.parse_response()`. See [How to Integrate A2UI into an Agent](../agent-integration/). +- **Specialized model extensions** (such as custom planner or decision-model packages) define narrow async callable protocols in their own extension packages and validate emitted `AgentToRendererMessage` payloads through `RendererState.commit` or `validate_payload`. + +## Validate and commit messages from a custom loop + +If your extension synthesizes A2UI messages directly instead of parsing LLM text, use `RendererState.commit` to validate and commit batches atomically to a `RendererState`, or `validate_payload` for stateless validation: + +```python +from a2ui.agent import ( + RendererState, + to_message_dicts, + to_message_models, + validate_payload, +) +from a2ui.core.basic_catalog import BasicCatalog +from a2ui.core.schema import ProtocolVersion + +catalogs = [BasicCatalog(ProtocolVersion.V1_0)] +state = RendererState(catalogs) + +candidate_messages = list( + to_message_models([ + { + "version": "1.0", + "createSurface": { + "surfaceId": "status_1", + "catalogId": catalogs[0].catalog_id, + }, + }, + { + "version": "1.0", + "updateComponents": { + "surfaceId": "status_1", + "components": [ + {"id": "root", "component": "Text", "text": "Ready"}, + ], + }, + }, + ]) +) + +state.commit(candidate_messages) +wire_payload = to_message_dicts(candidate_messages) +``` + +For stateless validation without mutating a session's `RendererState`, call `validate_payload(catalogs, candidate_messages)`. + +## Inspect catalog schemas dynamically + +Extensions that generate UI generically across arbitrary catalogs can inspect components, child slots, actions, and bindable properties with `CatalogSchemaInspector` (`@experimental` in `a2ui.utils.experimental`, scheduled to be superseded by canonical `CatalogModel` in `a2ui-core`): + +```python +from a2ui.core.basic_catalog import BasicCatalog +from a2ui.core.schema import ProtocolVersion +from a2ui.utils.experimental import CatalogSchemaInspector, resolve_default_catalog_id + +catalogs = [BasicCatalog(ProtocolVersion.V1_0)] +inspectors = CatalogSchemaInspector.for_catalogs(catalogs) +default_cid = resolve_default_catalog_id(catalogs) +assert default_cid is not None + +inspector = inspectors[default_cid] +for prop in inspector.component_property_infos("Button"): + print(f"Button.{prop.name}: kind={prop.kind}, required={prop.required}") +``` + +## Package a standalone Python extension + +To ship a reusable third-party extension package: + +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.constants`, `a2ui.core`, `a2ui.core.basic_catalog`, `a2ui.core.schema`, `a2ui.builder.v1_0`, and `a2ui.utils.experimental` for opt-in experimental schema inspection). Never deep-import internal submodules, even those without a leading underscore. +3. Enforce the boundary in CI with Ruff's `[tool.ruff.lint.flake8-tidy-imports.banned-api]` (banning internal `a2ui.*` submodules and any agent framework or transport imports in your core package). + +```toml +[project] +name = "acme-a2ui-charts" +version = "0.1.0" +dependencies = [ + "a2ui-core>=0.8.0,<0.9.0", + "a2ui-agent-sdk>=0.14.0,<0.15.0", +] +``` diff --git a/python/a2ui_agent/CHANGELOG.md b/python/a2ui_agent/CHANGELOG.md index c6012e3e6e..954956fa3b 100644 --- a/python/a2ui_agent/CHANGELOG.md +++ b/python/a2ui_agent/CHANGELOG.md @@ -1,5 +1,7 @@ ## Unreleased +- Added the unified `a2ui.agent` public facade package + ([#4549](https://github.com/a2ui-project/a2ui/pull/4549)). - **BREAKING CHANGE**: (v1_0) `RendererState.check_topology` and `validate_payload` on created surfaces (and therefore `Parser.parse_response` and `ResponseStream`) reject v1.0 `{"@call": "@index"}` function calls on diff --git a/python/a2ui_agent/src/a2ui/agent/__init__.py b/python/a2ui_agent/src/a2ui/agent/__init__.py new file mode 100644 index 0000000000..31603e9d40 --- /dev/null +++ b/python/a2ui_agent/src/a2ui/agent/__init__.py @@ -0,0 +1,138 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Unified public facade for the A2UI Python Agent SDK. + +Re-exports the primary agent coordination, inference format, transformer, +validation, skill generation, and RPC contracts from a single entry point, +matching `@a2ui/agent` in TypeScript and `package:a2ui_agent/a2ui_agent.dart` +in Dart. +""" + +from __future__ import annotations + +from a2ui.catalog_transformers import ( + CatalogTransformer, + ComponentPruningTransformer, + FunctionPruningTransformer, +) +from a2ui.inference_format import InferenceFormat, InferenceFormatFactory +from a2ui.inference_formats import ( + DirectJsonFormat, + DirectJsonFormatFactory, + DirectJsonParser, + ExpressFormat, + ExpressFormatFactory, + ExpressParser, + ExpressResponseStream, +) +from a2ui.inference_formats.direct_json import ( + DirectJsonDecompiler, + DirectJsonResponseStream, +) +from a2ui.inference_formats.express import ExpressDecompiler +from a2ui.parser import ( + A2uiCompilationError, + A2uiCompilationParseError, + A2uiCompilationValidationError, + A2uiPart, + ErrorPart, + Parser, + RawA2uiPart, + RawResponsePart, + ResponsePart, + ResponseStream, + StreamPart, + TextPart, + to_message_dicts, + to_message_models, +) +from a2ui.processor import ( + A2uiGenerator, + A2uiRequestProcessor, + CatalogConfig, + CatalogProvider, + FileSystemCatalogProvider, + InMemoryCatalogProvider, +) +from a2ui.prompt import PromptGenerator, assemble_instructions +from a2ui.rpc import ( + DEFAULT_RENDERER_CALL_TIMEOUT, + ProcessResult, + RendererFunctionCalls, + RendererToAgentMessageProcessor, +) +from a2ui.skill import Skill, SkillGenerator, SkillSet +from a2ui.transformers import MacroExpander, macro +from a2ui.utils import ( + RendererState, + agent_callable_functions, + read_renderer_capabilities, + resolve_catalogs, + validate_payload, +) + +__all__ = [ + "A2uiCompilationError", + "A2uiCompilationParseError", + "A2uiCompilationValidationError", + "A2uiGenerator", + "A2uiPart", + "A2uiRequestProcessor", + "CatalogConfig", + "CatalogProvider", + "CatalogTransformer", + "ComponentPruningTransformer", + "DEFAULT_RENDERER_CALL_TIMEOUT", + "DirectJsonDecompiler", + "DirectJsonFormat", + "DirectJsonFormatFactory", + "DirectJsonParser", + "DirectJsonResponseStream", + "ErrorPart", + "ExpressDecompiler", + "ExpressFormat", + "ExpressFormatFactory", + "ExpressParser", + "ExpressResponseStream", + "FileSystemCatalogProvider", + "FunctionPruningTransformer", + "InMemoryCatalogProvider", + "InferenceFormat", + "InferenceFormatFactory", + "MacroExpander", + "Parser", + "ProcessResult", + "PromptGenerator", + "RawA2uiPart", + "RawResponsePart", + "RendererFunctionCalls", + "RendererState", + "RendererToAgentMessageProcessor", + "ResponsePart", + "ResponseStream", + "Skill", + "SkillGenerator", + "SkillSet", + "StreamPart", + "TextPart", + "agent_callable_functions", + "assemble_instructions", + "macro", + "read_renderer_capabilities", + "resolve_catalogs", + "to_message_dicts", + "to_message_models", + "validate_payload", +] diff --git a/python/a2ui_agent/tests/test_agent_facade.py b/python/a2ui_agent/tests/test_agent_facade.py new file mode 100644 index 0000000000..1e435c6d5e --- /dev/null +++ b/python/a2ui_agent/tests/test_agent_facade.py @@ -0,0 +1,108 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for the unified `a2ui.agent` public facade package.""" + +from __future__ import annotations + +import a2ui.agent as agent +from a2ui.catalog_transformers import CatalogTransformer +from a2ui.inference_format import InferenceFormat, InferenceFormatFactory +from a2ui.inference_formats.direct_json import ( + DirectJsonDecompiler, + DirectJsonFormatFactory, + DirectJsonResponseStream, +) +from a2ui.inference_formats.express import ( + ExpressDecompiler, + ExpressFormatFactory, + ExpressResponseStream, +) +from a2ui.parser import ( + A2uiCompilationError, + A2uiCompilationParseError, + A2uiCompilationValidationError, + Parser, + ResponseStream, + to_message_dicts, + to_message_models, +) +from a2ui.processor import ( + A2uiGenerator, + A2uiRequestProcessor, + CatalogConfig, + CatalogProvider, +) +from a2ui.prompt import PromptGenerator +from a2ui.rpc import RendererFunctionCalls, RendererToAgentMessageProcessor +from a2ui.skill import SkillGenerator +from a2ui.transformers import MacroExpander, macro +from a2ui.utils import RendererState, validate_payload + + +def test_agent_facade_is_package_with_clean_all() -> None: + assert hasattr(agent, "__path__"), "a2ui.agent must be a package" + 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__) + + +def test_agent_facade_exports_core_contracts_by_identity() -> None: + expected = { + "A2uiCompilationError": A2uiCompilationError, + "A2uiCompilationParseError": A2uiCompilationParseError, + "A2uiCompilationValidationError": A2uiCompilationValidationError, + "A2uiGenerator": A2uiGenerator, + "A2uiRequestProcessor": A2uiRequestProcessor, + "CatalogConfig": CatalogConfig, + "CatalogProvider": CatalogProvider, + "CatalogTransformer": CatalogTransformer, + "DirectJsonDecompiler": DirectJsonDecompiler, + "DirectJsonFormatFactory": DirectJsonFormatFactory, + "DirectJsonResponseStream": DirectJsonResponseStream, + "ExpressDecompiler": ExpressDecompiler, + "ExpressFormatFactory": ExpressFormatFactory, + "ExpressResponseStream": ExpressResponseStream, + "InferenceFormat": InferenceFormat, + "InferenceFormatFactory": InferenceFormatFactory, + "MacroExpander": MacroExpander, + "Parser": Parser, + "PromptGenerator": PromptGenerator, + "RendererFunctionCalls": RendererFunctionCalls, + "RendererState": RendererState, + "RendererToAgentMessageProcessor": RendererToAgentMessageProcessor, + "ResponseStream": ResponseStream, + "SkillGenerator": SkillGenerator, + "macro": macro, + "to_message_dicts": to_message_dicts, + "to_message_models": to_message_models, + "validate_payload": validate_payload, + } + for name, obj in expected.items(): + assert name in agent.__all__, f"Missing {name!r} from a2ui.agent.__all__" + assert getattr(agent, name) is obj + + +def test_agent_facade_does_not_reexport_a2ui_core() -> None: + for name in agent.__all__: + obj = getattr(agent, name) + mod = getattr(obj, "__module__", "") or "" + assert not mod.startswith( + "a2ui.core" + ), f"a2ui.agent.{name} leaks a2ui.core symbol from {mod}" From 56b19967525eb2fa58524c27e74364432a6125bc Mon Sep 17 00:00:00 2001 From: Greg Spencer Date: Wed, 2 Dec 2026 22:43:55 +0000 Subject: [PATCH 2/4] docs(site): add abstract method stubs to Python and Dart Agent SDK guide snippets Signed-off-by: Greg Spencer --- .../docs/guides/extending-the-agent-sdk.mdx | 29 +++++++++++++++++-- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/docs/site/src/content/docs/guides/extending-the-agent-sdk.mdx b/docs/site/src/content/docs/guides/extending-the-agent-sdk.mdx index 55eb55737a..3a9f4781fe 100644 --- a/docs/site/src/content/docs/guides/extending-the-agent-sdk.mdx +++ b/docs/site/src/content/docs/guides/extending-the-agent-sdk.mdx @@ -141,13 +141,30 @@ from a2ui.core.schema import AgentToRendererMessage, ProtocolVersion class CustomParser(Parser): - """Subclass Parser and implement its six abstract members: - catalogs, has_format_content, wrap, unwrap, compile, and decompile. - """ + """Subclass Parser and implement its six abstract members.""" def __init__(self, catalogs: Sequence[CatalogApi]) -> None: self._catalogs = list(catalogs) + @property + def catalogs(self) -> list[CatalogApi]: + return list(self._catalogs) + + def has_format_content(self, response: str) -> bool: + raise NotImplementedError() + + def wrap(self, content: str) -> str: + raise NotImplementedError() + + def unwrap(self, response: str) -> str: + raise NotImplementedError() + + def compile(self, block: str) -> list[AgentToRendererMessage]: + raise NotImplementedError() + + def decompile(self, messages: Sequence[AgentToRendererMessage]) -> str: + raise NotImplementedError() + class CustomPromptGenerator(PromptGenerator): def __init__(self, catalogs: Sequence[CatalogApi]) -> None: @@ -169,6 +186,9 @@ class CustomPromptGenerator(PromptGenerator): targets = [catalog] if catalog is not None else self._catalogs return "\n".join(f"Catalog: {c.catalog_id}" for c in targets) + def generate_examples(self) -> str: + return "" + class CustomFormat(InferenceFormat): def __init__(self, catalogs: Sequence[CatalogApi]) -> None: @@ -218,6 +238,9 @@ class CustomPromptGenerator extends PromptGenerator { final targets = catalog != null ? [catalog] : catalogs; return targets.map((c) => 'Catalog: ${c.id}').join('\n'); } + + @override + String generateExamples() => ''; } class CustomFormat implements InferenceFormat { From b0e5cb53e6a13b8754883e1d415b39b896117b7e Mon Sep 17 00:00:00 2001 From: Greg Spencer Date: Wed, 2 Dec 2026 23:05:18 +0000 Subject: [PATCH 3/4] fix(docs): add blank line before for MDX parsing Signed-off-by: Greg Spencer --- docs/site/src/content/docs/guides/extending-the-agent-sdk.mdx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/site/src/content/docs/guides/extending-the-agent-sdk.mdx b/docs/site/src/content/docs/guides/extending-the-agent-sdk.mdx index 3a9f4781fe..adfa12d81c 100644 --- a/docs/site/src/content/docs/guides/extending-the-agent-sdk.mdx +++ b/docs/site/src/content/docs/guides/extending-the-agent-sdk.mdx @@ -282,7 +282,8 @@ class CustomFormatFactory implements InferenceFormatFactory { - **TypeScript**: `generate()` is concrete; override `generateBaseRules()`, `renderCatalogInstructions(catalog)`, and `renderExamples(catalog)`. - **Python**: `generate()` is `@final`; override `generate_base_rules()`, `generate_catalog_instructions()`, and `generate_examples()`. - **Dart**: `generate()` is `@nonVirtual`; override `generateBaseRules()`, `generateCatalogInstructions()`, and `generateExamples()`. - + + ## Transform catalogs and define macros From 09f3f10f780b5586c275d080a7f0aff574273e8b Mon Sep 17 00:00:00 2001 From: Greg Spencer Date: Thu, 3 Dec 2026 16:57:32 +0000 Subject: [PATCH 4/4] fix(python,docs): export RPC aliases/DEFAULT_EXPRESS_PROGRESSIVE_KEYS and fix guide snippets Signed-off-by: Greg Spencer --- .../docs/guides/extending-the-agent-sdk.mdx | 70 ++++++++++--------- python/a2ui_agent/src/a2ui/agent/__init__.py | 16 ++++- python/a2ui_agent/tests/test_agent_facade.py | 17 ++++- 3 files changed, 69 insertions(+), 34 deletions(-) diff --git a/docs/site/src/content/docs/guides/extending-the-agent-sdk.mdx b/docs/site/src/content/docs/guides/extending-the-agent-sdk.mdx index adfa12d81c..30480beaba 100644 --- a/docs/site/src/content/docs/guides/extending-the-agent-sdk.mdx +++ b/docs/site/src/content/docs/guides/extending-the-agent-sdk.mdx @@ -89,7 +89,7 @@ import { } from '@a2ui/agent'; // Implement Parser (compile, decompile, wrap, unwrap, etc.) for your syntax. -declare class CustomParser extends Parser {} +declare function createCustomParser(catalogs: CatalogApi[]): Parser; declare const catalogs: CatalogApi[]; class CustomPromptGenerator extends PromptGenerator { @@ -114,7 +114,7 @@ class CustomFormatFactory implements InferenceFormatFactory { ): InferenceFormat { return { promptGenerator: new CustomPromptGenerator(catalogs), - createParser: () => new CustomParser(catalogs), + createParser: () => createCustomParser(catalogs), }; } } @@ -126,7 +126,8 @@ const processor = new A2uiRequestProcessor(catalogs, undefined, new CustomFormat ```python -from collections.abc import Sequence +from collections.abc import Mapping, Sequence +from typing import Any from a2ui.agent import ( A2uiRequestProcessor, @@ -134,6 +135,7 @@ from a2ui.agent import ( InferenceFormatFactory, Parser, PromptGenerator, + RawResponsePart, ) from a2ui.core import CatalogApi from a2ui.core.basic_catalog import BasicCatalog @@ -150,19 +152,21 @@ class CustomParser(Parser): def catalogs(self) -> list[CatalogApi]: return list(self._catalogs) - def has_format_content(self, response: str) -> bool: + def has_format_content(self, content: str, complete: bool = False) -> bool: raise NotImplementedError() - def wrap(self, content: str) -> str: + def wrap(self, blocks: Sequence[RawResponsePart]) -> str: raise NotImplementedError() - def unwrap(self, response: str) -> str: + def unwrap(self, content: str) -> list[RawResponsePart]: raise NotImplementedError() - def compile(self, block: str) -> list[AgentToRendererMessage]: + def compile( + self, format_content: str, *, is_final: bool = True + ) -> Sequence[AgentToRendererMessage | Mapping[str, Any]]: raise NotImplementedError() - def decompile(self, messages: Sequence[AgentToRendererMessage]) -> str: + def decompile(self, a2ui_payload: Sequence[AgentToRendererMessage]) -> str: raise NotImplementedError() @@ -186,7 +190,12 @@ class CustomPromptGenerator(PromptGenerator): targets = [catalog] if catalog is not None else self._catalogs return "\n".join(f"Catalog: {c.catalog_id}" for c in targets) - def generate_examples(self) -> str: + def generate_examples( + self, + catalog: CatalogApi | None = None, + validate: bool = False, + ) -> str: + del catalog, validate return "" @@ -240,7 +249,7 @@ class CustomPromptGenerator extends PromptGenerator { } @override - String generateExamples() => ''; + String generateExamples({CatalogApi? catalog}) => ''; } class CustomFormat implements InferenceFormat { @@ -268,7 +277,7 @@ class CustomFormatFactory implements InferenceFormatFactory { // Wire the factory into A2uiRequestProcessor: // final processor = A2uiRequestProcessor( -// catalogs, +// activeCatalogs: catalogs, // formatFactory: const CustomFormatFactory(), // ); ``` @@ -295,8 +304,8 @@ For server-side composite components authored with `@macro` and expanded with `M The A2UI Agent SDK stays intentionally agnostic to LLM client libraries, network transports, and credentials: -- **Standard LLM providers** (Gemini, OpenAI, Anthropic, local models, or framework runtimes such as ADK and LangGraph) integrate outside `a2ui-agent-sdk` by feeding `processor.prompt_snippet` into your model call and passing streamed text chunks into `processor.open_stream()` or `processor.parse_response()`. See [How to Integrate A2UI into an Agent](../agent-integration/). -- **Specialized model extensions** (such as custom planner or decision-model packages) define narrow async callable protocols in their own extension packages and validate emitted `AgentToRendererMessage` payloads through `RendererState.commit` or `validate_payload`. +- **Standard LLM providers** (Gemini, OpenAI, Anthropic, local models, or framework runtimes such as ADK and LangGraph) integrate outside `a2ui-agent-sdk` by feeding `processor.prompt_snippet` into your model call and feeding streamed text chunks into the `ResponseStream` returned by `processor.open_stream()` (or passing a complete response to `processor.parse_response()`). The snake_case names below follow the Python SDK; TypeScript and Dart expose camelCase equivalents. See [How to Integrate A2UI into an Agent](../agent-integration/). +- **Specialized model extensions** (such as custom planner or decision-model packages) define narrow async callable protocols in their own extension packages and validate emitted `AgentToRendererMessage` payloads through `RendererState.commit` or `validate_payload` (`validatePayload` in TypeScript and Dart). ## Validate and commit messages from a custom loop @@ -307,7 +316,6 @@ from a2ui.agent import ( RendererState, to_message_dicts, to_message_models, - validate_payload, ) from a2ui.core.basic_catalog import BasicCatalog from a2ui.core.schema import ProtocolVersion @@ -315,26 +323,24 @@ from a2ui.core.schema import ProtocolVersion catalogs = [BasicCatalog(ProtocolVersion.V1_0)] state = RendererState(catalogs) -candidate_messages = list( - to_message_models([ - { - "version": "1.0", - "createSurface": { - "surfaceId": "status_1", - "catalogId": catalogs[0].catalog_id, - }, +candidate_messages = to_message_models([ + { + "version": "1.0", + "createSurface": { + "surfaceId": "status_1", + "catalogId": catalogs[0].catalog_id, }, - { - "version": "1.0", - "updateComponents": { - "surfaceId": "status_1", - "components": [ - {"id": "root", "component": "Text", "text": "Ready"}, - ], - }, + }, + { + "version": "1.0", + "updateComponents": { + "surfaceId": "status_1", + "components": [ + {"id": "root", "component": "Text", "text": "Ready"}, + ], }, - ]) -) + }, +]) state.commit(candidate_messages) wire_payload = to_message_dicts(candidate_messages) diff --git a/python/a2ui_agent/src/a2ui/agent/__init__.py b/python/a2ui_agent/src/a2ui/agent/__init__.py index 31603e9d40..24228151f8 100644 --- a/python/a2ui_agent/src/a2ui/agent/__init__.py +++ b/python/a2ui_agent/src/a2ui/agent/__init__.py @@ -41,7 +41,10 @@ DirectJsonDecompiler, DirectJsonResponseStream, ) -from a2ui.inference_formats.express import ExpressDecompiler +from a2ui.inference_formats.express import ( + DEFAULT_EXPRESS_PROGRESSIVE_KEYS, + ExpressDecompiler, +) from a2ui.parser import ( A2uiCompilationError, A2uiCompilationParseError, @@ -68,9 +71,14 @@ ) from a2ui.prompt import PromptGenerator, assemble_instructions from a2ui.rpc import ( + ActionCallback, DEFAULT_RENDERER_CALL_TIMEOUT, + ErrorCallback, ProcessResult, RendererFunctionCalls, + RendererFunctionResponseCallback, + RendererFunctionResponseInput, + RendererToAgentMessageInput, RendererToAgentMessageProcessor, ) from a2ui.skill import Skill, SkillGenerator, SkillSet @@ -90,16 +98,19 @@ "A2uiGenerator", "A2uiPart", "A2uiRequestProcessor", + "ActionCallback", "CatalogConfig", "CatalogProvider", "CatalogTransformer", "ComponentPruningTransformer", + "DEFAULT_EXPRESS_PROGRESSIVE_KEYS", "DEFAULT_RENDERER_CALL_TIMEOUT", "DirectJsonDecompiler", "DirectJsonFormat", "DirectJsonFormatFactory", "DirectJsonParser", "DirectJsonResponseStream", + "ErrorCallback", "ErrorPart", "ExpressDecompiler", "ExpressFormat", @@ -118,7 +129,10 @@ "RawA2uiPart", "RawResponsePart", "RendererFunctionCalls", + "RendererFunctionResponseCallback", + "RendererFunctionResponseInput", "RendererState", + "RendererToAgentMessageInput", "RendererToAgentMessageProcessor", "ResponsePart", "ResponseStream", diff --git a/python/a2ui_agent/tests/test_agent_facade.py b/python/a2ui_agent/tests/test_agent_facade.py index 1e435c6d5e..f9b2ec36f6 100644 --- a/python/a2ui_agent/tests/test_agent_facade.py +++ b/python/a2ui_agent/tests/test_agent_facade.py @@ -25,6 +25,7 @@ DirectJsonResponseStream, ) from a2ui.inference_formats.express import ( + DEFAULT_EXPRESS_PROGRESSIVE_KEYS, ExpressDecompiler, ExpressFormatFactory, ExpressResponseStream, @@ -45,7 +46,15 @@ CatalogProvider, ) from a2ui.prompt import PromptGenerator -from a2ui.rpc import RendererFunctionCalls, RendererToAgentMessageProcessor +from a2ui.rpc import ( + ActionCallback, + ErrorCallback, + RendererFunctionCalls, + RendererFunctionResponseCallback, + RendererFunctionResponseInput, + RendererToAgentMessageInput, + RendererToAgentMessageProcessor, +) from a2ui.skill import SkillGenerator from a2ui.transformers import MacroExpander, macro from a2ui.utils import RendererState, validate_payload @@ -70,12 +79,15 @@ def test_agent_facade_exports_core_contracts_by_identity() -> None: "A2uiCompilationValidationError": A2uiCompilationValidationError, "A2uiGenerator": A2uiGenerator, "A2uiRequestProcessor": A2uiRequestProcessor, + "ActionCallback": ActionCallback, "CatalogConfig": CatalogConfig, "CatalogProvider": CatalogProvider, "CatalogTransformer": CatalogTransformer, + "DEFAULT_EXPRESS_PROGRESSIVE_KEYS": DEFAULT_EXPRESS_PROGRESSIVE_KEYS, "DirectJsonDecompiler": DirectJsonDecompiler, "DirectJsonFormatFactory": DirectJsonFormatFactory, "DirectJsonResponseStream": DirectJsonResponseStream, + "ErrorCallback": ErrorCallback, "ExpressDecompiler": ExpressDecompiler, "ExpressFormatFactory": ExpressFormatFactory, "ExpressResponseStream": ExpressResponseStream, @@ -85,7 +97,10 @@ def test_agent_facade_exports_core_contracts_by_identity() -> None: "Parser": Parser, "PromptGenerator": PromptGenerator, "RendererFunctionCalls": RendererFunctionCalls, + "RendererFunctionResponseCallback": RendererFunctionResponseCallback, + "RendererFunctionResponseInput": RendererFunctionResponseInput, "RendererState": RendererState, + "RendererToAgentMessageInput": RendererToAgentMessageInput, "RendererToAgentMessageProcessor": RendererToAgentMessageProcessor, "ResponseStream": ResponseStream, "SkillGenerator": SkillGenerator,