Route a request to a tool by keyword score

EasyAgents

Why it matters Production agents often use a fast router before the LLM to cut latency on common intents.

A cheap router picks a tool before calling the big model.

Write route_tool(query, tools). tools is a dict {name: list of keywords}. Lowercase the query and split on whitespace. Score each tool by how many of its keywords appear as words in the query. Return the best tool name (ties broken by name alphabetically), or None if every score is 0.

Signaturedef route_tool(query, tools)

Example

route_tool("what is the weather today", {"weather": ["weather", "rain"], "calendar": ["today", "meeting"]}) ties at 1 and returns "calendar".

Understand the idea

Before calling an expensive model, a cheap keyword router can guess which tool a request needs. Each tool lists keywords; the router counts how many of a tool's keywords appear as whole words in the query and picks the tool with the highest count. Worked example: query 'Book a MEETING about the rain delay', tools {'calendar': ['meeting', 'book', 'today'], 'weather': ['rain', 'forecast']}. Lowercased words are book, a, meeting, about, the, rain, delay. calendar scores 2 (meeting, book) and weather scores 1 (rain), so return 'calendar'. If both scored the same, the alphabetically first name wins. If no tool scores above 0, return None. Rule: words = set of query.lower().split(); score(tool) = number of its keywords in words; best = highest score, tie broken by name; None if the best score is 0. Whole-word matching stops 'rain' from matching inside 'train'. Lowercasing makes 'RAIN' match. Lowercase keywords too if they might contain capitals. Used in: lightweight intent routing in chatbots and agents before an LLM call.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampleroute_tool('what is the weather today', {'weather': ['weather', 'rain'], 'calendar': ['today', 'meeting']})
  • Sample 2: clear winnerroute_tool('Will it RAIN or snow', {'weather': ['rain', 'snow'], 'search': ['find']})
  • Test 3: noneroute_tool('hello there', {'weather': ['rain']})
  • Test 4: uppercase queryroute_tool('RAIN expected', {'weather': ['rain'], 'search': ['find']})