• 3 min read • AI Engineering

Constraining an LLM's output space beats prompting it to be careful

The first instinct when an LLM output is wrong in a way that matters is to write a better prompt. Add a line that says “only suggest times that are actually available.” Add another that says “double-check the calendar before answering.” This works about as well as telling someone to be more careful. It lowers the error rate a little and leaves the failure mode in place, because the model can still produce any string you didn’t rule out.

A more durable fix is to not let the model generate the risky part of the output at all. Give it a small closed set of real options to pick from instead of a blank field to fill in responsibly.

What “generate” versus “pick” looks like in practice

A scheduling assistant asked to suggest a new meeting time will produce “how about 2pm Thursday” whether or not 2pm Thursday is open, and the sentence is equally fluent either way. Nothing in the answer tells you whether it came from checking a calendar or from imitating what a scheduling suggestion sounds like.

Here’s the other approach, from suggestAlternativeTimes() in a scheduling app’s AI layer (src/lib/ai/nlp-parser.ts). Ordinary application code computes the available slots first:

const formattedSlots = availableSlots.map((slot, index) =>
  `Option ${index + 1}: ${slot.start.toISOString()} - ${slot.end.toISOString()}`
);

The model sees this numbered list and ranks the best three. Its response is never used as a time value:

const lines = assistantMessage.split('\n')
  .map(line => line.trim())
  .filter(line => line.length > 0)
  .filter(line => /^\d+\./.test(line));

const selectedIndices: number[] = [];
for (const line of lines) {
  const match = line.match(/^(\d+)\./);
  if (match) {
    const index = parseInt(match[1]) - 1;
    if (index >= 0 && index < availableSlots.length) {
      selectedIndices.push(index);
    }
  }
}

return selectedIndices.map(index => {
  const slot = availableSlots[index];
  return slot.start.toISOString();
});

The regex extracts a line number, not a date. That number becomes an array index into availableSlots, and the bounds check (index >= 0 && index < availableSlots.length) drops a malformed or out-of-range line. The time the function returns is always availableSlots[index].start, which came from the calendar check. The model only chooses which of the verified options to show and in what order. It can’t invent another one, because no code path turns model text into a timestamp.

The same idea elsewhere

Structured decoding, output enums and function-calling schemas with typed parameters work the same way. Instead of taking free text and hoping a downstream validator catches the bad cases, you shrink what the model can say until every possible output is one you know how to handle. Here the regex that filters bad lines is defense in depth. The guarantee comes from timestamps only reaching the caller by lookup in a real array, never by parsing the model’s prose.

This matters in proportion to what a wrong answer costs. A user can shrug off or check a hallucinated fact in a chat reply. A hallucinated time slot is something they act on: they show up to a meeting the other party never agreed to, or accept a reschedule that conflicts with something the model never checked. The more consequential the action, the less you should rely on the model behaving well, and the more engineering effort it’s worth to limit what bad behavior can look like.

The tell for when you still have this problem

The same scheduling app’s chat assistant handles booking creation and cancellation differently: it asks the model to emit an [ACTION: {...}] tag inside its normal text reply, then finds and parses that tag with a regex:

const ACTION_RE = /\[ACTION:\s*\{[\s\S]*?\}\s*\]/g;
const actionMatches = assistantMessage.match(ACTION_RE);

This is the same kind of risk as a free-text time slot, with a JSON object instead of a timestamp: the model is trusted to format something correctly inside prose, and downstream code has to find it. It’s less dangerous in practice, because a malformed tag throws in JSON.parse instead of silently producing a wrong booking, and the action still goes through the same conflict check as every other booking path. It’s still a blank field where a small, pre-validated set of choices would do. The fix would follow suggestAlternativeTimes(): real tool definitions with typed parameters, called through structured function calling, instead of a tag matched out of free text.

Back to top