AI Agent UI Generation with a Structured Protocol
A declarative UI protocol lets AI agents generate structured interface descriptions instead of executable frontend code. This article explains the protocol’s core elements, a model-independent generation architecture, and the validation, rendering, event handling, and security controls needed to build portable, auditable AI-generated interfaces.
AI Agent UI Generation with a Structured Protocol
1. Why Agents Should Describe Interfaces Instead of Writing Pages
The most direct way to generate a user interface with an AI agent is to ask the model to produce frontend code. In practice, however, this approach has several engineering drawbacks:
- Limited validation: Generated code may be syntactically correct but logically flawed, or it may introduce unsafe calls.
- Poor portability: Technology stacks and client-side rendering capabilities vary, making generated code difficult to reuse across platforms.
- Insufficient control: Businesses need to enforce component allowlists, design tokens, permissions, and interaction boundaries. Unrestricted code generation is difficult to constrain.
- High maintenance costs: Once generated code becomes intertwined with business logic, upgrades, audits, and rollbacks become more complex.
A better approach is to have the agent produce a declarative UI description protocol that a controlled renderer interprets. Instead of manipulating the DOM or calling business APIs directly, the agent describes the interface through structured JSON: component trees, properties, data bindings, and action intents.
The renderer validates and renders that description, then passes events back to the host application. This separates model generation from interface execution, keeping open-ended generation within controlled boundaries.
2. What an Agent-Oriented UI Protocol Should Include
A UI description protocol for agents should cover at least the following layers.
Component Trees and Layout
Represent the interface as a tree with a root node, container nodes, and leaf components. Each node includes a component type, a unique identifier, children, and layout properties.
Component types should come from a controlled allowlist, such as text, buttons, forms, tables, charts, cards, and dialogs. Layout properties can include direction, spacing, alignment, and grid placement.
Properties and Design Tokens
Component properties describe content and behavior, including text, placeholders, disabled states, and validation rules.
Styling should use design tokens rather than arbitrary CSS. Tokens can represent primary and warning colors, corner-radius levels, and font-size levels. This supports brand consistency while reducing injection risks.
Data Bindings and State References
Interfaces often depend on business data. The protocol should support restricted data-binding expressions—for example, references to paths in context data rather than arbitrary script execution.
The host environment supplies the data sources. The agent declares which fields it needs without directly accessing databases or internal APIs.
Actions and Events
Interactions such as button clicks, form submissions, and row selections should be represented as action intents, such as submitForm, openDialog, or refreshData.
Action parameters must be structured data. The host environment uses an allowlist to determine whether an action may run, how to authorize it, and how to return its result.
The agent does not make network requests directly, reducing the risk of unauthorized or unauditable operations.
Versions and Capability Declarations
The protocol should include a version number and capability declarations so the renderer can handle compatibility.
For example, if a new protocol version introduces a chart component, an older renderer can fall back to a text summary or display an unsupported-component message.
The description should also declare required capabilities, such as table sorting or file uploads. The renderer decides whether it can satisfy those requirements.
3. Keep the Protocol Independent of the Model
A key advantage of this approach is model independence. The protocol does not require a particular plugin, platform feature, or vendor interface. Its central requirement is simple: can the model consistently produce structured JSON that conforms to the contract?
General-purpose models, domain-specific models, and hosted models accessed through a model-service API can all participate if they can:
- Follow system instructions and schema constraints.
- Produce parseable JSON.
- Correct their output in response to validation errors.
- Optionally support streaming or chunked output.
Avoid tying the protocol to a specific model feature. Instead, build a model-independent generation adapter:
User intent + page context↓Prompt template + JSON Schema + component allowlist↓Model generates a structured UI description↓Schema validation → semantic validation → repair retries↓Renderer displays UI → events return to host → state updates
In this pipeline, the model is only a description generator. Replacing the model, switching model services, or introducing multi-model routing does not change the protocol or renderer.
For cloud deployments, the architecture can combine model services, serverless functions, object storage, logging, and monitoring. On Baidu AI Cloud, for example, model invocation, validation services, static asset hosting, and logging and monitoring can be assembled from those general cloud-service categories. The protocol itself remains vendor-neutral.
4. End-to-End Architecture: Generate, Validate, Render, and Return Events
Generation Layer
The generation layer converts user intent into a UI description.
Prompts should explicitly define available components, permitted property values, data paths, and allowed actions. They should require JSON output and prohibit explanatory text.
Providing a JSON Schema or examples helps make these boundaries clear to the model.
Validation Layer
Validation has two levels:
- Structural validation: Check that fields exist, types are correct, required fields are present, and component types are allowlisted.
- Semantic validation: Check that data paths exist in the context, actions are permitted, design tokens are valid, and nesting depth and node counts remain within limits.
When validation fails, do not expose raw errors directly to the user. Instead, return a concise, actionable error summary to the model and require it to output only corrected JSON.
Limit the number of retries and record observability metrics.
Rendering Layer
The renderer is a controlled interpreter that maps protocol nodes to components in the host environment.
It should enforce sandbox restrictions: prohibit arbitrary scripts, restrict external links and file access, and sanitize rich text. Unsupported components should follow a defined fallback strategy.
Event Return Layer
When a user clicks a button, the renderer should not directly perform a sensitive operation. It sends the action intent, parameters, and current page context to the host application.
The host authorizes the action, executes the business operation, and returns the result as a state patch or a new UI description. This creates a loop of description, interaction, and updated description.
5. A Simplified UI Description
{"version": "1.0","capabilities": ["form", "table"],"root": {"id": "root","type": "Container","layout": { "direction": "vertical", "gap": "md" },"children": [{"id": "title","type": "Text","props": { "content": "Order Search", "level": "h2" }},{"id": "queryForm","type": "Form","props": { "submitAction": "queryOrders" },"children": [{"id": "orderNo","type": "Input","props": {"label": "Order Number","valueBinding": "$.context.orderNo","required": true}},{"id": "submitBtn","type": "Button","props": {"text": "Search","action": { "name": "submitForm", "target": "queryForm" }}}]}]}}
This example contains no executable code, arbitrary styling, or direct network requests. The agent describes what the interface looks like, where its data comes from, and what should happen when the user clicks a button.
The host environment executes the actual query through the allowlisted queryOrders action.
6. Engineering Practices
Define the Schema First and Enforce Allowlists
Define a stable schema before writing prompts. The schema is both the model’s output contract and the validator’s input.
Component types, action names, and design tokens should all be allowlisted. Allowing the model to invent component names would force the renderer to keep expanding to accommodate them.
Combine Structured Output with Repair Retries
Use structured-output constraints or tool-calling capabilities where available, but do not assume every model will comply consistently.
Implement a complete parse–validate–summarize–retry loop. Error summaries should be short, specific, and actionable, such as:
The submitAction on node queryForm is not in the allowed list.
If retries still fail, fall back to a safe form or a text message.
Support Streaming and Partial Updates
For complex pages, the model can produce chunks or patches. The renderer can display a skeleton first, then update individual nodes incrementally.
Use stable node IDs to avoid redrawing the entire tree. The protocol may define patch operations to add nodes, update properties, or remove nodes. Patches must pass validation just as complete descriptions do.
Separate Versions and Negotiate Capabilities
Keep protocol, component, and renderer versions separate.
At startup, the renderer declares its supported capabilities. The generation layer uses that list to restrict the available components.
New renderers should remain compatible with older pages where possible. New pages should have fallback behavior when displayed by older renderers.
Enforce Security and Permissions
Key risks include arbitrary script injection, unauthorized actions, sensitive-data exposure, external-link navigation, and file-upload abuse.
Apply the following controls:
- Authorize actions in the host application.
- Restrict data bindings to authorized context data.
- Sanitize rich text.
- Allowlist external links.
- Limit upload file types and sizes.
- Keep secrets and internal addresses out of the protocol.
Include Accessibility and Internationalization
The protocol should support accessibility fields for labels, descriptions, keyboard focus order, and error messages.
Text and formatting should support internationalization placeholders without allowing executable templates. Layouts should avoid reliance on absolute positioning that makes interfaces unusable on different screen sizes.
Measure Quality and Operational Behavior
Track generation success rates, schema-validation failure rates, repair retry counts, rendering fallback rates, action rejection rates, and end-to-end latency.
Build an offline evaluation set covering forms, lists, detail views, empty states, and error states.
When comparing models, evaluate the quality of their protocol output rather than relying on brand preference.
7. Use Cases and a Practical Rollout Plan
This approach is suitable for low-code page builders, AI-assisted customer-support workspaces, operations alert dashboards, data-analysis query pages, internal enterprise form workflows, and dynamic mobile cards.
Start with a narrow scope, strict constraints, and a clear rollback path:
- Select 10–20 general-purpose components and define a minimal schema.
- Initially support only read-only displays and simple forms.
- Establish allowlists for actions and accessible data context.
- Add validation, repair retries, fallbacks, and auditing.
- Gradually introduce charts, tables, complex layouts, and incremental patches.
8. Conclusion
Having an AI agent describe a UI is not about replacing frontend engineers with generated code. It is about producing an interface description that can be validated, rendered, and audited.
The protocol separates generation from execution: the model produces structured JSON, the renderer interprets it under controlled conditions, and the host application handles permissions and business logic.
With schema-first design, allowlists, repair retries, version compatibility, and sandboxed rendering, this approach provides a controlled and extensible foundation for AI-generated interfaces across models, platforms, and business applications.
