Building an Autonomous Fleet Maintenance Analysis Agent
Learn to create a fleet-analysis agent using SmolAgents without external APIs.
Project Overview
In this tutorial, we walk through the process of creating a fully autonomous fleet-analysis agent using SmolAgents and a local Qwen model. We generate telemetry data, load it through a custom tool, and let our agent reason, analyze, and visualize maintenance risks without any external API calls. At each step of implementation, we see how the agent interprets structured logs, applies logical filters, detects anomalies, and finally produces a clear visual warning for fleet managers.
Setting Up Your Environment
We install all required libraries and import the core modules we rely on for building our agent. The setup includes SmolAgents, Transformers, and basic data-handling tools to process telemetry and run the local model smoothly.
print("<img src=\"https://s.w.org/images/core/emoji/16.0.1/72x72/23f3.png\" alt=\"⏳\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" /> Installing libraries... (approx 30-60s)")
!pip install smolagents transformers accelerate bitsandbytes ddgs matplotlib pandas -qGenerating Fleet Data
Next, we generate a realistic dummy dataset that our agent will analyze later.
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]
}\ndf = pd.DataFrame(fleet_data)
df.to_csv("fleet_logs.csv", index=False)
print("<img src=\"https://s.w.org/images/core/emoji/16.0.1/72x72/2705.png\" alt=\"✅\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" /> 'fleet_logs.csv' created.")Creating the FleetDataTool
We create the FleetDataTool, enabling the agent to load and inspect our telemetry file.
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:
df = pd.read_csv("fleet_logs.csv")
return f"Columns: {list(df.columns)}\nData Sample:\n{df.to_string()}"
except Exception as e:
return f"Error loading logs: {e}"Loading the Local Model
We load the Qwen2.5 local model and initialize our CodeAgent with the custom tool.
model = TransformersModel(
model_id="Qwen/Qwen2.5-Coder-1.5B-Instruct",
device_map="auto",
max_new_tokens=2048
)
agent = CodeAgent(
tools=[FleetDataTool()],
model=model,
add_base_tools=True
)Querying Fleet Data
We craft a detailed query for the agent to analyze the fleet data step-by-step.
query = """
1. Load the fleet logs.
2. Find the truck with the worst fuel efficiency (lowest 'fuel_efficiency_kml').
3. For that truck, check if it is overdue for maintenance (threshold is 90 days).
4. Create a bar chart comparing the 'fuel_efficiency_kml' of ALL trucks.
5. Highlight the worst truck in RED and others in GRAY on the chart.
6. Save the chart as 'maintenance_alert.png'.
"""
response = agent.run(query)Displaying Generated Results
We check whether the agent successfully saved the generated maintenance chart and display it if available.
if os.path.exists("maintenance_alert.png"):
print("<img src=\"https://s.w.org/images/core/emoji/16.0.1/72x72/1f4ca.png\" alt=\"📊\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" /> Displaying Generated Chart:")
img = plt.imread("maintenance_alert.png")
plt.figure(figsize=(10, 5))
plt.imshow(img)
plt.axis('off')
plt.show()
else:
print("<img src=\"https://s.w.org/images/core/emoji/16.0.1/72x72/26a0.png\" alt=\"⚠\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" /> No chart image found. Check the agent logs above.")Implications for Fleet Management
In this setup, we built an intelligent pipeline that enables a local model to autonomously analyze fleet health. This framework can be extended to real-world datasets and can integrate more sophisticated tools for predictive maintenance.
For in-depth reference and complete code, check out the FULL CODES here.
Сменить язык
Читать эту статью на русском