Sub topic 5
Dispatching and running the call in your code
This chapter assumes you know how a model returns a tool call: a name, an id, and an arguments object. It also assumes you can write basic Python.
The model proposes, your code runs
The model never runs anything. It returns text that says "call get_weather with city = Oslo". Your program must read that request, decide whether to run it, run it, and capture the output. This step is called dispatching.
Dispatching matters because the model's output is untrusted input. It can name a tool that does not exist, omit a required argument, or pass the wrong type. Your dispatcher is the boundary where you decide what actually executes.
Use an allow-list
The simplest safe design is a dictionary that maps tool names to functions. Only names in the dictionary can run. Never build a function name from model text with eval, getattr on a module, or a shell command.
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)}
call = {"id": "call_1", "name": "get_weather", "arguments": {"city": "Oslo"}}
print(run_tool_call(call))This prints {'is_error': False, 'content': '{"city": "Oslo", "temperature": 7, "unit": "celsius"}'}.
What each branch does
The function has four exits:
- Unknown name. The lookup returns
None, so nothing runs. The model gets text it can read. - Wrong arguments.
fn(**call["arguments"])raisesTypeErrorwhen a required argument is missing or an extra one is present. - Tool failure. Any other exception, such as a network timeout, becomes error text.
- Success. The result is serialized with
json.dumps, because tool results are sent back as strings.
The function returns a value in every case and never lets an exception escape. One bad call should not crash your whole loop.
Common mistakes
- Treating
TypeErroras always the model's fault. A bug inside your tool can also raiseTypeError, and the message would then claim "Bad arguments". Check the argument names before the call to tell the two cases apart. The validation chapter covers this. - Leaking internals.
str(exc)can include file paths or secrets. Return a short, safe message and log the full traceback yourself. - Running slow tools without a timeout. A hung tool hangs your loop. Set timeouts on network and subprocess calls.
- Returning Python objects. Convert results to a string, usually JSON, before they go back to the model.
Exercise
A model requests a tool named "deletefile", and your TOOLS dictionary does not contain it. What should runtool_call do, and why not look the name up some other way?
Show answer
It should return an error result such as "Unknown tool: delete_file" without running anything, so the model can read the message and try something else. Resolving names dynamically, for example with eval or getattr, would let model-generated text choose what code executes. The allow-list limits execution to functions you chose to expose.