Skip to main content

Overview

BaseTool is the abstract base class for all tools in Qwen-Agent. Tools are functions that agents can call to perform specific actions like code execution, web searching, or data retrieval.

Class Signature

from qwen_agent.tools.base import BaseTool

class BaseTool(ABC):
    name: str = ''
    description: str = ''
    parameters: Union[List[dict], dict] = []
    
    def __init__(self, cfg: Optional[dict] = None)

Class Attributes

name
str
required
Unique identifier for the tool. Must be set either via @register_tool() decorator or explicitly
description
str
required
Human-readable description of what the tool does
parameters
Union[List[dict], dict]
required
Tool parameters in OpenAI-compatible JSON schema format:
{
    'type': 'object',
    'properties': {
        'param_name': {
            'type': 'string',
            'description': 'Parameter description'
        }
    },
    'required': ['param_name']
}

Constructor Parameters

cfg
dict
Configuration dictionary for tool-specific settings

Methods

call (Abstract)

@abstractmethod
def call(
    self,
    params: Union[str, dict],
    **kwargs
) -> Union[str, list, dict, List[ContentItem]]
Executes the tool’s functionality. Must be implemented by subclasses.
params
Union[str, dict]
required
Tool parameters as JSON string or dictionary
kwargs
dict
Additional parameters for tool execution
return
Union[str, list, dict, List[ContentItem]]
Tool execution result. Can be:
  • String: Simple text result
  • List/Dict: Structured data
  • List[ContentItem]: Multimodal content (text, images, etc.)

Properties

function

@property
def function(self) -> dict
Returns the tool’s metadata in OpenAI function format.
return
dict
{
    'name': 'tool_name',
    'description': 'Tool description',
    'parameters': {...}  # JSON schema
}

name_for_human

@property
def name_for_human(self) -> str
Returns human-readable tool name from config or falls back to name.

args_format

@property
def args_format(self) -> str
Returns instructions on how to format tool arguments (auto-detects language).

file_access

@property
def file_access(self) -> bool
Indicates whether the tool requires file access.

Creating Custom Tools

Basic Tool

from qwen_agent.tools.base import BaseTool, register_tool
from typing import Union

@register_tool('my_calculator')
class Calculator(BaseTool):
    description = 'Performs arithmetic calculations'
    parameters = {
        'type': 'object',
        'properties': {
            'expression': {
                'type': 'string',
                'description': 'Mathematical expression to evaluate'
            }
        },
        'required': ['expression']
    }
    
    def call(self, params: Union[str, dict], **kwargs) -> str:
        params = self._verify_json_format_args(params)
        expression = params['expression']
        try:
            result = eval(expression)  # Note: Use safe eval in production!
            return f"Result: {result}"
        except Exception as e:
            return f"Error: {str(e)}"

Tool with File Access

from qwen_agent.tools.base import BaseToolWithFileAccess, register_tool
from typing import List

@register_tool('file_reader')
class FileReader(BaseToolWithFileAccess):
    description = 'Reads content from files'
    parameters = {
        'type': 'object',
        'properties': {
            'filename': {
                'type': 'string',
                'description': 'Name of the file to read'
            }
        },
        'required': ['filename']
    }
    
    def call(self, params: Union[str, dict], files: List[str] = None, **kwargs) -> str:
        # BaseToolWithFileAccess automatically downloads remote files to self.work_dir
        super().call(params=params, files=files)
        
        params = self._verify_json_format_args(params)
        filename = params['filename']
        
        import os
        filepath = os.path.join(self.work_dir, filename)
        
        try:
            with open(filepath, 'r') as f:
                content = f.read()
            return content
        except Exception as e:
            return f"Error reading file: {str(e)}"

Using Tools with Agents

from qwen_agent.agents import FnCallAgent

# Using built-in tools
agent = FnCallAgent(
    function_list=['code_interpreter', 'web_extractor'],
    llm={'model': 'qwen-max'}
)

# Using custom tools
from my_tools import Calculator

agent = FnCallAgent(
    function_list=[Calculator(), 'code_interpreter'],
    llm={'model': 'qwen-max'}
)

# Using tool with configuration
agent = FnCallAgent(
    function_list=[
        {'name': 'code_interpreter', 'timeout': 60},
        Calculator()
    ],
    llm={'model': 'qwen-max'}
)

Tool Registry

Tools are registered globally using the @register_tool() decorator:
from qwen_agent.tools import TOOL_REGISTRY

# Check available tools
print(TOOL_REGISTRY.keys())

# Get tool class
ToolClass = TOOL_REGISTRY['code_interpreter']
tool_instance = ToolClass()

Error Handling

from qwen_agent.tools.base import ToolServiceError

class MyTool(BaseTool):
    def call(self, params, **kwargs):
        try:
            # Tool logic
            pass
        except Exception as e:
            raise ToolServiceError(
                code='500',
                message=f'Tool execution failed: {str(e)}'
            )

See Also

Build docs developers (and LLMs) love