Generative AI

How to Build a Fully Autonomous Space Analysis Agent Using SmolAgents and the Qwen Model

In this tutorial, we walk through the process of creating an autonomous vehicle analysis agent using SmolAgents and the Qwen spatial model. We generate telemetry data, upload it to a custom tool, and allow our agent to infer, analyze, and visualize remedial risks without any external API calls. At each step of the implementation, we see how the agent interprets structured logs, applies logical filters, detects anomalies, and finally issues a clear visual warning to fleet managers. Check it out FULL CODES here.

print("⏳ Installing libraries... (approx 30-60s)")
!pip install smolagents transformers accelerate bitsandbytes ddgs matplotlib pandas -q


import os
import pandas as pd
import matplotlib.pyplot as plt
from smolagents import CodeAgent, Tool, TransformersModel

We install all the necessary libraries and import the basic modules we rely on to build our agent. Set up SmolAgents, Transformers, and basic data management tools to process telemetry and run the local model smoothly. In this section, we prepare our site and make sure everything loads correctly before moving forward. Check it out 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.")

We create a dataset of dummy ships that our agent will analyze later. We create a small but realistic set of telemetry fields, convert it to a DataFrame, and save it as a CSV file. Here, we establish the primary data source that drives the agent's reasoning and predictions. Check it out 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:
           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}"

We describe the FleetDataTool, which acts as a bridge between the agent and the underlying telemetry file. We give the agent the ability to load and inspect the CSV file to understand its structure. This tool becomes the basis for all subsequent analyzes performed by the model. Check it out 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.")


agent = CodeAgent(
   tools=[FleetDataTool()],
   model=model,
   add_base_tools=True
)


print("n🤖 Agent is analyzing fleet data... (Check the 'Agent' output below)n")


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)


print(f"n📝 FINAL REPORT: {response}")

We load the Qwen2.5 environment model and run our CodeAgent with a custom tool. We then design a detailed query that describes the thought steps we want the agent to follow and ultimately execute. This is where we watch the agent think, analyze, calculate, and even structure, with full autonomy. Check it out FULL CODES here.

if 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.")

We check if the agent has successfully saved the built maintenance chart and display it if available. We visualize the output directly from the notebook, allowing us to ensure that the agent has performed data analysis and planning correctly. This gives us a clean, interpretable result for every job.

In conclusion, we have built an intelligent end-to-end pipeline that allows a spatial model to automatically load data, assess fleet health, identify the most dangerous vehicle, and generate a diagnostic chart of potential insights. We demonstrate how easily we can extend this framework to real-world datasets, integrate complex tools, or add multi-step reasoning capabilities for safety, efficiency, or use cases for predictive maintenance. Finally, we appreciate the way SmolAgents enables us to create functional systems that run real code, think about real telemetry, and deliver data quickly.


Check it out FULL CODES here. Also, feel free to follow us Twitter and don't forget to join our 100k+ ML SubReddit and Subscribe to Our newspaper. Wait! are you on telegram? now you can join us on telegram too.


Michal Sutter is a data science expert with a Master of Science in Data Science from the University of Padova. With a strong foundation in statistical analysis, machine learning, and data engineering, Michal excels at turning complex data sets into actionable insights.

Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button