StackPractices
advanced By Mathias Paulenko

Agent Tool Selection Pattern: Fewer Tools, Better Calls

Dynamically select which tools an LLM agent can use based on the task context. Reduce token usage and improve decision quality by narrowing the tool set.

Topics: ai

Overview

Give an LLM agent twenty tools and it picks the wrong one; give it three and it nails it. That’s not a model quirk — every tool definition burns prompt tokens and every extra option dilutes the model’s attention on the ones that matter.

The Agent Tool Selection pattern narrows the set before each step: a selector decides which tools the current task actually needs, and only those definitions reach the prompt. The agent sees five tools instead of thirty — fewer tokens, better choices, lower latency.

How the Selector Decides

Three strategies cover most production systems:

  • Phase-based: the workflow dictates the subset — research phase gets search+scrape, execution gets API calls, review gets file ops. Deterministic, cheapest, and the right default.
  • Embedding similarity: embed the current task and each tool’s description; keep the top-k matches. Handles open-ended tasks where phases don’t fit — and it’s where an embedding cache pays for itself, since the tool descriptions embed once.
  • LLM router: ask a small model “which of these tools does this step need?” — the LLM Router pattern applied to tools instead of models. Costs one call but handles ambiguity better than similarity scores.
A selector takes the current task plus the full set of 30 tools, keeps only the top-k, and the LLM prompt ends up with just 5 tool definitions.

When the Selector Itself Fails

The pattern’s failure mode is a bad selection: if the selector drops the right tool, the agent can’t recover — it doesn’t know the tool exists. Three defenses: keep the selector permissive (top-k=8 beats top-k=3), log every selection for audit, and add a fallback “request more tools” escape for cases where the agent knows it’s stuck.

And the selector costs something too — an LLM router call or a similarity search per step. For agents with few tools, that cost exceeds the savings; the pattern only pays when the tool count is high enough to matter.

When to Use

Use the Agent Tool Selection Pattern when:

  • Your agent has access to more than 8-10 tools and token costs are significant
  • Different phases of a task require different tool subsets (e.g., research phase vs. execution phase)
  • The agent frequently picks wrong tools because too many options confuse it
  • You want to enforce task workflows by restricting tools per phase
  • Examples: coding agents with file/search/terminal/deploy tools, research agents juggling several search APIs, customer support agents with department-specific tools

Skip it when the agent already picks correctly from a small set — a selector in front of five tools is overhead with nothing to save.

Solution

Python

from dataclasses import dataclass, field
from typing import Callable, Dict, List, Optional, Any
import re

@dataclass
class Tool:
    name: str
    description: str
    category: str
    parameters: Dict[str, str] = field(default_factory=dict)

@dataclass
class AgentState:
    task: str
    phase: str = "planning"
    history: List[str] = field(default_factory=list)
    available_tools: List[str] = field(default_factory=list)

# Tool registry
TOOL_REGISTRY: Dict[str, Tool] = {
    "web_search": Tool(
        "web_search", "Search the web for information", "research",
        {"query": "string", "max_results": "int"}
    ),
    "code_search": Tool(
        "code_search", "Search the codebase for patterns", "research",
        {"pattern": "string", "language": "string"}
    ),
    "read_file": Tool(
        "read_file", "Read file contents", "file_ops",
        {"path": "string"}
    ),
    "write_file": Tool(
        "write_file", "Write content to a file", "file_ops",
        {"path": "string", "content": "string"}
    ),
    "run_tests": Tool(
        "run_tests", "Execute test suite", "execution",
        {"test_file": "string", "filter": "string"}
    ),
    "deploy": Tool(
        "deploy", "Deploy application to environment", "execution",
        {"environment": "string", "version": "string"}
    ),
    "calculator": Tool(
        "calculator", "Perform mathematical calculations", "utility",
        {"expression": "string"}
    ),
    "sql_query": Tool(
        "sql_query", "Execute SQL query on database", "data",
        {"query": "string", "database": "string"}
    ),
}

# Phase-based tool mapping
PHASE_TOOLS: Dict[str, List[str]] = {
    "planning": ["web_search", "code_search", "calculator"],
    "implementation": ["read_file", "write_file", "code_search"],
    "testing": ["read_file", "run_tests", "code_search"],
    "deployment": ["run_tests", "deploy", "read_file"],
    "analysis": ["sql_query", "calculator", "web_search"],
}

def select_tools_by_phase(state: AgentState) -> List[Tool]:
    """Select tools based on the current agent phase."""
    tool_names = PHASE_TOOLS.get(state.phase, [])
    return [TOOL_REGISTRY[name] for name in tool_names if name in TOOL_REGISTRY]

def select_tools_by_keywords(state: AgentState) -> List[Tool]:
    """Select tools based on keyword matching in the task."""
    text = (state.task + " " + " ".join(state.history)).lower()

    keyword_map = {
        "search|find|look up|research": ["web_search", "code_search"],
        "read|open|view|inspect": ["read_file"],
        "write|create|modify|update|edit": ["write_file", "read_file"],
        "test|spec|assert|validate": ["run_tests", "read_file"],
        "deploy|release|publish|ship": ["deploy", "run_tests"],
        "calculate|compute|math|sum|average": ["calculator"],
        "query|database|sql|select|join": ["sql_query"],
    }

    selected: set = set()
    for pattern, tools in keyword_map.items():
        if re.search(pattern, text):
            selected.update(tools)

    if not selected:
        selected.update(PHASE_TOOLS.get(state.phase, ["web_search"]))

    return [TOOL_REGISTRY[name] for name in selected if name in TOOL_REGISTRY]

class ToolSelector:
    def __init__(self, strategy: str = "phase"):
        self.strategy = strategy

    def select(self, state: AgentState) -> List[Tool]:
        if self.strategy == "phase":
            return select_tools_by_phase(state)
        elif self.strategy == "keyword":
            return select_tools_by_keywords(state)
        else:
            return list(TOOL_REGISTRY.values())

    def format_tools_for_prompt(self, tools: List[Tool]) -> str:
        """Format tool definitions for inclusion in LLM prompt."""
        lines = []
        for tool in tools:
            params = ", ".join(f"{k}: {v}" for k, v in tool.parameters.items())
            lines.append(f"- {tool.name}({params}): {tool.description}")
        return "\n".join(lines)

# Usage
state = AgentState(
    task="Find all Python files with SQL injection vulnerabilities and fix them",
    phase="implementation",
    history=["Found 3 files with raw SQL queries"],
)

selector = ToolSelector(strategy="keyword")
tools = selector.select(state)

print(f"Selected {len(tools)} tools:")
for t in tools:
    print(f"  {t.name}: {t.description}")

print("\nFormatted for prompt:")
print(selector.format_tools_for_prompt(tools))

JavaScript

class Tool {
  constructor(name, description, category, parameters = {}) {
    this.name = name;
    this.description = description;
    this.category = category;
    this.parameters = parameters;
  }
}

const TOOL_REGISTRY = {
  web_search: new Tool("web_search", "Search the web", "research", { query: "string", maxResults: "int" }),
  code_search: new Tool("code_search", "Search codebase", "research", { pattern: "string", language: "string" }),
  read_file: new Tool("read_file", "Read file contents", "file_ops", { path: "string" }),
  write_file: new Tool("write_file", "Write to file", "file_ops", { path: "string", content: "string" }),
  run_tests: new Tool("run_tests", "Execute tests", "execution", { testFile: "string", filter: "string" }),
  deploy: new Tool("deploy", "Deploy app", "execution", { environment: "string", version: "string" }),
  calculator: new Tool("calculator", "Math calculations", "utility", { expression: "string" }),
  sql_query: new Tool("sql_query", "Execute SQL", "data", { query: "string", database: "string" }),
};

const PHASE_TOOLS = {
  planning: ["web_search", "code_search", "calculator"],
  implementation: ["read_file", "write_file", "code_search"],
  testing: ["read_file", "run_tests", "code_search"],
  deployment: ["run_tests", "deploy", "read_file"],
  analysis: ["sql_query", "calculator", "web_search"],
};

function selectToolsByPhase(state) {
  const names = PHASE_TOOLS[state.phase] || [];
  return names.map(n => TOOL_REGISTRY[n]).filter(Boolean);
}

function selectToolsByKeywords(state) {
  const text = (state.task + " " + state.history.join(" ")).toLowerCase();

  const keywordMap = {
    "search|find|look up|research": ["web_search", "code_search"],
    "read|open|view|inspect": ["read_file"],
    "write|create|modify|update|edit": ["write_file", "read_file"],
    "test|spec|assert|validate": ["run_tests", "read_file"],
    "deploy|release|publish|ship": ["deploy", "run_tests"],
    "calculate|compute|math|sum|average": ["calculator"],
    "query|database|sql|select|join": ["sql_query"],
  };

  const selected = new Set();
  for (const [pattern, tools] of Object.entries(keywordMap)) {
    if (new RegExp(pattern).test(text)) {
      tools.forEach(t => selected.add(t));
    }
  }

  if (selected.size === 0) {
    (PHASE_TOOLS[state.phase] || ["web_search"]).forEach(t => selected.add(t));
  }

  return [...selected].map(n => TOOL_REGISTRY[n]).filter(Boolean);
}

class ToolSelector {
  constructor(strategy = "phase") {
    this.strategy = strategy;
  }

  select(state) {
    if (this.strategy === "phase") return selectToolsByPhase(state);
    if (this.strategy === "keyword") return selectToolsByKeywords(state);
    return Object.values(TOOL_REGISTRY);
  }

  formatToolsForPrompt(tools) {
    return tools
      .map(t => {
        const params = Object.entries(t.parameters)
          .map(([k, v]) => `${k}: ${v}`)
          .join(", ");
        return `- ${t.name}(${params}): ${t.description}`;
      })
      .join("\n");
  }
}

// Usage
const state = {
  task: "Find all Python files with SQL injection vulnerabilities and fix them",
  phase: "implementation",
  history: ["Found 3 files with raw SQL queries"],
};

const selector = new ToolSelector("keyword");
const tools = selector.select(state);

console.log(`Selected ${tools.length} tools:`);
tools.forEach(t => console.log(`  ${t.name}: ${t.description}`));

console.log("\nFormatted for prompt:");
console.log(selector.formatToolsForPrompt(tools));

Java

import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class AgentToolSelection {

    record Tool(String name, String description, String category, Map<String, String> parameters) {}

    static final Map<String, Tool> TOOL_REGISTRY = Map.of(
        "web_search", new Tool("web_search", "Search the web", "research", Map.of("query", "string")),
        "code_search", new Tool("code_search", "Search codebase", "research", Map.of("pattern", "string")),
        "read_file", new Tool("read_file", "Read file", "file_ops", Map.of("path", "string")),
        "write_file", new Tool("write_file", "Write file", "file_ops", Map.of("path", "string", "content", "string")),
        "run_tests", new Tool("run_tests", "Execute tests", "execution", Map.of("testFile", "string")),
        "deploy", new Tool("deploy", "Deploy app", "execution", Map.of("environment", "string")),
        "calculator", new Tool("calculator", "Math calculations", "utility", Map.of("expression", "string")),
        "sql_query", new Tool("sql_query", "Execute SQL", "data", Map.of("query", "string"))
    );

    static final Map<String, List<String>> PHASE_TOOLS = Map.of(
        "planning", List.of("web_search", "code_search", "calculator"),
        "implementation", List.of("read_file", "write_file", "code_search"),
        "testing", List.of("read_file", "run_tests", "code_search"),
        "deployment", List.of("run_tests", "deploy", "read_file"),
        "analysis", List.of("sql_query", "calculator", "web_search")
    );

    record AgentState(String task, String phase, List<String> history) {}

    static List<Tool> selectToolsByPhase(AgentState state) {
        return PHASE_TOOLS.getOrDefault(state.phase(), List.of())
            .stream()
            .map(TOOL_REGISTRY::get)
            .filter(Objects::nonNull)
            .toList();
    }

    static List<Tool> selectToolsByKeywords(AgentState state) {
        String text = (state.task() + " " + String.join(" ", state.history())).toLowerCase();
        Map<String, List<String>> keywordMap = Map.of(
            "search|find|look up|research", List.of("web_search", "code_search"),
            "read|open|view|inspect", List.of("read_file"),
            "write|create|modify|update|edit", List.of("write_file", "read_file"),
            "test|spec|assert|validate", List.of("run_tests", "read_file"),
            "deploy|release|publish|ship", List.of("deploy", "run_tests"),
            "calculate|compute|math|sum|average", List.of("calculator"),
            "query|database|sql|select|join", List.of("sql_query")
        );

        Set<String> selected = new LinkedHashSet<>();
        for (var entry : keywordMap.entrySet()) {
            if (Pattern.compile(entry.getKey()).matcher(text).find()) {
                selected.addAll(entry.getValue());
            }
        }

        if (selected.isEmpty()) {
            selected.addAll(PHASE_TOOLS.getOrDefault(state.phase(), List.of("web_search")));
        }

        return selected.stream()
            .map(TOOL_REGISTRY::get)
            .filter(Objects::nonNull)
            .toList();
    }

    static String formatToolsForPrompt(List<Tool> tools) {
        return tools.stream()
            .map(t -> {
                String params = t.parameters().entrySet().stream()
                    .map(e -> e.getKey() + ": " + e.getValue())
                    .collect(Collectors.joining(", "));
                return "- " + t.name() + "(" + params + "): " + t.description();
            })
            .collect(Collectors.joining("\n"));
    }

    public static void main(String[] args) {
        var state = new AgentState(
            "Find all Python files with SQL injection vulnerabilities and fix them",
            "implementation",
            List.of("Found 3 files with raw SQL queries")
        );

        var tools = selectToolsByKeywords(state);
        System.out.println("Selected " + tools.size() + " tools:");
        tools.forEach(t -> System.out.println("  " + t.name() + ": " + t.description()));
        System.out.println("\nFormatted for prompt:");
        System.out.println(formatToolsForPrompt(tools));
    }
}

Explanation

The pattern works in three stages:

  1. State assessment: The agent keeps a state object that tracks the current phase (planning, implementation, testing, deployment) and conversation history. This state drives tool selection.
  2. Tool filtering: A selector function narrows the full tool registry to a relevant subset. Two common strategies: phase-based (static mapping from phase to tools) and keyword-based (regex matching on task + history text). More advanced approaches use embedding similarity or a small classifier.
  3. Prompt construction: Only the selected tool definitions are included in the LLM prompt. This reduces token count and helps the model focus on relevant options.

The key insight is that tool definitions consume tokens. A tool with 5 parameters and a description can use 50-100 tokens. With 20 tools, that’s 1000-2000 tokens per request. Narrowing to 4 relevant tools saves 75% of that budget.

Picking a Strategy

SelectorCost per stepBest whenWatch out for
Phase-based~0Structured workflowsBrittle when phases blur
Embedding top-kCheap (embed once)Open-ended tasksSimilar descriptions confuse it
LLM router1 small callAmbiguous, long tasksAdds latency, can hallucinate

Start phase-based; graduate to embeddings when the workflow stops being predictable. LLM routers are the escape hatch, not the default — every selection is a judgment call you’re paying a call for.

A hybrid that works well in production: phase-based as the base set, embedding similarity to re-rank within it, and the LLM router only when the first two disagree. Each stage stays cheap because the previous one already narrowed the field — the router call fires on maybe one step in ten.

Function Calling vs. Tool Selection

Worth separating: function calling is the API mechanic (the model emits a structured call); tool selection is the decision of which calls it can make. They’re complementary — the model can’t call what it wasn’t offered. MCP servers, plugin systems, and agent frameworks all sit on the same underlying question this pattern answers: what’s the minimum sufficient toolset for this step?

Implementation Notes

The boring details are where this pattern lives or dies. Log every selection — when the agent picks the wrong tool, the first question is “did the model choose badly or did the selector never offer it?” and without selection logs you can’t answer it. Keep tool descriptions tight: the selector’s embedding or router sees what the model sees, so a vague “utility function” description poisons both stages.

Version the selector itself like any model — an embedding index update or a prompt change to the router shifts which tools reach the prompt, and silent shifts are regressions nobody can bisect. And test the boundary cases: an agent that needs a tool the selector doesn’t offer should fail loudly (“no relevant tool”) not silently (hallucinate a wrong one).

What the Threshold Actually Is

The “more than 8-10 tools” rule of thumb isn’t magic — it’s the point where tool definitions start crowding out the actual task in the context window and choice accuracy measurably drops. Five well-described tools the model understands beat thirty it skims. If your agent uses eight tools and picks right, you don’t have the problem this pattern solves; if it uses twenty and misses, you do.

Combining with RAG and Caching

Tool selection composes naturally with the patterns around it: descriptions embedded once and served from an embedding cache cut the similarity-search cost per step, and the tool-call results themselves can flow into a RAG index the agent queries later. The selector is also a natural place for policy — ‘only read-only tools for untrusted inputs’ is a filter the selector applies before the model ever sees the list.

What all of these share: the selector is the policy surface of the agent. Every rule about what the agent may do — for this task, this user, this phase — compresses into which tools reach the prompt. Treat it as a security and quality boundary, not just a token optimization, and the pattern earns every bit of its complexity. That framing is also what makes it worth the engineering time: you’re not trimming a prompt, you’re defining what the agent is allowed to be.

Variants

VariantDescriptionUse Case
Embedding-based selectionEmbed task text, compare to tool description embeddingsSemantic matching, handles paraphrased tasks
Classifier-based selectionTrain a small model to predict tool relevanceHighest accuracy, requires labeled data
Hierarchical selectionFirst select a tool category, then tools within itVery large tool sets (50+ tools)
State machine selectionEach state in the agent graph has a fixed tool setLangGraph-style agents with explicit states

What Works

  • Start with phase-based selection — it’s simple, predictable, and covers most workflows
  • Combine phase + keyword — use phase as the base set, then add or remove based on keywords
  • Log tool selection decisions — track which tools were selected and whether the agent used them
  • Include a fallback tool — always provide a “search” or “ask_user” tool so the agent can escalate
  • Update tool sets per iteration — re-select tools after each agent step, not just at the start
  • Limit to 5-7 tools per step — more than that and the model’s selection accuracy drops

Common Mistakes

  • Passing all tools every time, negating the token savings and confusing the model
  • Not updating the tool set as the task progresses through phases
  • Selecting tools based only on the latest message, ignoring conversation history
  • Forgetting to include a read/search tool in every phase, leaving the agent unable to gather information
  • Making the selector too aggressive, removing tools the agent actually needs

Further Reading

Frequently Asked Questions

How many tools should I limit to per step?

Selection accuracy drops once the model has to pick from more than about ten options — in practice, 4-6 relevant tools per step is the working ceiling. If you need more, use hierarchical selection instead of a bigger flat list.

Should I use embeddings or rules for tool selection?

Start with rules (phase-based or keyword-based). They're free, fast, and debuggable. Move to embeddings if your tool descriptions are complex or users phrase tasks in varied ways.

What if the agent needs a tool that wasn't selected?

Include a fallback mechanism. The agent can request additional tools, or you can detect when the agent tries to call an unavailable tool and re-select with broader criteria.

Does this pattern work with function calling APIs?

Yes. OpenAI and Anthropic function calling APIs accept a list of tool definitions. Simply pass the filtered list instead of all tools. The API handles the rest.