Introduction
Waylingo is an open-source Rust library. An app gives it one trip request in plain language, plus what the app already knows (where the user is, saved places, the car), and gets back one GeoJSON document with the route and the stops.
"Drive to Berlin, a fast charger every 200 km and a McDonald's 15 minutes before we arrive"
│
▼ LLM: reads only the text, writes a fixed JSON plan
▼ map provider (TomTom or HERE): geocode, route, search along the route, rank by detour
▼
GeoJSON: the route, each stop with its pick and alternatives, and "did you mean" candidates
The end user can then pick another place for a stop, skip a stop, or choose another match for an ambiguous place name. Waylingo builds the new route from the previous result without calling the LLM again.
Waylingo runs in Android apps (Kotlin), iOS and macOS apps (Swift), Python and Rust: the engine is written in Rust, and the same API is generated for the other three languages. Quick start shows each one, and Try the demo runs it in your browser with your own keys.
Status: preview, version 0.1.2. The engine, the TomTom and HERE adapters and the Python, Swift and Kotlin bindings work and have tests. Packages are on PyPI, Maven Central, crates.io and Swift Package Manager; the API may still change before 1.0.
The problem
Map provider APIs work with coordinates. People describe stops relative to the trip:
- “40 minutes into the drive”
- “15 minutes before we arrive”
- “a charger every 200 km”
- “halfway there”
Answering one such request by hand means: turning the words into parameters, getting a route, finding where “40 minutes in” falls on it (which needs time and distance at every point of the route, reported differently by each provider), searching for places along the road near that point, and ranking them by how much time they add to the trip.
Giving an LLM agent map tools and letting it do these steps has two problems. LLMs are not reliable at route arithmetic and detour ranking. And it sends map provider data into the LLM, which providers’ terms may restrict. Check your own agreement; Waylingo avoids the question by never sending provider data to the LLM.
Waylingo splits the work: the LLM only translates language into a small, fixed plan. Ordinary, tested code does everything with coordinates.
What it is not
- Not a routing SDK. There is no public entry point that takes a plan instead of a
sentence.
Engine::starttakes aTripRequestwhose required field is the query text (crates/waylingo/src/engine/mod.rs). If you already have coordinates and categories, call the map provider directly. - Not a service. Waylingo is a library that runs in your app or on your server. It has no hosted endpoint and keeps no state between calls: everything needed to continue a trip is inside the result document.
- Not a navigation product. No turn-by-turn guidance, no map rendering, no live tracking.
- Not an EV range planner. “Every 200 km” places stops by spacing; there is no battery or consumption model.
The privacy boundary
Two rules shape the whole design:
- Map provider data never reaches an LLM. The LLM sees the request text, the locale and the names of saved places. It never sees coordinates, routes, place results or addresses returned by the provider.
- Developers bring their own keys. The engine never holds a key. It hands the host
HTTP request descriptions with a credential slot (
LlmorMap); the host adds the key when it sends the request (crates/waylingo-http/src/lib.rs).
The first rule is enforced in code, not by convention:
| Mechanism | Where |
|---|---|
| The LLM input type has no field for coordinates or provider data | ParseInput in crates/waylingo-parse/src/input.rs |
| The message history can only be extended by three crate-private methods: the input, the model’s reply, and validation errors | crates/waylingo-parse/src/conversation.rs |
| The parse crate and the provider crate never depend on each other | scripts/check_deps.sh, run in CI |
| Parsing finishes before the first map request | phase order in crates/waylingo/src/engine/mod.rs |
| A test fails if an LLM request follows a map request, or carries a canary string from a provider fixture or the user’s coordinates | provider_data_never_reaches_the_llm in crates/waylingo/tests/e2e.rs |
Who this book is for
Developers deciding whether to use Waylingo, and engineers who want to know how it works. Each chapter explains what the code does and why, with paths to the source so you can check. Where something is not built yet, or has a known gap, the text says so.
Crates
| Crate | Role |
|---|---|
waylingo | The engine: query in, GeoJSON out. Performs no I/O |
waylingo-parse | The LLM step: prompt, structured output, repairs, retries |
waylingo-plan | SurfaceIntent (what the LLM writes), the compiler, the canonical Plan, validation limits |
waylingo-geo | Route geometry: measured routes, anchors, windows, polylines, simplification |
waylingo-providers | TomTom and HERE adapters: pure request builders and response parsers |
waylingo-http | Request and response descriptions shared by the engine and hosts |
waylingo-reqwest | Ready-made hosts (blocking and async) that send the engine’s requests |
waylingo-ffi | Python, Swift and Kotlin bindings generated with UniFFI |
Licensed under Apache-2.0 or MIT, at your option. The project does not accept pull requests; issues and discussions are open.
How a trip is planned
This chapter follows one request from the app to the GeoJSON result.
The engine does no I/O
The engine is a synchronous state machine. It never opens a connection, never holds a key and never reads a clock. Instead it tells the host which HTTP requests to send, and continues when the host passes the responses back. This style is often called sans-IO.
#![allow(unused)]
fn main() {
let (mut session, mut step) = engine.start(request)?;
loop {
match step {
Step::Done { geojson } => break geojson,
Step::NeedRequests { requests } => {
let responses = send_all(&requests); // your own function: send, add keys
step = session.step(responses)?;
}
}
}
}
send_all is the reader’s own function: it sends each request with the host’s HTTP
client, adding the key the request names, and returns one response per request.
(Engine::start, Session::step and Step are in crates/waylingo/src/engine/mod.rs.)
Each HttpRequest carries an id, method, URL without any key, headers, body, a
credential slot (Llm or Map), an auth placement (a query parameter name, or a
header name and prefix such as Authorization: Bearer ), a timeout_ms hint and a
not_before_ms backoff hint (crates/waylingo-http/src/lib.rs). The host echoes the
id in the HttpResponse, or reports a transport error (Timeout, ConnectionFailed,
Cancelled) instead of a status.
Why this design:
- Keys stay with the host. The engine cannot leak what it never has.
- Bindings are simple. Everything crossing the boundary is plain owned data, so UniFFI can generate Swift and Kotlin without bridging async Rust callbacks.
- The app keeps its own network stack. A mobile app can send the requests with its own client, certificate pinning or proxy.
- Tests need no HTTP mocking. A test answers requests from fixtures; the same
answers always give byte-identical output (
same_inputs_give_identical_outputincrates/waylingo/tests/e2e.rs). - Cancellation is free. The host stops calling
step.
Rust users do not have to write the loop: waylingo-reqwest provides a blocking
drive and an AsyncHost (see Map providers and
Routing and stops).
Rules for the host
Session::step takes the responses to the whole last batch. The requests in a batch
are independent and may be sent in any order or in parallel. The engine returns
WaylingoError::UnknownResponse for an id it did not issue,
WaylingoError::MissingResponses when some requests of the batch got no response, and
WaylingoError::Finished after the session is done. A Session is single use.
The phases
Host Engine (crates/waylingo/src/engine/)
───────────────────────────────── ───────────────────────────────────────────
start(query, context) ───────────────────▶ Parse: build the LLM request from the text only
◀── [LLM request] ──────────────────
step(LLM response) ──────────────────────▶ compile + validate the plan
◀── [repair or retry] ───────────── (up to 2 repairs, 2 retries)
── no LLM request after this point ──
◀── [setup?, geocode × places] ───── Prepare: category list (TomTom), geocoding
step(...) ───────────────────────────────▶
◀── [base route] ─────────────────── BaseRoute: origin → waypoints → destination
step(...) ───────────────────────────────▶ place anchors on the route (local maths)
◀── [search × anchors] ───────────── Search: one along-route search per anchor
step(...) ───────────────────────────────▶
◀── [matrix × stops] ─────────────── Detour: HERE only, one matrix per stop
step(...) ───────────────────────────────▶ choose one place per stop
◀── [final route] ────────────────── FinalRoute: through the chosen places
step(...) ───────────────────────────────▶ build GeoJSON
◀── Done { geojson } ───────────────
The Phase enum (Parse, Prepare, BaseRoute, Search, Detour, FinalRoute,
Done) only moves forward (Session::advance in crates/waylingo/src/engine/mod.rs).
A phase with nothing to send is skipped in the same call: a destination given as
coordinates needs no geocoding, TomTom needs no matrix, and a trip without stops needs
no category list, no search and no final route.
What each phase does, with the code that does it:
| Phase | Requests | Code |
|---|---|---|
| Parse | 1 LLM call, plus repairs and retries | crates/waylingo-parse/src/parser.rs |
| Prepare | TomTom’s category list (only when the plan has stops); one geocode per place given as text | prepare_requests, setup_requests in engine/phases.rs |
| BaseRoute | 1 route through origin, waypoints and destination | base_route_request, apply_base_route |
| Search | 1 along-route search per anchor | search_requests |
| Detour | HERE: 1 travel-time matrix per stop with candidates; TomTom: none | detour_requests, apply_matrix |
| FinalRoute | 1 route through the chosen places, if any were found | choose_stops, route_through_stops in engine/stops.rs |
For the reference request in the offline tests (“Drive to Berlin, a fast charger every
200 km and a McDonald’s 15 minutes before we arrive”, TomTom fixtures) the engine makes
1 LLM call and 8 map calls: category list, geocode, base route, four searches (three
charger marks and one food stop), final route (query_in_geojson_out in
crates/waylingo/tests/e2e.rs).
What can stop a trip early
A failure in one phase sets a single failure (Session::fail; the first one wins) and
the next advance goes straight to building the output with status: "failed" and an
error object. Examples:
- the LLM step fails (
NEEDS_DESTINATION,LLM_AUTH, …): no map request is ever sent (llm_failure_gives_failed_geojson_and_no_map_callsintests/e2e.rs); - a place cannot be geocoded:
NO_GEOCODE; - the base route fails: the provider error’s code, for example
NO_ROUTE.
A failure that affects one stop does not fail the trip: the stop becomes an
unresolved_stop feature and the status is partial. Failures of optional calls
(TomTom’s category list, a HERE matrix, the final route) become warnings. See
Errors.
Output
Session::finish hands the collected state to output::build
(crates/waylingo/src/output.rs), which writes one RFC 7946 FeatureCollection with
extra top-level members (plan, usage, warnings, signature and so on). The format is
described in The result document.
The LLM step
The LLM has one job: turn the request text into a small JSON object, the
SurfaceIntent (see The plan). It does not answer the user, does not choose
places and never sees map data. All of this lives in crates/waylingo-parse/.
What the LLM can and cannot see
Every LLM request is built from three sources only:
- a fixed system prompt (
crates/waylingo-parse/src/prompt.rs); - the user message, built by
ParseInput::user_message(crates/waylingo-parse/src/input.rs); - during repairs, the model’s own earlier replies and a list of validation errors about them.
The user message looks like this:
Locale: en-GB
Saved places: saved:home, saved:work
Request: drive home, coffee halfway
ParseInput is built from the query and the TripContext, but it copies only the
query, the locale and the saved-place names. It has no field for coordinates, the
active destination, the vehicle or anything from a provider, and no way to add one.
The Conversation type (crates/waylingo-parse/src/conversation.rs) is the only way
to add messages, and each of its methods accepts one of the allowed sources above.
ParseInput::new also rejects input before any call is made: an empty query, a query
over 2,000 characters, more than 50 saved places, a saved-place name that is empty or
over 60 characters, a locale over 35 characters, or coordinates out of range. These
become InvalidRequest errors.
Prompt styles
LlmConfig.prompt selects one of two system prompts (PromptStyle in
crates/waylingo-parse/src/config.rs):
- Full (the default) is for general models. It states the rules (copy places as
written, never write coordinates, omit the origin unless named, keep the user’s units,
how to map phrases to anchors, brand versus category, the
not_understoodanswer; “fast charger” with no number means 150 kW and “rapid” means 50 kW) and gives four worked examples (prompt.rs). Inprompt_jsonmode the JSON Schema is appended. - Compact is one line,
"Convert the trip request to Waylingo JSON."(COMPACT_SYSTEM_PROMPT). It is for the fine-tuned parser, which was trained with exactly this string and learned the rules from data. No schema is appended, even inprompt_jsonmode.
Output modes
LlmConfig.mode selects how structured output is requested
(crates/waylingo-parse/src/openai.rs). All three use the OpenAI chat-completions
format at {base_url}/chat/completions.
| Mode | Request | Reply read from |
|---|---|---|
json_schema | response_format: {type: "json_schema", json_schema: {name: "surface_intent", strict: false, schema}} | message.content |
tool_call | one function, submit_trip_intent, whose parameters are the schema; tool_choice: "auto" | the tool call’s arguments, or content if the model answered in text |
prompt_json | nothing extra; the schema is in the full system prompt | message.content |
Details that came from real endpoints:
- The schema is generated from the Rust type with
schemars, with sub-schemas inlined (no$ref) and the$schemakey removed, because some endpoints do not resolve references in tool or response schemas (crates/waylingo-plan/src/schema.rs). tool_choiceis"auto", not a forced function, because some endpoints (the code comment names Anthropic’s compatibility layer with some models) reject forced tool choice.temperatureis left out unless configured, because some models reject it.- In every mode, code fences and prose around the JSON are dropped by keeping the
outermost
{ ... }. - An OpenAI-style
refusalfield ends the parse withLLM_REFUSED.
The bindings pick the mode per backend (crates/waylingo-ffi/src/config.rs): Anthropic
uses tool_call, OpenAI and Gemini use json_schema, and any other OpenAI-compatible
server uses prompt_json (with the compact prompt when fine_tuned is set).
Validation, repair and retry
Each reply goes through the same steps (Parser::on_response in
crates/waylingo-parse/src/parser.rs):
reply ──▶ HTTP error? ──yes──▶ retry (429, 5xx, transport) or fail with a code
│no
▼
JSON for SurfaceIntent? ──no──▶ repair
│yes
▼
"error": "not_understood"? ──yes──▶ NOT_UNDERSTOOD (no repair)
│no
▼
ground names in the query text
▼
compile + validate ──ok──▶ Plan (parse done)
│errors
▼
missing context (needs)? ──yes──▶ NEEDS_* (destination: one neutral question first)
│no
▼
repairs left? ──yes──▶ repair ──no──▶ INVALID_PLAN
Repair. The model’s reply is added to the conversation as an assistant message, followed by a user message listing every problem as a JSON Pointer into its own JSON, a reason, and the allowed values where the field has a fixed set:
Your JSON has these problems. Reply with the full corrected JSON object only.
- /stops/0/what/category: unknown category "cafe"; use text for other places (allowed: ev_charging, fuel, ...)
At most max_repairs (default 2) repairs are made, so a parse that never becomes
valid costs three LLM calls and ends with INVALID_PLAN and the last errors in the
message (gives_up_after_max_repairs). The SurfaceIntent type rejects unknown
fields, and its enum-like fields are plain strings so the compiler can answer “allowed
values: …” instead of a bare JSON parse error.
Retry. A 429, a 5xx or a transport failure (other than cancellation) is retried up
to max_retries (default 2) times for the whole parse, with the same body. The wait
is the Retry-After header when present, otherwise 1 s, then 2 s, capped at 30 s,
passed to the host as not_before_ms. A cancelled request is not retried and ends as
LLM_UNAVAILABLE. Other failures are not retried:
| Response | Code |
|---|---|
| 401, 403 | LLM_AUTH |
402, or a 429 whose body says insufficient_quota or quota exceeded | LLM_QUOTA_EXCEEDED |
| 429 after the retries | LLM_RATE_LIMITED |
| other 3xx or 4xx (a redirect usually means a wrong base URL; a 4xx a wrong model name) | LLM_BAD_REQUEST |
| 5xx or timeout after the retries | LLM_UNAVAILABLE |
| connection failure after the retries | LLM_UNREACHABLE |
| 2xx that is not a chat-completions body | LLM_BAD_RESPONSE |
Error messages include the endpoint’s own error text, cut to 300 characters, with any
word that starts with sk- or is longer than 40 characters replaced by <redacted>.
Grounding names in the query
Small models sometimes garble names they never saw in training (“Bordeaux” becomes
“Bordean”). Every place, brand and free-text string in the plan should come from the
request, so after parsing, ground_in_query (crates/waylingo-parse/src/ground.rs)
checks each one:
- If the string appears verbatim in the query (case-sensitive), keep it (trimmed).
- Otherwise, compare it with every run of consecutive query words whose length is within one word of the string’s word count. Skip runs whose first letter differs when the string starts with a letter (names rarely get their first letter wrong; house numbers do).
- Take the run with the smallest Levenshtein distance relative to the longer length; on a tie, the shorter run.
- Replace the string only if that relative distance is at most 0.5. Otherwise leave it alone: the geocoder may still resolve it (the request said “SF” and the model wrote “San Francisco”: no run of words is close, so “San Francisco” is kept).
saved:<name> references and current_location are never touched, and neither are
categories. The tests use real failures from evaluation runs, for example “Zagad” to
“Zagreb”, and “Terminal 5” to “Terminal 3” when the request said 3.
Missing context is not repaired
Some compile errors are not mistakes the model can fix: the information is missing.
These errors carry a needs value (Need in crates/waylingo-plan/src/compile.rs)
and are never sent back as a repair, because the model could only invent the value:
| Need | When | Result |
|---|---|---|
Request | nothing was asked for: no destination, waypoint or stop | NOT_UNDERSTOOD |
CurrentLocation | the trip starts at the current location (no origin named) and the host passed none | NEEDS_CURRENT_LOCATION |
Destination | no destination was named and the host passed no active route | NEEDS_DESTINATION, after one question |
The one neutral question. Models sometimes drop a destination the user did name.
So when a destination is missing and a repair slot is left, the parser asks once, even
if the reply has other errors (Parser::on_response in parser.rs). The question uses
the repair slot and a fixed text that does not suggest any answer. (Missing needs are
checked in the order the compiler reports them; the origin comes first, so a missing
current location is reported before the destination is asked about.)
- /destination: missing. If the request names where to go, add it exactly as written there; otherwise leave it out
After this question a destination is accepted only if it appears in the request text
(case-insensitive, with a saved: prefix removed). An invented one, or none, ends the
parse with NEEDS_DESTINATION (an_invented_destination_is_refused,
missing_destination_is_asked_once_then_reported in parser.rs). The app should then
ask the end user “where to?”.
Not a trip. For text that is not a trip request, the prompts and training data ask
for exactly {"error":"not_understood","stops":[]}. Any reply with error set ends the
parse with NOT_UNDERSTOOD and no repair.
After the parse
When the plan compiles, the parser is dropped and the session moves to map calls. From
then on, no LLM request can be issued: the parser no longer exists, and the phase only
moves forward. A trip made with a hosted model therefore costs one LLM call in the
common case, and at most 1 + max_repairs + max_retries calls.
The plan
There are two plan types, on purpose:
SurfaceIntentis what the LLM writes. It stays close to how people talk.Planis what the engine runs. It is exact: SI units, coordinates or geocoding text, checked references and bounded values.
A deterministic compiler turns one into the other (crates/waylingo-plan/src/compile.rs).
Why two tiers
Asking a model for metres, seconds and coordinates invites arithmetic and invention. Asking it to copy “200” and “km” from the sentence does not. So the LLM writes the units and names as the user said them, and Rust code does the conversion, the lookups and the checks. When the model gets something wrong, the compiler can say exactly what and where, which is what the repair loop needs.
SurfaceIntent
Defined in crates/waylingo-plan/src/surface.rs. Unknown fields are rejected.
Enum-like fields are plain strings, so a wrong value produces “unknown value, allowed:
…” rather than a parse failure.
{
"destination": "Berlin",
"stops": [
{"id": "charger",
"what": {"category": "ev_charging", "min_power_kw": 150},
"anchor": {"kind": "every", "amount": {"value": 200, "unit": "km"}}},
{"id": "food",
"what": {"brand": "McDonald's"},
"anchor": {"kind": "offset", "from": "destination", "direction": "before",
"amount": {"value": 15, "unit": "min"}}}
]
}
The prompt’s rules for chargers: “fast charger” with no number means min_power_kw
150, and “rapid” means 50 (see Prompt styles).
| Field | Meaning |
|---|---|
error | "not_understood" when the text is not a trip request |
origin, destination, waypoints | place text as written, saved:<name>, or current_location |
avoid | tolls, highways, ferries |
max_detour | a quantity, if the user said one (“within 5 minutes”) |
stops[].what | category (one of ten), text (a generic kind with no category, such as “bakery”), brand (a name, copied as written), min_power_kw, connector_types |
stops[].anchor | offset (from origin, destination or waypoint:<n>; direction after or before; amount), every (amount), or fraction (value) |
stops[].top_n | options wanted for this stop, 1 to 5 |
The ten categories are ev_charging, fuel, restaurant, fast_food, coffee,
rest_area, hotel, parking, supermarket, pharmacy. A brand is never mapped to
a category by the model: “a McDonald’s” is brand: "McDonald's", and the map search
finds the name. A category is added only when the user also says the kind (“a Shell
petrol station”).
Compiling
compile(&SurfaceIntent, &TripContext) -> Result<Plan, Vec<PlanError>> returns every
problem it finds, not just the first.
Places.
| Written | Becomes |
|---|---|
origin omitted or current_location | the host’s current location as coordinates, or a CurrentLocation need |
| destination omitted | the host’s active_destination, or a Destination need |
saved:<name> | the saved place’s coordinates (name matched case-insensitively), or an error listing the saved names |
| anything else | PlaceQuery { text }, geocoded later by the map provider |
Units. Distances: m, km, mi (and meter, kilometer, mile). Durations:
s, min, h (and sec, second, minute, hour). Units are lower-cased, metre
becomes meter, hr/hrs/mins/secs/miles are normalised, and a trailing s
is dropped from units longer than three letters.
Defaults and context. avoid merges the host’s list with the request’s.
max_detour_s is the request’s value, else the host’s, else the default (600 s).
top_n defaults to 3. An every anchor gets window_pct from the defaults (15).
Departure time, timezone and vehicle come from the host, never from the LLM.
EV filters. If the stop gives a power or connectors, those are used, and missing
connectors are taken from the vehicle. If the stop is ev_charging with neither, the
vehicle’s EV filter is used.
Anchors. from: origin with direction: before, and from: destination with
direction: after, are rejected: they point off the route. A waypoint:<n> must
exist. A fraction must be strictly between 0 and 1.
Ids. A stop without an id gets stop_<i>. Ids must be unique, because choices
and results refer to stops by (stop_request_id, occurrence).
The canonical Plan
crates/waylingo-plan/src/plan.rs:
Plan {
schema_version: "0.1.0"
origin, destination: Location // Coords { lat, lng, label } | PlaceQuery { text }
waypoints: Vec<Location>
departure: { time: Option<RFC 3339>, timezone: Option<IANA> }
vehicle: { ev: Option<EvFilter> }
avoid: Vec<Tolls | Highways | Ferries>
max_detour_s: u32
stop_requests: Vec<StopRequest { id, what, anchor, top_n }>
}
Anchor = Offset { from: Origin | Destination | Waypoint(u8), direction, amount }
| Every { interval: DistanceM | DurationS, window_pct }
| Fraction { value }
The destination is always set: a plan without one cannot be compiled. A plan with no stops is valid (“take me to Utrecht Centraal”); the engine then returns just the route.
plan_hash (crates/waylingo-plan/src/schema.rs) is the SHA-256 of the plan’s JSON.
Field order is fixed by the type definitions, so equal plans hash equally. The result
document carries it, so an app can tell whether two results came from the same
understanding of the request.
Validation limits
Plan::validate (crates/waylingo-plan/src/validate.rs) runs last in compile, and
again on every plan read back from a previous result by reroute.
| Limit | Value |
|---|---|
| Stops per plan | 10 |
| Waypoints per plan | 10 |
Options per stop (top_n) | 1 to 5 |
| Offset or interval | positive, at most 5,000 km or 72 h |
| Shortest “every” | 1 km or 5 minutes |
every window percentage | 1 to 50 |
| Fraction | strictly between 0 and 1 |
| Place text, brand, free text, stop id | at most 200 characters |
| Charger power | above 0, at most 1,000 kW |
max_detour_s | 1 s to 3,600 s |
| Departure time and timezone strings | at most 64 bytes |
| Coordinates | finite, latitude within ±90, longitude within ±180 |
| Plan schema version | exactly 0.1.0 |
Why these exist: the plan decides how much work the engine does (how many anchors,
searches and routes). A plan can come from a model that misread the request, and on
reroute it comes from a document the client sent back. Without bounds, “a coffee
every metre” or a tampered plan with thousands of stops could make a server send
thousands of map requests. The limits keep the work of any plan small, and they work
together with the per-stop cap of 30 anchors and the map call budget described in
Routing and stops.
The developer’s own settings are checked too (Defaults::validate in
crates/waylingo-plan/src/context.rs): anchor radius 100 to 50,000 m, search span from
the radius up to 150,000 m, search limit at least 1, maximum detour 1 to 3,600 s,
top_n 1 to 5, every_window_pct 1 to 50.
Routing and stops
This chapter covers what the map providers’ APIs do not: placing “40 minutes in” or “every 200 km” on a real route, searching the road near that point, and picking the place that adds the least driving time. All of it is ordinary code with tests; the LLM is not involved. One trip, step by step walks through it with numbers.
The steps, for each stop request in the plan:
base route ──▶ measured route (distance and time at every point)
│
anchor ────────────┼──▶ anchor point(s) on the route (local maths, no API call)
│
├──▶ search window: a stretch of route around each anchor point
│
├──▶ along-route search in that stretch (1 call per anchor)
│
├──▶ detour times (TomTom: in the search reply; HERE: 1 matrix call)
│
└──▶ choose: one place per stop, plus alternatives
│
▼
final route through all chosen places (1 call)
The measured route
A provider returns a route as a line of coordinates plus some timing data. Waylingo
turns it into a MeasuredRoute (crates/waylingo-geo/src/measured.rs): the
coordinates plus the cumulative distance cum_m and cumulative driving time cum_s at
every coordinate.
The provider reports distance and time at certain points along the route (checkpoints). Between two checkpoints, Waylingo spreads the provider’s distance and time over the coordinates in proportion to the haversine length of each segment. So the totals always match the provider’s, and the speed can change from one stretch to the next.
checkpoints: 0 km / 0 s ───────── 600 km / 19,800 s ──── 650 km / 23,400 s
(motorway: about 109 km/h) (city: 50 km/h)
This matters for time anchors. With an even spread the average speed is 650 km in
6.5 h, 100 km/h, so “15 minutes before we arrive” would land 900 s × 100 km/h = 25 km
before the end. With the checkpoints it lands in the city section at 50 km/h:
900 s × 50 km/h = 12.5 km before the end, which is what the driver will experience
(minutes_before_end_uses_slow_city_section in crates/waylingo-geo/src/anchor.rs).
Where the checkpoints come from:
- TomTom: the guidance instructions’
pointIndex,routeOffsetInMetersandtravelTimeInSeconds; an instruction is kept only when its point index increases and its distance and time do not go backwards; the last checkpoint is the route summary’s length and travel time (crates/waylingo-providers/src/tomtom.rs). Routes are requested withtraffic=true. - HERE: each section’s Flexible Polyline is decoded and joined; each action’s
offset,lengthanddurationadd a checkpoint, and each section end adds one so legs line up exactly (crates/waylingo-providers/src/here.rs).
Both adapters also report leg_end_m, the distance at the end of each leg, which
places waypoints on the route.
Lookup. position_at_distance(m) and position_at_time(s) binary-search the
cum_m or cum_s array (partition_point) for the segment that contains the value,
then interpolate the position and the other axis linearly within it. Values outside the
route return nothing.
Anchors
The engine converts each plan anchor into an AnchorSpec
(crates/waylingo/src/engine/anchor.rs), and resolve
(crates/waylingo-geo/src/anchor.rs) turns it into one or more AnchorPoints, each
with a position, cum_m, cum_s and an occurrence number.
Offset. Find the reference point (start, end, or a waypoint’s leg_end_m), then
move along the axis of the amount: a distance moves along cum_m, a time along
cum_s.
"15 min before we arrive": target cum_s = total_s - 900
"after 100 km": target cum_m = 0 + 100,000
"10 km after <waypoint 0>": target cum_m = leg_end_m[0] + 10,000
A target beyond either end of the route is an error. The stop is then reported as
UNSUPPORTED with the reason in detail.
Fraction. total_m × value. “Halfway” is half the distance, not half the time.
Every N. Marks at N, 2N, 3N, … from the start, measured on cum_m for a distance
interval or cum_s for a time interval. A mark is dropped when it is at or past the end,
or when less than window_pct percent of N (default 15%) is left after it: a stop that
close to the destination is not useful.
650 km route, "every 200 km", 15% of 200 km = 30 km tail:
0 200 400 600 650
|---------x----------x----------x-----| 600 km mark kept: 50 km left ≥ 30 km
If no mark fits (“every 200 km” on a 150 km route) the stop is UNSUPPORTED with “the
route is shorter than the interval”. One stop request may create at most 30 marks
(MAX_ANCHORS_PER_STOP in engine/phases.rs); further marks are dropped with a
warning.
Marks are counted from the start of the trip, not from the previous chosen stop. That keeps every search independent, so all searches go out in one parallel batch. The cost is that the real gap between two chosen stops can be longer than N (see Design decisions).
Search windows
For each anchor point the engine searches a stretch of the route around it, by
distance (Window::by_distance in crates/waylingo-geo/src/window.rs):
anchor
│
───────[─────────────●─────────────]───────▶ route
start_m end_m
◀── search_span_m ──▶◀── search_span_m ──▶ (clamped to the route)
Two developer settings control it (Defaults in crates/waylingo-plan/src/context.rs):
| Setting | Default | Meaning |
|---|---|---|
anchor_radius_m | 5,000 m | places within this straight-line distance of the anchor point are preferred |
search_span_m | 3 × radius (15 km) | route searched on each side of the anchor; at least the radius, at most 150 km |
Why a fixed span and not a percentage of the offset: a stop “every 200 km” and a stop “in 20 minutes” both want a place near a point, and the useful search area depends on how far a driver will go off the road, not on how far the point is from the start. The span is wider than the radius so that places just beyond the radius are still found when nothing is closer (see “beyond the radius” below).
The window’s slice of the route (with interpolated end points,
MeasuredRoute::slice) is simplified with Douglas-Peucker before it is sent, to stay
within each provider’s limit on route points: 250 for TomTom and 120 for HERE, whose
search is a GET request with the corridor encoded in the URL
(simplify_to_max_points in crates/waylingo-geo/src/simplify.rs). The simplifier
always drops points within 0.5 m of the line, then finds by bisection the smallest
tolerance that fits the limit, and always keeps the first and last point.
Along-route search
One request per anchor point, all in one batch (search_requests in
engine/phases.rs). What the request asks for:
- TomTom
searchAlongRoute(POST, the window’s points in the body):maxDetourTimeis the plan’smax_detour_s, results are sorted by detour time, up tomin(search_limit, 20)results. A category stop without a brand sends*as the query text plus thecategorySetid learned from TomTom’s category list, because generic text together withcategorySetreturned nothing in live tests. A brand with a category (“a Shell petrol station”) sends the brand as the text pluscategorySet, which works. A brand is sent as the query text, not asbrandSet, becausebrandSetonly matches chains in TomTom’s brand registry and would miss a local name. EV stops addminPowerKWandconnectorSet. - HERE Browse (category only) or Discover (brand or free text), with
route=<flexible polyline>;w=<corridor>: the corridor width isanchor_radius_m, clamped to 100 to 50,000 m. An EV category stop with a power addsevStation[minPower].
The details are in Map providers.
Detour time
The detour of a place is the extra driving time it adds compared with staying on the route.
TomTom returns detourTime (and detourDistance) with each result, relative to the
route points that were sent.
HERE returns only a distance off the route, so the engine computes detours with one
travel-time matrix per stop (detour_requests, apply_matrix in engine/phases.rs):
A = window start B = window end P1..Pk = candidates
origins = [A, P1, ..., Pk]
destinations = [P1, ..., Pk, B]
detour(Pi) = t(A→Pi) + t(Pi→B) − t(A→B) (never below 0)
To keep the matrix small, the candidates are first shortlisted: places within the
anchor radius before others, nearest to the anchor first, at most 8
(MATRIX_SHORTLIST). A place the end user chose earlier is always kept, even if it is
not among the nearest. Candidates outside the shortlist are dropped. If the matrix call
fails, the stop keeps its candidates without detour times, and a warning says they were
ranked by distance from the anchor.
Choosing one place per stop
choose in crates/waylingo/src/select.rs, called for each stop in plan order and,
within a stop, in occurrence order (choose_stops in engine/stops.rs):
- Drop places already used by another stop, so one place never serves two stops. Places the end user chose are reserved first.
- Drop places whose known detour is over
max_detour_s. A place with an unknown detour is kept. - If
strict_radiusis set, drop places beyondanchor_radius_m. - Sort: places within the radius first, ranked by detour time (unknown last), then by straight-line distance to the anchor. Places beyond the radius are ranked by distance only.
- The first place is the pick. The next
top_n − 1places on the same side of the radius are the alternatives.
within radius (5 km) beyond radius
┌──────────────────────┐ ┌─────────────────┐
│ detour 120 s ← pick │ │ 6.2 km │
│ detour 300 s ← alt │ │ 9.8 km │
│ detour ? ← alt │ └─────────────────┘
└──────────────────────┘
Alternatives never cross the radius: if the pick is within it, places beyond it are not offered.
When nothing is within the radius (and strict_radius is off), the nearest place
beyond it becomes the pick, the stop is flagged beyond_radius: true, and the result
gets a warning. The app can show “nearest match is 9 km from where you asked”. With
strict_radius on, such a stop is reported as not found instead.
A stop with no usable place becomes an unresolved_stop with NO_CANDIDATES and a
detail such as “provider returned 3 result(s), 1 within the detour limit”. With
strict_radius, that count is of results within the detour limit only; it does not say
how many were also within the radius. After all
stops are chosen, a place that became another stop’s pick is removed from every
alternatives list, because the end user could not choose it.
Each place also gets along_m: the distance along the base route of the route point
nearest to it, looking only inside the stop’s window (on a route that passes the same
area twice, the place belongs to the stretch that was searched). If the window holds no
route point, the whole route is used (nearest_cum_m in select.rs). This orders the
stops on the final route.
The final route
route_through_stops (engine/stops.rs) builds one route request: origin, then the
waypoints and chosen places sorted by along_m, then the destination. If no stop was
found, the base route is already the answer and no request is made.
The final route gives the real totals, including detours, and the arrival time at each
stop (eta_s, seconds from departure, read from the final route at the end of the leg
that reaches the stop). If the final route fails, the trip does not fail: the result
keeps the base route, ETAs fall back to the anchor’s time on the base route, and a
warning says so.
Anchors are placed on the base route and are not moved by earlier stops’ detours or time spent at a stop. The final route reports the true arrival times, but a stop “two hours in” is two hours into the base route, not two hours of driving after earlier stops.
Call budget, retries and pacing
Budget. Limits.max_map_calls (default 25) counts every map request a query
makes, retries included (crates/waylingo/src/config.rs). It is checked before each
search and each matrix request, keeping one call in reserve for the final route: a
search that does not fit is reported as SKIPPED_BUDGET; a matrix that does not fit
leaves that stop without detour times and adds a warning. Setup, geocoding, the base
route, the final route and retries are counted but not refused, so a query with many
retries can end slightly above the limit. The result’s usage reports the calls made.
Retries. A map response with 429, a 5xx or a transport failure (other than
cancellation) is sent again up to max_map_retries (default 2) times, after the
Retry-After value or 1 s, then 2 s (at most 30 s), passed as not_before_ms
(Session::handle in engine/mod.rs). Other errors are classified and reported (see
Errors).
Pacing is the host’s job, because only the host knows how many queries run at
once. The hosts in crates/waylingo-reqwest/:
- the blocking
drivesends one request at a time and waits 220 ms before each map request (MAP_SPACING, under TomTom’s default 5 requests per second); AsyncHostsends each batch in parallel, but map requests pass through one gate shared by every query on that host, so their starts are at leastmap_spacingapart; the whole query has a deadline, and time spent waiting at the gate counts against it. The bindings set the spacing frommap_requests_per_second(default 4.5) and the deadline fromtimeout_ms(default 60 s).
One trip, step by step
This page follows one request through the engine with numbers. The route, the candidates and their detours are illustrative: invented to show how the code decides, not output from a real provider. The rules applied to them are the ones in Routing and stops.
The request, sent with the user’s current location and the default settings (TomTom,
anchor radius 5 km, search span 15 km, top_n 3, maximum detour 600 s):
Drive to Berlin, a fast charger every 200 km and a McDonald’s 15 minutes before we arrive
1. The LLM writes the intent
{"destination": "Berlin",
"stops": [
{"id": "charger", "what": {"category": "ev_charging", "min_power_kw": 150},
"anchor": {"kind": "every", "amount": {"value": 200, "unit": "km"}}},
{"id": "food", "what": {"brand": "McDonald's"},
"anchor": {"kind": "offset", "from": "destination", "direction": "before",
"amount": {"value": 15, "unit": "min"}}}]}
“Fast charger” with no number becomes 150 kW (a rule in the prompt). “McDonald’s” is a brand, not a category. One LLM call; no coordinates in it.
2. The compiler makes the plan
Units become metres and seconds, the missing origin becomes the current location, defaults are filled in (trimmed):
{"origin": {"kind": "coords", "lat": 52.3702, "lng": 4.8952, "label": "current_location"},
"destination": {"kind": "place_query", "text": "Berlin"},
"max_detour_s": 600,
"stop_requests": [
{"id": "charger",
"what": {"category": "ev_charging", "text": null, "brand": null,
"ev": {"min_power_kw": 150.0, "connector_types": []}},
"anchor": {"kind": "every", "interval": {"distance_m": 200000.0}, "window_pct": 15},
"top_n": 3},
{"id": "food",
"what": {"category": null, "text": null, "brand": "McDonald's", "ev": null},
"anchor": {"kind": "offset", "from": "destination", "direction": "before",
"amount": {"duration_s": 900.0}},
"top_n": 3}]}
3. Geocoding and the base route
Map calls so far: TomTom’s category list (the plan has stops), one geocode for “Berlin”, then one route from the current location to the top geocoding match.
Suppose the route is 650 km and 6.5 h (23,400 s), with checkpoints showing a fast first 600 km (reached at 19,800 s) and a slow last 50 km through the city (3,600 s).
4. Anchors
Charger, every 200 km. Marks at 200, 400 and 600 km. The next one, 800 km, is past the end. The 600 km mark is kept because 50 km remain after it, more than 15% of 200 km (30 km). That gives occurrences 0, 1 and 2.
Food, 15 minutes before arrival. Target time 23,400 − 900 = 22,500 s. That is 2,700 s into the city section, which covers 50 km in 3,600 s, so 37.5 km past the 600 km checkpoint: the anchor is at 637.5 km.
0 km 200 400 600 637.5 650
|------------x----------x----------x----●------|
c#0 c#1 c#2 food
5. Windows and searches
Each anchor gets a window of 15 km each side, clamped to the route:
| Stop | Anchor | Window |
|---|---|---|
| charger #0 | 200 km | 185 to 215 km |
| charger #1 | 400 km | 385 to 415 km |
| charger #2 | 600 km | 585 to 615 km |
| food | 637.5 km | 622.5 to 650 km (clamped at the end) |
Four along-route searches go out in one batch. The charger searches send * with
TomTom’s EV charging category and minPowerKW=150; the food search sends
“McDonald’s” as text. All ask for places within a 600 s detour.
6. Choosing charger #2
Suppose the search in the 585 to 615 km window returns three places (fictional):
| Place | Distance from anchor | Detour |
|---|---|---|
| Example Charge Hub | 1.2 km | 240 s |
| Sample Fast Charge | 3.8 km | 150 s |
| Demo Chargepoint | 7.5 km | 90 s |
Two are within the 5 km radius; they come first and are ranked by detour time.
Sample Fast Charge (150 s) is the pick and Example Charge Hub (240 s) the
alternative. Demo Chargepoint has the smallest detour but is beyond the radius, and
alternatives never cross the radius, so it is not offered. Had nothing been within
5 km, it would have become the pick, flagged beyond_radius.
Stops are chosen in plan order, so charger #0 and #1 have already taken their places; none of those can be chosen again here. The food stop is chosen last the same way.
7. The final route
The chosen places are ordered by where they sit along the base route (along_m), and
one route request goes through them:
current location → charger #0 → charger #1 → charger #2 → McDonald's → Berlin
That route gives the real total distance and time, including detours, and each stop’s
eta_s.
8. The count
| Calls | Number |
|---|---|
| LLM | 1 |
| Category list | 1 |
| Geocode | 1 |
| Base route | 1 |
| Searches | 4 |
| Final route | 1 |
| Map calls in total | 8 |
The offline test query_in_geojson_out (crates/waylingo/tests/e2e.rs) runs this
request against fixtures and checks the same 1 LLM call and 8 map calls. With HERE
there would be no category list but up to four matrix calls, one per stop with
candidates. If the end user then picks Example Charge Hub instead,
reroute makes one more map call: a new final route.
The result document
Every plan and reroute returns one document: an RFC 7946 GeoJSON
FeatureCollection with extra top-level members (TripResult in
crates/waylingo/src/result.rs, written by crates/waylingo/src/output.rs). An app can
draw it on any GeoJSON map, read its fields, and pass it back to reroute. Positions
are [lng, lat], as GeoJSON requires.
A sample
A trimmed, hand-written sample for “Drive to Dornholm, coffee halfway”. The place names, ids and numbers are invented for illustration, not taken from a provider; the route line is shortened to three points and the hash to a placeholder. The field names, their order and the number formats follow the code.
{
"type": "FeatureCollection",
"result_schema": "1.0.0",
"plan_schema": "0.1.0",
"request_id": "req-1",
"status": "complete",
"error": null,
"provider": "tomtom",
"attribution": "© TomTom",
"plan": {
"schema_version": "0.1.0",
"origin": {"kind": "coords", "lat": 52.37, "lng": 4.90, "label": "current_location"},
"destination": {"kind": "place_query", "text": "Dornholm"},
"waypoints": [],
"departure": {"time": null, "timezone": null},
"vehicle": {"ev": null},
"avoid": [],
"max_detour_s": 600,
"stop_requests": [
{"id": "stop_0",
"what": {"category": "coffee", "text": null, "brand": null, "ev": null},
"anchor": {"kind": "fraction", "value": 0.5},
"top_n": 3}
]
},
"plan_hash": "<64 hex characters>",
"assumptions": [
"\"Dornholm\" matched 2 places; used the provider's top match (Dornholm, Example Province); the others are in the location's candidates"
],
"warnings": [],
"usage": {"llm_calls": 1, "map_calls": 5},
"search": {
"anchor_radius_m": 5000, "search_span_m": 15000, "search_limit": 20,
"search_limit_requested": 20, "strict_radius": false, "max_detour_s": 600,
"every_window_pct": 15, "top_n": 3
},
"features": [
{"type": "Feature",
"geometry": {"type": "LineString",
"coordinates": [[4.90, 52.37], [5.00, 52.21], [5.12, 52.09]]},
"properties": {"kind": "route", "total_m": 42600.0, "total_s": 2100.0, "includes_stops": true}},
{"type": "Feature",
"geometry": {"type": "Point", "coordinates": [4.90, 52.37]},
"properties": {"kind": "origin", "index": null, "text": "current_location",
"chosen_id": null, "along_m": 0.0, "candidates": []}},
{"type": "Feature",
"geometry": {"type": "Point", "coordinates": [5.12, 52.09]},
"properties": {"kind": "destination", "index": null, "text": "Dornholm",
"chosen_id": "example-geo-1", "along_m": 42000.0,
"candidates": [
{"id": "example-geo-1", "label": "Dornholm, Example Province",
"position": [5.12, 52.09], "score": 0.98},
{"id": "example-geo-2", "label": "Dornholm, Other Province",
"position": [6.50, 53.11], "score": 0.71}]}},
{"type": "Feature",
"geometry": {"type": "Point", "coordinates": [5.00, 52.21]},
"properties": {
"kind": "stop", "stop_request_id": "stop_0", "occurrence": 0,
"anchor": {"position": [5.00, 52.21], "cum_m": 21000.0, "cum_s": 990.0},
"window": {"start_m": 6000.0, "end_m": 36000.0},
"pick": {"provider_place_id": "example-place-1", "name": "Cafe Example",
"brand": null, "address": "Dornholm",
"position": [5.00, 52.21], "detour_s": 95.0, "detour_m": 800.0,
"along_m": 21200.0, "distance_from_anchor_m": 230.0},
"eta_s": 1010.0,
"beyond_radius": false,
"alternatives": [
{"provider_place_id": "example-place-2", "name": "Example Roasters",
"brand": null, "address": null, "position": [4.99, 52.23],
"detour_s": 180.0, "detour_m": 1500.0, "along_m": 19100.0,
"distance_from_anchor_m": 2240.0}],
"user_choice": null}}
],
"signature": null
}
Top-level members
| Member | Content |
|---|---|
type | "FeatureCollection" |
result_schema | "1.0.0"; a result with a different major version is not resumed |
plan_schema | "0.1.0", the version of the Plan format |
request_id | echoed from the request |
status | complete, partial or failed |
error | { code, message } when failed, else null (see Errors) |
provider | tomtom or here |
attribution | text that must be shown with the results |
plan, plan_hash | the compiled plan and the SHA-256 of its JSON (see The plan) |
assumptions | choices made for the user (below) |
warnings | degraded steps: budget, missing detour times, final route failed, a pick beyond the radius, … |
usage | { llm_calls, map_calls } for this call only; a reroute starts from zero |
search | the search settings in effect, so a reroute uses the same ones |
features | see below |
signature | hex HMAC-SHA256 when the engine has a signing key, else null (see Signing) |
assumptions lists choices Waylingo made where the request was ambiguous. Today that is
the geocoding case: when a place name matched more than one candidate, the provider’s
top match is used, the assumption says so, and the other matches are in that
location’s candidates for a “did you mean …?” prompt.
Features
Features come in a fixed order: the route, the origin, the waypoints, the destination,
then the stops in plan order. properties.kind says what a feature is.
| Kind | Geometry | Properties |
|---|---|---|
route | LineString | total_m, total_s, includes_stops (false when it is the base route because no stop was found or the final route failed) |
origin, waypoint, destination | Point, or null if unresolved | index (waypoints only), text as the user said it or the label of given coordinates, chosen_id, along_m, candidates (up to 5: id, label, position, score) |
stop | Point (the pick) | stop_request_id, occurrence, anchor, window, pick, eta_s, beyond_radius, alternatives, user_choice |
unresolved_stop | null | stop_request_id, occurrence, anchor, window, result, error_code (only for PROVIDER_ERROR), detail, options |
A place (pick, an alternative, or an option of a skipped stop) has
provider_place_id, name, brand, address, position, detour_s, detour_m,
along_m (distance along the base route to the route point nearest the place) and
distance_from_anchor_m (straight line). Places are map provider content: show them,
never send them to an LLM.
anchor is where the stop was asked for (position, cum_m, cum_s on the base
route); window is the stretch of route that was searched (start_m, end_m).
eta_s is seconds from departure. user_choice is chosen when the end user picked
the place, dropped when an earlier choice was not found again after a re-search.
Number formats
Output is deterministic: the same inputs give byte-identical output. Field order is
fixed by the types; positions are rounded to 6 decimals, distances and times to whole
metres and seconds, geocoding scores to 3 decimals (output.rs). This is what makes
signatures stable and lets tests compare whole documents.
In the bindings
The bindings parse the document into typed fields (TripOutput in
crates/waylingo-ffi/src/result.rs), so an app can show options and build choices
without parsing JSON, and pass geojson back to reroute. See
Bindings.
Reroute and the interaction loop
A planned trip is a proposal. The end user may prefer another charger, not want the coffee stop, or have meant a different “Springfield”. Waylingo handles this without a second LLM call and without keeping any state between calls.
The loop in an app
- The end user types or says a trip.
planreturns a result: the route, each stop’s pick and alternatives, unresolved stops, and each named place with its geocoding candidates.- The app shows the options.
- The end user picks another place for a stop, skips a stop, or picks another candidate for the origin, a waypoint or the destination.
reroute(previous_result, choices)returns a new result. Go to 3.
To undo, keep the earlier result and reroute from it instead.
Stateless resume
Engine::resume(previous, choices, request_id) (crates/waylingo/src/engine/resume.rs)
rebuilds a session from the previous result document alone. The plan, the search
settings, every location with its candidates, every stop with its anchor, window, pick
and alternatives are all in the document. The bindings call this reroute.
Why stateless: a server does not need a session store or sticky routing, a phone app can resume after being killed, and any earlier result can be resumed to undo. The cost is that the previous result is now input from the client, so it is checked like input.
Choices
Choices (crates/waylingo/src/choices.rs) has two lists:
stops: for a(stop_request_id, occurrence), eitherPlace { provider_place_id }(the pick, one of the alternatives, or for a skipped stop one of itsoptions) orSkip;locations: for the origin, a waypoint (by index) or the destination, acandidate_idfrom that place’scandidates.
Choices recorded in the previous result carry over: a pick marked
user_choice: "chosen" and a stop with result: "SKIPPED_BY_USER". A new choice for
the same stop replaces the old one.
What is fetched again
| Change | LLM | Geocode | Base route | Searches | Matrices (HERE) | Final route |
|---|---|---|---|---|---|---|
| Stop choices only (pick, skip, bring back) | no | no | no | no | no | 1 call |
| Another origin, waypoint or destination candidate | no | no | yes | yes | yes | yes |
| Previous result had no route | no | no | yes | yes | yes | yes |
| No choices, previous result had a route | no | no | no | no | no | 1 call |
When the base route is redone, TomTom’s category list is also fetched again (one call,
only when the plan has stops), because a resumed session starts with a fresh adapter
(Engine::resume in resume.rs). A previous result that never got as far as a route
is searched again from the base route in the same way.
Stop choices only. The stops are rebuilt from the document, the choices are
applied, and one route call goes through the chosen places
(a_stop_choice_reroutes_with_one_map_call_and_no_llm in
crates/waylingo/tests/resume.rs). A newly picked place becomes the pick; the old pick
becomes the first alternative, so the end user can switch back. A skipped stop keeps
the places it offered as options, so it can be brought back later.
A different location. Everything from the base route on is redone, because stops
anchored to the destination (“15 minutes before we arrive”) move with it. The new
position comes from the chosen geocoding candidate, so no new geocoding call is made.
Earlier stop choices become pins: if the same place is found again it is kept (and
kept in the matrix shortlist), otherwise the new best match is used and marked
user_choice: "dropped", with a warning. A stop skipped earlier stays skipped and is
not searched; it then has no options, so to bring it back, resume the earlier result.
What is not refreshed. On a stop-only reroute, stops that were unresolved in the
previous result (NO_CANDIDATES, PROVIDER_ERROR, SKIPPED_BUDGET, …) are copied as
they are; they are not searched again. Travel times come from the new route call, but
candidates, detours and alternatives are the ones found by the original search.
usage in the new result counts only the calls made by the reroute.
Checks on the previous result
resume rejects, with IncompatibleResult:
- text that is not a Waylingo result, or a different major result schema version or a different plan schema version;
- a result containing an error code this version does not know (it was made by a newer Waylingo);
- when the engine has a signing key: a missing or wrong signature;
- a result without a plan (the request was never understood);
- a plan that fails
Plan::validate, or search settings out of range; - a result from another map provider;
- positions off the globe, invalid distances, a waypoint without
along_m; - the same stop (
stop_request_idandoccurrence) appearing twice; - a stop whose
stop_request_idis not in the plan; - a geocoded place with no chosen candidate.
And it rejects bad choices: UnknownChoice for a stop, place or candidate the result
did not offer, and InvalidRequest when one stop gets two choices or one place is
chosen for two stops. Positions of geocoded places always come from the chosen
candidate, not from the feature geometry, so editing a location’s geometry has no
effect (a_tampered_destination_geometry_is_ignored).
Signing
Without a signing key, resume trusts the document’s contents within the checks above.
For a phone app resuming its own results, that is enough. A server that takes results
back from clients should set a signing key (EngineConfig::signing_key, or
signing_key in the bindings’ constructor; 32 random bytes are recommended). Then:
- every result carries
signature: HMAC-SHA256, hex, over the document serialized withsignature: null(crates/waylingo/src/signing.rs); resumeaccepts only documents whose signature verifies (constant-time comparison).
With a key, a client cannot inject a place Waylingo did not find, edit the plan to make the server do more work, or move a stop.
The route line is not signed. Before computing the HMAC, the route feature’s
geometry is replaced by an empty line. The reason is size: the route line is by far the
largest part of a result, and resume never reads it (positions come from candidates,
stops and anchors). So a client may empty the route’s coordinates, or set its
geometry to null, before sending a result back, and the signature still verifies. The
route feature itself must stay.
Signing works because serialization is deterministic: field order is fixed by the
types, positions are rounded to 6 decimals, distances and times to whole metres and
seconds, scores to 3 decimals (crates/waylingo/src/output.rs). A test checks that
signatures survive values that are awkward to round-trip
(signatures_survive_awkward_numbers).
The format of the document itself is described in The result document.
Map providers
Waylingo supports two map providers, TomTom and HERE. An app uses exactly one, chosen in its configuration. There is no mixing and no fallback from one to the other.
Why one provider per app: detour times subtract travel times, and times from two providers’ traffic models cannot be meaningfully subtracted. Mixing would also need several keys per app and could conflict with providers’ terms about combining their content.
The adapter trait
Each provider is a ProviderAdapter (crates/waylingo-providers/src/types.rs). Every
method is pure: it builds an HttpRequest or parses an HttpResponse. Adapters never
send anything and never hold a key.
#![allow(unused)]
fn main() {
pub trait ProviderAdapter {
fn kind(&self) -> ProviderKind;
fn capabilities(&self) -> Capabilities;
fn attribution(&self) -> &'static str;
fn setup_requests(&self, id_prefix: &str) -> Vec<HttpRequest>;
fn apply_setup(&mut self, resp: &HttpResponse) -> Result<(), ProviderError>;
fn geocode_request(&self, id: String, query: &str, bias: Option<LatLng>) -> HttpRequest;
fn parse_geocode(&self, resp: &HttpResponse) -> Result<Vec<GeocodeCandidate>, ProviderError>;
fn route_request(&self, id: String, q: &RouteQuery) -> HttpRequest;
fn parse_route(&self, resp: &HttpResponse) -> Result<RouteResult, ProviderError>;
fn search_request(&self, id: String, q: &SearchQuery) -> HttpRequest;
fn parse_search(&self, resp: &HttpResponse) -> Result<Vec<Candidate>, ProviderError>;
fn matrix_request(/* ... */) -> Option<HttpRequest> { None }
fn parse_matrix(/* ... */) -> Result<Vec<Option<f64>>, ProviderError> { /* unsupported */ }
}
}
A parsed route is a RouteResult: a MeasuredRoute (see
Routing and stops), the distance at the end of
each leg, and the provider’s traffic delay. A search result is a list of Candidates
with an id, name, position, address, brand and, where known, detour time and distance.
Everything an adapter parses is provider content: it goes into the GeoJSON output only.
The provider crate does not depend on the LLM crate, and scripts/check_deps.sh fails
CI if either ever depends on the other.
Capabilities tells the engine how to get detour times (Native or Matrix), the
most route points one search accepts, and the most results one search returns. It
also lists filter and avoid support, which is published as a support matrix; the engine
reads only the detour strategy and the two limits.
ProviderKind and DetourStrategy also have Google values (Google,
FromRoutingSummaries), left from the original design. There is no Google adapter.
TomTom and HERE compared
TomTom (tomtom.rs) | HERE (here.rs) | |
|---|---|---|
| Routing | Routing API v1 calculateRoute, GET, traffic=true, travelMode=car | Routing v8 routes, GET, return=polyline,summary,actions, via for intermediate points |
| Route timing | guidance instructions | section actions |
| Geocoding | Search v2 geocode, 5 results, biased to the current location | Geocoding v1 geocode, 5 results, at= the current location |
| Along-route search | Search v2 searchAlongRoute, POST with the window’s points | Browse (category only) or Discover (brand or free text), GET with route=<flexible polyline>;w=<metres> |
| Search limit | 20 results, 250 route points | 100 results, 120 route points |
| Search bound | maxDetourTime | corridor width w (the anchor radius) |
| Detour times | in the search results (detourTime) | one Matrix v8 call per stop (async=false) |
| Category ids | fetched once per session from poiCategories and matched by name and synonyms | fixed table of HERE category ids |
| Charger power filter | minPowerKW | evStation[minPower] (category searches only) |
| Connector filter | connectorSet | not supported |
| Avoid | tollRoads, motorways, ferries | avoid[features]=tollRoad,controlledAccessHighway,ferry |
| Electric vehicle flag on routes | vehicleEngineType=electric | not sent |
| Departure time | departAt | departureTime |
| Key | query parameter key | query parameter apiKey |
| Attribution | © TomTom | © HERE |
Notes from the code:
- TomTom’s category list is the only setup request. It is made only when the plan has stops. If it fails, the result gets a warning and searches use text only.
- TomTom and brands. A brand is sent as the search text, not as
brandSet, becausebrandSetonly knows chains in TomTom’s brand registry. As text, a local name (“Cafe de Jaren”) and a misspelt chain (“macdonalds”) are both found. - TomTom and categories. A category stop without a brand sends
*plus thecategorySetid, because generic text together withcategorySetreturned nothing in live tests. A brand with a category (“a Shell petrol station”) sends the brand as the text pluscategorySet, which works (search_requestintomtom.rs). - HERE and detours. HERE’s along-route search reports a distance off the route
(
excursionDistance, kept asdetour_m), not a time. Ranking by distance off the road would prefer a place that is close but slow to reach, so the engine asks for a travel-time matrix (see Detour time). - HERE’s URL length. The corridor is encoded into a GET URL; 120 route points keeps it under HERE’s 2,048-byte guidance.
Both adapters set an 8-second timeout_ms hint on every request.
Errors from providers
ProviderError::from_status (crates/waylingo-providers/src/error.rs) classifies a
failed response:
| Response | Kind | Code in the result |
|---|---|---|
| 401, 403 | Auth | PROVIDER_AUTH |
| 402 | QuotaExceeded | PROVIDER_QUOTA_EXCEEDED |
| 429 | RateLimited | PROVIDER_RATE_LIMITED |
| other 4xx | BadRequest | PROVIDER_BAD_REQUEST |
| 5xx | Upstream | PROVIDER_UNAVAILABLE |
| no response | Transport | PROVIDER_UNREACHABLE |
| 2xx that does not parse | BadResponse | PROVIDER_BAD_RESPONSE |
| route reply with no route | NoRoute | NO_ROUTE |
TomTom also answers 403 for some over-limit cases, so a used-up TomTom quota can appear
as PROVIDER_AUTH. The message includes the provider’s own error text (HERE title
and cause, TomTom errorText, and so on), cut to 300 characters, with words that look
like keys (key=, apikey=, or longer than 40 characters) masked. URLs are never put
in messages, because a URL may carry a key.
Keys and proxies
The engine emits requests with credential: Map (or Llm) and an auth placement.
The host adds the key at send time. In waylingo-reqwest this happens in one place,
prepare in crates/waylingo-reqwest/src/wire.rs: a query-parameter key is
percent-encoded and appended to the URL, a header key is added with its prefix, and an
empty key adds nothing (a local LLM server needs none). Keys prints as
<redacted>. Errors from the hosts never include URLs.
A key shipped inside an app can be extracted, so the bindings support proxies:
- Map proxy.
ProviderChoice::TomTom { base_url }replaceshttps://api.tomtom.com.ProviderChoice::Here { base_url }routes every HERE service through{base}/router,{base}/geocode,{base}/browse,{base}/discoverand{base}/matrix. The proxy adds the real key; the app’s map key may be empty or carry the proxy’s own token. - LLM proxy. Give the LLM backend a
base_url; the LLM key may then be left out.
Attribution and terms
Every result carries the provider’s attribution string, which must be shown with the
results. Each developer’s use of a provider is governed by their own agreement with that
provider; Waylingo does not check it.
Try the demo
The repository has a small web app for trying Waylingo before writing any code. It runs on your own computer: you paste your own map key, type trips in plain words, and see the route, the stops and their coordinates on a map. You can then change stops, pick another match for a place and undo, which is the interaction loop from Reroute.
The demo uses the published Python package, so what you see is what an app gets from
plan, reroute and parse.
Watch it
A 2-minute recording of the demo with the built-in model and a TomTom key, no sound:
| Time | Scenario |
|---|---|
| 0:05 | Connect your keys |
| 0:20 | Stops placed by time: fuel after 30 minutes, a McDonald’s before arrival |
| 0:35 | Change a stop, skip it, bring it back, undo |
| 0:57 | Not the right place? Another match for a name, and a clear answer when no road reaches it |
| 1:12 | A charger every 200 km on the way to Berlin |
| 1:26 | A waypoint and a lunch stop |
| 1:37 | Parse only: the plan as JSON, no map calls |
| 1:45 | Not a trip: refused before any map call |
| 1:53 | Dark theme at phone size |
Place results in the recording come from TomTom and the map from OpenStreetMap; yours depend on your provider and the day.
What you need
- Python 3.9 or later and a checkout of the repository.
- A TomTom or HERE key. Both have free tiers: developer.tomtom.com, platform.here.com.
- A language model, one of:
- the built-in model: Waylingo’s fine-tuned parser, running on your computer with llama.cpp. No key and no cost per request.
- an Anthropic, OpenAI or Gemini key.
Start it
git clone https://github.com/Rohith295/waylingo
cd waylingo
pip install -U waylingo
python demo/server.py
Open http://127.0.0.1:8770.
For the built-in model, install llama.cpp (brew install llama.cpp on macOS; other
systems: the llama.cpp install guide)
and start the model in a second terminal. The first start downloads it (1.2 GB) from
Hugging Face; later
starts take a few seconds.
llama-server -hf rangaraju963/waylingo-parser-qwen3-0.6b --jinja --temp 0 --port 8765
The model server uses about 2 GB of memory while it runs; stop it with Ctrl+C.
Connect your keys
The page opens on Connect your keys:
- Map provider: choose TomTom or HERE and paste the key.
- Language model: choose Built-in (the page shows whether the model server is running and checks again every few seconds) or paste an Anthropic, OpenAI or Gemini key. OpenAI and Gemini also need a model name.
Then choose Connect. The button at the top right shows the connection and opens these settings again.
Things to try
| Try | What you see |
|---|---|
Drive to Utrecht, coffee halfway | One stop at the midpoint of the drive, with how much time it adds |
To Rotterdam, fuel after 30 minutes and a McDonald's 15 minutes before we arrive | Two stops placed by time: one from the start, one before arrival |
Drive to Berlin, a fast charger every 200 km | A repeated stop, one charger per 200 km |
Take me to Haarlem via Zandvoort, lunch on the way | A waypoint and a stop |
What's the weather tomorrow? | A refusal: not a trip, and no map calls |
For each result the panel shows the distance, drive time and stops, then the trip in order: the start, each stop (how far into the drive, how much time it adds, its coordinates) and the destination. Click a coordinate to zoom to it. The line under the title says how long it took and how many language model and map calls it used.
Change a stop. Open Change on a stop to see its alternatives, numbered like their pins on the map, and choose Use. Or click a hollow pin on the map and choose Use this stop. Skip this stop leaves it out; Bring back restores it. Each of these reroutes from the previous result with no language model call and one map call.
Not the right place? When a place name matched more than one place (there is a
Rotterdam in New York State too), pick another match. This searches the stops again
along the new route, still without the language model. If no road connects the places,
the page says so (NO_ROUTE); use Undo.
Undo and Redo step through your changes.
Start point. The trip starts in Amsterdam. Click the map and choose Start here, or use My location (the browser asks first).
Parse only runs just the language model and shows the plan it wrote, as JSON. No
map calls are made, so places are still names. This is the parse call.
Light and dark. The page follows your system setting; the button next to the connection switches it.
At the bottom, Plan JSON from the model and Full result (GeoJSON) show the raw documents, and the GeoJSON can be downloaded.
How it maps to the API
demo/server.py is a
short, readable example of a Waylingo host:
| Page action | Call |
|---|---|
| Connect | one Waylingo(config, map_key, llm_key) per set of keys, reused for every request |
| Plan route | plan_blocking(TripInput(query, current_location)) |
| Use, Skip, Bring back, Not the right place? | reroute_blocking(previous_geojson, Choices(...)) |
| Parse only | parse_blocking(TripInput(...)) |
The page builds Choices from the result itself: a stop’s stop_request_id,
occurrence and an alternative’s provider_place_id, or a place’s candidate_id. See
The result document for those fields.
Your keys
Keys go only from the page to server.py, which listens on 127.0.0.1 and keeps them
in memory for the calls you start. It writes nothing to disk, logs nothing and refuses
requests from other websites. Map tiles also go through it, so keys never appear in
browser URLs. In the browser, keys last until the tab is closed, unless you turn on
Remember keys on this browser; Forget saved keys removes them.
The page loads nothing from other websites: its fonts and map library are in
demo/static. Map tiles come from HERE with a HERE key, from TomTom when the key
includes map display, and otherwise from OpenStreetMap.
The demo is for your own machine. Do not expose it on a network.
Troubleshooting
| Message | What to do |
|---|---|
couldn't bind HTTP server socket ... port: 8765 when starting llama-server | A model server is already running on that port; use it, or stop it first. To use another port, add --port 8766 and change Model address in the settings |
Address already in use when starting server.py | The demo is already running; open http://127.0.0.1:8770, or start another copy with python demo/server.py --port 8771 |
| “Not running yet” under the built-in model | Start llama-server with the command above and wait for it to finish loading |
The language model is not reachable (LLM_UNREACHABLE) | The model server stopped, or the address is wrong |
The map key was refused (PROVIDER_AUTH) | Check the key, and that it has routing and search enabled |
| “Parse only needs waylingo 0.1.1 or later” | pip install -U waylingo |
| The map shows OpenStreetMap with a TomTom key | The key does not include TomTom’s map display API; routing and search still use TomTom |
| My location does nothing | The browser blocked location access; allow it for 127.0.0.1, or click the map |
Quick start
Waylingo is a Rust library with the same API in Python, Swift and Kotlin, so it runs in Android and iOS apps, on servers and in scripts:
| Where | Language | Install |
|---|---|---|
| Android | Kotlin | Gradle: io.github.rohith295:waylingo-android (below) |
| iOS, macOS | Swift | Swift Package: https://github.com/Rohith295/waylingo (below) |
| Servers, scripts | Python | pip install waylingo (below) |
| Anything in Rust | Rust | crates waylingo and waylingo-reqwest (below) |
The current version is 0.1.2. Every example plans one trip and needs a map key (TomTom here) and an LLM key (Anthropic here). See Keys in shipped apps before putting keys in an app.
To try requests in a browser before writing code, run the demo: a local page where you paste your own keys (or use the built-in model) and see the route, the stops and their coordinates on a map.
The output contains map provider content (place names). Show it to the end user; do not send it to an LLM.
Python
pip install waylingo
Wheels are published for Linux (x86_64, aarch64), macOS and Windows, Python 3.9 and later.
import os
import waylingo as w
app = w.Waylingo(
w.WaylingoConfig(
map_provider=w.MapProvider.TOMTOM,
llm=w.LlmBackend.ANTHROPIC(model=None, base_url=None),
),
map_key=os.environ["TOMTOM_API_KEY"],
llm_key=os.environ["LLM_API_KEY"],
)
out = app.plan_blocking(w.TripInput(
query="Drive to Utrecht, coffee halfway",
current_location=w.LatLng(lat=52.3702, lng=4.8952),
))
if out.status == w.TripStatus.FAILED:
print("failed:", out.error_code, out.error_message)
else:
print(out.status, len(out.stops), "stops,", out.map_calls, "map calls")
print(out.attribution)
model=None uses the default Anthropic model; set it explicitly in shipped apps.
In async code use await app.plan(...).
iOS and macOS (Swift)
Add the package in Xcode (File > Add Package Dependencies) with the URL https://github.com/Rohith295/waylingo and a version, or in
Package.swift:
.package(url: "https://github.com/Rohith295/waylingo", from: "0.1.2")
// and in the target: .product(name: "Waylingo", package: "waylingo")
The package downloads a prebuilt XCFramework from the GitHub Release; no Rust is needed.
import Waylingo
let app = try Waylingo(
config: WaylingoConfig(mapProvider: .tomtom, llm: .anthropic(model: nil, baseUrl: nil)),
mapKey: tomtomKey, llmKey: anthropicKey)
// Inside an async context, never on the main thread's blocking path:
let out = try await app.plan(trip: TripInput(
query: "Drive to Utrecht, coffee halfway",
currentLocation: LatLng(lat: 52.3702, lng: 4.8952)))
if out.status == .failed {
print("failed:", String(describing: out.errorCode))
} else {
print(out.status, out.stops.count, "stops")
}
The minimum versions are iOS 15 and macOS 12.
Android (Kotlin)
Add the library from Maven Central in build.gradle.kts:
dependencies {
implementation("io.github.rohith295:waylingo-android:0.1.2")
}
It brings JNA and kotlinx-coroutines with it.
The app needs the internet permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
import io.waylingo.*
val app = Waylingo(
WaylingoConfig(mapProvider = MapProvider.TOMTOM, llm = LlmBackend.Anthropic(null, null)),
mapKey = tomtomKey, llmKey = anthropicKey)
// plan is a suspend function: call it from a coroutine, for example in a ViewModel.
viewModelScope.launch {
val out = app.plan(TripInput(
query = "Drive to Utrecht, coffee halfway",
currentLocation = LatLng(52.3702, 4.8952)))
if (out.status == TripStatus.FAILED) {
Log.w("trip", "failed: ${out.errorCode}")
} else {
Log.i("trip", "${out.stops.size} stops")
}
}
The minimum Android version is 7.0 (API 24).
Rust
Cargo.toml:
[dependencies]
waylingo = "0.1"
waylingo-reqwest = "0.1"
src/main.rs:
use waylingo::{
Coords, Engine, EngineConfig, LlmConfig, LlmMode, ProviderChoice, TripContext, TripRequest,
TripResult,
};
use waylingo_reqwest::{Keys, drive};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let engine = Engine::new(EngineConfig::new(
LlmConfig::new("https://api.anthropic.com/v1", "claude-sonnet-5-5", LlmMode::ToolCall),
ProviderChoice::TomTom { base_url: None },
));
let request = TripRequest {
query: "Drive to Utrecht, coffee halfway".into(),
context: TripContext {
current_location: Some(Coords { lat: 52.3702, lng: 4.8952 }),
..TripContext::default()
},
request_id: None,
};
let keys = Keys {
llm: std::env::var("LLM_API_KEY")?,
map: std::env::var("TOMTOM_API_KEY")?,
};
let geojson = drive(&engine, request, &keys)?;
let result = TripResult::parse(&geojson)?;
println!(
"status {:?}, {} features, {} map calls",
result.status,
result.features.len(),
result.usage.map_calls
);
std::fs::write("trip.geojson", geojson)?;
Ok(())
}
LLM_API_KEY=... TOMTOM_API_KEY=... cargo run
drive is the blocking host: it sends one request at a time and spaces map requests
220 ms apart. For apps and servers, use waylingo_reqwest::AsyncHost, which sends
each batch in parallel, paces map requests across all queries, and has a deadline. To
continue a result after the end user’s choices, use drive_resume or
AsyncHost::resume (see Reroute).
LlmMode::ToolCall is the mode the bindings use for Anthropic; see
Output modes for the others. Pin the model name in
anything you ship: a provider may retire it.
A fuller command-line example, with EV and search settings, is
crates/waylingo-reqwest/examples/plan.rs.
Next
- Bindings: the full API, rerouting after the end user’s choices, and async versus blocking calls.
- Errors: what to do with each
error_code. - The fine-tuned parser: running without an LLM key.
Bindings: Python, Swift, Kotlin
The same API in three languages, generated with UniFFI
from crates/waylingo-ffi. The guide in crates/waylingo-ffi/README.md has the build
commands; this chapter explains the shape of the API and the choices behind it.
Status
- Python: built and tested live; an offline test runs in CI.
- Swift (macOS): built and tested live with
crates/waylingo-ffi/examples/swift/run.sh. - Kotlin: CI compiles the generated bindings and runs offline tests on the JVM
(
crates/waylingo-ffi/tests/kotlin-jvm). - iOS and Android: the release workflow builds the iOS XCFramework and the Android library (AAR); neither has yet been run in an app on a device.
- Packages: version 0.1.2 is on PyPI (
waylingo), Maven Central (io.github.rohith295:waylingo-android) and Swift Package Manager (this repository). Onmain,Package.swiftholds placeholder URL and checksum values; the release workflow fills them in on each release tag, so depend on a version, not onmain.
The API
One object, created once per process:
Waylingo(config, map_key, llm_key = None, signing_key = None)
plan(trip) -> TripOutput async
reroute(previous_geojson, choices, request_id = None) -> TripOutput async
parse(trip) -> ParseOutput async
plan_blocking(trip), reroute_blocking(...), parse_blocking(trip) blocking
is_retryable(code), needs_user(code), version()
import waylingo as w
app = w.Waylingo(
w.WaylingoConfig(map_provider=w.MapProvider.TOMTOM,
llm=w.LlmBackend.ANTHROPIC(model=None, base_url=None)),
map_key=TOMTOM_KEY, llm_key=ANTHROPIC_KEY)
out = app.plan_blocking(w.TripInput(
query="Drive to Utrecht, coffee halfway",
current_location=w.LatLng(lat=52.3702, lng=4.8952)))
Rerouting after the end user picks the first alternative of the first stop:
stop = out.stops[0]
choices = w.Choices(stops=[
w.StopChoice(
stop_request_id=stop.stop_request_id,
occurrence=stop.occurrence,
pick=w.StopPick.PLACE(
provider_place_id=stop.alternatives[0].provider_place_id),
),
])
again = app.reroute_blocking(out.geojson, choices) # no LLM call, one map call
The same plan call in Swift (inside an async context) and Kotlin (inside a
coroutine):
let app = try Waylingo(
config: WaylingoConfig(mapProvider: .tomtom, llm: .anthropic(model: nil, baseUrl: nil)),
mapKey: tomtomKey, llmKey: anthropicKey)
let out = try await app.plan(trip: TripInput(
query: "Drive to Utrecht, coffee halfway",
currentLocation: LatLng(lat: 52.3702, lng: 4.8952)))
val app = Waylingo(
WaylingoConfig(mapProvider = MapProvider.TOMTOM, llm = LlmBackend.Anthropic(null, null)),
mapKey = tomtomKey, llmKey = anthropicKey)
val out = app.plan(TripInput(
query = "Drive to Utrecht, coffee halfway",
currentLocation = LatLng(52.3702, 4.8952)))
Parse only
parse runs only the LLM step: one LLM call (more if the reply needs a repair) and no
map call. It returns the plan the request compiled to, for example to show the end
user what was understood before spending map calls, or to test a model on your own
requests.
p = app.parse_blocking(w.TripInput(
query="Drive to Utrecht, coffee halfway",
current_location=w.LatLng(lat=52.3702, lng=4.8952)))
if p.status == w.ParseStatus.PARSED:
print(p.plan_json) # the same "plan" a plan() call puts in its GeoJSON
else:
print(p.error_code, p.error_message)
Nothing is looked up on the map, so the plan holds the place names from the request,
not coordinates; the only coordinates in it are the ones the app passed in, such as
current_location as the origin. The error codes are the same as for plan. A later
plan call parses the request again; there is no call that routes a plan you already
have. In Rust the same is Engine::parse, waylingo_reqwest::drive_parse and
AsyncHost::parse, which return a ParseResult document
(crates/waylingo/src/result.rs).
Results
TripOutput (crates/waylingo-ffi/src/result.rs) has the full geojson plus the
same facts as typed fields: status, error_code, error_message, stops (pick,
alternatives, eta_s, beyond_radius, user_choice), unresolved, locations (with
candidates), route length and time, warnings, assumptions, attribution, and the
call counts. An app can build Choices from these fields and pass out.geojson back to
reroute.
TripInput (crates/waylingo-ffi/src/trip.rs) carries the query and context:
current_location, heading_deg, locale, saved_places, active_destination, ev
(minimum power and connectors), avoid, departure_time, timezone, request_id.
Configuration
WaylingoConfig (crates/waylingo-ffi/src/config.rs):
| Field | Default | Notes |
|---|---|---|
map_provider | required | TOMTOM or HERE |
llm | required | see below |
map_base_url | none | your map proxy |
settings | Waylingo defaults | anchor_radius_m, search_span_m, search_limit, max_detour_s, top_n, strict_radius |
max_map_calls | 25 | at least 3 |
map_requests_per_second | 4.5 | pacing across every query on the instance |
timeout_ms | 60,000 | whole query, including waiting for map slots; at least 1,000 |
LLM backends:
| Backend | Default endpoint | Output mode |
|---|---|---|
Anthropic { model, base_url } | https://api.anthropic.com/v1; model defaults to claude-sonnet-5-5 | tool_call |
OpenAi { model, base_url } | https://api.openai.com/v1 | json_schema |
Gemini { model, base_url } | Google’s OpenAI-compatible endpoint | json_schema |
OpenAiCompatible { base_url, model, fine_tuned } | your server | prompt_json; compact prompt when fine_tuned |
Pin the Anthropic model in shipped apps: a default baked into an app may be retired by the provider. The bindings guide notes that Gemini has not been tested live yet.
Async and blocking
plan and reroute are async: await in Python’s asyncio, async in Swift, suspend
functions in Kotlin. They are exported with UniFFI’s async support
(#[uniffi::export(async_runtime = "tokio")]). plan_blocking and
reroute_blocking run the same futures on one process-wide tokio runtime with two
worker threads, created on first use (RUNTIME in
crates/waylingo-ffi/src/lib.rs). They block the calling thread for up to timeout_ms,
so never call them on a UI thread.
One instance per process. The instance holds the HTTP client (and its connections)
and the map pacing gate. Pacing works across queries only if they share the instance.
On servers that fork (for example gunicorn with --preload), create it after the fork.
Keys in shipped apps
Keys are constructor arguments, never fields of a record, so they cannot appear in a
generated toString() or repr(). The constructor refuses an empty map key unless
map_base_url is set, and an empty LLM key for a hosted backend unless that backend has
a base_url.
A key compiled into an app can be extracted. For apps in end users’ hands:
- set
map_base_urlto your proxy, which adds the provider key; - give the LLM backend a
base_urlpointing at your proxy; - if your server takes results back from clients, give it a
signing_key(see Signing).
Running the LLM step on the device with the fine-tuned parser is planned (a callback to an on-device runtime) and not built yet.
Android and TLS roots
On Android, waylingo-ffi enables the bundled-roots feature of waylingo-reqwest
(crates/waylingo-ffi/Cargo.toml). The HTTP client then trusts only the root
certificates bundled from webpki-root-certs (Mozilla’s root store), so no TLS set-up
is needed in the app. The trade-off: user-installed and enterprise certificate
authorities are not trusted, so networks that intercept TLS (some corporate proxies)
will fail with PROVIDER_UNREACHABLE or LLM_UNREACHABLE.
Packaging
- Python:
maturinbuilds wheels fromcrates/waylingo-ffi/pyproject.toml. - Swift: an XCFramework of static libraries (iOS device, iOS simulator, macOS), plus the
generated
Waylingo.swift;Package.swiftat the repository root points at the XCFramework attached to a release. The Swift module isWaylingo; the C module isWaylingoFFI(crates/waylingo-ffi/uniffi.toml). - Kotlin: package
io.waylingo, using JNA; an Android library (AAR) is built fromandroid/.
See Testing and releases for how these are built.
Errors
A call either throws (the request or configuration is unusable, or the host gave
up) or returns a result whose status says how it went. Map provider and LLM
failures are not thrown: the result still says what was understood and what was found,
and the app needs that to tell the end user something useful.
Thrown
In Rust, WaylingoError (crates/waylingo/src/engine/mod.rs) covers misuse:
| Variant | When |
|---|---|
InvalidRequest | empty or over-long query, too many saved places, bad coordinates, settings out of range; on reroute, two choices for one stop or one place for two stops |
UnknownResponse | a response with an id the session did not issue |
MissingResponses | some requests of the last batch got no response |
Finished | step after the session is done |
IncompatibleResult | resume got something it cannot continue |
UnknownChoice | a choice names something the previous result did not offer |
The reqwest hosts add DriveError::Client (the HTTP client could not be built) and
DriveError::Timeout (the async host’s deadline passed).
The bindings raise one exception type with these variants
(crates/waylingo-ffi/src/error.rs), each with a detail string:
| Exception | When | What to do |
|---|---|---|
InvalidConfig | an empty key without a proxy, a bad base_url, an empty model name, timeout_ms under 1,000, max_map_calls under 3, settings out of range | fix the configuration |
InvalidRequest | as above | fix the input |
IncompatibleResult | not a result from this instance: another version, provider or signing key; no plan | plan again |
UnknownChoice | a choice not offered by the result | rebuild choices from the latest result |
Timeout | the query took longer than timeout_ms | retry; raise timeout_ms if it happens often |
Internal | a bug in Waylingo | report it |
The field is called detail, not message, because message clashes with the
built-in property of Kotlin and Java exceptions.
Returned: status and error code
status is complete (every requested stop found; a trip may have none), partial
(the route was made, some stops were not found) or failed (no usable trip; see
error.code and error.message).
The codes are one fixed list (ErrorCode in crates/waylingo/src/error_code.rs). The
wire names are a public contract tested in wire_names_are_stable. Codes are only ever
added. A code from a newer version is read as UNKNOWN. Swift and Kotlin generate a
closed enum, so a switch/when without a default branch stops compiling when a code
is added. Include one.
| Code | Cause | Retryable | Needs user |
|---|---|---|---|
NOT_UNDERSTOOD | not a trip request, or nothing was asked for | yes | |
NEEDS_DESTINATION | no destination named and no active route passed | yes | |
NEEDS_CURRENT_LOCATION | the trip starts here, but no current_location was passed | yes | |
INVALID_PLAN | the model’s plan stayed invalid after the repairs | yes | |
NO_GEOCODE | a place in the request was not found | yes | |
NO_ROUTE | the provider found no route between the places | yes | |
LLM_REFUSED | the model declined | yes | |
LLM_AUTH | LLM 401 or 403 | ||
LLM_QUOTA_EXCEEDED | LLM 402, or a 429 that says the quota is used up | ||
LLM_RATE_LIMITED | LLM 429 after the retries | yes | |
LLM_BAD_REQUEST | other LLM 3xx/4xx: usually a wrong model name or base URL | ||
LLM_BAD_RESPONSE | a 2xx in a format Waylingo cannot read | ||
LLM_UNAVAILABLE | LLM 5xx or timeouts after the retries | yes | |
LLM_UNREACHABLE | no connection to the LLM | yes | |
PROVIDER_AUTH | map 401 or 403 (TomTom also uses 403 for some over-limit cases) | ||
PROVIDER_QUOTA_EXCEEDED | map 402 | ||
PROVIDER_RATE_LIMITED | map 429 after the retries | yes | |
PROVIDER_BAD_REQUEST | other map 4xx | ||
PROVIDER_BAD_RESPONSE | a map reply Waylingo cannot read | ||
PROVIDER_UNAVAILABLE | map 5xx after the retries | yes | |
PROVIDER_UNREACHABLE | no connection to the map provider | yes | |
INTERNAL | a bug in Waylingo or in the host | ||
UNKNOWN | a code from a newer version |
is_retryable(code) and needs_user(code) group the codes; a test checks that no code
is in both groups (retry_and_ask_user_do_not_overlap). The rest (auth, quota, bad
request or response) need the developer: retrying will not help and the end user cannot
fix them.
Why the “needs user” codes exist: Waylingo never asks the end user anything itself, and
it does not let the model guess what is missing. NEEDS_DESTINATION means the app should
ask “where to?”; NEEDS_CURRENT_LOCATION means the app should pass the location, or ask
where to start. See Missing context is not repaired.
Which failures fail the whole trip:
| Failure | Effect |
|---|---|
| the LLM step | failed, no map calls made |
| geocoding a place | failed with NO_GEOCODE, or the provider error’s code |
| the base route | failed with the provider error’s code |
| TomTom’s category list | warning; searches use text only |
| one stop’s search | that stop is unresolved with PROVIDER_ERROR |
| a HERE matrix | warning; that stop is ranked by distance from the anchor |
| the final route | warning; the base route and anchor ETAs are used (on a reroute with no base route to fall back on, failed) |
Unresolved stops
A stop without a place does not fail the trip. It appears as an unresolved_stop
feature (in the bindings, in unresolved) with a result (reason in the bindings):
| Reason | Meaning |
|---|---|
NO_CANDIDATES | nothing matched within the detour limit, every match serves another stop, or (with strict_radius) nothing was within the radius; detail gives the counts |
SKIPPED_BY_USER | the end user left it out; options keeps the places it offered |
SKIPPED_BUDGET | the map call budget ran out before it was searched |
UNSUPPORTED | the anchor cannot be placed on this route (for example, the route is shorter than the interval, or an offset lands past the end) |
PROVIDER_ERROR | the provider failed for this search; error_code says how, with the codes above |
NOT_SEARCHED | the search was set up but the result was built before its answer was processed. The engine processes every search answer before building a result, so a normal run does not produce it; it is a fallback (output.rs), and it is copied unchanged when a previous result carried it |
For PROVIDER_ERROR, is_retryable(error_code) tells the app whether trying again
later may help (for example PROVIDER_RATE_LIMITED). A stop-only reroute does not
search unresolved stops again; see Reroute.
The fine-tuned parser
Waylingo works with any LLM that speaks the OpenAI chat format. As an alternative to a hosted model, it has its own small parser model: Qwen3-0.6B fine-tuned for one job, turning a trip request into Waylingo’s JSON plan. It runs on a laptop or a small server with no API key and no per-call cost, and the request text never leaves the machine.
What it does
The model only turns language into the plan JSON (SurfaceIntent). It does not know
places or brands; it copies them:
- names are copied as written, and a name stays a name: “a McDonald’s” becomes
brand: "McDonald's", not a category; - categories are used only for generic words (“a coffee”, “somewhere to charge”);
- unknown names are copied as written: “drive me to Branmont” gives
destination: "Branmont", even though no such town exists; - text that is not a trip request gives
{"error":"not_understood","stops":[]}.
Finding the places is the map provider’s job, so the model never needs to know where anything is.
Performance
“Same plan” means the model’s JSON, after Waylingo’s name check, compiles to exactly the plan the correct answer compiles to, which is what the engine would run.
| Test set | What it checks | Same plan |
|---|---|---|
| Natural wording | 150 held-out requests rewritten by an LLM the way people type them; not used for training | 82.0% |
| Unseen places | 1,000 requests naming places and brands the model never saw | 89.9% |
| Destination only | 30 hand-written trips with a destination and no stops | 28 / 30 |
| Valid JSON | share of replies that are valid plan JSON | over 99% |
A request takes about 1.1 to 1.4 s on an Apple Silicon laptop (median, at temperature 0). The GGUF export scores the same as the original weights. The natural-wording set was made with the same rewriting tool as part of the training data, so real user input may score somewhat lower. The model card has the full table, including the model’s score without Waylingo’s name check.
Known limits:
- English only; trained on places in Europe, the US and India.
- The plan cannot express everything people ask for (“the cheapest fuel”, “open now”); such parts of a request may be dropped.
For hard or unusual requests, a large hosted model is more accurate; the fine-tuned model is for when cost, latency or privacy matter more.
The dataset
The training data is generated by crates/waylingo-parse/examples/make_dataset.rs:
- Correct by construction. Each sentence is built from templates, and its label from the same choices. Every label must compile with the real plan compiler, or the example is dropped.
- Invented names. About half of the places and brands are made up, so the model can only get them right by copying, not by remembering.
- Held-out names. Some places and brands never appear in training; the “unseen” test uses only those, which shows whether the model copies or memorises.
- Real-looking text. Typos, chat shorthand, questions, lower case, and about 4,000 rewrites into more natural wording. A rewrite is kept only if every name and number is still in it exactly.
- Negatives. A small share of non-trip sentences labelled
not_understood. - No map provider data is used anywhere.
The prompt is one line, COMPACT_SYSTEM_PROMPT (“Convert the trip request to Waylingo
JSON.”): the rules are learned from the data, which keeps each request short.
finetune/README.md has the commands to generate the data, train (LoRA with MLX) and
evaluate.
Getting it
Both are on Hugging Face:
- model (safetensors, GGUF and the LoRA adapter): rangaraju963/waylingo-parser-qwen3-0.6b
- dataset (the published copy has no rows naming streets): rangaraju963/waylingo-parser-data
Using it
Serve it with any OpenAI-compatible server, for example llama.cpp’s llama-server with
the GGUF file, and point Waylingo at it with fine_tuned set:
val llm = LlmBackend.OpenAiCompatible(
baseUrl = "http://localhost:8765/v1", model = "default", fineTuned = true)
fine_tuned (fineTuned in Kotlin) sends the one-line prompt the model was trained on
and reads the JSON from the reply (crates/waylingo-ffi/src/config.rs). In Rust, set
LlmConfig { mode: LlmMode::PromptJson, prompt: PromptStyle::Compact, .. }. No LLM key
is needed.
On the device
The model is small enough for a phone, but Waylingo cannot run it on the device yet. Running the parser on a phone covers the runtime to use (llama.cpp), size, speed, delivery, and how it will connect to Waylingo.
Running the parser on a phone
The fine-tuned parser is small enough to run inside an Android or iOS app, so a trip request never leaves the phone and needs no LLM key. Waylingo cannot do this yet: today the bindings call the LLM over HTTP. This chapter records which on-device runtime to use, what it costs, and how it will connect to Waylingo. It is based on research done in November 2026; versions move quickly, so check the links.
The runtime: llama.cpp
Use llama.cpp with the model’s GGUF file on both platforms.
- One model file for iOS and Android. The GGUF on Hugging Face has already been scored with llama.cpp and matches the original weights.
- It takes the exact prompt. Waylingo builds the prompt the model was trained on; llama.cpp runs it as given, without applying its own chat template.
- Greedy decoding and JSON grammars. The model must decode greedily. llama.cpp can also restrict output to a grammar (GBNF, or a JSON schema converted to one), which guarantees well-formed JSON.
- Packaging. Every release has a prebuilt iOS XCFramework that Swift Package Manager can use, with a checksum (docs; iOS 16.4 or later). On Android there is no official Maven package: build the library with the NDK (docs), the same toolchain Waylingo’s own Android build uses.
- MIT licence.
Other runtimes and why they are second choice:
| Runtime | Platforms | Why not first |
|---|---|---|
| MLX Swift | iOS 17+, macOS | A good iOS-only option, with JSON-schema guided generation; nothing for Android |
| LiteRT-LM | Android (stable), iOS (preview) | Bakes the chat template into the model file and documents no raw-prompt input or arbitrary JSON schema |
| ExecuTorch | Android, iOS 17+ | Needs a separate model export; no constrained JSON output found |
| MLC LLM | Android, iOS | No stable release; heavy compile step |
| Apple Foundation Models with Core AI | iOS 27+ | Very new; the framework applies its own template |
| MediaPipe LLM Inference | — | Retired in favour of LiteRT-LM |
| ONNX Runtime GenAI | — | Preview; no mobile packages |
Size and quantisation
| GGUF | Size | Notes |
|---|---|---|
| bf16 (published) | 1.2 GB | Too large for most apps |
| Q8_0 | about 640 MB | Recommended: 8-bit usually costs under 1% accuracy |
| Q4_K_M | about 400 MB | Only if it scores within about a point of Q8_0 |
Small models lose more from 4-bit quantisation than large ones; for Qwen3-0.6B one published measurement shows perplexity rising 18% at mixed 4/8-bit (Apple coreai-models). Before shipping a quantised file, run the same evaluation sets on it.
Memory: about 0.5 to 0.8 GB while running, including the attention cache for a short request.
Speed
No one has published phone numbers for this exact model on llama.cpp yet. From published figures for similar small models, expect about 2 to 4 seconds per request on 2023-or-newer flagship phones and 5 to 10 seconds on mid-range or older ones. Most of the time is spent generating the JSON, so shorter output is faster.
Getting the model onto the phone
Keep the model out of the app binary itself:
- Android: a fast-follow Play Asset Delivery pack (packs can be up to 1.5 GB).
- iOS 26 and later: Apple-hosted Background Assets; on older versions, a download on first launch.
- Downloading from Hugging Face: pin a commit (
/resolve/<commit>/…, notmain), check the file’s SHA-256 against a value built into the app, resume interrupted downloads, and ask before downloading over mobile data (both stores warn above 200 MB).
How it will connect to Waylingo
The plan is a callback that the app implements: Waylingo builds the exact prompt and calls the app’s local runtime, which returns the generated text. The rest (validation, name check, repairs, routing) stays in Waylingo.
#![allow(unused)]
fn main() {
// Implemented in Swift or Kotlin, called by Waylingo.
#[uniffi::export(with_foreign)]
#[async_trait::async_trait]
pub trait LocalLlm: Send + Sync {
/// `prompt` is complete and already templated; decode greedily.
async fn complete(&self, prompt: String, max_tokens: u32, grammar: Option<String>)
-> Result<String, LlmError>;
}
}
class LlamaLocalLlm(private val llama: LlamaEngine) : LocalLlm {
override suspend fun complete(prompt: String, maxTokens: UInt, grammar: String?) =
withContext(Dispatchers.Default) { llama.generate(prompt, maxTokens.toInt(), grammar) }
}
The app loads the model once and runs one request at a time. This is not built yet; the sketch shows the intended shape, not a working API.
Testing and releases
Offline tests
cargo test --workspace needs no keys and no network. Because the engine does no I/O
(see How a trip is planned), a test is a loop that answers each request
from a fixture.
| Area | What is tested | Where |
|---|---|---|
| Geometry | measured routes, anchors (including the slow-city case), windows, simplification, polylines | crates/waylingo-geo/src/*.rs |
| Plan | compilation, units, limits, tampered plans, plan hash | crates/waylingo-plan/src/*.rs |
| LLM step | request shapes per mode, repair, retries, error codes, the destination question, name grounding, no coordinates in requests | crates/waylingo-parse/src/*.rs |
| Adapters | request building and response parsing; no key in any URL | crates/waylingo-providers/tests/tomtom.rs, here.rs |
| Engine end to end | query in, GeoJSON out with a fake LLM and TomTom fixtures; byte-identical output for identical inputs; failures and their codes; settings | crates/waylingo/tests/e2e.rs |
| Reroute | one map call for a stop change, re-search for a new destination, signing, tampering, undo, skip and bring back | crates/waylingo/tests/resume.rs |
| Hosts | keys placed as the request says, redacted Debug, pacing across queries | crates/waylingo-reqwest/src/*.rs |
| Bindings | the library loads; bad configuration and bad results are rejected | crates/waylingo-ffi/tests/python/test_offline.py, tests/kotlin-jvm |
The TomTom fixtures are in crates/waylingo-providers/tests/fixtures/tomtom/; the HERE
tests use small synthetic JSON written inline. The fake LLM in
crates/waylingo/tests/common/mod.rs returns fixed plans, and some fixture place names
contain WAYLINGO_CANARY_<n>. provider_data_never_reaches_the_llm drives a full trip
and fails if any LLM request comes after a map request, contains a canary string or the
user’s coordinates, or if any URL carries a key.
Live contract tests
Offline fixtures cannot notice when a provider changes its response format, retires a
model or changes authentication. Live tests do, and they are all #[ignore]d so a
normal cargo test never calls a real API.
- Map providers, nightly.
.github/workflows/live.ymlruns at 04:17 UTC every day (and by hand). It runs the raw TomTom checks (crates/waylingo-providers/tests/live_tomtom.rs) and the whole engine against TomTom and HERE (crates/waylingo-reqwest/tests/live_maps.rs): geocode, route, search, detour ranking and reroute. The LLM step is answered with a fixed plan, so only map keys are needed and a map-side change is caught on its own.WAYLINGO_LIVE_REQUIREturns a missing key into a failure, so a scheduled run cannot pass by skipping. - LLM backends, by hand.
crates/waylingo-ffi/tests/live.rsgoes through the same public API the bindings use, for TomTom and HERE with Anthropic, and TomTom with OpenAI and Gemini, plus “not a trip”, wrong keys and destination-only trips. It is not scheduled. - Scenarios, by hand.
crates/waylingo-reqwest/examples/scenarios.rsruns every supported intent against the real LLM and map provider and checks the results.
Live tests print statuses, codes and counts only: no provider place names, addresses or coordinates, and never keys.
CI
.github/workflows/ci.yml, on every push to main and every pull request, with no
secrets and no network tests:
- Rust on Linux, macOS and Windows:
cargo fmt --all --check,cargo clippy --workspace --all-targets -- -D warnings,cargo test --workspace, and (not on Windows)scripts/check_deps.sh, which fails ifwaylingo-parseandwaylingo-providersdepend on each other in either direction; - Python: build the wheel with maturin, install it, run the offline test;
- Kotlin: build the library, generate the Kotlin bindings, compile and test them on the JVM with Gradle.
The workspace lints forbid unsafe code in every crate except waylingo-ffi
(Cargo.toml), whose generated UniFFI scaffolding needs it; the hand-written code in
waylingo-ffi has none.
Releases
.github/workflows/release.yml is started by hand with a version, which must match the
workspace version in Cargo.toml. With publish off, the default, it is a dry run:
everything is built and kept as workflow artifacts, and nothing leaves GitHub.
It builds:
- Python wheels (manylinux and musllinux for x86_64 and aarch64, macOS universal2, Windows x64) and an sdist;
- the Swift XCFramework (iOS device, iOS simulator, macOS) and the generated Swift
source, and checks that
Package.swiftcompiles against it; - the Android native libraries (arm64-v8a, armeabi-v7a, x86_64), the Kotlin bindings, and the AAR.
With publish on, it also points Package.swift at the release, commits the Swift
source, tags the version, creates the GitHub Release with the XCFramework and the AAR,
and publishes to PyPI (trusted publishing, no stored token) and Maven Central. Each
publish job runs in a GitHub environment that can require a manual approval.
Version 0.1.0 was released this way. The crates are published to crates.io by hand
with cargo publish, not by the workflow.
Pull requests
The project does not accept code contributions. .github/workflows/pull-requests.yml
closes pull requests from anyone but the owner with a short note. It uses
pull_request_target and never checks out or runs the pull request’s code.
Design decisions and limitations
Key decisions
Each decision is explained in the linked section.
| Decision | Reason |
|---|---|
| The LLM only turns text into a fixed JSON plan | LLMs are unreliable at route arithmetic and detour ranking, and this keeps provider data out of the LLM |
| The LLM is required; there is no public “run this plan” entry point | Waylingo is a natural-language engine, not a routing SDK. The cost: an agent that already runs an LLM pays for a second LLM call |
| The engine does no I/O | keys stay with the host; bindings need no async callbacks; apps keep their own network stack; tests replay fixtures without HTTP mocking |
Two plan tiers: SurfaceIntent from the LLM, Plan from a compiler | the model copies units and names as written; Rust converts and checks, and can tell the model exactly what to fix |
| Missing context is never repaired | a model asked for a missing value can only invent it; the app asks the end user instead |
| Names are grounded back to the request’s words | small models garble unfamiliar names; the request is the only valid source for them |
| One map provider per app | detours subtract travel times, which only makes sense within one provider’s traffic model |
| Anchors use the provider’s distance and time checkpoints | highway and city speeds differ; an even spread puts time anchors in the wrong place |
| “Every N” is counted from the start; anchors stay on the base route | all searches are independent and go out in one parallel batch; one final route gives the real ETAs |
| Prefer places within a radius, rank by detour time, flag a fallback beyond it | a place close in a straight line can cost a long detour; an answer with a clear flag beats “nothing found” |
| HERE detours from a matrix over a shortlist | HERE search returns distance off the route, not time; the shortlist keeps it to one small call per stop |
| Stateless reroute | no session store; resume after an app restart; undo by resuming an older result |
| Optional signing that leaves out the route line | servers can trust results sent back by clients; clients can drop the largest part to save bandwidth |
| Hard limits on plans and a map call budget | a misread request or a tampered result cannot make a server send thousands of requests |
| A fixed, append-only list of error codes | apps can handle every case and know whether to retry or ask the end user |
| Map pacing in the host, across queries | only the host knows how many queries share the provider’s rate limit |
Found against the live APIs
Some choices came from how real endpoints behaved, not from their documentation:
- TomTom categories: a category stop without a brand searches for
*pluscategorySet, because generic text together withcategorySetreturned nothing (search_requestincrates/waylingo-providers/src/tomtom.rs). - No TomTom
brandSet: it only matches chains in TomTom’s brand registry, so a local name such as “Cafe de Jaren” would find nothing; the name as search text finds both chains (even misspelt) and single places (tomtom.rs). tool_choice: "auto": some endpoints reject a forced tool call, so the tool is offered, not forced, and a text answer is read as well (crates/waylingo-parse/src/openai.rs).
Known limitations
These are true of the code as it is now.
Reroute
- A stop-only reroute does not search again for stops that were unresolved in the
previous result (
NO_CANDIDATES,PROVIDER_ERROR,SKIPPED_BUDGET). They are copied as they were. Only a change of origin, waypoint or destination re-runs the searches. - A stop skipped before a destination change has no options afterwards; to bring it back, resume the earlier result.
- Without a signing key,
reroutetrusts stop positions in the document as given. Servers that take results back from clients should set a key.
Providers
- TomTom answers 403 for some over-limit cases, so a used-up TomTom quota may surface as
PROVIDER_AUTHrather thanPROVIDER_QUOTA_EXCEEDED. - HERE: no connector filter; the electric-vehicle flag is not sent on route requests; only the 8 shortlisted candidates (plus a chosen one) survive the detour step.
- There is no Google adapter, although
ProviderKindhas aGooglevalue.
Routing and stops
- No EV range model. “Every 200 km” is spacing from the start of the trip, and the real gap between two chosen chargers can exceed 200 km (each pick may sit up to the radius from its mark, or further when the beyond-radius fallback is used).
- Anchors are not shifted by earlier stops’ detours or time spent at a stop.
- “Halfway” and other fractions are by distance, not by time.
heading_degis accepted but not used. An active route is passed only as its destination; the route is recomputed from the current location.- The timezone is carried in the plan but not sent to the providers.
- The call budget is checked before searches and matrices only; geocoding, routes and retries are counted but never refused.
Pacing under load
- Pacing is per
AsyncHost(perWaylingoinstance in the bindings). Several processes do not coordinate, so together they can exceed the provider’s rate limit. - Under heavy load, queries wait at the shared map gate, and that waiting counts against
each query’s deadline: queries then fail with
Timeoutinstead of being queued longer. The blocking host waits a fixed 220 ms before each map request whatever the load.
LLM step and parser model
- The fine-tuned parser is English-only and trained on places in Europe, the US and India.
- Running the parser on the device is planned, not built.
- Gemini has not been tested live.
Packaging
- Version 0.1.0 is published. Kotlin is tested on the JVM in CI but not on Android; iOS and Android device builds are not verified end to end in an app.
The original design document
docs/designs/waylingo.md is the original design, written before the code; this book
describes the current code.
Glossary
Alternative. Another place offered for a stop, ranked after the pick. At most
top_n − 1 per stop, and always on the same side of the radius as the pick.
Anchor. Where on the route a stop is wanted: an offset from the origin, the destination or a waypoint (“15 minutes before we arrive”), every N (“every 200 km”), or a fraction (“halfway”). Resolved to one or more anchor points on the base route.
Candidate. Two meanings. A geocoding candidate is one match for a place name the user said (up to 5 per place, for “did you mean …?”). A search candidate is one place returned by an along-route search, before the pick is chosen.
Intent (SurfaceIntent). The JSON the LLM writes: places and units as the user
said them. See The plan.
Mark. One anchor point of an “every N” anchor: at N, 2N, 3N, … from the start.
Occurrence. The number of a mark: 0, 1, 2, … A stop is identified by its stop request id plus its occurrence. Single anchors have occurrence 0.
Option. A place offered by a stop the end user skipped, kept so the stop can be brought back.
Pick. The place chosen for a stop; the final route goes through it.
Pin. An end user’s earlier stop choice carried into a re-search after the origin, a waypoint or the destination changed. It is kept if the same place is found again.
Plan (Plan). The compiled, validated form of the intent: metres, seconds,
coordinates or geocoding text, checked references. See The plan.
Radius (anchor_radius_m). Places within this straight-line distance of an anchor
point are preferred. Default 5 km.
Span (search_span_m). How much route is searched on each side of an anchor point.
Default 3 × the radius.
Window. The stretch of route searched for one anchor point: from anchor − span to anchor + span, clamped to the route.