Exploring SmolAgents
Part 2 of Demystifying AI Agents In Part 1 of this series, I covered the conceptual foundations of AI agents. In this part, I introduce SmolAgents, a lightweight agent framework, and demonstrate its use by implementing the stock trading scenario from Part 1. SmolAgents Framework SmolAgents is a lightweight AI agent framework developed by Hugging Face. It is designed to help developers build and deploy agents with minimal code. To observe or act on the environment, the LLM (large language model) powering an agent can request tool calls in two ways: By generating JSON, which the agent then parses, or By generating executable Python code, which the agent executes using a python interpreter. Research shows that the second method is more flexible and modular. SmolAgents supports both approaches; in this blog, I’ll focus on an implementation that uses executable Python code. Stock Trading Agent Let’s briefly recap the stock trading agent introduced in Part 1. This agent performs user-requested tasks using: An LLM as the planning and reasoning engine A set of tools for: Looking up stock tickers Fetching current holdings Getting stock prices Selling stocks For example, a user might issue this instruction: Check the stock price of Nvidia. If it is above $150, sell 80% of the stock that I hold. Part 1 walked through an agent execution for the above user instruction in terms of the think-act-observe loop. Now, let's see how to implement it using SmolAgents. SmolAgent Implementation of the Stock Trading Agent We begin by importing the required components from the smolagents library: from smolagents import CodeAgent, OpenAIServerModel, tool Next, we implement the four tools needed by our stock trading agent. These tools use hardcoded values (for demonstration purposes); in a real-world scenario, they would interface with external APIs. @tool def lookup_ticker(name: str) -> str: """ Looks up the stock ticker symbol for a given company name. """ if name.lower() == "nvidia": return "NVDA" else: return "Unknown" @tool def get_my_stock_holdings() -> dict: """ Returns the user's current stock holdings. """ return { "NVDA": 100, "MSFT": 50, "TSLA": 20, } @tool def get_stock_price(ticker: str) -> float: """ Returns the current price of the specified stock ticker. """ if ticker == "NVDA": return 293.46 elif ticker == "MSFT": return 225.23 else: raise ValueError(f"Unknown stock symbol: {ticker}") @tool def sell_stock(ticker: str, quantity: int) -> str: """ Sells a specified quantity of a given stock. """ print(f"Sold {quantity} shares of {ticker}") return "Success" Now we create the stock trading agent using the CodeAgent class: model = OpenAIServerModel( model_id="gpt-4o", api_key="" ) stock_agent = CodeAgent( tools=[lookup_ticker, get_my_stock_holdings, get_stock_price, sell_stock], model=model, planning_interval=3, ) Note that we're using CodeAgent, which relies on executable Python code for tool invocation. To run the agent: agent.run( "Check the stock price of Nvidia. If it is above $150, sell 80 percent of the stock that I hold." ) Results Here’s what happens when the agent executes. Observe how these align with each of the think-act-observe iterations I covered in Part 1. The agent analyzes the instruction and creates a plan: It calls the lookup_ticker tool to find Nvidia’s stock symbol: It calls get_stock_price to check Nvidia’s current price: It retrieves the user’s stock holdings via get_my_stock_holdings: Since Nvidia's stock price is above $150, it sells 80% of the holdings: Finally, it confirms the stock sale to the user: A few things to note in the above executions: All tool calls are implemented using Python, providing flexibility and reliability. Since the calculations are handled in Python, their accuracy is ensured. Unlike LLMs, which can sometimes make errors in mathematical calculations, Python executes exact calculations using its built-in logic and libraries. Conclusion In this second part of the Demystifying AI Agents series, we demonstrated how to implement a simple stock trading agent using the SmolAgents framework. This hands-on example showcases how lightweight frameworks like SmolAgents can help developers quickly build and experiment with autonomous agents using LLMs. In the next part, we’ll explore how CodeGate can be used in conjunction with SmolAgents for security and privacy. References: Artificial Intelligence: A Modern Approach, Russell & Norvig, Chapter 3 https://people.eecs.berkeley.edu/~russell/aima1e/chapter02.pdf Smolagents: https://huggingface.co/blog/smolagents Codegate: https://codegate.ai/

Part 2 of Demystifying AI Agents
In Part 1 of this series, I covered the conceptual foundations of AI agents. In this part, I introduce SmolAgents, a lightweight agent framework, and demonstrate its use by implementing the stock trading scenario from Part 1.
SmolAgents Framework
SmolAgents is a lightweight AI agent framework developed by Hugging Face. It is designed to help developers build and deploy agents with minimal code.
To observe or act on the environment, the LLM (large language model) powering an agent can request tool calls in two ways:
- By generating JSON, which the agent then parses, or
- By generating executable Python code, which the agent executes using a python interpreter.
Research shows that the second method is more flexible and modular. SmolAgents supports both approaches; in this blog, I’ll focus on an implementation that uses executable Python code.
Stock Trading Agent
Let’s briefly recap the stock trading agent introduced in Part 1. This agent performs user-requested tasks using:
- An LLM as the planning and reasoning engine
- A set of tools for:
- Looking up stock tickers
- Fetching current holdings
- Getting stock prices
- Selling stocks
For example, a user might issue this instruction:
Check the stock price of Nvidia. If it is above $150, sell 80% of the stock that I hold.
Part 1 walked through an agent execution for the above user instruction in terms of the think-act-observe loop. Now, let's see how to implement it using SmolAgents.
SmolAgent Implementation of the Stock Trading Agent
We begin by importing the required components from the smolagents
library:
from smolagents import CodeAgent, OpenAIServerModel, tool
Next, we implement the four tools needed by our stock trading agent. These tools use hardcoded values (for demonstration purposes); in a real-world scenario, they would interface with external APIs.
@tool
def lookup_ticker(name: str) -> str:
"""
Looks up the stock ticker symbol for a given company name.
"""
if name.lower() == "nvidia":
return "NVDA"
else:
return "Unknown"
@tool
def get_my_stock_holdings() -> dict:
"""
Returns the user's current stock holdings.
"""
return {
"NVDA": 100,
"MSFT": 50,
"TSLA": 20,
}
@tool
def get_stock_price(ticker: str) -> float:
"""
Returns the current price of the specified stock ticker.
"""
if ticker == "NVDA":
return 293.46
elif ticker == "MSFT":
return 225.23
else:
raise ValueError(f"Unknown stock symbol: {ticker}")
@tool
def sell_stock(ticker: str, quantity: int) -> str:
"""
Sells a specified quantity of a given stock.
"""
print(f"Sold {quantity} shares of {ticker}")
return "Success"
Now we create the stock trading agent using the CodeAgent class:
model = OpenAIServerModel(
model_id="gpt-4o",
api_key=" "
)
stock_agent = CodeAgent(
tools=[lookup_ticker, get_my_stock_holdings, get_stock_price, sell_stock],
model=model,
planning_interval=3,
)
Note that we're using CodeAgent, which relies on executable Python code for tool invocation.
To run the agent:
agent.run(
"Check the stock price of Nvidia. If it is above $150, sell 80 percent of the stock that I hold."
)
Results
Here’s what happens when the agent executes. Observe how these align with each of the think-act-observe iterations I covered in Part 1.
It calls the lookup_ticker tool to find Nvidia’s stock symbol:
It retrieves the user’s stock holdings via get_my_stock_holdings:
Since Nvidia's stock price is above $150, it sells 80% of the holdings:
A few things to note in the above executions:
- All tool calls are implemented using Python, providing flexibility and reliability.
- Since the calculations are handled in Python, their accuracy is ensured. Unlike LLMs, which can sometimes make errors in mathematical calculations, Python executes exact calculations using its built-in logic and libraries.
Conclusion
In this second part of the Demystifying AI Agents series, we demonstrated how to implement a simple stock trading agent using the SmolAgents framework. This hands-on example showcases how lightweight frameworks like SmolAgents can help developers quickly build and experiment with autonomous agents using LLMs. In the next part, we’ll explore how CodeGate can be used in conjunction with SmolAgents for security and privacy.
References:
- Artificial Intelligence: A Modern Approach, Russell & Norvig, Chapter 3 https://people.eecs.berkeley.edu/~russell/aima1e/chapter02.pdf
- Smolagents: https://huggingface.co/blog/smolagents
- Codegate: https://codegate.ai/