Route a Tool Name with Fuzzy Matching
Problem Statement
Models sometimes hallucinate a slightly wrong tool name (get_wether instead of get_weather). Route the requested name to the closest registered tool if it is within an edit-distance threshold.
Background
Compute the Levenshtein edit distance (insertions, deletions, substitutions, cost 1 each) between the requested name and every registered tool. Pick the tool with the smallest distance; if that distance is <= max_dist, route to it, else return None. Ties are broken by the tool that sorts first alphabetically.
Your Task
Implement:
def route_tool(name, tools, max_dist):
- tools: list of registered tool-name strings.
- Return the chosen tool name, or None if none is within max_dist.
Input Format
- name (str), tools (list of str), max_dist (int).
Output Format
- A tool-name string or None.
Sample
print(route_tool("get_wether", ["get_weather", "send_email"], 2))
Output:
get_weather
Example
print(route_tool("get_wether", ["get_weather", "send_email"], 2))get_weather
- Sort the registered tools alphabetically to ensure deterministic tie-breaking:
["get_weather", "send_email"]. - Calculate the Levenshtein edit distance between the requested name
"get_wether"and the first tool"get_weather": the single substitution ofetoaat index 7 yields a distance of . - Calculate the edit distance between
"get_wether"and the second tool"send_email": due to significant character differences and length mismatch, the distance is . - Identify the tool with the minimum distance: since ,
"get_weather"is selected as the candidate with . - Verify the threshold condition: the minimum distance is less than or equal to
max_dist(), so the candidate is valid. - The final output is
get_weather
Constraints
- Standard Levenshtein distance (unit costs).
- Smallest distance wins; ties broken alphabetically.
- Return None if the best distance exceeds
max_dist.