Connect Samsara to AI Agents: Automate Routing and Safety Coaching
Give your AI agent Samsara tools.
Connect Samsara to AI agents to automate fleet routing, DVIR defect triaging, and safety coaching. This guide covers fetching Samsara tools via Truto's API, binding them to LLMs, and handling strict rate limits.
In this guide
- 01Analyze the Samsara API
- 02Fetch Proxy Tools via API
- 03Bind Tools to the Agent Framework
- 04Implement Rate Limit Handling
- 05Execute Autonomous Workflows
The guide
A complete developer guide to connecting Samsara to AI agents. Learn how to fetch API tools, handle telematics rate limits, and automate fleet routing.
You want to connect Samsara to an AI agent so your system can autonomously track fleet telematics, orchestrate routing, and automate safety coaching. Here is exactly how to do it using Truto's /tools endpoint and SDK, bypassing the need to build and maintain a custom Samsara API integration from scratch.
Giving a Large Language Model (LLM) read and write access to your fleet operations instance is an engineering headache. You either spend weeks building, hosting, and maintaining a custom connector, or you use a managed infrastructure layer that handles the boilerplate for you. If your team uses ChatGPT, check out our guide on connecting Samsara to ChatGPT, or if you are building on Anthropic's models, read our guide on connecting Samsara to Claude. For developers building custom autonomous workflows, you need a programmatic way to fetch these tools and bind them to your agent framework.
This guide breaks down exactly how to fetch AI-ready tools for Samsara, bind them natively to an LLM using frameworks like LangChain, LangGraph, CrewAI, or the Vercel AI SDK, and execute complex fleet management workflows. For a deeper look at the architecture behind this approach, refer to our research on architecting AI agents and the SaaS integration bottleneck.
The Engineering Reality of the Samsara API
Giving an LLM access to external telematics data sounds simple in a prototype. You write a Node.js function that makes a fetch request and wrap it in an @tool decorator. In production against complex operational systems like Samsara, this approach collapses.
Samsara's API introduces several specific integration challenges. If you hardcode these interactions into your agent, you will spend your sprints writing defensive integration code instead of improving your model's reasoning.
The Telematics Data Volume Trap
Samsara acts as the central nervous system for physical operations. Endpoints like those returning vehicle stats or location histories yield massive, deeply nested JSON payloads containing GPS coordinates, engine states, and auxiliary inputs. Standard LLMs are easily overwhelmed by this sheer volume of data, blowing past context windows and increasing hallucination rates.
If you expose the raw Samsara API to an agent, the model will attempt to ingest entire paginated arrays of raw IoT telemetry. It will hallucinate cursor values and fail to parse the specific happenedAtTime ISO 8601 strings required for filtering.
Endpoint Fragmentation: Legacy vs. Beta vs. V1
Samsara's API is continuously evolving, resulting in a fragmented endpoint landscape. You have legacy endpoints (/v1/fleet/assets), standard endpoints (/fleet/vehicles), and beta streams (/fleet/safety-events/stream).
An AI agent cannot easily navigate this fragmentation. If the model reads outdated documentation during its training cutoff, it will repeatedly attempt to call deprecated legacy endpoints, causing persistent 404 Not Found or 400 Bad Request errors in your agent loop.
The Strict Rate Limiting Paradigm
Samsara enforces strict rate limits to protect its infrastructure from aggressive polling. This is a critical architectural consideration.
A factual note on how Truto handles this: Truto does not retry, throttle, or apply backoff on rate limit errors. When the upstream Samsara API returns an HTTP 429 (Too Many Requests), Truto passes that error directly to the caller. However, Truto normalizes the upstream rate limit information into standardized headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset) per the IETF specification. The caller - your agent framework or application logic - is entirely responsible for implementing the retry and backoff logic. Do not expect the integration layer to magically absorb rate limit errors.
Why a Unified Tool Layer Matters for Agent Safety
Before writing a line of integration code, decide what layer your agent talks to. Direct API tools (one custom function per raw Samsara endpoint) push provider quirks into the LLM's context.
Truto's Proxy APIs act as the first level of abstraction. Every integration on Truto is a comprehensive JSON object mapping the underlying API into a standardized format. These are surfaced to your LLM as ready-to-use tools via the GET /integrated-account/<id>/tools endpoint. Truto handles the pagination and authentication, providing schemas and descriptions that the LLM understands natively.
This gives you concrete safety wins:
- Smaller attack surface for hallucination. The LLM only chooses from stable function names with explicit, agent-optimized descriptions.
- Deterministic input validation. Every tool has a strict JSON schema. Invalid arguments are rejected before they hit Samsara, allowing the agent to self-correct quickly.
- Abstracted pagination. The agent does not need to manage cursor states or page numbers.
Hero Tools for Samsara AI Agents
Truto provides a comprehensive suite of proxy tools for Samsara. Instead of overwhelming the LLM with hundreds of endpoints, you should equip your agent with specific, high-leverage tools depending on the persona it is serving.
Here are six hero tools for building fleet automation workflows:
1. list_all_samsara_fleet_vehicles
This tool retrieves the core asset list for the organization. It returns vehicle IDs, names, and hardware attributes. Your agent needs this tool to translate human-readable vehicle names (e.g., "Truck 42") into the Samsara IDs required by other endpoints.
"Get a list of all active vehicles in our fleet and find the ID for the vehicle named 'Delivery Van Alpha'."
2. list_all_samsara_safety_events_streams
This stream tool pulls safety incidents over a specified time range, including harsh braking, rapid acceleration, and speeding events. It is the primary data source for any automated safety coaching workflow.
"Fetch all safety events from the last 24 hours to identify any drivers who triggered a harsh braking incident."
3. get_single_samsara_fleet_driver_by_id
Once your agent identifies a driver ID from a safety event or a route, it needs this tool to look up the driver's full profile, contact information, and current activation status.
"Look up the driver profile for ID 987654321 so we can send them a safety coaching email."
4. list_all_samsara_dvirs_streams
Driver Vehicle Inspection Reports (DVIRs) are critical for compliance and maintenance. This tool streams DVIR records submitted by drivers, allowing the agent to spot reported defects in real-time.
"Check the recent DVIR stream for any reports marked with safety-critical defects."
5. create_a_samsara_maintenance_work_order
When a defect is identified, the agent can use this write tool to autonomously generate a maintenance work order in Samsara, attaching it to the specific asset ID.
"Create a high-priority maintenance work order for vehicle ID 12345, noting that the driver reported a worn left front tire in their DVIR."
6. list_all_samsara_hos_violations
Hours of Service (HOS) compliance is strictly regulated. This tool returns active HOS violations across the fleet, enabling the agent to flag compliance risks before they result in fines.
"List all active HOS violations and group them by the associated driver."
For the complete inventory of available proxy tools, required parameters, and JSON schemas, review the Samsara integration page.
Building Multi-Step Workflows
To build an autonomous agent, you need to fetch the Samsara tools from Truto, bind them to your LLM, and orchestrate the execution loop. This approach works natively with any modern framework, including LangChain, CrewAI, and the Vercel AI SDK.
The Architecture
Here is how the data flows when your agent executes a multi-step Samsara workflow. Notice that the agent only communicates with the Truto Tool API, completely isolating it from the complexities of Samsara's raw API endpoints.
sequenceDiagram
participant User as User
participant Agent as AI Agent
participant Truto as Truto Tool API
participant Samsara as Samsara Upstream API
User->>Agent: "Check safety events and draft coaching notes."
Agent->>Truto: Call list_all_samsara_safety_events_streams
Truto->>Samsara: GET /fleet/safety-events/stream
Samsara-->>Truto: Raw Telematics Data
Truto-->>Agent: Normalized JSON Schema
Agent->>Truto: Call get_single_samsara_fleet_driver_by_id
Truto->>Samsara: GET /fleet/drivers/{id}
Samsara-->>Truto: Raw Driver Data
Truto-->>Agent: Normalized JSON Schema
Agent-->>User: Return drafted coaching notes.Fetching and Binding Tools
Using the Truto SDK (e.g., truto-langchainjs-toolset), you can programmatically fetch the tools for a specific integrated account.
import { ChatOpenAI } from "@langchain/openai";
import { TrutoToolManager } from "@trutohq/truto-langchainjs-toolset";
// Initialize the LLM
const llm = new ChatOpenAI({
modelName: "gpt-4o",
temperature: 0,
});
// Initialize Truto Tool Manager with your Samsara account ID
const toolManager = new TrutoToolManager({
trutoApiKey: process.env.TRUTO_API_KEY,
integratedAccountId: "samsara-account-id-123",
});
async function runAgent() {
// Fetch all proxy APIs defined on the Samsara integration
const tools = await toolManager.getTools();
// Bind the tools to the LLM
const agentWithTools = llm.bindTools(tools);
// Execute a prompt
const response = await agentWithTools.invoke(
"Find all active HOS violations and tell me which drivers are non-compliant."
);
console.log("Agent decision:", response.tool_calls);
}
runAgent();Handling Strict Rate Limits (HTTP 429)
As noted earlier, Truto passes upstream rate limits directly back to your agent. If your agent executes a loop over hundreds of vehicles, it will hit a 429 Too Many Requests error.
Your agent framework must catch this error, read the normalized IETF headers (ratelimit-reset), and apply a sleep function before allowing the agent to continue. Do not rely on LLM retries; handle it deterministically in your execution code.
import { ToolExecutionError } from "@trutohq/truto-langchainjs-toolset";
async function executeToolCall(tool, args) {
let retries = 3;
while (retries > 0) {
try {
return await tool.invoke(args);
} catch (error) {
if (error.status === 429) {
// Read the standardized rate limit header passed through by Truto
const resetTimeSeconds = error.headers.get('ratelimit-reset');
const waitMs = resetTimeSeconds ? parseInt(resetTimeSeconds) * 1000 : 5000;
console.warn(`Rate limit hit. Agent sleeping for ${waitMs}ms...`);
await new Promise(resolve => setTimeout(resolve, waitMs));
retries--;
} else {
// It's a different error (e.g., 400 Bad Request), pass it back to the agent to fix
return `Error executing tool: ${error.message}`;
}
}
}
return "Failed to execute tool after handling rate limits.";
}Workflows in Action
When you abstract away the API complexities, the LLM can focus entirely on reasoning and workflow orchestration. Here are three concrete ways AI agents can automate physical operations using the Samsara toolset.
1. Automated Safety Coaching for Fleet Managers
Safety managers spend hours manually reviewing telematics dashboards to find coaching opportunities. An AI agent can run this check autonomously every morning.
"Review all safety events from the last 24 hours. For any event flagged as 'harsh braking' or 'speeding', look up the driver's name and contact info. Draft a personalized coaching email for each driver detailing the specific time of the incident."
Step-by-step execution:
- The agent calls
list_all_samsara_safety_events_streamspassing in thestartTimefor the previous 24 hours. - It filters the normalized JSON response for specific
behaviorLabels(e.g., harsh braking). - It extracts the
driverIdfrom those events. - It loops through the IDs, calling
get_single_samsara_fleet_driver_by_idto retrieve the driver's full name and email. - The agent generates the final drafted emails and returns them to the user.
2. Proactive Maintenance Dispatch
Drivers submit daily DVIRs, but critical defects can easily get buried in the noise. An AI agent can act as an intelligent dispatcher, immediately triaging high-severity issues.
"Check the latest DVIR stream. If any vehicle has a 'critical' or 'unsafe' defect reported, find the vehicle's details and immediately create a new maintenance work order assigned to the shop."
Step-by-step execution:
- The agent calls
list_all_samsara_dvirs_streamsto pull recent inspection reports. - It analyzes the text and flags inside the DVIR to identify unsafe vehicles.
- It takes the associated
vehicleIdand callsget_single_samsara_fleet_vehicle_by_idto get the make, model, and location. - It formats a highly specific JSON payload and calls
create_a_samsara_maintenance_work_order, ensuring the mechanic has full context without manual data entry.
3. HOS Compliance Auditing
Compliance officers need to catch Hours of Service (HOS) violations before they lead to DOT fines or compromised safety.
"Audit the current HOS status across the fleet. List any active violations, identify the driver, and check if they currently have an active route assigned to them today."
Step-by-step execution:
- The agent calls
list_all_samsara_hos_violationsto retrieve the active list. - For each violation, it calls
get_single_samsara_fleet_driver_by_id. - It then calls
list_all_samsara_fleet_routes, cross-referencing the driver ID to see if they are actively dispatched despite being in violation. - The agent returns a prioritized risk report to the compliance officer.
Moving Beyond Point-to-Point Scripts
Building AI agents that interact with physical operations infrastructure requires a fundamental shift in how you handle integrations. Writing custom scripts to connect your agent to Samsara forces you to own the entire API lifecycle - from schema updates and pagination quirks to handling normalized rate limit headers.
By leveraging a unified tool layer, you remove the integration bottleneck. Your engineers stop writing defensive polling logic and start focusing on the core reasoning loops of your AI application.
FAQ
- Does Truto automatically retry Samsara rate limit errors (HTTP 429)?
- No. Truto passes the HTTP 429 error directly to the caller. However, it normalizes the upstream rate limit information into standard IETF headers (ratelimit-limit, ratelimit-remaining, ratelimit-reset). Your agent framework is responsible for handling the retry and backoff logic based on these headers.
- How do I give my LLM access to Samsara endpoints?
- Using Truto, you call the /tools endpoint for your connected Samsara account. This returns all available Proxy APIs as LLM-ready tools with descriptions and JSON schemas, which you can bind to your agent using methods like .bindTools() in LangChain.
- Can I filter which Samsara tools the AI agent has access to?
- Yes. You can use query parameters on the Truto /tools endpoint to filter by methods. For example, you can supply methods[]=read to only give the agent safe, read-only access to telematics data, preventing it from making accidental updates.
- How does an AI agent handle paginated telematics streams from Samsara?
- Truto's Proxy API layer handles the complex cursor and pagination logic underneath. The LLM only sees a clean query tool, eliminating the hallucination risks associated with an agent trying to manually parse and construct pagination cursors.