Quick answer

Reliable LLM output for downstream systems comes from schema-constrained output and well-designed tool calling rather than regex parsing. Use enums, additionalProperties: false and descriptive field names, and write tool descriptions that say when to use and when not to use a tool. Never accept identity as a parameter, still validate semantics, cap loops and confirm writes.

The moment an AI feature stops being a chat box and starts feeding another system, you need the output to be data rather than prose. Early implementations did this by asking nicely and parsing with regular expressions, which fails often enough to be an operational problem. Schema-constrained output and tool calling replaced that guesswork with something you can build on.

Schema-constrained output

Rather than asking for JSON and hoping, you supply a schema and the provider constrains generation so the output conforms:

{
  "type": "object",
  "properties": {
    "sentiment":  { "type": "string", "enum": ["positive", "neutral", "negative"] },
    "topics":     { "type": "array", "items": { "type": "string" }, "maxItems": 5 },
    "urgency":    { "type": "integer", "minimum": 1, "maximum": 5 },
    "needs_human": { "type": "boolean" },
    "reason":     { "type": "string", "maxLength": 200 }
  },
  "required": ["sentiment", "topics", "urgency", "needs_human", "reason"],
  "additionalProperties": false
}

Design notes that materially improve results:

  • Use enums wherever the value is from a fixed set. This eliminates an entire category of normalisation code — no more mapping "Positive", "POSITIVE" and "positive sentiment" to one value.
  • Set additionalProperties: false so the model cannot invent fields your parser will ignore.
  • Name fields descriptively. The field name is part of the prompt. customer_promised_delivery_date produces better extraction than date2.
  • Add descriptions to ambiguous fields — they are instructions the model reads.
  • Ask for the reasoning field first when the task needs thought. A model that writes its justification before its verdict produces better verdicts, and field order in the schema controls generation order.
  • Keep schemas flat where you can. Deeply nested structures are harder for models to fill correctly, and harder for you to validate meaningfully.

Designing tools a model can call

A tool definition is a prompt. The model decides whether to call it, and with what arguments, based entirely on the name, description and parameter schema:

{
  "name": "search_orders",
  "description": "Find orders for the CURRENT authenticated customer. Use when the customer asks about an order's status, contents, or delivery. Do not use for refunds — use create_refund_request instead.",
  "input_schema": {
    "type": "object",
    "properties": {
      "query":  { "type": "string", "description": "Free text: order number, product name, or date range." },
      "status": { "type": "string", "enum": ["any", "pending", "shipped", "delivered", "cancelled"], "default": "any" },
      "limit":  { "type": "integer", "minimum": 1, "maximum": 20, "default": 5 }
    },
    "required": ["query"]
  }
}

What separates tools that get called correctly from ones that do not:

  1. Say when to use it and when not to. The negative case in the description above is what stops the model calling search_orders for a refund request.
  2. Few tools, clearly distinct. Twenty tools with overlapping purposes produces wrong selections. If two tools are hard for you to distinguish in one sentence, merge them.
  3. No ambiguous parameters. A date field with no format specified will arrive in five formats. Say "ISO 8601 date, YYYY-MM-DD".
  4. Never take identity as a parameter. A customer_id argument means the model can be talked into passing someone else's. Resolve identity from the session on your side — this is the single most important security rule in tool design.
  5. Return errors the model can act on. {"error": "No orders found for that query. Try the order number instead."} lets it recover; {"error": "500"} makes it give up or hallucinate.
  6. Keep results small. Tool output goes back into the context. Returning a 40-row result set with every column burns the window and buries the answer.

Validate anyway

Constrained decoding guarantees the shape, not the meaning. The output can be schema-valid and wrong:

$data = json_decode($response, true);

// Structural — usually guaranteed, still worth asserting
$validator->validate($data, $schema);

// Semantic — never guaranteed
if (!Carbon::canBeCreatedFromFormat($data['delivery_date'], 'Y-m-d')) { /* ... */ }
if (Carbon::parse($data['delivery_date'])->isPast())                  { /* ... */ }
if (!Product::whereIn('sku', $data['skus'])->count() === count($data['skus'])) { /* ... */ }

A model asked to extract an invoice date will happily return 2026-02-30, or a SKU that does not exist, or a total that does not equal the sum of the lines. Business-rule validation is your job, and it is where most of the real errors are caught.

The failure modes to expect

  • Hallucinated arguments. The model invents an order number rather than asking. Mitigate by validating against real data and returning a clear "not found" so it corrects course.
  • Calling a tool it does not need, or answering from memory when it should have called one. Both are description problems.
  • Loops. The model calls the same tool with the same arguments repeatedly. Always cap iterations, and detect identical consecutive calls as a stop condition.
  • Truncation. A long structured response cut off by the output limit is invalid JSON. Set a generous max output and treat finish_reason: length as an error, not a success.
  • Silent partial extraction. Required fields filled with plausible defaults rather than the model admitting it could not find the value. Make "unknown" an explicit allowed value so it has a correct way to say so.

Guard the execution side

A model deciding which function to call is an untrusted input choosing a code path. Treat it that way:

  • Every tool runs with the permissions of the user, resolved server-side — never with elevated service credentials.
  • Read-only tools can execute freely; anything that writes, sends, charges or deletes needs an explicit confirmation step.
  • Rate-limit tool execution per conversation, not just per user.
  • Log every call with its arguments and result. When something goes wrong, this trace is the only account of what the system actually did.

Frequently Asked Questions

How do I get an LLM to return valid JSON reliably?

Supply a schema and let the provider constrain generation so the output conforms, instead of asking for JSON and parsing with regular expressions. Use enums for fixed sets, set additionalProperties to false, name fields descriptively, add descriptions to ambiguous fields and keep schemas flat where possible.

Why should I validate LLM output if it already matches the schema?

Constrained decoding guarantees the shape, not the meaning. Output can be schema-valid and wrong, such as a date like 2026-02-30, a SKU that does not exist, or a total that does not equal the sum of the lines. Business-rule validation is a separate job and catches most real errors.

What is the most important security rule when designing LLM tools?

Never take identity as a parameter. If a tool accepts a customer_id argument, the model can be talked into passing someone else's. Resolve identity from the authenticated session on the server, run tools with the user's permissions, and require confirmation for anything that writes, sends, charges or deletes.

Related Service

🤖 Business Process Automation

Business process automation with n8n, Zapier, Make, and AI — connect your tools, eliminate repetitive work, and let workflows run themselves around the clock.

Explore Business Process Automation →
Share this article
X Facebook LinkedIn