Skip to content
All patterns
Architecture

Dynamic tool routing

Problem

Exposing dozens or hundreds of tools in every agent prompt causes prompt bloat, inflates input token costs, degrades model reasoning, and increases tool hallucinations or misrouted invocations (needle-in-a-haystack tool selection problem).

Pattern

Index all tool schemas in a semantic search registry. On each user turn, run a fast intent classification or semantic retrieval step to select the top-k relevant tools (e.g., 3-5 candidates) and inject only those schemas into the active LLM context window.

Implementation
tool_routing.py
import numpy as np
from openai import OpenAI

client = OpenAI()

class ToolRegistry:
    def __init__(self, tools: list[dict]):
        self.tools = {t["function"]["name"]: t for t in tools}
        self.descriptions = [
            f"{t['function']['name']}: {t['function'].get('description', '')}"
            for t in tools
        ]
        # Embed tool descriptions once during registry initialization
        res = client.embeddings.create(model="text-embedding-3-small", input=self.descriptions)
        self.embeddings = [np.array(e.embedding) for e in res.data]

    def select_tools(self, query: str, top_k: int = 4) -> list[dict]:
        q_res = client.embeddings.create(model="text-embedding-3-small", input=query)
        q_emb = np.array(q_res.data[0].embedding)

        scores = [
            float(np.dot(q_emb, t_emb) / (np.linalg.norm(q_emb) * np.linalg.norm(t_emb)))
            for t_emb in self.embeddings
        ]
        ranked_indices = np.argsort(scores)[::-1][:top_k]
        tool_names = list(self.tools.keys())
        return [self.tools[tool_names[i]] for i in ranked_indices]

# Core tools always present; specialized tools routed dynamically
ALWAYS_ON_TOOLS = ["search_knowledge_base", "ask_human_clarification"]

def run_agent_turn(registry: ToolRegistry, user_message: str) -> str:
    candidate_tools = registry.select_tools(user_message, top_k=3)
    active_tools = candidate_tools + [registry.tools[n] for n in ALWAYS_ON_TOOLS if n in registry.tools]

    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": user_message}],
        tools=active_tools,
    )
    return response.choices[0].message
Trade-offs
  • Reduces tool schema tokens by 80-95% when managing large tool ecosystems
  • Improves tool call accuracy by removing irrelevant distractors from model context
  • Adds 20-50ms latency for the embedding retrieval step prior to the primary LLM call
  • Risk of false-negative tool pruning if query phrasing does not match tool description
Production checklist
  • Design crisp, unambiguous tool descriptions with domain keywords
  • Maintain a set of core always-on tools (fallback, clarification, search)
  • Provide a meta-tool ('search_all_tools') so the agent can discover missing capabilities
  • Evaluate tool retrieval recall across a benchmark of standard user intents
  • Combine with prompt caching by ordering tool schemas consistently across requests