Transformers Agents is an experimental API which is subject to change at any time. Results returned by the agents can vary as the APIs or underlying models are prone to change.
To learn more about agents and tools make sure to read the introductory guide. This page contains the API docs for the underlying classes.
We provide two types of agents, based on the main Agent class:
( tools: typing.Union[typing.List[transformers.agents.tools.Tool], transformers.agents.agents.Toolbox] llm_engine: typing.Callable = None system_prompt: typing.Optional[str] = None tool_description_template: typing.Optional[str] = None additional_args: typing.Dict = {} max_iterations: int = 6 tool_parser: typing.Optional[typing.Callable] = None add_base_tools: bool = False verbose: int = 0 grammar: typing.Optional[typing.Dict[str, str]] = None managed_agents: typing.Optional[typing.List] = None step_callbacks: typing.Optional[typing.List[typing.Callable]] = None monitor_metrics: bool = True )
( tool_name: str arguments: typing.Dict[str, str] )
Execute tool with the provided input and returns the result. This method replaces arguments with the actual values from the state if they refer to state variables.
( llm_output: str split_token: str )
Parse action from the LLM output
To be implemented in the child class
Reads past llm_outputs, actions, and observations or errors from the logs into a series of messages that can be used as input to the LLM.
( tools: typing.List[transformers.agents.tools.Tool] llm_engine: typing.Optional[typing.Callable] = None system_prompt: typing.Optional[str] = None tool_description_template: typing.Optional[str] = None grammar: typing.Optional[typing.Dict[str, str]] = None additional_authorized_imports: typing.Optional[typing.List[str]] = None **kwargs )
A class for an agent that solves the given task using a single block of code. It plans all its actions, then executes all in one shot.
Override this method if you want to change the way the code is
cleaned in the run
method.
( task: str return_generated_code: bool = False **kwargs )
Runs the agent for the given task.
( tools: typing.List[transformers.agents.tools.Tool] llm_engine: typing.Optional[typing.Callable] = None system_prompt: typing.Optional[str] = None tool_description_template: typing.Optional[str] = None grammar: typing.Optional[typing.Dict[str, str]] = None plan_type: typing.Optional[str] = None planning_interval: typing.Optional[int] = None **kwargs )
This agent that solves the given task step by step, using the ReAct framework: While the objective is not reached, the agent will perform a cycle of thinking and acting. The action will be parsed from the LLM output: it consists in calls to tools from the toolbox, with arguments chosen by the LLM engine.
Runs the agent in direct mode, returning outputs only at the end: should be launched only in the run
method.
( task is_first_step: bool = False iteration: int = None )
Used periodically by the agent to plan the next steps to reach the objective.
This method provides a final answer to the task, based on the logs of the agent’s interactions.
( task: str stream: bool = False reset: bool = True **kwargs )
Runs the agent for the given task.
Runs the agent in streaming mode, yielding steps as they are executed: should be launched only in the run
method.
( tools: typing.List[transformers.agents.tools.Tool] llm_engine: typing.Optional[typing.Callable] = None system_prompt: typing.Optional[str] = None tool_description_template: typing.Optional[str] = None grammar: typing.Optional[typing.Dict[str, str]] = None planning_interval: typing.Optional[int] = None **kwargs )
This agent that solves the given task step by step, using the ReAct framework: While the objective is not reached, the agent will perform a cycle of thinking and acting. The tool calls will be formulated by the LLM in JSON format, then parsed and executed.
Perform one step in the ReAct framework: the agent thinks, acts, and observes the result. The errors are raised here, they are caught and logged in the run() method.
( tools: typing.List[transformers.agents.tools.Tool] llm_engine: typing.Optional[typing.Callable] = None system_prompt: typing.Optional[str] = None tool_description_template: typing.Optional[str] = None grammar: typing.Optional[typing.Dict[str, str]] = None additional_authorized_imports: typing.Optional[typing.List[str]] = None planning_interval: typing.Optional[int] = None **kwargs )
This agent that solves the given task step by step, using the ReAct framework: While the objective is not reached, the agent will perform a cycle of thinking and acting. The tool calls will be formulated by the LLM in code format, then parsed and executed.
Perform one step in the ReAct framework: the agent thinks, acts, and observes the result. The errors are raised here, they are caught and logged in the run() method.
( agent name description additional_prompting = None provide_run_summary = False )
( task_or_repo_id model_repo_id = None token = None **kwargs )
Parameters
str
) —
The task for which to load the tool or a repo ID of a tool on the Hub. Tasks implemented in Transformers
are:
"document_question_answering"
"image_question_answering"
"speech_to_text"
"text_to_speech"
"translation"
str
, optional) —
Use this argument to use a different model than the default one for the tool you selected. str
, optional) —
The token to identify you on hf.co. If unset, will use the token generated when running huggingface-cli login
(stored in ~/.huggingface
). cache_dir
, revision
, subfolder
) will be used when downloading the files for your tool, and the others
will be passed along to its init. Main function to quickly load a tool, be it on the Hub or in the Transformers library.
Loading a tool means that you’ll download the tool and execute it locally. ALWAYS inspect the tool you’re downloading before loading it within your runtime, as you would do when installing a package using pip/npm/apt.
( tool_function: typing.Callable )
Converts a function into an instance of a Tool subclass.
A base class for the functions used by the agent. Subclass this and implement the __call__
method as well as the
following class attributes:
str
) — A short description of what your tool does, the inputs it expects and the output(s) it
will return. For instance ‘This is a tool that downloads a file from a url
. It takes the url
as input, and
returns the text contained in the file’.str
) — A performative name that will be used for your tool in the prompt to the agent. For instance
"text-classifier"
or "image_generator"
.Dict[str, Dict[str, Union[str, type]]]
) — The dict of modalities expected for the inputs.
It has one type
key and a description
key.
This is used by launch_gradio_demo
or to make a nice space from your tool, and also can be used in the generated
description for your tool.type
) — The type of the tool output. This is used by launch_gradio_demo
or to make a nice space from your tool, and also can be used in the generated description for your tool.You can also override the method setup() if your tool as an expensive operation to perform before being usable (such as loading a model). setup() will be called the first time you use your tool, but not at instantiation.
Creates a Tool from a gradio tool.
( repo_id: str token: typing.Optional[str] = None **kwargs )
Parameters
str
) —
The name of the repo on the Hub where your tool is defined. str
, optional) —
The token to identify you on hf.co. If unset, will use the token generated when running
huggingface-cli login
(stored in ~/.huggingface
). cache_dir
, revision
, subfolder
) will be used when downloading the files for your tool, and the
others will be passed along to its init. Loads a tool defined on the Hub.
Loading a tool from the Hub means that you’ll download the tool and execute it locally. ALWAYS inspect the tool you’re downloading before loading it within your runtime, as you would do when installing a package using pip/npm/apt.
Creates a Tool from a langchain tool.
( space_id: str name: str description: str api_name: typing.Optional[str] = None token: typing.Optional[str] = None ) → Tool
Parameters
str
) —
The id of the Space on the Hub. str
) —
The name of the tool. str
) —
The description of the tool. str
, optional) —
The specific api_name to use, if the space has several tabs. If not precised, will default to the first available api. str
, optional) —
Add your token to access private spaces or increase your GPU quotas. Returns
The Space, as a tool.
Creates a Tool from a Space given its id on the Hub.
( repo_id: str commit_message: str = 'Upload tool' private: typing.Optional[bool] = None token: typing.Union[bool, str, NoneType] = None create_pr: bool = False )
Parameters
str
) —
The name of the repository you want to push your tool to. It should contain your organization name when
pushing to a given organization. str
, optional, defaults to "Upload tool"
) —
Message to commit while pushing. bool
, optional) —
Whether to make the repo private. If None
(default), the repo will be public unless the organization’s default is private. This value is ignored if the repo already exists. bool
or str
, optional) —
The token to use as HTTP bearer authorization for remote files. If unset, will use the token generated
when running huggingface-cli login
(stored in ~/.huggingface
). bool
, optional, defaults to False
) —
Whether or not to create a PR with the uploaded files or directly commit. Upload the tool to the Hub.
For this method to work properly, your tool must have been defined in a separate module (not __main__
).
( output_dir )
Saves the relevant code files for your tool so it can be pushed to the Hub. This will copy the code of your
tool in output_dir
as well as autogenerate:
tool_config.json
app.py
file so that your tool can be converted to a spacerequirements.txt
containing the names of the module used by your tool (as detected when inspecting its
code)You should only use this method to save tools that are defined in a separate module (not __main__
).
Overwrite this method here for any operation that is expensive and needs to be executed before you start using your tool. Such as loading a big model.
( tools: typing.List[transformers.agents.tools.Tool] add_base_tools: bool = False )
The toolbox contains all tools that the agent can perform operations with, as well as a few methods to manage them.
Adds a tool to the toolbox
Clears the toolbox
( tool_name: str )
Removes a tool from the toolbox
( tool_description_template: str = None )
Returns the description of all tools in the toolbox
Updates a tool in the toolbox according to its name.
( model = None pre_processor = None post_processor = None device = None device_map = None model_kwargs = None token = None **hub_kwargs )
Parameters
str
or PreTrainedModel, optional) —
The name of the checkpoint to use for the model, or the instantiated model. If unset, will default to the
value of the class attribute default_checkpoint
. str
or Any
, optional) —
The name of the checkpoint to use for the pre-processor, or the instantiated pre-processor (can be a
tokenizer, an image processor, a feature extractor or a processor). Will default to the value of model
if
unset. str
or Any
, optional) —
The name of the checkpoint to use for the post-processor, or the instantiated pre-processor (can be a
tokenizer, an image processor, a feature extractor or a processor). Will default to the pre_processor
if
unset. int
, str
or torch.device
, optional) —
The device on which to execute the model. Will default to any accelerator available (GPU, MPS etc…), the
CPU otherwise. str
or dict
, optional) —
If passed along, will be used to instantiate the model. dict
, optional) —
Any keyword argument to send to the model instantiation. str
, optional) —
The token to use as HTTP bearer authorization for remote files. If unset, will use the token generated when
running huggingface-cli login
(stored in ~/.huggingface
). A Tool tailored towards Transformer models. On top of the class attributes of the base class Tool, you will need to specify:
type
) — The class to use to load the model in this tool.str
) — The default checkpoint that should be used when the user doesn’t specify one.type
, optional, defaults to AutoProcessor) — The class to use to load the
pre-processortype
, optional, defaults to AutoProcessor) — The class to use to load the
post-processor (when different from the pre-processor).Uses the post_processor
to decode the model output.
Uses the pre_processor
to prepare the inputs for the model
.
Sends the inputs through the model
.
Instantiates the pre_processor
, model
and post_processor
if necessary.
( tool_class: Tool )
Launches a gradio demo for a tool. The corresponding tool class needs to properly implement the class attributes
inputs
and output_type
.
Runs an agent with the given task and streams the messages from the agent as gradio ChatMessages.
( collection_slug: str token: typing.Optional[str] = None )
Tool collections enable loading all Spaces from a collection in order to be added to the agent’s toolbox.
[!NOTE] Only Spaces will be fetched, so you can feel free to add models and datasets to your collection if you’d like for this collection to showcase them.
Example:
>>> from transformers import ToolCollection, ReactCodeAgent
>>> image_tool_collection = ToolCollection(collection_slug="huggingface-tools/diffusion-tools-6630bb19a942c2306a2cdb6f")
>>> agent = ReactCodeAgent(tools=[*image_tool_collection.tools], add_base_tools=True)
>>> agent.run("Please draw me a picture of rivers and lakes.")
You’re free to create and use your own engines to be usable by the Agents framework. These engines have the following specification:
List[Dict[str, str]]
) and return a string.stop_sequences
For convenience, we have added a TransformersEngine
that implements the points above, taking a pre-initialized Pipeline
as input.
>>> from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, TransformersEngine
>>> model_name = "HuggingFaceTB/SmolLM-135M-Instruct"
>>> tokenizer = AutoTokenizer.from_pretrained(model_name)
>>> model = AutoModelForCausalLM.from_pretrained(model_name)
>>> pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
>>> engine = TransformersEngine(pipe)
>>> engine([{"role": "user", "content": "Ok!"}], stop_sequences=["great"])
"What a "
( pipeline: Pipeline model_id: typing.Optional[str] = None )
This engine uses a pre-initialized local text-generation pipeline.
The HfApiEngine
is an engine that wraps an HF Inference API client for the execution of the LLM.
>>> from transformers import HfApiEngine
>>> messages = [
... {"role": "user", "content": "Hello, how are you?"},
... {"role": "assistant", "content": "I'm doing great. How can I help you today?"},
... {"role": "user", "content": "No need to help, take it easy."},
... ]
>>> HfApiEngine()(messages, stop_sequences=["conversation"])
"That's very kind of you to say! It's always nice to have a relaxed "
( model: str = 'meta-llama/Meta-Llama-3.1-8B-Instruct' token: typing.Optional[str] = None max_tokens: typing.Optional[int] = 1500 timeout: typing.Optional[int] = 120 )
Parameters
str
, optional, defaults to "meta-llama/Meta-Llama-3.1-8B-Instruct"
) —
The Hugging Face model ID to be used for inference. This can be a path or model identifier from the Hugging Face model hub. str
, optional) —
Token used by the Hugging Face API for authentication.
If not provided, the class will use the token stored in the Hugging Face CLI configuration. int
, optional, defaults to 1500) —
The maximum number of tokens allowed in the output. int
, optional, defaults to 120) —
Timeout for the API request, in seconds. Raises
ValueError
ValueError
—
If the model name is not provided.A class to interact with Hugging Face’s Inference API for language model interaction.
This engine allows you to communicate with Hugging Face’s models using the Inference API. It can be used in both serverless mode or with a dedicated endpoint, supporting features like stop sequences and grammar customization.
Agents can handle any type of object in-between tools; tools, being completely multimodal, can accept and return text, image, audio, video, among other types. In order to increase compatibility between tools, as well as to correctly render these returns in ipython (jupyter, colab, ipython notebooks, …), we implement wrapper classes around these types.
The wrapped objects should continue behaving as initially; a text object should still behave as a string, an image
object should still behave as a PIL.Image
.
These types have three specific purposes:
to_raw
on the type should return the underlying objectto_string
on the type should return the object as a string: that can be the string in case of an AgentText
but will be the path of the serialized version of the object in other instancesText type returned by the agent. Behaves as a string.
Image type returned by the agent. Behaves as a PIL.Image.
( output_bytes format **params )
Saves the image to a file.
Returns the “raw” version of that object. In the case of an AgentImage, it is a PIL.Image.
Returns the stringified version of that object. In the case of an AgentImage, it is a path to the serialized version of the image.
Audio type returned by the agent.
Returns the “raw” version of that object. It is a torch.Tensor
object.
Returns the stringified version of that object. In the case of an AgentAudio, it is a path to the serialized version of the audio.