Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 60

Tool Selection and Usage with LLMs

This lesson is built with resources from digitalapplied.com and leoniemonigatti.com.

Hello! Welcome to the next lesson in our module on the Foundations of AI Agents.

In our last session, we gave our agent a memory, allowing it to hold multi-turn conversations using a checkpointer and manage its context window with middleware. We equipped it with a couple of tools, and it could use them when prompted.

However, a truly intelligent agent needs to do more than just use a tool; it needs to decide which tool is the right one for the job, especially when it has a whole toolbox at its disposal. This lesson focuses on that crucial decision-making process. We will explore how an agent selects the correct tool from a given set based on a user's request. This is the core of the agent's "reasoning" capability.

By the end of this lesson, you will be able to build an agent that can intelligently choose and use the most appropriate tool from a collection of options to fulfill a user's request.

How Does an Agent Choose a Tool?

The ability of an agent to select a tool isn't just a feature of a framework like LangChain. It's a native capability of modern LLMs (like OpenAI's GPT series, Anthropic's Claude, and Google's Gemini), often referred to as "tool calling" or "function calling".

The process works like this:

  1. Tool Description: When we create an agent, we provide it with a list of available tools. Frameworks like LangChain take our Python functions (decorated with @tool) and convert them into a structured format, like a JSON Schema, that the LLM can understand. This schema details the tool's name, its purpose, its parameters, and their data types.
  2. Reasoning: When the agent receives a user's message, the LLM analyzes the message in the context of the available tool descriptions. It asks itself, "Based on the user's request, is there a tool I can use to help answer this? If so, which one is the best fit, and what arguments does it need?"
  3. Action: If the LLM decides to use a tool, it doesn't output a final text answer. Instead, it outputs a special, structured message indicating the name of the tool it wants to call and the arguments to pass to it.
  4. Execution: The agent framework (e.g., LangChain's AgentExecutor) intercepts this message, executes the corresponding Python function with the provided arguments, and captures the result.
  5. Observation: The result from the tool is then sent back to the LLM in the next turn. The LLM observes this new information and decides its next step: either provide a final answer to the user or call another tool.

An illustration of the agent's execution flow: User Input -> Reasoning -> Tool Invocation -> Observation & Iteration -> State Persistence.

This diagram from "LangChain AI Agents: Complete Implementation Guide 2025" shows the iterative process an agent follows. The "Reasoning Phase" is where the agent analyzes the user request and available tools to decide which one to use.

For you as a developer, the most critical part of this process is step 1: describing the tools. The quality of your tool descriptions directly determines how well the agent can reason about when to use them.


Designing Effective Tools for Your Agent

Since the LLM relies entirely on the tool's description to make its decision, designing that description well is paramount. Your Python function's name, its type hints, and especially its docstring are no longer just for other developers—they are the primary interface for the AI.

Let's read about the best practices for this.

LangChain AI Agents: Complete Implementation Guide 2025

The following article, "LangChain AI Agents: Complete Implementation Guide 2025", provides an excellent summary of best practices for designing tools that agents can reliably understand and use.

Please read the subsection titled 'Tool Design Best Practices'. Focus on the four principles it outlines. Think of the docstring not as a comment, but as API documentation written specifically for an LLM.

As you just read, the key principles are:

  • Clear Names: search_company_info is much better than do_search. The name itself is the first clue for the LLM.
  • Comprehensive Docstrings: This is the most important element. A good docstring tells the LLM:
    • What the tool does in simple terms.
    • When to use it, often with concrete examples. This is crucial for disambiguation.
    • What each parameter means.
    • What the tool returns.
  • Type Hints: These are mandatory. LangChain uses them to create the tool's schema, ensuring the LLM knows what kind of data to provide for each argument (e.g., str, int, float).
  • Error Handling: A tool that can fail should catch exceptions and return an informative error message. This gives the agent a chance to try something else or report the failure, rather than crashing the entire process.

Hands-On: An Agent as a Business Analyst

Let's build an agent that acts as a simple business analyst. It will have two distinct tools: one for retrieving qualitative company information and another for performing quantitative financial calculations. This will force the agent to choose the correct tool based on the nature of the user's query.

We'll use the tool definitions inspired by the "LangChain AI Agents" guide.

Step 1: Define the Tools

Notice the detailed docstrings. We are explicitly telling the agent when to use each tool.

# Make sure you have the necessary libraries installed:
# pip install langchain langchain-openai langgraph

import os
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langchain.agents import create_agent, AgentExecutor
from langgraph.checkpoint.memory import InMemorySaver
from typing import Optional

# Set your OpenAI API key
# os.environ["OPENAI_API_KEY"] = "your-api-key"

@tool
def search_company_info(company_name: str, info_type: Optional[str] = "overview") -> str:
    """
    Search for company information from various sources.
    Use this tool when the user asks about a company's details, background,
    general information, financial data, revenue, market position, or recent news.
    
    Args:
        company_name: The name of the company to search for.
        info_type: Type of information to retrieve (e.g., 'overview', 'financials', 'news').
    """
    print(f"\n>> Called search_company_info(company_name='{company_name}', info_type='{info_type}')")
    # This is a mock implementation for demonstration
    if "innovate" in company_name.lower():
        if info_type == "financials":
            return f"Financial data for {company_name}: Revenue $10M, Growth 25%"
        elif info_type == "news":
            return f"Latest news for {company_name}: Expanded to new markets"
        else:
            return f"{company_name} is a leading technology company founded in 2020, specializing in AI solutions."
    return f"Sorry, I couldn't find any information on {company_name}."

@tool
def calculate_roi(investment: float, return_value: float) -> dict:
    """
    Calculate Return on Investment (ROI) for financial analysis.
    Use this tool when the user needs to calculate investment returns,
    profitability, or analyze financial performance metrics based on an investment and return.

    Args:
        investment: Initial investment amount.
        return_value: Final value or returns from the investment.
    """
    print(f"\n>> Called calculate_roi(investment={investment}, return_value={return_value})")
    if investment == 0:
        return {"error": "Investment cannot be zero."}
    total_return = return_value - investment
    roi_percentage = (total_return / investment) * 100
    return {
        "roi_percentage": round(roi_percentage, 2),
        "total_return": round(total_return, 2),
    }

tools = [search_company_info, calculate_roi]

Step 2: Create and Test the Agent

We'll create the agent just as we did in the last lesson, with a checkpointer for memory.

# Setup the agent
llm = ChatOpenAI(model="gpt-4-turbo", temperature=0)
memory_saver = InMemorySaver()
agent_executor = create_agent(llm, tools, checkpointer=memory_saver)

# Configure the conversation thread
thread_id = "business-analyst-1"
config = {"configurable": {"thread_id": thread_id}}

# --- Test Case 1: A query for company information ---
print("--- Test Case 1: Company Info ---")
response = agent_executor.invoke({"messages": ["Tell me about Innovate Inc."]}, config)
print(f"Agent: {response['messages'][-1].content}")

# --- Test Case 2: A query for financial calculation ---
print("\n--- Test Case 2: ROI Calculation ---")
response = agent_executor.invoke(
    {"messages": ["I invested $5000 and got back $7500. What was my ROI?"]}, config
)
print(f"Agent: {response['messages'][-1].content}")

# --- Test Case 3: A conversational follow-up ---
print("\n--- Test Case 3: Conversational Follow-up ---")
response = agent_executor.invoke(
    {"messages": ["That's great. And what were the financials for that company you just told me about?"]}, config
)
print(f"Agent: {response['messages'][-1].content}")

When you run this code, observe the >> Called... print statements. You will see that the agent correctly calls search_company_info for the first and third tests, and calculate_roi for the second. It successfully distinguishes between a qualitative request for information and a quantitative request for a calculation, all thanks to the descriptive docstrings.

Test your understanding!

Imagine you add a third tool to this agent:

@tool
def get_stock_price(ticker: str) -> str:
    """Gets the latest stock price for a company given its stock ticker symbol."""
    # ... implementation ...

A user then asks: "What is the financial status of Apple?"

Which tool is the agent most likely to choose: search_company_info or get_stock_price? Why might this query be ambiguous, and how could you improve the docstrings to guide the agent to a better decision?

Show answer

The agent would likely choose search_company_info with info_type='financials'. The phrase "financial status" is broad and aligns well with the description of search_company_info which mentions "financial data, revenue, or market position". The get_stock_price tool is very specific—it requires a "ticker symbol," which the user did not provide.

Ambiguity: The ambiguity arises because "financial status" could reasonably include the stock price. The agent might get stuck or choose a suboptimal tool.

Improvement: To resolve this, you could make the docstrings more explicit:

  • search_company_info docstring: Add a sentence like, "This provides high-level financial data like revenue and growth. For real-time stock prices, use the get_stock_price tool."
  • get_stock_price docstring: Add a sentence like, "Use this tool specifically for getting the current stock price of a publicly traded company. It requires a ticker symbol like 'AAPL' for Apple."

This cross-referencing in the docstrings helps the agent understand the distinct roles of each tool and when to prefer one over the other.


Conclusion

In this lesson, we demystified the process of tool selection in AI agents. You now have the knowledge and practical skills to design and build agents that can intelligently choose from a set of available functions to solve problems.

Key Takeaways:

  • Tool selection is a core capability of modern LLMs, enabled by providing them with structured descriptions of available functions.
  • As an agent developer, your most powerful lever for influencing tool selection is tool design.
  • A tool's docstring is its API for the LLM. It must clearly state what the tool does and, most importantly, when it should be used.
  • Clear function names, mandatory type hints, and robust error handling are essential for building reliable agents.

What's Next?

Our agent can now remember conversations and select the right tool for the job. But as software engineers, we know that things don't always work perfectly. What happens when the agent chooses the wrong tool, misunderstands the user, or gets stuck in a loop? In our next lesson, we will focus on debugging agent execution flows. We'll learn how to trace the agent's internal "thought process" to understand its decisions and fix its mistakes.