Syllabus Lesson 169 of 239 · Building Agents (Tool-Use & ReAct)
Building Agents (Tool-Use & ReAct)

Intent -> Tool + Argument Extraction

Before the loop can act, it has to decide which tool to call and pull the arguments out of the request. That is the router, and it is the most error-prone part of a real agent: misroute the intent or fumble the arguments and every downstream step is wrong. A production system often uses the LLM for this, but a router you can read, test, and reason about is faster, cheaper, and deterministic - and you should always have one as a fallback.

You will build route(query) that maps a free-text request to a structured {"tool": ..., "args": {...}} decision. Three real tools plus a catch-all:

  • calculator - a request like "12 * 3" contains two numbers around an operator. Parse it into {"a": 12, "op": "*", "b": 3}.
  • weather - the word weather appears. Pull the city out of "... in <City>" into {"city": "Paris"}.
  • dictionary - phrasing like define X or meaning of X. Extract the term into {"term": "photosynthesis"}.
  • fallback - nothing matched, so route to the safe default with the original text in {"query": ...}.

Regular expressions do the heavy lifting. The calculator pattern captures a number, an operator, and another number:

import re
m = re.search(r"(-?\d+(?:\.\d+)?)\s*([+\-*/])\s*(-?\d+(?:\.\d+)?)", text)
if m:
    a, op, b = m.group(1), m.group(2), m.group(3)
    # turn "12" into 12 (an int) so the calculator gets real numbers

For the city, search for the word in followed by capitalized words; for the term, search after define / meaning of / definition of. Order matters: check the calculator pattern first, then weather, then dictionary, and fall through to the fallback if none match.

Keep numbers as plain int when they are whole (so 12, not 12.0) - the tests check the exact dict. In a full agent this routed decision feeds straight into the dispatcher from the structured-tools module. Press Run to route four different requests.

Your turn

Write route(query) that returns {"tool": ..., "args": {...}}. Recognise, in order: a calculator request ("12 * 3" -> {"a": 12, "op": "*", "b": 3}, whole numbers as ints), a weather request (extract the city after in), a dictionary request (extract the term after define/meaning of), and a fallback for anything else with the original text in {"query": ...}.

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output