TellWorldAI World Archive
Ask中文

Home›Practice›Practice

Practice

Multi-agent systems with smolagents

A single agent slows down and runs up token costs when one task holds many steps. This guide splits the work between a manager agent and a web agent in smolagents, then adds a check on the final answer.

Who this is for and what you will be able to do

If a single smolagents agent is becoming slow, expensive or unreliable on a task with many steps, this guide shows one way to split the work. By the end you should be able to define a tool, build a baseline agent, move web research into a separate managed agent, put a manager agent in charge, and add a check that runs on the final answer.

Why use several agents

A multi-agent system lets specialized agents work together on a complex task. Compared with one agent doing everything, this structure improves modularity, scalability and robustness[1]. Tasks are distributed among agents that have different capabilities, and the agents can be combined to write Python code, call external tools and run web searches[1].

A typical setup has three roles: a manager agent that delegates tasks, a code interpreter agent that runs code, and a web search agent that retrieves information[1]. A multi-agent RAG system follows the same pattern and might add a web agent, a retriever agent for knowledge bases and an image generation agent, all under an orchestrator[1].

The main reason to split is memory. Each agent keeps its own memory and stays focused on its core task. Since each step carries fewer input tokens, latency and cost go down[1].

The example task

The example asks for every Batman filming location in the world, the time it would take to fly cargo there from Gotham, and a map that colors each location by that travel time. It also asks for some supercar factories with the same travel time[1]. The task needs web search, page reading and some geographic calculation, so it is a good test of splitting work.

Preparation

Install the packages the example uses. The litellm extra provides the model connection, and the others support plotting[1]:

pip install 'smolagents[litellm]' plotly geopandas shapely kaleido -q

The example uses Together AI as its model provider. It is one of the inference providers available on the Hub[1].

For web search, GoogleSearchTool uses the Serper API. Set the SERPAPI_API_KEY environment variable and pass provider="serpapi", or set SERPER_API_KEY and pass provider=serper[1]. Without a Serp API key, you can fall back to DuckDuckGoSearchTool, but it has a rate limit[1].

Create the model with the code below[1]:

import os
from PIL import Image
from smolagents import CodeAgent, GoogleSearchTool, InferenceClientModel, VisitWebpageTool

model = InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct", provider="together")

Step 1: write a travel-time tool

The example needs a tool that estimates the cargo plane time between two points. It is declared with @tool and takes two (latitude, longitude) tuples, plus a cruising speed that defaults to 750 km/h[1]:

import math
from typing import Optional, Tuple

from smolagents import tool


@tool
def calculate_cargo_travel_time(
    origin_coords: Tuple[float, float],
    destination_coords: Tuple[float, float],
    cruising_speed_kmh: Optional[float] = 750.0,  # Average speed for cargo planes
) -> float:

The function computes the great-circle distance with the haversine formula. It then adds 10% to the distance for non-direct routes and air traffic control, and adds one hour for takeoff and landing[1]. The final part of the calculation looks like this[1]:

    # Add 10% to account for non-direct routes and air traffic controls
    actual_distance = distance * 1.1

    # Calculate flight time
    # Add 1 hour for takeoff and landing procedures
    flight_time = (actual_distance / cruising_speed_kmh) + 1.0

    # Format the results
    return round(flight_time, 2)

The fixed 10% and one-hour allowances are the tool's own modeling choices, not measured flight data. Treat the output as a rough estimate.

Step 2: build a single-agent baseline

First, one agent with the search, page-reading and travel-time tools gives a baseline report. The example authorizes the pandas import and allows 20 steps[1]:

agent = CodeAgent(
    model=model,
    tools=[GoogleSearchTool("serper"), VisitWebpageTool(), calculate_cargo_travel_time],
    additional_authorized_imports=["pandas"],
    max_steps=20,
)

For a more detailed report, the example turns on planning. Planning steps let the agent think ahead about its next moves, and it is enabled with a single attribute[1]:

agent.planning_interval = 4

This works for a small task, but the context window fills up quickly. If one agent must combine the results of a detailed search with another job, the run gets slower and token use and costs climb quickly[1]. That is the point where the example splits the work.

Step 3: move web research into a managed agent

The web agent gets its own name, a short description and its own tools[1]:

web_agent = CodeAgent(
    model=model,
    tools=[
        GoogleSearchTool(provider="serper"),
        VisitWebpageTool(),
        calculate_cargo_travel_time,
    ],
    name="web_agent",
    description="Browses the web to find information",
    verbosity_level=0,
    max_steps=10,
)

The manager is the stronger model in this setup. The example uses DeepSeek-R1 through Together AI. It lists the web agent in managed_agents, allows several plotting and data imports, and sets a planning interval of 5[1]:

manager_agent = CodeAgent(
    model=InferenceClientModel("deepseek-ai/DeepSeek-R1", provider="together", max_tokens=8096),
    tools=[calculate_cargo_travel_time],
    managed_agents=[web_agent],
    additional_authorized_imports=[
        "geopandas",
        "plotly",
        "shapely",
        "json",
        "pandas",
        "numpy",
    ],
    planning_interval=5,
    verbosity_level=2,
    final_answer_checks=[check_reasoning_and_plot],
    max_steps=15,
)

Before running it, manager_agent.visualize() prints the team's structure, including the authorized imports, the tools and the managed agents[1].

Step 4: check the final answer

A final_answer_checks function runs on the final answer. The example's check looks for the saved plot and asks a multimodal model to review it. It starts with this part[1]:

def check_reasoning_and_plot(final_answer, agent_memory):
    multimodal_model = OpenAIServerModel("gpt-4o", max_tokens=8096)
    filepath = "saved_map.png"
    assert os.path.exists(filepath), "Make sure to save the plot under saved_map.png!"

If the review output contains FAIL, the check raises an exception[1]:

    if "FAIL" in output:
        raise Exception(output)
    return True

The example's run prompt asks for at least six points, a map saved as saved_map.png, and a rule that strings should be printed, not processed with code[1]:

manager_agent.run("""
Find all Batman filming locations in the world, calculate the time to transfer via cargo plane to here (we're in Gotham, 40.7128° N, 74.0060° W).
Also give me some supercar factories with the same cargo plane transfer time. You need at least 6 points in total.
Represent this as spatial map of the world, with the locations represented as scatter points with a color that depends on the travel time, and save it to saved_map.png!

Here's an example of how to plot and return a map:
import plotly.express as px
df = px.data.carshare()
fig = px.scatter_map(df, lat="centroid_lat", lon="centroid_lon", text="name", color="peak_hour", size=100,
     color_continuous_scale=px.colors.sequential.Magma, size_max=15, zoom=1)
fig.show()
fig.write_image("saved_image.png")
final_answer(fig)

Never try to process strings using code: when you have a string to read, just print it and you'll see it.
""")

The figure can be read back afterwards from the manager's state with manager_agent.python_executor.state["fig"][1].

Limits and common problems

  • The planning and checks add calls and cost. Use them when the task needs them.
  • Search quotas matter. DuckDuckGo's rate limit can stop a long run, and Serper needs its own key[1].
  • Estimates are estimates. The travel-time formula uses fixed allowances, so check the numbers against a real source before you rely on them.

Next steps

The smolagents documentation has a dedicated Multi-Agent Systems page[2]. For a longer walk-through of a multi-agent RAG system, see the step-by-step recipe[1].

Adapted from the Multi-Agent Systems lesson in the smolagents unit (Unit 2) of Hugging Face's open-source *Agents Course*[1], released under the Apache-2.0 License.

Sources

  1. 1
    Multi-Agent SystemsHugging Face agents-course (Apache-2.0)
  2. 2

Cite this page: Multi-agent systems with smolagents. TellWorld, https://www.tellworld.net/practice/practice-smolagents-multi-agent. Updated 2026-11-14

Related news

View all