### GenUI Functions Source: https://pub.dev/documentation/genui/latest/genui Utility functions for converting catalog examples, configuring logging, generating prompts, parsing tool calls, and resolving context. ```APIDOC ## Functions ### `catalogExampleToToolCall` - **Description**: Converts a catalog example to a ToolCall. - **Parameters**: - `example` (JsonMap) - The catalog example to convert. - `toolName` (String) - The name of the tool. - `surfaceId` (String) - The ID of the surface. - **Returns**: `ToolCall` ### `catalogToFunctionDeclaration` - **Description**: Converts a Catalog to a GenUiFunctionDeclaration. - **Parameters**: - `catalog` (Catalog) - The catalog to convert. - `toolName` (String) - The name of the tool. - `toolDescription` (String) - The description of the tool. - **Returns**: `GenUiFunctionDeclaration` ### `configureGenUiLogging` - **Description**: Configures the logging for the GenUI package. - **Parameters**: - `level` (Level) - Optional. The logging level. Defaults to `Level.INFO`. - `logCallback` (void Function(Level, String)?) - Optional. A callback function for logging. - **Returns**: `Logger` ### `genUiTechPrompt` - **Description**: Generates a prompt for the LLM about how to use the UI generation tools. - **Parameters**: - `toolNames` (List) - A list of tool names. - **Returns**: `String` ### `parseToolCall` - **Description**: Parses a ToolCall into a ParsedToolCall. - **Parameters**: - `toolCall` (ToolCall) - The ToolCall to parse. - `toolName` (String) - The name of the tool. - **Returns**: `ParsedToolCall` ### `resolveContext` - **Description**: Resolves a context map definition against a DataContext. - **Parameters**: - `dataContext` (DataContext) - The DataContext to resolve against. - `contextDefinitions` (List) - A list of context definitions. - **Returns**: `JsonMap` ``` -------------------------------- ### catalogExampleToToolCall Function Source: https://pub.dev/documentation/genui/latest/genui/catalogExampleToToolCall This function takes a JSON map representing a catalog example and converts it into a ToolCall object. It is used to generate UI surface updates based on provided examples. ```APIDOC ## catalogExampleToToolCall Function ### Description Converts a catalog example (provided as a JsonMap) into a ToolCall object. This is useful for dynamic updates to UI surfaces. ### Method N/A (This is a function, not an HTTP endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **example** (JsonMap) - Required - A JSON map representing the catalog example to be converted. * **toolName** (String) - Required - The name of the tool to be associated with the ToolCall. * **surfaceId** (String) - Required - The identifier of the UI surface to be updated. ### Request Example ```json { "example": { "type": "button", "properties": { "text": "Click Me", "color": "blue" } }, "toolName": "updateSurface", "surfaceId": "main-content" } ``` ### Response #### Success Response (200) * **ToolCall** (Object) - The generated ToolCall object. * **name** (String) - The name of the tool. * **args** (Object) - The arguments for the tool call. * **surfaceId** (String) - The ID of the surface to update. * **surfaceUpdate** (Object) - The data for the surface update. #### Response Example ```json { "name": "updateSurface", "args": { "surfaceId": "main-content", "surfaceUpdate": { "type": "button", "properties": { "text": "Click Me", "color": "blue" } } } } ``` ``` -------------------------------- ### Convert Catalog Example to ToolCall (Dart) Source: https://pub.dev/documentation/genui/latest/genui/catalogExampleToToolCall The catalogExampleToToolCall function takes a JsonMap example, a toolName string, and a surfaceId string as input. It converts the provided catalog example into a structured ToolCall object. This is useful for integrating catalog data into a tool's functionality. ```dart ToolCall catalogExampleToToolCall( JsonMap example, String toolName, String surfaceId, ) { final messageJson = {'surfaceUpdate': example}; final surfaceUpdateMessage = A2uiMessage.fromJson(messageJson); return ToolCall( name: toolName, args: {surfaceIdKey: surfaceId, 'surfaceUpdate': surfaceUpdateMessage}, ); } ``` -------------------------------- ### Configure GenUI Logging in Dart Source: https://pub.dev/documentation/genui/latest/index Provides an example of how to configure logging for the GenUI package. This involves importing the necessary libraries and setting the desired log level to observe communication between the app and the agent. ```dart import 'package:logging/logging.dart'; import 'package:genui/genui.dart'; final logger = configureGenUiLogging(level: Level.ALL); void main() async { logger.onRecord.listen((record) { debugPrint('${record.loggerName}: ${record.message}'); }); // Additional initialization of bindings and Firebase. } ``` -------------------------------- ### Generate UI Tech Prompt Source: https://pub.dev/documentation/genui/latest/genui/genUiTechPrompt Generates a prompt for an LLM to guide UI generation. It takes a list of tool names and constructs a detailed prompt including instructions on using tool names, surface IDs for UI creation/updates, and root component identification. ```APIDOC ## POST /generateUiTechPrompt ### Description Generates a prompt for an LLM to guide UI generation. This endpoint takes a list of tool names and constructs a detailed prompt including instructions on using tool names, surface IDs for UI creation/updates, and root component identification. ### Method POST ### Endpoint /generateUiTechPrompt ### Parameters #### Query Parameters - **toolNames** (List) - Required - A list of names of the UI generation tools to be included in the prompt. ### Request Body (No request body is expected for this endpoint, parameters are passed via query) ### Request Example (Not applicable as parameters are query parameters) ### Response #### Success Response (200) - **prompt** (String) - The generated prompt string for the LLM. #### Response Example ```json { "prompt": "To show generated UI, use the following UI generation tools: \"ToolA\", \"ToolB\".\nWhen generating UI, always provide a unique surfaceIdKey to identify the UI surface:\n* To create new UI, use a new surfaceIdKey.\n* To update existing UI, use the existing surfaceIdKey.\n\nUse the root component id: 'root'.\nEnsure one of the generated components has an id of 'root'." } ``` ``` -------------------------------- ### Generate LLM Prompt for UI Tools (Dart) Source: https://pub.dev/documentation/genui/latest/genui/genUiTechPrompt Generates a prompt string for an LLM to guide UI generation. It specifies the available tools and enforces the use of unique surface IDs for UI elements, ensuring a 'root' component is always included. Dependencies include the 'toolNames' list, which should contain strings representing the names of UI generation tools. ```dart String genUiTechPrompt(List toolNames) { final toolDescription = toolNames.length > 1 ? 'the following UI generation tools: ' '${toolNames.map((name) => '"$name"').join(', ')}' : 'the UI generation tool "${toolNames.first}"'; return ''' To show generated UI, use $toolDescription. When generating UI, always provide a unique $surfaceIdKey to identify the UI surface: * To create new UI, use a new $surfaceIdKey. * To update existing UI, use the existing $surfaceIdKey. Use the root component id: 'root'. Ensure one of the generated components has an id of 'root'. '''; } ``` -------------------------------- ### Generate Schema for UI Components and Styles (Dart) Source: https://pub.dev/documentation/genui/latest/genui/Catalog/definition Dynamically creates a JSON schema describing available UI components and styles. It processes a list of items to build a 'one-of' schema for component properties, enabling AI models to understand UI element structures. The schema includes definitions for 'components' and 'styles'. ```dart Schema get definition { final Map componentProperties = { for (var item in items) item.name: item.dataSchema, }; return S.object( title: 'A2UI Catalog Description Schema', description: 'A schema for a custom Catalog Description including A2UI ' 'components and styles.', properties: { 'components': S.object( title: 'A2UI Components', description: 'A schema that defines a catalog of A2UI components. ' 'Each key is a component name, and each value is the JSON ' 'schema for that component\'s properties.', properties: componentProperties, ), 'styles': S.object( title: 'A2UI Styles', description: 'A schema that defines a catalog of A2UI styles. Each key is a ' 'style name, and each value is the JSON schema for that style\'s ' 'properties.', properties: {}, ), }, required: ['components', 'styles'], ); } ``` -------------------------------- ### BeginRenderingTool Constructor Source: https://pub.dev/documentation/genui/latest/genui/BeginRenderingTool/BeginRenderingTool Constructs a BeginRenderingTool, which signals the client to begin rendering a surface with a root component. ```APIDOC ## BeginRenderingTool constructor ### Description Creates a BeginRenderingTool. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **handleMessage** (void Function(A2uiMessage)) - Required - A callback function to handle messages. * **surfaceIdKey** (string) - Required - The unique identifier for the UI surface to render. * **root** (string) - Required - The ID of the root widget. This ID must correspond to the ID of one of the widgets in the `components` list. ### Request Example ```json { "handleMessage": "function(message) { ... }", "surfaceIdKey": "uniqueSurfaceId", "root": "rootWidgetId" } ``` ### Response #### Success Response (200) This constructor does not return a value directly, but initializes the BeginRenderingTool. #### Response Example N/A ``` -------------------------------- ### Validate Catalog Item Examples (Dart) Source: https://pub.dev/documentation/genui/latest/test_validation/validateCatalogItemExamples Validates example data within a single catalog item against a provided schema. It parses JSON, checks for a 'root' component, and performs schema validation. Dependencies include `dart:convert`, `A2uiSchemas`, `CatalogItem`, `Catalog`, `Schema`, `ExampleValidationError`, `Component`, `SurfaceUpdate`, and `ValidationError`. Returns a list of `ExampleValidationError`. ```dart Future> validateCatalogItemExamples( CatalogItem item, Catalog catalog, ) async { final Schema schema = A2uiSchemas.surfaceUpdateSchema(catalog); final errors = []; for (var i = 0; i < item.exampleData.length; i++) { final String exampleJsonString = item.exampleData[i](); final List exampleData; try { exampleData = jsonDecode(exampleJsonString) as List; } catch (e) { errors.add( ExampleValidationError(i, 'Failed to parse as a JSON list', cause: e), ); continue; } final List components = exampleData.map((e) => Component.fromJson(e as JsonMap)).toList(); if (components.every((c) => c.id != 'root')) { errors.add( ExampleValidationError( i, 'Example must have a component with id "root"', ), ); } final surfaceUpdate = SurfaceUpdate( surfaceId: 'test-surface', components: components, ); final List validationErrors = await schema.validate( surfaceUpdate.toJson(), ); if (validationErrors.isNotEmpty) { errors.add( ExampleValidationError( i, 'Schema validation failed', cause: validationErrors, ), ); } } return errors; } ``` -------------------------------- ### BeginRendering Class Documentation Source: https://pub.dev/documentation/genui/latest/genui/BeginRendering-class Provides detailed information about the BeginRendering class, including its purpose, inheritance, constructors, properties, and methods. ```APIDOC ## Class: BeginRendering ### Description An A2UI message that signals the client to begin rendering. ### Inheritance * Object * A2uiMessage * BeginRendering ### Constructors #### `BeginRendering({required String surfaceId, required String root, JsonMap? styles})` Creates a BeginRendering message. * **surfaceId** (String) - Required - The ID of the surface that this message applies to. * **root** (String) - Required - The ID of the root component. * **styles** (JsonMap?) - Optional - The styles to apply to the UI. #### `BeginRendering.fromJson(JsonMap json)` Creates a BeginRendering message from a JSON map. ### Properties * **hashCode** (int) - The hash code for this object. * **root** (String) - The ID of the root component. * **runtimeType** (Type) - A representation of the runtime type of the object. * **styles** (JsonMap?) - The styles to apply to the UI. * **surfaceId** (String) - The ID of the surface that this message applies to. ### Methods * **noSuchMethod(Invocation invocation)** (dynamic) - Invoked when a nonexistent method or property is accessed. * **toString()** (String) - A string representation of this object. ### Operators * **operator ==(Object other)** (bool) - The equality operator. ``` -------------------------------- ### GenUiHost Class Overview Source: https://pub.dev/documentation/genui/latest/genui/GenUiHost-class Provides an overview of the GenUiHost class, its purpose, and its implementers. ```APIDOC ## GenUiHost Class ### Description An interface for a class that hosts UI surfaces. This is used by `GenUiSurface` to get the UI definition for a surface, listen for updates, and notify the host of user interactions. ### Implementers * GenUiManager ``` -------------------------------- ### POST /validateCatalogItemExamples Source: https://pub.dev/documentation/genui/latest/test_validation/validateCatalogItemExamples Validates the examples for a single catalog item against a provided catalog. It checks for JSON parsing errors, the presence of a 'root' component, and schema compliance. ```APIDOC ## POST /validateCatalogItemExamples ### Description Validates the examples for a single catalog item. It returns a list of validation errors, where an empty list signifies success. ### Method POST ### Endpoint /validateCatalogItemExamples ### Parameters #### Request Body - **item** (CatalogItem) - Required - The CatalogItem object to validate. - **catalog** (Catalog) - Required - The full catalog object used for context, including any additional catalogs. ### Request Example ```json { "item": { "exampleData": [ "() => \"[{\"id\": \"root\", \"type\": \"container\"}]\"" ] }, "catalog": { "// ... catalog object details ... " } } ``` ### Response #### Success Response (200) - **validationErrors** (List) - A list of validation errors. An empty list indicates that the examples are valid. #### Response Example ```json { "validationErrors": [ { "index": 0, "message": "Schema validation failed", "cause": [ { "// ... schema validation error details ... " } ] } ] } ``` #### Error Response - **500 Internal Server Error**: If an unexpected error occurs during validation. ``` -------------------------------- ### BeginRenderingTool Constructor and Usage Source: https://pub.dev/documentation/genui/latest/genui/BeginRenderingTool-class This section details how to construct and use the BeginRenderingTool, including its properties and methods. ```APIDOC ## BeginRenderingTool Class An AiTool for signaling the client to begin rendering. This tool allows the AI to specify the root component of a UI surface. ### Constructors #### `BeginRenderingTool({required void handleMessage(A2uiMessage message)})` Creates a `BeginRenderingTool`. - **handleMessage** (Function) - Required - The callback to invoke when signaling to begin rendering. ### Properties - **description** (String) - A description of what the tool does. - **fullName** (String) - Returns the full name of the tool, including the prefix if it exists. - **handleMessage** (Function) - The callback to invoke when signaling to begin rendering. - **hashCode** (int) - The hash code for this object. - **name** (String) - The unique name of the tool. - **parameters** (Schema?) - An optional `Schema` defining the parameters the tool accepts. - **prefix** (String?) - An optional name prefix that the tool will also be registered under. - **runtimeType** (Type) - A representation of the runtime type of the object. ### Methods #### `invoke(JsonMap args) → Future` Executes the tool's logic with the given `args`. - **args** (JsonMap) - Required - The arguments to pass to the tool. ### Operators #### `operator ==(Object other) → bool` The equality operator. ``` -------------------------------- ### Dart operator == Implementation Example Source: https://pub.dev/documentation/genui/latest/genui/Component/operator_equals An example implementation of the Dart 'operator ==' method for a 'Component' class. This method checks for equality based on 'id', 'weight', and 'componentProperties' using DeepCollectionEquality. It requires the 'collection_equality' package. ```dart @override bool operator ==(Object other) => other is Component && id == other.id && weight == other.weight && const DeepCollectionEquality().equals( componentProperties, other.componentProperties, ); ``` -------------------------------- ### BeginRenderingTool Constructor Implementation (Dart) Source: https://pub.dev/documentation/genui/latest/genui/BeginRenderingTool/BeginRenderingTool This snippet shows the Dart implementation of the BeginRenderingTool constructor. It initializes the tool with a name, description, and defines the required parameters 'surfaceIdKey' and 'root' for the rendering process. The 'handleMessage' callback is a required void function. ```dart BeginRenderingTool({ required void handleMessage(A2uiMessage message), }) : super( name: 'beginRendering', description: 'Signals the client to begin rendering a surface with a ', parameters: S.object( properties: { surfaceIdKey: S.string( description: 'The unique identifier for the UI surface to render.', ), 'root': S.string( description: 'The ID of the root widget. This ID must correspond to ', ), }, required: [surfaceIdKey, 'root'], ), ); ``` -------------------------------- ### GenUiHost Methods Source: https://pub.dev/documentation/genui/latest/genui/GenUiHost-class Details the methods available on the GenUiHost class. ```APIDOC ## GenUiHost Methods ### dataModelForSurface(String surfaceId) → DataModel * **Description**: The data model for storing the UI state for a given surface. ### getSurfaceNotifier(String surfaceId) → ValueNotifier * **Description**: Returns a ValueNotifier for the surface with the given `surfaceId`. ### handleUiEvent(UiEvent event) → void * **Description**: A callback to handle an action from a surface. ``` -------------------------------- ### GET /websites/pub_dev_genui/getSurfaceNotifier Source: https://pub.dev/documentation/genui/latest/genui/GenUiManager/getSurfaceNotifier Retrieves a ValueNotifier for a given surface ID. If the surface ID does not exist, a new ValueNotifier is created and returned. ```APIDOC ## GET /websites/pub_dev_genui/getSurfaceNotifier ### Description Returns a ValueNotifier for the surface with the given `surfaceId`. If the surface does not exist, it will be created. ### Method GET ### Endpoint /websites/pub_dev_genui/getSurfaceNotifier ### Parameters #### Query Parameters - **surfaceId** (String) - Required - The unique identifier for the surface. ### Request Example ``` GET /websites/pub_dev_genui/getSurfaceNotifier?surfaceId=exampleSurface123 ``` ### Response #### Success Response (200) - **value** (ValueNotifier) - A ValueNotifier that holds the UiDefinition for the requested surface. It will be null if the surface has not been initialized. #### Response Example ```json { "value": null } ``` ``` -------------------------------- ### DebugCatalogView Widget Documentation Source: https://pub.dev/documentation/genui/latest/genui/DebugCatalogView-class Documentation for the DebugCatalogView widget, which displays GenUI catalog widgets. This widget is intended for development and debugging purposes and requires example data for catalog items to be displayed. ```APIDOC ## DebugCatalogView Widget ### Description A widget that displays a GenUI catalog widgets. This widget is intended for development and debugging purposes. In order for a catalog item to be displayed, it must have example data defined. ### Inheritance - Object - DiagnosticableTree - Widget - StatefulWidget - DebugCatalogView ## Constructors ### `DebugCatalogView({Key? key, ValueChanged? onSubmit, required Catalog catalog, double? itemHeight})` - **key** (Key?) - Optional - Controls how one widget replaces another widget in the tree. - **onSubmit** (ValueChanged?) - Optional - A callback for when a user submits an action. - **catalog** (Catalog) - Required - The catalog of widgets to display. - **itemHeight** (double?) - Optional - If provided, constrains each item to the given height. ## Properties ### `catalog` → `Catalog` - **Description**: The catalog of widgets to display. - **Type**: `Catalog` - **Final**: `true` ### `hashCode` → `int` - **Description**: The hash code for this object. - **Type**: `int` - **Inherited**: `true` ### `itemHeight` → `double?` - **Description**: If provided, constrains each item to the given height. - **Type**: `double?` - **Final**: `true` ### `key` → `Key?` - **Description**: Controls how one widget replaces another widget in the tree. - **Type**: `Key?` - **Final**: `true` - **Inherited**: `true` ### `onSubmit` → `ValueChanged?` - **Description**: A callback for when a user submits an action. - **Type**: `ValueChanged?` - **Final**: `true` ### `runtimeType` → `Type` - **Description**: A representation of the runtime type of the object. - **Type**: `Type` - **Inherited**: `true` ## Methods ### `createElement()` → `StatefulElement` - **Description**: Creates a StatefulElement to manage this widget's location in the tree. - **Inherited**: `true` ### `createState()` → `State` - **Description**: Creates the mutable state for this widget at a given location in the tree. - **Override**: `true` ### `debugDescribeChildren()` → `List` - **Description**: Returns a list of DiagnosticsNode objects describing this node's children. - **Inherited**: `true` ### `debugFillProperties(DiagnosticPropertiesBuilder properties)` → `void` - **Description**: Add additional properties associated with the node. - **Inherited**: `true` ### `noSuchMethod(Invocation invocation)` → `dynamic` - **Description**: Invoked when a nonexistent method or property is accessed. - **Inherited**: `true` ### `toDiagnosticsNode({String? name, DiagnosticsTreeStyle? style})` → `DiagnosticsNode` - **Description**: Returns a debug representation of the object that is used by debugging tools and by DiagnosticsNode.toStringDeep. - **Inherited**: `true` ### `toString({DiagnosticLevel minLevel = DiagnosticLevel.info})` → `String` - **Description**: A string representation of this object. - **Inherited**: `true` ### `toStringDeep({String prefixLineOne = '', String? prefixOtherLines, DiagnosticLevel minLevel = DiagnosticLevel.debug, int wrapWidth = 65})` → `String` - **Description**: Returns a string representation of this node and its descendants. - **Inherited**: `true` ### `toStringShallow({String joiner = ', ', DiagnosticLevel minLevel = DiagnosticLevel.debug})` → `String` - **Description**: Returns a one-line detailed description of the object. - **Inherited**: `true` ### `toStringShort()` → `String` - **Description**: A short, textual description of this widget. - **Inherited**: `true` ## Operators ### `operator ==(Object other)` → `bool` - **Description**: The equality operator. - **Inherited**: `true` ``` -------------------------------- ### ThinkingPart Constructor Source: https://pub.dev/documentation/genui/latest/genui/ThinkingPart-class Provides details on how to create an instance of the ThinkingPart class. ```APIDOC ## ThinkingPart Constructor ### Description Creates a ThinkingPart with the given text. ### Method `ThinkingPart()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **text** (String) - Required - The reasoning content for the ThinkingPart. ### Request Example ```json { "text": "This is the reasoning content." } ``` ### Response #### Success Response (200) - **ThinkingPart** (Object) - An instance of the ThinkingPart class. #### Response Example ```json { "text": "This is the reasoning content." } ``` ``` -------------------------------- ### AiUiMessage Constructor Source: https://pub.dev/documentation/genui/latest/genui/AiUiMessage/AiUiMessage This section describes the AiUiMessage constructor, its parameters, and how it is implemented. ```APIDOC ## AiUiMessage Constructor ### Description Creates an AiUiMessage with the given UI `definition` and an optional `surfaceId`. ### Method Constructor ### Endpoint N/A (Class Constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **definition** (UiDefinition) - Required - The UI definition to be used for the message. - **surfaceId** (String?) - Optional - An identifier for the surface the message is associated with. ### Request Example ```dart AiUiMessage( definition: myUiDefinition, surfaceId: 'my-surface-123', ) ``` ### Response #### Success Response N/A (Constructor initializes an object) #### Response Example N/A ``` -------------------------------- ### Convert UserActionEvent to Map Source: https://pub.dev/documentation/genui/latest/genui/UserActionEvent-extension-type Shows how to convert a UserActionEvent object into a JsonMap using the toMap() method. This is useful for serializing the event data, for example, before sending it to an API. ```dart final eventMap = event.toMap(); // eventMap will be a JsonMap representing the UserActionEvent ``` -------------------------------- ### GenUiPromptFragments Constructor Source: https://pub.dev/documentation/genui/latest/genui/GenUiPromptFragments-class Initializes a new instance of the GenUiPromptFragments class. ```APIDOC ## GenUiPromptFragments() ### Description Initializes a new instance of the GenUiPromptFragments class. ### Method CONSTRUCTOR ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response #### Success Response (200) An instance of GenUiPromptFragments. #### Response Example N/A ``` -------------------------------- ### Create CatalogItem in Dart Source: https://pub.dev/documentation/genui/latest/index Defines a CatalogItem, which represents a type of widget that the agent can generate. It combines a name, a data schema, and a builder function to construct the widget. This example shows how to create a 'RiddleCard' widget. ```dart final riddleCard = CatalogItem( name: 'RiddleCard', dataSchema: _schema, widgetBuilder: ({ required data, required id, required buildChild, required dispatchEvent, required context, required dataContext, }) { final json = data as Map; final question = json['question'] as String; final answer = json['answer'] as String; return Container( constraints: const BoxConstraints(maxWidth: 400), decoration: BoxDecoration(border: Border.all()), padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(question, style: Theme.of(context).textTheme.headlineMedium), const SizedBox(height: 8.0), Text(answer, style: Theme.of(context).textTheme.headlineSmall), ], ), ); }, ); ``` -------------------------------- ### GenUiConfiguration Constructor Source: https://pub.dev/documentation/genui/latest/genui/GenUiConfiguration-class Creates a new GenUiConfiguration with optional actions configuration. ```APIDOC ## GenUiConfiguration Constructor ### Description Creates a new GenUiConfiguration. Allows for custom actions configuration, defaulting to 'createOnly'. ### Method Constructor ### Parameters #### Named Parameters - **actions** (ActionsConfig) - Optional - The configuration for the actions that can be performed by the GenUI. Defaults to `const ActionsConfig.createOnly()`. ### Request Example ```dart final config = GenUiConfiguration(actions: ActionsConfig.all()); ``` ### Response #### Success Response - **GenUiConfiguration** (GenUiConfiguration) - An instance of the GenUiConfiguration class. ``` -------------------------------- ### GET /websites/pub_dev_genui/a2uiMessageSchema Source: https://pub.dev/documentation/genui/latest/genui/A2uiMessage/a2uiMessageSchema Retrieves the JSON schema for an A2UI message. This schema defines the structure of messages used for agent-to-UI communication, including dynamic UI rendering and updates. ```APIDOC ## GET /websites/pub_dev_genui/a2uiMessageSchema ### Description Returns the JSON schema for an A2UI message. This schema is used to validate and understand the structure of messages sent from an agent to the UI for dynamic interface manipulation. ### Method GET ### Endpoint /websites/pub_dev_genui/a2uiMessageSchema ### Parameters #### Query Parameters - **catalog** (Catalog) - Required - The catalog object used to generate the schema. ### Response #### Success Response (200) - **schema** (object) - The JSON schema for an A2UI message. This schema includes properties for different UI actions such as 'surfaceUpdate', 'dataModelUpdate', 'beginRendering', and 'deleteSurface'. #### Response Example ```json { "title": "A2UI Message Schema", "description": "Describes a JSON payload for an A2UI (Agent to UI) message, which is used to dynamically construct and update user interfaces. A message MUST contain exactly ONE of the action properties: 'beginRendering', 'surfaceUpdate', 'dataModelUpdate', or 'deleteSurface'.", "properties": { "surfaceUpdate": { ... }, "dataModelUpdate": { ... }, "beginRendering": { ... }, "deleteSurface": { ... } }, "oneOf": [ { "required": ["beginRendering"] }, { "required": ["surfaceUpdate"] }, { "required": ["dataModelUpdate"] }, { "required": ["deleteSurface"] } ] } ``` ``` -------------------------------- ### DataModel Constructor Source: https://pub.dev/documentation/genui/latest/genui/DataModel-class Initializes a new instance of the DataModel class. ```APIDOC ## DataModel() ### Description Initializes a new instance of the DataModel class. ### Method CONSTRUCTOR ### Endpoint N/A ### Parameters None ### Request Example ```dart var dataModel = DataModel(); ``` ### Response #### Success Response (Instance) - **dataModel** (DataModel) - An instance of the DataModel class. #### Response Example ```dart Instance of 'DataModel' ``` ``` -------------------------------- ### Dart hashCode Implementation Example Source: https://pub.dev/documentation/genui/latest/genui/DataPath/hashCode This code snippet demonstrates the implementation of the 'hashCode' getter in Dart. It utilizes 'Object.hash' to generate a hash code based on the object's state, ensuring consistency with equality comparisons. ```dart @override int get hashCode => Object.hash(isAbsolute, Object.hashAll(segments)); ``` -------------------------------- ### GenUiSurface Constructor Source: https://pub.dev/documentation/genui/latest/genui/GenUiSurface-class Creates a new GenUiSurface instance, which is a StatefulWidget that builds a UI dynamically from a JSON-like definition and reports user interactions via the host. ```APIDOC ## GenUiSurface Constructor ### Description Creates a new GenUiSurface widget. This widget dynamically builds a UI from a JSON-like definition and reports user interactions via the provided `GenUiHost`. ### Method `GenUiSurface()` ### Parameters #### Named Parameters - **key** (Key?) - Optional - Controls how one widget replaces another widget in the tree. - **host** (GenUiHost) - Required - The manager that holds the state of the UI and reports interactions. - **surfaceId** (String) - Required - The unique identifier for the surface that this UI belongs to. - **defaultBuilder** (WidgetBuilder?) - Optional - A builder for the widget to display when the surface has no definition. ``` -------------------------------- ### CatalogItem Class Definition and Constructor Source: https://pub.dev/documentation/genui/latest/genui/CatalogItem-class Defines the CatalogItem class, used to represent a UI layout type. It includes properties for its name, data schema, widget builder, and optional example data. The constructor initializes these properties. ```dart class CatalogItem { final String name; final Schema dataSchema; final CatalogWidgetBuilder widgetBuilder; final List exampleData; CatalogItem({ required String name, required Schema dataSchema, required CatalogWidgetBuilder widgetBuilder, List exampleData = const [], }) : name = name, dataSchema = dataSchema, widgetBuilder = widgetBuilder, exampleData = exampleData; } ``` -------------------------------- ### SurfaceUpdateTool Constructor Source: https://pub.dev/documentation/genui/latest/genui/SurfaceUpdateTool-class Initializes a new instance of the SurfaceUpdateTool class. ```APIDOC ## SurfaceUpdateTool Constructor ### Description Creates an instance of the `SurfaceUpdateTool` class. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body for constructor" } ``` ### Response #### Success Response (200) None #### Response Example ```json { "example": "No response body for constructor" } ``` ``` -------------------------------- ### Dart operator == Implementation Example Source: https://pub.dev/documentation/genui/latest/genui/DataPath/operator_equals This code snippet demonstrates how to override the equality operator (==) for a Dart class. It checks for identity, type, runtime type, and then compares specific properties like 'isAbsolute' and 'segments' using 'listEquals'. This implementation ensures the operator is a valid equivalence relation. ```dart @override bool operator ==(Object other) => identical(this, other) || other is DataPath && runtimeType == other.runtimeType && isAbsolute == other.isAbsolute && listEquals(segments, other.segments); ``` -------------------------------- ### Get Surface Notifier (Dart) Source: https://pub.dev/documentation/genui/latest/genui/GenUiManager/getSurfaceNotifier Retrieves a ValueNotifier for a given surface ID. If the surface ID does not exist, it creates a new one with a null UiDefinition. It logs whether a new surface is being added or an existing one is being fetched. This method is crucial for managing UI state associated with specific surfaces. ```dart @override ValueNotifier getSurfaceNotifier(String surfaceId) { if (!_surfaces.containsKey(surfaceId)) { genUiLogger.fine('Adding new surface $surfaceId'); } else { genUiLogger.fine('Fetching surface notifier for $surfaceId'); } return _surfaces.putIfAbsent( surfaceId, () => ValueNotifier(null), ); } ``` -------------------------------- ### TextPart Class Source: https://pub.dev/documentation/genui/latest/genui/TextPart-class Details about the TextPart class, including its constructor, properties, and methods. ```APIDOC ## TextPart Class ### Description A text part of a message. Implemented types include MessagePart. ### Constructors #### TextPart(String text) Creates a TextPart with the given `text`. ### Properties #### hashCode → int The hash code for this object. #### runtimeType → Type A representation of the runtime type of the object. #### text → String The text content. ### Methods #### noSuchMethod(Invocation invocation) → dynamic Invoked when a nonexistent method or property is accessed. #### toString() → String A string representation of this object. ### Operators #### operator ==(Object other) → bool The equality operator. ``` -------------------------------- ### AiTool Constructor Source: https://pub.dev/documentation/genui/latest/genui/AiTool/AiTool This section details the constructor for the AiTool class, explaining each parameter and its purpose. ```APIDOC ## AiTool Constructor ### Description Creates an instance of AiTool. This constructor is used to define a new AI tool with its unique identifier, description, and optional parameters. ### Method `const` constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Constructor Parameters - **name** (String) - Required - A unique identifier for the tool. This name is used by the AI to specify which tool to call. - **description** (String) - Required - A natural language description of the tool's purpose and functionality. This helps the AI decide when and how to use the tool. - **parameters** (Schema?) - Optional - An optional `Schema` that defines the structure and types of arguments the tool accepts. If the tool requires no arguments, this can be omitted. - **prefix** (String?) - Optional - An optional prefix for the tool. ### Request Example ```dart const AiTool({ required this.name, required this.description, this.parameters, this.prefix, }); ``` ### Response #### Success Response (200) N/A (This is a constructor, not an API endpoint) #### Response Example N/A ``` -------------------------------- ### GenUiConversation Constructor Source: https://pub.dev/documentation/genui/latest/genui/GenUiConversation/GenUiConversation Initializes a new GenUiConversation object with optional callback functions and required content generator and UI manager instances. ```APIDOC ## GenUiConversation Constructor ### Description Creates a new GenUiConversation. Callbacks like `onSurfaceAdded`, `onSurfaceUpdated` and `onSurfaceDeleted` can be provided to react to UI changes initiated by the AI. ### Method Constructor ### Endpoint N/A (Constructor) ### Parameters #### Constructor Parameters - **onSurfaceAdded** (ValueChanged? ) - Optional - Callback for when a surface is added. - **onSurfaceUpdated** (ValueChanged? ) - Optional - Callback for when a surface is updated. - **onSurfaceDeleted** (ValueChanged? ) - Optional - Callback for when a surface is removed. - **onTextResponse** (ValueChanged? ) - Optional - Callback for text responses. - **onError** (ValueChanged? ) - Optional - Callback for errors. - **contentGenerator** (required ContentGenerator) - Required - The content generator instance. - **genUiManager** (required GenUiManager) - Required - The UI manager instance. ### Request Example ```dart GenUiConversation( onSurfaceAdded: (surface) => print('Surface added: $surface'), onTextResponse: (text) => print('Text response: $text'), contentGenerator: myContentGenerator, genUiManager: myGenUiManager, ) ``` ### Response #### Success Response (Constructor) - N/A (Constructor does not return a value in the traditional sense, but initializes an object) #### Response Example N/A ``` -------------------------------- ### GenUiConfiguration Methods and Operators Source: https://pub.dev/documentation/genui/latest/genui/GenUiConfiguration-class Information on inherited methods and operators for the GenUiConfiguration class. ```APIDOC ## GenUiConfiguration Methods and Operators ### Description Details about inherited methods and operators for the GenUiConfiguration class. ### Methods - **noSuchMethod(Invocation invocation)** (dynamic) - Invoked when a nonexistent method or property is accessed. (inherited) - **toString()** (String) - A string representation of this object. (inherited) ### Operators - **operator ==(Object other)** (bool) - The equality operator. (inherited) ``` -------------------------------- ### UiDefinition Class Overview Source: https://pub.dev/documentation/genui/latest/genui/UiDefinition-class Provides an overview of the UiDefinition class, including its purpose, constructors, properties, and methods. ```APIDOC ## UiDefinition Class A data object that represents the entire UI definition. This is the root object that defines a complete UI to be rendered. ### Constructors * **UiDefinition({required String surfaceId, String? rootComponentId, Map components = const {}, JsonMap? styles})** Creates a UiDefinition. ### Properties * **components** (Map) - A map of all widget definitions in the UI, keyed by their ID. * **hashCode** (int) - The hash code for this object. * **rootComponentId** (String?) - The ID of the root widget in the UI tree. * **runtimeType** (Type) - A representation of the runtime type of the object. * **styles** (JsonMap?) - (Future) The styles for this surface. * **surfaceId** (String) - The ID of the surface that this UI belongs to. ### Methods * **asContextDescriptionText() → String** Converts a UI definition into a blob of text. * **copyWith({String? rootComponentId, Map? components, JsonMap? styles}) → UiDefinition** Creates a copy of this UiDefinition with the given fields replaced. * **noSuchMethod(Invocation invocation) → dynamic** Invoked when a nonexistent method or property is accessed. * **toJson() → JsonMap** Converts this object to a JSON map. * **toString() → String** A string representation of this object. ### Operators * **operator ==(Object other) → bool** The equality operator. ``` -------------------------------- ### SurfaceUpdateTool Constructor and Implementation (Dart) Source: https://pub.dev/documentation/genui/latest/genui/SurfaceUpdateTool/SurfaceUpdateTool This snippet shows the definition and implementation of the SurfaceUpdateTool constructor. It requires a handleMessage callback, a Catalog object, and a GenUiConfiguration object. The constructor initializes the tool with a name, description, and schema parameters derived from the provided Catalog. ```Dart SurfaceUpdateTool({ required void Function(A2uiMessage message) handleMessage, required Catalog catalog, required GenUiConfiguration configuration, }) // Implementation SurfaceUpdateTool({ required this.handleMessage, required Catalog catalog, required this.configuration, }) : super( name: 'surfaceUpdate', description: 'Updates a surface with a new set of components.', parameters: A2uiSchemas.surfaceUpdateSchema(catalog), ); ``` -------------------------------- ### Prefix Property Documentation Source: https://pub.dev/documentation/genui/latest/genui/AiTool/prefix This section details the optional 'prefix' property, which allows tools to be registered under an additional name. This is useful for AI discoverability, especially in systems like MCP tools where the prefix might represent the server name. ```APIDOC ## Prefix Property ### Description This is an optional name prefix that the tool will also be registered under. If the prefix is provided, the tool will be registered under both the name and the `fullName` strings. For example, a tool with the name "readFile" and a prefix of "file" would be registered under both "readFile" and "file.readFile". This is so that the AI can ask for the "readFile" tool, even if it was registered as "file.readFile", and it will still find the right tool. For MCP tools, prefixes are typically set to the name of the MCP server. ### Implementation ```dart final String? prefix; ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body This property is typically part of a tool's configuration and not directly set via a request body in a typical API call. It's defined during the tool's registration. ### Request Example N/A (Configuration parameter) ### Response #### Success Response (200) N/A (Configuration parameter) #### Response Example N/A (Configuration parameter) ``` -------------------------------- ### Dart: BeginRendering Class Constructors Source: https://pub.dev/documentation/genui/latest/genui/BeginRendering-class Demonstrates how to create instances of the BeginRendering class using its default and named constructors. The default constructor requires surfaceId and root, and optionally accepts styles. The fromJson constructor allows creating an instance from a JSON map. ```dart final beginRenderingMessage = BeginRendering( surfaceId: 'mySurfaceId', root: 'myRootId', styles: {'backgroundColor': 'blue'}, ); final jsonMap = { 'surfaceId': 'anotherSurface', 'root': 'anotherRoot', 'styles': {'color': 'red'}, }; final beginRenderingFromJson = BeginRendering.fromJson(jsonMap); ``` -------------------------------- ### Create ChatMessageWidget Instance (Dart) Source: https://pub.dev/documentation/genui/latest/genui/ChatMessageWidget-class This snippet shows how to create a new instance of the ChatMessageWidget. It requires a key, the message text, an icon, and the alignment for the message. This is the primary way to instantiate the widget for displaying messages. ```dart ChatMessageWidget({ Key? key, required String text, required IconData icon, required MainAxisAlignment alignment, }) ``` -------------------------------- ### SurfaceUpdateTool Constructor Source: https://pub.dev/documentation/genui/latest/genui/SurfaceUpdateTool/SurfaceUpdateTool Constructor for the SurfaceUpdateTool class. It initializes the tool with required handlers and configurations. ```APIDOC ## SurfaceUpdateTool Constructor ### Description Creates an instance of SurfaceUpdateTool, initializing it with a message handler, a catalog, and a GenUI configuration. ### Method Constructor ### Parameters #### Constructor Parameters - **handleMessage** (void Function(A2uiMessage)) - Required - A callback function to handle incoming messages. - **catalog** (Catalog) - Required - The catalog object to be used by the tool. - **configuration** (GenUiConfiguration) - Required - The configuration settings for the GenUI. ### Implementation Details ```dart SurfaceUpdateTool({ required this.handleMessage, required Catalog catalog, required this.configuration, }) : super( name: 'surfaceUpdate', description: 'Updates a surface with a new set of components.', parameters: A2uiSchemas.surfaceUpdateSchema(catalog), ); ``` ``` -------------------------------- ### DataPath Class Overview Source: https://pub.dev/documentation/genui/latest/genui/DataPath-class Provides details on the DataPath class, including its constructors, properties, methods, and operators. ```APIDOC ## DataPath Class ### Description The `DataPath` class represents a file system path and provides methods for path manipulation and comparison. ### Properties - **basename** (String) - The base name of the path. - **dirname** (DataPath) - The directory name of the path. - **hashCode** (int) - The hash code for this object. - **isAbsolute** (bool) - Checks if the path is absolute. - **runtimeType** (Type) - A representation of the runtime type of the object. - **segments** (List) - A list of path segments. ### Methods - **join**(DataPath other) → DataPath - Joins the current path with another `DataPath` object. - **noSuchMethod**(Invocation invocation) → dynamic - Invoked when a nonexistent method or property is accessed. - **startsWith**(DataPath other) → bool - Checks if the current path starts with another `DataPath` object. - **toString**() → String - Returns a string representation of the path. ### Operators - **operator ==**(Object other) → bool - Compares the current path with another object for equality. ### Constants - **root** (const DataPath) - Represents the root path. ```