BuildBot

The Agent Loop

Structured output

Lesson 3 of 3

What you'll learn

  • See why "just parse the JSON from the text" is fragile
  • Use a tool definition as an output schema
  • Validate the result before trusting it

Often you don't want a conversation — you want data: a category, a score, a list of extracted fields. Asking the model to "respond in JSON" in prose works until it adds a friendly sentence, a markdown fence, or a trailing comma, and your JSON.parse throws.

The reliable pattern is to reuse the tool mechanism as a schema for the output. You define a single tool whose input schema is the shape you want, and force the model to call it:

const extract = {
  name: "save_contact",
  description: "Save the extracted contact details.",
  input_schema: {
    type: "object",
    properties: {
      name: { type: "string" },
      email: { type: "string" },
      company: { type: "string" },
    },
    required: ["name", "email"],
  },
};
// Request with tool_choice: { type: "tool", name: "save_contact" }

Now the model must return an input object matching that schema — no prose, no fences. You read toolUse.input directly.

Validate anyway

A schema guides the model; it isn't a hard runtime guarantee in your own code. Validate the returned object (a library like Zod is ideal) before writing it to a database or acting on it.

The challenge validates a structured result and rejects a bad one. Run it.

Validate structured output

validate() checks required fields before the data is trusted. Run it and see both a pass and a fail.

Loading editor…

You now have the three pieces of an agent: the loop, tools to act, and structured output to trust the results.

Sign in to save your progress across devices.