Introduction
In our previous lessons, we've built a robust and secure foundation for tool execution, implementing everything from authentication and permission scoping to resource constraints. Our agent can now use tools powerfully and safely. However, as we expand our agent's capabilities, we'll equip it with dozens or even hundreds of tools. Presenting this entire inventory to the Large Language Model (LLM) for every single task is inefficient, costly, and can paradoxically degrade its performance by creating excessive "cognitive load."
This lesson tackles that exact challenge: dynamic tool selection. We will move beyond a static list of tools and implement a system where the agent can intelligently search a large inventory and select only the most relevant tools for the task at hand. Drawing on your background in distributed systems, you can think of this as analogous to a service discovery mechanism, where instead of hardcoding service endpoints, a client queries a registry to find the appropriate service at runtime. Here, our agent will query a "tool registry" to discover the right tools for the job.
We will design and implement a relevance assessment mechanism that allows an agent to sift through a vast tool library, ensuring it only considers a small, highly relevant subset, thereby improving efficiency, reducing costs, and boosting the reliability of its decisions.
Part 1: The Challenge of Large Tool Inventories
When an agent interacts with an LLM, the list of available tools, including their names, descriptions, and parameter schemas, must be included in the context of the prompt. For a handful of tools, this is manageable. But what happens when an agent has access to 50, 100, or even more tools?
The problem manifests in several ways:
- Context Window Limits & Cost: Every tool definition consumes valuable tokens in the context window. A large toolset can quickly exhaust the available space, leaving little room for the actual problem description and conversation history. This directly translates to higher API costs.
- Increased Latency: A larger prompt takes longer for the LLM to process, increasing the end-to-end latency of your agent.
- Reduced Accuracy (Cognitive Load): Asking an LLM to reason over a massive list of options can be confusing. It might misinterpret a tool's purpose, choose a suboptimal one, or even fail to select a tool at all. This is often referred to as the "lost in the middle" problem, where information presented in the middle of a long context is less likely to be recalled accurately.
The article "Agentic Search in Action" touches upon this trade-off directly.
Agentic Search in Action: A Practical Guide to Building from Scratch
This article provides practical insights from building an agent with a diverse toolset. The section on tool selection discusses the real-world challenges of managing a large inventory.
Please read the section titled Tool Selection. Pay attention to the author's point that "Adding tools enhances the agent’s capabilities but also increases complexity. A larger toolset requires the agent to allocate more context for tool descriptions and make decisions about which tools to use, potentially affecting efficiency."
This confirms our intuition: a naive "more is better" approach to tooling is not a scalable strategy for building production-grade agents. We need a more intelligent approach.
Part 2: A Two-Stage Architecture for Tool Selection
The solution is to decouple tool discovery from tool execution. Instead of presenting the entire tool inventory to the agent's main reasoning process, we'll adopt a two-stage pattern.

The process works as follows:
- Retrieval Stage: Given a user's query, we first use a fast and efficient search mechanism to retrieve a small subset of potentially relevant tools from the full inventory. This stage prioritizes recall—finding all plausible candidates.
- Execution Stage: We then provide only this small subset of candidate tools to the main agent LLM. The LLM performs its detailed reasoning on this much shorter list to select the single best tool for the job. This stage prioritizes precision—choosing the correct tool from the filtered set.
This retrieve-then-rank approach dramatically reduces the cognitive load on the LLM and makes the system scalable to a virtually unlimited number of tools. The LangChain video on "BigTool" provides an excellent explanation of this architecture.
BigTool: Agents with large number of tools
This video introduces the "BigTool" architecture, which is a perfect implementation of the two-stage selection pattern. It clearly explains the problem and the high-level solution.
First, watch the introduction from the beginning to understand the concept of "cognitive load" and how it impacts agents with many tools. Then, watch the core idea from the next segment, which explains the "retrieve-on-demand" strategy of using a separate search process to find and bind only the most relevant tools.
Now, let's explore how to build this search process from first principles.
Part 3: Implementing the Retrieval Stage with Semantic Search
The most effective way to implement the retrieval stage is through semantic search. Instead of keyword matching, we'll search based on the conceptual meaning of the tool descriptions. This relies on vector embeddings.
The implementation involves these steps:
- Tool Specification: As we've done before, define each tool with a name, a set of parameters, and, most importantly, a highly descriptive
descriptionstring. The quality of the description is paramount for the success of semantic search. - Offline Indexing:
- For each tool in your inventory, use an embedding model (like
text-embedding-3-smallor a local Sentence Transformer) to generate a vector embedding from itsdescription. - Store these embeddings in a vector store. For our from-scratch approach, a simple in-memory structure like a NumPy array or a list of dictionaries will suffice. In production, you'd use a dedicated vector database like Pinecone, Weaviate, or Redis. Each vector should be associated with its corresponding tool's name or ID.
- For each tool in your inventory, use an embedding model (like
- Online Retrieval:
- When the agent receives a user query, generate an embedding for the query text using the same embedding model.
- Calculate the cosine similarity between the query vector and all the tool description vectors in your store.
- Identify the top-K tools with the highest similarity scores. These are your candidate tools.
Let's sketch this out in Python.
import numpy as np
from typing import List, Dict, Any
# Assume we have an embedding function (e.g., calling an API or a local model)
def get_embedding(text: str) -> np.ndarray:
# In a real implementation, this would call an embedding model
# For this example, we'll simulate with random vectors
# To make it deterministic for the example
np.random.seed(sum(ord(c) for c in text))
return np.random.rand(256)
# Our full tool inventory (simplified definitions)
TOOL_INVENTORY = [
{"name": "get_weather", "description": "Fetches the current weather for a given city."},
{"name": "search_news", "description": "Searches for recent news articles on a specific topic."},
{"name": "calculate_mortgage", "description": "Computes monthly mortgage payments based on loan amount, interest rate, and term."},
{"name": "stock_price", "description": "Retrieves the latest stock price for a given ticker symbol."},
{"name": "list_calendar_events", "description": "Lists events from the user's calendar for a specified date range."}
]
# --- Offline Indexing Step ---
class ToolVectorStore:
def __init__(self, tools: List[Dict[str, Any]]):
self.tools = tools
# Generate and store embeddings for each tool description
self.vectors = np.array([get_embedding(tool["description"]) for tool in self.tools])
self.vectors /= np.linalg.norm(self.vectors, axis=1, keepdims=True) # Normalize for cosine similarity
def search(self, query: str, top_k: int = 3) -> List[Dict[str, Any]]:
query_vector = get_embedding(query)
query_vector /= np.linalg.norm(query_vector) # Normalize
# Compute cosine similarity
similarities = np.dot(self.vectors, query_vector)
# Get top_k indices
top_indices = np.argsort(similarities)[-top_k:][::-1]
return [self.tools[i] for i in top_indices]
# Initialize the store with our inventory
tool_store = ToolVectorStore(TOOL_INVENTORY)
# --- Online Retrieval Step ---
user_query = "What's the market value of Apple right now?"
candidate_tools = tool_store.search(user_query)
print(f"Query: '{user_query}'")
print("Candidate tools retrieved:")
for tool in candidate_tools:
print(f"- {tool['name']}: {tool['description']}")
# --- Example 2 ---
user_query_2 = "Did anything interesting happen in finance today?"
candidate_tools_2 = tool_store.search(user_query_2, top_k=2)
print(f"\nQuery: '{user_query_2}'")
print("Candidate tools retrieved:")
for tool in candidate_tools_2:
print(f"- {tool['name']}: {tool['description']}")
This code demonstrates the core logic. You create an index of tool descriptions once, and then at runtime, you can perform a fast semantic search to find the most relevant tools for any given query.
Part 4: Integrating Retrieval into the Agent Loop
Now that we have a mechanism to find relevant tools, how do we integrate it into our agent's observe-think-act loop? The most elegant solution is to expose the search function itself as a tool. This creates a "meta-tool" or a "tool-finder tool."
The BigTool video explains this integration beautifully. The agent is initially given only one special tool, often named retrieve_tools. Its first action is to call this tool with the user's query. The orchestrator then takes the search results (the candidate tools) and dynamically binds them to the agent for the subsequent reasoning step.
BigTool: Agents with large number of tools
This video provides a detailed walkthrough of how the retrieval mechanism is integrated into the agent's execution flow.
Start by watching the section from this diagram, which illustrates how the retrieve_tools tool is called first. The retrieved tools are then bound to the LLM for the actual tool call. Next, watch the code walkthrough from "we can see convert". This section is crucial. It shows how tool descriptions are indexed in a vector store and how the agent trace reveals a two-step process: first, a call to retrieve_tools which returns tool IDs, and second, a call where the LLM sees only the retrieved tools (e.g., arc_coast and coast) and makes its final selection. Finally, watch the conclusion from the recap, which summarizes how this dynamic selection reduces cognitive load and improves reliability, even for smaller local models.
By structuring the process this way, the agent itself learns to first narrow down its options before committing to an action. This mimics a very natural human problem-solving pattern: first, gather relevant information, then make a decision based on that information. The logic fits seamlessly into the agent loop we have developed in prior lessons.
Part 5: From Matching to Meaning with LLM Re-ranking
Semantic search with vector embeddings is powerful and fast, but it operates on "matching" concepts. It's essentially a sophisticated pattern detector. However, true relevance can be more nuanced and may require reasoning. This is where we can introduce a second, more powerful filtering stage: LLM-based re-ranking.
The idea is to use the fast vector search to retrieve an initial, slightly larger set of candidates (e.g., top 10) and then use an LLM to re-rank this smaller set.
A Primer on Re-Ranking for Retrieval Systems
This article provides an exceptional deep dive into re-ranking, explaining how LLMs can move beyond simple matching to perform actual reasoning.
Read the section LLMs as Rerankers. The key insight is that you can frame re-ranking as a "micro chain-of-thought task." For each candidate tool retrieved by vector search, you prompt the LLM with the user's query and the tool's description and ask a simple question: "Is this document relevant to the question? Answer Yes/No." This forces the LLM to judge relevance rather than just similarity.
This hybrid approach gives you the best of both worlds: the speed of vector search for initial retrieval and the reasoning power of an LLM for final, precise ranking. While it adds a bit of latency, this two-pass system is a hallmark of production-grade search and recommendation systems and is a powerful pattern for advanced agent architectures.
The decision of whether to use vector search alone or add an LLM re-ranking layer is an engineering trade-off between latency, cost, and the required accuracy for your specific use case.
Conclusion
In this lesson, we have engineered a solution to one of the most significant scaling challenges in agent design: managing a large inventory of tools. By implementing a dynamic tool selection mechanism, we've made our agent more efficient, scalable, and reliable.
Key Takeaways:
- Cognitive Load is a Real Constraint: Providing an LLM with a long list of tools increases cost, latency, and can reduce accuracy.
- Two-Stage Selection is the Solution: A retrieve-then-execute architecture, where a fast search mechanism first finds candidate tools, is a robust and scalable pattern.
- Semantic Search is the Foundation: Indexing tool descriptions in a vector store and using semantic search is an effective way to implement the retrieval stage.
- Integrate via a Meta-Tool: The retrieval process can be exposed to the agent as a special
retrieve_toolstool, which fits naturally into theobserve-think-actloop. - LLM Re-ranking Adds Precision: For higher accuracy, an LLM can be used to re-rank the initial candidates from the retrieval stage, trading a little latency for better relevance assessment.
Now that our agent can intelligently select the right tool from a vast library, we are ready to move from orchestrating single actions to building complex, multi-step workflows.
Preview of the Next Module: In our next module, Orchestration with Workflow Graphs, we will begin modeling agentic processes as Directed Acyclic Graphs (DAGs). This will allow us to move beyond a simple reactive loop and construct predefined, reliable workflows with conditional logic, parallelism, and structured inputs and outputs—a critical step toward building production-grade agentic systems.