Agent Toolkit state
The Agent Toolkit keeps structured state for the whole conversation. Tools return compact summaries and keep the
underlying data in state, so the next tool call or turn reads it instead of the model re-deriving or inventing
it. The model reads it back with recallState, which also returns summaries.
State slices
State is organized by feature area:
Slices flagged datasets own an append-only history of results. The rest hold the map’s shared modules. A dataset is
plain data: its id, label, timestamp and data, which is always a GeoJSON FeatureCollection. Where the slice can
produce it again, its producedFrom records how, such as a route’s waypoints and parameters or the area and filters of an
incident dataset. Routes, traffic incidents, custom geometries and traffic area analytics require it. BYOD defaults it to
{ kind: 'integrator' }, and places and ranges have none.
A ranges dataset holds one polygon per origin and budget, each carrying its origin, budget and originQuery in its
properties. rangesOf(data) groups them back by origin. What a slice draws beside a dataset stays with the slice, keyed by
the dataset’s id: places.getDatasetGeometries(id) and places.getDatasetConnections(id) return a places dataset’s boundaries and
connecting lines, and byod.getDatasetLayers(id) a BYOD dataset’s layers.
Every dataset slice has the same members:
datasets,latestDatasetandfindById(id)- The history, its newest dataset, and one dataset by its id.findFeature(featureId)- The feature with this id in the newest dataset that holds it, together with that dataset.profile(id)- The dataset’sDatasetProfile: its feature count, geometry types and properties.addDataset(dataset)- Stores aDatasetInput, the dataset with itsidandtimestampoptional, and returns its id. Passidto ask for one, which gets a-2suffix if it’s taken.replaceDatasetData(id, data, timestamp)andremoveDataset(id)- Update or drop a dataset.upsertDataset(dataset)- Adds the dataset if no dataset has itsidyet, and otherwise replaces that dataset’s data and timestamp asreplaceDatasetDatadoes. It takes whataddDatasettakes, withidrequired, and resolves to'added'or'replaced'. A replace also records theproducedFromyou pass, so a monitor andeditRouteWaypointsreplay the new request, and a shown route’s waypoint pins move with it. It keeps the dataset’slabeland what the slice keeps beside it, such as BYOD layers. A places upsert replaces theconnectionsandgeometriesyou pass, and keeps the ones you leave out. A slice’s upserts andremoveDatasetcalls run in call order, so the last one wins, and a dataset you remove right after an upsert stays removed. Use it to mirror a live feed, as the BYOD guide shows.datasetModeandsetDatasetMode(mode)- See Dataset mode.showDataset(id),hideDataset(id)andshownDatasetIds- What’s on the map. The slice creates the SDK module that draws a dataset on its first display, andgetDatasetModule(id)returns it.setFocus(id, featureIds, reason?),getFocus(id)andclearFocus(id)- A subset of a dataset’s features to work on, aDatasetFocus, announced by thefocus-changeevent. The incidents slice highlights it on the map.startMonitoring(id, refresh),stopMonitoring(id),isMonitored(id)andgetMonitorStatus(id)- Poll theDatasetRefresh’sfetchand replace the dataset’s data with each answer, firingmonitor-tickwith the newDatasetSnapshot,{ takenAt, data }.getMonitorStatusreturnsidle,runningorstopped-error. ThesetDatasetMonitortool starts and stops them on routes and incidents.
Showing a dataset needs the map the agent was created with. Pass undefined as that map for an agent that only
reads datasets. baseMap.hasMap is then false, and ttMap and mapLibreMap throw.
| State slice | Datasets | What it holds |
|---|---|---|
places | Yes | Place datasets (search results, single lookups, datasets deriveDatasets wrote). getDatasetGeometries(id) and getDatasetConnections(id) return the boundaries and connections that came with one. getDatasetModule(id, markerType?) and getDatasetGeometriesModule(id) return each dataset’s modules, and findDatasetGeometriesModule(id) the boundaries’ module only if it exists. |
routing | Yes | Route datasets, staged waypoint slots and the current route parameters; getDatasetModule(id). |
ranges | Yes | Reachable range (isochrone / isodistance) datasets, with origins, budgets and polygons. showDataset(id, { polygons, fillStyle, originPins }) draws the polygons as bands, as plain geometries or not at all, and pins each origin. Leave an option out to keep how a shown dataset draws, except that one drawn without polygons gets its bands back, unless the call sets only originPins. A hidden dataset draws its bands and pins its origins. getDatasetModule(id) returns the bands’ ReachableRangesModule, getDatasetGeometriesModule(id) a plain GeometriesModule for polygons you style yourself, and getDatasetPlacesModule(id) the origin pins. |
customGeometries | Yes | Polygons derived by deriveDatasets (union, buffer, difference, h3 coverage, …), kept apart from places so producedFrom keeps the source ids and the operation; getDatasetModule(id). |
byod | Yes | Your GeoJSON datasets, each with an auto-detected DatasetProfile. getDatasetLayers(id) returns the layers it draws with, and getDatasetModule(id) its module. |
trafficAreaAnalytics | Yes | Area-analytics datasets with their request and result; getDatasetConfig(id) returns its module’s display config, or nothing before the module exists, and getDatasetModule(id) its module. |
trafficIncidents | Yes | Fetched incident datasets, focused subsets and the polling monitor that keeps them fresh; getDatasetModule(id). |
baseMap | — | The TomTomMap (ttMap) and its MapLibre map (mapLibreMap); getBaseMapModule(), getStylingFoundationsModule(), getTerrainModule(). hasMap says whether there’s a map: without one, ttMap and mapLibreMap throw. |
mapPOIs | — | The base-map POI layer; getPOIsModule(). |
trafficTiles | — | Traffic flow and incident tile overlays; getTrafficFlowModule(), getTrafficIncidentsModule(). |
The dataset slices also hold the look of their modules as a SliceKnobs: routing.knobs, places.knobs and
places.geometriesKnobs, ranges.knobs, ranges.geometriesKnobs and ranges.placesKnobs, customGeometries.knobs,
trafficAreaAnalytics.knobs and trafficIncidents.knobs. set(id, value) takes an id of the module’s
knob catalogue and sets it on every module of that kind the slice holds, and on each one
it creates later. setMapStyling writes through them. For example, agent.state.routing.knobs.set('color', '#e11d48')
recolours every route, shown now or later.
Beside the slices, agent.state holds every analyseDatasets result (analyses) except a persist: 'none' one, which
is only returned, the eventRules, each dataset deriveDatasets keeps live with persist: 'monitor' (derivedDatasets)
and the sandbox that runs generated code (codeExecution). derivedDatasets.datasetIds lists the live datasets in every
slice, each after the derived ones it reads, and you can save and restore them with the event rules.
derivedDatasets also tells you what each live dataset’s latest run did: the features it wrote, or the error that kept
the dataset as it was. A run that wrote can still break what reads the dataset, so it carries a drift when its
features stray from the result the code was written for. That’s when the run returns no feature from sources that
have some, or when a property most of the first result’s features carried is now missing, on under half of the
features or of a type it never had. Read it with lastRun(datasetId), or follow every
run, for example to wake the agent when one fails or drifts:
agent.state.derivedDatasets.events.on('derived-dataset-run', ({ datasetId, run }) => { if ('error' in run) notifyAgent(`${datasetId} stopped updating: ${run.error}`); else if (run.drift) notifyAgent(`${datasetId} drifted: ${run.drift}`);});The model sees the same outcome, with the code, in the dataset’s recallState detail, and can
correct the code.
When a live dataset keeps a history of its runs,
historyIdOf(datasetId) names the BYOD dataset that holds it, so your app can chart the trend from
agent.state.byod.findById(historyId).
Sharing across tools
All tools share state. A place that locatePlace resolves is available to editRouteWaypoints without the model
passing it along. Tools pass dataset ids, not data, which avoids the error-prone “read then pass” pattern.
Tool results carry summaries, not the data. When a user asks “what were those places?” an hour into a session, the
model calls recallState instead of guessing.
Dataset mode
Every dataset slice has an dataset mode. multiple, the default, renders several datasets side by side. single keeps
only the most recent one, and switching to it drops the older ones. The DatasetModeSliceName union names these slices by
their keys on agent.state (routing, not routes; customGeometries, not geometries):
| Slice | Field |
|---|---|
places | agent.state.places |
routing | agent.state.routing |
ranges | agent.state.ranges |
customGeometries | agent.state.customGeometries |
byod | agent.state.byod |
trafficAreaAnalytics | agent.state.trafficAreaAnalytics |
trafficIncidents | agent.state.trafficIncidents |
The model switches modes with the setDatasetMode tool when the user asks to “only show one at a time” or “let me
overlay multiple”. The state playground example shows every
slice’s datasets and mode live.
Defaults via createMapAgent
Set per-kind defaults with the datasets option. Each kind accepts { enabled?, datasetMode? }. Keys are data kinds
(routes, incidents), not slice names (routing, trafficIncidents).
import { createMapAgent } from '@tomtom-org/maps-sdk-plugin-agent-toolkit';
const agent = createMapAgent(map, { model: openai('gpt-4o'), datasets: { routes: { datasetMode: 'single' }, // only one route on the map incidents: { datasetMode: 'single' }, // each refresh replaces the previous snapshot byod: { enabled: false }, // hide byod from analyseDatasets / deriveDatasets + drop addByodSource / setByodLayers },});Omitted kinds keep their defaults (enabled: true, datasetMode: 'multiple'). enabled: false removes the kind from
the agent. The kind drops out of the analyseDatasets / deriveDatasets inputs and the slices updateDatasetDisplay and
setDatasetMonitor take (ranges stays in updateDatasetDisplay), and the agent drops the tools
TOOLS_BY_DATASET_KIND lists for it. With
routes and incidents both off, it drops setDatasetMonitor too. The agent keeps a tool you pass under one of those names in tools.
Switch a mode at any time after construction:
await agent.state.customGeometries.setDatasetMode('single');Working with the union from your own code
DatasetModeSliceName and its runtime list DATASET_MODE_SLICE_NAMES let custom tools and dev UIs iterate every dataset
slice without hard-coding names:
import { DATASET_MODE_SLICE_NAMES, type DatasetModeSliceName,} from '@tomtom-org/maps-sdk-plugin-agent-toolkit';
for (const slice of DATASET_MODE_SLICE_NAMES) { console.log(slice, agent.state[slice].datasetMode);}Inspecting state from your application
Read live state at any time:
agent.state.routing.currentRoutes; // most recent route resultsagent.state.places.latestPlace; // places of the most recent datasetagent.state.places.shownDatasetIds; // datasets currently on the mapagent.state.places.datasets; // full history of place datasetsagent.state.trafficIncidents.datasets; // fetched incident datasetsagent.state.trafficAreaAnalytics.datasets; // historical analytics datasetsagent.state.customGeometries.datasets; // derived polygon datasetsagent.state.byod.datasets; // bring-your-own-data layer datasetsagent.state.baseMap.mapLibreMap; // raw MapLibre Map instanceTelling the model what the user changed
If your UI changes the map between turns, such as hiding a layer or picking another route, the model doesn’t
know. getStateDigest snapshots what is shown. formatStateDigestDiff turns two snapshots into a short note to
prepend to the next message, or returns null when nothing changed:
import { formatStateDigestDiff, getStateDigest } from '@tomtom-org/maps-sdk-plugin-agent-toolkit';
let baseline = getStateDigest(agent.state); // after each assistant reply
// … before sending the user's next message:const diff = formatStateDigestDiff(baseline, getStateDigest(agent.state));const content = diff ? `${diff}\n${userText}` : userText;What state holds, and how to wipe it
State lives in memory only. The toolkit writes nothing to browser storage. State holds every dataset of the session, meaning the places, routes, ranges, BYOD layers, incidents, analyses and event rules the user produced, until one of these clears it:
- The
resetStatetool, which the agent calls when the user asks to start over. agent.destroy()from your code.
The chat history is not part of state. It lives in your chat component. To erase a user’s data, clear that history and call agent.destroy(). See What the agent sends, and where.
Custom state slices
If your custom tools need to share data across calls, extend ToolState with your own slice. Implement reset() to
take part in the cleanup of the resetState tool and agent.destroy(), and give the model a tool that reads the slice back:
import type { ToolState, StateSlice } from '@tomtom-org/maps-sdk-plugin-agent-toolkit';
class FleetState implements StateSlice { vehicles: Map<string, VehiclePosition> = new Map(); reset() { this.vehicles.clear(); }}
interface MyState extends ToolState { fleet: FleetState;}
const agent = createMapAgent<MyState>(map, { model: openai('gpt-4o'), state: { fleet: new FleetState() }, tools: { getFleetVehicle: myFleetTool },});
// Access live state from your applicationagent.state.fleet.vehicles;agent.state.routing.currentRoutes;The site selection agent example adds a custom slice. The tool registry lists the tools that read and write the built-in ones.
State lives in the page, so the person using your application can see and edit everything in it. Securing your agent covers what follows from that.