Deduplicate repeated tool calls with a canonical cache key
Why it matters Agent runtimes cache idempotent tool calls such as searches and file reads to cut latency and API cost.
Agents often repeat the same tool call, sometimes with arguments in a different order. Caching by a canonical key saves money and time.
Write dedupe_calls(calls). calls is a list of (name, args) where args is a JSON-serialisable dict. The cache key is name + "|" + json.dumps(args, sort_keys=True, separators=(",", ":")). Walk the calls in order: the first time a key is seen the call is executed; later calls with the same key are cache hits. Return (number of executed calls, list of indices of the cache hits).
def dedupe_calls(calls)Example
dedupe_calls([("search", {"q": "a", "k": 2}), ("search", {"k": 2, "q": "a"}), ("calc", {"x": 1})]) gives (2, [1]).
Understand the idea
Large language models repeat themselves: an agent may search for the same thing twice in one task, often writing the arguments in a different order. If a tool is idempotent (same input, same output), we can reuse the first answer. The trick is a canonical key: a string that is identical whenever two calls mean the same thing.
Example: search with {"q": "a", "k": 2} and search with {"k": 2, "q": "a"} are the same call. Serialising with sorted keys gives the same string for both, so the second is a cache hit and only 2 of the 3 calls run.
Rule: key = name + "|" + json.dumps(args, sort_keys=True, compact separators); execute if new, else return the cached result.
Only cache read-only tools; caching a "send email" call would silently drop real actions.