页面简介
We’re on a journey to advance and democratize artificial intelligence through open source and open science.
正文摘录
smolagents documentation Agents - Guided tour smolagents 🏡 View all docsAWS Trainium & InferentiaAccelerateBitsandbytesCLIChat UIDataset viewerDatasetsDeploying on AWSDiffusersGoogle CloudGoogle TPUsGradioHubHub Python LibraryHuggingface.jsInference Endpoints (dedicated)Inference ProvidersKernelsLeRobotLeaderboardsLightevalMicrosoft AzureOpenEnvOptimumPEFTReachy MiniSafetensorsSentence TransformersTRLTasksText Embeddings InferenceTokenizersTrackioTransformersTransformers.jsXetsmolagentstimm Search documentation mainv1.26.0v1.25.0v1.24.0v1.23.0v1.22.0v1.21.2v1.20.0v1.19.0v1.18.0v1.17.0v1.16.1v1.15.0v1.14.0v1.13.0v1.12.0v1.11.0v1.10.0v1.9.2v1.8.1v1.7.0v1.6.0v1.5.1v1.4.1v1.3.0v1.2.2v1.1.0v0.1.3 ENHIKOZH Join the Hugging Face community and get access to the augmented documentation experience Collaborate on models, datasets and Spaces Faster examples with accelerated inference Switch between documentation themes Sign Up to get started Copy page 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. Choosing an agent type: CodeAgent or ToolCallingAgent smolagents comes with two agent classes: CodeAgent and ToolCallingAgent, which represent two different paradigms for how agents interact with tools. The key difference lies in how actions are specified and executed: code generation vs structured tool calling. CodeAgent generates tool calls as Python code snippets. The code is executed either locally (potentially unsecure) or in a secure sandbox. Tools are exposed as Python functions (via bindings). Example of tool call: Copied result = search_docs("What is the capital of France?") print(result) Strengths: Highly expressive: Allows for complex logic and control flow and can combine tools, loop, transform, reason. Flexible: No need to predefine every possible action, can dynamically generate new actions/tools. Emergent reasoning: Ideal for multi-step problems or dynamic logic. Limitations Risk of errors: Must handle syntax errors, exceptions. Less predictable: More prone to unexpected or unsafe outputs. Requires secure execution environment. ToolCallingAgent writes tool calls as structured JSON. This is the common format used in many frameworks (OpenAI API), allowing for structured tool interactions without code execution. Tools are defined with a JSON schema: name, description, parameter types, etc. Example of tool call: Copied { "tool_call": { "name": "search_docs", "arguments": { "query": "What is the capital of France?" } } } Strengths: Reliable: Less prone to hallucination, outputs are structured and validated. Safe: Arguments are strictly validated, no risk of arbitrary code running. Interoperable: Easy to map to external APIs or services. Limitations: Low expressivity: Can’t easily combine or transform results dynamically, or perform complex logic or control flow. Inflexible: Must define all possible actions in advance, limited to predefined tools. No code synthesis: Limited to tool capabilities. When to use which agent type: Use CodeAgent when: You need reasoning, chaining, or dynamic composition. Tools are functions that can be combined (e.g., parsing + math + querying). Your agent is a problem solver or programmer. Use ToolCallingAgent when: You have simple, atomic tools (e.g., call an API, fetch a document). You want high reliability and clear validation. Your agent is like a dispatcher or controller. CodeAgent CodeAgent generates Python code snippets to perform actions and solve tasks. By default, the Python code 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: Copied model = InferenceClientModel() agent = CodeAgent(tools=[], model=model, additional_authorized_imports=['requests', 'bs4']) agent.run("Could you get me the title of the page at url 'https://huggingface.co/blog'?") Additionally, as an extra security layer, access to submodule is forbidden by default, unless explicitly authorized within the import list. For instance, to access the numpy.random submodule, you need to add 'numpy.random' to the additional_authorized_imports list. This could also be authorized by using numpy.*, which will allow numpy as well as any subpackage like numpy.random and its own subpackages. 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 Blaxel, E2B, or Docker instead of a local Python interpreter. For Blaxel, first set the BL_API_KEY and BL_WORKSPACE environment variables and then pass executor_type="blaxel" upon agent initialization. For E2B, first set the E2B_API_KEY environment variable and then pass executor_type="e2b". For Docker, pass executor_type="docker". Learn more about code execution in this tutorial. ToolCallingAgent ToolCallingAgent outputs JSON tool calls, which is the common format used in many frameworks (OpenAI API), allowing for structured tool interactions without code execution. We utilize the built-in WebSearchTool (from the smolagents toolkit extra, which will be described in more detail later) to enable our agent to perform web searches. It works much in the same way like CodeAgent, of course without additional_authorized_imports since it doesn’t execute code: Copied from smolagents import ToolCallingAgent, WebSearchTool agent = ToolCallingAgent(tools=[WebSearchTool()], model=model) agent.run("Could you get me the title of the page at url 'https://huggingface.co/blog'?") Using the CLI You can quickly get started with smolagents using the command line interface: Copied # Run with direct prompt and options smolagent "Plan a trip to Tokyo, Kyoto and Osaka between Mar 28 and Apr 7." --model-type "InferenceClientModel" --model-id "Qwen/Qwen2.5-Coder-32B-Instruct" --imports "pandas numpy" --tools "web_search" # Run in interactive mode: launches when no prompt is provided, will guide you through argument selection smolagent 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 using transformers. InferenceClientModel leverages a huggingface_hub.InferenceClient under the hood and supports all Inference Providers on the Hub: Cerebras, Cohere, Fal, Fireworks, HF-Inference, Hyperbolic, Nebius, Novita, Replicate, SambaNova, Together, and more. LiteLLMModel similarly lets you call 100+ different models and providers through LiteLLM! AzureOpenAIModel allows you to use OpenAI models deployed in Azure. AmazonBedrockModel allows you to use Amazon Bedrock in AWS. MLXModel creates a mlx-lm pipeline to run inference on your local machine. tools, a list of Tools 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 your tools list by defining the optional argument add_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, Amazon Bedrock, or mlx-lm. All model classes support passing additional keyword arguments (like temperature, max_tokens, top_p, etc.) directly at instantiation time. These parameters are automatically forwarded to the underlying model’s completion calls, allowing you to configure model behavior such as creativity, response length, and sampling strategies. Inference Providers Local Transformers Model OpenAI or Anthropic API Ollama Azure OpenAI Amazon Bedrock mlx-lm Inference Providers need a HF_TOKEN to authenticate, but a free HF account already comes with included credits. Upgrade to PRO to raise your included credits. 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 InferenceClientModel. You can get your token from your settings page Copied from smolagents import CodeAgent, InferenceClientModel model_id = "meta-llama/Llama-3.3-70B-Instruct" model = InferenceClientModel(model_id=model_id, token="<YOUR_HUGGINGFACEHUB_API_TOKEN>") # You can choose to not pass any model_id to InferenceClientModel to use a default model # you can also specify a particular provider e.g. provider="together" or provider="sambanova" agent = CodeAgent(tools=[], model=model, add_base_tools=True) agent.run( "Could you give me the 118th number in the Fibonacci sequence?", ) Model parameter management When initializing models, you can pass keyword arguments that will be forwarded as completion parameters to the underlying model API during inference. For fine-grained control over parameter handling, the REMOVE_PARAMETER sentinel value allows you to explicitly exclude parameters that might otherwise be set by default or passed through elsewhere: Copied from smolagents import OpenAIModel, REMOVE_PARAMETER # Remove "stop" parameter model = OpenAIModel( model_id="gpt-5", stop=REMOVE_PARAMETER, # Ensures "stop" is not included in API calls temperature=0.7 ) agent = CodeAgent(tools=[], model=model,