This tutorial will walk you through creating an autonomous agent for fleet analysis using SmolAgents, a Qwen local model and SmolAgents. The agent can analyze maintenance risks, visualize them, and make decisions without having to use any APIs. The agent is shown at each stage of the implementation process, interpreting structured logs, applying logical filtering, detecting anomalies and producing a clear warning for fleet management. Click here to see the FULL CODES here.
print("⏳ Installing libraries... (approx 30-60s)")
Install!pip smolagents Transformers Accelerate Bitsandbytes Ddgs Matplotlib Pandas -q
Import os
import pandas as pd
Import matplotlib.pyplot into plt
CodeAgents, Tool and TransformersModel can be imported from Smolagents
Installation of all necessary libraries is done, and we import the modules that are needed to build our agent. SmolAgents and Transformers are installed, along with basic data handling tools, to run our local model and process the telemetry. We prepare the environment at this point and make sure everything is loaded correctly. Look at the FULL CODES here.
fleet_data = {
"truck_id": ["T-101", "T-102", "T-103", "T-104", "T-105"],
"driver": ["Ali", "Sara", "Mike", "Omar", "Jen"],
"avg_speed_kmh": [65, 70, 62, 85, 60],
"fuel_efficiency_kml": [3.2, 3.1, 3.3, 1.8, 3.4],
"engine_temp_c": [85, 88, 86, 105, 84],
"last_maintenance_days": [30, 45, 120, 200, 15]
}
df = pd.DataFrame(fleet_data)
df.to_csv("fleet_logs.csv", index=False)
print("✅ 'fleet_logs.csv' created.")
The dummy dataset is generated that will be analyzed by our agent. Then, we create a set of realistic telemetry values, turn it into a DataFrame and save it in a CSV. We now establish the data that is the basis for the agent’s reasoning and prediction. Look at the FULL CODES here.
Class FleetDataTool (Tool)
Name = "load_fleet_logs"
description = "Loads vehicle telemetry logs from 'fleet_logs.csv'. Returns the data summary."
inputs = {}
output_type = "string"
def forward(self):
try:
Read_csv = df"fleet_logs.csv")
Return f"Columns: {list(df.columns)}nData Sample:n{df.to_string()}"
The Exception is e.
Return f"Error loading logs: {e}"
FleetDataTool acts as a link between the agent’s telemetry data and the underlying file. To understand its structure, we give the agent access to the CSV. This tool is the basis for all the subsequent analysis that the model does. Look at the FULL CODES here.
print("⏳ Downloading & Loading Local Model (approx 60-90s)...")
model = TransformersModel(
model_id="Qwen/Qwen2.5-Coder-1.5B-Instruct",
device_map="auto",
max_new_tokens=2048
)
print("✅ Model loaded on GPU.")
CodeAgent = agent
tools=[FleetDataTool()],
model=model,
add_base_tools=True
)
print("n🤖 Agent is analyzing fleet data... (Check the 'Agent' output below)n")
Question """
1. The fleet logs must be loaded.
2. Find the truck with the worst fuel efficiency (lowest 'fuel_efficiency_kml').
3. If you are looking at a truck, see if its due for service (the threshold is usually 90 days).
4. Create a bar chart comparing the 'fuel_efficiency_kml' of ALL trucks.
5. The chart will show the trucks in GRAY and RED.
6. Save the chart as 'maintenance_alert.png'.
"""
response = agent.run(query)
print(f"n📝 FINAL REPORT: {response}")
The Qwen2.5 model is loaded and our CodeAgent initialized with the customized tool. Then we create a query that outlines the steps of reasoning the agent should follow, and then execute the entire process. We can now watch as the agent analyses, computes, and plots, all on its own. See the FULL CODES here.
If the os.path.exists."maintenance_alert.png"):
print("n📊 Displaying Generated Chart:")
img = Plt.imread"maintenance_alert.png")
plt.figure(figsize=(10, 5))
plt.imshow(img)
plt.axis('off')
plt.show()
else:
print("⚠️ No chart image found. Check the agent logs above.")
If the maintenance chart is available, we display the result if the agent has saved it successfully. Visualizing the output in the notebook allows us confirm the accuracy of the data analysis. We get a clear, readable result of the whole workflow.
We built a pipeline from end to end that allows a model in a particular location autonomously load the data, assess fleet health, determine which vehicle is at highest risk, and create a diagnostic chart with actionable insight. It is easy to extend the framework for real-world datasets. We can also integrate complex tools and add reasoning capability in multi-steps. SmolAgents enables us to build practical systems which execute code, analyze real data, and provide insights instantly.
Click here to find out more FULL CODES here. Also, feel free to follow us on Twitter Join our Facebook group! 100k+ ML SubReddit Subscribe Now our Newsletter. Wait! Are you using Telegram? now you can join us on telegram as well.

