genkit-a2ui 0.12.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- genkit_a2ui/__init__.py +42 -0
- genkit_a2ui/_catalog.py +353 -0
- genkit_a2ui/_loader.py +108 -0
- genkit_a2ui/_middleware.py +332 -0
- genkit_a2ui/_parser.py +345 -0
- genkit_a2ui/_part.py +62 -0
- genkit_a2ui/_types.py +32 -0
- genkit_a2ui-0.12.0.dist-info/METADATA +92 -0
- genkit_a2ui-0.12.0.dist-info/RECORD +11 -0
- genkit_a2ui-0.12.0.dist-info/WHEEL +4 -0
- genkit_a2ui-0.12.0.dist-info/licenses/LICENSE +201 -0
genkit_a2ui/__init__.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# Copyright 2026 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
#
|
|
15
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
16
|
+
|
|
17
|
+
"""A2UI generate middleware for Genkit."""
|
|
18
|
+
|
|
19
|
+
from ._catalog import A2uiCatalog, A2uiCatalogComponent
|
|
20
|
+
from ._loader import A2uiCatalogError, load_catalog, load_catalog_file, register_basic_catalog
|
|
21
|
+
from ._middleware import Surfaces, SurfacesConfig
|
|
22
|
+
from ._parser import A2uiParseError
|
|
23
|
+
from ._part import a2ui_part, envelopes_from_parts, is_a2ui_part
|
|
24
|
+
from ._types import A2UI_CATALOG_VALUE_TYPE, A2UI_MIME_TYPE, DEFAULT_CATALOG_ID
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
'A2UI_CATALOG_VALUE_TYPE',
|
|
28
|
+
'A2UI_MIME_TYPE',
|
|
29
|
+
'DEFAULT_CATALOG_ID',
|
|
30
|
+
'A2uiCatalog',
|
|
31
|
+
'A2uiCatalogComponent',
|
|
32
|
+
'A2uiCatalogError',
|
|
33
|
+
'A2uiParseError',
|
|
34
|
+
'Surfaces',
|
|
35
|
+
'SurfacesConfig',
|
|
36
|
+
'a2ui_part',
|
|
37
|
+
'envelopes_from_parts',
|
|
38
|
+
'is_a2ui_part',
|
|
39
|
+
'load_catalog',
|
|
40
|
+
'load_catalog_file',
|
|
41
|
+
'register_basic_catalog',
|
|
42
|
+
]
|
genkit_a2ui/_catalog.py
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
# Copyright 2026 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
#
|
|
15
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
16
|
+
|
|
17
|
+
"""Bundled basic catalog and the system-prompt instructions it produces."""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from string import Template
|
|
23
|
+
from typing import Any, cast
|
|
24
|
+
|
|
25
|
+
from ._types import BASIC_CATALOG_ID
|
|
26
|
+
|
|
27
|
+
BASIC_ICON_NAMES = (
|
|
28
|
+
'accountCircle',
|
|
29
|
+
'add',
|
|
30
|
+
'arrowBack',
|
|
31
|
+
'arrowForward',
|
|
32
|
+
'attachFile',
|
|
33
|
+
'calendarToday',
|
|
34
|
+
'call',
|
|
35
|
+
'camera',
|
|
36
|
+
'check',
|
|
37
|
+
'close',
|
|
38
|
+
'delete',
|
|
39
|
+
'download',
|
|
40
|
+
'edit',
|
|
41
|
+
'event',
|
|
42
|
+
'error',
|
|
43
|
+
'fastForward',
|
|
44
|
+
'favorite',
|
|
45
|
+
'favoriteOff',
|
|
46
|
+
'folder',
|
|
47
|
+
'help',
|
|
48
|
+
'home',
|
|
49
|
+
'info',
|
|
50
|
+
'locationOn',
|
|
51
|
+
'lock',
|
|
52
|
+
'lockOpen',
|
|
53
|
+
'mail',
|
|
54
|
+
'menu',
|
|
55
|
+
'moreVert',
|
|
56
|
+
'moreHoriz',
|
|
57
|
+
'notificationsOff',
|
|
58
|
+
'notifications',
|
|
59
|
+
'pause',
|
|
60
|
+
'payment',
|
|
61
|
+
'person',
|
|
62
|
+
'phone',
|
|
63
|
+
'photo',
|
|
64
|
+
'play',
|
|
65
|
+
'print',
|
|
66
|
+
'refresh',
|
|
67
|
+
'rewind',
|
|
68
|
+
'search',
|
|
69
|
+
'send',
|
|
70
|
+
'settings',
|
|
71
|
+
'share',
|
|
72
|
+
'shoppingCart',
|
|
73
|
+
'skipNext',
|
|
74
|
+
'skipPrevious',
|
|
75
|
+
'star',
|
|
76
|
+
'starHalf',
|
|
77
|
+
'starOff',
|
|
78
|
+
'stop',
|
|
79
|
+
'upload',
|
|
80
|
+
'visibility',
|
|
81
|
+
'visibilityOff',
|
|
82
|
+
'volumeDown',
|
|
83
|
+
'volumeMute',
|
|
84
|
+
'volumeOff',
|
|
85
|
+
'volumeUp',
|
|
86
|
+
'warning',
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@dataclass(frozen=True)
|
|
91
|
+
class A2uiCatalogComponent:
|
|
92
|
+
name: str
|
|
93
|
+
description: str
|
|
94
|
+
props: str
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass(frozen=True)
|
|
98
|
+
class A2uiCatalog:
|
|
99
|
+
id: str
|
|
100
|
+
components: tuple[A2uiCatalogComponent, ...]
|
|
101
|
+
|
|
102
|
+
def as_value(self) -> dict[str, object]:
|
|
103
|
+
return {
|
|
104
|
+
'id': self.id,
|
|
105
|
+
'components': [{'name': c.name, 'description': c.description, 'props': c.props} for c in self.components],
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
@staticmethod
|
|
109
|
+
def from_value(value: object) -> A2uiCatalog | None:
|
|
110
|
+
if isinstance(value, A2uiCatalog):
|
|
111
|
+
return value
|
|
112
|
+
if not isinstance(value, dict):
|
|
113
|
+
return None
|
|
114
|
+
payload = cast(dict[str, Any], value)
|
|
115
|
+
catalog_id = payload.get('id')
|
|
116
|
+
raw = payload.get('components')
|
|
117
|
+
if not isinstance(catalog_id, str) or not catalog_id or not isinstance(raw, list):
|
|
118
|
+
return None
|
|
119
|
+
components: list[A2uiCatalogComponent] = []
|
|
120
|
+
for item in raw:
|
|
121
|
+
row = cast(dict[str, Any], item) if isinstance(item, dict) else None
|
|
122
|
+
if row is None or not isinstance(row.get('name'), str):
|
|
123
|
+
return None
|
|
124
|
+
components.append(
|
|
125
|
+
A2uiCatalogComponent(
|
|
126
|
+
name=row['name'],
|
|
127
|
+
description=row['description'] if isinstance(row.get('description'), str) else '',
|
|
128
|
+
props=row['props'] if isinstance(row.get('props'), str) else '',
|
|
129
|
+
)
|
|
130
|
+
)
|
|
131
|
+
return A2uiCatalog(id=catalog_id, components=tuple(components))
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
BASIC_CATALOG = A2uiCatalog(
|
|
135
|
+
id=BASIC_CATALOG_ID,
|
|
136
|
+
components=(
|
|
137
|
+
A2uiCatalogComponent(
|
|
138
|
+
name='Text',
|
|
139
|
+
description=(
|
|
140
|
+
'Displays a run of text. For headings/titles set the `variant` prop '
|
|
141
|
+
'(h1..h5) rather than embedding Markdown; the text itself may use '
|
|
142
|
+
'inline Markdown.'
|
|
143
|
+
),
|
|
144
|
+
props='text: string (required); variant?: one of h1|h2|h3|h4|h5|caption|body.',
|
|
145
|
+
),
|
|
146
|
+
A2uiCatalogComponent(
|
|
147
|
+
name='Image',
|
|
148
|
+
description='Displays an image from a URL.',
|
|
149
|
+
props=(
|
|
150
|
+
'url: string (required); description?: string; '
|
|
151
|
+
'fit?: contain|cover|fill|none|scaleDown; '
|
|
152
|
+
'variant?: icon|avatar|smallFeature|mediumFeature|largeFeature|header.'
|
|
153
|
+
),
|
|
154
|
+
),
|
|
155
|
+
A2uiCatalogComponent(
|
|
156
|
+
name='Icon',
|
|
157
|
+
description=(
|
|
158
|
+
'Displays a named material icon. `name` MUST be one of the exact names '
|
|
159
|
+
'listed below — do NOT invent names (e.g. there is no "cloud", "air", '
|
|
160
|
+
'or "thermostat"). If none fits, omit the Icon rather than guessing.'
|
|
161
|
+
),
|
|
162
|
+
props=f'name: one of {", ".join(BASIC_ICON_NAMES)} (required, exact).',
|
|
163
|
+
),
|
|
164
|
+
A2uiCatalogComponent(
|
|
165
|
+
name='Row',
|
|
166
|
+
description='Lays out children horizontally.',
|
|
167
|
+
props=(
|
|
168
|
+
'children: string[] of component ids (required); '
|
|
169
|
+
'justify?: start|center|end|spaceAround|spaceBetween|spaceEvenly|stretch; '
|
|
170
|
+
'align?: start|center|end|stretch.'
|
|
171
|
+
),
|
|
172
|
+
),
|
|
173
|
+
A2uiCatalogComponent(
|
|
174
|
+
name='Column',
|
|
175
|
+
description='Lays out children vertically.',
|
|
176
|
+
props=(
|
|
177
|
+
'children: string[] of component ids (required); '
|
|
178
|
+
'justify?: start|center|end|spaceBetween|spaceAround|spaceEvenly|stretch; '
|
|
179
|
+
'align?: start|center|end|stretch.'
|
|
180
|
+
),
|
|
181
|
+
),
|
|
182
|
+
A2uiCatalogComponent(
|
|
183
|
+
name='List',
|
|
184
|
+
description='A list of children.',
|
|
185
|
+
props=(
|
|
186
|
+
'children: string[] of component ids (required); '
|
|
187
|
+
'direction?: vertical|horizontal; listStyle?: ordered|unordered|none.'
|
|
188
|
+
),
|
|
189
|
+
),
|
|
190
|
+
A2uiCatalogComponent(
|
|
191
|
+
name='Card',
|
|
192
|
+
description='A visually-contained card wrapping a single child.',
|
|
193
|
+
props='child: string id of a single child component (required; wrap multiple in a Column/Row).',
|
|
194
|
+
),
|
|
195
|
+
A2uiCatalogComponent(
|
|
196
|
+
name='Divider',
|
|
197
|
+
description='A horizontal or vertical separator line.',
|
|
198
|
+
props='axis?: horizontal|vertical.',
|
|
199
|
+
),
|
|
200
|
+
A2uiCatalogComponent(
|
|
201
|
+
name='Button',
|
|
202
|
+
description='A clickable button that fires an action back to the agent.',
|
|
203
|
+
props=(
|
|
204
|
+
'child: string id of a child (usually a Text) (required); '
|
|
205
|
+
'variant?: default|primary|borderless; '
|
|
206
|
+
'action: { event: { name: string, context?: object } } '
|
|
207
|
+
'(required — the event name is sent back to the agent when clicked).'
|
|
208
|
+
),
|
|
209
|
+
),
|
|
210
|
+
A2uiCatalogComponent(
|
|
211
|
+
name='TextField',
|
|
212
|
+
description='A single- or multi-line text input.',
|
|
213
|
+
props=(
|
|
214
|
+
'label: string (required); value?: string or { path } binding; '
|
|
215
|
+
'variant?: shortText|longText|number|obscured.'
|
|
216
|
+
),
|
|
217
|
+
),
|
|
218
|
+
A2uiCatalogComponent(
|
|
219
|
+
name='CheckBox',
|
|
220
|
+
description='A labeled checkbox.',
|
|
221
|
+
props='label: string (required); value: boolean or { path } binding (required).',
|
|
222
|
+
),
|
|
223
|
+
A2uiCatalogComponent(
|
|
224
|
+
name='Slider',
|
|
225
|
+
description='A numeric slider.',
|
|
226
|
+
props=(
|
|
227
|
+
'max: number (required); value: number or { path } binding (required); '
|
|
228
|
+
'label?: string; min?: number; step?: number.'
|
|
229
|
+
),
|
|
230
|
+
),
|
|
231
|
+
),
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
FORMS_SECTION = Template("""
|
|
236
|
+
- Forms: input components ($input_list) do NOT send their values automatically.
|
|
237
|
+
To capture what the user entered you MUST do BOTH of these:
|
|
238
|
+
1. Bind each input's `value` to a data-model path, e.g.
|
|
239
|
+
`{ "component": "TextField", "label": "Email", "value": { "path": "/email" } }`.
|
|
240
|
+
Typing updates the data model at that path.
|
|
241
|
+
2. On the submit `Button`, echo those same paths in
|
|
242
|
+
`action.event.context` so their current values are sent back to you, e.g.
|
|
243
|
+
`"context": { "email": { "path": "/email" }, "name": { "path": "/name" } }`.
|
|
244
|
+
Without the `{ path }` bindings and the button `context`, the action arrives
|
|
245
|
+
with an empty `context` and the entered values are lost.""")
|
|
246
|
+
|
|
247
|
+
WEATHER_EXAMPLE = Template("""
|
|
248
|
+
|
|
249
|
+
Example (a small weather card):
|
|
250
|
+
```a2ui
|
|
251
|
+
[
|
|
252
|
+
{ "createSurface": { "surfaceId": "SURFACE_ID", "catalogId": "$catalog_id" } },
|
|
253
|
+
{ "updateComponents": { "surfaceId": "SURFACE_ID", "components": [
|
|
254
|
+
{ "id": "root", "component": "Card", "child": "body" },
|
|
255
|
+
{ "id": "body", "component": "Column", "children": ["title", "temp"] },
|
|
256
|
+
{ "id": "title", "component": "Text", "text": "Weather in Tokyo", "variant": "h3" },
|
|
257
|
+
{ "id": "temp", "component": "Text", "text": { "path": "/temp" } }
|
|
258
|
+
] } },
|
|
259
|
+
{ "updateDataModel": { "surfaceId": "SURFACE_ID", "path": "/temp", "value": "18°C" } }
|
|
260
|
+
]
|
|
261
|
+
```""")
|
|
262
|
+
|
|
263
|
+
MINIMAL_EXAMPLE = Template("""
|
|
264
|
+
|
|
265
|
+
Example (a minimal surface):
|
|
266
|
+
```a2ui
|
|
267
|
+
[
|
|
268
|
+
{ "createSurface": { "surfaceId": "SURFACE_ID", "catalogId": "$catalog_id" } },
|
|
269
|
+
{ "updateComponents": { "surfaceId": "SURFACE_ID", "components": [
|
|
270
|
+
{ "id": "root", "component": "$root" }
|
|
271
|
+
] } }
|
|
272
|
+
]
|
|
273
|
+
```""")
|
|
274
|
+
|
|
275
|
+
INSTRUCTIONS = Template("""# Rendering UI with A2UI
|
|
276
|
+
|
|
277
|
+
You can render rich, interactive UI (not just text) by emitting an A2UI surface.
|
|
278
|
+
When a result is better *shown* than *told* (weather, lists, forms, comparisons,
|
|
279
|
+
confirmations, anything visual or interactive), render a UI surface.
|
|
280
|
+
|
|
281
|
+
To render UI, output a single fenced code block tagged `a2ui` containing a JSON
|
|
282
|
+
array of A2UI envelope messages. You may still write normal prose before it.
|
|
283
|
+
|
|
284
|
+
Rules:
|
|
285
|
+
- The UI is an ADJACENCY LIST: a flat array of components. Build the tree using
|
|
286
|
+
string `id` references, NOT nested objects. Exactly one component MUST have
|
|
287
|
+
`id: "root"`.
|
|
288
|
+
- Every component has a `component` (type name) and an `id`. Container
|
|
289
|
+
components reference their children by id via a `children` array; single-child
|
|
290
|
+
wrappers reference one `child` id.
|
|
291
|
+
- Values can be literals, or a data-model binding `{ "path": "/somePath" }`.
|
|
292
|
+
- Use `createSurface` first (with `catalogId`), then `updateComponents` to add
|
|
293
|
+
the component list, then optionally `updateDataModel` to set data. You may
|
|
294
|
+
combine them in one array, in order.
|
|
295
|
+
- Interactive components fire an `action` with an event `name`; that name is
|
|
296
|
+
sent back to you when the user interacts, so choose meaningful names.$forms_section
|
|
297
|
+
- When a user interacts with a surface (e.g. presses a button) and you respond
|
|
298
|
+
with updated UI, RE-RENDER THE WHOLE SURFACE: start again with
|
|
299
|
+
`createSurface` followed by `updateComponents`. Do not emit a bare
|
|
300
|
+
`updateDataModel`/`updateComponents` expecting a previous surface to still
|
|
301
|
+
exist.$style_section
|
|
302
|
+
|
|
303
|
+
The catalogId to use is:
|
|
304
|
+
"$catalog_id"
|
|
305
|
+
|
|
306
|
+
Available components:
|
|
307
|
+
$component_docs$example_section
|
|
308
|
+
|
|
309
|
+
Do not explain the JSON; just render the block. Use "SURFACE_ID" literally as a
|
|
310
|
+
placeholder for the surface id — the system replaces it with a real id.""")
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def render_catalog_instructions(catalog: A2uiCatalog) -> str:
|
|
314
|
+
has = {c.name for c in catalog.components}
|
|
315
|
+
inputs = [name for name in ('TextField', 'CheckBox', 'Slider') if name in has]
|
|
316
|
+
forms_section = FORMS_SECTION.substitute(input_list=', '.join(inputs)) if inputs else ''
|
|
317
|
+
return INSTRUCTIONS.substitute(
|
|
318
|
+
forms_section=forms_section,
|
|
319
|
+
style_section=render_style_tips(has=has),
|
|
320
|
+
catalog_id=catalog.id,
|
|
321
|
+
component_docs='\n'.join(f'- {c.name}: {c.description} Props: {c.props}' for c in catalog.components),
|
|
322
|
+
example_section=render_example(catalog=catalog, has=has),
|
|
323
|
+
)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def render_style_tips(*, has: set[str]) -> str:
|
|
327
|
+
tips: list[str] = []
|
|
328
|
+
containers = [c for c in ('Card', 'Column', 'Row') if c in has]
|
|
329
|
+
if containers:
|
|
330
|
+
tips.append(
|
|
331
|
+
f'- Group related content with layout components ({"/".join(containers)}) and give it a clear hierarchy.'
|
|
332
|
+
)
|
|
333
|
+
if 'Text' in has:
|
|
334
|
+
tips.append(
|
|
335
|
+
'- Give titles a heading `variant` (e.g. h2/h3) and secondary text the '
|
|
336
|
+
'`caption` variant instead of embedding "#"/"##" heading markers in '
|
|
337
|
+
'the text.'
|
|
338
|
+
)
|
|
339
|
+
accents = [c for c in ('Icon', 'Divider', 'Image') if c in has]
|
|
340
|
+
if accents:
|
|
341
|
+
tips.append(f'- Use {"/".join(accents)} to add visual meaning and separate sections where it helps.')
|
|
342
|
+
if 'Button' in has:
|
|
343
|
+
tips.append('- Give primary buttons `variant: "primary"`.')
|
|
344
|
+
if not tips:
|
|
345
|
+
return ''
|
|
346
|
+
return '\n\nMake it look good, not bland:\n' + '\n'.join(tips)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def render_example(*, catalog: A2uiCatalog, has: set[str]) -> str:
|
|
350
|
+
if {'Card', 'Column', 'Text'} <= has:
|
|
351
|
+
return WEATHER_EXAMPLE.substitute(catalog_id=catalog.id)
|
|
352
|
+
root = catalog.components[0].name if catalog.components else 'Text'
|
|
353
|
+
return MINIMAL_EXAMPLE.substitute(catalog_id=catalog.id, root=root)
|
genkit_a2ui/_loader.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# Copyright 2026 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
#
|
|
15
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
16
|
+
|
|
17
|
+
"""Register A2UI catalogs so generate and the Developer UI can find them."""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import json
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
from genkit._core._error import GenkitError, RuntimeErrorReason
|
|
25
|
+
from genkit._core._logger import get_logger
|
|
26
|
+
from genkit._core._protocols import GenkitLike, RegistryLike
|
|
27
|
+
|
|
28
|
+
from ._catalog import BASIC_CATALOG, A2uiCatalog
|
|
29
|
+
from ._types import A2UI_CATALOG_VALUE_TYPE, BASIC_CATALOG_ID, DEFAULT_CATALOG_ID
|
|
30
|
+
|
|
31
|
+
logger = get_logger(__name__)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class A2uiCatalogError(GenkitError):
|
|
35
|
+
"""Raised when a catalog cannot be read, registered, or resolved.
|
|
36
|
+
|
|
37
|
+
`load_catalog` and `load_catalog_file` raise this at startup, so a bad
|
|
38
|
+
catalog file fails loudly before any model call. `resolve_catalog` runs
|
|
39
|
+
inside the model call instead, so an unregistered catalog id comes back as a
|
|
40
|
+
failed `ModelResponse` with the reason on `finish_message`.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(self, message: str) -> None:
|
|
44
|
+
# A catalog you did not register, or a file that does not parse, is a
|
|
45
|
+
# bad argument, not a bad model answer. Mirrors Go's
|
|
46
|
+
# ErrInvalidInput = ErrInvalidArgument.Subtype("invalid input").
|
|
47
|
+
super().__init__(
|
|
48
|
+
status='INVALID_ARGUMENT',
|
|
49
|
+
message=message,
|
|
50
|
+
reason=RuntimeErrorReason.INVALID_INPUT,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def load_catalog(ai: GenkitLike, catalog: A2uiCatalog) -> A2uiCatalog:
|
|
55
|
+
if not catalog.id:
|
|
56
|
+
raise A2uiCatalogError('a2ui: load_catalog: catalog has no id')
|
|
57
|
+
existing = ai.registry.lookup_value(A2UI_CATALOG_VALUE_TYPE, catalog.id)
|
|
58
|
+
if existing is not None:
|
|
59
|
+
current = A2uiCatalog.from_value(existing)
|
|
60
|
+
if current is None:
|
|
61
|
+
raise A2uiCatalogError(f'a2ui: load_catalog: registry value {catalog.id!r} is not a catalog')
|
|
62
|
+
if current != catalog:
|
|
63
|
+
logger.warning(
|
|
64
|
+
'a2ui: load_catalog: a different catalog is already registered under this id; keeping the existing one'
|
|
65
|
+
)
|
|
66
|
+
return current
|
|
67
|
+
ai.registry.register_value(A2UI_CATALOG_VALUE_TYPE, catalog.id, catalog.as_value())
|
|
68
|
+
return catalog
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def load_catalog_file(ai: GenkitLike, path: str) -> A2uiCatalog:
|
|
72
|
+
return load_catalog(ai, read_catalog_file(path=path))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def register_basic_catalog(ai: GenkitLike) -> A2uiCatalog:
|
|
76
|
+
return load_catalog(ai, BASIC_CATALOG)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def read_catalog_file(*, path: str) -> A2uiCatalog:
|
|
80
|
+
try:
|
|
81
|
+
raw = json.loads(Path(path).read_text(encoding='utf-8'))
|
|
82
|
+
except (OSError, UnicodeDecodeError) as exc:
|
|
83
|
+
raise A2uiCatalogError(f'a2ui: failed to read catalog file {path!r}: {exc}') from exc
|
|
84
|
+
except json.JSONDecodeError as exc:
|
|
85
|
+
raise A2uiCatalogError(f'a2ui: catalog file {path!r} is not valid JSON: {exc}') from exc
|
|
86
|
+
catalog = A2uiCatalog.from_value(raw)
|
|
87
|
+
if catalog is None:
|
|
88
|
+
raise A2uiCatalogError(
|
|
89
|
+
f'a2ui: catalog file {path!r} is not a catalog '
|
|
90
|
+
'(need an id, a components array, and a name on every component)'
|
|
91
|
+
)
|
|
92
|
+
return catalog
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def resolve_catalog(*, registry: RegistryLike, catalog: str | None) -> A2uiCatalog:
|
|
96
|
+
lookup = catalog or DEFAULT_CATALOG_ID
|
|
97
|
+
found = registry.lookup_value(A2UI_CATALOG_VALUE_TYPE, lookup)
|
|
98
|
+
if found is not None:
|
|
99
|
+
resolved = A2uiCatalog.from_value(found)
|
|
100
|
+
if resolved is None:
|
|
101
|
+
raise A2uiCatalogError(f'a2ui: registry value {lookup!r} is not a catalog')
|
|
102
|
+
return resolved
|
|
103
|
+
if lookup in {DEFAULT_CATALOG_ID, BASIC_CATALOG_ID}:
|
|
104
|
+
return BASIC_CATALOG
|
|
105
|
+
raise A2uiCatalogError(
|
|
106
|
+
f'a2ui: no catalog registered under id {lookup!r}; '
|
|
107
|
+
f'register one with load_catalog(ai, catalog) or use the default {DEFAULT_CATALOG_ID!r} catalog'
|
|
108
|
+
)
|