# 3. Tools and structured output

How models produce machine-readable output and call functions. Function calling, JSON Schema, tool choice, structured outputs, validation and repair.

Source: https://glamorous-boar.cloudvent.net/learn/structured-output-and-tools/

---

Free text is fine for people. Software needs **structure**: a label from a fixed set, a JSON object with known fields, a SQL query, a decision to call a function. This chapter covers how to get it reliably.

## Function calling (tool calling)

With **function calling**, you describe tools to the model, each with a **name**, a **description** and a **JSON Schema** for its arguments. When the model decides a tool would help, instead of answering in text it returns a **tool call**: the tool name and arguments as JSON. Your application executes the tool and sends the result back as a `tool` message; the model continues.

<CodeBlock language="json" filename="A tool definition" showCopy={true}>

```
{
  "name": "get_weather",
  "description": "Current weather for a city. Use for any question about weather now.",
  "parameters": {
    "type": "object",
    "properties": {
      "city": {"type": "string", "description": "City name, e.g. Oslo"},
      "unit": {"type": "string", "enum": ["c", "f"]}
    },
    "required": ["city"]
  }
}
```

</CodeBlock>

<Diagram caption="One round of function calling.">

```
sequenceDiagram
  participant App
  participant Model
  participant Tool
  App->>Model: messages + tool definitions
  Model-->>App: tool_call get_weather {city: Oslo}
  App->>Tool: run get_weather(city=Oslo)
  Tool-->>App: {temp_c: 3}
  App->>Model: messages + tool result
  Model-->>App: It is 3 degrees in Oslo right now.
```

</Diagram>

Important properties:

- **The model never executes anything.** It only *asks*. Your code decides whether and how to run the tool, which is where permissions, validation and sandboxing live.
- **The description is the interface.** The model chooses tools by reading their descriptions. Say when to use it and what it returns.
- **Parallel tool calls**: modern models may request several calls in one turn (search three things at once). Running them concurrently cuts latency.
- **Tool choice** controls behaviour: `auto` (the model decides), `required`/`any` (must call some tool), a specific tool (must call that one), or `none`.

## Forced tool calls as structured output

A neat trick: define a tool whose *arguments are the output you want*, and force the model to call it. The arguments then follow your schema. AgenticMind uses this pattern throughout:

| Node | Forced call | Schema |
|---|---|---|
| Router (LLM mode) | `choose_route` | `{route: enum of route names}` |
| Classifier | `classify` | labels (enum), confidence, reason |
| Planner | `submit_plan` | a list of tasks |
| NL-to-SQL | `submit_sql` | SQL, whether answerable, explanation |
| Evaluation judge | `submit_grade` | score 1–5, reasoning |
| Query Rewriter | standalone query + variants | |

Some providers also offer native **structured outputs** (a response format constrained to a JSON Schema). Either way: **validate** what comes back.

## JSON Schema in one minute

JSON Schema describes the shape of JSON: types (`string`, `number`, `integer`, `boolean`, `object`, `array`, `null`), `properties`, `required`, `enum`, `minimum`/`maximum`, `items`, `additionalProperties`. Draft 2020-12 is current. Schemas serve three purposes at once: they tell the model what to produce, let you validate it, and document the interface.

## Validate, then repair

Even with schemas, outputs can be wrong: missing fields, wrong types, values outside an enum, JSON wrapped in prose. Robust systems:

1. **Validate** against the schema.
2. On failure, **return the error to the model** and ask for a corrected version (a repair loop), a bounded number of times.
3. If still failing, take an explicit **fallback** path.

AgenticMind applies this to tool arguments (schema violations go back to the agent as errors), to Wingman's graph proposals (up to 3 repair rounds), to NL-to-SQL (policy and database errors go back for up to N attempts) and to the Output Guard (`max_repairs`).

## Designing good tools

- **One clear job per tool**, with a name that says it (`search_documents`, not `helper`).
- **Descriptions with *when* and *what*:** *Search the indexed documents for passages relevant to a query. Use it for any question about the documents' content. Returns numbered passages with source file, page and section.*
- **Small, typed arguments** with enums where possible.
- **Errors the model can act on:** *city must not be empty* lets it retry; a stack trace does not.
- **Bounded side effects:** timeouts, allow-lists, read-only modes, approvals for dangerous actions.
- **Return compact results.** Tool output goes back into the context window.
- **Mark permanent failures** so agents stop retrying (a site that refuses bots will not change its mind).

## Try it in AgenticMind

- Every **tool node** (Calculator, Date & Time, Web Fetch, Knowledge Search, SQL, Code Interpreter, MCP…) outputs a tool definition with a JSON Schema; rename it and rewrite its description in the inspector.
- **Output Guard** with `json_schema` and `max_repairs` gives you validated structured output from any LLM.
- **Tool Chain** calls tools deterministically, no model involved; **Tool Router** picks one tool and fills its arguments by function calling.
- The **Trace** shows every tool call's arguments and result.

<Alert variant="tip" title="Key takeaways" text="Function calling lets a model request actions with schema-shaped arguments while your code stays in control of execution. Forced tool calls are a reliable way to get structured output. Always validate, feed errors back for repair, and keep a fallback. Tool descriptions are prompts: write them carefully."/>
