0
0
LangchainHow-ToBeginner ยท 3 min read

How to Create a Custom Tool in Langchain Easily

To create a custom tool in Langchain, define a class that inherits from BaseTool and implement the _call method with your tool's logic. Then, instantiate and use this tool within your Langchain agent or workflow.
๐Ÿ“

Syntax

Creating a custom tool in Langchain involves subclassing BaseTool and overriding the _call method. The name and description attributes describe the tool for the agent.

  • BaseTool: The base class for all tools.
  • _call(self, input: str) -> str: The method where your tool's main logic goes.
  • name: A string to identify the tool.
  • description: A string explaining what the tool does.
python
from langchain.tools import BaseTool

class CustomTool(BaseTool):
    name = "custom_tool"
    description = "Describe what this tool does"

    def _call(self, input: str) -> str:
        # Your tool logic here
        return "Result based on " + input
๐Ÿ’ป

Example

This example shows a custom tool that reverses the input string. It demonstrates how to define the tool and use it by calling its _call method.

python
from langchain.tools import BaseTool

class ReverseStringTool(BaseTool):
    name = "reverse_string"
    description = "Reverses the input string"

    def _call(self, input: str) -> str:
        return input[::-1]

# Using the custom tool
reverse_tool = ReverseStringTool()
output = reverse_tool._call("hello world")
print(output)
Output
dlrow olleh
โš ๏ธ

Common Pitfalls

Common mistakes when creating custom tools include:

  • Not overriding the _call method properly, which causes the tool to do nothing or error.
  • Forgetting to set name and description, making the tool unclear to the agent.
  • Using synchronous code when async is required in some Langchain contexts.

Always test your tool independently before integrating it into an agent.

python
from langchain.tools import BaseTool

# Wrong: Missing _call method
class BadTool(BaseTool):
    name = "bad_tool"
    description = "Does nothing"

# Right: Proper _call implementation
class GoodTool(BaseTool):
    name = "good_tool"
    description = "Returns input uppercased"

    def _call(self, input: str) -> str:
        return input.upper()
๐Ÿ“Š

Quick Reference

Remember these key points when creating custom tools in Langchain:

  • Subclass BaseTool.
  • Implement the _call(self, input: str) -> str method.
  • Set name and description for clarity.
  • Test your tool standalone before integration.
โœ…

Key Takeaways

Create custom tools by subclassing BaseTool and overriding the _call method.
Always provide clear name and description attributes for your tool.
Test your tool independently before using it in Langchain agents.
Avoid missing the _call method or incorrect method signatures.
Use synchronous or asynchronous code as required by your Langchain setup.