liveBook · Manning

Tool decorator

As explained in Data Analysis with LLMs

The LangChain tool decorator is a Python decorator that converts a function into a tool with metadata describing its name, parameters, and behavior.

The `@tool` decorator turns a Python function into a tool an agent can invoke. Place it directly before the function. Give the function a clear name and annotate its parameters and return value: the agent uses this information to understand the tool and call it with appropriately typed inputs. section 10.5.1

Convert game-sale amounts

A data-analysis agent working with video-game sales in US dollars can use a `convert_currency` function to return an amount in a target currency. Its `USD_amount: float` and `currency: str` parameters make the expected inputs explicit; its result can be a converted amount or an error message. section 10.5.1

Listing 10.3 Data-analysis agent with currency-converter tool
import argparse

from langchain.agents.load_tools import load_tools
from langchain.tools import tool
from langchain_community.utilities.sql_database import SQLDatabase
from langchain_community.agent_toolkits.sql.base import create_sql_agent
from langchain_openai import ChatOpenAI
from typing import Union

@tool  #1
 #2
def convert_currency(USD_amount: float, currency: str)->Union[float, str]:
     #3
    """ Converts an amount in US dollars to another currency.
    
    Args:
        USD_amount: amount in US dollars.
        currency: name of target currency (e.g., "Yen").
    
    Returns:
        input amount in target currency.
    """
    conversion_factors = {
        'Euro':0.93, 'Yen':151.28, 'Yun':0.14, 
        'Pound':1.26, 'Won':0.00074, 'Rupee':0.012}
    
    if currency not in conversion_factors:
         #4
        error_message = (
            f'Unknown currency: {currency}!'
            f'Use one of {conversion_factors.keys()}')
        return error_message

     #5
    conversion_factor = conversion_factors[currency]
    converted_amount = USD_amount * conversion_factor
    return converted_amount

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('serpaikey', type=str, help='SERP API access key')
    parser.add_argument('dbpath', type=str, help='Path to SQLite database')
    parser.add_argument('question', type=str, help='A question to answer')
    args = parser.parse_args()
    
    llm = ChatOpenAI(
        temperature=0, model='gpt-4o')
    db = SQLDatabase.from_uri(f'sqlite:///{args.dbpath}')
    extra_tools = load_tools(
        ['serpapi'], serpapi_api_key=args.serpaikey, llm=llm)
     #6
    extra_tools.append(convert_currency)

    agent = create_sql_agent(
        llm=llm, db=db, verbose=True,
        agent_type='openai-tools',
        extra_tools=extra_tools)
    agent.invoke({'input':args.question})

See the currency-converter implementation and how the decorated function is added to a data-analysis agent. section 10.5.1

How Data Analysis with LLMs covers it

How deep it goes
Explains decorator placement, function naming, and type annotations; does not detail decorator internals.
Examples
Uses a currency-conversion function to support analysis of video-game sales across currencies.
What it assumes
Assumes familiarity with Python functions and type annotations.
What you can do after
Build it from scratch: decorate a typed Python function for use as an agent tool.
How it connects
Connects Python functions to agents, tools, and language models.

Also explained in

Compare how 2 books explain tool decorator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data Analysis with LLMs. The section links point to the parts of the book it draws on.