You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: units/en/unit1/tools.mdx
+32-21
Original file line number
Diff line number
Diff line change
@@ -24,7 +24,7 @@ Here are some commonly used tools in AI agents:
24
24
25
25
Those are only examples, as you can in fact create a tool for any use case!
26
26
27
-
A good tool should be something that **complements the power of an LLM**.
27
+
A good tool should be something that **complements the power of an LLM**.
28
28
29
29
For instance, if you need to perform arithmetic, giving a **calculator tool** to your LLM will provide better results than relying on the native capabilities of the model.
30
30
@@ -140,18 +140,18 @@ We create a generic `Tool` class that we can reuse whenever we need to use a too
140
140
classTool:
141
141
"""
142
142
A class representing a reusable piece of code (Tool).
143
-
143
+
144
144
Attributes:
145
145
name (str): Name of the tool.
146
146
description (str): A textual description of what the tool does.
147
147
func (callable): The function this tool wraps.
148
148
arguments (list): A list of argument.
149
149
outputs (str or list): The return type(s) of the wrapped function.
150
150
"""
151
-
def__init__(self,
152
-
name: str,
153
-
description: str,
154
-
func: callable,
151
+
def__init__(self,
152
+
name: str,
153
+
description: str,
154
+
func: callable,
155
155
arguments: list,
156
156
outputs: str):
157
157
self.name = name
@@ -162,13 +162,13 @@ class Tool:
162
162
163
163
defto_string(self) -> str:
164
164
"""
165
-
Return a string representation of the tool,
165
+
Return a string representation of the tool,
166
166
including its name, description, arguments, and outputs.
@@ -282,6 +282,17 @@ The description is **injected** in the system prompt. Taking the example with wh
282
282
283
283
In the [Actions](actions) section, we will learn more about how an Agent can **Call** this tool we just created.
284
284
285
+
### Model Context Protocol (MCP): a unified tool interface
286
+
287
+
Model Context Protocol (MCP) is an **open protocol** that standardizes how applications **provide tools to LLMs**.
288
+
MCP provides:
289
+
290
+
- A growing list of pre-built integrations that your LLM can directly plug into
291
+
- The flexibility to switch between LLM providers and vendors
292
+
- Best practices for securing your data within your infrastructure
293
+
294
+
This means that **any framework implementing MCP can leverage tools defined within the protocol**, eliminating the need to reimplement the same tool interface for each framework.
295
+
285
296
---
286
297
287
298
Tools play a crucial role in enhancing the capabilities of AI agents.
Oftentimes, directly querying an API **can return an excessive amount of data**, some of which may be irrelevant, overflow the context window of the LLM, or unnecessarily increase the number of tokens that you are using.
As we explored in [unit 1](https://huggingface.co/learn/agents-course/unit1/tools), agents use tools to perform various actions. In `smolagents`, tools are treated as **functions that an LLM can call within an agent system**.
9
+
As we explored in [unit 1](https://huggingface.co/learn/agents-course/unit1/tools), agents use tools to perform various actions. In `smolagents`, tools are treated as **functions that an LLM can call within an agent system**.
10
10
11
-
To interact with a tool, the LLM needs an **interface description** with these key components:
11
+
To interact with a tool, the LLM needs an **interface description** with these key components:
12
12
13
13
-**Name**: What the tool is called
14
-
-**Tool description**: What the tool does
14
+
-**Tool description**: What the tool does
15
15
-**Input types and descriptions**: What arguments the tool accepts
16
16
-**Output type**: What the tool returns
17
17
@@ -30,19 +30,19 @@ Below, you can see an animation illustrating how a tool call is managed:
30
30
31
31
## Tool Creation Methods
32
32
33
-
In `smolagents`, tools can be defined in two ways:
33
+
In `smolagents`, tools can be defined in two ways:
34
34
1.**Using the `@tool` decorator** for simple function-based tools
35
-
2.**Creating a subclass of `Tool`** for more complex functionality
35
+
2.**Creating a subclass of `Tool`** for more complex functionality
36
36
37
-
### The `@tool` Decorator
37
+
### The `@tool` Decorator
38
38
39
-
The `@tool` decorator is the **recommended way to define simple tools**. Under the hood, smolagents will parse basic information about the function from Python. So if you name your function clearly and write a good docstring, it will be easier for the LLM to use.
39
+
The `@tool` decorator is the **recommended way to define simple tools**. Under the hood, smolagents will parse basic information about the function from Python. So if you name your function clearly and write a good docstring, it will be easier for the LLM to use.
40
40
41
-
Using this approach, we define a function with:
41
+
Using this approach, we define a function with:
42
42
43
-
-**A clear and descriptive function name** that helps the LLM understand its purpose.
44
-
-**Type hints for both inputs and outputs** to ensure proper usage.
45
-
-**A detailed description**, including an `Args:` section where each argument is explicitly described. These descriptions provide valuable context for the LLM, so it's important to write them carefully.
43
+
-**A clear and descriptive function name** that helps the LLM understand its purpose.
44
+
-**Type hints for both inputs and outputs** to ensure proper usage.
45
+
-**A detailed description**, including an `Args:` section where each argument is explicitly described. These descriptions provide valuable context for the LLM, so it's important to write them carefully.
46
46
47
47
#### Generating a tool that retrieves the highest-rated catering
48
48
@@ -52,7 +52,7 @@ Using this approach, we define a function with:
52
52
You can follow the code in <ahref="https://huggingface.co/agents-course/notebooks/blob/main/unit2/smolagents/tools.ipynb"target="_blank">this notebook</a> that you can run using Google Colab.
53
53
</Tip>
54
54
55
-
Let's imagine that Alfred has already decided on the menu for the party, but now he needs help preparing food for such a large number of guests. To do so, he would like to hire a catering service and needs to identify the highest-rated options available. Alfred can leverage a tool to search for the best catering services in his area.
55
+
Let's imagine that Alfred has already decided on the menu for the party, but now he needs help preparing food for such a large number of guests. To do so, he would like to hire a catering service and needs to identify the highest-rated options available. Alfred can leverage a tool to search for the best catering services in his area.
56
56
57
57
Below is an example of how Alfred can use the `@tool` decorator to make this happen:
58
58
@@ -64,7 +64,7 @@ from smolagents import CodeAgent, HfApiModel, tool
64
64
defcatering_service_tool(query: str) -> str:
65
65
"""
66
66
This tool returns the highest-rated catering service in Gotham City.
67
-
67
+
68
68
Args:
69
69
query: A search term for finding catering services.
# Find the highest rated catering service (simulating search query filtering)
79
79
best_service =max(services, key=services.get)
80
-
80
+
81
81
return best_service
82
82
83
83
@@ -91,21 +91,21 @@ result = agent.run(
91
91
print(result) # Output: Gotham Catering Co.
92
92
```
93
93
94
-
### Defining a Tool as a Python Class
94
+
### Defining a Tool as a Python Class
95
95
96
-
This approach involves creating a subclass of [`Tool`](https://huggingface.co/docs/smolagents/v1.8.1/en/reference/tools#smolagents.Tool). For complex tools, we can implement a class instead of a Python function. The class wraps the function with metadata that helps the LLM understand how to use it effectively. In this class, we define:
96
+
This approach involves creating a subclass of [`Tool`](https://huggingface.co/docs/smolagents/v1.8.1/en/reference/tools#smolagents.Tool). For complex tools, we can implement a class instead of a Python function. The class wraps the function with metadata that helps the LLM understand how to use it effectively. In this class, we define:
97
97
98
-
-`name`: The tool's name.
99
-
-`description`: A description used to populate the agent's system prompt.
100
-
-`inputs`: A dictionary with keys `type` and `description`, providing information to help the Python interpreter process inputs.
101
-
-`output_type`: Specifies the expected output type.
98
+
-`name`: The tool's name.
99
+
-`description`: A description used to populate the agent's system prompt.
100
+
-`inputs`: A dictionary with keys `type` and `description`, providing information to help the Python interpreter process inputs.
101
+
-`output_type`: Specifies the expected output type.
102
102
-`forward`: The method containing the inference logic to execute.
103
103
104
104
Below, we can see an example of a tool built using `Tool` and how to integrate it within a `CodeAgent`.
105
105
106
106
#### Generating a tool to generate ideas about the superhero-themed party
107
107
108
-
Alfred's party at the mansion is a **superhero-themed event**, but he needs some creative ideas to make it truly special. As a fantastic host, he wants to surprise the guests with a unique theme.
108
+
Alfred's party at the mansion is a **superhero-themed event**, but he needs some creative ideas to make it truly special. As a fantastic host, he wants to surprise the guests with a unique theme.
109
109
110
110
To do this, he can use an agent that generates superhero-themed party ideas based on a given category. This way, Alfred can find the perfect party theme to wow his guests.
111
111
@@ -117,14 +117,14 @@ class SuperheroPartyThemeTool(Tool):
117
117
description ="""
118
118
This tool suggests creative superhero-themed party ideas based on a category.
119
119
It returns a unique party theme idea."""
120
-
120
+
121
121
inputs = {
122
122
"category": {
123
123
"type": "string",
124
124
"description": "The type of superhero party (e.g., 'classic heroes', 'villain masquerade', 'futuristic Gotham').",
125
125
}
126
126
}
127
-
127
+
128
128
output_type ="string"
129
129
130
130
defforward(self, category: str):
@@ -133,7 +133,7 @@ class SuperheroPartyThemeTool(Tool):
133
133
"villain masquerade": "Gotham Rogues' Ball: A mysterious masquerade where guests dress as classic Batman villains.",
134
134
"futuristic Gotham": "Neo-Gotham Night: A cyberpunk-style party inspired by Batman Beyond, with neon decorations and futuristic gadgets."
135
135
}
136
-
136
+
137
137
return themes.get(category.lower(), "Themed party idea not found. Try 'classic heroes', 'villain masquerade', or 'futuristic Gotham'.")
138
138
139
139
# Instantiate the tool
@@ -150,34 +150,34 @@ print(result) # Output: "Gotham Rogues' Ball: A mysterious masquerade where gue
150
150
151
151
With this tool, Alfred will be the ultimate super host, impressing his guests with a superhero-themed party they won't forget! 🦸♂️🦸♀️
152
152
153
-
## Default Toolbox
153
+
## Default Toolbox
154
154
155
-
`smolagents` comes with a set of pre-built tools that can be directly injected into your agent. The [default toolbox](https://huggingface.co/docs/smolagents/guided_tour?build-a-tool=Decorate+a+function+with+%40tool#default-toolbox) includes:
155
+
`smolagents` comes with a set of pre-built tools that can be directly injected into your agent. The [default toolbox](https://huggingface.co/docs/smolagents/guided_tour?build-a-tool=Decorate+a+function+with+%40tool#default-toolbox) includes:
156
156
157
-
-**PythonInterpreterTool**
158
-
-**FinalAnswerTool**
159
-
-**UserInputTool**
160
-
-**DuckDuckGoSearchTool**
161
-
-**GoogleSearchTool**
162
-
-**VisitWebpageTool**
157
+
-**PythonInterpreterTool**
158
+
-**FinalAnswerTool**
159
+
-**UserInputTool**
160
+
-**DuckDuckGoSearchTool**
161
+
-**GoogleSearchTool**
162
+
-**VisitWebpageTool**
163
163
164
164
Alfred could use various tools to ensure a flawless party at Wayne Manor:
165
165
166
-
- First, he could use the `DuckDuckGoSearchTool` to find creative superhero-themed party ideas.
166
+
- First, he could use the `DuckDuckGoSearchTool` to find creative superhero-themed party ideas.
167
167
168
-
- For catering, he'd rely on the `GoogleSearchTool` to find the highest-rated services in Gotham.
168
+
- For catering, he'd rely on the `GoogleSearchTool` to find the highest-rated services in Gotham.
169
169
170
-
- To manage seating arrangements, Alfred could run calculations with the `PythonInterpreterTool`.
170
+
- To manage seating arrangements, Alfred could run calculations with the `PythonInterpreterTool`.
171
171
172
-
- Once everything is gathered, he'd compile the plan using the `FinalAnswerTool`.
172
+
- Once everything is gathered, he'd compile the plan using the `FinalAnswerTool`.
173
173
174
174
With these tools, Alfred guarantees the party is both exceptional and seamless. 🦇💡
175
175
176
176
## Sharing and Importing Tools
177
177
178
-
One of the most powerful features of **smolagents** is its ability to share custom tools on the Hub and seamlessly integrate tools created by the community. This includes connecting with **HF Spaces** and **LangChain tools**, significantly enhancing Alfred's ability to orchestrate an unforgettable party at Wayne Manor. 🎭
178
+
One of the most powerful features of **smolagents** is its ability to share custom tools on the Hub and seamlessly integrate tools created by the community. This includes connecting with **HF Spaces** and **LangChain tools**, significantly enhancing Alfred's ability to orchestrate an unforgettable party at Wayne Manor. 🎭
179
179
180
-
With these integrations, Alfred can tap into advanced event-planning tools—whether it's adjusting the lighting for the perfect ambiance, curating the ideal playlist for the party, or coordinating with Gotham's finest caterers.
180
+
With these integrations, Alfred can tap into advanced event-planning tools—whether it's adjusting the lighting for the perfect ambiance, curating the ideal playlist for the party, or coordinating with Gotham's finest caterers.
181
181
182
182
Here are examples showcasing how these functionalities can elevate the party experience:
You can easily import tools created by other users using the `load_tool()` function. For example, Alfred might want to generate a promotional image for the party using AI. Instead of building a tool from scratch, he can leverage a predefined one from the community:
196
+
You can easily import tools created by other users using the `load_tool()` function. For example, Alfred might want to generate a promotional image for the party using AI. Instead of building a tool from scratch, he can leverage a predefined one from the community:
197
197
198
198
```python
199
199
from smolagents import load_tool, CodeAgent, HfApiModel
@@ -213,7 +213,7 @@ agent.run("Generate an image of a luxurious superhero-themed party at Wayne Mano
213
213
214
214
### Importing a Hugging Face Space as a Tool
215
215
216
-
You can also import a HF Space as a tool using `Tool.from_space()`. This opens up possibilities for integrating with thousands of spaces from the community for tasks from image generation to data analysis.
216
+
You can also import a HF Space as a tool using `Tool.from_space()`. This opens up possibilities for integrating with thousands of spaces from the community for tasks from image generation to data analysis.
217
217
218
218
The tool will connect with the spaces Gradio backend using the `gradio_client`, so make sure to install it via `pip` if you don't have it already.
219
219
@@ -233,7 +233,7 @@ model = HfApiModel("Qwen/Qwen2.5-Coder-32B-Instruct")
agent.run("Search for luxury entertainment ideas for a superhero-themed event, such as live performances and interactive experiences.")
261
261
```
262
262
263
+
### Importing a tool collection from any MCP server
264
+
265
+
`smolagents` also allows importing tools from the hundreds of MCP servers available on [glama.ai](https://glama.ai/mcp/servers) or [smithery.ai](https://smithery.ai).
266
+
267
+
<details>
268
+
<summary>Install mcp client</summary>
269
+
270
+
We first need to install the `mcp` integration for `smolagents`.
271
+
272
+
```bash
273
+
pip install "smolagents[mcp]"
274
+
```
275
+
</details>
276
+
277
+
The MCP servers tools can be loaded in a ToolCollection object as follow:
With this setup, Alfred can quickly discover luxurious entertainment options, ensuring Gotham's elite guests have an unforgettable experience. This tool helps him curate the perfect superhero-themed event for Wayne Manor! 🎉
0 commit comments