Skip to content

feat(decision): add minimal shared decision kernel, macro placement hints, and CI barrel guard - #4320

Closed
gspencergoog wants to merge 12 commits into
mainfrom
feat/decision-kernel-standalone
Closed

gspencergoog wants to merge 12 commits into
mainfrom
feat/decision-kernel-standalone

Conversation

@gspencergoog

Copy link
Copy Markdown
Collaborator

Summary

Adds a minimal shared experimental decision-model kernel (a2ui.inference_formats.experimental.decision), @macro parent/child placement hints (allowed_parents / allowed_children), optional a2ui-agent-sdk[decision] (httpx) gating, and CI barrel isolation checks directly on top of main.

Reviewer Focus

  • python/a2ui_agent/src/a2ui/inference_formats/experimental/decision/backends.py: DecisionBackend protocol, JevHttpBackend (native Jev, /v1/systemone, and /v1beta/decisions), StepZeroLogprobBackend (shared monotonic deadline), DeterministicMockBackend, per-loop _HttpClientOwner, and create_decision_backend vendor-key scoping.
  • python/a2ui_agent/src/a2ui/inference_formats/experimental/decision/transport.py: build_inference_catalogs and lower_for_transport (macro lowering and transactional RendererState topology validation).
  • python/a2ui_agent/src/a2ui/inference_formats/experimental/decision/payload_inspector.py: RFC 6901 pointer extraction, exclusion filtering, and camelCase/kebab-case secret redaction.
  • .github/workflows/python_ci.yml and python/a2ui_agent/pyproject.toml: optional decision extra (httpx>=0.27.0) and isolated import check verifying public barrels stay free of experimental decision/RPC modules and httpx.

Changes

  • Added allowed_parents and allowed_children parameters to @macro in python/a2ui_agent/src/a2ui/transformers/macros/macro.py, emitting allowedParents and allowedChildren schema metadata and rejecting bare strings.
  • Added the trimmed shared experimental kernel under python/a2ui_agent/src/a2ui/inference_formats/experimental/decision/:
    • models.py: DecisionBatch, DecisionQuestion, DecisionAnswer, DecisionDistribution, MediaInputPart, TextInputPart, ActionSpec, ExpressSurfaceSpec, ComponentNodeSpec, ComponentSlot, coerce_decision_payload, and DecisionBackendError.
    • backends.py and calibration_profiles.json: HTTP, Step-0, and mock decision backends with temperature calibration and optional httpx gating.
    • catalog_graph.py: CatalogDecisionGraph extracting catalog component slots and parent/child relationships.
    • payload_inspector.py and semantic_types.py: RFC 6901 JSON Pointer inspection, semantic scalar/array classification, and secret pointer redaction.
    • transport.py: build_inference_catalogs and lower_for_transport.
  • Added unit tests in python/a2ui_agent/tests/decision/test_decision_kernel.py, python/a2ui_agent/tests/decision/test_transport_and_core_extensions.py, and python/a2ui_agent/tests/test_experimental_import_isolation.py.
  • Updated .github/workflows/python_ci.yml, python/a2ui_agent/pyproject.toml, uv.lock, and python/a2ui_agent/CHANGELOG.md.

Impact & Risks

  • Public a2ui.inference_formats, a2ui.parser, a2ui.processor, and a2ui.rpc barrels do not import a2ui.inference_formats.experimental.decision or httpx; verified by the isolated CI check.
  • All new public entry points in a2ui.inference_formats.experimental.decision are decorated with @experimental.
  • @macro keeps backwards-compatible defaults (allowed_parents=(), allowed_children=()).

Testing

  • uv run pyink --check python/a2ui_agent
  • uv run --all-packages mypy . and uv run mypy --follow-imports=silent python/a2ui_agent/src/a2ui/inference_formats/experimental/decision/*.py
  • A2UI_SUPPRESS_EXPERIMENTAL_FEATURE_WARNINGS=1 uv run pytest python/a2ui_agent/tests/decision/ python/a2ui_agent/tests/test_experimental_import_isolation.py python/a2ui_agent/tests/test_framework_agnostic.py -q
  • Isolated barrel check from .github/workflows/python_ci.yml (uv run --isolated --no-project --with ./python/a2ui_core --with ./python/a2ui_agent python -c ...).

@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 adds a shared experimental decision-model kernel to the A2UI agent SDK, introducing decision backends, a catalog decision graph, a payload pointer inspector, and transport lowering. It also extends the @macro decorator with allowed_parents and allowed_children parameters. The review feedback recommends using isinstance(..., Awaitable) instead of asyncio.iscoroutine to support all awaitable types, handling task cancellation on asyncio.gather failures in StepZeroLogprobBackend to avoid leaking API requests, and removing the unused _function_return_type helper function.

@gspencergoog
gspencergoog added this pull request to stack #4324 November 20, 2026 01:47
…ints, and CI barrel guard

Signed-off-by: Greg Spencer <gspencer@google.com>
…ast import

Signed-off-by: Greg Spencer <gspencer@google.com>
@gspencergoog
gspencergoog marked this pull request as ready for review November 24, 2026 01:47
…l-standalone

# Conflicts:
#	python/a2ui_agent/CHANGELOG.md

@polina-c polina-c left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR adds 6,275 lines, and nothing in the repo calls the new kernel yet. That makes the API hard to review: I can't tell whether DecisionBatch, PointerSummary or ExpressSurfaceSpec have the right shape without the code that uses them. I ran the tests (all pass) and probed the code with small scripts. The inline comments cover the bugs I could reproduce. A few points apply to the whole PR:

  1. Several parts refer to code that is not in this PR or in main. The docstrings at backends.py#L588 and backends.py#L713 say DecisionSynthesizer.synthesize_sync calls aclose_current_loop(), but there is no DecisionSynthesizer, so nothing closes the per-loop clients (see the inline comment on L758). models.py#L408 names a DecisionTask, models.py#L65 and semantic_types.py#L15 an "archetype grammar", and models.py#L558 "cascade routing". test_experimental_import_isolation.py#L28-L40 forbids imports of 11 modules (archetypes, layout_planner, synthesizer and others) that don't exist. The fallback heuristics in payload_inspector.py#L30-L108 and payload_inspector.py#L156-L202 only run for a PointerSummary built without semantic_type and label, and nothing in the repo builds one that way.
  2. Test coverage is low for this much code. With pytest-cov on tests/decision/: backends.py 57%, payload_inspector.py 40%, semantic_types.py 59%. Most tests check several unrelated things at once (for example test_macro_allowed_parents_literal_primitive_and_transport_lowering), and one test file per module would make gaps easier to see. None of the bugs in the inline comments is covered by a test.

Smaller issues I didn't comment on inline:

  1. StepZeroLogprobBackend applies the temperature inside the softmax but returns the logit margin from before scaling (backends.py#L209, used at backends.py#L1769-L1776), while the Jev path divides the margin by the temperature (backends.py#L1041). At T=2 the two backends return the same probabilities with margins that differ by a factor of 2.
  2. _normalize_probabilities (backends.py#L183-L186) renormalizes only when the total mass, including keys that aren't candidates, passes 1. {"a": 0.3, "b": 0.3, "x": 0.40} gives a=0.3, b=0.3, but changing only x to 0.41 gives a=0.5, b=0.5.
  3. In semantic_types.py, "min" maps to minutes (semantic_types.py#L256), so temp_min: 12.5 and priceMin: 100 classify as durations. _detect_bounded_number (semantic_types.py#L803-L823) doesn't check that the value is inside the bounds, so {"offset": 100, "limit": 25} gives offset as bounded 0 to 25.
  4. exclude in inspect_pointers removes an array column from element_keys but keeps it in sample_pointers: with exclude={"/items/photo"}, /items still has sample_pointers=("/items/0/photo",).
  5. mutable_paths={"/"} turns off secret redaction for the whole payload, and a mutable parent such as /account exempts /account/apiKey. In RFC 6901, "/" is the empty-string key and "" is the root.
  6. _escape_pointer_segment (payload_inspector.py#L205-L212) duplicates pointer handling that a2ui_core already has in DataModel (data_model.py#L41-L60), and the two disagree on empty keys: the inspector emits / for {"": ...}, which DataModel reads as the root. A public helper in a2ui_core would give both the same behavior.

🤖 Agent-generated

Comment thread python/a2ui_agent/CHANGELOG.md Resolved
@polina-c

Copy link
Copy Markdown
Collaborator

What is the path forward to integrate this new code with the existing A2UI API? How will the API change? Maybe a 1-page design doc is helpful here.

@gspencergoog

Copy link
Copy Markdown
Collaborator Author

What is the path forward to integrate this new code with the existing A2UI API? How will the API change? Maybe a 1-page design doc is helpful here.

Good question. The whole stack is additive and opt-in, with no breaking changes to the v1.0 wire protocol, client renderers, CatalogApi, A2uiRequestProcessor, or RendererToAgentMessageProcessor.

Here's how the bot describes it:

Right now, all new modules live under a2ui.inference_formats.experimental.* and a2ui.rpc.experimental.decision (decorated with @experimental, excluded from stable barrels, with httpx behind the a2ui-agent-sdk[decision] extra). The only changes on stable APIs are two optional kwargs: allowed_parents/allowed_children on @macro (in this PR) and allowed_a2ui_tool_names=() on A2uiPartConverter/A2uiEventConverter (#4322).

Each track plugs into an existing boundary and emits standard v1.0 AgentToRendererMessage lists or AgentFunction callables. As individual tracks prove out in evals and the playground (#4325), they can graduate out of experimental into a2ui.decision / a2ui.rpc.decision with optional convenience hooks on A2uiInstruction and a2ui.adk, while unused tracks can be dropped without breaking callers.

One-Pager

Integrating Decision Models with the A2UI API

Summary

The 7-PR decision-model stack (#4320, #4321, #4322, #4323, #4342, #4344, #4325) adds fast binary and multiple-choice classification alongside generative inference formats (ExpressFormat, DirectJsonFormat).

Integration is additive and opt-in. The v1.0 wire protocol, client renderers, CatalogApi, A2uiRequestProcessor, and RendererToAgentMessageProcessor do not break or change their defaults. Each decision module plugs into an existing A2UI boundary and emits standard validated AgentToRendererMessage lists or AgentFunction handlers.

Architecture and Integration Seams

Decision models sit around the existing agent turn rather than replacing it:

flowchart LR
  User["User prompt or tool output"] --> Router["DecisionCascadeRouter (#4321)"]
  Router -->|"TEXT_ONLY"| TextLLM["Text LLM"]
  Router -->|"TEMPLATE"| Wire["Validated v1.0 AgentToRendererMessage"]
  Router -->|"PRUNED_EXPRESS (pruned CatalogApi)"| Proc["A2uiRequestProcessor / ExpressFormat"]
  Proc --> Wire
  TextLLM -->|"Optional post-turn"| Prose["ProseSurfaceUpgrader (#4344)"]
  Prose --> Wire
  Tool["ADK Tool Result"] -->|"after_tool_callback"| Binder["ToolPointerBinder (#4322)"]
  Binder -->|"A2uiPartConverter (allowlist)"| Wire
  Gated["GatedTemplateEvaluator (#4342)"] -->|"Prunes @metadata.extensions"| Wire
  Client["Renderer callAgentFunction"] --> RPC["RendererToAgentMessageProcessor"]
  RPC -->|"Registered AgentFunction"| Pred["Decision Predicates (#4323)"]
Loading
PR Experimental module How it connects to existing A2UI APIs Change to stable API today
#4320 a2ui.inference_formats.experimental.decision Reads CatalogApi schemas and lowers output via RendererState. Optional allowed_parents and allowed_children kwargs on @macro.
#4321 ...experimental.decision_cascade Runs before A2uiRequestProcessor, passing a pruned CatalogApi subset on the generative path. None.
#4322 ...experimental.decision_binder + a2ui.adk Hooks into ADK after_tool_callback; emits A2UI via A2uiPartConverter. Lazy make_adk_after_tool_callback; optional allowed_a2ui_tool_names=() on A2uiPartConverter and A2uiEventConverter.
#4323 a2ui.rpc.experimental.decision Returns standard AgentFunction callables that register on a Catalog and run in RendererToAgentMessageProcessor. None.
#4342 ...experimental.decision_gated_templates Reads a2ui_gate and a2ui_variant from v1.0 @metadata.extensions, prunes components, and strips those keys before lowering. None.
#4344 ...experimental.decision_prose_upgrade Runs after a text turn and compiles matching prose into an ExpressCompiler surface, or abstains. None.
#4325 samples/agent/adk/decision_playground Standalone sample agent and opt-in ?app=playground view in the Lit shell. None.

How the API Changes Over Time

Phase 1: Experimental Isolation (Current Stack)

All decision code lives under a2ui.inference_formats.experimental.* and a2ui.rpc.experimental.decision, decorated with @experimental. Public barrels do not import these modules, and CI enforces this isolation (test_experimental_import_isolation.py). The httpx dependency is optional under a2ui-agent-sdk[decision].

Only two backwards-compatible kwargs touch stable APIs:

# 1. Optional hierarchy hints on @macro (PR #4320)
@macro(allowed_parents=("Column", "Card"), allowed_children=("Text",))
def IncidentAlertCard(...): ...

# 2. Opt-in tool allowlist on ADK converters (PR #4322)
converter = A2uiPartConverter(
    a2ui_processor=processor,
    allowed_a2ui_tool_names=("get_host_health",),
)

Phase 2: Field Validation and Consolidation

Using the playground (#4325) and eval suites, we will measure latency, abstention accuracy, and developer ergonomics across the five tracks. Once track boundaries settle, we will move shared helpers (redact_data_model, Express-with-data lowering, and wire enums) into the shared kernel. Tracks that do not pull their weight can be dropped without affecting stable callers.

Phase 3: Promotion to Stable APIs

Graduated capabilities will move out of experimental into top-level namespaces (a2ui.decision and a2ui.rpc.decision) while keeping the core A2uiRequestProcessor and CatalogApi contracts intact. Likely convenience additions on existing facades include:

  • A2uiInstruction accepting a per-turn catalog provider (or router hook) so DecisionCascadeRouter can prune catalogs dynamically without manual ADK wiring.
  • Optional helper methods or factories on a2ui.adk for wiring ProseSurfaceUpgrader (after_model_callback) and GatedTemplateEvaluator alongside make_adk_after_tool_callback.
  • Standardizing a2ui_gate and a2ui_variant extension keys in the v1.0 catalog specification only if gated templates graduate.

What Does Not Change

  • Decision tracks emit standard A2UI v1.0 wire messages (createSurface, updateComponents, updateDataModel, agentFunctionResponse), so client renderers require no changes.
  • Existing A2uiRequestProcessor and ExpressFormat agents keep working identically without installing [decision] or configuring a DecisionBackend.
  • a2ui-agent-sdk stays framework-neutral with zero google.adk, a2a, or google.genai imports; ADK-specific glue stays in a2ui-adk.

@polina-c

Copy link
Copy Markdown
Collaborator

Thank you.

Can you craft 1-2 paragraph of documentation for end users that describes in a simple way:

  1. This feature
  2. How to add it to an existing a2ui app

@gspencergoog

Copy link
Copy Markdown
Collaborator Author

Thank you.

Can you craft 1-2 paragraph of documentation for end users that describes in a simple way:

  1. This feature
  2. How to add it to an existing a2ui app

Sure, here's a feature guide to the different ideas implemented in the stack, along with how to run the playground app locally, and how to add each one to an existing Python ADK app. Is that what you wanted to see?

User Guide

A2UI Decision Models: Feature Guide and Integration Walkthrough

Decision models evaluate typed yes/no, choice, and score questions over shared context in a single forward pass. They return calibrated probabilities with zero output tokens, which keeps latency under a few hundred milliseconds.

This seven-PR stack (PR #4320 through PR #4323, PR #4342, PR #4344, and PR #4325) adds a shared decision kernel, five opt-in capabilities, and an interactive playground to the Python A2UI Agent SDK. You can adopt any capability on its own, and none of them require changes to A2UI v1.0 client renderers.

PR Capability Module Playground showcase
#4320 Decision backend kernel a2ui.inference_formats.experimental.decision Backend header pills and Stage 2/3 inspector
#4321 Decision cascade router a2ui.inference_formats.experimental.decision_cascade cascade mode, /budget, and /compare
#4322 Tool pointer binder, @macro filler, and ADK callback a2ui.inference_formats.experimental.decision_binder binder mode, domain tools, and Incident Alert (Macro)
#4323 Submit-time RPC decision predicates a2ui.rpc.experimental.decision rpc mode and 3 live-validated forms
#4342 Gated template evaluator and graph pruner a2ui.inference_formats.experimental.decision_gated_templates gated mode, 2 gated templates, and 4 presets
#4344 Prose-to-surface upgrader and pluggable field extractors a2ui.inference_formats.experimental.decision_prose_upgrade prose mode, 3 structured presets, and unstructured abstention
#4325 Decision Playground agent and Lit shell samples/agent/adk/decision_playground Split-screen UI and <playground-inspector>

Running the Playground Locally

The tail of the stack, PR #4325 (feat/decision-playground-standalone), includes all seven PRs together.

1. Check out the stack branch

gh pr checkout 4325
# Or, using git directly:
git fetch origin feat/decision-playground-standalone
git checkout feat/decision-playground-standalone

2. Install dependencies and build

From the repository root, sync the Python workspace and build the TypeScript packages (samples/client/lit/shell builds @a2ui/web_core and @a2ui/lit automatically via Wireit):

# Python workspace (requires uv)
uv sync --all-packages

# Node/TypeScript workspace (requires Node and Yarn)
yarn install
yarn --cwd typescript/renderers/markdown-it build
yarn --cwd samples/client/lit/shell build

3. Start the agent and client

Start the agent in one terminal (offline mock requires no API keys; gemini uses GEMINI_API_KEY):

cd samples/agent/adk/decision_playground
./run.sh gemini    # or: ./run.sh mock

Start the Lit shell in a second terminal and open http://localhost:<port>/?app=playground (using the port Vite prints, usually 5173):

cd samples/client/lit/shell
yarn dev

Use the Mode and Backend pills at the top to switch capabilities live. Read the Explainer box at the bottom for mode-specific guidance, and inspect every decision batch and wire message in the Pipeline Inspector.


1. Decision Backend Kernel (PR #4320)

The kernel is the shared foundation used by every capability below. It defines the DecisionBackend protocol, typed question and answer models (DecisionBatch, DecisionQuestion, DecisionAnswer), payload pointer inspection (inspect_pointers), and catalog graph helpers (CatalogDecisionGraph). It ships four pluggable backends behind create_decision_backend():

  • gemini: Google Gemini Decisions API (gemini-decision-1 on /v1beta/decisions).
  • jev (systemone): Remote TypeSafe Jev endpoints (/v1/systemone).
  • step0: Single-token logprob scoring over any OpenAI-compatible completions server.
  • mock: Deterministic offline backend for local testing without API keys.

Common setup for all features

Every feature in this stack shares the same three-step setup on top of an existing A2UI v1.0 Python app (no client or renderer changes are needed):

  1. Install the optional decision extra: pip install "a2ui-agent-sdk[decision]".
  2. Configure backend credentials (for example, GEMINI_API_KEY for gemini, or skip credentials to test offline with mock).
  3. Create one shared DecisionBackend and pass it alongside your existing CatalogApi list to whichever capability you want to use:
from a2ui.inference_formats.experimental.decision import create_decision_backend

backend = create_decision_backend("gemini")  # or "mock", "jev", "step0"

2. Decision Cascade Router (PR #4321)

DecisionCascadeRouter runs one batched decision call per turn before your main LLM runs. It decides whether a prompt needs a UI and picks the cheapest tier that fits:

  1. TEXT_ONLY: plain text answer when gate:needs_ui falls below threshold, or when a tight latency budget rules out LLM synthesis and no template matches.
  2. TEMPLATE: instant compilation of a pre-authored A2UI Express template with zero UI LLM calls.
  3. PRUNED_EXPRESS: prunes unused components from the catalog (preserving layout primitives and ancestor/descendant closure) so the downstream LLM receives a smaller prompt.
  4. FULL_EXPRESS: falls back to the full catalog when the catalog exceeds the pruning cap.

An optional latency_budget_ms parameter restricts tight turns (below tight_budget_ms, default 500 ms) to TEMPLATE or TEXT_ONLY, without changing the backend's HTTP timeout (timeout_seconds).

Adding it to an existing app

Wrap your turn handler with DecisionCascadeRouter before invoking A2uiRequestProcessor (or A2uiInstruction). On TEXT_ONLY, skip A2UI generation; on TEMPLATE, compile decision.template.dsl directly; on PRUNED_EXPRESS, pass decision.pruned_catalogs into A2uiRequestProcessor instead of the full catalog:

from a2ui.inference_formats.experimental.decision_cascade import CascadeTier, DecisionCascadeRouter
from a2ui.processor import A2uiRequestProcessor

router = DecisionCascadeRouter(backend, templates=my_express_templates)
decision = await router.route(user_prompt, catalogs=[basic_catalog], latency_budget_ms=400)
if decision.tier is CascadeTier.PRUNED_EXPRESS:
    processor = A2uiRequestProcessor(catalogs=decision.pruned_catalogs)

In the playground

Select Mode: cascade and try four prompts:

  • Type "What is the capital of France?" to see gate:needs_ui route to TEXT_ONLY.
  • Click Host Health, Ski Resorts, Transfer Quote, or Playback Settings to hit TEMPLATE in one decision call with zero LLM tokens.
  • Type "Build a monthly budget calculator with rent, groceries, and savings sliders" to see per-component prune:* gates shrink the catalog before calling Gemini.
  • Type /budget 300 and repeat the budget calculator prompt to watch the tight budget downgrade the turn to TEXT_ONLY. Use /budget off to clear it, or /compare to run cascade, express, and direct side by side.

3. Tool Pointer Binder and Decision-Filled Macros (PR #4322)

ToolPointerBinder turns structured tool outputs and Python @macro components into A2UI v1.0 surfaces with zero UI LLM calls. It inspects JSON pointers on the payload, filters eligible targets (Express surfaces, @macro components, and Client-Side Templates), and scores select:target plus all slot-binding questions in one batch. Before emitting updateDataModel, it strips sensitive fields (such as apiKey, secret, token, or password) so credentials never reach the client wire.

Callers can invoke bind_tool_output(...) directly, fill_macro(intent, payload, *, macro_name=...) to fill a @macro without a tool wrapper, or make_adk_after_tool_callback inside an ADK agent loop.

Adding it to an existing app

Construct a ToolPointerBinder with your backend, transport_catalogs, and Express templates or @macro callables. In an ADK app, attach make_adk_after_tool_callback to your LlmAgent and allowlist those tool names on A2uiPartConverter (or A2uiEventConverter):

from a2ui.adk import A2uiPartConverter, make_adk_after_tool_callback
from a2ui.inference_formats.experimental.decision_binder import ToolPointerBinder

binder = ToolPointerBinder(backend, transport_catalogs=[basic_catalog], macros=[IncidentAlertCard])
agent = LlmAgent(
    ...,
    after_tool_callback=make_adk_after_tool_callback(binder, tool_names=("get_host_health",)),
)
converter = A2uiPartConverter(a2ui_processor=processor, allowed_a2ui_tool_names=("get_host_health",))

In the playground

Select Mode: binder and try the examples or paste any raw JSON object into the chat box:

  • Click Host Health, Ski Resorts, Transfer Quote, Playback Settings, or Order Details to see single-batch Express template binding. On Host Health, compare Stage 1 and Stage 4 updateDataModel to see apiKey redacted.
  • Click Incident Alert (Macro) to run /tool incident against the IncidentAlertCard Python @macro. It binds data pointers, plain primitives, Literal, bool, and Action slots in one call, then lowers to Basic Catalog v1.0 components.
  • Paste an unrelated JSON object to see the binder abstain cleanly instead of forcing a broken layout.

4. Submit-Time RPC Decision Predicates (PR #4323)

build_predicate_agent_functions exposes named boolean decision predicates as A2UI v1.0 agent functions (callAgentFunction / agentFunctionResponse). Renderers can bind form fields to semantic validation rules (reproduction steps, feedback quality, refund eligibility) without custom regexes or a full generative LLM. Each predicate keeps prompts server-owned and enforces input length limits, timeouts, and an optional SessionRateLimiter.

Adding it to an existing app

Define one or more NamedPredicateSpec entries, build the handlers with build_predicate_agent_functions, and pass them into your existing Catalog (which RendererToAgentMessageProcessor already dispatches):

from a2ui.rpc.experimental.decision import (
    NamedPredicateSpec,
    SessionRateLimiter,
    build_predicate_agent_functions,
)

fns = build_predicate_agent_functions(
    backend,
    specs=[NamedPredicateSpec(name="is_bug_report_complete", question="Does this include concrete reproduction steps?")],
    rate_limiter=SessionRateLimiter(max_calls=20, window_seconds=60.0),
)
# Register `fns` on your Catalog; RendererToAgentMessageProcessor handles callAgentFunction automatically.

In the playground

Select Mode: rpc to try Bug Report, Product Feedback, and Refund Request. Edit a text field and pause for ~800 ms: the Lit shell sends callAgentFunction over A2A, the server evaluates the boolean predicate, and agentFunctionResponse updates validation live without clearing the form.


5. Gated Templates (PR #4342)

One hand-authored A2UI v1.0 surface can carry optional regions (a2ui_gate) and mutually exclusive layout variants (a2ui_variant) inside standard v1.0 @metadata.extensions. Because the annotations live in @metadata.extensions, the unpruned base template still passes v1.0 catalog validation on its own.

GatedTemplateEvaluator scores every gate:* and variant:* question in one decision batch. prune_components then removes excluded subtrees, cleans parent children lists, and cascades upward when a required child slot becomes empty (Card, Button, Modal, Tabs, or ChildList templates). Before lowering, the evaluator strips the gate extension keys and redacts secret fields from the payload.

Adding it to an existing app

Annotate optional or variant components in your v1.0 template with @metadata.extensions.a2ui_gate or a2ui_variant, wrap the template in GatedTemplateSpec, and call evaluator.evaluate(...) (or select_and_evaluate(...)) to obtain validated wire messages:

from a2ui.inference_formats.experimental.decision_gated_templates import (
    GatedTemplateEvaluator,
    GatedTemplateSpec,
)

evaluator = GatedTemplateEvaluator(backend, transport_catalogs=[basic_catalog])
result = await evaluator.evaluate(incident_template, intent="Render service status", data_model=payload)
wire_messages = result.messages  # Pruned, redacted, validated v1.0 messages

In the playground

Select Mode: gated and compare Incident (Degraded) vs. Incident (Healthy), or Order (Delayed) vs. Order (Delivered). Watch optional alert/postmortem cards and layout variants toggle in one decision batch, or paste custom JSON directly into the chat box.


6. Prose-to-Surface Upgrade (PR #4344)

Existing text-only agents can keep answering in plain prose with zero A2UI prompt instructions. ProseSurfaceUpgrader runs a two-stage post-pass to decide whether to attach a companion A2UI v1.0 surface:

  1. One decision batch asks gate:has_structured_content and select:template (with allow_none=True). Unstructured prose abstains immediately without running extraction.
  2. A pluggable FieldExtractor lifts flat typed fields (ProseTemplateSpec and TypedFieldSpec) and checks each required field against ExtractionThresholds (confidence, p_null, truncation, type check, and optional verbatim source_span grounding). Any failure on a required field abstains cleanly so wrong values never appear beside accurate prose.

Adding it to an existing app

Pair ProseSurfaceUpgrader with your DecisionBackend, a StructuredOutputExtractor wrapping your preferred JSON-capable model call, and your ProseTemplateSpec catalog. Call upgrader.upgrade(prose_text) after a text LLM turn and attach result.messages when not result.abstained:

from a2ui.inference_formats.experimental.decision_prose_upgrade import (
    ProseSurfaceUpgrader,
    StructuredOutputExtractor,
)

upgrader = ProseSurfaceUpgrader(
    backend,
    extractor=StructuredOutputExtractor(my_async_json_caller, model_id="gemini-2.5-flash-lite"),
    templates=my_prose_templates,
    transport_catalogs=[basic_catalog],
)
result = await upgrader.upgrade(llm_prose_reply)
if not result.abstained:
    send_to_client(result.messages)

In the playground

Select Mode: prose and click Order Prose, Host Prose, or Ski Report Prose to watch the gate pass, extract grounded values into updateDataModel, and render the companion card. Click Unstructured Prose (or type general advice) to see the gate abstain without calling the extractor.

@gspencergoog

Copy link
Copy Markdown
Collaborator Author

This PR adds 6,275 lines, and nothing in the repo calls the new kernel yet. That makes the API hard to review: I can't tell whether DecisionBatch, PointerSummary or ExpressSurfaceSpec have the right shape without the code that uses them. I ran the tests (all pass) and probed the code with small scripts. The inline comments cover the bugs I could reproduce. A few points apply to the whole PR:

This PR is the base of a stack of PRs that adds implementations of various experimental ideas for using decision models. This one only contains the underlying implementation which all of the other ideas use in their implementation: the connection to the decision models themselves, for instance. I did it this way, rather than creating a 38K line single PR that would have been even more challenging to review. Does that help?

…n, regex, and docs

Signed-off-by: Greg Spencer <gspencer@google.com>
@polina-c

polina-c commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

Sure, here's a feature guide to the different ideas implemented in the stack, along with how to run the playground app locally, and how to add each one to an existing Python ADK app. Is that what you wanted to see? ...

Thanks, the guide is useful for reviewers, but I was looking for something much shorter, for people who build apps on A2UI:

  1. What is the delta compared to the current agent-model interaction?
  2. How does an app change for its users once the whole stack lands?

We are adding a lot of code to the repository, so it is important to have a shared vision/pitch of what it will be for the end user.

Here is my guess, to show the shape I mean. Please correct what's wrong.


Decision models in A2UI apps (experimental)

Today, an A2UI agent uses one generative model, such as Gemini Flash Lite, to write both text and UI. With this feature, the agent also calls a decision model, such as gemini-decision-1, which writes nothing and only chooses among the answers it is given. The agent combines the two models in four ways:

  1. Decision model, then generative model. The decision model decides whether the request needs UI and which components fit, then the generative model writes the reply. If a ready-made template fits, the generative model is skipped.
  2. Generative model, then decision model. After the generative model calls a tool, the decision model puts the result into a template.
  3. Generative model, then decision model, then generative model. After a text reply, the decision model decides whether to add a surface, and the generative model fills the surface with facts from the reply.
  4. Decision model only. It checks form fields as the user types.

People using the app will notice:

  1. Faster answers, because many turns skip the generative model or give it fewer components.
  2. Faster and more consistent surfaces after tool calls. When the agent calls a tool, such as an order lookup, it fills a template the developer wrote instead of asking the generative model to design the surface, so the same kind of data always gets the same layout.
  3. Template surfaces that include only the components that apply to the data. For example, an order status surface includes the delay notice only when the order is late.
  4. Replies from agents that answer only in text today will be enhanced with UI.
  5. Forms that check meaning as the user types.

When the decision model is unsure, the agent falls back to its current behavior.

The developer doesn't need a new package from PyPI. The code ships in the existing a2ui-agent-sdk package, and the hook for tool results ships in the existing a2ui-adk package. Installing with the decision extra (pip install "a2ui-agent-sdk[decision]") only adds the HTTP client that calls the decision model. The developer then adds the parts they want to the agent code. Each part works on its own. For example, asking the decision model before the generative model (way 1) could look like this, where write_text, write_ui and compile_template stand for the agent's own code:

from a2ui.decision import DecisionModel, choice, yes_no

decision_model = DecisionModel("gemini-decision-1")

async def respond(message):
    answers = await decision_model.ask(
        message,
        needs_ui=yes_no("Does this need UI?"),
        template=choice("Which template fits?", ["host_health", "order_status"]),
    )
    if answers.needs_ui < 0.5:
        return await write_text(message)  # generative model writes text only
    if template := answers.template.pick(min_probability=0.8):
        return compile_template(template)  # no generative model call
    return await write_ui(message)  # generative model writes UI, as today

A2UI messages and renderers don't change.


The snippet uses a simpler API than the one in this PR. I'd suggest something like it:

  1. DecisionModel("gemini-decision-1") instead of create_decision_backend("gemini"), so the model ID picks the backend.
  2. Questions as keyword arguments of ask(), created with yes_no(), choice() and score(). The argument name is the question ID, so the caller doesn't build DecisionBatch, DecisionQuestion or QuestionKind objects.
  3. Answers by name. answers.needs_ui is the probability of yes, and answers.template.pick(min_probability=0.8) returns the chosen option or None, instead of .top() and the "none" string.
  4. The module a2ui.decision, the name your one-pager plans for when the feature leaves experimental.

🤖 Agent-generated

@polina-c

Copy link
Copy Markdown
Collaborator

LGTM after addressing the comments and with TODO to iterate on #4320 (comment)

…ionModel

Remove vendor-specific backend types, HTTP connectors, gcloud/ADC auth,
and the httpx dependency from a2ui-agent-sdk in favor of a vendor-agnostic
DecisionModel callable alias, DecisionModelError, MockDecisionModel,
invoke_decision_model, and multi-turn DecisionBatch context fields.

Signed-off-by: Greg Spencer <gspencer@google.com>
- Add SlotKind.STRUCTURED and ComponentSlot.schema for lossless catalog graphs
- Extract PointerTypeClassifier, BasicEnglishTypeClassifier, DefaultSecretFilter,
  open semantic_type strings, and opt-in detect_groups in payload_inspector
- Guard bare str/bytes for mutable_paths/exclude and eliminate double @experimental warnings
- Add O(1) base64 length pre-check on MediaInputPart and duplicate/none checks on DecisionQuestion
- Fix priceMin duration misclassification and bounded number range checks
- Seed transport surface catalogs from renderer_state and scope macro shadowing by catalog_id
- Deduplicate and validate @macro allowed_parents/allowed_children
- Enforce barrel-only decision imports in test_experimental_import_isolation.py

Signed-off-by: Greg Spencer <gspencer@google.com>
- Filter excluded array columns from sample_pointers as well as element_keys.
- Treat '' (not '/') as RFC 6901 root in mutable_paths, require exact-path
  membership to exempt secrets from redaction, and wire secret_filter into
  array element filtering.
- Skip empty-string mapping keys across traversal and grouped-section helpers
  so unaddressable '/' pointers are never emitted.
- Base _normalize_probabilities renormalization on candidate mass only.

Signed-off-by: Greg Spencer <gspencer@google.com>
- Extract shared _validate_question_fields helper and add DecisionAnswer.pick()
  with separate probability (min_margin) and logit (min_logit_margin) bounds.
- Add ask(), yes_no(), choice(), score(), QuestionSpec, and DecisionAnswers
  under a2ui.inference_formats.experimental.decision on top of DecisionModel.
- Add unit tests and CHANGELOG entry.

Signed-off-by: Greg Spencer <gspencer@google.com>
Comment thread python/a2ui_agent/CHANGELOG.md Resolved
Comment thread uv.lock Resolved
…l-standalone

# Conflicts:
#	python/a2ui_agent/CHANGELOG.md
- Move Calibration, answer_from_distribution, and invoke_decision_model into
  runtime.py with @experimental decorators, strict weight/timeout/alignment
  validation, and Calibration bool/JSON guards; validate MockDecisionModel
  scripted specs.
- Fail closed in DecisionAnswer.pick() on NaN/all-zero distributions and add
  abstain_label; guard bare strings and add hash=False on DecisionBatch.
- Fix DecisionAnswers copy/deepcopy/pickle recursion, validate ask()
  instructions/shared_context/reserved names, and enforce non-empty string
  options in QuestionSpec and DecisionQuestion.
- Harden secret redaction across compound separator-free keys, benign token/
  cookie/password names, multi-word DefaultSecretFilter extra_keys, group
  label/subtitle selection, and array semantic/mutable filtering.
- Tighten SQL/class prose heuristics and durationMin detection, deep-copy
  ComponentSlot.schema, fix deleteSurface seeding in transport.py, close
  barrel alias bypass in test_experimental_import_isolation.py, clear
  warning suppression env var in test_decision_ask.py, and update CI httpx
  check.

Signed-off-by: Greg Spencer <gspencer@google.com>
gspencergoog added a commit that referenced this pull request Dec 1, 2026
Signed-off-by: Greg Spencer <gspencer@google.com>
gspencergoog added a commit that referenced this pull request Dec 1, 2026
…ning

Signed-off-by: Greg Spencer <gspencer@google.com>
gspencergoog added a commit to gspencergoog/A2UI that referenced this pull request Dec 1, 2026
…hardening fixes

Signed-off-by: Greg Spencer <gspencer@google.com>
gspencergoog added a commit to gspencergoog/A2UI that referenced this pull request Dec 1, 2026
…review hardening

Signed-off-by: Greg Spencer <gspencer@google.com>
@gspencergoog

Copy link
Copy Markdown
Collaborator Author

Closing this PR in favor of the modularized replacement stack.

@jacobsimionato @polina-c: Previous review comments have been incorporated into the replacement PRs:

🤖 Agent-generated

gspencergoog added a commit that referenced this pull request Dec 1, 2026
Signed-off-by: Greg Spencer <gspencer@google.com>
gspencergoog added a commit that referenced this pull request Dec 1, 2026
…ning

Signed-off-by: Greg Spencer <gspencer@google.com>
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.

3 participants