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

Hugging Face's Smolagents: A Guide With Examples

Mar 01, 2025 am 09:51 AM

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1668
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
10 Generative AI Coding Extensions in VS Code You Must Explore 10 Generative AI Coding Extensions in VS Code You Must Explore Apr 13, 2025 am 01:14 AM

Hey there, Coding ninja! What coding-related tasks do you have planned for the day? Before you dive further into this blog, I want you to think about all your coding-related woes—better list those down. Done? – Let&#8217

GPT-4o vs OpenAI o1: Is the New OpenAI Model Worth the Hype? GPT-4o vs OpenAI o1: Is the New OpenAI Model Worth the Hype? Apr 13, 2025 am 10:18 AM

Introduction OpenAI has released its new model based on the much-anticipated “strawberry” architecture. This innovative model, known as o1, enhances reasoning capabilities, allowing it to think through problems mor

Pixtral-12B: Mistral AI's First Multimodal Model - Analytics Vidhya Pixtral-12B: Mistral AI's First Multimodal Model - Analytics Vidhya Apr 13, 2025 am 11:20 AM

Introduction Mistral has released its very first multimodal model, namely the Pixtral-12B-2409. This model is built upon Mistral’s 12 Billion parameter, Nemo 12B. What sets this model apart? It can now take both images and tex

How to Add a Column in SQL? - Analytics Vidhya How to Add a Column in SQL? - Analytics Vidhya Apr 17, 2025 am 11:43 AM

SQL's ALTER TABLE Statement: Dynamically Adding Columns to Your Database In data management, SQL's adaptability is crucial. Need to adjust your database structure on the fly? The ALTER TABLE statement is your solution. This guide details adding colu

How to Build MultiModal AI Agents Using Agno Framework? How to Build MultiModal AI Agents Using Agno Framework? Apr 23, 2025 am 11:30 AM

While working on Agentic AI, developers often find themselves navigating the trade-offs between speed, flexibility, and resource efficiency. I have been exploring the Agentic AI framework and came across Agno (earlier it was Phi-

Beyond The Llama Drama: 4 New Benchmarks For Large Language Models Beyond The Llama Drama: 4 New Benchmarks For Large Language Models Apr 14, 2025 am 11:09 AM

Troubled Benchmarks: A Llama Case Study In early April 2025, Meta unveiled its Llama 4 suite of models, boasting impressive performance metrics that positioned them favorably against competitors like GPT-4o and Claude 3.5 Sonnet. Central to the launc

OpenAI Shifts Focus With GPT-4.1, Prioritizes Coding And Cost Efficiency OpenAI Shifts Focus With GPT-4.1, Prioritizes Coding And Cost Efficiency Apr 16, 2025 am 11:37 AM

The release includes three distinct models, GPT-4.1, GPT-4.1 mini and GPT-4.1 nano, signaling a move toward task-specific optimizations within the large language model landscape. These models are not immediately replacing user-facing interfaces like

How ADHD Games, Health Tools & AI Chatbots Are Transforming Global Health How ADHD Games, Health Tools & AI Chatbots Are Transforming Global Health Apr 14, 2025 am 11:27 AM

Can a video game ease anxiety, build focus, or support a child with ADHD? As healthcare challenges surge globally — especially among youth — innovators are turning to an unlikely tool: video games. Now one of the world’s largest entertainment indus

See all articles