Tools in LangChain

The need for tools

Imagine you’re having a conversation with an incredibly intelligent AI. It can discuss complex topics, generate creative text, and even understand your feelings. But what if you ask it something like, “What’s the weather like in New York right now?” It might be able to generate a plausible answer based on its training data, but it wouldn’t have real-time access to current weather information. This is where the concept of tools becomes crucial.

Tools are like superpowers for your AI. They allow it to interact with the outside world – databases, APIs, web search engines, and much more. With the right tools, your AI can go beyond just answering questions and actually perform actions, making it a more versatile and practical assistant.

This is where tool calling comes in, an incredibly important concept. Tool calling allows the AI to decide when and how to use these tools. This isn’t about just having access but about smart, contextual usage.

What exactly is a tool?

At its core, a tool is simply a Python function that performs a specific task. But in the context of LangChain, it’s more than just a function. A tool is a function packaged with metadata that helps the AI understand what it does, how to use it, and what kind of information it needs. Think of it like a well-documented instruction manual for your AI assistant.

The BaseTool interface

LangChain uses a class called BaseTool as the blueprint for all tools. It defines the core attributes and methods that all tools should have:

  • name: A descriptive name for the tool (e.g., “weather_lookup”, “multiply_numbers”).

  • description: A natural language explanation of what the tool does (e.g., “Retrieves the current weather conditions for a given city.”).

  • args: A definition of the expected inputs for the tool (e.g., a “city” string).

  • invoke(args): This is the method that is called to execute the tool.

The @tool Decorator

While we could manually create tools by subclassing BaseTool, LangChain provides a much easier way: the @tool decorator. Think of it like a magic wand that transforms your regular Python functions into powerful AI tools.

Here’s how it works:

  1. We define a regular Python function to do something.

  2. We decorate that function with @tool.

  3. LangChain automatically infers the tool’s name, description, and input arguments based on the function’s name, docstring, and type hints.

Let’s look at an example:

Get hands-on with 1300+ tech skills courses.