How to beginner to intermediate · 4 min read

How to create custom tool in LangChain

Quick answer
To create a custom tool in LangChain, subclass BaseTool and implement the _run method for synchronous logic or _arun for async. Register your tool with a name and description, then use it in chains or agents for AI workflows.

PREREQUISITES

  • Python 3.8+
  • pip install langchain>=0.2
  • OpenAI API key or other AI API key in environment variables

Setup

Install langchain via pip and set your API key as an environment variable. This example assumes you have an OpenAI API key.

bash
pip install langchain openai

Step by step

Create a custom tool by subclassing BaseTool and implementing the _run method. Then instantiate and use it in a LangChain agent or chain.

python
import os
from langchain.tools import BaseTool
from langchain.chains import LLMChain
from langchain_openai import ChatOpenAI

class ReverseTextTool(BaseTool):
    name = "reverse_text"
    description = "Reverses the input text string."

    def _run(self, query: str) -> str:
        return query[::-1]

    async def _arun(self, query: str) -> str:
        # Async version if needed
        return query[::-1]

# Example usage
if __name__ == "__main__":
    tool = ReverseTextTool()
    input_text = "Hello LangChain"
    output = tool.run(input_text)
    print(f"Input: {input_text}")
    print(f"Output: {output}")
output
Input: Hello LangChain
Output: niaChgnaL olleH

Common variations

  • Use _arun for async tool implementations.
  • Integrate with different LLMs by importing from langchain_openai or other providers.
  • Combine multiple tools in an agent for complex workflows.
python
from langchain_openai import ChatOpenAI
from langchain.agents import initialize_agent, Tool

# Wrap custom tool for agent
reverse_tool = Tool(
    name="reverse_text",
    func=ReverseTextTool().run,
    description="Reverses input text"
)

llm = ChatOpenAI(model_name="gpt-4o", temperature=0)
agent = initialize_agent([reverse_tool], llm, agent="zero-shot-react-description", verbose=True)

response = agent.run("Reverse the phrase: LangChain is powerful")
print(response)
output
lufrewop si niahCgnaL

Troubleshooting

  • If you see AttributeError on _run, ensure your tool class inherits from BaseTool and implements _run.
  • For environment variable issues, confirm OPENAI_API_KEY is set correctly.
  • Use verbose=True in agents to debug tool calls and outputs.

Key Takeaways

  • Subclass BaseTool and implement _run to create custom LangChain tools.
  • Use your custom tool in LangChain agents by wrapping it with Tool and initializing an agent.
  • Implement async logic with _arun for asynchronous workflows.
  • Set API keys in environment variables and install langchain and provider SDKs before use.
  • Enable verbose=True in agents to troubleshoot tool integration issues.
Verified 2026-04 · gpt-4o
Verify ↗