search
HomeTechnology peripheralsAIBuilding Custom Tools for AI Agents Using smolagents

LLMs are revolutionizing various fields, moving beyond web-based chatbots to integrate into enterprises and government. A significant advancement is the creation of custom tools for AI agents using smolagents, expanding their capabilities. smolagents empowers AI agents to utilize tools, perform actions within defined environments, and even interact with other agents.

This approach enhances LLM-powered AI systems' autonomy, improving their reliability for complete end-to-end task execution.

Learning Objectives

  • Understand AI agents, their distinction from traditional LLMs, and their role in modern AI applications with custom tools.
  • Explore why AI agents require custom tools for real-time data access, action execution, and improved decision-making.
  • Gain practical experience in integrating and deploying AI agents using smolagents for real-world scenarios.
  • Learn to create and integrate custom tools for enhanced AI agent functionality using smolagents.
  • Master hosting and interacting with an AI agent utilizing your custom tools, creating a more interactive and intelligent chatbot experience.

*This article is part of the***Data Science Blogathon.

Table of contents

  • Prerequisites
  • Understanding Agents in Generative AI
  • Agent Workflow
  • Components of an AI Agent
  • The Necessity of Tools
  • The smolagents Library
  • Our Codebase
  • Building Our First Tool
  • Final Step: Deployment
  • Summary
  • Frequently Asked Questions

Prerequisites

This tutorial targets intermediate developers and data professionals familiar with basic LLMs. The following is assumed:

  • Intermediate Python programming skills.
  • Basic LLM usage in code.
  • Familiarity with the GenAI ecosystem.
  • Fundamental understanding of the Hugging Face platform and the transformers library in Python.

Further recommended background for optimal learning:

  • Experience with LLM libraries like LangChain or Ollama.
  • Basic Machine Learning theory knowledge.
  • API usage and problem-solving with API responses.

Understanding Agents in Generative AI

Consider ChatGPT: it answers questions, writes code, and more. This capability extends to task completion—you provide a request, and it executes the entire task.

For example, an LLM can search the web and reason; combining these, it can create a travel itinerary. You might ask: "Plan a Himachal Pradesh vacation from April 1st to 7th, focusing on snow, skiing, ropeways, and green landscapes. Find the cheapest flights from Kolkata."

The AI would then compare flight costs, suggest locations, and find hotels, demonstrating an agentic approach in AI.

Agent Workflow

An agent uses an LLM that interacts with the external world solely through text.

Building Custom Tools for AI Agents Using smolagents

The agent receives input as text, reasons using language, and outputs text. Tools are crucial here, providing values the agent uses to generate its textual response. Actions can range from market transactions to image generation.

Building Custom Tools for AI Agents Using smolagents

The workflow is: Understand -> Reason -> Interact, or more broadly: Thought -> Action -> Observation.

Components of an AI Agent

An AI agent comprises:

  • The agent's "brain" (an LLM like llama3, phi4, or GPT4).
  • External tools the agent can invoke (APIs, other agents, calculators, etc.).

smolagents lets you create any Python function with an LLM tuned for function calling. Our example will include tools for dog facts, timezone retrieval, and image generation, using a Qwen LLM.

The Necessity of Tools

LLMs are no longer just text-completion tools. They're components in larger systems, often needing input from non-Generative AI parts.

Building Custom Tools for AI Agents Using smolagents

Tools bridge the gap between GenAI and other system components. LLMs have limitations:

  • Knowledge cut-off dates.
  • Hallucinations.
  • Unpredictable refusal to answer.
  • Suboptimal web search choices.

Deterministic tools address these issues.

The smolagents Library

smolagents (Hugging Face) is a framework for building agents. Unlike some libraries that output JSON, smolagents directly outputs Python code, improving efficiency.

Our Codebase

The GitHub repository contains:

  • Gradio_UI.py: Gradio UI code for user interaction.
  • agent.json: Agent configuration.
  • requirements.txt: Project dependencies.
  • prompts.yaml: Example prompts and responses (using Jinja templating).
  • app.py: The core application logic.

Building Our First Tool

We'll use a dog facts API (https://www.php.cn/link/0feaf58e2a12936c84c2510541b6e75a). To make a Python function usable by the AI agent:

  • Use the @tool decorator.
  • Write a clear docstring.
  • Add type annotations.
  • Ensure a clear return value.
  • Include ample comments.
@tool
def get_amazing_dog_fact()-> str:
    """Fetches a random dog fact from a public API."""
    # ... (API call and error handling) ...

A timezone tool:

@tool
def get_current_time_in_timezone(timezone: str) -> str:
    """Gets the current time in a specified timezone."""
    # ... (timezone handling) ...

An image generation tool can also be integrated:

image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)

The Qwen2.5-Coder-32B-Instruct model is used (requires application for access):

model = HfApiModel(
    max_tokens=2096,
    temperature=0.5,
    model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
    # ...
)

Prompts are loaded from prompts.yaml. The agent is created:

agent = CodeAgent(
    model=model,
    tools=[get_amazing_dog_fact, get_current_time_in_timezone, image_generation_tool],
    # ...
)

The tools argument lists the available functions.

Final Step: Deployment

The agent can be deployed on Hugging Face Spaces.

Summary

AI agents enhance LLM capabilities through tool integration, increasing autonomy and enabling complex task completion. smolagents simplifies agent creation, and custom tools extend functionality beyond standard LLMs. Deployment on platforms like Hugging Face Spaces facilitates easy sharing and interaction.

Frequently Asked Questions

Q1. What is an AI agent? An AI agent is an LLM-powered system interacting with tools to perform tasks.

Q2. Why are custom tools needed? They enable real-time data access, command execution, and actions beyond LLM capabilities.

Q3. What is smolagents? A Hugging Face framework for creating AI agents using custom tools.

Q4. How to create custom tools? Define functions, decorate with @tool, and integrate into the agent.

Q5. Where to deploy? Platforms like Hugging Face Spaces.

(Note: Images are assumed to be included as in the original input.)

The above is the detailed content of Building Custom Tools for AI Agents Using smolagents. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How to Build an Intelligent FAQ Chatbot Using Agentic RAGHow to Build an Intelligent FAQ Chatbot Using Agentic RAGMay 07, 2025 am 11:28 AM

AI agents are now a part of enterprises big and small. From filling forms at hospitals and checking legal documents to analyzing video footage and handling customer support – we have AI agents for all kinds of tasks. Compan

From Panic To Power: What Leaders Must Learn In The AI AgeFrom Panic To Power: What Leaders Must Learn In The AI AgeMay 07, 2025 am 11:26 AM

Life is good. Predictable, too—just the way your analytical mind prefers it. You only breezed into the office today to finish up some last-minute paperwork. Right after that you’re taking your partner and kids for a well-deserved vacation to sunny H

Why Convergence-Of-Evidence That Predicts AGI Will Outdo Scientific Consensus By AI ExpertsWhy Convergence-Of-Evidence That Predicts AGI Will Outdo Scientific Consensus By AI ExpertsMay 07, 2025 am 11:24 AM

But scientific consensus has its hiccups and gotchas, and perhaps a more prudent approach would be via the use of convergence-of-evidence, also known as consilience. Let’s talk about it. This analysis of an innovative AI breakthrough is part of my

The Studio Ghibli Dilemma – Copyright In The Age Of Generative AIThe Studio Ghibli Dilemma – Copyright In The Age Of Generative AIMay 07, 2025 am 11:19 AM

Neither OpenAI nor Studio Ghibli responded to requests for comment for this story. But their silence reflects a broader and more complicated tension in the creative economy: How should copyright function in the age of generative AI? With tools like

MuleSoft Formulates Mix For Galvanized Agentic AI ConnectionsMuleSoft Formulates Mix For Galvanized Agentic AI ConnectionsMay 07, 2025 am 11:18 AM

Both concrete and software can be galvanized for robust performance where needed. Both can be stress tested, both can suffer from fissures and cracks over time, both can be broken down and refactored into a “new build”, the production of both feature

OpenAI Reportedly Strikes $3 Billion Deal To Buy WindsurfOpenAI Reportedly Strikes $3 Billion Deal To Buy WindsurfMay 07, 2025 am 11:16 AM

However, a lot of the reporting stops at a very surface level. If you’re trying to figure out what Windsurf is all about, you might or might not get what you want from the syndicated content that shows up at the top of the Google Search Engine Resul

Mandatory AI Education For All U.S. Kids? 250-Plus CEOs Say YesMandatory AI Education For All U.S. Kids? 250-Plus CEOs Say YesMay 07, 2025 am 11:15 AM

Key Facts Leaders signing the open letter include CEOs of such high-profile companies as Adobe, Accenture, AMD, American Airlines, Blue Origin, Cognizant, Dell, Dropbox, IBM, LinkedIn, Lyft, Microsoft, Salesforce, Uber, Yahoo and Zoom.

Our Complacency Crisis: Navigating AI DeceptionOur Complacency Crisis: Navigating AI DeceptionMay 07, 2025 am 11:09 AM

That scenario is no longer speculative fiction. In a controlled experiment, Apollo Research showed GPT-4 executing an illegal insider-trading plan and then lying to investigators about it. The episode is a vivid reminder that two curves are rising to

See all articles

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 Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment