Papa Programmer
Lesson 31 of 36

Structured output and tool calls

9 min read

Optional

Why a valid-looking answer can still fail

A model writes tokens one at a time. Nothing in plain text generation guarantees that braces close, that a required key is present or that a value comes from your allowed list. Fine-tuning on correct examples makes those failures rarer. It does not remove them, and the rate depends on the model, the prompt, the training data and the generation settings.

A second kind of failure is harder to see. The JSON can parse and match the schema, and the values can still be wrong or unsafe: a refund of 5,000 when the policy says 50, or a tool called for a different customer. Measure the two separately, as Metrics for classification and generation advised: the share that parses, and the share that is correct.

Training examples for each shape

For JSON output, pair realistic inputs with outputs in exactly the format you will validate, and include the awkward cases:

  • Missing information. Show the model putting null or a clear "unknown" value instead of inventing one.
  • Optional fields. Include examples with and without them.
  • Edge values. Long strings, special characters and empty lists.

For tool calls, name only tools that exist, give arguments in the expected structure and include cases where no tool is the right answer. Keep near-duplicate examples in the same split, as Training, validation and test sets explained, so the test set stays honest. Formatting data for training shows the chat layout these examples live in.

Validate in code

The program below checks eight model outputs in four steps: parse the JSON, check the keys and types, check the values against allowed lists, and for tool calls check the caller's permissions. It then prints the rate at each step.

python
import json

ALLOWED_PRIORITY = {"low", "normal", "urgent"}
TOOLS = {
	"lookup_order": {"order_id": str},
	"issue_refund": {"order_id": str, "amount": int},
}
PERMISSIONS = {"agent": {"lookup_order"}, "manager": {"lookup_order", "issue_refund"}}

outputs = [
	("agent", '{"tool": "lookup_order", "args": {"order_id": "A100"}}'),
	("agent", '{"tool": "issue_refund", "args": {"order_id": "A100", "amount": 40}}'),
	("manager", '{"tool": "issue_refund", "args": {"order_id": "A100", "amount": 40}}'),
	("manager", '{"tool": "issue_refund", "args": {"order_id": "A100", "amount": "40"}}'),
	("manager", '{"tool": "delete_account", "args": {"order_id": "A100"}}'),
	("agent", '{"tool": "lookup_order", "args": {"order_id": "A100"'),
	("agent", '{"tool": "lookup_order", "args": {}}'),
	("manager", '{"tool": "lookup_order", "args": {"order_id": "B200"}}'),
]

def check(role, text):
	try:
		call = json.loads(text)
	except json.JSONDecodeError:
		return "not valid JSON"
	spec = TOOLS.get(call.get("tool"))
	if spec is None:
		return "unknown tool"
	args = call.get("args", {})
	if set(args) != set(spec) or not all(isinstance(args[k], t) for k, t in spec.items()):
		return "wrong arguments"
	if call["tool"] not in PERMISSIONS[role]:
		return "not permitted"
	return "ok"

results = [check(role, text) for role, text in outputs]
for (role, text), result in zip(outputs, results):
	print(f"{result:16} {role:8} {text[:48]}")
parsed = sum(r != "not valid JSON" for r in results)
print(f"parsed {parsed} of {len(results)}, accepted {results.count('ok')} of {len(results)}")

priority = '{"priority": "high"}'
print("priority allowed:", json.loads(priority)["priority"] in ALLOWED_PRIORITY)

It prints:

text
ok               agent    {"tool": "lookup_order", "args": {"order_id": "A
not permitted    agent    {"tool": "issue_refund", "args": {"order_id": "A
ok               manager  {"tool": "issue_refund", "args": {"order_id": "A
wrong arguments  manager  {"tool": "issue_refund", "args": {"order_id": "A
unknown tool     manager  {"tool": "delete_account", "args": {"order_id": 
not valid JSON   agent    {"tool": "lookup_order", "args": {"order_id": "A
wrong arguments  agent    {"tool": "lookup_order", "args": {}}
ok               manager  {"tool": "lookup_order", "args": {"order_id": "B
parsed 7 of 8, accepted 3 of 8
priority allowed: False

Seven of the eight outputs parse, but only three are accepted. One is cut off, one names a tool that does not exist, one passes the amount as text, one leaves out the order ID, and one asks an agent to issue a refund that only a manager may issue. Parsing alone would have accepted seven, so the later checks reject four more. The last line shows the same idea for a single field: high is a plausible priority that is not in the allowed list.

Note what the code does not check: whether order B200 belongs to the person asking. That check needs your data, and it is the one most often forgotten. Treat the model's call as a request, and let the application decide.

Making it more reliable

  1. Retry once with the error. Return the validation message to the model and ask for a corrected output. Limit the number of retries and fail clearly after that.
  2. Constrain decoding where available. Many providers and runtimes can force output to match a JSON Schema, which removes syntax errors. It does not make the values right. The JSON Schema site documents the format most of them accept.
  3. Keep the schema small. Fewer fields and short enums are easier to learn and to check.
  4. Test the unsafe cases. Include correct-looking calls that should be refused, and prompts that try to push a call the user may not make.
  5. Log failures. Each rejected output is a candidate training example, as Error analysis and the next round describes.

The tool use guide shows how a hosted model receives tool definitions and returns calls.

  1. ParseReject text that is not valid JSON.
  2. Check shapeConfirm the tool, keys and types match the schema.
  3. Check valuesCompare fields with allowed lists and limits.
  4. Check rightsConfirm this user may make this call on this record.
  5. Act or refuseRun it, or return a clear failure state.
From model output to action
Validate every outputParsing, schema, values and permissions are four separate checks.
The call is a requestThe application decides whether the user may do it.
Measure both ratesReport how often output parses and how often it is right.

Your reading position is saved

0%

0 of 36 complete

Contents

Learning tools