Building custom tools

Designing Agentic Systems with LangChain

Dilini K. Sumanapala, PhD

Founder & AI Engineer, Genverv, Ltd.

Calculating square footage

Rectangular floor plan of a studio apartment

Designing Agentic Systems with LangChain

Calculating square footage

Rectangular floor plan of a studio apartment with length and width respectively marked "side a" and "side b".

Designing Agentic Systems with LangChain

Creating a math tool

LangChain's internal query handling

"What is the area of a rectangle with 
sides 5 and 7?"

input = " 5, 7"

     

  • Natural language input

         
  • Extract numeric values as strings

Designing Agentic Systems with LangChain

Creating a math tool

Define your tool function

@tool

def rectangle_area(input: str) -> float:
"""Calculates the area of a rectangle given the lengths of sides a and b."""
sides = input.split(',')
a = float(sides[0].strip()) b = float(sides[1].strip())
return a * b

 

  • Use @tool decorator
  • Name the function
  • Create a docstring
  • Split the input using .split()
  • Strip whitespace using .strip() and convert to float
  • Multiply a and b and return the answer
Designing Agentic Systems with LangChain

Tools and query setup

# Define the tools that the agent can access
tools = [rectangle_area]

# Create a query using natural language query = "What is the area of a rectangle with sides 5 and 7?"
# Pass in the hypotenuse length tool and invoke the agent app = create_react_agent(model, tools)
Designing Agentic Systems with LangChain

Tools and query setup

# Invoke the agent and print the response
response = app.invoke({"messages": [("human", query)]})
print(response['messages'][-1].content)
The area of the rectangle with sides 5 and 7 is 35 square units.
Designing Agentic Systems with LangChain

Pre-built and custom tools

    Icon of tools

 

Designing Agentic Systems with LangChain

Let's practice!

Designing Agentic Systems with LangChain

Preparing Video For Download...