What is Tool in LangChain: Definition and Usage
Tool is a component that wraps external functionality or APIs so a language model can use them during its reasoning process. Tools let the model perform actions like searching, calculations, or calling APIs beyond just generating text.How It Works
A Tool in LangChain acts like a helper that the language model can call when it needs to do something specific outside of just chatting. Imagine you are talking to a friend who can also ask other experts for help when needed. The tool is like that expert the friend calls to get precise information or perform a task.
When the language model faces a question or task it can't solve by itself, it decides to use a tool. The tool runs its special function—like searching the internet, doing math, or fetching data—and returns the result back to the model. This way, the model can give smarter and more accurate answers by combining its language skills with real-world capabilities.
Example
This example shows how to create a simple tool that adds two numbers. The language model can then use this tool to perform addition when needed.
from langchain.tools import Tool def add_numbers_tool(input_str: str) -> str: # Expect input like '3, 5' try: a, b = map(int, input_str.split(",")) return str(a + b) except Exception: return "Invalid input" add_tool = Tool( name="Adder", func=add_numbers_tool, description="Adds two numbers given as 'num1, num2'" ) # Example usage print(add_tool.func("10, 20"))
When to Use
Use a Tool in LangChain when you want your language model to do more than just generate text. Tools are perfect for adding real-world actions like:
- Looking up current information from APIs or databases
- Performing calculations or data processing
- Interacting with external services like search engines, calendars, or messaging platforms
This makes your application smarter and more useful by combining language understanding with practical capabilities.
Key Points
- A
Toolwraps a function or API for the language model to call. - It extends the model's abilities beyond text generation.
- Tools have a name, a function, and a description to guide the model.
- They enable integration with real-world data and services.