TellWorldAI World Archive
Ask中文

Home›Practice›Practice

Practice

Custom tools in smolagents

In smolagents, a tool is a function an agent can call. This guide compares the @tool decorator with the Tool class, then covers built-in tools and importing tools from the Hub, Spaces, LangChain and MCP servers.

Who this is for and what you will be able to do

If you already have an agent running and want to connect it to your own functions, a third-party service or an MCP server, this guide is for you. By the end you should be able to define a tool in two ways, know which tools smolagents ships with, and import ready-made tools from the Hub, a Hugging Face Space, LangChain or an MCP server.

What a tool is in smolagents

In smolagents, tools are functions that a language model can call inside an agent system[1]. For the model to use a tool correctly, it needs an interface description with four parts: a name, a description of what the tool does, the input types and their descriptions, and the output type[1].

For example, a web search tool could be named web_search, take a query string as input, and return a string with the search results[1]. The description is what the model reads when it decides whether and how to call the tool, so it should be written with care.

Two ways to define a tool

smolagents offers two ways to define a tool. The @tool decorator wraps a plain Python function and suits simple tools. Subclassing the Tool class suits more complex functionality[1].

The @tool decorator is the recommended choice for simple tools. smolagents reads basic information about the function from Python, so a clear function name and a good docstring make the tool easier for the model to use[1]. A well-written @tool function has a descriptive name, type hints for its inputs and output, and a detailed description with an Args: section that explains each argument[1].

The following example defines a tool that returns the highest-rated catering service in Gotham City. The list of services is hard-coded example data, not a real search, so the code shows the structure rather than a working integration[1]:

@tool
def catering_service_tool(query: str) -> str:
    """
    This tool returns the highest-rated catering service in Gotham City.

    Args:
        query: A search term for finding catering services.
    """
    # Example list of catering services and their ratings
    services = {
        "Gotham Catering Co.": 4.9,
        "Wayne Manor Catering": 4.8,
        "Gotham City Events": 4.7,
    }

    # Find the highest rated catering service (simulating search query filtering)
    best_service = max(services, key=services.get)

    return best_service

The tool is passed to a CodeAgent that uses InferenceClientModel, and the result of agent.run() is printed. The output shown in the example is Gotham Catering Co.[1]:

agent = CodeAgent(tools=[catering_service_tool], model=InferenceClientModel())

# Run the agent to find the best catering service
result = agent.run(
    "Can you give me the name of the highest-rated catering service in Gotham City?"
)

print(result)   # Output: Gotham Catering Co.

The second way is to subclass Tool. A subclass wraps the function in metadata. It defines name, description, inputs, output_type and a forward method that holds the logic[1]. The description is used to populate the agent's system prompt[1]. The following class defines a tool that suggests superhero-themed party ideas[1]:

from smolagents import Tool, CodeAgent, InferenceClientModel

class SuperheroPartyThemeTool(Tool):
    name = "superhero_party_theme_generator"
    description = """
    This tool suggests creative superhero-themed party ideas based on a category.
    It returns a unique party theme idea."""

    inputs = {
        "category": {
            "type": "string",
            "description": "The type of superhero party (e.g., 'classic heroes', 'villain masquerade', 'futuristic Gotham').",
        }
    }

    output_type = "string"

The forward method looks up a theme by category and returns a fallback message when no match exists[1]:

    def forward(self, category: str):
        themes = {
            "classic heroes": "Justice League Gala: Guests come dressed as their favorite DC heroes with themed cocktails like 'The Kryptonite Punch'.",
            "villain masquerade": "Gotham Rogues' Ball: A mysterious masquerade where guests dress as classic Batman villains.",
            "futuristic Gotham": "Neo-Gotham Night: A cyberpunk-style party inspired by Batman Beyond, with neon decorations and futuristic gadgets."
        }

        return themes.get(category.lower(), "Themed party idea not found. Try 'classic heroes', 'villain masquerade', or 'futuristic Gotham'.")

To use it, create an instance and pass it to the agent[1]:

# Instantiate the tool
party_theme_tool = SuperheroPartyThemeTool()
agent = CodeAgent(tools=[party_theme_tool], model=InferenceClientModel())

# Run the agent to generate a party theme idea
result = agent.run(
    "What would be a good superhero party idea for a 'villain masquerade' theme?"
)

Built-in tools

smolagents includes pre-built tools that you can inject straight into an agent. They are PythonInterpreterTool, FinalAnswerTool, UserInputTool, DuckDuckGoSearchTool, GoogleSearchTool and VisitWebpageTool[1]. Add them to the tools list the same way you would add a custom tool.

Sharing and importing tools

A custom tool can be uploaded to your Hugging Face account with push_to_hub()[1]. Replace the placeholder username and token in the example with your own before running it:

party_theme_tool.push_to_hub("{your_username}/party_theme_tool", token="<YOUR_HUGGINGFACEHUB_API_TOKEN>")

In the other direction, load_tool() imports a tool that another user has shared on the Hub[1]. The example below loads a text-to-image tool and gives it to an agent:

from smolagents import load_tool, CodeAgent, InferenceClientModel

image_generation_tool = load_tool(
    "m-ric/text-to-image",
    trust_remote_code=True
)

agent = CodeAgent(
    tools=[image_generation_tool],
    model=InferenceClientModel()
)

agent.run("Generate an image of a luxurious superhero-themed party at Wayne Manor with made-up superheros.")

trust_remote_code=True lets the tool run code that is stored in its repository, so only load tools from authors you trust.

Importing a Hugging Face Space as a tool

Tool.from_space() turns a Hugging Face Space into a tool[1]. The connection goes through the Space's Gradio backend using the gradio_client package, so install that package with pip if it is missing[1]. The example below uses an image generation Space and gives the agent a prompt to improve before generating an image[1]:

from smolagents import CodeAgent, InferenceClientModel, Tool

image_generation_tool = Tool.from_space(
    "black-forest-labs/FLUX.1-schnell",
    name="image_generator",
    description="Generate an image from a prompt"
)

model = InferenceClientModel("Qwen/Qwen2.5-Coder-32B-Instruct")

agent = CodeAgent(tools=[image_generation_tool], model=model)

agent.run(
    "Improve this prompt, then generate an image of it.",
    additional_args={'user_prompt': 'A grand superhero-themed party at Wayne Manor, with Alfred overseeing a luxurious gala'}
)

Using LangChain tools

Tool.from_langchain() loads a LangChain tool into a smolagents workflow[1]. Install the LangChain integration first[1]:

pip install -U langchain-community

Search tools such as SerpAPITool need a SerpAPI key. The example sets it through the SERPAPI_API_KEY environment variable[1]:

os.environ['SERPAPI_API_KEY'] = '...'

The following snippet loads a SerpAPI tool and gives it to a CodeAgent. It uses a model object named model, which must be created beforehand[1]:

from langchain.agents import load_tools
from smolagents import CodeAgent, InferenceClientModel, Tool

search_tool = Tool.from_langchain(load_tools(["serpapi"])[0])

agent = CodeAgent(tools=[search_tool], model=model)

agent.run("Search for luxury entertainment ideas for a superhero-themed event, such as live performances and interactive experiences.")

Connecting to MCP servers

smolagents can also import tools from MCP servers. MCP servers are listed on glama.ai and smithery.ai, which together offer hundreds of them[1]. Install the MCP integration first[1]:

pip install "smolagents[mcp]"

The next example loads the tools of an MCP server into a ToolCollection and runs an agent inside a with block. The server is started with uvx and the pubmedmcp package[1]:

import os
from smolagents import ToolCollection, CodeAgent
from mcp import StdioServerParameters
from smolagents import InferenceClientModel


model = InferenceClientModel("Qwen/Qwen2.5-Coder-32B-Instruct")


server_parameters = StdioServerParameters(
    command="uvx",
    args=["--quiet", "pubmedmcp@0.1.3"],
    env={"UV_PYTHON": "3.12", **os.environ},
)

with ToolCollection.from_mcp(server_parameters, trust_remote_code=True) as tool_collection:
    agent = CodeAgent(tools=[*tool_collection.tools], model=model, add_base_tools=True)
    agent.run("Please find a remedy for hangover.")

MCP itself is covered in a separate free course[1].

Next steps

The smolagents tools tutorial covers more patterns[2]. For a deeper introduction to MCP, the free MCP course is the place to start[1].

Adapted from the Tools lesson in the smolagents unit (Unit 2) of Hugging Face's open-source *Agents Course*[1], released under the Apache-2.0 License.

Sources

  1. 1
    ToolsHugging Face agents-course (Apache-2.0)
  2. 2
    Tools TutorialHugging Face

Cite this page: Custom tools in smolagents. TellWorld, https://www.tellworld.net/practice/practice-smolagents-tools. Updated 2026-11-14

Related news

View all