diff --git a/catalogs/README.md b/catalogs/README.md index 3b243fffa1..0429e55626 100644 --- a/catalogs/README.md +++ b/catalogs/README.md @@ -15,8 +15,15 @@ catalogs/ ├── basic/ │ └── v1/ # Basic catalog, major version 1 │ ├── catalog.json +│ ├── patterns.json # Abstract block pattern templates for Basic v1 │ ├── examples/ │ └── basic_catalog_implementation_guide.md +├── decision/ # Catalog-agnostic layout archetype grammar & schemas +│ ├── README.md +│ └── v1/ +│ ├── archetypes.json +│ ├── archetype_definition.json +│ └── pattern_definition.json ├── mcp/ # MCP catalog │ ├── catalog.json # Pre-1.0 MCP catalog, protocol v0.9 │ └── v1/ # MCP catalog, major version 1 (protocol v1.0) @@ -35,6 +42,15 @@ catalogs/ catalog at its existing `$id` URL (`https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json`), so moving files here does not affect consumers. +- `basic/v1/patterns.json` maps the 17 abstract block patterns (`page`, `banner`, + `picture`, `media`, `filters`, `headline`, `facts`, `prose`, `collection`, + `comparison`, `steps`, `form`, `groups`, `actions`, `outcome`, `conversation`, + `compose`) onto Basic Catalog components for decision-model layout synthesis, + while `decision/v1/archetypes.json` (with `archetype_definition.json` and + `pattern_definition.json`, documented in `decision/README.md`) defines the + catalog-agnostic layout archetype grammar (`ArchetypeGrammar`). Python + packages mirror these assets via + `python/a2ui_agent/scripts/sync_decision_assets.py`. - `basic/` is versioned by catalog major version (`v1/`), which is independent of the protocol version. Newer catalogs start unversioned (`catalogs//catalog.json`) and add a version directory only when diff --git a/catalogs/basic/v1/patterns.json b/catalogs/basic/v1/patterns.json new file mode 100644 index 0000000000..1661ee0318 --- /dev/null +++ b/catalogs/basic/v1/patterns.json @@ -0,0 +1,1717 @@ +{ + "$schema": "https://a2ui.org/specification/v1_0/decision/pattern_definition.json", + "catalogIds": [ + "https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json", + "https://a2ui.org/specification/v0_9/catalogs/basic/catalog.json" + ], + "version": "1", + "patterns": { + "page": { + "slots": [ + "title", + "subtitle", + "mark", + "blocks" + ], + "knobs": { + "dialog": [ + "yes", + "no" + ], + "stickyActions": [ + "yes", + "no" + ] + }, + "note": "mark is a small image beside the title: a logo or avatar that the picture block's prominence score placed at level 0.", + "variants": [ + { + "when": { + "dialog": "yes" + }, + "root": "page_card", + "components": [ + { + "id": "page_card", + "component": "Card", + "child": "page_col" + }, + { + "id": "page_col", + "component": "Column", + "children": [ + "page_head", + { + "$if": "subtitle", + "id": "page_subtitle" + }, + { + "$blocks": true + } + ] + }, + { + "id": "page_head", + "component": "Row", + "align": "center", + "children": [ + { + "$if": "mark", + "id": "page_mark" + }, + "page_title" + ] + }, + { + "id": "page_mark", + "component": "Image", + "url": { + "$slot": "mark" + }, + "variant": "icon", + "fit": "contain" + }, + { + "id": "page_title", + "component": "Text", + "text": { + "$text": "## {title}" + } + }, + { + "id": "page_subtitle", + "component": "Text", + "text": { + "$slot": "subtitle" + }, + "variant": "caption" + } + ] + }, + { + "root": "page_col", + "components": [ + { + "id": "page_col", + "component": "Column", + "children": [ + "page_head", + { + "$if": "subtitle", + "id": "page_subtitle" + }, + { + "$blocks": true + } + ] + }, + { + "id": "page_head", + "component": "Row", + "align": "center", + "children": [ + { + "$if": "mark", + "id": "page_mark" + }, + "page_title" + ] + }, + { + "id": "page_mark", + "component": "Image", + "url": { + "$slot": "mark" + }, + "variant": "icon", + "fit": "contain" + }, + { + "id": "page_title", + "component": "Text", + "text": { + "$text": "## {title}" + } + }, + { + "id": "page_subtitle", + "component": "Text", + "text": { + "$slot": "subtitle" + }, + "variant": "caption" + } + ] + } + ] + }, + "banner": { + "slots": [ + "title", + "text", + "tone" + ], + "root": "banner_card", + "components": [ + { + "id": "banner_card", + "component": "Card", + "child": "banner_row" + }, + { + "id": "banner_row", + "component": "Row", + "align": "center", + "children": [ + "banner_icon", + "banner_col" + ] + }, + { + "id": "banner_icon", + "component": "Icon", + "name": { + "$map": "tone", + "success": "check", + "warning": "info", + "danger": "error", + "neutral": "info" + } + }, + { + "id": "banner_col", + "component": "Column", + "weight": 1, + "children": [ + "banner_title", + { + "$if": "text", + "id": "banner_text" + } + ] + }, + { + "id": "banner_title", + "component": "Text", + "text": { + "$text": "**{title}**" + } + }, + { + "id": "banner_text", + "component": "Text", + "text": { + "$slot": "text" + }, + "variant": "caption" + } + ] + }, + "picture": { + "slots": [ + "picture", + "caption" + ], + "knobs": { + "framing": [ + "banner", + "portrait", + "object", + "poster" + ], + "prominence": [ + "mark", + "supporting", + "leading", + "full" + ] + }, + "variants": [ + { + "when": { + "prominence": [ + "mark" + ] + }, + "root": "picture_img", + "components": [ + { + "id": "picture_img", + "component": "Image", + "url": { + "$slot": "picture" + }, + "variant": { + "$map": "framing", + "portrait": "avatar", + "object": "icon", + "banner": "icon", + "poster": "icon" + }, + "fit": "contain", + "description": { + "$slot": "caption", + "$default": "" + } + } + ] + }, + { + "when": { + "prominence": [ + "supporting" + ] + }, + "root": "picture_img", + "components": [ + { + "id": "picture_img", + "component": "Image", + "url": { + "$slot": "picture" + }, + "variant": { + "$map": "framing", + "portrait": "avatar", + "object": "smallFeature", + "banner": "mediumFeature", + "poster": "mediumFeature" + }, + "fit": { + "$map": "framing", + "banner": "cover", + "portrait": "cover", + "object": "contain", + "poster": "contain" + }, + "description": { + "$slot": "caption", + "$default": "" + } + } + ] + }, + { + "root": "picture_col", + "components": [ + { + "id": "picture_col", + "component": "Column", + "children": [ + "picture_img", + { + "$if": "caption", + "id": "picture_caption" + } + ] + }, + { + "id": "picture_img", + "component": "Image", + "url": { + "$slot": "picture" + }, + "variant": { + "$map": "framing", + "banner": "header", + "portrait": "largeFeature", + "object": "largeFeature", + "poster": "largeFeature" + }, + "fit": { + "$map": "framing", + "banner": "cover", + "portrait": "cover", + "object": "contain", + "poster": "contain" + }, + "description": { + "$slot": "caption", + "$default": "" + } + }, + { + "id": "picture_caption", + "component": "Text", + "text": { + "$slot": "caption" + }, + "variant": "caption" + } + ] + } + ], + "note": "Basic v1 Image has no aspect-ratio control; width, height, and orientation from the payload only inform framing and the choice between header and largeFeature. A catalog with an explicit aspect ratio property would map the aspectRatio slot directly." + }, + "media": { + "slots": [ + "source", + "poster", + "title", + "duration" + ], + "root": "media_col", + "components": [ + { + "id": "media_col", + "component": "Column", + "children": [ + { + "$if": "title", + "id": "media_title" + }, + { + "$byType": "source", + "video_url": "media_video", + "audio_url": "media_audio" + }, + { + "$if": "duration", + "id": "media_duration" + } + ] + }, + { + "id": "media_title", + "component": "Text", + "text": { + "$text": "### {title}" + } + }, + { + "id": "media_video", + "component": "Video", + "url": { + "$slot": "source" + }, + "posterUrl": { + "$slot": "poster", + "$default": "" + } + }, + { + "id": "media_audio", + "component": "AudioPlayer", + "url": { + "$slot": "source" + }, + "description": { + "$slot": "title", + "$default": "" + } + }, + { + "id": "media_duration", + "component": "Text", + "text": { + "$slot": "duration" + }, + "variant": "caption" + } + ] + }, + "filters": { + "slots": [ + "query", + "categories" + ], + "root": "filters_col", + "components": [ + { + "id": "filters_col", + "component": "Column", + "children": [ + { + "$if": "query", + "id": "filters_search" + }, + { + "$if": "categories", + "id": "filters_categories" + } + ] + }, + { + "id": "filters_search", + "component": "TextField", + "label": "Search", + "value": { + "$slot": "query" + }, + "variant": "shortText" + }, + { + "id": "filters_categories", + "component": "ChoicePicker", + "label": "Filter", + "variant": "mutuallyExclusive", + "displayStyle": "chips", + "options": { + "$slot": "categories" + }, + "value": { + "$slot": "categories.selected", + "$default": [] + } + } + ], + "note": "displayStyle chips is this catalog's own enum value; the grammar slot is categories and says nothing about how they are drawn." + }, + "headline": { + "slots": [ + "items" + ], + "knobs": { + "deltas": [ + "yes", + "no" + ], + "gauge": [ + "yes", + "no" + ] + }, + "root": "headline_row", + "components": [ + { + "id": "headline_row", + "component": "Row", + "justify": "spaceBetween", + "children": { + "$repeat": "items", + "component": "headline_item" + } + }, + { + "id": "headline_item", + "component": "Card", + "weight": 1, + "child": "headline_item_col" + }, + { + "id": "headline_item_col", + "component": "Column", + "align": "center", + "children": [ + "headline_value", + "headline_label", + { + "$if": "delta", + "id": "headline_delta" + }, + { + "$ifKnob": { + "gauge": [ + "yes" + ] + }, + "$if": "max", + "id": "headline_gauge" + } + ] + }, + { + "id": "headline_value", + "component": "Text", + "text": { + "$text": "### {value}" + } + }, + { + "id": "headline_label", + "component": "Text", + "text": { + "$slot": "label" + }, + "variant": "caption" + }, + { + "id": "headline_delta", + "component": "Text", + "text": { + "$text": "{delta}" + }, + "variant": "caption" + }, + { + "id": "headline_gauge", + "component": "Text", + "text": { + "$text": "{value} of {max}" + }, + "variant": "caption" + } + ], + "note": "No gauge or progress component in basic v1, so a bounded value is written as 'value of max'. Status and boolean values are rendered as their text; a catalog with a badge or chip would map state_tone to it." + }, + "facts": { + "slots": [ + "rows" + ], + "root": "facts_card", + "components": [ + { + "id": "facts_card", + "component": "Card", + "child": "facts_list" + }, + { + "id": "facts_list", + "component": "List", + "direction": "vertical", + "children": { + "$repeat": "rows", + "component": "facts_row" + } + }, + { + "id": "facts_row", + "component": "Row", + "justify": "spaceBetween", + "children": [ + "facts_label", + "facts_value" + ] + }, + { + "id": "facts_label", + "component": "Text", + "text": { + "$slot": "label" + }, + "variant": "caption" + }, + { + "id": "facts_value", + "component": "Text", + "text": { + "$slot": "value" + } + } + ] + }, + "prose": { + "slots": [ + "heading", + "body" + ], + "knobs": { + "length": [ + "line", + "blurb", + "summary", + "article" + ] + }, + "variants": [ + { + "when": { + "length": [ + "article" + ] + }, + "root": "prose_col", + "components": [ + { + "id": "prose_col", + "component": "Column", + "children": [ + { + "$if": "heading", + "id": "prose_heading" + }, + "prose_body" + ] + }, + { + "id": "prose_heading", + "component": "Text", + "text": { + "$text": "### {heading}" + } + }, + { + "id": "prose_body", + "component": "Text", + "text": { + "$slot": "body" + } + } + ], + "note": "Basic v1 cannot truncate text or collapse it behind a Read more without losing the inline copy, so an article is set in full. A catalog with a disclosure component would show the first paragraph and expand." + }, + { + "root": "prose_col", + "components": [ + { + "id": "prose_col", + "component": "Column", + "children": [ + { + "$if": "heading", + "id": "prose_heading" + }, + "prose_body" + ] + }, + { + "id": "prose_heading", + "component": "Text", + "text": { + "$text": "### {heading}" + } + }, + { + "id": "prose_body", + "component": "Text", + "text": { + "$slot": "body" + }, + "variant": { + "$map": "length", + "line": "caption", + "blurb": "body", + "summary": "body" + } + } + ] + } + ] + }, + "collection": { + "slots": [ + "items" + ], + "knobs": { + "layout": [ + "rows", + "cards", + "reel" + ], + "leading": [ + "thumbnail", + "avatar", + "icon", + "number", + "none" + ], + "trailing": [ + "chevron", + "button", + "value", + "none" + ] + }, + "variants": [ + { + "when": { + "layout": "rows" + }, + "root": "list", + "components": [ + { + "id": "list", + "component": "List", + "direction": "vertical", + "children": { + "$repeat": "items", + "component": "item" + } + }, + { + "id": "item", + "component": "Row", + "align": "center", + "children": [ + { + "$ifKnob": { + "leading": [ + "thumbnail" + ] + }, + "id": "item_thumb" + }, + { + "$ifKnob": { + "leading": [ + "avatar" + ] + }, + "id": "item_avatar" + }, + { + "$ifKnob": { + "leading": [ + "icon" + ] + }, + "id": "item_icon" + }, + "item_col", + { + "$if": "meta", + "id": "item_meta" + }, + { + "$ifKnob": { + "trailing": [ + "button" + ] + }, + "id": "item_button" + }, + { + "$ifKnob": { + "trailing": [ + "chevron" + ] + }, + "id": "item_chevron" + } + ] + }, + { + "id": "item_thumb", + "component": "Image", + "url": { + "$slot": "picture" + }, + "variant": "smallFeature", + "fit": "cover" + }, + { + "id": "item_avatar", + "component": "Image", + "url": { + "$slot": "picture" + }, + "variant": "avatar", + "fit": "cover" + }, + { + "id": "item_icon", + "component": "Icon", + "name": { + "$slot": "icon", + "$default": "info" + } + }, + { + "id": "item_col", + "component": "Column", + "weight": 1, + "children": [ + "item_headline", + { + "$if": "supporting", + "id": "item_supporting" + }, + { + "$if": "badge", + "id": "item_badge" + } + ] + }, + { + "id": "item_headline", + "component": "Text", + "text": { + "$text": "**{headline}**" + } + }, + { + "id": "item_supporting", + "component": "Text", + "text": { + "$slot": "supporting" + }, + "variant": "caption" + }, + { + "id": "item_badge", + "component": "Text", + "text": { + "$text": "`{badge}`" + }, + "variant": "caption" + }, + { + "id": "item_meta", + "component": "Text", + "text": { + "$slot": "meta" + } + }, + { + "id": "item_button", + "component": "Button", + "child": "item_button_label", + "action": { + "$event": "item_action", + "context": { + "$item": true + } + } + }, + { + "id": "item_button_label", + "component": "Text", + "text": { + "$knobValue": "trailing.label", + "$default": "Open" + } + }, + { + "id": "item_chevron", + "component": "Icon", + "name": "arrowForward" + } + ] + }, + { + "when": { + "layout": "cards" + }, + "root": "list", + "components": [ + { + "id": "list", + "component": "List", + "direction": "vertical", + "children": { + "$repeat": "items", + "component": "item" + } + }, + { + "id": "item", + "component": "Card", + "child": "item_col" + }, + { + "id": "item_col", + "component": "Column", + "children": [ + "item_img", + "item_headline", + { + "$if": "supporting", + "id": "item_supporting" + }, + "item_footer" + ] + }, + { + "id": "item_img", + "component": "Image", + "url": { + "$slot": "picture" + }, + "variant": "largeFeature", + "fit": "cover" + }, + { + "id": "item_headline", + "component": "Text", + "text": { + "$text": "**{headline}**" + } + }, + { + "id": "item_supporting", + "component": "Text", + "text": { + "$slot": "supporting" + }, + "variant": "caption" + }, + { + "id": "item_footer", + "component": "Row", + "justify": "spaceBetween", + "children": [ + { + "$if": "meta", + "id": "item_meta" + }, + { + "$if": "rating", + "id": "item_rating" + }, + { + "$ifKnob": { + "trailing": [ + "button" + ] + }, + "id": "item_button" + } + ] + }, + { + "id": "item_meta", + "component": "Text", + "text": { + "$slot": "meta" + } + }, + { + "id": "item_rating", + "component": "Text", + "text": { + "$text": "{rating} / 5" + }, + "variant": "caption" + }, + { + "id": "item_button", + "component": "Button", + "child": "item_button_label", + "action": { + "$event": "item_action", + "context": { + "$item": true + } + } + }, + { + "id": "item_button_label", + "component": "Text", + "text": { + "$knobValue": "trailing.label", + "$default": "Open" + } + } + ] + }, + { + "when": { + "layout": "reel" + }, + "root": "reel", + "components": [ + { + "id": "reel", + "component": "List", + "direction": "horizontal", + "children": { + "$repeat": "items", + "component": "item" + } + }, + { + "id": "item", + "component": "Column", + "children": [ + "item_img", + "item_headline", + { + "$if": "meta", + "id": "item_meta" + } + ] + }, + { + "id": "item_img", + "component": "Image", + "url": { + "$slot": "picture" + }, + "variant": "mediumFeature", + "fit": "cover" + }, + { + "id": "item_headline", + "component": "Text", + "text": { + "$slot": "headline" + }, + "variant": "caption" + }, + { + "id": "item_meta", + "component": "Text", + "text": { + "$slot": "meta" + }, + "variant": "caption" + } + ] + } + ], + "note": "No grid variant: basic v1 has no intrinsic grid, so grid is never offered for this catalog (requires pattern:collection:grid)." + }, + "comparison": { + "slots": [ + "options" + ], + "root": "cmp_row", + "components": [ + { + "id": "cmp_row", + "component": "Row", + "align": "stretch", + "children": { + "$repeat": "options", + "component": "cmp_card" + } + }, + { + "id": "cmp_card", + "component": "Card", + "weight": 1, + "child": "cmp_col" + }, + { + "id": "cmp_col", + "component": "Column", + "children": [ + { + "$if": "picture", + "id": "cmp_img" + }, + "cmp_headline", + { + "$if": "highlight", + "id": "cmp_highlight" + }, + "cmp_attrs" + ] + }, + { + "id": "cmp_img", + "component": "Image", + "url": { + "$slot": "picture" + }, + "variant": "mediumFeature", + "fit": "cover" + }, + { + "id": "cmp_headline", + "component": "Text", + "text": { + "$text": "**{headline}**" + } + }, + { + "id": "cmp_highlight", + "component": "Text", + "text": { + "$text": "**{highlight}**" + } + }, + { + "id": "cmp_attrs", + "component": "List", + "direction": "vertical", + "children": { + "$repeat": "attributes", + "component": "cmp_attr" + } + }, + { + "id": "cmp_attr", + "component": "Row", + "justify": "spaceBetween", + "children": [ + "cmp_attr_label", + "cmp_attr_value" + ] + }, + { + "id": "cmp_attr_label", + "component": "Text", + "text": { + "$slot": "label" + }, + "variant": "caption" + }, + { + "id": "cmp_attr_value", + "component": "Text", + "text": { + "$slot": "value" + }, + "variant": "caption" + } + ] + }, + "steps": { + "slots": [ + "items" + ], + "root": "steps_list", + "components": [ + { + "id": "steps_list", + "component": "List", + "direction": "vertical", + "children": { + "$repeat": "items", + "component": "step" + } + }, + { + "id": "step", + "component": "Row", + "align": "start", + "children": [ + "step_marker", + "step_col" + ] + }, + { + "id": "step_marker", + "component": "Text", + "text": { + "$text": "**{$index1}.**" + } + }, + { + "id": "step_col", + "component": "Column", + "weight": 1, + "children": [ + "step_title", + { + "$if": "detail", + "id": "step_detail" + } + ] + }, + { + "id": "step_title", + "component": "Text", + "text": { + "$slot": "title" + } + }, + { + "id": "step_detail", + "component": "Text", + "text": { + "$slot": "detail" + }, + "variant": "caption" + } + ] + }, + "form": { + "slots": [ + "fields" + ], + "root": "form_col", + "components": [ + { + "id": "form_col", + "component": "Column", + "children": { + "$repeat": "fields", + "component": { + "$byInstance": "control" + } + } + } + ], + "fieldVariants": { + "shortText": { + "component": "TextField", + "label": { + "$slot": "label" + }, + "value": { + "$slot": "value" + }, + "variant": "shortText", + "checks": { + "$ifInstance": { + "required": true + }, + "value": [ + { + "condition": { + "call": "required", + "args": { + "value": { + "$slot": "value" + } + } + }, + "message": "Required" + } + ] + } + }, + "longText": { + "component": "TextField", + "label": { + "$slot": "label" + }, + "value": { + "$slot": "value" + }, + "variant": "longText" + }, + "number": { + "component": "TextField", + "label": { + "$slot": "label" + }, + "value": { + "$slot": "value" + }, + "variant": "number" + }, + "obscured": { + "component": "TextField", + "label": { + "$slot": "label" + }, + "value": { + "$slot": "value" + }, + "variant": "obscured" + }, + "toggle": { + "component": "CheckBox", + "label": { + "$slot": "label" + }, + "value": { + "$slot": "value" + } + }, + "choice": { + "component": "ChoicePicker", + "label": { + "$slot": "label" + }, + "variant": "mutuallyExclusive", + "displayStyle": "chips", + "options": { + "$slot": "options" + }, + "value": { + "$slot": "value" + } + }, + "multiChoice": { + "component": "ChoicePicker", + "label": { + "$slot": "label" + }, + "variant": "multipleSelection", + "displayStyle": "checkbox", + "options": { + "$slot": "options" + }, + "value": { + "$slot": "value" + } + }, + "range": { + "component": "Slider", + "label": { + "$slot": "label" + }, + "value": { + "$slot": "value" + }, + "min": { + "$slot": "min" + }, + "max": { + "$slot": "max" + } + }, + "date": { + "component": "DateTimeInput", + "label": { + "$slot": "label" + }, + "value": { + "$slot": "value" + }, + "enableDate": true + } + } + }, + "groups": { + "slots": [ + "groups" + ], + "root": "groups_col", + "components": [ + { + "id": "groups_col", + "component": "Column", + "children": { + "$repeat": "groups", + "component": "group" + } + }, + { + "id": "group", + "component": "Column", + "children": [ + "group_heading", + "group_card" + ] + }, + { + "id": "group_heading", + "component": "Text", + "text": { + "$text": "### {heading}" + } + }, + { + "id": "group_card", + "component": "Card", + "child": "group_list" + }, + { + "id": "group_list", + "component": "List", + "direction": "vertical", + "children": { + "$repeat": "rows", + "component": { + "$byInstance": "row_kind" + } + } + } + ], + "fieldVariants": { + "switch": { + "component": "CheckBox", + "label": { + "$slot": "label" + }, + "value": { + "$slot": "value" + } + }, + "value": { + "component": "Row", + "justify": "spaceBetween", + "children": [ + { + "component": "Text", + "text": { + "$slot": "label" + } + }, + { + "component": "Text", + "text": { + "$slot": "value" + }, + "variant": "caption" + } + ] + }, + "navigation": { + "component": "Button", + "variant": "borderless", + "child": { + "component": "Row", + "justify": "spaceBetween", + "children": [ + { + "component": "Text", + "text": { + "$slot": "label" + } + }, + { + "component": "Icon", + "name": "arrowForward" + } + ] + }, + "action": { + "$event": "open", + "context": { + "$item": true + } + } + }, + "danger": { + "component": "Button", + "variant": "borderless", + "child": { + "component": "Text", + "text": { + "$slot": "label" + } + }, + "action": { + "$event": "label", + "context": { + "$item": true + } + } + } + } + }, + "actions": { + "slots": [ + "buttons" + ], + "knobs": { + "sticky": [ + "yes", + "no" + ] + }, + "root": "actions_row", + "components": [ + { + "id": "actions_row", + "component": "Row", + "justify": "end", + "children": { + "$repeat": "buttons", + "component": "action_button", + "order": "primaryLast" + } + }, + { + "id": "action_button", + "component": "Button", + "variant": { + "$byInstance": "primary", + "true": "primary", + "false": "default" + }, + "child": "action_label", + "action": { + "$event": "label" + } + }, + { + "id": "action_label", + "component": "Text", + "text": { + "$slot": "label" + } + } + ], + "note": "Basic v1 has no destructive variant. A destructive non-primary button is rendered default; a destructive primary is downgraded to default by the one-primary-action rule when stakes >= 2." + }, + "conversation": { + "slots": [ + "messages" + ], + "knobs": { + "self": [ + "", + "none" + ] + }, + "root": "conv_list", + "components": [ + { + "id": "conv_list", + "component": "List", + "direction": "vertical", + "children": { + "$repeat": "messages", + "component": "msg" + } + }, + { + "id": "msg", + "component": "Row", + "align": "start", + "justify": { + "$ifSelf": { + "true": "end", + "false": "start" + } + }, + "children": [ + { + "$if": "avatar", + "$ifSelf": { + "false": "msg_avatar" + } + }, + "msg_card" + ] + }, + { + "id": "msg_avatar", + "component": "Image", + "url": { + "$slot": "avatar" + }, + "variant": "avatar", + "fit": "cover" + }, + { + "id": "msg_card", + "component": "Card", + "child": "msg_col" + }, + { + "id": "msg_col", + "component": "Column", + "children": [ + "msg_head", + "msg_text", + { + "$if": "attachment", + "id": "msg_attachment" + } + ] + }, + { + "id": "msg_head", + "component": "Row", + "justify": "spaceBetween", + "children": [ + "msg_author", + { + "$if": "time", + "id": "msg_time" + } + ] + }, + { + "id": "msg_author", + "component": "Text", + "text": { + "$text": "**{author}**" + }, + "variant": "caption" + }, + { + "id": "msg_time", + "component": "Text", + "text": { + "$slot": "time" + }, + "variant": "caption" + }, + { + "id": "msg_text", + "component": "Text", + "text": { + "$slot": "text" + } + }, + { + "id": "msg_attachment", + "component": "Image", + "url": { + "$slot": "attachment" + }, + "variant": "mediumFeature", + "fit": "cover" + } + ], + "note": "Basic v1 has no bubble, so each message is a Card; self messages are pushed right with Row justify end. $ifSelf compares the message author to the self knob at expansion time." + }, + "compose": { + "slots": [ + "draft", + "sendLabel" + ], + "root": "compose_row", + "components": [ + { + "id": "compose_row", + "component": "Row", + "align": "end", + "children": [ + "compose_field", + "compose_send" + ] + }, + { + "id": "compose_field", + "component": "TextField", + "label": "Message", + "value": { + "$slot": "draft" + }, + "variant": "longText", + "weight": 1 + }, + { + "id": "compose_send", + "component": "Button", + "variant": "primary", + "child": "compose_send_label", + "action": { + "$event": "send", + "context": { + "draft": { + "$slot": "draft" + } + } + } + }, + { + "id": "compose_send_label", + "component": "Text", + "text": { + "$slot": "sendLabel", + "$default": "Send" + } + } + ] + }, + "outcome": { + "slots": [ + "headline", + "detail", + "tone" + ], + "root": "outcome_col", + "components": [ + { + "id": "outcome_col", + "component": "Column", + "align": "center", + "children": [ + "outcome_icon", + "outcome_headline", + { + "$if": "detail", + "id": "outcome_detail" + } + ] + }, + { + "id": "outcome_icon", + "component": "Icon", + "name": { + "$map": "tone", + "success": "check", + "danger": "error", + "neutral": "info" + } + }, + { + "id": "outcome_headline", + "component": "Text", + "text": { + "$text": "## {headline}" + } + }, + { + "id": "outcome_detail", + "component": "Text", + "text": { + "$slot": "detail" + }, + "variant": "caption" + } + ] + } + } +} diff --git a/catalogs/decision/README.md b/catalogs/decision/README.md new file mode 100644 index 0000000000..3d2e1baeef --- /dev/null +++ b/catalogs/decision/README.md @@ -0,0 +1,146 @@ +# Decision layout grammar and catalog patterns + +This directory holds the data files behind the layout stage of the decision +inference format. The format uses a small decision model (a local +cross-encoder, a logprob endpoint, or a mock) to answer short questions about an +intent and a data payload. The answers select a layout archetype, decide which +blocks it shows, and bind payload pointers to the blocks' slots. The files here +describe the archetypes and how each catalog draws them. + +Two kinds of file take part: + +| File | Scope | Who authors it | +| :--- | :--- | :--- | +| `decision/v1/archetypes.json` | Catalog-agnostic. One copy for the whole protocol, validated by `archetype_definition.json`. | The A2UI team, with the decision format. | +| `/patterns.json` | One per catalog, beside its `catalog.json`, validated by `decision/v1/pattern_definition.json`. The basic catalog's file is `catalogs/basic/v1/patterns.json`. | The catalog's maintainers. | + +The grammar names abstract patterns (`page`, `banner`, `picture`, `headline`, +`facts`, `prose`, `collection`, and so on). A pattern file says which real +components of one catalog draw each abstract pattern. A catalog without a +pattern file still works with the decision format. Before any question is +asked, the planner drops every archetype whose required blocks need a pattern +that catalog lacks. + +## Layout + +``` +catalogs/ +├── decision/ +│ ├── README.md +│ └── v1/ +│ ├── archetype_definition.json # JSON Schema for archetypes.json +│ ├── archetypes.json # the grammar +│ └── pattern_definition.json # JSON Schema for any patterns.json +└── basic/ + └── v1/ + ├── catalog.json + └── patterns.json # how basic v1 draws the patterns +``` + +The pattern file is a sidecar: it does not change `catalog.json` or the catalog +definition schema. Its `catalogIds` array lists every catalog id the file +applies to, so one file can serve two catalogs that share a component +vocabulary. The basic file lists both the v1.0 and the v0.9 basic catalog ids. + +## `archetypes.json` + +The grammar has five parts. + +`thresholds` are the probabilities at which a family, an archetype, an expected +block, an optional block, or an instance answer counts as chosen. The section +also holds `reask_below` (answers under it may be asked again with more +context) and the action gate bounds `actionGateFloor` and `actionGateCap`. + +`job` holds the three questions asked for every surface: the `family` choice +(browse, monitor, inspect, act, input, follow) and the `stakes` and `urgency` +scores. + +`archetypes` are ordered lists of blocks for one family. A block entry carries a +mark: `name!` is required and is always present, `name?` is optional and needs +its gate to pass the `optional` threshold, and a bare `name` is expected and +needs the `expected` threshold. An archetype may add a `shape` pre-filter, an +`atLeast` count of blocks that must be present, and a `frame` hint for the page +pattern (`dialog`, `stickyActions`). + +`blocks` describe each block once: the abstract `pattern` it draws, a `shape` +pre-filter, a boolean `gate` question, an optional per-pointer `salience` score, +`anatomy` questions (how the block is drawn), `instance` questions (asked per +element with the payload value filled into the question text), computed +`measures`, the `slots` the block binds, and a `fallback` chain of patterns to +try when the catalog lacks the first. A fallback entry is a pattern name or a +`pattern:variant` form such as `collection:cards`; the same `name:variant` +spelling is used by `requires` entries such as `pattern:collection:grid`. + +`rules` and `lint` are prose. The rules describe behavior the planner applies +(one primary action, the action gate, pointer-once-per-region, and so on). The +lint list states what a loader checks before accepting a grammar. + +Question objects come in three kinds. A `choice` lists `options` (id to +description) or takes them from a slot with `optionsFrom`, and gets an implicit +"none" option unless `allowNone` is false. A `boolean` carries `yes` and `no` +criteria texts. A `score` lists ordered `levels`, and the answer is the expected +level index. `appliesWhen` asks the question only when a slot is bound or has a +given type; `derivedWhen` answers it from key hints without asking; `requires` +offers an option only when the named slots, knob options, `pattern:.` +capabilities, or the `actions_allowed` flag are available. + +Slots list the semantic types they accept in `from`, most preferred first, and +may add `prefer` key hints, `avoidKeys`, `sibling` keys to look for beside the +bound pointer, `repeat` with `max` and `orderBy` for lists, `mutable`, and nested +`fields` for repeated elements. + +## `patterns.json` + +Each pattern names its `slots`, its `knobs` (the anatomy answers it varies by, +with their allowed values), and either one `root` plus `components` list or a +list of `variants`, each with a `when` clause over the knobs and its own `root` +and `components`. A variant without `when` is the default. `fieldVariants` holds +id-less component templates picked per element by `$byInstance`. + +Component templates are ordinary component objects for the catalog, plus +directives whose keys start with `$`: + +| Directive | Value | Meaning | +| :--- | :--- | :--- | +| `$slot` | slot name | A data binding to the pointer bound to that slot. Relative inside `$repeat`. `$default` beside it supplies a literal when the slot is unbound. | +| `$text` | literal with `{slot}` placeholders | A formatted string. When a placeholder is bound the expander emits a `formatString` call; `{$index1}` is the 1-based element index. | +| `$default` | any JSON | The value used when the `$slot` or `$knobValue` beside it resolves to nothing. | +| `$if` | slot name | Emit the component only when the slot is bound. | +| `$ifKnob` | `{knob: [values]}` | Emit the component only when every named knob has one of the listed values. | +| `$ifSelf` | `{"true": ..., "false": ...}` | Pick a value by whether the element's author equals the `self` knob. | +| `$ifInstance` | `{answer: value}` | Emit the enclosing property only when the element's instance answers match. | +| `$byType` | slot name | The sibling key equal to the slot's semantic type names the child id to emit. | +| `$byInstance` | instance answer name | Pick a `fieldVariants` entry (or a sibling key) by the element's answer. | +| `$repeat` | repeated slot name | Turn `children` into a template child list bound to the slot's array; the sibling `component` names the template. | +| `$map` | knob or answer name | The sibling key equal to its value is the literal to emit. | +| `$event` | event name or slot | An action `{"event": {"name": ...}}`; `context` beside it is passed through. | +| `$blocks` | `true` | In the page pattern, where the block roots go, in archetype order. | +| `$knobValue` | `knob.property` | A value looked up in the plan, with `$default` when absent. | +| `$item` | `true` | Inside `$repeat`, the current element, bound as event context. | +| `$index1` | `true` | Inside `$repeat`, the 1-based index of the current element. | + +Component ids in a pattern are local. The expander prefixes them with the block +id so a pattern can appear more than once on a surface. Headings use Markdown +(`##` for the page title, `###` for block headings) because the basic catalog's +`Text` has no heading variant. + +## How an SDK uses these files + +An installed package cannot read this repository, so each SDK vendors a copy of +the grammar, the two schemas, and the pattern files for the catalogs it bundles. +The Python SDK keeps them under +`python/a2ui_agent/src/a2ui/inference_formats/decision/assets/`, copies them +with `python/a2ui_agent/scripts/sync_decision_assets.py`, and has a test that +fails when a vendored copy differs from the file here. Other SDKs should do the +same: treat the files in `catalogs/` as the source of truth and the vendored +copies as build artifacts. + +At load time an SDK validates `archetypes.json` against +`archetype_definition.json`, runs the lint checks listed in the grammar, and +validates each `patterns.json` against `pattern_definition.json`. A grammar or +pattern file that fails is rejected rather than used in part. + +To add a pattern file for another catalog, create `patterns.json` beside that +catalog's `catalog.json`, set `catalogIds` to the catalog's id, implement the +patterns the catalog can draw with its own components, and leave out the rest. +Archetypes that need a missing pattern are not offered for that catalog. diff --git a/catalogs/decision/v1/archetype_definition.json b/catalogs/decision/v1/archetype_definition.json new file mode 100644 index 0000000000..ca918f3bd9 --- /dev/null +++ b/catalogs/decision/v1/archetype_definition.json @@ -0,0 +1,321 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://a2ui.org/specification/v1_0/decision/archetype_definition.json", + "title": "A2UI decision layout archetype grammar", + "description": "Catalog-agnostic grammar of layout archetypes, blocks, questions, slots, and rules consumed by the decision inference format.", + "type": "object", + "required": ["version", "thresholds", "job", "archetypes", "blocks"], + "additionalProperties": false, + "properties": { + "$schema": { "type": "string" }, + "version": { "type": "string", "minLength": 1 }, + "thresholds": { "$ref": "#/$defs/thresholds" }, + "job": { "$ref": "#/$defs/job" }, + "archetypes": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/archetype" } + }, + "blocks": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/block" } + }, + "rules": { + "type": "array", + "items": { "$ref": "#/$defs/rule" } + }, + "lint": { + "type": "array", + "items": { "type": "string" } + } + }, + "$defs": { + "unitInterval": { "type": "number", "minimum": 0, "maximum": 1 }, + "identifier": { "type": "string", "pattern": "^[a-z_]+$" }, + "blockMark": { + "type": "string", + "pattern": "^[a-z_]+[!?]?$", + "description": "A block id with an optional mark: `!` required, `?` optional, bare expected." + }, + "stringList": { + "type": "array", + "items": { "type": "string" } + }, + "stringMap": { + "type": "object", + "additionalProperties": { "type": "string" } + }, + "range": { + "type": "array", + "description": "An inclusive [min, max] pair; null leaves that end open.", + "prefixItems": [ + { "type": ["integer", "null"] }, + { "type": ["integer", "null"] } + ], + "minItems": 2, + "maxItems": 2, + "items": false + }, + "thresholds": { + "type": "object", + "required": [ + "family", + "archetype", + "expected", + "optional", + "instance", + "reask_below", + "actionGateFloor", + "actionGateCap" + ], + "additionalProperties": false, + "properties": { + "family": { "$ref": "#/$defs/unitInterval" }, + "archetype": { "$ref": "#/$defs/unitInterval" }, + "expected": { "$ref": "#/$defs/unitInterval" }, + "optional": { "$ref": "#/$defs/unitInterval" }, + "instance": { "$ref": "#/$defs/unitInterval" }, + "reask_below": { "$ref": "#/$defs/unitInterval" }, + "actionGateFloor": { "$ref": "#/$defs/unitInterval" }, + "actionGateCap": { "$ref": "#/$defs/unitInterval" } + } + }, + "job": { + "type": "object", + "required": ["family", "stakes", "urgency"], + "additionalProperties": false, + "properties": { + "family": { "$ref": "#/$defs/choiceQuestion" }, + "stakes": { "$ref": "#/$defs/scoreQuestion" }, + "urgency": { "$ref": "#/$defs/scoreQuestion" } + } + }, + "shapeFilter": { + "type": "object", + "description": "Deterministic payload pre-filter evaluated before a question enters the batch.", + "additionalProperties": false, + "properties": { + "pointers": { "$ref": "#/$defs/stringList" }, + "arrayLength": { "$ref": "#/$defs/range" }, + "elementTypes": { "$ref": "#/$defs/stringList" }, + "elementKeys": { "$ref": "#/$defs/stringList" }, + "mutable": { "type": "boolean" }, + "proseLength": { + "type": "array", + "items": { "enum": ["line", "blurb", "summary", "article"] } + }, + "count": { "$ref": "#/$defs/range" }, + "actions_allowed": { "type": "boolean" } + } + }, + "archetype": { + "type": "object", + "required": ["id", "family", "criteria", "blocks"], + "additionalProperties": false, + "properties": { + "id": { "$ref": "#/$defs/identifier" }, + "family": { "$ref": "#/$defs/identifier" }, + "criteria": { "type": "string", "minLength": 1 }, + "blocks": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/blockMark" } + }, + "shape": { "$ref": "#/$defs/shapeFilter" }, + "atLeast": { "type": "integer", "minimum": 1 }, + "frame": { + "type": "object", + "additionalProperties": { "type": "boolean" } + } + } + }, + "appliesWhen": { + "type": "object", + "description": "Slot name to semantic type(s) or the word `bound`; the question is asked only when it holds.", + "additionalProperties": { + "oneOf": [{ "type": "string" }, { "$ref": "#/$defs/stringList" }] + } + }, + "derivedWhen": { + "type": "object", + "description": "Deterministic answers keyed by hint source; the question is skipped when one matches.", + "additionalProperties": { "type": "object" } + }, + "requires": { + "type": "object", + "description": "Option id to the slots, knob options, pattern variants, or capability flags it needs.", + "additionalProperties": { "$ref": "#/$defs/stringList" } + }, + "questionBase": { + "type": "object", + "required": ["kind", "question"], + "properties": { + "kind": { "enum": ["choice", "boolean", "score"] }, + "question": { "type": "string", "minLength": 1 }, + "appliesWhen": { "$ref": "#/$defs/appliesWhen" }, + "derivedWhen": { "$ref": "#/$defs/derivedWhen" }, + "note": { "type": "string" } + } + }, + "choiceQuestion": { + "allOf": [{ "$ref": "#/$defs/questionBase" }], + "type": "object", + "additionalProperties": false, + "properties": { + "kind": { "const": "choice" }, + "question": true, + "appliesWhen": true, + "derivedWhen": true, + "note": true, + "options": { + "type": "object", + "minProperties": 1, + "propertyNames": { "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, + "additionalProperties": { "type": "string" } + }, + "optionsFrom": { "type": "string", "minLength": 1 }, + "requires": { "$ref": "#/$defs/requires" }, + "allowNone": { "type": "boolean" } + }, + "oneOf": [{ "required": ["options"] }, { "required": ["optionsFrom"] }] + }, + "booleanQuestion": { + "allOf": [{ "$ref": "#/$defs/questionBase" }], + "type": "object", + "required": ["yes", "no"], + "additionalProperties": false, + "properties": { + "kind": { "const": "boolean" }, + "question": true, + "appliesWhen": true, + "derivedWhen": true, + "note": true, + "yes": { "type": "string", "minLength": 1 }, + "no": { "type": "string", "minLength": 1 } + } + }, + "scoreQuestion": { + "allOf": [{ "$ref": "#/$defs/questionBase" }], + "type": "object", + "required": ["levels"], + "additionalProperties": false, + "properties": { + "kind": { "const": "score" }, + "question": true, + "appliesWhen": true, + "derivedWhen": true, + "note": true, + "levels": { + "type": "array", + "minItems": 2, + "items": { "type": "string", "minLength": 1 } + }, + "perPointer": { "type": "boolean" }, + "select": { + "type": "object", + "additionalProperties": false, + "properties": { + "min": { "type": "integer", "minimum": 0 }, + "max": { "type": "integer", "minimum": 1 }, + "aboveLevel": { "type": "number", "minimum": 0 } + } + } + } + }, + "question": { + "oneOf": [ + { "$ref": "#/$defs/choiceQuestion" }, + { "$ref": "#/$defs/booleanQuestion" }, + { "$ref": "#/$defs/scoreQuestion" } + ] + }, + "slot": { + "type": "object", + "required": ["from"], + "additionalProperties": false, + "properties": { + "from": { + "type": "array", + "minItems": 1, + "items": { "type": "string", "minLength": 1 } + }, + "required": { "type": "boolean" }, + "repeat": { "type": "boolean" }, + "max": { "type": "integer", "minimum": 1 }, + "prefer": { "$ref": "#/$defs/stringList" }, + "avoidKeys": { "$ref": "#/$defs/stringList" }, + "sibling": { "$ref": "#/$defs/stringList" }, + "orderBy": { "type": "string", "minLength": 1 }, + "mutable": { "type": "boolean" }, + "elementTypes": { "$ref": "#/$defs/stringList" }, + "default": true, + "note": { "type": "string" }, + "fields": { + "type": "object", + "propertyNames": { "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, + "additionalProperties": { "$ref": "#/$defs/slot" } + } + } + }, + "measure": { + "type": "object", + "required": ["derivedFrom", "levels"], + "additionalProperties": false, + "properties": { + "derivedFrom": { "type": "string", "minLength": 1 }, + "levels": { + "type": "object", + "minProperties": 1, + "additionalProperties": { "$ref": "#/$defs/range" } + }, + "note": { "type": "string" } + } + }, + "block": { + "type": "object", + "required": ["id", "pattern", "fallback"], + "additionalProperties": false, + "properties": { + "id": { "$ref": "#/$defs/identifier" }, + "pattern": { "$ref": "#/$defs/identifier" }, + "shape": { "$ref": "#/$defs/shapeFilter" }, + "gate": { "$ref": "#/$defs/booleanQuestion" }, + "salience": { "$ref": "#/$defs/scoreQuestion" }, + "anatomy": { + "type": "object", + "propertyNames": { "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, + "additionalProperties": { "$ref": "#/$defs/question" } + }, + "instance": { + "type": "object", + "propertyNames": { "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, + "additionalProperties": { "$ref": "#/$defs/question" } + }, + "measures": { + "type": "object", + "additionalProperties": { "$ref": "#/$defs/measure" } + }, + "slots": { + "type": "object", + "propertyNames": { "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, + "additionalProperties": { "$ref": "#/$defs/slot" } + }, + "fallback": { + "type": "array", + "minItems": 1, + "items": { "type": "string", "pattern": "^[a-z_-]+(:[a-z_]+)?$" } + } + } + }, + "rule": { + "type": "object", + "required": ["id", "rule"], + "additionalProperties": false, + "properties": { + "id": { "type": "string", "pattern": "^[a-z][a-z0-9-]*$" }, + "rule": { "type": "string", "minLength": 1 } + } + } + } +} diff --git a/catalogs/decision/v1/archetypes.json b/catalogs/decision/v1/archetypes.json new file mode 100644 index 0000000000..7baf58fba5 --- /dev/null +++ b/catalogs/decision/v1/archetypes.json @@ -0,0 +1,1813 @@ +{ + "$schema": "https://a2ui.org/specification/v1_0/decision/archetype_definition.json", + "version": "1", + "thresholds": { + "family": 0.4, + "archetype": 0.4, + "expected": 0.5, + "optional": 0.75, + "instance": 0.5, + "reask_below": 0.75, + "actionGateFloor": 0.7, + "actionGateCap": 0.95 + }, + "job": { + "family": { + "kind": "choice", + "question": "What is the person here to do?", + "options": { + "browse": "Look through a set of similar things: results, a catalogue, a feed, an inbox, a directory, records.", + "monitor": "See numbers and status at a glance: usage, health, progress, balances, today's summary.", + "inspect": "Understand one thing in depth: a product, a place, a person, an order, an event, an article.", + "act": "Commit to or confirm one action, or review something just before or just after it happens.", + "input": "Provide or change information: fill in details, adjust settings, answer questions.", + "follow": "Do something step by step: a how-to, a recipe, a checklist, troubleshooting." + } + }, + "stakes": { + "kind": "score", + "question": "If this goes wrong, how bad is it for the person?", + "levels": [ + "Nothing is at stake; the person is only looking.", + "A small inconvenience that is easy to undo.", + "Money, time, or data is involved; undoing it takes effort.", + "Irreversible: a deletion, a payment, a commitment that cannot be taken back." + ] + }, + "urgency": { + "kind": "score", + "question": "How quickly does the person need to act on what they see?", + "levels": [ + "No hurry; they are browsing or reading.", + "Soon; something is due or pending.", + "Right now; something is failing, expiring, or happening." + ] + } + }, + "archetypes": [ + { + "id": "feed", + "family": "browse", + "criteria": "A collection to look through, where the items matter more than any one of them.", + "blocks": [ + "banner?", + "filters?", + "picture?", + "collection!" + ] + }, + { + "id": "compare", + "family": "browse", + "criteria": "A few options the person is weighing against each other, with the same attributes for each.", + "shape": { + "arrayLength": [ + 2, + 5 + ] + }, + "blocks": [ + "banner?", + "prose?", + "comparison!", + "actions?" + ] + }, + { + "id": "dashboard", + "family": "monitor", + "criteria": "Numbers and status at a glance, with the most important figure first.", + "blocks": [ + "banner?", + "headline!", + "chart?", + "facts?", + "media?", + "collection?" + ], + "atLeast": 2 + }, + { + "id": "detail", + "family": "inspect", + "criteria": "One thing in depth: what it is, its key figures, its description, its particulars, what it contains, what can be done with it.", + "blocks": [ + "picture?", + "banner?", + "headline?", + "prose", + "facts", + "media?", + "collection?", + "actions?" + ], + "atLeast": 2 + }, + { + "id": "result", + "family": "act", + "criteria": "The outcome of something the person just did: success, failure, a receipt, nothing found.", + "blocks": [ + "outcome!", + "facts?", + "steps?", + "actions" + ] + }, + { + "id": "confirm", + "family": "act", + "criteria": "One short decision about one thing, asked before it happens: confirm, delete, approve, allow.", + "blocks": [ + "prose", + "facts?", + "actions!" + ], + "frame": { + "dialog": true + } + }, + { + "id": "checkout", + "family": "act", + "criteria": "Review and commit: a cart, an order or booking summary with totals, a payment.", + "blocks": [ + "banner?", + "collection", + "facts!", + "form?", + "actions!" + ], + "frame": { + "stickyActions": true + } + }, + { + "id": "form", + "family": "input", + "criteria": "Data entry: creating or editing a record, a booking, a survey, a request with several fields.", + "shape": { + "mutable": true + }, + "blocks": [ + "prose?", + "form!", + "actions" + ] + }, + { + "id": "settings", + "family": "input", + "criteria": "Preferences, account options, or configuration, arranged as groups of rows that each hold one setting.", + "shape": { + "mutable": true + }, + "blocks": [ + "banner?", + "groups!", + "actions?" + ] + }, + { + "id": "guide", + "family": "follow", + "criteria": "Instructions followed in order: a how-to, a method, troubleshooting, an onboarding checklist.", + "blocks": [ + "picture?", + "prose?", + "facts?", + "steps!", + "actions?" + ] + }, + { + "id": "article", + "family": "inspect", + "criteria": "Something to read: an explanation, a story, a report, documentation, where the text is the point.", + "shape": { + "proseLength": [ + "summary", + "article" + ] + }, + "blocks": [ + "picture?", + "prose!", + "facts?", + "collection?", + "actions?" + ] + }, + { + "id": "timeline", + "family": "inspect", + "criteria": "What happened, in order: shipment events, an audit trail, a build's stages, a patient's history, a project's milestones.", + "shape": { + "pointers": [ + "array" + ], + "elementTypes": [ + "datetime", + "date", + "time", + "relative_time" + ] + }, + "blocks": [ + "banner?", + "headline?", + "timeline!", + "actions?" + ] + }, + { + "id": "location", + "family": "inspect", + "criteria": "A place, or something at a place: where it is, how to get there, what is nearby.", + "shape": { + "pointers": [ + "location", + "address" + ] + }, + "blocks": [ + "picture?", + "map!", + "facts", + "collection?", + "actions?" + ] + }, + { + "id": "chat", + "family": "browse", + "criteria": "A conversation: messages between people or with an assistant, in order, each with who said it and when.", + "shape": { + "pointers": [ + "array" + ], + "elementKeys": [ + "author", + "sender", + "from", + "role", + "speaker" + ] + }, + "blocks": [ + "banner?", + "conversation!", + "compose?" + ] + } + ], + "blocks": [ + { + "id": "banner", + "pattern": "banner", + "gate": { + "kind": "boolean", + "question": "Does something here need the person's attention before anything else?", + "yes": "A warning, an outage, a deadline, an error, an offer about to expire, or a success to acknowledge.", + "no": "Nothing unusual is going on; this is business as usual." + }, + "slots": { + "title": { + "from": [ + "string", + "enum" + ], + "required": true + }, + "text": { + "from": [ + "string", + "long_text" + ] + } + }, + "instance": { + "tone": { + "kind": "choice", + "question": "For the person looking at this, what kind of news is {title}?", + "options": { + "success": "Good news or a healthy state: done, available, on time, paid, active.", + "warning": "Needs attention soon: low, delayed, pending, degraded, expiring.", + "danger": "Bad news: failed, overdue, critical, cancelled, offline.", + "neutral": "Plain information that is neither good nor bad." + } + } + }, + "fallback": [ + "banner", + "prose" + ] + }, + { + "id": "picture", + "pattern": "picture", + "shape": { + "pointers": [ + "image_url", + "media_object" + ] + }, + "gate": { + "kind": "boolean", + "question": "Should a picture lead this?", + "yes": "One visual subject leads: a place, dish, product, property, animal, trip, event, person, or artwork.", + "no": "The subject has no look: an order, an account, a transaction, a setting, a set of figures." + }, + "slots": { + "picture": { + "from": [ + "image_url", + "media_object" + ], + "required": true, + "avoidKeys": [ + "logo", + "icon", + "avatar", + "thumbnail" + ] + }, + "caption": { + "from": [ + "string", + "title" + ] + }, + "width": { + "from": [ + "integer" + ], + "sibling": [ + "width", + "w" + ] + }, + "height": { + "from": [ + "integer" + ], + "sibling": [ + "height", + "h" + ] + }, + "aspectRatio": { + "from": [ + "ratio", + "string" + ], + "sibling": [ + "aspectRatio", + "aspect" + ] + }, + "orientation": { + "from": [ + "enum" + ], + "sibling": [ + "orientation" + ] + } + }, + "anatomy": { + "framing": { + "kind": "choice", + "question": "What kind of picture is this, and how should it be framed?", + "options": { + "banner": "A wide scene that can be cropped: a place, a landscape, a venue, a dish on a table, a product in use.", + "portrait": "A person or a face: shown whole, square or round, never cropped at the head.", + "object": "A thing on its own that must not be cropped: a product on a plain background, a logo, a diagram, a chart image.", + "poster": "Taller than wide and read whole: a book cover, a poster, a document page, a phone screenshot." + }, + "derivedWhen": { + "keyHint": { + "logo": "object", + "icon": "object", + "avatar": "portrait", + "portrait": "portrait", + "cover": "poster", + "poster": "poster" + }, + "aspectRatio": { + "under": { + "0.8": "poster" + }, + "over": { + "1.5": "banner" + } + } + } + }, + "prominence": { + "kind": "score", + "question": "How much of the screen should this picture take?", + "levels": [ + "A small mark beside the title: a logo or avatar.", + "A supporting picture beside the text, about a third of the width.", + "A leading picture across the full width above the text.", + "The picture is the content; everything else is a caption." + ] + } + }, + "fallback": [ + "picture" + ] + }, + { + "id": "filters", + "pattern": "filters", + "shape": { + "pointers": [ + "array" + ], + "arrayLength": [ + 8, + null + ], + "mutable": true + }, + "gate": { + "kind": "boolean", + "question": "Will the person need to search or narrow down what is shown?", + "yes": "There are many items, more than fit on a screen, in recognisable categories.", + "no": "There are only a few items, or nothing to narrow." + }, + "slots": { + "query": { + "from": [ + "string" + ], + "mutable": true + }, + "categories": { + "from": [ + "enum", + "status", + "array" + ], + "note": "the distinct values of an enum field across the items, or a sibling list of category names; how they are drawn is the catalog's choice" + } + }, + "fallback": [ + "filters" + ] + }, + { + "id": "headline", + "pattern": "headline", + "shape": { + "pointers": [ + "number", + "integer", + "count", + "currency", + "percent", + "ratio", + "quantity", + "rating", + "bounded", + "duration", + "status", + "enum", + "boolean", + "time", + "datetime", + "relative_time" + ], + "count": [ + 1, + null + ] + }, + "gate": { + "kind": "boolean", + "question": "Are there a few values the person wants at a glance before anything else?", + "yes": "Key figures or states such as totals, counts, rates, balances, scores, durations, a status, a next time, on or off.", + "no": "The values are details to look up, not headlines, or there are too many for any to stand out." + }, + "salience": { + "kind": "score", + "perPointer": true, + "question": "How important is {label} to the person at a glance?", + "levels": [ + "A detail they might look up.", + "Useful context.", + "One of the main things they came to see.", + "The single most important value here." + ], + "select": { + "min": 1, + "max": 6, + "aboveLevel": 1.5 + } + }, + "slots": { + "items": { + "repeat": true, + "from": [ + "number", + "integer", + "count", + "currency", + "percent", + "ratio", + "quantity", + "rating", + "bounded", + "duration", + "status", + "enum", + "boolean", + "time", + "datetime", + "relative_time" + ], + "max": 6, + "orderBy": "salience", + "fields": { + "label": { + "from": [ + "key" + ] + }, + "value": { + "from": [ + "any" + ], + "required": true + }, + "delta": { + "from": [ + "number", + "percent" + ], + "sibling": [ + "delta", + "change", + "diff", + "previous" + ] + }, + "min": { + "from": [ + "number" + ], + "sibling": [ + "min" + ] + }, + "max": { + "from": [ + "number" + ], + "sibling": [ + "max", + "total", + "limit" + ] + } + } + } + }, + "anatomy": { + "deltas": { + "kind": "boolean", + "question": "Do these values change over time in a way the person tracks?", + "yes": "Usage, spending, revenue, health, or performance compared with a previous period or a target.", + "no": "Fixed figures such as counts or specifications, with nothing to compare against." + }, + "gauge": { + "kind": "boolean", + "appliesWhen": { + "value": "bounded" + }, + "question": "Is {label} read as a level between empty and full?", + "yes": "Progress, capacity, battery, utilization, a score out of a maximum.", + "no": "A plain number that happens to have bounds." + } + }, + "instance": { + "news": { + "kind": "choice", + "appliesWhen": { + "delta": "bound" + }, + "question": "For the person looking at this, is the change in {label} good or bad news?", + "options": { + "good": "The figure moved the way the person wants it to.", + "bad": "The figure moved the way the person does not want.", + "neutral": "Neither; it is just a change." + } + }, + "state_tone": { + "kind": "choice", + "appliesWhen": { + "value": [ + "status", + "enum", + "boolean" + ] + }, + "question": "Is {label} being {value} good, bad, or neutral for the person?", + "options": { + "success": "Good: active, healthy, on, done, in stock.", + "warning": "Needs attention: pending, low, degraded.", + "danger": "Bad: failed, offline, overdue.", + "neutral": "Neither." + } + } + }, + "fallback": [ + "headline", + "facts" + ] + }, + { + "id": "media", + "pattern": "media", + "shape": { + "pointers": [ + "video_url", + "audio_url" + ] + }, + "gate": { + "kind": "boolean", + "question": "Is there something to play here?", + "yes": "A video, an episode, a recording, a song, a voice note.", + "no": "The link is to a file or page, not something played in place." + }, + "slots": { + "source": { + "from": [ + "video_url", + "audio_url" + ], + "required": true + }, + "poster": { + "from": [ + "image_url" + ], + "sibling": [ + "poster", + "thumbnail", + "artwork" + ] + }, + "title": { + "from": [ + "title", + "string" + ] + }, + "duration": { + "from": [ + "duration" + ] + } + }, + "fallback": [ + "media", + "facts" + ] + }, + { + "id": "chart", + "pattern": "chart", + "shape": { + "pointers": [ + "array" + ], + "elementTypes": [ + "number", + "date", + "datetime" + ] + }, + "gate": { + "kind": "boolean", + "question": "Is there a series of values over time or categories that is easier to read as a chart than as numbers?", + "yes": "A trend, a history, a breakdown by category, a comparison of several series.", + "no": "Single figures, or a list of records that are not a series." + }, + "slots": { + "series": { + "from": [ + "array" + ], + "required": true + }, + "title": { + "from": [ + "key", + "string" + ] + } + }, + "fallback": [ + "chart", + "headline", + "collection" + ] + }, + { + "id": "facts", + "pattern": "facts", + "shape": { + "pointers": [ + "string", + "name", + "title", + "identifier", + "number", + "integer", + "count", + "quantity", + "percent", + "percentage", + "rating", + "bounded", + "date", + "time", + "datetime", + "relative_time", + "duration", + "enum", + "status", + "email", + "phone", + "url", + "place_name", + "address", + "boolean", + "currency" + ], + "count": [ + 1, + null + ] + }, + "gate": { + "kind": "boolean", + "question": "Are there particulars the person would look up, such as a reference, a date, an address, a status, a total?", + "yes": "Labelled values that are read, not acted on: order number, date, address, status, total, owner.", + "no": "There are no such particulars, or they are already shown as headline figures." + }, + "slots": { + "rows": { + "repeat": true, + "from": [ + "string", + "name", + "title", + "identifier", + "number", + "integer", + "count", + "quantity", + "percent", + "percentage", + "rating", + "bounded", + "date", + "time", + "datetime", + "relative_time", + "duration", + "enum", + "status", + "email", + "phone", + "url", + "place_name", + "address", + "boolean", + "currency" + ], + "max": 8, + "orderBy": "salience", + "fields": { + "label": { + "from": [ + "key" + ], + "required": true + }, + "value": { + "from": [ + "any" + ], + "required": true + } + } + } + }, + "fallback": [ + "facts", + "prose" + ] + }, + { + "id": "prose", + "pattern": "prose", + "shape": { + "pointers": [ + "long_text", + "string" + ] + }, + "gate": { + "kind": "boolean", + "question": "Is there something to read, a sentence or more, that explains or describes?", + "yes": "A description, a summary, an explanation, a message, terms, a note.", + "no": "Only short labels and values; nothing to read in sentences." + }, + "slots": { + "heading": { + "from": [ + "title", + "string" + ] + }, + "body": { + "from": [ + "long_text", + "markdown", + "string" + ], + "required": true + } + }, + "measures": { + "length": { + "derivedFrom": "body.hints.wordCount", + "levels": { + "line": [ + 0, + 15 + ], + "blurb": [ + 15, + 60 + ], + "summary": [ + 60, + 200 + ], + "article": [ + 200, + null + ] + }, + "note": "Computed, never asked. Patterns may vary by it (an article gets a heading and may be collapsed behind a Read more where the catalog can; a line is set inline). The rules use it too: article-length prose moves to the front of detail and suppresses the picture's prominence to supporting." + } + }, + "fallback": [ + "prose" + ] + }, + { + "id": "collection", + "pattern": "collection", + "shape": { + "pointers": [ + "array" + ], + "elementTypes": [ + "object", + "string" + ] + }, + "gate": { + "kind": "boolean", + "question": "Are there several similar items the person would scan or pick from?", + "yes": "Results, products, people, records, messages, line items, episodes, devices, or any set of comparable things.", + "no": "This is about one thing, or the list is only a series of numbers." + }, + "anatomy": { + "layout": { + "kind": "choice", + "question": "How should these items be laid out?", + "options": { + "rows": "Dense rows to scan quickly: text matters more than pictures, or there are many items.", + "cards": "Large picture cards, one per row: the person chooses mostly by look among a few rich items.", + "grid": "A grid of small picture tiles: many visual items browsed casually.", + "reel": "A sideways-scrolling shelf of picture cards: a short set of suggestions or a gallery." + }, + "requires": { + "cards": [ + "picture" + ], + "grid": [ + "picture", + "pattern:collection:grid" + ], + "reel": [ + "picture" + ] + }, + "note": "pattern:. means the option is offered only when the catalog's pattern has that variant, so a catalog that would draw grid as a reel is not asked about grid." + }, + "leading": { + "kind": "choice", + "question": "What should lead each item, so the person knows what kind of thing it is?", + "options": { + "thumbnail": "A small picture of the item.", + "avatar": "A picture of a person.", + "icon": "A symbol for the item's kind or state.", + "number": "Its rank or position.", + "none": "Nothing; the title is enough." + } + }, + "trailing": { + "kind": "choice", + "question": "What should end each item?", + "options": { + "chevron": "A way in: tapping the item opens it.", + "button": "One action on each item, such as Book, Add, Play.", + "value": "A figure or status read at a glance.", + "none": "Nothing." + }, + "requires": { + "button": [ + "actions_allowed" + ] + } + } + }, + "slots": { + "items": { + "repeat": true, + "from": [ + "array" + ], + "required": true, + "fields": { + "headline": { + "from": [ + "title", + "name", + "string" + ], + "required": true, + "prefer": [ + "name", + "title", + "label" + ] + }, + "supporting": { + "from": [ + "string", + "long_text", + "markdown", + "code", + "place_name", + "address", + "email", + "url", + "quantity", + "duration", + "date", + "number", + "integer", + "count" + ], + "prefer": [ + "subtitle", + "summary", + "description", + "snippet", + "detail", + "body", + "caption", + "location", + "address", + "elevation" + ], + "avoidKeys": [ + "id", + "currency" + ] + }, + "picture": { + "from": [ + "image_url", + "media_object" + ] + }, + "meta": { + "from": [ + "currency", + "quantity", + "date", + "time", + "datetime", + "relative_time", + "duration", + "distance", + "place_name", + "count", + "integer", + "number", + "percent", + "percentage", + "url", + "string", + "long_text", + "code", + "status", + "enum" + ], + "prefer": [ + "price", + "priceFrom", + "amount", + "cost", + "total", + "date", + "time", + "arrives", + "duration", + "distance", + "openRuns", + "runs", + "url", + "link", + "href" + ], + "max": 2, + "orderBy": "salience" + }, + "badge": { + "from": [ + "status", + "enum", + "boolean" + ], + "prefer": [ + "status", + "state", + "availability", + "stock", + "badge", + "tag", + "category", + "role" + ], + "avoidKeys": [ + "id", + "currency" + ] + }, + "rating": { + "from": [ + "rating", + "number" + ], + "prefer": [ + "rating", + "score", + "stars" + ] + } + } + } + }, + "instance": { + "badge_tone": { + "kind": "choice", + "appliesWhen": { + "badge": "bound" + }, + "question": "Is {badge} good, bad, or neutral news for the person?", + "options": { + "success": "Good: active, done, in stock, on time.", + "warning": "Needs attention: pending, low, delayed.", + "danger": "Bad: failed, cancelled, overdue.", + "neutral": "Neither." + } + } + }, + "fallback": [ + "collection" + ] + }, + { + "id": "comparison", + "pattern": "comparison", + "shape": { + "pointers": [ + "array" + ], + "arrayLength": [ + 2, + 5 + ], + "elementTypes": [ + "object" + ] + }, + "gate": { + "kind": "boolean", + "question": "Is the person choosing among these few options by comparing the same attributes?", + "yes": "Plans, flights, products, candidates, quotes: a handful of options with price, time, or features side by side.", + "no": "They are not alternatives to each other, or there are too many to compare side by side." + }, + "slots": { + "options": { + "repeat": true, + "from": [ + "array" + ], + "required": true, + "fields": { + "headline": { + "from": [ + "string" + ], + "required": true + }, + "picture": { + "from": [ + "image_url" + ] + }, + "attributes": { + "from": [ + "any" + ], + "repeat": true, + "max": 5 + }, + "highlight": { + "from": [ + "currency", + "number", + "date" + ] + } + } + } + }, + "instance": { + "headline_attribute": { + "kind": "choice", + "question": "Which attribute will the person decide on first?", + "optionsFrom": "attributes" + } + }, + "fallback": [ + "comparison", + "collection:cards", + "collection:rows" + ] + }, + { + "id": "steps", + "pattern": "steps", + "shape": { + "pointers": [ + "array" + ], + "elementTypes": [ + "string", + "object" + ] + }, + "gate": { + "kind": "boolean", + "question": "Are these things done in order, one after another?", + "yes": "Instructions, a method, a checklist, stages of a process, a timeline of what happened.", + "no": "They are independent items with no order to follow." + }, + "slots": { + "items": { + "repeat": true, + "from": [ + "array" + ], + "required": true, + "fields": { + "title": { + "from": [ + "title", + "name", + "string", + "long_text" + ], + "required": true + }, + "detail": { + "from": [ + "long_text", + "string" + ] + }, + "done": { + "from": [ + "boolean" + ] + } + } + } + }, + "fallback": [ + "steps", + "collection:rows" + ] + }, + { + "id": "form", + "pattern": "form", + "shape": { + "mutable": true + }, + "gate": { + "kind": "boolean", + "question": "Does the person need to type or choose values here?", + "yes": "Details to fill in: name, date, amount, notes, a choice among options.", + "no": "Everything is read-only, or the only choice is a button." + }, + "slots": { + "fields": { + "repeat": true, + "from": [ + "mutable" + ], + "required": true, + "fields": { + "label": { + "from": [ + "key" + ], + "required": true + }, + "value": { + "from": [ + "any" + ], + "required": true + }, + "options": { + "from": [ + "enum", + "array" + ] + }, + "min": { + "from": [ + "number" + ], + "sibling": [ + "min" + ] + }, + "max": { + "from": [ + "number" + ], + "sibling": [ + "max", + "limit" + ] + } + } + } + }, + "instance": { + "control": { + "kind": "choice", + "question": "What kind of input is {label}?", + "options": { + "shortText": "A word or a line: a name, a title, a code.", + "longText": "Several lines: notes, a message, a description.", + "number": "A quantity or amount typed as digits.", + "obscured": "A secret: a password or PIN.", + "toggle": "On or off, and it takes effect at once.", + "choice": "One of a few named options.", + "multiChoice": "Any number of named options.", + "range": "A value between a minimum and a maximum, where the exact number matters less than the position.", + "date": "A date, a time, or both." + }, + "requires": { + "choice": [ + "options" + ], + "multiChoice": [ + "options" + ], + "range": [ + "min", + "max" + ] + } + }, + "required": { + "kind": "boolean", + "question": "Must {label} be filled in before this can be submitted?", + "yes": "The task cannot proceed without it.", + "no": "It is optional or has a sensible default." + } + }, + "fallback": [ + "form", + "facts" + ] + }, + { + "id": "groups", + "pattern": "groups", + "shape": { + "mutable": true, + "pointers": [ + "object" + ] + }, + "gate": { + "kind": "boolean", + "question": "Are these settings, each one a row the person can read and change?", + "yes": "Preferences and options grouped by topic: notifications, privacy, playback, account.", + "no": "This is a single form to fill in and submit, not a set of standing preferences." + }, + "slots": { + "groups": { + "repeat": true, + "from": [ + "object" + ], + "required": true, + "fields": { + "heading": { + "from": [ + "key" + ], + "required": true + }, + "rows": { + "repeat": true, + "from": [ + "mutable" + ], + "fields": { + "label": { + "from": [ + "key" + ], + "required": true + }, + "value": { + "from": [ + "any" + ], + "required": true + } + } + } + } + } + }, + "instance": { + "row_kind": { + "kind": "choice", + "question": "What kind of row is {label}?", + "options": { + "switch": "One setting that is on or off and takes effect at once.", + "value": "A setting whose current value is shown and opens a picker of options when tapped.", + "navigation": "A way into another page of settings or information.", + "danger": "An action that removes or disconnects something: sign out, delete account." + } + } + }, + "fallback": [ + "groups", + "form" + ] + }, + { + "id": "actions", + "pattern": "actions", + "shape": { + "actions_allowed": true + }, + "gate": { + "kind": "boolean", + "question": "Is there something the person would do next from here, with a button?", + "yes": "Buy, book, save, send, confirm, retry, open, share.", + "no": "Nothing to do; the person only reads this." + }, + "slots": { + "buttons": { + "repeat": true, + "from": [ + "action" + ], + "max": 3, + "fields": { + "label": { + "from": [ + "string", + "key" + ], + "required": true + } + } + } + }, + "instance": { + "primary": { + "kind": "choice", + "question": "Which of these is the one thing the person most likely came to do?", + "optionsFrom": "buttons", + "allowNone": true + }, + "destructive": { + "kind": "boolean", + "question": "Does {label} remove, cancel, or spend something that cannot be easily undone?", + "yes": "Delete, cancel, sign out, pay, send.", + "no": "It opens, saves, continues, or can be undone." + } + }, + "fallback": [ + "actions" + ] + }, + { + "id": "timeline", + "pattern": "timeline", + "shape": { + "pointers": [ + "array" + ], + "elementTypes": [ + "datetime", + "date", + "time", + "relative_time" + ] + }, + "gate": { + "kind": "boolean", + "question": "Are these events that happened at particular times, best read in order?", + "yes": "Shipment scans, an audit log, build stages, visits, milestones, messages in a thread.", + "no": "The times are incidental; the items are things, not events." + }, + "slots": { + "events": { + "repeat": true, + "from": [ + "array" + ], + "required": true, + "orderBy": "time", + "fields": { + "time": { + "from": [ + "datetime", + "date", + "time", + "relative_time" + ], + "required": true + }, + "title": { + "from": [ + "title", + "string", + "status" + ], + "required": true + }, + "detail": { + "from": [ + "long_text", + "string", + "place_name", + "address" + ] + }, + "state": { + "from": [ + "status", + "enum", + "boolean" + ] + } + } + } + }, + "anatomy": { + "order": { + "kind": "choice", + "question": "Which end does the person want first?", + "options": { + "latest": "The most recent event matters most: tracking, a log, a feed of updates.", + "earliest": "The sequence is read from the start: a history, a story, a plan." + } + } + }, + "instance": { + "state_tone": { + "kind": "choice", + "appliesWhen": { + "state": "bound" + }, + "question": "Is {title} ({state}) good, bad, or neutral news?", + "options": { + "success": "Good.", + "warning": "Needs attention.", + "danger": "Bad.", + "neutral": "Neither." + } + } + }, + "fallback": [ + "timeline", + "steps", + "collection:rows" + ] + }, + { + "id": "map", + "pattern": "map", + "shape": { + "pointers": [ + "location", + "address" + ] + }, + "gate": { + "kind": "boolean", + "question": "Does the person need to see where this is?", + "yes": "A place to go to, something nearby, a route, an area.", + "no": "The address is a fact to read, as on a receipt or a profile." + }, + "slots": { + "location": { + "from": [ + "location", + "address" + ], + "required": true + }, + "label": { + "from": [ + "place_name", + "title", + "name", + "string" + ] + }, + "pins": { + "from": [ + "array" + ], + "elementTypes": [ + "location" + ] + } + }, + "fallback": [ + "map", + "facts" + ] + }, + { + "id": "conversation", + "pattern": "conversation", + "shape": { + "pointers": [ + "array" + ], + "elementKeys": [ + "author", + "sender", + "from", + "role", + "speaker" + ] + }, + "gate": { + "kind": "boolean", + "question": "Is this a back-and-forth between people, or between a person and an assistant?", + "yes": "Messages, replies, a chat log, a support thread, comments in order.", + "no": "A list of records that happen to have an author, such as articles or reviews." + }, + "slots": { + "messages": { + "repeat": true, + "from": [ + "array" + ], + "required": true, + "fields": { + "author": { + "from": [ + "name", + "string", + "enum" + ], + "required": true, + "prefer": [ + "author", + "sender", + "from", + "role", + "speaker" + ] + }, + "text": { + "from": [ + "long_text", + "markdown", + "string" + ], + "required": true, + "prefer": [ + "text", + "message", + "content", + "body" + ] + }, + "time": { + "from": [ + "datetime", + "time", + "relative_time" + ] + }, + "avatar": { + "from": [ + "image_url" + ], + "prefer": [ + "avatar", + "photo" + ] + }, + "attachment": { + "from": [ + "image_url", + "document_url", + "url" + ] + } + } + } + }, + "anatomy": { + "self": { + "kind": "choice", + "question": "Which author is the person reading this?", + "optionsFrom": "messages.author.distinct", + "allowNone": true, + "note": "Decides which side messages sit on; none means a transcript with every message on the left." + } + }, + "fallback": [ + "conversation", + "collection:rows" + ] + }, + { + "id": "compose", + "pattern": "compose", + "shape": { + "mutable": true, + "actions_allowed": true + }, + "gate": { + "kind": "boolean", + "question": "Can the person reply or add to this here?", + "yes": "An open conversation, a comment thread they take part in, a form of one field and a send button.", + "no": "A closed transcript or a log they only read." + }, + "slots": { + "draft": { + "from": [ + "string", + "long_text" + ], + "mutable": true, + "prefer": [ + "draft", + "reply", + "message", + "input" + ] + }, + "sendLabel": { + "from": [ + "string" + ], + "default": "Send" + } + }, + "fallback": [ + "compose" + ] + }, + { + "id": "outcome", + "pattern": "outcome", + "gate": { + "kind": "boolean", + "question": "Is this telling the person how something they did turned out?", + "yes": "Order placed, payment failed, message sent, nothing found, account deleted.", + "no": "Nothing has just happened; this is information or a task in progress." + }, + "slots": { + "headline": { + "from": [ + "string", + "enum" + ], + "required": true + }, + "detail": { + "from": [ + "long_text", + "string" + ] + } + }, + "instance": { + "tone": { + "kind": "choice", + "question": "Did {headline} go well for the person?", + "options": { + "success": "Yes: done, sent, placed, saved.", + "danger": "No: failed, declined, not found.", + "neutral": "Partly, or it is still pending." + } + } + }, + "fallback": [ + "outcome", + "banner", + "prose" + ] + } + ], + "rules": [ + { + "id": "required-block-wins", + "rule": "A block marked ! is present whatever its gate says; its gate is still asked so the trace can show disagreement." + }, + { + "id": "at-least", + "rule": "If fewer than atLeast blocks pass, include the highest-probability expected blocks until the count is met, before considering the archetype ineligible." + }, + { + "id": "one-primary-action", + "rule": "At most one button in actions is primary. If stakes >= 2 and a button is destructive, the destructive button is never primary and the non-destructive way out is placed first." + }, + { + "id": "actions-gate", + "rule": "actions, filters, form, groups, compose, and collection.trailing=button require actions_allowed, which is archetype confidence >= gate, where gate runs linearly from 0.70 at stakes 0 to 0.95 at stakes 3: gate = 0.70 + 0.25 * stakes / 3. Low-stakes toggles need 0.70; a payment needs 0.95. The floor and cap are grammar thresholds (actionGateFloor, actionGateCap) so a deployment can tighten them." + }, + { + "id": "catalog-eligibility", + "rule": "An archetype is offered only if every required block resolves to a pattern on the surface's catalogs after walking its fallback chain. Eligibility is computed once per catalog set and cached; ineligible archetypes cost nothing at query time." + }, + { + "id": "pointer-once-per-region", + "rule": "A pointer bound to a slot in one block is not offered to later blocks in the same region, except key-derived labels. Blocks claim pointers in archetype order, so a status shown in a banner is not repeated as a headline tile." + }, + { + "id": "pictures-need-a-look", + "rule": "picture, collection.layout in {cards, grid, reel}, and comparison.picture are only offered when an image_url pointer exists; the anatomy question is still asked so the answer can be traced." + }, + { + "id": "leading-all-or-none", + "rule": "Every item in a collection has the same leading kind; if the picture slot is bound for fewer than half the items, leading falls back to icon or none." + }, + { + "id": "urgency-terse", + "rule": "If urgency >= 1.5, prose is dropped unless required, headline tiles are limited to 3, and the primary action is placed in the frame's sticky slot when the catalog's page pattern supports it." + }, + { + "id": "no-empty-container", + "rule": "A block whose required slots cannot be bound is dropped; an archetype whose required block is dropped is ineligible." + }, + { + "id": "fallback-must-end", + "rule": "Every block's fallback chain entries must be abstract pattern names or pattern:variant forms such as collection:cards; the loader rejects a grammar with unknown fallback entries." + } + ], + "lint": [ + "Every archetype has at least one required or expected block.", + "Every block id used in an archetype exists in blocks.", + "Every fallback entry is an abstract pattern name or a pattern:variant form.", + "Every {placeholder} in a question names a field or slot of that block.", + "Every requires entry names a slot, a knob option, or a known capability flag." + ] +} diff --git a/catalogs/decision/v1/pattern_definition.json b/catalogs/decision/v1/pattern_definition.json new file mode 100644 index 0000000000..0c23fadb9b --- /dev/null +++ b/catalogs/decision/v1/pattern_definition.json @@ -0,0 +1,210 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://a2ui.org/specification/v1_0/decision/pattern_definition.json", + "title": "A2UI decision catalog pattern file", + "description": "How one component catalog draws the abstract layout patterns named by the decision archetype grammar.", + "type": "object", + "required": ["catalogIds", "version", "patterns"], + "additionalProperties": false, + "properties": { + "$schema": { "type": "string" }, + "catalogIds": { + "type": "array", + "description": "Catalog ids (the `catalogId` of each catalog.json) this file applies to.", + "minItems": 1, + "uniqueItems": true, + "items": { "type": "string", "format": "uri", "minLength": 1 } + }, + "version": { "type": "string", "minLength": 1 }, + "patterns": { + "type": "object", + "minProperties": 1, + "propertyNames": { "pattern": "^[a-z_]+$" }, + "additionalProperties": { "$ref": "#/$defs/pattern" } + } + }, + "$defs": { + "stringList": { + "type": "array", + "items": { "type": "string" } + }, + "pattern": { + "type": "object", + "required": ["slots"], + "additionalProperties": false, + "properties": { + "slots": { + "type": "array", + "items": { "type": "string", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" } + }, + "knobs": { + "type": "object", + "propertyNames": { "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, + "additionalProperties": { + "type": "array", + "minItems": 1, + "items": { "type": "string", "minLength": 1 } + } + }, + "root": { "type": "string", "minLength": 1 }, + "components": { "$ref": "#/$defs/componentList" }, + "variants": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/variant" } + }, + "fieldVariants": { + "type": "object", + "propertyNames": { "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, + "additionalProperties": { "$ref": "#/$defs/fieldVariant" } + }, + "note": { "type": "string" } + }, + "oneOf": [ + { "required": ["root", "components"] }, + { "required": ["variants"] } + ] + }, + "variant": { + "type": "object", + "required": ["root", "components"], + "additionalProperties": false, + "properties": { + "when": { + "type": "object", + "description": "Knob name to the value or values that select this variant; a variant without `when` is the default.", + "additionalProperties": { + "oneOf": [{ "type": "string" }, { "$ref": "#/$defs/stringList" }] + } + }, + "root": { "type": "string", "minLength": 1 }, + "components": { "$ref": "#/$defs/componentList" }, + "note": { "type": "string" } + } + }, + "componentList": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/component" } + }, + "component": { + "description": "A component template with an id, expanded once per block (or once per element inside `$repeat`).", + "allOf": [{ "$ref": "#/$defs/templateObject" }], + "required": ["id", "component"] + }, + "fieldVariant": { + "description": "An id-less component template selected by `$byInstance`; the expander assigns the id.", + "allOf": [{ "$ref": "#/$defs/templateObject" }], + "required": ["component"] + }, + "templateValue": { + "anyOf": [ + { "type": ["string", "number", "boolean", "null"] }, + { "type": "array", "items": { "$ref": "#/$defs/templateValue" } }, + { "$ref": "#/$defs/templateObject" } + ] + }, + "templateObject": { + "type": "object", + "description": "Any JSON object; keys starting with `$` are template directives with the value shapes below.", + "properties": { + "$slot": { "$ref": "#/$defs/slotDirective" }, + "$text": { "$ref": "#/$defs/textDirective" }, + "$default": { "$ref": "#/$defs/defaultDirective" }, + "$if": { "$ref": "#/$defs/ifDirective" }, + "$ifKnob": { "$ref": "#/$defs/ifKnobDirective" }, + "$ifSelf": { "$ref": "#/$defs/ifSelfDirective" }, + "$ifInstance": { "$ref": "#/$defs/ifInstanceDirective" }, + "$byType": { "$ref": "#/$defs/byTypeDirective" }, + "$byInstance": { "$ref": "#/$defs/byInstanceDirective" }, + "$repeat": { "$ref": "#/$defs/repeatDirective" }, + "$map": { "$ref": "#/$defs/mapDirective" }, + "$event": { "$ref": "#/$defs/eventDirective" }, + "$blocks": { "$ref": "#/$defs/blocksDirective" }, + "$knobValue": { "$ref": "#/$defs/knobValueDirective" }, + "$item": { "$ref": "#/$defs/itemDirective" } + }, + "patternProperties": { + "^[^$]": { "$ref": "#/$defs/templateValue" } + }, + "additionalProperties": false + }, + "slotDirective": { + "type": "string", + "minLength": 1, + "description": "Slot name (optionally `slot.field`); becomes a data binding to the bound pointer, or `$default` when unbound." + }, + "textDirective": { + "type": "string", + "description": "Literal with `{slot}` placeholders; a bound slot becomes a formatString call, `{$index1}` is the 1-based element index." + }, + "defaultDirective": { + "$ref": "#/$defs/templateValue", + "description": "Literal used when the `$slot` or `$knobValue` beside it resolves to nothing." + }, + "ifDirective": { + "type": "string", + "minLength": 1, + "description": "Slot name; the component is emitted only when that slot is bound." + }, + "ifKnobDirective": { + "type": "object", + "minProperties": 1, + "description": "Knob name to accepted values; the component is emitted only when every knob matches.", + "additionalProperties": { "$ref": "#/$defs/stringList" } + }, + "ifSelfDirective": { + "type": "object", + "description": "Value (or child id) to use when the element's author is the `self` knob (`true`) or not (`false`).", + "additionalProperties": false, + "properties": { + "true": { "type": "string" }, + "false": { "type": "string" } + } + }, + "ifInstanceDirective": { + "type": "object", + "minProperties": 1, + "description": "Instance answer name to required value; the enclosing property is emitted only when each holds.", + "additionalProperties": { "type": ["string", "boolean"] } + }, + "byTypeDirective": { + "type": "string", + "minLength": 1, + "description": "Slot name; the sibling key matching the slot's semantic type names the child id to emit." + }, + "byInstanceDirective": { + "type": "string", + "minLength": 1, + "description": "Instance answer name; selects a `fieldVariants` entry, or a sibling key matching the answer." + }, + "repeatDirective": { + "type": "string", + "minLength": 1, + "description": "Repeated slot name; `children` becomes a template child list bound to the slot's array (sibling `component` names the template)." + }, + "mapDirective": { + "type": "string", + "minLength": 1, + "description": "Knob or instance answer name; the sibling key matching its value is the literal to emit." + }, + "eventDirective": { + "type": "string", + "minLength": 1, + "description": "Event name, or a slot whose value is slugged into the event name; emits `{\"event\": {\"name\": ...}}` plus `context`." + }, + "blocksDirective": { + "const": true, + "description": "Placeholder in the page pattern's children for the block roots in archetype order." + }, + "knobValueDirective": { + "type": "string", + "minLength": 1, + "description": "`knob.property` lookup into the plan; `$default` applies when absent." + }, + "itemDirective": { + "const": true, + "description": "Inside `$repeat`, the current element's pointer, bound as the event context." + } + } +} diff --git a/conformance/agent/decision/archetypes.yaml b/conformance/agent/decision/archetypes.yaml new file mode 100644 index 0000000000..606eb571e5 --- /dev/null +++ b/conformance/agent/decision/archetypes.yaml @@ -0,0 +1,469 @@ +# 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. + +# Decision layout archetypes, eligibility, planning, and pattern expansion. + +- name: test_grammar_default_loads_and_lints + description: Default archetype grammar loads cleanly and passes structural lint checks. + action: load + args: + kind: grammar + expect: + version: "1" + families: + - browse + - monitor + - inspect + - act + - input + - follow + archetype_count: 14 + block_count: 19 + +- name: test_eligibility_resort_basic_v1 + description: Resort overview payload makes detail and feed archetypes eligible on Basic v1. + action: validate + args: + kind: eligibility + catalog: basic_v1 + input: + name: "Casa Verde" + logoUrl: "https://example.com/casa-verde/logo.png" + rating: 4.6 + priceFrom: 240 + about: "A quiet hillside resort twenty minutes from the old town, with a spring-fed pool, garden suites, and a breakfast terrace that looks over the valley. Families and walkers come back year after year." + photos: + - url: "https://example.com/casa-verde/1.jpg" + caption: "Pool at dusk" + - url: "https://example.com/casa-verde/2.jpg" + caption: "Garden suite" + - url: "https://example.com/casa-verde/3.jpg" + caption: "Breakfast terrace" + expect: + contains_archetypes: + - detail + - feed + +- name: test_eligibility_host_basic_v1 + description: Host health payload makes the dashboard archetype eligible on Basic v1. + action: validate + args: + kind: eligibility + catalog: basic_v1 + input: + host: "prod-1" + cpu: 0.78 + cpuDelta: 0.12 + status: "degraded" + uptimeHours: 412 + expect: + contains_archetypes: + - dashboard + +- name: test_eligibility_transfer_basic_v1 + description: Transfer confirmation payload makes confirm, checkout, and result eligible on Basic v1. + action: validate + args: + kind: eligibility + catalog: basic_v1 + mutable_paths: + - /actions + input: + amount: 50 + currency: "USD" + recipient: "Alex Chen" + fee: 0.5 + arrives: "2026-10-24" + actions: + - "Send" + - "Cancel" + expect: + contains_archetypes: + - confirm + - checkout + - result + +- name: test_eligibility_settings_basic_v1 + description: Podcast settings payload makes settings and form archetypes eligible on Basic v1. + action: validate + args: + kind: eligibility + catalog: basic_v1 + mutable_paths: + - /playback + - /notifications + - /account + input: + playback: + skipForward: "30 seconds" + autoDownload: true + speed: 1.25 + notifications: + newEpisodes: true + digest: false + account: + signOut: "Sign out" + expect: + contains_archetypes: + - settings + - form + +- name: test_eligibility_two_component_catalog_none + description: A two-component domain catalog with no basic patterns has zero eligible archetypes. + action: validate + args: + kind: eligibility + catalog: two_component + input: + name: "Casa Verde" + rating: 4.6 + priceFrom: 240 + expect: + exact_archetypes: [] + +- name: test_plan_resort_detail + description: Resort payload plans to inspect/detail with picture, headline, prose, and collection in order. + action: render + args: + kind: plan + intent: "Show the resort overview" + scripted_answers: + family: ["inspect", 0.80] + stakes: 0.2 + urgency: 0.1 + "archetype:inspect": ["detail", 0.85] + "gate:picture": 0.90 + "gate:banner": 0.10 + "gate:headline": 0.80 + "gate:prose": 0.90 + "gate:facts": 0.40 + "gate:collection": 0.85 + "gate:actions": 0.30 + "anatomy:picture.framing": ["banner", 0.80] + "anatomy:picture.prominence": 2.2 + "anatomy:collection.layout": ["reel", 0.70] + "anatomy:collection.leading": ["thumbnail", 0.80] + "anatomy:collection.trailing": ["none", 0.80] + "salience:/rating": 2.4 + "salience:/priceFrom": 2.6 + input: + name: "Casa Verde" + logoUrl: "https://example.com/casa-verde/logo.png" + rating: 4.6 + priceFrom: 240 + about: "A quiet hillside resort twenty minutes from the old town, with a spring-fed pool, garden suites, and a breakfast terrace that looks over the valley. Families and walkers come back year after year." + photos: + - url: "https://example.com/casa-verde/1.jpg" + caption: "Pool at dusk" + - url: "https://example.com/casa-verde/2.jpg" + caption: "Garden suite" + - url: "https://example.com/casa-verde/3.jpg" + caption: "Breakfast terrace" + expect: + reason: "planned" + family: "inspect" + archetype: "detail" + blocks: + - picture + - headline + - prose + - collection + actions_allowed: true + block_knobs: + picture: + framing: "banner" + prominence: "leading" + prose: + length: "blurb" + collection: + layout: "reel" + leading: "thumbnail" + +- name: test_plan_host_dashboard + description: Host payload plans to monitor/dashboard with banner, headline, and facts in order. + action: render + args: + kind: plan + intent: "Show CPU utilization for prod-1" + scripted_answers: + family: ["monitor", 0.90] + stakes: 1.0 + urgency: 1.4 + "archetype:monitor": ["dashboard", 0.85] + "gate:banner": 0.80 + "gate:headline": 0.90 + "gate:facts": 0.80 + "salience:/cpu": 2.8 + "salience:/status": 2.1 + "salience:/uptimeHours": 1.2 + "salience:/host": 0.4 + "instance:banner.tone:/status": ["warning", 0.90] + "instance:headline.news:/cpu": ["bad", 0.85] + "instance:headline.state_tone:/status": ["warning", 0.80] + input: + host: "prod-1" + cpu: 0.78 + cpuDelta: 0.12 + status: "degraded" + uptimeHours: 412 + expect: + reason: "planned" + family: "monitor" + archetype: "dashboard" + blocks: + - banner + - headline + - facts + actions_allowed: true + block_knobs: + banner: + tone: "warning" + +- name: test_plan_transfer_confirm_committed + description: Transfer payload at confidence 0.90 passes the 0.875 action gate and plans act/confirm. + action: render + args: + kind: plan + intent: "Confirm sending $50 to Alex before it goes through" + mutable_paths: + - /actions + scripted_answers: + family: ["act", 0.85] + stakes: 2.1 + urgency: 0.6 + "archetype:act": ["confirm", 0.90] + "gate:banner": 0.20 + "gate:prose": 0.45 + "gate:facts": 0.85 + "gate:actions": 0.90 + "instance:actions.primary:/actions": ["Send", 0.90] + "instance:actions.destructive:0": 0.80 + "instance:actions.destructive:1": 0.10 + "salience:/amount": 2.9 + "salience:/recipient": 2.6 + "salience:/fee": 1.9 + "salience:/arrives": 1.7 + input: + amount: 50 + currency: "USD" + recipient: "Alex Chen" + fee: 0.5 + arrives: "2026-10-24" + actions: + - "Send" + - "Cancel" + expect: + reason: "planned" + family: "act" + archetype: "confirm" + blocks: + - facts + - actions + actions_allowed: true + block_knobs: {} + +- name: test_plan_transfer_confirm_blocked + description: Transfer payload at confidence 0.80 is blocked by the 0.875 action gate. + action: render + args: + kind: plan + intent: "Confirm sending $50 to Alex before it goes through" + mutable_paths: + - /actions + scripted_answers: + family: ["act", 0.85] + stakes: 2.1 + urgency: 0.6 + "archetype:act": ["confirm", 0.80] + "gate:banner": 0.20 + "gate:prose": 0.45 + "gate:facts": 0.85 + "gate:actions": 0.90 + "instance:actions.primary:/actions": ["Send", 0.90] + "instance:actions.destructive:0": 0.80 + "instance:actions.destructive:1": 0.10 + "salience:/amount": 2.9 + "salience:/recipient": 2.6 + "salience:/fee": 1.9 + "salience:/arrives": 1.7 + input: + amount: 50 + currency: "USD" + recipient: "Alex Chen" + fee: 0.5 + arrives: "2026-10-24" + actions: + - "Send" + - "Cancel" + expect: + reason: "action_gate" + +- name: test_plan_settings_groups + description: Settings payload at confidence 0.85 plans input/settings with groups and actions_allowed=true. + action: render + args: + kind: plan + intent: "Playback and notification settings" + mutable_paths: + - /playback + - /notifications + - /account + scripted_answers: + family: ["input", 0.80] + stakes: 1.2 + urgency: 0.2 + "archetype:input": ["settings", 0.85] + "gate:groups": 0.90 + "gate:actions": 0.20 + "instance:groups.row_kind:/playback/skipForward": ["value", 0.90] + "instance:groups.row_kind:/playback/autoDownload": ["switch", 0.95] + "instance:groups.row_kind:/playback/speed": ["value", 0.70] + "instance:groups.row_kind:/notifications/newEpisodes": ["switch", 0.90] + "instance:groups.row_kind:/notifications/digest": ["switch", 0.90] + "instance:groups.row_kind:/account/signOut": ["danger", 0.90] + input: + playback: + skipForward: "30 seconds" + autoDownload: true + speed: 1.25 + notifications: + newEpisodes: true + digest: false + account: + signOut: "Sign out" + expect: + reason: "planned" + family: "input" + archetype: "settings" + blocks: + - groups + actions_allowed: true + block_knobs: {} + +- name: test_expand_banner_v1_0 + description: Expands the Basic v1 banner pattern with warning tone to its exact v1.0 component list. + action: render + args: + kind: expand_block + block_id: "banner" + pattern: "banner" + knobs: + tone: "warning" + slots: + title: + pointer: "/status" + expect: + - id: "banner_card" + component: "Card" + child: "banner_row" + - id: "banner_row" + component: "Row" + align: "center" + children: + - "banner_icon" + - "banner_col" + - id: "banner_icon" + component: "Icon" + name: "info" + - id: "banner_col" + component: "Column" + weight: 1 + children: + - "banner_title" + - id: "banner_title" + component: "Text" + text: + "@call": "formatString" + args: + value: "**${/status}**" + +- name: test_expand_prose_blurb_v1_0 + description: Expands the Basic v1 prose pattern with blurb length to its exact v1.0 component list. + action: render + args: + kind: expand_block + block_id: "prose" + pattern: "prose" + knobs: + length: "blurb" + slots: + body: + pointer: "/about" + expect: + - id: "prose_col" + component: "Column" + children: + - "prose_body" + - id: "prose_body" + component: "Text" + text: + "@path": "/about" + variant: "body" + +- name: test_expand_facts_v1_0 + description: Expands the Basic v1 facts pattern with two static item rows to its exact v1.0 component list. + action: render + args: + kind: expand_block + block_id: "facts" + pattern: "facts" + slots: + rows: + items: + - label: + literal: "Uptime Hours" + value: + pointer: "/uptimeHours" + - label: + literal: "Host" + value: + pointer: "/host" + expect: + - id: "facts_card" + component: "Card" + child: "facts_list" + - id: "facts_list" + component: "List" + direction: "vertical" + children: + - "facts_row_0" + - "facts_row_1" + - id: "facts_row_0" + component: "Row" + justify: "spaceBetween" + children: + - "facts_0_facts_label" + - "facts_0_facts_value" + - id: "facts_0_facts_label" + component: "Text" + text: "Uptime Hours" + variant: "caption" + - id: "facts_0_facts_value" + component: "Text" + text: + "@path": "/uptimeHours" + - id: "facts_row_1" + component: "Row" + justify: "spaceBetween" + children: + - "facts_1_facts_label" + - "facts_1_facts_value" + - id: "facts_1_facts_label" + component: "Text" + text: "Host" + variant: "caption" + - id: "facts_1_facts_value" + component: "Text" + text: + "@path": "/host" diff --git a/eval/DESIGN.md b/eval/DESIGN.md index d3c4233ca2..6bb9f61f3d 100644 --- a/eval/DESIGN.md +++ b/eval/DESIGN.md @@ -36,7 +36,11 @@ To ensure consistency between the evaluation framework and the actual agent impl `a2ui_eval/runner.py` exposes `generate_prompt` to build format prompts and `parse_and_validate` to parse and validate model completions in a pooled Python worker process, isolating the harness from runaway regexes or parser loops under `DEFAULT_PARSE_TIMEOUT_SEC`. -All format strategies (`direct`, `express`, `elemental`, and `atom`), `skill_mode`, and the `subagent_tool` specialist call `parse_and_validate` with `validate=True` during solver execution. The solver stores the validated messages in `state.metadata["compiled_messages"]`, and the Stage 1 scorer reuses them instead of parsing again. +All format strategies (`direct`, `express`, `elemental`, and `atom`), `skill_mode`, `decision`, and the `subagent_tool` specialist call `parse_and_validate` with `validate=True` during solver execution. The solver stores the validated messages in `state.metadata["compiled_messages"]`, and the Stage 1 scorer reuses them instead of parsing again. + +### **The Decision Strategy** + +The `decision` strategy evaluates the two-stage decision-model synthesis route. In Stage 1, the model emits intent, payload, and optional copy or layout hints in a `` block. In Stage 2, the decision synthesizer plans and expands the surface using the configured decision backend (`--decision-backend`, defaulting to `local`) without an additional UI generation model call. The strategy tracks Stage 1 validation retries (`pass_at_1`), decision latency (`decision_latency_ms`), decision calls (`decision_calls`), and planned archetype metadata. ### **Runner Options** diff --git a/eval/README.md b/eval/README.md index c7537b2b5e..dc99e78926 100644 --- a/eval/README.md +++ b/eval/README.md @@ -81,13 +81,19 @@ uv run main.py --dataset multi_turn_conversation_dataset uv run main.py --datasets core_v0_9_1,multi_turn_conversation_dataset ``` -By default `main.py` runs the production strategies: `direct`, `subagent_tool` and `express`. The experimental formats `elemental` and `atom`, and the `skill_mode` strategy, run only when you name them: +By default `main.py` runs the production strategies: `direct`, `subagent_tool` and `express`. The experimental formats `elemental` and `atom`, the `skill_mode` strategy, and the `decision` strategy run only when you name them: ```bash uv run main.py --dataset multi_turn_conversation_dataset --strategies direct,express,elemental uv run main.py --strategies skill_mode +uv run main.py --strategies decision --decision-backend local ``` +The `decision` strategy evaluates the two-stage decision-model synthesis route. In Stage 1, the model emits intent and payload in a `` block. In Stage 2, the decision synthesizer plans and expands the surface without an additional UI generation model call. +- `--decision-backend`: `local` (default), `jev`, or `mock`. +- `--decision-temperature`: Temperature scaling applied to logits (default `1.0`). +- `--decision-variety`: Sampling mode (`argmax` or `near_top`). + The `subagent_tool` strategy gives the outer model one tool, `a2ui_specialist`, and a second model call writes the payload. `--subagent-format {direct_json,express}` picks the format the specialist writes in (default `direct_json`). The `skill_mode` strategy does not put the A2UI prompt in the system message. It lists the available skills (`a2ui-core` plus one per catalog) and gives the model a `read_a2ui_skill` tool to load them. The skills the model read are recorded as `skills_read` in the sample metadata. @@ -314,6 +320,41 @@ To print a console summary or markdown table from an eval log file: uv run python bin/report_evals.py logs/.eval ``` +## Strategy Comparison + +`bin/compare_strategies.py` performs a pairwise comparison of two or more evaluated strategies from a shared evaluation log directory: + +```bash +uv run ./bin/compare_strategies.py logs/decision_vs_express --json logs/decision_vs_express/summary.json --markdown +``` + +It reports: +- Pass@1 accuracy and delta with statistical significance (p-value from McNemar's test). +- Token usage: prompt and output tokens per turn, and token reduction percentage. +- Latency: median and 95th percentile wall-clock response time. +- Cost: estimated dollar cost per 1,000 completed turns. + +## Decision Model Benchmarking + +`bin/decision_bench.py` benchmarks decision backend models directly against the encrypted golden plan dataset (`datasets/decision_plans/v1.yaml`): + +```bash +# Run against the local cross-encoder backend +uv run ./bin/decision_bench.py --backend local --repeat 3 --markdown + +# Fit optimal temperature on the calibration set +uv run ./bin/decision_bench.py --backend local --fit-temperature + +# Run against remote Jev +uv run ./bin/decision_bench.py --backend jev --repeat 3 --markdown +``` + +The benchmark reports: +- Job family and layout archetype classification accuracy. +- Block recall: whether all required semantic blocks were planned. +- Calibration: Brier score and Expected Calibration Error (ECE) across probability buckets. +- Latency: mean, median, P95, and P99 latency in milliseconds. + ## Running Unit Tests & Schema Validation To run the unit tests and validate all dataset files against `datasets/dataset_schema.json`: diff --git a/eval/a2ui_eval/dataset.py b/eval/a2ui_eval/dataset.py index 84015ea052..0d53691d8f 100644 --- a/eval/a2ui_eval/dataset.py +++ b/eval/a2ui_eval/dataset.py @@ -42,6 +42,7 @@ SCHEMA_PATH = GIT_ROOT / "eval" / "datasets" / "dataset_schema.json" DATASETS_DIR = GIT_ROOT / "eval" / "datasets" +OPT_IN_DATASETS: frozenset[str] = frozenset({"decision_v1_0"}) def _version_to_dir_name(version: str) -> str: @@ -246,6 +247,9 @@ def load_a2ui_dataset( target_files.append(yaml_file) is_json = format_name is None or format_name == "direct_json" + default_datasets = ( + OPT_IN_DATASETS if (format_name == "decision" and not file_path) else None + ) samples: list[Sample] = [] for target_file in target_files: @@ -257,7 +261,13 @@ def load_a2ui_dataset( for item in data: item_dataset = item.get("dataset") or inferred_dataset - if filter_names and item_dataset not in filter_names: + if filter_names: + if item_dataset not in filter_names: + continue + elif default_datasets is not None: + if item_dataset not in default_datasets: + continue + elif not file_path and item_dataset in OPT_IN_DATASETS: continue # Skip datasets specifically targeted at another protocol version if version is set diff --git a/eval/a2ui_eval/decision_bench.py b/eval/a2ui_eval/decision_bench.py new file mode 100644 index 0000000000..db287f5bdd --- /dev/null +++ b/eval/a2ui_eval/decision_bench.py @@ -0,0 +1,657 @@ +# 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. + +"""Golden plan evaluation and latency benchmark for A2UI decision models.""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass, field +import json +import math +from pathlib import Path +import time +from typing import Any + +from a2ui.core.basic_catalog import BasicCatalog +from a2ui.inference_formats.decision import ( + DecisionAnswer, + DecisionSynthesizer, + SynthesisOutput, + SynthesisStage, +) +import jsonschema +import yaml + +from .decision_common import build_decision_backend + + +@dataclass(frozen=True) +class PlanCase: + """A single ground-truth decision case.""" + + name: str + intent: str + payload: dict[str, Any] + expected_family: str + expected_archetypes: list[str] + mutable_paths: list[str] = field(default_factory=list) + required_blocks: list[str] = field(default_factory=list) + forbidden_blocks: list[str] = field(default_factory=list) + expected_action_gate: str = "pass" + tags: list[str] = field(default_factory=list) + verified: bool = True + source: dict[str, Any] | None = None + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> PlanCase: + expected = data.get("expected", {}) + blocks = expected.get("blocks", {}) + return cls( + name=data["name"], + intent=data["intent"], + payload=dict(data.get("payload", {})), + expected_family=expected.get("family", ""), + expected_archetypes=list(expected.get("archetypes", [])), + mutable_paths=list(data.get("mutable_paths", [])), + required_blocks=list(blocks.get("required", [])), + forbidden_blocks=list(blocks.get("forbidden", [])), + expected_action_gate=expected.get("action_gate", "pass"), + tags=list(data.get("tags", [])), + verified=bool(data.get("verified", True)), + source=data.get("source"), + ) + + +def load_plan_cases( + cases_path: str | Path, + *, + tags: Sequence[str] | str | None = None, + include_unverified: bool = False, + schema_path: str | Path | None = None, +) -> list[PlanCase]: + """Loads and validates decision plan cases from a YAML file. + + Args: + cases_path: Path to the YAML file holding cases. + tags: Optional filter tag(s) to match. + include_unverified: If True, include cases marked verified=False. + schema_path: Optional path to JSON schema; defaults to schema.json + alongside the cases file. + """ + path = Path(cases_path) + if not path.is_file(): + raise FileNotFoundError(f"Decision cases file not found: {path}") + + schema_file = Path(schema_path) if schema_path else path.parent / "schema.json" + if schema_file.is_file(): + with open(schema_file, "r", encoding="utf-8") as f: + schema = json.load(f) + else: + schema = None + + with open(path, "r", encoding="utf-8") as f: + raw_cases = yaml.safe_load(f) or [] + + if schema is not None: + jsonschema.validate(instance=raw_cases, schema=schema) + + target_tags: set[str] = set() + if isinstance(tags, str): + target_tags = {t.strip() for t in tags.split(",") if t.strip()} + elif tags: + target_tags = {str(t).strip() for t in tags if str(t).strip()} + + cases: list[PlanCase] = [] + for item in raw_cases: + if not isinstance(item, dict): + continue + if not include_unverified and not item.get("verified", True): + continue + case = PlanCase.from_dict(item) + if target_tags and not any(t in target_tags for t in case.tags): + continue + cases.append(case) + + return cases + + +def is_action_gate_blocked(output: SynthesisOutput) -> bool: + """Checks whether the synthesis run was blocked by an action gate. + + The action gate is recorded in the trace reason where question.id is + archetype_status and outcome is action_gate. + """ + if output.stage is not SynthesisStage.ABSTAIN_FALLBACK: + return False + return any( + record.question.id == "archetype_status" and record.outcome == "action_gate" + for record in output.trace + ) + + +@dataclass(frozen=True) +class CaseEvaluation: + """Evaluation metrics for a single synthesis execution.""" + + output: SynthesisOutput + wall_time_ms: float + family_correct: bool + archetype_correct: bool + block_precision: float + block_recall: float + forbidden_block_count: int + action_gate_outcome: str + abstained: bool + + @property + def host_overhead_ms(self) -> float: + return max(0.0, self.wall_time_ms - self.output.decision_latency_ms) + + +@dataclass +class CaseScore: + """Aggregated score for a case across repeats.""" + + case: PlanCase + repeats: int + evaluations: list[CaseEvaluation] = field(default_factory=list) + + @property + def family_accuracy(self) -> float: + if not self.evaluations: + return 0.0 + return sum(1.0 for e in self.evaluations if e.family_correct) / len( + self.evaluations + ) + + @property + def archetype_accuracy(self) -> float: + if not self.evaluations: + return 0.0 + return sum(1.0 for e in self.evaluations if e.archetype_correct) / len( + self.evaluations + ) + + @property + def block_precision(self) -> float: + if not self.evaluations: + return 0.0 + return sum(e.block_precision for e in self.evaluations) / len(self.evaluations) + + @property + def block_recall(self) -> float: + if not self.evaluations: + return 0.0 + return sum(e.block_recall for e in self.evaluations) / len(self.evaluations) + + @property + def abstain_rate(self) -> float: + if not self.evaluations: + return 0.0 + return sum(1.0 for e in self.evaluations if e.abstained) / len(self.evaluations) + + @property + def action_gate_match(self) -> bool: + if not self.evaluations: + return False + expected = self.case.expected_action_gate + if expected == "any": + return True + return all(e.action_gate_outcome == expected for e in self.evaluations) + + @property + def decision_latency_p50(self) -> float: + latencies = sorted(e.output.decision_latency_ms for e in self.evaluations) + return _percentile(latencies, 0.50) + + @property + def decision_latency_p95(self) -> float: + latencies = sorted(e.output.decision_latency_ms for e in self.evaluations) + return _percentile(latencies, 0.95) + + @property + def host_overhead_p50(self) -> float: + overheads = sorted(e.host_overhead_ms for e in self.evaluations) + return _percentile(overheads, 0.50) + + @property + def host_overhead_p95(self) -> float: + overheads = sorted(e.host_overhead_ms for e in self.evaluations) + return _percentile(overheads, 0.95) + + @property + def mean_decision_calls(self) -> float: + if not self.evaluations: + return 0.0 + return sum(e.output.decision_calls for e in self.evaluations) / len( + self.evaluations + ) + + +def _percentile(sorted_values: list[float], q: float) -> float: + if not sorted_values: + return 0.0 + idx = (len(sorted_values) - 1) * q + low = int(math.floor(idx)) + high = int(math.ceil(idx)) + if low == high: + return sorted_values[low] + weight = idx - low + return sorted_values[low] * (1.0 - weight) + sorted_values[high] * weight + + +def brier_score(pairs: Sequence[tuple[float, float]]) -> float: + """Computes the mean squared error (Brier score) for probability pairs.""" + if not pairs: + return 0.0 + return sum((p - y) ** 2 for p, y in pairs) / len(pairs) + + +def expected_calibration_error( + pairs: Sequence[tuple[float, float]], num_bins: int = 10 +) -> float: + """Computes Expected Calibration Error (ECE) across 10 equal bins.""" + if not pairs or num_bins <= 0: + return 0.0 + bin_size = 1.0 / num_bins + total = len(pairs) + ece = 0.0 + + for b in range(num_bins): + low = b * bin_size + high = (b + 1) * bin_size + if b == num_bins - 1: + in_bin = [ + (p, y) for p, y in pairs if low <= p <= high or math.isclose(p, high) + ] + else: + in_bin = [(p, y) for p, y in pairs if low <= p < high] + + if not in_bin: + continue + bin_count = len(in_bin) + avg_conf = sum(p for p, _ in in_bin) / bin_count + avg_acc = sum(y for _, y in in_bin) / bin_count + ece += (bin_count / total) * abs(avg_acc - avg_conf) + + return ece + + +TEMPERATURE_GRID = ( + 0.25, + 0.50, + 0.75, + 1.00, + 1.25, + 1.50, + 1.75, + 2.00, + 2.25, + 2.50, + 2.75, + 3.00, + 3.25, + 3.50, + 3.75, + 4.00, +) + + +def fit_temperature( + calibration_data: Sequence[tuple[float, float]], + candidates: Sequence[float] | None = None, +) -> float: + """Finds temperature T in candidates that minimizes Expected Calibration Error.""" + if not calibration_data: + return 1.0 + grid = candidates or TEMPERATURE_GRID + best_temp = 1.0 + best_ece = float("inf") + + for temp in grid: + rescaled: list[tuple[float, float]] = [] + for p, y in calibration_data: + # Rescale probability through temperature: + # logit = ln(p / (1 - p)), rescaled = logit / T + p_clamped = min(max(p, 1e-6), 1.0 - 1e-6) + logit = math.log(p_clamped / (1.0 - p_clamped)) + scaled_logit = max(min(logit / temp, 30.0), -30.0) + p_scaled = 1.0 / (1.0 + math.exp(-scaled_logit)) + rescaled.append((p_scaled, y)) + + ece = expected_calibration_error(rescaled) + if ece < best_ece or (math.isclose(ece, best_ece) and temp == 1.0): + best_ece = ece + best_temp = temp + + return best_temp + + +@dataclass +class BenchmarkSummary: + """Complete summary of a golden plan benchmark run.""" + + cases_count: int + total_runs: int + family_accuracy: float + archetype_accuracy: float + block_precision: float + block_recall: float + abstain_rate: float + decision_latency_p50: float + decision_latency_p95: float + host_overhead_p50: float + host_overhead_p95: float + decision_calls_mean: float + brier_family: float + ece_family: float + brier_archetype: float + ece_archetype: float + brier_gates: float + ece_gates: float + fitted_temperature: float | None = None + case_scores: list[CaseScore] = field(default_factory=list) + + +def evaluate_single_run( + case: PlanCase, output: SynthesisOutput, wall_time_ms: float +) -> tuple[CaseEvaluation, list[tuple[str, float, float]]]: + """Evaluates one synthesis output against case expectations. + + Returns the CaseEvaluation and calibration pairs (kind, prob, correct). + """ + answers_by_id = {ans.question_id: ans for ans in output.decision_answers} + + # Family accuracy + observed_family = "" + family_prob = 1.0 + if "family" in answers_by_id: + family_choice, family_prob = answers_by_id["family"].top() + observed_family = family_choice + elif output.layout_plan: + observed_family = output.layout_plan.family + + family_correct = observed_family.lower() == case.expected_family.lower() + + # Archetype accuracy + observed_archetype = "" + archetype_prob = 1.0 + if output.layout_plan: + observed_archetype = output.layout_plan.archetype + arch_ans = answers_by_id.get(f"archetype:{output.layout_plan.family}") + if arch_ans is not None: + _, archetype_prob = arch_ans.top() + elif f"archetype:{observed_family}" in answers_by_id: + observed_archetype, archetype_prob = answers_by_id[ + f"archetype:{observed_family}" + ].top() + else: + for qid, ans in answers_by_id.items(): + if qid.startswith("archetype:"): + top_arch, archetype_prob = ans.top() + observed_archetype = top_arch + break + + archetype_correct = observed_archetype.lower() in { + a.lower() for a in case.expected_archetypes + } + + # Blocks precision & recall + observed_blocks = set() + if output.layout_plan: + observed_blocks = {b.block_id for b in output.layout_plan.blocks} + + required_set = set(case.required_blocks) + forbidden_set = set(case.forbidden_blocks) + + if required_set: + recall = len(required_set & observed_blocks) / len(required_set) + precision = ( + len(required_set & observed_blocks) / len(observed_blocks) + if observed_blocks + else 0.0 + ) + else: + recall = 1.0 + precision = 1.0 + + forbidden_count = len(forbidden_set & observed_blocks) + if forbidden_count > 0: + precision = max(0.0, precision - (forbidden_count * 0.25)) + + # Action gate outcome + is_blocked = is_action_gate_blocked(output) + action_gate_outcome = "abstain" if is_blocked else "pass" + abstained = ( + output.stage is SynthesisStage.ABSTAIN_FALLBACK + and output.fallback_source is None + ) or not output.messages + + eval_result = CaseEvaluation( + output=output, + wall_time_ms=wall_time_ms, + family_correct=family_correct, + archetype_correct=archetype_correct, + block_precision=precision, + block_recall=recall, + forbidden_block_count=forbidden_count, + action_gate_outcome=action_gate_outcome, + abstained=abstained, + ) + + # Calibration points: (kind, prob, y) + cal_points: list[tuple[str, float, float]] = [] + cal_points.append(("family", family_prob, 1.0 if family_correct else 0.0)) + cal_points.append(("archetype", archetype_prob, 1.0 if archetype_correct else 0.0)) + + for qid, ans in answers_by_id.items(): + if qid.startswith("gate:"): + block_id = qid.removeprefix("gate:") + block_expected = 1.0 if block_id in required_set else 0.0 + cal_points.append(("gate", ans.yes, block_expected)) + + return eval_result, cal_points + + +async def run_case( + synth: DecisionSynthesizer, + case: PlanCase, + *, + repeat: int = 1, +) -> CaseScore: + """Executes a decision synthesis case multiple times and scores results.""" + score = CaseScore(case=case, repeats=repeat) + + for _ in range(repeat): + start = time.perf_counter() + output = await synth.synthesize( + case.intent, + case.payload, + mutable_paths=case.mutable_paths, + ) + elapsed_ms = (time.perf_counter() - start) * 1000.0 + evaluation, _ = evaluate_single_run(case, output, elapsed_ms) + score.evaluations.append(evaluation) + + return score + + +async def run_benchmark( + synth: DecisionSynthesizer, + cases: Sequence[PlanCase], + *, + repeat: int = 3, + fit_temp: bool = False, +) -> BenchmarkSummary: + """Runs the benchmark across all cases and summarizes accuracy, latency, and calibration.""" + case_scores: list[CaseScore] = [] + all_evaluations: list[CaseEvaluation] = [] + calibration_records: list[tuple[str, float, float]] = [] + + for case in cases: + score = CaseScore(case=case, repeats=repeat) + for _ in range(repeat): + start = time.perf_counter() + output = await synth.synthesize( + case.intent, + case.payload, + mutable_paths=case.mutable_paths, + ) + elapsed_ms = (time.perf_counter() - start) * 1000.0 + evaluation, cal_points = evaluate_single_run(case, output, elapsed_ms) + score.evaluations.append(evaluation) + all_evaluations.append(evaluation) + calibration_records.extend(cal_points) + case_scores.append(score) + + total_runs = len(all_evaluations) + if not total_runs: + return BenchmarkSummary( + cases_count=0, + total_runs=0, + family_accuracy=0.0, + archetype_accuracy=0.0, + block_precision=0.0, + block_recall=0.0, + abstain_rate=0.0, + decision_latency_p50=0.0, + decision_latency_p95=0.0, + host_overhead_p50=0.0, + host_overhead_p95=0.0, + decision_calls_mean=0.0, + brier_family=0.0, + ece_family=0.0, + brier_archetype=0.0, + ece_archetype=0.0, + brier_gates=0.0, + ece_gates=0.0, + ) + + family_acc = sum(1.0 for e in all_evaluations if e.family_correct) / total_runs + arch_acc = sum(1.0 for e in all_evaluations if e.archetype_correct) / total_runs + block_prec = sum(e.block_precision for e in all_evaluations) / total_runs + block_rec = sum(e.block_recall for e in all_evaluations) / total_runs + abstain_rate = sum(1.0 for e in all_evaluations if e.abstained) / total_runs + + latencies = sorted(e.output.decision_latency_ms for e in all_evaluations) + overheads = sorted(e.host_overhead_ms for e in all_evaluations) + mean_calls = sum(e.output.decision_calls for e in all_evaluations) / total_runs + + family_pairs = [(p, y) for k, p, y in calibration_records if k == "family"] + arch_pairs = [(p, y) for k, p, y in calibration_records if k == "archetype"] + gate_pairs = [(p, y) for k, p, y in calibration_records if k == "gate"] + + fitted_t = None + if fit_temp: + # Fit temperature over the combined classification & gate predictions + fitted_t = fit_temperature(family_pairs + arch_pairs + gate_pairs) + + return BenchmarkSummary( + cases_count=len(cases), + total_runs=total_runs, + family_accuracy=family_acc, + archetype_accuracy=arch_acc, + block_precision=block_prec, + block_recall=block_rec, + abstain_rate=abstain_rate, + decision_latency_p50=_percentile(latencies, 0.50), + decision_latency_p95=_percentile(latencies, 0.95), + host_overhead_p50=_percentile(overheads, 0.50), + host_overhead_p95=_percentile(overheads, 0.95), + decision_calls_mean=mean_calls, + brier_family=brier_score(family_pairs), + ece_family=expected_calibration_error(family_pairs), + brier_archetype=brier_score(arch_pairs), + ece_archetype=expected_calibration_error(arch_pairs), + brier_gates=brier_score(gate_pairs), + ece_gates=expected_calibration_error(gate_pairs), + fitted_temperature=fitted_t, + case_scores=case_scores, + ) + + +def render_markdown(summary: BenchmarkSummary, backend_name: str) -> str: + """Renders a markdown report from the benchmark summary.""" + lines: list[str] = [ + f"## Decision Model Benchmark Summary: `{backend_name}`", + "", + ( + f"- **Cases Evaluated**: {summary.cases_count} ({summary.total_runs} total" + " runs)" + ), + f"- **Family Accuracy**: {summary.family_accuracy * 100.0:.1f}%", + f"- **Archetype Accuracy**: {summary.archetype_accuracy * 100.0:.1f}%", + f"- **Block Precision**: {summary.block_precision * 100.0:.1f}%", + f"- **Block Recall**: {summary.block_recall * 100.0:.1f}%", + f"- **Abstain Rate**: {summary.abstain_rate * 100.0:.1f}%", + "", + "### Latency & Overhead", + "", + ( + f"- **Decision Latency (p50 / p95)**: {summary.decision_latency_p50:.1f} ms" + f" / {summary.decision_latency_p95:.1f} ms" + ), + ( + f"- **Host Overhead (p50 / p95)**: {summary.host_overhead_p50:.1f} ms /" + f" {summary.host_overhead_p95:.1f} ms" + ), + f"- **Mean Decision Calls**: {summary.decision_calls_mean:.2f}", + "", + "### Calibration", + "", + "| Question Kind | Brier Score | ECE (10-bin) |", + "| :--- | :--- | :--- |", + f"| Family | {summary.brier_family:.4f} | {summary.ece_family:.4f} |", + f"| Archetype | {summary.brier_archetype:.4f} | {summary.ece_archetype:.4f} |", + f"| Gates | {summary.brier_gates:.4f} | {summary.ece_gates:.4f} |", + ] + + if summary.fitted_temperature is not None: + lines.extend([ + "", + "### Recommended Temperature", + "", + ( + f"Set `A2UI_DECISION_TEMPERATURE={summary.fitted_temperature:.2f}` for" + " optimal ECE calibration." + ), + ]) + + lines.extend([ + "", + "### Case Breakdown", + "", + ( + "| Case | Family | Archetype | Recall | Prec | Backend ms | Overhead ms |" + " Abstain |" + ), + "| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |", + ]) + + for cs in summary.case_scores: + fam_mark = "✓" if cs.family_accuracy >= 1.0 else f"{cs.family_accuracy:.0%}" + arch_mark = ( + "✓" if cs.archetype_accuracy >= 1.0 else f"{cs.archetype_accuracy:.0%}" + ) + rec_mark = f"{cs.block_recall:.0%}" + prec_mark = f"{cs.block_precision:.0%}" + ab_mark = f"{cs.abstain_rate:.0%}" + lines.append( + f"| `{cs.case.name}` | {fam_mark} | {arch_mark} | {rec_mark} | {prec_mark}" + f" | {cs.decision_latency_p50:.1f} | {cs.host_overhead_p50:.1f} |" + f" {ab_mark} |" + ) + + return "\n".join(lines) diff --git a/eval/a2ui_eval/decision_common.py b/eval/a2ui_eval/decision_common.py new file mode 100644 index 0000000000..93cf553260 --- /dev/null +++ b/eval/a2ui_eval/decision_common.py @@ -0,0 +1,125 @@ +# 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. + +"""Common utilities, backend factories, and metadata aggregation for decision eval.""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +from a2ui.inference_formats.decision import ( + DecisionBackend, + DecisionBlock, + DeterministicMockBackend, + JevHttpBackend, + LocalCrossEncoderBackend, + SynthesisOutput, + create_decision_backend, +) + +DECISION_BACKEND_NAMES: tuple[str, ...] = ("mock", "local", "jev", "step0") + +DECISION_METADATA_KEYS: tuple[str, ...] = ( + "decision_backend", + "decision_latency_ms", + "decision_calls", + "decision_confidence", + "decision_archetype", + "decision_answers", + "decision_fallback_source", +) + + +def build_decision_backend( + name: str | None = None, + *, + endpoint_url: str | None = None, +) -> DecisionBackend: + """Instantiates a DecisionBackend by short name ('mock', 'local', 'jev'). + + When `name` is None, `create_decision_backend()` reads from the environment. + + Raises: + ValueError: If `name` is not in `DECISION_BACKEND_NAMES`. + """ + if name is None: + return create_decision_backend() + if name == "mock": + return DeterministicMockBackend() + if name == "local": + return LocalCrossEncoderBackend() + if name == "jev": + import os + + if not os.environ.get("JEV_API_KEY") and not os.environ.get("TYPESAFE_API_KEY"): + raise ValueError( + "JEV_API_KEY or TYPESAFE_API_KEY must be set in the environment" + " to use the jev decision backend" + ) + return create_decision_backend( + "jev", + endpoint_url=endpoint_url or "https://api.typesafe.ai/v1/systemone", + ) + if name == "step0": + return create_decision_backend("step0", endpoint_url=endpoint_url) + raise ValueError( + f"Unknown decision backend: {name}. Expected one of {DECISION_BACKEND_NAMES}" + ) + + +def decision_metadata( + outputs: Sequence[SynthesisOutput], + *, + backend_name: str, + block: DecisionBlock | None = None, +) -> dict[str, Any]: + """Aggregates metrics and diagnostics from synthesized outputs into task metadata. + + Args: + outputs: Sequence of `SynthesisOutput` instances from synthesizing blocks. + backend_name: Short name of the decision backend ('mock', 'local', 'jev'). + block: Optional parsed `DecisionBlock` for additional context. + + Returns: + Mapping of metadata keys conforming to `DECISION_METADATA_KEYS`. + """ + del block + latency_ms = sum(out.decision_latency_ms for out in outputs) + calls = sum(out.decision_calls for out in outputs) + confidence = min((out.confidence for out in outputs), default=0.0) + archetype: str | None = None + fallback_source: str | None = None + answers_count = 0 + for out in outputs: + answers_count += len(out.decision_answers) + if archetype is None and out.layout_plan is not None: + archetype = out.layout_plan.archetype + elif ( + archetype is None + and out.component_tree_spec + and "archetype" in out.component_tree_spec + ): + archetype = str(out.component_tree_spec["archetype"]) + if fallback_source is None and out.fallback_source is not None: + fallback_source = str(out.fallback_source) + return { + "decision_backend": backend_name, + "decision_latency_ms": latency_ms, + "decision_calls": calls, + "decision_confidence": confidence, + "decision_archetype": archetype, + "decision_answers": answers_count, + "decision_fallback_source": fallback_source, + } diff --git a/eval/a2ui_eval/runner.py b/eval/a2ui_eval/runner.py index afaf604fd9..6f781520f9 100644 --- a/eval/a2ui_eval/runner.py +++ b/eval/a2ui_eval/runner.py @@ -76,6 +76,7 @@ "skill_mode", "elemental", "atom", + "decision", ) # Strategies run when none are named on the command line: the production diff --git a/eval/a2ui_eval/shared/utils.py b/eval/a2ui_eval/shared/utils.py index 698910d318..3d08caf796 100644 --- a/eval/a2ui_eval/shared/utils.py +++ b/eval/a2ui_eval/shared/utils.py @@ -13,15 +13,16 @@ # limitations under the License. import time -from inspect_ai.solver import Solver, solver, TaskState, Generate +from inspect_ai.model import CachePolicy from inspect_ai.model._model import sample_model_usage +from inspect_ai.solver import Generate, Solver, TaskState, solver from pathlib import Path GIT_ROOT = (Path(__file__).resolve().parent / "../../..").resolve() @solver -def measured_generate() -> Solver: +def measured_generate(cache: bool | CachePolicy = False) -> Solver: """Solver that wraps generate() and records the duration in metadata.""" async def solve(state: TaskState, generate: Generate) -> TaskState: @@ -36,7 +37,7 @@ async def solve(state: TaskState, generate: Generate) -> TaskState: before_output = usage_before.output_tokens if usage_before else 0 before_reasoning = usage_before.reasoning_tokens or 0 if usage_before else 0 - state = await generate(state) + state = await generate(state, cache=cache) usage_after = sample_model_usage().get(str(state.model)) after_input = usage_after.input_tokens if usage_after else 0 diff --git a/eval/a2ui_eval/strategies/__init__.py b/eval/a2ui_eval/strategies/__init__.py index a27a9bbb0a..28fab021ed 100644 --- a/eval/a2ui_eval/strategies/__init__.py +++ b/eval/a2ui_eval/strategies/__init__.py @@ -21,6 +21,7 @@ from inspect_ai.solver import Solver from ..runner import validate_strategy +from .decision import decision_solver from .format import ( compile_format_payload, format_solver, @@ -39,6 +40,8 @@ STRATEGY_OPTION_KEYS: tuple[str, ...] = ( "max_validation_retries", "subagent_format", + "decision_backend", + "cache_generations", ) @@ -50,6 +53,7 @@ def build(version: str, **options: Any) -> list[Solver]: format_name, version, max_validation_retries=options.get("max_validation_retries", 0), + cache=options.get("cache_generations", False), ) return build @@ -71,6 +75,15 @@ def _skill_mode(version: str, **options: Any) -> list[Solver]: ) +def _decision_strategy(version: str, **options: Any) -> list[Solver]: + return decision_solver( + version, + decision_backend=options.get("decision_backend"), + max_validation_retries=options.get("max_validation_retries", 0), + cache=options.get("cache_generations", False), + ) + + STRATEGIES: dict[str, Callable[..., list[Solver]]] = { "direct": _format_strategy("direct_json"), "subagent_tool": _subagent_strategy, @@ -78,6 +91,7 @@ def _skill_mode(version: str, **options: Any) -> list[Solver]: "skill_mode": _skill_mode, "elemental": _format_strategy("elemental"), "atom": _format_strategy("atom"), + "decision": _decision_strategy, } diff --git a/eval/a2ui_eval/strategies/decision.py b/eval/a2ui_eval/strategies/decision.py new file mode 100644 index 0000000000..bee2c41bbe --- /dev/null +++ b/eval/a2ui_eval/strategies/decision.py @@ -0,0 +1,223 @@ +# 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. + +"""Decision-model solver strategy for A2UI evaluation.""" + +from __future__ import annotations + +import asyncio +import json +import re +from typing import Any + +from a2ui.inference_formats.decision import ( + ArchetypeGrammar, + DecisionFormatFactory, + DecisionPromptGenerator, +) +from a2ui.parser.messages import to_message_dicts +from inspect_ai.model import CachePolicy, ChatMessageSystem +from inspect_ai.solver import Generate, Solver, TaskState, solver + +from ..decision_common import build_decision_backend, decision_metadata +from ..runner import ( + DEFAULT_PARSE_TIMEOUT_SEC, + build_catalogs_and_examples, + parse_and_validate, + runner_options_from_metadata, +) +from ..shared.utils import GIT_ROOT, measured_generate +from .format import ( + _CompileResult, + _apply_compile_result, + assemble_system_prompt, + retry_until_ok, +) + +_SURFACE_ID_PATTERN = re.compile( + r"['\"]surfaceId['\"]\s*:\s*['\"]([^'\"]+)['\"]", re.IGNORECASE +) + + +def _find_surface_id(completion: str, allowed_surface_ids: list[str]) -> str: + """The surface ID named in the decision block, or the first allowed one.""" + default_surface_id = allowed_surface_ids[0] if allowed_surface_ids else "main" + match = _SURFACE_ID_PATTERN.search(completion) + if match and match.group(1) in allowed_surface_ids: + return match.group(1) + return default_surface_id + + +def _decision_retry_prompt(error: str) -> str: + """Builds a corrective prompt when decision block synthesis fails.""" + if "could not choose components" in error or "abstained" in error: + return ( + "The layout engine could not choose components for this block; restate the" + " intent and give the payload descriptive keys. Fix the decision block and" + " reply with the complete corrected block only." + ) + return ( + f"Validation failed: {error}. Fix the A2UI decision payload and reply with" + " the complete corrected block only." + ) + + +@solver +def decision_system_prompt(version: str) -> Solver: + """Injects system prompt instructions using the decision inference format.""" + + async def solve(state: TaskState, generate: Generate) -> TaskState: # pylint: disable=unused-argument + catalog_path = state.metadata["catalog"] + resolved_catalog_path = str(GIT_ROOT / catalog_path) + options = runner_options_from_metadata(state.metadata, resolved_catalog_path) + + catalogs, examples = build_catalogs_and_examples( + resolved_catalog_path, + version, + options.to_dict() if options else None, + ) + generator = DecisionPromptGenerator( + catalogs, + examples=examples, + archetypes=ArchetypeGrammar.default(), + ) + generated_snippet = generator.generate() + + full_prompt = assemble_system_prompt(state, generated_snippet, "decision") + state.messages.insert(0, ChatMessageSystem(content=full_prompt)) + return state + + return solve + + +@solver +def compile_decision_payload( + version: str, + *, + decision_backend: str | None = None, + max_validation_retries: int = 0, +) -> Solver: + """Synthesizes decision blocks into validated A2UI JSON components. + + Runs the DecisionSynthesizer on the generated decision block, validates the + resulting A2UI messages using the Direct JSON validator, and stores the + compiled messages and decision metadata on the task state. + """ + measured = measured_generate() + + async def solve(state: TaskState, generate: Generate) -> TaskState: + if not state.output or not state.output.completion: + return state + + resolved_catalog_path = str(GIT_ROOT / state.metadata["catalog"]) + options = runner_options_from_metadata(state.metadata, resolved_catalog_path) + allowed_surface_ids = state.metadata.get("allowed_surface_ids", ["main"]) + + catalogs, _ = build_catalogs_and_examples( + resolved_catalog_path, + version, + options.to_dict() if options else None, + ) + backend = build_decision_backend(decision_backend) + factory = DecisionFormatFactory(backend=backend) + format_obj = factory.create_format(catalogs) + + async def attempt_synthesize(completion: str) -> _CompileResult: + surface_id = _find_surface_id(completion, allowed_surface_ids) + parser = format_obj.create_parser() + try: + outputs = await parser.synthesize_blocks( + completion, default_surface_id=surface_id + ) + except Exception as e: # pylint: disable=broad-exception-caught + return _CompileResult(error=str(e)) + + if not outputs: + return _CompileResult(error="No decision blocks produced any messages") + + backend_name = decision_backend or "mock" + meta = decision_metadata(outputs, backend_name=backend_name) + state.metadata["decision_latency_ms"] = ( + state.metadata.get("decision_latency_ms") or 0.0 + ) + meta.get("decision_latency_ms", 0.0) + state.metadata["decision_calls"] = ( + state.metadata.get("decision_calls") or 0 + ) + meta.get("decision_calls", 0) + for k, v in meta.items(): + if k not in ("decision_latency_ms", "decision_calls"): + state.metadata[k] = v + + all_message_dicts: list[dict[str, Any]] = [] + for out in outputs: + all_message_dicts.extend(to_message_dicts(out.messages)) + + if not all_message_dicts: + return _CompileResult( + error=( + "The layout engine could not choose components for this" + " block; restate the intent and give the payload descriptive" + " keys." + ) + ) + + formatted = ( + f"\n{json.dumps(all_message_dicts, indent=2)}\n" + ) + try: + await asyncio.to_thread( + parse_and_validate, + "direct_json", + version, + resolved_catalog_path, + surface_id, + formatted, + DEFAULT_PARSE_TIMEOUT_SEC, + options=options, + ) + except Exception as e: # pylint: disable=broad-exception-caught + return _CompileResult(error=str(e)) + + return _CompileResult(formatted=formatted, compiled_jsons=all_message_dicts) + + result, completion, _ = await retry_until_ok( + state, + generate, + attempt_synthesize, + max_retries=max_validation_retries, + retry_prompt=_decision_retry_prompt, + measured=measured, + ) + _apply_compile_result(state, result, completion) + return state + + return solve + + +def decision_solver( + version: str, + *, + decision_backend: str | None = None, + max_validation_retries: int = 0, + cache: bool | CachePolicy = False, +) -> list[Solver]: + """Assembles the solver chain for the decision inference strategy.""" + return [ + decision_system_prompt(version), + measured_generate(cache=cache), + compile_decision_payload( + version, + decision_backend=decision_backend, + max_validation_retries=max_validation_retries, + ), + ] diff --git a/eval/a2ui_eval/strategies/format.py b/eval/a2ui_eval/strategies/format.py index b00c62197c..ea6afe4f94 100644 --- a/eval/a2ui_eval/strategies/format.py +++ b/eval/a2ui_eval/strategies/format.py @@ -17,12 +17,14 @@ from __future__ import annotations import asyncio +from collections.abc import Awaitable, Callable from dataclasses import dataclass, field import json import re from typing import Any from inspect_ai.model import ( + CachePolicy, ChatCompletionChoice, ChatMessageAssistant, ChatMessageSystem, @@ -64,6 +66,49 @@ def _set_completion(state: TaskState, content: str) -> None: ) +def assemble_system_prompt( + state: TaskState, + generated_snippet: str, + format_name: str, +) -> str: + """Combines role, workflow, environment notes, snippet, and domain instructions.""" + role_description = state.metadata.get("protocol_role") or state.metadata.get( + "role_description", "" + ) + workflow_description = state.metadata.get("generation_rules") or state.metadata.get( + "workflow_description", "" + ) + + prompt_parts = [] + if role_description: + prompt_parts.append(role_description) + if workflow_description and format_name != "decision": + prompt_parts.append(f"## Workflow Description:\n{workflow_description}") + if format_name == "direct_json": + prompt_parts.append( + "## Environment Notes:\n" + "- When specifying `catalogId` (in `createSurface` as the surface" + " default, or on individual components and function calls), always" + " use the exact `catalogId` value(s) defined in the provided" + " Catalog Schema(s); never invent a custom or placeholder" + " `catalogId` URL or identifier (such as `example.com`), even if" + " the user prompt mentions a custom catalog.\n" + "- In `createSurface`, set `catalogId` to the primary catalog ID" + " as the surface default. Components or functions belonging to" + " secondary catalogs must specify their own `catalogId`." + ) + prompt_parts.append(generated_snippet) + a2ui_prompt = "\n\n".join(prompt_parts) + + domain_prompt = state.metadata.get("system_prompt", "").strip() + if domain_prompt: + return ( + f"## Domain Instructions\n{domain_prompt}\n\n## UI Protocol" + f" Instructions\n{a2ui_prompt}" + ) + return a2ui_prompt + + @solver def format_system_prompt(format_name: str, version: str) -> Solver: """Injects system prompt instructions using the selected format strategy.""" @@ -82,43 +127,7 @@ async def solve(state: TaskState, generate: Generate) -> TaskState: # pylint: d options=options, ) - role_description = state.metadata.get("protocol_role") or state.metadata.get( - "role_description", "" - ) - workflow_description = state.metadata.get( - "generation_rules" - ) or state.metadata.get("workflow_description", "") - - prompt_parts = [] - if role_description: - prompt_parts.append(role_description) - if workflow_description: - prompt_parts.append(f"## Workflow Description:\n{workflow_description}") - if format_name == "direct_json": - prompt_parts.append( - "## Environment Notes:\n" - "- When specifying `catalogId` (in `createSurface` as the surface" - " default, or on individual components and function calls), always" - " use the exact `catalogId` value(s) defined in the provided" - " Catalog Schema(s); never invent a custom or placeholder" - " `catalogId` URL or identifier (such as `example.com`), even if" - " the user prompt mentions a custom catalog.\n" - "- In `createSurface`, set `catalogId` to the primary catalog ID" - " as the surface default. Components or functions belonging to" - " secondary catalogs must specify their own `catalogId`." - ) - prompt_parts.append(generated_snippet) - a2ui_prompt = "\n\n".join(prompt_parts) - - domain_prompt = state.metadata.get("system_prompt", "").strip() - if domain_prompt: - full_prompt = ( - f"## Domain Instructions\n{domain_prompt}\n\n## UI Protocol" - f" Instructions\n{a2ui_prompt}" - ) - else: - full_prompt = a2ui_prompt - + full_prompt = assemble_system_prompt(state, generated_snippet, format_name) state.messages.insert(0, ChatMessageSystem(content=full_prompt)) return state @@ -216,6 +225,45 @@ def _retry_prompt(error: str) -> str: ) +async def retry_until_ok( + state: TaskState, + generate: Generate, + attempt: Callable[[str], Awaitable[Any]], + *, + max_retries: int, + retry_prompt: Callable[[str], str], + measured: Solver | None = None, +) -> tuple[Any, str, int]: + """Runs an initial attempt and retries up to max_retries when invalid.""" + if measured is None: + measured = measured_generate() + + completion = ( + state.output.completion + if state.output is not None and state.output.completion + else "" + ).strip() + result = await attempt(completion) + state.metadata["pass_at_1"] = result.ok + + retries_used = 0 + while not result.ok and retries_used < max_retries: + retries_used += 1 + prompt_text = retry_prompt(result.error or "") + state.messages.append(ChatMessageUser(content=prompt_text)) + state = await _generate_accumulating(state, generate, measured) + completion = ( + state.output.completion + if state.output is not None and state.output.completion + else "" + ).strip() + result = await attempt(completion) + + state.metadata["pass_at_k"] = result.ok + state.metadata["validation_retries_used"] = retries_used + return result, completion, retries_used + + @solver def compile_format_payload( format_name: str, @@ -254,26 +302,14 @@ async def solve(state: TaskState, generate: Generate) -> TaskState: allowed_surface_ids=state.metadata.get("allowed_surface_ids", ["main"]), ) - completion = state.output.completion.strip() - result = await _attempt_compile(ctx, completion) - state.metadata["pass_at_1"] = result.ok - - retries_used = 0 - while not result.ok and retries_used < max_validation_retries: - retries_used += 1 - state.messages.append( - ChatMessageUser(content=_retry_prompt(result.error or "")) - ) - state = await _generate_accumulating(state, generate, measured) - completion = ( - state.output.completion - if state.output is not None and state.output.completion - else "" - ).strip() - result = await _attempt_compile(ctx, completion) - - state.metadata["pass_at_k"] = result.ok - state.metadata["validation_retries_used"] = retries_used + result, completion, _ = await retry_until_ok( + state, + generate, + lambda comp: _attempt_compile(ctx, comp), + max_retries=max_validation_retries, + retry_prompt=_retry_prompt, + measured=measured, + ) _apply_compile_result(state, result, completion) return state @@ -299,6 +335,7 @@ def format_solver( version: str, *, max_validation_retries: int = 0, + cache: bool | CachePolicy = False, ) -> list[Solver]: """Assembles the solver chain for the specified evaluation strategy. @@ -309,7 +346,7 @@ def format_solver( validate_format(format_name) return [ format_system_prompt(format_name, version), - measured_generate(), + measured_generate(cache=cache), compile_format_payload( format_name, version, diff --git a/eval/bin/compare_strategies.py b/eval/bin/compare_strategies.py new file mode 100755 index 0000000000..8b46605367 --- /dev/null +++ b/eval/bin/compare_strategies.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 +# 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. + +"""Compares evaluation results across inference strategies from Inspect AI eval logs.""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +from typing import Any, Sequence + +from report_evals import extract_run_labels, load_log_data, strategy_summary + + +def find_eval_logs(paths: Sequence[str]) -> list[str]: + """Finds all .eval log files from a sequence of file or directory paths.""" + eval_files: list[str] = [] + for p in paths: + if os.path.isdir(p): + for root, _, files in os.walk(p): + for f in sorted(files): + if f.endswith(".eval"): + eval_files.append(os.path.join(root, f)) + elif os.path.isfile(p) and p.endswith(".eval"): + eval_files.append(p) + return sorted(eval_files) + + +def summarize_log_groups( + log_paths: Sequence[str], +) -> list[dict[str, Any]]: + """Loads eval logs and groups summaries by (version, strategy, decision_backend).""" + groups: dict[tuple[str, str, str | None], list[dict[str, Any]]] = {} + for path in log_paths: + try: + data = load_log_data(path) + except Exception as e: # pylint: disable=broad-exception-caught + print(f"Warning: could not load {path}: {e}", file=sys.stderr) + continue + labels = extract_run_labels(data) + version = labels.get("version") or "unknown" + strategy = labels.get("strategy") or "unknown" + samples = data.get("samples") or [] + backend: str | None = None + for s in samples: + b = s.get("metadata", {}).get("decision_backend") + if b: + backend = str(b) + break + key = (version, strategy, backend) + groups.setdefault(key, []).extend(samples) + + rows: list[dict[str, Any]] = [] + for (version, strategy, backend), samples in sorted(groups.items()): + synthetic_log = {"samples": samples} + summary = strategy_summary(synthetic_log) + rows.append({ + "version": version, + "strategy": strategy, + "decision_backend": backend, + "total_samples": summary["total_samples"], + "algorithmic_pass_rate": summary["algorithmic_pass_rate"], + "judge_pass_rate": summary["judge_pass_rate"], + "combined_pass_rate": summary["combined_pass_rate"], + "median_input_tokens": summary["median_input_tokens"], + "median_output_tokens": summary["median_output_tokens"], + "median_duration_seconds": summary["median_duration_seconds"], + "median_decision_latency_ms": summary["median_decision_latency_ms"], + "fallback_rate": summary["fallback_rate"], + "reask_rate": summary["reask_rate"], + "cached": summary["cached"], + }) + return rows + + +def render_markdown_table(rows: Sequence[dict[str, Any]]) -> str: + """Formats comparison rows into a Markdown table.""" + if not rows: + return "No evaluation logs found." + + lines = [ + ( + "| Strategy | Version | Backend | Samples | S1/2 Pass | Judge C |" + " Combined | In Tok | Out Tok | Duration | Decision ms | Cached |" + ), + ( + "| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: |" + " :---: | :---: | :---: | :---: |" + ), + ] + for r in rows: + backend_str = f"`{r['decision_backend']}`" if r["decision_backend"] else "-" + in_tok_str = ( + f"{int(r['median_input_tokens'])}" + if r["median_input_tokens"] is not None + else "-" + ) + out_tok_str = ( + f"{int(r['median_output_tokens'])}" + if r["median_output_tokens"] is not None + else "-" + ) + dur_str = ( + f"{r['median_duration_seconds']:.2f}s" + if r["median_duration_seconds"] is not None + else "-" + ) + dec_str = ( + f"{r['median_decision_latency_ms']:.1f}ms" + if r["median_decision_latency_ms"] is not None + else "-" + ) + cached_str = "yes" if r["cached"] else "no" + lines.append( + f"| `{r['strategy']}` | `{r['version']}` | {backend_str} |" + f" {r['total_samples']} | {r['algorithmic_pass_rate'] * 100:.1f}% |" + f" {r['judge_pass_rate'] * 100:.1f}% |" + f" {r['combined_pass_rate'] * 100:.1f}% | {in_tok_str} |" + f" {out_tok_str} | {dur_str} | {dec_str} | {cached_str} |" + ) + return "\n".join(lines) + + +def main(argv: Sequence[str] | None = None) -> int: + """CLI entrypoint for compare_strategies.""" + parser = argparse.ArgumentParser( + description=( + "Compare evaluation results across strategies from Inspect AI eval logs." + ) + ) + parser.add_argument( + "paths", + nargs="+", + help="Path(s) to .eval log files or directories containing them.", + ) + parser.add_argument( + "--json", + dest="json_out", + type=str, + default=None, + help="Optional path to write comparison summary as JSON.", + ) + args = parser.parse_args(argv) + + log_files = find_eval_logs(args.paths) + if not log_files: + print(f"No .eval files found in {args.paths}", file=sys.stderr) + return 0 + + rows = summarize_log_groups(log_files) + table = render_markdown_table(rows) + print(table) + + if args.json_out: + os.makedirs(os.path.dirname(os.path.abspath(args.json_out)), exist_ok=True) + with open(args.json_out, "w", encoding="utf-8") as f: + json.dump(rows, f, indent=2) + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/eval/bin/decision_bench.py b/eval/bin/decision_bench.py new file mode 100755 index 0000000000..51b78d80c8 --- /dev/null +++ b/eval/bin/decision_bench.py @@ -0,0 +1,201 @@ +#!/usr/bin/env python3 +# 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. + +"""CLI tool for benchmarking A2UI decision models against golden plans.""" + +from __future__ import annotations + +import argparse +import asyncio +from dataclasses import asdict +import json +from pathlib import Path +import sys + +from a2ui.core.basic_catalog import BasicCatalog +from a2ui.inference_formats.decision import DecisionSynthesizer, SynthesisConfig +from a2ui_eval.decision_bench import ( + load_plan_cases, + render_markdown, + run_benchmark, +) +from a2ui_eval.decision_common import build_decision_backend +from a2ui_eval.shared.utils import GIT_ROOT +from dotenv import load_dotenv + +load_dotenv() +load_dotenv(Path.home() / ".env") + +DEFAULT_CASES_PATH = GIT_ROOT / "eval" / "datasets" / "decision_plans" / "v1.yaml" + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Benchmark decision backend latency, accuracy, and calibration.", + ) + parser.add_argument( + "--backend", + choices=["mock", "local", "jev", "step0"], + default=None, + help="Decision backend to evaluate (mock, local, jev, or step0; default: env).", + ) + parser.add_argument( + "--two-stage", + dest="two_stage", + action="store_true", + default=None, + help=( + "Force two-stage batching (Stage 1: family/archetype, Stage 2: winning" + " archetype blocks)." + ), + ) + parser.add_argument( + "--single-stage", + dest="two_stage", + action="store_false", + help="Force single-stage speculative batching.", + ) + parser.add_argument( + "--cases", + type=str, + default=str(DEFAULT_CASES_PATH), + help="Path to YAML cases file (default: eval/datasets/decision_plans/v1.yaml).", + ) + parser.add_argument( + "--tags", + type=str, + default="smoke", + help="Comma-separated filter tags (default: smoke).", + ) + parser.add_argument( + "--repeat", + type=int, + default=3, + help="Number of times to run each case (default: 3).", + ) + parser.add_argument( + "--include-unverified", + action="store_true", + help="Include cases with verified=false.", + ) + parser.add_argument( + "--fit-temperature", + action="store_true", + help="Fit temperature T to minimize Expected Calibration Error.", + ) + parser.add_argument( + "--json", + type=str, + default=None, + dest="json_path", + help="Optional path to write raw JSON summary.", + ) + parser.add_argument( + "--markdown", + action="store_true", + default=True, + help="Render summary table in markdown to stdout (default: True).", + ) + return parser.parse_args(argv) + + +async def _async_main(args: argparse.Namespace) -> int: + cases_path = Path(args.cases) + if not cases_path.is_absolute(): + cases_path = GIT_ROOT / cases_path + + cases = load_plan_cases( + cases_path, + tags=args.tags, + include_unverified=args.include_unverified, + ) + if not cases: + sys.stderr.write(f"No cases found matching criteria in {cases_path}\n") + return 1 + + backend = build_decision_backend(args.backend) + backend_name = args.backend or getattr(backend, "name", "default") + catalogs = [BasicCatalog("v1.0")] + config = SynthesisConfig(two_stage_batching=args.two_stage) + synth = DecisionSynthesizer(catalogs, backend, config=config) + + try: + summary = await run_benchmark( + synth, + cases, + repeat=args.repeat, + fit_temp=args.fit_temperature, + ) + finally: + if hasattr(backend, "aclose"): + await backend.aclose() + elif hasattr(backend, "close"): + backend.close() + + if args.markdown: + md = render_markdown(summary, backend_name=str(backend_name)) + print(md) + + if args.json_path: + out_path = Path(args.json_path) + out_path.parent.mkdir(parents=True, exist_ok=True) + # Serialize summary to JSON + serializable = { + "cases_count": summary.cases_count, + "total_runs": summary.total_runs, + "family_accuracy": summary.family_accuracy, + "archetype_accuracy": summary.archetype_accuracy, + "block_precision": summary.block_precision, + "block_recall": summary.block_recall, + "abstain_rate": summary.abstain_rate, + "decision_latency_p50": summary.decision_latency_p50, + "decision_latency_p95": summary.decision_latency_p95, + "host_overhead_p50": summary.host_overhead_p50, + "host_overhead_p95": summary.host_overhead_p95, + "decision_calls_mean": summary.decision_calls_mean, + "brier_family": summary.brier_family, + "ece_family": summary.ece_family, + "brier_archetype": summary.brier_archetype, + "ece_archetype": summary.ece_archetype, + "brier_gates": summary.brier_gates, + "ece_gates": summary.ece_gates, + "fitted_temperature": summary.fitted_temperature, + "cases": [ + { + "name": cs.case.name, + "family_accuracy": cs.family_accuracy, + "archetype_accuracy": cs.archetype_accuracy, + "block_precision": cs.block_precision, + "block_recall": cs.block_recall, + "abstain_rate": cs.abstain_rate, + "decision_latency_p50": cs.decision_latency_p50, + "host_overhead_p50": cs.host_overhead_p50, + } + for cs in summary.case_scores + ], + } + with open(out_path, "w", encoding="utf-8") as f: + json.dump(serializable, f, indent=2) + + return 0 + + +def main(argv: list[str] | None = None) -> int: + args = parse_args(argv) + return asyncio.run(_async_main(args)) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/eval/bin/report_evals.py b/eval/bin/report_evals.py index d9f3c4088e..760d3bc1e8 100755 --- a/eval/bin/report_evals.py +++ b/eval/bin/report_evals.py @@ -206,6 +206,100 @@ def print_results_summary(log_data: dict[str, Any]) -> None: print("==================================") +def strategy_summary(log_data: dict[str, Any]) -> dict[str, Any]: + """Computes aggregate performance metrics for a strategy run. + + Returns a mapping of summary metrics: + - total_samples: int + - algorithmic_pass_rate: float (0.0 to 1.0) + - judge_pass_rate: float (0.0 to 1.0) + - combined_pass_rate: float (0.0 to 1.0) + - median_input_tokens: float | None + - median_output_tokens: float | None + - median_duration_seconds: float | None + - median_decision_latency_ms: float | None + - fallback_rate: float + - reask_rate: float + - decision_backend: str | None + - cached: bool + """ + samples = log_data.get("samples") or [] + total = len(samples) + if not total: + return { + "total_samples": 0, + "algorithmic_pass_rate": 0.0, + "judge_pass_rate": 0.0, + "combined_pass_rate": 0.0, + "median_input_tokens": None, + "median_output_tokens": None, + "median_duration_seconds": None, + "median_decision_latency_ms": None, + "fallback_rate": 0.0, + "reask_rate": 0.0, + "decision_backend": None, + "cached": False, + } + + a2ui_pass_cnt = sum(1 for s in samples if a2ui_scorer_passed(s)) + judge_pass_cnt = sum(1 for s in samples if judge_grade(s) == "C") + both_pass_cnt = sum(1 for s in samples if sample_passed(s)) + + inputs: list[float] = [] + outputs: list[float] = [] + durations: list[float] = [] + decision_lats: list[float] = [] + fallbacks = 0 + reasks = 0 + backend: str | None = None + + for s in samples: + meta = s.get("metadata", {}) or {} + if backend is None and meta.get("decision_backend"): + backend = meta.get("decision_backend") + in_tok = meta.get("inference_input_tokens") + if in_tok is not None: + inputs.append(float(in_tok)) + out_tok = meta.get("inference_output_tokens") + if out_tok is not None: + outputs.append(float(out_tok)) + dur = meta.get("inference_duration_seconds") + if dur is not None: + durations.append(float(dur)) + dec_lat = meta.get("decision_latency_ms") + if dec_lat is not None: + decision_lats.append(float(dec_lat)) + if meta.get("decision_fallback_source"): + fallbacks += 1 + if meta.get("decision_reasked"): + reasks += 1 + + cached = bool(inputs and all(tok == 0.0 for tok in inputs)) + + return { + "total_samples": total, + "algorithmic_pass_rate": a2ui_pass_cnt / total, + "judge_pass_rate": judge_pass_cnt / total, + "combined_pass_rate": both_pass_cnt / total, + "median_input_tokens": ( + statistics.median(inputs) if inputs and not cached else None + ), + "median_output_tokens": ( + statistics.median(outputs) if outputs and not cached else None + ), + "median_duration_seconds": ( + statistics.median(durations) if durations and not cached else None + ), + "median_decision_latency_ms": ( + statistics.median(decision_lats) if decision_lats else None + ), + "fallback_rate": fallbacks / total, + "reask_rate": reasks / total, + "decision_backend": backend, + "cached": cached, + } + + def generate_markdown_summary( log_data: dict[str, Any], accuracy_percentage: float, threshold: float ) -> str: @@ -274,9 +368,24 @@ def generate_markdown_summary( ) lines.append("") + has_decision = any( + s.get("metadata", {}).get("decision_stage") + or s.get("metadata", {}).get("decision_archetype") + for s in samples + ) + lines.append("#### Sample Results") - lines.append("| Sample / Task | Algorithmic | Judging | Inference Time | Status |") - lines.append("| :--- | :---: | :---: | :---: | :---: |") + if has_decision: + lines.append( + "| Sample / Task | Algorithmic | Judging | Inference Time | Path |" + " Decision ms | Status |" + ) + lines.append("| :--- | :---: | :---: | :---: | :---: | :---: | :---: |") + else: + lines.append( + "| Sample / Task | Algorithmic | Judging | Inference Time | Status |" + ) + lines.append("| :--- | :---: | :---: | :---: | :---: |") failures = [] @@ -299,10 +408,22 @@ def generate_markdown_summary( passed_sample = sample_passed(sample) sample_status_str = "PASS" if passed_sample else "FAIL" - lines.append( - f"| {name} | {a2ui_str} | {qa_val} | {inference_time_str} |" - f" {sample_status_str} |" - ) + if has_decision: + meta = sample.get("metadata", {}) or {} + stage = meta.get("decision_stage") or "-" + arch = meta.get("decision_archetype") or "-" + path_str = f"{stage} · {arch}" + dec_ms = meta.get("decision_latency_ms") + dec_ms_str = f"{float(dec_ms):.1f}ms" if dec_ms is not None else "-" + lines.append( + f"| {name} | {a2ui_str} | {qa_val} | {inference_time_str} |" + f" {path_str} | {dec_ms_str} | {sample_status_str} |" + ) + else: + lines.append( + f"| {name} | {a2ui_str} | {qa_val} | {inference_time_str} |" + f" {sample_status_str} |" + ) if not passed_sample: failures.append(( diff --git a/eval/bin/seed_decision_plans.py b/eval/bin/seed_decision_plans.py new file mode 100755 index 0000000000..7ab93edfc5 --- /dev/null +++ b/eval/bin/seed_decision_plans.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +# 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. + +"""Seeds decision plan cases from recorded Inspect AI evaluation logs.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sys +from typing import Any + +from a2ui_eval.shared.utils import GIT_ROOT +import yaml + +BIN_DIR = Path(__file__).parent.resolve() +if str(BIN_DIR) not in sys.path: + sys.path.insert(0, str(BIN_DIR)) + +from report_evals import load_log_data + +DECISION_PLANS_DIR = (GIT_ROOT / "eval" / "datasets" / "decision_plans").resolve() + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Seed unverified decision plan cases from evaluation logs.", + ) + parser.add_argument( + "logs", + nargs="+", + help="Paths to .eval log files or directories containing them.", + ) + parser.add_argument( + "--out", + type=str, + default=str(DECISION_PLANS_DIR / "seeded.yaml"), + help="Output YAML file path (must reside under eval/datasets/decision_plans/).", + ) + return parser.parse_args(argv) + + +def _validate_out_path(out_path: Path) -> Path: + resolved = out_path.resolve() + try: + resolved.relative_to(DECISION_PLANS_DIR) + except ValueError as exc: + raise ValueError( + f"Output file must be inside {DECISION_PLANS_DIR}, got {resolved}" + ) from exc + return resolved + + +def seed_cases_from_logs( + log_paths: list[str | Path], + out_file: str | Path, +) -> int: + """Reads eval logs and seeds decision plan cases into out_file.""" + out_path = _validate_out_path(Path(out_file)) + + existing_cases: list[dict[str, Any]] = [] + existing_names: set[str] = set() + + if out_path.is_file(): + with open(out_path, "r", encoding="utf-8") as f: + existing_cases = yaml.safe_load(f) or [] + for item in existing_cases: + if isinstance(item, dict) and "name" in item: + existing_names.add(str(item["name"])) + + new_cases: list[dict[str, Any]] = [] + + for log_path_str in log_paths: + log_path = Path(log_path_str) + files_to_process = ( + list(log_path.glob("**/*.eval")) if log_path.is_dir() else [log_path] + ) + + for f in files_to_process: + if not f.is_file(): + continue + try: + log_data = load_log_data(str(f)) + except Exception as exc: # pylint: disable=broad-exception-caught + sys.stderr.write(f"Warning: could not load {f}: {exc}\n") + continue + + samples = log_data.get("samples") or [] + for sample in samples: + meta = sample.get("metadata") or {} + raw_block = meta.get("decision_block") + if not raw_block: + continue + + if isinstance(raw_block, str): + try: + block_data = json.loads(raw_block) + except json.JSONDecodeError: + continue + elif isinstance(raw_block, dict): + block_data = raw_block + else: + continue + + sample_id = str(sample.get("id") or sample.get("name") or "sample") + arch = meta.get("decision_archetype") or "unknown" + case_name = f"{sample_id}_{arch}" + if case_name in existing_names: + continue + + intent = block_data.get("intent") or sample.get("input") or "" + payload = block_data.get("payload") or {} + mutable_paths = block_data.get("mutable_paths") or [] + decision_blocks = meta.get("decision_blocks") or [] + if isinstance(decision_blocks, str): + decision_blocks = [ + b.strip() for b in decision_blocks.split(",") if b.strip() + ] + + family = ( + meta.get("decision_family") + or meta.get("decision_stage") + or "monitor" + ) + if family == "archetype": + family = "monitor" + + case_stub: dict[str, Any] = { + "name": case_name, + "intent": intent, + "payload": payload, + "expected": { + "family": family, + "archetypes": [arch] if arch != "unknown" else [], + "blocks": { + "required": decision_blocks, + }, + "action_gate": "pass", + }, + "tags": ["seeded"], + "verified": False, + "source": { + "log_path": str(f), + "sample_id": sample_id, + }, + } + if mutable_paths: + case_stub["mutable_paths"] = mutable_paths + + existing_names.add(case_name) + new_cases.append(case_stub) + + if not new_cases and not existing_cases: + return 0 + + all_cases = existing_cases + new_cases + out_path.parent.mkdir(parents=True, exist_ok=True) + with open(out_path, "w", encoding="utf-8") as f: + yaml.safe_dump(all_cases, f, sort_keys=False) + + return len(new_cases) + + +def main(argv: list[str] | None = None) -> int: + args = parse_args(argv) + try: + added = seed_cases_from_logs(args.logs, args.out) + print(f"Seeded {added} new case(s) into {args.out}") + return 0 + except Exception as exc: + sys.stderr.write(f"Error: {exc}\n") + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/eval/datasets/decision_plans/schema.json b/eval/datasets/decision_plans/schema.json new file mode 100644 index 0000000000..47c5e055dc --- /dev/null +++ b/eval/datasets/decision_plans/schema.json @@ -0,0 +1,87 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "A2UI Decision Plan Benchmark Cases Schema", + "description": "Schema for golden decision plan cases used to benchmark layout synthesis and backend accuracy.", + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Unique identifier for this decision case." + }, + "intent": { + "type": "string", + "description": "User intent or instruction driving the UI synthesis." + }, + "payload": { + "type": "object", + "description": "Structured JSON data payload passed to the decision synthesizer." + }, + "mutable_paths": { + "type": "array", + "items": {"type": "string"}, + "description": "Optional list of JSON pointer paths that are mutable." + }, + "expected": { + "type": "object", + "description": "Expected synthesis outcomes for calibration and accuracy scoring.", + "properties": { + "family": { + "type": "string", + "description": "Expected high-level UI family (e.g. monitor, browse, inspect, act, input, follow)." + }, + "archetypes": { + "type": "array", + "items": {"type": "string"}, + "minItems": 1, + "description": "Acceptable archetype names for this case." + }, + "blocks": { + "type": "object", + "properties": { + "required": { + "type": "array", + "items": {"type": "string"}, + "description": "Block IDs required in the synthesized layout plan." + }, + "forbidden": { + "type": "array", + "items": {"type": "string"}, + "description": "Block IDs that must not appear in the synthesized layout plan." + } + }, + "additionalProperties": false + }, + "action_gate": { + "type": "string", + "enum": ["pass", "abstain", "any"], + "default": "pass", + "description": "Expected action gate behavior: pass means synthesized, abstain means blocked by action gate." + } + }, + "required": ["family", "archetypes"], + "additionalProperties": false + }, + "tags": { + "type": "array", + "items": {"type": "string"}, + "description": "Classification tags (e.g. smoke, regression)." + }, + "verified": { + "type": "boolean", + "description": "Whether this case has been human-verified as a ground truth target." + }, + "source": { + "type": "object", + "properties": { + "log_path": {"type": "string"}, + "sample_id": {"type": "string"} + }, + "additionalProperties": false + } + }, + "required": ["name", "intent", "payload", "expected", "verified"], + "additionalProperties": false + } +} diff --git a/eval/datasets/decision_plans/v1.yaml b/eval/datasets/decision_plans/v1.yaml new file mode 100644 index 0000000000..f260c7a64b --- /dev/null +++ b/eval/datasets/decision_plans/v1.yaml @@ -0,0 +1,145 @@ +U2FsdGVkX19pl9ZS7LaPUVUNO+MdLxqhZzZi+iYI2h4Hodxdfe+8HTWDEGEk6nYr +WTkbyPqnSknJP1gbD+OxcO7OIsiQU+/mw5rvIx8rit+JCWzR1pKpvXgwuvv27Wlk +lPYAEvmHQy/DyrxJ+GCa2KE2h1y5YXzzJ/6e0AIjfNaG5Xr8lTDFc9NrHMuWzB1K +jnrJ+9297Io0ZYg9eQCSI/4tn5u0Bgh9SR1sBsOPZIaO3W/AOjWL8byEem+VyqfA +QH4NPR93P9gOpd33TAJZDruS++XY5fzNI66saAwd2jiAJvm6Wls8YdiDxFC+VHJD +F3IRA/U0VniBwOWrUL1GakXCpwCeTtFfLkTTY+4hUevbh9MDpDsJzkIGXp2A0JM/ +8apScS6YKZVvBrUdR+9buI9c37x/XxBCa5oA5FOzYH0tgJhgzw7SjxsvepXNREQQ +C+9g7/1YmpVWUDSQ5bjoxxxHVSBd7pBVL86Zd/MZhK1/2L+CwXjYmqhm0VFUj7FG +9djZhQ2MN7PwHgkk0Bg/qodNyYM0tC1wd/hiu96I8JPp4cUVfQfYTjhG+qFjhcmX +fwgKWwQ042Wtx6qyIk52AushiWOW1Y99hSRA8pSnIgQ/xvFguU0MwC4Z649EWfMh +qf2+njAu0k6SHUmXb4NY5FdnQZT7xGI0gO8T5yEy3e3C3oJnLg8I3t2D87ctS/TZ +qpZ6+6qk8SbFdKgPDVkkKr3+AqI0J6HDVYsV1tFpK2rU+AcWQkhlrxNH/lER1mQt +iE9wBhGm/Wigw58zI2OLFQ9i2uc3aeqnIvc3Dw+XO1+pwutWOAjfZEHsqQl4NNSH +wOg6hsh8r8wXeo0kdAeFctkFwYIvU8bhiy+uUW6sVXFE5OpeCgLoqX5nTFDIan9C +rZSYs37ZxlgPFM4vA97kWQ7p59JxcuiiRCP2qdTS3O/24kGl0q2HCpTl394kOuzy +dX098ALjVaKOJ2HCf7hgzkCvxUvt5kOXwefTDJw1veoo62VZRTacuCgOVLDa6ZtJ +GZcKwnvdet6fSoIjcil9/8sMwGs1DB7igTxAGSNaxBNshpFh67WnkFJfh8Yjsn9S +lw6Qsl6V6rfrZCDB8AiAFzZy9KMXF9fuSIzbIdW3//c7WkZ2nj06ljOLM9pAAGyW +77SWuYUyCRkaucRYXjsFdi3xyEb1ogiGZf6Sp//u1LAPx5F2ZEEbBo0aA/pbU/4H +owBxxjqJMHifc3YMrWTzVwZ8iNskcz8T3VSdZE8TcqKsIWyVMHeWGqbduwEZCZU4 +qougOb7gheajZmRn06tOkhOSINwH0jIaHzZcRVwaPvqE1ljV73EiLU8UeRUtZ8T7 +R0lGpsvnwk28IbDbLVKe/5Py0p6WjdWcct7+cIIVjZXxVFMBawcnFphxBbzfG75u +UKfLa4CzN7bLIcqDXmqfaPSEW+2jRtiAjHeqcZ0rAG3AoaljL9xK8LCHfpi9w6hh +PY5gou2PDQHhqm3p5IEyyKV3ys0FcjkaIUq0efounsaiR9DQW9GXrDkPX/tpQpnh +bRpIQUJQ8Tur/z6wHNZO+YKkHf6YmjrNLEz9OAuHoUhE36vM3d4+k3iKcSez6i/x +ymqI5XutKC/kQIRkZcDlUPQnkUktikHDlD0m+XhwV6qF5KDDH4Epf6A3I4lKF+3j +Pg7LHxiMtr1LsfcNCo/w8mHduwfy4zjJlOmwAvIisFCtRPDApVZuwoTfNSP8UkyJ +2UPUOjPmUKyeaN0lpSoletroucOCh1YKvGhHzui2zTi0G4xOkV8CvTtNnrllysvJ +RepdMGXHmXtKUjIwk3FsvgDjcYyB77BtxllUJ/iXSEk0WT6Ao6xcTdGgkwjwT38j +IqiFd15gcW8uBFkmH6dVLFM5V744qeWsiNoM19+iPuj+Qy9GKPikDwnA8EVEsbUP +N+cpLXRkeHrGvdIH3sLm0gm3TDqQwm3jYzmg40nOZziDdHzLhQ8q6CmldY3I1wPI +TVoPKx07sqxUBtBV7k8Zn0i/C85YjgyHIr+mWyFJ14GePeO9NJ6qJ3542ca1WQzf +Xbej8zJUqCb62+/MrClmnh2FNNywK7o8plKCz8rxrVCv8AhMb0xWVPrMO+QyxEy0 ++tpzo2xHmHgVdmtzQrbcorX5Hg6UEMic1nJVzCIebJKnlbexosyjipoVr2ZJfoxg +/yYkG+MCcfgFjdImLTCO/mrPqR+vUgu3YKMmAtUg0v2RJqYDxlHoqvAXr/sL4uGn ++rdT2Mlg6ipuo5NzUMGK0IP6PxCq8rnGPEYYoq5t82NrgRa++lZOO8rMRpXD4yEA +EVJXDiI/aYLKNsAMBoKvnFEbSq3ATryRR2PSCko//pFWjrZ+Ju9UTNAWmdEnKUKm +KP8lCW5tLEQIJR6Df8HjJj8D3VpBxhl7x+2T0/tx/iV5M5zm1dR9uX/n6DpK3xnK +vEcoeOEkz+1d7VJIQ8k/RCVRX+ekMnB0wgDSzaDSFMfPNwYjvnfWx2mQrN0QEGJW +o26gN99KSzkSH2t458zUJZoRD5HEXOe9jFYj1F0gMLYaU7PJwJvE00TdZOAQaxav +6uSvuv7JJgVgw2bi2QX6MLu+DfrSdVS3jl9v5s/KCz9gfArADFxsagJ6SddVHwpA +CHhBsKiGTjczcnfc7mJIQVvBcb2SQ/0fOgqhosFS9WGhT9eBKJXLbBbJqfERApN3 +2yGdO0Dz4mcgzEhVh9qInQ5clPshFGYf2tgVaIYI+5n84an/Adf9MwE1JC/4tdBB +BX62wA0dkLhYcEx0o0YL99s2i4Q/JSPg+POYc+IeOHc8V9itgEUq4JoZg53JI/Y7 +HWD60TPDDiTkOVsaTd5L6+aKiUlafxiQOdBBW+ZLT2bfFaPRp32bbUPET/CZ+tvJ +ZVFo5/CtXS4PSUmE4bFafaeZqPOtHDbjzp3RNTHqnlhYd6m9VT0M2P/3eRY2zP2D +gdPdQdWTBf8DdlAy1+BeBiXvha4cNqgibn+Xm1T3aqQXlvMCv3hXpiisDg3zo8Zw +W4dLXp/vy3yg67htrGNgBgvTBkhD3dgRsVQAKIK1+vtxUJc4nv1p6khVvPZzj0V0 +bUGhaA+rZY4djieEytBvOMYopTKUBFYm3bZeu7j+w2HIak5/T95XwExTmcJ+6dpC +/ECUHh3jpeah4TR34/2vDs2pWeW3QUJzllRTYPCdNrRq2g30i6chnHEhyrsTqXWO +VLuAEPuVZzcZY0hLerVkpmOFCSdpP+inj6Sday7gH9KXsQ+NoYv2EdrMpq7Cr3D/ +X5LuW2lSYaenZ3xIcEkev7tVkGFq3wMhLYLtqWkZ4OelNA4JPOjgFM118s6LR2px +fmwMeYNSR30rq+mJHkMTrl8FBaNLFLO4zq+Y4fNPdLtEBH/hhH4zPxOBhZvJJbsB +n1dtb41qhUcbMYePDkqzS0hw1mgg+vkjLUSAZ2C+LUa6A08YVcGeFY3lE5ILcDYj +on3zDE57ncJzpcXCsWeNyo8C5ko/d9HqU2Z9QGeJtk9FRYvA6UsoQ0xcGhWThMbX +mwpfUvVskbTcLBYpNUd3ilt46vjlmiAn8ey/OitgEe9zNYqP0EDlJgaeZgO2xO39 +PPyBswrPl7C/XS+BSZcx6sk1shH/kksyRJ5tXOO0WWYka4XihWlcHh0Ddkf25Nft +vsk4FzW2n16QLl2WZrn+MbzD82ruLsSSHVhNhvtEkd5qW7h0qa2JGZ0GrLgVKz4/ +GO6oFgTSK3ObBdL7WxyGGQ5l1ldEL8WCL2chrN5sxLaPJYGmzmiTbEShQPWxySmF +XOLhXYDohO1GfbTqj9rewqWIRZejRVbOq8M2za+ekvwlWIWD7ayD3XgPGVn4ipp0 +aX/JBtxJVeNuPSCxT4E7xsuYvY4Xq3NklZ/huqqLajSB3dKuJEWfrNMfHL0uodRI +Xlozla7/mSPNZnBxlPnRnWcYA4lgVwip0MOQEYKB5G1F1y6HKDlebHjtSl3Jz5Fm +Rqd7RTPtmv1pHD8PcUFzs3Pr1xIL6Z6ILlHHfV+TX9P4iTFOn0TsZUEljfeTzfwG +AWpTZhsZb4j6NX9DXK+eAr8h1U3BzbR+y7FbPPYexeOtnNApfJu2MsOuoCfNlFo2 +DsI0zUYX16DPtka16fTXraDenPX2pLL0GN/VsXi4xcARECKJzUfxnUs2st70CQAH +jUrluZFK6uQCN3ETp/xjnWq513ad0a3VVSqJfHSIZiFIOws+A9X13Wt4yDan3PQD +WrmZgZwAe8v+/e1TeaEpLzmRP3FzW55NO793BjiM4E9LennfU5U1vEolhY26PN0M +mn3Pd21JvpwVscC6ogKWYRujK6zOUhF8cbhjhWFGoi8epNdkeQlYhVCt3Wy0poPt +L74iO/0t4ApKJDIMYG8bgJPZZ8VWXkPWFFFYS+GcTrenoyZWmmVw2R+SwGE5Kaa9 +iXXllMaETt60VZRbcOHst1vdOYJXF5FMNA4hUO3/IRnNUpSQ90Z+pAnM4D5/3aIi +z1iE/H8Rt23WDwbwneVvf4S/CIuykSpt3qi3Kn3pmsEuRT7cAaHahNtGK0c0gk3D +Jx6vspm4ypzda7RrlYquXnoN8uU7sXsgh/CHblH5hf+IDXQgtRaBcDD+tiyCg0ox +ILSCbpMDqo1EepYIpUM2Jsc8l0VSYlFGOtFLH6iIPpatmk3mMXIhuw5Mg0MP2OlN +G3YaaWKjRfm8mV2J7hV/7e4ludsc5ziZotwLRpKwbeoh3fS4UlmCn869qu5bEg4M +eVqQFdrpViFcVNvIagg14tEXuCRSJmik6pFNKIqVMyuDtyGV3sj8wBFerTB3lrVF +kRbbXyMSAyq7zyxdOS5VRxYgkmdarxpcpmngnQu3xhyKFvjIyiTooDhru+xFO0hK +MjfDU7yiPQ/7PDcw6POvdXwosOJdedcSmZYZtB0vhRvJtLdQpbOnhd1f7A2yvove +0oHP7vO7WbSoUVIHo+bUlk+jYdTB0cTMGbv+VYohP6kCWYYoXvEzBQ3HNu3ijUGk +9gyGoHTTqY5eNVyjXNjoohR+1d7PNWBcbRuJzXQE2tKRTLIy3akLxJnRQ6u3A9A6 +a8J3Xg3KWZO03/rPKZEDTtT1O/qCNIm40mhX054uLYwgMtUsbnFkgRJXX/xh1GHW +9V7UtBKmd3+aRrB1pN0En7lLkWJJAHCbiIRtCOsr0P1nzuFslG4lDsVuWGgI6CJk +UVTCnXHIlpGqGxOZ+QSWegZo7zBz3J31mGNk3UfbNI0uXoU2UmZ4U+5YOcReY9Nt +qtgfu789mB41wGPAdJeenq/UCfnT3vUf5wBtpi1JU9LqZqpJ0ElV0Ord+W6y2WHB +AdCa9MDyuT8o6TtQ8MS/ItAJuvBi7IkQSkoISQ28jFPMn+LWMhDracCh/knLUAGd +0bD4/soxAoLBF3YwOekLXvPrjCVPfmXiwYtRF609r9jb3naMv7u765W7agjsPAep +UVthmhk3/3ffCxrRHxw9aPfPzx6TkclpH8C0RpKndQDzQFxINdKfYnbPqk8Q3bbs +B602HZwZrvVDRqsYpYoQjrL4OCKB0PLi380xB0ZPoyE+MtXhargAc7SyrqKf0ZXB +C9en2D10ziuitTrTblH6LOS38XGfqhly64W883pHi4x31HBGrjzC+XP3TtjdFjla +Y/R8ZQvrAopiv6hUxHSb5MXeKGAEGJtwrY6vPgX8Fq/RKs7EuECkfXvwxMpgnnxt +mXapiQonrqVlNP5VCU2PE7SHPzs+nPMEXzYwSHVse7i/PHoonx/XyZqtPGAMIMjC +QCdB79167/BbHW8Jfich4dkr+v4g7CpSVnA066R6XDVZp70BX+JYpQfnqrKaXV8p +49Wb5QGAmgwJ4wE4MFB3mUqScBNNCsL36u/neaZe4fmjzptwrhYyudzApaoJoMxX +c7T/XQ71EVQZckRbXLz0aiEdP2tWIoUJX889tEY6vvLiKxGzPAnjBDIYVjuRigaY +8kpmTf6C9hZzEwRbq9C0vA/p43Xk1cufa8mGDcEWdzsYObsz1Iw6if4hmCuu8O1G +idk3OwW/tO6uyPTqm5zLt06UKTKwQcdEHqmssVbkybS3IvWEAi+niIsLO98ul891 +rh+tt+7bPGEPKvljrCz78S2lnJyxCxMFjD0+TJmBvfHqPHfJ6T16EBXFIr1PNKbB +CtElZlSzI6E7AFrbB+tgBDo2jnn/ML4y2j77+K9lD5sW87ExpZLYQsCbEBRlcNON +MMwGSAVLnIzitG3palqDKJu9UBZbmDHgeguaXdojlPPVKigL9UwqBjH9xySIC5Lr +AWX6mp1kcJREsOSkKNMEUYrhYINdrsmgLpMzIFKz/FShZzYRB/Mv7w8FwlLjA+/h +4I2MbJLK/ljv5QCSCNaCdKToywFMckPVmPsYyLEecZjGLfDznt4q22lKTJU5wptz +CpnQFA6tAg4IVq1WfoMKRY8KdXXcXehUwZ3oMR1LFHL/v7fvx4vyIXUBwtSoXIgR +dKl1B4yEyJJZahk5cNeJBYi9NIfcLr8zf8eYL9jTdV/2OPBVIuGO25sFWCbftCOV +99yxLn0pAfYk0Gaxh9hg3HvC1zJu+tPNCaERmltgT4E99U+miy7CXlLeNtK/xEcH +FvaCuylxsuE8tJD2tKzSBWNAGJwZLvgKCBbEDS2dGDDFdZ8ft4iZs136YiuCDHB7 +hjdyQyeerzJbyQcuxAfPN48so1NDQwYWERdiA3J3OXDTqDSik1sesCLYwyCBuRDd +foQHqVIUCd/pohQF8lwVgwqFKnBWGnaJbRrdsts/SEn7eOLa8sHG9NT9OEuzF6mp +SKeCzazaO2VozNMAKShPNpvGezq8yqStFLMBtQ2HPuI/aZ7lCKdVQum8oDsoyjIo +ihZAShkLm5yTyWMe4YwjZyJP9zmAR0RQrYbh3E9oPBQxePTszrGlUTHg9CWZIPyb +Zpr9ga0c94XqBT9QT9c1D/w35+I/gaQ4tOSEzB0hD6OmbyrD0ZWvukwMj79u+OQx +Lz91VbC5bkQgOBQIhgnLx4wIUYndZqCr9o++S6VRxWsocNlRbf9MNcGW6Q7ctqnB +oNxyc9B/ozC5kS0vANuZNGP3SiYitY6EcgtBj9okkVTOVlPHLxxi1jvvGW5DpFsO +J2+OdkMcLf48GsW8pwFxv9EVX5itiE5C2fuI03p4KGuGPjBJc/h0FeQnMYb3sf6P +CyLWkCbnScqAnQPhCWDQGj1daYfAAg0ZeOgqF/hBhLYipSfHJtHQgP911oV/KIQ0 +quoNYayL2kzSYDna3Da0lhXS/zbX9DtFOe2aSFmpUongpwugXOzTAnAvmZuXbs89 +wi/LDu9LejsxP6IEU5ut9baqlWz872TYLaEoNZpUxWaQtzG4Uxqw050mld4uSyr3 +O6gNnEtTHxS4SlcPk0C0xavDVnHMH6hQnyFMJpFq5vHhu5GvAqKqZzwsplayO4sF +EAtvKxjuY7XiB4B+1K4lSKtqetx3N+ik2hvl10QUGRWXPpE+9txu0pDxNABQIdK1 +vmQDOFNi9x8afS9dtMsUrxJY3fH9Wds8HfRRsxrJvpBYVyakYL9A9FW5U00onpXr +VZXIOaKGrY/6tZIt131TERltNvPr2g5aigk76kelxwU9Vu66cCwlXEYKzwadq9ks +MT50Oh5whRsQUyHBby+QuxHkypUB5m+HPU2SYDa10ZgdPqcCwBbNP20rIo6CaKdn +J5UhDHQsMtBiZZOBUE/CBIi/I6QlPEFPub1nA5aPFYDcw5XjU9GtEHyz/6Am+auB +KGgKi0Kdvlsl+q91lyGgVFeTdf8hlCguYtp/xpeOJpW5ynef6njA28DA95jn1NgD +1LmlopF4WU48PB+UYhWDruuJNZVMNJSoDN9Vu55mFft8IUnlIThKT9w5mL9p9hOg +2nN9JhIHBNojthApfEjyAyJO29NGm6MinGikz5dnxw9gnGN1ocBRsYrzN6w++74N +f13waOr9BDGOQTDSoKA6fZLYwLn9XiAhVJTaLrfxOyerI6QMLyc/5OyHjfNIWTBh +8oAYGVITOBOrZ1sPj10152r7/pxRFy3TeNrT6SW17trmb0u2YU4OYUadyl5/QWMa +5/Q0X/i1LegNqL2e9U1cyaCtIwb3Sg+ebXmGXjG7LgijEF4qmrY0pI7HsvUV7I8u +GhMvDyHnI6E86t7EUl6VNdYhc+WVucf7XYBqn7e0vh3179wCunGO/yVbf0QUA/TZ +o1sjv+Rc9J5KOwnwv0Dl4MgpdIZ+pwxTq6+3CLB6oMiWML9Wk10p6frhDEyo/W+4 +aGg0MfdbReRwAyUMftFe7hUNEvvpDbP6MtXiTjGX/1w+eeTXsOtkvmmGE6Acqj4k +XqIahanT6P8MHEd7aVKkPB1cwwXwIAXioC0Um5Q8jpC+wXI5kqXFv01ZryiCx+VT +biyBanJhiYd4WT9M4PjpJVh3cU15kHUFp+/SWUjn6RcpXZd7PaV+M9DNg8tfULF1 +ovLH8Ewx8jtGwFqtBGQl3r8HAGNUObOigKqfPmNcQlwnnoVLEqYngdwz9JSX4XNL +SdFrNCgnW0u7zHWj1k16DI+Aqn+wJ2QuLZ90inr0strguGjrEocIPQ0LjpGqBKlG +VzCabo/B415HRIo8oBcW9RHGPu9lp3ojgt11qfRX6D77jz0J5M5zpp3S1PJhIzgk +8nhlmkX317YjnZctaQCaf9VRz6+hSOLZTYdP4i6M4KoVacRxRQcL87yWzu+Hq/GB +H/yauYVKNx5jvFitxvLaH1c6+OmXGABsp8bihWsQhKGkSlH9vECD8bTyItwKI8mA +1V28JhIr2fX6JMeNUGXFUlH/J5zxbK+O+KVGclu1D7HCBYnFUGTYRRL0UzWSHf7e +uY6R7Us273T4WHODiKAxAxTeR8MSdazD4P/BIubqRq+1IlzwHHeE/D8lri/Zi9lm +EIGvWR8q8n0KyvfcAJS+/wR0xcVEEgLb+D9Tui11Jaza+/TTKSEHh2grLo0aYbRr +WRLzySD0nW5/TBDSAx4lheNHwnhUIkB2NiSPnrbYU9dXSDL+j30uO6qb6ndpfFwk +hQQBZod2xlMWCC0/c5OyABSEsZkvjFqg2Yf3DHn4GrHYRwJA5BOQN2RFlR0kh/d+ +Ohe8HOBJotQnMnsaAc4roZaJREqPkNtvhrPz7fYvVgO/H+y/woLWaFxp6IMAr40r +ZYvxWWjCMzjzP4iDITaLk4NEiFA9Tgz8Uum3qAbp0Q0XBdUUp/9x21WLMYxflTQs +duKgzJPX86ADuaCNzD0g/5nAb1WtJJi7YY3P+IXxynNjqnIflxcoNUy+jOffdRYz diff --git a/eval/datasets/decision_v1_0.yaml b/eval/datasets/decision_v1_0.yaml new file mode 100644 index 0000000000..afedac34ad --- /dev/null +++ b/eval/datasets/decision_v1_0.yaml @@ -0,0 +1,254 @@ +U2FsdGVkX19eRfKFSfBQs0lhWwD0xejJMY10nOwroxU1K9Ds1hv28WDSUseh9rax +aBAD5AQ6/4nT1SQc60Df97RgO1qK08zxa48SvoCzDZpTEyBYo28kzNEvdHzr6Nxl +Y8REPpbJrXcQtS8KpNAo38APR8bxeb9u+vwp9y6xgqcWw4YfbBUlzwwgHEkv4X+B +sofp3n06WCCazEOwyn4Mfkj6eeFIjAW6FIcaXmXcmlgK1c3zaXB6kb5b80EhLad1 +HEPdEJEDtMO1tOg49nQLYPBD4ZwkC0pQa8HZ7JsvLCZXsOAhIBt43xb/kPL9SIG1 +Hp1cFU/SoTDWdufstyxUpbFf2F3zECxEC+cbceSjr0FkhgCT836q4Gwuuap8K3hq +liXe5zbfh07Q7O1P/MXjWL3/Fs0Vp/UYovF77kG9kYOCNW/xfy737a+vDgexVT21 +k40BuNPDbHOETktGsaXVi/LKLxJ1cC7sp5B7vG5GNa9vitlrEBHVVu2L/CVWHc5u +x/S3Iw/vw6aJzgHeZbM3hV3zv1zeL0Lt59uswkNLrn1SZWQP6z7yIKdRK1z0PEmU +ip11TbaLwqLsO7QubehT7kPpC83/kTfOdk9SkGgELgousmUPtLklPjKy0CX+eziK +7gKzfP2JQdFBWbLR3gMMNfwUgn30j2iUBkRXd5SvlZWtwPAcJDhRjHyzH14hBhQ+ +vf5T1utwFwnXSru2QZBIxRj+K4oOQ+8okmqLb6Df3+TfYYA9uJrlRDXYOeNrzXKV +giFzm8OWZvOdiL6BAL72kxNONwW0LkhHpuLRGhHU/EoSaxnuHuzruwEjQUBFkxVE +a7OvJTVXgAZhHsORegx03za0GiP8RrKjdzHUAMRC+DSysY27J5vN7/c2+wOBS7yw +DJio6OSJZCPItsCrb7O3t068jwepi8LTvKmM4t33YTbJn+5YqZ664QDFpFF80ezZ +8d/B5fiIsNIyrsU+O2M/SowmmSDfofSVZlFq+dFz/ZbSbFyYqgkde4MAGaGBXi69 +I6zcsO9Z178hg4ujcJpBW20FcfeRP5n/ukDLvDRTj9qs3cngljHhuPKFndRBicBH +IFeiNGwzGUOUzZDIv0dR01g563YVCvmIwfBr6V0GsoiesqCLA8dtNWXtWI7KJG8Y +lfnq75+YwZgW2tvSdm7TRlQHw/LS9CydliDp0db89bXFKCIMEeY1SxMO4n73eQuo +woZqaN2ZJxzwYwpoSqXlog01swwIj7eH0upNWyKxSsgy2AxZ3Op/U7z8NkGhiHEP +gi7XNXPpfuC1Jzl6lRoqVHwFClFSeGG69G3ZVKYcm8fXevmKEyroIZ3Wa1hdROWv +3iRm/lhjMBRMzpUUd3+Jsg3Joe0pyXbX41eBxtaMQ9wMeo4ENFotZrE75PaY8zos +w7ZusPw5JXIPMOUEC9Grjfke5nsc2XP/EuiVEnwC3Usb9BtI+WQ1s/GipCW6VQYC +CZuWy7STn/udcwBM3XnTQVYBjadjckST3UEYC/JrjJcbeW28fzaWLOcEE31sMSD6 +QSsdOr+Pm72agtPwd4f/I3Mpa0SqqPA5OkPfYChbRP0A7zzzcGYVIRFe8gOtVn3M +p14hM7KHqOdjTqVnH0IZTQgo8bsDjx6OLEMvIqVW0+cGkoCNQibRZIbNHyY7RIVE +M3G08uBcwpnc9srTK7ELJfUDQjpbqbzy4sZl31ZUSsuNf3OYySP2YgjSRoW9MwI6 +KWvrr0zwyPF1z0bIaCbGQ0koGiyrk9kAGBgDF8mPjHBHXwbxuF4pMdyzfrfZoKPo +YJbbehDyZnU1alUkXyGzM0gg96pEx7/V7+IdPKNJUx2KJQlWQ4k3kvdkGTHk6/2p +OxxLvzJLuXNXCOFgbSsmIq5KKlapI4ovijFvo7HKQeoclmjC7oBAjK2lu/YDBPdD +v3/AWQ09OtPSnj7Imj/4bAl1hIkA33JkSfgIJw51vNKm7Ep/vSb9+/HPKUOeS3ms +7M3Fo+L2gijsRzwRkkewG53s3QXV4uohMqQo9HbUMe59/G7muhqp1wEPp3lxyMOh +qcAMYHAC3lo5mntjc9rCX3ukvrLnhD1xRVadHT/nnkajrPD9zNii0wJhBCuBfF6g +7hAGTsuJVRIX5EXAM/6chKkF+YDfSWshmXpPzgLqrQdiSeDTsaTGXRA9bvX/wsx4 +0//ipYpFdb4ZKa4SjrWwJ/OFnYGHq51Og7cQcagE8aTT77VtqGhv3IWoK+SgW0nm +E+dUiQZDwb+bHgH/Lc/vgCLVBtUQthd4p3YzGEH0jQzXU2mCsn6Fe876FV6wiuUU +kn+kG3j4dB5lOikyqaBI4RwYeH+H7vKFPStMHMTJpZ43AW1Wv9bNtTVDcj9hyvpU +iUt+wMEsr3gg0HF4OuCAswRjJZ5dl1zssjzj0Jjh4R3haN5HdTs5njHJTbDNKAIg +w0ksuBuvpJk3r3q/4VLSo1XcEVGZ1ICgt3HPbThBIFCyqNUS8bPw0qAlabddsYLO +Lup9uLv2pj3rBVFaSlfVJn8rpuRyQT9AGr6TF0own3GsdbCo35GXmGK2Rv4K1KbR +7rD4ldfc0o/RFnFrI2Tt7OcaRDbctc4mSODlPs9fSz7crpOMKo9VTvYpIWjQ66JM +uXIRgDnSpcx0qpcbgv9p4T0mXsR9zW/8ImxW7cLbVb7dWyBhrprt8Nf2f4DbU6qo +j0UMCFkdSP82b7zj18RcjToRN/ZBJg3xpQrVsMVh+hb5tmGUATZKAKY6YsrXcgxZ +sR8X91QjO5uhEB4WblaY9cVb2iT0d8uZPrSwSapl06mcbu5bBbiH6qP0QJIWusqr +ErOefSfoMFFPgvVTtXeoJ7JW65jEkFIlvEgX+VwPz8DRrn2+vPez+6zNmpm+nOSh +A3niQAZ5DMs64ldz/1kgnbAzjnvI/qwogH0j/1Jcv4WRiZ/mWbqzpmybMDQ6wyLa +xtMYEwhjHZCZrHimZvP+1XkpCFYa4VfINeREFM0gx8hImbNuV22IL2PMiqKdS9pJ +GRf1oZ1FbhHylDQ5JReUhjAegegkbleMFKd58N18h+uMbi6XMIqGohig3B0dbrpz +Cx7pSLnnnlV+gyfvNnAMbJbaWIXIJTRqpoeyHYJP0KHCuJCzV+nKkwE7L5whe/tH +jpoX311xvnZO25zL7W4wZczCUwfidCum7W3mu90tBILlWsoRsFJCFx43z6J5sYEv +bJfKDi/Uijre3hQvZcbNNZkyKWBYiK+3qkG8VVykDQjxE61vcpEyHxD1DDX9d+U2 +CeCRXwHX3dIkMdTNTKO8xyFBcI2s/d5+Tm504kyBaP6tB25WrpEllXKB+LI6RzH2 +SDBKAUYqiv8o/mQWCLa0+3u8oLNVW2dkB4CdIiiIryGdofsUOOR8u2jwGOQVZB9d +Ntlo48ROVwn/PvkPQY97rB7cRx5yF2jwwLLQvjVHx+/ah31y/99HHPmaR3CgO/XE +Mzj9wX3V1PC3YI0k0KJTKxNlZypWMgVp/R5INepruFvJ2qYax2HHw6WAqK8l5JHH +pmj1anSI8a/JLw6st8eZHUr6mCUW7O8wfYFGcrpjyBqO7hBIGbvIOxNSf1F2902V +EPengAtoxkqV5mVf6hqMoSn46Z/Tmq4ZOJZydOoKFfUOuB0WdvH+2JRYabnlhBqx +y6N9hjLJBZk0hyJIhueUn1dSndj8zwEkQ1NgkfblRIs1m22ZcjcTHu5QPvbzF+rV +rGCTOlhqlim5ShbQtME/n5ISTTqGFqBgqVQMuD4prjaxshVwlUb6aGiKGhgmPlRL +SohL5vzhZhzAvGtCSq1eZH9lKHXtM0+kG3jPLbEkf+Sa1o5ZSpBAavHqSzZoLN75 +MOXVKq/I6oDh6QKC2JEVpP3CSfYrCGnGOFyyMPNYUhI01BtJ39KqFHvGM7uAcHAg +wadxFKcOaBCj8cOSPCNiB4/Ys2o+cbn5L2fD8bsoyzQzN0V678138ClHQynnRBpK +sobospk+NJ+D+yoE3D8c9g3wUH3cbeaSojUJDMJ2Bs2d2nSZ448ObN/KJzn0oxhw +TBFEv+K+gu/nCCeOVZe8xuYVTBMZKC8PqTGrbjsDPYbF9Kijwa/vuBT2IRGci/vk +d9QF/+sfuUQZcJ1s3XAjYZmowvZWmN2vC2ZZKLRY80NjGM/JFxSALKDhejlCzEje +Z0U/aSTytB7reQC2TQxPA44o+TA6ZvkPt45Qi8et3njgiw8iVEz/LSLcKjPQJtqV +7pwUs4u+jOd44A79QyqZNyJVJbk62oV2PnnlpoL20Q4v1UCl3ytQUjtPbKEtvpXW +lmGsdBT53S72CVQ6Okh+qsLnoFJclqCdJatCkZUdA6WIStTWoLaydRBMBgoLveJc +wbm3l0KH0GcR5OMDvAk0i0AGaR0G1ZLUZJRhiyRBOs48IUO/Y8ZOdPixyxLzCuR7 +s5I2loZ6npChwD/2BrkX6LPF3vy3i+/nLb4Fedc+kWbeVhNfRluZ2jzfJ1H6hCip +6E7ylw3wCQG120NMCGwdNnWaxZyQ24EcGtdfdDMEwxOHOa1QidIzQKaq9564Ls+V +xJ2iCVzuoBdMxVvV4Ph75lE4nOT+sIfGxkGYt4pskWg7z1izTY9NUwjWIPhgXmuB +/IJ62755NP+zLDB/8hmWRcgkPQTQHRJcXW7YsXLl8s5XZJ7NMnH/KjS6auUj8JqE +NriMFIS8C3v9WMIPKzb5sCjcPyxkL1RnS+pptnzMi9ReVoaAhOaqaPHoJJwafxdI +gZ9Ac5R2AC8yBwzJDcFZqdE2KLPswrJFFkvnHI20RO96PAvAZdaVmmTJuRz1Pvjl +vrDWUEz6x4MNfvLaQ0pox2mvuUWyDre2a1aXB9Hdfy55qCUX0yTFy08Do/LNqT+S +sNI2zy+hoR4ZvTnAo/Ws6PaflHjLvj/Ri/ufnxZYqZn+CQX3vtBLNlFWbS3/IoOd +9VNWy0ZIVnXE4jDP93KPeQLQktGFQeBJu0B7OMOpXO3b06nybTgCoHXIdVkuSTJb +Qt66F5Mq3roUm9DUsrF9f4LgGjMeULC8C84QlChpmhNYPxeKerP1g1pw6XhzLby1 +PEg2DaNqHUq2yqTN6C0BR6S7TKeWrarhnLAglEjQ6IChqXkQ/ZHYBg5lvJMW0CXe +/0DnTT1uRg/5lBpYI7HKaAPFZUjwmfTYq/2BHuzFgT0tKC/Pl9dVBg+MfjPWHW6l +qADpNNwjgCsz+u2P/9aKqFhfErJWy1Q2oCvtCwWrr8o+5md3b1UF1UYot9LFCG2y +HY2no2kjd7dsdGnLPj+kb/w4mh4b3Se7epAOv81ES0f/aJ5kY8YwkAGM0LwW1bOR +PF9lyd9kfiWQ07okjXU43GPWSC9SM2ucgJ9+CZ4SVaIv9fGmy/ZVNQxGp7TC5Xcp +Y0Wm737EHAUHb28QcFpcAdAML22yxaY/X199bnTCQLn+EbLCq7DC6HpztuIjgF2h +L68W3vFg6gSlxo7YTRbwXSKePtc5WdCyA/hgsrKOJzVGRmckfUUsUXECFR8ZoHHu +8PBwAIfOf6qX80I31oILclYEPhMOQuQXu4dHXf/5Puk2gOtEne49shAxaIW8vFTt +sZt21dUbSZWyEoJwKbqNflpcYVdtlzOJi8I6DcwdBziZ7bXY4iytryNzVmZW7GFn +H8vVeMh3RSakSltcWoeY9S/FkAYrha/eXGHf8LMDoSoyn48eO51klsLg2FSZNJCH +CUOV4nC9GN60yJxQ+8KVUDOMnmTK1r/g4Bxd/n9BF69T2dR2fE1qvviGY2pUx+Po +UydrDHYR19f4sSePRWIkobBHk1NEzEoB/r1rmBMoRQ2dqwOeqDr0d5CqUt1Nj3OJ +NupDltkkHkmBeEvZLOLhQlQQ4r5B+YPx3U0z+k9b0pJxID/IAnOWIes+px5n9A8p +VeR5/QeDaGSKIQNEsiIE/VG8c07pR1DtVOR/rnAij/cTd62fLVMIY5bfADyisaZA +CtmmZj1zxb+cuQJjsFVrpKfQBOAXpT+deKu7qE9vZQxpxxXW2/Naw0tD0rpnQX3a +0gG2y30O56vfxDRF/xE2KCO/31Ei4KMT3x+byYoQI1D8bF4cI/de09HAxhX9maEn +zaxiazYrs5LRoHkHblez9NDqPt/6K/IB3xwhgT4gr2pVq8789CXooN0k0PCXRdP/ +orQI/Di6Vn90oL7aIK9itT5apN2xFvnQgFmxwAtil8qiRo0Mqq/HpNYcluudm0fd +03FvPn3Mc3KOl/SUG6CPOPDBCgPtCxSZ/wxd3Wg5ArKKFIdo8DKQiSp9drz1AEpY +uk+7zHG6DtjBomRbW3HByHDEtExwETeRoxmfnAQUmiSa+z6e41TOY4SeAl8nlFUi +DCeVKrzxcXOcOLTIYqayb3eQjaXKc7HVZ+yzb315VrcgvTAFdxLYIKu6sZiCDJ4c +jJBQrWpuJg8FKAo2qJcKtLiQ2kSjBSoxyl4xi9J+lWe7oVMBAY7x8RmtcYW0DkzY +OkWnDB6kmJo5SkyIQvZx/qbwFp3UgjZt1RMjUVTm0NMMr0qDgcFD5MgCYzO+kJKw +ta/tlGfdv5z99gI0PLT/JNlgPYCEK0Vm6ulmopDy68vlTe80qdOANaYWeaYA+XJs +2ktT94rXQN2bPj5QWzH+MriZ3I4OWIuBj++6oQSKJGpbobJEWgnolUNK8BKCj7w1 +DG3dGZ6Fc9HgyB1ogbamWPGEZ2wf9QWCxCY0b3FWepnHajI+/EyVvk1qUGatopdU +GB/WX1Y7y4B1ePAIqzO3owsFLtqgkwfN0kCOoViYBrPYvYPvsOD0NyMwXhVNZJOK +F/y3ln1iLuNhXGW28T95G/7ZouE53BiyCPXyeEakmZWrlaeTjpIVxREzoIVlaPV1 +PaOuNXlSFWOJUc7dP6cMp16snlx+7+/KpXEKYfKtQYuh9T/2ESnvG1wH0DR9lhM7 +mmMCOUvYGiFOyHiJq25Y7xuITZ5oj757WqhzKsAthTgNgvjL7zjmPPM75D4Pwhjv +A8M+6jntCjMar/gcng2UB2TLz/KdDTu3WsFuZgXlryEEAjuJZJoIHXokmovawVL1 +DYRRH5FsLeQS9Ufj2nrSKdiGrW0VxyupawhD+9lsySLprC5r6DtJQz4aaeNeqlLo +N0HOwhF2fQssZCPNkX1PkCjT1+q2v9DwwLhi9z4qzIRcgwkPDk1QpTmuelVG49cQ +R/HRXbfOf1yWpjLKvZI46T/GImvjDbz4bMCptXcYxtb86OyCniULp0IpqYkKsNMq +TyjbwnQ+LE78Bxr++6+OXM4piFdrUly8qRUt4PJ6CYKISskaKPq8uj1fjfyPtb+L +97mBc0dnp1JB4QZjZJXpyjXZX4IEX7dJRcgn57eT9VD4PNaXX9kwKlgscZqB29x5 +h5vjYhIWJs+mVuiWChxmSTjRwSpU1AZI3opD8lCsS0SvVHcC/mVUaUoTPTuLO8Q4 +za7lwDUalcQYENy3tYUqAWob4sUwgoBNBVW6VxHQKy0jpE8pxHrB2N5wgtN70WVJ +RF5dF9seVmlbef0UrMntDsFl/EjLnUWPUtUVQaTRY1/C2cS0Ns5dwCtjmKuyYV1L +fawOKkTKHDQc2OUmZgWNPL5qpNciifYy8EMdD/qQvD/7BR/fNq7qiI5ZzpBrJwld +3XFjAAjLGeJthvHHtlY4y6vXagSzSxFusgjb5l8UVARjGjldXJGRtIgrNW7JX95Q +/kKrivX7tYGaYlh1DvyC/+tvKTw02PX72XYC8e8BzuHNSBIBxh8lW4OC4sYxv59b +MJP//0Ht5TR6VcxEdXpbIA4EBFoMHKacTPPbv9d5unE2eELbQZp9vBtXVKR6ms7t +ZHnXu23tvnu+t+YFRuzQyilLU65q6jx0/FfttDe/7h7Lo2DkW7sowH7iFxix5y9w +Ql0sAmwWIno2ao7OAn+FrfuL7TonK/KatP/YoeXBPEgNs5D7WCwrO6JY3bh+rflq +s6Uhc3ASkkfa3SB5gXDq3jinUfPr/WWPKZfzZr2xFQKEYnKz1yvwRq/lOnEMFU7E +bf40vln1sHbGMcVbyxHUqWR+f/C2CVC+ikfvk7MsjuLI2URR5GPe+22fMVtiBu96 +/979DXazIOanBegsMNioZ3B2IF59VY/GWWLayOiwn7DO2keOSLQPqi846apmqaYw +oHNNut5/5z6q0kECgW06HW9/vXqg8zjwE+kTmawUDoGkmDw07IoK46a+5pmJmPT5 +8xEiMGHV0d0UDoMaTIyr//G7S7fYkSdjmIhdbJ0RnvzHQ6D0rVqBkQITeKnWNd1t +0A5rBTjsevBXUJ/35Jh9G9iCHxOUB+kLQ9egHdiCgQk4GNrCz3ubdxcfADX0pCPt +9EXkDCHrR6Wg7jgurnZl/9Y5Hcoo9HXR53uy/Pk/17lFqUW2FCFP6RCXx8yUNGrc +WPIIE0PqbC+slcE2ub73AaNDdVioznYfbjAYhpw0BqWCDYTvSk2ABCW9E+ZLSsKv +Y+c+r5KFzi3Yt2ZCyVuA+lOlVqqD+mn1fX6f1V7iRzJF2LyhYxVHSZol1cQYUhQx +OdSNjCKfGko4DNkuFExoBvcQ6IEvJ1pBi20GhQNGYyEkaMDTkfVjMTOwuK6uCh3Q +9KC5PlslKUiCM4pnej7Wm6GuPhEW+LWCkqrgG0662iuW/SuznEJknGKFu+Q6+IQZ ++FjQScjEYw2pUqFwOFv038croZha8H70qXgZKbhWQTOR31XOetSFB6H/zj+b8jia +a1k4r/lnZPngQrlHfT0bC8YFfGKfnBAyQoKwkYcu3MvNGHPEmvksCOZpDstjwo8q +sXXFspolGMm2MG+1QGF8/xSHIffAxYgV4wVirDFMeNPFtMV9NlBw9O5j9qQbhVtq +2HmeLRe25a2xZ/sM6a5rmuA8rj9uwSK+t+VnGGWvNzH30q5eSOuCWlKAEsiOqg05 +d1TcJyDF9zVL79rrYzyn9Uc+5rUb+t804bs+mEXGilcrABvyKcQuKWNy63Ev6J6W +BpLwbernXpIZBxQ2DVEHmZfK3z/e74GfUa4ZJwHacuPh1rDMH7ebSwcp+1ZYkWWC +PQRJ95yPYIH0NMo+B4FQmfnaA/9B1i+n+WI80fAzREsLXs7eN7Q/4ngpFVAONb8B +nT2lQW/xkzXTANNv4E9d5W2aGEjRYijJy2a6/I7ZXBiC1PN+qFNqYKqWTvdLhvU1 +gBVD64hMDhGr3LmQ0KakuRye/e5KUyAXAXqAaLbCZhFbC2gFjxG/JONOYpg/4nyX +k/o6pE2FZqlNcWEIsmVQB2WnJX+qsYwlD5SnoEtlMk7dJ5Hq+kX+QhBjHznwtYyG +cKbucgStpNqiQxgUtpspBS/Pe9XsVuwjz5SdOXnI1xxAJDD599rxxnfZIk5BWxRG +gNfHyNOzUGRXI+gfMF44nLA3HAMDQ/hokWKZNswicBg2g57h5Zd7rsYiWVxz724f +tD+OQVnF3dMnr/MPdxQPeUKxd4o0ccVTc+KqoVdjVxYt1radVCVnfZS78CfWZrD9 +Z73h5UMeVXuuZVCx+2Bp9slJL54i2n+wCqsMvH6wYsvmOAv3s5jR0PIFvO0U90Dj +/ZjZTLNvGKGgJb3ldqkBZ1rE/QI0ANgTDzoTRFgrotymQfO5izvHg0xMGooUpSnm +8967zxiD1qJnCXy7PpD6eKZTjJx54oP+Kzn1s2Mo2XTHhF2PEqIts0kyqUlX/yVD +ry3ZDix559YtowyhndOXfTHbWyQ0TL9HPSwyprkqH7oGHB65BR0r++yql5pTrFFx +EVkhaA8UQVJrVrvbLQzLx7mxGPyYYtw8/BowRUw02D1lGW7eZhiP1baFI7hkatu4 +a3AcaNQYZKOMwFjZa6jjqqUCgBAsG+WwerjYGIhXmAIFf47dmJ70zMLmC9lld1b3 +AqHuTyR39DVtsFiA8wjk4hein8qggtyZPCki0AYbrnS6Yy9DRfKuCP7js8l0Y4jq +uXpmoArODJSR62UH/hHlrsgtcpe5bq4OB2YEylFhMlO5l28w2f+5c25h82Ryrj6+ +NmsXg0zA3ZIpkHNtBHC/eln5f+r6tQNtoyWOjT7f3TaisFOPklixwUILHX9UqAhd +kjJ3kdSNmO6umV+YChDXRxMb1mlizkCiLLaIcqD+G443TBIMWUbZcpa7yvzUWQoV +zqToJ3hGWLw0YzBxqb/iP/swPXdoF6Uf8z0689e8wFe66tBuXpTeEugvC9afVyVx +hjqBzwBJvcaM8LUYbPNG6dBMhiBChZG86b+XvSoFyaYgWUHoN3XUTSOMIdVhk10Y +DI2fqkhpCZMaVfm1EK8f0lCmnfKVDBvQ/HUMhyQ+Bpuh05/Lf7LlnxLGHu1vmavR +7kbFp8yKAe+FZ8IwJddgWoSEP8YFEHAQ/Sz47Vg9DV4I9wTXJfAE49pQDi93+frE +YU6AlMYR1Xg2+tEtG7gwMWnPkNbqTo5WL+lU9ume9CQjfu5ZwShMB9lETsaaIxUE +Jh39GEBuewZUN8kq2k7qo7wH4Y+/ohLuvYBBeQla38+sSzsGAYw58Xf+DVwQJlTu +3D99Urj/yI/y0pV62/FOsBDPu2TE3FX+nMiy82aRZa+qLih+p0IdVvWUNoQx3e4Z +YtYulvHmDwFHqQY5Ym0n0Uyko+Foi0xFjW0DS7FTkMB0wapLuAVv1VhFe3vSAZpK +eiVxAvR+NO22NY8yxZ5XIvT6oX6x4yOWlN6Pi3NzqCv++gpOG7RgksHN9fUHmFUa +PriADsLI874GtYM1PKUpRtP1wguQVUsGBV4VhDaUTmSfH+W/SvG4niz8h8YWWk/o +QccciF8GAhJyUi7tsC6DoRDAjo32uxfPXSi3qStQlaydqiclBv5FrtTb05SFl7Bv +Qwq64MHLwChkwsWkzR+alk/V+LR9CmCcJYXphnZ3TxBpVHeBxVdhd9MruF59C8yS +4aGzkcA9156QWO5CxUwOv1O06s9eNBvTBLT0Oi529v8xUbHVeg+DBjUn71FsBocQ +cojZC73szSZR4C8TiAk4Rxv8FbppQLDhoB2uI3xzRM/O7VwN5cz5vq0igR6tJN92 +jXJeq+A8RaHtN8Mz/MCOxGWYtAiPUNKobosrHctN2GmY4VSgC9tfXwTWwZsSGom8 +pdftXZ+ZUukDIKUlqN6HYoOyMp948dqt5mFa/pSU6T25TbiS/p+fiT7atWvKHVD5 +X5uaUlTMpqjZlsSUYmgOTiRoTnbrreU33+9qXX4JSmO5vFyjTycOxJsnTVEgTnG3 +qr9qsy2F4ULY53UMw8Fr1PCEHTJF1a4WuuD+M9/a6+8oWW/SSc0bU0k/yp5nyy+U +37MXNjCzMK3kf3io3RCu9A76hpPNeVVMaz9FOFBU12src4d3JUovDS8USo02B5tO +FVI/owyG6xQ/jGtXCNdkGw46GtEz0sx1kRS4EPigWjcDHlZxudhzKmddhi4meqRs +cUm5iXG1gd/KDeg481A1Ht2eJnXt2vj5+M/14tlzgmmc+Tnxcao4MFVTHkvxOPW+ +K1lhbWPLCPFZhk9LgruR2icTA0uk4tNtadNge61jXM7/FTnpHcBFq1A1LtIf1yP4 +kam7Rg1z/hHsjPXonAV3u3JkqRXFte1LWBziU6XMcX1/SVs//ePQUK7uyI9jth8+ +Eg43X7fus3zIzD9lISIFWIGlnEKNNHA32/7AOkSZCO7yJd41vT4YCUGa912njF5J +tiqbf2zFDb4K9fcDdJzDbwq2Xi3OE9ULhvZTtrOzf1jELoMnOXTU4JUH0j2nAz72 +zIvPjoylAJGaimNKXho7fjbpj4g0DGO2Pb/N9L9mMQyR7Mvttq9jBbJFEdEY0Dl2 +laZStEghLdD9dFhWOkgU+/edksjposMN+Gsl7f5y0SIg21IoKgHuyR3e9ETs56xO +WzjvvAQPC+giYe/iTY4blynvApf9aywgTmLyEf6+q8CAdKlC+Jqs2sijN7mEtOFq +uJZ8oHO1ZZsetKwGnZxqFb93v7xeC0sa2SN1lYimTfMwtltcheRm7+8PDuH+O3Xq +Yi0K1nO8vYmhrinG0kydHVhRpIwPRfsAuDTtbHp/1gAokaqFIhQZkpyQULcFsgPy +8HjUCWo0f0C1TqcV0RQGpza5iJ1yaB19IGUdM/P7y1vCp1cn5isATtn2wJceSbe/ +AjIgpJ+rkVaGKUL9BIbJWdZkyJ6mOc2o0qXc/0hUxfsBY8wTMGCCMZwYLOOSuM1d +g/797bEi2DTSaC+mlvSpPzBW6hvo3uVL6qvIjuxGFvLrx8bbU2DtyOrVjJKLEn+/ +IR/WzXPKfGaRcQ8McZd+ONSyk9p60D43adLmJbQ6gHFkONJ3sKt5Kv5CIsFVG9mj +OIO8reOWDEqSUlJLUc/PdN3D2SDnAqz+2VpS8cnZVPkRkCelM8wBkawSd+Ditlmm +/NYlo2Q674l3lv54AwdC6XI5iCIqPHvNAzcNsxyXr/P6PQ0vC3twHLOwyAvKqfXm +1oAidyvty14E0dRxqkFmNVVTASVLVpGJbkwww7w2UVSvglDCeeepqUAUG2/9F7Wk +7Y5hT3FoOL0BxtUctCv4lvM86dDON8Q4a2XqFdDO4ykAQ8dAa83o3zYD4FG/3eDT +LY98/gbV1JSiK+qryoR+h3xQNAycyVbDPp/EBf1C02EjKhiE1DvsrNwHFPAjzibR +Dp58wHyNr4OfbroFcedLRNkAP22HF09gqCJO14yNMoBBLsXCj7Aveo4jVjU6fWfK +WE/ZXSH5ZZHcCIMph5w8uP3qzpDUrFDvKuQdvBZoxIDxUY/2uUwLeuD4/ZH7uNZM +cwXTl6kAQENW/yN2wWEH1+zoUwz2257rlj0RsqBJWoT+xvzAztwW8/rtlQeO6zkw +1EJapScqz6qb06wO5f0facGQjHUHOFQsFwJKpP3jnXePu6OUCQ+dQMSVtoPcXYDm +r4xnrWQVYdplC2mhtbeZdaHOAxEL7a1CAaTV/YPHs1k8HEthEEnlE8Gx1wZBZXOK +SiWPGU3++Qyn86eHNi2YxddfOKAcEBg89m6M+ZWzDyZExeO+i6ZvoEFSU2i8Bdvc +e7XGsXmufuRvpo0KyD/Xa5u6KWG1bVpn5Bg1ESyB9TTn23BZmeCr8Gy22lrh12Aq +pti5eX8HJ3lipOyh7zHi2ubSiPHkuGp23r/kZpV2eiGOokM8hYqmhWXlk5/L4X+M +qwSO3+3YKDJHedT00NpyWT9dIjed57K3p1WlBq/ATDPfXslFmby7995cpI7tZbBx +cJ2VwPD3WCeu3/Y0y0VZA6ZOU5OTq5Yn/69ILUMKPWvsaAtYdScFgFbwvzi+0zdM +mPsdJhMLW5N5KnqWYSLKaM39B886OJbRDrE+euDZvjydOaZn8NvhaONtTeE2h0k6 +AT8TRMmbatBtDpjHo3bSamo3QBMksdgUxMv3nXi5DLtvMZkggJOnKMsWewxPPz12 +j6KQ4XzxJ1UP3QSeaolt2mXlx015oCF6RB5VZPEievtv7JhMwmGct1hqTyHv22MT +LnpLGmZLbKSCm4Pim3QCBcdv30f2Z7BEnxMPRLWxierrhdW7gx8jBfYadAWy7MJv +kfxBy7d6Mw/oCnMBwZqzIaJhvofVZKr65ZK3bAVoFcDDuEqCW4neFFlP9YFEqweS +H/LY42/UU3Hu/ShQqwKU1cbCFF/xV1v9myTHR0JKbSA2g5CArk3esK+FBjvqxyvQ +zob1cVEtaveVUQG0Nl5qXNpZ9wjzswuC/0XBFCUswOn8LPFlxx/Ydml4Scgh5ZCF +fof9oSEbygkFHGA490Y4HJ4W4ZKGA1SyTmJzVWLFamp5/SJTDKRiwBXh2cb0cg4H +CVXsGAAiKuTmPXmIlpovN5kKUTTwMxywNZSF3O2Ad7iFRf6yJOSi08Zx3r2JWzXN +zZWwG9/88D9lspOJFqh3y/fLKTbniuRlaDJWYCf4pKGa+1RLT7auR9jKK5eZAfn/ +GfxqjWDQIE4RJCWXrQE7DPbdSGPQf7ST29BAlWYYFJgOqBZ9mpWPw+NVBnqH9yf5 +SdP8OQF4XalvxQ8fcWzPnXEqN/Qrimf9dWYT97oyiQQms97kK5vwHoofcMQTANL3 +xnMfciLj0tB6AslM8IklEfkabqDEKa+dE2zhAE9CBHxSW/UlYl3Rv33XlI4IvuiH +1trY7xvuOj/WSQnWC1SHeA/LXESDizcJNRahi8NgZy+1Tf7vK5IkK/EBHyM5GYxT +y5SKBEVVhwHs57NyskQ7BRI9aoovgZhtfEca8D/K9C2Hm00QvG10v6re6Ehd8dMG +KoHYzSMmLZbVdNzknpNaNRqDKefJW40a/er9LCUP17k/JMGo5H6JFqMxAOC5Z6/k +VLep7uT46lhotL8iXQ21qiDm4YSPmkPc2prVHKqmdL+ZxNwk5S6IImE8MqVOujv0 +6yqAcVg0ZoXDdbN7f+W1fjTiD+UMEMkWPJLKRyrQ7VgNtvBYU5uaL4NZyFA0Ok+G +EQLZ3yPimgK6AoEGosbDs9m4HqjpKKbQYyHO8eXpzTWhkeIs/tPAXRU03AZzFp4R +3lnJanvrkOcZ8QPF6RO/asaBgeHZqzsb9jL5i84PadQGzKBqJg6TLt9SJTLJpzA9 +H1mEE2rxRAmFNsQgh5yi2OUQoO1vG7Oh52FkCjV9RclmknVCNlbXmu4Nf0o6V+lK +fp3HUinhJHhNgtb/M/lLUcvoD4sRxSvSDtEO4c3Lh4sWAG2i3gPi5VTyVse16ks6 +nI9bC/zy2PHxyi9pNHiXGqWNj6xgOhX8zizmMn613eVuf+9XP7C9hwmj/IDiinma +JWko8Cc6Y5xddo/AI1DfUirwpUts355bX6xldutM1YUkFTJyEL0p9cG8vs5gIg31 +mbEdjggkRq4u5N89brObxzsHSVI9bAE9/NbUVBVxFopaQcn/CtQzBkZKl65074HJ +2DG914KCxuF2bdJ4/l9f/3ZX6ifrL1zI9xpe7fxJvyol18s7P++5VagFwEZYQB3Y +wzsV/srN86nk7OHDXK2hhlt/Mc6gEksE7NOuwCOm9YI+3L0Q0+nQZz2NgYUATN69 +8a7dU6xtIQmEcYIY8iGmOGCxo2NM19ekqRFEC10S0tTBUPpc/2RugOtiuUW7LXxf +Tzziz6PbhjWlQXnbvLPC2kQtKLwZrYZEgR+VW2W32HdX3ikG9mYme0VIYouKyR43 +Q7PUWD8xSeBym5xQYAKG4zQ5GCq2v/J1HUJ054HQKfnospy1/mfA+vdZMyyVRVNe +VRIcFYpsXmYAmceTd3fC718BJPnS2WAlADTDqqTFnLebaGieFfIduXeSZNF73fjs +XmJbcLufKacgZmXGBCb+YyrFouDduLcMr9BvBDPjpnj9jZ8QEqr5E8WCw/KvgY8o +Xm5r89c614jZgxPUXiexE4YPdceOXeLguX1AfWoNGmnFIKa+PKg5cd8nTrJzwqTN +Eft8gsFVpo7qnrpZJn+39smLaHmrrqZL1SS5BjRrdXfeUFtR6yJ7V3Ec2ndapQln +iAv3Pj2q5JV8c1zvAnaxXR5DvnsG4hz/kiihe6/009V4TJ5hKzXoVpt6jiJHJKpZ +03swmMs93sn/UJtO/MHuFWhobcIWMgggWoI2XuCiktFkVS9HGBjvCUulZbRq41iI +M2jMbLK4ZuukAkMIPHM28N7qDhgqzytED0VI2BRJLJ4FqL6lucoTjVZj65HPCv7X +K+JVk+mD0PNnKxnqNSEJ+dzgOdgw6ZDyy6OwOtOl6xrNpcTVjPkKTA5qBid/YJ5Z +3DAE/6aT4nUsbAGhD317D1bIcjK6aWGQkl909D2GQcq3NigZXtKgNNTfulO2J8vg +y66l6CIn0TBO5c6lPogCjvqy+o3A449qj+yth8eRiUUDDpG3g7pIcf1/qHPDmZIv +m3fb+6F6DnlUI+Pn/3O6vVNztwReEKr1D5idJ1bUbvUPbLCms5v6ljidfpxseZUM +k9CfnMOEcOkJUA0uSvZV+a+FORFtw66RvaWTgZiKXMPopRyATT/tFvPibjoT22b9 +2PwK6r0NHfHtt6oQv0wQrOdqYKFfHE6L7Kn1XRi7sf406c5wC0sdK8qzm9nDIrO0 +NFo6m/foyTLUFzZrcfy02HCO+G6U6w5BwuqAF+tqbweJwRD6lfV0dQcBDOSEi0vR +c9dyYG31bS6oPVKXk8zym/9p+pEFhXz0AXesSFk8aa2LSdF8DjTFtZ2hG/OMR6g+ +toh9NBM/GjDofRMXJKexGoImdUsO7Mq5EaSRBKxvDuQ0f3EQfwCJt8frsal4zHDr +SxjHNnN58E4BcQCG683EnQ== diff --git a/eval/main.py b/eval/main.py index 2b3edd892a..466b58769d 100644 --- a/eval/main.py +++ b/eval/main.py @@ -326,11 +326,25 @@ def main() -> None: action="append", help=( "Evaluation strategies to run (choices: direct, subagent_tool," - " express, skill_mode, elemental, atom). Can be comma-separated or" - " specified multiple times. Defaults to the production strategies" - " direct, subagent_tool and express." + " express, skill_mode, elemental, atom, decision). Can be" + " comma-separated or specified multiple times. Defaults to the" + " production strategies direct, subagent_tool and express." ), ) + parser.add_argument( + "--decision-backend", + choices=["mock", "local", "jev"], + default=None, + help=( + "Decision backend to use for the decision strategy ('mock'," + " 'local', 'jev')." + ), + ) + parser.add_argument( + "--cache-generations", + action="store_true", + help="Cache LLM generations using Inspect's GenerateConfigArgs.cache.", + ) parser.add_argument( "--profile", choices=sorted(RUNTIME_PROFILES), @@ -475,6 +489,10 @@ def main() -> None: task_kwargs["max_validation_retries"] = args.max_validation_retries if args.subagent_format != "direct_json": task_kwargs["subagent_format"] = args.subagent_format + if args.decision_backend: + task_kwargs["decision_backend"] = args.decision_backend + if args.cache_generations: + task_kwargs["cache_generations"] = True task_obj = task_func(**task_kwargs) if args.prompt and getattr(task_obj, "dataset", None) is not None: diff --git a/eval/tasks.py b/eval/tasks.py index d265f4f39c..0c214d12cb 100644 --- a/eval/tasks.py +++ b/eval/tasks.py @@ -129,6 +129,8 @@ def build_task( no_judge: bool = False, max_validation_retries: int = 0, subagent_format: str = "direct_json", + decision_backend: str | None = None, + cache_generations: bool = False, ) -> Task: """Builds the evaluation task for one protocol version. @@ -142,10 +144,14 @@ def build_task( no_judge: Skip the LLM judge and grade on Stage 1 and 2 only. max_validation_retries: Validation self-retries per sample (Pass@K). subagent_format: Inference format of the `subagent_tool` specialist. + decision_backend: Short name of the decision backend ('mock', 'local', 'jev'). + cache_generations: Whether to cache LLM generations across runs. """ _check_task_inputs(active_version, dataset) format_name = ( - strategy if strategy in ["express", "elemental", "atom"] else "direct_json" + strategy + if strategy in ["express", "elemental", "atom", "decision"] + else "direct_json" ) if strategy == "skill_mode": format_name = "express" @@ -167,6 +173,8 @@ def build_task( version=active_version, max_validation_retries=max_validation_retries, subagent_format=subagent_format, + decision_backend=decision_backend, + cache_generations=cache_generations, ), scorer=[ a2ui_scorer(version=active_version), @@ -183,6 +191,8 @@ def build_task( "max_validation_retries": max_validation_retries, "no_judge": no_judge, "tags": tags, + "decision_backend": decision_backend, + "cache_generations": cache_generations, }, ) @@ -197,6 +207,8 @@ def a2ui_v0_9_1_eval( no_judge: bool = False, max_validation_retries: int = 0, subagent_format: str = "direct_json", + decision_backend: str | None = None, + cache_generations: bool = False, ) -> Task: """Evaluation task for A2UI v0.9.1 protocol generation. @@ -209,6 +221,8 @@ def a2ui_v0_9_1_eval( no_judge: Skip the LLM judge and grade on Stage 1 and 2 only. max_validation_retries: Validation self-retries per sample (Pass@K). subagent_format: Inference format of the `subagent_tool` specialist. + decision_backend: Short name of the decision backend ('mock', 'local', 'jev'). + cache_generations: Whether to cache LLM generations across runs. Returns: An Inspect Task object configured for A2UI v0.9.1 evaluation. @@ -225,6 +239,8 @@ def a2ui_v0_9_1_eval( no_judge=no_judge, max_validation_retries=max_validation_retries, subagent_format=subagent_format, + decision_backend=decision_backend, + cache_generations=cache_generations, ) @@ -238,6 +254,8 @@ def a2ui_v1_0_eval( no_judge: bool = False, max_validation_retries: int = 0, subagent_format: str = "direct_json", + decision_backend: str | None = None, + cache_generations: bool = False, ) -> Task: """Evaluation task for A2UI v1.0 protocol generation. @@ -250,6 +268,8 @@ def a2ui_v1_0_eval( no_judge: Skip the LLM judge and grade on Stage 1 and 2 only. max_validation_retries: Validation self-retries per sample (Pass@K). subagent_format: Inference format of the `subagent_tool` specialist. + decision_backend: Short name of the decision backend ('mock', 'local', 'jev'). + cache_generations: Whether to cache LLM generations across runs. Returns: An Inspect Task object configured for A2UI v1.0 evaluation. @@ -266,4 +286,6 @@ def a2ui_v1_0_eval( no_judge=no_judge, max_validation_retries=max_validation_retries, subagent_format=subagent_format, + decision_backend=decision_backend, + cache_generations=cache_generations, ) diff --git a/eval/tests/decision_fixtures.py b/eval/tests/decision_fixtures.py new file mode 100644 index 0000000000..0553cfe619 --- /dev/null +++ b/eval/tests/decision_fixtures.py @@ -0,0 +1,135 @@ +# 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. + +"""Standard decision block fixtures and scripted answers for evaluation tests.""" + +from __future__ import annotations + +from collections.abc import Mapping +import json +from typing import Any + +from a2ui.inference_formats.decision import ( + DecisionBlock, + DeterministicMockBackend, +) + +HOST_BLOCK: str = json.dumps({ + "intent": "Show CPU utilization for prod-1", + "payload": { + "host": "prod-1", + "cpu": 0.78, + "cpuDelta": 0.12, + "status": "degraded", + "uptimeHours": 412, + }, + "layout": ["headline:cpu,cpuDelta,status", "facts:host,uptimeHours"], +}) + +HOST_DECISION_BLOCK: DecisionBlock = DecisionBlock.from_mapping(json.loads(HOST_BLOCK)) + +HOST_ANSWERS: dict[str, Any] = { + "family": ("monitor", 0.90), + "stakes": 1.0, + "urgency": 1.4, + "archetype:monitor": ("dashboard", 0.85), + "gate:banner": 0.80, + "gate:headline": 0.90, + "gate:facts": 0.80, + "anatomy:headline.deltas": 0.85, + "salience:/cpu": 2.8, + "salience:/status": 2.1, + "salience:/uptimeHours": 1.2, + "salience:/host": 0.4, + "instance:banner.tone:/status": ("warning", 0.90), + "instance:headline.news:/cpu": ("bad", 0.85), + "instance:headline.state_tone:/status": ("warning", 0.80), +} + +TRANSFER_BLOCK: str = json.dumps({ + "intent": "Confirm sending $50 to Alex before it goes through", + "payload": { + "amount": 50, + "currency": "USD", + "recipient": "Alex Chen", + "fee": 0.5, + "arrives": "2026-10-24", + "actions": ["Send", "Cancel"], + }, + "layout": ["facts:amount,recipient,fee,arrives", "actions:actions"], + "mutablePaths": ["/actions"], +}) + +TRANSFER_DECISION_BLOCK: DecisionBlock = DecisionBlock.from_mapping( + json.loads(TRANSFER_BLOCK) +) + +TRANSFER_ANSWERS: dict[str, Any] = { + "family": ("act", 0.85), + "stakes": 2.1, + "urgency": 0.6, + "archetype:act": ("confirm", 0.90), + "gate:banner": 0.20, + "gate:prose": 0.45, + "gate:facts": 0.85, + "gate:actions": 0.90, + "instance:actions.primary:/actions": ("Send", 0.90), + "instance:actions.destructive:0": 0.80, + "instance:actions.destructive:1": 0.10, + "salience:/amount": 2.9, + "salience:/recipient": 2.6, + "salience:/fee": 1.9, + "salience:/arrives": 1.7, +} + +SETTINGS_BLOCK: str = json.dumps({ + "intent": "Playback and notification settings", + "payload": { + "playback": { + "skipForward": "30 seconds", + "autoDownload": True, + "speed": 1.25, + }, + "notifications": {"newEpisodes": True, "digest": False}, + "account": {"signOut": "Sign out"}, + }, + "layout": ["groups:/playback,/notifications,/account"], + "mutablePaths": ["/playback", "/notifications", "/account"], +}) + +SETTINGS_DECISION_BLOCK: DecisionBlock = DecisionBlock.from_mapping( + json.loads(SETTINGS_BLOCK) +) + +SETTINGS_ANSWERS: dict[str, Any] = { + "family": ("input", 0.80), + "stakes": 1.2, + "urgency": 0.2, + "archetype:input": ("settings", 0.90), + "gate:groups": 0.90, + "gate:actions": 0.20, + "instance:groups.row_kind:/playback/skipForward": ("value", 0.90), + "instance:groups.row_kind:/playback/autoDownload": ("switch", 0.95), + "instance:groups.row_kind:/playback/speed": ("value", 0.70), + "instance:groups.row_kind:/notifications/newEpisodes": ("switch", 0.90), + "instance:groups.row_kind:/notifications/digest": ("switch", 0.90), + "instance:groups.row_kind:/account/signOut": ("danger", 0.90), +} + + +def scripted_backend( + answers: Mapping[str, Any] | None = None, +) -> DeterministicMockBackend: + """Returns a `DeterministicMockBackend` seeded with `answers`.""" + return DeterministicMockBackend(scripted_answers=answers) diff --git a/eval/tests/test_compare_strategies.py b/eval/tests/test_compare_strategies.py new file mode 100644 index 0000000000..02a2873611 --- /dev/null +++ b/eval/tests/test_compare_strategies.py @@ -0,0 +1,183 @@ +# 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. + +"""Unit tests for the compare_strategies CLI utility.""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +import sys +from typing import Any +from unittest.mock import patch + +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../bin"))) +from compare_strategies import ( + main, + render_markdown_table, + summarize_log_groups, +) + + +def _synthetic_log( + strategy: str, + version: str, + *, + decision_backend: str | None = None, + samples_count: int = 2, + input_tokens: list[int] | None = None, + output_tokens: list[int] | None = None, + durations: list[float] | None = None, + decision_latencies: list[float] | None = None, + s1_pass: bool = True, + judge_grade: str = "C", +) -> dict[str, Any]: + samples = [] + for i in range(samples_count): + in_tok = input_tokens[i] if input_tokens else 500 + out_tok = output_tokens[i] if output_tokens else 100 + dur = durations[i] if durations else 1.2 + dec_lat = decision_latencies[i] if decision_latencies else 25.0 + meta = { + "name": f"sample_{i}", + "strategy": strategy, + "version": version, + "inference_input_tokens": in_tok, + "inference_output_tokens": out_tok, + "inference_duration_seconds": dur, + } + if decision_backend: + meta["decision_backend"] = decision_backend + meta["decision_latency_ms"] = dec_lat + meta["decision_stage"] = "archetype" + meta["decision_archetype"] = "dashboard" + + scores = { + "a2ui_scorer": {"value": 1.0 if s1_pass else 0.0}, + "measured_model_graded_qa": {"value": judge_grade}, + } + samples.append({ + "id": i + 1, + "metadata": meta, + "scores": scores, + }) + + return { + "eval": { + "metadata": { + "strategy": strategy, + "version": version, + } + }, + "samples": samples, + } + + +def test_summarize_log_groups_and_metrics() -> None: + log_express = _synthetic_log( + "express", + "1.0", + samples_count=2, + input_tokens=[400, 600], + output_tokens=[80, 120], + durations=[1.0, 1.4], + ) + log_decision = _synthetic_log( + "decision", + "1.0", + decision_backend="mock", + samples_count=2, + input_tokens=[200, 300], + output_tokens=[20, 40], + durations=[0.4, 0.6], + decision_latencies=[20.0, 40.0], + ) + + fake_logs = { + "/fake/express.eval": log_express, + "/fake/decision.eval": log_decision, + } + + with patch("compare_strategies.load_log_data", side_effect=lambda p: fake_logs[p]): + rows = summarize_log_groups(["/fake/express.eval", "/fake/decision.eval"]) + + assert len(rows) == 2 + row_map = {r["strategy"]: r for r in rows} + + express_row = row_map["express"] + assert express_row["version"] == "1.0" + assert express_row["decision_backend"] is None + assert express_row["total_samples"] == 2 + assert express_row["algorithmic_pass_rate"] == 1.0 + assert express_row["judge_pass_rate"] == 1.0 + assert express_row["median_input_tokens"] == 500.0 + assert express_row["median_output_tokens"] == 100.0 + assert express_row["median_duration_seconds"] == 1.2 + assert express_row["cached"] is False + + decision_row = row_map["decision"] + assert decision_row["version"] == "1.0" + assert decision_row["decision_backend"] == "mock" + assert decision_row["total_samples"] == 2 + assert decision_row["median_input_tokens"] == 250.0 + assert decision_row["median_output_tokens"] == 30.0 + assert decision_row["median_duration_seconds"] == 0.5 + assert decision_row["median_decision_latency_ms"] == 30.0 + + +def test_cached_row_omits_tokens_and_duration() -> None: + cached_log = _synthetic_log( + "decision", + "1.0", + decision_backend="jev", + samples_count=2, + input_tokens=[0, 0], + output_tokens=[0, 0], + durations=[0.01, 0.01], + decision_latencies=[15.0, 15.0], + ) + with patch("compare_strategies.load_log_data", return_value=cached_log): + rows = summarize_log_groups(["/fake/cached.eval"]) + + assert len(rows) == 1 + row = rows[0] + assert row["cached"] is True + assert row["median_input_tokens"] is None + assert row["median_output_tokens"] is None + assert row["median_duration_seconds"] is None + assert row["median_decision_latency_ms"] == 15.0 + + table = render_markdown_table(rows) + assert "`decision`" in table + assert "`jev`" in table + assert "yes" in table + + +def test_compare_strategies_cli_json_export(tmp_path: Path) -> None: + log_data = _synthetic_log("decision", "1.0", decision_backend="mock") + out_json = str(tmp_path / "out.json") + + with patch( + "compare_strategies.find_eval_logs", return_value=["/fake/decision.eval"] + ), patch("compare_strategies.load_log_data", return_value=log_data): + exit_code = main(["/fake/decision.eval", "--json", out_json]) + + assert exit_code == 0 + assert Path(out_json).exists() + with open(out_json, "r", encoding="utf-8") as f: + loaded = json.load(f) + assert len(loaded) == 1 + assert loaded[0]["strategy"] == "decision" + assert loaded[0]["decision_backend"] == "mock" diff --git a/eval/tests/test_dataset.py b/eval/tests/test_dataset.py index 1171555501..73efa1e595 100644 --- a/eval/tests/test_dataset.py +++ b/eval/tests/test_dataset.py @@ -423,3 +423,24 @@ def test_stage2_assertions_from_mapping() -> None: assert parsed.catalog_ids == ("basic",) assert parsed.required_bindings == () assert not parsed.is_empty + + +def test_decision_v1_0_dataset_is_default_for_decision_and_opt_in_for_others() -> None: + decision_default = load_a2ui_dataset(version="1.0", format_name="decision") + express_default = load_a2ui_dataset(version="1.0", format_name="express") + express_explicit = load_a2ui_dataset( + dataset="decision_v1_0", version="1.0", format_name="express" + ) + + assert len(decision_default) == 16 + assert all( + sample.metadata["dataset"] == "decision_v1_0" + for sample in decision_default + if sample.metadata + ) + assert all( + sample.metadata["dataset"] != "decision_v1_0" + for sample in express_default + if sample.metadata + ) + assert len(express_explicit) == 16 diff --git a/eval/tests/test_decision_bench.py b/eval/tests/test_decision_bench.py new file mode 100644 index 0000000000..654f3e9eae --- /dev/null +++ b/eval/tests/test_decision_bench.py @@ -0,0 +1,172 @@ +# 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. + +"""Unit tests for the decision plan golden dataset and benchmark runner.""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +import sys +from unittest.mock import patch + +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../bin"))) + +from a2ui.core.basic_catalog import BasicCatalog +from a2ui.inference_formats.decision import DecisionSynthesizer +from a2ui_eval.decision_bench import ( + brier_score, + expected_calibration_error, + fit_temperature, + load_plan_cases, + run_benchmark, + run_case, +) +from a2ui_eval.shared.utils import GIT_ROOT +import pytest +from seed_decision_plans import seed_cases_from_logs +from tests.decision_fixtures import HOST_ANSWERS, scripted_backend + +CASES_FILE = GIT_ROOT / "eval" / "datasets" / "decision_plans" / "v1.yaml" +SCHEMA_FILE = GIT_ROOT / "eval" / "datasets" / "decision_plans" / "schema.json" + + +def test_schema_and_v1_yaml_validation() -> None: + cases = load_plan_cases(CASES_FILE, schema_path=SCHEMA_FILE) + assert len(cases) == 16 + for case in cases: + assert case.verified is True + assert "smoke" in case.tags + assert len(case.expected_archetypes) > 0 + assert case.expected_family in { + "monitor", + "act", + "input", + "browse", + "inspect", + "follow", + } + + +@pytest.mark.asyncio +async def test_scripted_backend_host_case_scores_perfect() -> None: + cases = load_plan_cases(CASES_FILE) + host_case = next(c for c in cases if c.name == "host_health") + + backend = scripted_backend(HOST_ANSWERS) + synth = DecisionSynthesizer([BasicCatalog("v1.0")], backend) + + score = await run_case(synth, host_case, repeat=1) + assert score.family_accuracy == 1.0 + assert score.archetype_accuracy == 1.0 + assert score.block_recall == 1.0 + assert score.block_precision > 0.0 + assert score.abstain_rate == 0.0 + assert score.action_gate_match is True + + +@pytest.mark.asyncio +async def test_deliberately_wrong_script_scores_zero() -> None: + cases = load_plan_cases(CASES_FILE) + host_case = next(c for c in cases if c.name == "host_health") + + wrong_answers = dict(HOST_ANSWERS) + wrong_answers["family"] = ("input", 0.99) + backend = scripted_backend(wrong_answers) + synth = DecisionSynthesizer([BasicCatalog("v1.0")], backend) + + score = await run_case(synth, host_case, repeat=1) + assert score.family_accuracy == 0.0 + + +def test_brier_and_ece_computation() -> None: + # 1. Completely confident and wrong: p=1.0, y=0.0 + wrong_pairs = [(1.0, 0.0), (1.0, 0.0)] + assert brier_score(wrong_pairs) == 1.0 + assert expected_calibration_error(wrong_pairs, num_bins=10) == 1.0 + + # 2. Perfect calibration in single bin: 50% yes, 50% no with p=0.5 + calibrated_pairs = [(0.5, 1.0), (0.5, 0.0)] + # Brier: ((0.5 - 1.0)^2 + (0.5 - 0.0)^2) / 2 = (0.25 + 0.25) / 2 = 0.25 + assert brier_score(calibrated_pairs) == 0.25 + # Bin [0.5, 0.6) has avg_conf=0.5, avg_acc=0.5 -> diff=0.0 + assert expected_calibration_error(calibrated_pairs, num_bins=10) == 0.0 + + # 3. Hand-computed test with two points: + # Point 1: p=0.1, y=0.0 -> falls into bin 0 [0.0, 0.1) -> conf=0.1, acc=0.0 -> error=0.1 + # Point 2: p=0.9, y=1.0 -> falls into bin 9 [0.9, 1.0] -> conf=0.9, acc=1.0 -> error=0.1 + # Total ECE = 0.5 * 0.1 + 0.5 * 0.1 = 0.1 + pairs = [(0.1, 0.0), (0.9, 1.0)] + assert pytest.approx(brier_score(pairs)) == (0.01 + 0.01) / 2 + assert pytest.approx(expected_calibration_error(pairs, num_bins=10)) == 0.1 + + +def test_fit_temperature_returns_1_for_calibrated_inputs() -> None: + # Perfectly calibrated inputs: 80% confidence with 80% accuracy + calibrated_data = [(0.8, 1.0)] * 8 + [(0.8, 0.0)] * 2 + t = fit_temperature(calibrated_data) + assert t == 1.0 + + +def test_seed_script_creates_unverified_stubs_skipped_by_default( + tmp_path: Path, +) -> None: + fake_log = { + "samples": [{ + "id": "sample_123", + "input": "Show server stats", + "metadata": { + "decision_block": json.dumps({ + "intent": "Show server stats", + "payload": {"server": "web-1", "load": 0.42}, + "mutable_paths": [], + }), + "decision_archetype": "dashboard", + "decision_stage": "monitor", + "decision_blocks": ["headline_row", "facts_card"], + }, + }] + } + + # Target file strictly under eval/datasets/decision_plans/ + target_seeded = ( + GIT_ROOT / "eval" / "datasets" / "decision_plans" / "test_tmp_seeded.yaml" + ) + if target_seeded.is_file(): + target_seeded.unlink() + + fake_log_file = tmp_path / "test.eval" + fake_log_file.write_text("{}", encoding="utf-8") + + try: + with patch("seed_decision_plans.load_log_data", return_value=fake_log): + added = seed_cases_from_logs([fake_log_file], target_seeded) + assert added == 1 + + # Check default loader ignores unverified + loaded_default = load_plan_cases(target_seeded, include_unverified=False) + assert len(loaded_default) == 0 + + # Check loader with include_unverified=True includes it + loaded_all = load_plan_cases(target_seeded, include_unverified=True) + assert len(loaded_all) == 1 + assert loaded_all[0].name == "sample_123_dashboard" + assert loaded_all[0].verified is False + assert loaded_all[0].expected_family == "monitor" + assert loaded_all[0].expected_archetypes == ["dashboard"] + assert loaded_all[0].required_blocks == ["headline_row", "facts_card"] + finally: + if target_seeded.is_file(): + target_seeded.unlink() diff --git a/eval/tests/test_decision_fixtures.py b/eval/tests/test_decision_fixtures.py new file mode 100644 index 0000000000..9b57cc2938 --- /dev/null +++ b/eval/tests/test_decision_fixtures.py @@ -0,0 +1,112 @@ +# 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. + +"""Unit tests for decision_common utilities and decision_fixtures.""" + +from __future__ import annotations + +import pytest + +from a2ui.inference_formats.decision import ( + DecisionBlock, + DeterministicMockBackend, + JevHttpBackend, + LocalCrossEncoderBackend, + SynthesisOutput, + SynthesisStage, +) +from a2ui_eval.decision_common import ( + DECISION_BACKEND_NAMES, + DECISION_METADATA_KEYS, + build_decision_backend, + decision_metadata, +) +from tests.decision_fixtures import ( + HOST_ANSWERS, + HOST_BLOCK, + HOST_DECISION_BLOCK, + SETTINGS_ANSWERS, + SETTINGS_BLOCK, + SETTINGS_DECISION_BLOCK, + TRANSFER_ANSWERS, + TRANSFER_BLOCK, + TRANSFER_DECISION_BLOCK, + scripted_backend, +) + + +def test_build_decision_backend_known_names( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Verifies build_decision_backend returns the expected backend instance.""" + monkeypatch.setenv("JEV_API_KEY", "test-jev-key") + assert isinstance(build_decision_backend("mock"), DeterministicMockBackend) + assert isinstance(build_decision_backend("local"), LocalCrossEncoderBackend) + assert isinstance(build_decision_backend("jev"), JevHttpBackend) + + +def test_build_decision_backend_unknown_name() -> None: + """Verifies build_decision_backend raises ValueError on unknown backend names.""" + with pytest.raises(ValueError, match="Unknown decision backend: invalid"): + build_decision_backend("invalid") + + +def test_decision_metadata_aggregation() -> None: + """Verifies decision_metadata aggregates metrics correctly.""" + out1 = SynthesisOutput( + stage=SynthesisStage.ARCHETYPE, + messages=[], + confidence=0.85, + entropy=0.15, + component_tree_spec={"archetype": "dashboard"}, + decision_latency_ms=12.5, + decision_calls=1, + ) + out2 = SynthesisOutput( + stage=SynthesisStage.ARCHETYPE, + messages=[], + confidence=0.92, + entropy=0.08, + component_tree_spec={"archetype": "form"}, + decision_latency_ms=25.0, + decision_calls=2, + ) + meta = decision_metadata([out1, out2], backend_name="mock") + assert meta["decision_backend"] == "mock" + assert meta["decision_latency_ms"] == 37.5 + assert meta["decision_calls"] == 3 + assert meta["decision_confidence"] == 0.85 + assert meta["decision_archetype"] == "dashboard" + assert meta["decision_answers"] == 0 + assert meta["decision_fallback_source"] is None + for key in DECISION_METADATA_KEYS: + assert key in meta + + +def test_decision_fixtures_integrity() -> None: + """Verifies the standard decision block fixtures and canned answer dicts.""" + assert isinstance(HOST_DECISION_BLOCK, DecisionBlock) + assert isinstance(TRANSFER_DECISION_BLOCK, DecisionBlock) + assert isinstance(SETTINGS_DECISION_BLOCK, DecisionBlock) + + assert "intent" in HOST_BLOCK + assert "intent" in TRANSFER_BLOCK + assert "intent" in SETTINGS_BLOCK + + assert HOST_ANSWERS["family"] == ("monitor", 0.90) + assert TRANSFER_ANSWERS["family"] == ("act", 0.85) + assert SETTINGS_ANSWERS["family"] == ("input", 0.80) + + backend = scripted_backend(HOST_ANSWERS) + assert isinstance(backend, DeterministicMockBackend) diff --git a/eval/tests/test_decision_strategy.py b/eval/tests/test_decision_strategy.py new file mode 100644 index 0000000000..d708e18933 --- /dev/null +++ b/eval/tests/test_decision_strategy.py @@ -0,0 +1,203 @@ +# 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. + +"""Unit tests for the decision inference evaluation strategy.""" + +from __future__ import annotations + +import os +from typing import Any +from unittest.mock import patch + +from inspect_ai.model import ( + ChatCompletionChoice, + ChatMessageAssistant, + ModelName, + ModelOutput, +) +from inspect_ai.solver import Generate, TaskState +import pytest +from tests.decision_fixtures import ( + HOST_ANSWERS, + HOST_BLOCK, + scripted_backend, +) + +from a2ui_eval.decision_common import ( + DECISION_METADATA_KEYS, + build_decision_backend, +) +from a2ui_eval.strategies.decision import ( + compile_decision_payload, + decision_solver, + decision_system_prompt, +) + + +def _make_state( + metadata: dict[str, Any], + completion: str | None = None, + messages: list[Any] | None = None, +) -> TaskState: + output = ( + ModelOutput( + model="mock/model", + choices=[ + ChatCompletionChoice(message=ChatMessageAssistant(content=completion)) + ], + ) + if completion is not None + else None + ) + return TaskState( + model=ModelName("mock/model"), + sample_id=1, + epoch=1, + input="test", + messages=messages or [], + metadata=metadata, + output=output, + ) + + +async def _dummy_generate(state: TaskState, *args: Any, **kwargs: Any) -> TaskState: + return state + + +@pytest.mark.asyncio +async def test_decision_system_prompt_injection() -> None: + state = _make_state( + metadata={ + "catalog": "catalogs/basic/v1/catalog.json", + "protocol_role": "You are a UI generator.", + } + ) + step = decision_system_prompt("1.0") + state = await step(state, _dummy_generate) + assert len(state.messages) == 1 + system_content = str(state.messages[0].content) + assert "You are a UI generator." in system_content + assert "" in system_content + + +@pytest.mark.asyncio +async def test_decision_solver_scripted_success() -> None: + backend = scripted_backend(HOST_ANSWERS) + valid_completion = f"\n{HOST_BLOCK}\n" + state = _make_state( + metadata={ + "catalog": "catalogs/basic/v1/catalog.json", + "allowed_surface_ids": ["main"], + }, + completion=valid_completion, + ) + + with patch( + "a2ui_eval.strategies.decision.build_decision_backend", + return_value=backend, + ): + step = compile_decision_payload("1.0", decision_backend="mock") + state = await step(state, _dummy_generate) + + assert state.metadata.get("pass_at_1") is True + assert state.metadata.get("pass_at_k") is True + assert state.metadata.get("compiled_messages") is not None + assert len(state.metadata["compiled_messages"]) > 0 + assert state.output is not None + assert "" in state.output.completion + + # Metadata keys + for key in DECISION_METADATA_KEYS: + assert key in state.metadata, f"Missing decision metadata key: {key}" + assert state.metadata["decision_archetype"] == "dashboard" + assert state.metadata["decision_backend"] == "mock" + assert state.metadata["decision_calls"] > 0 + assert state.metadata["decision_latency_ms"] >= 0.0 + + +@pytest.mark.asyncio +async def test_decision_solver_unscripted_abstain_fails() -> None: + # Deliberately unparseable / abstaining block with no fallback + invalid_completion = ( + '\n{"intent": "Unknown intent", "payload": {}}\n' + ) + state = _make_state( + metadata={ + "catalog": "catalogs/basic/v1/catalog.json", + "allowed_surface_ids": ["main"], + }, + completion=invalid_completion, + ) + + step = compile_decision_payload("1.0", decision_backend="mock") + state = await step(state, _dummy_generate) + + assert state.metadata.get("pass_at_1") is False + assert state.output is not None + assert ( + state.output.completion.startswith("Compilation/validation failed:") + or "abstained" in state.output.completion.lower() + ) + + +@pytest.mark.asyncio +async def test_decision_solver_validation_retries() -> None: + backend = scripted_backend(HOST_ANSWERS) + call_count = 0 + + async def retry_generate(st: TaskState, *args: Any, **kwargs: Any) -> TaskState: + nonlocal call_count + call_count += 1 + st.output = ModelOutput( + model="mock/model", + choices=[ + ChatCompletionChoice( + message=ChatMessageAssistant( + content=f"\n{HOST_BLOCK}\n" + ) + ) + ], + ) + return st + + # Initially starts with invalid JSON + state = _make_state( + metadata={ + "catalog": "catalogs/basic/v1/catalog.json", + "allowed_surface_ids": ["main"], + }, + completion="\n{not valid json\n", + ) + + with patch( + "a2ui_eval.strategies.decision.build_decision_backend", + return_value=backend, + ): + step = compile_decision_payload( + "1.0", decision_backend="mock", max_validation_retries=1 + ) + state = await step(state, retry_generate) + + assert call_count == 1 + assert state.metadata.get("pass_at_1") is False + assert state.metadata.get("pass_at_k") is True + assert state.metadata.get("validation_retries_used") == 1 + assert state.metadata.get("compiled_messages") is not None + assert any("Validation failed:" in str(m.content) for m in state.messages) + + +def test_build_decision_backend_jev_missing_key() -> None: + with patch.dict(os.environ, {}, clear=True): + with pytest.raises(ValueError, match="JEV_API_KEY"): + build_decision_backend("jev") diff --git a/eval/tests/test_main.py b/eval/tests/test_main.py index 4c8de65fb5..1f80f6d60f 100644 --- a/eval/tests/test_main.py +++ b/eval/tests/test_main.py @@ -386,3 +386,21 @@ def test_main_tags_flag_takes_precedence_over_tier() -> None: "smoke", ]) assert _task_kwargs(mock_v1_eval)[0]["tags"] == "smoke,stateful" + + +def test_main_decision_backend_and_cache_generations() -> None: + from main import parse_strategies + + assert parse_strategies(["decision"]) == ["decision"] + + _, mock_v1_eval, _ = _run_main([ + "--strategies", + "decision", + "--decision-backend", + "jev", + "--cache-generations", + ]) + task_kwargs = _task_kwargs(mock_v1_eval)[0] + assert task_kwargs["strategy"] == "decision" + assert task_kwargs["decision_backend"] == "jev" + assert task_kwargs["cache_generations"] is True diff --git a/pyproject.toml b/pyproject.toml index 9bdf090796..84750cdb9f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -32,6 +32,7 @@ members = [ "eval", "samples/agent/adk/custom-components-example", "samples/agent/adk/restaurant_finder", + "samples/agent/adk/format_playground", "samples/community/agent/adk/gemini_enterprise/agent_engine", "samples/community/agent/adk/gemini_enterprise/cloud_run", "samples/community/agent/adk/mcp-apps-in-a2ui-sample", @@ -74,6 +75,7 @@ testpaths = [ "python/a2ui_core/tests", "eval/tests", "samples/agent/adk/tests", + "samples/agent/adk/format_playground/tests", "samples/community/agent/adk/personalized_learning/tests", "samples/community/mcp/a2ui-over-mcp-recipe/tests", ] diff --git a/python/a2ui_agent/CHANGELOG.md b/python/a2ui_agent/CHANGELOG.md index 83ffaedc1d..770e7e8689 100644 --- a/python/a2ui_agent/CHANGELOG.md +++ b/python/a2ui_agent/CHANGELOG.md @@ -62,6 +62,78 @@ - **BREAKING**: `A2uiGenerator` and `A2uiRequestProcessor` now default to `ExpressFormatFactory` (`ExpressFormat`) instead of `DirectJsonFormatFactory` (`DirectJsonFormat`). +- Add the decision inference format, `a2ui.inference_formats.decision`, in + which the model emits an intent and data and a local decision model picks + and binds the components. + - `DecisionFormat` and `DecisionFormatFactory` implement `InferenceFormat` + and `InferenceFormatFactory`, so + `A2uiRequestProcessor(catalogs, format_factory=DecisionFormatFactory())` + works like the Express and Direct JSON factories. `DecisionPromptGenerator` + asks for `` decision blocks and `DecisionParser` renders them through + `DecisionSynthesizer`. + - `DecisionRenderTool` supplies a JSON Schema tool declaration and + `run_async` / `run_sync` runners for MCP, ADK, and function-calling agents; + build one with `DecisionRenderTool.create(catalogs, ...)`. + - `DecisionSynthesizer` takes an optional `backend` (defaulting to + `create_decision_backend()`) or a prebuilt `CatalogDecisionGraph`, accepts + JSON-string and array payloads, renders a named `template_id` directly, + adds `synthesize_sync()`, and fills abstentions from `fallback_dsl`, + `fallback_fn`, or a deterministic `fallback_card`; + `SynthesisOutput.fallback_source` (a `FallbackSource` enum) names which + one applied. `DecisionFormatFactory` shares one backend across every + format it creates. + - `DecisionTask`, `DecisionWireFormat` (including `AUTO`), and + `DecisionBackendType` (where `ONNX` is an alias of `LOCAL`) string enums + replace raw string literals; `coerce_decision_payload` decodes + stringified payloads. + - Concrete backends, the `DecisionBackend` protocol, and + `DecisionFormatFactory` support `async with` and `aclose()`; the HTTP + backends own one client per active event loop and `JevHttpBackend` caches + ADC tokens per instance. + - `TemplateRegistry.promote_synthesized` reads v0.9 and v1.0 `createSurface` + and `updateComponents` envelopes (including v1.0 embedded components) and + normalizes v0.8 `surfaceUpdate` promotions to v0.9 wire envelopes. + - `LayoutPlanner`, `ArchetypeGrammar`, `PatternLibrary`, `MergedPatternLibrary`, + and `PatternExpander` plan and expand multi-block layout archetypes (`feed`, + `compare`, `dashboard`, `detail`, `result`, `confirm`, `checkout`, `form`, + `settings`, `guide`, `article`, `timeline`, `location`, `chat`) across 19 + semantic blocks in a single batched `DecisionBackend.answer(batch)` call + before falling back to the flat leaf/container path (`SynthesisStage.ARCHETYPE`, + `SynthesisConfig`: `use_archetypes`, `max_pairs`, `threshold_overrides`). + The grammar's `thresholds` are the single source of truth for planner + thresholds; `SynthesisConfig.threshold_overrides` tunes them by key. + - `SemanticType` and `classify_scalar` classify payload pointers across 36 + semantic types (`PointerSummary.semantic_type` and + `SlotBinding.semantic_type` are typed with the enum); `DecisionQuestion`, + `DecisionAnswer`, `DecisionBatch`, and `QuestionKind` (`choice`, `boolean`, + `score`) support batched multi-question scoring, `PredictOnlyBackend` and + `ensure_batch_backend` adapt single-query backends to `answer()`, and + `BatchingDecisionBackend` coalesces concurrent `predict()` and `answer()` + calls within a configurable time window. + - `DecisionBlock`, `DecisionPromptGenerator`, `DecisionFormatFactory`, and + `DecisionRenderTool` accept an optional `layout` brief + (`["role:key,key", ...]`), validated against the synthesizer's + `ArchetypeGrammar` (`decision_rules(grammar)` renders the prompt contract + for a grammar), and expose `SynthesisOutput.layout_plan` and + `SynthesisOutput.trace` (`include_trace=True`). `PlanReason`, + `Requirement`, `LintCode`, and `LintSeverity` are string enums; + `PatternRef` and `ResolvedPattern` replace `name:variant` string splitting. + - `LocalCrossEncoderBackend` optimizes CPU performance by defaulting + `intra_op_num_threads` to the core count (`A2UI_DECISION_LOCAL_THREADS`), + truncating candidate passages to 128 tokens (`A2UI_DECISION_MAX_SEQ_LENGTH`), + and sorting candidate pairs by length before padding and batching + (`A2UI_DECISION_SORT_BY_LENGTH`). + - `DecisionBackend` supports temperature scaling on raw logits before computing + softmax probabilities (`A2UI_DECISION_TEMPERATURE` or `temperature` parameter). + - `DecisionBlock`, `DecisionSynthesizer`, and `ArchetypeGrammar` support authored + copy fields (`title`, `summary`), layout variety sampling (`VarietyMode.NEAR_TOP`, + `SynthesisConfig.variety`, `variety_margin`), and zero-backend-call re-sampling + (`DecisionSynthesizer.remix` / `remix_sync`). + - Add the `decision` evaluation strategy (`eval/a2ui_eval/strategies/decision.py`), + strategy comparison CLI (`eval/bin/compare_strategies.py`), and decision model + benchmark harness (`eval/bin/decision_bench.py` and `eval/datasets/decision_plans/v1.yaml`). + - Format playground adds `tool` mode (`--mode tool`, `/mode tool`), `/rate` and + `/ratings` commands with JSONL persistence, and `/remix` zero-model-call re-planning. - Express variable and check identifiers now follow Unicode UAX 31 in the grammar and decompiler ([#3390](https://github.com/a2ui-project/a2ui/issues/3390)). From protocol v1.0 onward, `ExpressDecompiler` rejects component IDs that are @@ -169,6 +241,7 @@ that declare none, and a function call given to a property with a static type. Elemental output whose top-level element has no `id="root"` is rejected, as its prompt requires. +>>>>>>> upstream/main ## 0.9.0 (2026-10-17) diff --git a/python/a2ui_agent/README.md b/python/a2ui_agent/README.md index 25a3a01e9a..f3bfa8dd4d 100644 --- a/python/a2ui_agent/README.md +++ b/python/a2ui_agent/README.md @@ -68,7 +68,7 @@ The following directories contain the base protocol logic, parsing, and schema o - **`prompt/generator.py`**: Defines the `PromptGenerator` (`A2uiPromptGenerator`) abstract base class (`generate_base_rules`, `generate_catalog_instructions`, `generate_examples`, `generate`). - **`inference_format.py`**: Defines `InferenceFormat` and `InferenceFormatFactory`. -- **`inference_formats/`**: Format implementations and factories for Direct JSON (`direct_json/`), Express (`express/`), and experimental Elemental and Atom (`experimental/`) formats. Direct JSON is the format that streams: the stream from `DirectJsonParser.open_stream` heals the partial JSON of each chunk (`direct_json/json_reader.py`) and emits the messages that are ready. +- **`inference_formats/`**: Format implementations and factories for Direct JSON (`direct_json/`), Express (`express/`), Decision (`decision/`), and experimental Elemental and Atom (`experimental/`) formats. Direct JSON is the format that streams: the stream from `DirectJsonParser.open_stream` heals the partial JSON of each chunk (`direct_json/json_reader.py`) and emits the messages that are ready. ## Agent framework integrations diff --git a/python/a2ui_agent/pyproject.toml b/python/a2ui_agent/pyproject.toml index b4daa13d7b..548afbb121 100644 --- a/python/a2ui_agent/pyproject.toml +++ b/python/a2ui_agent/pyproject.toml @@ -30,6 +30,14 @@ dependencies = [ "pyyaml>=6.0" ] +[project.optional-dependencies] +decision-local = [ + "huggingface-hub>=0.25.0", + "numpy>=1.26.0", + "onnxruntime>=1.19.0", + "tokenizers>=0.20.0", +] + [project.urls] Homepage = "https://a2ui.org/" Repository = "https://github.com/a2ui-project/a2ui/tree/main/python/a2ui_agent" diff --git a/python/a2ui_agent/scripts/sync_decision_assets.py b/python/a2ui_agent/scripts/sync_decision_assets.py new file mode 100644 index 0000000000..70ae1e8a67 --- /dev/null +++ b/python/a2ui_agent/scripts/sync_decision_assets.py @@ -0,0 +1,124 @@ +# 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. + +"""Copies the decision layout grammar and catalog patterns into the package. + +The canonical files live in the repository's ``catalogs/`` directory. An +installed wheel cannot read the repository, so the decision format loads +vendored copies from ``src/a2ui/inference_formats/decision/assets/``. After +changing a canonical file, run this from ``python/a2ui_agent`` and commit the +result:: + + uv run python scripts/sync_decision_assets.py + +With ``--check``, the script compares the vendored copies with the canonical +files instead of writing, prints a unified diff for each difference, and +exits 1 if any differ. ``tests/decision/test_decision_assets.py`` runs the +same comparison. +""" + +import argparse +import difflib +from pathlib import Path +import sys + +_SDK_DIR = Path(__file__).resolve().parents[1] +_REPO_ROOT = _SDK_DIR.parents[1] +_ASSETS_DIR = _SDK_DIR / "src" / "a2ui" / "inference_formats" / "decision" / "assets" + +# Canonical file (relative to the repository root) to vendored copy (relative +# to the assets directory). +ASSET_SOURCES: dict[str, str] = { + "catalogs/decision/v1/archetypes.json": "archetypes.json", + "catalogs/decision/v1/archetype_definition.json": "archetype_definition.json", + "catalogs/decision/v1/pattern_definition.json": "pattern_definition.json", + "catalogs/basic/v1/patterns.json": "patterns/basic_v1_0.json", +} + +_SYNC_COMMAND = "uv run python scripts/sync_decision_assets.py" +_MAX_DIFF_LINES = 40 + + +def _diff(canonical: Path, vendored: Path) -> list[str]: + """Returns unified diff lines between `vendored` and `canonical` (empty if same).""" + expected = canonical.read_text(encoding="utf-8") + actual = vendored.read_text(encoding="utf-8") if vendored.is_file() else "" + if expected == actual: + return [] + return list( + difflib.unified_diff( + actual.splitlines(keepends=True), + expected.splitlines(keepends=True), + fromfile=str(vendored), + tofile=str(canonical), + ) + ) + + +def check(repo_root: Path, assets_dir: Path) -> int: + """Reports vendored assets that differ from their canonical files.""" + stale = 0 + for source, target in ASSET_SOURCES.items(): + diff = _diff(repo_root / source, assets_dir / target) + if not diff: + continue + stale += 1 + print(f"{target} is out of date with {source}:", file=sys.stderr) + for line in diff[:_MAX_DIFF_LINES]: + sys.stderr.write(line if line.endswith("\n") else line + "\n") + if len(diff) > _MAX_DIFF_LINES: + print(f" ... ({len(diff) - _MAX_DIFF_LINES} more lines)", file=sys.stderr) + if stale: + print( + f"{stale} vendored asset(s) out of date. Run `{_SYNC_COMMAND}` from" + " python/a2ui_agent and commit the result.", + file=sys.stderr, + ) + return 1 + print("Decision assets are in sync.") + return 0 + + +def sync(repo_root: Path, assets_dir: Path) -> int: + """Copies every canonical file over its vendored copy.""" + for source, target in ASSET_SOURCES.items(): + destination = assets_dir / target + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes((repo_root / source).read_bytes()) + print(f"{source} -> {destination.relative_to(_SDK_DIR)}") + return 0 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument( + "--check", + action="store_true", + help="compare instead of writing; exit 1 if any vendored asset differs", + ) + args = parser.parse_args(argv) + missing = [s for s in ASSET_SOURCES if not (_REPO_ROOT / s).is_file()] + if missing: + print( + f"Canonical file(s) not found under {_REPO_ROOT}: {missing}", + file=sys.stderr, + ) + return 2 + if args.check: + return check(_REPO_ROOT, _ASSETS_DIR) + return sync(_REPO_ROOT, _ASSETS_DIR) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/python/a2ui_agent/src/a2ui/inference_formats/README.md b/python/a2ui_agent/src/a2ui/inference_formats/README.md index 1e2a49e66a..c6f0092b17 100644 --- a/python/a2ui_agent/src/a2ui/inference_formats/README.md +++ b/python/a2ui_agent/src/a2ui/inference_formats/README.md @@ -1,23 +1,100 @@ # A2UI Inference Formats -This directory contains inference format implementations (`direct_json`, `express`, `elemental`, `atom`) for the A2UI Python SDK. +This directory contains inference format implementations (`direct_json`, `express`, `elemental`, `atom`, `decision`) for the A2UI Python SDK. -## Design Philosophy +## Overview -An **Inference Format** defines how an LLM or agent emits UI definitions (e.g. Direct JSON, Express DSL, Elemental HTML, or Atom). +An inference format defines how an agent emits UI definitions. A2UI supports both generative routes where a language model writes DSL or JSON code, and a decision-model synthesis route that compiles structured data into valid UI surfaces using a trained classifier or cross-encoder. -### Catalog-Agnostic Prompt Generation Rules +## The Decision Synthesis Route + +The `decision` route separates data generation from interface design. It supports two primary execution workflows: tool mode and chat mode. + +### 1. Tool Mode (Direct Synthesis) + +Tool mode is the most efficient way to render user interfaces in A2UI. In this flow, an agent calls standard domain tools (such as fetching server telemetry, retrieving catalog items, or getting a transfer quote). Instead of prompting a language model to author UI code from that tool output, the data passes directly to `DecisionRenderTool` or `DecisionSynthesizer.synthesize`. + +```python +from a2ui.inference_formats.decision import DecisionRenderTool + +# Provide the tool to your agent framework (e.g. ADK): +render_tool = DecisionRenderTool(catalogs=catalogs) + +# When an ADK tool produces data, render it directly: +result = render_tool.call( + intent="Show host health status", + payload={"host": "prod-01", "cpu": 0.94, "status": "critical"}, + mutable_paths=["/status"], +) +``` + +Key benefits of tool mode: +- **Zero UI model calls**: The language model only executes its normal function calling step. +- **Fast execution**: Layout planning and expansion complete in 15 to 40 ms on local CPUs. +- **Guaranteed schema validity**: Surfaces expand through validated catalog patterns without syntax errors or broken tags. + +### 2. Chat Mode (Two-Stage Synthesis) + +In open-ended conversation where no domain tool exists, the agent operates in two stages: +1. **Stage 1**: The language model converts the user's conversational request into a structured `DecisionBlock` containing `intent`, `payload`, and optional copy fields (`title`, `summary`) or layout hints (`layout: ["role:key,key", ...]`). +2. **Stage 2**: The decision model scores layout families and archetypes, assigns payload pointers, and expands catalog components without making a second language model call. + +```python +from a2ui.inference_formats.decision import DecisionBlock, DecisionSynthesizer + +block = DecisionBlock( + intent="Show stock portfolio overview", + payload={"portfolio": "Growth", "totalValue": 128450.0}, + title="Portfolio Summary", + summary="Daily portfolio valuation and holdings.", +) +output = await synthesizer.synthesize( + block.intent, + block.payload, + surface_id="turn-1", + title=block.title, + summary=block.summary, +) +``` + +### 3. Variety and Zero-Cost Remix + +The archetype grammar supports exploration and layout variation: +- **Variety Mode (`VarietyMode.NEAR_TOP`)**: Configured via `SynthesisConfig(variety=VarietyMode.NEAR_TOP, variety_margin=0.15)`. Options within the probability margin of the top candidate are sampled with a random seed rather than strictly choosing the argmax. +- **Zero-Cost Remix**: Call `synthesizer.remix(intent, payload, answers, seed=42)` using the recorded `output.decision_answers`. This re-samples layout choices instantly with zero model calls and zero decision backend queries. + +## Backend Configuration + +The decision model backend is selected through `A2UI_DECISION_BACKEND` or configured directly in code: + +| Backend | Setup | Characteristics | +| :--- | :--- | :--- | +| `local` | Requires extra `a2ui-agent-sdk[decision-local]` | In-process ONNX cross-encoder running on CPU. | +| `jev` | Set `JEV_API_KEY` (or `A2UI_DECISION_AUTH`) | Remote TypeSafe Jev model over HTTP. | +| `mock` | Default offline fallback | Deterministic keyword-based heuristic for tests. | + +### Environment Variables + +- `A2UI_DECISION_BACKEND`: `local`, `jev`, `gev`, or `mock`. +- `A2UI_DECISION_LOCAL_THREADS`: Intra-operation CPU thread count for local ONNX execution (defaults to all available CPU cores). +- `A2UI_DECISION_MAX_SEQ_LENGTH`: Maximum token sequence length for passage pairs (defaults to 128 tokens). +- `A2UI_DECISION_SORT_BY_LENGTH`: Sort candidate pairs by length before inference to minimize padding waste (defaults to `true`). +- `A2UI_DECISION_TEMPERATURE`: Temperature scaling parameter applied to logits before computing softmax probabilities (defaults to 1.0). +- `A2UI_DECISION_URL`: Endpoint URL for remote HTTP backends. +- `A2UI_DECISION_AUTH` / `JEV_API_KEY`: Authentication token for remote backends. + +## Catalog-Agnostic Prompt Generation Rules To ensure long-term maintainability, portability, and catalog independence: 1. **Single Source of Truth**: - All component signatures, parameter descriptions, function helpers, and property constraints MUST be derived dynamically from the `Catalog` JSON schema via schema helpers (`CatalogSchemaHelper`). + All component signatures, parameter descriptions, function helpers, and property constraints are derived dynamically from the `Catalog` JSON schema via schema helpers (`CatalogSchemaHelper`). 2. **No Hardcoded Catalog String Hacks**: - Prompt generators (`PromptGenerator` implementations) MUST NOT hardcode catalog-specific string replacements, regular expression filters, or custom text manipulations to modify component or property descriptions at runtime. + Prompt generators (`PromptGenerator` implementations) do not hardcode catalog-specific string replacements, regular expression filters, or custom text manipulations to modify component or property descriptions at runtime. 3. **Schema First**: - If a component parameter description or constraint needs adjustment (such as clarifying inline component usage vs. reference IDs), update the catalog JSON schema file (`specification//catalogs/basic/catalog.json`) directly, rather than patching prompt generator logic. + If a component parameter description or constraint needs adjustment, update the catalog JSON schema file (`specification//catalogs/basic/catalog.json`) directly, rather than patching prompt generator logic. 4. **Independent Grammar Contracts**: - Format-level grammar rules (such as `` sentinel tags or variable assignment syntax in `EXPRESS_RULES`) define the output syntax structure and MUST NOT contradict property guidelines defined in the catalog JSON schema. + Format-level grammar rules define the output syntax structure and do not contradict property guidelines defined in the catalog JSON schema. diff --git a/python/a2ui_agent/src/a2ui/inference_formats/__init__.py b/python/a2ui_agent/src/a2ui/inference_formats/__init__.py index 3a3d1122dd..af9c887b83 100644 --- a/python/a2ui_agent/src/a2ui/inference_formats/__init__.py +++ b/python/a2ui_agent/src/a2ui/inference_formats/__init__.py @@ -14,10 +14,24 @@ from __future__ import annotations +from . import decision as decision from . import direct_json as direct_json from . import express as express from ._shared import to_message_dicts from ._shared import to_message_models +from .decision import CatalogDecisionGraph +from .decision import DecisionBackend +from .decision import DecisionFormat +from .decision import DecisionFormatFactory +from .decision import DecisionParser +from .decision import DecisionPromptGenerator +from .decision import DecisionRenderTool +from .decision import DecisionSynthesizer +from .decision import SynthesisConfig +from .decision import SynthesisOutput +from .decision import SynthesisStage +from .decision import TemplateRegistry +from .decision import calibrate_thresholds from .direct_json import DirectJsonDecompiler from .direct_json import DirectJsonFormat from .direct_json import DirectJsonFormatFactory @@ -41,6 +55,14 @@ "AtomFormatFactory", "AtomParser", "AtomPromptGenerator", + "CatalogDecisionGraph", + "DecisionBackend", + "DecisionFormat", + "DecisionFormatFactory", + "DecisionParser", + "DecisionPromptGenerator", + "DecisionRenderTool", + "DecisionSynthesizer", "DirectJsonDecompiler", "DirectJsonFormat", "DirectJsonFormatFactory", @@ -54,6 +76,12 @@ "ExpressFormatFactory", "ExpressParser", "ExpressPromptGenerator", + "SynthesisConfig", + "SynthesisOutput", + "SynthesisStage", + "TemplateRegistry", + "calibrate_thresholds", + "decision", "direct_json", "express", "to_message_dicts", diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/__init__.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/__init__.py new file mode 100644 index 0000000000..09c4438273 --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/__init__.py @@ -0,0 +1,210 @@ +# 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. + +"""Public facade for catalog-agnostic local decision-model A2UI synthesis.""" + +from __future__ import annotations + +from .archetypes import ( + ArchetypeGrammar, + BlockSpec, + GrammarError, + LayoutArchetype, +) +from .backends import ( + DecisionBackend, + DeterministicMockBackend, + JevHttpBackend, + LocalCrossEncoderBackend, + PredictOnlyBackend, + StepZeroLogprobBackend, + answer_from_distribution, + create_decision_backend, + ensure_batch_backend, +) +from .batching import BatchingDecisionBackend +from .calibration import ( + LabeledDecisionExample, + SynthesizerLike, + calibrate_thresholds, + compute_bayes_optimal_threshold, +) +from .catalog_graph import CatalogDecisionGraph +from .decision_block import DecisionBlock, decision_block_from_messages +from .format import DecisionFormat, DecisionFormatFactory +from .layout_lint import LintCode, LintFinding, LintSeverity, lint_components +from .layout_planner import LayoutPlanner, PlannerState +from .models import ( + BRIEF_ITEM_PATTERN, + MAX_BRIEF_SECTIONS, + AuthoredCopy, + BlockBindings, + BriefSection, + CalibrationPoint, + CalibrationResult, + ComponentNodeSpec, + ComponentSlot, + DecisionAnswer, + DecisionBackendType, + DecisionBatch, + DecisionDistribution, + DecisionQuery, + DecisionQuestion, + DecisionRecord, + DecisionTask, + DecisionWireFormat, + FallbackSource, + LayoutBrief, + LayoutPlan, + PageBindings, + PatternCapabilities, + PlannedBlock, + PlanOutcome, + PlanReason, + QuestionKind, + Requirement, + SemanticType, + SlotBinding, + SlotKind, + SynthesisConfig, + SynthesisOutput, + SynthesisStage, + VarietyMode, + coerce_decision_payload, +) +from .parser import DecisionParser +from .patterns import ( + MergedPatternLibrary, + PatternError, + PatternExpander, + PatternLibrary, + PatternRef, + ResolvedPattern, + eligible_archetypes, + resolve_fallback_pattern, + shape_signature, +) +from .payload_inspector import ( + PointerSummary, + PointerValueType, + inspect_payload_pointers, +) +from .prompt_generator import DecisionPromptGenerator, decision_rules +from .semantic_types import classify_array_field, classify_scalar, humanize_key +from .synthesizer import DecisionSynthesizer, FallbackCallback +from .template_registry import SurfaceTemplate, TemplateRegistry +from .tool import DecisionRenderTool + + +def __getattr__(name: str) -> object: + # `DECISION_RULES` renders the bundled grammar's roles into the prompt + # contract; resolve it lazily so importing the package stays cheap. + if name == "DECISION_RULES": + from . import prompt_generator + + return prompt_generator.DECISION_RULES + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +__all__ = [ + "BRIEF_ITEM_PATTERN", + "DECISION_RULES", + "MAX_BRIEF_SECTIONS", + "ArchetypeGrammar", + "AuthoredCopy", + "BatchingDecisionBackend", + "BlockBindings", + "BlockSpec", + "BriefSection", + "CalibrationPoint", + "CalibrationResult", + "CatalogDecisionGraph", + "ComponentNodeSpec", + "ComponentSlot", + "DecisionAnswer", + "DecisionBackend", + "DecisionBackendType", + "DecisionBatch", + "DecisionBlock", + "DecisionDistribution", + "DecisionFormat", + "DecisionFormatFactory", + "DecisionParser", + "DecisionPromptGenerator", + "DecisionQuery", + "DecisionQuestion", + "DecisionRecord", + "DecisionRenderTool", + "DecisionSynthesizer", + "DecisionTask", + "DecisionWireFormat", + "DeterministicMockBackend", + "FallbackCallback", + "FallbackSource", + "GrammarError", + "JevHttpBackend", + "LabeledDecisionExample", + "LayoutArchetype", + "LayoutBrief", + "LayoutPlan", + "LayoutPlanner", + "LintCode", + "LintFinding", + "LintSeverity", + "LocalCrossEncoderBackend", + "MergedPatternLibrary", + "PageBindings", + "PatternCapabilities", + "PatternError", + "PatternExpander", + "PatternLibrary", + "PatternRef", + "PlanOutcome", + "PlanReason", + "PlannedBlock", + "PlannerState", + "PointerSummary", + "PointerValueType", + "PredictOnlyBackend", + "QuestionKind", + "Requirement", + "ResolvedPattern", + "SemanticType", + "SlotBinding", + "SlotKind", + "StepZeroLogprobBackend", + "SurfaceTemplate", + "SynthesisConfig", + "SynthesisOutput", + "SynthesisStage", + "SynthesizerLike", + "TemplateRegistry", + "VarietyMode", + "answer_from_distribution", + "calibrate_thresholds", + "classify_array_field", + "classify_scalar", + "coerce_decision_payload", + "compute_bayes_optimal_threshold", + "create_decision_backend", + "decision_block_from_messages", + "decision_rules", + "eligible_archetypes", + "ensure_batch_backend", + "humanize_key", + "inspect_payload_pointers", + "lint_components", + "resolve_fallback_pattern", + "shape_signature", +] diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/archetypes.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/archetypes.py new file mode 100644 index 0000000000..78caf16834 --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/archetypes.py @@ -0,0 +1,698 @@ +# 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. + +"""Layout archetype grammar: typed model, JSON loader, and lint. + +The grammar is authored as ``catalogs/decision/v1/archetypes.json`` and +vendored under this package's ``assets/`` directory. `ArchetypeGrammar.from_json` +validates a grammar against the bundled JSON Schema, parses it into frozen +dataclasses, and runs the lint checks the grammar itself lists; any failure +raises `GrammarError`. +""" + +from __future__ import annotations + +from collections.abc import Iterator, Mapping, Sequence +from dataclasses import dataclass, field +import functools +from importlib import resources +import json +import re +import sys +from typing import Any + +from jsonschema import Draft202012Validator + +from a2ui.core import A2uiValidationError + +from .models import QuestionKind, Requirement, validate_threshold_relations + +if sys.version_info >= (3, 11): + from importlib.resources.abc import Traversable +else: # pragma: no cover - Python 3.10 only + from importlib.abc import Traversable + +Range = tuple[int | None, int | None] +"""An inclusive ``(min, max)`` pair where None leaves that end open.""" + +ABSTRACT_PATTERNS: tuple[str, ...] = ( + "page", + "banner", + "picture", + "media", + "filters", + "headline", + "chart", + "facts", + "prose", + "collection", + "comparison", + "steps", + "timeline", + "conversation", + "compose", + "map", + "form", + "groups", + "actions", + "outcome", +) +"""Abstract pattern names a catalog pattern file may implement.""" + +FALLBACK_TERMINALS: tuple[str, ...] = ("prose", "facts") +"""Fallback entries every catalog is expected to draw, so a chain may end on them.""" + +CAPABILITY_FLAGS: tuple[str, ...] = ("actions_allowed",) +"""Planner flags a question's `requires` entry may name.""" + +_ASSETS_PACKAGE = "a2ui.inference_formats.decision" +_PLACEHOLDER_RE = re.compile(r"\{([A-Za-z_][A-Za-z0-9_]*)\}") +_PATTERN_KNOB_RE = re.compile(r"^([a-z_]+):([a-z_]+)$") +_PATTERN_VARIANT_RE = re.compile(r"^pattern:([a-z_]+):([a-z_]+)$") + + +class GrammarError(A2uiValidationError): + """An archetype grammar failed schema validation or lint.""" + + +def asset_path(*parts: str) -> Traversable: + """Returns the bundled asset at ``assets/`` inside this package.""" + path = resources.files(_ASSETS_PACKAGE) / "assets" + for part in parts: + path = path / part + return path + + +def load_asset(*parts: str) -> Any: + """Loads and decodes the bundled JSON asset at ``assets/``.""" + with asset_path(*parts).open("r", encoding="utf-8") as handle: + return json.load(handle) + + +@functools.cache +def _archetype_schema_validator() -> Draft202012Validator: + """The validator for the bundled ``archetype_definition.json``.""" + schema = load_asset("archetype_definition.json") + Draft202012Validator.check_schema(schema) + return Draft202012Validator(schema) + + +def _parse_range(raw: Sequence[Any] | None) -> Range | None: + """Parses a ``[min, max]`` list (either end may be null) into a `Range`.""" + if raw is None: + return None + low, high = raw + return (None if low is None else int(low), None if high is None else int(high)) + + +@dataclass(frozen=True) +class ShapeFilter: + """Deterministic payload pre-filter on an archetype or block. + + All fields are optional; an empty filter matches every payload. + """ + + pointers: tuple[str, ...] = () + """Semantic types of which at least one pointer must exist.""" + array_length: Range | None = None + element_types: tuple[str, ...] = () + element_keys: tuple[str, ...] = () + mutable: bool | None = None + prose_length: tuple[str, ...] = () + count: Range | None = None + """Bounds on how many pointers match `pointers`.""" + actions_allowed: bool | None = None + + @property + def is_empty(self) -> bool: + """Whether the filter places no constraint at all.""" + return self == ShapeFilter() + + @classmethod + def from_json(cls, raw: Mapping[str, Any] | None) -> ShapeFilter: + """Parses the ``shape`` object of an archetype or block.""" + if not raw: + return cls() + return cls( + pointers=tuple(raw.get("pointers", ())), + array_length=_parse_range(raw.get("arrayLength")), + element_types=tuple(raw.get("elementTypes", ())), + element_keys=tuple(raw.get("elementKeys", ())), + mutable=raw.get("mutable"), + prose_length=tuple(raw.get("proseLength", ())), + count=_parse_range(raw.get("count")), + actions_allowed=raw.get("actions_allowed"), + ) + + +@dataclass(frozen=True) +class BlockRef: + """A block named by an archetype, with the requirement its mark encodes.""" + + id: str + requirement: Requirement + + @classmethod + def parse(cls, mark: str) -> BlockRef: + """Parses ``name!`` (required), ``name?`` (optional), or ``name`` (expected).""" + if mark.endswith("!"): + return cls(id=mark[:-1], requirement=Requirement.REQUIRED) + if mark.endswith("?"): + return cls(id=mark[:-1], requirement=Requirement.OPTIONAL) + return cls(id=mark, requirement=Requirement.EXPECTED) + + @property + def mark(self) -> str: + """The ``name!`` / ``name?`` / ``name`` form.""" + suffix = { + Requirement.REQUIRED: "!", + Requirement.OPTIONAL: "?", + Requirement.EXPECTED: "", + }[self.requirement] + return f"{self.id}{suffix}" + + +@dataclass(frozen=True) +class LayoutArchetype: + """An ordered list of blocks that together serve one family of intent.""" + + id: str + family: str + criteria: str + blocks: tuple[BlockRef, ...] + shape: ShapeFilter = field(default_factory=ShapeFilter) + at_least: int = 1 + frame: Mapping[str, Any] = field(default_factory=dict, hash=False) + + def block_ids(self) -> tuple[str, ...]: + """Block ids in render order.""" + return tuple(ref.id for ref in self.blocks) + + def requirement_of(self, block_id: str) -> Requirement | None: + """The requirement of `block_id` in this archetype, or None if absent.""" + for ref in self.blocks: + if ref.id == block_id: + return ref.requirement + return None + + def required_block_ids(self) -> tuple[str, ...]: + """Ids of the blocks marked ``!``.""" + return tuple( + ref.id for ref in self.blocks if ref.requirement is Requirement.REQUIRED + ) + + @classmethod + def from_json(cls, raw: Mapping[str, Any]) -> LayoutArchetype: + """Parses one entry of the grammar's ``archetypes`` list.""" + return cls( + id=raw["id"], + family=raw["family"], + criteria=raw["criteria"], + blocks=tuple(BlockRef.parse(mark) for mark in raw["blocks"]), + shape=ShapeFilter.from_json(raw.get("shape")), + at_least=int(raw.get("atLeast", 1)), + frame=dict(raw.get("frame", {})), + ) + + +@dataclass(frozen=True) +class QuestionSpec: + """A question template from the grammar, before placeholders are filled.""" + + kind: QuestionKind + question: str + options: Mapping[str, str] = field(default_factory=dict, hash=False) + """`CHOICE`: option id to description.""" + levels: tuple[str, ...] = () + """`SCORE`: ordered level descriptions.""" + requires: Mapping[str, tuple[str, ...]] = field(default_factory=dict, hash=False) + """Option id to the slots, knob options, pattern variants, or flags it needs.""" + applies_when: Mapping[str, Any] = field(default_factory=dict, hash=False) + derived_when: Mapping[str, Any] = field(default_factory=dict, hash=False) + options_from: str | None = None + """`CHOICE`: a slot path whose bound values become the options.""" + allow_none: bool = True + yes: str = "" + """`BOOLEAN`: the criteria text for a yes answer.""" + no: str = "" + per_pointer: bool = False + """`SCORE` salience: asked once per candidate pointer.""" + select: Mapping[str, float] = field(default_factory=dict, hash=False) + """Salience selection rule: ``min``, ``max``, ``aboveLevel``.""" + note: str = "" + + def placeholders(self) -> tuple[str, ...]: + """Names inside ``{braces}`` in the question text, in order.""" + return tuple(_PLACEHOLDER_RE.findall(self.question)) + + def option_ids(self) -> tuple[str, ...]: + """Option ids for `CHOICE` questions, level labels for `SCORE`.""" + if self.kind is QuestionKind.SCORE: + return self.levels + return tuple(self.options) + + @classmethod + def from_json(cls, raw: Mapping[str, Any]) -> QuestionSpec: + """Parses a question object of any kind.""" + return cls( + kind=QuestionKind(raw["kind"]), + question=raw["question"], + options=dict(raw.get("options", {})), + levels=tuple(raw.get("levels", ())), + requires={k: tuple(v) for k, v in raw.get("requires", {}).items()}, + applies_when=dict(raw.get("appliesWhen", {})), + derived_when=dict(raw.get("derivedWhen", {})), + options_from=raw.get("optionsFrom"), + allow_none=bool(raw.get("allowNone", True)), + yes=raw.get("yes", ""), + no=raw.get("no", ""), + per_pointer=bool(raw.get("perPointer", False)), + select={k: float(v) for k, v in raw.get("select", {}).items()}, + note=raw.get("note", ""), + ) + + +@dataclass(frozen=True) +class SlotSpec: + """What a block slot accepts and how the deterministic binder fills it.""" + + name: str + from_types: tuple[str, ...] + """Accepted semantic types, most preferred first; ``any`` accepts scalars.""" + required: bool = False + repeat: bool = False + max: int | None = None + prefer: tuple[str, ...] = () + """Key hints that break ties among compatible pointers.""" + avoid_keys: tuple[str, ...] = () + sibling: tuple[str, ...] = () + """Sibling keys of the bound pointer this slot may be filled from.""" + order_by: str | None = None + mutable: bool = False + fields: Mapping[str, SlotSpec] = field(default_factory=dict, hash=False) + """Per-element slots of a repeated slot.""" + element_types: tuple[str, ...] = () + default: Any = None + note: str = "" + + def field_names(self) -> tuple[str, ...]: + """This slot's name followed by every nested field name, depth first.""" + names = [self.name] + for sub in self.fields.values(): + names.extend(sub.field_names()) + return tuple(names) + + @classmethod + def from_json(cls, name: str, raw: Mapping[str, Any]) -> SlotSpec: + """Parses one ``slots`` or ``fields`` entry.""" + return cls( + name=name, + from_types=tuple(raw["from"]), + required=bool(raw.get("required", False)), + repeat=bool(raw.get("repeat", False)), + max=raw.get("max"), + prefer=tuple(raw.get("prefer", ())), + avoid_keys=tuple(raw.get("avoidKeys", ())), + sibling=tuple(raw.get("sibling", ())), + order_by=raw.get("orderBy"), + mutable=bool(raw.get("mutable", False)), + fields=_parse_slots(raw.get("fields", {})), + element_types=tuple(raw.get("elementTypes", ())), + default=raw.get("default"), + note=raw.get("note", ""), + ) + + +def _parse_slots(raw: Mapping[str, Any]) -> dict[str, SlotSpec]: + """Parses a ``slots`` or ``fields`` mapping, preserving order.""" + return {name: SlotSpec.from_json(name, spec) for name, spec in raw.items()} + + +def _parse_questions(raw: Mapping[str, Any]) -> dict[str, QuestionSpec]: + """Parses an ``anatomy``, ``instance``, or ``job`` mapping.""" + return {name: QuestionSpec.from_json(spec) for name, spec in raw.items()} + + +@dataclass(frozen=True) +class MeasureSpec: + """A value computed from a bound slot, never asked, that patterns vary by.""" + + name: str + derived_from: str + """A ``slot.hints.`` path into the bound pointer's summary.""" + levels: Mapping[str, Range] = field(hash=False) + """Level name to its inclusive-exclusive ``[low, high)`` range, in order.""" + note: str = "" + + def level_for(self, value: float) -> str | None: + """The level whose range contains `value`, or None.""" + for name, (low, high) in self.levels.items(): + if (low is None or value >= low) and (high is None or value < high): + return name + return None + + @classmethod + def from_json(cls, name: str, raw: Mapping[str, Any]) -> MeasureSpec: + """Parses one ``measures`` entry.""" + levels: dict[str, Range] = {} + for level, bounds in raw["levels"].items(): + parsed = _parse_range(bounds) + if parsed is not None: + levels[level] = parsed + return cls( + name=name, + derived_from=raw["derivedFrom"], + levels=levels, + note=raw.get("note", ""), + ) + + +@dataclass(frozen=True) +class BlockSpec: + """One block of the grammar: its pattern, questions, slots, and fallbacks.""" + + id: str + pattern: str + shape: ShapeFilter = field(default_factory=ShapeFilter) + gate: QuestionSpec | None = None + salience: QuestionSpec | None = None + anatomy: Mapping[str, QuestionSpec] = field(default_factory=dict, hash=False) + instance: Mapping[str, QuestionSpec] = field(default_factory=dict, hash=False) + measures: Mapping[str, MeasureSpec] = field(default_factory=dict, hash=False) + slots: Mapping[str, SlotSpec] = field(default_factory=dict, hash=False) + fallback: tuple[str, ...] = () + + def slot_names(self) -> tuple[str, ...]: + """Every slot and nested field name a placeholder may refer to.""" + names: list[str] = [] + for slot in self.slots.values(): + names.extend(slot.field_names()) + return tuple(names) + + def questions(self) -> Iterator[tuple[str, QuestionSpec]]: + """Yields ``(label, question)`` for the gate, salience, anatomy, and instance.""" + if self.gate is not None: + yield "gate", self.gate + if self.salience is not None: + yield "salience", self.salience + for name, question in self.anatomy.items(): + yield f"anatomy.{name}", question + for name, question in self.instance.items(): + yield f"instance.{name}", question + + @classmethod + def from_json(cls, raw: Mapping[str, Any]) -> BlockSpec: + """Parses one entry of the grammar's ``blocks`` list.""" + gate = raw.get("gate") + salience = raw.get("salience") + return cls( + id=raw["id"], + pattern=raw["pattern"], + shape=ShapeFilter.from_json(raw.get("shape")), + gate=QuestionSpec.from_json(gate) if gate else None, + salience=QuestionSpec.from_json(salience) if salience else None, + anatomy=_parse_questions(raw.get("anatomy", {})), + instance=_parse_questions(raw.get("instance", {})), + measures={ + name: MeasureSpec.from_json(name, spec) + for name, spec in raw.get("measures", {}).items() + }, + slots=_parse_slots(raw.get("slots", {})), + fallback=tuple(raw["fallback"]), + ) + + +@dataclass(frozen=True) +class Rule: + """A prose rule the planner implements; kept for traces and documentation.""" + + id: str + rule: str + + +def _lint_unique_ids( + archetypes: Sequence[LayoutArchetype], blocks: Sequence[BlockSpec] +) -> list[str]: + """Archetype ids and block ids must each be unique.""" + findings: list[str] = [] + for label, ids in ( + ("archetype", [a.id for a in archetypes]), + ("block", [b.id for b in blocks]), + ): + duplicates = sorted({i for i in ids if ids.count(i) > 1}) + for dup in duplicates: + findings.append(f"Duplicate {label} id {dup!r}.") + return findings + + +def _lint_archetype_anchor(archetypes: Sequence[LayoutArchetype]) -> list[str]: + """Every archetype has at least one required or expected block.""" + return [ + f"Archetype {a.id!r} has no required or expected block." + for a in archetypes + if all(ref.requirement == "optional" for ref in a.blocks) + ] + + +def _lint_block_ids_exist( + archetypes: Sequence[LayoutArchetype], blocks: Mapping[str, BlockSpec] +) -> list[str]: + """Every block id used in an archetype exists in blocks.""" + return [ + f"Archetype {a.id!r} names unknown block {ref.id!r}." + for a in archetypes + for ref in a.blocks + if ref.id not in blocks + ] + + +def _is_valid_fallback(entry: str) -> bool: + """Whether `entry` is a pattern name or a ``pattern:variant`` form.""" + if entry in ABSTRACT_PATTERNS: + return True + match = _PATTERN_KNOB_RE.match(entry) + return match is not None and match.group(1) in ABSTRACT_PATTERNS + + +def _lint_fallbacks(blocks: Mapping[str, BlockSpec]) -> list[str]: + """Every fallback entry is a pattern name or a ``pattern:variant`` form.""" + findings = [ + f"Block {block.id!r} pattern {block.pattern!r} is not an abstract pattern." + for block in blocks.values() + if block.pattern not in ABSTRACT_PATTERNS + ] + findings.extend( + f"Block {block.id!r} fallback entry {entry!r} is not a pattern name or" + " pattern:variant form." + for block in blocks.values() + for entry in block.fallback + if not _is_valid_fallback(entry) + ) + return findings + + +def _lint_placeholders(blocks: Mapping[str, BlockSpec]) -> list[str]: + """Every ``{placeholder}`` and ``appliesWhen`` key names a slot or field.""" + findings: list[str] = [] + for block in blocks.values(): + known = set(block.slot_names()) + for label, question in block.questions(): + unknown = [p for p in question.placeholders() if p not in known] + unknown.extend(k for k in question.applies_when if k not in known) + findings.extend( + f"Block {block.id!r} question {label!r} refers to {name!r}, which" + " is not a slot or field of that block." + for name in unknown + ) + return findings + + +def _is_valid_requirement(entry: str, block: BlockSpec) -> bool: + """Whether a `requires` entry names a slot, knob option, pattern variant, or flag.""" + if entry in CAPABILITY_FLAGS or entry in block.slot_names(): + return True + if _PATTERN_VARIANT_RE.match(entry) is not None: + return _PATTERN_VARIANT_RE.sub(r"\1", entry) in ABSTRACT_PATTERNS + knob, _, option = entry.partition(":") + if option: + question = block.anatomy.get(knob) + return question is not None and option in question.option_ids() + return any(entry in q.option_ids() for q in block.anatomy.values()) + + +def _lint_requires(blocks: Mapping[str, BlockSpec]) -> list[str]: + """Every `requires` entry names a slot, a knob option, a pattern variant, or a flag.""" + return [ + f"Block {block.id!r} question {label!r} option {option!r} requires" + f" {entry!r}, which is not a slot, knob option, pattern variant, or" + " capability flag." + for block in blocks.values() + for label, question in block.questions() + for option, entries in question.requires.items() + for entry in entries + if not _is_valid_requirement(entry, block) + ] + + +def _lint_options_from(blocks: Mapping[str, BlockSpec]) -> list[str]: + """Every `optionsFrom` path starts at a slot or field of the block.""" + return [ + f"Block {block.id!r} question {label!r} optionsFrom" + f" {question.options_from!r} does not start at a slot of that block." + for block in blocks.values() + for label, question in block.questions() + if question.options_from is not None + and question.options_from.split(".", 1)[0] not in block.slot_names() + ] + + +def lint_grammar( + archetypes: Sequence[LayoutArchetype], + blocks: Sequence[BlockSpec], + *, + families: Sequence[str] = (), +) -> list[str]: + """Runs every lint check and returns the findings (empty when clean).""" + by_id = {b.id: b for b in blocks} + findings = _lint_unique_ids(archetypes, blocks) + if families: + allowed_families = set(families) + findings.extend( + f"Archetype {a.id!r} references unknown family {a.family!r}." + for a in archetypes + if a.family not in allowed_families + ) + findings.extend(_lint_archetype_anchor(archetypes)) + findings.extend(_lint_block_ids_exist(archetypes, by_id)) + findings.extend(_lint_fallbacks(by_id)) + findings.extend(_lint_placeholders(by_id)) + findings.extend(_lint_requires(by_id)) + findings.extend(_lint_options_from(by_id)) + return findings + + +def _schema_findings(data: Mapping[str, Any]) -> list[str]: + """Formats schema validation errors as ``path: message`` strings.""" + errors = sorted( + _archetype_schema_validator().iter_errors(data), + key=lambda err: list(map(str, err.absolute_path)), + ) + return [ + f"/{'/'.join(str(p) for p in err.absolute_path)}: {err.message}" + for err in errors + ] + + +@dataclass(frozen=True) +class ArchetypeGrammar: + """A validated, linted archetype grammar.""" + + version: str + thresholds: Mapping[str, float] = field(hash=False) + job: Mapping[str, QuestionSpec] = field(hash=False) + archetypes: tuple[LayoutArchetype, ...] + blocks: Mapping[str, BlockSpec] = field(hash=False) + rules: tuple[Rule, ...] = () + lint: tuple[str, ...] = () + + @classmethod + def from_json(cls, data: Mapping[str, Any]) -> ArchetypeGrammar: + """Validates `data` against the schema, parses it, and lints it. + + Raises: + GrammarError: On any schema violation or lint finding; the message + lists every finding. + """ + findings = _schema_findings(data) + if findings: + raise GrammarError( + "Archetype grammar failed schema validation:\n " + + "\n ".join(findings) + ) + job = _parse_questions(data["job"]) + archetypes = tuple(LayoutArchetype.from_json(a) for a in data["archetypes"]) + blocks = tuple(BlockSpec.from_json(b) for b in data["blocks"]) + thresholds = {k: float(v) for k, v in data["thresholds"].items()} + findings = lint_grammar( + archetypes, blocks, families=tuple(job["family"].options) + ) + try: + validate_threshold_relations(thresholds, "thresholds") + except ValueError as exc: + findings.append(str(exc)) + if findings: + raise GrammarError( + "Archetype grammar failed lint:\n " + "\n ".join(findings) + ) + return cls( + version=str(data["version"]), + thresholds=thresholds, + job=job, + archetypes=archetypes, + blocks={b.id: b for b in blocks}, + rules=tuple( + Rule(id=r["id"], rule=r["rule"]) for r in data.get("rules", ()) + ), + lint=tuple(data.get("lint", ())), + ) + + @classmethod + def default(cls) -> ArchetypeGrammar: + """The grammar bundled with this package, loaded once and cached.""" + return _default_grammar() + + def archetype(self, archetype_id: str) -> LayoutArchetype: + """The archetype with `archetype_id`. + + Raises: + KeyError: If no archetype has that id. + """ + for archetype in self.archetypes: + if archetype.id == archetype_id: + return archetype + raise KeyError(archetype_id) + + def block(self, block_id: str) -> BlockSpec: + """The block with `block_id`. + + Raises: + KeyError: If no block has that id. + """ + return self.blocks[block_id] + + def families(self) -> tuple[str, ...]: + """Family ids in the order the family question lists them.""" + return tuple(self.job["family"].options) + + def archetypes_in(self, family: str) -> tuple[LayoutArchetype, ...]: + """Archetypes of `family` in grammar order.""" + return tuple(a for a in self.archetypes if a.family == family) + + def brief_roles(self) -> tuple[str, ...]: + """Role names a `LayoutBrief` may use: family ids, then block ids.""" + return self.families() + tuple(self.blocks) + + def threshold(self, name: str) -> float: + """The threshold `name` (``family``, ``expected``, ``actionGateFloor``, ...). + + Raises: + KeyError: If the grammar defines no such threshold. + """ + return self.thresholds[name] + + +@functools.cache +def _default_grammar() -> ArchetypeGrammar: + """Loads ``assets/archetypes.json`` once per process.""" + return ArchetypeGrammar.from_json(load_asset("archetypes.json")) diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/assets/archetype_definition.json b/python/a2ui_agent/src/a2ui/inference_formats/decision/assets/archetype_definition.json new file mode 100644 index 0000000000..ca918f3bd9 --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/assets/archetype_definition.json @@ -0,0 +1,321 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://a2ui.org/specification/v1_0/decision/archetype_definition.json", + "title": "A2UI decision layout archetype grammar", + "description": "Catalog-agnostic grammar of layout archetypes, blocks, questions, slots, and rules consumed by the decision inference format.", + "type": "object", + "required": ["version", "thresholds", "job", "archetypes", "blocks"], + "additionalProperties": false, + "properties": { + "$schema": { "type": "string" }, + "version": { "type": "string", "minLength": 1 }, + "thresholds": { "$ref": "#/$defs/thresholds" }, + "job": { "$ref": "#/$defs/job" }, + "archetypes": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/archetype" } + }, + "blocks": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/block" } + }, + "rules": { + "type": "array", + "items": { "$ref": "#/$defs/rule" } + }, + "lint": { + "type": "array", + "items": { "type": "string" } + } + }, + "$defs": { + "unitInterval": { "type": "number", "minimum": 0, "maximum": 1 }, + "identifier": { "type": "string", "pattern": "^[a-z_]+$" }, + "blockMark": { + "type": "string", + "pattern": "^[a-z_]+[!?]?$", + "description": "A block id with an optional mark: `!` required, `?` optional, bare expected." + }, + "stringList": { + "type": "array", + "items": { "type": "string" } + }, + "stringMap": { + "type": "object", + "additionalProperties": { "type": "string" } + }, + "range": { + "type": "array", + "description": "An inclusive [min, max] pair; null leaves that end open.", + "prefixItems": [ + { "type": ["integer", "null"] }, + { "type": ["integer", "null"] } + ], + "minItems": 2, + "maxItems": 2, + "items": false + }, + "thresholds": { + "type": "object", + "required": [ + "family", + "archetype", + "expected", + "optional", + "instance", + "reask_below", + "actionGateFloor", + "actionGateCap" + ], + "additionalProperties": false, + "properties": { + "family": { "$ref": "#/$defs/unitInterval" }, + "archetype": { "$ref": "#/$defs/unitInterval" }, + "expected": { "$ref": "#/$defs/unitInterval" }, + "optional": { "$ref": "#/$defs/unitInterval" }, + "instance": { "$ref": "#/$defs/unitInterval" }, + "reask_below": { "$ref": "#/$defs/unitInterval" }, + "actionGateFloor": { "$ref": "#/$defs/unitInterval" }, + "actionGateCap": { "$ref": "#/$defs/unitInterval" } + } + }, + "job": { + "type": "object", + "required": ["family", "stakes", "urgency"], + "additionalProperties": false, + "properties": { + "family": { "$ref": "#/$defs/choiceQuestion" }, + "stakes": { "$ref": "#/$defs/scoreQuestion" }, + "urgency": { "$ref": "#/$defs/scoreQuestion" } + } + }, + "shapeFilter": { + "type": "object", + "description": "Deterministic payload pre-filter evaluated before a question enters the batch.", + "additionalProperties": false, + "properties": { + "pointers": { "$ref": "#/$defs/stringList" }, + "arrayLength": { "$ref": "#/$defs/range" }, + "elementTypes": { "$ref": "#/$defs/stringList" }, + "elementKeys": { "$ref": "#/$defs/stringList" }, + "mutable": { "type": "boolean" }, + "proseLength": { + "type": "array", + "items": { "enum": ["line", "blurb", "summary", "article"] } + }, + "count": { "$ref": "#/$defs/range" }, + "actions_allowed": { "type": "boolean" } + } + }, + "archetype": { + "type": "object", + "required": ["id", "family", "criteria", "blocks"], + "additionalProperties": false, + "properties": { + "id": { "$ref": "#/$defs/identifier" }, + "family": { "$ref": "#/$defs/identifier" }, + "criteria": { "type": "string", "minLength": 1 }, + "blocks": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/blockMark" } + }, + "shape": { "$ref": "#/$defs/shapeFilter" }, + "atLeast": { "type": "integer", "minimum": 1 }, + "frame": { + "type": "object", + "additionalProperties": { "type": "boolean" } + } + } + }, + "appliesWhen": { + "type": "object", + "description": "Slot name to semantic type(s) or the word `bound`; the question is asked only when it holds.", + "additionalProperties": { + "oneOf": [{ "type": "string" }, { "$ref": "#/$defs/stringList" }] + } + }, + "derivedWhen": { + "type": "object", + "description": "Deterministic answers keyed by hint source; the question is skipped when one matches.", + "additionalProperties": { "type": "object" } + }, + "requires": { + "type": "object", + "description": "Option id to the slots, knob options, pattern variants, or capability flags it needs.", + "additionalProperties": { "$ref": "#/$defs/stringList" } + }, + "questionBase": { + "type": "object", + "required": ["kind", "question"], + "properties": { + "kind": { "enum": ["choice", "boolean", "score"] }, + "question": { "type": "string", "minLength": 1 }, + "appliesWhen": { "$ref": "#/$defs/appliesWhen" }, + "derivedWhen": { "$ref": "#/$defs/derivedWhen" }, + "note": { "type": "string" } + } + }, + "choiceQuestion": { + "allOf": [{ "$ref": "#/$defs/questionBase" }], + "type": "object", + "additionalProperties": false, + "properties": { + "kind": { "const": "choice" }, + "question": true, + "appliesWhen": true, + "derivedWhen": true, + "note": true, + "options": { + "type": "object", + "minProperties": 1, + "propertyNames": { "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, + "additionalProperties": { "type": "string" } + }, + "optionsFrom": { "type": "string", "minLength": 1 }, + "requires": { "$ref": "#/$defs/requires" }, + "allowNone": { "type": "boolean" } + }, + "oneOf": [{ "required": ["options"] }, { "required": ["optionsFrom"] }] + }, + "booleanQuestion": { + "allOf": [{ "$ref": "#/$defs/questionBase" }], + "type": "object", + "required": ["yes", "no"], + "additionalProperties": false, + "properties": { + "kind": { "const": "boolean" }, + "question": true, + "appliesWhen": true, + "derivedWhen": true, + "note": true, + "yes": { "type": "string", "minLength": 1 }, + "no": { "type": "string", "minLength": 1 } + } + }, + "scoreQuestion": { + "allOf": [{ "$ref": "#/$defs/questionBase" }], + "type": "object", + "required": ["levels"], + "additionalProperties": false, + "properties": { + "kind": { "const": "score" }, + "question": true, + "appliesWhen": true, + "derivedWhen": true, + "note": true, + "levels": { + "type": "array", + "minItems": 2, + "items": { "type": "string", "minLength": 1 } + }, + "perPointer": { "type": "boolean" }, + "select": { + "type": "object", + "additionalProperties": false, + "properties": { + "min": { "type": "integer", "minimum": 0 }, + "max": { "type": "integer", "minimum": 1 }, + "aboveLevel": { "type": "number", "minimum": 0 } + } + } + } + }, + "question": { + "oneOf": [ + { "$ref": "#/$defs/choiceQuestion" }, + { "$ref": "#/$defs/booleanQuestion" }, + { "$ref": "#/$defs/scoreQuestion" } + ] + }, + "slot": { + "type": "object", + "required": ["from"], + "additionalProperties": false, + "properties": { + "from": { + "type": "array", + "minItems": 1, + "items": { "type": "string", "minLength": 1 } + }, + "required": { "type": "boolean" }, + "repeat": { "type": "boolean" }, + "max": { "type": "integer", "minimum": 1 }, + "prefer": { "$ref": "#/$defs/stringList" }, + "avoidKeys": { "$ref": "#/$defs/stringList" }, + "sibling": { "$ref": "#/$defs/stringList" }, + "orderBy": { "type": "string", "minLength": 1 }, + "mutable": { "type": "boolean" }, + "elementTypes": { "$ref": "#/$defs/stringList" }, + "default": true, + "note": { "type": "string" }, + "fields": { + "type": "object", + "propertyNames": { "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, + "additionalProperties": { "$ref": "#/$defs/slot" } + } + } + }, + "measure": { + "type": "object", + "required": ["derivedFrom", "levels"], + "additionalProperties": false, + "properties": { + "derivedFrom": { "type": "string", "minLength": 1 }, + "levels": { + "type": "object", + "minProperties": 1, + "additionalProperties": { "$ref": "#/$defs/range" } + }, + "note": { "type": "string" } + } + }, + "block": { + "type": "object", + "required": ["id", "pattern", "fallback"], + "additionalProperties": false, + "properties": { + "id": { "$ref": "#/$defs/identifier" }, + "pattern": { "$ref": "#/$defs/identifier" }, + "shape": { "$ref": "#/$defs/shapeFilter" }, + "gate": { "$ref": "#/$defs/booleanQuestion" }, + "salience": { "$ref": "#/$defs/scoreQuestion" }, + "anatomy": { + "type": "object", + "propertyNames": { "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, + "additionalProperties": { "$ref": "#/$defs/question" } + }, + "instance": { + "type": "object", + "propertyNames": { "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, + "additionalProperties": { "$ref": "#/$defs/question" } + }, + "measures": { + "type": "object", + "additionalProperties": { "$ref": "#/$defs/measure" } + }, + "slots": { + "type": "object", + "propertyNames": { "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, + "additionalProperties": { "$ref": "#/$defs/slot" } + }, + "fallback": { + "type": "array", + "minItems": 1, + "items": { "type": "string", "pattern": "^[a-z_-]+(:[a-z_]+)?$" } + } + } + }, + "rule": { + "type": "object", + "required": ["id", "rule"], + "additionalProperties": false, + "properties": { + "id": { "type": "string", "pattern": "^[a-z][a-z0-9-]*$" }, + "rule": { "type": "string", "minLength": 1 } + } + } + } +} diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/assets/archetypes.json b/python/a2ui_agent/src/a2ui/inference_formats/decision/assets/archetypes.json new file mode 100644 index 0000000000..7baf58fba5 --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/assets/archetypes.json @@ -0,0 +1,1813 @@ +{ + "$schema": "https://a2ui.org/specification/v1_0/decision/archetype_definition.json", + "version": "1", + "thresholds": { + "family": 0.4, + "archetype": 0.4, + "expected": 0.5, + "optional": 0.75, + "instance": 0.5, + "reask_below": 0.75, + "actionGateFloor": 0.7, + "actionGateCap": 0.95 + }, + "job": { + "family": { + "kind": "choice", + "question": "What is the person here to do?", + "options": { + "browse": "Look through a set of similar things: results, a catalogue, a feed, an inbox, a directory, records.", + "monitor": "See numbers and status at a glance: usage, health, progress, balances, today's summary.", + "inspect": "Understand one thing in depth: a product, a place, a person, an order, an event, an article.", + "act": "Commit to or confirm one action, or review something just before or just after it happens.", + "input": "Provide or change information: fill in details, adjust settings, answer questions.", + "follow": "Do something step by step: a how-to, a recipe, a checklist, troubleshooting." + } + }, + "stakes": { + "kind": "score", + "question": "If this goes wrong, how bad is it for the person?", + "levels": [ + "Nothing is at stake; the person is only looking.", + "A small inconvenience that is easy to undo.", + "Money, time, or data is involved; undoing it takes effort.", + "Irreversible: a deletion, a payment, a commitment that cannot be taken back." + ] + }, + "urgency": { + "kind": "score", + "question": "How quickly does the person need to act on what they see?", + "levels": [ + "No hurry; they are browsing or reading.", + "Soon; something is due or pending.", + "Right now; something is failing, expiring, or happening." + ] + } + }, + "archetypes": [ + { + "id": "feed", + "family": "browse", + "criteria": "A collection to look through, where the items matter more than any one of them.", + "blocks": [ + "banner?", + "filters?", + "picture?", + "collection!" + ] + }, + { + "id": "compare", + "family": "browse", + "criteria": "A few options the person is weighing against each other, with the same attributes for each.", + "shape": { + "arrayLength": [ + 2, + 5 + ] + }, + "blocks": [ + "banner?", + "prose?", + "comparison!", + "actions?" + ] + }, + { + "id": "dashboard", + "family": "monitor", + "criteria": "Numbers and status at a glance, with the most important figure first.", + "blocks": [ + "banner?", + "headline!", + "chart?", + "facts?", + "media?", + "collection?" + ], + "atLeast": 2 + }, + { + "id": "detail", + "family": "inspect", + "criteria": "One thing in depth: what it is, its key figures, its description, its particulars, what it contains, what can be done with it.", + "blocks": [ + "picture?", + "banner?", + "headline?", + "prose", + "facts", + "media?", + "collection?", + "actions?" + ], + "atLeast": 2 + }, + { + "id": "result", + "family": "act", + "criteria": "The outcome of something the person just did: success, failure, a receipt, nothing found.", + "blocks": [ + "outcome!", + "facts?", + "steps?", + "actions" + ] + }, + { + "id": "confirm", + "family": "act", + "criteria": "One short decision about one thing, asked before it happens: confirm, delete, approve, allow.", + "blocks": [ + "prose", + "facts?", + "actions!" + ], + "frame": { + "dialog": true + } + }, + { + "id": "checkout", + "family": "act", + "criteria": "Review and commit: a cart, an order or booking summary with totals, a payment.", + "blocks": [ + "banner?", + "collection", + "facts!", + "form?", + "actions!" + ], + "frame": { + "stickyActions": true + } + }, + { + "id": "form", + "family": "input", + "criteria": "Data entry: creating or editing a record, a booking, a survey, a request with several fields.", + "shape": { + "mutable": true + }, + "blocks": [ + "prose?", + "form!", + "actions" + ] + }, + { + "id": "settings", + "family": "input", + "criteria": "Preferences, account options, or configuration, arranged as groups of rows that each hold one setting.", + "shape": { + "mutable": true + }, + "blocks": [ + "banner?", + "groups!", + "actions?" + ] + }, + { + "id": "guide", + "family": "follow", + "criteria": "Instructions followed in order: a how-to, a method, troubleshooting, an onboarding checklist.", + "blocks": [ + "picture?", + "prose?", + "facts?", + "steps!", + "actions?" + ] + }, + { + "id": "article", + "family": "inspect", + "criteria": "Something to read: an explanation, a story, a report, documentation, where the text is the point.", + "shape": { + "proseLength": [ + "summary", + "article" + ] + }, + "blocks": [ + "picture?", + "prose!", + "facts?", + "collection?", + "actions?" + ] + }, + { + "id": "timeline", + "family": "inspect", + "criteria": "What happened, in order: shipment events, an audit trail, a build's stages, a patient's history, a project's milestones.", + "shape": { + "pointers": [ + "array" + ], + "elementTypes": [ + "datetime", + "date", + "time", + "relative_time" + ] + }, + "blocks": [ + "banner?", + "headline?", + "timeline!", + "actions?" + ] + }, + { + "id": "location", + "family": "inspect", + "criteria": "A place, or something at a place: where it is, how to get there, what is nearby.", + "shape": { + "pointers": [ + "location", + "address" + ] + }, + "blocks": [ + "picture?", + "map!", + "facts", + "collection?", + "actions?" + ] + }, + { + "id": "chat", + "family": "browse", + "criteria": "A conversation: messages between people or with an assistant, in order, each with who said it and when.", + "shape": { + "pointers": [ + "array" + ], + "elementKeys": [ + "author", + "sender", + "from", + "role", + "speaker" + ] + }, + "blocks": [ + "banner?", + "conversation!", + "compose?" + ] + } + ], + "blocks": [ + { + "id": "banner", + "pattern": "banner", + "gate": { + "kind": "boolean", + "question": "Does something here need the person's attention before anything else?", + "yes": "A warning, an outage, a deadline, an error, an offer about to expire, or a success to acknowledge.", + "no": "Nothing unusual is going on; this is business as usual." + }, + "slots": { + "title": { + "from": [ + "string", + "enum" + ], + "required": true + }, + "text": { + "from": [ + "string", + "long_text" + ] + } + }, + "instance": { + "tone": { + "kind": "choice", + "question": "For the person looking at this, what kind of news is {title}?", + "options": { + "success": "Good news or a healthy state: done, available, on time, paid, active.", + "warning": "Needs attention soon: low, delayed, pending, degraded, expiring.", + "danger": "Bad news: failed, overdue, critical, cancelled, offline.", + "neutral": "Plain information that is neither good nor bad." + } + } + }, + "fallback": [ + "banner", + "prose" + ] + }, + { + "id": "picture", + "pattern": "picture", + "shape": { + "pointers": [ + "image_url", + "media_object" + ] + }, + "gate": { + "kind": "boolean", + "question": "Should a picture lead this?", + "yes": "One visual subject leads: a place, dish, product, property, animal, trip, event, person, or artwork.", + "no": "The subject has no look: an order, an account, a transaction, a setting, a set of figures." + }, + "slots": { + "picture": { + "from": [ + "image_url", + "media_object" + ], + "required": true, + "avoidKeys": [ + "logo", + "icon", + "avatar", + "thumbnail" + ] + }, + "caption": { + "from": [ + "string", + "title" + ] + }, + "width": { + "from": [ + "integer" + ], + "sibling": [ + "width", + "w" + ] + }, + "height": { + "from": [ + "integer" + ], + "sibling": [ + "height", + "h" + ] + }, + "aspectRatio": { + "from": [ + "ratio", + "string" + ], + "sibling": [ + "aspectRatio", + "aspect" + ] + }, + "orientation": { + "from": [ + "enum" + ], + "sibling": [ + "orientation" + ] + } + }, + "anatomy": { + "framing": { + "kind": "choice", + "question": "What kind of picture is this, and how should it be framed?", + "options": { + "banner": "A wide scene that can be cropped: a place, a landscape, a venue, a dish on a table, a product in use.", + "portrait": "A person or a face: shown whole, square or round, never cropped at the head.", + "object": "A thing on its own that must not be cropped: a product on a plain background, a logo, a diagram, a chart image.", + "poster": "Taller than wide and read whole: a book cover, a poster, a document page, a phone screenshot." + }, + "derivedWhen": { + "keyHint": { + "logo": "object", + "icon": "object", + "avatar": "portrait", + "portrait": "portrait", + "cover": "poster", + "poster": "poster" + }, + "aspectRatio": { + "under": { + "0.8": "poster" + }, + "over": { + "1.5": "banner" + } + } + } + }, + "prominence": { + "kind": "score", + "question": "How much of the screen should this picture take?", + "levels": [ + "A small mark beside the title: a logo or avatar.", + "A supporting picture beside the text, about a third of the width.", + "A leading picture across the full width above the text.", + "The picture is the content; everything else is a caption." + ] + } + }, + "fallback": [ + "picture" + ] + }, + { + "id": "filters", + "pattern": "filters", + "shape": { + "pointers": [ + "array" + ], + "arrayLength": [ + 8, + null + ], + "mutable": true + }, + "gate": { + "kind": "boolean", + "question": "Will the person need to search or narrow down what is shown?", + "yes": "There are many items, more than fit on a screen, in recognisable categories.", + "no": "There are only a few items, or nothing to narrow." + }, + "slots": { + "query": { + "from": [ + "string" + ], + "mutable": true + }, + "categories": { + "from": [ + "enum", + "status", + "array" + ], + "note": "the distinct values of an enum field across the items, or a sibling list of category names; how they are drawn is the catalog's choice" + } + }, + "fallback": [ + "filters" + ] + }, + { + "id": "headline", + "pattern": "headline", + "shape": { + "pointers": [ + "number", + "integer", + "count", + "currency", + "percent", + "ratio", + "quantity", + "rating", + "bounded", + "duration", + "status", + "enum", + "boolean", + "time", + "datetime", + "relative_time" + ], + "count": [ + 1, + null + ] + }, + "gate": { + "kind": "boolean", + "question": "Are there a few values the person wants at a glance before anything else?", + "yes": "Key figures or states such as totals, counts, rates, balances, scores, durations, a status, a next time, on or off.", + "no": "The values are details to look up, not headlines, or there are too many for any to stand out." + }, + "salience": { + "kind": "score", + "perPointer": true, + "question": "How important is {label} to the person at a glance?", + "levels": [ + "A detail they might look up.", + "Useful context.", + "One of the main things they came to see.", + "The single most important value here." + ], + "select": { + "min": 1, + "max": 6, + "aboveLevel": 1.5 + } + }, + "slots": { + "items": { + "repeat": true, + "from": [ + "number", + "integer", + "count", + "currency", + "percent", + "ratio", + "quantity", + "rating", + "bounded", + "duration", + "status", + "enum", + "boolean", + "time", + "datetime", + "relative_time" + ], + "max": 6, + "orderBy": "salience", + "fields": { + "label": { + "from": [ + "key" + ] + }, + "value": { + "from": [ + "any" + ], + "required": true + }, + "delta": { + "from": [ + "number", + "percent" + ], + "sibling": [ + "delta", + "change", + "diff", + "previous" + ] + }, + "min": { + "from": [ + "number" + ], + "sibling": [ + "min" + ] + }, + "max": { + "from": [ + "number" + ], + "sibling": [ + "max", + "total", + "limit" + ] + } + } + } + }, + "anatomy": { + "deltas": { + "kind": "boolean", + "question": "Do these values change over time in a way the person tracks?", + "yes": "Usage, spending, revenue, health, or performance compared with a previous period or a target.", + "no": "Fixed figures such as counts or specifications, with nothing to compare against." + }, + "gauge": { + "kind": "boolean", + "appliesWhen": { + "value": "bounded" + }, + "question": "Is {label} read as a level between empty and full?", + "yes": "Progress, capacity, battery, utilization, a score out of a maximum.", + "no": "A plain number that happens to have bounds." + } + }, + "instance": { + "news": { + "kind": "choice", + "appliesWhen": { + "delta": "bound" + }, + "question": "For the person looking at this, is the change in {label} good or bad news?", + "options": { + "good": "The figure moved the way the person wants it to.", + "bad": "The figure moved the way the person does not want.", + "neutral": "Neither; it is just a change." + } + }, + "state_tone": { + "kind": "choice", + "appliesWhen": { + "value": [ + "status", + "enum", + "boolean" + ] + }, + "question": "Is {label} being {value} good, bad, or neutral for the person?", + "options": { + "success": "Good: active, healthy, on, done, in stock.", + "warning": "Needs attention: pending, low, degraded.", + "danger": "Bad: failed, offline, overdue.", + "neutral": "Neither." + } + } + }, + "fallback": [ + "headline", + "facts" + ] + }, + { + "id": "media", + "pattern": "media", + "shape": { + "pointers": [ + "video_url", + "audio_url" + ] + }, + "gate": { + "kind": "boolean", + "question": "Is there something to play here?", + "yes": "A video, an episode, a recording, a song, a voice note.", + "no": "The link is to a file or page, not something played in place." + }, + "slots": { + "source": { + "from": [ + "video_url", + "audio_url" + ], + "required": true + }, + "poster": { + "from": [ + "image_url" + ], + "sibling": [ + "poster", + "thumbnail", + "artwork" + ] + }, + "title": { + "from": [ + "title", + "string" + ] + }, + "duration": { + "from": [ + "duration" + ] + } + }, + "fallback": [ + "media", + "facts" + ] + }, + { + "id": "chart", + "pattern": "chart", + "shape": { + "pointers": [ + "array" + ], + "elementTypes": [ + "number", + "date", + "datetime" + ] + }, + "gate": { + "kind": "boolean", + "question": "Is there a series of values over time or categories that is easier to read as a chart than as numbers?", + "yes": "A trend, a history, a breakdown by category, a comparison of several series.", + "no": "Single figures, or a list of records that are not a series." + }, + "slots": { + "series": { + "from": [ + "array" + ], + "required": true + }, + "title": { + "from": [ + "key", + "string" + ] + } + }, + "fallback": [ + "chart", + "headline", + "collection" + ] + }, + { + "id": "facts", + "pattern": "facts", + "shape": { + "pointers": [ + "string", + "name", + "title", + "identifier", + "number", + "integer", + "count", + "quantity", + "percent", + "percentage", + "rating", + "bounded", + "date", + "time", + "datetime", + "relative_time", + "duration", + "enum", + "status", + "email", + "phone", + "url", + "place_name", + "address", + "boolean", + "currency" + ], + "count": [ + 1, + null + ] + }, + "gate": { + "kind": "boolean", + "question": "Are there particulars the person would look up, such as a reference, a date, an address, a status, a total?", + "yes": "Labelled values that are read, not acted on: order number, date, address, status, total, owner.", + "no": "There are no such particulars, or they are already shown as headline figures." + }, + "slots": { + "rows": { + "repeat": true, + "from": [ + "string", + "name", + "title", + "identifier", + "number", + "integer", + "count", + "quantity", + "percent", + "percentage", + "rating", + "bounded", + "date", + "time", + "datetime", + "relative_time", + "duration", + "enum", + "status", + "email", + "phone", + "url", + "place_name", + "address", + "boolean", + "currency" + ], + "max": 8, + "orderBy": "salience", + "fields": { + "label": { + "from": [ + "key" + ], + "required": true + }, + "value": { + "from": [ + "any" + ], + "required": true + } + } + } + }, + "fallback": [ + "facts", + "prose" + ] + }, + { + "id": "prose", + "pattern": "prose", + "shape": { + "pointers": [ + "long_text", + "string" + ] + }, + "gate": { + "kind": "boolean", + "question": "Is there something to read, a sentence or more, that explains or describes?", + "yes": "A description, a summary, an explanation, a message, terms, a note.", + "no": "Only short labels and values; nothing to read in sentences." + }, + "slots": { + "heading": { + "from": [ + "title", + "string" + ] + }, + "body": { + "from": [ + "long_text", + "markdown", + "string" + ], + "required": true + } + }, + "measures": { + "length": { + "derivedFrom": "body.hints.wordCount", + "levels": { + "line": [ + 0, + 15 + ], + "blurb": [ + 15, + 60 + ], + "summary": [ + 60, + 200 + ], + "article": [ + 200, + null + ] + }, + "note": "Computed, never asked. Patterns may vary by it (an article gets a heading and may be collapsed behind a Read more where the catalog can; a line is set inline). The rules use it too: article-length prose moves to the front of detail and suppresses the picture's prominence to supporting." + } + }, + "fallback": [ + "prose" + ] + }, + { + "id": "collection", + "pattern": "collection", + "shape": { + "pointers": [ + "array" + ], + "elementTypes": [ + "object", + "string" + ] + }, + "gate": { + "kind": "boolean", + "question": "Are there several similar items the person would scan or pick from?", + "yes": "Results, products, people, records, messages, line items, episodes, devices, or any set of comparable things.", + "no": "This is about one thing, or the list is only a series of numbers." + }, + "anatomy": { + "layout": { + "kind": "choice", + "question": "How should these items be laid out?", + "options": { + "rows": "Dense rows to scan quickly: text matters more than pictures, or there are many items.", + "cards": "Large picture cards, one per row: the person chooses mostly by look among a few rich items.", + "grid": "A grid of small picture tiles: many visual items browsed casually.", + "reel": "A sideways-scrolling shelf of picture cards: a short set of suggestions or a gallery." + }, + "requires": { + "cards": [ + "picture" + ], + "grid": [ + "picture", + "pattern:collection:grid" + ], + "reel": [ + "picture" + ] + }, + "note": "pattern:. means the option is offered only when the catalog's pattern has that variant, so a catalog that would draw grid as a reel is not asked about grid." + }, + "leading": { + "kind": "choice", + "question": "What should lead each item, so the person knows what kind of thing it is?", + "options": { + "thumbnail": "A small picture of the item.", + "avatar": "A picture of a person.", + "icon": "A symbol for the item's kind or state.", + "number": "Its rank or position.", + "none": "Nothing; the title is enough." + } + }, + "trailing": { + "kind": "choice", + "question": "What should end each item?", + "options": { + "chevron": "A way in: tapping the item opens it.", + "button": "One action on each item, such as Book, Add, Play.", + "value": "A figure or status read at a glance.", + "none": "Nothing." + }, + "requires": { + "button": [ + "actions_allowed" + ] + } + } + }, + "slots": { + "items": { + "repeat": true, + "from": [ + "array" + ], + "required": true, + "fields": { + "headline": { + "from": [ + "title", + "name", + "string" + ], + "required": true, + "prefer": [ + "name", + "title", + "label" + ] + }, + "supporting": { + "from": [ + "string", + "long_text", + "markdown", + "code", + "place_name", + "address", + "email", + "url", + "quantity", + "duration", + "date", + "number", + "integer", + "count" + ], + "prefer": [ + "subtitle", + "summary", + "description", + "snippet", + "detail", + "body", + "caption", + "location", + "address", + "elevation" + ], + "avoidKeys": [ + "id", + "currency" + ] + }, + "picture": { + "from": [ + "image_url", + "media_object" + ] + }, + "meta": { + "from": [ + "currency", + "quantity", + "date", + "time", + "datetime", + "relative_time", + "duration", + "distance", + "place_name", + "count", + "integer", + "number", + "percent", + "percentage", + "url", + "string", + "long_text", + "code", + "status", + "enum" + ], + "prefer": [ + "price", + "priceFrom", + "amount", + "cost", + "total", + "date", + "time", + "arrives", + "duration", + "distance", + "openRuns", + "runs", + "url", + "link", + "href" + ], + "max": 2, + "orderBy": "salience" + }, + "badge": { + "from": [ + "status", + "enum", + "boolean" + ], + "prefer": [ + "status", + "state", + "availability", + "stock", + "badge", + "tag", + "category", + "role" + ], + "avoidKeys": [ + "id", + "currency" + ] + }, + "rating": { + "from": [ + "rating", + "number" + ], + "prefer": [ + "rating", + "score", + "stars" + ] + } + } + } + }, + "instance": { + "badge_tone": { + "kind": "choice", + "appliesWhen": { + "badge": "bound" + }, + "question": "Is {badge} good, bad, or neutral news for the person?", + "options": { + "success": "Good: active, done, in stock, on time.", + "warning": "Needs attention: pending, low, delayed.", + "danger": "Bad: failed, cancelled, overdue.", + "neutral": "Neither." + } + } + }, + "fallback": [ + "collection" + ] + }, + { + "id": "comparison", + "pattern": "comparison", + "shape": { + "pointers": [ + "array" + ], + "arrayLength": [ + 2, + 5 + ], + "elementTypes": [ + "object" + ] + }, + "gate": { + "kind": "boolean", + "question": "Is the person choosing among these few options by comparing the same attributes?", + "yes": "Plans, flights, products, candidates, quotes: a handful of options with price, time, or features side by side.", + "no": "They are not alternatives to each other, or there are too many to compare side by side." + }, + "slots": { + "options": { + "repeat": true, + "from": [ + "array" + ], + "required": true, + "fields": { + "headline": { + "from": [ + "string" + ], + "required": true + }, + "picture": { + "from": [ + "image_url" + ] + }, + "attributes": { + "from": [ + "any" + ], + "repeat": true, + "max": 5 + }, + "highlight": { + "from": [ + "currency", + "number", + "date" + ] + } + } + } + }, + "instance": { + "headline_attribute": { + "kind": "choice", + "question": "Which attribute will the person decide on first?", + "optionsFrom": "attributes" + } + }, + "fallback": [ + "comparison", + "collection:cards", + "collection:rows" + ] + }, + { + "id": "steps", + "pattern": "steps", + "shape": { + "pointers": [ + "array" + ], + "elementTypes": [ + "string", + "object" + ] + }, + "gate": { + "kind": "boolean", + "question": "Are these things done in order, one after another?", + "yes": "Instructions, a method, a checklist, stages of a process, a timeline of what happened.", + "no": "They are independent items with no order to follow." + }, + "slots": { + "items": { + "repeat": true, + "from": [ + "array" + ], + "required": true, + "fields": { + "title": { + "from": [ + "title", + "name", + "string", + "long_text" + ], + "required": true + }, + "detail": { + "from": [ + "long_text", + "string" + ] + }, + "done": { + "from": [ + "boolean" + ] + } + } + } + }, + "fallback": [ + "steps", + "collection:rows" + ] + }, + { + "id": "form", + "pattern": "form", + "shape": { + "mutable": true + }, + "gate": { + "kind": "boolean", + "question": "Does the person need to type or choose values here?", + "yes": "Details to fill in: name, date, amount, notes, a choice among options.", + "no": "Everything is read-only, or the only choice is a button." + }, + "slots": { + "fields": { + "repeat": true, + "from": [ + "mutable" + ], + "required": true, + "fields": { + "label": { + "from": [ + "key" + ], + "required": true + }, + "value": { + "from": [ + "any" + ], + "required": true + }, + "options": { + "from": [ + "enum", + "array" + ] + }, + "min": { + "from": [ + "number" + ], + "sibling": [ + "min" + ] + }, + "max": { + "from": [ + "number" + ], + "sibling": [ + "max", + "limit" + ] + } + } + } + }, + "instance": { + "control": { + "kind": "choice", + "question": "What kind of input is {label}?", + "options": { + "shortText": "A word or a line: a name, a title, a code.", + "longText": "Several lines: notes, a message, a description.", + "number": "A quantity or amount typed as digits.", + "obscured": "A secret: a password or PIN.", + "toggle": "On or off, and it takes effect at once.", + "choice": "One of a few named options.", + "multiChoice": "Any number of named options.", + "range": "A value between a minimum and a maximum, where the exact number matters less than the position.", + "date": "A date, a time, or both." + }, + "requires": { + "choice": [ + "options" + ], + "multiChoice": [ + "options" + ], + "range": [ + "min", + "max" + ] + } + }, + "required": { + "kind": "boolean", + "question": "Must {label} be filled in before this can be submitted?", + "yes": "The task cannot proceed without it.", + "no": "It is optional or has a sensible default." + } + }, + "fallback": [ + "form", + "facts" + ] + }, + { + "id": "groups", + "pattern": "groups", + "shape": { + "mutable": true, + "pointers": [ + "object" + ] + }, + "gate": { + "kind": "boolean", + "question": "Are these settings, each one a row the person can read and change?", + "yes": "Preferences and options grouped by topic: notifications, privacy, playback, account.", + "no": "This is a single form to fill in and submit, not a set of standing preferences." + }, + "slots": { + "groups": { + "repeat": true, + "from": [ + "object" + ], + "required": true, + "fields": { + "heading": { + "from": [ + "key" + ], + "required": true + }, + "rows": { + "repeat": true, + "from": [ + "mutable" + ], + "fields": { + "label": { + "from": [ + "key" + ], + "required": true + }, + "value": { + "from": [ + "any" + ], + "required": true + } + } + } + } + } + }, + "instance": { + "row_kind": { + "kind": "choice", + "question": "What kind of row is {label}?", + "options": { + "switch": "One setting that is on or off and takes effect at once.", + "value": "A setting whose current value is shown and opens a picker of options when tapped.", + "navigation": "A way into another page of settings or information.", + "danger": "An action that removes or disconnects something: sign out, delete account." + } + } + }, + "fallback": [ + "groups", + "form" + ] + }, + { + "id": "actions", + "pattern": "actions", + "shape": { + "actions_allowed": true + }, + "gate": { + "kind": "boolean", + "question": "Is there something the person would do next from here, with a button?", + "yes": "Buy, book, save, send, confirm, retry, open, share.", + "no": "Nothing to do; the person only reads this." + }, + "slots": { + "buttons": { + "repeat": true, + "from": [ + "action" + ], + "max": 3, + "fields": { + "label": { + "from": [ + "string", + "key" + ], + "required": true + } + } + } + }, + "instance": { + "primary": { + "kind": "choice", + "question": "Which of these is the one thing the person most likely came to do?", + "optionsFrom": "buttons", + "allowNone": true + }, + "destructive": { + "kind": "boolean", + "question": "Does {label} remove, cancel, or spend something that cannot be easily undone?", + "yes": "Delete, cancel, sign out, pay, send.", + "no": "It opens, saves, continues, or can be undone." + } + }, + "fallback": [ + "actions" + ] + }, + { + "id": "timeline", + "pattern": "timeline", + "shape": { + "pointers": [ + "array" + ], + "elementTypes": [ + "datetime", + "date", + "time", + "relative_time" + ] + }, + "gate": { + "kind": "boolean", + "question": "Are these events that happened at particular times, best read in order?", + "yes": "Shipment scans, an audit log, build stages, visits, milestones, messages in a thread.", + "no": "The times are incidental; the items are things, not events." + }, + "slots": { + "events": { + "repeat": true, + "from": [ + "array" + ], + "required": true, + "orderBy": "time", + "fields": { + "time": { + "from": [ + "datetime", + "date", + "time", + "relative_time" + ], + "required": true + }, + "title": { + "from": [ + "title", + "string", + "status" + ], + "required": true + }, + "detail": { + "from": [ + "long_text", + "string", + "place_name", + "address" + ] + }, + "state": { + "from": [ + "status", + "enum", + "boolean" + ] + } + } + } + }, + "anatomy": { + "order": { + "kind": "choice", + "question": "Which end does the person want first?", + "options": { + "latest": "The most recent event matters most: tracking, a log, a feed of updates.", + "earliest": "The sequence is read from the start: a history, a story, a plan." + } + } + }, + "instance": { + "state_tone": { + "kind": "choice", + "appliesWhen": { + "state": "bound" + }, + "question": "Is {title} ({state}) good, bad, or neutral news?", + "options": { + "success": "Good.", + "warning": "Needs attention.", + "danger": "Bad.", + "neutral": "Neither." + } + } + }, + "fallback": [ + "timeline", + "steps", + "collection:rows" + ] + }, + { + "id": "map", + "pattern": "map", + "shape": { + "pointers": [ + "location", + "address" + ] + }, + "gate": { + "kind": "boolean", + "question": "Does the person need to see where this is?", + "yes": "A place to go to, something nearby, a route, an area.", + "no": "The address is a fact to read, as on a receipt or a profile." + }, + "slots": { + "location": { + "from": [ + "location", + "address" + ], + "required": true + }, + "label": { + "from": [ + "place_name", + "title", + "name", + "string" + ] + }, + "pins": { + "from": [ + "array" + ], + "elementTypes": [ + "location" + ] + } + }, + "fallback": [ + "map", + "facts" + ] + }, + { + "id": "conversation", + "pattern": "conversation", + "shape": { + "pointers": [ + "array" + ], + "elementKeys": [ + "author", + "sender", + "from", + "role", + "speaker" + ] + }, + "gate": { + "kind": "boolean", + "question": "Is this a back-and-forth between people, or between a person and an assistant?", + "yes": "Messages, replies, a chat log, a support thread, comments in order.", + "no": "A list of records that happen to have an author, such as articles or reviews." + }, + "slots": { + "messages": { + "repeat": true, + "from": [ + "array" + ], + "required": true, + "fields": { + "author": { + "from": [ + "name", + "string", + "enum" + ], + "required": true, + "prefer": [ + "author", + "sender", + "from", + "role", + "speaker" + ] + }, + "text": { + "from": [ + "long_text", + "markdown", + "string" + ], + "required": true, + "prefer": [ + "text", + "message", + "content", + "body" + ] + }, + "time": { + "from": [ + "datetime", + "time", + "relative_time" + ] + }, + "avatar": { + "from": [ + "image_url" + ], + "prefer": [ + "avatar", + "photo" + ] + }, + "attachment": { + "from": [ + "image_url", + "document_url", + "url" + ] + } + } + } + }, + "anatomy": { + "self": { + "kind": "choice", + "question": "Which author is the person reading this?", + "optionsFrom": "messages.author.distinct", + "allowNone": true, + "note": "Decides which side messages sit on; none means a transcript with every message on the left." + } + }, + "fallback": [ + "conversation", + "collection:rows" + ] + }, + { + "id": "compose", + "pattern": "compose", + "shape": { + "mutable": true, + "actions_allowed": true + }, + "gate": { + "kind": "boolean", + "question": "Can the person reply or add to this here?", + "yes": "An open conversation, a comment thread they take part in, a form of one field and a send button.", + "no": "A closed transcript or a log they only read." + }, + "slots": { + "draft": { + "from": [ + "string", + "long_text" + ], + "mutable": true, + "prefer": [ + "draft", + "reply", + "message", + "input" + ] + }, + "sendLabel": { + "from": [ + "string" + ], + "default": "Send" + } + }, + "fallback": [ + "compose" + ] + }, + { + "id": "outcome", + "pattern": "outcome", + "gate": { + "kind": "boolean", + "question": "Is this telling the person how something they did turned out?", + "yes": "Order placed, payment failed, message sent, nothing found, account deleted.", + "no": "Nothing has just happened; this is information or a task in progress." + }, + "slots": { + "headline": { + "from": [ + "string", + "enum" + ], + "required": true + }, + "detail": { + "from": [ + "long_text", + "string" + ] + } + }, + "instance": { + "tone": { + "kind": "choice", + "question": "Did {headline} go well for the person?", + "options": { + "success": "Yes: done, sent, placed, saved.", + "danger": "No: failed, declined, not found.", + "neutral": "Partly, or it is still pending." + } + } + }, + "fallback": [ + "outcome", + "banner", + "prose" + ] + } + ], + "rules": [ + { + "id": "required-block-wins", + "rule": "A block marked ! is present whatever its gate says; its gate is still asked so the trace can show disagreement." + }, + { + "id": "at-least", + "rule": "If fewer than atLeast blocks pass, include the highest-probability expected blocks until the count is met, before considering the archetype ineligible." + }, + { + "id": "one-primary-action", + "rule": "At most one button in actions is primary. If stakes >= 2 and a button is destructive, the destructive button is never primary and the non-destructive way out is placed first." + }, + { + "id": "actions-gate", + "rule": "actions, filters, form, groups, compose, and collection.trailing=button require actions_allowed, which is archetype confidence >= gate, where gate runs linearly from 0.70 at stakes 0 to 0.95 at stakes 3: gate = 0.70 + 0.25 * stakes / 3. Low-stakes toggles need 0.70; a payment needs 0.95. The floor and cap are grammar thresholds (actionGateFloor, actionGateCap) so a deployment can tighten them." + }, + { + "id": "catalog-eligibility", + "rule": "An archetype is offered only if every required block resolves to a pattern on the surface's catalogs after walking its fallback chain. Eligibility is computed once per catalog set and cached; ineligible archetypes cost nothing at query time." + }, + { + "id": "pointer-once-per-region", + "rule": "A pointer bound to a slot in one block is not offered to later blocks in the same region, except key-derived labels. Blocks claim pointers in archetype order, so a status shown in a banner is not repeated as a headline tile." + }, + { + "id": "pictures-need-a-look", + "rule": "picture, collection.layout in {cards, grid, reel}, and comparison.picture are only offered when an image_url pointer exists; the anatomy question is still asked so the answer can be traced." + }, + { + "id": "leading-all-or-none", + "rule": "Every item in a collection has the same leading kind; if the picture slot is bound for fewer than half the items, leading falls back to icon or none." + }, + { + "id": "urgency-terse", + "rule": "If urgency >= 1.5, prose is dropped unless required, headline tiles are limited to 3, and the primary action is placed in the frame's sticky slot when the catalog's page pattern supports it." + }, + { + "id": "no-empty-container", + "rule": "A block whose required slots cannot be bound is dropped; an archetype whose required block is dropped is ineligible." + }, + { + "id": "fallback-must-end", + "rule": "Every block's fallback chain entries must be abstract pattern names or pattern:variant forms such as collection:cards; the loader rejects a grammar with unknown fallback entries." + } + ], + "lint": [ + "Every archetype has at least one required or expected block.", + "Every block id used in an archetype exists in blocks.", + "Every fallback entry is an abstract pattern name or a pattern:variant form.", + "Every {placeholder} in a question names a field or slot of that block.", + "Every requires entry names a slot, a knob option, or a known capability flag." + ] +} diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/assets/pattern_definition.json b/python/a2ui_agent/src/a2ui/inference_formats/decision/assets/pattern_definition.json new file mode 100644 index 0000000000..0c23fadb9b --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/assets/pattern_definition.json @@ -0,0 +1,210 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://a2ui.org/specification/v1_0/decision/pattern_definition.json", + "title": "A2UI decision catalog pattern file", + "description": "How one component catalog draws the abstract layout patterns named by the decision archetype grammar.", + "type": "object", + "required": ["catalogIds", "version", "patterns"], + "additionalProperties": false, + "properties": { + "$schema": { "type": "string" }, + "catalogIds": { + "type": "array", + "description": "Catalog ids (the `catalogId` of each catalog.json) this file applies to.", + "minItems": 1, + "uniqueItems": true, + "items": { "type": "string", "format": "uri", "minLength": 1 } + }, + "version": { "type": "string", "minLength": 1 }, + "patterns": { + "type": "object", + "minProperties": 1, + "propertyNames": { "pattern": "^[a-z_]+$" }, + "additionalProperties": { "$ref": "#/$defs/pattern" } + } + }, + "$defs": { + "stringList": { + "type": "array", + "items": { "type": "string" } + }, + "pattern": { + "type": "object", + "required": ["slots"], + "additionalProperties": false, + "properties": { + "slots": { + "type": "array", + "items": { "type": "string", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" } + }, + "knobs": { + "type": "object", + "propertyNames": { "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, + "additionalProperties": { + "type": "array", + "minItems": 1, + "items": { "type": "string", "minLength": 1 } + } + }, + "root": { "type": "string", "minLength": 1 }, + "components": { "$ref": "#/$defs/componentList" }, + "variants": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/variant" } + }, + "fieldVariants": { + "type": "object", + "propertyNames": { "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }, + "additionalProperties": { "$ref": "#/$defs/fieldVariant" } + }, + "note": { "type": "string" } + }, + "oneOf": [ + { "required": ["root", "components"] }, + { "required": ["variants"] } + ] + }, + "variant": { + "type": "object", + "required": ["root", "components"], + "additionalProperties": false, + "properties": { + "when": { + "type": "object", + "description": "Knob name to the value or values that select this variant; a variant without `when` is the default.", + "additionalProperties": { + "oneOf": [{ "type": "string" }, { "$ref": "#/$defs/stringList" }] + } + }, + "root": { "type": "string", "minLength": 1 }, + "components": { "$ref": "#/$defs/componentList" }, + "note": { "type": "string" } + } + }, + "componentList": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#/$defs/component" } + }, + "component": { + "description": "A component template with an id, expanded once per block (or once per element inside `$repeat`).", + "allOf": [{ "$ref": "#/$defs/templateObject" }], + "required": ["id", "component"] + }, + "fieldVariant": { + "description": "An id-less component template selected by `$byInstance`; the expander assigns the id.", + "allOf": [{ "$ref": "#/$defs/templateObject" }], + "required": ["component"] + }, + "templateValue": { + "anyOf": [ + { "type": ["string", "number", "boolean", "null"] }, + { "type": "array", "items": { "$ref": "#/$defs/templateValue" } }, + { "$ref": "#/$defs/templateObject" } + ] + }, + "templateObject": { + "type": "object", + "description": "Any JSON object; keys starting with `$` are template directives with the value shapes below.", + "properties": { + "$slot": { "$ref": "#/$defs/slotDirective" }, + "$text": { "$ref": "#/$defs/textDirective" }, + "$default": { "$ref": "#/$defs/defaultDirective" }, + "$if": { "$ref": "#/$defs/ifDirective" }, + "$ifKnob": { "$ref": "#/$defs/ifKnobDirective" }, + "$ifSelf": { "$ref": "#/$defs/ifSelfDirective" }, + "$ifInstance": { "$ref": "#/$defs/ifInstanceDirective" }, + "$byType": { "$ref": "#/$defs/byTypeDirective" }, + "$byInstance": { "$ref": "#/$defs/byInstanceDirective" }, + "$repeat": { "$ref": "#/$defs/repeatDirective" }, + "$map": { "$ref": "#/$defs/mapDirective" }, + "$event": { "$ref": "#/$defs/eventDirective" }, + "$blocks": { "$ref": "#/$defs/blocksDirective" }, + "$knobValue": { "$ref": "#/$defs/knobValueDirective" }, + "$item": { "$ref": "#/$defs/itemDirective" } + }, + "patternProperties": { + "^[^$]": { "$ref": "#/$defs/templateValue" } + }, + "additionalProperties": false + }, + "slotDirective": { + "type": "string", + "minLength": 1, + "description": "Slot name (optionally `slot.field`); becomes a data binding to the bound pointer, or `$default` when unbound." + }, + "textDirective": { + "type": "string", + "description": "Literal with `{slot}` placeholders; a bound slot becomes a formatString call, `{$index1}` is the 1-based element index." + }, + "defaultDirective": { + "$ref": "#/$defs/templateValue", + "description": "Literal used when the `$slot` or `$knobValue` beside it resolves to nothing." + }, + "ifDirective": { + "type": "string", + "minLength": 1, + "description": "Slot name; the component is emitted only when that slot is bound." + }, + "ifKnobDirective": { + "type": "object", + "minProperties": 1, + "description": "Knob name to accepted values; the component is emitted only when every knob matches.", + "additionalProperties": { "$ref": "#/$defs/stringList" } + }, + "ifSelfDirective": { + "type": "object", + "description": "Value (or child id) to use when the element's author is the `self` knob (`true`) or not (`false`).", + "additionalProperties": false, + "properties": { + "true": { "type": "string" }, + "false": { "type": "string" } + } + }, + "ifInstanceDirective": { + "type": "object", + "minProperties": 1, + "description": "Instance answer name to required value; the enclosing property is emitted only when each holds.", + "additionalProperties": { "type": ["string", "boolean"] } + }, + "byTypeDirective": { + "type": "string", + "minLength": 1, + "description": "Slot name; the sibling key matching the slot's semantic type names the child id to emit." + }, + "byInstanceDirective": { + "type": "string", + "minLength": 1, + "description": "Instance answer name; selects a `fieldVariants` entry, or a sibling key matching the answer." + }, + "repeatDirective": { + "type": "string", + "minLength": 1, + "description": "Repeated slot name; `children` becomes a template child list bound to the slot's array (sibling `component` names the template)." + }, + "mapDirective": { + "type": "string", + "minLength": 1, + "description": "Knob or instance answer name; the sibling key matching its value is the literal to emit." + }, + "eventDirective": { + "type": "string", + "minLength": 1, + "description": "Event name, or a slot whose value is slugged into the event name; emits `{\"event\": {\"name\": ...}}` plus `context`." + }, + "blocksDirective": { + "const": true, + "description": "Placeholder in the page pattern's children for the block roots in archetype order." + }, + "knobValueDirective": { + "type": "string", + "minLength": 1, + "description": "`knob.property` lookup into the plan; `$default` applies when absent." + }, + "itemDirective": { + "const": true, + "description": "Inside `$repeat`, the current element's pointer, bound as the event context." + } + } +} diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/assets/patterns/basic_v1_0.json b/python/a2ui_agent/src/a2ui/inference_formats/decision/assets/patterns/basic_v1_0.json new file mode 100644 index 0000000000..1661ee0318 --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/assets/patterns/basic_v1_0.json @@ -0,0 +1,1717 @@ +{ + "$schema": "https://a2ui.org/specification/v1_0/decision/pattern_definition.json", + "catalogIds": [ + "https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json", + "https://a2ui.org/specification/v0_9/catalogs/basic/catalog.json" + ], + "version": "1", + "patterns": { + "page": { + "slots": [ + "title", + "subtitle", + "mark", + "blocks" + ], + "knobs": { + "dialog": [ + "yes", + "no" + ], + "stickyActions": [ + "yes", + "no" + ] + }, + "note": "mark is a small image beside the title: a logo or avatar that the picture block's prominence score placed at level 0.", + "variants": [ + { + "when": { + "dialog": "yes" + }, + "root": "page_card", + "components": [ + { + "id": "page_card", + "component": "Card", + "child": "page_col" + }, + { + "id": "page_col", + "component": "Column", + "children": [ + "page_head", + { + "$if": "subtitle", + "id": "page_subtitle" + }, + { + "$blocks": true + } + ] + }, + { + "id": "page_head", + "component": "Row", + "align": "center", + "children": [ + { + "$if": "mark", + "id": "page_mark" + }, + "page_title" + ] + }, + { + "id": "page_mark", + "component": "Image", + "url": { + "$slot": "mark" + }, + "variant": "icon", + "fit": "contain" + }, + { + "id": "page_title", + "component": "Text", + "text": { + "$text": "## {title}" + } + }, + { + "id": "page_subtitle", + "component": "Text", + "text": { + "$slot": "subtitle" + }, + "variant": "caption" + } + ] + }, + { + "root": "page_col", + "components": [ + { + "id": "page_col", + "component": "Column", + "children": [ + "page_head", + { + "$if": "subtitle", + "id": "page_subtitle" + }, + { + "$blocks": true + } + ] + }, + { + "id": "page_head", + "component": "Row", + "align": "center", + "children": [ + { + "$if": "mark", + "id": "page_mark" + }, + "page_title" + ] + }, + { + "id": "page_mark", + "component": "Image", + "url": { + "$slot": "mark" + }, + "variant": "icon", + "fit": "contain" + }, + { + "id": "page_title", + "component": "Text", + "text": { + "$text": "## {title}" + } + }, + { + "id": "page_subtitle", + "component": "Text", + "text": { + "$slot": "subtitle" + }, + "variant": "caption" + } + ] + } + ] + }, + "banner": { + "slots": [ + "title", + "text", + "tone" + ], + "root": "banner_card", + "components": [ + { + "id": "banner_card", + "component": "Card", + "child": "banner_row" + }, + { + "id": "banner_row", + "component": "Row", + "align": "center", + "children": [ + "banner_icon", + "banner_col" + ] + }, + { + "id": "banner_icon", + "component": "Icon", + "name": { + "$map": "tone", + "success": "check", + "warning": "info", + "danger": "error", + "neutral": "info" + } + }, + { + "id": "banner_col", + "component": "Column", + "weight": 1, + "children": [ + "banner_title", + { + "$if": "text", + "id": "banner_text" + } + ] + }, + { + "id": "banner_title", + "component": "Text", + "text": { + "$text": "**{title}**" + } + }, + { + "id": "banner_text", + "component": "Text", + "text": { + "$slot": "text" + }, + "variant": "caption" + } + ] + }, + "picture": { + "slots": [ + "picture", + "caption" + ], + "knobs": { + "framing": [ + "banner", + "portrait", + "object", + "poster" + ], + "prominence": [ + "mark", + "supporting", + "leading", + "full" + ] + }, + "variants": [ + { + "when": { + "prominence": [ + "mark" + ] + }, + "root": "picture_img", + "components": [ + { + "id": "picture_img", + "component": "Image", + "url": { + "$slot": "picture" + }, + "variant": { + "$map": "framing", + "portrait": "avatar", + "object": "icon", + "banner": "icon", + "poster": "icon" + }, + "fit": "contain", + "description": { + "$slot": "caption", + "$default": "" + } + } + ] + }, + { + "when": { + "prominence": [ + "supporting" + ] + }, + "root": "picture_img", + "components": [ + { + "id": "picture_img", + "component": "Image", + "url": { + "$slot": "picture" + }, + "variant": { + "$map": "framing", + "portrait": "avatar", + "object": "smallFeature", + "banner": "mediumFeature", + "poster": "mediumFeature" + }, + "fit": { + "$map": "framing", + "banner": "cover", + "portrait": "cover", + "object": "contain", + "poster": "contain" + }, + "description": { + "$slot": "caption", + "$default": "" + } + } + ] + }, + { + "root": "picture_col", + "components": [ + { + "id": "picture_col", + "component": "Column", + "children": [ + "picture_img", + { + "$if": "caption", + "id": "picture_caption" + } + ] + }, + { + "id": "picture_img", + "component": "Image", + "url": { + "$slot": "picture" + }, + "variant": { + "$map": "framing", + "banner": "header", + "portrait": "largeFeature", + "object": "largeFeature", + "poster": "largeFeature" + }, + "fit": { + "$map": "framing", + "banner": "cover", + "portrait": "cover", + "object": "contain", + "poster": "contain" + }, + "description": { + "$slot": "caption", + "$default": "" + } + }, + { + "id": "picture_caption", + "component": "Text", + "text": { + "$slot": "caption" + }, + "variant": "caption" + } + ] + } + ], + "note": "Basic v1 Image has no aspect-ratio control; width, height, and orientation from the payload only inform framing and the choice between header and largeFeature. A catalog with an explicit aspect ratio property would map the aspectRatio slot directly." + }, + "media": { + "slots": [ + "source", + "poster", + "title", + "duration" + ], + "root": "media_col", + "components": [ + { + "id": "media_col", + "component": "Column", + "children": [ + { + "$if": "title", + "id": "media_title" + }, + { + "$byType": "source", + "video_url": "media_video", + "audio_url": "media_audio" + }, + { + "$if": "duration", + "id": "media_duration" + } + ] + }, + { + "id": "media_title", + "component": "Text", + "text": { + "$text": "### {title}" + } + }, + { + "id": "media_video", + "component": "Video", + "url": { + "$slot": "source" + }, + "posterUrl": { + "$slot": "poster", + "$default": "" + } + }, + { + "id": "media_audio", + "component": "AudioPlayer", + "url": { + "$slot": "source" + }, + "description": { + "$slot": "title", + "$default": "" + } + }, + { + "id": "media_duration", + "component": "Text", + "text": { + "$slot": "duration" + }, + "variant": "caption" + } + ] + }, + "filters": { + "slots": [ + "query", + "categories" + ], + "root": "filters_col", + "components": [ + { + "id": "filters_col", + "component": "Column", + "children": [ + { + "$if": "query", + "id": "filters_search" + }, + { + "$if": "categories", + "id": "filters_categories" + } + ] + }, + { + "id": "filters_search", + "component": "TextField", + "label": "Search", + "value": { + "$slot": "query" + }, + "variant": "shortText" + }, + { + "id": "filters_categories", + "component": "ChoicePicker", + "label": "Filter", + "variant": "mutuallyExclusive", + "displayStyle": "chips", + "options": { + "$slot": "categories" + }, + "value": { + "$slot": "categories.selected", + "$default": [] + } + } + ], + "note": "displayStyle chips is this catalog's own enum value; the grammar slot is categories and says nothing about how they are drawn." + }, + "headline": { + "slots": [ + "items" + ], + "knobs": { + "deltas": [ + "yes", + "no" + ], + "gauge": [ + "yes", + "no" + ] + }, + "root": "headline_row", + "components": [ + { + "id": "headline_row", + "component": "Row", + "justify": "spaceBetween", + "children": { + "$repeat": "items", + "component": "headline_item" + } + }, + { + "id": "headline_item", + "component": "Card", + "weight": 1, + "child": "headline_item_col" + }, + { + "id": "headline_item_col", + "component": "Column", + "align": "center", + "children": [ + "headline_value", + "headline_label", + { + "$if": "delta", + "id": "headline_delta" + }, + { + "$ifKnob": { + "gauge": [ + "yes" + ] + }, + "$if": "max", + "id": "headline_gauge" + } + ] + }, + { + "id": "headline_value", + "component": "Text", + "text": { + "$text": "### {value}" + } + }, + { + "id": "headline_label", + "component": "Text", + "text": { + "$slot": "label" + }, + "variant": "caption" + }, + { + "id": "headline_delta", + "component": "Text", + "text": { + "$text": "{delta}" + }, + "variant": "caption" + }, + { + "id": "headline_gauge", + "component": "Text", + "text": { + "$text": "{value} of {max}" + }, + "variant": "caption" + } + ], + "note": "No gauge or progress component in basic v1, so a bounded value is written as 'value of max'. Status and boolean values are rendered as their text; a catalog with a badge or chip would map state_tone to it." + }, + "facts": { + "slots": [ + "rows" + ], + "root": "facts_card", + "components": [ + { + "id": "facts_card", + "component": "Card", + "child": "facts_list" + }, + { + "id": "facts_list", + "component": "List", + "direction": "vertical", + "children": { + "$repeat": "rows", + "component": "facts_row" + } + }, + { + "id": "facts_row", + "component": "Row", + "justify": "spaceBetween", + "children": [ + "facts_label", + "facts_value" + ] + }, + { + "id": "facts_label", + "component": "Text", + "text": { + "$slot": "label" + }, + "variant": "caption" + }, + { + "id": "facts_value", + "component": "Text", + "text": { + "$slot": "value" + } + } + ] + }, + "prose": { + "slots": [ + "heading", + "body" + ], + "knobs": { + "length": [ + "line", + "blurb", + "summary", + "article" + ] + }, + "variants": [ + { + "when": { + "length": [ + "article" + ] + }, + "root": "prose_col", + "components": [ + { + "id": "prose_col", + "component": "Column", + "children": [ + { + "$if": "heading", + "id": "prose_heading" + }, + "prose_body" + ] + }, + { + "id": "prose_heading", + "component": "Text", + "text": { + "$text": "### {heading}" + } + }, + { + "id": "prose_body", + "component": "Text", + "text": { + "$slot": "body" + } + } + ], + "note": "Basic v1 cannot truncate text or collapse it behind a Read more without losing the inline copy, so an article is set in full. A catalog with a disclosure component would show the first paragraph and expand." + }, + { + "root": "prose_col", + "components": [ + { + "id": "prose_col", + "component": "Column", + "children": [ + { + "$if": "heading", + "id": "prose_heading" + }, + "prose_body" + ] + }, + { + "id": "prose_heading", + "component": "Text", + "text": { + "$text": "### {heading}" + } + }, + { + "id": "prose_body", + "component": "Text", + "text": { + "$slot": "body" + }, + "variant": { + "$map": "length", + "line": "caption", + "blurb": "body", + "summary": "body" + } + } + ] + } + ] + }, + "collection": { + "slots": [ + "items" + ], + "knobs": { + "layout": [ + "rows", + "cards", + "reel" + ], + "leading": [ + "thumbnail", + "avatar", + "icon", + "number", + "none" + ], + "trailing": [ + "chevron", + "button", + "value", + "none" + ] + }, + "variants": [ + { + "when": { + "layout": "rows" + }, + "root": "list", + "components": [ + { + "id": "list", + "component": "List", + "direction": "vertical", + "children": { + "$repeat": "items", + "component": "item" + } + }, + { + "id": "item", + "component": "Row", + "align": "center", + "children": [ + { + "$ifKnob": { + "leading": [ + "thumbnail" + ] + }, + "id": "item_thumb" + }, + { + "$ifKnob": { + "leading": [ + "avatar" + ] + }, + "id": "item_avatar" + }, + { + "$ifKnob": { + "leading": [ + "icon" + ] + }, + "id": "item_icon" + }, + "item_col", + { + "$if": "meta", + "id": "item_meta" + }, + { + "$ifKnob": { + "trailing": [ + "button" + ] + }, + "id": "item_button" + }, + { + "$ifKnob": { + "trailing": [ + "chevron" + ] + }, + "id": "item_chevron" + } + ] + }, + { + "id": "item_thumb", + "component": "Image", + "url": { + "$slot": "picture" + }, + "variant": "smallFeature", + "fit": "cover" + }, + { + "id": "item_avatar", + "component": "Image", + "url": { + "$slot": "picture" + }, + "variant": "avatar", + "fit": "cover" + }, + { + "id": "item_icon", + "component": "Icon", + "name": { + "$slot": "icon", + "$default": "info" + } + }, + { + "id": "item_col", + "component": "Column", + "weight": 1, + "children": [ + "item_headline", + { + "$if": "supporting", + "id": "item_supporting" + }, + { + "$if": "badge", + "id": "item_badge" + } + ] + }, + { + "id": "item_headline", + "component": "Text", + "text": { + "$text": "**{headline}**" + } + }, + { + "id": "item_supporting", + "component": "Text", + "text": { + "$slot": "supporting" + }, + "variant": "caption" + }, + { + "id": "item_badge", + "component": "Text", + "text": { + "$text": "`{badge}`" + }, + "variant": "caption" + }, + { + "id": "item_meta", + "component": "Text", + "text": { + "$slot": "meta" + } + }, + { + "id": "item_button", + "component": "Button", + "child": "item_button_label", + "action": { + "$event": "item_action", + "context": { + "$item": true + } + } + }, + { + "id": "item_button_label", + "component": "Text", + "text": { + "$knobValue": "trailing.label", + "$default": "Open" + } + }, + { + "id": "item_chevron", + "component": "Icon", + "name": "arrowForward" + } + ] + }, + { + "when": { + "layout": "cards" + }, + "root": "list", + "components": [ + { + "id": "list", + "component": "List", + "direction": "vertical", + "children": { + "$repeat": "items", + "component": "item" + } + }, + { + "id": "item", + "component": "Card", + "child": "item_col" + }, + { + "id": "item_col", + "component": "Column", + "children": [ + "item_img", + "item_headline", + { + "$if": "supporting", + "id": "item_supporting" + }, + "item_footer" + ] + }, + { + "id": "item_img", + "component": "Image", + "url": { + "$slot": "picture" + }, + "variant": "largeFeature", + "fit": "cover" + }, + { + "id": "item_headline", + "component": "Text", + "text": { + "$text": "**{headline}**" + } + }, + { + "id": "item_supporting", + "component": "Text", + "text": { + "$slot": "supporting" + }, + "variant": "caption" + }, + { + "id": "item_footer", + "component": "Row", + "justify": "spaceBetween", + "children": [ + { + "$if": "meta", + "id": "item_meta" + }, + { + "$if": "rating", + "id": "item_rating" + }, + { + "$ifKnob": { + "trailing": [ + "button" + ] + }, + "id": "item_button" + } + ] + }, + { + "id": "item_meta", + "component": "Text", + "text": { + "$slot": "meta" + } + }, + { + "id": "item_rating", + "component": "Text", + "text": { + "$text": "{rating} / 5" + }, + "variant": "caption" + }, + { + "id": "item_button", + "component": "Button", + "child": "item_button_label", + "action": { + "$event": "item_action", + "context": { + "$item": true + } + } + }, + { + "id": "item_button_label", + "component": "Text", + "text": { + "$knobValue": "trailing.label", + "$default": "Open" + } + } + ] + }, + { + "when": { + "layout": "reel" + }, + "root": "reel", + "components": [ + { + "id": "reel", + "component": "List", + "direction": "horizontal", + "children": { + "$repeat": "items", + "component": "item" + } + }, + { + "id": "item", + "component": "Column", + "children": [ + "item_img", + "item_headline", + { + "$if": "meta", + "id": "item_meta" + } + ] + }, + { + "id": "item_img", + "component": "Image", + "url": { + "$slot": "picture" + }, + "variant": "mediumFeature", + "fit": "cover" + }, + { + "id": "item_headline", + "component": "Text", + "text": { + "$slot": "headline" + }, + "variant": "caption" + }, + { + "id": "item_meta", + "component": "Text", + "text": { + "$slot": "meta" + }, + "variant": "caption" + } + ] + } + ], + "note": "No grid variant: basic v1 has no intrinsic grid, so grid is never offered for this catalog (requires pattern:collection:grid)." + }, + "comparison": { + "slots": [ + "options" + ], + "root": "cmp_row", + "components": [ + { + "id": "cmp_row", + "component": "Row", + "align": "stretch", + "children": { + "$repeat": "options", + "component": "cmp_card" + } + }, + { + "id": "cmp_card", + "component": "Card", + "weight": 1, + "child": "cmp_col" + }, + { + "id": "cmp_col", + "component": "Column", + "children": [ + { + "$if": "picture", + "id": "cmp_img" + }, + "cmp_headline", + { + "$if": "highlight", + "id": "cmp_highlight" + }, + "cmp_attrs" + ] + }, + { + "id": "cmp_img", + "component": "Image", + "url": { + "$slot": "picture" + }, + "variant": "mediumFeature", + "fit": "cover" + }, + { + "id": "cmp_headline", + "component": "Text", + "text": { + "$text": "**{headline}**" + } + }, + { + "id": "cmp_highlight", + "component": "Text", + "text": { + "$text": "**{highlight}**" + } + }, + { + "id": "cmp_attrs", + "component": "List", + "direction": "vertical", + "children": { + "$repeat": "attributes", + "component": "cmp_attr" + } + }, + { + "id": "cmp_attr", + "component": "Row", + "justify": "spaceBetween", + "children": [ + "cmp_attr_label", + "cmp_attr_value" + ] + }, + { + "id": "cmp_attr_label", + "component": "Text", + "text": { + "$slot": "label" + }, + "variant": "caption" + }, + { + "id": "cmp_attr_value", + "component": "Text", + "text": { + "$slot": "value" + }, + "variant": "caption" + } + ] + }, + "steps": { + "slots": [ + "items" + ], + "root": "steps_list", + "components": [ + { + "id": "steps_list", + "component": "List", + "direction": "vertical", + "children": { + "$repeat": "items", + "component": "step" + } + }, + { + "id": "step", + "component": "Row", + "align": "start", + "children": [ + "step_marker", + "step_col" + ] + }, + { + "id": "step_marker", + "component": "Text", + "text": { + "$text": "**{$index1}.**" + } + }, + { + "id": "step_col", + "component": "Column", + "weight": 1, + "children": [ + "step_title", + { + "$if": "detail", + "id": "step_detail" + } + ] + }, + { + "id": "step_title", + "component": "Text", + "text": { + "$slot": "title" + } + }, + { + "id": "step_detail", + "component": "Text", + "text": { + "$slot": "detail" + }, + "variant": "caption" + } + ] + }, + "form": { + "slots": [ + "fields" + ], + "root": "form_col", + "components": [ + { + "id": "form_col", + "component": "Column", + "children": { + "$repeat": "fields", + "component": { + "$byInstance": "control" + } + } + } + ], + "fieldVariants": { + "shortText": { + "component": "TextField", + "label": { + "$slot": "label" + }, + "value": { + "$slot": "value" + }, + "variant": "shortText", + "checks": { + "$ifInstance": { + "required": true + }, + "value": [ + { + "condition": { + "call": "required", + "args": { + "value": { + "$slot": "value" + } + } + }, + "message": "Required" + } + ] + } + }, + "longText": { + "component": "TextField", + "label": { + "$slot": "label" + }, + "value": { + "$slot": "value" + }, + "variant": "longText" + }, + "number": { + "component": "TextField", + "label": { + "$slot": "label" + }, + "value": { + "$slot": "value" + }, + "variant": "number" + }, + "obscured": { + "component": "TextField", + "label": { + "$slot": "label" + }, + "value": { + "$slot": "value" + }, + "variant": "obscured" + }, + "toggle": { + "component": "CheckBox", + "label": { + "$slot": "label" + }, + "value": { + "$slot": "value" + } + }, + "choice": { + "component": "ChoicePicker", + "label": { + "$slot": "label" + }, + "variant": "mutuallyExclusive", + "displayStyle": "chips", + "options": { + "$slot": "options" + }, + "value": { + "$slot": "value" + } + }, + "multiChoice": { + "component": "ChoicePicker", + "label": { + "$slot": "label" + }, + "variant": "multipleSelection", + "displayStyle": "checkbox", + "options": { + "$slot": "options" + }, + "value": { + "$slot": "value" + } + }, + "range": { + "component": "Slider", + "label": { + "$slot": "label" + }, + "value": { + "$slot": "value" + }, + "min": { + "$slot": "min" + }, + "max": { + "$slot": "max" + } + }, + "date": { + "component": "DateTimeInput", + "label": { + "$slot": "label" + }, + "value": { + "$slot": "value" + }, + "enableDate": true + } + } + }, + "groups": { + "slots": [ + "groups" + ], + "root": "groups_col", + "components": [ + { + "id": "groups_col", + "component": "Column", + "children": { + "$repeat": "groups", + "component": "group" + } + }, + { + "id": "group", + "component": "Column", + "children": [ + "group_heading", + "group_card" + ] + }, + { + "id": "group_heading", + "component": "Text", + "text": { + "$text": "### {heading}" + } + }, + { + "id": "group_card", + "component": "Card", + "child": "group_list" + }, + { + "id": "group_list", + "component": "List", + "direction": "vertical", + "children": { + "$repeat": "rows", + "component": { + "$byInstance": "row_kind" + } + } + } + ], + "fieldVariants": { + "switch": { + "component": "CheckBox", + "label": { + "$slot": "label" + }, + "value": { + "$slot": "value" + } + }, + "value": { + "component": "Row", + "justify": "spaceBetween", + "children": [ + { + "component": "Text", + "text": { + "$slot": "label" + } + }, + { + "component": "Text", + "text": { + "$slot": "value" + }, + "variant": "caption" + } + ] + }, + "navigation": { + "component": "Button", + "variant": "borderless", + "child": { + "component": "Row", + "justify": "spaceBetween", + "children": [ + { + "component": "Text", + "text": { + "$slot": "label" + } + }, + { + "component": "Icon", + "name": "arrowForward" + } + ] + }, + "action": { + "$event": "open", + "context": { + "$item": true + } + } + }, + "danger": { + "component": "Button", + "variant": "borderless", + "child": { + "component": "Text", + "text": { + "$slot": "label" + } + }, + "action": { + "$event": "label", + "context": { + "$item": true + } + } + } + } + }, + "actions": { + "slots": [ + "buttons" + ], + "knobs": { + "sticky": [ + "yes", + "no" + ] + }, + "root": "actions_row", + "components": [ + { + "id": "actions_row", + "component": "Row", + "justify": "end", + "children": { + "$repeat": "buttons", + "component": "action_button", + "order": "primaryLast" + } + }, + { + "id": "action_button", + "component": "Button", + "variant": { + "$byInstance": "primary", + "true": "primary", + "false": "default" + }, + "child": "action_label", + "action": { + "$event": "label" + } + }, + { + "id": "action_label", + "component": "Text", + "text": { + "$slot": "label" + } + } + ], + "note": "Basic v1 has no destructive variant. A destructive non-primary button is rendered default; a destructive primary is downgraded to default by the one-primary-action rule when stakes >= 2." + }, + "conversation": { + "slots": [ + "messages" + ], + "knobs": { + "self": [ + "", + "none" + ] + }, + "root": "conv_list", + "components": [ + { + "id": "conv_list", + "component": "List", + "direction": "vertical", + "children": { + "$repeat": "messages", + "component": "msg" + } + }, + { + "id": "msg", + "component": "Row", + "align": "start", + "justify": { + "$ifSelf": { + "true": "end", + "false": "start" + } + }, + "children": [ + { + "$if": "avatar", + "$ifSelf": { + "false": "msg_avatar" + } + }, + "msg_card" + ] + }, + { + "id": "msg_avatar", + "component": "Image", + "url": { + "$slot": "avatar" + }, + "variant": "avatar", + "fit": "cover" + }, + { + "id": "msg_card", + "component": "Card", + "child": "msg_col" + }, + { + "id": "msg_col", + "component": "Column", + "children": [ + "msg_head", + "msg_text", + { + "$if": "attachment", + "id": "msg_attachment" + } + ] + }, + { + "id": "msg_head", + "component": "Row", + "justify": "spaceBetween", + "children": [ + "msg_author", + { + "$if": "time", + "id": "msg_time" + } + ] + }, + { + "id": "msg_author", + "component": "Text", + "text": { + "$text": "**{author}**" + }, + "variant": "caption" + }, + { + "id": "msg_time", + "component": "Text", + "text": { + "$slot": "time" + }, + "variant": "caption" + }, + { + "id": "msg_text", + "component": "Text", + "text": { + "$slot": "text" + } + }, + { + "id": "msg_attachment", + "component": "Image", + "url": { + "$slot": "attachment" + }, + "variant": "mediumFeature", + "fit": "cover" + } + ], + "note": "Basic v1 has no bubble, so each message is a Card; self messages are pushed right with Row justify end. $ifSelf compares the message author to the self knob at expansion time." + }, + "compose": { + "slots": [ + "draft", + "sendLabel" + ], + "root": "compose_row", + "components": [ + { + "id": "compose_row", + "component": "Row", + "align": "end", + "children": [ + "compose_field", + "compose_send" + ] + }, + { + "id": "compose_field", + "component": "TextField", + "label": "Message", + "value": { + "$slot": "draft" + }, + "variant": "longText", + "weight": 1 + }, + { + "id": "compose_send", + "component": "Button", + "variant": "primary", + "child": "compose_send_label", + "action": { + "$event": "send", + "context": { + "draft": { + "$slot": "draft" + } + } + } + }, + { + "id": "compose_send_label", + "component": "Text", + "text": { + "$slot": "sendLabel", + "$default": "Send" + } + } + ] + }, + "outcome": { + "slots": [ + "headline", + "detail", + "tone" + ], + "root": "outcome_col", + "components": [ + { + "id": "outcome_col", + "component": "Column", + "align": "center", + "children": [ + "outcome_icon", + "outcome_headline", + { + "$if": "detail", + "id": "outcome_detail" + } + ] + }, + { + "id": "outcome_icon", + "component": "Icon", + "name": { + "$map": "tone", + "success": "check", + "danger": "error", + "neutral": "info" + } + }, + { + "id": "outcome_headline", + "component": "Text", + "text": { + "$text": "## {headline}" + } + }, + { + "id": "outcome_detail", + "component": "Text", + "text": { + "$slot": "detail" + }, + "variant": "caption" + } + ] + } + } +} diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/backends.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/backends.py new file mode 100644 index 0000000000..e6f434511f --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/backends.py @@ -0,0 +1,1992 @@ +# 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. + +"""Inference backends for local decision-model A2UI synthesis. + +Environment variables: +- `A2UI_DECISION_BACKEND`: Default backend kind ('mock', 'local', 'jev', etc.). +- `A2UI_DECISION_URL`: Default URL for remote backends. +- `A2UI_DECISION_MODEL`: Default model identifier. +- `A2UI_DECISION_TEMPERATURE`: Temperature scaling for probability distributions. +- `A2UI_DECISION_THREADS`: Intra-op thread count for LocalCrossEncoderBackend + (defaults to CPU count). +- `A2UI_DECISION_MAX_SEQ`: Maximum sequence length for LocalCrossEncoderBackend + token truncation (defaults to 256). +""" + +from __future__ import annotations + +import asyncio +from collections.abc import Callable, Mapping, Sequence +import math +import os +import re +import time +from typing import Any, Protocol, TypeAlias, TypeVar, cast, runtime_checkable + +import httpx + +from a2ui.core import A2uiValidationError + +from .models import ( + DecisionAnswer, + DecisionBackendType, + DecisionBatch, + DecisionDistribution, + DecisionQuery, + DecisionQuestion, + DecisionTask, + DecisionWireFormat, + QuestionKind, +) + +_CAMEL_BOUNDARY_RE = re.compile(r"([a-z0-9])([A-Z])") +_TOKEN_RE = re.compile(r"[a-z0-9]+") + +# Lifetime of a cached Application Default Credentials access token. +_ADC_TOKEN_TTL_SECONDS = 1800.0 + +_DEFAULT_TYPESAFE_SYSTEMONE_URL = "https://api.typesafe.ai/v1/systemone" +_DEFAULT_VERCEL_TYPESAFE_SYSTEMONE_URL = ( + "https://ai-gateway.vercel.sh/typesafe/v1/systemone" +) + +_STEP_ZERO_LABELS: tuple[str, ...] = tuple("ABCDEFGHIJ") + +_BackendT = TypeVar("_BackendT", bound="_AsyncClosable") + +ScriptedAnswerSpec: TypeAlias = ( + DecisionAnswer | float | int | str | tuple[str, float] | Mapping[str, float] +) + + +def _safe_nonneg_float(value: Any) -> float: + """Converts `value` to a finite non-negative float, returning 0.0 on invalid input.""" + try: + parsed = float(value) + except (ValueError, TypeError): + return 0.0 + if not math.isfinite(parsed) or parsed <= 0.0: + return 0.0 + return parsed + + +def _normalize_probabilities( + raw_probs: Mapping[str, Any], + candidates: tuple[str, ...], +) -> dict[str, float]: + """Filters candidate probabilities and normalizes weights when sum > 1.0.""" + if not candidates: + return {} + filtered = {c: _safe_nonneg_float(raw_probs.get(c, 0.0)) for c in candidates} + total = sum(filtered.values()) + if total <= 0.0: + return {c: 0.0 for c in candidates} + raw_total = sum(_safe_nonneg_float(v) for v in raw_probs.values()) + if total <= 1.0 and raw_total <= 1.0 + 1e-6: + return filtered + return {c: val / total for c, val in filtered.items()} + + +def _fill_missing_logits( + logits: Mapping[str, float], candidates: Sequence[str] +) -> dict[str, float]: + """Populates missing candidate logits with a low floor value.""" + present = [logits[c] for c in candidates if c in logits] + floor = (min(present) - 10.0) if present else -20.0 + return {c: logits.get(c, floor) for c in candidates} + + +def _softmax_with_margin( + logits: Mapping[str, float], + candidates: Sequence[str], + *, + temperature: float = 1.0, +) -> tuple[dict[str, float], float | None]: + """Computes temperature-scaled softmax probabilities and top-2 logit margin.""" + if not candidates: + return {}, 0.0 + full_logits = _fill_missing_logits(logits, candidates) + z_sorted = sorted(full_logits.values(), reverse=True) + margin = (z_sorted[0] - z_sorted[1]) if len(z_sorted) >= 2 else float("inf") + z_max = z_sorted[0] + exp_scores = { + c: math.exp((z - z_max) / temperature) for c, z in full_logits.items() + } + total = sum(exp_scores.values()) + if total <= 0.0: + return {c: 0.0 for c in candidates}, margin + probs = {c: val / total for c, val in exp_scores.items()} + return probs, margin + + +def _child_slot_clause(query: DecisionQuery, *, full_template: str) -> str | None: + """Formats the parent/slot clause when `query.task` is `child_component`.""" + if query.task != "child_component": + return None + parent = query.context.get("parent_description") or query.context.get("parent") + slot = query.context.get("slot_description") or query.context.get("slot") + if parent and slot: + return full_template.format(parent=parent, slot=slot) + return f"Slot: {slot}" if slot else None + + +def _pointers_summary( + context: Mapping[str, Any], label: str, *, max_pointers: int | None = 12 +) -> str | None: + """Formats the available payload pointers clause if present in `context`.""" + pointers = context.get("pointers") + if isinstance(pointers, (list, tuple)) and pointers: + pts = list(pointers) + if max_pointers is not None and max_pointers > 0 and len(pts) > max_pointers: + pts = pts[:max_pointers] + return f"{label}: {', '.join(str(p) for p in pts)}" + return None + + +def _candidate_description( + context: Mapping[str, Any], candidate: str, *, max_chars: int = 240 +) -> str | None: + """Returns the description string for `candidate` from `context`, if any.""" + cand_descs = context.get("candidate_descriptions") + if isinstance(cand_descs, Mapping) and cand_descs.get(candidate): + desc = str(cand_descs[candidate]) + if max_chars > 0 and len(desc) > max_chars: + desc = desc[:max_chars] + return desc + return None + + +def _format_query_passage_pairs( + query: DecisionQuery, + *, + max_summary_pointers: int | None = 12, + max_option_chars: int = 240, +) -> tuple[str, list[str]]: + """Formats DecisionQuery into (query_text, passage_texts) for cross-encoder scoring.""" + intent = query.context.get("intent") + intent_clause = ( + f"User intent: {intent}" + if isinstance(intent, str) and intent and intent != query.prompt + else None + ) + slot_clause = _child_slot_clause( + query, + full_template="Selecting child component for {parent}, slot {slot}", + ) + ptr_clause = _pointers_summary( + query.context, "Available data fields", max_pointers=max_summary_pointers + ) + query_parts = [ + p for p in (intent_clause, query.prompt, slot_clause, ptr_clause) if p + ] + passage_texts = [ + f"{c}: {desc}" + if ( + desc := _candidate_description(query.context, c, max_chars=max_option_chars) + ) + else ("none: None of the above" if c == "none" else c) + for c in query.candidates + ] + return ". ".join(query_parts), passage_texts + + +def _validate_step_zero_candidates(candidates: Sequence[str]) -> None: + """Raises `A2uiValidationError` when `candidates` exceeds the A-J label cap.""" + if len(candidates) > len(_STEP_ZERO_LABELS): + raise A2uiValidationError( + "StepZeroLogprobBackend supports at most" + f" {len(_STEP_ZERO_LABELS)} options (A-J), got {len(candidates)}." + ) + + +def _format_step_zero_prompt(query: DecisionQuery, *, shared_prefix: str = "") -> str: + """Formats a structured DecisionQuery into a single-char (A-J) step-0 prompt.""" + _validate_step_zero_candidates(query.candidates) + labeled = [ + f"{_STEP_ZERO_LABELS[i]}: {cand}" for i, cand in enumerate(query.candidates) + ] + lines: list[str] = [] + if shared_prefix: + lines.append(shared_prefix) + lines.append(f"Task: {query.task}") + lines.append(f"Candidates: [{', '.join(labeled)}]") + if query.context: + lines.append(f"Context: {query.context}") + lines.append(f"Intent: {query.prompt}") + lines.append("Selection:") + return "\n".join(lines) + + +def _match_step_zero_logprobs( + candidates: Sequence[str], top_logprobs: Mapping[str, float] +) -> dict[str, float]: + """Maps single-character label (`A`-`J`) or candidate token logprobs to option ids.""" + matched: dict[str, float] = {} + for idx, cand in enumerate(candidates): + label = _STEP_ZERO_LABELS[idx] + if label in top_logprobs: + matched[cand] = top_logprobs[label] + elif cand in top_logprobs: + matched[cand] = top_logprobs[cand] + elif cand.strip() in top_logprobs: + matched[cand] = top_logprobs[cand.strip()] + return matched + + +def _extract_http_error_detail(response: httpx.Response) -> str | None: + """Extracts a human-readable error message from a JSON error response, if any.""" + try: + body = response.json() + except Exception: + return None + if not isinstance(body, Mapping): + return None + for key in ("error", "detail"): + val = body.get(key) + if isinstance(val, Mapping) and val.get("message"): + return str(val["message"]) + if isinstance(val, str) and val: + return val + return None + + +async def _post_json( + endpoint_url: str, + payload: Mapping[str, Any], + *, + client: httpx.AsyncClient, + timeout_seconds: float, + headers: Mapping[str, str] | None = None, +) -> dict[str, Any]: + """Sends an HTTP POST with JSON payload and returns the decoded JSON object.""" + hdrs = dict(headers) if headers else None + response = await client.post( + endpoint_url, json=payload, headers=hdrs, timeout=timeout_seconds + ) + if response.is_error: + detail = _extract_http_error_detail(response) + try: + response.raise_for_status() + except httpx.HTTPStatusError as err: + if detail: + raise httpx.HTTPStatusError( + f"{err}: {detail}", + request=err.request, + response=err.response, + ) from err + raise + return cast(dict[str, Any], response.json()) + + +def _extract_top_logprobs(data: Mapping[str, Any]) -> dict[str, float]: + """Extracts token-to-logprob mappings from an OpenAI-compatible response.""" + choices = data.get("choices") + if not isinstance(choices, list) or not choices: + return {} + logprobs_obj = choices[0].get("logprobs") + if not isinstance(logprobs_obj, Mapping): + return {} + + result: dict[str, float] = {} + content_list = logprobs_obj.get("content") + if isinstance(content_list, list) and content_list: + first_pos = content_list[0] + if isinstance(first_pos, Mapping): + chat_top = first_pos.get("top_logprobs") + if isinstance(chat_top, list): + for entry in chat_top: + if ( + isinstance(entry, Mapping) + and "token" in entry + and "logprob" in entry + ): + lp = float(entry["logprob"]) + token_str = str(entry["token"]) + result[token_str] = lp + stripped = token_str.strip() + if stripped and ( + stripped not in result or lp > result[stripped] + ): + result[stripped] = lp + return result + + top_list = logprobs_obj.get("top_logprobs") + if not isinstance(top_list, list) or not top_list: + return {} + first_step = top_list[0] + if not isinstance(first_step, Mapping): + return {} + + for token, logprob in first_step.items(): + lp = float(logprob) + token_str = str(token) + result[token_str] = lp + stripped = token_str.strip() + if stripped and (stripped not in result or lp > result[stripped]): + result[stripped] = lp + return result + + +def _tokenize(text: str) -> set[str]: + """Splits camelCase, PascalCase, and punctuation into lowercase tokens.""" + expanded = _CAMEL_BOUNDARY_RE.sub(r"\1 \2", text) + return set(_TOKEN_RE.findall(expanded.lower())) + + +def _extract_context_tokens(context: Mapping[str, Any]) -> set[str]: + """Extracts searchable lowercase tokens from a query context dictionary.""" + tokens: set[str] = set() + for key, value in context.items(): + tokens.update(_tokenize(str(key))) + if isinstance(value, str): + tokens.update(_tokenize(value)) + elif isinstance(value, (list, tuple, set)): + for item in value: + tokens.update(_tokenize(str(item))) + elif isinstance(value, Mapping): + for sub_k, sub_v in value.items(): + tokens.update(_tokenize(str(sub_k))) + tokens.update(_tokenize(str(sub_v))) + return tokens + + +def _score_candidate( + candidate: str, + prompt_lower: str, + prompt_tokens: set[str], + context_tokens: set[str], +) -> float: + """Computes a deterministic relevance score for a candidate.""" + cand_lower = candidate.lower() + cand_tokens = _tokenize(candidate) + score = 0.0 + if cand_lower and cand_lower in prompt_lower: + score += 4.0 + for tok in cand_tokens: + if tok in prompt_tokens: + score += 2.0 + elif len(tok) >= 4 and any( + pt.startswith(tok) or tok.startswith(pt) + for pt in prompt_tokens + if len(pt) >= 4 + ): + score += 1.5 + if tok in context_tokens: + score += 1.0 + return score + + +@runtime_checkable +class DecisionBackend(Protocol): + """Protocol for local decision-model inference backends. + + Implementations that only score one query at a time should subclass + `PredictOnlyBackend`, which supplies `answer`, `aclose`, + `aclose_current_loop`, and the context-manager methods; objects that + predate `answer` can be adapted with `ensure_batch_backend`. + """ + + async def predict(self, query: DecisionQuery) -> DecisionDistribution: + """Predicts a probability distribution over query candidates.""" + ... + + async def answer(self, batch: DecisionBatch) -> tuple[DecisionAnswer, ...]: + """Answers every question in `batch`, in order.""" + ... + + async def aclose(self) -> None: + """Releases resources owned by this backend.""" + ... + + async def aclose_current_loop(self) -> None: + """Releases resources bound to the running event loop only. + + `DecisionSynthesizer.synthesize_sync` calls this before its temporary + loop closes; backends with no loop-scoped state implement it as a + no-op. + """ + ... + + async def __aenter__(self) -> DecisionBackend: + ... + + async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None: + ... + + +def _question_query( + question: DecisionQuestion, shared_context: Mapping[str, Any] +) -> DecisionQuery: + """Builds the `DecisionQuery` a predict-only backend scores for `question`. + + The query context carries the batch's shared context, the question's own + context, ``question_id`` and ``question_kind``, and candidate descriptions + from `option_texts` (or the ``yes`` and ``no`` criteria texts in the + question context for boolean questions). + """ + context: dict[str, Any] = { + **shared_context, + **question.context, + "question_id": question.id, + "question_kind": str(question.kind), + } + descriptions: dict[str, str] = {} + if question.option_texts: + descriptions = dict(zip(question.options, question.option_texts)) + elif question.kind is QuestionKind.BOOLEAN: + descriptions = { + label: str(question.context[label]) + for label in ("yes", "no") + if label in question.context + } + if descriptions: + context["candidate_descriptions"] = descriptions + return DecisionQuery( + task=question.task, + prompt=question.prompt, + candidates=question.candidates(), + context=context, + ) + + +def _boolean_answer( + question: DecisionQuestion, dist: DecisionDistribution +) -> DecisionAnswer: + """Normalizes a yes/no distribution into ``{"yes": p, "no": 1 - p}``.""" + yes = dist.probabilities.get("yes", 0.0) + total = yes + dist.probabilities.get("no", 0.0) + p_yes = yes / total if total > 0.0 else 0.0 + return DecisionAnswer( + question_id=question.id, + distribution=DecisionDistribution( + probabilities={"yes": p_yes, "no": 1.0 - p_yes}, + calibrated=dist.calibrated, + top_logit_margin=dist.top_logit_margin, + ), + ) + + +def _score_answer( + question: DecisionQuestion, dist: DecisionDistribution +) -> DecisionAnswer: + """Normalizes a level distribution and computes its expected level index.""" + weights = [ + max(dist.probabilities.get(level, 0.0), 0.0) for level in question.options + ] + total = sum(weights) + if total <= 0.0: + return DecisionAnswer(question_id=question.id, distribution=dist) + probs = {level: w / total for level, w in zip(question.options, weights)} + expected = sum(p * idx for idx, p in enumerate(probs.values())) + return DecisionAnswer( + question_id=question.id, + distribution=DecisionDistribution( + probabilities=probs, + calibrated=dist.calibrated, + top_logit_margin=dist.top_logit_margin, + ), + expected=expected, + ) + + +def answer_from_distribution( + question: DecisionQuestion, dist: DecisionDistribution +) -> DecisionAnswer: + """Converts a candidate distribution into the `DecisionAnswer` for `question`. + + `CHOICE` answers keep the distribution as returned (over the options plus + ``"none"`` when `allow_none`); `BOOLEAN` answers are normalized to + ``{"yes": p, "no": 1 - p}``; `SCORE` answers are normalized over the + levels and carry ``expected = sum(p_i * i)``. + """ + if question.kind is QuestionKind.BOOLEAN: + return _boolean_answer(question, dist) + if question.kind is QuestionKind.SCORE: + return _score_answer(question, dist) + return DecisionAnswer(question_id=question.id, distribution=dist) + + +class _AsyncClosable: + """Mixin giving a backend `aclose()` and `async with` support. + + Backends that own no resources inherit the no-op `aclose`; backends that + hold an HTTP client override it. + """ + + async def aclose(self) -> None: + """Releases resources owned by this backend. No-op by default.""" + + async def aclose_current_loop(self) -> None: + """Closes resources owned by the currently running event loop, if any.""" + + async def __aenter__(self: _BackendT) -> _BackendT: + return self + + async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None: + await self.aclose() + + +class PredictOnlyBackend(_AsyncClosable): + """Base class for backends that score one `DecisionQuery` at a time. + + Subclasses implement `predict`; this class supplies `answer` by fanning a + batch out through `predict` with `asyncio.gather`, so backends that + coalesce concurrent requests batch naturally. `CHOICE` questions predict + over the options (plus ``"none"`` when `allow_none`), `BOOLEAN` questions + over ``("yes", "no")``, and `SCORE` questions over the level labels with + ``expected = sum(p_i * i)``. + """ + + async def predict(self, query: DecisionQuery) -> DecisionDistribution: + """Predicts a probability distribution over `query.candidates`.""" + raise NotImplementedError + + async def answer(self, batch: DecisionBatch) -> tuple[DecisionAnswer, ...]: + """Answers every question in `batch` through `predict`, in order.""" + queries = [_question_query(q, batch.shared_context) for q in batch.questions] + distributions = await asyncio.gather(*(self.predict(q) for q in queries)) + return tuple( + answer_from_distribution(question, dist) + for question, dist in zip(batch.questions, distributions) + ) + + +class _PredictOnlyAdapter(PredictOnlyBackend): + """Wraps an object that has `predict` but not the rest of `DecisionBackend`.""" + + def __init__(self, inner: Any) -> None: + self.inner = inner + + async def predict(self, query: DecisionQuery) -> DecisionDistribution: + return cast(DecisionDistribution, await self.inner.predict(query)) + + async def aclose(self) -> None: + close = getattr(self.inner, "aclose", None) + if callable(close): + await close() + + +def ensure_batch_backend(backend: Any) -> DecisionBackend: + """Returns `backend` as a full `DecisionBackend`, adapting predict-only objects. + + Objects that already provide `answer` and `aclose_current_loop` are + returned unchanged. Anything else with an async `predict` is wrapped in an + adapter that supplies the rest of the protocol. + + Raises: + TypeError: If `backend` has no callable `predict`. + """ + if not callable(getattr(backend, "predict", None)): + raise TypeError( + "A decision backend must provide an async predict(query) method;" + f" got {type(backend).__name__}." + ) + if callable(getattr(backend, "answer", None)) and callable( + getattr(backend, "aclose_current_loop", None) + ): + return cast(DecisionBackend, backend) + return _PredictOnlyAdapter(backend) + + +class _HttpClientOwner(_AsyncClosable): + """Mixin that lazily owns an `httpx.AsyncClient` per active event loop. + + An `httpx.AsyncClient` opens connections on the loop that first uses it, + so a client created on one loop fails when used from another (for + example when `DecisionSynthesizer.synthesize_sync` runs synthesis on a + helper thread). Owned clients are keyed by their `AbstractEventLoop` so + concurrent loops do not overwrite each other's client, and temporary + loops can close their own client via `aclose_current_loop()`. + """ + + _client: httpx.AsyncClient | None + _owned_clients: dict[asyncio.AbstractEventLoop, httpx.AsyncClient] + _timeout_seconds: float + + def _init_http_client( + self, client: httpx.AsyncClient | None, timeout_seconds: float + ) -> None: + self._client = client + self._owned_clients = {} + self._timeout_seconds = timeout_seconds + + @property + def _owned_client(self) -> httpx.AsyncClient | None: + """Returns the client owned by the current loop, or the most recent one.""" + if not self._owned_clients: + return None + try: + loop = asyncio.get_running_loop() + except RuntimeError: + return next(reversed(self._owned_clients.values())) + return self._owned_clients.get(loop) + + def _sweep_closed_loops(self) -> None: + """Removes entries whose event loop has already been closed.""" + closed = [lp for lp in self._owned_clients if lp.is_closed()] + for lp in closed: + self._owned_clients.pop(lp, None) + + def _get_client(self) -> httpx.AsyncClient: + """Returns the caller-supplied client or a loop-local owned one.""" + if self._client is not None: + return self._client + self._sweep_closed_loops() + loop = asyncio.get_running_loop() + client = self._owned_clients.get(loop) + if client is None or client.is_closed: + client = httpx.AsyncClient(timeout=self._timeout_seconds) + self._owned_clients[loop] = client + return client + + async def aclose_current_loop(self) -> None: + """Closes and removes the client owned by the currently running event loop.""" + self._sweep_closed_loops() + loop = asyncio.get_running_loop() + client = self._owned_clients.pop(loop, None) + if client is not None and not client.is_closed: + await client.aclose() + + async def aclose(self) -> None: + """Closes all internally owned `httpx.AsyncClient` instances.""" + if not self._owned_clients: + return + current_loop = asyncio.get_running_loop() + items = list(self._owned_clients.items()) + self._owned_clients.clear() + for loop, client in items: + if client.is_closed: + continue + if loop is current_loop or loop.is_closed(): + await client.aclose() + else: + try: + asyncio.run_coroutine_threadsafe(client.aclose(), loop) + except RuntimeError: + pass + + +def _get_adc_token_sync() -> str | None: + """Attempts to retrieve an ADC access token synchronously in a worker thread.""" + try: + import google.auth + import google.auth.transport.requests + + creds: Any + creds, _ = google.auth.default( + scopes=["https://www.googleapis.com/auth/cloud-platform"] + ) + creds.refresh(google.auth.transport.requests.Request()) + if creds.token: + return str(creds.token) + except Exception: + pass + + try: + import subprocess + + res = subprocess.run( + ["gcloud", "auth", "print-access-token"], + capture_output=True, + text=True, + timeout=5.0, + check=False, + ) + if res.returncode == 0 and res.stdout.strip(): + return res.stdout.strip() + except Exception: + pass + + return None + + +def _build_systemone_request(query: DecisionQuery, model: str) -> dict[str, Any]: + """Builds a structured /v1/systemone choice request envelope.""" + criteria = { + c: ( + _candidate_description(query.context, c) + or f"Candidate component or template: {c}" + ) + for c in query.candidates + } + slot_clause = _child_slot_clause( + query, full_template="Parent container: {parent}. Slot: {slot}" + ) + ptr_clause = _pointers_summary(query.context, "Payload data fields") + state_parts = [ + p for p in (f"User intent: {query.prompt}", slot_clause, ptr_clause) if p + ] + return { + "model": model, + "state": ". ".join(state_parts), + "questions": { + "q": { + "type": "choice", + "instructions": ( + "Evaluate which candidate best satisfies the user intent and" + " UI structure." + ), + "criteria": criteria, + } + }, + } + + +def _probability_margin(probabilities: Mapping[str, float]) -> float: + """Computes log-ratio margin between the top two probabilities.""" + sorted_probs = sorted(probabilities.values(), reverse=True) + if len(sorted_probs) < 2: + return float("inf") if sorted_probs and sorted_probs[0] > 0.0 else 0.0 + p0, p1 = sorted_probs[0], sorted_probs[1] + if p0 <= 0.0: + return 0.0 + return float("inf") if p1 <= 0.0 else math.log(p0 / p1) + + +def _parse_systemone_response( + data: Mapping[str, Any], candidates: tuple[str, ...] +) -> tuple[dict[str, float], bool, float | None]: + """Extracts probabilities and logit margin from /v1/systemone response.""" + answers = data.get("answers") + if not isinstance(answers, Mapping) or not answers: + return {c: 0.0 for c in candidates}, True, 0.0 + + first_val = answers.get("q") or next(iter(answers.values()), None) + q_data = first_val if isinstance(first_val, Mapping) else {} + raw_probs = q_data.get("probabilities") + probs_map = raw_probs if isinstance(raw_probs, Mapping) else {} + probabilities = _normalize_probabilities(probs_map, candidates) + calibrated = "confidence" in q_data or bool(data.get("calibrated", True)) + return probabilities, calibrated, _probability_margin(probabilities) + + +def _serialize_native_question(question: DecisionQuestion) -> dict[str, Any]: + """Serializes one `DecisionQuestion` into a native Jev batch request item.""" + entry: dict[str, Any] = { + "id": question.id, + "kind": question.kind.value, + "task": str(getattr(question.task, "value", question.task)), + "prompt": question.prompt, + "candidates": list(question.candidates()), + } + if question.options: + entry["options"] = list(question.options) + if question.option_texts: + entry["option_texts"] = list(question.option_texts) + if question.context: + entry["context"] = dict(question.context) + if question.kind is QuestionKind.CHOICE: + entry["allow_none"] = question.allow_none + return entry + + +def _extract_native_answer_entry( + raw_answers: Any, question_id: str, index: int +) -> Mapping[str, Any]: + """Finds the response object for `question_id` (or `index`) from `raw_answers`.""" + if isinstance(raw_answers, Mapping): + item = raw_answers.get(question_id) + return item if isinstance(item, Mapping) else {} + if not isinstance(raw_answers, list): + return {} + for elem in raw_answers: + if ( + isinstance(elem, Mapping) + and elem.get("id", elem.get("question_id")) == question_id + ): + return elem + indexed = raw_answers[index] if index < len(raw_answers) else None + return indexed if isinstance(indexed, Mapping) else {} + + +def _parse_native_question_answer( + question: DecisionQuestion, + entry: Mapping[str, Any], + envelope: Mapping[str, Any], +) -> DecisionAnswer: + """Builds a `DecisionAnswer` for `question` from a native Jev answer entry.""" + raw_probs = entry.get("probabilities") + if not isinstance(raw_probs, Mapping) and "yes" in entry: + p_yes = _safe_nonneg_float(entry["yes"]) + raw_probs = {"yes": p_yes, "no": max(0.0, 1.0 - p_yes)} + probs_map = raw_probs if isinstance(raw_probs, Mapping) else {} + candidates = question.candidates() + probabilities = _normalize_probabilities(probs_map, candidates) + calibrated = bool(entry.get("calibrated", envelope.get("calibrated", False))) + raw_margin = entry.get("top_logit_margin", envelope.get("top_logit_margin")) + top_logit_margin = float(raw_margin) if raw_margin is not None else None + dist = DecisionDistribution( + probabilities=probabilities, + calibrated=calibrated, + top_logit_margin=top_logit_margin, + ) + answer = answer_from_distribution(question, dist) + if question.kind is QuestionKind.SCORE and entry.get("expected") is not None: + return DecisionAnswer( + question_id=question.id, + distribution=answer.distribution, + expected=float(entry["expected"]), + ) + return answer + + +def _build_systemone_state(shared_context: Mapping[str, Any]) -> str: + """Formats `shared_context` into a non-empty `/v1/systemone` state string.""" + intent = shared_context.get("intent") + intent_part = f"User intent: {intent}" if intent else None + ptr_part = _pointers_summary(shared_context, "Payload data fields") + parts = [p for p in (intent_part, ptr_part) if p] + if not parts and shared_context: + parts = [f"{k}: {v}" for k, v in shared_context.items()] + return ". ".join(parts) if parts else "(no context)" + + +def _serialize_systemone_choice_criteria( + question: DecisionQuestion, +) -> dict[str, str]: + """Builds the candidate->description map for a `/v1/systemone` choice question.""" + desc_map: dict[str, str] = {} + if question.option_texts: + desc_map.update( + (opt, str(txt)) + for opt, txt in zip(question.options, question.option_texts) + if txt + ) + cand_descs = question.context.get("candidate_descriptions") + if isinstance(cand_descs, Mapping): + desc_map.update((str(k), str(v)) for k, v in cand_descs.items() if v) + return { + c: ( + desc_map.get(c) + or ("None of the above" if c == "none" else f"Candidate option: {c}") + ) + for c in question.candidates() + } + + +def _serialize_systemone_question(question: DecisionQuestion) -> dict[str, Any]: + """Serializes one `DecisionQuestion` into a `/v1/systemone` question spec.""" + if question.kind is QuestionKind.BOOLEAN: + spec: dict[str, Any] = { + "type": "noul", + "instructions": question.prompt, + } + criteria = { + target: str(question.context[src]) + for src, target in (("yes", "true"), ("no", "false")) + if question.context.get(src) + } + if criteria: + spec["criteria"] = criteria + return spec + if question.kind is QuestionKind.SCORE: + levels = ( + [ + f"{lvl}: {txt}" if txt else str(lvl) + for lvl, txt in zip(question.options, question.option_texts) + ] + if question.option_texts + and len(question.option_texts) == len(question.options) + else [str(lvl) for lvl in question.options] + ) + return { + "type": "score", + "instructions": question.prompt, + "criteria": levels, + } + return { + "type": "choice", + "instructions": question.prompt, + "criteria": _serialize_systemone_choice_criteria(question), + } + + +def _parse_systemone_boolean_probs(entry: Mapping[str, Any]) -> dict[str, float]: + """Extracts `{"yes": p, "no": 1 - p}` from a `/v1/systemone` noul/boolean answer.""" + for key in ("noul", "probability", "yes"): + if key in entry: + p_yes = min(1.0, _safe_nonneg_float(entry[key])) + return {"yes": p_yes, "no": max(0.0, 1.0 - p_yes)} + raw_probs = entry.get("probabilities") + if isinstance(raw_probs, Mapping): + mapped = { + "yes": raw_probs.get("yes", raw_probs.get("true", 0.0)), + "no": raw_probs.get("no", raw_probs.get("false", 0.0)), + } + return _normalize_probabilities(mapped, ("yes", "no")) + return {"yes": 0.0, "no": 0.0} + + +def _parse_systemone_score_probs( + question: DecisionQuestion, entry: Mapping[str, Any] +) -> dict[str, float]: + """Extracts level probabilities from a `/v1/systemone` score answer.""" + raw_probs = entry.get("probabilities") + mapped: dict[str, Any] = {} + if isinstance(raw_probs, Mapping): + for idx, level in enumerate(question.options): + if level in raw_probs: + mapped[level] = raw_probs[level] + elif str(idx) in raw_probs: + mapped[level] = raw_probs[str(idx)] + elif idx in raw_probs: + mapped[level] = raw_probs[idx] + elif isinstance(raw_probs, Sequence) and not isinstance(raw_probs, (str, bytes)): + for idx, level in enumerate(question.options): + if idx < len(raw_probs): + mapped[level] = raw_probs[idx] + return _normalize_probabilities(mapped, question.options) + + +def _parse_systemone_question_answer( + question: DecisionQuestion, + entry: Mapping[str, Any], + envelope: Mapping[str, Any], +) -> DecisionAnswer: + """Builds a `DecisionAnswer` for `question` from a `/v1/systemone` answer entry.""" + if question.kind is QuestionKind.BOOLEAN: + probabilities = _parse_systemone_boolean_probs(entry) + elif question.kind is QuestionKind.SCORE: + probabilities = _parse_systemone_score_probs(question, entry) + else: + raw_probs = entry.get("probabilities") + probs_map = raw_probs if isinstance(raw_probs, Mapping) else {} + probabilities = _normalize_probabilities(probs_map, question.candidates()) + + calibrated = ( + "confidence" in entry + or "noul" in entry + or bool(envelope.get("calibrated", True)) + ) + dist = DecisionDistribution( + probabilities=probabilities, + calibrated=calibrated, + top_logit_margin=_probability_margin(probabilities), + ) + answer = answer_from_distribution(question, dist) + raw_score = entry.get("score", entry.get("expected")) + if question.kind is QuestionKind.SCORE and raw_score is not None: + if sum(answer.distribution.probabilities.values()) <= 0.0: + return DecisionAnswer( + question_id=question.id, + distribution=answer.distribution, + expected=float(raw_score), + ) + return answer + + +def _single_candidate_answer(question: DecisionQuestion) -> DecisionAnswer: + """Returns a deterministic `DecisionAnswer` for a `< 2` candidate choice.""" + cands = question.candidates() + probs = {cands[0]: 1.0} if cands else {} + return DecisionAnswer( + question_id=question.id, + distribution=DecisionDistribution( + probabilities=probs, + calibrated=True, + top_logit_margin=float("inf") if probs else 0.0, + ), + ) + + +class JevHttpBackend(PredictOnlyBackend, _HttpClientOwner): + """HTTP backend for local Jev /predict or /v1/systemone decision endpoints. + + Supports `async with` to close the owned HTTP client on exit. ADC access + tokens (``auth="adc"``) are cached per instance for 30 minutes. + """ + + def __init__( + self, + endpoint_url: str, + *, + wire_format: DecisionWireFormat | str = DecisionWireFormat.AUTO, + model: str = "default", + auth: str | Callable[[], str | Any] | None = None, + headers: Mapping[str, str] | None = None, + client: httpx.AsyncClient | None = None, + timeout_seconds: float = 5.0, + ) -> None: + self._endpoint_url = endpoint_url + self._wire_format = str(getattr(wire_format, "value", wire_format)) + if "ai-gateway.vercel.sh/typesafe" in endpoint_url.lower() and model in ( + "default", + "jev-latest", + ): + model = "jev" + self._model = model + self._auth = auth + self._headers = dict(headers) if headers else None + self._init_http_client(client, timeout_seconds) + self._adc_token: str | None = None + self._adc_expires_at: float = 0.0 + self._adc_lock = asyncio.Lock() + + @property + def endpoint_url(self) -> str: + """The HTTP endpoint URL queried by this backend.""" + return self._endpoint_url + + @property + def model(self) -> str: + """The decision model identifier sent on `/v1/systemone` requests.""" + return self._model + + def _is_systemone(self) -> bool: + """Returns whether this backend uses the /v1/systemone wire format.""" + return self._wire_format == "systemone" or ( + self._wire_format == "auto" + and self._endpoint_url.rstrip("/").endswith("/v1/systemone") + ) + + async def _resolve_adc_token(self) -> str | None: + """Returns this instance's cached ADC token, refreshing it when expired.""" + now = time.time() + if self._adc_token and now < self._adc_expires_at: + return self._adc_token + + async with self._adc_lock: + now = time.time() + if self._adc_token and now < self._adc_expires_at: + return self._adc_token + token = await asyncio.to_thread(_get_adc_token_sync) + if token: + self._adc_token = token + self._adc_expires_at = now + _ADC_TOKEN_TTL_SECONDS + return token + return None + + async def _resolve_auth_token(self) -> str | None: + """Resolves bearer token string from auth argument or environment.""" + auth_target = self._auth + if auth_target is None: + import os + + auth_target = ( + os.environ.get("A2UI_DECISION_TOKEN") + or os.environ.get("A2UI_DECISION_AUTH") + or os.environ.get("JEV_API_KEY") + or os.environ.get("TYPESAFE_API_KEY") + ) + if not auth_target: + return None + + if auth_target == "adc": + return await self._resolve_adc_token() + if callable(auth_target): + res = auth_target() + if asyncio.iscoroutine(res): + res = await res + return str(res) if res else None + token_str = str(auth_target).strip() + return token_str if token_str else None + + async def _build_headers(self) -> dict[str, str]: + """Constructs headers including Authorization Bearer token if configured.""" + headers = dict(self._headers or {}) + token = await self._resolve_auth_token() + if token and "Authorization" not in headers: + headers["Authorization"] = f"Bearer {token}" + return headers + + async def predict(self, query: DecisionQuery) -> DecisionDistribution: + """Queries the decision endpoint and normalizes candidate probabilities.""" + if not query.candidates: + return DecisionDistribution( + probabilities={}, + calibrated=True, + top_logit_margin=0.0, + ) + + headers = await self._build_headers() + is_systemone = self._is_systemone() + + if is_systemone: + payload = _build_systemone_request(query, self._model) + else: + payload = { + "task": query.task, + "prompt": query.prompt, + "candidates": list(query.candidates), + "context": query.context, + } + + data = await _post_json( + self._endpoint_url, + payload, + client=self._get_client(), + timeout_seconds=self._timeout_seconds, + headers=headers, + ) + + if is_systemone or "answers" in data: + probs, calibrated, margin = _parse_systemone_response( + data, query.candidates + ) + return DecisionDistribution( + probabilities=probs, + calibrated=calibrated, + top_logit_margin=margin, + ) + + raw_probs = data.get("probabilities") + probs_map = raw_probs if isinstance(raw_probs, Mapping) else {} + probabilities = _normalize_probabilities(probs_map, query.candidates) + calibrated = bool(data.get("calibrated", False)) + raw_margin = data.get("top_logit_margin") + top_logit_margin = float(raw_margin) if raw_margin is not None else None + return DecisionDistribution( + probabilities=probabilities, + calibrated=calibrated, + top_logit_margin=top_logit_margin, + ) + + async def _answer_systemone( + self, batch: DecisionBatch + ) -> tuple[DecisionAnswer, ...]: + """Sends `batch` as one `/v1/systemone` request, short-circuiting 1-option choices.""" + wire_questions = { + q.id: _serialize_systemone_question(q) + for q in batch.questions + if not (q.kind is QuestionKind.CHOICE and len(q.candidates()) < 2) + } + data: Mapping[str, Any] = {} + if wire_questions: + headers = await self._build_headers() + payload = { + "model": self._model, + "state": _build_systemone_state(batch.shared_context), + "questions": wire_questions, + } + data = await _post_json( + self._endpoint_url, + payload, + client=self._get_client(), + timeout_seconds=self._timeout_seconds, + headers=headers, + ) + raw_answers = data.get("answers", {}) + answers_map = raw_answers if isinstance(raw_answers, Mapping) else {} + fallback_q = answers_map.get("q") + fallback_entry = fallback_q if isinstance(fallback_q, Mapping) else {} + results: list[DecisionAnswer] = [] + for q in batch.questions: + if q.kind is QuestionKind.CHOICE and len(q.candidates()) < 2: + results.append(_single_candidate_answer(q)) + continue + raw_entry = answers_map.get(q.id) + entry = raw_entry if isinstance(raw_entry, Mapping) else fallback_entry + results.append(_parse_systemone_question_answer(q, entry, data)) + return tuple(results) + + async def answer(self, batch: DecisionBatch) -> tuple[DecisionAnswer, ...]: + """Sends `batch` as one request for both native Jev and `/v1/systemone`.""" + if not batch.questions: + return () + if self._is_systemone(): + return await self._answer_systemone(batch) + + headers = await self._build_headers() + payload: dict[str, Any] = { + "shared_context": dict(batch.shared_context), + "questions": [_serialize_native_question(q) for q in batch.questions], + } + data = await _post_json( + self._endpoint_url, + payload, + client=self._get_client(), + timeout_seconds=self._timeout_seconds, + headers=headers, + ) + raw_answers = data.get("answers", data.get("questions", ())) + return tuple( + _parse_native_question_answer( + q, + _extract_native_answer_entry(raw_answers, q.id, idx), + data, + ) + for idx, q in enumerate(batch.questions) + ) + + +class StepZeroLogprobBackend(PredictOnlyBackend, _HttpClientOwner): + """OpenAI-compatible step-0 top-logprob decision backend. + + Supports `async with` to close the owned HTTP client on exit. + """ + + def __init__( + self, + endpoint_url: str, + model: str, + *, + temperature: float = 1.0, + max_logprobs: int = 20, + auth: str | Callable[[], str | Any] | None = None, + client: httpx.AsyncClient | None = None, + timeout_seconds: float = 20.0, + ) -> None: + if temperature <= 0.0: + raise ValueError(f"temperature must be positive, got {temperature}") + if not (1 <= max_logprobs <= 20): + raise ValueError(f"max_logprobs must be in [1, 20], got {max_logprobs}") + self._endpoint_url = endpoint_url + self._model = model + self._temperature = float(temperature) + self._max_logprobs = int(max_logprobs) + self._auth = auth + self._init_http_client(client, timeout_seconds) + + def _build_headers(self) -> dict[str, str] | None: + """Builds optional Bearer authorization headers.""" + if isinstance(self._auth, str) and self._auth.strip(): + return {"Authorization": f"Bearer {self._auth.strip()}"} + return None + + async def _predict_with_prefix( + self, query: DecisionQuery, *, shared_prefix: str = "" + ) -> DecisionDistribution: + """Queries step-0 logprobs using single-character `A`-`J` labels.""" + calibrated = self._temperature != 1.0 + if not query.candidates: + return DecisionDistribution( + probabilities={}, + calibrated=calibrated, + top_logit_margin=0.0, + ) + prompt = _format_step_zero_prompt(query, shared_prefix=shared_prefix) + num_logprobs = min(max(len(query.candidates), 5), self._max_logprobs) + if self._endpoint_url.rstrip("/").lower().endswith("/chat/completions"): + payload: dict[str, Any] = { + "model": self._model, + "messages": [ + { + "role": "system", + "content": ( + "Reply with ONLY the single uppercase letter (A-J)" + " of the best candidate." + ), + }, + {"role": "user", "content": prompt}, + ], + "max_tokens": 1, + "temperature": 0.0, + "logprobs": True, + "top_logprobs": num_logprobs, + } + else: + payload = { + "model": self._model, + "prompt": prompt, + "max_tokens": 1, + "temperature": 0.0, + "logprobs": num_logprobs, + } + data = await _post_json( + self._endpoint_url, + payload, + client=self._get_client(), + timeout_seconds=self._timeout_seconds, + headers=self._build_headers(), + ) + top_logprobs = _extract_top_logprobs(data) + matched = _match_step_zero_logprobs(query.candidates, top_logprobs) + + default_floor = (min(matched.values()) - 10.0) if matched else -20.0 + logits = {c: matched.get(c, default_floor) for c in query.candidates} + probabilities, top_logit_margin = _softmax_with_margin( + logits, query.candidates, temperature=self._temperature + ) + return DecisionDistribution( + probabilities=probabilities, + calibrated=calibrated, + top_logit_margin=top_logit_margin, + ) + + async def predict(self, query: DecisionQuery) -> DecisionDistribution: + """Queries step-0 logprobs and applies temperature-scaled softmax.""" + return await self._predict_with_prefix(query) + + async def answer(self, batch: DecisionBatch) -> tuple[DecisionAnswer, ...]: + """Answers all questions concurrently with a shared prefix for prefix caching.""" + if not batch.questions: + return () + for question in batch.questions: + _validate_step_zero_candidates(question.candidates()) + shared_prefix = f"Shared context: {batch.shared_context}" + queries = [_question_query(q, batch.shared_context) for q in batch.questions] + distributions = await asyncio.gather(*( + self._predict_with_prefix(q, shared_prefix=shared_prefix) for q in queries + )) + return tuple( + answer_from_distribution(question, dist) + for question, dist in zip(batch.questions, distributions) + ) + + +def _choice_option_probabilities( + chosen: str, probability: float, candidates: tuple[str, ...] +) -> dict[str, float]: + """Assigns `probability` to `chosen` and distributes the remainder evenly.""" + if chosen not in candidates: + raise ValueError(f"Scripted option {chosen!r} is not among {candidates}.") + others = [c for c in candidates if c != chosen] + if not others: + return {chosen: 1.0} + rest = max(0.0, 1.0 - probability) / len(others) + return {c: probability if c == chosen else rest for c in candidates} + + +def _score_expected_probabilities( + expected: float, levels: tuple[str, ...] +) -> dict[str, float]: + """Constructs a level distribution whose expected index equals `expected`.""" + top = len(levels) - 1 + clamped = min(max(expected, 0.0), float(top)) + low = min(int(math.floor(clamped)), top) + high = min(low + 1, top) + weight_high = clamped - low + probs = {level: 0.0 for level in levels} + probs[levels[low]] += 1.0 - weight_high + probs[levels[high]] += weight_high + return probs + + +class DeterministicMockBackend(PredictOnlyBackend): + """Deterministic offline decision backend for tests and local evaluation.""" + + def __init__( + self, + scripted: Mapping[str, Mapping[str, float]] | None = None, + *, + scripted_answers: Mapping[str, ScriptedAnswerSpec] | None = None, + scorer: Callable[[DecisionQuery], DecisionDistribution] | None = None, + calibrated: bool = True, + default_logit_margin: float = 2.5, + ) -> None: + self._scripted: dict[str, dict[str, float]] = ( + {k: dict(v) for k, v in scripted.items()} if scripted else {} + ) + self._scripted_answers: dict[str, ScriptedAnswerSpec] = ( + dict(scripted_answers) if scripted_answers else {} + ) + self._scorer = scorer + self._calibrated = calibrated + self._default_logit_margin = float(default_logit_margin) + self.batches: list[DecisionBatch] = [] + + def _lookup_scripted_entry( + self, task: Any, prompt: str, question_id: str = "" + ) -> dict[str, float] | None: + """Finds a matching probability dict in `self._scripted`, if any.""" + for key in (f"{task}:{prompt}", str(task), question_id): + if key and key in self._scripted: + return self._scripted[key] + return None + + def _resolve_scripted_answer( + self, question: DecisionQuestion, spec: ScriptedAnswerSpec + ) -> DecisionAnswer: + """Converts a `scripted_answers` entry into a `DecisionAnswer`.""" + if isinstance(spec, DecisionAnswer): + return spec + candidates = question.candidates() + if isinstance(spec, Mapping): + probs = _normalize_probabilities(spec, candidates) + elif isinstance(spec, tuple): + probs = _choice_option_probabilities( + str(spec[0]), float(spec[1]), candidates + ) + elif isinstance(spec, str): + probs = _choice_option_probabilities(spec, 0.9, candidates) + elif question.kind is QuestionKind.BOOLEAN: + p_yes = min(max(float(spec), 0.0), 1.0) + probs = {"yes": p_yes, "no": 1.0 - p_yes} + elif question.kind is QuestionKind.SCORE: + probs = _score_expected_probabilities(float(spec), question.options) + else: + raise ValueError( + f"Numeric scripted_answers value {spec!r} requires boolean or" + f" score question, got {question.kind}." + ) + dist = DecisionDistribution( + probabilities=probs, + calibrated=self._calibrated, + top_logit_margin=self._default_logit_margin, + ) + return answer_from_distribution(question, dist) + + def _heuristic_answer( + self, question: DecisionQuestion, shared_context: Mapping[str, Any] + ) -> DecisionAnswer: + """Computes a deterministic fallback answer for an unscripted question.""" + if question.kind is QuestionKind.BOOLEAN: + dist = DecisionDistribution( + probabilities={"yes": 0.5, "no": 0.5}, + calibrated=self._calibrated, + top_logit_margin=self._default_logit_margin, + ) + return _boolean_answer(question, dist) + if question.kind is QuestionKind.SCORE: + midpoint = (len(question.options) - 1) / 2.0 + probs = _score_expected_probabilities(midpoint, question.options) + dist = DecisionDistribution( + probabilities=probs, + calibrated=self._calibrated, + top_logit_margin=self._default_logit_margin, + ) + return _score_answer(question, dist) + dist = self._heuristic_predict(_question_query(question, shared_context)) + return answer_from_distribution(question, dist) + + async def predict(self, query: DecisionQuery) -> DecisionDistribution: + """Returns a scripted, custom-scored, or heuristic distribution.""" + if self._scorer is not None: + return self._scorer(query) + + if not query.candidates: + return DecisionDistribution( + probabilities={}, + calibrated=self._calibrated, + top_logit_margin=0.0, + ) + + q_id = str(query.context.get("question_id", "")) + scripted_entry = self._lookup_scripted_entry(query.task, query.prompt, q_id) + if scripted_entry is not None: + probabilities = _normalize_probabilities(scripted_entry, query.candidates) + return DecisionDistribution( + probabilities=probabilities, + calibrated=self._calibrated, + top_logit_margin=self._default_logit_margin, + ) + + return self._heuristic_predict(query) + + async def _answer_question( + self, question: DecisionQuestion, shared_context: Mapping[str, Any] + ) -> DecisionAnswer: + """Answers one `DecisionQuestion` with `scripted_answers` taking priority.""" + if question.id in self._scripted_answers: + return self._resolve_scripted_answer( + question, self._scripted_answers[question.id] + ) + if self._scorer is not None: + dist = await self.predict(_question_query(question, shared_context)) + return answer_from_distribution(question, dist) + scripted_entry = self._lookup_scripted_entry( + question.task, question.prompt, question.id + ) + if scripted_entry is not None: + probs = _normalize_probabilities(scripted_entry, question.candidates()) + dist = DecisionDistribution( + probabilities=probs, + calibrated=self._calibrated, + top_logit_margin=self._default_logit_margin, + ) + return answer_from_distribution(question, dist) + return self._heuristic_answer(question, shared_context) + + async def answer(self, batch: DecisionBatch) -> tuple[DecisionAnswer, ...]: + """Records `batch` on `self.batches` and answers every question in order.""" + self.batches.append(batch) + return tuple( + await asyncio.gather(*( + self._answer_question(q, batch.shared_context) for q in batch.questions + )) + ) + + def _heuristic_predict(self, query: DecisionQuery) -> DecisionDistribution: + """Computes a deterministic keyword/context heuristic distribution.""" + prompt_lower = query.prompt.lower() + prompt_tokens = _tokenize(query.prompt) + context_tokens = _extract_context_tokens(query.context) + + raw_scores: list[tuple[str, float]] = [] + n = len(query.candidates) + for idx, candidate in enumerate(query.candidates): + base = _score_candidate( + candidate, prompt_lower, prompt_tokens, context_tokens + ) + tie_breaker = (n - idx) * 0.01 + raw_scores.append((candidate, base + tie_breaker)) + + best_candidate, _ = max(raw_scores, key=lambda item: item[1]) + if n == 1: + return DecisionDistribution( + probabilities={query.candidates[0]: 1.0}, + calibrated=self._calibrated, + top_logit_margin=self._default_logit_margin, + ) + + weights: dict[str, float] = {} + for candidate, score in raw_scores: + if candidate == best_candidate: + weights[candidate] = 9.0 * (1.0 + score) + else: + weights[candidate] = (1.0 + score * 0.1) / (n - 1) + + probabilities = _normalize_probabilities(weights, query.candidates) + return DecisionDistribution( + probabilities=probabilities, + calibrated=self._calibrated, + top_logit_margin=self._default_logit_margin, + ) + + +class LocalCrossEncoderBackend(PredictOnlyBackend): + """In-process CPU cross-encoder backend backed by ONNX Runtime.""" + + def __init__( + self, + model_id: str = "cross-encoder/ms-marco-MiniLM-L-6-v2", + *, + onnx_subpath: str = "onnx/model.onnx", + temperature: float = 1.0, + calibrated: bool = True, + max_batch_pairs: int = 256, + threads: int | None = None, + max_seq_length: int = 256, + max_summary_pointers: int = 12, + cache_dir: str | None = None, + session: Any | None = None, + tokenizer: Any | None = None, + ) -> None: + if temperature <= 0.0: + raise ValueError(f"temperature must be positive, got {temperature}") + if max_batch_pairs < 1: + raise ValueError(f"max_batch_pairs must be >= 1, got {max_batch_pairs}") + if threads is not None and threads < 1: + raise ValueError(f"threads must be >= 1, got {threads}") + if max_seq_length < 32: + raise ValueError(f"max_seq_length must be >= 32, got {max_seq_length}") + if max_summary_pointers < 1: + raise ValueError( + f"max_summary_pointers must be >= 1, got {max_summary_pointers}" + ) + self.model_id = model_id + self.onnx_subpath = onnx_subpath + self.temperature = float(temperature) + self.calibrated = bool(calibrated) + self.max_batch_pairs = int(max_batch_pairs) + self.threads = threads + self.max_seq_length = int(max_seq_length) + self.max_summary_pointers = int(max_summary_pointers) + self.cache_dir = cache_dir + + self._session = session + self._tokenizer = tokenizer + + def _ensure_loaded(self) -> tuple[Any, Any]: + """Lazy-loads ONNX Runtime session and Hugging Face tokenizer.""" + if self._session is not None and self._tokenizer is not None: + return self._session, self._tokenizer + + try: + from huggingface_hub import hf_hub_download + import onnxruntime as ort # type: ignore + from tokenizers import Tokenizer + except ImportError as err: + raise ImportError( + "LocalCrossEncoderBackend requires the 'decision-local' extra. " + 'Install it with: pip install "a2ui-agent-sdk[decision-local]" ' + f"(missing dependency: {err})" + ) from err + + if self._session is None: + model_path = hf_hub_download( + repo_id=self.model_id, + filename=self.onnx_subpath, + cache_dir=self.cache_dir, + ) + opts = ort.SessionOptions() + opts.intra_op_num_threads = self.threads or max(1, os.cpu_count() or 1) + opts.inter_op_num_threads = 1 + opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL + self._session = ort.InferenceSession( + model_path, opts, providers=["CPUExecutionProvider"] + ) + + if self._tokenizer is None: + tok_path = hf_hub_download( + repo_id=self.model_id, + filename="tokenizer.json", + cache_dir=self.cache_dir, + ) + self._tokenizer = Tokenizer.from_file(tok_path) + self._tokenizer.enable_padding() + self._tokenizer.enable_truncation(max_length=self.max_seq_length) + + return self._session, self._tokenizer + + def _score_pairs_sync(self, pairs: Sequence[tuple[str, str]]) -> list[float]: + """Scores `(query, passage)` pairs in chunks of `self.max_batch_pairs`.""" + if not pairs: + return [] + + import numpy as np + + session, tokenizer = self._ensure_loaded() + input_names = [inp.name for inp in getattr(session, "get_inputs", lambda: ())()] + has_type_ids = "token_type_ids" in input_names + + raw_encodings = tokenizer.encode_batch(list(pairs)) + + def _token_count(enc: Any) -> int: + mask = getattr(enc, "attention_mask", None) + if mask is not None: + return int(sum(mask)) + ids = getattr(enc, "ids", None) + return len(ids) if ids is not None else 0 + + indexed = [ + (i, raw_encodings[i], _token_count(raw_encodings[i])) + for i in range(len(pairs)) + ] + indexed.sort(key=lambda item: item[2]) + + logits_by_original_index: list[tuple[int, float]] = [] + + for start in range(0, len(indexed), self.max_batch_pairs): + chunk = indexed[start : start + self.max_batch_pairs] + chunk_max_len = max(item[2] for item in chunk) + chunk_max_len = max(chunk_max_len, 1) + + padded_ids: list[list[int]] = [] + padded_masks: list[list[int]] = [] + padded_type_ids: list[list[int]] = [] + + for _, enc, count in chunk: + raw_ids = list(enc.ids[:count]) + raw_mask = ( + list(enc.attention_mask[:count]) + if hasattr(enc, "attention_mask") + else [1] * count + ) + raw_types = ( + list(enc.type_ids[:count]) + if hasattr(enc, "type_ids") + else [0] * count + ) + + pad_width = chunk_max_len - count + padded_ids.append(raw_ids + [0] * pad_width) + padded_masks.append(raw_mask + [0] * pad_width) + if has_type_ids: + padded_type_ids.append(raw_types + [0] * pad_width) + + feed: dict[str, Any] = { + "input_ids": np.array(padded_ids, dtype=np.int64), + "attention_mask": np.array(padded_masks, dtype=np.int64), + } + if has_type_ids: + feed["token_type_ids"] = np.array(padded_type_ids, dtype=np.int64) + + chunk_logits = np.atleast_1d( + np.squeeze(session.run(None, feed)[0]).astype(float) + ) + for (orig_idx, _, _), score in zip(chunk, chunk_logits): + logits_by_original_index.append((orig_idx, float(score))) + + logits_by_original_index.sort(key=lambda item: item[0]) + return [score for _, score in logits_by_original_index] + + def _infer_sync( + self, query: DecisionQuery + ) -> tuple[dict[str, float], float | None]: + """Loads the ONNX model if needed and scores candidates synchronously.""" + query_text, passage_texts = _format_query_passage_pairs( + query, max_summary_pointers=self.max_summary_pointers + ) + pairs = [(query_text, p) for p in passage_texts] + logits = self._score_pairs_sync(pairs) + token_logits = { + cand: float(logits[i]) for i, cand in enumerate(query.candidates) + } + return _softmax_with_margin( + token_logits, query.candidates, temperature=self.temperature + ) + + async def predict(self, query: DecisionQuery) -> DecisionDistribution: + """Scores candidates in-process using the ONNX cross-encoder.""" + if not query.candidates: + return DecisionDistribution( + probabilities={}, + calibrated=self.calibrated, + top_logit_margin=0.0, + ) + if len(query.candidates) == 1: + return DecisionDistribution( + probabilities={query.candidates[0]: 1.0}, + calibrated=self.calibrated, + top_logit_margin=float("inf"), + ) + + probs, margin = await asyncio.to_thread(self._infer_sync, query) + return DecisionDistribution( + probabilities=probs, + calibrated=self.calibrated, + top_logit_margin=margin, + ) + + async def answer(self, batch: DecisionBatch) -> tuple[DecisionAnswer, ...]: + """Scores all questions and options across `batch` in one threaded ONNX pass.""" + if not batch.questions: + return () + + all_pairs: list[tuple[str, str]] = [] + slices: list[tuple[DecisionQuestion, tuple[str, ...], int, int]] = [] + for question in batch.questions: + query = _question_query(question, batch.shared_context) + query_text, passage_texts = _format_query_passage_pairs( + query, max_summary_pointers=self.max_summary_pointers + ) + start = len(all_pairs) + all_pairs.extend((query_text, p) for p in passage_texts) + slices.append((question, query.candidates, start, len(all_pairs))) + + all_logits = ( + await asyncio.to_thread(self._score_pairs_sync, all_pairs) + if all_pairs + else [] + ) + + answers: list[DecisionAnswer] = [] + for question, candidates, start, end in slices: + q_logits = all_logits[start:end] + token_logits = { + cand: float(q_logits[i]) for i, cand in enumerate(candidates) + } + probs, margin = _softmax_with_margin( + token_logits, candidates, temperature=self.temperature + ) + dist = DecisionDistribution( + probabilities=probs, + calibrated=self.calibrated, + top_logit_margin=margin, + ) + answers.append(answer_from_distribution(question, dist)) + return tuple(answers) + + +def _infer_backend_kind(url: str | None) -> str: + """Picks a backend kind from the endpoint URL, or from installed extras.""" + if url: + clean_url = url.rstrip("/").lower() + if clean_url.endswith("/v1/systemone"): + return DecisionBackendType.SYSTEMONE.value + if clean_url.endswith("/v1/completions") or clean_url.endswith( + "/chat/completions" + ): + return DecisionBackendType.STEP_ZERO.value + return DecisionBackendType.JEV.value + try: + import onnxruntime # noqa: F401 + import tokenizers # noqa: F401 + except ImportError: + return DecisionBackendType.MOCK.value + return DecisionBackendType.LOCAL.value + + +def _require_url(kind: str, url: str | None) -> str: + """Returns `url`, or raises a ValueError naming the backend that needs it.""" + if not url: + raise ValueError( + f"{kind} backend requires an endpoint URL (pass endpoint_url or set" + " A2UI_DECISION_URL)" + ) + return url + + +def _parse_positive_int_env(name: str) -> int | None: + """Parses a positive integer from environment variable `name`, if set.""" + raw = os.environ.get(name) + if not raw or not raw.strip(): + return None + try: + val = int(raw.strip()) + except ValueError as err: + raise ValueError(f"{name} must be an integer, got '{raw}'") from err + if val < 1: + raise ValueError(f"{name} must be positive, got {val}") + return val + + +def _create_local_backend( + model_name: str | None, temperature: float +) -> LocalCrossEncoderBackend: + kw: dict[str, Any] = {"temperature": temperature} + if model_name: + kw["model_id"] = model_name + threads = _parse_positive_int_env("A2UI_DECISION_THREADS") + if threads is not None: + kw["threads"] = threads + max_seq = _parse_positive_int_env("A2UI_DECISION_MAX_SEQ") + if max_seq is not None: + kw["max_seq_length"] = max_seq + return LocalCrossEncoderBackend(**kw) + + +def _default_jev_url_and_model( + auth_val: str | Callable[[], str | Any] | None, +) -> tuple[str | None, str]: + """Resolves the hosted `/v1/systemone` URL and default model when a key is present.""" + import os + + jev_model = os.environ.get("JEV_MODEL") + if isinstance(auth_val, str): + token = auth_val.strip() + if token and token != "adc": + if token.startswith("vcp_"): + return _DEFAULT_VERCEL_TYPESAFE_SYSTEMONE_URL, jev_model or "jev" + return _DEFAULT_TYPESAFE_SYSTEMONE_URL, jev_model or "jev-latest" + return None, jev_model or "default" + + +def _create_jev_backend( + kind: str, + url: str | None, + model_name: str | None, + auth_val: str | Callable[[], str | Any] | None, +) -> JevHttpBackend: + default_url, default_model = _default_jev_url_and_model(auth_val) + endpoint = _require_url(kind, url or default_url) + if kind == DecisionBackendType.SYSTEMONE.value or endpoint.rstrip("/").endswith( + "/v1/systemone" + ): + return JevHttpBackend( + endpoint, + wire_format=DecisionWireFormat.SYSTEMONE, + model=model_name or default_model, + auth=auth_val, + ) + return JevHttpBackend(endpoint, wire_format=DecisionWireFormat.JEV, auth=auth_val) + + +def _create_step_zero_backend( + url: str | None, + model_name: str | None, + temperature: float, + auth_val: str | Callable[[], str | Any] | None = None, +) -> StepZeroLogprobBackend: + endpoint = _require_url(DecisionBackendType.STEP_ZERO.value, url) + return StepZeroLogprobBackend( + endpoint, + model=model_name or "default", + temperature=temperature, + auth=auth_val, + ) + + +def create_decision_backend( + backend_type: str | DecisionBackendType | None = None, + *, + endpoint_url: str | None = None, + model: str | None = None, + auth: str | Callable[[], str | Any] | None = None, + temperature: float | None = None, +) -> DecisionBackend: + """Creates a DecisionBackend from explicit arguments or environment variables. + + Args: + backend_type: A `DecisionBackendType` or its string value. When + omitted, read from `A2UI_DECISION_BACKEND`, then inferred from + the endpoint URL, then from the installed extras. + endpoint_url: Endpoint for the HTTP backends. + model: Model identifier (cross-encoder ID or remote model name). + auth: `"adc"`, a bearer token, or a callable returning one. + temperature: Softmax temperature for the local and step-0 backends. + + Environment variables: + A2UI_DECISION_BACKEND: 'local' (alias 'onnx'), 'systemone', 'jev', 'step0', 'mock' + A2UI_DECISION_URL: Endpoint URL for HTTP backends + A2UI_DECISION_MODEL: Model identifier (e.g. cross-encoder ID or remote model) + A2UI_DECISION_AUTH: 'adc', Bearer token string, or omitted + JEV_API_KEY / TYPESAFE_API_KEY: API key for hosted Jev (/v1/systemone) + A2UI_DECISION_TEMPERATURE: Float temperature scaling parameter + + Raises: + ValueError: If the backend kind is unknown or needs a URL that is + missing. + """ + import os + + raw_kind = backend_type or os.environ.get("A2UI_DECISION_BACKEND") + url = endpoint_url or os.environ.get("A2UI_DECISION_URL") + model_name = model or os.environ.get("A2UI_DECISION_MODEL") + auth_val = ( + auth + or os.environ.get("A2UI_DECISION_AUTH") + or os.environ.get("A2UI_DECISION_TOKEN") + or os.environ.get("JEV_API_KEY") + or os.environ.get("TYPESAFE_API_KEY") + ) + temp = _resolve_temperature( + temperature, os.environ.get("A2UI_DECISION_TEMPERATURE") + ) + kind = _normalize_backend_kind(raw_kind) or _infer_backend_kind(url) + + def build_local() -> DecisionBackend: + return _create_local_backend(model_name, temp) + + builders: dict[str, Callable[[], DecisionBackend]] = { + DecisionBackendType.LOCAL.value: build_local, + # "onnx" names the same in-process backend; kept as an alias. + DecisionBackendType.ONNX.value: build_local, + DecisionBackendType.SYSTEMONE.value: lambda: _create_jev_backend( + kind, url, model_name, auth_val + ), + DecisionBackendType.JEV.value: lambda: _create_jev_backend( + kind, url, model_name, auth_val + ), + DecisionBackendType.STEP_ZERO.value: lambda: _create_step_zero_backend( + url, model_name, temp, auth + ), + DecisionBackendType.MOCK.value: DeterministicMockBackend, + } + builder = builders.get(kind) + if builder is None: + choices = ", ".join(f"'{k}'" for k in builders) + raise ValueError( + f"Unknown decision backend type '{raw_kind}'. Choose from: {choices}." + ) + return builder() + + +def _normalize_backend_kind(raw_kind: str | DecisionBackendType | None) -> str | None: + """Lower-cases a backend kind given as a string or enum; None stays None.""" + if not raw_kind: + return None + return str(getattr(raw_kind, "value", raw_kind)).strip().lower() + + +def _resolve_temperature(explicit: float | None, from_env: str | None) -> float: + """Picks the explicit temperature, else the environment value, else 1.0.""" + if explicit is not None: + return float(explicit) + return float(from_env) if from_env else 1.0 + + +__all__ = [ + "DecisionBackend", + "DeterministicMockBackend", + "JevHttpBackend", + "LocalCrossEncoderBackend", + "PredictOnlyBackend", + "StepZeroLogprobBackend", + "answer_from_distribution", + "create_decision_backend", + "ensure_batch_backend", +] diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/batching.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/batching.py new file mode 100644 index 0000000000..5625db4bf4 --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/batching.py @@ -0,0 +1,238 @@ +# 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. + +"""Event-loop window batching wrapper for `DecisionBackend` implementations.""" + +from __future__ import annotations + +import asyncio +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import Any + +from .backends import DecisionBackend, _AsyncClosable, ensure_batch_backend +from .models import ( + DecisionAnswer, + DecisionBatch, + DecisionDistribution, + DecisionQuery, + DecisionQuestion, + QuestionKind, +) + + +@dataclass(frozen=True) +class _QueueEntry: + """One queued question awaiting batched execution.""" + + question: DecisionQuestion + shared_context: Mapping[str, Any] + future: asyncio.Future[DecisionAnswer] + + +def _query_to_question(query: DecisionQuery, seq: int) -> DecisionQuestion: + """Wraps a `DecisionQuery` as a `CHOICE` `DecisionQuestion` for batching.""" + task_str = str(getattr(query.task, "value", query.task)) + raw_id = query.context.get("question_id") + question_id = ( + str(raw_id) if isinstance(raw_id, str) and raw_id else f"{task_str}:q_{seq}" + ) + descriptions = query.context.get("candidate_descriptions") + option_texts: tuple[str, ...] = () + if isinstance(descriptions, Mapping) and all( + c in descriptions for c in query.candidates + ): + option_texts = tuple(str(descriptions[c]) for c in query.candidates) + return DecisionQuestion( + id=question_id, + kind=QuestionKind.CHOICE, + prompt=query.prompt, + options=query.candidates, + option_texts=option_texts, + context=query.context, + allow_none=False, + ) + + +def _set_future_result( + future: asyncio.Future[DecisionAnswer], answer: DecisionAnswer +) -> None: + """Resolves `future` with `answer` if it has not already been cancelled.""" + if not future.done(): + future.set_result(answer) + + +def _set_future_exception( + future: asyncio.Future[DecisionAnswer], exc: BaseException +) -> None: + """Rejects `future` with `exc` if it has not already been cancelled.""" + if not future.done(): + future.set_exception(exc) + + +class BatchingDecisionBackend(_AsyncClosable): + """Coalesces concurrent `predict` and `answer` calls into `inner.answer`. + + Args: + inner: The backend that scores each coalesced batch. Predict-only + objects are adapted with `ensure_batch_backend`. + window_ms: How long to wait for more calls before flushing a batch. + max_pairs: Largest number of (question, candidate) pairs sent to + `inner.answer` in one call; None sends every pending question in + a single call. Callers that own a `SynthesisConfig` pass its + `max_pairs` so the two budgets agree. + """ + + def __init__( + self, + inner: DecisionBackend, + *, + window_ms: float = 2.0, + max_pairs: int | None = None, + ) -> None: + if window_ms < 0.0: + raise ValueError(f"window_ms must be non-negative, got {window_ms}") + if max_pairs is not None and max_pairs < 1: + raise ValueError(f"max_pairs must be >= 1 or None, got {max_pairs}") + self.inner: DecisionBackend = ensure_batch_backend(inner) + self.window_ms = float(window_ms) + self.max_pairs: int | None = None if max_pairs is None else int(max_pairs) + self._seq = 0 + self._pending: list[_QueueEntry] = [] + self._scheduled_flush: asyncio.Task[None] | None = None + self._active_flushes: set[asyncio.Task[None]] = set() + + def _enqueue( + self, question: DecisionQuestion, shared_context: Mapping[str, Any] + ) -> asyncio.Future[DecisionAnswer]: + """Appends `question` to the pending window and ensures a flush is scheduled.""" + loop = asyncio.get_running_loop() + future: asyncio.Future[DecisionAnswer] = loop.create_future() + self._pending.append( + _QueueEntry( + question=question, + shared_context=shared_context, + future=future, + ) + ) + if self._scheduled_flush is None or self._scheduled_flush.done(): + task = loop.create_task(self._flush()) + self._scheduled_flush = task + self._active_flushes.add(task) + task.add_done_callback(self._active_flushes.discard) + return future + + def _collect(self, entries: Sequence[_QueueEntry]) -> list[list[_QueueEntry]]: + """Partitions `entries` into conflict-free chunks bounded by `max_pairs`.""" + chunks: list[list[_QueueEntry]] = [] + current: list[_QueueEntry] = [] + current_ids: set[str] = set() + current_pairs = 0 + + for entry in entries: + q_id = entry.question.id + q_pairs = len(entry.question.candidates()) + exceeds_pairs = ( + bool(current) + and self.max_pairs is not None + and current_pairs + q_pairs > self.max_pairs + ) + if q_id in current_ids or exceeds_pairs: + chunks.append(current) + current = [] + current_ids = set() + current_pairs = 0 + current.append(entry) + current_ids.add(q_id) + current_pairs += q_pairs + + if current: + chunks.append(current) + return chunks + + async def _dispatch(self, chunk: Sequence[_QueueEntry]) -> None: + """Executes one coalesced chunk against `inner.answer` and resolves futures.""" + merged_context: dict[str, Any] = {} + for entry in chunk: + merged_context.update(entry.shared_context) + batch = DecisionBatch( + shared_context=merged_context, + questions=tuple(entry.question for entry in chunk), + ) + try: + answers = await self.inner.answer(batch) + if len(answers) != len(chunk): + raise ValueError( + f"Expected {len(chunk)} answers from backend, got {len(answers)}." + ) + except Exception as exc: + if len(chunk) == 1: + _set_future_exception(chunk[0].future, exc) + return + for entry in chunk: + await self._dispatch((entry,)) + return + + for entry, ans in zip(chunk, answers): + _set_future_result(entry.future, ans) + + async def _flush(self) -> None: + """Waits one window, drains queued entries, and dispatches chunks.""" + await asyncio.sleep(self.window_ms / 1000.0) + if not self._pending: + return + entries = list(self._pending) + self._pending.clear() + self._scheduled_flush = None + chunks = self._collect(entries) + await asyncio.gather(*(self._dispatch(chunk) for chunk in chunks)) + + async def predict(self, query: DecisionQuery) -> DecisionDistribution: + """Coalesces `query` into the active batch window and returns its distribution.""" + if not query.candidates: + return await self.inner.predict(query) + self._seq += 1 + question = _query_to_question(query, self._seq) + answer = await self._enqueue(question, query.context) + return answer.distribution + + async def answer(self, batch: DecisionBatch) -> tuple[DecisionAnswer, ...]: + """Coalesces all questions in `batch` into the active window.""" + if not batch.questions: + return () + futures = [self._enqueue(q, batch.shared_context) for q in batch.questions] + results = await asyncio.gather(*futures) + return tuple(results) + + async def aclose_current_loop(self) -> None: + """Drains flushes on the running loop and closes loop-local inner state.""" + loop = asyncio.get_running_loop() + while True: + loop_tasks = tuple(t for t in self._active_flushes if t.get_loop() is loop) + if not loop_tasks: + break + self._active_flushes.difference_update(loop_tasks) + await asyncio.gather(*loop_tasks, return_exceptions=True) + await self.inner.aclose_current_loop() + + async def aclose(self) -> None: + """Drains any pending flushes and closes the inner backend.""" + while self._active_flushes: + pending_tasks = tuple(self._active_flushes) + self._active_flushes.difference_update(pending_tasks) + await asyncio.gather(*pending_tasks, return_exceptions=True) + await self.inner.aclose() + + +__all__ = ["BatchingDecisionBackend"] diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/bindings.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/bindings.py new file mode 100644 index 0000000000..e777679aa2 --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/bindings.py @@ -0,0 +1,43 @@ +# 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. + +"""Protocol-versioned wire helpers shared by the decision format modules. + +These are pure functions with no dependency on the synthesizer, so the +pattern expander and layout planner can emit wire forms without importing it. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + + +def is_v10(protocol_version: str) -> bool: + """Returns whether `protocol_version` targets A2UI v1.0 or later.""" + clean = protocol_version.lstrip("v") + return clean == "1" or clean.startswith("1.") + + +def make_data_binding(path: str, *, is_v10: bool) -> dict[str, Any]: + """Creates a protocol-versioned A2UI DataBinding dictionary.""" + return {"@path": path} if is_v10 else {"path": path} + + +def make_function_call( + name: str, args: Mapping[str, Any], *, is_v10: bool +) -> dict[str, Any]: + """Creates a protocol-versioned A2UI catalog function call dictionary.""" + call_key = "@call" if is_v10 else "call" + return {call_key: name, "args": dict(args)} diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/calibration.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/calibration.py new file mode 100644 index 0000000000..141bf171fd --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/calibration.py @@ -0,0 +1,241 @@ +# 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. + +"""Risk-controlled threshold calibration for local decision-model UI synthesis.""" + +from __future__ import annotations + +from collections.abc import Collection, Mapping, Sequence +from dataclasses import dataclass +from typing import Any, Protocol, runtime_checkable + +from .models import ( + CalibrationPoint, + CalibrationResult, + SynthesisConfig, + SynthesisOutput, + SynthesisStage, +) + +_DEFAULT_THRESHOLDS: tuple[float, ...] = ( + *(round(0.30 + 0.05 * i, 2) for i in range(14)), + 0.99, +) + + +@runtime_checkable +class SynthesizerLike(Protocol): + """Structural protocol for a decision synthesizer evaluated during calibration.""" + + config: SynthesisConfig + + async def synthesize( + self, + intent: str, + payload: Mapping[str, Any], + *, + surface_id: str | None = None, + mutable_paths: Collection[str] = (), + config: SynthesisConfig | None = None, + ) -> SynthesisOutput: + """Synthesizes an A2UI surface output for the given intent and payload.""" + ... + + +@dataclass(frozen=True) +class LabeledDecisionExample: + """Golden labeled example for empirical confidence threshold calibration.""" + + intent: str + payload: Mapping[str, Any] + expected_root_component: str | None = None + expected_template_id: str | None = None + should_abstain: bool = False + mutable_paths: tuple[str, ...] = () + + +def compute_bayes_optimal_threshold( + cost_fallback: float, cost_wrong_ui: float +) -> float: + """Computes the Bayes-optimal confidence threshold clamped to [0.0, 1.0]. + + Raises a ValueError if cost_fallback is negative or cost_wrong_ui is not + strictly positive. + """ + if cost_fallback < 0: + raise ValueError("cost_fallback must be non-negative.") + if cost_wrong_ui <= 0: + raise ValueError("cost_wrong_ui must be strictly positive.") + raw_threshold = 1.0 - (cost_fallback / cost_wrong_ui) + return max(0.0, min(1.0, raw_threshold)) + + +def _is_accepted_locally(output: SynthesisOutput, threshold: float) -> bool: + """Returns whether the synthesis output is accepted locally at threshold.""" + return ( + output.stage != SynthesisStage.ABSTAIN_FALLBACK + and output.confidence >= threshold + ) + + +def _is_prediction_correct( + output: SynthesisOutput, example: LabeledDecisionExample +) -> bool: + """Returns whether an accepted synthesis output matches the golden label.""" + if example.should_abstain: + return False + if ( + example.expected_template_id is not None + and output.selected_template_id != example.expected_template_id + ): + return False + if example.expected_root_component is not None: + root_comp = (output.component_tree_spec or {}).get("root_component") + if root_comp != example.expected_root_component: + return False + return True + + +def _evaluate_threshold( + evaluated: Sequence[tuple[SynthesisOutput, LabeledDecisionExample]], + threshold: float, +) -> CalibrationPoint: + """Computes coverage, precision, and fallback rate at a candidate threshold.""" + accepted = [ + (output, ex) + for output, ex in evaluated + if _is_accepted_locally(output, threshold) + ] + accepted_count = len(accepted) + correct_accepted = sum( + 1 for output, ex in accepted if _is_prediction_correct(output, ex) + ) + coverage = accepted_count / len(evaluated) + fallback_rate = 1.0 - coverage + precision = correct_accepted / accepted_count if accepted_count > 0 else 1.0 + return CalibrationPoint( + threshold=threshold, + coverage=coverage, + precision=precision, + fallback_rate=fallback_rate, + ) + + +def _select_best_point( + points: Sequence[CalibrationPoint], target_precision: float +) -> CalibrationPoint: + """Selects the optimal Pareto calibration point for target_precision.""" + feasible = [p for p in points if p.precision >= target_precision] + if feasible: + return max(feasible, key=lambda p: (p.coverage, -p.threshold)) + return max(points, key=lambda p: (p.precision, p.threshold)) + + +def _build_permissive_config( + base: SynthesisConfig, *, allow_low_confidence_templates: bool = True +) -> SynthesisConfig: + """Builds a permissive config for raw confidence collection during sweep.""" + tpl_threshold = ( + 0.0 if allow_low_confidence_templates else base.template_confidence_threshold + ) + return SynthesisConfig( + template_confidence_threshold=tpl_threshold, + mutable_confidence_threshold=tpl_threshold, + abstain_threshold=0.0, + uncalibrated_min_logit_margin=base.uncalibrated_min_logit_margin, + entropy_switch_margin=base.entropy_switch_margin, + max_tree_depth=base.max_tree_depth, + max_children_per_container=base.max_children_per_container, + default_surface_id=base.default_surface_id, + ) + + +async def _collect_evaluated_outputs( + synthesizer: SynthesizerLike, + dataset: Sequence[LabeledDecisionExample], +) -> list[tuple[SynthesisOutput, LabeledDecisionExample]]: + """Evaluates dataset examples with a permissive per-call config override.""" + raw_base = getattr(synthesizer, "config", None) + base = raw_base if isinstance(raw_base, SynthesisConfig) else SynthesisConfig() + permissive_config = _build_permissive_config( + base, allow_low_confidence_templates=True + ) + stage2_permissive_config = _build_permissive_config( + base, allow_low_confidence_templates=False + ) + evaluated: list[tuple[SynthesisOutput, LabeledDecisionExample]] = [] + for ex in dataset: + output = await synthesizer.synthesize( + ex.intent, + ex.payload, + mutable_paths=ex.mutable_paths, + config=permissive_config, + ) + if ( + ex.expected_template_id is None + and output.stage == SynthesisStage.TEMPLATE_SELECT + and not _is_prediction_correct(output, ex) + and output.confidence < base.template_confidence_threshold + ): + output = await synthesizer.synthesize( + ex.intent, + ex.payload, + mutable_paths=ex.mutable_paths, + config=stage2_permissive_config, + ) + evaluated.append((output, ex)) + return evaluated + + +async def calibrate_thresholds( + synthesizer: SynthesizerLike, + dataset: Sequence[LabeledDecisionExample], + *, + target_precision: float = 0.95, + thresholds: Sequence[float] | None = None, +) -> CalibrationResult: + """Calibrates decision confidence thresholds against a labeled golden dataset. + + Evaluates each example once through the synthesizer, sweeps candidate + thresholds to build the coverage-precision Pareto frontier, and selects + thresholds that satisfy target_precision while maximizing local coverage. + """ + if not dataset: + raise ValueError("dataset must not be empty.") + if not (0.0 < target_precision <= 1.0): + raise ValueError("target_precision must be in (0.0, 1.0].") + + candidate_thresholds: Sequence[float] = ( + _DEFAULT_THRESHOLDS if thresholds is None else thresholds + ) + if not candidate_thresholds: + raise ValueError("thresholds must not be empty.") + + evaluated = await _collect_evaluated_outputs(synthesizer, dataset) + + points = tuple( + _evaluate_threshold(evaluated, float(tau)) for tau in candidate_thresholds + ) + best = _select_best_point(points, target_precision) + + return CalibrationResult( + recommended_template_threshold=best.threshold, + recommended_mutable_threshold=max( + best.threshold, round(min(0.99, best.threshold + 0.10), 2) + ), + recommended_abstain_threshold=best.threshold, + achieved_precision=best.precision, + achieved_coverage=best.coverage, + pareto_points=points, + ) diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/catalog_graph.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/catalog_graph.py new file mode 100644 index 0000000000..db733ce896 --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/catalog_graph.py @@ -0,0 +1,426 @@ +# 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. + +"""Catalog-agnostic component decision graph for local A2UI synthesis.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from typing import Any + +from a2ui.core import CatalogApi +from a2ui.inference_formats._shared import ( + CatalogSchemaHelper, + build_catalog_helpers, + check_mixed_catalogs, + surface_catalog_id, +) + +from .models import ComponentNodeSpec, ComponentSlot, SlotKind + +_EXCLUDED_PROPERTIES = frozenset( + {"component", "id", "catalogId", "checks", "accessibility", "metadata"} +) + + +def _collect_refs(schema: Mapping[str, Any]) -> list[str]: + """Collects `$ref` targets from `schema` and its combinator sub-schemas.""" + refs: list[str] = [] + direct_ref = schema.get("$ref") + if isinstance(direct_ref, str): + refs.append(direct_ref) + for combinator in ("oneOf", "anyOf", "allOf"): + sub_list = schema.get(combinator) + if isinstance(sub_list, Sequence) and not isinstance(sub_list, (str, bytes)): + for sub in sub_list: + if isinstance(sub, Mapping): + refs.extend(_collect_refs(sub)) + return refs + + +def _ref_matches(refs: Sequence[str], suffixes: tuple[str, ...]) -> bool: + """Returns whether any `$ref` string ends with one of `suffixes`.""" + for ref in refs: + for suffix in suffixes: + if ref == suffix or ref.endswith(f"/{suffix}"): + return True + return False + + +def _combinator_objects(schema: Mapping[str, Any]) -> list[Mapping[str, Any]]: + """Returns dict sub-schemas inside `oneOf` or `anyOf` combinators.""" + objs: list[Mapping[str, Any]] = [] + for combinator in ("oneOf", "anyOf"): + sub_list = schema.get(combinator) + if isinstance(sub_list, Sequence) and not isinstance(sub_list, (str, bytes)): + objs.extend(sub for sub in sub_list if isinstance(sub, Mapping)) + return objs + + +def _is_child_list_schema(prop_schema: Mapping[str, Any], refs: Sequence[str]) -> bool: + """Checks if a property schema represents an A2UI `ChildList`.""" + if _ref_matches(refs, ("ChildList",)): + return True + for sub in _combinator_objects(prop_schema): + props = sub.get("properties") + if isinstance(props, Mapping) and "componentId" in props and "path" in props: + return True + return False + + +def _is_action_schema(prop_schema: Mapping[str, Any], refs: Sequence[str]) -> bool: + """Checks if a property schema represents an A2UI `Action`.""" + if _ref_matches(refs, ("Action",)): + return True + for sub in _combinator_objects(prop_schema): + props = sub.get("properties") + if isinstance(props, Mapping) and ("event" in props or "functionCall" in props): + return True + return False + + +def _find_label_key( + items_props: Mapping[str, Any], + required_keys: Any, + child_id_key: str, +) -> str | None: + """Selects the label/title key from an array item object schema.""" + req_set = ( + set(required_keys) + if isinstance(required_keys, Sequence) + and not isinstance(required_keys, (str, bytes)) + else set() + ) + other_keys = [str(k) for k in items_props if str(k) != child_id_key] + for key in other_keys: + if key in req_set: + return key + for key in other_keys: + sub = items_props.get(key) + if isinstance(sub, Mapping) and ( + sub.get("type") == "string" + or _ref_matches(_collect_refs(sub), ("DynamicString", "DataBinding")) + ): + return key + return other_keys[0] if other_keys else None + + +def _classify_named_child_array( + prop_name: str, + prop_schema: Mapping[str, Any], + is_required: bool, +) -> ComponentSlot | None: + """Detects an array of objects containing a child `ComponentId` reference.""" + if prop_schema.get("type") != "array": + return None + items = prop_schema.get("items") + if not isinstance(items, Mapping): + return None + items_props = items.get("properties") + if not isinstance(items_props, Mapping): + return None + child_id_key: str | None = None + for field_name, field_schema in items_props.items(): + if isinstance(field_schema, Mapping) and _ref_matches( + _collect_refs(field_schema), ("ComponentId", "Child") + ): + child_id_key = str(field_name) + break + if child_id_key is None: + return None + label_key = _find_label_key(items_props, items.get("required", ()), child_id_key) + return ComponentSlot( + name=prop_name, + kind=SlotKind.NAMED_CHILD_ARRAY, + required=is_required, + child_id_key=child_id_key, + label_key=label_key, + description=str(prop_schema.get("description") or ""), + ) + + +def _resolve_enum_values( + helper: CatalogSchemaHelper, + comp_name: str, + prop_name: str, + prop_schema: Mapping[str, Any], +) -> tuple[str, ...]: + """Extracts static enum values for a component property if present.""" + enum_list = helper.get_property_enum(comp_name, prop_name) + if not enum_list: + direct_enum = prop_schema.get("enum") + if isinstance(direct_enum, Sequence) and not isinstance( + direct_enum, (str, bytes) + ): + enum_list = list(direct_enum) + if not enum_list: + return () + return tuple(str(v) for v in enum_list) + + +def _primitive_to_value_type(prim_type: Any) -> str | None: + """Maps a JSON Schema primitive `type` string to a `ComponentSlot` type.""" + if prim_type == "string": + return "string" + if prim_type in ("number", "integer"): + return "number" + if prim_type == "boolean": + return "boolean" + if prim_type == "array": + return "array" + return None + + +def _resolve_data_value_type( + prop_schema: Mapping[str, Any], refs: Sequence[str] +) -> str | None: + """Determines the data value type for a bindable `DATA_VALUE` slot.""" + ref_type_pairs = ( + (("DynamicString",), "string"), + (("DynamicNumber",), "number"), + (("DynamicBoolean",), "boolean"), + (("DynamicStringList",), "array"), + (("DynamicValue",), "any"), + ) + for suffixes, val_type in ref_type_pairs: + if _ref_matches(refs, suffixes): + return val_type + if not _ref_matches(refs, ("DataBinding",)): + return None + direct = _primitive_to_value_type(prop_schema.get("type")) + if direct is not None: + return direct + sub_types = { + t + for sub in _combinator_objects(prop_schema) + for t in (_primitive_to_value_type(sub.get("type")),) + if t is not None + } + if len(sub_types) > 1: + return "any" + if len(sub_types) == 1: + return next(iter(sub_types)) + return "any" + + +def _classify_property_slot( + helper: CatalogSchemaHelper, + comp_name: str, + prop_name: str, + prop_schema: Mapping[str, Any], + is_required: bool, +) -> ComponentSlot | None: + """Classifies a single component property schema into a `ComponentSlot`.""" + description = str(prop_schema.get("description") or "") + refs = _collect_refs(prop_schema) + if _is_child_list_schema(prop_schema, refs): + return ComponentSlot( + name=prop_name, + kind=SlotKind.CHILD_LIST, + required=is_required, + description=description, + ) + named_array = _classify_named_child_array(prop_name, prop_schema, is_required) + if named_array is not None: + return named_array + if _ref_matches(refs, ("ComponentId", "Child")): + return ComponentSlot( + name=prop_name, + kind=SlotKind.CHILD, + required=is_required, + description=description, + ) + if _is_action_schema(prop_schema, refs): + return ComponentSlot( + name=prop_name, + kind=SlotKind.ACTION, + required=is_required, + description=description, + ) + enum_values = _resolve_enum_values(helper, comp_name, prop_name, prop_schema) + if enum_values: + return ComponentSlot( + name=prop_name, + kind=SlotKind.STATIC_ENUM, + required=is_required, + enum_values=enum_values, + description=description, + ) + value_type = _resolve_data_value_type(prop_schema, refs) + if value_type is not None: + return ComponentSlot( + name=prop_name, + kind=SlotKind.DATA_VALUE, + required=is_required, + value_type=value_type, + description=description, + ) + return None + + +def _is_component_checkable( + helper: CatalogSchemaHelper, comp_name: str, raw_props: Sequence[str] +) -> bool: + """Returns whether `comp_name` supports validation `checks`.""" + if "checks" in raw_props: + return True + return bool(helper.component_is_checkable.get(comp_name, False)) + + +def _collect_component_props_and_required( + helper: CatalogSchemaHelper, comp_name: str +) -> tuple[list[str], set[str]]: + """Returns `(ordered_property_names, required_property_names)` for `comp_name`.""" + required_set = set(helper.get_component_required(comp_name)) + raw_props = list(helper.get_component_properties(comp_name)) + comp_schema = helper.components.get(comp_name, {}) + if not isinstance(comp_schema, Mapping): + return raw_props, required_set + direct_props = comp_schema.get("properties") + if isinstance(direct_props, Mapping): + raw_props.extend(str(k) for k in direct_props if str(k) not in raw_props) + direct_req = comp_schema.get("required") + if isinstance(direct_req, Sequence) and not isinstance(direct_req, (str, bytes)): + required_set.update(str(r) for r in direct_req) + return raw_props, required_set + + +def _build_component_slots( + helper: CatalogSchemaHelper, + comp_name: str, + raw_props: Sequence[str], + required_set: set[str], +) -> tuple[ComponentSlot, ...]: + """Classifies all bindable slots on `comp_name`.""" + slots: list[ComponentSlot] = [] + for prop_name in raw_props: + if prop_name in _EXCLUDED_PROPERTIES: + continue + prop_schema = helper.get_property_schema(comp_name, prop_name) + if not isinstance(prop_schema, Mapping): + continue + slot = _classify_property_slot( + helper, comp_name, prop_name, prop_schema, prop_name in required_set + ) + if slot is not None: + slots.append(slot) + return tuple(slots) + + +def _extract_component_spec( + catalog_id: str, comp_name: str, helper: CatalogSchemaHelper +) -> ComponentNodeSpec: + """Extracts a `ComponentNodeSpec` for `comp_name` from `helper`.""" + raw_props, required_set = _collect_component_props_and_required(helper, comp_name) + slot_tuple = _build_component_slots(helper, comp_name, raw_props, required_set) + container_kinds = ( + SlotKind.CHILD, + SlotKind.CHILD_LIST, + SlotKind.NAMED_CHILD_ARRAY, + ) + return ComponentNodeSpec( + name=comp_name, + catalog_id=catalog_id, + description=helper.get_component_description(comp_name) or "", + slots=slot_tuple, + supports_checks=_is_component_checkable(helper, comp_name, raw_props), + is_container=any(s.kind in container_kinds for s in slot_tuple), + is_multi_view_switcher=any( + s.kind == SlotKind.NAMED_CHILD_ARRAY for s in slot_tuple + ), + has_action_slot=any(s.kind == SlotKind.ACTION for s in slot_tuple), + ) + + +def _function_return_type( + helper: CatalogSchemaHelper, fn_name: str, fn_schema: Any +) -> str | None: + """Extracts the declared returnType of a catalog function.""" + if isinstance(fn_schema, Mapping): + top_ret = fn_schema.get("returnType") + if isinstance(top_ret, str): + return top_ret + props = fn_schema.get("properties") + if isinstance(props, Mapping): + ret_prop = props.get("returnType") + if isinstance(ret_prop, Mapping) and isinstance(ret_prop.get("const"), str): + return str(ret_prop["const"]) + cat_model = getattr(helper, "catalog_model", None) + fn_map = getattr(cat_model, "functions", None) + if isinstance(fn_map, Mapping) and fn_name in fn_map: + ret = getattr(fn_map[fn_name], "return_type", None) + if isinstance(ret, str): + return ret + return None + + +class CatalogDecisionGraph: + """Catalog-agnostic component and function decision graph.""" + + def __init__(self, catalogs: Sequence[CatalogApi]) -> None: + self._catalogs = check_mixed_catalogs(catalogs) + self._helpers = build_catalog_helpers(self._catalogs) + first_ver = self._catalogs[0].protocol_version + raw_ver = str(first_ver.value if hasattr(first_ver, "value") else first_ver) + self.protocol_version: str = ( + raw_ver if raw_ver.startswith("v") else f"v{raw_ver}" + ) + self.surface_catalog_id: str | None = surface_catalog_id(self._catalogs) + + self._components: dict[str, ComponentNodeSpec] = {} + for catalog_id, helper in self._helpers.items(): + for comp_name in helper.components: + if comp_name not in self._components: + self._components[comp_name] = _extract_component_spec( + catalog_id, comp_name, helper + ) + + def get_component(self, name: str) -> ComponentNodeSpec | None: + """Returns the `ComponentNodeSpec` for `name`, or None if unknown.""" + return self._components.get(name) + + @property + def catalogs(self) -> tuple[CatalogApi, ...]: + """Returns the validated catalogs backing this decision graph.""" + return tuple(self._catalogs) + + def helpers(self) -> Mapping[str, CatalogSchemaHelper]: + """Returns the mapping of catalog IDs to their `CatalogSchemaHelper`.""" + return dict(self._helpers) + + def root_candidates(self) -> tuple[ComponentNodeSpec, ...]: + """Returns all catalog component specs eligible as a surface root.""" + return tuple(self._components.values()) + + def leaf_candidates(self) -> tuple[ComponentNodeSpec, ...]: + """Returns component specs that do not contain child component slots.""" + return tuple(c for c in self._components.values() if not c.is_container) + + def container_candidates(self) -> tuple[ComponentNodeSpec, ...]: + """Returns component specs that contain child component slots.""" + return tuple(c for c in self._components.values() if c.is_container) + + def multi_view_switchers(self) -> tuple[ComponentNodeSpec, ...]: + """Returns component specs with a `NAMED_CHILD_ARRAY` slot.""" + return tuple(c for c in self._components.values() if c.is_multi_view_switcher) + + def checkable_functions(self) -> tuple[str, ...]: + """Returns function names from catalog helpers whose returnType is boolean.""" + names: list[str] = [] + for helper in self._helpers.values(): + for fn_name, fn_schema in helper.functions.items(): + ret_type = _function_return_type(helper, fn_name, fn_schema) + if ret_type in ("boolean", "validationResult") and fn_name not in names: + names.append(fn_name) + return tuple(names) diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/decision_block.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/decision_block.py new file mode 100644 index 0000000000..6c27b6ac0c --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/decision_block.py @@ -0,0 +1,251 @@ +# 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. + +"""The decision block: the JSON object an LLM emits for the decision format. + +Shared by the prompt generator, the parser, and the render tool so all three +read and write the same field names. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import Any + +from a2ui.core.schema import AgentToRendererMessage +from a2ui.parser.messages import to_message_dicts + +from .models import LayoutBrief, coerce_decision_payload + +# Wire field names, with the snake_case spellings also accepted on input. +_FIELD_ALIASES: dict[str, tuple[str, ...]] = { + "intent": ("intent",), + "payload": ("payload", "data"), + "surface_id": ("surfaceId", "surface_id"), + "template_id": ("template", "templateId", "template_id"), + "fallback_dsl": ("fallbackDsl", "fallback_dsl"), + "layout": ("layout",), + "mutable_paths": ("mutablePaths", "mutable_paths"), + "title": ("title",), + "summary": ("summary",), +} + + +def _first_present(source: Mapping[str, Any], names: Sequence[str]) -> Any: + for name in names: + if name in source: + return source[name] + return None + + +def _parse_layout_items(raw: Any) -> tuple[str, ...]: + """Shape-checks an optional ``layout`` field into its raw brief items. + + Role validation happens later, in the synthesizer, against the grammar it + was configured with; the block only carries the strings. + """ + if raw is None: + return () + if isinstance(raw, LayoutBrief): + return tuple(raw.to_items()) + if ( + not isinstance(raw, Sequence) + or isinstance(raw, (str, bytes, bytearray)) + or not all(isinstance(item, str) for item in raw) + ): + raise TypeError( + "Decision block field 'layout' must be a list of 'role:key,key' strings." + ) + return tuple(item for item in raw if item.strip()) + + +def _parse_mutable_paths(raw: Any) -> tuple[str, ...]: + """Normalizes an optional ``mutablePaths`` sequence into ``/``-prefixed pointers.""" + if raw is None: + return () + if ( + not isinstance(raw, Sequence) + or isinstance(raw, (str, bytes, bytearray)) + or not all(isinstance(item, str) for item in raw) + ): + raise TypeError( + "Decision block field 'mutablePaths' must be a list of JSON pointer" + " strings." + ) + paths: list[str] = [] + for item in raw: + stripped = item.strip() + if not stripped: + continue + paths.append(stripped if stripped.startswith("/") else f"/{stripped}") + return tuple(paths) + + +@dataclass(frozen=True) +class DecisionBlock: + """One decision request: what to show and the data to show it with. + + Attributes: + intent: Natural-language description of the interface to render. + payload: The data to bind, as an object or array (a JSON string is + decoded by `from_mapping`). + surface_id: Target surface, or None for the synthesizer default. + template_id: A registered template to render directly, if any. + fallback_dsl: A2UI Express rendered when the model abstains, if any. + layout: Raw ``role:key,key`` brief items pinning roles to payload + pointers; empty when the block gave none. The synthesizer parses + and validates them against its grammar. + mutable_paths: JSON Pointers in `payload` that the user may edit. + """ + + intent: str + payload: Mapping[str, Any] | Sequence[Any] + surface_id: str | None = None + template_id: str | None = None + fallback_dsl: str | None = None + layout: tuple[str, ...] = () + mutable_paths: tuple[str, ...] = () + title: str | None = None + summary: str | None = None + + @classmethod + def from_mapping(cls, source: Mapping[str, Any]) -> DecisionBlock: + """Reads a block from a parsed JSON object. + + Accepts the camelCase wire names (`surfaceId`, `template`, + `fallbackDsl`, `layout`, `mutablePaths`, `title`, `summary`) and their + snake_case spellings. + + Raises: + ValueError: If `intent` is missing or blank, or `payload` is a + string that is not valid JSON. + TypeError: If `payload` is missing or is neither an object nor an + array, or an optional field has the wrong type. + """ + intent = _first_present(source, _FIELD_ALIASES["intent"]) + if not isinstance(intent, str) or not intent.strip(): + raise ValueError("Decision block requires a non-empty string 'intent'.") + raw_payload = _first_present(source, _FIELD_ALIASES["payload"]) + if raw_payload is None: + raise TypeError("Decision block requires a 'payload' object or array.") + payload = coerce_decision_payload(raw_payload) + + def _optional_str(key: str) -> str | None: + value = _first_present(source, _FIELD_ALIASES[key]) + if value is None: + return None + if not isinstance(value, str): + raise TypeError( + f"Decision block field '{_FIELD_ALIASES[key][0]}' must be a" + f" string, got {type(value).__name__}." + ) + stripped = value.strip() + return stripped or None + + layout = _parse_layout_items(_first_present(source, _FIELD_ALIASES["layout"])) + mutable_paths = _parse_mutable_paths( + _first_present(source, _FIELD_ALIASES["mutable_paths"]) + ) + return cls( + intent=intent.strip(), + payload=payload, + surface_id=_optional_str("surface_id"), + template_id=_optional_str("template_id"), + fallback_dsl=_optional_str("fallback_dsl"), + layout=layout, + mutable_paths=mutable_paths, + title=_optional_str("title"), + summary=_optional_str("summary"), + ) + + def to_json(self) -> dict[str, Any]: + """Serializes the block with the camelCase wire names, omitting None.""" + out: dict[str, Any] = {"intent": self.intent, "payload": self.payload} + if self.surface_id is not None: + out["surfaceId"] = self.surface_id + if self.template_id is not None: + out["template"] = self.template_id + if self.fallback_dsl is not None: + out["fallbackDsl"] = self.fallback_dsl + if self.layout: + out["layout"] = list(self.layout) + if self.mutable_paths: + out["mutablePaths"] = list(self.mutable_paths) + if self.title is not None: + out["title"] = self.title + if self.summary is not None: + out["summary"] = self.summary + return out + + +def _surface_id_in(msg: Mapping[str, Any]) -> str | None: + """Returns the first `surfaceId` any envelope body in the message names.""" + for body in msg.values(): + if isinstance(body, Mapping) and isinstance(body.get("surfaceId"), str): + return str(body["surfaceId"]) + return None + + +def _data_model_in(msg: Mapping[str, Any]) -> Mapping[str, Any] | Sequence[Any] | None: + """Returns the data model a message writes, if it writes one. + + Reads `updateDataModel.value`, v0.8 `dataModelUpdate.contents`, and a + v1.0 `createSurface.dataModel`. + """ + for key, field in (("updateDataModel", "value"), ("dataModelUpdate", "contents")): + body = msg.get(key) + if isinstance(body, Mapping): + value = body.get(field) + return value if isinstance(value, (Mapping, list, tuple)) else None + create = msg.get("createSurface") + if isinstance(create, Mapping): + data_model = create.get("dataModel") + if isinstance(data_model, Mapping): + return data_model + return None + + +def decision_block_from_messages( + messages: Sequence[AgentToRendererMessage], + *, + default_intent: str | None = None, +) -> DecisionBlock: + """Reconstructs a decision block from rendered messages. + + The round-trip is lossy: rendered messages carry no intent, so a synthetic + `Render ` intent (or `default_intent` when supplied) is used. The + payload is the first data model any message writes and the surface id + comes from the first message that names one. + """ + surface_id: str | None = None + payload: Mapping[str, Any] | Sequence[Any] | None = None + for msg in to_message_dicts(messages): + if surface_id is None: + surface_id = _surface_id_in(msg) + if payload is None: + payload = _data_model_in(msg) + intent = ( + default_intent + if default_intent is not None + else f"Render {surface_id or 'surface'}" + ) + return DecisionBlock( + intent=intent, + payload=payload if payload is not None else {}, + surface_id=surface_id, + ) + + +__all__ = ["DecisionBlock", "decision_block_from_messages"] diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/format.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/format.py new file mode 100644 index 0000000000..9dfb557ae5 --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/format.py @@ -0,0 +1,264 @@ +# 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. + +"""Decision inference format for `A2uiRequestProcessor`. + +Plugs local decision-model synthesis into the processor pipeline the same way +`ExpressFormatFactory` and `DirectJsonFormatFactory` do:: + + processor = A2uiRequestProcessor( + catalogs=catalogs, format_factory=DecisionFormatFactory() + ) +""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +from a2ui.core import CatalogApi +from a2ui.core.schema import AgentToRendererMessage +from a2ui.inference_format import InferenceFormat, InferenceFormatFactory +from a2ui.inference_formats._shared import check_mixed_catalogs + +from .archetypes import ArchetypeGrammar +from .backends import DecisionBackend, create_decision_backend +from .batching import BatchingDecisionBackend +from .catalog_graph import CatalogDecisionGraph +from .models import SynthesisConfig +from .parser import DecisionParser +from .patterns import MergedPatternLibrary, PatternLibrary +from .prompt_generator import DecisionPromptGenerator +from .synthesizer import DecisionSynthesizer, FallbackCallback +from .template_registry import TemplateRegistry + + +class DecisionFormat(InferenceFormat): + """Inference format in which the model emits intent and data, not UI. + + The prompt generator asks for `` decision blocks and the parser + renders them through a `DecisionSynthesizer`. The catalog graph and + synthesizer are built once per format and shared by every parser it + creates. + """ + + def __init__( + self, + catalogs: Sequence[CatalogApi], + examples: Sequence[Sequence[AgentToRendererMessage]] | None = None, + *, + backend: DecisionBackend | None = None, + config: SynthesisConfig | None = None, + registry: TemplateRegistry | None = None, + archetypes: ArchetypeGrammar | None = None, + patterns: PatternLibrary | MergedPatternLibrary | None = None, + surface_id: str = "main", + fallback_card: bool = True, + fallback_fn: FallbackCallback | None = None, + ) -> None: + """Creates a decision format. + + Args: + catalogs: The active catalogs. + examples: Few-shot example turns shown in the prompt. + backend: Decision backend; defaults to `create_decision_backend()`. + config: Synthesis thresholds and limits. + registry: Surface templates offered in the prompt and tried first. + archetypes: Layout archetype grammar; defaults to + `ArchetypeGrammar.default()`. + patterns: Catalog pattern library; defaults to + `MergedPatternLibrary.for_catalogs(catalogs)`. + surface_id: Surface used when a block names none. A block's own + `surfaceId` wins; `SynthesisConfig.default_surface_id` is not + consulted on this path. + fallback_card: Render a deterministic card when the model abstains + and the block carries no `fallbackDsl`. Defaults to True here, + unlike `DecisionSynthesizer`, because inside a parser an + abstention with no messages is a compilation error. + fallback_fn: Custom fallback called before the card. + """ + self._catalogs = list(check_mixed_catalogs(catalogs)) + self._examples = [list(t) for t in examples] if examples is not None else None + self._registry = registry if registry is not None else TemplateRegistry() + self.surface_id = surface_id + self._synthesizer = DecisionSynthesizer( + CatalogDecisionGraph(self._catalogs), + backend, + registry=self._registry, + config=config, + archetypes=archetypes, + patterns=patterns, + fallback_card=fallback_card, + fallback_fn=fallback_fn, + ) + self._prompt_generator: DecisionPromptGenerator | None = None + + @property + def catalogs(self) -> list[CatalogApi]: + """A copy of the active catalogs, in the order the format received them.""" + return list(self._catalogs) + + @property + def examples(self) -> list[list[AgentToRendererMessage]] | None: + """The configured few-shot example turns, if any.""" + return [list(t) for t in self._examples] if self._examples is not None else None + + @property + def synthesizer(self) -> DecisionSynthesizer: + """The synthesizer shared by every parser this format creates.""" + return self._synthesizer + + @property + def prompt_generator(self) -> DecisionPromptGenerator: + """The prompt generator configured for this format.""" + if self._prompt_generator is None: + self._prompt_generator = DecisionPromptGenerator( + self._catalogs, + examples=self._examples, + registry=self._registry, + archetypes=self._synthesizer.archetypes, + ) + return self._prompt_generator + + def create_parser(self) -> DecisionParser: + """Creates a parser that renders blocks through the shared synthesizer.""" + return DecisionParser(self._synthesizer, surface_id=self.surface_id) + + @property + def parser(self) -> DecisionParser: + """A parser configured for this format.""" + return self.create_parser() + + +class DecisionFormatFactory(InferenceFormatFactory): + """Factory for `DecisionFormat` instances, for `A2uiRequestProcessor`. + + One backend is shared by every format the factory creates, because a + backend may hold a loaded model or an HTTP connection pool and + `A2uiGenerator` creates a format per renderer request. The catalog graph + is still built per format, since catalogs are negotiated per renderer. + """ + + def __init__( + self, + *, + backend: DecisionBackend | None = None, + config: SynthesisConfig | None = None, + registry: TemplateRegistry | None = None, + archetypes: ArchetypeGrammar | None = None, + patterns: PatternLibrary | MergedPatternLibrary | None = None, + batch_backend: bool = True, + surface_id: str = "main", + fallback_card: bool = True, + fallback_fn: FallbackCallback | None = None, + ) -> None: + """Stores the settings every created format shares. See `DecisionFormat`. + + Args: + backend: The shared decision backend. When None, it is created + with `create_decision_backend()` on the first `create_format` + call and reused afterwards. + config: See `DecisionFormat`. + registry: See `DecisionFormat`. + archetypes: See `DecisionFormat`. + patterns: See `DecisionFormat`. When None, built once per catalog + set via `MergedPatternLibrary.for_catalogs`. + batch_backend: When True (default), wraps the shared backend in + `BatchingDecisionBackend` with `config.max_pairs` as its + per-call budget. + surface_id: See `DecisionFormat`. + fallback_card: See `DecisionFormat`. + fallback_fn: See `DecisionFormat`. + """ + self._raw_backend = backend + self._backend: DecisionBackend | None = None + self._config = config + self._batch_backend = batch_backend + if backend is not None: + self._backend = self._wrap_backend(backend) + self._registry = registry + self._archetypes = archetypes + self._patterns = patterns + self._pattern_cache: dict[ + tuple[str, ...], PatternLibrary | MergedPatternLibrary + ] = {} + self._surface_id = surface_id + self._fallback_card = fallback_card + self._fallback_fn = fallback_fn + + @property + def backend(self) -> DecisionBackend | None: + """The shared backend, or None until the first format is created.""" + return self._backend + + def _wrap_backend(self, raw: DecisionBackend) -> DecisionBackend: + """Wraps `raw` in `BatchingDecisionBackend` when `batch_backend` is on.""" + if not self._batch_backend or isinstance(raw, BatchingDecisionBackend): + return raw + budget = (self._config or SynthesisConfig()).max_pairs + return BatchingDecisionBackend(raw, max_pairs=budget) + + def _shared_backend(self) -> DecisionBackend: + """Returns the backend every created format shares, building it on first use.""" + if self._backend is None: + raw = ( + self._raw_backend + if self._raw_backend is not None + else create_decision_backend() + ) + self._backend = self._wrap_backend(raw) + return self._backend + + def _patterns_for_catalogs( + self, catalogs: Sequence[CatalogApi] + ) -> PatternLibrary | MergedPatternLibrary: + """Returns the cached `PatternLibrary` for `catalogs`.""" + if self._patterns is not None: + return self._patterns + key = tuple(c.catalog_id for c in catalogs) + if key not in self._pattern_cache: + self._pattern_cache[key] = MergedPatternLibrary.for_catalogs(catalogs) + return self._pattern_cache[key] + + def create_format( + self, + catalogs: Sequence[CatalogApi], + examples: Sequence[Sequence[AgentToRendererMessage]] | None = None, + ) -> DecisionFormat: + return DecisionFormat( + catalogs, + examples=examples, + backend=self._shared_backend(), + config=self._config, + registry=self._registry, + archetypes=self._archetypes, + patterns=self._patterns_for_catalogs(catalogs), + surface_id=self._surface_id, + fallback_card=self._fallback_card, + fallback_fn=self._fallback_fn, + ) + + async def aclose(self) -> None: + """Closes the shared decision backend if one has been initialized.""" + if self._backend is not None: + await self._backend.aclose() + + async def __aenter__(self) -> DecisionFormatFactory: + return self + + async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None: + await self.aclose() + + +__all__ = ["DecisionFormat", "DecisionFormatFactory"] diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/layout_lint.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/layout_lint.py new file mode 100644 index 0000000000..d7bfb73e85 --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/layout_lint.py @@ -0,0 +1,419 @@ +# 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. + +"""Post-expansion component lint for archetype-planned A2UI surfaces.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +import re +from typing import Any + +from a2ui.core import A2uiValidationError + +from .models import LayoutPlan, _WireEnum + +_HEADING_PREFIX_RE = re.compile(r"^(#{1,6})\s") +_HEADING_VARIANT_LEVELS: dict[str, int] = { + "h1": 1, + "h2": 2, + "h3": 3, + "h4": 4, + "h5": 5, + "h6": 6, +} +_CONTAINER_TYPES: frozenset[str] = frozenset( + {"Row", "Column", "Card", "List", "Modal", "Tabs"} +) +_LABEL_PROPERTIES: frozenset[str] = frozenset( + {"label", "accessibility", "checks", "action", "description"} +) + + +class LintCode(_WireEnum): + """Structural rule a `LintFinding` reports against.""" + + EMPTY_CONTAINER = "empty_container" + MISSING_COMPONENT = "missing_component" + MULTIPLE_PRIMARY_BUTTONS = "multiple_primary_buttons" + DUPLICATE_POINTER_BINDING = "duplicate_pointer_binding" + HEADING_AFTER_BODY = "heading_after_body" + MULTIPLE_REELS = "multiple_reels" + + +class LintSeverity(_WireEnum): + """Whether a `LintFinding` blocks output (`ERROR`) or only advises (`WARNING`).""" + + ERROR = "error" + WARNING = "warning" + + +@dataclass(frozen=True) +class LintFinding: + """One violation or warning detected by `lint_components`.""" + + code: LintCode + message: str + component_id: str | None = None + severity: LintSeverity = LintSeverity.ERROR + + def __post_init__(self) -> None: + object.__setattr__(self, "code", LintCode(self.code)) + object.__setattr__(self, "severity", LintSeverity(self.severity)) + + +def _unpack_component( + comp: Mapping[str, Any], +) -> tuple[str, str, Mapping[str, Any]]: + """Extracts ``(id, component_type, properties)`` from v0.9 or v1.0 component dicts.""" + comp_id = str(comp.get("id", "")) + raw_type = comp.get("component") + if isinstance(raw_type, str): + return comp_id, raw_type, comp + if isinstance(raw_type, Mapping) and len(raw_type) == 1: + comp_type, props = next(iter(raw_type.items())) + if isinstance(props, Mapping): + return comp_id, str(comp_type), props + return comp_id, "", comp + + +def _non_empty_strings(items: Any) -> list[str]: + """Returns non-empty string elements from a sequence, or an empty list.""" + if not isinstance(items, Sequence) or isinstance(items, (str, bytes)): + return [] + return [item for item in items if isinstance(item, str) and item] + + +def _template_target_id(mapping: Mapping[str, Any]) -> str: + """Extracts a template `componentId` or `component` from a `children` mapping.""" + template = mapping.get("template") + source = template if isinstance(template, Mapping) else mapping + target = source.get("componentId") or source.get("component") + return str(target) if isinstance(target, str) else "" + + +def _extract_child_list_ids(children: Any) -> tuple[list[str], bool]: + """Returns ``(referenced_ids, has_any_child_slot)`` from a ``children`` value.""" + direct = _non_empty_strings(children) + if direct: + return direct, True + if not isinstance(children, Mapping): + return [], False + if "explicitList" in children: + explicit = _non_empty_strings(children.get("explicitList")) + return explicit, bool(explicit) + target = _template_target_id(children) + return ([target] if target else []), bool(target) + + +def _tab_child_ids(tab_items: Any) -> list[str]: + """Extracts child IDs from a `Tabs.tabItems` sequence.""" + if not isinstance(tab_items, Sequence) or isinstance(tab_items, (str, bytes)): + return [] + return [ + str(tab["child"]) + for tab in tab_items + if isinstance(tab, Mapping) + and isinstance(tab.get("child"), str) + and tab["child"] + ] + + +def _referenced_child_ids( + comp_type: str, props: Mapping[str, Any] +) -> tuple[list[str], bool]: + """Returns ``(referenced_ids, is_non_empty)`` for a component's child slots.""" + refs = [ + str(props[key]) + for key in ("child", "entryPointChild", "contentChild") + if isinstance(props.get(key), str) and props.get(key) + ] + refs.extend(_tab_child_ids(props.get("tabItems"))) + list_ids, has_children = _extract_child_list_ids(props.get("children")) + refs.extend(list_ids) + if comp_type in {"Row", "Column", "List"}: + return refs, has_children + if comp_type in {"Card", "Tabs", "Modal"}: + return refs, bool(refs) + return refs, True + + +def _check_containers_and_references( + components: Sequence[Mapping[str, Any]], +) -> list[LintFinding]: + """Checks that no container is empty and every referenced child ID exists.""" + known_ids = {str(c.get("id", "")) for c in components if c.get("id")} + findings: list[LintFinding] = [] + for comp in components: + comp_id, comp_type, props = _unpack_component(comp) + refs, non_empty = _referenced_child_ids(comp_type, props) + if comp_type in _CONTAINER_TYPES and not non_empty: + findings.append( + LintFinding( + code=LintCode.EMPTY_CONTAINER, + message=f"Container {comp_id!r} ({comp_type}) has zero children.", + component_id=comp_id or None, + ) + ) + for ref in refs: + if ref not in known_ids: + findings.append( + LintFinding( + code=LintCode.MISSING_COMPONENT, + message=( + f"Component {comp_id!r} references unknown child {ref!r}." + ), + component_id=comp_id or None, + ) + ) + return findings + + +def _check_primary_buttons( + components: Sequence[Mapping[str, Any]], +) -> list[LintFinding]: + """Checks that at most one Button has ``variant: primary``.""" + primaries: list[str] = [] + for comp in components: + comp_id, comp_type, props = _unpack_component(comp) + if comp_type == "Button" and props.get("variant") == "primary": + primaries.append(comp_id) + if len(primaries) <= 1: + return [] + return [ + LintFinding( + code=LintCode.MULTIPLE_PRIMARY_BUTTONS, + message=( + f"Button {comp_id!r} is an extra primary button; at most one" + f" primary button is allowed (found {primaries})." + ), + component_id=comp_id or None, + ) + for comp_id in primaries[1:] + ] + + +def _extract_direct_pointer( + node: Mapping[str, Any], +) -> tuple[bool, str | None]: + """Checks for a function call or direct ``path``/``@path`` binding on `node`.""" + if "call" in node or "@call" in node: + return True, None + path = node.get("path") or node.get("@path") + if isinstance(path, str) and path.startswith("/"): + return True, path + return False, None + + +def _collect_value_pointers(node: Any) -> list[str]: + """Collects absolute JSON Pointers from data-binding dicts under `node`.""" + if isinstance(node, Mapping): + handled, path = _extract_direct_pointer(node) + if handled: + return [path] if path is not None else [] + found: list[str] = [] + for val in node.values(): + found.extend(_collect_value_pointers(val)) + return found + if isinstance(node, Sequence) and not isinstance(node, (str, bytes)): + found = [] + for item in node: + found.extend(_collect_value_pointers(item)) + return found + return [] + + +def _component_value_pointers(props: Mapping[str, Any]) -> list[str]: + """Returns non-label data-binding pointers bound on a single component.""" + pointers: list[str] = [] + for key, val in props.items(): + if key in {"id", "component", "children"} or key in _LABEL_PROPERTIES: + continue + pointers.extend(_collect_value_pointers(val)) + return pointers + + +def _check_duplicate_pointers( + components: Sequence[Mapping[str, Any]], +) -> list[LintFinding]: + """Checks that no absolute pointer is bound twice as a non-label value.""" + seen: dict[str, str] = {} + findings: list[LintFinding] = [] + for comp in components: + comp_id, _, props = _unpack_component(comp) + for pointer in _component_value_pointers(props): + first_id = seen.get(pointer) + if first_id is not None and first_id != comp_id: + findings.append( + LintFinding( + code=LintCode.DUPLICATE_POINTER_BINDING, + message=( + f"Pointer {pointer!r} is bound in both {first_id!r}" + f" and {comp_id!r}." + ), + component_id=comp_id or None, + ) + ) + else: + seen[pointer] = comp_id + return findings + + +def _text_heading_level(props: Mapping[str, Any]) -> int | None: + """Returns the heading level (1..6) of a Text component, or None for body text.""" + variant = str(props.get("variant", "")) + if variant in _HEADING_VARIANT_LEVELS: + return _HEADING_VARIANT_LEVELS[variant] + text_val = props.get("text") + raw_str = "" + if isinstance(text_val, str): + raw_str = text_val + elif isinstance(text_val, Mapping): + literal = text_val.get("literalString") or text_val.get("$text") + if isinstance(literal, str): + raw_str = literal + else: + args = text_val.get("args") + if isinstance(args, Mapping) and isinstance(args.get("value"), str): + raw_str = args["value"] + match = _HEADING_PREFIX_RE.match(raw_str.lstrip()) + if match is not None: + return len(match.group(1)) + return None + + +def _match_block_suffix(comp_id: str, block_id: str) -> str | None: + """Returns the suffix after `block_id_` in `comp_id`, or `None`.""" + prefix = f"{block_id}_" + if comp_id.startswith(prefix): + return comp_id[len(prefix) :] + if f"_{prefix}" in comp_id: + return comp_id.split(f"_{prefix}", 1)[1] + return None + + +def _block_group_for_id(comp_id: str, block_ids: Sequence[str]) -> str: + """Maps a component id to its owning block (or unrolled item) group.""" + for block_id in block_ids: + if comp_id == block_id: + return block_id + rest = _match_block_suffix(comp_id, block_id) + if rest is not None: + head = rest.split("_", 1)[0] + return f"{block_id}_{head}" if head.isdigit() else block_id + return "_surface" + + +def _check_heading_order( + components: Sequence[Mapping[str, Any]], + plan: LayoutPlan | None, +) -> list[LintFinding]: + """Checks that headings precede body copy and do not invert levels within a block.""" + block_ids = plan.block_ids() if plan is not None else () + seen_body: dict[str, bool] = {} + deepest_heading: dict[str, int] = {} + findings: list[LintFinding] = [] + for comp in components: + comp_id, comp_type, props = _unpack_component(comp) + if comp_type != "Text": + continue + group = _block_group_for_id(comp_id, block_ids) + level = _text_heading_level(props) + if level is None: + if props.get("variant") != "caption": + seen_body[group] = True + continue + prev_level = deepest_heading.get(group) + if seen_body.get(group, False) or ( + prev_level is not None and level < prev_level + ): + findings.append( + LintFinding( + code=LintCode.HEADING_AFTER_BODY, + message=( + f"Heading {comp_id!r} (h{level}) appears after body copy" + f" or a deeper heading in block {group!r}." + ), + component_id=comp_id or None, + ) + ) + deepest_heading[group] = max(prev_level or level, level) + return findings + + +def _check_single_reel( + components: Sequence[Mapping[str, Any]], + plan: LayoutPlan | None, +) -> list[LintFinding]: + """Checks that at most one horizontal reel exists on the surface.""" + reel_ids: list[str] = [] + for comp in components: + comp_id, comp_type, props = _unpack_component(comp) + if comp_type == "List" and props.get("direction") == "horizontal": + reel_ids.append(comp_id) + if not reel_ids and plan is not None: + reel_ids = [ + b.block_id + for b in plan.blocks + if b.variant_knobs.get("layout") == "reel" or b.pattern == "reel" + ] + if len(reel_ids) <= 1: + return [] + return [ + LintFinding( + code=LintCode.MULTIPLE_REELS, + message=( + f"Surface has multiple horizontal reels ({reel_ids}); at most" + " one reel is allowed." + ), + component_id=comp_id or None, + ) + for comp_id in reel_ids[1:] + ] + + +def lint_components( + components: Sequence[Mapping[str, Any]], + plan: LayoutPlan | None = None, + *, + raise_on_error: bool = False, +) -> tuple[LintFinding, ...]: + """Runs post-expansion layout lint checks over `components`. + + Args: + components: Expanded A2UI component dicts (v0.9 or v1.0 wire shape). + plan: Optional `LayoutPlan` providing block grouping and knob context. + raise_on_error: When True, raises `A2uiValidationError` if any finding + has `LintSeverity.ERROR`. + + Returns: + A tuple of `LintFinding` objects (empty when clean). + + Raises: + A2uiValidationError: If `raise_on_error` is True and any finding has + `LintSeverity.ERROR`. + """ + findings: list[LintFinding] = [] + findings.extend(_check_containers_and_references(components)) + findings.extend(_check_primary_buttons(components)) + findings.extend(_check_duplicate_pointers(components)) + findings.extend(_check_heading_order(components, plan)) + findings.extend(_check_single_reel(components, plan)) + if raise_on_error: + errors = [f for f in findings if f.severity is LintSeverity.ERROR] + if errors: + summary = "; ".join(f"{f.code}: {f.message}" for f in errors) + raise A2uiValidationError(f"Layout component lint failed: {summary}") + return tuple(findings) diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/layout_planner.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/layout_planner.py new file mode 100644 index 0000000000..a38f25935d --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/layout_planner.py @@ -0,0 +1,3428 @@ +# 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. + +"""Speculative batch planner and deterministic layout rules for A2UI surfaces.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field, replace +import random +import re +from typing import Any + +from a2ui.core import A2uiValidationError + +from .archetypes import ( + ABSTRACT_PATTERNS, + FALLBACK_TERMINALS, + ArchetypeGrammar, + BlockRef, + BlockSpec, + LayoutArchetype, + MeasureSpec, + QuestionSpec, + Range, + ShapeFilter, + SlotSpec, +) +from .models import ( + AuthoredCopy, + BlockBindings, + DecisionAnswer, + DecisionBatch, + DecisionQuestion, + DecisionRecord, + LayoutBrief, + LayoutPlan, + PageBindings, + PatternCapabilities, + PlannedBlock, + PlanOutcome, + PlanReason, + QuestionKind, + SemanticType, + SlotBinding, + SynthesisConfig, + VarietyMode, +) +from .payload_inspector import PointerSummary, split_pointer + +_CAMEL_RE = re.compile(r"([a-z0-9])([A-Z])") +_PATTERN_VARIANT_REQ_RE = re.compile(r"^pattern:([a-z_]+):([a-z_]+)$") + +_NUMERIC_SEMANTIC_TYPES: frozenset[str] = frozenset({ + "number", + "integer", + "count", + "currency", + "percent", + "ratio", + "quantity", + "rating", + "bounded", + "duration", +}) +_TEXT_FALLBACK_TYPES: frozenset[str] = frozenset({ + "string", + "name", + "title", + "identifier", +}) +_PAGE_TITLE_KEYS: frozenset[str] = frozenset({ + "title", + "name", + "subject", + "heading", +}) +_MARK_KEY_HINTS: frozenset[str] = frozenset({ + "logo", + "icon", + "avatar", +}) +_NON_FACT_SEMANTIC_TYPES: frozenset[str] = frozenset({ + "image_url", + "video_url", + "audio_url", + "document_url", + "long_text", + "markdown", + "code", + "array", + "object", + "empty", +}) +_OPTIONAL_TEXT_KEYS: Mapping[str, frozenset[str]] = { + "caption": frozenset({"caption", "alt", "subtitle", "title"}), + "heading": frozenset({"heading", "title", "header", "subject"}), + "text": frozenset({ + "text", + "message", + "detail", + "description", + "summary", + "body", + "reason", + }), +} +_FALLBACK_KEY_TYPES: Mapping[str, str] = { + "name": "name", + "rating": "rating", + "stars": "rating", + "score": "rating", + "amount": "currency", + "price": "currency", + "pricefrom": "currency", + "fee": "currency", + "cost": "currency", + "total": "currency", + "status": "status", + "state": "status", + "health": "status", + "arrives": "date", + "date": "date", + "due": "date", + "skipforward": "duration", + "uptimehours": "duration", + "duration": "duration", + "about": "long_text", + "description": "long_text", + "summary": "long_text", + "body": "long_text", +} + + +class _AllCapabilities: + """Default `PatternCapabilities` used when no catalog capabilities are passed.""" + + def has_pattern(self, name: str, variant: str | None = None) -> bool: + del variant + return name in ABSTRACT_PATTERNS + + +@dataclass +class PlannerState: + """State carried from `LayoutPlanner.build_batch` into `read` and `needs_reask`.""" + + intent: str + pointers: tuple[PointerSummary, ...] + eligible: tuple[LayoutArchetype, ...] + prior_archetypes: tuple[str, ...] + brief: LayoutBrief | None + batch: DecisionBatch + payload: Mapping[str, Any] = field(default_factory=dict) + derived_anatomy: dict[tuple[str, str], str] = field(default_factory=dict) + budget_exhausted: bool = False + trace: list[DecisionRecord] = field(default_factory=list) + answers_by_id: dict[str, DecisionAnswer] = field(default_factory=dict) + salience_scores: dict[str, float] = field(default_factory=dict) + gate_probabilities: dict[str, float] = field(default_factory=dict) + selected_archetype: LayoutArchetype | None = None + page_claimed_pointers: set[str] = field(default_factory=set) + action_gate_blocked: bool = False + required_block_missing: bool = False + copy: AuthoredCopy | None = None + seed: int | None = None + rng: random.Random | None = None + + +def _humanize_key(key: str) -> str: + """Converts a camelCase or snake_case key into a sentence-case label.""" + if not key: + return "" + spaced = _CAMEL_RE.sub(r"\1 \2", key).replace("_", " ").replace("-", " ") + words = [w.lower() for w in spaced.split() if w] + if not words: + return "" + joined = " ".join(words) + return joined[0].upper() + joined[1:] + + +def _resolve_pointer_value(payload: Mapping[str, Any], pointer: str) -> Any: + """Resolves an RFC 6901 JSON Pointer against `payload`, or returns None.""" + if not payload or not pointer.startswith("/"): + return None + current: Any = payload + for raw_seg in pointer.lstrip("/").split("/"): + seg = raw_seg.replace("~1", "/").replace("~0", "~") + if isinstance(current, Mapping) and seg in current: + current = current[seg] + elif ( + isinstance(current, Sequence) + and not isinstance(current, (str, bytes)) + and seg.isdigit() + and int(seg) < len(current) + ): + current = current[int(seg)] + else: + return None + return current + + +def _infer_image_key_hint(low_key: str) -> str | None: + """Returns a framing key hint if `low_key` names an image role.""" + for token in ("logo", "icon", "avatar", "photo", "image"): + if token in low_key: + return token + return None + + +def _infer_fallback_semantics( + ptr: PointerSummary, +) -> tuple[SemanticType, dict[str, Any]]: + """Infers semantic type and hints for a Wave-1 `PointerSummary` with default fields.""" + hints = dict(ptr.hints) + if ptr.semantic_type is not SemanticType.STRING or ptr.label: + return ptr.semantic_type, hints + if ptr.value_type in {"array", "object", "boolean"}: + return SemanticType(ptr.value_type), hints + low = ptr.key.lower() + img_hint = _infer_image_key_hint(low) + if img_hint is not None: + hints.setdefault("keyHint", img_hint) + return SemanticType.IMAGE_URL, hints + mapped = _FALLBACK_KEY_TYPES.get(low) + if mapped is not None: + hints.setdefault("keyHint", low) + if mapped == "long_text": + hints.setdefault("wordCount", 36) + hints.setdefault("length", "blurb") + return SemanticType(mapped), hints + if ptr.value_type == "number": + return SemanticType.NUMBER, hints + return SemanticType.STRING, hints + + +class _NormalizedPointers(tuple[PointerSummary, ...]): + """Marker tuple subclass indicating pointers have already been normalized.""" + + +def _normalize_single_pointer(ptr: PointerSummary) -> PointerSummary: + """Populates missing label, semantic type, and array sample fields on `ptr`.""" + if ( + ptr.label + and ptr.semantic_type is not SemanticType.STRING + and ( + ptr.value_type != "array" + or not ptr.element_keys + or ptr.element_semantic_types + ) + ): + return ptr + sem_type, hints = _infer_fallback_semantics(ptr) + label = ptr.label or _humanize_key(ptr.key) + elem_sem: dict[str, SemanticType] = dict(ptr.element_semantic_types) + samples = list(ptr.sample_pointers) + if ptr.value_type == "array" and ptr.element_keys and not elem_sem: + for ek in ptr.element_keys: + is_img = ek.lower() in {"url", "image", "photo", "thumbnail", "avatar"} + elem_sem[ek] = SemanticType.IMAGE_URL if is_img else SemanticType.STRING + if is_img and f"{ptr.path}/0/{ek}" not in samples: + samples.append(f"{ptr.path}/0/{ek}") + return replace( + ptr, + semantic_type=sem_type, + hints=hints, + label=label, + element_semantic_types=elem_sem, + sample_pointers=tuple(samples), + ) + + +def _build_parent_object_summary( + parent: str, normalized: Sequence[PointerSummary] +) -> PointerSummary: + """Synthesizes a parent `object` `PointerSummary` for grouped child pointers.""" + parent_key = split_pointer(parent)[1] + children = [p for p in normalized if p.parent == parent] + return PointerSummary( + path=parent, + value_type="object", + cardinality=len(children), + mutable_hint=any(c.mutable_hint for c in children), + semantic_type=SemanticType.OBJECT, + key=parent_key, + label=_humanize_key(parent_key), + ) + + +def _build_sample_pointer_summary(sample: str) -> PointerSummary: + """Builds a scalar `image_url` `PointerSummary` for an array sample pointer.""" + s_parent, s_key = split_pointer(sample) + return PointerSummary( + path=sample, + value_type="string", + cardinality=1, + semantic_type=SemanticType.IMAGE_URL, + key=s_key, + label=_humanize_key(s_key), + parent=s_parent, + ) + + +def _normalize_pointers( + pointers: Sequence[PointerSummary], +) -> tuple[PointerSummary, ...]: + """Normalizes `pointers` and adds missing parent object or sample pointers.""" + if isinstance(pointers, _NormalizedPointers): + return pointers + normalized = [_normalize_single_pointer(p) for p in pointers] + existing_paths = {p.path for p in normalized} + excluded_parents = existing_paths | { + p.path for p in normalized if p.value_type == "array" + } + result: list[PointerSummary] = [] + for ptr in normalized: + parent = ptr.parent or "" + if parent and parent not in excluded_parents: + excluded_parents.add(parent) + result.append(_build_parent_object_summary(parent, normalized)) + result.append(ptr) + for sample in ptr.sample_pointers: + if sample not in existing_paths: + existing_paths.add(sample) + result.append(_build_sample_pointer_summary(sample)) + return _NormalizedPointers(result) + + +def _in_range(value: int, bounds: Range | None) -> bool: + """Returns whether `value` falls within inclusive `bounds`.""" + if bounds is None: + return True + low, high = bounds + if low is not None and value < low: + return False + if high is not None and value > high: + return False + return True + + +def _matches_primary_type(sem_type: str, target: str, ptr: PointerSummary) -> bool: + """Checks whether `ptr` directly satisfies semantic type `target`.""" + if target == sem_type: + return True + if target == "enum" and sem_type == "status": + return True + if target == "any": + return ptr.value_type in {"string", "number", "boolean"} + if target == "mutable": + return ptr.mutable_hint and ptr.value_type in {"string", "number", "boolean"} + if target == "action": + return _is_action_pointer(ptr) + return False + + +def _matches_fallback_type(sem_type: str, target: str) -> bool: + """Checks coarse type compatibility (`number` and `string` supertypes).""" + if target == "number": + return sem_type in _NUMERIC_SEMANTIC_TYPES + if target == "string": + return sem_type in _TEXT_FALLBACK_TYPES + return False + + +def _pointer_matches_types( + ptr: PointerSummary, from_types: Sequence[str], *, allow_fallback: bool = True +) -> bool: + """Returns whether `ptr` matches any semantic type in `from_types`.""" + for target in from_types: + if _matches_primary_type(ptr.semantic_type, target, ptr): + return True + if not allow_fallback: + return False + return any(_matches_fallback_type(ptr.semantic_type, t) for t in from_types) + + +def _is_action_pointer(ptr: PointerSummary) -> bool: + """Returns whether `ptr` represents an action list or button trigger.""" + low = ptr.key.lower() + if low in {"actions", "buttons", "cta"}: + return True + return ptr.mutable_hint and ptr.value_type == "array" and not ptr.element_keys + + +def _array_element_types(ptr: PointerSummary) -> set[str]: + """Returns the set of element semantic types present on an array `ptr`.""" + types: set[str] = set() + if ptr.element_keys: + types.add("object") + for sem in ptr.element_semantic_types.values(): + types.add(sem) + if sem in _NUMERIC_SEMANTIC_TYPES: + types.add("number") + if not ptr.element_keys and ptr.cardinality > 0 and not types: + types.add("string") + return types + + +def _is_nested_mutable_setting( + ptr: PointerSummary, pointers: Sequence[PointerSummary] +) -> bool: + """Returns whether `ptr` is a child field of a mutable settings object.""" + if not ptr.mutable_hint or not ptr.parent: + return False + return any( + p.path == ptr.parent and p.value_type == "object" and p.mutable_hint + for p in pointers + ) + + +def _shape_matching_pointers( + shape: ShapeFilter, pointers: Sequence[PointerSummary] +) -> list[PointerSummary]: + """Returns pointers matching `shape.pointers`, excluding nested mutable settings.""" + matched: list[PointerSummary] = [] + for ptr in pointers: + if shape.mutable is None and _is_nested_mutable_setting(ptr, pointers): + continue + if _pointer_matches_types(ptr, shape.pointers): + matched.append(ptr) + return matched + + +def _single_array_matches_shape(arr: PointerSummary, shape: ShapeFilter) -> bool: + """Returns whether one array pointer `arr` satisfies `shape` array constraints.""" + if not _in_range(arr.cardinality, shape.array_length): + return False + if shape.element_types and not ( + _array_element_types(arr) & set(shape.element_types) + ): + return False + if shape.element_keys: + keys_low = {k.lower() for k in arr.element_keys} + if not (keys_low & {k.lower() for k in shape.element_keys}): + return False + return True + + +def _matches_array_shape( + shape: ShapeFilter, pointers: Sequence[PointerSummary] +) -> bool: + """Checks `array_length`, `element_types`, and `element_keys` on array pointers.""" + if ( + shape.array_length is None + and not shape.element_types + and not shape.element_keys + ): + return True + return any( + _single_array_matches_shape(p, shape) + for p in pointers + if p.value_type == "array" + ) + + +def _pointer_prose_level(ptr: PointerSummary) -> str | None: + """Extracts or computes the `prose.length` level for `ptr`.""" + level = ptr.hints.get("length") + if isinstance(level, str): + return level + wc = ptr.hints.get("wordCount") + if not isinstance(wc, (int, float)): + return None + if wc < 15: + return "line" + if wc < 60: + return "blurb" + return "summary" if wc < 200 else "article" + + +def _matches_prose_length( + shape: ShapeFilter, pointers: Sequence[PointerSummary] +) -> bool: + """Checks `shape.prose_length` against `long_text` and `markdown` pointers.""" + if not shape.prose_length: + return True + allowed = set(shape.prose_length) + return any(_pointer_prose_level(p) in allowed for p in pointers) + + +def _matches_shape( + shape: ShapeFilter, + pointers: Sequence[PointerSummary], + *, + check_actions_gate: bool = False, + actions_allowed: bool = True, +) -> bool: + """Evaluates a `ShapeFilter` against normalized `pointers`.""" + if shape.is_empty: + return True + if check_actions_gate and shape.actions_allowed and not actions_allowed: + return False + if shape.mutable is not None: + if not any(p.mutable_hint == shape.mutable for p in pointers): + return False + if shape.pointers: + matched = _shape_matching_pointers(shape, pointers) + if not matched or not _in_range(len(matched), shape.count): + return False + elif shape.count is not None and not _in_range(len(pointers), shape.count): + return False + if not _matches_array_shape(shape, pointers): + return False + return _matches_prose_length(shape, pointers) + + +def _find_sibling_pointer( + ptr: PointerSummary, + sibling_names: Sequence[str], + from_types: Sequence[str], + pointers: Sequence[PointerSummary], +) -> PointerSummary | None: + """Finds a sibling pointer in `ptr.parent` matching `sibling_names` and `from_types`.""" + base_low = ptr.key.lower() + targets_low = tuple(s.lower() for s in sibling_names) + for cand in pointers: + if cand.path == ptr.path or cand.parent != ptr.parent: + continue + if not _pointer_matches_types(cand, from_types): + continue + cand_low = cand.key.lower() + if cand_low in targets_low: + return cand + if any( + cand_low == f"{base_low}{t}" or cand_low == f"{base_low}_{t}" + for t in targets_low + ): + return cand + return None + + +def _absorbed_for_single_pointer( + ptr: PointerSummary, + pointers: Sequence[PointerSummary], + has_currency: bool, +) -> list[str]: + """Returns sibling pointer paths absorbed by `ptr`.""" + found: list[str] = [] + if has_currency and ptr.key.lower() == "currency": + found.append(ptr.path) + if ptr.semantic_type in _NUMERIC_SEMANTIC_TYPES: + sib = _find_sibling_pointer( + ptr, + ("delta", "change", "diff", "previous"), + ("number", "percent"), + pointers, + ) + if sib is not None: + found.append(sib.path) + if ptr.semantic_type == "bounded": + for bound_key in ("min", "max", "total", "limit"): + sib = _find_sibling_pointer(ptr, (bound_key,), ("number",), pointers) + if sib is not None: + found.append(sib.path) + return found + + +def _collect_absorbed_siblings( + pointers: Sequence[PointerSummary], +) -> set[str]: + """Returns paths of pointers absorbed as delta, bound, or currency siblings.""" + has_currency = any(p.semantic_type == "currency" for p in pointers) + absorbed: set[str] = set() + for ptr in pointers: + absorbed.update(_absorbed_for_single_pointer(ptr, pointers, has_currency)) + return absorbed + + +def _page_title_pointer( + pointers: Sequence[PointerSummary], +) -> PointerSummary | None: + """Finds the top-level pointer that serves as the page title, if any.""" + for ptr in pointers: + if ptr.parent or ptr.mutable_hint: + continue + if ( + ptr.key.lower() in _PAGE_TITLE_KEYS + and ptr.semantic_type in _TEXT_FALLBACK_TYPES + ): + return ptr + return None + + +def _is_avoided_key(ptr: PointerSummary, avoid_keys: Sequence[str]) -> bool: + """Returns whether `ptr.key` or `ptr.hints['keyHint']` matches `avoid_keys`.""" + if not avoid_keys: + return False + low = ptr.key.lower() + hint = str(ptr.hints.get("keyHint", "")).lower() + return any(ak.lower() in low or ak.lower() == hint for ak in avoid_keys) + + +def _score_candidate_pointer( + ptr: PointerSummary, + slot: SlotSpec, + preferred_paths: Sequence[str], +) -> tuple[int, int, int]: + """Scores `ptr` for `slot` (higher is better): brief preference, prefer hint, type rank.""" + brief_rank = 1 if ptr.path in preferred_paths else 0 + low = ptr.key.lower() + prefer_rank = ( + 1 + if any(pref.lower() == low or pref.lower() in low for pref in slot.prefer) + else 0 + ) + type_rank = 0 + for idx, target in enumerate(slot.from_types): + if _matches_primary_type(ptr.semantic_type, target, ptr): + type_rank = len(slot.from_types) - idx + 10 + break + if type_rank == 0: + for idx, target in enumerate(slot.from_types): + if _matches_fallback_type(ptr.semantic_type, target): + type_rank = len(slot.from_types) - idx + break + if "enum" in slot.from_types and ptr.semantic_type in {"status", "enum"}: + type_rank += 20 + return (brief_rank, prefer_rank, type_rank) + + +def _is_eligible_scalar_candidate( + ptr: PointerSummary, + slot: SlotSpec, + pointers: Sequence[PointerSummary], + used: set[str], +) -> bool: + """Checks whether `ptr` is an eligible candidate for non-repeated `slot`.""" + if ptr.path in used or not _pointer_matches_types(ptr, slot.from_types): + return False + if not slot.required and slot.name in _OPTIONAL_TEXT_KEYS: + allowed_keys = _OPTIONAL_TEXT_KEYS[slot.name] + return ptr.key.lower() in allowed_keys or ( + slot.name == "text" and ptr.semantic_type == "long_text" + ) + if slot.mutable and not ptr.mutable_hint: + return False + if _is_avoided_key(ptr, slot.avoid_keys): + return False + return not _is_nested_mutable_setting(ptr, pointers) + + +def _bind_scalar_slot( + slot: SlotSpec, + pointers: Sequence[PointerSummary], + used: set[str], + *, + preferred_paths: Sequence[str] = (), +) -> SlotBinding: + """Binds a single non-repeated `SlotSpec` against available `pointers`.""" + candidates = [ + p for p in pointers if _is_eligible_scalar_candidate(p, slot, pointers, used) + ] + if not candidates: + return ( + SlotBinding(literal=slot.default) + if slot.default is not None + else SlotBinding() + ) + best = max( + candidates, + key=lambda p: _score_candidate_pointer(p, slot, preferred_paths), + ) + return SlotBinding(pointer=best.path, semantic_type=best.semantic_type) + + +def _pick_best_element_key( + arr_ptr: PointerSummary, + field_name: str, + field_spec: SlotSpec, + used_keys: set[str], + *, + min_score: int = 0, +) -> str | None: + """Selects the best matching relative key on `arr_ptr` for `field_spec`.""" + best_key: str | None = None + best_score = min_score - 1 + preferred_names = {p.lower() for p in (*field_spec.prefer, field_name)} + for ek in arr_ptr.element_keys: + if ek in used_keys or ek.lower() in {"actions", "action"}: + continue + ek_sem = arr_ptr.element_semantic_types.get(ek, SemanticType.STRING) + fake_ptr = PointerSummary( + path=ek, + value_type="string", + cardinality=1, + semantic_type=ek_sem, + key=ek, + ) + if _is_avoided_key(fake_ptr, field_spec.avoid_keys): + continue + if not _pointer_matches_types(fake_ptr, field_spec.from_types): + continue + is_pref = any( + pref == ek.lower() or pref in ek.lower() for pref in preferred_names + ) + score = (10 if is_pref else 0) + (5 if ek_sem in field_spec.from_types else 1) + if score > best_score: + best_score = score + best_key = ek + return best_key + + +def _bind_array_element_fields( + arr_ptr: PointerSummary, + fields: Mapping[str, SlotSpec], +) -> dict[str, SlotBinding]: + """Binds relative per-element fields of a repeated array-backed slot.""" + bound_fields: dict[str, SlotBinding] = {} + used_keys: set[str] = set() + passes = ( + tuple((k, v) for k, v in fields.items() if v.required), + tuple((k, v) for k, v in fields.items() if not v.required), + ) + for req_pass, field_group in enumerate(passes): + score_cutoffs = (0,) if req_pass == 0 else (10, 0) + for min_score in score_cutoffs: + for field_name, field_spec in field_group: + if field_name in bound_fields: + continue + best_key = _pick_best_element_key( + arr_ptr, + field_name, + field_spec, + used_keys, + min_score=min_score, + ) + if best_key is not None: + used_keys.add(best_key) + bound_fields[field_name] = SlotBinding( + pointer=best_key, + semantic_type=arr_ptr.element_semantic_types.get( + best_key, SemanticType.STRING + ), + ) + elif ( + min_score == 0 and not arr_ptr.element_keys and field_spec.required + ): + bound_fields[field_name] = SlotBinding(pointer="") + return bound_fields + + +def _unroll_array_items( + ptr: PointerSummary, fields: Mapping[str, SlotBinding] +) -> tuple[dict[str, SlotBinding], ...]: + """Unrolls `fields` into indexed element bindings across `ptr.cardinality`.""" + return tuple( + { + f_name: SlotBinding( + pointer=( + f"{ptr.path}/{idx}/{f_bind.pointer}" + if f_bind.pointer + else f"{ptr.path}/{idx}" + ), + semantic_type=f_bind.semantic_type, + ) + for f_name, f_bind in fields.items() + if f_bind.bound + } + for idx in range(ptr.cardinality) + ) + + +def _bind_array_repeated_slot( + block_id: str, + slot: SlotSpec, + pointers: Sequence[PointerSummary], + used: set[str], +) -> SlotBinding: + """Binds a repeated slot whose `from_types` is ``('array',)``.""" + for ptr in pointers: + if ptr.path in used or ptr.value_type != "array" or ptr.cardinality <= 0: + continue + if _is_action_pointer(ptr): + continue + fields = _bind_array_element_fields(ptr, slot.fields) + if all( + not f_spec.required or f_name in fields + for f_name, f_spec in slot.fields.items() + ): + items = ( + _unroll_array_items(ptr, fields) + if (block_id == "steps" or not ptr.element_keys) + else () + ) + return SlotBinding(pointer=ptr.path, fields=fields, items=items) + return SlotBinding() + + +def _labels_from_sequence(raw: Any) -> list[str]: + """Extracts string labels from a runtime sequence of strings or mappings.""" + if not isinstance(raw, Sequence) or isinstance(raw, (str, bytes)): + return [] + labels: list[str] = [] + for item in raw: + if isinstance(item, Mapping): + val = item.get("label") or item.get("title") or item.get("name") or "" + labels.append(str(val)) + else: + labels.append(str(item)) + return labels + + +def _action_button_labels( + ptr: PointerSummary, + payload: Mapping[str, Any], + intent: str, + max_buttons: int | None, +) -> list[str]: + """Extracts button label strings for an action pointer.""" + labels = _labels_from_sequence(_resolve_pointer_value(payload, ptr.path)) + if not labels: + labels = _labels_from_sequence( + ptr.hints.get("values") or ptr.hints.get("items") + ) + if not labels and ptr.cardinality == 2 and "send" in intent.lower(): + labels = ["Send", "Cancel"] + if not labels: + labels = [str(i) for i in range(max(ptr.cardinality, 1))] + return labels[:max_buttons] if max_buttons is not None else labels + + +def _bind_actions_slot( + slot: SlotSpec, + pointers: Sequence[PointerSummary], + used: set[str], + payload: Mapping[str, Any], + intent: str, +) -> SlotBinding: + """Binds the `actions.buttons` repeated slot from an action array pointer.""" + for ptr in pointers: + if ptr.path in used or not _is_action_pointer(ptr): + continue + labels = _action_button_labels(ptr, payload, intent, slot.max) + items = tuple({"label": SlotBinding(literal=lbl)} for lbl in labels if lbl) + if items: + return SlotBinding(pointer=ptr.path, items=items) + return SlotBinding() + + +def _bind_groups_slot( + pointers: Sequence[PointerSummary], + used: set[str], +) -> SlotBinding: + """Binds `groups.groups` from object pointers and their mutable child rows.""" + group_items: list[dict[str, SlotBinding]] = [] + for obj_ptr in pointers: + if obj_ptr.path in used or obj_ptr.value_type != "object": + continue + child_rows = [ + p + for p in pointers + if p.parent == obj_ptr.path + and p.path not in used + and p.mutable_hint + and p.value_type in {"string", "number", "boolean"} + ] + if not child_rows: + continue + row_items = tuple( + { + "label": SlotBinding(literal=row.label or _humanize_key(row.key)), + "value": SlotBinding(pointer=row.path), + } + for row in child_rows + ) + group_items.append({ + "heading": SlotBinding(literal=obj_ptr.label or _humanize_key(obj_ptr.key)), + "rows": SlotBinding(items=row_items), + }) + if not group_items: + return SlotBinding() + return SlotBinding(items=tuple(group_items)) + + +def _build_scalar_item_mapping( + ptr: PointerSummary, + slot: SlotSpec, + pointers: Sequence[PointerSummary], +) -> dict[str, SlotBinding]: + """Builds the per-element field mapping for one scalar pointer in `items`/`rows`.""" + item: dict[str, SlotBinding] = {} + for f_name, f_spec in slot.fields.items(): + if "key" in f_spec.from_types: + item[f_name] = SlotBinding(literal=ptr.label or _humanize_key(ptr.key)) + elif f_spec.sibling: + sib = _find_sibling_pointer( + ptr, f_spec.sibling, f_spec.from_types, pointers + ) + if sib is not None: + item[f_name] = SlotBinding(pointer=sib.path) + elif f_name == "value" or "any" in f_spec.from_types: + item[f_name] = SlotBinding(pointer=ptr.path) + return item + + +def _is_scalar_repeated_candidate( + ptr: PointerSummary, + block_id: str, + slot: SlotSpec, + pointers: Sequence[PointerSummary], + used: set[str], + absorbed: set[str], +) -> bool: + """Checks whether `ptr` can be an element in a scalar-repeated slot.""" + if ptr.path in used or ptr.path in absorbed: + return False + if ptr.path.count("/") >= 2 and "/0/" in ptr.path: + return False + if block_id != "form" and _is_nested_mutable_setting(ptr, pointers): + return False + if block_id in {"headline", "facts"} and ( + ptr.semantic_type in _NON_FACT_SEMANTIC_TYPES + ): + return False + return _pointer_matches_types(ptr, slot.from_types) + + +def _select_candidates_by_salience( + candidates: list[PointerSummary], + slot: SlotSpec, + salience_scores: Mapping[str, float], + salience_spec: QuestionSpec | None, +) -> list[PointerSummary]: + """Orders and filters `candidates` according to `salience_scores` and `slot.max`.""" + ordered = list(candidates) + if slot.order_by == "salience" and salience_scores: + ordered.sort(key=lambda p: -salience_scores.get(p.path, 0.0)) + if salience_spec is not None and salience_spec.select and salience_scores: + cut = salience_spec.select.get("aboveLevel", 0.0) + above = [p for p in ordered if salience_scores.get(p.path, cut) >= cut] + min_count = int(salience_spec.select.get("min", 1)) + ordered = above if len(above) >= min_count else ordered[:min_count] + if slot.max is not None: + ordered = ordered[: slot.max] + return ordered + + +def _bind_scalar_repeated_slot( + block_id: str, + slot: SlotSpec, + pointers: Sequence[PointerSummary], + used: set[str], + salience_scores: Mapping[str, float], + salience_spec: QuestionSpec | None, +) -> SlotBinding: + """Binds a repeated slot assembled from scalar pointers (`headline`, `facts`, `form`).""" + absorbed = _collect_absorbed_siblings(pointers) + candidates = [ + p + for p in pointers + if _is_scalar_repeated_candidate(p, block_id, slot, pointers, used, absorbed) + ] + if not candidates: + return SlotBinding() + selected = _select_candidates_by_salience( + candidates, slot, salience_scores, salience_spec + ) + items = tuple(_build_scalar_item_mapping(ptr, slot, pointers) for ptr in selected) + return SlotBinding(items=items) + + +def _resolve_block_pattern( + spec: BlockSpec, capabilities: PatternCapabilities +) -> tuple[str, dict[str, str]] | None: + """Walks `spec.fallback` against `capabilities`, returning ``(pattern, preset_knobs)``.""" + candidates = (spec.pattern, *spec.fallback) + for entry in candidates: + if entry in FALLBACK_TERMINALS: + return entry, {} + pat_name, _, knob_val = entry.partition(":") + if knob_val: + if capabilities.has_pattern(pat_name, knob_val): + return pat_name, {"layout": knob_val} + elif capabilities.has_pattern(pat_name): + return pat_name, {} + return None + + +def _evaluate_single_measure( + m_spec: MeasureSpec, + bindings: BlockBindings, + pointers_by_path: Mapping[str, PointerSummary], +) -> str | None: + """Evaluates a single `MeasureSpec` against `bindings`.""" + parts = m_spec.derived_from.split(".") + if len(parts) != 3 or parts[1] != "hints": + return None + slot_binding = bindings.get(parts[0]) + ptr = ( + pointers_by_path.get(slot_binding.pointer or "") + if slot_binding is not None + else None + ) + raw_val = ptr.hints.get(parts[2]) if ptr is not None else None + if isinstance(raw_val, (int, float)): + return m_spec.level_for(float(raw_val)) + return None + + +def _compute_block_measures( + spec: BlockSpec, + bindings: BlockBindings, + pointers_by_path: Mapping[str, PointerSummary], +) -> dict[str, str]: + """Computes `MeasureSpec` levels (such as `prose.length`) from bound slots.""" + computed: dict[str, str] = {} + for m_name, m_spec in spec.measures.items(): + level = _evaluate_single_measure(m_spec, bindings, pointers_by_path) + if level is not None: + computed[m_name] = level + return computed + + +def _derive_from_key_hint(primary_ptr: PointerSummary, key_hint_map: Any) -> str | None: + """Matches `primary_ptr` key or `keyHint` against `key_hint_map`.""" + if not isinstance(key_hint_map, Mapping): + return None + hint = str(primary_ptr.hints.get("keyHint", "")).lower() + if hint in key_hint_map: + return str(key_hint_map[hint]) + low_key = primary_ptr.key.lower() + for k, derived in key_hint_map.items(): + if k in low_key: + return str(derived) + return None + + +def _derive_from_aspect_ratio( + primary_ptr: PointerSummary, aspect_map: Any +) -> str | None: + """Matches `primary_ptr.hints['aspectRatio']` against `aspect_map`.""" + ratio = primary_ptr.hints.get("aspectRatio") + if not isinstance(aspect_map, Mapping) or not isinstance(ratio, (int, float)): + return None + for thresh_str, derived in aspect_map.get("under", {}).items(): + if float(ratio) < float(thresh_str): + return str(derived) + for thresh_str, derived in aspect_map.get("over", {}).items(): + if float(ratio) > float(thresh_str): + return str(derived) + return None + + +def _derive_anatomy_from_hints( + q_spec: QuestionSpec, + bindings: BlockBindings, + pointers_by_path: Mapping[str, PointerSummary], +) -> str | None: + """Evaluates `q_spec.derived_when` against the block's primary bound pointer.""" + if not q_spec.derived_when: + return None + primary_ptr = next( + (pointers_by_path[p] for p in bindings.pointers() if p in pointers_by_path), + None, + ) + if primary_ptr is None: + return None + from_key = _derive_from_key_hint(primary_ptr, q_spec.derived_when.get("keyHint")) + if from_key is not None: + return from_key + return _derive_from_aspect_ratio( + primary_ptr, q_spec.derived_when.get("aspectRatio") + ) + + +def _find_matching_item_label( + field_name: str, + allowed: set[str], + bindings: BlockBindings, + pointers_by_path: Mapping[str, PointerSummary], +) -> str | None: + """Finds the label of the first bound item whose `field_name` has a type in `allowed`.""" + for slot_binding in bindings.slots.values(): + for item in slot_binding.items: + sub = item.get(field_name) + ptr = pointers_by_path.get(sub.pointer or "") if sub is not None else None + if ptr is not None and ptr.semantic_type in allowed: + return ptr.label or ptr.key + return None + + +def _anatomy_applies( + q_spec: QuestionSpec, + bindings: BlockBindings, + pointers_by_path: Mapping[str, PointerSummary], +) -> tuple[bool, dict[str, str]]: + """Checks `q_spec.applies_when` and returns placeholder values if applicable.""" + if not q_spec.applies_when: + return True, {} + for field_name, required_sem in q_spec.applies_when.items(): + allowed = {required_sem} if isinstance(required_sem, str) else set(required_sem) + matched_label = _find_matching_item_label( + field_name, allowed, bindings, pointers_by_path + ) + if matched_label is not None: + return True, {"label": matched_label} + return False, {} + + +def _filter_anatomy_options( + q_spec: QuestionSpec, capabilities: PatternCapabilities +) -> tuple[tuple[str, ...], tuple[str, ...]]: + """Removes choice options whose `pattern:.` requirement fails.""" + options: list[str] = [] + texts: list[str] = [] + for opt_id, desc in q_spec.options.items(): + reqs = q_spec.requires.get(opt_id, ()) + supported = True + for req in reqs: + match = _PATTERN_VARIANT_REQ_RE.match(req) + if match is not None and not capabilities.has_pattern( + match.group(1), match.group(2) + ): + supported = False + break + if supported: + options.append(opt_id) + texts.append(desc) + return tuple(options), tuple(texts) + + +def _expected_score(answer: DecisionAnswer) -> float: + """Returns `answer.expected` or computes the mean index from `distribution`.""" + if answer.expected is not None: + return float(answer.expected) + return sum( + idx * prob + for idx, (_, prob) in enumerate(answer.distribution.probabilities.items()) + ) + + +def _prominence_level(score: float) -> str: + """Maps a `picture.prominence` expected score in `[0, 3]` to its knob name.""" + levels = ("mark", "supporting", "leading", "full") + idx = min(max(int(score + 0.5), 0), len(levels) - 1) + return levels[idx] + + +def _single_requirement_holds( + req: str, + bindings: BlockBindings, + capabilities: PatternCapabilities, + actions_allowed: bool, + has_image: bool, +) -> bool: + """Checks one entry of a question option's `requires` list.""" + if req == "actions_allowed": + return actions_allowed + match = _PATTERN_VARIANT_REQ_RE.match(req) + if match is not None: + return capabilities.has_pattern(match.group(1), match.group(2)) + if req == "picture": + items = bindings.get("items") + pic_bound = ( + items is not None + and "picture" in items.fields + and items.fields["picture"].bound + ) + return has_image and (pic_bound or bindings.is_bound("picture")) + return bindings.is_bound(req) + + +def _option_requirements_hold( + reqs: Sequence[str], + bindings: BlockBindings, + capabilities: PatternCapabilities, + actions_allowed: bool, + pointers: Sequence[PointerSummary], +) -> bool: + """Checks whether all `requires` entries for a choice option are satisfied.""" + has_image = any(p.semantic_type in {"image_url", "media_object"} for p in pointers) + return all( + _single_requirement_holds( + req, bindings, capabilities, actions_allowed, has_image + ) + for req in reqs + ) + + +# --------------------------------------------------------------------------- +# The 11 Grammar Rules (`apply_`) +# --------------------------------------------------------------------------- + + +def apply_required_block_wins( + plan: LayoutPlan, + state: PlannerState, +) -> LayoutPlan: + """Rule `required-block-wins`: `!` blocks are present whatever their gate says.""" + archetype = state.selected_archetype + if archetype is None: + return plan + by_id = {b.block_id: b for b in plan.blocks} + for ref in archetype.blocks: + if ref.requirement != "required": + continue + if ref.id not in by_id: + prob = state.gate_probabilities.get(ref.id, 1.0) + by_id[ref.id] = PlannedBlock( + block_id=ref.id, + pattern=ref.id, + probability=prob, + ) + ordered = tuple(by_id[ref.id] for ref in archetype.blocks if ref.id in by_id) + return replace(plan, blocks=ordered) + + +def apply_at_least( + plan: LayoutPlan, + state: PlannerState, + grammar: ArchetypeGrammar | None = None, +) -> LayoutPlan: + """Rule `at-least`: top up with highest-probability expected blocks when needed.""" + archetype = state.selected_archetype + if archetype is None or len(plan.blocks) >= archetype.at_least: + return plan + gram = grammar or ArchetypeGrammar.default() + by_id = {b.block_id: b for b in plan.blocks} + candidates: list[tuple[float, int, BlockRef]] = [] + for idx, ref in enumerate(archetype.blocks): + if ref.requirement != "expected" or ref.id in by_id: + continue + spec = gram.block(ref.id) + if not _matches_shape(spec.shape, state.pointers): + continue + prob = state.gate_probabilities.get(ref.id, 0.0) + candidates.append((prob, -idx, ref)) + candidates.sort(reverse=True) + for prob, _, ref in candidates: + if len(by_id) >= archetype.at_least: + break + by_id[ref.id] = PlannedBlock( + block_id=ref.id, + pattern=gram.block(ref.id).pattern, + probability=prob, + ) + ordered = tuple(by_id[ref.id] for ref in archetype.blocks if ref.id in by_id) + return replace(plan, blocks=ordered) + + +def apply_fallback_must_end( + plan: LayoutPlan, + state: PlannerState, + grammar: ArchetypeGrammar | None = None, + capabilities: PatternCapabilities | None = None, +) -> LayoutPlan: + """Rule `fallback-must-end`: walks each block's fallback chain to a supported pattern.""" + del state + gram = grammar or ArchetypeGrammar.default() + caps = capabilities or _AllCapabilities() + updated: list[PlannedBlock] = [] + for block in plan.blocks: + spec = gram.block(block.block_id) + resolved = _resolve_block_pattern(spec, caps) + if resolved is None: + continue + pat_name, preset_knobs = resolved + knobs = {**preset_knobs, **block.variant_knobs} + updated.append(replace(block, pattern=pat_name, variant_knobs=knobs)) + return replace(plan, blocks=tuple(updated)) + + +def apply_catalog_eligibility( + plan: LayoutPlan, + state: PlannerState, +) -> LayoutPlan: + """Rule `catalog-eligibility`: required blocks must resolve on the catalog.""" + archetype = state.selected_archetype + if archetype is None: + return plan + present_ids = {b.block_id for b in plan.blocks} + for req_id in archetype.required_block_ids(): + if req_id not in present_ids: + state.required_block_missing = True + return plan + + +def apply_pointer_once_per_region( + plan: LayoutPlan, + state: PlannerState, + planner: LayoutPlanner, +) -> LayoutPlan: + """Rule `pointer-once-per-region`: blocks claim pointers in archetype order.""" + used: set[str] = set(state.page_claimed_pointers) + absorbed = _collect_absorbed_siblings(state.pointers) + updated: list[PlannedBlock] = [] + for block in plan.blocks: + spec = planner.grammar.block(block.block_id) + brief_sec = ( + state.brief.section(block.block_id) if state.brief is not None else None + ) + preferred = brief_sec.pointers if brief_sec is not None else () + bindings = planner.bind_slots( + spec, + state.pointers, + used, + salience_scores=state.salience_scores, + payload=state.payload, + intent=state.intent, + preferred_paths=preferred, + ) + if block.block_id == "prose" and state.copy is not None and state.copy.summary: + body_slot = bindings.get("body") + is_real_prose = False + if body_slot is not None and body_slot.pointer: + by_path = {p.path: p for p in state.pointers} + ptr_summary = by_path.get(body_slot.pointer) + if ptr_summary is not None and ( + ptr_summary.semantic_type + in {SemanticType.LONG_TEXT, SemanticType.MARKDOWN} + or any( + pref in ptr_summary.key.lower() + for pref in ( + "summary", + "description", + "body", + "overview", + "notes", + "article", + ) + ) + ): + is_real_prose = True + if not is_real_prose: + bound_slots = dict(bindings.slots) + bound_slots["body"] = SlotBinding(literal=state.copy.summary) + bindings = BlockBindings(slots=bound_slots) + for ptr_path in bindings.pointers(): + used.add(ptr_path) + if ptr_path in absorbed: + continue + knobs, instances = planner._resolve_block_questions( + spec, + bindings, + state, + actions_allowed=plan.actions_allowed, + preset_knobs=block.variant_knobs, + rng=state.rng, + ) + updated.append( + replace( + block, + bindings=bindings, + variant_knobs=knobs, + instances=instances, + ) + ) + return replace(plan, blocks=tuple(updated)) + + +def _adjust_collection_picture_layout( + block: PlannedBlock, has_image: bool +) -> PlannedBlock: + """Downgrades `collection` visual layouts to `rows` when no picture is bound.""" + if block.block_id != "collection" or block.variant_knobs.get("layout") not in { + "cards", + "grid", + "reel", + }: + return block + items = block.bindings.get("items") + has_pic_field = ( + items is not None + and "picture" in items.fields + and items.fields["picture"].bound + ) + if has_image and has_pic_field: + return block + return replace(block, variant_knobs={**block.variant_knobs, "layout": "rows"}) + + +def _find_unused_mark_pointer( + pointers: Sequence[PointerSummary], claimed: set[str] +) -> SlotBinding: + """Finds an unclaimed logo, icon, or avatar `image_url` pointer for `page.mark`.""" + for ptr in pointers: + if ( + ptr.path not in claimed + and ptr.semantic_type == "image_url" + and _is_avoided_key(ptr, tuple(_MARK_KEY_HINTS)) + ): + return SlotBinding(pointer=ptr.path) + return SlotBinding() + + +def _keep_picture_block( + block: PlannedBlock, has_image: bool, mark_binding: SlotBinding +) -> tuple[bool, SlotBinding]: + """Evaluates whether to keep a `picture` block and updates `page.mark`.""" + pic_slot = block.bindings.get("picture") + if not has_image or pic_slot is None or not pic_slot.bound: + return False, mark_binding + if block.variant_knobs.get("prominence") == "mark": + if not mark_binding.bound and pic_slot.pointer: + mark_binding = SlotBinding(pointer=pic_slot.pointer) + return False, mark_binding + return True, mark_binding + + +def apply_pictures_need_a_look( + plan: LayoutPlan, + state: PlannerState, +) -> LayoutPlan: + """Rule `pictures-need-a-look`: enforces image requirements and assigns `page.mark`.""" + has_image = any( + p.semantic_type in {"image_url", "media_object"} for p in state.pointers + ) + claimed: set[str] = set() + updated_blocks: list[PlannedBlock] = [] + mark_binding = plan.page.mark + for block in plan.blocks: + if block.block_id == "picture": + keep, mark_binding = _keep_picture_block(block, has_image, mark_binding) + if not keep: + continue + adjusted = _adjust_collection_picture_layout(block, has_image) + claimed.update(adjusted.bindings.pointers()) + updated_blocks.append(adjusted) + if not mark_binding.bound: + mark_binding = _find_unused_mark_pointer(state.pointers, claimed) + page = replace(plan.page, mark=mark_binding) + return replace(plan, blocks=tuple(updated_blocks), page=page) + + +def _is_pointer_covered(path: str, claimed: set[str]) -> bool: + """Returns whether `path` or any ancestor/descendant pointer is in `claimed`.""" + if path in claimed: + return True + prefix = f"{path}/" + return any(cp.startswith(prefix) or path.startswith(f"{cp}/") for cp in claimed) + + +def apply_no_orphaned_pointers( + plan: LayoutPlan, + state: PlannerState, + planner: LayoutPlanner, +) -> LayoutPlan: + """Recovers unclaimed top-level scalar or array pointers into `facts` or `collection`.""" + claimed: set[str] = ( + set(state.page_claimed_pointers) + | set(plan.page.title.pointers()) + | set(plan.page.subtitle.pointers()) + | set(plan.page.mark.pointers()) + | _collect_absorbed_siblings(state.pointers) + ) + for b in plan.blocks: + claimed.update(b.bindings.pointers()) + + blocks = list(plan.blocks) + present_ids = {b.block_id for b in blocks} + + # 1. Recover an unclaimed non-action data array into `collection` when no list block is present. + if not planner.config.threshold_overrides and not ( + present_ids & {"collection", "steps", "comparison"} + ): + uncovered_arrays = [ + p + for p in state.pointers + if p.value_type == "array" + and p.cardinality > 0 + and not _is_action_pointer(p) + and not _is_pointer_covered(p.path, claimed) + and "image_url" not in p.element_semantic_types.values() + ] + if uncovered_arrays: + col_spec = planner.grammar.block("collection") + resolved_col = _resolve_block_pattern(col_spec, planner._capabilities) + if resolved_col is not None: + col_pat, col_preset = resolved_col + col_bindings = planner.bind_slots( + col_spec, + state.pointers, + set(claimed), + salience_scores=state.salience_scores, + payload=state.payload, + intent=state.intent, + ) + if col_bindings.is_bound("items"): + col_knobs, col_inst = planner._resolve_block_questions( + col_spec, + col_bindings, + state, + actions_allowed=plan.actions_allowed, + preset_knobs=col_preset, + rng=state.rng, + ) + blocks.append( + PlannedBlock( + block_id="collection", + pattern=col_pat, + bindings=col_bindings, + variant_knobs=col_knobs, + instances=col_inst, + ) + ) + claimed.update(col_bindings.pointers()) + present_ids.add("collection") + + # 2. Recover unclaimed top-level scalar fact pointers into `facts` (or `prose` fallback rows). + prose_absent = "prose" not in present_ids + prose_ans = state.answers_by_id.get("gate:prose") + allow_prose_fallback_in_facts = ( + prose_absent + and plan.urgency < 1.5 + and (prose_ans is None or prose_ans.yes >= 0.50) + ) + uncovered_scalars = [ + p + for p in state.pointers + if not p.parent + and p.value_type in {"string", "number", "boolean"} + and not _is_nested_mutable_setting(p, state.pointers) + and not _is_pointer_covered(p.path, claimed) + and ( + p.semantic_type not in _NON_FACT_SEMANTIC_TYPES + or ( + allow_prose_fallback_in_facts + and p.semantic_type in {"long_text", "markdown", "code"} + ) + ) + ] + if uncovered_scalars: + facts_spec = planner.grammar.block("facts") + resolved_facts = _resolve_block_pattern(facts_spec, planner._capabilities) + if resolved_facts is not None: + facts_pat, facts_preset = resolved_facts + extra_rows = tuple( + _build_scalar_item_mapping( + ptr, facts_spec.slots["rows"], state.pointers + ) + for ptr in uncovered_scalars + ) + if "facts" in present_ids: + for idx, b in enumerate(blocks): + if b.block_id == "facts": + existing_rows = b.bindings.get("rows") + merged_items = ( + (*existing_rows.items, *extra_rows) + if existing_rows is not None + else extra_rows + ) + new_bindings = BlockBindings( + slots={ + **b.bindings.slots, + "rows": SlotBinding(items=merged_items), + } + ) + blocks[idx] = replace(b, bindings=new_bindings) + claimed.update(new_bindings.pointers()) + break + else: + facts_bindings = BlockBindings( + slots={"rows": SlotBinding(items=extra_rows)} + ) + facts_knobs, facts_inst = planner._resolve_block_questions( + facts_spec, + facts_bindings, + state, + actions_allowed=plan.actions_allowed, + preset_knobs=facts_preset, + rng=state.rng, + ) + insert_idx = len(blocks) + for idx, b in enumerate(blocks): + if b.block_id in {"actions", "compose"}: + insert_idx = idx + break + blocks.insert( + insert_idx, + PlannedBlock( + block_id="facts", + pattern=facts_pat, + bindings=facts_bindings, + variant_knobs=facts_knobs, + instances=facts_inst, + ), + ) + claimed.update(facts_bindings.pointers()) + + return replace(plan, blocks=tuple(blocks)) + + +def _is_collection_picture_sparse( + items: SlotBinding | None, payload: Mapping[str, Any] +) -> bool: + """Returns whether `picture` is unbound or missing on over half of `items`.""" + pic_field = items.fields.get("picture") if items is not None else None + if pic_field is None or not pic_field.bound: + return True + if items is None or not items.pointer or not payload: + return False + arr_val = _resolve_pointer_value(payload, items.pointer) + if ( + not isinstance(arr_val, Sequence) + or isinstance(arr_val, (str, bytes)) + or not arr_val + ): + return False + key = pic_field.pointer or "" + with_pic = sum(1 for el in arr_val if isinstance(el, Mapping) and bool(el.get(key))) + return with_pic * 2 < len(arr_val) + + +def apply_leading_all_or_none( + plan: LayoutPlan, + state: PlannerState, +) -> LayoutPlan: + """Rule `leading-all-or-none`: falls back to `icon` or `none` if pictures are sparse.""" + updated: list[PlannedBlock] = [] + for block in plan.blocks: + if block.block_id == "collection" and block.variant_knobs.get("leading") in { + "thumbnail", + "avatar", + }: + items = block.bindings.get("items") + if _is_collection_picture_sparse(items, state.payload): + fallback = ( + "icon" if items is not None and "icon" in items.fields else "none" + ) + block = replace( + block, + variant_knobs={**block.variant_knobs, "leading": fallback}, + ) + updated.append(block) + return replace(plan, blocks=tuple(updated)) + + +def _degrade_group_instances( + instances: Mapping[str, Mapping[str, str]], +) -> dict[str, dict[str, str]]: + """Degrades interactive `groups` row kinds (`switch`, `danger`, `navigation`) to `value`.""" + degraded: dict[str, dict[str, str]] = {} + for elem_key, elem_map in instances.items(): + row_kind = elem_map.get("row_kind") + if row_kind in {"switch", "danger", "navigation"}: + degraded[elem_key] = {**elem_map, "row_kind": "value"} + else: + degraded[elem_key] = dict(elem_map) + return degraded + + +def _gate_single_block( + block: PlannedBlock, required_ids: set[str], state: PlannerState +) -> PlannedBlock | None: + """Applies the `actions_allowed == False` gate to one `PlannedBlock`.""" + if block.block_id in {"actions", "compose"}: + if block.block_id in required_ids and block.bindings.pointers(): + state.action_gate_blocked = True + return None + if block.block_id == "filters": + return None + if ( + block.block_id == "collection" + and block.variant_knobs.get("trailing") == "button" + ): + return replace(block, variant_knobs={**block.variant_knobs, "trailing": "none"}) + if block.block_id == "groups": + return replace(block, instances=_degrade_group_instances(block.instances)) + return block + + +def apply_actions_gate( + plan: LayoutPlan, + state: PlannerState, + floor: float, + cap: float, +) -> LayoutPlan: + """Rule `actions-gate`: computes `actions_allowed` and gates interactive blocks. + + The gate is ``floor + (cap - floor) * stakes / 3``; `floor` and `cap` are + the grammar's ``actionGateFloor`` and ``actionGateCap`` thresholds. + """ + gate = floor + (cap - floor) * (plan.stakes / 3.0) + allowed = plan.confidence >= gate + plan = replace(plan, actions_allowed=allowed) + if allowed: + return plan + archetype = state.selected_archetype + required_ids = set(archetype.required_block_ids()) if archetype else set() + updated: list[PlannedBlock] = [] + for block in plan.blocks: + gated = _gate_single_block(block, required_ids, state) + if gated is not None: + updated.append(gated) + return replace(plan, blocks=tuple(updated)) + + +def _extract_button_records( + raw_items: Sequence[Mapping[str, SlotBinding]], + instances: Mapping[str, Mapping[str, str]], + stakes: float, +) -> list[tuple[Mapping[str, SlotBinding], str, bool, bool]]: + """Builds ``(item, label, is_primary, is_destructive)`` tuples for action buttons.""" + records: list[tuple[Mapping[str, SlotBinding], str, bool, bool]] = [] + seen_primary = False + for idx, item in enumerate(raw_items): + label = str(item["label"].literal or idx) + inst = instances.get(label) or instances.get(str(idx)) or {} + is_dest = inst.get("destructive") == "true" + is_prim = ( + inst.get("primary") == "true" + and not seen_primary + and not (stakes >= 2.0 and is_dest) + ) + if is_prim: + seen_primary = True + records.append((item, label, is_prim, is_dest)) + return records + + +def _reorder_and_enforce_actions(block: PlannedBlock, stakes: float) -> PlannedBlock: + """Enforces at most one primary button and demotes/reorders destructive buttons.""" + buttons = block.bindings.get("buttons") + if buttons is None or not buttons.items: + return block + records = _extract_button_records(buttons.items, block.instances, stakes) + sort_idx = 3 if (stakes >= 2.0 and any(r[3] for r in records)) else 2 + records.sort(key=lambda r: (1 if r[sort_idx] else 0)) + new_items = tuple(r[0] for r in records) + new_instances: dict[str, dict[str, str]] = {} + for idx, (_, label, is_prim, is_dest) in enumerate(records): + entry = { + "primary": "true" if is_prim else "false", + "destructive": "true" if is_dest else "false", + } + new_instances[str(idx)] = entry + new_instances[label] = entry + new_buttons = replace(buttons, items=new_items) + new_bindings = BlockBindings(slots={**block.bindings.slots, "buttons": new_buttons}) + return replace(block, bindings=new_bindings, instances=new_instances) + + +def apply_one_primary_action( + plan: LayoutPlan, + state: PlannerState, +) -> LayoutPlan: + """Rule `one-primary-action`: at most one primary button; destructive demoted at high stakes.""" + del state + updated = tuple( + _reorder_and_enforce_actions(b, plan.stakes) if b.block_id == "actions" else b + for b in plan.blocks + ) + return replace(plan, blocks=updated) + + +def _terse_transform_block( + block: PlannedBlock, + prose_req: bool, + has_page_pattern: bool, +) -> PlannedBlock | None: + """Applies `urgency-terse` trimming to a single `PlannedBlock`.""" + if block.block_id == "prose" and not prose_req: + return None + if block.block_id == "headline": + items = block.bindings.get("items") + if items is not None and len(items.items) > 3: + trimmed = replace(items, items=items.items[:3]) + return replace( + block, + bindings=BlockBindings( + slots={**block.bindings.slots, "items": trimmed} + ), + ) + if block.block_id == "actions" and has_page_pattern: + return replace(block, variant_knobs={**block.variant_knobs, "sticky": "yes"}) + return block + + +def apply_urgency_terse( + plan: LayoutPlan, + state: PlannerState, + capabilities: PatternCapabilities | None = None, +) -> LayoutPlan: + """Rule `urgency-terse`: drops optional prose, caps headline at 3, sets sticky actions.""" + if plan.urgency < 1.5: + return plan + caps = capabilities or _AllCapabilities() + has_page = caps.has_pattern("page") + archetype = state.selected_archetype + prose_req = ( + archetype.requirement_of("prose") == "required" + if archetype is not None + else False + ) + updated: list[PlannedBlock] = [] + for block in plan.blocks: + transformed = _terse_transform_block(block, prose_req, has_page) + if transformed is not None: + updated.append(transformed) + has_actions = any(b.block_id == "actions" for b in updated) + page = ( + replace(plan.page, sticky_actions=True) + if (has_actions and has_page) + else plan.page + ) + return replace(plan, blocks=tuple(updated), page=page) + + +def _block_has_required_bindings(block: PlannedBlock, spec: BlockSpec) -> bool: + """Returns whether `block` bound all required slots (and at least one slot).""" + if not block.bindings.pointers() and not any( + b.bound for b in block.bindings.slots.values() + ): + return False + for slot_name, slot_spec in spec.slots.items(): + if slot_spec.required and not block.bindings.is_bound(slot_name): + return False + return True + + +def apply_no_empty_container( + plan: LayoutPlan, + state: PlannerState, + grammar: ArchetypeGrammar | None = None, +) -> LayoutPlan: + """Rule `no-empty-container`: drops blocks with unbound required slots.""" + gram = grammar or ArchetypeGrammar.default() + kept = tuple( + b + for b in plan.blocks + if _block_has_required_bindings(b, gram.block(b.block_id)) + ) + archetype = state.selected_archetype + if archetype is not None: + kept_ids = {b.block_id for b in kept} + for req_id in archetype.required_block_ids(): + if req_id not in kept_ids: + state.required_block_missing = True + if not kept: + state.required_block_missing = True + return replace(plan, blocks=kept) + + +class LayoutPlanner: + """Speculative single-batch layout planner for archetype-driven A2UI synthesis.""" + + def __init__( + self, + grammar: ArchetypeGrammar | None = None, + config: SynthesisConfig | None = None, + *, + capabilities: PatternCapabilities | None = None, + ) -> None: + self._grammar = grammar or ArchetypeGrammar.default() + self._config = config or SynthesisConfig() + self._capabilities: PatternCapabilities = ( + capabilities if capabilities is not None else _AllCapabilities() + ) + + @property + def grammar(self) -> ArchetypeGrammar: + """The `ArchetypeGrammar` governing this planner.""" + return self._grammar + + @property + def config(self) -> SynthesisConfig: + """The `SynthesisConfig` governing pair budgets and threshold overrides.""" + return self._config + + def threshold(self, name: str) -> float: + """The effective threshold `name`: a `config.threshold_overrides` entry, else the grammar's. + + Raises: + KeyError: If neither the overrides nor the grammar define `name`. + """ + override = self._config.threshold_overrides.get(name) + return override if override is not None else self._grammar.threshold(name) + + def bind_slots( + self, + spec: BlockSpec, + pointers: Sequence[PointerSummary], + used: set[str], + *, + salience_scores: Mapping[str, float] | None = None, + payload: Mapping[str, Any] | None = None, + intent: str = "", + preferred_paths: Sequence[str] = (), + ) -> BlockBindings: + """Deterministically binds `spec.slots` against `pointers` excluding `used`.""" + norm_pointers = _normalize_pointers(pointers) + local_used = set(used) + bound_slots: dict[str, SlotBinding] = {} + for slot_name, slot_spec in spec.slots.items(): + binding = self._bind_one_slot( + spec, + slot_spec, + norm_pointers, + local_used, + salience_scores=salience_scores or {}, + payload=payload or {}, + intent=intent, + preferred_paths=preferred_paths, + ) + if binding.bound: + bound_slots[slot_name] = binding + local_used.update(binding.pointers()) + return BlockBindings(slots=bound_slots) + + def _bind_one_slot( + self, + spec: BlockSpec, + slot: SlotSpec, + pointers: Sequence[PointerSummary], + used: set[str], + *, + salience_scores: Mapping[str, float], + payload: Mapping[str, Any], + intent: str, + preferred_paths: Sequence[str], + ) -> SlotBinding: + """Dispatches binding for a single `SlotSpec`.""" + if not slot.repeat: + return _bind_scalar_slot( + slot, pointers, used, preferred_paths=preferred_paths + ) + if slot.from_types == ("action",): + return _bind_actions_slot(slot, pointers, used, payload, intent) + if slot.from_types == ("object",): + return _bind_groups_slot(pointers, used) + if slot.from_types == ("array",): + return _bind_array_repeated_slot(spec.id, slot, pointers, used) + return _bind_scalar_repeated_slot( + spec.id, + slot, + pointers, + used, + salience_scores, + spec.salience, + ) + + def _is_required_block_viable( + self, + req_id: str, + pointers: Sequence[PointerSummary], + base_used: set[str], + ) -> bool: + """Returns whether required block `req_id` resolves and binds on `pointers`.""" + spec = self._grammar.block(req_id) + if _resolve_block_pattern(spec, self._capabilities) is None: + return False + if not _matches_shape(spec.shape, pointers): + return False + bindings = self.bind_slots(spec, pointers, set(base_used)) + return _block_has_required_bindings( + PlannedBlock(block_id=req_id, pattern=spec.pattern, bindings=bindings), + spec, + ) + + def _default_eligible( + self, pointers: Sequence[PointerSummary] + ) -> tuple[LayoutArchetype, ...]: + """Filters `grammar.archetypes` by shape, catalog support, and required slots.""" + page_ptr = _page_title_pointer(pointers) + base_used = {page_ptr.path} if page_ptr is not None else set() + return tuple( + arch + for arch in self._grammar.archetypes + if _matches_shape(arch.shape, pointers) + and all( + self._is_required_block_viable(req_id, pointers, base_used) + for req_id in arch.required_block_ids() + ) + ) + + def _satisfied_block_count( + self, arch: LayoutArchetype, pointers: Sequence[PointerSummary] + ) -> int: + """Counts how many blocks in `arch` satisfy their shape filter on `pointers`.""" + page_ptr = _page_title_pointer(pointers) + base_used = {page_ptr.path} if page_ptr is not None else set() + count = 0 + for ref in arch.blocks: + spec = self._grammar.block(ref.id) + if spec.shape.is_empty: + bindings = self.bind_slots(spec, pointers, set(base_used)) + if _block_has_required_bindings( + PlannedBlock( + block_id=ref.id, pattern=spec.pattern, bindings=bindings + ), + spec, + ): + count += 1 + elif spec.id == "actions": + if any(_is_action_pointer(p) for p in pointers): + count += 1 + elif _matches_shape(spec.shape, pointers): + count += 1 + return count + + def prior_archetypes( + self, + eligible: Sequence[LayoutArchetype], + pointers: Sequence[PointerSummary], + brief: LayoutBrief | None = None, + ) -> tuple[LayoutArchetype, ...]: + """Orders `eligible` archetypes by brief pin first, then satisfied block shapes.""" + norm = _normalize_pointers(pointers) + pinned_families = ( + {r for r in brief.roles() if r in self._grammar.families()} + if brief is not None + else set() + ) + pinned_blocks = ( + {r for r in brief.roles() if r in self._grammar.blocks} + if brief is not None + else set() + ) + grammar_order = {a.id: idx for idx, a in enumerate(self._grammar.archetypes)} + + def _sort_key(arch: LayoutArchetype) -> tuple[int, int, int]: + is_pinned = 0 + if arch.family in pinned_families: + is_pinned = 2 + elif pinned_blocks and pinned_blocks.issubset(set(arch.block_ids())): + is_pinned = 1 + satisfied = self._satisfied_block_count(arch, norm) + return (-is_pinned, -satisfied, grammar_order.get(arch.id, 999)) + + return tuple(sorted(eligible, key=_sort_key)) + + def build_batch( + self, + intent: str, + pointers: Sequence[PointerSummary], + *, + eligible: Sequence[LayoutArchetype] | None = None, + brief: LayoutBrief | None = None, + payload: Mapping[str, Any] | None = None, + copy: AuthoredCopy | None = None, + ) -> tuple[DecisionBatch, PlannerState]: + """Builds a speculative `DecisionBatch` and `PlannerState` for one surface. + + Args: + intent: The author's natural-language intent. + pointers: Payload pointer summaries from `inspect_payload_pointers`. + eligible: Archetypes to consider; defaults to those whose shape and + required blocks the payload satisfies. + brief: Optional `LayoutBrief` pinning roles to pointers. + payload: The payload itself, used to read action labels and + option values; questions degrade to key-derived text without it. + copy: Optional authored title and summary strings supplied in the + decision block. + """ + norm_pointers = _normalize_pointers(pointers) + elig = ( + tuple(eligible) + if eligible is not None + else self._default_eligible(norm_pointers) + ) + prior = self.prior_archetypes(elig, norm_pointers, brief) + state = PlannerState( + intent=intent, + pointers=norm_pointers, + eligible=elig, + prior_archetypes=tuple(a.id for a in prior), + brief=brief, + batch=DecisionBatch(shared_context={}, questions=()), + payload=dict(payload) if payload is not None else {}, + copy=copy, + ) + questions: list[DecisionQuestion] = [] + self._append_job_questions(questions, state) + self._append_archetype_questions(questions, state) + self._append_gate_and_anatomy_questions(questions, state) + self._append_salience_questions(questions, state) + self._append_instance_questions(questions, state, prior[:2]) + batch = DecisionBatch( + shared_context={ + "intent": intent, + "pointers": [p.path for p in norm_pointers], + }, + questions=tuple(questions), + ) + state.batch = batch + return batch, state + + def build_stage1_batch( + self, + intent: str, + pointers: Sequence[PointerSummary], + *, + eligible: Sequence[LayoutArchetype] | None = None, + brief: LayoutBrief | None = None, + payload: Mapping[str, Any] | None = None, + copy: AuthoredCopy | None = None, + ) -> tuple[DecisionBatch, PlannerState]: + """Builds Stage 1 (`family`, `stakes`, `urgency`, and `archetype:*`) of a two-stage batch.""" + norm_pointers = _normalize_pointers(pointers) + elig = ( + tuple(eligible) + if eligible is not None + else self._default_eligible(norm_pointers) + ) + prior = self.prior_archetypes(elig, norm_pointers, brief) + state = PlannerState( + intent=intent, + pointers=norm_pointers, + eligible=elig, + prior_archetypes=tuple(a.id for a in prior), + brief=brief, + batch=DecisionBatch(shared_context={}, questions=()), + payload=dict(payload) if payload is not None else {}, + copy=copy, + ) + questions: list[DecisionQuestion] = [] + self._append_job_questions(questions, state) + self._append_archetype_questions(questions, state) + batch = DecisionBatch( + shared_context={ + "intent": intent, + "pointers": [p.path for p in norm_pointers], + }, + questions=tuple(questions), + ) + state.batch = batch + return batch, state + + def build_stage2_batch( + self, + state: PlannerState, + stage1_answers: Sequence[DecisionAnswer], + ) -> DecisionBatch: + """Builds Stage 2 (`gate`, `anatomy`, `salience`, and `instance` for the winning archetype).""" + self._validate_and_index_answers(state, stage1_answers) + family = self._read_family(state) + archetype = ( + self._read_archetype(state, family)[0] if family is not None else None + ) + state.trace.clear() + if archetype is None: + return DecisionBatch( + shared_context=dict(state.batch.shared_context), questions=() + ) + + questions: list[DecisionQuestion] = list(state.batch.questions) + seen_ids = {q.id for q in questions} + pinned_blocks = ( + {r for r in state.brief.roles() if r in self._grammar.blocks} + if state.brief is not None + else set() + ) + gated_blocks: list[BlockSpec] = [] + seen_block_ids: set[str] = set() + for ref in archetype.blocks: + if ref.id in seen_block_ids or self._is_redundant_optional_fallback( + ref, archetype + ): + continue + seen_block_ids.add(ref.id) + spec = self._grammar.block(ref.id) + if _matches_shape(spec.shape, state.pointers): + gated_blocks.append(spec) + + for spec in gated_blocks: + if spec.gate is not None and spec.id not in pinned_blocks: + self._try_add_question( + questions, + DecisionQuestion( + id=f"gate:{spec.id}", + kind=QuestionKind.BOOLEAN, + prompt=spec.gate.question, + context={"yes": spec.gate.yes, "no": spec.gate.no}, + allow_none=False, + ), + state, + seen_ids=seen_ids, + ) + self._append_anatomy_for_blocks(questions, gated_blocks, state, seen_ids) + if any(b.id in {"headline", "facts"} for b in gated_blocks): + page_ptr = _page_title_pointer(state.pointers) + absorbed = _collect_absorbed_siblings(state.pointers) + sal_candidates = [ + ptr + for ptr in state.pointers + if self._is_salience_candidate(ptr, page_ptr, absorbed, state) + ] + if len(sal_candidates) > 3: + self._append_salience_questions(questions, state) + self._append_instance_questions(questions, state, (archetype,)) + stage1_len = len(state.batch.questions) + stage2_questions = tuple(questions[stage1_len:]) + state.batch = DecisionBatch( + shared_context=dict(state.batch.shared_context), + questions=tuple(questions), + ) + return DecisionBatch( + shared_context=dict(state.batch.shared_context), + questions=stage2_questions, + ) + + def _try_add_question( + self, + questions: list[DecisionQuestion], + question: DecisionQuestion, + state: PlannerState, + *, + seen_ids: set[str], + ) -> bool: + """Appends `question` if its ID is unseen and within `config.max_pairs`.""" + if question.id in seen_ids: + return True + current_pairs = sum(len(q.candidates()) for q in questions) + if current_pairs + len(question.candidates()) > self._config.max_pairs: + state.budget_exhausted = True + return False + seen_ids.add(question.id) + questions.append(question) + return True + + def _pinned_families(self, state: PlannerState) -> list[str]: + """Returns family roles pinned by `state.brief`.""" + if state.brief is None: + return [] + return [r for r in state.brief.roles() if r in self._grammar.families()] + + def _append_job_questions( + self, questions: list[DecisionQuestion], state: PlannerState + ) -> None: + """Emits `family` (unless brief-pinned), `stakes`, and `urgency` questions.""" + seen_ids = {q.id for q in questions} + if not self._pinned_families(state): + fam_spec = self._grammar.job["family"] + self._try_add_question( + questions, + DecisionQuestion( + id="family", + kind=QuestionKind.CHOICE, + prompt=fam_spec.question, + options=tuple(fam_spec.options), + option_texts=tuple(fam_spec.options.values()), + allow_none=fam_spec.allow_none, + ), + state, + seen_ids=seen_ids, + ) + for score_id in ("stakes", "urgency"): + spec = self._grammar.job[score_id] + self._try_add_question( + questions, + DecisionQuestion( + id=score_id, + kind=QuestionKind.SCORE, + prompt=spec.question, + options=spec.levels, + allow_none=False, + ), + state, + seen_ids=seen_ids, + ) + + def _append_archetype_questions( + self, questions: list[DecisionQuestion], state: PlannerState + ) -> None: + """Emits one `archetype:` question per family with eligible archetypes.""" + seen_ids = {q.id for q in questions} + pinned = self._pinned_families(state) + families_to_ask = tuple(pinned) if pinned else self._grammar.families() + for fam in families_to_ask: + fam_archs = [a for a in state.eligible if a.family == fam] + if not fam_archs: + continue + self._try_add_question( + questions, + DecisionQuestion( + id=f"archetype:{fam}", + kind=QuestionKind.CHOICE, + prompt=f"Which {fam} archetype best fits this surface?", + options=tuple(a.id for a in fam_archs), + option_texts=tuple(a.criteria for a in fam_archs), + allow_none=True, + ), + state, + seen_ids=seen_ids, + ) + + def _is_redundant_optional_fallback( + self, ref: BlockRef, archetype: LayoutArchetype + ) -> bool: + """Returns True when an optional block's unsupported pattern degrades to a sibling block.""" + if ref.requirement != "optional": + return False + spec = self._grammar.block(ref.id) + if self._capabilities.has_pattern(spec.pattern): + return False + resolved = _resolve_block_pattern(spec, self._capabilities) + if resolved is None: + return True + fb_pat, _ = resolved + return fb_pat != spec.pattern and fb_pat in set(archetype.block_ids()) + + def _collect_gated_blocks(self, state: PlannerState) -> list[BlockSpec]: + """Returns unique `BlockSpec`s from `state.eligible` whose payload shape holds.""" + gated: list[BlockSpec] = [] + seen: set[str] = set() + for arch in state.eligible: + for ref in arch.blocks: + if ref.id in seen or self._is_redundant_optional_fallback(ref, arch): + continue + seen.add(ref.id) + spec = self._grammar.block(ref.id) + if _matches_shape(spec.shape, state.pointers): + gated.append(spec) + return gated + + def _append_gate_and_anatomy_questions( + self, questions: list[DecisionQuestion], state: PlannerState + ) -> None: + """Emits `gate:` and `anatomy:.` questions.""" + seen_ids = {q.id for q in questions} + pinned_blocks = ( + {r for r in state.brief.roles() if r in self._grammar.blocks} + if state.brief is not None + else set() + ) + gated_blocks = self._collect_gated_blocks(state) + for spec in gated_blocks: + if spec.gate is not None and spec.id not in pinned_blocks: + self._try_add_question( + questions, + DecisionQuestion( + id=f"gate:{spec.id}", + kind=QuestionKind.BOOLEAN, + prompt=spec.gate.question, + context={"yes": spec.gate.yes, "no": spec.gate.no}, + allow_none=False, + ), + state, + seen_ids=seen_ids, + ) + self._append_anatomy_for_blocks(questions, gated_blocks, state, seen_ids) + + def _append_anatomy_for_blocks( + self, + questions: list[DecisionQuestion], + blocks: Sequence[BlockSpec], + state: PlannerState, + seen_ids: set[str], + ) -> None: + """Emits `anatomy:.` questions for `blocks`.""" + by_path = {p.path: p for p in state.pointers} + page_ptr = _page_title_pointer(state.pointers) + base_used = {page_ptr.path} if page_ptr is not None else set() + for spec in blocks: + bindings = self.bind_slots( + spec, + state.pointers, + set(base_used), + payload=state.payload, + intent=state.intent, + ) + for knob, q_spec in spec.anatomy.items(): + derived = _derive_anatomy_from_hints(q_spec, bindings, by_path) + if derived is not None: + state.derived_anatomy[(spec.id, knob)] = derived + continue + applies, fmt_vars = _anatomy_applies(q_spec, bindings, by_path) + if not applies or q_spec.options_from is not None: + continue + q_obj = self._build_anatomy_question(spec.id, knob, q_spec, fmt_vars) + if q_obj is not None: + self._try_add_question(questions, q_obj, state, seen_ids=seen_ids) + + def _build_anatomy_question( + self, + block_id: str, + knob: str, + q_spec: QuestionSpec, + fmt_vars: Mapping[str, str], + ) -> DecisionQuestion | None: + """Constructs a single `anatomy:.` `DecisionQuestion`.""" + q_id = f"anatomy:{block_id}.{knob}" + prompt = q_spec.question.format(**fmt_vars) if fmt_vars else q_spec.question + if q_spec.kind is QuestionKind.BOOLEAN: + return DecisionQuestion( + id=q_id, + kind=QuestionKind.BOOLEAN, + prompt=prompt, + context={"yes": q_spec.yes, "no": q_spec.no}, + allow_none=False, + ) + if q_spec.kind is QuestionKind.SCORE: + return DecisionQuestion( + id=q_id, + kind=QuestionKind.SCORE, + prompt=prompt, + options=q_spec.levels, + allow_none=False, + ) + options, texts = _filter_anatomy_options(q_spec, self._capabilities) + if not options: + return None + return DecisionQuestion( + id=q_id, + kind=QuestionKind.CHOICE, + prompt=prompt, + options=options, + option_texts=texts, + allow_none=q_spec.allow_none, + ) + + def _is_salience_candidate( + self, + ptr: PointerSummary, + page_ptr: PointerSummary | None, + absorbed: set[str], + state: PlannerState, + ) -> bool: + """Returns whether `ptr` should receive a `salience:` question.""" + if page_ptr is not None and ptr.path == page_ptr.path: + return False + if ptr.path in absorbed or (ptr.path.count("/") >= 2 and "/0/" in ptr.path): + return False + if _is_nested_mutable_setting(ptr, state.pointers): + return False + if ptr.semantic_type in _NON_FACT_SEMANTIC_TYPES: + return False + headline_types = self._grammar.block("headline").slots["items"].from_types + facts_types = self._grammar.block("facts").slots["rows"].from_types + return _pointer_matches_types(ptr, headline_types) or _pointer_matches_types( + ptr, facts_types + ) + + def _append_salience_questions( + self, questions: list[DecisionQuestion], state: PlannerState + ) -> None: + """Emits `salience:` score questions for candidate scalar pointers.""" + has_salience_block = any( + ref.id in {"headline", "facts", "collection"} + for arch in state.eligible + for ref in arch.blocks + ) + sal_spec = self._grammar.block("headline").salience + if not has_salience_block or sal_spec is None: + return + seen_ids = {q.id for q in questions} + page_ptr = _page_title_pointer(state.pointers) + absorbed = _collect_absorbed_siblings(state.pointers) + added = 0 + for ptr in state.pointers: + if not self._is_salience_candidate(ptr, page_ptr, absorbed, state): + continue + if added >= _MAX_SALIENCE_QUESTIONS: + state.budget_exhausted = True + break + if self._try_add_question( + questions, + DecisionQuestion( + id=f"salience:{ptr.path}", + kind=QuestionKind.SCORE, + prompt=sal_spec.question.format(label=ptr.label or ptr.key), + options=sal_spec.levels, + allow_none=False, + ), + state, + seen_ids=seen_ids, + ): + added += 1 + + def _append_instance_questions( + self, + questions: list[DecisionQuestion], + state: PlannerState, + top_archetypes: Sequence[LayoutArchetype], + ) -> None: + """Emits speculative `instance:.:` questions for `top_archetypes`.""" + seen_ids = {q.id for q in questions} + page_ptr = _page_title_pointer(state.pointers) + base_used = {page_ptr.path} if page_ptr is not None else set() + seen_blocks: set[str] = set() + for arch in top_archetypes: + for ref in arch.blocks: + if ref.id in seen_blocks: + continue + seen_blocks.add(ref.id) + spec = self._grammar.block(ref.id) + if not spec.instance or not _matches_shape(spec.shape, state.pointers): + continue + bindings = self.bind_slots( + spec, + state.pointers, + set(base_used), + payload=state.payload, + intent=state.intent, + ) + for q_obj in self._build_block_instance_questions( + spec, bindings, state + ): + self._try_add_question(questions, q_obj, state, seen_ids=seen_ids) + + def _build_block_instance_questions( + self, + spec: BlockSpec, + bindings: BlockBindings, + state: PlannerState, + ) -> list[DecisionQuestion]: + """Builds the list of `DecisionQuestion` objects for `spec.instance`.""" + if spec.id in {"banner", "outcome"}: + return self._build_scalar_instance_questions(spec, bindings, state) + if spec.id == "actions": + return self._build_actions_instance_questions(spec, bindings) + if spec.id == "groups": + return self._build_groups_instance_questions(spec, bindings, state) + if spec.id in {"headline", "form"}: + return self._build_items_instance_questions(spec, bindings, state) + return [] + + def _build_scalar_instance_questions( + self, + spec: BlockSpec, + bindings: BlockBindings, + state: PlannerState, + ) -> list[DecisionQuestion]: + """Builds instance questions for single-slot blocks (`banner`, `outcome`).""" + slot_name = "title" if spec.id == "banner" else "headline" + slot_binding = bindings.get(slot_name) + if slot_binding is None or not slot_binding.pointer: + return [] + ptr_path = slot_binding.pointer + val = _resolve_pointer_value(state.payload, ptr_path) + display = str(val) if val is not None else ptr_path.lstrip("/") + built: list[DecisionQuestion] = [] + for q_name, q_spec in spec.instance.items(): + built.append( + DecisionQuestion( + id=f"instance:{spec.id}.{q_name}:{ptr_path}", + kind=QuestionKind.CHOICE, + prompt=q_spec.question.format(**{slot_name: display}), + options=tuple(q_spec.options), + option_texts=tuple(q_spec.options.values()), + allow_none=q_spec.allow_none, + ) + ) + return built + + def _build_actions_instance_questions( + self, spec: BlockSpec, bindings: BlockBindings + ) -> list[DecisionQuestion]: + """Builds `actions.primary` and `actions.destructive` instance questions.""" + buttons = bindings.get("buttons") + if buttons is None or not buttons.items: + return [] + ptr_path = buttons.pointer or "/actions" + labels = tuple( + str(item["label"].literal or idx) for idx, item in enumerate(buttons.items) + ) + built: list[DecisionQuestion] = [] + prim_spec = spec.instance.get("primary") + if prim_spec is not None and labels: + built.append( + DecisionQuestion( + id=f"instance:actions.primary:{ptr_path}", + kind=QuestionKind.CHOICE, + prompt=prim_spec.question, + options=labels, + allow_none=prim_spec.allow_none, + ) + ) + dest_spec = spec.instance.get("destructive") + if dest_spec is not None: + for idx, label in enumerate(labels): + built.append( + DecisionQuestion( + id=f"instance:actions.destructive:{idx}", + kind=QuestionKind.BOOLEAN, + prompt=dest_spec.question.format(label=label), + context={"yes": dest_spec.yes, "no": dest_spec.no}, + allow_none=False, + ) + ) + return built + + def _build_single_group_row_question( + self, + row_item: Mapping[str, SlotBinding], + q_spec: QuestionSpec, + state: PlannerState, + ) -> DecisionQuestion | None: + """Builds one `instance:groups.row_kind:` question for `row_item`.""" + val_binding = row_item.get("value") + lbl_binding = row_item.get("label") + if val_binding is None or not val_binding.pointer: + return None + ptr_path = val_binding.pointer + label = str( + (lbl_binding.literal if lbl_binding is not None else None) or ptr_path + ) + raw_val = _resolve_pointer_value(state.payload, ptr_path) + label_text = f"{label} ({raw_val})" if raw_val is not None else label + return DecisionQuestion( + id=f"instance:groups.row_kind:{ptr_path}", + kind=QuestionKind.CHOICE, + prompt=q_spec.question.format(label=label_text), + options=tuple(q_spec.options), + option_texts=tuple(q_spec.options.values()), + allow_none=q_spec.allow_none, + ) + + def _build_groups_instance_questions( + self, + spec: BlockSpec, + bindings: BlockBindings, + state: PlannerState, + ) -> list[DecisionQuestion]: + """Builds `instance:groups.row_kind:` questions for each setting row.""" + groups_slot = bindings.get("groups") + q_spec = spec.instance.get("row_kind") + if groups_slot is None or q_spec is None: + return [] + built: list[DecisionQuestion] = [] + for group_item in groups_slot.items: + rows_slot = group_item.get("rows") + if rows_slot is None: + continue + for row_item in rows_slot.items: + q_obj = self._build_single_group_row_question(row_item, q_spec, state) + if q_obj is not None: + built.append(q_obj) + return built + + def _questions_for_single_item( + self, + spec: BlockSpec, + item: Mapping[str, SlotBinding], + by_path: Mapping[str, PointerSummary], + state: PlannerState, + ) -> list[DecisionQuestion]: + """Builds instance questions for one item in `headline` or `form`.""" + val_b = item.get("value") + lbl_b = item.get("label") + if val_b is None or not val_b.pointer: + return [] + ptr_path = val_b.pointer + ptr = by_path.get(ptr_path) + label = str((lbl_b.literal if lbl_b else None) or ptr_path) + raw_val = _resolve_pointer_value(state.payload, ptr_path) + val_str = ( + str(raw_val) if raw_val is not None else (ptr.semantic_type if ptr else "") + ) + return [ + self._make_item_instance_question( + spec.id, q_name, q_spec, ptr_path, label, val_str, item + ) + for q_name, q_spec in spec.instance.items() + if _item_instance_applies(q_spec, item, ptr) + ] + + def _build_items_instance_questions( + self, + spec: BlockSpec, + bindings: BlockBindings, + state: PlannerState, + ) -> list[DecisionQuestion]: + """Builds per-item instance questions for `headline` and `form`.""" + slot_name = "items" if spec.id == "headline" else "fields" + slot_binding = bindings.get(slot_name) + if slot_binding is None or not slot_binding.items: + return [] + by_path = {p.path: p for p in state.pointers} + built: list[DecisionQuestion] = [] + for item in slot_binding.items: + built.extend(self._questions_for_single_item(spec, item, by_path, state)) + return built + + def _make_item_instance_question( + self, + block_id: str, + q_name: str, + q_spec: QuestionSpec, + ptr_path: str, + label: str, + val_str: str, + item: Mapping[str, SlotBinding], + ) -> DecisionQuestion: + """Creates one `DecisionQuestion` for an item in `headline` or `form`.""" + q_id = f"instance:{block_id}.{q_name}:{ptr_path}" + prompt = q_spec.question.format(label=label, value=val_str) + if q_spec.kind is QuestionKind.BOOLEAN: + return DecisionQuestion( + id=q_id, + kind=QuestionKind.BOOLEAN, + prompt=prompt, + context={"yes": q_spec.yes, "no": q_spec.no}, + allow_none=False, + ) + options = [ + opt + for opt in q_spec.options + if all( + req in item and item[req].bound for req in q_spec.requires.get(opt, ()) + ) + ] + texts = [q_spec.options[opt] for opt in options] + return DecisionQuestion( + id=q_id, + kind=QuestionKind.CHOICE, + prompt=prompt, + options=tuple(options), + option_texts=tuple(texts), + allow_none=q_spec.allow_none, + ) + + def read( + self, + state: PlannerState, + answers: Sequence[DecisionAnswer], + *, + seed: int | None = None, + ) -> PlanOutcome: + """Reads backend `answers` into a validated `PlanOutcome`.""" + state.seed = seed + if self._config.variety is VarietyMode.NEAR_TOP: + state.rng = random.Random(seed) + else: + state.rng = None + self._validate_and_index_answers(state, answers) + family = self._read_family(state) + if family is None: + return PlanOutcome(plan=None, reason=PlanReason.NO_FAMILY) + stakes, urgency = self._read_stakes_and_urgency(state) + archetype, confidence = self._read_archetype(state, family) + if archetype is None: + return PlanOutcome(plan=None, reason=PlanReason.NO_ARCHETYPE) + state.selected_archetype = archetype + self._warn_unused_brief_blocks(state, archetype) + self._read_salience_scores(state) + initial_blocks = self._read_gated_blocks(state, archetype) + page = self._initial_page_bindings(state, archetype) + plan = LayoutPlan( + archetype=archetype.id, + family=family, + blocks=initial_blocks, + page=page, + stakes=stakes, + urgency=urgency, + confidence=confidence, + ) + return self._apply_all_rules(plan, state) + + def _validate_and_index_answers( + self, state: PlannerState, answers: Sequence[DecisionAnswer] + ) -> None: + """Validates that `answers` matches `state.batch.questions` and indexes by ID.""" + expected_ids = {q.id for q in state.batch.questions} + by_id: dict[str, DecisionAnswer] = {} + for ans in answers: + if ans.question_id not in expected_ids: + raise A2uiValidationError( + f"Unknown question id {ans.question_id!r} in answers." + ) + by_id[ans.question_id] = ans + missing = [q.id for q in state.batch.questions if q.id not in by_id] + if missing: + raise A2uiValidationError( + f"Missing answers for batch questions: {missing}." + ) + state.answers_by_id = by_id + state.trace = [] + + def _read_family(self, state: PlannerState) -> str | None: + """Resolves the winning family ID from `brief` or the `family` answer.""" + if state.brief is not None: + for role in state.brief.roles(): + if role in self._grammar.families(): + return role + q_map = {q.id: q for q in state.batch.questions} + fam_q = q_map.get("family") + fam_ans = state.answers_by_id.get("family") + if fam_q is None or fam_ans is None: + return state.eligible[0].family if state.eligible else None + chosen, prob = fam_ans.top() + thresh = self.threshold("family") + eligible_fams = {a.family for a in state.eligible} + if ( + chosen == "none" + or prob < thresh + or not eligible_fams + or ( + chosen == "input" + and chosen not in eligible_fams + and not any(p.mutable_hint for p in state.pointers) + ) + ): + state.trace.append( + DecisionRecord( + question=fam_q, + answer=fam_ans, + threshold=thresh, + outcome="no_family", + ) + ) + return None + if chosen not in eligible_fams: + eligible_ranked = [ + (fam_id, fam_prob) + for fam_id, fam_prob in fam_ans.distribution.probabilities.items() + if fam_id in eligible_fams + ] + if eligible_ranked: + chosen = max(eligible_ranked, key=lambda kv: kv[1])[0] + else: + chosen = state.eligible[0].family + state.trace.append( + DecisionRecord( + question=fam_q, answer=fam_ans, threshold=thresh, outcome=chosen + ) + ) + return chosen + + def _read_stakes_and_urgency(self, state: PlannerState) -> tuple[float, float]: + """Reads the expected `stakes` and `urgency` scores and records them.""" + q_map = {q.id: q for q in state.batch.questions} + results: dict[str, float] = {"stakes": 0.0, "urgency": 0.0} + for key in ("stakes", "urgency"): + q_obj = q_map.get(key) + ans = state.answers_by_id.get(key) + if q_obj is not None and ans is not None: + val = _expected_score(ans) + results[key] = val + state.trace.append( + DecisionRecord(question=q_obj, answer=ans, outcome=f"{val:.2f}") + ) + return results["stakes"], results["urgency"] + + def _read_archetype( + self, state: PlannerState, family: str + ) -> tuple[LayoutArchetype | None, float]: + """Resolves the winning `LayoutArchetype` within `family`.""" + q_id = f"archetype:{family}" + q_map = {q.id: q for q in state.batch.questions} + arch_q = q_map.get(q_id) + arch_ans = state.answers_by_id.get(q_id) + fam_archs = [a for a in state.eligible if a.family == family] + if arch_q is None or arch_ans is None: + return (fam_archs[0], 1.0) if fam_archs else (None, 0.0) + chosen, prob = arch_ans.top() + thresh = self.threshold("archetype") + fam_ans = state.answers_by_id.get("family") + was_redirected = fam_ans is not None and fam_ans.top()[0] != family + if chosen == "none" or prob < thresh: + if was_redirected and fam_archs and fam_ans is not None: + non_none = [ + (opt, p) + for opt, p in arch_ans.distribution.probabilities.items() + if opt != "none" and any(a.id == opt for a in fam_archs) + ] + best_id = ( + max(non_none, key=lambda kv: kv[1])[0] + if non_none + else fam_archs[0].id + ) + best_prob = max(prob, fam_ans.top()[1]) + state.trace.append( + DecisionRecord( + question=arch_q, + answer=arch_ans, + threshold=thresh, + outcome=best_id, + ) + ) + return self._grammar.archetype(best_id), best_prob + state.trace.append( + DecisionRecord( + question=arch_q, + answer=arch_ans, + threshold=thresh, + outcome="no_archetype", + ) + ) + return None, prob + state.trace.append( + DecisionRecord( + question=arch_q, + answer=arch_ans, + threshold=thresh, + outcome=chosen, + ) + ) + return self._grammar.archetype(chosen), prob + + def _warn_unused_brief_blocks( + self, state: PlannerState, archetype: LayoutArchetype + ) -> None: + """Records a trace warning for any brief block not allowed by `archetype`.""" + if state.brief is None: + return + allowed = set(archetype.block_ids()) + for role in state.brief.roles(): + if role in self._grammar.blocks and role not in allowed: + state.trace.append( + DecisionRecord( + question=DecisionQuestion( + id=f"brief:{role}", + kind=QuestionKind.BOOLEAN, + prompt=f"Layout brief section {role!r}", + allow_none=False, + ), + outcome=f"warning:ignored_brief_block:{role}", + ) + ) + + def _read_salience_scores(self, state: PlannerState) -> None: + """Populates `state.salience_scores` from answers or fallback heuristics.""" + q_map = {q.id: q for q in state.batch.questions} + scores: dict[str, float] = {} + for idx, ptr in enumerate(state.pointers): + q_id = f"salience:{ptr.path}" + q_obj = q_map.get(q_id) + ans = state.answers_by_id.get(q_id) + if q_obj is not None and ans is not None: + val = _expected_score(ans) + scores[ptr.path] = val + state.trace.append( + DecisionRecord(question=q_obj, answer=ans, outcome=f"{val:.2f}") + ) + else: + base = ( + 1.8 + if ptr.semantic_type + in {"currency", "rating", "percent", "status", "bounded"} + else 1.0 + ) + scores[ptr.path] = base - idx * 0.001 + state.salience_scores = scores + + def _evaluate_single_block_gate( + self, + ref: BlockRef, + q_map: Mapping[str, DecisionQuestion], + pinned: set[str], + state: PlannerState, + ) -> PlannedBlock | None: + """Evaluates the gate for one `BlockRef` and records its trace entry.""" + spec = self._grammar.block(ref.id) + if not _matches_shape(spec.shape, state.pointers): + if not ( + ref.id == "prose" and state.copy is not None and state.copy.summary + ): + return None + if ref.id in pinned: + state.gate_probabilities[ref.id] = 1.0 + return PlannedBlock(block_id=ref.id, pattern=spec.pattern, probability=1.0) + q_id = f"gate:{ref.id}" + q_obj = q_map.get(q_id) + ans = state.answers_by_id.get(q_id) + prob = ( + ans.yes + if ans is not None + else (0.8 if ref.requirement != "optional" else 0.0) + ) + state.gate_probabilities[ref.id] = prob + thresh = ( + self.threshold("optional") + if ref.requirement == "optional" + else self.threshold("expected") + ) + passed = prob >= thresh + outcome = ( + "required_override (disagreement)" + if (ref.requirement == "required" and not passed) + else ("include" if passed else "drop") + ) + if q_obj is not None and ans is not None: + state.trace.append( + DecisionRecord( + question=q_obj, answer=ans, threshold=thresh, outcome=outcome + ) + ) + return ( + PlannedBlock(block_id=ref.id, pattern=spec.pattern, probability=prob) + if passed + else None + ) + + def _read_gated_blocks( + self, state: PlannerState, archetype: LayoutArchetype + ) -> tuple[PlannedBlock, ...]: + """Evaluates block gates for `archetype.blocks` and records trace entries.""" + q_map = {q.id: q for q in state.batch.questions} + pinned = ( + {r for r in state.brief.roles() if r in self._grammar.blocks} + if state.brief is not None + else set() + ) + active: list[PlannedBlock] = [] + for ref in archetype.blocks: + if self._is_redundant_optional_fallback(ref, archetype): + continue + block = self._evaluate_single_block_gate(ref, q_map, pinned, state) + if block is not None: + active.append(block) + return tuple(active) + + def _initial_page_bindings( + self, state: PlannerState, archetype: LayoutArchetype + ) -> PageBindings: + """Builds initial `PageBindings` for `archetype` and records claimed title pointer.""" + state.page_claimed_pointers = set() + if state.copy is not None and state.copy.title: + title_binding = SlotBinding(literal=state.copy.title) + else: + title_ptr = _page_title_pointer(state.pointers) + if title_ptr is not None: + state.page_claimed_pointers.add(title_ptr.path) + title_binding = SlotBinding(pointer=title_ptr.path) + else: + title_binding = SlotBinding(literal=state.intent) + return PageBindings( + title=title_binding, + dialog=bool(archetype.frame.get("dialog", False)), + sticky_actions=bool(archetype.frame.get("stickyActions", False)), + ) + + def _apply_all_rules(self, plan: LayoutPlan, state: PlannerState) -> PlanOutcome: + """Runs the grammar `apply_` functions in pipeline order.""" + plan = apply_required_block_wins(plan, state) + plan = apply_at_least(plan, state, self._grammar) + plan = apply_fallback_must_end(plan, state, self._grammar, self._capabilities) + plan = apply_catalog_eligibility(plan, state) + plan = apply_pointer_once_per_region(plan, state, self) + plan = apply_pictures_need_a_look(plan, state) + plan = apply_leading_all_or_none(plan, state) + plan = apply_actions_gate( + plan, + state, + self.threshold("actionGateFloor"), + self.threshold("actionGateCap"), + ) + plan = apply_one_primary_action(plan, state) + plan = apply_urgency_terse(plan, state, self._capabilities) + plan = apply_no_orphaned_pointers(plan, state, self) + plan = apply_no_empty_container(plan, state, self._grammar) + if state.action_gate_blocked: + return PlanOutcome(plan=None, reason=PlanReason.ACTION_GATE) + if state.required_block_missing or not plan.blocks: + return PlanOutcome(plan=None, reason=PlanReason.REQUIRED_BLOCK_MISSING) + return PlanOutcome(plan=plan, reason=PlanReason.PLANNED) + + def _pick_option( + self, + answer: DecisionAnswer, + *, + kind: str = "option", + rng: random.Random | None = None, + ) -> tuple[str, float]: + """Picks a winning option from `answer` using ARGMAX or NEAR_TOP sampling.""" + if ( + self._config.variety is not VarietyMode.NEAR_TOP + or rng is None + or not answer.distribution.probabilities + ): + return answer.top() + + probs = { + opt: prob + for opt, prob in answer.distribution.probabilities.items() + if opt != "none" + } + if not probs: + return answer.top() + + top_opt, top_prob = max(probs.items(), key=lambda item: item[1]) + cutoff = top_prob - self._config.variety_margin + near_top = [(opt, prob) for opt, prob in probs.items() if prob >= cutoff] + if len(near_top) <= 1: + return top_opt, top_prob + + candidates = [opt for opt, _ in near_top] + weights = [prob for _, prob in near_top] + chosen = rng.choices(candidates, weights=weights, k=1)[0] + return chosen, probs[chosen] + + def _resolve_block_questions( + self, + spec: BlockSpec, + bindings: BlockBindings, + state: PlannerState, + *, + actions_allowed: bool, + preset_knobs: Mapping[str, str], + rng: random.Random | None = None, + ) -> tuple[dict[str, str], dict[str, dict[str, str]]]: + """Resolves measures, anatomy knobs, and instance answers for `spec`.""" + by_path = {p.path: p for p in state.pointers} + knobs = { + **preset_knobs, + **_compute_block_measures(spec, bindings, by_path), + } + q_map = {q.id: q for q in state.batch.questions} + for knob, q_spec in spec.anatomy.items(): + derived = state.derived_anatomy.get( + (spec.id, knob) + ) or _derive_anatomy_from_hints(q_spec, bindings, by_path) + if derived is not None: + knobs[knob] = derived + continue + q_id = f"anatomy:{spec.id}.{knob}" + chosen = self._resolve_single_anatomy( + knob, + q_spec, + q_map.get(q_id), + state.answers_by_id.get(q_id), + bindings, + state, + actions_allowed=actions_allowed, + rng=rng, + ) + if chosen is not None: + knobs[knob] = chosen + instances = self._resolve_block_instances(spec, bindings, state, rng=rng) + if spec.id in {"banner", "outcome"}: + for elem_map in instances.values(): + if "tone" in elem_map: + knobs.setdefault("tone", elem_map["tone"]) + return knobs, instances + + def _resolve_choice_anatomy( + self, + q_spec: QuestionSpec, + q_obj: DecisionQuestion | None, + ans: DecisionAnswer | None, + bindings: BlockBindings, + state: PlannerState, + actions_allowed: bool, + *, + rng: random.Random | None = None, + ) -> str | None: + """Selects the highest-ranked choice option whose `requires` hold.""" + if ans is None: + ranked = list(q_spec.options) + else: + picked, _ = self._pick_option(ans, kind="anatomy", rng=rng) + other_opts = [ + opt + for opt, _ in sorted( + ans.distribution.probabilities.items(), + key=lambda item: -item[1], + ) + if opt != "none" and opt != picked + ] + ranked = [picked] + other_opts + + for opt in ranked: + reqs = q_spec.requires.get(opt, ()) + if _option_requirements_hold( + reqs, + bindings, + self._capabilities, + actions_allowed, + state.pointers, + ): + if q_obj is not None and ans is not None: + state.trace.append( + DecisionRecord(question=q_obj, answer=ans, outcome=opt) + ) + return opt + return ranked[0] if ranked else None + + def _resolve_single_anatomy( + self, + knob: str, + q_spec: QuestionSpec, + q_obj: DecisionQuestion | None, + ans: DecisionAnswer | None, + bindings: BlockBindings, + state: PlannerState, + *, + actions_allowed: bool, + rng: random.Random | None = None, + ) -> str | None: + """Resolves one anatomy knob answer with constraint-aware argmax.""" + if q_spec.kind is QuestionKind.BOOLEAN: + val = "yes" if (ans is not None and ans.yes >= 0.5) else "no" + if q_obj is not None and ans is not None: + state.trace.append( + DecisionRecord( + question=q_obj, answer=ans, threshold=0.5, outcome=val + ) + ) + return val + if q_spec.kind is QuestionKind.SCORE: + score = _expected_score(ans) if ans is not None else 1.5 + val = ( + _prominence_level(score) + if knob == "prominence" + else str(int(round(score))) + ) + if q_obj is not None and ans is not None: + state.trace.append( + DecisionRecord(question=q_obj, answer=ans, outcome=val) + ) + return val + return self._resolve_choice_anatomy( + q_spec, + q_obj, + ans, + bindings, + state, + actions_allowed, + rng=rng, + ) + + def _record_single_instance_answer( + self, + q_spec: QuestionSpec, + q_obj: DecisionQuestion | None, + ans: DecisionAnswer, + thresh: float, + state: PlannerState, + *, + rng: random.Random | None = None, + ) -> str: + """Evaluates one instance `DecisionAnswer` and appends a `DecisionRecord`.""" + is_bool = q_spec.kind is QuestionKind.BOOLEAN + val = ( + ("true" if ans.yes >= thresh else "false") + if is_bool + else self._pick_option(ans, kind="instance", rng=rng)[0] + ) + if q_obj is not None: + state.trace.append( + DecisionRecord( + question=q_obj, + answer=ans, + threshold=thresh if is_bool else None, + outcome=val, + ) + ) + return val + + def _resolve_block_instances( + self, + spec: BlockSpec, + bindings: BlockBindings, + state: PlannerState, + *, + rng: random.Random | None = None, + ) -> dict[str, dict[str, str]]: + """Reads instance answers for `spec` into an element-keyed mapping.""" + if spec.id == "actions": + return self._resolve_actions_instances(bindings, state, rng=rng) + q_map = {q.id: q for q in state.batch.questions} + thresh = self.threshold("instance") + instances: dict[str, dict[str, str]] = {} + prefix = f"instance:{spec.id}." + bound_ptrs = set(bindings.pointers()) + for q_id, ans in state.answers_by_id.items(): + if not q_id.startswith(prefix): + continue + q_name, _, elem_key = q_id[len(prefix) :].partition(":") + q_spec = spec.instance.get(q_name) + if q_spec is None or ( + elem_key.startswith("/") and elem_key not in bound_ptrs + ): + continue + val = self._record_single_instance_answer( + q_spec, q_map.get(q_id), ans, thresh, state, rng=rng + ) + instances.setdefault(elem_key, {})[q_name] = val + return instances + + def _read_primary_action_choice( + self, + ptr_path: str, + q_map: Mapping[str, DecisionQuestion], + state: PlannerState, + *, + rng: random.Random | None = None, + ) -> str: + """Reads the winning button option from `instance:actions.primary:`.""" + prim_id = f"instance:actions.primary:{ptr_path}" + prim_ans = state.answers_by_id.get(prim_id) + if prim_ans is None: + return "" + chosen = self._pick_option(prim_ans, kind="primary_action", rng=rng)[0] + if prim_id in q_map: + state.trace.append( + DecisionRecord( + question=q_map[prim_id], + answer=prim_ans, + outcome=chosen, + ) + ) + return chosen + + def _read_button_destructive_flag( + self, + idx: int, + thresh: float, + q_map: Mapping[str, DecisionQuestion], + state: PlannerState, + ) -> bool: + """Reads `instance:actions.destructive:` and appends a trace record.""" + dest_id = f"instance:actions.destructive:{idx}" + dest_ans = state.answers_by_id.get(dest_id) + if dest_ans is None: + return False + is_dest = dest_ans.yes >= thresh + if dest_id in q_map: + state.trace.append( + DecisionRecord( + question=q_map[dest_id], + answer=dest_ans, + threshold=thresh, + outcome="true" if is_dest else "false", + ) + ) + return is_dest + + def _resolve_actions_instances( + self, + bindings: BlockBindings, + state: PlannerState, + *, + rng: random.Random | None = None, + ) -> dict[str, dict[str, str]]: + """Resolves `actions.primary` and `actions.destructive` per button.""" + buttons = bindings.get("buttons") + if buttons is None or not buttons.items: + return {} + q_map = {q.id: q for q in state.batch.questions} + thresh = self.threshold("instance") + chosen_prim = self._read_primary_action_choice( + buttons.pointer or "/actions", q_map, state, rng=rng + ) + instances: dict[str, dict[str, str]] = {} + for idx, item in enumerate(buttons.items): + label = str(item["label"].literal or idx) + is_dest = self._read_button_destructive_flag(idx, thresh, q_map, state) + is_prim = chosen_prim in {label, str(idx)} + entry = { + "primary": "true" if is_prim else "false", + "destructive": "true" if is_dest else "false", + } + instances[str(idx)] = entry + instances[label] = entry + return instances + + def needs_reask( + self, plan: LayoutPlan, state: PlannerState + ) -> tuple[DecisionQuestion, ...]: + """Returns depended-on questions whose winning probability is below `reask_below`.""" + active_blocks = set(plan.block_ids()) + active_ptrs: set[str] = set() + for block in plan.blocks: + active_ptrs.update(block.bindings.pointers()) + reask: list[DecisionQuestion] = [] + for question in state.batch.questions: + if not _question_affects_plan( + question.id, plan.family, active_blocks, active_ptrs + ): + continue + ans = state.answers_by_id.get(question.id) + if ans is None: + continue + win_prob = ( + max(ans.yes, 1.0 - ans.yes) + if question.kind is QuestionKind.BOOLEAN + else ans.top()[1] + ) + if win_prob < self.threshold("reask_below"): + reask.append(question) + return tuple(reask) + + +_MAX_SALIENCE_QUESTIONS = 20 + + +def _single_apply_condition_holds( + key: str, + req: Any, + item: Mapping[str, SlotBinding], + ptr: PointerSummary | None, +) -> bool: + """Checks one `(key, req)` entry of an item question's `applies_when`.""" + if req == "bound": + return key in item and item[key].bound + allowed = {req} if isinstance(req, str) else set(req) + return ptr is not None and ptr.semantic_type in allowed + + +def _item_instance_applies( + q_spec: QuestionSpec, + item: Mapping[str, SlotBinding], + ptr: PointerSummary | None, +) -> bool: + """Checks `q_spec.applies_when` for one item in `headline` or `form`.""" + return all( + _single_apply_condition_holds(k, req, item, ptr) + for k, req in q_spec.applies_when.items() + ) + + +def _question_affects_plan( + question_id: str, + family: str, + active_blocks: set[str], + active_ptrs: set[str], +) -> bool: + """Returns whether `question_id` governs a block or element present in `plan`.""" + if question_id in {"family", f"archetype:{family}"}: + return True + if question_id.startswith("anatomy:"): + block_id = question_id[len("anatomy:") :].split(".", 1)[0] + return block_id in active_blocks + if question_id.startswith("instance:"): + rest = question_id[len("instance:") :] + block_id = rest.split(".", 1)[0] + if block_id not in active_blocks: + return False + _, _, elem_key = rest.partition(":") + if elem_key.startswith("/"): + return elem_key in active_ptrs + return True + if question_id.startswith("gate:"): + block_id = question_id[len("gate:") :] + return block_id in active_blocks + return False diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/models.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/models.py new file mode 100644 index 0000000000..4665a2faeb --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/models.py @@ -0,0 +1,943 @@ +# 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. + +"""Data models and configuration types for local decision-model A2UI synthesis.""" + +from __future__ import annotations + +from collections.abc import Collection, Mapping, Sequence +from dataclasses import dataclass, field +from enum import Enum +import json +import math +import re +from typing import Any, Literal, Protocol, runtime_checkable + +from a2ui.core import A2uiValidationError, CatalogApi +from a2ui.core.schema import AgentToRendererMessage + + +class _WireEnum(str, Enum): + """String enum whose `str()`, `format()`, and `hash()` follow the wire value. + + Since Python 3.11, `format()` on a plain `(str, Enum)` member returns + `ClassName.MEMBER`, which would break f-string keys such as + ``f"{query.task}:{query.prompt}"`` that existing backends build. Hashing + by the string value lets members stand in for their wire strings in sets + and dict keys (``SemanticType.IMAGE_URL in {"image_url"}``). + """ + + def __str__(self) -> str: + return str.__str__(self) + + def __format__(self, format_spec: str) -> str: + return str.__format__(str(self), format_spec) + + def __hash__(self) -> int: + return str.__hash__(self) + + +class DecisionTask(_WireEnum): + """Kind of choice a `DecisionQuery` asks a decision backend to make. + + Members compare equal to their string values, so backends and tests that + match on the literal strings keep working. + """ + + TEMPLATE_SELECT = "template_select" + ROOT_COMPONENT = "root_component" + CHILD_COMPONENT = "child_component" + FAMILY = "family" + ARCHETYPE = "archetype" + BLOCK_GATE = "block_gate" + ANATOMY = "anatomy" + SALIENCE = "salience" + INSTANCE = "instance" + STAKES = "stakes" + URGENCY = "urgency" + + +class QuestionKind(_WireEnum): + """Answer shape of a `DecisionQuestion`. + + `CHOICE` yields a distribution over named options, `BOOLEAN` a calibrated + yes probability, and `SCORE` an expected value over ordered levels. + """ + + CHOICE = "choice" + BOOLEAN = "boolean" + SCORE = "score" + + +class VarietyMode(_WireEnum): + """How the layout planner samples choices from question distributions. + + `ARGMAX` picks the highest-probability option deterministically. + `NEAR_TOP` samples among options within `variety_margin` of the top. + """ + + ARGMAX = "argmax" + NEAR_TOP = "near_top" + + +class SemanticType(_WireEnum): + """Semantic classification of a payload pointer's value. + + The archetype grammar's slots name these types in their `from` lists. + Detection lives in the payload inspector; this enum is the shared + vocabulary. Members in `DEFERRED_SEMANTIC_TYPES` are part of the + vocabulary but no detector produces them yet. + """ + + # Text + STRING = "string" + LONG_TEXT = "long_text" + MARKDOWN = "markdown" + CODE = "code" + NAME = "name" + TITLE = "title" + IDENTIFIER = "identifier" + # Contact and links + EMAIL = "email" + PHONE = "phone" + URL = "url" + IMAGE_URL = "image_url" + VIDEO_URL = "video_url" + AUDIO_URL = "audio_url" + DOCUMENT_URL = "document_url" + # Time + DATE = "date" + TIME = "time" + DATETIME = "datetime" + DURATION = "duration" + RELATIVE_TIME = "relative_time" + DATE_RANGE = "date_range" + # Quantity + NUMBER = "number" + INTEGER = "integer" + COUNT = "count" + CURRENCY = "currency" + PERCENT = "percent" + RATIO = "ratio" + QUANTITY = "quantity" + RATING = "rating" + BOUNDED = "bounded" + # State + ENUM = "enum" + STATUS = "status" + BOOLEAN = "boolean" + COLOR = "color" + # Structure + ARRAY = "array" + OBJECT = "object" + EMPTY = "empty" + # Place (deferred: no detector yet) + ADDRESS = "address" + LOCATION = "location" + PLACE_NAME = "place_name" + COUNTRY = "country" + REGION = "region" + TIMEZONE = "timezone" + LANGUAGE = "language" + LOCALE = "locale" + DISTANCE = "distance" + # Composite objects (deferred: no detector yet) + MEDIA_OBJECT = "media_object" + MONEY_OBJECT = "money_object" + + +DEFERRED_SEMANTIC_TYPES: frozenset[SemanticType] = frozenset({ + SemanticType.ADDRESS, + SemanticType.LOCATION, + SemanticType.PLACE_NAME, + SemanticType.COUNTRY, + SemanticType.REGION, + SemanticType.TIMEZONE, + SemanticType.LANGUAGE, + SemanticType.LOCALE, + SemanticType.DISTANCE, + SemanticType.MEDIA_OBJECT, + SemanticType.MONEY_OBJECT, +}) +"""Semantic types the grammar may reference that no detector produces yet. + +The Place family and the composite object types are deferred; slots that +accept only these types never bind until a detector lands. +""" + + +class Requirement(_WireEnum): + """How strongly an archetype wants a block, encoded by its mark. + + ``name!`` is `REQUIRED`, ``name`` is `EXPECTED`, ``name?`` is `OPTIONAL`. + """ + + REQUIRED = "required" + EXPECTED = "expected" + OPTIONAL = "optional" + + +class PlanReason(_WireEnum): + """Why `LayoutPlanner.read` did or did not produce a plan. + + `ACTION_GATE` means the archetype would have rendered but its actions were + refused by the confidence gate: the synthesizer must abstain rather than + fall through to the flat path. + """ + + PLANNED = "planned" + NO_FAMILY = "no_family" + NO_ARCHETYPE = "no_archetype" + REQUIRED_BLOCK_MISSING = "required_block_missing" + ACTION_GATE = "action_gate" + + +class DecisionWireFormat(_WireEnum): + """Request and response format spoken by a remote decision endpoint. + + `AUTO` picks SystemOne when the endpoint path ends in `/v1/systemone` + and Jev otherwise. + """ + + AUTO = "auto" + JEV = "jev" + SYSTEMONE = "systemone" + + +class FallbackSource(_WireEnum): + """Which fallback produced a `SynthesisOutput` after the model abstained.""" + + DSL = "fallback_dsl" + CALLBACK = "fallback_fn" + CARD = "fallback_card" + + +class DecisionBackendType(_WireEnum): + """Backend selector accepted by `create_decision_backend`.""" + + MOCK = "mock" + LOCAL = "local" + ONNX = "onnx" + JEV = "jev" + SYSTEMONE = "systemone" + STEP_ZERO = "step0" + + +def coerce_decision_payload( + payload: Mapping[str, Any] | Sequence[Any] | str, +) -> Mapping[str, Any] | Sequence[Any]: + """Normalizes a synthesis payload into a JSON object or array. + + LLM tool calls often pass the payload as a JSON-encoded string rather + than a parsed object. This helper decodes such strings so callers do not + have to. + + Args: + payload: A mapping, a non-string sequence, or a JSON-encoded string + of either. + + Returns: + The payload as a `Mapping` or a non-string `Sequence`. + + Raises: + TypeError: If the payload (after decoding) is neither a mapping nor a + non-string sequence. + ValueError: If a string payload is not valid JSON. + """ + if isinstance(payload, str): + try: + decoded = json.loads(payload) + except json.JSONDecodeError as exc: + raise ValueError(f"Payload string is not valid JSON: {exc.msg}") from exc + if isinstance(decoded, str): + raise TypeError( + "Payload must be a JSON object (Mapping) or array (Sequence), got" + " a JSON string." + ) + return coerce_decision_payload(decoded) + if isinstance(payload, Mapping): + return payload + if isinstance(payload, Sequence) and not isinstance(payload, (bytes, bytearray)): + return payload + raise TypeError( + "Payload must be a JSON object (Mapping) or array (Sequence), got" + f" {type(payload).__name__}." + ) + + +class SynthesisStage(str, Enum): + """Execution stage reached during decision-model UI synthesis.""" + + TEMPLATE_SELECT = "template_select" + FAST_1PASS_LEAF = "fast_1pass_leaf" + CONTAINER_2PASS = "container_2pass" + ARCHETYPE = "archetype" + ABSTAIN_FALLBACK = "abstain_fallback" + + +class SlotKind(str, Enum): + """Semantic classification of a component property slot in a catalog schema.""" + + CHILD = "child" + CHILD_LIST = "child_list" + NAMED_CHILD_ARRAY = "named_child_array" + DATA_VALUE = "data_value" + STATIC_ENUM = "static_enum" + ACTION = "action" + + +@dataclass(frozen=True) +class ComponentSlot: + """Metadata describing a single bindable or structural slot on a component.""" + + name: str + kind: SlotKind + required: bool + value_type: str | None = None + enum_values: tuple[str, ...] = () + child_id_key: str | None = None + label_key: str | None = None + description: str = "" + + +@dataclass(frozen=True) +class ComponentNodeSpec: + """Catalog-derived structural specification for a single A2UI component.""" + + name: str + catalog_id: str + description: str + slots: tuple[ComponentSlot, ...] + supports_checks: bool = False + is_container: bool = False + is_multi_view_switcher: bool = False + has_action_slot: bool = False + + def get_slot(self, name: str) -> ComponentSlot | None: + """Returns the ComponentSlot matching name (ignoring index brackets like [0]).""" + base_name = name.split("[", 1)[0] + for slot in self.slots: + if slot.name == base_name or slot.name == name: + return slot + return None + + +@dataclass(frozen=True, eq=True) +class DecisionQuery: + """Query payload sent to a local decision-model backend.""" + + task: DecisionTask | str + prompt: str + candidates: tuple[str, ...] + context: dict[str, Any] = field(default_factory=dict, hash=False) + + def __post_init__(self) -> None: + object.__setattr__(self, "candidates", tuple(self.candidates)) + object.__setattr__(self, "context", dict(self.context)) + + +@dataclass(frozen=True, eq=True) +class DecisionDistribution: + """Probability distribution returned by a decision-model backend.""" + + probabilities: dict[str, float] = field(hash=False) + calibrated: bool = True + top_logit_margin: float | None = None + + def __post_init__(self) -> None: + object.__setattr__( + self, + "probabilities", + {str(k): float(v) for k, v in self.probabilities.items()}, + ) + + def top_choice(self) -> tuple[str, float]: + """Returns the highest-probability candidate and its score, or ('', 0.0).""" + if not self.probabilities: + return ("", 0.0) + return max(self.probabilities.items(), key=lambda item: item[1]) + + def normalized_entropy(self) -> float: + """Computes normalized Shannon entropy in [0.0, 1.0] over candidates.""" + k = len(self.probabilities) + if k <= 1: + return 0.0 + entropy = -sum(p * math.log(p) for p in self.probabilities.values() if p > 0.0) + if entropy <= 0.0: + return 0.0 + return entropy / math.log(k) + + +@dataclass(frozen=True) +class DecisionQuestion: + """One question in a `DecisionBatch`. + + Attributes: + id: Stable identifier such as ``"gate:collection"``, + ``"anatomy:collection.layout"``, or ``"salience:/cpu"``. The prefix + before the first colon names the `DecisionTask`. + kind: The answer shape. + prompt: The question text with ``{placeholders}`` already filled. + options: `CHOICE`: option ids; `BOOLEAN`: empty; `SCORE`: level + labels in order. + option_texts: Optional descriptions parallel to `options`. + context: Extra context a backend may show the model. + allow_none: `CHOICE` only; adds an implicit ``"none"`` option. + """ + + id: str + kind: QuestionKind + prompt: str + options: tuple[str, ...] = () + option_texts: tuple[str, ...] = () + context: dict[str, Any] = field(default_factory=dict, hash=False) + allow_none: bool = True + + def __post_init__(self) -> None: + object.__setattr__(self, "kind", QuestionKind(self.kind)) + object.__setattr__(self, "options", tuple(self.options)) + object.__setattr__(self, "option_texts", tuple(self.option_texts)) + object.__setattr__(self, "context", dict(self.context)) + if not self.id: + raise ValueError("DecisionQuestion.id must be a non-empty string.") + if self.option_texts and len(self.option_texts) != len(self.options): + raise ValueError( + f"Question {self.id!r}: option_texts must be empty or match" + " options in length." + ) + if self.kind is QuestionKind.BOOLEAN and self.options: + raise ValueError( + f"Question {self.id!r}: boolean questions take no options." + ) + if self.kind is QuestionKind.CHOICE and not self.options: + raise ValueError(f"Question {self.id!r}: choice questions need options.") + if self.kind is QuestionKind.SCORE and len(self.options) < 2: + raise ValueError( + f"Question {self.id!r}: score questions need at least two levels." + ) + + @property + def task(self) -> DecisionTask | str: + """The `DecisionTask` named by the id prefix, or the raw prefix.""" + prefix = self.id.split(":", 1)[0] + aliases = {"gate": DecisionTask.BLOCK_GATE} + if prefix in aliases: + return aliases[prefix] + try: + return DecisionTask(prefix) + except ValueError: + return prefix + + def candidates(self) -> tuple[str, ...]: + """The labels a backend scores: options, ``yes``/``no``, or levels.""" + if self.kind is QuestionKind.BOOLEAN: + return ("yes", "no") + if self.kind is QuestionKind.CHOICE and self.allow_none: + return self.options + ("none",) + return self.options + + +@dataclass(frozen=True) +class DecisionAnswer: + """A backend's answer to one `DecisionQuestion`. + + Attributes: + question_id: The id of the question answered. + distribution: `CHOICE` and `SCORE`: over the options; `BOOLEAN`: + ``{"yes": p, "no": 1 - p}``. + expected: `SCORE` only: ``sum(p_i * i)`` over level indices. + """ + + question_id: str + distribution: DecisionDistribution + expected: float | None = None + + @property + def yes(self) -> float: + """The yes probability of a `BOOLEAN` answer (0.0 when absent).""" + return self.distribution.probabilities.get("yes", 0.0) + + def top(self) -> tuple[str, float]: + """The highest-probability option and its probability.""" + return self.distribution.top_choice() + + +@dataclass(frozen=True) +class DecisionBatch: + """All speculative questions for one surface, answered in one call.""" + + shared_context: dict[str, Any] + questions: tuple[DecisionQuestion, ...] + + def __post_init__(self) -> None: + object.__setattr__(self, "shared_context", dict(self.shared_context)) + object.__setattr__(self, "questions", tuple(self.questions)) + seen: set[str] = set() + for question in self.questions: + if question.id in seen: + raise ValueError(f"Duplicate question id {question.id!r} in batch.") + seen.add(question.id) + + def pair_count(self) -> int: + """Number of (question, candidate) pairs a cross-encoder would score.""" + return sum(len(q.candidates()) for q in self.questions) + + +@dataclass(frozen=True) +class DecisionRecord: + """One entry in a synthesis trace: a question, its answer, and the outcome.""" + + question: DecisionQuestion + answer: DecisionAnswer | None = None + threshold: float | None = None + outcome: str = "" + + +@dataclass(frozen=True) +class SlotBinding: + """What a grammar slot resolved to. + + A scalar slot binds a `pointer` or a `literal`. A repeated slot backed by + an array binds the array `pointer` plus per-element `fields` (relative + keys). A repeated slot assembled from scalar pointers (headline tiles, + fact rows, action buttons) lists one field mapping per element in + `items`. + """ + + pointer: str | None = None + literal: Any = None + fields: Mapping[str, SlotBinding] = field(default_factory=dict, hash=False) + items: tuple[Mapping[str, SlotBinding], ...] = () + semantic_type: SemanticType | None = field(default=None, compare=False) + """The bound pointer's semantic type, when known; informs `$byType` dispatch.""" + + def __post_init__(self) -> None: + object.__setattr__(self, "fields", dict(self.fields)) + object.__setattr__(self, "items", tuple(dict(item) for item in self.items)) + if self.semantic_type is not None: + object.__setattr__(self, "semantic_type", SemanticType(self.semantic_type)) + + @property + def bound(self) -> bool: + """Whether the slot resolved to anything at all.""" + return ( + self.pointer is not None + or self.literal is not None + or bool(self.fields) + or bool(self.items) + ) + + def pointers(self) -> tuple[str, ...]: + """Every absolute pointer this binding claims, including nested ones.""" + found: list[str] = [] + if self.pointer is not None: + found.append(self.pointer) + for item in self.items: + for sub in item.values(): + found.extend(sub.pointers()) + return tuple(found) + + +@dataclass(frozen=True) +class BlockBindings: + """Slot bindings for one planned block, keyed by slot name.""" + + slots: Mapping[str, SlotBinding] = field(default_factory=dict, hash=False) + + def __post_init__(self) -> None: + object.__setattr__(self, "slots", dict(self.slots)) + + def get(self, slot: str) -> SlotBinding | None: + """The binding for `slot`, or None when the slot was not bound.""" + binding = self.slots.get(slot) + return binding if binding is not None and binding.bound else None + + def is_bound(self, slot: str) -> bool: + """Whether `slot` resolved to a pointer, literal, or elements.""" + return self.get(slot) is not None + + def pointers(self) -> tuple[str, ...]: + """Every absolute pointer claimed by this block, in slot order.""" + found: list[str] = [] + for binding in self.slots.values(): + found.extend(binding.pointers()) + return tuple(found) + + +@dataclass(frozen=True) +class PageBindings: + """Bindings for the page pattern's own slots and frame knobs.""" + + title: SlotBinding = field(default_factory=SlotBinding) + subtitle: SlotBinding = field(default_factory=SlotBinding) + mark: SlotBinding = field(default_factory=SlotBinding) + dialog: bool = False + sticky_actions: bool = False + + +@dataclass(frozen=True) +class PlannedBlock: + """A block the planner decided to render, with its knobs and bindings.""" + + block_id: str + pattern: str + variant_knobs: Mapping[str, str] = field(default_factory=dict, hash=False) + bindings: BlockBindings = field(default_factory=BlockBindings) + instances: Mapping[str, Mapping[str, str]] = field(default_factory=dict, hash=False) + """Per-element instance answers: element key to (question name to option).""" + probability: float = 1.0 + + def __post_init__(self) -> None: + object.__setattr__(self, "variant_knobs", dict(self.variant_knobs)) + object.__setattr__( + self, "instances", {k: dict(v) for k, v in self.instances.items()} + ) + + +@dataclass(frozen=True) +class LayoutPlan: + """The planner's validated choice of archetype, blocks, and bindings.""" + + archetype: str + family: str + blocks: tuple[PlannedBlock, ...] + page: PageBindings = field(default_factory=PageBindings) + stakes: float = 0.0 + urgency: float = 0.0 + confidence: float = 0.0 + actions_allowed: bool = False + + def __post_init__(self) -> None: + object.__setattr__(self, "blocks", tuple(self.blocks)) + + def block_ids(self) -> tuple[str, ...]: + """The ids of the planned blocks in render order.""" + return tuple(block.block_id for block in self.blocks) + + +@dataclass(frozen=True) +class PlanOutcome: + """Result of reading a batch of answers into a `LayoutPlan`.""" + + plan: LayoutPlan | None + reason: PlanReason + + def __post_init__(self) -> None: + object.__setattr__(self, "reason", PlanReason(self.reason)) + if (self.reason is PlanReason.PLANNED) != (self.plan is not None): + raise ValueError( + "PlanOutcome.plan must be set exactly when reason is 'planned'." + ) + + +@runtime_checkable +class PatternCapabilities(Protocol): + """What the planner may ask about a catalog without loading its patterns.""" + + def has_pattern(self, name: str, variant: str | None = None) -> bool: + """Whether the catalog draws `name` (and, when given, that `variant`).""" + ... + + +MAX_BRIEF_SECTIONS = 6 +"""Most sections a `LayoutBrief` may carry.""" + +BRIEF_ITEM_PATTERN = r"^[a-z_]+:[A-Za-z0-9_/,.~-]+$" +"""Regular expression one ``role:key,key`` brief item must match. + +Shared with the tool JSON Schema so the model-facing contract and the parser +agree. +""" + +_BRIEF_ITEM_RE = re.compile(r"^([a-z_]+):([A-Za-z0-9_/,.~-]+)$") + + +def _brief_pointer(raw: str, item: str) -> str: + """Normalizes one brief key into an absolute JSON Pointer.""" + key = raw.strip() + if not key: + raise A2uiValidationError(f"Layout brief item {item!r} has an empty key.") + return key if key.startswith("/") else f"/{key}" + + +@dataclass(frozen=True) +class BriefSection: + """One ``role:pointers`` section of a `LayoutBrief`.""" + + role: str + pointers: tuple[str, ...] + + def __post_init__(self) -> None: + object.__setattr__(self, "pointers", tuple(self.pointers)) + + +@dataclass(frozen=True) +class LayoutBrief: + """An author's hint about which payload pointers belong to which layout role. + + Written as ``"hero:name,logoUrl"`` items: a role from the grammar's + vocabulary, a colon, and comma-separated payload keys or pointers. + """ + + sections: tuple[BriefSection, ...] + + def __post_init__(self) -> None: + object.__setattr__(self, "sections", tuple(self.sections)) + + @classmethod + def parse(cls, items: Sequence[str], *, roles: Collection[str]) -> LayoutBrief: + """Parses brief items, validating roles against `roles`. + + Bare keys become absolute pointers (``name`` to ``/name``). At most + `MAX_BRIEF_SECTIONS` sections are allowed, each role at most once, + and no nesting (a second colon in an item). + + Raises: + A2uiValidationError: On an unknown role, a malformed item, a + repeated role, or too many sections. + """ + if len(items) > MAX_BRIEF_SECTIONS: + raise A2uiValidationError( + f"Layout brief has {len(items)} sections; at most" + f" {MAX_BRIEF_SECTIONS} are allowed." + ) + sections: list[BriefSection] = [] + seen: set[str] = set() + for item in items: + match = _BRIEF_ITEM_RE.match(item.strip()) + if match is None: + raise A2uiValidationError( + f"Layout brief item {item!r} is not of the form 'role:key,key'." + ) + role, keys = match.group(1), match.group(2) + if role not in roles: + raise A2uiValidationError( + f"Layout brief role {role!r} is not one of {sorted(roles)}." + ) + if role in seen: + raise A2uiValidationError(f"Layout brief repeats role {role!r}.") + seen.add(role) + pointers = tuple(_brief_pointer(k, item) for k in keys.split(",")) + sections.append(BriefSection(role=role, pointers=pointers)) + return cls(sections=tuple(sections)) + + def roles(self) -> tuple[str, ...]: + """The roles named by the brief, in order.""" + return tuple(section.role for section in self.sections) + + def section(self, role: str) -> BriefSection | None: + """The section for `role`, or None.""" + for section in self.sections: + if section.role == role: + return section + return None + + def to_items(self) -> list[str]: + """Serializes back to ``role:/a,/b`` items.""" + return [f"{s.role}:{','.join(s.pointers)}" for s in self.sections] + + +@dataclass(frozen=True) +class AuthoredCopy: + """Optional authored copy supplied by the model in the decision block. + + Attributes: + title: Optional title string for the surface. + summary: Optional one-line summary string for the surface. + """ + + title: str | None = None + summary: str | None = None + + def __post_init__(self) -> None: + title = self.title.strip() if self.title else None + summary = self.summary.strip() if self.summary else None + object.__setattr__(self, "title", title or None) + object.__setattr__(self, "summary", summary or None) + + @property + def has_content(self) -> bool: + """Whether any copy string is present.""" + return bool(self.title or self.summary) + + +def _validate_unit_interval(name: str, value: float) -> None: + """Validates that a threshold or margin parameter lies in [0.0, 1.0].""" + if not (0.0 <= value <= 1.0): + raise ValueError(f"{name} must be in [0.0, 1.0], got {value}.") + + +@dataclass(frozen=True) +class SynthesisConfig: + """Thresholds and structural limits governing decision-model UI synthesis.""" + + template_confidence_threshold: float = 0.75 + mutable_confidence_threshold: float = 0.85 + abstain_threshold: float = 0.40 + uncalibrated_min_logit_margin: float = 1.50 + entropy_switch_margin: float = 0.20 + max_tree_depth: int = 3 + max_children_per_container: int = 8 + default_surface_id: str = "default_surface" + max_pairs: int = 400 + """Budget of (question, candidate) pairs for one batch. + + Past it the planner stops adding optional question groups and falls back + to heuristics for them. + """ + threshold_overrides: Mapping[str, float] = field(default_factory=dict, hash=False) + """Per-key overrides of `ArchetypeGrammar.thresholds`. + + Keys are the grammar's own names (``family``, ``archetype``, ``expected``, + ``optional``, ``instance``, ``reask_below``, ``actionGateFloor``, + ``actionGateCap``). The grammar is the single source of truth for the + defaults; set a key here to tune one without editing the grammar file. + """ + use_archetypes: bool = True + """When False, synthesis skips the archetype planner and uses the flat path.""" + variety: VarietyMode = VarietyMode.ARGMAX + """How choices are sampled from question distributions (ARGMAX or NEAR_TOP).""" + variety_margin: float = 0.15 + """In NEAR_TOP mode, options within this margin of top probability are sampled.""" + two_stage_batching: bool | None = None + """Splits planning into Stage 1 (family/archetype) and Stage 2 (winning archetype blocks). + + When None (default), enabled automatically for local/step-0 backends + (`LocalCrossEncoderBackend` and `StepZeroLogprobBackend`) and disabled for + single-round-trip remote/mock backends (`JevHttpBackend`, `DeterministicMockBackend`). + """ + + def __post_init__(self) -> None: + _validate_unit_interval( + "template_confidence_threshold", self.template_confidence_threshold + ) + _validate_unit_interval( + "mutable_confidence_threshold", self.mutable_confidence_threshold + ) + _validate_unit_interval("abstain_threshold", self.abstain_threshold) + _validate_unit_interval("entropy_switch_margin", self.entropy_switch_margin) + if not (0.0 < self.variety_margin <= 1.0): + raise ValueError( + f"variety_margin must be in (0.0, 1.0], got {self.variety_margin}." + ) + if self.mutable_confidence_threshold < self.template_confidence_threshold: + raise ValueError( + "mutable_confidence_threshold must be >= template_confidence_threshold." + ) + if self.template_confidence_threshold < self.abstain_threshold: + raise ValueError( + "template_confidence_threshold must be >= abstain_threshold." + ) + if self.uncalibrated_min_logit_margin < 0.0: + raise ValueError("uncalibrated_min_logit_margin must be non-negative.") + if self.max_tree_depth < 1: + raise ValueError("max_tree_depth must be >= 1.") + if self.max_children_per_container < 1: + raise ValueError("max_children_per_container must be >= 1.") + if not self.default_surface_id or not self.default_surface_id.strip(): + raise ValueError("default_surface_id must be a non-empty string.") + self._validate_archetype_fields() + + def _validate_archetype_fields(self) -> None: + """Validates the archetype planner budget and threshold overrides.""" + if self.max_pairs < 1: + raise ValueError("max_pairs must be >= 1.") + overrides = {str(k): float(v) for k, v in self.threshold_overrides.items()} + object.__setattr__(self, "threshold_overrides", overrides) + for name, value in overrides.items(): + _validate_unit_interval(f"threshold_overrides[{name!r}]", value) + validate_threshold_relations(overrides, "threshold_overrides") + + +def validate_threshold_relations(thresholds: Mapping[str, float], owner: str) -> None: + """Checks ordering constraints between grammar threshold keys that are present. + + Raises: + ValueError: If ``actionGateFloor > actionGateCap`` or + ``expected > optional`` when both keys of a pair are present. + """ + floor, cap = thresholds.get("actionGateFloor"), thresholds.get("actionGateCap") + if floor is not None and cap is not None and floor > cap: + raise ValueError(f"{owner}: actionGateFloor must be <= actionGateCap.") + expected, optional = thresholds.get("expected"), thresholds.get("optional") + if expected is not None and optional is not None and expected > optional: + raise ValueError(f"{owner}: expected must be <= optional.") + + +@dataclass(frozen=True) +class SynthesisOutput: + """Result produced by a single decision-model synthesis pass.""" + + stage: SynthesisStage + messages: list[AgentToRendererMessage] + confidence: float + entropy: float + selected_template_id: str | None = None + component_tree_spec: dict[str, Any] | None = None + fallback_source: FallbackSource | None = None + """Which fallback produced `messages` after the model abstained. + + None when the model did not abstain or no fallback applied. + """ + layout_plan: LayoutPlan | None = None + """The archetype plan behind `messages` when `stage` is `ARCHETYPE`.""" + trace: tuple[DecisionRecord, ...] = () + """Every question asked, with its answer and threshold outcome.""" + decision_latency_ms: float = 0.0 + """Wall-clock milliseconds spent waiting on the decision model backend.""" + decision_calls: int = 0 + """Number of backend `predict` or `answer` calls made during synthesis.""" + decision_answers: tuple[DecisionAnswer, ...] = () + """The batch answers that produced the layout plan, in question order.""" + + def __post_init__(self) -> None: + object.__setattr__(self, "trace", tuple(self.trace)) + object.__setattr__(self, "decision_answers", tuple(self.decision_answers)) + + def to_express( + self, + catalogs: Sequence[CatalogApi], + *, + use_keyword_args: bool = False, + ) -> str: + """Decompiles synthesized A2UI messages into A2UI Express DSL syntax.""" + if not self.messages: + return "" + from a2ui.inference_formats.express import ExpressDecompiler + + return ExpressDecompiler(catalogs).decompile( + self.messages, use_keyword_args=use_keyword_args + ) + + +@dataclass(frozen=True) +class CalibrationPoint: + """Coverage, precision, and fallback metrics at a single confidence threshold.""" + + threshold: float + coverage: float + precision: float + fallback_rate: float + + +@dataclass(frozen=True) +class CalibrationResult: + """Recommended confidence thresholds and Pareto frontier from calibration.""" + + recommended_template_threshold: float + recommended_mutable_threshold: float + recommended_abstain_threshold: float + achieved_precision: float + achieved_coverage: float + pareto_points: tuple[CalibrationPoint, ...] diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/parser.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/parser.py new file mode 100644 index 0000000000..88e8bede9e --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/parser.py @@ -0,0 +1,275 @@ +# 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. + +"""Parser that turns decision blocks in LLM output into A2UI messages.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from typing import Any + +from a2ui.constants import A2UI_INFERENCE_CLOSE_TAG, A2UI_INFERENCE_OPEN_TAG +from a2ui.core import A2uiError, CatalogApi +from a2ui.core.schema import AgentToRendererMessage +from a2ui.parser import ( + A2uiCompilationError, + A2uiCompilationParseError, + A2uiCompilationValidationError, + BlockLexer, + Parser, + RawA2uiPart, + RawResponsePart, + TextPart, + parse_and_fix, +) + +from .decision_block import DecisionBlock, decision_block_from_messages +from .models import SynthesisOutput, SynthesisStage +from .prompt_generator import DecisionPromptGenerator +from .synthesizer import DecisionSynthesizer + + +class DecisionParser(Parser): + """Compiles `` decision blocks through a `DecisionSynthesizer`. + + `compile` is synchronous by the `Parser` contract, so synthesis runs via + `DecisionSynthesizer.synthesize_sync`, which works with or without a + running event loop on the calling thread. + """ + + def __init__( + self, + synthesizer: DecisionSynthesizer, + surface_id: str = "main", + ) -> None: + """Creates a parser. + + Args: + synthesizer: The synthesizer that renders each block. + surface_id: Surface used when a block names none. A block's own + `surfaceId` wins; `SynthesisConfig.default_surface_id` is not + consulted on this path. + """ + self._synthesizer = synthesizer + self.surface_id = surface_id + + @property + def synthesizer(self) -> DecisionSynthesizer: + """The synthesizer this parser renders blocks with.""" + return self._synthesizer + + @property + def catalogs(self) -> list[CatalogApi]: + """A copy of the catalogs the synthesizer selects from.""" + return list(self._synthesizer.graph.catalogs) + + def has_format_content(self, content: str, complete: bool = False) -> bool: + """Checks whether `content` contains a decision block.""" + for part in self.unwrap(content): + if isinstance(part.part, RawA2uiPart) and (not complete or part.is_final): + return True + return False + + def wrap(self, blocks: Sequence[RawResponsePart]) -> str: + """Wraps text and raw decision blocks into one LLM-formatted string.""" + parts: list[str] = [] + for block in blocks: + inner = block.part if isinstance(block, RawResponsePart) else block + if isinstance(inner, TextPart): + parts.append(inner.text) + elif isinstance(inner, RawA2uiPart): + parts.append( + f"{A2UI_INFERENCE_OPEN_TAG}\n{inner.a2ui_raw}\n{A2UI_INFERENCE_CLOSE_TAG}" + ) + return "\n".join(parts) + + def unwrap(self, content: str) -> list[RawResponsePart]: + """Splits LLM output into text and raw decision block parts.""" + lexer = BlockLexer( + open_tag=A2UI_INFERENCE_OPEN_TAG, + close_tag=A2UI_INFERENCE_CLOSE_TAG, + string_delimiters={'"'}, + ) + return lexer.tokenize(content) + + def read_blocks(self, format_content: str) -> list[DecisionBlock]: + """Parses the JSON body of a block into one or more decision blocks.""" + try: + parsed: Any = parse_and_fix(format_content) + except Exception as exc: + raise A2uiCompilationParseError( + message=f"Decision block is not valid JSON: {exc}", + raw_content=format_content, + help_message=( + "Emit one JSON object with 'intent' and 'payload' fields inside" + " the tags." + ), + ) from exc + items = parsed if isinstance(parsed, list) else [parsed] + blocks: list[DecisionBlock] = [] + for item in items: + if not isinstance(item, Mapping): + raise A2uiCompilationValidationError( + message="Each decision block must be a JSON object.", + raw_content=format_content, + ) + try: + blocks.append(DecisionBlock.from_mapping(item)) + except (TypeError, ValueError) as exc: + raise A2uiCompilationValidationError( + message=str(exc), raw_content=format_content + ) from exc + return blocks + + _read_blocks = read_blocks + + async def synthesize_blocks( + self, format_content: str, *, default_surface_id: str | None = None + ) -> list[SynthesisOutput]: + """Synthesizes `SynthesisOutput`s for every decision block in `format_content`. + + Accepts either raw block JSON or text containing `` decision tags. + + Raises: + A2uiCompilationParseError: If the block is not valid JSON. + A2uiCompilationValidationError: If a block lacks required fields or + the synthesizer rejects it. + A2uiCompilationError: If the decision model abstains and no + fallback produced any messages. + """ + raw_parts = [ + part.part.a2ui_raw + for part in self.unwrap(format_content) + if isinstance(part.part, RawA2uiPart) + ] + if raw_parts: + blocks: list[DecisionBlock] = [] + for raw in raw_parts: + blocks.extend(self.read_blocks(raw)) + else: + blocks = self.read_blocks(format_content) + + outputs: list[SynthesisOutput] = [] + base_surface_id = ( + default_surface_id if default_surface_id is not None else self.surface_id + ) + for idx, block in enumerate(blocks, start=1): + default_id = ( + base_surface_id if len(blocks) == 1 else f"{base_surface_id}_{idx}" + ) + target_surface_id = block.surface_id or default_id + try: + output = await self._synthesizer.synthesize( + block.intent, + block.payload, + surface_id=target_surface_id, + mutable_paths=block.mutable_paths, + template_id=block.template_id, + fallback_dsl=block.fallback_dsl, + layout=block.layout or None, + title=block.title, + summary=block.summary, + ) + except A2uiError: + raise + except (TypeError, ValueError) as exc: + raise A2uiCompilationValidationError( + message=str(exc), raw_content=format_content + ) from exc + if not output.messages: + raise A2uiCompilationError( + message=( + "The decision model abstained" + f" (confidence {output.confidence:.2f}) and no fallback" + " produced messages." + ), + raw_content=format_content, + help_message=( + "Add a 'fallbackDsl' field, name a 'template', or enable" + " fallback_card on the synthesizer." + ), + ) + assert output.stage in SynthesisStage + outputs.append(output) + return outputs + + def compile( + self, format_content: str, *, is_final: bool = True + ) -> list[AgentToRendererMessage]: + """Synthesizes the messages for every decision block in `format_content`. + + Raises: + A2uiCompilationParseError: If the block is not valid JSON. + A2uiCompilationValidationError: If a block lacks required fields or + the synthesizer rejects it. + A2uiCompilationError: If the decision model abstains and no + fallback produced any messages. + """ + del is_final + messages_by_surface: dict[str, list[AgentToRendererMessage]] = {} + blocks = self.read_blocks(format_content) + for idx, block in enumerate(blocks, start=1): + default_id = ( + self.surface_id if len(blocks) == 1 else f"{self.surface_id}_{idx}" + ) + target_surface_id = block.surface_id or default_id + try: + output = self._synthesizer.synthesize_sync( + block.intent, + block.payload, + surface_id=target_surface_id, + mutable_paths=block.mutable_paths, + template_id=block.template_id, + fallback_dsl=block.fallback_dsl, + layout=block.layout or None, + title=block.title, + summary=block.summary, + ) + except A2uiError: + raise + except (TypeError, ValueError) as exc: + raise A2uiCompilationValidationError( + message=str(exc), raw_content=format_content + ) from exc + if not output.messages: + raise A2uiCompilationError( + message=( + "The decision model abstained" + f" (confidence {output.confidence:.2f}) and no fallback" + " produced messages." + ), + raw_content=format_content, + help_message=( + "Add a 'fallbackDsl' field, name a 'template', or enable" + " fallback_card on the synthesizer." + ), + ) + assert output.stage in SynthesisStage + messages_by_surface[target_surface_id] = list(output.messages) + return [ + msg for surface_msgs in messages_by_surface.values() for msg in surface_msgs + ] + + def decompile(self, a2ui_payload: Sequence[AgentToRendererMessage]) -> str: + """Renders messages as a wrapped decision block. + + Lossy: messages carry no intent, so a synthetic `Render ` + intent is used and only the data model and surface id are recovered. + """ + return DecisionPromptGenerator.wrap_block( + decision_block_from_messages(a2ui_payload) + ) + + +__all__ = ["DecisionParser"] diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/patterns.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/patterns.py new file mode 100644 index 0000000000..06a353f533 --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/patterns.py @@ -0,0 +1,2133 @@ +# 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. + +"""Catalog pattern libraries, template directive expansion, and archetype eligibility.""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +import copy +from dataclasses import dataclass, field +import functools +import json +import re +from typing import Any + +from jsonschema import Draft202012Validator + +from a2ui.core import A2uiValidationError, CatalogApi + +from .archetypes import ( + ArchetypeGrammar, + BlockSpec, + FALLBACK_TERMINALS, + LayoutArchetype, + MeasureSpec, + ShapeFilter, + asset_path, + load_asset, +) +from .bindings import is_v10 as _is_v10 +from .bindings import make_data_binding, make_function_call +from .catalog_graph import CatalogDecisionGraph +from .models import ( + BlockBindings, + PageBindings, + PatternCapabilities, + SlotBinding, +) +from .payload_inspector import PointerSummary + +_PLACEHOLDER_RE = re.compile(r"\{([A-Za-z0-9_$.]+)\}") +_SLUG_RE = re.compile(r"[^a-zA-Z0-9_]+") +_HEADING_LINE_RE = re.compile(r"^\s*#{1,6}\s") + +_OMIT = object() + + +class PatternError(A2uiValidationError): + """Raised when a catalog pattern file fails schema validation or expansion.""" + + +@dataclass(frozen=True) +class PatternVariant: + """One knob-selected component template tree within a catalog pattern.""" + + when: Mapping[str, tuple[str, ...]] = field(default_factory=dict, hash=False) + root: str = "" + components: tuple[Mapping[str, Any], ...] = () + note: str = "" + + def matches(self, knobs: Mapping[str, str]) -> bool: + """Returns whether every condition in `when` matches `knobs`.""" + if not self.when: + return False + return all(knobs.get(k) in allowed for k, allowed in self.when.items()) + + +def _normalize_when(raw: Mapping[str, Any] | None) -> dict[str, tuple[str, ...]]: + """Normalizes a variant ``when`` mapping into string-tuple values.""" + if not raw: + return {} + out: dict[str, tuple[str, ...]] = {} + for key, val in raw.items(): + if isinstance(val, str): + out[key] = (val,) + elif isinstance(val, Sequence): + out[key] = tuple(str(x) for x in val) + return out + + +@dataclass(frozen=True) +class CatalogPattern: + """How a catalog draws one abstract layout pattern.""" + + name: str + slots: tuple[str, ...] + knobs: Mapping[str, tuple[str, ...]] = field(default_factory=dict, hash=False) + variants: tuple[PatternVariant, ...] = () + field_variants: Mapping[str, Mapping[str, Any]] = field( + default_factory=dict, hash=False + ) + note: str = "" + + def select_variant(self, knobs: Mapping[str, str]) -> PatternVariant: + """Returns the first matching `PatternVariant` for `knobs`, or the default.""" + for variant in self.variants: + if variant.matches(knobs): + return variant + for variant in self.variants: + if not variant.when: + return variant + return self.variants[0] + + def supports_variant(self, variant_name: str) -> bool: + """Returns whether `variant_name` is supported by knobs, variants, or fields.""" + if variant_name in self.field_variants: + return True + if any(variant_name in vals for vals in self.knobs.values()): + return True + return any( + variant_name in vals for v in self.variants for vals in v.when.values() + ) + + @classmethod + def from_json(cls, name: str, raw: Mapping[str, Any]) -> CatalogPattern: + """Parses one entry from a pattern file's ``patterns`` mapping.""" + knobs = {k: tuple(str(x) for x in v) for k, v in raw.get("knobs", {}).items()} + raw_variants = raw.get("variants") + if isinstance(raw_variants, Sequence) and raw_variants: + variants = tuple( + PatternVariant( + when=_normalize_when(v.get("when")), + root=str(v["root"]), + components=tuple(copy.deepcopy(c) for c in v["components"]), + note=str(v.get("note", "")), + ) + for v in raw_variants + ) + else: + variants = ( + PatternVariant( + when={}, + root=str(raw["root"]), + components=tuple(copy.deepcopy(c) for c in raw["components"]), + note=str(raw.get("note", "")), + ), + ) + field_variants = { + k: copy.deepcopy(dict(v)) for k, v in raw.get("fieldVariants", {}).items() + } + return cls( + name=name, + slots=tuple(str(s) for s in raw.get("slots", ())), + knobs=knobs, + variants=variants, + field_variants=field_variants, + note=str(raw.get("note", "")), + ) + + +@functools.cache +def _pattern_validator() -> Draft202012Validator: + """Returns the cached JSON Schema validator for ``pattern_definition.json``.""" + return Draft202012Validator(load_asset("pattern_definition.json")) + + +@dataclass(frozen=True) +class PatternRef: + """A pattern name with an optional variant, written ``name:variant``.""" + + name: str + variant: str | None = None + + @classmethod + def parse(cls, text: str) -> PatternRef: + """Parses ``name`` or ``name:variant``; a second colon is part of the variant.""" + name, sep, variant = text.partition(":") + return cls(name=name, variant=variant if sep else None) + + def __str__(self) -> str: + return self.name if self.variant is None else f"{self.name}:{self.variant}" + + +@dataclass(frozen=True) +class ResolvedPattern: + """The pattern a block will draw with, after walking its fallback chain.""" + + pattern: str + knobs: Mapping[str, str] = field(default_factory=dict, hash=False) + """Knob values implied by a ``name:variant`` fallback entry.""" + + +def _split_pattern_query(name: str, variant: str | None) -> tuple[str, str | None]: + """Normalizes ``(name, variant)`` where `name` may itself be ``name:variant``.""" + if variant is not None: + return name, variant + ref = PatternRef.parse(name) + return ref.name, ref.variant + + +class PatternLibrary(PatternCapabilities): + """Pattern definitions loaded for one catalog (or versioned catalog family).""" + + def __init__( + self, + catalog_ids: Sequence[str] | str, + patterns: Mapping[str, CatalogPattern], + *, + version: str = "1", + ) -> None: + if isinstance(catalog_ids, str): + ids: tuple[str, ...] = (catalog_ids,) if catalog_ids else () + else: + ids = tuple(str(c) for c in catalog_ids if c) + self.catalog_ids: tuple[str, ...] = ids + self.catalog_id: str = ids[0] if ids else "" + self.version: str = version + self.patterns: Mapping[str, CatalogPattern] = dict(patterns) + + @classmethod + def from_json(cls, data: Mapping[str, Any]) -> PatternLibrary: + """Validates `data` against ``pattern_definition.json`` and returns a library.""" + if not isinstance(data, Mapping): + raise PatternError("Pattern library JSON must be an object.") + errors = sorted( + _pattern_validator().iter_errors(data), + key=lambda e: [str(p) for p in e.absolute_path], + ) + if errors: + first = errors[0] + loc = "/".join(str(p) for p in first.absolute_path) or "" + raise PatternError(f"Invalid pattern definition at {loc}: {first.message}") + raw_patterns = data["patterns"] + parsed = { + name: CatalogPattern.from_json(name, spec) + for name, spec in raw_patterns.items() + } + return cls( + tuple(data["catalogIds"]), + parsed, + version=str(data.get("version", "1")), + ) + + def has_pattern(self, name: str, variant: str | None = None) -> bool: + """Whether `name` (and `variant`, when given) is defined; implements `PatternCapabilities`.""" + base, sub = _split_pattern_query(name, variant) + pat = self.patterns.get(base) + if pat is None: + return False + if sub is None: + return True + return pat.supports_variant(sub) + + def get(self, pattern: str) -> CatalogPattern | None: + """Returns the `CatalogPattern` named `pattern`, or None.""" + base, _ = _split_pattern_query(pattern, None) + return self.patterns.get(base) + + +@functools.cache +def _bundled_pattern_libraries() -> Mapping[str, PatternLibrary]: + """Loads and indexes all bundled ``assets/patterns/*.json`` files by ``catalogId``.""" + by_catalog_id: dict[str, PatternLibrary] = {} + patterns_dir = asset_path("patterns") + for entry in sorted(patterns_dir.iterdir(), key=lambda p: p.name): + if not entry.name.endswith(".json"): + continue + raw = json.loads(entry.read_text(encoding="utf-8")) + lib = PatternLibrary.from_json(raw) + for cat_id in lib.catalog_ids: + by_catalog_id[cat_id] = lib + return by_catalog_id + + +class MergedPatternLibrary(PatternCapabilities): + """Pattern libraries merged across multiple catalogs, primary catalog winning.""" + + def __init__(self, libraries: Sequence[PatternLibrary]) -> None: + self.libraries: tuple[PatternLibrary, ...] = tuple(libraries) + merged: dict[str, CatalogPattern] = {} + owners: dict[str, str] = {} + cat_ids: list[str] = [] + for lib in self.libraries: + for cid in lib.catalog_ids: + if cid and cid not in cat_ids: + cat_ids.append(cid) + for name, pat in lib.patterns.items(): + if name not in merged: + merged[name] = pat + owners[name] = lib.catalog_id + self.catalog_ids: tuple[str, ...] = tuple(cat_ids) + self.patterns: Mapping[str, CatalogPattern] = merged + self._owners: Mapping[str, str] = owners + + @classmethod + def for_catalogs(cls, catalogs: Sequence[CatalogApi]) -> MergedPatternLibrary: + """Loads the bundled pattern libraries for `catalogs`, in catalog priority order. + + A catalog with no bundled pattern file contributes an empty library, so + the merged result always lists every catalog id. + """ + bundled = _bundled_pattern_libraries() + matched: list[PatternLibrary] = [] + for catalog in catalogs: + cat_id = catalog.catalog_id + lib = bundled.get(cat_id) + if lib is not None: + matched.append( + PatternLibrary( + (cat_id, *lib.catalog_ids), + lib.patterns, + version=lib.version, + ) + ) + else: + matched.append(PatternLibrary((cat_id,), {})) + return cls(matched) + + def has_pattern(self, name: str, variant: str | None = None) -> bool: + """Whether any constituent library defines `name` (and `variant`).""" + base, sub = _split_pattern_query(name, variant) + pat = self.patterns.get(base) + if pat is None: + return False + return True if sub is None else pat.supports_variant(sub) + + def get(self, pattern: str) -> CatalogPattern | None: + """Returns the highest-priority `CatalogPattern` for `pattern`, or None.""" + base, _ = _split_pattern_query(pattern, None) + return self.patterns.get(base) + + def owner_catalog_id(self, pattern: str) -> str | None: + """Returns the ``catalogId`` of the library that won `pattern`.""" + base, _ = _split_pattern_query(pattern, None) + return self._owners.get(base) + + +def _find_knob_in_variants( + variants: Sequence[PatternVariant], variant: str +) -> dict[str, str] | None: + """Searches `variants` for a `when` clause matching `variant`.""" + for v in variants: + for knob_name, values in v.when.items(): + if variant in values: + return {knob_name: variant} + return None + + +def _knob_for_variant( + library: PatternCapabilities, pattern_name: str, variant: str +) -> dict[str, str]: + """Finds the knob name on `pattern_name` that accepts `variant`.""" + getter = getattr(library, "get", None) + pat = getter(pattern_name) if callable(getter) else None + if not isinstance(pat, CatalogPattern): + return {"layout": variant} + for knob_name, values in pat.knobs.items(): + if variant in values: + return {knob_name: variant} + return _find_knob_in_variants(pat.variants, variant) or {"layout": variant} + + +def resolve_fallback_pattern( + block: BlockSpec, library: PatternCapabilities +) -> ResolvedPattern | None: + """Walks `block.pattern` and `block.fallback` against `library`. + + Returns the first entry `library` can draw, or ``None`` if no entry in the + chain is supported. + """ + candidates: list[str] = [block.pattern] + for fb in block.fallback: + if fb not in candidates: + candidates.append(fb) + for entry in candidates: + ref = PatternRef.parse(entry) + if not library.has_pattern(ref.name, ref.variant): + continue + if ref.variant is None: + return ResolvedPattern(pattern=ref.name) + return ResolvedPattern( + pattern=ref.name, + knobs=_knob_for_variant(library, ref.name, ref.variant), + ) + return None + + +# --- Eligibility & Shape Evaluation --- + +_IMAGE_KEY_HINTS = frozenset({ + "image", + "img", + "photo", + "picture", + "thumbnail", + "thumb", + "avatar", + "logo", + "icon", + "poster", +}) +_CURRENCY_KEY_HINTS = frozenset({ + "amount", + "price", + "cost", + "fee", + "total", + "subtotal", + "rate", + "balance", + "currency", + "usd", + "eur", +}) +_STATUS_KEY_HINTS = frozenset({"status", "state", "health", "phase", "stage"}) +_TIME_KEY_HINTS = frozenset( + {"date", "time", "datetime", "timestamp", "arrives", "created", "updated"} +) +_DURATION_KEY_HINTS = frozenset( + {"duration", "uptime", "elapsed", "latency", "ttl", "skipforward"} +) +_RATING_KEY_HINTS = frozenset({"rating", "score", "stars"}) +_LONG_TEXT_KEY_HINTS = frozenset( + {"about", "summary", "description", "body", "bio", "notes", "detail"} +) +_LOCATION_KEY_HINTS = frozenset( + {"address", "coordinates", "coords", "lat", "lng", "latitude", "longitude"} +) + +_NUMERIC_FAMILY = frozenset({ + "number", + "integer", + "count", + "currency", + "percent", + "percentage", + "ratio", + "quantity", + "rating", + "bounded", + "duration", +}) +_STRING_FAMILY = frozenset({ + "string", + "long_text", + "markdown", + "code", + "name", + "title", + "identifier", + "email", + "phone", + "url", + "image_url", + "video_url", + "audio_url", + "document_url", + "place_name", + "address", + "date", + "time", + "datetime", + "duration", + "relative_time", + "date_range", + "enum", + "status", + "color", +}) + + +def _key_tokens(key: str) -> set[str]: + """Splits a camelCase or snake_case key into lowercase tokens.""" + spaced = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", key) + return {t for t in re.split(r"[^a-zA-Z0-9]+", spaced.lower()) if t} + + +_NUMERIC_TOKEN_HINTS: tuple[tuple[frozenset[str], str], ...] = ( + (_RATING_KEY_HINTS, "rating"), + (_CURRENCY_KEY_HINTS, "currency"), + (_DURATION_KEY_HINTS, "duration"), +) +_STRING_TOKEN_HINTS: tuple[tuple[frozenset[str], str], ...] = ( + (_IMAGE_KEY_HINTS, "image_url"), + (_STATUS_KEY_HINTS, "status"), + (_CURRENCY_KEY_HINTS, "currency"), + (_TIME_KEY_HINTS, "date"), + (_LONG_TEXT_KEY_HINTS, "long_text"), + (_LOCATION_KEY_HINTS, "address"), +) + + +def _infer_by_key_table( + tokens: set[str], + table: Sequence[tuple[frozenset[str], str]], + default: str, +) -> str: + """Returns the first semantic type from `table` whose hint tokens match `tokens`.""" + for hints, sem_type in table: + if tokens & hints: + return sem_type + return default + + +def _infer_fallback_semantic_type(ptr: PointerSummary) -> str: + """Infers a fallback semantic type when `ptr.semantic_type` is not populated.""" + if ptr.semantic_type and ptr.semantic_type != "string": + return ptr.semantic_type + tokens = _key_tokens(ptr.key or ptr.path.rsplit("/", 1)[-1]) + if ptr.value_type in ("array", "object", "boolean"): + return ptr.value_type + if ptr.value_type == "number": + return _infer_by_key_table(tokens, _NUMERIC_TOKEN_HINTS, "number") + return _infer_by_key_table(tokens, _STRING_TOKEN_HINTS, ptr.value_type) + + +def _pointer_type_tags(ptr: PointerSummary) -> set[str]: + """Returns all semantic and value type tags matched by `ptr`.""" + sem = _infer_fallback_semantic_type(ptr) + tags = {ptr.value_type, sem, ptr.semantic_type} + if "percent" in tags or "percentage" in tags: + tags.update(("percent", "percentage")) + if sem in _NUMERIC_FAMILY or ptr.value_type == "number": + tags.add("number") + if sem in _STRING_FAMILY and ptr.value_type == "string": + tags.add("string") + if ptr.value_type == "array" and ptr.sample_pointers: + if "image_url" in ptr.element_semantic_types.values(): + tags.add("image_url") + return tags + + +def _key_hint_element_tags(element_keys: Sequence[str]) -> set[str]: + """Infers element semantic tags from `element_keys` tokens.""" + all_tokens: set[str] = set() + for k in element_keys: + all_tokens.update(_key_tokens(k)) + tags: set[str] = {"object"} + if all_tokens & _IMAGE_KEY_HINTS: + tags.add("image_url") + if all_tokens & _TIME_KEY_HINTS: + tags.add("datetime") + return tags + + +def _array_element_tags(ptr: PointerSummary) -> set[str]: + """Returns element type tags for an array `PointerSummary`.""" + tags: set[str] = set() + if ptr.element_keys: + tags.update(_key_hint_element_tags(ptr.element_keys)) + tags.update(ptr.sample_type_by_key.values()) + tags.update(ptr.element_semantic_types.values()) + return tags or {"string"} + + +def _in_bounds(val: int, bounds: tuple[int | None, int | None] | None) -> bool: + """Returns whether `val` lies within inclusive `(low, high)` `bounds`.""" + if bounds is None: + return True + low, high = bounds + return (low is None or val >= low) and (high is None or val <= high) + + +def _array_matches_shape(ptr: PointerSummary, shape: ShapeFilter) -> bool: + """Returns whether an array pointer `ptr` satisfies array constraints on `shape`.""" + if ptr.value_type != "array": + return False + if not _in_bounds(ptr.cardinality, shape.array_length): + return False + if shape.element_types and not ( + _array_element_tags(ptr) & set(shape.element_types) + ): + return False + if shape.element_keys: + wanted = {k.lower() for k in shape.element_keys} + actual = {k.lower() for k in ptr.element_keys} + if not (wanted & actual): + return False + return True + + +def _prose_length_matches( + wanted_levels: tuple[str, ...], + pointers: Sequence[PointerSummary], + measure: MeasureSpec | None, +) -> bool: + """Returns whether any pointer's word count falls in `wanted_levels`.""" + if measure is None: + return False + for ptr in pointers: + word_count = ptr.hints.get("wordCount") + if isinstance(word_count, (int, float)): + if measure.level_for(float(word_count)) in wanted_levels: + return True + return False + + +def _mutable_matches(mutable: bool | None, pointers: Sequence[PointerSummary]) -> bool: + """Returns whether `pointers` satisfy the `mutable` filter.""" + if mutable is None: + return True + has_mutable = any(p.mutable_hint for p in pointers) + return has_mutable if mutable else not has_mutable + + +def _pointer_count_matches( + shape: ShapeFilter, pointers: Sequence[PointerSummary] +) -> bool: + """Returns whether `pointers` satisfy `shape.pointers` and `shape.count`.""" + if shape.pointers: + wanted = set(shape.pointers) + matching = [p for p in pointers if _pointer_type_tags(p) & wanted] + return bool(matching) and _in_bounds(len(matching), shape.count) + if shape.count is not None: + scalars = [p for p in pointers if p.value_type not in ("array", "object")] + return _in_bounds(len(scalars), shape.count) + return True + + +def _has_array_constraint(shape: ShapeFilter) -> bool: + """Returns whether `shape` requires at least one matching array pointer.""" + return bool( + shape.array_length is not None + or shape.element_types + or shape.element_keys + or "array" in shape.pointers + ) + + +def _shape_matches( + shape: ShapeFilter, + pointers: Sequence[PointerSummary], + prose_measure: MeasureSpec | None, +) -> bool: + """Evaluates a `ShapeFilter` against `pointers`.""" + if shape.is_empty: + return True + if not _mutable_matches(shape.mutable, pointers): + return False + if shape.prose_length and not _prose_length_matches( + shape.prose_length, pointers, prose_measure + ): + return False + if _has_array_constraint(shape) and not any( + _array_matches_shape(p, shape) for p in pointers + ): + return False + return _pointer_count_matches(shape, pointers) + + +def _criteria_pattern_satisfied( + archetype: LayoutArchetype, library: PatternCapabilities +) -> bool: + """Checks any ``pattern::`` requirement in `archetype.criteria`.""" + for match in re.finditer( + r"pattern:([a-z_]+)(?::([A-Za-z0-9_]+))?", archetype.criteria + ): + pat_name, variant = match.group(1), match.group(2) + if not library.has_pattern(pat_name, variant): + return False + return True + + +def _block_is_viable( + block: BlockSpec, + library: PatternCapabilities, + pointers: Sequence[PointerSummary], + prose_measure: MeasureSpec | None, +) -> bool: + """Returns whether `block` resolves to a pattern and passes its shape filter.""" + if resolve_fallback_pattern(block, library) is None: + return False + return _shape_matches(block.shape, pointers, prose_measure) + + +def _archetype_is_eligible( + archetype: LayoutArchetype, + grammar: ArchetypeGrammar, + library: PatternCapabilities, + pointers: Sequence[PointerSummary], + prose_measure: MeasureSpec | None, +) -> bool: + """Returns whether `archetype` is eligible for `library` and `pointers`.""" + if not _criteria_pattern_satisfied(archetype, library): + return False + if not _shape_matches(archetype.shape, pointers, prose_measure): + return False + for req_id in archetype.required_block_ids(): + block = grammar.blocks.get(req_id) + if block is None or not _block_is_viable( + block, library, pointers, prose_measure + ): + return False + viable_count = sum( + 1 + for ref in archetype.blocks + if (b := grammar.blocks.get(ref.id)) is not None + and _block_is_viable(b, library, pointers, prose_measure) + ) + return viable_count >= archetype.at_least + + +def _shape_signature(pointers: Sequence[PointerSummary]) -> tuple[Any, ...]: + """Builds a hashable cache signature from `pointers`.""" + return tuple( + ( + p.path, + p.value_type, + p.semantic_type, + p.cardinality, + p.mutable_hint, + p.element_keys, + tuple(sorted(p.sample_type_by_key.items())), + tuple(sorted(p.element_semantic_types.items())), + p.hints.get("wordCount"), + p.sample_pointers, + ) + for p in pointers + ) + + +def eligible_archetypes( + grammar: ArchetypeGrammar, + library: PatternCapabilities, + pointers: Sequence[PointerSummary], +) -> tuple[LayoutArchetype, ...]: + """Returns the archetypes in `grammar` eligible for `library` and `pointers`. + + Pure: callers that evaluate the same payload shape repeatedly should + memoize on `shape_signature(pointers)` themselves. + """ + if not pointers: + return () + prose_block = grammar.blocks.get("prose") + prose_measure = ( + prose_block.measures.get("length") if prose_block is not None else None + ) + return tuple( + arch + for arch in grammar.archetypes + if _archetype_is_eligible(arch, grammar, library, pointers, prose_measure) + ) + + +def shape_signature(pointers: Sequence[PointerSummary]) -> tuple[Any, ...]: + """Builds a hashable key capturing everything eligibility depends on.""" + return _shape_signature(pointers) + + +# --- Pattern Expansion --- + + +@dataclass(frozen=True) +class _ExpansionScope: + """Context carried while expanding one pattern or `$repeat` item.""" + + block_id: str + id_prefix: str + bindings: BlockBindings + knobs: Mapping[str, str] + instances: Mapping[str, str] + field_variants: Mapping[str, Mapping[str, Any]] + block_roots: tuple[str, ...] = () + item_fields: Mapping[str, SlotBinding] = field(default_factory=dict) + item_index: int | None = None + item_pointer: str | None = None + in_template_repeat: bool = False + is_v10: bool = True + + +def _lookup_slot(scope: _ExpansionScope, slot_path: str) -> SlotBinding | None: + """Looks up `slot_path` (e.g. ``headline`` or ``categories.selected``) in `scope`.""" + if slot_path in scope.item_fields: + return scope.item_fields[slot_path] + direct = scope.bindings.get(slot_path) + if direct is not None: + return direct + if "." in slot_path: + parent_name, child_name = slot_path.split(".", 1) + if child_name in scope.item_fields: + return scope.item_fields[child_name] + parent = scope.bindings.get(parent_name) + if parent is not None and child_name in parent.fields: + return parent.fields[child_name] + for binding in scope.bindings.slots.values(): + if slot_path in binding.fields: + return binding.fields[slot_path] + return None + + +def _slot_is_bound(scope: _ExpansionScope, slot_path: str) -> bool: + """Returns whether `slot_path` is bound in `scope`.""" + binding = _lookup_slot(scope, slot_path) + return binding is not None and binding.bound + + +def _escape_markdown_inline(text: str, *, in_heading: bool) -> str: + """Escapes newlines and heading `#` characters before interpolating into `$text`.""" + cleaned = text.replace("\r\n", " ").replace("\n", " ").replace("\r", " ") + if in_heading or "#" in cleaned: + cleaned = cleaned.replace("#", r"\#") + return cleaned + + +def _eval_text_directive(template: str, scope: _ExpansionScope) -> Any: + """Evaluates a ``$text`` string with ``{slot}`` and ``{$index1}`` placeholders.""" + in_heading = bool(_HEADING_LINE_RE.match(template)) + has_pointer = False + + def _replace(match: re.Match[str]) -> str: + nonlocal has_pointer + token = match.group(1) + if token == "$index1": + return str((scope.item_index or 0) + 1) + binding = _lookup_slot(scope, token) + if binding is None or not binding.bound: + return "" + if binding.pointer: + has_pointer = True + return f"${{{binding.pointer}}}" + if binding.literal is not None: + return _escape_markdown_inline(str(binding.literal), in_heading=in_heading) + return "" + + interpolated = _PLACEHOLDER_RE.sub(_replace, template) + if has_pointer: + return make_function_call( + "formatString", {"value": interpolated}, is_v10=scope.is_v10 + ) + return interpolated + + +def _literal_to_str(val: Any) -> str: + """Formats a literal slot value as a lowercase boolean or string.""" + return str(val).lower() if isinstance(val, bool) else str(val) + + +def _item_identity_tokens(scope: _ExpansionScope) -> list[str]: + """Returns pointer, label, and index tokens identifying the current item.""" + tokens: list[str] = [] + if scope.item_pointer: + tokens.append(scope.item_pointer) + label_slot = scope.item_fields.get("label") + if label_slot is not None: + if label_slot.literal is not None: + tokens.append(str(label_slot.literal)) + if label_slot.pointer: + tokens.append(label_slot.pointer) + if scope.item_index is not None: + tokens.append(str(scope.item_index)) + return tokens + + +def _instance_key_candidates(scope: _ExpansionScope, key: str) -> list[str]: + """Builds candidate instance lookup keys in priority order.""" + candidates: list[str] = [] + for token in _item_identity_tokens(scope): + candidates.extend(( + f"{key}:{token}", + f"{scope.block_id}.{key}:{token}", + f"instance:{scope.block_id}.{key}:{token}", + )) + candidates.extend(( + key, + f"{scope.block_id}.{key}", + f"instance:{scope.block_id}.{key}", + )) + return candidates + + +def _flatten_instances( + instances: Mapping[str, Mapping[str, str]] | None, +) -> dict[str, str]: + """Flattens `{elem_key: {q_name: val}}` into ``q_name:elem_key`` lookup keys.""" + if not instances: + return {} + flat: dict[str, str] = {} + for outer_key, outer_val in instances.items(): + for inner_key, inner_val in outer_val.items(): + val_str = str(inner_val) + flat[f"{inner_key}:{outer_key}"] = val_str + flat.setdefault(f"{outer_key}:{inner_key}", val_str) + return flat + + +def _resolve_instance_candidate(scope: _ExpansionScope, key: str) -> str | None: + """Looks up `key` in `scope.instances` across all candidate key forms.""" + for cand in _instance_key_candidates(scope, key): + if cand in scope.instances: + raw = scope.instances[cand] + if key == "primary" and raw not in ("true", "false"): + return "true" if _matches_item_identity(scope, raw) else "false" + return raw + return None + + +def _lookup_instance_or_knob(scope: _ExpansionScope, key: str) -> str | None: + """Looks up `key` across `item_fields`, `instances`, `knobs`, and `bindings`.""" + item_slot = scope.item_fields.get(key) + if item_slot is not None and item_slot.literal is not None: + return _literal_to_str(item_slot.literal) + inst_val = _resolve_instance_candidate(scope, key) + if inst_val is not None: + return inst_val + if key in scope.knobs: + return scope.knobs[key] + slot = _lookup_slot(scope, key) + if slot is not None and slot.literal is not None: + return _literal_to_str(slot.literal) + return None + + +def _matches_item_identity(scope: _ExpansionScope, target: str) -> bool: + """Returns whether `target` matches the current item's index, pointer, or label.""" + if scope.item_index is not None and target == str(scope.item_index): + return True + if scope.item_pointer and target == scope.item_pointer: + return True + label_slot = scope.item_fields.get("label") + if label_slot is not None and ( + label_slot.literal == target or label_slot.pointer == target + ): + return True + return False + + +def _is_self_author(scope: _ExpansionScope) -> bool: + """Returns whether the current message item belongs to the `self` author.""" + self_author = scope.knobs.get("self") or scope.instances.get("self") + if not self_author or self_author == "none": + return False + if self_author in ("true", "yes"): + return True + for author_key in ("author", "sender", "from"): + slot = scope.item_fields.get(author_key) + if slot is not None and slot.literal is not None: + return str(slot.literal) == self_author + return False + + +def _eval_map_directive(directive: Mapping[str, Any], scope: _ExpansionScope) -> Any: + """Evaluates a ``$map`` directive against knobs, instances, or slot literals.""" + key = str(directive["$map"]) + options = {k: v for k, v in directive.items() if not k.startswith("$")} + val = _lookup_instance_or_knob(scope, key) + if val is not None and val in options: + return options[val] + if "$default" in directive: + return directive["$default"] + if "neutral" in options: + return options["neutral"] + return next(iter(options.values()), "") + + +def _slugify_event_name(raw: str) -> str: + """Converts a button label or pointer into a clean action event name.""" + slug = _SLUG_RE.sub("_", raw.strip().lower()).strip("_") + return slug or "action" + + +def _resolve_event_name(raw_name: str, scope: _ExpansionScope) -> str: + """Resolves an ``$event`` slot or literal name into a clean event name.""" + slot = _lookup_slot(scope, raw_name) + if slot is not None and slot.literal is not None: + return _slugify_event_name(str(slot.literal)) + if slot is not None and slot.pointer: + return _slugify_event_name(slot.pointer.rsplit("/", 1)[-1]) + return raw_name + + +def _resolve_event_context( + raw_ctx: Any, scope: _ExpansionScope +) -> dict[str, Any] | None: + """Resolves the optional ``context`` mapping on an ``$event`` directive.""" + if not isinstance(raw_ctx, Mapping): + return None + if raw_ctx.get("$item") is True: + if not scope.item_pointer: + return None + return {"item": make_data_binding(scope.item_pointer, is_v10=scope.is_v10)} + ctx_out: dict[str, Any] = {} + for k, v in raw_ctx.items(): + resolved = _eval_property_value(v, scope) + if resolved is not _OMIT and resolved is not None: + ctx_out[k] = resolved + return ctx_out or None + + +def _eval_event_directive( + directive: Mapping[str, Any], scope: _ExpansionScope +) -> dict[str, Any]: + """Evaluates an ``$event`` directive into an A2UI ``{"event": ...}`` dict.""" + event_body: dict[str, Any] = { + "name": _resolve_event_name(str(directive["$event"]), scope) + } + ctx = _resolve_event_context(directive.get("context"), scope) + if ctx is not None: + event_body["context"] = ctx + return {"event": event_body} + + +def _eval_slot_directive(directive: Mapping[str, Any], scope: _ExpansionScope) -> Any: + """Evaluates a ``$slot`` directive into a data binding, literal, or default.""" + slot_name = str(directive["$slot"]) + binding = _lookup_slot(scope, slot_name) + if binding is not None and binding.bound: + if binding.pointer: + return make_data_binding(binding.pointer, is_v10=scope.is_v10) + if binding.literal is not None: + return copy.deepcopy(binding.literal) + if "$default" in directive: + return copy.deepcopy(directive["$default"]) + return _OMIT + + +def _eval_if_instance_directive( + directive: Mapping[str, Any], scope: _ExpansionScope +) -> Any: + """Evaluates an ``$ifInstance`` conditional property directive.""" + conds = directive["$ifInstance"] + if not isinstance(conds, Mapping): + return _OMIT + for key, expected in conds.items(): + actual = _lookup_instance_or_knob(scope, key) + exp_str = _literal_to_str(expected) + act_norm = "true" if actual in ("true", "yes", "1") else (actual or "false") + if act_norm != exp_str: + return _OMIT + return _eval_property_value(directive.get("value"), scope) + + +def _eval_by_instance_value( + directive: Mapping[str, Any], scope: _ExpansionScope +) -> Any: + """Evaluates a ``$byInstance`` value mapping on a component property.""" + key = str(directive["$byInstance"]) + options = {k: v for k, v in directive.items() if not k.startswith("$")} + val = _lookup_instance_or_knob(scope, key) + if val is not None and val in options: + return options[val] + if "false" in options: + return options["false"] + return next(iter(options.values()), _OMIT) + + +def _eval_knob_value_directive( + directive: Mapping[str, Any], scope: _ExpansionScope +) -> Any: + """Evaluates a ``$knobValue`` directive.""" + val = _lookup_instance_or_knob(scope, str(directive["$knobValue"])) + return val if val is not None else copy.deepcopy(directive.get("$default", "")) + + +def _eval_if_self_directive( + directive: Mapping[str, Any], scope: _ExpansionScope +) -> Any: + """Evaluates an ``$ifSelf`` directive.""" + branch = "true" if _is_self_author(scope) else "false" + return directive["$ifSelf"].get(branch, _OMIT) + + +def _eval_text_wrapper(directive: Mapping[str, Any], scope: _ExpansionScope) -> Any: + """Evaluates a ``$text`` mapping directive.""" + return _eval_text_directive(str(directive["$text"]), scope) + + +_DIRECTIVE_HANDLERS = { + "$slot": _eval_slot_directive, + "$text": _eval_text_wrapper, + "$map": _eval_map_directive, + "$event": _eval_event_directive, + "$knobValue": _eval_knob_value_directive, + "$ifSelf": _eval_if_self_directive, + "$ifInstance": _eval_if_instance_directive, + "$byInstance": _eval_by_instance_value, +} + + +def _eval_mapping_property(raw: Mapping[str, Any], scope: _ExpansionScope) -> Any: + """Evaluates a mapping property value or template directive.""" + for key, handler in _DIRECTIVE_HANDLERS.items(): + if key in raw: + return handler(raw, scope) + if "call" in raw and "args" in raw: + args = _eval_property_value(raw["args"], scope) + return make_function_call( + str(raw["call"]), + args if isinstance(args, Mapping) else {}, + is_v10=scope.is_v10, + ) + out: dict[str, Any] = {} + for k, v in raw.items(): + resolved = _eval_property_value(v, scope) + if resolved is not _OMIT: + out[k] = resolved + return out + + +def _eval_property_value(raw: Any, scope: _ExpansionScope) -> Any: + """Recursively evaluates template directives inside a component property value.""" + if isinstance(raw, list): + items = [_eval_property_value(x, scope) for x in raw] + return [x for x in items if x is not _OMIT] + if isinstance(raw, Mapping): + return _eval_mapping_property(raw, scope) + return raw + + +def _knob_cond_passes(if_knob: Mapping[str, Any], knobs: Mapping[str, str]) -> bool: + """Returns whether every knob condition in `if_knob` is met by `knobs`.""" + for knob_name, allowed in if_knob.items(): + actual = knobs.get(knob_name) + allowed_set = ( + {allowed} if isinstance(allowed, str) else {str(x) for x in allowed} + ) + if actual not in allowed_set: + return False + return True + + +def _infer_media_from_target(target: str, options: Mapping[str, str]) -> str: + """Infers a media semantic type from a lowercased literal or pointer string.""" + if any(ext in target for ext in (".mp3", ".wav", ".ogg", "audio", "podcast")): + if "audio_url" in options: + return "audio_url" + if "long_text" in options and len(target.split()) >= 15: + return "long_text" + return "default" if "default" in options else next(iter(options.keys()), "") + + +def _infer_slot_media_type( + binding: SlotBinding | None, options: Mapping[str, str] +) -> str: + """Infers the semantic type key (e.g. ``video_url`` or ``audio_url``) for `$byType`.""" + if binding is not None: + if binding.semantic_type and binding.semantic_type in options: + return binding.semantic_type + target = ( + f"{binding.semantic_type or ''}" + f" {binding.literal or binding.pointer or ''}".lower() + ) + return _infer_media_from_target(target, options) + if "default" in options: + return "default" + return next(iter(options.keys()), "") + + +def _resolve_by_type_child( + entry: Mapping[str, Any], scope: _ExpansionScope, prefix_fn: Any +) -> list[str]: + """Resolves a ``$byType`` child entry into a single-element prefixed ID list.""" + by_type = entry.get("$byType") + if not isinstance(by_type, str): + return [] + options = {k: str(v) for k, v in entry.items() if not k.startswith("$")} + slot = _lookup_slot(scope, by_type) + chosen_type = _lookup_instance_or_knob( + scope, f"{by_type}.type" + ) or _infer_slot_media_type(slot, options) + chosen_id = options.get(chosen_type) or next(iter(options.values()), None) + return [prefix_fn(chosen_id)] if chosen_id else [] + + +def _child_conditions_pass(entry: Mapping[str, Any], scope: _ExpansionScope) -> bool: + """Returns whether `$if` and `$ifKnob` guards on `entry` pass.""" + if "$if" in entry and not _slot_is_bound(scope, str(entry["$if"])): + return False + if "$ifKnob" in entry and not _knob_cond_passes(entry["$ifKnob"], scope.knobs): + return False + return True + + +def _resolve_child_entry( + entry: Any, scope: _ExpansionScope, prefix_fn: Any +) -> list[str]: + """Resolves one entry in a container's ``children`` list into prefixed child IDs.""" + if isinstance(entry, str): + return [prefix_fn(entry)] + if not isinstance(entry, Mapping): + return [] + if entry.get("$blocks") is True: + return list(scope.block_roots) + if not _child_conditions_pass(entry, scope): + return [] + if "$ifSelf" in entry: + branch = "true" if _is_self_author(scope) else "false" + chosen = entry["$ifSelf"].get(branch) + return [prefix_fn(str(chosen))] if chosen else [] + if "$byType" in entry: + return _resolve_by_type_child(entry, scope, prefix_fn) + child_id = entry.get("id") + return [prefix_fn(str(child_id))] if isinstance(child_id, str) else [] + + +def _normalize_options_list(raw: Any) -> list[dict[str, Any]]: + """Normalizes `ChoicePicker.options` into ``[{"label": ..., "value": ...}]``.""" + if not isinstance(raw, Sequence) or isinstance(raw, (str, bytes)): + return [] + out: list[dict[str, Any]] = [] + for item in raw: + if isinstance(item, Mapping) and "label" in item and "value" in item: + out.append({"label": item["label"], "value": str(item["value"])}) + else: + text = str(item) + out.append({"label": text, "value": text}) + return out + + +_VALID_ICON_NAMES = frozenset({ + "accountCircle", + "add", + "arrowBack", + "arrowForward", + "attachFile", + "calendarToday", + "call", + "camera", + "check", + "close", + "delete", + "download", + "edit", + "event", + "error", + "fastForward", + "favorite", + "favoriteOff", + "folder", + "help", + "home", + "info", + "locationOn", + "lock", + "lockOpen", + "mail", + "menu", + "moreVert", + "moreHoriz", + "notificationsOff", + "notifications", + "pause", + "payment", + "person", + "phone", + "photo", + "print", + "refresh", + "rewind", + "search", + "send", + "settings", + "share", + "shoppingCart", + "skipNext", + "skipPrevious", + "star", + "starHalf", + "starOff", + "upload", + "visibility", + "visibilityOff", + "volumeDown", + "volumeMute", + "volumeOff", + "volumeUp", + "warning", +}) + + +def _coerce_text(comp: dict[str, Any]) -> None: + """Normalizes `Text.text`.""" + text_val = comp.get("text") + if text_val is None: + comp["text"] = "" + elif isinstance(text_val, (int, float, bool)): + comp["text"] = str(text_val) + + +def _coerce_icon(comp: dict[str, Any]) -> None: + """Normalizes `Icon.name` against `BasicCatalog` `IconName` enum values.""" + name_val = comp.get("name") + if name_val is None or ( + isinstance(name_val, str) and name_val not in _VALID_ICON_NAMES + ): + comp["name"] = "info" + + +def _coerce_checkbox(comp: dict[str, Any]) -> None: + """Normalizes `CheckBox` `label` and `value` properties.""" + comp.setdefault("label", "") + if "value" not in comp or isinstance(comp["value"], str): + comp["value"] = bool(comp.get("value")) + + +def _coerce_choice_picker(comp: dict[str, Any]) -> None: + """Normalizes `ChoicePicker` `options` and `value` properties.""" + comp["options"] = _normalize_options_list(comp.get("options")) + val = comp.get("value") + if val is None: + comp["value"] = [] + elif isinstance(val, Mapping): + return + elif isinstance(val, list): + comp["value"] = [str(x) for x in val] + else: + comp["value"] = [str(val)] + + +def _coerce_slider(comp: dict[str, Any]) -> None: + """Normalizes `Slider` `min`, `max`, and `value` properties.""" + if not isinstance(comp.get("min"), (int, float)) or isinstance( + comp.get("min"), bool + ): + comp["min"] = 0 + if not isinstance(comp.get("max"), (int, float)) or isinstance( + comp.get("max"), bool + ): + comp["max"] = 100 + val = comp.get("value") + if isinstance(val, Mapping): + return + if isinstance(val, bool) or not isinstance(val, (int, float)): + try: + comp["value"] = float(str(val)) + except (TypeError, ValueError): + comp["value"] = 0 + + +def _coerce_text_field(comp: dict[str, Any]) -> None: + """Normalizes `TextField` `label` property.""" + comp.setdefault("label", "") + + +def _coerce_datetime_input(comp: dict[str, Any]) -> None: + """Normalizes `DateTimeInput` `value` property.""" + comp.setdefault("value", "") + + +_COMPONENT_COERCERS: Mapping[str, Callable[[dict[str, Any]], None]] = { + "Text": _coerce_text, + "Icon": _coerce_icon, + "ChoicePicker": _coerce_choice_picker, + "CheckBox": _coerce_checkbox, + "Slider": _coerce_slider, + "TextField": _coerce_text_field, + "DateTimeInput": _coerce_datetime_input, +} + + +def _coerce_component_schema_types( + comp: dict[str, Any], *, is_v10: bool = True +) -> None: + """Ensures expanded component properties satisfy BasicCatalog schema types.""" + comp_type = str(comp.get("component", "")) + if comp_type in ("Image", "Video", "AudioPlayer"): + comp.setdefault("url", "") + if comp_type == "Video" and not is_v10: + comp.pop("posterUrl", None) + return + if comp_type == "Button": + if not is_v10 and comp.get("variant") == "default": + comp.pop("variant", None) + return + coercer = _COMPONENT_COERCERS.get(comp_type) + if coercer is not None: + coercer(comp) + + +def _order_repeat_items( + items: Sequence[Mapping[str, SlotBinding]], + order: str | None, + scope: _ExpansionScope, +) -> list[tuple[int, Mapping[str, SlotBinding]]]: + """Orders repeated items according to ``primaryLast`` or ``primaryFirst``.""" + indexed = list(enumerate(items)) + if order not in ("primaryLast", "primaryFirst"): + return indexed + + def _is_primary(pair: tuple[int, Mapping[str, SlotBinding]]) -> bool: + idx, fields = pair + sub_scope = _ExpansionScope( + block_id=scope.block_id, + id_prefix=scope.id_prefix, + bindings=scope.bindings, + knobs=scope.knobs, + instances=scope.instances, + field_variants=scope.field_variants, + item_fields=fields, + item_index=idx, + is_v10=scope.is_v10, + ) + return _lookup_instance_or_knob(sub_scope, "primary") in ( + "true", + "yes", + "primary", + ) + + if order == "primaryLast": + return [p for p in indexed if not _is_primary(p)] + [ + p for p in indexed if _is_primary(p) + ] + return [p for p in indexed if _is_primary(p)] + [ + p for p in indexed if not _is_primary(p) + ] + + +def _coerce_repeat_entry(entry: Any) -> Mapping[str, SlotBinding]: + """Converts one literal sequence element into a field-to-`SlotBinding` mapping.""" + if isinstance(entry, Mapping): + return { + k: v if isinstance(v, SlotBinding) else SlotBinding(literal=v) + for k, v in entry.items() + } + text = str(entry) + return { + "label": SlotBinding(literal=text), + "title": SlotBinding(literal=text), + "headline": SlotBinding(literal=text), + "value": SlotBinding(literal=entry), + } + + +def _default_items_for_repeat( + binding: SlotBinding | None, +) -> tuple[Mapping[str, SlotBinding], ...]: + """Returns per-element field mappings when a repeated slot is unrolled.""" + if binding is None: + return () + if binding.items: + return binding.items + if isinstance(binding.literal, Sequence) and not isinstance( + binding.literal, (str, bytes) + ): + return tuple(_coerce_repeat_entry(e) for e in binding.literal) + return () + + +def _select_field_variant_template( + by_instance_key: str, + scope: _ExpansionScope, +) -> Mapping[str, Any]: + """Selects a ``fieldVariants`` template from `scope` for `by_instance_key`.""" + choice = _lookup_instance_or_knob(scope, by_instance_key) + if choice and choice in scope.field_variants: + return scope.field_variants[choice] + return next(iter(scope.field_variants.values())) + + +def _prefix_for_scope(scope: _ExpansionScope, local_id: str) -> str: + """Prefixes `local_id` with `scope.id_prefix` if not already prefixed.""" + if not scope.id_prefix: + return local_id + if local_id == scope.id_prefix or local_id.startswith(f"{scope.id_prefix}_"): + return local_id + return f"{scope.id_prefix}_{local_id}" + + +def _ensure_template_emitted( + local_id: str, + target_id: str, + templates_by_id: Mapping[str, Mapping[str, Any]], + scope: _ExpansionScope, + emitted: list[dict[str, Any]], +) -> None: + """Expands `templates_by_id[local_id]` as `target_id` if not yet in `emitted`.""" + if local_id in templates_by_id and not any( + c.get("id") == target_id for c in emitted + ): + _expand_inline_component( + templates_by_id[local_id], + target_id, + templates_by_id, + scope, + emitted, + ) + + +def _expand_child_property( + comp_dict: dict[str, Any], + comp_id: str, + val: Any, + templates_by_id: Mapping[str, Mapping[str, Any]], + scope: _ExpansionScope, + emitted: list[dict[str, Any]], +) -> None: + """Expands a single-child ``child`` property on `comp_dict`.""" + if isinstance(val, Mapping) and "component" in val: + inline_id = f"{comp_id}_child" + _expand_inline_component(val, inline_id, templates_by_id, scope, emitted) + comp_dict["child"] = inline_id + elif isinstance(val, str): + target_id = _prefix_for_scope(scope, val) + comp_dict["child"] = target_id + _ensure_template_emitted(val, target_id, templates_by_id, scope, emitted) + + +def _expand_inline_component( + raw_comp: Mapping[str, Any], + comp_id: str, + templates_by_id: Mapping[str, Mapping[str, Any]], + scope: _ExpansionScope, + emitted: list[dict[str, Any]], +) -> str: + """Expands a single component template (and any inline child dicts) into `emitted`.""" + comp_dict: dict[str, Any] = {"id": comp_id} + emitted_index = len(emitted) + emitted.append(comp_dict) + prefix_fn = functools.partial(_prefix_for_scope, scope) + + for key, val in raw_comp.items(): + if key == "id" or key.startswith("$"): + continue + if key == "child": + _expand_child_property( + comp_dict, comp_id, val, templates_by_id, scope, emitted + ) + elif key == "children": + _expand_children_property( + comp_dict, comp_id, val, templates_by_id, scope, prefix_fn, emitted + ) + else: + resolved = _eval_property_value(val, scope) + if resolved is not _OMIT: + comp_dict[key] = resolved + + _coerce_component_schema_types(comp_dict, is_v10=scope.is_v10) + emitted[emitted_index] = comp_dict + return comp_id + + +def _infer_element_pointer(fields: Mapping[str, SlotBinding]) -> str | None: + """Extracts a representative JSON pointer from an item's field bindings.""" + for key in ("value", "headline", "title", "label"): + slot = fields.get(key) + if slot is not None and slot.pointer: + return slot.pointer + for slot in fields.values(): + if slot.pointer: + return slot.pointer + return None + + +def _expand_template_child_list( + comp_dict: dict[str, Any], + binding: SlotBinding, + tpl_local_id: str, + templates_by_id: Mapping[str, Mapping[str, Any]], + scope: _ExpansionScope, + prefix_fn: Any, + emitted: list[dict[str, Any]], +) -> None: + """Emits a ``TemplateChildList`` (`{"path": ..., "componentId": ...}`) on `comp_dict`.""" + tpl_id = prefix_fn(tpl_local_id) + rel_fields = { + k: SlotBinding( + pointer=v.pointer.lstrip("/") if v.pointer else None, + literal=v.literal, + fields=v.fields, + items=v.items, + ) + for k, v in binding.fields.items() + } + tpl_scope = _ExpansionScope( + block_id=scope.block_id, + id_prefix=scope.id_prefix, + bindings=scope.bindings, + knobs=scope.knobs, + instances=scope.instances, + field_variants=scope.field_variants, + item_fields=rel_fields, + item_pointer=binding.pointer, + in_template_repeat=True, + is_v10=scope.is_v10, + ) + _ensure_template_emitted(tpl_local_id, tpl_id, templates_by_id, tpl_scope, emitted) + comp_dict["children"] = {"path": binding.pointer, "componentId": tpl_id} + + +def _expand_single_repeat_item( + out_idx: int, + orig_idx: int, + item_fields: Mapping[str, SlotBinding], + parent_id: str, + comp_target: Any, + binding: SlotBinding | None, + templates_by_id: Mapping[str, Mapping[str, Any]], + scope: _ExpansionScope, + prefix_fn: Any, + emitted: list[dict[str, Any]], +) -> str: + """Expands one unrolled item in a `$repeat` container and returns its component ID.""" + elem_ptr = _infer_element_pointer(item_fields) or ( + f"{binding.pointer}/{orig_idx}" if binding and binding.pointer else None + ) + if isinstance(comp_target, Mapping) and "$byInstance" in comp_target: + item_scope = _ExpansionScope( + block_id=scope.block_id, + id_prefix=f"{parent_id}_{out_idx}", + bindings=scope.bindings, + knobs=scope.knobs, + instances=scope.instances, + field_variants=scope.field_variants, + item_fields=item_fields, + item_index=orig_idx, + item_pointer=elem_ptr, + is_v10=scope.is_v10, + ) + fv_template = _select_field_variant_template( + str(comp_target["$byInstance"]), item_scope + ) + item_comp_id = f"{parent_id}_item_{out_idx}" + return _expand_inline_component( + fv_template, item_comp_id, templates_by_id, item_scope, emitted + ) + + tpl_local_id = str(comp_target) + item_comp_id = f"{prefix_fn(tpl_local_id)}_{out_idx}" + base_prefix = scope.id_prefix or scope.block_id + item_scope_prefixed = _ExpansionScope( + block_id=scope.block_id, + id_prefix=f"{base_prefix}_{out_idx}", + bindings=scope.bindings, + knobs=scope.knobs, + instances=scope.instances, + field_variants=scope.field_variants, + item_fields=item_fields, + item_index=orig_idx, + item_pointer=elem_ptr, + is_v10=scope.is_v10, + ) + return _expand_inline_component( + templates_by_id[tpl_local_id], + item_comp_id, + templates_by_id, + item_scope_prefixed, + emitted, + ) + + +def _fallback_unrolled_items( + binding: SlotBinding | None, +) -> tuple[Mapping[str, SlotBinding], ...]: + """Returns fallback single-item fields when `$repeat` has no explicit items.""" + if binding is not None and binding.fields: + return (binding.fields,) + return ( + { + "label": SlotBinding(literal="Item"), + "title": SlotBinding(literal="Item"), + "headline": SlotBinding(literal="Item"), + "value": SlotBinding(literal=""), + }, + ) + + +def _expand_repeat_children( + comp_dict: dict[str, Any], + parent_id: str, + repeat_spec: Mapping[str, Any], + templates_by_id: Mapping[str, Mapping[str, Any]], + scope: _ExpansionScope, + prefix_fn: Any, + emitted: list[dict[str, Any]], +) -> None: + """Expands a ``{"$repeat": ...}`` ``children`` directive on `comp_dict`.""" + slot_name = str(repeat_spec["$repeat"]) + binding = _lookup_slot(scope, slot_name) + comp_target = repeat_spec["component"] + unrolled_items = _default_items_for_repeat(binding) + + if ( + not unrolled_items + and binding is not None + and binding.pointer + and isinstance(comp_target, str) + ): + _expand_template_child_list( + comp_dict, + binding, + comp_target, + templates_by_id, + scope, + prefix_fn, + emitted, + ) + return + + items_to_expand = unrolled_items or _fallback_unrolled_items(binding) + order = scope.knobs.get("order") or repeat_spec.get("order") + ordered = _order_repeat_items(items_to_expand, str(order) if order else None, scope) + comp_dict["children"] = [ + _expand_single_repeat_item( + out_idx, + orig_idx, + item_fields, + parent_id, + comp_target, + binding, + templates_by_id, + scope, + prefix_fn, + emitted, + ) + for out_idx, (orig_idx, item_fields) in enumerate(ordered) + ] + + +def _find_matching_template_id( + cid: str, + templates_by_id: Mapping[str, Mapping[str, Any]], + prefix_fn: Any, +) -> str | None: + """Finds the template key in `templates_by_id` that maps to `cid`.""" + for tid in templates_by_id: + if prefix_fn(tid) == cid or tid == cid: + return tid + return None + + +def _expand_children_property( + comp_dict: dict[str, Any], + comp_id: str, + raw_children: Any, + templates_by_id: Mapping[str, Mapping[str, Any]], + scope: _ExpansionScope, + prefix_fn: Any, + emitted: list[dict[str, Any]], +) -> None: + """Expands a ``children`` list or ``$repeat`` object on `comp_dict`.""" + if isinstance(raw_children, Mapping) and "$repeat" in raw_children: + _expand_repeat_children( + comp_dict, + comp_id, + raw_children, + templates_by_id, + scope, + prefix_fn, + emitted, + ) + return + if not isinstance(raw_children, Sequence) or isinstance(raw_children, (str, bytes)): + return + child_ids: list[str] = [] + for idx, entry in enumerate(raw_children): + if isinstance(entry, Mapping) and "component" in entry: + inline_id = f"{comp_id}_child_{idx}" + _expand_inline_component(entry, inline_id, templates_by_id, scope, emitted) + child_ids.append(inline_id) + continue + for cid in _resolve_child_entry(entry, scope, prefix_fn): + child_ids.append(cid) + local_match = _find_matching_template_id(cid, templates_by_id, prefix_fn) + if local_match is not None: + _ensure_template_emitted( + local_match, cid, templates_by_id, scope, emitted + ) + comp_dict["children"] = child_ids + + +def _is_container_now_empty( + comp: dict[str, Any], + by_id: Mapping[str, dict[str, Any]], + preserve_ids: set[str], +) -> bool: + """Updates container child references and returns whether the container is empty.""" + ctype = comp.get("component") + if ctype in ("Row", "Column", "List"): + children = comp.get("children") + if isinstance(children, list): + comp["children"] = [x for x in children if x in by_id or x in preserve_ids] + return not comp["children"] + elif ctype == "Card": + child = comp.get("child") + return child not in by_id and child not in preserve_ids + return False + + +def _drop_empty_non_root_containers( + by_id: dict[str, dict[str, Any]], + root_id: str, + preserve_ids: set[str], +) -> set[str]: + """Iteratively removes empty non-root containers from `by_id`.""" + removed_all: set[str] = set() + while True: + empty_ids = { + cid + for cid, comp in list(by_id.items()) + if cid != root_id and _is_container_now_empty(comp, by_id, preserve_ids) + } + if not empty_ids: + break + for eid in empty_ids: + by_id.pop(eid, None) + removed_all.update(empty_ids) + return removed_all + + +def _referenced_children(comp: Mapping[str, Any]) -> list[str]: + """Returns direct child component IDs referenced by `comp`.""" + refs: list[str] = [] + child = comp.get("child") + if isinstance(child, str): + refs.append(child) + children = comp.get("children") + if isinstance(children, list): + refs.extend(str(x) for x in children if isinstance(x, str)) + elif isinstance(children, Mapping): + tpl_id = children.get("componentId") + if isinstance(tpl_id, str): + refs.append(tpl_id) + return refs + + +def _collect_reachable_ids( + by_id: Mapping[str, dict[str, Any]], root_id: str +) -> set[str]: + """Returns component IDs reachable from `root_id`.""" + reachable: set[str] = set() + queue = [root_id] + while queue: + curr = queue.pop(0) + if curr in reachable or curr not in by_id: + continue + reachable.add(curr) + queue.extend(_referenced_children(by_id[curr])) + return reachable + + +def _prune_empty_containers( + components: list[dict[str, Any]], + root_id: str, + *, + preserve_ids: set[str] | None = None, +) -> list[dict[str, Any]]: + """Removes non-root empty containers and unreachable components.""" + preserved = preserve_ids or set() + by_id = {str(c["id"]): c for c in components if "id" in c} + removed_ids = _drop_empty_non_root_containers(by_id, root_id, preserved) + + root_comp = by_id.get(root_id) + if root_comp is not None and isinstance(root_comp.get("children"), list): + root_comp["children"] = [ + x for x in root_comp["children"] if x in by_id or x in preserved + ] + + reachable = _collect_reachable_ids(by_id, root_id) + return [c for c in components if c.get("id") in reachable] + + +def _remap_field_dict( + fields: Mapping[str, SlotBinding], field_map: Mapping[str, str] +) -> dict[str, SlotBinding]: + """Copies `fields` and aliases any `src -> dst` keys in `field_map`.""" + remapped = dict(fields) + for src, dst in field_map.items(): + if src in remapped and dst not in remapped: + remapped[dst] = remapped[src] + return remapped + + +def _remap_slot_binding( + binding: SlotBinding, field_map: Mapping[str, str] +) -> SlotBinding: + """Returns `binding` with `field_map` applied to both `fields` and `items`.""" + return SlotBinding( + pointer=binding.pointer, + literal=binding.literal, + fields=_remap_field_dict(binding.fields, field_map), + items=tuple(_remap_field_dict(it, field_map) for it in binding.items), + semantic_type=binding.semantic_type, + ) + + +def _adapt_comparison_slots(slots: dict[str, SlotBinding]) -> None: + """Remaps `comparison` `options` into `collection` `items`.""" + if "options" in slots and "items" not in slots: + slots["items"] = _remap_slot_binding( + slots["options"], {"badge": "meta", "highlight": "meta"} + ) + + +def _adapt_timeline_slots(slots: dict[str, SlotBinding], target_pattern: str) -> None: + """Remaps `timeline` `events` into `steps` or `collection` `items`.""" + if "events" in slots and "items" not in slots: + field_map = ( + {"title": "headline", "detail": "supporting", "time": "meta"} + if target_pattern == "collection" + else {} + ) + slots["items"] = _remap_slot_binding(slots["events"], field_map) + + +def _adapt_map_slots(slots: dict[str, SlotBinding]) -> None: + """Remaps `map` `location` and `label` slots into `facts` `rows`.""" + if "rows" in slots: + return + loc = slots.get("location") or SlotBinding(literal="") + lbl = slots.get("label") or SlotBinding(literal="Location") + slots["rows"] = SlotBinding(items=({"label": lbl, "value": loc},)) + + +_DIRECT_SLOT_REMAPS: dict[tuple[str, str], tuple[str, str]] = { + ("chart", "headline"): ("series", "items"), + ("chart", "collection"): ("series", "items"), + ("headline", "facts"): ("items", "rows"), +} + + +def _adapt_fallback_bindings( + source_pattern: str, target_pattern: str, bindings: BlockBindings +) -> BlockBindings: + """Remaps slot names when `source_pattern` degrades to `target_pattern`.""" + if source_pattern == target_pattern: + return bindings + slots = dict(bindings.slots) + pair = (source_pattern, target_pattern) + if pair == ("comparison", "collection"): + _adapt_comparison_slots(slots) + elif source_pattern == "timeline" and target_pattern in ("steps", "collection"): + _adapt_timeline_slots(slots, target_pattern) + elif pair in _DIRECT_SLOT_REMAPS: + src_slot, dst_slot = _DIRECT_SLOT_REMAPS[pair] + if src_slot in slots and dst_slot not in slots: + slots[dst_slot] = slots[src_slot] + elif pair == ("map", "facts"): + _adapt_map_slots(slots) + return BlockBindings(slots=slots) + + +def _compute_root_id(prefix: str, root_local_id: str) -> str: + """Computes the surface or block root component ID for `prefix`.""" + if prefix == "root": + return "root" + if root_local_id == prefix or root_local_id.startswith(f"{prefix}_"): + return root_local_id + return f"{prefix}_{root_local_id}" + + +def _page_knobs(page: PageBindings, active_knobs: dict[str, str]) -> None: + """Adds the frame knobs implied by `page` to `active_knobs`.""" + if page.dialog: + active_knobs.setdefault("dialog", "yes") + if page.sticky_actions: + active_knobs.setdefault("stickyActions", "yes") + + +class PatternExpander: + """Expands catalog pattern templates into flat, validated A2UI component dicts.""" + + def __init__( + self, + library: PatternLibrary | MergedPatternLibrary, + graph: CatalogDecisionGraph, + *, + grammar: ArchetypeGrammar | None = None, + protocol_version: str | None = None, + ) -> None: + """Creates an expander. + + Args: + library: Patterns to expand from. + graph: The catalog graph; supplies the protocol version by default. + grammar: Grammar consulted for fallback chains; defaults to + `ArchetypeGrammar.default()`. + protocol_version: A2UI protocol version the emitted components + target (``"0.9"``, ``"1.0"``, ...); defaults to + `graph.protocol_version`. + """ + self.library = library + self.graph = graph + self.grammar = grammar if grammar is not None else ArchetypeGrammar.default() + self.protocol_version: str = ( + protocol_version + if protocol_version is not None + else str(graph.protocol_version) + ) + self.is_v10 = _is_v10(self.protocol_version) + + def _resolve_block_pattern( + self, + block_id: str, + pattern: str, + base_pattern: str, + bindings: BlockBindings, + active_knobs: dict[str, str], + ) -> tuple[CatalogPattern, BlockBindings]: + """Resolves `base_pattern` (or its fallback chain) from `self.library`.""" + cat_pattern = self.library.get(base_pattern) + if cat_pattern is not None: + return cat_pattern, bindings + block_spec = self.grammar.blocks.get(block_id) or self.grammar.blocks.get( + base_pattern + ) + if block_spec is not None: + resolved = resolve_fallback_pattern(block_spec, self.library) + if resolved is not None: + for k, v in resolved.knobs.items(): + active_knobs.setdefault(k, v) + adapted = _adapt_fallback_bindings( + base_pattern, resolved.pattern, bindings + ) + cat_pattern = self.library.get(resolved.pattern) + if cat_pattern is not None: + return cat_pattern, adapted + raise PatternError( + f"Pattern {pattern!r} for block {block_id!r} is not available." + ) + + def expand_block( + self, + block_id: str, + pattern: str, + bindings: BlockBindings, + knobs: Mapping[str, str] | None = None, + instances: Mapping[str, Mapping[str, str]] | None = None, + id_prefix: str = "", + ) -> list[dict[str, Any]]: + """Expands one block pattern into flat A2UI component dicts. + + Args: + block_id: Grammar block id; prefixes every emitted component id. + pattern: Pattern name, optionally ``name:variant``. + bindings: Slot bindings for the block. + knobs: Anatomy knob values selecting the pattern variant. + instances: Per-element instance answers in the + `PlannedBlock.instances` shape: element key to a mapping of + question name to option. + id_prefix: Overrides `block_id` as the component id prefix. + """ + active_knobs: dict[str, str] = dict(knobs or {}) + active_instances = _flatten_instances(instances) + base_pattern, inline_variant = _split_pattern_query(pattern, None) + if inline_variant is not None: + active_knobs.update( + _knob_for_variant(self.library, base_pattern, inline_variant) + ) + + cat_pattern, effective_bindings = self._resolve_block_pattern( + block_id, pattern, base_pattern, bindings, active_knobs + ) + variant = cat_pattern.select_variant(active_knobs) + prefix = id_prefix or block_id + templates_by_id = {str(c["id"]): c for c in variant.components if "id" in c} + root_id = _compute_root_id(prefix, variant.root) + scope = _ExpansionScope( + block_id=block_id, + id_prefix=prefix, + bindings=effective_bindings, + knobs=active_knobs, + instances=active_instances, + field_variants=cat_pattern.field_variants, + is_v10=self.is_v10, + ) + emitted: list[dict[str, Any]] = [] + _expand_inline_component( + templates_by_id[variant.root], + root_id, + templates_by_id, + scope, + emitted, + ) + return _prune_empty_containers(emitted, root_id) + + def expand_page( + self, + page: PageBindings, + block_roots: Sequence[str] = (), + *, + knobs: Mapping[str, str] | None = None, + ) -> list[dict[str, Any]]: + """Expands the `page` pattern with ``root`` as the surface root component id. + + Args: + page: Title, subtitle, mark, and frame flags for the page. + block_roots: Root component ids of the expanded blocks, in order. + knobs: Extra page knobs; `page.dialog` and `page.sticky_actions` + set ``dialog`` and ``stickyActions`` unless given here. + """ + active_knobs: dict[str, str] = dict(knobs or {}) + _page_knobs(page, active_knobs) + title_slot, subtitle_slot, mark_slot = page.title, page.subtitle, page.mark + cat_pattern = self.library.get("page") + if cat_pattern is None: + raise PatternError("Pattern 'page' is not available in the library.") + variant = cat_pattern.select_variant(active_knobs) + templates_by_id = {str(c["id"]): c for c in variant.components if "id" in c} + bindings = BlockBindings( + slots={ + "title": title_slot, + "subtitle": subtitle_slot, + "mark": mark_slot, + } + ) + scope = _ExpansionScope( + block_id="page", + id_prefix="", + bindings=bindings, + knobs=active_knobs, + instances={}, + field_variants=cat_pattern.field_variants, + block_roots=tuple(block_roots), + is_v10=self.is_v10, + ) + emitted: list[dict[str, Any]] = [] + _expand_inline_component( + templates_by_id[variant.root], + "root", + templates_by_id, + scope, + emitted, + ) + if not title_slot.bound and ( + mark_slot.bound or subtitle_slot.bound or block_roots + ): + emitted = [c for c in emitted if c.get("id") != "page_title"] + return _prune_empty_containers(emitted, "root", preserve_ids=set(block_roots)) + + +__all__ = [ + "CatalogPattern", + "MergedPatternLibrary", + "PatternError", + "PatternExpander", + "PatternLibrary", + "PatternRef", + "PatternVariant", + "ResolvedPattern", + "eligible_archetypes", + "resolve_fallback_pattern", + "shape_signature", +] diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/payload_inspector.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/payload_inspector.py new file mode 100644 index 0000000000..2d886178e7 --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/payload_inspector.py @@ -0,0 +1,299 @@ +# 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. + +"""JSON Pointer payload inspector for local decision-model A2UI synthesis.""" + +from __future__ import annotations + +from collections.abc import Collection, Mapping, Sequence +from dataclasses import dataclass, field +from typing import Any, Literal + +from .models import SemanticType +from .semantic_types import classify_array_field, classify_scalar, humanize_key + +PointerValueType = Literal["string", "number", "boolean", "array", "object"] + + +@dataclass(frozen=True) +class PointerSummary: + """Structural summary of a bindable JSON Pointer path in a data payload. + + `value_type` is the coarse JSON type; `semantic_type` and the fields after + it are the semantic view the archetype grammar binds slots against. They + default so callers that only know the coarse type keep working. + """ + + path: str + value_type: PointerValueType + cardinality: int + element_keys: tuple[str, ...] = () + sample_type_by_key: dict[str, str] = field(default_factory=dict, hash=False) + mutable_hint: bool = False + semantic_type: SemanticType = SemanticType.STRING + """The payload inspector populates it; plain strings are coerced.""" + hints: Mapping[str, Any] = field(default_factory=dict, hash=False) + """Detector hints such as `wordCount`, `unit`, `currency`, `min`, `max`.""" + key: str = "" + """The last pointer segment, unescaped; derived from `path` when empty.""" + label: str = "" + """Humanized key for display.""" + parent: str | None = None + """The parent pointer (``""`` for top-level keys); derived when None.""" + element_semantic_types: Mapping[str, SemanticType] = field( + default_factory=dict, hash=False + ) + """For arrays: element key to its `SemanticType`.""" + sample_pointers: tuple[str, ...] = () + """Element-level pointers offered to single-value slots, e.g. ``/photos/0/url``.""" + + def __post_init__(self) -> None: + object.__setattr__(self, "element_keys", tuple(self.element_keys)) + object.__setattr__(self, "sample_type_by_key", dict(self.sample_type_by_key)) + object.__setattr__(self, "hints", dict(self.hints)) + object.__setattr__(self, "semantic_type", SemanticType(self.semantic_type)) + object.__setattr__( + self, + "element_semantic_types", + {k: SemanticType(v) for k, v in self.element_semantic_types.items()}, + ) + object.__setattr__(self, "sample_pointers", tuple(self.sample_pointers)) + if not self.key or self.parent is None: + parent, key = split_pointer(self.path) + if not self.key: + object.__setattr__(self, "key", key) + if self.parent is None: + object.__setattr__(self, "parent", parent) + + +def _escape_pointer_segment(key: str) -> str: + """Escapes a single JSON object key for an RFC 6901 JSON Pointer.""" + return key.replace("~", "~0").replace("/", "~1") + + +def _unescape_pointer_segment(segment: str) -> str: + """Reverses `_escape_pointer_segment` for a single pointer segment.""" + return segment.replace("~1", "/").replace("~0", "~") + + +def split_pointer(path: str) -> tuple[str, str]: + """Splits a JSON Pointer into its parent pointer and unescaped last key. + + ``"/a/b~1c"`` becomes ``("/a", "b/c")``; a relative key such as ``"name"`` + becomes ``("", "name")``; the root pointer ``""`` becomes ``("", "")``. + """ + if "/" not in path: + return "", _unescape_pointer_segment(path) + parent, _, last = path.rpartition("/") + return parent, _unescape_pointer_segment(last) + + +def _classify_value_type(value: Any) -> PointerValueType | None: + """Classifies a Python runtime value into an A2UI JSON Pointer value type.""" + if isinstance(value, bool): + return "boolean" + if isinstance(value, (int, float)): + return "number" + if isinstance(value, str): + return "string" + if isinstance(value, Mapping): + return "object" + if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)): + return "array" + return None + + +def _is_mutable_path(path: str, mutable_paths: set[str]) -> bool: + """Returns whether `path` or any of its parent prefixes is in `mutable_paths`.""" + if not mutable_paths: + return False + if "/" in mutable_paths or path in mutable_paths: + return True + for candidate in mutable_paths: + prefix = candidate.rstrip("/") + if prefix and path.startswith(f"{prefix}/"): + return True + return False + + +def _record_element_mapping( + item: Mapping[str, Any], + element_keys: list[str], + sample_type_by_key: dict[str, str], + values_by_key: dict[str, list[Any]], + siblings_by_key: dict[str, list[Mapping[str, Any]]], +) -> None: + """Records RFC 6901-escaped keys, coarse types, and column values from a dict item.""" + for raw_key, raw_val in item.items(): + key = _escape_pointer_segment(str(raw_key)) + if key not in element_keys: + element_keys.append(key) + if key not in sample_type_by_key: + val_type = _classify_value_type(raw_val) + if val_type is not None: + sample_type_by_key[key] = val_type + values_by_key.setdefault(key, []).append(raw_val) + siblings_by_key.setdefault(key, []).append(item) + + +def _compute_element_semantics( + path: str, + items: Sequence[Any], + unescaped_key: str, + element_keys: Sequence[str], + values_by_key: Mapping[str, Sequence[Any]], + siblings_by_key: Mapping[str, Sequence[Mapping[str, Any]]], +) -> tuple[dict[str, SemanticType], tuple[str, ...]]: + """Computes `element_semantic_types` and `sample_pointers` for an array node.""" + element_semantic_types: dict[str, SemanticType] = {} + sample_pointers: list[str] = [] + for key in element_keys: + raw_field = _unescape_pointer_segment(key) + sem = classify_array_field( + values_by_key.get(key, ()), + raw_field, + siblings_per_item=siblings_by_key.get(key), + ) + element_semantic_types[key] = sem + if sem == SemanticType.IMAGE_URL: + sample_pointers.append(f"{path}/0/{key}") + + if not element_keys and items: + scalar_sem = classify_array_field(items, unescaped_key) + if scalar_sem == SemanticType.IMAGE_URL: + sample_pointers.append(f"{path}/0") + + return element_semantic_types, tuple(sample_pointers) + + +def _summarize_array( + path: str, items: Sequence[Any], is_mutable: bool +) -> PointerSummary: + """Builds a PointerSummary for an array node without recursing into indices.""" + element_keys: list[str] = [] + sample_type_by_key: dict[str, str] = {} + values_by_key: dict[str, list[Any]] = {} + siblings_by_key: dict[str, list[Mapping[str, Any]]] = {} + for item in items: + if isinstance(item, Mapping): + _record_element_mapping( + item, + element_keys, + sample_type_by_key, + values_by_key, + siblings_by_key, + ) + + _, unescaped_key = split_pointer(path) + element_semantic_types, sample_pointers = _compute_element_semantics( + path, + items, + unescaped_key, + element_keys, + values_by_key, + siblings_by_key, + ) + sem_type = SemanticType.ARRAY if items else SemanticType.EMPTY + return PointerSummary( + path=path, + value_type="array", + cardinality=len(items), + element_keys=tuple(element_keys), + sample_type_by_key=sample_type_by_key, + mutable_hint=is_mutable, + semantic_type=sem_type, + key=unescaped_key, + label=humanize_key(unescaped_key), + element_semantic_types=element_semantic_types, + sample_pointers=sample_pointers, + ) + + +def _summarize_mapping_node( + path: str, + value: Mapping[str, Any], + raw_key: str, + is_mutable: bool, +) -> PointerSummary: + """Builds a `PointerSummary` for a nested mapping (empty or non-empty).""" + sem_type = SemanticType.OBJECT if value else SemanticType.EMPTY + return PointerSummary( + path=path, + value_type="object", + cardinality=len(value), + mutable_hint=is_mutable, + semantic_type=sem_type, + key=raw_key, + label=humanize_key(raw_key), + ) + + +def _traverse_mapping( + node: Mapping[str, Any], + prefix: str, + mutable_set: set[str], + out: list[PointerSummary], +) -> None: + """Recursively walks `node` and appends `PointerSummary` entries to `out`.""" + for raw_key, value in node.items(): + raw_key_str = str(raw_key) + segment = _escape_pointer_segment(raw_key_str) + path = f"{prefix}/{segment}" + is_mutable = _is_mutable_path(path, mutable_set) + if isinstance(value, Mapping): + out.append(_summarize_mapping_node(path, value, raw_key_str, is_mutable)) + if value: + _traverse_mapping(value, path, mutable_set, out) + continue + if isinstance(value, Sequence) and not isinstance( + value, (str, bytes, bytearray) + ): + out.append(_summarize_array(path, value, is_mutable)) + continue + scalar_type = _classify_value_type(value) + if scalar_type is not None: + sem_type, hints = classify_scalar(value, raw_key_str, siblings=node) + out.append( + PointerSummary( + path=path, + value_type=scalar_type, + cardinality=1, + mutable_hint=is_mutable, + semantic_type=sem_type, + hints=hints, + key=raw_key_str, + label=humanize_key(raw_key_str), + ) + ) + + +def inspect_payload_pointers( + payload: Mapping[str, Any], + *, + mutable_paths: Collection[str] = (), +) -> list[PointerSummary]: + """Extracts RFC 6901 JSON Pointer summaries from a structured data payload. + + Args: + payload: The root dictionary representing the surface data model. + mutable_paths: Collection of JSON Pointer paths (or parent prefixes) that + are mutable or user-editable. + + Returns: + A list of `PointerSummary` entries in traversal order. + """ + results: list[PointerSummary] = [] + mutable_set = {str(p) for p in mutable_paths} + _traverse_mapping(payload, "", mutable_set, results) + return results diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/prompt_generator.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/prompt_generator.py new file mode 100644 index 0000000000..78ce44efec --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/prompt_generator.py @@ -0,0 +1,276 @@ +# 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. + +"""Prompt generator for the decision inference format. + +In this format the model does not author UI. It emits an intent and the data +to show, and the local decision model picks and binds the components. +""" + +from __future__ import annotations + +from collections.abc import Sequence +import json +from typing import Any + +from a2ui.constants import A2UI_INFERENCE_CLOSE_TAG, A2UI_INFERENCE_OPEN_TAG +from a2ui.core import CatalogApi +from a2ui.core.schema import AgentToRendererMessage +from a2ui.inference_formats._shared import check_mixed_catalogs +from a2ui.prompt import PromptGenerator + +from .archetypes import ArchetypeGrammar +from .catalog_graph import CatalogDecisionGraph +from .decision_block import DecisionBlock, decision_block_from_messages +from .models import MAX_BRIEF_SECTIONS +from .template_registry import TemplateRegistry + +DECISION_RULES_TEMPLATE = f"""# A2UI Decision Block Output Contract + +To show the user a rich interface, do not write components. Describe what to +show and provide the data; a local decision model chooses and binds the +components from the active catalogs. + +IMPORTANT: Surround every decision block with the sentinel tags +`{A2UI_INFERENCE_OPEN_TAG}` and `{A2UI_INFERENCE_CLOSE_TAG}`. The block body is +one JSON object (or a JSON array of such objects, one per surface). + +## Fields + +1. `intent` (required, string): A short natural-language description of the + interface to render, naming what the data is and how the user should see + or interact with it. Example: "Show the order summary with a confirm button". + +2. `payload` (required, object or array): The data to display. Use descriptive + camelCase keys; key names guide which components are chosen. Keep values + JSON primitives, objects, and arrays. Store actual field values under each + key (for example `"email": "alex@example.com", "password": "", "rememberMe": false`), + not `*Label` or `*Placeholder` keys; field labels are humanized from the key + names, and action buttons come from an `actions` array of button labels + (for example `"actions": ["Sign In"]`). If you pass an array, it is stored + under the `items` key, so bindings read `/items/0/...`. + +3. `surfaceId` (optional, string): The surface to create or update. Reuse an + id to replace an earlier surface. + +4. `template` (optional, string): The id of a registered surface template to + render directly, when one listed below matches. + +5. `fallbackDsl` (optional, string): A2UI Express source rendered if the + decision model is not confident enough to choose components. + +6. `layout` (optional, array of up to {MAX_BRIEF_SECTIONS} strings): An ordered + layout brief grouping payload keys by role, each formatted as + `":,"` (keys may be bare top-level names or `/`-prefixed + JSON pointers; no nested sections). Valid roles are {{brief_roles}}. + Example: `["picture:name,logoUrl", "collection:/photos", "facts:address,phone"]`. + +7. `mutablePaths` (optional, array of strings): JSON pointers (for example + `["/email", "/password", "/rememberMe"]`) for fields in `payload` that the + user edits in a form or settings screen. + +8. `title` (optional, string): An optional title for the surface. When supplied, + the grammar places it into the page heading or banner without rewriting. + +9. `summary` (optional, string): An optional one-line summary or caption for the + surface. When supplied, the grammar places it into supporting prose without rewriting. + +## Example + +{A2UI_INFERENCE_OPEN_TAG} +{{{{"intent": "Show the service health with latency and a refresh button", + "payload": {{{{"serviceName": "checkout", "latencyMs": 42, "status": "healthy"}}}}, + "layout": ["headline:serviceName,latencyMs,status"], + "surfaceId": "main"}}}} +{A2UI_INFERENCE_CLOSE_TAG}""" +"""The decision block contract with a ``{brief_roles}`` placeholder. + +`decision_rules` fills the placeholder from a grammar; `DECISION_RULES` is +the rendering for the bundled grammar. +""" + + +def decision_rules(archetypes: ArchetypeGrammar) -> str: + """Renders `DECISION_RULES_TEMPLATE` with the brief roles of `archetypes`.""" + roles = ", ".join(f"`{r}`" for r in archetypes.brief_roles()) + return DECISION_RULES_TEMPLATE.format(brief_roles=roles) + + +def __getattr__(name: str) -> Any: + # `DECISION_RULES` is resolved lazily so importing this module does not load + # and validate the bundled grammar. + if name == "DECISION_RULES": + return decision_rules(ArchetypeGrammar.default()) + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +class DecisionPromptGenerator(PromptGenerator): + """Builds the system prompt for the decision inference format. + + The catalog section lists component names (not full signatures, which + the model does not need) and the registered template ids, derived from + the catalogs and registry at generation time. + """ + + def __init__( + self, + catalogs: Sequence[CatalogApi], + examples: Sequence[Sequence[AgentToRendererMessage]] | None = None, + *, + registry: TemplateRegistry | None = None, + archetypes: ArchetypeGrammar | None = None, + ) -> None: + """Creates a prompt generator. + + Args: + catalogs: The active catalogs. + examples: Few-shot example turns as A2UI messages; each is + decompiled into a decision block for the prompt. + registry: Templates whose ids are offered for the `template` field. + archetypes: Grammar whose brief roles the `layout` field rule + lists; defaults to `ArchetypeGrammar.default()`. + """ + self._catalogs = list(check_mixed_catalogs(catalogs)) + self._examples = [list(t) for t in examples] if examples is not None else None + self._registry = registry if registry is not None else TemplateRegistry() + self._archetypes = archetypes + self._graph: CatalogDecisionGraph | None = None + + @property + def catalogs(self) -> list[CatalogApi]: + """A copy of the catalogs configured on this prompt generator.""" + return list(self._catalogs) + + @property + def registry(self) -> TemplateRegistry: + """The template registry whose ids the prompt offers.""" + return self._registry + + @property + def archetypes(self) -> ArchetypeGrammar: + """The grammar whose brief roles the prompt lists.""" + if self._archetypes is None: + self._archetypes = ArchetypeGrammar.default() + return self._archetypes + + def _get_graph(self) -> CatalogDecisionGraph: + if self._graph is None: + self._graph = CatalogDecisionGraph(self._catalogs) + return self._graph + + def generate_base_rules(self) -> str: + """Returns the decision block contract and field rules.""" + return decision_rules(self.archetypes) + + def _component_lines(self, catalog: Any | None) -> list[str]: + """Lists the components the decision model may choose from.""" + specs = self._get_graph().root_candidates() + if catalog is not None: + wanted = getattr(catalog, "catalog_id", catalog) + specs = tuple(s for s in specs if s.catalog_id == wanted) + return [ + "## Available Components", + "", + ( + "The decision model selects from these components; you do not name" + " them, but your `intent` and `payload` keys should make the right" + " choice clear:" + ), + *(f"- {spec.name}" for spec in specs), + ] + + def _template_lines(self) -> list[str]: + """Lists the registered template ids, or nothing when there are none.""" + templates = self._registry.list_templates() + if not templates: + return [] + lines = ["", "## Registered Templates", ""] + lines.append("Set `template` to one of these ids when it fits:") + for template in templates: + desc = f": {template.description}" if template.description else "" + lines.append(f"- `{template.template_id}`{desc}") + return lines + + def generate_catalog_instructions( + self, + include_schema: bool = True, + catalog: Any | None = None, + ) -> str: + """Lists the components the decision model may choose and the templates. + + Args: + include_schema: When False, returns an empty string. + catalog: Restrict the component list to this catalog. + """ + if not include_schema: + return "" + return "\n".join([*self._component_lines(catalog), *self._template_lines()]) + + def generate_examples( + self, + catalog: Any | None = None, + validate: bool = False, + ) -> str: + """Formats the configured example turns as decision blocks. + + Args: + catalog: Unused; kept for the base-class signature. + validate: When True, example messages are validated against the + catalogs before decompilation. + """ + del catalog + if not self._examples: + return "" + if validate: + from a2ui.inference_formats._shared import to_message_dicts + from a2ui.utils import validate_payload + + for turn in self._examples: + validate_payload(self._catalogs, to_message_dicts(turn)) + return "\n\n".join(self.decompile(turn) for turn in self._examples) + + def decompile(self, a2ui_payload: Sequence[AgentToRendererMessage]) -> str: + """Renders messages as a wrapped decision block. + + Format-specific (not part of `PromptGenerator`): only the data model + and surface id survive, with a synthetic `Render ` intent. + See `decision_block_from_messages`. + """ + block = decision_block_from_messages(a2ui_payload) + return self.wrap_block(block) + + @staticmethod + def wrap_block(block: DecisionBlock) -> str: + """Serializes a decision block inside the sentinel tags.""" + body = json.dumps(block.to_json(), indent=1, sort_keys=True) + return f"{A2UI_INFERENCE_OPEN_TAG}\n{body}\n{A2UI_INFERENCE_CLOSE_TAG}" + + def generate(self) -> str: + """Assembles the prompt snippet for the decision format.""" + parts: list[str] = [f"## Workflow Description:\n{self.generate_base_rules()}"] + catalog_inst = self.generate_catalog_instructions(include_schema=True) + if catalog_inst: + parts.append(catalog_inst) + examples = self.generate_examples(validate=True) + if examples: + parts.append(f"### Examples:\n{examples}") + return "\n\n".join(parts) + + +__all__ = [ + "DECISION_RULES", + "DECISION_RULES_TEMPLATE", + "DecisionPromptGenerator", + "decision_rules", +] diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/semantic_types.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/semantic_types.py new file mode 100644 index 0000000000..5b78f39822 --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/semantic_types.py @@ -0,0 +1,1078 @@ +# 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. + +"""Semantic pointer classification for archetype-driven layout synthesis.""" + +from __future__ import annotations + +from collections.abc import Collection, Mapping, Sequence +import re +from typing import Any +from urllib.parse import urlparse + +from .models import SemanticType + +_CAMEL_SPLIT_RE = re.compile(r"([a-z0-9])([A-Z])|([A-Z]+)([A-Z][a-z])") +_KEY_SEP_RE = re.compile(r"[\s_\-/~]+") + +_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") +_PHONE_RE = re.compile( + r"^(?:\+\d[\d\s().-]{6,18}\d|\(\d{3}\)\s*\d{3}[-\s]\d{4}|\d{3}[-\s]\d{3}[-\s]\d{4})$" +) +_HTTP_URL_RE = re.compile(r"^(?:https?://|www\.)\S+$", re.IGNORECASE) +_UUID_RE = re.compile( + r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" +) +_HEX_HASH_RE = re.compile(r"^[0-9a-fA-F]{32,64}$") + +_ISO_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") +_SLASH_DATE_RE = re.compile(r"^\d{1,2}/\d{1,2}/\d{4}$") +_MONTH_DATE_RE = re.compile( + r"^(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s+\d{1,2},?\s+\d{4}$", + re.IGNORECASE, +) +_ISO_DATETIME_RE = re.compile( + r"^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?$" +) +_TIME_RE = re.compile(r"^(?:[01]?\d|2[0-3]):[0-5]\d(?::[0-5]\d)?(?:\s*[APap][Mm])?$") +_DATE_RANGE_RE = re.compile( + r"^(?:\d{4}-\d{2}-\d{2}\s*(?:\.\.|/|to|–|—|-)\s*\d{4}-\d{2}-\d{2}" + r"|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s+\d{1,2}" + r"\s*(?:to|–|—|-)\s*(?:(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s+)?" + r"\d{1,2}(?:,?\s+\d{4})?)$", + re.IGNORECASE, +) +_ISO_DURATION_RE = re.compile( + r"^P(?=\d|T\d)(?:\d+Y)?(?:\d+M)?(?:\d+W)?(?:\d+D)?" + r"(?:T(?:\d+H)?(?:\d+M)?(?:\d+(?:\.\d+)?S)?)?$" +) +_HUMAN_DURATION_RE = re.compile( + r"^\d+(?:\.\d+)?\s*(?:ms|msec|milliseconds?|s|secs?|seconds?|m|mins?|minutes?|" + r"h|hrs?|hours?|d|days?|w|wks?|weeks?)" + r"(?:\s+\d+\s*(?:s|secs?|m|mins?|h|hrs?|d|days?))*$", + re.IGNORECASE, +) +_RELATIVE_TIME_RE = re.compile( + r"^(?:just now|yesterday|today|tomorrow" + r"|\d+\s*(?:s|secs?|seconds?|m|mins?|minutes?|h|hrs?|hours?|d|days?|" + r"w|wks?|weeks?|mo|months?|y|yrs?|years?)\s+ago" + r"|in\s+\d+\s*(?:s|secs?|seconds?|m|mins?|minutes?|h|hrs?|hours?|d|days?|" + r"w|wks?|weeks?|mo|months?|y|yrs?|years?))$", + re.IGNORECASE, +) + +_HEX_COLOR_RE = re.compile( + r"^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$" +) +_CSS_COLOR_RE = re.compile(r"^(?:rgb|rgba|hsl|hsla|oklch)\([^)]+\)$", re.IGNORECASE) + +_CURRENCY_STR_RE = re.compile( + r"^(?:(?P[$€£¥₹])\s*-?\d[\d,]*(?:\.\d+)?" + r"|(?PUSD|EUR|GBP|JPY|CAD|AUD|CHF|CNY|INR)\s+-?\d[\d,]*(?:\.\d+)?" + r"|-?\d[\d,]*(?:\.\d+)?\s+(?PUSD|EUR|GBP|JPY|CAD|AUD|CHF|CNY|INR))$", + re.IGNORECASE, +) +_PERCENT_STR_RE = re.compile(r"^[+-]?\d+(?:\.\d+)?\s*%$") +_RATING_STR_RE = re.compile( + r"^(?:\d+(?:\.\d+)?\s*(?:/|out of)\s*(?:5|10)|[★☆]{3,10})$", + re.IGNORECASE, +) +_RATIO_STR_RE = re.compile( + r"^\d+(?:\.\d+)?\s*(?:/|:|of)\s*\d+(?:\.\d+)?$", re.IGNORECASE +) +_QUANTITY_STR_RE = re.compile( + r"^[+-]?\d[\d,]*(?:\.\d+)?\s*" + r"(?PkWh|Wh|MWh|kW|MW|W|kg|g|mg|lb|lbs|oz|km|m|cm|mm|mi|ft|in|" + r"GB|MB|KB|TB|PB|GiB|MiB|Mbps|Gbps|Hz|kHz|MHz|GHz|bpm|rpm|" + r"kcal|cal|L|mL|ml|gal|fl\s*oz|°C|°F|K|psi|bar|hPa|dB|ppm|pts|px|rem|em)$" +) + +_MARKDOWN_SYNTAX_RE = re.compile( + r"(?:^#{1,6}\s+\S|\*\*[^*\n]+\*\*|\[[^\]]+\]\(https?://[^)]+\)|^\s*[-*]\s+\S)", + re.MULTILINE, +) +_CODE_SYNTAX_RE = re.compile( + r"(?:^```|^(?:SELECT|INSERT|UPDATE|DELETE)\s+.+\s+FROM\b|" + r"^(?:def|class|function|import|from|const|let|var)\s+\w+|" + r"^\s*\{[\s\S]*\"[^\"]+\"\s*:[\s\S]*\}\s*$)", + re.IGNORECASE | re.MULTILINE, +) + +_IMAGE_EXTENSIONS = frozenset({ + ".png", + ".jpg", + ".jpeg", + ".gif", + ".webp", + ".svg", + ".avif", + ".bmp", + ".ico", +}) +_VIDEO_EXTENSIONS = frozenset( + {".mp4", ".webm", ".mov", ".m4v", ".mkv", ".avi", ".m3u8"} +) +_AUDIO_EXTENSIONS = frozenset( + {".mp3", ".wav", ".ogg", ".flac", ".m4a", ".aac", ".opus"} +) +_DOCUMENT_EXTENSIONS = frozenset({ + ".pdf", + ".doc", + ".docx", + ".xls", + ".xlsx", + ".ppt", + ".pptx", + ".csv", + ".rtf", + ".odt", + ".epub", +}) + +_IMAGE_FRAMING_HINTS = ( + "logo", + "icon", + "avatar", + "portrait", + "cover", + "poster", + "thumbnail", + "banner", + "hero", +) +_IMAGE_KEY_HINTS = frozenset({ + *_IMAGE_FRAMING_HINTS, + "image", + "img", + "photo", + "picture", + "thumb", + "artwork", + "illustration", +}) +_VIDEO_KEY_HINTS = frozenset( + {"video", "clip", "trailer", "stream", "movie", "recording", "footage"} +) +_AUDIO_KEY_HINTS = frozenset( + {"audio", "track", "song", "podcast", "voice", "sound", "voicemail"} +) +_DOCUMENT_KEY_HINTS = frozenset({ + "document", + "doc", + "pdf", + "invoice", + "receipt", + "report", + "contract", + "resume", + "attachment", + "syllabus", + "manual", + "datasheet", +}) +_URL_KEY_HINTS = frozenset({ + "url", + "uri", + "href", + "link", + "website", + "homepage", + "endpoint", + "callback", + "webhook", +}) +_EMAIL_KEY_HINTS = frozenset({"email", "e_mail", "mail", "contact_email"}) +_PHONE_KEY_HINTS = frozenset({ + "phone", + "tel", + "telephone", + "mobile", + "cell", + "fax", + "hotline", + "contact_phone", +}) + +_MEDIA_RULES: tuple[tuple[SemanticType, frozenset[str], frozenset[str]], ...] = ( + (SemanticType.IMAGE_URL, _IMAGE_EXTENSIONS, _IMAGE_KEY_HINTS), + (SemanticType.VIDEO_URL, _VIDEO_EXTENSIONS, _VIDEO_KEY_HINTS), + (SemanticType.AUDIO_URL, _AUDIO_EXTENSIONS, _AUDIO_KEY_HINTS), + (SemanticType.DOCUMENT_URL, _DOCUMENT_EXTENSIONS, _DOCUMENT_KEY_HINTS), +) + +_DATE_RANGE_KEY_HINTS = frozenset( + {"date_range", "daterange", "stay_dates", "booking_window", "date_window"} +) +_DATE_KEY_HINTS = frozenset({ + "date", + "birthdate", + "birthday", + "dob", + "arrives", + "departs", + "check_in", + "check_out", + "due_date", + "expires_on", +}) +_TIME_KEY_HINTS = frozenset({ + "time", + "start_time", + "end_time", + "check_in_time", + "departure_time", + "arrival_time", +}) +_DURATION_SECONDS_KEY_HINTS = frozenset({ + "duration", + "duration_sec", + "duration_seconds", + "skip", + "skip_forward", + "skip_backward", + "timeout", + "timeout_sec", + "ttl", + "ttl_seconds", +}) +_DURATION_UNIT_BY_TOKEN: Mapping[str, str] = { + "ms": "ms", + "msec": "ms", + "milliseconds": "ms", + "sec": "seconds", + "secs": "seconds", + "seconds": "seconds", + "min": "minutes", + "mins": "minutes", + "minutes": "minutes", +} + +_BOUNDED_KEY_HINTS = frozenset( + {"progress", "battery", "capacity", "quota", "completion"} +) +_RATING_KEY_HINTS = frozenset( + {"rating", "stars", "score", "review_score", "satisfaction"} +) +_CURRENCY_KEY_HINTS = frozenset({ + "price", + "cost", + "amount", + "fee", + "subtotal", + "tax", + "balance", + "salary", + "budget", + "revenue", + "spend", + "payment", + "charge", + "discount", + "tip", + "fare", + "rent", + "wage", +}) +_PERCENT_KEY_HINTS = frozenset({ + "percent", + "percentage", + "pct", + "apr", + "apy", + "yield", + "margin", + "tax_rate", + "discount_rate", + "completion_rate", + "error_rate", +}) +_RATIO_KEY_HINTS = frozenset({ + "ratio", + "share", + "fraction", + "proportion", + "probability", + "confidence", + "likelihood", + "odds", +}) +_COUNT_KEY_HINTS = frozenset({ + "count", + "num", + "total_count", + "items", + "qty", + "seats", + "guests", + "followers", + "views", + "likes", + "comments", + "retries", + "attempts", + "page_count", + "word_count", +}) +_KEY_UNIT_SUFFIXES: Mapping[str, str] = { + "kg": "kg", + "g": "g", + "mg": "mg", + "lb": "lb", + "lbs": "lbs", + "oz": "oz", + "km": "km", + "cm": "cm", + "mm": "mm", + "mi": "mi", + "ft": "ft", + "gb": "GB", + "mb": "MB", + "kb": "KB", + "tb": "TB", + "kwh": "kWh", + "wh": "Wh", + "kw": "kW", + "mhz": "MHz", + "ghz": "GHz", + "bpm": "bpm", + "rpm": "rpm", + "kcal": "kcal", + "cal": "cal", + "ml": "mL", + "celsius": "°C", + "fahrenheit": "°F", + "psi": "psi", +} +_CURRENCY_SYMBOL_MAP: Mapping[str, str] = { + "$": "USD", + "€": "EUR", + "£": "GBP", + "¥": "JPY", + "₹": "INR", +} +_CURRENCY_CODES = frozenset( + {"USD", "EUR", "GBP", "JPY", "CAD", "AUD", "CHF", "CNY", "INR", "MXN", "BRL"} +) + +_COLOR_KEY_HINTS = frozenset({ + "color", + "colour", + "bg_color", + "background_color", + "text_color", + "fill_color", + "stroke_color", + "accent_color", + "tint", +}) +_STATUS_KEY_HINTS = frozenset({ + "status", + "state", + "health", + "phase", + "stage", + "severity", + "condition", + "availability", + "lifecycle", +}) +_STATUS_VALUES = frozenset({ + "active", + "inactive", + "pending", + "completed", + "complete", + "failed", + "error", + "ok", + "healthy", + "degraded", + "unhealthy", + "critical", + "warning", + "online", + "offline", + "running", + "stopped", + "paused", + "cancelled", + "canceled", + "approved", + "rejected", + "draft", + "published", + "archived", + "open", + "closed", + "resolved", + "in_progress", + "in progress", + "queued", + "scheduled", + "expired", + "overdue", + "paid", + "unpaid", + "processing", + "shipped", + "delivered", +}) +_ENUM_KEY_HINTS = frozenset({ + "enum", + "category", + "type", + "kind", + "tier", + "plan", + "role", + "mode", + "currency", + "method", + "channel", + "environment", + "env", + "direction", + "side", + "priority", +}) + +_CODE_KEY_HINTS = frozenset({ + "code", + "code_snippet", + "script", + "sql_query", + "sql", + "regex", + "command", + "cmd", + "shell", + "expression", + "expr", + "formula", + "source_code", +}) +_MARKDOWN_KEY_HINTS = frozenset({"markdown", "md", "rich_text"}) +_LONG_TEXT_KEY_HINTS = frozenset({ + "about", + "bio", + "biography", + "description", + "summary", + "overview", + "body", + "content", + "notes", + "comment", + "message", + "review", + "excerpt", + "snippet", + "abstract", + "details", + "instructions", + "instruction", + "story", +}) +_IDENTIFIER_KEY_HINTS = frozenset({ + "id", + "uuid", + "guid", + "uid", + "slug", + "sku", + "isbn", + "asin", + "vin", + "iban", + "ssn", + "account_id", + "user_id", + "order_id", + "transaction_id", + "reference_id", + "ref_id", + "tracking_number", + "serial_number", + "token", + "api_key", + "hash", + "checksum", + "sha", + "commit", + "revision", +}) +_NAME_KEY_HINTS = frozenset({ + "name", + "full_name", + "fullname", + "first_name", + "firstname", + "last_name", + "lastname", + "display_name", + "username", + "author", + "artist", + "creator", + "owner", + "vendor", + "merchant", + "company", + "brand", + "organization", +}) +_TITLE_KEY_HINTS = frozenset({ + "title", + "headline", + "heading", + "subtitle", + "subheading", + "subject", + "topic", + "tagline", +}) + + +def prose_length_level(word_count: int) -> str: + """Maps a word count to the `prose.measures.length` level name.""" + if word_count < 15: + return "line" + if word_count < 60: + return "blurb" + if word_count < 200: + return "summary" + return "article" + + +def _split_key_tokens(key: str) -> tuple[str, ...]: + """Splits a camelCase, PascalCase, or snake_case key into lowercase tokens.""" + if not key: + return () + spaced = _CAMEL_SPLIT_RE.sub( + lambda m: f"{m.group(1) or m.group(3)} {m.group(2) or m.group(4)}", key + ) + parts = [part.lower() for part in _KEY_SEP_RE.split(spaced) if part] + return tuple(parts) + + +def humanize_key(key: str) -> str: + """Formats a raw JSON key or pointer segment as a human-readable label. + + ``"priceFrom"`` becomes ``"Price from"`` and ``"skip_forward"`` becomes + ``"Skip forward"``. + """ + tokens = _split_key_tokens(key) + if not tokens: + return "" + joined = " ".join(tokens) + return joined[0].upper() + joined[1:] + + +def _match_key_hint(tokens: Sequence[str], hints: Collection[str]) -> str | None: + """Returns the matching hint token or snake_case compound key, if any.""" + if not tokens: + return None + joined = "_".join(tokens) + if joined in hints: + return joined + for token in tokens: + if token in hints: + return token + return None + + +def _hint_dict(hint: str | None) -> dict[str, Any]: + """Builds a single-key ``{"keyHint": hint}`` dictionary when `hint` is set.""" + if hint is None: + return {} + return {"keyHint": hint} + + +def _url_extension(text: str) -> str: + """Extracts the lowercase file extension from a URL or file path.""" + path = urlparse(text).path if "://" in text else text.split("?", 1)[0] + dot = path.rfind(".") + if dot == -1: + return "" + return path[dot:].lower() + + +def _image_key_hint(tokens: Sequence[str]) -> dict[str, Any]: + """Builds the `keyHint` dictionary for an image pointer when matched.""" + for framing in _IMAGE_FRAMING_HINTS: + if framing in tokens: + return {"keyHint": framing} + return _hint_dict(_match_key_hint(tokens, _IMAGE_KEY_HINTS)) + + +def _detect_url_or_media( + text: str, tokens: tuple[str, ...] +) -> tuple[SemanticType, dict[str, Any]] | None: + """Detects `image_url`, `video_url`, `audio_url`, `document_url`, or `url`.""" + if text.startswith("data:image/"): + return SemanticType.IMAGE_URL, _image_key_hint(tokens) + + is_http = bool(_HTTP_URL_RE.match(text)) + is_url_like = is_http or text.startswith("/") + ext = _url_extension(text) if ("." in text) else "" + + for sem_type, extensions, key_hints in _MEDIA_RULES: + matched_hint = _match_key_hint(tokens, key_hints) + if ext in extensions or (is_url_like and matched_hint is not None): + hints = ( + _image_key_hint(tokens) + if sem_type == SemanticType.IMAGE_URL + else _hint_dict(matched_hint) + ) + return sem_type, hints + + url_hint = _match_key_hint(tokens, _URL_KEY_HINTS) + if is_http or (text.startswith("/") and len(text) > 1 and url_hint is not None): + return SemanticType.URL, _hint_dict(url_hint) + return None + + +def _detect_email_or_phone( + text: str, tokens: tuple[str, ...] +) -> tuple[SemanticType, dict[str, Any]] | None: + """Detects `email` or `phone` from scheme prefixes, key hints, or patterns.""" + lower = text.lower() + if lower.startswith("mailto:") or _EMAIL_RE.match(text): + return SemanticType.EMAIL, _hint_dict(_match_key_hint(tokens, _EMAIL_KEY_HINTS)) + phone_hint = _match_key_hint(tokens, _PHONE_KEY_HINTS) + if lower.startswith("tel:") or _PHONE_RE.match(text): + return SemanticType.PHONE, _hint_dict(phone_hint) + if phone_hint and sum(ch.isdigit() for ch in text) >= 7: + return SemanticType.PHONE, {"keyHint": phone_hint} + return None + + +def _has_digits(text: str, minimum: int = 1) -> bool: + """Returns whether `text` contains at least `minimum` ASCII digits.""" + return sum(ch.isdigit() for ch in text) >= minimum + + +def _is_date_string(text: str, tokens: tuple[str, ...]) -> bool: + """Returns whether `text` and `tokens` represent a calendar date.""" + if ( + _ISO_DATE_RE.match(text) + or _SLASH_DATE_RE.match(text) + or _MONTH_DATE_RE.match(text) + ): + return True + return _match_key_hint(tokens, _DATE_KEY_HINTS) is not None and _has_digits(text, 4) + + +def _detect_time_from_string( + text: str, tokens: tuple[str, ...] +) -> tuple[SemanticType, dict[str, Any]] | None: + """Detects `date_range`, `datetime`, `date`, `time`, `relative_time`, or `duration`.""" + if _DATE_RANGE_RE.match(text) or ( + _match_key_hint(tokens, _DATE_RANGE_KEY_HINTS) and _has_digits(text) + ): + return SemanticType.DATE_RANGE, {} + if _ISO_DATETIME_RE.match(text): + return SemanticType.DATETIME, {} + if _is_date_string(text, tokens): + return SemanticType.DATE, {} + if _TIME_RE.match(text) or ( + _match_key_hint(tokens, _TIME_KEY_HINTS) and _has_digits(text) + ): + return SemanticType.TIME, {} + if _RELATIVE_TIME_RE.match(text): + return SemanticType.RELATIVE_TIME, {} + if _ISO_DURATION_RE.match(text) or _HUMAN_DURATION_RE.match(text): + return SemanticType.DURATION, {} + return None + + +def _detect_duration_from_number( + value: int | float, tokens: tuple[str, ...] +) -> tuple[SemanticType, dict[str, Any]] | None: + """Detects numeric `duration` pointers such as `skipForward: 30` or `latencyMs: 12`.""" + if not tokens: + return None + if tokens[-1] in _DURATION_UNIT_BY_TOKEN and len(tokens) >= 2: + unit = _DURATION_UNIT_BY_TOKEN[tokens[-1]] + return SemanticType.DURATION, {"unit": unit, "keyHint": tokens[-1]} + hint = _match_key_hint(tokens, _DURATION_SECONDS_KEY_HINTS) + if hint is not None and value >= 0: + return SemanticType.DURATION, {"unit": "seconds", "keyHint": hint} + return None + + +def _detect_quantity_from_string( + text: str, tokens: tuple[str, ...] +) -> tuple[SemanticType, dict[str, Any]] | None: + """Detects `currency`, `percent`, `rating`, `ratio`, or `quantity` from strings.""" + curr_match = _CURRENCY_STR_RE.match(text) + if curr_match: + sym = curr_match.group("sym") + code = ( + curr_match.group("code1") + or curr_match.group("code2") + or _CURRENCY_SYMBOL_MAP.get(sym or "", "USD") + ) + return SemanticType.CURRENCY, {"currency": code.upper()} + if _PERCENT_STR_RE.match(text): + return SemanticType.PERCENT, {} + if _RATING_STR_RE.match(text): + return SemanticType.RATING, {} + if _RATIO_STR_RE.match(text): + return SemanticType.RATIO, {} + qty_match = _QUANTITY_STR_RE.match(text) + if qty_match: + unit = re.sub(r"\s+", " ", qty_match.group("unit").strip()) + return SemanticType.QUANTITY, {"unit": unit} + hint = _match_key_hint(tokens, _RATING_KEY_HINTS) + if hint and text.replace(".", "", 1).isdigit(): + return SemanticType.RATING, {"keyHint": hint} + return None + + +def _is_numeric_scalar(val: Any) -> bool: + """Returns whether `val` is an `int` or `float` (excluding `bool`).""" + return isinstance(val, (int, float)) and not isinstance(val, bool) + + +def _detect_bounded_number( + value: int | float, + key: str, + tokens: tuple[str, ...], + siblings: Mapping[str, Any] | None, +) -> tuple[SemanticType, dict[str, Any]] | None: + """Detects `bounded` numbers from sibling `min`/`max` bounds or key hints.""" + if siblings and key.lower() not in { + "min", + "max", + "limit", + "quota", + "total", + "step", + }: + raw_min = siblings.get("min", 0) + raw_max = siblings.get("max", siblings.get("limit", siblings.get("quota"))) + if ( + _is_numeric_scalar(raw_min) + and _is_numeric_scalar(raw_max) + and raw_min < raw_max + ): + return SemanticType.BOUNDED, {"min": raw_min, "max": raw_max} + hint = _match_key_hint(tokens, _BOUNDED_KEY_HINTS) + if hint is not None and 0 <= value <= 100: + upper = 1 if (isinstance(value, float) and value <= 1.0) else 100 + return SemanticType.BOUNDED, {"min": 0, "max": upper, "keyHint": hint} + return None + + +def _sibling_string(siblings: Mapping[str, Any] | None, field: str) -> str | None: + """Returns a non-empty string sibling value for `field`, if present.""" + if not siblings: + return None + val = siblings.get(field) + return val if isinstance(val, str) and val.strip() else None + + +def _detect_quantity_from_number( + value: int | float, + key: str, + tokens: tuple[str, ...], + siblings: Mapping[str, Any] | None, +) -> tuple[SemanticType, dict[str, Any]]: + """Classifies a numeric scalar into a specific Quantity-family `SemanticType`.""" + bounded = _detect_bounded_number(value, key, tokens, siblings) + if bounded is not None: + return bounded + + for sem_type, key_hints in ( + (SemanticType.RATING, _RATING_KEY_HINTS), + (SemanticType.PERCENT, _PERCENT_KEY_HINTS), + (SemanticType.RATIO, _RATIO_KEY_HINTS), + ): + hint = _match_key_hint(tokens, key_hints) + if hint is not None: + return sem_type, {"keyHint": hint} + + curr_hint = _match_key_hint(tokens, _CURRENCY_KEY_HINTS) + if curr_hint is not None: + hints: dict[str, Any] = {"keyHint": curr_hint} + sib_curr = _sibling_string(siblings, "currency") + if sib_curr is not None: + hints["currency"] = sib_curr + return SemanticType.CURRENCY, hints + + sib_unit = _sibling_string(siblings, "unit") + if sib_unit is not None and key.lower() != "unit": + return SemanticType.QUANTITY, {"unit": sib_unit} + + if len(tokens) >= 2 and tokens[-1] in _KEY_UNIT_SUFFIXES: + return SemanticType.QUANTITY, { + "unit": _KEY_UNIT_SUFFIXES[tokens[-1]], + "keyHint": tokens[-1], + } + + if isinstance(value, int): + count_hint = _match_key_hint(tokens, _COUNT_KEY_HINTS) + if count_hint is not None: + return SemanticType.COUNT, {"keyHint": count_hint} + return SemanticType.INTEGER, {} + + return SemanticType.NUMBER, {} + + +def _detect_color_from_string( + text: str, tokens: tuple[str, ...] +) -> tuple[SemanticType, dict[str, Any]] | None: + """Detects `color` from hex/CSS color strings or color key hints.""" + if _HEX_COLOR_RE.match(text) or _CSS_COLOR_RE.match(text): + return SemanticType.COLOR, {} + color_hint = _match_key_hint(tokens, _COLOR_KEY_HINTS) + if color_hint is not None and len(text) <= 24: + return SemanticType.COLOR, {"keyHint": color_hint} + return None + + +def _detect_state_from_string( + text: str, tokens: tuple[str, ...] +) -> tuple[SemanticType, dict[str, Any]] | None: + """Detects `color`, `status`, or `enum` from a string value and key tokens.""" + color = _detect_color_from_string(text, tokens) + if color is not None: + return color + + normalized = text.strip().lower() + status_hint = _match_key_hint(tokens, _STATUS_KEY_HINTS) + if normalized in _STATUS_VALUES or ( + status_hint is not None and len(text) <= 32 and " " not in normalized + ): + return SemanticType.STATUS, _hint_dict(status_hint) + + enum_hint = _match_key_hint(tokens, _ENUM_KEY_HINTS) + if text.upper() in _CURRENCY_CODES and (enum_hint == "currency" or text.isupper()): + return SemanticType.ENUM, _hint_dict(enum_hint) + if enum_hint is not None and len(text) <= 24 and "\n" not in text: + return SemanticType.ENUM, {"keyHint": enum_hint} + return None + + +def _prose_hints(text: str, key_hint: str | None = None) -> dict[str, Any]: + """Builds `wordCount`, `length`, and optional `keyHint` hints for prose text.""" + word_count = len(text.split()) + hints: dict[str, Any] = { + "wordCount": word_count, + "length": prose_length_level(word_count), + } + if key_hint is not None: + hints["keyHint"] = key_hint + return hints + + +def _is_identifier_key_or_value(text: str, tokens: tuple[str, ...]) -> bool: + """Returns whether `text` and `tokens` represent an `identifier` scalar.""" + if _UUID_RE.match(text) or _HEX_HASH_RE.match(text): + return True + if not tokens or " " in text.strip() or len(text) > 64: + return False + if _match_key_hint(tokens, _IDENTIFIER_KEY_HINTS) is not None: + return True + return len(tokens) >= 2 and tokens[-1] == "id" + + +def _is_long_text(text: str, long_hint: str | None) -> bool: + """Returns whether `text` qualifies as `long_text` by length or key hint.""" + word_count = len(text.split()) + if word_count >= 15 or len(text) >= 120: + return True + return long_hint is not None and (word_count >= 3 or len(text) >= 20) + + +def _detect_prose_or_code( + text: str, tokens: tuple[str, ...] +) -> tuple[SemanticType, dict[str, Any]] | None: + """Detects `code`, `markdown`, or `long_text` from text content and key hints.""" + code_hint = _match_key_hint(tokens, _CODE_KEY_HINTS) + if code_hint is not None or _CODE_SYNTAX_RE.search(text): + return SemanticType.CODE, _hint_dict(code_hint) + + md_hint = _match_key_hint(tokens, _MARKDOWN_KEY_HINTS) + if md_hint is not None or _MARKDOWN_SYNTAX_RE.search(text): + return SemanticType.MARKDOWN, _prose_hints(text, md_hint) + + long_hint = _match_key_hint(tokens, _LONG_TEXT_KEY_HINTS) + if _is_long_text(text, long_hint): + return SemanticType.LONG_TEXT, _prose_hints(text, long_hint) + return None + + +def _detect_text( + text: str, tokens: tuple[str, ...] +) -> tuple[SemanticType, dict[str, Any]]: + """Classifies a non-empty string into one of the Text-family `SemanticType`s.""" + prose_or_code = _detect_prose_or_code(text, tokens) + if prose_or_code is not None: + return prose_or_code + + if _is_identifier_key_or_value(text, tokens): + id_hint = _match_key_hint(tokens, _IDENTIFIER_KEY_HINTS) + if id_hint is None and tokens and tokens[-1] == "id": + id_hint = "id" + return SemanticType.IDENTIFIER, _hint_dict(id_hint) + + name_hint = _match_key_hint(tokens, _NAME_KEY_HINTS) + if name_hint is not None and len(text) <= 80: + return SemanticType.NAME, {"keyHint": name_hint} + + title_hint = _match_key_hint(tokens, _TITLE_KEY_HINTS) + if title_hint is not None and len(text) <= 140: + return SemanticType.TITLE, {"keyHint": title_hint} + + return SemanticType.STRING, {} + + +def _classify_string_scalar( + value: str, tokens: tuple[str, ...] +) -> tuple[SemanticType, dict[str, Any]]: + """Runs the ordered string detector chain on a non-empty string value.""" + for detector in ( + _detect_url_or_media, + _detect_time_from_string, + _detect_email_or_phone, + _detect_quantity_from_string, + _detect_state_from_string, + ): + detected = detector(value, tokens) + if detected is not None: + return detected + return _detect_text(value, tokens) + + +def _classify_container(value: Any) -> SemanticType | None: + """Classifies `None`, `Mapping`, or non-string `Sequence` values.""" + if value is None: + return SemanticType.EMPTY + if isinstance(value, Mapping): + return SemanticType.OBJECT if value else SemanticType.EMPTY + if isinstance(value, Sequence) and not isinstance(value, (str, bytes, bytearray)): + return SemanticType.ARRAY if value else SemanticType.EMPTY + return None + + +def classify_scalar( + value: Any, + key: str = "", + *, + siblings: Mapping[str, Any] | None = None, +) -> tuple[SemanticType, dict[str, Any]]: + """Classifies a scalar or container value into a `SemanticType` and hints. + + Detectors run from most specific (key hint and value pattern) to least + specific (coarse JSON type), so ``priceFrom: 240`` is classified as + `SemanticType.CURRENCY` before `SemanticType.INTEGER`. + + Args: + value: The runtime payload value at the pointer. + key: The unescaped JSON key or last pointer segment. + siblings: Optional parent mapping for sibling-aware rules (`bounded` + `min`/`max`, sibling `currency` or `unit`). + + Returns: + A ``(SemanticType, hints)`` pair. + """ + container_type = _classify_container(value) + if container_type is not None: + return container_type, {} + if isinstance(value, bool): + return SemanticType.BOOLEAN, {} + + tokens = _split_key_tokens(key) + if isinstance(value, (int, float)): + duration = _detect_duration_from_number(value, tokens) + if duration is not None: + return duration + return _detect_quantity_from_number(value, key, tokens, siblings) + + if isinstance(value, str): + stripped = value.strip() + if not stripped: + return SemanticType.EMPTY, {} + return _classify_string_scalar(stripped, tokens) + + return SemanticType.STRING, {} + + +def _non_empty_array_entries( + values: Sequence[Any], + siblings_per_item: Sequence[Mapping[str, Any]] | None, +) -> list[tuple[Any, Mapping[str, Any] | None]]: + """Filters out `None` and blank string entries while pairing item siblings.""" + entries: list[tuple[Any, Mapping[str, Any] | None]] = [] + for idx, val in enumerate(values): + if val is None or (isinstance(val, str) and not val.strip()): + continue + sib = ( + siblings_per_item[idx] + if siblings_per_item and idx < len(siblings_per_item) + else None + ) + entries.append((val, sib)) + return entries + + +def _classify_string_array_column( + values: Sequence[str], first_type: SemanticType +) -> SemanticType: + """Refines a string column into `STATUS` or `ENUM` using column statistics.""" + normalized = [v.strip().lower() for v in values] + if all(item in _STATUS_VALUES for item in normalized): + return SemanticType.STATUS + distinct = set(normalized) + if 1 <= len(distinct) <= 12 and len(distinct) * 2 <= len(normalized): + return SemanticType.ENUM + return first_type + + +def classify_array_field( + values: Sequence[Any], + key: str = "", + *, + siblings_per_item: Sequence[Mapping[str, Any]] | None = None, +) -> SemanticType: + """Classifies a column of values across array elements into a `SemanticType`. + + Applies array-level statistics for `SemanticType.STATUS` and + `SemanticType.ENUM` (low distinct ratio `<= 12` distinct values with + `<= 50%` uniqueness across non-empty string values) while delegating format + and key-hint classification to `classify_scalar`. + """ + non_empty = _non_empty_array_entries(values, siblings_per_item) + if not non_empty: + return SemanticType.EMPTY + + first_val, first_sib = non_empty[0] + first_type, _ = classify_scalar(first_val, key, siblings=first_sib) + raw_vals = [v for v, _ in non_empty] + + if all(isinstance(v, str) for v in raw_vals) and first_type in { + SemanticType.STRING, + SemanticType.STATUS, + SemanticType.ENUM, + }: + return _classify_string_array_column([str(v) for v in raw_vals], first_type) + + if first_type == SemanticType.INTEGER and any( + isinstance(v, float) for v in raw_vals + ): + return SemanticType.NUMBER + + return first_type diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/synthesizer.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/synthesizer.py new file mode 100644 index 0000000000..e3414480be --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/synthesizer.py @@ -0,0 +1,2333 @@ +# 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. + +"""Multi-stage local decision-model A2UI surface synthesizer.""" + +from __future__ import annotations + +import asyncio +import collections +from collections.abc import Awaitable, Callable, Collection, Mapping, Sequence +import concurrent.futures +import contextvars +from dataclasses import replace +import inspect +import re +import time +from typing import Any, TypeAlias, cast + +from a2ui.core import A2uiValidationError, CatalogApi +from a2ui.core.schema import AgentToRendererMessage +from a2ui.inference_formats._shared import CatalogSchemaHelper +from a2ui.parser.messages import to_message_models +from a2ui.utils import validate_payload + +from .archetypes import ArchetypeGrammar, LayoutArchetype +from .backends import ( + DecisionBackend, + DeterministicMockBackend, + LocalCrossEncoderBackend, + StepZeroLogprobBackend, + create_decision_backend, + ensure_batch_backend, +) +from .bindings import is_v10 as _is_v10 +from .bindings import make_data_binding as _make_data_binding +from .catalog_graph import CatalogDecisionGraph +from .layout_lint import lint_components +from .layout_planner import LayoutPlanner, PlannerState +from .models import ( + AuthoredCopy, + ComponentNodeSpec, + ComponentSlot, + DecisionAnswer, + DecisionBatch, + DecisionDistribution, + DecisionQuery, + DecisionQuestion, + DecisionRecord, + DecisionTask, + FallbackSource, + LayoutBrief, + LayoutPlan, + PlanOutcome, + QuestionKind, + SlotKind, + SynthesisConfig, + SynthesisOutput, + SynthesisStage, + VarietyMode, + coerce_decision_payload, +) +from .patterns import ( + MergedPatternLibrary, + PatternError, + PatternExpander, + PatternLibrary, + eligible_archetypes, + shape_signature, +) +from .payload_inspector import ( + PointerSummary, + PointerValueType, + inspect_payload_pointers, +) +from .template_registry import TemplateRegistry + +_CAMEL_RE = re.compile(r"([a-z0-9])([A-Z])") +_TOKEN_RE = re.compile(r"[a-z0-9]+") + +# Key under which a top-level JSON array payload is stored in the data model. +_ARRAY_PAYLOAD_KEY = "items" +_ELIGIBILITY_CACHE_SIZE = 256 +"""Distinct payload shapes whose archetype eligibility one synthesizer remembers.""" + +_DECISION_CALL_TIMINGS: contextvars.ContextVar[list[float] | None] = ( + contextvars.ContextVar("_DECISION_CALL_TIMINGS", default=None) +) + +FallbackMessages: TypeAlias = Sequence[AgentToRendererMessage | Mapping[str, Any]] +"""Messages a fallback callback may return: models or wire-format dicts.""" + +FallbackCallback: TypeAlias = Callable[ + [str, Mapping[str, Any], str], + FallbackMessages | Awaitable[FallbackMessages], +] +"""Callback invoked when the decision model abstains. + +Receives ``(intent, payload, surface_id)`` and returns the messages to render +instead, either directly or as an awaitable. Dicts are validated with +`to_message_models`. +""" + + +def _wire_version(protocol_version: str) -> str: + """Returns the canonical A2UI wire envelope version string.""" + return "v1.0" if _is_v10(protocol_version) else "v0.9" + + +def _as_data_model( + payload: Mapping[str, Any] | Sequence[Any] | str, +) -> Mapping[str, Any]: + """Coerces a payload into the mapping used as the surface data model. + + A JSON array is stored under the `items` key, since a surface data model + is always an object. + """ + data = coerce_decision_payload(payload) + if isinstance(data, Mapping): + return data + return {_ARRAY_PAYLOAD_KEY: list(data)} + + +def _populates_data_model(message: AgentToRendererMessage) -> bool: + """Returns whether a message writes the surface data model.""" + dumped = message.model_dump(by_alias=True, exclude_none=True) + if "updateDataModel" in dumped or "dataModelUpdate" in dumped: + return True + create = dumped.get("createSurface") + return isinstance(create, Mapping) and "dataModel" in create + + +def _passes_calibration_gate( + dist: DecisionDistribution, config: SynthesisConfig +) -> bool: + """Returns whether `dist` satisfies the calibration and logit-margin gate.""" + if dist.calibrated: + return True + return (dist.top_logit_margin or 0.0) >= config.uncalibrated_min_logit_margin + + +def _tokenize_identifier(text: str) -> set[str]: + """Splits camelCase, PascalCase, and path segments into lowercase tokens.""" + expanded = _CAMEL_RE.sub(r"\1 \2", text) + return set(_TOKEN_RE.findall(expanded.lower())) + + +def _pointer_matches_slot_type(ptr: PointerSummary, slot_type: str | None) -> bool: + """Returns whether a pointer's value type is compatible with `slot_type`.""" + if slot_type is None or slot_type == "any": + return True + return ptr.value_type == slot_type + + +def _best_pointer_by_tokens( + candidates: Sequence[PointerSummary], slot_tokens: set[str] +) -> PointerSummary: + """Returns the pointer in `candidates` with the highest token overlap.""" + return max( + candidates, + key=lambda p: len(slot_tokens & _tokenize_identifier(p.path)), + ) + + +def _select_required_pointer( + slot: ComponentSlot, + compatible: Sequence[PointerSummary], + unused: Sequence[PointerSummary], + used_paths: set[str], + *, + relative: bool, +) -> str: + """Selects a pointer path (or fallback path) for a required DATA_VALUE slot.""" + pool = unused if unused else compatible + if not pool: + return slot.name if relative else f"/{slot.name}" + chosen = _best_pointer_by_tokens(pool, _tokenize_identifier(slot.name)) + used_paths.add(chosen.path) + return chosen.path + + +def _select_optional_pointer( + slot: ComponentSlot, + unused: Sequence[PointerSummary], + used_paths: set[str], +) -> str | None: + """Selects an unused pointer path for an optional DATA_VALUE slot, or None.""" + if not unused: + return None + slot_tokens = _tokenize_identifier(slot.name) + if slot.value_type == "any": + matched = [ + p + for p in unused + if (slot_tokens & _tokenize_identifier(p.path)) or p.value_type == "object" + ] + if not matched: + return None + chosen = max( + matched, + key=lambda p: len(slot_tokens & _tokenize_identifier(p.path)), + ) + used_paths.add(chosen.path) + return chosen.path + chosen = _best_pointer_by_tokens(unused, slot_tokens) + used_paths.add(chosen.path) + return chosen.path + + +def _select_pointer_for_slot( + slot: ComponentSlot, + pointers: Sequence[PointerSummary], + used_paths: set[str], + *, + relative: bool, +) -> str | None: + """Selects a JSON Pointer path for `slot` from `pointers`.""" + compatible = [p for p in pointers if _pointer_matches_slot_type(p, slot.value_type)] + unused = [p for p in compatible if p.path not in used_paths] + if slot.required: + return _select_required_pointer( + slot, compatible, unused, used_paths, relative=relative + ) + return _select_optional_pointer(slot, unused, used_paths) + + +def _select_enum_value(slot: ComponentSlot, intent: str) -> str | None: + """Selects an enum literal matching `intent` or defaults to the first value.""" + if not slot.enum_values: + return None + intent_lower = intent.lower() + for val in slot.enum_values: + if val.lower() in intent_lower: + return val + return slot.enum_values[0] + + +def _is_binding_ref(ref: Any) -> bool: + """Returns whether `ref` is a JSON Schema `$ref` to a bindable type.""" + return isinstance(ref, str) and ("DataBinding" in ref or "Dynamic" in ref) + + +_SCHEMA_TYPE_CONSTRAINTS = frozenset( + {"type", "$ref", "enum", "const", "oneOf", "anyOf", "allOf"} +) + + +def _schema_allows_binding(schema: Mapping[str, Any]) -> bool: + """Returns whether `schema` accepts an A2UI `DataBinding` object.""" + if _is_binding_ref(schema.get("$ref")): + return True + for key in ("oneOf", "anyOf", "allOf"): + sub_list = schema.get(key) + if isinstance(sub_list, list) and any( + isinstance(s, Mapping) and _schema_allows_binding(s) for s in sub_list + ): + return True + return not bool(_SCHEMA_TYPE_CONSTRAINTS & schema.keys()) + + +def _default_arg_value( + param_name: str, + param_schema: Mapping[str, Any], + pointers: Sequence[PointerSummary], + *, + is_v10: bool, + relative: bool, +) -> Any: + """Builds a schema-valid argument value for a check function parameter.""" + if _schema_allows_binding(param_schema): + if pointers: + chosen = _best_pointer_by_tokens(pointers, _tokenize_identifier(param_name)) + path = chosen.path + else: + path = param_name if relative else f"/{param_name}" + return _make_data_binding(path, is_v10=is_v10) + prim_type = param_schema.get("type") + if prim_type in ("number", "integer"): + return 1 + if prim_type == "boolean": + return True + if prim_type == "array": + return [] + if prim_type == "object": + return {} + return "valid" + + +def _find_function_helper( + helpers: Mapping[str, CatalogSchemaHelper], + fn_name: str, + preferred_catalog_id: str, +) -> tuple[str | None, CatalogSchemaHelper | None]: + """Finds the catalog ID and schema helper defining `fn_name`.""" + preferred = helpers.get(preferred_catalog_id) + if preferred is not None and fn_name in preferred.functions: + return preferred_catalog_id, preferred + for cat_id, helper in helpers.items(): + if fn_name in helper.functions: + return cat_id, helper + return None, None + + +def _build_checks( + graph: CatalogDecisionGraph, + comp_spec: ComponentNodeSpec, + pointers: Sequence[PointerSummary], + *, + is_v10: bool, + relative: bool, +) -> list[dict[str, Any]]: + """Builds validation check rules for checkable components.""" + check_fns = graph.checkable_functions() + if not comp_spec.supports_checks or not check_fns: + return [] + helpers: Mapping[str, CatalogSchemaHelper] = graph.helpers() + chosen_fn = check_fns[0] + for fn_name in check_fns: + cat_id, _ = _find_function_helper(helpers, fn_name, comp_spec.catalog_id) + if cat_id == comp_spec.catalog_id: + chosen_fn = fn_name + break + fn_cat_id, helper = _find_function_helper(helpers, chosen_fn, comp_spec.catalog_id) + args: dict[str, Any] = {} + if helper is not None: + for param_name in helper.get_function_properties(chosen_fn): + p_schema = helper.get_function_property_schema(chosen_fn, param_name) + args[param_name] = _default_arg_value( + param_name, + p_schema or {}, + pointers, + is_v10=is_v10, + relative=relative, + ) + call_key = "@call" if is_v10 else "call" + condition: dict[str, Any] = {call_key: chosen_fn, "args": args} + if graph.surface_catalog_id is None and fn_cat_id is not None: + condition["catalogId"] = fn_cat_id + return [{ + "condition": condition, + "message": ( + f"{chosen_fn[0].upper() + chosen_fn[1:] if chosen_fn else ''} check failed" + ), + }] + + +class _NoEligibleChildError(Exception): + """Raised internally when a container slot has no eligible leaf candidates.""" + + +def _bind_non_child_slots( + comp: dict[str, Any], + spec: ComponentNodeSpec, + intent: str, + pointers: Sequence[PointerSummary], + *, + is_v10: bool, + relative: bool, + allow_actions: bool = True, +) -> None: + """Binds DATA_VALUE, STATIC_ENUM, and ACTION slots on `comp` in place.""" + used_paths: set[str] = set() + selected_paths: dict[str, str | None] = {} + data_slots = [s for s in spec.slots if s.kind == SlotKind.DATA_VALUE] + for slot in sorted(data_slots, key=lambda s: not s.required): + selected_paths[slot.name] = _select_pointer_for_slot( + slot, pointers, used_paths, relative=relative + ) + for slot in spec.slots: + if slot.kind == SlotKind.DATA_VALUE: + path = selected_paths.get(slot.name) + if path is not None: + comp[slot.name] = _make_data_binding(path, is_v10=is_v10) + elif slot.kind == SlotKind.STATIC_ENUM: + enum_val = _select_enum_value(slot, intent) + if enum_val is not None: + comp[slot.name] = enum_val + elif slot.kind == SlotKind.ACTION and allow_actions: + comp[slot.name] = {"event": {"name": slot.name}} + + +def _relative_pointers_for_array( + array_ptr: PointerSummary | None, + fallback_pointers: Sequence[PointerSummary], +) -> list[PointerSummary]: + """Builds relative `PointerSummary` entries for a repeating `ChildList`.""" + if array_ptr is not None and array_ptr.element_keys: + return [ + PointerSummary( + path=key, + value_type=cast( + PointerValueType, + array_ptr.sample_type_by_key.get(key, "string"), + ), + cardinality=1, + mutable_hint=array_ptr.mutable_hint, + ) + for key in array_ptr.element_keys + ] + return [ + PointerSummary( + path=p.path.rsplit("/", 1)[-1] or p.path.lstrip("/"), + value_type=p.value_type, + cardinality=1, + mutable_hint=p.mutable_hint, + ) + for p in fallback_pointers + if p.value_type != "array" + ] + + +def _can_bind_data_pointers( + spec: ComponentNodeSpec, ptr_types: Collection[str] +) -> bool: + """Returns whether `spec` has a data slot and needs no array the pointers lack.""" + data_slots = [s for s in spec.slots if s.kind == SlotKind.DATA_VALUE] + if not data_slots: + return False + return "array" in ptr_types or not any( + s.required and s.value_type == "array" for s in data_slots + ) + + +def _best_leaf_by_pointer_overlap( + candidates: Sequence[ComponentNodeSpec], + pointers: Sequence[PointerSummary], +) -> ComponentNodeSpec: + """Selects the leaf component whose DATA_VALUE slots best match `pointers`.""" + ptr_types = {p.value_type for p in pointers} + return max( + candidates, + key=lambda c: sum( + 1 + for s in c.slots + if s.kind == SlotKind.DATA_VALUE and s.value_type in ptr_types + ), + ) + + +def _named_child_entry( + slot: ComponentSlot, + child_spec: ComponentNodeSpec, + child_id: str, + view_ptrs: Sequence[PointerSummary], + idx: int, +) -> dict[str, Any]: + """Builds a single `NAMED_CHILD_ARRAY` item dict with label and child id.""" + entry: dict[str, Any] = {} + if slot.label_key is not None: + ptr_label = ( + view_ptrs[0].path.rsplit("/", 1)[-1].replace("_", " ").title() + if view_ptrs and view_ptrs[0].path.strip("/") + else f"{child_spec.name}_{idx}" + ) + entry[slot.label_key] = ptr_label + if slot.child_id_key is not None: + entry[slot.child_id_key] = child_id + return entry + + +_MUTABLE_BRIEF_ROLES: frozenset[str] = frozenset({ + "input", + "form", + "settings", + "groups", + "filters", + "compose", +}) +_FRAMING_SCALAR_KEYS: frozenset[str] = frozenset({ + "title", + "subtitle", + "heading", + "subheading", + "subject", + "description", + "summary", + "instructions", +}) +_ACTION_KEYS: frozenset[str] = frozenset({"actions", "buttons", "cta"}) + + +def _promote_mutable_pointers( + pointers: Sequence[PointerSummary], + brief: LayoutBrief | None = None, +) -> tuple[PointerSummary, ...]: + """Marks editable pointers as `mutable_hint=True` when the caller omitted `mutable_paths`.""" + if brief is not None: + pinned_paths = { + p + for sec in brief.sections + if sec.role in _MUTABLE_BRIEF_ROLES + for p in sec.pointers + } + if pinned_paths: + return tuple( + replace(p, mutable_hint=True) + if p.path in pinned_paths + or any(p.path.startswith(f"{bp}/") for bp in pinned_paths) + else p + for p in pointers + ) + editable_candidates = [ + p + for p in pointers + if p.value_type in {"string", "number", "boolean", "object"} + and p.key.lower() not in _ACTION_KEYS + ] + non_framing = { + p.path + for p in editable_candidates + if p.parent or p.key.lower() not in _FRAMING_SCALAR_KEYS + } + target_paths = non_framing if non_framing else {p.path for p in editable_candidates} + return tuple( + replace(p, mutable_hint=True) if p.path in target_paths else p for p in pointers + ) + + +def _coerce_layout_brief( + layout: LayoutBrief | Sequence[str] | None, + grammar: ArchetypeGrammar, +) -> LayoutBrief | None: + """Normalizes an optional `LayoutBrief` or string sequence into a `LayoutBrief`.""" + if layout is None: + return None + if isinstance(layout, LayoutBrief): + return layout if layout.sections else None + parsed = LayoutBrief.parse(layout, roles=grammar.brief_roles()) + return parsed if parsed.sections else None + + +def _catalog_slug(catalog_id: str) -> str: + """Extracts a short identifier slug from a catalog URI or ID.""" + parts = [ + p + for p in catalog_id.split("/") + if p + and not p.endswith(".json") + and not p.startswith("http") + and not re.match(r"^v\d", p) + ] + raw = parts[-1] if parts else catalog_id + return re.sub(r"[^a-zA-Z0-9]+", "_", raw).strip("_").lower() or "cat" + + +def _stamp_function_calls(value: Any, catalog_id: str) -> None: + """Recursively stamps `catalogId` onto function call dicts inside `value`.""" + if isinstance(value, list): + for item in value: + _stamp_function_calls(item, catalog_id) + return + if not isinstance(value, dict): + return + if ("@call" in value or "call" in value) and "args" in value: + value.setdefault("catalogId", catalog_id) + for child in value.values(): + _stamp_function_calls(child, catalog_id) + + +def _archetype_confidence_and_entropy( + state: PlannerState, plan: LayoutPlan | None +) -> tuple[float, float]: + """Extracts confidence and normalized entropy from the archetype or family answer.""" + family = ( + plan.family + if plan is not None + else ( + state.selected_archetype.family + if state.selected_archetype is not None + else None + ) + ) + arch_ans = state.answers_by_id.get(f"archetype:{family}") if family else None + conf = ( + plan.confidence + if plan is not None + else (arch_ans.top()[1] if arch_ans is not None else 0.0) + ) + if arch_ans is not None: + return conf, arch_ans.distribution.normalized_entropy() + fam_ans = state.answers_by_id.get("family") + if fam_ans is not None: + return conf, fam_ans.distribution.normalized_entropy() + return conf, 0.0 + + +def _record_trace_reason(trace: list[DecisionRecord], reason: str, prompt: str) -> None: + """Appends a synthetic `DecisionRecord` with `outcome=reason` if not already last.""" + if trace and trace[-1].outcome == reason: + return + trace.append( + DecisionRecord( + question=DecisionQuestion( + id="archetype_status", + kind=QuestionKind.BOOLEAN, + prompt=prompt, + allow_none=False, + ), + outcome=reason, + ) + ) + + +class DecisionSynthesizer: + """Catalog-agnostic local decision-model A2UI surface synthesizer. + + Attributes: + graph: The catalog decision graph the synthesizer selects from. + backend: The decision backend that scores candidates. + registry: The surface template registry consulted first. + config: Default thresholds and structural limits. + archetypes: The layout archetype grammar. + patterns: The catalog pattern library for expanding planned blocks. + planner: The speculative layout planner. + expander: The pattern template expander. + """ + + def __init__( + self, + catalogs: Sequence[CatalogApi] | CatalogDecisionGraph, + backend: DecisionBackend | None = None, + *, + registry: TemplateRegistry | None = None, + config: SynthesisConfig | None = None, + archetypes: ArchetypeGrammar | None = None, + patterns: PatternLibrary | MergedPatternLibrary | None = None, + fallback_card: bool = False, + fallback_fn: FallbackCallback | None = None, + ) -> None: + """Creates a synthesizer. + + Args: + catalogs: The active catalogs, or a `CatalogDecisionGraph` already + built from them. + backend: The decision backend. Defaults to + `create_decision_backend()`, which reads the + `A2UI_DECISION_*` environment variables. + registry: Surface templates tried before catalog synthesis. + config: Default `SynthesisConfig`; `synthesize` may override it + per call. + archetypes: Layout archetype grammar. Defaults to + `ArchetypeGrammar.default()`. + patterns: Catalog pattern library. Defaults to + `MergedPatternLibrary.for_catalogs(graph.catalogs)`. + fallback_card: When True and the model abstains with no other + fallback available, render a deterministic root container + bound to the payload instead of returning no messages. + fallback_fn: Called with `(intent, payload, surface_id)` when the + model abstains and no `fallback_dsl` was given; its messages + are rendered instead. + """ + self.graph = ( + catalogs + if isinstance(catalogs, CatalogDecisionGraph) + else CatalogDecisionGraph(catalogs) + ) + self.backend: DecisionBackend = ensure_batch_backend( + backend if backend is not None else create_decision_backend() + ) + self.registry = registry if registry is not None else TemplateRegistry() + self.config = config if config is not None else SynthesisConfig() + self.archetypes = ( + archetypes if archetypes is not None else ArchetypeGrammar.default() + ) + self.patterns: PatternLibrary | MergedPatternLibrary = ( + patterns + if patterns is not None + else MergedPatternLibrary.for_catalogs(self.graph.catalogs) + ) + self.planner = LayoutPlanner( + self.archetypes, self.config, capabilities=self.patterns + ) + self.expander = PatternExpander( + self.patterns, self.graph, grammar=self.archetypes + ) + self._fallback_card = fallback_card + self._fallback_fn = fallback_fn + self._eligibility_cache: collections.OrderedDict[ + tuple[Any, ...], tuple[LayoutArchetype, ...] + ] = collections.OrderedDict() + + @classmethod + def from_env( + cls, + catalogs: Sequence[CatalogApi] | CatalogDecisionGraph, + *, + backend: DecisionBackend | None = None, + registry: TemplateRegistry | None = None, + config: SynthesisConfig | None = None, + archetypes: ArchetypeGrammar | None = None, + patterns: PatternLibrary | MergedPatternLibrary | None = None, + fallback_card: bool = False, + fallback_fn: FallbackCallback | None = None, + ) -> DecisionSynthesizer: + """Constructs a DecisionSynthesizer using the environment-configured decision backend. + + Equivalent to calling the constructor; kept for callers that prefer the + explicit name. + """ + return cls( + catalogs, + backend, + registry=registry, + config=config, + archetypes=archetypes, + patterns=patterns, + fallback_card=fallback_card, + fallback_fn=fallback_fn, + ) + + def _describe_component(self, comp: ComponentNodeSpec) -> str: + """Produces a concise natural-language summary of a component spec.""" + parts: list[str] = [] + if comp.description: + parts.append(comp.description.rstrip(".")) + slot_summaries: list[str] = [] + for s in comp.slots: + slot_desc = s.description.rstrip(".") if s.description else "" + if slot_desc: + slot_summaries.append(f"{s.name} ({s.kind.value}: {slot_desc})") + else: + slot_summaries.append(f"{s.name} ({s.kind.value})") + if slot_summaries: + parts.append(f"Slots: {', '.join(slot_summaries)}") + return ". ".join(parts) if parts else comp.name + + async def synthesize( + self, + intent: str, + payload: Mapping[str, Any] | Sequence[Any] | str, + *, + surface_id: str | None = None, + mutable_paths: Collection[str] = (), + config: SynthesisConfig | None = None, + template_id: str | None = None, + fallback_dsl: str | None = None, + layout: LayoutBrief | Sequence[str] | None = None, + title: str | None = None, + summary: str | None = None, + variety_seed: int | None = None, + ) -> SynthesisOutput: + """Synthesizes validated A2UI messages without mutating the template registry. + + Args: + intent: Natural-language description of the UI to render. + payload: The data to bind. A mapping is used as the surface data + model; a JSON array is stored under the `items` key; a + JSON-encoded string of either is decoded first. + surface_id: Target surface. Defaults to `config.default_surface_id`. + mutable_paths: JSON Pointers the user may edit, which raises the + confidence bar. + config: Per-call override of the synthesizer's `SynthesisConfig`. + template_id: Render this registered template directly, skipping + model selection. + fallback_dsl: A2UI Express rendered when the model abstains. + layout: Optional `LayoutBrief` (or `'role:key,key'` string sequence) + pinning roles to payload pointers. + title: Optional authored surface title string placed into headings. + summary: Optional authored surface summary or caption string. + variety_seed: Optional integer seed for reproducible near-top sampling. + + Returns: + The synthesis result. When the model abstains and a fallback + (`fallback_dsl`, `fallback_fn`, or `fallback_card`) applies, the + stage stays `ABSTAIN_FALLBACK`, `messages` holds the fallback + output, and `fallback_source` names which fallback produced it. + + Raises: + ValueError: If `template_id` names no registered template, a + string payload is not valid JSON, or `layout` fails brief + validation. + TypeError: If the payload is neither an object nor an array. + """ + active_config = config if config is not None else self.config + target_surface_id = ( + surface_id if surface_id is not None else active_config.default_surface_id + ) + data = _as_data_model(payload) + brief = _coerce_layout_brief(layout, self.archetypes) + copy = ( + AuthoredCopy(title=title, summary=summary) + if (title is not None or summary is not None) + else None + ) + + if template_id is not None: + return self._render_named_template(template_id, data, target_surface_id) + + pointers = inspect_payload_pointers(data, mutable_paths=mutable_paths or ()) + has_mutable = bool(mutable_paths) or any(p.mutable_hint for p in pointers) + + timings: list[float] = [] + token = _DECISION_CALL_TIMINGS.set(timings) + try: + stage1_out = await self._try_template_stage( + intent, + data, + pointers, + target_surface_id=target_surface_id, + has_mutable=has_mutable, + config=active_config, + ) + if stage1_out is not None: + return replace( + stage1_out, + decision_latency_ms=sum(timings), + decision_calls=len(timings), + ) + + output = await self._synthesize_from_catalog( + intent, + data, + pointers, + target_surface_id=target_surface_id, + has_mutable=has_mutable, + config=active_config, + layout=brief, + copy=copy, + variety_seed=variety_seed, + ) + finally: + _DECISION_CALL_TIMINGS.reset(token) + + output = replace( + output, + decision_latency_ms=sum(timings), + decision_calls=len(timings), + ) + if output.stage is not SynthesisStage.ABSTAIN_FALLBACK or output.messages: + return output + return await self._resolve_abstention_fallback( + output, + intent, + data, + pointers, + surface_id=target_surface_id, + fallback_dsl=fallback_dsl, + config=active_config, + ) + + async def _backend_predict(self, query: DecisionQuery) -> DecisionDistribution: + """Calls `self.backend.predict` and records elapsed decision latency.""" + started = time.perf_counter() + dist = await self.backend.predict(query) + elapsed_ms = (time.perf_counter() - started) * 1000.0 + timings = _DECISION_CALL_TIMINGS.get() + if timings is not None: + timings.append(elapsed_ms) + return dist + + async def _backend_answer(self, batch: DecisionBatch) -> tuple[DecisionAnswer, ...]: + """Calls `self.backend.answer` and records elapsed decision latency.""" + started = time.perf_counter() + answers = await self.backend.answer(batch) + elapsed_ms = (time.perf_counter() - started) * 1000.0 + timings = _DECISION_CALL_TIMINGS.get() + if timings is not None: + timings.append(elapsed_ms) + return answers + + def synthesize_sync( + self, + intent: str, + payload: Mapping[str, Any] | Sequence[Any] | str, + **kwargs: Any, + ) -> SynthesisOutput: + """Runs `synthesize` to completion from synchronous code. + + Works both with and without a running event loop on the calling + thread. With a running loop (for example inside `Parser.compile` called + from an async framework), synthesis runs on a helper thread with its + own loop and the calling loop blocks until it finishes. HTTP backends + re-create their client per loop, so this is safe for every bundled + backend. + + Args: + intent: See `synthesize`. + payload: See `synthesize`. + **kwargs: Keyword arguments forwarded to `synthesize`. + + Returns: + The `SynthesisOutput` from `synthesize`. + """ + + async def _run() -> SynthesisOutput: + try: + return await self.synthesize(intent, payload, **kwargs) + finally: + await self.backend.aclose_current_loop() + + def run_in_new_loop() -> SynthesisOutput: + return asyncio.run(_run()) + + try: + asyncio.get_running_loop() + except RuntimeError: + return run_in_new_loop() + with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool: + return pool.submit(run_in_new_loop).result() + + async def remix( + self, + intent: str, + payload: Mapping[str, Any] | Sequence[Any] | str, + answers: Sequence[DecisionAnswer], + *, + surface_id: str | None = None, + mutable_paths: Collection[str] = (), + brief: LayoutBrief | Sequence[str] | None = None, + title: str | None = None, + summary: str | None = None, + seed: int | None = None, + ) -> SynthesisOutput: + """Re-plans a previously answered surface with variety sampling and 0 decision calls.""" + return self.remix_sync( + intent, + payload, + answers, + surface_id=surface_id, + mutable_paths=mutable_paths, + brief=brief, + title=title, + summary=summary, + seed=seed, + ) + + def remix_sync( + self, + intent: str, + payload: Mapping[str, Any] | Sequence[Any] | str, + answers: Sequence[DecisionAnswer], + *, + surface_id: str | None = None, + mutable_paths: Collection[str] = (), + brief: LayoutBrief | Sequence[str] | None = None, + title: str | None = None, + summary: str | None = None, + seed: int | None = None, + ) -> SynthesisOutput: + """Synchronously re-plans a previously answered surface with 0 decision calls.""" + if not answers: + raise ValueError("answers do not match this intent and payload") + + data = _as_data_model(payload) + brief_obj = _coerce_layout_brief(brief, self.archetypes) + copy = ( + AuthoredCopy(title=title, summary=summary) + if (title is not None or summary is not None) + else None + ) + pointers = inspect_payload_pointers(data, mutable_paths=mutable_paths or ()) + + config_with_variety = replace(self.config, variety=VarietyMode.NEAR_TOP) + planner = LayoutPlanner( + self.archetypes, config_with_variety, capabilities=self.patterns + ) + batch, state = planner.build_batch( + intent, pointers, brief=brief_obj, payload=data, copy=copy + ) + + batch_q_ids = {q.id for q in batch.questions} + ans_q_ids = {a.question_id for a in answers} + if batch_q_ids != ans_q_ids: + raise ValueError("answers do not match this intent and payload") + + outcome = planner.read(state, answers, seed=seed) + if outcome.plan is None: + return SynthesisOutput( + stage=SynthesisStage.ABSTAIN_FALLBACK, + messages=[], + confidence=0.0, + entropy=0.0, + decision_calls=0, + decision_latency_ms=0.0, + decision_answers=tuple(answers), + ) + + components = self._expand_plan(outcome.plan) + target_surface_id = ( + surface_id if surface_id is not None else self.config.default_surface_id + ) + output = self._finish_archetype_output( + outcome.plan, state, components, data, target_surface_id + ) + return replace( + output, + decision_calls=0, + decision_latency_ms=0.0, + decision_answers=tuple(answers), + ) + + def _render_named_template( + self, template_id: str, data: Mapping[str, Any], surface_id: str + ) -> SynthesisOutput: + """Renders a registered template by id with full confidence.""" + template = self.registry.get(template_id) + if template is None: + known = ", ".join(t.template_id for t in self.registry.list_templates()) + raise ValueError( + f"Unknown template '{template_id}'. Registered templates:" + f" {known or 'none'}." + ) + messages = template.render_messages(data, surface_id=surface_id) + validate_payload(self.graph.catalogs, messages) + tree_spec: dict[str, Any] = {"template_id": template.template_id} + root_comp_name = template.root_component() + if root_comp_name is not None: + tree_spec["root_component"] = root_comp_name + return SynthesisOutput( + stage=SynthesisStage.TEMPLATE_SELECT, + messages=messages, + confidence=1.0, + entropy=0.0, + selected_template_id=template.template_id, + component_tree_spec=tree_spec, + ) + + async def _resolve_abstention_fallback( + self, + abstained: SynthesisOutput, + intent: str, + data: Mapping[str, Any], + pointers: Sequence[PointerSummary], + *, + surface_id: str, + fallback_dsl: str | None, + config: SynthesisConfig, + ) -> SynthesisOutput: + """Fills an abstained output from the first applicable fallback. + + Order: `fallback_dsl`, then the configured `fallback_fn`, then the + deterministic card when `fallback_card` is on. With none applicable, + the abstained output is returned unchanged. + """ + messages: list[AgentToRendererMessage] | None = None + source: FallbackSource | None = None + if fallback_dsl and fallback_dsl.strip(): + messages = self._compile_fallback_dsl(fallback_dsl, data, surface_id) + source = FallbackSource.DSL + elif self._fallback_fn is not None: + produced = self._fallback_fn(intent, data, surface_id) + if inspect.isawaitable(produced): + produced = await produced + messages = to_message_models(list(produced)) + validate_payload(self.graph.catalogs, messages) + source = FallbackSource.CALLBACK + elif self._fallback_card: + messages = await self._synthesize_fallback_card( + intent, data, pointers, surface_id=surface_id, config=config + ) + source = FallbackSource.CARD if messages else None + if not messages: + return abstained + return SynthesisOutput( + stage=SynthesisStage.ABSTAIN_FALLBACK, + messages=messages, + confidence=abstained.confidence, + entropy=abstained.entropy, + fallback_source=source, + layout_plan=abstained.layout_plan, + trace=abstained.trace, + decision_latency_ms=abstained.decision_latency_ms, + decision_calls=abstained.decision_calls, + ) + + def _compile_fallback_dsl( + self, dsl: str, data: Mapping[str, Any], surface_id: str + ) -> list[AgentToRendererMessage]: + """Compiles Express fallback DSL, adding the payload as the data model. + + The Express package is imported lazily: `a2ui.inference_formats` + imports this package before `express`, so a module-level import would + see a partially initialized package. + """ + from a2ui.inference_formats.express import ExpressCompiler + + messages = ExpressCompiler(list(self.graph.catalogs)).compile( + dsl, surface_id=surface_id + ) + if data and not any(_populates_data_model(m) for m in messages): + messages.extend( + to_message_models([{ + "version": _wire_version(self.graph.protocol_version), + "updateDataModel": { + "surfaceId": surface_id, + "path": "/", + "value": dict(data), + }, + }]) + ) + validate_payload(self.graph.catalogs, messages) + return messages + + async def _synthesize_fallback_card( + self, + intent: str, + data: Mapping[str, Any], + pointers: Sequence[PointerSummary], + *, + surface_id: str, + config: SynthesisConfig, + ) -> list[AgentToRendererMessage]: + """Builds a deterministic root container bound to the payload pointers. + + Uses the first action-free container the catalogs define (or the first + action-free root candidate) and the deterministic heuristic backend for + child slots, so the result is the same for the same catalogs and + payload. Action slots are never bound because confidence was low. + """ + candidates = [ + c + for c in ( + *self.graph.container_candidates(), + *self.graph.leaf_candidates(), + ) + if not c.has_action_slot + ] + if not candidates: + return [] + deterministic = DecisionSynthesizer( + self.graph, + DeterministicMockBackend(), + registry=self.registry, + config=config, + ) + for candidate in candidates: + try: + components = await deterministic._build_component_subtree( + candidate, + "root", + intent, + pointers, + depth=1, + allow_actions=False, + config=config, + ) + return self._build_validated_messages(surface_id, components, data) + except (_NoEligibleChildError, A2uiValidationError): + continue + return [] + + async def _try_template_stage( + self, + intent: str, + payload: Mapping[str, Any], + pointers: Sequence[PointerSummary], + *, + target_surface_id: str, + has_mutable: bool, + config: SynthesisConfig, + ) -> SynthesisOutput | None: + """Executes Stage 1 template matching and risk-tiered confidence gating.""" + pointer_paths = [p.path for p in pointers] + matching = self.registry.matching_templates(pointer_paths) + if not matching: + return None + + matching_descriptions = { + t.template_id: t.description for t in matching if t.description + } + query_context: dict[str, Any] = {"pointers": pointer_paths} + if matching_descriptions: + query_context["candidate_descriptions"] = matching_descriptions + + dist = await self._backend_predict( + DecisionQuery( + task=DecisionTask.TEMPLATE_SELECT, + prompt=intent, + candidates=tuple(t.template_id for t in matching), + context=query_context, + ) + ) + if not _passes_calibration_gate(dist, config): + return None + + top_id, top_prob = dist.top_choice() + template = self.registry.get(top_id) + if template is None: + return None + + threshold = ( + config.mutable_confidence_threshold + if (has_mutable or template.is_mutable) + else config.template_confidence_threshold + ) + if top_prob < threshold: + return None + + messages = template.render_messages(payload, surface_id=target_surface_id) + validate_payload(self.graph.catalogs, messages) + tree_spec: dict[str, Any] = {"template_id": template.template_id} + root_comp_name = template.root_component() + if root_comp_name is not None: + tree_spec["root_component"] = root_comp_name + return SynthesisOutput( + stage=SynthesisStage.TEMPLATE_SELECT, + messages=messages, + confidence=top_prob, + entropy=dist.normalized_entropy(), + selected_template_id=template.template_id, + component_tree_spec=tree_spec, + ) + + async def _plan_layout( + self, + intent: str, + data: Mapping[str, Any], + pointers: Sequence[PointerSummary], + *, + brief: LayoutBrief | None, + config: SynthesisConfig, + copy: AuthoredCopy | None = None, + variety_seed: int | None = None, + ) -> tuple[PlanOutcome, PlannerState]: + """Builds a speculative batch, calls `backend.answer` (with at most one re-ask), and reads the plan.""" + planner = ( + self.planner + if config == self.config + else LayoutPlanner(self.archetypes, config, capabilities=self.patterns) + ) + use_two_stage = ( + config.two_stage_batching + if config.two_stage_batching is not None + else isinstance( + self.backend, (LocalCrossEncoderBackend, StepZeroLogprobBackend) + ) + ) + if use_two_stage: + stage1_batch, state = planner.build_stage1_batch( + intent, pointers, brief=brief, payload=data, copy=copy + ) + stage1_answers = await self._backend_answer(stage1_batch) + stage2_batch = planner.build_stage2_batch(state, stage1_answers) + stage2_answers = ( + await self._backend_answer(stage2_batch) + if stage2_batch.questions + else () + ) + answers = (*stage1_answers, *stage2_answers) + return planner.read(state, answers, seed=variety_seed), state + + batch, state = planner.build_batch( + intent, pointers, brief=brief, payload=data, copy=copy + ) + answers = await self._backend_answer(batch) + outcome = planner.read(state, answers, seed=variety_seed) + if outcome.plan is None: + return outcome, state + reask = planner.needs_reask(outcome.plan, state) + if not reask: + return outcome, state + reask_batch = DecisionBatch( + shared_context={**batch.shared_context, "reask": True}, + questions=reask, + ) + reask_answers = await self._backend_answer(reask_batch) + reask_by_id = {ans.question_id: ans for ans in reask_answers} + existing_ids = {a.question_id for a in answers} + merged = tuple(reask_by_id.get(a.question_id, a) for a in answers) + tuple( + ans for ans in reask_answers if ans.question_id not in existing_ids + ) + state.trace.clear() + return planner.read(state, merged, seed=variety_seed), state + + def _block_prefix_and_owner( + self, block_id: str, pattern: str + ) -> tuple[str, str | None]: + """Returns `(id_prefix, owner_catalog_id)` for a planned block.""" + if self.graph.surface_catalog_id is not None: + return block_id, None + base_pattern = pattern.split(".", 1)[0].split(":", 1)[0] + owner: str | None = None + if isinstance(self.patterns, MergedPatternLibrary): + owner = self.patterns.owner_catalog_id(base_pattern) + elif self.patterns.catalog_ids: + owner = self.patterns.catalog_ids[0] + if owner is None and self.graph.catalogs: + owner = self.graph.catalogs[0].catalog_id + slug = _catalog_slug(owner) if owner else "cat" + return f"{slug}_{block_id}", owner + + def _stamp_multi_catalog_id( + self, comps: Sequence[dict[str, Any]], owner: str | None + ) -> None: + """Assigns `catalogId` to expanded components on multi-catalog surfaces.""" + if self.graph.surface_catalog_id is not None: + return + default_cat = owner or ( + self.graph.catalogs[0].catalog_id if self.graph.catalogs else None + ) + if default_cat is None: + return + for comp in comps: + comp.setdefault("catalogId", default_cat) + _stamp_function_calls(comp, default_cat) + + def _expand_plan(self, plan: LayoutPlan) -> list[dict[str, Any]]: + """Expands every `PlannedBlock` and the `page` frame through `self.expander`.""" + block_roots: list[str] = [] + block_components: list[dict[str, Any]] = [] + for block in plan.blocks: + prefix, owner = self._block_prefix_and_owner(block.block_id, block.pattern) + expanded = self.expander.expand_block( + block.block_id, + block.pattern, + block.bindings, + block.variant_knobs, + block.instances, + prefix, + ) + if expanded: + self._stamp_multi_catalog_id(expanded, owner) + block_roots.append(str(expanded[0]["id"])) + block_components.extend(expanded) + page_owner = ( + self.patterns.owner_catalog_id("page") + if isinstance(self.patterns, MergedPatternLibrary) + else None + ) + page_components = self.expander.expand_page(plan.page, block_roots=block_roots) + self._stamp_multi_catalog_id(page_components, page_owner) + return [*page_components, *block_components] + + def _finish_archetype_output( + self, + plan: LayoutPlan, + state: PlannerState, + components: list[dict[str, Any]], + data: Mapping[str, Any], + target_surface_id: str, + ) -> SynthesisOutput: + """Runs `lint_components`, validates wire messages, and builds `SynthesisOutput`.""" + trace = list(state.trace) + findings = lint_components(components, plan) + has_error = False + for finding in findings: + trace.append( + DecisionRecord( + question=DecisionQuestion( + id=f"lint:{finding.code}", + kind=QuestionKind.BOOLEAN, + prompt=finding.message, + allow_none=False, + ), + outcome=f"{finding.severity}:{finding.code}", + ) + ) + if finding.severity == "error": + has_error = True + conf, entropy = _archetype_confidence_and_entropy(state, plan) + if has_error: + return SynthesisOutput( + stage=SynthesisStage.ABSTAIN_FALLBACK, + messages=[], + confidence=conf, + entropy=entropy, + layout_plan=plan, + trace=tuple(trace), + decision_answers=tuple(state.answers_by_id.values()), + ) + messages = self._build_validated_messages(target_surface_id, components, data) + root_comp = ( + str(components[0].get("component", "Column")) if components else "Column" + ) + return SynthesisOutput( + stage=SynthesisStage.ARCHETYPE, + messages=messages, + confidence=conf, + entropy=entropy, + component_tree_spec={ + "root_component": root_comp, + "archetype": plan.archetype, + "blocks": list(plan.block_ids()), + "layoutPlan": { + "archetype": plan.archetype, + "blocks": list(plan.block_ids()), + }, + "components": components, + }, + layout_plan=plan, + trace=tuple(trace), + decision_answers=tuple(state.answers_by_id.values()), + ) + + def _family_chose_input(self, state: PlannerState, config: SynthesisConfig) -> bool: + """Returns whether the `family` answer in `state` selected `input` above threshold.""" + fam_ans = state.answers_by_id.get("family") + if fam_ans is None: + return False + chosen, prob = fam_ans.top() + thresh = config.threshold_overrides.get( + "family", self.archetypes.threshold("family") + ) + return chosen == "input" and prob >= thresh + + def _eligible_archetypes( + self, pointers: Sequence[PointerSummary] + ) -> tuple[LayoutArchetype, ...]: + """Memoizes `eligible_archetypes` per payload shape on this synthesizer.""" + key = shape_signature(pointers) + cached = self._eligibility_cache.get(key) + if cached is not None: + self._eligibility_cache.move_to_end(key) + return cached + result = eligible_archetypes(self.archetypes, self.patterns, pointers) + self._eligibility_cache[key] = result + while len(self._eligibility_cache) > _ELIGIBILITY_CACHE_SIZE: + self._eligibility_cache.popitem(last=False) + return result + + async def _synthesize_with_archetypes( + self, + intent: str, + data: Mapping[str, Any], + pointers: Sequence[PointerSummary], + *, + target_surface_id: str, + brief: LayoutBrief | None, + config: SynthesisConfig, + copy: AuthoredCopy | None = None, + variety_seed: int | None = None, + ) -> tuple[SynthesisOutput | None, tuple[DecisionRecord, ...]]: + """Attempts archetype-planned synthesis, returning `(output, trace)`.""" + active_pointers: Sequence[PointerSummary] = pointers + if ( + brief is not None + and not any(p.mutable_hint for p in active_pointers) + and any(r in _MUTABLE_BRIEF_ROLES for r in brief.roles()) + ): + active_pointers = _promote_mutable_pointers(active_pointers, brief) + eligible = self._eligible_archetypes(active_pointers) + if not eligible: + trace: list[DecisionRecord] = [] + _record_trace_reason( + trace, + "no eligible archetype", + "Are any layout archetypes eligible for the active catalogs and" + " payload?", + ) + return None, tuple(trace) + trace = [] + try: + outcome, state = await self._plan_layout( + intent, + data, + active_pointers, + brief=brief, + config=config, + copy=copy, + variety_seed=variety_seed, + ) + if ( + outcome.reason == "no_family" + and not any(p.mutable_hint for p in active_pointers) + and self._family_chose_input(state, config) + ): + promoted = _promote_mutable_pointers(active_pointers, brief) + if any( + a.family == "input" for a in self._eligible_archetypes(promoted) + ): + outcome, state = await self._plan_layout( + intent, + data, + promoted, + brief=brief, + config=config, + copy=copy, + variety_seed=variety_seed, + ) + trace = list(state.trace) + if outcome.reason == "action_gate": + _record_trace_reason(trace, "action_gate", "Action confidence gate") + conf, entropy = _archetype_confidence_and_entropy(state, None) + return ( + SynthesisOutput( + stage=SynthesisStage.ABSTAIN_FALLBACK, + messages=[], + confidence=conf, + entropy=entropy, + trace=tuple(trace), + decision_answers=tuple(state.answers_by_id.values()), + ), + tuple(trace), + ) + if outcome.reason != "planned" or outcome.plan is None: + _record_trace_reason( + trace, str(outcome.reason), "Archetype planning outcome" + ) + return None, tuple(trace) + components = self._expand_plan(outcome.plan) + finished = self._finish_archetype_output( + outcome.plan, state, components, data, target_surface_id + ) + return finished, finished.trace + except ( + _NoEligibleChildError, + PatternError, + A2uiValidationError, + ) as exc: + _record_trace_reason( + trace, + f"{type(exc).__name__}: {exc}", + "Archetype planning or expansion validation", + ) + return None, tuple(trace) + + async def _synthesize_from_catalog( + self, + intent: str, + payload: Mapping[str, Any], + pointers: Sequence[PointerSummary], + *, + target_surface_id: str, + has_mutable: bool, + config: SynthesisConfig, + layout: LayoutBrief | None = None, + copy: AuthoredCopy | None = None, + variety_seed: int | None = None, + ) -> SynthesisOutput: + """Executes Stage 2 catalog-guided synthesis or Stage 3 abstain fallback.""" + arch_trace: tuple[DecisionRecord, ...] = () + if config.use_archetypes: + arch_out, arch_trace = await self._synthesize_with_archetypes( + intent, + payload, + pointers, + target_surface_id=target_surface_id, + brief=layout, + config=config, + copy=copy, + variety_seed=variety_seed, + ) + if arch_out is not None: + return arch_out + + flat_out = await self._synthesize_flat_catalog_path( + intent, + payload, + pointers, + target_surface_id=target_surface_id, + has_mutable=has_mutable, + config=config, + ) + return replace(flat_out, trace=arch_trace) if arch_trace else flat_out + + async def _synthesize_flat_catalog_path( + self, + intent: str, + payload: Mapping[str, Any], + pointers: Sequence[PointerSummary], + *, + target_surface_id: str, + has_mutable: bool, + config: SynthesisConfig, + ) -> SynthesisOutput: + """Executes the flat leaf/container/switcher catalog synthesis path.""" + root_candidates = ( + (self.graph.leaf_candidates() or self.graph.root_candidates()) + if config.max_tree_depth <= 1 + else self.graph.root_candidates() + ) + if not root_candidates: + return SynthesisOutput( + stage=SynthesisStage.ABSTAIN_FALLBACK, + messages=[], + confidence=0.0, + entropy=0.0, + ) + + cand_descriptions = { + c.name: self._describe_component(c) for c in root_candidates + } + dist = await self._backend_predict( + DecisionQuery( + task=DecisionTask.ROOT_COMPONENT, + prompt=intent, + candidates=tuple(c.name for c in root_candidates), + context={ + "pointers": [p.path for p in pointers], + "types": {p.path: p.value_type for p in pointers}, + "candidate_descriptions": cand_descriptions, + }, + ) + ) + top_name, top_prob = dist.top_choice() + entropy = dist.normalized_entropy() + root_spec = self.graph.get_component(top_name) + + if ( + not _passes_calibration_gate(dist, config) + or top_prob < config.abstain_threshold + or root_spec is None + ): + return SynthesisOutput( + stage=SynthesisStage.ABSTAIN_FALLBACK, + messages=[], + confidence=top_prob, + entropy=entropy, + ) + + if self._should_wrap_in_switcher(dist, root_spec, entropy, config=config): + return await self._synthesize_multi_view_switcher( + intent, + payload, + pointers, + dist, + target_surface_id=target_surface_id, + has_mutable=has_mutable, + confidence=top_prob, + entropy=entropy, + config=config, + ) + + if not root_spec.is_container or config.max_tree_depth <= 1: + return self._synthesize_leaf_fast_path( + root_spec, + intent, + payload, + pointers, + target_surface_id=target_surface_id, + has_mutable=has_mutable, + confidence=top_prob, + entropy=entropy, + config=config, + ) + + return await self._synthesize_container_tree( + root_spec, + intent, + payload, + pointers, + target_surface_id=target_surface_id, + has_mutable=has_mutable, + confidence=top_prob, + entropy=entropy, + config=config, + ) + + def _should_wrap_in_switcher( + self, + dist: DecisionDistribution, + root_spec: ComponentNodeSpec, + entropy: float, + *, + config: SynthesisConfig, + ) -> bool: + """Checks whether high-entropy multi-view switcher wrapping applies.""" + if config.max_tree_depth <= 1: + return False + if root_spec.is_multi_view_switcher: + return False + if not self.graph.multi_view_switchers(): + return False + if entropy < (1.0 - config.entropy_switch_margin): + return False + viable_count = sum(1 for p in dist.probabilities.values() if p >= 0.25) + return viable_count >= 2 + + def _select_competing_views( + self, dist: DecisionDistribution, switcher_name: str + ) -> list[ComponentNodeSpec]: + """Selects the top 2 non-switcher view specs from `dist`.""" + ranked = sorted( + dist.probabilities.items(), key=lambda item: item[1], reverse=True + ) + views: list[ComponentNodeSpec] = [] + for cand_name, _ in ranked: + if cand_name == switcher_name: + continue + spec = self.graph.get_component(cand_name) + if ( + spec is not None + and not spec.is_multi_view_switcher + and spec not in views + ): + views.append(spec) + if len(views) == 2: + return views + for fallback in self.graph.root_candidates(): + if not fallback.is_multi_view_switcher and fallback not in views: + views.append(fallback) + if len(views) == 2: + break + return views + + def _switcher_requires_mutable_gate( + self, + switcher: ComponentNodeSpec, + views: Sequence[ComponentNodeSpec], + has_mutable: bool, + ) -> bool: + """Returns whether switcher synthesis requires the mutable threshold.""" + return ( + has_mutable + or switcher.has_action_slot + or any(v.has_action_slot for v in views) + ) + + async def _synthesize_multi_view_switcher( + self, + intent: str, + payload: Mapping[str, Any], + pointers: Sequence[PointerSummary], + dist: DecisionDistribution, + *, + target_surface_id: str, + has_mutable: bool, + confidence: float, + entropy: float, + config: SynthesisConfig, + ) -> SynthesisOutput: + """Wraps competing candidate views in a multi-view switcher.""" + switcher = self.graph.multi_view_switchers()[0] + max_views = min(2, config.max_children_per_container) + views = self._select_competing_views(dist, switcher.name)[:max_views] + if ( + self._switcher_requires_mutable_gate(switcher, views, has_mutable) + and confidence < config.mutable_confidence_threshold + ): + return SynthesisOutput( + stage=SynthesisStage.ABSTAIN_FALLBACK, + messages=[], + confidence=confidence, + entropy=entropy, + ) + + is_v10 = _is_v10(self.graph.protocol_version) + allow_actions = confidence >= config.mutable_confidence_threshold + root_comp = self._init_component_dict(switcher, "root") + _bind_non_child_slots( + root_comp, + switcher, + intent, + pointers, + is_v10=is_v10, + relative=False, + allow_actions=allow_actions, + ) + + child_components: list[dict[str, Any]] = [] + named_items: list[dict[str, Any]] = [] + array_slot = next( + s for s in switcher.slots if s.kind == SlotKind.NAMED_CHILD_ARRAY + ) + + try: + for idx, view_spec in enumerate(views, start=1): + view_id = f"view_{idx}" + built = await self._build_component_subtree( + view_spec, + view_id, + intent, + pointers, + depth=2, + allow_actions=allow_actions, + config=config, + ) + child_components.extend(built) + item: dict[str, Any] = {} + if array_slot.label_key is not None: + item[array_slot.label_key] = view_spec.name + if array_slot.child_id_key is not None: + item[array_slot.child_id_key] = view_id + named_items.append(item) + except _NoEligibleChildError: + return SynthesisOutput( + stage=SynthesisStage.ABSTAIN_FALLBACK, + messages=[], + confidence=confidence, + entropy=entropy, + ) + + root_comp[array_slot.name] = named_items + checks = _build_checks( + self.graph, switcher, pointers, is_v10=is_v10, relative=False + ) + if checks: + root_comp["checks"] = checks + + components = [root_comp, *child_components] + messages = self._build_validated_messages( + target_surface_id, components, payload + ) + return SynthesisOutput( + stage=SynthesisStage.CONTAINER_2PASS, + messages=messages, + confidence=confidence, + entropy=entropy, + component_tree_spec={ + "root_component": switcher.name, + "views": [v.name for v in views], + "components": components, + }, + ) + + def _synthesize_leaf_fast_path( + self, + root_spec: ComponentNodeSpec, + intent: str, + payload: Mapping[str, Any], + pointers: Sequence[PointerSummary], + *, + target_surface_id: str, + has_mutable: bool, + confidence: float, + entropy: float, + config: SynthesisConfig, + ) -> SynthesisOutput: + """Executes Stage 2A 1-pass leaf component synthesis.""" + if ( + root_spec.has_action_slot or has_mutable + ) and confidence < config.mutable_confidence_threshold: + return SynthesisOutput( + stage=SynthesisStage.ABSTAIN_FALLBACK, + messages=[], + confidence=confidence, + entropy=entropy, + ) + + allow_actions = confidence >= config.mutable_confidence_threshold + leaf_comp = self._build_leaf_dict( + root_spec, + "root", + intent, + pointers, + relative=False, + allow_actions=allow_actions, + ) + components = [leaf_comp] + messages = self._build_validated_messages( + target_surface_id, components, payload + ) + return SynthesisOutput( + stage=SynthesisStage.FAST_1PASS_LEAF, + messages=messages, + confidence=confidence, + entropy=entropy, + component_tree_spec={ + "root_component": root_spec.name, + "components": components, + }, + ) + + async def _synthesize_container_tree( + self, + root_spec: ComponentNodeSpec, + intent: str, + payload: Mapping[str, Any], + pointers: Sequence[PointerSummary], + *, + target_surface_id: str, + has_mutable: bool, + confidence: float, + entropy: float, + config: SynthesisConfig, + ) -> SynthesisOutput: + """Executes Stage 2B 2-pass container and child slot synthesis.""" + if ( + root_spec.has_action_slot or has_mutable + ) and confidence < config.mutable_confidence_threshold: + return SynthesisOutput( + stage=SynthesisStage.ABSTAIN_FALLBACK, + messages=[], + confidence=confidence, + entropy=entropy, + ) + + allow_actions = confidence >= config.mutable_confidence_threshold + try: + components = await self._build_component_subtree( + root_spec, + "root", + intent, + pointers, + depth=1, + allow_actions=allow_actions, + config=config, + ) + except _NoEligibleChildError: + return SynthesisOutput( + stage=SynthesisStage.ABSTAIN_FALLBACK, + messages=[], + confidence=confidence, + entropy=entropy, + ) + messages = self._build_validated_messages( + target_surface_id, components, payload + ) + return SynthesisOutput( + stage=SynthesisStage.CONTAINER_2PASS, + messages=messages, + confidence=confidence, + entropy=entropy, + component_tree_spec={ + "root_component": root_spec.name, + "components": components, + }, + ) + + def _init_component_dict( + self, spec: ComponentNodeSpec, comp_id: str + ) -> dict[str, Any]: + """Creates a base component dictionary with `id`, `component`, and optional `catalogId`.""" + comp: dict[str, Any] = {"id": comp_id, "component": spec.name} + if self.graph.surface_catalog_id is None: + comp["catalogId"] = spec.catalog_id + return comp + + def _build_leaf_dict( + self, + spec: ComponentNodeSpec, + comp_id: str, + intent: str, + pointers: Sequence[PointerSummary], + *, + relative: bool, + allow_actions: bool = True, + ) -> dict[str, Any]: + """Builds a single leaf component dictionary bound to `pointers`.""" + is_v10 = _is_v10(self.graph.protocol_version) + comp = self._init_component_dict(spec, comp_id) + _bind_non_child_slots( + comp, + spec, + intent, + pointers, + is_v10=is_v10, + relative=relative, + allow_actions=allow_actions, + ) + checks = _build_checks( + self.graph, spec, pointers, is_v10=is_v10, relative=relative + ) + if checks: + comp["checks"] = checks + return comp + + def _coerce_to_leaf_if_depth_reached( + self, + spec: ComponentNodeSpec, + pointers: Sequence[PointerSummary], + *, + depth: int, + allow_actions: bool, + config: SynthesisConfig, + ) -> ComponentNodeSpec: + """Replaces a container `spec` with a leaf when `depth` hits `max_tree_depth`.""" + if not spec.is_container or depth < config.max_tree_depth: + return spec + leaf_pool = [ + c + for c in self.graph.leaf_candidates() + if allow_actions or not c.has_action_slot + ] + if not leaf_pool: + return spec + return _best_leaf_by_pointer_overlap(leaf_pool, pointers) + + async def _build_component_subtree( + self, + spec: ComponentNodeSpec, + comp_id: str, + intent: str, + pointers: Sequence[PointerSummary], + *, + depth: int = 1, + allow_actions: bool = True, + config: SynthesisConfig, + ) -> list[dict[str, Any]]: + """Builds a component and any child components required by its container slots.""" + effective_spec = self._coerce_to_leaf_if_depth_reached( + spec, + pointers, + depth=depth, + allow_actions=allow_actions, + config=config, + ) + if not effective_spec.is_container: + return [ + self._build_leaf_dict( + effective_spec, + comp_id, + intent, + pointers, + relative=False, + allow_actions=allow_actions, + ) + ] + + is_v10 = _is_v10(self.graph.protocol_version) + comp = self._init_component_dict(effective_spec, comp_id) + _bind_non_child_slots( + comp, + effective_spec, + intent, + pointers, + is_v10=is_v10, + relative=False, + allow_actions=allow_actions, + ) + + children: list[dict[str, Any]] = [] + prefix = "" if comp_id == "root" else f"{comp_id}_" + child_counter = 0 + + for slot in effective_spec.slots: + if not slot.required and len(children) >= config.max_children_per_container: + continue + if slot.kind == SlotKind.CHILD_LIST: + child_counter += 1 + item_id = f"{prefix}item_{child_counter}" + if any(p.value_type == "array" for p in pointers): + item_comp, array_path = await self._build_child_list_item( + effective_spec.name, + slot.name, + item_id, + intent, + pointers, + allow_actions=allow_actions, + ) + comp[slot.name] = {"path": array_path, "componentId": item_id} + else: + item_comp = await self._build_single_child( + effective_spec.name, + slot.name, + item_id, + intent, + pointers, + allow_actions=allow_actions, + ) + comp[slot.name] = [item_id] + children.append(item_comp) + elif slot.kind == SlotKind.CHILD: + child_counter += 1 + child_id = f"{prefix}child_{child_counter}" + child_comp = await self._build_single_child( + effective_spec.name, + slot.name, + child_id, + intent, + pointers, + allow_actions=allow_actions, + ) + comp[slot.name] = child_id + children.append(child_comp) + elif slot.kind == SlotKind.NAMED_CHILD_ARRAY: + remaining = max(1, config.max_children_per_container - len(children)) + named_items, named_children = await self._build_named_child_array( + effective_spec.name, + slot, + prefix, + intent, + pointers, + max_items=remaining, + allow_actions=allow_actions, + ) + comp[slot.name] = named_items + children.extend(named_children) + + checks = _build_checks( + self.graph, effective_spec, pointers, is_v10=is_v10, relative=False + ) + if checks: + comp["checks"] = checks + + return [comp, *children] + + async def _build_child_list_item( + self, + parent_name: str, + slot_name: str, + item_id: str, + intent: str, + pointers: Sequence[PointerSummary], + *, + allow_actions: bool = True, + ) -> tuple[dict[str, Any], str]: + """Synthesizes a repeating leaf component for a `CHILD_LIST` slot.""" + array_ptr = next((p for p in pointers if p.value_type == "array"), None) + array_path = array_ptr.path if array_ptr is not None else f"/{slot_name}" + rel_pointers = _relative_pointers_for_array(array_ptr, pointers) + item_spec = await self._choose_child_component( + intent, + slot_name, + parent_name, + rel_pointers, + allow_actions=allow_actions, + ) + item_comp = self._build_leaf_dict( + item_spec, + item_id, + intent, + rel_pointers, + relative=True, + allow_actions=allow_actions, + ) + return item_comp, array_path + + async def _build_single_child( + self, + parent_name: str, + slot_name: str, + child_id: str, + intent: str, + pointers: Sequence[PointerSummary], + *, + allow_actions: bool = True, + ) -> dict[str, Any]: + """Synthesizes a scalar-bound leaf component for a `CHILD` slot.""" + scalar_ptrs = [p for p in pointers if p.value_type != "array"] or list(pointers) + child_spec = await self._choose_child_component( + intent, + slot_name, + parent_name, + scalar_ptrs, + allow_actions=allow_actions, + ) + return self._build_leaf_dict( + child_spec, + child_id, + intent, + scalar_ptrs, + relative=False, + allow_actions=allow_actions, + ) + + def _select_named_child_specs( + self, + parent_name: str, + *, + max_items: int, + allow_actions: bool, + ) -> list[ComponentNodeSpec]: + """Selects up to `max_items` leaf specs for a `NAMED_CHILD_ARRAY` slot.""" + del parent_name + raw_leaves = [ + c + for c in self.graph.leaf_candidates() + if allow_actions or not c.has_action_slot + ] + if not raw_leaves: + return [] + cap = min(2, max(1, max_items)) + return raw_leaves[:cap] if len(raw_leaves) >= cap else (raw_leaves * cap)[:cap] + + async def _build_named_child_array( + self, + parent_name: str, + slot: ComponentSlot, + prefix: str, + intent: str, + pointers: Sequence[PointerSummary], + *, + max_items: int = 2, + allow_actions: bool = True, + ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + """Synthesizes child leaf views for a `NAMED_CHILD_ARRAY` slot.""" + scalar_ptrs = [p for p in pointers if p.value_type != "array"] or list(pointers) + fallback_specs = self._select_named_child_specs( + parent_name, max_items=max_items, allow_actions=allow_actions + ) + if not fallback_specs: + raise _NoEligibleChildError( + f"No eligible leaf candidates available for child slot '{slot.name}'" + f" on '{parent_name}'." + ) + items: list[dict[str, Any]] = [] + children: list[dict[str, Any]] = [] + for idx, _ in enumerate(fallback_specs, start=1): + view_ptrs = ( + [scalar_ptrs[idx - 1]] if idx <= len(scalar_ptrs) else scalar_ptrs + ) + child_spec = await self._choose_child_component( + intent, + f"{slot.name}[{idx - 1}]", + parent_name, + view_ptrs, + allow_actions=allow_actions, + ) + child_id = f"{prefix}view_{idx}" + children.append( + self._build_leaf_dict( + child_spec, + child_id, + intent, + view_ptrs, + relative=False, + allow_actions=allow_actions, + ) + ) + items.append(_named_child_entry(slot, child_spec, child_id, view_ptrs, idx)) + return items, children + + def _eligible_child_candidates( + self, + child_pointers: Sequence[PointerSummary], + *, + allow_actions: bool, + ) -> tuple[ComponentNodeSpec, ...]: + """Narrows leaf candidates to those that can bind `child_pointers`. + + Drops action-bearing components when actions are not allowed, then + prefers components with a data slot whose required array slots the + pointers can satisfy. + """ + raw_candidates = [ + c + for c in self.graph.leaf_candidates() + if allow_actions or not c.has_action_slot + ] + if not raw_candidates: + return () + filtered = list(raw_candidates) + ptr_types = {p.value_type for p in child_pointers} + data_capable = [c for c in filtered if _can_bind_data_pointers(c, ptr_types)] + if child_pointers and data_capable: + filtered = data_capable + return tuple(filtered) + + def _child_slot_context( + self, + slot_name: str, + parent_name: str, + child_pointers: Sequence[PointerSummary], + candidates: Sequence[ComponentNodeSpec], + ) -> dict[str, Any]: + """Builds the `DecisionQuery.context` for a child slot choice.""" + parent_spec = self.graph.get_component(parent_name) + parent_slot = parent_spec.get_slot(slot_name) if parent_spec else None + return { + "parent": parent_name, + "parent_description": ( + parent_spec.description + if parent_spec and parent_spec.description + else parent_name + ), + "slot": slot_name, + "slot_description": ( + parent_slot.description + if parent_slot and parent_slot.description + else slot_name + ), + "pointers": [p.path for p in child_pointers], + "candidate_descriptions": { + c.name: self._describe_component(c) for c in candidates + }, + } + + async def _choose_child_component( + self, + intent: str, + slot_name: str, + parent_name: str, + child_pointers: Sequence[PointerSummary], + *, + allow_actions: bool = True, + ) -> ComponentNodeSpec: + """Selects a leaf component for a container slot via backend or pointer fit.""" + candidates = self._eligible_child_candidates( + child_pointers, allow_actions=allow_actions + ) + if not candidates: + raise _NoEligibleChildError( + f"No eligible leaf candidates available for child slot '{slot_name}'" + f" on '{parent_name}'." + ) + if len(candidates) == 1: + return candidates[0] + dist = await self._backend_predict( + DecisionQuery( + task=DecisionTask.CHILD_COMPONENT, + prompt=intent, + candidates=tuple(c.name for c in candidates), + context=self._child_slot_context( + slot_name, parent_name, child_pointers, candidates + ), + ) + ) + top_name, top_prob = dist.top_choice() + chosen = self.graph.get_component(top_name) + if ( + chosen is not None + and not chosen.is_container + and top_prob > 0.0 + and chosen in candidates + ): + return chosen + return _best_leaf_by_pointer_overlap(candidates, child_pointers) + + def _build_validated_messages( + self, + surface_id: str, + components: list[dict[str, Any]], + payload: Mapping[str, Any], + ) -> list[AgentToRendererMessage]: + """Builds and validates `createSurface`, `updateComponents`, and `updateDataModel`.""" + wire_ver = _wire_version(self.graph.protocol_version) + create_body: dict[str, Any] = {"surfaceId": surface_id} + if self.graph.surface_catalog_id is not None: + create_body["catalogId"] = self.graph.surface_catalog_id + + raw_messages: list[dict[str, Any]] = [ + {"version": wire_ver, "createSurface": create_body}, + { + "version": wire_ver, + "updateComponents": { + "surfaceId": surface_id, + "components": components, + }, + }, + ] + if payload: + raw_messages.append({ + "version": wire_ver, + "updateDataModel": { + "surfaceId": surface_id, + "path": "/", + "value": dict(payload), + }, + }) + models = to_message_models(raw_messages) + validate_payload(self.graph.catalogs, models) + return models diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/template_registry.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/template_registry.py new file mode 100644 index 0000000000..93a4589cf1 --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/template_registry.py @@ -0,0 +1,290 @@ +# 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. + +"""Pre-validated A2UI surface templates and registry for decision-model synthesis.""" + +from __future__ import annotations + +from collections.abc import Collection, Mapping, Sequence +import copy +from dataclasses import dataclass +from typing import Any + +from a2ui.core import A2uiValidationError +from a2ui.core.schema import AgentToRendererMessage +from a2ui.parser.messages import to_message_dicts, to_message_models + +from .models import SynthesisOutput + + +def _normalize_wire_version(protocol_version: str) -> str: + """Returns the wire envelope version string for a given protocol version.""" + clean = protocol_version.strip().lstrip("v") + if clean == "1" or clean.startswith("1."): + return "v1.0" + if clean in ("0.8", "0.9", "0.9.1"): + return "v0.9" + return protocol_version + + +def _validate_component_dict(component: Mapping[str, Any]) -> None: + """Validates that a raw component dictionary has required A2UI keys.""" + if not isinstance(component, Mapping): + raise A2uiValidationError("Component definition must be a mapping.") + comp_id = component.get("id") + if not isinstance(comp_id, str) or not comp_id.strip(): + raise A2uiValidationError( + "Component definition must include a non-empty string 'id'." + ) + comp_type = component.get("component") + if not isinstance(comp_type, str) or not comp_type.strip(): + raise A2uiValidationError( + "Component definition must include a non-empty string 'component'." + ) + + +@dataclass(frozen=True) +class _SurfaceEnvelopes: + """Surface-defining fields collected from a message batch, any wire version.""" + + surface_id: str | None + catalog_id: str | None + components: list[Mapping[str, Any]] + protocol_version: str | None + + +def _mapping_or_none(value: Any) -> Mapping[str, Any] | None: + return value if isinstance(value, Mapping) else None + + +# Envelope keys whose body may carry a `components` list, by wire version: +# v1.0 `createSurface`, v0.9 `updateComponents`, v0.8 `surfaceUpdate`. +_COMPONENT_ENVELOPES = ("createSurface", "updateComponents", "surfaceUpdate") + + +def _surface_body(msg: Mapping[str, Any]) -> Mapping[str, Any] | None: + """Returns the surface-creating body (`createSurface` or v0.8 `beginRendering`).""" + return _mapping_or_none(msg.get("createSurface")) or _mapping_or_none( + msg.get("beginRendering") + ) + + +def _normalize_extracted_component(comp: Mapping[str, Any]) -> dict[str, Any]: + """Normalizes a component dict, flattening v0.8 `{id, component: {Type: props}}`.""" + raw_comp = comp.get("component") + if isinstance(raw_comp, Mapping) and len(raw_comp) == 1: + comp_type, props = next(iter(raw_comp.items())) + out: dict[str, Any] = {"id": comp.get("id"), "component": str(comp_type)} + if isinstance(props, Mapping): + out.update(props) + return out + return dict(comp) + + +def _components_in(msg: Mapping[str, Any]) -> list[Mapping[str, Any]]: + """Returns the component dicts the message carries, in order.""" + found: list[Mapping[str, Any]] = [] + for key in _COMPONENT_ENVELOPES: + body = _mapping_or_none(msg.get(key)) + raw = body.get("components") if body is not None else None + if isinstance(raw, Sequence) and not isinstance(raw, (str, bytes)): + found.extend( + _normalize_extracted_component(c) for c in raw if isinstance(c, Mapping) + ) + return found + + +def _surface_id_in(msg: Mapping[str, Any]) -> str | None: + """Returns the first `surfaceId` any envelope body in the message names.""" + for body in msg.values(): + if isinstance(body, Mapping) and isinstance(body.get("surfaceId"), str): + return str(body["surfaceId"]) + return None + + +def _catalog_id_in(msg: Mapping[str, Any]) -> str | None: + """Returns the `catalogId` of the surface-creating envelope, if any.""" + surface = _surface_body(msg) + raw = surface.get("catalogId") if surface is not None else None + return str(raw) if raw is not None else None + + +def _extract_envelopes(msg_dicts: Sequence[Mapping[str, Any]]) -> _SurfaceEnvelopes: + """Collects the surface id, catalog id, components, and wire version. + + Understands the three envelope shapes a synthesized or hand-written batch + may use: v0.9 `createSurface` + `updateComponents`, v1.0 `createSurface` + with embedded `components` (optionally followed by `updateComponents`), + and v0.8 `beginRendering` + `surfaceUpdate`. Components from every + component-bearing envelope are concatenated in message order. + """ + surface_id: str | None = None + catalog_id: str | None = None + components: list[Mapping[str, Any]] = [] + protocol_version: str | None = None + + for msg in msg_dicts: + version = msg.get("version") + protocol_version = ( + protocol_version + if protocol_version is not None or not isinstance(version, str) + else version + ) + catalog_id = catalog_id if catalog_id is not None else _catalog_id_in(msg) + surface_id = surface_id if surface_id is not None else _surface_id_in(msg) + components.extend(_components_in(msg)) + + return _SurfaceEnvelopes(surface_id, catalog_id, components, protocol_version) + + +@dataclass(frozen=True) +class SurfaceTemplate: + """Pre-validated A2UI surface template parameterized by JSON Pointer paths.""" + + template_id: str + description: str + surface_id: str + catalog_id: str | None + protocol_version: str + components: tuple[dict[str, Any], ...] + required_pointers: tuple[str, ...] = () + is_mutable: bool = False + + def matches_payload(self, available_pointers: Collection[str]) -> bool: + """Returns whether all required JSON Pointers are present in the payload.""" + return all(req in available_pointers for req in self.required_pointers) + + def root_component(self) -> str | None: + """Returns the component type name of the root component in this template.""" + if not self.components: + return None + for comp in self.components: + if comp.get("id") == "root" and isinstance(comp.get("component"), str): + return str(comp["component"]) + first_comp = self.components[0].get("component") + return str(first_comp) if isinstance(first_comp, str) else None + + def render_messages( + self, + payload: Mapping[str, Any], + *, + surface_id: str | None = None, + ) -> list[AgentToRendererMessage]: + """Renders and validates A2UI wire messages for this surface template.""" + target_surface_id = surface_id if surface_id is not None else self.surface_id + if not isinstance(target_surface_id, str) or not target_surface_id.strip(): + raise A2uiValidationError("Surface ID must be a non-empty string.") + if not self.components: + raise A2uiValidationError( + "SurfaceTemplate must define at least one component." + ) + for comp in self.components: + _validate_component_dict(comp) + + wire_version = _normalize_wire_version(self.protocol_version) + create_surface_body: dict[str, Any] = {"surfaceId": target_surface_id} + if self.catalog_id is not None: + create_surface_body["catalogId"] = self.catalog_id + + raw_messages: list[dict[str, Any]] = [ + { + "version": wire_version, + "createSurface": create_surface_body, + }, + { + "version": wire_version, + "updateComponents": { + "surfaceId": target_surface_id, + "components": [copy.deepcopy(c) for c in self.components], + }, + }, + ] + if payload: + raw_messages.append({ + "version": wire_version, + "updateDataModel": { + "surfaceId": target_surface_id, + "path": "/", + "value": dict(payload), + }, + }) + + return to_message_models(raw_messages) + + +class TemplateRegistry: + """Registry of pre-validated A2UI surface templates for Stage 1 selection.""" + + def __init__(self) -> None: + """Initializes an empty surface template registry.""" + self._templates: dict[str, SurfaceTemplate] = {} + + def register(self, template: SurfaceTemplate) -> None: + """Validates and registers a surface template by its template ID.""" + template.render_messages({}) + self._templates[template.template_id] = template + + def get(self, template_id: str) -> SurfaceTemplate | None: + """Returns the registered template for `template_id`, or None if absent.""" + return self._templates.get(template_id) + + def list_templates(self) -> tuple[SurfaceTemplate, ...]: + """Returns all registered surface templates in registration order.""" + return tuple(self._templates.values()) + + def matching_templates( + self, available_pointers: Collection[str] + ) -> tuple[SurfaceTemplate, ...]: + """Returns registered templates whose required pointers match the payload.""" + return tuple( + template + for template in self._templates.values() + if template.matches_payload(available_pointers) + ) + + def promote_synthesized( + self, + template_id: str, + description: str, + output: SynthesisOutput, + *, + required_pointers: Sequence[str] = (), + is_mutable: bool = False, + ) -> SurfaceTemplate: + """Promotes a synthesized UI output into a reusable registered template. + + Accepts v0.9, v1.0, and v0.8 message envelopes (see `_extract_envelopes`). + + Raises: + ValueError: If the messages define no components. + """ + envelopes = _extract_envelopes(to_message_dicts(output.messages)) + if not envelopes.components: + raise ValueError( + "SynthesisOutput messages must define components in a createSurface," + " updateComponents, or surfaceUpdate envelope." + ) + + template = SurfaceTemplate( + template_id=template_id, + description=description, + surface_id=envelopes.surface_id or "default_surface", + catalog_id=envelopes.catalog_id, + protocol_version=envelopes.protocol_version or "v0.9", + components=tuple(copy.deepcopy(dict(c)) for c in envelopes.components), + required_pointers=tuple(required_pointers), + is_mutable=is_mutable, + ) + self.register(template) + return template diff --git a/python/a2ui_agent/src/a2ui/inference_formats/decision/tool.py b/python/a2ui_agent/src/a2ui/inference_formats/decision/tool.py new file mode 100644 index 0000000000..51642c4287 --- /dev/null +++ b/python/a2ui_agent/src/a2ui/inference_formats/decision/tool.py @@ -0,0 +1,328 @@ +# 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. + +"""A framework-agnostic tool that renders A2UI from an intent and a payload. + +Agent frameworks (MCP servers, ADK, OpenAI and Gemini function calling) all +describe tools with a JSON Schema and call them with a dict of arguments. +`DecisionRenderTool` supplies both halves so an integration does not have to +write the schema, decode stringified payloads, or bridge sync and async +itself:: + + tool = DecisionRenderTool.create(catalogs) + declaration = {"name": tool.name, "description": tool.description, + "parameters": tool.parameters_json_schema()} + output = await tool.run_async(call_arguments) +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import replace +from typing import Any + +from a2ui.core import CatalogApi +from a2ui.parser.messages import to_message_dicts + +from .archetypes import ArchetypeGrammar +from .backends import DecisionBackend +from .catalog_graph import CatalogDecisionGraph +from .decision_block import DecisionBlock +from .models import ( + BRIEF_ITEM_PATTERN, + MAX_BRIEF_SECTIONS, + SynthesisConfig, + SynthesisOutput, +) +from .patterns import MergedPatternLibrary, PatternLibrary +from .synthesizer import DecisionSynthesizer, FallbackCallback +from .template_registry import TemplateRegistry + +_DEFAULT_TOOL_NAME = "render_a2ui_decision" +_DEFAULT_DESCRIPTION = ( + "Renders a user interface from a short description of what to show" + " (intent) and the data to show (payload). A local decision model picks" + " the components; do not describe components yourself." +) + + +class DecisionRenderTool: + """Tool declaration plus runner for decision-model UI synthesis. + + Attributes: + name: Tool name advertised to the model. + description: Tool description advertised to the model. + synthesizer: The synthesizer that renders each call. + include_trace: Whether serialized tool results include the decision trace. + """ + + def __init__( + self, + synthesizer: DecisionSynthesizer, + *, + name: str = _DEFAULT_TOOL_NAME, + description: str = _DEFAULT_DESCRIPTION, + surface_id: str | None = None, + include_trace: bool = False, + ) -> None: + """Wraps a synthesizer as a tool. + + Args: + synthesizer: Renders each tool call. + name: Tool name advertised to the model. + description: Tool description advertised to the model. + surface_id: Surface used when a call names none; None defers to + the synthesizer's `config.default_surface_id`. A call's own + `surfaceId` always wins. + include_trace: Whether serialized results include `trace`. + """ + self.name = name + self.description = description + self.synthesizer = synthesizer + self._surface_id = surface_id + self.include_trace = include_trace + + @classmethod + def create( + cls, + catalogs: Sequence[CatalogApi] | CatalogDecisionGraph, + *, + backend: DecisionBackend | None = None, + config: SynthesisConfig | None = None, + registry: TemplateRegistry | None = None, + archetypes: ArchetypeGrammar | None = None, + patterns: PatternLibrary | MergedPatternLibrary | None = None, + fallback_card: bool = True, + fallback_fn: FallbackCallback | None = None, + name: str = _DEFAULT_TOOL_NAME, + description: str = _DEFAULT_DESCRIPTION, + surface_id: str | None = None, + include_trace: bool = False, + ) -> DecisionRenderTool: + """Builds a tool and its synthesizer in one call. + + `fallback_card` defaults to True: a tool call that renders nothing is + an error from the model's point of view, so an abstention renders a + deterministic card unless the call supplied `fallbackDsl`. + + Args: + catalogs: The active catalogs, or a prebuilt `CatalogDecisionGraph`. + backend: Decision backend; defaults to `create_decision_backend()`. + config: Synthesis thresholds and limits. + registry: Surface templates offered through the `template` field. + archetypes: Layout archetype grammar. + patterns: Catalog pattern library. + fallback_card: Render a deterministic card on abstention. + fallback_fn: Custom fallback tried before the card. + name: Tool name advertised to the model. + description: Tool description advertised to the model. + surface_id: Surface used when a call names none; None defers to + `config.default_surface_id`. A call's own `surfaceId` wins. + include_trace: Whether serialized results include `trace`. + """ + synthesizer = DecisionSynthesizer( + catalogs, + backend, + registry=registry, + config=config, + archetypes=archetypes, + patterns=patterns, + fallback_card=fallback_card, + fallback_fn=fallback_fn, + ) + return cls( + synthesizer, + name=name, + description=description, + surface_id=surface_id, + include_trace=include_trace, + ) + + def parameters_json_schema(self) -> dict[str, Any]: + """Returns the JSON Schema for the tool's arguments. + + `payload` accepts an object, an array, or a JSON-encoded string of + either, since models often stringify nested arguments. + """ + template_ids = [ + t.template_id for t in self.synthesizer.registry.list_templates() + ] + template_schema: dict[str, Any] = { + "type": "string", + "description": "Id of a registered surface template to render directly.", + } + if template_ids: + template_schema["enum"] = template_ids + return { + "type": "object", + "properties": { + "intent": { + "type": "string", + "description": ( + "Short natural-language description of the interface to" + " render and how the user should interact with it." + ), + }, + "payload": { + "description": ( + "The data to display: a JSON object (preferred) or array," + " or a JSON-encoded string of either. Use descriptive" + " camelCase keys. A top-level array is stored under the" + " `items` key of the surface data model." + ), + "anyOf": [ + {"type": "object"}, + {"type": "array"}, + {"type": "string"}, + ], + }, + "surfaceId": { + "type": "string", + "description": "Surface to create or update.", + }, + "template": template_schema, + "fallbackDsl": { + "type": "string", + "description": ( + "A2UI Express rendered if the decision model is not" + " confident enough to choose components." + ), + }, + "layout": { + "type": "array", + "maxItems": MAX_BRIEF_SECTIONS, + "items": {"type": "string", "pattern": BRIEF_ITEM_PATTERN}, + "description": ( + "Optional ordered layout brief grouping payload keys by" + " role (':,', up to 6 sections; no" + " nested sections)." + ), + }, + "mutablePaths": { + "type": "array", + "items": {"type": "string"}, + "description": ( + "Optional JSON Pointers (or top-level key names) in" + " `payload` that the user may edit, such as form fields" + " or settings toggles." + ), + }, + }, + "required": ["intent", "payload"], + "additionalProperties": False, + } + + def _synthesis_kwargs( + self, args: Mapping[str, Any] + ) -> tuple[DecisionBlock, dict[str, Any]]: + block = DecisionBlock.from_mapping(args) + kwargs: dict[str, Any] = { + "template_id": block.template_id, + "fallback_dsl": block.fallback_dsl, + } + if block.layout: + kwargs["layout"] = block.layout + if block.mutable_paths: + kwargs["mutable_paths"] = block.mutable_paths + surface_id = block.surface_id or self._surface_id + if surface_id is not None: + kwargs["surface_id"] = surface_id + return block, kwargs + + def format_result( + self, + output: SynthesisOutput, + *, + include_trace: bool | None = None, + ) -> dict[str, Any]: + """Serializes a `SynthesisOutput` into a tool-result dictionary.""" + with_trace = self.include_trace if include_trace is None else include_trace + result: dict[str, Any] = { + "stage": str(output.stage), + "confidence": output.confidence, + "entropy": output.entropy, + "messages": to_message_dicts(output.messages), + } + if output.layout_plan is not None: + result["layoutPlan"] = { + "archetype": output.layout_plan.archetype, + "blocks": list(output.layout_plan.block_ids()), + } + if with_trace: + result["trace"] = [ + { + "questionId": r.question.id, + "outcome": r.outcome, + "threshold": r.threshold, + } + for r in output.trace + ] + return result + + def _enrich_output( + self, output: SynthesisOutput, *, include_trace: bool + ) -> SynthesisOutput: + """Attaches `layoutPlan` and optional `trace` to `output.component_tree_spec`.""" + if output.layout_plan is None and not include_trace: + return output + spec = dict(output.component_tree_spec or {}) + if output.layout_plan is not None: + spec["layoutPlan"] = { + "archetype": output.layout_plan.archetype, + "blocks": list(output.layout_plan.block_ids()), + } + if include_trace: + spec["trace"] = [ + { + "questionId": r.question.id, + "outcome": r.outcome, + "threshold": r.threshold, + } + for r in output.trace + ] + return replace(output, component_tree_spec=spec) + + async def run_async( + self, args: Mapping[str, Any], *, include_trace: bool | None = None + ) -> SynthesisOutput: + """Renders one tool call. + + Args: + args: The tool-call arguments, with the field names from + `parameters_json_schema` (snake_case spellings are accepted). + include_trace: When True, includes `trace` in `component_tree_spec`. + + Raises: + ValueError: If `intent` is missing, `payload` is an invalid JSON + string, `template` is unknown, or `layout` is invalid. + TypeError: If `payload` is neither an object nor an array. + """ + block, kwargs = self._synthesis_kwargs(args) + output = await self.synthesizer.synthesize( + block.intent, block.payload, **kwargs + ) + with_trace = self.include_trace if include_trace is None else include_trace + return self._enrich_output(output, include_trace=with_trace) + + def run_sync( + self, args: Mapping[str, Any], *, include_trace: bool | None = None + ) -> SynthesisOutput: + """Renders one tool call from synchronous code. See `run_async`.""" + block, kwargs = self._synthesis_kwargs(args) + output = self.synthesizer.synthesize_sync(block.intent, block.payload, **kwargs) + with_trace = self.include_trace if include_trace is None else include_trace + return self._enrich_output(output, include_trace=with_trace) + + +__all__ = ["DecisionRenderTool"] diff --git a/python/a2ui_agent/tests/decision/layout_fixtures.py b/python/a2ui_agent/tests/decision/layout_fixtures.py new file mode 100644 index 0000000000..a4b58a5f3c --- /dev/null +++ b/python/a2ui_agent/tests/decision/layout_fixtures.py @@ -0,0 +1,194 @@ +# 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. + +"""Shared payload fixtures and scripted answers for layout tests. + +The four payloads are the worked examples from the layout design (a resort +overview, host health, a transfer confirmation, and podcast settings). +`ScriptedAnswers` turns a mapping of question ids to answers into a scorer for +`DeterministicMockBackend`, so planner and end-to-end tests share one way of +scripting a batch. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass, field +import math +from typing import Any + +from a2ui.inference_formats.decision import ( + DecisionDistribution, + DecisionQuery, + DeterministicMockBackend, +) + + +@dataclass(frozen=True) +class LayoutFixture: + """One worked-example surface: intent, payload, and mutable paths.""" + + name: str + intent: str + payload: Mapping[str, Any] + mutable_paths: tuple[str, ...] = () + + +RESORT = LayoutFixture( + name="resort", + intent="Show the resort overview", + payload={ + "name": "Casa Verde", + "logoUrl": "https://example.com/casa-verde/logo.png", + "rating": 4.6, + "priceFrom": 240, + "about": ( + "A quiet hillside resort twenty minutes from the old town, with a" + " spring-fed pool, garden suites, and a breakfast terrace that looks" + " over the valley. Families and walkers come back year after year." + ), + "photos": [ + {"url": "https://example.com/casa-verde/1.jpg", "caption": "Pool at dusk"}, + {"url": "https://example.com/casa-verde/2.jpg", "caption": "Garden suite"}, + { + "url": "https://example.com/casa-verde/3.jpg", + "caption": "Breakfast terrace", + }, + ], + }, +) + +HOST = LayoutFixture( + name="host", + intent="Show CPU utilization for prod-1", + payload={ + "host": "prod-1", + "cpu": 0.78, + "cpuDelta": 0.12, + "status": "degraded", + "uptimeHours": 412, + }, +) + +TRANSFER = LayoutFixture( + name="transfer", + intent="Confirm sending $50 to Alex before it goes through", + payload={ + "amount": 50, + "currency": "USD", + "recipient": "Alex Chen", + "fee": 0.5, + "arrives": "2026-10-24", + "actions": ["Send", "Cancel"], + }, + mutable_paths=("/actions",), +) + +SETTINGS = LayoutFixture( + name="settings", + intent="Playback and notification settings", + payload={ + "playback": {"skipForward": "30 seconds", "autoDownload": True, "speed": 1.25}, + "notifications": {"newEpisodes": True, "digest": False}, + "account": {"signOut": "Sign out"}, + }, + mutable_paths=("/playback", "/notifications", "/account"), +) + +FIXTURES: dict[str, LayoutFixture] = { + f.name: f for f in (RESORT, HOST, TRANSFER, SETTINGS) +} + +ScriptedValue = float | str | tuple[str, float] | Mapping[str, float] +"""How one answer may be scripted. + +A float is the yes probability of a boolean question or the expected level of +a score question; a str is the chosen option of a choice question (with +probability 0.9); a ``(option, probability)`` pair sets that probability; a +mapping is the full distribution. +""" + + +def _choice_distribution( + chosen: str, probability: float, candidates: tuple[str, ...] +) -> dict[str, float]: + """Gives `chosen` `probability` and shares the rest among the others.""" + others = [c for c in candidates if c != chosen] + if chosen not in candidates: + raise ValueError(f"Scripted option {chosen!r} is not among {candidates}.") + rest = (1.0 - probability) / len(others) if others else 0.0 + return {c: probability if c == chosen else rest for c in candidates} + + +def _score_distribution(expected: float, levels: tuple[str, ...]) -> dict[str, float]: + """Splits mass between the two levels around `expected` so the mean matches.""" + top = len(levels) - 1 + value = min(max(expected, 0.0), float(top)) + low = min(int(math.floor(value)), top) + high = min(low + 1, top) + weight_high = value - low + probs = {level: 0.0 for level in levels} + probs[levels[low]] += 1.0 - weight_high + probs[levels[high]] += weight_high + return probs + + +def _boolean_distribution(yes: float) -> dict[str, float]: + return {"yes": yes, "no": 1.0 - yes} + + +@dataclass +class ScriptedAnswers: + """Question id to scripted answer, as a scorer for `DeterministicMockBackend`. + + Unscripted questions get a uniform distribution. Every question id scored + is appended to `asked`, in call order, for assertions. + """ + + answers: Mapping[str, ScriptedValue] = field(default_factory=dict) + asked: list[str] = field(default_factory=list) + + def scorer(self, query: DecisionQuery) -> DecisionDistribution: + """Scores a query built by `_AnswerViaPredict` from a `DecisionQuestion`.""" + question_id = str(query.context.get("question_id", "")) + kind = str(query.context.get("question_kind", "choice")) + self.asked.append(question_id) + probs = self._probabilities( + self.answers.get(question_id), kind, query.candidates + ) + return DecisionDistribution( + probabilities=probs, calibrated=True, top_logit_margin=2.5 + ) + + def backend(self) -> DeterministicMockBackend: + """A mock backend that answers through `scorer`.""" + return DeterministicMockBackend(scorer=self.scorer) + + @staticmethod + def _probabilities( + scripted: ScriptedValue | None, kind: str, candidates: tuple[str, ...] + ) -> dict[str, float]: + if scripted is None: + return {c: 1.0 / len(candidates) for c in candidates} if candidates else {} + if isinstance(scripted, Mapping): + return dict(scripted) + if isinstance(scripted, tuple): + return _choice_distribution(scripted[0], scripted[1], candidates) + if isinstance(scripted, str): + return _choice_distribution(scripted, 0.9, candidates) + if kind == "boolean": + return _boolean_distribution(float(scripted)) + if kind == "score": + return _score_distribution(float(scripted), candidates) + raise ValueError(f"A choice question cannot be scripted with {scripted!r}.") diff --git a/python/a2ui_agent/tests/decision/test_archetypes.py b/python/a2ui_agent/tests/decision/test_archetypes.py new file mode 100644 index 0000000000..595937c86e --- /dev/null +++ b/python/a2ui_agent/tests/decision/test_archetypes.py @@ -0,0 +1,480 @@ +# 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. + +"""Unit tests for the archetype grammar loader, model, and lint.""" + +from __future__ import annotations + +import copy +from typing import Any + +import pytest + +from a2ui.inference_formats.decision.archetypes import ( + ArchetypeGrammar, + BlockRef, + GrammarError, + MeasureSpec, + ShapeFilter, + lint_grammar, + load_asset, +) +from a2ui.inference_formats.decision.models import QuestionKind + +_EXPECTED_ARCHETYPES = ( + "feed", + "compare", + "dashboard", + "detail", + "result", + "confirm", + "checkout", + "form", + "settings", + "guide", + "article", + "timeline", + "location", + "chat", +) +_EXPECTED_BLOCKS = ( + "banner", + "picture", + "filters", + "headline", + "media", + "chart", + "facts", + "prose", + "collection", + "comparison", + "steps", + "form", + "groups", + "actions", + "timeline", + "map", + "conversation", + "compose", + "outcome", +) + + +def _raw_grammar() -> dict[str, Any]: + """A deep copy of the bundled grammar JSON, safe to mutate.""" + return copy.deepcopy(load_asset("archetypes.json")) + + +def _minimal_grammar() -> dict[str, Any]: + """The smallest grammar that passes schema validation and lint.""" + return { + "version": "1", + "thresholds": { + "family": 0.4, + "archetype": 0.4, + "expected": 0.5, + "optional": 0.75, + "instance": 0.5, + "reask_below": 0.75, + "actionGateFloor": 0.7, + "actionGateCap": 0.95, + }, + "job": { + "family": { + "kind": "choice", + "question": "What is the person here to do?", + "options": {"inspect": "Understand one thing."}, + }, + "stakes": { + "kind": "score", + "question": "Stakes?", + "levels": ["none", "high"], + }, + "urgency": { + "kind": "score", + "question": "Urgency?", + "levels": ["no", "now"], + }, + }, + "archetypes": [{ + "id": "detail", + "family": "inspect", + "criteria": "One thing in depth.", + "blocks": ["prose!", "facts?"], + }], + "blocks": [ + { + "id": "prose", + "pattern": "prose", + "gate": { + "kind": "boolean", + "question": "Is there something to read about {body}?", + "yes": "Yes.", + "no": "No.", + }, + "slots": {"body": {"from": ["long_text", "string"], "required": True}}, + "fallback": ["prose"], + }, + { + "id": "facts", + "pattern": "facts", + "slots": { + "rows": { + "repeat": True, + "from": ["string"], + "fields": { + "label": {"from": ["key"]}, + "value": {"from": ["any"], "required": True}, + }, + } + }, + "anatomy": { + "density": { + "kind": "choice", + "question": "How dense?", + "options": {"tight": "Tight rows.", "loose": "Loose rows."}, + "requires": {"tight": ["value"], "loose": ["actions_allowed"]}, + } + }, + "fallback": ["facts", "collection:rows", "prose"], + }, + ], + } + + +def test_default_grammar_round_trips_the_bundled_asset() -> None: + grammar = ArchetypeGrammar.default() + assert grammar.version == "1" + assert tuple(a.id for a in grammar.archetypes) == _EXPECTED_ARCHETYPES + assert tuple(grammar.blocks) == _EXPECTED_BLOCKS + assert grammar.families() == ( + "browse", + "monitor", + "inspect", + "act", + "input", + "follow", + ) + assert len({a.family for a in grammar.archetypes}) == 6 + assert grammar.thresholds["actionGateFloor"] == pytest.approx(0.70) + assert grammar.thresholds["actionGateCap"] == pytest.approx(0.95) + assert grammar.threshold("reask_below") == pytest.approx(0.75) + assert len(grammar.rules) == 11 + assert len(grammar.lint) == 5 + + +def test_default_grammar_is_cached() -> None: + assert ArchetypeGrammar.default() is ArchetypeGrammar.default() + fresh = ArchetypeGrammar.from_json(load_asset("archetypes.json")) + assert fresh is not ArchetypeGrammar.default() + assert fresh == ArchetypeGrammar.default() + + +def test_block_marks_are_parsed_into_requirements() -> None: + detail = ArchetypeGrammar.default().archetype("detail") + assert detail.block_ids() == ( + "picture", + "banner", + "headline", + "prose", + "facts", + "media", + "collection", + "actions", + ) + assert detail.requirement_of("picture") == "optional" + assert detail.requirement_of("prose") == "expected" + assert detail.requirement_of("missing") is None + assert detail.at_least == 2 + feed = ArchetypeGrammar.default().archetype("feed") + assert feed.required_block_ids() == ("collection",) + assert BlockRef.parse("x!").mark == "x!" + assert BlockRef.parse("x?").mark == "x?" + assert BlockRef.parse("x").mark == "x" + + +def test_archetype_shape_and_frame_are_parsed() -> None: + grammar = ArchetypeGrammar.default() + assert grammar.archetype("compare").shape == ShapeFilter(array_length=(2, 5)) + assert grammar.archetype("feed").shape.is_empty + assert grammar.archetype("confirm").frame == {"dialog": True} + chat = grammar.archetype("chat").shape + assert chat.pointers == ("array",) + assert "author" in chat.element_keys + filters = grammar.block("filters").shape + assert filters.array_length == (8, None) + assert filters.mutable is True + + +def test_block_questions_slots_and_fallbacks_are_parsed() -> None: + grammar = ArchetypeGrammar.default() + collection = grammar.block("collection") + assert collection.gate is not None + assert collection.gate.kind is QuestionKind.BOOLEAN + assert collection.gate.yes.startswith("Results") + layout = collection.anatomy["layout"] + assert layout.kind is QuestionKind.CHOICE + assert tuple(layout.options) == ("rows", "cards", "grid", "reel") + assert layout.requires["grid"] == ("picture", "pattern:collection:grid") + assert collection.instance["badge_tone"].applies_when == {"badge": "bound"} + assert collection.instance["badge_tone"].placeholders() == ("badge",) + items = collection.slots["items"] + assert items.repeat and items.required + assert items.fields["headline"].prefer == ("name", "title", "label") + assert items.fields["meta"].max == 2 + assert collection.fallback == ("collection",) + assert dict(collection.questions())["anatomy.layout"] is layout + + headline = grammar.block("headline") + assert headline.salience is not None + assert headline.salience.per_pointer + assert headline.salience.select == {"min": 1, "max": 6, "aboveLevel": 1.5} + assert headline.salience.option_ids() == headline.salience.levels + assert headline.anatomy["gauge"].applies_when == {"value": "bounded"} + + picture = grammar.block("picture") + assert picture.slots["picture"].avoid_keys == ( + "logo", + "icon", + "avatar", + "thumbnail", + ) + assert picture.slots["width"].sibling == ("width", "w") + assert "keyHint" in picture.anatomy["framing"].derived_when + + comparison = grammar.block("comparison") + assert comparison.instance["headline_attribute"].options_from == "attributes" + assert grammar.block("compose").slots["sendLabel"].default == "Send" + assert grammar.block("conversation").anatomy["self"].options_from == ( + "messages.author.distinct" + ) + + +def test_prose_length_measure_levels() -> None: + length = ArchetypeGrammar.default().block("prose").measures["length"] + assert length.derived_from == "body.hints.wordCount" + assert length.level_for(0) == "line" + assert length.level_for(14) == "line" + assert length.level_for(15) == "blurb" + assert length.level_for(199) == "summary" + assert length.level_for(200) == "article" + assert length.level_for(5000) == "article" + bounded = MeasureSpec(name="m", derived_from="x", levels={"a": (0, 1)}) + assert bounded.level_for(2) is None + + +def test_job_questions_and_brief_roles() -> None: + grammar = ArchetypeGrammar.default() + assert grammar.job["family"].kind is QuestionKind.CHOICE + assert grammar.job["stakes"].kind is QuestionKind.SCORE + assert len(grammar.job["stakes"].levels) == 4 + assert len(grammar.job["urgency"].levels) == 3 + roles = grammar.brief_roles() + assert roles[:6] == grammar.families() + assert set(roles[6:]) == set(_EXPECTED_BLOCKS) + assert grammar.archetypes_in("act") == tuple( + grammar.archetype(i) for i in ("result", "confirm", "checkout") + ) + with pytest.raises(KeyError): + grammar.archetype("nope") + with pytest.raises(KeyError): + grammar.threshold("nope") + + +def test_minimal_grammar_loads() -> None: + grammar = ArchetypeGrammar.from_json(_minimal_grammar()) + assert grammar.archetype("detail").requirement_of("prose") == "required" + assert grammar.block("facts").slot_names() == ("rows", "label", "value") + assert grammar.rules == () + + +def test_schema_violation_raises_grammar_error() -> None: + raw = _minimal_grammar() + raw["thresholds"]["family"] = 1.5 + with pytest.raises(GrammarError, match="schema validation") as info: + ArchetypeGrammar.from_json(raw) + assert "/thresholds/family" in str(info.value) + + raw = _minimal_grammar() + raw["blocks"][0]["gate"]["kind"] = "ternary" + with pytest.raises(GrammarError, match="schema validation"): + ArchetypeGrammar.from_json(raw) + + raw = _minimal_grammar() + raw["archetypes"][0]["blocks"] = ["Prose!"] + with pytest.raises(GrammarError, match="schema validation"): + ArchetypeGrammar.from_json(raw) + + +def test_lint_archetype_needs_required_or_expected_block() -> None: + raw = _minimal_grammar() + raw["archetypes"][0]["blocks"] = ["prose?", "facts?"] + with pytest.raises(GrammarError, match="no required or expected block"): + ArchetypeGrammar.from_json(raw) + + +def test_lint_block_ids_must_exist() -> None: + raw = _minimal_grammar() + raw["archetypes"][0]["blocks"].append("ghost") + with pytest.raises(GrammarError, match="unknown block 'ghost'"): + ArchetypeGrammar.from_json(raw) + + +@pytest.mark.parametrize("entry", ["sparkles", "sparkle-dust", "unknown:rows"]) +def test_lint_fallback_entries(entry: str) -> None: + raw = _minimal_grammar() + raw["blocks"][1]["fallback"] = [entry] + with pytest.raises(GrammarError, match="fallback entry"): + ArchetypeGrammar.from_json(raw) + + +@pytest.mark.parametrize("entry", ["collection:", "collection:Cards", "a:b:c"]) +def test_schema_rejects_malformed_fallback_entries(entry: str) -> None: + raw = _minimal_grammar() + raw["blocks"][1]["fallback"] = [entry] + with pytest.raises(GrammarError, match="schema validation"): + ArchetypeGrammar.from_json(raw) + + +def test_lint_block_pattern_must_be_abstract_pattern() -> None: + raw = _minimal_grammar() + raw["blocks"][1]["pattern"] = "sparkles" + with pytest.raises(GrammarError, match="not an abstract pattern"): + ArchetypeGrammar.from_json(raw) + + +def test_lint_placeholders_must_name_slots() -> None: + raw = _minimal_grammar() + raw["blocks"][0]["gate"]["question"] = "Is {headline} readable?" + with pytest.raises(GrammarError, match="refers to 'headline'"): + ArchetypeGrammar.from_json(raw) + + +def test_lint_applies_when_must_name_slots() -> None: + raw = _minimal_grammar() + raw["blocks"][1]["anatomy"]["density"]["appliesWhen"] = {"badge": "bound"} + with pytest.raises(GrammarError, match="refers to 'badge'"): + ArchetypeGrammar.from_json(raw) + + +@pytest.mark.parametrize( + "entry", ["nope", "pattern:sparkles.grid", "density:huge", "pattern:collection"] +) +def test_lint_requires_entries(entry: str) -> None: + raw = _minimal_grammar() + raw["blocks"][1]["anatomy"]["density"]["requires"] = {"tight": [entry]} + with pytest.raises(GrammarError, match=f"requires {entry!r}"): + ArchetypeGrammar.from_json(raw) + + +@pytest.mark.parametrize( + "entry", + [ + "value", + "rows", + "actions_allowed", + "pattern:collection:grid", + "loose", + "density:loose", + ], +) +def test_lint_requires_accepts_valid_entries(entry: str) -> None: + raw = _minimal_grammar() + raw["blocks"][1]["anatomy"]["density"]["requires"] = {"tight": [entry]} + ArchetypeGrammar.from_json(raw) + + +def test_lint_options_from_must_start_at_slot() -> None: + raw = _minimal_grammar() + raw["blocks"][1]["anatomy"]["density"] = { + "kind": "choice", + "question": "Which?", + "optionsFrom": "columns.name", + } + with pytest.raises(GrammarError, match="optionsFrom 'columns.name'"): + ArchetypeGrammar.from_json(raw) + raw["blocks"][1]["anatomy"]["density"]["optionsFrom"] = "rows.label" + ArchetypeGrammar.from_json(raw) + + +def test_lint_rejects_duplicate_ids() -> None: + raw = _minimal_grammar() + raw["blocks"].append(copy.deepcopy(raw["blocks"][0])) + with pytest.raises(GrammarError, match="Duplicate block id 'prose'"): + ArchetypeGrammar.from_json(raw) + raw = _minimal_grammar() + raw["archetypes"].append(copy.deepcopy(raw["archetypes"][0])) + with pytest.raises(GrammarError, match="Duplicate archetype id 'detail'"): + ArchetypeGrammar.from_json(raw) + + +def test_lint_reports_every_finding_at_once() -> None: + raw = _minimal_grammar() + raw["archetypes"][0]["blocks"] = ["ghost?", "prose?"] + raw["blocks"][1]["fallback"] = ["sparkles"] + with pytest.raises(GrammarError) as info: + ArchetypeGrammar.from_json(raw) + message = str(info.value) + assert "no required or expected block" in message + assert "unknown block 'ghost'" in message + assert "fallback entry 'sparkles'" in message + + +def test_lint_grammar_on_bundled_grammar_is_clean() -> None: + grammar = ArchetypeGrammar.default() + assert lint_grammar(grammar.archetypes, tuple(grammar.blocks.values())) == [] + + +def test_bundled_grammar_mutation_is_caught_by_lint() -> None: + raw = _raw_grammar() + raw["archetypes"][0]["blocks"] = ["banner?", "filters?"] + with pytest.raises(GrammarError, match="Archetype 'feed'"): + ArchetypeGrammar.from_json(raw) + + +def test_lint_rejects_unknown_archetype_family() -> None: + raw = _minimal_grammar() + raw["archetypes"][0]["family"] = "orient" + with pytest.raises( + GrammarError, match="Archetype 'detail' references unknown family 'orient'" + ): + ArchetypeGrammar.from_json(raw) + + +def test_grammar_threshold_relations_are_linted() -> None: + raw = _minimal_grammar() + raw["thresholds"]["actionGateFloor"] = 0.96 + with pytest.raises(GrammarError, match="actionGateFloor must be <= actionGateCap"): + ArchetypeGrammar.from_json(raw) + raw = _minimal_grammar() + raw["thresholds"]["expected"] = 0.8 + with pytest.raises(GrammarError, match="expected must be <= optional"): + ArchetypeGrammar.from_json(raw) + + +def test_requirement_and_block_marks_are_enums_that_compare_to_wire_strings() -> None: + from a2ui.inference_formats.decision.models import Requirement + + ref = BlockRef.parse("prose!") + assert ref.requirement is Requirement.REQUIRED + assert ref.requirement == "required" + assert ref.mark == "prose!" + assert {ref.requirement} == {"required"} + + +def test_lint_rejects_retired_fallback_keywords() -> None: + raw = _minimal_grammar() + raw["blocks"][1]["fallback"] = ["facts", "repeat-in-parent"] + with pytest.raises(GrammarError, match="fallback entry 'repeat-in-parent'"): + ArchetypeGrammar.from_json(raw) diff --git a/python/a2ui_agent/tests/decision/test_backends.py b/python/a2ui_agent/tests/decision/test_backends.py new file mode 100644 index 0000000000..0e82f8c035 --- /dev/null +++ b/python/a2ui_agent/tests/decision/test_backends.py @@ -0,0 +1,1664 @@ +# 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. + +"""Unit tests for local decision-model inference backends.""" + +from __future__ import annotations + +from dataclasses import dataclass +import json +import math +import sys +from typing import Any + +import httpx +import pytest + +from a2ui.inference_formats.decision import ( + DecisionBackend, + DecisionBatch, + DecisionDistribution, + DecisionQuery, + DecisionQuestion, + DeterministicMockBackend, + JevHttpBackend, + LocalCrossEncoderBackend, + PredictOnlyBackend, + QuestionKind, + StepZeroLogprobBackend, + create_decision_backend, + ensure_batch_backend, +) + + +def test_backends_satisfy_runtime_protocol() -> None: + jev = JevHttpBackend("http://localhost:8080/predict") + step_zero = StepZeroLogprobBackend("http://localhost:8000/v1/completions", "m") + mock = DeterministicMockBackend() + local = LocalCrossEncoderBackend() + assert isinstance(jev, DecisionBackend) + assert isinstance(step_zero, DecisionBackend) + assert isinstance(mock, DecisionBackend) + assert isinstance(local, DecisionBackend) + + +@pytest.mark.asyncio +async def test_predict_only_backends_are_adapted_to_the_full_protocol() -> None: + """A third-party object with only `predict` (and optionally `aclose`) still works.""" + closed = False + + class LegacyPredictOnly: + + async def predict(self, query: DecisionQuery) -> DecisionDistribution: + first = query.candidates[0] + return DecisionDistribution( + probabilities={c: 0.9 if c == first else 0.1 for c in query.candidates} + ) + + async def aclose(self) -> None: + nonlocal closed + closed = True + + legacy = LegacyPredictOnly() + assert not isinstance(legacy, DecisionBackend) + adapted = ensure_batch_backend(legacy) + assert isinstance(adapted, DecisionBackend) + assert isinstance(adapted, PredictOnlyBackend) + batch = DecisionBatch( + shared_context={}, + questions=( + DecisionQuestion( + id="gate:prose", kind=QuestionKind.BOOLEAN, prompt="Prose?" + ), + DecisionQuestion( + id="family", + kind=QuestionKind.CHOICE, + prompt="Family?", + options=("browse", "inspect"), + allow_none=False, + ), + ), + ) + answers = await adapted.answer(batch) + assert [a.question_id for a in answers] == ["gate:prose", "family"] + assert answers[0].yes == pytest.approx(0.9) + assert answers[1].top()[0] == "browse" + await adapted.aclose_current_loop() + async with adapted: + pass + assert closed + + # Objects that already satisfy the protocol are returned unchanged. + mock = DeterministicMockBackend() + assert ensure_batch_backend(mock) is mock + with pytest.raises(TypeError, match="predict"): + ensure_batch_backend(object()) + + +@pytest.mark.asyncio +async def test_jev_http_backend_normalizes_and_filters_probabilities() -> None: + captured_Bodies: list[dict[str, Any]] = [] + + def handler(request: httpx.Request) -> httpx.Response: + captured_Bodies.append(json.loads(request.content.decode("utf-8"))) + return httpx.Response( + 200, + json={ + "probabilities": { + "PortfolioCard": 0.6, + "OrderTicket": 0.2, + "UnrequestedWidget": 0.9, + }, + "calibrated": False, + "top_logit_margin": 1.85, + }, + ) + + transport = httpx.MockTransport(handler) + async with httpx.AsyncClient(transport=transport) as client: + backend = JevHttpBackend("http://jev.local/predict", client=client) + query = DecisionQuery( + task="root_component", + prompt="Show portfolio summary", + candidates=("PortfolioCard", "OrderTicket", "MissingCard"), + context={"pointers": ["/totalValue"]}, + ) + dist = await backend.predict(query) + + assert len(captured_Bodies) == 1 + assert captured_Bodies[0] == { + "task": "root_component", + "prompt": "Show portfolio summary", + "candidates": ["PortfolioCard", "OrderTicket", "MissingCard"], + "context": {"pointers": ["/totalValue"]}, + } + assert dist.calibrated is False + assert dist.top_logit_margin == pytest.approx(1.85) + assert set(dist.probabilities.keys()) == { + "PortfolioCard", + "OrderTicket", + "MissingCard", + } + assert dist.probabilities["PortfolioCard"] == pytest.approx(0.75) + assert dist.probabilities["OrderTicket"] == pytest.approx(0.25) + assert dist.probabilities["MissingCard"] == pytest.approx(0.0) + assert dist.top_choice() == ("PortfolioCard", pytest.approx(0.75)) + + +@pytest.mark.asyncio +async def test_jev_http_backend_handles_all_zero_and_empty_candidates() -> None: + def handler(request: httpx.Request) -> httpx.Response: + del request + return httpx.Response( + 200, + json={"probabilities": {"Other": 0.5}, "calibrated": True}, + ) + + transport = httpx.MockTransport(handler) + async with httpx.AsyncClient(transport=transport) as client: + backend = JevHttpBackend("http://jev.local/predict", client=client) + dist_zero = await backend.predict( + DecisionQuery(task="t", prompt="p", candidates=("A", "B")) + ) + assert dist_zero.probabilities == {"A": 0.0, "B": 0.0} + assert dist_zero.calibrated is True + assert dist_zero.top_logit_margin is None + + dist_empty = await backend.predict( + DecisionQuery(task="t", prompt="p", candidates=()) + ) + assert dist_empty.probabilities == {} + + +def test_step_zero_logprob_backend_rejects_non_positive_temperature() -> None: + with pytest.raises(ValueError, match="temperature"): + StepZeroLogprobBackend( + "http://localhost:8000/v1/completions", "model", temperature=0.0 + ) + with pytest.raises(ValueError, match="temperature"): + StepZeroLogprobBackend( + "http://localhost:8000/v1/completions", "model", temperature=-0.5 + ) + + +@pytest.mark.asyncio +async def test_step_zero_logprob_backend_softmax_and_temperature_scaling() -> None: + captured_requests: list[dict[str, Any]] = [] + + def handler(request: httpx.Request) -> httpx.Response: + captured_requests.append(json.loads(request.content.decode("utf-8"))) + return httpx.Response( + 200, + json={ + "choices": [{ + "logprobs": { + "top_logprobs": [{ + " VitalsCard": -0.5, + "LabTable": -2.5, + "IgnoredToken": -0.1, + }] + } + }] + }, + ) + + transport = httpx.MockTransport(handler) + query = DecisionQuery( + task="root_component", + prompt="Show patient vitals", + candidates=("VitalsCard", "LabTable"), + ) + + async with httpx.AsyncClient(transport=transport) as client: + uncalibrated_backend = StepZeroLogprobBackend( + "http://vllm.local/v1/completions", + "gemma-decision", + temperature=1.0, + client=client, + ) + dist_t1 = await uncalibrated_backend.predict(query) + + sharp_backend = StepZeroLogprobBackend( + "http://vllm.local/v1/completions", + "gemma-decision", + temperature=0.5, + client=client, + ) + dist_t05 = await sharp_backend.predict(query) + + flat_backend = StepZeroLogprobBackend( + "http://vllm.local/v1/completions", + "gemma-decision", + temperature=2.0, + client=client, + ) + dist_t2 = await flat_backend.predict(query) + + assert captured_requests[0]["model"] == "gemma-decision" + assert "Task: root_component" in captured_requests[0]["prompt"] + assert "Candidates: [A: VitalsCard, B: LabTable]" in captured_requests[0]["prompt"] + assert "Intent: Show patient vitals" in captured_requests[0]["prompt"] + assert captured_requests[0]["max_tokens"] == 1 + assert captured_requests[0]["temperature"] == 0.0 + assert captured_requests[0]["logprobs"] == 5 + assert dist_t1.calibrated is False + assert dist_t05.calibrated is True + assert dist_t2.calibrated is True + + assert dist_t1.top_logit_margin == pytest.approx(2.0) + assert dist_t05.top_logit_margin == pytest.approx(2.0) + assert dist_t2.top_logit_margin == pytest.approx(2.0) + + expected_t1_vitals = 1.0 / (1.0 + math.exp(-2.0)) + assert dist_t1.probabilities["VitalsCard"] == pytest.approx(expected_t1_vitals) + assert dist_t1.probabilities["LabTable"] == pytest.approx(1.0 - expected_t1_vitals) + assert ( + dist_t05.probabilities["VitalsCard"] + > dist_t1.probabilities["VitalsCard"] + > dist_t2.probabilities["VitalsCard"] + ) + + +@pytest.mark.asyncio +async def test_step_zero_logprob_backend_missing_and_empty_candidates() -> None: + def handler(request: httpx.Request) -> httpx.Response: + del request + return httpx.Response( + 200, + json={"choices": [{"logprobs": {"top_logprobs": [{"OnlyOne": -1.0}]}}]}, + ) + + transport = httpx.MockTransport(handler) + async with httpx.AsyncClient(transport=transport) as client: + backend = StepZeroLogprobBackend( + "http://vllm.local/v1/completions", + "gemma-decision", + temperature=1.2, + client=client, + ) + dist_single = await backend.predict( + DecisionQuery(task="t", prompt="p", candidates=("OnlyOne",)) + ) + assert dist_single.probabilities == {"OnlyOne": pytest.approx(1.0)} + assert dist_single.top_logit_margin is not None + assert math.isinf(dist_single.top_logit_margin) + + dist_missing = await backend.predict( + DecisionQuery(task="t", prompt="p", candidates=("MissingA", "MissingB")) + ) + assert dist_missing.probabilities == { + "MissingA": pytest.approx(0.5), + "MissingB": pytest.approx(0.5), + } + assert dist_missing.top_logit_margin == pytest.approx(0.0) + + dist_empty = await backend.predict( + DecisionQuery(task="t", prompt="p", candidates=()) + ) + assert dist_empty.probabilities == {} + assert dist_empty.top_logit_margin == pytest.approx(0.0) + assert dist_empty.calibrated is True + + +@pytest.mark.asyncio +async def test_deterministic_mock_backend_scorer_and_scripted() -> None: + custom_dist = DecisionDistribution( + probabilities={"Custom": 1.0}, calibrated=False, top_logit_margin=0.9 + ) + scored_backend = DeterministicMockBackend(scorer=lambda q: custom_dist) + res = await scored_backend.predict( + DecisionQuery(task="any", prompt="any", candidates=("Custom",)) + ) + assert res == custom_dist + + scripted_backend = DeterministicMockBackend( + scripted={ + "root_component": {"CardA": 3.0, "CardB": 1.0, "Extra": 5.0}, + "root_component:specific prompt": {"CardB": 4.0, "CardA": 1.0}, + }, + calibrated=False, + default_logit_margin=3.2, + ) + dist_task = await scripted_backend.predict( + DecisionQuery( + task="root_component", + prompt="general prompt", + candidates=("CardA", "CardB", "CardC"), + ) + ) + assert dist_task.calibrated is False + assert dist_task.top_logit_margin == pytest.approx(3.2) + assert dist_task.probabilities == { + "CardA": pytest.approx(0.75), + "CardB": pytest.approx(0.25), + "CardC": pytest.approx(0.0), + } + + dist_specific = await scripted_backend.predict( + DecisionQuery( + task="root_component", + prompt="specific prompt", + candidates=("CardA", "CardB"), + ) + ) + assert dist_specific.probabilities == { + "CardA": pytest.approx(0.20), + "CardB": pytest.approx(0.80), + } + + +@pytest.mark.asyncio +async def test_deterministic_mock_backend_heuristic_and_edge_cases() -> None: + backend = DeterministicMockBackend() + query = DecisionQuery( + task="root_component", + prompt="Display cluster cpu metrics and incident alerts", + candidates=("PortfolioSummary", "ClusterMetricsPanel", "PatientVitals"), + context={"pointers": ["/cluster/cpu", "/incidents"]}, + ) + dist1 = await backend.predict(query) + dist2 = await backend.predict(query) + assert dist1 == dist2 + assert sum(dist1.probabilities.values()) == pytest.approx(1.0) + top_cand, top_prob = dist1.top_choice() + assert top_cand == "ClusterMetricsPanel" + assert top_prob >= 0.85 + + dist_single = await backend.predict( + DecisionQuery(task="t", prompt="p", candidates=("SingleComp",)) + ) + assert dist_single.probabilities == {"SingleComp": 1.0} + + dist_empty = await backend.predict( + DecisionQuery(task="t", prompt="p", candidates=()) + ) + assert dist_empty.probabilities == {} + assert dist_empty.top_logit_margin == pytest.approx(0.0) + + +@pytest.mark.asyncio +async def test_normalize_probabilities_preserves_sub_unit_mass_and_fail_closed_calibration() -> ( + None +): + """Verifies H3 (sub-1.0 mass is not inflated to 1.0) and M2 (missing calibrated is False).""" + + def handler(request: httpx.Request) -> httpx.Response: + del request + return httpx.Response( + 200, + json={ + "probabilities": {"LowConfCandidate": 0.10, "Unlisted": 0.85}, + }, + ) + + transport = httpx.MockTransport(handler) + async with httpx.AsyncClient(transport=transport) as client: + backend = JevHttpBackend("http://jev.local/predict", client=client) + dist = await backend.predict( + DecisionQuery(task="t", prompt="p", candidates=("LowConfCandidate",)) + ) + assert dist.calibrated is False + assert dist.probabilities["LowConfCandidate"] == pytest.approx(0.10) + assert dist.top_choice() == ("LowConfCandidate", pytest.approx(0.10)) + + +@pytest.mark.asyncio +async def test_step_zero_logprob_backend_caps_logprobs_at_20_and_closes_owned_client() -> ( + None +): + """Verifies Q1 (logprobs capped at 20 for >20 candidates) and M6 (aclose on owned client).""" + captured: list[dict[str, Any]] = [] + + def handler(request: httpx.Request) -> httpx.Response: + captured.append(json.loads(request.content.decode("utf-8"))) + return httpx.Response( + 200, + json={"choices": [{"logprobs": {"top_logprobs": [{"C0": -0.2}]}}]}, + ) + + with pytest.raises(ValueError, match="max_logprobs"): + StepZeroLogprobBackend( + "http://localhost:8000/v1/completions", "m", max_logprobs=25 + ) + + transport = httpx.MockTransport(handler) + async with httpx.AsyncClient(transport=transport) as client: + backend = StepZeroLogprobBackend( + "http://vllm.local/v1/completions", + "gemma", + max_logprobs=8, + client=client, + ) + ten_candidates = tuple(f"C{i}" for i in range(10)) + await backend.predict( + DecisionQuery( + task="root_component", + prompt="Pick one", + candidates=ten_candidates, + context={"k": "v"}, + ) + ) + assert captured[0]["logprobs"] == 8 + assert "Context: {'k': 'v'}" in captured[0]["prompt"] + + owned_jev = JevHttpBackend("http://jev.local/predict") + c1 = owned_jev._get_client() + c2 = owned_jev._get_client() + assert c1 is c2 + await owned_jev.aclose() + + owned_step = StepZeroLogprobBackend("http://vllm.local/v1/completions", "m") + s1 = owned_step._get_client() + s2 = owned_step._get_client() + assert s1 is s2 + await owned_step.aclose() + + +@pytest.mark.asyncio +async def test_normalize_probabilities_ignores_non_numeric_values() -> None: + """Safely ignores non-numeric probability values during normalization.""" + + def handler(request: httpx.Request) -> httpx.Response: + del request + return httpx.Response( + 200, + json={ + "probabilities": { + "ValidCard": "0.75", + "InvalidCard": "not-a-number", + "NullMeta": None, + "ObjectMeta": {"nested": 1}, + }, + "calibrated": True, + }, + ) + + transport = httpx.MockTransport(handler) + async with httpx.AsyncClient(transport=transport) as client: + backend = JevHttpBackend("http://jev.local/predict", client=client) + dist = await backend.predict( + DecisionQuery( + task="root_component", + prompt="p", + candidates=("ValidCard", "InvalidCard"), + ) + ) + assert dist.probabilities == { + "ValidCard": pytest.approx(0.75), + "InvalidCard": pytest.approx(0.0), + } + + +def test_local_cross_encoder_satisfies_protocol() -> None: + backend = LocalCrossEncoderBackend(temperature=1.0) + assert isinstance(backend, DecisionBackend) + with pytest.raises(ValueError, match="temperature"): + LocalCrossEncoderBackend(temperature=0.0) + with pytest.raises(ValueError, match="temperature"): + LocalCrossEncoderBackend(temperature=-1.0) + + +@pytest.mark.asyncio +async def test_local_cross_encoder_missing_dependencies( + monkeypatch: pytest.MonkeyPatch, +) -> None: + import builtins + + real_import = builtins.__import__ + + def fake_import(name: str, *args: Any, **kwargs: Any) -> Any: + if name in ("onnxruntime", "tokenizers", "huggingface_hub"): + raise ImportError(f"No module named '{name}'") + return real_import(name, *args, **kwargs) + + monkeypatch.setattr(builtins, "__import__", fake_import) + backend = LocalCrossEncoderBackend() + with pytest.raises(ImportError, match="decision-local"): + await backend.predict( + DecisionQuery(task="t", prompt="p", candidates=("A", "B")) + ) + + +@pytest.mark.asyncio +async def test_local_cross_encoder_empty_and_single_candidate() -> None: + backend = LocalCrossEncoderBackend() + dist_empty = await backend.predict( + DecisionQuery(task="t", prompt="p", candidates=()) + ) + assert dist_empty.probabilities == {} + assert dist_empty.top_logit_margin == 0.0 + + dist_single = await backend.predict( + DecisionQuery(task="t", prompt="p", candidates=("OnlyOne",)) + ) + assert dist_single.probabilities == {"OnlyOne": 1.0} + assert math.isinf(dist_single.top_logit_margin or 0.0) + + +@dataclass +class _FakeEncoding: + ids: list[int] + attention_mask: list[int] + type_ids: list[int] + + +class _FakeTokenizer: + + def __init__(self) -> None: + self.captured_pairs: list[tuple[str, str]] = [] + + def encode_batch(self, pairs: list[tuple[str, str]]) -> list[_FakeEncoding]: + self.captured_pairs = pairs + return [ + _FakeEncoding(ids=[101, 102], attention_mask=[1, 1], type_ids=[0, 0]) + for _ in pairs + ] + + +class _FakeSessionInput: + + def __init__(self, name: str) -> None: + self.name = name + + +class _FakeSession: + + def __init__(self, logits: list[float]) -> None: + self.logits = logits + self.captured_feeds: list[dict[str, Any]] = [] + + def get_inputs(self) -> list[_FakeSessionInput]: + return [ + _FakeSessionInput("input_ids"), + _FakeSessionInput("attention_mask"), + _FakeSessionInput("token_type_ids"), + ] + + def run(self, output_names: Any, feeds: dict[str, Any]) -> list[Any]: + del output_names + self.captured_feeds.append(feeds) + import numpy as np + + return [np.array(self.logits, dtype=np.float32)[:, np.newaxis]] + + +@pytest.mark.asyncio +async def test_local_cross_encoder_scoring_and_context_formatting() -> None: + tok = _FakeTokenizer() + sess = _FakeSession(logits=[2.0, 0.0]) + backend = LocalCrossEncoderBackend(session=sess, tokenizer=tok, temperature=1.0) + + query = DecisionQuery( + task="child_component", + prompt="Show task progress", + candidates=("ProgressBar", "Collapsible"), + context={ + "parent": "Card", + "parent_description": "Card container", + "slot": "body", + "slot_description": "Main body child slot", + "pointers": ["/progress/percent"], + "candidate_descriptions": { + "ProgressBar": "Visual progress meter with percentage", + "Collapsible": "Expandable section", + }, + }, + ) + + dist = await backend.predict(query) + assert len(tok.captured_pairs) == 2 + query_text, passage_0 = tok.captured_pairs[0] + _, passage_1 = tok.captured_pairs[1] + + assert "Show task progress" in query_text + assert ( + "Selecting child component for Card container, slot Main body child slot" + in query_text + ) + assert "Available data fields: /progress/percent" in query_text + assert passage_0 == "ProgressBar: Visual progress meter with percentage" + assert passage_1 == "Collapsible: Expandable section" + + assert dist.calibrated is True + assert dist.top_logit_margin == pytest.approx(2.0) + expected_prob = math.exp(2.0) / (math.exp(2.0) + math.exp(0.0)) + assert dist.probabilities["ProgressBar"] == pytest.approx(expected_prob) + assert dist.probabilities["Collapsible"] == pytest.approx(1.0 - expected_prob) + + +def test_decision_module_lazy_import_isolation() -> None: + """Verifies that importing a2ui.inference_formats.decision does not eagerly import ONNX or tokenizers.""" + import a2ui.inference_formats.decision as decision_mod + + assert hasattr(decision_mod, "LocalCrossEncoderBackend") + assert "onnxruntime" not in sys.modules + assert "tokenizers" not in sys.modules + + +@pytest.mark.asyncio +async def test_jev_http_backend_systemone_auto_detection_and_payload() -> None: + captured_requests: list[dict[str, Any]] = [] + captured_headers: list[dict[str, str]] = [] + + def handler(request: httpx.Request) -> httpx.Response: + captured_requests.append(json.loads(request.content.decode("utf-8"))) + captured_headers.append(dict(request.headers)) + return httpx.Response( + 200, + json={ + "answers": { + "q": { + "probabilities": { + "CardA": 0.8, + "CardB": 0.2, + }, + "confidence": 0.8, + } + } + }, + ) + + transport = httpx.MockTransport(handler) + async with httpx.AsyncClient(transport=transport) as client: + backend = JevHttpBackend( + "https://api.example.com/v1/systemone", + model="decisiongemma", + auth="secret-bearer-token", + client=client, + ) + query = DecisionQuery( + task="child_component", + prompt="Render telemetry metric", + candidates=("CardA", "CardB"), + context={ + "parent_description": "TelemetryGrid", + "slot_description": "metrics slot", + "pointers": ["/cpu"], + "candidate_descriptions": { + "CardA": "Card displaying metric", + "CardB": "Card displaying chart", + }, + }, + ) + dist = await backend.predict(query) + + assert len(captured_requests) == 1 + req = captured_requests[0] + assert req["model"] == "decisiongemma" + assert "User intent: Render telemetry metric" in req["state"] + assert "Parent container: TelemetryGrid. Slot: metrics slot" in req["state"] + assert "Payload data fields: /cpu" in req["state"] + assert req["questions"]["q"]["criteria"]["CardA"] == "Card displaying metric" + assert req["questions"]["q"]["criteria"]["CardB"] == "Card displaying chart" + + assert captured_headers[0]["authorization"] == "Bearer secret-bearer-token" + assert dist.calibrated is True + assert dist.probabilities["CardA"] == pytest.approx(0.8) + assert dist.probabilities["CardB"] == pytest.approx(0.2) + assert dist.top_logit_margin == pytest.approx(math.log(0.8 / 0.2)) + + +@pytest.mark.asyncio +async def test_jev_http_backend_auth_callable_and_adc( + monkeypatch: pytest.MonkeyPatch, +) -> None: + captured_headers: list[dict[str, str]] = [] + + def handler(request: httpx.Request) -> httpx.Response: + captured_headers.append(dict(request.headers)) + return httpx.Response(200, json={"probabilities": {"A": 1.0}}) + + transport = httpx.MockTransport(handler) + async with httpx.AsyncClient(transport=transport) as client: + # 1. Callable auth + callable_backend = JevHttpBackend( + "http://local/predict", + auth=lambda: "callable-token", + client=client, + ) + await callable_backend.predict( + DecisionQuery(task="t", prompt="p", candidates=("A",)) + ) + assert captured_headers[-1]["authorization"] == "Bearer callable-token" + + # 2. ADC auth mock: the token cache lives on the backend instance, so a + # fresh instance starts without a cached token. + from a2ui.inference_formats.decision import backends + + adc_calls: list[int] = [] + + def fake_adc_token() -> str: + adc_calls.append(1) + return "mocked-adc-token" + + monkeypatch.setattr(backends, "_get_adc_token_sync", fake_adc_token) + + adc_backend = JevHttpBackend( + "http://local/predict", + auth="adc", + client=client, + ) + await adc_backend.predict( + DecisionQuery(task="t", prompt="p", candidates=("A",)) + ) + assert captured_headers[-1]["authorization"] == "Bearer mocked-adc-token" + + # A second predict on the same instance reuses the cached token. + await adc_backend.predict( + DecisionQuery(task="t", prompt="p", candidates=("A",)) + ) + assert len(adc_calls) == 1 + + # A different instance does not share the cache. + other_backend = JevHttpBackend( + "http://local/predict", auth="adc", client=client + ) + await other_backend.predict( + DecisionQuery(task="t", prompt="p", candidates=("A",)) + ) + assert len(adc_calls) == 2 + + +@pytest.mark.asyncio +async def test_jev_http_backend_systemone_empty_and_fallback() -> None: + def handler(request: httpx.Request) -> httpx.Response: + del request + return httpx.Response(200, json={"answers": {}}) + + transport = httpx.MockTransport(handler) + async with httpx.AsyncClient(transport=transport) as client: + backend = JevHttpBackend( + "http://local/v1/systemone", + client=client, + ) + dist = await backend.predict( + DecisionQuery(task="t", prompt="p", candidates=("A", "B")) + ) + assert dist.probabilities == {"A": 0.0, "B": 0.0} + assert dist.top_logit_margin == 0.0 + + +def test_create_decision_backend_mock_and_local( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # 1. Explicit mock + b_mock = create_decision_backend("mock") + assert isinstance(b_mock, DeterministicMockBackend) + + # 2. Env mock + monkeypatch.setenv("A2UI_DECISION_BACKEND", "mock") + b_env_mock = create_decision_backend() + assert isinstance(b_env_mock, DeterministicMockBackend) + + # 3. Explicit local + b_local = create_decision_backend("local", model="test-model", temperature=0.7) + assert isinstance(b_local, LocalCrossEncoderBackend) + assert b_local.model_id == "test-model" + assert b_local.temperature == 0.7 + + # 4. Unknown type + with pytest.raises(ValueError, match="Unknown decision backend type"): + create_decision_backend("unknown_kind") + + +def test_create_decision_backend_auto_inference_and_http( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # 1. URL ending in /v1/systemone auto-infers systemone + monkeypatch.delenv("A2UI_DECISION_BACKEND", raising=False) + monkeypatch.delenv("A2UI_DECISION_AUTH", raising=False) + monkeypatch.delenv("A2UI_DECISION_TOKEN", raising=False) + monkeypatch.delenv("JEV_API_KEY", raising=False) + monkeypatch.delenv("TYPESAFE_API_KEY", raising=False) + b_sys1 = create_decision_backend( + endpoint_url="https://api.example.com/v1/systemone", model="gemma" + ) + assert isinstance(b_sys1, JevHttpBackend) + assert b_sys1._wire_format == "systemone" + assert b_sys1.model == "gemma" + assert b_sys1.endpoint_url == "https://api.example.com/v1/systemone" + + # 2. URL ending in /v1/completions auto-infers step0 + b_step0 = create_decision_backend( + endpoint_url="http://localhost:8000/v1/completions", + model="gemma-step0", + ) + assert isinstance(b_step0, StepZeroLogprobBackend) + assert b_step0._model == "gemma-step0" + + # 3. Generic URL auto-infers jev + b_jev = create_decision_backend(endpoint_url="http://localhost:8080/predict") + assert isinstance(b_jev, JevHttpBackend) + assert b_jev._wire_format == "jev" + + # 4. HTTP backends without URL or JEV_API_KEY raise ValueError + with pytest.raises(ValueError, match="requires an endpoint URL"): + create_decision_backend("systemone") + with pytest.raises(ValueError, match="requires an endpoint URL"): + create_decision_backend("jev") + with pytest.raises(ValueError, match="requires an endpoint URL"): + create_decision_backend("step0") + + # 5. JEV_API_KEY auto-configures TypeSafe /v1/systemone or Vercel AI Gateway /typesafe/v1/systemone + monkeypatch.setenv("JEV_API_KEY", "ts-test-key") + b_typesafe = create_decision_backend("jev") + assert isinstance(b_typesafe, JevHttpBackend) + assert b_typesafe.endpoint_url == "https://api.typesafe.ai/v1/systemone" + assert b_typesafe.model == "jev-latest" + + monkeypatch.setenv("JEV_API_KEY", "vcp_vercel_gateway_key") + b_vercel = create_decision_backend("jev") + assert isinstance(b_vercel, JevHttpBackend) + assert b_vercel.endpoint_url == "https://ai-gateway.vercel.sh/typesafe/v1/systemone" + assert b_vercel.model == "jev" + + +def test_decision_synthesizer_from_env( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from a2ui.core import Catalog + from a2ui.inference_formats.decision import DecisionSynthesizer + + monkeypatch.setenv("A2UI_DECISION_BACKEND", "mock") + cat = Catalog.from_json({ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "catalogId": "https://example.com/cat", + "protocolVersion": "1.0", + "components": { + "Card": { + "type": "object", + "properties": {"component": {"const": "Card"}}, + "required": ["component"], + } + }, + }) + synth = DecisionSynthesizer.from_env([cat]) + assert isinstance(synth.backend, DeterministicMockBackend) + + +@pytest.mark.asyncio +async def test_non_finite_weights_adc_lock_and_off_thread_ensure_loaded( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Verifies M1 (_ensure_loaded off event loop), M4 (non-finite weight rejection), and M9 (ADC lock).""" + import asyncio + import threading + from a2ui.inference_formats.decision import backends + + # M4: "inf" and NaN weights are treated as 0.0 instead of producing NaN probabilities. + norm = backends._normalize_probabilities( + {"A": "inf", "B": float("nan"), "C": 2.0}, ("A", "B", "C") + ) + assert norm == {"A": 0.0, "B": 0.0, "C": 1.0} + assert all(math.isfinite(v) for v in norm.values()) + + # M9: Concurrent ADC requests only refresh the token once. + adc_call_count = 0 + + def slow_adc_token() -> str: + nonlocal adc_call_count + import time + + time.sleep(0.02) + adc_call_count += 1 + return "concurrent-adc-token" + + monkeypatch.setattr(backends, "_get_adc_token_sync", slow_adc_token) + transport = httpx.MockTransport( + lambda req: httpx.Response(200, json={"probabilities": {"A": 1.0}}) + ) + async with httpx.AsyncClient(transport=transport) as client: + jev = JevHttpBackend("http://local/predict", auth="adc", client=client) + q = DecisionQuery(task="t", prompt="p", candidates=("A",)) + await asyncio.gather(jev.predict(q), jev.predict(q), jev.predict(q)) + assert adc_call_count == 1 + + # M1: LocalCrossEncoderBackend._ensure_loaded runs in a worker thread, not on the event loop thread. + main_tid = threading.get_ident() + seen_tids: list[int] = [] + tok = _FakeTokenizer() + sess = _FakeSession(logits=[1.0, 0.0]) + local = LocalCrossEncoderBackend(session=sess, tokenizer=tok) + orig_ensure = local._ensure_loaded + + def recording_ensure() -> tuple[Any, Any]: + seen_tids.append(threading.get_ident()) + return orig_ensure() + + monkeypatch.setattr(local, "_ensure_loaded", recording_ensure) + await local.predict(DecisionQuery(task="t", prompt="p", candidates=("A", "B"))) + assert len(seen_tids) == 1 + assert seen_tids[0] != main_tid + + +@pytest.mark.asyncio +async def test_mock_backend_scripted_answers_and_batches_recording() -> None: + from a2ui.inference_formats.decision.models import ( + DecisionAnswer, + DecisionBatch, + DecisionQuestion, + QuestionKind, + ) + + q_choice = DecisionQuestion( + id="family", + kind=QuestionKind.CHOICE, + prompt="Browse or inspect?", + options=("browse", "inspect"), + ) + q_bool = DecisionQuestion( + id="gate:picture", + kind=QuestionKind.BOOLEAN, + prompt="Show a picture?", + context={"yes": "Visual item.", "no": "Plain text."}, + ) + q_score = DecisionQuestion( + id="stakes", + kind=QuestionKind.SCORE, + prompt="How high are the stakes?", + options=("low", "medium", "high", "critical"), + ) + q_explicit = DecisionQuestion( + id="anatomy:layout", + kind=QuestionKind.CHOICE, + prompt="Choose layout", + options=("rows", "cards"), + allow_none=False, + ) + q_unscripted_bool = DecisionQuestion( + id="gate:facts", + kind=QuestionKind.BOOLEAN, + prompt="Include facts?", + ) + q_unscripted_score = DecisionQuestion( + id="urgency", + kind=QuestionKind.SCORE, + prompt="How urgent?", + options=("none", "soon", "now", "immediate"), + ) + + explicit_ans = DecisionAnswer( + question_id="anatomy:layout", + distribution=DecisionDistribution({"rows": 0.15, "cards": 0.85}), + ) + backend = DeterministicMockBackend( + scripted={"family": {"browse": 0.9, "inspect": 0.1, "none": 0.0}}, + scripted_answers={ + "family": "inspect", + "gate:picture": 0.85, + "stakes": 2.4, + "anatomy:layout": explicit_ans, + }, + ) + batch = DecisionBatch( + shared_context={"intent": "Inspect the resort"}, + questions=( + q_choice, + q_bool, + q_score, + q_explicit, + q_unscripted_bool, + q_unscripted_score, + ), + ) + answers = await backend.answer(batch) + + assert backend.batches == [batch] + # scripted_answers wins over scripted when both match + assert answers[0].top() == ("inspect", pytest.approx(0.9)) + assert answers[1].yes == pytest.approx(0.85) + assert answers[2].expected == pytest.approx(2.4) + assert answers[3] == explicit_ans + # Unscripted boolean defaults to 0.5 and unscripted score to midpoint 1.5 + assert answers[4].yes == pytest.approx(0.5) + assert answers[5].expected == pytest.approx(1.5) + + +@pytest.mark.asyncio +async def test_step_zero_logprob_backend_single_char_labels_batch_and_over_10_error() -> ( + None +): + from a2ui.core import A2uiValidationError + from a2ui.inference_formats.decision.models import ( + DecisionBatch, + DecisionQuestion, + QuestionKind, + ) + + captured_prompts: list[str] = [] + + def handler(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content.decode("utf-8")) + captured_prompts.append(body["prompt"]) + return httpx.Response( + 200, + json={ + "choices": [{ + "logprobs": { + "top_logprobs": [{ + " A": -2.0, + " B": -0.2, + " C": -4.0, + }] + } + }] + }, + ) + + transport = httpx.MockTransport(handler) + async with httpx.AsyncClient(transport=transport) as client: + backend = StepZeroLogprobBackend( + "http://vllm.local/v1/completions", + "gemma-step0", + temperature=1.0, + client=client, + ) + + # 1. Single-char label mapping on predict + dist = await backend.predict( + DecisionQuery( + task="family", + prompt="Pick family", + candidates=("browse", "inspect", "monitor"), + ) + ) + assert dist.top_choice()[0] == "inspect" + assert "Candidates: [A: browse, B: inspect, C: monitor]" in captured_prompts[0] + + # 2. >10 options raises A2uiValidationError on both predict and answer + eleven_opts = tuple(f"opt_{i}" for i in range(11)) + with pytest.raises(A2uiValidationError, match="at most 10"): + await backend.predict( + DecisionQuery(task="t", prompt="p", candidates=eleven_opts) + ) + with pytest.raises(A2uiValidationError, match="at most 10"): + await backend.answer( + DecisionBatch( + shared_context={}, + questions=( + DecisionQuestion( + id="too_many", + kind=QuestionKind.CHOICE, + prompt="?", + options=eleven_opts, + allow_none=False, + ), + ), + ) + ) + + # 3. answer() issues concurrent requests with one shared prefix string + captured_prompts.clear() + q1 = DecisionQuestion( + id="family", + kind=QuestionKind.CHOICE, + prompt="What job?", + options=("browse", "inspect"), + ) + q2 = DecisionQuestion( + id="gate:picture", + kind=QuestionKind.BOOLEAN, + prompt="Show picture?", + ) + answers = await backend.answer( + DecisionBatch( + shared_context={"intent": "Show resort"}, + questions=(q1, q2), + ) + ) + assert len(answers) == 2 + assert len(captured_prompts) == 2 + first_line_0 = captured_prompts[0].splitlines()[0] + first_line_1 = captured_prompts[1].splitlines()[0] + assert first_line_0 == first_line_1 + assert first_line_0.startswith("Shared context:") + assert answers[0].top()[0] == "inspect" + # "B" is "no" for boolean ("yes", "no") so "yes" is lower than "no" + assert answers[1].yes < 0.5 + + +@pytest.mark.asyncio +async def test_jev_http_backend_answer_native_and_systemone() -> None: + from a2ui.inference_formats.decision.models import ( + DecisionBatch, + DecisionQuestion, + QuestionKind, + ) + + native_requests: list[dict[str, Any]] = [] + + def native_handler(request: httpx.Request) -> httpx.Response: + native_requests.append(json.loads(request.content.decode("utf-8"))) + return httpx.Response( + 200, + json={ + "calibrated": True, + "answers": { + "family": { + "probabilities": { + "browse": 0.1, + "inspect": 0.8, + "none": 0.1, + } + }, + "gate:picture": {"probabilities": {"yes": 0.9, "no": 0.1}}, + "stakes": { + "probabilities": { + "low": 0.0, + "medium": 0.5, + "high": 0.5, + } + }, + }, + }, + ) + + batch = DecisionBatch( + shared_context={"intent": "Show overview"}, + questions=( + DecisionQuestion( + id="family", + kind=QuestionKind.CHOICE, + prompt="Family?", + options=("browse", "inspect"), + ), + DecisionQuestion( + id="gate:picture", + kind=QuestionKind.BOOLEAN, + prompt="Picture?", + ), + DecisionQuestion( + id="stakes", + kind=QuestionKind.SCORE, + prompt="Stakes?", + options=("low", "medium", "high"), + ), + ), + ) + + async with httpx.AsyncClient( + transport=httpx.MockTransport(native_handler) + ) as client: + jev_native = JevHttpBackend("http://jev.local/predict", client=client) + native_answers = await jev_native.answer(batch) + + assert len(native_requests) == 1 + assert native_requests[0]["shared_context"] == {"intent": "Show overview"} + assert [q["id"] for q in native_requests[0]["questions"]] == [ + "family", + "gate:picture", + "stakes", + ] + assert [q["kind"] for q in native_requests[0]["questions"]] == [ + "choice", + "boolean", + "score", + ] + assert native_answers[0].top() == ("inspect", pytest.approx(0.8)) + assert native_answers[1].yes == pytest.approx(0.9) + assert native_answers[2].expected == pytest.approx(1.5) + + # systemone sends one batched /v1/systemone request with choice, noul, and score + sys1_requests: list[dict[str, Any]] = [] + + def sys1_handler(request: httpx.Request) -> httpx.Response: + sys1_requests.append(json.loads(request.content.decode("utf-8"))) + return httpx.Response( + 200, + json={ + "model": "vertex/decision-gemma", + "answers": { + "family": { + "type": "choice", + "choice": "inspect", + "probabilities": { + "browse": 0.2, + "inspect": 0.8, + "none": 0.0, + }, + "confidence": 0.8, + }, + "gate:picture": { + "type": "noul", + "noul": 0.75, + }, + "stakes": { + "type": "score", + "score": 0.5, + "legend": {"0": "low", "1": "medium", "2": "high"}, + "probabilities": { + "0": 0.5, + "1": 0.5, + "2": 0.0, + }, + "confidence": 0.8, + }, + }, + }, + ) + + async with httpx.AsyncClient(transport=httpx.MockTransport(sys1_handler)) as client: + jev_sys1 = JevHttpBackend( + "https://api.example.com/v1/systemone", + model="vertex/decision-gemma", + client=client, + ) + sys1_answers = await jev_sys1.answer(batch) + + assert len(sys1_requests) == 1 + assert sys1_requests[0]["model"] == "vertex/decision-gemma" + assert sys1_requests[0]["state"] == "User intent: Show overview" + assert sys1_requests[0]["questions"]["family"]["type"] == "choice" + assert sys1_requests[0]["questions"]["gate:picture"]["type"] == "noul" + assert sys1_requests[0]["questions"]["stakes"] == { + "type": "score", + "instructions": "Stakes?", + "criteria": ["low", "medium", "high"], + } + assert sys1_answers[0].top() == ("inspect", pytest.approx(0.8)) + assert sys1_answers[1].yes == pytest.approx(0.75) + assert sys1_answers[2].expected == pytest.approx(0.5) + + +@pytest.mark.asyncio +async def test_local_cross_encoder_answer_batches_and_chunks_pairs() -> None: + import numpy as np + from a2ui.inference_formats.decision.models import ( + DecisionBatch, + DecisionQuestion, + QuestionKind, + ) + + class _ChunkingFakeTokenizer: + + def __init__(self) -> None: + self.call_sizes: list[int] = [] + self.all_pairs: list[tuple[str, str]] = [] + + def encode_batch(self, pairs: list[tuple[str, str]]) -> list[_FakeEncoding]: + self.call_sizes.append(len(pairs)) + self.all_pairs.extend(pairs) + return [ + _FakeEncoding(ids=[101, 102], attention_mask=[1, 1], type_ids=[0, 0]) + for _ in pairs + ] + + class _DynamicFakeSession: + + def __init__(self, logits: list[float]) -> None: + self._logits = logits + self._offset = 0 + self.run_count = 0 + + def get_inputs(self) -> list[_FakeSessionInput]: + return [ + _FakeSessionInput("input_ids"), + _FakeSessionInput("attention_mask"), + ] + + def run(self, output_names: Any, feeds: dict[str, Any]) -> list[Any]: + del output_names + self.run_count += 1 + batch_len = len(feeds["input_ids"]) + chunk = self._logits[self._offset : self._offset + batch_len] + self._offset += batch_len + return [np.array(chunk, dtype=np.float32)[:, np.newaxis]] + + batch = DecisionBatch( + shared_context={"pointers": ["/name", "/rating"]}, + questions=( + DecisionQuestion( + id="family", + kind=QuestionKind.CHOICE, + prompt="What is the job?", + options=("browse", "inspect"), + option_texts=("Browse items", "Inspect one item"), + ), + DecisionQuestion( + id="gate:picture", + kind=QuestionKind.BOOLEAN, + prompt="Include a hero image?", + context={"yes": "Has a clear photo", "no": "Text only"}, + ), + DecisionQuestion( + id="stakes", + kind=QuestionKind.SCORE, + prompt="How high are the stakes?", + options=("low", "medium", "high"), + ), + ), + ) + # 3 candidates (browse, inspect, none) + 2 (yes, no) + 3 (low, medium, high) = 8 pairs + logits = [0.0, 3.0, -1.0, 2.0, 0.0, -2.0, 0.0, 2.0] + + tok = _ChunkingFakeTokenizer() + sess = _DynamicFakeSession(logits) + backend = LocalCrossEncoderBackend(session=sess, tokenizer=tok, max_batch_pairs=256) + answers = await backend.answer(batch) + + assert sess.run_count == 1 + assert tok.call_sizes == [8] + assert len(tok.all_pairs) == 8 + assert "yes: Has a clear photo" in tok.all_pairs[3][1] + assert "no: Text only" in tok.all_pairs[4][1] + assert answers[0].top()[0] == "inspect" + assert answers[1].yes > 0.85 + assert answers[2].expected is not None and answers[2].expected > 1.5 + + # Verify chunking when max_batch_pairs=3 (8 pairs -> encoded once, session called in chunks of 3, 3, 2) + tok_chunked = _ChunkingFakeTokenizer() + sess_chunked = _DynamicFakeSession(logits) + chunked_backend = LocalCrossEncoderBackend( + session=sess_chunked, tokenizer=tok_chunked, max_batch_pairs=3 + ) + chunked_answers = await chunked_backend.answer(batch) + assert sess_chunked.run_count == 3 + assert tok_chunked.call_sizes == [8] + assert [a.top() for a in chunked_answers] == [a.top() for a in answers] + + +@pytest.mark.asyncio +async def test_batching_decision_backend_coalesces_20_predicts_and_isolates_failure() -> ( + None +): + import asyncio + from a2ui.inference_formats.decision.batching import ( + BatchingDecisionBackend, + ) + from a2ui.inference_formats.decision.models import ( + DecisionAnswer, + DecisionBatch, + ) + + inner = DeterministicMockBackend() + async with BatchingDecisionBackend(inner, window_ms=2.0) as batcher: + queries = [ + DecisionQuery( + task="root_component", + prompt=f"Render component {i} with Target_{i}", + candidates=(f"Target_{i}", f"Other_{i}"), + ) + for i in range(20) + ] + results = await asyncio.gather(*(batcher.predict(q) for q in queries)) + + assert len(inner.batches) == 1 + assert len(inner.batches[0].questions) == 20 + for idx, dist in enumerate(results): + top_cand, _ = dist.top_choice() + assert top_cand == f"Target_{idx}" + + # Verify one failing call propagates its exception without poisoning the other 19 + class _SelectiveFailBackend(DeterministicMockBackend): + + async def answer(self, batch: DecisionBatch) -> tuple[DecisionAnswer, ...]: + for q in batch.questions: + if "POISON" in q.prompt: + raise RuntimeError(f"failed on {q.id}") + return await super().answer(batch) + + selective_inner = _SelectiveFailBackend() + async with BatchingDecisionBackend(selective_inner, window_ms=2.0) as batcher: + mixed_queries = [ + DecisionQuery( + task="root_component", + prompt="POISON query" if i == 7 else f"Valid query Target_{i}", + candidates=(f"Target_{i}", f"Other_{i}"), + ) + for i in range(20) + ] + outcomes = await asyncio.gather( + *(batcher.predict(q) for q in mixed_queries), + return_exceptions=True, + ) + + assert isinstance(outcomes[7], RuntimeError) + for idx, item in enumerate(outcomes): + if idx == 7: + continue + assert isinstance(item, DecisionDistribution) + assert item.top_choice()[0] == f"Target_{idx}" + + # H1: truncated answer tuple raises ValueError on all chunk futures instead of hanging + class _TruncatedAnswerBackend(DeterministicMockBackend): + + async def answer(self, batch: DecisionBatch) -> tuple[DecisionAnswer, ...]: + full = await super().answer(batch) + return full[:-1] + + trunc_inner = _TruncatedAnswerBackend() + async with BatchingDecisionBackend(trunc_inner, window_ms=2.0) as batcher: + with pytest.raises(ValueError, match="Expected .* answers from backend"): + await asyncio.gather( + batcher.predict( + DecisionQuery(task="t", prompt="q1", candidates=("A", "B")) + ), + batcher.predict( + DecisionQuery(task="t", prompt="q2", candidates=("A", "B")) + ), + ) + await batcher.aclose_current_loop() + + +@pytest.mark.asyncio +async def test_local_cross_encoder_sorting_and_padding_width() -> None: + import numpy as np + + class _DistinctTokenFakeTokenizer: + + def __init__(self, lengths: list[int]) -> None: + self._lengths = lengths + + def encode_batch(self, pairs: list[tuple[str, str]]) -> list[_FakeEncoding]: + return [ + _FakeEncoding( + ids=[i * 1000] + list(range(1, self._lengths[i])), + attention_mask=[1] * self._lengths[i], + type_ids=[0] * self._lengths[i], + ) + for i in range(len(pairs)) + ] + + class _InspectingFakeSession: + + def __init__(self, logits_by_input_id: dict[int, float]) -> None: + self._logits_by_input_id = logits_by_input_id + self.chunk_padding_widths: list[int] = [] + self.chunk_sizes: list[int] = [] + + def get_inputs(self) -> list[_FakeSessionInput]: + return [ + _FakeSessionInput("input_ids"), + _FakeSessionInput("attention_mask"), + ] + + def run(self, output_names: Any, feeds: dict[str, Any]) -> list[Any]: + del output_names + input_ids = feeds["input_ids"] + self.chunk_padding_widths.append(input_ids.shape[1]) + self.chunk_sizes.append(input_ids.shape[0]) + chunk_logits = [ + self._logits_by_input_id.get(int(row[0]), 0.0) for row in input_ids + ] + return [np.array(chunk_logits, dtype=np.float32)[:, np.newaxis]] + + lengths = [5, 2, 8, 3] + logits_map = {0: 10.0, 1000: 20.0, 2000: 30.0, 3000: 40.0} + tok = _DistinctTokenFakeTokenizer(lengths) + sess = _InspectingFakeSession(logits_map) + + backend = LocalCrossEncoderBackend(session=sess, tokenizer=tok, max_batch_pairs=2) + pairs = [("q", f"p_{i}") for i in range(4)] + logits = backend._score_pairs_sync(pairs) + + # Logits come back in original input order after sorting + assert logits == [10.0, 20.0, 30.0, 40.0] + + # Pairs sorted by length: index 1 (len 2), index 3 (len 3) -> chunk 1 max len 3 + # Index 0 (len 5), index 2 (len 8) -> chunk 2 max len 8 + assert sess.chunk_sizes == [2, 2] + assert sess.chunk_padding_widths == [3, 8] + + +def test_local_cross_encoder_threads_and_cpu_count( + monkeypatch: pytest.MonkeyPatch, +) -> None: + import os + from unittest.mock import MagicMock + + fake_ort = MagicMock() + fake_tokenizer_mod = MagicMock() + fake_hf = MagicMock() + + class _CaptureSessionOptions: + + def __init__(self) -> None: + self.intra_op_num_threads = -1 + self.inter_op_num_threads = -1 + self.graph_optimization_level = None + + fake_ort.SessionOptions = _CaptureSessionOptions + fake_ort.InferenceSession = MagicMock() + fake_hf.hf_hub_download = MagicMock(return_value="/fake/path") + fake_tokenizer_inst = MagicMock() + fake_tokenizer_mod.Tokenizer.from_file = MagicMock(return_value=fake_tokenizer_inst) + + monkeypatch.setattr( + "sys.modules", + { + **sys.modules, + "onnxruntime": fake_ort, + "tokenizers": fake_tokenizer_mod, + "huggingface_hub": fake_hf, + }, + ) + + # threads=None resolves to CPU count + backend = LocalCrossEncoderBackend(threads=None) + backend._ensure_loaded() + expected_cpu = max(1, os.cpu_count() or 1) + opts = fake_ort.InferenceSession.call_args[0][1] + assert opts.intra_op_num_threads == expected_cpu + + # threads=4 explicitly + backend4 = LocalCrossEncoderBackend(threads=4) + backend4._ensure_loaded() + opts4 = fake_ort.InferenceSession.call_args[0][1] + assert opts4.intra_op_num_threads == 4 + + # Validation + with pytest.raises(ValueError, match="threads must be >= 1"): + LocalCrossEncoderBackend(threads=0) + with pytest.raises(ValueError, match="threads must be >= 1"): + LocalCrossEncoderBackend(threads=-2) + + +def test_local_cross_encoder_max_seq_and_summary_pointers() -> None: + with pytest.raises(ValueError, match="max_seq_length must be >= 32"): + LocalCrossEncoderBackend(max_seq_length=16) + with pytest.raises(ValueError, match="max_summary_pointers must be >= 1"): + LocalCrossEncoderBackend(max_summary_pointers=0) + + from a2ui.inference_formats.decision.backends import ( + _format_query_passage_pairs, + ) + + query = DecisionQuery( + task="root_component", + prompt="Display host status", + candidates=("HostCard", "none"), + context={ + "pointers": [f"/field_{i}" for i in range(60)], + "candidate_descriptions": {"HostCard": "A" * 300}, + }, + ) + query_text, passages = _format_query_passage_pairs( + query, max_summary_pointers=12, max_option_chars=240 + ) + assert "/field_11" in query_text + assert "/field_12" not in query_text + assert len(passages[0]) == len("HostCard: ") + 240 + + +def test_create_decision_backend_env_knobs( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("A2UI_DECISION_THREADS", "6") + monkeypatch.setenv("A2UI_DECISION_MAX_SEQ", "128") + b = create_decision_backend("local") + assert isinstance(b, LocalCrossEncoderBackend) + assert b.threads == 6 + assert b.max_seq_length == 128 + + monkeypatch.setenv("A2UI_DECISION_THREADS", "0") + with pytest.raises(ValueError, match="positive"): + create_decision_backend("local") + + monkeypatch.setenv("A2UI_DECISION_THREADS", "invalid") + with pytest.raises(ValueError, match="integer"): + create_decision_backend("local") + + monkeypatch.setenv("A2UI_DECISION_THREADS", "4") + monkeypatch.setenv("A2UI_DECISION_MAX_SEQ", "16") + with pytest.raises(ValueError, match="max_seq_length must be >= 32"): + create_decision_backend("local") + + +@pytest.mark.asyncio +async def test_step_zero_chat_completions_and_bearer_auth() -> None: + """`StepZeroLogprobBackend` supports `/v1/chat/completions` and Bearer auth.""" + captured_headers: list[dict[str, str]] = [] + captured_bodies: list[dict[str, Any]] = [] + + def handler(request: httpx.Request) -> httpx.Response: + captured_headers.append(dict(request.headers)) + captured_bodies.append(json.loads(request.content.decode("utf-8"))) + return httpx.Response( + 200, + json={ + "choices": [{ + "logprobs": { + "content": [{ + "token": "B", + "logprob": -0.05, + "top_logprobs": [ + {"token": "B", "logprob": -0.05}, + {"token": "A", "logprob": -3.10}, + ], + }] + } + }] + }, + ) + + transport = httpx.MockTransport(handler) + async with httpx.AsyncClient(transport=transport) as client: + backend = StepZeroLogprobBackend( + "https://api.openai.com/v1/chat/completions", + "gpt-4o-mini", + auth="sk-test-123", + client=client, + ) + dist = await backend.predict( + DecisionQuery( + task="family", + prompt="What is the user trying to do?", + candidates=("browse", "monitor", "inspect"), + ) + ) + assert captured_headers[0].get("authorization") == "Bearer sk-test-123" + assert captured_bodies[0]["logprobs"] is True + assert captured_bodies[0]["top_logprobs"] == 5 + assert "messages" in captured_bodies[0] + assert dist.top_choice()[0] == "monitor" diff --git a/python/a2ui_agent/tests/decision/test_calibration.py b/python/a2ui_agent/tests/decision/test_calibration.py new file mode 100644 index 0000000000..8b930705ed --- /dev/null +++ b/python/a2ui_agent/tests/decision/test_calibration.py @@ -0,0 +1,407 @@ +# 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. + +"""Unit tests for decision-model confidence threshold calibration.""" + +from __future__ import annotations + +from collections.abc import Collection, Mapping +from typing import Any + +import pytest + +from a2ui.inference_formats.decision import ( + LabeledDecisionExample, + SurfaceTemplate, + SynthesisConfig, + SynthesisOutput, + SynthesisStage, + SynthesizerLike, + TemplateRegistry, + calibrate_thresholds, + compute_bayes_optimal_threshold, +) + + +class _FakeSynthesizer: + """Lightweight fake implementing SynthesizerLike for calibration tests.""" + + def __init__(self, scripted_outputs: Mapping[str, SynthesisOutput]) -> None: + self.config = SynthesisConfig() + self._scripted = dict(scripted_outputs) + self.calls: list[tuple[str, tuple[str, ...]]] = [] + self.seen_configs: list[SynthesisConfig | None] = [] + + async def synthesize( + self, + intent: str, + payload: Mapping[str, Any], + *, + surface_id: str | None = None, + mutable_paths: Collection[str] = (), + config: SynthesisConfig | None = None, + ) -> SynthesisOutput: + del payload, surface_id + self.calls.append((intent, tuple(mutable_paths))) + self.seen_configs.append(config) + return self._scripted[intent] + + +def test_compute_bayes_optimal_threshold_valid() -> None: + """Computes exact and clamped Bayes-optimal thresholds for valid costs.""" + assert compute_bayes_optimal_threshold(0.1, 1.0) == pytest.approx(0.9) + assert compute_bayes_optimal_threshold(0.25, 1.0) == pytest.approx(0.75) + assert compute_bayes_optimal_threshold(0.0, 2.0) == pytest.approx(1.0) + assert compute_bayes_optimal_threshold(2.5, 1.0) == pytest.approx(0.0) + + +@pytest.mark.parametrize( + ("cost_fallback", "cost_wrong_ui"), + [ + (-0.01, 1.0), + (0.5, 0.0), + (0.5, -1.0), + ], +) +def test_compute_bayes_optimal_threshold_invalid( + cost_fallback: float, cost_wrong_ui: float +) -> None: + """Raises ValueError when fallback cost is negative or wrong-UI cost <= 0.""" + with pytest.raises(ValueError): + compute_bayes_optimal_threshold(cost_fallback, cost_wrong_ui) + + +@pytest.mark.asyncio +async def test_calibrate_thresholds_validation_errors() -> None: + """Raises ValueError on empty dataset, invalid target_precision, or empty thresholds.""" + synth = _FakeSynthesizer({}) + assert isinstance(synth, SynthesizerLike) + + example = LabeledDecisionExample( + intent="show cpu", + payload={"cpu": 0.5}, + expected_root_component="MetricCard", + ) + + with pytest.raises(ValueError, match="dataset"): + await calibrate_thresholds(synth, []) + + with pytest.raises(ValueError, match="target_precision"): + await calibrate_thresholds(synth, [example], target_precision=0.0) + + with pytest.raises(ValueError, match="target_precision"): + await calibrate_thresholds(synth, [example], target_precision=1.05) + + with pytest.raises(ValueError, match="thresholds"): + await calibrate_thresholds(synth, [example], thresholds=[]) + + +@pytest.mark.asyncio +async def test_calibrate_thresholds_golden_mix() -> None: + """Calibrates thresholds across read-only, mutable, wrong, and abstain examples.""" + scripted = { + "readonly_template": SynthesisOutput( + stage=SynthesisStage.TEMPLATE_SELECT, + messages=[], + confidence=0.92, + entropy=0.10, + selected_template_id="tpl_portfolio", + component_tree_spec={"template_id": "tpl_portfolio"}, + ), + "mutable_leaf": SynthesisOutput( + stage=SynthesisStage.FAST_1PASS_LEAF, + messages=[], + confidence=0.86, + entropy=0.15, + component_tree_spec={"root_component": "OrderForm"}, + ), + "container_tree": SynthesisOutput( + stage=SynthesisStage.CONTAINER_2PASS, + messages=[], + confidence=0.78, + entropy=0.25, + component_tree_spec={"root_component": "VitalGrid"}, + ), + "wrong_component_low_conf": SynthesisOutput( + stage=SynthesisStage.FAST_1PASS_LEAF, + messages=[], + confidence=0.62, + entropy=0.55, + component_tree_spec={"root_component": "WrongWidget"}, + ), + "hallucinated_when_should_abstain": SynthesisOutput( + stage=SynthesisStage.FAST_1PASS_LEAF, + messages=[], + confidence=0.52, + entropy=0.70, + component_tree_spec={"root_component": "MetricCard"}, + ), + "already_abstained": SynthesisOutput( + stage=SynthesisStage.ABSTAIN_FALLBACK, + messages=[], + confidence=0.95, + entropy=0.90, + ), + } + synth = _FakeSynthesizer(scripted) + dataset = [ + LabeledDecisionExample( + intent="readonly_template", + payload={"balance": 100}, + expected_template_id="tpl_portfolio", + ), + LabeledDecisionExample( + intent="mutable_leaf", + payload={"qty": 10}, + expected_root_component="OrderForm", + mutable_paths=("/qty",), + ), + LabeledDecisionExample( + intent="container_tree", + payload={"vitals": []}, + expected_root_component="VitalGrid", + ), + LabeledDecisionExample( + intent="wrong_component_low_conf", + payload={"cpu": 90}, + expected_root_component="ClusterHealth", + ), + LabeledDecisionExample( + intent="hallucinated_when_should_abstain", + payload={"unknown": 1}, + should_abstain=True, + ), + LabeledDecisionExample( + intent="already_abstained", + payload={}, + should_abstain=True, + ), + ] + + result = await calibrate_thresholds(synth, dataset, target_precision=0.95) + + # Synthesize called once per example, preserving mutable_paths. + assert len(synth.calls) == len(dataset) + assert ("mutable_leaf", ("/qty",)) in synth.calls + assert len(result.pareto_points) == 15 + + # At tau=0.65, the 3 correct examples (0.92, 0.86, 0.78) are accepted and + # the 2 wrong ones (0.62, 0.52) are rejected -> precision = 1.0, coverage = 3/6 = 0.5. + # Tie-breaking among tau in [0.65, 0.70, 0.75] (all coverage 0.5, precision 1.0) + # picks the lowest threshold: 0.65. + assert result.recommended_template_threshold == pytest.approx(0.65) + assert result.recommended_mutable_threshold == pytest.approx(0.75) + assert result.recommended_abstain_threshold == pytest.approx(0.65) + assert result.achieved_precision == pytest.approx(1.0) + assert result.achieved_coverage == pytest.approx(0.5) + + +@pytest.mark.asyncio +async def test_calibrate_thresholds_unachievable_target_and_clamping() -> None: + """Falls back to highest precision/threshold and clamps derived thresholds.""" + scripted = { + "wrong_high": SynthesisOutput( + stage=SynthesisStage.TEMPLATE_SELECT, + messages=[], + confidence=0.96, + entropy=0.1, + selected_template_id="wrong_tpl", + ), + "right_mid": SynthesisOutput( + stage=SynthesisStage.FAST_1PASS_LEAF, + messages=[], + confidence=0.92, + entropy=0.1, + component_tree_spec={"root_component": "RightLeaf"}, + ), + } + synth = _FakeSynthesizer(scripted) + dataset = [ + LabeledDecisionExample( + intent="wrong_high", + payload={}, + expected_template_id="expected_tpl", + ), + LabeledDecisionExample( + intent="right_mid", + payload={}, + expected_root_component="RightLeaf", + ), + ] + + # At custom thresholds [0.80, 0.90], both examples are accepted (precision 0.5). + # Neither meets target_precision=0.95, so fallback selects highest precision + # and breaks ties by highest threshold (0.90). + result = await calibrate_thresholds( + synth, + dataset, + target_precision=0.95, + thresholds=[0.80, 0.90], + ) + assert result.recommended_template_threshold == pytest.approx(0.90) + assert result.recommended_mutable_threshold == pytest.approx(0.99) + assert result.recommended_abstain_threshold == pytest.approx(0.90) + assert result.achieved_precision == pytest.approx(0.5) + assert result.achieved_coverage == pytest.approx(1.0) + + # Test zero-accepted precision=1.0 behavior and exact abstain threshold. + low_result = await calibrate_thresholds( + synth, + [dataset[1]], + target_precision=0.95, + thresholds=[0.35, 0.99], + ) + assert low_result.recommended_template_threshold == pytest.approx(0.35) + assert low_result.recommended_abstain_threshold == pytest.approx(0.35) + assert low_result.pareto_points[1].coverage == pytest.approx(0.0) + assert low_result.pareto_points[1].precision == pytest.approx(1.0) + assert low_result.pareto_points[1].fallback_rate == pytest.approx(1.0) + + +@pytest.mark.asyncio +async def test_calibrate_thresholds_restores_config_and_matches_template_root() -> None: + """Verifies H2 (permissive sweep + config restoration) and M5 (template root_component match).""" + scripted = { + "template_with_root": SynthesisOutput( + stage=SynthesisStage.TEMPLATE_SELECT, + messages=[], + confidence=0.88, + entropy=0.1, + selected_template_id="tpl_1", + component_tree_spec={ + "template_id": "tpl_1", + "root_component": "MetricCard", + }, + ), + "low_conf_wrong": SynthesisOutput( + stage=SynthesisStage.FAST_1PASS_LEAF, + messages=[], + confidence=0.36, + entropy=0.8, + component_tree_spec={"root_component": "WrongCard"}, + ), + } + synth = _FakeSynthesizer(scripted) + original_cfg = SynthesisConfig( + template_confidence_threshold=0.80, + mutable_confidence_threshold=0.90, + abstain_threshold=0.50, + ) + synth.config = original_cfg + + dataset = [ + LabeledDecisionExample( + intent="template_with_root", + payload={}, + expected_root_component="MetricCard", + ), + LabeledDecisionExample( + intent="low_conf_wrong", + payload={}, + expected_root_component="MetricCard", + ), + ] + res = await calibrate_thresholds(synth, dataset, target_precision=1.0) + assert synth.config == original_cfg + assert all( + cfg is not None + and cfg.abstain_threshold == 0.0 + and cfg.template_confidence_threshold == 0.0 + and cfg.mutable_confidence_threshold == 0.0 + for cfg in synth.seen_configs + ) + assert res.achieved_precision == pytest.approx(1.0) + assert res.achieved_coverage == pytest.approx(0.5) + assert res.recommended_abstain_threshold == pytest.approx(0.40) + + +@pytest.mark.asyncio +async def test_calibrate_thresholds_stage2_shadowing_and_threshold_1_0_clamp() -> None: + """Verifies M7: low-confidence wrong template does not shadow Stage 2, and 1.0 threshold clamps cleanly.""" + from a2ui.core import Catalog + from a2ui.inference_formats.decision import ( + DecisionSynthesizer, + DeterministicMockBackend, + ) + + cat = Catalog.from_json({ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "catalogId": "https://example.com/catalogs/m7/v1", + "protocolVersion": "1.0", + "components": { + "RightWidget": { + "type": "object", + "properties": { + "component": {"const": "RightWidget"}, + "label": {"$ref": "common_types.json#/$defs/DynamicString"}, + }, + "required": ["component", "label"], + }, + "OtherWidget": { + "type": "object", + "properties": { + "component": {"const": "OtherWidget"}, + "label": {"$ref": "common_types.json#/$defs/DynamicString"}, + }, + "required": ["component", "label"], + }, + }, + }) + registry = TemplateRegistry() + registry.register( + SurfaceTemplate( + template_id="low_conf_tpl", + description="Unrelated template", + surface_id="s1", + catalog_id=cat.catalog_id, + protocol_version="v1.0", + components=( + { + "id": "root", + "component": "OtherWidget", + "label": {"@path": "/label"}, + }, + ), + required_pointers=("/label",), + ) + ) + backend = DeterministicMockBackend( + scripted={ + "template_select": {"low_conf_tpl": 0.60}, + "root_component": {"RightWidget": 0.92, "OtherWidget": 0.08}, + } + ) + synth = DecisionSynthesizer([cat], backend, registry=registry) + dataset = [ + LabeledDecisionExample( + intent="show right widget", + payload={"label": "ok"}, + expected_root_component="RightWidget", + ) + ] + res = await calibrate_thresholds(synth, dataset, target_precision=0.95) + assert res.achieved_coverage == pytest.approx(1.0) + assert res.achieved_precision == pytest.approx(1.0) + + # Candidate threshold 1.0 must keep recommended_mutable_threshold >= recommended_template_threshold. + res_one = await calibrate_thresholds( + synth, dataset, target_precision=0.95, thresholds=[1.0] + ) + assert res_one.recommended_template_threshold == pytest.approx(1.0) + assert res_one.recommended_mutable_threshold == pytest.approx(1.0) + SynthesisConfig( + template_confidence_threshold=res_one.recommended_template_threshold, + mutable_confidence_threshold=res_one.recommended_mutable_threshold, + abstain_threshold=res_one.recommended_abstain_threshold, + ) diff --git a/python/a2ui_agent/tests/decision/test_catalog_graph_and_inspector.py b/python/a2ui_agent/tests/decision/test_catalog_graph_and_inspector.py new file mode 100644 index 0000000000..4411ced0d8 --- /dev/null +++ b/python/a2ui_agent/tests/decision/test_catalog_graph_and_inspector.py @@ -0,0 +1,596 @@ +# 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. + +"""Unit tests for CatalogDecisionGraph and inspect_payload_pointers.""" + +from __future__ import annotations + +from typing import Any + +from a2ui.core import Catalog +from a2ui.inference_formats.decision import ( + CatalogDecisionGraph, + PointerSummary, + SlotKind, + inspect_payload_pointers, +) + + +def _make_finance_catalog(protocol_version: str = "1.0") -> Catalog: + """Builds a custom Finance catalog with zero Basic Catalog components.""" + is_v1 = protocol_version.lstrip("v").startswith("1.") + call_key = "@call" if is_v1 else "call" + schema: dict[str, Any] = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "catalogId": "https://example.com/catalogs/finance/v1/catalog.json", + "protocolVersion": protocol_version, + "components": { + "PortfolioGrid": { + "type": "object", + "description": "Displays a table of portfolio positions.", + "properties": { + "component": {"const": "PortfolioGrid"}, + "accountName": {"$ref": "common_types.json#/$defs/DynamicString"}, + "positions": {"$ref": "common_types.json#/$defs/ChildList"}, + }, + "required": ["component", "accountName", "positions"], + }, + "TradeTicket": { + "type": "object", + "description": "Order entry ticket for equities.", + "allOf": [ + {"$ref": "common_types.json#/$defs/Checkable"}, + { + "type": "object", + "properties": { + "component": {"const": "TradeTicket"}, + "ticker": { + "$ref": "common_types.json#/$defs/DynamicString", + "description": "Stock ticker symbol to trade.", + }, + "quantity": { + "$ref": "common_types.json#/$defs/DynamicNumber", + "description": "Number of shares.", + }, + "side": { + "type": "string", + "enum": ["BUY", "SELL"], + "description": "Order transaction side.", + }, + "onSubmit": { + "$ref": "common_types.json#/$defs/Action", + "description": "Submission event handler.", + }, + }, + "required": ["component", "ticker", "quantity", "onSubmit"], + }, + ], + }, + "StrategyComparison": { + "type": "object", + "description": "Multi-view switcher comparing option strategies.", + "properties": { + "component": {"const": "StrategyComparison"}, + "strategies": { + "type": "array", + "items": { + "type": "object", + "properties": { + "strategyName": { + "$ref": "common_types.json#/$defs/DynamicString" + }, + "viewId": { + "$ref": "common_types.json#/$defs/ComponentId" + }, + }, + "required": ["strategyName", "viewId"], + }, + }, + }, + "required": ["component", "strategies"], + }, + "MarginAlertBox": { + "type": "object", + "description": "Wrapper container displaying a margin warning.", + "properties": { + "component": {"const": "MarginAlertBox"}, + "bannerChild": {"$ref": "common_types.json#/$defs/ComponentId"}, + "isMarginCall": {"$ref": "common_types.json#/$defs/DynamicBoolean"}, + }, + "required": ["component", "bannerChild"], + }, + }, + "functions": { + "isValidTicker": { + "type": "object", + "returnType": "boolean", + "properties": { + call_key: {"const": "isValidTicker"}, + "args": { + "type": "object", + "properties": {"value": {"type": "string"}}, + "required": ["value"], + }, + }, + "required": [call_key, "args"], + }, + "formatCurrency": { + "type": "object", + "returnType": "string", + "properties": { + call_key: {"const": "formatCurrency"}, + "args": { + "type": "object", + "properties": {"amount": {"type": "number"}}, + "required": ["amount"], + }, + }, + "required": [call_key, "args"], + }, + }, + } + return Catalog.from_json(schema) + + +def _make_healthcare_catalog() -> Catalog: + """Builds a custom Healthcare catalog with zero Basic Catalog components.""" + schema: dict[str, Any] = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "catalogId": "https://example.com/catalogs/healthcare/v1/catalog.json", + "protocolVersion": "1.0", + "components": { + "VitalsMonitor": { + "type": "object", + "description": "Live telemetry card for patient vitals.", + "properties": { + "component": {"const": "VitalsMonitor"}, + "patientName": {"$ref": "common_types.json#/$defs/DynamicString"}, + "heartRate": {"$ref": "common_types.json#/$defs/DynamicNumber"}, + "criticalAlert": { + "$ref": "common_types.json#/$defs/DynamicBoolean" + }, + "triageLevel": { + "type": "string", + "enum": ["GREEN", "YELLOW", "RED"], + }, + }, + "required": ["component", "patientName", "heartRate"], + }, + "DosageOrderPanel": { + "type": "object", + "description": "Medication dosage order container with action.", + "allOf": [ + {"$ref": "common_types.json#/$defs/Checkable"}, + { + "type": "object", + "properties": { + "component": {"const": "DosageOrderPanel"}, + "summaryWidget": { + "$ref": "common_types.json#/$defs/ComponentId" + }, + "confirmAction": { + "$ref": "common_types.json#/$defs/Action" + }, + }, + "required": [ + "component", + "summaryWidget", + "confirmAction", + ], + }, + ], + }, + "ChartViewSwitcher": { + "type": "object", + "description": "Switches between clinical chart views.", + "properties": { + "component": {"const": "ChartViewSwitcher"}, + "panes": { + "type": "array", + "items": { + "type": "object", + "properties": { + "paneLabel": {"type": "string"}, + "paneComponent": { + "$ref": "common_types.json#/$defs/ComponentId" + }, + }, + "required": ["paneLabel", "paneComponent"], + }, + }, + }, + "required": ["component", "panes"], + }, + }, + "functions": { + "isSafeDosage": { + "type": "object", + "returnType": "boolean", + "properties": { + "@call": {"const": "isSafeDosage"}, + "args": { + "type": "object", + "properties": {"mg": {"type": "number"}}, + "required": ["mg"], + }, + }, + "required": ["@call", "args"], + }, + "computeBmi": { + "type": "object", + "returnType": "number", + "properties": { + "@call": {"const": "computeBmi"}, + "args": {"type": "object", "properties": {}}, + }, + "required": ["@call", "args"], + }, + }, + } + return Catalog.from_json(schema) + + +def _make_devops_catalog() -> Catalog: + """Builds a custom DevOps catalog with zero Basic Catalog components.""" + schema: dict[str, Any] = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "catalogId": "https://example.com/catalogs/devops/v1/catalog.json", + "protocolVersion": "1.0", + "components": { + "IncidentTimeline": { + "type": "object", + "description": "Repeating timeline of production incidents.", + "properties": { + "component": {"const": "IncidentTimeline"}, + "events": {"$ref": "common_types.json#/$defs/ChildList"}, + "severityFilter": { + "type": "string", + "enum": ["P0", "P1", "P2"], + }, + }, + "required": ["component", "events"], + }, + "ClusterGauge": { + "type": "object", + "description": "Displays cluster CPU and tags.", + "properties": { + "component": {"const": "ClusterGauge"}, + "clusterId": {"$ref": "common_types.json#/$defs/DynamicString"}, + "cpuUtilization": { + "$ref": "common_types.json#/$defs/DynamicNumber" + }, + "isHealthy": {"$ref": "common_types.json#/$defs/DynamicBoolean"}, + "tags": {"$ref": "common_types.json#/$defs/DynamicStringList"}, + "metadataPayload": { + "$ref": "common_types.json#/$defs/DynamicValue" + }, + }, + "required": ["component", "clusterId", "cpuUtilization"], + }, + "RollbackTrigger": { + "type": "object", + "description": "Triggers a deployment rollback.", + "allOf": [ + {"$ref": "common_types.json#/$defs/Checkable"}, + { + "type": "object", + "properties": { + "component": {"const": "RollbackTrigger"}, + "targetRevision": { + "$ref": "common_types.json#/$defs/DynamicString" + }, + "triggerRollback": { + "$ref": "common_types.json#/$defs/Action" + }, + }, + "required": [ + "component", + "targetRevision", + "triggerRollback", + ], + }, + ], + }, + }, + "functions": { + "isRevisionDeployed": { + "type": "object", + "returnType": "boolean", + "properties": { + "@call": {"const": "isRevisionDeployed"}, + "args": { + "type": "object", + "properties": {"revision": {"type": "string"}}, + "required": ["revision"], + }, + }, + "required": ["@call", "args"], + }, + }, + } + return Catalog.from_json(schema) + + +class TestPayloadInspector: + """Tests for RFC 6901 JSON Pointer extraction and type classification.""" + + def test_nested_scalars_booleans_and_empty_dicts(self) -> None: + payload = { + "metrics": { + "cpu": 72.5, + "cores": 16, + "throttled": True, + "healthy": False, + "host": "prod-us-east-1", + }, + "emptyConfig": {}, + } + pointers = inspect_payload_pointers(payload) + by_path = {p.path: p for p in pointers} + + assert set(by_path) == { + "/metrics", + "/metrics/cpu", + "/metrics/cores", + "/metrics/throttled", + "/metrics/healthy", + "/metrics/host", + "/emptyConfig", + } + assert by_path["/metrics"] == PointerSummary( + path="/metrics", + value_type="object", + cardinality=5, + semantic_type="object", + label="Metrics", + ) + assert by_path["/metrics/cpu"] == PointerSummary( + path="/metrics/cpu", + value_type="number", + cardinality=1, + semantic_type="number", + label="Cpu", + ) + assert by_path["/metrics/cores"] == PointerSummary( + path="/metrics/cores", + value_type="number", + cardinality=1, + semantic_type="integer", + label="Cores", + ) + assert by_path["/metrics/throttled"] == PointerSummary( + path="/metrics/throttled", + value_type="boolean", + cardinality=1, + semantic_type="boolean", + label="Throttled", + ) + assert by_path["/metrics/healthy"] == PointerSummary( + path="/metrics/healthy", + value_type="boolean", + cardinality=1, + semantic_type="boolean", + label="Healthy", + ) + assert by_path["/metrics/host"] == PointerSummary( + path="/metrics/host", + value_type="string", + cardinality=1, + semantic_type="string", + label="Host", + ) + assert by_path["/emptyConfig"] == PointerSummary( + path="/emptyConfig", + value_type="object", + cardinality=0, + semantic_type="empty", + label="Empty config", + ) + + def test_array_of_dicts_collects_element_keys_without_recursing(self) -> None: + payload = { + "positions": [ + {"ticker": "GOOG", "shares": 100, "hedged": True}, + {"ticker": "AAPL", "shares": 50, "sector": "Tech"}, + ], + } + pointers = inspect_payload_pointers(payload) + assert len(pointers) == 1 + summary = pointers[0] + assert summary.path == "/positions" + assert summary.value_type == "array" + assert summary.semantic_type == "array" + assert summary.cardinality == 2 + assert summary.label == "Positions" + assert summary.element_keys == ("ticker", "shares", "hedged", "sector") + assert summary.sample_type_by_key == { + "ticker": "string", + "shares": "number", + "hedged": "boolean", + "sector": "string", + } + assert summary.element_semantic_types == { + "ticker": "string", + "shares": "integer", + "hedged": "boolean", + "sector": "string", + } + + def test_array_sample_pointers_and_label_derivation(self) -> None: + payload = { + "photoGallery": [ + {"url": "https://example.com/1.jpg", "caption": "Pool"}, + {"url": "https://example.com/2.jpg", "caption": "Garden"}, + ], + "bannerImages": [ + "https://example.com/hero1.png", + "https://example.com/hero2.png", + ], + } + by_path = {p.path: p for p in inspect_payload_pointers(payload)} + gallery = by_path["/photoGallery"] + assert gallery.label == "Photo gallery" + assert gallery.element_semantic_types["url"] == "image_url" + assert gallery.sample_pointers == ("/photoGallery/0/url",) + + banners = by_path["/bannerImages"] + assert banners.label == "Banner images" + assert banners.sample_pointers == ("/bannerImages/0",) + + def test_rfc6901_tilde_and_slash_escaping(self) -> None: + payload = { + "a/b": {"c~d": "escaped", "normal": 1}, + "rows": [{"service/name": "auth", "latency~ms": 12.5}], + } + pointers = inspect_payload_pointers(payload) + by_path = {p.path: p for p in pointers} + assert list(by_path) == [ + "/a~1b", + "/a~1b/c~0d", + "/a~1b/normal", + "/rows", + ] + assert by_path["/a~1b"].key == "a/b" + assert by_path["/a~1b/c~0d"].key == "c~d" + assert by_path["/a~1b/c~0d"].parent == "/a~1b" + assert by_path["/rows"].element_keys == ("service~1name", "latency~0ms") + assert by_path["/rows"].sample_type_by_key == { + "service~1name": "string", + "latency~0ms": "number", + } + assert hash(by_path["/rows"]) is not None + + def test_mutable_paths_exact_and_prefix_matching(self) -> None: + payload = { + "form": {"ticker": "GOOG", "quantity": 10}, + "format": {"theme": "dark"}, + "directFlag": True, + } + pointers = inspect_payload_pointers( + payload, mutable_paths=["/form", "/directFlag"] + ) + by_path = {p.path: p for p in pointers} + assert by_path["/form"].mutable_hint is True + assert by_path["/form/ticker"].mutable_hint is True + assert by_path["/form/quantity"].mutable_hint is True + assert by_path["/directFlag"].mutable_hint is True + assert by_path["/format"].mutable_hint is False + assert by_path["/format/theme"].mutable_hint is False + + +class TestCatalogDecisionGraph: + """Tests for dynamic CatalogDecisionGraph extraction across custom domains.""" + + def test_finance_catalog_slots_and_candidates(self) -> None: + catalog = _make_finance_catalog("1.0") + graph = CatalogDecisionGraph([catalog]) + + assert graph.protocol_version == "v1.0" + assert ( + graph.surface_catalog_id + == "https://example.com/catalogs/finance/v1/catalog.json" + ) + assert [c.name for c in graph.root_candidates()] == [ + "PortfolioGrid", + "TradeTicket", + "StrategyComparison", + "MarginAlertBox", + ] + assert [c.name for c in graph.leaf_candidates()] == ["TradeTicket"] + assert [c.name for c in graph.container_candidates()] == [ + "PortfolioGrid", + "StrategyComparison", + "MarginAlertBox", + ] + assert [c.name for c in graph.multi_view_switchers()] == ["StrategyComparison"] + assert graph.checkable_functions() == ("isValidTicker",) + + ticket = graph.get_component("TradeTicket") + assert ticket is not None + assert ticket.supports_checks is True + assert ticket.has_action_slot is True + assert ticket.is_container is False + slots_by_name = {s.name: s for s in ticket.slots} + assert slots_by_name["ticker"].kind == SlotKind.DATA_VALUE + assert slots_by_name["ticker"].value_type == "string" + assert slots_by_name["ticker"].required is True + assert slots_by_name["ticker"].description == "Stock ticker symbol to trade." + assert slots_by_name["quantity"].kind == SlotKind.DATA_VALUE + assert slots_by_name["quantity"].value_type == "number" + assert slots_by_name["quantity"].description == "Number of shares." + assert slots_by_name["side"].kind == SlotKind.STATIC_ENUM + assert slots_by_name["side"].enum_values == ("BUY", "SELL") + assert slots_by_name["side"].description == "Order transaction side." + assert slots_by_name["onSubmit"].kind == SlotKind.ACTION + assert slots_by_name["onSubmit"].description == "Submission event handler." + + assert ticket.get_slot("ticker") is not None + assert ticket.get_slot("ticker").name == "ticker" + assert ticket.get_slot("ticker[0]") is not None + assert ticket.get_slot("ticker[0]").name == "ticker" + assert ticket.get_slot("unknown_slot") is None + + switcher = graph.get_component("StrategyComparison") + assert switcher is not None + assert switcher.is_multi_view_switcher is True + strat_slot = switcher.slots[0] + assert strat_slot.kind == SlotKind.NAMED_CHILD_ARRAY + assert strat_slot.child_id_key == "viewId" + assert strat_slot.label_key == "strategyName" + + def test_healthcare_and_devops_catalogs_and_multi_catalog_mode(self) -> None: + hc_cat = _make_healthcare_catalog() + devops_cat = _make_devops_catalog() + graph = CatalogDecisionGraph([hc_cat, devops_cat]) + + assert graph.surface_catalog_id is None + assert graph.checkable_functions() == ( + "isSafeDosage", + "isRevisionDeployed", + ) + + vitals = graph.get_component("VitalsMonitor") + assert vitals is not None + assert vitals.is_container is False + assert vitals.has_action_slot is False + assert vitals.supports_checks is False + + dosage = graph.get_component("DosageOrderPanel") + assert dosage is not None + assert dosage.is_container is True + assert dosage.has_action_slot is True + assert dosage.supports_checks is True + + gauge = graph.get_component("ClusterGauge") + assert gauge is not None + assert gauge.supports_checks is False + gauge_slots = {s.name: s for s in gauge.slots} + assert gauge_slots["tags"].kind == SlotKind.DATA_VALUE + assert gauge_slots["tags"].value_type == "array" + assert gauge_slots["metadataPayload"].kind == SlotKind.DATA_VALUE + assert gauge_slots["metadataPayload"].value_type == "any" + + timeline = graph.get_component("IncidentTimeline") + assert timeline is not None + timeline_slots = {s.name: s for s in timeline.slots} + assert timeline_slots["events"].kind == SlotKind.CHILD_LIST + assert timeline_slots["severityFilter"].kind == SlotKind.STATIC_ENUM + assert timeline_slots["severityFilter"].enum_values == ("P0", "P1", "P2") + + def test_v09_catalog_support(self) -> None: + catalog_v09 = _make_finance_catalog("0.9") + graph = CatalogDecisionGraph([catalog_v09]) + assert graph.protocol_version in ("v0.9", "0.9") + assert graph.checkable_functions() == ("isValidTicker",) + assert graph.get_component("NonExistent") is None diff --git a/python/a2ui_agent/tests/decision/test_custom_catalogs_e2e.py b/python/a2ui_agent/tests/decision/test_custom_catalogs_e2e.py new file mode 100644 index 0000000000..78f6315c42 --- /dev/null +++ b/python/a2ui_agent/tests/decision/test_custom_catalogs_e2e.py @@ -0,0 +1,467 @@ +# 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. + +"""End-to-end synthesis tests across custom Finance, Healthcare, and DevOps catalogs.""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +import pytest + +from a2ui.core import Catalog, PayloadValidator +from a2ui.inference_formats.decision import ( + DecisionSynthesizer, + DeterministicMockBackend, + LabeledDecisionExample, + SynthesisConfig, + SynthesisOutput, + SynthesisStage, + TemplateRegistry, + calibrate_thresholds, +) +from a2ui.parser.messages import to_message_dicts +from a2ui.utils import validate_payload + + +def _build_finance_catalog(protocol_version: str) -> Catalog: + """Builds a custom Finance catalog with zero Basic Catalog components.""" + is_v1 = protocol_version.lstrip("v").startswith("1.") + call_key = "@call" if is_v1 else "call" + schema: dict[str, Any] = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "catalogId": "https://example.com/catalogs/finance/v1/catalog.json", + "protocolVersion": protocol_version, + "components": { + "TickerQuoteCard": { + "type": "object", + "description": "Displays live equity quote and day change.", + "properties": { + "component": {"const": "TickerQuoteCard"}, + "ticker": {"$ref": "common_types.json#/$defs/DynamicString"}, + "price": {"$ref": "common_types.json#/$defs/DynamicNumber"}, + "marketSession": { + "type": "string", + "enum": ["PRE_MARKET", "REGULAR", "AFTER_HOURS"], + }, + }, + "required": ["component", "ticker", "price"], + }, + "OrderEntryTicket": { + "type": "object", + "description": "Mutable order entry ticket with validation.", + "allOf": [ + {"$ref": "common_types.json#/$defs/Checkable"}, + { + "type": "object", + "properties": { + "component": {"const": "OrderEntryTicket"}, + "symbol": { + "$ref": "common_types.json#/$defs/DynamicString" + }, + "shares": { + "$ref": "common_types.json#/$defs/DynamicNumber" + }, + "side": { + "type": "string", + "enum": ["BUY", "SELL"], + }, + "submitOrder": {"$ref": "common_types.json#/$defs/Action"}, + }, + "required": [ + "component", + "symbol", + "shares", + "submitOrder", + ], + }, + ], + }, + "HoldingsLedger": { + "type": "object", + "description": "Repeating ledger of portfolio holdings.", + "properties": { + "component": {"const": "HoldingsLedger"}, + "portfolioName": {"$ref": "common_types.json#/$defs/DynamicString"}, + "positions": {"$ref": "common_types.json#/$defs/ChildList"}, + }, + "required": ["component", "portfolioName", "positions"], + }, + }, + "functions": { + "isValidTickerSymbol": { + "type": "object", + "returnType": "boolean", + "properties": { + call_key: {"const": "isValidTickerSymbol"}, + "args": { + "type": "object", + "properties": { + "ticker": {"$ref": "common_types.json#/$defs/DynamicString"} + }, + "required": ["ticker"], + }, + }, + "required": [call_key, "args"], + }, + }, + } + return Catalog.from_json(schema) + + +def _build_healthcare_catalog(protocol_version: str) -> Catalog: + """Builds a custom Healthcare catalog with zero Basic Catalog components.""" + is_v1 = protocol_version.lstrip("v").startswith("1.") + call_key = "@call" if is_v1 else "call" + schema: dict[str, Any] = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "catalogId": "https://example.com/catalogs/healthcare/v1/catalog.json", + "protocolVersion": protocol_version, + "components": { + "VitalsTelemetryCard": { + "type": "object", + "description": "Displays patient heart rate and triage level.", + "properties": { + "component": {"const": "VitalsTelemetryCard"}, + "patientName": {"$ref": "common_types.json#/$defs/DynamicString"}, + "heartRateBpm": {"$ref": "common_types.json#/$defs/DynamicNumber"}, + "triageBand": { + "type": "string", + "enum": ["GREEN", "YELLOW", "RED"], + }, + }, + "required": ["component", "patientName", "heartRateBpm"], + }, + "WardBedBanner": { + "type": "object", + "description": "Container wrapping a patient vitals card.", + "properties": { + "component": {"const": "WardBedBanner"}, + "wardName": {"$ref": "common_types.json#/$defs/DynamicString"}, + "vitalsChild": {"$ref": "common_types.json#/$defs/ComponentId"}, + }, + "required": ["component", "wardName", "vitalsChild"], + }, + "ClinicalChartDeck": { + "type": "object", + "description": "Multi-view switcher for clinical panes.", + "properties": { + "component": {"const": "ClinicalChartDeck"}, + "panes": { + "type": "array", + "items": { + "type": "object", + "properties": { + "paneTitle": {"type": "string"}, + "paneId": { + "$ref": "common_types.json#/$defs/ComponentId" + }, + }, + "required": ["paneTitle", "paneId"], + }, + }, + }, + "required": ["component", "panes"], + }, + }, + "functions": { + "isSafeHeartRate": { + "type": "object", + "returnType": "boolean", + "properties": { + call_key: {"const": "isSafeHeartRate"}, + "args": { + "type": "object", + "properties": { + "bpm": {"$ref": "common_types.json#/$defs/DynamicNumber"} + }, + "required": ["bpm"], + }, + }, + "required": [call_key, "args"], + }, + }, + } + return Catalog.from_json(schema) + + +def _build_devops_catalog(protocol_version: str) -> Catalog: + """Builds a custom DevOps catalog with zero Basic Catalog components.""" + is_v1 = protocol_version.lstrip("v").startswith("1.") + call_key = "@call" if is_v1 else "call" + schema: dict[str, Any] = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "catalogId": "https://example.com/catalogs/devops/v1/catalog.json", + "protocolVersion": protocol_version, + "components": { + "ClusterHealthGauge": { + "type": "object", + "description": "Displays cluster CPU utilization and region.", + "properties": { + "component": {"const": "ClusterHealthGauge"}, + "clusterName": {"$ref": "common_types.json#/$defs/DynamicString"}, + "cpuPercent": {"$ref": "common_types.json#/$defs/DynamicNumber"}, + }, + "required": ["component", "clusterName", "cpuPercent"], + }, + "IncidentFeed": { + "type": "object", + "description": "Repeating list of incident rows.", + "properties": { + "component": {"const": "IncidentFeed"}, + "incidents": {"$ref": "common_types.json#/$defs/ChildList"}, + "severityFilter": { + "type": "string", + "enum": ["SEV1", "SEV2", "SEV3"], + }, + }, + "required": ["component", "incidents"], + }, + "RollbackActionCard": { + "type": "object", + "description": "Triggers deployment rollback with check.", + "allOf": [ + {"$ref": "common_types.json#/$defs/Checkable"}, + { + "type": "object", + "properties": { + "component": {"const": "RollbackActionCard"}, + "revisionTag": { + "$ref": "common_types.json#/$defs/DynamicString" + }, + "triggerRollback": { + "$ref": "common_types.json#/$defs/Action" + }, + }, + "required": [ + "component", + "revisionTag", + "triggerRollback", + ], + }, + ], + }, + }, + "functions": { + "isRevisionHealthy": { + "type": "object", + "returnType": "boolean", + "properties": { + call_key: {"const": "isRevisionHealthy"}, + "args": { + "type": "object", + "properties": { + "revision": { + "$ref": "common_types.json#/$defs/DynamicString" + } + }, + "required": ["revision"], + }, + }, + "required": [call_key, "args"], + }, + }, + } + return Catalog.from_json(schema) + + +def _assert_valid_surface( + catalogs: Sequence[Catalog], + output: SynthesisOutput, + *, + expected_root: str, +) -> None: + """Validates every synthesized component, wire envelope, and Express output.""" + assert output.messages + validate_payload(list(catalogs), output.messages) + msg_dicts = to_message_dicts(output.messages) + components = msg_dicts[1]["updateComponents"]["components"] + assert components[0]["component"] == expected_root + + validators = {cat.catalog_id: PayloadValidator(cat) for cat in catalogs} + default_validator = PayloadValidator(catalogs[0]) + for comp in components: + cat_id = comp.get("catalogId") + validator = ( + validators[cat_id] + if isinstance(cat_id, str) and cat_id in validators + else default_validator + ) + validator.validate_component(comp) + + express_text = output.to_express(catalogs) + assert expected_root in express_text + + +@pytest.mark.parametrize("protocol_version", ["0.9", "1.0"]) +@pytest.mark.asyncio +async def test_finance_catalog_e2e_v09_and_v10(protocol_version: str) -> None: + """Verifies Finance leaf, action+checks, and ChildList synthesis in v0.9 and v1.0.""" + catalog = _build_finance_catalog(protocol_version) + backend = DeterministicMockBackend() + registry = TemplateRegistry() + synth = DecisionSynthesizer([catalog], backend, registry=registry) + + quote_out = await synth.synthesize( + "Show TickerQuoteCard for regular market session", + {"ticker": "GOOG", "price": 182.50}, + ) + assert quote_out.stage == SynthesisStage.FAST_1PASS_LEAF + assert quote_out.trace and quote_out.trace[0].outcome == "no eligible archetype" + _assert_valid_surface([catalog], quote_out, expected_root="TickerQuoteCard") + + # Promote synthesized quote surface and verify Stage 1 template reuse. + registry.promote_synthesized( + "quote_tpl", + "Promoted equity quote card", + quote_out, + required_pointers=["/ticker", "/price"], + ) + reused_out = await synth.synthesize( + "Show quote_tpl for regular market session", + {"ticker": "MSFT", "price": 415.0}, + ) + assert reused_out.stage == SynthesisStage.TEMPLATE_SELECT + assert reused_out.selected_template_id == "quote_tpl" + _assert_valid_surface([catalog], reused_out, expected_root="TickerQuoteCard") + + order_out = await synth.synthesize( + "Submit BUY order with OrderEntryTicket", + {"symbol": "NVDA", "shares": 25}, + ) + assert order_out.stage == SynthesisStage.FAST_1PASS_LEAF + _assert_valid_surface([catalog], order_out, expected_root="OrderEntryTicket") + + ledger_out = await synth.synthesize( + "Display HoldingsLedger positions table", + { + "portfolioName": "Growth Fund", + "positions": [ + {"ticker": "GOOG", "price": 182.50}, + {"ticker": "AAPL", "price": 220.10}, + ], + }, + ) + assert ledger_out.stage == SynthesisStage.CONTAINER_2PASS + _assert_valid_surface([catalog], ledger_out, expected_root="HoldingsLedger") + + +@pytest.mark.parametrize("protocol_version", ["0.9", "1.0"]) +@pytest.mark.asyncio +async def test_healthcare_catalog_e2e_v09_and_v10( + protocol_version: str, +) -> None: + """Verifies Healthcare leaf, CHILD wrapper, and multi-view switcher in v0.9 and v1.0.""" + catalog = _build_healthcare_catalog(protocol_version) + backend = DeterministicMockBackend( + scripted={ + "root_component:vitals card": {"VitalsTelemetryCard": 0.92}, + "root_component:ward banner": {"WardBedBanner": 0.90}, + "root_component:chart deck": {"ClinicalChartDeck": 0.90}, + "child_component": {"VitalsTelemetryCard": 0.95}, + } + ) + synth = DecisionSynthesizer([catalog], backend) + + vitals_out = await synth.synthesize( + "vitals card", + {"patientName": "J. Doe", "heartRateBpm": 74}, + ) + assert vitals_out.stage == SynthesisStage.FAST_1PASS_LEAF + assert vitals_out.trace and vitals_out.trace[0].outcome == "no eligible archetype" + _assert_valid_surface([catalog], vitals_out, expected_root="VitalsTelemetryCard") + + banner_out = await synth.synthesize( + "ward banner", + {"wardName": "ICU-East", "patientName": "J. Doe", "heartRateBpm": 74}, + ) + assert banner_out.stage == SynthesisStage.CONTAINER_2PASS + _assert_valid_surface([catalog], banner_out, expected_root="WardBedBanner") + + deck_out = await synth.synthesize( + "chart deck", + {"patientName": "J. Doe", "heartRateBpm": 74}, + ) + assert deck_out.stage == SynthesisStage.CONTAINER_2PASS + _assert_valid_surface([catalog], deck_out, expected_root="ClinicalChartDeck") + + +@pytest.mark.parametrize("protocol_version", ["0.9", "1.0"]) +@pytest.mark.asyncio +async def test_devops_catalog_and_calibration_e2e( + protocol_version: str, +) -> None: + """Verifies DevOps synthesis and empirical threshold calibration end-to-end.""" + catalog = _build_devops_catalog(protocol_version) + backend = DeterministicMockBackend() + synth = DecisionSynthesizer( + [catalog], + backend, + config=SynthesisConfig(abstain_threshold=0.35), + ) + + gauge_out = await synth.synthesize( + "Show ClusterHealthGauge cpuPercent", + {"clusterName": "prod-us-west1", "cpuPercent": 68.2}, + ) + assert gauge_out.stage == SynthesisStage.FAST_1PASS_LEAF + assert gauge_out.trace and gauge_out.trace[0].outcome == "no eligible archetype" + _assert_valid_surface([catalog], gauge_out, expected_root="ClusterHealthGauge") + + feed_out = await synth.synthesize( + "Show SEV1 IncidentFeed list", + { + "incidents": [ + {"clusterName": "prod-us-west1", "cpuPercent": 95.4}, + {"clusterName": "prod-eu-west1", "cpuPercent": 89.1}, + ] + }, + ) + assert feed_out.stage == SynthesisStage.CONTAINER_2PASS + _assert_valid_surface([catalog], feed_out, expected_root="IncidentFeed") + + rollback_out = await synth.synthesize( + "Trigger RollbackActionCard for revisionTag", + {"revisionTag": "v2026.10.20-rc1"}, + ) + assert rollback_out.stage == SynthesisStage.FAST_1PASS_LEAF + _assert_valid_surface([catalog], rollback_out, expected_root="RollbackActionCard") + + dataset = [ + LabeledDecisionExample( + intent="Show ClusterHealthGauge cpuPercent", + payload={"clusterName": "prod-us-west1", "cpuPercent": 68.2}, + expected_root_component="ClusterHealthGauge", + ), + LabeledDecisionExample( + intent="Show SEV1 IncidentFeed list", + payload={ + "incidents": [ + {"clusterName": "prod-us-west1", "cpuPercent": 95.4}, + ] + }, + expected_root_component="IncidentFeed", + ), + LabeledDecisionExample( + intent="Trigger RollbackActionCard for revisionTag", + payload={"revisionTag": "v2026.10.20-rc1"}, + expected_root_component="RollbackActionCard", + mutable_paths=("/revisionTag",), + ), + ] + cal_result = await calibrate_thresholds(synth, dataset, target_precision=0.95) + assert cal_result.achieved_precision == pytest.approx(1.0) + assert cal_result.achieved_coverage == pytest.approx(1.0) + assert 0.30 <= cal_result.recommended_template_threshold <= 0.99 diff --git a/python/a2ui_agent/tests/decision/test_decision_assets.py b/python/a2ui_agent/tests/decision/test_decision_assets.py new file mode 100644 index 0000000000..983f3be48f --- /dev/null +++ b/python/a2ui_agent/tests/decision/test_decision_assets.py @@ -0,0 +1,133 @@ +# 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 that the vendored decision assets match the repository and their schemas.""" + +from __future__ import annotations + +import json +import os +from typing import Any + +from jsonschema import Draft202012Validator +import pytest + +from a2ui.inference_formats.decision.archetypes import asset_path, load_asset + +from ..repo_paths import find_repo_root + +# Canonical file (relative to the repository root) to vendored asset parts. +_ASSET_SOURCES: dict[str, tuple[str, ...]] = { + "catalogs/decision/v1/archetypes.json": ("archetypes.json",), + "catalogs/decision/v1/archetype_definition.json": ("archetype_definition.json",), + "catalogs/decision/v1/pattern_definition.json": ("pattern_definition.json",), + "catalogs/basic/v1/patterns.json": ("patterns", "basic_v1_0.json"), +} + +_BASIC_V10_ID = "https://a2ui.org/specification/v1_0/catalogs/basic/catalog.json" +_BASIC_V09_ID = "https://a2ui.org/specification/v0_9/catalogs/basic/catalog.json" + + +def _errors(schema: dict[str, Any], data: Any) -> list[str]: + validator = Draft202012Validator(schema) + return [ + f"/{'/'.join(str(p) for p in e.absolute_path)}: {e.message}" + for e in validator.iter_errors(data) + ] + + +@pytest.mark.parametrize("source", sorted(_ASSET_SOURCES)) +def test_vendored_asset_matches_canonical_file(source: str) -> None: + repo_root = find_repo_root() + if repo_root is None or not os.path.isfile(os.path.join(repo_root, source)): + pytest.skip("repository checkout not available") + with open(os.path.join(repo_root, source), encoding="utf-8") as handle: + canonical = handle.read() + vendored = asset_path(*_ASSET_SOURCES[source]).read_text(encoding="utf-8") + assert vendored == canonical, ( + f"{source} differs from its vendored copy; run" + " `uv run python scripts/sync_decision_assets.py` in python/a2ui_agent" + ) + + +@pytest.mark.parametrize( + "schema_name", ["archetype_definition.json", "pattern_definition.json"] +) +def test_schemas_are_valid_draft_2020_12(schema_name: str) -> None: + schema = load_asset(schema_name) + assert schema["$schema"] == "https://json-schema.org/draft/2020-12/schema" + Draft202012Validator.check_schema(schema) + + +def test_archetypes_validate_against_schema() -> None: + schema = load_asset("archetype_definition.json") + grammar = load_asset("archetypes.json") + assert _errors(schema, grammar) == [] + assert grammar["$schema"] == schema["$id"] + + +def test_basic_patterns_validate_against_schema() -> None: + schema = load_asset("pattern_definition.json") + patterns = load_asset("patterns", "basic_v1_0.json") + assert _errors(schema, patterns) == [] + assert patterns["$schema"] == schema["$id"] + + +def test_basic_patterns_list_both_basic_catalog_ids() -> None: + patterns = load_asset("patterns", "basic_v1_0.json") + assert patterns["catalogIds"] == [_BASIC_V10_ID, _BASIC_V09_ID] + + +def test_basic_patterns_cover_the_expected_names() -> None: + patterns = load_asset("patterns", "basic_v1_0.json")["patterns"] + expected = { + "page", + "banner", + "picture", + "media", + "filters", + "headline", + "facts", + "prose", + "collection", + "comparison", + "steps", + "form", + "groups", + "actions", + "outcome", + "conversation", + "compose", + } + assert set(patterns) == expected + assert not {"chart", "timeline", "map"} & set(patterns) + assert patterns["collection"]["knobs"]["layout"] == ["rows", "cards", "reel"] + + +def test_archetype_schema_rejects_unknown_properties() -> None: + schema = load_asset("archetype_definition.json") + grammar = json.loads(json.dumps(load_asset("archetypes.json"))) + grammar["blocks"][0]["colour"] = "red" + grammar["archetypes"][0]["blocks"].append("bad-mark!!") + errors = _errors(schema, grammar) + assert any("colour" in e for e in errors) + assert any("bad-mark!!" in e for e in errors) + + +def test_pattern_schema_rejects_unknown_directive() -> None: + schema = load_asset("pattern_definition.json") + patterns = json.loads(json.dumps(load_asset("patterns", "basic_v1_0.json"))) + patterns["patterns"]["banner"]["components"][0]["$unknown"] = "x" + errors = _errors(schema, patterns) + assert any("$unknown" in e for e in errors) diff --git a/python/a2ui_agent/tests/decision/test_format_and_tool.py b/python/a2ui_agent/tests/decision/test_format_and_tool.py new file mode 100644 index 0000000000..1535c4ec4e --- /dev/null +++ b/python/a2ui_agent/tests/decision/test_format_and_tool.py @@ -0,0 +1,875 @@ +# 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 decision inference format, render tool, and synthesizer ergonomics.""" + +from __future__ import annotations + +import asyncio +import json +from typing import Any + +import httpx +import pytest + +from a2ui.core import Catalog +from a2ui.inference_formats import ( + DecisionFormat, + DecisionFormatFactory, + DecisionParser, + DecisionPromptGenerator, + DecisionRenderTool, + DecisionSynthesizer, + SynthesisConfig, + SynthesisStage, + TemplateRegistry, +) +from a2ui.inference_formats.decision import ( + CatalogDecisionGraph, + DecisionBackendType, + DecisionBlock, + DecisionQuery, + DecisionTask, + DecisionWireFormat, + DeterministicMockBackend, + FallbackSource, + JevHttpBackend, + LocalCrossEncoderBackend, + StepZeroLogprobBackend, + SurfaceTemplate, + coerce_decision_payload, + create_decision_backend, + decision_block_from_messages, +) +from a2ui.parser import A2uiCompilationError, A2uiPart, TextPart +from a2ui.parser.messages import to_message_dicts +from a2ui.processor import A2uiRequestProcessor +from a2ui.utils import validate_payload + +CATALOG_ID = "https://example.com/catalogs/ops/v1/catalog.json" + + +def _make_catalog() -> Catalog: + """A small v1.0 catalog with a leaf, an action leaf, and a container.""" + schema: dict[str, Any] = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "catalogId": CATALOG_ID, + "protocolVersion": "1.0", + "components": { + "TelemetryBadge": { + "type": "object", + "description": "Read-only telemetry badge.", + "properties": { + "component": {"const": "TelemetryBadge"}, + "serviceName": {"$ref": "common_types.json#/$defs/DynamicString"}, + "latencyMs": {"$ref": "common_types.json#/$defs/DynamicNumber"}, + }, + "required": ["component", "serviceName", "latencyMs"], + }, + "ActionableControl": { + "type": "object", + "description": "Mutable control leaf with an action.", + "properties": { + "component": {"const": "ActionableControl"}, + "targetHost": {"$ref": "common_types.json#/$defs/DynamicString"}, + "onExecute": {"$ref": "common_types.json#/$defs/Action"}, + }, + "required": ["component", "targetHost", "onExecute"], + }, + "AlertFrame": { + "type": "object", + "description": "Container wrapping a single child component.", + "properties": { + "component": {"const": "AlertFrame"}, + "innerWidget": {"$ref": "common_types.json#/$defs/ComponentId"}, + }, + "required": ["component", "innerWidget"], + }, + }, + "functions": {}, + } + return Catalog.from_json(schema) + + +def _confident_backend() -> DeterministicMockBackend: + return DeterministicMockBackend( + scripted={ + "root_component": {"TelemetryBadge": 0.9, "AlertFrame": 0.05}, + "child_component": {"TelemetryBadge": 0.9}, + } + ) + + +def _abstaining_backend() -> DeterministicMockBackend: + return DeterministicMockBackend( + scripted={"root_component": {"TelemetryBadge": 0.2, "AlertFrame": 0.2}} + ) + + +def _badge_template(surface_id: str = "default_surface") -> SurfaceTemplate: + return SurfaceTemplate( + template_id="badge_tpl", + description="Pre-approved telemetry badge", + surface_id=surface_id, + catalog_id=CATALOG_ID, + protocol_version="v1.0", + components=( + { + "id": "root", + "component": "TelemetryBadge", + "serviceName": {"@path": "/serviceName"}, + "latencyMs": {"@path": "/latencyMs"}, + }, + ), + required_pointers=("/serviceName", "/latencyMs"), + ) + + +PAYLOAD = {"serviceName": "checkout", "latencyMs": 42} +BLOCK = {"intent": "Show service telemetry", "payload": PAYLOAD, "surfaceId": "s1"} + + +# -------------------------------------------------------------------------- +# Enums and payload coercion +# -------------------------------------------------------------------------- + + +def test_wire_enums_format_as_their_values() -> None: + assert DecisionTask.ROOT_COMPONENT == "root_component" + assert f"{DecisionTask.ROOT_COMPONENT}:x" == "root_component:x" + assert str(DecisionWireFormat.SYSTEMONE) == "systemone" + assert DecisionBackendType.STEP_ZERO.value == "step0" + # Scripted mock lookups built with f-strings keep matching enum tasks. + backend = DeterministicMockBackend(scripted={"root_component:p": {"A": 1.0}}) + dist = asyncio.run( + backend.predict( + DecisionQuery( + task=DecisionTask.ROOT_COMPONENT, prompt="p", candidates=("A", "B") + ) + ) + ) + assert dist.probabilities["A"] == pytest.approx(1.0) + + +def test_coerce_decision_payload() -> None: + assert coerce_decision_payload(PAYLOAD) is PAYLOAD + assert coerce_decision_payload(json.dumps(PAYLOAD)) == PAYLOAD + assert coerce_decision_payload("[1, 2]") == [1, 2] + with pytest.raises(ValueError, match="not valid JSON"): + coerce_decision_payload("{not json") + with pytest.raises(TypeError, match="JSON string"): + coerce_decision_payload('"just a string"') + with pytest.raises(TypeError): + coerce_decision_payload(42) # type: ignore[arg-type] + + +def test_create_decision_backend_accepts_enum_and_rejects_unknown() -> None: + assert isinstance( + create_decision_backend(DecisionBackendType.MOCK), DeterministicMockBackend + ) + backend = create_decision_backend( + DecisionBackendType.SYSTEMONE, endpoint_url="http://h/v1/systemone" + ) + assert isinstance(backend, JevHttpBackend) + # "onnx" is an alias of the local backend; construction loads no model. + assert isinstance( + create_decision_backend(DecisionBackendType.ONNX), LocalCrossEncoderBackend + ) + with pytest.raises(ValueError, match="Unknown decision backend type") as info: + create_decision_backend("nope") + assert "'onnx'" in str(info.value) + with pytest.raises(ValueError, match="requires an endpoint URL"): + create_decision_backend("jev") + + +@pytest.mark.asyncio +async def test_wire_format_auto_detects_systemone() -> None: + seen: list[dict[str, Any]] = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(json.loads(request.content)) + return httpx.Response(200, json={"answers": {"q": {"answer": "A"}}}) + + transport = httpx.MockTransport(handler) + async with httpx.AsyncClient(transport=transport) as client: + for wire in ("auto", DecisionWireFormat.AUTO): + backend = JevHttpBackend( + "http://h/v1/systemone", wire_format=wire, client=client + ) + await backend.predict( + DecisionQuery(task="t", prompt="p", candidates=("A",)) + ) + assert len(seen) == 2 + assert all("questions" in req for req in seen) + + +# -------------------------------------------------------------------------- +# Backend lifecycle +# -------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_http_backends_support_async_with_and_per_loop_clients() -> None: + calls = 0 + + def handler(request: httpx.Request) -> httpx.Response: + nonlocal calls + calls += 1 + return httpx.Response(200, json={"probabilities": {"A": 1.0}}) + + transport = httpx.MockTransport(handler) + async with httpx.AsyncClient(transport=transport) as client: + async with JevHttpBackend("http://local/predict", client=client) as backend: + dist = await backend.predict( + DecisionQuery(task="t", prompt="p", candidates=("A",)) + ) + assert dist.probabilities == {"A": 1.0} + async with StepZeroLogprobBackend("http://local/v1/completions", "m") as step: + assert step._owned_client is None + assert calls == 1 + + # An owned client is created per loop and closed by aclose / __aexit__. + owned = JevHttpBackend("http://local/predict") + async with owned: + first = owned._get_client() + assert owned._get_client() is first + assert owned._owned_client is None + + def on_other_loop() -> bool: + async def body() -> bool: + second = owned._get_client() + await owned.aclose() + return second is not first + + return asyncio.run(body()) + + assert await asyncio.to_thread(on_other_loop) + await first.aclose() + + +@pytest.mark.asyncio +async def test_mock_backend_supports_async_with() -> None: + async with DeterministicMockBackend() as backend: + dist = await backend.predict( + DecisionQuery(task="t", prompt="p", candidates=("A", "B")) + ) + assert set(dist.probabilities) == {"A", "B"} + + +# -------------------------------------------------------------------------- +# Synthesizer ergonomics +# -------------------------------------------------------------------------- + + +def test_synthesizer_constructor_defaults(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("A2UI_DECISION_BACKEND", "mock") + catalog = _make_catalog() + synth = DecisionSynthesizer([catalog]) + assert isinstance(synth.backend, DeterministicMockBackend) + + graph = CatalogDecisionGraph([catalog]) + from_graph = DecisionSynthesizer(graph, _confident_backend()) + assert from_graph.graph is graph + + via_env = DecisionSynthesizer.from_env(graph) + assert via_env.graph is graph + assert isinstance(via_env.backend, DeterministicMockBackend) + + +def test_synthesize_sync_without_and_within_running_loop() -> None: + catalog = _make_catalog() + synth = DecisionSynthesizer([catalog], _confident_backend()) + + out = synth.synthesize_sync("Show telemetry", PAYLOAD, surface_id="s1") + assert out.stage == SynthesisStage.FAST_1PASS_LEAF + validate_payload([catalog], out.messages) + + async def inside_loop() -> SynthesisStage: + return synth.synthesize_sync("Show telemetry", PAYLOAD).stage + + assert asyncio.run(inside_loop()) == SynthesisStage.FAST_1PASS_LEAF + + +@pytest.mark.asyncio +async def test_synthesize_accepts_json_string_and_array_payloads() -> None: + catalog = _make_catalog() + synth = DecisionSynthesizer([catalog], _confident_backend()) + + out = await synth.synthesize("Show telemetry", json.dumps(PAYLOAD)) + data = [d for d in to_message_dicts(out.messages) if "updateDataModel" in d] + assert data[0]["updateDataModel"]["value"] == PAYLOAD + + arr = await synth.synthesize( + "Show telemetry", [{"serviceName": "a", "latencyMs": 1}] + ) + data = [d for d in to_message_dicts(arr.messages) if "updateDataModel" in d] + assert data[0]["updateDataModel"]["value"] == { + "items": [{"serviceName": "a", "latencyMs": 1}] + } + + with pytest.raises(ValueError, match="not valid JSON"): + await synth.synthesize("x", "{bad") + with pytest.raises(TypeError, match="JSON string"): + await synth.synthesize("x", '"scalar"') + + +@pytest.mark.asyncio +async def test_synthesize_explicit_template_id() -> None: + catalog = _make_catalog() + registry = TemplateRegistry() + registry.register(_badge_template()) + synth = DecisionSynthesizer([catalog], _abstaining_backend(), registry=registry) + + out = await synth.synthesize( + "anything", PAYLOAD, template_id="badge_tpl", surface_id="s9" + ) + assert out.stage == SynthesisStage.TEMPLATE_SELECT + assert out.selected_template_id == "badge_tpl" + assert out.confidence == 1.0 + assert to_message_dicts(out.messages)[0]["createSurface"]["surfaceId"] == "s9" + + with pytest.raises(ValueError, match="Unknown template 'missing'"): + await synth.synthesize("anything", PAYLOAD, template_id="missing") + + +@pytest.mark.asyncio +async def test_abstention_without_fallback_is_unchanged() -> None: + catalog = _make_catalog() + synth = DecisionSynthesizer([catalog], _abstaining_backend()) + out = await synth.synthesize("low confidence", PAYLOAD) + assert out.stage == SynthesisStage.ABSTAIN_FALLBACK + assert out.messages == [] + assert out.fallback_source is None + + +@pytest.mark.asyncio +async def test_abstention_fallback_dsl_compiles_and_adds_data_model() -> None: + catalog = _make_catalog() + synth = DecisionSynthesizer([catalog], _abstaining_backend()) + out = await synth.synthesize( + "low confidence", + PAYLOAD, + surface_id="s1", + fallback_dsl="root = TelemetryBadge($/serviceName, $/latencyMs)", + ) + assert out.stage == SynthesisStage.ABSTAIN_FALLBACK + assert out.fallback_source is FallbackSource.DSL + assert out.fallback_source == "fallback_dsl" + dicts = to_message_dicts(out.messages) + assert dicts[0]["createSurface"]["surfaceId"] == "s1" + assert any("updateDataModel" in d for d in dicts) + validate_payload([catalog], out.messages) + + +@pytest.mark.asyncio +async def test_abstention_fallback_fn_sync_and_async() -> None: + catalog = _make_catalog() + template = _badge_template() + seen: list[tuple[str, str]] = [] + + def sync_fn(intent: str, payload: Any, surface_id: str) -> Any: + seen.append((intent, surface_id)) + return template.render_messages(payload, surface_id=surface_id) + + async def async_fn(intent: str, payload: Any, surface_id: str) -> Any: + return sync_fn(intent, payload, surface_id) + + def dict_fn(intent: str, payload: Any, surface_id: str) -> Any: + # Wire-format dicts are accepted too; to_message_models validates them. + return to_message_dicts(sync_fn(intent, payload, surface_id)) + + for fn in (sync_fn, async_fn, dict_fn): + synth = DecisionSynthesizer([catalog], _abstaining_backend(), fallback_fn=fn) + out = await synth.synthesize("low", PAYLOAD, surface_id="s2") + assert out.fallback_source is FallbackSource.CALLBACK + assert out.messages + assert seen == [("low", "s2")] * 3 + + +def test_format_factory_shares_one_backend(monkeypatch: pytest.MonkeyPatch) -> None: + from a2ui.inference_formats.decision import BatchingDecisionBackend + + monkeypatch.setenv("A2UI_DECISION_BACKEND", "mock") + catalog = _make_catalog() + + lazy = DecisionFormatFactory() + assert lazy.backend is None + first = lazy.create_format([catalog]) + second = lazy.create_format([catalog]) + assert first.synthesizer.backend is second.synthesizer.backend is lazy.backend + assert isinstance(lazy.backend, BatchingDecisionBackend) + assert isinstance(lazy.backend.inner, DeterministicMockBackend) + # The catalog graph is still per format. + assert first.synthesizer.graph is not second.synthesizer.graph + + explicit_backend = _confident_backend() + explicit = DecisionFormatFactory(backend=explicit_backend) + explicit_fmt = explicit.create_format([catalog]) + assert isinstance(explicit_fmt.synthesizer.backend, BatchingDecisionBackend) + assert explicit_fmt.synthesizer.backend.inner is explicit_backend + + unbatched = DecisionFormatFactory(backend=explicit_backend, batch_backend=False) + assert unbatched.create_format([catalog]).synthesizer.backend is explicit_backend + + +@pytest.mark.asyncio +async def test_abstention_fallback_card_is_deterministic_and_actionless() -> None: + catalog = _make_catalog() + synth = DecisionSynthesizer([catalog], _abstaining_backend(), fallback_card=True) + first = await synth.synthesize("low confidence", PAYLOAD, surface_id="s3") + second = await synth.synthesize("low confidence", PAYLOAD, surface_id="s3") + assert first.stage == SynthesisStage.ABSTAIN_FALLBACK + assert first.fallback_source is FallbackSource.CARD + assert to_message_dicts(first.messages) == to_message_dicts(second.messages) + components = next( + d["updateComponents"]["components"] + for d in to_message_dicts(first.messages) + if "updateComponents" in d + ) + assert components[0]["component"] == "AlertFrame" + assert all(c["component"] != "ActionableControl" for c in components) + validate_payload([catalog], first.messages) + + +# -------------------------------------------------------------------------- +# Templates with v1.0 envelopes +# -------------------------------------------------------------------------- + + +@pytest.mark.asyncio +async def test_promote_synthesized_accepts_v10_single_envelope() -> None: + catalog = _make_catalog() + synth = DecisionSynthesizer([catalog], _confident_backend()) + out = await synth.synthesize("Show telemetry", PAYLOAD, surface_id="s1") + dicts = to_message_dicts(out.messages) + components = next(d for d in dicts if "updateComponents" in d)["updateComponents"][ + "components" + ] + single = [{ + "version": "v1.0", + "createSurface": { + "surfaceId": "s1", + "catalogId": CATALOG_ID, + "components": components, + }, + }] + from a2ui.parser.messages import to_message_models + + single_output = type(out)( + stage=out.stage, + messages=to_message_models(single), + confidence=out.confidence, + entropy=out.entropy, + ) + registry = TemplateRegistry() + template = registry.promote_synthesized("from_v10", "desc", single_output) + assert template.surface_id == "s1" + assert template.catalog_id == CATALOG_ID + assert template.root_component() == "TelemetryBadge" + validate_payload([catalog], template.render_messages(PAYLOAD)) + + with pytest.raises(ValueError, match="must define components"): + registry.promote_synthesized( + "empty", + "desc", + type(out)(stage=out.stage, messages=[], confidence=0.0, entropy=0.0), + ) + + +# -------------------------------------------------------------------------- +# Decision block, prompt generator, parser, and format +# -------------------------------------------------------------------------- + + +def test_decision_block_round_trip_and_aliases() -> None: + block = DecisionBlock.from_mapping({ + "intent": " Show it ", + "data": json.dumps(PAYLOAD), + "surface_id": "s1", + "templateId": "badge_tpl", + "fallback_dsl": "", + }) + assert block.intent == "Show it" + assert block.payload == PAYLOAD + assert block.surface_id == "s1" + assert block.template_id == "badge_tpl" + assert block.fallback_dsl is None + assert block.layout == () + assert block.to_json() == { + "intent": "Show it", + "payload": PAYLOAD, + "surfaceId": "s1", + "template": "badge_tpl", + } + with pytest.raises(ValueError, match="intent"): + DecisionBlock.from_mapping({"payload": {}}) + with pytest.raises(TypeError, match="payload"): + DecisionBlock.from_mapping({"intent": "x"}) + with pytest.raises(TypeError, match="surfaceId"): + DecisionBlock.from_mapping({"intent": "x", "payload": {}, "surfaceId": 3}) + + +def test_decision_block_layout_carries_raw_items_and_synthesizer_validates() -> None: + from a2ui.inference_formats.decision.models import LayoutBrief, MAX_BRIEF_SECTIONS + + with_layout = DecisionBlock.from_mapping({ + "intent": "Show resort", + "payload": PAYLOAD, + "layout": ["picture:name,logoUrl", "collection:/photos", "facts:address"], + }) + # The block carries the items verbatim; it does not know the grammar. + assert with_layout.layout == ( + "picture:name,logoUrl", + "collection:/photos", + "facts:address", + ) + assert with_layout.to_json()["layout"] == list(with_layout.layout) + + # A pre-parsed brief is accepted and serialized back to items. + brief = LayoutBrief.parse(["picture:name"], roles=frozenset({"picture"})) + assert DecisionBlock.from_mapping( + {"intent": "x", "payload": PAYLOAD, "layout": brief} + ).layout == ("picture:/name",) + + # Empty or blank layout arrays normalize to no items and are omitted on output. + empty = DecisionBlock.from_mapping( + {"intent": "Show resort", "payload": PAYLOAD, "layout": ["", " "]} + ) + assert empty.layout == () + assert "layout" not in empty.to_json() + + # Shape errors are the block's job: non-array or non-string items. + with pytest.raises(TypeError, match="layout"): + DecisionBlock.from_mapping( + {"intent": "Show resort", "payload": PAYLOAD, "layout": "picture:name"} + ) + with pytest.raises(TypeError, match="layout"): + DecisionBlock.from_mapping( + {"intent": "Show resort", "payload": PAYLOAD, "layout": [123]} + ) + + # Role and structure validation happens against the synthesizer's grammar. + catalog = _make_catalog() + synth = DecisionSynthesizer([catalog], _confident_backend()) + roles = list(synth.archetypes.brief_roles()) + too_many = [f"{roles[i]}:k{i}" for i in range(MAX_BRIEF_SECTIONS + 1)] + with pytest.raises(ValueError, match=str(MAX_BRIEF_SECTIONS)): + synth.synthesize_sync("Show resort", PAYLOAD, layout=too_many) + for invalid_item in ("picture:name:sub", "sparkles:name", "name,logoUrl"): + with pytest.raises(ValueError): + synth.synthesize_sync("Show resort", PAYLOAD, layout=[invalid_item]) + + +def test_custom_grammar_roles_flow_through_prompt_parser_and_synthesizer() -> None: + """A grammar with an extra block id is honored end to end (no default-grammar leak).""" + import copy + + from a2ui.inference_formats.decision.archetypes import ArchetypeGrammar, load_asset + + raw = copy.deepcopy(load_asset("archetypes.json")) + gallery = copy.deepcopy(next(b for b in raw["blocks"] if b["id"] == "picture")) + gallery["id"] = "gallery" + raw["blocks"].append(gallery) + custom = ArchetypeGrammar.from_json(raw) + assert "gallery" in custom.brief_roles() + + catalog = _make_catalog() + fmt = DecisionFormat( + [catalog], backend=_confident_backend(), archetypes=custom, surface_id="s" + ) + assert "`gallery`" in fmt.prompt_generator.generate_base_rules() + assert "`gallery`" not in DecisionPromptGenerator([catalog]).generate_base_rules() + + block_json = json.dumps( + {"intent": "Show", "payload": PAYLOAD, "layout": ["gallery:serviceName"]} + ) + # The parser forwards the raw items; the custom grammar accepts the role. + messages = fmt.parser.compile(block_json) + assert messages + + +def test_prompt_generator_lists_components_and_templates() -> None: + from a2ui.inference_formats.decision.archetypes import ArchetypeGrammar + + catalog = _make_catalog() + registry = TemplateRegistry() + registry.register(_badge_template()) + gen = DecisionPromptGenerator([catalog], registry=registry) + prompt = gen.generate() + assert "" in prompt and "intent" in prompt and "payload" in prompt + assert "`layout`" in prompt + for role in ArchetypeGrammar.default().brief_roles(): + assert f"`{role}`" in prompt + assert "- TelemetryBadge" in prompt + assert "`badge_tpl`: Pre-approved telemetry badge" in prompt + assert gen.generate_catalog_instructions(include_schema=False) == "" + assert gen.generate_examples() == "" + + +def test_processor_with_decision_format_factory() -> None: + catalog = _make_catalog() + processor = A2uiRequestProcessor( + catalogs=[catalog], + format_factory=DecisionFormatFactory(backend=_confident_backend()), + ) + assert isinstance(processor.format, DecisionFormat) + prompt = processor.prompt_snippet + assert "Decision Block Output Contract" in prompt + + response = f"Here you go.\n\n{json.dumps(BLOCK)}\n\nDone." + parts = processor.parse_response(response) + assert isinstance(parts[0], TextPart) + a2ui_parts = [p for p in parts if isinstance(p, A2uiPart)] + assert len(a2ui_parts) == 1 + dicts = to_message_dicts(a2ui_parts[0].a2ui) + assert dicts[0]["createSurface"]["surfaceId"] == "s1" + validate_payload([catalog], a2ui_parts[0].a2ui) + + # Unwrapped compilation and lossy decompilation. + parser = processor.format.create_parser() + assert isinstance(parser, DecisionParser) + messages = parser.compile(json.dumps(BLOCK)) + back = parser.decompile(messages) + assert back.startswith("") and back.endswith("") + recovered = json.loads(back[len("") : -len("")]) + assert recovered == { + "intent": "Render s1", + "payload": PAYLOAD, + "surfaceId": "s1", + } + assert decision_block_from_messages(messages).surface_id == "s1" + # Decompiled output can be parsed and compiled back without error (H3). + round_trip_parts = processor.parse_response(back) + assert any(isinstance(p, A2uiPart) for p in round_trip_parts) + + +def test_decision_parser_errors() -> None: + catalog = _make_catalog() + strict = DecisionFormat( + [catalog], backend=_abstaining_backend(), fallback_card=False + ).create_parser() + with pytest.raises(A2uiCompilationError, match="abstained"): + strict.compile(json.dumps(BLOCK)) + with pytest.raises(A2uiCompilationError, match="not valid JSON"): + strict.compile("{nope") + with pytest.raises(A2uiCompilationError, match="intent"): + strict.compile(json.dumps({"payload": {}})) + with pytest.raises(A2uiCompilationError, match="Unknown template"): + strict.compile(json.dumps({**BLOCK, "template": "missing"})) + + # The format default renders a card instead of failing on abstention. + lenient = DecisionFormat([catalog], backend=_abstaining_backend()).create_parser() + assert lenient.compile(json.dumps(BLOCK)) + assert lenient.has_format_content("{}", complete=True) + assert not lenient.has_format_content("plain text") + + # A list of blocks renders every surface, and omits duplicate createSurface + # when surfaceId is omitted or reused (H4). + two = lenient.compile(json.dumps([BLOCK, {**BLOCK, "surfaceId": "s2"}])) + ids = { + d["createSurface"]["surfaceId"] + for d in to_message_dicts(two) + if "createSurface" in d + } + assert ids == {"s1", "s2"} + validate_payload([catalog], two) + + unnamed_pair = lenient.compile( + json.dumps([ + {"intent": "First", "payload": PAYLOAD}, + {"intent": "Second", "payload": PAYLOAD}, + ]) + ) + unnamed_ids = [ + d["createSurface"]["surfaceId"] + for d in to_message_dicts(unnamed_pair) + if "createSurface" in d + ] + assert unnamed_ids == ["main_1", "main_2"] + validate_payload([catalog], unnamed_pair) + + replaced = lenient.compile( + json.dumps([ + {"intent": "First", "payload": PAYLOAD, "surfaceId": "s1"}, + { + "intent": "Second", + "payload": {"serviceName": "auth", "latencyMs": 9}, + "surfaceId": "s1", + }, + ]) + ) + create_count = sum(1 for d in to_message_dicts(replaced) if "createSurface" in d) + assert create_count == 1 + validate_payload([catalog], replaced) + + +@pytest.mark.asyncio +async def test_prompt_generator_validates_examples_and_factory_aclose( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Verifies H3 (example validation on generate), Q1 (factory aclose), M2 (protocol aclose), and H1 (synthesize_sync client cleanup).""" + from a2ui.core import A2uiValidationError + from a2ui.inference_formats.decision import DecisionBackend + from a2ui.parser.messages import to_message_models + + assert hasattr(DecisionBackend, "aclose") + assert hasattr(DecisionBackend, "__aenter__") + assert hasattr(DecisionBackend, "__aexit__") + + catalog = _make_catalog() + bad_example = to_message_models([ + { + "version": "v1.0", + "createSurface": {"surfaceId": "s1", "catalogId": CATALOG_ID}, + }, + { + "version": "v1.0", + "updateComponents": { + "surfaceId": "s1", + "components": [{"id": "root", "component": "UnknownWidget"}], + }, + }, + ]) + gen_bad = DecisionPromptGenerator([catalog], examples=[bad_example]) + with pytest.raises(A2uiValidationError): + gen_bad.generate() + + valid_example = _badge_template("s1").render_messages(PAYLOAD) + gen_ok = DecisionPromptGenerator([catalog], examples=[valid_example]) + prompt_text = gen_ok.generate() + assert '"intent": "Render s1"' in prompt_text + + # DecisionFormatFactory supports async with and aclose() (Q1). + monkeypatch.setenv("A2UI_DECISION_BACKEND", "mock") + async with DecisionFormatFactory() as factory: + fmt = factory.create_format([catalog]) + assert fmt.synthesizer.backend is factory.backend + + # H1: synthesize_sync closes temporary loop clients on JevHttpBackend. + created_clients: list[httpx.AsyncClient] = [] + real_async_client = httpx.AsyncClient + + def tracking_client(*args: Any, **kwargs: Any) -> httpx.AsyncClient: + transport = httpx.MockTransport( + lambda req: httpx.Response( + 200, json={"probabilities": {"TelemetryBadge": 0.95}} + ) + ) + c = real_async_client(*args, transport=transport, **kwargs) + created_clients.append(c) + return c + + monkeypatch.setattr(httpx, "AsyncClient", tracking_client) + http_backend = JevHttpBackend("http://local/predict") + synth = DecisionSynthesizer([catalog], http_backend) + synth.synthesize_sync("Show telemetry", PAYLOAD) + synth.synthesize_sync("Show telemetry", PAYLOAD) + assert len(created_clients) == 2 + assert all(c.is_closed for c in created_clients) + + +def test_decision_format_shares_synthesizer_and_default_surface() -> None: + catalog = _make_catalog() + fmt = DecisionFormat([catalog], backend=_confident_backend(), surface_id="pane") + assert fmt.create_parser().synthesizer is fmt.synthesizer + assert fmt.catalogs == [catalog] and fmt.examples is None + messages = fmt.parser.compile(json.dumps({"intent": "Show", "payload": PAYLOAD})) + assert to_message_dicts(messages)[0]["createSurface"]["surfaceId"] == "pane" + + +# -------------------------------------------------------------------------- +# Render tool +# -------------------------------------------------------------------------- + + +def test_render_tool_schema_and_run_sync() -> None: + catalog = _make_catalog() + registry = TemplateRegistry() + registry.register(_badge_template()) + tool = DecisionRenderTool.create( + [catalog], backend=_confident_backend(), registry=registry + ) + schema = tool.parameters_json_schema() + assert schema["required"] == ["intent", "payload"] + assert schema["properties"]["template"]["enum"] == ["badge_tpl"] + assert {"type": "string"} in schema["properties"]["payload"]["anyOf"] + assert "`items`" in schema["properties"]["payload"]["description"] + assert tool.name == "render_a2ui_decision" + + out = tool.run_sync({"intent": "Show telemetry", "payload": json.dumps(PAYLOAD)}) + # The only registered template matches the payload, so Stage 1 wins. + assert out.stage == SynthesisStage.TEMPLATE_SELECT + assert out.selected_template_id == "badge_tpl" + assert ( + to_message_dicts(out.messages)[0]["createSurface"]["surfaceId"] + == SynthesisConfig().default_surface_id + ) + + templated = tool.run_sync( + {"intent": "x", "payload": PAYLOAD, "template": "badge_tpl", "surfaceId": "t"} + ) + assert templated.selected_template_id == "badge_tpl" + assert to_message_dicts(templated.messages)[0]["createSurface"]["surfaceId"] == "t" + + +@pytest.mark.asyncio +async def test_render_tool_run_async_fallbacks() -> None: + catalog = _make_catalog() + tool = DecisionRenderTool.create( + [catalog], backend=_abstaining_backend(), surface_id="main" + ) + card = await tool.run_async({"intent": "low", "payload": PAYLOAD}) + assert card.fallback_source is FallbackSource.CARD + assert to_message_dicts(card.messages)[0]["createSurface"]["surfaceId"] == "main" + + dsl = await tool.run_async({ + "intent": "low", + "payload": PAYLOAD, + "fallbackDsl": "root = TelemetryBadge($/serviceName, $/latencyMs)", + }) + assert dsl.fallback_source is FallbackSource.DSL + + with pytest.raises(ValueError, match="intent"): + await tool.run_async({"payload": PAYLOAD}) + + # L1 + M2: schema pattern accepts `~` tokens and tool accepts pre-parsed LayoutBrief + from a2ui.inference_formats.decision.models import LayoutBrief + + schema = tool.parameters_json_schema() + layout_pattern = schema["properties"]["layout"]["items"]["pattern"] + import re + + assert re.match(layout_pattern, "prose:/foo~1bar") is not None + brief_res = await tool.run_async({ + "intent": "low", + "payload": PAYLOAD, + "layout": LayoutBrief.parse(["prose:/foo~1bar"], roles=frozenset({"prose"})), + }) + assert brief_res.fallback_source is FallbackSource.CARD + + # DecisionBlock mutablePaths / mutable_paths parsing and tool schema + assert "mutablePaths" in schema["properties"] + mut_block = DecisionBlock.from_mapping({ + "intent": "Sign in", + "payload": {"email": "alex@example.com", "password": ""}, + "mutablePaths": ["email", "/password"], + }) + assert mut_block.mutable_paths == ("/email", "/password") + assert mut_block.to_json()["mutablePaths"] == ["/email", "/password"] + with pytest.raises(TypeError, match="mutablePaths"): + DecisionBlock.from_mapping({ + "intent": "Sign in", + "payload": {"email": "a"}, + "mutablePaths": "/email", + }) diff --git a/python/a2ui_agent/tests/decision/test_layout_conformance.py b/python/a2ui_agent/tests/decision/test_layout_conformance.py new file mode 100644 index 0000000000..f2439e28cd --- /dev/null +++ b/python/a2ui_agent/tests/decision/test_layout_conformance.py @@ -0,0 +1,196 @@ +# 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. + +"""Conformance harness for `conformance/agent/decision/archetypes.yaml`.""" + +from __future__ import annotations + +import asyncio +from collections.abc import Mapping +from typing import Any + +from a2ui.core import Catalog +from a2ui.core.basic_catalog import BasicCatalog +from a2ui.inference_formats.decision import ( + ArchetypeGrammar, + BlockBindings, + CatalogDecisionGraph, + LayoutPlanner, + PatternExpander, + MergedPatternLibrary, + PatternLibrary, + SlotBinding, + SynthesisConfig, + eligible_archetypes, + inspect_payload_pointers, +) +import pytest + +from ..conformance.conformance_helpers import load_conformance_yaml +from .layout_fixtures import ScriptedAnswers, ScriptedValue + +CASES: list[dict[str, Any]] = load_conformance_yaml("agent/decision/archetypes.yaml") + + +def _two_component_catalog() -> Catalog: + """Two-component domain catalog (`TelemetryBadge`, `AlertFrame`).""" + return Catalog.from_json({ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "catalogId": "https://example.com/catalogs/telemetry/v1/catalog.json", + "protocolVersion": "1.0", + "components": { + "TelemetryBadge": { + "type": "object", + "properties": { + "component": {"const": "TelemetryBadge"}, + "metric": {"$ref": "common_types.json#/$defs/DynamicString"}, + }, + "required": ["component", "metric"], + }, + "AlertFrame": { + "type": "object", + "properties": { + "component": {"const": "AlertFrame"}, + "child": {"$ref": "common_types.json#/$defs/ComponentId"}, + }, + "required": ["component", "child"], + }, + }, + "functions": {}, + }) + + +def _coerce_scripted(raw: Mapping[str, Any]) -> dict[str, ScriptedValue]: + """Converts YAML list pairs `[choice, prob]` into `(choice, prob)` tuples.""" + out: dict[str, ScriptedValue] = {} + for k, v in raw.items(): + if isinstance(v, list) and len(v) == 2: + out[k] = (str(v[0]), float(v[1])) + else: + out[k] = v + return out + + +def _slot_from_spec(spec: Mapping[str, Any]) -> SlotBinding: + """Builds a `SlotBinding` from a YAML slot dict.""" + if "items" in spec: + items = tuple( + { + field_name: _slot_from_spec(field_spec) + for field_name, field_spec in item.items() + } + for item in spec["items"] + ) + return SlotBinding(items=items) + return SlotBinding( + pointer=spec.get("pointer"), + literal=spec.get("literal"), + ) + + +def _run_grammar_case(expect: Mapping[str, Any]) -> None: + grammar = ArchetypeGrammar.default() + assert grammar.version == expect["version"] + assert list(grammar.families()) == expect["families"] + assert len(grammar.archetypes) == expect["archetype_count"] + assert len(grammar.blocks) == expect["block_count"] + + +def _run_eligibility_case(case: Mapping[str, Any]) -> None: + args = case["args"] + expect = case["expect"] + grammar = ArchetypeGrammar.default() + catalog = ( + BasicCatalog("v1.0") + if args["catalog"] == "basic_v1" + else _two_component_catalog() + ) + lib = MergedPatternLibrary.for_catalogs([catalog]) + pointers = inspect_payload_pointers( + case["input"], mutable_paths=args.get("mutable_paths", ()) + ) + actual_ids = [a.id for a in eligible_archetypes(grammar, lib, pointers)] + if "exact_archetypes" in expect: + assert actual_ids == expect["exact_archetypes"] + if "contains_archetypes" in expect: + for arch_id in expect["contains_archetypes"]: + assert arch_id in actual_ids + + +def _run_plan_case(case: Mapping[str, Any]) -> None: + args = case["args"] + expect = case["expect"] + grammar = ArchetypeGrammar.default() + lib = MergedPatternLibrary.for_catalogs([BasicCatalog("v1.0")]) + planner = LayoutPlanner(grammar, SynthesisConfig(), capabilities=lib) + pointers = inspect_payload_pointers( + case["input"], mutable_paths=args.get("mutable_paths", ()) + ) + batch, state = planner.build_batch( + intent=args["intent"], + pointers=pointers, + payload=case["input"], + ) + sa = ScriptedAnswers(answers=_coerce_scripted(args["scripted_answers"])) + answers = asyncio.run(sa.backend().answer(batch)) + outcome = planner.read(state, answers) + assert outcome.reason == expect["reason"] + if expect["reason"] != "planned": + assert outcome.plan is None + return + assert outcome.plan is not None + plan = outcome.plan + assert plan.family == expect["family"] + assert plan.archetype == expect["archetype"] + assert list(plan.block_ids()) == expect["blocks"] + assert plan.actions_allowed is expect["actions_allowed"] + by_id = {b.block_id: dict(b.variant_knobs) for b in plan.blocks} + for block_id, expected_knobs in expect.get("block_knobs", {}).items(): + for knob_k, knob_v in expected_knobs.items(): + assert by_id[block_id].get(knob_k) == knob_v + + +def _run_expand_block_case(case: Mapping[str, Any]) -> None: + args = case["args"] + cat = BasicCatalog("v1.0") + expander = PatternExpander( + MergedPatternLibrary.for_catalogs([cat]), CatalogDecisionGraph([cat]) + ) + slots = { + slot_name: _slot_from_spec(slot_spec) + for slot_name, slot_spec in args.get("slots", {}).items() + } + components = expander.expand_block( + args["block_id"], + args["pattern"], + BlockBindings(slots=slots), + knobs=args.get("knobs"), + ) + assert components == case["expect"] + + +@pytest.mark.parametrize("case", CASES, ids=lambda c: c["name"]) +def test_layout_conformance(case: Mapping[str, Any]) -> None: + """Executes one case from `conformance/agent/decision/archetypes.yaml`.""" + kind = case["args"]["kind"] + if kind == "grammar": + _run_grammar_case(case["expect"]) + elif kind == "eligibility": + _run_eligibility_case(case) + elif kind == "plan": + _run_plan_case(case) + elif kind == "expand_block": + _run_expand_block_case(case) + else: + pytest.fail(f"Unknown conformance case kind: {kind!r}") diff --git a/python/a2ui_agent/tests/decision/test_layout_e2e.py b/python/a2ui_agent/tests/decision/test_layout_e2e.py new file mode 100644 index 0000000000..3df76d028b --- /dev/null +++ b/python/a2ui_agent/tests/decision/test_layout_e2e.py @@ -0,0 +1,667 @@ +# 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. + +"""End-to-end tests for archetype layout planning, expansion, and integration.""" + +from __future__ import annotations + +import asyncio +import copy +import json +import os +import statistics +import time +from typing import Any + +from a2ui.core import A2uiValidationError, Catalog +from a2ui.core.basic_catalog import BasicCatalog +from a2ui.inference_formats.decision import ( + ArchetypeGrammar, + BatchingDecisionBackend, + BlockBindings, + CatalogDecisionGraph, + DecisionAnswer, + DecisionBatch, + DecisionDistribution, + DecisionFormatFactory, + DecisionQuery, + DecisionRenderTool, + DecisionSynthesizer, + DeterministicMockBackend, + FallbackSource, + MergedPatternLibrary, + PatternExpander, + PatternLibrary, + SlotBinding, + SynthesisConfig, + SynthesisStage, + eligible_archetypes, + inspect_payload_pointers, +) +from a2ui.parser import A2uiPart +from a2ui.parser.messages import to_message_dicts +from a2ui.processor import A2uiRequestProcessor, CatalogConfig +from a2ui.utils import validate_payload +import httpx +import pytest + +from .layout_fixtures import ( + HOST, + RESORT, + ScriptedAnswers, + ScriptedValue, + SETTINGS, + TRANSFER, +) + +RESORT_SCRIPTED: dict[str, ScriptedValue] = { + "family": ("inspect", 0.80), + "stakes": 0.2, + "urgency": 0.1, + "archetype:inspect": ("detail", 0.85), + "gate:picture": 0.90, + "gate:banner": 0.10, + "gate:headline": 0.80, + "gate:prose": 0.90, + "gate:facts": 0.40, + "gate:collection": 0.85, + "gate:actions": 0.30, + "anatomy:picture.framing": ("banner", 0.80), + "anatomy:picture.prominence": 2.2, + "anatomy:collection.layout": ("reel", 0.70), + "anatomy:collection.leading": ("thumbnail", 0.80), + "anatomy:collection.trailing": ("none", 0.80), + "salience:/rating": 2.4, + "salience:/priceFrom": 2.6, +} + +HOST_SCRIPTED: dict[str, ScriptedValue] = { + "family": ("monitor", 0.90), + "stakes": 1.0, + "urgency": 1.4, + "archetype:monitor": ("dashboard", 0.85), + "gate:banner": 0.80, + "gate:headline": 0.90, + "gate:facts": 0.80, + "anatomy:headline.deltas": 0.85, + "salience:/cpu": 2.8, + "salience:/status": 2.1, + "salience:/uptimeHours": 1.2, + "salience:/host": 0.4, + "instance:banner.tone:/status": ("warning", 0.90), + "instance:headline.news:/cpu": ("bad", 0.85), + "instance:headline.state_tone:/status": ("warning", 0.80), +} + +TRANSFER_BASE_SCRIPTED: dict[str, ScriptedValue] = { + "family": ("act", 0.85), + "stakes": 2.1, + "urgency": 0.6, + "gate:banner": 0.20, + "gate:prose": 0.45, + "gate:facts": 0.85, + "gate:actions": 0.90, + "instance:actions.primary:/actions": ("Send", 0.90), + "instance:actions.destructive:0": 0.80, + "instance:actions.destructive:1": 0.10, + "salience:/amount": 2.9, + "salience:/recipient": 2.6, + "salience:/fee": 1.9, + "salience:/arrives": 1.7, +} + +SETTINGS_BASE_SCRIPTED: dict[str, ScriptedValue] = { + "family": ("input", 0.80), + "stakes": 1.2, + "urgency": 0.2, + "gate:groups": 0.90, + "gate:actions": 0.20, + "instance:groups.row_kind:/playback/skipForward": ("value", 0.90), + "instance:groups.row_kind:/playback/autoDownload": ("switch", 0.95), + "instance:groups.row_kind:/playback/speed": ("value", 0.70), + "instance:groups.row_kind:/notifications/newEpisodes": ("switch", 0.90), + "instance:groups.row_kind:/notifications/digest": ("switch", 0.90), + "instance:groups.row_kind:/account/signOut": ("danger", 0.90), +} + + +def _extract_components(messages: Any) -> list[dict[str, Any]]: + """Returns the `updateComponents.components` list from `messages`.""" + for d in to_message_dicts(messages): + if "updateComponents" in d: + return list(d["updateComponents"]["components"]) + return [] + + +@pytest.mark.parametrize("version", ["v0.9", "v1.0"]) +@pytest.mark.asyncio +async def test_resort_e2e_v09_and_v10_and_logo_page_mark(version: str) -> None: + """Worked example 1 (`RESORT`): validates v0.9/v1.0 messages, logo page_mark, and $repeat.""" + catalog = BasicCatalog(version) + sa = ScriptedAnswers(answers=RESORT_SCRIPTED) + synth = DecisionSynthesizer([catalog], sa.backend()) + + out = await synth.synthesize(RESORT.intent, RESORT.payload) + assert out.stage == SynthesisStage.ARCHETYPE + assert out.layout_plan is not None + assert out.layout_plan.archetype == "detail" + assert list(out.layout_plan.block_ids()) == [ + "picture", + "headline", + "prose", + "collection", + ] + validate_payload([catalog], out.messages) + + components = _extract_components(out.messages) + by_id = {c["id"]: c for c in components} + assert "page_mark" in by_id + assert by_id["page_mark"]["component"] == "Image" + + reel_comp = by_id["collection_reel"] + assert reel_comp["children"] == { + "path": "/photos", + "componentId": "collection_item", + } + if version == "v0.9": + assert by_id["page_mark"]["url"] == {"path": "/logoUrl"} + else: + assert by_id["page_mark"]["url"] == {"@path": "/logoUrl"} + + +@pytest.mark.parametrize("version", ["v0.9", "v1.0"]) +@pytest.mark.asyncio +async def test_host_dashboard_e2e_v09_and_v10(version: str) -> None: + """Worked example 2 (`HOST`): `monitor -> dashboard` validates on v0.9 and v1.0.""" + catalog = BasicCatalog(version) + sa = ScriptedAnswers(answers=HOST_SCRIPTED) + synth = DecisionSynthesizer([catalog], sa.backend()) + + out = await synth.synthesize(HOST.intent, HOST.payload) + assert out.stage == SynthesisStage.ARCHETYPE + assert out.layout_plan is not None + assert out.layout_plan.archetype == "dashboard" + assert list(out.layout_plan.block_ids()) == ["banner", "headline", "facts"] + validate_payload([catalog], out.messages) + + +@pytest.mark.parametrize("version", ["v0.9", "v1.0"]) +@pytest.mark.asyncio +async def test_transfer_action_gate_blocks_080_commits_090_and_boundary_0875( + version: str, +) -> None: + """Worked example 3 (`TRANSFER`): abstains at 0.80, renders at 0.90, exact boundary 0.875.""" + catalog = BasicCatalog(version) + + # 0.80 < 0.875: abstains, and fallback_card never emits the refused Button. + sa_low = ScriptedAnswers( + answers={**TRANSFER_BASE_SCRIPTED, "archetype:act": ("confirm", 0.80)} + ) + synth_low = DecisionSynthesizer([catalog], sa_low.backend(), fallback_card=True) + out_low = await synth_low.synthesize( + TRANSFER.intent, TRANSFER.payload, mutable_paths=TRANSFER.mutable_paths + ) + assert out_low.stage == SynthesisStage.ABSTAIN_FALLBACK + assert out_low.fallback_source is FallbackSource.CARD + assert any(r.outcome == "action_gate" for r in out_low.trace) + card_comps = _extract_components(out_low.messages) + assert all(c["component"] != "Button" for c in card_comps) + + # 0.90 >= 0.875: commits and renders `confirm` with `facts` and `actions`. + sa_high = ScriptedAnswers( + answers={**TRANSFER_BASE_SCRIPTED, "archetype:act": ("confirm", 0.90)} + ) + synth_high = DecisionSynthesizer([catalog], sa_high.backend()) + out_high = await synth_high.synthesize( + TRANSFER.intent, TRANSFER.payload, mutable_paths=TRANSFER.mutable_paths + ) + assert out_high.stage == SynthesisStage.ARCHETYPE + assert out_high.layout_plan is not None + assert out_high.layout_plan.archetype == "confirm" + assert list(out_high.layout_plan.block_ids()) == ["facts", "actions"] + validate_payload([catalog], out_high.messages) + high_comps = _extract_components(out_high.messages) + assert any(c["component"] == "Button" for c in high_comps) + + # Exact gate boundary for stakes 2.1 (gate = 0.875): >= passes, < abstains. + sa_exact = ScriptedAnswers( + answers={**TRANSFER_BASE_SCRIPTED, "archetype:act": ("confirm", 0.875)} + ) + out_exact = await DecisionSynthesizer([catalog], sa_exact.backend()).synthesize( + TRANSFER.intent, TRANSFER.payload, mutable_paths=TRANSFER.mutable_paths + ) + assert out_exact.stage == SynthesisStage.ARCHETYPE + + sa_below = ScriptedAnswers( + answers={**TRANSFER_BASE_SCRIPTED, "archetype:act": ("confirm", 0.874)} + ) + out_below = await DecisionSynthesizer([catalog], sa_below.backend()).synthesize( + TRANSFER.intent, TRANSFER.payload, mutable_paths=TRANSFER.mutable_paths + ) + assert out_below.stage == SynthesisStage.ABSTAIN_FALLBACK + assert out_below.messages == [] + + +@pytest.mark.parametrize("version", ["v0.9", "v1.0"]) +@pytest.mark.asyncio +async def test_settings_toggles_live_at_085_and_degraded_below_080( + version: str, +) -> None: + """Worked example 4 (`SETTINGS`): toggles live at 0.85, degraded to read-only below 0.80.""" + catalog = BasicCatalog(version) + + sa_live = ScriptedAnswers( + answers={ + **SETTINGS_BASE_SCRIPTED, + "archetype:input": ("settings", 0.85), + } + ) + out_live = await DecisionSynthesizer([catalog], sa_live.backend()).synthesize( + SETTINGS.intent, SETTINGS.payload, mutable_paths=SETTINGS.mutable_paths + ) + assert out_live.stage == SynthesisStage.ARCHETYPE + validate_payload([catalog], out_live.messages) + live_types = {c["component"] for c in _extract_components(out_live.messages)} + assert "CheckBox" in live_types + assert "Button" in live_types + + sa_deg = ScriptedAnswers( + answers={ + **SETTINGS_BASE_SCRIPTED, + "archetype:input": ("settings", 0.75), + } + ) + out_deg = await DecisionSynthesizer([catalog], sa_deg.backend()).synthesize( + SETTINGS.intent, SETTINGS.payload, mutable_paths=SETTINGS.mutable_paths + ) + assert out_deg.stage == SynthesisStage.ARCHETYPE + validate_payload([catalog], out_deg.messages) + deg_types = {c["component"] for c in _extract_components(out_deg.messages)} + assert "CheckBox" not in deg_types + assert "Button" not in deg_types + + +@pytest.mark.asyncio +async def test_use_archetypes_false_and_container_only_catalog_abstention() -> None: + """`use_archetypes=False` reproduces flat output; container-only catalog abstains.""" + basic = BasicCatalog("v1.0") + flat_synth = DecisionSynthesizer( + [basic], + DeterministicMockBackend(scripted={"root_component": {"Text": 0.92}}), + config=SynthesisConfig(use_archetypes=False), + ) + flat_out = await flat_synth.synthesize("Show resort name", {"name": "Casa Verde"}) + assert flat_out.stage == SynthesisStage.FAST_1PASS_LEAF + assert flat_out.layout_plan is None + assert flat_out.trace == () + validate_payload([basic], flat_out.messages) + + container_only_cat = Catalog.from_json({ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "catalogId": "https://example.com/catalogs/container_only/v1", + "protocolVersion": "1.0", + "components": { + "OuterBox": { + "type": "object", + "properties": { + "component": {"const": "OuterBox"}, + "childId": {"$ref": "common_types.json#/$defs/ComponentId"}, + }, + "required": ["component", "childId"], + }, + }, + }) + container_synth = DecisionSynthesizer( + [container_only_cat], + DeterministicMockBackend(scripted={"root_component": {"OuterBox": 0.90}}), + fallback_card=True, + ) + container_out = await container_synth.synthesize( + "Show outer box", {"title": "hello"} + ) + assert container_out.stage == SynthesisStage.ABSTAIN_FALLBACK + assert container_out.messages == [] + assert ( + container_out.trace + and container_out.trace[0].outcome == "no eligible archetype" + ) + + +def test_format_factory_through_request_processor_with_layout_brief() -> None: + """`DecisionFormatFactory` through `A2uiRequestProcessor` compiles a block with `layout`.""" + catalog = BasicCatalog("v1.0") + sa = ScriptedAnswers(answers=RESORT_SCRIPTED) + factory = DecisionFormatFactory(backend=sa.backend()) + processor = A2uiRequestProcessor( + catalogs=[catalog], + format_factory=factory, + ) + + decision_json = json.dumps({ + "intent": RESORT.intent, + "payload": RESORT.payload, + "layout": ["headline:priceFrom,rating", "prose:about"], + }) + raw_response = f"Here is the resort overview:\n{decision_json}" + parts = processor.parse_response(raw_response) + a2ui_parts = [p for p in parts if isinstance(p, A2uiPart)] + assert len(a2ui_parts) == 1 + validate_payload([catalog], a2ui_parts[0].a2ui) + + +def test_render_tool_run_sync_with_layout_and_trace() -> None: + """`DecisionRenderTool.run_sync` parses `layout` and returns `layoutPlan` and `trace`.""" + catalog = BasicCatalog("v1.0") + sa = ScriptedAnswers(answers=RESORT_SCRIPTED) + synth = DecisionSynthesizer([catalog], sa.backend()) + tool = DecisionRenderTool(synth, include_trace=True) + + schema = tool.parameters_json_schema() + assert "layout" in schema["properties"] + assert schema["properties"]["layout"]["maxItems"] == 6 + + out = tool.run_sync({ + "intent": RESORT.intent, + "payload": RESORT.payload, + "layout": ["headline:priceFrom,rating", "prose:about"], + }) + assert out.stage == SynthesisStage.ARCHETYPE + result = tool.format_result(out) + assert "archetype" in result["stage"].lower() + assert result["layoutPlan"] == { + "archetype": "detail", + "blocks": ["picture", "headline", "prose", "collection"], + } + assert isinstance(result["trace"], list) and len(result["trace"]) > 0 + assert result["trace"][0]["questionId"] == "family" + + +@pytest.mark.asyncio +async def test_single_answer_call_per_surface_and_two_with_forced_reask() -> None: + """Verifies a single `backend.answer` call normally and two calls when `needs_reask` fires.""" + catalog = BasicCatalog("v1.0") + answer_calls = 0 + + class CountingBackend(DeterministicMockBackend): + + async def answer(self, batch: DecisionBatch) -> tuple[DecisionAnswer, ...]: + nonlocal answer_calls + answer_calls += 1 + return await super().answer(batch) + + sa_normal = ScriptedAnswers(answers=HOST_SCRIPTED) + normal_backend = CountingBackend(scorer=sa_normal.scorer) + synth_normal = DecisionSynthesizer([catalog], normal_backend) + out_normal = await synth_normal.synthesize(HOST.intent, HOST.payload) + assert out_normal.stage == SynthesisStage.ARCHETYPE + assert answer_calls == 1 + + # Forced re-ask: set `family` winning probability to 0.52 (< reask_below=0.55) + # on the first call, and 0.92 on the second call. + answer_calls = 0 + low_family_scripted = { + **HOST_SCRIPTED, + "family": ("monitor", 0.52), + } + sa_reask = ScriptedAnswers(answers=low_family_scripted) + + class ReaskBackend(DeterministicMockBackend): + + async def answer(self, batch: DecisionBatch) -> tuple[DecisionAnswer, ...]: + nonlocal answer_calls + answer_calls += 1 + if batch.shared_context.get("reask"): + sa_reask.answers = {**HOST_SCRIPTED, "family": ("monitor", 0.92)} + return await super().answer(batch) + + reask_backend = ReaskBackend(scorer=sa_reask.scorer) + synth_reask = DecisionSynthesizer( + [catalog], + reask_backend, + config=SynthesisConfig(threshold_overrides={"reask_below": 0.55}), + ) + out_reask = await synth_reask.synthesize(HOST.intent, HOST.payload) + assert out_reask.stage == SynthesisStage.ARCHETYPE + assert answer_calls == 2 + + +@pytest.mark.asyncio +async def test_edge_cases_empty_identifiers_60_pointers_and_bad_answers() -> None: + """Covers empty/identifier-only payloads, 60-pointer cap, and malformed backend answers.""" + catalog = BasicCatalog("v1.0") + grammar = ArchetypeGrammar.default() + lib = MergedPatternLibrary.for_catalogs([catalog]) + + # 1. Empty payload: no eligible archetypes, abstains cleanly. + sa = ScriptedAnswers(answers=HOST_SCRIPTED) + synth = DecisionSynthesizer([catalog], sa.backend()) + empty_out = await synth.synthesize("Show empty", {}) + assert empty_out.stage == SynthesisStage.ABSTAIN_FALLBACK + assert empty_out.messages == [] + + # Identifier-only payload: `headline` and `collection` shape-excluded. + id_ptrs = inspect_payload_pointers({ + "id": "usr_12345", + "uuid": "550e8400-e29b-41d4-a716-446655440000", + }) + el_ids = {a.id for a in eligible_archetypes(grammar, lib, id_ptrs)} + assert "dashboard" not in el_ids + assert "feed" not in el_ids + + # 2. Payload with 60 pointers: salience questions capped by `max_pairs`. + big_payload = {f"price_{i:02d}": float(i) for i in range(60)} + big_ptrs = inspect_payload_pointers(big_payload) + batch, state = synth.planner.build_batch( + "Show 60 prices", big_ptrs, payload=big_payload + ) + assert batch.pair_count() <= SynthesisConfig().max_pairs + assert state.budget_exhausted is True + + # 3. Backend returning fewer answers or an unknown question id: + # planner raises A2uiValidationError, synthesizer falls back to flat path and records in trace. + class TruncatedAnswerBackend(DeterministicMockBackend): + + async def answer(self, batch: DecisionBatch) -> tuple[DecisionAnswer, ...]: + full = await super().answer(batch) + return full[:-1] + + trunc_synth = DecisionSynthesizer( + [catalog], + TruncatedAnswerBackend(scripted={"root_component": {"Text": 0.92}}), + ) + trunc_out = await trunc_synth.synthesize(HOST.intent, HOST.payload) + assert trunc_out.stage in ( + SynthesisStage.FAST_1PASS_LEAF, + SynthesisStage.CONTAINER_2PASS, + ) + assert any( + "Answer count mismatch" in r.outcome + or "Missing answers" in r.outcome + or "validation_error" in r.outcome + for r in trunc_out.trace + ) + + class UnknownIdAnswerBackend(DeterministicMockBackend): + + async def answer(self, batch: DecisionBatch) -> tuple[DecisionAnswer, ...]: + full = list(await super().answer(batch)) + full[0] = DecisionAnswer( + question_id="unknown_question_id", + distribution=full[0].distribution, + ) + return tuple(full) + + unk_synth = DecisionSynthesizer( + [catalog], + UnknownIdAnswerBackend(scripted={"root_component": {"Text": 0.92}}), + ) + unk_out = await unk_synth.synthesize(HOST.intent, HOST.payload) + assert any("unknown_question_id" in r.outcome for r in unk_out.trace) + + +@pytest.mark.asyncio +async def test_batching_backend_timeout_propagates_to_all_waiters() -> None: + """`BatchingDecisionBackend` propagates backend timeout exceptions to every concurrent waiter.""" + + class TimeoutBackend(DeterministicMockBackend): + + async def answer(self, batch: DecisionBatch) -> tuple[DecisionAnswer, ...]: + await asyncio.sleep(0.01) + raise httpx.ReadTimeout("Decision backend timed out") + + batched = BatchingDecisionBackend(TimeoutBackend(), window_ms=5.0) + q = DecisionQuery( + task="family", + prompt="Show host", + candidates=("monitor", "inspect"), + ) + + with pytest.raises(httpx.ReadTimeout): + await asyncio.gather(batched.predict(q), batched.predict(q)) + await batched.aclose() + + +@pytest.mark.asyncio +async def test_required_block_wins_multi_catalog_markdown_escape_and_brief_warning() -> ( + None +): + """Covers required-block-wins trace, multi-catalog precedence, markdown escaping, and brief warnings.""" + catalog = BasicCatalog("v1.0") + + # 1. Required block gated `no` (`headline` at 0.20 on `dashboard`) + disallowed brief section (`compose:host`). + scripted = { + **HOST_SCRIPTED, + "gate:headline": 0.20, + } + sa = ScriptedAnswers(answers=scripted) + synth = DecisionSynthesizer([catalog], sa.backend()) + out = await synth.synthesize( + HOST.intent, + HOST.payload, + layout=["compose:host", "facts:uptimeHours,host"], + ) + assert out.stage == SynthesisStage.ARCHETYPE + assert out.layout_plan is not None + assert "headline" in out.layout_plan.block_ids() + assert any( + r.question.id == "gate:headline" and "required_override" in r.outcome + for r in out.trace + ) + assert any( + r.question.id == "brief:compose" and "ignored_brief_block" in r.outcome + for r in out.trace + ) + + # 2. Markdown heading in `$text` when slot value contains `#` or newlines: escaped. + expander = PatternExpander( + MergedPatternLibrary.for_catalogs([catalog]), + CatalogDecisionGraph([catalog]), + ) + prose_comps = expander.expand_block( + "prose", + "prose", + BlockBindings( + slots={ + "heading": SlotBinding(literal="Section #1\nSubheading"), + "body": SlotBinding(literal="Body text"), + } + ), + knobs={"length": "blurb"}, + ) + heading_comp = next(c for c in prose_comps if c["id"] == "prose_heading") + assert "\n" not in heading_comp["text"] + assert r"\#1" in heading_comp["text"] + + # 3. Multi-catalog surface: primary catalog wins on duplicate pattern name, + # and expansion ids carry the catalog-qualified block prefix. + secondary_cat = Catalog.from_json({ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "catalogId": "https://example.com/catalogs/domain_sec/v1/catalog.json", + "protocolVersion": "1.0", + "components": { + "DomainBanner": { + "type": "object", + "properties": { + "component": {"const": "DomainBanner"}, + "title": {"$ref": "common_types.json#/$defs/DynamicString"}, + }, + "required": ["component", "title"], + }, + }, + }) + basic_lib = MergedPatternLibrary.for_catalogs([catalog]).libraries[0] + sec_lib = PatternLibrary.from_json({ + "version": "1", + "catalogIds": [secondary_cat.catalog_id], + "patterns": { + "banner": { + "slots": ["title"], + "root": "sec_banner", + "components": [{ + "id": "sec_banner", + "component": "DomainBanner", + "title": {"$slot": "title"}, + }], + }, + }, + }) + merged = MergedPatternLibrary([basic_lib, sec_lib]) + assert merged.owner_catalog_id("banner") == basic_lib.catalog_id + + multi_synth = DecisionSynthesizer( + [catalog, secondary_cat], + ScriptedAnswers(answers=HOST_SCRIPTED).backend(), + patterns=merged, + ) + multi_out = await multi_synth.synthesize(HOST.intent, HOST.payload) + assert multi_out.stage == SynthesisStage.ARCHETYPE + validate_payload([catalog, secondary_cat], multi_out.messages) + multi_comps = _extract_components(multi_out.messages) + assert any(c["id"].startswith("basic_") for c in multi_comps) + assert all("catalogId" in c for c in multi_comps) + + +@pytest.mark.skipif( + not os.environ.get("A2UI_DECISION_BENCH"), + reason=( + "Set A2UI_DECISION_BENCH=1 to run the layout planning + expansion" + " micro-benchmark." + ), +) +@pytest.mark.asyncio +async def test_resort_planning_and_expansion_micro_benchmark() -> None: + """Planning plus expansion for the resort fixture completes in under 10 ms median.""" + catalog = BasicCatalog("v1.0") + sa = ScriptedAnswers(answers=RESORT_SCRIPTED) + backend = sa.backend() + synth = DecisionSynthesizer([catalog], backend) + pointers = inspect_payload_pointers(RESORT.payload) + elig = eligible_archetypes(synth.archetypes, synth.patterns, pointers) + + samples_ms: list[float] = [] + for _ in range(25): + start = time.perf_counter() + batch, state = synth.planner.build_batch( + RESORT.intent, pointers, eligible=elig, payload=RESORT.payload + ) + answers = await backend.answer(batch) + outcome = synth.planner.read(state, answers) + assert outcome.plan is not None + components = synth._expand_plan(outcome.plan) + elapsed_ms = (time.perf_counter() - start) * 1000.0 + assert len(components) > 0 + samples_ms.append(elapsed_ms) + + median_ms = statistics.median(samples_ms) + assert median_ms < 10.0, f"Median latency {median_ms:.2f} ms exceeded 10 ms" diff --git a/python/a2ui_agent/tests/decision/test_layout_planner.py b/python/a2ui_agent/tests/decision/test_layout_planner.py new file mode 100644 index 0000000000..8813a409a3 --- /dev/null +++ b/python/a2ui_agent/tests/decision/test_layout_planner.py @@ -0,0 +1,1049 @@ +# 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. + +"""Unit tests for the layout planner, grammar rules, and structural lint.""" + +from __future__ import annotations + +import asyncio +from collections.abc import Mapping +from dataclasses import dataclass, field, replace +from typing import Any + +from a2ui.core import A2uiValidationError +from a2ui.inference_formats.decision import ( + SynthesisConfig, + inspect_payload_pointers, +) +from a2ui.inference_formats.decision.archetypes import ArchetypeGrammar +from a2ui.inference_formats.decision.layout_lint import ( + LintFinding, + lint_components, +) +from a2ui.inference_formats.decision.layout_planner import ( + LayoutPlanner, + PlannerState, + apply_actions_gate, + apply_at_least, + apply_catalog_eligibility, + apply_fallback_must_end, + apply_leading_all_or_none, + apply_no_empty_container, + apply_one_primary_action, + apply_pictures_need_a_look, + apply_pointer_once_per_region, + apply_required_block_wins, + apply_urgency_terse, +) +from a2ui.inference_formats.decision.models import ( + BlockBindings, + DecisionAnswer, + DecisionDistribution, + LayoutBrief, + LayoutPlan, + PageBindings, + PatternCapabilities, + PlannedBlock, + PlanOutcome, + PlanReason, + SlotBinding, +) +import pytest + +from .layout_fixtures import ( + HOST, + LayoutFixture, + RESORT, + ScriptedAnswers, + ScriptedValue, + SETTINGS, + TRANSFER, +) + + +@dataclass(frozen=True) +class StubCapabilities: + """Stub `PatternCapabilities` implementation for planner tests.""" + + disabled: frozenset[tuple[str, str | None]] = field(default_factory=frozenset) + + def has_pattern(self, name: str, variant: str | None = None) -> bool: + if (name, None) in self.disabled: + return False + return (name, variant) not in self.disabled + + +def _run_fixture( + fixture: LayoutFixture, + scripted: Mapping[str, ScriptedValue], + *, + config: SynthesisConfig | None = None, + brief: LayoutBrief | None = None, + capabilities: PatternCapabilities | None = None, +) -> tuple[ + LayoutPlanner, + PlannerState, + tuple[DecisionAnswer, ...], + PlanOutcome, + ScriptedAnswers, +]: + """Builds a batch for `fixture`, answers via `ScriptedAnswers`, and reads.""" + grammar = ArchetypeGrammar.default() + cfg = config or SynthesisConfig() + planner = LayoutPlanner(grammar, cfg, capabilities=capabilities) + pointers = inspect_payload_pointers( + fixture.payload, mutable_paths=fixture.mutable_paths + ) + batch, state = planner.build_batch( + intent=fixture.intent, + pointers=pointers, + brief=brief, + payload=fixture.payload, + ) + sa = ScriptedAnswers(answers=scripted) + answers = asyncio.run(sa.backend().answer(batch)) + outcome = planner.read(state, answers) + return planner, state, answers, outcome, sa + + +def test_resort_detail_worked_example() -> None: + """Worked example 1 (`RESORT`): `inspect -> detail` with gallery reel.""" + scripted: dict[str, ScriptedValue] = { + "family": ("inspect", 0.80), + "stakes": 0.2, + "urgency": 0.1, + "archetype:inspect": ("detail", 0.85), + "gate:picture": 0.90, + "gate:banner": 0.10, + "gate:headline": 0.80, + "gate:prose": 0.90, + "gate:facts": 0.40, + "gate:collection": 0.85, + "gate:actions": 0.30, + "anatomy:picture.framing": ("banner", 0.80), + "anatomy:picture.prominence": 2.2, + "anatomy:collection.layout": ("reel", 0.70), + "anatomy:collection.leading": ("thumbnail", 0.80), + "anatomy:collection.trailing": ("none", 0.80), + "salience:/rating": 2.4, + "salience:/priceFrom": 2.6, + } + _, state, _, outcome, sa = _run_fixture(RESORT, scripted) + + assert "gate:media" not in sa.asked + assert state.batch.pair_count() <= SynthesisConfig().max_pairs + + assert outcome.reason == "planned" + assert outcome.plan is not None + plan = outcome.plan + assert plan.family == "inspect" + assert plan.archetype == "detail" + assert plan.page.title.pointer == "/name" + assert plan.page.mark.pointer == "/logoUrl" + + assert list(plan.block_ids()) == [ + "picture", + "headline", + "prose", + "collection", + ] + by_id = {b.block_id: b for b in plan.blocks} + + pic = by_id["picture"] + assert pic.bindings.get("picture") == SlotBinding(pointer="/photos/0/url") + assert pic.variant_knobs.get("framing") == "banner" + assert pic.variant_knobs.get("prominence") == "leading" + + headline = by_id["headline"] + hl_items = headline.bindings.get("items") + assert hl_items is not None + assert [it["value"].pointer for it in hl_items.items] == [ + "/priceFrom", + "/rating", + ] + + prose = by_id["prose"] + assert prose.bindings.get("body") == SlotBinding(pointer="/about") + assert prose.variant_knobs.get("length") == "blurb" + + collection = by_id["collection"] + assert collection.variant_knobs.get("layout") == "reel" + col_items = collection.bindings.get("items") + assert col_items is not None + assert col_items.pointer == "/photos" + assert col_items.fields["picture"] == SlotBinding(pointer="url") + assert col_items.fields["headline"] == SlotBinding(pointer="caption") + + +def test_host_dashboard_worked_example() -> None: + """Worked example 2 (`HOST`): `monitor -> dashboard` with banner, headline, facts.""" + scripted: dict[str, ScriptedValue] = { + "family": ("monitor", 0.90), + "stakes": 1.0, + "urgency": 1.4, + "archetype:monitor": ("dashboard", 0.85), + "gate:banner": 0.80, + "gate:headline": 0.90, + "gate:facts": 0.80, + "salience:/cpu": 2.8, + "salience:/status": 2.1, + "salience:/uptimeHours": 1.2, + "salience:/host": 0.4, + "instance:banner.tone:/status": ("warning", 0.90), + "instance:headline.news:/cpu": ("bad", 0.85), + "instance:headline.state_tone:/status": ("warning", 0.80), + } + _, _, _, outcome, sa = _run_fixture(HOST, scripted) + + assert "gate:chart" not in sa.asked + assert "gate:collection" not in sa.asked + assert "salience:/cpuDelta" not in sa.asked + + assert outcome.reason == "planned" + assert outcome.plan is not None + plan = outcome.plan + assert plan.family == "monitor" + assert plan.archetype == "dashboard" + assert list(plan.block_ids()) == ["banner", "headline", "facts"] + + by_id = {b.block_id: b for b in plan.blocks} + banner = by_id["banner"] + assert banner.bindings.get("title") == SlotBinding(pointer="/status") + assert banner.variant_knobs.get("tone") == "warning" + + headline = by_id["headline"] + hl_items = headline.bindings.get("items") + assert hl_items is not None + assert [it["value"].pointer for it in hl_items.items] == ["/cpu"] + assert hl_items.items[0]["delta"] == SlotBinding(pointer="/cpuDelta") + assert headline.instances.get("/cpu", {}).get("news") == "bad" + + facts = by_id["facts"] + rows = facts.bindings.get("rows") + assert rows is not None + assert [it["value"].pointer for it in rows.items] == [ + "/uptimeHours", + "/host", + ] + + +def test_transfer_confirm_action_gate_blocks_at_080_commits_at_090() -> None: + """Worked example 3 (`TRANSFER`): action gate at 0.875 blocks 0.80, passes 0.90.""" + base_scripted: dict[str, ScriptedValue] = { + "family": ("act", 0.85), + "stakes": 2.1, + "urgency": 0.6, + "gate:banner": 0.20, + "gate:prose": 0.45, + "gate:facts": 0.85, + "gate:actions": 0.90, + "instance:actions.primary:/actions": ("Send", 0.90), + "instance:actions.destructive:0": 0.80, + "instance:actions.destructive:1": 0.10, + "salience:/amount": 2.9, + "salience:/recipient": 2.6, + "salience:/fee": 1.9, + "salience:/arrives": 1.7, + } + + _, _, _, blocked, _ = _run_fixture( + TRANSFER, {**base_scripted, "archetype:act": ("confirm", 0.80)} + ) + assert blocked.reason == "action_gate" + assert blocked.plan is None + + _, _, _, committed, _ = _run_fixture( + TRANSFER, {**base_scripted, "archetype:act": ("confirm", 0.90)} + ) + assert committed.reason == "planned" + assert committed.plan is not None + plan = committed.plan + assert plan.family == "act" + assert plan.archetype == "confirm" + assert plan.actions_allowed is True + assert list(plan.block_ids()) == ["facts", "actions"] + + by_id = {b.block_id: b for b in plan.blocks} + facts = by_id["facts"] + rows = facts.bindings.get("rows") + assert rows is not None + assert [it["value"].pointer for it in rows.items] == [ + "/amount", + "/recipient", + "/fee", + "/arrives", + ] + + actions = by_id["actions"] + buttons = actions.bindings.get("buttons") + assert buttons is not None + assert [it["label"].literal for it in buttons.items] == ["Cancel", "Send"] + assert actions.instances["Send"]["primary"] == "false" + assert actions.instances["Send"]["destructive"] == "true" + assert actions.instances["Cancel"]["primary"] == "false" + + +def test_settings_worked_example_and_action_gate_degradation() -> None: + """Worked example 4 (`SETTINGS`): `input -> settings` at 0.85 and below 0.80.""" + base_scripted: dict[str, ScriptedValue] = { + "family": ("input", 0.80), + "stakes": 1.2, + "urgency": 0.2, + "gate:groups": 0.90, + "gate:actions": 0.20, + "instance:groups.row_kind:/playback/skipForward": ("value", 0.90), + "instance:groups.row_kind:/playback/autoDownload": ("switch", 0.95), + "instance:groups.row_kind:/playback/speed": ("value", 0.70), + "instance:groups.row_kind:/notifications/newEpisodes": ("switch", 0.90), + "instance:groups.row_kind:/notifications/digest": ("switch", 0.90), + "instance:groups.row_kind:/account/signOut": ("danger", 0.90), + } + + _, _, _, outcome, _ = _run_fixture( + SETTINGS, {**base_scripted, "archetype:input": ("settings", 0.85)} + ) + assert outcome.reason == "planned" + assert outcome.plan is not None + groups_block = outcome.plan.blocks[0] + assert groups_block.block_id == "groups" + groups_slot = groups_block.bindings.get("groups") + assert groups_slot is not None + assert len(groups_slot.items) == 3 + assert groups_block.instances["/playback/autoDownload"]["row_kind"] == "switch" + assert groups_block.instances["/account/signOut"]["row_kind"] == "danger" + + # Below 0.80 (at stakes 1.2, gate is 0.80): `actions_allowed` is False, + # so `danger` and `switch` rows degrade to read-only `value` rows. + _, _, _, degraded, _ = _run_fixture( + SETTINGS, {**base_scripted, "archetype:input": ("settings", 0.75)} + ) + assert degraded.reason == "planned" + assert degraded.plan is not None + deg_block = degraded.plan.blocks[0] + assert deg_block.instances["/account/signOut"]["row_kind"] == "value" + assert deg_block.instances["/playback/autoDownload"]["row_kind"] == "value" + + +def test_prior_archetypes_ordering() -> None: + """`prior_archetypes` puts brief-pinned first, then satisfied block count.""" + grammar = ArchetypeGrammar.default() + planner = LayoutPlanner(grammar, SynthesisConfig()) + pointers = inspect_payload_pointers( + TRANSFER.payload, mutable_paths=TRANSFER.mutable_paths + ) + eligible = grammar.archetypes + + unpinned = planner.prior_archetypes(eligible, pointers) + assert len(unpinned) == len(eligible) + + all_roles = set(grammar.families()) | set(grammar.blocks) + brief_family = LayoutBrief.parse(["input:amount"], roles=all_roles) + family_pinned = planner.prior_archetypes(eligible, pointers, brief=brief_family) + input_archs = {a.id for a in grammar.archetypes_in("input")} + assert {a.id for a in family_pinned[: len(input_archs)]} == input_archs + + brief_block = LayoutBrief.parse(["groups:amount"], roles=all_roles) + block_pinned = planner.prior_archetypes(eligible, pointers, brief=brief_block) + assert block_pinned[0].id == "settings" + + +def test_capabilities_filter_anatomy_options() -> None: + """Disabling `("collection", "grid")` removes `"grid"` from `collection.layout`.""" + caps = StubCapabilities(disabled=frozenset({("collection", "grid")})) + planner = LayoutPlanner( + ArchetypeGrammar.default(), SynthesisConfig(), capabilities=caps + ) + pointers = inspect_payload_pointers(RESORT.payload) + batch, _ = planner.build_batch( + intent=RESORT.intent, pointers=pointers, payload=RESORT.payload + ) + layout_q = next(q for q in batch.questions if q.id == "anatomy:collection.layout") + assert "grid" not in layout_q.options + assert "cards" in layout_q.options + assert "rows" in layout_q.options + + +def test_required_block_wins_records_disagreement_trace() -> None: + """A required `!` block with `gate: < 0.50` is kept and traced.""" + scripted: dict[str, ScriptedValue] = { + "family": ("monitor", 0.85), + "stakes": 0.5, + "urgency": 0.5, + "archetype:monitor": ("dashboard", 0.85), + "gate:headline": 0.20, + "gate:banner": 0.10, + "gate:facts": 0.80, + "salience:/cpu": 2.8, + "salience:/host": 2.0, + } + _, state, _, outcome, _ = _run_fixture(HOST, scripted) + assert outcome.reason == "planned" + assert outcome.plan is not None + assert "headline" in outcome.plan.block_ids() + assert any( + r.question.id == "gate:headline" and "required_override" in r.outcome + for r in state.trace + ) + + +def test_at_least_rule_tops_up_expected_blocks() -> None: + """`apply_at_least` adds expected `+` blocks when gated blocks are too few.""" + scripted: dict[str, ScriptedValue] = { + "family": ("inspect", 0.85), + "stakes": 0.5, + "urgency": 0.5, + "archetype:inspect": ("detail", 0.85), + "gate:picture": 0.10, + "gate:banner": 0.10, + "gate:headline": 0.20, + "gate:prose": 0.30, + "gate:facts": 0.25, + "gate:collection": 0.10, + "gate:actions": 0.10, + "salience:/rating": 2.4, + "salience:/priceFrom": 2.2, + } + _, _, _, outcome, _ = _run_fixture(RESORT, scripted) + assert outcome.reason == "planned" + assert outcome.plan is not None + assert list(outcome.plan.block_ids()) == ["prose", "facts"] + + +def test_budget_exhaustion_falls_back_to_heuristics() -> None: + """Exceeding `max_pairs` sets `budget_exhausted` and uses defaults for unasked.""" + cfg = SynthesisConfig(max_pairs=8) + _, state, _, outcome, _ = _run_fixture( + RESORT, + { + "family": ("inspect", 0.80), + "stakes": 0.2, + "urgency": 0.1, + "archetype:inspect": ("detail", 0.85), + }, + config=cfg, + ) + assert state.budget_exhausted is True + assert state.batch.pair_count() <= 8 + assert outcome.reason == "planned" + assert outcome.plan is not None + + +def test_layout_brief_pins_and_warns_on_unused_block() -> None: + """`LayoutBrief` skips pinned questions and logs a trace warning for extraneous blocks.""" + grammar = ArchetypeGrammar.default() + brief = LayoutBrief.parse( + ["monitor:cpu", "banner:status", "facts:host", "timeline:uptimeHours"], + roles=set(grammar.families()) | set(grammar.blocks), + ) + _, state, _, outcome, sa = _run_fixture( + HOST, + { + "stakes": 0.5, + "urgency": 0.5, + "archetype:monitor": ("dashboard", 0.85), + "gate:headline": 0.85, + "salience:/cpu": 2.9, + "salience:/status": 2.2, + "salience:/host": 1.9, + }, + brief=brief, + ) + assert "family" not in sa.asked + assert "gate:banner" not in sa.asked + assert "gate:facts" not in sa.asked + assert outcome.reason == "planned" + assert any( + r.question.id == "brief:timeline" and "warning" in r.outcome + for r in state.trace + ) + + +def test_needs_reask_identifies_low_confidence_depended_questions() -> None: + """`needs_reask` returns depended-on questions with winning prob < `reask_below`.""" + planner, state, _, outcome, _ = _run_fixture( + HOST, + { + "family": ("monitor", 0.55), + "stakes": 0.5, + "urgency": 0.5, + "archetype:monitor": ("dashboard", 0.62), + "archetype:orient": ("feed", 0.45), + "gate:banner": 0.78, + "gate:headline": 0.85, + "gate:facts": 0.82, + "instance:banner.tone:/status": ("warning", 0.60), + "salience:/cpu": 2.8, + "salience:/status": 2.2, + "salience:/host": 1.9, + }, + ) + assert outcome.reason == "planned" + assert outcome.plan is not None + reask = planner.needs_reask(outcome.plan, state) + reask_ids = [q.id for q in reask] + assert "family" in reask_ids + assert "archetype:monitor" in reask_ids + assert "instance:banner.tone:/status" in reask_ids + assert "archetype:orient" not in reask_ids + + +def test_answer_validation_rejects_missing_or_unknown_ids() -> None: + """`read` raises `A2uiValidationError` on missing or unknown question ids.""" + grammar = ArchetypeGrammar.default() + planner = LayoutPlanner(grammar, SynthesisConfig()) + pointers = inspect_payload_pointers(HOST.payload) + batch, state = planner.build_batch( + intent=HOST.intent, pointers=pointers, payload=HOST.payload + ) + answers = asyncio.run(ScriptedAnswers().backend().answer(batch)) + + with pytest.raises(A2uiValidationError, match="Missing answers"): + planner.read(state, answers[:-1]) + + extra = DecisionAnswer( + question_id="unknown:question", + distribution=DecisionDistribution( + probabilities={"yes": 0.8, "no": 0.2}, calibrated=True + ), + ) + with pytest.raises(A2uiValidationError, match="Unknown question id"): + planner.read(state, (*answers[:-1], extra)) + + +def test_individual_rule_functions_transform_plans() -> None: + """Direct unit tests for individual `apply_` functions.""" + grammar = ArchetypeGrammar.default() + caps = StubCapabilities(disabled=frozenset({("collection", "grid")})) + planner = LayoutPlanner(grammar, SynthesisConfig(), capabilities=caps) + pointers = inspect_payload_pointers(RESORT.payload) + batch, state = planner.build_batch( + intent=RESORT.intent, pointers=pointers, payload=RESORT.payload + ) + answers = asyncio.run(ScriptedAnswers().backend().answer(batch)) + planner.read(state, answers) + + plan = LayoutPlan( + family="inspect", + archetype="detail", + stakes=0.5, + urgency=2.5, + blocks=( + PlannedBlock( + block_id="picture", + pattern="picture", + bindings=BlockBindings( + {"picture": SlotBinding(pointer="/photos/0/url")} + ), + variant_knobs={"framing": "banner", "prominence": "hero"}, + ), + PlannedBlock( + block_id="prose", + pattern="prose", + bindings=BlockBindings({"body": SlotBinding(pointer="/about")}), + variant_knobs={"length": "blurb"}, + ), + PlannedBlock( + block_id="facts", + pattern="facts", + bindings=BlockBindings(), + ), + ), + page=PageBindings(title=SlotBinding(pointer="/name")), + ) + + p1 = apply_required_block_wins(plan, state) + p2 = apply_at_least(p1, state, grammar) + p3 = apply_fallback_must_end(p2, state, grammar, caps) + p4 = apply_catalog_eligibility(p3, state) + p5 = apply_pointer_once_per_region(p4, state, planner) + p6 = apply_pictures_need_a_look(p5, state) + assert p6.page.mark == SlotBinding(pointer="/logoUrl") + + p7 = apply_leading_all_or_none(p6, state) + p8 = apply_actions_gate( + p7, + state, + grammar.threshold("actionGateFloor"), + grammar.threshold("actionGateCap"), + ) + p9 = apply_one_primary_action(p8, state) + p10 = apply_urgency_terse(p9, state, caps) + assert all(b.block_id != "prose" for b in p10.blocks) + + with_empty = replace( + p10, + blocks=( + *p10.blocks, + PlannedBlock( + block_id="outcome", + pattern="outcome", + bindings=BlockBindings(), + ), + ), + ) + p11 = apply_no_empty_container(with_empty, state, grammar) + assert all(b.block_id != "outcome" for b in p11.blocks) + + +def test_lint_components_catches_all_six_structural_violations() -> None: + """`lint_components` reports all six structural violations and honors `raise_on_error`.""" + bad_components: list[dict[str, Any]] = [ + { + "id": "root", + "component": "Column", + "children": [ + "empty_col", + "missing_id", + "body_txt", + "h1_txt", + "btn1", + "btn2", + "reel1", + "reel2", + "dup1", + "dup2", + ], + }, + {"id": "empty_col", "component": "Column", "children": []}, + { + "id": "body_txt", + "component": "Text", + "text": {"path": "/a"}, + "variant": "body", + }, + { + "id": "h1_txt", + "component": "Text", + "text": "Heading", + "variant": "h1", + }, + { + "id": "btn1", + "component": "Button", + "label": "Go", + "variant": "primary", + }, + { + "id": "btn2", + "component": "Button", + "label": "Send", + "variant": "primary", + }, + { + "id": "reel1", + "component": "List", + "children": ["body_txt"], + "direction": "horizontal", + }, + { + "id": "reel2", + "component": "List", + "children": ["h1_txt"], + "direction": "horizontal", + }, + {"id": "dup1", "component": "Text", "text": {"path": "/shared"}}, + {"id": "dup2", "component": "Text", "text": {"@path": "/shared"}}, + ] + + findings: tuple[LintFinding, ...] = lint_components(bad_components) + codes = {f.code for f in findings} + assert codes == { + "empty_container", + "missing_component", + "multiple_primary_buttons", + "duplicate_pointer_binding", + "heading_after_body", + "multiple_reels", + } + + with pytest.raises(A2uiValidationError, match="Layout component lint failed"): + lint_components(bad_components, raise_on_error=True) + + valid_components: list[dict[str, Any]] = [ + { + "id": "root", + "component": "Column", + "children": ["h1_txt", "body_txt", "btn1"], + }, + { + "id": "h1_txt", + "component": "Text", + "text": {"path": "/title"}, + "variant": "h1", + }, + { + "id": "body_txt", + "component": "Text", + "text": {"path": "/body"}, + "variant": "body", + }, + { + "id": "btn1", + "component": "Button", + "label": "OK", + "variant": "primary", + }, + ] + assert lint_components(valid_components, raise_on_error=True) == () + + +def test_threshold_boundary_cases_050_075_and_0875() -> None: + """Tests exact boundary behavior at 0.50 (expected), 0.75 (optional), and 0.875 (action gate).""" + # 1. Expected block (`prose+` on detail) at 0.49 vs 0.50, and optional block (`collection?`) at 0.74 vs 0.75. + base_resort: dict[str, ScriptedValue] = { + "family": ("inspect", 0.80), + "stakes": 0.2, + "urgency": 0.1, + "archetype:inspect": ("detail", 0.85), + "gate:picture": 0.90, + "gate:headline": 0.80, + "gate:facts": 0.10, + "gate:banner": 0.10, + "gate:actions": 0.10, + "salience:/rating": 2.4, + "salience:/priceFrom": 2.6, + } + _, _, _, below, _ = _run_fixture( + RESORT, + {**base_resort, "gate:prose": 0.49, "gate:collection": 0.74}, + ) + assert below.plan is not None + assert "prose" not in below.plan.block_ids() + assert "collection" not in below.plan.block_ids() + + _, _, _, exact, _ = _run_fixture( + RESORT, + {**base_resort, "gate:prose": 0.50, "gate:collection": 0.75}, + ) + assert exact.plan is not None + assert "prose" in exact.plan.block_ids() + assert "collection" in exact.plan.block_ids() + + # 2. Action gate at stakes 2.1 is 0.70 + 0.25 * 2.1 / 3 = 0.875. + base_transfer: dict[str, ScriptedValue] = { + "family": ("act", 0.85), + "stakes": 2.1, + "urgency": 0.6, + "gate:facts": 0.85, + "gate:actions": 0.90, + "salience:/amount": 2.9, + "salience:/recipient": 2.6, + } + _, _, _, gate_below, _ = _run_fixture( + TRANSFER, {**base_transfer, "archetype:act": ("confirm", 0.874)} + ) + assert gate_below.reason == "action_gate" + + _, _, _, gate_exact, _ = _run_fixture( + TRANSFER, {**base_transfer, "archetype:act": ("confirm", 0.875)} + ) + assert gate_exact.reason == "planned" + assert gate_exact.plan is not None + assert gate_exact.plan.actions_allowed is True + + +def test_leading_all_or_none_degrades_sparse_collection_pictures() -> None: + """`apply_leading_all_or_none` sets `leading='none'` when over half of items lack pictures.""" + sparse_fixture = LayoutFixture( + name="sparse_resort", + intent="Show the resort overview", + payload={ + "name": "Casa Verde", + "rating": 4.6, + "photos": [ + {"url": "https://example.com/1.jpg", "caption": "One"}, + {"url": "", "caption": "Two"}, + {"url": "", "caption": "Three"}, + ], + }, + ) + _, _, _, outcome, _ = _run_fixture( + sparse_fixture, + { + "family": ("inspect", 0.80), + "stakes": 0.2, + "urgency": 0.1, + "archetype:inspect": ("detail", 0.85), + "gate:headline": 0.80, + "gate:collection": 0.85, + "anatomy:collection.layout": ("rows", 0.80), + "anatomy:collection.leading": ("thumbnail", 0.85), + "salience:/rating": 2.5, + }, + ) + assert outcome.reason == "planned" + assert outcome.plan is not None + col = next(b for b in outcome.plan.blocks if b.block_id == "collection") + assert col.variant_knobs.get("leading") == "none" + + # M3: fallback entry `collection:grid` requires the specific `(collection, grid)` variant + caps_no_grid = StubCapabilities( + disabled=frozenset({("nonexistent_pic", None), ("collection", "grid")}) + ) + planner_no_grid = LayoutPlanner( + ArchetypeGrammar.default(), SynthesisConfig(), capabilities=caps_no_grid + ) + spec_with_grid_fb = replace( + ArchetypeGrammar.default().block("picture"), + pattern="nonexistent_pic", + fallback=("nonexistent_pic", "collection:grid"), + ) + from a2ui.inference_formats.decision.layout_planner import ( + _resolve_block_pattern, + ) + + assert _resolve_block_pattern(spec_with_grid_fb, caps_no_grid) is None + + # Q1: `steps` array binding unrolls `items` so `{$index1}` renders 1., 2., 3. + steps_payload = { + "title": "How to brew", + "steps": [ + {"title": "Grind beans", "detail": "Medium-fine"}, + {"title": "Pour water", "detail": "93C"}, + ], + } + steps_ptrs = inspect_payload_pointers(steps_payload) + steps_bindings = planner_no_grid.bind_slots( + ArchetypeGrammar.default().block("steps"), + steps_ptrs, + set(), + payload=steps_payload, + ) + steps_slot = steps_bindings.get("items") + assert steps_slot is not None + assert len(steps_slot.items) == 2 + assert steps_slot.items[0]["title"].pointer == "/steps/0/title" + assert steps_slot.items[1]["title"].pointer == "/steps/1/title" + + +def test_threshold_overrides_take_precedence_over_grammar_thresholds() -> None: + """`SynthesisConfig.threshold_overrides` wins per key; other keys stay on the grammar.""" + grammar = ArchetypeGrammar.default() + planner = LayoutPlanner( + grammar, SynthesisConfig(threshold_overrides={"optional": 0.9}) + ) + assert planner.threshold("optional") == pytest.approx(0.9) + assert planner.threshold("expected") == pytest.approx(grammar.threshold("expected")) + assert planner.threshold("actionGateCap") == pytest.approx( + grammar.threshold("actionGateCap") + ) + with pytest.raises(KeyError): + planner.threshold("not_a_threshold") + + # Raising `optional` to 0.9 drops the 0.85 collection gate that passed at 0.75. + scripted: dict[str, ScriptedValue] = { + "family": ("inspect", 0.80), + "stakes": 0.2, + "urgency": 0.1, + "archetype:inspect": ("detail", 0.85), + "gate:headline": 0.80, + "gate:prose": 0.90, + "gate:collection": 0.85, + "salience:/rating": 2.4, + "salience:/priceFrom": 2.6, + } + _, _, _, default_outcome, _ = _run_fixture(RESORT, scripted) + assert default_outcome.plan is not None + assert "collection" in default_outcome.plan.block_ids() + _, _, _, strict_outcome, _ = _run_fixture( + RESORT, + scripted, + config=SynthesisConfig(threshold_overrides={"optional": 0.9}), + ) + assert strict_outcome.plan is not None + assert "collection" not in strict_outcome.plan.block_ids() + assert strict_outcome.reason is PlanReason.PLANNED + assert strict_outcome.reason == "planned" + + +def test_decision_suite_gap_fixes_orphan_recovery_3_field_items_redirect_and_primitive_arrays() -> ( + None +): + """Covers the four completeness gaps surfaced by `decision_v1_0`.""" + # Gap A: Unclaimed single top-level scalar pointer (`/author`) is recovered into `facts` + # even when `gate:facts < 0.75`. + article_fixture = LayoutFixture( + name="article_summary", + intent="Show the article summary", + payload={ + "title": "Why Declarative UIs Work", + "author": "Ada Lovelace", + "body": ( + "Declarative user interfaces separate state from structure so that" + " agents can emit data payloads while deterministic layout rules" + " handle presentation and accessibility." + ), + }, + ) + _, _, _, article_outcome, _ = _run_fixture( + article_fixture, + { + "family": ("inspect", 0.85), + "archetype:inspect": ("detail", 0.85), + "gate:prose": 0.90, + "gate:facts": 0.40, + }, + ) + assert article_outcome.plan is not None + assert "facts" in article_outcome.plan.block_ids() + facts_block = next(b for b in article_outcome.plan.blocks if b.block_id == "facts") + fact_ptrs = [it["value"].pointer for it in facts_block.bindings.get("rows").items] + assert "/author" in fact_ptrs + + # Gap B: 3-field collection items (`name`, `elevation`, `openRuns` and `title`, `snippet`, `url`) + # bind `headline`, `supporting`, and `meta`. + search_fixture = LayoutFixture( + name="search_results", + intent="Show search results", + payload={ + "results": [ + { + "title": "A2UI Protocol Specification", + "snippet": "Streaming declarative user interfaces for AI agents.", + "url": "https://a2ui.dev/spec", + }, + { + "title": "Decision Model Layout Grammar", + "snippet": "Archetype and block selection via zero-shot scoring.", + "url": "https://a2ui.dev/decision", + }, + ] + }, + ) + _, _, _, search_outcome, _ = _run_fixture( + search_fixture, + { + "family": ("browse", 0.90), + "archetype:browse": ("feed", 0.90), + "gate:collection": 0.90, + }, + ) + assert search_outcome.plan is not None + col_block = next( + b for b in search_outcome.plan.blocks if b.block_id == "collection" + ) + items_slot = col_block.bindings.get("items") + assert items_slot is not None + assert items_slot.fields["headline"].pointer == "title" + assert items_slot.fields["supporting"].pointer == "snippet" + assert items_slot.fields["meta"].pointer == "url" + + # Gap C: Flat scalar step payload (`recipeName`, `currentStep`, `totalSteps`, `instruction`) + # redirects `follow` to an eligible family (`inspect -> detail`) and binds all pointers. + recipe_fixture = LayoutFixture( + name="sourdough_step", + intent="Walk me through making sourdough bread step by step", + payload={ + "recipeName": "Country Sourdough", + "currentStep": 1, + "totalSteps": 5, + "instruction": "Mix 50g starter with 50g warm water and 50g bread flour.", + }, + ) + _, _, _, recipe_outcome, _ = _run_fixture( + recipe_fixture, + { + "family": {"follow": 0.80, "inspect": 0.15, "act": 0.05}, + "archetype:inspect": ("none", 0.60), + "gate:prose": 0.85, + "gate:facts": 0.85, + }, + ) + assert recipe_outcome.reason == "planned" + assert recipe_outcome.plan is not None + assert recipe_outcome.plan.family == "inspect" + all_bound_ptrs = set(recipe_outcome.plan.page.title.pointers()) + for b in recipe_outcome.plan.blocks: + all_bound_ptrs.update(b.bindings.pointers()) + assert { + "/recipeName", + "/currentStep", + "/totalSteps", + "/instruction", + } <= all_bound_ptrs + + # Gap D: On a catalog without `chart`, `chart?` in `dashboard` is skipped as a redundant + # optional fallback (since `headline` is already in `dashboard.blocks`), and primitive + # string arrays (`regions: ["us-east", "us-west", "eu-central"]`) unroll into `collection`. + cluster_fixture = LayoutFixture( + name="cluster_status", + intent="Show cluster status across regions", + payload={ + "clusterName": "prod-us-1", + "overallHealth": "healthy", + "activeNodes": 42, + "regions": ["us-east", "us-west", "eu-central"], + }, + ) + caps_no_chart = StubCapabilities(disabled=frozenset({("chart", None)})) + _, _, _, cluster_outcome, cluster_sa = _run_fixture( + cluster_fixture, + { + "family": ("monitor", 0.90), + "archetype:monitor": ("dashboard", 0.90), + "gate:banner": 0.85, + "gate:headline": 0.90, + "gate:collection": 0.85, + }, + capabilities=caps_no_chart, + ) + assert "gate:chart" not in cluster_sa.asked + assert cluster_outcome.plan is not None + assert "chart" not in cluster_outcome.plan.block_ids() + assert "collection" in cluster_outcome.plan.block_ids() + reg_col = next(b for b in cluster_outcome.plan.blocks if b.block_id == "collection") + reg_items = reg_col.bindings.get("items") + assert reg_items is not None + assert len(reg_items.items) == 3 + assert [it["headline"].pointer for it in reg_items.items] == [ + "/regions/0", + "/regions/1", + "/regions/2", + ] + + +def test_two_stage_batching_reduces_pairs_and_matches_single_stage() -> None: + """`build_stage1_batch` + `build_stage2_batch` asks fewer pairs while producing the same plan.""" + scripted: dict[str, ScriptedValue] = { + "family": ("monitor", 0.90), + "stakes": 0.4, + "urgency": 1.6, + "archetype:monitor": ("dashboard", 0.88), + "gate:banner": 0.85, + "gate:headline": 0.90, + "gate:facts": 0.80, + "gate:collection": 0.20, + "gate:actions": 0.20, + } + _, single_state, _, single_outcome, _ = _run_fixture(HOST, scripted) + assert single_outcome.plan is not None + + grammar = ArchetypeGrammar.default() + planner = LayoutPlanner(grammar) + pointers = inspect_payload_pointers(HOST.payload, mutable_paths=HOST.mutable_paths) + sa = ScriptedAnswers(answers=scripted) + backend = sa.backend() + stage1_batch, state = planner.build_stage1_batch( + HOST.intent, pointers, payload=HOST.payload + ) + stage1_answers = asyncio.run(backend.answer(stage1_batch)) + stage2_batch = planner.build_stage2_batch(state, stage1_answers) + stage2_answers = asyncio.run(backend.answer(stage2_batch)) + two_stage_outcome = planner.read(state, (*stage1_answers, *stage2_answers)) + + assert two_stage_outcome.plan is not None + assert two_stage_outcome.plan.family == single_outcome.plan.family + assert two_stage_outcome.plan.archetype == single_outcome.plan.archetype + assert two_stage_outcome.plan.block_ids() == single_outcome.plan.block_ids() + assert state.batch.pair_count() < single_state.batch.pair_count() diff --git a/python/a2ui_agent/tests/decision/test_models_questions.py b/python/a2ui_agent/tests/decision/test_models_questions.py new file mode 100644 index 0000000000..d9de4d52eb --- /dev/null +++ b/python/a2ui_agent/tests/decision/test_models_questions.py @@ -0,0 +1,607 @@ +# 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. + +"""Unit tests for the batched question types and the predict-to-answer adapter.""" + +from __future__ import annotations + +import pytest + +from a2ui.core import A2uiValidationError +from a2ui.inference_formats.decision import ( + DecisionBackend, + DecisionDistribution, + DecisionQuery, + DecisionTask, + DeterministicMockBackend, + JevHttpBackend, + LocalCrossEncoderBackend, + StepZeroLogprobBackend, + SynthesisConfig, + SynthesisOutput, + SynthesisStage, +) +from a2ui.inference_formats.decision.backends import answer_from_distribution +from a2ui.inference_formats.decision.bindings import ( + is_v10, + make_data_binding, + make_function_call, +) +from a2ui.inference_formats.decision.models import ( + MAX_BRIEF_SECTIONS, + BlockBindings, + BriefSection, + DecisionAnswer, + DecisionBatch, + DecisionQuestion, + DecisionRecord, + LayoutBrief, + LayoutPlan, + PatternCapabilities, + PlanOutcome, + PlannedBlock, + QuestionKind, + SemanticType, + SlotBinding, +) +from a2ui.inference_formats.decision.payload_inspector import ( + PointerSummary, + inspect_payload_pointers, + split_pointer, +) + +from .layout_fixtures import FIXTURES, HOST, RESORT, ScriptedAnswers + +_LEVELS = ("none", "small", "medium", "large") + + +def _choice( + question_id: str = "family", *, allow_none: bool = True +) -> DecisionQuestion: + return DecisionQuestion( + id=question_id, + kind=QuestionKind.CHOICE, + prompt="What is the person here to do?", + options=("browse", "inspect"), + option_texts=("Look through things.", "Understand one thing."), + allow_none=allow_none, + ) + + +def _boolean(question_id: str = "gate:collection") -> DecisionQuestion: + return DecisionQuestion( + id=question_id, + kind=QuestionKind.BOOLEAN, + prompt="Are there several similar items the person would scan?", + context={ + "yes": "Results, products, records.", + "no": "This is about one thing.", + }, + ) + + +def _score(question_id: str = "stakes") -> DecisionQuestion: + return DecisionQuestion( + id=question_id, + kind=QuestionKind.SCORE, + prompt="If this goes wrong, how bad is it?", + options=_LEVELS, + ) + + +# --- DecisionQuestion / DecisionAnswer / DecisionBatch ------------------------- + + +def test_question_candidates_and_task_prefix() -> None: + assert _choice().candidates() == ("browse", "inspect", "none") + assert _choice(allow_none=False).candidates() == ("browse", "inspect") + assert _boolean().candidates() == ("yes", "no") + assert _score().candidates() == _LEVELS + assert _choice("family").task is DecisionTask.FAMILY + assert _choice("archetype:browse").task is DecisionTask.ARCHETYPE + assert _boolean("gate:collection").task is DecisionTask.BLOCK_GATE + assert _choice("anatomy:collection.layout").task is DecisionTask.ANATOMY + assert _score("salience:/cpu").task is DecisionTask.SALIENCE + assert _choice("instance:banner.tone:/status").task is DecisionTask.INSTANCE + assert _score("stakes").task is DecisionTask.STAKES + assert _score("urgency").task is DecisionTask.URGENCY + assert _choice("custom:thing").task == "custom" + + +def test_question_validation() -> None: + with pytest.raises(ValueError, match="non-empty"): + DecisionQuestion(id="", kind=QuestionKind.BOOLEAN, prompt="?") + with pytest.raises(ValueError, match="take no options"): + DecisionQuestion(id="b", kind=QuestionKind.BOOLEAN, prompt="?", options=("x",)) + with pytest.raises(ValueError, match="need options"): + DecisionQuestion(id="c", kind=QuestionKind.CHOICE, prompt="?") + with pytest.raises(ValueError, match="at least two levels"): + DecisionQuestion(id="s", kind=QuestionKind.SCORE, prompt="?", options=("one",)) + with pytest.raises(ValueError, match="option_texts"): + DecisionQuestion( + id="c", kind="choice", prompt="?", options=("a", "b"), option_texts=("A",) + ) + coerced = DecisionQuestion(id="c", kind="choice", prompt="?", options=["a"]) + assert coerced.kind is QuestionKind.CHOICE + assert coerced.options == ("a",) + assert f"{coerced.kind}" == "choice" + + +def test_answer_yes_top_and_expected() -> None: + boolean = DecisionAnswer( + question_id="g", distribution=DecisionDistribution({"yes": 0.8, "no": 0.2}) + ) + assert boolean.yes == pytest.approx(0.8) + assert boolean.top() == ("yes", pytest.approx(0.8)) + choice = DecisionAnswer( + question_id="c", distribution=DecisionDistribution({"a": 0.3, "b": 0.7}) + ) + assert choice.yes == 0.0 + assert choice.top() == ("b", pytest.approx(0.7)) + assert choice.expected is None + score = DecisionAnswer( + question_id="s", + distribution=DecisionDistribution({"none": 0.5, "small": 0.5}), + expected=0.5, + ) + assert score.expected == 0.5 + + +def test_batch_rejects_duplicate_ids_and_counts_pairs() -> None: + batch = DecisionBatch( + shared_context={"intent": "x"}, questions=[_choice(), _boolean(), _score()] + ) + assert batch.pair_count() == 3 + 2 + 4 + with pytest.raises(ValueError, match="Duplicate question id"): + DecisionBatch(shared_context={}, questions=(_choice(), _choice())) + + +def test_decision_record_defaults() -> None: + record = DecisionRecord(question=_boolean()) + assert record.answer is None + assert record.threshold is None + assert record.outcome == "" + + +# --- _AnswerViaPredict on DeterministicMockBackend ------------------------------ + + +@pytest.mark.asyncio +async def test_mock_backend_answers_scripted_batch_for_all_kinds() -> None: + backend = DeterministicMockBackend( + scripted={ + "family:What is the person here to do?": { + "browse": 0.2, + "inspect": 0.7, + "none": 0.1, + }, + "block_gate:Are there several similar items the person would scan?": { + "yes": 0.9, + "no": 0.1, + }, + "stakes:If this goes wrong, how bad is it?": { + "none": 0.1, + "small": 0.2, + "medium": 0.3, + "large": 0.4, + }, + } + ) + batch = DecisionBatch( + shared_context={}, questions=(_choice(), _boolean(), _score()) + ) + answers = await backend.answer(batch) + assert [a.question_id for a in answers] == ["family", "gate:collection", "stakes"] + family, gate, stakes = answers + assert family.top() == ("inspect", pytest.approx(0.7)) + assert set(family.distribution.probabilities) == {"browse", "inspect", "none"} + assert gate.yes == pytest.approx(0.9) + assert gate.distribution.probabilities == { + "yes": pytest.approx(0.9), + "no": pytest.approx(0.1), + } + assert stakes.expected == pytest.approx(0.1 * 0 + 0.2 * 1 + 0.3 * 2 + 0.4 * 3) + assert stakes.top() == ("large", pytest.approx(0.4)) + + +@pytest.mark.asyncio +async def test_mock_backend_heuristic_answers_every_kind() -> None: + backend = DeterministicMockBackend() + batch = DecisionBatch( + shared_context={"intent": "Browse the feed"}, + questions=(_choice(), _boolean(), _score()), + ) + answers = await backend.answer(batch) + family, gate, stakes = answers + assert sum(family.distribution.probabilities.values()) == pytest.approx(1.0) + assert family.top()[0] in ("browse", "inspect", "none") + assert 0.0 <= gate.yes <= 1.0 + assert gate.distribution.probabilities["no"] == pytest.approx(1.0 - gate.yes) + assert stakes.expected is not None + assert 0.0 <= stakes.expected <= 3.0 + + +@pytest.mark.asyncio +async def test_allow_none_adds_and_removes_the_none_option() -> None: + seen: list[DecisionQuery] = [] + + def scorer(query: DecisionQuery) -> DecisionDistribution: + seen.append(query) + n = len(query.candidates) + return DecisionDistribution({c: 1.0 / n for c in query.candidates}) + + backend = DeterministicMockBackend(scorer=scorer) + with_none, without = await backend.answer( + DecisionBatch( + shared_context={"intent": "x"}, + questions=(_choice("a"), _choice("b", allow_none=False)), + ) + ) + assert seen[0].candidates == ("browse", "inspect", "none") + assert seen[1].candidates == ("browse", "inspect") + assert "none" in with_none.distribution.probabilities + assert "none" not in without.distribution.probabilities + + +@pytest.mark.asyncio +async def test_predict_query_carries_question_context() -> None: + seen: list[DecisionQuery] = [] + + def scorer(query: DecisionQuery) -> DecisionDistribution: + seen.append(query) + return DecisionDistribution({c: 1.0 for c in query.candidates[:1]}) + + backend = DeterministicMockBackend(scorer=scorer) + await backend.answer( + DecisionBatch( + shared_context={"intent": "Show it", "pointers": ["/a"]}, + questions=(_choice(), _boolean()), + ) + ) + choice_query, boolean_query = seen + assert choice_query.task is DecisionTask.FAMILY + assert choice_query.prompt == "What is the person here to do?" + assert choice_query.context["intent"] == "Show it" + assert choice_query.context["question_id"] == "family" + assert choice_query.context["question_kind"] == "choice" + assert choice_query.context["candidate_descriptions"] == { + "browse": "Look through things.", + "inspect": "Understand one thing.", + } + assert boolean_query.task is DecisionTask.BLOCK_GATE + assert boolean_query.context["candidate_descriptions"] == { + "yes": "Results, products, records.", + "no": "This is about one thing.", + } + + +def test_answer_from_distribution_handles_empty_mass() -> None: + gate = answer_from_distribution(_boolean(), DecisionDistribution({})) + assert gate.yes == 0.0 + assert gate.distribution.probabilities["no"] == 1.0 + score = answer_from_distribution(_score(), DecisionDistribution({})) + assert score.expected is None + unnormalized = answer_from_distribution( + _score(), DecisionDistribution({"none": 1.0, "large": 1.0}) + ) + assert unnormalized.expected == pytest.approx(1.5) + assert unnormalized.distribution.probabilities["none"] == pytest.approx(0.5) + + +def test_all_backends_expose_answer_and_satisfy_protocol() -> None: + backends = ( + JevHttpBackend("http://localhost:8080/predict"), + StepZeroLogprobBackend("http://localhost:8000/v1/completions", "m"), + DeterministicMockBackend(), + LocalCrossEncoderBackend(), + ) + for backend in backends: + assert isinstance(backend, DecisionBackend) + assert callable(backend.answer) + + +# --- ScriptedAnswers fixture helper ---------------------------------------------- + + +@pytest.mark.asyncio +async def test_scripted_answers_helper_scripts_by_question_id() -> None: + scripted = ScriptedAnswers({ + "family": "inspect", + "gate:collection": 0.85, + "stakes": 2.2, + "anatomy:collection.layout": ("reel", 0.7), + }) + layout = DecisionQuestion( + id="anatomy:collection.layout", + kind=QuestionKind.CHOICE, + prompt="How should these items be laid out?", + options=("rows", "cards", "reel"), + ) + answers = await scripted.backend().answer( + DecisionBatch( + shared_context={}, + questions=(_choice(), _boolean(), _score(), layout, _choice("archetype:x")), + ) + ) + family, gate, stakes, reel, unscripted = answers + assert family.top() == ("inspect", pytest.approx(0.9)) + assert gate.yes == pytest.approx(0.85) + assert stakes.expected == pytest.approx(2.2) + assert reel.top() == ("reel", pytest.approx(0.7)) + assert unscripted.top()[1] == pytest.approx(1.0 / 3) + assert scripted.asked == [ + "family", + "gate:collection", + "stakes", + "anatomy:collection.layout", + "archetype:x", + ] + + +def test_layout_fixtures_are_the_worked_examples() -> None: + assert set(FIXTURES) == {"resort", "host", "transfer", "settings"} + assert RESORT.payload["photos"][0]["caption"] == "Pool at dusk" + assert 15 <= len(str(RESORT.payload["about"]).split()) < 60 + assert HOST.mutable_paths == () + assert FIXTURES["transfer"].mutable_paths == ("/actions",) + assert FIXTURES["settings"].mutable_paths == ( + "/playback", + "/notifications", + "/account", + ) + + +# --- SynthesisConfig / SynthesisOutput / SynthesisStage --------------------------- + + +def test_synthesis_config_defaults_for_archetypes() -> None: + config = SynthesisConfig() + assert config.max_pairs == 400 + assert config.threshold_overrides == {} + assert config.use_archetypes is True + tuned = SynthesisConfig( + threshold_overrides={"actionGateFloor": 0.8, "actionGateCap": 0.8} + ) + assert tuned.threshold_overrides["actionGateFloor"] == pytest.approx(0.8) + SynthesisConfig(threshold_overrides={"expected": 0.6, "optional": 0.6}) + + +@pytest.mark.parametrize( + ("kwargs", "message"), + [ + ({"max_pairs": 0}, "max_pairs"), + ({"threshold_overrides": {"actionGateFloor": -0.1}}, "actionGateFloor"), + ({"threshold_overrides": {"actionGateCap": 1.1}}, "actionGateCap"), + ( + {"threshold_overrides": {"actionGateFloor": 0.9, "actionGateCap": 0.8}}, + "actionGateFloor must be <=", + ), + ({"threshold_overrides": {"expected": 1.5}}, "expected"), + ({"threshold_overrides": {"optional": -1.0}}, "optional"), + ( + {"threshold_overrides": {"expected": 0.8, "optional": 0.7}}, + "expected must be <=", + ), + ({"threshold_overrides": {"reask_below": 2.0}}, "reask_below"), + ], +) +def test_synthesis_config_rejects_bad_archetype_fields( + kwargs: dict[str, float], message: str +) -> None: + with pytest.raises(ValueError, match=message): + SynthesisConfig(**kwargs) + + +def test_synthesis_output_new_fields_default() -> None: + output = SynthesisOutput( + stage=SynthesisStage.ARCHETYPE, messages=[], confidence=0.9, entropy=0.1 + ) + assert output.layout_plan is None + assert output.trace == () + assert SynthesisStage.ARCHETYPE.value == "archetype" + plan = LayoutPlan(archetype="detail", family="inspect", blocks=()) + traced = SynthesisOutput( + stage=SynthesisStage.ARCHETYPE, + messages=[], + confidence=0.9, + entropy=0.1, + layout_plan=plan, + trace=[DecisionRecord(question=_boolean())], + ) + assert traced.layout_plan is plan + assert isinstance(traced.trace, tuple) + + +# --- Plan types --------------------------------------------------------------------- + + +def test_slot_and_block_bindings() -> None: + assert not SlotBinding().bound + assert SlotBinding(pointer="/a").bound + assert SlotBinding(literal="Send").bound + items = SlotBinding( + items=[ + {"label": SlotBinding(literal="CPU"), "value": SlotBinding(pointer="/cpu")}, + {"value": SlotBinding(pointer="/status")}, + ] + ) + assert items.bound + assert items.pointers() == ("/cpu", "/status") + bindings = BlockBindings({ + "items": items, + "title": SlotBinding(pointer="/name"), + "empty": SlotBinding(), + }) + assert bindings.is_bound("items") + assert bindings.is_bound("title") + assert not bindings.is_bound("empty") + assert bindings.get("missing") is None + assert bindings.pointers() == ("/cpu", "/status", "/name") + + +def test_layout_plan_and_outcome() -> None: + block = PlannedBlock( + block_id="headline", + pattern="headline", + variant_knobs={"deltas": "yes"}, + instances={"/cpu": {"news": "bad"}}, + probability=0.8, + ) + plan = LayoutPlan( + archetype="dashboard", + family="monitor", + blocks=[block], + stakes=1.0, + urgency=1.4, + confidence=0.9, + actions_allowed=True, + ) + assert plan.block_ids() == ("headline",) + assert plan.blocks[0].variant_knobs == {"deltas": "yes"} + assert PlanOutcome(plan=plan, reason="planned").plan is plan + assert PlanOutcome(plan=None, reason="action_gate").plan is None + with pytest.raises(ValueError): + PlanOutcome(plan=None, reason="planned") + with pytest.raises(ValueError): + PlanOutcome(plan=plan, reason="no_family") + + +def test_pattern_capabilities_protocol_is_structural() -> None: + class Stub: + + def has_pattern(self, name: str, variant: str | None = None) -> bool: + return name == "collection" and variant != "grid" + + stub = Stub() + assert isinstance(stub, PatternCapabilities) + assert stub.has_pattern("collection") + assert not stub.has_pattern("collection", "grid") + + +# --- LayoutBrief ---------------------------------------------------------------------- + + +_ROLES = ("inspect", "picture", "collection", "headline", "facts", "actions", "banner") + + +def test_layout_brief_parses_bare_keys_and_pointers() -> None: + brief = LayoutBrief.parse( + ["picture:name,logoUrl", "collection:/photos", " headline:rating,priceFrom "], + roles=_ROLES, + ) + assert brief.roles() == ("picture", "collection", "headline") + assert brief.sections[0] == BriefSection("picture", ("/name", "/logoUrl")) + assert brief.sections[1].pointers == ("/photos",) + assert brief.sections[2].pointers == ("/rating", "/priceFrom") + assert brief.section("collection") is not None + assert brief.section("facts") is None + assert brief.to_items() == [ + "picture:/name,/logoUrl", + "collection:/photos", + "headline:/rating,/priceFrom", + ] + assert LayoutBrief.parse(brief.to_items(), roles=_ROLES) == brief + assert LayoutBrief.parse([], roles=_ROLES).sections == () + + +@pytest.mark.parametrize( + ("items", "message"), + [ + (["hero:name"], "role 'hero'"), + (["picture"], "not of the form"), + (["picture:"], "not of the form"), + (["picture:a:b"], "not of the form"), + (["picture:name,,logoUrl"], "empty key"), + (["picture:name", "picture:logoUrl"], "repeats role"), + ([f"facts:k{i}" for i in range(MAX_BRIEF_SECTIONS + 1)], "at most 6"), + ], +) +def test_layout_brief_rejects_malformed_items(items: list[str], message: str) -> None: + with pytest.raises(A2uiValidationError, match=message): + LayoutBrief.parse(items, roles=_ROLES) + + +# --- bindings.py -------------------------------------------------------------------- + + +def test_wire_helpers() -> None: + assert is_v10("1.0") and is_v10("v1.0") and is_v10("1") and is_v10("v1.2") + assert not is_v10("0.9") and not is_v10("v0.9.1") + assert make_data_binding("/a", is_v10=True) == {"@path": "/a"} + assert make_data_binding("/a", is_v10=False) == {"path": "/a"} + assert make_function_call("formatString", {"value": "x"}, is_v10=True) == { + "@call": "formatString", + "args": {"value": "x"}, + } + assert make_function_call("required", {}, is_v10=False) == { + "call": "required", + "args": {}, + } + + +# --- PointerSummary additions --------------------------------------------------------- + + +def test_split_pointer() -> None: + assert split_pointer("/a/b") == ("/a", "b") + assert split_pointer("/name") == ("", "name") + assert split_pointer("name") == ("", "name") + assert split_pointer("/a/b~1c~0d") == ("/a", "b/c~d") + assert split_pointer("") == ("", "") + + +def test_pointer_summary_defaults_key_and_parent() -> None: + summary = PointerSummary(path="/photos/0/url", value_type="string", cardinality=1) + assert summary.key == "url" + assert summary.parent == "/photos/0" + assert summary.semantic_type == "string" + assert summary.hints == {} + assert summary.label == "" + assert summary.element_semantic_types == {} + assert summary.sample_pointers == () + explicit = PointerSummary( + path="/x", + value_type="number", + cardinality=1, + semantic_type=SemanticType.CURRENCY, + hints={"currency": "USD"}, + key="custom", + label="Price", + parent="/root", + sample_pointers=["/x/0"], + ) + assert explicit.key == "custom" + assert explicit.parent == "/root" + assert explicit.semantic_type == "currency" + assert explicit.sample_pointers == ("/x/0",) + relative = PointerSummary(path="caption", value_type="string", cardinality=1) + assert (relative.parent, relative.key) == ("", "caption") + + +def test_inspector_populates_key_and_parent() -> None: + pointers = {p.path: p for p in inspect_payload_pointers(dict(RESORT.payload))} + assert pointers["/name"].key == "name" + assert pointers["/name"].parent == "" + assert pointers["/photos"].key == "photos" + assert pointers["/photos"].element_keys == ("url", "caption") + nested = { + p.path: p + for p in inspect_payload_pointers( + dict(FIXTURES["settings"].payload), + mutable_paths=FIXTURES["settings"].mutable_paths, + ) + } + assert nested["/playback/speed"].parent == "/playback" + assert nested["/playback/speed"].key == "speed" + assert nested["/playback/speed"].mutable_hint diff --git a/python/a2ui_agent/tests/decision/test_patterns.py b/python/a2ui_agent/tests/decision/test_patterns.py new file mode 100644 index 0000000000..f26af86035 --- /dev/null +++ b/python/a2ui_agent/tests/decision/test_patterns.py @@ -0,0 +1,1058 @@ +# 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. + +"""Unit tests for catalog pattern libraries, expander, and archetype eligibility.""" + +from __future__ import annotations + +import copy +from typing import Any + +import pytest + +from a2ui.core import Catalog +from a2ui.core.basic_catalog import BasicCatalog +from a2ui.inference_formats.decision.archetypes import ( + ArchetypeGrammar, + load_asset, +) +from a2ui.inference_formats.decision.catalog_graph import CatalogDecisionGraph +from a2ui.inference_formats.decision.models import ( + BlockBindings, + PageBindings, + SlotBinding, +) +from a2ui.inference_formats.decision.patterns import ( + MergedPatternLibrary, + ResolvedPattern, + PatternError, + PatternExpander, + PatternLibrary, + eligible_archetypes, + resolve_fallback_pattern, +) +from a2ui.inference_formats.decision.payload_inspector import ( + inspect_payload_pointers, +) +from a2ui.utils import validate_payload + +from .layout_fixtures import HOST, RESORT, SETTINGS, TRANSFER + + +def _two_component_domain_catalog() -> Catalog: + """Two-component domain catalog (`TelemetryBadge`, `AlertFrame`) with no basic patterns.""" + return Catalog.from_json({ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "catalogId": "https://example.com/catalogs/telemetry/v1/catalog.json", + "protocolVersion": "1.0", + "components": { + "TelemetryBadge": { + "type": "object", + "properties": { + "component": {"const": "TelemetryBadge"}, + "metric": {"$ref": "common_types.json#/$defs/DynamicString"}, + }, + "required": ["component", "metric"], + }, + "AlertFrame": { + "type": "object", + "properties": { + "component": {"const": "AlertFrame"}, + "child": {"$ref": "common_types.json#/$defs/ComponentId"}, + }, + "required": ["component", "child"], + }, + }, + "functions": {}, + }) + + +def _wrap_surface( + components: list[dict[str, Any]], *, version: str = "1.0" +) -> list[dict[str, Any]]: + """Wraps expanded `components` in a valid `createSurface` + `updateComponents` envelope.""" + has_root = any(c.get("id") == "root" for c in components) + all_comps = list(components) + if not has_root: + first_id = str(all_comps[0]["id"]) + all_comps.insert( + 0, + { + "id": "root", + "component": "Column", + "children": [first_id], + }, + ) + catalog_id = BasicCatalog("v1.0" if version == "1.0" else "v0.9").catalog_id + return [ + { + "version": f"v{version}", + "createSurface": { + "surfaceId": "test_surface", + "catalogId": catalog_id, + }, + }, + { + "version": f"v{version}", + "updateComponents": { + "surfaceId": "test_surface", + "components": all_comps, + }, + }, + ] + + +# --- 1. Schema Rejection of Malformed Pattern Files --- + + +def test_pattern_library_rejects_missing_root() -> None: + raw = copy.deepcopy(load_asset("patterns/basic_v1_0.json")) + del raw["patterns"]["banner"]["root"] + with pytest.raises(PatternError, match="banner"): + PatternLibrary.from_json(raw) + + +def test_pattern_library_rejects_unknown_directive_in_children() -> None: + raw = copy.deepcopy(load_asset("patterns/basic_v1_0.json")) + raw["patterns"]["banner"]["components"][0]["children"] = [ + {"$unknownDirective": "banner_text"} + ] + with pytest.raises(PatternError): + PatternLibrary.from_json(raw) + + +def test_pattern_library_rejects_non_mapping_json() -> None: + with pytest.raises(PatternError, match="must be an object"): + PatternLibrary.from_json(["not", "a", "dict"]) # type: ignore[arg-type] + + +# --- 2 & 3. Catalog Matching & Pattern Capabilities --- + + +def test_for_catalogs_matches_v1_0_and_v0_9_basic_catalogs() -> None: + lib_v10 = MergedPatternLibrary.for_catalogs([BasicCatalog("v1.0")]) + lib_v09 = MergedPatternLibrary.for_catalogs([BasicCatalog("v0.9")]) + + for lib in (lib_v10, lib_v09): + assert lib.has_pattern("page") + assert lib.has_pattern("headline") + assert lib.has_pattern("collection", "rows") + assert lib.has_pattern("collection", "cards") + assert lib.has_pattern("collection", "reel") + assert lib.has_pattern("collection:cards") + assert lib.has_pattern("collection:reel") + assert not lib.has_pattern("collection", "grid") + assert not lib.has_pattern("collection:grid") + assert not lib.has_pattern("chart") + assert not lib.has_pattern("timeline") + assert not lib.has_pattern("map") + + +# --- 4. Multi-Catalog Merge & Primary Catalog Precedence --- + + +def test_multi_catalog_merge_and_primary_precedence() -> None: + basic_raw = copy.deepcopy(load_asset("patterns/basic_v1_0.json")) + basic_lib = PatternLibrary.from_json(basic_raw) + + domain_raw = { + "version": "1", + "catalogIds": ["https://example.com/catalogs/domain/v1/catalog.json"], + "patterns": { + "chart": { + "slots": ["series", "title"], + "root": "chart_root", + "components": [{ + "id": "chart_root", + "component": "Text", + "text": {"$slot": "title", "$default": "Chart"}, + }], + }, + "headline": { + "slots": ["headline"], + "root": "domain_headline", + "components": [{ + "id": "domain_headline", + "component": "Text", + "text": {"$slot": "headline"}, + }], + }, + }, + } + domain_lib = PatternLibrary.from_json(domain_raw) + + merged_domain_first = MergedPatternLibrary([domain_lib, basic_lib]) + assert merged_domain_first.has_pattern("chart") + assert merged_domain_first.has_pattern("facts") + assert ( + merged_domain_first.owner_catalog_id("headline") + == "https://example.com/catalogs/domain/v1/catalog.json" + ) + headline_pat = merged_domain_first.get("headline") + assert headline_pat is not None + assert headline_pat.variants[0].root == "domain_headline" + + merged_basic_first = MergedPatternLibrary([basic_lib, domain_lib]) + assert merged_basic_first.has_pattern("chart") + assert merged_basic_first.owner_catalog_id("headline") == basic_lib.catalog_id + basic_headline = merged_basic_first.get("headline") + assert basic_headline is not None + assert basic_headline.variants[0].root == "headline_row" + + +# --- 5 & 6. Eligibility across Fixtures & Domain Catalogs --- + + +def test_eligibility_on_four_layout_fixtures_against_basic_v1() -> None: + grammar = ArchetypeGrammar.default() + lib = MergedPatternLibrary.for_catalogs([BasicCatalog("v1.0")]) + + resort_ptrs = inspect_payload_pointers( + RESORT.payload, mutable_paths=RESORT.mutable_paths + ) + resort_ids = {a.id for a in eligible_archetypes(grammar, lib, resort_ptrs)} + assert {"detail", "feed"} <= resort_ids + + host_ptrs = inspect_payload_pointers(HOST.payload, mutable_paths=HOST.mutable_paths) + host_ids = {a.id for a in eligible_archetypes(grammar, lib, host_ptrs)} + assert "dashboard" in host_ids + + transfer_ptrs = inspect_payload_pointers( + TRANSFER.payload, mutable_paths=TRANSFER.mutable_paths + ) + transfer_ids = {a.id for a in eligible_archetypes(grammar, lib, transfer_ptrs)} + assert {"confirm", "checkout", "result"} <= transfer_ids + + settings_ptrs = inspect_payload_pointers( + SETTINGS.payload, mutable_paths=SETTINGS.mutable_paths + ) + settings_ids = {a.id for a in eligible_archetypes(grammar, lib, settings_ptrs)} + assert {"settings", "form"} <= settings_ids + + # `grid` is not offered by basic_v1_0.json on collection + assert not lib.has_pattern("collection", "grid") + assert eligible_archetypes(grammar, lib, ()) == () + + +def test_eligibility_two_component_domain_catalog_has_zero_archetypes() -> None: + grammar = ArchetypeGrammar.default() + domain_cat = _two_component_domain_catalog() + lib = MergedPatternLibrary.for_catalogs([domain_cat]) + + for fixture in (RESORT, HOST, TRANSFER, SETTINGS): + ptrs = inspect_payload_pointers( + fixture.payload, mutable_paths=fixture.mutable_paths + ) + assert eligible_archetypes(grammar, lib, ptrs) == () + + +# --- 7. Expander on Every Basic v1 Pattern (v1.0 & v0.9 Validation) --- + + +@pytest.mark.parametrize("version", ["1.0", "0.9"]) +def test_expand_every_basic_v1_pattern_validates(version: str) -> None: + catalog = BasicCatalog(f"v{version}") + lib = MergedPatternLibrary.for_catalogs([catalog]) + graph = CatalogDecisionGraph([catalog]) + expander = PatternExpander(lib, graph) + + # 1. banner + banner_comps = expander.expand_block( + "banner", + "banner", + BlockBindings(slots={"message": SlotBinding(pointer="/notice")}), + knobs={"tone": "warning"}, + ) + validate_payload([catalog], _wrap_surface(banner_comps, version=version)) + + # 2. picture (single & gallery) + pic_single = expander.expand_block( + "hero_media", + "picture", + BlockBindings( + slots={ + "source": SlotBinding(pointer="/photos/0/url"), + "caption": SlotBinding(literal="Pool at dusk"), + } + ), + knobs={"count": "single"}, + ) + validate_payload([catalog], _wrap_surface(pic_single, version=version)) + + pic_gallery = expander.expand_block( + "hero_media", + "picture", + BlockBindings( + slots={ + "source": SlotBinding( + pointer="/photos", + fields={"source": SlotBinding(pointer="/url")}, + ), + "caption": SlotBinding(literal="Gallery"), + } + ), + knobs={"count": "gallery"}, + ) + validate_payload([catalog], _wrap_surface(pic_gallery, version=version)) + + # 3. media (video & audio) + media_video = expander.expand_block( + "player", + "media", + BlockBindings( + slots={ + "source": SlotBinding(literal="https://example.com/clip.mp4"), + "poster": SlotBinding(literal="https://example.com/poster.jpg"), + "caption": SlotBinding(literal="Keynote"), + } + ), + ) + validate_payload([catalog], _wrap_surface(media_video, version=version)) + + media_audio = expander.expand_block( + "player", + "media", + BlockBindings( + slots={ + "source": SlotBinding(literal="https://example.com/ep1.mp3"), + "caption": SlotBinding(literal="Episode 1"), + } + ), + ) + validate_payload([catalog], _wrap_surface(media_audio, version=version)) + + # 4. filters (tabs & chips) + for style in ("tabs", "chips"): + filters_comps = expander.expand_block( + "filter_bar", + "filters", + BlockBindings( + slots={ + "query": SlotBinding(pointer="/query"), + "categories": SlotBinding( + literal=["All", "Active"], + fields={"selected": SlotBinding(pointer="/selected")}, + ), + } + ), + knobs={"style": style}, + ) + validate_payload([catalog], _wrap_surface(filters_comps, version=version)) + + # 5. headline + headline_comps = expander.expand_block( + "header", + "headline", + BlockBindings( + slots={ + "headline": SlotBinding(pointer="/name"), + "subhead": SlotBinding(literal=" Boutique Resort"), + "eyebrow": SlotBinding(literal="Featured"), + "status": SlotBinding(literal="Open"), + "icon": SlotBinding(literal="star"), + } + ), + ) + validate_payload([catalog], _wrap_surface(headline_comps, version=version)) + + # 6. facts + facts_comps = expander.expand_block( + "key_facts", + "facts", + BlockBindings( + slots={ + "rows": SlotBinding( + items=( + { + "label": SlotBinding(literal="CPU"), + "value": SlotBinding(pointer="/cpu"), + "note": SlotBinding(pointer="/cpuDelta"), + }, + { + "label": SlotBinding(literal="Host"), + "value": SlotBinding(pointer="/host"), + }, + ) + ) + } + ), + instances={"0": {"prominent": "true"}}, + ) + validate_payload([catalog], _wrap_surface(facts_comps, version=version)) + + # 7. prose + prose_comps = expander.expand_block( + "body_copy", + "prose", + BlockBindings( + slots={ + "title": SlotBinding(literal="Overview"), + "body": SlotBinding(pointer="/about"), + } + ), + ) + validate_payload([catalog], _wrap_surface(prose_comps, version=version)) + + # 8. collection (rows, cards, reel) + for layout_knob in ("rows", "cards", "reel"): + coll_comps = expander.expand_block( + "items_list", + "collection", + BlockBindings( + slots={ + "items": SlotBinding( + pointer="/photos", + fields={ + "headline": SlotBinding(pointer="/caption"), + "picture": SlotBinding(pointer="/url"), + "supporting": SlotBinding(literal="View details"), + }, + ) + } + ), + knobs={"layout": layout_knob, "trailing": "button"}, + ) + validate_payload([catalog], _wrap_surface(coll_comps, version=version)) + + # 9. comparison + comp_comps = expander.expand_block( + "options_table", + "comparison", + BlockBindings( + slots={ + "options": SlotBinding( + items=( + { + "title": SlotBinding(literal="Basic"), + "price": SlotBinding(literal="$10"), + "action": SlotBinding(literal="Choose Basic"), + }, + { + "title": SlotBinding(literal="Pro"), + "price": SlotBinding(literal="$25"), + "highlight": SlotBinding(literal="Popular"), + "action": SlotBinding(literal="Choose Pro"), + }, + ) + ) + } + ), + instances={"1": {"recommended": "true"}}, + ) + validate_payload([catalog], _wrap_surface(comp_comps, version=version)) + + # 10. steps + steps_comps = expander.expand_block( + "progress_steps", + "steps", + BlockBindings( + slots={ + "items": SlotBinding( + items=( + { + "title": SlotBinding(literal="Verify"), + "detail": SlotBinding(literal="Checked"), + "state": SlotBinding(literal="done"), + }, + { + "title": SlotBinding(literal="Confirm"), + "state": SlotBinding(literal="active"), + }, + ) + ) + } + ), + knobs={"numbered": "yes"}, + ) + validate_payload([catalog], _wrap_surface(steps_comps, version=version)) + + # 11. form (all 9 fieldVariants) + form_items = [] + for idx, control in enumerate(( + "shortText", + "longText", + "number", + "obscured", + "toggle", + "choice", + "multiChoice", + "range", + "date", + )): + form_items.append({ + "label": SlotBinding(literal=f"Field {idx}"), + "value": SlotBinding(pointer=f"/f{idx}"), + "options": SlotBinding(literal=["A", "B"]), + "control": SlotBinding(literal=control), + }) + form_comps = expander.expand_block( + "input_fields", + "form", + BlockBindings(slots={"fields": SlotBinding(items=tuple(form_items))}), + ) + validate_payload([catalog], _wrap_surface(form_comps, version=version)) + form_comp_types = {c["component"] for c in form_comps} + assert { + "TextField", + "CheckBox", + "ChoicePicker", + "Slider", + "DateTimeInput", + } <= form_comp_types + + # 12. groups (all 4 fieldVariants) + group_rows = [ + { + "label": SlotBinding(literal="Notifications"), + "value": SlotBinding(pointer="/notifications/newEpisodes"), + "row_kind": SlotBinding(literal="switch"), + }, + { + "label": SlotBinding(literal="Skip forward"), + "value": SlotBinding(pointer="/playback/skipForward"), + "row_kind": SlotBinding(literal="value"), + }, + { + "label": SlotBinding(literal="Privacy"), + "row_kind": SlotBinding(literal="navigation"), + }, + { + "label": SlotBinding(literal="Sign out"), + "row_kind": SlotBinding(literal="danger"), + }, + ] + groups_comps = expander.expand_block( + "setting_groups", + "groups", + BlockBindings( + slots={ + "groups": SlotBinding( + items=( + { + "heading": SlotBinding(literal="General"), + "rows": SlotBinding(items=tuple(group_rows)), + }, + ) + ) + } + ), + ) + validate_payload([catalog], _wrap_surface(groups_comps, version=version)) + groups_comp_types = {c["component"] for c in groups_comps} + assert {"CheckBox", "Button", "Text"} <= groups_comp_types + + # 13. actions + actions_comps = expander.expand_block( + "action_bar", + "actions", + BlockBindings( + slots={ + "buttons": SlotBinding( + items=( + {"label": SlotBinding(literal="Send")}, + {"label": SlotBinding(literal="Cancel")}, + ) + ) + } + ), + knobs={"order": "primaryLast"}, + instances={"0": {"primary": "true"}}, + ) + validate_payload([catalog], _wrap_surface(actions_comps, version=version)) + + # 14. outcome + outcome_comps = expander.expand_block( + "outcome_banner", + "outcome", + BlockBindings( + slots={ + "headline": SlotBinding(literal="Transfer Complete"), + "detail": SlotBinding(literal="Ref #1024"), + "status": SlotBinding(literal="success"), + } + ), + ) + validate_payload([catalog], _wrap_surface(outcome_comps, version=version)) + + # 15. conversation + conv_comps = expander.expand_block( + "messages", + "conversation", + BlockBindings( + slots={ + "messages": SlotBinding( + items=( + { + "author": SlotBinding(literal="Alex"), + "body": SlotBinding(literal="Hello!"), + "time": SlotBinding(literal="10:00"), + }, + { + "author": SlotBinding(literal="me"), + "body": SlotBinding(literal="Hi Alex!"), + "time": SlotBinding(literal="10:01"), + }, + ) + ), + "suggestions": SlotBinding( + items=({"label": SlotBinding(literal="Thanks!")},) + ), + } + ), + knobs={"self": "me"}, + ) + validate_payload([catalog], _wrap_surface(conv_comps, version=version)) + + # 16. compose + compose_comps = expander.expand_block( + "composer", + "compose", + BlockBindings( + slots={ + "input": SlotBinding(pointer="/draft"), + "placeholder": SlotBinding(literal="Reply"), + "submit": SlotBinding(literal="Send"), + } + ), + ) + validate_payload([catalog], _wrap_surface(compose_comps, version=version)) + + # 17. page (default & dialog) + for dialog in (False, True): + page_comps = expander.expand_page( + PageBindings( + title=SlotBinding(literal="Casa Verde"), + subtitle=SlotBinding(literal="Hillside Resort"), + mark=SlotBinding(literal="home"), + dialog=dialog, + ), + block_roots=[headline_comps[0]["id"]], + ) + validate_payload( + [catalog], + _wrap_surface(page_comps + headline_comps, version=version), + ) + + +# --- 8. Unbound Optional Slots Omit Child Component & Parent Reference --- + + +def test_unbound_optional_slots_omitted_from_components_and_children() -> None: + catalog = BasicCatalog("v1.0") + lib = MergedPatternLibrary.for_catalogs([catalog]) + graph = CatalogDecisionGraph([catalog]) + expander = PatternExpander(lib, graph) + + # Expand `outcome` with ONLY `headline` bound (`detail` unbound) + comps = expander.expand_block( + "outcome_block", + "outcome", + BlockBindings(slots={"headline": SlotBinding(literal="Done")}), + ) + by_id = {c["id"]: c for c in comps} + assert "outcome_block_outcome_headline" in by_id + assert "outcome_block_outcome_detail" not in by_id + root_children = by_id["outcome_block_outcome_col"]["children"] + assert "outcome_block_outcome_detail" not in root_children + + # Expand `collection` (`cards`) with `meta`, `rating`, `trailing` unbound -> `item_footer` pruned + coll_comps = expander.expand_block( + "cards_block", + "collection", + BlockBindings( + slots={ + "items": SlotBinding( + items=( + { + "headline": SlotBinding(literal="Suite"), + "picture": SlotBinding(literal="https://example.com/1.jpg"), + }, + ) + ) + } + ), + knobs={"layout": "cards", "trailing": "none"}, + ) + coll_by_id = {c["id"]: c for c in coll_comps} + assert "cards_block_0_item_supporting" not in coll_by_id + assert "cards_block_0_item_footer" not in coll_by_id + assert ( + "cards_block_0_item_footer" + not in coll_by_id["cards_block_0_item_col"]["children"] + ) + + +# --- 9. Actions Button Ordering (`primaryLast` vs `primaryFirst`) --- + + +def test_actions_button_ordering_primary_last_and_primary_first() -> None: + catalog = BasicCatalog("v1.0") + lib = MergedPatternLibrary.for_catalogs([catalog]) + graph = CatalogDecisionGraph([catalog]) + expander = PatternExpander(lib, graph, protocol_version="1.0") + + bindings = BlockBindings( + slots={ + "buttons": SlotBinding( + items=( + {"label": SlotBinding(literal="Send")}, + {"label": SlotBinding(literal="Cancel")}, + ) + ) + } + ) + + for instances_arg in ( + {"Send": {"primary": "true"}}, + {"0": {"primary": "true"}}, + ): + last_comps = expander.expand_block( + "action_bar", + "actions", + bindings, + {"order": "primaryLast"}, + instances_arg, + "action_bar", + ) + last_by_id = {c["id"]: c for c in last_comps} + last_btn_ids = last_by_id["action_bar_actions_row"]["children"] + first_btn = last_by_id[last_btn_ids[0]] + second_btn = last_by_id[last_btn_ids[1]] + assert first_btn.get("variant") == "default" + assert last_by_id[first_btn["child"]]["text"] == "Cancel" + assert second_btn.get("variant") == "primary" + assert last_by_id[second_btn["child"]]["text"] == "Send" + + first_comps = expander.expand_block( + "action_bar", + "actions", + bindings, + knobs={"order": "primaryFirst"}, + instances={"0": {"primary": "true"}}, + ) + first_by_id = {c["id"]: c for c in first_comps} + first_btn_ids = first_by_id["action_bar_actions_row"]["children"] + assert first_by_id[first_btn_ids[0]].get("variant") == "primary" + assert first_by_id[first_by_id[first_btn_ids[0]]["child"]]["text"] == "Send" + assert first_by_id[first_btn_ids[1]].get("variant") == "default" + assert first_by_id[first_by_id[first_btn_ids[1]]["child"]]["text"] == "Cancel" + + +# --- 10. v0.9 Catalog `$repeat` Template ChildList & Binding Syntax --- + + +def test_v09_repeat_template_child_list_and_bindings() -> None: + catalog = BasicCatalog("v0.9") + lib = MergedPatternLibrary.for_catalogs([catalog]) + graph = CatalogDecisionGraph([catalog]) + expander = PatternExpander(lib, graph) + + comps = expander.expand_block( + "items_list", + "collection", + BlockBindings( + slots={ + "items": SlotBinding( + pointer="/photos", + fields={ + "headline": SlotBinding(pointer="/caption"), + "picture": SlotBinding(pointer="/url"), + }, + ) + } + ), + knobs={"layout": "cards"}, + ) + by_id = {c["id"]: c for c in comps} + list_comp = by_id["items_list_list"] + assert list_comp["children"] == { + "path": "/photos", + "componentId": "items_list_item", + } + img_comp = by_id["items_list_item_img"] + assert img_comp["url"] == {"path": "url"} + title_comp = by_id["items_list_item_headline"] + assert title_comp["text"] == { + "call": "formatString", + "args": {"value": "**${caption}**"}, + } + validate_payload([catalog], _wrap_surface(comps, version="0.9")) + + +# --- 11. Markdown Heading Escaping, `formatString`, & Fallback Walking --- + + +def test_markdown_heading_escapes_hash_and_newlines_and_emits_format_string() -> None: + catalog = BasicCatalog("v1.0") + lib = MergedPatternLibrary.for_catalogs([catalog]) + graph = CatalogDecisionGraph([catalog]) + expander = PatternExpander(lib, graph) + + # Literal with `#` and newline inside a `## {headline}` template (`outcome`) + lit_comps = expander.expand_block( + "header", + "outcome", + BlockBindings(slots={"headline": SlotBinding(literal="Room #4\nSuite")}), + ) + lit_by_id = {c["id"]: c for c in lit_comps} + title_text = lit_by_id["header_outcome_headline"]["text"] + assert isinstance(title_text, str) + assert "\n" not in title_text + assert r"\#4" in title_text + + # Bound pointer inside `## {headline}` emits `formatString` function call + ptr_comps = expander.expand_block( + "header", + "outcome", + BlockBindings(slots={"headline": SlotBinding(pointer="/name")}), + ) + ptr_by_id = {c["id"]: c for c in ptr_comps} + assert ptr_by_id["header_outcome_headline"]["text"] == { + "@call": "formatString", + "args": {"value": "## ${/name}"}, + } + + +def test_fallback_chain_walking_for_timeline_and_map() -> None: + grammar = ArchetypeGrammar.default() + catalog = BasicCatalog("v1.0") + lib = MergedPatternLibrary.for_catalogs([catalog]) + graph = CatalogDecisionGraph([catalog]) + expander = PatternExpander(lib, graph) + + timeline_block = grammar.block("timeline") + assert timeline_block is not None + assert resolve_fallback_pattern(timeline_block, lib) == ResolvedPattern("steps") + + timeline_comps = expander.expand_block( + "timeline", + "timeline", + BlockBindings( + slots={ + "events": SlotBinding( + items=( + { + "title": SlotBinding(literal="Departed"), + "time": SlotBinding(literal="09:00"), + }, + ) + ) + } + ), + ) + validate_payload([catalog], _wrap_surface(timeline_comps)) + + map_block = grammar.block("map") + assert map_block is not None + assert resolve_fallback_pattern(map_block, lib) == ResolvedPattern("facts") + + map_comps = expander.expand_block( + "map", + "map", + BlockBindings( + slots={ + "location": SlotBinding(literal="100 Main St"), + "label": SlotBinding(literal="Address"), + } + ), + ) + validate_payload([catalog], _wrap_surface(map_comps)) + + chart_block = grammar.block("chart") + assert chart_block is not None + assert resolve_fallback_pattern(chart_block, lib) == ResolvedPattern("headline") + + chart_comps = expander.expand_block( + "chart", + "chart", + BlockBindings( + slots={ + "series": SlotBinding( + items=( + { + "label": SlotBinding(literal="CPU"), + "value": SlotBinding(literal="78%"), + }, + ) + ) + } + ), + ) + validate_payload([catalog], _wrap_surface(chart_comps)) + + # Fallback when `comparison` is absent -> `collection:cards` + raw_without_cmp = copy.deepcopy(load_asset("patterns/basic_v1_0.json")) + del raw_without_cmp["patterns"]["comparison"] + lib_without_cmp = PatternLibrary.from_json(raw_without_cmp) + cmp_block = grammar.block("comparison") + assert cmp_block is not None + assert resolve_fallback_pattern(cmp_block, lib_without_cmp) == ResolvedPattern( + "collection", {"layout": "cards"} + ) + exp_without_cmp = PatternExpander(lib_without_cmp, graph) + fb_cmp_comps = exp_without_cmp.expand_block( + "comparison", + "comparison", + BlockBindings( + slots={ + "options": SlotBinding( + items=( + { + "headline": SlotBinding(literal="Pro"), + "highlight": SlotBinding(literal="$25/mo"), + }, + ) + ) + } + ), + ) + validate_payload([catalog], _wrap_surface(fb_cmp_comps)) + + with pytest.raises(PatternError, match="not available"): + expander.expand_block("unknown_block", "nonexistent_pattern", BlockBindings()) + + +def test_by_type_honors_slot_binding_semantic_type_and_fallback_remaps() -> None: + """Tests `SlotBinding.semantic_type` dispatch (H2), root pruning (M4), and fallback slot adaptation (M5).""" + catalog = BasicCatalog("v1.0") + lib = MergedPatternLibrary.for_catalogs([catalog]) + graph = CatalogDecisionGraph([catalog]) + expander = PatternExpander(lib, graph) + + # H2: /stream/resource has no audio/video substring in the path, but carries semantic_type="audio_url" + media_comps = expander.expand_block( + "player", + "media", + BlockBindings( + slots={ + "source": SlotBinding( + pointer="/stream/resource", + semantic_type="audio_url", + ), + "caption": SlotBinding(literal="Episode 42"), + } + ), + ) + validate_payload([catalog], _wrap_surface(media_comps)) + assert any(c["component"] == "AudioPlayer" for c in media_comps) + + # M5: headline -> facts fallback remaps `items` -> `rows`, and timeline -> collection remaps `title` -> `headline` + raw_no_hl_tl = copy.deepcopy(load_asset("patterns/basic_v1_0.json")) + del raw_no_hl_tl["patterns"]["headline"] + del raw_no_hl_tl["patterns"]["steps"] + exp_fallback = PatternExpander(PatternLibrary.from_json(raw_no_hl_tl), graph) + + hl_as_facts = exp_fallback.expand_block( + "headline", + "headline", + BlockBindings( + slots={ + "items": SlotBinding( + items=( + { + "label": SlotBinding(literal="CPU"), + "value": SlotBinding(literal="82%"), + }, + ) + ) + } + ), + ) + validate_payload([catalog], _wrap_surface(hl_as_facts)) + assert any(c.get("text") == "82%" for c in hl_as_facts) + + # M5: timeline -> collection fallback remaps `title` -> `headline` + tl_as_col = exp_fallback.expand_block( + "timeline", + "timeline", + BlockBindings( + slots={ + "events": SlotBinding( + items=( + { + "title": SlotBinding(literal="Shipped"), + "time": SlotBinding(literal="10:00"), + }, + ) + ) + } + ), + ) + validate_payload([catalog], _wrap_surface(tl_as_col)) + assert any("Shipped" in str(c.get("text", "")) for c in tl_as_col) + + # M4: empty container child of pattern root is pruned from root["children"] + raw_pat = copy.deepcopy(load_asset("patterns/basic_v1_0.json")) + raw_pat["patterns"]["media"]["components"][0]["children"].append( + {"id": "empty_sub"} + ) + raw_pat["patterns"]["media"]["components"].append({ + "id": "empty_sub", + "component": "Row", + "children": [{"id": "opt_txt", "$if": "nonexistent_slot"}], + }) + raw_pat["patterns"]["media"]["components"].append( + {"id": "opt_txt", "component": "Text", "text": "Never"} + ) + custom_lib = PatternLibrary.from_json(raw_pat) + custom_exp = PatternExpander(custom_lib, graph) + pruned_comps = custom_exp.expand_block( + "media", + "media", + BlockBindings(slots={"source": SlotBinding(literal="https://a/b.mp4")}), + ) + validate_payload([catalog], _wrap_surface(pruned_comps)) + defined_ids = {c["id"] for c in pruned_comps} + for comp in pruned_comps: + if isinstance(comp.get("children"), list): + assert all(cid in defined_ids for cid in comp["children"]) + + +def test_pattern_ref_parses_one_separator_and_libraries_reject_dotted_variants() -> ( + None +): + from a2ui.inference_formats.decision.patterns import PatternRef + + assert PatternRef.parse("collection") == PatternRef("collection") + assert PatternRef.parse("collection:grid") == PatternRef("collection", "grid") + assert str(PatternRef("collection", "cards")) == "collection:cards" + lib = MergedPatternLibrary.for_catalogs([BasicCatalog("v1.0")]) + assert lib.has_pattern("collection:cards") + assert lib.has_pattern("collection", "cards") + # The dotted spelling is no longer a variant query; it names an unknown pattern. + assert not lib.has_pattern("collection.cards") + assert not hasattr(lib, "has") + + +def test_eligible_archetypes_is_pure_and_synthesizer_cache_is_per_instance() -> None: + import a2ui.inference_formats.decision.patterns as patterns_module + from a2ui.inference_formats.decision import DecisionSynthesizer, DeterministicMockBackend + from a2ui.inference_formats.decision.patterns import shape_signature + + assert not hasattr(patterns_module, "_ELIGIBILITY_CACHE") + grammar = ArchetypeGrammar.default() + catalog = BasicCatalog("v1.0") + lib = MergedPatternLibrary.for_catalogs([catalog]) + ptrs = inspect_payload_pointers(RESORT.payload) + first = eligible_archetypes(grammar, lib, ptrs) + assert first == eligible_archetypes(grammar, lib, ptrs) + assert shape_signature(ptrs) == shape_signature( + inspect_payload_pointers(RESORT.payload) + ) + + synth_a = DecisionSynthesizer([catalog], DeterministicMockBackend()) + synth_b = DecisionSynthesizer([catalog], DeterministicMockBackend()) + assert synth_a._eligible_archetypes(ptrs) == first + assert synth_a._eligibility_cache is not synth_b._eligibility_cache + assert len(synth_b._eligibility_cache) == 0 diff --git a/python/a2ui_agent/tests/decision/test_semantic_types.py b/python/a2ui_agent/tests/decision/test_semantic_types.py new file mode 100644 index 0000000000..013a2414c4 --- /dev/null +++ b/python/a2ui_agent/tests/decision/test_semantic_types.py @@ -0,0 +1,437 @@ +# 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. + +"""Unit tests for semantic pointer classification and payload inspection.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +import pytest + +from a2ui.inference_formats.decision.models import ( + DEFERRED_SEMANTIC_TYPES, + SemanticType, +) +from a2ui.inference_formats.decision.payload_inspector import ( + inspect_payload_pointers, +) +from a2ui.inference_formats.decision.semantic_types import ( + classify_array_field, + classify_scalar, + humanize_key, + prose_length_level, +) + +from .layout_fixtures import HOST, RESORT, SETTINGS, TRANSFER + +POSITIVE_CASES: tuple[tuple[SemanticType, Any, str, Mapping[str, Any] | None], ...] = ( + # Text (7) + (SemanticType.STRING, "prod-1", "host", None), + (SemanticType.STRING, "Alex Chen", "recipient", None), + ( + SemanticType.LONG_TEXT, + "Open-air pavilions with a saltwater infinity pool above the coast.", + "about", + None, + ), + ( + SemanticType.LONG_TEXT, + " ".join(["sentence"] * 18), + "plainField", + None, + ), + (SemanticType.MARKDOWN, "# Welcome\n\nRead **more** here.", "note", None), + (SemanticType.MARKDOWN, "Plain body with markdown key", "markdown", None), + (SemanticType.CODE, "SELECT id, email FROM users WHERE active = 1", "text", None), + (SemanticType.CODE, "total * 0.15", "formula", None), + (SemanticType.NAME, "Casa Verde", "name", None), + (SemanticType.NAME, "Elena Mora", "author", None), + (SemanticType.TITLE, "Quarterly Report", "title", None), + (SemanticType.TITLE, "System Health", "headline", None), + ( + SemanticType.IDENTIFIER, + "550e8400-e29b-41d4-a716-446655440000", + "record", + None, + ), + (SemanticType.IDENTIFIER, "ord_98765", "orderId", None), + # Contact & links (7) + (SemanticType.EMAIL, "alex@example.com", "contact", None), + (SemanticType.EMAIL, "mailto:help@example.org", "support", None), + (SemanticType.PHONE, "+1 (415) 555-0199", "contact", None), + (SemanticType.PHONE, "415-555-0123", "phone", None), + (SemanticType.URL, "https://example.com/docs", "website", None), + (SemanticType.URL, "/settings/security", "href", None), + ( + SemanticType.IMAGE_URL, + "https://example.com/casa-verde/logo.png", + "logoUrl", + None, + ), + ( + SemanticType.IMAGE_URL, + "https://cdn.example.com/u/42", + "avatarUrl", + None, + ), + (SemanticType.VIDEO_URL, "https://example.com/clip.mp4", "media", None), + ( + SemanticType.VIDEO_URL, + "https://cdn.example.com/watch/99", + "trailerUrl", + None, + ), + (SemanticType.AUDIO_URL, "https://example.com/track.mp3", "media", None), + ( + SemanticType.AUDIO_URL, + "https://cdn.example.com/listen/7", + "podcastAudio", + None, + ), + ( + SemanticType.DOCUMENT_URL, + "https://example.com/statement.pdf", + "file", + None, + ), + ( + SemanticType.DOCUMENT_URL, + "https://cdn.example.com/dl/10", + "invoiceDocument", + None, + ), + # Time (6) + (SemanticType.DATE, "2026-10-24", "arrives", None), + (SemanticType.DATE, "Oct 24, 2026", "published", None), + (SemanticType.TIME, "14:30", "slot", None), + (SemanticType.TIME, "9:15 AM", "startTime", None), + (SemanticType.DATETIME, "2026-10-24T14:30:00Z", "createdAt", None), + (SemanticType.DATETIME, "2026-10-24 09:15:00+02:00", "updatedAt", None), + (SemanticType.DURATION, 30, "skipForward", None), + (SemanticType.DURATION, "PT45M", "elapsed", None), + (SemanticType.RELATIVE_TIME, "3 hours ago", "seen", None), + (SemanticType.RELATIVE_TIME, "in 5 days", "renews", None), + (SemanticType.DATE_RANGE, "2026-10-24..2026-10-27", "window", None), + (SemanticType.DATE_RANGE, "Oct 24 - Oct 27, 2026", "stayDates", None), + # Quantity (9) + (SemanticType.NUMBER, 0.78, "cpu", None), + (SemanticType.NUMBER, 1.25, "speed", None), + (SemanticType.INTEGER, 412, "uptimeHours", None), + (SemanticType.INTEGER, 16, "cores", None), + (SemanticType.COUNT, 12, "guestCount", None), + (SemanticType.COUNT, 4, "seats", None), + (SemanticType.CURRENCY, 240, "priceFrom", None), + (SemanticType.CURRENCY, "$1,250.00", "value", None), + (SemanticType.PERCENT, 12.5, "taxRate", None), + (SemanticType.PERCENT, "78%", "utilization", None), + (SemanticType.RATIO, 0.85, "confidence", None), + (SemanticType.RATIO, "3/4", "progressText", None), + (SemanticType.QUANTITY, "24.2 kWh", "energy", None), + (SemanticType.QUANTITY, 70, "weightKg", None), + (SemanticType.RATING, 4.6, "rating", None), + (SemanticType.RATING, "4.8/5", "review", None), + ( + SemanticType.BOUNDED, + 65, + "level", + {"level": 65, "min": 0, "max": 100}, + ), + (SemanticType.BOUNDED, 80, "battery", None), + # State (4) + (SemanticType.ENUM, "USD", "currency", None), + (SemanticType.ENUM, "enterprise", "tier", None), + (SemanticType.STATUS, "degraded", "status", None), + (SemanticType.STATUS, "healthy", "clusterState", None), + (SemanticType.BOOLEAN, True, "autoDownload", None), + (SemanticType.BOOLEAN, False, "healthy", None), + (SemanticType.COLOR, "#ff5733", "swatch", None), + (SemanticType.COLOR, "rgb(12, 34, 56)", "fill", None), + # Structure (3) + (SemanticType.ARRAY, ["Send", "Cancel"], "actions", None), + (SemanticType.ARRAY, [{"url": "https://example.com/1.png"}], "photos", None), + (SemanticType.OBJECT, {"speed": 1.25}, "playback", None), + (SemanticType.OBJECT, {"plan": "Family"}, "account", None), + (SemanticType.EMPTY, None, "missing", None), + (SemanticType.EMPTY, " ", "blank", None), +) + +NEGATIVE_CASES: tuple[tuple[SemanticType, Any, str, Mapping[str, Any] | None], ...] = ( + (SemanticType.STRING, 42, "host", None), + (SemanticType.LONG_TEXT, "Short", "label", None), + (SemanticType.MARKDOWN, "Just a normal label", "label", None), + (SemanticType.CODE, "Casa Verde", "name", None), + (SemanticType.NAME, "Alex Chen", "recipient", None), + (SemanticType.TITLE, "Main pool", "caption", None), + (SemanticType.IDENTIFIER, "prod-1", "host", None), + (SemanticType.EMAIL, "not-an-email", "label", None), + (SemanticType.PHONE, "2026-10-24", "arrives", None), + (SemanticType.URL, "Casa Verde", "name", None), + (SemanticType.IMAGE_URL, "https://example.com/docs", "website", None), + (SemanticType.VIDEO_URL, "https://example.com/logo.png", "logoUrl", None), + (SemanticType.AUDIO_URL, "https://example.com/clip.mp4", "videoUrl", None), + (SemanticType.DOCUMENT_URL, "https://example.com/song.mp3", "audioUrl", None), + (SemanticType.DATE, "14:30", "time", None), + (SemanticType.TIME, "2026-10-24", "date", None), + (SemanticType.DATETIME, "2026-10-24", "date", None), + (SemanticType.DURATION, 412, "uptimeHours", None), + (SemanticType.RELATIVE_TIME, "30 seconds", "duration", None), + (SemanticType.DATE_RANGE, "2026-10-24", "arrives", None), + (SemanticType.NUMBER, 16, "cores", None), + (SemanticType.INTEGER, 0.78, "cpu", None), + (SemanticType.COUNT, 240, "priceFrom", None), + (SemanticType.CURRENCY, 16, "cores", None), + (SemanticType.PERCENT, 0.78, "cpu", None), + (SemanticType.RATIO, "2026/10/24", "date", None), + (SemanticType.QUANTITY, 50, "amount", {"amount": 50, "currency": "USD"}), + (SemanticType.RATING, 100, "price", None), + ( + SemanticType.BOUNDED, + 100, + "max", + {"level": 65, "min": 0, "max": 100}, + ), + (SemanticType.ENUM, "degraded", "status", None), + (SemanticType.STATUS, "Casa Verde", "name", None), + (SemanticType.BOOLEAN, "true", "label", None), + (SemanticType.COLOR, "#notacolor", "label", None), + (SemanticType.ARRAY, [], "emptyList", None), + (SemanticType.OBJECT, {}, "emptyObj", None), + (SemanticType.EMPTY, 0, "zeroCount", None), +) + + +class TestSemanticTypesCoverage: + """Verifies coverage across every detected `SemanticType` value.""" + + def test_every_semantic_type_has_at_least_two_positive_and_one_negative_case( + self, + ) -> None: + pos_counts: dict[SemanticType, int] = {} + for sem_type, _, _, _ in POSITIVE_CASES: + pos_counts[sem_type] = pos_counts.get(sem_type, 0) + 1 + + neg_types = {sem_type for sem_type, _, _, _ in NEGATIVE_CASES} + detected = set(SemanticType) - DEFERRED_SEMANTIC_TYPES + assert set(pos_counts) == detected + for member in detected: + assert pos_counts[member] >= 2, f"fewer than 2 positive cases for {member}" + assert member in neg_types, f"missing negative case for {member}" + + @pytest.mark.parametrize(("expected", "value", "key", "siblings"), POSITIVE_CASES) + def test_positive_cases( + self, + expected: SemanticType, + value: Any, + key: str, + siblings: Mapping[str, Any] | None, + ) -> None: + actual, _ = classify_scalar(value, key, siblings=siblings) + assert actual == expected + + @pytest.mark.parametrize(("unexpected", "value", "key", "siblings"), NEGATIVE_CASES) + def test_negative_cases( + self, + unexpected: SemanticType, + value: Any, + key: str, + siblings: Mapping[str, Any] | None, + ) -> None: + actual, _ = classify_scalar(value, key, siblings=siblings) + assert actual != unexpected + + +class TestDetectorPrecedenceAndHints: + """Tests key-hint precedence, sibling hints, prose length levels, and arrays.""" + + def test_key_hint_precedes_coarse_numeric_and_url_types(self) -> None: + assert classify_scalar(240, "priceFrom") == ( + SemanticType.CURRENCY, + {"keyHint": "price"}, + ) + assert classify_scalar(30, "skipForward") == ( + SemanticType.DURATION, + {"unit": "seconds", "keyHint": "skip_forward"}, + ) + assert classify_scalar(12, "latencyMs") == ( + SemanticType.DURATION, + {"unit": "ms", "keyHint": "ms"}, + ) + assert classify_scalar( + "https://example.com/casa-verde/logo.png", "logoUrl" + ) == ( + SemanticType.IMAGE_URL, + {"keyHint": "logo"}, + ) + + def test_sibling_currency_and_unit_and_bounded_hints(self) -> None: + siblings = {"amount": 50, "fee": 0.5, "currency": "USD"} + assert classify_scalar(50, "amount", siblings=siblings) == ( + SemanticType.CURRENCY, + {"keyHint": "amount", "currency": "USD"}, + ) + + unit_siblings = {"temperature": 21.5, "unit": "°C"} + assert classify_scalar(21.5, "temperature", siblings=unit_siblings) == ( + SemanticType.QUANTITY, + {"unit": "°C"}, + ) + + bounded_siblings = {"used": 42, "min": 0, "max": 100} + assert classify_scalar(42, "used", siblings=bounded_siblings) == ( + SemanticType.BOUNDED, + {"min": 0, "max": 100}, + ) + assert classify_scalar(100, "max", siblings=bounded_siblings) == ( + SemanticType.INTEGER, + {}, + ) + + @pytest.mark.parametrize( + ("word_count", "expected_level"), + [ + (5, "line"), + (14, "line"), + (15, "blurb"), + (33, "blurb"), + (59, "blurb"), + (60, "summary"), + (199, "summary"), + (200, "article"), + (350, "article"), + ], + ) + def test_prose_length_levels_and_long_text_hints( + self, word_count: int, expected_level: str + ) -> None: + assert prose_length_level(word_count) == expected_level + text = " ".join(["word"] * word_count) + sem_type, hints = classify_scalar(text, "about") + assert sem_type == SemanticType.LONG_TEXT + assert hints["wordCount"] == word_count + assert hints["length"] == expected_level + assert hints["keyHint"] == "about" + + def test_classify_array_field_enum_status_and_mixed_numbers(self) -> None: + assert ( + classify_array_field(["active", "pending", "failed", "active"]) + == SemanticType.STATUS + ) + assert ( + classify_array_field( + ["basic", "pro", "basic", "enterprise", "basic", "pro"] + ) + == SemanticType.ENUM + ) + assert ( + classify_array_field(["Alice", "Bob", "Carol", "Dave"]) + == SemanticType.STRING + ) + assert classify_array_field([1, 2.5, 3], "values") == SemanticType.NUMBER + assert classify_array_field([None, "", " "], "notes") == SemanticType.EMPTY + + @pytest.mark.parametrize( + ("raw_key", "expected_label"), + [ + ("priceFrom", "Price from"), + ("skip_forward", "Skip forward"), + ("uptimeHours", "Uptime hours"), + ("newEpisodes", "New episodes"), + ("URLPath", "Url path"), + ("", ""), + ], + ) + def test_humanize_key(self, raw_key: str, expected_label: str) -> None: + assert humanize_key(raw_key) == expected_label + + +class TestFixturePayloadPointerSemantics: + """Verifies semantic pointer extraction on the canonical layout fixtures.""" + + def test_resort_fixture_pointers(self) -> None: + by_path = { + p.path: p + for p in inspect_payload_pointers( + RESORT.payload, mutable_paths=RESORT.mutable_paths + ) + } + assert by_path["/name"].semantic_type == "name" + assert by_path["/name"].label == "Name" + assert by_path["/logoUrl"].semantic_type == "image_url" + assert by_path["/logoUrl"].hints.get("keyHint") == "logo" + assert by_path["/rating"].semantic_type == "rating" + assert by_path["/priceFrom"].semantic_type == "currency" + assert by_path["/priceFrom"].label == "Price from" + assert by_path["/about"].semantic_type == "long_text" + assert by_path["/about"].hints["wordCount"] >= 25 + assert by_path["/about"].hints["length"] == "blurb" + + photos = by_path["/photos"] + assert photos.semantic_type == "array" + assert photos.element_semantic_types == { + "url": "image_url", + "caption": "string", + } + assert photos.sample_pointers == ("/photos/0/url",) + + def test_host_fixture_pointers(self) -> None: + by_path = { + p.path: p + for p in inspect_payload_pointers( + HOST.payload, mutable_paths=HOST.mutable_paths + ) + } + assert by_path["/host"].semantic_type == "string" + assert by_path["/cpu"].semantic_type == "number" + assert by_path["/cpuDelta"].semantic_type == "number" + assert by_path["/status"].semantic_type == "status" + assert by_path["/uptimeHours"].semantic_type == "integer" + + def test_transfer_fixture_pointers(self) -> None: + by_path = { + p.path: p + for p in inspect_payload_pointers( + TRANSFER.payload, mutable_paths=TRANSFER.mutable_paths + ) + } + assert by_path["/amount"].semantic_type == "currency" + assert by_path["/amount"].hints.get("currency") == "USD" + assert by_path["/currency"].semantic_type == "enum" + assert by_path["/recipient"].semantic_type == "string" + assert by_path["/fee"].semantic_type == "currency" + assert by_path["/fee"].hints.get("currency") == "USD" + assert by_path["/arrives"].semantic_type == "date" + assert by_path["/actions"].semantic_type == "array" + assert by_path["/actions"].mutable_hint is True + + def test_settings_fixture_pointers(self) -> None: + by_path = { + p.path: p + for p in inspect_payload_pointers( + SETTINGS.payload, mutable_paths=SETTINGS.mutable_paths + ) + } + assert by_path["/playback"].value_type == "object" + assert by_path["/playback"].semantic_type == "object" + assert by_path["/playback"].cardinality == 3 + assert by_path["/playback"].mutable_hint is True + assert by_path["/notifications"].semantic_type == "object" + assert by_path["/notifications"].cardinality == 2 + assert by_path["/account"].semantic_type == "object" + assert by_path["/account"].cardinality == 1 + assert by_path["/playback/skipForward"].semantic_type == "duration" + assert by_path["/playback/autoDownload"].semantic_type == "boolean" + assert by_path["/playback/speed"].semantic_type == "number" + assert by_path["/account/signOut"].semantic_type == "string" diff --git a/python/a2ui_agent/tests/decision/test_synthesizer.py b/python/a2ui_agent/tests/decision/test_synthesizer.py new file mode 100644 index 0000000000..37cb56cbd6 --- /dev/null +++ b/python/a2ui_agent/tests/decision/test_synthesizer.py @@ -0,0 +1,1219 @@ +# 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. + +"""Unit tests for DecisionSynthesizer across all synthesis stages and gates.""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from a2ui.core import Catalog +from a2ui.inference_formats import ( + CatalogDecisionGraph, + DecisionBackend, + DecisionSynthesizer, + SynthesisConfig, + SynthesisOutput, + SynthesisStage, + TemplateRegistry, + calibrate_thresholds, +) +from a2ui.inference_formats.decision import ( + DecisionDistribution, + DecisionQuery, + DeterministicMockBackend, + SurfaceTemplate, +) +from a2ui.parser.messages import to_message_dicts +from a2ui.utils import validate_payload + + +def _make_domain_catalog(protocol_version: str = "1.0") -> Catalog: + """Builds a custom domain catalog with leaf, container, and switcher nodes.""" + is_v1 = protocol_version.lstrip("v").startswith("1.") + call_key = "@call" if is_v1 else "call" + schema: dict[str, Any] = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "catalogId": "https://example.com/catalogs/ops/v1/catalog.json", + "protocolVersion": protocol_version, + "components": { + "TelemetryBadge": { + "type": "object", + "description": "Read-only telemetry badge.", + "properties": { + "component": {"const": "TelemetryBadge"}, + "serviceName": {"$ref": "common_types.json#/$defs/DynamicString"}, + "latencyMs": {"$ref": "common_types.json#/$defs/DynamicNumber"}, + "severity": { + "type": "string", + "enum": ["INFO", "WARN", "CRITICAL"], + }, + }, + "required": ["component", "serviceName", "latencyMs"], + }, + "ActionableControl": { + "type": "object", + "description": "Mutable control leaf with action and checkable.", + "allOf": [ + {"$ref": "common_types.json#/$defs/Checkable"}, + { + "type": "object", + "properties": { + "component": {"const": "ActionableControl"}, + "targetHost": { + "$ref": "common_types.json#/$defs/DynamicString" + }, + "replicaCount": { + "$ref": "common_types.json#/$defs/DynamicNumber" + }, + "onExecute": {"$ref": "common_types.json#/$defs/Action"}, + }, + "required": ["component", "targetHost", "onExecute"], + }, + ], + }, + "EventStreamList": { + "type": "object", + "description": "Container with a repeating ChildList.", + "properties": { + "component": {"const": "EventStreamList"}, + "clusterTitle": {"$ref": "common_types.json#/$defs/DynamicString"}, + "records": {"$ref": "common_types.json#/$defs/ChildList"}, + }, + "required": ["component", "records"], + }, + "AlertFrame": { + "type": "object", + "description": "Container wrapping a single child component.", + "properties": { + "component": {"const": "AlertFrame"}, + "innerWidget": {"$ref": "common_types.json#/$defs/ComponentId"}, + }, + "required": ["component", "innerWidget"], + }, + "WorkspaceDeck": { + "type": "object", + "description": "Multi-view switcher for competing views.", + "properties": { + "component": {"const": "WorkspaceDeck"}, + "views": { + "type": "array", + "items": { + "type": "object", + "properties": { + "tabTitle": {"type": "string"}, + "viewComponent": { + "$ref": "common_types.json#/$defs/ComponentId" + }, + }, + "required": ["tabTitle", "viewComponent"], + }, + }, + }, + "required": ["component", "views"], + }, + }, + "functions": { + "isHostReachable": { + "type": "object", + "returnType": "boolean", + "properties": { + call_key: {"const": "isHostReachable"}, + "args": { + "type": "object", + "properties": { + "host": {"$ref": "common_types.json#/$defs/DynamicString"}, + "minReplicas": {"type": "integer"}, + }, + "required": ["host", "minReplicas"], + }, + }, + "required": [call_key, "args"], + }, + }, + } + return Catalog.from_json(schema) + + +def test_public_facade_exports() -> None: + """Verifies top-level and subpackage facade exports.""" + assert CatalogDecisionGraph is not None + assert DecisionBackend is not None + assert DecisionSynthesizer is not None + assert SynthesisConfig is not None + assert SynthesisOutput is not None + assert SynthesisStage is not None + assert TemplateRegistry is not None + assert calibrate_thresholds is not None + + +@pytest.mark.asyncio +async def test_stage1_template_hit_and_miss() -> None: + """Verifies Stage 1 template selection hit and pointer-mismatch fallback.""" + catalog = _make_domain_catalog("1.0") + registry = TemplateRegistry() + registry.register( + SurfaceTemplate( + template_id="badge_tpl", + description="Pre-approved telemetry badge", + surface_id="default_surface", + catalog_id=catalog.catalog_id, + protocol_version="v1.0", + components=( + { + "id": "root", + "component": "TelemetryBadge", + "serviceName": {"@path": "/serviceName"}, + "latencyMs": {"@path": "/latencyMs"}, + }, + ), + required_pointers=("/serviceName", "/latencyMs"), + ) + ) + + backend = DeterministicMockBackend( + scripted={ + "template_select": {"badge_tpl": 0.90}, + "root_component": {"TelemetryBadge": 0.88}, + } + ) + synth = DecisionSynthesizer([catalog], backend, registry=registry) + + hit_out = await synth.synthesize( + "Show service telemetry", + {"serviceName": "auth-api", "latencyMs": 12.4}, + surface_id="custom_s1", + ) + assert hit_out.stage == SynthesisStage.TEMPLATE_SELECT + assert hit_out.selected_template_id == "badge_tpl" + assert hit_out.confidence == pytest.approx(0.90) + assert hit_out.component_tree_spec == { + "template_id": "badge_tpl", + "root_component": "TelemetryBadge", + } + validate_payload([catalog], hit_out.messages) + express_str = hit_out.to_express([catalog]) + assert "TelemetryBadge" in express_str + + # Missing required pointer '/latencyMs' bypasses Stage 1 and uses Stage 2A. + miss_out = await synth.synthesize( + "Show service telemetry", + {"serviceName": "auth-api"}, + ) + assert miss_out.stage == SynthesisStage.FAST_1PASS_LEAF + assert miss_out.selected_template_id is None + + +@pytest.mark.asyncio +async def test_mutability_risk_tiers_across_stages() -> None: + """Verifies stricter threshold gating for mutable templates, paths, and actions.""" + catalog = _make_domain_catalog("1.0") + registry = TemplateRegistry() + registry.register( + SurfaceTemplate( + template_id="readonly_tpl", + description="Read-only telemetry template", + surface_id="s1", + catalog_id=catalog.catalog_id, + protocol_version="v1.0", + components=( + { + "id": "root", + "component": "TelemetryBadge", + "serviceName": {"@path": "/serviceName"}, + "latencyMs": {"@path": "/latencyMs"}, + }, + ), + required_pointers=("/serviceName", "/latencyMs"), + is_mutable=False, + ) + ) + registry.register( + SurfaceTemplate( + template_id="other_tpl", + description="Alternative template", + surface_id="s2", + catalog_id=catalog.catalog_id, + protocol_version="v1.0", + components=( + { + "id": "root", + "component": "TelemetryBadge", + "serviceName": {"@path": "/serviceName"}, + "latencyMs": {"@path": "/latencyMs"}, + }, + ), + required_pointers=("/serviceName", "/latencyMs"), + is_mutable=True, + ) + ) + + # Top probability 0.80 is >= template_confidence_threshold (0.75) + # but < mutable_confidence_threshold (0.85). + backend = DeterministicMockBackend( + scripted={ + "template_select": {"readonly_tpl": 0.80, "other_tpl": 0.20}, + "root_component": {"ActionableControl": 0.80, "TelemetryBadge": 0.20}, + } + ) + config = SynthesisConfig( + template_confidence_threshold=0.75, + mutable_confidence_threshold=0.85, + abstain_threshold=0.40, + ) + synth = DecisionSynthesizer([catalog], backend, registry=registry, config=config) + + # Read-only call succeeds in Stage 1 at 0.80 >= 0.75. + ro_out = await synth.synthesize( + "Show telemetry", + {"serviceName": "payments", "latencyMs": 42}, + ) + assert ro_out.stage == SynthesisStage.TEMPLATE_SELECT + + # Passing mutable_paths elevates Stage 1 threshold to 0.85 -> Stage 1 rejected, + # and Stage 2A ActionableControl also requires 0.85 -> abstains! + mut_out = await synth.synthesize( + "Update telemetry control", + {"serviceName": "payments", "latencyMs": 42}, + mutable_paths=["/latencyMs"], + ) + assert mut_out.stage == SynthesisStage.ABSTAIN_FALLBACK + assert mut_out.messages == [] + + +@pytest.mark.asyncio +async def test_uncalibrated_logit_margin_rejection() -> None: + """Verifies uncalibrated backend distributions require min top_logit_margin.""" + catalog = _make_domain_catalog("1.0") + registry = TemplateRegistry() + registry.register( + SurfaceTemplate( + template_id="badge_tpl", + description="Telemetry template", + surface_id="s1", + catalog_id=catalog.catalog_id, + protocol_version="v1.0", + components=( + { + "id": "root", + "component": "TelemetryBadge", + "serviceName": {"@path": "/serviceName"}, + "latencyMs": {"@path": "/latencyMs"}, + }, + ), + required_pointers=("/serviceName", "/latencyMs"), + ) + ) + + low_margin_backend = DeterministicMockBackend( + scripted={ + "template_select": {"badge_tpl": 0.95}, + "root_component": {"TelemetryBadge": 0.95}, + }, + calibrated=False, + default_logit_margin=0.5, + ) + synth_low = DecisionSynthesizer( + [catalog], + low_margin_backend, + registry=registry, + config=SynthesisConfig(uncalibrated_min_logit_margin=1.5), + ) + rejected = await synth_low.synthesize( + "Show telemetry", + {"serviceName": "api", "latencyMs": 10}, + ) + assert rejected.stage == SynthesisStage.ABSTAIN_FALLBACK + + high_margin_backend = DeterministicMockBackend( + scripted={"root_component": {"TelemetryBadge": 0.95}}, + calibrated=False, + default_logit_margin=2.2, + ) + synth_high = DecisionSynthesizer( + [catalog], + high_margin_backend, + config=SynthesisConfig(uncalibrated_min_logit_margin=1.5), + ) + accepted = await synth_high.synthesize( + "Show telemetry", + {"serviceName": "api", "latencyMs": 10}, + ) + assert accepted.stage == SynthesisStage.FAST_1PASS_LEAF + + +@pytest.mark.asyncio +async def test_stage2a_leaf_fast_path_bindings_and_checks() -> None: + """Verifies Stage 2A binds DATA_VALUE, STATIC_ENUM, ACTION, and checks.""" + catalog = _make_domain_catalog("1.0") + backend = DeterministicMockBackend( + scripted={ + "root_component:critical badge": { + "TelemetryBadge": 0.92, + "ActionableControl": 0.08, + }, + "root_component:execute control": { + "ActionableControl": 0.94, + "TelemetryBadge": 0.06, + }, + } + ) + synth = DecisionSynthesizer([catalog], backend) + + badge_out = await synth.synthesize( + "critical badge", + {"serviceName": "billing", "latencyMs": 85.0}, + ) + assert badge_out.stage == SynthesisStage.FAST_1PASS_LEAF + validate_payload([catalog], badge_out.messages) + badge_dicts = to_message_dicts(badge_out.messages) + root_comp = badge_dicts[1]["updateComponents"]["components"][0] + assert root_comp["component"] == "TelemetryBadge" + assert root_comp["serviceName"] == {"@path": "/serviceName"} + assert root_comp["latencyMs"] == {"@path": "/latencyMs"} + assert root_comp["severity"] == "CRITICAL" + + ctrl_out = await synth.synthesize( + "execute control", + {"targetHost": "node-1", "replicaCount": 3}, + ) + assert ctrl_out.stage == SynthesisStage.FAST_1PASS_LEAF + validate_payload([catalog], ctrl_out.messages) + ctrl_dicts = to_message_dicts(ctrl_out.messages) + ctrl_comp = ctrl_dicts[1]["updateComponents"]["components"][0] + assert ctrl_comp["component"] == "ActionableControl" + assert ctrl_comp["onExecute"] == {"event": {"name": "onExecute"}} + assert len(ctrl_comp["checks"]) == 1 + assert ctrl_comp["checks"][0]["condition"]["@call"] == "isHostReachable" + assert "ActionableControl" in ctrl_out.to_express([catalog]) + + +@pytest.mark.asyncio +async def test_stage2b_container_child_list_and_single_child() -> None: + """Verifies Stage 2B synthesizes CHILD_LIST with relative paths and CHILD slots.""" + catalog = _make_domain_catalog("1.0") + backend = DeterministicMockBackend( + scripted={ + "root_component:stream list": { + "EventStreamList": 0.90, + "TelemetryBadge": 0.10, + }, + "root_component:alert frame": { + "AlertFrame": 0.90, + "TelemetryBadge": 0.10, + }, + "child_component": { + "TelemetryBadge": 0.90, + "ActionableControl": 0.10, + }, + } + ) + synth = DecisionSynthesizer([catalog], backend) + + list_out = await synth.synthesize( + "stream list", + { + "clusterTitle": "us-central1", + "records": [ + {"serviceName": "frontend", "latencyMs": 11.2}, + {"serviceName": "checkout", "latencyMs": 24.8}, + ], + }, + ) + assert list_out.stage == SynthesisStage.CONTAINER_2PASS + validate_payload([catalog], list_out.messages) + list_dicts = to_message_dicts(list_out.messages) + comps = list_dicts[1]["updateComponents"]["components"] + assert len(comps) == 2 + assert comps[0]["component"] == "EventStreamList" + assert comps[0]["records"] == { + "path": "/records", + "componentId": "item_1", + } + assert comps[1]["id"] == "item_1" + assert comps[1]["serviceName"] == {"@path": "serviceName"} + assert comps[1]["latencyMs"] == {"@path": "latencyMs"} + assert "EventStreamList" in list_out.to_express([catalog]) + + frame_out = await synth.synthesize( + "alert frame", + {"serviceName": "search", "latencyMs": 19.0}, + ) + assert frame_out.stage == SynthesisStage.CONTAINER_2PASS + validate_payload([catalog], frame_out.messages) + frame_comps = to_message_dicts(frame_out.messages)[1]["updateComponents"][ + "components" + ] + assert frame_comps[0]["component"] == "AlertFrame" + assert frame_comps[0]["innerWidget"] == "child_1" + assert frame_comps[1]["id"] == "child_1" + assert frame_comps[1]["serviceName"] == {"@path": "/serviceName"} + + +@pytest.mark.asyncio +async def test_high_entropy_multi_view_switcher_wrapping() -> None: + """Verifies high-entropy distributions wrap top competing views in switcher.""" + catalog = _make_domain_catalog("1.0") + + def high_entropy_scorer(query: DecisionQuery) -> DecisionDistribution: + if query.task == "root_component": + # Near-uniform over 2 viable non-switcher candidates -> high entropy. + probs = {c: 0.0 for c in query.candidates} + probs["TelemetryBadge"] = 0.52 + probs["AlertFrame"] = 0.48 + return DecisionDistribution(probabilities=probs, calibrated=True) + return DecisionDistribution( + probabilities={"TelemetryBadge": 0.9, "ActionableControl": 0.1}, + calibrated=True, + ) + + backend = DeterministicMockBackend(scorer=high_entropy_scorer) + config = SynthesisConfig( + abstain_threshold=0.40, + entropy_switch_margin=0.65, + ) + synth = DecisionSynthesizer([catalog], backend, config=config) + + out = await synth.synthesize( + "Ambiguous telemetry or alert view", + {"serviceName": "edge-proxy", "latencyMs": 31.0}, + ) + assert out.stage == SynthesisStage.CONTAINER_2PASS + assert out.component_tree_spec is not None + assert out.component_tree_spec["root_component"] == "WorkspaceDeck" + assert out.component_tree_spec["views"] == ["TelemetryBadge", "AlertFrame"] + validate_payload([catalog], out.messages) + assert "WorkspaceDeck" in out.to_express([catalog]) + + +@pytest.mark.asyncio +async def test_stage3_abstain_fallback_and_cqs_promotion() -> None: + """Verifies Stage 3 abstention and Command-Query Separation promotion.""" + catalog = _make_domain_catalog("1.0") + registry = TemplateRegistry() + + backend = DeterministicMockBackend( + scripted={ + "root_component:low confidence": { + "TelemetryBadge": 0.30, + "ActionableControl": 0.25, + "EventStreamList": 0.25, + "AlertFrame": 0.20, + }, + "root_component:high confidence": { + "TelemetryBadge": 0.92, + "ActionableControl": 0.08, + }, + "template_select": {"promoted_badge": 0.95}, + } + ) + config = SynthesisConfig( + abstain_threshold=0.45, + entropy_switch_margin=0.01, + ) + synth = DecisionSynthesizer([catalog], backend, registry=registry, config=config) + + abstain_out = await synth.synthesize( + "low confidence", + {"serviceName": "cache", "latencyMs": 5.0}, + ) + assert abstain_out.stage == SynthesisStage.ABSTAIN_FALLBACK + assert abstain_out.messages == [] + assert registry.list_templates() == () + + # Synthesize high-confidence leaf: CQS guarantees registry is still empty. + leaf_out = await synth.synthesize( + "high confidence", + {"serviceName": "cache", "latencyMs": 5.0}, + ) + assert leaf_out.stage == SynthesisStage.FAST_1PASS_LEAF + assert registry.list_templates() == () + + # Explicit command promotes synthesized output into the registry. + registry.promote_synthesized( + "promoted_badge", + "Promoted cache telemetry badge", + leaf_out, + required_pointers=["/serviceName", "/latencyMs"], + ) + assert len(registry.list_templates()) == 1 + + # Subsequent query now hits Stage 1 TEMPLATE_SELECT. + stage1_out = await synth.synthesize( + "high confidence", + {"serviceName": "cache-2", "latencyMs": 7.5}, + ) + assert stage1_out.stage == SynthesisStage.TEMPLATE_SELECT + assert stage1_out.selected_template_id == "promoted_badge" + + +@pytest.mark.asyncio +async def test_switcher_mutable_gate_and_tree_limits_and_static_primitives() -> None: + """Verifies H1 (switcher mutable gate), H4 (static primitives not bound), M1 (tree limits), and M4 (SynthesisConfig validation).""" + with pytest.raises(ValueError, match="mutable_confidence_threshold"): + SynthesisConfig( + template_confidence_threshold=0.80, + mutable_confidence_threshold=0.70, + ) + with pytest.raises(ValueError, match="max_tree_depth"): + SynthesisConfig(max_tree_depth=0) + with pytest.raises(ValueError, match="max_children_per_container"): + SynthesisConfig(max_children_per_container=0) + + schema: dict[str, Any] = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "catalogId": "https://example.com/catalogs/strict/v1/catalog.json", + "protocolVersion": "1.0", + "components": { + "StaticNoteLeaf": { + "type": "object", + "properties": { + "component": {"const": "StaticNoteLeaf"}, + "title": {"$ref": "common_types.json#/$defs/DynamicString"}, + "staticTag": {"type": "string"}, + }, + "required": ["component", "title"], + }, + "ActionView": { + "type": "object", + "properties": { + "component": {"const": "ActionView"}, + "title": {"$ref": "common_types.json#/$defs/DynamicString"}, + "onFire": {"$ref": "common_types.json#/$defs/Action"}, + }, + "required": ["component", "title", "onFire"], + }, + "DeckSwitcher": { + "type": "object", + "properties": { + "component": {"const": "DeckSwitcher"}, + "tabs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "label": {"type": "string"}, + "child": { + "$ref": "common_types.json#/$defs/ComponentId" + }, + }, + "required": ["label", "child"], + }, + }, + }, + "required": ["component", "tabs"], + }, + }, + } + cat = Catalog.from_json(schema) + + # High-entropy distribution between StaticNoteLeaf (0.52) and ActionView (0.48) + # has top_prob=0.52 < mutable_confidence_threshold=0.85 -> H1 must abstain! + def ambiguous_action_scorer(query: DecisionQuery) -> DecisionDistribution: + del query + return DecisionDistribution( + probabilities={ + "StaticNoteLeaf": 0.52, + "ActionView": 0.48, + "DeckSwitcher": 0.0, + }, + calibrated=True, + ) + + synth_h1 = DecisionSynthesizer( + [cat], + DeterministicMockBackend(scorer=ambiguous_action_scorer), + config=SynthesisConfig( + abstain_threshold=0.40, + mutable_confidence_threshold=0.85, + entropy_switch_margin=0.80, + ), + ) + abstained = await synth_h1.synthesize("ambiguous action", {"title": "hello"}) + assert abstained.stage == SynthesisStage.ABSTAIN_FALLBACK + + # StaticNoteLeaf should NOT bind plain string property 'staticTag' to a DataBinding (H4). + synth_h4 = DecisionSynthesizer( + [cat], + DeterministicMockBackend(scripted={"root_component": {"StaticNoteLeaf": 0.92}}), + ) + leaf_out = await synth_h4.synthesize( + "show note", {"title": "hello", "staticTag": "raw"} + ) + assert leaf_out.stage == SynthesisStage.FAST_1PASS_LEAF + comp_dict = to_message_dicts(leaf_out.messages)[1]["updateComponents"][ + "components" + ][0] + assert "staticTag" not in comp_dict + validate_payload([cat], leaf_out.messages) + + # M1: max_children_per_container=1 limits DeckSwitcher to 1 child view. + synth_m1 = DecisionSynthesizer( + [cat], + DeterministicMockBackend(scripted={"root_component": {"DeckSwitcher": 0.92}}), + config=SynthesisConfig(max_children_per_container=1), + ) + deck_out = await synth_m1.synthesize("show deck", {"title": "hello"}) + deck_comps = to_message_dicts(deck_out.messages)[1]["updateComponents"][ + "components" + ] + assert len(deck_comps[0]["tabs"]) == 1 + assert len(deck_comps) == 2 + + +@pytest.mark.asyncio +async def test_any_slot_ranking_and_check_arg_binding_and_camelcase_checks() -> None: + """Verifies token-overlap ranking for 'any' slots, check arg pointer selection, camelCase check messages, and per-call config overrides.""" + schema: dict[str, Any] = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "catalogId": "https://example.com/catalogs/review_fixes/v1/catalog.json", + "protocolVersion": "1.0", + "components": { + "OrderInspector": { + "type": "object", + "allOf": [{"$ref": "common_types.json#/$defs/Checkable"}], + "properties": { + "component": {"const": "OrderInspector"}, + "title": {"$ref": "common_types.json#/$defs/DynamicString"}, + "summaryPayload": {"$ref": "common_types.json#/$defs/DynamicValue"}, + }, + "required": ["component", "title"], + }, + }, + "functions": { + "isValidTickerSymbol": { + "type": "object", + "properties": { + "call": {"const": "isValidTickerSymbol"}, + "args": { + "type": "object", + "properties": { + "tickerSymbol": { + "description": "Unconstrained parameter schema." + }, + }, + "required": ["tickerSymbol"], + }, + "returnType": {"const": "boolean"}, + }, + "required": ["call", "args", "returnType"], + }, + }, + } + cat = Catalog.from_json(schema) + synth = DecisionSynthesizer( + [cat], + DeterministicMockBackend(scripted={"root_component": {"OrderInspector": 0.60}}), + config=SynthesisConfig(abstain_threshold=0.70), + ) + payload = { + "unrelatedObject": {}, + "title": "Order View", + "summaryPayload": {}, + "tickerSymbol": "GOOG", + } + + # Default config has abstain_threshold=0.70, so 0.60 abstains. + abstained = await synth.synthesize("inspect order", payload) + assert abstained.stage == SynthesisStage.ABSTAIN_FALLBACK + + # Per-call config override allows 0.60 without mutating synth.config. + override_cfg = SynthesisConfig(abstain_threshold=0.50) + out = await synth.synthesize("inspect order", payload, config=override_cfg) + assert synth.config.abstain_threshold == pytest.approx(0.70) + assert out.stage == SynthesisStage.FAST_1PASS_LEAF + + comp = to_message_dicts(out.messages)[1]["updateComponents"]["components"][0] + # Optional DynamicValue ('any') slot selects /summaryPayload over /unrelatedObject. + assert comp["summaryPayload"] == {"@path": "/summaryPayload"} + # Check function argument 'tickerSymbol' binds to /tickerSymbol instead of first pointer, + # and camelCase function name 'isValidTickerSymbol' is preserved in message. + assert comp["checks"] == [{ + "condition": { + "@call": "isValidTickerSymbol", + "args": {"tickerSymbol": {"@path": "/tickerSymbol"}}, + }, + "message": "IsValidTickerSymbol check failed", + }] + validate_payload([cat], out.messages) + + +@pytest.mark.asyncio +async def test_named_child_array_queries_backend_and_filters_incompatible_leaves() -> ( + None +): + """Verifies NAMED_CHILD_ARRAY queries backend per view and filters array-only/static leaves.""" + schema: dict[str, Any] = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "catalogId": "https://example.com/catalogs/tabs_filter/v1/catalog.json", + "protocolVersion": "1.0", + "components": { + "StaticIcon": { + "type": "object", + "properties": { + "component": {"const": "StaticIcon"}, + "glyph": {"type": "string", "enum": ["star", "check"]}, + }, + "required": ["component", "glyph"], + }, + "ArrayPicker": { + "type": "object", + "properties": { + "component": {"const": "ArrayPicker"}, + "selected": {"$ref": "common_types.json#/$defs/DynamicStringList"}, + }, + "required": ["component", "selected"], + }, + "ScalarText": { + "type": "object", + "properties": { + "component": {"const": "ScalarText"}, + "text": {"$ref": "common_types.json#/$defs/DynamicString"}, + }, + "required": ["component", "text"], + }, + "ScalarMetric": { + "type": "object", + "properties": { + "component": {"const": "ScalarMetric"}, + "label": {"$ref": "common_types.json#/$defs/DynamicString"}, + }, + "required": ["component", "label"], + }, + "TabContainer": { + "type": "object", + "properties": { + "component": {"const": "TabContainer"}, + "tabs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "title": {"type": "string"}, + "child": { + "$ref": "common_types.json#/$defs/ComponentId" + }, + }, + "required": ["title", "child"], + }, + }, + }, + "required": ["component", "tabs"], + }, + }, + } + cat = Catalog.from_json(schema) + seen_candidates: list[tuple[str, ...]] = [] + + def scorer(query: DecisionQuery) -> DecisionDistribution: + if query.task == "root_component": + return DecisionDistribution( + probabilities={"TabContainer": 0.90, "ScalarText": 0.10}, + calibrated=True, + ) + seen_candidates.append(query.candidates) + slot = query.context.get("slot", "") + if slot == "tabs[0]": + return DecisionDistribution( + probabilities={"ScalarText": 0.85, "ScalarMetric": 0.15}, + calibrated=True, + ) + return DecisionDistribution( + probabilities={"ScalarMetric": 0.85, "ScalarText": 0.15}, + calibrated=True, + ) + + synth = DecisionSynthesizer([cat], DeterministicMockBackend(scorer=scorer)) + out = await synth.synthesize( + "Show tabs for summary and logs", + {"overview_summary": "All systems operational", "recent_logs": "OK"}, + ) + assert out.stage == SynthesisStage.CONTAINER_2PASS + # StaticIcon (no DATA_VALUE slot) and ArrayPicker (requires array pointer) are filtered out. + for cand_tuple in seen_candidates: + assert "StaticIcon" not in cand_tuple + assert "ArrayPicker" not in cand_tuple + assert set(cand_tuple) == {"ScalarText", "ScalarMetric"} + + comps = to_message_dicts(out.messages)[1]["updateComponents"]["components"] + assert comps[0]["tabs"] == [ + {"title": "Overview Summary", "child": "view_1"}, + {"title": "Recent Logs", "child": "view_2"}, + ] + assert comps[1]["component"] == "ScalarText" + assert comps[1]["text"] == {"@path": "/overview_summary"} + assert comps[2]["component"] == "ScalarMetric" + assert comps[2]["label"] == {"@path": "/recent_logs"} + validate_payload([cat], out.messages) + + +@pytest.mark.asyncio +async def test_decision_query_context_enrichment() -> None: + """Verifies that DecisionQuery.context includes candidate and slot descriptions.""" + cat = _make_domain_catalog("1.0") + reg = TemplateRegistry() + reg.register( + SurfaceTemplate( + template_id="ops_badge_tpl", + description="Ops telemetry badge summary", + surface_id="s1", + catalog_id=cat.catalog_id, + protocol_version="v1.0", + components=( + { + "id": "root", + "component": "TelemetryBadge", + "serviceName": {"@path": "/serviceName"}, + "latencyMs": {"@path": "/latencyMs"}, + }, + ), + required_pointers=("/serviceName", "/latencyMs"), + ) + ) + + captured_queries: list[DecisionQuery] = [] + + def capturing_scorer(q: DecisionQuery) -> DecisionDistribution: + captured_queries.append(q) + if q.task == "template_select": + return DecisionDistribution(probabilities={q.candidates[0]: 0.10}) + if q.task == "root_component": + return DecisionDistribution(probabilities={"AlertFrame": 0.90}) + return DecisionDistribution(probabilities={q.candidates[0]: 0.90}) + + synth = DecisionSynthesizer( + [cat], DeterministicMockBackend(scorer=capturing_scorer), registry=reg + ) + await synth.synthesize( + "Display ops latency badge", + {"serviceName": "auth", "latencyMs": 15}, + ) + + by_task = {q.task: q for q in captured_queries} + assert "template_select" in by_task + assert "candidate_descriptions" in by_task["template_select"].context + assert ( + by_task["template_select"].context["candidate_descriptions"]["ops_badge_tpl"] + == "Ops telemetry badge summary" + ) + + assert "root_component" in by_task + assert "candidate_descriptions" in by_task["root_component"].context + assert ( + "TelemetryBadge" in by_task["root_component"].context["candidate_descriptions"] + ) + telemetry_desc = by_task["root_component"].context["candidate_descriptions"][ + "TelemetryBadge" + ] + assert "Read-only telemetry badge" in telemetry_desc + assert "serviceName" in telemetry_desc + + assert "child_component" in by_task + child_q = by_task["child_component"] + assert "candidate_descriptions" in child_q.context + assert "parent_description" in child_q.context + assert "slot_description" in child_q.context + + +@pytest.mark.asyncio +async def test_stage2b_action_filtering_and_all_action_leaf_catalog_abstention() -> ( + None +): + """Verifies M10 (Stage 2B child action filtering below mutable_confidence_threshold), H2 (no action fallback when all leaves have actions), M5 (template/fallback_fn validation), and M6 (container-only catalog abstention).""" + from a2ui.core import A2uiValidationError + + cat = _make_domain_catalog("1.0") + low_mut_backend = DeterministicMockBackend( + scripted={ + "root_component": {"AlertFrame": 0.70, "TelemetryBadge": 0.30}, + "child_component": {"ActionableControl": 0.95, "TelemetryBadge": 0.05}, + } + ) + low_mut_synth = DecisionSynthesizer( + [cat], + low_mut_backend, + config=SynthesisConfig( + abstain_threshold=0.50, + template_confidence_threshold=0.60, + mutable_confidence_threshold=0.85, + entropy_switch_margin=0.01, + ), + ) + low_mut_out = await low_mut_synth.synthesize( + "Show alert frame", + {"serviceName": "billing-api", "latencyMs": 42.5}, + ) + assert low_mut_out.stage == SynthesisStage.CONTAINER_2PASS + assert low_mut_out.component_tree_spec is not None + child_names = [ + c["component"] for c in low_mut_out.component_tree_spec["components"] + ] + assert "ActionableControl" not in child_names + + # H2: When all leaves in a catalog have required action slots and confidence + # is below mutable_confidence_threshold, Stage 2B abstains and fallback_card + # returns [] rather than emitting an action-bearing leaf. + action_only_cat = Catalog.from_json({ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "catalogId": "https://example.com/catalogs/action_only/v1", + "protocolVersion": "1.0", + "components": { + "TradePanel": { + "type": "object", + "properties": { + "component": {"const": "TradePanel"}, + "child": {"$ref": "common_types.json#/$defs/ComponentId"}, + }, + "required": ["component", "child"], + }, + "TradeTicket": { + "type": "object", + "properties": { + "component": {"const": "TradeTicket"}, + "symbol": {"$ref": "common_types.json#/$defs/DynamicString"}, + "onSubmit": {"$ref": "common_types.json#/$defs/Action"}, + }, + "required": ["component", "symbol", "onSubmit"], + }, + }, + }) + action_only_synth = DecisionSynthesizer( + [action_only_cat], + DeterministicMockBackend(scripted={"root_component": {"TradePanel": 0.60}}), + config=SynthesisConfig( + abstain_threshold=0.50, + template_confidence_threshold=0.55, + mutable_confidence_threshold=0.85, + entropy_switch_margin=0.01, + ), + fallback_card=True, + ) + action_only_out = await action_only_synth.synthesize( + "Show trade panel", {"symbol": "GOOG"} + ) + assert action_only_out.stage == SynthesisStage.ABSTAIN_FALLBACK + assert action_only_out.messages == [] + + # M6: Container-only catalog abstains cleanly without raising A2uiValidationError. + container_only_cat = Catalog.from_json({ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "catalogId": "https://example.com/catalogs/container_only/v1", + "protocolVersion": "1.0", + "components": { + "OuterBox": { + "type": "object", + "properties": { + "component": {"const": "OuterBox"}, + "childId": {"$ref": "common_types.json#/$defs/ComponentId"}, + }, + "required": ["component", "childId"], + }, + }, + }) + container_only_synth = DecisionSynthesizer( + [container_only_cat], + DeterministicMockBackend(scripted={"root_component": {"OuterBox": 0.90}}), + fallback_card=True, + ) + container_only_out = await container_only_synth.synthesize( + "Show outer box", {"title": "x"} + ) + assert container_only_out.stage == SynthesisStage.ABSTAIN_FALLBACK + assert container_only_out.messages == [] + + # M5: Template rendering and fallback_fn validate against active catalogs. + bad_reg = TemplateRegistry() + bad_reg.register( + SurfaceTemplate( + template_id="bad_comp_tpl", + description="Template with component not in catalog", + surface_id="s1", + catalog_id=cat.catalog_id, + protocol_version="v1.0", + components=({"id": "root", "component": "NonExistentWidget"},), + ) + ) + bad_tpl_synth = DecisionSynthesizer( + [cat], + DeterministicMockBackend(scripted={"template_select": {"bad_comp_tpl": 0.95}}), + registry=bad_reg, + ) + with pytest.raises(A2uiValidationError): + await bad_tpl_synth.synthesize("Show widget", {"serviceName": "a"}) + with pytest.raises(A2uiValidationError): + await bad_tpl_synth.synthesize( + "Show widget", {"serviceName": "a"}, template_id="bad_comp_tpl" + ) + + +@pytest.mark.asyncio +async def test_basic_catalog_default_config_attempts_archetype_path_and_flat_opt_out() -> ( + None +): + """Verifies BasicCatalog attempts the archetype path by default and flat path when use_archetypes=False.""" + from a2ui.core.basic_catalog import BasicCatalog + from .layout_fixtures import RESORT, ScriptedAnswers + + basic = BasicCatalog("v1.0") + sa = ScriptedAnswers( + answers={ + "family": ("inspect", 0.80), + "stakes": 0.2, + "urgency": 0.1, + "archetype:inspect": ("detail", 0.85), + "gate:picture": 0.90, + "gate:banner": 0.10, + "gate:headline": 0.80, + "gate:prose": 0.90, + "gate:facts": 0.40, + "gate:collection": 0.85, + "gate:actions": 0.30, + "anatomy:picture.framing": ("banner", 0.80), + "anatomy:picture.prominence": 2.2, + "anatomy:collection.layout": ("reel", 0.70), + "anatomy:collection.leading": ("thumbnail", 0.80), + "anatomy:collection.trailing": ("none", 0.80), + "salience:/rating": 2.4, + "salience:/priceFrom": 2.6, + } + ) + synth = DecisionSynthesizer([basic], sa.backend()) + out = await synth.synthesize(RESORT.intent, RESORT.payload) + assert out.stage == SynthesisStage.ARCHETYPE + assert out.trace + assert out.trace[0].question.id == "family" + validate_payload([basic], out.messages) + + flat_synth = DecisionSynthesizer( + [basic], + DeterministicMockBackend(scripted={"root_component": {"Text": 0.90}}), + config=SynthesisConfig(use_archetypes=False), + ) + flat_out = await flat_synth.synthesize("Show title", {"title": "Coral Bay Resort"}) + assert flat_out.stage == SynthesisStage.FAST_1PASS_LEAF + assert flat_out.layout_plan is None + + +@pytest.mark.asyncio +async def test_input_family_promotes_mutable_pointers_and_scalar_child_list_is_static() -> ( + None +): + """Verifies automatic mutable promotion when family chooses 'input' and static [item_id] for scalar CHILD_LIST.""" + from a2ui.core.basic_catalog import BasicCatalog + from .layout_fixtures import ScriptedAnswers + + basic = BasicCatalog("v0.9") + sa = ScriptedAnswers( + answers={ + "family": ("input", 0.92), + "stakes": 1.0, + "urgency": 0.3, + "archetype:input": ("form", 0.88), + "gate:prose": 0.10, + "gate:form": 0.98, + "gate:actions": 0.95, + "instance:form.control:/email": ("shortText", 0.95), + "instance:form.required:/email": 0.99, + "instance:form.control:/password": ("obscured", 0.99), + "instance:form.required:/password": 0.99, + "instance:form.control:/rememberMe": ("toggle", 0.99), + "instance:form.required:/rememberMe": 0.05, + "instance:actions.primary:/actions": ("Sign In", 0.98), + "instance:actions.destructive:0": 0.01, + } + ) + synth = DecisionSynthesizer([basic], sa.backend()) + login_out = await synth.synthesize( + "Make me a login form", + { + "title": "Welcome Back", + "email": "alex.smith@example.com", + "password": "", + "rememberMe": False, + "actions": ["Sign In"], + }, + ) + assert login_out.stage == SynthesisStage.ARCHETYPE + assert login_out.layout_plan is not None + assert login_out.layout_plan.archetype == "form" + assert len(login_out.decision_answers) > 0 + assert login_out.decision_answers[0].question_id == "family" + validate_payload([basic], login_out.messages) + + # Scalar-only payload with a CHILD_LIST container (Column) emits static [item_id], + # not a template object referencing a non-existent '/children' array path. + col_synth = DecisionSynthesizer( + [basic], + DeterministicMockBackend( + scripted={ + "root_component": {"Column": 0.90}, + "child_component": {"Text": 0.90}, + } + ), + config=SynthesisConfig(use_archetypes=False), + ) + col_out = await col_synth.synthesize("Show welcome", {"title": "Welcome Back"}) + assert col_out.stage == SynthesisStage.CONTAINER_2PASS + validate_payload([basic], col_out.messages) + col_comps = to_message_dicts(col_out.messages)[1]["updateComponents"]["components"] + assert col_comps[0]["component"] == "Column" + assert col_comps[0]["children"] == ["item_1"] + assert col_comps[1]["text"] == {"path": "/title"} + + +@pytest.mark.asyncio +async def test_parser_read_blocks_and_synthesize_blocks() -> None: + import json + from a2ui.core.basic_catalog import BasicCatalog + from a2ui.inference_formats.decision import DecisionBlock, DecisionParser + from tests.decision.layout_fixtures import ScriptedAnswers + + basic = BasicCatalog("v1.0") + sa = ScriptedAnswers( + answers={ + "family": ("input", 0.92), + "stakes": 1.0, + "urgency": 0.3, + "archetype:input": ("form", 0.88), + "gate:prose": 0.10, + "gate:form": 0.98, + "gate:actions": 0.95, + "instance:form.control:/email": ("shortText", 0.95), + "instance:form.required:/email": 0.99, + "instance:actions.primary:/actions": ("Submit", 0.98), + } + ) + synth = DecisionSynthesizer([basic], sa.backend()) + parser = DecisionParser(synthesizer=synth) + + content = json.dumps({ + "intent": "Enter email", + "payload": {"email": "user@example.com", "actions": ["Submit"]}, + "title": "Email Signup", + "summary": "Join our newsletter", + }) + blocks = parser.read_blocks(content) + assert len(blocks) == 1 + assert isinstance(blocks[0], DecisionBlock) + assert blocks[0].intent == "Enter email" + assert blocks[0].title == "Email Signup" + assert blocks[0].summary == "Join our newsletter" + + outputs = await parser.synthesize_blocks(content) + assert len(outputs) == 1 + assert outputs[0].stage == SynthesisStage.ARCHETYPE + assert len(outputs[0].decision_answers) > 0 + assert len(outputs[0].messages) > 0 diff --git a/python/a2ui_agent/tests/decision/test_template_registry.py b/python/a2ui_agent/tests/decision/test_template_registry.py new file mode 100644 index 0000000000..4544c770c9 --- /dev/null +++ b/python/a2ui_agent/tests/decision/test_template_registry.py @@ -0,0 +1,364 @@ +# 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. + +"""Unit tests for SurfaceTemplate and TemplateRegistry.""" + +from __future__ import annotations + +import pytest + +from a2ui.core import A2uiValidationError +from a2ui.inference_formats.decision import ( + SurfaceTemplate, + SynthesisOutput, + SynthesisStage, + TemplateRegistry, +) +from a2ui.parser.messages import to_message_dicts, to_message_models + + +def _make_v09_template( + template_id: str = "metric_card_v09", + *, + required_pointers: tuple[str, ...] = ("/cpu",), + is_mutable: bool = False, + protocol_version: str = "v0.9", +) -> SurfaceTemplate: + return SurfaceTemplate( + template_id=template_id, + description="Displays CPU metric card", + surface_id="metrics_surface", + catalog_id="https://example.com/catalogs/devops/v1", + protocol_version=protocol_version, + components=( + { + "id": "root", + "component": "MetricGauge", + "label": "CPU Usage", + "value": {"path": "/cpu"}, + }, + ), + required_pointers=required_pointers, + is_mutable=is_mutable, + ) + + +def _make_v10_template( + template_id: str = "metric_card_v10", + *, + catalog_id: str | None = "https://example.com/catalogs/devops/v1", + required_pointers: tuple[str, ...] = ("/cpu",), +) -> SurfaceTemplate: + return SurfaceTemplate( + template_id=template_id, + description="Displays CPU metric card in v1.0", + surface_id="metrics_v10_surface", + catalog_id=catalog_id, + protocol_version="v1.0", + components=( + { + "id": "root", + "component": "MetricGauge", + "label": "CPU Usage", + "value": {"@path": "/cpu"}, + }, + ), + required_pointers=required_pointers, + ) + + +class TestSurfaceTemplate: + """Tests for SurfaceTemplate matching and message rendering.""" + + def test_matches_payload_checks_all_required_pointers(self) -> None: + template = _make_v09_template(required_pointers=("/cpu", "/memory")) + assert template.matches_payload(["/cpu", "/memory", "/disk"]) is True + assert template.matches_payload(["/cpu"]) is False + assert template.matches_payload([]) is False + + def test_matches_payload_with_empty_requirements_always_matches(self) -> None: + template = _make_v09_template(required_pointers=()) + assert template.matches_payload([]) is True + assert template.matches_payload(["/any"]) is True + + def test_render_messages_v09_with_and_without_payload(self) -> None: + template = _make_v09_template(protocol_version="v0.9") + + empty_msgs = template.render_messages({}) + assert len(empty_msgs) == 2 + empty_dicts = to_message_dicts(empty_msgs) + assert empty_dicts[0] == { + "version": "v0.9", + "createSurface": { + "surfaceId": "metrics_surface", + "catalogId": "https://example.com/catalogs/devops/v1", + }, + } + assert empty_dicts[1] == { + "version": "v0.9", + "updateComponents": { + "surfaceId": "metrics_surface", + "components": [{ + "id": "root", + "component": "MetricGauge", + "label": "CPU Usage", + "value": {"path": "/cpu"}, + }], + }, + } + + populated_msgs = template.render_messages( + {"cpu": 72.5}, surface_id="custom_surface" + ) + assert len(populated_msgs) == 3 + populated_dicts = to_message_dicts(populated_msgs) + assert populated_dicts[0]["createSurface"]["surfaceId"] == "custom_surface" + assert populated_dicts[1]["updateComponents"]["surfaceId"] == "custom_surface" + assert populated_dicts[2] == { + "version": "v0.9", + "updateDataModel": { + "surfaceId": "custom_surface", + "path": "/", + "value": {"cpu": 72.5}, + }, + } + + def test_render_messages_normalizes_v091_wire_version_to_v09(self) -> None: + template = _make_v09_template(protocol_version="v0.9.1") + msgs = template.render_messages({"cpu": 40}) + msg_dicts = to_message_dicts(msgs) + assert [m["version"] for m in msg_dicts] == ["v0.9", "v0.9", "v0.9"] + + bare_v10 = SurfaceTemplate( + template_id="bare_v10", + description="Bare 1.0 protocol version", + surface_id="s_v10", + catalog_id=None, + protocol_version="1.0", + components=({"id": "root", "component": "MetricGauge"},), + ) + assert bare_v10.root_component() == "MetricGauge" + v10_dicts = to_message_dicts(bare_v10.render_messages({})) + assert [m["version"] for m in v10_dicts] == ["v1.0", "v1.0"] + + def test_render_messages_v10_with_and_without_catalog_id(self) -> None: + template_with_cat = _make_v10_template( + catalog_id="https://example.com/catalogs/devops/v1" + ) + msgs = template_with_cat.render_messages({"cpu": 88}) + msg_dicts = to_message_dicts(msgs) + assert len(msg_dicts) == 3 + assert msg_dicts[0] == { + "version": "v1.0", + "createSurface": { + "surfaceId": "metrics_v10_surface", + "catalogId": "https://example.com/catalogs/devops/v1", + }, + } + assert msg_dicts[1]["version"] == "v1.0" + assert msg_dicts[2]["version"] == "v1.0" + + template_no_cat = _make_v10_template(catalog_id=None) + no_cat_dicts = to_message_dicts(template_no_cat.render_messages({})) + assert no_cat_dicts[0] == { + "version": "v1.0", + "createSurface": {"surfaceId": "metrics_v10_surface"}, + } + + def test_render_messages_deep_copies_components(self) -> None: + template = _make_v09_template() + msgs = template.render_messages({}) + msg_dicts = to_message_dicts(msgs) + msg_dicts[1]["updateComponents"]["components"][0]["label"] = "Mutated" + assert template.components[0]["label"] == "CPU Usage" + + +class TestTemplateRegistry: + """Tests for TemplateRegistry registration, lookup, and CQS promotion.""" + + def test_register_get_list_and_matching_templates(self) -> None: + registry = TemplateRegistry() + t1 = _make_v09_template("t1", required_pointers=("/cpu",)) + t2 = _make_v09_template("t2", required_pointers=("/cpu", "/mem")) + + registry.register(t1) + registry.register(t2) + + assert registry.get("t1") == t1 + assert registry.get("t2") == t2 + assert registry.get("unknown") is None + assert registry.list_templates() == (t1, t2) + + assert registry.matching_templates(["/cpu"]) == (t1,) + assert registry.matching_templates(["/cpu", "/mem"]) == (t1, t2) + assert registry.matching_templates(["/disk"]) == () + + @pytest.mark.parametrize( + "bad_components", + [ + (), + ({"id": "root"},), + ({"component": "MetricGauge"},), + ({"id": "", "component": "MetricGauge"},), + ({"id": "root", "component": " "},), + ], + ) + def test_register_fails_fast_on_malformed_components( + self, bad_components: tuple[dict[str, object], ...] + ) -> None: + registry = TemplateRegistry() + bad_template = SurfaceTemplate( + template_id="bad_template", + description="Malformed component template", + surface_id="s1", + catalog_id="https://example.com/catalog", + protocol_version="v0.9", + components=bad_components, + ) + with pytest.raises((A2uiValidationError, ValueError)): + registry.register(bad_template) + assert registry.get("bad_template") is None + + def test_register_fails_fast_on_invalid_envelope_schema(self) -> None: + registry = TemplateRegistry() + # In v0.9, CreateSurface requires a non-null catalogId. + missing_catalog_v09 = SurfaceTemplate( + template_id="bad_v09", + description="Missing catalogId in v0.9", + surface_id="s1", + catalog_id=None, + protocol_version="v0.9", + components=({"id": "root", "component": "MetricGauge"},), + ) + with pytest.raises((A2uiValidationError, ValueError)): + registry.register(missing_catalog_v09) + + def test_promote_synthesized_registers_reusable_template(self) -> None: + registry = TemplateRegistry() + raw_messages = to_message_models([ + { + "version": "v1.0", + "createSurface": { + "surfaceId": "synth_surface", + "catalogId": "https://example.com/catalogs/finance/v1", + }, + }, + { + "version": "v1.0", + "updateComponents": { + "surfaceId": "synth_surface", + "components": [{ + "id": "root", + "component": "TickerCard", + "symbol": {"@path": "/ticker"}, + }], + }, + }, + { + "version": "v1.0", + "updateDataModel": { + "surfaceId": "synth_surface", + "path": "/", + "value": {"ticker": "GOOG"}, + }, + }, + ]) + output = SynthesisOutput( + stage=SynthesisStage.FAST_1PASS_LEAF, + messages=raw_messages, + confidence=0.92, + entropy=0.12, + component_tree_spec={"root_component": "TickerCard"}, + ) + + promoted = registry.promote_synthesized( + "ticker_template", + "Promoted ticker card", + output, + required_pointers=["/ticker"], + is_mutable=True, + ) + + assert promoted.template_id == "ticker_template" + assert promoted.surface_id == "synth_surface" + assert promoted.catalog_id == "https://example.com/catalogs/finance/v1" + assert promoted.protocol_version == "v1.0" + assert promoted.required_pointers == ("/ticker",) + assert promoted.is_mutable is True + assert registry.get("ticker_template") == promoted + + rendered = promoted.render_messages({"ticker": "Alphabet"}, surface_id="s2") + rendered_dicts = to_message_dicts(rendered) + assert rendered_dicts[0]["createSurface"]["surfaceId"] == "s2" + assert rendered_dicts[2]["updateDataModel"]["value"] == {"ticker": "Alphabet"} + + def test_promote_synthesized_raises_when_missing_update_components( + self, + ) -> None: + registry = TemplateRegistry() + abstain_output = SynthesisOutput( + stage=SynthesisStage.ABSTAIN_FALLBACK, + messages=[], + confidence=0.20, + entropy=0.95, + ) + with pytest.raises(ValueError, match="updateComponents"): + registry.promote_synthesized( + "invalid_promotion", "Should fail", abstain_output + ) + + def test_promote_synthesized_normalizes_v08_surface_update_to_v09( + self, + ) -> None: + registry = TemplateRegistry() + v08_messages = to_message_models([ + { + "beginRendering": { + "surfaceId": "v08_surface", + "catalogId": "https://example.com/catalogs/ops/v1", + "root": "root", + }, + }, + { + "surfaceUpdate": { + "surfaceId": "v08_surface", + "components": [{ + "id": "root", + "component": {"MetricGauge": {"value": {"path": "/cpu"}}}, + }], + }, + }, + ]) + output = SynthesisOutput( + stage=SynthesisStage.FAST_1PASS_LEAF, + messages=v08_messages, + confidence=0.90, + entropy=0.10, + ) + promoted = registry.promote_synthesized( + "from_v08", "Promoted from v0.8", output, required_pointers=["/cpu"] + ) + rendered = promoted.render_messages({"cpu": 55.0}) + rendered_dicts = to_message_dicts(rendered) + assert [m["version"] for m in rendered_dicts] == ["v0.9", "v0.9", "v0.9"] + assert rendered_dicts[0]["createSurface"]["surfaceId"] == "v08_surface" + assert ( + rendered_dicts[1]["updateComponents"]["components"][0]["component"] + == "MetricGauge" + ) + + # Also verify explicit protocol_version="v0.8" on SurfaceTemplate normalizes to v0.9. + explicit_v08 = _make_v09_template("explicit_v08", protocol_version="v0.8") + v08_dicts = to_message_dicts(explicit_v08.render_messages({"cpu": 10})) + assert [m["version"] for m in v08_dicts] == ["v0.9", "v0.9", "v0.9"] diff --git a/python/a2ui_agent/tests/decision/test_variety_and_copy.py b/python/a2ui_agent/tests/decision/test_variety_and_copy.py new file mode 100644 index 0000000000..dd2f503895 --- /dev/null +++ b/python/a2ui_agent/tests/decision/test_variety_and_copy.py @@ -0,0 +1,290 @@ +# 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 variety mode sampling, authored copy placement, and remix.""" + +from __future__ import annotations + +from typing import Any + +from a2ui.core.basic_catalog import BasicCatalog +from a2ui.inference_formats.decision import ( + DecisionSynthesizer, + SynthesisConfig, + SynthesisStage, + VarietyMode, +) +import pytest + +from .layout_fixtures import HOST, RESORT, ScriptedAnswers + +HOST_SCRIPTED = { + "family": ("monitor", 0.90), + "stakes": 1.0, + "urgency": 1.4, + "archetype:monitor": ("dashboard", 0.85), + "gate:banner": 0.80, + "gate:headline": 0.90, + "gate:facts": 0.80, + "anatomy:headline.deltas": 0.85, + "salience:/cpu": 2.8, + "salience:/status": 2.1, + "salience:/uptimeHours": 1.2, + "salience:/host": 0.4, + "instance:banner.tone:/status": ("warning", 0.90), + "instance:headline.news:/cpu": ("bad", 0.85), + "instance:headline.state_tone:/status": ("warning", 0.80), +} + +HOST_DETAIL_SCRIPTED = { + "family": ("inspect", 0.90), + "stakes": 1.0, + "urgency": 1.4, + "archetype:inspect": ("detail", 0.85), + "gate:picture": 0.10, + "gate:banner": 0.80, + "gate:headline": 0.90, + "gate:prose": 0.85, + "gate:facts": 0.80, + "gate:media": 0.10, + "gate:collection": 0.10, + "gate:actions": 0.10, + "anatomy:headline.deltas": 0.85, + "salience:/cpu": 2.8, + "salience:/status": 2.1, + "salience:/uptimeHours": 1.2, + "salience:/host": 0.4, + "instance:banner.tone:/status": ("warning", 0.90), + "instance:headline.news:/cpu": ("bad", 0.85), + "instance:headline.state_tone:/status": ("warning", 0.80), +} + +RESORT_SCRIPTED = { + "family": ("inspect", 0.80), + "stakes": 0.2, + "urgency": 0.1, + "archetype:inspect": ("detail", 0.85), + "gate:picture": 0.90, + "gate:banner": 0.10, + "gate:headline": 0.80, + "gate:prose": 0.90, + "gate:facts": 0.40, + "gate:collection": 0.85, + "gate:actions": 0.30, + "anatomy:picture.framing": ("banner", 0.80), + "anatomy:picture.prominence": 2.2, + "anatomy:collection.layout": ("reel", 0.70), + "anatomy:collection.leading": ("thumbnail", 0.80), + "anatomy:collection.trailing": ("none", 0.80), + "salience:/rating": 2.4, + "salience:/priceFrom": 2.6, +} + + +def _extract_components(messages: Any) -> list[dict[str, Any]]: + """Returns the `updateComponents.components` list from `messages`.""" + comps: list[dict[str, Any]] = [] + for msg in messages: + d = msg if isinstance(msg, dict) else msg.model_dump(by_alias=True) + if "updateComponents" in d: + comps.extend(d["updateComponents"].get("components", [])) + return comps + + +@pytest.mark.asyncio +async def test_authored_title_replaces_intent_in_page_title() -> None: + catalog = BasicCatalog("v1.0") + sa = ScriptedAnswers(answers=HOST_SCRIPTED) + synth = DecisionSynthesizer([catalog], sa.backend()) + + # Without authored title, the title falls back to intent (or title pointer if any) + out_default = await synth.synthesize(HOST.intent, HOST.payload) + assert out_default.stage == SynthesisStage.ARCHETYPE + assert out_default.layout_plan is not None + + # With authored title + custom_title = "Production Cluster Health" + out_custom = await synth.synthesize(HOST.intent, HOST.payload, title=custom_title) + assert out_custom.stage == SynthesisStage.ARCHETYPE + assert out_custom.layout_plan is not None + assert out_custom.layout_plan.page.title.literal == custom_title + + comps = _extract_components(out_custom.messages) + # Confirm title appears in page header component (with markdown heading prefix) + assert any( + c.get("component") in {"Text", "Heading", "Title"} + and custom_title in str(c.get("text", "")) + for c in comps + ) + + +@pytest.mark.asyncio +async def test_authored_summary_yields_prose_block_on_host_payload() -> None: + catalog = BasicCatalog("v1.0") + sa = ScriptedAnswers(answers=HOST_DETAIL_SCRIPTED) + synth = DecisionSynthesizer([catalog], sa.backend()) + + summary_text = "Host is running with normal CPU utilization." + out = await synth.synthesize( + "Inspect host details", HOST.payload, summary=summary_text + ) + assert out.stage == SynthesisStage.ARCHETYPE + assert out.layout_plan is not None + assert "prose" in out.layout_plan.block_ids() + block_map = {b.block_id: b for b in out.layout_plan.blocks} + prose_block = block_map["prose"] + assert prose_block.bindings.get("body") is not None + assert prose_block.bindings.get("body").literal == summary_text + + # When payload has an 'about' field with text, the summary is ignored in favor of the pointer + payload_with_about = dict(HOST.payload) + payload_with_about["about"] = "Pre-existing telemetry description." + answers_about = dict(HOST_DETAIL_SCRIPTED) + answers_about["gate:banner"] = 0.10 + sa_about = ScriptedAnswers(answers=answers_about) + synth_about = DecisionSynthesizer([catalog], sa_about.backend()) + out_about = await synth_about.synthesize( + "Inspect host details", payload_with_about, summary=summary_text + ) + assert out_about.stage == SynthesisStage.ARCHETYPE + assert out_about.layout_plan is not None + assert "prose" in out_about.layout_plan.block_ids() + about_block_map = {b.block_id: b for b in out_about.layout_plan.blocks} + prose_about = about_block_map["prose"] + # Bound to pointer /about + assert prose_about.bindings.get("body") is not None + assert prose_about.bindings.get("body").pointer == "/about" + assert prose_about.bindings.get("body").literal is None + + +@pytest.mark.asyncio +async def test_variety_sampling_near_top_seeds_and_deterministic_invariants() -> None: + catalog = BasicCatalog("v1.0") + # Set up near-top probabilities for collection.layout: + # "cards": 0.46, "reel": 0.44 (within variety_margin=0.15 of top), "rows": 0.10 (outside margin) + dist_answers = dict(RESORT_SCRIPTED) + dist_answers["anatomy:collection.layout"] = { + "cards": 0.46, + "reel": 0.44, + "rows": 0.10, + } + + config = SynthesisConfig(variety=VarietyMode.NEAR_TOP, variety_margin=0.15) + + # Seed 1 + backend1 = ScriptedAnswers(answers=dist_answers).backend() + synth1 = DecisionSynthesizer([catalog], backend1, config=config) + out1 = await synth1.synthesize(RESORT.intent, RESORT.payload, variety_seed=42) + + # Re-run with the same seed 1 reproduces identical plan + backend1_repeat = ScriptedAnswers(answers=dist_answers).backend() + synth1_repeat = DecisionSynthesizer([catalog], backend1_repeat, config=config) + out1_repeat = await synth1_repeat.synthesize( + RESORT.intent, RESORT.payload, variety_seed=42 + ) + assert out1.layout_plan is not None + assert out1_repeat.layout_plan is not None + assert out1.layout_plan.archetype == out1_repeat.layout_plan.archetype + assert out1.layout_plan.family == out1_repeat.layout_plan.family + map1 = {b.block_id: b for b in out1.layout_plan.blocks} + map1_repeat = {b.block_id: b for b in out1_repeat.layout_plan.blocks} + assert ( + map1["collection"].variant_knobs["layout"] + == map1_repeat["collection"].variant_knobs["layout"] + ) + + # Find a seed that selects the alternative near-top option + layout1 = map1["collection"].variant_knobs["layout"] + found_diff = False + for alt_seed in range(1, 20): + backend_alt = ScriptedAnswers(answers=dist_answers).backend() + synth_alt = DecisionSynthesizer([catalog], backend_alt, config=config) + out_alt = await synth_alt.synthesize( + RESORT.intent, RESORT.payload, variety_seed=alt_seed + ) + assert out_alt.layout_plan is not None + assert out_alt.layout_plan.family == "inspect" + assert out_alt.layout_plan.archetype == "detail" + map_alt = {b.block_id: b for b in out_alt.layout_plan.blocks} + alt_layout = map_alt["collection"].variant_knobs["layout"] + # Option must only be one of the near-top options ("cards" or "reel"), never "rows" + assert alt_layout in {"cards", "reel"} + if alt_layout != layout1: + found_diff = True + break + assert ( + found_diff + ), "Expected at least one seed to pick the alternative near-top option" + + +@pytest.mark.asyncio +async def test_remix_zero_backend_calls_and_validation() -> None: + catalog = BasicCatalog("v1.0") + sa = ScriptedAnswers(answers=HOST_SCRIPTED) + backend = sa.backend() + synth = DecisionSynthesizer([catalog], backend) + + out = await synth.synthesize(HOST.intent, HOST.payload) + assert out.stage == SynthesisStage.ARCHETYPE + assert len(out.decision_answers) > 0 + initial_batch_count = len(backend.batches) + + # Remix re-uses existing answers without any backend calls + remix_out = await synth.remix( + HOST.intent, HOST.payload, out.decision_answers, seed=123 + ) + assert remix_out.stage == SynthesisStage.ARCHETYPE + assert len(backend.batches) == initial_batch_count + assert remix_out.decision_calls == 0 + assert remix_out.decision_latency_ms == 0.0 + assert remix_out.decision_answers == out.decision_answers + + # Synchronous remix works identically + remix_sync_out = synth.remix_sync( + HOST.intent, HOST.payload, out.decision_answers, seed=123 + ) + assert remix_sync_out.stage == SynthesisStage.ARCHETYPE + assert len(backend.batches) == initial_batch_count + assert remix_sync_out.decision_calls == 0 + + # Mismatched answers raise ValueError + with pytest.raises( + ValueError, match="answers do not match this intent and payload" + ): + await synth.remix(HOST.intent, HOST.payload, out.decision_answers[:-1]) + + with pytest.raises( + ValueError, match="answers do not match this intent and payload" + ): + await synth.remix(HOST.intent, HOST.payload, ()) + + +@pytest.mark.asyncio +async def test_argmax_reproduces_existing_plans_exactly() -> None: + catalog = BasicCatalog("v1.0") + sa = ScriptedAnswers(answers=HOST_SCRIPTED) + synth = DecisionSynthesizer( + [catalog], sa.backend(), config=SynthesisConfig(variety=VarietyMode.ARGMAX) + ) + + out = await synth.synthesize(HOST.intent, HOST.payload) + assert out.stage == SynthesisStage.ARCHETYPE + assert out.layout_plan is not None + assert out.layout_plan.family == "monitor" + assert out.layout_plan.archetype == "dashboard" + assert list(out.layout_plan.block_ids()) == [ + "banner", + "headline", + "facts", + ] diff --git a/runit b/runit new file mode 100755 index 0000000000..768397d268 --- /dev/null +++ b/runit @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +exec "${SCRIPT_DIR}/samples/agent/adk/format_playground/run.sh" "$@" diff --git a/samples/agent/adk/format_playground/README.md b/samples/agent/adk/format_playground/README.md new file mode 100644 index 0000000000..4f94bf6fab --- /dev/null +++ b/samples/agent/adk/format_playground/README.md @@ -0,0 +1,112 @@ +# A2UI format playground + +A chat-style sample agent for exploring A2UI inference formats and tool rendering workflows. You can interact with the agent in chat mode (`decision`, `express`, or `direct`) or try `tool` mode where tool execution data is rendered directly via the decision model. + +In chat mode, the agent works in two stages. Stage 1 is a single model call that turns your request into a decision block (`intent`, `payload`, optional `layout`, `title`, `summary`), which is the same structure the `decision` inference format publishes to agents. Stage 2 renders it: `decision` compiles the block with the decision model with zero additional model calls; `express` and `direct` make a second model call using that format's prompt and validate the reply. Running `/compare` renders all three modes from one payload for direct comparison. + +In `tool` mode, the language model is provided domain tools (`get_host_health`, `get_resort`, `get_transfer_quote`, `get_playback_settings`). The tool output is passed directly to the decision synthesizer without asking the language model to write UI code. + +Every turn ends with a footer card naming the mode, the backend, the number of model calls, the latency, token counts, and archetype or path details. + +## Prerequisites + +- Python (see `requires-python` in `pyproject.toml`) and [uv](https://docs.astral.sh/uv/) +- Node and Yarn for the sample client +- A Gemini API key (`GEMINI_API_KEY`), or Vertex AI configured through `GOOGLE_GENAI_USE_VERTEXAI=TRUE` +- Optional: `MODEL_NAME` to pick a model (defaults to `gemini-3.6-flash`) + +## Running the agent + +Use [`run.sh`](run.sh) with a preset name (`local`, `mock`, `jev`, `gev`, `express`, `direct`, or `tool`): + +```bash +cd samples/agent/adk/format_playground +export GEMINI_API_KEY=... + +./run.sh local # in-process ONNX cross-encoder (auto-installs local deps) +./run.sh mock # deterministic offline heuristic +./run.sh gev # starts local Gev server (vertex/decision-gemma) and connects to it +JEV_API_KEY=... ./run.sh jev # remote TypeSafe Jev (/v1/systemone) +./run.sh express # start in express render mode +./run.sh direct # start in direct render mode +./run.sh tool # start in tool mode (ADK tool call with zero UI model calls) +``` + +Or run the package directly with `uv`: + +```bash +A2UI_DECISION_BACKEND=mock uv run . --mode tool +``` + +The startup log names the initial mode, the model, the decision backend, and the +URL (`http://localhost:10010` by default; `--port` changes it). + +### Decision backends + +The decision backend is chosen by `A2UI_DECISION_BACKEND` and the other +`A2UI_DECISION_*` variables, exactly as `create_decision_backend()` documents +them. The resolved backend is shown in `/help` and in every footer. + +| Backend | Setup | What to expect | +| :-- | :-- | :-- | +| `mock` | Nothing. Runs offline. | A deterministic keyword heuristic. Layouts are plain; use it to check the wiring, not the quality. | +| `local` | `uv sync --package a2ui-format-playground --extra local`, then `A2UI_DECISION_BACKEND=local`. The first run downloads the cross-encoder model. | The real in-process experience, no network at render time. | +| `jev` / `systemone` | `A2UI_DECISION_BACKEND=jev A2UI_DECISION_URL=https://... A2UI_DECISION_AUTH=adc` | Remote decision model over HTTP. | + +## Running the client + +The Lit sample shell talks to any A2A agent and already knows this one: + +```bash +cd samples/client/lit/shell +yarn build # the first build also builds typescript/renderers/lit, so it is slow +yarn dev +``` + +Open `http://localhost:/?app=playground` with the port Vite prints. + +Two things about this client are worth knowing. It renders A2UI surfaces only +and clears them before each reply, so the agent's text replies (`/help`, the +footer, `/trace`) arrive as small cards, and earlier turns do not stay on +screen. And if you paste a message that is a bare JSON object, the shell sends +it as data rather than text; the agent uses it verbatim as the payload, which is +the quickest way to try your own data shapes. + +## Commands + +| Command | Effect | +| :-- | :-- | +| `/mode decision` \| `express` \| `direct` \| `tool` | Picks how the next requests render. | +| `/compare` | Renders the next request through all three chat modes from the same data. | +| `/trace` | Shows the planner's questions, answers, and thresholds for the last `decision` render. | +| `/rate [comment]` | Records a preference vote for the last rendered turn. | +| `/ratings` | Summarizes recorded mode preference win counts from the ratings log. | +| `/remix [seed]` | Re-samples the last decision layout with 0 model calls and 0 decision backend queries. | +| `/help` | Shows the active settings and these commands. | + +Anything else is a render request. A message that contains a JSON object or +array uses it verbatim as the payload. Pressing a button on a rendered surface +sends the action back to stage 1 as text, so forms round-trip. + +## What the footer tells you + +```text +decision · mock · 1 LLM call · 1.8 s · 412 in / 96 out tokens · archetype detail (0.82) · 4 blocks +express · llm · 2 LLM calls · 4.1 s · 5,210 in / 318 out tokens +direct · llm · 2 LLM calls · 5.6 s · 12,044 in / 890 out tokens +``` + +The `decision` row counts only the stage-1 call; the other two add the format's +own call. When stage 2 had to retry an invalid reply the footer says +`fallback: validation_retry`; when the decision planner abstained and rendered +the fallback card it says `fallback: fallback_card`. + +## Disclaimer + +Important: The sample code provided is for demonstration purposes and illustrates the mechanics of A2UI and the Agent-to-Agent (A2A) protocol. When building production applications, it is critical to treat any agent operating outside of your direct control as a potentially untrusted entity. + +All operational data received from an external agent, including its AgentCard, messages, artifacts, and task statuses, should be handled as untrusted input. For example, a malicious agent could provide crafted data in its fields (e.g., name, skills.description) that, if used without sanitization to construct prompts for a Large Language Model (LLM), could expose your application to prompt injection attacks. + +Similarly, any UI definition or data stream received must be treated as untrusted. Malicious agents could attempt to spoof legitimate interfaces to deceive users (phishing), inject malicious scripts via property values (XSS), or generate excessive layout complexity to degrade client performance (DoS). If your application supports optional embedded content (such as iframes or web views), additional care must be taken to prevent exposure to malicious external sites. + +Developer Responsibility: Failure to properly validate data and strictly sandbox rendered content can introduce severe vulnerabilities. Developers are responsible for implementing appropriate security measures, such as input sanitization, Content Security Policies (CSP), strict isolation for optional embedded content, and secure credential handling, to protect their systems and users. diff --git a/samples/agent/adk/format_playground/__init__.py b/samples/agent/adk/format_playground/__init__.py new file mode 100644 index 0000000000..10c96753bb --- /dev/null +++ b/samples/agent/adk/format_playground/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/samples/agent/adk/format_playground/__main__.py b/samples/agent/adk/format_playground/__main__.py new file mode 100644 index 0000000000..4841fe8f93 --- /dev/null +++ b/samples/agent/adk/format_playground/__main__.py @@ -0,0 +1,112 @@ +# 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. + +"""Serves the format playground as an A2A agent.""" + +import logging +import os +from pathlib import Path + +from a2a.server.apps import A2AStarletteApplication +from a2a.server.request_handlers import DefaultRequestHandler +from a2a.server.tasks import InMemoryTaskStore +import click +from dotenv import load_dotenv +from starlette.middleware.cors import CORSMiddleware + +from agent import PlaygroundAgent +from agent_executor import PlaygroundAgentExecutor +from modes import RenderMode + +load_dotenv(Path.home() / ".env") +load_dotenv() + +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + + +class MissingAPIKeyError(Exception): + """Exception for missing API key.""" + + +@click.command() +@click.option("--host", default="localhost") +@click.option("--port", default=10010) +@click.option( + "--mode", + type=click.Choice([m.value for m in RenderMode], case_sensitive=False), + default=os.getenv("A2UI_PLAYGROUND_MODE") or RenderMode.DECISION.value, + help="Initial render mode for new conversations.", +) +@click.option( + "--backend", + default=None, + help=( + "Decision backend ('mock', 'local', 'jev', 'systemone', 'step0');" + " overrides A2UI_DECISION_BACKEND." + ), +) +def main(host: str, port: int, mode: str, backend: str | None) -> None: + try: + if not os.getenv("GOOGLE_GENAI_USE_VERTEXAI") == "TRUE": + if not os.getenv("GEMINI_API_KEY"): + raise MissingAPIKeyError( + "GEMINI_API_KEY environment variable not set and" + " GOOGLE_GENAI_USE_VERTEXAI is not TRUE." + ) + + if backend: + os.environ["A2UI_DECISION_BACKEND"] = backend + + base_url = f"http://{host}:{port}" + agent = PlaygroundAgent( + base_url=base_url, + default_mode=RenderMode(mode.lower()), + ) + logger.info( + "Format playground on %s (mode %s, model %s, decision backend %s)", + base_url, + agent.default_mode, + agent.model_name, + agent.renderers.backend_name, + ) + + request_handler = DefaultRequestHandler( + agent_executor=PlaygroundAgentExecutor(agent), + task_store=InMemoryTaskStore(), + ) + server = A2AStarletteApplication( + agent_card=agent.agent_card, http_handler=request_handler + ) + import uvicorn + + app = server.build() + app.add_middleware( + CORSMiddleware, + allow_origin_regex=r"http://localhost:\d+", + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + ) + uvicorn.run(app, host=host, port=port) + except MissingAPIKeyError as e: + logger.error(f"Error: {e}") + exit(1) + except Exception as e: + logger.error(f"An error occurred during server startup: {e}") + exit(1) + + +if __name__ == "__main__": + main() diff --git a/samples/agent/adk/format_playground/agent.py b/samples/agent/adk/format_playground/agent.py new file mode 100644 index 0000000000..89f276f201 --- /dev/null +++ b/samples/agent/adk/format_playground/agent.py @@ -0,0 +1,834 @@ +# 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. + +"""The format playground agent: commands, stage 1, and per-mode rendering.""" + +from __future__ import annotations + +from collections import OrderedDict +from collections.abc import AsyncIterable, Sequence +import logging +import os +import random +import time +from typing import Any +import uuid + +from a2a.types import AgentCapabilities, AgentCard, AgentSkill, Part, TextPart +from google.adk.agents import run_config +from google.adk.agents.llm_agent import LlmAgent +from google.adk.artifacts import InMemoryArtifactService +from google.adk.memory.in_memory_memory_service import InMemoryMemoryService +from google.adk.models import Gemini +from google.adk.runners import Runner +from google.adk.sessions import InMemorySessionService +from google.genai import types + +from a2ui.a2a import get_a2ui_agent_extension +from a2ui.core import A2uiError +from a2ui.inference_formats.decision import ( + ArchetypeGrammar, + DecisionBlock, + create_decision_backend, +) +from commands import DECISION_BACKENDS, apply_command, help_text, parse_command +from modes import ( + CHAT_MODES, + LlmCaller, + LlmToolTurn, + LlmTurn, + PlaygroundSettings, + RenderMode, + RenderResult, + TurnMetrics, + as_mode, + format_decision_ms, + surface_id_for, +) +from ratings import ( + RATINGS_PATH, + RatingRecord, + append_rating, + summarize_ratings, +) +from renderers import Renderers, build_named_backend +from stage1 import ( + TOOL_MODE_INSTRUCTION, + extract_block, + stage1_instruction, + stage1_user_text, +) +from tools import TOOL_INTENTS, TOOL_MUTABLE_PATHS, TOOLS + +logger = logging.getLogger(__name__) + +_STAGE1_KEY = "stage1" +_MAX_SESSIONS = 100 +_VERSIONS = ("0.9", "1.0") +_SUPPORTED_CONTENT_TYPES = ["text", "text/plain"] + + +def default_model_name() -> str: + """The model name from `MODEL_NAME`, `LITELLM_MODEL`, or the sample default.""" + model_env = ( + os.getenv("MODEL_NAME") or os.getenv("LITELLM_MODEL") or "gemini-3.6-flash" + ) + return model_env.split("/")[-1] + + +class AdkLlmCaller: + """`LlmCaller` over the ADK: one `LlmAgent` and `Runner` per instruction key.""" + + def __init__( + self, model_name: str, app_name: str, user_id: str = "playground" + ) -> None: + self._model_name = model_name + self._app_name = app_name + self._user_id = user_id + self._runners: dict[str, Runner] = {} + + def _runner_for( + self, + instruction_key: str, + instruction: str, + tools: Sequence[Any] | None = None, + ) -> Runner: + cache_key = f"{instruction_key}:{len(tools or ())}" + runner = self._runners.get(cache_key) + if runner is None: + agent = LlmAgent( + model=Gemini( + model=self._model_name, + retry_options=types.HttpRetryOptions(attempts=3, initial_delay=2.0), + ), + name=( + f"playground_{instruction_key.replace(':', '_').replace('.', '_')}" + ), + description="Format playground stage agent.", + instruction=instruction, + tools=list(tools) if tools else None, + ) + runner = Runner( + app_name=self._app_name, + agent=agent, + artifact_service=InMemoryArtifactService(), + session_service=InMemorySessionService(), + memory_service=InMemoryMemoryService(), + ) + self._runners[cache_key] = runner + return runner + + async def _session_for(self, runner: Runner, session_id: str | None) -> str: + """Returns an existing session id, or creates one (fresh when `session_id` is None).""" + sid = session_id or f"oneshot-{uuid.uuid4()}" + session = await runner.session_service.get_session( + app_name=self._app_name, user_id=self._user_id, session_id=sid + ) + if session is None: + await runner.session_service.create_session( + app_name=self._app_name, user_id=self._user_id, session_id=sid + ) + return sid + + async def __call__( + self, + *, + instruction_key: str, + instruction: str, + user_text: str, + session_id: str | None, + ) -> LlmTurn: + runner = self._runner_for(instruction_key, instruction) + sid = await self._session_for(runner, session_id) + started = time.perf_counter() + chunks: list[str] = [] + prompt_tokens = output_tokens = 0 + async for event in runner.run_async( + user_id=self._user_id, + session_id=sid, + new_message=types.Content( + role="user", parts=[types.Part.from_text(text=user_text)] + ), + run_config=run_config.RunConfig( + streaming_mode=run_config.StreamingMode.NONE + ), + ): + if event.content and event.content.parts: + chunks.extend(p.text for p in event.content.parts if p.text) + usage = getattr(event, "usage_metadata", None) + if usage is not None: + prompt_tokens = int(usage.prompt_token_count or 0) + output_tokens += int(usage.candidates_token_count or 0) + return LlmTurn( + text="".join(chunks), + prompt_tokens=prompt_tokens, + output_tokens=output_tokens, + latency_ms=(time.perf_counter() - started) * 1000.0, + ) + + async def call_with_tools( + self, + *, + instruction_key: str, + instruction: str, + user_text: str, + session_id: str | None, + tools: Sequence[Any], + ) -> LlmToolTurn: + runner = self._runner_for(instruction_key, instruction, tools=tools) + sid = await self._session_for(runner, session_id) + started = time.perf_counter() + chunks: list[str] = [] + tool_name: str | None = None + tool_args: dict[str, Any] = {} + tool_result: Any = None + prompt_tokens = output_tokens = 0 + async for event in runner.run_async( + user_id=self._user_id, + session_id=sid, + new_message=types.Content( + role="user", parts=[types.Part.from_text(text=user_text)] + ), + run_config=run_config.RunConfig( + streaming_mode=run_config.StreamingMode.NONE + ), + ): + if event.content and event.content.parts: + for p in event.content.parts: + if p.text: + chunks.append(p.text) + if hasattr(p, "function_call") and p.function_call: + tool_name = p.function_call.name + tool_args = dict(p.function_call.args or {}) + if hasattr(p, "function_response") and p.function_response: + tool_result = p.function_response.response + usage = getattr(event, "usage_metadata", None) + if usage is not None: + prompt_tokens = int(usage.prompt_token_count or 0) + output_tokens += int(usage.candidates_token_count or 0) + + if tool_name and tool_result is None: + for t in tools: + if getattr(t, "__name__", None) == tool_name: + try: + tool_result = t(**tool_args) + except Exception as exc: # pylint: disable=broad-exception-caught + logger.warning("Failed executing tool %s: %s", tool_name, exc) + break + + return LlmToolTurn( + tool_name=tool_name, + arguments=tool_args, + result=tool_result, + prompt_tokens=prompt_tokens, + output_tokens=output_tokens, + latency_ms=(time.perf_counter() - started) * 1000.0, + text="".join(chunks), + ) + + +class PlaygroundAgent: + """Chat agent that renders one request through the chosen inference mode.""" + + def __init__( + self, + base_url: str, + *, + llm: LlmCaller | None = None, + renderers: Renderers | None = None, + model_name: str | None = None, + default_mode: RenderMode = RenderMode.DECISION, + ) -> None: + self.base_url = base_url + self.model_name = model_name or default_model_name() + self.default_mode = default_mode + self.llm: LlmCaller = ( + llm + if llm is not None + else AdkLlmCaller(self.model_name, "format_playground") + ) + self.renderers = ( + renderers + if renderers is not None + else Renderers(versions=_VERSIONS, backend=create_decision_backend()) + ) + self._grammar = ArchetypeGrammar.default() + self._stage1_instruction = stage1_instruction(self._grammar) + self._settings: OrderedDict[str, PlaygroundSettings] = OrderedDict() + self._last_trace: OrderedDict[str, tuple[str, ...]] = OrderedDict() + self._last_turn: OrderedDict[ + str, tuple[str, list[tuple[RenderMode, RenderResult, TurnMetrics]]] + ] = OrderedDict() + self._last_decision_context: OrderedDict[ + str, + tuple[ + str, + Any, + tuple[Any, ...], + Sequence[str], + str | None, + str | None, + ], + ] = OrderedDict() + self.agent_card = self._build_agent_card() + + def _build_agent_card(self) -> AgentCard: + extensions = [ + get_a2ui_agent_extension( + version, + supported_catalog_ids=[ + c.catalog_id + for c in self.renderers.processor( + RenderMode.DECISION, version + ).active_catalogs + ], + ) + for version in self.renderers.versions + ] + skill = AgentSkill( + id="render_ui", + name="Render a described interface", + description=( + "Describe an interface in plain language and it is rendered through" + " the decision, express, or direct inference format. Commands:" + " /mode, /backend, /compare, /trace, /help." + ), + tags=["a2ui", "playground", "decision"], + examples=["Give me an address entry form", "Show my stock portfolio"], + ) + return AgentCard( + name="A2UI Format Playground", + description="Renders chat requests through the A2UI inference formats.", + url=self.base_url, + version="1.0.0", + default_input_modes=_SUPPORTED_CONTENT_TYPES, + default_output_modes=_SUPPORTED_CONTENT_TYPES, + capabilities=AgentCapabilities(streaming=True, extensions=extensions), + skills=[skill], + ) + + # --- per-conversation state ------------------------------------------------- + + def _settings_for(self, session_id: str) -> PlaygroundSettings: + settings = self._settings.get(session_id) + if settings is None: + settings = PlaygroundSettings(mode=self.default_mode) + self._remember(self._settings, session_id, settings) + return settings + + @staticmethod + def _remember(store: OrderedDict[str, Any], key: str, value: Any) -> None: + store[key] = value + store.move_to_end(key) + while len(store) > _MAX_SESSIONS: + store.popitem(last=False) + + # --- replies --------------------------------------------------------------- + + def _status( + self, + lines: Sequence[str], + settings: PlaygroundSettings, + version: str, + suffix: str = "status", + ) -> list[Part]: + return self.renderers.status_surface( + lines, + surface_id=f"{surface_id_for(settings)}-{suffix}", + version=version, + ) + + async def stream( + self, query: str, session_id: str, ui_version: str | None + ) -> AsyncIterable[dict[str, Any]]: + """Handles one chat message and yields a single final item of parts.""" + if ui_version is None: + yield { + "is_task_complete": True, + "parts": [ + Part( + root=TextPart( + text=( + "This playground renders A2UI surfaces; connect with" + " a client that requests the A2UI extension." + ) + ) + ) + ], + } + return + settings = self._settings_for(session_id) + command = parse_command(query) + if command is not None: + parts = await self._run_command(command, session_id, settings, ui_version) + elif settings.mode is RenderMode.TOOL and not settings.compare: + parts = await self._render_tool_turn( + query, session_id, settings, ui_version + ) + else: + parts = await self._render_turn(query, session_id, settings, ui_version) + yield {"is_task_complete": True, "parts": parts} + + async def _run_command( + self, + command: Any, + session_id: str, + settings: PlaygroundSettings, + version: str, + ) -> list[Part]: + new_settings, reply = apply_command(command, settings) + self._remember(self._settings, session_id, new_settings) + if command.name == "help": + lines = help_text( + new_settings, self.renderers.backend_name, self.model_name + ) + if command.argument and command.argument.startswith("unknown:"): + lines.insert( + 0, f"Unknown command `{command.argument[len('unknown:'):]}`." + ) + elif command.name == "backend": + lines = self._switch_backend(command.argument) + elif command.name == "trace": + lines = list(self._last_trace.get(session_id, ())) or [ + "No decision turn yet. Render something in `decision` mode first." + ] + elif command.name == "rate": + lines = self._rate_turn(session_id, command.argument, command.text) + elif command.name == "ratings": + lines = self._show_ratings() + elif command.name == "remix": + return await self._remix_turn( + session_id, command.argument, new_settings, version + ) + else: + lines = [reply or ""] + return self._status(lines, new_settings, version) + + def _switch_backend(self, argument: str | None) -> list[str]: + if not argument: + choices = ", ".join(DECISION_BACKENDS) + return [ + f"Active decision backend: `{self.renderers.backend_name}`" + f" (choose {choices})." + ] + try: + backend = build_named_backend(argument) + except ValueError as exc: + return [str(exc)] + self.renderers.set_backend(backend) + return [f"Decision backend set to `{self.renderers.backend_name}`."] + + async def _render_turn( + self, + query: str, + session_id: str, + settings: PlaygroundSettings, + version: str, + ) -> list[Part]: + settings = settings.next_turn() + try: + stage1 = await self.llm( + instruction_key=_STAGE1_KEY, + instruction=self._stage1_instruction, + user_text=stage1_user_text(query), + session_id=session_id, + ) + except Exception as exc: # the model call itself failed; keep the chat alive + logger.exception("Stage 1 failed") + self._remember(self._settings, session_id, settings) + return self._status([f"Stage 1 failed: {exc}"], settings, version) + block = extract_block(stage1.text) + if block is None: + self._remember(self._settings, session_id, settings) + prose = stage1.text.strip() or "(empty reply)" + return self._status( + [ + ( + "I could not turn that into a decision block; try describing" + " the data you want to see." + ), + f"The model said: {prose[:500]}", + ], + settings, + version, + ) + modes = list(CHAT_MODES) if settings.compare else [settings.mode] + parts: list[Part] = [] + results: list[tuple[RenderMode, RenderResult]] = [] + turn_candidates: list[tuple[RenderMode, RenderResult, TurnMetrics]] = [] + for mode in modes: + result = await self._render_mode(mode, block, settings, version) + results.append((mode, result)) + parts.extend(result.parts) + parts.extend(self._footer_parts(mode, result, stage1, settings, version)) + if mode is RenderMode.DECISION: + if result.trace_lines: + self._remember(self._last_trace, session_id, result.trace_lines) + if result.decision_answers: + self._remember( + self._last_decision_context, + session_id, + ( + block.intent, + block.payload, + result.decision_answers, + block.mutable_paths, + block.title, + block.summary, + ), + ) + cand_metrics = ( + result.metrics + or TurnMetrics(mode=mode, backend="llm", llm_calls=0, latency_ms=0.0) + ).plus_stage1(stage1) + turn_candidates.append((mode, result, cand_metrics)) + if settings.compare: + parts.extend(self._compare_summary(results, stage1, settings, version)) + self._remember(self._last_turn, session_id, (query, turn_candidates)) + self._remember( + self._settings, + session_id, + settings.__class__(mode=settings.mode, turn=settings.turn), + ) + return parts + + async def _render_tool_turn( + self, + query: str, + session_id: str, + settings: PlaygroundSettings, + version: str, + ) -> list[Part]: + settings = settings.next_turn() + try: + tool_turn = await self.llm.call_with_tools( + instruction_key="tool_mode", + instruction=TOOL_MODE_INSTRUCTION, + user_text=query, + session_id=session_id, + tools=TOOLS, + ) + except Exception as exc: # the model call itself failed; keep the chat alive + logger.exception("Tool mode call failed") + self._remember(self._settings, session_id, settings) + return self._status([f"Tool call failed: {exc}"], settings, version) + + surface_id = surface_id_for(settings, RenderMode.TOOL) + if not tool_turn.tool_name or tool_turn.result is None: + self._remember(self._settings, session_id, settings) + prose = ( + tool_turn.text.strip() or "No relevant tool was found for that request." + ) + metrics = TurnMetrics( + mode=RenderMode.TOOL, + backend="llm", + llm_calls=1, + latency_ms=tool_turn.latency_ms, + prompt_tokens=tool_turn.prompt_tokens, + output_tokens=tool_turn.output_tokens, + ) + parts = self._status([prose], settings, version) + footer_lines = [metrics.footer()] + parts.extend( + self._status(footer_lines, settings, version, suffix="tool-footer") + ) + self._remember( + self._last_turn, + session_id, + ( + query, + [( + RenderMode.TOOL, + RenderResult(parts=parts, metrics=metrics), + metrics, + )], + ), + ) + return parts + + tool_result = tool_turn.result + intent = TOOL_INTENTS.get(tool_turn.tool_name, "Tool Result") + mutable_paths = TOOL_MUTABLE_PATHS.get(tool_turn.tool_name, ()) + + result = await self.renderers.render_tool_result( + intent, + tool_result, + surface_id=surface_id, + version=version, + mutable_paths=mutable_paths, + ) + + stage1_equivalent = LlmTurn( + text=tool_turn.text, + prompt_tokens=tool_turn.prompt_tokens, + output_tokens=tool_turn.output_tokens, + latency_ms=tool_turn.latency_ms, + ) + base_metrics = result.metrics or TurnMetrics( + mode=RenderMode.TOOL, + backend=self.renderers.backend_name, + llm_calls=0, + latency_ms=0.0, + ) + metrics = base_metrics.plus_stage1(stage1_equivalent) + + parts = list(result.parts) + footer_lines = [metrics.footer()] + if result.error: + footer_lines.append(f"Render failed: {result.error}") + parts.extend( + self._status(footer_lines, settings, version, suffix="tool-footer") + ) + + if result.trace_lines: + self._remember(self._last_trace, session_id, result.trace_lines) + if result.decision_answers: + self._remember( + self._last_decision_context, + session_id, + ( + intent, + tool_result, + result.decision_answers, + mutable_paths, + None, + None, + ), + ) + + self._remember( + self._last_turn, + session_id, + (query, [(RenderMode.TOOL, result, metrics)]), + ) + self._remember( + self._settings, + session_id, + settings.__class__(mode=settings.mode, turn=settings.turn), + ) + return parts + + async def _remix_turn( + self, + session_id: str, + argument: str | None, + settings: PlaygroundSettings, + version: str, + ) -> list[Part]: + context = self._last_decision_context.get(session_id) + if not context: + return self._status( + [ + "No previous decision render to remix. Render something" + " in `decision` or `tool` mode first." + ], + settings, + version, + ) + seed: int | None = None + if argument: + try: + seed = int(argument) + except ValueError: + return self._status( + [ + f"Invalid seed `{argument}`; provide an integer (e.g." + " `/remix 42`)." + ], + settings, + version, + ) + else: + seed = random.randint(1, 1000000) + + intent, payload, answers, mutable_paths, title, summary = context + surface_id = surface_id_for(settings, RenderMode.DECISION) + result = await self.renderers.remix( + intent, + payload, + answers, + surface_id=surface_id, + version=version, + mutable_paths=mutable_paths, + title=title, + summary=summary, + seed=seed, + ) + if not result.ok: + return self._status([f"Remix failed: {result.error}"], settings, version) + + parts = list(result.parts) + metrics = result.metrics or TurnMetrics( + mode=RenderMode.DECISION, + backend="remix", + llm_calls=0, + latency_ms=0.0, + remix_seed=seed, + ) + footer_lines = [metrics.footer()] + parts.extend( + self._status(footer_lines, settings, version, suffix="remix-footer") + ) + + if result.trace_lines: + self._remember(self._last_trace, session_id, result.trace_lines) + if result.decision_answers: + self._remember( + self._last_decision_context, + session_id, + ( + intent, + payload, + result.decision_answers, + mutable_paths, + title, + summary, + ), + ) + self._remember( + self._last_turn, + session_id, + (f"/remix {seed}", [(RenderMode.DECISION, result, metrics)]), + ) + return parts + + def _rate_turn( + self, session_id: str, argument: str | None, comment: str | None + ) -> list[str]: + if not argument: + return [ + "Usage: `/rate [comment]` (e.g. `/rate decision Looks cleaner`)." + ] + winner = argument.lower() + if winner not in [m.value for m in RenderMode]: + choices = ", ".join(m.value for m in RenderMode) + return [f"Unknown mode `{winner}`; choose {choices}."] + last_turn = self._last_turn.get(session_id) + if last_turn is None: + return ["No previous turn to rate. Render an interface first."] + query, candidates = last_turn + candidate_dicts = [ + { + "mode": mode.value, + "ok": res.ok, + "error": res.error, + "latency_ms": metrics.latency_ms, + "llm_calls": metrics.llm_calls, + "output_tokens": metrics.output_tokens, + } + for mode, res, metrics in candidates + ] + record = RatingRecord( + session_id=session_id, + request=query, + winner=winner, + comment=comment or "", + candidates=candidate_dicts, + ) + try: + append_rating(RATINGS_PATH, record) + except Exception as exc: # pylint: disable=broad-exception-caught + logger.warning("Failed appending rating: %s", exc) + return [f"Failed saving rating: {exc}"] + suffix = f" with comment: {comment}" if comment else "" + return [f"Recorded preference for `{winner}`{suffix}."] + + def _show_ratings(self) -> list[str]: + wins = summarize_ratings(RATINGS_PATH) + if not wins: + return ["No ratings recorded yet. Use `/rate [comment]` to vote."] + total = sum(wins.values()) + lines = [ + f"**Mode preferences** ({total} total vote{'s' if total != 1 else ''}):" + ] + for mode in RenderMode: + count = wins.get(mode.value, 0) + pct = (count / total * 100.0) if total > 0 else 0.0 + lines.append(f"- `{mode.value}`: {count} ({pct:.1f}%)") + return lines + + async def _render_mode( + self, + mode: RenderMode, + block: DecisionBlock, + settings: PlaygroundSettings, + version: str, + ) -> RenderResult: + surface_id = surface_id_for(settings, mode) + try: + if mode is RenderMode.DECISION: + return await self.renderers.render_decision( + block, surface_id=surface_id, version=version + ) + if mode is RenderMode.TOOL: + return await self.renderers.render_tool_result( + block.intent, + block.payload, + surface_id=surface_id, + version=version, + mutable_paths=block.mutable_paths, + ) + return await self.renderers.render_with_llm( + mode, block, surface_id=surface_id, version=version, llm=self.llm + ) + except (A2uiError, ValueError) as exc: + logger.warning("%s render failed: %s", mode, exc) + return RenderResult(error=str(exc)) + + def _footer_parts( + self, + mode: RenderMode, + result: RenderResult, + stage1: LlmTurn, + settings: PlaygroundSettings, + version: str, + ) -> list[Part]: + metrics = result.metrics or TurnMetrics( + mode=mode, backend="llm", llm_calls=0, latency_ms=0.0 + ) + lines = [metrics.plus_stage1(stage1).footer()] + if result.error: + lines.append(f"Render failed: {result.error}") + return self._status(lines, settings, version, suffix=f"{mode}-footer") + + def _compare_summary( + self, + results: Sequence[tuple[RenderMode, RenderResult]], + stage1: LlmTurn, + settings: PlaygroundSettings, + version: str, + ) -> list[Part]: + lines = ["**Compare** (same intent and data through every mode)"] + for mode, result in results: + metrics = ( + result.metrics + or TurnMetrics(mode=mode, backend="llm", llm_calls=0, latency_ms=0.0) + ).plus_stage1(stage1) + status = "ok" if result.ok else f"failed: {result.error}" + extra_parts: list[str] = [] + if metrics.decision_latency_ms is not None: + extra_parts.append( + f"decision {format_decision_ms(metrics.decision_latency_ms)}" + ) + path = metrics.path_summary() + if path is not None: + extra_parts.append(path) + extra = f" ({', '.join(extra_parts)})" if extra_parts else "" + lines.append( + f"`{mode}`: {metrics.llm_calls}" + f" call{'s' if metrics.llm_calls != 1 else ''}," + f" {metrics.latency_ms / 1000.0:.1f} s{extra}," + f" {metrics.output_tokens} out tokens, {status}" + ) + return self._status(lines, settings, version, suffix="compare") diff --git a/samples/agent/adk/format_playground/agent_executor.py b/samples/agent/adk/format_playground/agent_executor.py new file mode 100644 index 0000000000..85348b3e82 --- /dev/null +++ b/samples/agent/adk/format_playground/agent_executor.py @@ -0,0 +1,140 @@ +# 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. + +"""A2A executor for the format playground. + +Turns an incoming A2A message into one text query for the agent. Three kinds +of `DataPart` are understood: the `useStreaming` flag, a UI action (either the +v0.9 `{"version", "action"}` shape or the `{"userAction"}` shape the sample +clients send), and anything else, which is treated as a pasted JSON payload. +""" + +from __future__ import annotations + +from collections.abc import Mapping +import json +import logging +from typing import TYPE_CHECKING, Any, Literal + +from a2a.server.agent_execution import AgentExecutor, RequestContext +from a2a.server.events import EventQueue +from a2a.server.tasks import TaskUpdater +from a2a.types import DataPart, Task, TaskState, TextPart, UnsupportedOperationError +from a2a.utils import new_agent_parts_message, new_agent_text_message, new_task +from a2a.utils.errors import ServerError + +from a2ui.a2a import try_activate_a2ui_extension +from a2ui.core.schema import ProtocolVersion +from stage1 import UI_ACTION_PREFIX + +if TYPE_CHECKING: + from agent import PlaygroundAgent + +logger = logging.getLogger(__name__) + +DataPartKind = Literal["streaming", "action", "payload"] + + +def classify_data_part(data: Mapping[str, Any]) -> tuple[DataPartKind, Any]: + """Classifies one `DataPart` payload. + + Returns ``("streaming", bool)`` for the `useStreaming` flag, + ``("action", mapping)`` for a v0.9 `action` or a `userAction` payload, and + ``("payload", data)`` for anything else (a pasted JSON object). + """ + if "useStreaming" in data: + return "streaming", bool(data["useStreaming"]) + if data.get("version") == ProtocolVersion.V0_9 and isinstance( + data.get("action"), Mapping + ): + return "action", data["action"] + if isinstance(data.get("userAction"), Mapping): + return "action", data["userAction"] + return "payload", data + + +def action_query(action: Mapping[str, Any]) -> str: + """The stage-1 text for a UI action.""" + name = action.get("name", "unknown") + context = action.get("context", {}) + return ( + f"{UI_ACTION_PREFIX} action `{name}` with context {json.dumps(context)}." + " Reply with an updated interface or a confirmation." + ) + + +def payload_query(data: Any, text: str) -> str: + """The stage-1 text for a pasted JSON payload, prefixed by any typed text.""" + encoded = json.dumps(data, indent=2) + prefix = f"{text}\n\n" if text else "" + return f"{prefix}Use this JSON verbatim as the payload:\n```json\n{encoded}\n```" + + +def build_query(parts: list[Any]) -> str: + """Builds the agent query from the message parts, text first.""" + text = " ".join( + p.root.text for p in parts if isinstance(p.root, TextPart) and p.root.text + ).strip() + for part in parts: + if not isinstance(part.root, DataPart): + continue + kind, value = classify_data_part(part.root.data) + if kind == "action": + return action_query(value) + if kind == "payload": + return payload_query(value, text) + return text + + +class PlaygroundAgentExecutor(AgentExecutor): + """Routes A2A requests to `PlaygroundAgent.stream`.""" + + def __init__(self, agent: PlaygroundAgent) -> None: + self._agent = agent + + async def execute(self, context: RequestContext, event_queue: EventQueue) -> None: + active_ui_version = try_activate_a2ui_extension(context, self._agent.agent_card) + parts = list(context.message.parts) if context.message else [] + query = build_query(parts) or context.get_user_input() + logger.info("Playground query (a2ui %s): %r", active_ui_version, query[:200]) + + task = context.current_task + if not task: + task = new_task(context.message) # type: ignore[arg-type] + await event_queue.enqueue_event(task) + updater = TaskUpdater(event_queue, task.id, task.context_id) + + async for item in self._agent.stream(query, task.context_id, active_ui_version): + if not item["is_task_complete"]: + if "parts" in item: + message = new_agent_parts_message( + item["parts"], task.context_id, task.id + ) + else: + message = new_agent_text_message( + item.get("updates", ""), task.context_id, task.id + ) + await updater.update_status(TaskState.working, message) + continue + await updater.update_status( + TaskState.input_required, + new_agent_parts_message(item["parts"], task.context_id, task.id), + final=False, + ) + break + + async def cancel( + self, request: RequestContext, event_queue: EventQueue + ) -> Task | None: + raise ServerError(error=UnsupportedOperationError()) diff --git a/samples/agent/adk/format_playground/commands.py b/samples/agent/adk/format_playground/commands.py new file mode 100644 index 0000000000..4373afe06b --- /dev/null +++ b/samples/agent/adk/format_playground/commands.py @@ -0,0 +1,114 @@ +# 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. + +"""Slash commands that change playground settings or ask for information.""" + +from __future__ import annotations + +from dataclasses import dataclass, replace +from typing import Literal + +from modes import PlaygroundSettings, RenderMode, as_mode + +CommandName = Literal[ + "mode", "backend", "compare", "trace", "help", "rate", "ratings", "remix" +] + +DECISION_BACKENDS: tuple[str, ...] = ("jev", "gev", "local", "mock") + +_KNOWN: tuple[CommandName, ...] = ( + "mode", + "backend", + "compare", + "trace", + "help", + "rate", + "ratings", + "remix", +) + + +@dataclass(frozen=True) +class Command: + """A parsed slash command.""" + + name: CommandName + argument: str | None = None + """The first word after the command, lowercased; for `/help`, an `unknown:` + marker when the user typed a command that does not exist.""" + text: str | None = None + """The remainder of the command line after the argument, if any.""" + + +def parse_command(text: str) -> Command | None: + """Parses `/mode express`, `/compare`, `/trace`, `/rate`, `/ratings`, or `/help`.""" + stripped = text.strip() + if not stripped.startswith("/"): + return None + words = stripped[1:].split() + if not words: + return Command("help", argument="unknown:/") + name = words[0].lower() + argument = words[1].lower() if len(words) > 1 else None + rest = " ".join(words[2:]) if len(words) > 2 else None + if name not in _KNOWN: + return Command("help", argument=f"unknown:{stripped}") + return Command(name, argument, rest) + + +def apply_command( + cmd: Command, settings: PlaygroundSettings +) -> tuple[PlaygroundSettings, str | None]: + """Applies `cmd` to `settings`. + + Returns the new settings and a reply, or `None` as the reply for `/help` + and `/trace`, which the agent answers itself. + """ + if cmd.name == "mode": + mode = as_mode(cmd.argument) if cmd.argument else None + if mode is None: + choices = ", ".join(m.value for m in RenderMode) + return settings, f"Unknown mode `{cmd.argument or ''}`; choose {choices}." + return replace(settings, mode=mode), f"Mode set to `{mode}`." + if cmd.name == "compare": + return replace(settings, compare=True), ( + "Next request renders through all three modes from the same data." + ) + return settings, None + + +def help_text( + settings: PlaygroundSettings, backend_name: str, model_name: str +) -> list[str]: + """The `/help` reply, one entry per line.""" + return [ + "**Format playground**", + "Describe an interface and it is rendered through the active mode.", + ( + f"Active mode: `{settings.mode}` · decision backend: `{backend_name}`" + f" · model: `{model_name}`" + ), + "`/mode decision|express|direct|tool` picks how the next requests render.", + "`/backend jev|gev|local|mock` switches the decision model.", + "`/compare` renders the next request through all three modes.", + "`/trace` shows the planner's questions for the last decision render.", + "`/rate [comment]` records a preference vote for the last render.", + "`/ratings` summarizes recorded mode preference win counts.", + "`/remix [seed]` re-samples the last decision layout with 0 model calls.", + "`/help` shows this card.", + ( + "Try: *give me an address entry form*, *show my stock portfolio*," + " or paste a JSON object to render it as is." + ), + ] diff --git a/samples/agent/adk/format_playground/modes.py b/samples/agent/adk/format_playground/modes.py new file mode 100644 index 0000000000..40b1390c29 --- /dev/null +++ b/samples/agent/adk/format_playground/modes.py @@ -0,0 +1,295 @@ +# 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. + +"""Shared contracts for the format playground: modes, settings, and metrics. + +This module has no ADK or A2A imports so the renderers, commands, and tests can +depend on it without pulling in a model runtime. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass, field, replace +from enum import Enum +from typing import Any, Protocol + +from a2a.types import Part + + +class RenderMode(str, Enum): + """Inference mode a turn is rendered through.""" + + DECISION = "decision" + EXPRESS = "express" + DIRECT = "direct" + TOOL = "tool" + + def __str__(self) -> str: + return self.value + + +CHAT_MODES: tuple[RenderMode, ...] = ( + RenderMode.DECISION, + RenderMode.EXPRESS, + RenderMode.DIRECT, +) + + +@dataclass(frozen=True) +class PlaygroundSettings: + """Per-conversation state the slash commands change.""" + + mode: RenderMode = RenderMode.DECISION + compare: bool = False + """When True, the next render goes through all three modes, then resets.""" + turn: int = 0 + """Number of render requests so far; drives the per-turn surface ids.""" + + def next_turn(self) -> PlaygroundSettings: + """The settings for the next render request.""" + return replace(self, turn=self.turn + 1) + + +@dataclass(frozen=True) +class LlmTurn: + """One model call: its text and what it cost.""" + + text: str + prompt_tokens: int = 0 + output_tokens: int = 0 + latency_ms: float = 0.0 + + +@dataclass(frozen=True) +class LlmToolTurn: + """One model call that invokes a tool: the tool called and what it cost.""" + + tool_name: str | None = None + arguments: dict[str, Any] = field(default_factory=dict) + result: Any = None + prompt_tokens: int = 0 + output_tokens: int = 0 + latency_ms: float = 0.0 + text: str = "" + + +class LlmCaller(Protocol): + """Runs one instruction-plus-message turn against a language model. + + `instruction_key` identifies the system instruction so an implementation + can keep one configured agent per key. `session_id=None` means a fresh + session with no history (stage 2); a string keeps conversation history + under that id (stage 1). + """ + + async def __call__( + self, + *, + instruction_key: str, + instruction: str, + user_text: str, + session_id: str | None, + ) -> LlmTurn: + ... + + async def call_with_tools( + self, + *, + instruction_key: str, + instruction: str, + user_text: str, + session_id: str | None, + tools: Sequence[Any], + ) -> LlmToolTurn: + ... + + +def format_decision_ms(ms: float) -> str: + """Formats a decision-model latency in milliseconds (or seconds when >= 1000 ms).""" + if ms < 1.0: + return f"{ms:.2f} ms" + if ms < 1000.0: + return f"{ms:.0f} ms" + return f"{ms / 1000.0:.2f} s ({ms:.0f} ms)" + + +@dataclass(frozen=True) +class TurnMetrics: + """What one render cost, shown in the footer under every surface.""" + + mode: RenderMode + backend: str + """Decision backend name (`mock`, `local`, `jev`, ...) or `llm` for stage-2 modes.""" + llm_calls: int + latency_ms: float + prompt_tokens: int = 0 + output_tokens: int = 0 + archetype: str | None = None + confidence: float | None = None + block_count: int | None = None + fallback: str | None = None + """A `FallbackSource` value, or `validation_retry` when stage 2 needed a retry.""" + stage: str | None = None + """The `SynthesisStage` value (`template_select`, `archetype`, `fast_1pass_leaf`, `container_2pass`, `abstain_fallback`).""" + decision_latency_ms: float | None = None + """Wall-clock milliseconds spent waiting on the decision model.""" + decision_calls: int | None = None + """Number of decision model calls or batches.""" + template_id: str | None = None + """Registered template id when `stage == 'template_select'`.""" + root_component: str | None = None + """Catalog root component when `stage` is `fast_1pass_leaf` or `container_2pass`.""" + remix_seed: int | None = None + """Random seed used when re-sampling layout during remix.""" + + def path_summary(self) -> str | None: + """Describes whether rendering used the decision model, templates, or fallback.""" + conf = f" ({self.confidence:.2f})" if self.confidence is not None else "" + if self.stage == "template_select": + tpl = f" {self.template_id}" if self.template_id else "" + return f"path: templates · template{tpl}{conf}" + if self.stage == "archetype": + arch = ( + f"archetype {self.archetype}{conf}" + if self.archetype is not None + else f"archetype{conf}" + ) + if self.block_count is not None: + blocks = ( + f"{self.block_count} block{'' if self.block_count == 1 else 's'}" + ) + return f"path: decision model · {arch} · {blocks}" + return f"path: decision model · {arch}" + if self.stage == "fast_1pass_leaf": + comp = f" {self.root_component}" if self.root_component else "" + return f"path: decision model · 1-pass leaf{comp}{conf}" + if self.stage == "container_2pass": + comp = f" {self.root_component}" if self.root_component else "" + return f"path: decision model · 2-pass container{comp}{conf}" + if self.stage == "abstain_fallback": + source = self.fallback or "abstained" + return f"path: fallback ({source}) · decision model abstained{conf}" + return None + + def footer(self) -> str: + """One line summarizing the turn, fields separated by ` · `.""" + if self.backend == "remix": + call_label = "0 LLM calls · 0 decision calls" + timing = ( + f"{self.latency_ms:.1f} ms" + if self.latency_ms < 1000.0 + else f"{self.latency_ms / 1000.0:.2f} s" + ) + parts: list[str] = [ + f"**{self.mode}**", + self.backend, + call_label, + timing, + ] + if self.remix_seed is not None: + parts.append(f"remix seed {self.remix_seed}") + path = self.path_summary() + if path is not None: + parts.append(path) + return " · ".join(parts) + + if self.decision_latency_ms is not None: + dec_time = f"decision {format_decision_ms(self.decision_latency_ms)}" + if self.llm_calls > 0: + timing = f"{dec_time} (total {self.latency_ms / 1000.0:.1f} s)" + else: + timing = dec_time + else: + timing = f"{self.latency_ms / 1000.0:.1f} s" + if self.mode == RenderMode.TOOL and self.llm_calls > 0: + call_label = ( + f"{self.llm_calls} LLM call (tool call only)" + if self.llm_calls == 1 + else f"{self.llm_calls} LLM calls (tool calls only)" + ) + else: + call_label = ( + f"{self.llm_calls} LLM call{'' if self.llm_calls == 1 else 's'}" + ) + parts: list[str] = [ + f"**{self.mode}**", + self.backend, + call_label, + timing, + ] + if self.prompt_tokens or self.output_tokens: + parts.append(f"{self.prompt_tokens} in / {self.output_tokens} out tokens") + path = self.path_summary() + if path is not None: + parts.append(path) + else: + if self.archetype is not None: + conf = ( + f" ({self.confidence:.2f})" if self.confidence is not None else "" + ) + parts.append(f"archetype {self.archetype}{conf}") + if self.block_count is not None: + parts.append( + f"{self.block_count} block{'' if self.block_count == 1 else 's'}" + ) + if self.fallback is not None: + parts.append(f"fallback: {self.fallback}") + return " · ".join(parts) + + def plus_stage1(self, stage1: LlmTurn) -> TurnMetrics: + """Folds the stage-1 call into these metrics.""" + return replace( + self, + llm_calls=self.llm_calls + 1, + latency_ms=self.latency_ms + stage1.latency_ms, + prompt_tokens=self.prompt_tokens + stage1.prompt_tokens, + output_tokens=self.output_tokens + stage1.output_tokens, + ) + + +@dataclass(frozen=True) +class RenderResult: + """The outcome of rendering one block through one mode.""" + + parts: list[Part] = field(default_factory=list) + """A2UI data parts for the rendered surface; empty when `error` is set.""" + metrics: TurnMetrics | None = None + trace_lines: tuple[str, ...] = () + """Decision only: one line per planner question, for `/trace`.""" + error: str | None = None + """Why rendering failed, if it did.""" + decision_answers: tuple[Any, ...] = () + output: Any = None + + @property + def ok(self) -> bool: + """Whether the render produced a surface.""" + return self.error is None and bool(self.parts) + + +def surface_id_for(settings: PlaygroundSettings, mode: RenderMode | None = None) -> str: + """The surface id for `settings.turn`, suffixed with `mode` when comparing.""" + base = f"turn-{settings.turn}" + if mode is not None and settings.compare: + return f"{base}-{mode}" + return base + + +def as_mode(value: Any) -> RenderMode | None: + """Parses a user-typed mode name, or None when it is not one.""" + try: + return RenderMode(str(value).strip().lower()) + except ValueError: + return None diff --git a/samples/agent/adk/format_playground/pyproject.toml b/samples/agent/adk/format_playground/pyproject.toml new file mode 100644 index 0000000000..3af73fc73e --- /dev/null +++ b/samples/agent/adk/format_playground/pyproject.toml @@ -0,0 +1,51 @@ +# 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. + +[project] +name = "a2ui-format-playground" +version = "0.1.0" +description = "Chat playground that renders one request through the decision, express, or direct inference format." +readme = "README.md" +requires-python = ">=3.10" +dependencies = [ + "a2a-sdk[http-server]>=0.3.0", + "click>=8.1.8", + "google-adk>=1.28.1", + "google-genai>=1.27.0", + "python-dotenv>=1.1.0", + "a2ui-a2a", + "a2ui-agent-sdk", + "uvicorn>=0.40.0", +] + +[project.optional-dependencies] +local = ["a2ui-agent-sdk[decision-local]"] + +[tool.hatch.build.targets.wheel] +packages = ["."] + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.metadata] +allow-direct-references = true + +[[tool.uv.index]] +url = "https://pypi.org/simple" +default = true + +[tool.uv.sources] +a2ui-a2a = { workspace = true } +a2ui-agent-sdk = { workspace = true } diff --git a/samples/agent/adk/format_playground/ratings.py b/samples/agent/adk/format_playground/ratings.py new file mode 100644 index 0000000000..7f793ce8ee --- /dev/null +++ b/samples/agent/adk/format_playground/ratings.py @@ -0,0 +1,89 @@ +# 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. + +"""Pairwise and multi-candidate rating tracking for the format playground.""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass, field +import datetime +import json +import logging +from pathlib import Path +from typing import Any + +logger = logging.getLogger(__name__) + +RATINGS_PATH = Path(__file__).parent / "logs" / "ratings.jsonl" + + +@dataclass(frozen=True) +class RatingRecord: + """A record capturing a user preference between playground render modes.""" + + session_id: str + request: str + winner: str + comment: str = "" + timestamp: str = field( + default_factory=lambda: datetime.datetime.now(datetime.timezone.utc).isoformat() + ) + candidates: list[dict[str, Any]] = field(default_factory=list) + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> RatingRecord: + return cls( + session_id=str(data.get("session_id", "")), + request=str(data.get("request", "")), + winner=str(data.get("winner", "")), + comment=str(data.get("comment", "")), + timestamp=str(data.get("timestamp", "")), + candidates=list(data.get("candidates", [])), + ) + + +def append_rating(path: str | Path, record: RatingRecord) -> None: + """Appends a rating record to a JSONL file, creating parent directories if needed.""" + p = Path(path) + p.parent.mkdir(parents=True, exist_ok=True) + with open(p, "a", encoding="utf-8") as f: + f.write(json.dumps(record.to_dict()) + "\n") + + +def summarize_ratings(path: str | Path) -> dict[str, int]: + """Reads a ratings JSONL file and summarizes win counts per mode.""" + p = Path(path) + if not p.is_file(): + return {} + + wins: dict[str, int] = {} + with open(p, "r", encoding="utf-8") as f: + for idx, line in enumerate(f, start=1): + stripped = line.strip() + if not stripped: + continue + try: + data = json.loads(stripped) + winner = str(data.get("winner", "")).lower() + if winner: + wins[winner] = wins.get(winner, 0) + 1 + except Exception as exc: # pylint: disable=broad-exception-caught + logger.warning( + "Skipping corrupt rating line %d in %s: %s", idx, path, exc + ) + + return wins diff --git a/samples/agent/adk/format_playground/renderers.py b/samples/agent/adk/format_playground/renderers.py new file mode 100644 index 0000000000..d498c2985b --- /dev/null +++ b/samples/agent/adk/format_playground/renderers.py @@ -0,0 +1,572 @@ +# 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. + +"""Stage 2 of the playground: render one decision block through a mode. + +`decision` compiles the block through `DecisionSynthesizer` with no further +model call. `express` and `direct` ask a model for that format's source with +the same intent and payload, then validate it through the format's processor. +`status_surface` turns footer and help text into a small A2UI surface, because +the sample clients render surfaces only. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass +import json +import logging +import os +import time +from typing import Any + +from a2a.types import Part +import httpx + +from a2ui.a2a import create_a2ui_part +from a2ui.core import A2uiError +from a2ui.core.basic_catalog import BasicCatalog +from a2ui.inference_formats.decision import ( + DecisionBackend, + DecisionBackendType, + DecisionBlock, + DecisionFormat, + DecisionFormatFactory, + DecisionRecord, + DecisionSynthesizer, + DecisionWireFormat, + DeterministicMockBackend, + JevHttpBackend, + LocalCrossEncoderBackend, + QuestionKind, + StepZeroLogprobBackend, + SynthesisConfig, + SynthesisOutput, + create_decision_backend, +) +from a2ui.inference_formats.direct_json import DirectJsonFormatFactory +from a2ui.inference_formats.express import ExpressFormatFactory +from a2ui.parser import A2uiPart +from a2ui.parser.messages import to_message_dicts +from a2ui.processor import A2uiGenerator, A2uiRequestProcessor, CatalogConfig +from a2ui.utils import to_version_number +from modes import ( + LlmCaller, + LlmTurn, + RenderMode, + RenderResult, + TurnMetrics, + format_decision_ms, +) + +logger = logging.getLogger(__name__) + +_BACKEND_NAMES: dict[type, DecisionBackendType] = { + DeterministicMockBackend: DecisionBackendType.MOCK, + LocalCrossEncoderBackend: DecisionBackendType.LOCAL, + JevHttpBackend: DecisionBackendType.JEV, + StepZeroLogprobBackend: DecisionBackendType.STEP_ZERO, +} +_STAGE2_RETRIES = 1 + + +def backend_display_name(backend: DecisionBackend) -> str: + """The short name of a bundled backend (`mock`, `local`, `jev`, `gev`, ...) or its class name.""" + if isinstance(backend, JevHttpBackend): + url_lower = backend.endpoint_url.lower() + is_local_gev = backend.model.startswith("vertex/") or ( + ("127.0.0.1" in url_lower or "localhost" in url_lower) + and url_lower.rstrip("/").endswith("/v1/systemone") + ) + label = "gev" if is_local_gev else "jev" + if backend.model and backend.model != "default": + return f"{label} ({backend.model})" + return label + for cls, kind in _BACKEND_NAMES.items(): + if isinstance(backend, cls): + return kind.value + return type(backend).__name__ + + +def build_named_backend(name: str) -> DecisionBackend: + """Constructs a named playground decision backend (`jev`, `gev`, `local`, `mock`).""" + clean = name.strip().lower() + if clean == "mock": + return DeterministicMockBackend() + if clean in ("local", "onnx"): + return create_decision_backend("local") + if clean == "gev": + host = os.environ.get("GEV_HOST", "127.0.0.1") + port = os.environ.get("GEV_PORT", "8790") + url = os.environ.get("GEV_URL") or f"http://{host}:{port}/v1/systemone" + model = os.environ.get("GEV_MODEL") or "vertex/decision-gemma" + return JevHttpBackend( + url, + wire_format=DecisionWireFormat.SYSTEMONE, + model=model, + ) + if clean in ("jev", "systemone"): + key = ( + os.environ.get("JEV_API_KEY") + or os.environ.get("TYPESAFE_API_KEY") + or os.environ.get("A2UI_DECISION_AUTH") + or os.environ.get("A2UI_DECISION_TOKEN") + ) + jev_url = os.environ.get("JEV_URL") + if not key and not jev_url: + raise ValueError("JEV_API_KEY is not set in the environment or ~/.env.") + return create_decision_backend( + "systemone", + endpoint_url=jev_url, + model=os.environ.get("JEV_MODEL"), + auth=key, + ) + raise ValueError( + f"Unknown decision backend `{name}`; choose jev, gev, local, or mock." + ) + + +def stage2_user_text(block: DecisionBlock, surface_id: str) -> str: + """The user message for an `express` or `direct` render of `block`.""" + payload = json.dumps(block.payload, indent=2) + return ( + "Render this interface using the format rules in your instructions.\n" + f"Intent: {block.intent}\n" + f'Use surface id "{surface_id}".\n' + "Bind only to the JSON pointers in this data model; do not invent other" + " data:\n" + f"```json\n{payload}\n```" + ) + + +def _record_line(record: DecisionRecord) -> str: + """Formats one planner `DecisionRecord` as a single status line.""" + question = record.question + if record.answer is None: + winner = "unanswered" + elif question.kind is QuestionKind.BOOLEAN: + winner = f"yes p={record.answer.yes:.2f}" + else: + option, prob = record.answer.top() + winner = f"{option} p={prob:.2f}" + pieces = [f"`{question.id}`", winner] + if record.threshold is not None: + pieces.append(f"threshold {record.threshold:.2f}") + if record.outcome: + pieces.append(record.outcome) + return " · ".join(pieces) + + +def _output_summary_line(output: SynthesisOutput) -> str: + """Formats a summary header line for `/trace` showing path and decision latency.""" + conf = f"p={output.confidence:.2f}" + stage = output.stage.value + if stage == "template_select": + tpl = f" `{output.selected_template_id}`" if output.selected_template_id else "" + path = f"**Path**: templates · template{tpl} ({conf})" + elif stage == "archetype" and output.layout_plan is not None: + plan = output.layout_plan + blocks = ", ".join(f"`{b.block_id}:{b.pattern}`" for b in plan.blocks) + n = len(plan.blocks) + block_desc = ( + f"{n} block{'' if n == 1 else 's'}: {blocks}" if blocks else "0 blocks" + ) + path = ( + f"**Path**: decision model · archetype `{plan.archetype}`" + f" ({conf}, {block_desc})" + ) + elif stage == "fast_1pass_leaf": + root = (output.component_tree_spec or {}).get("root_component") + comp = f" `{root}`" if root else "" + path = f"**Path**: decision model · 1-pass leaf{comp} ({conf})" + elif stage == "container_2pass": + root = (output.component_tree_spec or {}).get("root_component") + comp = f" `{root}`" if root else "" + path = f"**Path**: decision model · 2-pass container{comp} ({conf})" + else: + source = ( + str(output.fallback_source) + if output.fallback_source is not None + else "abstained" + ) + path = f"**Path**: fallback (`{source}`) · decision model abstained ({conf})" + calls = output.decision_calls + call_label = f"{calls} call{'' if calls == 1 else 's'}" + timing = ( + f"**Decision time**: {format_decision_ms(output.decision_latency_ms)}" + f" ({call_label})" + ) + return f"{path} · {timing}" + + +def trace_lines(output: SynthesisOutput) -> tuple[str, ...]: + """Summary line of the path and decision timing followed by each planner question.""" + return (_output_summary_line(output),) + tuple( + _record_line(record) for record in output.trace + ) + + +def _express_literal(text: str) -> str: + """Quotes `text` as an Express string literal (non-ASCII kept as is).""" + return json.dumps(text, ensure_ascii=False) + + +@dataclass +class _Stage2Attempt: + """One stage-2 model call and its validated result.""" + + turn: LlmTurn + parts: list[Part] + error: str | None + + +class Renderers: + """Renders decision blocks through every mode for a set of protocol versions.""" + + def __init__( + self, + *, + versions: Sequence[str], + backend: DecisionBackend, + config: SynthesisConfig | None = None, + ) -> None: + self._versions = tuple(versions) + self._config = config + self._raw_backend = backend + self._decision_factory = DecisionFormatFactory( + backend=backend, config=config, fallback_card=True + ) + self._processors: dict[tuple[RenderMode, str], A2uiRequestProcessor] = {} + for version in self._versions: + key = to_version_number(version) + self._processors[(RenderMode.DECISION, key)] = self._build_processor( + version, self._decision_factory + ) + self._processors[(RenderMode.EXPRESS, key)] = self._build_processor( + version, ExpressFormatFactory() + ) + self._processors[(RenderMode.DIRECT, key)] = self._build_processor( + version, DirectJsonFormatFactory() + ) + + def set_backend(self, backend: DecisionBackend) -> None: + """Replaces the active decision backend across all configured protocol versions.""" + self._raw_backend = backend + self._decision_factory = DecisionFormatFactory( + backend=backend, config=self._config, fallback_card=True + ) + for version in self._versions: + key = to_version_number(version) + self._processors[(RenderMode.DECISION, key)] = self._build_processor( + version, self._decision_factory + ) + + @staticmethod + def _build_processor(version: str, factory: Any) -> A2uiRequestProcessor: + generator = A2uiGenerator( + [CatalogConfig(BasicCatalog(version))], inference_format_factory=factory + ) + return generator.create_processor({ + f"v{to_version_number(version)}": { + "supportedCatalogIds": [ + c.transformed_catalog.catalog_id for c in generator.catalogs + ] + } + }) + + @property + def backend_name(self) -> str: + """The decision backend's short name, from the backend passed in.""" + return backend_display_name(self._raw_backend) + + @property + def versions(self) -> tuple[str, ...]: + """Protocol version numbers this instance renders for.""" + return tuple(sorted({v for _, v in self._processors})) + + def processor(self, mode: RenderMode, version: str) -> A2uiRequestProcessor: + """The processor for `mode` and `version`. + + Raises: + KeyError: If `version` was not configured. + """ + return self._processors[(mode, to_version_number(version))] + + def prompt_for(self, mode: RenderMode, version: str) -> str: + """The stage-2 system instruction for `mode` (the format's own prompt).""" + return self.processor(mode, version).prompt_snippet + + def _synthesizer(self, version: str) -> DecisionSynthesizer: + fmt = self.processor(RenderMode.DECISION, version).format + if not isinstance(fmt, DecisionFormat): + raise TypeError(f"Expected a DecisionFormat, got {type(fmt).__name__}.") + return fmt.synthesizer + + async def render_decision( + self, block: DecisionBlock, *, surface_id: str, version: str + ) -> RenderResult: + """Compiles `block` with the decision synthesizer; no model call.""" + started = time.perf_counter() + try: + output = await self._synthesizer(version).synthesize( + block.intent, + block.payload, + surface_id=surface_id, + mutable_paths=block.mutable_paths, + layout=block.layout or None, + ) + except (A2uiError, ValueError, httpx.HTTPError) as exc: + logger.warning("Decision render failed: %s", exc) + return RenderResult( + metrics=self._decision_metrics(None, started), error=str(exc) + ) + parts = [ + create_a2ui_part(message, version=version) + for message in to_message_dicts(output.messages) + ] + return RenderResult( + parts=parts, + metrics=self._decision_metrics(output, started), + trace_lines=trace_lines(output), + decision_answers=output.decision_answers, + output=output, + error=None if parts else "The decision model produced no surface.", + ) + + async def render_tool_result( + self, + intent: str, + payload: dict[str, Any], + *, + surface_id: str, + version: str = "1.0", + mutable_paths: Sequence[str] = (), + ) -> RenderResult: + """Renders tool data directly via decision synthesizer with no UI-writing model call.""" + started = time.perf_counter() + try: + output = await self._synthesizer(version).synthesize( + intent, + payload, + surface_id=surface_id, + mutable_paths=mutable_paths, + ) + except (A2uiError, ValueError, httpx.HTTPError) as exc: + logger.warning("Tool render failed: %s", exc) + return RenderResult( + metrics=self._decision_metrics(None, started, mode=RenderMode.TOOL), + error=str(exc), + ) + parts = [ + create_a2ui_part(message, version=version) + for message in to_message_dicts(output.messages) + ] + return RenderResult( + parts=parts, + metrics=self._decision_metrics(output, started, mode=RenderMode.TOOL), + trace_lines=trace_lines(output), + decision_answers=output.decision_answers, + output=output, + error=None if parts else "The decision model produced no surface.", + ) + + async def remix( + self, + intent: str, + payload: Mapping[str, Any] | Sequence[Any] | str, + answers: Sequence[Any], + *, + surface_id: str, + version: str = "1.0", + mutable_paths: Sequence[str] = (), + title: str | None = None, + summary: str | None = None, + seed: int | None = None, + ) -> RenderResult: + """Re-plans a previous decision surface using variety sampling with 0 backend calls.""" + started = time.perf_counter() + try: + output = await self._synthesizer(version).remix( + intent, + payload, + answers, + surface_id=surface_id, + mutable_paths=mutable_paths, + title=title, + summary=summary, + seed=seed, + ) + except (A2uiError, ValueError, httpx.HTTPError) as exc: + logger.warning("Remix failed: %s", exc) + return RenderResult( + metrics=TurnMetrics( + mode=RenderMode.DECISION, + backend="remix", + llm_calls=0, + decision_calls=0, + decision_latency_ms=0.0, + latency_ms=(time.perf_counter() - started) * 1000.0, + remix_seed=seed, + ), + error=str(exc), + ) + parts = [ + create_a2ui_part(message, version=version) + for message in to_message_dicts(output.messages) + ] + metrics = TurnMetrics( + mode=RenderMode.DECISION, + backend="remix", + llm_calls=0, + decision_calls=0, + decision_latency_ms=0.0, + latency_ms=(time.perf_counter() - started) * 1000.0, + archetype=output.layout_plan.archetype if output.layout_plan else None, + block_count=( + len(output.layout_plan.blocks) if output.layout_plan else None + ), + confidence=output.confidence, + stage=output.stage.value, + remix_seed=seed, + ) + return RenderResult( + parts=parts, + metrics=metrics, + trace_lines=trace_lines(output), + decision_answers=output.decision_answers, + output=output, + error=None if parts else "Remix produced no surface.", + ) + + def _decision_metrics( + self, + output: SynthesisOutput | None, + started: float, + mode: RenderMode = RenderMode.DECISION, + ) -> TurnMetrics: + elapsed_ms = (time.perf_counter() - started) * 1000.0 + plan = output.layout_plan if output is not None else None + tree = output.component_tree_spec if output is not None else None + root_comp = ( + str(tree["root_component"]) + if isinstance(tree, dict) and tree.get("root_component") + else None + ) + decision_ms = ( + output.decision_latency_ms + if output is not None and output.decision_latency_ms > 0.0 + else elapsed_ms + ) + return TurnMetrics( + mode=mode, + backend=self.backend_name, + llm_calls=0, + latency_ms=elapsed_ms, + archetype=plan.archetype if plan is not None else None, + confidence=output.confidence if output is not None else None, + block_count=len(plan.blocks) if plan is not None else None, + fallback=( + str(output.fallback_source) + if output is not None and output.fallback_source is not None + else None + ), + stage=output.stage.value if output is not None else None, + decision_latency_ms=decision_ms, + decision_calls=output.decision_calls if output is not None else None, + template_id=(output.selected_template_id if output is not None else None), + root_component=root_comp, + ) + + async def _call_and_parse( + self, + mode: RenderMode, + version: str, + llm: LlmCaller, + user_text: str, + ) -> _Stage2Attempt: + """Makes one stage-2 call and validates its reply through the processor.""" + processor = self.processor(mode, version) + turn = await llm( + instruction_key=f"{mode}:{to_version_number(version)}", + instruction=processor.prompt_snippet, + user_text=user_text, + session_id=None, + ) + try: + response_parts = processor.parse_response(turn.text) + except (A2uiError, ValueError, json.JSONDecodeError) as exc: + return _Stage2Attempt(turn=turn, parts=[], error=str(exc)) + parts = [ + create_a2ui_part(message, version=version) + for part in response_parts + if isinstance(part, A2uiPart) + for message in to_message_dicts(part.a2ui) + ] + error = None if parts else "The reply contained no A2UI block." + return _Stage2Attempt(turn=turn, parts=parts, error=error) + + async def render_with_llm( + self, + mode: RenderMode, + block: DecisionBlock, + *, + surface_id: str, + version: str, + llm: LlmCaller, + ) -> RenderResult: + """Asks the model for `mode` source for `block`, retrying once on invalid output.""" + if mode is RenderMode.DECISION: + raise ValueError("render_with_llm renders express or direct, not decision.") + user_text = stage2_user_text(block, surface_id) + attempts: list[_Stage2Attempt] = [] + for _ in range(_STAGE2_RETRIES + 1): + attempt = await self._call_and_parse(mode, version, llm, user_text) + attempts.append(attempt) + if attempt.error is None: + break + user_text = ( + f"{stage2_user_text(block, surface_id)}\n\nYour previous reply was" + f" invalid: {attempt.error} Reply again following the format rules" + " exactly." + ) + last = attempts[-1] + metrics = TurnMetrics( + mode=mode, + backend="llm", + llm_calls=len(attempts), + latency_ms=sum(a.turn.latency_ms for a in attempts), + prompt_tokens=sum(a.turn.prompt_tokens for a in attempts), + output_tokens=sum(a.turn.output_tokens for a in attempts), + fallback="validation_retry" if len(attempts) > 1 else None, + ) + return RenderResult(parts=last.parts, metrics=metrics, error=last.error) + + def status_surface( + self, lines: Sequence[str], *, surface_id: str, version: str + ) -> list[Part]: + """Renders `lines` as a small A2UI surface (a column of Markdown text).""" + texts = ", ".join(f"Text({_express_literal(line)})" for line in lines) or ( + 'Text("")' + ) + source = f'surface("{surface_id}")\nroot = Column([{texts}])' + parser = self.processor(RenderMode.EXPRESS, version).parser + messages = parser.compile(source) + return [ + create_a2ui_part(message, version=version) + for message in to_message_dicts(messages) + ] + + async def aclose(self) -> None: + """Closes the shared decision backend.""" + await self._decision_factory.aclose() diff --git a/samples/agent/adk/format_playground/run.sh b/samples/agent/adk/format_playground/run.sh new file mode 100755 index 0000000000..2dcba353ac --- /dev/null +++ b/samples/agent/adk/format_playground/run.sh @@ -0,0 +1,260 @@ +#!/usr/bin/env bash +# 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. + +# Starts the A2UI format playground agent in the requested mode/backend preset. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +cd "${SCRIPT_DIR}" + +if [[ -f "${HOME}/.env" ]]; then + set -a + # shellcheck disable=SC1091 + source "${HOME}/.env" + set +a +fi + +if [[ -f ".env" ]]; then + set -a + # shellcheck disable=SC1091 + source ".env" + set +a +fi + +if [[ -x "${HOME}/.local/bin/uv" ]]; then + UV_BIN="${HOME}/.local/bin/uv" +else + UV_BIN="uv" +fi + +usage() { + cat <<'EOF' +Usage: ./run.sh [PRESET] [OPTIONS...] + +Starts the A2UI Format Playground agent with a preset decision backend and +initial render mode. Extra flags (such as --port or --host) are forwarded to +the server entrypoint. + +Presets: + local (default) In-process ONNX cross-encoder in decision mode. + Installs the `local` extra automatically if not yet synced. + mock Deterministic offline mock backend in decision mode. + jev Remote TypeSafe Jev (/v1/systemone) in decision mode. + Uses A2UI_DECISION_AUTH or JEV_API_KEY. + gev Local Gev server (/v1/systemone, default model: vertex/decision-gemma) + in decision mode. Starts the local Gev server on port 8790 if not + already running. + express Starts in `express` render mode (decision backend defaults to mock). + direct Starts in `direct` render mode (decision backend defaults to mock). + tool Starts in `tool` render mode (decision backend defaults to mock). + +Environment variables: + GEMINI_API_KEY Gemini API key (or set GOOGLE_GENAI_USE_VERTEXAI=TRUE) + MODEL_NAME Stage-1/Stage-2 Gemini model (default: gemini-3.6-flash) + JEV_API_KEY API key for the `jev` preset (or set A2UI_DECISION_AUTH) + GEV_PORT Local Gev server port for the `gev` preset (default: 8790) + GEV_SERVER_BIN Path to prebuilt Gev server binary (auto-detected if unset) + A2UI_DECISION_URL Override the HTTP endpoint URL for `jev` / `gev` + A2UI_DECISION_MODEL Override the decision model ID (default for `gev`: vertex/decision-gemma) + +Examples: + ./run.sh local + ./run.sh mock + JEV_API_KEY=... ./run.sh jev + ./run.sh gev + ./run.sh express --port 10011 +EOF +} + +PRESET="local" +if [[ $# -gt 0 ]]; then + case "$1" in + -h|--help|help) + usage + exit 0 + ;; + --*) + # Only options were passed; keep the default preset. + ;; + *) + PRESET="$1" + shift + ;; + esac +fi + +RENDER_MODE="decision" +GEV_SERVER_PID="" + +cleanup_gev_server() { + if [[ -n "${GEV_SERVER_PID}" ]] && kill -0 "${GEV_SERVER_PID}" 2>/dev/null; then + echo "Stopping local Gev server (pid ${GEV_SERVER_PID})..." + kill -INT "${GEV_SERVER_PID}" 2>/dev/null || true + wait "${GEV_SERVER_PID}" 2>/dev/null || true + fi +} + +find_or_build_gev_server() { + if [[ -n "${GEV_SERVER_BIN:-}" && -x "${GEV_SERVER_BIN}" ]]; then + echo "${GEV_SERVER_BIN}" + return 0 + fi + + local citc_root="/google/src/cloud/${USER}" + if [[ -d "${citc_root}" ]]; then + local ws bin + while IFS= read -r ws; do + [[ -z "${ws}" ]] && continue + bin="${citc_root}/${ws}/google3/blaze-bin/prototypes/projects/gev/server" + if [[ -x "${bin}" ]]; then + echo "${bin}" + return 0 + fi + done < <(ls -t "${citc_root}" 2>/dev/null | head -n 25) + + local build_ws="" + while IFS= read -r ws; do + [[ -z "${ws}" ]] && continue + if [[ -f "${citc_root}/${ws}/google3/prototypes/projects/gev/BUILD" ]]; then + build_ws="${citc_root}/${ws}/google3" + break + fi + done < <(ls -t "${citc_root}" 2>/dev/null | head -n 25) + + if [[ -n "${build_ws}" ]]; then + echo "Building //prototypes/projects/gev:server in ${build_ws}..." >&2 + local blaze_cmd="blaze" + if [[ -x "/google/bin/releases/arca9-local-blaze-cli/blaze-for-agents" ]]; then + blaze_cmd="/google/bin/releases/arca9-local-blaze-cli/blaze-for-agents" + fi + (cd "${build_ws}" && "${blaze_cmd}" build //prototypes/projects/gev:server >&2) + bin="${build_ws}/blaze-bin/prototypes/projects/gev/server" + if [[ -x "${bin}" ]]; then + echo "${bin}" + return 0 + fi + fi + fi + + return 1 +} + +start_gev_server_if_needed() { + local host="${GEV_HOST:-127.0.0.1}" + local port="${GEV_PORT:-8790}" + local model="$1" + local healthz_url="$2" + + if curl -fsS --max-time 1 "${healthz_url}" >/dev/null 2>&1; then + echo "Using running Gev server at ${healthz_url%/healthz}/v1/systemone (model: ${model})" + return 0 + fi + + local gev_bin + if ! gev_bin="$(find_or_build_gev_server)"; then + echo "Error: Could not find or build //prototypes/projects/gev:server." >&2 + echo "Set GEV_SERVER_BIN or start the server manually on port ${port}." >&2 + exit 1 + fi + + echo "Starting local Gev server (${gev_bin}) on ${host}:${port} (model: ${model})..." + "${gev_bin}" --host="${host}" --port="${port}" --model="${model}" & + GEV_SERVER_PID="$!" + trap cleanup_gev_server EXIT INT TERM + + local i + for ((i = 0; i < 120; i++)); do + if ! kill -0 "${GEV_SERVER_PID}" 2>/dev/null; then + echo "Error: Local Gev server exited prematurely." >&2 + exit 1 + fi + if curl -fsS --max-time 1 "${healthz_url}" >/dev/null 2>&1; then + echo "Local Gev server ready at http://${host}:${port}/v1/systemone" + return 0 + fi + sleep 0.25 + done + + echo "Error: Timed out waiting for local Gev server at ${healthz_url}." >&2 + exit 1 +} + +case "${PRESET}" in + local|onnx) + if ! "${UV_BIN}" run --no-sync python -c "import onnxruntime, tokenizers" >/dev/null 2>&1; then + echo "Installing local ONNX decision dependencies..." + "${UV_BIN}" pip install "onnxruntime>=1.16.0" "tokenizers>=0.15.0" "huggingface-hub>=0.20.0" "numpy>=1.24.0" + fi + export A2UI_DECISION_BACKEND="local" + RENDER_MODE="decision" + ;; + mock) + export A2UI_DECISION_BACKEND="mock" + RENDER_MODE="decision" + ;; + jev|systemone) + export A2UI_DECISION_BACKEND="systemone" + export A2UI_DECISION_AUTH="${A2UI_DECISION_AUTH:-${JEV_API_KEY:-${TYPESAFE_API_KEY:-}}}" + if [[ -z "${A2UI_DECISION_AUTH}" && -z "${A2UI_DECISION_TOKEN:-}" ]]; then + echo "Error: 'jev' preset requires JEV_API_KEY or A2UI_DECISION_AUTH to be set (use './runit gev' for the local Gev server)." >&2 + exit 1 + fi + if [[ "${A2UI_DECISION_AUTH}" == vcp_* ]]; then + export A2UI_DECISION_URL="${A2UI_DECISION_URL:-https://ai-gateway.vercel.sh/typesafe/v1/systemone}" + export A2UI_DECISION_MODEL="${A2UI_DECISION_MODEL:-${JEV_MODEL:-jev}}" + else + export A2UI_DECISION_URL="${A2UI_DECISION_URL:-https://api.typesafe.ai/v1/systemone}" + export A2UI_DECISION_MODEL="${A2UI_DECISION_MODEL:-${JEV_MODEL:-jev-latest}}" + fi + RENDER_MODE="decision" + ;; + gev) + GEV_HOST="${GEV_HOST:-127.0.0.1}" + GEV_PORT="${GEV_PORT:-8790}" + export A2UI_DECISION_BACKEND="systemone" + export A2UI_DECISION_URL="${A2UI_DECISION_URL:-http://${GEV_HOST}:${GEV_PORT}/v1/systemone}" + export A2UI_DECISION_MODEL="${A2UI_DECISION_MODEL:-${JEV_MODEL:-vertex/decision-gemma}}" + GEV_HEALTHZ_URL="${A2UI_DECISION_URL%/v1/systemone}/healthz" + start_gev_server_if_needed "${A2UI_DECISION_MODEL}" "${GEV_HEALTHZ_URL}" + RENDER_MODE="decision" + ;; + express) + export A2UI_DECISION_BACKEND="${A2UI_DECISION_BACKEND:-mock}" + RENDER_MODE="express" + ;; + direct) + export A2UI_DECISION_BACKEND="${A2UI_DECISION_BACKEND:-mock}" + RENDER_MODE="direct" + ;; + tool) + export A2UI_DECISION_BACKEND="${A2UI_DECISION_BACKEND:-mock}" + RENDER_MODE="tool" + ;; + decision) + RENDER_MODE="decision" + ;; + *) + echo "Error: Unknown preset '${PRESET}'. Choose from: local, mock, jev, gev, express, direct, tool." >&2 + usage >&2 + exit 1 + ;; +esac + +if [[ -n "${GEV_SERVER_PID}" ]]; then + "${UV_BIN}" run --no-sync . --mode "${RENDER_MODE}" "$@" +else + exec "${UV_BIN}" run --no-sync . --mode "${RENDER_MODE}" "$@" +fi diff --git a/samples/agent/adk/format_playground/stage1.py b/samples/agent/adk/format_playground/stage1.py new file mode 100644 index 0000000000..e5e836781b --- /dev/null +++ b/samples/agent/adk/format_playground/stage1.py @@ -0,0 +1,151 @@ +# 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. + +"""Stage 1 of the playground: turn a chat request into one decision block. + +The model is asked for exactly one `{"intent", "payload", "layout"}` +block using the same contract the decision inference format publishes. Reading +the block back reuses the SDK's own lexer and tolerant JSON parser so the +playground accepts exactly what `DecisionParser` would accept. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +import json +import logging +from typing import Any + +from a2ui.constants import A2UI_INFERENCE_CLOSE_TAG, A2UI_INFERENCE_OPEN_TAG +from a2ui.inference_formats.decision import ( + ArchetypeGrammar, + DecisionBlock, + decision_rules, +) +from a2ui.parser import BlockLexer, RawA2uiPart, parse_and_fix + +logger = logging.getLogger(__name__) + +TOOL_MODE_INSTRUCTION = """# Format playground: Tool Mode + +You are an assistant with access to backend data and configuration tools. +When the person asks for information or an action that a tool provides, invoke that tool. +Never describe or emit user interface code yourself: the decision layout model will render the tool result into a user interface. +When no tool fits the request, reply with a single concise sentence explaining that no tool is available. +""" + +STAGE1_PREAMBLE = """# Format playground + +You are the first stage of a UI playground. The person describes an interface +they want to see; you describe what to show and provide the data. A local +decision model (or a second model call) turns your description into the +actual components, so you never write components yourself. + +Rules: + +- Reply with exactly one decision block and nothing else: no prose before or + after it. +- Invent realistic, specific data: real-looking names, prices, dates, and + 3 to 6 items for any list. Keep payload keys camelCase and values JSON + primitives, objects, and arrays. +- For forms, inputs, or settings, put the field values themselves under each + field key (for example `"email": "alex.smith@example.com"`, `"password": ""`, + `"rememberMe": false`), put button labels in an `"actions"` array (for + example `"actions": ["Sign In"]`), and list the editable pointers in + `"mutablePaths"` (for example `["/email", "/password", "/rememberMe"]`). Do + not emit `*Label`, `*Placeholder`, or `*ButtonText` keys. +- When the message supplies JSON, use it verbatim as `payload` and write only + the `intent`. +- When the message reports a UI action (a button press, a form submission), + reply with a block that reflects the result: a confirmation, the updated + record, or the next step. +- Set `layout` only when the person names a layout role explicitly; otherwise + leave it out. +- The `intent` is one sentence naming what the data is and how the person + should see or interact with it.""" + +_JSON_OPENERS = ("{", "[") + +UI_ACTION_PREFIX = "User interacted with the UI:" +"""Prefix the executor puts on UI action reports; such text is never JSON-pinned.""" + + +def stage1_instruction(grammar: ArchetypeGrammar) -> str: + """The stage-1 system instruction: the preamble plus the decision block contract.""" + return f"{STAGE1_PREAMBLE}\n\n{decision_rules(grammar)}" + + +def extract_pasted_json(query: str) -> Mapping[str, Any] | Sequence[Any] | None: + """Returns the first JSON object or array embedded in `query`, or None. + + Scans from each `{` or `[` with `JSONDecoder.raw_decode`, so braces inside + prose that are not JSON are ignored. + """ + decoder = json.JSONDecoder() + for index, char in enumerate(query): + if char not in _JSON_OPENERS: + continue + try: + value, _ = decoder.raw_decode(query, index) + except json.JSONDecodeError: + continue + if isinstance(value, (Mapping, list)): + return value + return None + + +def stage1_user_text(query: str) -> str: + """The stage-1 user message, with pasted JSON pinned as the payload. + + UI action reports carry their context as JSON, which must not be mistaken + for a payload, so text starting with `UI_ACTION_PREFIX` is passed through. + """ + if query.startswith(UI_ACTION_PREFIX): + return query + pasted = extract_pasted_json(query) + if pasted is None: + return query + encoded = json.dumps(pasted, indent=2) + return f"{query}\n\nUse this JSON verbatim as the payload:\n```json\n{encoded}\n```" + + +def extract_block(text: str) -> DecisionBlock | None: + """Reads the first decision block out of a stage-1 reply. + + Returns None when the reply has no block, the block is not JSON the SDK's + tolerant parser can fix, or `DecisionBlock.from_mapping` rejects it. + """ + lexer = BlockLexer( + open_tag=A2UI_INFERENCE_OPEN_TAG, + close_tag=A2UI_INFERENCE_CLOSE_TAG, + string_delimiters={'"'}, + ) + blocks = lexer.tokenize(text) + raw_parts = [b.part for b in blocks if isinstance(b.part, RawA2uiPart)] + if not raw_parts: + return None + try: + parsed: Any = parse_and_fix(raw_parts[0].a2ui_raw) + except Exception as exc: # parse_and_fix raises several JSON error types + logger.warning("Stage 1 block is not valid JSON: %s", exc) + return None + item = parsed[0] if isinstance(parsed, list) and parsed else parsed + if not isinstance(item, Mapping): + logger.warning("Stage 1 block is not a JSON object: %r", type(item).__name__) + return None + try: + return DecisionBlock.from_mapping(item) + except (TypeError, ValueError) as exc: + logger.warning("Stage 1 block rejected: %s", exc) + return None diff --git a/samples/agent/adk/format_playground/tests/conftest.py b/samples/agent/adk/format_playground/tests/conftest.py new file mode 100644 index 0000000000..0e7b6808ee --- /dev/null +++ b/samples/agent/adk/format_playground/tests/conftest.py @@ -0,0 +1,50 @@ +# 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. + +"""Test fixtures for the format playground. + +The sample's modules are flat top-level names (`agent`, `modes`, ...), as in +the other ADK samples, so the sample directory is put on `sys.path` here. +""" + +from __future__ import annotations + +import os +from pathlib import Path +import sys + +import pytest + +_TESTS_DIR = Path(__file__).resolve().parent +_SAMPLE_DIR = _TESTS_DIR.parent +for _dir in (_TESTS_DIR, _SAMPLE_DIR): + _dir_str = str(_dir) + if _dir_str in sys.path: + sys.path.remove(_dir_str) + sys.path.insert(0, _dir_str) +for _mod in ("agent", "agent_executor"): + _loaded = sys.modules.get(_mod) + _file = getattr(_loaded, "__file__", None) if _loaded else None + if _file and not str(Path(_file).resolve()).startswith(str(_SAMPLE_DIR)): + sys.modules.pop(_mod, None) + +os.environ.setdefault("A2UI_DECISION_BACKEND", "mock") +os.environ.setdefault("GEMINI_API_KEY", "test-key") + +from fakes import FakeLlmCaller # noqa: E402 (needs the sys.path change above) + + +@pytest.fixture +def scripted_llm() -> FakeLlmCaller: + return FakeLlmCaller() diff --git a/samples/agent/adk/format_playground/tests/fakes.py b/samples/agent/adk/format_playground/tests/fakes.py new file mode 100644 index 0000000000..145b74c414 --- /dev/null +++ b/samples/agent/adk/format_playground/tests/fakes.py @@ -0,0 +1,151 @@ +# 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. + +"""Scripted test doubles for the format playground.""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass, field +from typing import Any + +from a2ui.inference_formats.decision import DeterministicMockBackend +from modes import LlmToolTurn, LlmTurn + + +@dataclass +class FakeLlmCaller: + """Scripted `LlmCaller`: replies are popped per `instruction_key`. + + A key with no scripted replies falls back to the `default` reply so a test + can script only the stage it cares about. + """ + + replies: dict[str, list[str]] = field(default_factory=dict) + default: str = "" + tool_replies: dict[str, list[LlmToolTurn]] = field(default_factory=dict) + default_tool_turn: LlmToolTurn = field( + default_factory=lambda: LlmToolTurn(text="No tool found.") + ) + calls: list[dict[str, object]] = field(default_factory=list) + + def script(self, instruction_key: str, *texts: str) -> None: + self.replies.setdefault(instruction_key, []).extend(texts) + + def script_tool(self, instruction_key: str, *turns: LlmToolTurn) -> None: + self.tool_replies.setdefault(instruction_key, []).extend(turns) + + async def __call__( + self, + *, + instruction_key: str, + instruction: str, + user_text: str, + session_id: str | None, + ) -> LlmTurn: + self.calls.append({ + "instruction_key": instruction_key, + "instruction": instruction, + "user_text": user_text, + "session_id": session_id, + }) + queue = self.replies.get(instruction_key) + text = queue.pop(0) if queue else self.default + return LlmTurn(text=text, prompt_tokens=100, output_tokens=40, latency_ms=5.0) + + async def call_with_tools( + self, + *, + instruction_key: str, + instruction: str, + user_text: str, + session_id: str | None, + tools: Sequence[Any], + ) -> LlmToolTurn: + self.calls.append({ + "instruction_key": instruction_key, + "instruction": instruction, + "user_text": user_text, + "session_id": session_id, + "tools": tools, + }) + queue = self.tool_replies.get(instruction_key) + if queue: + return queue.pop(0) + return self.default_tool_turn + + def calls_for(self, instruction_key: str) -> list[dict[str, object]]: + return [c for c in self.calls if c["instruction_key"] == instruction_key] + + +HOST_ANSWERS: dict[str, Any] = { + "family": ("monitor", 0.90), + "stakes": 1.0, + "urgency": 1.4, + "archetype:monitor": ("dashboard", 0.85), + "gate:banner": 0.80, + "gate:headline": 0.90, + "gate:facts": 0.80, + "anatomy:headline.deltas": 0.85, + "salience:/cpu": 2.8, + "salience:/status": 2.1, + "salience:/uptimeHours": 1.2, + "salience:/host": 0.4, + "instance:banner.tone:/status": ("warning", 0.90), + "instance:headline.news:/cpu": ("bad", 0.85), + "instance:headline.state_tone:/status": ("warning", 0.80), +} + +RESORT_ANSWERS: dict[str, Any] = { + "family": ("browse", 0.92), + "stakes": 0.5, + "urgency": 0.3, + "archetype:browse": ("feed", 0.88), + "gate:collection": 0.95, + "gate:filters": 0.20, + "salience:/resorts": 2.5, +} + +TRANSFER_ANSWERS: dict[str, Any] = { + "family": ("act", 0.85), + "stakes": 2.1, + "urgency": 0.6, + "archetype:act": ("confirm", 0.90), + "gate:banner": 0.20, + "gate:prose": 0.45, + "gate:facts": 0.85, + "gate:actions": 0.90, + "instance:actions.primary:/actions": ("Confirm Transfer", 0.90), + "salience:/amount": 2.9, + "salience:/recipient": 2.6, + "salience:/fee": 1.9, +} + +SETTINGS_ANSWERS: dict[str, Any] = { + "family": ("input", 0.92), + "stakes": 1.0, + "urgency": 0.3, + "archetype:input": ("form", 0.88), + "gate:form": 0.98, + "gate:actions": 0.95, + "instance:actions.primary:/actions": ("Save", 0.98), + "salience:/volume": 2.5, + "salience:/subtitles": 2.1, + "salience:/theme": 1.8, +} + + +def scripted_backend(answers: dict[str, Any]) -> DeterministicMockBackend: + """Builds a DeterministicMockBackend with scripted question answers.""" + return DeterministicMockBackend(scripted_answers=answers) diff --git a/samples/agent/adk/format_playground/tests/test_agent_stream.py b/samples/agent/adk/format_playground/tests/test_agent_stream.py new file mode 100644 index 0000000000..43e24d12b1 --- /dev/null +++ b/samples/agent/adk/format_playground/tests/test_agent_stream.py @@ -0,0 +1,342 @@ +# 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. + +"""End-to-end tests for `PlaygroundAgent.stream` with a scripted model.""" + +from __future__ import annotations + +import json +from typing import Any + +from a2a.types import DataPart, Part, TextPart +import pytest + +from a2ui.inference_formats.decision import DeterministicMockBackend +from agent import PlaygroundAgent +from fakes import FakeLlmCaller +from modes import LlmToolTurn, RenderMode +from renderers import Renderers +from stage1 import UI_ACTION_PREFIX +from test_renderers import EXPRESS_BAD, EXPRESS_OK, RESORT_PAYLOAD, direct_json_reply + +pytestmark = pytest.mark.asyncio + +STAGE1_BLOCK = ( + "" + + json.dumps({"intent": "Show the resort overview", "payload": RESORT_PAYLOAD}) + + "" +) + + +def messages_of(parts: list[Part]) -> list[dict[str, Any]]: + return [p.root.data for p in parts if isinstance(p.root, DataPart)] + + +def surface_ids(parts: list[Part]) -> list[str]: + ids: list[str] = [] + for msg in messages_of(parts): + create = msg.get("createSurface") + if isinstance(create, dict): + ids.append(str(create["surfaceId"])) + return ids + + +def _component_text(comp: dict[str, Any]) -> str | None: + """The `text` of a `Text` component in either the v0.9 or v1.0 shape.""" + kind = comp.get("component") + props = kind.get("Text") if isinstance(kind, dict) else comp + text = props.get("text") if isinstance(props, dict) else None + return text if isinstance(text, str) else None + + +def _components_of(msg: dict[str, Any]) -> list[dict[str, Any]]: + """Components carried by a `createSurface` (v1.0) or `updateComponents` message.""" + found: list[dict[str, Any]] = [] + for key in ("createSurface", "updateComponents"): + body = msg.get(key) + if isinstance(body, dict): + found.extend(body.get("components", [])) + return found + + +def status_text(parts: list[Part]) -> str: + """Joins every `Text` literal in the parts, in order.""" + texts = [ + text + for msg in messages_of(parts) + for comp in _components_of(msg) + if (text := _component_text(comp)) is not None + ] + return "\n".join(texts) + + +async def collect( + agent: PlaygroundAgent, query: str, session: str, version: str | None = "0.9" +) -> list[Part]: + items = [item async for item in agent.stream(query, session, version)] + assert len(items) == 1 and items[0]["is_task_complete"] is True + return items[0]["parts"] + + +@pytest.fixture +def agent(scripted_llm: FakeLlmCaller) -> PlaygroundAgent: + renderers = Renderers(versions=["0.9", "1.0"], backend=DeterministicMockBackend()) + return PlaygroundAgent( + "http://localhost:10010", + llm=scripted_llm, + renderers=renderers, + model_name="fake-model", + ) + + +async def test_agent_card_advertises_both_versions(agent: PlaygroundAgent) -> None: + uris = [e.uri for e in agent.agent_card.capabilities.extensions or []] + assert len(uris) == 2 + assert agent.agent_card.skills[0].id == "render_ui" + + +async def test_help_mode_and_trace_before_any_render( + agent: PlaygroundAgent, monkeypatch: pytest.MonkeyPatch +) -> None: + help_parts = await collect(agent, "/help", "s1") + assert surface_ids(help_parts) == ["turn-0-status"] + text = status_text(help_parts) + assert "/compare" in text and "`mock`" in text and "`fake-model`" in text + assert "/backend" in text + + mode_parts = await collect(agent, "/mode express", "s1") + assert "Mode set to `express`" in status_text(mode_parts) + unknown = await collect(agent, "/sparkle", "s1") + assert "Unknown command `/sparkle`" in status_text(unknown) + + monkeypatch.setenv("JEV_API_KEY", "vcp_test_key") + backend_parts = await collect(agent, "/backend jev", "s1") + assert "Decision backend set to `jev (jev)`." in status_text(backend_parts) + reset_parts = await collect(agent, "/backend mock", "s1") + assert "Decision backend set to `mock`." in status_text(reset_parts) + + trace_parts = await collect(agent, "/trace", "s1") + assert "No decision turn yet" in status_text(trace_parts) + + text_only = await collect(agent, "hello", "s1", version=None) + assert isinstance(text_only[0].root, TextPart) + + +@pytest.mark.parametrize("version", ["0.9", "1.0"]) +async def test_decision_turn_renders_surface_footer_and_trace( + agent: PlaygroundAgent, scripted_llm: FakeLlmCaller, version: str +) -> None: + scripted_llm.script("stage1", STAGE1_BLOCK) + parts = await collect(agent, "I want to see the resort", "s2", version) + ids = surface_ids(parts) + assert ids == ["turn-1", "turn-1-decision-footer"] + footer = status_text(parts) + assert "**decision** · mock · 1 LLM call" in footer + assert "archetype" in footer + stage1_call = scripted_llm.calls_for("stage1")[-1] + assert stage1_call["session_id"] == "s2" + assert "Format playground" in str(stage1_call["instruction"]) + + trace = await collect(agent, "/trace", "s2", version) + assert "`family`" in status_text(trace) + + +async def test_express_turn_uses_fresh_stage2_session( + agent: PlaygroundAgent, scripted_llm: FakeLlmCaller +) -> None: + await collect(agent, "/mode express", "s3") + scripted_llm.script("stage1", STAGE1_BLOCK) + scripted_llm.script("express:0.9", EXPRESS_OK.replace("turn-1", "turn-1")) + parts = await collect(agent, "show the resort", "s3") + assert surface_ids(parts) == ["turn-1", "turn-1-express-footer"] + assert "**express** · llm · 2 LLM calls" in status_text(parts) + stage2_call = scripted_llm.calls_for("express:0.9")[-1] + assert stage2_call["session_id"] is None + assert "Casa Verde" in str(stage2_call["user_text"]) + + +async def test_compare_renders_three_surfaces_and_resets( + agent: PlaygroundAgent, scripted_llm: FakeLlmCaller +) -> None: + await collect(agent, "/compare", "s4") + scripted_llm.script("stage1", STAGE1_BLOCK, STAGE1_BLOCK) + scripted_llm.script("express:0.9", EXPRESS_OK.replace("turn-1", "turn-1-express")) + scripted_llm.script( + "direct:0.9", + direct_json_reply(agent.renderers, "0.9").replace("turn-1", "turn-1-direct"), + ) + parts = await collect(agent, "compare the resort", "s4") + assert surface_ids(parts) == [ + "turn-1-decision", + "turn-1-decision-footer", + "turn-1-express", + "turn-1-express-footer", + "turn-1-direct", + "turn-1-direct-footer", + "turn-1-compare", + ] + summary = status_text(parts) + assert "**Compare**" in summary and "`decision`: 1 call" in summary + assert "`express`: 2 calls" in summary and "`direct`: 2 calls" in summary + assert len(scripted_llm.calls_for("stage1")) == 1 + + # The next turn is back to the single default mode. + again = await collect(agent, "again", "s4") + assert surface_ids(again) == ["turn-2", "turn-2-decision-footer"] + + +async def test_prose_from_stage1_and_stage2_failures_never_raise( + agent: PlaygroundAgent, scripted_llm: FakeLlmCaller +) -> None: + scripted_llm.script("stage1", "I would show a card with the resort name.") + prose = await collect(agent, "show the resort", "s5") + assert surface_ids(prose) == ["turn-1-status"] + assert "could not turn that into a decision block" in status_text(prose) + + await collect(agent, "/mode express", "s5") + scripted_llm.script("stage1", STAGE1_BLOCK) + scripted_llm.script("express:0.9", EXPRESS_BAD, EXPRESS_BAD) + failed = await collect(agent, "show the resort", "s5") + assert surface_ids(failed) == ["turn-2-express-footer"] + text = status_text(failed) + assert "3 LLM calls" in text and "Render failed" in text + + +async def test_ui_action_text_goes_through_stage1( + agent: PlaygroundAgent, scripted_llm: FakeLlmCaller +) -> None: + scripted_llm.script("stage1", STAGE1_BLOCK) + action_text = "User interacted with the UI: action `submit` with context {}." + parts = await collect(agent, action_text, "s6") + assert surface_ids(parts)[0] == "turn-1" + assert scripted_llm.calls_for("stage1")[-1]["user_text"] == action_text + assert action_text.startswith(UI_ACTION_PREFIX) + assert RenderMode.DECISION.value in status_text(parts) + + +async def test_default_mode_starts_new_session_in_configured_mode( + scripted_llm: FakeLlmCaller, +) -> None: + renderers = Renderers(versions=["0.9"], backend=DeterministicMockBackend()) + express_agent = PlaygroundAgent( + "http://localhost:10010", + llm=scripted_llm, + renderers=renderers, + model_name="fake-model", + default_mode=RenderMode.EXPRESS, + ) + help_parts = await collect(express_agent, "/help", "s-default-express") + assert "Active mode: `express`" in status_text(help_parts) + + +async def test_tool_mode_renders_surface_with_tool_result( + agent: PlaygroundAgent, scripted_llm: FakeLlmCaller +) -> None: + await collect(agent, "/mode tool", "s-tool-1") + scripted_llm.script_tool( + "tool_mode", + LlmToolTurn( + tool_name="get_host_health", + arguments={"hostname": "prod-01"}, + result={"hostname": "prod-01", "cpu": "98%", "status": "critical"}, + prompt_tokens=150, + output_tokens=30, + latency_ms=120.0, + ), + ) + parts = await collect(agent, "check host 01 health", "s-tool-1") + ids = surface_ids(parts) + assert ids == ["turn-1", "turn-1-tool-footer"] + footer = status_text(parts) + assert "**tool**" in footer + assert "1 LLM call (tool call only)" in footer + + +async def test_tool_mode_plain_text_reply_when_no_tool_called( + agent: PlaygroundAgent, scripted_llm: FakeLlmCaller +) -> None: + await collect(agent, "/mode tool", "s-tool-2") + scripted_llm.script_tool( + "tool_mode", + LlmToolTurn( + tool_name=None, + arguments={}, + result=None, + text="I can only check host health or ski resorts.", + prompt_tokens=100, + output_tokens=20, + latency_ms=80.0, + ), + ) + parts = await collect(agent, "what is the capital of France?", "s-tool-2") + assert surface_ids(parts) == ["turn-1-status", "turn-1-tool-footer"] + assert "I can only check host health" in status_text(parts) + + +async def test_rate_command_records_preference_and_summarizes( + agent: PlaygroundAgent, + scripted_llm: FakeLlmCaller, + tmp_path: Any, + monkeypatch: pytest.MonkeyPatch, +) -> None: + ratings_file = tmp_path / "ratings.jsonl" + monkeypatch.setattr("agent.RATINGS_PATH", ratings_file) + + # Rate before turn + unrated = await collect(agent, "/rate decision", "s-rate") + assert "No previous turn to rate" in status_text(unrated) + + # Valid turn + scripted_llm.script("stage1", STAGE1_BLOCK) + await collect(agent, "show resort", "s-rate") + + # Rate invalid mode + bad_mode = await collect(agent, "/rate glitter", "s-rate") + assert "Unknown mode `glitter`" in status_text(bad_mode) + + # Rate with comment + rated = await collect(agent, "/rate decision Very fast and clean", "s-rate") + assert ( + "Recorded preference for `decision` with comment: Very fast and clean" + in status_text(rated) + ) + + # Show ratings + summary = await collect(agent, "/ratings", "s-rate") + assert "(1 total vote)" in status_text(summary) + assert "`decision`: 1 (100.0%)" in status_text(summary) + + +async def test_remix_command_resamples_layout_with_zero_calls( + agent: PlaygroundAgent, scripted_llm: FakeLlmCaller +) -> None: + # Remix before decision turn + unremixed = await collect(agent, "/remix", "s-remix") + assert "No previous decision render to remix" in status_text(unremixed) + + # Valid decision turn + scripted_llm.script("stage1", STAGE1_BLOCK) + parts = await collect(agent, "show resort", "s-remix") + assert surface_ids(parts) == ["turn-1", "turn-1-decision-footer"] + + # Invalid seed + bad_seed = await collect(agent, "/remix abc", "s-remix") + assert "Invalid seed `abc`" in status_text(bad_seed) + + # Valid remix with seed + remixed = await collect(agent, "/remix 42", "s-remix") + assert surface_ids(remixed) == ["turn-1", "turn-1-remix-footer"] + footer = status_text(remixed) + assert "**decision** · remix · 0 LLM calls · 0 decision calls" in footer + assert "remix seed 42" in footer diff --git a/samples/agent/adk/format_playground/tests/test_commands.py b/samples/agent/adk/format_playground/tests/test_commands.py new file mode 100644 index 0000000000..8c87aeed5c --- /dev/null +++ b/samples/agent/adk/format_playground/tests/test_commands.py @@ -0,0 +1,113 @@ +# 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 slash commands and A2A part classification.""" + +from __future__ import annotations + +from a2a.types import DataPart, Part, TextPart +import pytest + +from agent_executor import build_query, classify_data_part +from commands import Command, apply_command, help_text, parse_command +from modes import PlaygroundSettings, RenderMode + + +@pytest.mark.parametrize( + ("text", "expected"), + [ + ("/mode express", Command("mode", "express")), + (" /MODE Direct ", Command("mode", "direct")), + ("/mode tool", Command("mode", "tool")), + ("/mode", Command("mode", None)), + ("/backend jev", Command("backend", "jev")), + ("/backend gev", Command("backend", "gev")), + ("/backend", Command("backend", None)), + ("/compare", Command("compare")), + ("/trace", Command("trace")), + ("/help", Command("help")), + ("/rate decision", Command("rate", "decision")), + ( + "/rate decision looks great", + Command("rate", "decision", "looks great"), + ), + ("/ratings", Command("ratings")), + ("/remix", Command("remix")), + ("/remix 42", Command("remix", "42")), + ("/nope now", Command("help", "unknown:/nope now")), + ("/", Command("help", "unknown:/")), + ("plain text", None), + ("show me / a slash", None), + ], +) +def test_parse_command(text: str, expected: Command | None) -> None: + assert parse_command(text) == expected + + +def test_apply_command_transitions() -> None: + settings = PlaygroundSettings() + changed, reply = apply_command(Command("mode", "express"), settings) + assert changed.mode is RenderMode.EXPRESS and reply == "Mode set to `express`." + + same, reply = apply_command(Command("mode", "sparkles"), settings) + assert same == settings + assert reply is not None and "decision, express, direct" in reply + same, reply = apply_command(Command("mode", None), settings) + assert same == settings and reply is not None and reply.startswith("Unknown mode") + + comparing, reply = apply_command(Command("compare"), settings) + assert comparing.compare is True and reply is not None and "all three" in reply + + for name in ("trace", "help"): + unchanged, reply = apply_command(Command(name), settings) # type: ignore[arg-type] + assert unchanged == settings and reply is None + + +def test_help_text_names_every_mode_backend_and_model() -> None: + lines = help_text(PlaygroundSettings(mode=RenderMode.DIRECT), "mock", "gemini-x") + joined = "\n".join(lines) + for mode in RenderMode: + assert mode.value in joined + assert "`direct`" in joined and "`mock`" in joined and "`gemini-x`" in joined + assert "/compare" in joined and "/trace" in joined + + +def test_classify_data_part_shapes() -> None: + assert classify_data_part({"useStreaming": False}) == ("streaming", False) + v09 = {"version": "v0.9", "action": {"name": "submit", "context": {"a": 1}}} + assert classify_data_part(v09) == ("action", v09["action"]) + user = {"userAction": {"name": "submit", "surfaceId": "turn-1", "context": {}}} + assert classify_data_part(user) == ("action", user["userAction"]) + pasted = {"name": "Casa Verde", "rating": 4.6} + assert classify_data_part(pasted) == ("payload", pasted) + + +def test_build_query_prefers_actions_then_payloads_then_text() -> None: + text = Part(root=TextPart(text="Show this")) + action = Part( + root=DataPart(data={"userAction": {"name": "submit", "context": {"x": 1}}}) + ) + pasted = Part(root=DataPart(data={"name": "Casa Verde"})) + streaming = Part(root=DataPart(data={"useStreaming": True})) + + assert build_query([text]) == "Show this" + assert build_query([streaming, text]) == "Show this" + action_q = build_query([text, action]) + assert action_q.startswith("User interacted with the UI: action `submit`") + assert '{"x": 1}' in action_q + payload_q = build_query([text, pasted]) + assert payload_q.startswith("Show this\n\nUse this JSON verbatim as the payload:") + assert '"name": "Casa Verde"' in payload_q + assert build_query([pasted]).startswith("Use this JSON verbatim") + assert build_query([]) == "" diff --git a/samples/agent/adk/format_playground/tests/test_modes.py b/samples/agent/adk/format_playground/tests/test_modes.py new file mode 100644 index 0000000000..38c8ed32aa --- /dev/null +++ b/samples/agent/adk/format_playground/tests/test_modes.py @@ -0,0 +1,178 @@ +# 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 shared playground contracts.""" + +from __future__ import annotations + +from modes import ( + LlmTurn, + PlaygroundSettings, + RenderMode, + RenderResult, + TurnMetrics, + as_mode, + surface_id_for, +) + + +def test_render_mode_round_trips_and_formats_as_value() -> None: + assert RenderMode("express") is RenderMode.EXPRESS + assert str(RenderMode.DECISION) == "decision" + assert f"{RenderMode.DIRECT}" == "direct" + assert as_mode(" Express ") is RenderMode.EXPRESS + assert as_mode("sparkles") is None + + +def test_footer_with_every_field() -> None: + metrics = TurnMetrics( + mode=RenderMode.DECISION, + backend="mock", + llm_calls=1, + latency_ms=1840.0, + prompt_tokens=120, + output_tokens=45, + archetype="detail", + confidence=0.82, + block_count=4, + fallback=None, + ) + assert metrics.footer() == ( + "**decision** · mock · 1 LLM call · 1.8 s · 120 in / 45 out tokens" + " · archetype detail (0.82) · 4 blocks" + ) + + +def test_footer_minimal_and_plural_forms() -> None: + metrics = TurnMetrics( + mode=RenderMode.EXPRESS, backend="llm", llm_calls=2, latency_ms=4100.0 + ) + assert metrics.footer() == "**express** · llm · 2 LLM calls · 4.1 s" + with_fallback = TurnMetrics( + mode=RenderMode.DIRECT, + backend="llm", + llm_calls=0, + latency_ms=0.0, + block_count=1, + fallback="validation_retry", + ) + assert with_fallback.footer().endswith("· 1 block · fallback: validation_retry") + + +def test_plus_stage1_folds_the_first_call_in() -> None: + base = TurnMetrics( + mode=RenderMode.DECISION, backend="mock", llm_calls=0, latency_ms=12.0 + ) + folded = base.plus_stage1( + LlmTurn(text="x", prompt_tokens=300, output_tokens=80, latency_ms=900.0) + ) + assert folded.llm_calls == 1 + assert folded.latency_ms == 912.0 + assert (folded.prompt_tokens, folded.output_tokens) == (300, 80) + assert base.llm_calls == 0 + + +def test_surface_ids_and_turn_counter() -> None: + settings = PlaygroundSettings().next_turn() + assert settings.turn == 1 + assert surface_id_for(settings) == "turn-1" + assert surface_id_for(settings, RenderMode.EXPRESS) == "turn-1" + comparing = PlaygroundSettings(compare=True, turn=3) + assert surface_id_for(comparing, RenderMode.EXPRESS) == "turn-3-express" + assert surface_id_for(comparing) == "turn-3" + + +def test_render_result_ok_requires_parts_and_no_error() -> None: + assert not RenderResult().ok + assert not RenderResult(parts=[object()], error="boom").ok # type: ignore[list-item] + assert RenderResult(parts=[object()]).ok # type: ignore[list-item] + + +def test_path_summary_and_decision_timing_across_stages() -> None: + archetype_m = TurnMetrics( + mode=RenderMode.DECISION, + backend="jev", + llm_calls=0, + latency_ms=415.0, + decision_latency_ms=412.0, + decision_calls=1, + stage="archetype", + archetype="form", + confidence=0.86, + block_count=2, + ).plus_stage1( + LlmTurn(text="x", prompt_tokens=600, output_tokens=90, latency_ms=1800.0) + ) + assert archetype_m.footer() == ( + "**decision** · jev · 1 LLM call · decision 412 ms (total 2.2 s)" + " · 600 in / 90 out tokens · path: decision model · archetype form" + " (0.86) · 2 blocks" + ) + + template_m = TurnMetrics( + mode=RenderMode.DECISION, + backend="local", + llm_calls=0, + latency_ms=19.0, + decision_latency_ms=18.2, + stage="template_select", + template_id="login_card", + confidence=0.91, + ) + assert template_m.footer() == ( + "**decision** · local · 0 LLM calls · decision 18 ms" + " · path: templates · template login_card (0.91)" + ) + + container_m = TurnMetrics( + mode=RenderMode.DECISION, + backend="jev", + llm_calls=0, + latency_ms=385.0, + decision_latency_ms=380.0, + stage="container_2pass", + root_component="Column", + confidence=0.74, + ) + assert "path: decision model · 2-pass container Column (0.74)" in ( + container_m.footer() + ) + + leaf_m = TurnMetrics( + mode=RenderMode.DECISION, + backend="mock", + llm_calls=0, + latency_ms=0.5, + decision_latency_ms=0.42, + stage="fast_1pass_leaf", + root_component="Text", + confidence=0.83, + ) + assert "decision 0.42 ms · path: decision model · 1-pass leaf Text (0.83)" in ( + leaf_m.footer() + ) + + fallback_m = TurnMetrics( + mode=RenderMode.DECISION, + backend="jev", + llm_calls=0, + latency_ms=345.0, + decision_latency_ms=340.0, + stage="abstain_fallback", + fallback="card", + confidence=0.31, + ) + assert ( + "path: fallback (card) · decision model abstained (0.31)" in fallback_m.footer() + ) diff --git a/samples/agent/adk/format_playground/tests/test_ratings.py b/samples/agent/adk/format_playground/tests/test_ratings.py new file mode 100644 index 0000000000..a8cc27e7fd --- /dev/null +++ b/samples/agent/adk/format_playground/tests/test_ratings.py @@ -0,0 +1,87 @@ +# 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 format playground rating persistence and summarization.""" + +from __future__ import annotations + +from pathlib import Path + +from ratings import RatingRecord, append_rating, summarize_ratings + + +def test_append_and_summarize_ratings(tmp_path: Path) -> None: + ratings_file = tmp_path / "logs" / "ratings.jsonl" + assert summarize_ratings(ratings_file) == {} + + rec1 = RatingRecord( + session_id="s1", + request="Show stock portfolio", + winner="decision", + comment="Fast and clean", + candidates=[{"mode": "decision", "ok": True}], + ) + rec2 = RatingRecord( + session_id="s2", + request="Show host health", + winner="tool", + comment="Zero model latency", + ) + rec3 = RatingRecord( + session_id="s3", + request="Address form", + winner="decision", + ) + + append_rating(ratings_file, rec1) + append_rating(ratings_file, rec2) + append_rating(ratings_file, rec3) + + summary = summarize_ratings(ratings_file) + assert summary == {"decision": 2, "tool": 1} + + +def test_corrupt_lines_ignored(tmp_path: Path) -> None: + ratings_file = tmp_path / "corrupt.jsonl" + ratings_file.write_text( + '{"winner": "decision"}\n' + "\n" + '{"not_json": broken\n' + '{"winner": "express"}\n' + '{"no_winner_field": 1}\n', + encoding="utf-8", + ) + + summary = summarize_ratings(ratings_file) + assert summary == {"decision": 1, "express": 1} + + +def test_rating_record_dict_roundtrip() -> None: + rec = RatingRecord( + session_id="sess-42", + request="Query text", + winner="direct", + comment="Nice layout", + candidates=[{"mode": "direct", "latency_ms": 12.5}], + ) + data = rec.to_dict() + assert data["session_id"] == "sess-42" + assert data["winner"] == "direct" + assert data["comment"] == "Nice layout" + + rec2 = RatingRecord.from_dict(data) + assert rec2.session_id == rec.session_id + assert rec2.winner == rec.winner + assert rec2.comment == rec.comment + assert rec2.candidates == rec.candidates diff --git a/samples/agent/adk/format_playground/tests/test_renderers.py b/samples/agent/adk/format_playground/tests/test_renderers.py new file mode 100644 index 0000000000..654a3a9755 --- /dev/null +++ b/samples/agent/adk/format_playground/tests/test_renderers.py @@ -0,0 +1,335 @@ +# 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 stage 2: decision, express, and direct renderers plus status surfaces.""" + +from __future__ import annotations + +import json +from typing import Any + +from a2a.types import DataPart, Part +import pytest + +from a2ui.core.basic_catalog import BasicCatalog +from a2ui.inference_formats.decision import DecisionBlock, DeterministicMockBackend +from a2ui.utils import validate_payload +from fakes import FakeLlmCaller +from modes import RenderMode +from renderers import Renderers, backend_display_name, stage2_user_text + +RESORT_PAYLOAD: dict[str, Any] = { + "name": "Casa Verde", + "logoUrl": "https://example.com/casa-verde/logo.png", + "rating": 4.6, + "priceFrom": 240, + "about": ( + "A quiet hillside resort twenty minutes from the old town, with a" + " spring-fed pool, garden suites, and a breakfast terrace that looks" + " over the valley. Families and walkers come back year after year." + ), + "photos": [ + { + "url": "https://example.com/casa-verde/1.jpg", + "caption": "Pool at dusk", + }, + { + "url": "https://example.com/casa-verde/2.jpg", + "caption": "Garden suite", + }, + { + "url": "https://example.com/casa-verde/3.jpg", + "caption": "Breakfast terrace", + }, + ], +} +RESORT_BLOCK = DecisionBlock(intent="Show the resort overview", payload=RESORT_PAYLOAD) + +EXPRESS_OK = 'surface("turn-1")\nroot = Column([Text("Portfolio")])' +EXPRESS_BAD = "root = Nope(" + + +def direct_json_reply(renderers: Renderers, version: str) -> str: + """A valid Direct JSON reply for `version`, built from a compiled surface.""" + parts = renderers.status_surface( + ["Portfolio"], surface_id="turn-1", version=version + ) + return f"{json.dumps(messages_of(parts))}" + + +def messages_of(parts: list[Part]) -> list[dict[str, Any]]: + return [p.root.data for p in parts if isinstance(p.root, DataPart)] + + +def surface_ids(parts: list[Part]) -> list[str]: + ids: list[str] = [] + for msg in messages_of(parts): + create = msg.get("createSurface") + if isinstance(create, dict) and "surfaceId" in create: + ids.append(str(create["surfaceId"])) + return ids + + +@pytest.fixture(scope="module") +def renderers() -> Renderers: + return Renderers(versions=["0.9", "1.0"], backend=DeterministicMockBackend()) + + +def test_backend_display_name_maps_bundled_backends( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from a2ui.inference_formats.decision import JevHttpBackend + from renderers import build_named_backend + + assert backend_display_name(DeterministicMockBackend()) == "mock" + assert ( + backend_display_name( + JevHttpBackend("https://api.typesafe.ai/v1/systemone", model="jev-latest") + ) + == "jev (jev-latest)" + ) + assert ( + backend_display_name( + JevHttpBackend( + "http://127.0.0.1:8790/v1/systemone", + model="vertex/decision-gemma", + ) + ) + == "gev (vertex/decision-gemma)" + ) + + monkeypatch.setenv("JEV_API_KEY", "vcp_test_key") + jev_b = build_named_backend("jev") + assert backend_display_name(jev_b) == "jev (jev)" + gev_b = build_named_backend("gev") + assert backend_display_name(gev_b) == "gev (vertex/decision-gemma)" + + class Custom: + pass + + assert backend_display_name(Custom()) == "Custom" # type: ignore[arg-type] + + +@pytest.mark.parametrize("version", ["0.9", "1.0"]) +@pytest.mark.asyncio +async def test_render_decision_produces_a_surface_without_llm_calls( + renderers: Renderers, version: str +) -> None: + result = await renderers.render_decision( + RESORT_BLOCK, surface_id="turn-1", version=version + ) + assert result.ok, result.error + assert surface_ids(result.parts) == ["turn-1"] + validate_payload([BasicCatalog(version)], messages_of(result.parts)) + assert result.metrics is not None + assert result.metrics.llm_calls == 0 + assert result.metrics.backend == "mock" + assert result.metrics.mode is RenderMode.DECISION + assert any("`family`" in line for line in result.trace_lines) + assert "**decision** · mock · 0 LLM calls" in result.metrics.footer() + + +@pytest.mark.asyncio +async def test_render_with_llm_express_succeeds_retries_and_fails( + renderers: Renderers, scripted_llm: FakeLlmCaller +) -> None: + scripted_llm.script("express:1.0", EXPRESS_OK) + ok = await renderers.render_with_llm( + RenderMode.EXPRESS, + RESORT_BLOCK, + surface_id="turn-1", + version="1.0", + llm=scripted_llm, + ) + assert ok.ok, ok.error + assert surface_ids(ok.parts) == ["turn-1"] + assert ok.metrics is not None and ok.metrics.llm_calls == 1 + assert ok.metrics.backend == "llm" and ok.metrics.fallback is None + call = scripted_llm.calls_for("express:1.0")[0] + assert call["session_id"] is None + assert "Casa Verde" in str(call["user_text"]) and "turn-1" in str(call["user_text"]) + assert "Express" in str(call["instruction"]) or "surface(" in str( + call["instruction"] + ) + + scripted_llm.script("express:1.0", EXPRESS_BAD, EXPRESS_OK) + retried = await renderers.render_with_llm( + RenderMode.EXPRESS, + RESORT_BLOCK, + surface_id="turn-1", + version="1.0", + llm=scripted_llm, + ) + assert retried.ok + assert retried.metrics is not None and retried.metrics.llm_calls == 2 + assert retried.metrics.fallback == "validation_retry" + assert "previous reply was invalid" in str( + scripted_llm.calls_for("express:1.0")[-1]["user_text"] + ) + + scripted_llm.script("express:1.0", EXPRESS_BAD, EXPRESS_BAD) + failed = await renderers.render_with_llm( + RenderMode.EXPRESS, + RESORT_BLOCK, + surface_id="turn-1", + version="1.0", + llm=scripted_llm, + ) + assert not failed.ok and failed.error and failed.parts == [] + assert failed.metrics is not None and failed.metrics.llm_calls == 2 + + +@pytest.mark.asyncio +async def test_render_with_llm_direct_and_prose_reply( + renderers: Renderers, scripted_llm: FakeLlmCaller +) -> None: + scripted_llm.script("direct:1.0", direct_json_reply(renderers, "1.0")) + ok = await renderers.render_with_llm( + RenderMode.DIRECT, + RESORT_BLOCK, + surface_id="turn-1", + version="1.0", + llm=scripted_llm, + ) + assert ok.ok, ok.error + assert surface_ids(ok.parts) == ["turn-1"] + validate_payload([BasicCatalog("1.0")], messages_of(ok.parts)) + + scripted_llm.script("direct:1.0", "Here is a nice card.", "Still prose.") + prose = await renderers.render_with_llm( + RenderMode.DIRECT, + RESORT_BLOCK, + surface_id="turn-1", + version="1.0", + llm=scripted_llm, + ) + assert not prose.ok + assert prose.error == "The reply contained no A2UI block." + + +@pytest.mark.asyncio +async def test_render_with_llm_rejects_decision_mode( + renderers: Renderers, scripted_llm: FakeLlmCaller +) -> None: + with pytest.raises(ValueError, match="express or direct"): + await renderers.render_with_llm( + RenderMode.DECISION, + RESORT_BLOCK, + surface_id="t", + version="1.0", + llm=scripted_llm, + ) + + +@pytest.mark.parametrize("version", ["0.9", "1.0"]) +def test_status_surface_validates_and_escapes( + renderers: Renderers, version: str +) -> None: + lines = [ + "**decision** · mock · 1 LLM call", + 'He said "hi" \\ bye', + "`gate:prose` · yes p=0.90", + ] + parts = renderers.status_surface(lines, surface_id="turn-1-status", version=version) + msgs = messages_of(parts) + validate_payload([BasicCatalog(version)], msgs) + assert surface_ids(parts) == ["turn-1-status"] + flat = json.dumps(msgs, ensure_ascii=False) + assert 'He said \\"hi\\" \\\\ bye' in flat + assert "`gate:prose` · yes p=0.90" in flat + + +def test_stage2_user_text_mentions_intent_surface_and_payload() -> None: + text = stage2_user_text(RESORT_BLOCK, "turn-7") + assert "Show the resort overview" in text + assert 'surface id "turn-7"' in text + assert '"priceFrom": 240' in text + + +def test_prompt_for_each_mode_is_that_formats_prompt( + renderers: Renderers, +) -> None: + express = renderers.prompt_for(RenderMode.EXPRESS, "1.0") + direct = renderers.prompt_for(RenderMode.DIRECT, "1.0") + assert express != direct + assert "surface(" in express + assert renderers.versions == ("0.9", "1.0") + + +@pytest.mark.asyncio +async def test_render_decision_login_form_forwards_mutable_paths() -> None: + backend = DeterministicMockBackend( + scripted={ + "family": {"input": 0.92, "browse": 0.02}, + "archetype:input": {"form": 0.88, "settings": 0.12}, + "gate:form": {"yes": 0.95, "no": 0.05}, + "gate:actions": {"yes": 0.95, "no": 0.05}, + } + ) + form_renderers = Renderers(versions=["0.9"], backend=backend) + for mutable_paths in (["/email", "/password", "/rememberMe"], []): + login_block = DecisionBlock.from_mapping({ + "intent": "Render a login form with email, password, and sign in button", + "payload": { + "title": "Welcome Back", + "email": "alex.smith@example.com", + "password": "", + "rememberMe": False, + "actions": ["Sign In"], + }, + "mutablePaths": mutable_paths, + }) + res = await form_renderers.render_decision( + login_block, surface_id="turn-login", version="0.9" + ) + assert res.ok, res.error + validate_payload([BasicCatalog("0.9")], messages_of(res.parts)) + assert res.metrics is not None + assert res.metrics.archetype == "form" + assert res.metrics.stage == "archetype" + assert ( + res.metrics.decision_latency_ms is not None + and res.metrics.decision_latency_ms > 0.0 + ) + assert "path: decision model · archetype form" in res.metrics.footer() + assert "decision " in res.metrics.footer() + assert res.trace_lines[0].startswith("**Path**: decision model · archetype") + assert "**Decision time**:" in res.trace_lines[0] + + +@pytest.mark.asyncio +async def test_render_tool_result_synthesizes_with_zero_llm_calls() -> None: + backend = DeterministicMockBackend( + scripted={ + "family": {"dashboard": 0.95, "browse": 0.05}, + "archetype:dashboard": {"status": 0.90, "summary": 0.10}, + "gate:headline": {"yes": 0.95, "no": 0.05}, + "gate:facts": {"yes": 0.95, "no": 0.05}, + "gate:actions": {"yes": 0.95, "no": 0.05}, + } + ) + tool_renderers = Renderers(versions=["1.0"], backend=backend) + res = await tool_renderers.render_tool_result( + "Show host health status", + {"hostname": "server-1", "cpu": "98%", "status": "critical"}, + surface_id="turn-tool-test", + version="1.0", + mutable_paths=["/status"], + ) + assert res.ok, res.error + assert res.metrics is not None + assert res.metrics.mode is RenderMode.TOOL + assert res.metrics.llm_calls == 0 + assert res.metrics.decision_latency_ms is not None + assert "0 LLM calls" in res.metrics.footer() diff --git a/samples/agent/adk/format_playground/tests/test_stage1.py b/samples/agent/adk/format_playground/tests/test_stage1.py new file mode 100644 index 0000000000..80a6b09a85 --- /dev/null +++ b/samples/agent/adk/format_playground/tests/test_stage1.py @@ -0,0 +1,104 @@ +# 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 stage 1: prompt assembly, pasted JSON, and block extraction.""" + +from __future__ import annotations + +import json + +from a2ui.inference_formats.decision import ArchetypeGrammar +from stage1 import ( + STAGE1_PREAMBLE, + UI_ACTION_PREFIX, + extract_block, + extract_pasted_json, + stage1_instruction, + stage1_user_text, +) + +_BLOCK = { + "intent": "Show the resort overview", + "payload": {"name": "Casa Verde", "rating": 4.6}, +} + + +def _wrap(body: str) -> str: + return f"{body}" + + +def test_extract_block_reads_a_well_formed_block() -> None: + block = extract_block("Sure!\n" + _wrap(json.dumps(_BLOCK)) + "\nDone.") + assert block is not None + assert block.intent == "Show the resort overview" + assert block.payload == _BLOCK["payload"] + assert block.layout == () + + +def test_extract_block_accepts_a_list_wrapper_tolerant_json_and_tags_in_strings() -> ( + None +): + listed = extract_block( + _wrap(json.dumps([_BLOCK, {"intent": "second", "payload": {}}])) + ) + assert listed is not None and listed.intent == "Show the resort overview" + trailing_comma = extract_block( + _wrap('{"intent": "Show it", "payload": {"a": 1,},}') + ) + assert trailing_comma is not None and trailing_comma.payload == {"a": 1} + with_tag_in_string = extract_block( + _wrap('{"intent": "Say literally", "payload": {"x": ""}}') + ) + assert with_tag_in_string is not None + assert with_tag_in_string.payload == {"x": ""} + + +def test_extract_block_returns_none_for_prose_or_invalid_blocks() -> None: + assert extract_block("I would show a card with the resort name.") is None + assert extract_block(_wrap("not json at all")) is None + assert extract_block(_wrap(json.dumps({"payload": {"a": 1}}))) is None + assert extract_block(_wrap(json.dumps(["just", "strings"]))) is None + + +def test_extract_pasted_json_finds_objects_and_arrays_and_ignores_prose_braces() -> ( + None +): + assert extract_pasted_json('Show this: {"a": 1, "b": [1, 2]}') == { + "a": 1, + "b": [1, 2], + } + assert extract_pasted_json("List: [1, 2, 3] please") == [1, 2, 3] + assert extract_pasted_json("Use {curly} braces {like this}") is None + assert extract_pasted_json('first {"a": 1} then {"b": 2}') == {"a": 1} + assert extract_pasted_json("no json here") is None + + +def test_stage1_user_text_pins_pasted_json_only_when_present() -> None: + plain = stage1_user_text("Give me an address entry form") + assert plain == "Give me an address entry form" + pinned = stage1_user_text('Render {"name": "Casa Verde"}') + assert pinned.startswith('Render {"name": "Casa Verde"}') + assert "Use this JSON verbatim as the payload" in pinned + assert '"name": "Casa Verde"' in pinned + action = f'{UI_ACTION_PREFIX} action `submit` with context {{"x": 1}}.' + assert stage1_user_text(action) == action + + +def test_stage1_instruction_lists_every_brief_role() -> None: + grammar = ArchetypeGrammar.default() + instruction = stage1_instruction(grammar) + assert instruction.startswith(STAGE1_PREAMBLE) + for role in grammar.brief_roles(): + assert f"`{role}`" in instruction + assert "" in instruction diff --git a/samples/agent/adk/format_playground/tests/test_tools.py b/samples/agent/adk/format_playground/tests/test_tools.py new file mode 100644 index 0000000000..26a52ef055 --- /dev/null +++ b/samples/agent/adk/format_playground/tests/test_tools.py @@ -0,0 +1,94 @@ +# 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 format playground ADK tools and their decision synthesis.""" + +from __future__ import annotations + +import pytest + +from a2ui.core.basic_catalog import BasicCatalog +from a2ui.processor import CatalogConfig +from a2ui.inference_formats.decision import ( + ArchetypeGrammar, + CatalogDecisionGraph, + DecisionSynthesizer, + SynthesisStage, +) +from tools import ( + TOOL_INTENTS, + TOOL_MUTABLE_PATHS, + TOOLS, + get_host_health, + get_playback_settings, + get_resort, + get_transfer_quote, +) +from .fakes import ( + HOST_ANSWERS, + RESORT_ANSWERS, + SETTINGS_ANSWERS, + TRANSFER_ANSWERS, + scripted_backend, +) + + +def test_all_tools_have_intents_and_mutable_paths() -> None: + assert len(TOOLS) == 4 + for tool in TOOLS: + name = getattr(tool, "__name__", "") + assert name in TOOL_INTENTS + assert name in TOOL_MUTABLE_PATHS + assert TOOL_INTENTS[name] + + +def test_tool_direct_calls() -> None: + assert "cpu" in get_host_health("host-01") + assert "resorts" in get_resort("vail") + assert "fee" in get_transfer_quote(100.0, "hotel") + assert "volume" in get_playback_settings() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("tool_fn", "kwargs", "answers"), + [ + (get_host_health, {"host": "prod-db-01"}, HOST_ANSWERS), + (get_resort, {"name": "whistler"}, RESORT_ANSWERS), + ( + get_transfer_quote, + {"amount": 1000.0, "recipient": "Manhattan"}, + TRANSFER_ANSWERS, + ), + (get_playback_settings, {}, SETTINGS_ANSWERS), + ], +) +async def test_tool_result_synthesizes_to_archetype(tool_fn, kwargs, answers) -> None: + catalog = BasicCatalog("1.0") + graph = CatalogDecisionGraph([catalog]) + synthesizer = DecisionSynthesizer( + graph, + backend=scripted_backend(answers), + archetypes=ArchetypeGrammar.default(), + ) + result = tool_fn(**kwargs) + name = tool_fn.__name__ + intent = TOOL_INTENTS[name] + mutable_paths = TOOL_MUTABLE_PATHS[name] + + output = await synthesizer.synthesize( + intent, result, surface_id="test", mutable_paths=mutable_paths + ) + assert output.stage is SynthesisStage.ARCHETYPE + assert output.messages diff --git a/samples/agent/adk/format_playground/tools.py b/samples/agent/adk/format_playground/tools.py new file mode 100644 index 0000000000..fd025338b2 --- /dev/null +++ b/samples/agent/adk/format_playground/tools.py @@ -0,0 +1,85 @@ +# 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. + +"""Tools exposed to the language model in playground tool mode.""" + +from __future__ import annotations + +from typing import Any, Callable + + +def get_host_health(host: str = "prod-1") -> dict[str, Any]: + """Retrieves operational and health metrics for a production host server.""" + return { + "host": host, + "cpu": 0.78, + "cpuDelta": 0.12, + "status": "degraded", + "uptimeHours": 412, + } + + +def get_resort(name: str = "Snowbird") -> dict[str, Any]: + """Fetches details, elevation, and open trail information for mountain ski resorts.""" + return { + "resorts": [ + {"name": name, "elevation": 11000, "openRuns": 85}, + {"name": "Alta", "elevation": 10500, "openRuns": 70}, + ] + } + + +def get_transfer_quote( + amount: float = 15000.0, recipient: str = "Acme Corp" +) -> dict[str, Any]: + """Calculates fee and prepares a quote for an outbound bank wire transfer.""" + return { + "recipient": recipient, + "amount": amount, + "fee": 25.0, + "sourceAccount": "Checking ...4821", + "actions": ["Confirm Transfer", "Cancel"], + } + + +def get_playback_settings() -> dict[str, Any]: + """Loads current audio, subtitle, and user interface playback settings.""" + return { + "volume": 80, + "subtitles": True, + "theme": "dark", + "actions": ["Save", "Cancel"], + } + + +TOOL_INTENTS: dict[str, str] = { + "get_host_health": "Show CPU utilization and host health", + "get_resort": "Browse mountain ski resort details", + "get_transfer_quote": "Review wire transfer quote", + "get_playback_settings": "Adjust audio playback and notification preferences", +} + +TOOL_MUTABLE_PATHS: dict[str, tuple[str, ...]] = { + "get_host_health": (), + "get_resort": (), + "get_transfer_quote": ("/actions",), + "get_playback_settings": ("/volume", "/subtitles", "/theme", "/actions"), +} + +TOOLS: list[Callable[..., Any]] = [ + get_host_health, + get_resort, + get_transfer_quote, + get_playback_settings, +] diff --git a/samples/client/lit/shell/app.ts b/samples/client/lit/shell/app.ts index f0cac3f5d3..738f19fe4d 100644 --- a/samples/client/lit/shell/app.ts +++ b/samples/client/lit/shell/app.ts @@ -29,11 +29,17 @@ import {renderMarkdown} from '@a2ui/markdown-it'; // Configurations import {A2UIClient} from './client.js'; -import {restaurantConfig, localConfig, AppConfig} from './configs/configs.js'; +import { + restaurantConfig, + localConfig, + playgroundConfig, + AppConfig, +} from './configs/configs.js'; import {styleMap} from 'lit/directives/style-map.js'; const configs: Record = { restaurant: restaurantConfig, local: localConfig, + playground: playgroundConfig, }; type MarkdownRendererFn = (value: string, options?: any) => Promise; diff --git a/samples/client/lit/shell/configs/configs.ts b/samples/client/lit/shell/configs/configs.ts index ac75a5f1d6..976b67b9cf 100644 --- a/samples/client/lit/shell/configs/configs.ts +++ b/samples/client/lit/shell/configs/configs.ts @@ -17,3 +17,4 @@ export type {AppConfig} from './types.js'; export {restaurantConfig} from './restaurant.js'; export {localConfig} from './local.js'; +export {playgroundConfig} from './playground.js'; diff --git a/samples/client/lit/shell/configs/playground.ts b/samples/client/lit/shell/configs/playground.ts new file mode 100644 index 0000000000..f491b11be8 --- /dev/null +++ b/samples/client/lit/shell/configs/playground.ts @@ -0,0 +1,29 @@ +/* + * 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. + */ + +import {AppConfig} from './types.js'; + +export const playgroundConfig: AppConfig = { + key: 'playground', + title: 'A2UI Format Playground', + placeholder: 'Describe a UI, paste JSON, or type /help', + loadingText: [ + 'Describing the interface...', + 'Planning the layout...', + 'Rendering...', + ], + serverUrl: 'http://localhost:10010', +}; diff --git a/uv.lock b/uv.lock index 04db9631d3..0a97e0c190 100644 --- a/uv.lock +++ b/uv.lock @@ -23,6 +23,7 @@ members = [ "a2ui-core", "a2ui-custom-components-example", "a2ui-eval", + "a2ui-format-playground", "a2ui-in-mcp-apps-server", "a2ui-mcp-apps-in-a2ui-sample", "a2ui-mcp-calculator-demo", @@ -114,6 +115,17 @@ dependencies = [ { name = "pyyaml" }, ] +[package.optional-dependencies] +decision-local = [ + { name = "huggingface-hub" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "numpy", version = "2.5.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "onnxruntime", version = "1.24.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "onnxruntime", version = "1.31.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "tokenizers" }, +] + [package.dev-dependencies] dev = [ { name = "antlr4-tools" }, @@ -126,10 +138,15 @@ requires-dist = [ { name = "a2ui-core", editable = "python/a2ui_core" }, { name = "antlr4-python3-runtime", specifier = ">=4.13.0,<4.14.0" }, { name = "httpx", specifier = ">=0.27.0" }, + { name = "huggingface-hub", marker = "extra == 'decision-local'", specifier = ">=0.25.0" }, { name = "jsonschema", specifier = ">=4.0.0" }, + { name = "numpy", marker = "extra == 'decision-local'", specifier = ">=1.26.0" }, + { name = "onnxruntime", marker = "extra == 'decision-local'", specifier = ">=1.19.0" }, { name = "pydantic", specifier = ">=2.11.0" }, { name = "pyyaml", specifier = ">=6.0" }, + { name = "tokenizers", marker = "extra == 'decision-local'", specifier = ">=0.20.0" }, ] +provides-extras = ["decision-local"] [package.metadata.requires-dev] dev = [ @@ -289,6 +306,40 @@ requires-dist = [ ] provides-extras = ["frontier"] +[[package]] +name = "a2ui-format-playground" +version = "0.1.0" +source = { editable = "samples/agent/adk/format_playground" } +dependencies = [ + { name = "a2a-sdk", extra = ["http-server"] }, + { name = "a2ui-a2a" }, + { name = "a2ui-agent-sdk" }, + { name = "click" }, + { name = "google-adk" }, + { name = "google-genai" }, + { name = "python-dotenv" }, + { name = "uvicorn" }, +] + +[package.optional-dependencies] +local = [ + { name = "a2ui-agent-sdk", extra = ["decision-local"] }, +] + +[package.metadata] +requires-dist = [ + { name = "a2a-sdk", extras = ["http-server"], specifier = ">=0.3.0" }, + { name = "a2ui-a2a", editable = "python/a2ui_a2a" }, + { name = "a2ui-agent-sdk", editable = "python/a2ui_agent" }, + { name = "a2ui-agent-sdk", extras = ["decision-local"], marker = "extra == 'local'", editable = "python/a2ui_agent" }, + { name = "click", specifier = ">=8.1.8" }, + { name = "google-adk", specifier = ">=1.28.1" }, + { name = "google-genai", specifier = ">=1.27.0" }, + { name = "python-dotenv", specifier = ">=1.1.0" }, + { name = "uvicorn", specifier = ">=0.40.0" }, +] +provides-extras = ["local"] + [[package]] name = "a2ui-in-mcp-apps-server" version = "0.1.0" @@ -1578,6 +1629,14 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/13/37/a065dc3bd6e49423a6532c642ca7378d3f467b1ef44c2800c937af7f9739/filelock-3.29.4-py3-none-any.whl", hash = "sha256:dac1648087d5115554850d113e7dd8c83ab2d38e3435dde2d4f163847e57b767", size = 42757, upload-time = "2026-06-13T16:11:59.582Z" }, ] +[[package]] +name = "flatbuffers" +version = "25.12.19" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e8/2d/d2a548598be01649e2d46231d151a6c56d10b964d94043a335ae56ea2d92/flatbuffers-25.12.19-py2.py3-none-any.whl", hash = "sha256:7634f50c427838bb021c2d66a3d1168e9d199b0607e6329399f04846d42e20b4", size = 26661, upload-time = "2025-12-19T23:16:13.622Z" }, +] + [[package]] name = "frozenlist" version = "1.8.0" @@ -3106,6 +3165,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e8/3d/1087453384dbde46a8c7f9356eead2c58be8a7bf156bca40243377c85715/more_itertools-11.1.0-py3-none-any.whl", hash = "sha256:4b65538ae22f6fed0ce4874efd317463a7489796a0939fa66824dd542125a192", size = 72226, upload-time = "2026-05-22T14:14:28.824Z" }, ] +[[package]] +name = "mpmath" +version = "1.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e0/47/dd32fa426cc72114383ac549964eecb20ecfd886d1e5ccf5340b55b02f57/mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f", size = 508106, upload-time = "2023-03-07T16:47:11.061Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198, upload-time = "2023-03-07T16:47:09.197Z" }, +] + [[package]] name = "multidict" version = "6.7.1" @@ -3571,6 +3639,95 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fd/6a/d3a169aaf8536cf228d56a09e04bcb713a2fe4410d4e2105b9419b5a9c89/numpy-2.5.0-cp314-cp314t-win_arm64.whl", hash = "sha256:016623417bb330d719d579daf2d6b9a01ddc52e41a9ed61a47f39fde46dcd865", size = 10686451, upload-time = "2026-06-21T20:57:49.313Z" }, ] +[[package]] +name = "onnxruntime" +version = "1.24.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version < '3.11'", +] +dependencies = [ + { name = "flatbuffers" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, + { name = "packaging" }, + { name = "protobuf" }, + { name = "sympy" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/15/41/3253db975a90c3ce1d475e2a230773a21cd7998537f0657947df6fb79861/onnxruntime-1.24.3-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:3e6456801c66b095c5cd68e690ca25db970ea5202bd0c5b84a2c3ef7731c5a3c", size = 17332766, upload-time = "2026-03-05T17:18:59.714Z" }, + { url = "https://files.pythonhosted.org/packages/7e/c5/3af6b325f1492d691b23844d88ed26844c1164620860c5efe95c0e22782d/onnxruntime-1.24.3-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8b2ebc54c6d8281dccff78d4b06e47d4cf07535937584ab759448390a70f4978", size = 15130330, upload-time = "2026-03-05T16:34:53.831Z" }, + { url = "https://files.pythonhosted.org/packages/03/4b/f96b46c1866a293ed23ca2cf5e5a63d413ad3a951da60dd877e3c56cbbca/onnxruntime-1.24.3-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fb56575d7794bf0781156955610c9e651c9504c64d42ec880784b6106244882d", size = 17213247, upload-time = "2026-03-05T17:17:59.812Z" }, + { url = "https://files.pythonhosted.org/packages/36/13/27cf4d8df2578747584e8758aeb0b673b60274048510257f1f084b15e80e/onnxruntime-1.24.3-cp311-cp311-win_amd64.whl", hash = "sha256:c958222ef9eff54018332beecd32d5d94a3ab079d8821937b333811bf4da0d39", size = 12595530, upload-time = "2026-03-05T17:18:49.356Z" }, + { url = "https://files.pythonhosted.org/packages/19/8c/6d9f31e6bae72a8079be12ed8ba36c4126a571fad38ded0a1b96f60f6896/onnxruntime-1.24.3-cp311-cp311-win_arm64.whl", hash = "sha256:a8f761857ebaf58a85b9e42422d03207f1d39e6bb8fecfdbf613bac5b9710723", size = 12261715, upload-time = "2026-03-05T17:18:39.699Z" }, + { url = "https://files.pythonhosted.org/packages/d0/7f/dfdc4e52600fde4c02d59bfe98c4b057931c1114b701e175aee311a9bc11/onnxruntime-1.24.3-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:0d244227dc5e00a9ae15a7ac1eba4c4460d7876dfecafe73fb00db9f1d914d91", size = 17342578, upload-time = "2026-03-05T17:19:02.403Z" }, + { url = "https://files.pythonhosted.org/packages/1c/dc/1f5489f7b21817d4ad352bf7a92a252bd5b438bcbaa7ad20ea50814edc79/onnxruntime-1.24.3-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0a9847b870b6cb462652b547bc98c49e0efb67553410a082fde1918a38707452", size = 15150105, upload-time = "2026-03-05T16:34:56.897Z" }, + { url = "https://files.pythonhosted.org/packages/28/7c/fd253da53594ab8efbefdc85b3638620ab1a6aab6eb7028a513c853559ce/onnxruntime-1.24.3-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b354afce3333f2859c7e8706d84b6c552beac39233bcd3141ce7ab77b4cabb5d", size = 17237101, upload-time = "2026-03-05T17:18:02.561Z" }, + { url = "https://files.pythonhosted.org/packages/71/5f/eaabc5699eeed6a9188c5c055ac1948ae50138697a0428d562ac970d7db5/onnxruntime-1.24.3-cp312-cp312-win_amd64.whl", hash = "sha256:44ea708c34965439170d811267c51281d3897ecfc4aa0087fa25d4a4c3eb2e4a", size = 12597638, upload-time = "2026-03-05T17:18:52.141Z" }, + { url = "https://files.pythonhosted.org/packages/cc/5c/d8066c320b90610dbeb489a483b132c3b3879b2f93f949fb5d30cfa9b119/onnxruntime-1.24.3-cp312-cp312-win_arm64.whl", hash = "sha256:48d1092b44ca2ba6f9543892e7c422c15a568481403c10440945685faf27a8d8", size = 12270943, upload-time = "2026-03-05T17:18:42.006Z" }, + { url = "https://files.pythonhosted.org/packages/51/8d/487ece554119e2991242d4de55de7019ac6e47ee8dfafa69fcf41d37f8ed/onnxruntime-1.24.3-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:34a0ea5ff191d8420d9c1332355644148b1bf1a0d10c411af890a63a9f662aa7", size = 17342706, upload-time = "2026-03-05T16:35:10.813Z" }, + { url = "https://files.pythonhosted.org/packages/dd/25/8b444f463c1ac6106b889f6235c84f01eec001eaf689c3eff8c69cf48fae/onnxruntime-1.24.3-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1fd2ec7bb0fabe42f55e8337cfc9b1969d0d14622711aac73d69b4bd5abb5ed7", size = 15149956, upload-time = "2026-03-05T16:34:59.264Z" }, + { url = "https://files.pythonhosted.org/packages/34/fc/c9182a3e1ab46940dd4f30e61071f59eee8804c1f641f37ce6e173633fb6/onnxruntime-1.24.3-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:df8e70e732fe26346faaeec9147fa38bef35d232d2495d27e93dd221a2d473a9", size = 17237370, upload-time = "2026-03-05T17:18:05.258Z" }, + { url = "https://files.pythonhosted.org/packages/05/7e/3b549e1f4538514118bff98a1bcd6481dd9a17067f8c9af77151621c9a5c/onnxruntime-1.24.3-cp313-cp313-win_amd64.whl", hash = "sha256:2d3706719be6ad41d38a2250998b1d87758a20f6ea4546962e21dc79f1f1fd2b", size = 12597939, upload-time = "2026-03-05T17:18:54.772Z" }, + { url = "https://files.pythonhosted.org/packages/80/41/9696a5c4631a0caa75cc8bc4efd30938fd483694aa614898d087c3ee6d29/onnxruntime-1.24.3-cp313-cp313-win_arm64.whl", hash = "sha256:b082f3ba9519f0a1a1e754556bc7e635c7526ef81b98b3f78da4455d25f0437b", size = 12270705, upload-time = "2026-03-05T17:18:44.774Z" }, + { url = "https://files.pythonhosted.org/packages/b7/65/a26c5e59e3b210852ee04248cf8843c81fe7d40d94cf95343b66efe7eec9/onnxruntime-1.24.3-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:72f956634bc2e4bd2e8b006bef111849bd42c42dea37bd0a4c728404fdaf4d34", size = 15161796, upload-time = "2026-03-05T16:35:02.871Z" }, + { url = "https://files.pythonhosted.org/packages/f3/25/2035b4aa2ccb5be6acf139397731ec507c5f09e199ab39d3262b22ffa1ac/onnxruntime-1.24.3-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:78d1f25eed4ab9959db70a626ed50ee24cf497e60774f59f1207ac8556399c4d", size = 17240936, upload-time = "2026-03-05T17:18:09.534Z" }, + { url = "https://files.pythonhosted.org/packages/f9/a4/b3240ea84b92a3efb83d49cc16c04a17ade1ab47a6a95c4866d15bf0ac35/onnxruntime-1.24.3-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:a6b4bce87d96f78f0a9bf5cefab3303ae95d558c5bfea53d0bf7f9ea207880a8", size = 17344149, upload-time = "2026-03-05T16:35:13.382Z" }, + { url = "https://files.pythonhosted.org/packages/bb/4a/4b56757e51a56265e8c56764d9c36d7b435045e05e3b8a38bedfc5aedba3/onnxruntime-1.24.3-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d48f36c87b25ab3b2b4c88826c96cf1399a5631e3c2c03cc27d6a1e5d6b18eb4", size = 15151571, upload-time = "2026-03-05T16:35:05.679Z" }, + { url = "https://files.pythonhosted.org/packages/cf/14/c6fb84980cec8f682a523fcac7c2bdd6b311e7f342c61ce48d3a9cb87fc6/onnxruntime-1.24.3-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e104d33a409bf6e3f30f0e8198ec2aaf8d445b8395490a80f6e6ad56da98e400", size = 17238951, upload-time = "2026-03-05T17:18:12.394Z" }, + { url = "https://files.pythonhosted.org/packages/57/14/447e1400165aca8caf35dabd46540eb943c92f3065927bb4d9bcbc91e221/onnxruntime-1.24.3-cp314-cp314-win_amd64.whl", hash = "sha256:e785d73fbd17421c2513b0bb09eb25d88fa22c8c10c3f5d6060589efa5537c5b", size = 12903820, upload-time = "2026-03-05T17:18:57.123Z" }, + { url = "https://files.pythonhosted.org/packages/1d/ec/6b2fa5702e4bbba7339ca5787a9d056fc564a16079f8833cc6ba4798da1c/onnxruntime-1.24.3-cp314-cp314-win_arm64.whl", hash = "sha256:951e897a275f897a05ffbcaa615d98777882decaeb80c9216c68cdc62f849f53", size = 12594089, upload-time = "2026-03-05T17:18:47.169Z" }, + { url = "https://files.pythonhosted.org/packages/12/dc/cd06cba3ddad92ceb17b914a8e8d49836c79e38936e26bde6e368b62c1fe/onnxruntime-1.24.3-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4d4e70ce578aa214c74c7a7a9226bc8e229814db4a5b2d097333b81279ecde36", size = 15162789, upload-time = "2026-03-05T16:35:08.282Z" }, + { url = "https://files.pythonhosted.org/packages/a6/d6/413e98ab666c6fb9e8be7d1c6eb3bd403b0bea1b8d42db066dab98c7df07/onnxruntime-1.24.3-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:02aaf6ddfa784523b6873b4176a79d508e599efe12ab0ea1a3a6e7314408b7aa", size = 17240738, upload-time = "2026-03-05T17:18:15.203Z" }, +] + +[[package]] +name = "onnxruntime" +version = "1.31.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.15' and sys_platform == 'win32'", + "python_full_version >= '3.15' and sys_platform != 'win32'", + "python_full_version == '3.14.*' and sys_platform == 'win32'", + "python_full_version == '3.14.*' and sys_platform != 'win32'", + "python_full_version == '3.13.*' and sys_platform == 'win32'", + "python_full_version == '3.13.*' and sys_platform != 'win32'", + "python_full_version == '3.12.*'", + "python_full_version == '3.11.*'", +] +dependencies = [ + { name = "flatbuffers" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "numpy", version = "2.5.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "packaging" }, + { name = "protobuf" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/e7/61b2768393646bd12e31eeb71958193f4e02c98c4980cf9289d19bbb4a8f/onnxruntime-1.31.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:cbf1a7f6470ddfe9dbc781966af8ce4a10e1858d75a93f93cc6b9367c9587870", size = 20871717, upload-time = "2026-10-09T04:18:03.504Z" }, + { url = "https://files.pythonhosted.org/packages/44/86/e57025ab9c1eb83b6e686c92507fa6b7156d9d375e197a6c3a2afc05a1e2/onnxruntime-1.31.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:37c7dfe398550afdf9670a29315dbb88e49d8afc473ffaf1f410376efbb9c80a", size = 21413529, upload-time = "2026-10-09T04:18:06.493Z" }, + { url = "https://files.pythonhosted.org/packages/a6/72/6c57163b63b5343853d7f0619c4f424a6e53ee762d7263667ff004bfede1/onnxruntime-1.31.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:d4092b78fc5bab77ce6522393098cdb2535423045ecdcff15cc0d022162d6b66", size = 23753636, upload-time = "2026-10-09T04:18:09.974Z" }, + { url = "https://files.pythonhosted.org/packages/37/de/6cab7e39917cc87728d2f00abe97c81fe86b29f9e1f758627864c28f0c21/onnxruntime-1.31.0-cp311-cp311-win_amd64.whl", hash = "sha256:317608967b03807ed4661113b08293fac02a1db6496a6863a07d9f19232936ad", size = 14885750, upload-time = "2026-10-09T04:18:13.004Z" }, + { url = "https://files.pythonhosted.org/packages/1d/11/f335a124a1aadda99e5a2b618264606504bd9e3763b1b2486e6441cd65e5/onnxruntime-1.31.0-cp311-cp311-win_arm64.whl", hash = "sha256:e85c1632c0a8cf488bd8f1039f5320877b864c8f9ebd4122fb8bb909f83b7096", size = 14735138, upload-time = "2026-10-09T04:18:15.895Z" }, + { url = "https://files.pythonhosted.org/packages/b3/bd/2ac094311163b803e3626c3937461d6900934bd56cca7601f6150ff860c3/onnxruntime-1.31.0-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:aaab9b3af536b06ca27ab5e35e3d429c97457ce76cf298af103f687e8b9975c0", size = 20882054, upload-time = "2026-10-09T04:18:18.811Z" }, + { url = "https://files.pythonhosted.org/packages/53/1a/561b43ca1536d9e81d1785bb8a1a260a9e314ef6d04976ba0411c652bda1/onnxruntime-1.31.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:35758d7606d578ec5b9d65f6e8a1f488013194c3f6097038a3223cb26d35ef9a", size = 21420804, upload-time = "2026-10-09T04:18:21.729Z" }, + { url = "https://files.pythonhosted.org/packages/6c/44/1e9e762b95b7da0a8424913a1ed7c38cdaf88624a3c41ddba24ebac88bc9/onnxruntime-1.31.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:5e129d6c56abd53e659cb70f00a108d6824086470ff99c2e47a82e5786563db3", size = 23760984, upload-time = "2026-10-09T04:18:24.61Z" }, + { url = "https://files.pythonhosted.org/packages/be/ed/b12cea136ccd7b03d924f46b8393faf7ceac21115c0c50e729faa248cf23/onnxruntime-1.31.0-cp312-cp312-win_amd64.whl", hash = "sha256:09d56445c1753e66e0912de69d3f0184016ad9a191dcd6925bf5dd570d2bfbe5", size = 14888841, upload-time = "2026-10-09T04:18:27.62Z" }, + { url = "https://files.pythonhosted.org/packages/02/ad/37bbc51dcb5cd105c5b2fe98f122b23e90171c2719516964edc65bb1d4cc/onnxruntime-1.31.0-cp312-cp312-win_arm64.whl", hash = "sha256:5c54a0eb7b2b4eef3eb9dcfaf82f5ce880db07288dc309574f6657e9da5cc754", size = 14740604, upload-time = "2026-10-09T04:18:30.399Z" }, + { url = "https://files.pythonhosted.org/packages/e0/2b/117f94d73a3bac4276c285c47e384e1b3ea67b191aa4c7592df9d3f4a136/onnxruntime-1.31.0-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:0ba02a44acb6203040354d9a1f160e3f37a43feac7bb05caa3e0ea545efed505", size = 20881803, upload-time = "2026-10-09T04:18:33.62Z" }, + { url = "https://files.pythonhosted.org/packages/8a/d0/3677fe93ec0fa3c637744aa4c3ae6ef89a93ee229cd3c5157820f267c7bd/onnxruntime-1.31.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:ad663106f6eeff3d454f24a786450459d07f30e74863851104fc1b8b3f368127", size = 21420629, upload-time = "2026-10-09T04:18:36.731Z" }, + { url = "https://files.pythonhosted.org/packages/0d/ac/67ebbaab4b3083f2a6b27ee6c4aa400c7f8d6c72b5499aac7e4cd6ba74f5/onnxruntime-1.31.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:37fd78cee5160c7a43a1730ccb3682ffd880af9c9e80385d625c0c2f8b125809", size = 23760708, upload-time = "2026-10-09T04:18:40.883Z" }, + { url = "https://files.pythonhosted.org/packages/c4/86/05ed2056f43b27aaf12ebc592ebd9037a26bed315958cf882f43425fd469/onnxruntime-1.31.0-cp313-cp313-win_amd64.whl", hash = "sha256:73e0165d58ece068c2a8a1c477c90b38e5a8adbbd399fdfdfd4bd79cbc28ff8d", size = 14888306, upload-time = "2026-10-09T04:18:43.722Z" }, + { url = "https://files.pythonhosted.org/packages/c9/93/d33bae7b1a78780c4946ce03989c59a67d42d7015ad62d2098975fc5a580/onnxruntime-1.31.0-cp313-cp313-win_arm64.whl", hash = "sha256:e51d10d2e2e1e5bbf9b126a0cd9853d3e6c4e21424518dd50160b91471be33dc", size = 14740892, upload-time = "2026-10-09T04:18:46.338Z" }, + { url = "https://files.pythonhosted.org/packages/12/05/cf44f7642269b285aada4b662c4662b14ac63f6e03e129d939c4a956a0f5/onnxruntime-1.31.0-cp313-cp313t-manylinux_2_28_aarch64.whl", hash = "sha256:e0e050bf9ec754950a6ba9830e4032f4004d972c6f38c5642fef26d44d894965", size = 21432644, upload-time = "2026-10-09T04:18:48.925Z" }, + { url = "https://files.pythonhosted.org/packages/b5/8e/673315b2dd2eb99b2f4774d7a5986fe00d933ebed17ee72c441f579226e6/onnxruntime-1.31.0-cp313-cp313t-manylinux_2_28_x86_64.whl", hash = "sha256:e93d7c5fad20afa697ac16f376fd0306ed180f9a376e86106cc0b7d84f53ef87", size = 23773868, upload-time = "2026-10-09T04:18:51.776Z" }, + { url = "https://files.pythonhosted.org/packages/9d/fb/b4c52e500c6f3d00dfc22fad4d7513524f3ea2100a24a077ee3b0daf552d/onnxruntime-1.31.0-cp314-cp314-macosx_14_0_arm64.whl", hash = "sha256:278e0dc922ec69b05a28f59110d5421e2ec8b1d0dd46c6b10c063069a4051e72", size = 20883462, upload-time = "2026-10-09T04:18:54.978Z" }, + { url = "https://files.pythonhosted.org/packages/37/fb/8be04665b700cb6e874d944e9932bb3c3969d3f53e820f5c42bfd26565d0/onnxruntime-1.31.0-cp314-cp314-manylinux_2_28_aarch64.whl", hash = "sha256:984c0a2c1ad6a41fbc101dc3949abe4a72254892d01a5e70d9b792711e0bfa54", size = 21421618, upload-time = "2026-10-09T04:18:58.1Z" }, + { url = "https://files.pythonhosted.org/packages/30/2e/5c6ec7e26a097e97ee70f2dee68b8ca4d9d26701f2f33c3f8ab585cb89fe/onnxruntime-1.31.0-cp314-cp314-manylinux_2_28_x86_64.whl", hash = "sha256:e4efa4a1a0bb0b5173c6a3292c181d518b8323f9d56e978635d0c09d38c94d1a", size = 23762993, upload-time = "2026-10-09T04:19:01.236Z" }, + { url = "https://files.pythonhosted.org/packages/6a/66/0bf4fdb9f58efa69cf4eddde24c72aebcc628d6ff1d67c9546145c6b9922/onnxruntime-1.31.0-cp314-cp314-win_amd64.whl", hash = "sha256:83e3dbcf6abc6189c4bdf7d329c07ba1133c88172134c266d84b4409aa3b9dbf", size = 15268709, upload-time = "2026-10-09T04:19:04.2Z" }, + { url = "https://files.pythonhosted.org/packages/af/99/75a36172c1ed1d74ac0e91c11d642548081e2c9c63f15ee796564619556f/onnxruntime-1.31.0-cp314-cp314-win_arm64.whl", hash = "sha256:d2d5ac22f896c810be2b2b171392bb908f80b6c9a7e2d592ddb7435c928044e1", size = 15153795, upload-time = "2026-10-09T04:19:06.609Z" }, + { url = "https://files.pythonhosted.org/packages/9c/ec/23b7749edc7aad53bf4632de190399fda69a9195499426637ef1b02f06c6/onnxruntime-1.31.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:d25cd65874b75fdf16149120a04d0cd4551f860a3c8e2ecec785a1903e41d8aa", size = 21432344, upload-time = "2026-10-09T04:19:09.646Z" }, + { url = "https://files.pythonhosted.org/packages/f2/76/155ab0b265e9ceade28a8dd3858fdfa509b039f78010042c875940e32e58/onnxruntime-1.31.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:1ecc1450af28d2cf362990e188ccc81b51388f317f641ad973ab4301473200f2", size = 23772576, upload-time = "2026-10-09T04:19:12.731Z" }, +] + [[package]] name = "openai" version = "2.44.0" @@ -5043,6 +5200,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ec/bb/2799cc2ede3ed41131f8975621e7213dfc7ef4acbbaadfa440f32500c370/starlette-1.3.1-py3-none-any.whl", hash = "sha256:c7372aae11c3c3f26a42df7bd626cec2f47d03483d261d369516a615a53714c6", size = 73632, upload-time = "2026-06-12T09:23:10.017Z" }, ] +[[package]] +name = "sympy" +version = "1.14.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mpmath" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl", hash = "sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", size = 6299353, upload-time = "2025-04-27T18:04:59.103Z" }, +] + [[package]] name = "tenacity" version = "9.1.4"