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:

agent.stateplaces (datasets)routing (datasets)ranges (datasets)customGeometries (datasets)byod (datasets)trafficAreaAnalytics (datasets)trafficIncidents (datasets)baseMap (flat)mapPOIs (flat)trafficTiles (flat)places-0 — places-by-query 'coffee shops'places-1 — single-place 'Eiffel Tower'places-2 — deriveDatasets outputroutes-0 — Berlin → Munichroutes-1 — Amsterdam → Utrechtranges-0 — 20 min from hospitalgeometries-0 — union of city polysbyod-0 — sales territoriestta-0 — central Berlin congestionincidents-0 — Berlin viewport snapshotTomTomMap, MapLibre Map, base-map, styling and terrain modulesbase-map POI layer moduleflow + incident overlay tile visibility

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, latestDataset and findById(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’s DatasetProfile: its feature count, geometry types and properties.
  • addDataset(dataset) - Stores a DatasetInput, the dataset with its id and timestamp optional, and returns its id. Pass id to ask for one, which gets a -2 suffix if it’s taken.
  • replaceDatasetData(id, data, timestamp) and removeDataset(id) - Update or drop a dataset.
  • upsertDataset(dataset) - Adds the dataset if no dataset has its id yet, and otherwise replaces that dataset’s data and timestamp as replaceDatasetData does. It takes what addDataset takes, with id required, and resolves to 'added' or 'replaced'. A replace also records the producedFrom you pass, so a monitor and editRouteWaypoints replay the new request, and a shown route’s waypoint pins move with it. It keeps the dataset’s label and what the slice keeps beside it, such as BYOD layers. A places upsert replaces the connections and geometries you pass, and keeps the ones you leave out. A slice’s upserts and removeDataset calls 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.
  • datasetMode and setDatasetMode(mode) - See Dataset mode.
  • showDataset(id), hideDataset(id) and shownDatasetIds - What’s on the map. The slice creates the SDK module that draws a dataset on its first display, and getDatasetModule(id) returns it.
  • setFocus(id, featureIds, reason?), getFocus(id) and clearFocus(id) - A subset of a dataset’s features to work on, a DatasetFocus, announced by the focus-change event. The incidents slice highlights it on the map.
  • startMonitoring(id, refresh), stopMonitoring(id), isMonitored(id) and getMonitorStatus(id) - Poll the DatasetRefresh’s fetch and replace the dataset’s data with each answer, firing monitor-tick with the new DatasetSnapshot, { takenAt, data }. getMonitorStatus returns idle, running or stopped-error. The setDatasetMonitor tool 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 sliceDatasetsWhat it holds
placesYesPlace 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.
routingYesRoute datasets, staged waypoint slots and the current route parameters; getDatasetModule(id).
rangesYesReachable 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.
customGeometriesYesPolygons derived by deriveDatasets (union, buffer, difference, h3 coverage, …), kept apart from places so producedFrom keeps the source ids and the operation; getDatasetModule(id).
byodYesYour GeoJSON datasets, each with an auto-detected DatasetProfile. getDatasetLayers(id) returns the layers it draws with, and getDatasetModule(id) its module.
trafficAreaAnalyticsYesArea-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.
trafficIncidentsYesFetched 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):

SliceField
placesagent.state.places
routingagent.state.routing
rangesagent.state.ranges
customGeometriesagent.state.customGeometries
byodagent.state.byod
trafficAreaAnalyticsagent.state.trafficAreaAnalytics
trafficIncidentsagent.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 results
agent.state.places.latestPlace; // places of the most recent dataset
agent.state.places.shownDatasetIds; // datasets currently on the map
agent.state.places.datasets; // full history of place datasets
agent.state.trafficIncidents.datasets; // fetched incident datasets
agent.state.trafficAreaAnalytics.datasets; // historical analytics datasets
agent.state.customGeometries.datasets; // derived polygon datasets
agent.state.byod.datasets; // bring-your-own-data layer datasets
agent.state.baseMap.mapLibreMap; // raw MapLibre Map instance

Telling 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 resetState tool, 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 application
agent.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.