Repository navigation
feat(decision): add minimal shared decision kernel, macro placement hints, and CI barrel guard - #4320
gspencergoog wants to merge 12 commits into
Conversation
There was a problem hiding this comment.
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.
…ints, and CI barrel guard Signed-off-by: Greg Spencer <gspencer@google.com>
2f17c99 to
ba30612
Compare
…ast import Signed-off-by: Greg Spencer <gspencer@google.com>
…l-standalone # Conflicts: # python/a2ui_agent/CHANGELOG.md
There was a problem hiding this comment.
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:
- Several parts refer to code that is not in this PR or in
main. The docstrings at backends.py#L588 and backends.py#L713 sayDecisionSynthesizer.synthesize_synccallsaclose_current_loop(), but there is noDecisionSynthesizer, so nothing closes the per-loop clients (see the inline comment on L758). models.py#L408 names aDecisionTask, 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,synthesizerand others) that don't exist. The fallback heuristics in payload_inspector.py#L30-L108 and payload_inspector.py#L156-L202 only run for aPointerSummarybuilt withoutsemantic_typeandlabel, and nothing in the repo builds one that way. - Test coverage is low for this much code. With
pytest-covontests/decision/:backends.py57%,payload_inspector.py40%,semantic_types.py59%. Most tests check several unrelated things at once (for exampletest_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:
StepZeroLogprobBackendapplies 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._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.- In
semantic_types.py,"min"maps to minutes (semantic_types.py#L256), sotemp_min: 12.5andpriceMin: 100classify 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}givesoffsetas bounded 0 to 25. excludeininspect_pointersremoves an array column fromelement_keysbut keeps it insample_pointers: withexclude={"/items/photo"},/itemsstill hassample_pointers=("/items/0/photo",).mutable_paths={"/"}turns off secret redaction for the whole payload, and a mutable parent such as/accountexempts/account/apiKey. In RFC 6901,"/"is the empty-string key and""is the root._escape_pointer_segment(payload_inspector.py#L205-L212) duplicates pointer handling thata2ui_corealready has inDataModel(data_model.py#L41-L60), and the two disagree on empty keys: the inspector emits/for{"": ...}, whichDataModelreads as the root. A public helper ina2ui_corewould give both the same behavior.
🤖 Agent-generated
|
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, Here's how the bot describes it: Right now, all new modules live under Each track plugs into an existing boundary and emits standard v1.0 One-PagerIntegrating Decision Models with the A2UI APISummaryThe 7-PR decision-model stack (#4320, #4321, #4322, #4323, #4342, #4344, #4325) adds fast binary and multiple-choice classification alongside generative inference formats ( Integration is additive and opt-in. The v1.0 wire protocol, client renderers, Architecture and Integration SeamsDecision 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)"]
How the API Changes Over TimePhase 1: Experimental Isolation (Current Stack)All decision code lives under 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 ConsolidationUsing 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 ( Phase 3: Promotion to Stable APIsGraduated capabilities will move out of
What Does Not Change
|
|
Thank you. Can you craft 1-2 paragraph of documentation for end users that describes in a simple way:
|
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 GuideA2UI Decision Models: Feature Guide and Integration WalkthroughDecision 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.
Running the Playground LocallyThe tail of the stack, PR #4325 ( 1. Check out the stack branchgh pr checkout 4325
# Or, using git directly:
git fetch origin feat/decision-playground-standalone
git checkout feat/decision-playground-standalone2. Install dependencies and buildFrom the repository root, sync the Python workspace and build the TypeScript packages ( # 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 build3. Start the agent and clientStart the agent in one terminal (offline cd samples/agent/adk/decision_playground
./run.sh gemini # or: ./run.sh mockStart the Lit shell in a second terminal and open cd samples/client/lit/shell
yarn devUse 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
Common setup for all featuresEvery 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):
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)
An optional Adding it to an existing appWrap your turn handler with 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 playgroundSelect Mode: cascade and try four prompts:
3. Tool Pointer Binder and Decision-Filled Macros (PR #4322)
Callers can invoke Adding it to an existing appConstruct a 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 playgroundSelect Mode: binder and try the examples or paste any raw JSON object into the chat box:
4. Submit-Time RPC Decision Predicates (PR #4323)
Adding it to an existing appDefine one or more 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 playgroundSelect Mode: rpc to try Bug Report, Product Feedback, and Refund Request. Edit a text field and pause for ~800 ms: the Lit shell sends 5. Gated Templates (PR #4342)One hand-authored A2UI v1.0 surface can carry optional regions (
Adding it to an existing appAnnotate optional or variant components in your v1.0 template with 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 messagesIn the playgroundSelect 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.
Adding it to an existing appPair 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 playgroundSelect Mode: prose and click Order Prose, Host Prose, or Ski Report Prose to watch the gate pass, extract grounded values into |
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>
Thanks, the guide is useful for reviewers, but I was looking for something much shorter, for people who build apps on A2UI:
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
People using the app will notice:
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 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 todayA2UI messages and renderers don't change. The snippet uses a simpler API than the one in this PR. I'd suggest something like it:
🤖 Agent-generated |
|
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>
…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>
Signed-off-by: Greg Spencer <gspencer@google.com>
…ning Signed-off-by: Greg Spencer <gspencer@google.com>
…hardening fixes Signed-off-by: Greg Spencer <gspencer@google.com>
…review hardening Signed-off-by: Greg Spencer <gspencer@google.com>
|
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 |
Signed-off-by: Greg Spencer <gspencer@google.com>
…ning Signed-off-by: Greg Spencer <gspencer@google.com>
Summary
Adds a minimal shared experimental decision-model kernel (
a2ui.inference_formats.experimental.decision),@macroparent/child placement hints (allowed_parents/allowed_children), optionala2ui-agent-sdk[decision](httpx) gating, and CI barrel isolation checks directly on top ofmain.Reviewer Focus
python/a2ui_agent/src/a2ui/inference_formats/experimental/decision/backends.py:DecisionBackendprotocol,JevHttpBackend(native Jev,/v1/systemone, and/v1beta/decisions),StepZeroLogprobBackend(shared monotonic deadline),DeterministicMockBackend, per-loop_HttpClientOwner, andcreate_decision_backendvendor-key scoping.python/a2ui_agent/src/a2ui/inference_formats/experimental/decision/transport.py:build_inference_catalogsandlower_for_transport(macro lowering and transactionalRendererStatetopology 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.ymlandpython/a2ui_agent/pyproject.toml: optionaldecisionextra (httpx>=0.27.0) and isolated import check verifying public barrels stay free of experimental decision/RPC modules andhttpx.Changes
allowed_parentsandallowed_childrenparameters to@macroinpython/a2ui_agent/src/a2ui/transformers/macros/macro.py, emittingallowedParentsandallowedChildrenschema metadata and rejecting bare strings.python/a2ui_agent/src/a2ui/inference_formats/experimental/decision/:models.py:DecisionBatch,DecisionQuestion,DecisionAnswer,DecisionDistribution,MediaInputPart,TextInputPart,ActionSpec,ExpressSurfaceSpec,ComponentNodeSpec,ComponentSlot,coerce_decision_payload, andDecisionBackendError.backends.pyandcalibration_profiles.json: HTTP, Step-0, and mock decision backends with temperature calibration and optionalhttpxgating.catalog_graph.py:CatalogDecisionGraphextracting catalog component slots and parent/child relationships.payload_inspector.pyandsemantic_types.py: RFC 6901 JSON Pointer inspection, semantic scalar/array classification, and secret pointer redaction.transport.py:build_inference_catalogsandlower_for_transport.python/a2ui_agent/tests/decision/test_decision_kernel.py,python/a2ui_agent/tests/decision/test_transport_and_core_extensions.py, andpython/a2ui_agent/tests/test_experimental_import_isolation.py..github/workflows/python_ci.yml,python/a2ui_agent/pyproject.toml,uv.lock, andpython/a2ui_agent/CHANGELOG.md.Impact & Risks
a2ui.inference_formats,a2ui.parser,a2ui.processor, anda2ui.rpcbarrels do not importa2ui.inference_formats.experimental.decisionorhttpx; verified by the isolated CI check.a2ui.inference_formats.experimental.decisionare decorated with@experimental.@macrokeeps backwards-compatible defaults (allowed_parents=(),allowed_children=()).Testing
uv run pyink --check python/a2ui_agentuv run --all-packages mypy .anduv run mypy --follow-imports=silent python/a2ui_agent/src/a2ui/inference_formats/experimental/decision/*.pyA2UI_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.github/workflows/python_ci.yml(uv run --isolated --no-project --with ./python/a2ui_core --with ./python/a2ui_agent python -c ...).