Home > Technology peripherals > AI > Hugging Face's Smolagents: A Guide With Examples

Hugging Face's Smolagents: A Guide With Examples

Jennifer Aniston
Release: 2025-03-01 09:51:11
Original
330 people have browsed it

Hugging Face's smolagents: A streamlined Python library for building AI agents

This blog post introduces smolagents, a new Python library from Hugging Face that simplifies AI agent development. We'll explore its benefits and walk through a demo project.

What is smolagents?

Hugging Face describes smolagents as a straightforward library enabling language model agents. But why are specialized libraries needed for agent creation?

Agents leverage LLMs to dynamically solve tasks by interacting with their environment, planning, and executing actions using a defined toolkit. While building these agents isn't impossible from scratch, it requires developing numerous components to ensure efficient resource usage (avoiding excessive API calls and execution time). Agentic frameworks streamline this process.

Common criticisms of AI agent frameworks include excessive abstraction layers (leading to rigidity and debugging difficulties) and a focus on rigid workflows rather than dynamic collaboration. Smolagents addresses these concerns:

  • Minimal abstraction layers.
  • Code-based actions: Agents define actions using Python code snippets (distinct from agents that generate code).
  • Seamless Hugging Face integration: Works well with the Hub and Transformers library, supporting various models (including some requiring a Pro subscription) and models from OpenAI, Anthropic, etc.
  • Easy custom tool creation: Defining custom tools is as simple as writing a Python function.

Let's see if smolagents lives up to its promise of plug-and-play AI agent development.

Demo Project: Retrieving the Top-Upvoted Hugging Face Daily Paper

This demo uses smolagents to retrieve the most upvoted paper from the Hugging Face Daily Papers page. We'll build custom tools and observe their interaction.

Hugging Face's Smolagents: A Guide With Examples

Daily Papers: A valuable resource for keeping up with recent research.

Setting up smolagents

Installation is simple:

pip install smolagents
Copy after login
Copy after login

A Hugging Face token is required.

Building Custom Tools

While smolagents offers built-in tools (e.g., DuckDuckGoSearchTool), creating custom tools is equally straightforward. Our demo uses four tools:

  1. get_hugging_face_top_daily_paper: Retrieves the title of the top daily paper.
  2. get_paper_id_by_title: Obtains the paper ID using its title.
  3. download_paper_by_id: Downloads the paper from arXiv using its ID.
  4. read_pdf_file: Reads the downloaded PDF file.

Effective tool design is crucial for agent success. To ensure clarity:

  • Use descriptive function names.
  • Employ type hints for inputs and outputs.
  • Include detailed docstrings explaining the tool's purpose.

Here's the get_hugging_face_top_daily_paper tool example:

pip install smolagents
Copy after login
Copy after login

The other tools (get_paper_id_by_title, download_paper_by_id, read_pdf_file) are similarly defined (using huggingface_hub, arxiv, and pypdf respectively), following the same best practices.

Running the Agent

We'll use the Qwen2.5-Coder-32B-Instruct model (free to use):

from smolagents import tool
import requests
from bs4 import BeautifulSoup
import json

@tool
def get_hugging_face_top_daily_paper() -> str:
    """
    Retrieves the most upvoted paper from Hugging Face daily papers.
    Returns the paper's title.
    """
    try:
      url = "<https:>"  # URL to Hugging Face Daily Papers
      response = requests.get(url)
      response.raise_for_status()
      soup = BeautifulSoup(response.content, "html.parser")
      containers = soup.find_all('div', class_='SVELTE_HYDRATER contents')
      top_paper = ""
      for container in containers:
          data_props = container.get('data-props', '')
          if data_props:
              try:
                  json_data = json.loads(data_props.replace('"', '"'))
                  if 'dailyPapers' in json_data:
                      top_paper = json_data['dailyPapers'][0]['title']
              except json.JSONDecodeError:
                  continue
      return top_paper
    except requests.exceptions.RequestException as e:
      print(f"Error fetching HTML: {e}")
      return None</https:>
Copy after login

The agent's step-by-step output demonstrates its tool usage. (Screenshots of the agent's output in steps 0, 1, 2, and 3 would be included here, showing the agent's process and final summary).

Conclusion

Smolagents offers a lightweight, controllable framework for AI agent development. Its Hugging Face integration provides access to a wide range of models and tools. While additional built-in tools would be beneficial, smolagents effectively delivers on its core promise. For developers seeking a straightforward, uncluttered agent framework, smolagents is worth exploring.

(Links to the Introduction to AI Agents, Understanding AI Agents, Smolagents documentation, and Smolagents repository would be included here.)

The above is the detailed content of Hugging Face's Smolagents: A Guide With Examples. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template