1. Building custom tools
Great work! Now that we know how to create an agent,
2. Calculating square footage
let's imagine a use case for a real estate agency. The agency staff may be interested in calculating the square footage of rectangular one-bed apartments.
3. Calculating square footage
We can build a math tool that does this using the lengths of the sides of the apartment, supplied by the staff using casual, natural language.
4. Creating a math tool
By default, LangChain accepts such natural language queries as strings. Internally, it uses the LLM to extract the necessary input from the query. Here, LangChain might extract the two numbers, "5" and "7", as string inputs representing rectangle lengths before performing calculations.
5. Creating a math tool
Let's create a function that can handle this kind of input. We'll start by using a decorator called @tool that LangChain uses to recognize custom functions as tools. After the decorator, we'll create a function called rectangle_area that takes in a string as an input. We then include a docstring to describe the function's purpose, specifying that it calculates the area of a rectangle given the lengths of two sides, a and b. Inside the function, we split the input string extracted from the query into the two values representing sides a and b. To multiply the sides, we strip any whitespace around the string inputs using Python's .strip() method and then convert each string to a float. We then multiply sides a and b together to calculate and return the area of the rectangle.
6. Tools and query setup
Now that we have our tool, let's make sure LangChain can access it by passing it within a list called "tools". Although we're only using one tool here, it's possible to list more, depending on our workflow. Then, we'll create a variable called "query" that accepts a question from the user in the form of natural language, perhaps passed from a real estate chatbot used by staff. We'll then create our ReAct agent called app, passing in the model, and the tool we just built.
7. Tools and query setup
To test that the agent works, we'll invoke the agent we just created, passing in the query we defined and then print the agent's response by identifying the last item in "messages" using the .content attribute. Looks like it works! So far, we've reviewed math tools in agentic workflows.
8. Pre-built and custom tools
LangChain also has an extensive library of pre-built tools for solving many other problems such as database querying, web scraping, and image generation, which can be incorporated by referencing LangChain's API guide. We can also reference LangChain's guide for using tool decorators to build other custom tools!
9. Let's practice!
Let's return to your agents and build your first tool!