Repository navigation
feat(python,docs): add a2ui.agent facade package and Agent SDK extension guide - #4549
gspencergoog wants to merge 3 commits into
Conversation
…ion guide Signed-off-by: Greg Spencer <gspencer@google.com>
3374bf5 to
e04b414
Compare
There was a problem hiding this comment.
Code Review
This pull request introduces a unified a2ui.agent public facade package for the Python Agent SDK, complete with unit tests, and adds a comprehensive documentation guide on "How to Extend the A2UI Agent SDK" with examples in TypeScript, Python, and Dart. The review feedback points out critical issues in the documentation's code snippets where abstract methods are not implemented for Python's CustomParser and CustomPromptGenerator, as well as Dart's CustomPromptGenerator, which would lead to runtime TypeErrors or compilation failures.
…ide snippets Signed-off-by: Greg Spencer <gspencer@google.com>
Signed-off-by: Greg Spencer <gspencer@google.com>
📖 Docs Site Preview DeployedPreview URL: https://a2ui.org/pr-preview/pr-4549/ Modified pages in this PR: Built from commit |
| def catalogs(self) -> list[CatalogApi]: | ||
| return list(self._catalogs) | ||
|
|
||
| def has_format_content(self, response: str) -> bool: |
There was a problem hiding this comment.
All three language tabs in the custom inference format example currently fail compilation or type-checking when copied into a project. In Python, five of the CustomParser and CustomPromptGenerator.generate_examples overrides mismatch their base signatures (failing mypy --strict and raising TypeError at runtime when Parser._apply_block passes is_final=, parse_response iterates RawResponsePart, or SkillGenerator/assemble_instructions passes catalog=). In Dart, generateExamples() omits {CatalogApi? catalog} and the commented A2uiRequestProcessor(catalogs, ...) omits the required named activeCatalogs: parameter, while TypeScript's declare class CustomParser extends Parser {} fails tsc (TS2655 and TS2554).
Additional details
Note that generate_examples (Python, python/a2ui_agent/src/a2ui/prompt/generator.py:68) and generateExamples (Dart, dart/a2ui_agent/lib/src/prompt/generator.dart:54) are concrete methods defaulting to an empty string—not abstract—so they can either be omitted or written with their full base signatures.
1. Python (lines 129–191) — passes uv run mypy --strict:
from collections.abc import Mapping, Sequence
from typing import Any
from a2ui.agent import (
A2uiRequestProcessor,
InferenceFormat,
InferenceFormatFactory,
Parser,
PromptGenerator,
RawResponsePart,
)
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."""
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, content: str, complete: bool = False) -> bool:
raise NotImplementedError()
def wrap(self, blocks: Sequence[RawResponsePart]) -> str:
raise NotImplementedError()
def unwrap(self, content: str) -> list[RawResponsePart]:
raise NotImplementedError()
def compile(
self, format_content: str, *, is_final: bool = True
) -> Sequence[AgentToRendererMessage | Mapping[str, Any]]:
raise NotImplementedError()
def decompile(self, a2ui_payload: Sequence[AgentToRendererMessage]) -> str:
raise NotImplementedError()And for CustomPromptGenerator.generate_examples (lines 189–190), either omit it or match the base signature:
def generate_examples(
self,
catalog: CatalogApi | None = None,
validate: bool = False,
) -> str:
del catalog, validate
return ""2. Dart (lines 242–244 and 270–273) (dart/a2ui_agent/lib/src/prompt/generator.dart:54, dart/a2ui_agent/lib/src/processor/processor.dart:72):
@override
- String generateExamples() => '';
+ String generateExamples({CatalogApi? catalog}) => ''; // final processor = A2uiRequestProcessor(
-// catalogs,
+// activeCatalogs: catalogs,
// formatFactory: const CustomFormatFactory(),
// );3. TypeScript (lines 92 and 117) (typescript/agents/a2ui_agent/src/parser/parser.ts:63-107 declares 6 abstract members and no constructor):
-declare class CustomParser extends Parser {}
+declare function createCustomParser(catalogs: CatalogApi[]): Parser;- createParser: () => new CustomParser(catalogs),
+ createParser: () => createCustomParser(catalogs),🤖 Agent-generated
| from a2ui.rpc import ( | ||
| DEFAULT_RENDERER_CALL_TIMEOUT, | ||
| ProcessResult, | ||
| RendererFunctionCalls, | ||
| RendererToAgentMessageProcessor, | ||
| ) |
There was a problem hiding this comment.
Extensions following the guide's single-entry-point rule (a2ui.agent only, banning other a2ui.* agent submodules in Ruff) currently cannot type RendererToAgentMessageProcessor callbacks or pass DEFAULT_EXPRESS_PROGRESSIVE_KEYS to ExpressFormatFactory without reaching back into internal submodules. Re-exporting the companion RPC type aliases from a2ui.rpc and DEFAULT_EXPRESS_PROGRESSIVE_KEYS from a2ui.inference_formats.express closes that gap.
Additional details
Specifically, RendererToAgentMessageProcessor.__init__ and process_message (python/a2ui_agent/src/a2ui/rpc/processor.py:38-62) use these a2ui.rpc type aliases in their public signatures, and ExpressFormatFactory accepts DEFAULT_EXPRESS_PROGRESSIVE_KEYS (which @a2ui/agent exports as DEFAULT_EXPRESS_PROGRESSIVE_KEYS and package:a2ui_agent/a2ui_agent.dart exports as defaultExpressProgressiveKeys):
- From
a2ui.rpc:ActionCallback,ErrorCallback,RendererFunctionResponseCallback,RendererFunctionResponseInput,RendererToAgentMessageInput - From
a2ui.inference_formats.express:DEFAULT_EXPRESS_PROGRESSIVE_KEYS
None of these originate from a2ui.core, so exporting them keeps test_agent_facade_does_not_reexport_a2ui_core green. (Keeping DirectJsonPromptGenerator/ExpressPromptGenerator unexported per #3568 makes sense.)
| from a2ui.rpc import ( | |
| DEFAULT_RENDERER_CALL_TIMEOUT, | |
| ProcessResult, | |
| RendererFunctionCalls, | |
| RendererToAgentMessageProcessor, | |
| ) | |
| from a2ui.rpc import ( | |
| ActionCallback, | |
| DEFAULT_RENDERER_CALL_TIMEOUT, | |
| ErrorCallback, | |
| ProcessResult, | |
| RendererFunctionCalls, | |
| RendererFunctionResponseCallback, | |
| RendererFunctionResponseInput, | |
| RendererToAgentMessageInput, | |
| RendererToAgentMessageProcessor, | |
| ) |
(Also add DEFAULT_EXPRESS_PROGRESSIVE_KEYS to the a2ui.inference_formats.express import and include all six names in __all__ and test_agent_facade.py.)
🤖 Agent-generated
|
|
||
| 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/). |
There was a problem hiding this comment.
A couple of small details in the lower sections of the guide could trip up readers: processor.open_stream() does not accept text chunks directly (callers feed chunks to the returned ResponseStream.feed(chunk)), and processor.parse_response() expects the complete response text. In the validation snippet right below, validate_payload is imported without being called and list(...) around to_message_models(...) is redundant.
Additional details
Minor cleanups to batch together:
- Line 298: Rephrase
passing streamed text chunks into processor.open_stream() or processor.parse_response()tofeeding streamed text chunks into the ResponseStream returned by processor.open_stream() (or passing a complete response to processor.parse_response()), and optionally note that these snake_case names andRendererState.commiton line 299 are Python examples (TypeScript/Dart use camelCase andvalidatePayload, as noted in the table on line 18). - Lines 310 & 318: Drop unused
validate_payloadfrom the import block (or call it inside the snippet) to avoid anF401lint warning, and simplifycandidate_messages = to_message_models([...])(to_message_modelsalready returnslist[AgentToRendererMessage]). - PR description: Consider adding the standard
**Live Preview**: https://a2ui.org/pr-preview/pr-4549/section per.agents/skills/public-documentation/SKILL.mdso reviewers can inspect the rendered guide directly.
🤖 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.
Thanks for structuring this as an a2ui.agent package! Right now this still leaves all the legacy top-level subpackages (a2ui.processor, a2ui.parser, a2ui.rpc, etc.) public alongside it, so callers and IDEs have two ways to import everything—is the plan to follow up by moving those implementations behind _-prefixed modules under a2ui.agent (with DeprecationWarning shims or removal) and migrating our docs and sibling packages so there's just one canonical way to import the Agent SDK?
Additional details
Not a blocker for this PR—just want to align on the direction so we don't end up maintaining parallel public import paths long-term:
- Moving the internal subpackages under
a2ui/agent/_...(while keeping intentional separate facades likea2ui.constants,a2ui.builder.v1_0, anda2ui.agent.experimental) lets Pyright (reportPrivateImportUsage), Ruff (PLC2701), and IDE auto-import enforce the single entry point automatically, instead of asking downstream authors to maintain Ruffbanned-apilists. - Legacy paths (
a2ui.processor,a2ui.parser,a2ui.prompt,a2ui.rpc, etc.) can either stay as thinDeprecationWarningshims (matchinga2ui.inference_strategy) or be dropped in a breaking0.xrelease, alongside migrating the legacy imports indocs/site/(~31 imports) anda2ui_a2a/a2ui_adk(~62 imports).
🤖 Agent-generated
Motivation
Extension packages targeting
a2ui-agent-sdkpreviously had to deep-import symbols across internal submodules (a2ui.processor,a2ui.prompt,a2ui.parser,a2ui.inference_format,a2ui.inference_formats.*,a2ui.rpc,a2ui.skill,a2ui.transformers,a2ui.utils). This PR introduces a single public facade package (a2ui.agent) matching@a2ui/agentin TypeScript andpackage:a2ui_agent/a2ui_agent.dartin Dart, along with a developer guide for extending the Agent SDK.Replaces #4543 (which was auto-closed by GitHub when its base branch
feat/modular-agent-seamswas deleted on merge of #4471) and incorporates all 9 review comments from@jacobsimionatoon #4543.Summary of Changes
a2ui-agent-sdk):a2ui.agentpublic facade package (python/a2ui_agent/src/a2ui/agent/__init__.py) re-exporting core coordination, inference format, compilation error, decompiler/stream, catalog transformer, macro, validation, skill generation, and RPC contracts from a single entry point (without wideninga2ui.inference_formats).python/a2ui_agent/tests/test_agent_facade.pyverifying package structure, sorted deduplicated__all__, exact match against public attributes, identity against defining submodules, and noa2ui.corere-export leaks.python/a2ui_agent/CHANGELOG.md.docs/site/):How to Extend the A2UI Agent SDK(docs/site/src/content/docs/guides/extending-the-agent-sdk.mdx), registered it indocs/site/astro.config.mjsanddocs/site/llms.txt, and linked to it fromdocs/site/src/content/docs/concepts/inference-formats.mdxanddocs/site/src/content/docs/guides/agent-integration.mdx.Testing
uv run --directory python/a2ui_agent pytest tests/test_agent_facade.py(3 passed)uv run --directory python/a2ui_agent mypy --explicit-package-bases --namespace-packages -p a2ui.agent(0 issues)python3 scripts/fix_licenses.py --check(passed)pyinkandprettierformatting applied