Skip to the content

Lesson 275 of 296

Hallucination, structured outputs and tool calling

What you will learn

  • What hallucination is and how to reduce it
  • Prompting basics that work
  • Structured outputs: getting reliable JSON
  • Validating model output with Zod
  • Tool calling (function calling)
On this page

Hallucination

A hallucination is when the model states something false as if it were true: a made-up function, a wrong date, a fake reference. It happens because the model produces likely-sounding text; it does not check facts.

Ways to reduce it:

MethodHow it helps
Give it the factsPut the real data or documents in the request (RAG, Lesson 276)
Allow "I don't know"Tell it to say it does not know when the answer is not in the given text
Ask for sourcesMake it point to which document it used, then check
Lower temperatureLess random output for factual tasks
ValidateCheck the output with code before using it
Human reviewFor anything important: money, health, legal, security

You cannot remove hallucination completely. You design around it.

Prompting basics

A prompt is the text you send. Good prompts are clear and specific:

  • Say the task, the audience and the format you want.
  • Give examples of good input and output ("few-shot" prompting).
  • Separate instructions from data with clear markers, for example put user documents inside <document> tags.
  • Keep one job per request where possible. Several small, clear calls beat one huge vague one.
  • Keep prompts in version control and test them like code (Lesson 277).

Structured outputs

Apps need data, not chatty text. If you ask "return JSON", the model usually does, but sometimes adds text, misses a field or uses the wrong type.

Many providers now offer structured outputs: you send a JSON Schema (the shape you want) and the provider makes the model's output follow that schema. Even then, validate on your side, because your code is the last line of defence and the values can still be wrong even when the shape is right.

Validating with Zod

Zod (Lesson 114) checks that unknown data has the right shape. Here the model's output is checked, and on failure the error is sent back so the model can try again, up to a limit.

TypeScript
import { z } from "zod";

const Ticket = z.object({
  category: z.enum(["billing", "delivery", "other"]),
  urgent: z.boolean(),
  summary: z.string().min(1).max(200),
});
type Ticket = z.infer<typeof Ticket>;

// A fake model: first reply is invalid, second is valid.
const replies = [
  '{"category":"shipping","urgent":"yes"}',
  '{"category":"delivery","urgent":true,"summary":"Parcel is two days late"}',
];
async function fakeModel(_prompt: string): Promise<string> {
  return replies.shift() ?? "{}";
}

async function classify(text: string, maxTries = 3): Promise<Ticket> {
  let prompt = `Classify this ticket as JSON: ${text}`;
  for (let attempt = 1; attempt <= maxTries; attempt++) {
    const raw = await fakeModel(prompt);
    let data: unknown;
    try {
      data = JSON.parse(raw);
    } catch {
      prompt += "\nYour last reply was not valid JSON. Reply with JSON only.";
      continue;
    }
    const result = Ticket.safeParse(data);
    if (result.success) return result.data;
    prompt += `\nYour last reply had errors: ${result.error.issues.map((i) => i.path.join(".") + " " + i.message).join("; ")}`;
  }
  throw new Error("Model did not return a valid ticket");
}

classify("My parcel has not arrived").then((t) => console.log(t.category, t.urgent)); // delivery true

Tool calling (function calling)

On its own, a model can only write text. Tool calling lets it ask your code to do something: look up an order, check the weather, run a search.

How it works:

  1. You send the messages plus a list of tools: each has a name, a description and a JSON Schema for its arguments.
  2. The model either answers directly or replies with a tool call: "call getOrderStatus with { "orderId": "A100" }".
  3. Your code runs the function. The model never runs anything itself.
  4. You send the tool result back to the model.
  5. The model writes the final answer using that result.
TypeScript
type ToolCall = { name: string; args: Record<string, unknown> };
type ModelReply = { type: "tool_call"; call: ToolCall } | { type: "text"; text: string };

const orders: Record<string, string> = { A100: "dispatched", B200: "processing" };

const tools: Record<string, (args: Record<string, unknown>) => string> = {
  getOrderStatus: (args) => {
    const id = String(args.orderId ?? "");
    return orders[id] ?? "not found";
  },
};

// Fake model: asks for a tool first, then answers using the tool result.
function fakeModel(history: string[]): ModelReply {
  const toolResult = history.find((h) => h.startsWith("tool:"));
  if (!toolResult) return { type: "tool_call", call: { name: "getOrderStatus", args: { orderId: "A100" } } };
  return { type: "text", text: `Your order is ${toolResult.slice(5)}.` };
}

function run(question: string): string {
  const history = [`user:${question}`];
  for (let step = 0; step < 5; step++) {
    const reply = fakeModel(history);
    if (reply.type === "text") return reply.text;
    const tool = tools[reply.call.name];
    if (!tool) throw new Error(`Unknown tool ${reply.call.name}`);
    history.push(`tool:${tool(reply.call.args)}`);
  }
  throw new Error("Too many steps");
}

console.log(run("Where is order A100?")); // Your order is dispatched.

Safety rules for tools:

  • Validate the arguments the model sends, exactly like user input. The model can send anything.
  • Check permissions: the tool must act as the logged-in user, never as an admin.
  • Ask the user to confirm before actions that change things: refunds, emails, deletes.
  • Set a step limit so a loop cannot run forever.

How to say it in an interview

"Models can hallucinate, so I give them the facts they need, let them say 'I don't know', use low temperature for factual tasks, and validate everything. For data I use structured outputs with a JSON Schema and still validate with Zod, retrying with the error message a limited number of times. For actions I use tool calling: the model only requests a tool call, my server validates the arguments, checks the user's permissions, asks for confirmation for anything that changes data, runs it and returns the result, with a step limit."

Key words

WordMeaning
HallucinationConfident but false output
Few-shot promptingIncluding examples in the prompt
Structured outputsMaking the model follow a JSON Schema
JSON SchemaA standard way to describe the shape of JSON data
Tool callingThe model asks your code to run a named function
Step limitA maximum number of model and tool rounds

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.