A State Machine for LLM UI: Beyond Loading, Error, and Success
Every frontend developer learns to read these states: loading, error, and success, to know whether an API has their data or not. Then you plug an LLM into your app, and things get weird.
Every frontend developer learns to read these states: loading, error, and success, to know whether an API has their data or not. Then you plug an LLM into your app, and things get weird.
A response can come back with a 200 status, pass your Zod schema, and still be completely wrong in a way your code can't catch.
I found this out while building Very Hungry Tourists, a food app powered by Gemini with Google Search grounding on. I asked for Italian restaurants in Montpellier, France. One result was "Via Balbi," 4.8 stars, and a note about the focaccia. However, Via Balbi is a street in Genoa, not a restaurant. No error, valid JSON, schema passed right through.
That bug is where this article starts, but it's about what happened after, when I stopped guessing why and measured it instead.
The fix that feels right but is basically a guess
The instinctive fix is a flag on your schema:
const RestaurantSchema = z.object({
name: z.string(),
rating: z.number(),
address: z.string(),
verified: z.boolean(), // but did we actually check this?
});
Then a badge when verified is false. I almost built this at first, assuming I knew the cause: my prompt demanded "exactly THREE" results, and when grounding found only two matches, the model filled the gap. I call it the alignment trap. So I benchmarked the theory instead of shipping the badge.
Building a rig to test the theory
I ran 30 food queries across 10 cities under three conditions:
- Condition A: No search grounding.
- Condition B: Grounding on, my original rigid prompt still demanding exactly three results.
- Condition C: Grounding on, a softer prompt allowing "up to three" and forbidding invented venues, plus a self check pass.
I wrote this TypeScript code that calls the Gemini API directly, to see exactly what was sent:
const body = {
contents: [{ role: "user", parts: [{ text: prompt }] }],
};
if (useGrounding) body.tools = [{ googleSearch: {} }];
For every restaurant across all 90 calls, I checked manually whether it existed, was in the right city, and was still open. Accurate only if it passed all three.
interface EvaluationRow {
query_id: number;
city: string;
venue_name: string;
exists: boolean;
correct_city: boolean;
is_operating: boolean;
failure_reason: string;
}
I expected Condition B to fall apart and Condition C to fix it.
Where the data disagreed with me
| Condition | Accuracy Rate | Failure Rate | Total Evaluated |
|---|---|---|---|
| A: No Grounding | 40.0% | 60.0% | 30 |
| B: Grounding + Rigid Prompt | 73.3% | 26.7% | 30 |
| C: Grounding + Guardrails | 72.4% | 27.6% | 29 (1 didn’t run) |
B and C are nearly identical, a one point gap that's within noise at this sample size. My theory that a strict "exactly three" instruction was pushing the model to lie didn't hold up. Grounding does nearly all the work; prompt wording barely matters next to it.
So, what caused the other quarter of failures? Two boring, useful patterns:
- Old information. The model doesn't know when a place shuts down. Café Bun in Montpellier, Companion Coffee in Berlin, Sydney Cove Oyster Bar, all recommended, all closed. Like asking a friend who moved away years ago for a dinner spot, they're not lying, their knowledge is just outdated.
- Fuzzy geography. Come Prima was recommended for Montpellier, but it's in Le Crès, a nearby town. Big Milly's Backyard came up for Accra, really 25 kilometers away in Kokrobite. The model has no strong sense of "that's a different town."
- Actual made up places. These happened too, but turned out to be the smallest category, not the biggest.
A hallucination is not one thing. A fake restaurant, a closed cafe, and one in the wrong city look identical the moment they land in your UI as a name and a rating. Each needs a different response.
Why one boolean isn't enough
A single verified: boolean treats a closed restaurant, one two hours away, and one that doesn't exist the same. Each needs a different message, a different action, and one should never reach the user at all.
An airport departures board doesn't just say "on time" or "not on time." It says delayed, cancelled, gate changed, boarding, each label specific enough to act on. That's what's missing when everything AI generated collapses into "verified" or "not verified."
So build a state for each root cause the data showed, the same way you'd define any other schema:
const VenueStateSchema = z.discriminatedUnion("status", [
z.object({ status: z.literal("verified") }),
z.object({
status: z.literal("closed"),
lastConfirmedOpen: z.string().optional(),
}),
z.object({
status: z.literal("locality_drift"),
actualLocation: z.string(),
distanceKm: z.number(),
}),
z.object({ status: z.literal("unverifiable") }),
z.object({ status: z.literal("rejected") }), // caught before it ever reaches the UI
]);
type VenueState = z.infer<typeof VenueStateSchema>;
const VenueSchema = z.object({
name: z.string(),
rating: z.number(),
address: z.string(),
location: z.object({ lat: z.number(), lng: z.number() }),
state: VenueStateSchema,
});
type Venue = z.infer<typeof VenueSchema>;
Every venue still gets parsed through a schema before it reaches the UI, the same way RestaurantSchema did back at the start. The difference is the state is modeled honestly now, instead of collapsed into one boolean.
rejected never renders. closed and locality_drift carry their own data, a last open date or a distance, since that's what makes the message useful instead of vague. unverifiable is the honest middle ground: nothing confirmed, nothing contradicted.
Why you can't check this with the tool you already have
You can't write the validation logic above using native Google Search grounding, the googleSearch: {} tool from earlier. Not because it's hard, because the data isn't available. The search happens inside a black box, a finished answer with citations, but never the raw results behind it.
If you want the state machine above to work, retrieval and generation need to be two separate steps.
const results = await searchApi.search(`italian restaurants ${city}`);
const filtered = results.filter((r) => r.businessStatus !== "CLOSED");
const geofenced = filtered.filter((r) =>
isWithinCityBounds(r.location, city)
);
const recommendations = await generateFromVerifiedData(geofenced);
Bad data gets removed before the model touches it, instead of asking it to self report uncertainty afterward. A dedicated search API gives you a business status field and real coordinates, none available inside a single grounded call.
Putting it in the components
Once the data carries the right state, the UI work is easy: a card that treats each state as its own design decision instead of one generic disclaimer.
function VenueCard({ venue }: { venue: Venue }) {
const { state } = venue;
return (
<article className={`venue-card venue-card--${state.status}`}>
<header>
<h3>{venue.name}</h3>
<StatusBadge state={state} />
</header>
<p>{venue.address}</p>
{state.status === "closed" && (
<p className="notice notice--closed">
This spot looks closed based on recent data.
{state.lastConfirmedOpen &&
` Last confirmed open around ${state.lastConfirmedOpen}.`}{" "}
Here are some nearby places that are open now.
</p>
)}
{state.status === "locality_drift" && (
<p className="notice notice--distance">
Heads up, this is actually in {state.actualLocation}, about{" "}
{state.distanceKm} km away. Want to widen your search radius?
</p>
)}
{state.status === "unverifiable" && (
<p className="notice notice--soft">
We couldn't fully confirm this one. Worth a quick check before
you head out.
</p>
)}
</article>
);
}
rejected doesn't show up here, it never should. verified needs no extra markup, a normal card is the point of that state. The design work happens in between, each state earning its own message instead of one vague warning label.
Where this still falls short
The benchmark is a diagnostic sample, not a full map. Thirty queries across ten cities tells you something real, but won't catch every pattern, especially in regions with thinner search coverage. Maps has its own gaps too, so "verified" here means "verified against Maps," not reality.
There's a real cost too: an extra API call, extra latency, a second system to maintain. Fun weekend for a side project, real line item at scale. A lighter version, just the geofencing check, gets most of the benefit for less.
A state machine is only as good as the checks feeding it. If your search API's "closed" flag is out of date, you've just moved the zombie restaurant problem one layer over.
None of this is worth building for every LLM feature. An internal tool that auto-fills a field can tolerate a wrong guess, someone just fixes it. A customer-facing recommendation that sends a stranger to a closed restaurant costs something different: trust. Match the sophistication to what a bad guess actually costs.
The one thing to take from this
Don't design uncertainty states from a single bug or a hunch, design them from what you measured. I was sure Via Balbi was a prompt problem. The data said stale listings and blurry geography instead, things no prompt tweaking would have touched.
Loading, error, and success assume an API either has your data or it doesn't. LLMs live in a messier middle, where the response arrives, parses fine, and is still wrong. Build the states your data says you need, not the ones that feel intuitive.
The full benchmark, including the complete 89 row evaluation matrix, is available in the research post and the GitHub repo.