The tool-calling loop
Watch a model pick tools, call them and read their results until it answers.
Explain it simply
You see three tool cards. Each card is a function schema, a short form that says what a tool does and what it needs. The model knows the tools only through these cards. The request is the first message of the context.
Three tool cards: get_weather, find_city and get_time, each with its arguments. The request: What is the temperature in Paris and in Tokyo, in C?
A schema names the tool and gives each argument its allowed values.
Show the code ▾Hide the code ▴ · Try it yourself · Python 3
import json, math, re
REQUEST = "What is the temperature in Paris and in Tokyo, in C?"
PARALLEL = True # many calls per model turn, or one
VALIDATE = True # check arguments against the schema first
MODEL_MS = 400
CITIES = ["Paris", "Tokyo", "Lima"]
TOOLS = [
{"name": "get_weather", "description": "Get the current temperature in a city, in C or F.", "ms": 300,
"parameters": {"type": "object", "required": ["city", "unit"], "additionalProperties": False,
"properties": {"city": {"type": "string", "enum": CITIES},
"unit": {"type": "string", "enum": ["C", "F"]}}}},
{"name": "find_city", "description": "Find the city a landmark is in.", "ms": 200,
"parameters": {"type": "object", "required": ["landmark"], "additionalProperties": False,
"properties": {"landmark": {"type": "string", "minLength": 1}}}},
{"name": "get_time", "description": "Get the local time in a city.", "ms": 150,
"parameters": {"type": "object", "required": ["city"], "additionalProperties": False,
"properties": {"city": {"type": "string", "enum": CITIES}}}},
]
TEMPS = {"Paris": 14, "Tokyo": 22, "Lima": 19}
LANDMARKS = {"Eiffel Tower": "Paris"}
STOP = {"what", "is", "the", "in", "and", "at", "a", "or", "of", "to", "it"}
def words(text):
for l in LANDMARKS:
text = text.replace(l, " LANDMARK ")
out = []
for w in re.findall(r"[A-Za-z]+", text):
if w in CITIES: out.append("city")
elif w == "LANDMARK": out.append("landmark")
elif w.lower() not in STOP: out.append(w.lower())
return out
# tool selection: request words against each description, weighted by idf
docs = [set(words(t["description"])) for t in TOOLS]
idf = {w: math.log(len(TOOLS) / sum(w in d for d in docs)) for d in docs for w in d}
q = set(words(REQUEST))
scores = {t["name"]: sum(idf[w] for w in q & d) for t, d in zip(TOOLS, docs)}
picked = sorted((n for n in scores if scores[n] > 0), key=lambda n: -scores[n])
def validate(tool, args): # a JSON Schema subset, errors worded like jsonschema
ps = tool["parameters"]
for k in ps["required"]:
if k not in args: return f"'{k}' is a required property"
for k, v in args.items():
s = ps["properties"].get(k)
if s is None: return f"Additional properties are not allowed ('{k}' was unexpected)"
if "enum" in s and v not in s["enum"]: return f"{k}: '{v}' is not one of {s['enum']}"
return None
def run_tool(name, a):
if name == "get_weather": # converts only F: any other unit passes as C
c = TEMPS[a["city"]]
return {"city": a["city"], "temp": round(c * 9 / 5 + 32, 1) if a["unit"] == "F" else c, "unit": a["unit"]}
if name == "find_city":
return {"landmark": a["landmark"], "city": LANDMARKS[a["landmark"]]}
return {"city": a["city"], "time": "12:00"}
asked = "K" if "kelvin" in q else "F" if "f" in q else "C"
context = [{"role": "user", "content": REQUEST}]
done, clock, turn = [], 0, 0
while True:
turn += 1
clock += MODEL_MS # the model reads the whole context
cities = [c for c in re.findall(r"[A-Za-z]+", REQUEST) if c in CITIES]
unit = asked
for m in context:
if m["role"] != "tool": continue
r = json.loads(m["content"])
if r.get("city") and r["city"] not in cities and "landmark" in r: cities.append(r["city"])
e = re.search(r"unit: '\w+' is not one of \['(\w+)'", r.get("error", ""))
if e: unit = e.group(1)
ready = []
for n in picked:
if n == "get_weather": ready += [(n, {"city": c, "unit": unit}) for c in cities]
elif n == "find_city": ready += [(n, {"landmark": l}) for l in LANDMARKS if l in REQUEST]
else: ready += [(n, {"city": c}) for c in cities]
ready = [x for x in ready if x not in done]
if not ready:
parts = []
for m in context:
r = json.loads(m["content"]) if m["role"] == "tool" else {}
if "landmark" in r: parts.append(f"The {r['landmark']} is in {r['city']}.")
elif "temp" in r and asked == "K" and r["unit"] == "C": parts.append(f"{r['city']} is {round(r['temp'] + 273.15, 2)} K.")
elif "temp" in r: parts.append(f"{r['city']} is {r['temp']} {r['unit']}.")
print(f"turn {turn}: answer: {' '.join(parts)}")
break
calls = ready if PARALLEL else ready[:1]
context.append({"role": "assistant", "tool_calls": calls})
longest = 0
for name, a in calls:
tool = next(t for t in TOOLS if t["name"] == name)
err = validate(tool, a) if VALIDATE else None
result = {"error": err} if err else run_tool(name, a)
if not err:
done.append((name, a))
longest = max(longest, tool["ms"])
context.append({"role": "tool", "content": json.dumps(result)}) # result injection
print(f"turn {turn}: {name}({json.dumps(a)}) -> {json.dumps(result)}")
clock += longest # calls of one turn run at the same time
print(f"{turn} model turns, {clock} ms")
# turn 1: get_weather({"city": "Paris", "unit": "C"}) -> {"city": "Paris", "temp": 14, "unit": "C"}
# turn 1: get_weather({"city": "Tokyo", "unit": "C"}) -> {"city": "Tokyo", "temp": 22, "unit": "C"}
# turn 2: answer: Paris is 14 C. Tokyo is 22 C.
# 2 model turns, 1100 ms
Copy it into a file and run it. Change REQUEST, PARALLEL and VALIDATE at the top.
Common mix-ups
MYTHA tool rejects a bad argument by itself.
FIXWith validation off, get_weather reads unit K as C and returns 19. The answer says 19 K, but Lima is 292.15 K.
MYTHParallel tool calls make every request faster.
FIXFor the landmark, get_weather needs the city that find_city returns. Each turn has one call, so both modes take 1,700 ms.
Takeaways
- The model picks tools only from what their schemas say.
- Validate each call before it runs, and inject results and errors back.
- Parallel calls save time only when no call needs another call's result.