An AI tool argument string can contain the same JSON member twice. If decoding retains only the last value, a later field validator cannot discover that ambiguity. Reject duplicates during parsing, before converting the object into the dictionary your application uses.
This example defines an application-owned search argument contract: one query and one limit. It validates a synthetic argument string and exercises malformed fixtures without executing a search tool. The same boundary can sit between a provider’s tool-call response and your dispatch layer.
Prerequisites
Use Python 3.12 or later. No packages or provider credentials are required. Save the program as arguments.py. Pass the original JSON argument string to the function; a dictionary decoded earlier has already lost duplicate-member information.
Complete example
import json
def unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError("duplicate object member")
result[key] = value
return result
def reject_constant(value):
raise ValueError("nonstandard numeric constant")
def tool_arguments(raw):
if not isinstance(raw, str) or len(raw.encode("utf-8")) > 2048:
raise ValueError("argument text exceeds contract")
value = json.loads(raw, object_pairs_hook=unique_object, parse_constant=reject_constant)
if type(value) is not dict or set(value) != {"query", "limit"}:
raise ValueError("wrong argument fields")
if type(value["query"]) is not str or not 1 <= len(value["query"]) <= 100:
raise ValueError("bad query")
if type(value["limit"]) is not int or not 1 <= value["limit"] <= 5:
raise ValueError("bad limit")
return value
print(tool_arguments('{"query":"manual","limit":2}'))
bad = ['{"query":"a","query":"b","limit":2}',
'{"query":{"x":1,"x":2},"limit":2}',
'{"query":"a","limit":true}', '{"query":"a","limit":NaN}',
'{"query":"a","limit":2,"extra":0}', '[]', 'x' * 2049]
for raw in bad:
try:
tool_arguments(raw)
except (ValueError, RecursionError):
pass
else:
raise AssertionError("bad arguments accepted")
print(f"rejected={len(bad)}; no tool executed")
Run and expected output
python3 arguments.py
{'query': 'manual', 'limit': 2}
rejected=7; no tool executed
Why parsing order matters
The object-pairs hook receives members before a normal dictionary is built. It checks each name against those already encountered and refuses repeats. Nested JSON objects pass through the hook too, so the nested duplicate fixture fails at the parsing boundary even though that object would also violate the query field’s type.
After decoding, the exact field set rejects missing and unknown arguments. The integer check deliberately uses an exact type comparison: Python Boolean values otherwise satisfy many integer checks. The numeric-constant hook also rejects nonstandard NaN and infinity tokens accepted by Python’s default decoder behavior.
Limits and troubleshooting
The byte cap applies to an already available string. It does not bound the memory used while an HTTP client receives a response; enforce a separate transport limit before building that string. Query length uses Python string length, while the outer cap uses UTF-8 bytes. Those are different units and serve different purposes.
The helper does not authorize a tool name, decide whether a user may search a resource, or validate returned documents. Keep those checks in the dispatcher and data-access layer. Do not log rejected raw arguments by default: production arguments can contain sensitive text.
If a provider SDK returns only a decoded argument object, investigate whether it also exposes the original argument string. Duplicate detection cannot be reconstructed from the final dictionary. Malformed JSON raises a decoding error, which is a ValueError subclass; a deeply nested input may instead raise RecursionError. Treat either as invalid input and do not dispatch the tool.
These are fixture tests of a parser and application contract. They do not demonstrate provider compliance, tool execution or model accuracy.
References and related tutorials
See the official Python JSON documentation for decoder hooks and repeated-name behavior. Explore Python tutorials and AI tutorials.