🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Tool Calling: Schemas, Safety, and Reliable Selection

đŸŸĸ Free Lesson

What the model actually receives

The model never sees your Python. When you register a tool, the framework generates a JSON schema from three things: the function name, the type annotations, and the docstring. That schema is what goes into the request, which means those three fields are the entire interface, and everything else about your implementation is invisible.

This explains most tool-calling failures. A tool that is never selected usually has a docstring that describes what it does but not when to use it. A tool that is called with wrong arguments usually has vague parameter names or missing annotations. A tool that is called when it should not be usually has a name that overlaps with another tool's purpose, such as search alongside lookup.

Architecture Diagram
Without tools:  "I believe the weather is probably..."
With tools:     calls get_weather("London")  ->  "55F, rainy"

The loop that surrounds the call is worth knowing by heart. The model emits a structured request naming the tool and filling the arguments. The framework validates those arguments against the schema, executes your function, and returns the result as a new message. The model then reads that result and either answers the user or calls another tool. Because the arguments are validated before execution, a well-typed signature catches a large share of bad calls before any side effect happens.


Anatomy of a tool that the model can use

Write each tool as if a colleague will call it without reading the source, because that is literally what happens. Name it after the action, annotate every parameter, and spend most of your docstring on when to use it and when not to.

python
from langchain_core.tools import tool


@tool
def get_stock_price(symbol: str, currency: str = "USD") -> str:
    """Current stock price for a ticker symbol.

    Use this when the user asks about a share price, market value
    or how a stock is trading today. Do not use it for historical
    charts or fundamentals; this tool returns one snapshot only.
    The symbol is the exchange ticker, for example AAPL or RELIANCE.
    """
    catalog = {"AAPL": 189.42, "MSFT": 412.07, "RELIANCE": 2891.50}
    key = symbol.strip().upper()
    if key not in catalog:
        return f"No price available for symbol '{key}'."
    rate = {"USD": 1.0, "EUR": 0.92, "INR": 83.4}[currency]
    return f"{key}: {catalog[key] * rate:.2f} {currency}"


@tool
def list_open_tickets(team: str, status: str = "open") -> str:
    """Count and list support tickets for one team.

    Args:
        team: Team slug such as 'billing' or 'platform'.
        status: One of 'open', 'pending' or 'closed'.

    Returns a short numbered list with ticket ids and titles.
    """
    allowed = {"open", "pending", "closed"}
    if status not in allowed:
        return f"Error: status must be one of {sorted(allowed)}"
    tickets = {
        ("billing", "open"): ["#1041 refund for double charge",
                              "#1047 invoice VAT number wrong"],
        ("platform", "open"): ["#1033 webhook retries failing"],
    }.get((team.lower(), status), [])
    if not tickets:
        return f"No {status} tickets for team '{team}'."
    body = "\n".join(f"{i + 1}. {t}" for i, t in enumerate(tickets))
    return f"{len(tickets)} {status} ticket(s):\n{body}"

Three habits in that code are worth copying everywhere. Every parameter has a name that is meaningful in isolation, so the model can fill it without guessing. Default values are legal and documented, so the model can omit them. And every failure path returns a sentence the model can act on, including the list of valid options when an argument is rejected.

💡The docstring is a prompt

Treat the tool description as part of your prompt engineering budget. If two tools are getting confused for each other, rewrite the usage guidance before you rewrite the model.


A small toolset worth building once

Four tools cover a surprising range of agent projects: a search that reaches outside the model's training data, a calculator for exact arithmetic, a reader for local documents, and a query tool for structured data. Each one has a specific hazard, noted inline.

python
import sqlite3
from langchain_core.tools import tool
from duckduckgo_search import DDGS


@tool
def web_search(query: str) -> str:
    """Search the web for current information on any topic.

    Use for news, versions, prices or events after the model's
    training cutoff. Returns up to three short snippets.
    """
    try:
        with DDGS() as ddgs:
            results = list(ddgs.text(query, max_results=3))
    except Exception as exc:
        return f"Search failed: {exc}"
    if not results:
        return "No results found."
    return "\n\n".join(r.get("body", "")[:240] for r in results)


@tool
def calculator(expression: str) -> str:
    """Evaluate an arithmetic expression using digits and + - * / ( )."""
    allowed = set("0123456789+-*/(). ")
    if not set(expression) <= allowed:
        return "Error: only digits and basic operators are allowed"
    try:
        value = eval(expression, {"__builtins__": None}, {})
        return f"The answer is {value}"
    except Exception as exc:
        return f"Error while calculating: {exc}"


@tool
def read_document(filename: str) -> str:
    """Read up to 2000 characters from a text file in the docs folder."""
    import pathlib
    root = pathlib.Path("docs").resolve()
    target = (root / filename).resolve()
    if not str(target).startswith(str(root)):
        return "Error: path outside the docs folder is not allowed"
    if not target.exists():
        return f"File '{filename}' not found in docs/"
    return target.read_text(encoding="utf-8")[:2000]


@tool
def query_orders(customer_email: str, limit: int = 5) -> str:
    """List recent orders for one customer email address.

    Returns order id, date and total. Use for questions about
    someone's orders or purchase history.
    """
    conn = sqlite3.connect("orders.db")
    rows = conn.execute(
        "SELECT id, ordered_at, total FROM orders "
        "WHERE email = ? ORDER BY ordered_at DESC LIMIT ?",
        (customer_email.strip().lower(), min(max(limit, 1), 20)),
    ).fetchall()
    conn.close()
    if not rows:
        return "No orders found for that email."
    return "\n".join(f"#{r[0]} {r[1]} total {r[2]}" for r in rows)

Note the three safety patterns embedded in that set. The calculator rejects characters rather than trying to sanitize them after evaluation. The document reader resolves the path and refuses anything that escapes the allowed directory, which is how you stop a model from being talked into reading your environment file. The database tool uses parameterized queries, so an email containing a quote cannot turn into an injection.


Choosing, refusing, and calling in parallel

Most provider APIs let you constrain tool choice. With auto, the model may answer directly or call a tool, which is the right default for a general assistant. With a named tool, you force an action, which is useful in a workflow where this step must always query the database. With none, you forbid tools entirely, which is the cheapest way to generate a final answer after the research phase.

SituationTool choiceWhy
General assistant answering anythingAutoDirect answers are cheaper for simple questions
Workflow step that must fetch dataForcedRemoves the chance the model skips the fetch
Final answer after a research loopNonePrevents an unnecessary extra call
User explicitly asking to searchForced searchMatches the stated intent exactly

Parallel calls deserve a mention because they change the latency profile. When a question needs weather in two cities, a model that emits both calls in one turn lets the framework execute them concurrently, turning two sequential round trips into one. Your tools must be independent for this to help, so avoid tools that write to the same file or mutate shared state in a single turn.

Refusal is the capability people forget to design. A tool set without a graceful no leaves the model inventing an answer when the right action is unavailable. Return messages such as no results found or that file is not readable, and instruct the agent, in its system prompt, to relay those messages honestly rather than papering over them.


Testing tools without spending a model call

Tools are plain functions, so test them like plain functions. The framework lets you invoke a tool directly with a dictionary of arguments, which is exactly what the agent loop will do at runtime.

python
import pytest


def test_calculator_rejects_python_expressions():
    result = calculator.invoke({"expression": "__import__('os')"})
    assert "Error" in result


def test_calculator_handles_division_by_zero():
    result = calculator.invoke({"expression": "1 / 0"})
    assert result.startswith("Error")


def test_document_reader_blocks_path_traversal():
    result = read_document.invoke({"filename": "../.env"})
    assert "not allowed" in result


def test_order_query_parameterizes_email():
    result = query_orders.invoke(
        {"customer_email": "[email protected]' OR '1'='1"})
    assert result == "No orders found for that email."


def test_stock_price_converts_currency():
    result = get_stock_price.invoke({"symbol": "aapl", "currency": "EUR"})
    assert "EUR" in result and "174" in result

Those five tests take milliseconds and catch the failures that embarrass you in a demo: unsafe evaluation, unhandled exceptions, path traversal, injection, and argument coercion. Add them to your repository before you register the tools with any agent, and the first model call you make is already testing behavior you understand.

Latency, cost, and the tools you should not build

Every tool call adds at least one model round trip, and many add network latency on top. A three-call research turn can take ten seconds, which is fine for an interactive assistant and unacceptable behind a web request. Two mitigations work at different layers. Parallel independent calls collapse sequential round trips into one, and caching identical calls collapses repeat work, which matters more than people expect because agents often re-fetch the same fact within a session.

Caching needs care around correctness. Search results for a breaking news query are stale within minutes, while a currency rate is stale within seconds and a product catalogue lookup can safely live for an hour. Attach an explicit time-to-live to every cached tool and pick it from the volatility of the underlying data rather than from a single global default. Log cache hits as well, because a sudden drop in hit rate is often the first sign that an upstream service changed its behavior.

It is equally worth asking which tools should not exist. If the model can answer the question reliably from its own knowledge, a tool call is pure added latency and cost. Arithmetic beyond a few digits is the classic case for a calculator; famous historical dates are not. Design the toolset around the failures you actually observe in traces, and resist the temptation to expose an internal API just because it is available.

Common Mistakes

Writing a docstring that describes the function rather than when to call it

Fix: State the trigger conditions, the exclusions, and the format of the returned text

Returning None or raising an exception on failure

Fix: Return a sentence the model can act on, including valid options when an argument is rejected

Passing unsanitized input to eval, open or string-built SQL

Fix: Whitelist characters, resolve and confine paths, and use parameterized queries

Testing tools only through the agent, which makes failures slow and expensive to reproduce

Fix: Call tool.invoke directly in unit tests covering success, bad input and hostile input

Adding a tool for every internal endpoint you happen to have

Fix: Add a tool only after a trace shows the agent failing without it, since every tool costs latency and selection accuracy

Best Practices

  • Annotate every parameter and give defaults, so the model can omit what it does not know
  • Make every tool return text for both success and failure, with failures suggesting a next step
  • Run tools under the same input validation you would apply to an external API
  • Cap output size so a single call cannot flood the context window
  • Register tools with explicit names, and check for overlap before adding a new one

Interview Questions

Q1: What information does the model receive about a tool?

The name, the JSON schema generated from type annotations, and the docstring. The implementation body never leaves your process, so those three fields are the whole contract.

Q2: Why should argument validation happen inside the tool even though the framework validates types?

Type validation catches wrong shapes but not wrong values, such as an unknown status string or a path outside the allowed directory. Semantic checks belong in your function.

Q3: How do you stop a model from calling a tool that should not be used for a question?

Sharpen the docstring exclusions first, since ambiguous usage guidance is the usual cause. If overlap is unavoidable, constrain tool choice for that step or restructure the tools so their scopes do not intersect.

Q4: What is the cheapest way to test a tool?

Invoke it directly with a dictionary of arguments and assert on the returned string, covering success, invalid input and hostile input. No model call is needed.

Key Takeaways

  • The model reads a generated JSON schema, not your source, so name, annotations and docstring are the interface
  • Docstrings should specify when to call the tool and when not to
  • Every failure path must return readable text the agent can relay or recover from
  • Sanitize inputs for eval, file access and SQL before the framework's type validation gives you false confidence
  • Force, forbid or allow tool choice per workflow step instead of relying on auto everywhere
  • Tools are plain functions; unit test them with direct invoke calls before wiring an agent
  • Watch for output size and tool overlap, both of which cause silent quality loss
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert AI Agents Beginner Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement