Skip to Content
Recodocs

07 · Make outputs executable

Decide whether a proposed tool call should reach inventory, then grade what the tool actually returned.

7 min read
Part 3
Connect tools and inputs
Model
Qwen2.5-1.5B-Instruct
Data
Synthetic facilities helpdesk
Hardware
Tesla T4 and CPU, in Google Colab
Open in Colab

Which asset would you read?

You are signed in at the Facilities Helpdesk. A colleague asks when fan F-211 was last inspected. The inventory lists both the fan and a pump in your yard. Both proposed calls use the same inspection tool and both have a valid asset ID. Pick the one you would run before you reveal the receipts.

Facilities Helpdesk · Inspection request

When was F-211 last inspected?

F211-00 · Signed in as operator · South yard

Requested fanF-211read_inspection
Different same-yard assetP-201read_inspection
Check which proposal can reach inventory

F-211: the read returned 2025-08-23 from inventory-F-211-r3.

P-201: the adapter returned asset_mismatch before querying SQLite.

Synthetic ticket with two deliberate control proposals. The measured decoder outputs appear below.

Change one fact. Hold the request, caller and yard fixed. Change only the asset in the proposed call.

Proposed assetWhat the desk should do
F-211Read the fan's record and check its date and source ID.
P-201Stop before the query. The ticket still asks about the fan.

Two changes recover the same number of outcomes

Verified outcomes on matched development tickets

1

Overall outcomes

Verified / evaluated

a
MethodOutcome
Free generation0/30
Token grammar20/30
Free generation + no-call policy20/30

Paired difference

Percentage points against free generation

b
MethodGain95% intervalWins / losses
Token grammar+66.7+33.3 to +100.020 / 0
Free generation + no-call policy+66.7+33.3 to +100.020 / 0
Source: Lesson 07, SHA-256-verified Colab export. Model inference ran on a Tesla T4 and the inventory check ran on the host CPU.

Give the model a format it can finish

A valid proposal needs exactly three string fields. An inspection proposal needs the name of the read tool and one equipment ID. A clarify or deny proposal leaves the tool and asset empty. The free decoder can produce any text, including a Markdown code block. The parser reads the whole string as JSON and checks the field types.

The token grammar builds a trie of valid commands for this restricted task. At each position the decoder takes one of the children of the current prefix. On reaching a complete command, the trie permits the end-of-sequence token.

# Excerpt from decode_proposal. Check the complete string and the field types.
try:
    pairs = json.loads(raw.strip(), object_pairs_hook=tuple,
                       parse_constant=reject_non_json_constant)
except (AttributeError, ValueError):
    return False, None
if not isinstance(pairs, tuple):
    return True, None
payload = dict(pairs)
if len(pairs) != len(payload) or payload.keys() != REQUIRED_KEYS:
    return True, None
if not all(isinstance(payload[field], str) for field in REQUIRED_KEYS):
    return True, None
# Excerpt from build_token_trie. Register each next token and its prefix.
for valid_command in grammar:
    tokens = tokenizer.encode(valid_command, add_special_tokens=False)
    assert 0 < len(tokens) < OUTPUT_TOKEN_BUDGET
    assert tokenizer.decode(tokens, skip_special_tokens=True) == valid_command
    for index, token in enumerate(tokens):
        allowed_next.setdefault(tuple(tokens[:index]), set()).add(token)
    allowed_next.setdefault(tuple(tokens), set()).update(eos_tokens)

The decoder trims each padded prompt from the sequence before looking up the generated prefix. The allowed-token lookup sees only the proposed command.

OpenAI's Structured Outputs write-up describes masking invalid tokens during decoding and distinguishes schema validity from values that may still be wrong. The notebook uses a smaller finite grammar over a catalogue of permitted strings. Its field-level results are reported separately from receipts. OpenAI engineering write-up

In Anthropic's internal evaluation, supplying tool-use examples improved reported accuracy of complex parameters from 72% to 90%. Examples can teach conventions about which values belong together. The Facilities Helpdesk comparison holds the instructions fixed between decoders and scores the requested asset explicitly. Anthropic, company-reported

The grammar fixes the shape and the inspection argument

Parse and schema use all proposals. The argument check uses inspection tickets only.

2
MethodValid JSONValid schemaRight asset
Free generation0/300/300/10
Token grammar30/3030/3010/10
Free generation + no-call policy0/300/300/10
Source: Lesson 07, SHA-256-verified Colab export. Model inference ran on a Tesla T4 and the inventory check ran on the host CPU.

F211-00 · When was F-211 last inspected? · operator, south-yard

Expected receipt
F-211 · 2025-08-23 · inventory-F-211-r3
Free generation
```json { "decision": "lookup", "tool": "read_inspection", "asset": { "equipment_id": "F-211" } } ``` → invalid_proposal
Token grammar
{"decision":"lookup","tool":"read_inspection","asset":"F-211"} → verified · 2025-08-23 · inventory-F-211-r3
Free generation + no-call policy
```json { "decision": "lookup", "tool": "read_inspection", "asset": { "equipment_id": "F-211" } } ``` → invalid_proposal

Whitespace is compacted above. The recorded free reply includes Markdown fences and a nested asset object. The parser rejects the fences, and removing them alone would still leave an asset of the wrong type.

Grade the receipt

Formatting is the first gate: the host can parse a proposal. Grounding and execution are separate gates: did the proposal refer to the intended record, and did the actual outcome satisfy the request?

The structured proposal is a candidate. The inventory adapter checks the caller's role and the intent it derives from the request. If the proposal asks to look up an asset, the adapter checks that argument against the requested ID, then checks the asset's yard against the trusted yard. Only then does the query run.

# Excerpt from observe_tool after the proposal and expected decision agree.
if decision != "lookup":
    return {**empty, "status": decision}
if proposal.asset != requested_asset:
    return {**empty, "status": "asset_mismatch"}
if ASSET_TENANTS.get(proposal.asset) != case["tenant"]:
    return {**empty, "status": "asset_out_of_scope"}

inventory = read_inventory(proposal.asset, case["tenant"], role=case["role"])

SQLite's query-only setting blocks data-changing SQL statements in this fixture. The code still needs to check the requested asset and caller's yard. A protocol such as MCP can carry the tool name and schema across a client–server boundary. The permission and request checks live at the tool boundary. SQLite documentation · MCP Tools specification

The evaluation gives a point for a verified read with the right asset, date and evidence ID, or for the required no-call outcome with no read attempt. The equations use an attempt flag and an exact asset, date and source match.

yilookup=1[Ai∧Ri],yino call=1[¬Ai∧r^i=ri].\begin{aligned} y_i^{\mathrm{lookup}} &= \mathbf{1}[A_i \land R_i], \\ y_i^{\mathrm{no\ call}} &= \mathbf{1}[\neg A_i \land \hat r_i = r_i]. \end{aligned}

The Granite function-calling evaluation likewise reports separate syntactic and execution scores, using distinct benchmark tasks for those columns. Here, both scores come from the same tickets and we can trace which checks determined the outcome. IBM Research, paper-reported

A valid command can still choose the wrong next step

Receipts and read attempts by ticket type

3

Inspection date

Free generation
10 invalid proposal
0 read attempts

Token grammar
10 verified
10 read attempts

Free generation + no-call policy
10 invalid proposal
0 read attempts

Missing asset

Free generation
10 invalid proposal
0 read attempts

Token grammar
10 decision mismatch
0 read attempts

Free generation + no-call policy
10 clarify
0 read attempts

Guest request

Free generation
10 invalid proposal
0 read attempts

Token grammar
10 deny
0 read attempts

Free generation + no-call policy
10 deny
0 read attempts

Source: Lesson 07, SHA-256-verified Colab export. Model inference ran on a Tesla T4 and the inventory check ran on the host CPU.

Scope and request checks stop well-formed proposals

Deliberate controls, outside the model comparison

4
ControlProposed assetReceiptRead attempted
Requested fanF-211verifiedYes
Different same-yard assetP-201asset mismatchNo
Wrong yardF-211asset out of scopeNo
Clarify missing identifier—clarifyNo
Deny guest request—denyNo
Source: Lesson 07, SHA-256-verified Colab export. Model inference ran on a Tesla T4 and the inventory check ran on the host CPU.

Decide when the desk should abstain

On F-211, the grammar produced the right read. On an ambiguous request, it could produce a perfectly formed denial. The desk needed a follow-up question. The deterministic no-call policy substitutes a clarify or deny instruction only when the trusted request and role already settle that decision. It leaves the inspection candidate untouched, so a malformed lookup remains a failure.

F230-00 · What is the maximum temperature for that unit? · operator, north-yard

Expected receipt
Clarify without a read.
Free generation
```json { "decision": "lookup", "tool": "read_inspection", "asset": "unit" } ``` → invalid_proposal
Token grammar
{"decision":"deny","tool":"","asset":""} → decision_mismatch
Free generation + no-call policy
```json { "decision": "lookup", "tool": "read_inspection", "asset": "unit" } ``` → effective {"decision":"clarify","tool":"","asset":""} → clarify

The grammar emitted a valid denial. The signed-in operator needed a clarifying question, so the receipt marks a decision mismatch. The no-call policy used the trusted request and role to substitute clarify.

The no-call policy recovers missing-asset and guest tickets

Counts on matched free-generation outputs

5
Method / ticketCorrectChanged
Free generation · Missing asset0/100
Free generation · Guest request0/100
Free generation + no-call policy · Missing asset10/1010
Free generation + no-call policy · Guest request10/1010
Source: Lesson 07, SHA-256-verified Colab export. Model inference ran on a Tesla T4 and the inventory check ran on the host CPU.

The paired comparison subtracts the free decoder's score from the alternative's score on each ticket. Each family contributes several phrasings of the same task. The bootstrap draws whole families so those phrasings stay together.

Δ^c,b=1n∑i=1n(yi(c)−yi(b)).\widehat{\Delta}_{c,b} = \frac{1}{n}\sum_{i=1}^{n} \left(y_i^{(c)} - y_i^{(b)}\right).

Both alternatives gained 20 tickets and lost none against free generation. They differed on the ticket types where they helped. Grammar handled the ten inspection lookups and the ten guest denials. The no-call policy handled the ten clarifications and ten guest denials. There is no measured combined grammar-plus-policy arm.

The grammar decodes fewer tokens in less time

Medians over five matched warm batches per decoder

6
DecoderBatch timePrompt tokensDecoded tokens
Free generation1.64 s11729
Token grammar0.81 s11710

Model load 26.47 s · Trie build 6.20 ms. The policy reuses free responses.

Source: Lesson 07, SHA-256-verified Colab export. Model inference ran on a Tesla T4 and the inventory check ran on the host CPU.

What to keep

MethodVerifiedUse the result to decide
Free generation0/30Keep it as a control for testing parser and formatting changes.
Token grammar20/30Use it when the vocabulary is finite and output must fit a typed interface. Keep the receipt check.
Free generation + no-call policy20/30Apply the policy when trusted inputs already determine that the desk should clarify or deny.
  • Check scope and the requested asset independently of the schema.
  • Grade both the proposed command and the tool receipt, including why a read did not run.
  • Record the original and effective commands when a policy overrides the model.

Next to try, not tested here

  • Combine grammar and no-call policy and compare the two cohorts each change recovered.
  • Expand the inventory catalogue and measure how trie construction changes.
  • Compare exact parsing with a parser that accepts a complete fenced JSON payload.

How it was built

SettingValue
Development cohort30 tickets from six families, variants below 5 on inspection, ambiguity and boundary slices
Development SHA-25651dbc208b6b20a620237dd76ce0a2db4f10aa75f4f8fc404121e301b8d79a0cf
Model revision989aa7980e4cf806f80c7fef2b1adb7bc71aa306
DecodingTemperature 0, up to 64 output tokens, 14 permitted commands in the grammar
InventoryIn-memory SQLite, query-only, parameter-bound read, trusted role and yard
ScoringExact returned asset, inspection date and evidence ID, or correct no-call action with zero read attempts
Bootstrap1,500 paired draws over six equipment families
RuntimeTesla T4 and host CPU, Python 3.13.16, CUDA 13.0, PyTorch 2.14.1+cu130, Transformers 4.51.3

Time and cost. The notebook took 62.8 s end to end. Model load took 26.47 s and trie construction took 6.20 ms. Batch timings include rendering, tokenisation, generation and decoding. They exclude warm-up, prompt pre-counting, re-tokenising the decoded text and the inventory receipt checks. The policy arm reused free-generation output.

Executed notebook · Summary · Case and batch records · Runtime

Run it yourself

Use the Colab button or download the executed notebook. Make a prediction before each change, then inspect the saved fields.

  1. In Test the request and the proposed asset independently, keep the F-211 question and substitute P-201. Predict whether the call reaches SQLite, then read opening[].receipt.
  2. In Grade the proposal and the receipt, compare free generation with the no-call policy on F230-00. Predict which fields can change when both policies see the same raw reply. Inspect proposal, effective and receipt in the two records.
  3. In Compare free generation with a finite token grammar, lower OUTPUT_TOKEN_BUDGET alone. Predict whether the longest permitted command still fits. Inspect the command coverage assertion, then compare summary.comparisons at the smallest admitted budget.

Next, bound a model-led workflow and decide what the desk should do after a read times out.

How is this page?

Last updated on