Artificial Intelligence • AI Application Engineering • 5 min read

Structured Outputs, Function Calling, and Tools

A generative model can write a sentence about the weather, but an application may need a reliable machine-readable forecast object or permission to call a weather service. These are distinct requirements. Structured outputs constrain how information is represented, while function calling lets a model request that an external operation be performed.

Picture a university assistant that receives: “Show my next class.” A language model does not automatically know the student’s live timetable. It can select a tool such as get_next_class with validated arguments. The application’s code then looks up the timetable and returns an authorized result. The model may turn that result into a readable answer.

1. Text, data, and actions are different

CapabilityWhat happensExample
Ordinary generationModel produces prose“Your next lecture may be at 10”
Structured outputModel produces data matching a format{ "course": "CS201" }
Tool selectionModel requests an operationget_next_class(student_id)
Tool executionApplication performs the operationDatabase query with access checks

The crucial boundary is that a proposed tool call is not an executed action. The host application controls if, when, and how the requested operation happens.

2. Why JSON alone is not enough

JSON is a syntax for representing values. A JSON document can be well formed and still violate application requirements.

{
  "grade": "banana",
  "passed": "probably"
}

This is valid JSON but not a valid grade record. A schema adds rules about names, value types, ranges, and required fields.

{
  "type": "object",
  "properties": {
    "grade": { "type": "integer", "minimum": 0, "maximum": 100 },
    "passed": { "type": "boolean" }
  },
  "required": ["grade", "passed"],
  "additionalProperties": false
}

Schema-supported generation can improve compliance, but application-level validation remains necessary. And passed: true still might be the wrong decision if the grading policy was misunderstood.

3. A small Python validation example

The example below does not connect to an AI service. It shows the application-side verification that should occur after model output is received.

import json

raw = '{"category": "technical", "priority": 2}'
result = json.loads(raw)

allowed = {"technical", "billing", "other"}
if not isinstance(result, dict):
    raise ValueError("Expected an object")
if set(result) != {"category", "priority"}:
    raise ValueError("Unexpected keys")
if result["category"] not in allowed:
    raise ValueError("Unknown category")
if type(result["priority"]) is not int or not 1 <= result["priority"] <= 3:
    raise ValueError("Invalid priority")

print(result)

Notice the explicit type(...) is int: in Python, bool is a subclass of int, so an ordinary isinstance(value, int) would accept booleans.

4. Tool calling as a controlled loop

A typical tool-enabled application follows this sequence:

  1. Present the model with a list of permitted tools and argument schemas.
  2. Send the user’s request and available context.
  3. Receive a tool-call proposal containing a tool name and arguments.
  4. Validate those arguments and check user permissions.
  5. Execute the permitted function in the application’s environment.
  6. Give the tool result back to the model, if a follow-up response is needed.
  7. Return a final answer or continue within a bounded workflow.
User request goes to model, which proposes tool arguments; application validates and executes a tool before displaying a result
The application, not the model, enforces permission boundaries and actually runs tools.

5. Design narrow tools

Prefer a function such as lookup_course_schedule(course_id) to a function that runs arbitrary SQL submitted by the model. Narrow tool interfaces reduce unintended behavior and simplify tests.

For a tool definition, document:

  • Purpose: What it is allowed to do.
  • Arguments: Types, formats, and restrictions.
  • Authorization: Who is permitted to use it.
  • Side effects: Whether it reads, writes, sends, deletes, or purchases.
  • Failure behavior: How errors and timeouts are reported.
  • Idempotency: Whether retrying would duplicate an action.

A model can propose a dangerous tool call even when its text appears benign. High-impact operations should use separate approval and authorization checks.

6. Handle failures deliberately

A call may fail because of invalid arguments, unavailable services, permission denial, rate limits, or unexpected responses. Use bounded retries for transient failures, not for permission denials. Never report that an action succeeded solely because the model said it would.

For example, if a calendar service returns an error when creating an event, the assistant should describe that failure rather than invent an event ID.

7. Common security boundaries

  • Prompt injection: A retrieved page may contain instructions demanding that the assistant disclose secrets; treat the page as untrusted data.
  • Excessive agency: A tool with broader permissions than necessary increases risk.
  • Sensitive outputs: Mask or exclude credentials and personal records not needed for the task.
  • Untrusted arguments: Validate IDs, file paths, domains, and SQL-like strings.
  • Logging: Store sufficient metadata for debugging without exposing sensitive payloads.
  • Human confirmation: Require approval for impactful or irreversible operations.

8. Evaluate the tool workflow

A robust evaluation checks more than whether the final text sounds convincing. Include tool selection accuracy, argument validity, authorization decisions, execution correctness, latency, cost, and behavior when the tool is down. Test cases should include malicious content and ambiguous requests.

References

Related articles in

Image preview

Fit