Tool Selection in LLM Agents: Routing and Validation
Summary
Tool selection in LLM agents determines which functions to call for each request; proper routing and validation reduce errors and costs.
Why Tool Selection Is Needed
An LLM agent may have dozens of tools: search, DB, API, calculator. Passing all descriptions in every request increases token usage and reduces selection accuracy. The task is to select relevant tools before calling the model.
Approaches to Selection
1. Passing All Tools
Simple approach: include all tool schemas in the prompt. Suitable for 2–5 tools.
from openai import OpenAI
client = OpenAI()
tools = [
{"type": "function", "function": {"name": "search", "description": "Search in knowledge base", "parameters": {"type": "object", "properties": {"query": {"type": "string"}}}}},
{"type": "function", "function": {"name": "calculator", "description": "Arithmetic operations", "parameters": {"type": "object", "properties": {"expr": {"type": "string"}}}}}
]
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "What is 2+2?"}],
tools=tools
)
2. Semantic Routing
For a large number of tools, use a semantic router: the query embedding is compared to the embeddings of tool descriptions.
from sentence_transformers import SentenceTransformer
import numpy as np
model = SentenceTransformer('all-MiniLM-L6-v2')
tool_descriptions = {
"search": "Search information in knowledge base",
"calculator": "Perform mathematical operations",
"weather": "Get weather forecast"
}
def select_tools(query: str, top_k: int = 2) -> list[str]:
query_emb = model.encode(query)
tool_embs = {name: model.encode(desc) for name, desc in tool_descriptions.items()}
scores = {name: np.dot(query_emb, emb) for name, emb in tool_embs.items()}
sorted_tools = sorted(scores.items(), key=lambda x: x[1], reverse=True)
return [name for name, _ in sorted_tools[:top_k]]
3. Query Classification
Train a classifier (or use an LLM) to determine the type of task: search, calculation, generation. This gives a more accurate selection than embeddings.
from openai import OpenAI
client = OpenAI()
def classify_intent(query: str) -> str:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "Determine the task type: search, calculator, weather, other. Respond with one word."},
{"role": "user", "content": query}
],
max_tokens=10
)
return response.choices[0].message.content.strip()
4. Hybrid Approach
Combine methods: classification for coarse filtering, then embeddings for precise ranking.
Tool Schema
Each tool should have a JSON Schema with a clear description. Poor descriptions are the main cause of selection errors.
{
"name": "search_documents",
"description": "Search documents by keywords. Returns a list of IDs and titles.",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"},
"limit": {"type": "integer", "description": "Maximum results", "default": 5}
},
"required": ["query"]
}
}
Call Validation
After the model selects a tool, check the arguments before execution:
import jsonschema
def validate_tool_call(tool_name: str, arguments: dict, schemas: dict) -> bool:
schema = schemas.get(tool_name)
if not schema:
return False
try:
jsonschema.validate(arguments, schema)
return True
except jsonschema.ValidationError:
return False
For invalid arguments, return a model error and ask for correction:
messages.append({"role": "tool", "tool_call_id": call_id, "content": "Error: field 'query' is required"})
Error Handling
- Tool unavailable: return a message and suggest an alternative.
- Timeout: use retries with exponential delay.
- Incorrect selection: add examples of correct selection to the prompt.
Step-by-Step Implementation
Step 1. Inventory of Tools
Create a list of all functions with descriptions and schemas. Remove duplicates.
Step 2. Strategy Selection
| Number of Tools | Strategy |
|---|---|
| 1–5 | Pass all |
| 5–20 | Semantic routing |
| > 20 | Classification + routing |
Step 3. Implementation of Router
Create a module tool_router.py:
class ToolRouter:
def __init__(self, strategy: str, tools: dict):
self.strategy = strategy
self.tools = tools
def route(self, query: str) -> list[str]:
if self.strategy == "all":
return list(self.tools.keys())
elif self.strategy == "semantic":
return select_tools(query)
elif self.strategy == "classify":
intent = classify_intent(query)
return [intent] if intent in self.tools else []
Step 4. Integration with Agent
In the agent loop:
- Get the request.
- Call the router to select tools.
- Pass the selected schemas to the LLM.
- Validate the call.
- Execute the tool and return the result.
Step 5. Testing
Create a set of test queries and check:
- tool selection accuracy;
- percentage of invalid calls;
- average number of tokens per request.