Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/main/smolagents_doc/en/guided_tour.ipynb
Views: 2935
Agents - Guided tour
In this guided visit, you will learn how to build an agent, how to run it, and how to customize it to make it work better for your use-case.
Building your agent
To initialize a minimal agent, you need at least these two arguments:
model
, a text-generation model to power your agent - because the agent is different from a simple LLM, it is a system that uses a LLM as its engine. You can use any of these options:TransformersModel takes a pre-initialized
transformers
pipeline to run inference on your local machine usingtransformers
.HfApiModel leverages a
huggingface_hub.InferenceClient
under the hood and supports all Inference Providers on the Hub.LiteLLMModel similarly lets you call 100+ different models and providers through LiteLLM!
AzureOpenAIServerModel allows you to use OpenAI models deployed in Azure.
MLXModel creates a mlx-lm pipeline to run inference on your local machine.
tools
, a list ofTools
that the agent can use to solve the task. It can be an empty list. You can also add the default toolbox on top of yourtools
list by defining the optional argumentadd_base_tools=True
.
Once you have these two arguments, tools
and model
, you can create an agent and run it. You can use any LLM you'd like, either through Inference Providers, transformers, ollama, LiteLLM, Azure OpenAI, or mlx-lm.
HF Inference API is free to use without a token, but then it will have a rate limit.
To access gated models or rise your rate limits with a PRO account, you need to set the environment variable HF_TOKEN
or pass token
variable upon initialization of HfApiModel
. You can get your token from your settings page
To use LiteLLMModel
, you need to set the environment variable ANTHROPIC_API_KEY
or OPENAI_API_KEY
, or pass api_key
variable upon initialization.
To connect to Azure OpenAI, you can either use AzureOpenAIServerModel
directly, or use LiteLLMModel
and configure it accordingly.
To initialize an instance of AzureOpenAIServerModel
, you need to pass your model deployment name and then either pass the azure_endpoint
, api_key
, and api_version
arguments, or set the environment variables AZURE_OPENAI_ENDPOINT
, AZURE_OPENAI_API_KEY
, and OPENAI_API_VERSION
.
Similarly, you can configure LiteLLMModel
to connect to Azure OpenAI as follows:
pass your model deployment name as
model_id
, and make sure to prefix it withazure/
make sure to set the environment variable
AZURE_API_VERSION
either pass the
api_base
andapi_key
arguments, or set the environment variablesAZURE_API_KEY
, andAZURE_API_BASE
CodeAgent and ToolCallingAgent
The CodeAgent is our default agent. It will write and execute python code snippets at each step.
By default, the execution is done in your local environment. This should be safe because the only functions that can be called are the tools you provided (especially if it's only tools by Hugging Face) and a set of predefined safe functions like print
or functions from the math
module, so you're already limited in what can be executed.
The Python interpreter also doesn't allow imports by default outside of a safe list, so all the most obvious attacks shouldn't be an issue. You can authorize additional imports by passing the authorized modules as a list of strings in argument additional_authorized_imports
upon initialization of your CodeAgent:
[!WARNING] The LLM can generate arbitrary code that will then be executed: do not add any unsafe imports!
The execution will stop at any code trying to perform an illegal operation or if there is a regular Python error with the code generated by the agent.
You can also use E2B code executor or Docker instead of a local Python interpreter. For E2B, first set the E2B_API_KEY
environment variable and then pass executor_type="e2b"
upon agent initialization. For Docker, pass executor_type="docker"
during initialization.
[!TIP] Learn more about code execution in this tutorial.
We also support the widely-used way of writing actions as JSON-like blobs: this is ToolCallingAgent, it works much in the same way like CodeAgent, of course without additional_authorized_imports
since it doesn't execute code:
Inspecting an agent run
Here are a few useful attributes to inspect what happened after a run:
agent.logs
stores the fine-grained logs of the agent. At every step of the agent's run, everything gets stored in a dictionary that then is appended toagent.logs
.Running
agent.write_memory_to_messages()
writes the agent's memory as list of chat messages for the Model to view. This method goes over each step of the log and only stores what it's interested in as a message: for instance, it will save the system prompt and task in separate messages, then for each step it will store the LLM output as a message, and the tool call output as another message. Use this if you want a higher-level view of what has happened - but not every log will be transcripted by this method.
Tools
A tool is an atomic function to be used by an agent. To be used by an LLM, it also needs a few attributes that constitute its API and will be used to describe to the LLM how to call this tool:
A name
A description
Input types and descriptions
An output type
You can for instance check the PythonInterpreterTool: it has a name, a description, input descriptions, an output type, and a forward
method to perform the action.
When the agent is initialized, the tool attributes are used to generate a tool description which is baked into the agent's system prompt. This lets the agent know which tools it can use and why.
Default toolbox
smolagents
comes with a default toolbox for empowering agents, that you can add to your agent upon initialization with argument add_base_tools = True
:
DuckDuckGo web search*: performs a web search using DuckDuckGo browser.
Python code interpreter: runs your LLM generated Python code in a secure environment. This tool will only be added to ToolCallingAgent if you initialize it with
add_base_tools=True
, since code-based agent can already natively execute Python codeTranscriber: a speech-to-text pipeline built on Whisper-Turbo that transcribes an audio to text.
You can manually use a tool by calling it with its arguments.
Create a new tool
You can create your own tool for use cases not covered by the default tools from Hugging Face. For example, let's create a tool that returns the most downloaded model for a given task from the Hub.
You'll start with the code below.
This code can quickly be converted into a tool, just by wrapping it in a function and adding the tool
decorator: This is not the only way to build the tool: you can directly define it as a subclass of Tool, which gives you more flexibility, for instance the possibility to initialize heavy class attributes.
Let's see how it works for both options:
The function needs:
A clear name. The name should be descriptive enough of what this tool does to help the LLM brain powering the agent. Since this tool returns the model with the most downloads for a task, let's name it
model_download_tool
.Type hints on both inputs and output
A description, that includes an 'Args:' part where each argument is described (without a type indication this time, it will be pulled from the type hint). Same as for the tool name, this description is an instruction manual for the LLM powering you agent, so do not neglect it. All these elements will be automatically baked into the agent's system prompt upon initialization: so strive to make them as clear as possible!
[!TIP] This definition format is the same as tool schemas used in
apply_chat_template
, the only difference is the addedtool
decorator: read more on our tool use API here. [removed]
The subclass needs the following attributes:
A clear
name
. The name should be descriptive enough of what this tool does to help the LLM brain powering the agent. Since this tool returns the model with the most downloads for a task, let's name itmodel_download_tool
.A
description
. Same as for thename
, this description is an instruction manual for the LLM powering you agent, so do not neglect it.Input types and descriptions
Output type All these attributes will be automatically baked into the agent's system prompt upon initialization: so strive to make them as clear as possible!
Then you can directly initialize your agent:
Multi-agents
Multi-agent systems have been introduced with Microsoft's framework Autogen.
In this type of framework, you have several agents working together to solve your task instead of only one. It empirically yields better performance on most benchmarks. The reason for this better performance is conceptually simple: for many tasks, rather than using a do-it-all system, you would prefer to specialize units on sub-tasks. Here, having agents with separate tool sets and memories allows to achieve efficient specialization. For instance, why fill the memory of the code generating agent with all the content of webpages visited by the web search agent? It's better to keep them separate.
You can easily build hierarchical multi-agent systems with smolagents
.
To do so, just ensure your agent has name
anddescription
attributes, which will then be embedded in the manager agent's system prompt to let it know how to call this managed agent, as we also do for tools. Then you can pass this managed agent in the parameter managed_agents upon initialization of the manager agent.
Here's an example of making an agent that managed a specific web search agent using our DuckDuckGoSearchTool:
[!TIP] For an in-depth example of an efficient multi-agent implementation, see how we pushed our multi-agent system to the top of the GAIA leaderboard.
Talk with your agent and visualize its thoughts in a cool Gradio interface
You can use GradioUI
to interactively submit tasks to your agent and observe its thought and execution process, here is an example:
Under the hood, when the user types a new answer, the agent is launched with agent.run(user_request, reset=False)
. The reset=False
flag means the agent's memory is not flushed before launching this new task, which lets the conversation go on.
You can also use this reset=False
argument to keep the conversation going in any other agentic application.
Next steps
Finally, when you've configured your agent to your needs, you can share it to the Hub!
Similarly, to load an agent that has been pushed to hub, if you trust the code from its tools, use:
For more in-depth usage, you will then want to check out our tutorials: