Sub topic 5
Dispatching and Running the Call in Your Code
This chapter assumes you can read Python, know what a JSON object is, and have seen the shape of a tool call: the model returns an id, a tool name, and arguments. Here you build the part that sits between that request and the result you send back. That part is the dispatcher.
The model proposes, your code decides
The model never runs anything. It produces text in a structured format that says "I would like to call get_weather with {"city": "Oslo"}". Your program receives that text and chooses what to do with it. It may run the function, refuse, or ask the model to try again.
This separation is the main safety property of tool calling. Everything the model sends is untrusted input, in the same way a web form submission is. The name might not exist, the arguments might be malformed, and the values might be valid but unwise. The dispatcher is where you enforce your rules.
A dispatcher has four jobs:
- Find the function for the requested name, using an allow-list.
- Get the arguments into a Python dictionary.
- Call the function with them.
- Convert the outcome, success or failure, into content for a tool message.
Every branch ends in a result. The dispatcher never leaves a call unanswered, because most providers reject a conversation where a tool call has no matching result.
A minimal dispatcher
This version looks up the tool in a dictionary, calls it, and turns problems into error text.
import json
def get_weather(city, unit="celsius"):
return {"city": city, "temperature": 7, "unit": unit}
TOOLS = {"get_weather": get_weather}
def run_tool_call(call):
fn = TOOLS.get(call["name"])
if fn is None:
return {"is_error": True, "content": "Unknown tool: " + str(call["name"])}
try:
result = fn(**call["arguments"])
except TypeError as exc:
return {"is_error": True, "content": "Bad arguments: " + str(exc)}
except Exception as exc:
return {"is_error": True, "content": "Tool failed: " + str(exc)}
return {"is_error": False, "content": json.dumps(result)}Why a dictionary and not `getattr` or `eval`
TOOLS is an allow-list. Only functions you registered can be reached. If you instead wrote globals()[call["name"]] or getattr(module, name), the model could name any function in scope, including ones never meant to be exposed, such as os.system or a helper that deletes records. An explicit dictionary makes the exposed surface visible in one place.
Why `**call["arguments"]`
Unpacking the dictionary as keyword arguments maps each JSON key to a parameter name. Missing optional arguments fall back to the function's defaults, so {"city": "Oslo"} works even though unit has a default. A missing required argument or an unexpected key raises TypeError, which the dispatcher reports.
Arguments are not always a dictionary
The examples in this tutorial show arguments as a parsed object. Some provider APIs instead return arguments as a string containing JSON, and that string can be invalid, for example when the output was cut off by a token limit. Your adapter code should normalize this before dispatch.
import inspect
import json
def parse_arguments(raw):
if isinstance(raw, dict):
return raw
if isinstance(raw, str):
try:
parsed = json.loads(raw or "{}")
except json.JSONDecodeError as exc:
raise ValueError("Arguments are not valid JSON: " + str(exc))
if not isinstance(parsed, dict):
raise ValueError("Arguments must be a JSON object")
return parsed
raise ValueError("Arguments must be an object or a JSON string")
def get_weather(city, unit="celsius"):
return {"city": city, "temperature": 7, "unit": unit}
TOOLS = {"get_weather": get_weather}
def run_tool_call(call):
name = call.get("name")
fn = TOOLS.get(name)
if fn is None:
return {"is_error": True, "content": "Unknown tool: " + str(name)}
try:
args = parse_arguments(call.get("arguments", {}))
inspect.signature(fn).bind(**args)
except (ValueError, TypeError) as exc:
return {"is_error": True, "content": "Bad arguments: " + str(exc)}
try:
result = fn(**args)
except Exception as exc:
return {"is_error": True, "content": "Tool failed: " + str(exc)}
try:
return {"is_error": False, "content": json.dumps(result)}
except TypeError as exc:
return {"is_error": True, "content": "Result is not JSON serializable: " + str(exc)}
if __name__ == "__main__":
print(run_tool_call({"id": "call_1", "name": "get_weather", "arguments": '{"city": "Oslo"}'}))
print(run_tool_call({"id": "call_2", "name": "get_weather", "arguments": {"town": "Oslo"}}))
print(run_tool_call({"id": "call_3", "name": "delete_all", "arguments": {}}))Running it prints a success result for the first call and error results for the other two.
The change from the minimal version is inspect.signature(fn).bind(**args). It checks that the arguments fit the function's signature without running the function. This matters because of a gotcha in the minimal version: a TypeError raised deep inside a tool, such as None + 1, would be reported as "Bad arguments", which misleads the model into changing arguments that were fine. Binding first separates "the call did not fit the signature" from "the tool crashed". It checks names and counts only. Checking types and value ranges is the job of schema validation, covered in a later chapter.
Tagging the result with the call id
Each tool message carries the tool_call_id of the request it answers. The id is how the model matches results to calls, which matters most when several calls arrive in one turn. Copy the id from the request exactly. Do not generate your own.
{"role": "tool", "tool_call_id": "call_1", "content": "{\"temperature\": 7, \"unit\": \"celsius\"}"}The content is a string. If your function returns a dictionary, serialize it, as json.dumps does above. How to word and structure results is the subject of the next chapter.
Running tools safely
The dispatcher is also the place to apply operational limits.
- Timeouts. A hung HTTP call blocks the whole conversation. Give network calls their own timeout. If you wrap a tool in a thread pool with a deadline, remember that Python cannot kill a running thread. The call is abandoned but may keep running.
- Side effects. A tool that sends an email or charges a card should not run twice by accident. If a tool is not idempotent, which means repeating it changes the outcome again, consider an idempotency key or a confirmation step for it.
- Result size. A tool that returns a 2 MB log fills the context window. Truncate or summarize in the tool and say so in the text, for example "first 50 of 1,203 rows".
- Logging. Record the call id, tool name, arguments, duration, and outcome. When a conversation goes wrong, this log is how you tell whether the model chose badly or the tool misbehaved. Redact secrets before logging.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Looking up tools with `getattr` or `eval` | The model can reach unintended functions | Use an explicit dictionary |
| Letting an exception escape the dispatcher | The program crashes and the call gets no result | Catch exceptions and return error text |
| Catching only `TypeError` for argument problems | Bugs inside the tool are mislabeled as bad arguments | Bind to the signature before calling |
| Returning a Python object instead of a string | Provider rejects the message or shows `repr` text | Serialize with `json.dumps` |
| Skipping a call that failed to parse | Provider rejects the conversation: call without result | Always return a result for every id |
| Reusing a tool's name for a different function | Old conversation history points at new behavior | Version names when behavior changes |
Exercise
A model calls get_weather with {"city": "Oslo"}, but your get_weather function raises TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' because of a bug inside it. In the minimal dispatcher at the start of this chapter, what does the model see, and why is that a problem? How does the second dispatcher avoid it?
Show answer
The minimal dispatcher catches every TypeError around the call and reports "Bad arguments: ...". The model is told its arguments were wrong when they were fine, so it may retry with different arguments and fail again. The second dispatcher calls inspect.signature(fn).bind(**args) first, so only real signature mismatches are reported as bad arguments. The internal TypeError then reaches the general except Exception branch and is reported as "Tool failed: ...".
Exercise
Why must the dispatcher return a result for an unknown tool name instead of raising an exception that stops the program?
Show answer
The conversation needs one tool message for every call id the model issued, and providers commonly reject a request that lacks one. Returning an error result such as "Unknown tool: delete_all" keeps the history valid and lets the model correct itself, for example by choosing a tool that exists. An uncaught exception ends the run with no recovery.