AI / Generative UI interview questions
Last updated
1. What is Generative UI?
Generative UI is an approach where an AI model decides, at runtime, which interface to show for a given request, instead of every screen being designed ahead of time. The model picks components, fills them with data, and arranges them around what the user is trying to do.
In practice the model rarely writes raw HTML. It selects from a pre-approved set of components (cards, tables, charts, forms) and returns structured data that the app renders.
- Intent goes in, an interface comes out.
- Components come from a vetted catalog.
- Data comes from tools and APIs, not from the model's memory.
Take quiz
The AI model, at runtime, based on the request and context
A designer who hand-built every screen in advance
The browser, using CSS media queries
Structured data that selects and configures approved components
Only plain paragraphs of text
A compiled native binary
A screenshot of the finished page
2. What are the main benefits of Generative UI?
Generative UI gives users an interface shaped to their task instead of a generic screen, and it lets teams cover rare requests without designing a screen for each one.
- Task fit: a comparison request gets a comparison table, not a paragraph.
- Fewer steps: the controls needed for the goal appear together.
- Long-tail coverage: uncommon needs are served without custom design work.
- Personalization: layout and density adapt to role and context.
- Richer chat: charts, forms, and maps replace walls of text.
The trade-off is less predictability, which is why guardrails and fallbacks matter.
Take quiz
A sortable comparison table or cards instead of a wall of text
It removes the need for any product data
It guarantees the cheapest laptop is chosen
It stores every possible screen in a database
It makes API calls unnecessary
It forces every user into one default layout
Rare tasks get a fitting interface without a designer building a screen for each one
3. Define intent-driven design?
Intent-driven design builds the interface around what the user wants to accomplish, not around a fixed menu of screens. The system infers a goal from language, context, or behavior, then assembles the controls needed to reach it.
Take "plan a weekend in Lisbon". A traditional app sends the user through search, filters, and booking tabs. An intent-driven one shows a day-by-day itinerary, a map, and a booking button on one screen.
- Capture the intent from the request or context.
- Resolve missing details by asking a short question or applying a visible default.
- Choose the UI pattern that matches the intent and fill it with data.
Take quiz
"Show me last month's refunds by region"
Hover over the settings icon
A cached cookie value
Scroll position at 480px
Silently guess and hide the assumption
Show an empty screen
Ask a short clarifying question or apply a sensible, visible default
4. What is outcome-oriented design in Generative UI?
Outcome-oriented design optimizes for the result the user wants (a booked flight, a resolved ticket, an approved expense) rather than for completing individual screens. Success is measured by whether the result was reached quickly and correctly.
Intent-driven design asks what the user wants. Outcome-oriented design goes further and asks what "done" looks like, then removes every step that does not move toward it.
| Screen-oriented | Outcome-oriented | |
| Unit of design | Pages and flows | The end result |
| Success metric | Page views, clicks | Completion time, success rate, error rate |
| Steps | Fixed sequence | Only what the outcome needs |
Take quiz
Number of pages viewed per session
Total clicks generated
Number of components rendered
Time and error rate to complete the task
List every menu of the clinic site first
Ask the user to describe the page layout
Show available slots with a single confirm action
5. What is a composable component system in Generative UI?
It is a library of small, well-defined building blocks (card, table, chart, form field, stepper) with typed props that the model can combine into larger interfaces. The model composes; it does not invent new primitives.
Each component declares its name, props schema, allowed children, and accessibility behavior. Because blocks are reused, output stays on-brand and testable.
- Layout: stack, grid, tabs
- Content: text, image, callout
- Data: table, chart, map
- Input: form, select, date picker
- Action: button, confirm dialog
A useful test is whether a new screen can be built purely by combining existing blocks. If the model needs a component that does not exist, that is a signal to add one through your normal design review, not to let the model improvise markup.
Take quiz
Invent new primitives for every request
Bypass the design system for speed
Select and arrange registered components with valid props
Compile CSS from scratch
A props schema and its accessibility behavior
The end user's browsing history
The model's training data list
The server's private API keys
6. What are guardrails in Generative UI?
Guardrails are the constraints that keep generated interfaces safe, valid, and on-brand. They work at three points: before generation (what the model may use), during it (schema-constrained output), and after it (validation and review).
- An allow-list of components and actions
- Schema validation of every spec
- Content filters and PII redaction
- Confirmation steps for payments and deletions
- Rate and cost limits
- A fallback UI when something fails
No single guardrail is enough. Schema checks catch malformed output but not a well-formed button that deletes the wrong record, which is why action limits and confirmations sit alongside validation. Treat them as layers, each assuming the one before it can fail.
Take quiz
Logging errors after the page has rendered
Restricting the model to an allow-list of components
Holding a post-incident review meeting
Retrying requests after a timeout
Dialogs make pages load faster
CSS cannot style buttons otherwise
It lets the model skip validation
Model output can be wrong or manipulated, so risky actions need a human check
7. What is a component schema in Generative UI?
A component schema is a machine-readable definition, usually JSON Schema or Zod, of a component's name and props: types, required fields, enums, and limits. The model is shown the schema, and the app validates its output before rendering.
const ProductCard = z.object({ type: z.literal("product_card"), title: z.string().max(80), price: z.number().nonnegative(), currency: z.enum(["USD", "EUR", "GBP"]), imageUrl: z.string().url().optional() });
Limits like max(80) and enums stop broken layouts and unexpected values from reaching the screen.
The same schema usually does double duty: it becomes the tool definition the model sees, and it is the validator your server runs. Keeping one source of truth avoids drift between what the model is told and what the app accepts.
Take quiz
Wrong types, missing required props, and values outside allowed enums
Slow network connections
Poor color choices by designers
Users who disable JavaScript
To make the price field optional
To let the model write any currency name
So only approved currency codes can ever be rendered
To compress the response
8. Describe a micro-app in Generative UI?
A micro-app is a small, single-purpose interactive tool generated on demand inside a conversation or page, such as a loan calculator, a meeting-time picker, or a filterable table. It has its own state and controls and lives only as long as it is useful.
Unlike a static card, it responds to input: sliders update results and filters re-query data. It is usually built from catalog components wired to a small state model, or runs in a sandboxed iframe when the model writes custom code.
Take quiz
It always requires a native install
It can only display text
It never talks to data
It holds state and responds to user input
A permanent company-wide login system
A mortgage calculator with adjustable rate and term
A nightly database backup job
A DNS migration
9. How do you generate an interactive chart with Generative UI?
- Identify the question and the fields involved from the user's request.
- Fetch the data through a tool call (SQL or API), not from the model's memory.
- Have the model return a chart spec (type, x, y, color, filters) and validate it against a schema.
- Render it with a charting library such as Recharts, Vega-Lite, or D3, including tooltips, legend, and filters.
- Send interaction events (brush, filter) back as local state or as a new intent.
The model chooses the encoding; the tool supplies the numbers. That split keeps the chart from showing invented values.
Take quiz
The model's best recollection
Randomly sampled placeholder values
A tool call to the real data source
The previous chart's labels
A validated spec describing type, axes, and encodings
Raw pixel data
The full dataset rewritten as prose
A GPU shader program
10. What is adaptive personalization in Generative UI?
Adaptive personalization changes layout, content density, defaults, and component choice based on who the user is and what they are doing. Typical signals are role, recent tasks, device, and the current goal.
A finance manager might see pending approvals first with a weekly trend chart, while a new employee sees a guided form with help text. The data is the same; the interface differs.
Users should be able to see why the UI adapted and to override or reset it.
Take quiz
The server's CPU temperature
The user's role and recent tasks
The current git commit hash
The CDN provider's region name
No visibility, to avoid confusion
Only the model's choice
A locked layout
A way to see, override, or reset the personalization
11. What is perceptual personalization in Generative UI?
Perceptual personalization adapts how an interface is perceived: contrast, font size, spacing, motion, color-blind-safe palettes, reading level, and information density. It serves sensory, cognitive, or situational needs.
It differs from content personalization because the information stays the same and only the presentation changes.
- Larger text and no animation for users with
prefers-reduced-motion - Fewer choices per screen for lower cognitive load
- Patterns and labels in charts instead of color alone
Many of these signals are free, because the browser already exposes prefers-contrast, prefers-reduced-motion, and the color scheme. A generator that reads them can adapt without profiling anyone, which makes perceptual personalization one of the lower-risk forms of adaptation.
Take quiz
Presentation: contrast, size, motion, and density
Database schema
Pricing tier
Authentication method
The Accept-Language header
window.devicePixelRatio
The prefers-reduced-motion media query
The document title
12. List common domain use cases of Generative UI?
Generative UI fits any domain where users ask open-ended questions and need a different screen each time.
| Domain | Generated UI example |
| E-commerce | Comparison grids, size guides, outfit boards |
| Healthcare | Patient summary cards, lab-trend charts, intake forms |
| Finance | Portfolio breakdowns, loan calculators, expense approvals |
| Customer support | Order status cards, return flows, refund forms |
| Education | Quizzes, interactive diagrams, adaptive practice |
| Analytics and BI | Ad-hoc dashboards built from a question |
| Travel | Itineraries with maps and booking |
| Developer tools | Log explorers, pull request review views |
Take quiz
A 3D game level
A video editing timeline
A compiler flag editor
An order-status card with a return button
Replacing grading policy
Interactive diagrams and practice tailored to the learner
Hiding answers permanently
Removing assessments
13. How do you use tool calling to render UI components?
Expose each component as a tool. When the model decides a UI is needed, it calls the tool with arguments. Your app maps the tool name to a component and renders it with those arguments. The sketch below follows the Vercel AI SDK pattern; exact names vary by SDK version.
const tools = { show_weather: tool({ description: "Show a weather card for a city", inputSchema: z.object({ city: z.string(), unit: z.enum(["C", "F"]) }), execute: async ({ city, unit }) => getWeather(city, unit) }) }; // client {message.parts.map(part => part.type === "tool-show_weather" && part.state === "output-available" ? <WeatherCard {...part.output} /> : null )}
Arguments are schema-validated, data comes from execute, and unknown tool names never render.
Take quiz
A CSS class name
The HTTP status code
The tool name mapped to a component
The user's cookie
The tool's execute function
The model's guess
The component's CSS
The message id
14. What is streaming UI in Generative UI?
Streaming UI renders the interface progressively while the model is still generating, instead of waiting for the full response. Skeletons appear first, then text, then components as their arguments complete.
It matters because model calls take seconds, and showing structure early lowers perceived latency. It also needs a tolerant parser for partial JSON, and components that render safely with incomplete props.
For example, a dashboard request can show a title and three skeleton cards immediately, fill the summary text as tokens arrive, and swap each skeleton for a real chart when its tool result lands. Components should reserve their final size so the page does not jump while this happens.
Take quiz
It removes the need for validation
Lower perceived latency because parts appear early
It makes the model more accurate
It reduces the number of components needed
The absence of any props
CSS variables
Print stylesheets
Partial or incomplete props arriving mid-generation
15. What is UI hallucination in Generative UI?
UI hallucination is when the model generates interface elements that do not exist or do not work: a component missing from the catalog, a button wired to an action your app never defined, a link to an invented page, or a chart with numbers the data does not contain.
- Allow-list components and action names.
- Validate every spec against a schema.
- Pull data through tools, never from model memory.
- Allow-list link domains.
- Run evals and keep a fallback UI.
These failures are easy to miss because the output looks plausible. A generated "Export to PDF" button may render perfectly yet do nothing, which erodes trust faster than an honest error message. Catching it at validation time is far cheaper than catching it from user complaints.
Take quiz
A button bound to an action your app never defined
A skeleton loader shown during streaming
A cached image
A dark-mode toggle
Making the buttons bigger
A longer system prompt alone
An allow-list of registered action names checked before rendering
Removing the error logs
16. List the main accessibility requirements for Generative UI?
Generated interfaces must meet the same baseline as hand-built ones:
- Semantic HTML: real buttons, headings, and labels
- Keyboard operation with visible focus
- Text contrast of at least 4.5:1 (WCAG AA)
- Text alternatives for charts and images
aria-liveannouncements for content that updates- Focus management when dialogs or new content appear
- Respect for reduced-motion settings
- No meaning conveyed by color alone
Most of this is best built into the catalog components once, rather than asking the model to remember it each time. The model then only supplies content such as labels and alt text, which a lint rule can check.
Take quiz
To speed up streaming
To change fonts
To block copy-paste
So screen readers announce updates that appear without a page load
Autoplay audio
A text summary or data table alternative
A hidden decorative GIF
A longer animation
17. What is a fallback UI in Generative UI?
A fallback UI is the safe default shown when generation fails or validation rejects the output: a plain text answer, a standard table, a static template, or a retry panel.
Typical triggers are timeouts, schema failures, unsafe content, missing data, and unsupported devices. The principle is that the user must always be able to finish the task. Test fallbacks like any other screen and log why they fired.
Fallbacks usually come in levels, from least to most drastic:
- Render the valid components and put a placeholder where one failed.
- Show the standard template for that intent.
- Show a plain text answer with a retry button.
Take quiz
Whenever the user scrolls
Only on the first-ever visit
When generation times out or output fails validation
Whenever the model succeeds
The user can still complete the task
It blocks until the model recovers
It shows raw stack traces
It shows nothing and hides the error
18. What is the difference between Generative UI and server-driven UI?
Both send a declarative description of the screen to the client. The difference is who writes that description: in server-driven UI, humans author rules and configs; in Generative UI, a model produces it at runtime from the user's intent.
| Aspect | Server-driven UI | Generative UI |
| Layout decided by | Backend rules and configs | Model, from intent and context |
| Variety | Predefined layouts and variants | Open-ended combinations within a catalog |
| Predictability | High | Lower, needs guardrails |
| Testing | Snapshot tests | Schema tests plus evals |
| Best for | Stable flows, A/B tests | Long-tail, exploratory tasks |
They combine well: the same renderer can serve both, with the model simply being another producer of the JSON.
Take quiz
Both require the model to write JavaScript
Both send a declarative description that the client renders
Both avoid component libraries
Both skip validation
Server-driven UI, because it never changes
Neither, both are identical
Static HTML
Generative UI, because layouts vary by request
19. How does intent detection drive UI selection?
The system classifies the request into an intent (compare, track, schedule, analyze, create) and extracts entities such as items, dates, and metrics. The intent maps to a UI pattern, and the entities fill its props.
flowchart LR
A["User request"] --> B["Intent classifier"]
B --> C["Entity extraction"]
C --> D{Confident?}
D -->|Yes| E["Pattern router"]
D -->|No| F["Ask clarifying question"]
E --> G["Component + props"]
G --> H[Render]
Routing can be a rule table, a small classifier, or the main model using tools. Low confidence should trigger a clarifying question rather than a wrong screen.
Keep a short list of supported intents and measure how often requests land in an "unknown" bucket. That bucket is the best source of new patterns to build next.
Take quiz
Fill the chosen pattern's props, such as dates or metrics
Choose the CSS theme
Replace the intent label
Encrypt the request
Render the most complex layout
Always pick the first pattern
Ask a clarifying question instead of rendering a guess
Reload the page
20. Why do we use a component registry instead of letting the LLM write raw HTML?
Raw HTML from a model is hard to trust. It can break layout, ignore brand rules, skip accessibility, or carry injected scripts. A registry limits output to vetted components.
- Safety: no arbitrary script or markup reaches the page.
- Consistency: components use design tokens.
- Accessibility: semantics and keyboard support are built in.
- Testability: each component is tested once.
- Cost: a short spec is cheaper than a page of markup.
The trade-off is novelty: the model cannot produce layouts the catalog lacks. Teams add components as new needs show up in logs.
A registry also makes reviews practical: designers and accessibility specialists approve each component once, instead of auditing every generated page.
Take quiz
Slow database queries
DNS outages
Expired TLS certificates
Arbitrary script or markup being injected into the page
It makes output less secure
The model cannot produce layouts the catalog lacks
It forbids data fetching
It removes theming
21. How does schema validation protect generated UIs?
Validation checks the model's JSON against the component schema before anything renders. Invalid output is repaired, retried, or replaced.
- Parse the output with a tolerant JSON parser.
- Validate types, required fields, and enums.
- Sanitize strings and check URLs against an allow-list.
- On failure, retry with the error message or show a fallback.
const result = ProductCard.safeParse(candidate); if (!result.success) { return retryWithFeedback(result.error.issues); } render(result.data);
Feeding the validation error back to the model usually fixes the problem in one retry. Cap retries to bound cost and latency.
Run strict validation only when a component's JSON is complete. Half-finished streamed JSON will always fail a strict schema, so partial output needs a tolerant parser until the closing brace arrives.
Take quiz
To expose internals to users
To increase the token limit
So it can correct the specific fields that failed
To disable validation next time
To bound latency and cost before showing a fallback
Because schemas expire
So the model forgets context
To avoid streaming
22. Why is a design token system important for Generative UI?
Design tokens (color, spacing, typography, radius, elevation) let generated screens look like your product without the model choosing raw values. The model picks semantic names such as color.danger or space.md, and the renderer maps them to real values.
- Brand consistency across every generated screen
- Dark mode and high-contrast themes by swapping a token set
- Contrast ratios guaranteed upstream, not left to the model
- Rebranding without rewriting prompts
Without tokens, the model may pick arbitrary hex colors that fail contrast checks.
Tokens also keep the prompt short. Instead of describing brand colors and spacing scales to the model, you list a few dozen token names and let the theme resolve them.
Take quiz
Arbitrary hex values for each element
Semantic names such as color.danger
Pixel coordinates
Font file binaries
They delete unsupported components
They encrypt the theme
They cache API calls
Swapping a token set changes contrast or size across every component
23. How does a Generative UI pipeline work end to end?
The app sends the request plus the component catalog and context to the model. The model may call data tools, then returns a UI spec that the app validates and renders. User interactions loop back into the flow.
sequenceDiagram participant U as User participant A as App participant M as Model participant T as Data tool U->>A: Request A->>M: Prompt + catalog + context M->>T: Call data tool T-->>M: Data M-->>A: UI spec A->>A: Validate spec A-->>U: Render components U->>A: Interaction
Validation sits between the model and the renderer, so nothing unchecked reaches the screen.
Each hop is a place to add logging, which is what makes failures debuggable: you can replay the exact prompt, catalog version, tool results, and spec that produced any given screen.
Take quiz
Between the model's UI spec and rendering
After the user closes the app
Before the user types
Inside the database
The full source of the browser
All other users' sessions
The component catalog and relevant context
Private signing keys
24. When should you choose structured output over free-form code generation?
Choose structured output (a JSON spec rendered by your own components) when the task fits the catalog, when safety and consistency matter, and when latency and cost count. Choose code generation when the user needs something genuinely novel, like a custom simulation, and you can sandbox it.
| Factor | Structured output | Code generation |
| Safety | High | Needs a sandbox |
| Flexibility | Bounded by the catalog | Very high |
| Cost and latency | Low | Higher |
| Accessibility | Inherited from components | Must be verified |
| Debugging | Schema errors | Runtime errors |
Many teams use structured output for the large majority of requests and keep code generation behind a flag for power users, since the sandbox, review, and monitoring work only pays off when requests are truly open-ended.
Take quiz
Free-form code executed in the main page
Raw HTML injected via innerHTML
An eval of the model's text
Structured output rendered by vetted components
Latency must be the lowest possible
The request is novel and the code can be sandboxed
The design system must be strictly enforced
Accessibility must come for free
25. What is the difference between a micro-app and a static widget in Generative UI?
A static widget shows a result and stops. A micro-app keeps state, handles events, and can re-query data.
| Static widget | Micro-app | |
| State | None | Local state, such as filters or inputs |
| Interaction | Read-only | Edit, filter, calculate |
| Data | Fetched once | May re-query |
| Example | Weather card | Budget planner |
Micro-apps need clear state ownership: slider positions stay local, while a changed request ("add a region filter") goes back to the model as a new intent.
For instance, a generated "compare two plans" card is a widget. Add a monthly or yearly toggle, a seat-count slider, and a recalculated total, and it becomes a micro-app. The second needs state handling, input validation, and tests that the first does not.
Take quiz
By asking the model on every pixel of movement
In the URL hash only
In local component state, without calling the model on each move
In the model's weights
A read-only weather card
An editable budget planner
A drag-and-drop kanban board
A filterable data grid
26. How do you pick the right chart type from user intent?
Map the question to a chart family, then check the field types.
| User intent | Chart |
| Trend over time | Line |
| Compare categories | Bar |
| Part of a whole (few parts) | Stacked bar or donut |
| Distribution | Histogram or box plot |
| Relationship between two measures | Scatter |
| Geography | Map |
Add rules the model must follow: time on the x-axis, bar axes start at zero, avoid pies beyond about five slices, and cap the number of series. Validate that a temporal field is used for lines and a categorical field for bars.
When the intent is vague, such as "show me sales", prefer a sensible default (a line over time) and offer a one-click switch to alternatives rather than asking a question first.
Take quiz
A pie chart by weekday
A line chart with time on the x-axis
A scatter of user IDs
A map
Truncate the axis to exaggerate differences
Use 3D bars
Always sort alphabetically
Start the value axis at zero
27. How does adaptive personalization differ from static user preferences?
Static preferences are chosen once by the user (theme, language, default view). Adaptive personalization is inferred from behavior and context and can change per session.
| Static preferences | Adaptive personalization | |
| Source | Explicit settings | Inferred signals |
| Change | Manual | Automatic |
| Predictability | High | Lower |
| Main risk | Stale settings | Wrong or creepy assumptions |
Let explicit preferences always win over inferred ones, and explain adaptations briefly, for example "Showing approvals first because you open them daily".
A practical rule is to treat inference as a suggestion. Show the adapted layout, make the reason visible, and offer an "always use this" option that converts an inferred behavior into an explicit preference the user owns.
Take quiz
Follow the explicit setting
Follow the inference silently
Alternate randomly
Ask the model to decide each time
Bundle size
Database indexing
Transparency and trust
Build time
28. How do you personalize a generated UI without invasive tracking?
Use the least data that still works, and keep it close to the session.
- Prefer on-device or session-only signals.
- Use coarse signals (role, device type) instead of raw history.
- Ask for consent and expire stored data.
- Send the model derived traits such as "prefers compact tables", not raw logs.
- Provide a clear off switch.
- Avoid sensitive inferences (health, finances) unless the user opts in.
The current task alone often gives most of the benefit and needs no stored profile.
Review data flows the way you would for any analytics feature: document what is collected, why, how long it is kept, and who can access it. Generated UIs make it tempting to pass more context to the model than is needed.
Take quiz
The full raw click history
The user's complete browsing log
Unredacted chat transcripts from last year
A derived trait like "prefers compact tables"
Inferred health conditions
The current task in this session
Cross-site browsing history
A precise location trail
29. Why should generated forms keep human confirmation for irreversible actions?
The model may misread intent, fill in wrong values, or be steered by injected content. Deleting data, sending money, or emailing customers cannot be undone cheaply, so a person must approve the exact action.
- Show a summary of what will happen, with the exact values.
- Require an explicit confirm action.
- Offer undo where it is possible.
- Log who approved what.
- Scope permissions so a tricked model cannot reach more than the user could.
Drafting is a safer pattern than doing. Let the model prepare the email or transfer as a draft with every value visible, and keep the final send as a deliberate user action handled by app code, not by another model call.
Take quiz
A generic "Are you sure?" only
Only the model's confidence
The exact values and effect of the action
The system prompt
Sending a bank transfer
Changing a chart color
Collapsing a panel
Sorting a table
30. How is Generative UI used in e-commerce?
Shoppers describe a need ("a waterproof jacket for hiking under $150") and the interface builds around it: a comparison grid with only relevant attributes, a size and fit helper, outfit bundles, and a short path to checkout.
- Attributes vary by category: waterproof rating for jackets, memory for laptops.
- Prices and stock come from catalog APIs through tools.
- Guardrails block invented discounts or unavailable items.
- Personalization can reorder results, but sponsored items must be labeled.
Freshness matters: the same query a minute apart may show different stock. Show an as-of time for price and availability, and rerun the tool call at checkout instead of trusting what the earlier card displayed.
Take quiz
The model's memory of past prices
The catalog API via a tool call
An estimate from the user's query
Random rounding
To hide the price
To shrink the database
Because tables cannot hold more columns
Different products matter on different specs
31. How is Generative UI used in healthcare dashboards?
A clinician asks for "this patient's A1C trend and current medications" and gets a summary card plus a lab chart with reference ranges, instead of clicking through several EHR tabs.
- Data comes only from the EHR through authorized tools.
- Every value shows its source, units, and timestamp.
- The UI never presents a generated diagnosis as fact.
- Access follows role and the minimum-necessary principle, with audit logs.
- Any write action needs clinician review.
Clarity matters more than novelty here. Use consistent units, flag abnormal values with text and icons as well as color, and keep the generated view reproducible so a clinician can see exactly what was displayed at decision time.
Take quiz
Reference ranges, units, and timestamps
Decorative animations
Marketing banners
Model temperature settings
Let the model apply them silently
Skip permissions for speed
Require clinician review and log them
Store them only in the browser
32. How is Generative UI used in enterprise analytics and BI?
Users ask a question in plain language ("why did EMEA revenue drop in Q3?"). The system generates a query through a semantic layer, runs it, and returns charts, a table, and notes. Users then drill down or pin the view as a dashboard.
- A semantic layer defines metrics once, so "revenue" means the same everywhere.
- Row-level security applies the user's data permissions.
- Showing the query or metric definition builds trust.
- Results can be cached and saved as dashboards.
Ambiguity is the main risk: "revenue" might mean booked or recognized. When the semantic layer has several candidates, ask which one is meant or show the chosen definition prominently beside the chart.
Take quiz
To make charts animate
To avoid querying the database
To hide data from admins
So metrics like revenue are defined once and used consistently
Faster rendering
Trust and verification of the numbers
Smaller CSS
Color accessibility
33. Why do generated UIs need accessible semantics like ARIA and focus management?
Generated content appears without page loads, and screen reader and keyboard users will not notice it unless the UI announces it and manages focus. Native HTML comes first; ARIA fills the gaps.
- Use
<button>,<label>, and<table>before adding roles. - Use
aria-live="polite"for streamed answers. - Move focus into new dialogs and return it on close.
- Label chart regions and announce loading and error states.
Charts and dynamic tables are the usual failure points. Give each chart an accessible name and a text summary, offer the underlying table, and make tooltips reachable by keyboard, not only on mouse hover.
Another frequent bug is streamed text updating a live region token by token, which makes screen readers chatter. Announce completed sentences or a short "answer ready" message instead.
Take quiz
A div with only an onclick handler
A span with a pointer cursor
A native button element
An image map
Move into the dialog and return to the trigger on close
Stay on the page behind it
Jump to the browser address bar
Reset to the top of the document
34. How do you evaluate the quality of generated UI?
Combine automated checks with human review, and run them on a fixed prompt set after every model, prompt, or catalog change.
- Schema validity rate: how often output is structurally correct.
- Task success: golden prompts with expected outcomes.
- Visual regression: screenshots of representative outputs.
- Accessibility audits: axe checks on rendered screens.
- LLM-as-judge: relevance and layout scoring, spot-checked by people.
- Latency and cost: p95 per request.
- User signals: edits, regenerations, abandonment.
Start small. Even 50 representative prompts with expected component types and key facts will catch most regressions. Add every production failure to the set, so the evals grow from real problems instead of imagined ones.
Take quiz
To avoid testing accessibility
To compare model and prompt changes on the same inputs
To reduce model size
To stop schema validation
Average font size
Page weight in MB
Number of CSS files
Schema validity rate
35. How does streaming improve perceived performance in Generative UI?
By controlling what appears first: a skeleton layout within a second, then text, then data components as tool results arrive. Users see progress and can start reading while the rest generates.
- Stream the layout skeleton first.
- Render each component as soon as its props are complete.
- Reserve space so content does not jump (avoid layout shift).
- Show progress labels such as "Fetching sales data...".
- Let the user cancel.
Streaming does not fix slow tools. If a data query takes eight seconds, the skeleton and progress label are what keep the screen feeling alive, so show which step is running and let the fast parts of the answer appear first.
Take quiz
To prevent layout shift as content streams in
To hide errors
To speed up the model
To disable scrolling
Faster GPUs
A higher token limit
Control when the answer heads in the wrong direction
Better contrast
36. Explain the lifecycle of a generated micro-app session?
A micro-app moves from intent to a validated interactive tool, may be regenerated as the request changes, and ends by being pinned or discarded.
stateDiagram-v2 [*] --> Intent Intent --> Generating Generating --> Validating Validating --> Interactive: valid Validating --> Fallback: invalid Interactive --> Interactive: local event Interactive --> Regenerating: structure change Regenerating --> Validating Interactive --> Pinned: save Interactive --> [*]: close
- Intent: the request and context are captured.
- Generation: the model returns a spec and initial data.
- Validation: schema and safety checks run; failures go to a fallback.
- Interactive phase: local state handles sliders and filters; tools fetch fresh data.
- Regeneration: when the request changes shape ("add a region filter"), the model updates the spec while stable IDs preserve existing state.
- Persistence or teardown: the user pins it, shares it (with a permission check), or it expires.
Version the spec together with its saved state, so a pinned micro-app still renders after the catalog changes.
Take quiz
When a slider moves
When the cursor hovers
On every keystroke
When the request changes its structure, like adding a new filter
To speed up streaming
So a pinned micro-app still renders after catalog updates
To remove validation
To shrink the model
37. Explain the execution flow of rendering a tool-call result as a UI component?
The model asks for a UI by calling a tool, the server validates and runs it, and the client turns the result into a component.
sequenceDiagram participant C as Client participant S as Server participant M as Model participant T as Tool C->>S: User message S->>M: Messages + tool definitions M-->>S: Tool call (name, args) S->>S: Validate args against schema S->>T: execute(args) T-->>S: Result data S-->>C: Stream tool part C->>C: Map tool name to component C-->>C: Render component S->>M: Tool result M-->>S: Short text summary
- The client sends the message.
- The server calls the model with the tool definitions.
- The model emits a tool call with arguments.
- The server validates the arguments before executing anything.
executefetches data and returns a result.- The result streams to the client as a message part.
- The client looks up the component by tool name and renders it.
- The model continues with a short text that refers to the UI.
Unknown tool names fall through to a fallback, so a bad name never renders anything unexpected.
Take quiz
The user's IP address
The HTTP method
The tool name in the message part
The model's temperature
Model output is untrusted input and must be checked before execution
The client cannot parse JSON
To avoid streaming
Validation is only for databases
38. How do you prevent prompt injection from manipulating generated UI?
Injection arrives through content the model reads (web pages, emails, tickets, documents) and tries to steer it into rendering deceptive UI, links, or actions. Treat all retrieved content as untrusted data.
- Separate instructions from data and mark retrieved text as untrusted.
- Render only catalog components and never inject model-produced HTML.
- Use URL and action allow-lists, and show the real link destination.
- Apply least privilege: tools carry only the current user's permissions.
- Require confirmation for sensitive actions, showing exact values taken from the app, not from model prose.
- Block lookalike login forms and credential requests in output.
- Red-team with injection test cases and log every blocked attempt.
Assume the model can be tricked, and make sure a tricked model still cannot do damage. In particular, avoid giving write tools to a turn that also reads untrusted content, unless a human confirms.
Take quiz
Execute any commands it contains
Treat it as untrusted data, never as instructions or markup
Trust it if the site looks official
Inject it directly with innerHTML
Tools run as admin for convenience
One shared service key serves all users
Tools run with no logging
Tools carry only the permissions the current user already has
39. How can you sandbox generated code or micro-apps?
Run model-written code in an isolated origin with no access to the host page, strict network rules, and a narrow message channel.
- Use an
iframewith thesandboxattribute, hosted on a separate origin. - Set a strict CSP (no inline eval, limited
connect-src). - Talk to the host only through
postMessagewith schema-validated messages. - Keep cookies and storage out of reach of the sandbox.
- Enforce timeouts, memory limits, and a network egress allow-list.
- Keep a kill switch to disable a bad app quickly.
<iframe sandbox="allow-scripts" src="https://apps-sandbox.example.com/run/abc123" referrerpolicy="no-referrer"></iframe>
Be careful with allow-scripts plus allow-same-origin on a frame that shares the host's origin: the framed page could then remove its own sandbox.
Treat sandboxed apps as untrusted even when your own model wrote them, since the model may have been influenced by injected content. Run a static scan for risky APIs such as dynamic eval and unexpected network calls before executing the code.
Take quiz
allow-scripts together with allow-same-origin
allow-forms with allow-modals
allow-popups with allow-downloads
allow-pointer-lock with allow-orientation-lock
Reading parent.document directly
Sharing cookies
postMessage with schema-validated messages
Global variables on window.top
40. What happens when the model emits an invalid component or props?
A well-built pipeline catches it before rendering and reacts in a defined order.
- Detect: schema failure, unknown component type, or out-of-range value.
- Repair deterministically when it is safe: trim a string, clamp a number, apply a default enum.
- Retry once or twice with the validation error fed back to the model.
- Degrade: render the valid parts and swap only the broken component for a placeholder.
- Fall back to plain text or a standard template if the whole spec is unusable.
- Log the prompt and spec so the case can join your evals.
Never render partially trusted props. Partial rendering is fine only at component boundaries, using a per-component error boundary, so one bad card does not blank the screen.
Distinguish error types in your logs. A spike in unknown component names suggests the prompt or catalog descriptions are unclear, while frequent out-of-range values point to a constraint missing from the schema description the model sees.
Take quiz
Reloading the entire app
Ignoring the error silently
Disabling schema validation
A per-component error boundary with a placeholder
Guessing a missing account number
Clamping a number into its allowed range
Inventing a missing URL
Changing a currency code
41. How do you troubleshoot inconsistent UI across sessions for the same request?
Variation comes from sampling, prompt drift, changing context, and catalog versions. Work through the causes in order.
- Capture the prompts and specs from both runs and diff them.
- Check sampling settings and lower temperature for layout decisions.
- Compare context: personalization signals, history, locale.
- Check for catalog or prompt version changes between runs.
- Add deterministic routing for common intents so the pattern is fixed and only the content varies.
- Cache or pin successful specs per intent and context hash.
- Add the case to your eval set to catch regressions.
Some variation is intended, for example personalization. The goal is a stable structure with variable content.
Also check whether the difference is user-visible or only structural. Two specs with different wrapper layouts but identical content may render the same, in which case normalizing the spec before caching or comparing avoids chasing noise.
Take quiz
Rewrite the design system
Raise the temperature
Diff the stored prompts and specs from both runs
Delete the logs
Deterministic routing rules that fix the pattern
Removing validation
Randomizing component order
Longer greetings
42. How can you optimize token cost and latency in Generative UI?
The biggest win is not making the model reproduce your data. Return a reference such as "table of query_17" and let the renderer load the rows.
| Technique | Effect |
| Prompt caching of the catalog and system prompt | Cuts input cost and time-to-first-token |
| Compact specs with data references | Fewer output tokens |
| Tools fetch data; model picks encodings | No invented or retyped numbers |
| Small fast model for routing, larger one for composition | Lower cost on easy steps |
| Stream skeleton first | Lower perceived latency |
| Cache specs per intent and context | Skip generation on repeats |
| Cap retries, paginate big tables | Bounded worst case |
Measure before tuning: log input tokens, output tokens, tool time, and time-to-first-component per request. Most teams find that the catalog prompt and retyped data dominate cost, which is exactly what caching and references address.
Take quiz
It makes charts 3D
The model emits far fewer output tokens
It removes the need for tools
It improves color contrast
Unique user questions
Streamed output
Image resizing
A large, repeated catalog and system prompt prefix
43. Which is better and why: a constrained component catalog or open-ended code generation?
For most production products, a constrained catalog, because it gives safety, accessibility, brand consistency, and predictable cost. Open-ended code generation wins only for truly novel, one-off tools, and it needs sandboxing.
| Constrained catalog | Open-ended code | |
| Safety | Strong | Needs sandbox |
| Accessibility | Built into components | Unverified by default |
| Brand consistency | Enforced by tokens | Drifts |
| Novelty | Limited to catalog | Unlimited |
| Cost and latency | Low | Higher |
A practical pattern is a hybrid: catalog by default, with a labeled, sandboxed micro-app as an escape hatch for the long tail. Use request logs to decide which new components to add.
A decision test: would ten different users with the same request be well served by the same components filled with different data? If yes, a catalog is enough. If every request needs a unique interaction model, the sandboxed route earns its cost.
Take quiz
Catalog by default with a sandboxed escape hatch for novel requests
Open code generation in the main page by default
No catalog and no sandbox
A catalog that can never be extended
Unlimited novelty
Zero maintenance
Accessibility and brand consistency built into components
No testing needed
44. How do you design guardrails for Generative UI in finance?
Finance raises the stakes on accuracy, compliance, and irreversible actions, so guardrails go beyond schema checks.
- Numbers come only from authorized systems through tools, with an as-of timestamp.
- Calculations (interest, totals, tax) run in deterministic code, not in model arithmetic.
- Regulatory disclosures are fixed, approved template text, never freshly generated.
- No personalized investment advice unless the product is approved for it.
- Transfers need explicit confirmation and step-up authentication.
- Keep an audit trail of the prompt, spec, and user action.
- Apply role-based access, PII masking, and anomaly detection.
- Label generated content clearly.
Requirements vary by jurisdiction, so involve compliance early in the design.
Test with adversarial cases: ambiguous amounts, mixed currencies, rounding edges, and attempts to make the model skip a disclosure. These are the failures that regulators and customers notice.
Take quiz
The model's estimation
A guess rounded by CSS
The user's browser history
Deterministic code, not by the model's arithmetic
Freshly worded by the model each time
Fixed, approved template text
Omitted when space is tight
Summarized loosely
45. How do you automate accessibility testing for generated interfaces?
Because the output varies, test at three levels: components, specs, and rendered screens.
- Components: run axe and keyboard tests on every catalog component in CI, so most accessibility is guaranteed upstream.
- Specs: lint for rules such as every chart has a text alternative, every input has a label, heading order is valid, and only contrast-safe tokens are used.
- Rendered screens: render a sample of generated screens in a headless browser and fail or fall back on serious violations.
- Key flows: smoke-test keyboard and screen reader behavior.
- People: audit with real assistive technology users.
import AxeBuilder from "@axe-core/playwright"; const results = await new AxeBuilder({ page }) .withTags(["wcag2a", "wcag2aa", "wcag22aa"]) .analyze(); expect(results.violations).toEqual([]);
Automated tools find only a portion of issues, so they complement manual review rather than replace it.
Take quiz
They never appear in generated screens
It replaces user testing
Every generated screen inherits their accessibility
It speeds up the model
They detect only a portion of accessibility issues
They cannot run in CI
They only check fonts
They require native apps
46. How does perceptual personalization adapt UI to sensory and cognitive needs?
It reads device signals and explicit settings, then applies them as constraints or token overrides.
| Need or signal | Adaptation |
| Low vision, large text setting | Bigger type, high-contrast tokens, simpler layout |
| Color blindness | Patterns and direct labels in charts, safe palettes |
| Motion sensitivity (prefers-reduced-motion) | No animation, simple fades |
| Lower cognitive load preference | Fewer choices per screen, step-by-step flow |
| Reading level preference | Plain-language rewrite of text |
| Bright or noisy situation | High-contrast mode, captions |
Apply visual adaptations after generation as token overrides, so they hold no matter what the model produced. Use the model for content adaptations like simplified wording. Avoid inferring a disability from behavior; rely on OS signals (prefers-contrast, prefers-reduced-motion) and opt-in settings.
Test each adaptation on real components. Raising text size to 200 percent should not truncate content or break layouts, and high-contrast mode should keep focus indicators and chart series distinguishable.
Take quiz
It uses too many tokens
It is sensitive and error-prone, so rely on explicit settings and device signals
Disabilities cannot be supported on the web
Device signals are illegal
More saturated red-green pairs
Color-only legends
Rainbow gradients
Patterns or direct labels in addition to color
47. How do you maintain user trust and predictability when the UI changes per session?
Think "consistent skeleton, flexible content". Keep the frame stable and let only the content region adapt.
- Keep navigation and primary actions in fixed places.
- Explain adaptations briefly.
- Let users pin or save a layout that worked.
- Offer undo, revert, and regenerate controls.
- Show data sources and freshness.
- Label AI-generated areas.
- Use the same interaction patterns and terminology across components.
- Never move a control under the user's cursor.
Track trust signals such as regenerate and undo rates; a spike usually means the UI is surprising people.
Transparency helps most at moments of surprise. If a screen differs from last time, a one-line note such as "Reordered to show open tickets first" lets the user understand it and reverse it. Unexplained change feels random even when it is helpful.
Take quiz
A stable shell with a variable content region
Regenerating the whole page, navigation included, each time
Moving buttons while the user hovers
Renaming actions per session
It removes the need for data sources
It speeds up GPUs
Users can return to a layout that worked for them
It removes accessibility needs
48. How would you design an outcome-oriented interface to replace a multi-step workflow?
Take expense reporting. The outcome is a submitted, policy-compliant report with receipts attached.
flowchart LR
A["Intent + receipts"] --> B["Tools pre-fill from receipts, calendar, policy"]
B --> C["Single review screen"]
C --> D{Exceptions?}
D -->|Yes| E["User resolves flags"]
D -->|No| F["One-click submit"]
E --> F
F --> G["Status shown"]
- Define the outcome and its completion criteria.
- Map existing steps and mark those that exist only because of the old UI.
- Capture intent ("submit my Berlin trip expenses") and receipts.
- Pre-fill through tools from receipts, calendar, and policy.
- Generate one review screen with grouped expenses, policy flags with reasons, and the total, asking only about exceptions.
- Confirm once, then show status.
- Keep an escape hatch to the classic form.
- Measure completion time, corrections, and policy violations.
Take quiz
Every field of the old form in sequence
Decorative onboarding tips
Unrelated dashboards
Exceptions and policy flags that need the user's decision
To hide the new interface
So users can finish when automation misreads the situation
To double the number of steps
To avoid logging
49. How do you version and govern the component catalog for generated UIs?
The catalog is a contract between design, engineering, and the model, so it needs the same discipline as a public API.
- Use semantic versions for components and schemas, and prefer additive changes.
- Set deprecation windows and keep adapters so older saved specs still render.
- Require design, accessibility, and security sign-off for new components.
- Roll out new components behind feature flags with canary traffic.
- Run contract tests between each schema and its renderer.
- Track usage telemetry and retire unused components.
- Keep documentation and examples per component, and reuse them as few-shot examples in prompts.
Version the prompt and few-shot examples together with the catalog. A catalog change that ships without updated model instructions is a common source of invalid specs, so release them as a pair and run the eval set against both before rollout.
Take quiz
To allow breaking changes without notice
To increase model temperature
Saved or pinned UIs must keep rendering after the catalog evolves
To avoid versioning
A feature flag with canary traffic and telemetry
Ship to everyone and fix issues later
Remove older versions first
Ask the model whether it works
50. Explain the internal working of declarative chart generation in Generative UI?
The model writes a small declarative spec, such as Vega-Lite, describing what to show. A renderer decides how to draw it.
flowchart LR Q[Question] --> M[Model] M --> S["Chart spec JSON"] S --> V[Validator] V --> D["Bind dataset"] D --> R[Renderer] R --> I["Interactive chart"] I -->|selection events| M
{ "data": { "url": "/api/datasets/q17" }, "mark": "line", "encoding": { "x": { "field": "week", "type": "temporal" }, "y": { "field": "signups", "type": "quantitative" }, "color": { "field": "region", "type": "nominal" } }, "params": [{ "name": "brush", "select": "interval" }] }
- The tool prepares the dataset; the spec only references it.
- The validator checks that every field exists in the dataset schema and that types fit the encoding, for example a temporal field for a line.
- The renderer compiles the spec: it builds scales, axes, legend, and marks.
- Selection params emit events that can filter other components or go back to the model as a new intent.
The model reasons about encodings, not pixels, so rendering is deterministic and testable. Highly custom visuals fall outside what a declarative spec can express.