Skip to main content

Module coerce

Module coerce 

Source
Expand description

Deterministic local repair of a tool-call body the parsers rejected.

The cheapest rung of the escalation ladder, and the only one that costs no model call at all. When a model emits a tool call wrapped in a code fence, trailed by prose, or carrying a trailing comma, the payload is right and the packaging is wrong. Today that turn is thrown away and the raw bytes are shown to the person as text. Repairing the packaging is measured in microseconds and cannot cost a generation.

§Only ever additive

coerce_json_object returns Some only when its output parses. Every failure path returns None and the caller behaves exactly as it did before. A turn can therefore be rescued by this module but never made worse by it — the same fail-open rule the repair re-issue follows.

§The one repair deliberately not attempted

An unterminated string is never closed. Given {"name":"read_file","arguments":{"path":"/etc/ho the structurally obvious fix is to add "}}, which yields valid JSON and a tool call that reads the wrong file. Dispatching a plausible-but-wrong call is worse than dispatching none: the client executes it, and a truncated path or query is a side effect nobody asked for. Truncation mid-string means the model’s output was cut off, which is a real failure, and this module declines to paper over it.

Structural delimiters are different in kind. A missing } at the very end of an otherwise complete object cannot change the meaning of any value already present; it can only fail to terminate them.

Structs§

StringScan 🔒
Tracks whether the scan is inside a JSON string literal.

Constants§

MAX_NESTING 🔒
The most nesting a tool-call body may legitimately carry.

Functions§

close_delimiters 🔒
Append whatever closing delimiters the body is missing.
coerce_json_object 🔒
Try to make body parse as a JSON object, without changing what it says.
drop_trailing_commas 🔒
Drop commas that sit immediately before a closing delimiter.
parses_as_object 🔒
strip_packaging 🔒
Remove a surrounding code fence and any prose either side of the object.