kardinal
Python SDK for the Kardinal route-optimization API: submit a plan, follow its optimization, retrieve the solution, update it to re-optimize.
pip install kardinal-ai # library only
pip install "kardinal-ai[cli]" # + the `kardinal` command
The package is published as kardinal-ai, but you import it as kardinal
(from kardinal import Kardinal) and the command is kardinal. Python 3.10
or later.
The package ships its types, so a type checker sees them: a misspelled attribute or a wrong argument type is reported in your editor, before anything runs.
Documentation: https://developers.kardinal.ai/sdks/overview (SDK guides and reference) and https://developers.kardinal.ai (the API itself).
Changelog: https://developers.kardinal.ai/sdks/python/changelog (what changes in each release of this SDK) and https://developers.kardinal.ai/reference/changelog (what changes in the API itself).
Quickstart
from kardinal import Kardinal
from kardinal.routing import examples
k = Kardinal() # KARDINAL_API_KEY
plan = k.routing.plans.submit(examples.small_delivery_plan())
solution = k.routing.solutions.wait(plan.id) # returns in ~20s
wait, not get, on purpose: the API is asynchronous. Right after submit,
get raises KardinalNotFoundError (404) while the plan is still waiting
or being processed, then returns whatever the engine has found so far,
which can be empty or incomplete until the optimization is over. wait
returns once it is.
For a larger, realistic plan, examples.cold_chain_plan() and
examples.parcel_express_plan() return the plans of the
cold-chain
and parcel express
case studies, as typed objects to adapt to your data. Their content follows
the published pages and may change in any release.
API reference
All methods hang off the client: k = Kardinal().
| Method | HTTP call | What it does |
|---|---|---|
k.routing.plans.submit(plan) |
POST /plans |
Creates a plan from a PlanCreate (no id: the server assigns it) and starts its optimization. Consumes credits. Returns the Plan, with .warnings. |
k.routing.plans.get(plan_id) |
GET /plans/{id} |
Returns the plan as currently stored. |
k.routing.plans.update(plan, force=False) |
PUT /plans/{id} |
Replaces the whole plan (anything left out is removed; fields this SDK version doesn't know, read by get(), are kept and sent back). The version increments, and the plan is re-optimized, only if the plan actually changed; an identical update is a free no-op. force=True unarchives an archived plan first. |
k.routing.plans.replace(plan_id, plan, force=False) |
PUT /plans/{id} |
Updates a plan from a new PlanCreate, the same object you give submit(), with no id, agencyId or version to copy. Anything you leave out is removed, including a field this SDK version doesn't know: use get() and update() to keep it. The last write wins. force=True unarchives an archived plan first. |
k.whoami() |
GET /plans |
Returns the host (baseUrl) and the agency (agencyId) your API key resolves to. It is a read, so it is free. |
k.routing.plans.delete(plan_id) |
DELETE /plans/{id} |
Permanently deletes the plan and its solution; any optimization in progress is stopped. |
k.routing.plans.list(page=1, items_per_page=20, archived="excluded") |
GET /plans |
Returns one Page of plans, in their light form (PlanLight). |
k.routing.plans.iter_all(archived="excluded") |
GET /plans, every page |
Iterates over every plan. |
k.routing.plans.start(plan_id, force=False) |
PUT /plans/{id}/running |
Restarts the optimization of the current version, without changing its data or version. |
k.routing.plans.stop(plan_id, force=False) |
PUT /plans/{id}/running |
Stops the optimization, without changing the plan's data or version. |
k.routing.plans.get_status(plan_id) |
GET /plans/{id}/state |
Returns the plan's current PlanState: waiting, processing, optimizing, optimized, stopped, interrupted, ... |
k.routing.solutions.wait(plan_id, timeout=None) |
GET /plans/{id}/state, then /solution |
Blocks until the current version stops optimizing, then returns its solution (see below). |
k.routing.solutions.get(plan_id) |
GET /plans/{id}/solution |
Returns the current best solution right away, without waiting. |
k.routing.solutions.get_objectives(plan_id) |
GET /plans/{id}/solution/objectives |
Returns only the value of each objective, without the tours. |
A Page has items, page, total_pages, total, next_page (None
on the last page), previous_page (None on the first page) and
items_per_page. Asking for a page past the last one returns the last page:
.page gives the page actually returned.
How wait() works
- It polls
get_status()every 10 seconds at first, stretching to every 60 seconds on long optimizations, and fetches the solution only once the plan is done. It never sleeps through the wholemaxOptimizationDuration: the engine stops on its own once it stops finding improvements. - The returned solution's
final_statetells how the optimization ended:optimized, orinterrupted/stoppedwhen it was cut short (stopped, replaced by a newer version, or given up by the engine). Check it before treating the result as final. - It raises
KardinalOptimizationErrorwhen it has no solution to return:NO_SOLUTION(the plan ended without one for this version),PLAN_SUPERSEDED(a newer version was pushed meanwhile), orOPTIMIZATION_STALLED(still optimizing 5 minutes past itsmaxOptimizationDuration: the engine most likely crashed). A plan deleted while waiting raisesKardinalNotFoundError. timeout(seconds) is a hard limit that raisesKardinalTimeoutError, after checking the state one last time.- It's meant for scripts and notebooks. A server tracking many plans should
schedule its own
get_status()calls instead of blocking, and like any manual tracking, poll no more than once every 10 seconds per plan.
Configuration
Kardinal(api_key=None, *, base_url=None, timeout=30, max_retries=3)
| argument | env var | default | |
|---|---|---|---|
api_key |
Kardinal(api_key="<your API key>") |
KARDINAL_API_KEY |
(required: raises MissingApiKeyError if none is found) |
base_url |
Kardinal(base_url="https://...") |
KARDINAL_BASE_URL |
https://app.kardinal.ai/api/v2 |
The argument wins over the environment variable, which wins over the
default. api_key="" raises EmptyApiKeyError rather than silently falling
back to the environment variable.
Sandbox and production share the same host: the API key you use determines which of your agencies a call applies to.
timeout (seconds) is passed to httpx as each request's timeout, which
applies to each phase (connecting, sending, each read of the response)
separately, not to the request as a whole.
max_retries is how many times a read, update(), replace(), delete(),
start() or stop() is retried after a network error, a 429 or a 5xx.
submit() is never retried (see "Good to know" below).
The client can be used as a context manager (with Kardinal() as k:), or
closed with k.close().
Check the agency at startup
A sandbox key and a production key can look alike. whoami() tells you which
host and which agency your key resolves to, so you can check it before the
first plan is submitted:
who = k.whoami()
print(who.baseUrl)
expected_agency = "A_sandbox" # read it from your own configuration
if who.agencyId != expected_agency:
raise RuntimeError(f"This API key belongs to {who.agencyId}, not to {expected_agency}")
agencyId is None when the API doesn't return one.
Full walkthrough
from datetime import datetime, timedelta, timezone
from kardinal import Kardinal
from kardinal.routing.plans import PlanCreate, Order
from kardinal.routing import models
from kardinal import KardinalValidationError, KardinalNotFoundError
k = Kardinal(timeout=30, max_retries=3)
# A resource's workingTimeWindow in the past isn't a meaningful plan to
# optimize — computing "tomorrow" here keeps this example runnable as-is,
# rather than pinning a calendar date that goes stale.
tomorrow = (datetime.now(timezone.utc) + timedelta(days=1)).replace(
hour=8, minute=0, second=0, microsecond=0
)
plan_input = PlanCreate(
tz="Europe/Paris",
maxOptimizationDuration="PT5M",
resources=[
models.Resource(
id="truck-1",
vehicleProfile=models.VehicleProfileCar(type="car"),
workingTimeWindow=models.TimeWindow(
begin=tomorrow.isoformat(), end=tomorrow.replace(hour=18).isoformat()
),
)
],
orders=[
Order(
id="order-1",
stops=[
models.SingleStop(
type="single",
id="stop-1",
position=models.Position(lat=48.8566, lon=2.3522),
)
],
)
],
)
try:
plan = k.routing.plans.submit(plan_input) # the server assigns `id`
except KardinalValidationError as e:
print(e.code) # INVALID_VALUE, ID_NOT_UNIQUE, ...
print(e.errors) # every error, not just the first
raise
solution = k.routing.solutions.wait(plan.id) # blocks until it's done
print(solution.final_state) # optimized, or interrupted/stopped if cut short
for tour in solution.tours or []: # tours is None when no stop could be planned
print(tour.resourceId, len(tour.wayPoints))
# manual tracking instead of a blocking wait, what a server tracking many
# plans should do (no more than one call every 10 seconds per plan)
objectives = k.routing.solutions.get_objectives(plan.id) # objective values only
status = k.routing.plans.get_status(plan.id)
# re-optimize: same id; the version increments only if the plan changed
# (an identical update is a free no-op)
plan.orders.append(
Order(id="order-2", stops=[models.SingleStop(type="single", id="stop-2",
position=models.Position(lat=48.86, lon=2.35))])
)
plan = k.routing.plans.update(plan)
# or send a new PlanCreate for the same plan: no id, agencyId or version to copy
plan = k.routing.plans.replace(plan.id, plan_input)
replace() sends the same body as submit(). A plan created by either SDK
keeps its version when you replace it with the same PlanCreate. A plan
created from raw JSON, without the SDK's default values, gets one extra
version on its first replace(). Later identical calls keep that version.
replace() raises a TypeError if you pass it a plan you read with get().
Send that plan back with update().
A plan has no top-level list of stops: stops live inside Order.stops[],
and Plan.orders[] is the list of orders. An Order groups one or more
stops that must be planned onto the same resource (for example a pickup and
its delivery).
Errors
KardinalError
├── KardinalAuthError NOT_AUTHENTICATED (401): missing, invalid or expired key;
│ also a revoked or regenerated key (403 NOT_ALLOWED)
├── KardinalLimitError 403 (NOT_ALLOWED) recognised as a limit: plan size,
│ optimization quota, or insufficient credits
├── KardinalForbiddenError any other 403: read `.details`
├── KardinalValidationError the 7 codes under 400, with the full error list; also an
│ archived plan updated, stopped or restarted without `force` (403 NOT_ALLOWED)
├── KardinalNotFoundError NOT_FOUND: raised on every 404, including reads
├── KardinalRateLimitError 429: temporary overload, retry after a pause
├── KardinalServerError INTERNAL_SERVER_ERROR, or any other 5xx
├── KardinalTimeoutError solutions.wait()'s hard `timeout` elapsed
├── KardinalOptimizationError solutions.wait() has no solution to return: NO_SOLUTION,
│ PLAN_SUPERSEDED, OPTIMIZATION_STALLED (engine crashed)
├── KardinalConnectionError DNS/connection/read failure, no HTTP response at all
└── UnknownFieldError a key no model declares, raised before sending
(submit: any; update: one the server didn't send)
UnknownFieldError is the one raised without a request being made. Most
plan fields are optional, and the API drops a key it doesn't know without
an error: operationDurationn would leave the stop with no service time,
requiredSkills spelled wrong would let any resource serve the order, and
the plan would still come back valid. So submit() lists every such key
with its path and refuses to send:
Unknown field(s) in the plan:
plan.id (not a field you set: the server assigns it)
plan.resources[0].maxWorkingDurationn (did you mean maxWorkingDuration?)
plan.orders[0].stops[0].operationDurationn (did you mean operationDuration?)
update() sorts an unknown key by where it came from. One the server sent
is a field the API added after this SDK version: it is sent back untouched,
since a full replacement would otherwise delete it. One you added is a typo
— the API drops what it doesn't know — and raises, exactly as submit()
does. On a plan this SDK didn't read from the API (built by hand, or loaded
from a file) there is nothing to sort by, so it only warns, and only for a
key within two edits of a real field.
The CLI works the same way: plans update reads the stored plan first to
borrow its provenance, so a typo in an edited file is refused rather than sent.
And --allow-unknown NAME, repeatable, is the command-line form of allow_unknown
on plans submit, plans update and plans validate.
If the API gains a field before this SDK knows it, name it to send it anyway — everything else stays checked:
k.routing.plans.update(plan, allow_unknown=["aFieldAddedByTheApi"])
A name listed there is allowed anywhere in the plan, not only on the
object you had in mind — so prefer a distinctive name over a common one
like priority, which would stop being checked on every resource, order
and stop at once.
To ask before sending rather than catch the error, run the same check yourself:
from kardinal.routing import unknown_fields
for field in unknown_fields(plan):
print(field) # plan.resources[0].maxWorkingDurationn (did you mean maxWorkingDuration?)
Responses are never affected: a key the API adds is kept, not refused.
All of them are importable from kardinal itself
(from kardinal import KardinalNotFoundError), as are MissingApiKeyError
and EmptyApiKeyError (both KardinalErrors, raised by Kardinal()
without a usable key) and Page, the type plans.list() returns.
Every exception carries .code, .status, .request_id, .retryable,
.warnings, .errors and .details. .errors is every error object of
the response; .details is the properties.details of the error .code
came from, the only way to tell apart errors that share a code.
The API answers every refusal with a 403 NOT_ALLOWED, so the SDK sorts a
403 by what the response carries. KardinalLimitError is what a 403 becomes
when a limit was hit, and .details says which one. Two 403s that are not
limits are recognised by their exact .details and raised as another
family: the token is invalid (a revoked or regenerated key) raises
KardinalAuthError, and Cannot update an archived plan, except with the 'force' query param raises KardinalValidationError (its .errors has no
field path: add force=True). Any other 403 raises KardinalForbiddenError:
the SDK couldn't tell what it is, so it doesn't call it a limit, and
.details holds the API's own explanation. For a plan-size limit (too many resources, orders or
stops, or more than 4 stops in an order without successiveStops),
.errors also holds one INVALID_VALUE entry per exceeded limit, whose
properties.path and properties.details name the field and the allowed
value: shrink the plan. For the daily/monthly quota, wait or ask for a
higher one; for credits, top them up.
from kardinal import KardinalLimitError
try:
plan = k.routing.plans.submit(plan_input)
except KardinalLimitError as e:
print(e.details) # which limit was hit
print(e.errors) # for a plan-size limit, the field and the allowed value
KardinalRateLimitError (429) signals a temporary overload, not a quota: it
comes with an empty body and, today, no Retry-After header — the SDK
honours one if the API ever sends it, and otherwise backs off on a jittered
schedule of its own. Reads, update(), replace(), delete(), start(),
stop() and wait() retry it automatically. submit() doesn't, so retry it
yourself after a pause.
.retryable is computed by the SDK and means "retrying is safe and may
succeed": true for a 429, and for a 5xx or a connection error, except
when a submit() may have reached the server (the plan may then already
exist: check with list() before submitting again). An unrecognized code
falls back to the family matching the HTTP status rather than disappearing,
since the API may add new codes in a non-breaking release. .warnings is
usually empty: it's populated when a rejected payload had already been
amended (a value clamped, crow-fly distances forced, ...) before the error
that rejected it was found.
Warnings
When the API accepts a plan but amends part of it, submit(), update() and
replace() return the amendments in .warnings:
plan = k.routing.plans.submit(plan_input)
for warning in plan.warnings:
print(warning.code, warning.properties) # e.g. maxOptimizationDuration clamped
Read them from that return value: warnings aren't stored with the plan, so
a later get() never returns them, only the amended value.
The same three methods also log each kind of warning once, on the kardinal
logger at the WARNING level. You need no logging setup to see the line:
Python prints it on stderr. A line looks like this:
Kardinal API warning INVALID_VALUE: The crowfly mode is forced for agency A_sandbox (resources.0.vehicleProfile, resources.1.vehicleProfile)
The sandbox sends the crow-fly warning once per vehicle. The SDK groups them in one line and lists the first three paths. To silence the lines, raise the level of the logger:
import logging
logging.getLogger("kardinal").setLevel(logging.ERROR)
The wording of the line is for people and may change in a later release.
A program should read plan.warnings. When the API rejects a plan, its
warnings come with the exception, and the SDK doesn't log them.
If your application calls logging.config.dictConfig after the first
warning, set disable_existing_loggers to False in that configuration.
Otherwise dictConfig disables the kardinal logger.
The CLI
kardinal auth check confirms the API key works, and shows its host and agency (what `k.whoami()` returns)
kardinal version
kardinal routing plans submit <file> | get <id> | update <file> | delete <id>
kardinal routing plans list | start <id> | stop <id> | status <id>
kardinal routing plans validate <file> local only, no API call, no credits
kardinal routing solutions get <id> | objectives <id> | wait <id>
kardinal routing demo submits the example plan, waits for it
kardinal init writes .claude/skills/kardinal-python/SKILL.md, a skill for Claude Code and any tool that reads Agent Skills (run it at the repository root)
JSON output when stdout isn't a terminal, or with --json; a readable table
otherwise. Error output is always JSON, regardless of --json or the
terminal, since it's the one output shape a caller is most likely to parse
programmatically. Exit codes: 0 success, 1 business error, 2 usage
error. The CLI reads the same KARDINAL_API_KEY / KARDINAL_BASE_URL as
Kardinal() (see Configuration above), with no --api-key flag, so a key
never lands in shell history or the process list. solutions wait takes
--timeout <seconds>, and prints how the optimization ended as
finalState, like the API's other fields.
Good to know
submit()is never retried automatically, not even after a network error or a5xx: the API has no idempotency key, so a retry could create the plan twice. Reads,update(),replace(),delete(),start()andstop()are retried. Replaying the sameupdate()is harmless: an identical update keeps the same version and isn't billed.maxOptimizationDurationis capped by your agency. A value above the cap is clamped to it, andsubmit()/update()/replace()report it in.warnings. By default: 5 seconds in the sandbox (also the default when omitted); in production, 15 minutes when omitted and 6 hours at most. The engine stops earlier on its own once it stops finding improvements.- In the sandbox, distances are crow-fly: road routing is replaced, and
each resource's
vehicleProfilegets a warning saying so. - The SDK identifies itself in two headers on every request:
User-Agent(SDK version, Python version, OS and architecture, and thehttpxversion, plusclifor calls made by thekardinalcommand) andX-Kardinal-Client(SDK version). Nothing personal: no hostname, user or key. .request_idis usuallyNone: it's only set when the server happens to send anX-Request-Idresponse header.get_status()returns aPlanState(a single value), not the detailedPlanStatusobject embedded inPlan.status; a state this SDK version doesn't know yet still comes back as aPlanState, a pseudo-member that equals its raw string.get_objectives()returns a plainlistofSolutionObjective, with a.warningsattribute attached.start()/stop()return anEnvelopedPlanReference(agencyId,planId,planVersion,warnings): the plan's current version, which starting or stopping doesn't change.
License
MIT.
Metadata
Release files for kardinal-ai 2.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| kardinal_ai-2.1.0.tar.gz | 129.9 kB | With provenance | Details for kardinal_ai-2.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| kardinal_ai-2.1.0-py3-none-any.whl | Python 3 | none | any | Details for kardinal_ai-2.1.0-py3-none-any.whl |
Total release size: 216.9 kB
Release files / kardinal_ai-2.1.0.tar.gz
| Download URL | kardinal_ai-2.1.0.tar.gz |
|---|---|
| Size | 129.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
67db25411cd33d29f8667129cf1db12b13050271285c3e0f200d3b998865e15d
|
|
BLAKE2b-256 checksum How to use checksums |
abe7ae5943c3cecea3ff8d0b97a638702d1c9231d57464f4412558eaade860b8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 4, 2026.
Transparency logRelease files / kardinal_ai-2.1.0-py3-none-any.whl
| Download URL | kardinal_ai-2.1.0-py3-none-any.whl |
|---|---|
| Size | 87.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
c73c7ccdf849fc6a2f363958cef3a82afecb46378d534d18afd7a56eb22cc39c
|
|
BLAKE2b-256 checksum How to use checksums |
2f7530fbf1b12348435f750b9158b9ad59c38c44cd5c83ef6a7528546c153d6e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 4, 2026.
Transparency logSecurity for kardinal-ai 2.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for kardinal_ai-2.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 4, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.