Simple Tool Registry Lookup & Dispatch

Basics
BasicsTool CallingDispatchOpenAIAnthropicGoogle

Problem

Implement dispatch(registry, tool_name, args) that looks up tool_name in registry (dict[str, Callable]). If missing, return {"ok": False, "error": "unknown_tool"}. Otherwise invoke registry[tool_name](**args) and return {"ok": True, "result": value}.

Why It Matters: A safe registry dispatcher decouples LLM tool names from raw eval() and returns structured error envelopes when the model hallucinates a nonexistent tool.

Function Signature

def dispatch(registry: dict, tool_name: str, args: dict) -> dict:
    """Look up tool_name in registry and invoke it with **args."""

Sample Input & Output

Example 1: Successful Registered Tool Call

Input:

registry = {"add": lambda a, b: a + b}
dispatch(registry, "add", {"a": 4, "b": 7})

Expected Output:

{"ok": True, "result": 11}

Explanation: Finds 'add' in registry, unpacks **args, and wraps the return value in an ok: True envelope.

Example 2: Hallucinated Unknown Tool

Input:

registry = {"add": lambda a, b: a + b}
dispatch(registry, "drop_table", {})

Expected Output:

{"ok": False, "error": "unknown_tool"}

Explanation: Unregistered tool names never raise KeyError—they return a structured error dict.

Constraints & Edge Cases

  • Return a dict with 'ok' boolean.
  • Never execute functions outside registry.
  • Preserve the exact return keys ok, result, and error.

Constraints & Evaluation Criteria

  • Return a dict with `'ok'` boolean.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
add(a=2, b=3)
Expected Output / Criteria
{'ok': True, 'result': 5}