Creating Your Own Custom Tool

This is an example of how to create a custom tool that can be registered to GLChat.

Prerequisites

This example specifically requires:

Installation

# you can use a Conda environment
pip install gllm-plugin-binary

Creating a Custom Tool

  1. Create a new Python file for your tool, e.g., my_calculator_tool.py.

  2. Import necessary modules. You typically will need:

    • BaseTool from gllm_agents,

    • BaseModel and Field from pydantic,

    • tool_plugin decorator from gllm_plugin.tools.

  3. Define an input schema if needed. If your tool requires specific inputs, define a Pydantic BaseModel subclass. Use the Pydantic Field to add the description and validation for each input parameter.

from pydantic import BaseModel, Field

class MyCalculatorToolInput(BaseModel):
    param1: int = Field(..., description="Description for parameter 1")
    param2: str = Field(..., description="Description for parameter 2")
    param3: int = Field(..., description="Description for parameter 3")
  1. Create a tool class that inherits from gllm_agents.BaseTool.

  2. Apply the @tool_plugin(version="...") decorator to your class so that your custom tool can be registered to GLChat.

  3. Set the required attributes for your class:

    • name: A unique string identifier for your tool.

    • description: A clear, concise description of what the tool does. This description will be used by the AI agent to decide when to use the tool.

    • args_schema: Set this to your Pydantic input schema class defined in Step #3. If your tool takes no input, you may omit this and use the default value.

  4. Implement the _run method. This is the core logic of your tool. It receives the input parameters defined in your args_schema as arguments and should return a string result.

from gllm_agents import BaseTool
from gllm_plugin.tools import tool_plugin
from typing import Any

# Assuming MyCalculatorToolInput is defined as above
@tool_plugin(version="1.0.0")
class MyCalculatorTool(BaseTool):
    name: str = "my_calculator"
    description: str = "A simple tool that performs basic arithmetic operations."
    args_schema: type[BaseModel] = MyCalculatorToolInput
    
    def _run(self, param1: int, param2: str, param3: int, **kwargs: Any) -> str:
        # Calculator logic goes here
        result = f"The result of {param1} {param2} {param3} is …"
        return result

Once you create your tool, you can try running it by following Running a Custom Tool and Agent Locally or Running a Custom Tool and Agent in GLChat guide.

Troubleshooting

For common issues and their solutions, please refer to the centralized FAQ document.

Last updated